# Handlers ## Summary Domain handlers implement the `ICommandHandler` interface and contain the actual logic for each command namespace. Each handler is constructed with references to the subsystems it needs, registered onto the `CommandBus` via `CommunicationRouter::registerHandlers()`, and called synchronously by the bus when a matching command arrives. Handlers never call `envelope.reply()` directly — they return a `CommandResult` and the bus handles the reply. Handlers must not throw. See [ICommandHandler.hpp](ICommandHandler.hpp) for the interface definition. --- ## Handler Registry | Handler | Commands owned | Dependencies | |---------|---------------|--------------| | `PlaybackHandler` | `playback` | `Player` | | `RelayHandler` | `relay.set_durations`, `relay.set_outputs`, `relay.get_config`, `relay.test_output` | `ConfigManager`, `OutputManager`, `Player` | | `ClockHandler` | `clock.set_outputs`, `clock.set_timings`, `clock.set_alerts`, `clock.set_backlight`, `clock.set_silence`, `clock.set_time`, `clock.set_face`, `clock.set_timezone`, `clock.get_timezone`, `clock.sync_ntp`, `clock.enable`, `clock.disable`, `clock.pause`, `clock.resume`, `clock.get_face`, `clock.get_config` | `ConfigManager`, `Timekeeper` | | `SystemHandler` | `ping`, `identify`, `system.status`, `system.get_time`, `system.get_settings`, `system.get_device_info`, `system.health`, `system.factory_reset`, `system.restart` | `ConfigManager`, `Player`, `Telemetry`, `HealthMonitor`, `Timekeeper`, `ClientManager` | | `FirmwareHandler` | `firmware.status`, `firmware.commit`, `firmware.rollback`, `ota.update`, `ota.custom` | `FirmwareValidator`, `OTAManager`, `Player` | | `NetworkHandler` | `network.info`, `network.status`, `network.set_config` | `ConfigManager`, `Networking` | | `FileHandler` | `files.list`, `files.list_builtin`, `files.download`, `files.delete` | `FileManager` | | `LoggingHandler` | `log.set_serial`, `log.set_sd`, `log.set_mqtt` | `ConfigManager` | | `TelemetryHandler` | `telemetry.get_strikes`, `telemetry.reset_strikes`, `telemetry.get_loads` | `Telemetry` | | `MQTTHandler` | `mqtt.enable`, `mqtt.disable` | `ConfigManager`, `MQTTDriver` | --- ## PlaybackHandler Forwards the entire `contents` object to `Player::command()` as a `JsonVariant`. The Player interprets the contents internally (action, melody name, bell selection, etc.). **Commands:** | Command | Contents | Description | |---------|----------|-------------| | `playback` | Player-specific JSON | Forward to `Player::command()`. Returns error if the player rejects the command. | --- ## RelayHandler Manages relay output configuration (durations and output pin mappings). Persists changes to SD via `ConfigManager`. Test output is blocked while the player is active. **Commands:** | Command | Required contents | Description | |---------|------------------|-------------| | `relay.set_durations` | `{ "bells": { "0": 500, ... } }` | Update strike durations (ms) for up to 16 bells. Saves to SD. | | `relay.set_outputs` | `{ "bells": { "0": 2, ... } }` | Update physical output pin mapping for each bell. Saves to SD. | | `relay.get_config` | — | Returns all 16 bell durations and output assignments. | | `relay.test_output` | `{ "output": 0–31, "duration_ms": 1–5000 }` | Fires a single output. Blocked if player is not stopped. | --- ## ClockHandler Full control over the Timekeeper clock subsystem and its persisted configuration. Most commands save to SD via `ConfigManager`. **Commands:** | Command | Key contents fields | Description | |---------|---------------------|-------------| | `clock.set_outputs` | Clock output config object | Set C1/C2 output pins. Saves clock config. | | `clock.set_timings` | `pulse_duration`, `pause_duration` | Set impulse clock pulse and pause durations (ms). | | `clock.set_alerts` | Alert config object | Set hourly/half/quarter bell alert settings. | | `clock.set_backlight` | Backlight config object | Configure backlight output and schedule. | | `clock.set_silence` | Silence config object | Configure daytime/nighttime silence windows. | | `clock.set_time` | `timestamp` (unix), optional `timezone_offset`, `dst_offset` | Set RTC time. Also updates timezone config if offsets provided. | | `clock.set_face` | `hour` (0–23), `minute` (0–59) | Set the physical clock face position. Saves clock state. | | `clock.set_timezone` | `gmt_offset_sec`, optional `dst_offset_sec` | Persist timezone config. Does not update RTC. | | `clock.get_timezone` | — | Returns `gmt_offset_sec`, `dst_offset_sec`, `ntp_server`. | | `clock.sync_ntp` | — | Triggers an immediate NTP sync via `Timekeeper::syncTimeWithNTP()`. | | `clock.enable` | — | Enables clock operation. Saves to SD. | | `clock.disable` | — | Disables clock operation. Saves to SD. | | `clock.pause` | — | Pauses clock motor updates (in-memory only, not saved). | | `clock.resume` | — | Resumes clock motor updates. | | `clock.get_face` | — | Returns `clock_hour`, `clock_minute`, `last_sync_time`, `next_output_is_c1`. | | `clock.get_config` | — | Returns the full `ClockConfig` struct as JSON. | --- ## SystemHandler General device management. `identify` is WebSocket-only. `system.restart` defers the actual reboot to a FreeRTOS task so the reply reaches the client first. **Commands:** | Command | Key contents | Description | |---------|-------------|-------------| | `ping` | — | Returns `{ "status": "SUCCESS", "type": "pong" }`. | | `identify` | `{ "device_type": "master"\|"secondary" }` | WebSocket only. Classifies the calling client in `ClientManager`. | | `system.status` | — | Player status, time elapsed, projected run time, 16 strike counters. | | `system.get_time` | — | Local and UTC timestamps, broken-down time fields, `rtc_available`. | | `system.get_settings` | — | Full device settings as JSON (from `ConfigManager::getAllSettingsAsJson()`). | | `system.get_device_info` | — | UID, hw type, hw version, fw version, uptime, free heap. | | `system.health` | — | Triggers `HealthMonitor::performFullHealthCheck()`; returns per-subsystem status. | | `system.factory_reset` | — | Resets all config to defaults. **Does not reboot automatically.** | | `system.restart` | — | Schedules `ESP.restart()` 2 seconds after reply. | --- ## FirmwareHandler OTA update management and firmware validation control. OTA commands are blocked during active playback. **Commands:** | Command | Key contents | Description | |---------|-------------|-------------| | `firmware.status` | — | Returns validation state, version info, `can_commit`, `can_rollback`. | | `firmware.commit` | — | Manually commits the firmware under test. Errors if not in testing mode. | | `firmware.rollback` | — | Rolls back to previous firmware and reboots. | | `ota.update` | optional `{ "channel": "stable" }` | Triggers OTA update from configured channel. Blocked if player is active. | | `ota.custom` | `{ "firmware_url": "...", "checksum": "...", "file_size": N, "version": N }` | OTA from a custom URL. `firmware_url` is required. | --- ## NetworkHandler Network status queries and configuration. AP mode toggle via `network.set_config` with `permanent_ap_mode` is the primary use case (also called by `WebServerTransport`). Full static IP configuration is supported. **Commands:** | Command | Key contents | Description | |---------|-------------|-------------| | `network.info` | — | Returns `ip`, `gateway`, `dns` from `WiFi` directly. | | `network.status` | — | Returns `connected`, `ip`, `ap_mode`, `rssi`, `state`, `type`. | | `network.set_config` | `permanent_ap_mode` bool, or `hostname`/`useStaticIP`/`ip`/`gateway`/`subnet`/`dns1`/`dns2` | Saves network config. Restart required to apply. AP mode toggle is handled independently. | --- ## FileHandler SD card melody file management. All operations require a healthy SD card via `FileManager`. **Commands:** | Command | Key contents | Description | |---------|-------------|-------------| | `files.list` | — | Lists all `.json` files in `/melodies`. Returns `{ "files": [...] }`. | | `files.list_builtin` | — | Returns the built-in melody list from `BuiltInMelodies`. | | `files.download` | Melody JSON object | Downloads / saves a melody to SD via `FileManager::addMelody()`. Uses `melodys_uid` or `name` for logging. | | `files.delete` | `{ "name": "filename.json" }` | Deletes `/melodies/{name}`. | --- ## LoggingHandler Runtime log level control. Changes take effect immediately and are persisted to SD via `ConfigManager::saveGeneralConfig()`. **Commands:** | Command | Contents | Description | |---------|----------|-------------| | `log.set_serial` | `{ "level": 0–5 }` | Sets serial log level. 0=NONE, 5=VERBOSE. | | `log.set_sd` | `{ "level": 0–5 }` | Sets SD card log level. | | `log.set_mqtt` | `{ "level": 0–5 }` | Sets MQTT log level. | --- ## TelemetryHandler Read-only access to bell strike counters and load measurements. Reset clears all 16 counters at once. **Commands:** | Command | Description | |---------|-------------| | `telemetry.get_strikes` | Returns strike counts for all 16 bells as `{ "strikes": { "0": N, ... } }`. | | `telemetry.reset_strikes` | Resets all 16 strike counters to 0. | | `telemetry.get_loads` | Returns current load values, `cooling_active` flag, and array of overloaded bell indices. | --- ## MQTTHandler Enables or disables the MQTT connection at runtime. The state is saved to SD and the connection is immediately opened or closed. **Commands:** | Command | Description | |---------|-------------| | `mqtt.enable` | Enables MQTT in config, saves, calls `MQTTDriver::connect()`. | | `mqtt.disable` | Disables MQTT in config, saves, calls `MQTTDriver::disconnect()`. | --- ## General Notes - **All handlers are registered once** at boot in `CommunicationRouter::registerHandlers()`. Adding a new handler requires only adding a `registerHandler()` call there — the bus registration is automatic via `commands()`. - **SD-writing commands can return partial success.** Several commands return a `CommandResult::err` with a message like `"Updated but failed to save to SD"`. The in-memory state is applied even if the SD save fails. - **`system.factory_reset` does not reboot.** The caller must issue a separate `system.restart` to apply the reset. - **`identify` enforces transport type.** It checks `envelope.transport == CommandEnvelope::Transport::WEBSOCKET` and returns an error for other transports. This is the only handler with transport-specific behaviour. - **`system.restart` uses a deferred task.** `xTaskCreate` spawns a 1 KB task that waits 2 seconds then calls `ESP.restart()`. This ensures the `CommandResult::ok` reply reaches the client before the device reboots.