ua_clock.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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) Fraunhofer IOSB (Author: Julius Pfrommer)
  5. * Copyright 2017 (c) Stefan Profanter, fortiss GmbH
  6. * Copyright 2017 (c) Thomas Stalder, Blue Time Concept SA
  7. */
  8. #ifdef UA_ARCHITECTURE_POSIX
  9. #include <open62541/types.h>
  10. #include <time.h>
  11. #include <sys/time.h>
  12. #if defined(__APPLE__) || defined(__MACH__)
  13. # include <mach/clock.h>
  14. # include <mach/mach.h>
  15. #endif
  16. UA_DateTime UA_DateTime_now(void) {
  17. struct timeval tv;
  18. gettimeofday(&tv, NULL);
  19. return (tv.tv_sec * UA_DATETIME_SEC) + (tv.tv_usec * UA_DATETIME_USEC) + UA_DATETIME_UNIX_EPOCH;
  20. }
  21. /* Credit to https://stackoverflow.com/questions/13804095/get-the-time-zone-gmt-offset-in-c */
  22. UA_Int64 UA_DateTime_localTimeUtcOffset(void) {
  23. time_t gmt, rawtime = time(NULL);
  24. struct tm *ptm;
  25. struct tm gbuf;
  26. ptm = gmtime_r(&rawtime, &gbuf);
  27. // Request that mktime() looksup dst in timezone database
  28. ptm->tm_isdst = -1;
  29. gmt = mktime(ptm);
  30. return (UA_Int64) (difftime(rawtime, gmt) * UA_DATETIME_SEC);
  31. }
  32. UA_DateTime UA_DateTime_nowMonotonic(void) {
  33. #if defined(__APPLE__) || defined(__MACH__)
  34. /* OS X does not have clock_gettime, use clock_get_time */
  35. clock_serv_t cclock;
  36. mach_timespec_t mts;
  37. host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
  38. clock_get_time(cclock, &mts);
  39. mach_port_deallocate(mach_task_self(), cclock);
  40. return (mts.tv_sec * UA_DATETIME_SEC) + (mts.tv_nsec / 100);
  41. #elif !defined(CLOCK_MONOTONIC_RAW)
  42. struct timespec ts;
  43. clock_gettime(CLOCK_MONOTONIC, &ts);
  44. return (ts.tv_sec * UA_DATETIME_SEC) + (ts.tv_nsec / 100);
  45. #else
  46. struct timespec ts;
  47. clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
  48. return (ts.tv_sec * UA_DATETIME_SEC) + (ts.tv_nsec / 100);
  49. #endif
  50. }
  51. #endif /* UA_ARCHITECTURE_POSIX */