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`