Files
project-vesper/src/Communication/CommunicationRouter/CommunicationRouter.cpp
T
bonaminandClaude Sonnet 4.6 d4bd990e53 feat: semver versioning, FastAPI OTA integration, health alerts via MQTT
- Version.hpp: extract FW_VERSION from main.cpp into shared header
- OTAManager: replace uint16_t version with SemVer struct; update API URLs
  to new FastAPI backend (/api/firmware/{hw_type}/{channel}/latest);
  add postDownloadTelemetry() and postFlashTelemetry() for fleet visibility
- ConfigManager: remove fwVersion from DeviceConfig (always read from
  FW_VERSION constant); saveDeviceConfig/loadDeviceConfig are now no-ops;
  fallbackServerUrl replaced with fallbackServerUrls[2] array
- HealthMonitor: add AlertCallback + setAlertCallback() firing on state
  transitions (including CLEARED on recovery)
- CommunicationRouter: wire HealthMonitor alert callback on begin();
  add publishAlert() and publishInfo() for MQTT status topics
- MQTTDriver: add _alertsTopic + _infoTopic; add publishDirect() for
  absolute topic publishing; migrate heartbeat to JsonDocument
- ResponseBuilder, ClientManager, BellEngine: StaticJsonDocument /
  DynamicJsonDocument → JsonDocument; remove dead notifyBellsFired()
- docs: reorganise into architecture/, dev/, features/, reference/

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-14 22:15:27 +02:00

460 lines
21 KiB
C++

/*
* CommunicationRouter.cpp — Stage 4 refactor
*
* Wires CommandBus + transports + handlers.
* Old CommandHandler is no longer used.
*/
#include "CommunicationRouter.hpp"
#define TAG "CommRouter"
#include "../../ConfigManager/ConfigManager.hpp"
#include "../../OTAManager/OTAManager.hpp"
#include "../../Networking/Networking.hpp"
#include "../../Logging/Logging.hpp"
#include "../../Player/Player.hpp"
#include "../../FileManager/FileManager.hpp"
#include "../../TimeKeeper/TimeKeeper.hpp"
#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"
#include "../Handlers/ClockHandler/ClockHandler.hpp"
#include "../Handlers/SystemHandler/SystemHandler.hpp"
#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"
// ─────────────────────────────────────────────────────────────────────────────
// 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)
, _uartHandler()
// New architecture — transports reference the bus
, _bus()
, _mqttTransport(_mqttClient, _bus)
, _wsTransport(_wsServer, _bus)
, _httpTransport(server, _bus, configManager)
, _uartTransport(_uartHandler, _bus)
, _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();
String logTopic = "vesper/" + _configManager.getDeviceUID() + "/logs";
Logging::setMqttPublishCallback(
[this](const String& topic, const String& payload, int qos) {
_mqttClient.publish(topic, payload, qos, false);
},
logTopic
);
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());
Logging::setSubsystemMqttLevel("MQTTClient", Logging::NONE);
Logging::setSubsystemMqttLevel("CommRouter", Logging::WARNING);
Logging::setSubsystemMqttLevel("Logger", Logging::NONE);
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 ─────────────────────────────────────────────────────────────────
LOG_INFO(TAG, "Setting up UART transport...");
_uartTransport.begin();
LOG_INFO(TAG, "UART transport initialised");
// ── Register transports with the bus ─────────────────────────────────────
_bus.addTransport(&_mqttTransport);
_bus.addTransport(&_wsTransport);
_bus.addTransport(&_httpTransport);
_bus.addTransport(&_uartTransport);
_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() {
_uartTransport.loop();
}
// ─────────────────────────────────────────────────────────────────────────────
// 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) {
fm->appendLine("/logs/vesper.log", line);
});
LOG_INFO(TAG, "SD log channel registered -> /logs/vesper.log");
}
}
void CommunicationRouter::setTimeKeeperReference(Timekeeper* tk) {
_timeKeeper = tk;
}
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;
}
// ─────────────────────────────────────────────────────────────────────────────
// 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 (!_timeKeeper) LOG_ERROR(TAG, "registerHandlers: _timeKeeper is null — ClockHandler skipped");
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));
}
// Clock
if (_timeKeeper) {
_bus.registerHandler(std::make_unique<ClockHandler>(_configManager, *_timeKeeper));
}
// System — requires player, telemetry, healthMonitor, timeKeeper, clientManager
if (_player && _telemetry && _healthMonitor && _timeKeeper) {
_bus.registerHandler(std::make_unique<SystemHandler>(
_configManager, *_player, *_telemetry, *_healthMonitor,
*_timeKeeper, _clientManager));
}
// Firmware / OTA
if (_firmwareValidator && _player) {
_bus.registerHandler(std::make_unique<FirmwareHandler>(
*_firmwareValidator, _otaManager, *_player));
}
// Network — no optional dependencies
_bus.registerHandler(std::make_unique<NetworkHandler>(_configManager, _networking));
// File
if (_fileManager) {
_bus.registerHandler(std::make_unique<FileHandler>(*_fileManager));
}
// Logging — no optional dependencies
_bus.registerHandler(std::make_unique<LoggingHandler>(_configManager));
// Telemetry
if (_telemetry) {
_bus.registerHandler(std::make_unique<TelemetryHandler>(*_telemetry));
}
// MQTT control (enable / disable)
_bus.registerHandler(std::make_unique<MQTTHandler>(_configManager, _mqttClient));
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 (!_player || !_fileManager || !_timeKeeper) {
LOG_WARNING(TAG, "Unhealthy — missing subsystem references (player=%d fileManager=%d timeKeeper=%d)",
_player != nullptr, _fileManager != nullptr, _timeKeeper != nullptr);
return false;
}
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) {
publishToMqtt(message);
_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);
}
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
// ─────────────────────────────────────────────────────────────────────────────
void CommunicationRouter::sendBellOverloadNotification(
const std::vector<uint8_t>& bellNumbers,
const std::vector<uint16_t>& bellLoads,
const String& severity) {
JsonDocument doc;
doc["status"] = "INFO";
doc["type"] = "bell_overload";
JsonArray bellsArr = doc["payload"]["bells"].to<JsonArray>();
JsonArray loadsArr = doc["payload"]["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;
broadcastStatus(doc);
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;
JsonDocument doc;
doc["subsystem"] = subsystem;
doc["state"] = newState;
if (!message.isEmpty()) {
doc["msg"] = message;
}
String out;
serializeJson(doc, out);
_mqttClient.publishDirect(_mqttClient.getAlertsTopic(), out, 1, false);
LOG_DEBUG(TAG, "Alert published: %s → %s", subsystem.c_str(), newState.c_str());
}
void CommunicationRouter::publishInfo(const String& type, const JsonDocument& payload) {
if (!_mqttClient.isConnected()) return;
JsonDocument doc;
doc["type"] = type;
if (!payload.isNull()) {
doc["payload"] = payload;
}
String out;
serializeJson(doc, out);
_mqttClient.publishDirect(_mqttClient.getInfoTopic(), out, 0, false);
LOG_DEBUG(TAG, "Info published: %s", type.c_str());
}
// ─────────────────────────────────────────────────────────────────────────────
// 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();
}