fix(MQTT): self-recovering supervisor, LWT payload fix, QoS 0 publishes (F-071, F-072)
Device went cloud-silent after days of uptime while WebSocket kept working; last thing on status/heartbeat was garbage. Causes and fixes: - LWT payload was a dangling pointer: setWill() stores the raw char*, begin() passed a temporary String. The broker published freed heap as the Will on the unclean drop. Now held in _willPayload. - Reconnect/stabilisation/heartbeat timers each xTaskCreate()d a short-lived task with the result ignored; one failed allocation ended the one-shot reconnect chain for good. Replaced by one persistent supervisor task that polls WiFi.status() itself, reconnects with backoff (cap now 60 s), sends the heartbeat, and force-resets the client when a connect attempt is stuck for 30 s or the heartbeat PUBACK is missing for 20 s. - New mqtt.status command (all transports) exposes connect/disconnect counters, last reasons and forced resets for post-mortems over WebSocket. Latency (F-072): AsyncMqttClient holds its queue behind every QoS 1 PUBACK and only resumes on the ~500 ms poll, so each QoS 1 message cost RTT + up to 500 ms. All publishes are now QoS 0 except the heartbeat (liveness probe); cleanSession=true on both ends meant QoS 1 never gave redelivery. WiFi modem sleep disabled on connect to remove DTIM-induced RX delays. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
|
||||
## 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`. The driver uses three FreeRTOS software timers with one-shot tasks deferred off the Tmr Svc stack to avoid stack overflows in timer callbacks.
|
||||
`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:
|
||||
|
||||
@@ -21,7 +21,7 @@ See [docs/reference/vesper_mqtt_topic_spec_v2.md](../../../../docs/reference/ves
|
||||
| `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 = 1, 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 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 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()`. |
|
||||
@@ -30,8 +30,10 @@ See [docs/reference/vesper_mqtt_topic_spec_v2.md](../../../../docs/reference/ves
|
||||
| `void setStateProvider(std::function<DeviceState()> 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 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()`. |
|
||||
| `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. |
|
||||
|
||||
---
|
||||
|
||||
@@ -44,7 +46,7 @@ See [docs/reference/vesper_mqtt_topic_spec_v2.md](../../../../docs/reference/ves
|
||||
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.
|
||||
`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.
|
||||
|
||||
---
|
||||
|
||||
@@ -56,15 +58,30 @@ The constructor creates all three FreeRTOS timers. If timer creation fails (extr
|
||||
| 4 | 10 seconds |
|
||||
| 5 | 20 seconds |
|
||||
| 6 | 40 seconds |
|
||||
| 7+ | Capped at 300 seconds (5 minutes) |
|
||||
| 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. |
|
||||
| The heartbeat's PUBACK hasn't arrived 20 s after it was sent (`"heartbeat 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
|
||||
|
||||
All publishes are QoS 0 except the heartbeat. This AsyncMqttClient build sends its queue strictly in order and holds every later packet until a QoS 1 PUBACK arrives, and `_onPubAck()` doesn't kick the queue — the next packet waits for the ~500 ms TCP poll. A burst of QoS 1 messages (playback + ack + log lines) cost RTT + up to 500 ms *each*. With `cleanSession=true` on both device and backend, QoS 1 never provided redelivery anyway.
|
||||
|
||||
---
|
||||
|
||||
## 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}`. `AsyncMqttClient` resends the Will on every CONNECT packet, including reconnects, so no manual re-registration is needed after the first `begin()`.
|
||||
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.
|
||||
|
||||
@@ -95,7 +112,7 @@ Once connected, a heartbeat is published immediately and then every 30 seconds t
|
||||
|
||||
`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 heartbeat timer is stopped on disconnect and restarted on reconnect.
|
||||
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).
|
||||
|
||||
---
|
||||
|
||||
@@ -103,8 +120,8 @@ The heartbeat timer is stopped on disconnect and restarted on reconnect.
|
||||
|
||||
- `AsyncMqttClient` — broker protocol
|
||||
- `ConfigManager` — MQTT host, port, credentials, enabled flag, device UID, per-topic switches (`MqttTopicConfig`)
|
||||
- `Networking` — `isConnected()` check before reconnect attempts; IP and gateway for heartbeat
|
||||
- FreeRTOS — three `TimerHandle_t` timers, one `TaskHandle_t` for heartbeat task guard
|
||||
- `Networking` — IP and gateway for heartbeat (reconnect gating uses `WiFi.status()` directly)
|
||||
- FreeRTOS — one persistent supervisor task, woken by task notifications
|
||||
- `Logging`
|
||||
|
||||
---
|
||||
@@ -112,9 +129,7 @@ The heartbeat timer is stopped on disconnect and restarted on reconnect.
|
||||
## 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.** `publishAck()` does not log an error when `_mqttClient.publish()` returns 0 (packet ID failure), because it's also reachable from the MQTT log channel and logging an error there would recurse infinitely.
|
||||
- **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.
|
||||
|
||||
Reference in New Issue
Block a user