59 lines
1.4 KiB
C
59 lines
1.4 KiB
C
/*
|
|
* clock.c
|
|
*
|
|
* Created on: Apr 23, 2020
|
|
* Author: chris
|
|
*/
|
|
|
|
#include "clock.h"
|
|
|
|
const char* TAG = "clock";
|
|
|
|
void time_sync_notification_cb(struct timeval *tv)
|
|
{
|
|
ESP_LOGI(TAG, "Synchronized time to PTB!");
|
|
}
|
|
|
|
esp_err_t init_clock()
|
|
{
|
|
ESP_LOGI(TAG, "Initializing SNTP");
|
|
esp_event_loop_create_default();
|
|
sntp_setoperatingmode(SNTP_OPMODE_POLL);
|
|
sntp_setservername(0, "ptbtime1.ptb.de");
|
|
sntp_set_time_sync_notification_cb(time_sync_notification_cb);
|
|
sntp_set_sync_mode(SNTP_SYNC_MODE_IMMED);
|
|
sntp_init();
|
|
|
|
// wait for time to be set
|
|
time_t now = 0;
|
|
struct tm timeinfo = { 0 };
|
|
int retry = 0;
|
|
const int retry_count = 10;
|
|
while (sntp_get_sync_status() == SNTP_SYNC_STATUS_RESET && ++retry < retry_count) {
|
|
ESP_LOGI(TAG, "Waiting for system time to be set... (%d/%d)", retry, retry_count);
|
|
vTaskDelay(2000 / portTICK_PERIOD_MS);
|
|
}
|
|
time(&now);
|
|
localtime_r(&now, &timeinfo);
|
|
|
|
setenv("TZ", "CET-1CEST-2,M3.5.0/02:00:00,M10.5.0/03:00:00", 1);
|
|
tzset();
|
|
|
|
return ESP_OK;
|
|
}
|
|
|
|
void get_time(time_str_t* res)
|
|
{
|
|
time_t now;
|
|
struct tm timeinfo;
|
|
time(&now);
|
|
localtime_r(&now, &timeinfo);
|
|
|
|
char date_str[64];
|
|
char time_str[64];
|
|
strftime(date_str, sizeof(date_str), "%d.%m.%Y", &timeinfo);
|
|
strftime(time_str, sizeof(time_str), "%H:%M:%S", &timeinfo);
|
|
strcpy(res->date_str, date_str);
|
|
strcpy(res->time_str, time_str);
|
|
}
|