status/playback is retained but was only published on a Player transition. After a power loss mid-melody the Player boots straight into STOPPED with no transition, so the broker kept serving the old "playing" forever. The MQTT on-connect callback now publishes Player::getPlaybackSnapshot() on every CONNECT (not just the first after boot) — "idle" after a reboot, the live state after a plain reconnect. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
713 lines
32 KiB
C++
713 lines
32 KiB
C++
/*
|
|
* CommunicationRouter.cpp — Stage 4 refactor
|
|
*
|
|
* Wires CommandBus + transports + handlers.
|
|
* Old CommandHandler is no longer used.
|
|
*/
|
|
|
|
#include "CommunicationRouter.hpp"
|
|
#include <time.h>
|
|
|
|
#define TAG "CommRouter"
|
|
|
|
// Total size budget for /logs on SD, across all rotated daily files.
|
|
// Oldest day is pruned first once this is exceeded.
|
|
static constexpr size_t SD_LOG_MAX_TOTAL_BYTES = 512 * 1024; // 512KB
|
|
|
|
#include "../../ConfigManager/ConfigManager.hpp"
|
|
#include "../../OTAManager/OTAManager.hpp"
|
|
#include "../../Networking/Networking.hpp"
|
|
#include "../../Logging/Logging.hpp"
|
|
#include "../../Player/Player.hpp"
|
|
#include "../../FileManager/FileManager.hpp"
|
|
#if HAS_RTC
|
|
#include "../../TimeKeeper/TimeKeeper.hpp"
|
|
#endif
|
|
#include "../../FirmwareValidator/FirmwareValidator.hpp"
|
|
#include "../../Telemetry/Telemetry.hpp"
|
|
#include "../../HealthMonitor/HealthMonitor.hpp"
|
|
#include "../../OutputManager/OutputManager.hpp"
|
|
|
|
// Domain handlers
|
|
#include "../Handlers/PlaybackHandler/PlaybackHandler.hpp"
|
|
#include "../Handlers/RelayHandler/RelayHandler.hpp"
|
|
#if HAS_RTC
|
|
#include "../Handlers/ClockHandler/ClockHandler.hpp"
|
|
#include "../Handlers/SystemHandler/SystemHandler.hpp"
|
|
#endif
|
|
#include "../Handlers/FirmwareHandler/FirmwareHandler.hpp"
|
|
#include "../Handlers/NetworkHandler/NetworkHandler.hpp"
|
|
#include "../Handlers/FileHandler/FileHandler.hpp"
|
|
#include "../Handlers/LoggingHandler/LoggingHandler.hpp"
|
|
#include "../Handlers/TelemetryHandler/TelemetryHandler.hpp"
|
|
#include "../Handlers/MQTTHandler/MQTTHandler.hpp"
|
|
#include "../Handlers/BellsHandler/BellsHandler.hpp"
|
|
#if HAS_RF
|
|
#include "../../RFRemote/RFRemoteHandler.hpp"
|
|
#endif
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// Constructor
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
CommunicationRouter::CommunicationRouter(ConfigManager& configManager,
|
|
OTAManager& otaManager,
|
|
Networking& networking,
|
|
AsyncWebServer& server,
|
|
AsyncWebSocket& webSocket,
|
|
AsyncUDP& udp)
|
|
: _configManager(configManager)
|
|
, _otaManager(otaManager)
|
|
, _networking(networking)
|
|
, _server(server)
|
|
, _webSocket(webSocket)
|
|
, _udp(udp)
|
|
// Underlying protocol objects
|
|
, _mqttClient(configManager, networking)
|
|
, _clientManager()
|
|
, _wsServer(webSocket, _clientManager)
|
|
#if HAS_UART
|
|
, _uartHandler()
|
|
#endif
|
|
// New architecture — transports reference the bus
|
|
, _bus()
|
|
, _mqttTransport(_mqttClient, _bus)
|
|
, _wsTransport(_wsServer, _bus)
|
|
, _httpTransport(server, _bus, configManager)
|
|
#if HAS_UART
|
|
, _uartTransport(_uartHandler, _bus)
|
|
#endif
|
|
, _webServerTransport(server, _bus, configManager, networking)
|
|
{}
|
|
|
|
CommunicationRouter::~CommunicationRouter() {}
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// begin()
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
void CommunicationRouter::begin() {
|
|
LOG_INFO(TAG, "Initializing Communication Router v5.0 (CommandBus)");
|
|
|
|
// ── WebSocket ─────────────────────────────────────────────────────────────
|
|
LOG_INFO(TAG, "Setting up WebSocket transport...");
|
|
_server.addHandler(&_webSocket);
|
|
_wsTransport.begin();
|
|
LOG_INFO(TAG, "WebSocket transport initialised (/ws)");
|
|
|
|
// ── MQTT ─────────────────────────────────────────────────────────────────
|
|
LOG_INFO(TAG, "Setting up MQTT transport...");
|
|
_mqttTransport.begin();
|
|
|
|
Logging::setMqttPublishCallback(
|
|
[this](const String& topic, const String& payload, int qos) {
|
|
// 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);
|
|
},
|
|
_mqttClient.getLogsTopic()
|
|
);
|
|
|
|
Logging::setSerialLevel((Logging::LogLevel)_configManager.getSerialLogLevel());
|
|
Logging::setMqttLevel((Logging::LogLevel)_configManager.getMqttLogLevel());
|
|
Logging::setSdLevel((Logging::LogLevel)_configManager.getSdLogLevel());
|
|
LOG_INFO(TAG, "Log levels applied — Serial:%d MQTT:%d SD:%d",
|
|
_configManager.getSerialLogLevel(),
|
|
_configManager.getMqttLogLevel(),
|
|
_configManager.getSdLogLevel());
|
|
|
|
// Suppress internal-plumbing subsystems on MQTT to prevent feedback loops
|
|
Logging::setSubsystemMqttLevel("MQTTClient", Logging::NONE);
|
|
Logging::setSubsystemMqttLevel("CommRouter", Logging::WARNING);
|
|
Logging::setSubsystemMqttLevel("Logger", Logging::NONE);
|
|
|
|
// Per-subsystem MQTT caps: keep remote logs signal-rich, not noisy
|
|
Logging::setSubsystemMqttLevel("BellEngine", Logging::WARNING); // per-note strike spam
|
|
Logging::setSubsystemMqttLevel("OutputManager", Logging::WARNING); // per-note extinguish spam
|
|
Logging::setSubsystemMqttLevel("HealthMonitor", Logging::WARNING); // periodic check spam
|
|
Logging::setSubsystemMqttLevel("ConfigManager", Logging::WARNING); // NVS read spam
|
|
Logging::setSubsystemMqttLevel("Player", Logging::INFO); // state transitions useful
|
|
Logging::setSubsystemMqttLevel("Telemetry", Logging::INFO); // load data useful
|
|
Logging::setSubsystemMqttLevel("OTAManager", Logging::INFO); // update events important
|
|
|
|
_mqttClient.setOnConnectCallback([this](bool /*sessionPresent*/) {
|
|
reportBootOnce();
|
|
|
|
// status/playback is retained: if the board lost power (or the link)
|
|
// mid-melody, the broker would keep serving "playing" indefinitely.
|
|
// Overwrite it with the Player's real state on EVERY connect — normally
|
|
// "idle" after a reboot, the live state after a plain reconnect.
|
|
if (_player) publishPlayback(_player->getPlaybackSnapshot());
|
|
});
|
|
|
|
// 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 ─────────────────────────────────────────────────────────────────
|
|
LOG_INFO(TAG, "Setting up HTTP transport...");
|
|
_httpTransport.begin();
|
|
LOG_INFO(TAG, "HTTP transport initialised");
|
|
|
|
// ── Settings Web Server (4th transport — Stage 6)
|
|
LOG_INFO(TAG, "Setting up WebServer transport...");
|
|
_webServerTransport.begin();
|
|
LOG_INFO(TAG, "WebServer transport initialised (/settings)");
|
|
|
|
// ── UART ─────────────────────────────────────────────────────────────────
|
|
#if HAS_UART
|
|
LOG_INFO(TAG, "Setting up UART transport...");
|
|
_uartTransport.begin();
|
|
LOG_INFO(TAG, "UART transport initialised");
|
|
#endif
|
|
|
|
// ── Register transports with the bus ─────────────────────────────────────
|
|
_bus.addTransport(&_mqttTransport);
|
|
_bus.addTransport(&_wsTransport);
|
|
_bus.addTransport(&_httpTransport);
|
|
#if HAS_UART
|
|
_bus.addTransport(&_uartTransport);
|
|
#endif
|
|
_bus.addTransport(&_webServerTransport);
|
|
|
|
// ── Register all domain handlers ─────────────────────────────────────────
|
|
registerHandlers();
|
|
|
|
// ── Wire HealthMonitor alert callback ────────────────────────────────────
|
|
if (_healthMonitor) {
|
|
_healthMonitor->setAlertCallback(
|
|
[this](const String& subsystem, const String& newState, const String& message) {
|
|
publishAlert(subsystem, newState, message);
|
|
}
|
|
);
|
|
LOG_INFO(TAG, "HealthMonitor alert callback registered");
|
|
}
|
|
|
|
LOG_INFO(TAG, "Communication Router ready — CommandBus active");
|
|
}
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// loop()
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
void CommunicationRouter::loop() {
|
|
#if HAS_UART
|
|
_uartTransport.loop();
|
|
#endif
|
|
reportDiagnosticsIfDue();
|
|
}
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// Late-bound reference setters
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
void CommunicationRouter::setPlayerReference(Player* player) {
|
|
_player = player;
|
|
}
|
|
|
|
void CommunicationRouter::setFileManagerReference(FileManager* fm) {
|
|
_fileManager = fm;
|
|
|
|
if (fm != nullptr) {
|
|
Logging::setSdWriteCallback([fm](const String& line) {
|
|
// Day-rotated: /logs/YYYY-MM-DD.log, capped at SD_LOG_MAX_TOTAL_BYTES
|
|
// total across the directory (oldest day pruned first).
|
|
fm->appendLogLine("/logs", line, time(nullptr), SD_LOG_MAX_TOTAL_BYTES);
|
|
});
|
|
LOG_INFO(TAG, "SD log channel registered -> /logs/YYYY-MM-DD.log (cap: %u bytes)", (unsigned)SD_LOG_MAX_TOTAL_BYTES);
|
|
}
|
|
}
|
|
|
|
#if HAS_RTC
|
|
void CommunicationRouter::setTimeKeeperReference(Timekeeper* tk) {
|
|
_timeKeeper = tk;
|
|
}
|
|
#endif
|
|
|
|
void CommunicationRouter::setFirmwareValidatorReference(FirmwareValidator* fv) {
|
|
_firmwareValidator = fv;
|
|
}
|
|
|
|
void CommunicationRouter::setTelemetryReference(Telemetry* telemetry) {
|
|
_telemetry = telemetry;
|
|
}
|
|
|
|
void CommunicationRouter::setHealthMonitorReference(HealthMonitor* hm) {
|
|
_healthMonitor = hm;
|
|
}
|
|
|
|
void CommunicationRouter::setOutputManagerReference(OutputManager* om) {
|
|
_outputManager = om;
|
|
}
|
|
|
|
#if HAS_RF
|
|
void CommunicationRouter::setRFRemoteReference(RFRemote* rf) {
|
|
_rfRemote = rf;
|
|
}
|
|
#endif
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// registerHandlers()
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
void CommunicationRouter::registerHandlers() {
|
|
// Log any missing optional dependencies so issues surface at boot, not later.
|
|
if (!_player) LOG_ERROR(TAG, "registerHandlers: _player is null — PlaybackHandler, RelayHandler, FirmwareHandler, SystemHandler skipped");
|
|
if (!_fileManager) LOG_ERROR(TAG, "registerHandlers: _fileManager is null — FileHandler skipped");
|
|
#if HAS_RTC
|
|
if (!_timeKeeper) LOG_ERROR(TAG, "registerHandlers: _timeKeeper is null — ClockHandler skipped");
|
|
#endif
|
|
if (!_firmwareValidator) LOG_ERROR(TAG, "registerHandlers: _firmwareValidator is null — FirmwareHandler skipped");
|
|
if (!_telemetry) LOG_ERROR(TAG, "registerHandlers: _telemetry is null — TelemetryHandler and SystemHandler skipped");
|
|
if (!_healthMonitor) LOG_WARNING(TAG, "registerHandlers: _healthMonitor is null — system.health unavailable");
|
|
if (!_outputManager) LOG_ERROR(TAG, "registerHandlers: _outputManager is null — RelayHandler skipped");
|
|
|
|
// Playback
|
|
if (_player) {
|
|
_bus.registerHandler(std::make_unique<PlaybackHandler>(*_player));
|
|
}
|
|
|
|
// Relay
|
|
if (_player && _outputManager) {
|
|
_bus.registerHandler(std::make_unique<RelayHandler>(_configManager, *_outputManager, *_player));
|
|
}
|
|
|
|
#if HAS_RTC
|
|
// Clock
|
|
if (_timeKeeper) {
|
|
_bus.registerHandler(std::make_unique<ClockHandler>(_configManager, *_timeKeeper, _outputManager));
|
|
}
|
|
#endif
|
|
|
|
// System — requires player, telemetry, healthMonitor, timeKeeper, clientManager
|
|
#if HAS_RTC
|
|
if (_player && _telemetry && _healthMonitor && _timeKeeper) {
|
|
_bus.registerHandler(std::make_unique<SystemHandler>(
|
|
_configManager, *_player, *_telemetry, *_healthMonitor,
|
|
*_timeKeeper, _clientManager));
|
|
}
|
|
#endif
|
|
|
|
// Firmware / OTA
|
|
if (_firmwareValidator && _player) {
|
|
_bus.registerHandler(std::make_unique<FirmwareHandler>(
|
|
*_firmwareValidator, _otaManager, *_player, _configManager));
|
|
}
|
|
|
|
// Network — no optional dependencies
|
|
_bus.registerHandler(std::make_unique<NetworkHandler>(_configManager, _networking));
|
|
|
|
// File
|
|
if (_fileManager) {
|
|
_bus.registerHandler(std::make_unique<FileHandler>(*_fileManager));
|
|
}
|
|
|
|
// Logging — FileManager optional; logs.list/logs.download degrade gracefully without it
|
|
_bus.registerHandler(std::make_unique<LoggingHandler>(_configManager, _fileManager));
|
|
|
|
// Telemetry
|
|
if (_telemetry) {
|
|
_bus.registerHandler(std::make_unique<TelemetryHandler>(*_telemetry, _otaManager, _networking));
|
|
}
|
|
|
|
// MQTT control (enable / disable / get_config)
|
|
_bus.registerHandler(std::make_unique<MQTTHandler>(_configManager, _mqttClient));
|
|
|
|
// Bell mechanism master switch
|
|
_bus.registerHandler(std::make_unique<BellsHandler>(_configManager));
|
|
|
|
#if HAS_RF
|
|
// RF remote control
|
|
if (_rfRemote) {
|
|
_bus.registerHandler(std::make_unique<RFRemoteHandler>(*_rfRemote));
|
|
}
|
|
#endif
|
|
|
|
LOG_INFO(TAG, "All domain handlers registered on CommandBus");
|
|
}
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// UDP Discovery
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
void CommunicationRouter::setupUdpDiscovery() {
|
|
uint16_t discoveryPort = _configManager.getNetworkConfig().discoveryPort;
|
|
if (_udp.listen(discoveryPort)) {
|
|
LOG_INFO(TAG, "UDP discovery listening on port %u", discoveryPort);
|
|
|
|
_udp.onPacket([this](AsyncUDPPacket packet) {
|
|
String msg = String((const char*)packet.data(), packet.length());
|
|
LOG_DEBUG(TAG, "UDP from %s:%u -> %s",
|
|
packet.remoteIP().toString().c_str(),
|
|
packet.remotePort(),
|
|
msg.c_str());
|
|
|
|
bool shouldReply = false;
|
|
if (msg.indexOf("discover") >= 0) {
|
|
shouldReply = true;
|
|
} else {
|
|
JsonDocument req;
|
|
if (!deserializeJson(req, msg)) {
|
|
shouldReply = (req["op"] == "discover");
|
|
}
|
|
}
|
|
|
|
if (!shouldReply) return;
|
|
|
|
JsonDocument doc;
|
|
doc["op"] = "discover_reply";
|
|
doc["svc"] = "vesper";
|
|
doc["ver"] = 1;
|
|
doc["name"] = "Proj. Vesper v2.0";
|
|
doc["id"] = _configManager.getDeviceUID();
|
|
doc["ip"] = _networking.getLocalIP();
|
|
doc["port"] = 80;
|
|
doc["fw"] = "2.0";
|
|
doc["clients"] = _clientManager.getClientCount();
|
|
|
|
char wsUrl[64];
|
|
snprintf(wsUrl, sizeof(wsUrl), "ws://%s:80/ws", _networking.getLocalIP().c_str());
|
|
doc["ws"] = wsUrl;
|
|
|
|
String out;
|
|
serializeJson(doc, out);
|
|
_udp.writeTo((const uint8_t*)out.c_str(), out.length(),
|
|
packet.remoteIP(), packet.remotePort());
|
|
});
|
|
} else {
|
|
LOG_ERROR(TAG, "Failed to start UDP discovery");
|
|
}
|
|
}
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// Status
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
bool CommunicationRouter::isMqttConnected() const {
|
|
return _mqttClient.isConnected();
|
|
}
|
|
|
|
bool CommunicationRouter::hasActiveWebSocketClients() const {
|
|
return _wsTransport.hasClients();
|
|
}
|
|
|
|
size_t CommunicationRouter::getWebSocketClientCount() const {
|
|
return _wsTransport.getClientCount();
|
|
}
|
|
|
|
bool CommunicationRouter::isHealthy() const {
|
|
#if HAS_RTC
|
|
if (!_player || !_timeKeeper) {
|
|
LOG_WARNING(TAG, "Unhealthy — missing subsystem references (player=%d timeKeeper=%d)",
|
|
_player != nullptr, _timeKeeper != nullptr);
|
|
return false;
|
|
}
|
|
#else
|
|
if (!_player) {
|
|
LOG_WARNING(TAG, "Unhealthy — missing subsystem references (player=%d)",
|
|
_player != nullptr);
|
|
return false;
|
|
}
|
|
#endif
|
|
if (!_networking.isConnected()) {
|
|
LOG_WARNING(TAG, "Unhealthy — no network connection");
|
|
return false;
|
|
}
|
|
if (!isMqttConnected() && !hasActiveWebSocketClients()) {
|
|
LOG_WARNING(TAG, "Unhealthy — no active connections (MQTT=%d WS=%d)",
|
|
isMqttConnected(), hasActiveWebSocketClients());
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// Broadcast helpers
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
void CommunicationRouter::broadcastStatus(const String& 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);
|
|
}
|
|
|
|
void CommunicationRouter::broadcastStatus(const JsonDocument& statusJson) {
|
|
String msg;
|
|
serializeJson(statusJson, msg);
|
|
broadcastStatus(msg);
|
|
}
|
|
|
|
void CommunicationRouter::broadcastToMasterClients(const String& message) {
|
|
_wsTransport.broadcastToMasters(message);
|
|
}
|
|
|
|
void CommunicationRouter::broadcastToSecondaryClients(const String& message) {
|
|
_wsTransport.broadcastToSecondary(message);
|
|
}
|
|
|
|
void CommunicationRouter::broadcastToAllWebSocketClients(const String& message) {
|
|
_wsTransport.broadcast(message);
|
|
}
|
|
|
|
void CommunicationRouter::broadcastToAllWebSocketClients(const JsonDocument& message) {
|
|
String msg;
|
|
serializeJson(message, msg);
|
|
_wsTransport.broadcast(msg);
|
|
}
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// Bell overload notification
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
void CommunicationRouter::sendBellOverloadNotification(
|
|
const std::vector<uint8_t>& bellNumbers,
|
|
const std::vector<uint16_t>& bellLoads,
|
|
const String& severity) {
|
|
|
|
// WS clients keep the existing shape (unchanged transport, untouched per
|
|
// the refactor's scope).
|
|
JsonDocument wsDoc;
|
|
wsDoc["status"] = "INFO";
|
|
wsDoc["type"] = "bell_overload";
|
|
|
|
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]);
|
|
}
|
|
reportPayload["severity"] = severity;
|
|
publishReport("bell_overload", reportPayload);
|
|
|
|
LOG_WARNING(TAG, "Bell overload notification sent: %d bells, severity: %s",
|
|
bellNumbers.size(), severity.c_str());
|
|
}
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// Alert / Info publishing
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
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;
|
|
doc["state"] = newState;
|
|
if (!message.isEmpty()) {
|
|
doc["msg"] = message;
|
|
}
|
|
|
|
String out;
|
|
serializeJson(doc, out);
|
|
// 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());
|
|
}
|
|
|
|
void CommunicationRouter::reportBootOnce() {
|
|
if (_bootReasonReported || !_telemetry) return;
|
|
_bootReasonReported = true;
|
|
|
|
String reason = _telemetry->getResetReasonString();
|
|
bool isFault = _telemetry->isFaultReset();
|
|
|
|
// Existing fault alert — unchanged trigger condition and topic, so consoles
|
|
// already handling this WARNING keep working as-is.
|
|
if (isFault) {
|
|
publishAlert("System", "WARNING", "Device reset due to fault: " + reason);
|
|
LOG_WARNING(TAG, "Fault reset reported: %s", reason.c_str());
|
|
}
|
|
|
|
// Consolidated boot report — always published, fault or not. Single place
|
|
// a console needs to watch for "device rebooted" plus everything useful
|
|
// about why: lifetime boot count, reset reason, and (if the last reset was
|
|
// a crash with a coredump available) the faulting task/PC/exception detail.
|
|
JsonDocument payload;
|
|
payload["boot_count"] = _telemetry->getLifetimeBootCount();
|
|
payload["reset_reason"] = reason;
|
|
payload["is_fault"] = isFault;
|
|
payload["free_heap"] = (uint32_t)ESP.getFreeHeap();
|
|
|
|
const CrashReport& crash = _telemetry->getCrashReport();
|
|
if (crash.available) {
|
|
JsonObject crashObj = payload["crash"].to<JsonObject>();
|
|
crashObj["task"] = crash.taskName;
|
|
crashObj["pc"] = crash.pc;
|
|
crashObj["exc_cause"] = crash.excCause;
|
|
crashObj["exc_vaddr"] = crash.excVaddr;
|
|
}
|
|
|
|
publishInfo("boot_report", payload);
|
|
LOG_INFO(TAG, "Boot report published: count=%lu reason=%s%s",
|
|
_telemetry->getLifetimeBootCount(), reason.c_str(),
|
|
crash.available ? " (crash detail included)" : "");
|
|
}
|
|
|
|
// Diagnostics report — batched every DIAGNOSTICS_REPORT_INTERVAL_MS (5 min).
|
|
// Deliberately separate from the 30s heartbeat: temperature/stack/WiFi-
|
|
// reconnect/OTA state don't need 30s freshness, and the heartbeat already
|
|
// fires forever, per device, at fleet scale — adding heavier/rarer-need
|
|
// fields there is a permanent cost paid whether or not anyone's watching.
|
|
// Temperature is locally sampled every 15s by Telemetry::sampleDiagnosticsIfDue()
|
|
// (called from TelemetryTask's own loop) and reduced to min/max/avg here, so a
|
|
// short-lived spike between two 5-minute reports still gets caught — the other
|
|
// three fields (stack high-water, WiFi reconnects, OTA state) are monotonic/
|
|
// cumulative counters where a single read at report time is exactly as
|
|
// informative as continuous sampling would be. See docs/features/feature-catalog.md.
|
|
void CommunicationRouter::reportDiagnosticsIfDue() {
|
|
if (!_telemetry) return;
|
|
uint32_t now = millis();
|
|
if (now - _lastDiagnosticsReportMs < DIAGNOSTICS_REPORT_INTERVAL_MS) return;
|
|
_lastDiagnosticsReportMs = now;
|
|
|
|
JsonDocument payload;
|
|
|
|
// CPU temperature — min/max/avg since the last report. Captured before
|
|
// reset() so this report gets the full accumulated window.
|
|
uint16_t tempSampleCount = _telemetry->getTemperatureStats().count;
|
|
_telemetry->writeTemperatureStats(payload);
|
|
_telemetry->resetDiagnosticsStats();
|
|
|
|
// WiFi reconnects — lifetime this boot, plus last disconnect reason/time.
|
|
JsonObject wifiObj = payload["wifi_reconnects"].to<JsonObject>();
|
|
wifiObj["lifetime_count"] = _networking.getReconnectCount();
|
|
wifiObj["last_reason"] = _networking.getLastDisconnectReason();
|
|
wifiObj["last_at_uptime_ms"] = _networking.getLastDisconnectUptimeMs();
|
|
|
|
// OTA — current/available version, update-available flag, last check, last error.
|
|
JsonObject otaObj = payload["ota"].to<JsonObject>();
|
|
otaObj["current_version"] = _otaManager.getCurrentVersion().toString();
|
|
otaObj["update_available"] = _otaManager.isUpdateAvailable();
|
|
if (_otaManager.isUpdateAvailable()) {
|
|
otaObj["available_version"] = _otaManager.getAvailableVersion().toString();
|
|
}
|
|
otaObj["last_check_uptime_ms"] = _otaManager.getLastCheckUptimeMs();
|
|
otaObj["last_error"] = OTAManager::errorCodeToString(_otaManager.getLastError());
|
|
|
|
// Stack high-water mark — bytes free, per registered task (TelemetryTask,
|
|
// HealthMonitor, etc. — see Telemetry::registerTaskForStackMonitoring()).
|
|
JsonObject stackObj = payload["stack_high_water"].to<JsonObject>();
|
|
Telemetry::writeStackHighWaterMarks(stackObj);
|
|
|
|
// 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;
|
|
if (!payload.isNull()) {
|
|
doc["payload"] = payload;
|
|
}
|
|
|
|
String out;
|
|
serializeJson(doc, out);
|
|
_mqttClient.publishDirect(_mqttClient.getInfoTopic(), out, 1, true);
|
|
LOG_DEBUG(TAG, "Info published: %s", type.c_str());
|
|
}
|
|
|
|
void CommunicationRouter::publishPlayback(const PlaybackSnapshot& snapshot) {
|
|
if (!_mqttClient.isConnected()) return;
|
|
if (!_configManager.getMqttTopicConfig().playback) return;
|
|
if (!_mqttClient.hasHeapForPublish()) return; // skip building the JsonDocument too, not just the publish
|
|
|
|
JsonDocument doc;
|
|
snapshot.writeTo(doc.to<JsonObject>());
|
|
|
|
String out;
|
|
serializeJson(doc, out);
|
|
_mqttClient.publishDirect(_mqttClient.getPlaybackTopic(), out, 1, true);
|
|
LOG_DEBUG(TAG, "Playback published: %s", snapshot.action);
|
|
}
|
|
|
|
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
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
void CommunicationRouter::onNetworkConnected() {
|
|
LOG_DEBUG(TAG, "Network connected — notifying MQTT transport");
|
|
_mqttTransport.onNetworkConnected();
|
|
}
|
|
|
|
void CommunicationRouter::onNetworkDisconnected() {
|
|
LOG_DEBUG(TAG, "Network disconnected — notifying MQTT transport");
|
|
_mqttTransport.onNetworkDisconnected();
|
|
}
|