From 778041ec064e56bbb802fe823363ff97cb05bf42 Mon Sep 17 00:00:00 2001 From: Manuel <71137295+mverch67@users.noreply.github.com> Date: Thu, 13 Aug 2026 19:57:07 +0200 Subject: [PATCH] fix esp32 time sync (RTC / NTP) (#11494) --- src/gps/RTC.cpp | 15 ++++++++++++++- src/mesh/wifi/WiFiAPClient.cpp | 8 ++++++-- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/gps/RTC.cpp b/src/gps/RTC.cpp index 5c18cca62..93e59e31e 100644 --- a/src/gps/RTC.cpp +++ b/src/gps/RTC.cpp @@ -140,6 +140,9 @@ RTCSetResult readFromRTC() RTCQuality oldQuality = currentQuality; timeStartMs64 = now; zeroOffsetSecs = tv.tv_sec; +#if defined(ARCH_ESP32) || defined(ARCH_RP2040) + settimeofday(&tv, NULL); +#endif currentQuality = RTCQualityDevice; onTimeSourceQualityChanged(oldQuality, currentQuality); } @@ -186,6 +189,9 @@ RTCSetResult readFromRTC() RTCQuality oldQuality = currentQuality; timeStartMs64 = now; zeroOffsetSecs = tv.tv_sec; +#if defined(ARCH_ESP32) || defined(ARCH_RP2040) + settimeofday(&tv, NULL); +#endif currentQuality = RTCQualityDevice; onTimeSourceQualityChanged(oldQuality, currentQuality); } @@ -222,6 +228,9 @@ RTCSetResult readFromRTC() RTCQuality oldQuality = currentQuality; timeStartMs64 = now; zeroOffsetSecs = tv.tv_sec; +#if defined(ARCH_ESP32) || defined(ARCH_RP2040) + settimeofday(&tv, NULL); +#endif currentQuality = RTCQualityDevice; onTimeSourceQualityChanged(oldQuality, currentQuality); } @@ -389,7 +398,11 @@ RTCSetResult perhapsSetRTC(RTCQuality q, const struct timeval *tv, bool forceUpd if (stm32wlRtcAvailable()) { STM32RTC::getInstance().setEpoch(tv->tv_sec); } -#elif defined(ARCH_ESP32) || defined(ARCH_RP2040) +#endif + // Keep the POSIX system clock in sync on platforms that support it so that + // any code using time() (e.g. the device-ui thread) sees the correct wall time + // even when a hardware RTC chip is also present and handled above. +#if defined(ARCH_ESP32) || defined(ARCH_RP2040) settimeofday(tv, NULL); #endif diff --git a/src/mesh/wifi/WiFiAPClient.cpp b/src/mesh/wifi/WiFiAPClient.cpp index c7fc1b25f..8bb80cd96 100644 --- a/src/mesh/wifi/WiFiAPClient.cpp +++ b/src/mesh/wifi/WiFiAPClient.cpp @@ -294,7 +294,7 @@ static int32_t reconnectWiFi() #ifndef DISABLE_NTP if (WiFi.isConnected() && (!Throttle::isWithinTimespanMs(lastrun_ntp, 43200000) || (lastrun_ntp == 0))) { // every 12 hours LOG_DEBUG("Update NTP time from %s", config.network.ntp_server); - if (timeClient.update()) { + if (timeClient.forceUpdate()) { LOG_DEBUG("NTP success - set RTCQualityNTP if needed"); struct timeval tv; @@ -316,7 +316,11 @@ static int32_t reconnectWiFi() return 1000; // check once per second } else { onNetworkConnected(); // will only do anything once (guarded by APStartupComplete) - return 300000; // every 5 minutes +#ifndef DISABLE_NTP + if (lastrun_ntp == 0) + return 5000; // NTP not yet synced, retry sooner +#endif + return 300000; // every 5 minutes } }