# 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`, `rssi`, 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.