docs: add per-subsystem README files

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

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-14 22:16:03 +02:00
co-authored by Claude Sonnet 4.6
parent d4bd990e53
commit d4d8b1c380
29 changed files with 2961 additions and 0 deletions
+112
View File
@@ -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<ICommandHandler> 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<void(const CommandResult&)>` | 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<String> 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.
@@ -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<uint8_t>& bells, const std::vector<uint16_t>& 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()`.
@@ -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.
@@ -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":"<error>"}\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()`.
@@ -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.
+194
View File
@@ -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.
@@ -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()`.
@@ -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": <ms> }`. 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.
@@ -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.
+33
View File
@@ -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.
@@ -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": "<ArduinoJson error string>" }\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.
@@ -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`).
@@ -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.