Files
project-vesper/docs/reference/mqtt-events.md
T
bonaminandClaude Opus 5.5 cec4db4894 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>
2026-10-15 21:07:14 +03:00

411 lines
22 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Vesper — MQTT Events Reference (v2)
> Source of truth for all unsolicited MQTT messages published by Vesper firmware.
> Use this document to generate or update the AsyncAPI specification in the backend console.
> Companion spec: [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_topic_spec_v2.md) — topic table, per-topic ON/OFF switches, `req_id` correlation, LWT.
> Last updated: 2026-09-21 (v2 topic rebuild — see F-062 in [feature-catalog.md](../features/feature-catalog.md))
---
## Overview
Vesper publishes on eight MQTT topics (a ninth, `system/ota`, is reserved but not yet built). All topics are device-scoped under the prefix `vesper/{device_id}/`.
| 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 | 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 | 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 |
Subscribe to `vesper/+/#` to receive everything from all devices (fleet webserver pattern). The phone app subscribes to `control/ack`, `status/heartbeat`, `status/playback`, and `control/reports` (for `playback_failed`).
Every topic above except `control/command`/`control/ack` (which share one switch, `command`) has its own independent ON/OFF publish switch — see [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_topic_spec_v2.md#per-topic-onoff-switches) for the full mechanism (`mqtt.get_topics`/`mqtt.set_topics`).
---
## `vesper/{id}/status/heartbeat`
**QoS:** 1 — **Retained:** yes — **Interval:** 30 seconds — **Switch:** `heartbeat`
Published immediately on MQTT connect, then every 30 seconds. The broker retains the last message so any new subscriber instantly sees the device's last known state. Also the LWT target — see [LWT](#last-will-and-testament-lwt) below.
The server should:
- Update `last_seen` timestamp silently — **no log entry, no display update**
- Raise an offline alert if no heartbeat is received within 90 seconds (3 missed beats), or immediately on receiving an LWT-triggered `state: "offline"` message
### Payload
Flat — no envelope wrapper (the topic is the discriminator).
```json
{
"device_id": "BSVSPR-26E11J-STD10R-M4SC2Z",
"state": "idle",
"ok": true,
"fw_version": "2.2.0",
"uptime_ms": 19425000,
"uptime_human": "5h 23m 45s",
"ip_address": "10.0.0.3",
"gateway": "10.0.0.1",
"rssi": -62,
"free_heap": 142000
}
```
| Field | Type | Description |
|-------|------|-------------|
| `device_id` | string | Device serial number (from NVS) |
| `state` | string | `idle` \| `playing` \| `paused` \| `error` \| `booting` — independently derived from `Player`/`HealthMonitor`, never mirrored from `status/playback` or `system/alerts` |
| `ok` | bool | Overall device health (`HealthMonitor::isFirmwareStable()`), independent of playback state |
| `fw_version` | string | Firmware SemVer string |
| `uptime_ms` | integer | Milliseconds since boot |
| `uptime_human` | string | Human-readable uptime, e.g. `"5h 23m 45s"` |
| `ip_address` | string | Current device IP |
| `gateway` | string | Network gateway IP |
| `rssi` | integer | WiFi signal strength (dBm) |
| `free_heap` | integer | Free heap in bytes |
### Last Will and Testament (LWT)
Registered on every `begin()`/reconnect. If the connection drops **uncleanly** (crash, power loss, network loss), the broker automatically publishes:
```json
{ "device_id": "BSVSPR-26E11J-STD10R-M4SC2Z", "state": "offline", "ok": false }
```
to `status/heartbeat` (QoS 1, retained), overwriting the last "online" heartbeat. For **intentional** disconnects (e.g. `mqtt.disable`), the firmware explicitly publishes the same payload before disconnecting, since LWT does not fire on a clean disconnect.
---
## `vesper/{id}/status/playback`
**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.
### Payload
Flat — no envelope wrapper.
```json
{
"action": "playing",
"time_elapsed": 12,
"projected_run_time": 45000,
"pid": "westminster",
"speed": 400,
"duration": 120000,
"started_at": 1790000000,
"source": "app",
"ts": 1790000012
}
```
```json
{ "action": "idle", "time_elapsed": 0, "projected_run_time": 0, "pid": "", "speed": 0, "duration": 0, "started_at": 0, "source": "", "ts": 1790000130 }
```
| Field | Type | Description |
|-------|------|-------------|
| `action` | string | `loading` \| `playing` \| `paused` \| `stopping` \| `idle` — see [States](#states) |
| `time_elapsed` | integer | Seconds since playback started, as of `ts` (0 for `idle`) |
| `projected_run_time` | integer | Projected total run time in ms (0 if not applicable) |
| `pid` | string | Melody being played or loaded (`""` when idle) |
| `speed` | integer | ms per beat (0 when idle) |
| `duration` | integer | Requested run-time cap in ms — the effective stop timer after `mode`/legacy field resolution (`timed` → `duration`, `interval` → `total_duration`, legacy → `segment_duration`/`total_duration`). `0` = no cap: a `single` play ends naturally, `infinite` runs until stopped. 0 when idle. |
| `started_at` | integer | Unix epoch seconds (UTC) when playback started. `0` when idle, while `loading` (not started yet), or when the board has no valid clock. |
| `source` | string | What started the playback: `app` (MQTT/WebSocket/HTTP command), `rf` (RF remote slot), `button` (UART LCD/button slave board), `schedule` (reserved — scheduled events don't start playback yet), `unknown`. `""` when idle. |
| `ts` | integer | Unix epoch seconds (UTC) when this message was built. `0` when the board has no valid clock. |
**Clock source for `started_at` / `ts`:** the NTP-synced system clock if valid, else the RTC (converted from its stored local time to UTC using the configured offsets), else `0`. RTC-less builds (agnus) therefore report `0` until NTP has synced. Always check for `0` before using either.
**Stale retained messages.** Because the topic is retained, a client may receive a message published long ago. Real elapsed time is `now − started_at` (when `started_at != 0`); `ts` tells you how old the snapshot is. `time_elapsed` is only correct as of `ts`.
```json
{ "action": "loading", "time_elapsed": 0, "projected_run_time": 0, "pid": "ABC123", "speed": 400, "duration": 120000, "started_at": 0, "source": "app", "ts": 1790000100 }
```
The WebSocket transport receives the same fields on every transition, wrapped in the legacy broadcast envelope: `{ "status": "INFO", "type": "playback", "payload": { ...fields above... } }` — **except `loading`, which is MQTT-only**: v1 tablets (WebSocket) map any unknown playback action to "unavailable", so WebSocket clients keep seeing `idle` → `playing` for a download.
### States
| `action` | Meaning | Entered from | Leaves to |
|---|---|---|---|
| `loading` | A `playback.play` was accepted (ACK: `Melody download started — …`) and the melody is downloading to SD first. No bells yet; `pid` identifies what is coming. | `idle` | `playing` (download OK), `idle` (download failed → also a [`playback_failed`](#playback-failed-event) report; or `playback.stop` → cancelled) |
| `playing` | Bells are ringing. | `idle` (play accepted), `loading` (download done), `paused` (segment pause over) | `paused`, `stopping`, `idle` |
| `paused` | Between segments of an `interval` (or legacy `continuous_loop`) play — bells silent, playback still active. | `playing` | `playing`, `idle` |
| `stopping` | The run-time cap (`duration`) has elapsed; the bells are **finishing the current melody loop** before stopping (can last up to one full loop, i.e. steps × `speed`). Still ringing. | `playing` (timer reached `duration`) | `idle` (loop finished) |
| `idle` | Nothing playing. | any (`playback.stop`, natural end, overload force-stop) | `playing` |
`playback.stop` during `playing`/`paused`/`stopping` cuts the bells immediately and goes straight to `idle` — it never passes through `stopping`. During `loading` it cancels the pending start (ACK `Download cancelled — playback will not start`); the transfer itself finishes in the background and is discarded. A new `playback.play` is rejected in every state except `idle` (and briefly after a cancelled download, until that transfer ends).
On a SUCCESS play ACK the board publishes `status/playback` **before** the ACK: `playing` (melody was local) or `loading` (download needed). The heartbeat's independently-derived `state` reports `idle` during `stopping`.
---
## `vesper/{id}/control/reports`
**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.
### Envelope
```json
{ "type": "event_type", "payload": { ... } }
```
### Bell overload event
Published by `CommunicationRouter::sendBellOverloadNotification()` → `publishReport("bell_overload", ...)` when per-bell strike load exceeds configured thresholds.
```json
{
"type": "bell_overload",
"payload": {
"bells": [2, 5],
"loads": [54, 48],
"severity": "WARNING"
}
}
```
| Field | Type | Description |
|-------|------|-------------|
| `payload.bells` | array of int | 1-indexed bell channel numbers that are overloaded |
| `payload.loads` | array of int | Strike count load per bell channel |
| `payload.severity` | string | `WARNING` (≥60% load) or `CRITICAL` (≥90% load) |
### Playback failed event
Published by `CommunicationRouter::sendPlaybackFailedNotification()` from the melody download task when a `playback.play` was already ACKed SUCCESS (`Melody download started — …`) but playback never began. `status/playback` goes `loading` → `idle` at the same moment. Not sent when the download was cancelled by `playback.stop`.
```json
{ "type": "playback_failed", "payload": { "pid": "ABC123", "reason": "Melody download failed" } }
```
| Field | Type | Description |
|-------|------|-------------|
| `payload.pid` | string | The melody that failed to start |
| `payload.reason` | string | One of: `Melody download failed` (HTTP/SD failure), `Melody failed to load: file is empty or corrupt` (downloaded file unusable), `Playback blocked: bell mechanism is disabled (bells.enable)` / `Playback blocked: bell overload protection active — wait for the bells to cool` (conditions changed during the download) |
Like every `control/reports` event it carries no `req_id` — correlate with the command by `pid` (only one download can be pending at a time). WebSocket clients get the same as `{ "status": "INFO", "type": "playback_failed", "payload": { "pid", "reason" } }`.
---
## `vesper/{id}/system/alerts`
**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.
The server should:
- Maintain a **per-device active alert set** (e.g. a dict keyed by `subsystem`)
- On receipt: upsert the alert in the set
- On `CLEARED`: remove the entry from the set
- Display the active alert set statically on the device detail page — **not as a scrolling log**
### Alert payload (problem)
```json
{ "subsystem": "FileManager", "state": "WARNING", "msg": "ConfigManager health check failed" }
```
### Cleared payload (recovery)
```json
{ "subsystem": "FileManager", "state": "CLEARED" }
```
| Field | Type | Description |
|-------|------|-------------|
| `subsystem` | string | Subsystem name. One of: `BellEngine`, `OutputManager`, `Player`, `Communication`, `TimeKeeper`, `Telemetry`, `OTAManager`, `Networking`, `ConfigManager`, `FileManager`, `System` |
| `state` | string | New state: `WARNING` \| `CRITICAL` \| `FAILED` \| `CLEARED` |
| `msg` | string | Human-readable description. Absent when `state` is `CLEARED`. |
### State meanings
| State | Meaning |
|-------|---------|
| `WARNING` | Subsystem has an issue but device continues to operate |
| `CRITICAL` | Subsystem failure affects core functionality |
| `FAILED` | Subsystem is non-functional (equivalent to CRITICAL for critical subsystems) |
| `CLEARED` | Subsystem has recovered; remove from active alert set |
### Critical vs non-critical subsystems
| Subsystem | Critical? | Notes |
|-----------|-----------|-------|
| BellEngine | yes | Core timing — CRITICAL triggers rollback consideration |
| OutputManager | yes | Hardware — CRITICAL triggers rollback consideration |
| Player | yes | Melody control |
| ConfigManager | no | SD card absence maps to WARNING |
| FileManager | no | SD card absence maps to WARNING |
| Communication | no | MQTT/WS failure |
| TimeKeeper | no | RTC sync failure |
| Telemetry | no | Strike counting |
| OTAManager | no | OTA update subsystem |
| Networking | no | WiFi connectivity |
A fault-class boot reset also publishes here — `subsystem: "System"`, e.g.:
```json
{ "subsystem": "System", "state": "WARNING", "msg": "Device reset due to fault: TASK_WATCHDOG" }
```
---
## `vesper/{id}/system/info`
**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.
### Envelope
```json
{ "type": "event_type", "payload": { ... } }
```
### `boot_report`
Published once, the first time MQTT connects after boot (guarded, not repeated on reconnect).
```json
{
"type": "boot_report",
"payload": {
"boot_count": 47,
"reset_reason": "PANIC",
"is_fault": true,
"free_heap": 187234,
"crash": {
"task": "async_tcp", "pc": 1074282197, "exc_cause": 29, "exc_vaddr": 0,
"backtrace": [1074282194, 1074340312, 1074348122, 1074606712],
"backtrace_corrupted": false,
"elf_sha256": "3f9a1c0be7d2a441"
},
"pre_crash": {
"uptime_ms": 5412000, "free_heap": 21480, "largest_block": 9716, "min_free_heap": 18112,
"abort_msg": "abort() was called at PC 0x400d8a3f on core 0"
}
}
}
```
`crash` is present only when a coredump was found for the crash that caused this boot — omitted on a clean/expected reset or a fault reset with no coredump (e.g. brownout). `backtrace` (up to 16 PCs, decimal) and `elf_sha256` (first 16 hex chars of the crashing build's ELF SHA-256) identify the call chain; decode with `addr2line` against that exact `.elf`.
`pre_crash` (F-070) is present only on a fault reset where RTC memory survived (not power-on/brownout): the last once-per-second heap/uptime snapshot before the reset, plus `abort_msg` when the reset came from `abort()`/`assert`/a stack-overflow check. For those resets `pc`/`exc_cause 29`/`exc_vaddr 0` are the abort mechanism itself; `abort_msg` and the later `backtrace` frames are the real cause. A fault-class reset additionally publishes a `system/alerts` WARNING (see above) — `system/info`'s `boot_report` is published unconditionally, fault or not.
---
## `vesper/{id}/system/logs`
**QoS:** 0 — **Retained:** no — **Switch:** `logs`
Mirrors the serial log stream, respecting both the configured MQTT log level (`log.set_mqtt`, 0–5) and this topic's own ON/OFF switch independently — the switch can silence the whole channel without touching the configured level. See [Logging](../../src/Logging/README.md).
```json
{ "level": "WARNING", "subsystem": "BellEngine", "message": "...", "timestamp": 12345 }
```
`timestamp` is `millis()` (ms since boot), not wall-clock time.
---
## `vesper/{id}/system/metrics`
**QoS:** 0 — **Retained:** no — **Switch:** `metrics` — **Interval:** 5 minutes
Structured telemetry for fleet-health graphing — not consumed by the phone app. Published by `CommunicationRouter::reportDiagnosticsIfDue()`.
```json
{
"cpu_temp": { "avg": 47.1, "min": 44.8, "max": 52.8, "samples": 20 },
"wifi_reconnects": { "lifetime_count": 2, "last_reason": "AUTH_EXPIRE", "last_at_uptime_ms": 3600000 },
"ota": { "current_version": "2.2.0", "update_available": false, "last_check_uptime_ms": 180000, "last_error": "NONE" },
"stack_high_water": { "TelemetryTask": 1024, "HealthMonitor": 890 },
"bell_strikes": { "0": 1234, "1": 567 },
"bell_loads": { "0": 12, "1": 0 },
"cooling_active": false
}
```
| Field | Type | Description |
|-------|------|-------------|
| `cpu_temp` | object | Min/max/avg CPU die temperature (°C) since the last report |
| `wifi_reconnects` | object | Lifetime-this-boot reconnect count, last disconnect reason/uptime |
| `ota` | object | Current/available version, update-available flag, last check time, last error |
| `stack_high_water` | object | Bytes free per registered task (low-water mark) |
| `bell_strikes` | object | Cumulative strike count per bell channel (0–15) |
| `bell_loads` | object | Current heat-load accumulator per bell channel |
| `cooling_active` | bool | True if any bell still has residual heat |
---
## `vesper/{id}/control/command` and `vesper/{id}/control/ack`
**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).
### Command (inbound)
```json
{ "v": 2, "cmd": "playback.stop", "req_id": "abc123" }
```
### Reply (outbound)
```json
{ "status": "SUCCESS", "type": "playback", "req_id": "abc123", "message": "Playback command executed" }
```
Reply envelope: `status` (`SUCCESS`/`ERROR`), `type`, optional `req_id`, and either `message` (string — text replies and every error) or `data` (object — structured replies). There is no `payload` key. `req_id` only appears in the reply if the request included one. See [api-reference.md](api-reference.md#response-envelope) for the full envelope rules.
`CommandBus::broadcast()` would also publish here (same envelope, `status: "INFO"`, no `req_id`), but nothing in the firmware calls it today — purpose-specific events (playback, alerts, reports, metrics) publish directly to their own topics.
### Malformed input
Invalid JSON or a missing `cmd` field gets an `ERROR` reply on `control/ack` (`type: "parse_error"`) instead of being silently dropped:
```json
{ "status": "ERROR", "type": "parse_error", "message": "Invalid JSON: IncompleteInput" }
{ "status": "ERROR", "type": "parse_error", "message": "Missing required field: cmd" }
```
---
## Server subscription pattern
```
vesper/+/status/heartbeat → update last_seen + state/ok, no logging (unless state:"offline" from LWT)
vesper/+/status/playback → update device detail panel's playback state
vesper/+/control/reports → surface immediately — critical, time-sensitive (bell_overload, playback_failed)
vesper/+/system/alerts → upsert/remove active alert set per device
vesper/+/system/info → update device state panel (boot_report, etc.)
vesper/+/system/logs → remote log viewer / archival
vesper/+/system/metrics → fleet-health graphing / time-series storage
vesper/+/control/ack → command responses only (phone app / whoever issued the command)
```
---
## Migration from v1 topics
See [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_topic_spec_v2.md#migration-from-v1) for the full old→new topic mapping. Summary: `control`→`control/command`, `data`→`control/ack` (+ new `control/reports` and `status/playback` split out), `status/alerts`→`system/alerts`, `status/info`→`system/info` (diagnostics moved to new `system/metrics`), plus new `system/logs`.
---
## Removed events
| Event | Was published to | Removed in | Reason |
|-------|-----------------|------------|--------|
| `ding` (bell fired) | `vesper/{id}/data` (WebSocket only) | Firmware v155+ | Unstable under load; no active consumers |
| *(entire v1 topic set: `control`, `data`, `status/alerts`, `status/info`)* | — | v2.2.0 | Replaced wholesale by the v2 topic spec — see F-062 in [feature-catalog.md](../features/feature-catalog.md) |