Debian Codegraph @

3rdparty/xspublic/xstypes/xstime.c

raw
1
2 // Copyright (c) 2003-2019 Xsens Technologies B.V. or subsidiaries worldwide.
3 // All rights reserved.
4 //
5 // Redistribution and use in source and binary forms, with or without modification,
6 // are permitted provided that the following conditions are met:
7 //
8 // 1. Redistributions of source code must retain the above copyright notice,
9 // this list of conditions, and the following disclaimer.
10 //
11 // 2. Redistributions in binary form must reproduce the above copyright notice,
12 // this list of conditions, and the following disclaimer in the documentation
13 // and/or other materials provided with the distribution.
14 //
15 // 3. Neither the names of the copyright holders nor the names of their contributors
16 // may be used to endorse or promote products derived from this software without
17 // specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
20 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
22 // THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
24 // OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY OR
26 // TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.THE LAWS OF THE NETHERLANDS
28 // SHALL BE EXCLUSIVELY APPLICABLE AND ANY DISPUTES SHALL BE FINALLY SETTLED UNDER THE RULES
29 // OF ARBITRATION OF THE INTERNATIONAL CHAMBER OF COMMERCE IN THE HAGUE BY ONE OR MORE
30 // ARBITRATORS APPOINTED IN ACCORDANCE WITH SAID RULES.
31 //
32
33 // Note, this function requires compiler option "-lrt" to be set when compiling with gcc
34 #include "xstime.h"
35 #include "xstimestamp.h"
36 #include <stdio.h>
37 #include <wchar.h>
38
39 #ifdef _WIN32
40 # include <windows.h>
41 # define snprintf _snprintf
42 #else
43 //# include <errno.h>
44 # include <unistd.h>
45 # include <sys/time.h>
46 # include <pthread.h>
47 # include <string.h>
48 #endif
49 #include <time.h>
50
51 /*! \namespace XsTime
52 \brief Namespace for time and date constants and operations
53 */
54
55 //! The number of seconds in a normal day
56 const XsTimeStamp XsTime_secPerDay = { 60*60*24LL };
57
58 //! The number of milliseconds in a normal day
59 const XsTimeStamp XsTime_milliSecPerDay = { 60*60*24*1000LL };
60
61 //! The maximum positive value of an XsTimeStamp value
62 const XsTimeStamp XsTime_timeStampMax = { 0x7FFFFFFFFFFFFFFFLL };
63
64 //////////////////////////////////////////////////////////////////////////////////////////
65 //////////////////////////////////// Other functions ////////////////////////////////////
66 //////////////////////////////////////////////////////////////////////////////////////////
67 #if 0 // def __APPLE__, it is in fact available on apple, so...
68 /*! \brief An implementation of linux' clock_gettime()
69
70 clock_gettime() is not available on Apple/Darwin platforms. This function helps
71 maintaining compatibility with Linux code.
72 */
73 #ifndef CLOCK_REALTIME
74 #define CLOCK_REALTIME 0
75 #endif
76 static int clock_gettime(int clk_id, struct timespec *tp)
77 {
78 (void)clk_id;
79 struct timeval now;
80
81 int rv = gettimeofday(&now, NULL);
82 if (rv != 0)
83 return rv;
84
85 tp->tv_sec = now.tv_sec;
86 tp->tv_nsec = now.tv_usec * 1000;
87
88 return 0;
89 }
90 #endif
91
92 /*! \addtogroup cinterface C Interface
93 @{
94 */
95
96 //////////////////////////////////////////////////////////////////////////////////////////
97 /*! \brief The function returns the current time of day in ms since midnight
98 \param date_ When not 0, the corresponding current date is put in here.
99 \param secs_ When not 0, the full timestamp in seconds since the epoch is put in here.
100 \returns The number of milliseconds that have passed since midnight.
101 */
102 uint32_t XsTime_getTimeOfDay(struct tm* date_, time_t* secs_)
103 {
104 #ifdef _WIN32
105 // CORRECTION_DELTA_MS is the maximum allowed difference between the system time and the performance counter time. This depends on the granularity of the clocks.
106 static const int64_t CORRECTION_DELTA_MS = 32;
107 static int64_t startTimePerfCount;
108 static int64_t startTimeSysTime;
109 static int64_t perfCountFreq = 0;
110 int64_t t;
111 LARGE_INTEGER pc;
112 FILETIME now;
113 __time64_t tin;
114
115 GetSystemTimeAsFileTime(&now);
116 t = (int64_t) (((((uint64_t) now.dwHighDateTime << 32) | now.dwLowDateTime)/10000) - 11644473600000);
117
118 if (QueryPerformanceCounter(&pc))
119 {
120 int64_t tNow;
121 if (!perfCountFreq)
122 {
123 LARGE_INTEGER tmp;
124 QueryPerformanceFrequency(&tmp);
125 perfCountFreq = tmp.QuadPart;
126 startTimePerfCount = pc.QuadPart;
127 startTimeSysTime = t;
128 }
129
130 tNow = startTimeSysTime + (1000*(pc.QuadPart - startTimePerfCount))/perfCountFreq;
131
132 if (t > tNow || (tNow-t) > CORRECTION_DELTA_MS)
133 {
134 startTimePerfCount = pc.QuadPart;
135 startTimeSysTime = t;
136 }
137 else
138 t = tNow;
139 }
140
141 tin = t/1000;
142 if (date_ != NULL)
143 _localtime64_s(date_,&tin);
144 if (secs_ != NULL)
145 *secs_ = (time_t) tin;
146 return (uint32_t) (t % (XsTime_secPerDay.m_msTime*1000));
147 #else
148 struct timespec tp;
149 clock_gettime(CLOCK_REALTIME, &tp); // compile with -lrt
150
151 if (date_ != NULL)
152 localtime_r(&tp.tv_sec,date_);
153
154 if (secs_ != NULL)
155 secs_[0] = tp.tv_sec;
156
157 // 86400 = 24*60*60 = secs in a day, this gives us the seconds since midnight
158 return (uint32_t)((1000 * (tp.tv_sec % XsTime_secPerDay.m_msTime)) + (tp.tv_nsec/1000000));
159 #endif
160 }
161
162 /*! \brief Retrieves the date and time (platform-independent)
163 \param date : if non-zero the local (!) date and time is stored in the tm struct this parameter points to
164 \returns The UTC date and time as seconds since 1970
165 */
166 int64_t XsTime_getDateTime(struct tm *date)
167 {
168 #ifdef _WIN32
169 __time64_t t;
170 _time64(&t);
171 if (date != 0)
172 _localtime64_s(date, &t);
173 return (int64_t)t;
174 #else
175 time_t t;
176 time(&t);
177 if(date != 0)
178 {
179 struct tm *result = localtime(&t);
180 memcpy(date, result, sizeof(struct tm));
181 }
182 return (int64_t)t;
183 #endif
184 }
185
186 /*! \brief Retrieves the date as string representation
187 The format is YYYYMMDD
188 so 25 dec 2010 is stored as an array dest[8] = {'2', '0', '1', '0', '1', '2', '2', '5' }
189 \param dest : A pointer to an array of at least (!) 8 bytes
190 \param date : If date is non-zero this date is converted, otherwise the current date is retrieved and used)
191 */
192 void XsTime_getDateAsString(char* dest, const struct tm* date)
193 {
194 struct tm dt;
195 int year, month;
196
197 if(date != 0)
198 dt = *date;
199 else
200 XsTime_getDateTime(&dt);
201
202 year = dt.tm_year + 1900;
203 month = dt.tm_mon + 1;
204 volatile int dst_size = 9; // JLBC: just to supress truncation warning
205 snprintf(dest, dst_size, "%04d%02d%02d", year, month, dt.tm_mday);
206 }
207
208 /*! \brief Retrieves the time as binary
209 The format is HHMMSShh (where H is hour and 'h' is hundredths)
210 so 14:25:01.23 is stored as an array dest[8] = { '1', '4', '2', '5', '0', '1', '2', '3'}
211 \param dest : A pointer to an array of at least (!) 8 bytes
212 \param date : If date is non-zero this date is converted, otherwise the current date is retrieved and used)
213 \note (for now hundreths are set to 0)
214 */
215 void XsTime_getTimeAsString(char* dest, const struct tm* date)
216 {
217 struct tm dt;
218
219 if (date != 0)
220 dt = *date;
221 else
222 XsTime_getDateTime(&dt);
223
224 volatile int dst_size = 8; // JLBC: just to supress truncation warning
225 snprintf(dest, dst_size, "%02d%02d%02d%02d", dt.tm_hour, dt.tm_min, dt.tm_sec, 0);
226 }
227
228 /*! \brief Retrieves the date as wstring representation
229 The format is YYYYMMDD
230 so 25 dec 2010 is stored as an array dest[8] = {'2', '0', '1', '0', '1', '2', '2', '5' }
231 \param dest : A pointer to an array of at least (!) 8 wchars
232 \param date : If date is non-zero this date is converted, otherwise the current date is retrieved and used)
233 */
234 void XsTime_getDateAsWString(wchar_t* dest, const struct tm* date)
235 {
236 struct tm dt;
237 int year, month;
238
239 if(date != 0)
240 dt = *date;
241 else
242 XsTime_getDateTime(&dt);
243
244 year = dt.tm_year + 1900;
245 month = dt.tm_mon + 1;
246 swprintf(dest, 9, L"%04d%02d%02d", year, month, dt.tm_mday);
247 }
248
249 /*! \brief Retrieves the time as binary
250 The format is HHMMSShh (where H is hour and 'h' is hundredths)
251 so 14:25:01.23 is stored as an array dest[8] = { '1', '4', '2', '5', '0', '1', '2', '3'}
252 \param dest : A pointer to an array of at least (!) 8 wchars
253 \param date : If date is non-zero this date is converted, otherwise the current date is retrieved and used)
254 \note (for now hundreths are set to 0)
255 */
256 void XsTime_getTimeAsWString(wchar_t* dest, const struct tm* date)
257 {
258 struct tm dt;
259
260 if (date != 0)
261 dt = *date;
262 else
263 XsTime_getDateTime(&dt);
264
265 swprintf(dest, 9, L"%02d%02d%02d%02d", dt.tm_hour, dt.tm_min, dt.tm_sec, 0);
266 }
267
268 /*! \brief Make the current thread sleep for at least \a ms milliseconds
269 \details A platform independent sleep routine to sleep for at least \a ms milliseconds.
270
271 \param ms The number of milliseconds to sleep
272
273 \sa XsTime_udelay
274 */
275 void XsTime_msleep(uint32_t ms)
276 {
277 #ifdef _WIN32
278 Sleep(ms);
279 #else
280 XsTime_udelay(ms * 1000);
281 #endif
282 }
283
284 /*! \brief Delays the current thread for at least \a us microseconds
285 \details A platform independent delay routine to sleep for at least \a us microseconds.
286
287 \param us The number of microseconds to delay
288
289 \sa XsTime_msleep
290 */
291 void XsTime_udelay(uint64_t us)
292 {
293 #ifdef _WIN32
294 LARGE_INTEGER freq, start, stop;
295 double countPerMicroSecond ;
296 QueryPerformanceCounter(&start);
297 QueryPerformanceFrequency(&freq);
298 countPerMicroSecond = freq.QuadPart / 1.0e6;
299 do
300 {
301 QueryPerformanceCounter(&stop);
302 }
303 while (start.QuadPart + ((double)(us) * countPerMicroSecond) > stop.QuadPart);
304 #else
305 struct timespec ts;
306 int ret = -1;
307
308 ts.tv_sec = us / 1000000;
309 ts.tv_nsec = (us - (ts.tv_sec * 1000000)) * 1000;
310
311 while (ret)
312 {
313 ret = nanosleep(&ts, &ts);
314 if (ret)
315 assert(errno == EINTR);
316 }
317 #endif
318 }
319
320 /*! \brief Returns the current time in ms since the epoch (Jan 1st 1970)
321 \param now Pointer to %XsTimeStamp container for the returned value, may be 0
322 \returns The current time in ms since the epoch (Jan 1st 1970) as a 64-bit integer
323 */
324 int64_t XsTime_timeStampNow(XsTimeStamp* now)
325 {
326 XsTimeStamp tmp;
327 time_t s;
328
329 if (now == 0)
330 now = &tmp;
331
332 now->m_msTime = (long long) XsTime_getTimeOfDay(NULL,&s);
333 now->m_msTime = (now->m_msTime % 1000) + (((long long)s)*1000);
334
335 return now->m_msTime;
336 }
337
338 /*! \cond XS_INTERNAL */
339 int64_t XsTime_utcToLocalValue = 0; //!< Internal storage for UTC to local time correction (ms)
340 int64_t XsTime_localToUtcValue = 0; //!< Internal storage for local time to UTC correction (ms)
341 /*! \endcond XS_INTERNAL */
342
343 /*! \brief Stabilize the clock
344 \details Repeatedly calls XsTime_timeStampNow for 16-32 ms to stabilize the clock.
345 Initializes the local to UTC conversion parameters.
346 */
347 void XsTime_initializeTime()
348 {
349 int64_t tutc, tloc;
350 #ifdef _WIN32
351 FILETIME now, nowloc;
352
353 GetSystemTimeAsFileTime(&now);
354 FileTimeToLocalFileTime(&now, &nowloc);
355
356 tutc = (int64_t) (((((uint64_t) now.dwHighDateTime << 32) | now.dwLowDateTime)/10000) - 11644473600000);
357 tloc = (int64_t) (((((uint64_t) nowloc.dwHighDateTime << 32) | nowloc.dwLowDateTime)/10000) - 11644473600000);
358
359 #else
360 struct timespec tp;
361 struct tm now, nowloc;
362
363 clock_gettime(CLOCK_REALTIME, &tp); // compile with -lrt
364 gmtime_r(&tp.tv_sec, &now);
365 localtime_r(&tp.tv_sec, &nowloc);
366
367 tutc = (int64_t) now.tm_min * 60000;
368 tloc = (int64_t) nowloc.tm_min * 60000;
369 #endif
370
371 XsTime_utcToLocalValue = tloc - tutc;
372 XsTime_localToUtcValue = tutc - tloc;
373
374 long long start = XsTime_timeStampNow(0);
375 while (XsTime_timeStampNow(0) - start < 32) {}
376 }
377
378 /*! \brief Returns the conversion value from UTC time to local time in ms
379 \returns The conversion value from UTC time to local time in ms
380 \note Make sure to call XsTime_initializeTime() before calling this function as well as when changing time zones.
381 */
382 int64_t XsTime_utcToLocal()
383 {
384 return XsTime_utcToLocalValue;
385 }
386
387 /*! \brief Returns the conversion value from local time to UTC time in ms
388 \returns The conversion value from local time to UTC time in ms
389 \note Make sure to call XsTime_initializeTime() before calling this function as well as when changing time zones.
390 */
391 int64_t XsTime_localToUtc()
392 {
393 return XsTime_localToUtcValue;
394 }
395
396 /*! @} */