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:
@@ -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
|
||||
@@ -0,0 +1,39 @@
|
||||
COMMANDS:
|
||||
|
||||
|
||||
{
|
||||
"cmd":"system",
|
||||
"contents":
|
||||
{
|
||||
"action":"force_update",
|
||||
"channel":"beta"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
{
|
||||
"cmd":"system",
|
||||
"contents":
|
||||
{
|
||||
"action":"set_mqtt_log_level",
|
||||
"level":3
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
{
|
||||
"cmd":"system",
|
||||
"contents":
|
||||
{
|
||||
"action":"restart"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
{
|
||||
"cmd":"system_info",
|
||||
"contents":
|
||||
{
|
||||
"action":"get_full_settings"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
Features:
|
||||
|
||||
// mqtt topics:
|
||||
vesper/<DEVID>/data // Data sent from the controller
|
||||
vesper/<DEVID>/control // Commands sent to the controller
|
||||
vesper/<DEVID>/kiosk/event // Kiosk Mode Events
|
||||
vesper/<DEVID>/kiosk/info // Kiosk Mode General Info
|
||||
|
||||
// WiFi Local AP
|
||||
BellSystemsInfra
|
||||
v3sp3r_8998!
|
||||
|
||||
|
||||
|
||||
- WiFi Manager (captive portal with hotspot)
|
||||
- MQTT Support (Subscribing and Publishing)
|
||||
- WebSocket Support (Sending and Receiving)
|
||||
- JSON Format Messaging (both MQTT and WS)
|
||||
- SD Card Handling and File Ops
|
||||
- Stand-alone Player/BellEngine Classes, with functions to Play/Pause/Stop etc
|
||||
- NoteAssignments - Effectively mapping Notes to Bells
|
||||
- Independent SubSystems for all Core Functions (Networking/Comms/Scheduling/Logging/etc)
|
||||
- Custom Relay Output Maps and Timings (saved on SD)
|
||||
- Timekeeper with RTC/Clock/Alerts/Scheduling features
|
||||
- OTA Update Functionality with Versioning/Rollbacks/Checksum/Firmware Validation/NTP Sync
|
||||
- Global logger with Mode Selection (None, Error, Warning, Info, Debug, Verbose)
|
||||
- UDP Listener for Auto Device Discovery
|
||||
- Datalogging and Statistics:
|
||||
- Counter for each bell (counts total times the bell ringed)
|
||||
- Counter per bell, beats/minute for reliability and thermal protection. Warranty Void scenario.
|
||||
- Ability to change Log levels (in-app)
|
||||
|
||||
|
||||
|
||||
ToDo Features:
|
||||
|
||||
- (optional) Add Bluetooth support
|
||||
- (optional) Add WiFi Direct AP Support
|
||||
- (optional) Add PCB Temperature Sensor Support
|
||||
|
||||
- (critical) Counters and Statistics:
|
||||
- Counter per playback, to figure out which melody is the most played.
|
||||
This can be implemented on the App itself. Doesn't need to be on the Device.
|
||||
|
||||
- Create a "humanizer" mode that randomizes delays on playback to simulate human ringing.
|
||||
|
||||
|
||||
ToDo Fixes:
|
||||
|
||||
- (small significance) Fix each Log's level Correctly + Fix Log Syntax where needed
|
||||
- (medium significance) BellGuard: Make the buttons functional.
|
||||
|
||||
- Fix IP Settings not applying. More Specifically, Variables inside the Components take long to update. Either Ditch the components, or find another way.
|
||||
- On Very fast playback speeds and small programs that will run for less than a second or so, STOP isn't sent properly. Player keeps indicating "playing".
|
||||
- When a new user is created, set default PINs for both Quick Settings, and Settings.
|
||||
|
||||
|
||||
@@ -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 |
|
||||
Reference in New Issue
Block a user