/* * SPDX-License-Identifier: AGPL-3.0-only * Copyright (c) Camden Dixie O'Brien */ #include "time_sntp.h" #include "console.h" #include "settings.h" #include "esp_log.h" #include "esp_sntp.h" #define TAG "Time SNTP" static void handle_sntp_server_update(const char *sntp_server) { esp_sntp_setservername(0, sntp_server); time_sntp_restart(); } static void sntp_sync_callback(struct timeval *tv) { const time_t now = tv->tv_sec; struct tm timeinfo; (void)localtime_r(&now, &timeinfo); ESP_LOGI( TAG, "Received SNTP time notification: %02u:%02u", timeinfo.tm_hour, timeinfo.tm_min); } static const char *sync_status_description(sntp_sync_status_t status) { switch (status) { case SNTP_SYNC_STATUS_RESET: return "Reset"; case SNTP_SYNC_STATUS_COMPLETED: return "Completed"; case SNTP_SYNC_STATUS_IN_PROGRESS: return "In progress"; default: return "Invalid"; } } static int command_func(int argc, char **argv) { if (argc == 2) { if (strcmp(argv[1], "status") == 0) { if (esp_sntp_enabled()) { const sntp_sync_status_t status = sntp_get_sync_status(); printf("%s\n", sync_status_description(status)); } else { printf("Disabled\n"); } return 0; } else if (strcmp(argv[1], "restart") == 0) { time_sntp_restart(); return 0; } else if (strcmp(argv[1], "stop") == 0) { sntp_stop(); return 0; } else { printf("Unrecognised subcommand\n"); return 1; } } else { printf("Invalid number of arguments\n"); return 1; } } void time_sntp_init(void) { char sntp_server[SETTINGS_MAX_VALUE_SIZE]; (void)settings_get_sntp_server(sntp_server, SETTINGS_MAX_VALUE_SIZE); settings_add_sntp_server_callback(&handle_sntp_server_update); esp_sntp_set_sync_mode(SNTP_SYNC_MODE_SMOOTH); esp_sntp_setoperatingmode(ESP_SNTP_OPMODE_POLL); esp_sntp_setservername(0, sntp_server); sntp_set_time_sync_notification_cb(sntp_sync_callback); esp_sntp_init(); console_register( "sntp", "Manage SNTP", "sntp ", command_func); } void time_sntp_restart(void) { if (!sntp_restart()) ESP_LOGW(TAG, "SNTP restart requested, but SNTP is not running"); }