Files
project-vesper/docs/reference/vesper_mqtt_topic_spec_v2.md
T
bonaminandClaude Opus 5.5 b80dbc9b89 docs(api-reference): audit against real handlers — playback.play/stop, message/data envelope, ~30 missing commands
The API reference had drifted far from the firmware. Rewritten against the
handlers' commands() lists, field parsing and CommandResult::err() strings:

- Playback: document playback.play / playback.stop (the bare v2
  cmd:"playback"+action form returns "Unknown command"; v1 form still works
  via LegacyAdapter, and is the only form UART's whitelist accepts). List the
  fields Player::setMelodyAttributes() actually parses (url, not download_url),
  how mode/duration interact, the legacy segment_duration/total_duration
  path, sticky fields, and reply type "playback".
- Response envelope: message (string) + data (object), status INFO only on
  WS broadcasts, no "payload" key; req_id is MQTT-only; v defaults per
  transport; type exceptions (pong/playback/unknown/parse_error/bad_request).
- Add missing commands: relay.set_config/test_bell/test_batch,
  clock.set_config/set_alerts_config/test_c1/test_c2, system.get_config/
  get_all/get_telemetry, ota.set_channel, log.get_config, logs.clear, all
  telemetry.* and bells.*. Remove nonexistent ota.status/ota.check.
- Fix wrong fields: clock.set_alerts is camelCase, clock.set_silence is
  nested, clock.set_time offsets need both fields, clock.set_timezone has no
  timezone_name, files.download needs download_url, ota.update defaults to
  "stable", RF play-slot fields are required (duration 0 rejected), fix legacy
  map to match LegacyAdapter.
- mqtt-events.md: fix the control/command example; note nothing calls
  CommandBus::broadcast(). Topic spec: req_id is MQTT-only today.

Doc-only — no catalog entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 20:02:58 +03:00

87 lines
9.6 KiB
Markdown

# Vesper MQTT Topic Specification v2
Reference for firmware implementation. Device ID placeholder: `{device_id}`.
Implemented in [MQTTDriver](../../src/Communication/Drivers/MQTTDriver/README.md) (topic strings, LWT, heartbeat)
and [MQTTTransport](../../src/Communication/Transport/MQTTTransport/README.md) (command/ack dispatch, req_id).
## Topic Table
| Topic | Purpose | QoS | Retain | Switch | Notes |
|---|---|---|---|---|---|
| `vesper/{device_id}/control/command` | Inbound commands (play, stop, ping, etc.) | 1 | No | `command` | **Read-only from the board's perspective — the board only receives here, never publishes.** Includes optional `req_id` for correlation. `v`, `cmd`, `contents` as before. |
| `vesper/{device_id}/control/ack` | Replies to commands, including `pong` | 1 | No | `command` | **Strictly replies only — every message here answers a specific request, and every reply goes here. Nothing unsolicited is ever published to this topic.** Echoes `req_id` from the originating command when one was sent. `status: SUCCESS/ERROR/INFO`, `type`, optional `message`/`data`. Malformed input (invalid JSON, missing `cmd`) also gets an `ERROR` reply here (`type: "parse_error"`) rather than being silently dropped — see [Malformed input](#malformed-input) below. |
| `vesper/{device_id}/control/reports` | Critical, time-sensitive board-initiated events (e.g. bell overload) | 1 | No | `reports` | The opposite of `control/command` — unsolicited data the board sends because it needs to be read *now*. Not a reply to anything, no `req_id`. Not retained — an event stream, not a status snapshot. |
| `vesper/{device_id}/status/heartbeat` | Periodic health/state summary, every 30s | 1 | **Yes** | `heartbeat` | Also carries LWT (see below). Fields: `device_id`, `state` (`idle`/`playing`/`paused`/`error`/`booting`), `ok` (bool), `fw_version`, `uptime_ms`, `uptime_human`, `ip_address`, `gateway`, `rssi`, `free_heap` — `state`/`ok` independently derived, never mirrored from `status/playback` or `system/alerts`. |
| `vesper/{device_id}/status/playback` | Playback state transitions only | 1 | **Yes** | `playback` | `action`: `playing`/`paused`/`idle`, plus `time_elapsed`, `projected_run_time`. Published on transition, not polled. |
| `vesper/{device_id}/system/alerts` | Subsystem state changes (warnings/errors) | 1 | **Yes**, until cleared | `alerts` | Published on transition only (WARNING/CRITICAL/FAILED/CLEARED). Not consumed by phone app — webserver/fleet only. |
| `vesper/{device_id}/system/info` | Discrete system events (e.g. `boot_report`) | 1 | **Yes** | `info` | Not consumed by phone app. Excludes errors (those go to `alerts`) and metrics (those go to `metrics`). |
| `vesper/{device_id}/system/logs` | Full log stream, serial-log equivalent | 0 | No | `logs` | Not consumed by phone app. Respects device's configured log level (`log.set_mqtt`) **and** this on/off switch independently — the switch can silence the whole channel without touching the configured level. Should not compete with heap/buffer needed for command traffic — guard same as `hasHeapForPublish()`. |
| `vesper/{device_id}/system/metrics` | Structured telemetry (heap free, WiFi RSSI, CPU temp, WiFi reconnects, OTA state, stack high-water marks, bell strike/heat data) | 0 | No | `metrics` | Not consumed by phone app. For fleet-health graphing on webserver. Published every 5 minutes by the existing diagnostics-report mechanism — see [CommunicationRouter](../../src/Communication/CommunicationRouter/README.md). |
| `vesper/{device_id}/system/ota` | OTA update status | 1 | No (transient by nature) | — | Not consumed by phone app. Reserved topic — build only once OTA-over-MQTT capability exists. States: e.g. `downloading`/`flashing`/`rebooting`/`failed`. No switch yet (doesn't exist).
## Per-Topic ON/OFF Switches
Every topic above (except the not-yet-built `system/ota`) has an independent publish switch, persisted in `ConfigManager::MqttTopicConfig` (SD: `generalConfig.json` → `mqttTopics`; NVS on no-SD boards: packed bitfield at key `gc_mtop`). Default: all on.
- **Master + sub-switches.** `mqtt.enable`/`mqtt.disable` remains the master kill switch — it disconnects the broker entirely. The per-topic switches below only take effect *while the master switch is on*; they prune which topics publish, not whether the device is connected at all.
- **`command` covers both directions.** One switch, `command`, gates `control/command` (the subscription) and `control/ack` (its replies) together — turning it off unsubscribes from `control/command` live (no reconnect needed) and drops any reply that would have gone to `control/ack`.
- **Read current state:** `mqtt.get_topics` — returns all 8 switches as booleans.
- **Change state:** `mqtt.set_topics` — partial update, only send the fields you want to change:
```json
{ "v": 2, "cmd": "mqtt.set_topics", "contents": { "heartbeat": true, "metrics": false } }
```
Persisted to SD/NVS immediately. The `command` switch also applies live (subscribe/unsubscribe) without waiting for a reconnect; the others are simply checked on each publish attempt.
This lets a device "breathe" — a fleet-monitoring-only install with no phone app can turn off `command` entirely; a bandwidth-constrained site can turn off `logs` and `metrics` while keeping `heartbeat` and `command` alive.
## req_id Correlation
`control/command` and `control/ack` both support an optional `req_id` string field for correlating a reply to its request:
```json
{ "v": 2, "cmd": "ping", "req_id": "abc123", "contents": {} }
```
```json
{ "status": "SUCCESS", "type": "pong", "req_id": "abc123" }
```
- **Always optional.** A request without `req_id` gets a reply without `req_id` — this is deliberate so v1 clients and any caller not fanning requests out over a shared channel keep working unchanged.
- **Bus-wide plumbing, MQTT-only today.** `req_id` lives on `CommandEnvelope`/`CommandResult` in the shared `CommandBus` core (see [CommandBus](../../src/Communication/CommandBus/README.md)), not bolted onto MQTT alone — the intent is that any transport where multiple logical senders share one channel (multiple devices on one broker; a future multiplexed transport) can use the same mechanism to route replies. Only `MQTTTransport` currently reads it from the request; WebSocket, HTTP and UART ignore it and their replies never carry it.
- **No access control yet.** Any caller can set any `req_id` today. If needed later, safeguards (e.g. restricting who may set one, or validating format) can be added without a wire-format change.
## Malformed Input
`control/command` messages that fail to parse, or parse but have no `cmd` field, get an `ERROR` reply on `control/ack` 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" }
```
A reply to unparseable JSON necessarily has no `req_id` — it couldn't be read out of input that failed to parse. A reply to a parseable-but-`cmd`-less message echoes `req_id` if one was present. This exists so a caller waiting on a timeout gets an immediate, actionable "malformed" instead of silence indistinguishable from a lost network message — the same reasoning the heap guard's silent drop (see [MQTTTransport's README](../../src/Communication/Transport/MQTTTransport/README.md)) deliberately does *not* apply here, since that guard exists specifically to avoid allocating under critical heap pressure, whereas a parse error is cheap to report.
## Cross-Cutting Notes
- **LWT (Last Will and Testament)**: on connect, register Last Will → publishes to `status/heartbeat` with `{"device_id": "...", "state": "offline", "ok": false}` (retained), fired by the broker only on an *unclean* disconnect. Re-registered automatically on every reconnect (AsyncMqttClient resends the Will on every CONNECT).
- **Graceful disconnect**: if the firmware ever disconnects intentionally (e.g. `mqtt.disable`, before OTA), it explicitly publishes the same offline payload before disconnecting, since LWT won't fire for clean disconnects. See `MQTTDriver::disconnect(bool graceful)`.
- **Subscribers**:
- Phone app subscribes only to `control/ack`, `status/heartbeat`, `status/playback` (+ publishes to `control/command`).
- Fleet webserver subscribes to everything via `vesper/+/#`, including `control/reports`, `system/alerts`, `system/info`, `system/logs`, `system/metrics`.
## Migration from v1
The previous topic set (`control` in, `data` out, plus `status/alerts` and `status/info`) is fully replaced by this spec — there is no dual-publish period. See [communication-refactor-plan.md](../architecture/communication-refactor-plan.md) for the wire-protocol migration this topic change shipped alongside, and the console's API Reference → Transports → Legacy tab for what will eventually document the pre-v2 shape for historical reference.
| v1 topic | v2 topic |
|---|---|
| `vesper/{id}/control` (in) | `vesper/{id}/control/command` |
| `vesper/{id}/data` (out — replies + broadcasts mixed) | `vesper/{id}/control/ack` (replies + bus-wide broadcasts) — purpose-specific broadcasts moved to their own topics below |
| `vesper/{id}/status/heartbeat` | `vesper/{id}/status/heartbeat` (same topic, new field shape — see table above) |
| *(none — playback transitions were mixed into `data`)* | `vesper/{id}/status/playback` |
| *(none — bell overload etc. were mixed into `data`)* | `vesper/{id}/control/reports` |
| `vesper/{id}/status/alerts` | `vesper/{id}/system/alerts` |
| `vesper/{id}/status/info` | `vesper/{id}/system/info` |
| *(none)* | `vesper/{id}/system/logs` |
| *(none — diagnostics report was on `status/info`)* | `vesper/{id}/system/metrics` |