fix(TimeKeeper): guard NTP sync against reconnect storms and bad readings

Field units on unstable internet had RTC time drift wildly (10 min to
half a day), while units with stable internet stayed accurate. Root
cause: syncTimeWithNTP() wrote getLocalTime()'s result straight to the
RTC with no plausibility check, and fires on every WiFi reconnect
(not a fixed schedule) — so flaky links produced far more unguarded
sync attempts than healthy ones. The underlying configTime()/
getLocalTime() API has no request/response correlation, so a stale
reply from an abandoned attempt could be picked up by a later
attempt's window if reconnects outpaced a single attempt's ~5s resolve
time.

Three layers of defense, all in TimeKeeper:
- In-flight de-dup guard (ntpSyncInProgress) so only one sync attempt
  is ever listening at a time, closing the window a stale reply could
  land in.
- 10s cooldown between attempts to throttle reconnect storms.
- commitNtpResult(): corrections under 2 minutes commit immediately
  (normal drift); anything larger is held as a pending candidate and
  only written to the RTC once 3 consecutive syncs agree within 5s of
  each other, so a single bad reading can no longer move the clock by
  hours.

Documented in TimeKeeper/README.md under "NTP sync safety".
This commit is contained in:
2026-07-20 09:08:05 +03:00
parent f41332a771
commit e89a1b623f
3 changed files with 166 additions and 15 deletions
+105 -14
View File
@@ -8,6 +8,14 @@
#include "SD.h"
#include <time.h>
// ────────────────────────────────────────────────────────────────────────────
// NTP sync safety thresholds — see README.md "NTP sync safety"
// ────────────────────────────────────────────────────────────────────────────
static constexpr time_t NTP_JUMP_THRESHOLD_SEC = 120; // >2 min drift requires consensus
static constexpr uint8_t NTP_AGREE_REQUIRED = 3; // consecutive agreeing syncs needed
static constexpr time_t NTP_AGREE_TOLERANCE_SEC = 5; // candidates must agree within this
static constexpr unsigned long NTP_MIN_RETRY_MS = 10000; // cooldown between attempts
void Timekeeper::begin() {
LOG_INFO(TAG, "Timekeeper initialized - clock outputs managed by ConfigManager");
@@ -160,6 +168,29 @@ void Timekeeper::syncTimeWithNTP() {
return;
}
// De-dup guard: never allow two sync attempts in flight at once. Without this,
// rapid WiFi reconnects on a flaky link could each start their own configTime()
// call, and a stale reply from an earlier abandoned attempt could be read back
// during a later attempt's getLocalTime() window (there is no request/response
// correlation in the underlying SNTP client — see README.md "NTP sync safety").
bool expected = false;
if (!ntpSyncInProgress.compare_exchange_strong(expected, true)) {
LOG_INFO(TAG, "⏰ NTP sync already in progress - skipping overlapping attempt");
return;
}
// Cooldown: refuse to retry too soon after the previous attempt. This throttles
// reconnect storms so each attempt gets a clean, uncontested window instead of
// stacking up behind each other.
unsigned long now = millis();
if (lastNtpAttemptMs != 0 && (now - lastNtpAttemptMs) < NTP_MIN_RETRY_MS) {
LOG_INFO(TAG, "⏰ NTP sync attempted too soon after last try (%lu ms ago) - skipping",
now - lastNtpAttemptMs);
ntpSyncInProgress.store(false);
return;
}
lastNtpAttemptMs = now;
LOG_INFO(TAG, "⏰ Starting NTP sync (UTC-only, offsets applied manually)...");
// Get stored offsets from config — these are the only source of truth
@@ -178,26 +209,86 @@ void Timekeeper::syncTimeWithNTP() {
time_t utcEpoch = mktime(&utcTimeInfo);
time_t localEpoch = utcEpoch + totalOffsetSec;
struct tm localTimeInfo;
gmtime_r(&localEpoch, &localTimeInfo);
if (commitNtpResult(localEpoch)) {
struct tm localTimeInfo;
gmtime_r(&localEpoch, &localTimeInfo);
// Write local time into RTC
rtc.adjust(DateTime(localTimeInfo.tm_year + 1900, localTimeInfo.tm_mon + 1, localTimeInfo.tm_mday,
localTimeInfo.tm_hour, localTimeInfo.tm_min, localTimeInfo.tm_sec));
LOG_INFO(TAG, "✅ NTP sync successful: UTC %04d-%02d-%02d %02d:%02d:%02d → Local %04d-%02d-%02d %02d:%02d:%02d (offset %+ld s)",
utcTimeInfo.tm_year + 1900, utcTimeInfo.tm_mon + 1, utcTimeInfo.tm_mday,
utcTimeInfo.tm_hour, utcTimeInfo.tm_min, utcTimeInfo.tm_sec,
localTimeInfo.tm_year + 1900, localTimeInfo.tm_mon + 1, localTimeInfo.tm_mday,
localTimeInfo.tm_hour, localTimeInfo.tm_min, localTimeInfo.tm_sec,
totalOffsetSec);
LOG_INFO(TAG, "✅ NTP sync successful: UTC %04d-%02d-%02d %02d:%02d:%02d → Local %04d-%02d-%02d %02d:%02d:%02d (offset %+ld s)",
utcTimeInfo.tm_year + 1900, utcTimeInfo.tm_mon + 1, utcTimeInfo.tm_mday,
utcTimeInfo.tm_hour, utcTimeInfo.tm_min, utcTimeInfo.tm_sec,
localTimeInfo.tm_year + 1900, localTimeInfo.tm_mon + 1, localTimeInfo.tm_mday,
localTimeInfo.tm_hour, localTimeInfo.tm_min, localTimeInfo.tm_sec,
totalOffsetSec);
// Reload today's events since the time might have changed significantly
loadTodaysEvents();
// Reload today's events since the time might have changed significantly
loadTodaysEvents();
}
// commitNtpResult() logs its own rejection/pending-consensus messages
} else {
// No internet or NTP server unreachable — this is NORMAL for local networks
LOG_INFO(TAG, "⚠️ NTP sync skipped (no internet) - using RTC time. This is normal for local networks.");
}
ntpSyncInProgress.store(false);
}
bool Timekeeper::commitNtpResult(time_t candidateLocalEpoch) {
// No existing RTC time to compare against (not running) — trust NTP outright,
// this is the "RTC lost power / brand new board" case.
if (!rtc.isrunning()) {
rtc.adjust(DateTime((uint32_t)candidateLocalEpoch));
pendingNtpAgreeCount = 0;
LOG_INFO(TAG, "⏰ RTC was not running - accepting NTP result unconditionally");
return true;
}
time_t rtcEpoch = (time_t)rtc.now().unixtime();
time_t drift = candidateLocalEpoch - rtcEpoch;
time_t absDrift = drift < 0 ? -drift : drift;
if (absDrift <= NTP_JUMP_THRESHOLD_SEC) {
// Small correction — normal drift compensation, commit immediately.
rtc.adjust(DateTime((uint32_t)candidateLocalEpoch));
pendingNtpAgreeCount = 0;
LOG_DEBUG(TAG, "⏰ NTP drift %+ld s within threshold - committing directly", (long)drift);
return true;
}
// Large jump (>NTP_JUMP_THRESHOLD_SEC) — do not trust a single reading. Require
// NTP_AGREE_REQUIRED consecutive attempts to agree with each other (within
// NTP_AGREE_TOLERANCE_SEC) before writing the RTC. This is what actually stops
// a single bad/stale reply from corrupting the clock — see README.md.
time_t agreeDrift = pendingNtpAgreeCount == 0
? 0
: (candidateLocalEpoch - pendingNtpEpoch);
time_t absAgreeDrift = agreeDrift < 0 ? -agreeDrift : agreeDrift;
if (pendingNtpAgreeCount == 0 || absAgreeDrift > NTP_AGREE_TOLERANCE_SEC) {
// First candidate of a new sequence, or this one disagrees with the running
// sequence — restart the consensus count from this reading.
pendingNtpEpoch = candidateLocalEpoch;
pendingNtpAgreeCount = 1;
LOG_WARNING(TAG, "⚠️ NTP result differs from RTC by %+ld s (>%ld s threshold) - "
"holding, need %d consecutive agreeing syncs (1/%d so far)",
(long)drift, (long)NTP_JUMP_THRESHOLD_SEC, NTP_AGREE_REQUIRED, NTP_AGREE_REQUIRED);
return false;
}
// Agrees with the pending candidate.
pendingNtpAgreeCount++;
LOG_WARNING(TAG, "⚠️ NTP large jump (%+ld s) candidate confirmed (%d/%d agreeing syncs)",
(long)drift, pendingNtpAgreeCount, NTP_AGREE_REQUIRED);
if (pendingNtpAgreeCount < NTP_AGREE_REQUIRED) {
return false;
}
// Consensus reached — commit.
rtc.adjust(DateTime((uint32_t)candidateLocalEpoch));
LOG_INFO(TAG, "✅ NTP large jump confirmed by %d consecutive syncs - committing %+ld s correction",
NTP_AGREE_REQUIRED, (long)drift);
pendingNtpAgreeCount = 0;
return true;
}
// ════════════════════════════════════════════════════════════════════════════