time_conversion.c 963 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. * SPDX-FileCopyrightText: 2023 Helmut Pozimski <helmut@pozimski.eu>
  3. *
  4. * SPDX-License-Identifier: GPL-2.0-only
  5. */
  6. #include <freertos/FreeRTOS.h>
  7. #include <freertos/semphr.h>
  8. #include <time.h>
  9. #include <string.h>
  10. #include "configuration.h"
  11. static SemaphoreHandle_t mutex = NULL;
  12. static char* tz = NULL;
  13. static void initialize_tz() {
  14. unsetenv("TZ");
  15. setenv("TZ", LOCAL_TIMEZONE, 1);
  16. tz = getenv("TZ");
  17. }
  18. static void set_tz_gmt() {
  19. strncpy(tz, "GMT0", 5);
  20. tzset();
  21. }
  22. static void set_tz_local() {
  23. strncpy(tz, LOCAL_TIMEZONE, strlen(LOCAL_TIMEZONE) +1);
  24. tzset();
  25. }
  26. struct tm* convert_to_local(struct tm *timeinfo) {
  27. if (mutex == NULL) {
  28. mutex = xSemaphoreCreateMutex();
  29. }
  30. xSemaphoreTake(mutex, portMAX_DELAY);
  31. if (tz == NULL) {
  32. initialize_tz();
  33. }
  34. set_tz_gmt();
  35. time_t epoch_time = mktime(timeinfo);
  36. set_tz_local();
  37. struct tm* result = localtime(&epoch_time);
  38. set_tz_gmt();
  39. xSemaphoreGive(mutex);
  40. return result;
  41. }