From f73a53636864cae0918cde2723dc3f6615eb5c55 Mon Sep 17 00:00:00 2001 From: Forairaaaaa Date: Thu, 5 Nov 2026 10:37:22 +0800 Subject: [PATCH] fix(time): resync on every SetWiFi request and report failures --- main/apps/app_set_wifi/app_set_wifi.cpp | 8 +- main/apps/utils/sntp_wrap/sntp_wrap.c | 197 ++++++------------------ main/apps/utils/sntp_wrap/sntp_wrap.h | 4 +- 3 files changed, 52 insertions(+), 157 deletions(-) diff --git a/main/apps/app_set_wifi/app_set_wifi.cpp b/main/apps/app_set_wifi/app_set_wifi.cpp index 5471d73f..1b34e8f5 100644 --- a/main/apps/app_set_wifi/app_set_wifi.cpp +++ b/main/apps/app_set_wifi/app_set_wifi.cpp @@ -185,11 +185,11 @@ void AppSetWiFi::_update_state() _canvas->setTextColor(THEME_COLOR_REPL_TEXT, THEME_COLOR_BG); _canvas_update(); - sntp_warp_init(); - _data.hal->setSntpAdjusted(true); + bool time_synced = sntp_warp_init(); + _data.hal->setSntpAdjusted(time_synced); - _canvas->setTextColor(TFT_GREENYELLOW, THEME_COLOR_BG); - _canvas->printf("Done\n"); + _canvas->setTextColor(time_synced ? TFT_GREENYELLOW : TFT_RED, THEME_COLOR_BG); + _canvas->printf(time_synced ? "Done\n" : "Time sync failed. Retry SetWiFi.\n"); _canvas->setTextColor(THEME_COLOR_REPL_TEXT, THEME_COLOR_BG); _canvas->printf(">>> "); _canvas_update(); diff --git a/main/apps/utils/sntp_wrap/sntp_wrap.c b/main/apps/utils/sntp_wrap/sntp_wrap.c index 008a9b28..14e7e862 100644 --- a/main/apps/utils/sntp_wrap/sntp_wrap.c +++ b/main/apps/utils/sntp_wrap/sntp_wrap.c @@ -1,181 +1,74 @@ /** * @file sntp_wrap.c * @author Forairaaaaa - * @brief - * @version 0.6 - * @date 2023-10-18 - * https://github.com/espressif/esp-idf/blob/v4.4.6/examples/protocols/sntp/main/sntp_example_main.c + * @brief Network time synchronization for SetWiFi. * @copyright Copyright (c) 2023 - * */ #include "sntp_wrap.h" -#include "../wifi_connect_wrap/wifi_connect_wrap.h" - -/* LwIP SNTP example - - This example code is in the Public Domain (or CC0 licensed, at your option.) - - Unless required by applicable law or agreed to in writing, this - software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. -*/ -#include +#include #include -#include #include "freertos/FreeRTOS.h" #include "freertos/task.h" -#include "freertos/event_groups.h" -#include "esp_system.h" -#include "esp_event.h" #include "esp_log.h" -#include "esp_attr.h" -#include "esp_sleep.h" -#include "nvs_flash.h" -// #include "protocol_examples_common.h" #include "esp_sntp.h" -static const char *TAG = "example"; - -/* Variable holding number of times ESP32 restarted since first boot. - * It is placed into RTC memory using RTC_DATA_ATTR and - * maintains its value when ESP32 wakes from deep sleep. - */ -RTC_DATA_ATTR static int boot_count = 0; +static const char* TAG = "sntp"; -static void obtain_time(void); -static void initialize_sntp(void); +static void time_sync_notification_cb(struct timeval* tv) { ESP_LOGI(TAG, "Notification of a time synchronization event"); } -#ifdef CONFIG_SNTP_TIME_SYNC_METHOD_CUSTOM -void sntp_sync_time(struct timeval *tv) +bool sntp_warp_init(void) { - settimeofday(tv, NULL); - ESP_LOGI(TAG, "Time is synchronized from custom code"); - sntp_set_sync_status(SNTP_SYNC_STATUS_COMPLETED); -} + // Each SetWiFi request must obtain fresh time, even if the current year + // looks valid. Stop the previous client before configuring another request. + esp_sntp_stop(); +#if LWIP_DHCP_GET_NTP_SRV + esp_sntp_servermode_dhcp(1); #endif + esp_sntp_setoperatingmode(ESP_SNTP_OPMODE_POLL); + esp_sntp_setservername(0, "pool.ntp.org"); + sntp_set_sync_mode(SNTP_SYNC_MODE_IMMED); + sntp_set_sync_status(SNTP_SYNC_STATUS_RESET); + sntp_set_time_sync_notification_cb(time_sync_notification_cb); -void time_sync_notification_cb(struct timeval *tv) -{ - ESP_LOGI(TAG, "Notification of a time synchronization event"); -} - -void sntp_warp_init(void) -{ - ++boot_count; - ESP_LOGI(TAG, "Boot count: %d", boot_count); + ESP_LOGI(TAG, "Initializing SNTP"); + esp_sntp_init(); - time_t now; - struct tm timeinfo; - time(&now); - localtime_r(&now, &timeinfo); - // Is time set? If not, tm_year will be (1970 - 1900). - if (timeinfo.tm_year < (2016 - 1900)) { - ESP_LOGI(TAG, "Time is not set yet. Connecting to WiFi and getting time over NTP."); - obtain_time(); - // update 'now' variable with current time - time(&now); - } -#ifdef CONFIG_SNTP_TIME_SYNC_METHOD_SMOOTH - else { - // add 500 ms error to the current system time. - // Only to demonstrate a work of adjusting method! + bool synced = false; + const int retry_count = 10; + for (int retry = 0; retry <= retry_count; ++retry) + { + // Read this once: a COMPLETED status is cleared by the getter. + if (sntp_get_sync_status() == SNTP_SYNC_STATUS_COMPLETED) { - ESP_LOGI(TAG, "Add a error for test adjtime"); - struct timeval tv_now; - gettimeofday(&tv_now, NULL); - int64_t cpu_time = (int64_t)tv_now.tv_sec * 1000000L + (int64_t)tv_now.tv_usec; - int64_t error_time = cpu_time + 500 * 1000L; - struct timeval tv_error = { .tv_sec = error_time / 1000000L, .tv_usec = error_time % 1000000L }; - settimeofday(&tv_error, NULL); + synced = true; + break; } - - ESP_LOGI(TAG, "Time was set, now just adjusting it. Use SMOOTH SYNC method."); - obtain_time(); - // update 'now' variable with current time - time(&now); + if (retry == retry_count) + { + break; + } + ESP_LOGI(TAG, "Waiting for system time to be set... (%d/%d)", retry + 1, retry_count); + vTaskDelay(pdMS_TO_TICKS(2000)); } -#endif - - char strftime_buf[64]; - // Set timezone to Eastern Standard Time and print local time - setenv("TZ", "EST5EDT,M3.2.0/2,M11.1.0", 1); - tzset(); - localtime_r(&now, &timeinfo); - strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo); - ESP_LOGI(TAG, "The current date/time in New York is: %s", strftime_buf); + // SetWiFi disconnects Wi-Fi after this call; do not leave a client running + // after a timeout or let an old request satisfy the next attempt. + esp_sntp_stop(); + if (!synced) + { + ESP_LOGW(TAG, "Time synchronization timed out"); + return false; + } - // Set timezone to China Standard Time + // Preserve the demo's existing local timezone. setenv("TZ", "CST-8", 1); tzset(); + time_t now; + struct tm timeinfo; + char strftime_buf[64]; + time(&now); localtime_r(&now, &timeinfo); strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo); ESP_LOGI(TAG, "The current date/time in Shanghai is: %s", strftime_buf); - - if (sntp_get_sync_mode() == SNTP_SYNC_MODE_SMOOTH) { - struct timeval outdelta; - while (sntp_get_sync_status() == SNTP_SYNC_STATUS_IN_PROGRESS) { - adjtime(NULL, &outdelta); - ESP_LOGI(TAG, "Waiting for adjusting time ... outdelta = %li sec: %li ms: %li us", - (long)outdelta.tv_sec, - outdelta.tv_usec/1000, - outdelta.tv_usec%1000); - vTaskDelay(2000 / portTICK_PERIOD_MS); - } - } - - // const int deep_sleep_sec = 10; - // ESP_LOGI(TAG, "Entering deep sleep for %d seconds", deep_sleep_sec); - // esp_deep_sleep(1000000LL * deep_sleep_sec); -} - -static void obtain_time(void) -{ - // ESP_ERROR_CHECK( nvs_flash_init() ); - // ESP_ERROR_CHECK(esp_netif_init()); - // ESP_ERROR_CHECK( esp_event_loop_create_default() ); - - /** - * NTP server address could be aquired via DHCP, - * see LWIP_DHCP_GET_NTP_SRV menuconfig option - */ -#if LWIP_DHCP_GET_NTP_SRV - esp_sntp_servermode_dhcp(1); // accept NTP offers from DHCP server, if any -#endif - - /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig. - * Read "Establishing Wi-Fi or Ethernet Connection" section in - * examples/protocols/README.md for more information about this function. - */ - // ESP_ERROR_CHECK(example_connect()); - // wifi_connect_wrap_connect(); - - initialize_sntp(); - - // 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); - - // ESP_ERROR_CHECK( example_disconnect() ); - // wifi_connect_wrap_disconnect(); -} - -static void initialize_sntp(void) -{ - ESP_LOGI(TAG, "Initializing SNTP"); - esp_sntp_setoperatingmode(ESP_SNTP_OPMODE_POLL); - esp_sntp_setservername(0, "pool.ntp.org"); - sntp_set_time_sync_notification_cb(time_sync_notification_cb); -#ifdef CONFIG_SNTP_TIME_SYNC_METHOD_SMOOTH - sntp_set_sync_mode(SNTP_SYNC_MODE_SMOOTH); -#endif - esp_sntp_init(); + return true; } diff --git a/main/apps/utils/sntp_wrap/sntp_wrap.h b/main/apps/utils/sntp_wrap/sntp_wrap.h index 71b72cb0..116d27d4 100644 --- a/main/apps/utils/sntp_wrap/sntp_wrap.h +++ b/main/apps/utils/sntp_wrap/sntp_wrap.h @@ -9,12 +9,14 @@ * */ #pragma once +#include #ifdef __cplusplus extern "C" { #endif -void sntp_warp_init(void); +// Returns true only after a fresh SNTP response has updated the system clock. +bool sntp_warp_init(void); #ifdef __cplusplus