# CommandBus ## Summary The CommandBus is the dispatch core of the communication layer. It owns a registry of `ICommandHandler` instances keyed by command name, and a list of `ITransport` instances that can receive broadcasts. When a transport receives a message, it parses it into a `CommandEnvelope` and calls `CommandBus::dispatch()`, which does an O(1) map lookup to find the right handler, calls `execute()`, then calls the envelope's reply lambda exactly once with the result. Unsolicited events (bell strikes, telemetry, status changes) are pushed out to all transports via `broadcast()`. The bus has no knowledge of which protocol a message arrived on — that concern lives entirely in the transport's reply lambda. This directory also contains four supporting types used everywhere in the communication layer: `CommandEnvelope`, `CommandResult`, `ICommandHandler`, and `LegacyAdapter`. --- ## Public API — CommandBus | Method | Description | |--------|-------------| | `void registerHandler(std::unique_ptr handler)` | Takes ownership of a handler; maps every command name returned by `handler->commands()` to this instance. Duplicate registrations log a warning and the later handler wins. | | `void addTransport(ITransport* transport)` | Registers a non-owning transport pointer for broadcast fan-out. | | `void dispatch(CommandEnvelope& envelope)` | Looks up the handler for `envelope.command`, calls `execute()`, and fires `envelope.reply()` with the result. If no handler is found, replies with an error. Automatically translates v1 envelopes before lookup. | | `void broadcast(const CommandResult& result)` | Serialises `result` to JSON once, then calls `broadcast()` on every registered transport. | --- ## Supporting Types ### CommandEnvelope Universal message wrapper produced by each transport before calling `dispatch()`. The transport injects the reply lambda so the bus and handlers never need to know which wire the response goes back on. | Field | Type | Description | |-------|------|-------------| | `version` | `uint8_t` | Protocol version: `2` = v2 (default), `1` = legacy | | `transport` | `Transport` enum | `MQTT`, `WEBSOCKET`, `HTTP`, or `UART` | | `clientId` | `uint32_t` | WebSocket client ID; `0` for transports without per-client identity | | `command` | `String` | Flat command name, e.g. `"relay.set_durations"`, `"ping"` | | `contents` | `JsonDocument` | The `"contents"` object from the raw JSON message | | `reply` | `std::function` | Injected by the transport; called exactly once by the bus after dispatch | **Wire format (v2):** ```json { "v": 2, "cmd": "namespace.command", "contents": { ... } } ``` --- ### CommandResult Standardised return value from every `ICommandHandler::execute()` call. Use the static factory methods. | Method | Description | |--------|-------------| | `static CommandResult ok(type, msg)` | Success with optional human-readable message | | `static CommandResult ok(type, JsonDocument)` | Success with structured JSON data payload | | `static CommandResult err(type, msg)` | Error with required message | | `static CommandResult info(type, msg)` | Unsolicited informational event (used for broadcasts) | | `bool isOk() const` | Returns true if status is `SUCCESS` | | `bool isErr() const` | Returns true if status is `ERROR` | Serialised over the wire as: ```json { "status": "SUCCESS|ERROR|INFO", "type": "command_name", "message": "...", "data": { ... } } ``` `message` is omitted when empty; `data` is omitted when `hasData` is false. --- ### ICommandHandler Interface that all domain handlers implement. | Method | Description | |--------|-------------| | `virtual std::vector commands() const = 0` | Returns all command names this handler owns. The bus registers all of them at startup. | | `virtual CommandResult execute(const CommandEnvelope& envelope) = 0` | Executes the command and returns a result. Must not call `envelope.reply()` directly — the bus owns that. Must not throw. | --- ### LegacyAdapter `translateLegacyEnvelope(CommandEnvelope& envelope)` — translates a v1 envelope into its v2 equivalent in place. Called automatically by `CommandBus::dispatch()` when `envelope.version == 1`. Not part of the public API for new code. **Translation rules:** 1. Simple 1-to-1 commands (`ping`, `identify`, `playback`) are passed through unchanged. 2. Commands with an `"action"` field in `contents` are mapped using a lookup table (e.g. `{ "cmd": "relay_setup", "contents": { "action": "set_timings" } }` → `relay.set_durations`). 3. Two boolean-split special cases: `clock_setup/set_enabled` → `clock.enable` or `clock.disable`; `system/set_mqtt_enabled` → `mqtt.enable` or `mqtt.disable`. 4. Unknown v1 commands are left unchanged so the bus returns its standard "Unknown command" error. To remove legacy support entirely: delete this file and the single `translateLegacyEnvelope()` call in `CommandBus::dispatch()`. --- ## Initialization The `CommandBus` is a plain value member of `CommunicationRouter` — no explicit initialization required. Handlers are registered via `registerHandlers()` inside `CommunicationRouter::begin()`, which is called from `main.cpp` after all late-bound references have been set via `setXxxReference()`. Transports are added to the bus with `addTransport()` inside `CommunicationRouter::begin()`, after each transport's own `begin()` has been called. --- ## Dependencies - `ArduinoJson` — for `CommandEnvelope::contents` and `CommandResult::data` - `Logging` — for registration warnings and dispatch debug logs - `ICommandHandler` / `ITransport` interfaces (headers in `Communication/Handlers/` and `Communication/Transport/`) --- ## Gotchas / Notes - **`std::map` instead of `std::unordered_map`**: Arduino's `String` type has no `std::hash` specialisation, so a tree-map is used. Lookup is O(log n) in practice, though with ~30 commands in the registry this is negligible. - **Duplicate registrations**: If two handlers claim the same command name (e.g. during a refactor), the last one registered wins and a `LOG_WARNING` is emitted. Check serial output at boot to catch this. - **`envelope.reply` is called exactly once**: Handlers must return a `CommandResult` and must not call `envelope.reply()` themselves. If a handler returns without going through the bus (e.g. throws), the client receives no response. Handlers must not throw. - **Broadcast vs reply**: `dispatch()` calls `envelope.reply()` — response goes back to the originating transport/client only. `broadcast()` sends to all transports — used for unsolicited events. These are distinct paths. - **Thread safety**: `CommandBus` has no internal locking. All dispatch calls happen on the main Arduino loop / AsyncWebServer callback thread. Do not call `dispatch()` or `broadcast()` from ISRs or FreeRTOS tasks that run concurrently with the loop.