#include "WebSocketTransport.hpp" #include "../../CommandBus/CommandBus.hpp" #include "../../CommandBus/CommandEnvelope.hpp" #include "../../CommandBus/CommandResult.hpp" #define TAG "WebSocketTransport" #include "../../../Logging/Logging.hpp" WebSocketTransport::WebSocketTransport(WebSocketDriver& 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"] | 1; 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); }