feat: semver versioning, FastAPI OTA integration, health alerts via MQTT

- Version.hpp: extract FW_VERSION from main.cpp into shared header
- OTAManager: replace uint16_t version with SemVer struct; update API URLs
  to new FastAPI backend (/api/firmware/{hw_type}/{channel}/latest);
  add postDownloadTelemetry() and postFlashTelemetry() for fleet visibility
- ConfigManager: remove fwVersion from DeviceConfig (always read from
  FW_VERSION constant); saveDeviceConfig/loadDeviceConfig are now no-ops;
  fallbackServerUrl replaced with fallbackServerUrls[2] array
- HealthMonitor: add AlertCallback + setAlertCallback() firing on state
  transitions (including CLEARED on recovery)
- CommunicationRouter: wire HealthMonitor alert callback on begin();
  add publishAlert() and publishInfo() for MQTT status topics
- MQTTDriver: add _alertsTopic + _infoTopic; add publishDirect() for
  absolute topic publishing; migrate heartbeat to JsonDocument
- ResponseBuilder, ClientManager, BellEngine: StaticJsonDocument /
  DynamicJsonDocument → JsonDocument; remove dead notifyBellsFired()
- docs: reorganise into architecture/, dev/, features/, reference/

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-14 22:15:27 +02:00
co-authored by Claude Sonnet 4.6
parent c3dc0a79bc
commit d4bd990e53
33 changed files with 1874 additions and 301 deletions
+40
View File
@@ -0,0 +1,40 @@
# Project Vesper — Documentation
Bell automation firmware for ESP32 (Kincony KC868-A6).
---
## Reference
| File | Description |
|---|---|
| [reference/api-reference.md](reference/api-reference.md) | **Firmware API v2** — all commands, transports, envelope format |
| [reference/firmware-variants.md](reference/firmware-variants.md) | PlatformIO environments, partition tables, build flags, OTA URLs |
| [reference/api-reference-v1-legacy.md](reference/api-reference-v1-legacy.md) | Old v1 API (pre-refactor) — kept for historical reference |
## Architecture
| File | Description |
|---|---|
| [architecture/communication-refactor-plan.md](architecture/communication-refactor-plan.md) | Full design doc for the v2 Communication subsystem (CommandBus, Handlers, Transports) |
## Features
| File | Description |
|---|---|
| [features/heartbeat.md](features/heartbeat.md) | MQTT heartbeat — retained 30s status publish |
## Development
| File | Description |
|---|---|
| [dev/platformio-commands.md](dev/platformio-commands.md) | PlatformIO CLI reference |
| [dev/common-commands.md](dev/common-commands.md) | Common v1 command snippets (scratch/lab use) |
| [dev/features-scratch.md](dev/features-scratch.md) | Feature notes and todo scratch pad |
## Other
| File | Description |
|---|---|
| [roadmap.md](roadmap.md) | Product roadmap |
| [SentDevices/](SentDevices/) | Records of deployed devices |
+153
View File
@@ -0,0 +1,153 @@
# Backend Task: Subscribe to Vesper MQTT Alert Topics
> Use this document as a prompt / task brief for implementing the backend side
> of the Vesper MQTT alert system. The firmware changes are complete.
> Full topic spec: `docs/reference/mqtt-events.md`
---
## What the firmware now publishes
The Vesper firmware (v155+) publishes on three status topics:
### 1. `vesper/{device_id}/status/heartbeat` (unchanged)
- Every 30 seconds, retained, QoS 1
- You already handle this — **no change needed** except: suppress any log entry / display update triggered by heartbeat arrival. Update `last_seen` silently. Only surface an event when the device goes *silent* (no heartbeat for 90s).
### 2. `vesper/{device_id}/status/alerts` (NEW)
- Published only when a subsystem state changes (HEALTHY → WARNING, WARNING → CRITICAL, etc.)
- QoS 1, not retained
- One message per state transition — not repeated until state changes again
**Alert payload:**
```json
{ "subsystem": "FileManager", "state": "WARNING", "msg": "ConfigManager health check failed" }
```
**Cleared payload (recovery):**
```json
{ "subsystem": "FileManager", "state": "CLEARED" }
```
### 3. `vesper/{device_id}/status/info` (NEW)
- Published on significant device state changes (playback start/stop, etc.)
- QoS 0, not retained
```json
{ "type": "playback_started", "payload": { "melody_uid": "ABC123" } }
```
---
## What to implement in the backend (FastAPI + MQTT)
### Subscribe to new topics
Add to your MQTT subscription list:
```python
client.subscribe("vesper/+/status/alerts", qos=1)
client.subscribe("vesper/+/status/info", qos=0)
```
### Database model — active alerts per device
Create a table (or document) to store the current alert state per device:
```sql
CREATE TABLE device_alerts (
device_id TEXT NOT NULL,
subsystem TEXT NOT NULL,
state TEXT NOT NULL, -- WARNING | CRITICAL | FAILED
message TEXT,
updated_at TIMESTAMP NOT NULL,
PRIMARY KEY (device_id, subsystem)
);
```
Or equivalent in your ORM / MongoDB / Redis structure.
### MQTT message handler — alerts topic
```python
def on_alerts_message(device_id: str, payload: dict):
subsystem = payload["subsystem"]
state = payload["state"]
message = payload.get("msg", "")
if state == "CLEARED":
# Remove alert from active set
db.device_alerts.delete(device_id=device_id, subsystem=subsystem)
else:
# Upsert — create or update
db.device_alerts.upsert(
device_id = device_id,
subsystem = subsystem,
state = state,
message = message,
updated_at = now()
)
# Optionally push a WebSocket event to the console UI
ws_broadcast(device_id, {"event": "alert_update", "subsystem": subsystem, "state": state})
```
### MQTT message handler — info topic
```python
def on_info_message(device_id: str, payload: dict):
event_type = payload["type"]
data = payload.get("payload", {})
# Store or forward as needed — e.g. update device playback state
if event_type == "playback_started":
db.devices.update(device_id, playback_active=True, melody_uid=data.get("melody_uid"))
elif event_type == "playback_stopped":
db.devices.update(device_id, playback_active=False, melody_uid=None)
```
### API endpoint — get active alerts for a device
```
GET /api/devices/{device_id}/alerts
```
Returns the current active alert set (the upserted rows from the table above):
```json
[
{ "subsystem": "FileManager", "state": "WARNING", "message": "SD mount failed", "updated_at": "..." },
{ "subsystem": "TimeKeeper", "state": "WARNING", "message": "NTP sync failed", "updated_at": "..." }
]
```
An empty array means the device is fully healthy (no active alerts).
### Console UI guidance
- Device list: show a coloured dot next to each device (green = no alerts, yellow = warnings, red = critical/failed). Update via WebSocket push.
- Device detail page: show an "Active Alerts" section that renders the alert set statically. Do not render a scrolling alert log — just the current state.
- When a `CLEARED` event arrives, remove the entry from the UI immediately.
---
## What NOT to do
- **Do not log every heartbeat** as a visible event. Heartbeats are internal housekeeping.
- **Do not poll the device** for health status — the device pushes on change.
- **Do not store alerts as an append-only log** — upsert by `(device_id, subsystem)`. The server holds the current state, not a history.
---
## Testing
1. Flash a device with firmware v155+
2. Subscribe manually:
```bash
mosquitto_sub -h <broker> -t "vesper/+/status/alerts" -v
mosquitto_sub -h <broker> -t "vesper/+/status/info" -v
```
3. Remove the SD card from the device — expect a `FileManager` `WARNING` alert within 5 minutes (next health check cycle), or trigger it immediately via:
```json
{ "v": 2, "cmd": "system.health" }
```
sent to `vesper/{device_id}/control`
4. Reinsert the SD card — expect a `FileManager` `CLEARED` alert on the next health check
@@ -1,9 +1,6 @@
COMMANDS:
PV26A28BC01R01
{
"cmd":"system",
"contents":
+151
View File
@@ -0,0 +1,151 @@
# OTA Telemetry API — Backend Endpoints Required
The firmware POSTs two events during an OTA update. Both are **best-effort** — a failure does not abort the update. The device does not retry on failure.
---
## 1. Download Event
**Trigger:** Firmware binary fully written to the staged flash partition, before `Update.end()` is called. The new firmware is not yet active.
**Method:** `POST`
**Path:** `/api/ota/events/download`
### Request Body (JSON)
```json
{
"device_uid": "PV000000000000",
"hw_type": "VS",
"hw_version": "01",
"from_version": "1.2.3",
"to_version": "1.3.0",
"channel": "stable"
}
```
| Field | Type | Description |
|----------------|--------|--------------------------------------------------|
| `device_uid` | string | Unique device identifier from NVS |
| `hw_type` | string | Hardware type code (e.g. `VS`, `VP`, `VX`) |
| `hw_version` | string | Hardware revision from NVS (e.g. `01`) |
| `from_version` | string | Semver of the firmware currently running |
| `to_version` | string | Semver of the firmware that was just downloaded |
| `channel` | string | Update channel (`stable`, `beta`, etc.) |
### Expected Response
Any `2xx` status is accepted. Recommended: `204 No Content`.
---
## 2. Flash Event
**Trigger:** `Update.end()` succeeded — the new partition is committed and the device is about to restart. This is the most reliable signal that the update actually landed.
**Method:** `POST`
**Path:** `/api/ota/events/flash`
### Request Body (JSON)
```json
{
"device_uid": "PV000000000000",
"hw_type": "VS",
"hw_version": "01",
"from_version": "1.2.3",
"to_version": "1.3.0",
"channel": "stable",
"sha256": "a3f1...64hexchars...b9e2"
}
```
| Field | Type | Description |
|----------------|--------|-------------------------------------------------------|
| `device_uid` | string | Unique device identifier from NVS |
| `hw_type` | string | Hardware type code |
| `hw_version` | string | Hardware revision from NVS |
| `from_version` | string | Semver of the firmware that was running |
| `to_version` | string | Semver of the firmware now committed to flash |
| `channel` | string | Update channel |
| `sha256` | string | SHA256 of the downloaded binary (from `/latest` metadata) |
### Expected Response
Any `2xx` status is accepted. Recommended: `204 No Content`.
---
## Notes
- Both requests use the **primary server only** (`servers[0]` from the configured list). No retry, no fallback server attempt.
- Timeout is hardcoded to **5 seconds** to avoid blocking the reboot.
- If WiFi is not connected at the time of the POST, the call is silently skipped.
- The difference between the two events: `download` tells you the device received the binary; `flash` tells you the partition was committed. A device that posts `download` but never posts `flash` may have had a verification failure — worth flagging in the backend.
---
## Suggested Backend Behaviour
- Store both events in a `firmware_events` table with a `type` column (`download` / `flash`).
- Index by `device_uid` + `to_version` to detect partial failures (download without flash).
- Use the `flash` event to drive the "current fleet version" dashboard — it is the ground truth.
---
## Backend Changes Required — Upgrade Chain Resolution
### Background
The firmware sends its current version as a query parameter on every version check:
```
GET /api/firmware/{hw_type}/{channel}/latest?current_version=5.7.1
```
The server must use `current_version` to resolve upgrade chains and return the **correct next hop** rather than blindly returning the absolute latest. The device trusts whatever version the server returns and installs it.
**Example:** Device is on `5.7.1`. Latest is `7.2.2` but has `min_fw_version = 6.0.0`.
- Without chain resolution → server returns `7.2.2` → device cannot install → update silently fails.
- With chain resolution → server returns `6.0.0` → device installs it → on next boot, server returns `7.2.2` → device installs it.
---
### Changes needed in `/api/firmware/{hw_type}/{channel}/latest`
1. **Accept `current_version` as an optional query parameter** (string, semver format e.g. `5.7.1`). If absent or unparseable, fall back to current behaviour (return absolute latest).
2. **Resolve the next hop:**
```
query all published versions for (hw_type, channel), ordered ascending
find the lowest version V where:
V > current_version
AND (V.min_fw_version is null OR current_version >= V.min_fw_version)
return V
```
If no such version exists (current is already at latest, or all higher versions have unsatisfied min_fw_version), return `404` or the current version with no update flag.
3. **The response shape does not change** — same fields as today. The device doesn't need to know it received an intermediate version rather than the latest.
### Example query logic (pseudo-SQL)
```sql
SELECT * FROM firmware_releases
WHERE hw_type = :hw_type
AND channel = :channel
AND version > :current_version
AND (min_fw_version IS NULL OR :current_version >= min_fw_version)
ORDER BY version ASC -- semver-aware sort
LIMIT 1;
```
> Note: semver ordering must be numeric (`1.10.0 > 1.9.0`), not lexicographic. Use a semver-aware sort or store major/minor/patch as separate integer columns.
### Edge cases to handle
| Scenario | Expected behaviour |
|---|---|
| `current_version` absent / malformed | Ignore param, return absolute latest (existing behaviour) |
| Device already at latest | Return `404` or `200` with a "no update" indicator — firmware handles both |
| No version satisfies the chain constraint | Return `404` — firmware logs and skips |
| Multiple intermediate hops needed | Server returns only the immediate next hop; device re-checks after each reboot and walks the chain naturally |
+872
View File
@@ -0,0 +1,872 @@
# Vesper Firmware — API Reference (v2)
> Command reference for the Vesper Bell Automation System.
> Firmware v2 command bus architecture — all transports, all handlers.
> Last updated: 2026-03-01
---
## Overview
### Message Envelope
Every command sent to Vesper uses this JSON envelope:
```json
{
"v": 2,
"cmd": "namespace.command",
"contents": { ... }
}
```
| Field | Type | Notes |
|---|---|---|
| `v` | int | Protocol version. `2` = current. Omit or set `1` for legacy (LegacyAdapter runs). |
| `cmd` | string | `namespace.command` format (e.g. `relay.set_durations`). |
| `contents` | object | Command payload. May be omitted if command takes no fields. |
### Response Envelope
```json
{
"status": "SUCCESS" | "ERROR",
"type": "command_name",
"payload": { ... }
}
```
`payload` is command-specific. On error, `payload` typically contains a `"message"` string.
---
## Transports
| Transport | Address | Direction | Notes |
|---|---|---|---|
| MQTT | `vesper/{device_id}/control` | Inbound commands | Responses go to `vesper/{device_id}/data` |
| MQTT | `vesper/{device_id}/data` | Outbound responses + events | Command replies and bell overload notifications |
| MQTT | `vesper/{device_id}/status/heartbeat` | Outbound, retained, QoS 1 | Heartbeat every 30s; server updates last_seen |
| MQTT | `vesper/{device_id}/status/alerts` | Outbound, QoS 1 | Subsystem state-change events (published on change only) |
| MQTT | `vesper/{device_id}/status/info` | Outbound, QoS 0 | General device state events (playback, reboot reason, etc.) |
| 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 |
### UART Whitelist
Only the following commands are accepted over UART (LCD/button slave board). All others are silently dropped.
```
ping
playback
clock.pause
clock.resume
system.get_time
```
### WebSocket — Client Identification
WebSocket clients must send `identify` immediately after connecting, or they will not receive targeted responses:
```json
{ "v": 2, "cmd": "identify", "contents": { "device_type": "master" } }
```
`device_type`: `"master"` (app/console) or `"secondary"` (slave board).
---
## Command Reference
---
### `ping`
| | |
|---|---|
| Handler | SystemHandler |
| Transports | All |
| Contents | *(none)* |
| Returns | `{ "status": "SUCCESS", "type": "pong" }` |
```json
{ "v": 2, "cmd": "ping" }
```
---
### `identify`
| | |
|---|---|
| Handler | SystemHandler |
| Transports | WebSocket only |
| Contents | `device_type` (required) |
```json
{ "v": 2, "cmd": "identify", "contents": { "device_type": "master" } }
```
---
### `playback`
| | |
|---|---|
| Handler | PlaybackHandler |
| Transports | All |
| Contents | `action` (required) + melody fields |
`action` values: `"play"`, `"stop"`, `"pause"`, `"unpause"`
```json
{ "v": 2, "cmd": "playback", "contents": { "action": "play", "melody_uid": "ABC123" } }
{ "v": 2, "cmd": "playback", "contents": { "action": "stop" } }
```
---
## Relay Namespace — `RelayHandler`
---
### `relay.set_durations`
Set strike duration (ms) for one or more bell channels. Partial updates accepted — omitted channels are unchanged.
| | |
|---|---|
| Required | At least one bell entry |
| Contents | `{ "bells": { "0": 95, "2": 110 } }` |
```json
{
"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.
| | |
|---|---|
| Required | At least one bell entry |
| Contents | `{ "bells": { "0": 2, "1": 3 } }` |
```json
{
"v": 2,
"cmd": "relay.set_outputs",
"contents": { "bells": { "0": 2, "1": 3, "2": 4 } }
}
```
---
### `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" }
```
---
### `relay.test_output`
Fire a specific relay for a caller-specified duration. Safety-gated: Player must be stopped.
| | |
|---|---|
| Required | `output` (int), `duration_ms` (int) |
| Notes | Both fields required — no defaults. Typical range: 85–140 ms. |
```json
{
"v": 2,
"cmd": "relay.test_output",
"contents": { "output": 2, "duration_ms": 95 }
}
```
---
## Clock Namespace — `ClockHandler`
---
### `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 |
---
### `clock.set_timings`
Set clock strike timing configuration. Partial updates accepted.
---
### `clock.set_alerts`
Configure hourly/quarter alert behavior. Partial updates accepted.
---
### `clock.set_backlight`
Configure backlight behavior. Partial updates accepted.
---
### `clock.set_silence`
Configure silence period (quiet hours). Partial updates accepted.
---
### `clock.set_time`
Set the RTC time.
| | |
|---|---|
| Required | `timestamp` (Unix epoch, int) |
| Optional | `timezone_offset` (int, seconds), `dst_offset` (int, seconds) |
```json
{
"v": 2,
"cmd": "clock.set_time",
"contents": { "timestamp": 1740000000, "timezone_offset": 7200 }
}
```
---
### `clock.set_face`
Set the physical analog clock face position.
| | |
|---|---|
| Required | `hour` (int), `minute` (int) |
```json
{ "v": 2, "cmd": "clock.set_face", "contents": { "hour": 10, "minute": 10 } }
```
---
### `clock.set_timezone`
Set timezone independently of RTC time.
| | |
|---|---|
| Required | `gmt_offset_sec` (int) |
| Optional | `dst_offset_sec` (int), `timezone_name` (string) |
```json
{
"v": 2,
"cmd": "clock.set_timezone",
"contents": { "gmt_offset_sec": 7200, "dst_offset_sec": 3600, "timezone_name": "Europe/Athens" }
}
```
---
### `clock.get_timezone`
Read current timezone settings.
| | |
|---|---|
| Returns | `{ "gmt_offset_sec": 7200, "dst_offset_sec": 3600, "timezone_name": "..." }` |
---
### `clock.sync_ntp`
Force an immediate NTP time sync.
| | |
|---|---|
| Required | *(none)* |
---
### `clock.enable` / `clock.disable`
Enable or disable clock strike output.
```json
{ "v": 2, "cmd": "clock.enable" }
{ "v": 2, "cmd": "clock.disable" }
```
---
### `clock.pause` / `clock.resume`
Pause or resume clock updates.
```json
{ "v": 2, "cmd": "clock.pause" }
{ "v": 2, "cmd": "clock.resume" }
```
---
### `clock.get_face`
Read current analog clock face position.
| | |
|---|---|
| Returns | `{ "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).
---
## System Namespace — `SystemHandler`
---
### `system.status`
Get current device status: player state, strike counters, projected run time.
```json
{ "v": 2, "cmd": "system.status" }
```
---
### `system.get_time`
Get current RTC time.
| | |
|---|---|
| Returns | `{ "local_timestamp", "utc_timestamp", "year", "month", "day", "hour", "minute", "second", "rtc_available" }` |
```json
{ "v": 2, "cmd": "system.get_time" }
```
---
### `system.get_settings`
Get full ConfigManager JSON dump (all saved settings).
```json
{ "v": 2, "cmd": "system.get_settings" }
```
---
### `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" }
```
---
### `system.health`
Get full HealthMonitor report — all subsystem states, warnings, critical failures.
```json
{ "v": 2, "cmd": "system.health" }
```
---
### `system.factory_reset`
Reset all settings to factory defaults.
> **Warning:** Non-reversible. All saved configuration is wiped.
```json
{ "v": 2, "cmd": "system.factory_reset" }
```
---
### `system.restart`
Reboot the device. Response is sent before reboot (2s delay).
```json
{ "v": 2, "cmd": "system.restart" }
```
---
## Firmware Namespace — `FirmwareHandler`
---
### `firmware.status`
Get firmware validation state.
| | |
|---|---|
| Returns | `{ "validation_state", "version", "boot_count", "can_commit", "can_rollback" }` |
```json
{ "v": 2, "cmd": "firmware.status" }
```
---
### `firmware.commit`
Commit the current firmware as permanent (marks OTA slot as valid).
```json
{ "v": 2, "cmd": "firmware.commit" }
```
---
### `firmware.rollback`
Roll back to the previous firmware. Device reboots.
```json
{ "v": 2, "cmd": "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" } }
```
---
### `ota.update`
Trigger OTA update from VPS. Device may reboot.
| | |
|---|---|
| Optional | `channel` (string, default `"stable"`) |
```json
{ "v": 2, "cmd": "ota.update", "contents": { "channel": "stable" } }
```
---
### `ota.custom`
Flash firmware from a custom URL.
| | |
|---|---|
| Required | `firmware_url` (string) |
| Optional | `checksum` (string), `file_size` (int), `version` (string) |
```json
{
"v": 2,
"cmd": "ota.custom",
"contents": {
"firmware_url": "http://example.com/firmware.bin",
"checksum": "abc123",
"version": "142"
}
}
```
---
## Network Namespace — `NetworkHandler`
---
### `network.info`
Get IP/gateway/DNS.
| | |
|---|---|
| Returns | `{ "ip", "gateway", "dns" }` |
```json
{ "v": 2, "cmd": "network.info" }
```
---
### `network.status`
Get full connection state.
| | |
|---|---|
| Returns | `{ "connected", "state", "type", "ip", "rssi", "ap_mode" }` |
```json
{ "v": 2, "cmd": "network.status" }
```
---
### `network.set_config`
Update network configuration. Partial updates accepted. Returns `restart_required` flag.
| | |
|---|---|
| Required | At least one field |
| Optional | `hostname`, `useStaticIP`, `ip`, `gateway`, `subnet`, `dns1`, `dns2` |
| Notes | Static IP requires `ip` + `gateway` + `subnet` together |
```json
{
"v": 2,
"cmd": "network.set_config",
"contents": { "hostname": "vesper-lab", "useStaticIP": false }
}
```
---
## 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" }
```
---
### `files.list_builtin`
List all built-in melodies compiled into the firmware.
| | |
|---|---|
| Returns | `[{ "name": "...", "uid": "..." }, ...]` |
```json
{ "v": 2, "cmd": "files.list_builtin" }
```
---
### `files.download`
Download a melody from the server to the SD card.
| | |
|---|---|
| Required | `melodys_uid` (string) |
```json
{ "v": 2, "cmd": "files.download", "contents": { "melodys_uid": "ABC123" } }
```
---
### `files.delete`
Delete a melody from the SD card.
| | |
|---|---|
| Required | `name` (string) |
```json
{ "v": 2, "cmd": "files.delete", "contents": { "name": "westminster.mel" } }
```
---
## Log Namespace — `LoggingHandler`
Set log verbosity per output channel. Level 0 = off, 5 = verbose.
| Level | Meaning |
|---|---|
| 0 | None |
| 1 | Error |
| 2 | Warning |
| 3 | Info |
| 4 | Debug |
| 5 | Verbose |
### `log.set_serial`
```json
{ "v": 2, "cmd": "log.set_serial", "contents": { "level": 3 } }
```
### `log.set_sd`
```json
{ "v": 2, "cmd": "log.set_sd", "contents": { "level": 2 } }
```
### `log.set_mqtt`
```json
{ "v": 2, "cmd": "log.set_mqtt", "contents": { "level": 1 } }
```
---
## MQTT Namespace — `MQTTHandler`
### `mqtt.enable` / `mqtt.disable`
Enable or disable MQTT connectivity.
```json
{ "v": 2, "cmd": "mqtt.enable" }
{ "v": 2, "cmd": "mqtt.disable" }
```
---
## 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" }
```
---
### `telemetry.reset_strikes`
Reset strike counters. Omit `bell` to reset all channels; include it to reset one.
| | |
|---|---|
| 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" }
```
---
## MQTT Events (Unsolicited)
These messages are published by the device without a request. See [mqtt-events.md](mqtt-events.md) for the full AsyncAPI-compatible reference.
| Topic | When | QoS | Retained | Format |
|---|---|---|---|---|
| `vesper/{id}/status/heartbeat` | Every 30s | 1 | yes | Heartbeat envelope |
| `vesper/{id}/status/alerts` | On subsystem state change only | 1 | no | Alert envelope |
| `vesper/{id}/status/info` | On device state change | 0 | no | Info envelope |
| `vesper/{id}/data` | Any command response / bell overload | 0 | no | Standard response envelope |
### Heartbeat Payload
```json
{
"status": "INFO",
"type": "heartbeat",
"payload": {
"device_id": "PV-26B18-VS01R-X7KQA",
"firmware_version": "142",
"timestamp": "Uptime: 5h 23m 45s",
"ip_address": "10.0.0.3",
"gateway": "10.0.0.1",
"uptime_ms": 19425000
}
}
```
Subscribe to `vesper/+/status/heartbeat` to discover all online devices.
### Alert Payload (`vesper/{id}/status/alerts`)
Published only when a subsystem state changes. The server should store the active alert set per device and update the display in place rather than appending a log entry.
```json
{ "subsystem": "FileManager", "state": "WARNING", "msg": "ConfigManager health check failed" }
```
On recovery:
```json
{ "subsystem": "FileManager", "state": "CLEARED" }
```
`state` values: `WARNING` | `CRITICAL` | `FAILED` | `CLEARED`
### Info Payload (`vesper/{id}/status/info`)
Published on significant device state changes. `type` identifies the event; `payload` is event-specific.
```json
{ "type": "playback_started", "payload": { "melody_uid": "ABC123" } }
{ "type": "playback_stopped", "payload": {} }
```
---
## 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.
| 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` *(LCD now uses request/response)* |
| `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` |
---
## Quick Reference
| 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` |
| `firmware` | `status`, `commit`, `rollback` |
| `ota` | `status`, `check`, `update`, `custom` |
| `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` |
+209
View File
@@ -0,0 +1,209 @@
# Vesper — MQTT Events Reference
> Source of truth for all unsolicited MQTT messages published by Vesper firmware.
> Use this document to generate or update the AsyncAPI specification in the backend console.
> Last updated: 2026-03-01
---
## Overview
Vesper publishes on four MQTT topics. All topics are device-scoped under the prefix `vesper/{device_id}/`.
| Topic | Direction | QoS | Retained | Purpose |
|-------|-----------|-----|----------|---------|
| `vesper/{id}/control` | Inbound | — | — | Commands from server/app |
| `vesper/{id}/data` | Outbound | 0 | no | Command responses + bell overload events |
| `vesper/{id}/status/heartbeat` | Outbound | 1 | yes | Periodic liveness signal |
| `vesper/{id}/status/alerts` | Outbound | 1 | no | Subsystem state-change events |
| `vesper/{id}/status/info` | Outbound | 0 | no | General device state events |
Subscribe to `vesper/+/status/#` to receive all status events from all devices.
---
## `vesper/{id}/status/heartbeat`
**QoS:** 1 — **Retained:** yes — **Interval:** 30 seconds
Published immediately on MQTT connect, then every 30 seconds. The broker retains the last message so any new subscriber instantly sees whether the device is alive.
The server should:
- Update `last_seen` timestamp silently — **no log entry, no display update**
- Raise an offline alert if no heartbeat is received within 90 seconds (3 missed beats)
### Payload
```json
{
"status": "INFO",
"type": "heartbeat",
"payload": {
"device_id": "PV-26B18-VS01R-X7KQA",
"firmware_version": "154",
"timestamp": "Uptime: 5h 23m 45s",
"ip_address": "10.0.0.3",
"gateway": "10.0.0.1",
"uptime_ms": 19425000
}
}
```
| Field | Type | Description |
|-------|------|-------------|
| `payload.device_id` | string | Device serial number (from NVS) |
| `payload.firmware_version` | string | Firmware build version string |
| `payload.timestamp` | string | Human-readable uptime string |
| `payload.ip_address` | string | Current device IP |
| `payload.gateway` | string | Network gateway IP |
| `payload.uptime_ms` | integer | Milliseconds since boot |
---
## `vesper/{id}/status/alerts`
**QoS:** 1 — **Retained:** no — **Trigger:** subsystem state change only
Published by `HealthMonitor` (via `CommunicationRouter::publishAlert()`) whenever a subsystem transitions between health states. Published once on change; not repeated until the state changes again. Silent if MQTT is not connected at the moment of the transition.
The server should:
- Maintain a **per-device active alert set** (e.g. a dict keyed by `subsystem`)
- On receipt: upsert the alert in the set
- On `CLEARED`: remove the entry from the set
- Display the active alert set statically on the device detail page — **not as a scrolling log**
### Alert payload (problem)
```json
{
"subsystem": "FileManager",
"state": "WARNING",
"msg": "ConfigManager health check failed"
}
```
### Cleared payload (recovery)
```json
{
"subsystem": "FileManager",
"state": "CLEARED"
}
```
| Field | Type | Description |
|-------|------|-------------|
| `subsystem` | string | Subsystem name. One of: `BellEngine`, `OutputManager`, `Player`, `Communication`, `TimeKeeper`, `Telemetry`, `OTAManager`, `Networking`, `ConfigManager`, `FileManager` |
| `state` | string | New state: `WARNING` \| `CRITICAL` \| `FAILED` \| `CLEARED` |
| `msg` | string | Human-readable description. Absent when `state` is `CLEARED`. |
### State meanings
| State | Meaning |
|-------|---------|
| `WARNING` | Subsystem has an issue but device continues to operate |
| `CRITICAL` | Subsystem failure affects core functionality |
| `FAILED` | Subsystem is non-functional (equivalent to CRITICAL for critical subsystems) |
| `CLEARED` | Subsystem has recovered; remove from active alert set |
### Critical vs non-critical subsystems
| Subsystem | Critical? | Notes |
|-----------|-----------|-------|
| BellEngine | yes | Core timing — CRITICAL triggers rollback consideration |
| OutputManager | yes | Hardware — CRITICAL triggers rollback consideration |
| Player | yes | Melody control |
| ConfigManager | no | SD card absence maps to WARNING |
| FileManager | no | SD card absence maps to WARNING |
| Communication | no | MQTT/WS failure |
| TimeKeeper | no | RTC sync failure |
| Telemetry | no | Strike counting |
| OTAManager | no | OTA update subsystem |
| Networking | no | WiFi connectivity |
---
## `vesper/{id}/status/info`
**QoS:** 0 — **Retained:** no — **Trigger:** significant device state change
Published for general device state changes that are not health failures. Use this topic to update the device detail panel (e.g. current playback, reboot reason) without polling.
The server should display the most recent `info` payload for each event `type` on the device detail page.
### Envelope
```json
{
"type": "event_type",
"payload": { ... }
}
```
### Event types (current and planned)
| `type` | When | Payload fields |
|--------|------|----------------|
| `playback_started` | Player begins playing a melody | `melody_uid` (string) |
| `playback_stopped` | Player stops | *(none)* |
> **Note:** `publishInfo()` exists in `CommunicationRouter` but is not yet called from any subsystem. Call sites will be added as feature work in subsequent firmware versions. The API is stable.
---
## `vesper/{id}/data`
**QoS:** 0 — **Retained:** no
Published in response to commands and for unsolicited events that are not health-related.
### Command response envelope
```json
{
"status": "SUCCESS" | "ERROR",
"type": "command_name",
"payload": { ... }
}
```
### Bell overload event
Published by `CommunicationRouter::sendBellOverloadNotification()` when per-bell strike load exceeds configured thresholds.
```json
{
"status": "INFO",
"type": "bell_overload",
"payload": {
"bells": [2, 5],
"loads": [54, 48],
"severity": "WARNING"
}
}
```
| Field | Type | Description |
|-------|------|-------------|
| `payload.bells` | array of int | 1-indexed bell channel numbers that are overloaded |
| `payload.loads` | array of int | Strike count load per bell channel |
| `payload.severity` | string | `WARNING` (≥60% load) or `CRITICAL` (≥90% load) |
---
## Server subscription pattern
```
vesper/+/status/heartbeat → update last_seen, no logging
vesper/+/status/alerts → upsert/remove active alert set per device
vesper/+/status/info → update device state panel
vesper/+/data → display command responses, handle bell_overload
```
---
## Removed events
| Event | Was published to | Removed in | Reason |
|-------|-----------------|------------|--------|
| `ding` (bell fired) | `vesper/{id}/data` (WebSocket only) | Firmware v155+ | Unstable under load; no active consumers |