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:
@@ -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");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user