feat(comms): Stages 3–6 — transport layer, router simplification, legacy adapter, WebServerTransport

## Stage 3 — Transport Layer
- MQTTTransport: wraps MQTTAsyncClient, implements ITransport
- WebSocketTransport: wraps WebSocketServer + ClientManager; broadcastToMasters/Secondary
- HTTPTransport: first-class HTTP identity (no more 0xFFFFFFFF fake WS client); registers
  POST /api/command, GET /api/ping, GET /api/status; reply lambda captures AsyncWebServerRequest*
- UARTTransport: wraps UARTCommandHandler; UART whitelist enforced before dispatch

## Stage 4 — CommunicationRouter simplification
- Router now owns CommandBus + 4 transports; registerHandlers() wires all 10 domain handlers
- Old CommandHandler marked DEPRECATED on disk, no longer called
- HTTPRequestHandler no longer instantiated (replaced by HTTPTransport)
- ResponseBuilder::fromResult() factory method added
- main.cpp: all setXxxReference() calls moved before begin(); HealthMonitor + OutputManager wired

## Stage 5 — Legacy Adapter
- LegacyAdapter.hpp/cpp: 35 v1→v2 command mappings (simple 1:1, action-based, boolean splits)
- CommandBus::dispatch() applies translation when envelope.version == 1

