Repo for ESP32 Weather Station Development
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.4KB

  1. /*
  2. * clock.c
  3. *
  4. * Created on: Apr 23, 2020
  5. * Author: chris
  6. */
  7. #include "clock.h"
  8. const char* TAG = "clock";
  9. void time_sync_notification_cb(struct timeval *tv)
  10. {
  11. ESP_LOGI(TAG, "Synchronized time to PTB!");
  12. }
  13. esp_err_t init_clock()
  14. {
  15. ESP_LOGI(TAG, "Initializing SNTP");
  16. esp_event_loop_create_default();
  17. sntp_setoperatingmode(SNTP_OPMODE_POLL);
  18. sntp_setservername(0, "ptbtime1.ptb.de");
  19. sntp_set_time_sync_notification_cb(time_sync_notification_cb);
  20. sntp_set_sync_mode(SNTP_SYNC_MODE_IMMED);
  21. sntp_init();
  22. // wait for time to be set
  23. time_t now = 0;
  24. struct tm timeinfo = { 0 };
  25. int retry = 0;
  26. const int retry_count = 10;
  27. while (sntp_get_sync_status() == SNTP_SYNC_STATUS_RESET && ++retry < retry_count) {
  28. ESP_LOGI(TAG, "Waiting for system time to be set... (%d/%d)", retry, retry_count);
  29. vTaskDelay(2000 / portTICK_PERIOD_MS);
  30. }
  31. time(&now);
  32. localtime_r(&now, &timeinfo);
  33. setenv("TZ", "CET-1CEST-2,M3.5.0/02:00:00,M10.5.0/03:00:00", 1);
  34. tzset();
  35. return ESP_OK;
  36. }
  37. void get_time(time_str_t* res)
  38. {
  39. time_t now;
  40. struct tm timeinfo;
  41. time(&now);
  42. localtime_r(&now, &timeinfo);
  43. char date_str[64];
  44. char time_str[64];
  45. strftime(date_str, sizeof(date_str), "%d.%m.%Y", &timeinfo);
  46. strftime(time_str, sizeof(time_str), "%H:%M:%S", &timeinfo);
  47. strcpy(res->date_str, date_str);
  48. strcpy(res->time_str, time_str);
  49. }