Skip to content

Commit

Permalink
Made srand(...) and rand() platform independent
Browse files Browse the repository at this point in the history
The srand(...) and rand() functions are not available on all embedded
platforms, so they were replaced with lwm2m_srand(...) and lwm2m_rand()
to make these calls platform independent.
  • Loading branch information
parmi93 committed Jun 16, 2023
1 parent 5146594 commit e5dbff6
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
4 changes: 2 additions & 2 deletions core/liblwm2m.c
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ lwm2m_context_t * lwm2m_init(void * userData)
{
memset(contextP, 0, sizeof(lwm2m_context_t));
contextP->userData = userData;
srand((int)lwm2m_gettime());
contextP->nextMID = rand();
lwm2m_srand((int)lwm2m_gettime());
contextP->nextMID = lwm2m_rand();
}

return contextP;
Expand Down
10 changes: 10 additions & 0 deletions examples/shared/platform.c
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,16 @@ time_t lwm2m_gettime(void)
return time(NULL);
}

void lwm2m_srand(unsigned int seed)
{
srand(seed);
}

int lwm2m_rand()
{
return rand();
}

void lwm2m_printf(const char * format, ...)
{
va_list ap;
Expand Down
4 changes: 4 additions & 0 deletions include/liblwm2m.h
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,10 @@ int lwm2m_strcasecmp(const char * str1, const char * str2);
// In case of error, this must return a negative value.
// Per POSIX specifications, time_t is a signed integer.
time_t lwm2m_gettime(void);
// Initialize random number generator
void lwm2m_srand(unsigned int seed);
// Get a random number
int lwm2m_rand(void);

#ifdef LWM2M_WITH_LOGS
// Same usage as C89 printf()
Expand Down

0 comments on commit e5dbff6

Please sign in to comment.