feat: multi-board HAL guards, RFRemote subsystem, Player/OTA improvements

Multi-board variant support:
- variants/vesper.hpp: enable HAS_RF=1, define RF_RX_PIN=22
- variants/agnus.hpp: enable HAS_RF=1, RF_RX_PIN=22, correct HAS_RTC=0
- main.cpp, Player, HealthMonitor, OTAManager, ConfigManager: wrap all
  RTC/SD/RF-dependent code in #if HAS_RTC / HAS_SD_CARD / HAS_RF guards
  so Agnus builds cleanly without those peripherals

RFRemote subsystem (new):
- src/RFRemote/: RF receiver driver (GPIO RF_RX_PIN) + command handler
- Registered with HealthMonitor and CommunicationRouter when HAS_RF=1

Player improvements:
- uid -> pid rename throughout (Player, BuiltInMelodies, api-reference)
- loadMelodyInRAM() now returns bool
- playerControlTaskFn task added — defers stop/pause/resume out of
  timer callback (Tmr Svc) to avoid stack overflows
- setDependencies() accepts nullptr FileManager for SD-less boards

OTAManager:
- Consume download_url from server metadata response instead of
  constructing firmware path locally
- HTTP redirect following enabled (setFollowRedirects)
- HAS_RTC guards on TimeKeeper references

platformio.ini:
- Add rc-switch library for RF remote support
- Remove BOARD_TYPE/BOARD_NAME/BOARD_VERSION flags (moved to variant headers)
- MQTT_SECRET placeholders only — no secrets in source

