diff --git a/include/coap/coap_time.h b/include/coap/coap_time.h index 4274fcb6..6228b4f9 100644 --- a/include/coap/coap_time.h +++ b/include/coap/coap_time.h @@ -109,8 +109,7 @@ typedef long coap_tick_diff_t; /** * Initializes the internal clock. */ -static inline void coap_clock_init(void) { -} +void coap_clock_init(void); /** * Sets @p t to the internal time with COAP_TICKS_PER_SECOND resolution. @@ -127,9 +126,7 @@ void coap_ticks(coap_tick_t *t); * @return The number of seconds that has passed since a specific reference * point (seconds since epoch on POSIX). */ -static inline coap_time_t coap_ticks_to_rt(coap_tick_t t) { - return t / COAP_TICKS_PER_SECOND; -} +coap_time_t coap_ticks_to_rt(coap_tick_t t); #endif /* WITH_POSIX */ /** diff --git a/src/coap_time.c b/src/coap_time.c index 10dcc5e8..1da2132c 100644 --- a/src/coap_time.c +++ b/src/coap_time.c @@ -14,6 +14,8 @@ #include "coap_config.h" #include "coap_time.h" +static coap_time_t coap_clock_offset = 0; + #if _POSIX_TIMERS && !defined(__APPLE__) /* _POSIX_TIMERS is > 0 when clock_gettime() is available */ @@ -21,6 +23,19 @@ #define COAP_CLOCK CLOCK_REALTIME #endif +void +coap_clock_init(void) { +#ifdef COAP_CLOCK + struct timespec tv; + clock_gettime(COAP_CLOCK, &tv); +#else /* _POSIX_TIMERS */ + struct timeval tv; + gettimeofday(&tv, NULL); +#endif /* not _POSIX_TIMERS */ + + coap_clock_offset = tv.tv_sec; +} + /* creates a Qx.frac from fval */ #define Q(frac,fval) ((coap_tick_t)(((1 << (frac)) * (fval)))) @@ -60,7 +75,12 @@ coap_ticks(coap_tick_t *t) { /* Finally, convert temporary FP representation to multiple of * COAP_TICKS_PER_SECOND */ - *t = tmp + tv.tv_sec * COAP_TICKS_PER_SECOND; + *t = tmp + (tv.tv_sec - coap_clock_offset) * COAP_TICKS_PER_SECOND; +} + +coap_time_t +coap_ticks_to_rt(coap_tick_t t) { + return coap_clock_offset + (t / COAP_TICKS_PER_SECOND); } #undef Q