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:
2026-09-21 10:48:36 +03:00
co-authored by Claude Sonnet 5
parent 20576f12ff
commit 391ecb63fc
26 changed files with 1053 additions and 330 deletions
+7 -1
View File
@@ -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;
+18 -12
View File
@@ -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()`.
@@ -70,56 +70,79 @@ MQTTDriver::~MQTTDriver() {
void MQTTDriver::begin() {
LOG_INFO(TAG, "Initializing MQTT Async Client");
auto& mqttConfig = _configManager.getMqttConfig();
// Build topic strings (cache for performance)
String deviceUID = _configManager.getDeviceUID();
_controlTopic = "vesper/" + deviceUID + "/control";
_dataTopic = "vesper/" + deviceUID + "/data";
_alertsTopic = "vesper/" + deviceUID + "/status/alerts";
_infoTopic = "vesper/" + deviceUID + "/status/info";
_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());
auto& mqttConfig = _configManager.getMqttConfig();
// Build topic strings (cache for performance) — see docs/reference/vesper_mqtt_topic_spec_v2.md
String deviceUID = _configManager.getDeviceUID();
_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: 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) {
this->onMqttConnect(sessionPresent);
});
_mqttClient.onDisconnect([this](AsyncMqttClientDisconnectReason reason) {
this->onMqttDisconnect(reason);
});
_mqttClient.onSubscribe([this](uint16_t packetId, uint8_t qos) {
this->onMqttSubscribe(packetId, qos);
});
_mqttClient.onUnsubscribe([this](uint16_t packetId) {
this->onMqttUnsubscribe(packetId);
});
_mqttClient.onMessage([this](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
this->onMqttMessage(topic, payload, properties, len, index, total);
});
_mqttClient.onPublish([this](uint16_t packetId) {
this->onMqttPublish(packetId);
});
// Configure connection
_mqttClient.setServer(mqttConfig.host, mqttConfig.port);
_mqttClient.setCredentials(mqttConfig.user.c_str(), mqttConfig.password.c_str());
_mqttClient.setClientId(_clientId.c_str()); // Use member variable
_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>();
// Device ID from NVS
payload["device_id"] = _configManager.getDeviceUID();
// Firmware version
payload["firmware_version"] = _configManager.getFwVersion();
// Current date/time (from TimeKeeper if available, else uptime-based)
// For now, we'll use a simple timestamp format
doc["device_id"] = _configManager.getDeviceUID();
DeviceState ds = _stateProvider ? _stateProvider() : DeviceState{"booting", true};
doc["state"] = ds.state;
doc["ok"] = ds.ok;
doc["fw_version"] = _configManager.getFwVersion();
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;
char timestampStr[64];
snprintf(timestampStr, sizeof(timestampStr), "Uptime: %luh %lum %lus", hours, minutes, seconds);
payload["timestamp"] = timestampStr;
// IP address
payload["ip_address"] = _networking.getLocalIP();
// Gateway address
payload["gateway"] = _networking.getGateway();
// Uptime in milliseconds
payload["uptime_ms"] = uptimeMs;
doc["uptime_ms"] = uptimeMs;
// WiFi signal strength
payload["rssi"] = WiFi.RSSI();
char uptimeHuman[32];
snprintf(uptimeHuman, sizeof(uptimeHuman), "%luh %lum %lus", hours, minutes, seconds);
doc["uptime_human"] = uptimeHuman;
// 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& getAlertsTopic() const { return _alertsTopic; }
const String& getInfoTopic() const { return _infoTopic; }
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,14 +154,23 @@ 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
String _clientId; // Store client ID to keep it alive
// 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
+51 -18
View File
@@ -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.
+51 -5
View File
@@ -1434,15 +1434,15 @@ bool ConfigManager::loadGeneralConfig() {
return false;
}
StaticJsonDocument<256> doc;
StaticJsonDocument<512> doc;
DeserializationError error = deserializeJson(doc, file);
file.close();
if (error) {
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to parse general config from SD: %s", error.c_str());
return false;
}
if (doc.containsKey("serialLogLevel")) {
generalConfig.serialLogLevel = doc["serialLogLevel"].as<uint8_t>();
}
@@ -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;
+31 -1
View File
@@ -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
+4 -2
View File
@@ -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
+3 -1
View File
@@ -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
+12 -4
View File
@@ -555,11 +555,19 @@ void Player::setStatus(PlayerStatus newStatus) {
// Add projected run time for all states (0 if not applicable)
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);
LOG_DEBUG(TAG, "Status changed: %d → %d, broadcast sent with runTime: %llu",
// 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);
}
}
+1 -1
View File
@@ -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
View File
@@ -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