Docs:
- docs/architecture/codebase-refactor-plan.md: new migration strategy doc
- docs/reference/api-reference.md: updated for pid, note_assignments, download_url
- Remove stale docs: ota-telemetry-api.md, platformio-commands.md, firmware-variants.md

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-17 17:02:01 +02:00
co-authored by Claude Sonnet 4.6
parent 37b65cc15a
commit a4d071d5d5
31 changed files with 2431 additions and 891 deletions
+320
View File
@@ -0,0 +1,320 @@
# BellSystems Firmware Architecture — Strategy & Migration Guide
> **Status:** Planning document for the next-generation firmware codebase.
> **Scope:** Vesper and Agnus product lines (ESP32-based). Excludes future dual-MCU / RPi variants — those will be separate projects.
---
## 1. Context & Decisions Already Made
- All currently deployed devices run the **same hardware** (KC868-A6). Agnus units simply have RTC and SD disabled in firmware and ship with a more affordable tablet.
- Going forward, **Vesper and Agnus will have their own PCBs**, but both use ESP32. Agnus will be stripped down (no RTC, no SD, no extras). Vesper keeps those and may gain sensors on higher-end variants.
- The **current project stays frozen** as-is — it keeps running on all deployed units. The new architecture starts fresh in a new folder/project, migrated by Claude Code when ready.
- Future **dual-MCU or RPi-based** products will be entirely separate projects and are out of scope here.
---
## 2. Why the Current HAL Still Works
Since both Vesper and Agnus use ESP32 with the same SDK, toolchain, and similar peripherals, a single PlatformIO project with a HAL layer is the correct approach. There is no need to split into separate repos or branches for these two families.
The problem with the *current* codebase is not the HAL concept — it's that board-specific logic leaks into shared code via `#ifdef` chains, and there's no clean separation between "what the system does" and "how the hardware does it."
The current variant system (`variants/vesper.hpp`, `variants/agnus.hpp`) is a step in the right direction but it only defines compile-time capability flags — it doesn't enforce a proper driver boundary. The new project fixes that with a stricter folder structure and clearer rules about what lives where.
---
## 3. New Project Structure
```
/bellsystems-firmware/
│
├── platformio.ini ← all board environments defined here
│
├── lib/
│ ├── core/ ← shared business logic, NO hardware calls
│ │ ├── BellEngine/ ← microsecond-precision bell timing (Core 1)
│ │ ├── Player/ ← melody playback control & timing
│ │ ├── Scheduler/ ← clock pulse / scheduled bell events
│ │ ├── CommandBus/ ← O(1) command dispatch, ICommandHandler
│ │ ├── CommunicationRouter/ ← transport orchestration, publish/broadcast
│ │ ├── Handlers/ ← PlaybackHandler, RelayHandler, SystemHandler, etc.
│ │ ├── MqttManager/ ← MQTT auth, topic management, reconnect logic
│ │ ├── ConfigManager/ ← factory (NVS) + user (storage) settings
│ │ ├── HealthMonitor/ ← subsystem health polling, rollback decisions
│ │ ├── OTAManager/ ← version checking, download, flash
│ │ ├── FirmwareValidator/ ← startup validation, runtime monitoring
│ │ ├── Telemetry/ ← bell strike tracking, load monitoring
│ │ ├── Logging/ ← three-channel log (Serial/MQTT/SD)
│ │ └── SystemInfo/ ← version, device identity
│ │
│ ├── hal/ ← interfaces (abstract classes) ONLY
│ │ ├── IOutputDriver.h ← setOutput(ch, state), getOutputCount()
│ │ ├── IRtcDriver.h ← getTime(), setTime(), isPresent()
│ │ ├── IStorageDriver.h ← read/write files, listDir, exists
│ │ ├── INetworkDriver.h ← connect, disconnect, getIP, isConnected
│ │ └── IDisplayDriver.h ← (future: Agnus Mini LCD)
│ │
│ ├── drivers/ ← concrete hardware implementations
│ │ ├── output/
│ │ │ ├── Pcf8574OutputDriver/ ← current: PCF8574/PCF8575 I2C expanders
│ │ │ └── DirectGpioOutputDriver/ ← fallback for direct GPIO
│ │ ├── rtc/
│ │ │ └── Ds3231Driver/ ← current: DS3231 RTC
│ │ ├── storage/
│ │ │ ├── SdCardDriver/ ← current: SD via SPI
│ │ │ └── NvsOnlyDriver/ ← current: Agnus config-only fallback
│ │ ├── network/
│ │ │ └── WifiDriver/ ← current: WiFi (Ethernet removed v138)
│ │ └── display/
│ │ └── OledDriver/ ← (future: Agnus Mini)
│ │
│ └── features/ ← optional, self-contained modules
│ ├── RfRemote/ ← current: RF receiver on GPIO 22 (HAS_RF=1)
│ ├── Rs485RelayBridge/ ← bespoke client: Waveshare 16-output RS485
│ ├── TemperatureSensor/ ← (future: Vesper Pro sensors)
│ └── UdpDiscovery/ ← current: UDP broadcast for local discovery
│
├── boards/
│ ├── agnus/
│ │ ├── main.cpp
│ │ ├── board_config.h ← pin definitions, compile-time caps
│ │ └── board_init.cpp ← wires drivers to HAL interfaces
│ │
│ ├── agnus_mini/
│ │ └── ...
│ │
│ ├── vesper/
│ │ ├── main.cpp
│ │ ├── board_config.h
│ │ └── board_init.cpp
│ │
│ ├── vesper_plus/
│ │ └── ... ← adds RF, sensors vs base Vesper
│ │
│ └── bespoke_rs485/ ← one-off client board
│ ├── main.cpp
│ ├── board_config.h
│ └── board_init.cpp
│
└── scripts/ ← build helpers, OTA tools, NVS gen, etc.
```
---
## 4. Layer Rules — The Hard Lines
These rules are what make the architecture actually work. Breaking them is how codebases turn into spaghetti.
### `lib/core/`
- **Zero** hardware calls. No `GPIO`, no `Wire`, no `SPI`, no SDK includes.
- Calls hardware only through HAL interfaces (pointers/references to abstract classes).
- No `#ifdef BOARD_X` anywhere inside this folder. Ever.
- This is the code you write once and never touch again for hardware reasons.
### `lib/hal/`
- Pure abstract classes (interfaces). No implementation.
- Example: `IOutputDriver` declares `virtual void setOutput(uint8_t ch, bool state) = 0;`
- Core code depends only on these. Never on concrete drivers.
### `lib/drivers/`
- Each driver implements exactly one HAL interface.
- A driver may use SDK calls, SPI, I2C, whatever it needs.
- A driver must **not** know about MQTT, bell melodies, scheduling, or any core concept.
- If a driver is not needed for a board, it is simply not compiled in (not referenced in that board's `platformio.ini`).
### `lib/features/`
- Optional modules that add functionality not present on all boards.
- A feature may use drivers and core, but must be guarded by a compile flag.
- Example: `RfRemote` only compiles when `-D HAS_RF=1` is set.
- Features that are one-off and unlikely to ship broadly (like the RS485 bridge) live here and are simply never enabled on other boards.
### `boards/X/`
- The **only** place where drivers are selected and wired to HAL interfaces.
- The only place `board_config.h` lives (pins, output counts, feature flags).
- `board_init.cpp` instantiates the concrete drivers and passes them to core systems.
- This is intentionally thin — just wiring, no logic.
---
## 5. `platformio.ini` Structure
```ini
; ── Shared base (common flags, libs, framework) ──────────────────────────
[env:base]
platform = espressif32
framework = arduino
monitor_speed = 115200
lib_deps =
knolleary/PubSubClient
bblanchon/ArduinoJson
; ... other shared deps
; ── Agnus ─────────────────────────────────────────────────────────────────
[env:agnus]
extends = env:base
board = esp32dev
build_src_filter = +<../boards/agnus/>
build_flags =
${env:base.build_flags}
-D BOARD_AGNUS
-D HW_FAMILY="agnus"
-D OUTPUT_COUNT=3
-D HAS_RTC=0
-D HAS_SD_CARD=0
-D HAS_RF=1
; ── Vesper ────────────────────────────────────────────────────────────────
[env:vesper]
extends = env:base
board = esp32dev
build_src_filter = +<../boards/vesper/>
build_flags =
${env:base.build_flags}
-D BOARD_VESPER
-D HW_FAMILY="vesper"
-D OUTPUT_COUNT=6
-D HAS_RTC=1
-D HAS_SD_CARD=1
-D HAS_RF=1
-D HAS_PCF8574=1
; ── Bespoke RS485 Client ──────────────────────────────────────────────────
[env:bespoke_rs485]
extends = env:vesper
build_src_filter = +<../boards/bespoke_rs485/>
build_flags =
${env:vesper.build_flags}
-D BOARD_BESPOKE_RS485
-D OUTPUT_COUNT=16
-D FEATURE_RS485=1
```
---
## 6. Handling the Bespoke RS485 Client
This client needs 16 outputs via a Waveshare RS485 relay board. Here is exactly how to handle it without polluting the rest of the codebase:
1. Create `lib/features/Rs485RelayBridge/` — the driver that talks to the Waveshare board over RS485/Modbus.
2. Create `boards/bespoke_rs485/` — extends Vesper config, enables `FEATURE_RS485`.
3. In `boards/bespoke_rs485/board_init.cpp`, wire the RS485 driver to `IOutputDriver` instead of the PCF8574 driver.
4. Ship this client a binary built from `env:bespoke_rs485`. They always get OTA updates from **this environment only**.
5. Future Vesper updates never touch this environment. No code removal needed — it simply isn't compiled into other targets.
**Git strategy for this client:** No branch needed. The `bespoke_rs485` board folder in `main` is sufficient. The environment isolation is the protection. If the client ever needs a frozen firmware version, tag it: `release/bespoke-rs485-v1.0`.
---
## 7. Feature Flags Pattern
Inside a driver or feature file that is conditionally compiled:
```cpp
// boards/vesper/board_init.cpp
#include "board_config.h"
#if HAS_RTC
#include <drivers/rtc/Ds3231Driver.h>
Ds3231Driver rtcDriver;
#endif
#if HAS_SD_CARD
#include <drivers/storage/SdCardDriver.h>
SdCardDriver storageDriver;
#else
#include <drivers/storage/NvsOnlyDriver.h>
NvsOnlyDriver storageDriver;
#endif
void boardInit() {
// Wire drivers to core systems
BellEngine::init(&outputDriver);
ConfigManager::setStorage(&storageDriver);
#if HAS_RTC
Scheduler::setRtc(&rtcDriver);
#endif
#if HAS_RF
RfRemote::begin();
#endif
}
```
The rule: `#if HAS_X` / `#if FEATURE_X` blocks live **only** in `boards/` and `lib/features/`. Never in `lib/core/`.
---
## 8. Product Capability Mapping
| Board Env | MCU | RTC | SD | Ethernet | Outputs | Extra Features |
|---|---|---|---|---|---|---|
| `agnus` | ESP32 | ✗ | ✗ | ✗ | 3 | RF |
| `agnus_mini` | ESP32 | ✗ | ✗ | ✗ | 1 | RF, 7" LCD |
| `vesper` | ESP32 | ✓ | ✓ | ✗ | 6 | RF |
| `vesper_plus` | ESP32 | ✓ | ✓ | ✗ | 10 | RF, Sensors |
| `bespoke_rs485` | ESP32 | ✓ | ✓ | ✗ | 16 | RS485 Bridge |
> Note: Ethernet was removed in firmware v138. All boards are WiFi-only for the foreseeable future.
---
## 9. What Needs Cleaning Up in the Current Codebase
Before migration, it's worth noting the main structural problems in the current `src/` tree that the new architecture resolves:
- **`BellEngine`** depends directly on `ConfigManager`, `Telemetry`, `OutputManager`, and `Player` — all injected via constructor. Clean, but `OutputManager` is a concrete class, not an interface. In the new project it becomes `IOutputDriver`.
- **`ConfigManager`** does too much: NVS factory settings, SD user settings, and MQTT auth derivation. In the new project these separate into `DeviceConfig` (NVS, read-only), `UserConfig` (storage driver), and `MqttAuth` (core utility).
- **`FileManager`** is tightly coupled to SD. In the new project it becomes `IStorageDriver` with `SdCardDriver` and `NvsOnlyDriver` implementations.
- **`HealthMonitor`** has hardcoded knowledge of which subsystems are critical vs warning. In the new project subsystems register themselves with a severity level.
- **`main.cpp`** is the wiring layer but also contains NTP sync logic, UDP discovery, and loop management. In the new project `main.cpp` is pure board init wiring; everything else moves to its module.
- **`variants/vesper.hpp`** / **`variants/agnus.hpp`** are capability flag headers — good pattern, wrong location. In the new project these become `board_config.h` inside each board folder.
- **`CommunicationRouter`** + `CommandBus` + `ITransport` pattern is already close to the target architecture. Port it as-is.
---
## 10. Migration Plan (Current → New Project)
When ready to start the new project, the migration order matters. Do it in this sequence to avoid rewriting things twice:
1. **Scaffold** — new PlatformIO project, folder structure, `platformio.ini` with all envs (empty builds that compile clean).
2. **HAL interfaces** — write all `IXxxDriver.h` abstract classes first, before any implementation.
3. **Port core modules** — migrate `BellEngine`, `Player`, `ConfigManager`, `CommunicationRouter`+`CommandBus`+handlers one by one. Compile-check against HAL interfaces only.
4. **Port drivers** — migrate concrete hardware code into `lib/drivers/`. One driver at a time:
- `Pcf8574OutputDriver` (from `OutputManager`)
- `Ds3231Driver` (from `Timekeeper`)
- `SdCardDriver` (from `FileManager`)
- `NvsOnlyDriver` (new, from Agnus config path in `ConfigManager`)
- `WifiDriver` (from `Networking`)
5. **Wire Vesper first** — `boards/vesper/board_init.cpp`. Get one full board building and running before touching others.
6. **Wire Agnus** — derive from Vesper wiring, remove RTC/SD, verify Agnus env compiles and runs correctly.
7. **Port features** — `RfRemote`, `UdpDiscovery` into `lib/features/`.
8. **Add bespoke_rs485** — implement RS485 feature module, wire into its board env.
9. **Freeze current project** — once new project is verified on hardware, stop merging anything into the old codebase.
---
## 11. What NOT to Do
- Do not put `#ifdef BOARD_VESPER` inside `lib/core/`. If you feel the urge to do this, it means a feature belongs in `lib/features/` or `boards/`.
- Do not share a single `main.cpp` across boards. Each board has its own. The shared code is in `lib/core/`.
- Do not make drivers know about MQTT topics, melody IDs, bell scheduling, or any core concept. Drivers are dumb hardware translators.
- Do not create a "utils" dumping ground. Every file has a home in one of the four layers.
- Do not branch for hardware variants. Board environments in `platformio.ini` are the branching mechanism for hardware.
- Do not reinvent the `CommunicationRouter` / `CommandBus` / `ITransport` pattern — it already works. Port it directly.
---
## 12. Future Proofing (Dual-MCU / RPi Variants)
When the time comes for a Vesper Pro with dual MCU or an RPi:
- That is a **new git repository**, not a new environment in this one.
- The ESP32 side of a dual-MCU board *may* reuse `lib/core/` and `lib/drivers/` as a git subtree or submodule if the logic is truly shared.
- The STM32 or RPi side is its own project with its own toolchain.
- Do not force these into the current PlatformIO project. The toolchain incompatibility alone makes it not worth it.
---
*Last updated: March 2026*
-155
View File
@@ -1,155 +0,0 @@
# 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": "vesper",
"hw_version": "1.0",
"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. `vesper`, `vesper-plus`, `vesper-pro`) |
| `hw_version` | string | Hardware revision from NVS (e.g. `1.0`) |
| `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": "vesper",
"hw_version": "1.0",
"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 and hardware revision as query parameters on every version check:
```
GET /api/firmware/{hw_type}/{channel}/latest?hw_version=1.0&current_version=5.7.1
```
Both parameters are optional. 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.
`hw_version` allows the server to filter firmware releases to those compatible with the device's specific hardware revision — useful when a hardware change between revisions requires a different binary.
**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 `hw_version` and `current_version` as optional query parameters** (both strings). If absent or unparseable, fall back to current behaviour (return absolute latest, no hw revision filtering).
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)
AND (min_hw_version IS NULL OR :hw_version >= min_hw_version) -- optional hw revision gate
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 |
|---|---|
| `hw_version` absent / malformed | Ignore param, skip hw revision filtering |
| `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 |
View File
+167 -7
View File
@@ -2,7 +2,7 @@
> Command reference for the Vesper Bell Automation System.
> Firmware v2 command bus architecture — all transports, all handlers.
> Last updated: 2026-03-01
> Last updated: 2026-03-16
---
@@ -122,10 +122,22 @@ WebSocket clients must send `identify` immediately after connecting, or they wil
`action` values: `"play"`, `"stop"`, `"pause"`, `"unpause"`
```json
{ "v": 2, "cmd": "playback", "contents": { "action": "play", "melody_uid": "ABC123" } }
{ "v": 2, "cmd": "playback", "contents": { "action": "play", "pid": "ormilia_1_8", "speed": 200, "total_duration": 60000, "note_assignments": [1,2,3,4,5,6,0,0,0,0,0,0,0,0,0,0] } }
{ "v": 2, "cmd": "playback", "contents": { "action": "stop" } }
```
| Field | Type | Required | Notes |
|---|---|---|---|
| `action` | string | yes | `"play"` or `"stop"` |
| `pid` | string | yes (play) | Playback ID. Checked against built-in library first, then SD card, then downloaded via `download_url`. |
| `download_url` | string | no | URL to download the melody binary if not found locally. |
| `speed` | int | no | ms per beat. Default 500. |
| `total_duration` | int | no | Total playback ms. `0` = play to natural end. |
| `segment_duration` | int | no | Duration per loop segment (ms). Used with `continuous_loop`. |
| `pause_duration` | int | no | Pause between segments (ms). |
| `continuous_loop` | bool | no | Loop with pause/resume segments. |
| `note_assignments` | int[16] | no | Bell mapping (0-indexed note → 1-indexed output, 0 = unused). |
---
## Relay Namespace — `RelayHandler`
@@ -620,7 +632,7 @@ List all built-in melodies compiled into the firmware.
| | |
|---|---|
| Returns | `[{ "name": "...", "uid": "..." }, ...]` |
| Returns | `[{ "name": "...", "pid": "..." }, ...]` |
```json
{ "v": 2, "cmd": "files.list_builtin" }
@@ -672,19 +684,166 @@ Set log verbosity per output channel. Level 0 = off, 5 = verbose.
### `log.set_serial`
```json
{ "v": 2, "cmd": "log.set_serial", "contents": { "level": 3 } }
{ "v": 2, "cmd": "log.set_serial", "contents": { "level": 0 } }
```
### `log.set_sd`
```json
{ "v": 2, "cmd": "log.set_sd", "contents": { "level": 2 } }
{ "v": 2, "cmd": "log.set_sd", "contents": { "level": 0 } }
```
### `log.set_mqtt`
```json
{ "v": 2, "cmd": "log.set_mqtt", "contents": { "level": 1 } }
{ "v": 2, "cmd": "log.set_mqtt", "contents": { "level": 0 } }
```
---
## RF Remote Namespace — `RFRemoteHandler`
> Available on hardware variants with `HAS_RF=1` (e.g. Vesper, Vesper+).
> All commands are silently rejected on variants without RF hardware.
The RF subsystem uses a **slot model**: up to 16 independent slots, each binding one RF trigger code to a complete playback action. Slots are blank by default — nothing is pre-seeded. Program them over MQTT after flashing.
### Slot object
| Field | Type | Required | Notes |
|---|---|---|---|
| `slot` | int | yes | Slot index, 0–15 |
| `rf_code` | uint32 | yes | Raw 433 MHz code that triggers this slot. Must be non-zero. |
| `pid` | string | yes (play) | Playback ID. Checked against built-in library first, then SD card. Use `files.list_builtin` or `files.list` for valid PIDs. |
| `speed` | int | no | ms per beat. Default 500. |
| `duration` | int | no | Total playback ms. Default 30000. `0` = play to natural end. |
| `note_assignments` | int[16] | no | Bell mapping array (0-indexed note → 1-indexed bell output, 0 = unused). Default all zeros. |
| `is_stop` | bool | no | If `true`, receiving this code calls force-stop (single press, no long-press required). `pid`/`speed`/`duration` ignored. Default `false`. |
**`note_assignments` example:** A melody written for 6 bells played on 3 physical bells, doubled:
```json
"note_assignments": [1, 2, 3, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
```
---
### `rf.set_slot`
Program one slot, or multiple slots in a single command.
| | |
|---|---|
| Handler | RFRemoteHandler |
| Transports | All |
| Persists | NVS namespace `rf` (survives reboot) |
**Single slot:**
```json
{
"v": 2,
"cmd": "rf.set_slot",
"contents": {
"slot": 0,
"rf_code": 9274392,
"pid": "vesper_fst_1_4",
"speed": 500,
"duration": 60000,
"note_assignments": [1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
"is_stop": false
}
}
```
**Multiple slots (batch):**
```json
{
"v": 2,
"cmd": "rf.set_slot",
"contents": {
"slots": [
{ "slot": 0, "rf_code": 9274392, "pid": "vesper_fst_1_4", "speed": 500, "duration": 60000, "note_assignments": [1,2,3,4,5,6,0,0,0,0,0,0,0,0,0,0] },
{ "slot": 1, "rf_code": 9274388, "pid": "doxology_1_4", "speed": 500, "duration": 60000 },
{ "slot": 7, "rf_code": 9274385, "is_stop": true }
]
}
}
```
Returns:
```json
{ "status": "SUCCESS", "type": "rf.set_slot", "payload": "3 slot(s) programmed" }
```
---
### `rf.clear_slot`
Clear a single slot, or all slots.
| | |
|---|---|
| Required | `slot` — int (0–15) or string `"all"` |
```json
{ "v": 2, "cmd": "rf.clear_slot", "contents": { "slot": 3 } }
{ "v": 2, "cmd": "rf.clear_slot", "contents": { "slot": "all" } }
```
---
### `rf.get_slots`
Return the full slot table (all 16 slots).
| | |
|---|---|
| Contents | *(none)* |
| Returns | `{ "enabled": bool, "slots": [ { slot object } × 16 ] }` |
Each entry includes an `"empty": true/false` field. Empty slots have `rf_code: 0` and all other fields at their defaults.
```json
{ "v": 2, "cmd": "rf.get_slots" }
```
Example response excerpt:
```json
{
"status": "SUCCESS",
"type": "rf.get_slots",
"data": {
"enabled": true,
"slots": [
{
"slot": 0,
"empty": false,
"rf_code": 9274392,
"pid": "vesper_fst_1_4",
"speed": 500,
"duration": 60000,
"is_stop": false,
"note_assignments": [1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
},
{ "slot": 1, "empty": true, "rf_code": 0, ... },
...
]
}
}
```
---
### `rf.enable`
Enable or disable RF reception at runtime.
| | |
|---|---|
| Required | `enabled` (bool) |
```json
{ "v": 2, "cmd": "rf.enable", "contents": { "enabled": true } }
{ "v": 2, "cmd": "rf.enable", "contents": { "enabled": false } }
```
---
@@ -799,7 +958,7 @@ On recovery:
Published on significant device state changes. `type` identifies the event; `payload` is event-specific.
```json
{ "type": "playback_started", "payload": { "melody_uid": "ABC123" } }
{ "type": "playback_started", "payload": { "pid": "ormilia_1_8" } }
{ "type": "playback_stopped", "payload": {} }
```
@@ -870,3 +1029,4 @@ If a client sends `"v": 1` (or omits `v`), the `LegacyAdapter` translates the ol
| `log` | `set_serial`, `set_sd`, `set_mqtt` |
| `mqtt` | `enable`, `disable` |
| `telemetry` | `get_strikes`, `reset_strikes`, `get_loads` |
| `rf` | `set_slot`, `clear_slot`, `get_slots`, `enable` *(HAS_RF variants only)* |
-178
View File
@@ -1,178 +0,0 @@
# Firmware Variants — Project Vesper
> Reference for all PlatformIO build environments defined in `vesper/platformio.ini`.
---
## Active Environments
### `vesper-v1` — Vesper (VS)
| Property | Value |
|---|---|
| Board | Kincony KC868-A6 |
| MCU | ESP32-D0WD-V3 (rev 3.1) |
| PlatformIO board target | `esp32dev` |
| Flash size | 4 MB |
| Partition table | `min_spiffs.csv` |
| Board type code | `VS` |
| Board version | `01` |
| PSRAM | No |
| RF remote | No |
| Onboard LCD | No |
**Partition layout (`min_spiffs.csv`):**
| Partition | Address | Size |
|---|---|---|
| nvs | `0x9000` | 20 KB (0x5000) |
| app0 (active) | `0x10000` | ~1.8 MB |
| app1 (OTA) | `0x1F0000` | ~1.8 MB |
| spiffs | `0x3D0000` | 128 KB |
**Build:**
```bash
# From repo root
pio run -e vesper-v1
# Output: vesper/.pio/build/vesper-v1/firmware.bin
```
**Full erase + upload:**
```bash
pio run -e vesper-v1 --target upload --upload-port COM8
```
**Flash NVS after full upload** (NVS is wiped by full erase — must reflash separately):
```bash
C:/Users/espi_/.espressif/python_env/idf5.4_py3.11_env/Scripts/python.exe \
-m esptool --chip esp32 --port COM8 --baud 921600 \
write_flash 0x9000 vesper/provisioning/nvs_lab_device.bin
```
**Serial monitor:**
```bash
pio device monitor # 115200 baud
```
**OTA URL pattern (VPS NGINX):**
```
http://72.61.191.197/ota/vs/stable/firmware.bin
http://72.61.191.197/ota/vs/{channel}/firmware.bin
```
Channels: `stable`, `beta`
**Key build flags:**
```ini
-DBOARD_TYPE="VS"
-DBOARD_VERSION="01"
-DBOARD_NAME="Vesper"
-DPSRAM_ENABLED=0
-DHAS_RF=0
-DHAS_LCD=0
-DMQTT_SECRET="<set-locally-not-committed>"
```
> **Important:** `MQTT_SECRET` must match the `MQTT_SECRET` in the backend `.env` on the VPS.
> Never commit the real secret. Override locally via a `platformio.ini.local` file (gitignored):
> ```ini
> [env:vesper-v1]
> build_flags =
> ... (copy existing flags) ...
> -DMQTT_SECRET=\"your_actual_secret\"
> ```
---
## Planned Environments (Not Yet Active)
### `vesper-plus-v1` — Vesper+ (VP)
| Property | Value |
|---|---|
| Board target | `esp32dev` |
| Board type code | `VP` |
| RF remote | **Yes** (`HAS_RF=1`) |
| Onboard LCD | No |
| Status | Commented out in `platformio.ini` |
**When activated, upload command:**
```bash
pio run -e vesper-plus-v1 --target upload --upload-port <PORT>
```
**OTA URL pattern:**
```
http://72.61.191.197/ota/vp/stable/firmware.bin
```
---
### `vesper-pro-v1` — Vesper Pro (VX)
| Property | Value |
|---|---|
| Board target | `esp32dev` |
| Board type code | `VX` |
| RF remote | No |
| Onboard LCD | **Yes** (`HAS_LCD=1`) |
| Status | Commented out in `platformio.ini` |
**When activated, upload command:**
```bash
pio run -e vesper-pro-v1 --target upload --upload-port <PORT>
```
**OTA URL pattern:**
```
http://72.61.191.197/ota/vx/stable/firmware.bin
```
---
## NVS Identity (All Variants)
Each device has a pre-flashed NVS partition at `0x9000` containing:
| NVS namespace | Key | Example |
|---|---|---|
| `device_id` | `device_uid` | `PV-26B18-VS01R-X7KQA` |
| `device_id` | `hw_type` | `VS` |
| `device_id` | `hw_version` | `01` |
NVS binaries are generated by the admin console at:
```
GET /api/manufacturing/devices/{sn}/nvs.bin
```
The lab device NVS CSV and binary live at:
```
vesper/provisioning/nvs_lab_device.csv
vesper/provisioning/nvs_lab_device.bin
```
---
## Shared Library Dependencies
All variants share the same `lib_deps` (defined in `[common]`):
| Library | Purpose |
|---|---|
| `tzapu/WiFiManager` | WiFi provisioning captive portal |
| `me-no-dev/ESPAsyncWebServer` | Async HTTP server + WebSocket |
| `me-no-dev/AsyncTCP` | Async TCP (required by above) |
| `bblanchon/ArduinoJson` | JSON parsing (v7) |
| `adafruit/Adafruit PCF8574` | I2C GPIO expander (relay control) |
| `adafruit/RTClib` | Real-time clock |
| `marvinroger/async-mqtt-client` | Async MQTT client |
---
## Adding a New Variant
1. Copy a `[env:vesper-*]` block in `vesper/platformio.ini` and uncomment it.
2. Set the correct `BOARD_TYPE`, `BOARD_VERSION`, `HAS_RF`, `HAS_LCD` flags.
3. Add the new `BoardType` value to `backend/manufacturing/models.py` (`BoardType` enum and `BOARD_TYPE_LABELS`).
4. Add the NVS gen path for the new `hw_type` in `backend/utils/nvs_generator.py` if needed.
5. Create the NGINX OTA directory on the VPS: `/srv/ota/{new_type}/stable/`.
6. Upload a firmware binary and update the firmware manager entry.