feat(MQTT): rebuild topic spec to v2 (F-062)
Full MQTT topic rebuild per docs/reference/vesper_mqtt_topic_spec_v2.md.
Only the MQTT transport path changed — WebSocket, HTTP, and UART are untouched.
- control/command (in) + control/ack (out, strictly replies) replace the old
control/data pair; new control/reports for critical unsolicited events
(bell overload) that don't belong on the strictly-reply ack channel
- status/playback split out for playback transitions only
- status/alerts + status/info renamed to system/alerts + system/info, both
now correctly retained; new system/logs and system/metrics (diagnostics
report moved here from system/info, gained bell strike/heat data)
- LWT registered for the first time — status/heartbeat gets
{"state":"offline","ok":false} on an unclean disconnect; graceful
disconnect (mqtt.disable) announces offline explicitly since LWT doesn't
fire on a clean disconnect
- heartbeat payload flattened, gains independently-derived state/ok fields
(via a new MQTTDriver::setStateProvider() wired from Player+HealthMonitor)
- optional req_id correlation added bus-wide (CommandEnvelope/CommandResult),
not MQTT-only, since any transport with multiple senders sharing one
channel has the same problem. Always optional — v1 clients unaffected.
- per-topic ON/OFF switches (ConfigManager::MqttTopicConfig, 8 flags) as
sub-switches under the existing mqtt.enable/disable master switch, so a
device can breathe by disabling topics it doesn't need. New
mqtt.get_topics/mqtt.set_topics commands; command switch applies live.
Bumped to v2.2.0. Verified: pio run -e vesper-std-v1 -e agnus-v1 both build clean.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -396,7 +396,7 @@ With this architecture, adding it costs almost nothing:
|
||||
| `ResponseBuilder` | Keep — add `fromResult(CommandResult)` factory method |
|
||||
| `ClientManager` | Keep — used by `WebSocketTransport` |
|
||||
| Wire protocol format | Keep — `{ "cmd": "...", "contents": { ... } }` unchanged |
|
||||
| MQTT topics | Keep — no change |
|
||||
| MQTT topics | **Changed in v2.2.0** — full topic rebuild, see `docs/reference/vesper_mqtt_topic_spec_v2.md` and F-062 in the feature catalog |
|
||||
| MQTT auth system | Keep — no change |
|
||||
| UART whitelist | Keep — move into `UARTTransport` |
|
||||
|
||||
|
||||
@@ -74,6 +74,7 @@ Check `git log -- src/Version.hpp` for the real bump history before tagging a ne
|
||||
| F-059 | Fix: partition table mismatch blocking safe OTA to pre-restructure field devices | v2.1.0 | Stable |
|
||||
| F-060 | `system.set_identity` — sysadmin override of factory-set device identity (serial/hw_family/hw_revision) | v2.1.0 | Stable |
|
||||
| F-061 | Fix: `LegacyResponseAdapter` — v1 tablets saw device as "unavailable" while playing, due to `system.status` reply schema mismatch | v2.1.1 | Stable (temporary migration scaffolding) |
|
||||
| F-062 | MQTT topic spec v2 — restructured topics (`control/command`/`control/ack`/`control/reports`/`status/playback`/`system/*`), LWT, `req_id` correlation, per-topic ON/OFF switches (`mqtt.set_topics`) | v2.2.0 | Stable |
|
||||
|
||||
---
|
||||
|
||||
@@ -1036,3 +1037,86 @@ before/after schema table, and the exact removal steps are in
|
||||
Verified: `pio run -e vesper-std-v1` builds clean (all four environments share the touched files).
|
||||
|
||||
Subsystem: `src/Communication/CommandBus/LegacyResponseAdapter.hpp` (new), `src/Communication/CommandBus/LegacyResponseAdapter.cpp` (new), `src/Communication/Transport/WebSocketTransport/WebSocketTransport.cpp`, `src/Communication/Transport/MQTTTransport/MQTTTransport.cpp`, `src/Communication/Transport/HTTPTransport/HTTPTransport.cpp`
|
||||
|
||||
---
|
||||
|
||||
### F-062 — MQTT topic spec v2
|
||||
|
||||
Full rebuild of the MQTT wire topics per `docs/reference/vesper_mqtt_topic_spec_v2.md`. Only the MQTT
|
||||
transport path changed — WebSocket, HTTP, and UART are untouched.
|
||||
|
||||
**Old → new topic mapping:**
|
||||
- `control` (in) / `data` (out, replies + broadcasts mixed) → `control/command` (in, read-only from
|
||||
the board's perspective) / `control/ack` (out, **strictly** replies + bus-wide broadcasts — nothing
|
||||
purpose-specific is ever published here)
|
||||
- `status/alerts` → `system/alerts` (unchanged shape, now retained until cleared — previously published
|
||||
with `retain=false`, which was a latent bug against its own stated "state-change events" intent)
|
||||
- `status/info` → `system/info` (unchanged shape, now retained)
|
||||
- New: `status/playback` — playback transitions only, split out of the old `data` topic. Published by
|
||||
`CommunicationRouter::publishPlayback()`, called from `Player::setStatus()` alongside the existing
|
||||
WebSocket `broadcastStatus()` call (WS shape/behaviour unchanged).
|
||||
- New: `control/reports` — critical, unsolicited, board-initiated events that need to be read *now*
|
||||
(currently: `bell_overload`, moved off the old `data` topic). Not retained — an event stream, not a
|
||||
status snapshot. The naming mirrors `control/command`: where `command` is inbound-only from the
|
||||
board's perspective, `reports` is outbound-only, unsolicited.
|
||||
- New: `system/logs` — the log-publish topic, unchanged in shape/mechanism from the pre-existing
|
||||
`Logging` MQTT channel, just renamed and moved under `system/`.
|
||||
- New: `system/metrics` — the existing 5-minute diagnostics report (CPU temp, WiFi reconnects, OTA
|
||||
state, stack high-water marks) moved here from `system/info`, since it's exactly the "structured
|
||||
telemetry for fleet-health graphing" the spec describes for this topic. Also gained per-bell
|
||||
strike/heat-load data (`Telemetry::getStrikeCount()`/`getBellLoad()`/`isCoolingActive()` for all 16
|
||||
channels) — the spec explicitly calls out "bell heat ratings" for this topic and there was previously
|
||||
no MQTT-side exposure of it at all.
|
||||
- Reserved, not yet built: `system/ota` (OTA-over-MQTT status streaming — no OTA-over-MQTT capability
|
||||
exists yet).
|
||||
|
||||
**LWT (Last Will and Testament) — new.** `MQTTDriver::begin()` registers a Will via
|
||||
`AsyncMqttClient::setWill()` targeting `status/heartbeat` with `{"device_id","state":"offline","ok":false}`
|
||||
(QoS 1, retained). The broker publishes this automatically on an *unclean* disconnect
|
||||
(crash/power-loss/network-loss) — there was no LWT at all before this change, so an unclean disconnect
|
||||
previously left a stale "last known good" heartbeat retained indefinitely with no way to distinguish
|
||||
"device is fine, just hasn't sent one in a while" from "device dropped off the network an hour ago."
|
||||
`AsyncMqttClient` resends the Will on every reconnect automatically — no manual re-registration needed.
|
||||
For *intentional* disconnects (which don't trigger LWT), `MQTTDriver::disconnect(true)` explicitly
|
||||
publishes the same offline payload first — wired into `mqtt.disable`.
|
||||
|
||||
**Heartbeat payload reshaped.** Flattened (no more `status`/`type`/`payload` envelope wrapper — the
|
||||
topic itself is the discriminator now, matching every other v2 topic). New fields: `state`
|
||||
(`idle`/`playing`/`paused`/`error`/`booting`) and `ok` (bool), both independently derived via a new
|
||||
`MQTTDriver::setStateProvider()` callback — wired by `CommunicationRouter` from
|
||||
`Player::isCurrentlyPlaying()`/`isCurrentlyPaused()` and `HealthMonitor::isFirmwareStable()`, per the
|
||||
spec's explicit requirement that these NOT be mirrored from `status/playback` or `system/alerts`.
|
||||
`timestamp`/`firmware_version` renamed to `uptime_human`/`fw_version` for consistency with the rest of
|
||||
the v2 field naming.
|
||||
|
||||
**`req_id` correlation — new, bus-wide.** `CommandEnvelope` and `CommandResult` both gained an optional
|
||||
`reqId` field (`CommandBus::dispatch()` copies it from envelope to result before calling `reply()`, so
|
||||
individual handlers never need to know about it). Always optional — a request without `req_id` gets a
|
||||
reply without one, so v1 clients and any existing caller are unaffected. Implemented bus-wide rather
|
||||
than MQTT-only because the same correlation problem (multiple logical senders sharing one channel)
|
||||
applies to any future multiplexed transport, not just MQTT's shared broker topics. MQTT is the first
|
||||
(and currently only) transport that actually parses/echoes it, in `MQTTTransport::onMessage()`.
|
||||
|
||||
**Per-topic ON/OFF switches — new.** `ConfigManager::MqttTopicConfig` (8 bools: `command`, `heartbeat`,
|
||||
`playback`, `reports`, `alerts`, `info`, `logs`, `metrics`) persisted alongside the existing
|
||||
`GeneralConfig` (SD: nested `mqttTopics` object in `generalConfig.json`; NVS on no-SD boards: packed
|
||||
into a single `u8` bitfield at key `gc_mtop`). All default to `true` (no behaviour change on upgrade).
|
||||
These are **sub-switches under the existing `mqtt.enable`/`mqtt.disable` master switch** — turning the
|
||||
master off still disconnects the broker entirely regardless of these flags; while connected, each flag
|
||||
independently gates whether its topic publishes. `command` is the one switch that covers both
|
||||
directions — turning it off unsubscribes `control/command` live (`MQTTDriver::applyCommandTopicSwitch()`,
|
||||
no reconnect needed) and blocks `control/ack` replies. Read via `mqtt.get_topics`, changed via
|
||||
`mqtt.set_topics` (partial update — only send the fields you want to change).
|
||||
|
||||
**Why this shape (design decisions made with the user):** `control/ack` is strictly reply-only — no
|
||||
unsolicited event is ever published there, full stop; anything unsolicited-but-important got its own
|
||||
topic (`control/reports`) instead of being folded into the reply channel. Diagnostics moved to
|
||||
`system/metrics` rather than staying on `system/info` because it's quantitative telemetry, not a
|
||||
discrete one-off event like `boot_report`. `req_id` went in bus-wide (not MQTT-scoped) on the reasoning
|
||||
that multiple devices/senders sharing one transport is a general problem, not MQTT-specific — with no
|
||||
access control for now (anyone can set any `req_id`), left as a deliberate future extension point.
|
||||
|
||||
Verified: `pio run -e vesper-std-v1` and `pio run -e agnus-v1` both build clean (SD and no-SD NVS config
|
||||
paths both touched).
|
||||
|
||||
Subsystem: `src/Communication/Drivers/MQTTDriver/MQTTDriver.hpp`, `src/Communication/Drivers/MQTTDriver/MQTTDriver.cpp`, `src/Communication/Transport/MQTTTransport/MQTTTransport.hpp`, `src/Communication/Transport/MQTTTransport/MQTTTransport.cpp`, `src/Communication/Handlers/MQTTHandler/MQTTHandler.hpp`, `src/Communication/Handlers/MQTTHandler/MQTTHandler.cpp`, `src/Communication/CommandBus/CommandEnvelope.hpp`, `src/Communication/CommandBus/CommandResult.hpp`, `src/Communication/CommandBus/CommandBus.cpp`, `src/Communication/CommunicationRouter/CommunicationRouter.hpp`, `src/Communication/CommunicationRouter/CommunicationRouter.cpp`, `src/ConfigManager/ConfigManager.hpp`, `src/ConfigManager/ConfigManager.cpp`, `src/Player/Player.cpp`
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
> Command reference for the Vesper Bell Automation System.
|
||||
> Firmware v2 command bus architecture — all transports, all handlers.
|
||||
> Last updated: 2026-03-16
|
||||
> Last updated: 2026-09-21 (MQTT topic spec v2 — see F-062 in feature-catalog.md)
|
||||
|
||||
---
|
||||
|
||||
@@ -16,6 +16,7 @@ Every command sent to Vesper uses this JSON envelope:
|
||||
{
|
||||
"v": 2,
|
||||
"cmd": "namespace.command",
|
||||
"req_id": "abc123",
|
||||
"contents": { ... }
|
||||
}
|
||||
```
|
||||
@@ -24,6 +25,7 @@ Every command sent to Vesper uses this JSON envelope:
|
||||
|---|---|---|
|
||||
| `v` | int | Protocol version. `2` = current. Omit or set `1` for legacy (LegacyAdapter runs). |
|
||||
| `cmd` | string | `namespace.command` format (e.g. `relay.set_durations`). |
|
||||
| `req_id` | string | Optional. Echoed back on the reply for correlation when a caller shares one channel across multiple requests/senders (e.g. MQTT `control/command`). Omit for a reply with no `req_id` field — fully backward compatible. |
|
||||
| `contents` | object | Command payload. May be omitted if command takes no fields. |
|
||||
|
||||
### Response Envelope
|
||||
@@ -32,23 +34,30 @@ Every command sent to Vesper uses this JSON envelope:
|
||||
{
|
||||
"status": "SUCCESS" | "ERROR",
|
||||
"type": "command_name",
|
||||
"req_id": "abc123",
|
||||
"payload": { ... }
|
||||
}
|
||||
```
|
||||
|
||||
`payload` is command-specific. On error, `payload` typically contains a `"message"` string.
|
||||
`payload` is command-specific. On error, `payload` typically contains a `"message"` string. `req_id` is present only if the request included one.
|
||||
|
||||
---
|
||||
|
||||
## Transports
|
||||
|
||||
MQTT uses the v2 topic set — see [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_topic_spec_v2.md) for the full table, per-topic ON/OFF switches, `req_id` correlation, and LWT. WebSocket, HTTP, and UART are unchanged by the v2 MQTT rebuild.
|
||||
|
||||
| Transport | Address | Direction | Notes |
|
||||
|---|---|---|---|
|
||||
| MQTT | `vesper/{device_id}/control` | Inbound commands | Responses go to `vesper/{device_id}/data` |
|
||||
| MQTT | `vesper/{device_id}/data` | Outbound responses + events | Command replies and bell overload notifications |
|
||||
| MQTT | `vesper/{device_id}/status/heartbeat` | Outbound, retained, QoS 1 | Heartbeat every 30s; server updates last_seen |
|
||||
| MQTT | `vesper/{device_id}/status/alerts` | Outbound, QoS 1 | Subsystem state-change events (published on change only) |
|
||||
| MQTT | `vesper/{device_id}/status/info` | Outbound, QoS 0 | General device state events (playback, reboot reason, etc.) |
|
||||
| MQTT | `vesper/{device_id}/control/command` | Inbound commands | Read-only from the board's perspective. Replies go to `control/ack`. |
|
||||
| MQTT | `vesper/{device_id}/control/ack` | Outbound replies | Strictly request/response — nothing unsolicited |
|
||||
| MQTT | `vesper/{device_id}/control/reports` | Outbound, critical unsolicited events | e.g. bell overload — not retained |
|
||||
| MQTT | `vesper/{device_id}/status/heartbeat` | Outbound, retained, QoS 1 | Heartbeat every 30s + LWT; server updates last_seen |
|
||||
| MQTT | `vesper/{device_id}/status/playback` | Outbound, retained, QoS 1 | Playback transitions only |
|
||||
| MQTT | `vesper/{device_id}/system/alerts` | Outbound, retained until cleared, QoS 1 | Subsystem state-change events (published on change only) |
|
||||
| MQTT | `vesper/{device_id}/system/info` | Outbound, retained, QoS 1 | Discrete device state events (boot report, etc.) |
|
||||
| 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 — fleet-health graphing |
|
||||
| WebSocket | `ws://{device_ip}/ws` | Bidirectional | Requires `identify` on connect |
|
||||
| HTTP | `http://{device_ip}/...` | REST | Web console endpoints |
|
||||
| UART | Hardware serial | Bidirectional | Restricted — whitelist only (see below) |
|
||||
@@ -913,13 +922,54 @@ Enable or disable RF reception at runtime.
|
||||
|
||||
### `mqtt.enable` / `mqtt.disable`
|
||||
|
||||
Enable or disable MQTT connectivity.
|
||||
Enable or disable MQTT connectivity (master switch — disconnects/reconnects the broker entirely). `mqtt.disable` publishes a graceful offline heartbeat before disconnecting.
|
||||
|
||||
```json
|
||||
{ "v": 2, "cmd": "mqtt.enable" }
|
||||
{ "v": 2, "cmd": "mqtt.disable" }
|
||||
```
|
||||
|
||||
### `mqtt.get_config`
|
||||
|
||||
Returns broker connection settings.
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Returns | `{ "enabled": true, "host": "72.61.191.197", "port": 1883, "user": "...", "use_ssl": false }` |
|
||||
|
||||
```json
|
||||
{ "v": 2, "cmd": "mqtt.get_config" }
|
||||
```
|
||||
|
||||
### `mqtt.get_topics`
|
||||
|
||||
Returns the current state of all 8 per-topic ON/OFF publish switches. See [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_topic_spec_v2.md#per-topic-onoff-switches).
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Returns | `{ "command": true, "heartbeat": true, "playback": true, "reports": true, "alerts": true, "info": true, "logs": true, "metrics": true }` |
|
||||
|
||||
```json
|
||||
{ "v": 2, "cmd": "mqtt.get_topics" }
|
||||
```
|
||||
|
||||
### `mqtt.set_topics`
|
||||
|
||||
Partial update of the per-topic ON/OFF switches — only send the fields you want to change. These only take effect while `mqtt.enable` (the master switch) is on. `command` gates both `control/command` (subscription) and `control/ack` (replies) together, and applies live without a reconnect.
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Optional | Any of `command`, `heartbeat`, `playback`, `reports`, `alerts`, `info`, `logs`, `metrics` (bool) — at least one required |
|
||||
|
||||
```json
|
||||
{ "v": 2, "cmd": "mqtt.set_topics", "contents": { "heartbeat": true, "metrics": false } }
|
||||
```
|
||||
|
||||
| Error | Condition |
|
||||
|---|---|
|
||||
| `"No recognised topic fields in contents (command, heartbeat, playback, reports, alerts, info, logs, metrics)"` | No valid boolean fields present |
|
||||
| `"Topic switches changed but failed to save to SD"` | Applied in RAM but persistence failed |
|
||||
|
||||
---
|
||||
|
||||
## Telemetry Namespace — `TelemetryHandler`
|
||||
@@ -971,66 +1021,18 @@ Get heat load per bell channel, cooling status, and overload flags.
|
||||
|
||||
## MQTT Events (Unsolicited)
|
||||
|
||||
These messages are published by the device without a request. See [mqtt-events.md](mqtt-events.md) for the full AsyncAPI-compatible reference.
|
||||
These messages are published by the device without a request, on the v2 topic set (`control/command`+`control/ack`, `control/reports`, `status/heartbeat`, `status/playback`, `system/alerts`, `system/info`, `system/logs`, `system/metrics`). Full field-level reference, per-topic switches, LWT, and `req_id` correlation: [mqtt-events.md](mqtt-events.md) and [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_topic_spec_v2.md).
|
||||
|
||||
| Topic | When | QoS | Retained | Format |
|
||||
| Topic | When | QoS | Retained | Switch |
|
||||
|---|---|---|---|---|
|
||||
| `vesper/{id}/status/heartbeat` | Every 30s | 1 | yes | Heartbeat envelope |
|
||||
| `vesper/{id}/status/alerts` | On subsystem state change only | 1 | no | Alert envelope |
|
||||
| `vesper/{id}/status/info` | On device state change | 0 | no | Info envelope |
|
||||
| `vesper/{id}/data` | Any command response / bell overload | 0 | no | Standard response envelope |
|
||||
|
||||
### Heartbeat Payload
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "INFO",
|
||||
"type": "heartbeat",
|
||||
"payload": {
|
||||
"device_id": "PV-26B18-VS01R-X7KQA",
|
||||
"firmware_version": "142",
|
||||
"timestamp": "Uptime: 5h 23m 45s",
|
||||
"ip_address": "10.0.0.3",
|
||||
"gateway": "10.0.0.1",
|
||||
"uptime_ms": 19425000,
|
||||
"rssi": -62
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Subscribe to `vesper/+/status/heartbeat` to discover all online devices.
|
||||
|
||||
### Alert Payload (`vesper/{id}/status/alerts`)
|
||||
|
||||
Published only when a subsystem state changes. The server should store the active alert set per device and update the display in place rather than appending a log entry.
|
||||
|
||||
```json
|
||||
{ "subsystem": "FileManager", "state": "WARNING", "msg": "ConfigManager health check failed" }
|
||||
```
|
||||
|
||||
On recovery:
|
||||
```json
|
||||
{ "subsystem": "FileManager", "state": "CLEARED" }
|
||||
```
|
||||
|
||||
`state` values: `WARNING` | `CRITICAL` | `FAILED` | `CLEARED`
|
||||
|
||||
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" }
|
||||
```
|
||||
|
||||
### Info Payload (`vesper/{id}/status/info`)
|
||||
|
||||
Published on significant device state changes. `type` identifies the event; `payload` is event-specific.
|
||||
|
||||
```json
|
||||
{ "type": "playback_started", "payload": { "pid": "ormilia_1_8" } }
|
||||
{ "type": "playback_stopped", "payload": {} }
|
||||
{ "type": "boot_reason", "payload": { "reason": "POWERON" } }
|
||||
```
|
||||
|
||||
`boot_reason` is published once, the first time MQTT connects after boot — only for expected reset reasons (`POWERON`, `SOFTWARE`, `DEEPSLEEP_WAKE`, `EXTERNAL_PIN`, `SDIO`, `UNKNOWN`). Fault reasons (`PANIC`, `TASK_WATCHDOG`, `INTERRUPT_WATCHDOG`, `OTHER_WATCHDOG`, `BROWNOUT`) go to `status/alerts` instead (see above).
|
||||
| `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 (e.g. bell overload) | 1 | no | `reports` |
|
||||
| `vesper/{id}/system/alerts` | On subsystem state change only | 1 | yes, until cleared | `alerts` |
|
||||
| `vesper/{id}/system/info` | On discrete device state events (e.g. boot report) | 1 | yes | `info` |
|
||||
| `vesper/{id}/system/logs` | Mirrors serial log stream | 0 | no | `logs` |
|
||||
| `vesper/{id}/system/metrics` | Every 5 min — CPU temp, WiFi/OTA state, bell heat | 0 | no | `metrics` |
|
||||
| `vesper/{id}/control/ack` | Reply to every command (strictly request/response) | 1 | no | `command` |
|
||||
|
||||
---
|
||||
|
||||
|
||||
+200
-82
@@ -1,70 +1,148 @@
|
||||
# Vesper — MQTT Events Reference
|
||||
# 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.
|
||||
> Last updated: 2026-03-01
|
||||
> 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 four MQTT topics. All topics are device-scoped under the prefix `vesper/{device_id}/`.
|
||||
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 | Purpose |
|
||||
|-------|-----------|-----|----------|---------|
|
||||
| `vesper/{id}/control` | Inbound | — | — | Commands from server/app |
|
||||
| `vesper/{id}/data` | Outbound | 0 | no | Command responses + bell overload events |
|
||||
| `vesper/{id}/status/heartbeat` | Outbound | 1 | yes | Periodic liveness signal |
|
||||
| `vesper/{id}/status/alerts` | Outbound | 1 | no | Subsystem state-change events |
|
||||
| `vesper/{id}/status/info` | Outbound | 0 | no | General device state events |
|
||||
| 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 (e.g. bell overload) |
|
||||
| `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}/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/+/status/#` to receive all status events from all devices.
|
||||
Subscribe to `vesper/+/#` to receive everything from all devices (fleet webserver pattern). The phone app subscribes only to `control/ack`, `status/heartbeat`, `status/playback`.
|
||||
|
||||
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
|
||||
**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 whether the device is alive.
|
||||
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)
|
||||
- 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:** 1 — **Retained:** yes — **Switch:** `playback` — **Trigger:** playback state transition only
|
||||
|
||||
Published by `Player::setStatus()` on every transition (not polled).
|
||||
|
||||
### Payload
|
||||
|
||||
```json
|
||||
{ "action": "playing", "time_elapsed": 12, "projected_run_time": 45000 }
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `action` | string | `playing` \| `paused` \| `idle` |
|
||||
| `time_elapsed` | integer | Seconds since playback started (0 for `idle`) |
|
||||
| `projected_run_time` | integer | Projected total run time in ms (0 if not applicable) |
|
||||
|
||||
---
|
||||
|
||||
## `vesper/{id}/control/reports`
|
||||
|
||||
**QoS:** 1 — **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
|
||||
{
|
||||
"status": "INFO",
|
||||
"type": "heartbeat",
|
||||
"type": "bell_overload",
|
||||
"payload": {
|
||||
"device_id": "PV-26B18-VS01R-X7KQA",
|
||||
"firmware_version": "154",
|
||||
"timestamp": "Uptime: 5h 23m 45s",
|
||||
"ip_address": "10.0.0.3",
|
||||
"gateway": "10.0.0.1",
|
||||
"uptime_ms": 19425000
|
||||
"bells": [2, 5],
|
||||
"loads": [54, 48],
|
||||
"severity": "WARNING"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `payload.device_id` | string | Device serial number (from NVS) |
|
||||
| `payload.firmware_version` | string | Firmware build version string |
|
||||
| `payload.timestamp` | string | Human-readable uptime string |
|
||||
| `payload.ip_address` | string | Current device IP |
|
||||
| `payload.gateway` | string | Network gateway IP |
|
||||
| `payload.uptime_ms` | integer | Milliseconds since boot |
|
||||
| `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) |
|
||||
|
||||
---
|
||||
|
||||
## `vesper/{id}/status/alerts`
|
||||
## `vesper/{id}/system/alerts`
|
||||
|
||||
**QoS:** 1 — **Retained:** no — **Trigger:** subsystem state change only
|
||||
**QoS:** 1 — **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 at the moment of the transition.
|
||||
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`)
|
||||
@@ -75,25 +153,18 @@ The server should:
|
||||
### Alert payload (problem)
|
||||
|
||||
```json
|
||||
{
|
||||
"subsystem": "FileManager",
|
||||
"state": "WARNING",
|
||||
"msg": "ConfigManager health check failed"
|
||||
}
|
||||
{ "subsystem": "FileManager", "state": "WARNING", "msg": "ConfigManager health check failed" }
|
||||
```
|
||||
|
||||
### Cleared payload (recovery)
|
||||
|
||||
```json
|
||||
{
|
||||
"subsystem": "FileManager",
|
||||
"state": "CLEARED"
|
||||
}
|
||||
{ "subsystem": "FileManager", "state": "CLEARED" }
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `subsystem` | string | Subsystem name. One of: `BellEngine`, `OutputManager`, `Player`, `Communication`, `TimeKeeper`, `Telemetry`, `OTAManager`, `Networking`, `ConfigManager`, `FileManager` |
|
||||
| `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`. |
|
||||
|
||||
@@ -121,89 +192,136 @@ The server should:
|
||||
| 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}/status/info`
|
||||
## `vesper/{id}/system/info`
|
||||
|
||||
**QoS:** 0 — **Retained:** no — **Trigger:** significant device state change
|
||||
**QoS:** 1 — **Retained:** yes — **Switch:** `info` — **Trigger:** discrete device state event
|
||||
|
||||
Published for general device state changes that are not health failures. Use this topic to update the device detail panel (e.g. current playback, reboot reason) without polling.
|
||||
|
||||
The server should display the most recent `info` payload for each event `type` on the device detail page.
|
||||
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": "event_type",
|
||||
"payload": { ... }
|
||||
"type": "boot_report",
|
||||
"payload": {
|
||||
"boot_count": 47,
|
||||
"reset_reason": "PANIC",
|
||||
"is_fault": true,
|
||||
"free_heap": 187234,
|
||||
"crash": { "task": "TelemetryTask", "pc": 1074111832, "exc_cause": 1, "exc_vaddr": 0 }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Event types (current and planned)
|
||||
|
||||
| `type` | When | Payload fields |
|
||||
|--------|------|----------------|
|
||||
| `playback_started` | Player begins playing a melody | `melody_uid` (string) |
|
||||
| `playback_stopped` | Player stops | *(none)* |
|
||||
|
||||
> **Note:** `publishInfo()` exists in `CommunicationRouter` but is not yet called from any subsystem. Call sites will be added as feature work in subsequent firmware versions. The API is stable.
|
||||
`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). 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}/data`
|
||||
## `vesper/{id}/system/logs`
|
||||
|
||||
**QoS:** 0 — **Retained:** no
|
||||
**QoS:** 0 — **Retained:** no — **Switch:** `logs`
|
||||
|
||||
Published in response to commands and for unsolicited events that are not health-related.
|
||||
|
||||
### Command response envelope
|
||||
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
|
||||
{
|
||||
"status": "SUCCESS" | "ERROR",
|
||||
"type": "command_name",
|
||||
"payload": { ... }
|
||||
}
|
||||
{ "level": "WARNING", "subsystem": "BellEngine", "message": "...", "timestamp": 12345 }
|
||||
```
|
||||
|
||||
### Bell overload event
|
||||
`timestamp` is `millis()` (ms since boot), not wall-clock time.
|
||||
|
||||
Published by `CommunicationRouter::sendBellOverloadNotification()` when per-bell strike load exceeds configured thresholds.
|
||||
---
|
||||
|
||||
## `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
|
||||
{
|
||||
"status": "INFO",
|
||||
"type": "bell_overload",
|
||||
"payload": {
|
||||
"bells": [2, 5],
|
||||
"loads": [54, 48],
|
||||
"severity": "WARNING"
|
||||
}
|
||||
"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 |
|
||||
|-------|------|-------------|
|
||||
| `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) |
|
||||
| `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 — **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", "req_id": "abc123", "contents": { "action": "stop" } }
|
||||
```
|
||||
|
||||
### Reply (outbound)
|
||||
|
||||
```json
|
||||
{ "status": "SUCCESS", "type": "playback", "req_id": "abc123", "message": "Command executed" }
|
||||
```
|
||||
|
||||
`req_id` only appears in the reply if the request included one. Bus-wide unsolicited broadcasts (`CommandBus::broadcast()`) also publish here, with the same envelope shape and no `req_id` — but purpose-specific events (playback, alerts, reports, metrics) never use this path; they publish directly to their own topics instead.
|
||||
|
||||
---
|
||||
|
||||
## Server subscription pattern
|
||||
|
||||
```
|
||||
vesper/+/status/heartbeat → update last_seen, no logging
|
||||
vesper/+/status/alerts → upsert/remove active alert set per device
|
||||
vesper/+/status/info → update device state panel
|
||||
vesper/+/data → display command responses, handle bell_overload
|
||||
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 (e.g. bell_overload)
|
||||
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) |
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
# 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`. |
|
||||
| `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, not MQTT-only.** `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.
|
||||
- **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.
|
||||
|
||||
## 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` |
|
||||
@@ -45,12 +45,15 @@ void CommandBus::dispatch(CommandEnvelope& envelope) {
|
||||
|
||||
if (it == _registry.end()) {
|
||||
LOG_WARNING(TAG, "No handler for command: '%s'", envelope.command.c_str());
|
||||
envelope.reply(CommandResult::err("unknown", "Unknown command: " + envelope.command));
|
||||
CommandResult unknown = CommandResult::err("unknown", "Unknown command: " + envelope.command);
|
||||
unknown.reqId = envelope.reqId;
|
||||
envelope.reply(unknown);
|
||||
return;
|
||||
}
|
||||
|
||||
LOG_DEBUG(TAG, "Dispatching: %s", envelope.command.c_str());
|
||||
CommandResult result = it->second->execute(envelope);
|
||||
result.reqId = envelope.reqId;
|
||||
envelope.reply(result);
|
||||
}
|
||||
|
||||
@@ -71,6 +74,9 @@ void CommandBus::broadcast(const CommandResult& result) {
|
||||
if (result.hasData) {
|
||||
doc["data"] = result.data;
|
||||
}
|
||||
if (!result.reqId.isEmpty()) {
|
||||
doc["req_id"] = result.reqId;
|
||||
}
|
||||
|
||||
String serialised;
|
||||
serializeJson(doc, serialised);
|
||||
|
||||
@@ -36,6 +36,13 @@ struct CommandEnvelope {
|
||||
// Flat command name — e.g. "playback", "relay.set_durations", "system.restart"
|
||||
String command;
|
||||
|
||||
// Optional caller-supplied correlation ID, echoed back in CommandResult's
|
||||
// reply so a client that fans requests out over a shared channel (MQTT
|
||||
// control/command, multiple devices on one broker) can match replies to
|
||||
// requests. Empty when the caller didn't send one — always optional, so
|
||||
// v1 clients and any request without it keep working unchanged.
|
||||
String reqId;
|
||||
|
||||
// The "contents" object from the raw JSON message
|
||||
JsonDocument contents;
|
||||
|
||||
|
||||
@@ -24,6 +24,9 @@ struct CommandResult {
|
||||
String payload; // human-readable message (empty is fine for data responses)
|
||||
JsonDocument data; // structured data payload (optional)
|
||||
bool hasData = false;
|
||||
String reqId; // echoes CommandEnvelope::reqId, if the caller sent one. Set by
|
||||
// CommandBus::dispatch(), not by handlers — factory methods below
|
||||
// never need to know about it.
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Factory methods
|
||||
|
||||
@@ -99,12 +99,16 @@ void CommunicationRouter::begin() {
|
||||
LOG_INFO(TAG, "Setting up MQTT transport...");
|
||||
_mqttTransport.begin();
|
||||
|
||||
String logTopic = "vesper/" + _configManager.getDeviceUID() + "/logs";
|
||||
Logging::setMqttPublishCallback(
|
||||
[this](const String& topic, const String& payload, int qos) {
|
||||
_mqttClient.publish(topic, payload, qos, false);
|
||||
// Gated by the "logs" topic switch, independent of the per-level
|
||||
// log.set_mqtt setting — this lets an operator turn the whole
|
||||
// system/logs channel off without touching the configured level,
|
||||
// and turn it back on later with the level untouched.
|
||||
if (!_configManager.getMqttTopicConfig().logs) return;
|
||||
_mqttClient.publishDirect(topic, payload, qos, false);
|
||||
},
|
||||
logTopic
|
||||
_mqttClient.getLogsTopic()
|
||||
);
|
||||
|
||||
Logging::setSerialLevel((Logging::LogLevel)_configManager.getSerialLogLevel());
|
||||
@@ -133,6 +137,22 @@ void CommunicationRouter::begin() {
|
||||
reportBootOnce();
|
||||
});
|
||||
|
||||
// Heartbeat state/ok derivation — independently derived per the topic spec,
|
||||
// not mirrored from status/playback or system/alerts. _player and
|
||||
// _healthMonitor are late-bound (set after begin() via setXxxReference()),
|
||||
// so this lambda captures `this` and reads them at call time, not at
|
||||
// registration time — safe because the heartbeat timer only starts once
|
||||
// MQTT connects, which is always well after main.cpp finishes wiring.
|
||||
_mqttClient.setStateProvider([this]() -> MQTTDriver::DeviceState {
|
||||
if (!_player) return MQTTDriver::DeviceState{"booting", true};
|
||||
|
||||
String state = _player->isCurrentlyPlaying() ? "playing"
|
||||
: _player->isCurrentlyPaused() ? "paused"
|
||||
: "idle";
|
||||
bool ok = _healthMonitor ? _healthMonitor->isFirmwareStable() : true;
|
||||
return MQTTDriver::DeviceState{state, ok};
|
||||
});
|
||||
|
||||
LOG_INFO(TAG, "MQTT transport initialised");
|
||||
|
||||
// ── HTTP ─────────────────────────────────────────────────────────────────
|
||||
@@ -417,7 +437,10 @@ bool CommunicationRouter::isHealthy() const {
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
void CommunicationRouter::broadcastStatus(const String& message) {
|
||||
publishToMqtt(message);
|
||||
// WebSocket-only. MQTT publishing for the same events now goes through
|
||||
// the dedicated topic methods (publishPlayback, publishReport, etc.) —
|
||||
// see docs/reference/vesper_mqtt_topic_spec_v2.md. Kept as a WS fan-out
|
||||
// helper for callers that don't need MQTT at all.
|
||||
_wsTransport.broadcast(message);
|
||||
}
|
||||
|
||||
@@ -445,15 +468,6 @@ void CommunicationRouter::broadcastToAllWebSocketClients(const JsonDocument& mes
|
||||
_wsTransport.broadcast(msg);
|
||||
}
|
||||
|
||||
void CommunicationRouter::publishToMqtt(const String& data) {
|
||||
if (_mqttClient.isConnected()) {
|
||||
_mqttClient.publish("", data, 0, false);
|
||||
LOG_DEBUG(TAG, "Published to MQTT data topic");
|
||||
} else {
|
||||
LOG_WARNING(TAG, "MQTT not connected — message dropped");
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Bell overload notification
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
@@ -463,20 +477,33 @@ void CommunicationRouter::sendBellOverloadNotification(
|
||||
const std::vector<uint16_t>& bellLoads,
|
||||
const String& severity) {
|
||||
|
||||
JsonDocument doc;
|
||||
doc["status"] = "INFO";
|
||||
doc["type"] = "bell_overload";
|
||||
// WS clients keep the existing shape (unchanged transport, untouched per
|
||||
// the refactor's scope).
|
||||
JsonDocument wsDoc;
|
||||
wsDoc["status"] = "INFO";
|
||||
wsDoc["type"] = "bell_overload";
|
||||
|
||||
JsonArray bellsArr = doc["payload"]["bells"].to<JsonArray>();
|
||||
JsonArray loadsArr = doc["payload"]["loads"].to<JsonArray>();
|
||||
JsonArray wsBells = wsDoc["payload"]["bells"].to<JsonArray>();
|
||||
JsonArray wsLoads = wsDoc["payload"]["loads"].to<JsonArray>();
|
||||
for (size_t i = 0; i < bellNumbers.size() && i < bellLoads.size(); ++i) {
|
||||
wsBells.add(bellNumbers[i] + 1);
|
||||
wsLoads.add(bellLoads[i]);
|
||||
}
|
||||
wsDoc["payload"]["severity"] = severity;
|
||||
broadcastStatus(wsDoc);
|
||||
|
||||
// MQTT gets the dedicated control/reports topic — critical, unsolicited,
|
||||
// board-initiated events that need to be read now.
|
||||
JsonDocument reportPayload;
|
||||
JsonArray bellsArr = reportPayload["bells"].to<JsonArray>();
|
||||
JsonArray loadsArr = reportPayload["loads"].to<JsonArray>();
|
||||
for (size_t i = 0; i < bellNumbers.size() && i < bellLoads.size(); ++i) {
|
||||
bellsArr.add(bellNumbers[i] + 1);
|
||||
loadsArr.add(bellLoads[i]);
|
||||
}
|
||||
doc["payload"]["severity"] = severity;
|
||||
reportPayload["severity"] = severity;
|
||||
publishReport("bell_overload", reportPayload);
|
||||
|
||||
broadcastStatus(doc);
|
||||
LOG_WARNING(TAG, "Bell overload notification sent: %d bells, severity: %s",
|
||||
bellNumbers.size(), severity.c_str());
|
||||
}
|
||||
@@ -487,6 +514,7 @@ void CommunicationRouter::sendBellOverloadNotification(
|
||||
|
||||
void CommunicationRouter::publishAlert(const String& subsystem, const String& newState, const String& message) {
|
||||
if (!_mqttClient.isConnected()) return;
|
||||
if (!_configManager.getMqttTopicConfig().alerts) return;
|
||||
|
||||
JsonDocument doc;
|
||||
doc["subsystem"] = subsystem;
|
||||
@@ -497,7 +525,11 @@ void CommunicationRouter::publishAlert(const String& subsystem, const String& ne
|
||||
|
||||
String out;
|
||||
serializeJson(doc, out);
|
||||
_mqttClient.publishDirect(_mqttClient.getAlertsTopic(), out, 1, false);
|
||||
// Retained until cleared — a late-connecting console (fleet webserver)
|
||||
// immediately sees the last unresolved alert per subsystem. A CLEARED
|
||||
// publish (empty message, state="CLEARED") overwrites the retained
|
||||
// message with the resolved state, same retain semantics.
|
||||
_mqttClient.publishDirect(_mqttClient.getAlertsTopic(), out, 1, true);
|
||||
LOG_DEBUG(TAG, "Alert published: %s → %s", subsystem.c_str(), newState.c_str());
|
||||
}
|
||||
|
||||
@@ -586,13 +618,24 @@ void CommunicationRouter::reportDiagnosticsIfDue() {
|
||||
JsonObject stackObj = payload["stack_high_water"].to<JsonObject>();
|
||||
Telemetry::writeStackHighWaterMarks(stackObj);
|
||||
|
||||
publishInfo("diagnostics_report", payload);
|
||||
LOG_INFO(TAG, "Diagnostics report published (temp samples=%u, wifi_reconnects=%lu)",
|
||||
// Bell strike counts and heat load — the "bell heat ratings" the topic
|
||||
// spec calls out explicitly for system/metrics.
|
||||
JsonObject strikesObj = payload["bell_strikes"].to<JsonObject>();
|
||||
JsonObject loadsObj = payload["bell_loads"].to<JsonObject>();
|
||||
for (uint8_t i = 0; i < 16; i++) {
|
||||
strikesObj[String(i)] = _telemetry->getStrikeCount(i);
|
||||
loadsObj[String(i)] = _telemetry->getBellLoad(i);
|
||||
}
|
||||
payload["cooling_active"] = _telemetry->isCoolingActive();
|
||||
|
||||
publishMetrics(payload);
|
||||
LOG_INFO(TAG, "Diagnostics/metrics report published (temp samples=%u, wifi_reconnects=%lu)",
|
||||
tempSampleCount, _networking.getReconnectCount());
|
||||
}
|
||||
|
||||
void CommunicationRouter::publishInfo(const String& type, const JsonDocument& payload) {
|
||||
if (!_mqttClient.isConnected()) return;
|
||||
if (!_configManager.getMqttTopicConfig().info) return;
|
||||
|
||||
JsonDocument doc;
|
||||
doc["type"] = type;
|
||||
@@ -602,10 +645,53 @@ void CommunicationRouter::publishInfo(const String& type, const JsonDocument& pa
|
||||
|
||||
String out;
|
||||
serializeJson(doc, out);
|
||||
_mqttClient.publishDirect(_mqttClient.getInfoTopic(), out, 0, false);
|
||||
_mqttClient.publishDirect(_mqttClient.getInfoTopic(), out, 1, true);
|
||||
LOG_DEBUG(TAG, "Info published: %s", type.c_str());
|
||||
}
|
||||
|
||||
void CommunicationRouter::publishPlayback(const String& action, uint32_t timeElapsedSec, uint64_t projectedRunTimeMs) {
|
||||
if (!_mqttClient.isConnected()) return;
|
||||
if (!_configManager.getMqttTopicConfig().playback) return;
|
||||
|
||||
JsonDocument doc;
|
||||
doc["action"] = action;
|
||||
doc["time_elapsed"] = timeElapsedSec;
|
||||
doc["projected_run_time"] = projectedRunTimeMs;
|
||||
|
||||
String out;
|
||||
serializeJson(doc, out);
|
||||
_mqttClient.publishDirect(_mqttClient.getPlaybackTopic(), out, 1, true);
|
||||
LOG_DEBUG(TAG, "Playback published: %s", action.c_str());
|
||||
}
|
||||
|
||||
void CommunicationRouter::publishReport(const String& type, const JsonDocument& payload) {
|
||||
if (!_mqttClient.isConnected()) return;
|
||||
if (!_configManager.getMqttTopicConfig().reports) return;
|
||||
|
||||
JsonDocument doc;
|
||||
doc["type"] = type;
|
||||
if (!payload.isNull()) {
|
||||
doc["payload"] = payload;
|
||||
}
|
||||
|
||||
String out;
|
||||
serializeJson(doc, out);
|
||||
// Not retained — an event stream of critical-but-transient reports, not a
|
||||
// status snapshot. A late subscriber doesn't need old reports replayed.
|
||||
_mqttClient.publishDirect(_mqttClient.getReportsTopic(), out, 1, false);
|
||||
LOG_DEBUG(TAG, "Report published: %s", type.c_str());
|
||||
}
|
||||
|
||||
void CommunicationRouter::publishMetrics(const JsonDocument& payload) {
|
||||
if (!_mqttClient.isConnected()) return;
|
||||
if (!_configManager.getMqttTopicConfig().metrics) return;
|
||||
|
||||
String out;
|
||||
serializeJson(payload, out);
|
||||
_mqttClient.publishDirect(_mqttClient.getMetricsTopic(), out, 0, false);
|
||||
LOG_DEBUG(TAG, "Metrics published");
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Network state callbacks
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -101,23 +101,52 @@ public:
|
||||
#endif
|
||||
|
||||
// Broadcast helpers — called by BellEngine, Player, Telemetry, etc.
|
||||
// These remain WebSocket-only fan-out helpers; MQTT publishing for the
|
||||
// same events now goes through the dedicated topic methods below instead
|
||||
// (see docs/reference/vesper_mqtt_topic_spec_v2.md). broadcastStatus() is
|
||||
// kept for WS-only callers but no longer also publishes to MQTT — see
|
||||
// publishPlayback() for the MQTT equivalent used by Player.
|
||||
void broadcastStatus(const String& statusMessage);
|
||||
void broadcastStatus(const JsonDocument& statusJson);
|
||||
void broadcastToMasterClients(const String& message);
|
||||
void broadcastToSecondaryClients(const String& message);
|
||||
void broadcastToAllWebSocketClients(const String& message);
|
||||
void broadcastToAllWebSocketClients(const JsonDocument& message);
|
||||
void publishToMqtt(const String& data);
|
||||
|
||||
// Bell overload notification (called by Telemetry / BellEngine)
|
||||
// Bell overload notification (called by Telemetry / BellEngine).
|
||||
// WS clients get the existing broadcastStatus() shape; MQTT gets a
|
||||
// dedicated control/reports publish — see publishReport().
|
||||
void sendBellOverloadNotification(const std::vector<uint8_t>& bellNumbers,
|
||||
const std::vector<uint16_t>& bellLoads,
|
||||
const String& severity);
|
||||
|
||||
/**
|
||||
* @brief Publish a subsystem alert to vesper/{id}/status/alerts.
|
||||
* @brief Publish a playback state transition to vesper/{id}/status/playback (retained).
|
||||
* Called by Player::setStatus() on every transition. WS clients
|
||||
* still receive the same event via broadcastStatus() separately —
|
||||
* this is the MQTT-specific path.
|
||||
*
|
||||
* @param action "playing" | "paused" | "idle"
|
||||
* @param timeElapsedSec Seconds since playback started (0 for idle)
|
||||
* @param projectedRunTimeMs Projected total run time in ms (0 if not applicable)
|
||||
*/
|
||||
void publishPlayback(const String& action, uint32_t timeElapsedSec, uint64_t projectedRunTimeMs);
|
||||
|
||||
/**
|
||||
* @brief Publish a critical, time-sensitive board-initiated event to
|
||||
* vesper/{id}/control/reports (e.g. bell overload). Not retained —
|
||||
* an event stream, not a status snapshot. Gated by its own topic switch.
|
||||
*
|
||||
* @param type Event type string e.g. "bell_overload"
|
||||
* @param payload JSON object with event-specific fields
|
||||
*/
|
||||
void publishReport(const String& type, const JsonDocument& payload);
|
||||
|
||||
/**
|
||||
* @brief Publish a subsystem alert to vesper/{id}/system/alerts.
|
||||
* Called by HealthMonitor when a subsystem state changes.
|
||||
* Only publishes on actual state change; no-ops if MQTT not connected.
|
||||
* Only publishes on actual state change; no-ops if MQTT not connected
|
||||
* or the "alerts" topic switch is off.
|
||||
*
|
||||
* @param subsystem Subsystem name e.g. "BellEngine"
|
||||
* @param newState New state string: "HEALTHY" | "WARNING" | "CRITICAL" | "FAILED"
|
||||
@@ -126,14 +155,22 @@ public:
|
||||
void publishAlert(const String& subsystem, const String& newState, const String& message = "");
|
||||
|
||||
/**
|
||||
* @brief Publish a general device info event to vesper/{id}/status/info.
|
||||
* Used for state changes such as playback start/stop, reboot reason, etc.
|
||||
* @brief Publish a general device info event to vesper/{id}/system/info.
|
||||
* Used for state changes such as boot report, diagnostics, etc.
|
||||
*
|
||||
* @param type Event type string e.g. "playback_started"
|
||||
* @param type Event type string e.g. "boot_report"
|
||||
* @param payload JSON object with event-specific fields (pass an empty doc for no payload)
|
||||
*/
|
||||
void publishInfo(const String& type, const JsonDocument& payload);
|
||||
|
||||
/**
|
||||
* @brief Publish structured telemetry to vesper/{id}/system/metrics.
|
||||
* Not consumed by the phone app — fleet-health graphing only.
|
||||
*
|
||||
* @param payload JSON object with metric fields (heap, RSSI, loop timing, bell heat, etc.)
|
||||
*/
|
||||
void publishMetrics(const JsonDocument& payload);
|
||||
|
||||
// Network state callbacks (called by Networking)
|
||||
void onNetworkConnected();
|
||||
void onNetworkDisconnected();
|
||||
@@ -148,12 +185,13 @@ private:
|
||||
void reportBootOnce();
|
||||
bool _bootReasonReported = false;
|
||||
|
||||
// Publishes a consolidated diagnostics_report to status/info every
|
||||
// Publishes a consolidated diagnostics report to system/metrics every
|
||||
// DIAGNOSTICS_REPORT_INTERVAL_MS (5 min) — CPU temperature (min/max/avg
|
||||
// since last report), WiFi reconnect count + last disconnect reason, OTA
|
||||
// check/update state, and per-task stack high-water marks. Checked from
|
||||
// loop() (millis()-diff, same style as Telemetry's own flush-interval
|
||||
// check) rather than a FreeRTOS timer. No-ops until _telemetry is set.
|
||||
// check/update state, per-task stack high-water marks, and bell strike/
|
||||
// heat-load metrics. Checked from loop() (millis()-diff, same style as
|
||||
// Telemetry's own flush-interval check) rather than a FreeRTOS timer.
|
||||
// No-ops until _telemetry is set.
|
||||
void reportDiagnosticsIfDue();
|
||||
uint32_t _lastDiagnosticsReportMs = 0;
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## Summary
|
||||
|
||||
`CommunicationRouter` is the top-level coordinator for all inbound and outbound communication. It owns the `CommandBus`, all five transport objects (`MQTTTransport`, `WebSocketTransport`, `HTTPTransport`, `UARTTransport`, `WebServerTransport`), and the three underlying protocol driver objects (`MQTTDriver`, `WebSocketDriver`, `UARTDriver`). It also owns `ClientManager`. On `begin()`, it initialises all transports, registers them with the bus, and calls `registerHandlers()` to bind all ten domain handlers to the bus. After that, the router largely gets out of the way: incoming messages are routed internally by the bus, and outbound unsolicited events (status, telemetry, bell strikes) are pushed through the broadcast helpers exposed on this class. All other subsystems that need to send data call into the router rather than touching transports directly.
|
||||
`CommunicationRouter` is the top-level coordinator for all inbound and outbound communication. It owns the `CommandBus`, all five transport objects (`MQTTTransport`, `WebSocketTransport`, `HTTPTransport`, `UARTTransport`, `WebServerTransport`), and the three underlying protocol driver objects (`MQTTDriver`, `WebSocketDriver`, `UARTDriver`). It also owns `ClientManager`. On `begin()`, it initialises all transports, registers them with the bus, and calls `registerHandlers()` to bind all ten domain handlers to the bus. After that, the router largely gets out of the way: incoming messages are routed internally by the bus, and outbound unsolicited events (status, telemetry, bell strikes) are pushed through the broadcast/publish helpers exposed on this class — WS-only broadcast helpers for WebSocket, and dedicated `publishXxx()` methods for each MQTT v2 topic (see `docs/reference/vesper_mqtt_topic_spec_v2.md`). All other subsystems that need to send data call into the router rather than touching transports directly.
|
||||
|
||||
---
|
||||
|
||||
@@ -41,16 +41,18 @@
|
||||
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `void broadcastStatus(const String& msg)` | Sends raw string to MQTT data topic and all WebSocket clients. |
|
||||
| `void broadcastStatus(const String& msg)` | WebSocket-only fan-out (all clients). No longer also publishes to MQTT — see the dedicated topic methods below for the MQTT equivalents. |
|
||||
| `void broadcastStatus(const JsonDocument& json)` | Serialises JSON then calls the string overload. |
|
||||
| `void broadcastToMasterClients(const String& msg)` | WebSocket only — master-classified clients. |
|
||||
| `void broadcastToSecondaryClients(const String& msg)` | WebSocket only — secondary-classified clients. |
|
||||
| `void broadcastToAllWebSocketClients(const String& msg)` | All WebSocket clients. |
|
||||
| `void broadcastToAllWebSocketClients(const JsonDocument& msg)` | Serialises then sends to all WebSocket clients. |
|
||||
| `void publishToMqtt(const String& data)` | Publishes to the device data topic. No-op if MQTT is not connected. |
|
||||
| `void sendBellOverloadNotification(const std::vector<uint8_t>& bells, const std::vector<uint16_t>& loads, const String& severity)` | Builds and broadcasts a structured `bell_overload` INFO event. |
|
||||
| `void publishAlert(const String& subsystem, const String& newState, const String& message)` | Publishes a subsystem state-change event to `vesper/{uid}/status/alerts` (QoS 1). `newState` is one of `"WARNING"`, `"CRITICAL"`, `"FAILED"`, or `"CLEARED"`. Called automatically by the HealthMonitor alert callback registered in `begin()`, and by `reportBootOnce()` for fault reset reasons. No-op if MQTT is not connected. |
|
||||
| `void publishInfo(const String& type, const JsonDocument& payload)` | Publishes a general device state event to `vesper/{uid}/status/info` (QoS 0). No-op if MQTT is not connected. Used for e.g. the `"boot_report"` event published once per boot — see below. |
|
||||
| `void sendBellOverloadNotification(const std::vector<uint8_t>& bells, const std::vector<uint16_t>& loads, const String& severity)` | WS clients get the existing `bell_overload` INFO event via `broadcastStatus()`. MQTT clients get the same data via `publishReport("bell_overload", ...)` on `control/reports` instead. |
|
||||
| `void publishPlayback(const String& action, uint32_t timeElapsedSec, uint64_t projectedRunTimeMs)` | Publishes a playback transition to `vesper/{uid}/status/playback` (QoS 1, retained). Called by `Player::setStatus()` on every transition, alongside the existing WS `broadcastStatus()` call. Gated by the `playback` topic switch. |
|
||||
| `void publishReport(const String& type, const JsonDocument& payload)` | Publishes a critical, unsolicited, time-sensitive event to `vesper/{uid}/control/reports` (QoS 1, not retained). Gated by the `reports` topic switch. |
|
||||
| `void publishAlert(const String& subsystem, const String& newState, const String& message)` | Publishes a subsystem state-change event to `vesper/{uid}/system/alerts` (QoS 1, retained until cleared). `newState` is one of `"WARNING"`, `"CRITICAL"`, `"FAILED"`, or `"CLEARED"`. Called automatically by the HealthMonitor alert callback registered in `begin()`, and by `reportBootOnce()` for fault reset reasons. No-op if MQTT is not connected or the `alerts` topic switch is off. |
|
||||
| `void publishInfo(const String& type, const JsonDocument& payload)` | Publishes a general device state event to `vesper/{uid}/system/info` (QoS 1, retained). No-op if MQTT is not connected or the `info` topic switch is off. Used for e.g. the `"boot_report"` event published once per boot — see below. |
|
||||
| `void publishMetrics(const JsonDocument& payload)` | Publishes structured telemetry to `vesper/{uid}/system/metrics` (QoS 0, not retained). Used by the 5-minute diagnostics report — see below. Gated by the `metrics` topic switch. |
|
||||
|
||||
### Network callbacks (called by Networking)
|
||||
|
||||
@@ -97,6 +99,8 @@ communication.begin();
|
||||
|
||||
If any required reference is null when `registerHandlers()` runs (inside `begin()`), the corresponding handler(s) are skipped and an `LOG_ERROR` is emitted. The bus still starts; commands for missing handlers return "Unknown command".
|
||||
|
||||
`begin()` also registers `MQTTDriver::setStateProvider()` — a lambda that reads `_player`/`_healthMonitor` at call time (not registration time) to derive the heartbeat's `state`/`ok` fields. Because `_player`/`_healthMonitor` are late-bound, this lambda safely returns `state="booting", ok=true` if called before `setPlayerReference()`/`setHealthMonitorReference()` run — in practice this never happens, since the heartbeat timer only starts once MQTT connects, well after `main.cpp` finishes wiring all references.
|
||||
|
||||
`AsyncWebServer::begin()` is **not** called inside `CommunicationRouter::begin()`. It is started from the network-connected callback in `main.cpp` to avoid conflicting with WiFiManager's captive portal on port 80.
|
||||
|
||||
---
|
||||
@@ -120,7 +124,7 @@ If any required reference is null when `registerHandlers()` runs (inside `begin(
|
||||
- **MQTT log suppression**: During `begin()`, the subsystem MQTT log levels for `"MQTTClient"` and `"CommRouter"` are explicitly suppressed to `NONE` and `WARNING` respectively to prevent feedback loops when MQTT is used as a log sink.
|
||||
- **Boot reporting**: `begin()` registers a one-shot `onConnect` callback on `MQTTDriver` (`reportBootOnce()`) that fires the first time MQTT connects after startup (including the very first connection). Guarded by `_bootReasonReported` so it only fires once per boot, not on every reconnect. It does two things:
|
||||
1. If `Telemetry::isFaultReset()` is true (panic, watchdog, brownout), publishes the existing fault alert via `publishAlert("System", "WARNING", "Device reset due to fault: " + reason)` — unchanged behavior/topic from before.
|
||||
2. **Always** — fault or not — publishes a consolidated `"boot_report"` event via `publishInfo` to `vesper/{uid}/status/info`:
|
||||
2. **Always** — fault or not — publishes a consolidated `"boot_report"` event via `publishInfo` to `vesper/{uid}/system/info`:
|
||||
```json
|
||||
{
|
||||
"type": "boot_report",
|
||||
@@ -137,16 +141,18 @@ If any required reference is null when `registerHandlers()` runs (inside `begin(
|
||||
}
|
||||
```
|
||||
`boot_count` is `Telemetry::getLifetimeBootCount()` — see [Telemetry's Boot tracking section](../../Telemetry/README.md#boot-tracking) for why this is a separate counter from `FirmwareValidator`'s NVS `boot_count`. The `crash` object is present only when a coredump was found for the crash that caused this boot (`CrashReport::available == true`) — omitted entirely on a clean/expected reset, or when no coredump was captured for a fault reset (e.g. a brownout, which doesn't produce one).
|
||||
- **Diagnostics reporting**: `loop()` calls `reportDiagnosticsIfDue()` every main-loop iteration, which no-ops until `DIAGNOSTICS_REPORT_INTERVAL_MS` (5 minutes, `Telemetry.hpp`) has elapsed and `_telemetry` is set. Unlike `reportBootOnce()` (a one-shot MQTT-onConnect callback), this is a plain `millis()`-diff check — same style as `Telemetry`'s own `RUNTIME_FLUSH_INTERVAL_MS` check — so it fires on a fixed wall-clock cadence regardless of MQTT connection churn (a no-op `publishInfo()` call if disconnected, same as any other info event). Publishes a consolidated `"diagnostics_report"` event to `vesper/{uid}/status/info`:
|
||||
- **Diagnostics/metrics reporting**: `loop()` calls `reportDiagnosticsIfDue()` every main-loop iteration, which no-ops until `DIAGNOSTICS_REPORT_INTERVAL_MS` (5 minutes, `Telemetry.hpp`) has elapsed and `_telemetry` is set. Unlike `reportBootOnce()` (a one-shot MQTT-onConnect callback), this is a plain `millis()`-diff check — same style as `Telemetry`'s own `RUNTIME_FLUSH_INTERVAL_MS` check — so it fires on a fixed wall-clock cadence regardless of MQTT connection churn (a no-op `publishMetrics()` call if disconnected). Publishes a consolidated payload to `vesper/{uid}/system/metrics` (not wrapped in a `"type"` envelope — the topic itself is the discriminator):
|
||||
```json
|
||||
{
|
||||
"type": "diagnostics_report",
|
||||
"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.7.3", "update_available": false, "last_check_uptime_ms": 180000, "last_error": "NONE" },
|
||||
"stack_high_water": { "TelemetryTask": 1024, "HealthMonitor": 890 }
|
||||
"stack_high_water": { "TelemetryTask": 1024, "HealthMonitor": 890 },
|
||||
"bell_strikes": { "0": 1234, "1": 567, "...": "..." },
|
||||
"bell_loads": { "0": 12, "1": 0, "...": "..." },
|
||||
"cooling_active": false
|
||||
}
|
||||
```
|
||||
`cpu_temp` pulls from `Telemetry::writeTemperatureStats()` then calls `resetDiagnosticsStats()` — the accumulator is consumed on the periodic path (unlike the on-demand `telemetry.get_diagnostics` command, which peeks without resetting). `wifi_reconnects`/`ota` read directly from the router's own `_networking`/`_otaManager` references (constructor-injected, not late-bound — no null guard needed). `stack_high_water` comes from `Telemetry::writeStackHighWaterMarks()`'s static task registry — see [Telemetry's Diagnostics reporting section](../../Telemetry/README.md#diagnostics-reporting) for the full design rationale (F-056 in the feature catalog), including why temperature alone needs local 15s sampling while the other three fields are read once per report.
|
||||
- **Broadcast vs CommandBus broadcast**: The `broadcastXxx()` helpers on this class send raw pre-serialised strings. `CommandBus::broadcast()` serialises a `CommandResult` and fans it out. They are separate paths; subsystems outside the communication layer use the router's helpers.
|
||||
`cpu_temp` pulls from `Telemetry::writeTemperatureStats()` then calls `resetDiagnosticsStats()` — the accumulator is consumed on the periodic path (unlike the on-demand `telemetry.get_diagnostics` command, which peeks without resetting). `wifi_reconnects`/`ota` read directly from the router's own `_networking`/`_otaManager` references (constructor-injected, not late-bound — no null guard needed). `stack_high_water` comes from `Telemetry::writeStackHighWaterMarks()`'s static task registry — see [Telemetry's Diagnostics reporting section](../../Telemetry/README.md#diagnostics-reporting) for the full design rationale (F-056 in the feature catalog), including why temperature alone needs local 15s sampling while the other three fields are read once per report. `bell_strikes`/`bell_loads`/`cooling_active` are read directly from `Telemetry::getStrikeCount()`/`getBellLoad()`/`isCoolingActive()` for all 16 bell channels — added when this report moved from `system/info` to `system/metrics`, matching the topic spec's explicit call-out of "bell heat ratings" for this topic.
|
||||
- **Broadcast vs CommandBus broadcast**: The `broadcastXxx()` helpers on this class send raw pre-serialised strings over WebSocket only. `CommandBus::broadcast()` serialises a `CommandResult` and fans it out to every registered transport, including MQTT's `control/ack` (see `MQTTTransport::broadcast()`). They are separate paths; subsystems outside the communication layer use whichever fits — the router's WS-only helpers for WS-specific fan-out, or the dedicated `publishXxx()` topic methods for MQTT-specific events.
|
||||
- **Handler skipping is silent to clients**: If a reference is null and a handler is not registered, the bus returns `{"status":"ERROR","type":"unknown","message":"Unknown command: ..."}`. There is no boot-time safeguard beyond the `LOG_ERROR` in `registerHandlers()`.
|
||||
|
||||
@@ -73,17 +73,22 @@ void MQTTDriver::begin() {
|
||||
|
||||
auto& mqttConfig = _configManager.getMqttConfig();
|
||||
|
||||
// Build topic strings (cache for performance)
|
||||
// Build topic strings (cache for performance) — see docs/reference/vesper_mqtt_topic_spec_v2.md
|
||||
String deviceUID = _configManager.getDeviceUID();
|
||||
_controlTopic = "vesper/" + deviceUID + "/control";
|
||||
_dataTopic = "vesper/" + deviceUID + "/data";
|
||||
_alertsTopic = "vesper/" + deviceUID + "/status/alerts";
|
||||
_infoTopic = "vesper/" + deviceUID + "/status/info";
|
||||
_commandTopic = "vesper/" + deviceUID + "/control/command";
|
||||
_ackTopic = "vesper/" + deviceUID + "/control/ack";
|
||||
_heartbeatTopic = "vesper/" + deviceUID + "/status/heartbeat";
|
||||
_playbackTopic = "vesper/" + deviceUID + "/status/playback";
|
||||
_reportsTopic = "vesper/" + deviceUID + "/control/reports";
|
||||
_alertsTopic = "vesper/" + deviceUID + "/system/alerts";
|
||||
_infoTopic = "vesper/" + deviceUID + "/system/info";
|
||||
_logsTopic = "vesper/" + deviceUID + "/system/logs";
|
||||
_metricsTopic = "vesper/" + deviceUID + "/system/metrics";
|
||||
_clientId = "vesper-" + deviceUID;
|
||||
|
||||
LOG_INFO(TAG, "MQTT Topics: control=%s, data=%s, alerts=%s, info=%s",
|
||||
_controlTopic.c_str(), _dataTopic.c_str(),
|
||||
_alertsTopic.c_str(), _infoTopic.c_str());
|
||||
LOG_INFO(TAG, "MQTT Topics: command=%s, ack=%s, heartbeat=%s, playback=%s, reports=%s, alerts=%s, info=%s, logs=%s, metrics=%s",
|
||||
_commandTopic.c_str(), _ackTopic.c_str(), _heartbeatTopic.c_str(), _playbackTopic.c_str(),
|
||||
_reportsTopic.c_str(), _alertsTopic.c_str(), _infoTopic.c_str(), _logsTopic.c_str(), _metricsTopic.c_str());
|
||||
|
||||
// Setup event handlers
|
||||
_mqttClient.onConnect([this](bool sessionPresent) {
|
||||
@@ -117,9 +122,27 @@ void MQTTDriver::begin() {
|
||||
_mqttClient.setKeepAlive(15);
|
||||
_mqttClient.setCleanSession(true);
|
||||
|
||||
// Last Will and Testament — the broker publishes this to status/heartbeat
|
||||
// (retained) automatically if the connection drops uncleanly (network loss,
|
||||
// crash, power loss). Must be re-registered on every reconnect, which is
|
||||
// automatic here since setWill() is applied on every begin()/connect() —
|
||||
// AsyncMqttClient resends CONNECT (with Will) on every reconnection attempt.
|
||||
String willPayload = buildOfflinePayload();
|
||||
_mqttClient.setWill(_heartbeatTopic.c_str(), 1, true, willPayload.c_str());
|
||||
|
||||
LOG_INFO(TAG, "✅ MQTT Async Client initialized");
|
||||
}
|
||||
|
||||
String MQTTDriver::buildOfflinePayload() const {
|
||||
JsonDocument doc;
|
||||
doc["device_id"] = _configManager.getDeviceUID();
|
||||
doc["state"] = "offline";
|
||||
doc["ok"] = false;
|
||||
String out;
|
||||
serializeJson(doc, out);
|
||||
return out;
|
||||
}
|
||||
|
||||
void MQTTDriver::connect() {
|
||||
auto& mqttConfig = _configManager.getMqttConfig();
|
||||
|
||||
@@ -144,7 +167,15 @@ void MQTTDriver::connect() {
|
||||
LOG_INFO(TAG, "MQTT connect() called - waiting for async connection...");
|
||||
}
|
||||
|
||||
void MQTTDriver::disconnect() {
|
||||
void MQTTDriver::disconnect(bool graceful) {
|
||||
if (graceful && _mqttClient.connected()) {
|
||||
// LWT only fires on an *unclean* disconnect — announce offline explicitly
|
||||
// before a clean one so status/heartbeat doesn't keep a stale "online"
|
||||
// retained message around (e.g. before an OTA flash).
|
||||
String offlinePayload = buildOfflinePayload();
|
||||
_mqttClient.publish(_heartbeatTopic.c_str(), 1, true, offlinePayload.c_str());
|
||||
LOG_INFO(TAG, "Published graceful offline heartbeat before disconnect");
|
||||
}
|
||||
_mqttClient.disconnect();
|
||||
LOG_INFO(TAG, "Disconnected from MQTT broker");
|
||||
}
|
||||
@@ -160,7 +191,7 @@ bool MQTTDriver::hasHeapForPublish() const {
|
||||
return false;
|
||||
}
|
||||
|
||||
uint16_t MQTTDriver::publish(const String& topic, const String& payload, int qos, bool retain) {
|
||||
uint16_t MQTTDriver::publishAck(const String& payload, int qos, bool retain) {
|
||||
// Check if connected before attempting to publish
|
||||
if (!_mqttClient.connected()) {
|
||||
// Don't log error here - would cause infinite loop with MQTT logging
|
||||
@@ -168,13 +199,15 @@ uint16_t MQTTDriver::publish(const String& topic, const String& payload, int qos
|
||||
}
|
||||
if (!hasHeapForPublish()) return 0;
|
||||
|
||||
// Build full topic (if relative)
|
||||
String fullTopic = topic.startsWith("vesper/") ? topic : _dataTopic;
|
||||
// control/ack shares the "command" topic switch with control/command — if a
|
||||
// client somehow gets a reply queued while the switch just got turned off
|
||||
// mid-flight, drop it rather than publish to a channel the operator disabled.
|
||||
if (!_configManager.getMqttTopicConfig().command) return 0;
|
||||
|
||||
uint16_t packetId = _mqttClient.publish(fullTopic.c_str(), qos, retain, payload.c_str());
|
||||
uint16_t packetId = _mqttClient.publish(_ackTopic.c_str(), qos, retain, payload.c_str());
|
||||
|
||||
if (packetId > 0) {
|
||||
LOG_DEBUG(TAG, "Published to %s: %s (packetId=%d)", fullTopic.c_str(), payload.c_str(), packetId);
|
||||
LOG_DEBUG(TAG, "Published to %s: %s (packetId=%d)", _ackTopic.c_str(), payload.c_str(), packetId);
|
||||
}
|
||||
// REMOVED: Error logging here to prevent infinite recursion with MQTT logs
|
||||
|
||||
@@ -236,8 +269,15 @@ void MQTTDriver::onNetworkDisconnected() {
|
||||
}
|
||||
|
||||
void MQTTDriver::subscribe() {
|
||||
uint16_t packetId = _mqttClient.subscribe(_controlTopic.c_str(), 0);
|
||||
LOG_INFO(TAG, "📬 Subscribing to control topic: %s (packetId=%d)", _controlTopic.c_str(), packetId);
|
||||
// Gated by the "command" topic switch — a device that doesn't need remote
|
||||
// control (e.g. fleet-monitoring-only) can turn this off entirely and skip
|
||||
// both control/command (this subscribe) and control/ack (its replies).
|
||||
if (!_configManager.getMqttTopicConfig().command) {
|
||||
LOG_INFO(TAG, "control/command subscription skipped — 'command' topic switch is off");
|
||||
return;
|
||||
}
|
||||
uint16_t packetId = _mqttClient.subscribe(_commandTopic.c_str(), 1);
|
||||
LOG_INFO(TAG, "📬 Subscribing to control/command topic: %s (packetId=%d)", _commandTopic.c_str(), packetId);
|
||||
}
|
||||
|
||||
void MQTTDriver::onMqttConnect(bool sessionPresent) {
|
||||
@@ -316,6 +356,18 @@ void MQTTDriver::onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
|
||||
|
||||
}
|
||||
|
||||
void MQTTDriver::applyCommandTopicSwitch(bool enabled) {
|
||||
if (!_mqttClient.connected()) return; // picked up naturally by subscribe() on next connect
|
||||
|
||||
if (enabled) {
|
||||
uint16_t packetId = _mqttClient.subscribe(_commandTopic.c_str(), 1);
|
||||
LOG_INFO(TAG, "control/command switch turned on — subscribing live (packetId=%d)", packetId);
|
||||
} else {
|
||||
uint16_t packetId = _mqttClient.unsubscribe(_commandTopic.c_str());
|
||||
LOG_INFO(TAG, "control/command switch turned off — unsubscribing live (packetId=%d)", packetId);
|
||||
}
|
||||
}
|
||||
|
||||
void MQTTDriver::onMqttSubscribe(uint16_t packetId, uint8_t qos) {
|
||||
LOG_INFO(TAG, "✅ Subscribed to topic (packetId=%d, QoS=%d)", packetId, qos);
|
||||
}
|
||||
@@ -392,60 +444,48 @@ void MQTTDriver::publishHeartbeat() {
|
||||
LOG_WARNING(TAG, "⚠️ Cannot publish heartbeat - MQTT not connected");
|
||||
return;
|
||||
}
|
||||
if (!_configManager.getMqttTopicConfig().heartbeat) return;
|
||||
if (!hasHeapForPublish()) return; // skip building the JsonDocument too, not just the publish
|
||||
|
||||
// Build heartbeat JSON message
|
||||
// Build heartbeat JSON message — flat shape per docs/reference/vesper_mqtt_topic_spec_v2.md.
|
||||
// state/ok are independently derived via _stateProvider, never mirrored from
|
||||
// status/playback or system/alerts.
|
||||
JsonDocument doc;
|
||||
doc["status"] = "INFO";
|
||||
doc["type"] = "heartbeat";
|
||||
|
||||
JsonObject payload = doc["payload"].to<JsonObject>();
|
||||
doc["device_id"] = _configManager.getDeviceUID();
|
||||
|
||||
// Device ID from NVS
|
||||
payload["device_id"] = _configManager.getDeviceUID();
|
||||
DeviceState ds = _stateProvider ? _stateProvider() : DeviceState{"booting", true};
|
||||
doc["state"] = ds.state;
|
||||
doc["ok"] = ds.ok;
|
||||
|
||||
// Firmware version
|
||||
payload["firmware_version"] = _configManager.getFwVersion();
|
||||
doc["fw_version"] = _configManager.getFwVersion();
|
||||
|
||||
// Current date/time (from TimeKeeper if available, else uptime-based)
|
||||
// For now, we'll use a simple timestamp format
|
||||
unsigned long uptimeMs = millis();
|
||||
unsigned long uptimeSec = uptimeMs / 1000;
|
||||
unsigned long hours = uptimeSec / 3600;
|
||||
unsigned long minutes = (uptimeSec % 3600) / 60;
|
||||
unsigned long seconds = uptimeSec % 60;
|
||||
doc["uptime_ms"] = uptimeMs;
|
||||
|
||||
char timestampStr[64];
|
||||
snprintf(timestampStr, sizeof(timestampStr), "Uptime: %luh %lum %lus", hours, minutes, seconds);
|
||||
payload["timestamp"] = timestampStr;
|
||||
char uptimeHuman[32];
|
||||
snprintf(uptimeHuman, sizeof(uptimeHuman), "%luh %lum %lus", hours, minutes, seconds);
|
||||
doc["uptime_human"] = uptimeHuman;
|
||||
|
||||
// IP address
|
||||
payload["ip_address"] = _networking.getLocalIP();
|
||||
|
||||
// Gateway address
|
||||
payload["gateway"] = _networking.getGateway();
|
||||
|
||||
// Uptime in milliseconds
|
||||
payload["uptime_ms"] = uptimeMs;
|
||||
|
||||
// WiFi signal strength
|
||||
payload["rssi"] = WiFi.RSSI();
|
||||
|
||||
// Free heap (bytes) — lets the console chart heap trend over time instead of
|
||||
// only seeing one sample per boot (via boot_report)
|
||||
payload["free_heap"] = ESP.getFreeHeap();
|
||||
doc["ip_address"] = _networking.getLocalIP();
|
||||
doc["gateway"] = _networking.getGateway();
|
||||
doc["rssi"] = WiFi.RSSI();
|
||||
doc["free_heap"] = ESP.getFreeHeap();
|
||||
|
||||
// Serialize to string
|
||||
String heartbeatMessage;
|
||||
serializeJson(doc, heartbeatMessage);
|
||||
|
||||
// Publish to heartbeat topic with RETAIN flag
|
||||
String heartbeatTopic = "vesper/" + _configManager.getDeviceUID() + "/status/heartbeat";
|
||||
uint16_t packetId = _mqttClient.publish(heartbeatTopic.c_str(), 1, true, heartbeatMessage.c_str());
|
||||
uint16_t packetId = _mqttClient.publish(_heartbeatTopic.c_str(), 1, true, heartbeatMessage.c_str());
|
||||
|
||||
if (packetId > 0) {
|
||||
LOG_DEBUG(TAG, "💓 Published heartbeat (retained) - IP: %s, Uptime: %lums",
|
||||
_networking.getLocalIP().c_str(), uptimeMs);
|
||||
LOG_DEBUG(TAG, "💓 Published heartbeat (retained) - state: %s, IP: %s, Uptime: %lums",
|
||||
ds.state.c_str(), _networking.getLocalIP().c_str(), uptimeMs);
|
||||
} else {
|
||||
LOG_ERROR(TAG, "❌ Failed to publish heartbeat");
|
||||
}
|
||||
|
||||
@@ -43,23 +43,31 @@ public:
|
||||
void connect();
|
||||
|
||||
/**
|
||||
* @brief Disconnect from MQTT broker
|
||||
* @brief Disconnect from MQTT broker.
|
||||
* @param graceful If true, explicitly publishes the retained offline payload to
|
||||
* status/heartbeat before disconnecting cleanly — the broker's LWT only
|
||||
* fires on an *unclean* disconnect, so an intentional disconnect (e.g.
|
||||
* before an OTA flash) would otherwise leave the last "online" heartbeat
|
||||
* retained and misleading. Default false preserves existing call sites'
|
||||
* behaviour (e.g. mqtt.disable, which does want a clean disconnect with
|
||||
* no offline announcement — the broker keeps whatever was last retained).
|
||||
*/
|
||||
void disconnect();
|
||||
void disconnect(bool graceful = false);
|
||||
|
||||
/**
|
||||
* @brief Publish message to MQTT
|
||||
* @param topic Topic to publish to (relative, will prepend "vesper/{deviceID}/")
|
||||
* If empty string — publishes to the data topic.
|
||||
* @brief Publish a reply to the control/ack topic.
|
||||
* @param payload Message payload
|
||||
* @param qos QoS level (0, 1, or 2)
|
||||
* @param retain Retain flag
|
||||
* @return Packet ID (0 if failed)
|
||||
* @return Packet ID (0 if failed, MQTT disabled, low heap, or the "command"
|
||||
* topic switch is off — control/ack shares that switch with control/command)
|
||||
*/
|
||||
uint16_t publish(const String& topic, const String& payload, int qos = 0, bool retain = false);
|
||||
uint16_t publishAck(const String& payload, int qos = 1, bool retain = false);
|
||||
|
||||
/**
|
||||
* @brief Publish to an absolute, fully-qualified topic (no prefix applied).
|
||||
* Used for topics whose gating is decided by the caller (e.g.
|
||||
* CommunicationRouter checking the relevant MqttTopicConfig flag).
|
||||
* @param fullTopic Complete topic string
|
||||
* @param payload Message payload
|
||||
* @param qos QoS level (0, 1, or 2)
|
||||
@@ -80,14 +88,35 @@ public:
|
||||
*/
|
||||
void setOnConnectCallback(std::function<void(bool sessionPresent)> callback) { _onConnectCallback = callback; }
|
||||
|
||||
/**
|
||||
* @brief Register the callback used to derive the heartbeat's "state" and
|
||||
* "ok" fields. Per the v2 spec these must be independently derived,
|
||||
* not mirrored from status/playback or system/alerts — this callback
|
||||
* is the one place that derivation happens.
|
||||
* state: "idle" | "playing" | "paused" | "error" | "booting"
|
||||
* ok: overall device health, independent of playback state
|
||||
* Wired by CommunicationRouter from Player + HealthMonitor. If never
|
||||
* set, heartbeats report state="booting", ok=true (subsystems not
|
||||
* wired up yet, not necessarily unhealthy).
|
||||
*/
|
||||
struct DeviceState { String state; bool ok; };
|
||||
void setStateProvider(std::function<DeviceState()> provider) { _stateProvider = provider; }
|
||||
|
||||
/**
|
||||
* @brief Check if connected to MQTT broker
|
||||
*/
|
||||
bool isConnected() const;
|
||||
|
||||
/** @brief Full topic strings (read-only, available after begin()) */
|
||||
const String& getCommandTopic() const { return _commandTopic; } // control/command (subscribe)
|
||||
const String& getAckTopic() const { return _ackTopic; } // control/ack (reply)
|
||||
const String& getHeartbeatTopic() const { return _heartbeatTopic; }
|
||||
const String& getPlaybackTopic() const { return _playbackTopic; }
|
||||
const String& getReportsTopic() const { return _reportsTopic; }
|
||||
const String& getAlertsTopic() const { return _alertsTopic; }
|
||||
const String& getInfoTopic() const { return _infoTopic; }
|
||||
const String& getLogsTopic() const { return _logsTopic; }
|
||||
const String& getMetricsTopic() const { return _metricsTopic; }
|
||||
|
||||
/**
|
||||
* @brief Handle network connection callback
|
||||
@@ -99,6 +128,14 @@ public:
|
||||
*/
|
||||
void onNetworkDisconnected();
|
||||
|
||||
/**
|
||||
* @brief Live-apply a change to the "command" topic switch without waiting
|
||||
* for a reconnect. Subscribes/unsubscribes control/command immediately
|
||||
* if currently connected; no-ops otherwise (the new setting is picked
|
||||
* up naturally by subscribe() on the next connect via ConfigManager).
|
||||
*/
|
||||
void applyCommandTopicSwitch(bool enabled);
|
||||
|
||||
// Minimum free heap (bytes) required before attempting a publish. Below this,
|
||||
// AsyncMqttClient's internal packet-buffer allocation risks failing outright —
|
||||
// this SDK build has CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE=0, so a failed
|
||||
@@ -117,15 +154,24 @@ private:
|
||||
AsyncMqttClient _mqttClient;
|
||||
MessageCallback _messageCallback;
|
||||
std::function<void(bool sessionPresent)> _onConnectCallback;
|
||||
std::function<DeviceState()> _stateProvider;
|
||||
|
||||
|
||||
// Device topic strings (cached for performance)
|
||||
String _controlTopic;
|
||||
String _dataTopic;
|
||||
String _alertsTopic; // vesper/{id}/status/alerts
|
||||
String _infoTopic; // vesper/{id}/status/info
|
||||
// Device topic strings (cached for performance) — see docs/reference/vesper_mqtt_topic_spec_v2.md
|
||||
String _commandTopic; // vesper/{id}/control/command (subscribe)
|
||||
String _ackTopic; // vesper/{id}/control/ack (reply)
|
||||
String _heartbeatTopic; // vesper/{id}/status/heartbeat
|
||||
String _playbackTopic; // vesper/{id}/status/playback
|
||||
String _reportsTopic; // vesper/{id}/control/reports
|
||||
String _alertsTopic; // vesper/{id}/system/alerts
|
||||
String _infoTopic; // vesper/{id}/system/info
|
||||
String _logsTopic; // vesper/{id}/system/logs
|
||||
String _metricsTopic; // vesper/{id}/system/metrics
|
||||
String _clientId; // Store client ID to keep it alive
|
||||
|
||||
// Builds the retained LWT/offline payload: {"state":"offline","ok":false}
|
||||
String buildOfflinePayload() const;
|
||||
|
||||
/**
|
||||
* @brief Subscribe to control topic
|
||||
*/
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
|
||||
## 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, and network-stabilisation delay. 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`. The driver uses three FreeRTOS software timers with one-shot tasks deferred off the Tmr Svc stack to avoid stack overflows in timer callbacks.
|
||||
|
||||
Topics:
|
||||
- Control (inbound): `vesper/{uid}/control`
|
||||
- Data (outbound): `vesper/{uid}/data`
|
||||
- Heartbeat (retained, QoS 1): `vesper/{uid}/status/heartbeat`
|
||||
- Alerts (state-change events, QoS 1): `vesper/{uid}/status/alerts`
|
||||
- Info (general state events, QoS 0): `vesper/{uid}/status/info`
|
||||
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:
|
||||
|
||||
- `control/command` (inbound, subscribe) — gated by the `command` topic switch
|
||||
- `control/ack` (outbound replies) — gated by the `command` topic switch
|
||||
- `status/heartbeat` (retained, QoS 1) — gated by the `heartbeat` topic switch
|
||||
- `status/playback`, `control/reports`, `system/alerts`, `system/info`, `system/logs`, `system/metrics` — published directly by `CommunicationRouter` via `publishDirect()`, each gated by its own topic switch (see [CommunicationRouter](../../CommunicationRouter/README.md))
|
||||
|
||||
---
|
||||
|
||||
@@ -18,16 +18,17 @@ Topics:
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `MQTTDriver(ConfigManager& configManager, Networking& networking)` | Constructor. Creates the three FreeRTOS timers. Sets the global `_instance` pointer. |
|
||||
| `void begin()` | Caches topic strings, registers AsyncMqttClient event handlers, configures broker host/port/credentials/keepalive. Does not connect. |
|
||||
| `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()` | Disconnects cleanly. |
|
||||
| `uint16_t publish(const String& topic, const String& payload, int qos, bool retain)` | Publishes to `topic`. If `topic` does not start with `"vesper/"`, it is treated as relative and the full data topic is used instead. Returns packet ID, or 0 on failure (not connected, or free heap below `hasHeapForPublish()`'s threshold). |
|
||||
| `uint16_t publishDirect(const String& fullTopic, const String& payload, int qos, bool retain)` | Publishes to an absolute, fully-qualified topic — no prefix is applied. Used by `CommunicationRouter` to target `status/alerts` and `status/info` topics directly. Same heap guard as `publish()`. |
|
||||
| `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 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& getAlertsTopic() const` | Returns the cached `vesper/{uid}/status/alerts` topic string. Available after `begin()`. |
|
||||
| `const String& getInfoTopic() const` | Returns the cached `vesper/{uid}/status/info` topic string. Available after `begin()`. |
|
||||
| `const String& getCommandTopic() const` / `getAckTopic()` / `getHeartbeatTopic()` / `getPlaybackTopic()` / `getReportsTopic()` / `getAlertsTopic()` / `getInfoTopic()` / `getLogsTopic()` / `getMetricsTopic()` | Cached full topic strings, available after `begin()`. |
|
||||
| `void setCallback(MessageCallback callback)` | Registers the message-received callback. Called by `MQTTTransport::begin()`. |
|
||||
| `void setOnConnectCallback(std::function<void(bool sessionPresent)> callback)` | Registers a callback fired once each time MQTT successfully connects (including reconnects). Used by `CommunicationRouter` for one-shot "publish now that we're online" work such as reporting the boot/reset reason. |
|
||||
| `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()`. |
|
||||
@@ -61,16 +62,47 @@ Reconnect attempts are reset to 0 on a successful connection or a new `onNetwork
|
||||
|
||||
---
|
||||
|
||||
## 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()`.
|
||||
|
||||
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.
|
||||
|
||||
### Graceful disconnect
|
||||
|
||||
`disconnect(true)` publishes the same offline payload explicitly, with `retain=true`, before calling the underlying clean disconnect — this prevents a stale "online" heartbeat from staying retained after an intentional disconnect (e.g. `mqtt.disable`, or before an OTA flash). `disconnect(false)` (the default) skips this and disconnects immediately — used where the caller doesn't want an offline announcement (rare; most call sites should use `graceful=true`).
|
||||
|
||||
---
|
||||
|
||||
## Heartbeat
|
||||
|
||||
Once connected, a heartbeat is published immediately and then every 30 seconds to `vesper/{uid}/status/heartbeat` with `retain = true`. Heartbeat payload includes `device_id`, `firmware_version`, `ip_address`, `gateway`, `uptime_ms`, `rssi`, `free_heap` (bytes, via `ESP.getFreeHeap()` — added so a console can chart heap trend over time from the same 30s cadence as RSSI, rather than only seeing one heap sample per boot via `boot_report`), and an uptime string. The heartbeat timer is stopped on disconnect and restarted on reconnect.
|
||||
Once connected, a heartbeat is published immediately and then every 30 seconds to `status/heartbeat` with `retain = true`, gated by the `heartbeat` topic switch. Payload (flat, no envelope wrapper):
|
||||
|
||||
```json
|
||||
{
|
||||
"device_id": "PV000000000000",
|
||||
"state": "idle",
|
||||
"ok": true,
|
||||
"fw_version": "2.1.1",
|
||||
"uptime_ms": 19425000,
|
||||
"uptime_human": "5h 23m 45s",
|
||||
"ip_address": "10.0.0.3",
|
||||
"gateway": "10.0.0.1",
|
||||
"rssi": -62,
|
||||
"free_heap": 142000
|
||||
}
|
||||
```
|
||||
|
||||
`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.
|
||||
|
||||
---
|
||||
|
||||
## Dependencies
|
||||
|
||||
- `AsyncMqttClient` — broker protocol
|
||||
- `ConfigManager` — MQTT host, port, credentials, enabled flag, device UID
|
||||
- `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
|
||||
- `Logging`
|
||||
@@ -82,8 +114,9 @@ Once connected, a heartbeat is published immediately and then every 30 seconds t
|
||||
- **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.** `publish()` does not log an error when `_mqttClient.publish()` returns 0 (packet ID failure), because `publish()` is also called from the MQTT log channel and logging an error there would recurse infinitely.
|
||||
- **Free-heap guard before publishing (`hasHeapForPublish()`).** Below `MIN_FREE_HEAP_FOR_PUBLISH` (20KB), `publish()`, `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.
|
||||
- **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.
|
||||
- **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 and configures the server. Calling `connect()` before `begin()` will silently do nothing useful.
|
||||
- **`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.
|
||||
- **`onConnect` callback fires on every connect, not just the first.** `setOnConnectCallback` fires on every successful connection, including reconnects after a drop — callers that want "once per boot" semantics (like `CommunicationRouter::reportBootOnce()`) must track that themselves.
|
||||
- **`command` topic switch gates both directions.** Turning `command` off both unsubscribes `control/command` (no more inbound commands) and blocks `publishAck()` (no more outbound replies) — see `docs/reference/vesper_mqtt_topic_spec_v2.md`. The other seven switches (`heartbeat`, `playback`, `reports`, `alerts`, `info`, `logs`, `metrics`) are checked by their respective publishers, not inside this driver — `publishDirect()` itself does not know which topic switch applies to the topic it's given.
|
||||
|
||||
@@ -9,11 +9,14 @@ MQTTHandler::MQTTHandler(ConfigManager& configManager, MQTTDriver& mqttClient)
|
||||
: _configManager(configManager), _mqttClient(mqttClient) {}
|
||||
|
||||
std::vector<String> MQTTHandler::commands() const {
|
||||
return { "mqtt.enable", "mqtt.disable", "mqtt.get_config" };
|
||||
return { "mqtt.enable", "mqtt.disable", "mqtt.get_config",
|
||||
"mqtt.get_topics", "mqtt.set_topics" };
|
||||
}
|
||||
|
||||
CommandResult MQTTHandler::execute(const CommandEnvelope& envelope) {
|
||||
if (envelope.command == "mqtt.get_config") return handleGetConfig(envelope);
|
||||
if (envelope.command == "mqtt.get_topics") return handleGetTopics(envelope);
|
||||
if (envelope.command == "mqtt.set_topics") return handleSetTopics(envelope);
|
||||
|
||||
bool enable = (envelope.command == "mqtt.enable");
|
||||
|
||||
@@ -26,7 +29,10 @@ CommandResult MQTTHandler::execute(const CommandEnvelope& envelope) {
|
||||
if (enable) {
|
||||
_mqttClient.connect();
|
||||
} else {
|
||||
_mqttClient.disconnect();
|
||||
// Graceful: announce offline on status/heartbeat before disconnecting —
|
||||
// LWT only fires on an unclean drop, so an intentional disable would
|
||||
// otherwise leave a stale "online" retained heartbeat behind.
|
||||
_mqttClient.disconnect(true);
|
||||
}
|
||||
|
||||
LOG_INFO(TAG, "MQTT %s by user command", enable ? "enabled" : "disabled");
|
||||
@@ -44,3 +50,56 @@ CommandResult MQTTHandler::handleGetConfig(const CommandEnvelope& e) {
|
||||
doc["use_ssl"] = mqttCfg.useSSL;
|
||||
return CommandResult::ok("mqtt.get_config", doc);
|
||||
}
|
||||
|
||||
CommandResult MQTTHandler::handleGetTopics(const CommandEnvelope& e) {
|
||||
const auto& t = _configManager.getMqttTopicConfig();
|
||||
JsonDocument doc;
|
||||
doc["command"] = t.command;
|
||||
doc["heartbeat"] = t.heartbeat;
|
||||
doc["playback"] = t.playback;
|
||||
doc["reports"] = t.reports;
|
||||
doc["alerts"] = t.alerts;
|
||||
doc["info"] = t.info;
|
||||
doc["logs"] = t.logs;
|
||||
doc["metrics"] = t.metrics;
|
||||
return CommandResult::ok("mqtt.get_topics", doc);
|
||||
}
|
||||
|
||||
CommandResult MQTTHandler::handleSetTopics(const CommandEnvelope& e) {
|
||||
// Partial update — only fields present in contents are changed, matching
|
||||
// the "at least one field, partial OK" handler convention used elsewhere
|
||||
// (relay.set_durations, network.set_config, etc.). These switches only
|
||||
// take effect while the mqtt.enable master switch is on.
|
||||
ConfigManager::MqttTopicConfig t = _configManager.getMqttTopicConfig();
|
||||
bool any = false;
|
||||
|
||||
if (e.contents["command"].is<bool>()) { t.command = e.contents["command"].as<bool>(); any = true; }
|
||||
if (e.contents["heartbeat"].is<bool>()) { t.heartbeat = e.contents["heartbeat"].as<bool>(); any = true; }
|
||||
if (e.contents["playback"].is<bool>()) { t.playback = e.contents["playback"].as<bool>(); any = true; }
|
||||
if (e.contents["reports"].is<bool>()) { t.reports = e.contents["reports"].as<bool>(); any = true; }
|
||||
if (e.contents["alerts"].is<bool>()) { t.alerts = e.contents["alerts"].as<bool>(); any = true; }
|
||||
if (e.contents["info"].is<bool>()) { t.info = e.contents["info"].as<bool>(); any = true; }
|
||||
if (e.contents["logs"].is<bool>()) { t.logs = e.contents["logs"].as<bool>(); any = true; }
|
||||
if (e.contents["metrics"].is<bool>()) { t.metrics = e.contents["metrics"].as<bool>(); any = true; }
|
||||
|
||||
if (!any) {
|
||||
return CommandResult::err("mqtt.set_topics",
|
||||
"No recognised topic fields in contents (command, heartbeat, playback, reports, alerts, info, logs, metrics)");
|
||||
}
|
||||
|
||||
bool wasCommandOn = _configManager.getMqttTopicConfig().command;
|
||||
_configManager.setMqttTopicConfig(t);
|
||||
|
||||
if (!_configManager.saveGeneralConfig()) {
|
||||
return CommandResult::err("mqtt.set_topics", "Topic switches changed but failed to save to SD");
|
||||
}
|
||||
|
||||
// command topic switch controls the control/command subscription — flip
|
||||
// the live subscription immediately rather than waiting for a reconnect.
|
||||
if (wasCommandOn != t.command) {
|
||||
_mqttClient.applyCommandTopicSwitch(t.command);
|
||||
}
|
||||
|
||||
LOG_INFO(TAG, "MQTT topic switches updated");
|
||||
return CommandResult::ok("mqtt.set_topics", "MQTT topic switches updated and saved");
|
||||
}
|
||||
|
||||
@@ -20,4 +20,6 @@ private:
|
||||
MQTTDriver& _mqttClient;
|
||||
|
||||
CommandResult handleGetConfig(const CommandEnvelope& e);
|
||||
CommandResult handleGetTopics(const CommandEnvelope& e);
|
||||
CommandResult handleSetTopics(const CommandEnvelope& e);
|
||||
};
|
||||
|
||||
@@ -32,7 +32,13 @@ bool MQTTTransport::isHealthy() const {
|
||||
}
|
||||
|
||||
void MQTTTransport::broadcast(const String& message) {
|
||||
_mqtt.publish("", message); // MQTTDriver::publish() routes "" → _dataTopic
|
||||
// Unsolicited bus-wide broadcasts (e.g. CommandBus::broadcast()) go out on
|
||||
// control/ack alongside command replies — control/ack is the only outbound
|
||||
// channel this transport owns for arbitrary CommandResult-shaped messages.
|
||||
// Purpose-specific events (playback transitions, alerts, reports) are
|
||||
// published directly by CommunicationRouter to their own dedicated topics
|
||||
// instead of going through this path.
|
||||
_mqtt.publishAck(message);
|
||||
}
|
||||
|
||||
void MQTTTransport::onNetworkConnected() {
|
||||
@@ -69,6 +75,13 @@ void MQTTTransport::onMessage(const String& topic, const String& payload) {
|
||||
envelope.command = doc["cmd"].as<String>();
|
||||
envelope.version = doc["v"] | 1;
|
||||
|
||||
// req_id is optional (see CommandEnvelope.hpp) — a v1 client, or any caller
|
||||
// not fanning requests out over a shared channel, simply omits it and gets
|
||||
// a reply with no req_id field, same as before this was added.
|
||||
if (doc.containsKey("req_id")) {
|
||||
envelope.reqId = doc["req_id"].as<String>();
|
||||
}
|
||||
|
||||
if (doc.containsKey("contents")) {
|
||||
envelope.contents.set(doc["contents"]);
|
||||
}
|
||||
@@ -82,7 +95,7 @@ void MQTTTransport::onMessage(const String& topic, const String& payload) {
|
||||
// envelope.version to 2 post-translation (see LegacyAdapter.hpp).
|
||||
bool isLegacyRequest = (envelope.version == 1);
|
||||
|
||||
// Reply lambda — publishes the response back to the MQTT data topic
|
||||
// Reply lambda — publishes the response back to control/ack
|
||||
envelope.reply = [this, isLegacyRequest](const CommandResult& result) {
|
||||
JsonDocument resp;
|
||||
if (!isLegacyRequest || !translateLegacyResponse(result, resp)) {
|
||||
@@ -96,9 +109,16 @@ void MQTTTransport::onMessage(const String& topic, const String& payload) {
|
||||
resp["data"] = result.data;
|
||||
}
|
||||
}
|
||||
// Always echo req_id on the outer envelope, even for legacy-translated
|
||||
// replies — translateLegacyResponse() only rewrites the v1-known shape,
|
||||
// it doesn't know about req_id, and legacy clients simply ignore the
|
||||
// extra field.
|
||||
if (!result.reqId.isEmpty()) {
|
||||
resp["req_id"] = result.reqId;
|
||||
}
|
||||
String out;
|
||||
serializeJson(resp, out);
|
||||
_mqtt.publish("", out);
|
||||
_mqtt.publishAck(out);
|
||||
};
|
||||
|
||||
_bus.dispatch(envelope);
|
||||
|
||||
@@ -13,13 +13,17 @@ class CommandBus;
|
||||
//
|
||||
// Responsibilities:
|
||||
// - Delegates connection lifecycle to MQTTDriver
|
||||
// - Parses incoming MQTT JSON messages into CommandEnvelopes
|
||||
// - Injects a reply lambda that publishes the response to the data topic
|
||||
// - Subscribes to control/command, parses incoming JSON into CommandEnvelopes
|
||||
// (extracting the optional req_id for correlation — see CommandEnvelope.hpp)
|
||||
// - Injects a reply lambda that publishes the response to control/ack
|
||||
// - Dispatches to the CommandBus
|
||||
// - broadcast() publishes to the device data topic (telemetry, events)
|
||||
// - broadcast() publishes to control/ack (bus-wide unsolicited events only —
|
||||
// purpose-specific events like playback/alerts/reports go directly through
|
||||
// CommunicationRouter to their own topics, not through this path)
|
||||
//
|
||||
// The underlying MQTTDriver (and its timers, heartbeat, reconnect logic)
|
||||
// is unchanged — this transport just owns the bus glue.
|
||||
// See docs/reference/vesper_mqtt_topic_spec_v2.md for the full topic table.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class MQTTTransport : public ITransport {
|
||||
@@ -31,7 +35,7 @@ public:
|
||||
bool isHealthy() const override;
|
||||
String name() const override { return "MQTT"; }
|
||||
|
||||
// Publish a pre-serialised JSON string to the device data topic.
|
||||
// Publish a pre-serialised JSON string to control/ack.
|
||||
// Called by CommandBus::broadcast() for unsolicited events.
|
||||
void broadcast(const String& message) override;
|
||||
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
## Summary
|
||||
|
||||
`MQTTTransport` wraps `MQTTDriver` and connects it to the `CommandBus`. It subscribes to the device control topic, parses incoming JSON messages into `CommandEnvelope` objects, and dispatches them. Command replies are published back to the device data topic. Unsolicited events (telemetry, bell strikes) reach clients via `broadcast()`, which also publishes to the data topic. The underlying `MQTTDriver` manages the broker connection lifecycle, reconnect backoff, and heartbeat independently; `MQTTTransport` only owns the message-routing glue.
|
||||
`MQTTTransport` wraps `MQTTDriver` and connects it to the `CommandBus`. It subscribes to `control/command`, parses incoming JSON messages into `CommandEnvelope` objects (including the optional `req_id`), and dispatches them. Command replies are published back to `control/ack`. Bus-wide unsolicited broadcasts also go through `broadcast()` to `control/ack` — but purpose-specific events (playback transitions, alerts, reports, metrics) are published directly by `CommunicationRouter` to their own dedicated topics instead, so `control/ack` stays strictly request/response. The underlying `MQTTDriver` manages the broker connection lifecycle, reconnect backoff, LWT, and heartbeat independently; `MQTTTransport` only owns the message-routing glue.
|
||||
|
||||
See [docs/reference/vesper_mqtt_topic_spec_v2.md](../../../../docs/reference/vesper_mqtt_topic_spec_v2.md) for the full topic table.
|
||||
|
||||
---
|
||||
|
||||
@@ -15,7 +17,7 @@
|
||||
| `void loop()` | No-op. AsyncMqttClient is fully event-driven. |
|
||||
| `bool isHealthy() const` | Returns `MQTTDriver::isConnected()`. |
|
||||
| `String name() const` | Returns `"MQTT"`. |
|
||||
| `void broadcast(const String& msg)` | Publishes `msg` to the device data topic (`vesper/{uid}/data`). |
|
||||
| `void broadcast(const String& msg)` | Publishes `msg` to `control/ack` (bus-wide broadcasts only — see summary above). |
|
||||
| `void onNetworkConnected()` | Forwards to `MQTTDriver::onNetworkConnected()`, which schedules the broker connection after a 2-second stabilisation delay. |
|
||||
| `void onNetworkDisconnected()` | Forwards to `MQTTDriver::onNetworkDisconnected()`. |
|
||||
|
||||
@@ -29,19 +31,21 @@
|
||||
|
||||
## Message Format
|
||||
|
||||
Incoming control messages must be JSON with at least a `"cmd"` field:
|
||||
Incoming control messages (on `control/command`) must be JSON with at least a `"cmd"` field:
|
||||
|
||||
```json
|
||||
{ "v": 2, "cmd": "relay.set_durations", "contents": { "bells": { "0": 500 } } }
|
||||
{ "v": 2, "cmd": "relay.set_durations", "req_id": "abc123", "contents": { "bells": { "0": 500 } } }
|
||||
```
|
||||
|
||||
`"v"` defaults to `2` if omitted. `"v": 1` triggers legacy translation before dispatch.
|
||||
`"v"` defaults to `2` if omitted. `"v": 1` triggers legacy translation before dispatch. `"req_id"` is optional — see `CommandEnvelope.hpp` / `docs/reference/vesper_mqtt_topic_spec_v2.md` for the correlation contract.
|
||||
|
||||
Responses are published to the data topic:
|
||||
Responses are published to `control/ack`:
|
||||
```json
|
||||
{ "status": "SUCCESS", "type": "relay.set_durations", "message": "Bell durations updated and saved" }
|
||||
{ "status": "SUCCESS", "type": "relay.set_durations", "req_id": "abc123", "message": "Bell durations updated and saved" }
|
||||
```
|
||||
|
||||
`req_id` is only present in the reply if the request included one.
|
||||
|
||||
---
|
||||
|
||||
## Dependencies
|
||||
@@ -54,9 +58,9 @@ Responses are published to the data topic:
|
||||
|
||||
## Gotchas / Notes
|
||||
|
||||
- **Both reply and broadcast publish to the same data topic.** The broker does not distinguish between command replies and unsolicited events — clients must inspect `"type"` and `"status"` to differentiate.
|
||||
- **`control/ack` is strictly request/response plus bus-wide broadcasts — never purpose-specific events.** The broker does not distinguish a command reply from a `CommandBus::broadcast()` fan-out; clients must inspect `"type"` and `"status"` to differentiate. But playback transitions, alerts, reports, and metrics never appear here — those go to their own topics via `CommunicationRouter` (`publishPlayback()`, `publishAlert()`, `publishReport()`, `publishMetrics()`), bypassing this transport entirely.
|
||||
- **Broker connection is deferred.** `begin()` does not connect. The connection is triggered by `onNetworkConnected()`, which starts a 2-second non-blocking stabilisation timer in `MQTTDriver`.
|
||||
- **MQTT must be enabled in config.** `MQTTDriver::connect()` is a no-op if `mqttConfig.enabled` is false. Toggle with `mqtt.enable` / `mqtt.disable` commands.
|
||||
- **No per-message QoS.** Command replies and broadcasts are published at QoS 0. Heartbeats use QoS 1 with `retain = true`.
|
||||
- **MQTT must be enabled in config, and the `command` topic switch must be on.** `MQTTDriver::connect()` is a no-op if `mqttConfig.enabled` is false. Toggle the master switch with `mqtt.enable` / `mqtt.disable`. Independently, the `command` topic switch (via `mqtt.set_topics`) gates the `control/command` subscription and `control/ack` replies — turning it off while MQTT stays connected silently stops all command traffic.
|
||||
- **No per-message QoS.** Command replies and broadcasts are published at QoS 1 (matching the topic table). Heartbeats use QoS 1 with `retain = true`.
|
||||
- **JSON parse errors drop the message silently** (with a `LOG_WARNING`). The client receives no error response.
|
||||
- **Incoming commands are dropped under critical heap pressure.** `onMessage()` checks `MQTTDriver::hasHeapForPublish()` (free heap ≥ 20KB) before even constructing the `JsonDocument` used to deserialize the incoming payload. Below that threshold, the message is dropped with no reply and no error response — indistinguishable from a lost network message to the caller. This exists because a rapid burst of commands (each involving deserialize + dispatch + reply, all allocation-heavy, all running inline on AsyncTCP's own task) previously fragmented the heap enough to crash the device with an unrecoverable `abort()` — see `docs/features/feature-catalog.md` F-055. A full fix (queueing incoming commands to a dedicated task, so this work never runs on AsyncTCP's task at all) is a scoped future improvement, not yet implemented.
|
||||
|
||||
@@ -1434,7 +1434,7 @@ bool ConfigManager::loadGeneralConfig() {
|
||||
return false;
|
||||
}
|
||||
|
||||
StaticJsonDocument<256> doc;
|
||||
StaticJsonDocument<512> doc;
|
||||
DeserializationError error = deserializeJson(doc, file);
|
||||
file.close();
|
||||
|
||||
@@ -1462,6 +1462,17 @@ bool ConfigManager::loadGeneralConfig() {
|
||||
if (doc.containsKey("otaChannel")) {
|
||||
generalConfig.otaChannel = doc["otaChannel"].as<String>();
|
||||
}
|
||||
if (doc.containsKey("mqttTopics")) {
|
||||
JsonObjectConst t = doc["mqttTopics"];
|
||||
if (t.containsKey("command")) generalConfig.mqttTopics.command = t["command"].as<bool>();
|
||||
if (t.containsKey("heartbeat")) generalConfig.mqttTopics.heartbeat = t["heartbeat"].as<bool>();
|
||||
if (t.containsKey("playback")) generalConfig.mqttTopics.playback = t["playback"].as<bool>();
|
||||
if (t.containsKey("reports")) generalConfig.mqttTopics.reports = t["reports"].as<bool>();
|
||||
if (t.containsKey("alerts")) generalConfig.mqttTopics.alerts = t["alerts"].as<bool>();
|
||||
if (t.containsKey("info")) generalConfig.mqttTopics.info = t["info"].as<bool>();
|
||||
if (t.containsKey("logs")) generalConfig.mqttTopics.logs = t["logs"].as<bool>();
|
||||
if (t.containsKey("metrics")) generalConfig.mqttTopics.metrics = t["metrics"].as<bool>();
|
||||
}
|
||||
|
||||
LOG_DEBUG(TAG, "ConfigManager - General config loaded - serialLog: %d, mqttEnabled: %s, bellsEnabled: %s, otaChannel: %s",
|
||||
generalConfig.serialLogLevel,
|
||||
@@ -1477,7 +1488,7 @@ bool ConfigManager::saveGeneralConfig() {
|
||||
#endif
|
||||
if (!ensureSDCard()) return false;
|
||||
|
||||
StaticJsonDocument<256> doc;
|
||||
StaticJsonDocument<512> doc;
|
||||
doc["serialLogLevel"] = generalConfig.serialLogLevel;
|
||||
doc["sdLogLevel"] = generalConfig.sdLogLevel;
|
||||
doc["mqttLogLevel"] = generalConfig.mqttLogLevel;
|
||||
@@ -1485,7 +1496,17 @@ bool ConfigManager::saveGeneralConfig() {
|
||||
doc["bellsEnabled"] = generalConfig.bellsEnabled;
|
||||
doc["otaChannel"] = generalConfig.otaChannel;
|
||||
|
||||
char buffer[256];
|
||||
JsonObject topics = doc.createNestedObject("mqttTopics");
|
||||
topics["command"] = generalConfig.mqttTopics.command;
|
||||
topics["heartbeat"] = generalConfig.mqttTopics.heartbeat;
|
||||
topics["playback"] = generalConfig.mqttTopics.playback;
|
||||
topics["reports"] = generalConfig.mqttTopics.reports;
|
||||
topics["alerts"] = generalConfig.mqttTopics.alerts;
|
||||
topics["info"] = generalConfig.mqttTopics.info;
|
||||
topics["logs"] = generalConfig.mqttTopics.logs;
|
||||
topics["metrics"] = generalConfig.mqttTopics.metrics;
|
||||
|
||||
char buffer[512];
|
||||
size_t len = serializeJson(doc, buffer, sizeof(buffer));
|
||||
|
||||
if (len == 0 || len >= sizeof(buffer)) {
|
||||
@@ -1505,6 +1526,8 @@ bool ConfigManager::saveGeneralConfig() {
|
||||
// gc_mlog — mqttLogLevel (u8)
|
||||
// gc_mqtt — mqttEnabled (u8 bool)
|
||||
// gc_ota — otaChannel (str)
|
||||
// gc_mtop — mqttTopics, packed as one u8 bitfield (bit0=command, bit1=heartbeat,
|
||||
// bit2=playback, bit3=reports, bit4=alerts, bit5=info, bit6=logs, bit7=metrics)
|
||||
// Note: sdLogLevel omitted — no SD card on Agnus.
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
#if !HAS_SD_CARD
|
||||
@@ -1514,6 +1537,17 @@ bool ConfigManager::loadGeneralConfigFromNVS() {
|
||||
generalConfig.mqttEnabled = readNVSBool ("gc_mqtt", generalConfig.mqttEnabled);
|
||||
generalConfig.otaChannel = readNVSString("gc_ota", generalConfig.otaChannel);
|
||||
mqttConfig.enabled = generalConfig.mqttEnabled;
|
||||
|
||||
uint8_t topicBits = readNVSU8("gc_mtop", 0xFF); // default: all topics on
|
||||
generalConfig.mqttTopics.command = topicBits & (1 << 0);
|
||||
generalConfig.mqttTopics.heartbeat = topicBits & (1 << 1);
|
||||
generalConfig.mqttTopics.playback = topicBits & (1 << 2);
|
||||
generalConfig.mqttTopics.reports = topicBits & (1 << 3);
|
||||
generalConfig.mqttTopics.alerts = topicBits & (1 << 4);
|
||||
generalConfig.mqttTopics.info = topicBits & (1 << 5);
|
||||
generalConfig.mqttTopics.logs = topicBits & (1 << 6);
|
||||
generalConfig.mqttTopics.metrics = topicBits & (1 << 7);
|
||||
|
||||
LOG_DEBUG(TAG, "ConfigManager - General config loaded from NVS — serialLog: %d, mqttEnabled: %s, otaCh: %s",
|
||||
generalConfig.serialLogLevel, generalConfig.mqttEnabled ? "true" : "false",
|
||||
generalConfig.otaChannel.c_str());
|
||||
@@ -1526,6 +1560,18 @@ bool ConfigManager::saveGeneralConfigToNVS() {
|
||||
ok &= writeNVSU8 ("gc_mlog", generalConfig.mqttLogLevel);
|
||||
ok &= writeNVSBool ("gc_mqtt", generalConfig.mqttEnabled);
|
||||
ok &= writeNVSString("gc_ota", generalConfig.otaChannel);
|
||||
|
||||
uint8_t topicBits = 0;
|
||||
if (generalConfig.mqttTopics.command) topicBits |= (1 << 0);
|
||||
if (generalConfig.mqttTopics.heartbeat) topicBits |= (1 << 1);
|
||||
if (generalConfig.mqttTopics.playback) topicBits |= (1 << 2);
|
||||
if (generalConfig.mqttTopics.reports) topicBits |= (1 << 3);
|
||||
if (generalConfig.mqttTopics.alerts) topicBits |= (1 << 4);
|
||||
if (generalConfig.mqttTopics.info) topicBits |= (1 << 5);
|
||||
if (generalConfig.mqttTopics.logs) topicBits |= (1 << 6);
|
||||
if (generalConfig.mqttTopics.metrics) topicBits |= (1 << 7);
|
||||
ok &= writeNVSU8("gc_mtop", topicBits);
|
||||
|
||||
ok &= commitNVS();
|
||||
LOG_DEBUG(TAG, "ConfigManager - General config saved to NVS (%s)", ok ? "ok" : "errors");
|
||||
return ok;
|
||||
|
||||
@@ -89,6 +89,31 @@ public:
|
||||
bool enabled = true; // 🔘 MQTT enabled by default (can be toggled via command)
|
||||
};
|
||||
|
||||
/**
|
||||
* @struct MqttTopicConfig
|
||||
* @brief Per-topic ON/OFF switches for MQTT v2 publishing (loaded from SD/NVS)
|
||||
*
|
||||
* These only take effect while MqttConfig::enabled (the master switch) is
|
||||
* true — turning the master off stops everything regardless of these flags.
|
||||
* While the master is on, each flag independently gates whether its topic
|
||||
* publishes at all, so a device can "breathe" by disabling topics it
|
||||
* doesn't need (e.g. a fleet-only install with no phone app can turn off
|
||||
* control/command + control/ack entirely).
|
||||
*
|
||||
* `command` gates BOTH control/command (inbound subscribe) and control/ack
|
||||
* (outbound reply) together — see docs/reference/vesper_mqtt_topic_spec_v2.md.
|
||||
*/
|
||||
struct MqttTopicConfig {
|
||||
bool command = true; // control/command (subscribe) + control/ack (reply)
|
||||
bool heartbeat = true; // status/heartbeat
|
||||
bool playback = true; // status/playback
|
||||
bool reports = true; // control/reports (bell overload etc. — critical, unsolicited)
|
||||
bool alerts = true; // system/alerts
|
||||
bool info = true; // system/info
|
||||
bool logs = true; // system/logs (also gated by log.set_mqtt level — see Logging)
|
||||
bool metrics = true; // system/metrics
|
||||
};
|
||||
|
||||
/**
|
||||
* @struct HardwareConfig
|
||||
* @brief Hardware-specific settings (compiled per HWID)
|
||||
@@ -220,9 +245,10 @@ public:
|
||||
uint8_t serialLogLevel = 3; // INFO
|
||||
uint8_t sdLogLevel = 2; // WARNING
|
||||
uint8_t mqttLogLevel = 2; // WARNING
|
||||
bool mqttEnabled = true; // MQTT enabled by default
|
||||
bool mqttEnabled = true; // MQTT enabled by default (master switch)
|
||||
bool bellsEnabled = true; // Master bell mechanism ON/OFF (blocks playback + clock alerts)
|
||||
String otaChannel = "stable"; // OTA release channel: "stable" | "beta" | "development"
|
||||
MqttTopicConfig mqttTopics; // Per-topic MQTT publish switches (only apply while mqttEnabled)
|
||||
};
|
||||
|
||||
private:
|
||||
@@ -452,6 +478,10 @@ public:
|
||||
bool getBellsEnabled() const { return generalConfig.bellsEnabled; }
|
||||
String getOtaChannel() const { return generalConfig.otaChannel; }
|
||||
void setOtaChannel(const String& channel) { generalConfig.otaChannel = channel; }
|
||||
|
||||
// Per-topic MQTT switches (only take effect while getMqttEnabled() is true — see MqttTopicConfig)
|
||||
const MqttTopicConfig& getMqttTopicConfig() const { return generalConfig.mqttTopics; }
|
||||
void setMqttTopicConfig(const MqttTopicConfig& cfg) { generalConfig.mqttTopics = cfg; }
|
||||
bool loadGeneralConfig();
|
||||
bool saveGeneralConfig();
|
||||
#if !HAS_SD_CARD
|
||||
|
||||
@@ -158,8 +158,10 @@ ConfigManager has **no dependency on any other application subsystem**. It is th
|
||||
| `uint8_t getSerialLogLevel() const` | Current serial log level |
|
||||
| `uint8_t getSdLogLevel() const` | Current SD log level |
|
||||
| `uint8_t getMqttLogLevel() const` | Current MQTT log level |
|
||||
| `void setMqttEnabled(bool)` | Toggle MQTT (mirrors to both `GeneralConfig` and `MqttConfig`) |
|
||||
| `bool getMqttEnabled() const` | Whether MQTT is enabled |
|
||||
| `void setMqttEnabled(bool)` | Toggle MQTT master switch (mirrors to both `GeneralConfig` and `MqttConfig`) |
|
||||
| `bool getMqttEnabled() const` | Whether MQTT is enabled (master switch) |
|
||||
| `const MqttTopicConfig& getMqttTopicConfig() const` | Per-topic MQTT publish switches (`command`, `heartbeat`, `playback`, `reports`, `alerts`, `info`, `logs`, `metrics`) — only take effect while `getMqttEnabled()` is true. See `docs/reference/vesper_mqtt_topic_spec_v2.md`. |
|
||||
| `void setMqttTopicConfig(const MqttTopicConfig&)` | Replace all 8 topic switches at once (persist with `saveGeneralConfig()`) |
|
||||
|
||||
### Misc
|
||||
|
||||
|
||||
@@ -125,7 +125,7 @@ This happens immediately after `configManager.begin()`, before any other subsyst
|
||||
`CommunicationRouter::begin()` registers both callbacks and applies all three channel levels from `ConfigManager`:
|
||||
|
||||
```cpp
|
||||
Logging::setMqttPublishCallback(..., "vesper/<uid>/logs");
|
||||
Logging::setMqttPublishCallback(..., mqttClient.getLogsTopic()); // vesper/<uid>/system/logs
|
||||
Logging::setSdWriteCallback([fm](const String& line) {
|
||||
fm->appendLogLine("/logs", line, time(nullptr), SD_LOG_MAX_TOTAL_BYTES);
|
||||
});
|
||||
@@ -134,6 +134,8 @@ Logging::setMqttLevel(...);
|
||||
Logging::setSdLevel(...);
|
||||
```
|
||||
|
||||
The registered MQTT publish callback also checks `ConfigManager::getMqttTopicConfig().logs` before publishing — this is a second, independent gate alongside the per-level `mqttLevel` check `Logging` already does internally. An operator can silence the whole `system/logs` channel via `mqtt.set_topics { "logs": false }` without changing the configured level, then re-enable it later with the level untouched. See `docs/reference/vesper_mqtt_topic_spec_v2.md`.
|
||||
|
||||
It also sets the default per-subsystem MQTT suppressions to prevent feedback loops:
|
||||
|
||||
```cpp
|
||||
|
||||
@@ -556,9 +556,17 @@ void Player::setStatus(PlayerStatus newStatus) {
|
||||
uint64_t projectedRunTime = calculateProjectedRunTime();
|
||||
payload["projected_run_time"] = projectedRunTime;
|
||||
|
||||
// 🔥 Use broadcastStatus() to send to BOTH WebSocket AND MQTT clients!
|
||||
// WebSocket clients keep the existing envelope shape via broadcastStatus().
|
||||
_commManager->broadcastStatus(doc);
|
||||
|
||||
// MQTT clients get the dedicated status/playback topic — see
|
||||
// docs/reference/vesper_mqtt_topic_spec_v2.md. Same action/time_elapsed/
|
||||
// projected_run_time values, just published to a topic that carries
|
||||
// ONLY playback transitions instead of every broadcastStatus() event.
|
||||
_commManager->publishPlayback(payload["action"].as<String>(),
|
||||
payload["time_elapsed"].as<uint32_t>(),
|
||||
projectedRunTime);
|
||||
|
||||
LOG_DEBUG(TAG, "Status changed: %d → %d, broadcast sent with runTime: %llu",
|
||||
(int)oldStatus, (int)newStatus, projectedRunTime);
|
||||
}
|
||||
|
||||
@@ -200,7 +200,7 @@ A second, lower-frequency reporting mechanism alongside boot tracking above —
|
||||
|
||||
**Why temperature alone needs local sampling, and the other three don't:** temperature genuinely fluctuates between reports — a short thermal spike (e.g. a burst of relay activity) could occur and fully subside within the 5-minute gap between two reports, and a device reporting only its *current* value at report time would simply never see it. The other three fields are all monotonic or self-tracking (a reconnect counter only grows; `uxTaskGetStackHighWaterMark()` is itself already a running minimum since task start; OTA state changes only around an actual update) — reading them more often than once per report cannot reveal information a less-frequent read would miss.
|
||||
|
||||
**Publish cadence.** `CommunicationRouter::reportDiagnosticsIfDue()` checks a `millis()`-diff every main-loop iteration (same lightweight pattern as this class's own `RUNTIME_FLUSH_INTERVAL_MS` check — no new FreeRTOS timer) and publishes to `vesper/{uid}/status/info` every `DIAGNOSTICS_REPORT_INTERVAL_MS` (5 minutes) once `_telemetry` is set. See [CommunicationRouter's README](../Communication/CommunicationRouter/README.md) for the full payload shape.
|
||||
**Publish cadence.** `CommunicationRouter::reportDiagnosticsIfDue()` checks a `millis()`-diff every main-loop iteration (same lightweight pattern as this class's own `RUNTIME_FLUSH_INTERVAL_MS` check — no new FreeRTOS timer) and publishes to `vesper/{uid}/system/metrics` every `DIAGNOSTICS_REPORT_INTERVAL_MS` (5 minutes) once `_telemetry` is set. Also includes per-bell strike/load data (via `getStrikeCount()`/`getBellLoad()`/`isCoolingActive()`) since moving to the `system/metrics` topic — see [CommunicationRouter's README](../Communication/CommunicationRouter/README.md) for the full payload shape.
|
||||
|
||||
**On-demand vs. periodic — the accumulator reset distinction.** `telemetry.get_diagnostics` (`TelemetryHandler`) returns the identical shape but calls `writeTemperatureStats()` — a peek — instead of resetting the accumulator afterward. This means polling the command doesn't rob the next scheduled periodic report of samples it would otherwise have seen; only the periodic path's own `resetDiagnosticsStats()` call clears the window.
|
||||
|
||||
|
||||
+3
-1
@@ -17,8 +17,10 @@
|
||||
// v2.1.0 - Corrects builds that were incorrectly shipped as 2.0.11 before the firmware was properly rebuilt.
|
||||
// First 2.x release to be tested on the field
|
||||
// v2.1.1 - Adds LegacyResponseAdapter for v1 tablet compatibility
|
||||
// v2.2.0 - MQTT topic spec v2: control/command+ack+reports, status/playback,
|
||||
// system/alerts+info+logs+metrics, LWT, req_id correlation, per-topic switches
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
#define FW_VERSION "2.1.1"
|
||||
#define FW_VERSION "2.2.0"
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
// SemVer — lightweight 3-part version struct
|
||||
|
||||
Reference in New Issue
Block a user