75 lines
1.8 KiB
C
75 lines
1.8 KiB
C
#include "time_sync.h"
|
|
|
|
#include <stdbool.h>
|
|
#include <stdlib.h>
|
|
#include <time.h>
|
|
|
|
#include "esp_log.h"
|
|
#include "esp_netif_sntp.h"
|
|
#include "sdkconfig.h"
|
|
|
|
static const char *TAG = "sese_time";
|
|
static bool s_initialized;
|
|
|
|
static void log_local_time(const char *prefix)
|
|
{
|
|
time_t now;
|
|
struct tm local_time;
|
|
char timestamp[40];
|
|
|
|
time(&now);
|
|
localtime_r(&now, &local_time);
|
|
if (strftime(timestamp, sizeof(timestamp), "%Y-%m-%dT%H:%M:%S%z", &local_time) == 0) {
|
|
ESP_LOGW(TAG, "%s, but timestamp formatting failed", prefix);
|
|
return;
|
|
}
|
|
ESP_LOGI(TAG, "%s: %s", prefix, timestamp);
|
|
}
|
|
|
|
static void time_sync_notification(struct timeval *time_value)
|
|
{
|
|
(void)time_value;
|
|
log_local_time("NTP time synchronized");
|
|
}
|
|
|
|
esp_err_t time_sync_start(void)
|
|
{
|
|
if (s_initialized) {
|
|
return ESP_OK;
|
|
}
|
|
|
|
if (setenv("TZ", CONFIG_SESE_TIMEZONE, 1) != 0) {
|
|
return ESP_FAIL;
|
|
}
|
|
tzset();
|
|
|
|
esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG(CONFIG_SESE_NTP_SERVER);
|
|
config.sync_cb = time_sync_notification;
|
|
esp_err_t err = esp_netif_sntp_init(&config);
|
|
if (err != ESP_OK) {
|
|
return err;
|
|
}
|
|
|
|
s_initialized = true;
|
|
ESP_LOGI(TAG, "NTP started with server '%s' and timezone '%s'",
|
|
CONFIG_SESE_NTP_SERVER, CONFIG_SESE_TIMEZONE);
|
|
return ESP_OK;
|
|
}
|
|
|
|
esp_err_t time_sync_wait(TickType_t timeout)
|
|
{
|
|
if (!s_initialized) {
|
|
return ESP_ERR_INVALID_STATE;
|
|
}
|
|
|
|
esp_err_t err = esp_netif_sntp_sync_wait(timeout);
|
|
if (err == ESP_OK) {
|
|
log_local_time("Initial system time ready");
|
|
} else if (err == ESP_ERR_TIMEOUT) {
|
|
ESP_LOGW(TAG, "Initial NTP synchronization timed out; periodic retries remain active");
|
|
} else {
|
|
ESP_LOGW(TAG, "Initial NTP synchronization did not complete: %s", esp_err_to_name(err));
|
|
}
|
|
return err;
|
|
}
|