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:
@@ -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
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
Reference in New Issue
Block a user