# 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, network-stabilisation delay, and Last Will and Testament. It is not aware of the `CommandBus` — that coupling lives in `MQTTTransport`. All time-driven work runs on one persistent supervisor task (see Initialization). See [docs/reference/vesper_mqtt_topic_spec_v2.md](../../../../docs/reference/vesper_mqtt_topic_spec_v2.md) for the full topic table, per-topic switches, and `req_id` correlation. Topics: - `control/command` (inbound, subscribe) — gated by the `command` topic switch - `control/ack` (outbound replies) — gated by the `command` topic switch - `status/heartbeat` (retained, QoS 1) — gated by the `heartbeat` topic switch - `status/playback`, `control/reports`, `system/alerts`, `system/info`, `system/logs`, `system/metrics` — published directly by `CommunicationRouter` via `publishDirect()`, each gated by its own topic switch (see [CommunicationRouter](../../CommunicationRouter/README.md)) --- ## 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, and registers the Last Will (see [LWT](#last-will-and-testament-lwt) below). Does not connect. | | `void connect()` | Calls `AsyncMqttClient::connect()`. No-op if MQTT is disabled in config or already connected. | | `void disconnect(bool graceful = false)` | Disconnects. If `graceful` is true, explicitly publishes the retained offline payload to `status/heartbeat` first — see [Graceful disconnect](#graceful-disconnect). | | `uint16_t publishAck(const String& payload, int qos = 0, bool retain = false)` | Publishes a reply to `control/ack`. Returns packet ID, or 0 on failure (not connected, low heap, or the `command` topic switch is off). | | `uint16_t publishConfirmed(const String& fullTopic, const String& payload, bool retain, bool resendOnReconnect)` | QoS 1 publish with PUBACK tracking (8 s deadline). A missed deadline makes the supervisor reset the connection. `resendOnReconnect=true` keeps the message and republishes it after the reconnect (event topics); `false` for retained state the caller republishes itself on connect. Used for `status/playback` (false) and `control/reports` (true). | | `uint16_t publishDirect(const String& fullTopic, const String& payload, int qos = 0, bool retain = false)` | Publishes to an absolute, fully-qualified topic (no prefix applied) — no topic-switch gating here; the caller (`CommunicationRouter`) checks the relevant switch before calling. Same heap guard as `publishAck()`. | | `bool hasHeapForPublish() const` | Returns `true` if `ESP.getFreeHeap() >= MIN_FREE_HEAP_FOR_PUBLISH` (20KB). Public so `MQTTTransport` can apply the same threshold before its own allocation-heavy work (JSON deserialization of incoming commands) without duplicating the constant. See [Gotchas](#gotchas--notes) below for why this exists. | | `const String& getCommandTopic() const` / `getAckTopic()` / `getHeartbeatTopic()` / `getPlaybackTopic()` / `getReportsTopic()` / `getAlertsTopic()` / `getInfoTopic()` / `getLogsTopic()` / `getMetricsTopic()` | Cached full topic strings, available after `begin()`. | | `void setCallback(MessageCallback callback)` | Registers the message-received callback. Called by `MQTTTransport::begin()`. | | `void setOnConnectCallback(std::function callback)` | Registers a callback fired once each time MQTT successfully connects (including reconnects). Used by `CommunicationRouter` for one-shot "publish now that we're online" work such as reporting the boot/reset reason. | | `void setStateProvider(std::function provider)` | Registers the callback used to derive the heartbeat's `state`/`ok` fields — see [Heartbeat](#heartbeat) below. Wired by `CommunicationRouter` from `Player` + `HealthMonitor`. | | `void applyCommandTopicSwitch(bool enabled)` | Live-applies a change to the `command` topic switch: subscribes/unsubscribes `control/command` immediately if connected, no-ops otherwise (picked up naturally on next connect). Called by `MQTTHandler::handleSetTopics()`. | | `bool isConnected() const` | Returns the AsyncMqttClient connection state. | | `void connect()` | Requests a connect now (resets backoff) and wakes the supervisor. Used by `mqtt.enable`. | | `void writeStatus(JsonObject out) const` | Fills the `mqtt.status` diagnostics object (connect/disconnect counters, last reasons, forced resets). | | `void onNetworkConnected()` | Resets `_reconnectAttempts` and wakes the supervisor, which connects once WiFi has been up for 2 s. Not required for reconnects — the supervisor polls `WiFi.status()` itself. | | `void onNetworkDisconnected()` | Force-disconnects the client if connected. The supervisor reconnects once WiFi is back. | --- ## 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 ``` `begin()` creates one persistent **supervisor task** (`mqttSup`, 4 KB, priority 3) that owns everything time-driven: connect/reconnect with backoff, the 2 s network stabilisation, the 30 s heartbeat, and wedge detection. It replaced three FreeRTOS timers that each spawned a short-lived task per firing; one failed `xTaskCreate()` on a fragmented heap used to end the reconnect chain for good. See F-071. --- ## Reconnect Behaviour | Attempts | Delay | |----------|-------| | 1–3 (quick retries) | 5 seconds each | | 4 | 10 seconds | | 5 | 20 seconds | | 6 | 40 seconds | | 7+ | Capped at 60 seconds | Reconnect attempts are reset to 0 on a successful connection or a new `onNetworkConnected()` event. ### Self-recovery (wedge detection) The supervisor forces a reset (`AsyncMqttClient::disconnect(true)`, then a normal reconnect) when: | Condition | Why it happens | |---|---| | A connect attempt produced neither CONNACK nor a disconnect callback within 30 s (`"connect attempt stuck"`) | AsyncMqttClient ignores `AsyncClient::connect()`'s return value and stays in CONNECTING forever if it fails (e.g. lwIP out of PCBs); a failed `tcp_close` never fires onDisconnect. Every later `connect()` is then a silent no-op. | | A tracked QoS 1 publish has no PUBACK by its deadline: heartbeat 20 s (`"heartbeat PUBACK timeout"`), playback / report 8 s (`"playback PUBACK timeout"`, `"report PUBACK timeout"`) | Half-open socket or stalled send queue while the library still reports CONNECTED. | Counters and last reasons are reported by `mqtt.status`. ### QoS policy QoS 1 only for the heartbeat, `status/playback` and `control/reports`, all with PUBACK tracking; everything else QoS 0. The library sends its queue strictly in order and holds later packets until a QoS 1 PUBACK arrives, so each QoS 1 message costs whatever is behind it one round trip. Upstream also waited for the next ~500 ms TCP poll after each PUBACK; the vendored copy in `lib/AsyncMqttClient` is patched to send immediately (see its `VENDORED.md`). Plain QoS 1 recovers nothing here — with `cleanSession=true` the library drops unacked packets on reconnect — which is why delivery is guaranteed by the tracking + reset + republish/resend path instead. --- ## Last Will and Testament (LWT) Registered once in `begin()` via `AsyncMqttClient::setWill()`, targeting `status/heartbeat` (QoS 1, retained) with payload `{"device_id": "...", "state": "offline", "ok": false}`. The payload is kept in the `_willPayload` member: `setWill()` stores the raw pointer, and before F-071 it pointed at a freed temporary, so the broker published garbage as the LWT. `AsyncMqttClient` resends the Will on every CONNECT packet, including reconnects, so no manual re-registration is needed after the first `begin()`. The broker fires the Will **only on an unclean disconnect** (network loss, crash, power loss) — it does not fire on a clean, intentional disconnect. See [Graceful disconnect](#graceful-disconnect) for the intentional case. ### Graceful disconnect `disconnect(true)` publishes the same offline payload explicitly, with `retain=true`, before calling the underlying clean disconnect — this prevents a stale "online" heartbeat from staying retained after an intentional disconnect (e.g. `mqtt.disable`, or before an OTA flash). `disconnect(false)` (the default) skips this and disconnects immediately — used where the caller doesn't want an offline announcement (rare; most call sites should use `graceful=true`). --- ## Heartbeat Once connected, a heartbeat is published immediately and then every 30 seconds to `status/heartbeat` with `retain = true`, gated by the `heartbeat` topic switch. Payload (flat, no envelope wrapper): ```json { "device_id": "PV000000000000", "state": "idle", "ok": true, "fw_version": "2.1.1", "uptime_ms": 19425000, "uptime_human": "5h 23m 45s", "ip_address": "10.0.0.3", "gateway": "10.0.0.1", "rssi": -62, "free_heap": 142000 } ``` `state` (`idle`/`playing`/`paused`/`error`/`booting`) and `ok` are produced by the `_stateProvider` callback — see `setStateProvider()` above — and are **independently derived**, never mirrored from `status/playback` or `system/alerts`, per the topic spec. `CommunicationRouter` wires this from `Player::isCurrentlyPlaying()`/`isCurrentlyPaused()` and `HealthMonitor::isFirmwareStable()`. If no provider is registered, heartbeats report `state="booting", ok=true`. The supervisor publishes the first heartbeat right after CONNACK, then every 30 s while connected. It is QoS 1 on purpose: if its PUBACK is missing after 20 s, the connection is treated as dead (see Self-recovery). --- ## Dependencies - `AsyncMqttClient` — broker protocol - `ConfigManager` — MQTT host, port, credentials, enabled flag, device UID, per-topic switches (`MqttTopicConfig`) - `Networking` — IP and gateway for heartbeat (reconnect gating uses `WiFi.status()` directly) - FreeRTOS — one persistent supervisor task, woken by task notifications - `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. - **No per-event tasks.** Earlier versions spawned a short-lived task from every timer firing (reconnect, stabilisation, heartbeat). `xTaskCreate()` return values weren't checked, so on a fragmented heap a single failure silently ended MQTT until reboot. The supervisor task is allocated once at boot instead. - **Free-heap guard before publishing (`hasHeapForPublish()`).** Below `MIN_FREE_HEAP_FOR_PUBLISH` (20KB), `publishAck()`, `publishDirect()`, and `publishHeartbeat()` skip the operation entirely rather than risk `AsyncMqttClient::publish()`'s internal packet-buffer allocation failing. This SDK build has `CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE=0` — a failed allocation under heavy fragmentation can't even throw a catchable `std::bad_alloc`, it calls `abort()` directly. This guard exists because exactly that happened in production under a rapid MQTT command burst with verbose logging (see `docs/features/feature-catalog.md` F-055 for the full `addr2line`-decoded diagnosis). The skip is logged via `Serial.printf()` directly, not `LOG_*` — logging the skip over MQTT would itself attempt a publish, recursing into the same low-heap condition. - **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, configures the server, and registers the Will. Calling `connect()` before `begin()` will silently do nothing useful. - **`onConnect` callback fires on every connect, not just the first.** `setOnConnectCallback` fires on every successful connection, including reconnects after a drop — callers that want "once per boot" semantics (like `CommunicationRouter::reportBootOnce()`) must track that themselves. - **`command` topic switch gates both directions.** Turning `command` off both unsubscribes `control/command` (no more inbound commands) and blocks `publishAck()` (no more outbound replies) — see `docs/reference/vesper_mqtt_topic_spec_v2.md`. The other seven switches (`heartbeat`, `playback`, `reports`, `alerts`, `info`, `logs`, `metrics`) are checked by their respective publishers, not inside this driver — `publishDirect()` itself does not know which topic switch applies to the topic it's given.