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>
9.2 KiB
HealthMonitor
Summary
HealthMonitor is a continuous background subsystem that polls every registered component for a self-reported health status, aggregates the results into a HEALTHY / WARNING / CRITICAL / FAILED verdict, and uses that verdict to advise the FirmwareValidator on whether the running image should be kept or rolled back. It exists to give the firmware an objective, runtime view of system integrity so that a bad OTA image — or a hardware failure — is detected and acted on automatically rather than silently degrading the device.
Public API
Subsystem registration (call before begin() if possible, or immediately after)
| Method | Description |
|---|---|
void setBellEngine(BellEngine*) |
Register BellEngine for monitoring |
void setOutputManager(OutputManager*) |
Register OutputManager for monitoring |
void setCommunication(CommunicationRouter*) |
Register CommunicationRouter for monitoring |
void setPlayer(Player*) |
Register Player for monitoring |
void setTimeKeeper(Timekeeper*) |
Register Timekeeper for monitoring |
void setTelemetry(Telemetry*) |
Register Telemetry for monitoring |
void setOTAManager(OTAManager*) |
Register OTAManager for monitoring |
void setNetworking(Networking*) |
Register Networking for monitoring |
void setConfigManager(ConfigManager*) |
Register ConfigManager for monitoring |
void setFileManager(FileManager*) |
Register FileManager for monitoring |
Subsystems that have not been registered are simply skipped during checks — they do not count as failures.
Lifecycle
| Method | Description |
|---|---|
bool begin() |
Starts the background FreeRTOS monitoring task. Returns false if task creation fails. |
Health checks
| Method | Return type | Description |
|---|---|---|
HealthStatus performFullHealthCheck() |
HealthStatus |
Polls every registered subsystem's isHealthy() and updates internal state. Returns the computed overall status. |
HealthStatus checkSubsystemHealth(const String& name) |
HealthStatus |
Polls and updates a single named subsystem. Returns FAILED for unknown or unregistered names. |
const std::map<String, SubsystemHealth>& getAllSubsystemHealth() const |
const map ref | Returns the full internal health table. Safe to read from any task after the last write has completed. |
SubsystemHealth getSubsystemHealth(const String& name) const |
SubsystemHealth |
Returns the cached health record for one subsystem. Returns a synthetic FAILED record for unknown names. |
Firmware stability
| Method | Return type | Description |
|---|---|---|
bool isFirmwareStable() const |
bool |
true if no critical subsystem is in CRITICAL or FAILED state. Used by FirmwareValidator to decide whether to commit the OTA image. |
bool shouldRollbackFirmware() const |
bool |
true if more than 2 critical subsystems have failed simultaneously. Threshold is hard-coded at MAX_CRITICAL_FAILURES = 2. |
uint8_t getCriticalFailureCount() const |
uint8_t |
Count of subsystems flagged isCritical = true that are in CRITICAL or FAILED state. |
uint8_t getWarningCount() const |
uint8_t |
Count of subsystems in WARNING state (regardless of isCritical flag). |
Reporting
| Method | Return type | Description |
|---|---|---|
String generateHealthReport() const |
String |
Serializes the full health table to a pretty-printed JSON string (ArduinoJson, up to ~2 KB). |
String getHealthSummary() const |
String |
Returns a single human-readable summary line, e.g. "System Health: WARNING (1 warnings)". |
Configuration
| Method | Description |
|---|---|
void setHealthCheckInterval(unsigned long ms) |
Override the default 300 000 ms (5 min) polling interval. Takes effect on the next task wake. |
void setAutoMonitoring(bool) |
If set to false before begin(), no FreeRTOS task is created and checks must be triggered manually. |
void setAlertCallback(AlertCallback cb) |
Register a callback invoked whenever a subsystem state changes. The callback signature is void(const String& subsystem, const String& newState, const String& message). When a subsystem recovers to HEALTHY, newState is "CLEARED" and message is empty. Called by CommunicationRouter::begin() to wire MQTT alert publishing. |
Initialization
HealthMonitor is constructed as a global in main.cpp and initialized early in setup(), before most other subsystems, because FirmwareValidator depends on it at startup:
1. SDCardMutex::begin() // must be first
2. configManager.begin()
3. healthMonitor.begin() // <-- here; monitoring task starts
4. healthMonitor.setConfigManager / setFileManager
5. outputManager.initialize()
6. healthMonitor.setOutputManager(...)
7. bellEngine.begin()
8. healthMonitor.setBellEngine(...)
9. firmwareValidator.begin(&healthMonitor, &configManager)
10. firmwareValidator.performStartupValidation()
... remaining subsystems initialized and registered ...
The subset registered before firmwareValidator.performStartupValidation() is intentionally minimal: only BellEngine and OutputManager (the two subsystems needed for FirmwareValidator::performBasicHealthCheck()). ConfigManager and FileManager references are set even earlier so the monitor is aware of them, but their health check failures are mapped to WARNING (see below). All other subsystems register themselves after startup validation has passed.
Dependencies
| Dependency | Role |
|---|---|
BellEngine |
isHealthy() — critical subsystem |
OutputManager |
isHealthy() — critical subsystem |
Player |
isHealthy() — critical subsystem; _status field read directly to skip checks during active playback |
CommunicationRouter |
isHealthy() — non-critical (WARNING on failure) |
Timekeeper |
isHealthy() — non-critical |
Telemetry |
isHealthy() — non-critical |
OTAManager |
isHealthy() — non-critical |
Networking |
isHealthy() — non-critical |
ConfigManager |
isHealthy() — non-critical (SD absence expected) |
FileManager |
isHealthy() — non-critical (SD absence expected) |
ArduinoJson |
Used in generateHealthReport() with a 2 048-byte StaticJsonDocument |
| FreeRTOS | xTaskCreatePinnedToCore, vTaskDelay, vTaskDelete |
Gotchas / Notes
Critical vs. non-critical classification.
The isCritical flag is set in initializeSubsystemHealth() and does not match the performFullHealthCheck() failure severity one-to-one. ConfigManager and FileManager are initialised as isCritical = true in the map but performFullHealthCheck() maps their failures to WARNING, not CRITICAL. This was an intentional fix to prevent SD card absence from triggering rollback — the device operates normally without an SD card.
Health check skipped during playback.
monitoringLoop() checks Player::_status directly (accessing a private member via a friend or the fact that the pointer is typed correctly) and returns early if the player is not stopped. This avoids I/O-heavy health checks interfering with bell timing. On-demand calls to performFullHealthCheck() from the SystemHandler do not have this guard.
FreeRTOS task details.
- Task name:
HealthMonitor - Stack: 4 096 bytes, Core 0
- Priority: 3 (medium)
- Interval: 300 000 ms default (
_healthCheckInterval) - BellEngine runs on Core 1 at high priority; placing HealthMonitor on Core 0 avoids contention.
No mutex on _subsystemHealth.
The std::map<String, SubsystemHealth> is written by the monitoring task and read by the SystemHandler (network-driven, Core 0) and FirmwareValidator. There is currently no FreeRTOS mutex protecting concurrent access. In practice, races are unlikely because the monitoring interval is long and all callers run on Core 0, but this is a known limitation if calling patterns change.
Rollback is advisory only.
shouldRollbackFirmware() returning true only logs a recommendation. The actual rollback decision and esp_ota_set_boot_partition() call are owned by FirmwareValidator, which calls isFirmwareStable() — not shouldRollbackFirmware() — as its gate condition.
system.health command.
The SystemHandler exposes a system.health command that callers can send over MQTT, WebSocket, or HTTP. It triggers an immediate performFullHealthCheck() and returns the result. Command format (v2):
{ "v": 2, "cmd": "system.health", "contents": {} }
Response payload includes critical_count, warning_count, firmware_stable, and a subsystems array with per-subsystem name, status, and optional error fields.
Alert callback and MQTT publishing.
CommunicationRouter::begin() calls setAlertCallback() to wire a lambda that calls CommunicationRouter::publishAlert(). From that point on, any subsystem state change that occurs inside updateSubsystemHealth() — whether triggered by the periodic check or an on-demand system.health call — automatically publishes a JSON event to vesper/{uid}/status/alerts over MQTT. The callback fires only when the status actually changes; repeated checks that return the same status are silent. The server therefore only receives a message when something changes (new problem, worsening, or recovery).