# TimeKeeper ## Summary TimeKeeper is the timekeeping and scheduling subsystem for Vesper. It owns the DS1307 RTC, performs NTP synchronisation, fires scheduled bell events loaded from SD, drives a hardware analog clock face (two-wire impulse motor), and manages timed bell alerts (hourly, half-hour, quarter-hour). It exists to decouple all time-dependent behaviour from the other subsystems: the RTC is the single source of truth for wall-clock time, and everything that needs to act at a specific time goes through TimeKeeper rather than polling `millis()` itself. --- ## Public API | Method | Description | |---|---| | `void begin()` | Initialises the RTC, loads today's scheduled events from SD, and creates the main FreeRTOS task. Must be called in `setup()`. | | `void setOutputManager(OutputManager*)` | Injects the OutputManager dependency. Required before the task loop can drive relays or fire bells. | | `void setConfigManager(ConfigManager*)` | Injects the ConfigManager dependency. Required for reading clock config, timezone, and physical clock state. | | `void setNetworking(Networking*)` | Injects the Networking dependency. Required for NTP sync (checks `isConnected()` before attempting). | | `void setPlayer(Player*)` | Injects the Player dependency. Used to detect active playback and suppress or interrupt clock alerts. | | `void setTime(unsigned long timestamp)` | Sets the RTC from a UTC Unix timestamp. Applies the timezone offset from ConfigManager before writing to the RTC. Reloads today's events afterward. | | `void setTimeWithLocalTimestamp(unsigned long localTimestamp)` | Sets the RTC directly from a pre-offset (local) Unix timestamp. No additional timezone conversion is applied. Used by ClockHandler when the caller has already computed the local time. | | `unsigned long getTime()` | Returns the current RTC time as a Unix timestamp. Returns 0 if the RTC is not running. | | `void syncTimeWithNTP()` | Calls `configTime()` + `getLocalTime()` with a 5-second timeout. Guards against overlapping/rapid-fire attempts (see "NTP sync safety" below), then runs the result through `commitNtpResult()` before writing the RTC and reloading events. Silently skips if network is unavailable. | | `void loadTodaysEvents()` | Reads `/events/events.json` from SD and populates the internal event list for the current date. Handles `single`, `weekly`, and `monthly` event types. | | `void loadNextDayEvents()` | Stub — pre-loads tomorrow's events for smooth midnight transitions. Not yet implemented. | | `void pauseClockUpdates()` | Pauses physical clock motor advancement (sets internal flag). | | `void resumeClockUpdates()` | Resumes physical clock motor advancement. | | `bool areClockUpdatesPaused() const` | Returns the current pause state. | | `void interruptActiveAlert()` | Clears the `alertInProgress` atomic flag. Called by Player when starting playback so a running multi-ring alert stops at the next ring boundary. | | `bool isHealthy() const` | Returns `true` if the RTC is running, the FreeRTOS task is alive, both ConfigManager and OutputManager are set, and the RTC year is in the range 2020–2100. | ### Deprecated — do not use | Method | Note | |---|---| | `void setRelayWriteFunction(void (*func)(int, int))` | Legacy relay function pointer. Superseded by OutputManager. | | `void setClockOutputs(int, int)` | Forwards to ConfigManager if available. Will be removed. | --- ## Initialization TimeKeeper must be initialized in `setup()` after ConfigManager and OutputManager, and before the Communication subsystem (ClockHandler holds a reference to it): ```cpp timekeeper.begin(); // initialises RTC, creates FreeRTOS task timekeeper.setOutputManager(&outputManager); timekeeper.setConfigManager(&configManager); timekeeper.setNetworking(&networking); timekeeper.setPlayer(&player); ``` The dependency setters can be called after `begin()` — the task loop checks each pointer for null before use, so there is no race condition as long as all setters complete before the first 1-second tick fires. In practice the FreeRTOS scheduler does not preempt the remaining `setup()` code on the same core, so this is safe. NTP sync is not triggered by `begin()`. It is deferred to a one-shot FreeRTOS timer started in the network-connected callback (3-second delay for link stabilisation), which spawns a short-lived `ntpSync` task (3072-byte stack) that calls `timekeeper.syncTimeWithNTP()`. --- ## Dependencies | Dependency | Required | Purpose | |---|---|---| | **RTClib** (`RTC_DS1307`) | Yes | Hardware RTC over I2C. `Wire.begin()` must be called before `begin()`. | | **ConfigManager** | Yes (at task runtime) | Clock config (outputs, pulse/pause timing, alert settings, silence periods, backlight), timezone offsets, physical clock face state. | | **OutputManager** | Yes (at task runtime) | Fires relay outputs for clock motor pulses, alert bells, and backlight relay. | | **Networking** | Yes (for NTP) | Checked with `isConnected()` before attempting NTP. If absent or disconnected, NTP is skipped and the RTC value is used as-is. | | **Player** | Yes (for alert coordination) | `checkClockAlerts()` reads `player->isPlaying` to suppress alerts during active playback. | | **SD card** | Yes (for events) | `loadTodaysEvents()` opens `/events/events.json` directly via `SD.open()`. If the file is absent or unparseable the event list is empty and boot continues. | | **ArduinoJson** | Yes | Event file parsing. Uses a `static StaticJsonDocument<8192>` to reduce heap fragmentation. | --- ## NTP sync safety (bugfix) **Background.** Field units with unstable internet were observed to have RTC time off by anywhere from ~10 minutes to half a day, while units with stable internet stayed accurate indefinitely. Root cause: `syncTimeWithNTP()` wrote whatever `getLocalTime()` returned straight to the RTC via `rtc.adjust()`, with no plausibility check and no protection against overlapping sync attempts. On a flaky link, `ntpSyncTimerCallback` (`main.cpp`) fires on **every** WiFi reconnect — not on a fixed schedule — so an unstable connection produces far more sync attempts than a healthy one, and each attempt was an unguarded write straight to the RTC. Because the Arduino `configTime()`/`getLocalTime()` API has no request/response correlation (a reply is accepted as valid based only on "does the system clock look set", not "is this the reply to the request I just sent"), a stale or delayed reply from an earlier, already-abandoned attempt could be picked up by a later attempt's listening window if reconnects happened faster than a single attempt's ~5s resolve time. This matches the reported symptom: random-magnitude jumps rather than a fixed offset. **Fix — three layers in `syncTimeWithNTP()` / `commitNtpResult()`:** 1. **In-flight de-dup guard.** `ntpSyncInProgress` (atomic) rejects a new sync attempt if one is already running. This is the primary fix for the missing request/response correlation: since the underlying SNTP client can't tell attempts apart, the safest fix is to never have more than one attempt in flight, so there's nothing for a stale reply to collide with. 2. **Cooldown between attempts.** `lastNtpAttemptMs` enforces a minimum gap (`NTP_MIN_RETRY_MS`, 10s) between sync attempts, independent of the de-dup guard. This throttles reconnect storms on a flapping link so attempts don't stack up back-to-back. 3. **Plausibility + consensus gate (`commitNtpResult()`).** A result within `NTP_JUMP_THRESHOLD_SEC` (2 minutes) of the current RTC value is committed immediately — this is normal drift correction. A result that would jump the clock by more than that is **not** written to the RTC on the first sighting. It is held as a pending candidate, and only committed once `NTP_AGREE_REQUIRED` (3) consecutive sync attempts agree with each other within `NTP_AGREE_TOLERANCE_SEC` (5s). A single bad/stale reply can no longer move the clock by hours — it would have to be reproduced by three independent syncs in a row. If the RTC is not running at all (dead battery, brand new board), the first NTP result is trusted unconditionally since there is nothing meaningful to compare it against. **Tuning.** All four constants are `static constexpr` at the top of `TimeKeeper.cpp`. Raising `NTP_AGREE_REQUIRED` or `NTP_AGREE_TOLERANCE_SEC` trades slower recovery from a genuinely large clock error (e.g. after extended power-off) for stronger rejection of bad readings. Lowering `NTP_JUMP_THRESHOLD_SEC` below normal RTC drift-per-sync-interval will cause routine corrections to go through the consensus path unnecessarily. **Consensus state does not persist across reboots or resets.** `pendingNtpEpoch` / `pendingNtpAgreeCount` are in-RAM only. A device that reboots mid-consensus starts the count over from zero on the next large-jump candidate. This is intentional — a fresh boot has no reason to trust a partially-built consensus from before the restart. --- ## Gotchas / Notes **Single FreeRTOS task.** Everything — physical clock sync, alerts, backlight automation, event scheduling, RTC health — runs in one task: `mainTimekeeperTask`, pinned to Core 1, priority 2, 4096-byte stack. The stack is shared with `fireAlertBell()`, which calls `vTaskDelay()` in a loop. Account for this when increasing ring counts or pulse durations. **Physical clock blocks the task.** `checkAndSyncPhysicalClock()` is called every loop iteration. When the motor needs to advance, `advancePhysicalClockOneMinute()` calls `vTaskDelay(pulseDuration + pauseDuration)` synchronously. Long pulse/pause settings delay all other task functions (alerts, event checks) by that duration per motor step. **RTC stores local time, not UTC.** The RTC is written with timezone-adjusted local time. `getTime()` returns a Unix timestamp computed directly from RTC registers — this is local time expressed as a Unix epoch value, not true UTC. Any caller treating `getTime()` as UTC will compute incorrect offsets. **Event trigger granularity is per-minute.** `checkScheduledEvents()` matches only `HH:MM`; seconds in the event file are ignored. An event fires once per minute and resets its trigger flag only after the current minute has passed. **Midnight event reload.** The RTC maintenance block runs every 10 seconds. The midnight reload check (`hour == 0 && minute == 0 && second < 10`) fires within 10 seconds of 00:00:00, not exactly at midnight. **Alert interruption is cooperative, not preemptive.** `interruptActiveAlert()` clears an atomic flag. The running `fireAlertBell()` loop checks the flag before each ring, so the current ring always completes before the alert stops. **Silence periods support midnight rollover.** `isTimeInRange()` detects a crossed-midnight range when `startTime > endTime` and applies `current >= start || current <= end` logic accordingly. **Duplicate `isHealthy()` declaration in header.** The header declares `isHealthy()` twice — once non-const in the public block and once `const` below a comment block. The implementation matches the `const` form. The non-const declaration is a defect and should be removed. **No mutex on `todaysEvents`.** The event vector is normally only touched from within `mainTimekeeperTask`. However, `setTime()` and `setTimeWithLocalTimestamp()` (called from the Communication task via ClockHandler) also call `loadTodaysEvents()`, which clears and repopulates the vector. If this races with the event-check loop there is an unguarded data race. The symptom would be a spurious event trigger or a missed reload, not a crash.