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:
2026-10-15 21:07:14 +03:00
co-authored by Claude Opus 5.5
parent 09f562cf1d
commit cec4db4894
13 changed files with 382 additions and 258 deletions
+69
View File
@@ -83,6 +83,8 @@ Check `git log -- src/Version.hpp` for the real bump history before tagging a ne
| F-068 | `loading` playback state while a melody downloads (MQTT `status/playback`), cancellable by `playback.stop`; `playback_failed` event on `control/reports` when an ACKed play never starts | v2.3.0 | Stable |
| F-069 | RF remote disabled on Vesper Standard builds (`HAS_RF=0`) — no fielded unit has a receiver; `rf.*` now only on agnus | v2.3.0 | Stable |
| F-070 | Richer crash reports — coredump backtrace + ELF SHA, abort() reason string, and last pre-crash heap/uptime snapshot in `boot_report` and the SD boot log | v2.3.0 | Stable |
| F-071 | MQTT self-recovery — single supervisor task replaces timer/task chain, wedge detection (stuck connect, missing heartbeat PUBACK), LWT payload fix, `mqtt.status` diagnostics | v2.3.0 | Stable |
| F-072 | Lower status/reply latency — all MQTT publishes QoS 0 except heartbeat; WiFi modem sleep disabled | v2.3.0 | Stable |
---
@@ -1422,3 +1424,70 @@ confirms `abort()` now calls `__wrap_esp_system_abort` (IRAM) and the breadcrumb
memory (`0x5000xxxx`). Not yet exercised with a deliberate crash on hardware.
Subsystem: `src/Telemetry/CrashBreadcrumbs.hpp`, `src/Telemetry/CrashBreadcrumbs.cpp`, `src/Telemetry/Telemetry.hpp`, `src/Telemetry/Telemetry.cpp`, `src/Communication/CommunicationRouter/CommunicationRouter.cpp`, `platformio.ini`
---
### F-071 — MQTT self-recovery and `mqtt.status`
**Incident.** A device that had been up for days stopped talking MQTT mid-session: the cloud console
saw it offline, pings and commands went unanswered, but the local WebSocket app kept working, and full
logs showed no errors. The last thing on `status/heartbeat` was a garbage payload.
**Root causes found in `MQTTDriver`:**
1. **The LWT payload was a dangling pointer.** `AsyncMqttClient::setWill()` stores the raw `const char*`;
`begin()` passed `.c_str()` of a local `String`. Every later CONNECT carried whatever was in that freed
heap block as the Will, so on an unclean drop the broker published garbage to `status/heartbeat` (retained).
The garbage seen in the incident was the broker announcing that the connection had died. Now kept in the
`_willPayload` member.
2. **The reconnect chain could die silently.** Reconnect, network stabilisation and heartbeat were
FreeRTOS timers whose callbacks each `xTaskCreate()`d a short-lived 4 KB task, with the return value
ignored. The reconnect timer is one-shot, so a single failed allocation (fragmented heap after days of
uptime) ended reconnection until reboot, and nothing was logged afterwards. A reconnect that fired while
WiFi was briefly down also gave up without rescheduling and waited for a network callback that might never come.
3. **AsyncMqttClient can wedge without telling anyone.** It ignores `AsyncClient::connect()`'s return value
(lwIP out of PCBs leaves it in CONNECTING forever), and a failed `tcp_close` never fires onDisconnect.
In both cases every later `connect()` is a silent no-op.
**What changed.** One persistent supervisor task (`mqttSup`, allocated at boot, never freed) owns
connect/reconnect with backoff (5 s ×3, then doubling, **now capped at 60 s instead of 5 min**), the 2 s
network stabilisation (it polls `WiFi.status()` itself, so it doesn't depend on Networking callbacks), the
30 s heartbeat, and wedge detection. It forces a reset (`disconnect(true)` + normal reconnect) when:
- a connect attempt gets neither CONNACK nor a disconnect callback within 30 s (`"connect attempt stuck"`), or
- the heartbeat's PUBACK is still missing 20 s after it was sent (`"heartbeat PUBACK timeout"`): a half-open
socket or stalled send queue while the library still says CONNECTED. The heartbeat stays QoS 1 for this
reason. With the `heartbeat` topic switch off, this probe is off too.
**`mqtt.status`** (new command, all transports) returns connect/disconnect counters, last disconnect reason
and age, forced-reset count/reason/age, WiFi state and free heap. If a device goes cloud-silent again, send
it over WebSocket: `forced_resets > 0` means self-recovery is firing, `connected:true` while the cloud sees
it offline points at the broker/backend side.
Not covered: if the broker is reachable but rejects the device (auth), the device keeps retrying at the
60 s cap, which is visible in `mqtt.status` as climbing `reconnect_attempts`.
Subsystem: `src/Communication/Drivers/MQTTDriver/MQTTDriver.hpp/.cpp`, `src/Communication/Handlers/MQTTHandler/MQTTHandler.hpp/.cpp`
### F-072 — Lower status/reply latency (QoS 0, WiFi sleep off)
**Symptom.** Playback status and command replies usually took 1–2 s to reach the apps, and MQTT sometimes 3–5 s+.
**Why MQTT was slow.** This AsyncMqttClient build sends its outbound queue strictly in order and holds every
later packet until a QoS 1 PUBACK arrives. `_onPubAck()` releases the packet but doesn't restart the queue,
so the next packet waits for the next lwIP poll (~500 ms). Everything the board published was QoS 1
(acks, playback, alerts, info, reports, and log lines), so a play command queued playback + ack + several
log lines, each costing a round trip plus up to 500 ms. The PUBACK the board owes the broker for the incoming
command waited in the same queue. With `cleanSession=true` on both the device and the backend
(`backend/mqtt/client.py`), QoS 1 never bought redelivery: unacked packets are dropped on reconnect either way.
**Change.** Everything is published at QoS 0 except the heartbeat (QoS 1, see F-071). Topics, retain flags
and payloads are unchanged. Subscribers receive at min(publish QoS, subscription QoS), so they now get QoS 0
delivery, which changes nothing with clean sessions.
**WiFi modem sleep off.** Arduino-ESP32 defaults to `WIFI_PS_MIN_MODEM`: the radio dozes between AP beacons
and inbound packets wait for the next DTIM (100 ms to 1 s+ depending on the AP). This affects WebSocket and
MQTT equally. `Networking::onWiFiConnected()` now calls `WiFi.setSleep(false)` on every connect. The device is
mains powered, so the extra ~80 mA doesn't matter.
Subsystem: `src/Communication/CommunicationRouter/CommunicationRouter.cpp`, `src/Communication/Drivers/MQTTDriver/MQTTDriver.hpp`, `src/Logging/Logging.cpp`, `src/Networking/Networking.cpp`
+16 -8
View File
@@ -80,9 +80,9 @@ MQTT uses the v2 topic set — see [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_to
| MQTT | `vesper/{device_id}/control/ack` | Outbound replies | Strictly request/response — nothing unsolicited |
| MQTT | `vesper/{device_id}/control/reports` | Outbound, critical unsolicited events | `bell_overload`, `playback_failed` — not retained |
| MQTT | `vesper/{device_id}/status/heartbeat` | Outbound, retained, QoS 1 | Heartbeat every 30s + LWT |
| MQTT | `vesper/{device_id}/status/playback` | Outbound, retained, QoS 1 | Playback transitions |
| MQTT | `vesper/{device_id}/system/alerts` | Outbound, retained until cleared, QoS 1 | Subsystem state-change events |
| MQTT | `vesper/{device_id}/system/info` | Outbound, retained, QoS 1 | Discrete device events (boot report) |
| MQTT | `vesper/{device_id}/status/playback` | Outbound, retained, QoS 0 | Playback transitions |
| MQTT | `vesper/{device_id}/system/alerts` | Outbound, retained until cleared, QoS 0 | Subsystem state-change events |
| MQTT | `vesper/{device_id}/system/info` | Outbound, retained, QoS 0 | Discrete device events (boot report) |
| MQTT | `vesper/{device_id}/system/logs` | Outbound, QoS 0 | Mirrors serial log stream |
| MQTT | `vesper/{device_id}/system/metrics` | Outbound, QoS 0 | Structured telemetry every 5 min |
| WebSocket | `ws://{device_ip}/ws` | Bidirectional | Send `identify` on connect |
@@ -821,6 +821,12 @@ Returns `message: "MQTT enabled and saved"` / `"MQTT disabled and saved"`. Error
Returns `data: { "enabled", "host", "port", "user", "use_ssl" }` (never the password).
### `mqtt.status`
Connection health since boot — works on every transport, so it's the command to send over WebSocket when the cloud shows a device offline but the local app still works.
Returns `data: { "enabled", "connected", "connected_for_ms", "connects", "disconnects", "reconnect_attempts", "last_disconnect_reason", "last_disconnect_ago_ms", "forced_resets", "last_forced_reset_reason", "last_forced_reset_ago_ms", "wifi_connected", "free_heap" }`.
`*_ago_ms` and `connected_for_ms` are `0` when the event never happened / not connected. `last_forced_reset_reason` is `"connect attempt stuck"` or `"heartbeat PUBACK timeout"` (empty if self-recovery never fired). No errors.
### `mqtt.get_topics`
Returns `data: { "command", "heartbeat", "playback", "reports", "alerts", "info", "logs", "metrics" }` (bools).
@@ -873,14 +879,16 @@ Published without a request, on the v2 topic set. Full field-level reference: [m
| Topic | When | QoS | Retained | Switch |
|---|---|---|---|---|
| `vesper/{id}/status/heartbeat` | Every 30s (+ LWT on unclean disconnect) | 1 | yes | `heartbeat` |
| `vesper/{id}/status/playback` | On playback transition | 1 | yes | `playback` |
| `vesper/{id}/control/reports` | Critical unsolicited events (`bell_overload`, `playback_failed`) | 1 | no | `reports` |
| `vesper/{id}/system/alerts` | On subsystem state change only | 1 | yes, until cleared | `alerts` |
| `vesper/{id}/system/info` | Discrete device events (e.g. boot report) | 1 | yes | `info` |
| `vesper/{id}/status/playback` | On playback transition | 0 | yes | `playback` |
| `vesper/{id}/control/reports` | Critical unsolicited events (`bell_overload`, `playback_failed`) | 0 | no | `reports` |
| `vesper/{id}/system/alerts` | On subsystem state change only | 0 | yes, until cleared | `alerts` |
| `vesper/{id}/system/info` | Discrete device events (e.g. boot report) | 0 | yes | `info` |
| `vesper/{id}/system/logs` | Mirrors serial log stream | 0 | no | `logs` |
| `vesper/{id}/system/metrics` | Every 5 min | 0 | no | `metrics` |
`control/ack` carries only replies (it is not an event topic).
`control/ack` carries only replies (it is not an event topic). Replies are published at QoS 0.
Everything the board publishes is QoS 0 except the heartbeat (QoS 1, its PUBACK doubles as a liveness probe) — see F-071 in the feature catalog for why.
---
+10 -10
View File
@@ -14,12 +14,12 @@ Vesper publishes on eight MQTT topics (a ninth, `system/ota`, is reserved but no
| Topic | Direction | QoS | Retained | Switch | Purpose |
|-------|-----------|-----|----------|--------|---------|
| `vesper/{id}/control/command` | Inbound | 1 | no | `command` | Commands from server/app — board only ever receives here |
| `vesper/{id}/control/ack` | Outbound | 1 | no | `command` | Replies to commands **only** — strictly request/response |
| `vesper/{id}/control/reports` | Outbound | 1 | no | `reports` | Critical, unsolicited, time-sensitive board-initiated events (`bell_overload`, `playback_failed`) |
| `vesper/{id}/control/ack` | Outbound | 0 | no | `command` | Replies to commands **only** — strictly request/response |
| `vesper/{id}/control/reports` | Outbound | 0 | no | `reports` | Critical, unsolicited, time-sensitive board-initiated events (`bell_overload`, `playback_failed`) |
| `vesper/{id}/status/heartbeat` | Outbound | 1 | yes | `heartbeat` | Periodic liveness + state signal. Also carries LWT. |
| `vesper/{id}/status/playback` | Outbound | 1 | yes | `playback` | Playback transitions only |
| `vesper/{id}/system/alerts` | Outbound | 1 | yes, until cleared | `alerts` | Subsystem state-change events |
| `vesper/{id}/system/info` | Outbound | 1 | yes | `info` | Discrete device state events (boot report, etc.) |
| `vesper/{id}/status/playback` | Outbound | 0 | yes | `playback` | Playback transitions only |
| `vesper/{id}/system/alerts` | Outbound | 0 | yes, until cleared | `alerts` | Subsystem state-change events |
| `vesper/{id}/system/info` | Outbound | 0 | yes | `info` | Discrete device state events (boot report, etc.) |
| `vesper/{id}/system/logs` | Outbound | 0 | no | `logs` | Full log stream, mirrors serial log output |
| `vesper/{id}/system/metrics` | Outbound | 0 | no | `metrics` | Structured telemetry — fleet-health graphing |
@@ -85,7 +85,7 @@ to `status/heartbeat` (QoS 1, retained), overwriting the last "online" heartbeat
## `vesper/{id}/status/playback`
**QoS:** 1 — **Retained:** yes — **Switch:** `playback` — **Trigger:** playback state transition only
**QoS:** 0 — **Retained:** yes — **Switch:** `playback` — **Trigger:** playback state transition only
Published by `Player::setStatus()` on every transition (not polled), **and on every MQTT connect/reconnect** with the Player's current real state — so a retained `playing` left behind by a power loss mid-melody is overwritten (normally with `idle`) as soon as the board is back. This topic — not the `control/ack` reply — is the source of truth for what the board is actually doing. Skipped (not queued) while free heap is below the publish guard.
@@ -151,7 +151,7 @@ On a SUCCESS play ACK the board publishes `status/playback` **before** the ACK:
## `vesper/{id}/control/reports`
**QoS:** 1 — **Retained:** no — **Switch:** `reports` — **Trigger:** critical, time-sensitive, board-initiated event
**QoS:** 0 — **Retained:** no — **Switch:** `reports` — **Trigger:** critical, time-sensitive, board-initiated event
The opposite of `control/command`: unsolicited data the board sends because it needs to be read *now*. Not a reply to anything — never carries `req_id`. Not retained, since it's an event stream, not a status snapshot.
@@ -201,7 +201,7 @@ Like every `control/reports` event it carries no `req_id` — correlate with the
## `vesper/{id}/system/alerts`
**QoS:** 1 — **Retained:** yes, until cleared — **Switch:** `alerts` — **Trigger:** subsystem state change only
**QoS:** 0 — **Retained:** yes, until cleared — **Switch:** `alerts` — **Trigger:** subsystem state change only
Published by `HealthMonitor` (via `CommunicationRouter::publishAlert()`) whenever a subsystem transitions between health states. Published once on change; not repeated until the state changes again. Silent if MQTT is not connected, or the `alerts` switch is off, at the moment of the transition. Retained so a late-connecting console (fleet webserver) immediately sees the last unresolved alert per subsystem.
@@ -262,7 +262,7 @@ A fault-class boot reset also publishes here — `subsystem: "System"`, e.g.:
## `vesper/{id}/system/info`
**QoS:** 1 — **Retained:** yes — **Switch:** `info` — **Trigger:** discrete device state event
**QoS:** 0 — **Retained:** yes — **Switch:** `info` — **Trigger:** discrete device state event
Published for general device state changes that are not health failures and not quantitative telemetry (see `system/metrics` for that). Use this topic to update the device detail panel (e.g. boot reason) without polling.
@@ -350,7 +350,7 @@ Structured telemetry for fleet-health graphing — not consumed by the phone app
## `vesper/{id}/control/command` and `vesper/{id}/control/ack`
**QoS:** 1 — **Retained:** no — **Switch:** `command`
**QoS:** 1 inbound (`control/command`), 0 outbound (`control/ack`) — **Retained:** no — **Switch:** `command`
`control/command` is read-only from the board's perspective — the board only ever receives here. `control/ack` is strictly reply-only: every message on it answers a specific request (including `pong`), and no unsolicited event is ever published there. Both support an optional `req_id` field for correlation — see [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_topic_spec_v2.md#req_id-correlation).