Adds full bidirectional remote control across all major subsystems, establishing the device as the single source of truth for all settings. New firmware features (F-029 to F-037): - bells.enable / bells.disable: master ON/OFF for all playback and clock alerts (relay.test_output intentionally unaffected) - telemetry.set_guard_enabled: enable/disable thermal protection at runtime without touching thresholds - telemetry.set_max_loads: set bellMaxLoad per-bell or globally via command - Device runtime tracking: lifetime seconds flushed to SD every 10 min, boot log (up to 200 entries, rotating) written after first NTP sync - Total playback counter persisted to SD, increments on every play() - telemetry.get_metrics / telemetry.reset_metrics: new aggregate read + reset - system.get_config (replaces system.get_settings, old name still accepted), system.get_all (everything in one call), system.get_telemetry - log.get_config, mqtt.get_config, bells.get_config: new getters for previously write-only subsystems - network.status now includes ssid, mac, hostname - BellsHandler: new handler registered on CommandBus - LegacyAdapter updated with all new command mappings Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
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<ICommandHandler> 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<void(const CommandResult&)> |
Injected by the transport; called exactly once by the bus after dispatch |
Wire format (v2):
{ "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:
{ "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<String> 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:
- Simple 1-to-1 commands (
ping,identify,playback) are passed through unchanged. - Commands with an
"action"field incontentsare mapped using a lookup table (e.g.{ "cmd": "relay_setup", "contents": { "action": "set_timings" } }→relay.set_durations). - Two boolean-split special cases:
clock_setup/set_enabled→clock.enableorclock.disable;system/set_mqtt_enabled→mqtt.enableormqtt.disable. - 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— forCommandEnvelope::contentsandCommandResult::dataLogging— for registration warnings and dispatch debug logsICommandHandler/ITransportinterfaces (headers inCommunication/Handlers/andCommunication/Transport/)
Gotchas / Notes
std::mapinstead ofstd::unordered_map: Arduino'sStringtype has nostd::hashspecialisation, 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_WARNINGis emitted. Check serial output at boot to catch this. envelope.replyis called exactly once: Handlers must return aCommandResultand must not callenvelope.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()callsenvelope.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:
CommandBushas no internal locking. All dispatch calls happen on the main Arduino loop / AsyncWebServer callback thread. Do not calldispatch()orbroadcast()from ISRs or FreeRTOS tasks that run concurrently with the loop.