ua_clock.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
  2. * See http://creativecommons.org/publicdomain/zero/1.0/ for more information.
  3. *
  4. * Copyright 2016-2017 (c) Julius Pfrommer, Fraunhofer IOSB
  5. * Copyright 2017 (c) Stefan Profanter, fortiss GmbH
  6. * Copyright 2017 (c) Thomas Stalder
  7. */
  8. /* Enable POSIX features */
  9. #if !defined(_XOPEN_SOURCE)
  10. # define _XOPEN_SOURCE 600
  11. #endif
  12. #ifndef _DEFAULT_SOURCE
  13. # define _DEFAULT_SOURCE
  14. #endif
  15. /* On older systems we need to define _BSD_SOURCE.
  16. * _DEFAULT_SOURCE is an alias for that. */
  17. #ifndef _BSD_SOURCE
  18. # define _BSD_SOURCE
  19. #endif
  20. #include <time.h>
  21. #include <sys/time.h>
  22. #include "ua_types.h"
  23. #include <task.h>
  24. UA_DateTime UA_DateTime_now(void) {
  25. struct timeval tv;
  26. gettimeofday(&tv, NULL);
  27. return (tv.tv_sec * UA_DATETIME_SEC) + (tv.tv_usec * UA_DATETIME_USEC) + UA_DATETIME_UNIX_EPOCH;
  28. }
  29. /* Credit to https://stackoverflow.com/questions/13804095/get-the-time-zone-gmt-offset-in-c */
  30. UA_Int64 UA_DateTime_localTimeUtcOffset(void) {
  31. time_t gmt, rawtime = time(NULL);
  32. struct tm *ptm;
  33. struct tm gbuf;
  34. ptm = gmtime_r(&rawtime, &gbuf);
  35. // Request that mktime() looksup dst in timezone database
  36. ptm->tm_isdst = -1;
  37. gmt = mktime(ptm);
  38. return (UA_Int64) (difftime(rawtime, gmt) * UA_DATETIME_SEC);
  39. }
  40. UA_DateTime UA_DateTime_nowMonotonic(void) {
  41. portTickType TaskTime = xTaskGetTickCount();
  42. UA_DateTimeStruct UATime;
  43. UATime.milliSec = (UA_UInt16) TaskTime;
  44. struct timespec ts;
  45. ts.tv_sec = UATime.milliSec/1000;
  46. ts.tv_nsec = (UATime.milliSec % 1000)* 1000000;
  47. return (ts.tv_sec * UA_DATETIME_SEC) + (ts.tv_nsec / 100);
  48. }