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,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 |
|
||||
@@ -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":
|
||||
@@ -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 |
|
||||
@@ -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` |
|
||||
@@ -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 |
|
||||
@@ -316,10 +316,6 @@ void BellEngine::activateNote(uint16_t note) {
|
||||
if (!bellDurations.empty()) {
|
||||
_outputManager.fireOutputsBatchForDuration(bellDurations);
|
||||
LOG_VERBOSE(TAG, "BellEngine - 🔥 Batch Fired %d bells Simultaneously !", bellDurations.size());
|
||||
|
||||
// 🔔 NOTIFY WEBSOCKET CLIENTS OF BELL DINGS!
|
||||
// * deactivated currently, since unstable and causes performance issues *
|
||||
// notifyBellsFired(firedBellIndices);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -345,34 +341,6 @@ void BellEngine::emergencyShutdown() {
|
||||
_outputManager.emergencyShutdown();
|
||||
}
|
||||
|
||||
void BellEngine::notifyBellsFired(const std::vector<uint8_t>& bellIndices) {
|
||||
if (!_communicationManager || bellIndices.empty()) {
|
||||
|
||||
return; // No communication manager or no bells fired
|
||||
}
|
||||
|
||||
try {
|
||||
// Create notification message
|
||||
StaticJsonDocument<256> dingMsg;
|
||||
dingMsg["status"] = "INFO";
|
||||
dingMsg["type"] = "ding";
|
||||
|
||||
// Create payload array with fired bell numbers (1-indexed for display)
|
||||
JsonArray bellsArray = dingMsg["payload"].to<JsonArray>();
|
||||
for (uint8_t bellIndex : bellIndices) {
|
||||
bellsArray.add(bellIndex); // Already converted to 1-indexed in activateNote
|
||||
}
|
||||
|
||||
// Send notification to WebSocket clients only (not MQTT)
|
||||
_communicationManager->broadcastToAllWebSocketClients(dingMsg);
|
||||
|
||||
LOG_DEBUG(TAG, "BellEngine - 🔔 DING notification sent for %d bells", bellIndices.size());
|
||||
|
||||
} catch (...) {
|
||||
LOG_WARNING(TAG, "BellEngine - ❌ Failed to send ding notification");
|
||||
}
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// HEALTH CHECK IMPLEMENTATION
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -357,13 +357,6 @@ private:
|
||||
*/
|
||||
void checkAndNotifyOverloads();
|
||||
|
||||
/**
|
||||
* @brief Notify WebSocket clients of fired bells
|
||||
* @param bellIndices Vector of bell indices that were fired (1-indexed)
|
||||
*
|
||||
* Sends INFO/ding message to WebSocket clients only (not MQTT)
|
||||
*/
|
||||
void notifyBellsFired(const std::vector<uint8_t>& bellIndices);
|
||||
};
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -134,11 +134,11 @@ void ClientManager::cleanupDisconnectedClients() {
|
||||
}
|
||||
|
||||
String ClientManager::getClientListJson() const {
|
||||
StaticJsonDocument<512> doc;
|
||||
JsonArray clients = doc.createNestedArray("clients");
|
||||
JsonDocument doc;
|
||||
JsonArray clients = doc["clients"].to<JsonArray>();
|
||||
|
||||
for (const auto& pair : _clients) {
|
||||
JsonObject client = clients.createNestedObject();
|
||||
JsonObject client = clients.add<JsonObject>();
|
||||
client["id"] = pair.first;
|
||||
client["type"] = deviceTypeToString(pair.second.deviceType);
|
||||
client["connected"] = isValidClient(pair.second.client);
|
||||
|
||||
@@ -129,6 +129,16 @@ void CommunicationRouter::begin() {
|
||||
// ── Register all domain handlers ─────────────────────────────────────────
|
||||
registerHandlers();
|
||||
|
||||
// ── Wire HealthMonitor alert callback ────────────────────────────────────
|
||||
if (_healthMonitor) {
|
||||
_healthMonitor->setAlertCallback(
|
||||
[this](const String& subsystem, const String& newState, const String& message) {
|
||||
publishAlert(subsystem, newState, message);
|
||||
}
|
||||
);
|
||||
LOG_INFO(TAG, "HealthMonitor alert callback registered");
|
||||
}
|
||||
|
||||
LOG_INFO(TAG, "Communication Router ready — CommandBus active");
|
||||
}
|
||||
|
||||
@@ -263,7 +273,7 @@ void CommunicationRouter::setupUdpDiscovery() {
|
||||
if (msg.indexOf("discover") >= 0) {
|
||||
shouldReply = true;
|
||||
} else {
|
||||
StaticJsonDocument<128> req;
|
||||
JsonDocument req;
|
||||
if (!deserializeJson(req, msg)) {
|
||||
shouldReply = (req["op"] == "discover");
|
||||
}
|
||||
@@ -271,7 +281,7 @@ void CommunicationRouter::setupUdpDiscovery() {
|
||||
|
||||
if (!shouldReply) return;
|
||||
|
||||
StaticJsonDocument<256> doc;
|
||||
JsonDocument doc;
|
||||
doc["op"] = "discover_reply";
|
||||
doc["svc"] = "vesper";
|
||||
doc["ver"] = 1;
|
||||
@@ -381,7 +391,7 @@ void CommunicationRouter::sendBellOverloadNotification(
|
||||
const std::vector<uint16_t>& bellLoads,
|
||||
const String& severity) {
|
||||
|
||||
StaticJsonDocument<512> doc;
|
||||
JsonDocument doc;
|
||||
doc["status"] = "INFO";
|
||||
doc["type"] = "bell_overload";
|
||||
|
||||
@@ -399,6 +409,41 @@ void CommunicationRouter::sendBellOverloadNotification(
|
||||
bellNumbers.size(), severity.c_str());
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Alert / Info publishing
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
void CommunicationRouter::publishAlert(const String& subsystem, const String& newState, const String& message) {
|
||||
if (!_mqttClient.isConnected()) return;
|
||||
|
||||
JsonDocument doc;
|
||||
doc["subsystem"] = subsystem;
|
||||
doc["state"] = newState;
|
||||
if (!message.isEmpty()) {
|
||||
doc["msg"] = message;
|
||||
}
|
||||
|
||||
String out;
|
||||
serializeJson(doc, out);
|
||||
_mqttClient.publishDirect(_mqttClient.getAlertsTopic(), out, 1, false);
|
||||
LOG_DEBUG(TAG, "Alert published: %s → %s", subsystem.c_str(), newState.c_str());
|
||||
}
|
||||
|
||||
void CommunicationRouter::publishInfo(const String& type, const JsonDocument& payload) {
|
||||
if (!_mqttClient.isConnected()) return;
|
||||
|
||||
JsonDocument doc;
|
||||
doc["type"] = type;
|
||||
if (!payload.isNull()) {
|
||||
doc["payload"] = payload;
|
||||
}
|
||||
|
||||
String out;
|
||||
serializeJson(doc, out);
|
||||
_mqttClient.publishDirect(_mqttClient.getInfoTopic(), out, 0, false);
|
||||
LOG_DEBUG(TAG, "Info published: %s", type.c_str());
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Network state callbacks
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -97,6 +97,26 @@ public:
|
||||
const std::vector<uint16_t>& bellLoads,
|
||||
const String& severity);
|
||||
|
||||
/**
|
||||
* @brief Publish a subsystem alert to vesper/{id}/status/alerts.
|
||||
* Called by HealthMonitor when a subsystem state changes.
|
||||
* Only publishes on actual state change; no-ops if MQTT not connected.
|
||||
*
|
||||
* @param subsystem Subsystem name e.g. "BellEngine"
|
||||
* @param newState New state string: "HEALTHY" | "WARNING" | "CRITICAL" | "FAILED"
|
||||
* @param message Human-readable description (empty string on CLEARED)
|
||||
*/
|
||||
void publishAlert(const String& subsystem, const String& newState, const String& message = "");
|
||||
|
||||
/**
|
||||
* @brief Publish a general device info event to vesper/{id}/status/info.
|
||||
* Used for state changes such as playback start/stop, reboot reason, etc.
|
||||
*
|
||||
* @param type Event type string e.g. "playback_started"
|
||||
* @param payload JSON object with event-specific fields (pass an empty doc for no payload)
|
||||
*/
|
||||
void publishInfo(const String& type, const JsonDocument& payload);
|
||||
|
||||
// Network state callbacks (called by Networking)
|
||||
void onNetworkConnected();
|
||||
void onNetworkDisconnected();
|
||||
|
||||
@@ -77,9 +77,13 @@ void MQTTDriver::begin() {
|
||||
String deviceUID = _configManager.getDeviceUID();
|
||||
_controlTopic = "vesper/" + deviceUID + "/control";
|
||||
_dataTopic = "vesper/" + deviceUID + "/data";
|
||||
_alertsTopic = "vesper/" + deviceUID + "/status/alerts";
|
||||
_infoTopic = "vesper/" + deviceUID + "/status/info";
|
||||
_clientId = "vesper-" + deviceUID;
|
||||
|
||||
LOG_INFO(TAG, "MQTT Topics: control=%s, data=%s", _controlTopic.c_str(), _dataTopic.c_str());
|
||||
LOG_INFO(TAG, "MQTT Topics: control=%s, data=%s, alerts=%s, info=%s",
|
||||
_controlTopic.c_str(), _dataTopic.c_str(),
|
||||
_alertsTopic.c_str(), _infoTopic.c_str());
|
||||
|
||||
// Setup event handlers
|
||||
_mqttClient.onConnect([this](bool sessionPresent) {
|
||||
@@ -165,6 +169,17 @@ uint16_t MQTTDriver::publish(const String& topic, const String& payload, int qos
|
||||
return packetId;
|
||||
}
|
||||
|
||||
uint16_t MQTTDriver::publishDirect(const String& fullTopic, const String& payload, int qos, bool retain) {
|
||||
if (!_mqttClient.connected()) {
|
||||
return 0;
|
||||
}
|
||||
uint16_t packetId = _mqttClient.publish(fullTopic.c_str(), qos, retain, payload.c_str());
|
||||
if (packetId > 0) {
|
||||
LOG_DEBUG(TAG, "Published to %s (packetId=%d)", fullTopic.c_str(), packetId);
|
||||
}
|
||||
return packetId;
|
||||
}
|
||||
|
||||
void MQTTDriver::setCallback(MessageCallback callback) {
|
||||
_messageCallback = callback;
|
||||
}
|
||||
@@ -361,11 +376,11 @@ void MQTTDriver::publishHeartbeat() {
|
||||
}
|
||||
|
||||
// Build heartbeat JSON message
|
||||
StaticJsonDocument<512> doc;
|
||||
JsonDocument doc;
|
||||
doc["status"] = "INFO";
|
||||
doc["type"] = "heartbeat";
|
||||
|
||||
JsonObject payload = doc.createNestedObject("payload");
|
||||
JsonObject payload = doc["payload"].to<JsonObject>();
|
||||
|
||||
// Device ID from NVS
|
||||
payload["device_id"] = _configManager.getDeviceUID();
|
||||
|
||||
@@ -49,6 +49,7 @@ public:
|
||||
/**
|
||||
* @brief Publish message to MQTT
|
||||
* @param topic Topic to publish to (relative, will prepend "vesper/{deviceID}/")
|
||||
* If empty string — publishes to the data topic.
|
||||
* @param payload Message payload
|
||||
* @param qos QoS level (0, 1, or 2)
|
||||
* @param retain Retain flag
|
||||
@@ -56,6 +57,16 @@ public:
|
||||
*/
|
||||
uint16_t publish(const String& topic, const String& payload, int qos = 0, bool retain = false);
|
||||
|
||||
/**
|
||||
* @brief Publish to an absolute, fully-qualified topic (no prefix applied).
|
||||
* @param fullTopic Complete topic string
|
||||
* @param payload Message payload
|
||||
* @param qos QoS level (0, 1, or 2)
|
||||
* @param retain Retain flag
|
||||
* @return Packet ID (0 if failed)
|
||||
*/
|
||||
uint16_t publishDirect(const String& fullTopic, const String& payload, int qos = 0, bool retain = false);
|
||||
|
||||
/**
|
||||
* @brief Set message received callback
|
||||
*/
|
||||
@@ -66,6 +77,10 @@ public:
|
||||
*/
|
||||
bool isConnected() const;
|
||||
|
||||
/** @brief Full topic strings (read-only, available after begin()) */
|
||||
const String& getAlertsTopic() const { return _alertsTopic; }
|
||||
const String& getInfoTopic() const { return _infoTopic; }
|
||||
|
||||
/**
|
||||
* @brief Handle network connection callback
|
||||
*/
|
||||
@@ -86,6 +101,8 @@ private:
|
||||
// Device topic strings (cached for performance)
|
||||
String _controlTopic;
|
||||
String _dataTopic;
|
||||
String _alertsTopic; // vesper/{id}/status/alerts
|
||||
String _infoTopic; // vesper/{id}/status/info
|
||||
String _clientId; // Store client ID to keep it alive
|
||||
|
||||
/**
|
||||
|
||||
@@ -98,7 +98,7 @@ void UARTDriver::processLine(const char* line) {
|
||||
if (strlen(line) == 0) return;
|
||||
|
||||
// Parse JSON
|
||||
StaticJsonDocument<1024> doc;
|
||||
JsonDocument doc;
|
||||
DeserializationError error = deserializeJson(doc, line);
|
||||
|
||||
if (error) {
|
||||
@@ -106,7 +106,7 @@ void UARTDriver::processLine(const char* line) {
|
||||
_errorCount++;
|
||||
|
||||
// Send error response back
|
||||
StaticJsonDocument<256> errorDoc;
|
||||
JsonDocument errorDoc;
|
||||
errorDoc["status"] = "ERROR";
|
||||
errorDoc["type"] = "parse_error";
|
||||
errorDoc["payload"] = error.c_str();
|
||||
|
||||
@@ -132,7 +132,7 @@ void WebSocketDriver::onData(AsyncWebSocketClient* client, void* arg, uint8_t* d
|
||||
LOG_DEBUG(TAG, "WebSocket client #%u sent: %s", client->id(), payload);
|
||||
|
||||
// Parse JSON
|
||||
StaticJsonDocument<2048> doc;
|
||||
JsonDocument doc;
|
||||
DeserializationError error = deserializeJson(doc, payload);
|
||||
|
||||
if (error) {
|
||||
|
||||
@@ -103,7 +103,7 @@ CommandResult FirmwareHandler::handleOtaCustom(const CommandEnvelope& e) {
|
||||
String url = e.contents["firmware_url"].as<String>();
|
||||
String checksum = e.contents["checksum"] | String("");
|
||||
size_t fileSize = e.contents["file_size"] | 0;
|
||||
uint16_t version = e.contents["version"] | 0;
|
||||
String version = e.contents["version"].as<String>();
|
||||
|
||||
LOG_WARNING(TAG, "Custom OTA update: %s", url.c_str());
|
||||
_otaManager.performCustomUpdate(url, checksum, fileSize, version);
|
||||
|
||||
@@ -21,7 +21,7 @@ String ResponseBuilder::fromResult(const CommandResult& result) {
|
||||
}
|
||||
|
||||
// Static member initialization
|
||||
StaticJsonDocument<512> ResponseBuilder::_responseDoc;
|
||||
JsonDocument ResponseBuilder::_responseDoc;
|
||||
|
||||
String ResponseBuilder::success(const String& type, const String& payload) {
|
||||
return buildResponse(Status::SUCCESS, type, payload);
|
||||
@@ -52,13 +52,13 @@ String ResponseBuilder::pong() {
|
||||
}
|
||||
|
||||
String ResponseBuilder::deviceStatus(PlayerStatus playerStatus, uint32_t timeElapsed, uint64_t projectedRunTime, const uint32_t strikeCounters[16]) {
|
||||
DynamicJsonDocument statusDoc(1024); // Increased size for strikeCounters array
|
||||
JsonDocument statusDoc;
|
||||
|
||||
statusDoc["status"] = "SUCCESS";
|
||||
statusDoc["type"] = "current_status";
|
||||
|
||||
// Create payload object with the exact format expected by Flutter
|
||||
JsonObject payload = statusDoc.createNestedObject("payload");
|
||||
JsonObject payload = statusDoc["payload"].to<JsonObject>();
|
||||
|
||||
// Convert PlayerStatus to string
|
||||
const char* statusStr;
|
||||
@@ -83,7 +83,7 @@ String ResponseBuilder::deviceStatus(PlayerStatus playerStatus, uint32_t timeEla
|
||||
payload["projected_run_time"] = projectedRunTime; // NEW: total projected duration
|
||||
|
||||
// Add strike counters array
|
||||
JsonArray strikeCountersArray = payload.createNestedArray("strike_counters");
|
||||
JsonArray strikeCountersArray = payload["strike_counters"].to<JsonArray>();
|
||||
for (uint8_t i = 0; i < 16; i++) {
|
||||
strikeCountersArray.add(strikeCounters[i]);
|
||||
}
|
||||
|
||||
@@ -90,5 +90,5 @@ public:
|
||||
private:
|
||||
// Internal helper methods
|
||||
static const char* statusToString(Status status);
|
||||
static StaticJsonDocument<512> _responseDoc; // Reusable document for efficiency
|
||||
static JsonDocument _responseDoc; // Reusable document for efficiency
|
||||
};
|
||||
|
||||
@@ -88,7 +88,7 @@ void HTTPTransport::handleCommandRequest(AsyncWebServerRequest* request,
|
||||
envelope.command = cmd;
|
||||
envelope.version = doc["v"] | 2;
|
||||
|
||||
if (doc.containsKey("contents")) {
|
||||
if (doc["contents"].is<JsonVariant>()) {
|
||||
envelope.contents.set(doc["contents"]);
|
||||
}
|
||||
|
||||
|
||||
@@ -256,51 +256,13 @@ bool ConfigManager::saveToSD() {
|
||||
return success;
|
||||
}
|
||||
|
||||
// Device configuration now only handles firmware version (identity is in NVS)
|
||||
// Firmware version is now owned by the binary (FW_VERSION in Version.hpp).
|
||||
// saveDeviceConfig / loadDeviceConfig are no-ops kept for call-site compatibility.
|
||||
bool ConfigManager::saveDeviceConfig() {
|
||||
if (!ensureSDCard()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
StaticJsonDocument<256> doc;
|
||||
doc["fwVersion"] = deviceConfig.fwVersion;
|
||||
|
||||
char buffer[256];
|
||||
size_t len = serializeJson(doc, buffer, sizeof(buffer));
|
||||
|
||||
if (len == 0 || len >= sizeof(buffer)) {
|
||||
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to serialize device config JSON");
|
||||
return false;
|
||||
}
|
||||
|
||||
saveFileToSD("/settings", "deviceConfig.json", buffer);
|
||||
LOG_DEBUG(TAG, "ConfigManager - Device config saved - FwVer: %s", deviceConfig.fwVersion.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ConfigManager::loadDeviceConfig() {
|
||||
if (!ensureSDCard()) return false;
|
||||
|
||||
File file = SD.open("/settings/deviceConfig.json", FILE_READ);
|
||||
if (!file) {
|
||||
LOG_WARNING(TAG, "ConfigManager - ⚠️ Device config file not found - using firmware version default");
|
||||
return false;
|
||||
}
|
||||
|
||||
StaticJsonDocument<512> doc;
|
||||
DeserializationError error = deserializeJson(doc, file);
|
||||
file.close();
|
||||
|
||||
if (error) {
|
||||
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to parse device config from SD: %s", error.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
if (doc.containsKey("fwVersion")) {
|
||||
deviceConfig.fwVersion = doc["fwVersion"].as<String>();
|
||||
LOG_VERBOSE(TAG, "ConfigManager - Firmware version loaded from SD: %s", deviceConfig.fwVersion.c_str());
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -790,7 +752,9 @@ std::vector<String> ConfigManager::getUpdateServers() const {
|
||||
for (const String& server : updateServers) {
|
||||
servers.push_back(server);
|
||||
}
|
||||
servers.push_back(updateConfig.fallbackServerUrl);
|
||||
for (const String& url : updateConfig.fallbackServerUrls) {
|
||||
if (!url.isEmpty()) servers.push_back(url);
|
||||
}
|
||||
return servers;
|
||||
}
|
||||
|
||||
@@ -1138,7 +1102,7 @@ String ConfigManager::getAllSettingsAsJson() const {
|
||||
device["uid"] = deviceConfig.deviceUID;
|
||||
device["hwType"] = deviceConfig.hwType;
|
||||
device["hwVersion"] = deviceConfig.hwVersion;
|
||||
device["fwVersion"] = deviceConfig.fwVersion;
|
||||
device["fwVersion"] = FW_VERSION;
|
||||
|
||||
// Network config
|
||||
JsonObject network = doc.createNestedObject("network");
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
#include <vector>
|
||||
#include <nvs_flash.h>
|
||||
#include <nvs.h>
|
||||
#include "../Version.hpp"
|
||||
|
||||
class ConfigManager {
|
||||
public:
|
||||
@@ -40,13 +41,12 @@ public:
|
||||
* @brief Factory-set device identity (NVS storage)
|
||||
*
|
||||
* These values are set once during manufacturing and stored in NVS.
|
||||
* fwVersion is updated automatically after OTA updates (SD storage).
|
||||
* fwVersion is NOT stored — it is always read from the compiled FW_VERSION constant.
|
||||
*/
|
||||
struct DeviceConfig {
|
||||
String deviceUID = ""; // 🏷️ Factory-set UID (NVS) - NO DEFAULT
|
||||
String hwType = ""; // 🔧 Factory-set hardware type (NVS) - NO DEFAULT
|
||||
String hwVersion = ""; // 📐 Factory-set hardware revision (NVS) - NO DEFAULT
|
||||
String fwVersion = "0"; // 📋 Current firmware version (SD) - auto-updated (integer string)
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -133,7 +133,10 @@ public:
|
||||
* Universal defaults for all devices.
|
||||
*/
|
||||
struct UpdateConfig {
|
||||
String fallbackServerUrl = "http://firmware.bonamin.space"; // 🛡️ Universal fallback - OK as is
|
||||
String fallbackServerUrls[2] = {
|
||||
"http://firmware.bellsystems.net", // 🥇 Primary fallback
|
||||
"http://firmware.bonamin.space" // 🥈 Secondary fallback
|
||||
};
|
||||
int timeout = 10000; // ⏱️ Universal timeout - OK as is
|
||||
int retries = 3; // 🔄 Universal retries - OK as is
|
||||
};
|
||||
@@ -313,10 +316,10 @@ public:
|
||||
String getDeviceUID() const { return deviceConfig.deviceUID; }
|
||||
String getHwType() const { return deviceConfig.hwType; }
|
||||
String getHwVersion() const { return deviceConfig.hwVersion; }
|
||||
String getFwVersion() const { return deviceConfig.fwVersion; }
|
||||
|
||||
/** @brief Set firmware version (auto-updated after OTA) */
|
||||
void setFwVersion(const String& version) { deviceConfig.fwVersion = version; }
|
||||
// Firmware version is owned by the binary — always returns the compiled-in constant.
|
||||
String getFwVersion() const { return FW_VERSION; }
|
||||
// No-op: version is compiled in, not stored. Kept for call-site compatibility.
|
||||
void setFwVersion(const String&) {}
|
||||
|
||||
// Configuration update methods for app commands
|
||||
void updateTimeConfig(long gmtOffsetSec, int daylightOffsetSec);
|
||||
|
||||
@@ -386,7 +386,10 @@ String HealthMonitor::getHealthSummary() const {
|
||||
|
||||
void HealthMonitor::updateSubsystemHealth(const String& name, HealthStatus status, const String& error) {
|
||||
auto it = _subsystemHealth.find(name);
|
||||
if (it != _subsystemHealth.end()) {
|
||||
if (it == _subsystemHealth.end()) return;
|
||||
|
||||
HealthStatus previousStatus = it->second.status;
|
||||
|
||||
it->second.status = status;
|
||||
it->second.lastError = error;
|
||||
it->second.lastCheck = millis();
|
||||
@@ -395,6 +398,15 @@ void HealthMonitor::updateSubsystemHealth(const String& name, HealthStatus statu
|
||||
name.c_str(),
|
||||
healthStatusToString(status).c_str(),
|
||||
error.isEmpty() ? "" : ("(" + error + ")").c_str());
|
||||
|
||||
// Fire alert callback only on actual state change
|
||||
if (_alertCallback && status != previousStatus) {
|
||||
if (status == HealthStatus::HEALTHY) {
|
||||
// Transitioning back to healthy — send CLEARED
|
||||
_alertCallback(name, "CLEARED", "");
|
||||
} else {
|
||||
_alertCallback(name, healthStatusToString(status), error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -48,6 +48,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <functional>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
@@ -250,6 +251,17 @@ public:
|
||||
*/
|
||||
void setAutoMonitoring(bool enabled) { _autoMonitoring = enabled; }
|
||||
|
||||
/**
|
||||
* @brief Register a callback invoked whenever a subsystem state changes.
|
||||
* The callback receives: subsystemName, newStateString, errorMessage.
|
||||
* Called with state "CLEARED" (empty message) when transitioning back to HEALTHY.
|
||||
* Safe to call before begin().
|
||||
*/
|
||||
using AlertCallback = std::function<void(const String& subsystem,
|
||||
const String& newState,
|
||||
const String& message)>;
|
||||
void setAlertCallback(AlertCallback cb) { _alertCallback = cb; }
|
||||
|
||||
private:
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// SUBSYSTEM REFERENCES
|
||||
@@ -272,6 +284,7 @@ private:
|
||||
TaskHandle_t _monitoringTaskHandle = nullptr;
|
||||
unsigned long _healthCheckInterval = 300000; // 5 minutes default
|
||||
bool _autoMonitoring = true;
|
||||
AlertCallback _alertCallback = nullptr; // Optional: fires on state change
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// PRIVATE HELPER METHODS
|
||||
|
||||
+171
-106
@@ -17,8 +17,8 @@ OTAManager::OTAManager(ConfigManager& configManager)
|
||||
, _telemetry(nullptr)
|
||||
, _status(Status::IDLE)
|
||||
, _lastError(ErrorCode::NONE)
|
||||
, _availableVersion(0.0f)
|
||||
, _minVersion(0.0f)
|
||||
, _availableVersion({0, 0, 0})
|
||||
, _minVersion({0, 0, 0})
|
||||
, _expectedFileSize(0)
|
||||
, _updateAvailable(false)
|
||||
, _availableChecksum("")
|
||||
@@ -222,9 +222,9 @@ void OTAManager::checkForUpdates(const String& channel) {
|
||||
channel.c_str(), _configManager.getHardwareVariant().c_str());
|
||||
|
||||
if (checkVersion(channel)) {
|
||||
uint16_t currentVersion = getCurrentVersion();
|
||||
LOG_INFO(TAG, "Current version: %u, Available version: %u (Channel: %s)",
|
||||
currentVersion, _availableVersion, channel.c_str());
|
||||
SemVer currentVersion = getCurrentVersion();
|
||||
LOG_INFO(TAG, "Current version: %s, Available version: %s (Channel: %s)",
|
||||
currentVersion.toString().c_str(), _availableVersion.toString().c_str(), channel.c_str());
|
||||
|
||||
if (_availableVersion > currentVersion) {
|
||||
_updateAvailable = true;
|
||||
@@ -276,10 +276,8 @@ void OTAManager::update(const String& channel) {
|
||||
}
|
||||
}
|
||||
|
||||
uint16_t OTAManager::getCurrentVersion() const {
|
||||
String fwVersionStr = _configManager.getFwVersion();
|
||||
// Parse integer directly: "130" -> 130
|
||||
return fwVersionStr.toInt();
|
||||
SemVer OTAManager::getCurrentVersion() const {
|
||||
return SemVer::parse(FW_VERSION);
|
||||
}
|
||||
|
||||
void OTAManager::setStatus(Status status, ErrorCode error) {
|
||||
@@ -297,16 +295,20 @@ void OTAManager::notifyProgress(size_t current, size_t total) {
|
||||
}
|
||||
}
|
||||
|
||||
// ✅ ENHANCED: Version checking with full validation
|
||||
// Version checking against new FastAPI backend
|
||||
// API: GET {baseUrl}/api/firmware/{hw_type}/{channel}/latest
|
||||
// Response: { "version": "1.2.3", "min_fw_version": "1.0.0", "sha256": "abc...",
|
||||
// "size": 123456, "update_type": "stable", "mandatory": true, "emergency": false }
|
||||
bool OTAManager::checkVersion(const String& channel) {
|
||||
std::vector<String> servers = _configManager.getUpdateServers();
|
||||
auto& updateConfig = _configManager.getUpdateConfig();
|
||||
String hwType = _configManager.getHardwareVariant();
|
||||
|
||||
for (size_t serverIndex = 0; serverIndex < servers.size(); serverIndex++) {
|
||||
String baseUrl = servers[serverIndex];
|
||||
String metadataUrl = baseUrl + "/ota/" + _configManager.getHardwareVariant() + "/" + channel + "/metadata.json";
|
||||
String metadataUrl = buildLatestUrl(baseUrl, hwType, channel);
|
||||
|
||||
LOG_INFO(TAG, "OTA: Trying server %d/%d: %s", serverIndex + 1, servers.size(), baseUrl.c_str());
|
||||
LOG_INFO(TAG, "OTA: Trying server %d/%d: %s", serverIndex + 1, servers.size(), metadataUrl.c_str());
|
||||
|
||||
HTTPClient http;
|
||||
http.setTimeout(updateConfig.timeout);
|
||||
@@ -315,13 +317,11 @@ bool OTAManager::checkVersion(const String& channel) {
|
||||
int retryCount = 0;
|
||||
int httpCode = -1;
|
||||
|
||||
// Retry logic for current server
|
||||
while (retryCount < updateConfig.retries && httpCode != HTTP_CODE_OK) {
|
||||
if (retryCount > 0) {
|
||||
LOG_INFO(TAG, "OTA: Retry %d/%d for %s", retryCount + 1, updateConfig.retries, baseUrl.c_str());
|
||||
LOG_INFO(TAG, "OTA: Retry %d/%d for server %d", retryCount + 1, updateConfig.retries, serverIndex + 1);
|
||||
delay(1000 * retryCount); // Exponential backoff
|
||||
}
|
||||
|
||||
httpCode = http.GET();
|
||||
retryCount++;
|
||||
}
|
||||
@@ -330,106 +330,105 @@ bool OTAManager::checkVersion(const String& channel) {
|
||||
String jsonStr = http.getString();
|
||||
http.end();
|
||||
|
||||
// Parse JSON metadata
|
||||
DynamicJsonDocument doc(1024);
|
||||
DeserializationError error = deserializeJson(doc, jsonStr);
|
||||
|
||||
if (error) {
|
||||
LOG_ERROR(TAG, "OTA: Failed to parse metadata JSON from %s: %s",
|
||||
baseUrl.c_str(), error.c_str());
|
||||
continue; // Try next server
|
||||
LOG_ERROR(TAG, "OTA: Failed to parse metadata JSON from server %d: %s", serverIndex + 1, error.c_str());
|
||||
continue;
|
||||
}
|
||||
|
||||
// Extract metadata - all integers now
|
||||
_availableVersion = doc["version"].as<uint16_t>();
|
||||
_availableChecksum = doc["checksum"].as<String>();
|
||||
_updateChannel = doc["channel"].as<String>();
|
||||
_isMandatory = doc["mandatory"].as<bool>();
|
||||
_isEmergency = doc["emergency"].as<bool>();
|
||||
_minVersion = doc["minVersion"].as<uint16_t>();
|
||||
_expectedFileSize = doc["fileSize"].as<size_t>();
|
||||
// FastAPI response fields
|
||||
const char* versionStr = doc["version"] | "";
|
||||
if (strlen(versionStr) == 0) {
|
||||
LOG_ERROR(TAG, "OTA: Missing 'version' field in metadata from server %d", serverIndex + 1);
|
||||
continue;
|
||||
}
|
||||
_availableVersion = SemVer::parse(String(versionStr));
|
||||
|
||||
// ✅ NEW: Validate channel matches requested
|
||||
if (_updateChannel != channel) {
|
||||
LOG_ERROR(TAG, "OTA: Channel mismatch! Requested: %s, Got: %s",
|
||||
channel.c_str(), _updateChannel.c_str());
|
||||
const char* minVersionStr = doc["min_fw_version"] | "";
|
||||
_minVersion = (strlen(minVersionStr) > 0) ? SemVer::parse(String(minVersionStr)) : SemVer{0, 0, 0};
|
||||
|
||||
_availableChecksum = doc["sha256"] | "";
|
||||
_expectedFileSize = doc["size"] | (size_t)0;
|
||||
_isMandatory = doc["mandatory"] | false;
|
||||
_isEmergency = doc["emergency"] | false;
|
||||
_updateChannel = channel; // channel is what we requested — server returns update_type
|
||||
|
||||
// Validate channel matches what server says
|
||||
const char* serverUpdateType = doc["update_type"] | "";
|
||||
if (strlen(serverUpdateType) > 0 && String(serverUpdateType) != channel) {
|
||||
LOG_ERROR(TAG, "OTA: Channel mismatch! Requested: %s, Got: %s", channel.c_str(), serverUpdateType);
|
||||
_lastError = ErrorCode::CHANNEL_MISMATCH;
|
||||
continue; // Try next server
|
||||
continue;
|
||||
}
|
||||
|
||||
// Validate hardware variant matches
|
||||
String hwVariant = doc["hardwareVariant"].as<String>();
|
||||
String ourHardwareVariant = _configManager.getHardwareVariant();
|
||||
if (!hwVariant.isEmpty() && hwVariant != ourHardwareVariant) {
|
||||
LOG_ERROR(TAG, "OTA: Hardware variant mismatch! Expected: %s, Got: %s",
|
||||
ourHardwareVariant.c_str(), hwVariant.c_str());
|
||||
continue; // Try next server
|
||||
// Validate version parsed correctly
|
||||
if (_availableVersion.isZero()) {
|
||||
LOG_ERROR(TAG, "OTA: Invalid version string '%s' from server %d", versionStr, serverIndex + 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
// ✅ NEW: Check minVersion compatibility
|
||||
uint16_t currentVersion = getCurrentVersion();
|
||||
if (_minVersion > 0 && currentVersion < _minVersion) {
|
||||
LOG_ERROR(TAG, "OTA: Current version %u is below minimum required %u",
|
||||
currentVersion, _minVersion);
|
||||
LOG_ERROR(TAG, "OTA: Intermediate update required first - cannot proceed");
|
||||
_lastError = ErrorCode::VERSION_TOO_LOW;
|
||||
continue; // Try next server
|
||||
// Validate checksum is a 64-char SHA256 hex string
|
||||
if (_availableChecksum.length() != 64) {
|
||||
LOG_ERROR(TAG, "OTA: Invalid sha256 length (%d) from server %d", _availableChecksum.length(), serverIndex + 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (_availableVersion == 0) {
|
||||
LOG_ERROR(TAG, "OTA: Invalid version in metadata from %s", baseUrl.c_str());
|
||||
continue; // Try next server
|
||||
// min_fw_version is informational only — the server already resolved the correct
|
||||
// next hop for our current_version, so we trust the version it returned.
|
||||
// We still log it for visibility.
|
||||
SemVer currentVersion = getCurrentVersion();
|
||||
if (!_minVersion.isZero() && currentVersion < _minVersion) {
|
||||
LOG_WARNING(TAG, "OTA: Server returned version %s with min_fw_version %s — server is handling upgrade chain",
|
||||
versionStr, _minVersion.toString().c_str());
|
||||
}
|
||||
|
||||
if (_availableChecksum.length() != 64) { // SHA256 is 64 hex characters
|
||||
LOG_ERROR(TAG, "OTA: Invalid checksum in metadata from %s", baseUrl.c_str());
|
||||
continue; // Try next server
|
||||
}
|
||||
LOG_INFO(TAG, "OTA: Metadata OK from server %d — version=%s, size=%u, mandatory=%s, emergency=%s",
|
||||
serverIndex + 1, versionStr, _expectedFileSize,
|
||||
_isMandatory ? "YES" : "NO", _isEmergency ? "YES" : "NO");
|
||||
return true;
|
||||
|
||||
LOG_INFO(TAG, "OTA: Successfully got metadata from %s", baseUrl.c_str());
|
||||
LOG_INFO(TAG, "OTA: Expected file size: %u bytes, Min version: %u",
|
||||
_expectedFileSize, _minVersion);
|
||||
return true; // Success!
|
||||
} else {
|
||||
LOG_ERROR(TAG, "OTA: Server %s failed after %d retries. HTTP error: %d",
|
||||
baseUrl.c_str(), updateConfig.retries, httpCode);
|
||||
LOG_ERROR(TAG, "OTA: Server %d failed after %d retries. HTTP code: %d",
|
||||
serverIndex + 1, updateConfig.retries, httpCode);
|
||||
http.end();
|
||||
}
|
||||
}
|
||||
|
||||
// All servers failed
|
||||
LOG_ERROR(TAG, "OTA: All %d servers failed to provide metadata", servers.size());
|
||||
_lastError = ErrorCode::HTTP_ERROR;
|
||||
return false;
|
||||
}
|
||||
|
||||
// ✅ ENHANCED: Download and install with size validation
|
||||
// Download and install firmware from new FastAPI backend
|
||||
// API: GET {baseUrl}/api/firmware/{hw_type}/{channel}/{version}/firmware.bin
|
||||
bool OTAManager::downloadAndInstall(const String& channel) {
|
||||
std::vector<String> servers = _configManager.getUpdateServers();
|
||||
String hwType = _configManager.getHardwareVariant();
|
||||
String toVersion = _availableVersion.toString();
|
||||
|
||||
for (size_t serverIndex = 0; serverIndex < servers.size(); serverIndex++) {
|
||||
String baseUrl = servers[serverIndex];
|
||||
String firmwareUrl = baseUrl + "/ota/" + _configManager.getHardwareVariant() + "/" + channel + "/firmware.bin";
|
||||
String firmwareUrl = buildFirmwareUrl(baseUrl, hwType, channel, toVersion);
|
||||
|
||||
LOG_INFO(TAG, "OTA: Trying firmware download from server %d/%d: %s",
|
||||
serverIndex + 1, servers.size(), baseUrl.c_str());
|
||||
serverIndex + 1, servers.size(), firmwareUrl.c_str());
|
||||
|
||||
// 🔥 Download directly to flash (bypassing problematic SD card writes)
|
||||
if (downloadDirectToFlash(firmwareUrl, _expectedFileSize)) {
|
||||
LOG_INFO(TAG, "✅ OTA update successful!");
|
||||
String fromVersion = getCurrentVersion().toString();
|
||||
if (downloadDirectToFlash(firmwareUrl, _expectedFileSize, fromVersion, toVersion, channel)) {
|
||||
LOG_INFO(TAG, "OTA: Firmware download and flash successful from server %d", serverIndex + 1);
|
||||
return true;
|
||||
} else {
|
||||
LOG_WARNING(TAG, "OTA: Firmware download failed from %s, trying next server", baseUrl.c_str());
|
||||
LOG_WARNING(TAG, "OTA: Firmware download failed from server %d, trying next", serverIndex + 1);
|
||||
}
|
||||
}
|
||||
|
||||
// All servers failed
|
||||
LOG_ERROR(TAG, "OTA: All %d servers failed to provide firmware", servers.size());
|
||||
return false;
|
||||
}
|
||||
|
||||
// 🔥 NEW: Download directly to flash memory, bypassing SD card
|
||||
bool OTAManager::downloadDirectToFlash(const String& url, size_t expectedSize) {
|
||||
bool OTAManager::downloadDirectToFlash(const String& url, size_t expectedSize, const String& fromVersion, const String& toVersion, const String& channel) {
|
||||
LOG_INFO(TAG, "OTA: Starting direct-to-flash download (bypassing SD card)");
|
||||
|
||||
HTTPClient http;
|
||||
@@ -570,16 +569,16 @@ bool OTAManager::downloadDirectToFlash(const String& url, size_t expectedSize) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Binary is fully written to the staged partition — report download event
|
||||
postDownloadTelemetry(fromVersion, toVersion, channel);
|
||||
|
||||
if (Update.end(true)) { // true = set new boot partition
|
||||
LOG_INFO(TAG, "OTA: Update complete!");
|
||||
if (Update.isFinished()) {
|
||||
setStatus(Status::SUCCESS);
|
||||
// Partition committed — report flash event before reboot
|
||||
postFlashTelemetry(fromVersion, toVersion, channel);
|
||||
LOG_INFO(TAG, "OTA: Firmware update successful. Rebooting...");
|
||||
|
||||
// Update version in config
|
||||
_configManager.setFwVersion(String(_availableVersion));
|
||||
_configManager.saveDeviceConfig();
|
||||
|
||||
delay(1000);
|
||||
ESP.restart();
|
||||
return true;
|
||||
@@ -998,10 +997,6 @@ bool OTAManager::installFromSD(const String& filePath) {
|
||||
}
|
||||
|
||||
delay(1000);
|
||||
// Version is already an integer - just convert to string: 130 -> "130"
|
||||
_configManager.setFwVersion(String(_availableVersion));
|
||||
_configManager.saveDeviceConfig();
|
||||
delay(500);
|
||||
ESP.restart();
|
||||
return true;
|
||||
} else {
|
||||
@@ -1088,7 +1083,7 @@ bool OTAManager::performManualUpdate(const String& channel) {
|
||||
// CUSTOM FIRMWARE UPDATE
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
bool OTAManager::performCustomUpdate(const String& firmwareUrl, const String& checksum, size_t fileSize, uint16_t version) {
|
||||
bool OTAManager::performCustomUpdate(const String& firmwareUrl, const String& checksum, size_t fileSize, const String& version) {
|
||||
if (_status != Status::IDLE) {
|
||||
LOG_WARNING(TAG, "OTA update already in progress");
|
||||
return false;
|
||||
@@ -1109,25 +1104,15 @@ bool OTAManager::performCustomUpdate(const String& firmwareUrl, const String& ch
|
||||
LOG_INFO(TAG, " Checksum: %s (NOTE: ESP32 will validate after flash)", checksum.c_str());
|
||||
}
|
||||
|
||||
if (version > 0) {
|
||||
LOG_INFO(TAG, " Target Version: %u", version);
|
||||
if (!version.isEmpty()) {
|
||||
LOG_INFO(TAG, " Target Version: %s", version.c_str());
|
||||
}
|
||||
|
||||
setStatus(Status::DOWNLOADING);
|
||||
|
||||
// Download directly to flash
|
||||
bool result = downloadDirectToFlash(firmwareUrl, fileSize);
|
||||
|
||||
if (result) {
|
||||
// Update version in config if provided
|
||||
if (version > 0) {
|
||||
_configManager.setFwVersion(String(version));
|
||||
_configManager.saveDeviceConfig();
|
||||
LOG_INFO(TAG, "✅ Custom firmware version %u saved to NVS", version);
|
||||
} else {
|
||||
LOG_WARNING(TAG, "⚠️ No version provided - NVS version unchanged");
|
||||
}
|
||||
|
||||
LOG_INFO(TAG, "🚀 Custom firmware installed - device will reboot");
|
||||
} else {
|
||||
LOG_ERROR(TAG, "❌ Custom firmware installation failed");
|
||||
@@ -1145,20 +1130,101 @@ void OTAManager::setHardwareVariant(const String& variant) {
|
||||
LOG_WARNING(TAG, "OTAManager::setHardwareVariant is deprecated. Use ConfigManager::setHardwareVariant instead");
|
||||
}
|
||||
|
||||
// URL builders for multi-channel architecture
|
||||
String OTAManager::buildChannelUrl(const String& channel) const {
|
||||
auto& updateConfig = _configManager.getUpdateConfig();
|
||||
String baseUrl = updateConfig.fallbackServerUrl;
|
||||
|
||||
return baseUrl + "/" + _configManager.getHardwareVariant() + "/" + channel + "/";
|
||||
// URL builders for FastAPI backend
|
||||
// GET /api/firmware/{hw_type}/{channel}/latest?current_version={semver}
|
||||
// Passing current_version lets the server resolve upgrade chains and return the
|
||||
// correct next hop instead of the absolute latest.
|
||||
String OTAManager::buildLatestUrl(const String& baseUrl, const String& hwType, const String& channel) const {
|
||||
String currentVersion = getCurrentVersion().toString();
|
||||
return baseUrl + "/api/firmware/" + hwType + "/" + channel + "/latest?current_version=" + currentVersion;
|
||||
}
|
||||
|
||||
String OTAManager::buildMetadataUrl(const String& channel) const {
|
||||
return buildChannelUrl(channel) + "metadata.json";
|
||||
// GET /api/firmware/{hw_type}/{channel}/{version}/info
|
||||
String OTAManager::buildVersionInfoUrl(const String& baseUrl, const String& hwType, const String& channel, const String& version) const {
|
||||
return baseUrl + "/api/firmware/" + hwType + "/" + channel + "/" + version + "/info";
|
||||
}
|
||||
|
||||
String OTAManager::buildFirmwareUrl(const String& channel) const {
|
||||
return buildChannelUrl(channel) + "firmware.bin";
|
||||
// GET /api/firmware/{hw_type}/{channel}/{version}/firmware.bin
|
||||
String OTAManager::buildFirmwareUrl(const String& baseUrl, const String& hwType, const String& channel, const String& version) const {
|
||||
return baseUrl + "/api/firmware/" + hwType + "/" + channel + "/" + version + "/firmware.bin";
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
// OTA TELEMETRY - POST events to backend for fleet visibility
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
// Called after the firmware binary has been fully downloaded and written to flash,
|
||||
// but BEFORE Update.end() is called (i.e. the new partition is staged but not yet active).
|
||||
// POST /api/ota/events/download
|
||||
void OTAManager::postDownloadTelemetry(const String& fromVersion, const String& toVersion, const String& channel) {
|
||||
if (WiFi.status() != WL_CONNECTED) return;
|
||||
|
||||
std::vector<String> servers = _configManager.getUpdateServers();
|
||||
if (servers.empty()) return;
|
||||
|
||||
// Use primary server only — this is best-effort, not critical path
|
||||
String url = servers[0] + "/api/ota/events/download";
|
||||
|
||||
DynamicJsonDocument doc(256);
|
||||
doc["device_uid"] = _configManager.getDeviceUID();
|
||||
doc["hw_type"] = _configManager.getHardwareVariant();
|
||||
doc["hw_version"] = _configManager.getHwVersion();
|
||||
doc["from_version"] = fromVersion;
|
||||
doc["to_version"] = toVersion;
|
||||
doc["channel"] = channel;
|
||||
|
||||
String body;
|
||||
serializeJson(doc, body);
|
||||
|
||||
HTTPClient http;
|
||||
http.begin(url.c_str());
|
||||
http.addHeader("Content-Type", "application/json");
|
||||
http.setTimeout(5000);
|
||||
|
||||
int code = http.POST(body);
|
||||
if (code == HTTP_CODE_OK || code == HTTP_CODE_CREATED || code == 204) {
|
||||
LOG_INFO(TAG, "OTA: Download event reported to backend (HTTP %d)", code);
|
||||
} else {
|
||||
LOG_WARNING(TAG, "OTA: Download event POST failed (HTTP %d) — non-critical, continuing", code);
|
||||
}
|
||||
http.end();
|
||||
}
|
||||
|
||||
// Called immediately after Update.end() succeeds — the new firmware is committed
|
||||
// to the boot partition and the device is about to restart.
|
||||
// POST /api/ota/events/flash
|
||||
void OTAManager::postFlashTelemetry(const String& fromVersion, const String& toVersion, const String& channel) {
|
||||
if (WiFi.status() != WL_CONNECTED) return;
|
||||
|
||||
std::vector<String> servers = _configManager.getUpdateServers();
|
||||
if (servers.empty()) return;
|
||||
|
||||
String url = servers[0] + "/api/ota/events/flash";
|
||||
|
||||
DynamicJsonDocument doc(256);
|
||||
doc["device_uid"] = _configManager.getDeviceUID();
|
||||
doc["hw_type"] = _configManager.getHardwareVariant();
|
||||
doc["hw_version"] = _configManager.getHwVersion();
|
||||
doc["from_version"] = fromVersion;
|
||||
doc["to_version"] = toVersion;
|
||||
doc["channel"] = channel;
|
||||
doc["sha256"] = _availableChecksum;
|
||||
|
||||
String body;
|
||||
serializeJson(doc, body);
|
||||
|
||||
HTTPClient http;
|
||||
http.begin(url.c_str());
|
||||
http.addHeader("Content-Type", "application/json");
|
||||
http.setTimeout(5000);
|
||||
|
||||
int code = http.POST(body);
|
||||
if (code == HTTP_CODE_OK || code == HTTP_CODE_CREATED || code == 204) {
|
||||
LOG_INFO(TAG, "OTA: Flash event reported to backend (HTTP %d)", code);
|
||||
} else {
|
||||
LOG_WARNING(TAG, "OTA: Flash event POST failed (HTTP %d) — non-critical, continuing", code);
|
||||
}
|
||||
http.end();
|
||||
}
|
||||
|
||||
// ✅ NEW: Check if player is currently active
|
||||
@@ -1226,9 +1292,8 @@ bool OTAManager::isHealthy() const {
|
||||
return false;
|
||||
}
|
||||
|
||||
String fwVersion = _configManager.getFwVersion();
|
||||
if (fwVersion.isEmpty() || fwVersion == "0") {
|
||||
LOG_DEBUG(TAG, "OTAManager: Unhealthy - Invalid firmware version: %s", fwVersion.c_str());
|
||||
if (getCurrentVersion().isZero()) {
|
||||
LOG_DEBUG(TAG, "OTAManager: Unhealthy - Firmware version is 0.0.0");
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
#include "../FileManager/FileManager.hpp"
|
||||
#include "../Telemetry/Telemetry.hpp"
|
||||
#include "../TimeKeeper/TimeKeeper.hpp"
|
||||
#include "../Version.hpp"
|
||||
|
||||
class ConfigManager; // Forward declaration
|
||||
class Player; // Forward declaration for idle check
|
||||
@@ -83,7 +84,7 @@ public:
|
||||
void checkFirmwareUpdateFromSD(); // Check SD for firmware update
|
||||
bool performManualUpdate(); // Manual update triggered by app
|
||||
bool performManualUpdate(const String& channel); // Manual update from specific channel
|
||||
bool performCustomUpdate(const String& firmwareUrl, const String& checksum = "", size_t fileSize = 0, uint16_t version = 0); // Custom firmware update
|
||||
bool performCustomUpdate(const String& firmwareUrl, const String& checksum = "", size_t fileSize = 0, const String& version = ""); // Custom firmware update
|
||||
|
||||
// Hardware identification
|
||||
String getHardwareVariant() const;
|
||||
@@ -92,8 +93,8 @@ public:
|
||||
// Status and info
|
||||
Status getStatus() const { return _status; }
|
||||
ErrorCode getLastError() const { return _lastError; }
|
||||
uint16_t getCurrentVersion() const;
|
||||
uint16_t getAvailableVersion() const { return _availableVersion; }
|
||||
SemVer getCurrentVersion() const;
|
||||
SemVer getAvailableVersion() const { return _availableVersion; }
|
||||
bool isUpdateAvailable() const { return _updateAvailable; }
|
||||
|
||||
// Callbacks
|
||||
@@ -115,8 +116,8 @@ private:
|
||||
Telemetry* _telemetry; // Telemetry reference for freeze mode
|
||||
Status _status;
|
||||
ErrorCode _lastError;
|
||||
uint16_t _availableVersion;
|
||||
uint16_t _minVersion; // NEW: Minimum required version
|
||||
SemVer _availableVersion;
|
||||
SemVer _minVersion;
|
||||
size_t _expectedFileSize; // NEW: Expected firmware file size
|
||||
bool _updateAvailable;
|
||||
String _availableChecksum;
|
||||
@@ -156,14 +157,20 @@ private:
|
||||
bool checkChannelsMetadata();
|
||||
bool downloadAndInstall();
|
||||
bool downloadAndInstall(const String& channel);
|
||||
bool downloadDirectToFlash(const String& url, size_t expectedSize); // NEW: Direct to flash (bypasses SD)
|
||||
bool downloadToSD(const String& url, const String& expectedChecksum, size_t expectedSize); // OLD: Via SD card
|
||||
bool downloadDirectToFlash(const String& url, size_t expectedSize, const String& fromVersion, const String& toVersion, const String& channel);
|
||||
bool downloadToSD(const String& url, const String& expectedChecksum, size_t expectedSize);
|
||||
bool verifyChecksum(const String& filePath, const String& expectedChecksum);
|
||||
String calculateSHA256(const String& filePath);
|
||||
bool installFromSD(const String& filePath);
|
||||
String buildChannelUrl(const String& channel) const;
|
||||
String buildMetadataUrl(const String& channel) const;
|
||||
String buildFirmwareUrl(const String& channel) const;
|
||||
|
||||
// FastAPI URL builders
|
||||
String buildLatestUrl(const String& baseUrl, const String& hwType, const String& channel) const;
|
||||
String buildVersionInfoUrl(const String& baseUrl, const String& hwType, const String& channel, const String& version) const;
|
||||
String buildFirmwareUrl(const String& baseUrl, const String& hwType, const String& channel, const String& version) const;
|
||||
|
||||
// OTA telemetry — best-effort POSTs, never block or fail the update
|
||||
void postDownloadTelemetry(const String& fromVersion, const String& toVersion, const String& channel);
|
||||
void postFlashTelemetry(const String& fromVersion, const String& toVersion, const String& channel);
|
||||
|
||||
// NEW: Helper methods
|
||||
bool isPlayerActive() const;
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
// FIRMWARE VERSION
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
// Format: MAJOR.MINOR.PATCH (e.g. "2.0.0")
|
||||
// This is the single source of truth. It is compiled into the binary
|
||||
// and never stored in NVS — the binary IS the version.
|
||||
//
|
||||
// VERSION HISTORY:
|
||||
// v154 (legacy integer) - Last integer-versioned release
|
||||
// v2.0.0 - First SemVer release
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
#define FW_VERSION "2.0.0"
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
// SemVer — lightweight 3-part version struct
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
struct SemVer {
|
||||
uint8_t major;
|
||||
uint8_t minor;
|
||||
uint8_t patch;
|
||||
|
||||
// Parse "2.0.0" or legacy integer "154" (treated as 0.0.154)
|
||||
static SemVer parse(const String& s) {
|
||||
SemVer v{0, 0, 0};
|
||||
int first = s.indexOf('.');
|
||||
if (first == -1) {
|
||||
// Legacy integer format: "154" -> {0, 0, 154}
|
||||
// Clamp to uint8_t range; values > 255 are stored in minor too
|
||||
uint16_t n = (uint16_t)s.toInt();
|
||||
v.minor = (uint8_t)(n / 100);
|
||||
v.patch = (uint8_t)(n % 100);
|
||||
return v;
|
||||
}
|
||||
int second = s.indexOf('.', first + 1);
|
||||
v.major = (uint8_t)s.substring(0, first).toInt();
|
||||
if (second == -1) {
|
||||
v.minor = (uint8_t)s.substring(first + 1).toInt();
|
||||
} else {
|
||||
v.minor = (uint8_t)s.substring(first + 1, second).toInt();
|
||||
v.patch = (uint8_t)s.substring(second + 1).toInt();
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
bool operator==(const SemVer& o) const {
|
||||
return major == o.major && minor == o.minor && patch == o.patch;
|
||||
}
|
||||
bool operator!=(const SemVer& o) const { return !(*this == o); }
|
||||
bool operator<(const SemVer& o) const {
|
||||
if (major != o.major) return major < o.major;
|
||||
if (minor != o.minor) return minor < o.minor;
|
||||
return patch < o.patch;
|
||||
}
|
||||
bool operator>(const SemVer& o) const { return o < *this; }
|
||||
bool operator<=(const SemVer& o) const { return !(o < *this); }
|
||||
bool operator>=(const SemVer& o) const { return !(*this < o); }
|
||||
|
||||
bool isZero() const { return major == 0 && minor == 0 && patch == 0; }
|
||||
|
||||
String toString() const {
|
||||
return String(major) + "." + String(minor) + "." + String(patch);
|
||||
}
|
||||
};
|
||||
+2
-39
@@ -56,33 +56,7 @@
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════
|
||||
* 📋 VERSION CONFIGURATION
|
||||
* ═══════════════════════════════════════════════════════════════════════════════
|
||||
* 📅 DATE: 2025-10-10
|
||||
* 👨💻 AUTHOR: BellSystems bonamin
|
||||
*/
|
||||
|
||||
#define FW_VERSION "154"
|
||||
|
||||
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════
|
||||
* 📅 VERSION HISTORY:
|
||||
* NOTE: Versions are now stored as integers (v1.3 = 130)
|
||||
* ═══════════════════════════════════════════════════════════════════════════════
|
||||
* v0.1 (100) - Vesper Launch Beta
|
||||
* v1.2 (120) - Added Log Level Configuration via App/MQTT
|
||||
* v1.3 (130) - Added Telemetry Reports to App, Various Playback Fixes
|
||||
* v137 - Made OTA and MQTT delays Async
|
||||
* v138 - Removed Ethernet, added default WiFi creds (Mikrotik AP) and fixed various Clock issues
|
||||
* v140 - Changed FW Updates to Direct-to-Flash and added manual update functionality with version check
|
||||
* v151 - Fixed Clock Alerts not running properly
|
||||
* v152 - Fix RTC Time Reports, added sync_time_to_LCD functionality
|
||||
* v153 - Fix Infinite Loop Bug and Melody Download crashes.
|
||||
* ═══════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
// Firmware version is defined in Version.hpp (FW_VERSION)
|
||||
|
||||
|
||||
|
||||
@@ -143,6 +117,7 @@
|
||||
#include "HealthMonitor/HealthMonitor.hpp"
|
||||
#include "FirmwareValidator/FirmwareValidator.hpp"
|
||||
#include "InputManager/InputManager.hpp"
|
||||
#include "Version.hpp"
|
||||
|
||||
#define TAG "Main"
|
||||
|
||||
@@ -257,18 +232,6 @@ void setup()
|
||||
|
||||
// Update firmware version (this is the ONLY identity field that can be set)
|
||||
|
||||
// 🔥 MIGRATION: Convert old float-style version to integer format
|
||||
String currentVersion = configManager.getFwVersion();
|
||||
if (currentVersion.indexOf('.') != -1) {
|
||||
// Old format detected (e.g., "1.3"), convert to integer ("130")
|
||||
float versionFloat = currentVersion.toFloat();
|
||||
uint16_t versionInt = (uint16_t)(versionFloat * 100.0f);
|
||||
configManager.setFwVersion(String(versionInt));
|
||||
configManager.saveDeviceConfig();
|
||||
LOG_INFO(TAG, "⚠️ Migrated version format: %s -> %u", currentVersion.c_str(), versionInt);
|
||||
}
|
||||
|
||||
configManager.setFwVersion(FW_VERSION);
|
||||
LOG_INFO(TAG, "Firmware version: %s", FW_VERSION);
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user