ua_clock.c 1.4 KB

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