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
+99
View File
@@ -0,0 +1,99 @@
# Telemetry
Telemetry tracks per-bell strike counts and thermal load to protect actuators from overuse and enable warranty/maintenance reporting. Each hammer activation increments both a persistent strike counter and an in-memory heat accumulator; a background FreeRTOS task decays the heat values every second and triggers a force-stop via callback if any bell crosses its maximum load threshold. Strike counters survive reboots by persisting to `/telemetry_data.json` on the SD card. The subsystem is intentionally lightweight — it owns no network or UI logic; external subsystems (BellEngine, TelemetryHandler) read from it and act on its state.
---
## Public API
| Method | Description |
|--------|-------------|
| `void begin()` | Initializes arrays, loads persisted strike counters from SD (if available), and starts `TelemetryTask` on Core 1 at priority 2. |
| `void setPlayerReference(bool* isPlayingPtr)` | Provides a pointer to `Player::isPlaying` so the background task can skip processing when no playback is active. Must be called before `begin()`. |
| `void setFileManager(FileManager* fm)` | Provides the FileManager used for SD persistence. Optional — if not set, save/load calls are silently skipped. |
| `void setForceStopCallback(void (*callback)())` | Registers a zero-argument callback invoked when any bell's load exceeds its maximum. In production this calls `player.forceStop()`. |
| `void recordBellStrike(uint8_t bellIndex)` | Increments `strikeCounters[bellIndex]` and `bellLoad[bellIndex]` by 1 under spinlock. Sets the system-wide `coolingActive` flag. Called by BellEngine on every hammer activation. |
| `uint32_t getStrikeCount(uint8_t bellIndex)` | Returns the cumulative strike count for a bell (0–15). Returns 0 for out-of-range indices. |
| `void resetStrikeCounters()` | Zeroes all 16 strike counters under spinlock. Does not reset bell loads. Does not auto-save; the caller is responsible for persistence if needed. |
| `void saveStrikeCounters()` | Serialises strike counters to `/telemetry_data.json` via FileManager. Called by Player on melody end and on forced stop. |
| `void loadStrikeCounters()` | Deserialises strike counters from `/telemetry_data.json`. Called automatically during `begin()`. |
| `uint16_t getBellLoad(uint8_t bellIndex)` | Returns the current heat accumulator value for a bell. Decremented by 1 per second by the background task. |
| `void setBellMaxLoad(uint8_t bellIndex, uint16_t maxLoad)` | Overrides the per-bell overload threshold (default: 200). |
| `bool isOverloaded(uint8_t bellIndex)` | Returns `true` when `bellLoad[bellIndex] > bellMaxLoad[bellIndex]`. |
| `bool isCoolingActive()` | Returns `true` if any bell still has residual heat (i.e. `bellLoad > 0` for at least one bell). |
| `void pause()` | Suspends the background task's processing loop. Called by OTAManager before a firmware flash to prevent SD writes mid-update. |
| `void resume()` | Re-enables background task processing after OTA completes or aborts. |
| `bool isHealthy() const` | Returns `true` if the task is running, the player reference is set, and no bell is currently overloaded. Polled by HealthMonitor. |
| `void logTemperature(float temperature)` | Stub — logs value to serial only. No persistent storage or analysis yet. |
| `void logVibration(float vibration)` | Stub — logs value to serial only. No persistent storage or analysis yet. |
---
## Initialization
Setup order in `main.cpp`:
```cpp
// 1. Provide dependencies BEFORE begin()
telemetry.setPlayerReference(&player.isPlaying); // must exist before begin()
telemetry.setForceStopCallback([]() { player.forceStop(); });
telemetry.setFileManager(&fileManager); // optional but needed for persistence
// 2. Start the subsystem
telemetry.begin(); // loads counters from SD, spawns TelemetryTask
// 3. Register with HealthMonitor
healthMonitor.setTelemetry(&telemetry);
// 4. OTAManager receives the pointer for freeze mode
otaManager.setTelemetry(&telemetry);
// 5. CommunicationRouter receives the pointer for handler registration
communication.setTelemetryReference(&telemetry);
```
`FileManager` does not need to be fully initialised before `begin()` is called — the load attempt inside `begin()` silently exits if the file is missing or the FileManager pointer is null. The `Player` object must exist at the time `setPlayerReference` is called, but `player.begin()` can happen after `telemetry.begin()`.
---
## Dependencies
| Dependency | Required | Purpose |
|------------|----------|---------|
| `FileManager` | Optional | Read/write `/telemetry_data.json` on SD card |
| `Player::isPlaying` (bool*) | Required | Gates background processing to active playback / cooling |
| Force-stop callback | Required for overload protection | Calls `player.forceStop()` on overload |
| `Logging` | Required | All log output |
| FreeRTOS | Required | `xTaskCreatePinnedToCore`, `portMUX_TYPE` spinlock |
| ArduinoJson | Required | JSON serialisation for SD persistence |
---
## Gotchas / Notes
**Thread safety.** `recordBellStrike()`, `resetStrikeCounters()`, `saveStrikeCounters()`, and `loadStrikeCounters()` all use a `portMUX_TYPE` spinlock (`portENTER_CRITICAL` / `portEXIT_CRITICAL`). These are safe to call from any task or ISR context. `getBellLoad()`, `isOverloaded()`, and `isCoolingActive()` are not spinlock-protected and are intended for read-only polling from a single task (BellEngine or TelemetryHandler); concurrent writes from `checkBellLoads()` are unlikely to cause corruption but are not formally atomic.
**Background task.** `TelemetryTask` runs on Core 1 at priority 2 with a 4096-byte stack. It wakes every 1000 ms. Processing is skipped entirely when `isPaused` is set (OTA freeze mode) or when neither `isPlaying` nor `coolingActive` is true. This means load decay halts if no strike has occurred since the last play session — load values will be stale until the next play starts.
**Overload detection and force-stop.** When `checkBellLoads()` finds any bell with `load > maxLoad`, it invokes the force-stop callback. The callback runs in the context of `TelemetryTask` on Core 1. Ensure the callback (`player.forceStop()`) is safe to call from Core 1.
**Save timing.** Strike counters are saved to SD by `Player` at melody end and forced stop — not by Telemetry itself on a timer. If power is lost mid-melody, the current session's strikes are lost. There is no periodic auto-save.
**SD dependency at boot.** If the SD card is absent at boot, `loadStrikeCounters()` silently succeeds with all-zero counters — there is no warning that previously persisted data is unavailable.
**Heat model.** The thermal model is a simple increment/decrement counter, not a physical model. One strike adds 1 unit of load; 1 unit decays per second. A bell with `maxLoad = 200` (the default) tolerates sustained rates up to ~200 strikes per second before triggering overload, which is far beyond any realistic bell schedule. The threshold is more useful as a runaway-loop guard than a true thermal limit. Adjust per-bell thresholds via `setBellMaxLoad()` if tighter protection is needed for a specific installation.
**Remote commands (via TelemetryHandler).** The following v2 commands are handled by `TelemetryHandler` and routed through `CommunicationRouter`:
| Command | Description |
|---------|-------------|
| `telemetry.get_strikes` | Returns strike counts for all 16 bells |
| `telemetry.reset_strikes` | Resets all counters to 0 (all-at-once; per-bell reset not yet implemented) |
| `telemetry.get_loads` | Returns current load values, `cooling_active` flag, and list of overloaded bell indices |
Example requests:
```json
{ "v": 2, "cmd": "telemetry.get_strikes", "contents": {} }
{ "v": 2, "cmd": "telemetry.get_loads", "contents": {} }
{ "v": 2, "cmd": "telemetry.reset_strikes", "contents": {} }
```