From 6294044569a21f450035043134691faf2a8f2659 Mon Sep 17 00:00:00 2001 From: bonamin Date: Sat, 28 Feb 2026 22:04:51 +0200 Subject: [PATCH] =?UTF-8?q?feat(comms):=20Stage=201=20=E2=80=94=20CommandB?= =?UTF-8?q?us=20scaffolding=20(headers=20+=20skeleton)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the core data structures and interfaces for the comms refactor. No behaviour change — old CommandHandler is completely untouched. New files: CommandEnvelope.hpp — universal message wrapper (transport + command + reply lambda) CommandResult.hpp — standardised return type with ok/err/info factories ICommandHandler.hpp — interface every domain handler will implement ITransport.hpp — interface every transport layer will implement CommandBus.hpp/.cpp — registry + dispatcher (std::map, O(log n) lookup) Two minor corrections vs. plan: std::unordered_map → std::map (Arduino String has no std::hash) LOG_WARN → LOG_WARNING (codebase macro name) Co-Authored-By: Claude Sonnet 4.6 --- src/Communication/CommandBus/CommandBus.cpp | 72 +++++++++++++++++++ src/Communication/CommandBus/CommandBus.hpp | 59 +++++++++++++++ .../CommandBus/CommandEnvelope.hpp | 45 ++++++++++++ .../CommandBus/CommandResult.hpp | 72 +++++++++++++++++++ .../Handlers/ICommandHandler.hpp | 43 +++++++++++ src/Communication/Transport/ITransport.hpp | 44 ++++++++++++ 6 files changed, 335 insertions(+) create mode 100644 src/Communication/CommandBus/CommandBus.cpp create mode 100644 src/Communication/CommandBus/CommandBus.hpp create mode 100644 src/Communication/CommandBus/CommandEnvelope.hpp create mode 100644 src/Communication/CommandBus/CommandResult.hpp create mode 100644 src/Communication/Handlers/ICommandHandler.hpp create mode 100644 src/Communication/Transport/ITransport.hpp diff --git a/src/Communication/CommandBus/CommandBus.cpp b/src/Communication/CommandBus/CommandBus.cpp new file mode 100644 index 0000000..2c94199 --- /dev/null +++ b/src/Communication/CommandBus/CommandBus.cpp @@ -0,0 +1,72 @@ +#include "CommandBus.hpp" +#include "../../Logging/Logging.hpp" + +#define TAG "CommandBus" + +// --------------------------------------------------------------------------- +// Handler registration +// --------------------------------------------------------------------------- + +void CommandBus::registerHandler(std::unique_ptr handler) { + auto cmds = handler->commands(); + ICommandHandler* raw = handler.get(); + + for (const auto& cmd : cmds) { + if (_registry.count(cmd)) { + LOG_WARNING(TAG, "Duplicate command registration: '%s' — overwriting previous handler", cmd.c_str()); + } + _registry[cmd] = raw; + LOG_DEBUG(TAG, "Registered handler for command: %s", cmd.c_str()); + } + + _handlers.push_back(std::move(handler)); +} + +void CommandBus::addTransport(ITransport* transport) { + _transports.push_back(transport); + LOG_DEBUG(TAG, "Transport registered: %s", transport->name().c_str()); +} + +// --------------------------------------------------------------------------- +// Dispatch +// --------------------------------------------------------------------------- + +void CommandBus::dispatch(CommandEnvelope& envelope) { + auto it = _registry.find(envelope.command); + + if (it == _registry.end()) { + LOG_WARNING(TAG, "No handler for command: '%s'", envelope.command.c_str()); + envelope.reply(CommandResult::err("unknown", "Unknown command: " + envelope.command)); + return; + } + + LOG_DEBUG(TAG, "Dispatching: %s", envelope.command.c_str()); + CommandResult result = it->second->execute(envelope); + envelope.reply(result); +} + +// --------------------------------------------------------------------------- +// Broadcast +// --------------------------------------------------------------------------- + +void CommandBus::broadcast(const CommandResult& result) { + // Serialise once, fan out to all transports + JsonDocument doc; + doc["status"] = (result.status == CommandResult::Status::SUCCESS) ? "SUCCESS" + : (result.status == CommandResult::Status::INFO) ? "INFO" + : "ERROR"; + doc["type"] = result.type; + if (!result.payload.isEmpty()) { + doc["message"] = result.payload; + } + if (result.hasData) { + doc["data"] = result.data; + } + + String serialised; + serializeJson(doc, serialised); + + for (auto* transport : _transports) { + transport->broadcast(serialised); + } +} diff --git a/src/Communication/CommandBus/CommandBus.hpp b/src/Communication/CommandBus/CommandBus.hpp new file mode 100644 index 0000000..b71a9b3 --- /dev/null +++ b/src/Communication/CommandBus/CommandBus.hpp @@ -0,0 +1,59 @@ +#pragma once + +#include +#include +#include +#include +#include "CommandEnvelope.hpp" +#include "CommandResult.hpp" +#include "../Handlers/ICommandHandler.hpp" +#include "../Transport/ITransport.hpp" + +// --------------------------------------------------------------------------- +// CommandBus +// +// Registry + dispatcher. Replaces the 700-line if/else chain in CommandHandler. +// +// Usage: +// // Registration (once, in CommunicationRouter::registerHandlers()) +// _bus.registerHandler(std::make_unique(_player)); +// _bus.addTransport(&_mqtt); +// +// // Dispatch (called from each transport's message callback) +// _bus.dispatch(envelope); +// +// // Broadcast event to all transports +// _bus.broadcast(CommandResult::info("bell.strike", "Bell 2 fired")); +// --------------------------------------------------------------------------- + +class CommandBus { +public: + // Register a handler. All command names reported by handler->commands() + // are mapped to this handler instance. Duplicate command names log a + // warning and the later registration wins. + void registerHandler(std::unique_ptr handler); + + // Add a transport that receives broadcasts and participates in health checks. + void addTransport(ITransport* transport); + + // Dispatch an envelope to the registered handler (O(1) hash-map lookup). + // Calls envelope.reply() exactly once — with an error result if no handler + // is registered for envelope.command. + void dispatch(CommandEnvelope& envelope); + + // Broadcast a serialised result to all registered transports. + // Each transport's broadcast() implementation decides how to fan it out + // (e.g. WebSocket sends to all connected clients; HTTP is a no-op). + void broadcast(const CommandResult& result); + +private: + // Owned storage for handler instances + std::vector> _handlers; + + // Command name → handler pointer (non-owning, points into _handlers) + // std::map used instead of unordered_map — Arduino String has no std::hash specialisation + std::map _registry; + + // Non-owning references to transports (owned by CommunicationRouter) + std::vector _transports; +}; diff --git a/src/Communication/CommandBus/CommandEnvelope.hpp b/src/Communication/CommandBus/CommandEnvelope.hpp new file mode 100644 index 0000000..6370092 --- /dev/null +++ b/src/Communication/CommandBus/CommandEnvelope.hpp @@ -0,0 +1,45 @@ +#pragma once + +#include +#include +#include + +// Forward declare so CommandEnvelope.hpp doesn't pull in CommandResult.hpp circularly +struct CommandResult; + +// --------------------------------------------------------------------------- +// CommandEnvelope +// +// Universal message wrapper. Every transport (MQTT, WebSocket, HTTP, UART) +// parses its raw input and produces one of these before calling CommandBus::dispatch(). +// +// The reply lambda is injected by the transport so the bus and handlers never +// need to know which wire the response goes back on. +// --------------------------------------------------------------------------- + +struct CommandEnvelope { + enum class Transport { + MQTT, + WEBSOCKET, + HTTP, + UART + }; + + // Protocol version: 2 = v2 namespaced commands, 1 = legacy v1 (default 2) + uint8_t version = 2; + + Transport transport = Transport::WEBSOCKET; + + // WebSocket client ID — 0 for transports that don't have per-client identity + uint32_t clientId = 0; + + // Flat command name — e.g. "playback", "relay.set_durations", "system.restart" + String command; + + // The "contents" object from the raw JSON message + JsonDocument contents; + + // Reply callback injected by the transport layer. + // The bus calls this exactly once after dispatch completes. + std::function reply; +}; diff --git a/src/Communication/CommandBus/CommandResult.hpp b/src/Communication/CommandBus/CommandResult.hpp new file mode 100644 index 0000000..91fef56 --- /dev/null +++ b/src/Communication/CommandBus/CommandResult.hpp @@ -0,0 +1,72 @@ +#pragma once + +#include +#include + +// --------------------------------------------------------------------------- +// CommandResult +// +// Standardised return type from every ICommandHandler::execute() call. +// Replaces ad-hoc string building scattered across CommandHandler.cpp. +// +// Use the static factory methods — they read clearly at the call site: +// +// return CommandResult::ok("playback", "Command executed"); +// return CommandResult::ok("relay.get_config", doc); +// return CommandResult::err("relay.test_output", "Player must be stopped first"); +// --------------------------------------------------------------------------- + +struct CommandResult { + enum class Status { SUCCESS, ERROR, INFO }; + + Status status = Status::ERROR; + String type; // echoes the command name back to the caller + String payload; // human-readable message (empty is fine for data responses) + JsonDocument data; // structured data payload (optional) + bool hasData = false; + + // ----------------------------------------------------------------------- + // Factory methods + // ----------------------------------------------------------------------- + + // Simple success with an optional message + static CommandResult ok(const String& type, const String& msg = "") { + CommandResult r; + r.status = Status::SUCCESS; + r.type = type; + r.payload = msg; + return r; + } + + // Success with a structured JSON data payload + static CommandResult ok(const String& type, const JsonDocument& d) { + CommandResult r; + r.status = Status::SUCCESS; + r.type = type; + r.data.set(d); + r.hasData = true; + return r; + } + + // Error with a required message + static CommandResult err(const String& type, const String& msg) { + CommandResult r; + r.status = Status::ERROR; + r.type = type; + r.payload = msg; + return r; + } + + // Info / event (used for unsolicited broadcasts) + static CommandResult info(const String& type, const String& msg = "") { + CommandResult r; + r.status = Status::INFO; + r.type = type; + r.payload = msg; + return r; + } + + // Convenience + bool isOk() const { return status == Status::SUCCESS; } + bool isErr() const { return status == Status::ERROR; } +}; diff --git a/src/Communication/Handlers/ICommandHandler.hpp b/src/Communication/Handlers/ICommandHandler.hpp new file mode 100644 index 0000000..761f3e1 --- /dev/null +++ b/src/Communication/Handlers/ICommandHandler.hpp @@ -0,0 +1,43 @@ +#pragma once + +#include +#include +#include "../CommandBus/CommandEnvelope.hpp" +#include "../CommandBus/CommandResult.hpp" + +// --------------------------------------------------------------------------- +// ICommandHandler +// +// Interface every domain handler implements. +// +// - commands() declares which command names this handler owns. +// The CommandBus iterates this list at registration time and builds +// its lookup map automatically — no manual registration per command. +// +// - execute() receives a fully-parsed CommandEnvelope and returns a +// CommandResult. It must never call envelope.reply() directly — +// the bus handles that after execute() returns. +// +// Example: +// class PlaybackHandler : public ICommandHandler { +// public: +// explicit PlaybackHandler(Player& player); +// std::vector commands() const override { return { "playback" }; } +// CommandResult execute(const CommandEnvelope& envelope) override; +// private: +// Player& _player; +// }; +// --------------------------------------------------------------------------- + +class ICommandHandler { +public: + virtual ~ICommandHandler() = default; + + // Returns every command name this handler is responsible for. + // The bus registers all of them to the same handler instance. + virtual std::vector commands() const = 0; + + // Execute the command described by envelope and return the result. + // Must not throw. Must not call envelope.reply() — the bus owns that. + virtual CommandResult execute(const CommandEnvelope& envelope) = 0; +}; diff --git a/src/Communication/Transport/ITransport.hpp b/src/Communication/Transport/ITransport.hpp new file mode 100644 index 0000000..61e98ef --- /dev/null +++ b/src/Communication/Transport/ITransport.hpp @@ -0,0 +1,44 @@ +#pragma once + +#include +#include "../CommandBus/CommandResult.hpp" + +// --------------------------------------------------------------------------- +// ITransport +// +// Interface every transport layer implements. +// +// Transports are responsible for: +// 1. Receiving raw input from their protocol (MQTT, WebSocket, HTTP, UART) +// 2. Parsing it into a CommandEnvelope +// 3. Injecting a reply lambda that routes the response back correctly +// 4. Calling CommandBus::dispatch() +// +// The CommandBus never knows which transport originated a command. +// The transport never knows what a handler does with it. +// +// broadcast() is used by CommunicationRouter to push unsolicited events +// (telemetry, bell strikes, status changes) to all connected clients of +// this transport. +// --------------------------------------------------------------------------- + +class ITransport { +public: + virtual ~ITransport() = default; + + // Initialise the transport (called once from CommunicationRouter::begin()) + virtual void begin() = 0; + + // Service the transport's event loop (called from CommunicationRouter::loop()) + virtual void loop() = 0; + + // Health check used by HealthMonitor / CommunicationRouter::isHealthy() + virtual bool isHealthy() const = 0; + + // Human-readable name for logging (e.g. "MQTT", "WebSocket", "HTTP", "UART") + virtual String name() const = 0; + + // Push a pre-serialised JSON string to all clients of this transport. + // For connection-less transports (HTTP, UART) this is a no-op. + virtual void broadcast(const String& message) = 0; +};