refactor: Fixed the file hierarchy and switched to platform.io

This commit is contained in:
2026-02-28 21:57:42 +02:00
parent ab1e4f2e6d
commit 30d660268f
65 changed files with 1208 additions and 1281 deletions
+841
View File
@@ -0,0 +1,841 @@
# Communication Subsystem — Complete Refactor Plan
> Written: 2026-02-27
> Status: **Planning** — Not yet implemented
> Related: MQTT refactor, Logging refactor (separate plans)
---
## Current State Assessment
### What works well
- Unified JSON command format across all protocols — worth keeping
- CommunicationRouter as the central hub — right architectural instinct
- Non-blocking async design — correct
- ResponseBuilder consistency — good
### What's broken architecturally
- `CommandHandler.cpp` is ~700+ lines of a single giant `if/else if` chain — classic "God Class" anti-pattern
- HTTP is a second-class citizen, faking a WebSocket context with `clientId=0xFFFFFFFF` — no proper identity
- `MessageSource` has no `HTTP` value — HTTP is disguised as WebSocket throughout the code
- CommandHandler has 8 injected dependencies via raw pointers + setters — tightly coupled to everything
- Sub-commands (`relay_setup → set_timings`) are a second level of `if/else` inside the first — inconsistent
- No protocol versioning — adding the 4th transport requires touching CommandHandler again
- `SettingsWebServer` bypasses the command system entirely
---
## Architectural Philosophy
**Target pattern:** A transport-agnostic command bus with registered handlers.
- **Transport Layer** — MQTT, WebSocket, HTTP, UART, future WebServer — each just delivers a `CommandEnvelope` to the bus
- **Command Bus** — receives envelopes, dispatches to the right handler by command name
- **Command Handlers** — small, focused classes, one per domain (Playback, Clock, Relay, System, etc.)
- **Response** — returned to the bus, which delivers it back through the originating transport
Pattern: **Command Pattern + Message Bus** (standard embedded system architecture)
---
## New Directory Structure
```
src/Communication/
├── Transport/
│ ├── ITransport.hpp ← Interface all transports implement
│ ├── MQTTTransport/
│ │ ├── MQTTTransport.hpp
│ │ └── MQTTTransport.cpp
│ ├── WebSocketTransport/
│ │ ├── WebSocketTransport.hpp
│ │ └── WebSocketTransport.cpp
│ ├── HTTPTransport/
│ │ ├── HTTPTransport.hpp
│ │ └── HTTPTransport.cpp
│ ├── UARTTransport/
│ │ ├── UARTTransport.hpp
│ │ └── UARTTransport.cpp
│ └── WebServerTransport/ ← Future 4th transport, slot ready
│ └── (placeholder)
│
├── CommandBus/
│ ├── CommandBus.hpp ← Registry + dispatcher
│ ├── CommandBus.cpp
│ ├── CommandEnvelope.hpp ← Universal message wrapper
│ ├── CommandResult.hpp ← Standardized return type
│ └── LegacyAdapter.hpp/cpp ← Optional: v1 legacy shim (deletable)
│
├── Handlers/
│ ├── ICommandHandler.hpp ← Handler interface
│ ├── PlaybackHandler/
│ ├── FileHandler/
│ ├── RelayHandler/
│ ├── ClockHandler/
│ ├── SystemHandler/
│ ├── FirmwareHandler/
│ ├── NetworkHandler/
│ └── LoggingHandler/
│
├── ResponseBuilder/ ← Keep as-is, add fromResult() factory
│ ├── ResponseBuilder.hpp
│ └── ResponseBuilder.cpp
│
└── CommunicationRouter/ ← Keeps coordinating role, simplified
├── CommunicationRouter.hpp
└── CommunicationRouter.cpp
```
---
## Core Data Structures
### CommandEnvelope
Replaces `JsonDocument + MessageContext`.
```cpp
// CommandBus/CommandEnvelope.hpp
struct CommandEnvelope {
// Protocol version — enables forward compatibility
uint8_t version; // 2 = new, 1 = legacy (default 2)
enum class Transport {
MQTT,
WEBSOCKET,
HTTP,
UART
} transport;
uint32_t clientId; // WS client ID, 0 for others
String command; // e.g. "playback", "relay_setup"
JsonDocument contents; // The "contents" object
// Reply callback injected by the transport
std::function<void(const CommandResult&)> reply;
};
```
### CommandResult
Replaces ad-hoc string building in handler methods.
```cpp
// CommandBus/CommandResult.hpp
struct CommandResult {
enum class Status { SUCCESS, ERROR, INFO };
Status status;
String type; // command type echo
String payload; // string payload
JsonDocument data; // structured data payload (optional)
bool hasData = false;
// Factory methods
static CommandResult ok(const String& type, const String& msg = "");
static CommandResult ok(const String& type, const JsonDocument& data);
static CommandResult err(const String& type, const String& msg);
};
```
### ICommandHandler
Interface every domain handler implements.
```cpp
// Handlers/ICommandHandler.hpp
class ICommandHandler {
public:
virtual ~ICommandHandler() = default;
// Returns the command name(s) this handler owns
virtual std::vector<String> commands() const = 0;
// Execute the command, return result
virtual CommandResult execute(const CommandEnvelope& envelope) = 0;
};
```
### ITransport
Interface every transport implements.
```cpp
// Transport/ITransport.hpp
class ITransport {
public:
virtual ~ITransport() = default;
virtual void begin() = 0;
virtual void loop() = 0;
virtual bool isHealthy() const = 0;
virtual String name() const = 0;
// Broadcast to all clients of this transport
virtual void broadcast(const String& message) = 0;
};
```
---
## The CommandBus
Replaces the giant `if/else` chain. The entire dispatcher is ~10 lines.
```cpp
// CommandBus/CommandBus.hpp
class CommandBus {
public:
void registerHandler(std::unique_ptr<ICommandHandler> handler);
void dispatch(CommandEnvelope& envelope);
void broadcast(const CommandResult& result);
void addTransport(ITransport* transport);
private:
std::unordered_map<String, ICommandHandler*> _registry;
std::vector<std::unique_ptr<ICommandHandler>> _handlers;
std::vector<ITransport*> _transports;
};
// CommandBus/CommandBus.cpp
void CommandBus::dispatch(CommandEnvelope& envelope) {
auto it = _registry.find(envelope.command);
if (it == _registry.end()) {
envelope.reply(CommandResult::err("unknown", "Unknown command: " + envelope.command));
return;
}
CommandResult result = it->second->execute(envelope);
envelope.reply(result);
}
```
---
## Per-Domain Handler Pattern
Each handler: ~50–100 lines, focused, one dependency set, independently testable.
```cpp
// Handlers/PlaybackHandler/PlaybackHandler.hpp
class PlaybackHandler : public ICommandHandler {
public:
explicit PlaybackHandler(Player& player);
std::vector<String> commands() const override;
CommandResult execute(const CommandEnvelope& envelope) override;
private:
Player& _player;
};
// Handlers/PlaybackHandler/PlaybackHandler.cpp
std::vector<String> PlaybackHandler::commands() const {
return { "playback" };
}
CommandResult PlaybackHandler::execute(const CommandEnvelope& envelope) {
bool ok = _player.command(envelope.contents.as<JsonVariant>());
if (ok) return CommandResult::ok("playback", "Command executed");
return CommandResult::err("playback", "Player rejected command");
}
```
---
## Transport Layer Pattern
Each transport parses raw input, builds a `CommandEnvelope` with a reply lambda, and dispatches.
```cpp
// WebSocketTransport — on message received:
void WebSocketTransport::onMessage(uint32_t clientId, const String& raw) {
JsonDocument doc;
if (deserializeJson(doc, raw) != DeserializationError::Ok) {
sendToClient(clientId, ResponseBuilder::error("parse", "Invalid JSON"));
return;
}
CommandEnvelope envelope;
envelope.transport = CommandEnvelope::Transport::WEBSOCKET;
envelope.clientId = clientId;
envelope.command = doc["cmd"].as<String>();
envelope.contents = doc["contents"];
envelope.version = doc["v"] | 2;
envelope.reply = [this, clientId](const CommandResult& result) {
sendToClient(clientId, ResponseBuilder::fromResult(result));
};
_commandBus.dispatch(envelope);
}
```
HTTP is now a proper first-class transport — no more `0xFFFFFFFF` hack:
```cpp
// HTTPTransport — on POST /api/command:
envelope.transport = CommandEnvelope::Transport::HTTP;
envelope.reply = [request](const CommandResult& result) {
request->send(200, "application/json", ResponseBuilder::fromResult(result));
};
```
UART keeps its whitelist — lives inside `UARTTransport`, not in the bus:
```cpp
// UARTTransport — before dispatch:
if (!isWhitelisted(envelope.command)) {
// silently ignore (prevent feedback loops)
return;
}
_commandBus.dispatch(envelope);
```
---
## Simplified CommunicationRouter
```cpp
class CommunicationRouter {
public:
CommunicationRouter(/* core dependencies */);
void begin();
void loop();
bool isHealthy() const;
// For subsystems pushing events (telemetry, bell strikes, etc.)
void broadcast(const CommandResult& event);
void broadcastToMasters(const String& message);
private:
CommandBus _commandBus;
MQTTTransport _mqtt;
WebSocketTransport _ws;
HTTPTransport _http;
UARTTransport _uart;
void registerHandlers(); // Replaces all setXxxReference() calls
};
// All handler wiring in one place:
void CommunicationRouter::registerHandlers() {
_commandBus.registerHandler(std::make_unique<PlaybackHandler>(_player));
_commandBus.registerHandler(std::make_unique<RelayHandler>(_configManager));
_commandBus.registerHandler(std::make_unique<ClockHandler>(_configManager, _timeKeeper));
_commandBus.registerHandler(std::make_unique<FileHandler>(_fileManager));
_commandBus.registerHandler(std::make_unique<SystemHandler>(_configManager, _networking));
_commandBus.registerHandler(std::make_unique<FirmwareHandler>(_firmwareValidator, _otaManager));
_commandBus.registerHandler(std::make_unique<NetworkHandler>(_configManager, _networking));
_commandBus.registerHandler(std::make_unique<LoggingHandler>(_logging));
}
```
---
## Sub-Command Strategy
Two options — pick one:
### Option A — Flatten (Recommended for new protocol)
Register `relay.set_timings` and `relay.set_outputs` as separate top-level commands. Removes nested `if/else` entirely.
```json
{ "cmd": "relay.set_timings", "v": 2, "contents": { ... } }
```
### Option B — Keep Nesting (Recommended for wire compatibility)
Keep `relay_setup` as the command. `RelayHandler` switches on `contents["action"]` internally. Still clean because it's isolated in one small class.
```json
{ "cmd": "relay_setup", "contents": { "action": "set_timings", ... } }
```
**Decision:** Option B is safer if FlutterFlow app rollout is staggered. Wire format stays identical.
---
## Protocol Versioning / Legacy Compatibility
`CommandEnvelope.version` enables a clean cutover:
- Client sends `"v": 1` (or omits `v`) → treated as legacy
- Client sends `"v": 2` → goes straight through
```cpp
// CommandBus/LegacyAdapter.hpp / .cpp
// Maps old command names / content shapes to new ones
// Completely deletable in one PR when legacy support ends
static const std::unordered_map<String, String> LEGACY_COMMAND_MAP = {
// Add entries here only if command names change in v2
// If names stay the same, this file may not be needed at all
};
void translateLegacyEnvelope(CommandEnvelope& env) {
auto it = LEGACY_COMMAND_MAP.find(env.command);
if (it != LEGACY_COMMAND_MAP.end()) {
env.command = it->second;
}
}
```
**Recommendation:** If command names stay identical between v1 and v2, skip the legacy adapter entirely and just force-update the FlutterFlow app.
---
## The 4th Transport — On-Board Web Server
With this architecture, adding it costs almost nothing:
1. Create `WebServerTransport` implementing `ITransport`
2. HTML routes POST to CommandBus via synthetic `CommandEnvelope`
3. Register it in `CommunicationRouter::begin()`
4. `SettingsWebServer` absorbs into this transport (fixes the current bypass of the command system)
---
## What Stays the Same
| Component | Action |
|---|---|
| `ResponseBuilder` | Keep — add `fromResult(CommandResult)` factory method |
| `ClientManager` | Keep — used by `WebSocketTransport` |
| Wire protocol format | Keep — `{ "cmd": "...", "contents": { ... } }` unchanged |
| MQTT topics | Keep — no change |
| MQTT auth system | Keep — no change |
| UART whitelist | Keep — move into `UARTTransport` |
---
## Implementation Stages
### Stage 1 — Core Scaffolding ✅ / ⬜ TODO
> No behavior change. Zero risk. Headers only.
- [ ] Define `CommandEnvelope.hpp`
- [ ] Define `CommandResult.hpp`
- [ ] Define `ICommandHandler.hpp`
- [ ] Define `ITransport.hpp`
- [ ] Create `CommandBus` skeleton (register + dispatch, no handlers yet)
- [ ] Old `CommandHandler` stays untouched
### Stage 2 — Migrate Handlers One Domain at a Time
> Write new handler → register on bus → comment out old if/else branch → test
- [ ] `PlaybackHandler` (simplest — one dependency)
- [ ] `SystemHandler`
- [ ] `FirmwareHandler`
- [ ] `LoggingHandler`
- [ ] `RelayHandler` (complex — multiple sub-commands)
- [ ] `ClockHandler` (most complex — many sub-commands)
- [ ] `FileHandler`
- [ ] `NetworkHandler`
### Stage 3 — Transport Layer Refactor
- [ ] Refactor `MQTTAsyncClient` → `MQTTTransport` (implement `ITransport`)
- [ ] Refactor `WebSocketServer` → `WebSocketTransport` (implement `ITransport`)
- [ ] Promote `HTTPRequestHandler` → `HTTPTransport` (proper HTTP identity, no more 0xFFFFFFFF)
- [ ] Refactor `UARTCommandHandler` → `UARTTransport` (whitelist lives here)
### Stage 4 — CommunicationRouter Simplification
- [ ] Replace router internals with `CommandBus` + transport array
- [ ] Implement `registerHandlers()` — replaces all `setXxxReference()` calls
- [ ] Delete old `CommandHandler` once all handlers migrated and tested
### Stage 5 — Legacy Adapter (optional)
- [ ] Add `LegacyAdapter.cpp` if needed for staggered FlutterFlow rollout
- [ ] Test with FlutterFlow app sending `"v": 1`
- [ ] Set cutover date — delete adapter in one clean PR
### Stage 6 — SettingsWebServer Integration (4th Transport)
- [ ] Create `WebServerTransport` skeleton
- [ ] Absorb `SettingsWebServer` into `WebServerTransport`
- [ ] Settings page form POSTs route through `CommandBus`
- [ ] All 4 transports share single command pipeline
---
## Before / After Comparison
| Concern | Current | New |
|---|---|---|
| Command dispatch | 700-line `if/else` | Hash map, O(1) lookup |
| Adding a command | Edit giant `CommandHandler` | Add a new ~50-line class |
| HTTP identity | Fake WebSocket (`0xFFFFFFFF`) | Proper `HTTPTransport` |
| Adding a transport | Touch `CommandHandler` | Implement `ITransport`, register |
| Handler dependencies | 8 setter injections on one class | Explicit constructor per handler |
| Sub-commands | Nested `if/else` inside `if/else` | Internal to focused handler class |
| Legacy support | N/A | Isolated `LegacyAdapter`, deletable in one PR |
| On-board WebServer | Bypasses command system | `WebServerTransport`, full integration |
---
## ESP32 Memory Notes
- `std::unordered_map` is fine on ESP32-D0WD for a ~10-entry registry (trivial footprint)
- `std::unique_ptr` for handler ownership — no raw pointer leaks
- `std::function` reply lambdas — small captures (one pointer + one uint32)
- If memory gets tight: replace `unordered_map` with sorted static array + binary search — zero impact on handler code
---
---
# Command System Redesign
> This section documents the complete v2 command API — what changes, what's removed, what's new, and the full canonical command table.
---
## What's Wrong With the Current Commands
### Problem 1 — Two umbrella commands doing the same job
`system` and `system_info` are both grab-bags. Two commands even overlap directly:
- `system → status` duplicates `system_info → report_status`
- `system → get_firmware_status` duplicates `system_info → get_firmware_status`
### Problem 2 — Wrong grouping
- `set_network_config` is buried inside `system` instead of being in a `network` namespace
- Log level commands are inside `system` instead of a `log` namespace
- `set_mqtt_enabled` controls a transport but lives in `system`
- `get_device_time` and `get_clock_time` are in `system_info` but logically belong in `clock` and `system` respectively
### Problem 3 — Internal command exposed publicly
- `sync_time_to_lcd` is a UART push that the device sends to its own LCD slave board. It is not a client command — a FlutterFlow app should never need to call this. It should be an internal method, not a public API endpoint.
### Problem 4 — Entire subsystems have zero command coverage
- `HealthMonitor` — no commands at all
- `Telemetry` — no commands at all
- `OutputManager` — no direct control (relay fire/extinguish only reachable via Player)
- `BuiltInMelodies` — list never exposed, clients can't see what's available without downloading
### Problem 5 — Naming inconsistency
- `set_timings` on relay means "bell strike durations" — ambiguous
- `restart` and `reboot` are aliases doing the same thing — pick one
- `reset_defaults` is unclear — `factory_reset` is universally understood
---
## Handler Input Contract (Design Principle)
This rule applies to **every single handler** without exception. It must be enforced during implementation.
```
Extra fields in contents? → Ignore silently. Never crash on unknown keys.
Missing optional fields? → Use defaults or skip that part of the operation.
Missing required fields? → Return ERROR with a clear message. Do nothing else.
Wrong type / bad format? → Return ERROR with a clear message. Do nothing else.
No contents at all? → If the command needs none, proceed. If it needs some, return ERROR.
```
Concretely: if a client sends `relay.set_durations` with only bell `"0"`, update bell 0 and leave all others unchanged. Do not require all 6 bells to be present. If a client sends `relay.test_output` with no `output` field, return an error — that field is required. If a client sends `relay.test_output` with `output`, `duration_ms`, and an extra unknown field `foo`, ignore `foo` and proceed.
This applies to ALL multi-field commands: relay durations, relay outputs, clock outputs, clock alerts, network config, etc.
---
## Command Decisions: Keep / Change / Remove / Add
### KEEP (as-is or renamed)
| Old command | Decision | Reason |
|---|---|---|
| `ping` | Keep → `ping` | Simple, universally understood utility |
| `identify` | Keep → `identify` | WebSocket client-type registration, needed |
| `playback` | Keep → `playback` | Already flat and well-structured |
| `relay_setup → set_outputs` | Keep → `relay.set_outputs` | Correct grouping, just flatten |
| `clock_setup → set_outputs` | Keep → `clock.set_outputs` | Correct grouping |
| `clock_setup → set_alerts` | Keep → `clock.set_alerts` | Correct grouping |
| `clock_setup → set_backlight` | Keep → `clock.set_backlight` | Correct grouping |
| `clock_setup → set_silence` | Keep → `clock.set_silence` | Correct grouping |
| `clock_setup → set_rtc_time` | Keep → `clock.set_time` | Shorter, clearer |
| `clock_setup → set_physical_clock_time` | Keep → `clock.set_face` | "Face" = analog clock face position |
| `clock_setup → pause_clock_updates` | Keep → `clock.pause` | Fine |
| `clock_setup → resume_clock_updates` | Keep → `clock.resume` | Fine |
| `system_info → get_full_settings` | Keep → `system.get_settings` | Useful, correct namespace |
| `system_info → network_info` | Keep → `network.info` | Move to correct namespace |
| `system → reset_defaults` | Keep → `system.factory_reset` | Rename: clearer intent |
| `system → commit_firmware` | Keep → `firmware.commit` | Correct namespace |
| `system → rollback_firmware` | Keep → `firmware.rollback` | Correct namespace |
| `system → get_firmware_status` | Keep → `firmware.status` | Deduplicated, correct namespace |
| `system → set_network_config` | Keep → `network.set_config` | Move to correct namespace |
| `system → set_serial_log_level` | Keep → `log.set_serial` | Correct namespace |
| `system → set_sd_log_level` | Keep → `log.set_sd` | Correct namespace |
| `system → set_mqtt_log_level` | Keep → `log.set_mqtt` | Correct namespace |
| `system → restart` | Keep → `system.restart` | Collapse `reboot` alias, one canonical name |
| `system → force_update` | Keep → `ota.update` | Correct namespace |
| `system → custom_update` | Keep → `ota.custom` | Correct namespace |
| `file_manager → list_melodies` | Keep → `files.list` | Flat, cleaner — melodies only (SD card) |
| `file_manager → download_melody` | Keep → `files.download` | Fine |
| `file_manager → delete_melody` | Keep → `files.delete` | Fine |
### CHANGE (same function, fixed grouping or naming)
| Old command | New command | What changes |
|---|---|---|
| `relay_setup → set_timings` | `relay.set_durations` | Renamed: "timings" is vague, "durations" is what it actually sets (ms per strike) |
| `clock_setup → set_timings` | `clock.set_timings` | Keep name, but note: currently calls `updateClockOutputs()` — **bug in original code**, fix during migration |
| `clock_setup → set_enabled` | Split into `clock.enable` / `clock.disable` | No boolean needed — intent is unambiguous, cleaner in logs and app code |
| `system → set_mqtt_enabled` | Split into `mqtt.enable` / `mqtt.disable` | Same reasoning as clock enable/disable |
| `system_info → report_status` | `system.status` | Moved out of umbrella, deduplicated with `system → status` |
| `system_info → get_device_time` | `system.get_time` | Moved: this is system-level RTC time, not clock-face time |
| `system_info → get_clock_time` | `clock.get_face` | Moved to `clock` namespace — returns analog face position |
| `telemetry.reset_strikes` | `telemetry.reset_strikes` + optional `{ "bell": N }` | Omit `bell` → reset all. Include `bell` → reset only that channel. Enables per-bell reset when a striker is replaced. |
| `relay.test_output` | `relay.test_output` with required `duration_ms` | No default duration — caller must be explicit. Forces operator intentionality. 85–140ms is typical; 200ms is too long for sensitive strikers. Both `output` and `duration_ms` are required fields. |
### REMOVE
| Old command | Reason |
|---|---|
| `system → status` | Duplicate of `system_info → report_status`. One survives as `system.status`. |
| `system → get_firmware_status` (under `system`) | Duplicate. Survives as `firmware.status`. |
| `system_info → get_firmware_status` (under `system_info`) | Duplicate. Same as above. |
| `system → reboot` | Alias for `restart`. Removed. `system.restart` is the one. |
| `system_info → sync_time_to_lcd` | **Removed as a public push command.** The LCD slave is a proper bidirectional UART client — it requests time with `system.get_time` and gets a response. The old model (master pushing time unsolicited) caused infinite loop bugs when responses were corrupted. The new model is clean request/response. |
### ADD (new commands, previously uncovered functionality)
| New command | Handler | What it does | Why |
|---|---|---|---|
| `system.get_device_info` | SystemHandler | Returns device UID, hw_type, hw_version, fw_version, uptime, free heap | Currently buried in `get_full_settings` — needs its own fast endpoint |
| `system.health` | SystemHandler | Returns full `HealthMonitor` report — all subsystem states, warnings, critical failures | `HealthMonitor` has zero command coverage today |
| `clock.set_timezone` | ClockHandler | Sets GMT offset + DST offset + optional timezone name, saves to SD | Timezone is currently piggybacked onto `clock.set_time` — can't change timezone without resending a timestamp |
| `clock.get_timezone` | ClockHandler | Returns current GMT offset, DST offset, timezone name | No read command for timezone today |
| `clock.sync_ntp` | ClockHandler | Forces an immediate NTP sync via `TimeKeeper::syncTimeWithNTP()` | No on-demand NTP sync exists today |
| `telemetry.get_strikes` | TelemetryHandler | Returns strike counts per bell channel | Currently only returned as part of `system.status` |
| `telemetry.reset_strikes` | TelemetryHandler | Resets strike counters — all channels, or a single channel via `{ "bell": N }` | No command exists today; per-bell reset is critical for striker replacement |
| `telemetry.get_loads` | TelemetryHandler | Returns current heat load per bell channel, cooling status, overload flags | No command exists today |
| `files.list_builtin` | FileHandler | Returns list of all built-in melodies (name + UID) from `BuiltInMelodies::getBuiltInMelodiesJSON()` | Currently impossible for a client to know what built-ins exist without trying to play them |
| `ota.status` | FirmwareHandler | Returns OTAManager status: current version, available version, update channel, last check time, update progress | No status query exists today |
| `ota.check` | FirmwareHandler | Triggers `OTAManager::checkForUpdates()` and returns result immediately | No on-demand check exists today |
| `relay.get_config` | RelayHandler | Returns current bell durations + output assignments as JSON | No read command for relay config today — only write |
| `clock.get_config` | ClockHandler | Returns full clock configuration (outputs, timings, alerts, backlight, silence, enabled state) | No read command for clock config today — only write |
| `network.status` | NetworkHandler | Returns connection state, IP, RSSI, AP mode flag | `network.info` only returns IP/gateway/DNS — no connection state or signal strength |
| `relay.test_output` | RelayHandler | Fires a specific relay for a caller-specified duration. Both `output` and `duration_ms` required. Safety-gated: only works when Player is stopped | Diagnostic/commissioning — currently impossible without a full playback command |
---
## Complete v2 Command Table
The canonical reference. Every command in the new system.
### `ping`
| Field | Value |
|---|---|
| Handler | SystemHandler |
| Transport restriction | None (all transports) |
| Contents | *(none)* |
| Returns | `{ "status": "SUCCESS", "type": "pong" }` |
### `identify`
| Field | Value |
|---|---|
| Handler | SystemHandler |
| Transport restriction | WebSocket only |
| Contents | `{ "device_type": "master" \| "secondary" }` — required |
| Returns | Success/error |
### `playback`
| Field | Value |
|---|---|
| Handler | PlaybackHandler |
| Transport restriction | None |
| Contents | `{ "action": "play" \| "stop" \| "pause" \| "unpause", ...melody attributes }` — `action` required |
| Returns | Success/error |
---
### Relay namespace — `RelayHandler`
| Command | Required fields | Optional fields | Returns |
|---|---|---|---|
| `relay.set_durations` | *(at least one bell)* | `{ "bells": { "0": 95, "2": 110, ... } }` — partial updates accepted | Success/error |
| `relay.set_outputs` | *(at least one bell)* | `{ "bells": { "0": 2, "1": 3, ... } }` — partial updates accepted | Success/error |
| `relay.get_config` | *(none)* | — | `{ "durations": {...}, "outputs": {...} }` |
| `relay.test_output` | `output`, `duration_ms` | — | Success/error — **player must be stopped** |
---
### Clock namespace — `ClockHandler`
| Command | Required fields | Optional fields | Returns |
|---|---|---|---|
| `clock.set_outputs` | *(at least one of c1, c2)* | `{ "c1": 4, "c2": 5 }` — partial OK | Success/error |
| `clock.set_timings` | *(at least one timing field)* | timing config fields — partial OK | Success/error |
| `clock.set_alerts` | *(at least one alert field)* | alert config fields — partial OK | Success/error |
| `clock.set_backlight` | *(at least one field)* | backlight config fields — partial OK | Success/error |
| `clock.set_silence` | *(at least one field)* | silence period fields — partial OK | Success/error |
| `clock.set_time` | `timestamp` | `timezone_offset`, `dst_offset` | Success/error |
| `clock.set_face` | `hour`, `minute` | — | Success/error |
| `clock.set_timezone` | `gmt_offset_sec` | `dst_offset_sec`, `timezone_name` | Success/error |
| `clock.get_timezone` | *(none)* | — | `{ gmt_offset_sec, dst_offset_sec, timezone_name }` |
| `clock.sync_ntp` | *(none)* | — | Success/error |
| `clock.enable` | *(none)* | — | Success/error |
| `clock.disable` | *(none)* | — | Success/error |
| `clock.pause` | *(none)* | — | Success/error |
| `clock.resume` | *(none)* | — | Success/error |
| `clock.get_face` | *(none)* | — | `{ clock_hour, clock_minute, last_sync_time, next_output_is_c1 }` |
| `clock.get_config` | *(none)* | — | Full clock config object |
---
### System namespace — `SystemHandler`
| Command | Required fields | Optional fields | Returns |
|---|---|---|---|
| `system.status` | *(none)* | — | Player state, strike counters, projected run time |
| `system.get_time` | *(none)* | — | `{ local_timestamp, utc_timestamp, year, month, day, hour, minute, second, rtc_available }` |
| `system.get_settings` | *(none)* | — | Full ConfigManager JSON dump |
| `system.get_device_info` | *(none)* | — | `{ uid, hw_type, hw_version, fw_version, uptime_ms, free_heap, min_free_heap }` |
| `system.health` | *(none)* | — | Full HealthMonitor report — subsystem states, warnings, critical count |
| `system.factory_reset` | *(none)* | — | Success/error |
| `system.restart` | *(none)* | — | Sends response, then reboots after 2s |
---
### Firmware namespace — `FirmwareHandler`
| Command | Required fields | Returns |
|---|---|---|
| `firmware.status` | *(none)* | Validation state, version, boot count, can_commit, can_rollback |
| `firmware.commit` | *(none)* | Success/error |
| `firmware.rollback` | *(none)* | Success/error — device reboots |
---
### OTA namespace — `FirmwareHandler`
| Command | Required fields | Optional fields | Returns |
|---|---|---|---|
| `ota.status` | *(none)* | — | `{ current_version, available_version, channel, update_available, last_check, progress }` |
| `ota.check` | *(none)* | `channel` (default: "stable") | Update availability result |
| `ota.update` | *(none)* | `channel` (default: "stable") | Success/error — device may reboot |
| `ota.custom` | `firmware_url` | `checksum`, `file_size`, `version` | Success/error — device may reboot |
---
### Network namespace — `NetworkHandler`
| Command | Required fields | Optional fields | Returns |
|---|---|---|---|
| `network.info` | *(none)* | — | `{ ip, gateway, dns }` |
| `network.status` | *(none)* | — | `{ connected, state, type, ip, rssi, ap_mode }` |
| `network.set_config` | *(at least one field)* | `hostname`, `useStaticIP`, `ip`, `gateway`, `subnet`, `dns1`, `dns2` — partial OK; static IP requires ip+gateway+subnet together | Success/error + restart_required flag |
---
### Files namespace — `FileHandler`
| Command | Required fields | Returns |
|---|---|---|
| `files.list` | *(none)* | Array of melody files on SD card (melodies only) |
| `files.list_builtin` | *(none)* | Array of built-in melodies `[{ name, uid }, ...]` |
| `files.download` | `melodys_uid` | Success/error |
| `files.delete` | `name` | Success/error |
> `files.list` returns SD card melodies only. Built-in melodies have their own endpoint. Future: add `type` filter for other file categories (schedules, etc.)
---
### Log namespace — `LoggingHandler`
| Command | Required fields | Returns |
|---|---|---|
| `log.set_serial` | `level` (0–5) | Success/error |
| `log.set_sd` | `level` (0–5) | Success/error |
| `log.set_mqtt` | `level` (0–5) | Success/error |
---
### MQTT namespace — `MQTTHandler`
| Command | Required fields | Returns |
|---|---|---|
| `mqtt.enable` | *(none)* | Success/error |
| `mqtt.disable` | *(none)* | Success/error |
---
### Telemetry namespace — `TelemetryHandler` *(new — zero coverage today)*
| Command | Required fields | Optional fields | Returns |
|---|---|---|---|
| `telemetry.get_strikes` | *(none)* | — | `{ "strikes": { "0": 1234, "1": 567, ... } }` |
| `telemetry.reset_strikes` | *(none)* | `bell` (int) — omit to reset all, include to reset one channel | Success/error |
| `telemetry.get_loads` | *(none)* | — | `{ "loads": { "0": 42.5, ... }, "cooling_active": false, "overloaded": [2, 5] }` |
---
## Handler → Dependency Map
| Handler | Dependencies |
|---|---|
| `PlaybackHandler` | `Player` |
| `RelayHandler` | `ConfigManager`, `OutputManager`, `Player` (for safety gate) |
| `ClockHandler` | `ConfigManager`, `TimeKeeper` |
| `SystemHandler` | `ConfigManager`, `Player`, `Telemetry`, `HealthMonitor` |
| `FirmwareHandler` | `FirmwareValidator`, `OTAManager`, `Player` |
| `NetworkHandler` | `ConfigManager`, `Networking` |
| `FileHandler` | `FileManager` |
| `LoggingHandler` | `ConfigManager` |
| `TelemetryHandler` | `Telemetry` |
| `MQTTHandler` | `ConfigManager`, `MQTTTransport` (direct reference) |
---
## UART Whitelist (v2)
The UART transport only allows commands that make sense for a slave LCD/button board. All others are silently dropped to prevent feedback loops.
The LCD is a proper bidirectional client in v2 — it can send requests and receive responses. The old push model (`sync_time_to_lcd`) is retired. The LCD requests `system.get_time` and the response is a normal command reply — no loop possible because replies are not commands.
```
Allowed via UART (whitelist):
- ping (connection check)
- playback (play/stop from physical buttons)
- clock.pause (button-triggered pause)
- clock.resume (button-triggered resume)
- system.get_time (LCD requests current time — replaces old push model)
```
All other commands are silently dropped by `UARTTransport` before reaching the bus.
---
## v1 → v2 Legacy Mapping (LegacyAdapter)
Full translation table for `LegacyAdapter.cpp`. When a client sends `"v": 1` (or omits `v`), this runs first. The adapter extracts `contents["action"]`, combines it with `cmd` to produce the flat v2 command, and strips `action` from contents before dispatch.
| v1 `cmd` | v1 `action` | v2 `cmd` |
|---|---|---|
| `ping` | — | `ping` |
| `identify` | — | `identify` |
| `playback` | — | `playback` |
| `file_manager` | `list_melodies` | `files.list` |
| `file_manager` | `download_melody` | `files.download` |
| `file_manager` | `delete_melody` | `files.delete` |
| `relay_setup` | `set_timings` | `relay.set_durations` |
| `relay_setup` | `set_outputs` | `relay.set_outputs` |
| `clock_setup` | `set_outputs` | `clock.set_outputs` |
| `clock_setup` | `set_timings` | `clock.set_timings` |
| `clock_setup` | `set_alerts` | `clock.set_alerts` |
| `clock_setup` | `set_backlight` | `clock.set_backlight` |
| `clock_setup` | `set_silence` | `clock.set_silence` |
| `clock_setup` | `set_rtc_time` | `clock.set_time` |
| `clock_setup` | `set_physical_clock_time` | `clock.set_face` |
| `clock_setup` | `pause_clock_updates` | `clock.pause` |
| `clock_setup` | `resume_clock_updates` | `clock.resume` |
| `clock_setup` | `set_enabled` + `enabled=true` | `clock.enable` |
| `clock_setup` | `set_enabled` + `enabled=false` | `clock.disable` |
| `system_info` | `report_status` | `system.status` |
| `system_info` | `get_device_time` | `system.get_time` |
| `system_info` | `get_clock_time` | `clock.get_face` |
| `system_info` | `get_firmware_status` | `firmware.status` |
| `system_info` | `network_info` | `network.info` |
| `system_info` | `get_full_settings` | `system.get_settings` |
| `system_info` | `sync_time_to_lcd` | `system.get_time` *(remapped — LCD now uses request/response model)* |
| `system` | `status` | `system.status` |
| `system` | `reset_defaults` | `system.factory_reset` |
| `system` | `commit_firmware` | `firmware.commit` |
| `system` | `rollback_firmware` | `firmware.rollback` |
| `system` | `get_firmware_status` | `firmware.status` |
| `system` | `set_network_config` | `network.set_config` |
| `system` | `set_serial_log_level` | `log.set_serial` |
| `system` | `set_sd_log_level` | `log.set_sd` |
| `system` | `set_mqtt_log_level` | `log.set_mqtt` |
| `system` | `set_mqtt_enabled` + `enabled=true` | `mqtt.enable` |
| `system` | `set_mqtt_enabled` + `enabled=false` | `mqtt.disable` |
| `system` | `restart` | `system.restart` |
| `system` | `reboot` | `system.restart` |
| `system` | `force_update` | `ota.update` |
| `system` | `custom_update` | `ota.custom` |