## Stage 6 — WebServerTransport (4th transport, absorbs SettingsWebServer)
- WebServerTransport implements ITransport; registered in CommunicationRouter::begin()
- GET /settings: HTML settings page (PROGMEM template unchanged)
- POST /api/set-mode: routes network.set_config {permanent_ap_mode} through CommandBus
- POST /api/reboot: routes system.restart through CommandBus
- NetworkHandler::handleSetConfig: handles permanent_ap_mode field independently
- SettingsWebServer member removed from CommunicationRouter; src/SettingsWebServer/ is dead
  code, deletable in a follow-up PR once SettingsPage.h is moved

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-28 22:54:43 +02:00
co-authored by Claude Sonnet 4.6
parent f6107e2cfe
commit 682c604abe
21 changed files with 1505 additions and 365 deletions
@@ -0,0 +1,170 @@
#include "HTTPTransport.hpp"
#include "../../CommandBus/CommandBus.hpp"
#include "../../CommandBus/CommandEnvelope.hpp"
#include "../../CommandBus/CommandResult.hpp"
#include "../../../ConfigManager/ConfigManager.hpp"
#define TAG "HTTPTransport"
#include "../../../Logging/Logging.hpp"
HTTPTransport::HTTPTransport(AsyncWebServer& server, CommandBus& bus, ConfigManager& configManager)
: _server(server)
, _bus(bus)
, _configManager(configManager) {
}
void HTTPTransport::begin() {
// POST /api/command — execute any command
_server.on("/api/command", HTTP_POST,
// Called when body-less POST completes (shouldn't happen, but guard it)
[](AsyncWebServerRequest* request) {
request->send(400, "application/json",
R"({"status":"ERROR","type":"bad_request","message":"Body required"})");
},
nullptr, // no upload handler
[this](AsyncWebServerRequest* request, uint8_t* data, size_t len,
size_t index, size_t total) {
// Wait for full body before processing
if (index + len == total) {
handleCommandRequest(request, data, len);
}
}
);
// GET /api/ping — lightweight health check
_server.on("/api/ping", HTTP_GET,
[this](AsyncWebServerRequest* request) {
handlePingRequest(request);
}
);
// GET /api/status — convenience shortcut for system.status
_server.on("/api/status", HTTP_GET,
[this](AsyncWebServerRequest* request) {
handleStatusRequest(request);
}
);
// CORS headers for browser clients
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*");
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Headers", "Content-Type");
_initialised = true;
LOG_INFO(TAG, "HTTPTransport initialised — POST /api/command, GET /api/ping, GET /api/status");
}
void HTTPTransport::loop() {
// AsyncWebServer is fully event-driven; nothing to poll.
}
bool HTTPTransport::isHealthy() const {
return _initialised;
}
// ---------------------------------------------------------------------------
void HTTPTransport::handleCommandRequest(AsyncWebServerRequest* request,
uint8_t* data, size_t len) {
JsonDocument doc;
DeserializationError err = deserializeJson(doc, data, len);
if (err) {
LOG_WARNING(TAG, "JSON parse error: %s", err.c_str());
sendErrorJson(request, 400, "Invalid JSON");
return;
}
const char* cmd = doc["cmd"] | "";
if (cmd[0] == '\0') {
sendErrorJson(request, 400, "Missing 'cmd' field");
return;
}
LOG_DEBUG(TAG, "HTTP CMD: %s", cmd);
CommandEnvelope envelope;
envelope.transport = CommandEnvelope::Transport::HTTP;
envelope.clientId = 0;
envelope.command = cmd;
envelope.version = doc["v"] | 2;
if (doc.containsKey("contents")) {
envelope.contents.set(doc["contents"]);
}
// Capture request pointer. The reply lambda must call request->send() exactly once.
// AsyncWebServer keeps the request alive until we call send() or the connection closes.
envelope.reply = [this, request](const CommandResult& result) {
JsonDocument resp;
resp["status"] = result.isOk() ? "SUCCESS"
: (result.status == CommandResult::Status::INFO ? "INFO" : "ERROR");
resp["type"] = result.type;
if (!result.payload.isEmpty()) {
resp["message"] = result.payload;
}
if (result.hasData) {
resp["data"] = result.data;
}
String out;
serializeJson(resp, out);
sendJsonResponse(request, 200, out);
};
_bus.dispatch(envelope);
}
void HTTPTransport::handlePingRequest(AsyncWebServerRequest* request) {
LOG_DEBUG(TAG, "Ping request");
JsonDocument doc;
doc["status"] = "SUCCESS";
doc["type"] = "pong";
doc["uptime"] = millis();
String out;
serializeJson(doc, out);
sendJsonResponse(request, 200, out);
}
void HTTPTransport::handleStatusRequest(AsyncWebServerRequest* request) {
LOG_DEBUG(TAG, "Status shortcut — dispatching system.status");
CommandEnvelope envelope;
envelope.transport = CommandEnvelope::Transport::HTTP;
envelope.clientId = 0;
envelope.command = "system.status";
envelope.version = 2;
envelope.reply = [this, request](const CommandResult& result) {
JsonDocument resp;
resp["status"] = result.isOk() ? "SUCCESS" : "ERROR";
resp["type"] = result.type;
if (!result.payload.isEmpty()) {
resp["message"] = result.payload;
}
if (result.hasData) {
resp["data"] = result.data;
}
String out;
serializeJson(resp, out);
sendJsonResponse(request, 200, out);
};
_bus.dispatch(envelope);
}
// ---------------------------------------------------------------------------
void HTTPTransport::sendJsonResponse(AsyncWebServerRequest* request,
int code, const String& json) {
request->send(code, "application/json", json);
}
void HTTPTransport::sendErrorJson(AsyncWebServerRequest* request,
int code, const String& message) {
JsonDocument doc;
doc["status"] = "ERROR";
doc["type"] = "bad_request";
doc["message"] = message;
String out;
serializeJson(doc, out);
sendJsonResponse(request, code, out);
}
@@ -0,0 +1,54 @@
#pragma once
#include <Arduino.h>
#include <ESPAsyncWebServer.h>
#include "../ITransport.hpp"
class CommandBus;
class ConfigManager;
// ---------------------------------------------------------------------------
// HTTPTransport
//
// ITransport implementation for HTTP — replaces HTTPRequestHandler.
//
// HTTP is now a proper first-class transport with its own identity.
// No more 0xFFFFFFFF fake WebSocket client ID.
//
// Endpoints registered:
// POST /api/command — execute any command via CommandBus
// GET /api/ping — health check (no bus involvement)
// GET /api/status — shortcut: dispatches system.status to the bus
//
// broadcast() is a no-op (HTTP is stateless; no persistent connection to push to).
//
// The reply lambda captures the AsyncWebServerRequest* and sends the HTTP
// response directly — the bus and handlers never see the HTTP layer.
// ---------------------------------------------------------------------------
class HTTPTransport : public ITransport {
public:
HTTPTransport(AsyncWebServer& server, CommandBus& bus, ConfigManager& configManager);
void begin() override;
void loop() override; // no-op — AsyncWebServer is event-driven
bool isHealthy() const override;
String name() const override { return "HTTP"; }
// No persistent connections — broadcast is a no-op.
void broadcast(const String& message) override {}
private:
AsyncWebServer& _server;
CommandBus& _bus;
ConfigManager& _configManager;
bool _initialised = false;
// Endpoint handlers
void handleCommandRequest(AsyncWebServerRequest* request, uint8_t* data, size_t len);
void handlePingRequest(AsyncWebServerRequest* request);
void handleStatusRequest(AsyncWebServerRequest* request);
void sendJsonResponse(AsyncWebServerRequest* request, int code, const String& json);
void sendErrorJson(AsyncWebServerRequest* request, int code, const String& message);
};
@@ -0,0 +1,91 @@
#include "MQTTTransport.hpp"
#include "../../CommandBus/CommandBus.hpp"
#include "../../CommandBus/CommandEnvelope.hpp"
#include "../../CommandBus/CommandResult.hpp"
#define TAG "MQTTTransport"
#include "../../../Logging/Logging.hpp"
MQTTTransport::MQTTTransport(MQTTAsyncClient& mqttClient, CommandBus& bus)
: _mqtt(mqttClient)
, _bus(bus) {
}
void MQTTTransport::begin() {
// Wire up the message callback — any message arriving on the control topic
// is routed through here.
_mqtt.setCallback([this](const String& topic, const String& payload) {
onMessage(topic, payload);
});
_mqtt.begin();
LOG_INFO(TAG, "MQTTTransport initialised");
}
void MQTTTransport::loop() {
// AsyncMqttClient drives itself; nothing to poll here.
}
bool MQTTTransport::isHealthy() const {
return _mqtt.isConnected();
}
void MQTTTransport::broadcast(const String& message) {
_mqtt.publish("", message); // MQTTAsyncClient::publish() routes "" → _dataTopic
}
void MQTTTransport::onNetworkConnected() {
_mqtt.onNetworkConnected();
}
void MQTTTransport::onNetworkDisconnected() {
_mqtt.onNetworkDisconnected();
}
// ---------------------------------------------------------------------------
void MQTTTransport::onMessage(const String& topic, const String& payload) {
LOG_DEBUG(TAG, "RX [%s]: %s", topic.c_str(), payload.c_str());
JsonDocument doc;
DeserializationError err = deserializeJson(doc, payload);
if (err) {
LOG_WARNING(TAG, "JSON parse error: %s — dropping message", err.c_str());
return;
}
// Build the envelope
CommandEnvelope envelope;
envelope.transport = CommandEnvelope::Transport::MQTT;
envelope.clientId = 0;
envelope.command = doc["cmd"].as<String>();
envelope.version = doc["v"] | 2;
if (doc.containsKey("contents")) {
envelope.contents.set(doc["contents"]);
}
if (envelope.command.isEmpty()) {
LOG_WARNING(TAG, "MQTT message missing 'cmd' field — dropping");
return;
}
// Reply lambda — publishes the response back to the MQTT data topic
envelope.reply = [this](const CommandResult& result) {
JsonDocument resp;
resp["status"] = result.isOk() ? "SUCCESS"
: (result.status == CommandResult::Status::INFO ? "INFO" : "ERROR");
resp["type"] = result.type;
if (!result.payload.isEmpty()) {
resp["message"] = result.payload;
}
if (result.hasData) {
resp["data"] = result.data;
}
String out;
serializeJson(resp, out);
_mqtt.publish("", out);
};
_bus.dispatch(envelope);
}
@@ -0,0 +1,48 @@
#pragma once
#include <Arduino.h>
#include "../ITransport.hpp"
#include "../../MQTTAsyncClient/MQTTAsyncClient.hpp"
class CommandBus;
// ---------------------------------------------------------------------------
// MQTTTransport
//
// ITransport wrapper around the existing MQTTAsyncClient.
//
// Responsibilities:
// - Delegates connection lifecycle to MQTTAsyncClient
// - Parses incoming MQTT JSON messages into CommandEnvelopes
// - Injects a reply lambda that publishes the response to the data topic
// - Dispatches to the CommandBus
// - broadcast() publishes to the device data topic (telemetry, events)
//
// The underlying MQTTAsyncClient (and its timers, heartbeat, reconnect logic)
// is unchanged — this transport just owns the bus glue.
// ---------------------------------------------------------------------------
class MQTTTransport : public ITransport {
public:
MQTTTransport(MQTTAsyncClient& mqttClient, CommandBus& bus);
void begin() override;
void loop() override; // no-op — AsyncMqttClient is fully async
bool isHealthy() const override;
String name() const override { return "MQTT"; }
// Publish a pre-serialised JSON string to the device data topic.
// Called by CommandBus::broadcast() for unsolicited events.
void broadcast(const String& message) override;
// Called by CommunicationRouter when the network connects / disconnects
void onNetworkConnected();
void onNetworkDisconnected();
private:
MQTTAsyncClient& _mqtt;
CommandBus& _bus;
// Invoked by MQTTAsyncClient's message callback
void onMessage(const String& topic, const String& payload);
};
@@ -0,0 +1,105 @@
#include "UARTTransport.hpp"
#include "../../CommandBus/CommandBus.hpp"
#include "../../CommandBus/CommandEnvelope.hpp"
#include "../../CommandBus/CommandResult.hpp"
#define TAG "UARTTransport"
#include "../../../Logging/Logging.hpp"
// ---------------------------------------------------------------------------
// Whitelist
// ---------------------------------------------------------------------------
const char* const UARTTransport::WHITELIST[] = {
"ping",
"playback",
"clock.pause",
"clock.resume",
"system.get_time",
};
const size_t UARTTransport::WHITELIST_SIZE =
sizeof(UARTTransport::WHITELIST) / sizeof(UARTTransport::WHITELIST[0]);
// ---------------------------------------------------------------------------
UARTTransport::UARTTransport(UARTCommandHandler& uart, CommandBus& bus)
: _uart(uart)
, _bus(bus) {
}
void UARTTransport::begin() {
_uart.setCallback([this](JsonDocument& doc) {
onMessage(doc);
});
_uart.begin();
LOG_INFO(TAG, "UARTTransport initialised (whitelist: %u commands)", WHITELIST_SIZE);
}
void UARTTransport::loop() {
_uart.loop();
}
bool UARTTransport::isHealthy() const {
return _uart.isReady();
}
void UARTTransport::broadcast(const String& message) {
_uart.send(message);
}
// ---------------------------------------------------------------------------
bool UARTTransport::isWhitelisted(const String& command) const {
for (size_t i = 0; i < WHITELIST_SIZE; ++i) {
if (command == WHITELIST[i]) {
return true;
}
}
return false;
}
void UARTTransport::onMessage(JsonDocument& doc) {
const char* cmd = doc["cmd"] | "";
if (cmd[0] == '\0') {
LOG_WARNING(TAG, "UART message missing 'cmd' field — dropping");
return;
}
if (!isWhitelisted(cmd)) {
LOG_WARNING(TAG, "UART command '%s' not whitelisted — silently dropped", cmd);
return;
}
LOG_DEBUG(TAG, "UART CMD (whitelisted): %s", cmd);
CommandEnvelope envelope;
envelope.transport = CommandEnvelope::Transport::UART;
envelope.clientId = 0;
envelope.command = cmd;
envelope.version = doc["v"] | 2;
if (doc.containsKey("contents")) {
envelope.contents.set(doc["contents"]);
}
// Reply routes back over UART to the slave
envelope.reply = [this](const CommandResult& result) {
JsonDocument resp;
resp["status"] = result.isOk() ? "SUCCESS"
: (result.status == CommandResult::Status::INFO ? "INFO" : "ERROR");
resp["type"] = result.type;
if (!result.payload.isEmpty()) {
resp["message"] = result.payload;
}
if (result.hasData) {
resp["data"] = result.data;
}
String out;
serializeJson(resp, out);
_uart.send(out);
};
_bus.dispatch(envelope);
}
@@ -0,0 +1,56 @@
#pragma once
#include <Arduino.h>
#include "../ITransport.hpp"
#include "../../UARTCommandHandler/UARTCommandHandler.hpp"
class CommandBus;
// ---------------------------------------------------------------------------
// UARTTransport
//
// ITransport wrapper around the existing UARTCommandHandler.
//
// The UART port talks to a slave LCD/button board. Only a small whitelist of
// commands are accepted from this transport to prevent feedback loops and
// stop a compromised slave from issuing sensitive commands.
//
// Whitelist (v2 — see Communication-Refactor-Plan.md):
// ping — connection check
// playback — play/stop from physical buttons
// clock.pause — button-triggered pause
// clock.resume — button-triggered resume
// system.get_time — LCD requests current time (replaces old push model)
//
// All other commands are silently dropped before they reach the bus.
//
// broadcast() sends to the UART slave (unsolicited events / telemetry).
// For connection-less context this is optional; the slave may ignore messages
// it doesn't request.
// ---------------------------------------------------------------------------
class UARTTransport : public ITransport {
public:
UARTTransport(UARTCommandHandler& uart, CommandBus& bus);
void begin() override;
void loop() override; // polls UARTCommandHandler::loop()
bool isHealthy() const override;
String name() const override { return "UART"; }
// Send a serialised JSON string to the UART slave (newline appended by handler).
void broadcast(const String& message) override;
private:
UARTCommandHandler& _uart;
CommandBus& _bus;
// Commands the UART slave is allowed to issue
static const char* const WHITELIST[];
static const size_t WHITELIST_SIZE;
bool isWhitelisted(const String& command) const;
// Invoked by UARTCommandHandler's message callback
void onMessage(JsonDocument& doc);
};
@@ -0,0 +1,156 @@
#include "WebServerTransport.hpp"
#include "../../CommandBus/CommandBus.hpp"
#include "../../CommandBus/CommandEnvelope.hpp"
#include "../../CommandBus/CommandResult.hpp"
#include "../../../ConfigManager/ConfigManager.hpp"
#include "../../../Networking/Networking.hpp"
#define TAG "WebServerTransport"
#include "../../../Logging/Logging.hpp"
// HTML template lives alongside the old SettingsWebServer — include from there
// until the old directory is deleted.
#include "../../../SettingsWebServer/SettingsPage.h"
WebServerTransport::WebServerTransport(AsyncWebServer& server,
CommandBus& bus,
ConfigManager& configManager,
Networking& networking)
: _server(server)
, _bus(bus)
, _configManager(configManager)
, _networking(networking) {
}
void WebServerTransport::begin() {
// GET /settings — HTML settings page
_server.on("/settings", HTTP_GET,
[this](AsyncWebServerRequest* request) {
handleSettingsPage(request);
}
);
// POST /api/set-mode — AP / station toggle
_server.on("/api/set-mode", HTTP_POST,
[this](AsyncWebServerRequest* request) {
handleSetMode(request);
}
);
// POST /api/reboot — restart via CommandBus (system.restart)
_server.on("/api/reboot", HTTP_POST,
[this](AsyncWebServerRequest* request) {
handleReboot(request);
}
);
_initialised = true;
LOG_INFO(TAG, "WebServerTransport initialised");
LOG_INFO(TAG, " GET /settings - Settings page");
LOG_INFO(TAG, " POST /api/set-mode - AP/station toggle");
LOG_INFO(TAG, " POST /api/reboot - Device restart");
}
void WebServerTransport::loop() {
// AsyncWebServer is fully event-driven; nothing to poll.
}
bool WebServerTransport::isHealthy() const {
return _initialised;
}
// ---------------------------------------------------------------------------
// Endpoint handlers
// ---------------------------------------------------------------------------
void WebServerTransport::handleSettingsPage(AsyncWebServerRequest* request) {
LOG_DEBUG(TAG, "Settings page requested");
request->send(200, "text/html", generateSettingsHTML());
}
void WebServerTransport::handleSetMode(AsyncWebServerRequest* request) {
if (!request->hasParam("mode", true)) {
request->send(400, "text/plain", "Missing mode parameter");
return;
}
String mode = request->getParam("mode", true)->value();
LOG_INFO(TAG, "Mode change requested via web: %s", mode.c_str());
if (mode != "ap" && mode != "station") {
request->send(400, "text/plain", "Invalid mode. Use 'ap' or 'station'");
return;
}
bool apMode = (mode == "ap");
// Route through CommandBus: network.set_config with permanent_ap_mode field.
CommandEnvelope envelope;
envelope.transport = CommandEnvelope::Transport::HTTP;
envelope.clientId = 0;
envelope.command = "network.set_config";
envelope.version = 2;
envelope.contents["permanent_ap_mode"] = apMode;
// The reply lambda sends the HTTP response, then triggers a restart.
// We capture by value to be safe (request pointer stays valid until send()).
envelope.reply = [request, apMode](const CommandResult& result) {
if (result.isOk()) {
String msg = apMode
? "AP mode enabled. Device will reboot in 3 seconds."
: "Station mode enabled. Device will reboot in 3 seconds.";
request->send(200, "text/plain", msg);
delay(3000);
ESP.restart();
} else {
request->send(500, "text/plain",
String("Failed to set mode: ") + result.payload);
}
};
_bus.dispatch(envelope);
}
void WebServerTransport::handleReboot(AsyncWebServerRequest* request) {
LOG_INFO(TAG, "Reboot requested via web");
CommandEnvelope envelope;
envelope.transport = CommandEnvelope::Transport::HTTP;
envelope.clientId = 0;
envelope.command = "system.restart";
envelope.version = 2;
// system.restart sends its own response and then reboots.
// For the web client we send a simple text ack before the handler fires.
request->send(200, "text/plain", "Rebooting device in 2 seconds...");
envelope.reply = [](const CommandResult&) {
// Response already sent above; restart is handled by SystemHandler.
};
_bus.dispatch(envelope);
}
// ---------------------------------------------------------------------------
// HTML generation
// ---------------------------------------------------------------------------
String WebServerTransport::generateSettingsHTML() {
bool isAPMode = _networking.isInAPMode();
String currentIP = _networking.getLocalIP();
String deviceUID = _configManager.getDeviceUID();
String fwVersion = _configManager.getFwVersion();
String html = String(FPSTR(SETTINGS_PAGE_HTML));
html.replace("%MODE_BADGE_CLASS%", isAPMode ? "ap" : "station");
html.replace("%MODE_TEXT%", isAPMode ? "AP Mode" : "Station Mode");
html.replace("%CURRENT_IP%", currentIP);
html.replace("%DEVICE_UID%", deviceUID);
html.replace("%FW_VERSION%", fwVersion);
html.replace("%AP_ACTIVE_CLASS%", isAPMode ? "active" : "");
html.replace("%STATION_ACTIVE_CLASS%", !isAPMode ? "active" : "");
html.replace("%SELECTED_MODE%", isAPMode ? "ap" : "station");
return html;
}
@@ -0,0 +1,58 @@
#pragma once
#include <Arduino.h>
#include <ESPAsyncWebServer.h>
#include "../ITransport.hpp"
class CommandBus;
class ConfigManager;
class Networking;
// ---------------------------------------------------------------------------
// WebServerTransport
//
// ITransport implementation for the on-board settings web interface.
// Absorbs SettingsWebServer — Stage 6 of the comms refactor.
//
// Serves the network-mode settings page and routes form actions through
// the CommandBus, giving the settings UI the same command pipeline as
// every other transport.
//
// Endpoints:
// GET /settings — Settings page (HTML)
// POST /api/set-mode — Routes to network.set_ap_mode via CommandBus
// POST /api/reboot — Routes to system.restart via CommandBus
//
// broadcast() is a no-op (web server has no persistent client connections).
// ---------------------------------------------------------------------------
class WebServerTransport : public ITransport {
public:
WebServerTransport(AsyncWebServer& server,
CommandBus& bus,
ConfigManager& configManager,
Networking& networking);
void begin() override;
void loop() override; // no-op — AsyncWebServer is event-driven
bool isHealthy() const override;
String name() const override { return "WebServer"; }
// No persistent connections — broadcast is a no-op.
void broadcast(const String& message) override {}
private:
AsyncWebServer& _server;
CommandBus& _bus;
ConfigManager& _configManager;
Networking& _networking;
bool _initialised = false;
// Endpoint handlers
void handleSettingsPage(AsyncWebServerRequest* request);
void handleSetMode(AsyncWebServerRequest* request);
void handleReboot(AsyncWebServerRequest* request);
// Generates the settings HTML with runtime values substituted.
String generateSettingsHTML();
};
@@ -0,0 +1,96 @@
#include "WebSocketTransport.hpp"
#include "../../CommandBus/CommandBus.hpp"
#include "../../CommandBus/CommandEnvelope.hpp"
#include "../../CommandBus/CommandResult.hpp"
#define TAG "WebSocketTransport"
#include "../../../Logging/Logging.hpp"
WebSocketTransport::WebSocketTransport(WebSocketServer& wsServer, CommandBus& bus)
: _ws(wsServer)
, _bus(bus) {
}
void WebSocketTransport::begin() {
_ws.setCallback([this](uint32_t clientId, const JsonDocument& doc) {
onMessage(clientId, doc);
});
_ws.begin();
LOG_INFO(TAG, "WebSocketTransport initialised");
}
void WebSocketTransport::loop() {
// AsyncWebServer drives the event loop; nothing to poll here.
}
bool WebSocketTransport::isHealthy() const {
return true; // Always healthy — WebSocket server is always listening
}
void WebSocketTransport::broadcast(const String& message) {
_ws.broadcastToAll(message);
}
void WebSocketTransport::sendToClient(uint32_t clientId, const String& message) {
_ws.sendToClient(clientId, message);
}
void WebSocketTransport::broadcastToMasters(const String& message) {
_ws.broadcastToMaster(message);
}
void WebSocketTransport::broadcastToSecondary(const String& message) {
_ws.broadcastToSecondary(message);
}
bool WebSocketTransport::hasClients() const {
return _ws.hasClients();
}
size_t WebSocketTransport::getClientCount() const {
return _ws.getClientCount();
}
// ---------------------------------------------------------------------------
void WebSocketTransport::onMessage(uint32_t clientId, const JsonDocument& doc) {
const char* cmd = doc["cmd"] | "";
if (cmd[0] == '\0') {
LOG_WARNING(TAG, "Client #%u: WebSocket message missing 'cmd' field — dropping", clientId);
String err = R"({"status":"ERROR","type":"bad_request","message":"Missing 'cmd' field"})";
_ws.sendToClient(clientId, err);
return;
}
LOG_DEBUG(TAG, "Client #%u CMD: %s", clientId, cmd);
CommandEnvelope envelope;
envelope.transport = CommandEnvelope::Transport::WEBSOCKET;
envelope.clientId = clientId;
envelope.command = cmd;
envelope.version = doc["v"] | 2;
if (doc.containsKey("contents")) {
envelope.contents.set(doc["contents"]);
}
// Reply routes back to the originating WebSocket client only
envelope.reply = [this, clientId](const CommandResult& result) {
JsonDocument resp;
resp["status"] = result.isOk() ? "SUCCESS"
: (result.status == CommandResult::Status::INFO ? "INFO" : "ERROR");
resp["type"] = result.type;
if (!result.payload.isEmpty()) {
resp["message"] = result.payload;
}
if (result.hasData) {
resp["data"] = result.data;
}
String out;
serializeJson(resp, out);
_ws.sendToClient(clientId, out);
};
_bus.dispatch(envelope);
}
@@ -0,0 +1,53 @@
#pragma once
#include <Arduino.h>
#include "../ITransport.hpp"
#include "../../WebSocketServer/WebSocketServer.hpp"
class CommandBus;
// ---------------------------------------------------------------------------
// WebSocketTransport
//
// ITransport wrapper around the existing WebSocketServer.
//
// Responsibilities:
// - Delegates connection lifecycle and client management to WebSocketServer
// - Parses incoming WebSocket JSON messages into CommandEnvelopes
// - Injects a reply lambda that sends the response back to the originating client
// - Dispatches to the CommandBus
// - broadcast() sends to all connected WebSocket clients
//
// The identify command is still handled by SystemHandler (registered on the bus),
// not special-cased here — the transport is protocol-neutral.
// ---------------------------------------------------------------------------
class WebSocketTransport : public ITransport {
public:
WebSocketTransport(WebSocketServer& wsServer, CommandBus& bus);
void begin() override;
void loop() override; // no-op — AsyncWebServer is event-driven
bool isHealthy() const override;
String name() const override { return "WebSocket"; }
// Send to all connected WebSocket clients.
void broadcast(const String& message) override;
// Targeted send — used by the identify handler and other per-client responses.
void sendToClient(uint32_t clientId, const String& message);
// Access for CommunicationRouter broadcast helpers
void broadcastToMasters(const String& message);
void broadcastToSecondary(const String& message);
bool hasClients() const;
size_t getClientCount() const;
private:
WebSocketServer& _ws;
CommandBus& _bus;
// Invoked by WebSocketServer's message callback
void onMessage(uint32_t clientId, const JsonDocument& doc);
};