diff --git a/docs/reference/api-reference.md b/docs/reference/api-reference.md index e16ec88..5dad6b4 100644 --- a/docs/reference/api-reference.md +++ b/docs/reference/api-reference.md @@ -2,7 +2,9 @@ > Command reference for the Vesper Bell Automation System. > Firmware v2 command bus architecture — all transports, all handlers. -> Last updated: 2026-09-21 (MQTT topic spec v2 — see F-062 in feature-catalog.md) +> Last updated: 2026-09-29 (full audit against the handlers' `commands()` lists, field parsing and error strings). +> Companion docs: [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_topic_spec_v2.md) (MQTT topics, `req_id`, LWT) and [mqtt-events.md](mqtt-events.md) (unsolicited MQTT payloads). +> The console's API Reference page (`bellsystems-cp` → `ApiReferencePage.jsx`) mirrors this file — keep both in sync. --- @@ -23,61 +25,90 @@ Every command sent to Vesper uses this JSON envelope: | Field | Type | Notes | |---|---|---| -| `v` | int | Protocol version. `2` = current. Omit or set `1` for legacy (LegacyAdapter runs). | +| `v` | int | Protocol version. `2` = current, `1` = legacy (runs through `LegacyAdapter` first — see [Legacy Compatibility](#legacy-compatibility-v1)). **If omitted, MQTT, WebSocket and UART assume `1`; HTTP assumes `2`.** A v2 command name sent as v1 still works — the adapter leaves names it doesn't recognise unchanged. | | `cmd` | string | `namespace.command` format (e.g. `relay.set_durations`). | -| `req_id` | string | Optional. Echoed back on the reply for correlation when a caller shares one channel across multiple requests/senders (e.g. MQTT `control/command`). Omit for a reply with no `req_id` field — fully backward compatible. | -| `contents` | object | Command payload. May be omitted if command takes no fields. | +| `req_id` | string | Optional. **MQTT only** — echoed back on the `control/ack` reply for correlation. WebSocket, HTTP and UART ignore it (their replies never carry `req_id`). See [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_topic_spec_v2.md#req_id-correlation). | +| `contents` | object | Command payload. May be omitted if the command takes no fields. | ### Response Envelope ```json { - "status": "SUCCESS" | "ERROR", + "status": "SUCCESS" | "ERROR" | "INFO", "type": "command_name", "req_id": "abc123", - "payload": { ... } + "message": "human-readable text", + "data": { ... } } ``` -`payload` is command-specific. On error, `payload` typically contains a `"message"` string. `req_id` is present only if the request included one. +| Field | Present when | Notes | +|---|---|---| +| `status` | always | `SUCCESS` or `ERROR` for command replies. `INFO` is only used for unsolicited broadcasts (see below) — never as a reply to a command. | +| `type` | always | Normally echoes the command name. Exceptions: `ping` → `"pong"`; `playback.play`/`playback.stop` → `"playback"`; unregistered command → `"unknown"`; unparseable MQTT input → `"parse_error"`; WebSocket/HTTP input with no `cmd` → `"bad_request"`. | +| `req_id` | MQTT only, when the request sent one | Echoed unchanged. | +| `message` | text replies and **every** error | A plain string. | +| `data` | structured replies | An object (or array, for `files.list_builtin`). A reply carries `message` or `data`, never both. | + +There is **no `payload` field** in v2 replies. `payload` only appears in (a) replies to *legacy v1* `system.status` requests (translated by `LegacyResponseAdapter` — see [`system.status`](#systemstatus)), and (b) unsolicited WebSocket broadcasts (`status: "INFO"`, e.g. the playback transition event), which keep the pre-v2 shape. Unsolicited MQTT events are published on their own topics with their own shapes — see [mqtt-events.md](mqtt-events.md). + +**Unknown command** (any transport): +```json +{ "status": "ERROR", "type": "unknown", "message": "Unknown command: playback" } +``` + +### Variant availability + +Handlers are only registered when their dependencies exist on the build: + +| Handler | Missing on | Effect | +|---|---|---| +| `SystemHandler` (`ping`, `identify`, `system.*`) | RTC-less builds (`HAS_RTC=0`: agnus, agnus-mini) | `Unknown command` (HTTP `GET /api/ping` still works) | +| `ClockHandler` (`clock.*`) | RTC-less builds | `Unknown command` | +| `RFRemoteHandler` (`rf.*`) | builds without RF (`HAS_RF=0`: bespoke-rs485) | `Unknown command` | +| `FileHandler` (`files.*`) | builds with no FileManager | `Unknown command` | --- ## Transports -MQTT uses the v2 topic set — see [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_topic_spec_v2.md) for the full table, per-topic ON/OFF switches, `req_id` correlation, and LWT. WebSocket, HTTP, and UART are unchanged by the v2 MQTT rebuild. +MQTT uses the v2 topic set — see [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_topic_spec_v2.md) for the full table, per-topic ON/OFF switches, `req_id` correlation, and LWT. | Transport | Address | Direction | Notes | |---|---|---|---| | MQTT | `vesper/{device_id}/control/command` | Inbound commands | Read-only from the board's perspective. Replies go to `control/ack`. | | MQTT | `vesper/{device_id}/control/ack` | Outbound replies | Strictly request/response — nothing unsolicited | | MQTT | `vesper/{device_id}/control/reports` | Outbound, critical unsolicited events | e.g. bell overload — not retained | -| MQTT | `vesper/{device_id}/status/heartbeat` | Outbound, retained, QoS 1 | Heartbeat every 30s + LWT; server updates last_seen | -| MQTT | `vesper/{device_id}/status/playback` | Outbound, retained, QoS 1 | Playback transitions only | -| MQTT | `vesper/{device_id}/system/alerts` | Outbound, retained until cleared, QoS 1 | Subsystem state-change events (published on change only) | -| MQTT | `vesper/{device_id}/system/info` | Outbound, retained, QoS 1 | Discrete device state events (boot report, etc.) | +| MQTT | `vesper/{device_id}/status/heartbeat` | Outbound, retained, QoS 1 | Heartbeat every 30s + LWT | +| MQTT | `vesper/{device_id}/status/playback` | Outbound, retained, QoS 1 | Playback transitions | +| MQTT | `vesper/{device_id}/system/alerts` | Outbound, retained until cleared, QoS 1 | Subsystem state-change events | +| MQTT | `vesper/{device_id}/system/info` | Outbound, retained, QoS 1 | Discrete device events (boot report) | | MQTT | `vesper/{device_id}/system/logs` | Outbound, QoS 0 | Mirrors serial log stream | -| MQTT | `vesper/{device_id}/system/metrics` | Outbound, QoS 0 | Structured telemetry every 5 min — fleet-health graphing | -| WebSocket | `ws://{device_ip}/ws` | Bidirectional | Requires `identify` on connect | -| HTTP | `http://{device_ip}/...` | REST | Web console endpoints | -| UART | Hardware serial | Bidirectional | Restricted — whitelist only (see below) | -| UDP | Port 32101 | Discovery broadcast | Passive — device announces itself | +| MQTT | `vesper/{device_id}/system/metrics` | Outbound, QoS 0 | Structured telemetry every 5 min | +| WebSocket | `ws://{device_ip}/ws` | Bidirectional | Send `identify` on connect | +| HTTP | `POST http://{device_ip}/api/command` | Request/response | Body = command envelope. Also `GET /api/ping`, `GET /api/status` (= `system.status`) | +| UART | Serial2 (GPIO12 TX / GPIO13 RX, 115200) | Bidirectional | LCD/button slave board. Whitelist only (below) | +| UDP | Port 32101 | Discovery | Replies to `discover` probes | + +MQTT drops incoming commands silently (no reply) while free heap is below the publish guard (`MQTTDriver::hasHeapForPublish()`), and any reply is dropped if the `command` topic switch is off. ### UART Whitelist -Only the following commands are accepted over UART (LCD/button slave board). All others are silently dropped. +Only these **raw `cmd` strings** are accepted over UART; everything else is silently dropped. The check runs *before* legacy translation, so the v1 form must be used for playback: ``` ping -playback +playback ← v1 form only: { "cmd": "playback", "contents": { "action": "play" | "stop", ... } } clock.pause clock.resume system.get_time ``` +`playback.play` / `playback.stop` sent over UART by their v2 names are **not** whitelisted and are dropped. UART replies never carry `req_id`. + ### WebSocket — Client Identification -WebSocket clients must send `identify` immediately after connecting, or they will not receive targeted responses: +WebSocket clients should send `identify` immediately after connecting so targeted broadcasts reach them: ```json { "v": 2, "cmd": "identify", "contents": { "device_type": "master" } } @@ -89,794 +120,644 @@ WebSocket clients must send `identify` immediately after connecting, or they wil ## Command Reference +Unless stated otherwise every error reply is `{ "status": "ERROR", "type": "", "message": "" }`. + --- +## Root — `SystemHandler` + ### `ping` | | | |---|---| -| Handler | SystemHandler | -| Transports | All | -| Contents | *(none)* | -| Returns | `{ "status": "SUCCESS", "type": "pong" }` | +| Transports | All (RTC builds only) | +| Contents | `ts` (int, optional) — caller's epoch-ms; echoed back for RTT measurement | +| Returns | `{ "status": "SUCCESS", "type": "pong", "data": { "type": "pong", "ts": 1752600000123, "device_uptime_ms": 184213 } }` (`ts` only if sent) | ```json -{ "v": 2, "cmd": "ping" } +{ "v": 2, "cmd": "ping", "contents": { "ts": 1752600000123 } } ``` ---- - ### `identify` | | | |---|---| -| Handler | SystemHandler | | Transports | WebSocket only | -| Contents | `device_type` (required) | +| Contents | `device_type` (string, required) — `"master"` or `"secondary"` | +| Returns | `{ "status": "SUCCESS", "type": "identify", "message": "Device identified as master" }` | -```json -{ "v": 2, "cmd": "identify", "contents": { "device_type": "master" } } -``` +| Error | Condition | +|---|---| +| `identify is only available via WebSocket` | Sent over MQTT/HTTP/UART | +| `Missing required field: device_type` | `device_type` absent / not a string | +| `Invalid device_type. Use 'master' or 'secondary'` | Any other value | --- -### `playback` +## Playback — `PlaybackHandler` + +The registered commands are **`playback.play`** and **`playback.stop`**. There is no v2 `cmd: "playback"` with an `action` field — see [Bare `playback` command](#bare-playback-command) below. + +Both commands reply with **`type: "playback"`** (not the command name). + +### `playback.play` | | | |---|---| -| Handler | PlaybackHandler | -| Transports | All | -| Contents | `action` (required) + melody fields | +| Transports | MQTT, WebSocket, HTTP (UART: v1 form only) | +| Returns | `{ "status": "SUCCESS", "type": "playback", "message": "Playback command executed" }` | -`action` values: `"play"`, `"stop"`, `"pause"`, `"unpause"` +The SUCCESS reply means the board **accepted** the command, not that bells are ringing. `status/playback` (MQTT) is the source of truth for what the board is actually doing. -```json -{ "v": 2, "cmd": "playback", "contents": { "action": "play", "pid": "ormilia_1_8", "speed": 200, "total_duration": 60000, "note_assignments": [1,2,3,4,5,6,0,0,0,0,0,0,0,0,0,0] } } -{ "v": 2, "cmd": "playback", "contents": { "action": "stop" } } -``` +**Fields are sticky.** Every field except `mode`/`continuous_loop` keeps the value from the *previous* `playback.play` (or its boot default) when omitted — including `pid`, `url`, `speed` and the tail of `note_assignments`. Send every field you care about on every play. | Field | Type | Required | Notes | |---|---|---|---| -| `action` | string | yes | `"play"` or `"stop"` | -| `pid` | string | yes (play) | Playback ID. Checked against built-in library first, then SD card, then downloaded via `download_url`. | -| `download_url` | string | no | URL to download the melody binary if not found locally. | -| `speed` | int | no | ms per beat. Default 500. | -| `total_duration` | int | no | Total playback ms. `0` = play to natural end. | -| `segment_duration` | int | no | Duration per loop segment (ms). Used with `continuous_loop`. | -| `pause_duration` | int | no | Pause between segments (ms). | -| `continuous_loop` | bool | no | Loop with pause/resume segments. | -| `note_assignments` | int[16] | no | Bell mapping (0-indexed note → 1-indexed output, 0 = unused). | +| `pid` | string | yes* | Melody ID. Looked up in the built-in library, then `/melodies/{pid}` on SD, then downloaded from `url`. *If omitted, the previous `pid` is reused; the command fails if that is empty. | +| `uid` | string | no | Alias for `pid`, read only when `pid` is absent. | +| `name` | string | no | Display name. Informational only. | +| `url` | string | no | Download URL, used only when the melody is not built-in and not on SD. **The field is `url` — `download_url` is not read by `playback.play`** (that name belongs to `files.download`). Sticky: a URL from an earlier play is reused if omitted. | +| `speed` | int | no | ms per beat. Boot default 500. `0` is coerced to 300. | +| `note_assignments` | int[] | no | Up to 16 entries. Index = melody note (0-based), value = **1-based bell channel** to ring for that note, `0` = silent. Boot default `[1,2,…,16]`. Entries past 16 are ignored; a shorter array leaves the remaining entries at their previous values. | +| `mode` | string | no | `"single"` \| `"timed"` \| `"interval"` \| `"infinite"`. Unrecognised values behave as `"single"`. Selects the timing model — see below. | +| `duration` | int | no | ms. **Read only when `mode` is present.** | +| `pause_duration` | int | no | ms between segments. Read when `mode` is `"interval"`, or when `mode` is absent. | +| `total_duration` | int | no | ms. Read when `mode` is `"interval"`, or (with `continuous_loop: true`) when `mode` is absent. | +| `segment_duration` | int | no | ms. Legacy — read only when `mode` is absent. | +| `continuous_loop` | bool | no | Legacy — read only when `mode` is absent. Defaults to `false` on every command (not sticky). | + +**How `mode` and `duration` interact** (`mode` present — `segment_duration` and `continuous_loop` are ignored): + +| `mode` | Behaviour | Fields read | +|---|---|---| +| `"single"` | Play the melody once, then stop. | — (`duration` ignored) | +| `"timed"` | Loop the melody; when `duration` ms have elapsed, finish the current loop and stop (status goes `stopping` → `idle`). `duration: 0` behaves like `single`. | `duration` | +| `"interval"` | Play for `duration` ms, pause `pause_duration` ms, repeat; stop after `total_duration` ms overall (`0` = forever). | `duration`, `pause_duration`, `total_duration` | +| `"infinite"` | Loop until `playback.stop`. | — | + +**Legacy timing** (`mode` absent): + +| `continuous_loop` | Behaviour | +|---|---| +| `false` / absent | Run for `segment_duration` ms (sticky, boot default 15000), finish the loop, stop. **`total_duration` is ignored** — it is overwritten with `segment_duration`. `segment_duration: 0` plays the melody once. | +| `true` | Segments of `segment_duration` ms separated by `pause_duration` ms. Stops after `total_duration` ms if given in this command, else after `segment_duration` if that was given, else the previous `total_duration`. Total `0` = forever. | + +| Error | Condition | +|---|---| +| `Playback command failed` | Any rejection: playback already active (playing / paused / stopping — send `playback.stop` first); `pid` empty or `"-"`; melody file on SD could not be loaded; melody not built-in/on SD and no `url` | + +Known gaps in current firmware (addressed separately — see the feature catalog): when a download is needed the reply is SUCCESS and a failed download is only logged; with `bells.disable` in effect the command succeeds and status reports `playing` but no bell rings. + +```json +{ "v": 2, "req_id": "a1", "cmd": "playback.play", "contents": { "pid": "westminster", "speed": 400, "mode": "single" } } +{ "v": 2, "cmd": "playback.play", "contents": { "pid": "ABC123", "url": "https://example.com/ABC123.bin", "mode": "timed", "duration": 120000 } } +{ "v": 2, "cmd": "playback.play", "contents": { "pid": "ABC123", "mode": "interval", "duration": 15000, "pause_duration": 5000, "total_duration": 180000 } } +{ "v": 2, "cmd": "playback.play", "contents": { "pid": "ABC123", "segment_duration": 15000, "pause_duration": 5000, "continuous_loop": true } } +``` + +### `playback.stop` + +| | | +|---|---| +| Transports | MQTT, WebSocket, HTTP (UART: v1 form only) | +| Contents | *(none)* | +| Returns | `{ "status": "SUCCESS", "type": "playback", "message": "Playback command executed" }` | + +Stops immediately (bells are cut mid-loop, status goes straight to `idle`). Sending it while already idle also returns SUCCESS with the same message. + +```json +{ "v": 2, "cmd": "playback.stop" } +``` + +### Bare `playback` command + +| Request | Result | +|---|---| +| `{ "cmd": "playback", "contents": { "action": "play", ... } }` with `v` omitted or `1` | Works — `LegacyAdapter` maps it to `playback.play` (strips `action`) | +| same with `"action": "stop"` | Works — mapped to `playback.stop` | +| `"action": "pause"` / `"unpause"` / anything else | `Unknown command: playback` | +| `{ "v": 2, "cmd": "playback", ... }` | `Unknown command: playback` | +| over HTTP without `v` | `Unknown command: playback` (HTTP defaults to v2) | --- ## Relay Namespace — `RelayHandler` ---- +Bell channels are **0-based** (`"0"`..`"15"`). Relay output numbers in config are **1-based** (1 = first relay, 0 = disabled) — except `relay.test_output`, which takes a raw 0-based chip pin. ### `relay.set_durations` -Set strike duration (ms) for one or more bell channels. Partial updates accepted — omitted channels are unchanged. +Set strike duration (ms) for one or more bell channels. Partial updates accepted. | | | |---|---| -| Required | At least one bell entry | -| Contents | `{ "bells": { "0": 95, "2": 110 } }` | +| Contents | `bells` (object) — `{ "0": 95, "2": 110 }`. v1 flat form (`{ "b1": 95 }` at the top level) also accepted. | +| Returns | `message: "Bell durations updated and saved"` | + +| Error | Condition | +|---|---| +| `Missing or invalid 'bells' object` | `contents` is empty/absent | +| `Durations updated but failed to save to SD` | Applied in RAM, SD write failed | ```json -{ - "v": 2, - "cmd": "relay.set_durations", - "contents": { "bells": { "0": 95, "1": 100, "2": 110 } } -} +{ "v": 2, "cmd": "relay.set_durations", "contents": { "bells": { "0": 95, "1": 100, "2": 110 } } } ``` ---- - ### `relay.set_outputs` -Map bell channels to physical relay outputs. Partial updates accepted. +Map bell channels to relay outputs (1-based, 0 = disabled). Partial updates accepted. Same shape and errors as `relay.set_durations` (`Outputs updated but failed to save to SD`). Returns `message: "Bell outputs updated and saved"`. + +```json +{ "v": 2, "cmd": "relay.set_outputs", "contents": { "bells": { "0": 1, "1": 2, "2": 3 } } } +``` + +### `relay.set_config` + +Durations and/or outputs in one command. | | | |---|---| -| Required | At least one bell entry | -| Contents | `{ "bells": { "0": 2, "1": 3 } }` | +| Contents | `durations` (object, optional), `outputs` (object, optional) — at least one | +| Returns | `message: "Bell configuration updated and saved"` | -```json -{ - "v": 2, - "cmd": "relay.set_outputs", - "contents": { "bells": { "0": 2, "1": 3, "2": 4 } } -} -``` - ---- +| Error | Condition | +|---|---| +| `Provide 'durations' and/or 'outputs' objects` | Neither present | +| `Durations applied but failed to save to SD` | SD write failed | +| `Outputs applied but failed to save to SD` | SD write failed | ### `relay.get_config` -Read current bell durations and output assignments. - | | | |---|---| -| Required | *(none)* | -| Returns | `{ "durations": { "0": 95, ... }, "outputs": { "0": 2, ... } }` | - -```json -{ "v": 2, "cmd": "relay.get_config" } -``` - ---- +| Returns | `data: { "durations": { "0": 95, ... }, "outputs": { "0": 1, ... } }` | ### `relay.test_output` -Fire a specific relay for a caller-specified duration. Safety-gated: Player must be stopped. +Fire a raw chip output for a caller-specified duration. | | | |---|---| -| Required | `output` (int), `duration_ms` (int) | -| Notes | Both fields required — no defaults. Typical range: 85–140 ms. | +| Contents | `output` (int, required, **0-based chip pin 0–31**), `duration_ms` (int, required, 1–5000) | +| Returns | `message: "Output 2 fired for 95 ms"` | -```json -{ - "v": 2, - "cmd": "relay.test_output", - "contents": { "output": 2, "duration_ms": 95 } -} -``` +| Error | Condition | +|---|---| +| `Missing required field: output` | | +| `Missing required field: duration_ms` | | +| `Player must be stopped before testing outputs` | Player not idle | +| `output must be 0-31` | | +| `duration_ms must be 1-5000` | | + +### `relay.test_bell` + +Fire bell channel N on its configured output for its configured duration. Bypasses `bells.disable`. + +| | | +|---|---| +| Contents | `bell` (int, required, 0–15) | +| Returns | `data: { "bell": 0, "output": 1, "duration_ms": 95 }` (`output` 1-based) | + +| Error | Condition | +|---|---| +| `Missing required field: bell (0-based bell index)` | | +| `bell must be 0-15` | | +| `Bell is disabled or unconfigured` | Bell has no output assigned | + +### `relay.test_batch` + +Fire several bell channels at once. Bypasses `bells.disable`. + +| | | +|---|---| +| Contents | `bells` (int[], required) — 0-based channels; out-of-range, non-integer and unconfigured entries are skipped | +| Returns | `data: { "fired": 3 }` | + +| Error | Condition | +|---|---| +| `Missing required field: bells (array of 0-based bell indices)` | | +| `bells array must not be empty` | | +| `No valid bell indices in array` | Nothing was fired | --- -## Clock Namespace — `ClockHandler` +## Clock Namespace — `ClockHandler` (RTC builds only) ---- +Every `set_*` below except `set_time`/`set_face`/`set_timezone` can also fail with `Updated but failed to save to SD` (or the command-specific save message listed). ### `clock.set_outputs` -Set which relay outputs the clock strikes use. - | | | |---|---| -| Required | At least one of `c1`, `c2` | -| Contents | `{ "c1": 4, "c2": 5 }` — partial OK | - ---- +| Contents | `c1` (int), `c2` (int), `pulseDuration` (int), `pauseDuration` (int) — all optional; unknown/missing fields are silently ignored (no "nothing to do" error) | +| Returns | `message: "Clock outputs updated and saved"` | ### `clock.set_timings` -Set clock strike timing configuration. Partial updates accepted. - ---- +| | | +|---|---| +| Contents | `pulse_duration` (int), `pause_duration` (int) — at least one | +| Returns | `message: "Clock timings updated and saved"` | +| Error | `No timing fields provided (pulse_duration, pause_duration)` | ### `clock.set_alerts` -Configure hourly/quarter alert behavior. Partial updates accepted. +**Field names are camelCase** (they go straight to `ConfigManager::updateClockAlerts()`); snake_case names are silently ignored. Use `clock.set_alerts_config` for the snake_case form. ---- +| | | +|---|---| +| Contents | `alertType` (`"OFF"`/`"SINGLE"`/`"HOURS"`), `alertRingInterval` (int), `hourBell`, `halfBell`, `quarterBell` (int, **1-based** bell, 255 = disabled) — all optional | +| Returns | `message: "Clock alerts updated and saved"` | ### `clock.set_backlight` -Configure backlight behavior. Partial updates accepted. - ---- +| | | +|---|---| +| Contents | `backlight` (bool), `backlight_output` (int), `backlight_on` / `backlight_off` (`"HH:MM"`) — all optional | +| Returns | `message: "Clock backlight updated and saved"` | ### `clock.set_silence` -Configure silence period (quiet hours). Partial updates accepted. +**Nested shape** — flat snake_case fields are silently ignored (use `clock.set_alerts_config` for those): ---- +```json +{ "v": 2, "cmd": "clock.set_silence", "contents": { + "daytime": { "enabled": false, "onTime": "12:00", "offTime": "14:00" }, + "nighttime": { "enabled": true, "onTime": "22:00", "offTime": "07:00" } } } +``` + +Returns `message: "Clock silence periods updated and saved"`. + +### `clock.set_config` + +| | | +|---|---| +| Contents | `enabled` (bool), `c1`, `c2` (int, 1-based output, 0 = disabled), `pulse_duration`, `pause_duration` (int) — at least one | +| Returns | `message: "Clock configuration updated and saved"` | + +| Error | Condition | +|---|---| +| `Provide at least one field: enabled, c1, c2, pulse_duration, pause_duration` | | +| `Settings applied but failed to save to SD` | | + +### `clock.set_alerts_config` + +Snake_case alerts + silence in one command. + +| | | +|---|---| +| Contents | `alert_type`, `alert_interval`, `hour_bell`, `half_bell`, `quarter_bell`, `daytime_silence`, `daytime_on`, `daytime_off`, `night_silence`, `night_on`, `night_off` — at least one | +| Returns | `message: "Clock alerts and silence configuration updated and saved"` | + +| Error | Condition | +|---|---| +| `Provide at least one of: alert_type, alert_interval, hour_bell, half_bell, quarter_bell, daytime_silence, daytime_on, daytime_off, night_silence, night_on, night_off` | | +| `Settings applied but failed to save to SD` | | ### `clock.set_time` -Set the RTC time. - | | | |---|---| -| Required | `timestamp` (Unix epoch, int) | -| Optional | `timezone_offset` (int, seconds), `dst_offset` (int, seconds) | +| Contents | `timestamp` (int, required, Unix epoch UTC), `timezone_offset` + `dst_offset` (int, seconds) | +| Returns | `message: "RTC time updated successfully"` | + +`timezone_offset` (total UTC offset incl. DST) and `dst_offset` are **only applied when both are present** — they also update the stored timezone. With only one (or neither), `timestamp` is written to the RTC as-is. + +| Error | Condition | +|---|---| +| `Missing required field: timestamp` | | +| `Invalid timestamp value` | `timestamp` is 0 | +| `RTC time set but verification failed` | RTC read-back returned 0 | ```json -{ - "v": 2, - "cmd": "clock.set_time", - "contents": { "timestamp": 1740000000, "timezone_offset": 7200 } -} +{ "v": 2, "cmd": "clock.set_time", "contents": { "timestamp": 1740000000, "timezone_offset": 10800, "dst_offset": 3600 } } ``` ---- - ### `clock.set_face` -Set the physical analog clock face position. - | | | |---|---| -| Required | `hour` (int), `minute` (int) | +| Contents | `hour` (0–23), `minute` (0–59) — both required | +| Returns | `message: "Physical clock face updated and saved"` | -```json -{ "v": 2, "cmd": "clock.set_face", "contents": { "hour": 10, "minute": 10 } } -``` - ---- +Errors: `Missing required fields: hour, minute`, `hour must be 0-23`, `minute must be 0-59`, `Face set but failed to save to SD`. ### `clock.set_timezone` -Set timezone independently of RTC time. - | | | |---|---| -| Required | `gmt_offset_sec` (int) | -| Optional | `dst_offset_sec` (int), `timezone_name` (string) | +| Contents | `gmt_offset_sec` (int, required), `dst_offset_sec` (int, optional, default 0) | +| Returns | `message: "Timezone updated and saved"` | -```json -{ - "v": 2, - "cmd": "clock.set_timezone", - "contents": { "gmt_offset_sec": 7200, "dst_offset_sec": 3600, "timezone_name": "Europe/Athens" } -} -``` - ---- +Errors: `Missing required field: gmt_offset_sec`, `Timezone updated but failed to save to SD`. ### `clock.get_timezone` -Read current timezone settings. - -| | | -|---|---| -| Returns | `{ "gmt_offset_sec": 7200, "dst_offset_sec": 3600, "timezone_name": "..." }` | - ---- +Returns `data: { "gmt_offset_sec": 7200, "dst_offset_sec": 3600, "ntp_server": "pool.ntp.org" }`. ### `clock.sync_ntp` -Force an immediate NTP time sync. - -| | | -|---|---| -| Required | *(none)* | - ---- +Runs an NTP sync (blocking up to ~5 s). Returns `message: "NTP sync initiated"` regardless of outcome. ### `clock.enable` / `clock.disable` -Enable or disable clock strike output. - -```json -{ "v": 2, "cmd": "clock.enable" } -{ "v": 2, "cmd": "clock.disable" } -``` - ---- +Returns `message: "Clock enabled and saved"` / `"Clock disabled and saved"`. Errors: `Enabled but failed to save to SD` / `Disabled but failed to save to SD`. ### `clock.pause` / `clock.resume` -Pause or resume clock updates. - -```json -{ "v": 2, "cmd": "clock.pause" } -{ "v": 2, "cmd": "clock.resume" } -``` - ---- +Returns `message: "Clock updates paused"` / `"Clock updates resumed"`. ### `clock.get_face` -Read current analog clock face position. - -| | | -|---|---| -| Returns | `{ "clock_hour", "clock_minute", "last_sync_time", "next_output_is_c1" }` | - ---- +Returns `data: { "clock_hour", "clock_minute", "last_sync_time", "next_output_is_c1" }`. ### `clock.get_config` -Read full clock configuration (outputs, timings, alerts, backlight, silence, enabled state). +Returns `data: { "enabled", "c1output", "c2output", "pulse_duration", "pause_duration", "physical_hour", "physical_minute", "next_is_c1", "last_sync_time", "alert_type", "alert_interval", "hour_bell", "half_bell", "quarter_bell", "backlight", "backlight_output", "backlight_on", "backlight_off", "daytime_silence", "daytime_on", "daytime_off", "night_silence", "night_on", "night_off", "gmt_offset_sec", "dst_offset_sec", "ntp_server" }` (bells 1-based, 255 = disabled). + +### `clock.test_c1` / `clock.test_c2` + +Fire C1/C2 for the configured pulse. Returns `data: { "output": "C1", "duration_ms": 100 }`. Error: `OutputManager not available`. --- -## System Namespace — `SystemHandler` - ---- +## System Namespace — `SystemHandler` (RTC builds only) ### `system.status` -Get current device status: player state, strike counters, projected run time. +Returns `data: { "player_status": "PLAYING"|"PAUSED"|"STOPPING"|"STOPPED", "time_elapsed_ms", "projected_run_time", "strike_counters": { "0": 1234, ... } }`. -```json -{ "v": 2, "cmd": "system.status" } -``` - ---- +A **v1** request (no `v`, or `v:1`) gets the reply translated by `LegacyResponseAdapter`: `type: "current_status"`, fields under `payload` (not `data`), lowercase `player_status` (`playing`/`paused`/`stopping`/`idle`), `time_elapsed` (ms), `strike_counters` as an array. ### `system.get_time` -Get current RTC time. +Returns `data: { "local_timestamp", "utc_timestamp", "rtc_available", "year", "month", "day", "hour", "minute", "second" }`. -| | | -|---|---| -| Returns | `{ "local_timestamp", "utc_timestamp", "year", "month", "day", "hour", "minute", "second", "rtc_available" }` | +### `system.get_config` (alias `system.get_settings`) -```json -{ "v": 2, "cmd": "system.get_time" } -``` +Full ConfigManager dump plus `general: { bells_enabled, mqtt_enabled, ota_channel, serial_log, sd_log, mqtt_log }`. Error: `Failed to serialize settings`. ---- +### `system.get_all` -### `system.get_settings` +Returns `data: { "device": { serial, hw_family, hw_revision, fw_version, uptime_ms, free_heap }, "config": {...}, "telemetry": {...}, "player": { "status": "PLAYING"|"PAUSED"|"STOPPING"|"STOPPED" } }`. -Get full ConfigManager JSON dump (all saved settings). +### `system.get_telemetry` -```json -{ "v": 2, "cmd": "system.get_settings" } -``` - ---- +Returns `data: { strikes, loads, max_loads, cooling_active, guard_enabled, lifetime_runtime_seconds, session_runtime_seconds, total_playbacks, lifetime_boot_count, uptime_ms, free_heap }`. ### `system.get_device_info` -Get device identity and runtime stats. - -| | | -|---|---| -| Returns | `{ "uid", "hw_type", "hw_version", "fw_version", "uptime_ms", "free_heap", "min_free_heap" }` | - -```json -{ "v": 2, "cmd": "system.get_device_info" } -``` - ---- +Returns `data: { "uid", "hw_type", "hw_version", "fw_version", "uptime_ms", "free_heap", "min_free_heap" }`. ### `system.health` -Get full HealthMonitor report — all subsystem states, warnings, critical failures. - -```json -{ "v": 2, "cmd": "system.health" } -``` - ---- +Returns `data: { "critical_count", "warning_count", "firmware_stable", "subsystems": [ { "name", "status": "HEALTHY"|"WARNING"|"CRITICAL"|"FAILED", "error"? } ] }`. ### `system.factory_reset` -Reset all settings to factory defaults. +> **Warning:** Non-reversible. All saved configuration is wiped. Restart to apply. -> **Warning:** Non-reversible. All saved configuration is wiped. - -```json -{ "v": 2, "cmd": "system.factory_reset" } -``` - ---- +Returns `message: "Factory reset complete. Restart device to apply."`. Error: `Factory reset partially applied — some settings may not have saved`. ### `system.restart` -Reboot the device. Response is sent before reboot (2s delay). - -```json -{ "v": 2, "cmd": "system.restart" } -``` - ---- +Returns `message: "Device will restart in 2 seconds"`, then reboots. ### `system.set_identity` -Overwrite the device's factory-set identity (`serial`, `hw_family`, `hw_revision`) in NVS and reboot to apply it. Intended for sysadmin use only — e.g. reassigning a serial after a board swap, or correcting a mis-provisioned unit — via the backend console, which is responsible for updating its own device record (including re-deriving the MQTT password from the new serial) in the same operation. Firmware does not touch the backend record itself. +Overwrite the device's factory-set identity (`serial`, `hw_family`, `hw_revision`) in NVS and reboot to apply it. Sysadmin use only, via the backend console, which must update its own device record (including re-deriving the MQTT password from the new serial) in the same operation. -> **Warning:** Non-reversible from the device's perspective, and dangerous if the backend device record isn't updated to match — a serial mismatch will break MQTT auth (password is derived from serial), and a wrong `hw_family`/`hw_revision` can pull an OTA build for the wrong hardware. Device restarts 2s after a successful response to apply the new identity. +> **Warning:** A serial mismatch with the backend record breaks MQTT auth; a wrong `hw_family`/`hw_revision` can pull the wrong OTA build. Restarts 2 s after a successful reply. | | | |---|---| -| Handler | SystemHandler | | Transports | MQTT only | -| Contents | `serial` (required), `hw_family` (required), `hw_revision` (required) | +| Contents | `serial`, `hw_family`, `hw_revision` (all required strings) | +| Returns | `message: "Device identity updated. Restarting in 2 seconds to apply."` | -```json -{ "v": 2, "cmd": "system.set_identity", "contents": { "serial": "PV000000000001", "hw_family": "VS", "hw_revision": "01" } } -``` - -**Errors:** - -| Message | Condition | +| Error | Condition | |---|---| | `system.set_identity is only available via MQTT` | Sent over WebSocket, HTTP, or UART | -| `Missing required fields: serial, hw_family, hw_revision (all required)` | One or more fields absent or not a string | -| `serial, hw_family and hw_revision must be non-empty` | One or more fields present but empty | -| `Failed to persist new identity to NVS — device identity unchanged` | NVS write/commit failed | +| `Missing required fields: serial, hw_family, hw_revision (all required)` | Any field absent or not a string | +| `serial, hw_family and hw_revision must be non-empty` | Any field empty | +| `Failed to persist new identity to NVS — device identity unchanged` | NVS write failed | --- ## Firmware Namespace — `FirmwareHandler` ---- - ### `firmware.status` -Get firmware validation state. - -| | | -|---|---| -| Returns | `{ "validation_state", "current_version", "is_testing", "is_valid", "boot_count", "build_date", "ota_channel", "startup_retry_count", "max_startup_retries", "runtime_failure_count", "max_runtime_failures", "backup_version", "backup_is_valid", "can_commit", "can_rollback", "runtime_timeout_ms"? }` | - -`startup_retry_count`, `runtime_failure_count`, and the backup partition fields are the OTA rollback safety-net's internal counters — previously only visible via serial/SD log output, now queryable remotely. Useful for diagnosing why a device rolled back an update. `runtime_timeout_ms` is only present while `is_testing` is true. - -```json -{ "v": 2, "cmd": "firmware.status" } -``` - ---- +Returns `data: { "validation_state", "current_version", "is_testing", "is_valid", "boot_count", "build_date", "ota_channel", "startup_retry_count", "max_startup_retries", "runtime_failure_count", "max_runtime_failures", "backup_version", "backup_is_valid", "can_commit", "can_rollback", "runtime_timeout_ms"? }` (`runtime_timeout_ms` only while testing). ### `firmware.commit` -Commit the current firmware as permanent (marks OTA slot as valid). - -```json -{ "v": 2, "cmd": "firmware.commit" } -``` - ---- +Returns `message: "Firmware committed successfully"`. Errors: `No firmware validation in progress`, `Failed to commit firmware`. ### `firmware.rollback` -Roll back to the previous firmware. Device reboots. +> **Warning:** Device reboots. -```json -{ "v": 2, "cmd": "firmware.rollback" } -``` +Returns `message: "Firmware rollback initiated — device will reboot"`. Error: `Failed to initiate firmware rollback`. --- ## OTA Namespace — `FirmwareHandler` ---- - -### `ota.status` - -Get OTA update status. - -| | | -|---|---| -| Returns | `{ "current_version", "available_version", "channel", "update_available", "last_check", "progress" }` | - -```json -{ "v": 2, "cmd": "ota.status" } -``` - ---- - -### `ota.check` - -Check for available updates. - -| | | -|---|---| -| Optional | `channel` (string, default `"stable"`) | - -```json -{ "v": 2, "cmd": "ota.check", "contents": { "channel": "beta" } } -``` - ---- +There are no `ota.status` / `ota.check` commands — OTA state is in `firmware.status`, `telemetry.get_diagnostics` and `system/metrics`. ### `ota.update` -Trigger OTA update from VPS. Device may reboot. +> **Warning:** Device reboots after flashing. | | | |---|---| -| Optional | `channel` (string, default `"stable"`) | - -```json -{ "v": 2, "cmd": "ota.update", "contents": { "channel": "stable" } } -``` - ---- +| Contents | `channel` (string, optional) — **defaults to `"stable"` when omitted** (not the channel saved with `ota.set_channel`) | +| Returns | `message: "OTA update started from channel: stable"` | +| Error | `Cannot update while playback is active` (only checked while `PLAYING`) | ### `ota.custom` -Flash firmware from a custom URL. +> **Warning:** Device reboots after flashing. | | | |---|---| -| Required | `firmware_url` (string) | -| Optional | `checksum` (string), `file_size` (int), `version` (string) | +| Contents | `firmware_url` (string, required), `checksum` (string), `file_size` (int), `version` (string) | +| Returns | `message: "Custom OTA update started"` | -```json -{ - "v": 2, - "cmd": "ota.custom", - "contents": { - "firmware_url": "http://example.com/firmware.bin", - "checksum": "abc123", - "version": "142" - } -} -``` +Errors: `Missing required field: firmware_url`, `Cannot update while playback is active`. + +### `ota.set_channel` + +Persists the OTA channel used by the scheduled update check. + +| | | +|---|---| +| Contents | `channel` (string, required) — `stable` / `beta` / `development` | +| Returns | `data: { "channel": "beta" }` | + +Errors: `Missing required field: channel`, `Invalid channel. Valid values: stable, beta, development`. --- ## Network Namespace — `NetworkHandler` ---- - ### `network.info` -Get IP/gateway/DNS. - -| | | -|---|---| -| Returns | `{ "ip", "gateway", "dns" }` | - -```json -{ "v": 2, "cmd": "network.info" } -``` - ---- +Returns `data: { "ip", "subnet", "gateway", "dns", "mac", "hostname", "ssid", "connection_type": "WIFI"|"ETHERNET"|"AP" }`. ### `network.status` -Get full connection state. - -| | | -|---|---| -| Returns | `{ "connected", "state", "type", "ip", "rssi", "ap_mode" }` | - -```json -{ "v": 2, "cmd": "network.status" } -``` - ---- +Returns `data: { "connected", "ap_mode", "rssi", "uptime_ms", "state" }`. ### `network.set_config` -Update network configuration. Partial updates accepted. Returns `restart_required` flag. +Partial update; restart required to apply. | | | |---|---| -| Required | At least one field | -| Optional | `hostname`, `useStaticIP`, `ip`, `gateway`, `subnet`, `dns1`, `dns2` | -| Notes | Static IP requires `ip` + `gateway` + `subnet` together | +| Contents | `hostname` (string), `useStaticIP` (bool), `ip`, `gateway`, `subnet`, `dns1`, `dns2` (strings), `permanent_ap_mode` (bool) | +| Returns | `message: "Network configuration saved. Restart device to apply changes."` — or, when `permanent_ap_mode` is sent (all other fields are then ignored), `"AP mode saved. Restart to apply."` / `"Station mode saved. Restart to apply."` | -```json -{ - "v": 2, - "cmd": "network.set_config", - "contents": { "hostname": "vesper-lab", "useStaticIP": false } -} -``` +| Error | Condition | +|---|---| +| `No network parameters provided` | None of `hostname`, `useStaticIP`, `permanent_ap_mode` present | +| `Hostname must be 1-32 characters` | | +| `Static IP requires: ip, gateway, subnet` | `useStaticIP: true` without all three | +| `Invalid IP address format` / `Invalid gateway format` / `Invalid subnet format` | | --- ## Files Namespace — `FileHandler` ---- - ### `files.list` -List melody files on the SD card. - -| | | -|---|---| -| Returns | Array of SD card melody file objects | - -```json -{ "v": 2, "cmd": "files.list" } -``` - ---- +Returns `data: { "files": [ ... ] }` — melody files in `/melodies` on SD. Error: `Failed to read melody list`. ### `files.list_builtin` -List all built-in melodies compiled into the firmware. - -| | | -|---|---| -| Returns | `[{ "name": "...", "pid": "..." }, ...]` | - -```json -{ "v": 2, "cmd": "files.list_builtin" } -``` - ---- +Returns `data: [ { "name": "...", "pid": "..." }, ... ]` (an array). Error: `Failed to read built-in melody list`. ### `files.download` -Download a melody from the server to the SD card. +Download a melody to `/melodies/{melodys_uid}` on SD. Built-in melodies are skipped (reported as success). | | | |---|---| -| Required | `melodys_uid` (string) | +| Contents | `download_url` (string, required), `melodys_uid` (string, required) | +| Returns | `message: "Melody downloaded: "` | +| Error | `Failed to download melody: ` — either field missing, HTTP/SD failure | ```json -{ "v": 2, "cmd": "files.download", "contents": { "melodys_uid": "ABC123" } } +{ "v": 2, "cmd": "files.download", "contents": { "melodys_uid": "ABC123", "download_url": "https://example.com/ABC123.bin" } } ``` ---- - ### `files.delete` -Delete a melody from the SD card. - | | | |---|---| -| Required | `name` (string) | +| Contents | `name` (string, required) | +| Returns | `message: "Melody deleted: "` | -```json -{ "v": 2, "cmd": "files.delete", "contents": { "name": "westminster.mel" } } -``` +Errors: `Missing required field: name`, `Failed to delete melody: `. --- ## Log Namespace — `LoggingHandler` -Set log verbosity per output channel. Level 0 = off, 5 = verbose. +Level 0 = none, 1 = error, 2 = warning, 3 = info, 4 = debug, 5 = verbose. -| Level | Meaning | +### `log.set_serial` / `log.set_sd` / `log.set_mqtt` + +| | | |---|---| -| 0 | None | -| 1 | Error | -| 2 | Warning | -| 3 | Info | -| 4 | Debug | -| 5 | Verbose | +| Contents | `level` (int 0–5, required) | +| Returns | `message: "serial log level set to 3 and saved"` (channel name varies) | -### `log.set_serial` +Errors: `Missing or invalid 'level' (0-5 required)`, `Invalid log level (must be 0-5)`, `Level applied but failed to save to SD`. -```json -{ "v": 2, "cmd": "log.set_serial", "contents": { "level": 0 } } -``` +### `log.get_config` -### `log.set_sd` - -```json -{ "v": 2, "cmd": "log.set_sd", "contents": { "level": 0 } } -``` - -### `log.set_mqtt` - -```json -{ "v": 2, "cmd": "log.set_mqtt", "contents": { "level": 0 } } -``` - ---- +Returns `data: { "serial_level", "sd_level", "mqtt_level" }`. ### `logs.list` -List day-rotated SD log files (`/logs/YYYY-MM-DD.log`). Requires an SD card — returns an error on boards without one. - -| | | -|---|---| -| Returns | `{ "files": [{ "name": "2026-07-14.log", "size": 1234 }, ...] }` | - -```json -{ "v": 2, "cmd": "logs.list" } -``` - ---- +Day-rotated SD log files. Returns `data: { "files": [ { "name": "2026-07-14.log", "size": 1234 } ] }`. +Errors: `SD card not available on this device`, `Failed to read log directory`. ### `logs.download` -Read a bounded chunk of a log file. Responses are capped at 4096 bytes regardless of file size — callers loop, feeding `next_offset` back in as `offset`, until `eof` is `true`. Requires an SD card. +Read ≤4096 bytes of a log file; loop with `next_offset` until `eof`. | | | |---|---| -| Required | `file` (string) — bare filename as returned by `logs.list`, no path separators | -| Optional | `offset` (int, default `0`) | -| Returns | `{ "file", "data", "next_offset", "eof" }` | +| Contents | `file` (string, required, bare filename), `offset` (int, default 0) | +| Returns | `data: { "file", "data", "next_offset", "eof" }` | -```json -{ "v": 2, "cmd": "logs.download", "contents": { "file": "2026-07-14.log", "offset": 0 } } -``` +Errors: `SD card not available on this device`, `Missing required field: file`, `Log file not found: `. -Loop example: keep calling with `contents.offset = ` until the response has `"eof": true`. +### `logs.clear` + +> **Warning:** Deletes all SD debug log files. + +Returns `data: { "deleted": 4 }`. Error: `SD card not available on this device`. --- -## RF Remote Namespace — `RFRemoteHandler` +## RF Remote Namespace — `RFRemoteHandler` (HAS_RF builds only) -> Available on hardware variants with `HAS_RF=1` (e.g. Vesper, Vesper+). -> All commands are silently rejected on variants without RF hardware. - -The RF subsystem uses a **slot model**: up to 16 independent slots, each binding one RF trigger code to a complete playback action. Slots are blank by default — nothing is pre-seeded. Program them over MQTT after flashing. +Up to 16 slots, each binding one 433 MHz code to a playback action. Slots are blank by default. Stored in NVS namespace `rf`. ### Slot object | Field | Type | Required | Notes | |---|---|---|---| -| `slot` | int | yes | Slot index, 0–15 | -| `rf_code` | uint32 | yes | Raw 433 MHz code that triggers this slot. Must be non-zero. | -| `pid` | string | yes (play) | Playback ID. Checked against built-in library first, then SD card. Use `files.list_builtin` or `files.list` for valid PIDs. | -| `speed` | int | no | ms per beat. Default 500. | -| `duration` | int | no | Total playback ms. Default 30000. `0` = play to natural end. | -| `note_assignments` | int[16] | no | Bell mapping array (0-indexed note → 1-indexed bell output, 0 = unused). Default all zeros. | -| `is_stop` | bool | no | If `true`, receiving this code calls force-stop (single press, no long-press required). `pid`/`speed`/`duration` ignored. Default `false`. | - -**`note_assignments` example:** A melody written for 6 bells played on 3 physical bells, doubled: -```json -"note_assignments": [1, 2, 3, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -``` - ---- +| `slot` | int | yes | 0–15 | +| `rf_code` | uint32 | yes | Must be non-zero | +| `is_stop` | bool | no | Default `false`. If `true`, the code force-stops playback; the fields below are ignored. | +| `pid` | string | yes (play) | Built-in or SD melody ID | +| `speed` | int | yes (play) | ms per beat, non-zero | +| `duration` | int | yes (play) | ms, non-zero. The slot plays like legacy `segment_duration`: loop for `duration` ms, finish the loop, stop. | +| `note_assignments` | int[16] | yes (play) | Exactly 16 entries, at least one non-zero. Index = note, value = 1-based bell, 0 = silent. | ### `rf.set_slot` -Program one slot, or multiple slots in a single command. +Single slot (fields at top level) or batch (`{ "slots": [ ... ] }`). | | | |---|---| -| Handler | RFRemoteHandler | -| Transports | All | -| Persists | NVS namespace `rf` (survives reboot) | +| Returns | `message: "Slot 0 programmed"` or `"3 slot(s) programmed"` | + +| Error (single form) | Condition | +|---|---| +| `missing 'slot'` | | +| `'slot' out of range (got , must be 0–15)` | | +| `slot : missing or zero 'rf_code'` | | +| `slot : play slot missing 'pid'` | | +| `slot : play slot missing 'speed'` / `slot : 'speed' must be non-zero` | | +| `slot : play slot missing 'duration'` / `slot : 'duration' must be non-zero` | | +| `slot : play slot missing 'note_assignments'` | | +| `slot : 'note_assignments' must have exactly 16 elements (got )` | | +| `slot : 'note_assignments' are all zero — no bells would ring` | | + +Batch form wraps the same reason: `Slot entry invalid — . No slots were saved.` — **note:** entries *before* the invalid one have in fact already been saved despite the wording. -**Single slot:** ```json -{ - "v": 2, - "cmd": "rf.set_slot", - "contents": { - "slot": 0, - "rf_code": 9274392, - "pid": "vesper_fst_1_4", - "speed": 500, - "duration": 60000, - "note_assignments": [1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - "is_stop": false - } -} +{ "v": 2, "cmd": "rf.set_slot", "contents": { "slot": 0, "rf_code": 9274392, "pid": "vesper_fst_1_4", "speed": 500, "duration": 60000, "note_assignments": [1,2,3,4,5,6,0,0,0,0,0,0,0,0,0,0] } } +{ "v": 2, "cmd": "rf.set_slot", "contents": { "slots": [ { "slot": 7, "rf_code": 9274385, "is_stop": true } ] } } ``` -**Multiple slots (batch):** -```json -{ - "v": 2, - "cmd": "rf.set_slot", - "contents": { - "slots": [ - { "slot": 0, "rf_code": 9274392, "pid": "vesper_fst_1_4", "speed": 500, "duration": 60000, "note_assignments": [1,2,3,4,5,6,0,0,0,0,0,0,0,0,0,0] }, - { "slot": 1, "rf_code": 9274388, "pid": "doxology_1_4", "speed": 500, "duration": 60000 }, - { "slot": 7, "rf_code": 9274385, "is_stop": true } - ] - } -} -``` - -Returns: -```json -{ "status": "SUCCESS", "type": "rf.set_slot", "payload": "3 slot(s) programmed" } -``` - ---- - ### `rf.clear_slot` -Clear a single slot, or all slots. - | | | |---|---| -| Required | `slot` — int (0–15) or string `"all"` | +| Contents | `slot` — int 0–15 or `"all"` | +| Returns | `message: "Slot 3 cleared"` / `"All slots cleared"` | -```json -{ "v": 2, "cmd": "rf.clear_slot", "contents": { "slot": 3 } } -{ "v": 2, "cmd": "rf.clear_slot", "contents": { "slot": "all" } } -``` - ---- +Errors: `Invalid value for 'slot' — use a slot index (0–15) or "all"`, `Required: 'slot' — slot index (0–15) or "all"`, `Invalid slot index — must be 0–15`. ### `rf.get_slots` -Return the full slot table (all 16 slots). - -| | | -|---|---| -| Contents | *(none)* | -| Returns | `{ "enabled": bool, "slots": [ { slot object } × 16 ] }` | - -Each entry includes an `"empty": true/false` field. Empty slots have `rf_code: 0` and all other fields at their defaults. - -```json -{ "v": 2, "cmd": "rf.get_slots" } -``` - -Example response excerpt: ```json { "status": "SUCCESS", @@ -884,37 +765,21 @@ Example response excerpt: "data": { "enabled": true, "slots": [ - { - "slot": 0, - "empty": false, - "rf_code": 9274392, - "pid": "vesper_fst_1_4", - "speed": 500, - "duration": 60000, - "is_stop": false, - "note_assignments": [1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] - }, - { "slot": 1, "empty": true, "rf_code": 0, ... }, - ... + { "slot": 0, "empty": false, "rf_code": 9274392, "pid": "vesper_fst_1_4", "speed": 500, "duration": 60000, "is_stop": false, + "note_assignments": [1,2,3,4,5,6,0,0,0,0,0,0,0,0,0,0] }, + { "slot": 1, "empty": true, "rf_code": 0, "pid": "", "speed": 0, "duration": 0, "is_stop": false, "note_assignments": [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] } ] } } ``` ---- - ### `rf.enable` -Enable or disable RF reception at runtime. - | | | |---|---| -| Required | `enabled` (bool) | - -```json -{ "v": 2, "cmd": "rf.enable", "contents": { "enabled": true } } -{ "v": 2, "cmd": "rf.enable", "contents": { "enabled": false } } -``` +| Contents | `enabled` (bool, required) | +| Returns | `message: "RF remote enabled"` / `"RF remote disabled"` | +| Error | `Required: 'enabled' (bool)` | --- @@ -922,106 +787,61 @@ Enable or disable RF reception at runtime. ### `mqtt.enable` / `mqtt.disable` -Enable or disable MQTT connectivity (master switch — disconnects/reconnects the broker entirely). `mqtt.disable` publishes a graceful offline heartbeat before disconnecting. - -```json -{ "v": 2, "cmd": "mqtt.enable" } -{ "v": 2, "cmd": "mqtt.disable" } -``` +Master switch. `mqtt.enable` connects; `mqtt.disable` publishes the offline heartbeat, then disconnects. +Returns `message: "MQTT enabled and saved"` / `"MQTT disabled and saved"`. Error: `MQTT state changed but failed to save to SD`. ### `mqtt.get_config` -Returns broker connection settings. - -| | | -|---|---| -| Returns | `{ "enabled": true, "host": "72.61.191.197", "port": 1883, "user": "...", "use_ssl": false }` | - -```json -{ "v": 2, "cmd": "mqtt.get_config" } -``` +Returns `data: { "enabled", "host", "port", "user", "use_ssl" }` (never the password). ### `mqtt.get_topics` -Returns the current state of all 8 per-topic ON/OFF publish switches. See [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_topic_spec_v2.md#per-topic-onoff-switches). - -| | | -|---|---| -| Returns | `{ "command": true, "heartbeat": true, "playback": true, "reports": true, "alerts": true, "info": true, "logs": true, "metrics": true }` | - -```json -{ "v": 2, "cmd": "mqtt.get_topics" } -``` +Returns `data: { "command", "heartbeat", "playback", "reports", "alerts", "info", "logs", "metrics" }` (bools). ### `mqtt.set_topics` -Partial update of the per-topic ON/OFF switches — only send the fields you want to change. These only take effect while `mqtt.enable` (the master switch) is on. `command` gates both `control/command` (subscription) and `control/ack` (replies) together, and applies live without a reconnect. - -| | | -|---|---| -| Optional | Any of `command`, `heartbeat`, `playback`, `reports`, `alerts`, `info`, `logs`, `metrics` (bool) — at least one required | - -```json -{ "v": 2, "cmd": "mqtt.set_topics", "contents": { "heartbeat": true, "metrics": false } } -``` +Partial update — any of the 8 switch names as bools, at least one. +Returns `message: "MQTT topic switches updated and saved"`. | Error | Condition | |---|---| -| `"No recognised topic fields in contents (command, heartbeat, playback, reports, alerts, info, logs, metrics)"` | No valid boolean fields present | -| `"Topic switches changed but failed to save to SD"` | Applied in RAM but persistence failed | +| `No recognised topic fields in contents (command, heartbeat, playback, reports, alerts, info, logs, metrics)` | | +| `Topic switches changed but failed to save to SD` | | --- ## Telemetry Namespace — `TelemetryHandler` ---- - -### `telemetry.get_strikes` - -Get strike counts per bell channel. - -| | | -|---|---| -| Returns | `{ "strikes": { "0": 1234, "1": 567, ... } }` | - -```json -{ "v": 2, "cmd": "telemetry.get_strikes" } -``` +| Command | Contents | Returns | Errors | +|---|---|---|---| +| `telemetry.get_strikes` | — | `data: { "strikes": { "0": 1234, ... } }` | — | +| `telemetry.reset_strikes` | `bell` (ignored — always resets all) | `message: "All strike counts reset"` | — | +| `telemetry.get_loads` | — | `data: { "loads", "max_loads", "cooling_active", "guard_enabled", "overloaded": [0-based channels] }` | — | +| `telemetry.set_max_loads` | `all` (int > 0) **or** `loads` (`{ "0": 300 }`; zero/out-of-range entries skipped) | `message: "All bell max loads updated"` / `"Bell max loads updated"` | `max_load must be > 0`, `Provide 'all' (uint16) or 'loads' (object)` | +| `telemetry.set_guard_enabled` | `enabled` (bool, required) | `message: "Bell guard enabled"` / `"... disabled"` | `Missing required field: enabled (bool)` | +| `telemetry.get_metrics` | — | `data: { lifetime_runtime_seconds, session_runtime_seconds, total_playbacks, guard_enabled, lifetime_boot_count }` | — | +| `telemetry.reset_metrics` | — | `message: "Lifetime runtime and playback count reset to zero"` | — | +| `telemetry.get_boot_history` | `limit` (int, optional; clamped to 1–200, `0` → 1, omitted → 200) | `data: { "count", "boots": [...] }` | `No boot history available (no SD card, or no boot has completed NTP sync yet)` | +| `telemetry.get_diagnostics` | — | `data: { cpu_temp?, wifi_reconnects, ota, stack_high_water }` (non-consuming peek of the `system/metrics` report) | — | +| `telemetry.reset_boot_data` | — | `message: "Lifetime boot count and SD boot log reset"` | `Failed to reset lifetime boot count in NVS` | --- -### `telemetry.reset_strikes` +## Bells Namespace — `BellsHandler` -Reset strike counters. Omit `bell` to reset all channels; include it to reset one. +Master switch for the bell mechanism (BellEngine playback and clock alerts). `relay.test_*` bypass it. -| | | -|---|---| -| Optional | `bell` (int) — channel index | - -```json -{ "v": 2, "cmd": "telemetry.reset_strikes" } -{ "v": 2, "cmd": "telemetry.reset_strikes", "contents": { "bell": 2 } } -``` - ---- - -### `telemetry.get_loads` - -Get heat load per bell channel, cooling status, and overload flags. - -| | | -|---|---| -| Returns | `{ "loads": { "0": 42.5, ... }, "cooling_active": false, "overloaded": [2, 5] }` | - -```json -{ "v": 2, "cmd": "telemetry.get_loads" } -``` +| Command | Returns | Error | +|---|---|---| +| `bells.enable` | `message: "Bell mechanism enabled and saved"` | `Bell mechanism enabled but failed to save to SD` | +| `bells.disable` | `message: "Bell mechanism disabled and saved"` | `Bell mechanism disabled but failed to save to SD` | +| `bells.get_config` | `data: { "bells_enabled", "durations", "outputs" }` | — | --- ## MQTT Events (Unsolicited) -These messages are published by the device without a request, on the v2 topic set (`control/command`+`control/ack`, `control/reports`, `status/heartbeat`, `status/playback`, `system/alerts`, `system/info`, `system/logs`, `system/metrics`). Full field-level reference, per-topic switches, LWT, and `req_id` correlation: [mqtt-events.md](mqtt-events.md) and [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_topic_spec_v2.md). +Published without a request, on the v2 topic set. Full field-level reference: [mqtt-events.md](mqtt-events.md). | Topic | When | QoS | Retained | Switch | |---|---|---|---|---| @@ -1029,22 +849,24 @@ These messages are published by the device without a request, on the v2 topic se | `vesper/{id}/status/playback` | On playback transition | 1 | yes | `playback` | | `vesper/{id}/control/reports` | Critical unsolicited events (e.g. bell overload) | 1 | no | `reports` | | `vesper/{id}/system/alerts` | On subsystem state change only | 1 | yes, until cleared | `alerts` | -| `vesper/{id}/system/info` | On discrete device state events (e.g. boot report) | 1 | yes | `info` | +| `vesper/{id}/system/info` | Discrete device events (e.g. boot report) | 1 | yes | `info` | | `vesper/{id}/system/logs` | Mirrors serial log stream | 0 | no | `logs` | -| `vesper/{id}/system/metrics` | Every 5 min — CPU temp, WiFi/OTA state, bell heat | 0 | no | `metrics` | -| `vesper/{id}/control/ack` | Reply to every command (strictly request/response) | 1 | no | `command` | +| `vesper/{id}/system/metrics` | Every 5 min | 0 | no | `metrics` | + +`control/ack` carries only replies (it is not an event topic). --- ## Legacy Compatibility (v1) -If a client sends `"v": 1` (or omits `v`), the `LegacyAdapter` translates the old `cmd` + `action` pair to a v2 command before dispatch. No code changes needed on the client side during transition. +When `v` is `1` (or omitted on MQTT/WebSocket/UART), `LegacyAdapter` rewrites `cmd` + `contents.action` to a v2 command (removing `action`) before dispatch. A `cmd` it doesn't recognise is passed through unchanged, so v2 command names still work without `v`. Only `system.status` replies are translated back to the v1 shape (see [`system.status`](#systemstatus)). | v1 `cmd` | v1 `action` | v2 `cmd` | |---|---|---| | `ping` | — | `ping` | | `identify` | — | `identify` | -| `playback` | — | `playback` | +| `playback` | `play` | `playback.play` | +| `playback` | `stop` | `playback.stop` | | `file_manager` | `list_melodies` | `files.list` | | `file_manager` | `download_melody` | `files.download` | | `file_manager` | `delete_melody` | `files.delete` | @@ -1066,8 +888,13 @@ If a client sends `"v": 1` (or omits `v`), the `LegacyAdapter` translates the ol | `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` | `get_full_settings` | `system.get_config` | +| `system_info` | `get_all_settings` | `system.get_all` | +| `system_info` | `get_telemetry` | `system.get_telemetry` | | `system_info` | `sync_time_to_lcd` | `system.get_time` *(LCD now uses request/response)* | +| `bells` | `enable` | `bells.enable` | +| `bells` | `disable` | `bells.disable` | +| `bells` | `get_config` | `bells.get_config` | | `system` | `status` | `system.status` | | `system` | `reset_defaults` | `system.factory_reset` | | `system` | `commit_firmware` | `firmware.commit` | @@ -1090,15 +917,17 @@ If a client sends `"v": 1` (or omits `v`), the `LegacyAdapter` translates the ol | Namespace | Commands | |---|---| -| *(root)* | `ping`, `identify`, `playback` | -| `relay` | `set_durations`, `set_outputs`, `get_config`, `test_output` | -| `clock` | `set_outputs`, `set_timings`, `set_alerts`, `set_backlight`, `set_silence`, `set_time`, `set_face`, `set_timezone`, `get_timezone`, `sync_ntp`, `enable`, `disable`, `pause`, `resume`, `get_face`, `get_config` | -| `system` | `status`, `get_time`, `get_settings`, `get_device_info`, `health`, `factory_reset`, `restart` | +| *(root)* | `ping`, `identify` | +| `playback` | `play`, `stop` | +| `relay` | `set_durations`, `set_outputs`, `set_config`, `get_config`, `test_output`, `test_bell`, `test_batch` | +| `clock` | `set_outputs`, `set_timings`, `set_alerts`, `set_backlight`, `set_silence`, `set_config`, `set_alerts_config`, `set_time`, `set_face`, `set_timezone`, `get_timezone`, `sync_ntp`, `enable`, `disable`, `pause`, `resume`, `get_face`, `get_config`, `test_c1`, `test_c2` | +| `system` | `status`, `get_time`, `get_config` (alias `get_settings`), `get_all`, `get_telemetry`, `get_device_info`, `health`, `factory_reset`, `restart`, `set_identity` | | `firmware` | `status`, `commit`, `rollback` | -| `ota` | `status`, `check`, `update`, `custom` | +| `ota` | `update`, `custom`, `set_channel` | | `network` | `info`, `status`, `set_config` | | `files` | `list`, `list_builtin`, `download`, `delete` | -| `log` | `set_serial`, `set_sd`, `set_mqtt` | -| `mqtt` | `enable`, `disable` | -| `telemetry` | `get_strikes`, `reset_strikes`, `get_loads` | -| `rf` | `set_slot`, `clear_slot`, `get_slots`, `enable` *(HAS_RF variants only)* | +| `log` / `logs` | `log.set_serial`, `log.set_sd`, `log.set_mqtt`, `log.get_config`, `logs.list`, `logs.download`, `logs.clear` | +| `mqtt` | `enable`, `disable`, `get_config`, `get_topics`, `set_topics` | +| `telemetry` | `get_strikes`, `reset_strikes`, `get_loads`, `set_max_loads`, `set_guard_enabled`, `get_metrics`, `reset_metrics`, `get_boot_history`, `get_diagnostics`, `reset_boot_data` | +| `bells` | `enable`, `disable`, `get_config` | +| `rf` | `set_slot`, `clear_slot`, `get_slots`, `enable` *(HAS_RF builds only)* | diff --git a/docs/reference/mqtt-events.md b/docs/reference/mqtt-events.md index 10d6646..13038c2 100644 --- a/docs/reference/mqtt-events.md +++ b/docs/reference/mqtt-events.md @@ -285,16 +285,18 @@ Structured telemetry for fleet-health graphing — not consumed by the phone app ### Command (inbound) ```json -{ "v": 2, "cmd": "playback", "req_id": "abc123", "contents": { "action": "stop" } } +{ "v": 2, "cmd": "playback.stop", "req_id": "abc123" } ``` ### Reply (outbound) ```json -{ "status": "SUCCESS", "type": "playback", "req_id": "abc123", "message": "Command executed" } +{ "status": "SUCCESS", "type": "playback", "req_id": "abc123", "message": "Playback command executed" } ``` -`req_id` only appears in the reply if the request included one. Bus-wide unsolicited broadcasts (`CommandBus::broadcast()`) also publish here, with the same envelope shape and no `req_id` — but purpose-specific events (playback, alerts, reports, metrics) never use this path; they publish directly to their own topics instead. +Reply envelope: `status` (`SUCCESS`/`ERROR`), `type`, optional `req_id`, and either `message` (string — text replies and every error) or `data` (object — structured replies). There is no `payload` key. `req_id` only appears in the reply if the request included one. See [api-reference.md](api-reference.md#response-envelope) for the full envelope rules. + +`CommandBus::broadcast()` would also publish here (same envelope, `status: "INFO"`, no `req_id`), but nothing in the firmware calls it today — purpose-specific events (playback, alerts, reports, metrics) publish directly to their own topics. ### Malformed input diff --git a/docs/reference/vesper_mqtt_topic_spec_v2.md b/docs/reference/vesper_mqtt_topic_spec_v2.md index 4ae0646..c8a46f7 100644 --- a/docs/reference/vesper_mqtt_topic_spec_v2.md +++ b/docs/reference/vesper_mqtt_topic_spec_v2.md @@ -47,7 +47,7 @@ This lets a device "breathe" — a fleet-monitoring-only install with no phone a ``` - **Always optional.** A request without `req_id` gets a reply without `req_id` — this is deliberate so v1 clients and any caller not fanning requests out over a shared channel keep working unchanged. -- **Bus-wide, not MQTT-only.** `req_id` lives on `CommandEnvelope`/`CommandResult` in the shared `CommandBus` core (see [CommandBus](../../src/Communication/CommandBus/README.md)), not bolted onto MQTT alone — the intent is that any transport where multiple logical senders share one channel (multiple devices on one broker; a future multiplexed transport) can use the same mechanism to route replies. +- **Bus-wide plumbing, MQTT-only today.** `req_id` lives on `CommandEnvelope`/`CommandResult` in the shared `CommandBus` core (see [CommandBus](../../src/Communication/CommandBus/README.md)), not bolted onto MQTT alone — the intent is that any transport where multiple logical senders share one channel (multiple devices on one broker; a future multiplexed transport) can use the same mechanism to route replies. Only `MQTTTransport` currently reads it from the request; WebSocket, HTTP and UART ignore it and their replies never carry it. - **No access control yet.** Any caller can set any `req_id` today. If needed later, safeguards (e.g. restricting who may set one, or validating format) can be added without a wire-format change. ## Malformed Input