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
@@ -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.