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:
@@ -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.
|
||||
Reference in New Issue
Block a user