ua_clock.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. #include "ua_types.h"
  9. #include <time.h>
  10. #include <sys/time.h>
  11. #include <task.h>
  12. UA_DateTime UA_DateTime_now(void) {
  13. struct timeval tv;
  14. gettimeofday(&tv, NULL);
  15. return (tv.tv_sec * UA_DATETIME_SEC) + (tv.tv_usec * UA_DATETIME_USEC) + UA_DATETIME_UNIX_EPOCH;
  16. }
  17. /* Credit to https://stackoverflow.com/questions/13804095/get-the-time-zone-gmt-offset-in-c */
  18. UA_Int64 UA_DateTime_localTimeUtcOffset(void) {
  19. time_t gmt, rawtime = time(NULL);
  20. struct tm *ptm;
  21. struct tm gbuf;
  22. ptm = gmtime_r(&rawtime, &gbuf);
  23. // Request that mktime() looksup dst in timezone database
  24. ptm->tm_isdst = -1;
  25. gmt = mktime(ptm);
  26. return (UA_Int64) (difftime(rawtime, gmt) * UA_DATETIME_SEC);
  27. }
  28. UA_DateTime UA_DateTime_nowMonotonic(void) {
  29. portTickType TaskTime = xTaskGetTickCount();
  30. UA_DateTimeStruct UATime;
  31. UATime.milliSec = (UA_UInt16) TaskTime;
  32. struct timespec ts;
  33. ts.tv_sec = UATime.milliSec/1000;
  34. ts.tv_nsec = (UATime.milliSec % 1000)* 1000000;
  35. return (ts.tv_sec * UA_DATETIME_SEC) + (ts.tv_nsec / 100);
  36. }