docs: add per-subsystem README files

Add inline documentation for all src/ subsystems covering purpose,
responsibilities, public API, and usage notes.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-14 22:16:03 +02:00
co-authored by Claude Sonnet 4.6
parent d4bd990e53
commit d4d8b1c380
29 changed files with 2961 additions and 0 deletions
+89
View File
@@ -0,0 +1,89 @@
# 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. On success, writes the result to the RTC and reloads 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. |
---
## 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.