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