feat(comms): Stage 1 — CommandBus scaffolding (headers + skeleton)

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 <noreply@anthropic.com>
This commit is contained in:
2026-02-28 22:04:51 +02:00
co-authored by Claude Sonnet 4.6
parent 30d660268f
commit 6294044569
6 changed files with 335 additions and 0 deletions
@@ -0,0 +1,72 @@
#include "CommandBus.hpp"
#include "../../Logging/Logging.hpp"
#define TAG "CommandBus"
// ---------------------------------------------------------------------------
// Handler registration
// ---------------------------------------------------------------------------
void CommandBus::registerHandler(std::unique_ptr<ICommandHandler> 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);
}
}
@@ -0,0 +1,59 @@
#pragma once
#include <Arduino.h>
#include <vector>
#include <memory>
#include <map>
#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<PlaybackHandler>(_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<ICommandHandler> 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<std::unique_ptr<ICommandHandler>> _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<String, ICommandHandler*> _registry;
// Non-owning references to transports (owned by CommunicationRouter)
std::vector<ITransport*> _transports;
};
@@ -0,0 +1,45 @@
#pragma once
#include <Arduino.h>
#include <ArduinoJson.h>
#include <functional>
// 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<void(const CommandResult&)> reply;
};
@@ -0,0 +1,72 @@
#pragma once
#include <Arduino.h>
#include <ArduinoJson.h>
// ---------------------------------------------------------------------------
// 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; }
};
@@ -0,0 +1,43 @@
#pragma once
#include <Arduino.h>
#include <vector>
#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<String> 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<String> 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;
};
@@ -0,0 +1,44 @@
#pragma once
#include <Arduino.h>
#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;
};