diff --git a/src/BellEngine/README.md b/src/BellEngine/README.md new file mode 100644 index 0000000..b0e93ff --- /dev/null +++ b/src/BellEngine/README.md @@ -0,0 +1,86 @@ +# BellEngine + +## Summary + +BellEngine is the real-time bell activation core of the Vesper firmware. It receives compiled melody data from `Player` and fires physical relay outputs through `OutputManager` with microsecond-precision inter-note timing. The engine runs permanently on a dedicated FreeRTOS task (priority 6, Core 1, 12 KB stack) that spins idle between plays; when `start()` is called, it executes the full melody step-by-step without interruption, applying a hybrid vTaskDelay + busy-wait strategy to hit sub-millisecond timing accuracy. BellEngine exists as a separate subsystem so that all hardware-agnostic timing logic is isolated from both the higher-level playback policy (owned by `Player`) and the hardware abstraction (owned by `OutputManager`). + +--- + +## Public API + +| Method | Description | +|--------|-------------| +| `BellEngine(Player&, ConfigManager&, Telemetry&, OutputManager&)` | Constructor. All four references must remain valid for the object lifetime. `CommunicationRouter` is injected separately via `setCommunicationManager()`. | +| `void begin()` | Creates the FreeRTOS engine task. Must be called once before `start()`. Does **not** start playback. | +| `void setCommunicationManager(CommunicationRouter*)` | Wires the optional communication reference used for overload notifications. May be called at any time before or after `begin()`. Pass `nullptr` to disconnect. | +| `void setMelodyData(const std::vector&)` | Copies melody step data into the engine under a critical section. Each `uint16_t` is a bitmask: bit N set means note-slot N fires on this step. Must be called before `start()`. | +| `void clearMelodyData()` | Clears melody data and marks the engine as not ready. Thread-safe. | +| `void start()` | Signals the engine task to begin playback. No-op (with error log) if no melody data is loaded. | +| `void stop()` | Graceful stop — sets the `_engineRunning` flag; the engine halts after the current inter-note delay. Does not cut mid-note relay pulses. | +| `void emergencyStop()` | Immediate stop. Sets both `_emergencyStop` and `_engineRunning` flags and calls `emergencyShutdown()` to de-energize all relays via `OutputManager`. | +| `bool isRunning() const` | Returns `true` if the engine is actively executing a melody. Atomic read. | +| `bool isEmergencyStopped() const` | Returns `true` if an emergency stop is in effect. Atomic read. | +| `uint32_t getMaxLoopTime() const` | Returns the worst-case engine loop execution time in microseconds, for performance diagnostics. | +| `bool isHealthy() const` | Returns `true` if the engine task handle is valid, the task state is neither deleted nor invalid, and `OutputManager::isInitialized()` is true. Used by `HealthMonitor`. | + +--- + +## Initialization + +BellEngine depends on `OutputManager` being initialized before `begin()` is called. In `main.cpp`, the sequence is: + +``` +outputManager.initialize() // OutputManager must be ready first +bellEngine.begin() // Creates engine task; task waits idle +healthMonitor.setBellEngine(&bellEngine) +// ... other subsystems ... +player.setBellEngine(&bellEngine) +bellEngine.setCommunicationManager(&communication) +``` + +`begin()` is called early (before networking and communication) so that `HealthMonitor` and `FirmwareValidator` can include BellEngine in startup validation. The engine task itself remains idle at this stage — it does nothing until `Player` loads melody data and calls `start()`. + +Typical playback sequence (driven by `Player`): + +1. `Player::loadMelodyInRAM()` — loads melody steps from SD into RAM. +2. `bellEngine.setMelodyData(steps)` — copies steps into BellEngine. +3. `bellEngine.start()` — sets `_engineRunning = true`. +4. Engine task calls `playbackLoop()`, iterates steps, fires relays via `OutputManager::fireOutputsBatchForDuration()`, applies `preciseDelay()` between steps. +5. On final step: `player.onMelodyLoopCompleted()` is called so Player can handle looping, pausing, or stopping. +6. `Player` calls `bellEngine.stop()` or `bellEngine.emergencyStop()` when done. + +--- + +## Dependencies + +| Dependency | Role | +|------------|------| +| `Player` | Provides `isPlaying`, `isPaused`, `hardStop`, `speed`, `noteAssignments`, and the `onMelodyLoopCompleted()` callback. BellEngine reads these public fields directly — no locking around them. | +| `ConfigManager` | Supplies per-bell relay duration (`getBellDuration(bellIndex)`) used when firing a note. | +| `OutputManager` | Hardware abstraction. `fireOutputsBatchForDuration()` fires one or more relays simultaneously; `getPhysicalOutput()` maps logical bell index to physical pin; `emergencyShutdown()` de-energizes everything. | +| `Telemetry` | `recordBellStrike(bellIndex)` is called on every activation. `getBellLoad()` and `isOverloaded()` are queried after each full melody loop to detect overload conditions. | +| `CommunicationRouter` (optional) | `sendBellOverloadNotification()` is called when load thresholds are exceeded. | +| FreeRTOS | Task, critical section (`portMUX_TYPE`), and `vTaskDelay` APIs. | +| `esp_timer` | `esp_timer_get_time()` provides the microsecond timestamp used by `preciseDelay()` and performance tracking. | + +--- + +## Gotchas / Notes + +**Thread safety model.** Engine state (`_engineRunning`, `_emergencyStop`, `_melodyDataReady`) uses `std::atomic` — safe to read/write from any task. Melody step data (`_melodySteps`) is guarded by a `portMUX_TYPE` spinlock via `portENTER_CRITICAL` / `portEXIT_CRITICAL`. The engine makes a local copy of `_melodySteps` at the start of each playback pass, so late calls to `setMelodyData()` do not affect an in-progress play. + +**Player state is read without locks.** `playbackLoop()` reads `_player.isPlaying`, `_player.hardStop`, `_player.isPaused`, and `_player.speed` directly as plain public members. These are written only from Core 0 tasks; the implicit memory ordering from `atomic` flag checks provides adequate coordination in practice, but this is a weak coupling point. + +**Timing strategy.** `preciseDelay(us)` uses `vTaskDelay` for the bulk of a delay (leaving a 500 µs margin) and then busy-waits for the remainder. This means Core 1 will spin-wait for up to 500 µs per note step. At typical bell speeds (≥ 100 ms per beat) the busy-wait fraction is negligible, but it will starve any other Core 1 work during that window. + +**Core 1 is dedicated.** The engine task is pinned to Core 1 at priority 6. No other application task should be pinned to Core 1 at equal or higher priority, or timing jitter will increase. + +**Stack size.** The engine task allocates 12 KB. The `activateNote()` path allocates two `std::vector` objects and a fixed 16-element `bool` array on the stack per note step; this is the dominant stack consumer. + +**`notifyBellsFired()` has been removed.** The per-bell ding notification (previously sent to WebSocket clients only) was unstable under load and had no consumers. The function and its call site have been deleted. Bell activity is visible to external systems via telemetry strike counts and health monitor alerts only. + +**`_precisionTimer` is unused.** The `esp_timer_handle_t _precisionTimer` field is allocated but never started. It is vestigial from an earlier design iteration. + +**Overload thresholds are hardcoded.** `checkAndNotifyOverloads()` uses fixed values of 54 (critical, ~90% of 60 strikes/min) and 36 (warning, ~60%) rather than reading per-bell maximums from config. This should be parameterized if bell load limits become configurable. + +**Emergency stop in destructor.** `~BellEngine()` calls `emergencyShutdown()`, which in turn calls `OutputManager::emergencyShutdown()`. If `OutputManager` has already been destroyed before `BellEngine`, this will be a use-after-free. Ensure destruction order in `main.cpp` is consistent with construction order (BellEngine before OutputManager). diff --git a/src/ClientManager/README.md b/src/ClientManager/README.md new file mode 100644 index 0000000..27e0d21 --- /dev/null +++ b/src/ClientManager/README.md @@ -0,0 +1,89 @@ +# ClientManager + +## Summary + +`ClientManager` tracks all active WebSocket clients and their assigned device roles. It exists because the Vesper WebSocket API distinguishes between **master** clients (primary control apps) and **secondary** clients (auxiliary devices), and different subsystems need to send targeted responses rather than indiscriminate broadcasts. The class owns the client registry and exposes send primitives that `WebSocketDriver` delegates to; it does not interact with the network stack directly. + +--- + +## Public API + +### Client Lifecycle + +| Method | Description | +|---|---| +| `addClient(client, deviceType)` | Registers a new WebSocket client, defaulting to `UNKNOWN` type until identified. | +| `removeClient(clientId)` | Erases a client from the registry by its WebSocket ID. | +| `updateClientType(clientId, deviceType)` | Promotes a client from `UNKNOWN` to `MASTER` or `SECONDARY` after the `system.identify` handshake. | +| `updateClientLastSeen(clientId)` | Stamps the client's `lastSeen` field with the current `millis()`. Called on every received message and every outbound send. | +| `cleanupDisconnectedClients()` | Iterates the registry and removes entries whose underlying `AsyncWebSocketClient` is no longer in `WS_CONNECTED` state. | + +### Client Queries + +| Method | Description | +|---|---| +| `hasClients()` | Returns `true` if the registry is non-empty. | +| `getClientCount()` | Returns the number of entries currently in the registry. | +| `isClientConnected(clientId)` | Returns `true` if the client is registered and its socket reports `WS_CONNECTED`. | +| `getClientType(clientId)` | Returns the `DeviceType` of the client, or `UNKNOWN` if not found. | +| `getClientInfo(clientId)` | Returns a raw pointer to the `ClientInfo` struct, or `nullptr` if not found. | +| `getClientListJson()` | Serializes the current client registry to a JSON string (`{"clients":[...]}`). | + +### Messaging + +| Method | Description | +|---|---| +| `sendToClient(clientId, message)` | Sends a text message to a single client; returns `false` if the client is absent or disconnected. | +| `sendToMasterClients(message)` | Sends to all clients whose type is `MASTER`. | +| `sendToSecondaryClients(message)` | Sends to all clients whose type is `SECONDARY`. | +| `broadcastToAll(message)` | Sends to every client that passes the `isValidClient` check, regardless of type. | + +--- + +## Initialization + +`ClientManager` has no `begin()` method and no hardware dependencies. It is constructed at global scope inside `CommunicationRouter` (which owns a `ClientManager` member). `CommunicationRouter` passes the instance by reference into `WebSocketDriver` and `SystemHandler` at construction time. + +The relevant initialization chain in `main.cpp`: + +``` +CommunicationRouter communication(...); // constructs ClientManager internally +communication.begin(); // constructs WebSocketDriver and SystemHandler, + // both receive ClientManager& at this point +``` + +No explicit ordering constraint beyond `CommunicationRouter::begin()` being called after the `AsyncWebServer` and `AsyncWebSocket` objects exist. + +--- + +## Dependencies + +| Dependency | Role | +|---|---| +| `ESPAsyncWebServer` (`AsyncWebSocket`, `AsyncWebSocketClient`) | Provides the socket handle and connection status via `client->status()`. | +| `ArduinoJson` | Used only in `getClientListJson()` to serialize the registry. | +| `Logging` | All lifecycle events and send results are logged at `INFO` or `DEBUG` level. | + +`ClientManager` has no dependency on `ConfigManager`, `MQTT`, `SD`, or any hardware peripheral. + +--- + +## Gotchas / Notes + +**No FreeRTOS task.** `ClientManager` is purely synchronous. All methods execute in the caller's context. `WebSocketDriver` event callbacks fire in the `AsyncTCP` task (Core 0); the `SystemHandler` `system.identify` handler runs in whatever task dispatches `CommandBus`. If both paths mutate `_clients` concurrently there is a potential race on the `std::map`. In practice, the async event task and the command dispatch path currently share Core 0, reducing (but not eliminating) the risk. There is no mutex guarding `_clients`. + +**`isValidClient` is the source of truth for liveness.** The `isConnected` flag inside `ClientInfo` is set to `false` only during `cleanupDisconnectedClients()` and is otherwise not authoritative — actual connectivity is determined by `client->status() == WS_CONNECTED`. Do not rely on `ClientInfo::isConnected` alone. + +**`cleanupDisconnectedClients()` must be called externally.** The class does not self-clean. `WebSocketDriver::onDisconnect()` calls it after every disconnect event. The `main.cpp` loop also calls `ws.cleanupClients()` every 2 seconds at the `AsyncWebSocket` level, which is a separate mechanism. + +**Client type identification requires a handshake.** Clients connect as `UNKNOWN`. The app must send a `system.identify` command to be promoted: + +```json +{ "v": 2, "cmd": "system.identify", "contents": { "device_type": "master" } } +``` + +`SystemHandler` calls `updateClientType()` upon receiving this command. Until then, `sendToMasterClients` and `sendToSecondaryClients` will not reach the client. + +**Maximum client capacity is not enforced.** The header comment mentions "up to 5 total devices" but there is no enforcement in the code. The `std::map` will grow without bound if clients connect without disconnecting. + +**`getClientListJson()` uses a fixed `StaticJsonDocument<512>`.** With the current 5-client design intent this is sufficient, but it will silently truncate if a large number of clients are present. diff --git a/src/Communication/CommandBus/README.md b/src/Communication/CommandBus/README.md new file mode 100644 index 0000000..bb2fbff --- /dev/null +++ b/src/Communication/CommandBus/README.md @@ -0,0 +1,112 @@ +# CommandBus + +## Summary + +The CommandBus is the dispatch core of the communication layer. It owns a registry of `ICommandHandler` instances keyed by command name, and a list of `ITransport` instances that can receive broadcasts. When a transport receives a message, it parses it into a `CommandEnvelope` and calls `CommandBus::dispatch()`, which does an O(1) map lookup to find the right handler, calls `execute()`, then calls the envelope's reply lambda exactly once with the result. Unsolicited events (bell strikes, telemetry, status changes) are pushed out to all transports via `broadcast()`. The bus has no knowledge of which protocol a message arrived on — that concern lives entirely in the transport's reply lambda. + +This directory also contains four supporting types used everywhere in the communication layer: `CommandEnvelope`, `CommandResult`, `ICommandHandler`, and `LegacyAdapter`. + +--- + +## Public API — CommandBus + +| Method | Description | +|--------|-------------| +| `void registerHandler(std::unique_ptr handler)` | Takes ownership of a handler; maps every command name returned by `handler->commands()` to this instance. Duplicate registrations log a warning and the later handler wins. | +| `void addTransport(ITransport* transport)` | Registers a non-owning transport pointer for broadcast fan-out. | +| `void dispatch(CommandEnvelope& envelope)` | Looks up the handler for `envelope.command`, calls `execute()`, and fires `envelope.reply()` with the result. If no handler is found, replies with an error. Automatically translates v1 envelopes before lookup. | +| `void broadcast(const CommandResult& result)` | Serialises `result` to JSON once, then calls `broadcast()` on every registered transport. | + +--- + +## Supporting Types + +### CommandEnvelope + +Universal message wrapper produced by each transport before calling `dispatch()`. The transport injects the reply lambda so the bus and handlers never need to know which wire the response goes back on. + +| Field | Type | Description | +|-------|------|-------------| +| `version` | `uint8_t` | Protocol version: `2` = v2 (default), `1` = legacy | +| `transport` | `Transport` enum | `MQTT`, `WEBSOCKET`, `HTTP`, or `UART` | +| `clientId` | `uint32_t` | WebSocket client ID; `0` for transports without per-client identity | +| `command` | `String` | Flat command name, e.g. `"relay.set_durations"`, `"ping"` | +| `contents` | `JsonDocument` | The `"contents"` object from the raw JSON message | +| `reply` | `std::function` | Injected by the transport; called exactly once by the bus after dispatch | + +**Wire format (v2):** +```json +{ "v": 2, "cmd": "namespace.command", "contents": { ... } } +``` + +--- + +### CommandResult + +Standardised return value from every `ICommandHandler::execute()` call. Use the static factory methods. + +| Method | Description | +|--------|-------------| +| `static CommandResult ok(type, msg)` | Success with optional human-readable message | +| `static CommandResult ok(type, JsonDocument)` | Success with structured JSON data payload | +| `static CommandResult err(type, msg)` | Error with required message | +| `static CommandResult info(type, msg)` | Unsolicited informational event (used for broadcasts) | +| `bool isOk() const` | Returns true if status is `SUCCESS` | +| `bool isErr() const` | Returns true if status is `ERROR` | + +Serialised over the wire as: +```json +{ "status": "SUCCESS|ERROR|INFO", "type": "command_name", "message": "...", "data": { ... } } +``` +`message` is omitted when empty; `data` is omitted when `hasData` is false. + +--- + +### ICommandHandler + +Interface that all domain handlers implement. + +| Method | Description | +|--------|-------------| +| `virtual std::vector commands() const = 0` | Returns all command names this handler owns. The bus registers all of them at startup. | +| `virtual CommandResult execute(const CommandEnvelope& envelope) = 0` | Executes the command and returns a result. Must not call `envelope.reply()` directly — the bus owns that. Must not throw. | + +--- + +### LegacyAdapter + +`translateLegacyEnvelope(CommandEnvelope& envelope)` — translates a v1 envelope into its v2 equivalent in place. Called automatically by `CommandBus::dispatch()` when `envelope.version == 1`. Not part of the public API for new code. + +**Translation rules:** +1. Simple 1-to-1 commands (`ping`, `identify`, `playback`) are passed through unchanged. +2. Commands with an `"action"` field in `contents` are mapped using a lookup table (e.g. `{ "cmd": "relay_setup", "contents": { "action": "set_timings" } }` → `relay.set_durations`). +3. Two boolean-split special cases: `clock_setup/set_enabled` → `clock.enable` or `clock.disable`; `system/set_mqtt_enabled` → `mqtt.enable` or `mqtt.disable`. +4. Unknown v1 commands are left unchanged so the bus returns its standard "Unknown command" error. + +To remove legacy support entirely: delete this file and the single `translateLegacyEnvelope()` call in `CommandBus::dispatch()`. + +--- + +## Initialization + +The `CommandBus` is a plain value member of `CommunicationRouter` — no explicit initialization required. Handlers are registered via `registerHandlers()` inside `CommunicationRouter::begin()`, which is called from `main.cpp` after all late-bound references have been set via `setXxxReference()`. + +Transports are added to the bus with `addTransport()` inside `CommunicationRouter::begin()`, after each transport's own `begin()` has been called. + +--- + +## Dependencies + +- `ArduinoJson` — for `CommandEnvelope::contents` and `CommandResult::data` +- `Logging` — for registration warnings and dispatch debug logs +- `ICommandHandler` / `ITransport` interfaces (headers in `Communication/Handlers/` and `Communication/Transport/`) + +--- + +## Gotchas / Notes + +- **`std::map` instead of `std::unordered_map`**: Arduino's `String` type has no `std::hash` specialisation, so a tree-map is used. Lookup is O(log n) in practice, though with ~30 commands in the registry this is negligible. +- **Duplicate registrations**: If two handlers claim the same command name (e.g. during a refactor), the last one registered wins and a `LOG_WARNING` is emitted. Check serial output at boot to catch this. +- **`envelope.reply` is called exactly once**: Handlers must return a `CommandResult` and must not call `envelope.reply()` themselves. If a handler returns without going through the bus (e.g. throws), the client receives no response. Handlers must not throw. +- **Broadcast vs reply**: `dispatch()` calls `envelope.reply()` — response goes back to the originating transport/client only. `broadcast()` sends to all transports — used for unsolicited events. These are distinct paths. +- **Thread safety**: `CommandBus` has no internal locking. All dispatch calls happen on the main Arduino loop / AsyncWebServer callback thread. Do not call `dispatch()` or `broadcast()` from ISRs or FreeRTOS tasks that run concurrently with the loop. diff --git a/src/Communication/CommunicationRouter/README.md b/src/Communication/CommunicationRouter/README.md new file mode 100644 index 0000000..21a2f79 --- /dev/null +++ b/src/Communication/CommunicationRouter/README.md @@ -0,0 +1,122 @@ +# CommunicationRouter + +## Summary + +`CommunicationRouter` is the top-level coordinator for all inbound and outbound communication. It owns the `CommandBus`, all five transport objects (`MQTTTransport`, `WebSocketTransport`, `HTTPTransport`, `UARTTransport`, `WebServerTransport`), and the three underlying protocol driver objects (`MQTTDriver`, `WebSocketDriver`, `UARTDriver`). It also owns `ClientManager`. On `begin()`, it initialises all transports, registers them with the bus, and calls `registerHandlers()` to bind all ten domain handlers to the bus. After that, the router largely gets out of the way: incoming messages are routed internally by the bus, and outbound unsolicited events (status, telemetry, bell strikes) are pushed through the broadcast helpers exposed on this class. All other subsystems that need to send data call into the router rather than touching transports directly. + +--- + +## Public API + +### Lifecycle + +| Method | Description | +|--------|-------------| +| `CommunicationRouter(ConfigManager&, OTAManager&, Networking&, AsyncWebServer&, AsyncWebSocket&, AsyncUDP&)` | Constructor. Builds all owned objects; does not start any communication. | +| `void begin()` | Initialises all transports, registers them with the bus, calls `registerHandlers()`. Must be called after all `setXxxReference()` calls. | +| `void loop()` | Forwards to `UARTTransport::loop()` to poll UART input. Call from `main.cpp` loop. | + +### Late-bound references (call before `begin()`) + +| Method | Description | +|--------|-------------| +| `void setPlayerReference(Player*)` | Required for PlaybackHandler, RelayHandler, FirmwareHandler, SystemHandler. | +| `void setFileManagerReference(FileManager*)` | Required for FileHandler; also wires the SD log channel into `Logging`. | +| `void setTimeKeeperReference(Timekeeper*)` | Required for ClockHandler, SystemHandler. | +| `void setFirmwareValidatorReference(FirmwareValidator*)` | Required for FirmwareHandler. | +| `void setTelemetryReference(Telemetry*)` | Required for TelemetryHandler, SystemHandler. | +| `void setHealthMonitorReference(HealthMonitor*)` | Required for SystemHandler (`system.health`). | +| `void setOutputManagerReference(OutputManager*)` | Required for RelayHandler. | + +### Status + +| Method | Description | +|--------|-------------| +| `bool isMqttConnected() const` | True if `MQTTDriver` has an active broker connection. | +| `bool hasActiveWebSocketClients() const` | True if at least one WebSocket client is connected. | +| `size_t getWebSocketClientCount() const` | Number of currently connected WebSocket clients. | +| `bool isHealthy() const` | True if network is up and at least one of MQTT or WebSocket is active. | + +### Broadcast helpers (called by other subsystems) + +| Method | Description | +|--------|-------------| +| `void broadcastStatus(const String& msg)` | Sends raw string to MQTT data topic and all WebSocket clients. | +| `void broadcastStatus(const JsonDocument& json)` | Serialises JSON then calls the string overload. | +| `void broadcastToMasterClients(const String& msg)` | WebSocket only — master-classified clients. | +| `void broadcastToSecondaryClients(const String& msg)` | WebSocket only — secondary-classified clients. | +| `void broadcastToAllWebSocketClients(const String& msg)` | All WebSocket clients. | +| `void broadcastToAllWebSocketClients(const JsonDocument& msg)` | Serialises then sends to all WebSocket clients. | +| `void publishToMqtt(const String& data)` | Publishes to the device data topic. No-op if MQTT is not connected. | +| `void sendBellOverloadNotification(const std::vector& bells, const std::vector& loads, const String& severity)` | Builds and broadcasts a structured `bell_overload` INFO event. | +| `void publishAlert(const String& subsystem, const String& newState, const String& message)` | Publishes a subsystem state-change event to `vesper/{uid}/status/alerts` (QoS 1). `newState` is one of `"WARNING"`, `"CRITICAL"`, `"FAILED"`, or `"CLEARED"`. Called automatically by the HealthMonitor alert callback registered in `begin()`. No-op if MQTT is not connected. | +| `void publishInfo(const String& type, const JsonDocument& payload)` | Publishes a general device state event to `vesper/{uid}/status/info` (QoS 0). No-op if MQTT is not connected. | + +### Network callbacks (called by Networking) + +| Method | Description | +|--------|-------------| +| `void onNetworkConnected()` | Forwards to `MQTTTransport`, which triggers the MQTT connection stabilisation timer. | +| `void onNetworkDisconnected()` | Forwards to `MQTTTransport` to stop heartbeat and abort pending reconnects. | + +### Legacy accessors + +| Method | Description | +|--------|-------------| +| `MQTTDriver& getMQTTClient()` | Direct access to the MQTT driver; used by `Logging` to set up the MQTT log channel. | +| `UARTDriver& getUARTHandler()` | Direct access to the UART driver (currently not used outside the router). | + +### UDP Discovery + +| Method | Description | +|--------|-------------| +| `void setupUdpDiscovery()` | Starts listening on the configured discovery port. Replies to UDP `"discover"` packets with a JSON `discover_reply` payload containing IP, WebSocket URL, firmware version, and client count. | + +--- + +## Initialization + +In `main.cpp`, the router is constructed as a global alongside the other subsystems: + +```cpp +CommunicationRouter communication(configManager, otaManager, networking, server, ws, udp); +``` + +Before calling `begin()`, all late-bound references must be set: + +```cpp +communication.setPlayerReference(&player); +communication.setFileManagerReference(&fileManager); +communication.setTimeKeeperReference(&timekeeper); +communication.setFirmwareValidatorReference(&firmwareValidator); +communication.setTelemetryReference(&telemetry); +communication.setHealthMonitorReference(&healthMonitor); +communication.setOutputManagerReference(&outputManager); +communication.begin(); +``` + +If any required reference is null when `registerHandlers()` runs (inside `begin()`), the corresponding handler(s) are skipped and an `LOG_ERROR` is emitted. The bus still starts; commands for missing handlers return "Unknown command". + +`AsyncWebServer::begin()` is **not** called inside `CommunicationRouter::begin()`. It is started from the network-connected callback in `main.cpp` to avoid conflicting with WiFiManager's captive portal on port 80. + +--- + +## Dependencies + +- `ConfigManager` — MQTT config, network config, log levels, device UID +- `OTAManager` — passed to `FirmwareHandler` +- `Networking` — passed to `NetworkHandler`; used for health check and UDP discovery +- `AsyncWebServer` / `AsyncWebSocket` / `AsyncUDP` — passed to transports +- All domain handler dependencies: `Player`, `FileManager`, `Timekeeper`, `FirmwareValidator`, `Telemetry`, `HealthMonitor`, `OutputManager` +- Libraries: `ESPAsyncWebServer`, `ArduinoJson`, `AsyncUDP` + +--- + +## Gotchas / Notes + +- **Order matters**: All `setXxxReference()` calls must happen before `begin()`. `registerHandlers()` is called at the end of `begin()` and will silently omit handlers for any null reference. +- **`server.begin()` is deferred**: The `AsyncWebServer` is not started inside `begin()` — it is started in the `onNetworkConnected` callback in `main.cpp`. This prevents a port 80 conflict when WiFiManager's captive portal is active. +- **`loop()` must be called**: `UARTTransport` is the only transport that requires polling. `CommunicationRouter::loop()` delegates to it. All other transports are fully event-driven. +- **MQTT log suppression**: During `begin()`, the subsystem MQTT log levels for `"MQTTClient"` and `"CommRouter"` are explicitly suppressed to `NONE` and `WARNING` respectively to prevent feedback loops when MQTT is used as a log sink. +- **Broadcast vs CommandBus broadcast**: The `broadcastXxx()` helpers on this class send raw pre-serialised strings. `CommandBus::broadcast()` serialises a `CommandResult` and fans it out. They are separate paths; subsystems outside the communication layer use the router's helpers. +- **Handler skipping is silent to clients**: If a reference is null and a handler is not registered, the bus returns `{"status":"ERROR","type":"unknown","message":"Unknown command: ..."}`. There is no boot-time safeguard beyond the `LOG_ERROR` in `registerHandlers()`. diff --git a/src/Communication/Drivers/MQTTDriver/README.md b/src/Communication/Drivers/MQTTDriver/README.md new file mode 100644 index 0000000..fee274e --- /dev/null +++ b/src/Communication/Drivers/MQTTDriver/README.md @@ -0,0 +1,85 @@ +# MQTTDriver + +## Summary + +`MQTTDriver` is the low-level MQTT protocol driver. It wraps `AsyncMqttClient` and manages the full broker connection lifecycle: configuration, authentication, subscribe/publish, exponential backoff reconnection, 30-second heartbeat, and network-stabilisation delay. It is not aware of the `CommandBus` — that coupling lives in `MQTTTransport`. The driver uses three FreeRTOS software timers with one-shot tasks deferred off the Tmr Svc stack to avoid stack overflows in timer callbacks. + +Topics: +- Control (inbound): `vesper/{uid}/control` +- Data (outbound): `vesper/{uid}/data` +- Heartbeat (retained, QoS 1): `vesper/{uid}/status/heartbeat` +- Alerts (state-change events, QoS 1): `vesper/{uid}/status/alerts` +- Info (general state events, QoS 0): `vesper/{uid}/status/info` + +--- + +## Public API + +| Method | Description | +|--------|-------------| +| `MQTTDriver(ConfigManager& configManager, Networking& networking)` | Constructor. Creates the three FreeRTOS timers. Sets the global `_instance` pointer. | +| `void begin()` | Caches topic strings, registers AsyncMqttClient event handlers, configures broker host/port/credentials/keepalive. Does not connect. | +| `void connect()` | Calls `AsyncMqttClient::connect()`. No-op if MQTT is disabled in config or already connected. | +| `void disconnect()` | Disconnects cleanly. | +| `uint16_t publish(const String& topic, const String& payload, int qos, bool retain)` | Publishes to `topic`. If `topic` does not start with `"vesper/"`, it is treated as relative and the full data topic is used instead. Returns packet ID or 0 on failure. | +| `uint16_t publishDirect(const String& fullTopic, const String& payload, int qos, bool retain)` | Publishes to an absolute, fully-qualified topic — no prefix is applied. Used by `CommunicationRouter` to target `status/alerts` and `status/info` topics directly. | +| `const String& getAlertsTopic() const` | Returns the cached `vesper/{uid}/status/alerts` topic string. Available after `begin()`. | +| `const String& getInfoTopic() const` | Returns the cached `vesper/{uid}/status/info` topic string. Available after `begin()`. | +| `void setCallback(MessageCallback callback)` | Registers the message-received callback. Called by `MQTTTransport::begin()`. | +| `bool isConnected() const` | Returns the AsyncMqttClient connection state. | +| `void onNetworkConnected()` | Starts the 2-second network-stabilisation timer; connects after it fires. Resets `_reconnectAttempts`. | +| `void onNetworkDisconnected()` | Force-disconnects the client if connected. Reconnect logic waits for the next `onNetworkConnected()`. | + +--- + +## Initialization + +`MQTTTransport::begin()` sets the message callback on the driver, then calls `MQTTDriver::begin()`. The broker connection is not initiated here — it is triggered by `onNetworkConnected()` when the network becomes available. + +`MQTTDriver` is constructed inside `CommunicationRouter` as a member: +```cpp +MQTTDriver _mqttClient; // in CommunicationRouter +``` + +The constructor creates all three FreeRTOS timers. If timer creation fails (extremely low memory), the `nullptr` guards in each callback will prevent crashes but MQTT will not reconnect automatically. + +--- + +## Reconnect Behaviour + +| Attempts | Delay | +|----------|-------| +| 1–3 (quick retries) | 5 seconds each | +| 4 | 10 seconds | +| 5 | 20 seconds | +| 6 | 40 seconds | +| 7+ | Capped at 300 seconds (5 minutes) | + +Reconnect attempts are reset to 0 on a successful connection or a new `onNetworkConnected()` event. + +--- + +## Heartbeat + +Once connected, a heartbeat is published immediately and then every 30 seconds to `vesper/{uid}/status/heartbeat` with `retain = true`. Heartbeat payload includes `device_id`, `firmware_version`, `ip_address`, `gateway`, `uptime_ms`, and an uptime string. The heartbeat timer is stopped on disconnect and restarted on reconnect. + +--- + +## Dependencies + +- `AsyncMqttClient` — broker protocol +- `ConfigManager` — MQTT host, port, credentials, enabled flag, device UID +- `Networking` — `isConnected()` check before reconnect attempts; IP and gateway for heartbeat +- FreeRTOS — three `TimerHandle_t` timers, one `TaskHandle_t` for heartbeat task guard +- `Logging` + +--- + +## Gotchas / Notes + +- **Singleton pattern via `_instance`.** The class uses a static `_instance` pointer for routing timer callbacks back to the instance. Only one `MQTTDriver` should exist at a time. The constructor overwrites `_instance`, so creating two instances will break the first one's callbacks. +- **Timer callbacks defer to tasks.** Timer callbacks run in the FreeRTOS Timer Service task (Tmr Svc, default 2 KB stack). Any callback that calls `LOG_*` macros, `connect()`, or JSON serialisation would overflow this stack. All three callbacks (`mqttReconnectTimerCallback`, `networkStabilizationTimerCallback`, `heartbeatTimerCallback`) spawn a 3 KB task and return immediately. +- **Heartbeat task guard.** If the previous heartbeat task has not yet exited when the next timer fires, the new task is not spawned. This prevents task accumulation under slow broker connections. +- **Error logging is suppressed on publish failure.** `publish()` does not log an error when `_mqttClient.publish()` returns 0 (packet ID failure), because `publish()` is also called from the MQTT log channel and logging an error there would recurse infinitely. +- **Credentials from NVS.** The broker username and password are read from `ConfigManager`, which loads them from NVS at boot. The password is a 32-character HMAC-SHA256 hex digest derived from the device UID and `MQTT_SECRET` (compiled in via `-DMQTT_SECRET`). +- **`begin()` must be called before `connect()`.** `begin()` registers AsyncMqttClient event handlers and configures the server. Calling `connect()` before `begin()` will silently do nothing useful. diff --git a/src/Communication/Drivers/UARTDriver/README.md b/src/Communication/Drivers/UARTDriver/README.md new file mode 100644 index 0000000..31dac93 --- /dev/null +++ b/src/Communication/Drivers/UARTDriver/README.md @@ -0,0 +1,67 @@ +# UARTDriver + +## Summary + +`UARTDriver` is the low-level UART I/O driver for the slave device interface (LCD panel, button board). It operates on `Serial2` using newline-delimited JSON framing. Incoming bytes are accumulated in a 1 KB ring buffer; when a newline is received, the accumulated line is parsed as JSON and the registered callback is invoked. Outgoing messages are sent with an appended newline and a blocking `flush()`. The driver must be polled via `loop()` — it does not run in its own task. + +--- + +## Public API + +| Method | Description | +|--------|-------------| +| `UARTDriver(uint8_t txPin, uint8_t rxPin, uint32_t baudRate)` | Constructor. Defaults: TX=GPIO 12, RX=GPIO 13, 115200 baud. Uses `Serial2`. | +| `void begin()` | Initialises `Serial2` with the configured pins and baud rate; flushes any garbage in the RX buffer. | +| `void loop()` | Reads all available bytes from `Serial2` into the line buffer. Calls `processLine()` when `'\n'` or `'\r'` is detected. **Must be called from the main loop or a polling task.** | +| `void setCallback(MessageCallback callback)` | Registers the callback invoked with a parsed `JsonDocument&` for each valid message. | +| `void send(const String& response)` | Sends `response` followed by `'\n'` and calls `flush()`. | +| `bool isReady() const` | Returns `true` after `begin()` has been called successfully. | +| `uint32_t getMessageCount() const` | Number of successfully parsed messages since boot. | +| `uint32_t getErrorCount() const` | Number of JSON parse errors or buffer overflows since boot. | + +--- + +## Initialization + +`UARTTransport::begin()` sets the message callback, then calls `UARTDriver::begin()`. The driver is a member of `CommunicationRouter` via `UARTTransport`. + +--- + +## Wire Protocol + +- **Physical**: Serial2, TX GPIO 12, RX GPIO 13, 115200 8N1 +- **Framing**: newline-delimited (`'\n'` or `'\r'`) +- **Encoding**: JSON, max 1023 bytes per message (1024-byte buffer minus null terminator) + +Example message from slave: +``` +{"v":2,"cmd":"playback","contents":{"action":"stop"}}\n +``` + +Example response to slave: +``` +{"status":"SUCCESS","type":"playback","message":"Playback command executed"}\n +``` + +JSON parse errors generate an automatic error response: +``` +{"status":"ERROR","type":"parse_error","payload":""}\n +``` + +--- + +## Dependencies + +- `HardwareSerial` (Arduino) — `Serial2` +- `ArduinoJson` — JSON parsing (`StaticJsonDocument<1024>`) +- `Logging` + +--- + +## Gotchas / Notes + +- **`loop()` must be called.** UART input is not interrupt-driven at the application level. Without regular `loop()` calls, the Serial2 hardware FIFO can overflow. +- **Buffer overflow drops the entire message.** When `_bufferIndex` reaches 1023 without a newline, the buffer is reset and `_errorCount` is incremented. The slave receives no error response in this case. +- **`send()` is blocking.** `Serial.flush()` blocks until the TX hardware buffer drains. At 115200 baud this is approximately 1 byte per 87 µs. A 100-byte response takes ~8.7 ms. This can affect main loop timing if the slave is slow to consume data. +- **`JsonDocument&` is passed by reference** to the callback. The document lives on the stack inside `processLine()` and is valid only for the duration of the callback. Do not store a reference to it. +- **No v1 legacy handling at this level.** The driver passes raw JSON to the callback. Legacy translation (if `"v": 1`) is handled upstream by `CommandBus::dispatch()`. diff --git a/src/Communication/Drivers/WebSocketDriver/README.md b/src/Communication/Drivers/WebSocketDriver/README.md new file mode 100644 index 0000000..ee3bec5 --- /dev/null +++ b/src/Communication/Drivers/WebSocketDriver/README.md @@ -0,0 +1,51 @@ +# WebSocketDriver + +## Summary + +`WebSocketDriver` is the low-level WebSocket protocol driver. It wraps `AsyncWebSocket` and delegates client lifecycle management (add, remove, type classification, targeted sends, broadcast) to `ClientManager`. When a complete text frame is received, it parses the JSON payload and invokes the registered callback with the client ID and parsed document. `WebSocketTransport` sits on top of this driver and connects it to the `CommandBus`. The driver also sends an unsolicited welcome message to each new client on connect. + +--- + +## Public API + +| Method | Description | +|--------|-------------| +| `WebSocketDriver(AsyncWebSocket& webSocket, ClientManager& clientManager)` | Constructor. Sets the global `_instance` pointer. | +| `void begin()` | Registers the static `onEvent` callback with `AsyncWebSocket`. Does not add the handler to `AsyncWebServer` — that is done by `CommunicationRouter::begin()` via `_server.addHandler(&_webSocket)`. | +| `void setCallback(MessageCallback callback)` | Registers the message-received callback. Called by `WebSocketTransport::begin()`. Signature: `void(uint32_t clientId, const JsonDocument& message)`. | +| `void sendToClient(uint32_t clientId, const String& message)` | Sends a message to a specific connected client. Delegates to `ClientManager::sendToClient()`. | +| `void broadcastToAll(const String& message)` | Sends to all connected clients via `ClientManager::broadcastToAll()`. | +| `void broadcastToMaster(const String& message)` | Sends to clients classified as `MASTER` only. | +| `void broadcastToSecondary(const String& message)` | Sends to clients classified as `SECONDARY` only. | +| `bool hasClients() const` | True if at least one client is connected. | +| `size_t getClientCount() const` | Number of currently connected clients. | + +--- + +## Initialization + +`CommunicationRouter::begin()`: +1. Calls `_server.addHandler(&_webSocket)` — attaches the WebSocket handler to the HTTP server. +2. Calls `_wsTransport.begin()` — which calls `WebSocketDriver::begin()` to register the event callback. + +The `AsyncWebServer` is started later by `main.cpp` in the network-connected callback. + +--- + +## Dependencies + +- `AsyncWebSocket` (ESPAsyncWebServer) — WebSocket protocol layer +- `ClientManager` — client registry, type tracking, targeted/broadcast sends +- `ResponseBuilder` — used for the welcome message on connect and parse error responses +- `ArduinoJson`, `Logging` + +--- + +## Gotchas / Notes + +- **Singleton pattern via `_instance`.** `AsyncWebSocket::onEvent` is a static C-style callback. The driver routes it through `WebSocketDriver::_instance`. Only one instance should ever be created. +- **Only complete single-frame text messages are processed.** The `onData` handler checks `info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT`. Fragmented messages and binary frames are dropped with a warning. +- **Per-message heap allocation.** Each incoming message allocates a `char*` buffer via `malloc(len + 1)`. If allocation fails, the client receives a `"memory_error"` response. This is the only dynamic allocation path in the driver. +- **JSON parse limit: 2 KB (`StaticJsonDocument<2048>`).** Messages larger than this will fail to parse. The client receives a `"parse_error"` response. +- **Client cleanup is external.** The driver calls `_clientManager.cleanupDisconnectedClients()` on each disconnect event, but dead ghost connections (network drop without close frame) are only evicted when `ws.cleanupClients()` is called from `main.cpp` every 2 seconds. +- **Welcome message uses `ResponseBuilder`.** The welcome message on connect (`"type": "connection"`) is built with the legacy `ResponseBuilder::success()` path. New code should use `CommandResult` factory methods. diff --git a/src/Communication/Handlers/README.md b/src/Communication/Handlers/README.md new file mode 100644 index 0000000..554ca03 --- /dev/null +++ b/src/Communication/Handlers/README.md @@ -0,0 +1,194 @@ +# Handlers + +## Summary + +Domain handlers implement the `ICommandHandler` interface and contain the actual logic for each command namespace. Each handler is constructed with references to the subsystems it needs, registered onto the `CommandBus` via `CommunicationRouter::registerHandlers()`, and called synchronously by the bus when a matching command arrives. Handlers never call `envelope.reply()` directly — they return a `CommandResult` and the bus handles the reply. Handlers must not throw. + +See [ICommandHandler.hpp](ICommandHandler.hpp) for the interface definition. + +--- + +## Handler Registry + +| Handler | Commands owned | Dependencies | +|---------|---------------|--------------| +| `PlaybackHandler` | `playback` | `Player` | +| `RelayHandler` | `relay.set_durations`, `relay.set_outputs`, `relay.get_config`, `relay.test_output` | `ConfigManager`, `OutputManager`, `Player` | +| `ClockHandler` | `clock.set_outputs`, `clock.set_timings`, `clock.set_alerts`, `clock.set_backlight`, `clock.set_silence`, `clock.set_time`, `clock.set_face`, `clock.set_timezone`, `clock.get_timezone`, `clock.sync_ntp`, `clock.enable`, `clock.disable`, `clock.pause`, `clock.resume`, `clock.get_face`, `clock.get_config` | `ConfigManager`, `Timekeeper` | +| `SystemHandler` | `ping`, `identify`, `system.status`, `system.get_time`, `system.get_settings`, `system.get_device_info`, `system.health`, `system.factory_reset`, `system.restart` | `ConfigManager`, `Player`, `Telemetry`, `HealthMonitor`, `Timekeeper`, `ClientManager` | +| `FirmwareHandler` | `firmware.status`, `firmware.commit`, `firmware.rollback`, `ota.update`, `ota.custom` | `FirmwareValidator`, `OTAManager`, `Player` | +| `NetworkHandler` | `network.info`, `network.status`, `network.set_config` | `ConfigManager`, `Networking` | +| `FileHandler` | `files.list`, `files.list_builtin`, `files.download`, `files.delete` | `FileManager` | +| `LoggingHandler` | `log.set_serial`, `log.set_sd`, `log.set_mqtt` | `ConfigManager` | +| `TelemetryHandler` | `telemetry.get_strikes`, `telemetry.reset_strikes`, `telemetry.get_loads` | `Telemetry` | +| `MQTTHandler` | `mqtt.enable`, `mqtt.disable` | `ConfigManager`, `MQTTDriver` | + +--- + +## PlaybackHandler + +Forwards the entire `contents` object to `Player::command()` as a `JsonVariant`. The Player interprets the contents internally (action, melody name, bell selection, etc.). + +**Commands:** + +| Command | Contents | Description | +|---------|----------|-------------| +| `playback` | Player-specific JSON | Forward to `Player::command()`. Returns error if the player rejects the command. | + +--- + +## RelayHandler + +Manages relay output configuration (durations and output pin mappings). Persists changes to SD via `ConfigManager`. Test output is blocked while the player is active. + +**Commands:** + +| Command | Required contents | Description | +|---------|------------------|-------------| +| `relay.set_durations` | `{ "bells": { "0": 500, ... } }` | Update strike durations (ms) for up to 16 bells. Saves to SD. | +| `relay.set_outputs` | `{ "bells": { "0": 2, ... } }` | Update physical output pin mapping for each bell. Saves to SD. | +| `relay.get_config` | — | Returns all 16 bell durations and output assignments. | +| `relay.test_output` | `{ "output": 0–31, "duration_ms": 1–5000 }` | Fires a single output. Blocked if player is not stopped. | + +--- + +## ClockHandler + +Full control over the Timekeeper clock subsystem and its persisted configuration. Most commands save to SD via `ConfigManager`. + +**Commands:** + +| Command | Key contents fields | Description | +|---------|---------------------|-------------| +| `clock.set_outputs` | Clock output config object | Set C1/C2 output pins. Saves clock config. | +| `clock.set_timings` | `pulse_duration`, `pause_duration` | Set impulse clock pulse and pause durations (ms). | +| `clock.set_alerts` | Alert config object | Set hourly/half/quarter bell alert settings. | +| `clock.set_backlight` | Backlight config object | Configure backlight output and schedule. | +| `clock.set_silence` | Silence config object | Configure daytime/nighttime silence windows. | +| `clock.set_time` | `timestamp` (unix), optional `timezone_offset`, `dst_offset` | Set RTC time. Also updates timezone config if offsets provided. | +| `clock.set_face` | `hour` (0–23), `minute` (0–59) | Set the physical clock face position. Saves clock state. | +| `clock.set_timezone` | `gmt_offset_sec`, optional `dst_offset_sec` | Persist timezone config. Does not update RTC. | +| `clock.get_timezone` | — | Returns `gmt_offset_sec`, `dst_offset_sec`, `ntp_server`. | +| `clock.sync_ntp` | — | Triggers an immediate NTP sync via `Timekeeper::syncTimeWithNTP()`. | +| `clock.enable` | — | Enables clock operation. Saves to SD. | +| `clock.disable` | — | Disables clock operation. Saves to SD. | +| `clock.pause` | — | Pauses clock motor updates (in-memory only, not saved). | +| `clock.resume` | — | Resumes clock motor updates. | +| `clock.get_face` | — | Returns `clock_hour`, `clock_minute`, `last_sync_time`, `next_output_is_c1`. | +| `clock.get_config` | — | Returns the full `ClockConfig` struct as JSON. | + +--- + +## SystemHandler + +General device management. `identify` is WebSocket-only. `system.restart` defers the actual reboot to a FreeRTOS task so the reply reaches the client first. + +**Commands:** + +| Command | Key contents | Description | +|---------|-------------|-------------| +| `ping` | — | Returns `{ "status": "SUCCESS", "type": "pong" }`. | +| `identify` | `{ "device_type": "master"\|"secondary" }` | WebSocket only. Classifies the calling client in `ClientManager`. | +| `system.status` | — | Player status, time elapsed, projected run time, 16 strike counters. | +| `system.get_time` | — | Local and UTC timestamps, broken-down time fields, `rtc_available`. | +| `system.get_settings` | — | Full device settings as JSON (from `ConfigManager::getAllSettingsAsJson()`). | +| `system.get_device_info` | — | UID, hw type, hw version, fw version, uptime, free heap. | +| `system.health` | — | Triggers `HealthMonitor::performFullHealthCheck()`; returns per-subsystem status. | +| `system.factory_reset` | — | Resets all config to defaults. **Does not reboot automatically.** | +| `system.restart` | — | Schedules `ESP.restart()` 2 seconds after reply. | + +--- + +## FirmwareHandler + +OTA update management and firmware validation control. OTA commands are blocked during active playback. + +**Commands:** + +| Command | Key contents | Description | +|---------|-------------|-------------| +| `firmware.status` | — | Returns validation state, version info, `can_commit`, `can_rollback`. | +| `firmware.commit` | — | Manually commits the firmware under test. Errors if not in testing mode. | +| `firmware.rollback` | — | Rolls back to previous firmware and reboots. | +| `ota.update` | optional `{ "channel": "stable" }` | Triggers OTA update from configured channel. Blocked if player is active. | +| `ota.custom` | `{ "firmware_url": "...", "checksum": "...", "file_size": N, "version": N }` | OTA from a custom URL. `firmware_url` is required. | + +--- + +## NetworkHandler + +Network status queries and configuration. AP mode toggle via `network.set_config` with `permanent_ap_mode` is the primary use case (also called by `WebServerTransport`). Full static IP configuration is supported. + +**Commands:** + +| Command | Key contents | Description | +|---------|-------------|-------------| +| `network.info` | — | Returns `ip`, `gateway`, `dns` from `WiFi` directly. | +| `network.status` | — | Returns `connected`, `ip`, `ap_mode`, `rssi`, `state`, `type`. | +| `network.set_config` | `permanent_ap_mode` bool, or `hostname`/`useStaticIP`/`ip`/`gateway`/`subnet`/`dns1`/`dns2` | Saves network config. Restart required to apply. AP mode toggle is handled independently. | + +--- + +## FileHandler + +SD card melody file management. All operations require a healthy SD card via `FileManager`. + +**Commands:** + +| Command | Key contents | Description | +|---------|-------------|-------------| +| `files.list` | — | Lists all `.json` files in `/melodies`. Returns `{ "files": [...] }`. | +| `files.list_builtin` | — | Returns the built-in melody list from `BuiltInMelodies`. | +| `files.download` | Melody JSON object | Downloads / saves a melody to SD via `FileManager::addMelody()`. Uses `melodys_uid` or `name` for logging. | +| `files.delete` | `{ "name": "filename.json" }` | Deletes `/melodies/{name}`. | + +--- + +## LoggingHandler + +Runtime log level control. Changes take effect immediately and are persisted to SD via `ConfigManager::saveGeneralConfig()`. + +**Commands:** + +| Command | Contents | Description | +|---------|----------|-------------| +| `log.set_serial` | `{ "level": 0–5 }` | Sets serial log level. 0=NONE, 5=VERBOSE. | +| `log.set_sd` | `{ "level": 0–5 }` | Sets SD card log level. | +| `log.set_mqtt` | `{ "level": 0–5 }` | Sets MQTT log level. | + +--- + +## TelemetryHandler + +Read-only access to bell strike counters and load measurements. Reset clears all 16 counters at once. + +**Commands:** + +| Command | Description | +|---------|-------------| +| `telemetry.get_strikes` | Returns strike counts for all 16 bells as `{ "strikes": { "0": N, ... } }`. | +| `telemetry.reset_strikes` | Resets all 16 strike counters to 0. | +| `telemetry.get_loads` | Returns current load values, `cooling_active` flag, and array of overloaded bell indices. | + +--- + +## MQTTHandler + +Enables or disables the MQTT connection at runtime. The state is saved to SD and the connection is immediately opened or closed. + +**Commands:** + +| Command | Description | +|---------|-------------| +| `mqtt.enable` | Enables MQTT in config, saves, calls `MQTTDriver::connect()`. | +| `mqtt.disable` | Disables MQTT in config, saves, calls `MQTTDriver::disconnect()`. | + +--- + +## General Notes + +- **All handlers are registered once** at boot in `CommunicationRouter::registerHandlers()`. Adding a new handler requires only adding a `registerHandler()` call there — the bus registration is automatic via `commands()`. +- **SD-writing commands can return partial success.** Several commands return a `CommandResult::err` with a message like `"Updated but failed to save to SD"`. The in-memory state is applied even if the SD save fails. +- **`system.factory_reset` does not reboot.** The caller must issue a separate `system.restart` to apply the reset. +- **`identify` enforces transport type.** It checks `envelope.transport == CommandEnvelope::Transport::WEBSOCKET` and returns an error for other transports. This is the only handler with transport-specific behaviour. +- **`system.restart` uses a deferred task.** `xTaskCreate` spawns a 1 KB task that waits 2 seconds then calls `ESP.restart()`. This ensures the `CommandResult::ok` reply reaches the client before the device reboots. diff --git a/src/Communication/ResponseBuilder/README.md b/src/Communication/ResponseBuilder/README.md new file mode 100644 index 0000000..2758c82 --- /dev/null +++ b/src/Communication/ResponseBuilder/README.md @@ -0,0 +1,87 @@ +# ResponseBuilder + +## Summary + +`ResponseBuilder` is a legacy utility class that serialises responses to JSON strings for direct transmission. It predates the `CommandResult` / `CommandBus` architecture and was the primary response-building mechanism before the Stage 4 comms refactor. Its role has shrunk significantly: new handler code uses `CommandResult` factory methods, and transports serialise `CommandResult` inline. `ResponseBuilder` is still used by `WebSocketDriver` (welcome message on connect, parse error responses) and by some older code paths. It is not on the critical command-dispatch path for any handler. New code should use `CommandResult` instead. + +--- + +## Public API + +### Bridge method (preferred for integrating with CommandBus) + +| Method | Description | +|--------|-------------| +| `static String fromResult(const CommandResult& result)` | Serialises a `CommandResult` to the standard wire JSON format. Used to convert `CommandResult` objects when a pre-serialised string is needed outside the transport dispatch path. | + +### Generic builders + +| Method | Description | +|--------|-------------| +| `static String success(const String& type, const String& payload = "")` | `{ "status": "SUCCESS", "type": ..., "payload": ... }` | +| `static String success(const String& type, const JsonObject& payload)` | Success with a JSON object payload. | +| `static String error(const String& type, const String& message)` | `{ "status": "ERROR", "type": ..., "payload": ... }` | +| `static String status(const String& type, const JsonObject& data)` | Alias for `success` with JSON data. | +| `static String status(const String& type, const String& data)` | Alias for `success` with string data. | +| `static String buildResponse(Status, const String& type, const String& payload)` | Low-level builder. Reuses a static `StaticJsonDocument<512>`. | +| `static String buildResponse(Status, const String& type, const JsonObject& payload)` | Low-level builder with JSON payload. | + +### Specialised builders + +| Method | Description | +|--------|-------------| +| `static String acknowledgment(const String& commandType)` | `success(type, "Command acknowledged")` | +| `static String pong()` | `success("pong", "")` | +| `static String deviceStatus(PlayerStatus, uint32_t elapsed, uint64_t projected, const uint32_t counters[16])` | Serialises full player status. Uses a `DynamicJsonDocument<1024>`. | +| `static String melodyList(const String& fileListJson)` | Wraps a pre-serialised file list. | +| `static String downloadResult(bool success, const String& filename)` | Download success/failure response. | +| `static String configUpdate(const String& configType)` | Generic config-saved acknowledgment. | + +### Error builders + +| Method | Description | +|--------|-------------| +| `static String invalidCommand(const String& command)` | `error("invalid_command", "Unknown command: ...")` | +| `static String missingParameter(const String& parameter)` | `error("missing_parameter", "Required parameter missing: ...")` | +| `static String operationFailed(const String& operation, const String& reason)` | `error(operation, "... failed: ...")` | +| `static String deviceBusy()` | `error("device_busy", "Device is currently busy, try again later")` | +| `static String unauthorized()` | `error("unauthorized", "Operation not authorized for this client")` | + +--- + +## Response Format + +`buildResponse()` produces: +```json +{ "status": "SUCCESS|ERROR|INFO", "type": "command_type", "payload": "..." } +``` + +`fromResult()` produces: +```json +{ "status": "SUCCESS|ERROR|INFO", "type": "command_type", "message": "...", "data": { ... } } +``` + +Note: `buildResponse` uses the key `"payload"` while `fromResult` and all transport reply lambdas use `"message"` and `"data"`. These two formats are not identical. Prefer `fromResult` / `CommandResult` for consistency with the transport layer. + +--- + +## Initialization + +No initialization required. All methods are static. The static member `_responseDoc` is zero-initialised. + +--- + +## Dependencies + +- `CommandResult` — used by `fromResult()` +- `Player` — `PlayerStatus` enum used by `deviceStatus()` +- `ArduinoJson`, `Logging` + +--- + +## Gotchas / Notes + +- **`_responseDoc` is a shared static.** `buildResponse()` calls `_responseDoc.clear()` before use, but if two calls interleave (e.g. from an ISR or concurrent task), the shared document will be corrupted. All current callers are on the main loop / AsyncWebServer callback thread, so this is not currently a problem. Do not call `ResponseBuilder` methods from FreeRTOS tasks. +- **`buildResponse` vs `fromResult` key mismatch.** `buildResponse` uses `"payload"` as the JSON key; `fromResult` (and all transport reply lambdas) use `"message"`. Mixing these in a single client will require handling both keys. Prefer `CommandResult` + transport serialisation for all new code. +- **`deviceStatus()` uses `DynamicJsonDocument<1024>`.** This is a heap allocation per call. All other methods use the static `_responseDoc`. For high-frequency status polling, this is a notable allocation hotspot. +- **Prefer `CommandResult` for new handlers.** `ResponseBuilder` is retained for backward compatibility with `WebSocketDriver` and any code that needs a pre-serialised string before the bus is involved. For all command handler responses, use `CommandResult::ok()`, `CommandResult::err()`, or `CommandResult::info()`. diff --git a/src/Communication/Transport/HTTPTransport/README.md b/src/Communication/Transport/HTTPTransport/README.md new file mode 100644 index 0000000..4d0b138 --- /dev/null +++ b/src/Communication/Transport/HTTPTransport/README.md @@ -0,0 +1,72 @@ +# HTTPTransport + +## Summary + +`HTTPTransport` exposes a minimal REST API over HTTP that routes commands through the `CommandBus`. It registers three endpoints on the `AsyncWebServer`: `POST /api/command` accepts any v2 command in JSON, `GET /api/ping` is a lightweight health check that bypasses the bus entirely, and `GET /api/status` is a convenience shortcut that dispatches `system.status` and returns the result. HTTP is stateless — there are no persistent connections — so `broadcast()` is a no-op. Each request's reply lambda captures the `AsyncWebServerRequest*` pointer and sends the HTTP response when the handler returns. + +--- + +## Public API + +| Method | Description | +|--------|-------------| +| `HTTPTransport(AsyncWebServer& server, CommandBus& bus, ConfigManager& configManager)` | Constructor. Does not register routes yet. | +| `void begin()` | Registers all HTTP routes and sets global CORS headers (`Access-Control-Allow-Origin: *`). Sets `_initialised = true`. | +| `void loop()` | No-op. AsyncWebServer is event-driven. | +| `bool isHealthy() const` | Returns `_initialised`. True once `begin()` has been called. | +| `String name() const` | Returns `"HTTP"`. | +| `void broadcast(const String&)` | No-op. | + +--- + +## Endpoints + +| Method | Path | Description | +|--------|------|-------------| +| `POST` | `/api/command` | Execute any command. Body must be JSON with at least a `"cmd"` field. | +| `GET` | `/api/ping` | Returns `{ "status": "SUCCESS", "type": "pong", "uptime": }`. No bus involvement. | +| `GET` | `/api/status` | Dispatches `system.status` and returns the result. | + +### POST /api/command + +Request body: +```json +{ "v": 2, "cmd": "relay.get_config", "contents": {} } +``` + +Response (success): +```json +{ "status": "SUCCESS", "type": "relay.get_config", "data": { ... } } +``` + +Response (error): +```json +{ "status": "ERROR", "type": "relay.set_durations", "message": "Missing or invalid 'bells' object" } +``` + +HTTP status code is always `200` for dispatched commands (even errors — the error is in the JSON body). HTTP `400` is returned only for malformed requests (bad JSON, missing `"cmd"`). + +--- + +## Initialization + +`CommunicationRouter::begin()` calls `_httpTransport.begin()`, then adds the transport to the bus with `_bus.addTransport(&_httpTransport)`. The underlying `AsyncWebServer` is started separately by `main.cpp` in the network-connected callback. + +--- + +## Dependencies + +- `AsyncWebServer` (ESPAsyncWebServer) — route registration and request handling +- `CommandBus` — dispatch +- `ConfigManager` — held as a reference (available for future auth/rate-limiting) +- `ArduinoJson`, `Logging` + +--- + +## Gotchas / Notes + +- **CORS is global.** `DefaultHeaders::Instance().addHeader(...)` applies to all responses served by the `AsyncWebServer`, not just HTTP transport routes. Any other handler sharing the same server will also emit these headers. +- **Body must arrive complete.** The body callback only processes the message when `index + len == total`, i.e. when the full body has been received. Partial delivery (chunked transfer, slow clients) will be ignored until the final chunk. +- **HTTP status is always 200 for dispatched commands.** Error results from handlers still return HTTP 200. Callers must inspect `"status"` in the JSON body. Only truly malformed requests (no body, bad JSON, missing `"cmd"`) return 4xx. +- **No authentication.** Any client that can reach the device on port 80 can issue any command. This is intentional for the local-network deployment context. +- **`broadcast()` is a no-op.** HTTP has no persistent connection. The transport is registered with the bus so that `broadcast()` calls don't crash, but no data is sent. diff --git a/src/Communication/Transport/MQTTTransport/README.md b/src/Communication/Transport/MQTTTransport/README.md new file mode 100644 index 0000000..d525e3d --- /dev/null +++ b/src/Communication/Transport/MQTTTransport/README.md @@ -0,0 +1,61 @@ +# MQTTTransport + +## Summary + +`MQTTTransport` wraps `MQTTDriver` and connects it to the `CommandBus`. It subscribes to the device control topic, parses incoming JSON messages into `CommandEnvelope` objects, and dispatches them. Command replies are published back to the device data topic. Unsolicited events (telemetry, bell strikes) reach clients via `broadcast()`, which also publishes to the data topic. The underlying `MQTTDriver` manages the broker connection lifecycle, reconnect backoff, and heartbeat independently; `MQTTTransport` only owns the message-routing glue. + +--- + +## Public API + +| Method | Description | +|--------|-------------| +| `MQTTTransport(MQTTDriver& mqtt, CommandBus& bus)` | Constructor. Does not start the connection. | +| `void begin()` | Wires the message callback onto `MQTTDriver`, then calls `MQTTDriver::begin()` to configure the AsyncMqttClient. Does not connect to the broker — connection is triggered by `onNetworkConnected()`. | +| `void loop()` | No-op. AsyncMqttClient is fully event-driven. | +| `bool isHealthy() const` | Returns `MQTTDriver::isConnected()`. | +| `String name() const` | Returns `"MQTT"`. | +| `void broadcast(const String& msg)` | Publishes `msg` to the device data topic (`vesper/{uid}/data`). | +| `void onNetworkConnected()` | Forwards to `MQTTDriver::onNetworkConnected()`, which schedules the broker connection after a 2-second stabilisation delay. | +| `void onNetworkDisconnected()` | Forwards to `MQTTDriver::onNetworkDisconnected()`. | + +--- + +## Initialization + +`CommunicationRouter::begin()` calls `_mqttTransport.begin()`, then adds the transport to the bus with `_bus.addTransport(&_mqttTransport)`. Network events from `Networking` arrive via `CommunicationRouter::onNetworkConnected()` / `onNetworkDisconnected()`, which forward to this transport. + +--- + +## Message Format + +Incoming control messages must be JSON with at least a `"cmd"` field: + +```json +{ "v": 2, "cmd": "relay.set_durations", "contents": { "bells": { "0": 500 } } } +``` + +`"v"` defaults to `2` if omitted. `"v": 1` triggers legacy translation before dispatch. + +Responses are published to the data topic: +```json +{ "status": "SUCCESS", "type": "relay.set_durations", "message": "Bell durations updated and saved" } +``` + +--- + +## Dependencies + +- `MQTTDriver` — broker connection, publish/subscribe, reconnect, heartbeat +- `CommandBus` — dispatch and broadcast +- `ArduinoJson`, `Logging` + +--- + +## Gotchas / Notes + +- **Both reply and broadcast publish to the same data topic.** The broker does not distinguish between command replies and unsolicited events — clients must inspect `"type"` and `"status"` to differentiate. +- **Broker connection is deferred.** `begin()` does not connect. The connection is triggered by `onNetworkConnected()`, which starts a 2-second non-blocking stabilisation timer in `MQTTDriver`. +- **MQTT must be enabled in config.** `MQTTDriver::connect()` is a no-op if `mqttConfig.enabled` is false. Toggle with `mqtt.enable` / `mqtt.disable` commands. +- **No per-message QoS.** Command replies and broadcasts are published at QoS 0. Heartbeats use QoS 1 with `retain = true`. +- **JSON parse errors drop the message silently** (with a `LOG_WARNING`). The client receives no error response. diff --git a/src/Communication/Transport/README.md b/src/Communication/Transport/README.md new file mode 100644 index 0000000..66ed4ca --- /dev/null +++ b/src/Communication/Transport/README.md @@ -0,0 +1,33 @@ +# Transport Layer + +## Summary + +The Transport layer adapts five communication protocols — MQTT, WebSocket, HTTP, UART, and the settings web server — to a common interface consumed by the `CommandBus`. Each transport is responsible for receiving raw input from its protocol, parsing it into a `CommandEnvelope`, injecting a reply lambda that routes the response back over the same protocol, and calling `CommandBus::dispatch()`. For unsolicited events, the bus calls each transport's `broadcast()` method. Transports have no knowledge of what handlers do; handlers have no knowledge of which transport a command arrived on. The transport identity is recorded in `CommandEnvelope::transport` for the rare cases where a handler needs it (e.g. `identify` is WebSocket-only). + +--- + +## ITransport Interface + +All transports implement `ITransport`: + +| Method | Description | +|--------|-------------| +| `virtual void begin() = 0` | Initialise the transport. Called once from `CommunicationRouter::begin()`. | +| `virtual void loop() = 0` | Service the event loop. No-op for event-driven transports; required for UART polling. | +| `virtual bool isHealthy() const = 0` | Health check used by `HealthMonitor` / `CommunicationRouter::isHealthy()`. | +| `virtual String name() const = 0` | Human-readable name for logging (e.g. `"MQTT"`, `"WebSocket"`). | +| `virtual void broadcast(const String& msg) = 0` | Push a pre-serialised JSON string to all clients. No-op for stateless transports (HTTP, WebServerTransport). | + +--- + +## Transports at a Glance + +| Transport | Protocol | Endpoint / Topic | Persistent connection | Broadcast | +|-----------|----------|------------------|-----------------------|-----------| +| `MQTTTransport` | MQTT (AsyncMqttClient) | `vesper/{uid}/control` (RX), `vesper/{uid}/data` (TX) | Yes (broker) | Yes — publishes to data topic | +| `WebSocketTransport` | WebSocket | `/ws` | Yes (per client) | Yes — all or targeted clients | +| `HTTPTransport` | HTTP REST | `POST /api/command`, `GET /api/ping`, `GET /api/status` | No | No-op | +| `UARTTransport` | UART (Serial2) | GPIO 12 TX / 13 RX @ 115200 | Yes (slave device) | Yes — sends to UART slave | +| `WebServerTransport` | HTTP (settings UI) | `GET /settings`, `POST /api/set-mode`, `POST /api/reboot` | No | No-op | + +See the subdirectory README for each transport for details. diff --git a/src/Communication/Transport/UARTTransport/README.md b/src/Communication/Transport/UARTTransport/README.md new file mode 100644 index 0000000..d8ceb26 --- /dev/null +++ b/src/Communication/Transport/UARTTransport/README.md @@ -0,0 +1,78 @@ +# UARTTransport + +## Summary + +`UARTTransport` wraps `UARTDriver` and connects it to the `CommandBus` for the UART slave interface (LCD panel / button board on Serial2). Unlike other transports, UART requires polling — `loop()` must be called each iteration of the Arduino main loop. A command whitelist is enforced before dispatch: only five commands are allowed from the UART slave. All other commands are silently dropped. This prevents a compromised or misbehaving slave from issuing sensitive commands (factory reset, OTA update, etc.). Replies are sent back over UART as newline-delimited JSON. + +--- + +## Public API + +| Method | Description | +|--------|-------------| +| `UARTTransport(UARTDriver& uart, CommandBus& bus)` | Constructor. | +| `void begin()` | Wires the message callback onto `UARTDriver`, then calls `UARTDriver::begin()` to initialise Serial2. | +| `void loop()` | Calls `UARTDriver::loop()` to poll for incoming bytes. **Must be called from the Arduino main loop.** | +| `bool isHealthy() const` | Returns `UARTDriver::isReady()`. | +| `String name() const` | Returns `"UART"`. | +| `void broadcast(const String& msg)` | Sends a JSON string to the UART slave (newline appended by `UARTDriver::send()`). | + +--- + +## Command Whitelist + +Only the following commands are accepted from the UART slave: + +| Command | Purpose | +|---------|---------| +| `ping` | Connection check | +| `playback` | Play / stop from physical buttons | +| `clock.pause` | Button-triggered clock pause | +| `clock.resume` | Button-triggered clock resume | +| `system.get_time` | LCD requests current time (pull model, replaces old push) | + +Any command not in this list is dropped with a `LOG_WARNING` and the client receives no response. + +--- + +## Initialization + +`CommunicationRouter::begin()` calls `_uartTransport.begin()`, then adds the transport to the bus. `CommunicationRouter::loop()` calls `_uartTransport.loop()`, which is the only mandatory polling call in the system. + +--- + +## Wire Protocol + +Messages are newline-delimited JSON on Serial2 (TX: GPIO 12, RX: GPIO 13, 115200 baud): + +``` +{ "v": 2, "cmd": "playback", "contents": { ... } }\n +``` + +Responses are sent back immediately after dispatch: +``` +{ "status": "SUCCESS", "type": "playback", "message": "Playback command executed" }\n +``` + +JSON parse errors on the slave side generate an error response: +``` +{ "status": "ERROR", "type": "parse_error", "payload": "" }\n +``` + +--- + +## Dependencies + +- `UARTDriver` — Serial2 I/O, line buffering, JSON parsing +- `CommandBus` — dispatch +- `ArduinoJson`, `Logging` + +--- + +## Gotchas / Notes + +- **`loop()` must be called.** Without it, no UART messages are processed. `CommunicationRouter::loop()` handles this for you. +- **Whitelist is enforced before the bus.** Dropped commands produce a `LOG_WARNING` but no response to the slave. If the slave is polling for a response that never arrives, it will time out. Design slave firmware accordingly. +- **Buffer overflow drops the message.** `UARTDriver` has a 1024-byte receive buffer. Messages longer than this are discarded and `_errorCount` is incremented. +- **Blocking flush.** `UARTDriver::send()` calls `Serial.flush()` after each response, which blocks until the UART TX buffer drains. At 115200 baud this is typically under 1 ms for short responses. +- **No v1 translation for UART.** In practice the UART slave sends v2 commands, but `CommandBus::dispatch()` will still translate v1 envelopes if `"v": 1` is set. diff --git a/src/Communication/Transport/WebServerTransport/README.md b/src/Communication/Transport/WebServerTransport/README.md new file mode 100644 index 0000000..8d507a3 --- /dev/null +++ b/src/Communication/Transport/WebServerTransport/README.md @@ -0,0 +1,70 @@ +# WebServerTransport + +## Summary + +`WebServerTransport` absorbs the old `SettingsWebServer` subsystem into the transport layer (Stage 6 of the comms refactor). It serves an on-board network configuration page at `GET /settings` and routes two form actions through the `CommandBus`: `POST /api/set-mode` (AP/station toggle via `network.set_config`) and `POST /api/reboot` (device restart via `system.restart`). By routing through the bus, the settings UI benefits from the same validation and persistence logic as every other client. Like `HTTPTransport`, it has no persistent connections, so `broadcast()` is a no-op. + +--- + +## Public API + +| Method | Description | +|--------|-------------| +| `WebServerTransport(AsyncWebServer&, CommandBus&, ConfigManager&, Networking&)` | Constructor. | +| `void begin()` | Registers the three HTTP routes. Sets `_initialised = true`. | +| `void loop()` | No-op. AsyncWebServer is event-driven. | +| `bool isHealthy() const` | Returns `_initialised`. | +| `String name() const` | Returns `"WebServer"`. | +| `void broadcast(const String&)` | No-op. | + +--- + +## Endpoints + +| Method | Path | Description | +|--------|------|-------------| +| `GET` | `/settings` | Serves the network settings HTML page with current values substituted. | +| `POST` | `/api/set-mode` | Accepts form parameter `mode=ap` or `mode=station`. Dispatches `network.set_config`, then reboots the device on success. | +| `POST` | `/api/reboot` | Dispatches `system.restart`. Sends a plain-text ack to the browser before the handler fires. | + +### Settings Page Template Variables + +The HTML template (`SettingsWebServer/SettingsPage.h`) uses the following substitution tokens: + +| Token | Source | +|-------|--------| +| `%MODE_BADGE_CLASS%` | `networking.isInAPMode()` → `"ap"` or `"station"` | +| `%MODE_TEXT%` | `"AP Mode"` or `"Station Mode"` | +| `%CURRENT_IP%` | `networking.getLocalIP()` | +| `%DEVICE_UID%` | `configManager.getDeviceUID()` | +| `%FW_VERSION%` | `configManager.getFwVersion()` | +| `%AP_ACTIVE_CLASS%` | `"active"` if in AP mode | +| `%STATION_ACTIVE_CLASS%` | `"active"` if in station mode | +| `%SELECTED_MODE%` | `"ap"` or `"station"` | + +--- + +## Initialization + +`CommunicationRouter::begin()` calls `_webServerTransport.begin()` and adds it to the bus. The underlying `AsyncWebServer` is started by `main.cpp` in the network-connected callback. + +--- + +## Dependencies + +- `AsyncWebServer` (ESPAsyncWebServer) +- `CommandBus` — dispatches `network.set_config` and `system.restart` +- `ConfigManager` — supplies device UID, firmware version, and current network config +- `Networking` — supplies current IP and AP mode state +- `SettingsWebServer/SettingsPage.h` — HTML template (PROGMEM string `SETTINGS_PAGE_HTML`) +- `ArduinoJson`, `Logging` + +--- + +## Gotchas / Notes + +- **AP mode change triggers a hard reboot.** The reply lambda for `POST /api/set-mode` calls `delay(3000)` followed by `ESP.restart()` on success. This is intentional — network mode changes require a full reboot to take effect. Any in-flight WebSocket connections or MQTT sessions will be dropped without notice. +- **Reboot ack is sent before the handler.** For `POST /api/reboot`, `request->send()` is called before dispatching to the bus. The `system.restart` handler schedules a 2-second delayed task reboot. The browser receives the ack and the device reboots shortly after. +- **HTML template is in PROGMEM.** `SETTINGS_PAGE_HTML` is stored in flash, not RAM. `String(FPSTR(...))` copies it to heap. On low-memory devices this allocation (~2 KB) can fail — watch heap at `/api/ping`. +- **`broadcast()` is a no-op.** This transport has no active client connections to push to. +- **Shared server with HTTPTransport.** Both transports register routes on the same `AsyncWebServer`. Route prefixes (`/settings`, `/api/set-mode`, `/api/reboot`) must not conflict with those registered by `HTTPTransport` (`/api/command`, `/api/ping`, `/api/status`). diff --git a/src/Communication/Transport/WebSocketTransport/README.md b/src/Communication/Transport/WebSocketTransport/README.md new file mode 100644 index 0000000..ef87d52 --- /dev/null +++ b/src/Communication/Transport/WebSocketTransport/README.md @@ -0,0 +1,77 @@ +# WebSocketTransport + +## Summary + +`WebSocketTransport` wraps `WebSocketDriver` and connects it to the `CommandBus`. When a WebSocket client sends a JSON message, the driver parses it and invokes a callback on this transport, which builds a `CommandEnvelope` with a reply lambda that sends the response back to the originating client only. `broadcast()` sends to all connected clients. The transport also exposes targeted and role-based broadcast methods used by `CommunicationRouter`'s helpers. All client lifecycle tracking (type classification as master/secondary, heartbeat, cleanup) is handled by `ClientManager` through the driver. + +--- + +## Public API + +| Method | Description | +|--------|-------------| +| `WebSocketTransport(WebSocketDriver& ws, CommandBus& bus)` | Constructor. | +| `void begin()` | Wires the message callback onto `WebSocketDriver` and calls `WebSocketDriver::begin()`. The `AsyncWebSocket` handler must be added to `AsyncWebServer` separately (done in `CommunicationRouter::begin()`). | +| `void loop()` | No-op. AsyncWebServer is event-driven. | +| `bool isHealthy() const` | Always returns `true` — the WebSocket server is always listening once started. | +| `String name() const` | Returns `"WebSocket"`. | +| `void broadcast(const String& msg)` | Sends `msg` to all connected WebSocket clients. | +| `void sendToClient(uint32_t clientId, const String& msg)` | Sends to a single client by ID. Used by handlers that need to target the originating client directly. | +| `void broadcastToMasters(const String& msg)` | Sends to clients classified as `MASTER` type only. | +| `void broadcastToSecondary(const String& msg)` | Sends to clients classified as `SECONDARY` type only. | +| `bool hasClients() const` | True if at least one client is connected. | +| `size_t getClientCount() const` | Number of currently connected clients. | + +--- + +## Initialization + +`CommunicationRouter::begin()` does two things for WebSocket: +1. Calls `_server.addHandler(&_webSocket)` to attach the `AsyncWebSocket` instance to the HTTP server. +2. Calls `_wsTransport.begin()` to wire the message callback. + +The `AsyncWebServer` itself is started later from the network-connected callback in `main.cpp`. + +--- + +## Message Format + +Incoming WebSocket messages must be JSON: +```json +{ "v": 2, "cmd": "system.status", "contents": {} } +``` + +Missing `"cmd"` field results in an immediate error response to that client: +```json +{ "status": "ERROR", "type": "bad_request", "message": "Missing 'cmd' field" } +``` + +Responses are sent only to the originating client: +```json +{ "status": "SUCCESS", "type": "system.status", "data": { ... } } +``` + +On connect, each client receives an unsolicited welcome message: +```json +{ "status": "SUCCESS", "type": "connection", "payload": "Connected to Vesper" } +``` + +--- + +## Dependencies + +- `WebSocketDriver` — client lifecycle, connection events, routing +- `ClientManager` — client type classification (master/secondary), targeted sends +- `CommandBus` — dispatch and broadcast +- `ESPAsyncWebServer`, `ArduinoJson`, `Logging` + +--- + +## Gotchas / Notes + +- **Only single-frame, complete text messages are processed.** Fragmented or binary WebSocket frames are logged as a warning and dropped. +- **`isHealthy()` is always true.** The transport has no broker or physical connection to check — it returns `true` as long as the code is running. `CommunicationRouter::isHealthy()` accounts for this by also checking `isMqttConnected()`. +- **WebSocket cleanup must be driven externally.** `main.cpp` calls `ws.cleanupClients()` every 2 seconds to evict dead connections. Without this, ghost clients can block new connections. +- **Replies go only to the originating client.** Command responses are not broadcast. If other clients need to know about a state change, the handler or the subsystem must trigger a broadcast separately. +- **`identify` command is WebSocket-only.** If sent over HTTP or UART, `SystemHandler` returns an error. This is enforced by checking `envelope.transport`. +- **Message buffer: 2 KB.** The `StaticJsonDocument<2048>` in `WebSocketDriver::onData()` limits individual message size. Large melody or config payloads must be split by the client. diff --git a/src/ConfigManager/README.md b/src/ConfigManager/README.md new file mode 100644 index 0000000..c572cc1 --- /dev/null +++ b/src/ConfigManager/README.md @@ -0,0 +1,220 @@ +# ConfigManager + +## Summary + +ConfigManager is the single source of truth for all device configuration in Vesper firmware. It owns three distinct storage tiers: factory identity (device UID, hardware type/version) read once from ESP32 NVS at boot; user-configurable settings (network, time, bell, clock, general) stored as JSON files on the SD card; and compiled-in hardware constants for pin assignments and similar build-time values. Every other subsystem that needs persistent configuration reads it from ConfigManager rather than accessing NVS or the SD card directly. ConfigManager also derives the MQTT credentials at runtime using HMAC-SHA256 so that no plaintext secrets need to be stored on the device. + +--- + +## Initialization + +ConfigManager must be the **first** subsystem initialized after `SDCardMutex`. The SD card mutex must be up before any SD I/O is attempted. + +``` +SDCardMutex::getInstance().begin(); // must come first +configManager.begin(); // NVS -> defaults -> SD card loads +``` + +`begin()` executes the following load sequence: + +1. `nvs_flash_init()` + open handle for namespace `device_id` +2. Read `device_uid`, `hw_type`, `hw_version` from NVS (read-only; empty strings if not provisioned) +3. Auto-generate `hostname` (`BellSystems-`) and `apSsid` (`BellSystems-Setup-`) +4. Set `mqttConfig.user = deviceUID` and derive `mqttConfig.password` via HMAC-SHA256 +5. Mount SD card on the SPI CS pin stored in `HardwareConfig::sdChipSelect` (default GPIO 5) +6. Load each config domain from `/settings/*.json`; if a file is missing, write defaults and continue + +`begin()` returns `false` if the SD card cannot be mounted. This is logged as an error but the system continues with in-RAM defaults — callers should treat a `false` return as a warning that persistence is unavailable rather than a fatal condition. + +After `configManager.begin()` returns, `main.cpp` immediately applies the stored log level: + +```cpp +Logging::setLevel((Logging::LogLevel)configManager.getGeneralConfig().serialLogLevel); +``` + +--- + +## Dependencies + +| Dependency | Purpose | +|---|---| +| `SDCardMutex` | Must be initialized first; protects concurrent SD access | +| `nvs_flash` / `nvs` (ESP-IDF) | Reads factory identity from NVS partition | +| `SD` (Arduino) | All `/settings/*.json` file I/O | +| `ArduinoJson` | JSON serialization / deserialization for every config file | +| `mbedtls/md.h` | HMAC-SHA256 for MQTT password derivation | +| `MQTT_SECRET` build flag | Injected at compile time via `-DMQTT_SECRET="..."` in `platformio.ini`; must match the backend `.env` value | + +ConfigManager has **no dependency on any other application subsystem**. It is the root of the dependency tree. + +--- + +## Public API + +### Lifecycle + +| Method | Description | +|---|---| +| `bool begin()` | Full initialization: NVS load, defaults, SD mount, all config file loads | +| `bool saveToSD()` | Convenience save: writes bell durations, clock config, and clock state | +| `bool isHealthy() const` | Returns true if SD is mounted, UID is set, and hostname is generated | +| `bool resetAllToDefaults()` | Deletes all `/settings/*.json` files and `/melodies/*`; device identity in NVS is preserved | + +### Config Struct Accessors (read-only references) + +| Method | Description | +|---|---| +| `const DeviceConfig& getDeviceConfig() const` | Device UID, hardware type/version, firmware version | +| `const NetworkConfig& getNetworkConfig() const` | Hostname, static IP settings, AP mode, discovery port | +| `const MqttConfig& getMqttConfig() const` | Broker host/port, credentials, SSL flag, enabled flag | +| `const HardwareConfig& getHardwareConfig() const` | PCF8574 I2C address, SPI pins, SD CS pin | +| `const TimeConfig& getTimeConfig() const` | NTP server, GMT offset, DST offset | +| `const UpdateConfig& getUpdateConfig() const` | OTA fallback URL, timeout, retry count | +| `const BellConfig& getBellConfig() const` | Per-bell durations and output mappings (16 bells) | +| `const ClockConfig& getClockConfig() const` | All clock, alert, backlight, and silence settings | +| `const GeneralConfig& getGeneralConfig() const` | Per-transport log levels, MQTT enabled flag | + +### Device Identity (read-only) + +| Method | Description | +|---|---| +| `String getDeviceUID() const` | Factory-set device UID from NVS | +| `String getHwType() const` | Hardware type code (e.g., `VS` for Vesper) | +| `String getHwVersion() const` | Hardware revision string (e.g., `01`) | +| `String getFwVersion() const` | Current firmware version string (integer format, e.g., `154`) | +| `void setFwVersion(const String&)` | Updates firmware version in RAM; persist with `saveDeviceConfig()` | +| `String getHardwareVariant() const` | Alias for `getHwType()` | +| `String getAPSSID() const` | Auto-generated AP SSID (`BellSystems-Setup-`) | + +### Network Config + +| Method | Description | +|---|---| +| `bool loadNetworkConfig()` | Load `/settings/networkConfig.json` from SD | +| `bool saveNetworkConfig()` | Persist current network settings to SD | +| `void updateNetworkConfig(hostname, useStaticIP, ip, gateway, subnet, dns1, dns2)` | Apply new network settings and save immediately | +| `bool getPermanentAPMode() const` | Whether device is locked in AP mode | +| `void setPermanentAPMode(bool)` | Toggle permanent AP mode (persist with `saveNetworkConfig()`) | + +### Time Config + +| Method | Description | +|---|---| +| `bool loadTimeConfig()` | Load `/settings/timeConfig.json` from SD | +| `bool saveTimeConfig()` | Persist time settings to SD | +| `void updateTimeConfig(gmtOffsetSec, daylightOffsetSec)` | Apply new timezone offsets and save immediately | + +### Bell Config + +| Method | Description | +|---|---| +| `bool loadBellDurations()` | Load `/settings/relayTimings.json` | +| `bool saveBellDurations()` | Persist bell durations to SD | +| `bool loadBellOutputs()` | Load `/settings/bellOutputs.json` | +| `bool saveBellOutputs()` | Persist bell output mappings to SD | +| `void updateBellDurations(JsonVariant)` | Bulk-update durations from a JSON object (`{"b1": 90, "b2": 120, ...}`) | +| `void updateBellOutputs(JsonVariant)` | Bulk-update output mappings; converts 1-based API indices to 0-based internal | +| `uint16_t getBellDuration(uint8_t index) const` | Single-bell duration in ms (0-based index, max 15) | +| `uint16_t getBellOutput(uint8_t index) const` | Physical output for a bell slot (0-based) | +| `void setBellDuration(uint8_t index, uint16_t ms)` | Set one bell's duration in RAM | +| `void setBellOutput(uint8_t index, uint16_t output)` | Set one bell's output mapping in RAM | + +### Clock Config + +| Method | Description | +|---|---| +| `bool loadClockConfig()` | Load `/settings/clockConfig.json` | +| `bool saveClockConfig()` | Persist clock configuration to SD | +| `bool loadClockState()` | Load `/settings/clockState.json` (physical hand position) | +| `bool saveClockState()` | Persist physical clock state to SD | +| `void updateClockOutputs(JsonVariant)` | Set C1/C2 output pins and pulse/pause durations from JSON | +| `void updateClockAlerts(JsonVariant)` | Set alert type, ring interval, and bell assignments from JSON | +| `void updateClockBacklight(JsonVariant)` | Set backlight output and on/off times from JSON | +| `void updateClockSilence(JsonVariant)` | Set daytime and nighttime silence periods from JSON | +| `bool getClockEnabled() const` | Whether clock mechanism is active | +| `void setClockEnabled(bool)` | Enable/disable clock mechanism | +| `uint8_t getPhysicalClockHour() const` | Current physical clock hour (0–11) | +| `uint8_t getPhysicalClockMinute() const` | Current physical clock minute (0–59) | +| `bool getNextOutputIsC1() const` | Which coil fires next during advancement | +| `uint32_t getLastSyncTime() const` | Unix timestamp of last successful clock sync | +| `void setPhysicalClockHour(uint8_t)` | Update tracked hour (auto-clamps to 0–11) | +| `void setPhysicalClockMinute(uint8_t)` | Update tracked minute (auto-clamps to 0–59) | +| `void setNextOutputIsC1(bool)` | Update alternation state | +| `void setLastSyncTime(uint32_t)` | Update sync timestamp | +| `String getAlertType() const` | Alert mode string: `"OFF"`, `"SINGLE"`, or `"HOURS"` | +| `uint8_t getHourBell() const` | Bell index for hourly alert (255 = disabled) | +| `uint8_t getHalfBell() const` | Bell index for half-hour alert (255 = disabled) | +| `uint8_t getQuarterBell() const` | Bell index for quarter-hour alert (255 = disabled) | + +### General Config / Logging + +| Method | Description | +|---|---| +| `bool loadGeneralConfig()` | Load `/settings/generalConfig.json` | +| `bool saveGeneralConfig()` | Persist log levels and MQTT enabled flag to SD | +| `bool setSerialLogLevel(uint8_t)` | Set serial log level 0–5; returns false on invalid input | +| `bool setSdLogLevel(uint8_t)` | Set SD log level 0–5 | +| `bool setMqttLogLevel(uint8_t)` | Set MQTT log level 0–5 | +| `uint8_t getSerialLogLevel() const` | Current serial log level | +| `uint8_t getSdLogLevel() const` | Current SD log level | +| `uint8_t getMqttLogLevel() const` | Current MQTT log level | +| `void setMqttEnabled(bool)` | Toggle MQTT (mirrors to both `GeneralConfig` and `MqttConfig`) | +| `bool getMqttEnabled() const` | Whether MQTT is enabled | + +### Misc + +| Method | Description | +|---|---| +| `bool loadDeviceConfig()` | Load `/settings/deviceConfig.json` (firmware version only) | +| `bool saveDeviceConfig()` | Persist firmware version to SD | +| `bool loadUpdateServers()` | Load `/settings/updateServers.json` (optional OTA server list) | +| `std::vector getUpdateServers() const` | Returns loaded OTA server URLs plus the compiled-in fallback URL | +| `String getAllSettingsAsJson() const` | Serializes all in-RAM config domains to a single JSON string | +| `void saveFileToSD(dirPath, filename, data)` | Low-level helper used internally; creates directory if absent | + +--- + +## SD Card File Layout + +All files live under `/settings/` on the FAT SD card. + +| File | Config domain | +|---|---| +| `deviceConfig.json` | Firmware version | +| `networkConfig.json` | Hostname, static IP, permanent AP mode | +| `timeConfig.json` | NTP server, GMT offset, DST offset | +| `relayTimings.json` | Bell pulse durations (keys `b1`–`b16`) | +| `bellOutputs.json` | Bell-to-output mappings (keys `b1`–`b16`) | +| `clockConfig.json` | All clock settings, alerts, backlight, silence | +| `clockState.json` | Physical hand position and sync timestamp | +| `generalConfig.json` | Log levels, MQTT enabled | +| `updateServers.json` | Optional OTA server list (`{"servers": [{"url": "..."}]}`) | +| `/melodies/*` | Melody files; deleted by `resetAllToDefaults()` | + +--- + +## Gotchas / Notes + +**NVS is strictly read-only in production firmware.** +`device_uid`, `hw_type`, and `hw_version` are written only by the factory provisioning tool. If any of these keys are absent in NVS, `begin()` logs a critical warning and the device will use empty strings. MQTT auth will fail and subsystems that gate on `getDeviceUID()` will behave incorrectly. Reflash the NVS partition using `esptool` and the provisioning binary. + +**MQTT password is derived at boot, not stored.** +`computeMqttPassword()` runs HMAC-SHA256(`MQTT_SECRET`, `deviceUID`) and takes the first 16 bytes (32 hex chars). The build flag `MQTT_SECRET` must match the value in the backend `.env` exactly. A mismatch will cause MQTT `CONNACK` error 5 (Not Authorized). The secret is logged at `INFO` level on boot — remove or gate this log line before shipping. + +**SD card is required for user settings.** +`begin()` returns `false` if `SD.begin()` fails. All `load*()` and `save*()` methods silently return `false` when the card is absent. The HealthMonitor reports ConfigManager as unhealthy when `isHealthy()` returns false (SD unmounted or UID empty). This is classified as a WARNING, not CRITICAL, so the firmware continues running with in-RAM defaults. + +**`updateBellOutputs` converts 1-based to 0-based.** +The external API sends bell output numbers as 1-based integers. `updateBellOutputs()` subtracts 1 before storing. `getBellOutput()` returns a 0-based index. Do not apply an additional offset when passing values to OutputManager. + +**`setPhysicalClockHour` normalizes to 1–12 range.** +The setter uses `hour % 12 == 0 ? 12 : hour % 12`, so passing `0` or `12` both result in `12`. Internal storage is 0–11 in `loadClockState()` (via `% 12`). This is an inconsistency in the current code; treat the setter output as 1-based and storage as 0-based. + +**Bell index 255 means disabled.** +Used for `hourBell`, `halfBell`, `quarterBell`, `c1output`, `c2output`, and `backlightOutput`. Always compare against 255 before using these values to index into an output array. + +**No thread safety.** +ConfigManager contains no FreeRTOS mutexes. All callers that mutate config (communication handler callbacks) run on the same core/task in the current architecture. If that changes, callers must serialize access externally. + +**`getAllSettingsAsJson` uses a 4096-byte `DynamicJsonDocument`.** +Calling this on the stack is safe. Calling it frequently from a low-stack task (e.g., from inside a timer callback) is not — allocate from a dedicated task with at least 8 KB of stack. diff --git a/src/FileManager/README.md b/src/FileManager/README.md new file mode 100644 index 0000000..47fca4e --- /dev/null +++ b/src/FileManager/README.md @@ -0,0 +1,85 @@ +# FileManager + +## Summary + +FileManager is the single access point for all SD card I/O in Vesper. It abstracts the Arduino `SD` library behind a stable API covering file downloads, JSON persistence, directory management, line appending, and existence/size queries. The subsystem exists because multiple independent consumers (Player, OTAManager, Telemetry, CommunicationRouter's SD log channel, and the `files.*` command handlers) all need SD access; centralizing it avoids direct `SD.*` calls scattered across the codebase and provides a single place to handle SD re-initialization, path normalization, and error logging. + +--- + +## Public API + +| Method | Signature | Description | +|---|---|---| +| Constructor | `FileManager(ConfigManager* config)` | Stores the ConfigManager pointer; does not initialize the SD card. | +| `downloadFile` | `bool downloadFile(const String& url, const String& directory, const String& filename)` | Downloads a file over HTTP or HTTPS (TLS, no cert validation) and writes it to `directory/filename` on the SD card. Creates the target directory if it does not exist. | +| `addMelody` | `bool addMelody(JsonVariant doc)` | High-level helper: extracts `download_url` and `melodys_uid` from a JSON object and calls `downloadFile` into `/melodies/`. Skips the download silently if the UID matches a built-in melody. | +| `listFilesAsJson` | `String listFilesAsJson(const char* dirPath)` | Returns a JSON string `{"files": [...]}` listing all non-directory entries in `dirPath`. Returns `"{}"` on any error. | +| `fileExists` | `bool fileExists(const String& filePath)` | Returns `true` if the file can be opened on the SD card. | +| `deleteFile` | `bool deleteFile(const String& filePath)` | Removes a file from the SD card. Returns `false` on failure. | +| `createDirectory` | `bool createDirectory(const String& dirPath)` | Creates a directory (and re-initializes the SD card if needed). No-op if it already exists. | +| `getFileSize` | `size_t getFileSize(const String& filePath)` | Returns the size in bytes of a file, or `0` if it cannot be opened. | +| `writeJsonFile` | `bool writeJsonFile(const String& filePath, JsonDocument& doc)` | Serializes an ArduinoJson `JsonDocument` to a file, overwriting any existing content. | +| `readJsonFile` | `bool readJsonFile(const String& filePath, JsonDocument& doc)` | Deserializes a file into an ArduinoJson `JsonDocument`. Returns `false` on open or parse failure. | +| `appendLine` | `bool appendLine(const String& filePath, const String& line)` | Opens a file in `FILE_APPEND` mode and writes `line` followed by `\n`. Used by the Logging subsystem's SD write callback to write to `/logs/vesper.log`. | +| `isHealthy` | `bool isHealthy() const` | Returns `true` if the ConfigManager pointer is set and `SD.cardType() != CARD_NONE`. Used by HealthMonitor. | + +--- + +## Initialization + +FileManager is constructed at file scope in `main.cpp` immediately after `ConfigManager`: + +```cpp +ConfigManager configManager; +FileManager fileManager(&configManager); +``` + +The constructor does nothing beyond storing the pointer. The SD card is not initialized at construction time; instead, `initializeSD()` (private) is called lazily at the start of every operation that needs the card. This means the subsystem is usable even if the SD card is absent at boot — individual calls will fail and log an error, but the device continues operating. + +After construction, other subsystems receive a pointer via setter injection during `setup()`: + +```cpp +healthMonitor.setFileManager(&fileManager); // ~line 288 +telemetry.setFileManager(&fileManager); // ~line 340 +communication.setFileManagerReference(&fileManager); // ~line 365 — also registers SD log callback +player.setDependencies(&communication, &fileManager);// ~line 373 +otaManager.setFileManager(&fileManager); // ~line 445 +``` + +The `setFileManagerReference` call on `CommunicationRouter` is particularly important: it registers an `appendLine` callback with the Logging subsystem so that all `LOG_*` output is mirrored to `/logs/vesper.log` on the SD card. + +**Setup order requirement:** `ConfigManager` must be constructed before `FileManager`. `SDCardMutex::getInstance().begin()` must be called before any SD operation executes (it is called early in `setup()`). + +--- + +## Dependencies + +| Dependency | Type | Reason | +|---|---|---| +| `ConfigManager` | Subsystem pointer | Reads `hardwareConfig.sdChipSelect` to get the CS pin for `SD.begin()`. | +| Arduino `SD` library | Platform library | All card I/O. | +| `HTTPClient`, `WiFiClient`, `WiFiClientSecure` | Platform libraries | HTTP/HTTPS file downloads. | +| `ArduinoJson` | Library | JSON serialization and deserialization. | +| `esp_task_wdt` | ESP-IDF | Watchdog disable/re-enable around blocking HTTPS operations in `downloadFile`. | +| `BuiltInMelodies` | Subsystem | Consulted by `addMelody` to skip unnecessary downloads. | +| `Logging` | Subsystem | `LOG_*` macros throughout. | + +--- + +## Gotchas / Notes + +**SD card is optional at runtime.** Every method calls `initializeSD()` which calls `SD.begin()` on each invocation. If no card is inserted the call fails, the method returns `false` or `"{}"`, and the device continues. HealthMonitor marks FileManager as WARNING (not CRITICAL) when the card is absent, so the device does not halt. + +**No internal mutex.** FileManager does not acquire `SDCardMutex` internally. The ESP32 `SD` library is not thread-safe. If FileManager methods are called from multiple FreeRTOS tasks concurrently, callers must coordinate via `SDCardMutex` / `SDCardLock` themselves. Currently `downloadFile` (called from the CommandBus task via `FileHandler`) and `appendLine` (called from the Logging callback, which fires from whatever task emits the log) are the most likely concurrent paths — audit this before adding new callers from additional tasks. + +**Watchdog is temporarily disabled during downloads.** `downloadFile` calls `esp_task_wdt_delete(NULL)` before the HTTP GET and `esp_task_wdt_add(NULL)` after. This removes watchdog coverage for the calling task for the duration of the TLS handshake (can be several seconds). Avoid calling `downloadFile` from tasks where watchdog removal is inappropriate. + +**HTTPS uses `setInsecure()`.** TLS certificate validation is skipped. This is intentional for compatibility with Firebase/CDN redirect chains, but means downloads are not authenticated — file content is trusted implicitly. + +**`SD.begin()` called on every operation.** Because `initializeSD()` runs at the top of every method, a card inserted after boot is detected automatically on the next call. Calling `SD.begin()` on an already-mounted card is harmless but adds ~1 ms overhead per call. + +**`isHealthy()` is lightweight by design.** It uses `SD.cardType()` rather than `SD.begin()` to avoid the cost and side-effects of re-mounting on every HealthMonitor poll cycle. + +**`listFilesAsJson` has a fixed 1024-byte JSON budget.** Directories with more than roughly 20–25 average-length filenames will overflow this `DynamicJsonDocument` allocation silently. Increase the capacity if `/melodies` is expected to hold a large number of files. + +**Log file path is hardcoded in the caller.** The path `/logs/vesper.log` is set inside `CommunicationRouter::setFileManagerReference`, not inside FileManager. FileManager itself is path-agnostic. diff --git a/src/FirmwareValidator/README.md b/src/FirmwareValidator/README.md new file mode 100644 index 0000000..48bd602 --- /dev/null +++ b/src/FirmwareValidator/README.md @@ -0,0 +1,111 @@ +# FirmwareValidator + +## Summary + +FirmwareValidator implements a two-phase OTA safety gate for the Vesper firmware. After a new firmware image boots, the subsystem intercepts startup before most other systems are live, performs a targeted health check, and either lets the boot proceed or immediately triggers `esp_ota_mark_app_invalid_rollback_and_reboot()` to return to the previous partition. If startup passes, a FreeRTOS monitoring task polls HealthMonitor every 30 seconds for up to 5 minutes; if the device remains healthy throughout, the partition is committed as valid via `esp_ota_set_boot_partition()`. On already-validated firmware the subsystem is transparent — it loads the persisted `VALIDATED` state from NVS and skips the validation paths entirely. The subsystem also exposes remote control of commit/rollback through FirmwareHandler in the communication layer. + +--- + +## Public API + +| Method | Description | +|---|---| +| `bool begin(HealthMonitor*, ConfigManager*)` | Initialize NVS namespace, resolve OTA partitions, reload persisted state. Must be called before `performStartupValidation()`. | +| `bool performStartupValidation()` | Run immediate startup health check. Returns `false` (and reboots or halts) only if max retries are exhausted. Must be called early in `setup()`, before non-critical subsystems start. | +| `void startRuntimeValidation()` | Start the 5-minute FreeRTOS monitoring task and one-shot commit timer. Call once, after all subsystems are initialized, when `isInTestingMode()` is true. | +| `void commitFirmware()` | Mark running partition valid and tear down monitoring resources. Normally called automatically by the timer; can be called manually (e.g. from FirmwareHandler). | +| `void rollbackFirmware()` | Force immediate rollback to the backup partition. Device reboots. | +| `bool isInTestingMode() const` | Returns `true` while validation is in any pending/running/runtime-testing state. | +| `FirmwareValidationState getValidationState() const` | Returns the current `FirmwareValidationState` enum value. | +| `FirmwareInfo getCurrentFirmwareInfo() const` | Returns version, build date, validity flag, testing flag, and boot count for the running partition. | +| `FirmwareInfo getBackupFirmwareInfo() const` | Returns basic validity info for the inactive OTA partition. Version is not populated (returns `"Unknown"`). | +| `const ValidationConfig& getValidationConfig() const` | Returns the active timing/threshold configuration (timeouts, retry counts, watchdog settings). | +| `void setValidationConfig(const ValidationConfig&)` | Replace the timing/threshold configuration before calling `begin()`. | +| `bool isHealthy() const` | Returns `true` if NVS is open, both partitions resolved, dependencies injected, and state is not a terminal failure. Used by HealthMonitor. | +| `const esp_partition_t* getRunningPartition() const` | Returns the ESP-IDF partition descriptor for the currently executing partition. | +| `const esp_partition_t* getBackupPartition() const` | Returns the ESP-IDF partition descriptor for the inactive OTA partition. | +| `bool isNewFirmwarePending() const` | Returns `true` if validation has not yet completed (`STARTUP_PENDING`, `STARTUP_RUNNING`, or `RUNTIME_TESTING`). | + +--- + +## Initialization + +**Order required in `setup()`:** + +``` +1. SDCardMutex::getInstance().begin() +2. configManager.begin() +3. healthMonitor.begin() +4. outputManager.initialize() // registered with healthMonitor +5. bellEngine.begin() // registered with healthMonitor +6. firmwareValidator.begin(&healthMonitor, &configManager) +7. firmwareValidator.performStartupValidation() ← CRITICAL GATE + (boot continues only if this returns true) +8. ... all other subsystems ... +9. communication.setFirmwareValidatorReference(&firmwareValidator) +10. communication.begin() +11. if (firmwareValidator.isInTestingMode()) firmwareValidator.startRuntimeValidation() +``` + +`performStartupValidation()` polls `healthMonitor.checkSubsystemHealth()` for `BellEngine` and `OutputManager` only. Those two subsystems must be registered with HealthMonitor **before** this call. ConfigManager and FileManager are intentionally excluded from the startup check because SD absence is non-fatal at this stage. + +`startRuntimeValidation()` is a no-op if the state is not `RUNTIME_TESTING`; it is safe to call unconditionally after checking `isInTestingMode()`. + +--- + +## Dependencies + +| Dependency | Role | +|---|---| +| `HealthMonitor` | Startup check queries `checkSubsystemHealth()`; runtime check calls `performFullHealthCheck()` and `getCriticalFailureCount()`. | +| `ConfigManager` | Provides firmware version string for `getCurrentFirmwareInfo()`. | +| ESP-IDF `esp_ota_ops` | Partition discovery, boot partition management, rollback. | +| ESP-IDF `nvs` / `nvs_flash` | Persists validation state, boot count, and retry counters across reboots. | +| ESP-IDF `esp_task_wdt` | Optional watchdog registered on the monitoring task. Uses IDF v4 API (`esp_task_wdt_init` / `esp_task_wdt_add`). | +| FreeRTOS `xTimerCreate` / `xTaskCreatePinnedToCore` | Runtime validation timer (one-shot, Tmr Svc) and monitoring task (Core 0, priority 4). | +| `ArduinoJson` | Used internally; no JSON exposed through the public API of this class directly. | + +--- + +## Gotchas / Notes + +**Timer callback vs. commit location.** The `validationTimerCallback` runs in the FreeRTOS `Tmr Svc` task, which has a 2 KB stack. It only sets `_commitPending = true`. The monitoring task polls this flag and calls `commitFirmware()` from its own 4 KB stack. Do not move blocking or heap-allocating code into the timer callback. + +**Startup check scope.** `performBasicHealthCheck()` intentionally checks only `BellEngine` and `OutputManager`. `ConfigManager` and `FileManager` are excluded because they depend on the SD card, whose absence is tolerated at startup (defaults are used). Adding SD-dependent subsystems to this check will cause spurious rollbacks on devices without an SD card inserted. + +**NVS namespace collision.** The subsystem opens its own NVS namespace `fw_validator`. Erasing NVS (e.g. during factory reset) resets validation state to `UNKNOWN`, which causes the next boot to re-enter `STARTUP_PENDING` and run a full startup validation cycle. This is expected and safe. + +**Rollback fallback path.** If `esp_ota_mark_app_invalid_rollback_and_reboot()` fails (e.g. the backup partition has no valid image header), `executeRollback()` attempts `esp_ota_set_boot_partition(_backupPartition)` + `ESP.restart()`. If even that fails, the system enters a `while(1)` halt. There is no recovery from this state without a wired flash. + +**Watchdog registration.** The watchdog is added to the `FW_Monitor` task (Core 0, priority 4). `loop()` also feeds the watchdog while `isInTestingMode()` returns true, and removes itself from the watchdog when validation completes. If `startRuntimeValidation()` is not called (already-validated firmware), the watchdog is never initialized by this subsystem. + +**Monitoring task lifetime.** `_monitoringTask` is deleted inside `commitFirmware()` (success path) and `executeRollback()` (failure path). If `rollbackFirmware()` is called while the task is running, the task deletes itself as part of `executeRollback()`. After `commitFirmware()`, `_monitoringTask` is `nullptr` and the timer handle is also cleaned up — do not call `startRuntimeValidation()` a second time. + +**Partition table requirement.** The subsystem requires two OTA partitions (`ota_0`, `ota_1`). Vesper uses `min_spiffs.csv` which provides both. If only one OTA slot is present, `initializePartitions()` returns `false` and `begin()` fails. + +--- + +## Remote Commands (via FirmwareHandler) + +These commands are dispatched through the communication layer and map directly to FirmwareValidator methods. + +| Command | Description | +|---|---| +| `firmware.status` | Returns current validation state, version, boot count, and whether commit/rollback are available. | +| `firmware.commit` | Manually commits firmware. Returns an error if not in testing mode. | +| `firmware.rollback` | Forces immediate rollback. Device will reboot. | + +Example status query: +```json +{ "v": 2, "cmd": "firmware.status", "contents": {} } +``` + +Example manual commit: +```json +{ "v": 2, "cmd": "firmware.commit", "contents": {} } +``` + +Example forced rollback: +```json +{ "v": 2, "cmd": "firmware.rollback", "contents": {} } +``` diff --git a/src/HealthMonitor/README.md b/src/HealthMonitor/README.md new file mode 100644 index 0000000..ef55c8f --- /dev/null +++ b/src/HealthMonitor/README.md @@ -0,0 +1,141 @@ +# 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& 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](../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` 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): + +```json +{ "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). diff --git a/src/InputManager/README.md b/src/InputManager/README.md new file mode 100644 index 0000000..f89e933 --- /dev/null +++ b/src/InputManager/README.md @@ -0,0 +1,67 @@ +# InputManager + +## Summary + +InputManager handles all physical button inputs on the Vesper hardware. It implements a non-blocking state machine with software debouncing and long-press detection, firing registered callbacks on press or long-press events. Currently it manages one input: the factory reset button on GPIO 0. The subsystem runs a dedicated FreeRTOS task that polls GPIO state at 10 ms intervals, keeping input handling entirely off the main loop and isolated from time-critical subsystems. + +--- + +## Public API + +| Method | Description | +|---|---| +| `bool begin()` | Configures GPIO pins and starts the polling task. Returns `false` if task creation fails. | +| `void end()` | Deletes the polling task and marks the subsystem uninitialized. | +| `void setFactoryResetPressCallback(ButtonCallback cb)` | Registers a callback fired on a confirmed short press of the factory reset button (released before the long-press threshold). | +| `void setFactoryResetLongPressCallback(ButtonCallback cb)` | Registers a callback fired when the factory reset button is held for 10 seconds. | +| `bool isFactoryResetPressed() const` | Returns `true` if the factory reset button is in any pressed state (debouncing, held, or long-pressed). | +| `uint32_t getFactoryResetPressDuration() const` | Returns how long the factory reset button has been held, in milliseconds. Returns 0 if not pressed. | +| `bool isHealthy() const` | Returns `true` if `begin()` completed successfully and the task is running. | + +`ButtonCallback` is `std::function`. + +--- + +## Initialization + +InputManager is instantiated as a global in `main.cpp` and initialized near the top of `setup()`, immediately after `configManager.begin()`: + +```cpp +inputManager.begin(); +inputManager.setFactoryResetLongPressCallback(handleFactoryReset); +``` + +`handleFactoryReset` calls `configManager.resetAllToDefaults()` then `ESP.restart()`, so `ConfigManager` must be initialized before the callback is registered. No other subsystem dependencies are required for `begin()` itself. + +The subsystem does not need to be initialized before networking, communication, or any other subsystem. Its only constraint is that `ConfigManager` is ready if the long-press callback touches it. + +--- + +## Dependencies + +| Dependency | Reason | +|---|---| +| Arduino framework (`Arduino.h`) | `pinMode`, `digitalRead`, `millis` | +| FreeRTOS (`xTaskCreate`, `vTaskDelayUntil`) | Polling task lifecycle | +| `Logging/Logging.hpp` | `LOG_*` macros | +| `ConfigManager` | Indirect — required by the `handleFactoryReset` callback registered in `main.cpp`, not by InputManager itself | + +No external libraries, I2C peripherals, SD card, or network stack are required. + +--- + +## Gotchas / Notes + +**Singleton pattern.** The constructor assigns `this` to the static `InputManager::_instance` pointer. Only one instance should exist at a time. Constructing a second instance will overwrite the pointer, which is harmless in practice but indicates a design assumption of a single global instance. + +**Short-press fires on release.** The `onPress` callback is invoked after the button is released and the release debounce passes, not on the initial press. The `onLongPress` callback fires immediately when the 10-second threshold is reached, while the button is still held. + +**Long press suppresses short press.** If the long-press threshold is crossed, `onPress` is never called for that press cycle. The two callbacks are mutually exclusive per press. + +**Callbacks execute in the polling task context.** Both `onPress` and `onLongPress` are called directly from the `InputTask` FreeRTOS task (stack: 4096 bytes, priority 2). The factory reset callback blocks this task while `configManager.resetAllToDefaults()` runs and then calls `ESP.restart()`, so blocking behavior is acceptable for that use case. Any future callbacks should be kept short or should defer work to a separate task. + +**GPIO 0 is the ESP32 boot strapping pin.** Holding GPIO 0 low during reset enters the ESP32 bootloader. This is intentional for factory reset but means the button must not be pressed during power-on or OTA reboot if the bootloader is not desired. + +**No ISR — polling only.** Input detection is purely poll-based at 10 ms intervals. The debounce window is 50 ms (5 poll cycles), which is sufficient to filter typical contact bounce. There is no interrupt-driven wakeup from deep sleep. + +**Not thread-safe for callback registration.** `setFactoryResetPressCallback` and `setFactoryResetLongPressCallback` write directly to the `ButtonConfig` struct that the polling task reads. Register callbacks before calling `begin()`, or accept that a race is possible if registering after the task starts. diff --git a/src/Logging/README.md b/src/Logging/README.md new file mode 100644 index 0000000..6a84f9d --- /dev/null +++ b/src/Logging/README.md @@ -0,0 +1,170 @@ +# Logging + +Centralized, subsystem-aware logging layer for Vesper firmware. It routes log messages to up to three independent output channels — Serial (USB), MQTT, and SD card — each with its own configurable log level. Per-subsystem tag overrides let individual subsystems be silenced or restricted on a specific channel without affecting others (e.g. silencing `MQTTClient` on the MQTT channel to prevent recursion). The class is fully static; there is no instance to manage. + +--- + +## Public API + +### Log emission + +Each `.cpp` file defines `#define TAG "SubsystemName"` at the top and calls the macros below. The macros are thin wrappers around the static methods. + +| Macro / Method | Description | +|---|---| +| `LOG_ERROR(tag, fmt, ...)` / `Logging::error(tag, fmt, ...)` | Emit at ERROR level | +| `LOG_WARNING(tag, fmt, ...)` / `Logging::warning(tag, fmt, ...)` | Emit at WARNING level | +| `LOG_INFO(tag, fmt, ...)` / `Logging::info(tag, fmt, ...)` | Emit at INFO level | +| `LOG_DEBUG(tag, fmt, ...)` / `Logging::debug(tag, fmt, ...)` | Emit at DEBUG level | +| `LOG_VERBOSE(tag, fmt, ...)` / `Logging::verbose(tag, fmt, ...)` | Emit at VERBOSE level | + +`fmt` is a `printf`-style format string. The formatted message is capped at 512 bytes internally. + +### Global channel levels + +| Method | Description | +|---|---| +| `Logging::setSerialLevel(level)` | Set baseline level for Serial output | +| `Logging::setMqttLevel(level)` | Set baseline level for MQTT output | +| `Logging::setSdLevel(level)` | Set baseline level for SD output | +| `Logging::getSerialLevel()` | Return current Serial level | +| `Logging::getMqttLevel()` | Return current MQTT level | +| `Logging::getSdLevel()` | Return current SD level | +| `Logging::setLevel(level)` | Legacy alias for `setSerialLevel` | +| `Logging::getLevel()` | Legacy alias for `getSerialLevel` | +| `Logging::setMqttLogLevel(level)` | Legacy alias for `setMqttLevel` | +| `Logging::getMqttLogLevel()` | Legacy alias for `getMqttLevel` | + +### Per-subsystem overrides + +| Method | Description | +|---|---| +| `Logging::setSubsystemSerialLevel(tag, level)` | Cap or silence `tag` on Serial only | +| `Logging::setSubsystemMqttLevel(tag, level)` | Cap or silence `tag` on MQTT only | +| `Logging::setSubsystemSdLevel(tag, level)` | Cap or silence `tag` on SD only | + +Pass `Logging::NONE` to fully suppress a tag on a channel. The override map is keyed by the exact `tag` string. + +### Output channel registration + +| Method | Description | +|---|---| +| `Logging::setMqttPublishCallback(callback, logTopic)` | Register the function used to publish log messages over MQTT, and the topic to publish to | +| `Logging::setSdWriteCallback(callback)` | Register the function used to append log lines to the SD log file | + +Both channels start disabled (callbacks are `nullptr`). Output on a channel is silenced until the relevant callback is registered. + +### Utilities + +| Method | Description | +|---|---| +| `Logging::isLevelEnabled(level)` | Returns `true` if Serial level is at or above `level` (checks Serial only) | +| `Logging::levelToString(level)` | Returns a human-readable string for a `LogLevel` value | + +--- + +## Log levels + +| Value | Name | Integer | +|---|---|---| +| `NONE` | No output | 0 | +| `ERROR` | Errors only | 1 | +| `WARNING` | Warnings and errors | 2 | +| `INFO` | Info, warnings, errors | 3 | +| `DEBUG` | Debug detail | 4 | +| `VERBOSE` | Everything | 5 | + +--- + +## Output formats + +**Serial:** `[LEVL][Tag] message\n` + +**MQTT payload (JSON):** +```json +{"level":"WARNING","subsystem":"BellEngine","message":"...","timestamp":12345} +``` +`timestamp` is `millis()` (ms since boot), not wall-clock time. + +**SD line (plain text):** `[LEVL][Tag] message (12345ms)` + +--- + +## Initialization + +Logging has no `begin()` call. Static defaults at startup are: + +- Serial: `VERBOSE` +- MQTT: `NONE` +- SD: `NONE` + +### Step 1 — Apply Serial level from config (`main.cpp`, early in `setup`) + +```cpp +Logging::setLevel((Logging::LogLevel)configManager.getGeneralConfig().serialLogLevel); +``` + +This happens immediately after `configManager.begin()`, before any other subsystem is initialized, so all subsequent boot messages respect the configured level. + +### Step 2 — Register MQTT and SD callbacks (`CommunicationRouter::begin`) + +`CommunicationRouter::begin()` registers both callbacks and applies all three channel levels from `ConfigManager`: + +```cpp +Logging::setMqttPublishCallback(..., "vesper//logs"); +Logging::setSdWriteCallback([fm](const String& line) { fm->appendLine("/logs/vesper.log", line); }); +Logging::setSerialLevel(...); +Logging::setMqttLevel(...); +Logging::setSdLevel(...); +``` + +It also sets the default per-subsystem MQTT suppressions to prevent feedback loops: + +```cpp +Logging::setSubsystemMqttLevel("MQTTClient", Logging::NONE); +Logging::setSubsystemMqttLevel("CommRouter", Logging::WARNING); +Logging::setSubsystemMqttLevel("Logger", Logging::NONE); +``` + +MQTT and SD output are therefore inactive until `CommunicationRouter::begin()` runs. + +### Runtime level changes + +`LoggingHandler` handles the `log.set_serial`, `log.set_mqtt`, and `log.set_sd` commands routed through the `CommandBus`. These persist the new level to `ConfigManager` (saved to SD) and apply it immediately. + +Command example: +```json +{ "v": 2, "cmd": "log.set_mqtt", "contents": { "level": 3 } } +``` + +--- + +## Dependencies + +| Dependency | Why | +|---|---| +| `Arduino.h` / `Serial` | Serial output channel | +| `ConfigManager` | Reads initial log levels at boot; saves runtime changes | +| `CommunicationRouter` | Registers the MQTT publish callback and SD write callback | +| `FileManager` | Provides `appendLine()` used by the SD callback | +| `std::map` | Per-subsystem override storage | + +`Logging.hpp` includes `` and `` directly. No FreeRTOS headers are included; the class does not create any tasks or timers. + +--- + +## Gotchas / Notes + +**Thread safety.** The class has no mutex protection. The per-channel re-entrancy guards (`isPublishing`, `isWriting`) are `static bool` flags, not atomics. These prevent log-of-a-log recursion within a single call path but are not safe across concurrent FreeRTOS tasks. In practice, Serial output is the only channel exercised from multiple tasks simultaneously (e.g. BellEngine on Core 1, MQTT task on Core 0). Serial's hardware FIFO makes this tolerable in practice, but strictly speaking concurrent calls are a data race. + +**MQTT feedback loop.** Any subsystem whose logs are emitted on the MQTT channel must not call `Logging` from within the MQTT publish path. `MQTTClient` and `CommRouter` are silenced on MQTT by default for this reason. The `isPublishing` guard is a secondary safeguard. + +**SD writes are synchronous.** `setSdWriteCallback` delegates to `FileManager::appendLine`, which acquires the SD card mutex. Calling `LOG_*` at high frequency with SD enabled can stall the calling task for the duration of the SD write. + +**`isLevelEnabled` checks Serial only.** If you need to guard an expensive log-string build (e.g. formatting a large buffer before calling `LOG_DEBUG`), use `Logging::isLevelEnabled(Logging::DEBUG)`. Be aware this ignores MQTT and SD levels. + +**Message truncation.** The internal format buffer is 512 bytes. Messages longer than 511 characters are silently truncated by `vsnprintf`. + +**No timestamps beyond `millis()`.** MQTT and SD payloads use `millis()` (ms since boot). Wall-clock timestamps are not included; correlate with NTP-synced log entries from the backend if absolute time is needed. + +**MQTT and SD channels are disabled by default.** Both callbacks start as `nullptr`. Messages targeting those channels are dropped silently until `CommunicationRouter::begin()` registers the callbacks. Any logs emitted before that point (early boot) are Serial-only regardless of configured levels. diff --git a/src/Networking/README.md b/src/Networking/README.md new file mode 100644 index 0000000..1a81cac --- /dev/null +++ b/src/Networking/README.md @@ -0,0 +1,100 @@ +# Networking + +## Summary + +`Networking` manages all WiFi connectivity for the Vesper device. It owns the connection lifecycle — initial association, timeout detection, automatic reconnection, and fallback to a WiFiManager captive portal or permanent AP mode — and exposes a minimal callback interface so the rest of the firmware reacts to link-up/link-down events without polling. Ethernet hardware is present in the source but permanently disabled as of firmware v138; the code paths are commented out and will not execute. + +--- + +## Public API + +| Method | Description | +|---|---| +| `Networking(ConfigManager& configManager)` | Constructor. Allocates `WiFiManager`, registers static instance pointer. | +| `void begin()` | Initializes the FreeRTOS reconnection timer, registers the Arduino WiFi event handler, and starts the first connection attempt (or permanent AP mode if configured). | +| `bool isConnected() const` | Returns `true` if any transport (`WIFI` or `AP`) has an active connection. | +| `String getLocalIP() const` | Returns the current IP address as a string; `"0.0.0.0"` when disconnected. | +| `String getGateway() const` | Returns the gateway IP string for the active WiFi connection. | +| `ConnectionType getActiveConnection() const` | Returns the `ConnectionType` enum value: `NONE`, `WIFI`, or `AP`. | +| `NetworkState getState() const` | Returns the full `NetworkState` enum for more granular status inspection. | +| `void setNetworkCallbacks(onConnected, onDisconnected)` | Registers `std::function` callbacks fired on link-up and link-down events. Must be called before the first connection completes to avoid missing the event. | +| `void forceReconnect()` | Tears down the current WiFi connection and restarts the connection sequence. Intended for debug/testing; blocks for ~1 second during teardown. | +| `void startPermanentAPMode()` | Switches to a fixed AP at `192.168.4.1` using the SSID/password from `NetworkConfig`. Sets state to `AP_MODE_PERMANENT`. | +| `bool isInAPMode() const` | Returns `true` when state is `AP_MODE_PERMANENT`. | +| `bool isHealthy() const` | Returns `true` if connected with a valid IP and, for WiFi, RSSI >= -80 dBm. Used by `HealthMonitor`. | + +### Enumerations + +**`NetworkState`** + +| Value | Meaning | +|---|---| +| `DISCONNECTED` | No active connection, not attempting | +| `CONNECTING_ETHERNET` | Ethernet attempt in progress (disabled, unused) | +| `CONNECTING_WIFI` | WiFi association in progress | +| `WIFI_PORTAL_MODE` | WiFiManager captive portal is active | +| `CONNECTED_ETHERNET` | Ethernet up (disabled, unused) | +| `CONNECTED_WIFI` | WiFi up and IP assigned | +| `RECONNECTING` | Transitional state during `forceReconnect()` | +| `AP_MODE_PERMANENT` | Device is running as a standalone AP | + +**`ConnectionType`**: `NONE`, `ETHERNET`, `WIFI`, `AP` + +--- + +## Initialization + +`Networking` is constructed with a reference to `ConfigManager`, then initialized in `setup()` after `ConfigManager::begin()` has run (so network settings from SD are available): + +```cpp +Networking networking(configManager); +// ... +networking.begin(); +``` + +Network callbacks **must be registered after `begin()`** and before `setup()` returns, because a fast WiFi reconnect can fire the connected callback during the same `setup()` call: + +```cpp +networking.setNetworkCallbacks( + []() { communication.onNetworkConnected(); /* start server, NTP, etc. */ }, + []() { communication.onNetworkDisconnected(); } +); + +// Handle the case where WiFi was already up before callbacks were registered: +if (networking.isConnected()) { + communication.onNetworkConnected(); +} +``` + +The `AsyncWebServer` must **not** be started before the `onNetworkConnected` callback fires, because `WiFiManager` binds port 80 during portal mode. Starting the server before the portal closes causes a port conflict. + +--- + +## Dependencies + +| Dependency | Role | +|---|---| +| `ConfigManager` | Reads `NetworkConfig` (SSID, PSK, static IP, hostname, AP credentials, `permanentAPMode` flag) | +| `WiFiManager` (library) | Handles captive-portal credential entry when saved credentials are absent or fail repeatedly | +| `WiFi` (Arduino/ESP32) | Underlying WiFi driver; event handler registered via `WiFi.onEvent()` | +| FreeRTOS | One-shot `TimerHandle_t` for reconnection scheduling; reconnect logic runs in a short-lived task (`netRecon`) | + +--- + +## Gotchas / Notes + +**Ethernet is disabled.** The code contains Ethernet paths (`ARDUINO_EVENT_ETH_*` handlers, `startEthernetConnection`, `onEthernetConnected`, etc.) that are entirely commented out or guarded with early returns. Enabling Ethernet requires uncommenting the `ETH.begin(...)` call in `begin()` and restoring the disabled code blocks. + +**Static `_instance` pointer.** The event handler is a static function that dispatches through `Networking::_instance`. Only one `Networking` instance should exist at runtime. Constructing a second instance logs a warning and overwrites the pointer, which will break event dispatch for the original instance. + +**Reconnection timer runs in a task.** `reconnectionTimerCallback` is called from the FreeRTOS timer service task (2 KB stack). To avoid stack overflow, the callback immediately spawns a `netRecon` task (3072 bytes) which calls `handleReconnection()` and deletes itself. Do not add blocking or stack-heavy logic to the timer callback directly. + +**Portal fallback threshold.** After `MAX_WIFI_FAILURES` (3) consecutive 10-second timeouts during the boot sequence, `handleReconnection()` opens the WiFiManager captive portal. After boot is complete (`_bootSequenceComplete == true`), it instead keeps retrying indefinitely without opening the portal. + +**`forceReconnect()` is blocking.** It calls `delay(1000)` synchronously. Do not call it from a timer callback, ISR, or any task with a tight deadline. + +**AP mode and IP addresses.** In `AP_MODE_PERMANENT`, `getLocalIP()` returns `WiFi.softAPIP()` (`192.168.4.1`). In STA mode it returns `WiFi.localIP()`. `getGateway()` always returns `"0.0.0.0"` in AP mode. + +**`isHealthy()` signal threshold.** RSSI < -80 dBm is treated as unhealthy. This can cause `HealthMonitor` to flag the subsystem in marginal RF environments even when packets are flowing normally. + +**`NetworkConfig` is loaded from SD card.** If the SD card is absent or unreadable at boot, `ConfigManager` falls back to compiled-in defaults (`defaultWifiSsid = "BellSystemsInfra"`). The device will still attempt to connect; it will not stall waiting for SD. diff --git a/src/OTAManager/README.md b/src/OTAManager/README.md new file mode 100644 index 0000000..0d85e7e --- /dev/null +++ b/src/OTAManager/README.md @@ -0,0 +1,145 @@ +# OTAManager + +OTAManager handles over-the-air firmware updates for Vesper devices. It fetches a `metadata.json` manifest from one or more configured update servers, validates the available version against the running firmware, and streams the binary directly into the OTA flash partition using the ESP-IDF `Update` library. Updates can be triggered automatically at boot (emergency/mandatory only), on a nightly schedule (3:00 AM, emergency only), or on-demand via the communication layer. After a successful flash, the device saves the new version to NVS and reboots. + +--- + +## Public API + +| Method | Description | +|---|---| +| `OTAManager(ConfigManager& configManager)` | Constructor. Takes a reference to ConfigManager; all other dependencies are injected post-construction. | +| `void begin()` | Allocates the worker task (8 KB stack, Core 0), the binary semaphore, the per-minute scheduled-check timer, and the one-shot 5-second boot-check timer. Must be called after `ConfigManager` is initialized. | +| `void setFileManager(FileManager* fm)` | Injects the FileManager dependency. Required before `isHealthy()` returns true and before any SD-based code paths run. | +| `void setPlayer(Player* player)` | Injects the Player reference. Used to gate updates — updates are blocked if the player is active. | +| `void setTimeKeeper(Timekeeper* tk)` | Injects the Timekeeper reference. Its clock updates are paused during the flash write to reduce contention. | +| `void setTelemetry(Telemetry* telemetry)` | Injects the Telemetry reference. Telemetry is paused during the flash write. | +| `void checkForUpdates()` | Checks the `stable` channel for a newer version. Auto-applies if the update is flagged emergency or mandatory. | +| `void checkForUpdates(const String& channel)` | Same as above but against the specified channel. | +| `void checkForEmergencyUpdates()` | Checks `stable` and applies immediately only if the `emergency` flag is set in metadata. Used by the 3:00 AM scheduled timer. | +| `void update()` | Applies the most recently checked update from the `stable` channel. Reboots on success. | +| `void update(const String& channel)` | Applies the most recently checked update from the specified channel. Reboots on success. | +| `void checkFirmwareUpdateFromSD()` | Checks the SD card for `/firmware/update.bin`. If found (and a matching `.sha256` file exists), installs it. Reboots on success. | +| `bool performManualUpdate()` | Checks `stable` channel then applies if an update is available. Returns `false` if none found or already in progress. | +| `bool performManualUpdate(const String& channel)` | Same as above for a specific channel. | +| `bool performCustomUpdate(const String& firmwareUrl, const String& checksum, size_t fileSize, uint16_t version)` | Flashes firmware from an arbitrary URL. `checksum` and `fileSize` are optional (pass `""` / `0` to skip). `version` is written to NVS on success. Blocked if the player is active. | +| `String getHardwareVariant() const` | Returns the hardware variant string from ConfigManager (e.g. `"VS"`). | +| `void setHardwareVariant(const String& variant)` | **Deprecated.** Use `ConfigManager::setHardwareVariant` instead. Logs a warning and does nothing. | +| `Status getStatus() const` | Returns the current `Status` enum value (`IDLE`, `CHECKING_VERSION`, `DOWNLOADING`, `INSTALLING`, `SUCCESS`, `FAILED`). | +| `ErrorCode getLastError() const` | Returns the most recent `ErrorCode`. Useful after a `FAILED` status. | +| `uint16_t getCurrentVersion() const` | Returns the running firmware version as a `uint16_t` (reads `ConfigManager::getFwVersion()` and calls `.toInt()`). | +| `uint16_t getAvailableVersion() const` | Returns the version number from the last successful metadata fetch. | +| `bool isUpdateAvailable() const` | `true` if the last `checkForUpdates` call found a newer version. | +| `void setProgressCallback(ProgressCallback callback)` | Registers a `(size_t current, size_t total)` callback, fired during SD-based downloads. Not called during direct-to-flash downloads. | +| `void setStatusCallback(StatusCallback callback)` | Registers a `(Status, ErrorCode)` callback fired on every status transition. | +| `bool isHealthy() const` | Returns `true` if FileManager is set and healthy, status is not `FAILED`, hardware variant and firmware version are valid, update servers are configured, and the scheduled timer is active. | + +--- + +## Initialization + +`OTAManager` is constructed as a global in [main.cpp](../main.cpp) with a reference to `configManager`: + +```cpp +OTAManager otaManager(configManager); +``` + +After `configManager.begin()` and before `otaManager.begin()`, the optional dependencies are injected: + +```cpp +otaManager.begin(); +otaManager.setFileManager(&fileManager); +otaManager.setPlayer(&player); +otaManager.setTimeKeeper(&timekeeper); +otaManager.setTelemetry(&telemetry); +``` + +`healthMonitor.setOTAManager(&otaManager)` is called afterwards to register it for periodic health polling. + +`begin()` must be called before any update methods. The optional setters (`setFileManager`, `setPlayer`, etc.) can be called after `begin()` — the worker task and timers will already be running, but the 5-second initial-check timer fires after boot so there is enough time to inject dependencies before the first check runs. + +--- + +## Dependencies + +| Dependency | Type | Purpose | +|---|---|---| +| `ConfigManager` | Required (constructor) | Hardware variant, firmware version, update server URLs, update config (timeout, retries) | +| `FileManager` | Required (setter) | SD card path helpers; health check delegates to `FileManager::isHealthy()` | +| `Player` | Optional (setter) | Blocks updates while audio playback is active | +| `Timekeeper` | Optional (setter) | Paused during flash write to reduce timer interrupt load | +| `Telemetry` | Optional (setter) | Paused during flash write | +| `SDCardMutex` | Internal (singleton) | Guards concurrent SD access in the legacy SD-download code path | +| `Update` (ESP-IDF) | Internal | Writes firmware to the OTA flash partition | +| `HTTPClient` | Internal | Downloads metadata and firmware | +| `mbedtls` | Internal | SHA-256 checksum calculation for SD-based installs | + +--- + +## Metadata format + +`checkVersion()` fetches `metadata.json` from: + +``` +/ota///metadata.json +``` + +Expected fields: + +| Field | Type | Notes | +|---|---|---| +| `version` | `uint16_t` | Build number (e.g. `138`) | +| `channel` | `String` | Must match the requested channel or the server is skipped | +| `hardwareVariant` | `String` | Must match `ConfigManager::getHardwareVariant()` if present | +| `checksum` | `String` | 64-character SHA-256 hex string | +| `fileSize` | `size_t` | Expected byte count; validated against `Content-Length` | +| `minVersion` | `uint16_t` | Minimum version that can upgrade directly; `0` = no restriction | +| `mandatory` | `bool` | Applied automatically at boot-time check | +| `emergency` | `bool` | Applied automatically at boot and at the 3:00 AM scheduled check | + +--- + +## Communication interface + +OTA updates are triggered through `FirmwareHandler`, which is wired into the `CommunicationRouter`. Two commands are relevant: + +**`ota.update`** — triggers a channel update: +```json +{ "v": 2, "cmd": "ota.update", "contents": { "channel": "stable" } } +``` +`channel` defaults to `"stable"` if omitted. Blocked if the player is active. + +**`ota.custom`** — flashes from an arbitrary URL: +```json +{ "v": 2, "cmd": "ota.custom", "contents": { + "firmware_url": "http://example.com/firmware.bin", + "checksum": "abc123...", + "file_size": 1234567, + "version": 139 +}} +``` +`checksum`, `file_size`, and `version` are optional. Blocked if the player is active. + +Both commands return a response to the caller before the update begins. If the update succeeds, the device reboots and the caller receives no further response. + +--- + +## Gotchas and notes + +**Direct-to-flash vs SD-based download.** The current primary code path (`downloadDirectToFlash`) streams HTTP directly into the OTA flash partition using `Update.write()` in 4 KB chunks. The older SD-based path (`downloadToSD` + `installFromSD`) is retained in the code but is not called by the active `downloadAndInstall` method. The SD path includes SHA-256 verification; the direct-to-flash path relies on the ESP32 bootloader's own integrity checks. + +**Timer callbacks are non-blocking.** Both `initialCheckCallback` and `scheduledCheckCallback` run in the FreeRTOS Timer Service task, which has a limited stack. They only set `_pendingWork` and give a semaphore; the actual HTTP work is done in the dedicated `OTA_Worker` task (8 KB stack, Core 0, priority 2). + +**Freeze mode.** During a flash write, `Timekeeper::pauseClockUpdates()` and `Telemetry::pause()` are called. Both are resumed on success or failure before returning. This prevents SD bus contention and reduces timer interrupt interference during the write loop. + +**Watchdog feeding.** The direct-to-flash write loop calls `esp_task_wdt_reset()` every 500 ms. If the firmware binary is unexpectedly large or the download stalls, the watchdog will eventually fire. + +**Scheduled check timing.** The `_scheduledCheckTimer` fires every 60 seconds. The callback checks `localtime` and only proceeds at exactly 03:00. The minute window means the check fires once at 3:00:00–3:00:59. NTP must be synchronized for this to land at the right time. + +**`minVersion` enforcement.** If the server specifies a `minVersion` greater than the currently running version, the update is rejected with `VERSION_TOO_LOW`. An intermediate update must be applied first. This is checked per-server; the manager will try remaining servers in the list before giving up. + +**Multiple update servers.** `ConfigManager::getUpdateServers()` returns an ordered list. Each server is tried in sequence with configurable retry count and exponential backoff. The first server to return a valid `200 OK` with a parseable, consistent metadata response is used. + +**`isHealthy()` requires the scheduled timer to be active.** If `begin()` fails to create the timer (e.g., insufficient FreeRTOS heap), `isHealthy()` will return `false` indefinitely. Check the serial log for `"Failed to create OTA scheduled check timer!"`. + +**`setHardwareVariant` is a no-op.** The method exists for API compatibility but logs a warning and does nothing. Hardware variant is read from NVS via `ConfigManager`. diff --git a/src/OutputManager/README.md b/src/OutputManager/README.md new file mode 100644 index 0000000..6e7e5fa --- /dev/null +++ b/src/OutputManager/README.md @@ -0,0 +1,109 @@ +# OutputManager + +## Summary + +OutputManager is the hardware abstraction layer for all relay/output control in Vesper. It decouples the rest of the firmware from the specifics of the I2C GPIO expander hardware, presenting a uniform virtual-output model that BellEngine, TimeKeeper, and the RelayHandler command layer all call into. It manages both bell outputs (indexed by logical bell number, resolved to physical pins via ConfigManager) and clock outputs (C1/C2, resolved from clock configuration). Automatic timed de-energization is handled internally by a background FreeRTOS task, so callers never need to schedule their own shutoff. + +--- + +## Public API + +### `OutputManager` (abstract base) + +| Method | Description | +|---|---| +| `virtual bool initialize() = 0` | Initialize hardware. Must be called before any output operations. Returns `false` on failure. | +| `virtual void fireOutput(uint8_t outputIndex)` | Energize a virtual output immediately. No automatic shutoff. | +| `virtual void extinguishOutput(uint8_t outputIndex)` | De-energize a virtual output immediately. | +| `virtual void fireOutputForDuration(uint8_t outputIndex, uint16_t durationMs)` | Energize a virtual output and automatically de-energize it after `durationMs` milliseconds. | +| `virtual void fireOutputsBatch(const std::vector& outputIndices)` | Energize multiple virtual outputs simultaneously. No automatic shutoff. | +| `virtual void extinguishOutputsBatch(const std::vector& outputIndices)` | De-energize multiple virtual outputs simultaneously. | +| `virtual void fireOutputsBatchForDuration(const std::vector>& outputDurations)` | Energize multiple virtual outputs simultaneously, each with its own duration. This is the primary method BellEngine calls for bell strikes. | +| `virtual void emergencyShutdown()` | Immediately de-energize all outputs and clear all pending timers. | +| `virtual bool isInitialized() const` | Returns `true` if hardware initialization succeeded. | +| `virtual uint8_t getMaxOutputs() const` | Returns total number of available virtual outputs. | +| `virtual const char* getHardwareType() const` | Returns a human-readable string describing the hardware configuration (e.g. `"PCF8574 I2C Expander (6/8 outputs)"`). | +| `uint8_t getPhysicalOutput(uint8_t virtualOutput) const` | Resolves a logical bell index (0–15) to its configured physical output pin via ConfigManager. Returns `255` if the bell is unconfigured/disabled. Used by BellEngine before firing. | +| `virtual void fireClockOutput(uint8_t virtualOutput, uint16_t durationMs)` | Fire a clock output by virtual index: `0` = C1, `1` = C2. Resolves the physical pin from ConfigManager's clock output configuration. Used by TimeKeeper. | +| `virtual uint8_t getTotalVirtualOutputs() const` | Returns `getMaxOutputs()`. Alias used by TimeKeeper. | +| `virtual bool isHealthy() const` | Returns `true` if initialized, ConfigManager is set, the duration task is running, and output count is sane. Used by HealthMonitor. | +| `virtual void setConfigManager(ConfigManager* config)` | Inject the ConfigManager reference. Must be called before `initialize()`. | + +### `PCF8574OutputManager` (concrete — I2C expander) + +Inherits all of the above. Additional methods: + +| Method | Description | +|---|---| +| `PCF8574OutputManager(uint8_t i2cAddress, ChipType chipType, uint8_t activeOutputs)` | Single-chip constructor. `activeOutputs` limits how many of the chip's pins are exposed as virtual outputs. | +| `PCF8574OutputManager(uint8_t addr1, ChipType chip1, uint8_t active1, uint8_t addr2, ChipType chip2, uint8_t active2)` | Dual-chip constructor. Virtual output indices are contiguous: chip 1 first, chip 2 second. | +| `uint8_t getChipCount() const` | Returns number of configured chips (1 or 2). | +| `ChipConfig getChipConfig(uint8_t chipIndex) const` | Returns configuration struct for a given chip slot. | +| `VirtualOutputInfo getVirtualOutputInfo(uint8_t virtualOutput) const` | Returns the chip index and local pin for a given virtual output index. Useful for diagnostics. | + +--- + +## Initialization + +`outputManager` is a global instance in `main.cpp` constructed before `setup()` runs. The setup sequence that matters: + +```cpp +Wire.begin(4, 15); // I2C must be up first +outputManager.setConfigManager(&configManager); // inject config before init +outputManager.initialize(); // start hardware + duration task +healthMonitor.setOutputManager(&outputManager); +bellEngine.begin(); // depends on outputManager being ready +timekeeper.setOutputManager(&outputManager); +communication.setOutputManagerReference(&outputManager); +``` + +`initialize()` runs a 100 ms stabilization delay, then calls `emergencyShutdown()` to ensure all outputs start in the de-energized (HIGH) state, and starts the background duration management task. Calling any fire method before `initialize()` is a no-op with an error log. + +The Vesper hardware configuration (Kincony KC868-A6, 6 active outputs on a single PCF8574 at address `0x24`): + +```cpp +PCF8574OutputManager outputManager(0x24, ChipType::PCF8574, 6); +``` + +--- + +## Dependencies + +| Dependency | Why | +|---|---| +| `Wire` (I2C) | Communication bus to PCF8574/PCF8575 chips. Must be initialized with `Wire.begin()` before `initialize()`. | +| `Adafruit_PCF8574` / `Adafruit_PCF8575` | Low-level I2C driver libraries for the expander chips. | +| `ConfigManager` | Resolves logical bell indices to physical output pins (`getBellOutput()`), and reads clock output assignments (`getClockOutput1()`, `getClockOutput2()`). | +| `FreeRTOS` | The duration management task (`OutputDuration`) runs on Core 1 at priority 5 with a 4 KB stack. Created during `initialize()`. | +| `esp_timer` | `esp_timer_get_time()` provides microsecond timestamps for duration tracking. | + +--- + +## Gotchas / Notes + +**Active-LOW relay logic.** The PCF8574/PCF8575 implementation inverts the output state: `fireOutput()` writes `LOW` to the I2C pin, `extinguishOutput()` writes `HIGH`. All outputs are set `HIGH` (inactive) on initialization and emergency shutdown. + +**Virtual vs. physical output indexing.** `fireOutput(n)` treats `n` as a direct virtual output index (chip pin 0–N). `getPhysicalOutput(bellIndex)` reads the bell-to-output mapping from ConfigManager and returns the physical (virtual) index — this is what BellEngine calls before passing to `fireOutputsBatchForDuration`. A return value of `255` means the bell is not configured; BellEngine skips it. + +**Bell index vs. virtual output.** There are up to 16 bells (indices 0–15), each mapped to a virtual output (0–N) in config. Virtual output indices map directly to chip pins. These are the same address space — the "virtual output" number is what gets written to the chip. + +**Duration task processes one expiry per 1 ms tick.** `processExpiredOutputs()` exits after the first expired entry it finds. If multiple outputs expire simultaneously, they are processed in successive 1 ms ticks, not atomically. This introduces at most ~1 ms of extra energization per simultaneous expiry beyond the first. + +**Critical section scope.** The `_outputMutex` spinlock (`portMUX_TYPE`) is held during `_activeOutputs` reads and writes. `extinguishOutput()` is called from the duration task after the lock is released — the lock must not be held when calling it. Do not call `fireOutputForDuration` or `emergencyShutdown` from an ISR context. + +**Chip instances are static locals.** `initializeChip()` uses `static Adafruit_PCF8574 pcf8574Instances[MAX_CHIPS]` and `static Adafruit_PCF8575 pcf8575Instances[MAX_CHIPS]` inside the function. The Adafruit driver objects are never destructed, and `PCF8574OutputManager` can only ever be meaningfully instantiated once — a second instance would alias the same static storage. + +**No SD card required.** OutputManager has no direct dependency on the SD card. All configuration reads go through ConfigManager, which caches values in RAM after its own initialization. + +**Destruction order.** `~BellEngine()` calls `emergencyShutdown()` on OutputManager. BellEngine must be destroyed before OutputManager. This is consistent with global construction order in `main.cpp` (BellEngine is declared after `outputManager` and is therefore destroyed first). + +**HealthMonitor integration.** `isHealthy()` checks: `_initialized`, `_configManager != nullptr`, `_durationTaskHandle != nullptr`, `getMaxOutputs()` in range 1–64, all chips initialized with valid `chipInstance` pointers, I2C addresses in `0x20`–`0x27`, and `_totalOutputs` consistent with per-chip active output counts. + +**Remote commands (v2 format).** The RelayHandler exposes OutputManager functionality over MQTT/WebSocket/HTTP: + +| Command | Description | +|---|---| +| `relay.test_output` | Fire a single physical output for a given duration. Player must be stopped. `contents: { "output": 0, "duration_ms": 500 }` | +| `relay.set_outputs` | Update bell-to-output mappings in ConfigManager and save to SD. `contents: { "bells": { "0": 2, "1": 3 } }` | +| `relay.set_durations` | Update per-bell strike durations in ConfigManager and save to SD. `contents: { "bells": { "0": 150, "1": 200 } }` | +| `relay.get_config` | Returns current output and duration mappings for all 16 bells. | diff --git a/src/Player/README.md b/src/Player/README.md new file mode 100644 index 0000000..b970975 --- /dev/null +++ b/src/Player/README.md @@ -0,0 +1,141 @@ +# Player + +## Summary + +Player is the melody playback controller for Vesper. It sits between the communication layer and the BellEngine: it receives play/stop commands (with melody metadata and timing parameters) from `PlaybackHandler`, loads the corresponding melody binary into RAM, configures BellEngine, and manages the full playback lifecycle — including segment looping, inter-segment pauses, and total-duration enforcement. It does not generate bell output directly; that is BellEngine's job. Player owns the timing policy (how long and in what pattern the melody runs) while BellEngine owns the precision strike scheduling. + +--- + +## Public API + +### Initialization and dependency wiring + +| Method | Description | +|---|---| +| `Player()` | Default constructor. All dependency pointers are null; call `setDependencies()` and the individual setters before `begin()`. | +| `Player(CommunicationRouter*, FileManager*)` | Constructor with the two mandatory dependencies pre-wired. | +| `void setDependencies(CommunicationRouter*, FileManager*)` | Set communication and file manager references after default construction. | +| `void setBellEngine(BellEngine*)` | Wire the timing engine. Required before `play()` will do anything. | +| `void setTelemetry(Telemetry*)` | Wire the telemetry subsystem for strike-counter persistence on stop. | +| `void setTimekeeper(Timekeeper*)` | Wire the Timekeeper so that active clock alerts are interrupted when manual playback starts. | +| `void begin()` | Creates and starts the 500 ms periodic FreeRTOS timer that drives duration/pause/resume logic. Must be called once in `setup()`. | + +### Playback control + +| Method | Description | +|---|---| +| `bool command(JsonVariant data)` | High-level entry point called by `PlaybackHandler`. Parses melody attributes from the JSON payload, loads the melody, then dispatches to `play()` or `forceStop()` based on `action`. Returns `true` on success. | +| `void play()` | Starts BellEngine with the currently-loaded melody steps and transitions state to `PLAYING`. Interrupts any active Timekeeper clock alert. Does nothing if `_melodySteps` is empty. | +| `void stop()` | Soft stop: signals BellEngine to stop after the current loop completes and sets state to `STOPPING`. If already paused, stops immediately. | +| `void forceStop()` | Hard stop: calls `BellEngine::emergencyStop()`, sets state to `STOPPED` immediately, and persists strike counters via Telemetry. Used by the overload-protection path in Telemetry and by `command()` on `action == "stop"`. | +| `void pause()` | Marks the player as paused between segments. Called internally by the duration timer; not typically called from outside. | +| `void unpause()` | Resumes playback after a segment pause and resets the segment start timestamp. Called internally by the duration timer. | + +### Melody loading and configuration + +| Method | Description | +|---|---| +| `void setMelodyAttributes(JsonVariant doc)` | Parses and stores all melody metadata fields from a JSON object (name, uid, url, speed, note_assignments, segment_duration, pause_duration, total_duration, continuous_loop). Derives `infinite_play` and adjusts `total_duration` for non-looping playback. | +| `void loadMelodyInRAM()` | Resolves the melody identified by `uid`: first checks the firmware-baked `BuiltInMelodies` library, then falls back to `/melodies/` on the SD card, downloading from `url` via FileManager if the file is absent. Stores steps in `_melodySteps`. | + +### Status queries + +| Method | Description | +|---|---| +| `PlayerStatus getStatus() const` | Returns the current `PlayerStatus` enum value (`STOPPED`, `PLAYING`, `PAUSED`, `STOPPING`). | +| `bool isCurrentlyPlaying() const` | Returns `true` when status is `PLAYING`. | +| `bool isCurrentlyPaused() const` | Returns `true` when status is `PAUSED`. | +| `bool isCurrentlyStopping() const` | Returns `true` when a soft stop has been requested but BellEngine has not yet completed the current loop. | +| `bool isCurrentlyStopped() const` | Returns `true` when fully idle. | +| `uint64_t calculateProjectedRunTime() const` | Returns the projected total wall-clock duration of the current playback in milliseconds (steps × speed, rounded up to a whole number of loops). Returns 0 for infinite or stopped playback. | +| `bool isHealthy() const` | Returns `true` if all required dependency pointers are set, the FreeRTOS timer is active, and the playback state flags are internally consistent. Used by HealthMonitor. | + +### BellEngine callback + +| Method | Description | +|---|---| +| `void onMelodyLoopCompleted()` | Called by BellEngine when a melody loop finishes. If state is `STOPPING`, transitions to `STOPPED` and broadcasts the final status. Also records `segmentCmpltTime` for pause-resume timing. | + +--- + +## Initialization + +Player is constructed as a global in `main.cpp` using the default constructor (`Player player;`), then wired in two phases inside `setup()`: + +1. **Early init** (before `communication.begin()`): + ```cpp + player.begin(); // creates the 500 ms FreeRTOS timer + healthMonitor.setPlayer(&player); + ``` + +2. **Late wiring** (after `communication.begin()`, so CommunicationRouter is fully initialised): + ```cpp + player.setDependencies(&communication, &fileManager); + player.setBellEngine(&bellEngine); + player.setTelemetry(&telemetry); + player.setTimekeeper(&timekeeper); + ``` + +Additionally, Telemetry holds a pointer to `player.isPlaying` (taken before `begin()`) and a `forceStop` callback: +```cpp +telemetry.setPlayerReference(&player.isPlaying); +telemetry.setForceStopCallback([]() { player.forceStop(); }); +``` + +**Dependency order constraints:** +- `BellEngine` must exist before `setBellEngine()` is called. BellEngine is constructed with Player as a constructor argument, so both exist globally before `setup()` runs. +- `CommunicationRouter::begin()` must complete before `setDependencies()` is called (it registers handlers that store a `Player&` reference). +- `FileManager` (and by extension, the SD card mutex) must be initialised before any `loadMelodyInRAM()` call that reaches the SD fallback path. + +--- + +## Dependencies + +| Dependency | Role | +|---|---| +| `BellEngine` | Executes the actual bell strike sequence with microsecond precision. Player configures it with melody data and start/stop signals. | +| `CommunicationRouter` | Receives playback status broadcasts (`broadcastStatus()`) on every state transition. | +| `FileManager` | Downloads melody binaries from a remote URL and saves them to SD when a requested melody is not found locally. | +| `Telemetry` | `saveStrikeCounters()` is called on every hard stop to persist cumulative strike data. Also holds a raw pointer to `player.isPlaying` for load monitoring. | +| `Timekeeper` | `interruptActiveAlert()` is called at the start of `play()` so that a manually-triggered melody pre-empts a scheduled clock alert. | +| `BuiltInMelodies` | Header-only namespace (PROGMEM data) consulted before the SD card for melodies with UIDs prefixed `builtin_`. | +| FreeRTOS | A single periodic software timer (`_durationTimerHandle`, 500 ms period) drives all duration, pause, and resume logic. No dedicated task is created. | +| `SD` / `ArduinoJson` | Used directly inside `loadMelodyInRAM()` for raw file I/O and for the FileManager download fallback. | + +--- + +## Gotchas / Notes + +**State flag duality.** There are two overlapping playback flags: the public `bool isPlaying` and the private `PlayerStatus _status`. Telemetry polls `isPlaying` directly (pointer taken at startup). `_status` is the authoritative state for everything else, including status broadcasts. If you stop playback programmatically, set both consistently — the safest way is always via `forceStop()` or `stop()` rather than touching flags directly. + +**`stop()` vs `forceStop()`.** `stop()` is a soft stop: it signals BellEngine to finish the current loop before halting. State becomes `STOPPING` and the final `STOPPED` broadcast is deferred to `onMelodyLoopCompleted()`. `forceStop()` cuts the output immediately via `BellEngine::emergencyStop()`. Use `forceStop()` for overload/safety shutdowns; use `stop()` for graceful end-of-play. + +**Duration timer runs even when idle.** The 500 ms timer is always active after `begin()`. The callback exits immediately if `isPlaying == false`, so the overhead is negligible, but the timer is not paused between plays. + +**SD access context.** `loadMelodyInRAM()` is called from `command()`, which runs in whatever task delivers the command (MQTT task on Core 0 or the WebSocket handler). If the SD fallback download path is triggered, it performs blocking SD and HTTP I/O in that context. FileManager handles the SD card mutex internally. + +**Note assignments.** `noteAssignments[16]` is a mapping from melody note indices (0–15) to physical bell outputs. It is populated by `setMelodyAttributes()` from the `note_assignments` JSON array and must be configured before `play()` is called. BellEngine reads this mapping when interpreting each step's bitmask. + +**No task created by Player.** Player uses a FreeRTOS software timer (Tmr Svc context, 2 KB stack) rather than a dedicated task. All logic in the timer callback is lightweight (timestamp comparisons, state transitions). Do not perform any blocking operations inside `durationTimerCallback`. + +**Clock alert preemption.** When `play()` is called, it unconditionally calls `_timekeeper->interruptActiveAlert()`. Any ongoing scheduled clock alert (e.g., an hourly chime) will be cut short. This is intentional — manual playback takes priority. + +**Command format.** Commands arrive via the `playback` namespace through `PlaybackHandler`. Example payload: + +```json +{ "v": 2, "cmd": "playback", "contents": { + "action": "play", + "uid": "builtin_doxology_traditional", + "name": "Doxology Traditional", + "speed": 400, + "segment_duration": 30000, + "pause_duration": 5000, + "total_duration": 90000, + "continuous_loop": true, + "note_assignments": [1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] +} } +``` + +Recognized `action` values: `"play"`, `"stop"`. Any other value returns an error from `command()`. + +**Built-in melody UIDs** must start with the prefix `builtin_` (e.g., `builtin_doxology_traditional`). Player checks this prefix first and reads from PROGMEM, bypassing the SD card entirely. diff --git a/src/SDCardMutex/README.md b/src/SDCardMutex/README.md new file mode 100644 index 0000000..dca938f --- /dev/null +++ b/src/SDCardMutex/README.md @@ -0,0 +1,83 @@ +# SDCardMutex + +## Summary + +SDCardMutex provides a global FreeRTOS mutex that serializes all SD card access across the firmware. The ESP32 Arduino SD library is not thread-safe; without coordination, concurrent reads or writes from multiple FreeRTOS tasks (e.g., OTA downloading a firmware image while logging writes a file) will silently corrupt data, produce write failures, or cause the card to become unresponsive. SDCardMutex wraps a single `SemaphoreHandle_t` in a singleton and exposes two usage patterns: explicit `lock()`/`unlock()` calls and an RAII guard class (`SDCardLock`) that releases the mutex automatically when it leaves scope. + +--- + +## Public API + +### `SDCardMutex` (singleton) + +| Method | Signature | Description | +|--------|-----------|-------------| +| `getInstance` | `static SDCardMutex& getInstance()` | Returns the singleton instance. | +| `begin` | `bool begin()` | Creates the underlying FreeRTOS mutex. Must be called once before any `lock()` call. Returns `false` if `xSemaphoreCreateMutex` fails (heap exhaustion). | +| `lock` | `bool lock(uint32_t timeoutMs = 5000)` | Blocks the calling task until the mutex is acquired or `timeoutMs` elapses. Returns `false` on timeout and logs an error. Pass `portMAX_DELAY` to block indefinitely. | +| `unlock` | `void unlock()` | Releases the mutex. Must be paired with every successful `lock()`. | +| `getStats` | `void getStats(uint32_t& locks, uint32_t& unlocks) const` | Writes cumulative lock and unlock call counts to the provided references. Useful for debugging lock/unlock imbalances. | +| `isLockedByMe` | `bool isLockedByMe() const` | Returns `true` if the calling FreeRTOS task currently holds the mutex. | + +### `SDCardLock` (RAII guard) + +| Method / Operation | Description | +|--------------------|-------------| +| `SDCardLock(uint32_t timeoutMs = 5000)` | Constructor. Calls `SDCardMutex::getInstance().lock()`. If acquisition fails, logs an error and sets internal state to unlocked. | +| `~SDCardLock()` | Destructor. Calls `unlock()` only if the mutex was successfully acquired. | +| `isLocked() const` | Returns `true` if the constructor successfully acquired the mutex. | +| `operator bool() const` | Explicit bool conversion; equivalent to `isLocked()`. Use in `if (SDCardLock lock; lock)` patterns. | + +--- + +## Initialization + +`SDCardMutex::getInstance().begin()` is called in `setup()` in [main.cpp](../main.cpp) as the **very first** subsystem initialization step — before `ConfigManager`, `FileManager`, or any other subsystem that touches the SD card: + +```cpp +// main.cpp — setup() +if (!SDCardMutex::getInstance().begin()) { + // Fatal: halts in infinite loop + while(1) { delay(1000); } +} +configManager.begin(); // SD access starts here +``` + +If `begin()` fails the system halts immediately, because proceeding without the mutex would allow uncoordinated SD access from the moment `ConfigManager` mounts the card. + +The header comment in [main.cpp](../main.cpp) line 129 enforces include order: +```cpp +#include "SDCardMutex/SDCardMutex.hpp" // MUST be included before any SD-using classes +``` + +**No other setup steps are required.** There are no tasks, timers, or background threads created by this subsystem. + +--- + +## Dependencies + +| Dependency | Reason | +|------------|--------| +| FreeRTOS (`freertos/semphr.h`) | `xSemaphoreCreateMutex`, `xSemaphoreTake`, `xSemaphoreGive`, `xSemaphoreGetMutexHolder` | +| Arduino core (`Arduino.h`) | `uint32_t`, base types | +| `Logging/Logging.hpp` | `LOG_INFO`, `LOG_WARNING`, `LOG_ERROR` macros | + +No hardware peripherals, I2C, or SPI are required by this subsystem itself. It purely manages concurrency at the software level. + +--- + +## Gotchas / Notes + +**Always check the return value of `lock()`.** A timeout returns `false`; proceeding to call `SD.open()` after a failed lock gives you unprotected SD access, which is exactly the failure mode this subsystem exists to prevent. + +**Do not call `unlock()` without a preceding successful `lock()`.** The FreeRTOS mutex implementation does not guard against over-releasing; calling `xSemaphoreGive` from a task that does not own the mutex results in undefined behavior. The `SDCardLock` RAII guard handles this correctly — prefer it over manual `lock()`/`unlock()` pairs wherever possible. + +**OTAManager uses explicit lock/unlock, not `SDCardLock`.** This is intentional because the OTA download spans multiple distinct code paths (download loop, verification, flash) where the mutex must be held across function call boundaries and released at precise intermediate points. The RAII pattern would require artificially scoping those sections; explicit calls are clearer there. + +**The mutex is a standard (non-recursive) FreeRTOS mutex.** A task that calls `lock()` twice without an intervening `unlock()` will deadlock itself. Use `isLockedByMe()` to detect re-entrant attempts if needed. + +**Timeout values vary by call site.** OTAManager uses 10–30 second timeouts for long flash operations; general SD access defaults to 5 seconds. Choose your timeout based on the worst-case duration the mutex holder might hold it, not just how long you are willing to wait. + +**`getStats()` counters are not reset between boots** (they are in-RAM accumulators). A persistent mismatch between `locks` and `unlocks` after a defined sequence of operations indicates a missing `unlock()` somewhere in the call path. + +**The mutex is only meaningful if all SD callers use it.** Any subsystem that calls `SD.open()`, `SD.remove()`, or similar without first acquiring the mutex can still cause corruption. New code touching the SD card must include `SDCardMutex/SDCardMutex.hpp` and acquire the mutex before every SD operation. diff --git a/src/SettingsWebServer/README.md b/src/SettingsWebServer/README.md new file mode 100644 index 0000000..d4340e3 --- /dev/null +++ b/src/SettingsWebServer/README.md @@ -0,0 +1,117 @@ +# SettingsWebServer + +## Summary + +SettingsWebServer is a lightweight web interface that lets a user switch the device between +AP mode and Station (router) mode, view basic device status, and trigger a reboot. It +registers three HTTP endpoints on a shared `AsyncWebServer` instance, serves a single-page +HTML UI (defined in `SettingsPage.h` and stored in PROGMEM), and persists mode changes +through `ConfigManager` before issuing `ESP.restart()`. + +> **Status — superseded.** The ongoing comms refactor (Stage 6) replaces this class with +> `WebServerTransport`, which registers the same three endpoints but routes form actions +> through the `CommandBus` instead of calling `ConfigManager` directly. +> `SettingsPage.h` remains in this directory and is still `#include`d by +> `WebServerTransport` until the old directory is removed. + +--- + +## Public API + +| Method | Signature | Description | +|---|---|---| +| Constructor | `SettingsWebServer(AsyncWebServer& server, ConfigManager& configManager, Networking& networking)` | Stores references to dependencies. Does not register any routes. | +| `begin` | `void begin()` | Registers the three HTTP endpoints on `server`. Must be called before `server.begin()`. | + +All other methods are private. + +--- + +## HTTP Endpoints + +Registered by `begin()`: + +| Method | Path | Behaviour | +|---|---|---| +| `GET` | `/settings` | Serves the settings HTML page with runtime values substituted into PROGMEM template. | +| `POST` | `/api/set-mode` | Accepts form body `mode=ap\|station`. Calls `ConfigManager::setPermanentAPMode()` + `saveNetworkConfig()`, then `delay(3000)` + `ESP.restart()`. | +| `POST` | `/api/reboot` | Responds with a plain-text ack, then `delay(2000)` + `ESP.restart()`. | + +The page is reachable at: +- `http://192.168.4.1/settings` when the device is in AP mode +- `http:///settings` when in Station mode + +--- + +## Initialization + +`SettingsWebServer` does not own the `AsyncWebServer` — it receives it by reference. +The expected setup order in the caller is: + +```cpp +// 1. Construct dependencies first +ConfigManager configManager; +Networking networking; +AsyncWebServer server(80); + +// 2. Construct and register routes (before server.begin()) +SettingsWebServer settingsWebServer(server, configManager, networking); +settingsWebServer.begin(); + +// 3. Start the server +server.begin(); +``` + +`ConfigManager` must already be initialised (NVS loaded) before `begin()` is called, +because `handleSetMode` writes to it immediately on receipt of a POST. `Networking` must +be initialised before any request arrives, because `generateSettingsHTML` calls +`networking.isInAPMode()` and `networking.getLocalIP()` on every page load. + +--- + +## Dependencies + +| Dependency | Header | Purpose | +|---|---|---| +| `ESPAsyncWebServer` | `` | Non-blocking HTTP server | +| `ConfigManager` | `ConfigManager/ConfigManager.hpp` | Read device UID / fw version; write and persist AP mode flag | +| `Networking` | `Networking/Networking.hpp` | Read current IP and AP/station state for status display | +| `Logging` | `Logging/Logging.hpp` | `LOG_INFO` / `LOG_DEBUG` macros | +| `SettingsPage.h` | (same directory) | PROGMEM HTML template with `%PLACEHOLDER%` tokens | + +No SD card, I2C, or SPIFFS access. No FreeRTOS tasks are created. + +--- + +## Gotchas / Notes + +**Blocking `delay()` inside async callbacks.** `handleSetMode` and `handleReboot` call +`delay()` (3 s and 2 s respectively) on the AsyncWebServer callback task before calling +`ESP.restart()`. This blocks the entire async task during that window. All in-flight +requests will stall. This is intentional — the device is about to reboot — but be aware +if adding new endpoints that share the same server. + +**`ESP.restart()` inside an async callback.** `ESP.restart()` is called from within an +`AsyncWebServer` request handler lambda. This works in practice on ESP32 because the +preceding `delay()` gives the HTTP response time to flush, but it is not guaranteed by +the library. If the response is not received by the browser, the user will see a network +error before the reboot confirmation alert fires. + +**Single public method.** `begin()` is the only call site ever needs to make after +construction. There is no `loop()` method — `AsyncWebServer` is fully event-driven. + +**HTML loaded from PROGMEM on every request.** `generateSettingsHTML()` allocates a +`String` from `FPSTR(SETTINGS_PAGE_HTML)` on every `GET /settings`. The template is +roughly 2.5 KB. On a heavily loaded device this could cause heap fragmentation; in normal +usage (infrequent human access) it is fine. + +**No authentication.** The settings page is unauthenticated. Anyone on the same network +can trigger a mode change or reboot. This is by design for the provisioning/setup use +case but should be noted for deployments where the device IP is reachable by untrusted +clients. + +**Superseded by WebServerTransport.** New code should not instantiate `SettingsWebServer` +directly. `WebServerTransport` (in `src/Communication/Transport/WebServerTransport/`) +provides identical endpoints and routes actions through the `CommandBus`. The only +remaining shared artifact is `SettingsPage.h`, which `WebServerTransport` includes by +path until this directory is cleaned up. diff --git a/src/Telemetry/README.md b/src/Telemetry/README.md new file mode 100644 index 0000000..1989b81 --- /dev/null +++ b/src/Telemetry/README.md @@ -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": {} } +``` diff --git a/src/TimeKeeper/README.md b/src/TimeKeeper/README.md new file mode 100644 index 0000000..1b07241 --- /dev/null +++ b/src/TimeKeeper/README.md @@ -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.