Compare commits
85
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b01e755c92 | ||
|
|
46a1a2567f | ||
|
|
92a0a8d5e8 | ||
|
|
fe5ab6223c | ||
|
|
204b54fce1 | ||
|
|
b80dbc9b89 | ||
|
|
4ea581af5b | ||
|
|
391ecb63fc | ||
|
|
20576f12ff | ||
|
|
1a7706d695 | ||
|
|
2748cd5cce | ||
|
|
230c1edfed | ||
|
|
2707594f65 | ||
|
|
64a8bc2b88 | ||
|
|
28b175b4fc | ||
|
|
99ca468b54 | ||
|
|
e89a1b623f | ||
|
|
f41332a771 | ||
|
|
959cb77d81 | ||
|
|
9cd6b142ef | ||
|
|
8546604490 | ||
|
|
957c283788 | ||
|
|
829ae23f09 | ||
|
|
381465cfe4 | ||
|
|
838e206a82 | ||
|
|
326ae2b767 | ||
|
|
e737769887 | ||
|
|
7675a67c90 | ||
|
|
85cdc55b78 | ||
|
|
2b4fd7c5b0 | ||
|
|
399b4d056c | ||
|
|
3582218b54 | ||
|
|
eb440a9888 | ||
|
|
0ac63e82ed | ||
|
|
a5395b0de7 | ||
|
|
07d5b2fb81 | ||
|
|
e90771a539 | ||
|
|
825ffce5f5 | ||
|
|
3d90ed4292 | ||
|
|
67da788738 | ||
|
|
9e415de7bc | ||
|
|
9f33f90ea9 | ||
|
|
7e8d91673f | ||
|
|
df8426fce6 | ||
|
|
ee73d4d2c4 | ||
|
|
ed1123283b | ||
|
|
a4d071d5d5 | ||
|
|
37b65cc15a | ||
|
|
d4d8b1c380 | ||
|
|
d4bd990e53 | ||
|
|
c3dc0a79bc | ||
|
|
682c604abe | ||
|
|
f6107e2cfe | ||
|
|
6294044569 | ||
|
|
30d660268f | ||
|
|
ab1e4f2e6d | ||
|
|
3877d27dae | ||
|
|
fe6b1d871a | ||
|
|
c656835d8e | ||
|
|
980de08584 | ||
|
|
9c314d88cf | ||
|
|
53c55d2726 | ||
|
|
094b1a9620 | ||
|
|
11b98166d1 | ||
|
|
7e279c6e45 | ||
|
|
eb6e0f0e5c | ||
|
|
7adc1fec34 | ||
|
|
51b7722e1d | ||
|
|
9f07e9ea39 | ||
|
|
3d184773c1 | ||
|
|
953b5bd07d | ||
|
|
db57b355b9 | ||
|
|
0f0b67cab9 | ||
|
|
8d397c6dd5 | ||
|
|
7d9bc42078 | ||
|
|
b04590d270 | ||
|
|
a7f1bd1667 | ||
|
|
f286abb023 | ||
|
|
c9f1e8e4ae | ||
|
|
06891e8d82 | ||
|
|
d1835beff5 | ||
|
|
470d7bfacc | ||
|
|
cc0bec97b5 | ||
|
|
d6f105319d | ||
|
|
fce760ebe0 |
+18
-6
@@ -1,9 +1,21 @@
|
|||||||
.vscode/
|
.vscode/
|
||||||
docs/
|
|
||||||
html/
|
html/
|
||||||
vesper/build/
|
build/
|
||||||
vesper/sd_settings/
|
sd_settings/
|
||||||
vesper/CLAUDE.md
|
CLAUDE.md
|
||||||
vesper/flutter/
|
flutter/
|
||||||
vesper/docs_manual/
|
docs_manual/
|
||||||
Doxyfile
|
Doxyfile
|
||||||
|
.claude/
|
||||||
|
|
||||||
|
# PlatformIO — build output and downloaded libraries (never commit these)
|
||||||
|
.pio/
|
||||||
|
|
||||||
|
# Local PlatformIO overrides (contains secrets — never commit)
|
||||||
|
platformio.ini.local
|
||||||
|
|
||||||
|
# Per-device NVS binaries (generated, never commit)
|
||||||
|
provisioning/*.bin
|
||||||
|
|
||||||
|
# Claude Code memory/session files
|
||||||
|
.claude/
|
||||||
|
|||||||
+114
@@ -0,0 +1,114 @@
|
|||||||
|
# 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) |
|
||||||
|
| [architecture/legacy-response-adapter.md](architecture/legacy-response-adapter.md) | `LegacyResponseAdapter` — v2→v1 reply translation for the v1→v2 migration window (temporary, with removal steps) |
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
| File | Description |
|
||||||
|
|---|---|
|
||||||
|
| [features/feature-catalog.md](features/feature-catalog.md) | **Feature catalog** — index + details for every feature on the device |
|
||||||
|
| [features/heartbeat.md](features/heartbeat.md) | MQTT heartbeat — retained 30s status publish (detail doc, also in catalog as F-008) |
|
||||||
|
|
||||||
|
## 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 |
|
||||||
|
|
||||||
|
|
||||||
|
## Working Rules (enforced in every session)
|
||||||
|
|
||||||
|
### Context
|
||||||
|
This is ESP32 firmware (C++/Arduino/PlatformIO) for a bell automation controller.
|
||||||
|
It is maintained by a **single developer over a long time**, with AI assistance.
|
||||||
|
That means both of us can forget what was built weeks ago — so we need hard process rules to compensate.
|
||||||
|
|
||||||
|
### Rules — non-negotiable
|
||||||
|
|
||||||
|
**1. Feature catalog is mandatory.**
|
||||||
|
Every feature added or changed must be logged in `docs/features/feature-catalog.md`.
|
||||||
|
Format: a short one-line entry in the index at the top, plus a detailed section below.
|
||||||
|
This is the single source of truth for "what does this device actually do?"
|
||||||
|
|
||||||
|
**2. Commit every meaningful step.**
|
||||||
|
Nothing stays uncommitted for long. Each logical unit of work (a fix, a feature, a refactor) gets its own commit with a clear message. Stacked uncommitted changes are a liability — they blur what changed and why.
|
||||||
|
|
||||||
|
**3. Commit messages are descriptive.**
|
||||||
|
`fix(InputManager): add medium-press tier at 5s for WiFi-only reset`
|
||||||
|
is better than `fix button`. The message must make sense to a reader in 6 months who has never seen this codebase.
|
||||||
|
|
||||||
|
**4. Feature catalog entry before (or with) the commit.**
|
||||||
|
When committing a feature or significant fix, the catalog entry is part of the same commit or committed immediately after. Never leave a feature undocumented.
|
||||||
|
|
||||||
|
**5. At the start of every session, check what is uncommitted.**
|
||||||
|
Before writing any new code, surface any dirty working tree and deal with it first — commit, discard, or document why it stays pending.
|
||||||
|
|
||||||
|
### Feature catalog location
|
||||||
|
`docs/features/feature-catalog.md`
|
||||||
|
|
||||||
|
### What counts as a "feature" for the catalog
|
||||||
|
- Any new user-facing behaviour (commands, button gestures, network modes, playback options)
|
||||||
|
- Any significant internal mechanism a future developer would need to know (e.g. two-tier factory reset, NTP UTC correction, builtin melody aliases)
|
||||||
|
- Bug fixes that change observable behaviour (e.g. default version fallback changed from 2→1)
|
||||||
|
|
||||||
|
### What does NOT need a catalog entry
|
||||||
|
- Pure refactors with no behaviour change
|
||||||
|
- Log message tweaks
|
||||||
|
- Doc-only commits
|
||||||
|
|
||||||
|
**6. Console API Reference is mandatory.**
|
||||||
|
Any new command/API endpoint, or a change to an existing one's contents/response/errors, must be reflected in the console's live API Reference page — not just in `docs/reference/api-reference.md`. The two are separate files in separate repos and neither auto-syncs from the other; both must be updated by hand in the same change.
|
||||||
|
|
||||||
|
### Console API Reference location
|
||||||
|
`C:\development\bellsystems-cp\frontend\src\pages\engineering\developer\ApiReferencePage.jsx`
|
||||||
|
|
||||||
|
This is a different repo (`bellsystems-cp`, the backend/console repo) from this firmware repo (`project-vesper`) — open it directly by path, it will not show up in a search scoped to this repo.
|
||||||
|
|
||||||
|
### How to update it
|
||||||
|
Commands are grouped into a `NAMESPACES` array. Each entry is `{ id, label, description, commands: [...] }` — one entry per namespace (e.g. `system`, `clock`, `relay`, `ota`, `firmware`, `network`, or `root` for commands with no prefix). Find the matching namespace (or add a new one) and add/edit a command object in its `commands` array with these fields:
|
||||||
|
|
||||||
|
| Field | Required | Meaning |
|
||||||
|
|---|---|---|
|
||||||
|
| `cmd` | yes | Full command name, e.g. `"clock.set_time"` |
|
||||||
|
| `handler` | yes | The C++ handler class that services it, e.g. `"ClockHandler"` |
|
||||||
|
| `transports` | yes | Array/label of which transports accept it — usually `['All']`; narrow it if the command is transport-restricted (e.g. `identify` is WebSocket-only, `ping` is unavailable on RTC-less variants) |
|
||||||
|
| `description` | yes | What the command does, plus any caveats (rejection conditions, variant restrictions, blocking behaviour) |
|
||||||
|
| `contents` | yes (`null` if none) | Array of request fields, or `null` if the command takes no `contents` body |
|
||||||
|
| `contents[].field` | yes | Field name as it appears in the JSON `contents` object |
|
||||||
|
| `contents[].type` | yes | Wire type: `string`, `int`, `bool`, `int[]`, `object`, etc. |
|
||||||
|
| `contents[].required` | yes | `true`/`false` — whether the field is mandatory. If a command requires "at least one of" a set of optional fields, say so in `notes` on each and add an error entry for the all-missing case |
|
||||||
|
| `contents[].notes` | yes | What the field means, valid ranges/values, 0-based vs 1-based indexing (call this out explicitly — this API mixes both), defaults, and interactions with other fields |
|
||||||
|
| `response` | yes | Exact success wire-format JSON as a string, matching the real `{ "status": "SUCCESS", "type": "<cmd>", "message"/"data": ... }` envelope the firmware actually sends |
|
||||||
|
| `errors` | yes (`[]` if none) | Array of `{ message, condition }` — `message` is the exact error string the firmware emits, `condition` is when it fires. Should cover every `CommandResult::err()` path in the handler |
|
||||||
|
| `example` | yes | One or more realistic full request JSON payloads (`{ "v": 2, "cmd": "...", "contents": {...} }`), as a string |
|
||||||
|
| `warning` | yes (`null` if none) | Set for anything destructive or irreversible (reboot, factory reset, rollback) — short caller-facing warning string |
|
||||||
|
|
||||||
|
When adding a **new namespace**, also check `UART_WHITELIST` near the top of the file — if the command should be reachable over UART, add its name there too (UART only accepts whitelisted commands).
|
||||||
|
|
||||||
|
Keep `docs/reference/api-reference.md` (this repo) and the console page in sync — update both in the same change whenever a command is added or changed.
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# # # # # # # # # # # # # # # # # # # # # #
|
||||||
|
STAMNA:
|
||||||
|
# # # # # # # # # # # # # # # # # # # # # #
|
||||||
|
|
||||||
|
PV25L22BP01R01
|
||||||
|
Bell Plus
|
||||||
|
HW: 1.0
|
||||||
|
|
||||||
|
u6545309759@gmail.com
|
||||||
|
bellsystems2025
|
||||||
|
aCx!97IEfTiA073^#*Jj
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# # # # # # # # # # # # # # # # # # # # # #
|
||||||
|
XRISTIANIKH_ELPIS:
|
||||||
|
# # # # # # # # # # # # # # # # # # # # # #
|
||||||
|
|
||||||
|
PV26B02BP01R01
|
||||||
|
Bell Plus
|
||||||
|
HW: 1.0
|
||||||
|
|
||||||
|
mail: christianikielpis@gmail.com
|
||||||
|
pass: bellsystems2025
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# # # # # # # # # # # # # # # # # # # # # #
|
||||||
|
GREVENA:
|
||||||
|
# # # # # # # # # # # # # # # # # # # # # #
|
||||||
|
|
||||||
|
PA26B06AM01R01
|
||||||
|
Agnus Mini
|
||||||
|
HW: 1.0
|
||||||
|
|
||||||
|
|
||||||
|
# # # # # # # # # # # # # # # # # # # # # #
|
||||||
|
LARISA:
|
||||||
|
# # # # # # # # # # # # # # # # # # # # # #
|
||||||
|
|
||||||
|
PA26B06AM01R02
|
||||||
|
Agnus Mini
|
||||||
|
HW: 1.0
|
||||||
@@ -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*
|
||||||
@@ -0,0 +1,869 @@
|
|||||||
|
# Communication Subsystem — Complete Refactor Plan
|
||||||
|
|
||||||
|
> Written: 2026-02-27
|
||||||
|
> Updated: 2026-02-28
|
||||||
|
> Status: **Stage 6 complete** — All stages done. SettingsWebServer absorbed into WebServerTransport.
|
||||||
|
> Related: MQTT refactor, Logging refactor (separate plans)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Current State Assessment
|
||||||
|
|
||||||
|
### What works well
|
||||||
|
- Unified JSON command format across all protocols — worth keeping
|
||||||
|
- CommunicationRouter as the central hub — right architectural instinct
|
||||||
|
- Non-blocking async design — correct
|
||||||
|
- ResponseBuilder consistency — good
|
||||||
|
|
||||||
|
### What's broken architecturally
|
||||||
|
- `CommandHandler.cpp` is ~700+ lines of a single giant `if/else if` chain — classic "God Class" anti-pattern
|
||||||
|
- HTTP is a second-class citizen, faking a WebSocket context with `clientId=0xFFFFFFFF` — no proper identity
|
||||||
|
- `MessageSource` has no `HTTP` value — HTTP is disguised as WebSocket throughout the code
|
||||||
|
- CommandHandler has 8 injected dependencies via raw pointers + setters — tightly coupled to everything
|
||||||
|
- Sub-commands (`relay_setup → set_timings`) are a second level of `if/else` inside the first — inconsistent
|
||||||
|
- No protocol versioning — adding the 4th transport requires touching CommandHandler again
|
||||||
|
- `SettingsWebServer` bypasses the command system entirely
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Architectural Philosophy
|
||||||
|
|
||||||
|
**Target pattern:** A transport-agnostic command bus with registered handlers.
|
||||||
|
|
||||||
|
- **Transport Layer** — MQTT, WebSocket, HTTP, UART, future WebServer — each just delivers a `CommandEnvelope` to the bus
|
||||||
|
- **Command Bus** — receives envelopes, dispatches to the right handler by command name
|
||||||
|
- **Command Handlers** — small, focused classes, one per domain (Playback, Clock, Relay, System, etc.)
|
||||||
|
- **Response** — returned to the bus, which delivers it back through the originating transport
|
||||||
|
|
||||||
|
Pattern: **Command Pattern + Message Bus** (standard embedded system architecture)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## New Directory Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
src/Communication/
|
||||||
|
├── Transport/
|
||||||
|
│ ├── ITransport.hpp ← Interface all transports implement
|
||||||
|
│ ├── MQTTTransport/
|
||||||
|
│ │ ├── MQTTTransport.hpp
|
||||||
|
│ │ └── MQTTTransport.cpp
|
||||||
|
│ ├── WebSocketTransport/
|
||||||
|
│ │ ├── WebSocketTransport.hpp
|
||||||
|
│ │ └── WebSocketTransport.cpp
|
||||||
|
│ ├── HTTPTransport/
|
||||||
|
│ │ ├── HTTPTransport.hpp
|
||||||
|
│ │ └── HTTPTransport.cpp
|
||||||
|
│ ├── UARTTransport/
|
||||||
|
│ │ ├── UARTTransport.hpp
|
||||||
|
│ │ └── UARTTransport.cpp
|
||||||
|
│ └── WebServerTransport/ ← Future 4th transport, slot ready
|
||||||
|
│ └── (placeholder)
|
||||||
|
│
|
||||||
|
├── CommandBus/
|
||||||
|
│ ├── CommandBus.hpp ← Registry + dispatcher
|
||||||
|
│ ├── CommandBus.cpp
|
||||||
|
│ ├── CommandEnvelope.hpp ← Universal message wrapper
|
||||||
|
│ ├── CommandResult.hpp ← Standardized return type
|
||||||
|
│ └── LegacyAdapter.hpp/cpp ← Optional: v1 legacy shim (deletable)
|
||||||
|
│
|
||||||
|
├── Handlers/
|
||||||
|
│ ├── ICommandHandler.hpp ← Handler interface
|
||||||
|
│ ├── PlaybackHandler/
|
||||||
|
│ ├── FileHandler/
|
||||||
|
│ ├── RelayHandler/
|
||||||
|
│ ├── ClockHandler/
|
||||||
|
│ ├── SystemHandler/
|
||||||
|
│ ├── FirmwareHandler/
|
||||||
|
│ ├── NetworkHandler/
|
||||||
|
│ └── LoggingHandler/
|
||||||
|
│
|
||||||
|
├── ResponseBuilder/ ← Keep as-is, add fromResult() factory
|
||||||
|
│ ├── ResponseBuilder.hpp
|
||||||
|
│ └── ResponseBuilder.cpp
|
||||||
|
│
|
||||||
|
└── CommunicationRouter/ ← Keeps coordinating role, simplified
|
||||||
|
├── CommunicationRouter.hpp
|
||||||
|
└── CommunicationRouter.cpp
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Core Data Structures
|
||||||
|
|
||||||
|
### CommandEnvelope
|
||||||
|
Replaces `JsonDocument + MessageContext`.
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
// CommandBus/CommandEnvelope.hpp
|
||||||
|
struct CommandEnvelope {
|
||||||
|
// Protocol version — enables forward compatibility
|
||||||
|
uint8_t version; // 2 = new, 1 = legacy (default 2)
|
||||||
|
|
||||||
|
enum class Transport {
|
||||||
|
MQTT,
|
||||||
|
WEBSOCKET,
|
||||||
|
HTTP,
|
||||||
|
UART
|
||||||
|
} transport;
|
||||||
|
|
||||||
|
uint32_t clientId; // WS client ID, 0 for others
|
||||||
|
|
||||||
|
String command; // e.g. "playback", "relay_setup"
|
||||||
|
JsonDocument contents; // The "contents" object
|
||||||
|
|
||||||
|
// Reply callback injected by the transport
|
||||||
|
std::function<void(const CommandResult&)> reply;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### CommandResult
|
||||||
|
Replaces ad-hoc string building in handler methods.
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
// CommandBus/CommandResult.hpp
|
||||||
|
struct CommandResult {
|
||||||
|
enum class Status { SUCCESS, ERROR, INFO };
|
||||||
|
|
||||||
|
Status status;
|
||||||
|
String type; // command type echo
|
||||||
|
String payload; // string payload
|
||||||
|
JsonDocument data; // structured data payload (optional)
|
||||||
|
bool hasData = false;
|
||||||
|
|
||||||
|
// Factory methods
|
||||||
|
static CommandResult ok(const String& type, const String& msg = "");
|
||||||
|
static CommandResult ok(const String& type, const JsonDocument& data);
|
||||||
|
static CommandResult err(const String& type, const String& msg);
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### ICommandHandler
|
||||||
|
Interface every domain handler implements.
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
// Handlers/ICommandHandler.hpp
|
||||||
|
class ICommandHandler {
|
||||||
|
public:
|
||||||
|
virtual ~ICommandHandler() = default;
|
||||||
|
|
||||||
|
// Returns the command name(s) this handler owns
|
||||||
|
virtual std::vector<String> commands() const = 0;
|
||||||
|
|
||||||
|
// Execute the command, return result
|
||||||
|
virtual CommandResult execute(const CommandEnvelope& envelope) = 0;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### ITransport
|
||||||
|
Interface every transport implements.
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
// Transport/ITransport.hpp
|
||||||
|
class ITransport {
|
||||||
|
public:
|
||||||
|
virtual ~ITransport() = default;
|
||||||
|
|
||||||
|
virtual void begin() = 0;
|
||||||
|
virtual void loop() = 0;
|
||||||
|
virtual bool isHealthy() const = 0;
|
||||||
|
virtual String name() const = 0;
|
||||||
|
|
||||||
|
// Broadcast to all clients of this transport
|
||||||
|
virtual void broadcast(const String& message) = 0;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## The CommandBus
|
||||||
|
|
||||||
|
Replaces the giant `if/else` chain. The entire dispatcher is ~10 lines.
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
// CommandBus/CommandBus.hpp
|
||||||
|
class CommandBus {
|
||||||
|
public:
|
||||||
|
void registerHandler(std::unique_ptr<ICommandHandler> handler);
|
||||||
|
void dispatch(CommandEnvelope& envelope);
|
||||||
|
void broadcast(const CommandResult& result);
|
||||||
|
void addTransport(ITransport* transport);
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::unordered_map<String, ICommandHandler*> _registry;
|
||||||
|
std::vector<std::unique_ptr<ICommandHandler>> _handlers;
|
||||||
|
std::vector<ITransport*> _transports;
|
||||||
|
};
|
||||||
|
|
||||||
|
// CommandBus/CommandBus.cpp
|
||||||
|
void CommandBus::dispatch(CommandEnvelope& envelope) {
|
||||||
|
auto it = _registry.find(envelope.command);
|
||||||
|
if (it == _registry.end()) {
|
||||||
|
envelope.reply(CommandResult::err("unknown", "Unknown command: " + envelope.command));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
CommandResult result = it->second->execute(envelope);
|
||||||
|
envelope.reply(result);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Per-Domain Handler Pattern
|
||||||
|
|
||||||
|
Each handler: ~50–100 lines, focused, one dependency set, independently testable.
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
// Handlers/PlaybackHandler/PlaybackHandler.hpp
|
||||||
|
class PlaybackHandler : public ICommandHandler {
|
||||||
|
public:
|
||||||
|
explicit PlaybackHandler(Player& player);
|
||||||
|
std::vector<String> commands() const override;
|
||||||
|
CommandResult execute(const CommandEnvelope& envelope) override;
|
||||||
|
private:
|
||||||
|
Player& _player;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handlers/PlaybackHandler/PlaybackHandler.cpp
|
||||||
|
std::vector<String> PlaybackHandler::commands() const {
|
||||||
|
return { "playback" };
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult PlaybackHandler::execute(const CommandEnvelope& envelope) {
|
||||||
|
bool ok = _player.command(envelope.contents.as<JsonVariant>());
|
||||||
|
if (ok) return CommandResult::ok("playback", "Command executed");
|
||||||
|
return CommandResult::err("playback", "Player rejected command");
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Transport Layer Pattern
|
||||||
|
|
||||||
|
Each transport parses raw input, builds a `CommandEnvelope` with a reply lambda, and dispatches.
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
// WebSocketTransport — on message received:
|
||||||
|
void WebSocketTransport::onMessage(uint32_t clientId, const String& raw) {
|
||||||
|
JsonDocument doc;
|
||||||
|
if (deserializeJson(doc, raw) != DeserializationError::Ok) {
|
||||||
|
sendToClient(clientId, ResponseBuilder::error("parse", "Invalid JSON"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandEnvelope envelope;
|
||||||
|
envelope.transport = CommandEnvelope::Transport::WEBSOCKET;
|
||||||
|
envelope.clientId = clientId;
|
||||||
|
envelope.command = doc["cmd"].as<String>();
|
||||||
|
envelope.contents = doc["contents"];
|
||||||
|
envelope.version = doc["v"] | 2;
|
||||||
|
|
||||||
|
envelope.reply = [this, clientId](const CommandResult& result) {
|
||||||
|
sendToClient(clientId, ResponseBuilder::fromResult(result));
|
||||||
|
};
|
||||||
|
|
||||||
|
_commandBus.dispatch(envelope);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
HTTP is now a proper first-class transport — no more `0xFFFFFFFF` hack:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
// HTTPTransport — on POST /api/command:
|
||||||
|
envelope.transport = CommandEnvelope::Transport::HTTP;
|
||||||
|
envelope.reply = [request](const CommandResult& result) {
|
||||||
|
request->send(200, "application/json", ResponseBuilder::fromResult(result));
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
UART keeps its whitelist — lives inside `UARTTransport`, not in the bus:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
// UARTTransport — before dispatch:
|
||||||
|
if (!isWhitelisted(envelope.command)) {
|
||||||
|
// silently ignore (prevent feedback loops)
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_commandBus.dispatch(envelope);
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Simplified CommunicationRouter
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
class CommunicationRouter {
|
||||||
|
public:
|
||||||
|
CommunicationRouter(/* core dependencies */);
|
||||||
|
|
||||||
|
void begin();
|
||||||
|
void loop();
|
||||||
|
bool isHealthy() const;
|
||||||
|
|
||||||
|
// For subsystems pushing events (telemetry, bell strikes, etc.)
|
||||||
|
void broadcast(const CommandResult& event);
|
||||||
|
void broadcastToMasters(const String& message);
|
||||||
|
|
||||||
|
private:
|
||||||
|
CommandBus _commandBus;
|
||||||
|
|
||||||
|
MQTTTransport _mqtt;
|
||||||
|
WebSocketTransport _ws;
|
||||||
|
HTTPTransport _http;
|
||||||
|
UARTTransport _uart;
|
||||||
|
|
||||||
|
void registerHandlers(); // Replaces all setXxxReference() calls
|
||||||
|
};
|
||||||
|
|
||||||
|
// All handler wiring in one place:
|
||||||
|
void CommunicationRouter::registerHandlers() {
|
||||||
|
_commandBus.registerHandler(std::make_unique<PlaybackHandler>(_player));
|
||||||
|
_commandBus.registerHandler(std::make_unique<RelayHandler>(_configManager));
|
||||||
|
_commandBus.registerHandler(std::make_unique<ClockHandler>(_configManager, _timeKeeper));
|
||||||
|
_commandBus.registerHandler(std::make_unique<FileHandler>(_fileManager));
|
||||||
|
_commandBus.registerHandler(std::make_unique<SystemHandler>(_configManager, _networking));
|
||||||
|
_commandBus.registerHandler(std::make_unique<FirmwareHandler>(_firmwareValidator, _otaManager));
|
||||||
|
_commandBus.registerHandler(std::make_unique<NetworkHandler>(_configManager, _networking));
|
||||||
|
_commandBus.registerHandler(std::make_unique<LoggingHandler>(_logging));
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Sub-Command Strategy
|
||||||
|
|
||||||
|
Two options — pick one:
|
||||||
|
|
||||||
|
### Option A — Flatten (Recommended for new protocol)
|
||||||
|
Register `relay.set_timings` and `relay.set_outputs` as separate top-level commands. Removes nested `if/else` entirely.
|
||||||
|
```json
|
||||||
|
{ "cmd": "relay.set_timings", "v": 2, "contents": { ... } }
|
||||||
|
```
|
||||||
|
|
||||||
|
### Option B — Keep Nesting (Recommended for wire compatibility)
|
||||||
|
Keep `relay_setup` as the command. `RelayHandler` switches on `contents["action"]` internally. Still clean because it's isolated in one small class.
|
||||||
|
```json
|
||||||
|
{ "cmd": "relay_setup", "contents": { "action": "set_timings", ... } }
|
||||||
|
```
|
||||||
|
|
||||||
|
**Decision:** Option B is safer if FlutterFlow app rollout is staggered. Wire format stays identical.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Protocol Versioning / Legacy Compatibility
|
||||||
|
|
||||||
|
`CommandEnvelope.version` enables a clean cutover:
|
||||||
|
|
||||||
|
- Client sends `"v": 1` (or omits `v`) → treated as legacy
|
||||||
|
- Client sends `"v": 2` → goes straight through
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
// CommandBus/LegacyAdapter.hpp / .cpp
|
||||||
|
// Maps old command names / content shapes to new ones
|
||||||
|
// Completely deletable in one PR when legacy support ends
|
||||||
|
|
||||||
|
static const std::unordered_map<String, String> LEGACY_COMMAND_MAP = {
|
||||||
|
// Add entries here only if command names change in v2
|
||||||
|
// If names stay the same, this file may not be needed at all
|
||||||
|
};
|
||||||
|
|
||||||
|
void translateLegacyEnvelope(CommandEnvelope& env) {
|
||||||
|
auto it = LEGACY_COMMAND_MAP.find(env.command);
|
||||||
|
if (it != LEGACY_COMMAND_MAP.end()) {
|
||||||
|
env.command = it->second;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Recommendation:** If command names stay identical between v1 and v2, skip the legacy adapter entirely and just force-update the FlutterFlow app.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## The 4th Transport — On-Board Web Server
|
||||||
|
|
||||||
|
With this architecture, adding it costs almost nothing:
|
||||||
|
1. Create `WebServerTransport` implementing `ITransport`
|
||||||
|
2. HTML routes POST to CommandBus via synthetic `CommandEnvelope`
|
||||||
|
3. Register it in `CommunicationRouter::begin()`
|
||||||
|
4. `SettingsWebServer` absorbs into this transport (fixes the current bypass of the command system)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What Stays the Same
|
||||||
|
|
||||||
|
| Component | Action |
|
||||||
|
|---|---|
|
||||||
|
| `ResponseBuilder` | Keep — add `fromResult(CommandResult)` factory method |
|
||||||
|
| `ClientManager` | Keep — used by `WebSocketTransport` |
|
||||||
|
| Wire protocol format | Keep — `{ "cmd": "...", "contents": { ... } }` unchanged |
|
||||||
|
| MQTT topics | **Changed in v2.2.0** — full topic rebuild, see `docs/reference/vesper_mqtt_topic_spec_v2.md` and F-062 in the feature catalog |
|
||||||
|
| MQTT auth system | Keep — no change |
|
||||||
|
| UART whitelist | Keep — move into `UARTTransport` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Implementation Stages
|
||||||
|
|
||||||
|
### Stage 1 — Core Scaffolding ✅ COMPLETE
|
||||||
|
> No behavior change. Zero risk. Headers only.
|
||||||
|
|
||||||
|
- [x] Define `CommandEnvelope.hpp`
|
||||||
|
- [x] Define `CommandResult.hpp`
|
||||||
|
- [x] Define `ICommandHandler.hpp`
|
||||||
|
- [x] Define `ITransport.hpp`
|
||||||
|
- [x] Create `CommandBus` skeleton (register + dispatch, no handlers yet)
|
||||||
|
- [x] Old `CommandHandler` stays untouched
|
||||||
|
|
||||||
|
### Stage 2 — Migrate Handlers One Domain at a Time ✅ COMPLETE
|
||||||
|
> Write new handler → register on bus → comment out old if/else branch → test
|
||||||
|
|
||||||
|
- [x] `PlaybackHandler` (simplest — one dependency)
|
||||||
|
- [x] `SystemHandler`
|
||||||
|
- [x] `FirmwareHandler`
|
||||||
|
- [x] `LoggingHandler`
|
||||||
|
- [x] `RelayHandler` (complex — multiple sub-commands)
|
||||||
|
- [x] `ClockHandler` (most complex — many sub-commands)
|
||||||
|
- [x] `FileHandler`
|
||||||
|
- [x] `NetworkHandler`
|
||||||
|
- [x] `TelemetryHandler` (new — zero coverage in old system)
|
||||||
|
- [x] `MQTTHandler` (new — mqtt.enable / mqtt.disable)
|
||||||
|
|
||||||
|
> Also added: `ResponseBuilder::fromResult(CommandResult)` factory method (needed by transports)
|
||||||
|
|
||||||
|
### Stage 3 — Transport Layer Refactor ✅ COMPLETE
|
||||||
|
|
||||||
|
- [x] `MQTTTransport` — wraps `MQTTAsyncClient`, implements `ITransport`. All timers/heartbeat/reconnect logic in the underlying client untouched. Callback → `CommandEnvelope` → bus → reply publishes to data topic.
|
||||||
|
- [x] `WebSocketTransport` — wraps `WebSocketServer` + `ClientManager`. Reply lambda routes response back to the originating client by `clientId`. Exposes `broadcastToMasters()` / `broadcastToSecondary()` for router helpers.
|
||||||
|
- [x] `HTTPTransport` — **proper first-class HTTP identity**. No more `0xFFFFFFFF` fake WS client ID. Registers `POST /api/command`, `GET /api/ping`, `GET /api/status`. Reply lambda captures `AsyncWebServerRequest*` and calls `send()` exactly once. `broadcast()` is a no-op (stateless protocol).
|
||||||
|
- [x] `UARTTransport` — wraps `UARTCommandHandler`. Whitelist enforced before bus dispatch; non-whitelisted commands silently dropped (no error response — prevents feedback loops). `loop()` polls the underlying handler.
|
||||||
|
|
||||||
|
> Note: existing `MQTTAsyncClient`, `WebSocketServer`, `HTTPRequestHandler`, `UARTCommandHandler`
|
||||||
|
> are **not deleted** — they remain in place until Stage 4 wires the router. The transports wrap them.
|
||||||
|
|
||||||
|
### Stage 4 — CommunicationRouter Simplification ✅ COMPLETE
|
||||||
|
|
||||||
|
- [x] Replace router internals with `CommandBus` + transport array
|
||||||
|
- [x] Implement `registerHandlers()` — called from `begin()` after all setters are applied
|
||||||
|
- [x] `setHealthMonitorReference()` + `setOutputManagerReference()` added; main.cpp updated
|
||||||
|
- [x] All setters now called **before** `begin()` in main.cpp so registerHandlers() has full dependency set
|
||||||
|
- [x] Old `CommandHandler` marked `// DEPRECATED` — kept on disk until confirmed stable in production
|
||||||
|
- [x] `HTTPRequestHandler` no longer instantiated in router (replaced by `HTTPTransport`)
|
||||||
|
- [x] `CommunicationRouter` public API unchanged — BellEngine, Player, Telemetry callers need no changes
|
||||||
|
|
||||||
|
### Stage 5 — Legacy Adapter ✅ COMPLETE
|
||||||
|
|
||||||
|
- [x] `LegacyAdapter.hpp` — `translateLegacyEnvelope()` declaration + deletion instructions
|
||||||
|
- [x] `LegacyAdapter.cpp` — full translation table: 35 mappings covering all v1 command/action pairs
|
||||||
|
- Simple 1-to-1: `ping`, `identify`, `playback`
|
||||||
|
- Action-based: `file_manager`, `relay_setup`, `clock_setup`, `system_info`, `system`
|
||||||
|
- Boolean splits: `clock_setup → set_enabled` → `clock.enable`/`clock.disable`; `system → set_mqtt_enabled` → `mqtt.enable`/`mqtt.disable`
|
||||||
|
- Retired command: `sync_time_to_lcd` → `system.get_time` (LCD now uses request/response)
|
||||||
|
- [x] `CommandBus::dispatch()` — single `if (version == 1)` gate before registry lookup; zero transport changes
|
||||||
|
- [ ] Test with FlutterFlow app sending `"v": 1`
|
||||||
|
- [ ] Set cutover date — delete adapter in one clean PR
|
||||||
|
|
||||||
|
### Stage 6 — SettingsWebServer Integration (4th Transport) ✅ COMPLETE
|
||||||
|
|
||||||
|
- [x] Create `WebServerTransport` (implements `ITransport`)
|
||||||
|
- [x] Absorb `SettingsWebServer` into `WebServerTransport` — old class is dead code
|
||||||
|
- [x] `POST /api/set-mode` → `network.set_config { permanent_ap_mode }` via CommandBus
|
||||||
|
- [x] `POST /api/reboot` → `system.restart` via CommandBus
|
||||||
|
- [x] `NetworkHandler::handleSetConfig` extended to handle `permanent_ap_mode` field
|
||||||
|
- [x] `WebServerTransport` registered in `CommunicationRouter::begin()` and on the bus
|
||||||
|
- [x] `SettingsWebServer` member removed from router — `src/SettingsWebServer/` is deletable in one PR
|
||||||
|
|
||||||
|
> `src/SettingsWebServer/SettingsPage.h` still included by `WebServerTransport.cpp` for the PROGMEM HTML template.
|
||||||
|
> Move or inline it when deleting the old directory.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Before / After Comparison
|
||||||
|
|
||||||
|
| Concern | Current | New |
|
||||||
|
|---|---|---|
|
||||||
|
| Command dispatch | 700-line `if/else` | Hash map, O(1) lookup |
|
||||||
|
| Adding a command | Edit giant `CommandHandler` | Add a new ~50-line class |
|
||||||
|
| HTTP identity | Fake WebSocket (`0xFFFFFFFF`) | Proper `HTTPTransport` |
|
||||||
|
| Adding a transport | Touch `CommandHandler` | Implement `ITransport`, register |
|
||||||
|
| Handler dependencies | 8 setter injections on one class | Explicit constructor per handler |
|
||||||
|
| Sub-commands | Nested `if/else` inside `if/else` | Internal to focused handler class |
|
||||||
|
| Legacy support | N/A | Isolated `LegacyAdapter`, deletable in one PR |
|
||||||
|
| On-board WebServer | Bypasses command system | `WebServerTransport`, full integration |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ESP32 Memory Notes
|
||||||
|
|
||||||
|
- `std::unordered_map` is fine on ESP32-D0WD for a ~10-entry registry (trivial footprint)
|
||||||
|
- `std::unique_ptr` for handler ownership — no raw pointer leaks
|
||||||
|
- `std::function` reply lambdas — small captures (one pointer + one uint32)
|
||||||
|
- If memory gets tight: replace `unordered_map` with sorted static array + binary search — zero impact on handler code
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Command System Redesign
|
||||||
|
|
||||||
|
> This section documents the complete v2 command API — what changes, what's removed, what's new, and the full canonical command table.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What's Wrong With the Current Commands
|
||||||
|
|
||||||
|
### Problem 1 — Two umbrella commands doing the same job
|
||||||
|
`system` and `system_info` are both grab-bags. Two commands even overlap directly:
|
||||||
|
- `system → status` duplicates `system_info → report_status`
|
||||||
|
- `system → get_firmware_status` duplicates `system_info → get_firmware_status`
|
||||||
|
|
||||||
|
### Problem 2 — Wrong grouping
|
||||||
|
- `set_network_config` is buried inside `system` instead of being in a `network` namespace
|
||||||
|
- Log level commands are inside `system` instead of a `log` namespace
|
||||||
|
- `set_mqtt_enabled` controls a transport but lives in `system`
|
||||||
|
- `get_device_time` and `get_clock_time` are in `system_info` but logically belong in `clock` and `system` respectively
|
||||||
|
|
||||||
|
### Problem 3 — Internal command exposed publicly
|
||||||
|
- `sync_time_to_lcd` is a UART push that the device sends to its own LCD slave board. It is not a client command — a FlutterFlow app should never need to call this. It should be an internal method, not a public API endpoint.
|
||||||
|
|
||||||
|
### Problem 4 — Entire subsystems have zero command coverage
|
||||||
|
- `HealthMonitor` — no commands at all
|
||||||
|
- `Telemetry` — no commands at all
|
||||||
|
- `OutputManager` — no direct control (relay fire/extinguish only reachable via Player)
|
||||||
|
- `BuiltInMelodies` — list never exposed, clients can't see what's available without downloading
|
||||||
|
|
||||||
|
### Problem 5 — Naming inconsistency
|
||||||
|
- `set_timings` on relay means "bell strike durations" — ambiguous
|
||||||
|
- `restart` and `reboot` are aliases doing the same thing — pick one
|
||||||
|
- `reset_defaults` is unclear — `factory_reset` is universally understood
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Handler Input Contract (Design Principle)
|
||||||
|
|
||||||
|
This rule applies to **every single handler** without exception. It must be enforced during implementation.
|
||||||
|
|
||||||
|
```
|
||||||
|
Extra fields in contents? → Ignore silently. Never crash on unknown keys.
|
||||||
|
Missing optional fields? → Use defaults or skip that part of the operation.
|
||||||
|
Missing required fields? → Return ERROR with a clear message. Do nothing else.
|
||||||
|
Wrong type / bad format? → Return ERROR with a clear message. Do nothing else.
|
||||||
|
No contents at all? → If the command needs none, proceed. If it needs some, return ERROR.
|
||||||
|
```
|
||||||
|
|
||||||
|
Concretely: if a client sends `relay.set_durations` with only bell `"0"`, update bell 0 and leave all others unchanged. Do not require all 6 bells to be present. If a client sends `relay.test_output` with no `output` field, return an error — that field is required. If a client sends `relay.test_output` with `output`, `duration_ms`, and an extra unknown field `foo`, ignore `foo` and proceed.
|
||||||
|
|
||||||
|
This applies to ALL multi-field commands: relay durations, relay outputs, clock outputs, clock alerts, network config, etc.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Command Decisions: Keep / Change / Remove / Add
|
||||||
|
|
||||||
|
### KEEP (as-is or renamed)
|
||||||
|
| Old command | Decision | Reason |
|
||||||
|
|---|---|---|
|
||||||
|
| `ping` | Keep → `ping` | Simple, universally understood utility |
|
||||||
|
| `identify` | Keep → `identify` | WebSocket client-type registration, needed |
|
||||||
|
| `playback` | Keep → `playback` | Already flat and well-structured |
|
||||||
|
| `relay_setup → set_outputs` | Keep → `relay.set_outputs` | Correct grouping, just flatten |
|
||||||
|
| `clock_setup → set_outputs` | Keep → `clock.set_outputs` | Correct grouping |
|
||||||
|
| `clock_setup → set_alerts` | Keep → `clock.set_alerts` | Correct grouping |
|
||||||
|
| `clock_setup → set_backlight` | Keep → `clock.set_backlight` | Correct grouping |
|
||||||
|
| `clock_setup → set_silence` | Keep → `clock.set_silence` | Correct grouping |
|
||||||
|
| `clock_setup → set_rtc_time` | Keep → `clock.set_time` | Shorter, clearer |
|
||||||
|
| `clock_setup → set_physical_clock_time` | Keep → `clock.set_face` | "Face" = analog clock face position |
|
||||||
|
| `clock_setup → pause_clock_updates` | Keep → `clock.pause` | Fine |
|
||||||
|
| `clock_setup → resume_clock_updates` | Keep → `clock.resume` | Fine |
|
||||||
|
| `system_info → get_full_settings` | Keep → `system.get_settings` | Useful, correct namespace |
|
||||||
|
| `system_info → network_info` | Keep → `network.info` | Move to correct namespace |
|
||||||
|
| `system → reset_defaults` | Keep → `system.factory_reset` | Rename: clearer intent |
|
||||||
|
| `system → commit_firmware` | Keep → `firmware.commit` | Correct namespace |
|
||||||
|
| `system → rollback_firmware` | Keep → `firmware.rollback` | Correct namespace |
|
||||||
|
| `system → get_firmware_status` | Keep → `firmware.status` | Deduplicated, correct namespace |
|
||||||
|
| `system → set_network_config` | Keep → `network.set_config` | Move to correct namespace |
|
||||||
|
| `system → set_serial_log_level` | Keep → `log.set_serial` | Correct namespace |
|
||||||
|
| `system → set_sd_log_level` | Keep → `log.set_sd` | Correct namespace |
|
||||||
|
| `system → set_mqtt_log_level` | Keep → `log.set_mqtt` | Correct namespace |
|
||||||
|
| `system → restart` | Keep → `system.restart` | Collapse `reboot` alias, one canonical name |
|
||||||
|
| `system → force_update` | Keep → `ota.update` | Correct namespace |
|
||||||
|
| `system → custom_update` | Keep → `ota.custom` | Correct namespace |
|
||||||
|
| `file_manager → list_melodies` | Keep → `files.list` | Flat, cleaner — melodies only (SD card) |
|
||||||
|
| `file_manager → download_melody` | Keep → `files.download` | Fine |
|
||||||
|
| `file_manager → delete_melody` | Keep → `files.delete` | Fine |
|
||||||
|
|
||||||
|
### CHANGE (same function, fixed grouping or naming)
|
||||||
|
| Old command | New command | What changes |
|
||||||
|
|---|---|---|
|
||||||
|
| `relay_setup → set_timings` | `relay.set_durations` | Renamed: "timings" is vague, "durations" is what it actually sets (ms per strike) |
|
||||||
|
| `clock_setup → set_timings` | `clock.set_timings` | Keep name, but note: currently calls `updateClockOutputs()` — **bug in original code**, fix during migration |
|
||||||
|
| `clock_setup → set_enabled` | Split into `clock.enable` / `clock.disable` | No boolean needed — intent is unambiguous, cleaner in logs and app code |
|
||||||
|
| `system → set_mqtt_enabled` | Split into `mqtt.enable` / `mqtt.disable` | Same reasoning as clock enable/disable |
|
||||||
|
| `system_info → report_status` | `system.status` | Moved out of umbrella, deduplicated with `system → status` |
|
||||||
|
| `system_info → get_device_time` | `system.get_time` | Moved: this is system-level RTC time, not clock-face time |
|
||||||
|
| `system_info → get_clock_time` | `clock.get_face` | Moved to `clock` namespace — returns analog face position |
|
||||||
|
| `telemetry.reset_strikes` | `telemetry.reset_strikes` + optional `{ "bell": N }` | Omit `bell` → reset all. Include `bell` → reset only that channel. Enables per-bell reset when a striker is replaced. |
|
||||||
|
| `relay.test_output` | `relay.test_output` with required `duration_ms` | No default duration — caller must be explicit. Forces operator intentionality. 85–140ms is typical; 200ms is too long for sensitive strikers. Both `output` and `duration_ms` are required fields. |
|
||||||
|
|
||||||
|
### REMOVE
|
||||||
|
| Old command | Reason |
|
||||||
|
|---|---|
|
||||||
|
| `system → status` | Duplicate of `system_info → report_status`. One survives as `system.status`. |
|
||||||
|
| `system → get_firmware_status` (under `system`) | Duplicate. Survives as `firmware.status`. |
|
||||||
|
| `system_info → get_firmware_status` (under `system_info`) | Duplicate. Same as above. |
|
||||||
|
| `system → reboot` | Alias for `restart`. Removed. `system.restart` is the one. |
|
||||||
|
| `system_info → sync_time_to_lcd` | **Removed as a public push command.** The LCD slave is a proper bidirectional UART client — it requests time with `system.get_time` and gets a response. The old model (master pushing time unsolicited) caused infinite loop bugs when responses were corrupted. The new model is clean request/response. |
|
||||||
|
|
||||||
|
### ADD (new commands, previously uncovered functionality)
|
||||||
|
| New command | Handler | What it does | Why |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `system.get_device_info` | SystemHandler | Returns device UID, hw_type, hw_version, fw_version, uptime, free heap | Currently buried in `get_full_settings` — needs its own fast endpoint |
|
||||||
|
| `system.health` | SystemHandler | Returns full `HealthMonitor` report — all subsystem states, warnings, critical failures | `HealthMonitor` has zero command coverage today |
|
||||||
|
| `clock.set_timezone` | ClockHandler | Sets GMT offset + DST offset + optional timezone name, saves to SD | Timezone is currently piggybacked onto `clock.set_time` — can't change timezone without resending a timestamp |
|
||||||
|
| `clock.get_timezone` | ClockHandler | Returns current GMT offset, DST offset, timezone name | No read command for timezone today |
|
||||||
|
| `clock.sync_ntp` | ClockHandler | Forces an immediate NTP sync via `TimeKeeper::syncTimeWithNTP()` | No on-demand NTP sync exists today |
|
||||||
|
| `telemetry.get_strikes` | TelemetryHandler | Returns strike counts per bell channel | Currently only returned as part of `system.status` |
|
||||||
|
| `telemetry.reset_strikes` | TelemetryHandler | Resets strike counters — all channels, or a single channel via `{ "bell": N }` | No command exists today; per-bell reset is critical for striker replacement |
|
||||||
|
| `telemetry.get_loads` | TelemetryHandler | Returns current heat load per bell channel, cooling status, overload flags | No command exists today |
|
||||||
|
| `files.list_builtin` | FileHandler | Returns list of all built-in melodies (name + UID) from `BuiltInMelodies::getBuiltInMelodiesJSON()` | Currently impossible for a client to know what built-ins exist without trying to play them |
|
||||||
|
| `ota.status` | FirmwareHandler | Returns OTAManager status: current version, available version, update channel, last check time, update progress | No status query exists today |
|
||||||
|
| `ota.check` | FirmwareHandler | Triggers `OTAManager::checkForUpdates()` and returns result immediately | No on-demand check exists today |
|
||||||
|
| `relay.get_config` | RelayHandler | Returns current bell durations + output assignments as JSON | No read command for relay config today — only write |
|
||||||
|
| `clock.get_config` | ClockHandler | Returns full clock configuration (outputs, timings, alerts, backlight, silence, enabled state) | No read command for clock config today — only write |
|
||||||
|
| `network.status` | NetworkHandler | Returns connection state, IP, RSSI, AP mode flag | `network.info` only returns IP/gateway/DNS — no connection state or signal strength |
|
||||||
|
| `relay.test_output` | RelayHandler | Fires a specific relay for a caller-specified duration. Both `output` and `duration_ms` required. Safety-gated: only works when Player is stopped | Diagnostic/commissioning — currently impossible without a full playback command |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Complete v2 Command Table
|
||||||
|
|
||||||
|
The canonical reference. Every command in the new system.
|
||||||
|
|
||||||
|
### `ping`
|
||||||
|
| Field | Value |
|
||||||
|
|---|---|
|
||||||
|
| Handler | SystemHandler |
|
||||||
|
| Transport restriction | None (all transports) |
|
||||||
|
| Contents | *(none)* |
|
||||||
|
| Returns | `{ "status": "SUCCESS", "type": "pong" }` |
|
||||||
|
|
||||||
|
### `identify`
|
||||||
|
| Field | Value |
|
||||||
|
|---|---|
|
||||||
|
| Handler | SystemHandler |
|
||||||
|
| Transport restriction | WebSocket only |
|
||||||
|
| Contents | `{ "device_type": "master" \| "secondary" }` — required |
|
||||||
|
| Returns | Success/error |
|
||||||
|
|
||||||
|
### `playback`
|
||||||
|
| Field | Value |
|
||||||
|
|---|---|
|
||||||
|
| Handler | PlaybackHandler |
|
||||||
|
| Transport restriction | None |
|
||||||
|
| Contents | `{ "action": "play" \| "stop" \| "pause" \| "unpause", ...melody attributes }` — `action` required |
|
||||||
|
| Returns | Success/error |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Relay namespace — `RelayHandler`
|
||||||
|
|
||||||
|
| Command | Required fields | Optional fields | Returns |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `relay.set_durations` | *(at least one bell)* | `{ "bells": { "0": 95, "2": 110, ... } }` — partial updates accepted | Success/error |
|
||||||
|
| `relay.set_outputs` | *(at least one bell)* | `{ "bells": { "0": 2, "1": 3, ... } }` — partial updates accepted | Success/error |
|
||||||
|
| `relay.get_config` | *(none)* | — | `{ "durations": {...}, "outputs": {...} }` |
|
||||||
|
| `relay.test_output` | `output`, `duration_ms` | — | Success/error — **player must be stopped** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Clock namespace — `ClockHandler`
|
||||||
|
|
||||||
|
| Command | Required fields | Optional fields | Returns |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `clock.set_outputs` | *(at least one of c1, c2)* | `{ "c1": 4, "c2": 5 }` — partial OK | Success/error |
|
||||||
|
| `clock.set_timings` | *(at least one timing field)* | timing config fields — partial OK | Success/error |
|
||||||
|
| `clock.set_alerts` | *(at least one alert field)* | alert config fields — partial OK | Success/error |
|
||||||
|
| `clock.set_backlight` | *(at least one field)* | backlight config fields — partial OK | Success/error |
|
||||||
|
| `clock.set_silence` | *(at least one field)* | silence period fields — partial OK | Success/error |
|
||||||
|
| `clock.set_time` | `timestamp` | `timezone_offset`, `dst_offset` | Success/error |
|
||||||
|
| `clock.set_face` | `hour`, `minute` | — | Success/error |
|
||||||
|
| `clock.set_timezone` | `gmt_offset_sec` | `dst_offset_sec`, `timezone_name` | Success/error |
|
||||||
|
| `clock.get_timezone` | *(none)* | — | `{ gmt_offset_sec, dst_offset_sec, timezone_name }` |
|
||||||
|
| `clock.sync_ntp` | *(none)* | — | Success/error |
|
||||||
|
| `clock.enable` | *(none)* | — | Success/error |
|
||||||
|
| `clock.disable` | *(none)* | — | Success/error |
|
||||||
|
| `clock.pause` | *(none)* | — | Success/error |
|
||||||
|
| `clock.resume` | *(none)* | — | Success/error |
|
||||||
|
| `clock.get_face` | *(none)* | — | `{ clock_hour, clock_minute, last_sync_time, next_output_is_c1 }` |
|
||||||
|
| `clock.get_config` | *(none)* | — | Full clock config object |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### System namespace — `SystemHandler`
|
||||||
|
|
||||||
|
| Command | Required fields | Optional fields | Returns |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `system.status` | *(none)* | — | Player state, strike counters, projected run time |
|
||||||
|
| `system.get_time` | *(none)* | — | `{ local_timestamp, utc_timestamp, year, month, day, hour, minute, second, rtc_available }` |
|
||||||
|
| `system.get_settings` | *(none)* | — | Full ConfigManager JSON dump |
|
||||||
|
| `system.get_device_info` | *(none)* | — | `{ uid, hw_type, hw_version, fw_version, uptime_ms, free_heap, min_free_heap }` |
|
||||||
|
| `system.health` | *(none)* | — | Full HealthMonitor report — subsystem states, warnings, critical count |
|
||||||
|
| `system.factory_reset` | *(none)* | — | Success/error |
|
||||||
|
| `system.restart` | *(none)* | — | Sends response, then reboots after 2s |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Firmware namespace — `FirmwareHandler`
|
||||||
|
|
||||||
|
| Command | Required fields | Returns |
|
||||||
|
|---|---|---|
|
||||||
|
| `firmware.status` | *(none)* | Validation state, version, boot count, can_commit, can_rollback |
|
||||||
|
| `firmware.commit` | *(none)* | Success/error |
|
||||||
|
| `firmware.rollback` | *(none)* | Success/error — device reboots |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### OTA namespace — `FirmwareHandler`
|
||||||
|
|
||||||
|
| Command | Required fields | Optional fields | Returns |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `ota.status` | *(none)* | — | `{ current_version, available_version, channel, update_available, last_check, progress }` |
|
||||||
|
| `ota.check` | *(none)* | `channel` (default: "stable") | Update availability result |
|
||||||
|
| `ota.update` | *(none)* | `channel` (default: "stable") | Success/error — device may reboot |
|
||||||
|
| `ota.custom` | `firmware_url` | `checksum`, `file_size`, `version` | Success/error — device may reboot |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Network namespace — `NetworkHandler`
|
||||||
|
|
||||||
|
| Command | Required fields | Optional fields | Returns |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `network.info` | *(none)* | — | `{ ip, gateway, dns }` |
|
||||||
|
| `network.status` | *(none)* | — | `{ connected, state, type, ip, rssi, ap_mode }` |
|
||||||
|
| `network.set_config` | *(at least one field)* | `hostname`, `useStaticIP`, `ip`, `gateway`, `subnet`, `dns1`, `dns2` — partial OK; static IP requires ip+gateway+subnet together | Success/error + restart_required flag |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Files namespace — `FileHandler`
|
||||||
|
|
||||||
|
| Command | Required fields | Returns |
|
||||||
|
|---|---|---|
|
||||||
|
| `files.list` | *(none)* | Array of melody files on SD card (melodies only) |
|
||||||
|
| `files.list_builtin` | *(none)* | Array of built-in melodies `[{ name, uid }, ...]` |
|
||||||
|
| `files.download` | `melodys_uid` | Success/error |
|
||||||
|
| `files.delete` | `name` | Success/error |
|
||||||
|
|
||||||
|
> `files.list` returns SD card melodies only. Built-in melodies have their own endpoint. Future: add `type` filter for other file categories (schedules, etc.)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Log namespace — `LoggingHandler`
|
||||||
|
|
||||||
|
| Command | Required fields | Returns |
|
||||||
|
|---|---|---|
|
||||||
|
| `log.set_serial` | `level` (0–5) | Success/error |
|
||||||
|
| `log.set_sd` | `level` (0–5) | Success/error |
|
||||||
|
| `log.set_mqtt` | `level` (0–5) | Success/error |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### MQTT namespace — `MQTTHandler`
|
||||||
|
|
||||||
|
| Command | Required fields | Returns |
|
||||||
|
|---|---|---|
|
||||||
|
| `mqtt.enable` | *(none)* | Success/error |
|
||||||
|
| `mqtt.disable` | *(none)* | Success/error |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Telemetry namespace — `TelemetryHandler` *(new — zero coverage today)*
|
||||||
|
|
||||||
|
| Command | Required fields | Optional fields | Returns |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `telemetry.get_strikes` | *(none)* | — | `{ "strikes": { "0": 1234, "1": 567, ... } }` |
|
||||||
|
| `telemetry.reset_strikes` | *(none)* | `bell` (int) — omit to reset all, include to reset one channel | Success/error |
|
||||||
|
| `telemetry.get_loads` | *(none)* | — | `{ "loads": { "0": 42.5, ... }, "cooling_active": false, "overloaded": [2, 5] }` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Handler → Dependency Map
|
||||||
|
|
||||||
|
| Handler | Dependencies |
|
||||||
|
|---|---|
|
||||||
|
| `PlaybackHandler` | `Player` |
|
||||||
|
| `RelayHandler` | `ConfigManager`, `OutputManager`, `Player` (for safety gate) |
|
||||||
|
| `ClockHandler` | `ConfigManager`, `TimeKeeper` |
|
||||||
|
| `SystemHandler` | `ConfigManager`, `Player`, `Telemetry`, `HealthMonitor` |
|
||||||
|
| `FirmwareHandler` | `FirmwareValidator`, `OTAManager`, `Player` |
|
||||||
|
| `NetworkHandler` | `ConfigManager`, `Networking` |
|
||||||
|
| `FileHandler` | `FileManager` |
|
||||||
|
| `LoggingHandler` | `ConfigManager` |
|
||||||
|
| `TelemetryHandler` | `Telemetry` |
|
||||||
|
| `MQTTHandler` | `ConfigManager`, `MQTTTransport` (direct reference) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## UART Whitelist (v2)
|
||||||
|
|
||||||
|
The UART transport only allows commands that make sense for a slave LCD/button board. All others are silently dropped to prevent feedback loops.
|
||||||
|
|
||||||
|
The LCD is a proper bidirectional client in v2 — it can send requests and receive responses. The old push model (`sync_time_to_lcd`) is retired. The LCD requests `system.get_time` and the response is a normal command reply — no loop possible because replies are not commands.
|
||||||
|
|
||||||
|
```
|
||||||
|
Allowed via UART (whitelist):
|
||||||
|
- ping (connection check)
|
||||||
|
- playback (play/stop from physical buttons)
|
||||||
|
- clock.pause (button-triggered pause)
|
||||||
|
- clock.resume (button-triggered resume)
|
||||||
|
- system.get_time (LCD requests current time — replaces old push model)
|
||||||
|
```
|
||||||
|
|
||||||
|
All other commands are silently dropped by `UARTTransport` before reaching the bus.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## v1 → v2 Legacy Mapping (LegacyAdapter)
|
||||||
|
|
||||||
|
Full translation table for `LegacyAdapter.cpp`. When a client sends `"v": 1` (or omits `v`), this runs first. The adapter extracts `contents["action"]`, combines it with `cmd` to produce the flat v2 command, and strips `action` from contents before dispatch.
|
||||||
|
|
||||||
|
| 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` *(remapped — LCD now uses request/response model)* |
|
||||||
|
| `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` |
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
# LegacyResponseAdapter — v2 → v1 reply translation
|
||||||
|
|
||||||
|
> Written: 2026-09-17
|
||||||
|
> Status: **Active** — temporary migration scaffolding, scoped to a known removal condition
|
||||||
|
> Related: [communication-refactor-plan.md](communication-refactor-plan.md), [reference/api-reference.md](../reference/api-reference.md), [reference/api-reference-v1-legacy.md](../reference/api-reference-v1-legacy.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Why this exists
|
||||||
|
|
||||||
|
The firmware's `LegacyAdapter` (`src/Communication/CommandBus/LegacyAdapter.cpp`) already translates
|
||||||
|
incoming v1 **requests** (no `"v"` field, or `"v":1` — sent by tablets still running the pre-refactor
|
||||||
|
Flutter app) into v2 internal commands, so old and new clients can share the same handler code. That
|
||||||
|
half of the migration bridge works correctly.
|
||||||
|
|
||||||
|
The other half was missing: v2 handlers reply using v2 conventions (namespaced `type` strings, data
|
||||||
|
nested under `"data"` instead of `"payload"`, UPPERCASE status-enum strings, object-keyed
|
||||||
|
`strike_counters` instead of an array). A v1-only app doesn't recognise any of that. Concretely, for
|
||||||
|
`system.status` (the v1 app's `system_info/report_status` poll):
|
||||||
|
|
||||||
|
| Aspect | v1 app expects | v2 firmware sent (before this fix) |
|
||||||
|
|---|---|---|
|
||||||
|
| Reply `type` | `"current_status"` | `"system.status"` |
|
||||||
|
| Structured field container | `payload` | `data` |
|
||||||
|
| `player_status` value | lowercase (`"playing"`, `"idle"`, ...) | UPPERCASE (`"PLAYING"`, `"STOPPED"`, ...) |
|
||||||
|
| Elapsed-time field | `time_elapsed` | `time_elapsed_ms` |
|
||||||
|
| `strike_counters` | JSON array | JSON object keyed `"0".."15"` |
|
||||||
|
|
||||||
|
Because the reply never matched what the app's `sendAndWaitForResponse` matcher was waiting for, the
|
||||||
|
app's own 5-second request timeout fired, hit its `catch` block, and explicitly set
|
||||||
|
`playbackStatus: PlaybackStatus.unavailable` — **while the device was actually playing correctly and
|
||||||
|
had already replied.** This looked like an intermittent connectivity/availability bug but was a pure
|
||||||
|
reply-schema mismatch. `ResponseBuilder::deviceStatus()` (still present in
|
||||||
|
`src/Communication/ResponseBuilder/ResponseBuilder.cpp`) already builds the exact correct v1 shape —
|
||||||
|
it's dead code, unwired since the v2 refactor, which is the strongest evidence this was a regression
|
||||||
|
rather than an intentional break.
|
||||||
|
|
||||||
|
The async `playback` INFO push (`Player::setStatus()`, `src/Player/Player.cpp:519-565`) was checked
|
||||||
|
too and does **not** have this problem — it already uses `type/payload`, `action` (not
|
||||||
|
`player_status`), and lowercase status words, matching what the v1 app expects. No changes were made
|
||||||
|
there.
|
||||||
|
|
||||||
|
## What this migration is (and isn't)
|
||||||
|
|
||||||
|
The plan going forward is to update **all** devices (firmware + tablets) to the v2 API. Until every
|
||||||
|
tablet in the field is confirmed on v2+, some boards running v2 firmware will still be talking to
|
||||||
|
tablets that only understand v1. `LegacyResponseAdapter` exists purely to keep that mixed-fleet window
|
||||||
|
functional — it is not a permanent second protocol.
|
||||||
|
|
||||||
|
**Exit condition:** once fleet/console telemetry confirms zero v1-originated requests (no envelope
|
||||||
|
arriving with `"v"` missing or `"v":1`) for a safe observation period, delete this adapter and
|
||||||
|
`LegacyAdapter` together — see "How to remove" below.
|
||||||
|
|
||||||
|
## What was built
|
||||||
|
|
||||||
|
### `LegacyResponseAdapter` (`src/Communication/CommandBus/LegacyResponseAdapter.{hpp,cpp}`)
|
||||||
|
|
||||||
|
A narrow, allowlisted translator — the reply-side mirror of `LegacyAdapter`. It does **not** attempt a
|
||||||
|
generic v1/v2 schema mapping; it only rewrites the specific `CommandResult` types known to diverge.
|
||||||
|
Today that's just `system.status`. If a future v2 handler introduces another reply shape a v1 client
|
||||||
|
depends on, add a case to `LegacyResponseAdapter.cpp` rather than generalising the mechanism — keeping
|
||||||
|
it a short, explicit list makes it easy to audit and easy to delete in full later.
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
// Returns true and fills `out` if a translation was applied.
|
||||||
|
// Returns false (out untouched) if the result isn't one this adapter
|
||||||
|
// knows how to translate — caller falls back to normal v2 serialisation.
|
||||||
|
bool translateLegacyResponse(const CommandResult& result, JsonDocument& out);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Wiring: capture the *original* request version before dispatch mutates it
|
||||||
|
|
||||||
|
`CommandBus::dispatch()` overwrites `envelope.version = 2` after `LegacyAdapter` translates a v1
|
||||||
|
envelope (so the bus doesn't re-translate on a hypothetical second pass). That happens *before* the
|
||||||
|
reply lambda runs, so the reply lambda can't just read `envelope.version` at reply time — it has to
|
||||||
|
capture the original value by copy, at the point the lambda is constructed (which happens after
|
||||||
|
`envelope.version` is set from the incoming `"v"` field, but before `_bus.dispatch(envelope)` runs).
|
||||||
|
|
||||||
|
Each transport's reply lambda now does this:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
envelope.version = doc["v"] | 1; // (unchanged — existing per-transport default)
|
||||||
|
|
||||||
|
// Capture the ORIGINAL version before CommandBus::dispatch() rewrites
|
||||||
|
// envelope.version to 2 post-translation (see LegacyAdapter.hpp).
|
||||||
|
bool isLegacyRequest = (envelope.version == 1);
|
||||||
|
|
||||||
|
envelope.reply = [this, /* ... */, isLegacyRequest](const CommandResult& result) {
|
||||||
|
JsonDocument resp;
|
||||||
|
if (!isLegacyRequest || !translateLegacyResponse(result, resp)) {
|
||||||
|
// ... existing v2 serialisation, unchanged ...
|
||||||
|
}
|
||||||
|
// ... serialise `resp` and send, unchanged ...
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
If `isLegacyRequest` is false, or the result's `type` isn't one `LegacyResponseAdapter` knows about,
|
||||||
|
behaviour is byte-for-byte identical to before this change — v2 clients and unaffected reply types are
|
||||||
|
untouched.
|
||||||
|
|
||||||
|
### Scope — which transports were changed
|
||||||
|
|
||||||
|
| Transport | Changed? | Reason |
|
||||||
|
|---|---|---|
|
||||||
|
| WebSocket (`WebSocketTransport.cpp`) | ✅ | Primary tablet transport — this is the live bug's path |
|
||||||
|
| MQTT (`MQTTTransport.cpp`) | ✅ | Same request/reply shape, same v1 default; console/backend or any MQTT-side v1 caller gets the same fix |
|
||||||
|
| HTTP (`HTTPTransport.cpp`, `handleCommandRequest`) | ✅ | Defaults unversioned requests to v2 already (`doc["v"] \| 2`, unlike the other transports' `\| 1`), so this only fires if a caller explicitly sends `"v":1` — added for symmetry/completeness, not a known live bug |
|
||||||
|
| HTTP (`HTTPTransport.cpp`, `handleStatusRequest`) | ❌ | Hardcodes `envelope.version = 2` — internal shortcut route, never receives a v1-tagged request |
|
||||||
|
| UART (`UARTTransport.cpp`) | ❌ | Used for board-to-board/internal links per `UARTTransport::WHITELIST`, not tablets. No evidence any UART peer speaks v1. Left alone to avoid unnecessary risk — revisit if that assumption changes |
|
||||||
|
| `CommandBus::broadcast()` | ❌ | Separate mechanism (internal subsystem → client push events, e.g. `_bus.broadcast(CommandResult::info(...))`), unrelated to per-request replies or to `Player`'s playback push. Not exercised by the bug. |
|
||||||
|
|
||||||
|
## How to remove (when the migration is complete)
|
||||||
|
|
||||||
|
This was designed to be deleted as a single, contained change:
|
||||||
|
|
||||||
|
1. Delete `src/Communication/CommandBus/LegacyResponseAdapter.hpp` and `.cpp`.
|
||||||
|
2. In each of `WebSocketTransport.cpp`, `MQTTTransport.cpp`, `HTTPTransport.cpp`:
|
||||||
|
- Remove the `#include ".../LegacyResponseAdapter.hpp"` line.
|
||||||
|
- Remove the `bool isLegacyRequest = ...` line.
|
||||||
|
- Remove the `if (!isLegacyRequest || !translateLegacyResponse(result, resp))` wrapper, keeping the
|
||||||
|
v2 serialisation body unconditional (drop the `if`, keep the `{ ... }` contents).
|
||||||
|
3. Do the same removal for `LegacyAdapter` (see its own header comment in
|
||||||
|
`src/Communication/CommandBus/LegacyAdapter.hpp`) in the same PR — the two are a matched pair; there
|
||||||
|
is no reason to keep one without the other.
|
||||||
|
4. Delete `ResponseBuilder::deviceStatus()` (dead code, superseded by this adapter) if it's still
|
||||||
|
unused at that point — confirm with a repo-wide grep first.
|
||||||
|
5. Update `docs/README.md`'s reference table and this file's own status line to reflect removal, and
|
||||||
|
move `docs/reference/api-reference-v1-legacy.md` content into a clearly historical/archived note if
|
||||||
|
it isn't already treated that way.
|
||||||
|
|
||||||
|
No data migration, no NVS changes, no wire-format changes for v2-only clients — this is a pure code
|
||||||
|
deletion once the exit condition is met.
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
# Backend Task: Subscribe to Vesper MQTT Alert Topics
|
||||||
|
|
||||||
|
> Use this document as a prompt / task brief for implementing the backend side
|
||||||
|
> of the Vesper MQTT alert system. The firmware changes are complete.
|
||||||
|
> Full topic spec: `docs/reference/mqtt-events.md`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What the firmware now publishes
|
||||||
|
|
||||||
|
The Vesper firmware (v155+) publishes on three status topics:
|
||||||
|
|
||||||
|
### 1. `vesper/{device_id}/status/heartbeat` (unchanged)
|
||||||
|
- Every 30 seconds, retained, QoS 1
|
||||||
|
- You already handle this — **no change needed** except: suppress any log entry / display update triggered by heartbeat arrival. Update `last_seen` silently. Only surface an event when the device goes *silent* (no heartbeat for 90s).
|
||||||
|
|
||||||
|
### 2. `vesper/{device_id}/status/alerts` (NEW)
|
||||||
|
- Published only when a subsystem state changes (HEALTHY → WARNING, WARNING → CRITICAL, etc.)
|
||||||
|
- QoS 1, not retained
|
||||||
|
- One message per state transition — not repeated until state changes again
|
||||||
|
|
||||||
|
**Alert payload:**
|
||||||
|
```json
|
||||||
|
{ "subsystem": "FileManager", "state": "WARNING", "msg": "ConfigManager health check failed" }
|
||||||
|
```
|
||||||
|
**Cleared payload (recovery):**
|
||||||
|
```json
|
||||||
|
{ "subsystem": "FileManager", "state": "CLEARED" }
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. `vesper/{device_id}/status/info` (NEW)
|
||||||
|
- Published on significant device state changes (playback start/stop, etc.)
|
||||||
|
- QoS 0, not retained
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "type": "playback_started", "payload": { "melody_uid": "ABC123" } }
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What to implement in the backend (FastAPI + MQTT)
|
||||||
|
|
||||||
|
### Subscribe to new topics
|
||||||
|
|
||||||
|
Add to your MQTT subscription list:
|
||||||
|
```python
|
||||||
|
client.subscribe("vesper/+/status/alerts", qos=1)
|
||||||
|
client.subscribe("vesper/+/status/info", qos=0)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Database model — active alerts per device
|
||||||
|
|
||||||
|
Create a table (or document) to store the current alert state per device:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE device_alerts (
|
||||||
|
device_id TEXT NOT NULL,
|
||||||
|
subsystem TEXT NOT NULL,
|
||||||
|
state TEXT NOT NULL, -- WARNING | CRITICAL | FAILED
|
||||||
|
message TEXT,
|
||||||
|
updated_at TIMESTAMP NOT NULL,
|
||||||
|
PRIMARY KEY (device_id, subsystem)
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
Or equivalent in your ORM / MongoDB / Redis structure.
|
||||||
|
|
||||||
|
### MQTT message handler — alerts topic
|
||||||
|
|
||||||
|
```python
|
||||||
|
def on_alerts_message(device_id: str, payload: dict):
|
||||||
|
subsystem = payload["subsystem"]
|
||||||
|
state = payload["state"]
|
||||||
|
message = payload.get("msg", "")
|
||||||
|
|
||||||
|
if state == "CLEARED":
|
||||||
|
# Remove alert from active set
|
||||||
|
db.device_alerts.delete(device_id=device_id, subsystem=subsystem)
|
||||||
|
else:
|
||||||
|
# Upsert — create or update
|
||||||
|
db.device_alerts.upsert(
|
||||||
|
device_id = device_id,
|
||||||
|
subsystem = subsystem,
|
||||||
|
state = state,
|
||||||
|
message = message,
|
||||||
|
updated_at = now()
|
||||||
|
)
|
||||||
|
|
||||||
|
# Optionally push a WebSocket event to the console UI
|
||||||
|
ws_broadcast(device_id, {"event": "alert_update", "subsystem": subsystem, "state": state})
|
||||||
|
```
|
||||||
|
|
||||||
|
### MQTT message handler — info topic
|
||||||
|
|
||||||
|
```python
|
||||||
|
def on_info_message(device_id: str, payload: dict):
|
||||||
|
event_type = payload["type"]
|
||||||
|
data = payload.get("payload", {})
|
||||||
|
|
||||||
|
# Store or forward as needed — e.g. update device playback state
|
||||||
|
if event_type == "playback_started":
|
||||||
|
db.devices.update(device_id, playback_active=True, melody_uid=data.get("melody_uid"))
|
||||||
|
elif event_type == "playback_stopped":
|
||||||
|
db.devices.update(device_id, playback_active=False, melody_uid=None)
|
||||||
|
```
|
||||||
|
|
||||||
|
### API endpoint — get active alerts for a device
|
||||||
|
|
||||||
|
```
|
||||||
|
GET /api/devices/{device_id}/alerts
|
||||||
|
```
|
||||||
|
|
||||||
|
Returns the current active alert set (the upserted rows from the table above):
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{ "subsystem": "FileManager", "state": "WARNING", "message": "SD mount failed", "updated_at": "..." },
|
||||||
|
{ "subsystem": "TimeKeeper", "state": "WARNING", "message": "NTP sync failed", "updated_at": "..." }
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
An empty array means the device is fully healthy (no active alerts).
|
||||||
|
|
||||||
|
### Console UI guidance
|
||||||
|
|
||||||
|
- Device list: show a coloured dot next to each device (green = no alerts, yellow = warnings, red = critical/failed). Update via WebSocket push.
|
||||||
|
- Device detail page: show an "Active Alerts" section that renders the alert set statically. Do not render a scrolling alert log — just the current state.
|
||||||
|
- When a `CLEARED` event arrives, remove the entry from the UI immediately.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What NOT to do
|
||||||
|
|
||||||
|
- **Do not log every heartbeat** as a visible event. Heartbeats are internal housekeeping.
|
||||||
|
- **Do not poll the device** for health status — the device pushes on change.
|
||||||
|
- **Do not store alerts as an append-only log** — upsert by `(device_id, subsystem)`. The server holds the current state, not a history.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
1. Flash a device with firmware v155+
|
||||||
|
2. Subscribe manually:
|
||||||
|
```bash
|
||||||
|
mosquitto_sub -h <broker> -t "vesper/+/status/alerts" -v
|
||||||
|
mosquitto_sub -h <broker> -t "vesper/+/status/info" -v
|
||||||
|
```
|
||||||
|
3. Remove the SD card from the device — expect a `FileManager` `WARNING` alert within 5 minutes (next health check cycle), or trigger it immediately via:
|
||||||
|
```json
|
||||||
|
{ "v": 2, "cmd": "system.health" }
|
||||||
|
```
|
||||||
|
sent to `vesper/{device_id}/control`
|
||||||
|
4. Reinsert the SD card — expect a `FileManager` `CLEARED` alert on the next health check
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
COMMANDS:
|
||||||
|
|
||||||
|
|
||||||
|
PV26A28BC01R01
|
||||||
|
|
||||||
|
|
||||||
|
{
|
||||||
|
"cmd":"system",
|
||||||
|
"contents":
|
||||||
|
{
|
||||||
|
"action":"force_update",
|
||||||
|
"channel":"beta"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
{
|
||||||
|
"cmd":"system",
|
||||||
|
"contents":
|
||||||
|
{
|
||||||
|
"action":"set_mqtt_log_level",
|
||||||
|
"level":3
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
{
|
||||||
|
"cmd":"system",
|
||||||
|
"contents":
|
||||||
|
{
|
||||||
|
"action":"restart"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
{
|
||||||
|
"cmd":"system_info",
|
||||||
|
"contents":
|
||||||
|
{
|
||||||
|
"action":"get_full_settings"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
"cmd":"system_info",
|
||||||
|
"contents":
|
||||||
|
{
|
||||||
|
"action":"get_full_settings"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
"cmd": "clock_setup",
|
||||||
|
"contents": {
|
||||||
|
"action": "set_alerts",
|
||||||
|
"alertType": "OFF"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
{
|
||||||
|
"cmd":"system_info",
|
||||||
|
"contents":
|
||||||
|
{
|
||||||
|
"action":"get_clock_time"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
{
|
||||||
|
"cmd": "clock_setup",
|
||||||
|
"contents": {
|
||||||
|
"action": "set_rtc_time",
|
||||||
|
"timestamp": 1775329309,
|
||||||
|
"timezone_offset": 10800,
|
||||||
|
"dst_offset": 3600,
|
||||||
|
"timezone_name": "EEST"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
{
|
||||||
|
"cmd": "playback",
|
||||||
|
"contents": {
|
||||||
|
"action": "stop",
|
||||||
|
"name": "one_bell_test",
|
||||||
|
"uid": "01DegzV9FA8tYbQpkIHR",
|
||||||
|
"url": "https://example.com/melody.bin",
|
||||||
|
"speed": 500,
|
||||||
|
"note_assignments": [4, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||||
|
"segment_duration": 15000,
|
||||||
|
"pause_duration": 5000,
|
||||||
|
"total_duration": 60000,
|
||||||
|
"continuous_loop": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
{
|
||||||
|
"cmd": "playback",
|
||||||
|
"contents": {
|
||||||
|
"action": "play",
|
||||||
|
"name": "Great Friday Mournfull",
|
||||||
|
"uid": "mournfull_gf_1_4",
|
||||||
|
"url": "https://storage.googleapis.com/bs-vesper.firebasestorage.app/melodies/95fd22bb-56fb-4635-a1c3-51cad3a0ccb6/mournfull_gf_1_4.bsm",
|
||||||
|
"speed": 600,
|
||||||
|
"note_assignments": [1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||||
|
"segment_duration": 15000,
|
||||||
|
"pause_duration": 5000,
|
||||||
|
"total_duration": 60000,
|
||||||
|
"continuous_loop": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
{
|
||||||
|
"cmd": "playback",
|
||||||
|
"contents": {
|
||||||
|
"action": "stop",
|
||||||
|
"uid": "one_bell_test",
|
||||||
|
"speed": 100,
|
||||||
|
"note_assignments": [1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||||
|
"segment_duration": 15000,
|
||||||
|
"pause_duration": 5000,
|
||||||
|
"total_duration": 60000,
|
||||||
|
"continuous_loop": true
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
Features:
|
||||||
|
|
||||||
|
// mqtt topics:
|
||||||
|
vesper/<DEVID>/data // Data sent from the controller
|
||||||
|
vesper/<DEVID>/control // Commands sent to the controller
|
||||||
|
vesper/<DEVID>/kiosk/event // Kiosk Mode Events
|
||||||
|
vesper/<DEVID>/kiosk/info // Kiosk Mode General Info
|
||||||
|
|
||||||
|
// WiFi Local AP
|
||||||
|
|
||||||
|
BellSystemsInfra
|
||||||
|
|
||||||
|
v3sp3r_8998!
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
- WiFi Manager (captive portal with hotspot)
|
||||||
|
- MQTT Support (Subscribing and Publishing)
|
||||||
|
- WebSocket Support (Sending and Receiving)
|
||||||
|
- JSON Format Messaging (both MQTT and WS)
|
||||||
|
- SD Card Handling and File Ops
|
||||||
|
- Stand-alone Player/BellEngine Classes, with functions to Play/Pause/Stop etc
|
||||||
|
- NoteAssignments - Effectively mapping Notes to Bells
|
||||||
|
- Independent SubSystems for all Core Functions (Networking/Comms/Scheduling/Logging/etc)
|
||||||
|
- Custom Relay Output Maps and Timings (saved on SD)
|
||||||
|
- Timekeeper with RTC/Clock/Alerts/Scheduling features
|
||||||
|
- OTA Update Functionality with Versioning/Rollbacks/Checksum/Firmware Validation/NTP Sync
|
||||||
|
- Global logger with Mode Selection (None, Error, Warning, Info, Debug, Verbose)
|
||||||
|
- UDP Listener for Auto Device Discovery
|
||||||
|
- Datalogging and Statistics:
|
||||||
|
- Counter for each bell (counts total times the bell ringed)
|
||||||
|
- Counter per bell, beats/minute for reliability and thermal protection. Warranty Void scenario.
|
||||||
|
- Ability to change Log levels (in-app)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
ToDo Features:
|
||||||
|
|
||||||
|
- (optional) Add Bluetooth support
|
||||||
|
- (optional) Add WiFi Direct AP Support
|
||||||
|
- (optional) Add PCB Temperature Sensor Support
|
||||||
|
|
||||||
|
- (critical) Counters and Statistics:
|
||||||
|
- Counter per playback, to figure out which melody is the most played.
|
||||||
|
This can be implemented on the App itself. Doesn't need to be on the Device.
|
||||||
|
|
||||||
|
- Create a "humanizer" mode that randomizes delays on playback to simulate human ringing.
|
||||||
|
|
||||||
|
|
||||||
|
ToDo Fixes:
|
||||||
|
|
||||||
|
- (small significance) Fix each Log's level Correctly + Fix Log Syntax where needed
|
||||||
|
- (medium significance) BellGuard: Make the buttons functional.
|
||||||
|
|
||||||
|
- Fix IP Settings not applying. More Specifically, Variables inside the Components take long to update. Either Ditch the components, or find another way.
|
||||||
|
- On Very fast playback speeds and small programs that will run for less than a second or so, STOP isn't sent properly. Player keeps indicating "playing".
|
||||||
|
- When a new user is created, set default PINs for both Quick Settings, and Settings.
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
/*
|
||||||
|
* ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
* is31fl3193_led_test.ino — Bring-up test for IS31FL3193 3-channel LED driver
|
||||||
|
* ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
*
|
||||||
|
* TEMPORARY TEST SKETCH — not part of the Vesper firmware build.
|
||||||
|
* Open directly in Arduino IDE and flash it on its own (does NOT go through
|
||||||
|
* PlatformIO / src/main.cpp). Delete once the chip/board is verified.
|
||||||
|
*
|
||||||
|
* Hardware:
|
||||||
|
* - Board: Kincony KC868-A6 (ESP32-D0WD-V3)
|
||||||
|
* - I2C bus: SDA = GPIO4, SCL = GPIO15 (see src/main.cpp Wire.begin(4, 15))
|
||||||
|
* - Chip: IS31FL3193-DLS2-TR, address 0x6B (AD pin tied to VCC)
|
||||||
|
* - OUT1/OUT2/OUT3 are CURRENT SOURCE outputs, LED anodes on OUT1~OUT3,
|
||||||
|
* cathodes to GND.
|
||||||
|
*
|
||||||
|
* Register map — read directly from the official Lumissil datasheet
|
||||||
|
* (IS31FL3193_DS.pdf, Rev. D, 2024-03-28):
|
||||||
|
* 0x00 Shutdown Register D5=EN (1=channels enabled), D0=SSD (1=shutdown!)
|
||||||
|
* Must write EN=1, SSD=0 -> 0x20 to enable.
|
||||||
|
* 0x02 LED Mode Register D5=RGB (0=PWM control mode, 1=one-shot mode)
|
||||||
|
* 0x03 Current Setting D4:D2=CS
|
||||||
|
* 0x04 PWM Register OUT1 0-255 duty cycle
|
||||||
|
* 0x05 PWM Register OUT2 0-255 duty cycle
|
||||||
|
* 0x06 PWM Register OUT3 0-255 duty cycle
|
||||||
|
* 0x07 Update Register write 0x00 to latch PWM/LED-control changes
|
||||||
|
*
|
||||||
|
* NOTE: this board is missing the datasheet-recommended VCC decoupling caps
|
||||||
|
* (1uF + 0.1uF) and the LED-side 1uF cap. Suspected cause of no output: the
|
||||||
|
* current-source stage's switching transient (up to 3 channels x 42mA) isn't
|
||||||
|
* being absorbed locally, so the bias/reference circuit glitches every time
|
||||||
|
* an output tries to turn on, while the low-current digital I2C block keeps
|
||||||
|
* working fine regardless. This variant minimizes that transient as a test:
|
||||||
|
* only ONE channel active at a time, lowest current setting (5mA instead of
|
||||||
|
* 42mA), and a slow software ramp instead of an instant full-brightness step.
|
||||||
|
* If this makes the LED light where full-brightness/all-channels didn't,
|
||||||
|
* that's strong confirmation the missing caps are the real fix needed.
|
||||||
|
*
|
||||||
|
* Behavior: OUT1 -> OUT2 -> OUT3, one at a time, each ramping 0->dim->0.
|
||||||
|
* ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <Wire.h>
|
||||||
|
|
||||||
|
#define I2C_SDA_PIN 4
|
||||||
|
#define I2C_SCL_PIN 15
|
||||||
|
#define IS31FL3193_ADDR 0x6B
|
||||||
|
|
||||||
|
#define REG_SHUTDOWN 0x00
|
||||||
|
#define REG_LED_MODE 0x02
|
||||||
|
#define REG_CURRENT 0x03
|
||||||
|
#define REG_PWM_OUT1 0x04
|
||||||
|
#define REG_PWM_OUT2 0x05
|
||||||
|
#define REG_PWM_OUT3 0x06
|
||||||
|
#define REG_UPDATE 0x07
|
||||||
|
#define REG_LED_CONTROL 0x1D
|
||||||
|
#define REG_RESET 0x2F
|
||||||
|
|
||||||
|
#define SHUTDOWN_NORMAL 0x20 // EN=1, SSD=0 — channels enabled, not in shutdown
|
||||||
|
#define MODE_PWM 0x00
|
||||||
|
#define LED_CONTROL_ALL_ON 0x07
|
||||||
|
#define CURRENT_5MA (0x2 << 2) // lowest available current step
|
||||||
|
|
||||||
|
#define MAX_DIM_PWM 40 // cap brightness low — small fraction of 255
|
||||||
|
#define RAMP_STEP 2
|
||||||
|
#define RAMP_DELAY_MS 30 // slow ramp -> gentler current transient
|
||||||
|
#define HOLD_MS 500
|
||||||
|
#define GAP_MS 300 // pause between channels, all outputs off
|
||||||
|
|
||||||
|
void writeReg(uint8_t reg, uint8_t value) {
|
||||||
|
Wire.beginTransmission(IS31FL3193_ADDR);
|
||||||
|
Wire.write(reg);
|
||||||
|
Wire.write(value);
|
||||||
|
Wire.endTransmission();
|
||||||
|
}
|
||||||
|
|
||||||
|
void update() {
|
||||||
|
writeReg(REG_UPDATE, 0x00);
|
||||||
|
}
|
||||||
|
|
||||||
|
void setAll(uint8_t out1, uint8_t out2, uint8_t out3) {
|
||||||
|
writeReg(REG_PWM_OUT1, out1);
|
||||||
|
writeReg(REG_PWM_OUT2, out2);
|
||||||
|
writeReg(REG_PWM_OUT3, out3);
|
||||||
|
update();
|
||||||
|
}
|
||||||
|
|
||||||
|
void rampChannel(int channel) {
|
||||||
|
// channel: 0=OUT1, 1=OUT2, 2=OUT3
|
||||||
|
const char* names[3] = {"OUT1", "OUT2", "OUT3"};
|
||||||
|
Serial.printf("%s -> ramping up (low brightness, low current)\n", names[channel]);
|
||||||
|
|
||||||
|
for (int v = 0; v <= MAX_DIM_PWM; v += RAMP_STEP) {
|
||||||
|
uint8_t out1 = (channel == 0) ? v : 0;
|
||||||
|
uint8_t out2 = (channel == 1) ? v : 0;
|
||||||
|
uint8_t out3 = (channel == 2) ? v : 0;
|
||||||
|
setAll(out1, out2, out3);
|
||||||
|
delay(RAMP_DELAY_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
delay(HOLD_MS);
|
||||||
|
|
||||||
|
for (int v = MAX_DIM_PWM; v >= 0; v -= RAMP_STEP) {
|
||||||
|
uint8_t out1 = (channel == 0) ? v : 0;
|
||||||
|
uint8_t out2 = (channel == 1) ? v : 0;
|
||||||
|
uint8_t out3 = (channel == 2) ? v : 0;
|
||||||
|
setAll(out1, out2, out3);
|
||||||
|
delay(RAMP_DELAY_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
setAll(0, 0, 0);
|
||||||
|
delay(GAP_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
void setup() {
|
||||||
|
Serial.begin(115200);
|
||||||
|
delay(1000);
|
||||||
|
Serial.println("=== IS31FL3193 LED Test — one channel at a time, low brightness ===");
|
||||||
|
|
||||||
|
Wire.begin(I2C_SDA_PIN, I2C_SCL_PIN);
|
||||||
|
|
||||||
|
writeReg(REG_RESET, 0x00);
|
||||||
|
delay(10);
|
||||||
|
writeReg(REG_SHUTDOWN, SHUTDOWN_NORMAL);
|
||||||
|
delay(10);
|
||||||
|
writeReg(REG_LED_MODE, MODE_PWM);
|
||||||
|
writeReg(REG_CURRENT, CURRENT_5MA);
|
||||||
|
writeReg(REG_LED_CONTROL, LED_CONTROL_ALL_ON);
|
||||||
|
update();
|
||||||
|
setAll(0, 0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
rampChannel(0);
|
||||||
|
rampChannel(1);
|
||||||
|
rampChannel(2);
|
||||||
|
Serial.println("=== cycle complete, restarting ===\n");
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
/*
|
||||||
|
* ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
* pcf8575_external_diagnostic.ino — Per-pin write + readback test, external PCF8575
|
||||||
|
* ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
*
|
||||||
|
* TEMPORARY TEST SKETCH — not part of the Vesper firmware build.
|
||||||
|
* Open directly in Arduino IDE and flash it on its own (does NOT go through
|
||||||
|
* PlatformIO / src/main.cpp). Delete once the chip is verified.
|
||||||
|
*
|
||||||
|
* Purpose: isolate whether P00-P02 (indices 0-2) failing to fire is a software
|
||||||
|
* problem (write never reaching the chip / shadow register not flushing) or a
|
||||||
|
* hardware problem (chip accepts the write but can't sink the pin).
|
||||||
|
*
|
||||||
|
* For each pin 0-15:
|
||||||
|
* 1. Write LOW.
|
||||||
|
* 2. Immediately read back via digitalRead() — this tells us what the
|
||||||
|
* library's shadow register / the chip itself reports.
|
||||||
|
* 3. Hold LOW for HOLD_MS so you can probe the physical pin with a meter.
|
||||||
|
* 4. Write HIGH, read back again, hold OFF_MS.
|
||||||
|
*
|
||||||
|
* How to interpret:
|
||||||
|
* - Readback says LOW, meter says ~3.3V -> chip accepted the write but
|
||||||
|
* can't sink the pin -> hardware fault (bad driver transistor on that pin).
|
||||||
|
* - Readback says HIGH (write didn't take) -> library/addressing issue,
|
||||||
|
* not chip damage. Check pin index mapping / I2C bus health on retry.
|
||||||
|
* - Readback says LOW, meter says ~0V -> pin is fine.
|
||||||
|
*
|
||||||
|
* Hardware:
|
||||||
|
* - Board: Kincony KC868-A6 (ESP32-D0WD-V3)
|
||||||
|
* - I2C bus: SDA = GPIO4, SCL = GPIO15 (see src/main.cpp Wire.begin(4, 15))
|
||||||
|
* - Chip: PCF8575, address 0x20 (external expansion board)
|
||||||
|
*
|
||||||
|
* Library: Adafruit PCF8575 (same library the firmware uses in
|
||||||
|
* src/OutputManager/OutputManager.cpp)
|
||||||
|
*
|
||||||
|
* Convention: ACTIVE-LOW outputs, matching OutputManager::firePhysicalOutput()
|
||||||
|
* — LOW = relay energized/fired, HIGH = relay off.
|
||||||
|
* ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <Wire.h>
|
||||||
|
#include <Adafruit_PCF8575.h>
|
||||||
|
|
||||||
|
// ── Config ───────────────────────────────────────────────────────────────────
|
||||||
|
#define I2C_SDA_PIN 4
|
||||||
|
#define I2C_SCL_PIN 15
|
||||||
|
#define PCF8575_ADDR 0x20
|
||||||
|
#define NUM_OUTPUTS 16
|
||||||
|
|
||||||
|
#define HOLD_MS 3000 // time held LOW — probe the pin during this window
|
||||||
|
#define OFF_MS 500
|
||||||
|
|
||||||
|
#define FIRED LOW // active-low: LOW = relay on
|
||||||
|
#define OFF HIGH // active-low: HIGH = relay off
|
||||||
|
|
||||||
|
Adafruit_PCF8575 pcf;
|
||||||
|
|
||||||
|
// P00-P02 (indices 0-2) are the pins reported as not firing on the board.
|
||||||
|
bool isSuspect(uint8_t i) { return i <= 2; }
|
||||||
|
|
||||||
|
void allOff() {
|
||||||
|
for (uint8_t i = 0; i < NUM_OUTPUTS; i++) pcf.digitalWrite(i, OFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
void setup() {
|
||||||
|
Serial.begin(115200);
|
||||||
|
delay(1000);
|
||||||
|
Serial.println();
|
||||||
|
Serial.println("=== External PCF8575 — per-pin write/readback diagnostic ===");
|
||||||
|
|
||||||
|
Wire.begin(I2C_SDA_PIN, I2C_SCL_PIN);
|
||||||
|
|
||||||
|
if (!pcf.begin(PCF8575_ADDR, &Wire)) {
|
||||||
|
Serial.printf("FAILED to initialize PCF8575 at 0x%02X — check wiring/address.\n", PCF8575_ADDR);
|
||||||
|
while (true) { delay(1000); }
|
||||||
|
}
|
||||||
|
Serial.printf("PCF8575 initialized at 0x%02X\n", PCF8575_ADDR);
|
||||||
|
|
||||||
|
for (uint8_t i = 0; i < NUM_OUTPUTS; i++) pcf.pinMode(i, OUTPUT);
|
||||||
|
allOff();
|
||||||
|
|
||||||
|
Serial.println("Each pin holds LOW for 3s — probe the physical pin with a");
|
||||||
|
Serial.println("multimeter during that window. Compare against the printed");
|
||||||
|
Serial.println("readback value.");
|
||||||
|
Serial.println();
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
for (uint8_t i = 0; i < NUM_OUTPUTS; i++) {
|
||||||
|
const char* tag = isSuspect(i) ? " <-- SUSPECT PIN (P0x reported dead)" : "";
|
||||||
|
|
||||||
|
bool writeOk = pcf.digitalWrite(i, FIRED);
|
||||||
|
delay(10);
|
||||||
|
bool readLow = (pcf.digitalRead(i) == LOW);
|
||||||
|
|
||||||
|
Serial.print("Pin ");
|
||||||
|
Serial.print(i);
|
||||||
|
Serial.print(" (P");
|
||||||
|
Serial.print((i < 8) ? 0 : 1);
|
||||||
|
Serial.print(i % 8);
|
||||||
|
Serial.print(") -> write_ok=");
|
||||||
|
Serial.print(writeOk);
|
||||||
|
Serial.print(" readback=");
|
||||||
|
Serial.print(readLow ? "LOW" : "HIGH");
|
||||||
|
Serial.println(tag);
|
||||||
|
|
||||||
|
delay(HOLD_MS);
|
||||||
|
|
||||||
|
pcf.digitalWrite(i, OFF);
|
||||||
|
delay(OFF_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.println("=== cycle complete, restarting ===\n");
|
||||||
|
delay(200);
|
||||||
|
}
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
/*
|
||||||
|
* ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
* pcf_22_relay_sequence_test.ino — Combined bring-up test: onboard 6 + external 16
|
||||||
|
* ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
*
|
||||||
|
* TEMPORARY TEST SKETCH — not part of the Vesper firmware build.
|
||||||
|
* Open directly in Arduino IDE and flash it on its own (does NOT go through
|
||||||
|
* PlatformIO / src/main.cpp). Delete once both chips are verified.
|
||||||
|
*
|
||||||
|
* Purpose: treat the board as one 22-relay unit —
|
||||||
|
* - Outputs 0-5 = onboard PCF8574 (KC868-A6 relays, 6ch)
|
||||||
|
* - Outputs 6-21 = external PCF8575 (your 16ch expansion board)
|
||||||
|
*
|
||||||
|
* Sequence:
|
||||||
|
* 1. Fire all 22 relays in order, one at a time (onboard 1-6, then external 1-16).
|
||||||
|
* 2. Flash all 22 relays together ALL_FLASH_COUNT times (on/off/on/off...).
|
||||||
|
* 3. Repeat forever.
|
||||||
|
*
|
||||||
|
* Hardware:
|
||||||
|
* - Board: Kincony KC868-A6 (ESP32-D0WD-V3)
|
||||||
|
* - I2C bus: SDA = GPIO4, SCL = GPIO15 (see src/main.cpp Wire.begin(4, 15))
|
||||||
|
* - Chip 1: PCF8574, address 0x24 (onboard relay outputs)
|
||||||
|
* - Chip 2: PCF8575, address 0x20 (external expansion board)
|
||||||
|
* - Both chips share the same I2C bus/address space as the firmware —
|
||||||
|
* do NOT run this at the same time as the main Vesper firmware.
|
||||||
|
*
|
||||||
|
* Library: Adafruit PCF8574 + Adafruit PCF8575 (same libraries the firmware
|
||||||
|
* uses in src/OutputManager/OutputManager.cpp)
|
||||||
|
*
|
||||||
|
* Convention: ACTIVE-LOW outputs, matching OutputManager::firePhysicalOutput()
|
||||||
|
* — LOW = relay energized/fired, HIGH = relay off.
|
||||||
|
* ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <Wire.h>
|
||||||
|
#include <Adafruit_PCF8574.h>
|
||||||
|
#include <Adafruit_PCF8575.h>
|
||||||
|
|
||||||
|
// ── Config ───────────────────────────────────────────────────────────────────
|
||||||
|
#define I2C_SDA_PIN 4
|
||||||
|
#define I2C_SCL_PIN 15
|
||||||
|
|
||||||
|
#define ONBOARD_ADDR 0x24 // KC868-A6 relay PCF8574
|
||||||
|
#define EXTERNAL_ADDR 0x20 // External PCF8575
|
||||||
|
|
||||||
|
#define ONBOARD_COUNT 6
|
||||||
|
#define EXTERNAL_COUNT 16
|
||||||
|
#define TOTAL_COUNT (ONBOARD_COUNT + EXTERNAL_COUNT) // 22
|
||||||
|
|
||||||
|
#define STEP_ON_MS 150
|
||||||
|
#define STEP_OFF_MS 30
|
||||||
|
|
||||||
|
#define ALL_FLASH_COUNT 5 // how many times to flash all 22 together
|
||||||
|
#define ALL_ON_MS 300
|
||||||
|
#define ALL_OFF_MS 300
|
||||||
|
|
||||||
|
#define CYCLE_PAUSE_MS 1500
|
||||||
|
|
||||||
|
#define FIRED LOW // active-low: LOW = relay on
|
||||||
|
#define OFF HIGH // active-low: HIGH = relay off
|
||||||
|
|
||||||
|
Adafruit_PCF8574 onboard;
|
||||||
|
Adafruit_PCF8575 external;
|
||||||
|
|
||||||
|
void allOff() {
|
||||||
|
for (uint8_t i = 0; i < ONBOARD_COUNT; i++) onboard.digitalWrite(i, OFF);
|
||||||
|
for (uint8_t i = 0; i < EXTERNAL_COUNT; i++) external.digitalWrite(i, OFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
void allOn() {
|
||||||
|
for (uint8_t i = 0; i < ONBOARD_COUNT; i++) onboard.digitalWrite(i, FIRED);
|
||||||
|
for (uint8_t i = 0; i < EXTERNAL_COUNT; i++) external.digitalWrite(i, FIRED);
|
||||||
|
}
|
||||||
|
|
||||||
|
void setup() {
|
||||||
|
Serial.begin(115200);
|
||||||
|
delay(1000);
|
||||||
|
Serial.println();
|
||||||
|
Serial.println("=== 22-Relay Sequence + Flash Test (onboard 6 + external 16) ===");
|
||||||
|
|
||||||
|
Wire.begin(I2C_SDA_PIN, I2C_SCL_PIN);
|
||||||
|
|
||||||
|
if (!onboard.begin(ONBOARD_ADDR, &Wire)) {
|
||||||
|
Serial.printf("FAILED to init onboard PCF8574 at 0x%02X\n", ONBOARD_ADDR);
|
||||||
|
while (true) { delay(1000); }
|
||||||
|
}
|
||||||
|
Serial.printf("Onboard PCF8574 OK at 0x%02X\n", ONBOARD_ADDR);
|
||||||
|
|
||||||
|
if (!external.begin(EXTERNAL_ADDR, &Wire)) {
|
||||||
|
Serial.printf("FAILED to init external PCF8575 at 0x%02X\n", EXTERNAL_ADDR);
|
||||||
|
while (true) { delay(1000); }
|
||||||
|
}
|
||||||
|
Serial.printf("External PCF8575 OK at 0x%02X\n", EXTERNAL_ADDR);
|
||||||
|
|
||||||
|
for (uint8_t i = 0; i < ONBOARD_COUNT; i++) onboard.pinMode(i, OUTPUT);
|
||||||
|
for (uint8_t i = 0; i < EXTERNAL_COUNT; i++) external.pinMode(i, OUTPUT);
|
||||||
|
allOff();
|
||||||
|
|
||||||
|
Serial.printf("Ready. %d onboard + %d external = %d total relays.\n",
|
||||||
|
ONBOARD_COUNT, EXTERNAL_COUNT, TOTAL_COUNT);
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
// ── Step 1: fire all 22 relays in sequence, one at a time ──────────────
|
||||||
|
Serial.println("--- Sequence: onboard 1-6, then external 1-16 ---");
|
||||||
|
for (uint8_t i = 0; i < ONBOARD_COUNT; i++) {
|
||||||
|
Serial.printf("Onboard relay %d -> ON\n", i + 1);
|
||||||
|
onboard.digitalWrite(i, FIRED);
|
||||||
|
delay(STEP_ON_MS);
|
||||||
|
onboard.digitalWrite(i, OFF);
|
||||||
|
delay(STEP_OFF_MS);
|
||||||
|
}
|
||||||
|
for (uint8_t i = 0; i < EXTERNAL_COUNT; i++) {
|
||||||
|
Serial.printf("External relay %d -> ON\n", i + 1);
|
||||||
|
external.digitalWrite(i, FIRED);
|
||||||
|
delay(STEP_ON_MS);
|
||||||
|
external.digitalWrite(i, OFF);
|
||||||
|
delay(STEP_OFF_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Step 2: flash all 22 together, several times ───────────────────────
|
||||||
|
Serial.printf("--- Flashing all %d relays together x%d ---\n", TOTAL_COUNT, ALL_FLASH_COUNT);
|
||||||
|
for (uint8_t flash = 0; flash < ALL_FLASH_COUNT; flash++) {
|
||||||
|
Serial.printf("Flash %d: ALL ON\n", flash + 1);
|
||||||
|
allOn();
|
||||||
|
delay(ALL_ON_MS);
|
||||||
|
|
||||||
|
Serial.printf("Flash %d: ALL OFF\n", flash + 1);
|
||||||
|
allOff();
|
||||||
|
delay(ALL_OFF_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.println("=== cycle complete, restarting ===\n");
|
||||||
|
delay(CYCLE_PAUSE_MS);
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,131 @@
|
|||||||
|
# 💓 MQTT Heartbeat Feature
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
Implemented a **retained MQTT heartbeat** system that sends periodic status updates every 30 seconds when the controller is connected to MQTT.
|
||||||
|
|
||||||
|
## What It Does
|
||||||
|
|
||||||
|
### Heartbeat Message
|
||||||
|
Every 30 seconds, the controller publishes a **retained** message to:
|
||||||
|
```
|
||||||
|
vesper/{deviceID}/status/heartbeat
|
||||||
|
```
|
||||||
|
|
||||||
|
### Message Format
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "INFO",
|
||||||
|
"type": "heartbeat",
|
||||||
|
"payload": {
|
||||||
|
"device_id": "VESPER-ABC123",
|
||||||
|
"firmware_version": "130",
|
||||||
|
"timestamp": "Uptime: 5h 23m 45s",
|
||||||
|
"ip_address": "192.168.1.100",
|
||||||
|
"gateway": "192.168.1.1",
|
||||||
|
"uptime_ms": 19425000,
|
||||||
|
"rssi": -62
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Key Features
|
||||||
|
✅ **Retained Message** - Only the LAST heartbeat stays on the broker
|
||||||
|
✅ **Auto-Start** - Begins when MQTT connects
|
||||||
|
✅ **Auto-Stop** - Stops when MQTT disconnects
|
||||||
|
✅ **30-Second Interval** - Periodic updates
|
||||||
|
✅ **First Beat Immediate** - Sends first heartbeat right after connecting
|
||||||
|
✅ **QoS 1** - Reliable delivery
|
||||||
|
|
||||||
|
## Why This is Awesome
|
||||||
|
|
||||||
|
### For Your Flutter App
|
||||||
|
1. **Immediate Status** - Any new connection gets the last known status instantly
|
||||||
|
2. **Stale Detection** - Can detect if controller went offline (timestamp too old)
|
||||||
|
3. **Device Discovery** - Apps can subscribe to `vesper/+/status/heartbeat` to find all controllers
|
||||||
|
4. **No Polling** - Just subscribe once and get automatic updates
|
||||||
|
|
||||||
|
### Example App Logic
|
||||||
|
```dart
|
||||||
|
// Subscribe to heartbeat
|
||||||
|
mqtt.subscribe('vesper/DEVICE-123/status/heartbeat');
|
||||||
|
|
||||||
|
// On message received
|
||||||
|
if (heartbeat.uptime_ms > lastSeen.uptime_ms + 120000) {
|
||||||
|
// No heartbeat for 2+ minutes = controller offline
|
||||||
|
showOfflineWarning();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Implementation Details
|
||||||
|
|
||||||
|
### Files Modified
|
||||||
|
1. **MQTTAsyncClient.hpp** - Added heartbeat timer and methods
|
||||||
|
2. **MQTTAsyncClient.cpp** - Implemented heartbeat logic
|
||||||
|
3. **Networking.hpp** - Added `getGateway()` method
|
||||||
|
4. **Networking.cpp** - Implemented `getGateway()` method
|
||||||
|
|
||||||
|
### New Methods Added
|
||||||
|
```cpp
|
||||||
|
void startHeartbeat(); // Start 30s periodic timer
|
||||||
|
void stopHeartbeat(); // Stop timer
|
||||||
|
void publishHeartbeat(); // Build and publish message
|
||||||
|
void heartbeatTimerCallback(); // Timer callback handler
|
||||||
|
```
|
||||||
|
|
||||||
|
### Timer Configuration
|
||||||
|
- **Type**: FreeRTOS Software Timer
|
||||||
|
- **Mode**: Auto-reload (repeating)
|
||||||
|
- **Period**: 30,000 ms (30 seconds)
|
||||||
|
- **Core**: Runs on Core 0 (MQTT task core)
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
### How to Test
|
||||||
|
1. Flash the firmware
|
||||||
|
2. Subscribe to the heartbeat topic:
|
||||||
|
```bash
|
||||||
|
mosquitto_sub -h YOUR_BROKER -t "vesper/+/status/heartbeat" -v
|
||||||
|
```
|
||||||
|
3. You should see heartbeats every 30 seconds
|
||||||
|
4. Disconnect the controller - the last message stays retained
|
||||||
|
5. Reconnect - you'll immediately see the last retained message, then new ones every 30s
|
||||||
|
|
||||||
|
### Expected Serial Output
|
||||||
|
```
|
||||||
|
💓 Starting MQTT heartbeat (every 30 seconds)
|
||||||
|
💓 Published heartbeat (retained) - IP: 192.168.1.100, Uptime: 45000ms
|
||||||
|
💓 Published heartbeat (retained) - IP: 192.168.1.100, Uptime: 75000ms
|
||||||
|
❤️ Stopped MQTT heartbeat (when MQTT disconnects)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Future Enhancements (Optional)
|
||||||
|
|
||||||
|
### Possible Additions:
|
||||||
|
- Add actual RTC timestamp (instead of just uptime)
|
||||||
|
- Add free heap memory
|
||||||
|
- Add current playback status
|
||||||
|
- Add bell configuration version/hash
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
### Current Settings (can be changed in MQTTAsyncClient.hpp):
|
||||||
|
```cpp
|
||||||
|
static const unsigned long HEARTBEAT_INTERVAL = 30000; // 30 seconds
|
||||||
|
```
|
||||||
|
|
||||||
|
To change interval to 60 seconds:
|
||||||
|
```cpp
|
||||||
|
static const unsigned long HEARTBEAT_INTERVAL = 60000; // 60 seconds
|
||||||
|
```
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
- Message is published with **QoS 1** (at least once delivery)
|
||||||
|
- Message is **retained** (broker keeps last message)
|
||||||
|
- Timer starts automatically when MQTT connects
|
||||||
|
- Timer stops automatically when MQTT disconnects
|
||||||
|
- First heartbeat is sent immediately upon connection (no 30s wait)
|
||||||
|
|
||||||
|
---
|
||||||
|
**Feature Implemented**: January 2025
|
||||||
|
**Version**: Firmware v130+
|
||||||
|
**Status**: ✅ Production Ready
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
- Uptime on the hearbeat maxes out at 299 days.
|
||||||
@@ -0,0 +1,828 @@
|
|||||||
|
# 🔔 VESPER ESP32 Communication API Reference v3.0
|
||||||
|
|
||||||
|
> **Complete command reference for Vesper Bell Automation System with Grouped Commands**
|
||||||
|
> Version: 3.0 | Updated: 2025-09-15
|
||||||
|
> Supports: MQTT + WebSocket protocols with multi-client support and batch processing
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀 Getting Started
|
||||||
|
|
||||||
|
### Connection Protocols
|
||||||
|
- **MQTT**: `vesper/{device_id}/control` (commands) → `vesper/{device_id}/data` (responses)
|
||||||
|
- **WebSocket**: `ws://{esp_ip}/ws` (bidirectional)
|
||||||
|
- **UDP Discovery**: Broadcast on configured port for device discovery
|
||||||
|
- **UDP Port**: 32101
|
||||||
|
|
||||||
|
### WebSocket Client Identification
|
||||||
|
**Required for WebSocket clients to receive targeted messages:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cmd": "system",
|
||||||
|
"contents": {
|
||||||
|
"action": "identify",
|
||||||
|
"device_type": "master" // or "secondary"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "SUCCESS",
|
||||||
|
"type": "identify",
|
||||||
|
"payload": "Device identified as master"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📋 Command Categories (NEW GROUPED ARCHITECTURE)
|
||||||
|
|
||||||
|
- [🖥️ System Commands](#️-system-commands)
|
||||||
|
- [🎵 Playback Control](#-playback-control)
|
||||||
|
- [📁 File Management](#-file-management)
|
||||||
|
- [🔧 Relay Setup](#-relay-setup)
|
||||||
|
- [🕐 Clock Setup](#-clock-setup)
|
||||||
|
- [📢 Information Messages](#-information-messages)
|
||||||
|
- [🌐 Network & Discovery](#-network--discovery)
|
||||||
|
- [🔄 Legacy Command Support](#-legacy-command-support)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🖥️ System Commands
|
||||||
|
|
||||||
|
### 🏓 Ping Test
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cmd": "system",
|
||||||
|
"contents": {
|
||||||
|
"action": "ping"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "SUCCESS",
|
||||||
|
"type": "pong",
|
||||||
|
"payload": ""
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 📊 System Status
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cmd": "system",
|
||||||
|
"contents": {
|
||||||
|
"action": "status"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "SUCCESS",
|
||||||
|
"type": "current_status",
|
||||||
|
"payload": {
|
||||||
|
"player_status": "playing",
|
||||||
|
"time_elapsed": 45230,
|
||||||
|
"projected_run_time": 34598,
|
||||||
|
"timestamp": 1699123456789
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 👤 Device Identification (WebSocket Only)
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cmd": "system",
|
||||||
|
"contents": {
|
||||||
|
"action": "identify",
|
||||||
|
"device_type": "master"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🔄 Restart Device
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cmd": "system",
|
||||||
|
"contents": {
|
||||||
|
"action": "restart"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "SUCCESS",
|
||||||
|
"type": "restart",
|
||||||
|
"payload": "Device will restart in 2 seconds"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Note:** Device will reboot after sending the response.
|
||||||
|
|
||||||
|
### 🔄 Force OTA Update
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cmd": "system",
|
||||||
|
"contents": {
|
||||||
|
"action": "force_update",
|
||||||
|
"channel": "stable" // optional: "stable", "beta", or "emergency" (default: "stable")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "SUCCESS",
|
||||||
|
"type": "force_update",
|
||||||
|
"payload": "Starting forced OTA update from channel: stable. Device may reboot."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Error Response (if player is active):**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "ERROR",
|
||||||
|
"type": "force_update",
|
||||||
|
"payload": "Cannot update while playback is active"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Note:** If update is successful, device will reboot automatically.
|
||||||
|
|
||||||
|
### 🔥 Custom Firmware Update
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cmd": "system",
|
||||||
|
"contents": {
|
||||||
|
"action": "custom_update",
|
||||||
|
"firmware_url": "https://example.com/path/to/firmware.bin",
|
||||||
|
"checksum": "a1b2c3d4e5f6...", // optional: SHA256 checksum for verification
|
||||||
|
"file_size": 1234567, // optional: expected file size in bytes
|
||||||
|
"version": 145 // optional: firmware version number to save in NVS
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "SUCCESS",
|
||||||
|
"type": "custom_update",
|
||||||
|
"payload": "Starting custom OTA update. Device may reboot."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Error Responses:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "ERROR",
|
||||||
|
"type": "custom_update",
|
||||||
|
"payload": "Missing firmware_url parameter"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "ERROR",
|
||||||
|
"type": "custom_update",
|
||||||
|
"payload": "Cannot update while playback is active"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Features:**
|
||||||
|
- Download firmware from any URL (bypasses configured update servers)
|
||||||
|
- Optional SHA256 checksum verification
|
||||||
|
- Optional file size validation
|
||||||
|
- Optional version number to update NVS (prevents unwanted auto-downgrades)
|
||||||
|
- Automatically blocks updates during playback
|
||||||
|
- Device reboots on successful installation
|
||||||
|
|
||||||
|
**Version Parameter Behavior:**
|
||||||
|
- If `version` is provided (> 0): NVS firmware version will be updated to this value
|
||||||
|
- If `version` is omitted or 0: NVS firmware version remains unchanged
|
||||||
|
- **Important:** Without version parameter, future OTA checks may detect your custom firmware as "outdated" and trigger auto-updates/downgrades
|
||||||
|
|
||||||
|
**Note:** If update is successful, device will reboot automatically. Use with caution!
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎵 Playback Control
|
||||||
|
|
||||||
|
### ▶️ Start Playback
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cmd": "playback",
|
||||||
|
"contents": {
|
||||||
|
"action": "play",
|
||||||
|
"name": "My Melody",
|
||||||
|
"uid": "01DegzV9FA8tYbQpkIHR",
|
||||||
|
"url": "https://example.com/melody.bin",
|
||||||
|
"speed": 500,
|
||||||
|
"note_assignments": [1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||||
|
"segment_duration": 15000,
|
||||||
|
"pause_duration": 5000,
|
||||||
|
"total_duration": 60000,
|
||||||
|
"continuous_loop": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### ⏹️ Stop Playback
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cmd": "playback",
|
||||||
|
"contents": {
|
||||||
|
"action": "stop"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📁 File Management
|
||||||
|
|
||||||
|
### 📋 List Available Melodies
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cmd": "file_manager",
|
||||||
|
"contents": {
|
||||||
|
"action": "list_melodies"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Success Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "SUCCESS",
|
||||||
|
"type": "list_melodies",
|
||||||
|
"payload": ["melody1.bin", "melody2.bin", "melody3.bin"]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 📥 Download Melody
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cmd": "file_manager",
|
||||||
|
"contents": {
|
||||||
|
"action": "download_melody",
|
||||||
|
"download_url": "https://example.com/melody.bin",
|
||||||
|
"melodys_uid": "01DegzV9FA8tYbQpkIHR",
|
||||||
|
"name": "Optional Display Name"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🗑️ Delete Melody
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cmd": "file_manager",
|
||||||
|
"contents": {
|
||||||
|
"action": "delete_melody",
|
||||||
|
"name": "01DegzV9FA8tYbQpkIHR"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔧 Relay Setup
|
||||||
|
|
||||||
|
### ⏱️ Set Relay Timers (Single Bell)
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cmd": "relay_setup",
|
||||||
|
"contents": {
|
||||||
|
"action": "set_timers",
|
||||||
|
"b1": 100,
|
||||||
|
"b2": 200,
|
||||||
|
"b3": 150
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### ⏱️ Set Relay Timers (Batch Mode)
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cmd": "relay_setup",
|
||||||
|
"contents": {
|
||||||
|
"action": "set_timers",
|
||||||
|
"timers": {
|
||||||
|
"b1": 100,
|
||||||
|
"b2": 200,
|
||||||
|
"b3": 150,
|
||||||
|
"b4": 300,
|
||||||
|
"b5": 250,
|
||||||
|
"b6": 180
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🔌 Set Relay Outputs (Single Bell)
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cmd": "relay_setup",
|
||||||
|
"contents": {
|
||||||
|
"action": "set_outputs",
|
||||||
|
"b1": 1,
|
||||||
|
"b2": 2,
|
||||||
|
"b3": 3
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🔌 Set Relay Outputs (Batch Mode)
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cmd": "relay_setup",
|
||||||
|
"contents": {
|
||||||
|
"action": "set_outputs",
|
||||||
|
"outputs": {
|
||||||
|
"b1": 1,
|
||||||
|
"b2": 2,
|
||||||
|
"b3": 3,
|
||||||
|
"b4": 4,
|
||||||
|
"b5": 5,
|
||||||
|
"b6": 6
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🕐 Clock Setup
|
||||||
|
|
||||||
|
### 🔌 Set Clock Outputs
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cmd": "clock_setup",
|
||||||
|
"contents": {
|
||||||
|
"action": "set_outputs",
|
||||||
|
"c1": 1,
|
||||||
|
"c2": 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### ⏰ Set Clock Timings
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cmd": "clock_setup",
|
||||||
|
"contents": {
|
||||||
|
"action": "set_timings",
|
||||||
|
"pulseDuration": 5000,
|
||||||
|
"pauseDuration": 2000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🔔 Set Clock Alerts
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cmd": "clock_setup",
|
||||||
|
"contents": {
|
||||||
|
"action": "set_alerts",
|
||||||
|
"alertType": "HOURS",
|
||||||
|
"alertRingInterval": 1000,
|
||||||
|
"hourBell": 1,
|
||||||
|
"halfBell": 2,
|
||||||
|
"quarterBell": 3
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 💡 Set Clock Backlight
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cmd": "clock_setup",
|
||||||
|
"contents": {
|
||||||
|
"action": "set_backlight",
|
||||||
|
"enabled": true,
|
||||||
|
"output": 5,
|
||||||
|
"onTime": "18:00",
|
||||||
|
"offTime": "06:00"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🔇 Set Clock Silence Periods
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cmd": "clock_setup",
|
||||||
|
"contents": {
|
||||||
|
"action": "set_silence",
|
||||||
|
"daytime": {
|
||||||
|
"enabled": true,
|
||||||
|
"onTime": "13:00",
|
||||||
|
"offTime": "15:00"
|
||||||
|
},
|
||||||
|
"nighttime": {
|
||||||
|
"enabled": true,
|
||||||
|
"onTime": "22:00",
|
||||||
|
"offTime": "07:00"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🚀 Batch Clock Setup (Multiple Settings at Once)
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cmd": "clock_setup",
|
||||||
|
"contents": {
|
||||||
|
"action": "batch_setup",
|
||||||
|
"outputs": {
|
||||||
|
"c1": 1,
|
||||||
|
"c2": 2
|
||||||
|
},
|
||||||
|
"timings": {
|
||||||
|
"pulseDuration": 5000,
|
||||||
|
"pauseDuration": 2000
|
||||||
|
},
|
||||||
|
"alerts": {
|
||||||
|
"alertType": "HOURS",
|
||||||
|
"hourBell": 1,
|
||||||
|
"halfBell": 2
|
||||||
|
},
|
||||||
|
"backlight": {
|
||||||
|
"enabled": true,
|
||||||
|
"output": 5,
|
||||||
|
"onTime": "18:00",
|
||||||
|
"offTime": "06:00"
|
||||||
|
},
|
||||||
|
"silence": {
|
||||||
|
"daytime": {
|
||||||
|
"enabled": true,
|
||||||
|
"onTime": "13:00",
|
||||||
|
"offTime": "15:00"
|
||||||
|
},
|
||||||
|
"nighttime": {
|
||||||
|
"enabled": true,
|
||||||
|
"onTime": "22:00",
|
||||||
|
"offTime": "07:00"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Success Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "SUCCESS",
|
||||||
|
"type": "clock_setup",
|
||||||
|
"payload": "Batch clock setup updated: 5 sections"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📢 Information Messages
|
||||||
|
|
||||||
|
> **Automatic status broadcasts sent to ALL clients**
|
||||||
|
> These messages are initiated by the ESP32 system and broadcast to all connected clients without being requested.
|
||||||
|
|
||||||
|
### 🎵 Playback Status Updates
|
||||||
|
|
||||||
|
**Sent automatically during playback state changes:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "INFO",
|
||||||
|
"type": "playback",
|
||||||
|
"payload": {
|
||||||
|
"action": "playing",
|
||||||
|
"time_elapsed": 125,
|
||||||
|
"projected_run_time": 5158
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### ⚠️ Bell Overload Warnings
|
||||||
|
|
||||||
|
**Sent automatically when bell load monitoring detects issues:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "INFO",
|
||||||
|
"type": "bell_overload",
|
||||||
|
"payload": {
|
||||||
|
"bells": [1, 3, 5],
|
||||||
|
"loads": [85, 92, 78],
|
||||||
|
"severity": "warning"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🌐 Network & Discovery
|
||||||
|
|
||||||
|
### 🔍 UDP Discovery
|
||||||
|
|
||||||
|
**UDP Broadcast Request:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"op": "discover",
|
||||||
|
"svc": "vesper"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**UDP Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"op": "discover_reply",
|
||||||
|
"svc": "vesper",
|
||||||
|
"ver": 1,
|
||||||
|
"name": "Proj. Vesper v0.5",
|
||||||
|
"id": "ESP32_ABC123",
|
||||||
|
"ip": "192.168.1.100",
|
||||||
|
"ws": "ws://192.168.1.100/ws",
|
||||||
|
"port": 80,
|
||||||
|
"fw": "1.2.3",
|
||||||
|
"clients": 2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔄 Legacy Command Support
|
||||||
|
|
||||||
|
**For backward compatibility, the following legacy commands are still supported:**
|
||||||
|
|
||||||
|
### Individual Commands (Legacy)
|
||||||
|
- `cmd: "ping"` → Use `system` with `action: "ping"`
|
||||||
|
- `cmd: "report_status"` → Use `system` with `action: "status"`
|
||||||
|
- `cmd: "identify"` → Use `system` with `action: "identify"`
|
||||||
|
- `cmd: "list_melodies"` → Use `file_manager` with `action: "list_melodies"`
|
||||||
|
- `cmd: "download_melody"` → Use `file_manager` with `action: "download_melody"`
|
||||||
|
- `cmd: "delete_melody"` → Use `file_manager` with `action: "delete_melody"`
|
||||||
|
- `cmd: "set_relay_timers"` → Use `relay_setup` with `action: "set_timers"`
|
||||||
|
- `cmd: "set_relay_outputs"` → Use `relay_setup` with `action: "set_outputs"`
|
||||||
|
- `cmd: "set_clock_outputs"` → Use `clock_setup` with `action: "set_outputs"`
|
||||||
|
- `cmd: "set_clock_timings"` → Use `clock_setup` with `action: "set_timings"`
|
||||||
|
- `cmd: "set_clock_alerts"` → Use `clock_setup` with `action: "set_alerts"`
|
||||||
|
- `cmd: "set_clock_backlight"` → Use `clock_setup` with `action: "set_backlight"`
|
||||||
|
- `cmd: "set_clock_silence"` → Use `clock_setup` with `action: "set_silence"`
|
||||||
|
|
||||||
|
**Legacy commands will continue to work but are deprecated. Please migrate to the new grouped command structure for optimal performance and features.**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔧 Key Advantages of Grouped Commands
|
||||||
|
|
||||||
|
### 🚀 **Batch Processing**
|
||||||
|
- Send multiple settings in a single command
|
||||||
|
- Reduce network overhead and latency
|
||||||
|
- Atomic operations ensure consistency
|
||||||
|
|
||||||
|
### 📊 **Better Organization**
|
||||||
|
- Logical grouping of related commands
|
||||||
|
- Cleaner API structure
|
||||||
|
- Easier to understand and maintain
|
||||||
|
|
||||||
|
### ⚡ **Enhanced Performance**
|
||||||
|
- Fewer round-trips for complex configurations
|
||||||
|
- Optimized ESP32 processing
|
||||||
|
- Improved user experience
|
||||||
|
|
||||||
|
### 🔄 **Backward Compatibility**
|
||||||
|
- Legacy commands still supported
|
||||||
|
- Gradual migration path
|
||||||
|
- No breaking changes for existing implementations
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔧 Integration Examples
|
||||||
|
|
||||||
|
### Dart/Flutter App Integration
|
||||||
|
|
||||||
|
```dart
|
||||||
|
// New grouped command approach
|
||||||
|
await ClockSetup.batchClockSetup(
|
||||||
|
c1Output: 1,
|
||||||
|
c2Output: 2,
|
||||||
|
pulseDuration: 5000,
|
||||||
|
pauseDuration: 2000,
|
||||||
|
alertType: 'HOURS',
|
||||||
|
hourBell: 1,
|
||||||
|
backlightEnabled: true,
|
||||||
|
backlightOutput: 5,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Batch relay setup
|
||||||
|
await RelaySetup.setBatchRelayOutputs({
|
||||||
|
1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Individual settings still work
|
||||||
|
await ClockSetup.setOddClockOutput(1);
|
||||||
|
await ClockSetup.setEvenClockOutput(2);
|
||||||
|
```
|
||||||
|
|
||||||
|
### JavaScript/WebSocket Integration
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Batch clock configuration
|
||||||
|
const clockConfig = {
|
||||||
|
cmd: "clock_setup",
|
||||||
|
contents: {
|
||||||
|
action: "batch_setup",
|
||||||
|
outputs: { c1: 1, c2: 2 },
|
||||||
|
timings: { pulseDuration: 5000, pauseDuration: 2000 },
|
||||||
|
alerts: { alertType: "HOURS", hourBell: 1 },
|
||||||
|
backlight: { enabled: true, output: 5 }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
webSocket.send(JSON.stringify(clockConfig));
|
||||||
|
|
||||||
|
// Batch relay configuration
|
||||||
|
const relayConfig = {
|
||||||
|
cmd: "relay_setup",
|
||||||
|
contents: {
|
||||||
|
action: "set_outputs",
|
||||||
|
outputs: {
|
||||||
|
b1: 1, b2: 2, b3: 3, b4: 4, b5: 5, b6: 6
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
webSocket.send(JSON.stringify(relayConfig));
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚨 Error Handling
|
||||||
|
|
||||||
|
### Common Error Types
|
||||||
|
|
||||||
|
**Missing Action Parameter:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "ERROR",
|
||||||
|
"type": "relay_setup",
|
||||||
|
"payload": "Missing action parameter"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Unknown Action:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "ERROR",
|
||||||
|
"type": "clock_setup",
|
||||||
|
"payload": "Unknown action: invalid_action"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Batch Processing Errors:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "ERROR",
|
||||||
|
"type": "relay_setup",
|
||||||
|
"payload": "No valid relay timers found in batch"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Success with Count:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "SUCCESS",
|
||||||
|
"type": "relay_setup",
|
||||||
|
"payload": "Batch relay outputs updated: 6 bells"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📡 Message Routing
|
||||||
|
|
||||||
|
### Response Routing Rules
|
||||||
|
|
||||||
|
1. **Command Responses**: Sent only to the originating client/protocol
|
||||||
|
- MQTT command → MQTT response
|
||||||
|
- WebSocket client #3 → WebSocket client #3 only
|
||||||
|
|
||||||
|
2. **Status Broadcasts**: Sent to ALL connected clients
|
||||||
|
- All WebSocket clients receive the message
|
||||||
|
- MQTT subscribers receive the message
|
||||||
|
- Used for system notifications and status updates
|
||||||
|
|
||||||
|
3. **Targeted Messages**: Based on device type
|
||||||
|
- `broadcastToMasterClients()`: Only master devices
|
||||||
|
- `broadcastToSecondaryClients()`: Only secondary devices
|
||||||
|
- `broadcastToAllWebSocketClients()`: All WebSocket clients
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ⚡ Performance Optimizations
|
||||||
|
|
||||||
|
### Batch Command Benefits
|
||||||
|
|
||||||
|
**Before (Legacy - 6 separate commands):**
|
||||||
|
```javascript
|
||||||
|
// 6 separate network calls
|
||||||
|
await setRelayOutput(1, 1);
|
||||||
|
await setRelayOutput(2, 2);
|
||||||
|
await setRelayOutput(3, 3);
|
||||||
|
await setRelayOutput(4, 4);
|
||||||
|
await setRelayOutput(5, 5);
|
||||||
|
await setRelayOutput(6, 6);
|
||||||
|
```
|
||||||
|
|
||||||
|
**After (Grouped - 1 batch command):**
|
||||||
|
```javascript
|
||||||
|
// 1 network call for all settings
|
||||||
|
await setBatchRelayOutputs({
|
||||||
|
1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### Performance Metrics
|
||||||
|
- **Network Calls**: Reduced by up to 85%
|
||||||
|
- **Configuration Time**: 3-5x faster
|
||||||
|
- **ESP32 Processing**: More efficient batch updates
|
||||||
|
- **Error Handling**: Atomic operations ensure consistency
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔧 Quick Reference
|
||||||
|
|
||||||
|
### Command Groups
|
||||||
|
| Group | Purpose | Batch Support |
|
||||||
|
|-------|---------|---------------|
|
||||||
|
| `system` | Device management, ping, status | No |
|
||||||
|
| `playback` | Music playback control | No |
|
||||||
|
| `file_manager` | Melody file operations | No |
|
||||||
|
| `relay_setup` | Bell configuration | ✅ Yes |
|
||||||
|
| `clock_setup` | Clock mechanism setup | ✅ Yes |
|
||||||
|
|
||||||
|
### Actions by Group
|
||||||
|
|
||||||
|
**System:** `ping`, `status`, `identify`, `restart`, `force_update`, `custom_update`
|
||||||
|
|
||||||
|
**Playback:** `play`, `stop`
|
||||||
|
|
||||||
|
**File Manager:** `list_melodies`, `download_melody`, `delete_melody`
|
||||||
|
|
||||||
|
**Relay Setup:** `set_timers`, `set_outputs`
|
||||||
|
|
||||||
|
**Clock Setup:** `set_outputs`, `set_timings`, `set_alerts`, `set_backlight`, `set_silence`, `batch_setup`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Happy Bell Automation with Grouped Commands! 🔔*
|
||||||
@@ -0,0 +1,960 @@
|
|||||||
|
# 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-09-29 (full audit against the handlers' `commands()` lists, field parsing and error strings).
|
||||||
|
> Companion docs: [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_topic_spec_v2.md) (MQTT topics, `req_id`, LWT) and [mqtt-events.md](mqtt-events.md) (unsolicited MQTT payloads).
|
||||||
|
> The console's API Reference page (`bellsystems-cp` → `ApiReferencePage.jsx`) mirrors this file — keep both in sync.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
### Message Envelope
|
||||||
|
|
||||||
|
Every command sent to Vesper uses this JSON envelope:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"v": 2,
|
||||||
|
"cmd": "namespace.command",
|
||||||
|
"req_id": "abc123",
|
||||||
|
"contents": { ... }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Field | Type | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| `v` | int | Protocol version. `2` = current, `1` = legacy (runs through `LegacyAdapter` first — see [Legacy Compatibility](#legacy-compatibility-v1)). **If omitted, MQTT, WebSocket and UART assume `1`; HTTP assumes `2`.** A v2 command name sent as v1 still works — the adapter leaves names it doesn't recognise unchanged. |
|
||||||
|
| `cmd` | string | `namespace.command` format (e.g. `relay.set_durations`). |
|
||||||
|
| `req_id` | string | Optional. **MQTT only** — echoed back on the `control/ack` reply for correlation. WebSocket, HTTP and UART ignore it (their replies never carry `req_id`). See [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_topic_spec_v2.md#req_id-correlation). |
|
||||||
|
| `contents` | object | Command payload. May be omitted if the command takes no fields. |
|
||||||
|
|
||||||
|
### Response Envelope
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "SUCCESS" | "ERROR" | "INFO",
|
||||||
|
"type": "command_name",
|
||||||
|
"req_id": "abc123",
|
||||||
|
"message": "human-readable text",
|
||||||
|
"data": { ... }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Field | Present when | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| `status` | always | `SUCCESS` or `ERROR` for command replies. `INFO` is only used for unsolicited broadcasts (see below) — never as a reply to a command. |
|
||||||
|
| `type` | always | Normally echoes the command name. Exceptions: `ping` → `"pong"`; `playback.play`/`playback.stop` → `"playback"`; unregistered command → `"unknown"`; unparseable MQTT input → `"parse_error"`; WebSocket/HTTP input with no `cmd` → `"bad_request"`. |
|
||||||
|
| `req_id` | MQTT only, when the request sent one | Echoed unchanged. |
|
||||||
|
| `message` | text replies and **every** error | A plain string. |
|
||||||
|
| `data` | structured replies | An object (or array, for `files.list_builtin`). A reply carries `message` or `data`, never both. |
|
||||||
|
|
||||||
|
There is **no `payload` field** in v2 replies. `payload` only appears in (a) replies to *legacy v1* `system.status` requests (translated by `LegacyResponseAdapter` — see [`system.status`](#systemstatus)), and (b) unsolicited WebSocket broadcasts (`status: "INFO"`, e.g. the playback transition event), which keep the pre-v2 shape. Unsolicited MQTT events are published on their own topics with their own shapes — see [mqtt-events.md](mqtt-events.md).
|
||||||
|
|
||||||
|
**Unknown command** (any transport):
|
||||||
|
```json
|
||||||
|
{ "status": "ERROR", "type": "unknown", "message": "Unknown command: playback" }
|
||||||
|
```
|
||||||
|
|
||||||
|
### Variant availability
|
||||||
|
|
||||||
|
Handlers are only registered when their dependencies exist on the build:
|
||||||
|
|
||||||
|
| Handler | Missing on | Effect |
|
||||||
|
|---|---|---|
|
||||||
|
| `SystemHandler` (`ping`, `identify`, `system.*`) | RTC-less builds (`HAS_RTC=0`: agnus, agnus-mini) | `Unknown command` (HTTP `GET /api/ping` still works) |
|
||||||
|
| `ClockHandler` (`clock.*`) | RTC-less builds | `Unknown command` |
|
||||||
|
| `RFRemoteHandler` (`rf.*`) | builds without RF (`HAS_RF=0`: bespoke-rs485) | `Unknown command` |
|
||||||
|
| `FileHandler` (`files.*`) | builds with no FileManager | `Unknown command` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Transports
|
||||||
|
|
||||||
|
MQTT uses the v2 topic set — see [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_topic_spec_v2.md) for the full table, per-topic ON/OFF switches, `req_id` correlation, and LWT.
|
||||||
|
|
||||||
|
| Transport | Address | Direction | Notes |
|
||||||
|
|---|---|---|---|
|
||||||
|
| MQTT | `vesper/{device_id}/control/command` | Inbound commands | Read-only from the board's perspective. Replies go to `control/ack`. |
|
||||||
|
| MQTT | `vesper/{device_id}/control/ack` | Outbound replies | Strictly request/response — nothing unsolicited |
|
||||||
|
| MQTT | `vesper/{device_id}/control/reports` | Outbound, critical unsolicited events | `bell_overload`, `playback_failed` — not retained |
|
||||||
|
| MQTT | `vesper/{device_id}/status/heartbeat` | Outbound, retained, QoS 1 | Heartbeat every 30s + LWT |
|
||||||
|
| MQTT | `vesper/{device_id}/status/playback` | Outbound, retained, QoS 1 | Playback transitions |
|
||||||
|
| MQTT | `vesper/{device_id}/system/alerts` | Outbound, retained until cleared, QoS 1 | Subsystem state-change events |
|
||||||
|
| MQTT | `vesper/{device_id}/system/info` | Outbound, retained, QoS 1 | Discrete device events (boot report) |
|
||||||
|
| MQTT | `vesper/{device_id}/system/logs` | Outbound, QoS 0 | Mirrors serial log stream |
|
||||||
|
| MQTT | `vesper/{device_id}/system/metrics` | Outbound, QoS 0 | Structured telemetry every 5 min |
|
||||||
|
| WebSocket | `ws://{device_ip}/ws` | Bidirectional | Send `identify` on connect |
|
||||||
|
| HTTP | `POST http://{device_ip}/api/command` | Request/response | Body = command envelope. Also `GET /api/ping`, `GET /api/status` (= `system.status`) |
|
||||||
|
| UART | Serial2 (GPIO12 TX / GPIO13 RX, 115200) | Bidirectional | LCD/button slave board. Whitelist only (below) |
|
||||||
|
| UDP | Port 32101 | Discovery | Replies to `discover` probes |
|
||||||
|
|
||||||
|
MQTT drops incoming commands silently (no reply) while free heap is below the publish guard (`MQTTDriver::hasHeapForPublish()`), and any reply is dropped if the `command` topic switch is off.
|
||||||
|
|
||||||
|
### UART Whitelist
|
||||||
|
|
||||||
|
Only these **raw `cmd` strings** are accepted over UART; everything else is silently dropped. The check runs *before* legacy translation, so the v1 form must be used for playback:
|
||||||
|
|
||||||
|
```
|
||||||
|
ping
|
||||||
|
playback ← v1 form only: { "cmd": "playback", "contents": { "action": "play" | "stop", ... } }
|
||||||
|
clock.pause
|
||||||
|
clock.resume
|
||||||
|
system.get_time
|
||||||
|
```
|
||||||
|
|
||||||
|
`playback.play` / `playback.stop` sent over UART by their v2 names are **not** whitelisted and are dropped. UART replies never carry `req_id`.
|
||||||
|
|
||||||
|
### WebSocket — Client Identification
|
||||||
|
|
||||||
|
WebSocket clients should send `identify` immediately after connecting so targeted broadcasts reach them:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "v": 2, "cmd": "identify", "contents": { "device_type": "master" } }
|
||||||
|
```
|
||||||
|
|
||||||
|
`device_type`: `"master"` (app/console) or `"secondary"` (slave board).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Command Reference
|
||||||
|
|
||||||
|
Unless stated otherwise every error reply is `{ "status": "ERROR", "type": "<cmd>", "message": "<message>" }`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Root — `SystemHandler`
|
||||||
|
|
||||||
|
### `ping`
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Transports | All (RTC builds only) |
|
||||||
|
| Contents | `ts` (int, optional) — caller's epoch-ms; echoed back for RTT measurement |
|
||||||
|
| Returns | `{ "status": "SUCCESS", "type": "pong", "data": { "type": "pong", "ts": 1752600000123, "device_uptime_ms": 184213 } }` (`ts` only if sent) |
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "v": 2, "cmd": "ping", "contents": { "ts": 1752600000123 } }
|
||||||
|
```
|
||||||
|
|
||||||
|
### `identify`
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Transports | WebSocket only |
|
||||||
|
| Contents | `device_type` (string, required) — `"master"` or `"secondary"` |
|
||||||
|
| Returns | `{ "status": "SUCCESS", "type": "identify", "message": "Device identified as master" }` |
|
||||||
|
|
||||||
|
| Error | Condition |
|
||||||
|
|---|---|
|
||||||
|
| `identify is only available via WebSocket` | Sent over MQTT/HTTP/UART |
|
||||||
|
| `Missing required field: device_type` | `device_type` absent / not a string |
|
||||||
|
| `Invalid device_type. Use 'master' or 'secondary'` | Any other value |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Playback — `PlaybackHandler`
|
||||||
|
|
||||||
|
The registered commands are **`playback.play`** and **`playback.stop`**. There is no v2 `cmd: "playback"` with an `action` field — see [Bare `playback` command](#bare-playback-command) below.
|
||||||
|
|
||||||
|
Both commands reply with **`type: "playback"`** (not the command name).
|
||||||
|
|
||||||
|
### `playback.play`
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Transports | MQTT, WebSocket, HTTP (UART: v1 form only) |
|
||||||
|
| Returns | `{ "status": "SUCCESS", "type": "playback", "message": "Playback started" }` — or `"message": "Melody download started — playback begins when it completes"` when the melody must be downloaded first |
|
||||||
|
|
||||||
|
The SUCCESS reply means the board **accepted** the command, not that bells are ringing. `status/playback` (MQTT) is the source of truth for what the board is actually doing — `loading` / `playing` / `paused` / `stopping` / `idle`; see [mqtt-events.md → States](mqtt-events.md#states).
|
||||||
|
|
||||||
|
**Fields are sticky.** Every field except `url`, `mode` and `continuous_loop` keeps the value from the *previous* `playback.play` (or its boot default) when omitted — including `pid`, `speed` and the tail of `note_assignments`. Send every field you care about on every play. A rejected play never changes the stored values (all checks run first).
|
||||||
|
|
||||||
|
| Field | Type | Required | Notes |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `pid` | string | yes* | Melody ID. Looked up in the built-in library, then `/melodies/{pid}` on SD, then downloaded from `url`. *If omitted, the previous `pid` is reused; the command fails if that is empty. |
|
||||||
|
| `uid` | string | no | Alias for `pid`, read only when `pid` is absent. |
|
||||||
|
| `name` | string | no | Display name. Informational only. |
|
||||||
|
| `url` | string | no | Download URL, used only when the melody is not built-in and not on SD. **The field is `url` — `download_url` is not read by `playback.play`** (that name belongs to `files.download`). Not sticky: omitted = no download possible for this play. |
|
||||||
|
| `speed` | int | no | ms per beat, 0–65535. Boot default 500. `0` is coerced to 300. |
|
||||||
|
| `note_assignments` | int[] | no | Up to 16 integers, each 0–16. Index = melody note (0-based), value = **1-based bell channel** to ring for that note, `0` = silent. Boot default `[1,2,…,16]`. A shorter array leaves the remaining entries at their previous values. |
|
||||||
|
| `mode` | string | no | `"single"` \| `"timed"` \| `"interval"` \| `"infinite"` — anything else is rejected. Selects the timing model — see below. |
|
||||||
|
| `duration` | int | no | ms, ≥ 0. **Read only when `mode` is present**; must be > 0 for `timed`/`interval`. |
|
||||||
|
| `pause_duration` | int | no | ms between segments. Read when `mode` is `"interval"`, or when `mode` is absent. |
|
||||||
|
| `total_duration` | int | no | ms. Read when `mode` is `"interval"`, or (with `continuous_loop: true`) when `mode` is absent. |
|
||||||
|
| `segment_duration` | int | no | ms. Legacy — read only when `mode` is absent. |
|
||||||
|
| `continuous_loop` | bool | no | Legacy — read only when `mode` is absent. Defaults to `false` on every command (not sticky). |
|
||||||
|
|
||||||
|
**How `mode` and `duration` interact** (`mode` present — `segment_duration` and `continuous_loop` are ignored):
|
||||||
|
|
||||||
|
| `mode` | Behaviour | Fields read |
|
||||||
|
|---|---|---|
|
||||||
|
| `"single"` | Play the melody once, then stop. | — (`duration` ignored) |
|
||||||
|
| `"timed"` | Loop the melody; when `duration` ms have elapsed, finish the current loop and stop (status goes `stopping` → `idle`). | `duration` (> 0) |
|
||||||
|
| `"interval"` | Play for `duration` ms, pause `pause_duration` ms, repeat; stop after `total_duration` ms overall (`0` = forever). | `duration` (> 0), `pause_duration`, `total_duration` |
|
||||||
|
| `"infinite"` | Loop until `playback.stop`. | — |
|
||||||
|
|
||||||
|
**Legacy timing** (`mode` absent):
|
||||||
|
|
||||||
|
| `continuous_loop` | Behaviour |
|
||||||
|
|---|---|
|
||||||
|
| `false` / absent | Run for `segment_duration` ms (sticky, boot default 15000), finish the loop, stop. **`total_duration` is ignored** — it is overwritten with `segment_duration`. `segment_duration: 0` plays the melody once. |
|
||||||
|
| `true` | Segments of `segment_duration` ms separated by `pause_duration` ms. Stops after `total_duration` ms if given in this command, else after `segment_duration` if that was given, else the previous `total_duration`. Total `0` = forever. |
|
||||||
|
|
||||||
|
Errors are checked in this order; the first that applies is returned. Every one leaves the player (and its stored fields) untouched.
|
||||||
|
|
||||||
|
| Error `message` | Condition |
|
||||||
|
|---|---|
|
||||||
|
| `Playback already active — send playback.stop first` | Player is not idle (`loading` / `playing` / `paused` / `stopping`) |
|
||||||
|
| `Playback blocked: a cancelled melody download is still finishing — try again shortly` | A download was cancelled by `playback.stop` and its transfer hasn't ended yet |
|
||||||
|
| `Missing required field: pid` | No `pid`/`uid` in this command and none stored from a previous play; or it is empty, `"-"`, or not a string |
|
||||||
|
| `Invalid speed: must be an integer from 0 to 65535 (ms per beat)` | `speed` present but not an integer in range |
|
||||||
|
| `Invalid note_assignments: must be an array of up to 16 integers, each 0-16` | Not an array, more than 16 entries, or an entry outside 0–16 |
|
||||||
|
| `Invalid duration: must be a non-negative integer (ms)` | `duration` negative / non-integer / > 4294967295 |
|
||||||
|
| `Invalid segment_duration: must be a non-negative integer (ms)` | same, for `segment_duration` |
|
||||||
|
| `Invalid pause_duration: must be a non-negative integer (ms)` | same, for `pause_duration` |
|
||||||
|
| `Invalid total_duration: must be a non-negative integer (ms)` | same, for `total_duration` |
|
||||||
|
| `Invalid mode: must be single, timed, interval or infinite` | Unrecognised `mode` |
|
||||||
|
| `Invalid duration: mode timed and interval require duration > 0` | `mode` is `timed`/`interval` and `duration` is missing or 0 |
|
||||||
|
| `Playback blocked: bell mechanism is disabled (bells.enable)` | Bells master switch off (`bells.disable`) |
|
||||||
|
| `Playback blocked: bell overload protection active — wait for the bells to cool` | Load guard enabled and any bell is over its max load (the guard would force-stop immediately) |
|
||||||
|
| `Melody failed to load: file is empty or corrupt` | `/melodies/{pid}` exists on SD but is empty or has an odd byte count |
|
||||||
|
| `Melody not found: not built-in, not on SD card, and no url given` | Needs a download but no `url` was sent |
|
||||||
|
| `Melody not found locally and this device has no SD card to download it to` | Needs a download but the build has no SD card / FileManager (agnus) |
|
||||||
|
|
||||||
|
**Download path.** When the melody must be downloaded, the ACK is SUCCESS `Melody download started — playback begins when it completes`, and `status/playback` shows **`loading`** (with `pid` set) — published just before the ACK. The download runs after the reply (it would otherwise block the network task for seconds), so its failure can't be an ACK error. Instead:
|
||||||
|
|
||||||
|
- success → `status/playback` goes `loading` → `playing`;
|
||||||
|
- failure → `status/playback` goes `loading` → `idle` **and** a [`playback_failed`](mqtt-events.md#playback-failed-event) event `{ "pid", "reason" }` is published on `control/reports` (reason: `Melody download failed`, `Melody failed to load: file is empty or corrupt`, or one of the two `Playback blocked: …` messages if conditions changed during the download);
|
||||||
|
- `playback.stop` while `loading` → cancelled, `idle`, no `playback_failed`.
|
||||||
|
|
||||||
|
The ACK itself is always sent synchronously from the command's own dispatch, so `req_id` is echoed on it in both the local and the download case. `playback_failed` (like every `control/reports` event) carries no `req_id` — match it by `pid`.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "v": 2, "req_id": "a1", "cmd": "playback.play", "contents": { "pid": "westminster", "speed": 400, "mode": "single" } }
|
||||||
|
{ "v": 2, "cmd": "playback.play", "contents": { "pid": "ABC123", "url": "https://example.com/ABC123.bin", "mode": "timed", "duration": 120000 } }
|
||||||
|
{ "v": 2, "cmd": "playback.play", "contents": { "pid": "ABC123", "mode": "interval", "duration": 15000, "pause_duration": 5000, "total_duration": 180000 } }
|
||||||
|
{ "v": 2, "cmd": "playback.play", "contents": { "pid": "ABC123", "segment_duration": 15000, "pause_duration": 5000, "continuous_loop": true } }
|
||||||
|
```
|
||||||
|
|
||||||
|
### `playback.stop`
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Transports | MQTT, WebSocket, HTTP (UART: v1 form only) |
|
||||||
|
| Contents | *(none)* |
|
||||||
|
| Returns | `{ "status": "SUCCESS", "type": "playback", "message": "Playback stopped" }` |
|
||||||
|
|
||||||
|
Stops immediately (bells are cut mid-loop, status goes straight to `idle`).
|
||||||
|
|
||||||
|
**While `loading` → SUCCESS**, `"message": "Download cancelled — playback will not start"` (status goes `loading` → `idle`; the transfer finishes in the background and is discarded).
|
||||||
|
|
||||||
|
**Already idle → SUCCESS**, `"message": "Already stopped"` (no status/playback publish, since nothing changed). Stop is idempotent: the caller's goal state is reached, so it is not an error — the distinct message lets a client tell the two cases apart if it cares. `playback.stop` has no error replies.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "v": 2, "cmd": "playback.stop" }
|
||||||
|
```
|
||||||
|
|
||||||
|
### Bare `playback` command
|
||||||
|
|
||||||
|
| Request | Result |
|
||||||
|
|---|---|
|
||||||
|
| `{ "cmd": "playback", "contents": { "action": "play", ... } }` with `v` omitted or `1` | Works — `LegacyAdapter` maps it to `playback.play` (strips `action`) |
|
||||||
|
| same with `"action": "stop"` | Works — mapped to `playback.stop` |
|
||||||
|
| `"action": "pause"` / `"unpause"` / anything else | `Unknown command: playback` |
|
||||||
|
| `{ "v": 2, "cmd": "playback", ... }` | `Unknown command: playback` |
|
||||||
|
| over HTTP without `v` | `Unknown command: playback` (HTTP defaults to v2) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Relay Namespace — `RelayHandler`
|
||||||
|
|
||||||
|
Bell channels are **0-based** (`"0"`..`"15"`). Relay output numbers in config are **1-based** (1 = first relay, 0 = disabled) — except `relay.test_output`, which takes a raw 0-based chip pin.
|
||||||
|
|
||||||
|
### `relay.set_durations`
|
||||||
|
|
||||||
|
Set strike duration (ms) for one or more bell channels. Partial updates accepted.
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `bells` (object) — `{ "0": 95, "2": 110 }`. v1 flat form (`{ "b1": 95 }` at the top level) also accepted. |
|
||||||
|
| Returns | `message: "Bell durations updated and saved"` |
|
||||||
|
|
||||||
|
| Error | Condition |
|
||||||
|
|---|---|
|
||||||
|
| `Missing or invalid 'bells' object` | `contents` is empty/absent |
|
||||||
|
| `Durations updated but failed to save to SD` | Applied in RAM, SD write failed |
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "v": 2, "cmd": "relay.set_durations", "contents": { "bells": { "0": 95, "1": 100, "2": 110 } } }
|
||||||
|
```
|
||||||
|
|
||||||
|
### `relay.set_outputs`
|
||||||
|
|
||||||
|
Map bell channels to relay outputs (1-based, 0 = disabled). Partial updates accepted. Same shape and errors as `relay.set_durations` (`Outputs updated but failed to save to SD`). Returns `message: "Bell outputs updated and saved"`.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "v": 2, "cmd": "relay.set_outputs", "contents": { "bells": { "0": 1, "1": 2, "2": 3 } } }
|
||||||
|
```
|
||||||
|
|
||||||
|
### `relay.set_config`
|
||||||
|
|
||||||
|
Durations and/or outputs in one command.
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `durations` (object, optional), `outputs` (object, optional) — at least one |
|
||||||
|
| Returns | `message: "Bell configuration updated and saved"` |
|
||||||
|
|
||||||
|
| Error | Condition |
|
||||||
|
|---|---|
|
||||||
|
| `Provide 'durations' and/or 'outputs' objects` | Neither present |
|
||||||
|
| `Durations applied but failed to save to SD` | SD write failed |
|
||||||
|
| `Outputs applied but failed to save to SD` | SD write failed |
|
||||||
|
|
||||||
|
### `relay.get_config`
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Returns | `data: { "durations": { "0": 95, ... }, "outputs": { "0": 1, ... } }` |
|
||||||
|
|
||||||
|
### `relay.test_output`
|
||||||
|
|
||||||
|
Fire a raw chip output for a caller-specified duration.
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `output` (int, required, **0-based chip pin 0–31**), `duration_ms` (int, required, 1–5000) |
|
||||||
|
| Returns | `message: "Output 2 fired for 95 ms"` |
|
||||||
|
|
||||||
|
| Error | Condition |
|
||||||
|
|---|---|
|
||||||
|
| `Missing required field: output` | |
|
||||||
|
| `Missing required field: duration_ms` | |
|
||||||
|
| `Player must be stopped before testing outputs` | Player not idle |
|
||||||
|
| `output must be 0-31` | |
|
||||||
|
| `duration_ms must be 1-5000` | |
|
||||||
|
|
||||||
|
### `relay.test_bell`
|
||||||
|
|
||||||
|
Fire bell channel N on its configured output for its configured duration. Bypasses `bells.disable`.
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `bell` (int, required, 0–15) |
|
||||||
|
| Returns | `data: { "bell": 0, "output": 1, "duration_ms": 95 }` (`output` 1-based) |
|
||||||
|
|
||||||
|
| Error | Condition |
|
||||||
|
|---|---|
|
||||||
|
| `Missing required field: bell (0-based bell index)` | |
|
||||||
|
| `bell must be 0-15` | |
|
||||||
|
| `Bell <n> is disabled or unconfigured` | Bell has no output assigned |
|
||||||
|
|
||||||
|
### `relay.test_batch`
|
||||||
|
|
||||||
|
Fire several bell channels at once. Bypasses `bells.disable`.
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `bells` (int[], required) — 0-based channels; out-of-range, non-integer and unconfigured entries are skipped |
|
||||||
|
| Returns | `data: { "fired": 3 }` |
|
||||||
|
|
||||||
|
| Error | Condition |
|
||||||
|
|---|---|
|
||||||
|
| `Missing required field: bells (array of 0-based bell indices)` | |
|
||||||
|
| `bells array must not be empty` | |
|
||||||
|
| `No valid bell indices in array` | Nothing was fired |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Clock Namespace — `ClockHandler` (RTC builds only)
|
||||||
|
|
||||||
|
Every `set_*` below except `set_time`/`set_face`/`set_timezone` can also fail with `Updated but failed to save to SD` (or the command-specific save message listed).
|
||||||
|
|
||||||
|
### `clock.set_outputs`
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `c1` (int), `c2` (int), `pulseDuration` (int), `pauseDuration` (int) — all optional; unknown/missing fields are silently ignored (no "nothing to do" error) |
|
||||||
|
| Returns | `message: "Clock outputs updated and saved"` |
|
||||||
|
|
||||||
|
### `clock.set_timings`
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `pulse_duration` (int), `pause_duration` (int) — at least one |
|
||||||
|
| Returns | `message: "Clock timings updated and saved"` |
|
||||||
|
| Error | `No timing fields provided (pulse_duration, pause_duration)` |
|
||||||
|
|
||||||
|
### `clock.set_alerts`
|
||||||
|
|
||||||
|
**Field names are camelCase** (they go straight to `ConfigManager::updateClockAlerts()`); snake_case names are silently ignored. Use `clock.set_alerts_config` for the snake_case form.
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `alertType` (`"OFF"`/`"SINGLE"`/`"HOURS"`), `alertRingInterval` (int), `hourBell`, `halfBell`, `quarterBell` (int, **1-based** bell, 255 = disabled) — all optional |
|
||||||
|
| Returns | `message: "Clock alerts updated and saved"` |
|
||||||
|
|
||||||
|
### `clock.set_backlight`
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `backlight` (bool), `backlight_output` (int), `backlight_on` / `backlight_off` (`"HH:MM"`) — all optional |
|
||||||
|
| Returns | `message: "Clock backlight updated and saved"` |
|
||||||
|
|
||||||
|
### `clock.set_silence`
|
||||||
|
|
||||||
|
**Nested shape** — flat snake_case fields are silently ignored (use `clock.set_alerts_config` for those):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "v": 2, "cmd": "clock.set_silence", "contents": {
|
||||||
|
"daytime": { "enabled": false, "onTime": "12:00", "offTime": "14:00" },
|
||||||
|
"nighttime": { "enabled": true, "onTime": "22:00", "offTime": "07:00" } } }
|
||||||
|
```
|
||||||
|
|
||||||
|
Returns `message: "Clock silence periods updated and saved"`.
|
||||||
|
|
||||||
|
### `clock.set_config`
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `enabled` (bool), `c1`, `c2` (int, 1-based output, 0 = disabled), `pulse_duration`, `pause_duration` (int) — at least one |
|
||||||
|
| Returns | `message: "Clock configuration updated and saved"` |
|
||||||
|
|
||||||
|
| Error | Condition |
|
||||||
|
|---|---|
|
||||||
|
| `Provide at least one field: enabled, c1, c2, pulse_duration, pause_duration` | |
|
||||||
|
| `Settings applied but failed to save to SD` | |
|
||||||
|
|
||||||
|
### `clock.set_alerts_config`
|
||||||
|
|
||||||
|
Snake_case alerts + silence in one command.
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `alert_type`, `alert_interval`, `hour_bell`, `half_bell`, `quarter_bell`, `daytime_silence`, `daytime_on`, `daytime_off`, `night_silence`, `night_on`, `night_off` — at least one |
|
||||||
|
| Returns | `message: "Clock alerts and silence configuration updated and saved"` |
|
||||||
|
|
||||||
|
| Error | Condition |
|
||||||
|
|---|---|
|
||||||
|
| `Provide at least one of: alert_type, alert_interval, hour_bell, half_bell, quarter_bell, daytime_silence, daytime_on, daytime_off, night_silence, night_on, night_off` | |
|
||||||
|
| `Settings applied but failed to save to SD` | |
|
||||||
|
|
||||||
|
### `clock.set_time`
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `timestamp` (int, required, Unix epoch UTC), `timezone_offset` + `dst_offset` (int, seconds) |
|
||||||
|
| Returns | `message: "RTC time updated successfully"` |
|
||||||
|
|
||||||
|
`timezone_offset` (total UTC offset incl. DST) and `dst_offset` are **only applied when both are present** — they also update the stored timezone. With only one (or neither), `timestamp` is written to the RTC as-is.
|
||||||
|
|
||||||
|
| Error | Condition |
|
||||||
|
|---|---|
|
||||||
|
| `Missing required field: timestamp` | |
|
||||||
|
| `Invalid timestamp value` | `timestamp` is 0 |
|
||||||
|
| `RTC time set but verification failed` | RTC read-back returned 0 |
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "v": 2, "cmd": "clock.set_time", "contents": { "timestamp": 1740000000, "timezone_offset": 10800, "dst_offset": 3600 } }
|
||||||
|
```
|
||||||
|
|
||||||
|
### `clock.set_face`
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `hour` (0–23), `minute` (0–59) — both required |
|
||||||
|
| Returns | `message: "Physical clock face updated and saved"` |
|
||||||
|
|
||||||
|
Errors: `Missing required fields: hour, minute`, `hour must be 0-23`, `minute must be 0-59`, `Face set but failed to save to SD`.
|
||||||
|
|
||||||
|
### `clock.set_timezone`
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `gmt_offset_sec` (int, required), `dst_offset_sec` (int, optional, default 0) |
|
||||||
|
| Returns | `message: "Timezone updated and saved"` |
|
||||||
|
|
||||||
|
Errors: `Missing required field: gmt_offset_sec`, `Timezone updated but failed to save to SD`.
|
||||||
|
|
||||||
|
### `clock.get_timezone`
|
||||||
|
|
||||||
|
Returns `data: { "gmt_offset_sec": 7200, "dst_offset_sec": 3600, "ntp_server": "pool.ntp.org" }`.
|
||||||
|
|
||||||
|
### `clock.sync_ntp`
|
||||||
|
|
||||||
|
Runs an NTP sync (blocking up to ~5 s). Returns `message: "NTP sync initiated"` regardless of outcome.
|
||||||
|
|
||||||
|
### `clock.enable` / `clock.disable`
|
||||||
|
|
||||||
|
Returns `message: "Clock enabled and saved"` / `"Clock disabled and saved"`. Errors: `Enabled but failed to save to SD` / `Disabled but failed to save to SD`.
|
||||||
|
|
||||||
|
### `clock.pause` / `clock.resume`
|
||||||
|
|
||||||
|
Returns `message: "Clock updates paused"` / `"Clock updates resumed"`.
|
||||||
|
|
||||||
|
### `clock.get_face`
|
||||||
|
|
||||||
|
Returns `data: { "clock_hour", "clock_minute", "last_sync_time", "next_output_is_c1" }`.
|
||||||
|
|
||||||
|
### `clock.get_config`
|
||||||
|
|
||||||
|
Returns `data: { "enabled", "c1output", "c2output", "pulse_duration", "pause_duration", "physical_hour", "physical_minute", "next_is_c1", "last_sync_time", "alert_type", "alert_interval", "hour_bell", "half_bell", "quarter_bell", "backlight", "backlight_output", "backlight_on", "backlight_off", "daytime_silence", "daytime_on", "daytime_off", "night_silence", "night_on", "night_off", "gmt_offset_sec", "dst_offset_sec", "ntp_server" }` (bells 1-based, 255 = disabled).
|
||||||
|
|
||||||
|
### `clock.test_c1` / `clock.test_c2`
|
||||||
|
|
||||||
|
Fire C1/C2 for the configured pulse. Returns `data: { "output": "C1", "duration_ms": 100 }`. Error: `OutputManager not available`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## System Namespace — `SystemHandler` (RTC builds only)
|
||||||
|
|
||||||
|
### `system.status`
|
||||||
|
|
||||||
|
Returns `data: { "player_status": "PLAYING"|"PAUSED"|"STOPPING"|"LOADING"|"STOPPED", "time_elapsed_ms", "projected_run_time", "strike_counters": { "0": 1234, ... } }`.
|
||||||
|
|
||||||
|
A **v1** request (no `v`, or `v:1`) gets the reply translated by `LegacyResponseAdapter`: `type: "current_status"`, fields under `payload` (not `data`), lowercase `player_status` (`playing`/`paused`/`stopping`/`idle` — `LOADING` is reported as `idle`), `time_elapsed` (ms), `strike_counters` as an array.
|
||||||
|
|
||||||
|
### `system.get_time`
|
||||||
|
|
||||||
|
Returns `data: { "local_timestamp", "utc_timestamp", "rtc_available", "year", "month", "day", "hour", "minute", "second" }`.
|
||||||
|
|
||||||
|
### `system.get_config` (alias `system.get_settings`)
|
||||||
|
|
||||||
|
Full ConfigManager dump plus `general: { bells_enabled, mqtt_enabled, ota_channel, serial_log, sd_log, mqtt_log }`. Error: `Failed to serialize settings`.
|
||||||
|
|
||||||
|
### `system.get_all`
|
||||||
|
|
||||||
|
Returns `data: { "device": { serial, hw_family, hw_revision, fw_version, uptime_ms, free_heap }, "config": {...}, "telemetry": {...}, "player": { "status": "PLAYING"|"PAUSED"|"STOPPING"|"LOADING"|"STOPPED" } }`.
|
||||||
|
|
||||||
|
### `system.get_telemetry`
|
||||||
|
|
||||||
|
Returns `data: { strikes, loads, max_loads, cooling_active, guard_enabled, lifetime_runtime_seconds, session_runtime_seconds, total_playbacks, lifetime_boot_count, uptime_ms, free_heap }`.
|
||||||
|
|
||||||
|
### `system.get_device_info`
|
||||||
|
|
||||||
|
Returns `data: { "uid", "hw_type", "hw_version", "fw_version", "uptime_ms", "free_heap", "min_free_heap" }`.
|
||||||
|
|
||||||
|
### `system.health`
|
||||||
|
|
||||||
|
Returns `data: { "critical_count", "warning_count", "firmware_stable", "subsystems": [ { "name", "status": "HEALTHY"|"WARNING"|"CRITICAL"|"FAILED", "error"? } ] }`.
|
||||||
|
|
||||||
|
### `system.factory_reset`
|
||||||
|
|
||||||
|
> **Warning:** Non-reversible. All saved configuration is wiped. Restart to apply.
|
||||||
|
|
||||||
|
Returns `message: "Factory reset complete. Restart device to apply."`. Error: `Factory reset partially applied — some settings may not have saved`.
|
||||||
|
|
||||||
|
### `system.restart`
|
||||||
|
|
||||||
|
Returns `message: "Device will restart in 2 seconds"`, then reboots.
|
||||||
|
|
||||||
|
### `system.set_identity`
|
||||||
|
|
||||||
|
Overwrite the device's factory-set identity (`serial`, `hw_family`, `hw_revision`) in NVS and reboot to apply it. Sysadmin use only, via the backend console, which must update its own device record (including re-deriving the MQTT password from the new serial) in the same operation.
|
||||||
|
|
||||||
|
> **Warning:** A serial mismatch with the backend record breaks MQTT auth; a wrong `hw_family`/`hw_revision` can pull the wrong OTA build. Restarts 2 s after a successful reply.
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Transports | MQTT only |
|
||||||
|
| Contents | `serial`, `hw_family`, `hw_revision` (all required strings) |
|
||||||
|
| Returns | `message: "Device identity updated. Restarting in 2 seconds to apply."` |
|
||||||
|
|
||||||
|
| Error | Condition |
|
||||||
|
|---|---|
|
||||||
|
| `system.set_identity is only available via MQTT` | Sent over WebSocket, HTTP, or UART |
|
||||||
|
| `Missing required fields: serial, hw_family, hw_revision (all required)` | Any field absent or not a string |
|
||||||
|
| `serial, hw_family and hw_revision must be non-empty` | Any field empty |
|
||||||
|
| `Failed to persist new identity to NVS — device identity unchanged` | NVS write failed |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Firmware Namespace — `FirmwareHandler`
|
||||||
|
|
||||||
|
### `firmware.status`
|
||||||
|
|
||||||
|
Returns `data: { "validation_state", "current_version", "is_testing", "is_valid", "boot_count", "build_date", "ota_channel", "startup_retry_count", "max_startup_retries", "runtime_failure_count", "max_runtime_failures", "backup_version", "backup_is_valid", "can_commit", "can_rollback", "runtime_timeout_ms"? }` (`runtime_timeout_ms` only while testing).
|
||||||
|
|
||||||
|
### `firmware.commit`
|
||||||
|
|
||||||
|
Returns `message: "Firmware committed successfully"`. Errors: `No firmware validation in progress`, `Failed to commit firmware`.
|
||||||
|
|
||||||
|
### `firmware.rollback`
|
||||||
|
|
||||||
|
> **Warning:** Device reboots.
|
||||||
|
|
||||||
|
Returns `message: "Firmware rollback initiated — device will reboot"`. Error: `Failed to initiate firmware rollback`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## OTA Namespace — `FirmwareHandler`
|
||||||
|
|
||||||
|
There are no `ota.status` / `ota.check` commands — OTA state is in `firmware.status`, `telemetry.get_diagnostics` and `system/metrics`.
|
||||||
|
|
||||||
|
### `ota.update`
|
||||||
|
|
||||||
|
> **Warning:** Device reboots after flashing.
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `channel` (string, optional) — **defaults to `"stable"` when omitted** (not the channel saved with `ota.set_channel`) |
|
||||||
|
| Returns | `message: "OTA update started from channel: stable"` |
|
||||||
|
| Error | `Cannot update while playback is active` (only checked while `PLAYING`) |
|
||||||
|
|
||||||
|
### `ota.custom`
|
||||||
|
|
||||||
|
> **Warning:** Device reboots after flashing.
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `firmware_url` (string, required), `checksum` (string), `file_size` (int), `version` (string) |
|
||||||
|
| Returns | `message: "Custom OTA update started"` |
|
||||||
|
|
||||||
|
Errors: `Missing required field: firmware_url`, `Cannot update while playback is active`.
|
||||||
|
|
||||||
|
### `ota.set_channel`
|
||||||
|
|
||||||
|
Persists the OTA channel used by the scheduled update check.
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `channel` (string, required) — `stable` / `beta` / `development` |
|
||||||
|
| Returns | `data: { "channel": "beta" }` |
|
||||||
|
|
||||||
|
Errors: `Missing required field: channel`, `Invalid channel. Valid values: stable, beta, development`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Network Namespace — `NetworkHandler`
|
||||||
|
|
||||||
|
### `network.info`
|
||||||
|
|
||||||
|
Returns `data: { "ip", "subnet", "gateway", "dns", "mac", "hostname", "ssid", "connection_type": "WIFI"|"ETHERNET"|"AP" }`.
|
||||||
|
|
||||||
|
### `network.status`
|
||||||
|
|
||||||
|
Returns `data: { "connected", "ap_mode", "rssi", "uptime_ms", "state" }`.
|
||||||
|
|
||||||
|
### `network.set_config`
|
||||||
|
|
||||||
|
Partial update; restart required to apply.
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `hostname` (string), `useStaticIP` (bool), `ip`, `gateway`, `subnet`, `dns1`, `dns2` (strings), `permanent_ap_mode` (bool) |
|
||||||
|
| Returns | `message: "Network configuration saved. Restart device to apply changes."` — or, when `permanent_ap_mode` is sent (all other fields are then ignored), `"AP mode saved. Restart to apply."` / `"Station mode saved. Restart to apply."` |
|
||||||
|
|
||||||
|
| Error | Condition |
|
||||||
|
|---|---|
|
||||||
|
| `No network parameters provided` | None of `hostname`, `useStaticIP`, `permanent_ap_mode` present |
|
||||||
|
| `Hostname must be 1-32 characters` | |
|
||||||
|
| `Static IP requires: ip, gateway, subnet` | `useStaticIP: true` without all three |
|
||||||
|
| `Invalid IP address format` / `Invalid gateway format` / `Invalid subnet format` | |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Files Namespace — `FileHandler`
|
||||||
|
|
||||||
|
### `files.list`
|
||||||
|
|
||||||
|
Returns `data: { "files": [ ... ] }` — melody files in `/melodies` on SD. Error: `Failed to read melody list`.
|
||||||
|
|
||||||
|
### `files.list_builtin`
|
||||||
|
|
||||||
|
Returns `data: [ { "name": "...", "pid": "..." }, ... ]` (an array). Error: `Failed to read built-in melody list`.
|
||||||
|
|
||||||
|
### `files.download`
|
||||||
|
|
||||||
|
Download a melody to `/melodies/{melodys_uid}` on SD. Built-in melodies are skipped (reported as success).
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `download_url` (string, required), `melodys_uid` (string, required) |
|
||||||
|
| Returns | `message: "Melody downloaded: <uid>"` |
|
||||||
|
| Error | `Failed to download melody: <uid>` — either field missing, HTTP/SD failure |
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "v": 2, "cmd": "files.download", "contents": { "melodys_uid": "ABC123", "download_url": "https://example.com/ABC123.bin" } }
|
||||||
|
```
|
||||||
|
|
||||||
|
### `files.delete`
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `name` (string, required) |
|
||||||
|
| Returns | `message: "Melody deleted: <name>"` |
|
||||||
|
|
||||||
|
Errors: `Missing required field: name`, `Failed to delete melody: <name>`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Log Namespace — `LoggingHandler`
|
||||||
|
|
||||||
|
Level 0 = none, 1 = error, 2 = warning, 3 = info, 4 = debug, 5 = verbose.
|
||||||
|
|
||||||
|
### `log.set_serial` / `log.set_sd` / `log.set_mqtt`
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `level` (int 0–5, required) |
|
||||||
|
| Returns | `message: "serial log level set to 3 and saved"` (channel name varies) |
|
||||||
|
|
||||||
|
Errors: `Missing or invalid 'level' (0-5 required)`, `Invalid log level (must be 0-5)`, `Level applied but failed to save to SD`.
|
||||||
|
|
||||||
|
### `log.get_config`
|
||||||
|
|
||||||
|
Returns `data: { "serial_level", "sd_level", "mqtt_level" }`.
|
||||||
|
|
||||||
|
### `logs.list`
|
||||||
|
|
||||||
|
Day-rotated SD log files. Returns `data: { "files": [ { "name": "2026-07-14.log", "size": 1234 } ] }`.
|
||||||
|
Errors: `SD card not available on this device`, `Failed to read log directory`.
|
||||||
|
|
||||||
|
### `logs.download`
|
||||||
|
|
||||||
|
Read ≤4096 bytes of a log file; loop with `next_offset` until `eof`.
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `file` (string, required, bare filename), `offset` (int, default 0) |
|
||||||
|
| Returns | `data: { "file", "data", "next_offset", "eof" }` |
|
||||||
|
|
||||||
|
Errors: `SD card not available on this device`, `Missing required field: file`, `Log file not found: <file>`.
|
||||||
|
|
||||||
|
### `logs.clear`
|
||||||
|
|
||||||
|
> **Warning:** Deletes all SD debug log files.
|
||||||
|
|
||||||
|
Returns `data: { "deleted": 4 }`. Error: `SD card not available on this device`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## RF Remote Namespace — `RFRemoteHandler` (HAS_RF builds only)
|
||||||
|
|
||||||
|
Up to 16 slots, each binding one 433 MHz code to a playback action. Slots are blank by default. Stored in NVS namespace `rf`.
|
||||||
|
|
||||||
|
### Slot object
|
||||||
|
|
||||||
|
| Field | Type | Required | Notes |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `slot` | int | yes | 0–15 |
|
||||||
|
| `rf_code` | uint32 | yes | Must be non-zero |
|
||||||
|
| `is_stop` | bool | no | Default `false`. If `true`, the code force-stops playback; the fields below are ignored. |
|
||||||
|
| `pid` | string | yes (play) | Built-in or SD melody ID |
|
||||||
|
| `speed` | int | yes (play) | ms per beat, non-zero |
|
||||||
|
| `duration` | int | yes (play) | ms, non-zero. The slot plays like legacy `segment_duration`: loop for `duration` ms, finish the loop, stop. |
|
||||||
|
| `note_assignments` | int[16] | yes (play) | Exactly 16 entries, at least one non-zero. Index = note, value = 1-based bell, 0 = silent. |
|
||||||
|
|
||||||
|
### `rf.set_slot`
|
||||||
|
|
||||||
|
Single slot (fields at top level) or batch (`{ "slots": [ ... ] }`).
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Returns | `message: "Slot 0 programmed"` or `"3 slot(s) programmed"` |
|
||||||
|
|
||||||
|
| Error (single form) | Condition |
|
||||||
|
|---|---|
|
||||||
|
| `missing 'slot'` | |
|
||||||
|
| `'slot' out of range (got <n>, must be 0–15)` | |
|
||||||
|
| `slot <n>: missing or zero 'rf_code'` | |
|
||||||
|
| `slot <n>: play slot missing 'pid'` | |
|
||||||
|
| `slot <n>: play slot missing 'speed'` / `slot <n>: 'speed' must be non-zero` | |
|
||||||
|
| `slot <n>: play slot missing 'duration'` / `slot <n>: 'duration' must be non-zero` | |
|
||||||
|
| `slot <n>: play slot missing 'note_assignments'` | |
|
||||||
|
| `slot <n>: 'note_assignments' must have exactly 16 elements (got <k>)` | |
|
||||||
|
| `slot <n>: 'note_assignments' are all zero — no bells would ring` | |
|
||||||
|
|
||||||
|
Batch form wraps the same reason: `Slot entry invalid — <reason>. No slots were saved.` — **note:** entries *before* the invalid one have in fact already been saved despite the wording.
|
||||||
|
|
||||||
|
```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] } }
|
||||||
|
{ "v": 2, "cmd": "rf.set_slot", "contents": { "slots": [ { "slot": 7, "rf_code": 9274385, "is_stop": true } ] } }
|
||||||
|
```
|
||||||
|
|
||||||
|
### `rf.clear_slot`
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `slot` — int 0–15 or `"all"` |
|
||||||
|
| Returns | `message: "Slot 3 cleared"` / `"All slots cleared"` |
|
||||||
|
|
||||||
|
Errors: `Invalid value for 'slot' — use a slot index (0–15) or "all"`, `Required: 'slot' — slot index (0–15) or "all"`, `Invalid slot index — must be 0–15`.
|
||||||
|
|
||||||
|
### `rf.get_slots`
|
||||||
|
|
||||||
|
```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, "pid": "", "speed": 0, "duration": 0, "is_stop": false, "note_assignments": [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `rf.enable`
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Contents | `enabled` (bool, required) |
|
||||||
|
| Returns | `message: "RF remote enabled"` / `"RF remote disabled"` |
|
||||||
|
| Error | `Required: 'enabled' (bool)` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## MQTT Namespace — `MQTTHandler`
|
||||||
|
|
||||||
|
### `mqtt.enable` / `mqtt.disable`
|
||||||
|
|
||||||
|
Master switch. `mqtt.enable` connects; `mqtt.disable` publishes the offline heartbeat, then disconnects.
|
||||||
|
Returns `message: "MQTT enabled and saved"` / `"MQTT disabled and saved"`. Error: `MQTT state changed but failed to save to SD`.
|
||||||
|
|
||||||
|
### `mqtt.get_config`
|
||||||
|
|
||||||
|
Returns `data: { "enabled", "host", "port", "user", "use_ssl" }` (never the password).
|
||||||
|
|
||||||
|
### `mqtt.get_topics`
|
||||||
|
|
||||||
|
Returns `data: { "command", "heartbeat", "playback", "reports", "alerts", "info", "logs", "metrics" }` (bools).
|
||||||
|
|
||||||
|
### `mqtt.set_topics`
|
||||||
|
|
||||||
|
Partial update — any of the 8 switch names as bools, at least one.
|
||||||
|
Returns `message: "MQTT topic switches updated and saved"`.
|
||||||
|
|
||||||
|
| Error | Condition |
|
||||||
|
|---|---|
|
||||||
|
| `No recognised topic fields in contents (command, heartbeat, playback, reports, alerts, info, logs, metrics)` | |
|
||||||
|
| `Topic switches changed but failed to save to SD` | |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Telemetry Namespace — `TelemetryHandler`
|
||||||
|
|
||||||
|
| Command | Contents | Returns | Errors |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `telemetry.get_strikes` | — | `data: { "strikes": { "0": 1234, ... } }` | — |
|
||||||
|
| `telemetry.reset_strikes` | `bell` (ignored — always resets all) | `message: "All strike counts reset"` | — |
|
||||||
|
| `telemetry.get_loads` | — | `data: { "loads", "max_loads", "cooling_active", "guard_enabled", "overloaded": [0-based channels] }` | — |
|
||||||
|
| `telemetry.set_max_loads` | `all` (int > 0) **or** `loads` (`{ "0": 300 }`; zero/out-of-range entries skipped) | `message: "All bell max loads updated"` / `"Bell max loads updated"` | `max_load must be > 0`, `Provide 'all' (uint16) or 'loads' (object)` |
|
||||||
|
| `telemetry.set_guard_enabled` | `enabled` (bool, required) | `message: "Bell guard enabled"` / `"... disabled"` | `Missing required field: enabled (bool)` |
|
||||||
|
| `telemetry.get_metrics` | — | `data: { lifetime_runtime_seconds, session_runtime_seconds, total_playbacks, guard_enabled, lifetime_boot_count }` | — |
|
||||||
|
| `telemetry.reset_metrics` | — | `message: "Lifetime runtime and playback count reset to zero"` | — |
|
||||||
|
| `telemetry.get_boot_history` | `limit` (int, optional; clamped to 1–200, `0` → 1, omitted → 200) | `data: { "count", "boots": [...] }` | `No boot history available (no SD card, or no boot has completed NTP sync yet)` |
|
||||||
|
| `telemetry.get_diagnostics` | — | `data: { cpu_temp?, wifi_reconnects, ota, stack_high_water }` (non-consuming peek of the `system/metrics` report) | — |
|
||||||
|
| `telemetry.reset_boot_data` | — | `message: "Lifetime boot count and SD boot log reset"` | `Failed to reset lifetime boot count in NVS` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Bells Namespace — `BellsHandler`
|
||||||
|
|
||||||
|
Master switch for the bell mechanism (BellEngine playback and clock alerts). `relay.test_*` bypass it.
|
||||||
|
|
||||||
|
| Command | Returns | Error |
|
||||||
|
|---|---|---|
|
||||||
|
| `bells.enable` | `message: "Bell mechanism enabled and saved"` | `Bell mechanism enabled but failed to save to SD` |
|
||||||
|
| `bells.disable` | `message: "Bell mechanism disabled and saved"` | `Bell mechanism disabled but failed to save to SD` |
|
||||||
|
| `bells.get_config` | `data: { "bells_enabled", "durations", "outputs" }` | — |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## MQTT Events (Unsolicited)
|
||||||
|
|
||||||
|
Published without a request, on the v2 topic set. Full field-level reference: [mqtt-events.md](mqtt-events.md).
|
||||||
|
|
||||||
|
| Topic | When | QoS | Retained | Switch |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| `vesper/{id}/status/heartbeat` | Every 30s (+ LWT on unclean disconnect) | 1 | yes | `heartbeat` |
|
||||||
|
| `vesper/{id}/status/playback` | On playback transition | 1 | yes | `playback` |
|
||||||
|
| `vesper/{id}/control/reports` | Critical unsolicited events (`bell_overload`, `playback_failed`) | 1 | no | `reports` |
|
||||||
|
| `vesper/{id}/system/alerts` | On subsystem state change only | 1 | yes, until cleared | `alerts` |
|
||||||
|
| `vesper/{id}/system/info` | Discrete device events (e.g. boot report) | 1 | yes | `info` |
|
||||||
|
| `vesper/{id}/system/logs` | Mirrors serial log stream | 0 | no | `logs` |
|
||||||
|
| `vesper/{id}/system/metrics` | Every 5 min | 0 | no | `metrics` |
|
||||||
|
|
||||||
|
`control/ack` carries only replies (it is not an event topic).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Legacy Compatibility (v1)
|
||||||
|
|
||||||
|
When `v` is `1` (or omitted on MQTT/WebSocket/UART), `LegacyAdapter` rewrites `cmd` + `contents.action` to a v2 command (removing `action`) before dispatch. A `cmd` it doesn't recognise is passed through unchanged, so v2 command names still work without `v`. Only `system.status` replies are translated back to the v1 shape (see [`system.status`](#systemstatus)).
|
||||||
|
|
||||||
|
| v1 `cmd` | v1 `action` | v2 `cmd` |
|
||||||
|
|---|---|---|
|
||||||
|
| `ping` | — | `ping` |
|
||||||
|
| `identify` | — | `identify` |
|
||||||
|
| `playback` | `play` | `playback.play` |
|
||||||
|
| `playback` | `stop` | `playback.stop` |
|
||||||
|
| `file_manager` | `list_melodies` | `files.list` |
|
||||||
|
| `file_manager` | `download_melody` | `files.download` |
|
||||||
|
| `file_manager` | `delete_melody` | `files.delete` |
|
||||||
|
| `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_config` |
|
||||||
|
| `system_info` | `get_all_settings` | `system.get_all` |
|
||||||
|
| `system_info` | `get_telemetry` | `system.get_telemetry` |
|
||||||
|
| `system_info` | `sync_time_to_lcd` | `system.get_time` *(LCD now uses request/response)* |
|
||||||
|
| `bells` | `enable` | `bells.enable` |
|
||||||
|
| `bells` | `disable` | `bells.disable` |
|
||||||
|
| `bells` | `get_config` | `bells.get_config` |
|
||||||
|
| `system` | `status` | `system.status` |
|
||||||
|
| `system` | `reset_defaults` | `system.factory_reset` |
|
||||||
|
| `system` | `commit_firmware` | `firmware.commit` |
|
||||||
|
| `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` | `play`, `stop` |
|
||||||
|
| `relay` | `set_durations`, `set_outputs`, `set_config`, `get_config`, `test_output`, `test_bell`, `test_batch` |
|
||||||
|
| `clock` | `set_outputs`, `set_timings`, `set_alerts`, `set_backlight`, `set_silence`, `set_config`, `set_alerts_config`, `set_time`, `set_face`, `set_timezone`, `get_timezone`, `sync_ntp`, `enable`, `disable`, `pause`, `resume`, `get_face`, `get_config`, `test_c1`, `test_c2` |
|
||||||
|
| `system` | `status`, `get_time`, `get_config` (alias `get_settings`), `get_all`, `get_telemetry`, `get_device_info`, `health`, `factory_reset`, `restart`, `set_identity` |
|
||||||
|
| `firmware` | `status`, `commit`, `rollback` |
|
||||||
|
| `ota` | `update`, `custom`, `set_channel` |
|
||||||
|
| `network` | `info`, `status`, `set_config` |
|
||||||
|
| `files` | `list`, `list_builtin`, `download`, `delete` |
|
||||||
|
| `log` / `logs` | `log.set_serial`, `log.set_sd`, `log.set_mqtt`, `log.get_config`, `logs.list`, `logs.download`, `logs.clear` |
|
||||||
|
| `mqtt` | `enable`, `disable`, `get_config`, `get_topics`, `set_topics` |
|
||||||
|
| `telemetry` | `get_strikes`, `reset_strikes`, `get_loads`, `set_max_loads`, `set_guard_enabled`, `get_metrics`, `reset_metrics`, `get_boot_history`, `get_diagnostics`, `reset_boot_data` |
|
||||||
|
| `bells` | `enable`, `disable`, `get_config` |
|
||||||
|
| `rf` | `set_slot`, `clear_slot`, `get_slots`, `enable` *(HAS_RF builds only)* |
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,389 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import '/flutter_flow/flutter_flow_util.dart';
|
||||||
|
import '/backend/backend.dart';
|
||||||
|
import '/backend/schema/structs/index.dart';
|
||||||
|
import '/backend/schema/enums/enums.dart';
|
||||||
|
import '/custom_code/actions/index.dart';
|
||||||
|
import 'dart:async';
|
||||||
|
import '/auth/firebase_auth/auth_util.dart' as auth_util;
|
||||||
|
|
||||||
|
class OverloadHandler {
|
||||||
|
/// Handle Overload - WARNING
|
||||||
|
static Future<void> handleBellOverloadWarning(
|
||||||
|
List<int> bellNumbers, List<int> loadPercentages) async {
|
||||||
|
// Create notification message
|
||||||
|
String message = 'Bell Overload Warning!\n\n';
|
||||||
|
for (int i = 0; i < bellNumbers.length; i++) {
|
||||||
|
message += 'Bell ${bellNumbers[i]}: ${loadPercentages[i]}% load\n';
|
||||||
|
}
|
||||||
|
message += '\nHey, you are driving the hammers too hard. Calm down.';
|
||||||
|
|
||||||
|
// Create a notification in user's sub-collection
|
||||||
|
try {
|
||||||
|
final currentUser = auth_util.currentUserReference;
|
||||||
|
final deviceRef = FFAppState().activeDeviceSettings.deviceReference;
|
||||||
|
|
||||||
|
if (currentUser != null && deviceRef != null) {
|
||||||
|
await currentUser.collection('user_notifications').add({
|
||||||
|
'title': 'Bell Overload Warning',
|
||||||
|
'body': message,
|
||||||
|
'timestamp': getCurrentTimestamp,
|
||||||
|
'type': HelperNotificationTypes.warning, // Using your enum
|
||||||
|
'is_read': false,
|
||||||
|
'device_ref': deviceRef,
|
||||||
|
});
|
||||||
|
print('Bell overload warning notification created: $message');
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
print('Failed to create bell overload warning notification: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static Future<void> handleBellOverloadCritical(
|
||||||
|
List<int> bellNumbers, List<int> loadPercentages) async {
|
||||||
|
// Create critical alert message
|
||||||
|
String message = 'CRITICAL: Bell Protection Activated!\n\n';
|
||||||
|
for (int i = 0; i < bellNumbers.length; i++) {
|
||||||
|
message += 'Bell ${bellNumbers[i]}: ${loadPercentages[i]}% load\n';
|
||||||
|
}
|
||||||
|
message +=
|
||||||
|
'\nWe noticed overloading so we kicked in the protection for you.';
|
||||||
|
|
||||||
|
// Create notification in user's sub-collection
|
||||||
|
try {
|
||||||
|
final currentUser = auth_util.currentUserReference;
|
||||||
|
final deviceRef = FFAppState().activeDeviceSettings.deviceReference;
|
||||||
|
|
||||||
|
if (currentUser != null && deviceRef != null) {
|
||||||
|
await currentUser.collection('user_notifications').add({
|
||||||
|
'title': 'CRITICAL: Bell Protection Activated',
|
||||||
|
'body': message,
|
||||||
|
'timestamp': getCurrentTimestamp,
|
||||||
|
'type': HelperNotificationTypes
|
||||||
|
.warning, // Using your enum - could also be GENERAL depending on your preference
|
||||||
|
'is_read': false,
|
||||||
|
'device_ref': deviceRef,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
print('Failed to create critical bell overload notification: $e');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Also trigger a popup/dialog by setting app state variables
|
||||||
|
FFAppState().update(() {
|
||||||
|
FFAppState().alerts = AlertsStruct(
|
||||||
|
criticalAlertMessage: message,
|
||||||
|
showCriticalAlert: true,
|
||||||
|
errorAlertMessage:
|
||||||
|
FFAppState().alerts.errorAlertMessage, // Keep existing
|
||||||
|
showErrorAlert: FFAppState().alerts.showErrorAlert, // Keep existing
|
||||||
|
alertIsActive: FFAppState().alerts.alertIsActive,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
print('Critical bell overload alert triggered: $message');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class InfoMessageHandler {
|
||||||
|
static InfoMessageHandler? _instance;
|
||||||
|
Timer? _clearFiredBellsTimer;
|
||||||
|
|
||||||
|
InfoMessageHandler._internal();
|
||||||
|
|
||||||
|
factory InfoMessageHandler() {
|
||||||
|
_instance ??= InfoMessageHandler._internal();
|
||||||
|
return _instance!;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> handleMessage(dynamic data) async {
|
||||||
|
// Only handle if it's a proper Map and has INFO status
|
||||||
|
if (data is! Map<String, dynamic>) {
|
||||||
|
debugPrint('InfoMessageHandler: Data is not a Map, skipping');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final Map<String, dynamic> message = data;
|
||||||
|
|
||||||
|
if (message['status'] != 'INFO') {
|
||||||
|
debugPrint('InfoMessageHandler: Not an INFO message, skipping');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final String type = message['type'] ?? '';
|
||||||
|
final dynamic payload = message['payload'];
|
||||||
|
|
||||||
|
debugPrint(
|
||||||
|
'InfoMessageHandler: Handling INFO message - type: $type, payload: $payload');
|
||||||
|
|
||||||
|
try {
|
||||||
|
switch (type) {
|
||||||
|
case 'playback':
|
||||||
|
await _handlePlaybackMessage(payload);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'bell_overload':
|
||||||
|
await _handleBellOverloadMessage(payload);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'general':
|
||||||
|
case 'error':
|
||||||
|
case 'warning':
|
||||||
|
await _handleGeneralInfoMessage(type, payload);
|
||||||
|
break;
|
||||||
|
case 'ding':
|
||||||
|
await _handleDingMessage(payload);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
debugPrint('InfoMessageHandler: Unhandled message type: $type');
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('InfoMessageHandler: Error handling message: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _handleDingMessage(dynamic payload) async {
|
||||||
|
debugPrint(
|
||||||
|
'InfoMessageHandler: Handling Ding Message with payload: $payload');
|
||||||
|
|
||||||
|
try {
|
||||||
|
List<int> firedBells = [];
|
||||||
|
|
||||||
|
if (payload is List) {
|
||||||
|
// Handle array of bell numbers [1, 3, 5]
|
||||||
|
for (dynamic bellItem in payload) {
|
||||||
|
if (bellItem is int) {
|
||||||
|
firedBells.add(bellItem);
|
||||||
|
} else if (bellItem is double) {
|
||||||
|
firedBells.add(bellItem.toInt());
|
||||||
|
} else if (bellItem is String) {
|
||||||
|
final parsed = int.tryParse(bellItem);
|
||||||
|
if (parsed != null) {
|
||||||
|
firedBells.add(parsed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (payload is int) {
|
||||||
|
firedBells.add(payload);
|
||||||
|
} else if (payload is double) {
|
||||||
|
firedBells.add(payload.toInt());
|
||||||
|
} else if (payload is String) {
|
||||||
|
final parsed = int.tryParse(payload);
|
||||||
|
if (parsed != null) {
|
||||||
|
firedBells.add(parsed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Merge with existing fired bells (don't overwrite, combine)
|
||||||
|
Set<int> combinedBells =
|
||||||
|
Set<int>.from(FFAppState().activeDeviceStatus.firedBells ?? []);
|
||||||
|
combinedBells.addAll(firedBells);
|
||||||
|
|
||||||
|
// Update app state with combined bells
|
||||||
|
FFAppState().update(() {
|
||||||
|
FFAppState().activeDeviceStatus.firedBells = combinedBells.toList();
|
||||||
|
});
|
||||||
|
|
||||||
|
debugPrint(
|
||||||
|
'InfoMessageHandler: Updated firedBells with bells: ${combinedBells.toList()}');
|
||||||
|
|
||||||
|
// CANCEL any existing timer
|
||||||
|
_clearFiredBellsTimer?.cancel();
|
||||||
|
|
||||||
|
// Start NEW timer - this ensures 150ms after the LAST message
|
||||||
|
_clearFiredBellsTimer = Timer(Duration(milliseconds: 60), () {
|
||||||
|
FFAppState().update(() {
|
||||||
|
FFAppState().activeDeviceStatus.firedBells = [];
|
||||||
|
});
|
||||||
|
debugPrint('InfoMessageHandler: Cleared firedBells after 60');
|
||||||
|
_clearFiredBellsTimer = null;
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('InfoMessageHandler: Error processing ding message: $e');
|
||||||
|
|
||||||
|
// On error, clear immediately
|
||||||
|
_clearFiredBellsTimer?.cancel();
|
||||||
|
FFAppState().update(() {
|
||||||
|
FFAppState().activeDeviceStatus.firedBells = [];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _handlePlaybackMessage(dynamic payload) async {
|
||||||
|
debugPrint(
|
||||||
|
'InfoMessageHandler: Handling playback message with payload: $payload');
|
||||||
|
PlaybackStatus playbackStatus;
|
||||||
|
|
||||||
|
if (payload is String) {
|
||||||
|
// Simple string payload like "playing", "paused", "stopping", "idle"
|
||||||
|
switch (payload.toLowerCase()) {
|
||||||
|
case 'playing':
|
||||||
|
playbackStatus = PlaybackStatus.playing;
|
||||||
|
debugPrint('Playback started (via INFO message)');
|
||||||
|
break;
|
||||||
|
case 'paused':
|
||||||
|
playbackStatus = PlaybackStatus.paused;
|
||||||
|
debugPrint('Playback is paused (via INFO message)');
|
||||||
|
break;
|
||||||
|
case 'stopping':
|
||||||
|
playbackStatus = PlaybackStatus.stopping;
|
||||||
|
debugPrint('Playback is stopping (via INFO message)');
|
||||||
|
break;
|
||||||
|
case 'idle':
|
||||||
|
playbackStatus = PlaybackStatus.idle;
|
||||||
|
debugPrint('Playback is idle (via INFO message)');
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
playbackStatus = PlaybackStatus.unavailable;
|
||||||
|
debugPrint('InfoMessageHandler: Unknown playback payload: $payload');
|
||||||
|
}
|
||||||
|
|
||||||
|
// For simple string payloads, we don't have timing info
|
||||||
|
FFAppState().update(() {
|
||||||
|
FFAppState().activeDeviceStatus = DeviceStatusStruct(
|
||||||
|
playbackStatus: playbackStatus,
|
||||||
|
playbackStartTime: playbackStatus == PlaybackStatus.playing
|
||||||
|
? getCurrentTimestamp
|
||||||
|
: null,
|
||||||
|
projectedEndTime:
|
||||||
|
null, // No timing info available for simple payloads
|
||||||
|
);
|
||||||
|
});
|
||||||
|
} else if (payload is Map<String, dynamic>) {
|
||||||
|
// Complex payload with additional data
|
||||||
|
final String action = payload['action'] ?? '';
|
||||||
|
final dynamic timeElapsedDynamic = payload['time_elapsed'] ?? 0;
|
||||||
|
final dynamic projectedRunTimeDynamic =
|
||||||
|
payload['projected_run_time'] ?? 0;
|
||||||
|
|
||||||
|
// Convert time_elapsed to int (could be in seconds or milliseconds from ESP32)
|
||||||
|
int timeElapsed = 0;
|
||||||
|
if (timeElapsedDynamic is int) {
|
||||||
|
timeElapsed = timeElapsedDynamic;
|
||||||
|
} else if (timeElapsedDynamic is double) {
|
||||||
|
timeElapsed = timeElapsedDynamic.toInt();
|
||||||
|
} else if (timeElapsedDynamic is String) {
|
||||||
|
timeElapsed = int.tryParse(timeElapsedDynamic) ?? 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert projected_run_time to int
|
||||||
|
int projectedRunTime = 0;
|
||||||
|
if (projectedRunTimeDynamic is int) {
|
||||||
|
projectedRunTime = projectedRunTimeDynamic;
|
||||||
|
} else if (projectedRunTimeDynamic is double) {
|
||||||
|
projectedRunTime = projectedRunTimeDynamic.toInt();
|
||||||
|
} else if (projectedRunTimeDynamic is String) {
|
||||||
|
projectedRunTime = int.tryParse(projectedRunTimeDynamic) ?? 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (action.toLowerCase()) {
|
||||||
|
case 'playing':
|
||||||
|
playbackStatus = PlaybackStatus.playing;
|
||||||
|
debugPrint(
|
||||||
|
'Playback started (via INFO message) with elapsed time: ${timeElapsed}ms, projected duration: ${projectedRunTime}ms');
|
||||||
|
break;
|
||||||
|
case 'paused':
|
||||||
|
playbackStatus = PlaybackStatus.paused;
|
||||||
|
debugPrint(
|
||||||
|
'Playback paused (via INFO message) with elapsed time: ${timeElapsed}ms');
|
||||||
|
break;
|
||||||
|
case 'stopping':
|
||||||
|
playbackStatus = PlaybackStatus.stopping;
|
||||||
|
debugPrint(
|
||||||
|
'Playback stopping (via INFO message) with elapsed time: ${timeElapsed}ms');
|
||||||
|
break;
|
||||||
|
case 'idle':
|
||||||
|
playbackStatus = PlaybackStatus.idle;
|
||||||
|
debugPrint('Playback is idle (via INFO message)');
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
playbackStatus = PlaybackStatus.unavailable;
|
||||||
|
debugPrint('InfoMessageHandler: Unknown playback action: $action');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate playbackStartTime (currentTime - time_elapsed)
|
||||||
|
// timeElapsed from ESP32 is in seconds, but we need milliseconds
|
||||||
|
DateTime? playbackStartTime;
|
||||||
|
if ((playbackStatus == PlaybackStatus.playing ||
|
||||||
|
playbackStatus == PlaybackStatus.paused ||
|
||||||
|
playbackStatus == PlaybackStatus.stopping) &&
|
||||||
|
timeElapsed > 0) {
|
||||||
|
final now = getCurrentTimestamp;
|
||||||
|
// timeElapsed is in seconds from ESP32, convert to milliseconds
|
||||||
|
playbackStartTime = DateTime.fromMillisecondsSinceEpoch(
|
||||||
|
now.millisecondsSinceEpoch - (timeElapsed * 1000));
|
||||||
|
} else if (playbackStatus == PlaybackStatus.playing) {
|
||||||
|
// If just started playing, use current time
|
||||||
|
playbackStartTime = getCurrentTimestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate projectedEndTime only if we have valid data
|
||||||
|
DateTime? projectedEndTime;
|
||||||
|
if (playbackStartTime != null && projectedRunTime > 0) {
|
||||||
|
projectedEndTime =
|
||||||
|
playbackStartTime.add(Duration(milliseconds: projectedRunTime));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update the DeviceStatus app state
|
||||||
|
FFAppState().update(() {
|
||||||
|
FFAppState().activeDeviceStatus = DeviceStatusStruct(
|
||||||
|
playbackStatus: playbackStatus,
|
||||||
|
playbackStartTime: playbackStartTime,
|
||||||
|
projectedEndTime: projectedEndTime,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
debugPrint(
|
||||||
|
'InfoMessageHandler: Updated device status - status: $playbackStatus, '
|
||||||
|
'startTime: $playbackStartTime, endTime: $projectedEndTime');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _handleBellOverloadMessage(dynamic payload) async {
|
||||||
|
debugPrint('InfoMessageHandler: Handling bell overload message');
|
||||||
|
|
||||||
|
if (payload is Map<String, dynamic>) {
|
||||||
|
final List<dynamic>? bells = payload['bells'];
|
||||||
|
final List<dynamic>? loads = payload['loads'];
|
||||||
|
final String severity =
|
||||||
|
payload['severity'] ?? 'warning'; // 'warning' or 'critical'
|
||||||
|
|
||||||
|
if (bells != null && loads != null && bells.length == loads.length) {
|
||||||
|
// Convert to proper types
|
||||||
|
final List<int> bellNumbers = bells.cast<int>();
|
||||||
|
final List<int> loadPercentages = loads.cast<int>();
|
||||||
|
|
||||||
|
if (severity == 'critical') {
|
||||||
|
await OverloadHandler.handleBellOverloadCritical(
|
||||||
|
bellNumbers, loadPercentages);
|
||||||
|
} else {
|
||||||
|
await OverloadHandler.handleBellOverloadWarning(
|
||||||
|
bellNumbers, loadPercentages);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
debugPrint(
|
||||||
|
'InfoMessageHandler: Invalid bell overload payload structure');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _handleGeneralInfoMessage(String type, dynamic payload) async {
|
||||||
|
debugPrint(
|
||||||
|
'InfoMessageHandler: Handling general info message - type: $type');
|
||||||
|
|
||||||
|
String message = '';
|
||||||
|
String severity = type; // 'general', 'error', 'warning'
|
||||||
|
|
||||||
|
if (payload is String) {
|
||||||
|
message = payload;
|
||||||
|
} else if (payload is Map<String, dynamic>) {
|
||||||
|
message = payload['message'] ?? payload.toString();
|
||||||
|
severity = payload['severity'] ?? type;
|
||||||
|
} else {
|
||||||
|
message = payload.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
await handleGeneralNotification(message, severity);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,399 @@
|
|||||||
|
# Vesper — MQTT Events Reference (v2)
|
||||||
|
|
||||||
|
> 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.
|
||||||
|
> Companion spec: [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_topic_spec_v2.md) — topic table, per-topic ON/OFF switches, `req_id` correlation, LWT.
|
||||||
|
> Last updated: 2026-09-21 (v2 topic rebuild — see F-062 in [feature-catalog.md](../features/feature-catalog.md))
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Vesper publishes on eight MQTT topics (a ninth, `system/ota`, is reserved but not yet built). All topics are device-scoped under the prefix `vesper/{device_id}/`.
|
||||||
|
|
||||||
|
| Topic | Direction | QoS | Retained | Switch | Purpose |
|
||||||
|
|-------|-----------|-----|----------|--------|---------|
|
||||||
|
| `vesper/{id}/control/command` | Inbound | 1 | no | `command` | Commands from server/app — board only ever receives here |
|
||||||
|
| `vesper/{id}/control/ack` | Outbound | 1 | no | `command` | Replies to commands **only** — strictly request/response |
|
||||||
|
| `vesper/{id}/control/reports` | Outbound | 1 | no | `reports` | Critical, unsolicited, time-sensitive board-initiated events (`bell_overload`, `playback_failed`) |
|
||||||
|
| `vesper/{id}/status/heartbeat` | Outbound | 1 | yes | `heartbeat` | Periodic liveness + state signal. Also carries LWT. |
|
||||||
|
| `vesper/{id}/status/playback` | Outbound | 1 | yes | `playback` | Playback transitions only |
|
||||||
|
| `vesper/{id}/system/alerts` | Outbound | 1 | yes, until cleared | `alerts` | Subsystem state-change events |
|
||||||
|
| `vesper/{id}/system/info` | Outbound | 1 | yes | `info` | Discrete device state events (boot report, etc.) |
|
||||||
|
| `vesper/{id}/system/logs` | Outbound | 0 | no | `logs` | Full log stream, mirrors serial log output |
|
||||||
|
| `vesper/{id}/system/metrics` | Outbound | 0 | no | `metrics` | Structured telemetry — fleet-health graphing |
|
||||||
|
|
||||||
|
Subscribe to `vesper/+/#` to receive everything from all devices (fleet webserver pattern). The phone app subscribes to `control/ack`, `status/heartbeat`, `status/playback`, and `control/reports` (for `playback_failed`).
|
||||||
|
|
||||||
|
Every topic above except `control/command`/`control/ack` (which share one switch, `command`) has its own independent ON/OFF publish switch — see [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_topic_spec_v2.md#per-topic-onoff-switches) for the full mechanism (`mqtt.get_topics`/`mqtt.set_topics`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## `vesper/{id}/status/heartbeat`
|
||||||
|
|
||||||
|
**QoS:** 1 — **Retained:** yes — **Interval:** 30 seconds — **Switch:** `heartbeat`
|
||||||
|
|
||||||
|
Published immediately on MQTT connect, then every 30 seconds. The broker retains the last message so any new subscriber instantly sees the device's last known state. Also the LWT target — see [LWT](#last-will-and-testament-lwt) below.
|
||||||
|
|
||||||
|
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), or immediately on receiving an LWT-triggered `state: "offline"` message
|
||||||
|
|
||||||
|
### Payload
|
||||||
|
|
||||||
|
Flat — no envelope wrapper (the topic is the discriminator).
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"device_id": "BSVSPR-26E11J-STD10R-M4SC2Z",
|
||||||
|
"state": "idle",
|
||||||
|
"ok": true,
|
||||||
|
"fw_version": "2.2.0",
|
||||||
|
"uptime_ms": 19425000,
|
||||||
|
"uptime_human": "5h 23m 45s",
|
||||||
|
"ip_address": "10.0.0.3",
|
||||||
|
"gateway": "10.0.0.1",
|
||||||
|
"rssi": -62,
|
||||||
|
"free_heap": 142000
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Field | Type | Description |
|
||||||
|
|-------|------|-------------|
|
||||||
|
| `device_id` | string | Device serial number (from NVS) |
|
||||||
|
| `state` | string | `idle` \| `playing` \| `paused` \| `error` \| `booting` — independently derived from `Player`/`HealthMonitor`, never mirrored from `status/playback` or `system/alerts` |
|
||||||
|
| `ok` | bool | Overall device health (`HealthMonitor::isFirmwareStable()`), independent of playback state |
|
||||||
|
| `fw_version` | string | Firmware SemVer string |
|
||||||
|
| `uptime_ms` | integer | Milliseconds since boot |
|
||||||
|
| `uptime_human` | string | Human-readable uptime, e.g. `"5h 23m 45s"` |
|
||||||
|
| `ip_address` | string | Current device IP |
|
||||||
|
| `gateway` | string | Network gateway IP |
|
||||||
|
| `rssi` | integer | WiFi signal strength (dBm) |
|
||||||
|
| `free_heap` | integer | Free heap in bytes |
|
||||||
|
|
||||||
|
### Last Will and Testament (LWT)
|
||||||
|
|
||||||
|
Registered on every `begin()`/reconnect. If the connection drops **uncleanly** (crash, power loss, network loss), the broker automatically publishes:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "device_id": "BSVSPR-26E11J-STD10R-M4SC2Z", "state": "offline", "ok": false }
|
||||||
|
```
|
||||||
|
|
||||||
|
to `status/heartbeat` (QoS 1, retained), overwriting the last "online" heartbeat. For **intentional** disconnects (e.g. `mqtt.disable`), the firmware explicitly publishes the same payload before disconnecting, since LWT does not fire on a clean disconnect.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## `vesper/{id}/status/playback`
|
||||||
|
|
||||||
|
**QoS:** 1 — **Retained:** yes — **Switch:** `playback` — **Trigger:** playback state transition only
|
||||||
|
|
||||||
|
Published by `Player::setStatus()` on every transition (not polled), **and on every MQTT connect/reconnect** with the Player's current real state — so a retained `playing` left behind by a power loss mid-melody is overwritten (normally with `idle`) as soon as the board is back. This topic — not the `control/ack` reply — is the source of truth for what the board is actually doing. Skipped (not queued) while free heap is below the publish guard.
|
||||||
|
|
||||||
|
### Payload
|
||||||
|
|
||||||
|
Flat — no envelope wrapper.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"action": "playing",
|
||||||
|
"time_elapsed": 12,
|
||||||
|
"projected_run_time": 45000,
|
||||||
|
"pid": "westminster",
|
||||||
|
"speed": 400,
|
||||||
|
"duration": 120000,
|
||||||
|
"started_at": 1790000000,
|
||||||
|
"source": "app",
|
||||||
|
"ts": 1790000012
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "action": "idle", "time_elapsed": 0, "projected_run_time": 0, "pid": "", "speed": 0, "duration": 0, "started_at": 0, "source": "", "ts": 1790000130 }
|
||||||
|
```
|
||||||
|
|
||||||
|
| Field | Type | Description |
|
||||||
|
|-------|------|-------------|
|
||||||
|
| `action` | string | `loading` \| `playing` \| `paused` \| `stopping` \| `idle` — see [States](#states) |
|
||||||
|
| `time_elapsed` | integer | Seconds since playback started, as of `ts` (0 for `idle`) |
|
||||||
|
| `projected_run_time` | integer | Projected total run time in ms (0 if not applicable) |
|
||||||
|
| `pid` | string | Melody being played or loaded (`""` when idle) |
|
||||||
|
| `speed` | integer | ms per beat (0 when idle) |
|
||||||
|
| `duration` | integer | Requested run-time cap in ms — the effective stop timer after `mode`/legacy field resolution (`timed` → `duration`, `interval` → `total_duration`, legacy → `segment_duration`/`total_duration`). `0` = no cap: a `single` play ends naturally, `infinite` runs until stopped. 0 when idle. |
|
||||||
|
| `started_at` | integer | Unix epoch seconds (UTC) when playback started. `0` when idle, while `loading` (not started yet), or when the board has no valid clock. |
|
||||||
|
| `source` | string | What started the playback: `app` (MQTT/WebSocket/HTTP command), `rf` (RF remote slot), `button` (UART LCD/button slave board), `schedule` (reserved — scheduled events don't start playback yet), `unknown`. `""` when idle. |
|
||||||
|
| `ts` | integer | Unix epoch seconds (UTC) when this message was built. `0` when the board has no valid clock. |
|
||||||
|
|
||||||
|
**Clock source for `started_at` / `ts`:** the NTP-synced system clock if valid, else the RTC (converted from its stored local time to UTC using the configured offsets), else `0`. RTC-less builds (agnus) therefore report `0` until NTP has synced. Always check for `0` before using either.
|
||||||
|
|
||||||
|
**Stale retained messages.** Because the topic is retained, a client may receive a message published long ago. Real elapsed time is `now − started_at` (when `started_at != 0`); `ts` tells you how old the snapshot is. `time_elapsed` is only correct as of `ts`.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "action": "loading", "time_elapsed": 0, "projected_run_time": 0, "pid": "ABC123", "speed": 400, "duration": 120000, "started_at": 0, "source": "app", "ts": 1790000100 }
|
||||||
|
```
|
||||||
|
|
||||||
|
The WebSocket transport receives the same fields on every transition, wrapped in the legacy broadcast envelope: `{ "status": "INFO", "type": "playback", "payload": { ...fields above... } }` — **except `loading`, which is MQTT-only**: v1 tablets (WebSocket) map any unknown playback action to "unavailable", so WebSocket clients keep seeing `idle` → `playing` for a download.
|
||||||
|
|
||||||
|
### States
|
||||||
|
|
||||||
|
| `action` | Meaning | Entered from | Leaves to |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `loading` | A `playback.play` was accepted (ACK: `Melody download started — …`) and the melody is downloading to SD first. No bells yet; `pid` identifies what is coming. | `idle` | `playing` (download OK), `idle` (download failed → also a [`playback_failed`](#playback-failed-event) report; or `playback.stop` → cancelled) |
|
||||||
|
| `playing` | Bells are ringing. | `idle` (play accepted), `loading` (download done), `paused` (segment pause over) | `paused`, `stopping`, `idle` |
|
||||||
|
| `paused` | Between segments of an `interval` (or legacy `continuous_loop`) play — bells silent, playback still active. | `playing` | `playing`, `idle` |
|
||||||
|
| `stopping` | The run-time cap (`duration`) has elapsed; the bells are **finishing the current melody loop** before stopping (can last up to one full loop, i.e. steps × `speed`). Still ringing. | `playing` (timer reached `duration`) | `idle` (loop finished) |
|
||||||
|
| `idle` | Nothing playing. | any (`playback.stop`, natural end, overload force-stop) | `playing` |
|
||||||
|
|
||||||
|
`playback.stop` during `playing`/`paused`/`stopping` cuts the bells immediately and goes straight to `idle` — it never passes through `stopping`. During `loading` it cancels the pending start (ACK `Download cancelled — playback will not start`); the transfer itself finishes in the background and is discarded. A new `playback.play` is rejected in every state except `idle` (and briefly after a cancelled download, until that transfer ends).
|
||||||
|
|
||||||
|
On a SUCCESS play ACK the board publishes `status/playback` **before** the ACK: `playing` (melody was local) or `loading` (download needed). The heartbeat's independently-derived `state` reports `idle` during `stopping`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## `vesper/{id}/control/reports`
|
||||||
|
|
||||||
|
**QoS:** 1 — **Retained:** no — **Switch:** `reports` — **Trigger:** critical, time-sensitive, board-initiated event
|
||||||
|
|
||||||
|
The opposite of `control/command`: unsolicited data the board sends because it needs to be read *now*. Not a reply to anything — never carries `req_id`. Not retained, since it's an event stream, not a status snapshot.
|
||||||
|
|
||||||
|
### Envelope
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "type": "event_type", "payload": { ... } }
|
||||||
|
```
|
||||||
|
|
||||||
|
### Bell overload event
|
||||||
|
|
||||||
|
Published by `CommunicationRouter::sendBellOverloadNotification()` → `publishReport("bell_overload", ...)` when per-bell strike load exceeds configured thresholds.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"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) |
|
||||||
|
|
||||||
|
### Playback failed event
|
||||||
|
|
||||||
|
Published by `CommunicationRouter::sendPlaybackFailedNotification()` from the melody download task when a `playback.play` was already ACKed SUCCESS (`Melody download started — …`) but playback never began. `status/playback` goes `loading` → `idle` at the same moment. Not sent when the download was cancelled by `playback.stop`.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "type": "playback_failed", "payload": { "pid": "ABC123", "reason": "Melody download failed" } }
|
||||||
|
```
|
||||||
|
|
||||||
|
| Field | Type | Description |
|
||||||
|
|-------|------|-------------|
|
||||||
|
| `payload.pid` | string | The melody that failed to start |
|
||||||
|
| `payload.reason` | string | One of: `Melody download failed` (HTTP/SD failure), `Melody failed to load: file is empty or corrupt` (downloaded file unusable), `Playback blocked: bell mechanism is disabled (bells.enable)` / `Playback blocked: bell overload protection active — wait for the bells to cool` (conditions changed during the download) |
|
||||||
|
|
||||||
|
Like every `control/reports` event it carries no `req_id` — correlate with the command by `pid` (only one download can be pending at a time). WebSocket clients get the same as `{ "status": "INFO", "type": "playback_failed", "payload": { "pid", "reason" } }`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## `vesper/{id}/system/alerts`
|
||||||
|
|
||||||
|
**QoS:** 1 — **Retained:** yes, until cleared — **Switch:** `alerts` — **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, or the `alerts` switch is off, at the moment of the transition. Retained so a late-connecting console (fleet webserver) immediately sees the last unresolved alert per subsystem.
|
||||||
|
|
||||||
|
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`, `System` |
|
||||||
|
| `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 |
|
||||||
|
|
||||||
|
A fault-class boot reset also publishes here — `subsystem: "System"`, e.g.:
|
||||||
|
```json
|
||||||
|
{ "subsystem": "System", "state": "WARNING", "msg": "Device reset due to fault: TASK_WATCHDOG" }
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## `vesper/{id}/system/info`
|
||||||
|
|
||||||
|
**QoS:** 1 — **Retained:** yes — **Switch:** `info` — **Trigger:** discrete device state event
|
||||||
|
|
||||||
|
Published for general device state changes that are not health failures and not quantitative telemetry (see `system/metrics` for that). Use this topic to update the device detail panel (e.g. boot reason) without polling.
|
||||||
|
|
||||||
|
### Envelope
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "type": "event_type", "payload": { ... } }
|
||||||
|
```
|
||||||
|
|
||||||
|
### `boot_report`
|
||||||
|
|
||||||
|
Published once, the first time MQTT connects after boot (guarded, not repeated on reconnect).
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "boot_report",
|
||||||
|
"payload": {
|
||||||
|
"boot_count": 47,
|
||||||
|
"reset_reason": "PANIC",
|
||||||
|
"is_fault": true,
|
||||||
|
"free_heap": 187234,
|
||||||
|
"crash": { "task": "TelemetryTask", "pc": 1074111832, "exc_cause": 1, "exc_vaddr": 0 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`crash` is present only when a coredump was found for the crash that caused this boot — omitted on a clean/expected reset or a fault reset with no coredump (e.g. brownout). A fault-class reset additionally publishes a `system/alerts` WARNING (see above) — `system/info`'s `boot_report` is published unconditionally, fault or not.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## `vesper/{id}/system/logs`
|
||||||
|
|
||||||
|
**QoS:** 0 — **Retained:** no — **Switch:** `logs`
|
||||||
|
|
||||||
|
Mirrors the serial log stream, respecting both the configured MQTT log level (`log.set_mqtt`, 0–5) and this topic's own ON/OFF switch independently — the switch can silence the whole channel without touching the configured level. See [Logging](../../src/Logging/README.md).
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "level": "WARNING", "subsystem": "BellEngine", "message": "...", "timestamp": 12345 }
|
||||||
|
```
|
||||||
|
|
||||||
|
`timestamp` is `millis()` (ms since boot), not wall-clock time.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## `vesper/{id}/system/metrics`
|
||||||
|
|
||||||
|
**QoS:** 0 — **Retained:** no — **Switch:** `metrics` — **Interval:** 5 minutes
|
||||||
|
|
||||||
|
Structured telemetry for fleet-health graphing — not consumed by the phone app. Published by `CommunicationRouter::reportDiagnosticsIfDue()`.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cpu_temp": { "avg": 47.1, "min": 44.8, "max": 52.8, "samples": 20 },
|
||||||
|
"wifi_reconnects": { "lifetime_count": 2, "last_reason": "AUTH_EXPIRE", "last_at_uptime_ms": 3600000 },
|
||||||
|
"ota": { "current_version": "2.2.0", "update_available": false, "last_check_uptime_ms": 180000, "last_error": "NONE" },
|
||||||
|
"stack_high_water": { "TelemetryTask": 1024, "HealthMonitor": 890 },
|
||||||
|
"bell_strikes": { "0": 1234, "1": 567 },
|
||||||
|
"bell_loads": { "0": 12, "1": 0 },
|
||||||
|
"cooling_active": false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Field | Type | Description |
|
||||||
|
|-------|------|-------------|
|
||||||
|
| `cpu_temp` | object | Min/max/avg CPU die temperature (°C) since the last report |
|
||||||
|
| `wifi_reconnects` | object | Lifetime-this-boot reconnect count, last disconnect reason/uptime |
|
||||||
|
| `ota` | object | Current/available version, update-available flag, last check time, last error |
|
||||||
|
| `stack_high_water` | object | Bytes free per registered task (low-water mark) |
|
||||||
|
| `bell_strikes` | object | Cumulative strike count per bell channel (0–15) |
|
||||||
|
| `bell_loads` | object | Current heat-load accumulator per bell channel |
|
||||||
|
| `cooling_active` | bool | True if any bell still has residual heat |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## `vesper/{id}/control/command` and `vesper/{id}/control/ack`
|
||||||
|
|
||||||
|
**QoS:** 1 — **Retained:** no — **Switch:** `command`
|
||||||
|
|
||||||
|
`control/command` is read-only from the board's perspective — the board only ever receives here. `control/ack` is strictly reply-only: every message on it answers a specific request (including `pong`), and no unsolicited event is ever published there. Both support an optional `req_id` field for correlation — see [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_topic_spec_v2.md#req_id-correlation).
|
||||||
|
|
||||||
|
### Command (inbound)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "v": 2, "cmd": "playback.stop", "req_id": "abc123" }
|
||||||
|
```
|
||||||
|
|
||||||
|
### Reply (outbound)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "status": "SUCCESS", "type": "playback", "req_id": "abc123", "message": "Playback command executed" }
|
||||||
|
```
|
||||||
|
|
||||||
|
Reply envelope: `status` (`SUCCESS`/`ERROR`), `type`, optional `req_id`, and either `message` (string — text replies and every error) or `data` (object — structured replies). There is no `payload` key. `req_id` only appears in the reply if the request included one. See [api-reference.md](api-reference.md#response-envelope) for the full envelope rules.
|
||||||
|
|
||||||
|
`CommandBus::broadcast()` would also publish here (same envelope, `status: "INFO"`, no `req_id`), but nothing in the firmware calls it today — purpose-specific events (playback, alerts, reports, metrics) publish directly to their own topics.
|
||||||
|
|
||||||
|
### Malformed input
|
||||||
|
|
||||||
|
Invalid JSON or a missing `cmd` field gets an `ERROR` reply on `control/ack` (`type: "parse_error"`) instead of being silently dropped:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "status": "ERROR", "type": "parse_error", "message": "Invalid JSON: IncompleteInput" }
|
||||||
|
{ "status": "ERROR", "type": "parse_error", "message": "Missing required field: cmd" }
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Server subscription pattern
|
||||||
|
|
||||||
|
```
|
||||||
|
vesper/+/status/heartbeat → update last_seen + state/ok, no logging (unless state:"offline" from LWT)
|
||||||
|
vesper/+/status/playback → update device detail panel's playback state
|
||||||
|
vesper/+/control/reports → surface immediately — critical, time-sensitive (bell_overload, playback_failed)
|
||||||
|
vesper/+/system/alerts → upsert/remove active alert set per device
|
||||||
|
vesper/+/system/info → update device state panel (boot_report, etc.)
|
||||||
|
vesper/+/system/logs → remote log viewer / archival
|
||||||
|
vesper/+/system/metrics → fleet-health graphing / time-series storage
|
||||||
|
vesper/+/control/ack → command responses only (phone app / whoever issued the command)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Migration from v1 topics
|
||||||
|
|
||||||
|
See [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_topic_spec_v2.md#migration-from-v1) for the full old→new topic mapping. Summary: `control`→`control/command`, `data`→`control/ack` (+ new `control/reports` and `status/playback` split out), `status/alerts`→`system/alerts`, `status/info`→`system/info` (diagnostics moved to new `system/metrics`), plus new `system/logs`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 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 |
|
||||||
|
| *(entire v1 topic set: `control`, `data`, `status/alerts`, `status/info`)* | — | v2.2.0 | Replaced wholesale by the v2 topic spec — see F-062 in [feature-catalog.md](../features/feature-catalog.md) |
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
# Vesper MQTT Topic Specification v2
|
||||||
|
|
||||||
|
Reference for firmware implementation. Device ID placeholder: `{device_id}`.
|
||||||
|
Implemented in [MQTTDriver](../../src/Communication/Drivers/MQTTDriver/README.md) (topic strings, LWT, heartbeat)
|
||||||
|
and [MQTTTransport](../../src/Communication/Transport/MQTTTransport/README.md) (command/ack dispatch, req_id).
|
||||||
|
|
||||||
|
## Topic Table
|
||||||
|
|
||||||
|
| Topic | Purpose | QoS | Retain | Switch | Notes |
|
||||||
|
|---|---|---|---|---|---|
|
||||||
|
| `vesper/{device_id}/control/command` | Inbound commands (play, stop, ping, etc.) | 1 | No | `command` | **Read-only from the board's perspective — the board only receives here, never publishes.** Includes optional `req_id` for correlation. `v`, `cmd`, `contents` as before. |
|
||||||
|
| `vesper/{device_id}/control/ack` | Replies to commands, including `pong` | 1 | No | `command` | **Strictly replies only — every message here answers a specific request, and every reply goes here. Nothing unsolicited is ever published to this topic.** Echoes `req_id` from the originating command when one was sent. `status: SUCCESS/ERROR/INFO`, `type`, optional `message`/`data`. Malformed input (invalid JSON, missing `cmd`) also gets an `ERROR` reply here (`type: "parse_error"`) rather than being silently dropped — see [Malformed input](#malformed-input) below. |
|
||||||
|
| `vesper/{device_id}/control/reports` | Critical, time-sensitive board-initiated events (`bell_overload`, `playback_failed`) | 1 | No | `reports` | The opposite of `control/command` — unsolicited data the board sends because it needs to be read *now*. Not a reply to anything, no `req_id`. Not retained — an event stream, not a status snapshot. |
|
||||||
|
| `vesper/{device_id}/status/heartbeat` | Periodic health/state summary, every 30s | 1 | **Yes** | `heartbeat` | Also carries LWT (see below). Fields: `device_id`, `state` (`idle`/`playing`/`paused`/`error`/`booting`), `ok` (bool), `fw_version`, `uptime_ms`, `uptime_human`, `ip_address`, `gateway`, `rssi`, `free_heap` — `state`/`ok` independently derived, never mirrored from `status/playback` or `system/alerts`. |
|
||||||
|
| `vesper/{device_id}/status/playback` | Playback state transitions only | 1 | **Yes** | `playback` | `action`: `loading`/`playing`/`paused`/`stopping`/`idle` (`loading` = play accepted, melody downloading; `stopping` = run-time cap reached, bells finishing the current loop), plus `time_elapsed`, `projected_run_time`, `pid`, `speed`, `duration`, `started_at`, `source`, `ts` — see [mqtt-events.md](mqtt-events.md#vesperidstatusplayback). Published on transition, not polled — plus once on every (re)connect with the current real state, so a stale retained `playing` never outlives a reboot. Source of truth for what the board is doing (a `control/ack` SUCCESS only means "accepted"). |
|
||||||
|
| `vesper/{device_id}/system/alerts` | Subsystem state changes (warnings/errors) | 1 | **Yes**, until cleared | `alerts` | Published on transition only (WARNING/CRITICAL/FAILED/CLEARED). Not consumed by phone app — webserver/fleet only. |
|
||||||
|
| `vesper/{device_id}/system/info` | Discrete system events (e.g. `boot_report`) | 1 | **Yes** | `info` | Not consumed by phone app. Excludes errors (those go to `alerts`) and metrics (those go to `metrics`). |
|
||||||
|
| `vesper/{device_id}/system/logs` | Full log stream, serial-log equivalent | 0 | No | `logs` | Not consumed by phone app. Respects device's configured log level (`log.set_mqtt`) **and** this on/off switch independently — the switch can silence the whole channel without touching the configured level. Should not compete with heap/buffer needed for command traffic — guard same as `hasHeapForPublish()`. |
|
||||||
|
| `vesper/{device_id}/system/metrics` | Structured telemetry (heap free, WiFi RSSI, CPU temp, WiFi reconnects, OTA state, stack high-water marks, bell strike/heat data) | 0 | No | `metrics` | Not consumed by phone app. For fleet-health graphing on webserver. Published every 5 minutes by the existing diagnostics-report mechanism — see [CommunicationRouter](../../src/Communication/CommunicationRouter/README.md). |
|
||||||
|
| `vesper/{device_id}/system/ota` | OTA update status | 1 | No (transient by nature) | — | Not consumed by phone app. Reserved topic — build only once OTA-over-MQTT capability exists. States: e.g. `downloading`/`flashing`/`rebooting`/`failed`. No switch yet (doesn't exist).
|
||||||
|
|
||||||
|
## Per-Topic ON/OFF Switches
|
||||||
|
|
||||||
|
Every topic above (except the not-yet-built `system/ota`) has an independent publish switch, persisted in `ConfigManager::MqttTopicConfig` (SD: `generalConfig.json` → `mqttTopics`; NVS on no-SD boards: packed bitfield at key `gc_mtop`). Default: all on.
|
||||||
|
|
||||||
|
- **Master + sub-switches.** `mqtt.enable`/`mqtt.disable` remains the master kill switch — it disconnects the broker entirely. The per-topic switches below only take effect *while the master switch is on*; they prune which topics publish, not whether the device is connected at all.
|
||||||
|
- **`command` covers both directions.** One switch, `command`, gates `control/command` (the subscription) and `control/ack` (its replies) together — turning it off unsubscribes from `control/command` live (no reconnect needed) and drops any reply that would have gone to `control/ack`.
|
||||||
|
- **Read current state:** `mqtt.get_topics` — returns all 8 switches as booleans.
|
||||||
|
- **Change state:** `mqtt.set_topics` — partial update, only send the fields you want to change:
|
||||||
|
```json
|
||||||
|
{ "v": 2, "cmd": "mqtt.set_topics", "contents": { "heartbeat": true, "metrics": false } }
|
||||||
|
```
|
||||||
|
Persisted to SD/NVS immediately. The `command` switch also applies live (subscribe/unsubscribe) without waiting for a reconnect; the others are simply checked on each publish attempt.
|
||||||
|
|
||||||
|
This lets a device "breathe" — a fleet-monitoring-only install with no phone app can turn off `command` entirely; a bandwidth-constrained site can turn off `logs` and `metrics` while keeping `heartbeat` and `command` alive.
|
||||||
|
|
||||||
|
## req_id Correlation
|
||||||
|
|
||||||
|
`control/command` and `control/ack` both support an optional `req_id` string field for correlating a reply to its request:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "v": 2, "cmd": "ping", "req_id": "abc123", "contents": {} }
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "status": "SUCCESS", "type": "pong", "req_id": "abc123" }
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Always optional.** A request without `req_id` gets a reply without `req_id` — this is deliberate so v1 clients and any caller not fanning requests out over a shared channel keep working unchanged.
|
||||||
|
- **Bus-wide plumbing, MQTT-only today.** `req_id` lives on `CommandEnvelope`/`CommandResult` in the shared `CommandBus` core (see [CommandBus](../../src/Communication/CommandBus/README.md)), not bolted onto MQTT alone — the intent is that any transport where multiple logical senders share one channel (multiple devices on one broker; a future multiplexed transport) can use the same mechanism to route replies. Only `MQTTTransport` currently reads it from the request; WebSocket, HTTP and UART ignore it and their replies never carry it.
|
||||||
|
- **No access control yet.** Any caller can set any `req_id` today. If needed later, safeguards (e.g. restricting who may set one, or validating format) can be added without a wire-format change.
|
||||||
|
|
||||||
|
## Malformed Input
|
||||||
|
|
||||||
|
`control/command` messages that fail to parse, or parse but have no `cmd` field, get an `ERROR` reply on `control/ack` instead of being silently dropped:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "status": "ERROR", "type": "parse_error", "message": "Invalid JSON: IncompleteInput" }
|
||||||
|
{ "status": "ERROR", "type": "parse_error", "message": "Missing required field: cmd" }
|
||||||
|
```
|
||||||
|
|
||||||
|
A reply to unparseable JSON necessarily has no `req_id` — it couldn't be read out of input that failed to parse. A reply to a parseable-but-`cmd`-less message echoes `req_id` if one was present. This exists so a caller waiting on a timeout gets an immediate, actionable "malformed" instead of silence indistinguishable from a lost network message — the same reasoning the heap guard's silent drop (see [MQTTTransport's README](../../src/Communication/Transport/MQTTTransport/README.md)) deliberately does *not* apply here, since that guard exists specifically to avoid allocating under critical heap pressure, whereas a parse error is cheap to report.
|
||||||
|
|
||||||
|
## Cross-Cutting Notes
|
||||||
|
|
||||||
|
- **LWT (Last Will and Testament)**: on connect, register Last Will → publishes to `status/heartbeat` with `{"device_id": "...", "state": "offline", "ok": false}` (retained), fired by the broker only on an *unclean* disconnect. Re-registered automatically on every reconnect (AsyncMqttClient resends the Will on every CONNECT).
|
||||||
|
- **Graceful disconnect**: if the firmware ever disconnects intentionally (e.g. `mqtt.disable`, before OTA), it explicitly publishes the same offline payload before disconnecting, since LWT won't fire for clean disconnects. See `MQTTDriver::disconnect(bool graceful)`.
|
||||||
|
- **Subscribers**:
|
||||||
|
- Phone app subscribes to `control/ack`, `status/heartbeat`, `status/playback`, plus `control/reports` for `playback_failed` (a play that was ACKed but whose melody download then failed) — publishes to `control/command`.
|
||||||
|
- Fleet webserver subscribes to everything via `vesper/+/#`, including `control/reports`, `system/alerts`, `system/info`, `system/logs`, `system/metrics`.
|
||||||
|
|
||||||
|
## Migration from v1
|
||||||
|
|
||||||
|
The previous topic set (`control` in, `data` out, plus `status/alerts` and `status/info`) is fully replaced by this spec — there is no dual-publish period. See [communication-refactor-plan.md](../architecture/communication-refactor-plan.md) for the wire-protocol migration this topic change shipped alongside, and the console's API Reference → Transports → Legacy tab for what will eventually document the pre-v2 shape for historical reference.
|
||||||
|
|
||||||
|
| v1 topic | v2 topic |
|
||||||
|
|---|---|
|
||||||
|
| `vesper/{id}/control` (in) | `vesper/{id}/control/command` |
|
||||||
|
| `vesper/{id}/data` (out — replies + broadcasts mixed) | `vesper/{id}/control/ack` (replies + bus-wide broadcasts) — purpose-specific broadcasts moved to their own topics below |
|
||||||
|
| `vesper/{id}/status/heartbeat` | `vesper/{id}/status/heartbeat` (same topic, new field shape — see table above) |
|
||||||
|
| *(none — playback transitions were mixed into `data`)* | `vesper/{id}/status/playback` |
|
||||||
|
| *(none — bell overload etc. were mixed into `data`)* | `vesper/{id}/control/reports` |
|
||||||
|
| `vesper/{id}/status/alerts` | `vesper/{id}/system/alerts` |
|
||||||
|
| `vesper/{id}/status/info` | `vesper/{id}/system/info` |
|
||||||
|
| *(none)* | `vesper/{id}/system/logs` |
|
||||||
|
| *(none — diagnostics report was on `status/info`)* | `vesper/{id}/system/metrics` |
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
# Name, Type, SubType, Offset, Size, Flags
|
||||||
|
nvs, data, nvs, 0x9000, 0x5000,
|
||||||
|
otadata, data, ota, 0xe000, 0x2000,
|
||||||
|
app0, app, ota_0, 0x10000, 0x1F0000,
|
||||||
|
app1, app, ota_1, 0x200000,0x1F0000,
|
||||||
|
coredump, data, coredump,0x3F0000,0x10000,
|
||||||
|
+236
@@ -0,0 +1,236 @@
|
|||||||
|
; ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
; Project Vesper — PlatformIO Configuration
|
||||||
|
; ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
;
|
||||||
|
; Hardware Variants (active):
|
||||||
|
; vesper-v1 — Kincony KC868-A6 (ESP32-D0WD-V3, 4MB flash) — current production board
|
||||||
|
; agnus-v1 — ESP32 base, no SD card, NVS-only settings storage
|
||||||
|
; agnus-mini-v1 — Same binary as agnus-v1, output limit enforced via app/NVS
|
||||||
|
;
|
||||||
|
; Future variants (commented out):
|
||||||
|
; vesper-plus-v1 — Vesper+ with RF remote support
|
||||||
|
; vesper-pro-v1 — Vesper Pro with onboard LCD
|
||||||
|
;
|
||||||
|
; Each environment auto-includes its variant header via -include variants/<name>.hpp
|
||||||
|
; which defines HAS_SD_CARD, HAS_RTC, OUTPUT_COUNT_MAX, etc. for that build.
|
||||||
|
;
|
||||||
|
; Build: pio run -e vesper-v1
|
||||||
|
; Upload: pio run -e vesper-v1 --target upload --upload-port COM8
|
||||||
|
; Monitor: pio device monitor
|
||||||
|
; Clean: pio run -e vesper-v1 --target clean
|
||||||
|
; ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
; ───────────────────────────────────────────────────────────────────────────────
|
||||||
|
; SHARED SETTINGS — inherited by all environments
|
||||||
|
; ───────────────────────────────────────────────────────────────────────────────
|
||||||
|
[common]
|
||||||
|
platform = espressif32
|
||||||
|
framework = arduino
|
||||||
|
monitor_speed = 115200
|
||||||
|
|
||||||
|
; All external library dependencies
|
||||||
|
lib_deps =
|
||||||
|
; WiFi provisioning portal
|
||||||
|
tzapu/WiFiManager @ ^2.0.17
|
||||||
|
|
||||||
|
; Async web server + WebSocket support
|
||||||
|
; NOTE: Use the ESP32-compatible fork, not the original
|
||||||
|
https://github.com/me-no-dev/ESPAsyncWebServer.git
|
||||||
|
https://github.com/me-no-dev/AsyncTCP.git
|
||||||
|
|
||||||
|
; JSON parsing
|
||||||
|
bblanchon/ArduinoJson @ ^7.0.0
|
||||||
|
|
||||||
|
; I2C GPIO expanders (relay control) — PCF8575 header is bundled in same library
|
||||||
|
adafruit/Adafruit PCF8574 @ ^1.1.0
|
||||||
|
|
||||||
|
; Real-time clock
|
||||||
|
adafruit/RTClib @ ^2.1.4
|
||||||
|
|
||||||
|
; Async MQTT client
|
||||||
|
; NOTE: Requires AsyncTCP (already listed above)
|
||||||
|
https://github.com/marvinroger/async-mqtt-client.git
|
||||||
|
|
||||||
|
; RF remote receiver (433MHz, RCSwitch protocol)
|
||||||
|
sui77/rc-switch @ ^2.6.4
|
||||||
|
|
||||||
|
; Modbus RTU master (used by Rs485OutputManager for bespoke-rs485 build)
|
||||||
|
4-20ma/ModbusMaster @ ^2.0.1
|
||||||
|
|
||||||
|
build_flags_common =
|
||||||
|
-std=gnu++14
|
||||||
|
-DCORE_DEBUG_LEVEL=0
|
||||||
|
-DCONFIG_ASYNC_TCP_RUNNING_CORE=0
|
||||||
|
|
||||||
|
; ───────────────────────────────────────────────────────────────────────────────
|
||||||
|
; VESPER Standard v1 — Kincony KC868-A6 (ESP32-D0WD-V3, 4MB Flash)
|
||||||
|
; Current production board
|
||||||
|
; ───────────────────────────────────────────────────────────────────────────────
|
||||||
|
[env:vesper-std-v1]
|
||||||
|
platform = ${common.platform}
|
||||||
|
framework = ${common.framework}
|
||||||
|
board = esp32dev
|
||||||
|
|
||||||
|
; Serial monitor
|
||||||
|
monitor_speed = ${common.monitor_speed}
|
||||||
|
|
||||||
|
; Upload settings
|
||||||
|
upload_speed = 921600
|
||||||
|
upload_protocol = esptool
|
||||||
|
|
||||||
|
; Partition table — MUST match the layout already burned into field devices
|
||||||
|
; running the pre-restructure firmware (Arduino IDE PartitionScheme=no_fs).
|
||||||
|
; No spiffs partition — this firmware is SD-card only and never used SPIFFS.
|
||||||
|
; Using min_spiffs.csv here would move app1's offset (0x1F0000 vs 0x200000)
|
||||||
|
; and shrink both app slots, which OTA cannot safely migrate on its own —
|
||||||
|
; the currently-burned partition table on those devices has no entry at the
|
||||||
|
; new offset, so pushing a min_spiffs-built binary via OTA leaves the
|
||||||
|
; bootloader unable to find a valid image after the slot flip. See
|
||||||
|
; docs/features/feature-catalog.md F-059 for the full writeup.
|
||||||
|
board_build.partitions = no_fs.csv
|
||||||
|
|
||||||
|
; Upgrade to C++14 so std::make_unique is available
|
||||||
|
build_unflags = -std=gnu++11
|
||||||
|
|
||||||
|
; FreeRTOS timer service task stack — default 2048 is too small when timer callbacks
|
||||||
|
; do LOG formatting, MQTT connect(), NTP sync, etc. Increase to 4096.
|
||||||
|
board_build.cmake_extra_args = -DCONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=4096
|
||||||
|
|
||||||
|
; Build flags for this variant
|
||||||
|
; IMPORTANT: MQTT_SECRET must match the MQTT_SECRET in the backend .env file exactly.
|
||||||
|
; Do NOT commit the real secret value to git.
|
||||||
|
; To override locally without modifying this file, use a platformio.ini.local file:
|
||||||
|
; [env:vesper-v1]
|
||||||
|
; build_flags = ... -DMQTT_SECRET=\"your_actual_secret\"
|
||||||
|
build_flags =
|
||||||
|
${common.build_flags_common}
|
||||||
|
-DPSRAM_ENABLED=0
|
||||||
|
-DMQTT_SECRET=\"deea8b2dbf21872bff8b4639ca16d0348358945ccd4c1cb6c5934ba510de1dce\"
|
||||||
|
-include variants/vesper-std.hpp
|
||||||
|
|
||||||
|
lib_deps = ${common.lib_deps}
|
||||||
|
|
||||||
|
|
||||||
|
; ───────────────────────────────────────────────────────────────────────────────
|
||||||
|
; AGNUS v1 — No SD card, NVS-only settings storage
|
||||||
|
; Same ESP32 base as Vesper. Agnus Mini is the same binary — output limiting
|
||||||
|
; is handled in the app and NVS, not in firmware.
|
||||||
|
; ───────────────────────────────────────────────────────────────────────────────
|
||||||
|
[env:agnus-v1]
|
||||||
|
platform = ${common.platform}
|
||||||
|
framework = ${common.framework}
|
||||||
|
board = esp32dev
|
||||||
|
|
||||||
|
monitor_speed = ${common.monitor_speed}
|
||||||
|
upload_speed = 921600
|
||||||
|
upload_protocol = esptool
|
||||||
|
|
||||||
|
; Partition table — kept consistent with vesper-std-v1 (see that env's comment
|
||||||
|
; for the full rationale). No spiffs partition; SD-card only, no SPIFFS usage.
|
||||||
|
board_build.partitions = no_fs.csv
|
||||||
|
build_unflags = -std=gnu++11
|
||||||
|
board_build.cmake_extra_args = -DCONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=4096
|
||||||
|
|
||||||
|
build_flags =
|
||||||
|
${common.build_flags_common}
|
||||||
|
-DPSRAM_ENABLED=0
|
||||||
|
-DMQTT_SECRET=\"deea8b2dbf21872bff8b4639ca16d0348358945ccd4c1cb6c5934ba510de1dce\"
|
||||||
|
-include variants/agnus.hpp
|
||||||
|
|
||||||
|
lib_deps = ${common.lib_deps}
|
||||||
|
|
||||||
|
|
||||||
|
; ───────────────────────────────────────────────────────────────────────────────
|
||||||
|
; AGNUS MINI v1 — Same binary as agnus-v1, different NVS provisioning
|
||||||
|
; Output count is limited via the app and NVS key, not in firmware.
|
||||||
|
; Only exists as a separate env so OTA can target it independently.
|
||||||
|
; ───────────────────────────────────────────────────────────────────────────────
|
||||||
|
[env:agnus-mini-v1]
|
||||||
|
platform = ${common.platform}
|
||||||
|
framework = ${common.framework}
|
||||||
|
board = esp32dev
|
||||||
|
|
||||||
|
monitor_speed = ${common.monitor_speed}
|
||||||
|
upload_speed = 921600
|
||||||
|
upload_protocol = esptool
|
||||||
|
|
||||||
|
; Partition table — kept consistent with vesper-std-v1 (see that env's comment
|
||||||
|
; for the full rationale). No spiffs partition; SD-card only, no SPIFFS usage.
|
||||||
|
board_build.partitions = no_fs.csv
|
||||||
|
build_unflags = -std=gnu++11
|
||||||
|
board_build.cmake_extra_args = -DCONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=4096
|
||||||
|
|
||||||
|
build_flags =
|
||||||
|
${common.build_flags_common}
|
||||||
|
-DPSRAM_ENABLED=0
|
||||||
|
-DMQTT_SECRET=\"deea8b2dbf21872bff8b4639ca16d0348358945ccd4c1cb6c5934ba510de1dce\"
|
||||||
|
-include variants/agnus.hpp
|
||||||
|
|
||||||
|
lib_deps = ${common.lib_deps}
|
||||||
|
|
||||||
|
|
||||||
|
; ───────────────────────────────────────────────────────────────────────────────
|
||||||
|
; BESPOKE RS485 v1 — Vesper base board + Waveshare 16CH RS485 Modbus RTU relay
|
||||||
|
;
|
||||||
|
; One-off build for a single client requiring 16 outputs. The internal PCF8574
|
||||||
|
; relays on the KC868-A6 are NOT used. All outputs go through the Waveshare board
|
||||||
|
; via UART2 RS485 (GPIO27 TX, GPIO14 RX, MAX13487EESA auto-direction transceiver).
|
||||||
|
;
|
||||||
|
; OTA updates for this device must be built from THIS environment only.
|
||||||
|
; Other environments are unaffected — Rs485OutputManager is dead code for them
|
||||||
|
; since FEATURE_RS485 is not set.
|
||||||
|
; ───────────────────────────────────────────────────────────────────────────────
|
||||||
|
[env:bespoke-rs485-v1]
|
||||||
|
platform = ${common.platform}
|
||||||
|
framework = ${common.framework}
|
||||||
|
board = esp32dev
|
||||||
|
|
||||||
|
monitor_speed = ${common.monitor_speed}
|
||||||
|
upload_speed = 921600
|
||||||
|
upload_protocol = esptool
|
||||||
|
|
||||||
|
; Partition table — kept consistent with vesper-std-v1 (see that env's comment
|
||||||
|
; for the full rationale). No spiffs partition; SD-card only, no SPIFFS usage.
|
||||||
|
board_build.partitions = no_fs.csv
|
||||||
|
build_unflags = -std=gnu++11
|
||||||
|
board_build.cmake_extra_args = -DCONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=4096
|
||||||
|
|
||||||
|
build_flags =
|
||||||
|
${common.build_flags_common}
|
||||||
|
-DPSRAM_ENABLED=0
|
||||||
|
-DMQTT_SECRET=\"deea8b2dbf21872bff8b4639ca16d0348358945ccd4c1cb6c5934ba510de1dce\"
|
||||||
|
-include variants/bespoke_rs485.hpp
|
||||||
|
|
||||||
|
lib_deps = ${common.lib_deps}
|
||||||
|
|
||||||
|
|
||||||
|
; ───────────────────────────────────────────────────────────────────────────────
|
||||||
|
; VESPER+ v1 — Future: adds RF remote support
|
||||||
|
; ───────────────────────────────────────────────────────────────────────────────
|
||||||
|
; [env:vesper-plus-v1]
|
||||||
|
; platform = ${common.platform}
|
||||||
|
; framework = ${common.framework}
|
||||||
|
; board = esp32dev
|
||||||
|
; monitor_speed = ${common.monitor_speed}
|
||||||
|
; build_flags =
|
||||||
|
; ${common.build_flags_common}
|
||||||
|
; -DPSRAM_ENABLED=0
|
||||||
|
; -DMQTT_SECRET=\"change-me-in-platformio-ini\"
|
||||||
|
; -include variants/vesper.hpp
|
||||||
|
; lib_deps = ${common.lib_deps}
|
||||||
|
|
||||||
|
|
||||||
|
; ───────────────────────────────────────────────────────────────────────────────
|
||||||
|
; VESPER PRO v1 — Future: adds onboard LCD
|
||||||
|
; ───────────────────────────────────────────────────────────────────────────────
|
||||||
|
; [env:vesper-pro-v1]
|
||||||
|
; platform = ${common.platform}
|
||||||
|
; framework = ${common.framework}
|
||||||
|
; board = esp32dev
|
||||||
|
; monitor_speed = ${common.monitor_speed}
|
||||||
|
; build_flags =
|
||||||
|
; ${common.build_flags_common}
|
||||||
|
; -DPSRAM_ENABLED=0
|
||||||
|
; -DMQTT_SECRET=\"change-me-in-platformio-ini\"
|
||||||
|
; -include variants/vesper.hpp
|
||||||
|
; lib_deps = ${common.lib_deps}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
key,type,encoding,value
|
||||||
|
device_id,namespace,,
|
||||||
|
serial,data,string,AG000000000000
|
||||||
|
hw_family,data,string,agnus
|
||||||
|
hw_revision,data,string,01
|
||||||
|
@@ -0,0 +1,5 @@
|
|||||||
|
key,type,encoding,value
|
||||||
|
device_id,namespace,,
|
||||||
|
serial,data,string,PV000000000000
|
||||||
|
hw_family,data,string,vesper
|
||||||
|
hw_revision,data,string,01
|
||||||
|
@@ -22,6 +22,8 @@
|
|||||||
// DEPENDENCY INCLUDES - Required system components
|
// DEPENDENCY INCLUDES - Required system components
|
||||||
// ═════════════════════════════════════════════════════════════════════════════════
|
// ═════════════════════════════════════════════════════════════════════════════════
|
||||||
#include "BellEngine.hpp" // Header file with class definition
|
#include "BellEngine.hpp" // Header file with class definition
|
||||||
|
|
||||||
|
#define TAG "BellEngine"
|
||||||
#include "../Player/Player.hpp" // Melody playback controller
|
#include "../Player/Player.hpp" // Melody playback controller
|
||||||
#include "../ConfigManager/ConfigManager.hpp" // Configuration and settings
|
#include "../ConfigManager/ConfigManager.hpp" // Configuration and settings
|
||||||
#include "../Telemetry/Telemetry.hpp" // System monitoring and analytics
|
#include "../Telemetry/Telemetry.hpp" // System monitoring and analytics
|
||||||
@@ -74,7 +76,7 @@ BellEngine::~BellEngine() {
|
|||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
void BellEngine::begin() {
|
void BellEngine::begin() {
|
||||||
LOG_DEBUG("Initializing BellEngine with high-precision timing");
|
LOG_DEBUG(TAG, "Initializing BellEngine...");
|
||||||
|
|
||||||
// Create engine task with HIGHEST priority on dedicated Core 1
|
// Create engine task with HIGHEST priority on dedicated Core 1
|
||||||
// This ensures maximum performance and timing precision
|
// This ensures maximum performance and timing precision
|
||||||
@@ -88,7 +90,7 @@ void BellEngine::begin() {
|
|||||||
1 // 💻 Pin to Core 1 (dedicated)
|
1 // 💻 Pin to Core 1 (dedicated)
|
||||||
);
|
);
|
||||||
|
|
||||||
LOG_INFO("BellEngine initialized - Ready for MAXIMUM PRECISION! 🎯");
|
LOG_INFO(TAG, "BellEngine initialized !");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -96,7 +98,7 @@ void BellEngine::begin() {
|
|||||||
*/
|
*/
|
||||||
void BellEngine::setCommunicationManager(CommunicationRouter* commManager) {
|
void BellEngine::setCommunicationManager(CommunicationRouter* commManager) {
|
||||||
_communicationManager = commManager;
|
_communicationManager = commManager;
|
||||||
LOG_DEBUG("BellEngine: Communication manager %s",
|
LOG_DEBUG(TAG, "BellEngine: Communication manager %s",
|
||||||
commManager ? "connected" : "disconnected");
|
commManager ? "connected" : "disconnected");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,6 +106,10 @@ void BellEngine::setCommunicationManager(CommunicationRouter* commManager) {
|
|||||||
// ENGINE CONTROL IMPLEMENTATION (Thread-safe)
|
// ENGINE CONTROL IMPLEMENTATION (Thread-safe)
|
||||||
// ═════════════════════════════════════════════════════════════════════════════════
|
// ═════════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
bool BellEngine::areBellsEnabled() const {
|
||||||
|
return _configManager.getBellsEnabled();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Start the precision timing engine
|
* @brief Start the precision timing engine
|
||||||
*
|
*
|
||||||
@@ -114,24 +120,27 @@ void BellEngine::setCommunicationManager(CommunicationRouter* commManager) {
|
|||||||
* @note Will log error and return if no melody data is available
|
* @note Will log error and return if no melody data is available
|
||||||
*/
|
*/
|
||||||
void BellEngine::start() {
|
void BellEngine::start() {
|
||||||
// Validate that melody data is ready before starting
|
if (!_configManager.getBellsEnabled()) {
|
||||||
|
LOG_WARNING(TAG, "BellEngine: start() rejected — bell mechanism is disabled");
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (!_melodyDataReady.load()) {
|
if (!_melodyDataReady.load()) {
|
||||||
LOG_ERROR("Cannot start BellEngine: No melody data loaded");
|
LOG_ERROR(TAG, "Cannot start BellEngine: No melody data loaded");
|
||||||
return; // ⛔ Early exit if no melody data
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
LOG_INFO("🚀 BellEngine IGNITION - Starting precision playback");
|
LOG_INFO(TAG, "🚀 BellEngine Ignition - Starting precision playback");
|
||||||
_emergencyStop.store(false); // ✅ Clear any emergency stop state
|
_emergencyStop.store(false);
|
||||||
_engineRunning.store(true); // ✅ Activate the engine atomically
|
_engineRunning.store(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
void BellEngine::stop() {
|
void BellEngine::stop() {
|
||||||
LOG_INFO("BellEngine stopping gracefully");
|
LOG_INFO(TAG, "BellEngine - Stopping Gracefully");
|
||||||
_engineRunning.store(false);
|
_engineRunning.store(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
void BellEngine::emergencyStop() {
|
void BellEngine::emergencyStop() {
|
||||||
LOG_INFO("🛑 EMERGENCY STOP ACTIVATED");
|
LOG_INFO(TAG, "BellEngine - 🛑 Forcing Stop Immediately");
|
||||||
_emergencyStop.store(true);
|
_emergencyStop.store(true);
|
||||||
_engineRunning.store(false);
|
_engineRunning.store(false);
|
||||||
emergencyShutdown();
|
emergencyShutdown();
|
||||||
@@ -142,7 +151,7 @@ void BellEngine::setMelodyData(const std::vector<uint16_t>& melodySteps) {
|
|||||||
_melodySteps = melodySteps;
|
_melodySteps = melodySteps;
|
||||||
_melodyDataReady.store(true);
|
_melodyDataReady.store(true);
|
||||||
portEXIT_CRITICAL(&_melodyMutex);
|
portEXIT_CRITICAL(&_melodyMutex);
|
||||||
LOG_DEBUG("BellEngine loaded melody: %d steps", melodySteps.size());
|
LOG_DEBUG(TAG, "BellEngine - Loaded melody: %d steps", melodySteps.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
void BellEngine::clearMelodyData() {
|
void BellEngine::clearMelodyData() {
|
||||||
@@ -150,7 +159,7 @@ void BellEngine::clearMelodyData() {
|
|||||||
_melodySteps.clear();
|
_melodySteps.clear();
|
||||||
_melodyDataReady.store(false);
|
_melodyDataReady.store(false);
|
||||||
portEXIT_CRITICAL(&_melodyMutex);
|
portEXIT_CRITICAL(&_melodyMutex);
|
||||||
LOG_DEBUG("BellEngine melody data cleared");
|
LOG_DEBUG(TAG, "BellEngine - Melody data cleared");
|
||||||
}
|
}
|
||||||
|
|
||||||
// ================== CRITICAL TIMING SECTION ==================
|
// ================== CRITICAL TIMING SECTION ==================
|
||||||
@@ -158,7 +167,7 @@ void BellEngine::clearMelodyData() {
|
|||||||
|
|
||||||
void BellEngine::engineTask(void* parameter) {
|
void BellEngine::engineTask(void* parameter) {
|
||||||
BellEngine* engine = static_cast<BellEngine*>(parameter);
|
BellEngine* engine = static_cast<BellEngine*>(parameter);
|
||||||
LOG_DEBUG("🔥 BellEngine task started on Core %d with MAXIMUM priority", xPortGetCoreID());
|
LOG_DEBUG(TAG, "BellEngine - 🔥 Engine task started on Core %d with MAXIMUM priority", xPortGetCoreID());
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
if (engine->_engineRunning.load() && !engine->_emergencyStop.load()) {
|
if (engine->_engineRunning.load() && !engine->_emergencyStop.load()) {
|
||||||
@@ -186,7 +195,7 @@ void BellEngine::engineLoop() {
|
|||||||
|
|
||||||
// Pause handling AFTER complete loop - never interrupt mid-melody!
|
// Pause handling AFTER complete loop - never interrupt mid-melody!
|
||||||
while (_player.isPaused && _player.isPlaying && !_player.hardStop) {
|
while (_player.isPaused && _player.isPlaying && !_player.hardStop) {
|
||||||
LOG_DEBUG("⏸️ Pausing between melody loops");
|
LOG_VERBOSE(TAG, "BellEngine - ⏸️ Pausing between melody loops");
|
||||||
vTaskDelay(pdMS_TO_TICKS(10)); // Wait during pause
|
vTaskDelay(pdMS_TO_TICKS(10)); // Wait during pause
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -207,32 +216,44 @@ void BellEngine::playbackLoop() {
|
|||||||
portEXIT_CRITICAL(&_melodyMutex);
|
portEXIT_CRITICAL(&_melodyMutex);
|
||||||
|
|
||||||
if (melodySteps.empty()) {
|
if (melodySteps.empty()) {
|
||||||
LOG_ERROR("Empty melody in playback loop!");
|
LOG_ERROR(TAG, "BellEngine - ❌ Empty melody in playback loop!");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
LOG_DEBUG("🎵 Starting melody loop (%d steps)", melodySteps.size());
|
LOG_DEBUG(TAG, "BellEngine - 🎵 Starting melody loop (%d steps)", melodySteps.size());
|
||||||
|
|
||||||
// CRITICAL TIMING LOOP - Complete the entire melody without interruption
|
// CRITICAL TIMING LOOP - Complete the entire melody without interruption
|
||||||
for (uint16_t note : melodySteps) {
|
for (uint16_t note : melodySteps) {
|
||||||
// Emergency exit check (only emergency stops can interrupt mid-loop)
|
// Emergency exit check (only emergency stops can interrupt mid-loop)
|
||||||
if (_emergencyStop.load() || _player.hardStop) {
|
if (_emergencyStop.load() || _player.hardStop) {
|
||||||
LOG_DEBUG("Emergency exit from playback loop");
|
LOG_DEBUG(TAG, "BellEngine - Emergency exit from playback loop");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Activate note with MAXIMUM PRECISION
|
// Activate note with MAXIMUM PRECISION
|
||||||
activateNote(note);
|
activateNote(note);
|
||||||
|
|
||||||
// Precise timing delay
|
// Precise timing delay - validate speed to prevent division by zero
|
||||||
|
// I THINK this should be moved outside the Bell Engine
|
||||||
|
if (_player.speed == 0) {
|
||||||
|
LOG_ERROR(TAG, "BellEngine - ❌ Invalid Speed (0) detected, stopping playback");
|
||||||
|
_player.hardStop = true;
|
||||||
|
_engineRunning.store(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
uint32_t tempoMicros = _player.speed * 1000; // Convert ms to microseconds
|
uint32_t tempoMicros = _player.speed * 1000; // Convert ms to microseconds
|
||||||
preciseDelay(tempoMicros);
|
preciseDelay(tempoMicros);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mark segment completion and notify Player
|
// Mark segment completion and notify Player
|
||||||
_player.segmentCmpltTime = millis();
|
_player.segmentCmpltTime = millis();
|
||||||
_player.onMelodyLoopCompleted(); // 🔥 Notify Player that melody actually finished!
|
_player.onMelodyLoopCompleted(); // 🔥 Notify Player that melody actually finished!
|
||||||
LOG_DEBUG("🎵 Melody loop completed with PRECISION");
|
if ((_player.continuous_loop && _player.segment_duration == 0) || _player.total_duration == 0) {
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(500)); //Give Player time to pause/stop
|
||||||
|
LOG_VERBOSE(TAG, "BellEngine - Loop completed in SINGLE Mode - waiting for Player to handle pause/stop");
|
||||||
|
}
|
||||||
|
LOG_DEBUG(TAG, "BellEngine - 🎵 Melody loop completed with PRECISION");
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -256,26 +277,26 @@ void BellEngine::activateNote(uint16_t note) {
|
|||||||
|
|
||||||
// Additional safety check to prevent underflow crashes
|
// Additional safety check to prevent underflow crashes
|
||||||
if (bellIndex >= 255) {
|
if (bellIndex >= 255) {
|
||||||
LOG_ERROR("🚨 UNDERFLOW ERROR: bellIndex underflow for noteIndex %d", noteIndex);
|
LOG_ERROR(TAG, "BellEngine - 🚨 UNDERFLOW ERROR: bellIndex underflow for noteIndex %d", noteIndex);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bounds check (CRITICAL SAFETY)
|
// Bounds check (CRITICAL SAFETY)
|
||||||
if (bellIndex >= 16) {
|
if (bellIndex >= 16) {
|
||||||
LOG_ERROR("🚨 BOUNDS ERROR: bellIndex %d >= 16", bellIndex);
|
LOG_ERROR(TAG, "BellEngine - 🚨 BOUNDS ERROR: bellIndex %d >= 16", bellIndex);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for duplicate bell firing in this note
|
// Check for duplicate bell firing in this note
|
||||||
if (bellFired[bellIndex]) {
|
if (bellFired[bellIndex]) {
|
||||||
LOG_DEBUG("⚠️ DUPLICATE BELL: Skipping duplicate firing of bell %d for note %d", bellIndex, noteIndex);
|
LOG_DEBUG(TAG, "BellEngine - ⚠️ DUPLICATE BELL: Skipping duplicate firing of bell %d for note %d", bellIndex, noteIndex);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if bell is configured (OutputManager will validate this)
|
// Check if bell is configured (OutputManager will validate this)
|
||||||
uint8_t physicalOutput = _outputManager.getPhysicalOutput(bellIndex);
|
uint8_t physicalOutput = _outputManager.getPhysicalOutput(bellIndex);
|
||||||
if (physicalOutput == 255) {
|
if (physicalOutput == 255) {
|
||||||
LOG_DEBUG("⚠️ UNCONFIGURED: Bell %d not configured, skipping", bellIndex);
|
LOG_DEBUG(TAG, "BellEngine - ⚠️ UNCONFIGURED: Bell %d not configured, skipping", bellIndex);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -286,7 +307,7 @@ void BellEngine::activateNote(uint16_t note) {
|
|||||||
uint16_t durationMs = _configManager.getBellDuration(bellIndex);
|
uint16_t durationMs = _configManager.getBellDuration(bellIndex);
|
||||||
|
|
||||||
// Add to batch firing list
|
// Add to batch firing list
|
||||||
bellDurations.push_back({bellIndex, durationMs});
|
bellDurations.push_back({physicalOutput, durationMs});
|
||||||
|
|
||||||
// Add to notification list (convert to 1-indexed for display)
|
// Add to notification list (convert to 1-indexed for display)
|
||||||
firedBellIndices.push_back(bellIndex + 1);
|
firedBellIndices.push_back(bellIndex + 1);
|
||||||
@@ -294,17 +315,14 @@ void BellEngine::activateNote(uint16_t note) {
|
|||||||
// Record telemetry
|
// Record telemetry
|
||||||
_telemetry.recordBellStrike(bellIndex);
|
_telemetry.recordBellStrike(bellIndex);
|
||||||
|
|
||||||
LOG_VERBOSE("🔨 STRIKE! Note:%d → Bell:%d for %dms", noteIndex, bellIndex, durationMs);
|
LOG_VERBOSE(TAG, "BellEngine - 🔨 STRIKE! Note:%d → Bell:%d for %dms", noteIndex, bellIndex, durationMs);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 🚀 FIRE ALL BELLS SIMULTANEOUSLY!
|
// 🚀 FIRE ALL BELLS SIMULTANEOUSLY!
|
||||||
if (!bellDurations.empty()) {
|
if (!bellDurations.empty()) {
|
||||||
_outputManager.fireOutputsBatchForDuration(bellDurations);
|
_outputManager.fireOutputsBatchForDuration(bellDurations);
|
||||||
LOG_VERBOSE("🔥🔥 BATCH FIRED %d bells SIMULTANEOUSLY!", bellDurations.size());
|
LOG_VERBOSE(TAG, "BellEngine - 🔥 Batch Fired %d bells Simultaneously !", bellDurations.size());
|
||||||
|
|
||||||
// 🔔 NOTIFY WEBSOCKET CLIENTS OF BELL DINGS!
|
|
||||||
notifyBellsFired(firedBellIndices);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -326,38 +344,10 @@ void BellEngine::preciseDelay(uint32_t microseconds) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void BellEngine::emergencyShutdown() {
|
void BellEngine::emergencyShutdown() {
|
||||||
LOG_INFO("🚨 EMERGENCY SHUTDOWN - Using OutputManager");
|
LOG_INFO(TAG, "BellEngine - 🚨 Emergency Shutdown - Notifying OutputManager");
|
||||||
_outputManager.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("🔔 DING notification sent for %d bells", bellIndices.size());
|
|
||||||
|
|
||||||
} catch (...) {
|
|
||||||
LOG_ERROR("Failed to send ding notification");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ════════════════════════════════════════════════════════════════════════════
|
// ════════════════════════════════════════════════════════════════════════════
|
||||||
// HEALTH CHECK IMPLEMENTATION
|
// HEALTH CHECK IMPLEMENTATION
|
||||||
// ════════════════════════════════════════════════════════════════════════════
|
// ════════════════════════════════════════════════════════════════════════════
|
||||||
@@ -365,20 +355,20 @@ void BellEngine::notifyBellsFired(const std::vector<uint8_t>& bellIndices) {
|
|||||||
bool BellEngine::isHealthy() const {
|
bool BellEngine::isHealthy() const {
|
||||||
// Check if engine task is created and running
|
// Check if engine task is created and running
|
||||||
if (_engineTaskHandle == NULL) {
|
if (_engineTaskHandle == NULL) {
|
||||||
LOG_DEBUG("BellEngine: Unhealthy - Task not created");
|
LOG_DEBUG(TAG, "BellEngine: Unhealthy - Task not created");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if task is still alive
|
// Check if task is still alive
|
||||||
eTaskState taskState = eTaskGetState(_engineTaskHandle);
|
eTaskState taskState = eTaskGetState(_engineTaskHandle);
|
||||||
if (taskState == eDeleted || taskState == eInvalid) {
|
if (taskState == eDeleted || taskState == eInvalid) {
|
||||||
LOG_DEBUG("BellEngine: Unhealthy - Task deleted or invalid");
|
LOG_DEBUG(TAG, "BellEngine: Unhealthy - Task deleted or invalid");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if OutputManager is properly connected and healthy
|
// Check if OutputManager is properly connected and healthy
|
||||||
if (!_outputManager.isInitialized()) {
|
if (!_outputManager.isInitialized()) {
|
||||||
LOG_DEBUG("BellEngine: Unhealthy - OutputManager not initialized");
|
LOG_DEBUG(TAG, "BellEngine: Unhealthy - OutputManager not initialized");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -205,6 +205,13 @@ public:
|
|||||||
*/
|
*/
|
||||||
bool isEmergencyStopped() const { return _emergencyStop.load(); }
|
bool isEmergencyStopped() const { return _emergencyStop.load(); }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Whether the bell mechanism master switch (bells.enable/disable) allows playback.
|
||||||
|
* start() refuses to run while this is false — Player checks it up front so a
|
||||||
|
* play command can be rejected with a reason instead of "playing" silently.
|
||||||
|
*/
|
||||||
|
bool areBellsEnabled() const;
|
||||||
|
|
||||||
// ═══════════════════════════════════════════════════════════════════════════════
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
// PERFORMANCE MONITORING
|
// PERFORMANCE MONITORING
|
||||||
// ═══════════════════════════════════════════════════════════════════════════════
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
@@ -357,13 +364,6 @@ private:
|
|||||||
*/
|
*/
|
||||||
void checkAndNotifyOverloads();
|
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);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
# BellEngine
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
BellEngine is the real-time bell activation core of the Vesper firmware. It receives compiled melody data from `Player` and fires physical relay outputs through `OutputManager` with microsecond-precision inter-note timing. The engine runs permanently on a dedicated FreeRTOS task (priority 6, Core 1, 12 KB stack) that spins idle between plays; when `start()` is called, it executes the full melody step-by-step without interruption, applying a hybrid vTaskDelay + busy-wait strategy to hit sub-millisecond timing accuracy. BellEngine exists as a separate subsystem so that all hardware-agnostic timing logic is isolated from both the higher-level playback policy (owned by `Player`) and the hardware abstraction (owned by `OutputManager`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Public API
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `BellEngine(Player&, ConfigManager&, Telemetry&, OutputManager&)` | Constructor. All four references must remain valid for the object lifetime. `CommunicationRouter` is injected separately via `setCommunicationManager()`. |
|
||||||
|
| `void begin()` | Creates the FreeRTOS engine task. Must be called once before `start()`. Does **not** start playback. |
|
||||||
|
| `void setCommunicationManager(CommunicationRouter*)` | Wires the optional communication reference used for overload notifications. May be called at any time before or after `begin()`. Pass `nullptr` to disconnect. |
|
||||||
|
| `void setMelodyData(const std::vector<uint16_t>&)` | Copies melody step data into the engine under a critical section. Each `uint16_t` is a bitmask: bit N set means note-slot N fires on this step. Must be called before `start()`. |
|
||||||
|
| `void clearMelodyData()` | Clears melody data and marks the engine as not ready. Thread-safe. |
|
||||||
|
| `void start()` | Signals the engine task to begin playback. No-op (with error log) if no melody data is loaded. |
|
||||||
|
| `void stop()` | Graceful stop — sets the `_engineRunning` flag; the engine halts after the current inter-note delay. Does not cut mid-note relay pulses. |
|
||||||
|
| `void emergencyStop()` | Immediate stop. Sets both `_emergencyStop` and `_engineRunning` flags and calls `emergencyShutdown()` to de-energize all relays via `OutputManager`. |
|
||||||
|
| `bool isRunning() const` | Returns `true` if the engine is actively executing a melody. Atomic read. |
|
||||||
|
| `bool isEmergencyStopped() const` | Returns `true` if an emergency stop is in effect. Atomic read. |
|
||||||
|
| `uint32_t getMaxLoopTime() const` | Returns the worst-case engine loop execution time in microseconds, for performance diagnostics. |
|
||||||
|
| `bool isHealthy() const` | Returns `true` if the engine task handle is valid, the task state is neither deleted nor invalid, and `OutputManager::isInitialized()` is true. Used by `HealthMonitor`. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Initialization
|
||||||
|
|
||||||
|
BellEngine depends on `OutputManager` being initialized before `begin()` is called. In `main.cpp`, the sequence is:
|
||||||
|
|
||||||
|
```
|
||||||
|
outputManager.initialize() // OutputManager must be ready first
|
||||||
|
bellEngine.begin() // Creates engine task; task waits idle
|
||||||
|
healthMonitor.setBellEngine(&bellEngine)
|
||||||
|
// ... other subsystems ...
|
||||||
|
player.setBellEngine(&bellEngine)
|
||||||
|
bellEngine.setCommunicationManager(&communication)
|
||||||
|
```
|
||||||
|
|
||||||
|
`begin()` is called early (before networking and communication) so that `HealthMonitor` and `FirmwareValidator` can include BellEngine in startup validation. The engine task itself remains idle at this stage — it does nothing until `Player` loads melody data and calls `start()`.
|
||||||
|
|
||||||
|
Typical playback sequence (driven by `Player`):
|
||||||
|
|
||||||
|
1. `Player::loadMelodyInRAM()` — loads melody steps from SD into RAM.
|
||||||
|
2. `bellEngine.setMelodyData(steps)` — copies steps into BellEngine.
|
||||||
|
3. `bellEngine.start()` — sets `_engineRunning = true`.
|
||||||
|
4. Engine task calls `playbackLoop()`, iterates steps, fires relays via `OutputManager::fireOutputsBatchForDuration()`, applies `preciseDelay()` between steps.
|
||||||
|
5. On final step: `player.onMelodyLoopCompleted()` is called so Player can handle looping, pausing, or stopping.
|
||||||
|
6. `Player` calls `bellEngine.stop()` or `bellEngine.emergencyStop()` when done.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
| Dependency | Role |
|
||||||
|
|------------|------|
|
||||||
|
| `Player` | Provides `isPlaying`, `isPaused`, `hardStop`, `speed`, `noteAssignments`, and the `onMelodyLoopCompleted()` callback. BellEngine reads these public fields directly — no locking around them. |
|
||||||
|
| `ConfigManager` | Supplies per-bell relay duration (`getBellDuration(bellIndex)`) used when firing a note. |
|
||||||
|
| `OutputManager` | Hardware abstraction. `fireOutputsBatchForDuration()` fires one or more relays simultaneously; `getPhysicalOutput()` maps logical bell index to physical pin; `emergencyShutdown()` de-energizes everything. |
|
||||||
|
| `Telemetry` | `recordBellStrike(bellIndex)` is called on every activation. `getBellLoad()` and `isOverloaded()` are queried after each full melody loop to detect overload conditions. |
|
||||||
|
| `CommunicationRouter` (optional) | `sendBellOverloadNotification()` is called when load thresholds are exceeded. |
|
||||||
|
| FreeRTOS | Task, critical section (`portMUX_TYPE`), and `vTaskDelay` APIs. |
|
||||||
|
| `esp_timer` | `esp_timer_get_time()` provides the microsecond timestamp used by `preciseDelay()` and performance tracking. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Gotchas / Notes
|
||||||
|
|
||||||
|
**Thread safety model.** Engine state (`_engineRunning`, `_emergencyStop`, `_melodyDataReady`) uses `std::atomic<bool>` — safe to read/write from any task. Melody step data (`_melodySteps`) is guarded by a `portMUX_TYPE` spinlock via `portENTER_CRITICAL` / `portEXIT_CRITICAL`. The engine makes a local copy of `_melodySteps` at the start of each playback pass, so late calls to `setMelodyData()` do not affect an in-progress play.
|
||||||
|
|
||||||
|
**Player state is read without locks.** `playbackLoop()` reads `_player.isPlaying`, `_player.hardStop`, `_player.isPaused`, and `_player.speed` directly as plain public members. These are written only from Core 0 tasks; the implicit memory ordering from `atomic` flag checks provides adequate coordination in practice, but this is a weak coupling point.
|
||||||
|
|
||||||
|
**Timing strategy.** `preciseDelay(us)` uses `vTaskDelay` for the bulk of a delay (leaving a 500 µs margin) and then busy-waits for the remainder. This means Core 1 will spin-wait for up to 500 µs per note step. At typical bell speeds (≥ 100 ms per beat) the busy-wait fraction is negligible, but it will starve any other Core 1 work during that window.
|
||||||
|
|
||||||
|
**Core 1 is dedicated.** The engine task is pinned to Core 1 at priority 6. No other application task should be pinned to Core 1 at equal or higher priority, or timing jitter will increase.
|
||||||
|
|
||||||
|
**Stack size.** The engine task allocates 12 KB. The `activateNote()` path allocates two `std::vector` objects and a fixed 16-element `bool` array on the stack per note step; this is the dominant stack consumer.
|
||||||
|
|
||||||
|
**`notifyBellsFired()` has been removed.** The per-bell ding notification (previously sent to WebSocket clients only) was unstable under load and had no consumers. The function and its call site have been deleted. Bell activity is visible to external systems via telemetry strike counts and health monitor alerts only.
|
||||||
|
|
||||||
|
**`_precisionTimer` is unused.** The `esp_timer_handle_t _precisionTimer` field is allocated but never started. It is vestigial from an earlier design iteration.
|
||||||
|
|
||||||
|
**Overload thresholds are hardcoded.** `checkAndNotifyOverloads()` uses fixed values of 54 (critical, ~90% of 60 strikes/min) and 36 (warning, ~60%) rather than reading per-bell maximums from config. This should be parameterized if bell load limits become configurable.
|
||||||
|
|
||||||
|
**Emergency stop in destructor.** `~BellEngine()` calls `emergencyShutdown()`, which in turn calls `OutputManager::emergencyShutdown()`. If `OutputManager` has already been destroyed before `BellEngine`, this will be a use-after-free. Ensure destruction order in `main.cpp` is consistent with construction order (BellEngine before OutputManager).
|
||||||
@@ -0,0 +1,619 @@
|
|||||||
|
/*
|
||||||
|
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||||
|
* BUILTINMELODIES.HPP - Firmware-Baked Melody Library
|
||||||
|
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||||
|
*
|
||||||
|
* 🎵 BUILT-IN MELODY LIBRARY FOR VESPER 🎵
|
||||||
|
*
|
||||||
|
* This file contains melodies baked directly into the firmware, eliminating
|
||||||
|
* the need for SD card downloads. Each melody is stored in PROGMEM to save RAM.
|
||||||
|
*
|
||||||
|
* 🏗️ ARCHITECTURE:
|
||||||
|
* • Melodies stored in PROGMEM (Flash memory, not RAM)
|
||||||
|
* • Each melody step is 2 bytes (uint16_t bitmask)
|
||||||
|
* • Metadata includes name, UID, default speed
|
||||||
|
* • Easy to add new melodies
|
||||||
|
*
|
||||||
|
* 📦 STORAGE EFFICIENCY:
|
||||||
|
* • Small melodies (~30 steps = 60 bytes)
|
||||||
|
* • Large melodies (~200 steps = 400 bytes)
|
||||||
|
* • 40 melodies average = ~6-10KB total (Flash, not RAM!)
|
||||||
|
*
|
||||||
|
* 🎶 MELODY FORMAT:
|
||||||
|
* Each uint16_t is a bitmask:
|
||||||
|
* - Bit 0-15: Which bells/notes to activate
|
||||||
|
* - Example: 0x0001 = Bell 0, 0x0003 = Bells 0+1, 0x8000 = Bell 15
|
||||||
|
*
|
||||||
|
* 📋 VERSION: 1.1
|
||||||
|
* 📅 DATE: 2026-03-19
|
||||||
|
* 👨💻 AUTHOR: bonamin
|
||||||
|
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <vector>
|
||||||
|
#include <pgmspace.h>
|
||||||
|
|
||||||
|
namespace BuiltInMelodies {
|
||||||
|
|
||||||
|
// ═════════════════════════════════════════════════════════════════════════════════
|
||||||
|
// MELODY METADATA STRUCTURE
|
||||||
|
// ═════════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
struct MelodyInfo {
|
||||||
|
const char* name; // Display name
|
||||||
|
const char* pid; // Playback ID
|
||||||
|
const uint16_t* data; // Pointer to melody data in PROGMEM
|
||||||
|
uint16_t stepCount; // Number of steps
|
||||||
|
};
|
||||||
|
|
||||||
|
// ═════════════════════════════════════════════════════════════════════════════════
|
||||||
|
// BuiltIn Melodies // More can be added here
|
||||||
|
// ═════════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
// 1 Bell Test Melody
|
||||||
|
const uint16_t PROGMEM one_bell_test[] = {
|
||||||
|
0x0001, 0x0000, 0x0001, 0x0000
|
||||||
|
};
|
||||||
|
|
||||||
|
// Generated: 2026-03-16 08:57:17
|
||||||
|
|
||||||
|
// Melody: Ormilia 1,2,3,4,5,6,7,8
|
||||||
|
const uint16_t PROGMEM ormilia_1_8[] = {
|
||||||
|
0x0002, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001,
|
||||||
|
0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0002, 0x0009, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0002, 0x0005, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0002, 0x0009, 0x0000, 0x0001, 0x0002, 0x0005, 0x0000, 0x0001,
|
||||||
|
0x0002, 0x0009, 0x0000, 0x0001, 0x0002, 0x0005, 0x0000, 0x0001,
|
||||||
|
0x0002, 0x0011, 0x0002, 0x0001, 0x0002, 0x0021, 0x0002, 0x0001,
|
||||||
|
0x0002, 0x0011, 0x0002, 0x0001, 0x0002, 0x0021, 0x0002, 0x0041,
|
||||||
|
0x0002, 0x0081, 0x0002, 0x0009, 0x0002, 0x0041, 0x0002, 0x0081,
|
||||||
|
0x0002, 0x0009, 0x0002, 0x0041, 0x0002, 0x0081, 0x0002, 0x0005,
|
||||||
|
0x0002, 0x0001, 0x0000
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: Festal 1,2,3,4,5
|
||||||
|
const uint16_t PROGMEM festive_1_8[] = {
|
||||||
|
0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: Festive Chord 1,2,3,4,5
|
||||||
|
const uint16_t PROGMEM festive_alt_5[] = {
|
||||||
|
0x0004, 0x0002, 0x0008, 0x0001, 0x0004, 0x0004, 0x0002, 0x0008,
|
||||||
|
0x0001, 0x0010, 0x0004, 0x0002, 0x0008, 0x0001, 0x0004, 0x0004,
|
||||||
|
0x0002, 0x0008, 0x0001, 0x0011, 0x0004, 0x0002, 0x0008, 0x0001,
|
||||||
|
0x0004, 0x0004, 0x0002, 0x0008, 0x0001, 0x0011, 0x0004, 0x0002,
|
||||||
|
0x0008, 0x0001, 0x0005, 0x0004, 0x0002, 0x0008, 0x0001, 0x0011,
|
||||||
|
0x0004, 0x0002, 0x0008, 0x0001, 0x0005, 0x0004, 0x0002, 0x0008,
|
||||||
|
0x0001, 0x0011, 0x0004, 0x0002, 0x0008, 0x0001, 0x0004, 0x0004,
|
||||||
|
0x0002, 0x0008, 0x0001, 0x0010, 0x0004, 0x0002, 0x0008, 0x0001,
|
||||||
|
0x0004, 0x0004, 0x0002, 0x0008, 0x0001, 0x0010
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: Festive 1,2,3,4,5,6
|
||||||
|
const uint16_t PROGMEM festive_6[] = {
|
||||||
|
0x0001, 0x0002, 0x0004, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
|
||||||
|
0x0008, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0004, 0x0002,
|
||||||
|
0x0001, 0x0002, 0x0001, 0x0002, 0x0010, 0x0002, 0x0001, 0x0002,
|
||||||
|
0x0001, 0x0002, 0x0009, 0x0002, 0x0001, 0x0002, 0x0011, 0x0002,
|
||||||
|
0x0001, 0x0002, 0x0005, 0x0002, 0x0001, 0x0002, 0x0021, 0x0002,
|
||||||
|
0x0001, 0x0002, 0x0009, 0x0002, 0x0001, 0x0002, 0x0011, 0x0002,
|
||||||
|
0x0001, 0x0002, 0x0005, 0x0002, 0x0001, 0x0002, 0x0021, 0x0002,
|
||||||
|
0x0001, 0x0002, 0x0009, 0x0002, 0x0001, 0x0002, 0x0011, 0x0002,
|
||||||
|
0x0001, 0x0002, 0x0005, 0x0002, 0x0001, 0x0002, 0x0021, 0x0002,
|
||||||
|
0x0001, 0x0002
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: Festive 1,2,3,4,5
|
||||||
|
const uint16_t PROGMEM festive_5[] = {
|
||||||
|
0x0001, 0x0002, 0x0004, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
|
||||||
|
0x0008, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0004, 0x0002,
|
||||||
|
0x0001, 0x0002, 0x0001, 0x0002, 0x0010, 0x0002, 0x0001, 0x0002
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: Festive 1,2,3,4
|
||||||
|
const uint16_t PROGMEM festive_2_4[] = {
|
||||||
|
0x0001, 0x0002, 0x0004, 0x0009, 0x0002, 0x0001, 0x0004, 0x0009
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: Festive 1
|
||||||
|
const uint16_t PROGMEM festive_1[] = {
|
||||||
|
0x0001, 0x0001, 0x0001, 0x0000, 0x0001, 0x0001, 0x0001, 0x0001,
|
||||||
|
0x0000, 0x0001, 0x0000, 0x0001, 0x0001, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0000, 0x0001, 0x0000
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: One By One 1,2,3,4,5,6,7,8
|
||||||
|
const uint16_t PROGMEM onebyone_4_8[] = {
|
||||||
|
0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000,
|
||||||
|
0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000,
|
||||||
|
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
|
||||||
|
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
|
||||||
|
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
|
||||||
|
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
|
||||||
|
0x0002, 0x0004, 0x0008, 0x0004, 0x0002, 0x0011, 0x0002, 0x0004,
|
||||||
|
0x0008, 0x0004, 0x0002, 0x0021, 0x0002, 0x0004, 0x0008, 0x0004,
|
||||||
|
0x0002, 0x0041, 0x0002, 0x0004, 0x0008, 0x0004, 0x0002, 0x0081,
|
||||||
|
0x0002, 0x0004, 0x0008, 0x0004, 0x0002, 0x0041, 0x0002, 0x0004,
|
||||||
|
0x0008, 0x0004, 0x0002, 0x0021, 0x0002, 0x0004, 0x0008, 0x0004,
|
||||||
|
0x0002, 0x0041, 0x0002, 0x0004, 0x0008, 0x0004, 0x0002, 0x0081,
|
||||||
|
0x0002, 0x0004, 0x0008, 0x0004, 0x0002, 0x0041, 0x0002, 0x0004,
|
||||||
|
0x0008, 0x0004, 0x0002, 0x0021, 0x0002, 0x0004, 0x0008, 0x0004,
|
||||||
|
0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001,
|
||||||
|
0x0004, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001,
|
||||||
|
0x0004, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0000
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: One By One 1,2,3
|
||||||
|
const uint16_t PROGMEM onebyone_2_3[] = {
|
||||||
|
0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000,
|
||||||
|
0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000,
|
||||||
|
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
|
||||||
|
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
|
||||||
|
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
|
||||||
|
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
|
||||||
|
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
|
||||||
|
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
|
||||||
|
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
|
||||||
|
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
|
||||||
|
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
|
||||||
|
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: Athonite Extended 1,2,3,4,5,6,7,8
|
||||||
|
const uint16_t PROGMEM athonite_4_8[] = {
|
||||||
|
0x0002, 0x0001, 0x0000, 0x0000, 0x0002, 0x0001, 0x0000, 0x0000,
|
||||||
|
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0000, 0x0005,
|
||||||
|
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0002, 0x0005,
|
||||||
|
0x0002, 0x0001, 0x0008, 0x0005, 0x0002, 0x0001, 0x0000, 0x0005,
|
||||||
|
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0002, 0x0005,
|
||||||
|
0x0002, 0x0001, 0x0009, 0x0002, 0x0001, 0x0011, 0x0002, 0x0001,
|
||||||
|
0x0022, 0x0002, 0x0001, 0x0081, 0x0002, 0x0001, 0x000A, 0x0002,
|
||||||
|
0x0001, 0x0041, 0x0002, 0x0001, 0x0012, 0x0002, 0x0001, 0x0021,
|
||||||
|
0x0002, 0x0001, 0x0082, 0x0002, 0x0001, 0x0009, 0x0002, 0x0001,
|
||||||
|
0x0042, 0x0002, 0x0001, 0x0011, 0x0002, 0x0001, 0x0022, 0x0002,
|
||||||
|
0x0001, 0x0081, 0x0002, 0x0001, 0x000A, 0x0002, 0x0001, 0x0041,
|
||||||
|
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0000, 0x0005,
|
||||||
|
0x0002, 0x0001, 0x0002, 0x0005, 0x0002, 0x0001, 0x0000, 0x0000,
|
||||||
|
0x0000
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: Athonite Extended 1,2,3,4
|
||||||
|
const uint16_t PROGMEM athonite_3_4[] = {
|
||||||
|
0x0002, 0x0001, 0x0000, 0x0000, 0x0002, 0x0001, 0x0000, 0x0000,
|
||||||
|
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0000, 0x0005,
|
||||||
|
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0002, 0x0005,
|
||||||
|
0x0002, 0x0001, 0x0008, 0x0005, 0x0002, 0x0001, 0x0000, 0x0005,
|
||||||
|
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0002, 0x0005,
|
||||||
|
0x0002, 0x0001, 0x0009, 0x0002, 0x0001, 0x0005, 0x0002, 0x0001,
|
||||||
|
0x000A, 0x0002, 0x0001, 0x0006, 0x0002, 0x0001, 0x0009, 0x0002,
|
||||||
|
0x0001, 0x0005, 0x0002, 0x0001, 0x000A, 0x0002, 0x0001, 0x0006,
|
||||||
|
0x0002, 0x0001, 0x0009
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: Athonite 1,2,3
|
||||||
|
const uint16_t PROGMEM athonite_3[] = {
|
||||||
|
0x0002, 0x0001, 0x0000, 0x0000, 0x0002, 0x0001, 0x0000, 0x0000,
|
||||||
|
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
|
||||||
|
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: Athonite 2
|
||||||
|
const uint16_t PROGMEM athonite_1_2[] = {
|
||||||
|
0x0001, 0x0002, 0x0001, 0x0001, 0x0002, 0x0001, 0x0001, 0x0002,
|
||||||
|
0x0001, 0x0001, 0x0002, 0x0001, 0x0002
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: Talanto 1,2,3,4
|
||||||
|
const uint16_t PROGMEM talanto_1_4[] = {
|
||||||
|
0x0001, 0x0001, 0x0001, 0x0002, 0x0001, 0x0001, 0x0001, 0x0008,
|
||||||
|
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0001, 0x0001, 0x0008
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: Semantron 1,2,3,4
|
||||||
|
const uint16_t PROGMEM semantron_1_4[] = {
|
||||||
|
0x0001, 0x0001, 0x0001, 0x0002, 0x0001, 0x0001, 0x0001, 0x0008,
|
||||||
|
0x0001, 0x0001, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0008
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: Toll Great Friday 1,2,3,4
|
||||||
|
const uint16_t PROGMEM mournfull_gf_1_4[] = {
|
||||||
|
0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001,
|
||||||
|
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0001,
|
||||||
|
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0004, 0x0000,
|
||||||
|
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0004, 0x0000, 0x0000,
|
||||||
|
0x0000, 0x0000, 0x0000, 0x0000, 0x0004, 0x0004, 0x0000, 0x0000,
|
||||||
|
0x0000, 0x0000, 0x0000, 0x0000, 0x0002, 0x0000, 0x0000, 0x0000,
|
||||||
|
0x0000, 0x0000, 0x0000, 0x0002, 0x0000, 0x0000, 0x0000, 0x0000,
|
||||||
|
0x0000, 0x0000, 0x0002, 0x0002, 0x0000, 0x0000, 0x0000, 0x0000,
|
||||||
|
0x0000, 0x0000, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
|
||||||
|
0x0000, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
|
||||||
|
0x0008, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: Mournfull Toll 1,2,3,4
|
||||||
|
const uint16_t PROGMEM mournfull_1_4[] = {
|
||||||
|
0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001,
|
||||||
|
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0004, 0x0000,
|
||||||
|
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0004, 0x0000, 0x0000,
|
||||||
|
0x0000, 0x0000, 0x0000, 0x0000, 0x0002, 0x0000, 0x0000, 0x0000,
|
||||||
|
0x0000, 0x0000, 0x0000, 0x0002, 0x0000, 0x0000, 0x0000, 0x0000,
|
||||||
|
0x0000, 0x0000, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
|
||||||
|
0x0000, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: Orthros Festive 1,2,3
|
||||||
|
const uint16_t PROGMEM orthros_fst_1_3[] = {
|
||||||
|
0x0001, 0x0000, 0x0002, 0x0001, 0x0000, 0x0002, 0x0000, 0x0001,
|
||||||
|
0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0004, 0x0000
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: Orthros 2,1
|
||||||
|
const uint16_t PROGMEM orthros_1_8[] = {
|
||||||
|
0x0001, 0x0000, 0x0002, 0x0000, 0x0004, 0x0008, 0x0000, 0x0010,
|
||||||
|
0x0000, 0x0020, 0x0000, 0x0040, 0x0080, 0x0000
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: Catechetical 1,2,3
|
||||||
|
const uint16_t PROGMEM catechetical_1_5[] = {
|
||||||
|
0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0000
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: Vesper Festive 1,2,3,4
|
||||||
|
const uint16_t PROGMEM vesper_fst_1_4[] = {
|
||||||
|
0x0001, 0x0002, 0x0000, 0x0000, 0x0001, 0x0002, 0x0000, 0x0000,
|
||||||
|
0x0001, 0x0004, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
|
||||||
|
0x0001, 0x0002, 0x0000, 0x0000, 0x0001, 0x0002, 0x0000, 0x0000,
|
||||||
|
0x0001, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
|
||||||
|
0x0001, 0x0002, 0x0000, 0x0000, 0x0001, 0x0002, 0x0000, 0x0000,
|
||||||
|
0x0001, 0x0002, 0x0000, 0x0000, 0x0001, 0x0002, 0x0000, 0x0000,
|
||||||
|
0x0001, 0x0002, 0x0000, 0x0000, 0x0001, 0x0004, 0x0000, 0x0000,
|
||||||
|
0x0001, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: Vesper 1,2,3
|
||||||
|
const uint16_t PROGMEM vesper_1_3[] = {
|
||||||
|
0x0001, 0x0002, 0x0004, 0x0000, 0x0001, 0x0002, 0x0004, 0x0000,
|
||||||
|
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0004, 0x0000
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: Doxology Festive 1,2,3,4,5,6
|
||||||
|
const uint16_t PROGMEM doxology_fst_1_6[] = {
|
||||||
|
0x0002, 0x0004, 0x0009, 0x0004, 0x0002, 0x0004, 0x0011, 0x0004,
|
||||||
|
0x0002, 0x0004, 0x0021, 0x0004, 0x0002, 0x0004, 0x0011, 0x0004
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: Doxology Alternative 1,2,3,4,5
|
||||||
|
const uint16_t PROGMEM doxology_alt_1_5[] = {
|
||||||
|
0x0001, 0x0000, 0x0002, 0x0004, 0x0000, 0x0018, 0x0000, 0x0001,
|
||||||
|
0x0000, 0x0002, 0x0004, 0x0000, 0x0018, 0x0000, 0x0001, 0x0000,
|
||||||
|
0x0002, 0x0004, 0x0000, 0x0018, 0x0000, 0x0001, 0x0002, 0x0001,
|
||||||
|
0x0002, 0x0004, 0x0000, 0x0018, 0x0000
|
||||||
|
};
|
||||||
|
|
||||||
|
// Melody: Doxology 1,2,3,4
|
||||||
|
const uint16_t PROGMEM doxology_1_4[] = {
|
||||||
|
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0000, 0x0000,
|
||||||
|
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0008, 0x0000, 0x0000,
|
||||||
|
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
|
||||||
|
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0008, 0x0000, 0x0000
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
// ═════════════════════════════════════════════════════════════════════════════════
|
||||||
|
// PROGMEM for builtin_* UIDs that have no identical current array
|
||||||
|
// ═════════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
// builtin_catehetical: same as catechetical_1_5 but without trailing 0x0000
|
||||||
|
const uint16_t PROGMEM builtin_catehetical[] = {
|
||||||
|
0x0001, 0x0002, 0x0004, 0x0008, 0x0010
|
||||||
|
};
|
||||||
|
|
||||||
|
// builtin_mournfull_toll_alternative: unique doubled-beat pattern
|
||||||
|
const uint16_t PROGMEM builtin_mournfull_toll_alternative[] = {
|
||||||
|
0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001,
|
||||||
|
0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0004,
|
||||||
|
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0004, 0x0004,
|
||||||
|
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0002, 0x0000,
|
||||||
|
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0002, 0x0002, 0x0000,
|
||||||
|
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0008, 0x0000, 0x0000,
|
||||||
|
0x0000, 0x0000, 0x0000, 0x0000, 0x0008, 0x0008, 0x0000, 0x0000,
|
||||||
|
0x0000, 0x0000, 0x0000, 0x0000
|
||||||
|
};
|
||||||
|
|
||||||
|
// ═════════════════════════════════════════════════════════════════════════════════
|
||||||
|
// MELODY LIBRARY - Array of all built-in melodies
|
||||||
|
// ═════════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
const MelodyInfo MELODY_LIBRARY[] = {
|
||||||
|
{
|
||||||
|
"1 Bell Test",
|
||||||
|
"one_bell_test",
|
||||||
|
one_bell_test,
|
||||||
|
sizeof(one_bell_test) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Ormilia 1,2,3,4,5,6,7,8",
|
||||||
|
"ormilia_1_8",
|
||||||
|
ormilia_1_8,
|
||||||
|
sizeof(ormilia_1_8) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Festal 1,2,3,4,5",
|
||||||
|
"festive_1_8",
|
||||||
|
festive_1_8,
|
||||||
|
sizeof(festive_1_8) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Festive Chord 1,2,3,4,5",
|
||||||
|
"festive_alt_5",
|
||||||
|
festive_alt_5,
|
||||||
|
sizeof(festive_alt_5) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Festive 1,2,3,4,5,6",
|
||||||
|
"festive_6",
|
||||||
|
festive_6,
|
||||||
|
sizeof(festive_6) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Festive 1,2,3,4,5",
|
||||||
|
"festive_5",
|
||||||
|
festive_5,
|
||||||
|
sizeof(festive_5) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Festive 1,2,3,4",
|
||||||
|
"festive_2_4",
|
||||||
|
festive_2_4,
|
||||||
|
sizeof(festive_2_4) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Festive 1",
|
||||||
|
"festive_1",
|
||||||
|
festive_1,
|
||||||
|
sizeof(festive_1) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"One By One 1,2,3,4,5,6,7,8",
|
||||||
|
"onebyone_4_8",
|
||||||
|
onebyone_4_8,
|
||||||
|
sizeof(onebyone_4_8) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"One By One 1,2,3",
|
||||||
|
"onebyone_2_3",
|
||||||
|
onebyone_2_3,
|
||||||
|
sizeof(onebyone_2_3) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Athonite Extended 1,2,3,4,5,6,7,8",
|
||||||
|
"athonite_4_8",
|
||||||
|
athonite_4_8,
|
||||||
|
sizeof(athonite_4_8) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Athonite Extended 1,2,3,4",
|
||||||
|
"athonite_3_4",
|
||||||
|
athonite_3_4,
|
||||||
|
sizeof(athonite_3_4) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Athonite 1,2,3",
|
||||||
|
"athonite_3",
|
||||||
|
athonite_3,
|
||||||
|
sizeof(athonite_3) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Athonite 1,2",
|
||||||
|
"athonite_1_2",
|
||||||
|
athonite_1_2,
|
||||||
|
sizeof(athonite_1_2) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Talanto 1,2,3,4",
|
||||||
|
"talanto_1_4",
|
||||||
|
talanto_1_4,
|
||||||
|
sizeof(talanto_1_4) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Semantron 1,2,3,4",
|
||||||
|
"semantron_1_4",
|
||||||
|
semantron_1_4,
|
||||||
|
sizeof(semantron_1_4) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Toll Great Friday 1,2,3,4",
|
||||||
|
"mournfull_gf_1_4",
|
||||||
|
mournfull_gf_1_4,
|
||||||
|
sizeof(mournfull_gf_1_4) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Mournfull Toll 1,2,3,4",
|
||||||
|
"mournfull_1_4",
|
||||||
|
mournfull_1_4,
|
||||||
|
sizeof(mournfull_1_4) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Orthros Festive 1,2,3",
|
||||||
|
"orthros_fst_1_3",
|
||||||
|
orthros_fst_1_3,
|
||||||
|
sizeof(orthros_fst_1_3) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Orthros 1,2,3,4,5,6,7,8",
|
||||||
|
"orthros_1_8",
|
||||||
|
orthros_1_8,
|
||||||
|
sizeof(orthros_1_8) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Catechetical 1,2,3,4,5",
|
||||||
|
"catechetical_1_5",
|
||||||
|
catechetical_1_5,
|
||||||
|
sizeof(catechetical_1_5) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Vesper Festive 1,2,3,4",
|
||||||
|
"vesper_fst_1_4",
|
||||||
|
vesper_fst_1_4,
|
||||||
|
sizeof(vesper_fst_1_4) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Vesper 1,2,3",
|
||||||
|
"vesper_1_3",
|
||||||
|
vesper_1_3,
|
||||||
|
sizeof(vesper_1_3) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Doxology Festive 1,2,3,4,5,6",
|
||||||
|
"doxology_fst_1_6",
|
||||||
|
doxology_fst_1_6,
|
||||||
|
sizeof(doxology_fst_1_6) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Doxology Alternative 1,2,3,4,5",
|
||||||
|
"doxology_alt_1_5",
|
||||||
|
doxology_alt_1_5,
|
||||||
|
sizeof(doxology_alt_1_5) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Doxology 1,2,3,4",
|
||||||
|
"doxology_1_4",
|
||||||
|
doxology_1_4,
|
||||||
|
sizeof(doxology_1_4) / sizeof(uint16_t)
|
||||||
|
},
|
||||||
|
// ── builtin_* UIDs — backward-compat aliases for devices using old PIDs ──────
|
||||||
|
{ "1 Bell Test", "builtin_1bell_test", one_bell_test, sizeof(one_bell_test) / sizeof(uint16_t) },
|
||||||
|
{ "Doxology Traditional", "builtin_doxology_traditional", doxology_1_4, sizeof(doxology_1_4) / sizeof(uint16_t) },
|
||||||
|
{ "Doxology Alternative", "builtin_doxology_alternative", doxology_alt_1_5, sizeof(doxology_alt_1_5) / sizeof(uint16_t) },
|
||||||
|
{ "Doxology Festive", "builtin_doxology_festive", doxology_fst_1_6, sizeof(doxology_fst_1_6) / sizeof(uint16_t) },
|
||||||
|
{ "Vesper Traditional", "builtin_vesper_traditional", vesper_1_3, sizeof(vesper_1_3) / sizeof(uint16_t) },
|
||||||
|
{ "Vesper Alternative", "builtin_vesper_alternative", vesper_fst_1_4, sizeof(vesper_fst_1_4) / sizeof(uint16_t) },
|
||||||
|
{ "Catehetical", "builtin_catehetical", builtin_catehetical, sizeof(builtin_catehetical) / sizeof(uint16_t) },
|
||||||
|
{ "Orthros Traditional", "builtin_orthros_traditional", orthros_1_8, sizeof(orthros_1_8) / sizeof(uint16_t) },
|
||||||
|
{ "Orthros Alternative", "builtin_orthros_alternative", orthros_fst_1_3, sizeof(orthros_fst_1_3) / sizeof(uint16_t) },
|
||||||
|
{ "Mournfull Toll", "builtin_mournfull_toll", mournfull_1_4, sizeof(mournfull_1_4) / sizeof(uint16_t) },
|
||||||
|
{ "Mournfull Toll Alternative", "builtin_mournfull_toll_alternative", builtin_mournfull_toll_alternative, sizeof(builtin_mournfull_toll_alternative) / sizeof(uint16_t) },
|
||||||
|
{ "Mournfull Toll Meg Par", "builtin_mournfull_toll_meg_par", mournfull_gf_1_4, sizeof(mournfull_gf_1_4) / sizeof(uint16_t) },
|
||||||
|
{ "Sematron", "builtin_sematron", semantron_1_4, sizeof(semantron_1_4) / sizeof(uint16_t) },
|
||||||
|
{ "Sematron Alternative", "builtin_sematron_alternative", talanto_1_4, sizeof(talanto_1_4) / sizeof(uint16_t) },
|
||||||
|
{ "Athonite 1 2 Voices", "builtin_athonite_1_2_voices", athonite_1_2, sizeof(athonite_1_2) / sizeof(uint16_t) },
|
||||||
|
{ "Athonite 3 Voices", "builtin_athonite_3_voices", athonite_3, sizeof(athonite_3) / sizeof(uint16_t) },
|
||||||
|
{ "Athonite 3 4 Voices", "builtin_athonite_3_4_voices", athonite_3_4, sizeof(athonite_3_4) / sizeof(uint16_t) },
|
||||||
|
{ "Athonite 4 8 Voices", "builtin_athonite_4_8_voices", athonite_4_8, sizeof(athonite_4_8) / sizeof(uint16_t) },
|
||||||
|
{ "Onebyone 2 3 Voices", "builtin_onebyone_2_3_voices", onebyone_2_3, sizeof(onebyone_2_3) / sizeof(uint16_t) },
|
||||||
|
{ "Onebyone 4 8 Voices", "builtin_onebyone_4_8_voices", onebyone_4_8, sizeof(onebyone_4_8) / sizeof(uint16_t) },
|
||||||
|
{ "Festive 1Voice", "builtin_festive_1voice", festive_1, sizeof(festive_1) / sizeof(uint16_t) },
|
||||||
|
{ "Festive 4Voices", "builtin_festive_4voices", festive_2_4, sizeof(festive_2_4) / sizeof(uint16_t) },
|
||||||
|
{ "Festive 5Voices", "builtin_festive_5voices", festive_5, sizeof(festive_5) / sizeof(uint16_t) },
|
||||||
|
{ "Festive 5Voice Alternative", "builtin_festive_5voice_alternative", festive_alt_5, sizeof(festive_alt_5) / sizeof(uint16_t) },
|
||||||
|
{ "Festive 6Voices", "builtin_festive_6voices", festive_6, sizeof(festive_6) / sizeof(uint16_t) },
|
||||||
|
{ "Festive 8Voices", "builtin_festive_8voices", festive_1_8, sizeof(festive_1_8) / sizeof(uint16_t) },
|
||||||
|
{ "Ormilia", "builtin_ormilia", ormilia_1_8, sizeof(ormilia_1_8) / sizeof(uint16_t) }
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
const uint16_t MELODY_COUNT = sizeof(MELODY_LIBRARY) / sizeof(MelodyInfo);
|
||||||
|
|
||||||
|
// ═════════════════════════════════════════════════════════════════════════════════
|
||||||
|
// HELPER FUNCTIONS
|
||||||
|
// ═════════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Check if a PID corresponds to a built-in melody
|
||||||
|
* @param pid The melody PID to check
|
||||||
|
* @return true if the PID exists in the built-in melody library
|
||||||
|
*/
|
||||||
|
inline bool isBuiltInMelody(const String& pid) {
|
||||||
|
for (uint16_t i = 0; i < MELODY_COUNT; i++) {
|
||||||
|
if (pid == MELODY_LIBRARY[i].pid) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Find a built-in melody by PID
|
||||||
|
* @param pid The melody playback ID to find
|
||||||
|
* @return Pointer to MelodyInfo if found, nullptr otherwise
|
||||||
|
*/
|
||||||
|
inline const MelodyInfo* findMelodyByPID(const String& pid) {
|
||||||
|
for (uint16_t i = 0; i < MELODY_COUNT; i++) {
|
||||||
|
if (pid == MELODY_LIBRARY[i].pid) {
|
||||||
|
return &MELODY_LIBRARY[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Load a built-in melody into a vector
|
||||||
|
* @param pid The melody playback ID to load
|
||||||
|
* @param melodySteps Vector to fill with melody data
|
||||||
|
* @return true if melody was found and loaded, false otherwise
|
||||||
|
*/
|
||||||
|
inline bool loadBuiltInMelody(const String& pid, std::vector<uint16_t>& melodySteps) {
|
||||||
|
const MelodyInfo* melody = findMelodyByPID(pid);
|
||||||
|
if (!melody) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resize vector and copy data from PROGMEM
|
||||||
|
melodySteps.resize(melody->stepCount);
|
||||||
|
for (uint16_t i = 0; i < melody->stepCount; i++) {
|
||||||
|
melodySteps[i] = pgm_read_word(&(melody->data[i]));
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Get list of all built-in melodies as JSON string
|
||||||
|
* @return JSON array string of melody names and PIDs
|
||||||
|
*/
|
||||||
|
inline String getBuiltInMelodiesJSON() {
|
||||||
|
String json = "[";
|
||||||
|
for (uint16_t i = 0; i < MELODY_COUNT; i++) {
|
||||||
|
if (i > 0) json += ",";
|
||||||
|
json += "{";
|
||||||
|
json += "\"name\":\"" + String(MELODY_LIBRARY[i].name) + "\",";
|
||||||
|
json += "\"pid\":\"" + String(MELODY_LIBRARY[i].pid) + "\"";
|
||||||
|
json += "}";
|
||||||
|
}
|
||||||
|
json += "]";
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,187 @@
|
|||||||
|
# Built-In Melodies System
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
The built-in melodies system allows you to bake melodies directly into the firmware, eliminating the need for SD card downloads. Melodies are stored in **PROGMEM** (Flash memory), so they don't consume precious RAM.
|
||||||
|
|
||||||
|
## How It Works
|
||||||
|
|
||||||
|
1. **Check**: When a melody is requested, the Player first checks if the UID starts with `builtin_`
|
||||||
|
2. **Load**: If it's built-in, the melody is loaded from Flash memory (PROGMEM)
|
||||||
|
3. **Fallback**: If not built-in, it loads from SD card as usual
|
||||||
|
|
||||||
|
## Adding New Melodies
|
||||||
|
|
||||||
|
### Step 1: Create Your Melody Data
|
||||||
|
|
||||||
|
Each melody step is a **2-byte (uint16_t) bitmask** representing which bells to activate:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
// Example: Simple pattern
|
||||||
|
const uint16_t PROGMEM melody_my_tune[] = {
|
||||||
|
0x0001, // Bell 0
|
||||||
|
0x0002, // Bell 1
|
||||||
|
0x0004, // Bell 2
|
||||||
|
0x0008, // Bell 3
|
||||||
|
0x0003, // Bells 0+1 together
|
||||||
|
0x000F // Bells 0+1+2+3 together
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
**Bitmask Reference:**
|
||||||
|
- `0x0001` = Bell 0 (bit 0)
|
||||||
|
- `0x0002` = Bell 1 (bit 1)
|
||||||
|
- `0x0004` = Bell 2 (bit 2)
|
||||||
|
- `0x0008` = Bell 3 (bit 3)
|
||||||
|
- `0x0010` = Bell 4 (bit 4)
|
||||||
|
- `0x0020` = Bell 5 (bit 5)
|
||||||
|
- `0x0040` = Bell 6 (bit 6)
|
||||||
|
- `0x0080` = Bell 7 (bit 7)
|
||||||
|
- `0x0100` = Bell 8 (bit 8)
|
||||||
|
- ... up to `0x8000` = Bell 15 (bit 15)
|
||||||
|
- `0x0000` = Silence/rest
|
||||||
|
|
||||||
|
**Combining Bells:**
|
||||||
|
- `0x0003` = Bells 0+1 (0x0001 | 0x0002)
|
||||||
|
- `0x0005` = Bells 0+2 (0x0001 | 0x0004)
|
||||||
|
- `0x000F` = Bells 0+1+2+3
|
||||||
|
- `0xFFFF` = All 16 bells
|
||||||
|
|
||||||
|
### Step 2: Add to BuiltInMelodies.hpp
|
||||||
|
|
||||||
|
Open `src/BuiltInMelodies/BuiltInMelodies.hpp` and:
|
||||||
|
|
||||||
|
1. **Add your melody array:**
|
||||||
|
```cpp
|
||||||
|
// Your new melody
|
||||||
|
const uint16_t PROGMEM melody_my_awesome_tune[] = {
|
||||||
|
0x0001, 0x0002, 0x0004, 0x0008,
|
||||||
|
0x0010, 0x0020, 0x0040, 0x0080,
|
||||||
|
// ... up to 200 steps
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Add to MELODY_LIBRARY array:**
|
||||||
|
```cpp
|
||||||
|
const MelodyInfo MELODY_LIBRARY[] = {
|
||||||
|
// ... existing melodies ...
|
||||||
|
|
||||||
|
// Your new melody
|
||||||
|
{
|
||||||
|
"My Awesome Tune", // Display name
|
||||||
|
"builtin_my_awesome_tune", // UID (must start with "builtin_")
|
||||||
|
melody_my_awesome_tune, // Data array
|
||||||
|
sizeof(melody_my_awesome_tune) / sizeof(uint16_t), // Step count
|
||||||
|
200 // Default speed in milliseconds per beat
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 3: Use Your Melody
|
||||||
|
|
||||||
|
Send a play command with the built-in melody UID:
|
||||||
|
|
||||||
|
**MQTT:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"group": "playback",
|
||||||
|
"action": "play",
|
||||||
|
"uid": "builtin_my_awesome_tune",
|
||||||
|
"name": "My Awesome Tune",
|
||||||
|
"speed": 200
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**WebSocket/HTTP:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"group": "playback",
|
||||||
|
"action": "play",
|
||||||
|
"uid": "builtin_my_awesome_tune",
|
||||||
|
"name": "My Awesome Tune",
|
||||||
|
"speed": 200
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Pre-Loaded Melodies
|
||||||
|
|
||||||
|
The following melodies are already built-in:
|
||||||
|
|
||||||
|
| UID | Name | Steps | Default Speed |
|
||||||
|
|-----|------|-------|---------------|
|
||||||
|
| `builtin_scale` | Simple Scale | 8 | 200ms |
|
||||||
|
| `builtin_happy_birthday` | Happy Birthday | 23 | 250ms |
|
||||||
|
| `builtin_jingle_bells` | Jingle Bells | 32 | 180ms |
|
||||||
|
| `builtin_westminster` | Westminster Chimes | 16 | 400ms |
|
||||||
|
| `builtin_alarm` | Alarm | 16 | 150ms |
|
||||||
|
| `builtin_doorbell` | Doorbell | 4 | 300ms |
|
||||||
|
| `builtin_single_bell` | Single Bell Test | 1 | 100ms |
|
||||||
|
|
||||||
|
## Memory Usage
|
||||||
|
|
||||||
|
### Flash Memory (PROGMEM)
|
||||||
|
- Small melody (~30 steps): **60 bytes**
|
||||||
|
- Large melody (~200 steps): **400 bytes**
|
||||||
|
- 40 melodies average: **~6-10KB** (stored in Flash, not RAM!)
|
||||||
|
|
||||||
|
### RAM Usage
|
||||||
|
Only the **currently playing melody** is loaded into RAM. Built-in melodies are copied from Flash when needed.
|
||||||
|
|
||||||
|
## Tips
|
||||||
|
|
||||||
|
1. **Always use `builtin_` prefix** for UIDs to identify them as built-in
|
||||||
|
2. **Test with small melodies first** before adding large ones
|
||||||
|
3. **Use hex calculator** for complex bell combinations: `0x0001 | 0x0004 = 0x0005`
|
||||||
|
4. **Add rests** with `0x0000` for silence between notes
|
||||||
|
5. **Keep it simple** - most melodies work great with 30-50 steps
|
||||||
|
|
||||||
|
## Converting Binary Files to Code
|
||||||
|
|
||||||
|
If you have existing binary melody files and want to convert them to built-in format:
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Python script to convert binary file to C++ array
|
||||||
|
with open('melody.bin', 'rb') as f:
|
||||||
|
data = f.read()
|
||||||
|
|
||||||
|
print("const uint16_t PROGMEM melody_name[] = {")
|
||||||
|
for i in range(0, len(data), 2):
|
||||||
|
if i % 16 == 0:
|
||||||
|
print(" ", end="")
|
||||||
|
high = data[i]
|
||||||
|
low = data[i+1]
|
||||||
|
value = (high << 8) | low
|
||||||
|
print(f"0x{value:04X}", end="")
|
||||||
|
if i < len(data) - 2:
|
||||||
|
print(", ", end="")
|
||||||
|
if (i + 2) % 16 == 0:
|
||||||
|
print()
|
||||||
|
print("\n};")
|
||||||
|
```
|
||||||
|
|
||||||
|
## Example: Creating a Custom Melody
|
||||||
|
|
||||||
|
Let's create "Mary Had a Little Lamb":
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
// Mary Had a Little Lamb
|
||||||
|
// Notes: E D C D E E E, D D D, E G G
|
||||||
|
// Mapping: E=0, D=1, C=2, G=3
|
||||||
|
const uint16_t PROGMEM melody_mary_lamb[] = {
|
||||||
|
0x0001, 0x0002, 0x0004, 0x0002, // E D C D
|
||||||
|
0x0001, 0x0001, 0x0001, 0x0000, // E E E (rest)
|
||||||
|
0x0002, 0x0002, 0x0002, 0x0000, // D D D (rest)
|
||||||
|
0x0001, 0x0008, 0x0008 // E G G
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add to MELODY_LIBRARY:
|
||||||
|
{
|
||||||
|
"Mary Had a Little Lamb",
|
||||||
|
"builtin_mary_lamb",
|
||||||
|
melody_mary_lamb,
|
||||||
|
sizeof(melody_mary_lamb) / sizeof(uint16_t),
|
||||||
|
300 // 300ms per beat
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Now you can play it with UID `builtin_mary_lamb`!
|
||||||
@@ -1,31 +1,33 @@
|
|||||||
#include "ClientManager.hpp"
|
#include "ClientManager.hpp"
|
||||||
|
|
||||||
|
#define TAG "ClientManager"
|
||||||
#include "../Logging/Logging.hpp"
|
#include "../Logging/Logging.hpp"
|
||||||
|
|
||||||
ClientManager::ClientManager() {
|
ClientManager::ClientManager() {
|
||||||
LOG_INFO("Client Manager Component - Initialized");
|
LOG_INFO(TAG, "Client Manager initialized !");
|
||||||
}
|
}
|
||||||
|
|
||||||
ClientManager::~ClientManager() {
|
ClientManager::~ClientManager() {
|
||||||
_clients.clear();
|
_clients.clear();
|
||||||
LOG_INFO("Client Manager Component - Destroyed");
|
LOG_INFO(TAG, "Client Manager destroyed");
|
||||||
}
|
}
|
||||||
|
|
||||||
void ClientManager::addClient(AsyncWebSocketClient* client, DeviceType deviceType) {
|
void ClientManager::addClient(AsyncWebSocketClient* client, DeviceType deviceType) {
|
||||||
if (!isValidClient(client)) {
|
if (!isValidClient(client)) {
|
||||||
LOG_ERROR("Cannot add invalid client");
|
LOG_WARNING(TAG, "Client Manager - Cannot add invalid client");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
uint32_t clientId = client->id();
|
uint32_t clientId = client->id();
|
||||||
_clients[clientId] = ClientInfo(client, deviceType);
|
_clients[clientId] = ClientInfo(client, deviceType);
|
||||||
|
|
||||||
LOG_INFO("Client #%u added as %s device", clientId, deviceTypeToString(deviceType));
|
LOG_INFO(TAG, "Client Manager - Client #%u added as %s device", clientId, deviceTypeToString(deviceType));
|
||||||
}
|
}
|
||||||
|
|
||||||
void ClientManager::removeClient(uint32_t clientId) {
|
void ClientManager::removeClient(uint32_t clientId) {
|
||||||
auto it = _clients.find(clientId);
|
auto it = _clients.find(clientId);
|
||||||
if (it != _clients.end()) {
|
if (it != _clients.end()) {
|
||||||
LOG_INFO("Client #%u removed (%s device)", clientId,
|
LOG_INFO(TAG, "Client Manager - Client #%u removed (%s device)", clientId,
|
||||||
deviceTypeToString(it->second.deviceType));
|
deviceTypeToString(it->second.deviceType));
|
||||||
_clients.erase(it);
|
_clients.erase(it);
|
||||||
}
|
}
|
||||||
@@ -36,7 +38,7 @@ void ClientManager::updateClientType(uint32_t clientId, DeviceType deviceType) {
|
|||||||
if (it != _clients.end()) {
|
if (it != _clients.end()) {
|
||||||
DeviceType oldType = it->second.deviceType;
|
DeviceType oldType = it->second.deviceType;
|
||||||
it->second.deviceType = deviceType;
|
it->second.deviceType = deviceType;
|
||||||
LOG_INFO("Client #%u type updated from %s to %s", clientId,
|
LOG_INFO(TAG, "Client Manager - Client #%u type updated from %s to %s", clientId,
|
||||||
deviceTypeToString(oldType), deviceTypeToString(deviceType));
|
deviceTypeToString(oldType), deviceTypeToString(deviceType));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -72,11 +74,11 @@ bool ClientManager::sendToClient(uint32_t clientId, const String& message) {
|
|||||||
if (it != _clients.end() && isValidClient(it->second.client)) {
|
if (it != _clients.end() && isValidClient(it->second.client)) {
|
||||||
it->second.client->text(message);
|
it->second.client->text(message);
|
||||||
updateClientLastSeen(clientId);
|
updateClientLastSeen(clientId);
|
||||||
LOG_DEBUG("Message sent to client #%u: %s", clientId, message.c_str());
|
LOG_DEBUG(TAG, "Client Manager - Message sent to client #%u: %s", clientId, message.c_str());
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
LOG_WARNING("Failed to send message to client #%u - client not found or invalid", clientId);
|
LOG_WARNING(TAG, "Client Manager - Failed to send message to client #%u - client not found or invalid", clientId);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -90,7 +92,7 @@ void ClientManager::sendToMasterClients(const String& message) {
|
|||||||
count++;
|
count++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
LOG_DEBUG("Message sent to %d master client(s): %s", count, message.c_str());
|
LOG_DEBUG(TAG, "Client Manager - Message sent to %d master client(s): %s", count, message.c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
void ClientManager::sendToSecondaryClients(const String& message) {
|
void ClientManager::sendToSecondaryClients(const String& message) {
|
||||||
@@ -103,7 +105,7 @@ void ClientManager::sendToSecondaryClients(const String& message) {
|
|||||||
count++;
|
count++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
LOG_DEBUG("Message sent to %d secondary client(s): %s", count, message.c_str());
|
LOG_DEBUG(TAG, "Client Manager - Message sent to %d secondary client(s): %s", count, message.c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
void ClientManager::broadcastToAll(const String& message) {
|
void ClientManager::broadcastToAll(const String& message) {
|
||||||
@@ -115,14 +117,14 @@ void ClientManager::broadcastToAll(const String& message) {
|
|||||||
count++;
|
count++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
LOG_DEBUG("Message broadcasted to %d client(s): %s", count, message.c_str());
|
LOG_DEBUG(TAG, "Client Manager - Message broadcasted to %d client(s): %s", count, message.c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
void ClientManager::cleanupDisconnectedClients() {
|
void ClientManager::cleanupDisconnectedClients() {
|
||||||
auto it = _clients.begin();
|
auto it = _clients.begin();
|
||||||
while (it != _clients.end()) {
|
while (it != _clients.end()) {
|
||||||
if (!isValidClient(it->second.client)) {
|
if (!isValidClient(it->second.client)) {
|
||||||
LOG_DEBUG("Cleaning up disconnected client #%u", it->first);
|
LOG_DEBUG(TAG, "Client Manager - Cleaning up disconnected client #%u", it->first);
|
||||||
it->second.isConnected = false;
|
it->second.isConnected = false;
|
||||||
it = _clients.erase(it);
|
it = _clients.erase(it);
|
||||||
} else {
|
} else {
|
||||||
@@ -132,11 +134,11 @@ void ClientManager::cleanupDisconnectedClients() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
String ClientManager::getClientListJson() const {
|
String ClientManager::getClientListJson() const {
|
||||||
StaticJsonDocument<512> doc;
|
JsonDocument doc;
|
||||||
JsonArray clients = doc.createNestedArray("clients");
|
JsonArray clients = doc["clients"].to<JsonArray>();
|
||||||
|
|
||||||
for (const auto& pair : _clients) {
|
for (const auto& pair : _clients) {
|
||||||
JsonObject client = clients.createNestedObject();
|
JsonObject client = clients.add<JsonObject>();
|
||||||
client["id"] = pair.first;
|
client["id"] = pair.first;
|
||||||
client["type"] = deviceTypeToString(pair.second.deviceType);
|
client["type"] = deviceTypeToString(pair.second.deviceType);
|
||||||
client["connected"] = isValidClient(pair.second.client);
|
client["connected"] = isValidClient(pair.second.client);
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
# ClientManager
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
`ClientManager` tracks all active WebSocket clients and their assigned device roles. It exists because the Vesper WebSocket API distinguishes between **master** clients (primary control apps) and **secondary** clients (auxiliary devices), and different subsystems need to send targeted responses rather than indiscriminate broadcasts. The class owns the client registry and exposes send primitives that `WebSocketDriver` delegates to; it does not interact with the network stack directly.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Public API
|
||||||
|
|
||||||
|
### Client Lifecycle
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|---|---|
|
||||||
|
| `addClient(client, deviceType)` | Registers a new WebSocket client, defaulting to `UNKNOWN` type until identified. |
|
||||||
|
| `removeClient(clientId)` | Erases a client from the registry by its WebSocket ID. |
|
||||||
|
| `updateClientType(clientId, deviceType)` | Promotes a client from `UNKNOWN` to `MASTER` or `SECONDARY` after the `system.identify` handshake. |
|
||||||
|
| `updateClientLastSeen(clientId)` | Stamps the client's `lastSeen` field with the current `millis()`. Called on every received message and every outbound send. |
|
||||||
|
| `cleanupDisconnectedClients()` | Iterates the registry and removes entries whose underlying `AsyncWebSocketClient` is no longer in `WS_CONNECTED` state. |
|
||||||
|
|
||||||
|
### Client Queries
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|---|---|
|
||||||
|
| `hasClients()` | Returns `true` if the registry is non-empty. |
|
||||||
|
| `getClientCount()` | Returns the number of entries currently in the registry. |
|
||||||
|
| `isClientConnected(clientId)` | Returns `true` if the client is registered and its socket reports `WS_CONNECTED`. |
|
||||||
|
| `getClientType(clientId)` | Returns the `DeviceType` of the client, or `UNKNOWN` if not found. |
|
||||||
|
| `getClientInfo(clientId)` | Returns a raw pointer to the `ClientInfo` struct, or `nullptr` if not found. |
|
||||||
|
| `getClientListJson()` | Serializes the current client registry to a JSON string (`{"clients":[...]}`). |
|
||||||
|
|
||||||
|
### Messaging
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|---|---|
|
||||||
|
| `sendToClient(clientId, message)` | Sends a text message to a single client; returns `false` if the client is absent or disconnected. |
|
||||||
|
| `sendToMasterClients(message)` | Sends to all clients whose type is `MASTER`. |
|
||||||
|
| `sendToSecondaryClients(message)` | Sends to all clients whose type is `SECONDARY`. |
|
||||||
|
| `broadcastToAll(message)` | Sends to every client that passes the `isValidClient` check, regardless of type. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Initialization
|
||||||
|
|
||||||
|
`ClientManager` has no `begin()` method and no hardware dependencies. It is constructed at global scope inside `CommunicationRouter` (which owns a `ClientManager` member). `CommunicationRouter` passes the instance by reference into `WebSocketDriver` and `SystemHandler` at construction time.
|
||||||
|
|
||||||
|
The relevant initialization chain in `main.cpp`:
|
||||||
|
|
||||||
|
```
|
||||||
|
CommunicationRouter communication(...); // constructs ClientManager internally
|
||||||
|
communication.begin(); // constructs WebSocketDriver and SystemHandler,
|
||||||
|
// both receive ClientManager& at this point
|
||||||
|
```
|
||||||
|
|
||||||
|
No explicit ordering constraint beyond `CommunicationRouter::begin()` being called after the `AsyncWebServer` and `AsyncWebSocket` objects exist.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
| Dependency | Role |
|
||||||
|
|---|---|
|
||||||
|
| `ESPAsyncWebServer` (`AsyncWebSocket`, `AsyncWebSocketClient`) | Provides the socket handle and connection status via `client->status()`. |
|
||||||
|
| `ArduinoJson` | Used only in `getClientListJson()` to serialize the registry. |
|
||||||
|
| `Logging` | All lifecycle events and send results are logged at `INFO` or `DEBUG` level. |
|
||||||
|
|
||||||
|
`ClientManager` has no dependency on `ConfigManager`, `MQTT`, `SD`, or any hardware peripheral.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Gotchas / Notes
|
||||||
|
|
||||||
|
**No FreeRTOS task.** `ClientManager` is purely synchronous. All methods execute in the caller's context. `WebSocketDriver` event callbacks fire in the `AsyncTCP` task (Core 0); the `SystemHandler` `system.identify` handler runs in whatever task dispatches `CommandBus`. If both paths mutate `_clients` concurrently there is a potential race on the `std::map`. In practice, the async event task and the command dispatch path currently share Core 0, reducing (but not eliminating) the risk. There is no mutex guarding `_clients`.
|
||||||
|
|
||||||
|
**`isValidClient` is the source of truth for liveness.** The `isConnected` flag inside `ClientInfo` is set to `false` only during `cleanupDisconnectedClients()` and is otherwise not authoritative — actual connectivity is determined by `client->status() == WS_CONNECTED`. Do not rely on `ClientInfo::isConnected` alone.
|
||||||
|
|
||||||
|
**`cleanupDisconnectedClients()` must be called externally.** The class does not self-clean. `WebSocketDriver::onDisconnect()` calls it after every disconnect event. The `main.cpp` loop also calls `ws.cleanupClients()` every 2 seconds at the `AsyncWebSocket` level, which is a separate mechanism.
|
||||||
|
|
||||||
|
**Client type identification requires a handshake.** Clients connect as `UNKNOWN`. The app must send a `system.identify` command to be promoted:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "v": 2, "cmd": "system.identify", "contents": { "device_type": "master" } }
|
||||||
|
```
|
||||||
|
|
||||||
|
`SystemHandler` calls `updateClientType()` upon receiving this command. Until then, `sendToMasterClients` and `sendToSecondaryClients` will not reach the client.
|
||||||
|
|
||||||
|
**Maximum client capacity is not enforced.** The header comment mentions "up to 5 total devices" but there is no enforcement in the code. The `std::map` will grow without bound if clients connect without disconnecting.
|
||||||
|
|
||||||
|
**`getClientListJson()` uses a fixed `StaticJsonDocument<512>`.** With the current 5-client design intent this is sufficient, but it will silently truncate if a large number of clients are present.
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
#include "CommandBus.hpp"
|
||||||
|
#include "LegacyAdapter.hpp"
|
||||||
|
#include "../../Logging/Logging.hpp"
|
||||||
|
|
||||||
|
#define TAG "CommandBus"
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Handler registration
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
void CommandBus::registerHandler(std::unique_ptr<ICommandHandler> handler) {
|
||||||
|
auto cmds = handler->commands();
|
||||||
|
ICommandHandler* raw = handler.get();
|
||||||
|
|
||||||
|
for (const auto& cmd : cmds) {
|
||||||
|
if (_registry.count(cmd)) {
|
||||||
|
LOG_WARNING(TAG, "Duplicate command registration: '%s' — overwriting previous handler", cmd.c_str());
|
||||||
|
}
|
||||||
|
_registry[cmd] = raw;
|
||||||
|
LOG_DEBUG(TAG, "Registered handler for command: %s", cmd.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
_handlers.push_back(std::move(handler));
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommandBus::addTransport(ITransport* transport) {
|
||||||
|
_transports.push_back(transport);
|
||||||
|
LOG_DEBUG(TAG, "Transport registered: %s", transport->name().c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Dispatch
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
void CommandBus::dispatch(CommandEnvelope& envelope) {
|
||||||
|
// Translate legacy v1 envelopes before registry lookup.
|
||||||
|
// No-op for v2 — the check is a single integer compare.
|
||||||
|
if (envelope.version == 1) {
|
||||||
|
LOG_DEBUG(TAG, "v1 envelope received — translating '%s'", envelope.command.c_str());
|
||||||
|
translateLegacyEnvelope(envelope);
|
||||||
|
LOG_DEBUG(TAG, "v1 translation result: '%s'", envelope.command.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
auto it = _registry.find(envelope.command);
|
||||||
|
|
||||||
|
if (it == _registry.end()) {
|
||||||
|
LOG_WARNING(TAG, "No handler for command: '%s'", envelope.command.c_str());
|
||||||
|
CommandResult unknown = CommandResult::err("unknown", "Unknown command: " + envelope.command);
|
||||||
|
unknown.reqId = envelope.reqId;
|
||||||
|
envelope.reply(unknown);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
LOG_DEBUG(TAG, "Dispatching: %s", envelope.command.c_str());
|
||||||
|
CommandResult result = it->second->execute(envelope);
|
||||||
|
result.reqId = envelope.reqId;
|
||||||
|
envelope.reply(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Broadcast
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
void CommandBus::broadcast(const CommandResult& result) {
|
||||||
|
// Serialise once, fan out to all transports
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["status"] = (result.status == CommandResult::Status::SUCCESS) ? "SUCCESS"
|
||||||
|
: (result.status == CommandResult::Status::INFO) ? "INFO"
|
||||||
|
: "ERROR";
|
||||||
|
doc["type"] = result.type;
|
||||||
|
if (!result.payload.isEmpty()) {
|
||||||
|
doc["message"] = result.payload;
|
||||||
|
}
|
||||||
|
if (result.hasData) {
|
||||||
|
doc["data"] = result.data;
|
||||||
|
}
|
||||||
|
if (!result.reqId.isEmpty()) {
|
||||||
|
doc["req_id"] = result.reqId;
|
||||||
|
}
|
||||||
|
|
||||||
|
String serialised;
|
||||||
|
serializeJson(doc, serialised);
|
||||||
|
|
||||||
|
for (auto* transport : _transports) {
|
||||||
|
transport->broadcast(serialised);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <vector>
|
||||||
|
#include <memory>
|
||||||
|
#include <map>
|
||||||
|
#include "CommandEnvelope.hpp"
|
||||||
|
#include "CommandResult.hpp"
|
||||||
|
#include "../Handlers/ICommandHandler.hpp"
|
||||||
|
#include "../Transport/ITransport.hpp"
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// CommandBus
|
||||||
|
//
|
||||||
|
// Registry + dispatcher. Replaces the 700-line if/else chain in CommandHandler.
|
||||||
|
//
|
||||||
|
// Usage:
|
||||||
|
// // Registration (once, in CommunicationRouter::registerHandlers())
|
||||||
|
// _bus.registerHandler(std::make_unique<PlaybackHandler>(_player));
|
||||||
|
// _bus.addTransport(&_mqtt);
|
||||||
|
//
|
||||||
|
// // Dispatch (called from each transport's message callback)
|
||||||
|
// _bus.dispatch(envelope);
|
||||||
|
//
|
||||||
|
// // Broadcast event to all transports
|
||||||
|
// _bus.broadcast(CommandResult::info("bell.strike", "Bell 2 fired"));
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class CommandBus {
|
||||||
|
public:
|
||||||
|
// Register a handler. All command names reported by handler->commands()
|
||||||
|
// are mapped to this handler instance. Duplicate command names log a
|
||||||
|
// warning and the later registration wins.
|
||||||
|
void registerHandler(std::unique_ptr<ICommandHandler> handler);
|
||||||
|
|
||||||
|
// Add a transport that receives broadcasts and participates in health checks.
|
||||||
|
void addTransport(ITransport* transport);
|
||||||
|
|
||||||
|
// Dispatch an envelope to the registered handler (O(1) hash-map lookup).
|
||||||
|
// Calls envelope.reply() exactly once — with an error result if no handler
|
||||||
|
// is registered for envelope.command.
|
||||||
|
void dispatch(CommandEnvelope& envelope);
|
||||||
|
|
||||||
|
// Broadcast a serialised result to all registered transports.
|
||||||
|
// Each transport's broadcast() implementation decides how to fan it out
|
||||||
|
// (e.g. WebSocket sends to all connected clients; HTTP is a no-op).
|
||||||
|
void broadcast(const CommandResult& result);
|
||||||
|
|
||||||
|
private:
|
||||||
|
// Owned storage for handler instances
|
||||||
|
std::vector<std::unique_ptr<ICommandHandler>> _handlers;
|
||||||
|
|
||||||
|
// Command name → handler pointer (non-owning, points into _handlers)
|
||||||
|
// std::map used instead of unordered_map — Arduino String has no std::hash specialisation
|
||||||
|
std::map<String, ICommandHandler*> _registry;
|
||||||
|
|
||||||
|
// Non-owning references to transports (owned by CommunicationRouter)
|
||||||
|
std::vector<ITransport*> _transports;
|
||||||
|
};
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <ArduinoJson.h>
|
||||||
|
#include <functional>
|
||||||
|
|
||||||
|
// Forward declare so CommandEnvelope.hpp doesn't pull in CommandResult.hpp circularly
|
||||||
|
struct CommandResult;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// CommandEnvelope
|
||||||
|
//
|
||||||
|
// Universal message wrapper. Every transport (MQTT, WebSocket, HTTP, UART)
|
||||||
|
// parses its raw input and produces one of these before calling CommandBus::dispatch().
|
||||||
|
//
|
||||||
|
// The reply lambda is injected by the transport so the bus and handlers never
|
||||||
|
// need to know which wire the response goes back on.
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
struct CommandEnvelope {
|
||||||
|
enum class Transport {
|
||||||
|
MQTT,
|
||||||
|
WEBSOCKET,
|
||||||
|
HTTP,
|
||||||
|
UART
|
||||||
|
};
|
||||||
|
|
||||||
|
// Protocol version: 2 = v2 namespaced commands, 1 = legacy v1 (default 2)
|
||||||
|
uint8_t version = 2;
|
||||||
|
|
||||||
|
Transport transport = Transport::WEBSOCKET;
|
||||||
|
|
||||||
|
// Who issued the command, as far as the transport knows. Set by each
|
||||||
|
// transport when it builds the envelope (MQTT/WebSocket/HTTP → APP, UART
|
||||||
|
// slave board → BUTTON). Handlers that record provenance (PlaybackHandler →
|
||||||
|
// status/playback "source") read this instead of guessing from `transport`.
|
||||||
|
enum class Origin {
|
||||||
|
UNKNOWN,
|
||||||
|
APP,
|
||||||
|
BUTTON,
|
||||||
|
SCHEDULE
|
||||||
|
};
|
||||||
|
Origin origin = Origin::UNKNOWN;
|
||||||
|
|
||||||
|
// WebSocket client ID — 0 for transports that don't have per-client identity
|
||||||
|
uint32_t clientId = 0;
|
||||||
|
|
||||||
|
// Flat command name — e.g. "playback", "relay.set_durations", "system.restart"
|
||||||
|
String command;
|
||||||
|
|
||||||
|
// Optional caller-supplied correlation ID, echoed back in CommandResult's
|
||||||
|
// reply so a client that fans requests out over a shared channel (MQTT
|
||||||
|
// control/command, multiple devices on one broker) can match replies to
|
||||||
|
// requests. Empty when the caller didn't send one — always optional, so
|
||||||
|
// v1 clients and any request without it keep working unchanged.
|
||||||
|
String reqId;
|
||||||
|
|
||||||
|
// The "contents" object from the raw JSON message
|
||||||
|
JsonDocument contents;
|
||||||
|
|
||||||
|
// Reply callback injected by the transport layer.
|
||||||
|
// The bus calls this exactly once after dispatch completes.
|
||||||
|
std::function<void(const CommandResult&)> reply;
|
||||||
|
};
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <ArduinoJson.h>
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// CommandResult
|
||||||
|
//
|
||||||
|
// Standardised return type from every ICommandHandler::execute() call.
|
||||||
|
// Replaces ad-hoc string building scattered across CommandHandler.cpp.
|
||||||
|
//
|
||||||
|
// Use the static factory methods — they read clearly at the call site:
|
||||||
|
//
|
||||||
|
// return CommandResult::ok("playback", "Command executed");
|
||||||
|
// return CommandResult::ok("relay.get_config", doc);
|
||||||
|
// return CommandResult::err("relay.test_output", "Player must be stopped first");
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
struct CommandResult {
|
||||||
|
enum class Status { SUCCESS, ERROR, INFO };
|
||||||
|
|
||||||
|
Status status = Status::ERROR;
|
||||||
|
String type; // echoes the command name back to the caller
|
||||||
|
String payload; // human-readable message (empty is fine for data responses)
|
||||||
|
JsonDocument data; // structured data payload (optional)
|
||||||
|
bool hasData = false;
|
||||||
|
String reqId; // echoes CommandEnvelope::reqId, if the caller sent one. Set by
|
||||||
|
// CommandBus::dispatch(), not by handlers — factory methods below
|
||||||
|
// never need to know about it.
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------
|
||||||
|
// Factory methods
|
||||||
|
// -----------------------------------------------------------------------
|
||||||
|
|
||||||
|
// Simple success with an optional message
|
||||||
|
static CommandResult ok(const String& type, const String& msg = "") {
|
||||||
|
CommandResult r;
|
||||||
|
r.status = Status::SUCCESS;
|
||||||
|
r.type = type;
|
||||||
|
r.payload = msg;
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Success with a structured JSON data payload
|
||||||
|
static CommandResult ok(const String& type, const JsonDocument& d) {
|
||||||
|
CommandResult r;
|
||||||
|
r.status = Status::SUCCESS;
|
||||||
|
r.type = type;
|
||||||
|
r.data.set(d);
|
||||||
|
r.hasData = true;
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Error with a required message
|
||||||
|
static CommandResult err(const String& type, const String& msg) {
|
||||||
|
CommandResult r;
|
||||||
|
r.status = Status::ERROR;
|
||||||
|
r.type = type;
|
||||||
|
r.payload = msg;
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Info / event (used for unsolicited broadcasts)
|
||||||
|
static CommandResult info(const String& type, const String& msg = "") {
|
||||||
|
CommandResult r;
|
||||||
|
r.status = Status::INFO;
|
||||||
|
r.type = type;
|
||||||
|
r.payload = msg;
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convenience
|
||||||
|
bool isOk() const { return status == Status::SUCCESS; }
|
||||||
|
bool isErr() const { return status == Status::ERROR; }
|
||||||
|
};
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
#include "LegacyAdapter.hpp"
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Translation tables
|
||||||
|
//
|
||||||
|
// SIMPLE_MAP: v1 cmd (no action) → v2 cmd
|
||||||
|
// ACTION_MAP: v1 "cmd:action" compound key → v2 cmd
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// Compound key helper — "cmd\0action" stored as two concatenated const char* pairs
|
||||||
|
struct ActionEntry {
|
||||||
|
const char* cmd;
|
||||||
|
const char* action;
|
||||||
|
const char* v2;
|
||||||
|
};
|
||||||
|
|
||||||
|
static const ActionEntry ACTION_MAP[] = {
|
||||||
|
// playback
|
||||||
|
{ "playback", "play", "playback.play" },
|
||||||
|
{ "playback", "stop", "playback.stop" },
|
||||||
|
|
||||||
|
// file_manager
|
||||||
|
{ "file_manager", "list_melodies", "files.list" },
|
||||||
|
{ "file_manager", "download_melody", "files.download" },
|
||||||
|
{ "file_manager", "delete_melody", "files.delete" },
|
||||||
|
|
||||||
|
// relay_setup
|
||||||
|
{ "relay_setup", "set_timings", "relay.set_durations" },
|
||||||
|
{ "relay_setup", "set_outputs", "relay.set_outputs" },
|
||||||
|
|
||||||
|
// clock_setup — generic actions (enabled split handled separately below)
|
||||||
|
{ "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" },
|
||||||
|
|
||||||
|
// system_info
|
||||||
|
{ "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_config" },
|
||||||
|
{ "system_info", "get_all_settings", "system.get_all" },
|
||||||
|
{ "system_info", "get_telemetry", "system.get_telemetry" },
|
||||||
|
// sync_time_to_lcd retired — LCD now uses request/response model
|
||||||
|
{ "system_info", "sync_time_to_lcd", "system.get_time" },
|
||||||
|
|
||||||
|
// bells
|
||||||
|
{ "bells", "enable", "bells.enable" },
|
||||||
|
{ "bells", "disable", "bells.disable" },
|
||||||
|
{ "bells", "get_config", "bells.get_config" },
|
||||||
|
|
||||||
|
// system
|
||||||
|
{ "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", "restart", "system.restart" },
|
||||||
|
{ "system", "reboot", "system.restart" },
|
||||||
|
{ "system", "force_update", "ota.update" },
|
||||||
|
{ "system", "custom_update", "ota.custom" },
|
||||||
|
};
|
||||||
|
|
||||||
|
static constexpr size_t ACTION_MAP_SIZE = sizeof(ACTION_MAP) / sizeof(ACTION_MAP[0]);
|
||||||
|
|
||||||
|
// v1 top-level commands with no "action" field that map 1-to-1
|
||||||
|
struct SimpleEntry {
|
||||||
|
const char* v1;
|
||||||
|
const char* v2;
|
||||||
|
};
|
||||||
|
|
||||||
|
static const SimpleEntry SIMPLE_MAP[] = {
|
||||||
|
{ "ping", "ping" },
|
||||||
|
{ "identify", "identify" },
|
||||||
|
};
|
||||||
|
|
||||||
|
static constexpr size_t SIMPLE_MAP_SIZE = sizeof(SIMPLE_MAP) / sizeof(SIMPLE_MAP[0]);
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
void translateLegacyEnvelope(CommandEnvelope& envelope) {
|
||||||
|
const String& cmd = envelope.command;
|
||||||
|
|
||||||
|
// ── 1. Simple 1-to-1 commands (no action needed) ───────────────────────
|
||||||
|
for (size_t i = 0; i < SIMPLE_MAP_SIZE; ++i) {
|
||||||
|
if (cmd == SIMPLE_MAP[i].v1) {
|
||||||
|
envelope.command = SIMPLE_MAP[i].v2;
|
||||||
|
envelope.version = 2;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 2. Commands that require an "action" field ──────────────────────────
|
||||||
|
// Extract action from contents, strip it, then look up in ACTION_MAP.
|
||||||
|
const char* action = envelope.contents["action"] | "";
|
||||||
|
|
||||||
|
// ── 2a. Special case: clock_setup → set_enabled (boolean split) ─────────
|
||||||
|
if (cmd == "clock_setup" && strcmp(action, "set_enabled") == 0) {
|
||||||
|
bool enabled = envelope.contents["enabled"] | false;
|
||||||
|
envelope.command = enabled ? "clock.enable" : "clock.disable";
|
||||||
|
envelope.contents.remove("action");
|
||||||
|
envelope.contents.remove("enabled");
|
||||||
|
envelope.version = 2;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 2b. Special case: system → set_mqtt_enabled (boolean split) ─────────
|
||||||
|
if (cmd == "system" && strcmp(action, "set_mqtt_enabled") == 0) {
|
||||||
|
bool enabled = envelope.contents["enabled"] | false;
|
||||||
|
envelope.command = enabled ? "mqtt.enable" : "mqtt.disable";
|
||||||
|
envelope.contents.remove("action");
|
||||||
|
envelope.contents.remove("enabled");
|
||||||
|
envelope.version = 2;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 2c. General action-based lookup ─────────────────────────────────────
|
||||||
|
if (action[0] != '\0') {
|
||||||
|
for (size_t i = 0; i < ACTION_MAP_SIZE; ++i) {
|
||||||
|
if (cmd == ACTION_MAP[i].cmd && strcmp(action, ACTION_MAP[i].action) == 0) {
|
||||||
|
envelope.command = ACTION_MAP[i].v2;
|
||||||
|
envelope.contents.remove("action");
|
||||||
|
envelope.version = 2;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 3. Unknown / unmapped — leave command unchanged so the bus returns ──
|
||||||
|
// its normal "Unknown command: ..." error. Mark as v2 so we don't loop.
|
||||||
|
envelope.version = 2;
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// LegacyAdapter — v1 → v2 command translation
|
||||||
|
//
|
||||||
|
// When a client sends { "v": 1 } (or omits "v"), the envelope arrives here
|
||||||
|
// before reaching the CommandBus registry. The adapter maps the old flat/
|
||||||
|
// umbrella command shape to the new namespaced v2 command.
|
||||||
|
//
|
||||||
|
// Translation logic:
|
||||||
|
// 1. If the v1 message has an "action" field inside contents, combine
|
||||||
|
// cmd + action → v2 flat command name, then strip "action" from contents.
|
||||||
|
// 2. If no action, map the top-level cmd name directly (e.g. "ping" → "ping").
|
||||||
|
// 3. Special cases:
|
||||||
|
// - clock_setup → set_enabled uses contents["enabled"] bool to pick
|
||||||
|
// clock.enable vs clock.disable
|
||||||
|
// - system → set_mqtt_enabled uses contents["enabled"] bool to pick
|
||||||
|
// mqtt.enable vs mqtt.disable
|
||||||
|
// - system_info → sync_time_to_lcd is remapped to system.get_time
|
||||||
|
// (LCD now uses request/response; old push model retired)
|
||||||
|
//
|
||||||
|
// To delete legacy support in one PR: remove the #include and the single
|
||||||
|
// call in CommandBus::dispatch(), then delete this file.
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#include "CommandEnvelope.hpp"
|
||||||
|
|
||||||
|
// Translate an envelope whose version == 1 into its v2 equivalent.
|
||||||
|
// Mutates envelope.command and (where needed) envelope.contents in place.
|
||||||
|
// Sets envelope.version = 2 on return.
|
||||||
|
// No-op if the command is already valid v2 (unknown v1 commands are left
|
||||||
|
// unchanged so the bus returns a proper "Unknown command" error).
|
||||||
|
void translateLegacyEnvelope(CommandEnvelope& envelope);
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
#include "LegacyResponseAdapter.hpp"
|
||||||
|
#include "CommandResult.hpp"
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Known v2 → v1 reply divergences.
|
||||||
|
//
|
||||||
|
// Each entry here corresponds to a v2 CommandResult "type" that a v1 client
|
||||||
|
// polls for and parses with hardcoded v1 field names/shapes. Add a new case
|
||||||
|
// only when a real v1 caller is confirmed to depend on the old shape — see
|
||||||
|
// the file header for why this stays a narrow allowlist rather than a
|
||||||
|
// generic mapper.
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// system.status → current_status
|
||||||
|
// v1 app: docs/reference/dart-command-handler.dart SystemInfo.getDeviceStatus()
|
||||||
|
// matches on type=="current_status", reads payload.player_status (lowercase),
|
||||||
|
// payload.time_elapsed, payload.strike_counters as an array.
|
||||||
|
static bool translateSystemStatus(const CommandResult& result, JsonDocument& out) {
|
||||||
|
JsonObjectConst data = result.data.as<JsonObjectConst>();
|
||||||
|
|
||||||
|
out["status"] = "SUCCESS";
|
||||||
|
out["type"] = "current_status";
|
||||||
|
JsonObject payload = out["payload"].to<JsonObject>();
|
||||||
|
|
||||||
|
// v2 sends UPPERCASE enum names (PLAYING/PAUSED/STOPPING/STOPPED/LOADING);
|
||||||
|
// v1 expects lowercase state words, with STOPPED spelled "idle". LOADING
|
||||||
|
// deliberately falls through to "idle" — v1 apps have no loading state and
|
||||||
|
// treat unknown words as "unavailable".
|
||||||
|
const char* v2Status = data["player_status"] | "STOPPED";
|
||||||
|
const char* v1Status = "idle";
|
||||||
|
if (strcmp(v2Status, "PLAYING") == 0) v1Status = "playing";
|
||||||
|
else if (strcmp(v2Status, "PAUSED") == 0) v1Status = "paused";
|
||||||
|
else if (strcmp(v2Status, "STOPPING") == 0) v1Status = "stopping";
|
||||||
|
|
||||||
|
payload["player_status"] = v1Status;
|
||||||
|
payload["time_elapsed"] = data["time_elapsed_ms"] | 0; // same unit (ms), renamed key
|
||||||
|
payload["projected_run_time"] = data["projected_run_time"] | 0;
|
||||||
|
|
||||||
|
// v2 sends strike_counters as an object keyed "0".."15"; v1 expects an array.
|
||||||
|
JsonArray strikes = payload["strike_counters"].to<JsonArray>();
|
||||||
|
JsonObjectConst v2Strikes = data["strike_counters"].as<JsonObjectConst>();
|
||||||
|
for (uint8_t i = 0; i < 16; i++) {
|
||||||
|
strikes.add(v2Strikes[String(i)] | 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool translateLegacyResponse(const CommandResult& result, JsonDocument& out) {
|
||||||
|
if (result.type == "system.status" && result.hasData) {
|
||||||
|
return translateSystemStatus(result, out);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Not a known divergence — caller falls back to standard v2 serialisation.
|
||||||
|
return false;
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// LegacyResponseAdapter — v2 → v1 reply translation
|
||||||
|
//
|
||||||
|
// Companion to LegacyAdapter (which translates v1 *requests* into v2 before
|
||||||
|
// dispatch). This adapter runs the other direction: it takes the v2
|
||||||
|
// CommandResult a handler produced and rewrites it into the wire shape a v1
|
||||||
|
// client expects, but ONLY for replies going back to a client whose original
|
||||||
|
// request came in as v1 (no "v" field, or "v":1).
|
||||||
|
//
|
||||||
|
// Why this exists:
|
||||||
|
// V1 tablets (old Flutter app, pre-refactor) send commands without a "v"
|
||||||
|
// field. LegacyAdapter maps those onto v2 internal commands so the same
|
||||||
|
// handler code services both old and new clients. But v2 handlers reply
|
||||||
|
// using the v2 envelope/field conventions (e.g. "system.status" instead of
|
||||||
|
// "current_status", data nested under "data" instead of "payload",
|
||||||
|
// UPPERCASE status enum strings, "strike_counters" as an object keyed by
|
||||||
|
// index instead of an array). A v1-only app doesn't recognise any of that,
|
||||||
|
// so from its point of view the device never replies — its own
|
||||||
|
// request-timeout logic then marks the device "unavailable" even though it
|
||||||
|
// answered correctly and promptly. See docs/architecture/legacy-response-adapter.md
|
||||||
|
// for the full incident writeup.
|
||||||
|
//
|
||||||
|
// Translation is intentionally narrow: it only rewrites the handful of
|
||||||
|
// fields/types that are actually known to diverge (see the .cpp). It is NOT
|
||||||
|
// a generic v1/v2 schema mapper — anything not explicitly listed here is
|
||||||
|
// passed through unchanged. If a future v2 handler introduces another
|
||||||
|
// diverging reply shape that v1 clients rely on, add a case here rather than
|
||||||
|
// generalising the mechanism.
|
||||||
|
//
|
||||||
|
// This is temporary migration scaffolding, not permanent architecture. Once
|
||||||
|
// fleet telemetry (or "identify" logs) show zero v1 requests for a safe
|
||||||
|
// observation period, delete this adapter, LegacyAdapter, and the call sites
|
||||||
|
// in the transports together in one PR — see
|
||||||
|
// docs/architecture/legacy-response-adapter.md for the exact removal steps.
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#include <ArduinoJson.h>
|
||||||
|
|
||||||
|
struct CommandResult;
|
||||||
|
|
||||||
|
// Rewrites `result` into a v1-shaped reply JsonDocument if (and only if) its
|
||||||
|
// `type` is one this adapter knows how to translate. Returns true and fills
|
||||||
|
// `out` if a translation was applied; returns false (leaving `out`
|
||||||
|
// untouched) if the result should be serialised normally — the caller must
|
||||||
|
// fall back to the standard v2 serialisation in that case.
|
||||||
|
bool translateLegacyResponse(const CommandResult& result, JsonDocument& out);
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
# CommandBus
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
The CommandBus is the dispatch core of the communication layer. It owns a registry of `ICommandHandler` instances keyed by command name, and a list of `ITransport` instances that can receive broadcasts. When a transport receives a message, it parses it into a `CommandEnvelope` and calls `CommandBus::dispatch()`, which does an O(1) map lookup to find the right handler, calls `execute()`, then calls the envelope's reply lambda exactly once with the result. Unsolicited events (bell strikes, telemetry, status changes) are pushed out to all transports via `broadcast()`. The bus has no knowledge of which protocol a message arrived on — that concern lives entirely in the transport's reply lambda.
|
||||||
|
|
||||||
|
This directory also contains four supporting types used everywhere in the communication layer: `CommandEnvelope`, `CommandResult`, `ICommandHandler`, and `LegacyAdapter`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Public API — CommandBus
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `void registerHandler(std::unique_ptr<ICommandHandler> handler)` | Takes ownership of a handler; maps every command name returned by `handler->commands()` to this instance. Duplicate registrations log a warning and the later handler wins. |
|
||||||
|
| `void addTransport(ITransport* transport)` | Registers a non-owning transport pointer for broadcast fan-out. |
|
||||||
|
| `void dispatch(CommandEnvelope& envelope)` | Looks up the handler for `envelope.command`, calls `execute()`, and fires `envelope.reply()` with the result. If no handler is found, replies with an error. Automatically translates v1 envelopes before lookup. |
|
||||||
|
| `void broadcast(const CommandResult& result)` | Serialises `result` to JSON once, then calls `broadcast()` on every registered transport. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Supporting Types
|
||||||
|
|
||||||
|
### CommandEnvelope
|
||||||
|
|
||||||
|
Universal message wrapper produced by each transport before calling `dispatch()`. The transport injects the reply lambda so the bus and handlers never need to know which wire the response goes back on.
|
||||||
|
|
||||||
|
| Field | Type | Description |
|
||||||
|
|-------|------|-------------|
|
||||||
|
| `version` | `uint8_t` | Protocol version: `2` = v2 (default), `1` = legacy |
|
||||||
|
| `transport` | `Transport` enum | `MQTT`, `WEBSOCKET`, `HTTP`, or `UART` |
|
||||||
|
| `clientId` | `uint32_t` | WebSocket client ID; `0` for transports without per-client identity |
|
||||||
|
| `command` | `String` | Flat command name, e.g. `"relay.set_durations"`, `"ping"` |
|
||||||
|
| `contents` | `JsonDocument` | The `"contents"` object from the raw JSON message |
|
||||||
|
| `reply` | `std::function<void(const CommandResult&)>` | Injected by the transport; called exactly once by the bus after dispatch |
|
||||||
|
|
||||||
|
**Wire format (v2):**
|
||||||
|
```json
|
||||||
|
{ "v": 2, "cmd": "namespace.command", "contents": { ... } }
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### CommandResult
|
||||||
|
|
||||||
|
Standardised return value from every `ICommandHandler::execute()` call. Use the static factory methods.
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `static CommandResult ok(type, msg)` | Success with optional human-readable message |
|
||||||
|
| `static CommandResult ok(type, JsonDocument)` | Success with structured JSON data payload |
|
||||||
|
| `static CommandResult err(type, msg)` | Error with required message |
|
||||||
|
| `static CommandResult info(type, msg)` | Unsolicited informational event (used for broadcasts) |
|
||||||
|
| `bool isOk() const` | Returns true if status is `SUCCESS` |
|
||||||
|
| `bool isErr() const` | Returns true if status is `ERROR` |
|
||||||
|
|
||||||
|
Serialised over the wire as:
|
||||||
|
```json
|
||||||
|
{ "status": "SUCCESS|ERROR|INFO", "type": "command_name", "message": "...", "data": { ... } }
|
||||||
|
```
|
||||||
|
`message` is omitted when empty; `data` is omitted when `hasData` is false.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### ICommandHandler
|
||||||
|
|
||||||
|
Interface that all domain handlers implement.
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `virtual std::vector<String> commands() const = 0` | Returns all command names this handler owns. The bus registers all of them at startup. |
|
||||||
|
| `virtual CommandResult execute(const CommandEnvelope& envelope) = 0` | Executes the command and returns a result. Must not call `envelope.reply()` directly — the bus owns that. Must not throw. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### LegacyAdapter
|
||||||
|
|
||||||
|
`translateLegacyEnvelope(CommandEnvelope& envelope)` — translates a v1 envelope into its v2 equivalent in place. Called automatically by `CommandBus::dispatch()` when `envelope.version == 1`. Not part of the public API for new code.
|
||||||
|
|
||||||
|
**Translation rules:**
|
||||||
|
1. Simple 1-to-1 commands (`ping`, `identify`, `playback`) are passed through unchanged.
|
||||||
|
2. Commands with an `"action"` field in `contents` are mapped using a lookup table (e.g. `{ "cmd": "relay_setup", "contents": { "action": "set_timings" } }` → `relay.set_durations`).
|
||||||
|
3. Two boolean-split special cases: `clock_setup/set_enabled` → `clock.enable` or `clock.disable`; `system/set_mqtt_enabled` → `mqtt.enable` or `mqtt.disable`.
|
||||||
|
4. Unknown v1 commands are left unchanged so the bus returns its standard "Unknown command" error.
|
||||||
|
|
||||||
|
To remove legacy support entirely: delete this file and the single `translateLegacyEnvelope()` call in `CommandBus::dispatch()`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Initialization
|
||||||
|
|
||||||
|
The `CommandBus` is a plain value member of `CommunicationRouter` — no explicit initialization required. Handlers are registered via `registerHandlers()` inside `CommunicationRouter::begin()`, which is called from `main.cpp` after all late-bound references have been set via `setXxxReference()`.
|
||||||
|
|
||||||
|
Transports are added to the bus with `addTransport()` inside `CommunicationRouter::begin()`, after each transport's own `begin()` has been called.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
- `ArduinoJson` — for `CommandEnvelope::contents` and `CommandResult::data`
|
||||||
|
- `Logging` — for registration warnings and dispatch debug logs
|
||||||
|
- `ICommandHandler` / `ITransport` interfaces (headers in `Communication/Handlers/` and `Communication/Transport/`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Gotchas / Notes
|
||||||
|
|
||||||
|
- **`std::map` instead of `std::unordered_map`**: Arduino's `String` type has no `std::hash` specialisation, so a tree-map is used. Lookup is O(log n) in practice, though with ~30 commands in the registry this is negligible.
|
||||||
|
- **Duplicate registrations**: If two handlers claim the same command name (e.g. during a refactor), the last one registered wins and a `LOG_WARNING` is emitted. Check serial output at boot to catch this.
|
||||||
|
- **`envelope.reply` is called exactly once**: Handlers must return a `CommandResult` and must not call `envelope.reply()` themselves. If a handler returns without going through the bus (e.g. throws), the client receives no response. Handlers must not throw.
|
||||||
|
- **Broadcast vs reply**: `dispatch()` calls `envelope.reply()` — response goes back to the originating transport/client only. `broadcast()` sends to all transports — used for unsolicited events. These are distinct paths.
|
||||||
|
- **Thread safety**: `CommandBus` has no internal locking. All dispatch calls happen on the main Arduino loop / AsyncWebServer callback thread. Do not call `dispatch()` or `broadcast()` from ISRs or FreeRTOS tasks that run concurrently with the loop.
|
||||||
@@ -0,0 +1,731 @@
|
|||||||
|
/*
|
||||||
|
* CommunicationRouter.cpp — Stage 4 refactor
|
||||||
|
*
|
||||||
|
* Wires CommandBus + transports + handlers.
|
||||||
|
* Old CommandHandler is no longer used.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "CommunicationRouter.hpp"
|
||||||
|
#include <time.h>
|
||||||
|
|
||||||
|
#define TAG "CommRouter"
|
||||||
|
|
||||||
|
// Total size budget for /logs on SD, across all rotated daily files.
|
||||||
|
// Oldest day is pruned first once this is exceeded.
|
||||||
|
static constexpr size_t SD_LOG_MAX_TOTAL_BYTES = 512 * 1024; // 512KB
|
||||||
|
|
||||||
|
#include "../../ConfigManager/ConfigManager.hpp"
|
||||||
|
#include "../../OTAManager/OTAManager.hpp"
|
||||||
|
#include "../../Networking/Networking.hpp"
|
||||||
|
#include "../../Logging/Logging.hpp"
|
||||||
|
#include "../../Player/Player.hpp"
|
||||||
|
#include "../../FileManager/FileManager.hpp"
|
||||||
|
#if HAS_RTC
|
||||||
|
#include "../../TimeKeeper/TimeKeeper.hpp"
|
||||||
|
#endif
|
||||||
|
#include "../../FirmwareValidator/FirmwareValidator.hpp"
|
||||||
|
#include "../../Telemetry/Telemetry.hpp"
|
||||||
|
#include "../../HealthMonitor/HealthMonitor.hpp"
|
||||||
|
#include "../../OutputManager/OutputManager.hpp"
|
||||||
|
|
||||||
|
// Domain handlers
|
||||||
|
#include "../Handlers/PlaybackHandler/PlaybackHandler.hpp"
|
||||||
|
#include "../Handlers/RelayHandler/RelayHandler.hpp"
|
||||||
|
#if HAS_RTC
|
||||||
|
#include "../Handlers/ClockHandler/ClockHandler.hpp"
|
||||||
|
#include "../Handlers/SystemHandler/SystemHandler.hpp"
|
||||||
|
#endif
|
||||||
|
#include "../Handlers/FirmwareHandler/FirmwareHandler.hpp"
|
||||||
|
#include "../Handlers/NetworkHandler/NetworkHandler.hpp"
|
||||||
|
#include "../Handlers/FileHandler/FileHandler.hpp"
|
||||||
|
#include "../Handlers/LoggingHandler/LoggingHandler.hpp"
|
||||||
|
#include "../Handlers/TelemetryHandler/TelemetryHandler.hpp"
|
||||||
|
#include "../Handlers/MQTTHandler/MQTTHandler.hpp"
|
||||||
|
#include "../Handlers/BellsHandler/BellsHandler.hpp"
|
||||||
|
#if HAS_RF
|
||||||
|
#include "../../RFRemote/RFRemoteHandler.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
// Constructor
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
CommunicationRouter::CommunicationRouter(ConfigManager& configManager,
|
||||||
|
OTAManager& otaManager,
|
||||||
|
Networking& networking,
|
||||||
|
AsyncWebServer& server,
|
||||||
|
AsyncWebSocket& webSocket,
|
||||||
|
AsyncUDP& udp)
|
||||||
|
: _configManager(configManager)
|
||||||
|
, _otaManager(otaManager)
|
||||||
|
, _networking(networking)
|
||||||
|
, _server(server)
|
||||||
|
, _webSocket(webSocket)
|
||||||
|
, _udp(udp)
|
||||||
|
// Underlying protocol objects
|
||||||
|
, _mqttClient(configManager, networking)
|
||||||
|
, _clientManager()
|
||||||
|
, _wsServer(webSocket, _clientManager)
|
||||||
|
#if HAS_UART
|
||||||
|
, _uartHandler()
|
||||||
|
#endif
|
||||||
|
// New architecture — transports reference the bus
|
||||||
|
, _bus()
|
||||||
|
, _mqttTransport(_mqttClient, _bus)
|
||||||
|
, _wsTransport(_wsServer, _bus)
|
||||||
|
, _httpTransport(server, _bus, configManager)
|
||||||
|
#if HAS_UART
|
||||||
|
, _uartTransport(_uartHandler, _bus)
|
||||||
|
#endif
|
||||||
|
, _webServerTransport(server, _bus, configManager, networking)
|
||||||
|
{}
|
||||||
|
|
||||||
|
CommunicationRouter::~CommunicationRouter() {}
|
||||||
|
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
// begin()
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
void CommunicationRouter::begin() {
|
||||||
|
LOG_INFO(TAG, "Initializing Communication Router v5.0 (CommandBus)");
|
||||||
|
|
||||||
|
// ── WebSocket ─────────────────────────────────────────────────────────────
|
||||||
|
LOG_INFO(TAG, "Setting up WebSocket transport...");
|
||||||
|
_server.addHandler(&_webSocket);
|
||||||
|
_wsTransport.begin();
|
||||||
|
LOG_INFO(TAG, "WebSocket transport initialised (/ws)");
|
||||||
|
|
||||||
|
// ── MQTT ─────────────────────────────────────────────────────────────────
|
||||||
|
LOG_INFO(TAG, "Setting up MQTT transport...");
|
||||||
|
_mqttTransport.begin();
|
||||||
|
|
||||||
|
Logging::setMqttPublishCallback(
|
||||||
|
[this](const String& topic, const String& payload, int qos) {
|
||||||
|
// Gated by the "logs" topic switch, independent of the per-level
|
||||||
|
// log.set_mqtt setting — this lets an operator turn the whole
|
||||||
|
// system/logs channel off without touching the configured level,
|
||||||
|
// and turn it back on later with the level untouched.
|
||||||
|
if (!_configManager.getMqttTopicConfig().logs) return;
|
||||||
|
_mqttClient.publishDirect(topic, payload, qos, false);
|
||||||
|
},
|
||||||
|
_mqttClient.getLogsTopic()
|
||||||
|
);
|
||||||
|
|
||||||
|
Logging::setSerialLevel((Logging::LogLevel)_configManager.getSerialLogLevel());
|
||||||
|
Logging::setMqttLevel((Logging::LogLevel)_configManager.getMqttLogLevel());
|
||||||
|
Logging::setSdLevel((Logging::LogLevel)_configManager.getSdLogLevel());
|
||||||
|
LOG_INFO(TAG, "Log levels applied — Serial:%d MQTT:%d SD:%d",
|
||||||
|
_configManager.getSerialLogLevel(),
|
||||||
|
_configManager.getMqttLogLevel(),
|
||||||
|
_configManager.getSdLogLevel());
|
||||||
|
|
||||||
|
// Suppress internal-plumbing subsystems on MQTT to prevent feedback loops
|
||||||
|
Logging::setSubsystemMqttLevel("MQTTClient", Logging::NONE);
|
||||||
|
Logging::setSubsystemMqttLevel("CommRouter", Logging::WARNING);
|
||||||
|
Logging::setSubsystemMqttLevel("Logger", Logging::NONE);
|
||||||
|
|
||||||
|
// Per-subsystem MQTT caps: keep remote logs signal-rich, not noisy
|
||||||
|
Logging::setSubsystemMqttLevel("BellEngine", Logging::WARNING); // per-note strike spam
|
||||||
|
Logging::setSubsystemMqttLevel("OutputManager", Logging::WARNING); // per-note extinguish spam
|
||||||
|
Logging::setSubsystemMqttLevel("HealthMonitor", Logging::WARNING); // periodic check spam
|
||||||
|
Logging::setSubsystemMqttLevel("ConfigManager", Logging::WARNING); // NVS read spam
|
||||||
|
Logging::setSubsystemMqttLevel("Player", Logging::INFO); // state transitions useful
|
||||||
|
Logging::setSubsystemMqttLevel("Telemetry", Logging::INFO); // load data useful
|
||||||
|
Logging::setSubsystemMqttLevel("OTAManager", Logging::INFO); // update events important
|
||||||
|
|
||||||
|
_mqttClient.setOnConnectCallback([this](bool /*sessionPresent*/) {
|
||||||
|
reportBootOnce();
|
||||||
|
|
||||||
|
// status/playback is retained: if the board lost power (or the link)
|
||||||
|
// mid-melody, the broker would keep serving "playing" indefinitely.
|
||||||
|
// Overwrite it with the Player's real state on EVERY connect — normally
|
||||||
|
// "idle" after a reboot, the live state after a plain reconnect.
|
||||||
|
if (_player) publishPlayback(_player->getPlaybackSnapshot());
|
||||||
|
});
|
||||||
|
|
||||||
|
// Heartbeat state/ok derivation — independently derived per the topic spec,
|
||||||
|
// not mirrored from status/playback or system/alerts. _player and
|
||||||
|
// _healthMonitor are late-bound (set after begin() via setXxxReference()),
|
||||||
|
// so this lambda captures `this` and reads them at call time, not at
|
||||||
|
// registration time — safe because the heartbeat timer only starts once
|
||||||
|
// MQTT connects, which is always well after main.cpp finishes wiring.
|
||||||
|
_mqttClient.setStateProvider([this]() -> MQTTDriver::DeviceState {
|
||||||
|
if (!_player) return MQTTDriver::DeviceState{"booting", true};
|
||||||
|
|
||||||
|
String state = _player->isCurrentlyPlaying() ? "playing"
|
||||||
|
: _player->isCurrentlyPaused() ? "paused"
|
||||||
|
: "idle";
|
||||||
|
bool ok = _healthMonitor ? _healthMonitor->isFirmwareStable() : true;
|
||||||
|
return MQTTDriver::DeviceState{state, ok};
|
||||||
|
});
|
||||||
|
|
||||||
|
LOG_INFO(TAG, "MQTT transport initialised");
|
||||||
|
|
||||||
|
// ── HTTP ─────────────────────────────────────────────────────────────────
|
||||||
|
LOG_INFO(TAG, "Setting up HTTP transport...");
|
||||||
|
_httpTransport.begin();
|
||||||
|
LOG_INFO(TAG, "HTTP transport initialised");
|
||||||
|
|
||||||
|
// ── Settings Web Server (4th transport — Stage 6)
|
||||||
|
LOG_INFO(TAG, "Setting up WebServer transport...");
|
||||||
|
_webServerTransport.begin();
|
||||||
|
LOG_INFO(TAG, "WebServer transport initialised (/settings)");
|
||||||
|
|
||||||
|
// ── UART ─────────────────────────────────────────────────────────────────
|
||||||
|
#if HAS_UART
|
||||||
|
LOG_INFO(TAG, "Setting up UART transport...");
|
||||||
|
_uartTransport.begin();
|
||||||
|
LOG_INFO(TAG, "UART transport initialised");
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// ── Register transports with the bus ─────────────────────────────────────
|
||||||
|
_bus.addTransport(&_mqttTransport);
|
||||||
|
_bus.addTransport(&_wsTransport);
|
||||||
|
_bus.addTransport(&_httpTransport);
|
||||||
|
#if HAS_UART
|
||||||
|
_bus.addTransport(&_uartTransport);
|
||||||
|
#endif
|
||||||
|
_bus.addTransport(&_webServerTransport);
|
||||||
|
|
||||||
|
// ── 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");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
// loop()
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
void CommunicationRouter::loop() {
|
||||||
|
#if HAS_UART
|
||||||
|
_uartTransport.loop();
|
||||||
|
#endif
|
||||||
|
reportDiagnosticsIfDue();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
// Late-bound reference setters
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
void CommunicationRouter::setPlayerReference(Player* player) {
|
||||||
|
_player = player;
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommunicationRouter::setFileManagerReference(FileManager* fm) {
|
||||||
|
_fileManager = fm;
|
||||||
|
|
||||||
|
if (fm != nullptr) {
|
||||||
|
Logging::setSdWriteCallback([fm](const String& line) {
|
||||||
|
// Day-rotated: /logs/YYYY-MM-DD.log, capped at SD_LOG_MAX_TOTAL_BYTES
|
||||||
|
// total across the directory (oldest day pruned first).
|
||||||
|
fm->appendLogLine("/logs", line, time(nullptr), SD_LOG_MAX_TOTAL_BYTES);
|
||||||
|
});
|
||||||
|
LOG_INFO(TAG, "SD log channel registered -> /logs/YYYY-MM-DD.log (cap: %u bytes)", (unsigned)SD_LOG_MAX_TOTAL_BYTES);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#if HAS_RTC
|
||||||
|
void CommunicationRouter::setTimeKeeperReference(Timekeeper* tk) {
|
||||||
|
_timeKeeper = tk;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
void CommunicationRouter::setFirmwareValidatorReference(FirmwareValidator* fv) {
|
||||||
|
_firmwareValidator = fv;
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommunicationRouter::setTelemetryReference(Telemetry* telemetry) {
|
||||||
|
_telemetry = telemetry;
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommunicationRouter::setHealthMonitorReference(HealthMonitor* hm) {
|
||||||
|
_healthMonitor = hm;
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommunicationRouter::setOutputManagerReference(OutputManager* om) {
|
||||||
|
_outputManager = om;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if HAS_RF
|
||||||
|
void CommunicationRouter::setRFRemoteReference(RFRemote* rf) {
|
||||||
|
_rfRemote = rf;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
// registerHandlers()
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
void CommunicationRouter::registerHandlers() {
|
||||||
|
// Log any missing optional dependencies so issues surface at boot, not later.
|
||||||
|
if (!_player) LOG_ERROR(TAG, "registerHandlers: _player is null — PlaybackHandler, RelayHandler, FirmwareHandler, SystemHandler skipped");
|
||||||
|
if (!_fileManager) LOG_ERROR(TAG, "registerHandlers: _fileManager is null — FileHandler skipped");
|
||||||
|
#if HAS_RTC
|
||||||
|
if (!_timeKeeper) LOG_ERROR(TAG, "registerHandlers: _timeKeeper is null — ClockHandler skipped");
|
||||||
|
#endif
|
||||||
|
if (!_firmwareValidator) LOG_ERROR(TAG, "registerHandlers: _firmwareValidator is null — FirmwareHandler skipped");
|
||||||
|
if (!_telemetry) LOG_ERROR(TAG, "registerHandlers: _telemetry is null — TelemetryHandler and SystemHandler skipped");
|
||||||
|
if (!_healthMonitor) LOG_WARNING(TAG, "registerHandlers: _healthMonitor is null — system.health unavailable");
|
||||||
|
if (!_outputManager) LOG_ERROR(TAG, "registerHandlers: _outputManager is null — RelayHandler skipped");
|
||||||
|
|
||||||
|
// Playback
|
||||||
|
if (_player) {
|
||||||
|
_bus.registerHandler(std::make_unique<PlaybackHandler>(*_player));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Relay
|
||||||
|
if (_player && _outputManager) {
|
||||||
|
_bus.registerHandler(std::make_unique<RelayHandler>(_configManager, *_outputManager, *_player));
|
||||||
|
}
|
||||||
|
|
||||||
|
#if HAS_RTC
|
||||||
|
// Clock
|
||||||
|
if (_timeKeeper) {
|
||||||
|
_bus.registerHandler(std::make_unique<ClockHandler>(_configManager, *_timeKeeper, _outputManager));
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// System — requires player, telemetry, healthMonitor, timeKeeper, clientManager
|
||||||
|
#if HAS_RTC
|
||||||
|
if (_player && _telemetry && _healthMonitor && _timeKeeper) {
|
||||||
|
_bus.registerHandler(std::make_unique<SystemHandler>(
|
||||||
|
_configManager, *_player, *_telemetry, *_healthMonitor,
|
||||||
|
*_timeKeeper, _clientManager));
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Firmware / OTA
|
||||||
|
if (_firmwareValidator && _player) {
|
||||||
|
_bus.registerHandler(std::make_unique<FirmwareHandler>(
|
||||||
|
*_firmwareValidator, _otaManager, *_player, _configManager));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Network — no optional dependencies
|
||||||
|
_bus.registerHandler(std::make_unique<NetworkHandler>(_configManager, _networking));
|
||||||
|
|
||||||
|
// File
|
||||||
|
if (_fileManager) {
|
||||||
|
_bus.registerHandler(std::make_unique<FileHandler>(*_fileManager));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Logging — FileManager optional; logs.list/logs.download degrade gracefully without it
|
||||||
|
_bus.registerHandler(std::make_unique<LoggingHandler>(_configManager, _fileManager));
|
||||||
|
|
||||||
|
// Telemetry
|
||||||
|
if (_telemetry) {
|
||||||
|
_bus.registerHandler(std::make_unique<TelemetryHandler>(*_telemetry, _otaManager, _networking));
|
||||||
|
}
|
||||||
|
|
||||||
|
// MQTT control (enable / disable / get_config)
|
||||||
|
_bus.registerHandler(std::make_unique<MQTTHandler>(_configManager, _mqttClient));
|
||||||
|
|
||||||
|
// Bell mechanism master switch
|
||||||
|
_bus.registerHandler(std::make_unique<BellsHandler>(_configManager));
|
||||||
|
|
||||||
|
#if HAS_RF
|
||||||
|
// RF remote control
|
||||||
|
if (_rfRemote) {
|
||||||
|
_bus.registerHandler(std::make_unique<RFRemoteHandler>(*_rfRemote));
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
LOG_INFO(TAG, "All domain handlers registered on CommandBus");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
// UDP Discovery
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
void CommunicationRouter::setupUdpDiscovery() {
|
||||||
|
uint16_t discoveryPort = _configManager.getNetworkConfig().discoveryPort;
|
||||||
|
if (_udp.listen(discoveryPort)) {
|
||||||
|
LOG_INFO(TAG, "UDP discovery listening on port %u", discoveryPort);
|
||||||
|
|
||||||
|
_udp.onPacket([this](AsyncUDPPacket packet) {
|
||||||
|
String msg = String((const char*)packet.data(), packet.length());
|
||||||
|
LOG_DEBUG(TAG, "UDP from %s:%u -> %s",
|
||||||
|
packet.remoteIP().toString().c_str(),
|
||||||
|
packet.remotePort(),
|
||||||
|
msg.c_str());
|
||||||
|
|
||||||
|
bool shouldReply = false;
|
||||||
|
if (msg.indexOf("discover") >= 0) {
|
||||||
|
shouldReply = true;
|
||||||
|
} else {
|
||||||
|
JsonDocument req;
|
||||||
|
if (!deserializeJson(req, msg)) {
|
||||||
|
shouldReply = (req["op"] == "discover");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!shouldReply) return;
|
||||||
|
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["op"] = "discover_reply";
|
||||||
|
doc["svc"] = "vesper";
|
||||||
|
doc["ver"] = 1;
|
||||||
|
doc["name"] = "Proj. Vesper v2.0";
|
||||||
|
doc["id"] = _configManager.getDeviceUID();
|
||||||
|
doc["ip"] = _networking.getLocalIP();
|
||||||
|
doc["port"] = 80;
|
||||||
|
doc["fw"] = "2.0";
|
||||||
|
doc["clients"] = _clientManager.getClientCount();
|
||||||
|
|
||||||
|
char wsUrl[64];
|
||||||
|
snprintf(wsUrl, sizeof(wsUrl), "ws://%s:80/ws", _networking.getLocalIP().c_str());
|
||||||
|
doc["ws"] = wsUrl;
|
||||||
|
|
||||||
|
String out;
|
||||||
|
serializeJson(doc, out);
|
||||||
|
_udp.writeTo((const uint8_t*)out.c_str(), out.length(),
|
||||||
|
packet.remoteIP(), packet.remotePort());
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
LOG_ERROR(TAG, "Failed to start UDP discovery");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
// Status
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
bool CommunicationRouter::isMqttConnected() const {
|
||||||
|
return _mqttClient.isConnected();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CommunicationRouter::hasActiveWebSocketClients() const {
|
||||||
|
return _wsTransport.hasClients();
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t CommunicationRouter::getWebSocketClientCount() const {
|
||||||
|
return _wsTransport.getClientCount();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CommunicationRouter::isHealthy() const {
|
||||||
|
#if HAS_RTC
|
||||||
|
if (!_player || !_timeKeeper) {
|
||||||
|
LOG_WARNING(TAG, "Unhealthy — missing subsystem references (player=%d timeKeeper=%d)",
|
||||||
|
_player != nullptr, _timeKeeper != nullptr);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
if (!_player) {
|
||||||
|
LOG_WARNING(TAG, "Unhealthy — missing subsystem references (player=%d)",
|
||||||
|
_player != nullptr);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
if (!_networking.isConnected()) {
|
||||||
|
LOG_WARNING(TAG, "Unhealthy — no network connection");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!isMqttConnected() && !hasActiveWebSocketClients()) {
|
||||||
|
LOG_WARNING(TAG, "Unhealthy — no active connections (MQTT=%d WS=%d)",
|
||||||
|
isMqttConnected(), hasActiveWebSocketClients());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
// Broadcast helpers
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
void CommunicationRouter::broadcastStatus(const String& message) {
|
||||||
|
// WebSocket-only. MQTT publishing for the same events now goes through
|
||||||
|
// the dedicated topic methods (publishPlayback, publishReport, etc.) —
|
||||||
|
// see docs/reference/vesper_mqtt_topic_spec_v2.md. Kept as a WS fan-out
|
||||||
|
// helper for callers that don't need MQTT at all.
|
||||||
|
_wsTransport.broadcast(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommunicationRouter::broadcastStatus(const JsonDocument& statusJson) {
|
||||||
|
String msg;
|
||||||
|
serializeJson(statusJson, msg);
|
||||||
|
broadcastStatus(msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommunicationRouter::broadcastToMasterClients(const String& message) {
|
||||||
|
_wsTransport.broadcastToMasters(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommunicationRouter::broadcastToSecondaryClients(const String& message) {
|
||||||
|
_wsTransport.broadcastToSecondary(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommunicationRouter::broadcastToAllWebSocketClients(const String& message) {
|
||||||
|
_wsTransport.broadcast(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommunicationRouter::broadcastToAllWebSocketClients(const JsonDocument& message) {
|
||||||
|
String msg;
|
||||||
|
serializeJson(message, msg);
|
||||||
|
_wsTransport.broadcast(msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
// Bell overload notification
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
void CommunicationRouter::sendBellOverloadNotification(
|
||||||
|
const std::vector<uint8_t>& bellNumbers,
|
||||||
|
const std::vector<uint16_t>& bellLoads,
|
||||||
|
const String& severity) {
|
||||||
|
|
||||||
|
// WS clients keep the existing shape (unchanged transport, untouched per
|
||||||
|
// the refactor's scope).
|
||||||
|
JsonDocument wsDoc;
|
||||||
|
wsDoc["status"] = "INFO";
|
||||||
|
wsDoc["type"] = "bell_overload";
|
||||||
|
|
||||||
|
JsonArray wsBells = wsDoc["payload"]["bells"].to<JsonArray>();
|
||||||
|
JsonArray wsLoads = wsDoc["payload"]["loads"].to<JsonArray>();
|
||||||
|
for (size_t i = 0; i < bellNumbers.size() && i < bellLoads.size(); ++i) {
|
||||||
|
wsBells.add(bellNumbers[i] + 1);
|
||||||
|
wsLoads.add(bellLoads[i]);
|
||||||
|
}
|
||||||
|
wsDoc["payload"]["severity"] = severity;
|
||||||
|
broadcastStatus(wsDoc);
|
||||||
|
|
||||||
|
// MQTT gets the dedicated control/reports topic — critical, unsolicited,
|
||||||
|
// board-initiated events that need to be read now.
|
||||||
|
JsonDocument reportPayload;
|
||||||
|
JsonArray bellsArr = reportPayload["bells"].to<JsonArray>();
|
||||||
|
JsonArray loadsArr = reportPayload["loads"].to<JsonArray>();
|
||||||
|
for (size_t i = 0; i < bellNumbers.size() && i < bellLoads.size(); ++i) {
|
||||||
|
bellsArr.add(bellNumbers[i] + 1);
|
||||||
|
loadsArr.add(bellLoads[i]);
|
||||||
|
}
|
||||||
|
reportPayload["severity"] = severity;
|
||||||
|
publishReport("bell_overload", reportPayload);
|
||||||
|
|
||||||
|
LOG_WARNING(TAG, "Bell overload notification sent: %d bells, severity: %s",
|
||||||
|
bellNumbers.size(), severity.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
// Playback failed notification
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
void CommunicationRouter::sendPlaybackFailedNotification(const String& pid, const String& reason) {
|
||||||
|
JsonDocument payload;
|
||||||
|
payload["pid"] = pid;
|
||||||
|
payload["reason"] = reason;
|
||||||
|
|
||||||
|
JsonDocument wsDoc;
|
||||||
|
wsDoc["status"] = "INFO";
|
||||||
|
wsDoc["type"] = "playback_failed";
|
||||||
|
wsDoc["payload"] = payload;
|
||||||
|
broadcastStatus(wsDoc);
|
||||||
|
|
||||||
|
publishReport("playback_failed", payload);
|
||||||
|
LOG_WARNING(TAG, "Playback failed notification sent: %s — %s", pid.c_str(), reason.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
// Alert / Info publishing
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
void CommunicationRouter::publishAlert(const String& subsystem, const String& newState, const String& message) {
|
||||||
|
if (!_mqttClient.isConnected()) return;
|
||||||
|
if (!_configManager.getMqttTopicConfig().alerts) return;
|
||||||
|
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["subsystem"] = subsystem;
|
||||||
|
doc["state"] = newState;
|
||||||
|
if (!message.isEmpty()) {
|
||||||
|
doc["msg"] = message;
|
||||||
|
}
|
||||||
|
|
||||||
|
String out;
|
||||||
|
serializeJson(doc, out);
|
||||||
|
// Retained until cleared — a late-connecting console (fleet webserver)
|
||||||
|
// immediately sees the last unresolved alert per subsystem. A CLEARED
|
||||||
|
// publish (empty message, state="CLEARED") overwrites the retained
|
||||||
|
// message with the resolved state, same retain semantics.
|
||||||
|
_mqttClient.publishDirect(_mqttClient.getAlertsTopic(), out, 1, true);
|
||||||
|
LOG_DEBUG(TAG, "Alert published: %s → %s", subsystem.c_str(), newState.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommunicationRouter::reportBootOnce() {
|
||||||
|
if (_bootReasonReported || !_telemetry) return;
|
||||||
|
_bootReasonReported = true;
|
||||||
|
|
||||||
|
String reason = _telemetry->getResetReasonString();
|
||||||
|
bool isFault = _telemetry->isFaultReset();
|
||||||
|
|
||||||
|
// Existing fault alert — unchanged trigger condition and topic, so consoles
|
||||||
|
// already handling this WARNING keep working as-is.
|
||||||
|
if (isFault) {
|
||||||
|
publishAlert("System", "WARNING", "Device reset due to fault: " + reason);
|
||||||
|
LOG_WARNING(TAG, "Fault reset reported: %s", reason.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Consolidated boot report — always published, fault or not. Single place
|
||||||
|
// a console needs to watch for "device rebooted" plus everything useful
|
||||||
|
// about why: lifetime boot count, reset reason, and (if the last reset was
|
||||||
|
// a crash with a coredump available) the faulting task/PC/exception detail.
|
||||||
|
JsonDocument payload;
|
||||||
|
payload["boot_count"] = _telemetry->getLifetimeBootCount();
|
||||||
|
payload["reset_reason"] = reason;
|
||||||
|
payload["is_fault"] = isFault;
|
||||||
|
payload["free_heap"] = (uint32_t)ESP.getFreeHeap();
|
||||||
|
|
||||||
|
const CrashReport& crash = _telemetry->getCrashReport();
|
||||||
|
if (crash.available) {
|
||||||
|
JsonObject crashObj = payload["crash"].to<JsonObject>();
|
||||||
|
crashObj["task"] = crash.taskName;
|
||||||
|
crashObj["pc"] = crash.pc;
|
||||||
|
crashObj["exc_cause"] = crash.excCause;
|
||||||
|
crashObj["exc_vaddr"] = crash.excVaddr;
|
||||||
|
}
|
||||||
|
|
||||||
|
publishInfo("boot_report", payload);
|
||||||
|
LOG_INFO(TAG, "Boot report published: count=%lu reason=%s%s",
|
||||||
|
_telemetry->getLifetimeBootCount(), reason.c_str(),
|
||||||
|
crash.available ? " (crash detail included)" : "");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Diagnostics report — batched every DIAGNOSTICS_REPORT_INTERVAL_MS (5 min).
|
||||||
|
// Deliberately separate from the 30s heartbeat: temperature/stack/WiFi-
|
||||||
|
// reconnect/OTA state don't need 30s freshness, and the heartbeat already
|
||||||
|
// fires forever, per device, at fleet scale — adding heavier/rarer-need
|
||||||
|
// fields there is a permanent cost paid whether or not anyone's watching.
|
||||||
|
// Temperature is locally sampled every 15s by Telemetry::sampleDiagnosticsIfDue()
|
||||||
|
// (called from TelemetryTask's own loop) and reduced to min/max/avg here, so a
|
||||||
|
// short-lived spike between two 5-minute reports still gets caught — the other
|
||||||
|
// three fields (stack high-water, WiFi reconnects, OTA state) are monotonic/
|
||||||
|
// cumulative counters where a single read at report time is exactly as
|
||||||
|
// informative as continuous sampling would be. See docs/features/feature-catalog.md.
|
||||||
|
void CommunicationRouter::reportDiagnosticsIfDue() {
|
||||||
|
if (!_telemetry) return;
|
||||||
|
uint32_t now = millis();
|
||||||
|
if (now - _lastDiagnosticsReportMs < DIAGNOSTICS_REPORT_INTERVAL_MS) return;
|
||||||
|
_lastDiagnosticsReportMs = now;
|
||||||
|
|
||||||
|
JsonDocument payload;
|
||||||
|
|
||||||
|
// CPU temperature — min/max/avg since the last report. Captured before
|
||||||
|
// reset() so this report gets the full accumulated window.
|
||||||
|
uint16_t tempSampleCount = _telemetry->getTemperatureStats().count;
|
||||||
|
_telemetry->writeTemperatureStats(payload);
|
||||||
|
_telemetry->resetDiagnosticsStats();
|
||||||
|
|
||||||
|
// WiFi reconnects — lifetime this boot, plus last disconnect reason/time.
|
||||||
|
JsonObject wifiObj = payload["wifi_reconnects"].to<JsonObject>();
|
||||||
|
wifiObj["lifetime_count"] = _networking.getReconnectCount();
|
||||||
|
wifiObj["last_reason"] = _networking.getLastDisconnectReason();
|
||||||
|
wifiObj["last_at_uptime_ms"] = _networking.getLastDisconnectUptimeMs();
|
||||||
|
|
||||||
|
// OTA — current/available version, update-available flag, last check, last error.
|
||||||
|
JsonObject otaObj = payload["ota"].to<JsonObject>();
|
||||||
|
otaObj["current_version"] = _otaManager.getCurrentVersion().toString();
|
||||||
|
otaObj["update_available"] = _otaManager.isUpdateAvailable();
|
||||||
|
if (_otaManager.isUpdateAvailable()) {
|
||||||
|
otaObj["available_version"] = _otaManager.getAvailableVersion().toString();
|
||||||
|
}
|
||||||
|
otaObj["last_check_uptime_ms"] = _otaManager.getLastCheckUptimeMs();
|
||||||
|
otaObj["last_error"] = OTAManager::errorCodeToString(_otaManager.getLastError());
|
||||||
|
|
||||||
|
// Stack high-water mark — bytes free, per registered task (TelemetryTask,
|
||||||
|
// HealthMonitor, etc. — see Telemetry::registerTaskForStackMonitoring()).
|
||||||
|
JsonObject stackObj = payload["stack_high_water"].to<JsonObject>();
|
||||||
|
Telemetry::writeStackHighWaterMarks(stackObj);
|
||||||
|
|
||||||
|
// Bell strike counts and heat load — the "bell heat ratings" the topic
|
||||||
|
// spec calls out explicitly for system/metrics.
|
||||||
|
JsonObject strikesObj = payload["bell_strikes"].to<JsonObject>();
|
||||||
|
JsonObject loadsObj = payload["bell_loads"].to<JsonObject>();
|
||||||
|
for (uint8_t i = 0; i < 16; i++) {
|
||||||
|
strikesObj[String(i)] = _telemetry->getStrikeCount(i);
|
||||||
|
loadsObj[String(i)] = _telemetry->getBellLoad(i);
|
||||||
|
}
|
||||||
|
payload["cooling_active"] = _telemetry->isCoolingActive();
|
||||||
|
|
||||||
|
publishMetrics(payload);
|
||||||
|
LOG_INFO(TAG, "Diagnostics/metrics report published (temp samples=%u, wifi_reconnects=%lu)",
|
||||||
|
tempSampleCount, _networking.getReconnectCount());
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommunicationRouter::publishInfo(const String& type, const JsonDocument& payload) {
|
||||||
|
if (!_mqttClient.isConnected()) return;
|
||||||
|
if (!_configManager.getMqttTopicConfig().info) return;
|
||||||
|
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["type"] = type;
|
||||||
|
if (!payload.isNull()) {
|
||||||
|
doc["payload"] = payload;
|
||||||
|
}
|
||||||
|
|
||||||
|
String out;
|
||||||
|
serializeJson(doc, out);
|
||||||
|
_mqttClient.publishDirect(_mqttClient.getInfoTopic(), out, 1, true);
|
||||||
|
LOG_DEBUG(TAG, "Info published: %s", type.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommunicationRouter::publishPlayback(const PlaybackSnapshot& snapshot) {
|
||||||
|
if (!_mqttClient.isConnected()) return;
|
||||||
|
if (!_configManager.getMqttTopicConfig().playback) return;
|
||||||
|
if (!_mqttClient.hasHeapForPublish()) return; // skip building the JsonDocument too, not just the publish
|
||||||
|
|
||||||
|
JsonDocument doc;
|
||||||
|
snapshot.writeTo(doc.to<JsonObject>());
|
||||||
|
|
||||||
|
String out;
|
||||||
|
serializeJson(doc, out);
|
||||||
|
_mqttClient.publishDirect(_mqttClient.getPlaybackTopic(), out, 1, true);
|
||||||
|
LOG_DEBUG(TAG, "Playback published: %s", snapshot.action);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommunicationRouter::publishReport(const String& type, const JsonDocument& payload) {
|
||||||
|
if (!_mqttClient.isConnected()) return;
|
||||||
|
if (!_configManager.getMqttTopicConfig().reports) return;
|
||||||
|
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["type"] = type;
|
||||||
|
if (!payload.isNull()) {
|
||||||
|
doc["payload"] = payload;
|
||||||
|
}
|
||||||
|
|
||||||
|
String out;
|
||||||
|
serializeJson(doc, out);
|
||||||
|
// Not retained — an event stream of critical-but-transient reports, not a
|
||||||
|
// status snapshot. A late subscriber doesn't need old reports replayed.
|
||||||
|
_mqttClient.publishDirect(_mqttClient.getReportsTopic(), out, 1, false);
|
||||||
|
LOG_DEBUG(TAG, "Report published: %s", type.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommunicationRouter::publishMetrics(const JsonDocument& payload) {
|
||||||
|
if (!_mqttClient.isConnected()) return;
|
||||||
|
if (!_configManager.getMqttTopicConfig().metrics) return;
|
||||||
|
|
||||||
|
String out;
|
||||||
|
serializeJson(payload, out);
|
||||||
|
_mqttClient.publishDirect(_mqttClient.getMetricsTopic(), out, 0, false);
|
||||||
|
LOG_DEBUG(TAG, "Metrics published");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
// Network state callbacks
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
void CommunicationRouter::onNetworkConnected() {
|
||||||
|
LOG_DEBUG(TAG, "Network connected — notifying MQTT transport");
|
||||||
|
_mqttTransport.onNetworkConnected();
|
||||||
|
}
|
||||||
|
|
||||||
|
void CommunicationRouter::onNetworkDisconnected() {
|
||||||
|
LOG_DEBUG(TAG, "Network disconnected — notifying MQTT transport");
|
||||||
|
_mqttTransport.onNetworkDisconnected();
|
||||||
|
}
|
||||||
@@ -0,0 +1,250 @@
|
|||||||
|
/*
|
||||||
|
* CommunicationRouter.hpp — Stage 4 refactor
|
||||||
|
*
|
||||||
|
* The router is now a thin coordinator:
|
||||||
|
* • Owns the CommandBus and four transports (MQTT, WS, HTTP, UART)
|
||||||
|
* • Owns the underlying legacy protocol objects (MQTTDriver, etc.)
|
||||||
|
* so the rest of the codebase doesn't need to change
|
||||||
|
* • Registers all domain handlers in registerHandlers()
|
||||||
|
* • Exposes the same public API as before so main.cpp is unchanged
|
||||||
|
*
|
||||||
|
* The old CommandHandler and HTTPRequestHandler have been deleted.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <ESPAsyncWebServer.h>
|
||||||
|
#include <AsyncUDP.h>
|
||||||
|
#include <ArduinoJson.h>
|
||||||
|
|
||||||
|
// Underlying protocol drivers (still owned here)
|
||||||
|
#include "../Drivers/MQTTDriver/MQTTDriver.hpp"
|
||||||
|
#include "../Drivers/WebSocketDriver/WebSocketDriver.hpp"
|
||||||
|
#if HAS_UART
|
||||||
|
#include "../Drivers/UARTDriver/UARTDriver.hpp"
|
||||||
|
#endif
|
||||||
|
#include "../../ClientManager/ClientManager.hpp"
|
||||||
|
|
||||||
|
// New architecture
|
||||||
|
#include "../CommandBus/CommandBus.hpp"
|
||||||
|
#include "../Transport/MQTTTransport/MQTTTransport.hpp"
|
||||||
|
#include "../Transport/WebSocketTransport/WebSocketTransport.hpp"
|
||||||
|
#include "../Transport/HTTPTransport/HTTPTransport.hpp"
|
||||||
|
#if HAS_UART
|
||||||
|
#include "../Transport/UARTTransport/UARTTransport.hpp"
|
||||||
|
#endif
|
||||||
|
#include "../Transport/WebServerTransport/WebServerTransport.hpp"
|
||||||
|
|
||||||
|
#include "../../OTAManager/OTAManager.hpp" // needed for OTAManager::ErrorCode in otaErrorCodeToString()
|
||||||
|
#include "../../Player/PlaybackState.hpp" // PlaybackSnapshot for publishPlayback()
|
||||||
|
|
||||||
|
// Forward declarations — resolved in .cpp
|
||||||
|
class ConfigManager;
|
||||||
|
class Player;
|
||||||
|
class FileManager;
|
||||||
|
#if HAS_RTC
|
||||||
|
class Timekeeper;
|
||||||
|
#endif
|
||||||
|
class Networking;
|
||||||
|
class FirmwareValidator;
|
||||||
|
class Telemetry;
|
||||||
|
class HealthMonitor;
|
||||||
|
class OutputManager;
|
||||||
|
#if HAS_RF
|
||||||
|
class RFRemote;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
class CommunicationRouter {
|
||||||
|
public:
|
||||||
|
// Same constructor signature as before — main.cpp is unchanged.
|
||||||
|
explicit CommunicationRouter(ConfigManager& configManager,
|
||||||
|
OTAManager& otaManager,
|
||||||
|
Networking& networking,
|
||||||
|
AsyncWebServer& server,
|
||||||
|
AsyncWebSocket& webSocket,
|
||||||
|
AsyncUDP& udp);
|
||||||
|
|
||||||
|
~CommunicationRouter();
|
||||||
|
|
||||||
|
void begin();
|
||||||
|
void loop();
|
||||||
|
|
||||||
|
// Late-bound references — called by main.cpp after construction.
|
||||||
|
// registerHandlers() is deferred until begin() is called after all
|
||||||
|
// setXxxReference() calls have been made.
|
||||||
|
void setPlayerReference(Player* player);
|
||||||
|
void setFileManagerReference(FileManager* fm);
|
||||||
|
#if HAS_RTC
|
||||||
|
void setTimeKeeperReference(Timekeeper* tk);
|
||||||
|
#endif
|
||||||
|
void setFirmwareValidatorReference(FirmwareValidator* fv);
|
||||||
|
void setTelemetryReference(Telemetry* telemetry);
|
||||||
|
void setHealthMonitorReference(HealthMonitor* hm);
|
||||||
|
void setOutputManagerReference(OutputManager* om);
|
||||||
|
#if HAS_RF
|
||||||
|
void setRFRemoteReference(RFRemote* rf);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// UDP discovery (called by main.cpp)
|
||||||
|
void setupUdpDiscovery();
|
||||||
|
|
||||||
|
// Status
|
||||||
|
bool isMqttConnected() const;
|
||||||
|
bool hasActiveWebSocketClients() const;
|
||||||
|
size_t getWebSocketClientCount() const;
|
||||||
|
bool isHealthy() const;
|
||||||
|
|
||||||
|
// Legacy accessors used by other subsystems
|
||||||
|
MQTTDriver& getMQTTClient() { return _mqttClient; }
|
||||||
|
#if HAS_UART
|
||||||
|
UARTDriver& getUARTHandler() { return _uartHandler; }
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Broadcast helpers — called by BellEngine, Player, Telemetry, etc.
|
||||||
|
// These remain WebSocket-only fan-out helpers; MQTT publishing for the
|
||||||
|
// same events now goes through the dedicated topic methods below instead
|
||||||
|
// (see docs/reference/vesper_mqtt_topic_spec_v2.md). broadcastStatus() is
|
||||||
|
// kept for WS-only callers but no longer also publishes to MQTT — see
|
||||||
|
// publishPlayback() for the MQTT equivalent used by Player.
|
||||||
|
void broadcastStatus(const String& statusMessage);
|
||||||
|
void broadcastStatus(const JsonDocument& statusJson);
|
||||||
|
void broadcastToMasterClients(const String& message);
|
||||||
|
void broadcastToSecondaryClients(const String& message);
|
||||||
|
void broadcastToAllWebSocketClients(const String& message);
|
||||||
|
void broadcastToAllWebSocketClients(const JsonDocument& message);
|
||||||
|
|
||||||
|
// Bell overload notification (called by Telemetry / BellEngine).
|
||||||
|
// WS clients get the existing broadcastStatus() shape; MQTT gets a
|
||||||
|
// dedicated control/reports publish — see publishReport().
|
||||||
|
void sendBellOverloadNotification(const std::vector<uint8_t>& bellNumbers,
|
||||||
|
const std::vector<uint16_t>& bellLoads,
|
||||||
|
const String& severity);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief A play command was ACKed SUCCESS ("download started") but playback
|
||||||
|
* never began — download failed, file bad, or blocked by the time it
|
||||||
|
* finished. MQTT: control/reports {"type":"playback_failed","payload":
|
||||||
|
* {"pid","reason"}}. WS: INFO broadcast of the same (v1 tablets ignore
|
||||||
|
* unknown INFO types). Called from the MelodyDL task.
|
||||||
|
*/
|
||||||
|
void sendPlaybackFailedNotification(const String& pid, const String& reason);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Publish the playback state to vesper/{id}/status/playback (retained, QoS 1).
|
||||||
|
* Called by Player::setStatus() on every transition. WS clients
|
||||||
|
* still receive the same fields via broadcastStatus() separately —
|
||||||
|
* this is the MQTT-specific path. Skipped (not queued) when MQTT is
|
||||||
|
* down, the "playback" switch is off, or heap is below the publish guard.
|
||||||
|
*
|
||||||
|
* @param snapshot Player::getPlaybackSnapshot() — see PlaybackState.hpp for fields
|
||||||
|
*/
|
||||||
|
void publishPlayback(const PlaybackSnapshot& snapshot);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Publish a critical, time-sensitive board-initiated event to
|
||||||
|
* vesper/{id}/control/reports (e.g. bell overload). Not retained —
|
||||||
|
* an event stream, not a status snapshot. Gated by its own topic switch.
|
||||||
|
*
|
||||||
|
* @param type Event type string e.g. "bell_overload"
|
||||||
|
* @param payload JSON object with event-specific fields
|
||||||
|
*/
|
||||||
|
void publishReport(const String& type, const JsonDocument& payload);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Publish a subsystem alert to vesper/{id}/system/alerts.
|
||||||
|
* Called by HealthMonitor when a subsystem state changes.
|
||||||
|
* Only publishes on actual state change; no-ops if MQTT not connected
|
||||||
|
* or the "alerts" topic switch is off.
|
||||||
|
*
|
||||||
|
* @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}/system/info.
|
||||||
|
* Used for state changes such as boot report, diagnostics, etc.
|
||||||
|
*
|
||||||
|
* @param type Event type string e.g. "boot_report"
|
||||||
|
* @param payload JSON object with event-specific fields (pass an empty doc for no payload)
|
||||||
|
*/
|
||||||
|
void publishInfo(const String& type, const JsonDocument& payload);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Publish structured telemetry to vesper/{id}/system/metrics.
|
||||||
|
* Not consumed by the phone app — fleet-health graphing only.
|
||||||
|
*
|
||||||
|
* @param payload JSON object with metric fields (heap, RSSI, loop timing, bell heat, etc.)
|
||||||
|
*/
|
||||||
|
void publishMetrics(const JsonDocument& payload);
|
||||||
|
|
||||||
|
// Network state callbacks (called by Networking)
|
||||||
|
void onNetworkConnected();
|
||||||
|
void onNetworkDisconnected();
|
||||||
|
|
||||||
|
private:
|
||||||
|
// Reports boot state once, the first time MQTT connects after startup:
|
||||||
|
// lifetime boot count, reset reason, and (if the last reset was a crash)
|
||||||
|
// the coredump summary — faulting task name, PC, exception cause/vaddr.
|
||||||
|
// Fault reasons additionally go to status/alerts (existing WARNING alert,
|
||||||
|
// unchanged); this consolidated report always goes to status/info,
|
||||||
|
// fault or not. Registered as MQTTDriver's onConnect callback in begin().
|
||||||
|
void reportBootOnce();
|
||||||
|
bool _bootReasonReported = false;
|
||||||
|
|
||||||
|
// Publishes a consolidated diagnostics report to system/metrics every
|
||||||
|
// DIAGNOSTICS_REPORT_INTERVAL_MS (5 min) — CPU temperature (min/max/avg
|
||||||
|
// since last report), WiFi reconnect count + last disconnect reason, OTA
|
||||||
|
// check/update state, per-task stack high-water marks, and bell strike/
|
||||||
|
// heat-load metrics. Checked from loop() (millis()-diff, same style as
|
||||||
|
// Telemetry's own flush-interval check) rather than a FreeRTOS timer.
|
||||||
|
// No-ops until _telemetry is set.
|
||||||
|
void reportDiagnosticsIfDue();
|
||||||
|
uint32_t _lastDiagnosticsReportMs = 0;
|
||||||
|
|
||||||
|
// ── External dependencies (injected) ────────────────────────────────────
|
||||||
|
ConfigManager& _configManager;
|
||||||
|
OTAManager& _otaManager;
|
||||||
|
Networking& _networking;
|
||||||
|
AsyncWebServer& _server;
|
||||||
|
AsyncWebSocket& _webSocket;
|
||||||
|
AsyncUDP& _udp;
|
||||||
|
|
||||||
|
// Late-bound (set via setXxxReference after construction)
|
||||||
|
Player* _player = nullptr;
|
||||||
|
FileManager* _fileManager = nullptr;
|
||||||
|
#if HAS_RTC
|
||||||
|
Timekeeper* _timeKeeper = nullptr;
|
||||||
|
#endif
|
||||||
|
FirmwareValidator* _firmwareValidator = nullptr;
|
||||||
|
Telemetry* _telemetry = nullptr;
|
||||||
|
HealthMonitor* _healthMonitor = nullptr;
|
||||||
|
OutputManager* _outputManager = nullptr;
|
||||||
|
#if HAS_RF
|
||||||
|
RFRemote* _rfRemote = nullptr;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// ── Underlying protocol objects (owned) ─────────────────────────────────
|
||||||
|
MQTTDriver _mqttClient;
|
||||||
|
ClientManager _clientManager;
|
||||||
|
WebSocketDriver _wsServer;
|
||||||
|
#if HAS_UART
|
||||||
|
UARTDriver _uartHandler;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// ── New architecture (owned) ────────────────────────────────────────────
|
||||||
|
CommandBus _bus;
|
||||||
|
MQTTTransport _mqttTransport;
|
||||||
|
WebSocketTransport _wsTransport;
|
||||||
|
HTTPTransport _httpTransport;
|
||||||
|
#if HAS_UART
|
||||||
|
UARTTransport _uartTransport;
|
||||||
|
#endif
|
||||||
|
WebServerTransport _webServerTransport;
|
||||||
|
|
||||||
|
// Register all domain handlers onto the bus.
|
||||||
|
// Called once from begin() after all late-bound references are confirmed.
|
||||||
|
void registerHandlers();
|
||||||
|
};
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
# CommunicationRouter
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
`CommunicationRouter` is the top-level coordinator for all inbound and outbound communication. It owns the `CommandBus`, all five transport objects (`MQTTTransport`, `WebSocketTransport`, `HTTPTransport`, `UARTTransport`, `WebServerTransport`), and the three underlying protocol driver objects (`MQTTDriver`, `WebSocketDriver`, `UARTDriver`). It also owns `ClientManager`. On `begin()`, it initialises all transports, registers them with the bus, and calls `registerHandlers()` to bind all ten domain handlers to the bus. After that, the router largely gets out of the way: incoming messages are routed internally by the bus, and outbound unsolicited events (status, telemetry, bell strikes) are pushed through the broadcast/publish helpers exposed on this class — WS-only broadcast helpers for WebSocket, and dedicated `publishXxx()` methods for each MQTT v2 topic (see `docs/reference/vesper_mqtt_topic_spec_v2.md`). All other subsystems that need to send data call into the router rather than touching transports directly.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Public API
|
||||||
|
|
||||||
|
### Lifecycle
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `CommunicationRouter(ConfigManager&, OTAManager&, Networking&, AsyncWebServer&, AsyncWebSocket&, AsyncUDP&)` | Constructor. Builds all owned objects; does not start any communication. |
|
||||||
|
| `void begin()` | Initialises all transports, registers them with the bus, calls `registerHandlers()`. Must be called after all `setXxxReference()` calls. |
|
||||||
|
| `void loop()` | Forwards to `UARTTransport::loop()` to poll UART input. Call from `main.cpp` loop. |
|
||||||
|
|
||||||
|
### Late-bound references (call before `begin()`)
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `void setPlayerReference(Player*)` | Required for PlaybackHandler, RelayHandler, FirmwareHandler, SystemHandler. |
|
||||||
|
| `void setFileManagerReference(FileManager*)` | Required for FileHandler and for `logs.list`/`logs.download` on LoggingHandler; also wires the day-rotated SD log channel into `Logging` (`/logs/YYYY-MM-DD.log`, capped at `SD_LOG_MAX_TOTAL_BYTES` — 512KB — across the directory). |
|
||||||
|
| `void setTimeKeeperReference(Timekeeper*)` | Required for ClockHandler, SystemHandler. |
|
||||||
|
| `void setFirmwareValidatorReference(FirmwareValidator*)` | Required for FirmwareHandler. |
|
||||||
|
| `void setTelemetryReference(Telemetry*)` | Required for TelemetryHandler, SystemHandler. |
|
||||||
|
| `void setHealthMonitorReference(HealthMonitor*)` | Required for SystemHandler (`system.health`). |
|
||||||
|
| `void setOutputManagerReference(OutputManager*)` | Required for RelayHandler. |
|
||||||
|
|
||||||
|
### Status
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `bool isMqttConnected() const` | True if `MQTTDriver` has an active broker connection. |
|
||||||
|
| `bool hasActiveWebSocketClients() const` | True if at least one WebSocket client is connected. |
|
||||||
|
| `size_t getWebSocketClientCount() const` | Number of currently connected WebSocket clients. |
|
||||||
|
| `bool isHealthy() const` | True if network is up and at least one of MQTT or WebSocket is active. |
|
||||||
|
|
||||||
|
### Broadcast helpers (called by other subsystems)
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `void broadcastStatus(const String& msg)` | WebSocket-only fan-out (all clients). No longer also publishes to MQTT — see the dedicated topic methods below for the MQTT equivalents. |
|
||||||
|
| `void broadcastStatus(const JsonDocument& json)` | Serialises JSON then calls the string overload. |
|
||||||
|
| `void broadcastToMasterClients(const String& msg)` | WebSocket only — master-classified clients. |
|
||||||
|
| `void broadcastToSecondaryClients(const String& msg)` | WebSocket only — secondary-classified clients. |
|
||||||
|
| `void broadcastToAllWebSocketClients(const String& msg)` | All WebSocket clients. |
|
||||||
|
| `void broadcastToAllWebSocketClients(const JsonDocument& msg)` | Serialises then sends to all WebSocket clients. |
|
||||||
|
| `void sendBellOverloadNotification(const std::vector<uint8_t>& bells, const std::vector<uint16_t>& loads, const String& severity)` | WS clients get the existing `bell_overload` INFO event via `broadcastStatus()`. MQTT clients get the same data via `publishReport("bell_overload", ...)` on `control/reports` instead. |
|
||||||
|
| `void publishPlayback(const String& action, uint32_t timeElapsedSec, uint64_t projectedRunTimeMs)` | Publishes a playback transition to `vesper/{uid}/status/playback` (QoS 1, retained). Called by `Player::setStatus()` on every transition, alongside the existing WS `broadcastStatus()` call. Gated by the `playback` topic switch. |
|
||||||
|
| `void publishReport(const String& type, const JsonDocument& payload)` | Publishes a critical, unsolicited, time-sensitive event to `vesper/{uid}/control/reports` (QoS 1, not retained). Gated by the `reports` topic switch. |
|
||||||
|
| `void publishAlert(const String& subsystem, const String& newState, const String& message)` | Publishes a subsystem state-change event to `vesper/{uid}/system/alerts` (QoS 1, retained until cleared). `newState` is one of `"WARNING"`, `"CRITICAL"`, `"FAILED"`, or `"CLEARED"`. Called automatically by the HealthMonitor alert callback registered in `begin()`, and by `reportBootOnce()` for fault reset reasons. No-op if MQTT is not connected or the `alerts` topic switch is off. |
|
||||||
|
| `void publishInfo(const String& type, const JsonDocument& payload)` | Publishes a general device state event to `vesper/{uid}/system/info` (QoS 1, retained). No-op if MQTT is not connected or the `info` topic switch is off. Used for e.g. the `"boot_report"` event published once per boot — see below. |
|
||||||
|
| `void publishMetrics(const JsonDocument& payload)` | Publishes structured telemetry to `vesper/{uid}/system/metrics` (QoS 0, not retained). Used by the 5-minute diagnostics report — see below. Gated by the `metrics` topic switch. |
|
||||||
|
|
||||||
|
### Network callbacks (called by Networking)
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `void onNetworkConnected()` | Forwards to `MQTTTransport`, which triggers the MQTT connection stabilisation timer. |
|
||||||
|
| `void onNetworkDisconnected()` | Forwards to `MQTTTransport` to stop heartbeat and abort pending reconnects. |
|
||||||
|
|
||||||
|
### Legacy accessors
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `MQTTDriver& getMQTTClient()` | Direct access to the MQTT driver; used by `Logging` to set up the MQTT log channel. |
|
||||||
|
| `UARTDriver& getUARTHandler()` | Direct access to the UART driver (currently not used outside the router). |
|
||||||
|
|
||||||
|
### UDP Discovery
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `void setupUdpDiscovery()` | Starts listening on the configured discovery port. Replies to UDP `"discover"` packets with a JSON `discover_reply` payload containing IP, WebSocket URL, firmware version, and client count. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Initialization
|
||||||
|
|
||||||
|
In `main.cpp`, the router is constructed as a global alongside the other subsystems:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
CommunicationRouter communication(configManager, otaManager, networking, server, ws, udp);
|
||||||
|
```
|
||||||
|
|
||||||
|
Before calling `begin()`, all late-bound references must be set:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
communication.setPlayerReference(&player);
|
||||||
|
communication.setFileManagerReference(&fileManager);
|
||||||
|
communication.setTimeKeeperReference(&timekeeper);
|
||||||
|
communication.setFirmwareValidatorReference(&firmwareValidator);
|
||||||
|
communication.setTelemetryReference(&telemetry);
|
||||||
|
communication.setHealthMonitorReference(&healthMonitor);
|
||||||
|
communication.setOutputManagerReference(&outputManager);
|
||||||
|
communication.begin();
|
||||||
|
```
|
||||||
|
|
||||||
|
If any required reference is null when `registerHandlers()` runs (inside `begin()`), the corresponding handler(s) are skipped and an `LOG_ERROR` is emitted. The bus still starts; commands for missing handlers return "Unknown command".
|
||||||
|
|
||||||
|
`begin()` also registers `MQTTDriver::setStateProvider()` — a lambda that reads `_player`/`_healthMonitor` at call time (not registration time) to derive the heartbeat's `state`/`ok` fields. Because `_player`/`_healthMonitor` are late-bound, this lambda safely returns `state="booting", ok=true` if called before `setPlayerReference()`/`setHealthMonitorReference()` run — in practice this never happens, since the heartbeat timer only starts once MQTT connects, well after `main.cpp` finishes wiring all references.
|
||||||
|
|
||||||
|
`AsyncWebServer::begin()` is **not** called inside `CommunicationRouter::begin()`. It is started from the network-connected callback in `main.cpp` to avoid conflicting with WiFiManager's captive portal on port 80.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
- `ConfigManager` — MQTT config, network config, log levels, device UID
|
||||||
|
- `OTAManager` — passed to `FirmwareHandler`
|
||||||
|
- `Networking` — passed to `NetworkHandler`; used for health check and UDP discovery
|
||||||
|
- `AsyncWebServer` / `AsyncWebSocket` / `AsyncUDP` — passed to transports
|
||||||
|
- All domain handler dependencies: `Player`, `FileManager`, `Timekeeper`, `FirmwareValidator`, `Telemetry`, `HealthMonitor`, `OutputManager`
|
||||||
|
- Libraries: `ESPAsyncWebServer`, `ArduinoJson`, `AsyncUDP`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Gotchas / Notes
|
||||||
|
|
||||||
|
- **Order matters**: All `setXxxReference()` calls must happen before `begin()`. `registerHandlers()` is called at the end of `begin()` and will silently omit handlers for any null reference.
|
||||||
|
- **`server.begin()` is deferred**: The `AsyncWebServer` is not started inside `begin()` — it is started in the `onNetworkConnected` callback in `main.cpp`. This prevents a port 80 conflict when WiFiManager's captive portal is active.
|
||||||
|
- **`loop()` must be called**: `UARTTransport` is the only transport that requires polling. `CommunicationRouter::loop()` delegates to it. All other transports are fully event-driven.
|
||||||
|
- **MQTT log suppression**: During `begin()`, the subsystem MQTT log levels for `"MQTTClient"` and `"CommRouter"` are explicitly suppressed to `NONE` and `WARNING` respectively to prevent feedback loops when MQTT is used as a log sink.
|
||||||
|
- **Boot reporting**: `begin()` registers a one-shot `onConnect` callback on `MQTTDriver` (`reportBootOnce()`) that fires the first time MQTT connects after startup (including the very first connection). Guarded by `_bootReasonReported` so it only fires once per boot, not on every reconnect. It does two things:
|
||||||
|
1. If `Telemetry::isFaultReset()` is true (panic, watchdog, brownout), publishes the existing fault alert via `publishAlert("System", "WARNING", "Device reset due to fault: " + reason)` — unchanged behavior/topic from before.
|
||||||
|
2. **Always** — fault or not — publishes a consolidated `"boot_report"` event via `publishInfo` to `vesper/{uid}/system/info`:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "boot_report",
|
||||||
|
"boot_count": 47,
|
||||||
|
"reset_reason": "PANIC",
|
||||||
|
"is_fault": true,
|
||||||
|
"free_heap": 187234,
|
||||||
|
"crash": {
|
||||||
|
"task": "TelemetryTask",
|
||||||
|
"pc": 1074111832,
|
||||||
|
"exc_cause": 1,
|
||||||
|
"exc_vaddr": 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
`boot_count` is `Telemetry::getLifetimeBootCount()` — see [Telemetry's Boot tracking section](../../Telemetry/README.md#boot-tracking) for why this is a separate counter from `FirmwareValidator`'s NVS `boot_count`. The `crash` object is present only when a coredump was found for the crash that caused this boot (`CrashReport::available == true`) — omitted entirely on a clean/expected reset, or when no coredump was captured for a fault reset (e.g. a brownout, which doesn't produce one).
|
||||||
|
- **Diagnostics/metrics reporting**: `loop()` calls `reportDiagnosticsIfDue()` every main-loop iteration, which no-ops until `DIAGNOSTICS_REPORT_INTERVAL_MS` (5 minutes, `Telemetry.hpp`) has elapsed and `_telemetry` is set. Unlike `reportBootOnce()` (a one-shot MQTT-onConnect callback), this is a plain `millis()`-diff check — same style as `Telemetry`'s own `RUNTIME_FLUSH_INTERVAL_MS` check — so it fires on a fixed wall-clock cadence regardless of MQTT connection churn (a no-op `publishMetrics()` call if disconnected). Publishes a consolidated payload to `vesper/{uid}/system/metrics` (not wrapped in a `"type"` envelope — the topic itself is the discriminator):
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"cpu_temp": { "avg": 47.1, "min": 44.8, "max": 52.8, "samples": 20 },
|
||||||
|
"wifi_reconnects": { "lifetime_count": 2, "last_reason": "AUTH_EXPIRE", "last_at_uptime_ms": 3600000 },
|
||||||
|
"ota": { "current_version": "2.7.3", "update_available": false, "last_check_uptime_ms": 180000, "last_error": "NONE" },
|
||||||
|
"stack_high_water": { "TelemetryTask": 1024, "HealthMonitor": 890 },
|
||||||
|
"bell_strikes": { "0": 1234, "1": 567, "...": "..." },
|
||||||
|
"bell_loads": { "0": 12, "1": 0, "...": "..." },
|
||||||
|
"cooling_active": false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
`cpu_temp` pulls from `Telemetry::writeTemperatureStats()` then calls `resetDiagnosticsStats()` — the accumulator is consumed on the periodic path (unlike the on-demand `telemetry.get_diagnostics` command, which peeks without resetting). `wifi_reconnects`/`ota` read directly from the router's own `_networking`/`_otaManager` references (constructor-injected, not late-bound — no null guard needed). `stack_high_water` comes from `Telemetry::writeStackHighWaterMarks()`'s static task registry — see [Telemetry's Diagnostics reporting section](../../Telemetry/README.md#diagnostics-reporting) for the full design rationale (F-056 in the feature catalog), including why temperature alone needs local 15s sampling while the other three fields are read once per report. `bell_strikes`/`bell_loads`/`cooling_active` are read directly from `Telemetry::getStrikeCount()`/`getBellLoad()`/`isCoolingActive()` for all 16 bell channels — added when this report moved from `system/info` to `system/metrics`, matching the topic spec's explicit call-out of "bell heat ratings" for this topic.
|
||||||
|
- **Broadcast vs CommandBus broadcast**: The `broadcastXxx()` helpers on this class send raw pre-serialised strings over WebSocket only. `CommandBus::broadcast()` serialises a `CommandResult` and fans it out to every registered transport, including MQTT's `control/ack` (see `MQTTTransport::broadcast()`). They are separate paths; subsystems outside the communication layer use whichever fits — the router's WS-only helpers for WS-specific fan-out, or the dedicated `publishXxx()` topic methods for MQTT-specific events.
|
||||||
|
- **Handler skipping is silent to clients**: If a reference is null and a handler is not registered, the bus returns `{"status":"ERROR","type":"unknown","message":"Unknown command: ..."}`. There is no boot-time safeguard beyond the `LOG_ERROR` in `registerHandlers()`.
|
||||||
@@ -0,0 +1,557 @@
|
|||||||
|
/*
|
||||||
|
* MQTTDRIVER.CPP - MQTT Protocol Driver Implementation
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "MQTTDriver.hpp"
|
||||||
|
|
||||||
|
#define TAG "MQTTClient"
|
||||||
|
#include "../../../ConfigManager/ConfigManager.hpp"
|
||||||
|
#include "../../../Networking/Networking.hpp"
|
||||||
|
#include "../../../Logging/Logging.hpp"
|
||||||
|
|
||||||
|
MQTTDriver* MQTTDriver::_instance = nullptr;
|
||||||
|
|
||||||
|
MQTTDriver::MQTTDriver(ConfigManager& configManager, Networking& networking)
|
||||||
|
: _configManager(configManager)
|
||||||
|
, _networking(networking)
|
||||||
|
, _messageCallback(nullptr)
|
||||||
|
, _mqttReconnectTimer(nullptr)
|
||||||
|
, _networkStabilizationTimer(nullptr)
|
||||||
|
, _heartbeatTimer(nullptr)
|
||||||
|
, _heartbeatTaskHandle(nullptr)
|
||||||
|
, _reconnectAttempts(0)
|
||||||
|
, _lastConnectionAttempt(0) {
|
||||||
|
|
||||||
|
_instance = this; // Set static instance pointer
|
||||||
|
|
||||||
|
// Create reconnection timer (initial delay will be calculated dynamically)
|
||||||
|
_mqttReconnectTimer = xTimerCreate(
|
||||||
|
"mqttReconnect", // Timer name (for debugging)
|
||||||
|
pdMS_TO_TICKS(MQTT_RECONNECT_BASE_DELAY), // Initial period: 5000ms = 5 seconds
|
||||||
|
pdFALSE, // One-shot (false) or Auto-reload (true)
|
||||||
|
(void*)0, // Timer ID (can store data)
|
||||||
|
mqttReconnectTimerCallback // Callback function when timer expires
|
||||||
|
);
|
||||||
|
|
||||||
|
// Create network stabilization timer (one-shot, 2 seconds)
|
||||||
|
_networkStabilizationTimer = xTimerCreate(
|
||||||
|
"mqttNetStable", // Timer name
|
||||||
|
pdMS_TO_TICKS(NETWORK_STABILIZATION_DELAY), // Period: 2000ms = 2 seconds
|
||||||
|
pdFALSE, // One-shot timer
|
||||||
|
(void*)0, // Timer ID
|
||||||
|
networkStabilizationTimerCallback // Callback function
|
||||||
|
);
|
||||||
|
|
||||||
|
// Create heartbeat timer (auto-reload every 30 seconds)
|
||||||
|
_heartbeatTimer = xTimerCreate(
|
||||||
|
"mqttHeartbeat", // Timer name
|
||||||
|
pdMS_TO_TICKS(HEARTBEAT_INTERVAL), // Period: 30000ms = 30 seconds
|
||||||
|
pdTRUE, // Auto-reload (true) - repeating timer
|
||||||
|
(void*)0, // Timer ID
|
||||||
|
heartbeatTimerCallback // Callback function
|
||||||
|
);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
MQTTDriver::~MQTTDriver() {
|
||||||
|
if (_mqttReconnectTimer) {
|
||||||
|
xTimerDelete(_mqttReconnectTimer, portMAX_DELAY);
|
||||||
|
}
|
||||||
|
if (_networkStabilizationTimer) {
|
||||||
|
xTimerStop(_networkStabilizationTimer, 0);
|
||||||
|
xTimerDelete(_networkStabilizationTimer, portMAX_DELAY);
|
||||||
|
}
|
||||||
|
if (_heartbeatTimer) {
|
||||||
|
xTimerStop(_heartbeatTimer, 0);
|
||||||
|
xTimerDelete(_heartbeatTimer, portMAX_DELAY);
|
||||||
|
}
|
||||||
|
_mqttClient.disconnect();
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTDriver::begin() {
|
||||||
|
LOG_INFO(TAG, "Initializing MQTT Async Client");
|
||||||
|
|
||||||
|
auto& mqttConfig = _configManager.getMqttConfig();
|
||||||
|
|
||||||
|
// Build topic strings (cache for performance) — see docs/reference/vesper_mqtt_topic_spec_v2.md
|
||||||
|
String deviceUID = _configManager.getDeviceUID();
|
||||||
|
_commandTopic = "vesper/" + deviceUID + "/control/command";
|
||||||
|
_ackTopic = "vesper/" + deviceUID + "/control/ack";
|
||||||
|
_heartbeatTopic = "vesper/" + deviceUID + "/status/heartbeat";
|
||||||
|
_playbackTopic = "vesper/" + deviceUID + "/status/playback";
|
||||||
|
_reportsTopic = "vesper/" + deviceUID + "/control/reports";
|
||||||
|
_alertsTopic = "vesper/" + deviceUID + "/system/alerts";
|
||||||
|
_infoTopic = "vesper/" + deviceUID + "/system/info";
|
||||||
|
_logsTopic = "vesper/" + deviceUID + "/system/logs";
|
||||||
|
_metricsTopic = "vesper/" + deviceUID + "/system/metrics";
|
||||||
|
_clientId = "vesper-" + deviceUID;
|
||||||
|
|
||||||
|
LOG_INFO(TAG, "MQTT Topics: command=%s, ack=%s, heartbeat=%s, playback=%s, reports=%s, alerts=%s, info=%s, logs=%s, metrics=%s",
|
||||||
|
_commandTopic.c_str(), _ackTopic.c_str(), _heartbeatTopic.c_str(), _playbackTopic.c_str(),
|
||||||
|
_reportsTopic.c_str(), _alertsTopic.c_str(), _infoTopic.c_str(), _logsTopic.c_str(), _metricsTopic.c_str());
|
||||||
|
|
||||||
|
// Setup event handlers
|
||||||
|
_mqttClient.onConnect([this](bool sessionPresent) {
|
||||||
|
this->onMqttConnect(sessionPresent);
|
||||||
|
});
|
||||||
|
|
||||||
|
_mqttClient.onDisconnect([this](AsyncMqttClientDisconnectReason reason) {
|
||||||
|
this->onMqttDisconnect(reason);
|
||||||
|
});
|
||||||
|
|
||||||
|
_mqttClient.onSubscribe([this](uint16_t packetId, uint8_t qos) {
|
||||||
|
this->onMqttSubscribe(packetId, qos);
|
||||||
|
});
|
||||||
|
|
||||||
|
_mqttClient.onUnsubscribe([this](uint16_t packetId) {
|
||||||
|
this->onMqttUnsubscribe(packetId);
|
||||||
|
});
|
||||||
|
|
||||||
|
_mqttClient.onMessage([this](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
|
||||||
|
this->onMqttMessage(topic, payload, properties, len, index, total);
|
||||||
|
});
|
||||||
|
|
||||||
|
_mqttClient.onPublish([this](uint16_t packetId) {
|
||||||
|
this->onMqttPublish(packetId);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Configure connection
|
||||||
|
_mqttClient.setServer(mqttConfig.host, mqttConfig.port);
|
||||||
|
_mqttClient.setCredentials(mqttConfig.user.c_str(), mqttConfig.password.c_str());
|
||||||
|
_mqttClient.setClientId(_clientId.c_str()); // Use member variable
|
||||||
|
_mqttClient.setKeepAlive(15);
|
||||||
|
_mqttClient.setCleanSession(true);
|
||||||
|
|
||||||
|
// Last Will and Testament — the broker publishes this to status/heartbeat
|
||||||
|
// (retained) automatically if the connection drops uncleanly (network loss,
|
||||||
|
// crash, power loss). Must be re-registered on every reconnect, which is
|
||||||
|
// automatic here since setWill() is applied on every begin()/connect() —
|
||||||
|
// AsyncMqttClient resends CONNECT (with Will) on every reconnection attempt.
|
||||||
|
String willPayload = buildOfflinePayload();
|
||||||
|
_mqttClient.setWill(_heartbeatTopic.c_str(), 1, true, willPayload.c_str());
|
||||||
|
|
||||||
|
LOG_INFO(TAG, "✅ MQTT Async Client initialized");
|
||||||
|
}
|
||||||
|
|
||||||
|
String MQTTDriver::buildOfflinePayload() const {
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["device_id"] = _configManager.getDeviceUID();
|
||||||
|
doc["state"] = "offline";
|
||||||
|
doc["ok"] = false;
|
||||||
|
String out;
|
||||||
|
serializeJson(doc, out);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTDriver::connect() {
|
||||||
|
auto& mqttConfig = _configManager.getMqttConfig();
|
||||||
|
|
||||||
|
// 🔥 Check if MQTT is enabled
|
||||||
|
if (!mqttConfig.enabled) {
|
||||||
|
LOG_DEBUG(TAG, "MQTT is disabled in configuration - skipping connection");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_mqttClient.connected()) {
|
||||||
|
LOG_DEBUG(TAG, "Already connected to MQTT");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Track connection attempt
|
||||||
|
_lastConnectionAttempt = millis();
|
||||||
|
|
||||||
|
LOG_INFO(TAG, "Free heap BEFORE MQTT connect: %d bytes", ESP.getFreeHeap());
|
||||||
|
|
||||||
|
_mqttClient.connect();
|
||||||
|
|
||||||
|
LOG_INFO(TAG, "MQTT connect() called - waiting for async connection...");
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTDriver::disconnect(bool graceful) {
|
||||||
|
if (graceful && _mqttClient.connected()) {
|
||||||
|
// LWT only fires on an *unclean* disconnect — announce offline explicitly
|
||||||
|
// before a clean one so status/heartbeat doesn't keep a stale "online"
|
||||||
|
// retained message around (e.g. before an OTA flash).
|
||||||
|
String offlinePayload = buildOfflinePayload();
|
||||||
|
_mqttClient.publish(_heartbeatTopic.c_str(), 1, true, offlinePayload.c_str());
|
||||||
|
LOG_INFO(TAG, "Published graceful offline heartbeat before disconnect");
|
||||||
|
}
|
||||||
|
_mqttClient.disconnect();
|
||||||
|
LOG_INFO(TAG, "Disconnected from MQTT broker");
|
||||||
|
}
|
||||||
|
|
||||||
|
bool MQTTDriver::hasHeapForPublish() const {
|
||||||
|
if (ESP.getFreeHeap() >= MIN_FREE_HEAP_FOR_PUBLISH) return true;
|
||||||
|
|
||||||
|
// Serial.printf directly, not LOG_* — MQTT-channel logging would try to publish
|
||||||
|
// this very warning, recursing straight back into the low-heap condition we're
|
||||||
|
// trying to avoid. Same reasoning as the disconnected-check below.
|
||||||
|
Serial.printf("[MQTTClient] Skipping publish - free heap %u below %u byte threshold\n",
|
||||||
|
(unsigned)ESP.getFreeHeap(), (unsigned)MIN_FREE_HEAP_FOR_PUBLISH);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint16_t MQTTDriver::publishAck(const String& payload, int qos, bool retain) {
|
||||||
|
// Check if connected before attempting to publish
|
||||||
|
if (!_mqttClient.connected()) {
|
||||||
|
// Don't log error here - would cause infinite loop with MQTT logging
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (!hasHeapForPublish()) return 0;
|
||||||
|
|
||||||
|
// control/ack shares the "command" topic switch with control/command — if a
|
||||||
|
// client somehow gets a reply queued while the switch just got turned off
|
||||||
|
// mid-flight, drop it rather than publish to a channel the operator disabled.
|
||||||
|
if (!_configManager.getMqttTopicConfig().command) return 0;
|
||||||
|
|
||||||
|
uint16_t packetId = _mqttClient.publish(_ackTopic.c_str(), qos, retain, payload.c_str());
|
||||||
|
|
||||||
|
if (packetId > 0) {
|
||||||
|
LOG_DEBUG(TAG, "Published to %s: %s (packetId=%d)", _ackTopic.c_str(), payload.c_str(), packetId);
|
||||||
|
}
|
||||||
|
// REMOVED: Error logging here to prevent infinite recursion with MQTT logs
|
||||||
|
|
||||||
|
return packetId;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint16_t MQTTDriver::publishDirect(const String& fullTopic, const String& payload, int qos, bool retain) {
|
||||||
|
if (!_mqttClient.connected()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (!hasHeapForPublish()) 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool MQTTDriver::isConnected() const {
|
||||||
|
return _mqttClient.connected();
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTDriver::onNetworkConnected() {
|
||||||
|
auto& mqttConfig = _configManager.getMqttConfig();
|
||||||
|
|
||||||
|
// 🔥 Only attempt connection if MQTT is enabled
|
||||||
|
if (!mqttConfig.enabled) {
|
||||||
|
LOG_DEBUG(TAG, "Network connected but MQTT is disabled - skipping MQTT connection");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
LOG_DEBUG(TAG, "Network connected - scheduling MQTT connection after 2s stabilization (non-blocking)");
|
||||||
|
|
||||||
|
// Reset reconnect attempts on fresh network connection
|
||||||
|
_reconnectAttempts = 0;
|
||||||
|
|
||||||
|
// 🔥 CRITICAL FIX: Use non-blocking timer instead of delay()
|
||||||
|
// This prevents blocking UDP discovery, WebSocket connections, and async operations
|
||||||
|
if (_networkStabilizationTimer) {
|
||||||
|
xTimerStart(_networkStabilizationTimer, 0);
|
||||||
|
} else {
|
||||||
|
LOG_ERROR(TAG, "Network stabilization timer not initialized!");
|
||||||
|
// Fallback to immediate connection (better than blocking)
|
||||||
|
connect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTDriver::onNetworkDisconnected() {
|
||||||
|
LOG_DEBUG(TAG, "Network disconnected - MQTT will auto-reconnect when network returns");
|
||||||
|
|
||||||
|
if (_mqttClient.connected()) {
|
||||||
|
_mqttClient.disconnect(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTDriver::subscribe() {
|
||||||
|
// Gated by the "command" topic switch — a device that doesn't need remote
|
||||||
|
// control (e.g. fleet-monitoring-only) can turn this off entirely and skip
|
||||||
|
// both control/command (this subscribe) and control/ack (its replies).
|
||||||
|
if (!_configManager.getMqttTopicConfig().command) {
|
||||||
|
LOG_INFO(TAG, "control/command subscription skipped — 'command' topic switch is off");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
uint16_t packetId = _mqttClient.subscribe(_commandTopic.c_str(), 1);
|
||||||
|
LOG_INFO(TAG, "📬 Subscribing to control/command topic: %s (packetId=%d)", _commandTopic.c_str(), packetId);
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTDriver::onMqttConnect(bool sessionPresent) {
|
||||||
|
LOG_INFO(TAG, "✅ Connected to MQTT broker (session present: %s)", sessionPresent ? "yes" : "no");
|
||||||
|
LOG_INFO(TAG, "🔍 Free heap AFTER MQTT connect: %d bytes", ESP.getFreeHeap());
|
||||||
|
|
||||||
|
// Reset reconnection attempts on successful connection
|
||||||
|
_reconnectAttempts = 0;
|
||||||
|
|
||||||
|
// Subscribe to control topic
|
||||||
|
subscribe();
|
||||||
|
|
||||||
|
// 🔥 Start heartbeat timer
|
||||||
|
startHeartbeat();
|
||||||
|
|
||||||
|
if (_onConnectCallback) {
|
||||||
|
_onConnectCallback(sessionPresent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTDriver::onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
|
||||||
|
auto& mqttConfig = _configManager.getMqttConfig();
|
||||||
|
|
||||||
|
const char* reasonStr;
|
||||||
|
switch(reason) {
|
||||||
|
case AsyncMqttClientDisconnectReason::TCP_DISCONNECTED:
|
||||||
|
reasonStr = "TCP disconnected";
|
||||||
|
break;
|
||||||
|
case AsyncMqttClientDisconnectReason::MQTT_UNACCEPTABLE_PROTOCOL_VERSION:
|
||||||
|
reasonStr = "Unacceptable protocol version";
|
||||||
|
break;
|
||||||
|
case AsyncMqttClientDisconnectReason::MQTT_IDENTIFIER_REJECTED:
|
||||||
|
reasonStr = "Identifier rejected";
|
||||||
|
break;
|
||||||
|
case AsyncMqttClientDisconnectReason::MQTT_SERVER_UNAVAILABLE:
|
||||||
|
reasonStr = "Server unavailable";
|
||||||
|
break;
|
||||||
|
case AsyncMqttClientDisconnectReason::MQTT_MALFORMED_CREDENTIALS:
|
||||||
|
reasonStr = "Malformed credentials";
|
||||||
|
break;
|
||||||
|
case AsyncMqttClientDisconnectReason::MQTT_NOT_AUTHORIZED:
|
||||||
|
reasonStr = "Not authorized";
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
reasonStr = "Unknown";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
LOG_ERROR(TAG, "❌ Disconnected from MQTT broker - Reason: %s (%d)", reasonStr, static_cast<int>(reason));
|
||||||
|
|
||||||
|
// Stop heartbeat timer when disconnected
|
||||||
|
stopHeartbeat();
|
||||||
|
|
||||||
|
// 🔥 Don't attempt reconnection if MQTT is disabled
|
||||||
|
if (!mqttConfig.enabled) {
|
||||||
|
LOG_INFO(TAG, "MQTT is disabled - not attempting reconnection");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_networking.isConnected()) {
|
||||||
|
// Increment reconnection attempts
|
||||||
|
_reconnectAttempts++;
|
||||||
|
|
||||||
|
// Calculate backoff delay
|
||||||
|
unsigned long reconnectDelay = getReconnectDelay();
|
||||||
|
|
||||||
|
LOG_INFO(TAG, "Network still connected - scheduling MQTT reconnection #%d in %lu seconds (backoff active)",
|
||||||
|
_reconnectAttempts, reconnectDelay / 1000);
|
||||||
|
|
||||||
|
// Update timer period with new delay
|
||||||
|
xTimerChangePeriod(_mqttReconnectTimer, pdMS_TO_TICKS(reconnectDelay), 0);
|
||||||
|
xTimerStart(_mqttReconnectTimer, 0);
|
||||||
|
} else {
|
||||||
|
LOG_INFO(TAG, "Network is down - waiting for network to reconnect");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTDriver::applyCommandTopicSwitch(bool enabled) {
|
||||||
|
if (!_mqttClient.connected()) return; // picked up naturally by subscribe() on next connect
|
||||||
|
|
||||||
|
if (enabled) {
|
||||||
|
uint16_t packetId = _mqttClient.subscribe(_commandTopic.c_str(), 1);
|
||||||
|
LOG_INFO(TAG, "control/command switch turned on — subscribing live (packetId=%d)", packetId);
|
||||||
|
} else {
|
||||||
|
uint16_t packetId = _mqttClient.unsubscribe(_commandTopic.c_str());
|
||||||
|
LOG_INFO(TAG, "control/command switch turned off — unsubscribing live (packetId=%d)", packetId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTDriver::onMqttSubscribe(uint16_t packetId, uint8_t qos) {
|
||||||
|
LOG_INFO(TAG, "✅ Subscribed to topic (packetId=%d, QoS=%d)", packetId, qos);
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTDriver::onMqttUnsubscribe(uint16_t packetId) {
|
||||||
|
LOG_DEBUG(TAG, "Unsubscribed from topic (packetId=%d)", packetId);
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTDriver::onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
|
||||||
|
// Convert to String
|
||||||
|
String topicStr = String(topic);
|
||||||
|
String payloadStr = String(payload).substring(0, len);
|
||||||
|
|
||||||
|
LOG_DEBUG(TAG, "MQTT message received - topic: %s, payload: %s", topicStr.c_str(), payloadStr.c_str());
|
||||||
|
|
||||||
|
// Call user callback
|
||||||
|
if (_messageCallback) {
|
||||||
|
_messageCallback(topicStr, payloadStr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTDriver::onMqttPublish(uint16_t packetId) {
|
||||||
|
LOG_DEBUG(TAG, "MQTT publish acknowledged (packetId=%d)", packetId);
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTDriver::attemptReconnection() {
|
||||||
|
// Double-check network is still up
|
||||||
|
if (_networking.isConnected()) {
|
||||||
|
LOG_INFO(TAG, "Attempting MQTT reconnection...");
|
||||||
|
connect();
|
||||||
|
} else {
|
||||||
|
LOG_WARNING(TAG, "Network down during reconnect attempt - aborting");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTDriver::mqttReconnectTaskFn(void* param) {
|
||||||
|
MQTTDriver* client = static_cast<MQTTDriver*>(param);
|
||||||
|
client->attemptReconnection();
|
||||||
|
vTaskDelete(NULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTDriver::mqttReconnectTimerCallback(TimerHandle_t xTimer) {
|
||||||
|
if (MQTTDriver::_instance) {
|
||||||
|
xTaskCreate(mqttReconnectTaskFn, "mqttRecon", 4096, MQTTDriver::_instance, 5, NULL);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||||
|
// HEARTBEAT FUNCTIONALITY
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
void MQTTDriver::startHeartbeat() {
|
||||||
|
if (_heartbeatTimer) {
|
||||||
|
LOG_INFO(TAG, "💓 Starting MQTT heartbeat (every %d seconds)", HEARTBEAT_INTERVAL / 1000);
|
||||||
|
|
||||||
|
// Publish first heartbeat immediately
|
||||||
|
publishHeartbeat();
|
||||||
|
|
||||||
|
// Start periodic timer
|
||||||
|
xTimerStart(_heartbeatTimer, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTDriver::stopHeartbeat() {
|
||||||
|
if (_heartbeatTimer) {
|
||||||
|
xTimerStop(_heartbeatTimer, 0);
|
||||||
|
_heartbeatTaskHandle = nullptr;
|
||||||
|
LOG_INFO(TAG, "❤️ Stopped MQTT heartbeat");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTDriver::publishHeartbeat() {
|
||||||
|
if (!_mqttClient.connected()) {
|
||||||
|
LOG_WARNING(TAG, "⚠️ Cannot publish heartbeat - MQTT not connected");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!_configManager.getMqttTopicConfig().heartbeat) return;
|
||||||
|
if (!hasHeapForPublish()) return; // skip building the JsonDocument too, not just the publish
|
||||||
|
|
||||||
|
// Build heartbeat JSON message — flat shape per docs/reference/vesper_mqtt_topic_spec_v2.md.
|
||||||
|
// state/ok are independently derived via _stateProvider, never mirrored from
|
||||||
|
// status/playback or system/alerts.
|
||||||
|
JsonDocument doc;
|
||||||
|
|
||||||
|
doc["device_id"] = _configManager.getDeviceUID();
|
||||||
|
|
||||||
|
DeviceState ds = _stateProvider ? _stateProvider() : DeviceState{"booting", true};
|
||||||
|
doc["state"] = ds.state;
|
||||||
|
doc["ok"] = ds.ok;
|
||||||
|
|
||||||
|
doc["fw_version"] = _configManager.getFwVersion();
|
||||||
|
|
||||||
|
unsigned long uptimeMs = millis();
|
||||||
|
unsigned long uptimeSec = uptimeMs / 1000;
|
||||||
|
unsigned long hours = uptimeSec / 3600;
|
||||||
|
unsigned long minutes = (uptimeSec % 3600) / 60;
|
||||||
|
unsigned long seconds = uptimeSec % 60;
|
||||||
|
doc["uptime_ms"] = uptimeMs;
|
||||||
|
|
||||||
|
char uptimeHuman[32];
|
||||||
|
snprintf(uptimeHuman, sizeof(uptimeHuman), "%luh %lum %lus", hours, minutes, seconds);
|
||||||
|
doc["uptime_human"] = uptimeHuman;
|
||||||
|
|
||||||
|
doc["ip_address"] = _networking.getLocalIP();
|
||||||
|
doc["gateway"] = _networking.getGateway();
|
||||||
|
doc["rssi"] = WiFi.RSSI();
|
||||||
|
doc["free_heap"] = ESP.getFreeHeap();
|
||||||
|
|
||||||
|
// Serialize to string
|
||||||
|
String heartbeatMessage;
|
||||||
|
serializeJson(doc, heartbeatMessage);
|
||||||
|
|
||||||
|
// Publish to heartbeat topic with RETAIN flag
|
||||||
|
uint16_t packetId = _mqttClient.publish(_heartbeatTopic.c_str(), 1, true, heartbeatMessage.c_str());
|
||||||
|
|
||||||
|
if (packetId > 0) {
|
||||||
|
LOG_DEBUG(TAG, "💓 Published heartbeat (retained) - state: %s, IP: %s, Uptime: %lums",
|
||||||
|
ds.state.c_str(), _networking.getLocalIP().c_str(), uptimeMs);
|
||||||
|
} else {
|
||||||
|
LOG_ERROR(TAG, "❌ Failed to publish heartbeat");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTDriver::mqttHeartbeatTaskFn(void* param) {
|
||||||
|
MQTTDriver* client = static_cast<MQTTDriver*>(param);
|
||||||
|
client->publishHeartbeat();
|
||||||
|
client->_heartbeatTaskHandle = nullptr;
|
||||||
|
vTaskDelete(NULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTDriver::heartbeatTimerCallback(TimerHandle_t xTimer) {
|
||||||
|
if (MQTTDriver::_instance) {
|
||||||
|
// Guard: skip if previous heartbeat task is still running
|
||||||
|
if (MQTTDriver::_instance->_heartbeatTaskHandle != nullptr) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
xTaskCreate(mqttHeartbeatTaskFn, "mqttHB", 4096, MQTTDriver::_instance, 3,
|
||||||
|
&MQTTDriver::_instance->_heartbeatTaskHandle);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||||
|
// NETWORK STABILIZATION - NON-BLOCKING TIMER APPROACH
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
void MQTTDriver::connectAfterStabilization() {
|
||||||
|
LOG_DEBUG(TAG, "Network stabilization complete - connecting to MQTT");
|
||||||
|
connect();
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTDriver::mqttConnectTaskFn(void* param) {
|
||||||
|
// Runs in its own task so LOG calls don't overflow the Tmr Svc stack
|
||||||
|
MQTTDriver* client = static_cast<MQTTDriver*>(param);
|
||||||
|
client->connectAfterStabilization();
|
||||||
|
vTaskDelete(NULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTDriver::networkStabilizationTimerCallback(TimerHandle_t xTimer) {
|
||||||
|
if (MQTTDriver::_instance) {
|
||||||
|
// Defer to a task — timer callbacks run in Tmr Svc (2KB stack), not enough for connect()
|
||||||
|
xTaskCreate(mqttConnectTaskFn, "mqttConnect", 4096, MQTTDriver::_instance, 5, NULL);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||||
|
// EXPONENTIAL BACKOFF CALCULATION
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
unsigned long MQTTDriver::getReconnectDelay() {
|
||||||
|
// First 3 attempts: Quick retries (5 seconds each)
|
||||||
|
if (_reconnectAttempts <= MQTT_MAX_QUICK_RETRIES) {
|
||||||
|
return MQTT_RECONNECT_BASE_DELAY;
|
||||||
|
}
|
||||||
|
|
||||||
|
// After quick retries: Exponential backoff
|
||||||
|
// Formula: base_delay * 2^(attempts - quick_retries)
|
||||||
|
// Examples: 10s, 20s, 40s, 80s, 160s, 300s (capped at 5 minutes)
|
||||||
|
uint8_t backoffPower = _reconnectAttempts - MQTT_MAX_QUICK_RETRIES;
|
||||||
|
unsigned long delay = MQTT_RECONNECT_BASE_DELAY * (1 << backoffPower); // 2^backoffPower
|
||||||
|
|
||||||
|
// Cap at maximum delay (5 minutes)
|
||||||
|
if (delay > MQTT_RECONNECT_MAX_DELAY) {
|
||||||
|
delay = MQTT_RECONNECT_MAX_DELAY;
|
||||||
|
}
|
||||||
|
|
||||||
|
return delay;
|
||||||
|
}
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
/*
|
||||||
|
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||||
|
* MQTTDRIVER.HPP - MQTT Protocol Driver
|
||||||
|
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||||
|
*
|
||||||
|
* Low-level MQTT protocol driver using AsyncMqttClient.
|
||||||
|
* Handles broker connection, auth, publish/subscribe, reconnect with exponential
|
||||||
|
* backoff, and heartbeat. Wrapped by MQTTTransport for CommandBus integration.
|
||||||
|
*
|
||||||
|
* 📋 VERSION: 3.0 (AsyncMqttClient-based)
|
||||||
|
* 📅 DATE: 2025-01-04
|
||||||
|
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||||
|
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <AsyncMqttClient.h>
|
||||||
|
#include <functional>
|
||||||
|
|
||||||
|
class ConfigManager;
|
||||||
|
class Networking;
|
||||||
|
|
||||||
|
class MQTTDriver {
|
||||||
|
public:
|
||||||
|
static MQTTDriver* _instance;
|
||||||
|
|
||||||
|
// Message callback type
|
||||||
|
using MessageCallback = std::function<void(const String& topic, const String& payload)>;
|
||||||
|
|
||||||
|
explicit MQTTDriver(ConfigManager& configManager, Networking& networking);
|
||||||
|
~MQTTDriver();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Initialize MQTT client
|
||||||
|
*/
|
||||||
|
void begin();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Connect to MQTT broker
|
||||||
|
*/
|
||||||
|
void connect();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Disconnect from MQTT broker.
|
||||||
|
* @param graceful If true, explicitly publishes the retained offline payload to
|
||||||
|
* status/heartbeat before disconnecting cleanly — the broker's LWT only
|
||||||
|
* fires on an *unclean* disconnect, so an intentional disconnect (e.g.
|
||||||
|
* before an OTA flash) would otherwise leave the last "online" heartbeat
|
||||||
|
* retained and misleading. Default false preserves existing call sites'
|
||||||
|
* behaviour (e.g. mqtt.disable, which does want a clean disconnect with
|
||||||
|
* no offline announcement — the broker keeps whatever was last retained).
|
||||||
|
*/
|
||||||
|
void disconnect(bool graceful = false);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Publish a reply to the control/ack topic.
|
||||||
|
* @param payload Message payload
|
||||||
|
* @param qos QoS level (0, 1, or 2)
|
||||||
|
* @param retain Retain flag
|
||||||
|
* @return Packet ID (0 if failed, MQTT disabled, low heap, or the "command"
|
||||||
|
* topic switch is off — control/ack shares that switch with control/command)
|
||||||
|
*/
|
||||||
|
uint16_t publishAck(const String& payload, int qos = 1, bool retain = false);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Publish to an absolute, fully-qualified topic (no prefix applied).
|
||||||
|
* Used for topics whose gating is decided by the caller (e.g.
|
||||||
|
* CommunicationRouter checking the relevant MqttTopicConfig flag).
|
||||||
|
* @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
|
||||||
|
*/
|
||||||
|
void setCallback(MessageCallback callback);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Set a callback fired once each time MQTT successfully connects
|
||||||
|
* (including reconnects). Used for one-shot "publish now that we're
|
||||||
|
* online" work like reporting the boot/reset reason.
|
||||||
|
*/
|
||||||
|
void setOnConnectCallback(std::function<void(bool sessionPresent)> callback) { _onConnectCallback = callback; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Register the callback used to derive the heartbeat's "state" and
|
||||||
|
* "ok" fields. Per the v2 spec these must be independently derived,
|
||||||
|
* not mirrored from status/playback or system/alerts — this callback
|
||||||
|
* is the one place that derivation happens.
|
||||||
|
* state: "idle" | "playing" | "paused" | "error" | "booting"
|
||||||
|
* ok: overall device health, independent of playback state
|
||||||
|
* Wired by CommunicationRouter from Player + HealthMonitor. If never
|
||||||
|
* set, heartbeats report state="booting", ok=true (subsystems not
|
||||||
|
* wired up yet, not necessarily unhealthy).
|
||||||
|
*/
|
||||||
|
struct DeviceState { String state; bool ok; };
|
||||||
|
void setStateProvider(std::function<DeviceState()> provider) { _stateProvider = provider; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Check if connected to MQTT broker
|
||||||
|
*/
|
||||||
|
bool isConnected() const;
|
||||||
|
|
||||||
|
/** @brief Full topic strings (read-only, available after begin()) */
|
||||||
|
const String& getCommandTopic() const { return _commandTopic; } // control/command (subscribe)
|
||||||
|
const String& getAckTopic() const { return _ackTopic; } // control/ack (reply)
|
||||||
|
const String& getHeartbeatTopic() const { return _heartbeatTopic; }
|
||||||
|
const String& getPlaybackTopic() const { return _playbackTopic; }
|
||||||
|
const String& getReportsTopic() const { return _reportsTopic; }
|
||||||
|
const String& getAlertsTopic() const { return _alertsTopic; }
|
||||||
|
const String& getInfoTopic() const { return _infoTopic; }
|
||||||
|
const String& getLogsTopic() const { return _logsTopic; }
|
||||||
|
const String& getMetricsTopic() const { return _metricsTopic; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Handle network connection callback
|
||||||
|
*/
|
||||||
|
void onNetworkConnected();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Handle network disconnection callback
|
||||||
|
*/
|
||||||
|
void onNetworkDisconnected();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Live-apply a change to the "command" topic switch without waiting
|
||||||
|
* for a reconnect. Subscribes/unsubscribes control/command immediately
|
||||||
|
* if currently connected; no-ops otherwise (the new setting is picked
|
||||||
|
* up naturally by subscribe() on the next connect via ConfigManager).
|
||||||
|
*/
|
||||||
|
void applyCommandTopicSwitch(bool enabled);
|
||||||
|
|
||||||
|
// Minimum free heap (bytes) required before attempting a publish. Below this,
|
||||||
|
// AsyncMqttClient's internal packet-buffer allocation risks failing outright —
|
||||||
|
// this SDK build has CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE=0, so a failed
|
||||||
|
// allocation that can't even throw std::bad_alloc calls abort() instead of being
|
||||||
|
// catchable. Skipping the publish (or, from MQTTTransport, skipping incoming
|
||||||
|
// command processing) is far cheaper than crashing the device. Public so
|
||||||
|
// MQTTTransport can apply the same threshold before doing its own allocation-
|
||||||
|
// heavy work (JSON deserialization) without duplicating the constant.
|
||||||
|
// See docs/features/feature-catalog.md for the incident this guards against.
|
||||||
|
static constexpr uint32_t MIN_FREE_HEAP_FOR_PUBLISH = 20480; // 20KB
|
||||||
|
bool hasHeapForPublish() const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
ConfigManager& _configManager;
|
||||||
|
Networking& _networking;
|
||||||
|
AsyncMqttClient _mqttClient;
|
||||||
|
MessageCallback _messageCallback;
|
||||||
|
std::function<void(bool sessionPresent)> _onConnectCallback;
|
||||||
|
std::function<DeviceState()> _stateProvider;
|
||||||
|
|
||||||
|
|
||||||
|
// Device topic strings (cached for performance) — see docs/reference/vesper_mqtt_topic_spec_v2.md
|
||||||
|
String _commandTopic; // vesper/{id}/control/command (subscribe)
|
||||||
|
String _ackTopic; // vesper/{id}/control/ack (reply)
|
||||||
|
String _heartbeatTopic; // vesper/{id}/status/heartbeat
|
||||||
|
String _playbackTopic; // vesper/{id}/status/playback
|
||||||
|
String _reportsTopic; // vesper/{id}/control/reports
|
||||||
|
String _alertsTopic; // vesper/{id}/system/alerts
|
||||||
|
String _infoTopic; // vesper/{id}/system/info
|
||||||
|
String _logsTopic; // vesper/{id}/system/logs
|
||||||
|
String _metricsTopic; // vesper/{id}/system/metrics
|
||||||
|
String _clientId; // Store client ID to keep it alive
|
||||||
|
|
||||||
|
// Builds the retained LWT/offline payload: {"state":"offline","ok":false}
|
||||||
|
String buildOfflinePayload() const;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Subscribe to control topic
|
||||||
|
*/
|
||||||
|
void subscribe();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief MQTT event handlers
|
||||||
|
*/
|
||||||
|
void onMqttConnect(bool sessionPresent);
|
||||||
|
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason);
|
||||||
|
void onMqttSubscribe(uint16_t packetId, uint8_t qos);
|
||||||
|
void onMqttUnsubscribe(uint16_t packetId);
|
||||||
|
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total);
|
||||||
|
void onMqttPublish(uint16_t packetId);
|
||||||
|
|
||||||
|
// Reconnection Timer with Exponential Backoff
|
||||||
|
TimerHandle_t _mqttReconnectTimer;
|
||||||
|
static const unsigned long MQTT_RECONNECT_BASE_DELAY = 5000; // 5 seconds base
|
||||||
|
static const unsigned long MQTT_RECONNECT_MAX_DELAY = 300000; // 5 minutes max
|
||||||
|
static const uint8_t MQTT_MAX_QUICK_RETRIES = 3; // Try 3 times quickly
|
||||||
|
uint8_t _reconnectAttempts; // Track failed attempts
|
||||||
|
unsigned long _lastConnectionAttempt; // Track last attempt time
|
||||||
|
void attemptReconnection();
|
||||||
|
static void mqttReconnectTimerCallback(TimerHandle_t xTimer);
|
||||||
|
static void mqttReconnectTaskFn(void* param);
|
||||||
|
unsigned long getReconnectDelay(); // Calculate backoff delay
|
||||||
|
|
||||||
|
// Network Stabilization Timer (non-blocking replacement for delay)
|
||||||
|
TimerHandle_t _networkStabilizationTimer;
|
||||||
|
static const unsigned long NETWORK_STABILIZATION_DELAY = 2000; // 2 seconds
|
||||||
|
void connectAfterStabilization();
|
||||||
|
static void networkStabilizationTimerCallback(TimerHandle_t xTimer);
|
||||||
|
static void mqttConnectTaskFn(void* param);
|
||||||
|
|
||||||
|
// Heartbeat Timer (30 seconds)
|
||||||
|
TimerHandle_t _heartbeatTimer;
|
||||||
|
static const unsigned long HEARTBEAT_INTERVAL = 30000; // 30 seconds
|
||||||
|
TaskHandle_t _heartbeatTaskHandle; // Guard: only one heartbeat task at a time
|
||||||
|
void publishHeartbeat();
|
||||||
|
static void heartbeatTimerCallback(TimerHandle_t xTimer);
|
||||||
|
static void mqttHeartbeatTaskFn(void* param);
|
||||||
|
void startHeartbeat();
|
||||||
|
void stopHeartbeat();
|
||||||
|
};
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
# MQTTDriver
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
`MQTTDriver` is the low-level MQTT protocol driver. It wraps `AsyncMqttClient` and manages the full broker connection lifecycle: configuration, authentication, subscribe/publish, exponential backoff reconnection, 30-second heartbeat, network-stabilisation delay, and Last Will and Testament. It is not aware of the `CommandBus` — that coupling lives in `MQTTTransport`. The driver uses three FreeRTOS software timers with one-shot tasks deferred off the Tmr Svc stack to avoid stack overflows in timer callbacks.
|
||||||
|
|
||||||
|
See [docs/reference/vesper_mqtt_topic_spec_v2.md](../../../../docs/reference/vesper_mqtt_topic_spec_v2.md) for the full topic table, per-topic switches, and `req_id` correlation. Topics:
|
||||||
|
|
||||||
|
- `control/command` (inbound, subscribe) — gated by the `command` topic switch
|
||||||
|
- `control/ack` (outbound replies) — gated by the `command` topic switch
|
||||||
|
- `status/heartbeat` (retained, QoS 1) — gated by the `heartbeat` topic switch
|
||||||
|
- `status/playback`, `control/reports`, `system/alerts`, `system/info`, `system/logs`, `system/metrics` — published directly by `CommunicationRouter` via `publishDirect()`, each gated by its own topic switch (see [CommunicationRouter](../../CommunicationRouter/README.md))
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Public API
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `MQTTDriver(ConfigManager& configManager, Networking& networking)` | Constructor. Creates the three FreeRTOS timers. Sets the global `_instance` pointer. |
|
||||||
|
| `void begin()` | Caches topic strings, registers AsyncMqttClient event handlers, configures broker host/port/credentials/keepalive, and registers the Last Will (see [LWT](#last-will-and-testament-lwt) below). Does not connect. |
|
||||||
|
| `void connect()` | Calls `AsyncMqttClient::connect()`. No-op if MQTT is disabled in config or already connected. |
|
||||||
|
| `void disconnect(bool graceful = false)` | Disconnects. If `graceful` is true, explicitly publishes the retained offline payload to `status/heartbeat` first — see [Graceful disconnect](#graceful-disconnect). |
|
||||||
|
| `uint16_t publishAck(const String& payload, int qos = 1, bool retain = false)` | Publishes a reply to `control/ack`. Returns packet ID, or 0 on failure (not connected, low heap, or the `command` topic switch is off). |
|
||||||
|
| `uint16_t publishDirect(const String& fullTopic, const String& payload, int qos = 0, bool retain = false)` | Publishes to an absolute, fully-qualified topic (no prefix applied) — no topic-switch gating here; the caller (`CommunicationRouter`) checks the relevant switch before calling. Same heap guard as `publishAck()`. |
|
||||||
|
| `bool hasHeapForPublish() const` | Returns `true` if `ESP.getFreeHeap() >= MIN_FREE_HEAP_FOR_PUBLISH` (20KB). Public so `MQTTTransport` can apply the same threshold before its own allocation-heavy work (JSON deserialization of incoming commands) without duplicating the constant. See [Gotchas](#gotchas--notes) below for why this exists. |
|
||||||
|
| `const String& getCommandTopic() const` / `getAckTopic()` / `getHeartbeatTopic()` / `getPlaybackTopic()` / `getReportsTopic()` / `getAlertsTopic()` / `getInfoTopic()` / `getLogsTopic()` / `getMetricsTopic()` | Cached full topic strings, available after `begin()`. |
|
||||||
|
| `void setCallback(MessageCallback callback)` | Registers the message-received callback. Called by `MQTTTransport::begin()`. |
|
||||||
|
| `void setOnConnectCallback(std::function<void(bool sessionPresent)> callback)` | Registers a callback fired once each time MQTT successfully connects (including reconnects). Used by `CommunicationRouter` for one-shot "publish now that we're online" work such as reporting the boot/reset reason. |
|
||||||
|
| `void setStateProvider(std::function<DeviceState()> provider)` | Registers the callback used to derive the heartbeat's `state`/`ok` fields — see [Heartbeat](#heartbeat) below. Wired by `CommunicationRouter` from `Player` + `HealthMonitor`. |
|
||||||
|
| `void applyCommandTopicSwitch(bool enabled)` | Live-applies a change to the `command` topic switch: subscribes/unsubscribes `control/command` immediately if connected, no-ops otherwise (picked up naturally on next connect). Called by `MQTTHandler::handleSetTopics()`. |
|
||||||
|
| `bool isConnected() const` | Returns the AsyncMqttClient connection state. |
|
||||||
|
| `void onNetworkConnected()` | Starts the 2-second network-stabilisation timer; connects after it fires. Resets `_reconnectAttempts`. |
|
||||||
|
| `void onNetworkDisconnected()` | Force-disconnects the client if connected. Reconnect logic waits for the next `onNetworkConnected()`. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Initialization
|
||||||
|
|
||||||
|
`MQTTTransport::begin()` sets the message callback on the driver, then calls `MQTTDriver::begin()`. The broker connection is not initiated here — it is triggered by `onNetworkConnected()` when the network becomes available.
|
||||||
|
|
||||||
|
`MQTTDriver` is constructed inside `CommunicationRouter` as a member:
|
||||||
|
```cpp
|
||||||
|
MQTTDriver _mqttClient; // in CommunicationRouter
|
||||||
|
```
|
||||||
|
|
||||||
|
The constructor creates all three FreeRTOS timers. If timer creation fails (extremely low memory), the `nullptr` guards in each callback will prevent crashes but MQTT will not reconnect automatically.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Reconnect Behaviour
|
||||||
|
|
||||||
|
| Attempts | Delay |
|
||||||
|
|----------|-------|
|
||||||
|
| 1–3 (quick retries) | 5 seconds each |
|
||||||
|
| 4 | 10 seconds |
|
||||||
|
| 5 | 20 seconds |
|
||||||
|
| 6 | 40 seconds |
|
||||||
|
| 7+ | Capped at 300 seconds (5 minutes) |
|
||||||
|
|
||||||
|
Reconnect attempts are reset to 0 on a successful connection or a new `onNetworkConnected()` event.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Last Will and Testament (LWT)
|
||||||
|
|
||||||
|
Registered once in `begin()` via `AsyncMqttClient::setWill()`, targeting `status/heartbeat` (QoS 1, retained) with payload `{"device_id": "...", "state": "offline", "ok": false}`. `AsyncMqttClient` resends the Will on every CONNECT packet, including reconnects, so no manual re-registration is needed after the first `begin()`.
|
||||||
|
|
||||||
|
The broker fires the Will **only on an unclean disconnect** (network loss, crash, power loss) — it does not fire on a clean, intentional disconnect. See [Graceful disconnect](#graceful-disconnect) for the intentional case.
|
||||||
|
|
||||||
|
### Graceful disconnect
|
||||||
|
|
||||||
|
`disconnect(true)` publishes the same offline payload explicitly, with `retain=true`, before calling the underlying clean disconnect — this prevents a stale "online" heartbeat from staying retained after an intentional disconnect (e.g. `mqtt.disable`, or before an OTA flash). `disconnect(false)` (the default) skips this and disconnects immediately — used where the caller doesn't want an offline announcement (rare; most call sites should use `graceful=true`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Heartbeat
|
||||||
|
|
||||||
|
Once connected, a heartbeat is published immediately and then every 30 seconds to `status/heartbeat` with `retain = true`, gated by the `heartbeat` topic switch. Payload (flat, no envelope wrapper):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"device_id": "PV000000000000",
|
||||||
|
"state": "idle",
|
||||||
|
"ok": true,
|
||||||
|
"fw_version": "2.1.1",
|
||||||
|
"uptime_ms": 19425000,
|
||||||
|
"uptime_human": "5h 23m 45s",
|
||||||
|
"ip_address": "10.0.0.3",
|
||||||
|
"gateway": "10.0.0.1",
|
||||||
|
"rssi": -62,
|
||||||
|
"free_heap": 142000
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`state` (`idle`/`playing`/`paused`/`error`/`booting`) and `ok` are produced by the `_stateProvider` callback — see `setStateProvider()` above — and are **independently derived**, never mirrored from `status/playback` or `system/alerts`, per the topic spec. `CommunicationRouter` wires this from `Player::isCurrentlyPlaying()`/`isCurrentlyPaused()` and `HealthMonitor::isFirmwareStable()`. If no provider is registered, heartbeats report `state="booting", ok=true`.
|
||||||
|
|
||||||
|
The heartbeat timer is stopped on disconnect and restarted on reconnect.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
- `AsyncMqttClient` — broker protocol
|
||||||
|
- `ConfigManager` — MQTT host, port, credentials, enabled flag, device UID, per-topic switches (`MqttTopicConfig`)
|
||||||
|
- `Networking` — `isConnected()` check before reconnect attempts; IP and gateway for heartbeat
|
||||||
|
- FreeRTOS — three `TimerHandle_t` timers, one `TaskHandle_t` for heartbeat task guard
|
||||||
|
- `Logging`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Gotchas / Notes
|
||||||
|
|
||||||
|
- **Singleton pattern via `_instance`.** The class uses a static `_instance` pointer for routing timer callbacks back to the instance. Only one `MQTTDriver` should exist at a time. The constructor overwrites `_instance`, so creating two instances will break the first one's callbacks.
|
||||||
|
- **Timer callbacks defer to tasks.** Timer callbacks run in the FreeRTOS Timer Service task (Tmr Svc, default 2 KB stack). Any callback that calls `LOG_*` macros, `connect()`, or JSON serialisation would overflow this stack. All three callbacks (`mqttReconnectTimerCallback`, `networkStabilizationTimerCallback`, `heartbeatTimerCallback`) spawn a 3 KB task and return immediately.
|
||||||
|
- **Heartbeat task guard.** If the previous heartbeat task has not yet exited when the next timer fires, the new task is not spawned. This prevents task accumulation under slow broker connections.
|
||||||
|
- **Error logging is suppressed on publish failure.** `publishAck()` does not log an error when `_mqttClient.publish()` returns 0 (packet ID failure), because it's also reachable from the MQTT log channel and logging an error there would recurse infinitely.
|
||||||
|
- **Free-heap guard before publishing (`hasHeapForPublish()`).** Below `MIN_FREE_HEAP_FOR_PUBLISH` (20KB), `publishAck()`, `publishDirect()`, and `publishHeartbeat()` skip the operation entirely rather than risk `AsyncMqttClient::publish()`'s internal packet-buffer allocation failing. This SDK build has `CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE=0` — a failed allocation under heavy fragmentation can't even throw a catchable `std::bad_alloc`, it calls `abort()` directly. This guard exists because exactly that happened in production under a rapid MQTT command burst with verbose logging (see `docs/features/feature-catalog.md` F-055 for the full `addr2line`-decoded diagnosis). The skip is logged via `Serial.printf()` directly, not `LOG_*` — logging the skip over MQTT would itself attempt a publish, recursing into the same low-heap condition.
|
||||||
|
- **Credentials from NVS.** The broker username and password are read from `ConfigManager`, which loads them from NVS at boot. The password is a 32-character HMAC-SHA256 hex digest derived from the device UID and `MQTT_SECRET` (compiled in via `-DMQTT_SECRET`).
|
||||||
|
- **`begin()` must be called before `connect()`.** `begin()` registers AsyncMqttClient event handlers, configures the server, and registers the Will. Calling `connect()` before `begin()` will silently do nothing useful.
|
||||||
|
- **`onConnect` callback fires on every connect, not just the first.** `setOnConnectCallback` fires on every successful connection, including reconnects after a drop — callers that want "once per boot" semantics (like `CommunicationRouter::reportBootOnce()`) must track that themselves.
|
||||||
|
- **`command` topic switch gates both directions.** Turning `command` off both unsubscribes `control/command` (no more inbound commands) and blocks `publishAck()` (no more outbound replies) — see `docs/reference/vesper_mqtt_topic_spec_v2.md`. The other seven switches (`heartbeat`, `playback`, `reports`, `alerts`, `info`, `logs`, `metrics`) are checked by their respective publishers, not inside this driver — `publishDirect()` itself does not know which topic switch applies to the topic it's given.
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
# UARTDriver
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
`UARTDriver` is the low-level UART I/O driver for the slave device interface (LCD panel, button board). It operates on `Serial2` using newline-delimited JSON framing. Incoming bytes are accumulated in a 1 KB ring buffer; when a newline is received, the accumulated line is parsed as JSON and the registered callback is invoked. Outgoing messages are sent with an appended newline and a blocking `flush()`. The driver must be polled via `loop()` — it does not run in its own task.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Public API
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `UARTDriver(uint8_t txPin, uint8_t rxPin, uint32_t baudRate)` | Constructor. Defaults: TX=GPIO 12, RX=GPIO 13, 115200 baud. Uses `Serial2`. |
|
||||||
|
| `void begin()` | Initialises `Serial2` with the configured pins and baud rate; flushes any garbage in the RX buffer. |
|
||||||
|
| `void loop()` | Reads all available bytes from `Serial2` into the line buffer. Calls `processLine()` when `'\n'` or `'\r'` is detected. **Must be called from the main loop or a polling task.** |
|
||||||
|
| `void setCallback(MessageCallback callback)` | Registers the callback invoked with a parsed `JsonDocument&` for each valid message. |
|
||||||
|
| `void send(const String& response)` | Sends `response` followed by `'\n'` and calls `flush()`. |
|
||||||
|
| `bool isReady() const` | Returns `true` after `begin()` has been called successfully. |
|
||||||
|
| `uint32_t getMessageCount() const` | Number of successfully parsed messages since boot. |
|
||||||
|
| `uint32_t getErrorCount() const` | Number of JSON parse errors or buffer overflows since boot. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Initialization
|
||||||
|
|
||||||
|
`UARTTransport::begin()` sets the message callback, then calls `UARTDriver::begin()`. The driver is a member of `CommunicationRouter` via `UARTTransport`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Wire Protocol
|
||||||
|
|
||||||
|
- **Physical**: Serial2, TX GPIO 12, RX GPIO 13, 115200 8N1
|
||||||
|
- **Framing**: newline-delimited (`'\n'` or `'\r'`)
|
||||||
|
- **Encoding**: JSON, max 1023 bytes per message (1024-byte buffer minus null terminator)
|
||||||
|
|
||||||
|
Example message from slave:
|
||||||
|
```
|
||||||
|
{"v":2,"cmd":"playback","contents":{"action":"stop"}}\n
|
||||||
|
```
|
||||||
|
|
||||||
|
Example response to slave:
|
||||||
|
```
|
||||||
|
{"status":"SUCCESS","type":"playback","message":"Playback command executed"}\n
|
||||||
|
```
|
||||||
|
|
||||||
|
JSON parse errors generate an automatic error response:
|
||||||
|
```
|
||||||
|
{"status":"ERROR","type":"parse_error","payload":"<error>"}\n
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
- `HardwareSerial` (Arduino) — `Serial2`
|
||||||
|
- `ArduinoJson` — JSON parsing (`StaticJsonDocument<1024>`)
|
||||||
|
- `Logging`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Gotchas / Notes
|
||||||
|
|
||||||
|
- **`loop()` must be called.** UART input is not interrupt-driven at the application level. Without regular `loop()` calls, the Serial2 hardware FIFO can overflow.
|
||||||
|
- **Buffer overflow drops the entire message.** When `_bufferIndex` reaches 1023 without a newline, the buffer is reset and `_errorCount` is incremented. The slave receives no error response in this case.
|
||||||
|
- **`send()` is blocking.** `Serial.flush()` blocks until the TX hardware buffer drains. At 115200 baud this is approximately 1 byte per 87 µs. A 100-byte response takes ~8.7 ms. This can affect main loop timing if the slave is slow to consume data.
|
||||||
|
- **`JsonDocument&` is passed by reference** to the callback. The document lives on the stack inside `processLine()` and is valid only for the duration of the callback. Do not store a reference to it.
|
||||||
|
- **No v1 legacy handling at this level.** The driver passes raw JSON to the callback. Legacy translation (if `"v": 1`) is handled upstream by `CommandBus::dispatch()`.
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
/*
|
||||||
|
* UARTDRIVER.CPP - UART Protocol Driver Implementation
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "UARTDriver.hpp"
|
||||||
|
|
||||||
|
#define TAG "UARTHandler"
|
||||||
|
#include "../../../Logging/Logging.hpp"
|
||||||
|
|
||||||
|
UARTDriver::UARTDriver(uint8_t txPin, uint8_t rxPin, uint32_t baudRate)
|
||||||
|
: _serial(Serial2)
|
||||||
|
, _txPin(txPin)
|
||||||
|
, _rxPin(rxPin)
|
||||||
|
, _baudRate(baudRate)
|
||||||
|
, _ready(false)
|
||||||
|
, _bufferIndex(0)
|
||||||
|
, _messageCount(0)
|
||||||
|
, _errorCount(0)
|
||||||
|
, _callback(nullptr)
|
||||||
|
{
|
||||||
|
resetBuffer();
|
||||||
|
}
|
||||||
|
|
||||||
|
UARTDriver::~UARTDriver() {
|
||||||
|
_serial.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
void UARTDriver::begin() {
|
||||||
|
LOG_INFO(TAG, "Initializing UART Command Handler");
|
||||||
|
LOG_INFO(TAG, " TX Pin: GPIO%d", _txPin);
|
||||||
|
LOG_INFO(TAG, " RX Pin: GPIO%d", _rxPin);
|
||||||
|
LOG_INFO(TAG, " Baud Rate: %u", _baudRate);
|
||||||
|
|
||||||
|
// Initialize Serial2 with custom pins
|
||||||
|
_serial.begin(_baudRate, SERIAL_8N1, _rxPin, _txPin);
|
||||||
|
|
||||||
|
// Clear any garbage in the buffer
|
||||||
|
while (_serial.available()) {
|
||||||
|
_serial.read();
|
||||||
|
}
|
||||||
|
|
||||||
|
_ready = true;
|
||||||
|
LOG_INFO(TAG, "UART Command Handler ready");
|
||||||
|
}
|
||||||
|
|
||||||
|
void UARTDriver::loop() {
|
||||||
|
if (!_ready) return;
|
||||||
|
|
||||||
|
// Process all available bytes
|
||||||
|
while (_serial.available()) {
|
||||||
|
char c = _serial.read();
|
||||||
|
|
||||||
|
// Check for message delimiter (newline)
|
||||||
|
if (c == '\n' || c == '\r') {
|
||||||
|
if (_bufferIndex > 0) {
|
||||||
|
// Null-terminate and process
|
||||||
|
_buffer[_bufferIndex] = '\0';
|
||||||
|
processLine(_buffer);
|
||||||
|
resetBuffer();
|
||||||
|
}
|
||||||
|
// Skip empty lines
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add character to buffer
|
||||||
|
if (_bufferIndex < BUFFER_SIZE - 1) {
|
||||||
|
_buffer[_bufferIndex++] = c;
|
||||||
|
} else {
|
||||||
|
// Buffer overflow - discard and reset
|
||||||
|
LOG_ERROR(TAG, "UART buffer overflow, discarding message");
|
||||||
|
_errorCount++;
|
||||||
|
resetBuffer();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void UARTDriver::setCallback(MessageCallback callback) {
|
||||||
|
_callback = callback;
|
||||||
|
}
|
||||||
|
|
||||||
|
void UARTDriver::send(const String& response) {
|
||||||
|
if (!_ready) {
|
||||||
|
LOG_ERROR(TAG, "UART not ready, cannot send response");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_serial.print(response);
|
||||||
|
_serial.print('\n'); // Newline delimiter
|
||||||
|
_serial.flush(); // Ensure data is sent
|
||||||
|
|
||||||
|
LOG_DEBUG(TAG, "UART TX: %s", response.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
void UARTDriver::processLine(const char* line) {
|
||||||
|
LOG_DEBUG(TAG, "UART RX: %s", line);
|
||||||
|
|
||||||
|
// Skip empty lines or whitespace-only
|
||||||
|
if (strlen(line) == 0) return;
|
||||||
|
|
||||||
|
// Parse JSON
|
||||||
|
JsonDocument doc;
|
||||||
|
DeserializationError error = deserializeJson(doc, line);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
LOG_ERROR(TAG, "UART JSON parse error: %s", error.c_str());
|
||||||
|
_errorCount++;
|
||||||
|
|
||||||
|
// Send error response back
|
||||||
|
JsonDocument errorDoc;
|
||||||
|
errorDoc["status"] = "ERROR";
|
||||||
|
errorDoc["type"] = "parse_error";
|
||||||
|
errorDoc["payload"] = error.c_str();
|
||||||
|
|
||||||
|
String errorResponse;
|
||||||
|
serializeJson(errorDoc, errorResponse);
|
||||||
|
send(errorResponse);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_messageCount++;
|
||||||
|
|
||||||
|
// Invoke callback if set
|
||||||
|
if (_callback) {
|
||||||
|
_callback(doc);
|
||||||
|
} else {
|
||||||
|
LOG_WARNING(TAG, "UART message received but no callback set");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void UARTDriver::resetBuffer() {
|
||||||
|
_bufferIndex = 0;
|
||||||
|
memset(_buffer, 0, BUFFER_SIZE);
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
/*
|
||||||
|
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||||
|
* UARTDRIVER.HPP - UART Protocol Driver
|
||||||
|
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||||
|
*
|
||||||
|
* Low-level UART protocol driver for external devices (LCD panels, button boards).
|
||||||
|
* Reads newline-delimited JSON on Serial2 (TX: GPIO12, RX: GPIO13 @ 115200 baud).
|
||||||
|
* Wrapped by UARTTransport for CommandBus integration.
|
||||||
|
*
|
||||||
|
* 📋 VERSION: 1.0
|
||||||
|
* 📅 DATE: 2025-01-19
|
||||||
|
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||||
|
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <ArduinoJson.h>
|
||||||
|
#include <functional>
|
||||||
|
|
||||||
|
class UARTDriver {
|
||||||
|
public:
|
||||||
|
// Default pin configuration
|
||||||
|
static constexpr uint8_t DEFAULT_TX_PIN = 12;
|
||||||
|
static constexpr uint8_t DEFAULT_RX_PIN = 13;
|
||||||
|
static constexpr uint32_t DEFAULT_BAUD_RATE = 115200;
|
||||||
|
static constexpr size_t BUFFER_SIZE = 1024;
|
||||||
|
|
||||||
|
// Message callback type - called when a complete JSON message is received
|
||||||
|
using MessageCallback = std::function<void(JsonDocument& message)>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Construct UART handler with custom pins
|
||||||
|
* @param txPin GPIO pin for TX (default: 12)
|
||||||
|
* @param rxPin GPIO pin for RX (default: 13)
|
||||||
|
* @param baudRate Baud rate (default: 115200)
|
||||||
|
*/
|
||||||
|
explicit UARTDriver(uint8_t txPin = DEFAULT_TX_PIN,
|
||||||
|
uint8_t rxPin = DEFAULT_RX_PIN,
|
||||||
|
uint32_t baudRate = DEFAULT_BAUD_RATE);
|
||||||
|
|
||||||
|
~UARTDriver();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Initialize the UART interface
|
||||||
|
*/
|
||||||
|
void begin();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Process incoming UART data (call from loop or task)
|
||||||
|
* Non-blocking - processes available bytes and returns
|
||||||
|
*/
|
||||||
|
void loop();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Set callback for received messages
|
||||||
|
* @param callback Function to call with parsed JSON
|
||||||
|
*/
|
||||||
|
void setCallback(MessageCallback callback);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Send a response back over UART
|
||||||
|
* @param response JSON string to send (newline appended automatically)
|
||||||
|
*/
|
||||||
|
void send(const String& response);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Check if UART is initialized and ready
|
||||||
|
*/
|
||||||
|
bool isReady() const { return _ready; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Get number of messages received since boot
|
||||||
|
*/
|
||||||
|
uint32_t getMessageCount() const { return _messageCount; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Get number of parse errors since boot
|
||||||
|
*/
|
||||||
|
uint32_t getErrorCount() const { return _errorCount; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
HardwareSerial& _serial;
|
||||||
|
uint8_t _txPin;
|
||||||
|
uint8_t _rxPin;
|
||||||
|
uint32_t _baudRate;
|
||||||
|
bool _ready;
|
||||||
|
|
||||||
|
// Receive buffer
|
||||||
|
char _buffer[BUFFER_SIZE];
|
||||||
|
size_t _bufferIndex;
|
||||||
|
|
||||||
|
// Statistics
|
||||||
|
uint32_t _messageCount;
|
||||||
|
uint32_t _errorCount;
|
||||||
|
|
||||||
|
// Callback
|
||||||
|
MessageCallback _callback;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Process a complete line from the buffer
|
||||||
|
* @param line Null-terminated string containing the message
|
||||||
|
*/
|
||||||
|
void processLine(const char* line);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Reset the receive buffer
|
||||||
|
*/
|
||||||
|
void resetBuffer();
|
||||||
|
};
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# WebSocketDriver
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
`WebSocketDriver` is the low-level WebSocket protocol driver. It wraps `AsyncWebSocket` and delegates client lifecycle management (add, remove, type classification, targeted sends, broadcast) to `ClientManager`. When a complete text frame is received, it parses the JSON payload and invokes the registered callback with the client ID and parsed document. `WebSocketTransport` sits on top of this driver and connects it to the `CommandBus`. The driver also sends an unsolicited welcome message to each new client on connect.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Public API
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `WebSocketDriver(AsyncWebSocket& webSocket, ClientManager& clientManager)` | Constructor. Sets the global `_instance` pointer. |
|
||||||
|
| `void begin()` | Registers the static `onEvent` callback with `AsyncWebSocket`. Does not add the handler to `AsyncWebServer` — that is done by `CommunicationRouter::begin()` via `_server.addHandler(&_webSocket)`. |
|
||||||
|
| `void setCallback(MessageCallback callback)` | Registers the message-received callback. Called by `WebSocketTransport::begin()`. Signature: `void(uint32_t clientId, const JsonDocument& message)`. |
|
||||||
|
| `void sendToClient(uint32_t clientId, const String& message)` | Sends a message to a specific connected client. Delegates to `ClientManager::sendToClient()`. |
|
||||||
|
| `void broadcastToAll(const String& message)` | Sends to all connected clients via `ClientManager::broadcastToAll()`. |
|
||||||
|
| `void broadcastToMaster(const String& message)` | Sends to clients classified as `MASTER` only. |
|
||||||
|
| `void broadcastToSecondary(const String& message)` | Sends to clients classified as `SECONDARY` only. |
|
||||||
|
| `bool hasClients() const` | True if at least one client is connected. |
|
||||||
|
| `size_t getClientCount() const` | Number of currently connected clients. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Initialization
|
||||||
|
|
||||||
|
`CommunicationRouter::begin()`:
|
||||||
|
1. Calls `_server.addHandler(&_webSocket)` — attaches the WebSocket handler to the HTTP server.
|
||||||
|
2. Calls `_wsTransport.begin()` — which calls `WebSocketDriver::begin()` to register the event callback.
|
||||||
|
|
||||||
|
The `AsyncWebServer` is started later by `main.cpp` in the network-connected callback.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
- `AsyncWebSocket` (ESPAsyncWebServer) — WebSocket protocol layer
|
||||||
|
- `ClientManager` — client registry, type tracking, targeted/broadcast sends
|
||||||
|
- `ResponseBuilder` — used for the welcome message on connect and parse error responses
|
||||||
|
- `ArduinoJson`, `Logging`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Gotchas / Notes
|
||||||
|
|
||||||
|
- **Singleton pattern via `_instance`.** `AsyncWebSocket::onEvent` is a static C-style callback. The driver routes it through `WebSocketDriver::_instance`. Only one instance should ever be created.
|
||||||
|
- **Only complete single-frame text messages are processed.** The `onData` handler checks `info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT`. Fragmented messages and binary frames are dropped with a warning.
|
||||||
|
- **Per-message heap allocation.** Each incoming message allocates a `char*` buffer via `malloc(len + 1)`. If allocation fails, the client receives a `"memory_error"` response. This is the only dynamic allocation path in the driver.
|
||||||
|
- **JSON parse limit: 2 KB (`StaticJsonDocument<2048>`).** Messages larger than this will fail to parse. The client receives a `"parse_error"` response.
|
||||||
|
- **Client cleanup is external.** The driver calls `_clientManager.cleanupDisconnectedClients()` on each disconnect event, but dead ghost connections (network drop without close frame) are only evicted when `ws.cleanupClients()` is called from `main.cpp` every 2 seconds.
|
||||||
|
- **Welcome message uses `ResponseBuilder`.** The welcome message on connect (`"type": "connection"`) is built with the legacy `ResponseBuilder::success()` path. New code should use `CommandResult` factory methods.
|
||||||
+36
-34
@@ -1,15 +1,17 @@
|
|||||||
/*
|
/*
|
||||||
* WEBSOCKETSERVER.CPP - WebSocket Server Implementation
|
* WEBSOCKETDRIVER.CPP - WebSocket Protocol Driver Implementation
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include "WebSocketServer.hpp"
|
#include "WebSocketDriver.hpp"
|
||||||
#include "../../Logging/Logging.hpp"
|
|
||||||
#include "../ResponseBuilder/ResponseBuilder.hpp"
|
#define TAG "WebSocket"
|
||||||
|
#include "../../../Logging/Logging.hpp"
|
||||||
|
#include "../../ResponseBuilder/ResponseBuilder.hpp"
|
||||||
|
|
||||||
// Static instance for callback
|
// Static instance for callback
|
||||||
WebSocketServer* WebSocketServer::_instance = nullptr;
|
WebSocketDriver* WebSocketDriver::_instance = nullptr;
|
||||||
|
|
||||||
WebSocketServer::WebSocketServer(AsyncWebSocket& webSocket, ClientManager& clientManager)
|
WebSocketDriver::WebSocketDriver(AsyncWebSocket& webSocket, ClientManager& clientManager)
|
||||||
: _webSocket(webSocket)
|
: _webSocket(webSocket)
|
||||||
, _clientManager(clientManager)
|
, _clientManager(clientManager)
|
||||||
, _messageCallback(nullptr) {
|
, _messageCallback(nullptr) {
|
||||||
@@ -17,54 +19,54 @@ WebSocketServer::WebSocketServer(AsyncWebSocket& webSocket, ClientManager& clien
|
|||||||
_instance = this;
|
_instance = this;
|
||||||
}
|
}
|
||||||
|
|
||||||
WebSocketServer::~WebSocketServer() {
|
WebSocketDriver::~WebSocketDriver() {
|
||||||
_instance = nullptr;
|
_instance = nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
void WebSocketServer::begin() {
|
void WebSocketDriver::begin() {
|
||||||
_webSocket.onEvent(onEvent);
|
_webSocket.onEvent(onEvent);
|
||||||
LOG_INFO("WebSocket server initialized on /ws");
|
LOG_INFO(TAG, "WebSocket server initialized on /ws");
|
||||||
|
|
||||||
// 🔥 CRITICAL: This line was missing - attach WebSocket to the AsyncWebServer
|
// 🔥 CRITICAL: This line was missing - attach WebSocket to the AsyncWebServer
|
||||||
// Without this, the server doesn't know about the WebSocket handler!
|
// Without this, the server doesn't know about the WebSocket handler!
|
||||||
// Note: We can't access _server here directly, so this must be done in CommunicationRouter
|
// Note: We can't access _server here directly, so this must be done in CommunicationRouter
|
||||||
}
|
}
|
||||||
|
|
||||||
void WebSocketServer::setCallback(MessageCallback callback) {
|
void WebSocketDriver::setCallback(MessageCallback callback) {
|
||||||
_messageCallback = callback;
|
_messageCallback = callback;
|
||||||
}
|
}
|
||||||
|
|
||||||
void WebSocketServer::sendToClient(uint32_t clientId, const String& message) {
|
void WebSocketDriver::sendToClient(uint32_t clientId, const String& message) {
|
||||||
_clientManager.sendToClient(clientId, message);
|
_clientManager.sendToClient(clientId, message);
|
||||||
}
|
}
|
||||||
|
|
||||||
void WebSocketServer::broadcastToAll(const String& message) {
|
void WebSocketDriver::broadcastToAll(const String& message) {
|
||||||
_clientManager.broadcastToAll(message);
|
_clientManager.broadcastToAll(message);
|
||||||
LOG_DEBUG("Broadcast to all WebSocket clients: %s", message.c_str());
|
LOG_DEBUG(TAG, "Broadcast to all WebSocket clients: %s", message.c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
void WebSocketServer::broadcastToMaster(const String& message) {
|
void WebSocketDriver::broadcastToMaster(const String& message) {
|
||||||
_clientManager.sendToMasterClients(message);
|
_clientManager.sendToMasterClients(message);
|
||||||
LOG_DEBUG("Broadcast to master clients: %s", message.c_str());
|
LOG_DEBUG(TAG, "Broadcast to master clients: %s", message.c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
void WebSocketServer::broadcastToSecondary(const String& message) {
|
void WebSocketDriver::broadcastToSecondary(const String& message) {
|
||||||
_clientManager.sendToSecondaryClients(message);
|
_clientManager.sendToSecondaryClients(message);
|
||||||
LOG_DEBUG("Broadcast to secondary clients: %s", message.c_str());
|
LOG_DEBUG(TAG, "Broadcast to secondary clients: %s", message.c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
bool WebSocketServer::hasClients() const {
|
bool WebSocketDriver::hasClients() const {
|
||||||
return _clientManager.hasClients();
|
return _clientManager.hasClients();
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t WebSocketServer::getClientCount() const {
|
size_t WebSocketDriver::getClientCount() const {
|
||||||
return _clientManager.getClientCount();
|
return _clientManager.getClientCount();
|
||||||
}
|
}
|
||||||
|
|
||||||
void WebSocketServer::onEvent(AsyncWebSocket* server, AsyncWebSocketClient* client,
|
void WebSocketDriver::onEvent(AsyncWebSocket* server, AsyncWebSocketClient* client,
|
||||||
AwsEventType type, void* arg, uint8_t* data, size_t len) {
|
AwsEventType type, void* arg, uint8_t* data, size_t len) {
|
||||||
if (!_instance) {
|
if (!_instance) {
|
||||||
LOG_ERROR("WebSocketServer static instance is NULL - callback ignored!");
|
LOG_ERROR(TAG, "WebSocketDriver static instance is NULL - callback ignored!");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,7 +84,7 @@ void WebSocketServer::onEvent(AsyncWebSocket* server, AsyncWebSocketClient* clie
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case WS_EVT_ERROR:
|
case WS_EVT_ERROR:
|
||||||
LOG_ERROR("WebSocket client #%u error(%u): %s",
|
LOG_ERROR(TAG, "WebSocket client #%u error(%u): %s",
|
||||||
client->id(), *((uint16_t*)arg), (char*)data);
|
client->id(), *((uint16_t*)arg), (char*)data);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
@@ -91,8 +93,8 @@ void WebSocketServer::onEvent(AsyncWebSocket* server, AsyncWebSocketClient* clie
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void WebSocketServer::onConnect(AsyncWebSocketClient* client) {
|
void WebSocketDriver::onConnect(AsyncWebSocketClient* client) {
|
||||||
LOG_INFO("WebSocket client #%u connected from %s",
|
LOG_INFO(TAG, "WebSocket client #%u connected from %s",
|
||||||
client->id(), client->remoteIP().toString().c_str());
|
client->id(), client->remoteIP().toString().c_str());
|
||||||
|
|
||||||
// Add client to manager (type UNKNOWN until they identify)
|
// Add client to manager (type UNKNOWN until they identify)
|
||||||
@@ -103,14 +105,14 @@ void WebSocketServer::onConnect(AsyncWebSocketClient* client) {
|
|||||||
_clientManager.sendToClient(client->id(), welcomeMsg);
|
_clientManager.sendToClient(client->id(), welcomeMsg);
|
||||||
}
|
}
|
||||||
|
|
||||||
void WebSocketServer::onDisconnect(AsyncWebSocketClient* client) {
|
void WebSocketDriver::onDisconnect(AsyncWebSocketClient* client) {
|
||||||
LOG_INFO("WebSocket client #%u disconnected", client->id());
|
LOG_INFO(TAG, "WebSocket client #%u disconnected", client->id());
|
||||||
|
|
||||||
_clientManager.removeClient(client->id());
|
_clientManager.removeClient(client->id());
|
||||||
_clientManager.cleanupDisconnectedClients();
|
_clientManager.cleanupDisconnectedClients();
|
||||||
}
|
}
|
||||||
|
|
||||||
void WebSocketServer::onData(AsyncWebSocketClient* client, void* arg, uint8_t* data, size_t len) {
|
void WebSocketDriver::onData(AsyncWebSocketClient* client, void* arg, uint8_t* data, size_t len) {
|
||||||
AwsFrameInfo* info = (AwsFrameInfo*)arg;
|
AwsFrameInfo* info = (AwsFrameInfo*)arg;
|
||||||
|
|
||||||
// Only handle complete, single-frame text messages
|
// Only handle complete, single-frame text messages
|
||||||
@@ -118,7 +120,7 @@ void WebSocketServer::onData(AsyncWebSocketClient* client, void* arg, uint8_t* d
|
|||||||
// Allocate buffer for payload
|
// Allocate buffer for payload
|
||||||
char* payload = (char*)malloc(len + 1);
|
char* payload = (char*)malloc(len + 1);
|
||||||
if (!payload) {
|
if (!payload) {
|
||||||
LOG_ERROR("Failed to allocate memory for WebSocket payload");
|
LOG_ERROR(TAG, "Failed to allocate memory for WebSocket payload");
|
||||||
String errorResponse = ResponseBuilder::error("memory_error", "Out of memory");
|
String errorResponse = ResponseBuilder::error("memory_error", "Out of memory");
|
||||||
_clientManager.sendToClient(client->id(), errorResponse);
|
_clientManager.sendToClient(client->id(), errorResponse);
|
||||||
return;
|
return;
|
||||||
@@ -127,14 +129,14 @@ void WebSocketServer::onData(AsyncWebSocketClient* client, void* arg, uint8_t* d
|
|||||||
memcpy(payload, data, len);
|
memcpy(payload, data, len);
|
||||||
payload[len] = '\0';
|
payload[len] = '\0';
|
||||||
|
|
||||||
LOG_DEBUG("WebSocket client #%u sent: %s", client->id(), payload);
|
LOG_DEBUG(TAG, "WebSocket client #%u sent: %s", client->id(), payload);
|
||||||
|
|
||||||
// Parse JSON
|
// Parse JSON
|
||||||
StaticJsonDocument<2048> doc;
|
JsonDocument doc;
|
||||||
DeserializationError error = deserializeJson(doc, payload);
|
DeserializationError error = deserializeJson(doc, payload);
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
LOG_ERROR("Failed to parse WebSocket JSON from client #%u: %s", client->id(), error.c_str());
|
LOG_ERROR(TAG, "Failed to parse WebSocket JSON from client #%u: %s", client->id(), error.c_str());
|
||||||
String errorResponse = ResponseBuilder::error("parse_error", "Invalid JSON");
|
String errorResponse = ResponseBuilder::error("parse_error", "Invalid JSON");
|
||||||
_clientManager.sendToClient(client->id(), errorResponse);
|
_clientManager.sendToClient(client->id(), errorResponse);
|
||||||
} else {
|
} else {
|
||||||
@@ -143,15 +145,15 @@ void WebSocketServer::onData(AsyncWebSocketClient* client, void* arg, uint8_t* d
|
|||||||
|
|
||||||
// Call user callback if set
|
// Call user callback if set
|
||||||
if (_messageCallback) {
|
if (_messageCallback) {
|
||||||
LOG_DEBUG("Routing message from client #%u to callback handler", client->id());
|
LOG_DEBUG(TAG, "Routing message from client #%u to callback handler", client->id());
|
||||||
_messageCallback(client->id(), doc);
|
_messageCallback(client->id(), doc);
|
||||||
} else {
|
} else {
|
||||||
LOG_WARNING("WebSocket message received but no callback handler is set!");
|
LOG_WARNING(TAG, "WebSocket message received but no callback handler is set!");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
free(payload);
|
free(payload);
|
||||||
} else {
|
} else {
|
||||||
LOG_WARNING("Received fragmented or non-text WebSocket message from client #%u - ignoring", client->id());
|
LOG_WARNING(TAG, "Received fragmented or non-text WebSocket message from client #%u - ignoring", client->id());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+9
-13
@@ -1,15 +1,11 @@
|
|||||||
/*
|
/*
|
||||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||||
* WEBSOCKETSERVER.HPP - WebSocket Server Manager
|
* WEBSOCKETDRIVER.HPP - WebSocket Protocol Driver
|
||||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||||
*
|
*
|
||||||
* 📡 WEBSOCKET MULTI-CLIENT MANAGER 📡
|
* Low-level WebSocket protocol driver. Manages client lifecycle, broadcasts,
|
||||||
*
|
* and targeted messaging. Wraps AsyncWebSocket + ClientManager.
|
||||||
* Handles WebSocket connections with:
|
* Wrapped by WebSocketTransport for CommandBus integration.
|
||||||
* • Multi-client support with device type identification
|
|
||||||
* • Automatic client cleanup
|
|
||||||
* • Broadcast and targeted messaging
|
|
||||||
* • Integration with ClientManager
|
|
||||||
*
|
*
|
||||||
* 📋 VERSION: 1.0
|
* 📋 VERSION: 1.0
|
||||||
* 📅 DATE: 2025-10-01
|
* 📅 DATE: 2025-10-01
|
||||||
@@ -22,15 +18,15 @@
|
|||||||
#include <Arduino.h>
|
#include <Arduino.h>
|
||||||
#include <ESPAsyncWebServer.h>
|
#include <ESPAsyncWebServer.h>
|
||||||
#include <ArduinoJson.h>
|
#include <ArduinoJson.h>
|
||||||
#include "../../ClientManager/ClientManager.hpp"
|
#include "../../../ClientManager/ClientManager.hpp"
|
||||||
|
|
||||||
class WebSocketServer {
|
class WebSocketDriver {
|
||||||
public:
|
public:
|
||||||
// Message callback type
|
// Message callback type
|
||||||
using MessageCallback = std::function<void(uint32_t clientId, const JsonDocument& message)>;
|
using MessageCallback = std::function<void(uint32_t clientId, const JsonDocument& message)>;
|
||||||
|
|
||||||
explicit WebSocketServer(AsyncWebSocket& webSocket, ClientManager& clientManager);
|
explicit WebSocketDriver(AsyncWebSocket& webSocket, ClientManager& clientManager);
|
||||||
~WebSocketServer();
|
~WebSocketDriver();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Initialize WebSocket server
|
* @brief Initialize WebSocket server
|
||||||
@@ -99,5 +95,5 @@ private:
|
|||||||
void onData(AsyncWebSocketClient* client, void* arg, uint8_t* data, size_t len);
|
void onData(AsyncWebSocketClient* client, void* arg, uint8_t* data, size_t len);
|
||||||
|
|
||||||
// Static instance for callback routing
|
// Static instance for callback routing
|
||||||
static WebSocketServer* _instance;
|
static WebSocketDriver* _instance;
|
||||||
};
|
};
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
#include "BellsHandler.hpp"
|
||||||
|
#include "../../../ConfigManager/ConfigManager.hpp"
|
||||||
|
#include "../../../Logging/Logging.hpp"
|
||||||
|
|
||||||
|
#define TAG "BellsHandler"
|
||||||
|
|
||||||
|
BellsHandler::BellsHandler(ConfigManager& configManager)
|
||||||
|
: _configManager(configManager) {}
|
||||||
|
|
||||||
|
std::vector<String> BellsHandler::commands() const {
|
||||||
|
return { "bells.enable", "bells.disable", "bells.get_config" };
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult BellsHandler::execute(const CommandEnvelope& envelope) {
|
||||||
|
if (envelope.command == "bells.enable") return handleEnable(envelope);
|
||||||
|
if (envelope.command == "bells.disable") return handleDisable(envelope);
|
||||||
|
if (envelope.command == "bells.get_config") return handleGetConfig(envelope);
|
||||||
|
return CommandResult::err(envelope.command, "Unknown bells command");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult BellsHandler::handleEnable(const CommandEnvelope& e) {
|
||||||
|
_configManager.setBellsEnabled(true);
|
||||||
|
if (!_configManager.saveGeneralConfig()) {
|
||||||
|
return CommandResult::err("bells.enable", "Bell mechanism enabled but failed to save to SD");
|
||||||
|
}
|
||||||
|
LOG_WARNING(TAG, "Bell mechanism enabled by command");
|
||||||
|
return CommandResult::ok("bells.enable", "Bell mechanism enabled and saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult BellsHandler::handleDisable(const CommandEnvelope& e) {
|
||||||
|
_configManager.setBellsEnabled(false);
|
||||||
|
if (!_configManager.saveGeneralConfig()) {
|
||||||
|
return CommandResult::err("bells.disable", "Bell mechanism disabled but failed to save to SD");
|
||||||
|
}
|
||||||
|
LOG_WARNING(TAG, "Bell mechanism disabled by command");
|
||||||
|
return CommandResult::ok("bells.disable", "Bell mechanism disabled and saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult BellsHandler::handleGetConfig(const CommandEnvelope& e) {
|
||||||
|
const auto& bellConfig = _configManager.getBellConfig();
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["bells_enabled"] = _configManager.getBellsEnabled();
|
||||||
|
|
||||||
|
JsonObject durations = doc["durations"].to<JsonObject>();
|
||||||
|
JsonObject outputs = doc["outputs"].to<JsonObject>();
|
||||||
|
for (uint8_t i = 0; i < 16; i++) {
|
||||||
|
durations[String(i)] = bellConfig.durations[i];
|
||||||
|
outputs[String(i)] = bellConfig.outputs[i];
|
||||||
|
}
|
||||||
|
return CommandResult::ok("bells.get_config", doc);
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
#include "../ICommandHandler.hpp"
|
||||||
|
|
||||||
|
class ConfigManager;
|
||||||
|
|
||||||
|
class BellsHandler : public ICommandHandler {
|
||||||
|
public:
|
||||||
|
explicit BellsHandler(ConfigManager& configManager);
|
||||||
|
|
||||||
|
std::vector<String> commands() const override;
|
||||||
|
CommandResult execute(const CommandEnvelope& envelope) override;
|
||||||
|
|
||||||
|
private:
|
||||||
|
ConfigManager& _configManager;
|
||||||
|
|
||||||
|
CommandResult handleEnable(const CommandEnvelope& e);
|
||||||
|
CommandResult handleDisable(const CommandEnvelope& e);
|
||||||
|
CommandResult handleGetConfig(const CommandEnvelope& e);
|
||||||
|
};
|
||||||
@@ -0,0 +1,372 @@
|
|||||||
|
#if HAS_RTC
|
||||||
|
#include "ClockHandler.hpp"
|
||||||
|
#include "../../../ConfigManager/ConfigManager.hpp"
|
||||||
|
#include "../../../TimeKeeper/TimeKeeper.hpp"
|
||||||
|
#include "../../../OutputManager/OutputManager.hpp"
|
||||||
|
#include "../../../Logging/Logging.hpp"
|
||||||
|
|
||||||
|
#define TAG "ClockHandler"
|
||||||
|
|
||||||
|
ClockHandler::ClockHandler(ConfigManager& configManager, Timekeeper& timeKeeper, OutputManager* outputManager)
|
||||||
|
: _configManager(configManager), _timeKeeper(timeKeeper), _outputManager(outputManager) {}
|
||||||
|
|
||||||
|
std::vector<String> ClockHandler::commands() const {
|
||||||
|
return {
|
||||||
|
"clock.set_outputs", "clock.set_timings", "clock.set_alerts",
|
||||||
|
"clock.set_backlight", "clock.set_silence",
|
||||||
|
"clock.set_config", "clock.set_alerts_config",
|
||||||
|
"clock.set_time", "clock.set_face",
|
||||||
|
"clock.set_timezone", "clock.get_timezone", "clock.sync_ntp",
|
||||||
|
"clock.enable", "clock.disable",
|
||||||
|
"clock.pause", "clock.resume",
|
||||||
|
"clock.get_face", "clock.get_config",
|
||||||
|
"clock.test_c1", "clock.test_c2"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult ClockHandler::execute(const CommandEnvelope& envelope) {
|
||||||
|
if (envelope.command == "clock.set_outputs") return handleSetOutputs(envelope);
|
||||||
|
if (envelope.command == "clock.set_timings") return handleSetTimings(envelope);
|
||||||
|
if (envelope.command == "clock.set_alerts") return handleSetAlerts(envelope);
|
||||||
|
if (envelope.command == "clock.set_config") return handleSetConfig(envelope);
|
||||||
|
if (envelope.command == "clock.set_alerts_config") return handleSetAlertsConfig(envelope);
|
||||||
|
if (envelope.command == "clock.set_backlight") return handleSetBacklight(envelope);
|
||||||
|
if (envelope.command == "clock.set_silence") return handleSetSilence(envelope);
|
||||||
|
if (envelope.command == "clock.set_time") return handleSetTime(envelope);
|
||||||
|
if (envelope.command == "clock.set_face") return handleSetFace(envelope);
|
||||||
|
if (envelope.command == "clock.set_timezone") return handleSetTimezone(envelope);
|
||||||
|
if (envelope.command == "clock.get_timezone") return handleGetTimezone(envelope);
|
||||||
|
if (envelope.command == "clock.sync_ntp") return handleSyncNtp(envelope);
|
||||||
|
if (envelope.command == "clock.enable") return handleEnable(envelope);
|
||||||
|
if (envelope.command == "clock.disable") return handleDisable(envelope);
|
||||||
|
if (envelope.command == "clock.pause") return handlePause(envelope);
|
||||||
|
if (envelope.command == "clock.resume") return handleResume(envelope);
|
||||||
|
if (envelope.command == "clock.get_face") return handleGetFace(envelope);
|
||||||
|
if (envelope.command == "clock.get_config") return handleGetConfig(envelope);
|
||||||
|
if (envelope.command == "clock.test_c1") return handleTestC1(envelope);
|
||||||
|
if (envelope.command == "clock.test_c2") return handleTestC2(envelope);
|
||||||
|
return CommandResult::err(envelope.command, "Unknown clock command");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
CommandResult ClockHandler::handleSetOutputs(const CommandEnvelope& e) {
|
||||||
|
_configManager.updateClockOutputs(const_cast<JsonDocument&>(e.contents).as<JsonVariant>());
|
||||||
|
if (!_configManager.saveClockConfig()) {
|
||||||
|
return CommandResult::err("clock.set_outputs", "Updated but failed to save to SD");
|
||||||
|
}
|
||||||
|
return CommandResult::ok("clock.set_outputs", "Clock outputs updated and saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult ClockHandler::handleSetTimings(const CommandEnvelope& e) {
|
||||||
|
// Note: original code called updateClockOutputs for timings — that was a bug.
|
||||||
|
// ClockConfig has pulseDuration and pauseDuration fields which should be set directly.
|
||||||
|
bool changed = false;
|
||||||
|
JsonVariantConst c = e.contents.as<JsonVariantConst>();
|
||||||
|
if (c["pulse_duration"].is<int>()) {
|
||||||
|
_configManager.setClockPulseDuration(c["pulse_duration"].as<uint16_t>());
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if (c["pause_duration"].is<int>()) {
|
||||||
|
_configManager.setClockPauseDuration(c["pause_duration"].as<uint16_t>());
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if (!changed) {
|
||||||
|
return CommandResult::err("clock.set_timings",
|
||||||
|
"No timing fields provided (pulse_duration, pause_duration)");
|
||||||
|
}
|
||||||
|
if (!_configManager.saveClockConfig()) {
|
||||||
|
return CommandResult::err("clock.set_timings", "Updated but failed to save to SD");
|
||||||
|
}
|
||||||
|
return CommandResult::ok("clock.set_timings", "Clock timings updated and saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult ClockHandler::handleSetAlerts(const CommandEnvelope& e) {
|
||||||
|
_configManager.updateClockAlerts(const_cast<JsonDocument&>(e.contents).as<JsonVariant>());
|
||||||
|
if (!_configManager.saveClockConfig()) {
|
||||||
|
return CommandResult::err("clock.set_alerts", "Updated but failed to save to SD");
|
||||||
|
}
|
||||||
|
return CommandResult::ok("clock.set_alerts", "Clock alerts updated and saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult ClockHandler::handleSetBacklight(const CommandEnvelope& e) {
|
||||||
|
_configManager.updateClockBacklight(const_cast<JsonDocument&>(e.contents).as<JsonVariant>());
|
||||||
|
if (!_configManager.saveClockConfig()) {
|
||||||
|
return CommandResult::err("clock.set_backlight", "Updated but failed to save to SD");
|
||||||
|
}
|
||||||
|
return CommandResult::ok("clock.set_backlight", "Clock backlight updated and saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult ClockHandler::handleSetSilence(const CommandEnvelope& e) {
|
||||||
|
_configManager.updateClockSilence(const_cast<JsonDocument&>(e.contents).as<JsonVariant>());
|
||||||
|
if (!_configManager.saveClockConfig()) {
|
||||||
|
return CommandResult::err("clock.set_silence", "Updated but failed to save to SD");
|
||||||
|
}
|
||||||
|
return CommandResult::ok("clock.set_silence", "Clock silence periods updated and saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult ClockHandler::handleSetTime(const CommandEnvelope& e) {
|
||||||
|
if (!e.contents["timestamp"].is<unsigned long>()) {
|
||||||
|
return CommandResult::err("clock.set_time", "Missing required field: timestamp");
|
||||||
|
}
|
||||||
|
unsigned long timestamp = e.contents["timestamp"].as<unsigned long>();
|
||||||
|
if (timestamp == 0) {
|
||||||
|
return CommandResult::err("clock.set_time", "Invalid timestamp value");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (e.contents["timezone_offset"].is<long>() && e.contents["dst_offset"].is<long>()) {
|
||||||
|
long tzOffset = e.contents["timezone_offset"].as<long>();
|
||||||
|
long dstOffset = e.contents["dst_offset"].as<long>();
|
||||||
|
long baseGmt = tzOffset - dstOffset;
|
||||||
|
_configManager.updateTimeConfig(baseGmt, dstOffset);
|
||||||
|
_timeKeeper.setTimeWithLocalTimestamp(timestamp + tzOffset);
|
||||||
|
LOG_INFO(TAG, "RTC time + timezone updated");
|
||||||
|
} else {
|
||||||
|
_timeKeeper.setTime(timestamp);
|
||||||
|
LOG_INFO(TAG, "RTC time updated (legacy path, no timezone)");
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned long verify = _timeKeeper.getTime();
|
||||||
|
if (verify == 0) {
|
||||||
|
return CommandResult::err("clock.set_time", "RTC time set but verification failed");
|
||||||
|
}
|
||||||
|
return CommandResult::ok("clock.set_time", "RTC time updated successfully");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult ClockHandler::handleSetFace(const CommandEnvelope& e) {
|
||||||
|
if (!e.contents["hour"].is<int>() || !e.contents["minute"].is<int>()) {
|
||||||
|
return CommandResult::err("clock.set_face", "Missing required fields: hour, minute");
|
||||||
|
}
|
||||||
|
int hour = e.contents["hour"].as<int>();
|
||||||
|
int minute = e.contents["minute"].as<int>();
|
||||||
|
if (hour < 0 || hour > 23) {
|
||||||
|
return CommandResult::err("clock.set_face", "hour must be 0-23");
|
||||||
|
}
|
||||||
|
if (minute < 0 || minute > 59) {
|
||||||
|
return CommandResult::err("clock.set_face", "minute must be 0-59");
|
||||||
|
}
|
||||||
|
|
||||||
|
int clockHour = hour % 12;
|
||||||
|
if (clockHour == 0) clockHour = 12;
|
||||||
|
|
||||||
|
_configManager.setPhysicalClockHour(clockHour);
|
||||||
|
_configManager.setPhysicalClockMinute(minute);
|
||||||
|
_configManager.setLastSyncTime(millis() / 1000);
|
||||||
|
|
||||||
|
if (!_configManager.saveClockState()) {
|
||||||
|
return CommandResult::err("clock.set_face", "Face set but failed to save to SD");
|
||||||
|
}
|
||||||
|
LOG_INFO(TAG, "Physical clock face set to %02d:%02d", hour, minute);
|
||||||
|
return CommandResult::ok("clock.set_face", "Physical clock face updated and saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult ClockHandler::handleSetTimezone(const CommandEnvelope& e) {
|
||||||
|
if (!e.contents["gmt_offset_sec"].is<long>()) {
|
||||||
|
return CommandResult::err("clock.set_timezone", "Missing required field: gmt_offset_sec");
|
||||||
|
}
|
||||||
|
long gmtOffset = e.contents["gmt_offset_sec"].as<long>();
|
||||||
|
int dstOffset = e.contents["dst_offset_sec"] | 0;
|
||||||
|
_configManager.updateTimeConfig(gmtOffset, dstOffset);
|
||||||
|
if (!_configManager.saveTimeConfig()) {
|
||||||
|
return CommandResult::err("clock.set_timezone", "Timezone updated but failed to save to SD");
|
||||||
|
}
|
||||||
|
LOG_INFO(TAG, "Timezone set: GMT%+ld DST%+d", gmtOffset / 3600, dstOffset / 3600);
|
||||||
|
return CommandResult::ok("clock.set_timezone", "Timezone updated and saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult ClockHandler::handleGetTimezone(const CommandEnvelope& e) {
|
||||||
|
const auto& tc = _configManager.getTimeConfig();
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["gmt_offset_sec"] = tc.gmtOffsetSec;
|
||||||
|
doc["dst_offset_sec"] = tc.daylightOffsetSec;
|
||||||
|
doc["ntp_server"] = tc.ntpServer;
|
||||||
|
return CommandResult::ok("clock.get_timezone", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult ClockHandler::handleSyncNtp(const CommandEnvelope& e) {
|
||||||
|
_timeKeeper.syncTimeWithNTP();
|
||||||
|
LOG_INFO(TAG, "NTP sync triggered via command");
|
||||||
|
return CommandResult::ok("clock.sync_ntp", "NTP sync initiated");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult ClockHandler::handleEnable(const CommandEnvelope& e) {
|
||||||
|
_configManager.setClockEnabled(true);
|
||||||
|
if (!_configManager.saveClockConfig()) {
|
||||||
|
return CommandResult::err("clock.enable", "Enabled but failed to save to SD");
|
||||||
|
}
|
||||||
|
return CommandResult::ok("clock.enable", "Clock enabled and saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult ClockHandler::handleDisable(const CommandEnvelope& e) {
|
||||||
|
_configManager.setClockEnabled(false);
|
||||||
|
if (!_configManager.saveClockConfig()) {
|
||||||
|
return CommandResult::err("clock.disable", "Disabled but failed to save to SD");
|
||||||
|
}
|
||||||
|
return CommandResult::ok("clock.disable", "Clock disabled and saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult ClockHandler::handlePause(const CommandEnvelope& e) {
|
||||||
|
_timeKeeper.pauseClockUpdates();
|
||||||
|
return CommandResult::ok("clock.pause", "Clock updates paused");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult ClockHandler::handleResume(const CommandEnvelope& e) {
|
||||||
|
_timeKeeper.resumeClockUpdates();
|
||||||
|
return CommandResult::ok("clock.resume", "Clock updates resumed");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult ClockHandler::handleGetFace(const CommandEnvelope& e) {
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["clock_hour"] = _configManager.getPhysicalClockHour();
|
||||||
|
doc["clock_minute"] = _configManager.getPhysicalClockMinute();
|
||||||
|
doc["last_sync_time"] = _configManager.getLastSyncTime();
|
||||||
|
doc["next_output_is_c1"] = _configManager.getNextOutputIsC1();
|
||||||
|
return CommandResult::ok("clock.get_face", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult ClockHandler::handleGetConfig(const CommandEnvelope& e) {
|
||||||
|
const auto& cc = _configManager.getClockConfig();
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["enabled"] = cc.enabled;
|
||||||
|
doc["c1output"] = cc.c1output;
|
||||||
|
doc["c2output"] = cc.c2output;
|
||||||
|
doc["pulse_duration"] = cc.pulseDuration;
|
||||||
|
doc["pause_duration"] = cc.pauseDuration;
|
||||||
|
doc["physical_hour"] = cc.physicalHour;
|
||||||
|
doc["physical_minute"] = cc.physicalMinute;
|
||||||
|
doc["next_is_c1"] = cc.nextOutputIsC1;
|
||||||
|
doc["last_sync_time"] = cc.lastSyncTime;
|
||||||
|
doc["alert_type"] = cc.alertType;
|
||||||
|
doc["alert_interval"] = cc.alertRingInterval;
|
||||||
|
// Stored 0-based internally; report 1-based to match API convention (255 = disabled, unchanged)
|
||||||
|
doc["hour_bell"] = (cc.hourBell == 255) ? 255 : cc.hourBell + 1;
|
||||||
|
doc["half_bell"] = (cc.halfBell == 255) ? 255 : cc.halfBell + 1;
|
||||||
|
doc["quarter_bell"] = (cc.quarterBell == 255) ? 255 : cc.quarterBell + 1;
|
||||||
|
doc["backlight"] = cc.backlight;
|
||||||
|
doc["backlight_output"] = cc.backlightOutput;
|
||||||
|
doc["backlight_on"] = cc.backlightOnTime;
|
||||||
|
doc["backlight_off"] = cc.backlightOffTime;
|
||||||
|
doc["daytime_silence"] = cc.daytimeSilenceEnabled;
|
||||||
|
doc["daytime_on"] = cc.daytimeSilenceOnTime;
|
||||||
|
doc["daytime_off"] = cc.daytimeSilenceOffTime;
|
||||||
|
doc["night_silence"] = cc.nighttimeSilenceEnabled;
|
||||||
|
doc["night_on"] = cc.nighttimeSilenceOnTime;
|
||||||
|
doc["night_off"] = cc.nighttimeSilenceOffTime;
|
||||||
|
const auto& tc = _configManager.getTimeConfig();
|
||||||
|
doc["gmt_offset_sec"] = tc.gmtOffsetSec;
|
||||||
|
doc["dst_offset_sec"] = tc.daylightOffsetSec;
|
||||||
|
doc["ntp_server"] = tc.ntpServer;
|
||||||
|
return CommandResult::ok("clock.get_config", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult ClockHandler::handleTestC1(const CommandEnvelope& e) {
|
||||||
|
if (!_outputManager) {
|
||||||
|
return CommandResult::err("clock.test_c1", "OutputManager not available");
|
||||||
|
}
|
||||||
|
uint16_t durationMs = _configManager.getClockPulseDuration();
|
||||||
|
_outputManager->fireClockOutput(0, durationMs);
|
||||||
|
LOG_INFO(TAG, "Test C1 fired for %d ms", durationMs);
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["output"] = "C1";
|
||||||
|
doc["duration_ms"] = durationMs;
|
||||||
|
return CommandResult::ok("clock.test_c1", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult ClockHandler::handleTestC2(const CommandEnvelope& e) {
|
||||||
|
if (!_outputManager) {
|
||||||
|
return CommandResult::err("clock.test_c2", "OutputManager not available");
|
||||||
|
}
|
||||||
|
uint16_t durationMs = _configManager.getClockPulseDuration();
|
||||||
|
_outputManager->fireClockOutput(1, durationMs);
|
||||||
|
LOG_INFO(TAG, "Test C2 fired for %d ms", durationMs);
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["output"] = "C2";
|
||||||
|
doc["duration_ms"] = durationMs;
|
||||||
|
return CommandResult::ok("clock.test_c2", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult ClockHandler::handleSetConfig(const CommandEnvelope& e) {
|
||||||
|
JsonVariantConst c = e.contents.as<JsonVariantConst>();
|
||||||
|
|
||||||
|
bool hasEnabled = c["enabled"].is<bool>();
|
||||||
|
bool hasC1 = c["c1"].is<int>();
|
||||||
|
bool hasC2 = c["c2"].is<int>();
|
||||||
|
bool hasPulseDuration = c["pulse_duration"].is<int>();
|
||||||
|
bool hasPauseDuration = c["pause_duration"].is<int>();
|
||||||
|
|
||||||
|
if (!hasEnabled && !hasC1 && !hasC2 && !hasPulseDuration && !hasPauseDuration) {
|
||||||
|
return CommandResult::err("clock.set_config",
|
||||||
|
"Provide at least one field: enabled, c1, c2, pulse_duration, pause_duration");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hasEnabled) _configManager.setClockEnabled(c["enabled"].as<bool>());
|
||||||
|
if (hasC1) _configManager.setClockOutput1(c["c1"].as<uint8_t>());
|
||||||
|
if (hasC2) _configManager.setClockOutput2(c["c2"].as<uint8_t>());
|
||||||
|
if (hasPulseDuration) _configManager.setClockPulseDuration(c["pulse_duration"].as<uint16_t>());
|
||||||
|
if (hasPauseDuration) _configManager.setClockPauseDuration(c["pause_duration"].as<uint16_t>());
|
||||||
|
|
||||||
|
if (!_configManager.saveClockConfig()) {
|
||||||
|
return CommandResult::err("clock.set_config", "Settings applied but failed to save to SD");
|
||||||
|
}
|
||||||
|
LOG_INFO(TAG, "clock.set_config applied");
|
||||||
|
return CommandResult::ok("clock.set_config", "Clock configuration updated and saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult ClockHandler::handleSetAlertsConfig(const CommandEnvelope& e) {
|
||||||
|
JsonVariantConst c = e.contents.as<JsonVariantConst>();
|
||||||
|
|
||||||
|
bool hasAlerts = c["alert_type"].is<JsonVariantConst>() ||
|
||||||
|
c["alert_interval"].is<JsonVariantConst>() ||
|
||||||
|
c["hour_bell"].is<JsonVariantConst>() ||
|
||||||
|
c["half_bell"].is<JsonVariantConst>() ||
|
||||||
|
c["quarter_bell"].is<JsonVariantConst>();
|
||||||
|
bool hasSilence = c["daytime_silence"].is<JsonVariantConst>() ||
|
||||||
|
c["daytime_on"].is<JsonVariantConst>() ||
|
||||||
|
c["daytime_off"].is<JsonVariantConst>() ||
|
||||||
|
c["night_silence"].is<JsonVariantConst>() ||
|
||||||
|
c["night_on"].is<JsonVariantConst>() ||
|
||||||
|
c["night_off"].is<JsonVariantConst>();
|
||||||
|
|
||||||
|
if (!hasAlerts && !hasSilence) {
|
||||||
|
return CommandResult::err("clock.set_alerts_config",
|
||||||
|
"Provide at least one of: alert_type, alert_interval, hour_bell, half_bell, quarter_bell, "
|
||||||
|
"daytime_silence, daytime_on, daytime_off, night_silence, night_on, night_off");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hasAlerts) {
|
||||||
|
// Map wire-format snake_case keys to what updateClockAlerts expects (camelCase)
|
||||||
|
JsonDocument alertsDoc;
|
||||||
|
if (c["alert_type"].is<JsonVariantConst>()) alertsDoc["alertType"] = c["alert_type"];
|
||||||
|
if (c["alert_interval"].is<JsonVariantConst>()) alertsDoc["alertRingInterval"] = c["alert_interval"];
|
||||||
|
if (c["hour_bell"].is<JsonVariantConst>()) alertsDoc["hourBell"] = c["hour_bell"];
|
||||||
|
if (c["half_bell"].is<JsonVariantConst>()) alertsDoc["halfBell"] = c["half_bell"];
|
||||||
|
if (c["quarter_bell"].is<JsonVariantConst>()) alertsDoc["quarterBell"] = c["quarter_bell"];
|
||||||
|
_configManager.updateClockAlerts(alertsDoc.as<JsonVariant>());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hasSilence) {
|
||||||
|
// Map wire-format flat keys to nested structure that updateClockSilence expects
|
||||||
|
JsonDocument silenceDoc;
|
||||||
|
if (c["daytime_silence"].is<JsonVariantConst>() || c["daytime_on"].is<JsonVariantConst>() || c["daytime_off"].is<JsonVariantConst>()) {
|
||||||
|
JsonObject dt = silenceDoc["daytime"].to<JsonObject>();
|
||||||
|
if (c["daytime_silence"].is<JsonVariantConst>()) dt["enabled"] = c["daytime_silence"];
|
||||||
|
if (c["daytime_on"].is<JsonVariantConst>()) dt["onTime"] = c["daytime_on"];
|
||||||
|
if (c["daytime_off"].is<JsonVariantConst>()) dt["offTime"] = c["daytime_off"];
|
||||||
|
}
|
||||||
|
if (c["night_silence"].is<JsonVariantConst>() || c["night_on"].is<JsonVariantConst>() || c["night_off"].is<JsonVariantConst>()) {
|
||||||
|
JsonObject nt = silenceDoc["nighttime"].to<JsonObject>();
|
||||||
|
if (c["night_silence"].is<JsonVariantConst>()) nt["enabled"] = c["night_silence"];
|
||||||
|
if (c["night_on"].is<JsonVariantConst>()) nt["onTime"] = c["night_on"];
|
||||||
|
if (c["night_off"].is<JsonVariantConst>()) nt["offTime"] = c["night_off"];
|
||||||
|
}
|
||||||
|
_configManager.updateClockSilence(silenceDoc.as<JsonVariant>());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!_configManager.saveClockConfig()) {
|
||||||
|
return CommandResult::err("clock.set_alerts_config", "Settings applied but failed to save to SD");
|
||||||
|
}
|
||||||
|
LOG_INFO(TAG, "clock.set_alerts_config applied");
|
||||||
|
return CommandResult::ok("clock.set_alerts_config", "Clock alerts and silence configuration updated and saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif // HAS_RTC
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#if HAS_RTC
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
#include "../ICommandHandler.hpp"
|
||||||
|
|
||||||
|
class ConfigManager;
|
||||||
|
class Timekeeper;
|
||||||
|
class OutputManager;
|
||||||
|
|
||||||
|
class ClockHandler : public ICommandHandler {
|
||||||
|
public:
|
||||||
|
ClockHandler(ConfigManager& configManager, Timekeeper& timeKeeper, OutputManager* outputManager = nullptr);
|
||||||
|
|
||||||
|
std::vector<String> commands() const override;
|
||||||
|
CommandResult execute(const CommandEnvelope& envelope) override;
|
||||||
|
|
||||||
|
private:
|
||||||
|
ConfigManager& _configManager;
|
||||||
|
Timekeeper& _timeKeeper;
|
||||||
|
OutputManager* _outputManager;
|
||||||
|
|
||||||
|
CommandResult handleSetOutputs(const CommandEnvelope& e);
|
||||||
|
CommandResult handleSetTimings(const CommandEnvelope& e);
|
||||||
|
CommandResult handleSetAlerts(const CommandEnvelope& e);
|
||||||
|
CommandResult handleSetBacklight(const CommandEnvelope& e);
|
||||||
|
CommandResult handleSetSilence(const CommandEnvelope& e);
|
||||||
|
CommandResult handleSetTime(const CommandEnvelope& e);
|
||||||
|
CommandResult handleSetFace(const CommandEnvelope& e);
|
||||||
|
CommandResult handleSetTimezone(const CommandEnvelope& e);
|
||||||
|
CommandResult handleGetTimezone(const CommandEnvelope& e);
|
||||||
|
CommandResult handleSyncNtp(const CommandEnvelope& e);
|
||||||
|
CommandResult handleEnable(const CommandEnvelope& e);
|
||||||
|
CommandResult handleDisable(const CommandEnvelope& e);
|
||||||
|
CommandResult handlePause(const CommandEnvelope& e);
|
||||||
|
CommandResult handleResume(const CommandEnvelope& e);
|
||||||
|
CommandResult handleGetFace(const CommandEnvelope& e);
|
||||||
|
CommandResult handleGetConfig(const CommandEnvelope& e);
|
||||||
|
CommandResult handleTestC1(const CommandEnvelope& e);
|
||||||
|
CommandResult handleTestC2(const CommandEnvelope& e);
|
||||||
|
CommandResult handleSetConfig(const CommandEnvelope& e);
|
||||||
|
CommandResult handleSetAlertsConfig(const CommandEnvelope& e);
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif // HAS_RTC
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
#include "FileHandler.hpp"
|
||||||
|
#include "../../../FileManager/FileManager.hpp"
|
||||||
|
#include "../../../BuiltInMelodies/BuiltInMelodies.hpp"
|
||||||
|
#include "../../../Logging/Logging.hpp"
|
||||||
|
|
||||||
|
#define TAG "FileHandler"
|
||||||
|
|
||||||
|
FileHandler::FileHandler(FileManager& fileManager) : _fileManager(fileManager) {}
|
||||||
|
|
||||||
|
std::vector<String> FileHandler::commands() const {
|
||||||
|
return { "files.list", "files.list_builtin", "files.download", "files.delete" };
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult FileHandler::execute(const CommandEnvelope& envelope) {
|
||||||
|
if (envelope.command == "files.list") return handleList(envelope);
|
||||||
|
if (envelope.command == "files.list_builtin") return handleListBuiltin(envelope);
|
||||||
|
if (envelope.command == "files.download") return handleDownload(envelope);
|
||||||
|
if (envelope.command == "files.delete") return handleDelete(envelope);
|
||||||
|
return CommandResult::err(envelope.command, "Unknown files command");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult FileHandler::handleList(const CommandEnvelope& e) {
|
||||||
|
String fileListJson = _fileManager.listFilesAsJson("/melodies");
|
||||||
|
|
||||||
|
JsonDocument doc;
|
||||||
|
DeserializationError err = deserializeJson(doc, fileListJson);
|
||||||
|
if (err) {
|
||||||
|
LOG_ERROR(TAG, "Failed to parse file list JSON: %s", err.c_str());
|
||||||
|
return CommandResult::err("files.list", "Failed to read melody list");
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonDocument result;
|
||||||
|
result["files"] = doc["files"];
|
||||||
|
return CommandResult::ok("files.list", result);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult FileHandler::handleListBuiltin(const CommandEnvelope& e) {
|
||||||
|
String builtinJson = BuiltInMelodies::getBuiltInMelodiesJSON();
|
||||||
|
|
||||||
|
JsonDocument doc;
|
||||||
|
DeserializationError err = deserializeJson(doc, builtinJson);
|
||||||
|
if (err) {
|
||||||
|
LOG_ERROR(TAG, "Failed to parse built-in melodies JSON: %s", err.c_str());
|
||||||
|
return CommandResult::err("files.list_builtin", "Failed to read built-in melody list");
|
||||||
|
}
|
||||||
|
|
||||||
|
return CommandResult::ok("files.list_builtin", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult FileHandler::handleDownload(const CommandEnvelope& e) {
|
||||||
|
bool ok = _fileManager.addMelody(const_cast<JsonDocument&>(e.contents).as<JsonVariant>());
|
||||||
|
String uid = e.contents["melodys_uid"] | e.contents["name"] | String("unknown");
|
||||||
|
if (ok) return CommandResult::ok("files.download", "Melody downloaded: " + uid);
|
||||||
|
return CommandResult::err("files.download", "Failed to download melody: " + uid);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult FileHandler::handleDelete(const CommandEnvelope& e) {
|
||||||
|
if (!e.contents["name"].is<const char*>()) {
|
||||||
|
return CommandResult::err("files.delete", "Missing required field: name");
|
||||||
|
}
|
||||||
|
String name = e.contents["name"].as<String>();
|
||||||
|
bool ok = _fileManager.deleteFile("/melodies/" + name);
|
||||||
|
if (ok) return CommandResult::ok("files.delete", "Melody deleted: " + name);
|
||||||
|
return CommandResult::err("files.delete", "Failed to delete melody: " + name);
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
#include "../ICommandHandler.hpp"
|
||||||
|
|
||||||
|
class FileManager;
|
||||||
|
|
||||||
|
class FileHandler : public ICommandHandler {
|
||||||
|
public:
|
||||||
|
explicit FileHandler(FileManager& fileManager);
|
||||||
|
|
||||||
|
std::vector<String> commands() const override;
|
||||||
|
CommandResult execute(const CommandEnvelope& envelope) override;
|
||||||
|
|
||||||
|
private:
|
||||||
|
FileManager& _fileManager;
|
||||||
|
|
||||||
|
CommandResult handleList(const CommandEnvelope& e);
|
||||||
|
CommandResult handleListBuiltin(const CommandEnvelope& e);
|
||||||
|
CommandResult handleDownload(const CommandEnvelope& e);
|
||||||
|
CommandResult handleDelete(const CommandEnvelope& e);
|
||||||
|
};
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
#include "FirmwareHandler.hpp"
|
||||||
|
#include "../../../FirmwareValidator/FirmwareValidator.hpp"
|
||||||
|
#include "../../../OTAManager/OTAManager.hpp"
|
||||||
|
#include "../../../Player/Player.hpp"
|
||||||
|
#include "../../../ConfigManager/ConfigManager.hpp"
|
||||||
|
#include "../../../Logging/Logging.hpp"
|
||||||
|
|
||||||
|
#define TAG "FirmwareHandler"
|
||||||
|
|
||||||
|
static const char* VALID_CHANNELS[] = { "stable", "beta", "development" };
|
||||||
|
static const size_t VALID_CHANNEL_COUNT = sizeof(VALID_CHANNELS) / sizeof(VALID_CHANNELS[0]);
|
||||||
|
|
||||||
|
FirmwareHandler::FirmwareHandler(FirmwareValidator& firmwareValidator,
|
||||||
|
OTAManager& otaManager,
|
||||||
|
Player& player,
|
||||||
|
ConfigManager& configManager)
|
||||||
|
: _firmwareValidator(firmwareValidator)
|
||||||
|
, _otaManager(otaManager)
|
||||||
|
, _player(player)
|
||||||
|
, _configManager(configManager) {}
|
||||||
|
|
||||||
|
std::vector<String> FirmwareHandler::commands() const {
|
||||||
|
return {
|
||||||
|
"firmware.status", "firmware.commit", "firmware.rollback",
|
||||||
|
"ota.update", "ota.custom", "ota.set_channel"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult FirmwareHandler::execute(const CommandEnvelope& envelope) {
|
||||||
|
if (envelope.command == "firmware.status") return handleFirmwareStatus(envelope);
|
||||||
|
if (envelope.command == "firmware.commit") return handleCommit(envelope);
|
||||||
|
if (envelope.command == "firmware.rollback") return handleRollback(envelope);
|
||||||
|
if (envelope.command == "ota.update") return handleOtaUpdate(envelope);
|
||||||
|
if (envelope.command == "ota.custom") return handleOtaCustom(envelope);
|
||||||
|
if (envelope.command == "ota.set_channel") return handleOtaSetChannel(envelope);
|
||||||
|
return CommandResult::err(envelope.command, "Unknown firmware command");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult FirmwareHandler::handleFirmwareStatus(const CommandEnvelope& e) {
|
||||||
|
auto validationState = _firmwareValidator.getValidationState();
|
||||||
|
auto currentInfo = _firmwareValidator.getCurrentFirmwareInfo();
|
||||||
|
auto backupInfo = _firmwareValidator.getBackupFirmwareInfo();
|
||||||
|
auto config = _firmwareValidator.getValidationConfig();
|
||||||
|
|
||||||
|
static const char* stateNames[] = {
|
||||||
|
"UNKNOWN", "STARTUP_PENDING", "STARTUP_RUNNING", "RUNTIME_TESTING",
|
||||||
|
"VALIDATED", "FAILED_STARTUP", "FAILED_RUNTIME", "ROLLED_BACK"
|
||||||
|
};
|
||||||
|
const char* stateStr = stateNames[static_cast<int>(validationState)];
|
||||||
|
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["validation_state"] = stateStr;
|
||||||
|
doc["current_version"] = currentInfo.version;
|
||||||
|
doc["is_testing"] = currentInfo.isTesting;
|
||||||
|
doc["is_valid"] = currentInfo.isValid;
|
||||||
|
doc["boot_count"] = currentInfo.bootCount;
|
||||||
|
doc["build_date"] = currentInfo.buildDate;
|
||||||
|
doc["ota_channel"] = _configManager.getOtaChannel();
|
||||||
|
|
||||||
|
// Rollback safety-net diagnostics — previously logged only, not queryable remotely.
|
||||||
|
doc["startup_retry_count"] = _firmwareValidator.getStartupRetryCount();
|
||||||
|
doc["max_startup_retries"] = config.maxStartupRetries;
|
||||||
|
doc["runtime_failure_count"] = _firmwareValidator.getRuntimeFailureCount();
|
||||||
|
doc["max_runtime_failures"] = config.maxRuntimeFailures;
|
||||||
|
doc["backup_version"] = backupInfo.version;
|
||||||
|
doc["backup_is_valid"] = backupInfo.isValid;
|
||||||
|
|
||||||
|
bool inTesting = _firmwareValidator.isInTestingMode();
|
||||||
|
doc["can_commit"] = inTesting;
|
||||||
|
doc["can_rollback"] = (validationState != FirmwareValidationState::VALIDATED);
|
||||||
|
if (inTesting) doc["runtime_timeout_ms"] = config.runtimeTimeoutMs;
|
||||||
|
|
||||||
|
return CommandResult::ok("firmware.status", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult FirmwareHandler::handleCommit(const CommandEnvelope& e) {
|
||||||
|
if (!_firmwareValidator.isInTestingMode()) {
|
||||||
|
return CommandResult::err("firmware.commit", "No firmware validation in progress");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
_firmwareValidator.commitFirmware();
|
||||||
|
LOG_INFO(TAG, "Firmware manually committed");
|
||||||
|
return CommandResult::ok("firmware.commit", "Firmware committed successfully");
|
||||||
|
} catch (...) {
|
||||||
|
return CommandResult::err("firmware.commit", "Failed to commit firmware");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult FirmwareHandler::handleRollback(const CommandEnvelope& e) {
|
||||||
|
try {
|
||||||
|
_firmwareValidator.rollbackFirmware();
|
||||||
|
LOG_WARNING(TAG, "Firmware rollback initiated");
|
||||||
|
return CommandResult::ok("firmware.rollback", "Firmware rollback initiated — device will reboot");
|
||||||
|
} catch (...) {
|
||||||
|
return CommandResult::err("firmware.rollback", "Failed to initiate firmware rollback");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult FirmwareHandler::handleOtaUpdate(const CommandEnvelope& e) {
|
||||||
|
if (_player.isCurrentlyPlaying()) {
|
||||||
|
return CommandResult::err("ota.update", "Cannot update while playback is active");
|
||||||
|
}
|
||||||
|
String channel = e.contents["channel"] | String("stable");
|
||||||
|
LOG_WARNING(TAG, "OTA update requested, channel: %s", channel.c_str());
|
||||||
|
|
||||||
|
// Reply is sent before the update begins so the client gets a response
|
||||||
|
// (the device may reboot mid-update)
|
||||||
|
_otaManager.performManualUpdate(channel);
|
||||||
|
return CommandResult::ok("ota.update", "OTA update started from channel: " + channel);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult FirmwareHandler::handleOtaCustom(const CommandEnvelope& e) {
|
||||||
|
if (!e.contents["firmware_url"].is<const char*>()) {
|
||||||
|
return CommandResult::err("ota.custom", "Missing required field: firmware_url");
|
||||||
|
}
|
||||||
|
if (_player.isCurrentlyPlaying()) {
|
||||||
|
return CommandResult::err("ota.custom", "Cannot update while playback is active");
|
||||||
|
}
|
||||||
|
|
||||||
|
String url = e.contents["firmware_url"].as<String>();
|
||||||
|
String checksum = e.contents["checksum"] | String("");
|
||||||
|
size_t fileSize = e.contents["file_size"] | 0;
|
||||||
|
String version = e.contents["version"].as<String>();
|
||||||
|
|
||||||
|
LOG_WARNING(TAG, "Custom OTA update: %s", url.c_str());
|
||||||
|
_otaManager.performCustomUpdate(url, checksum, fileSize, version);
|
||||||
|
return CommandResult::ok("ota.custom", "Custom OTA update started");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult FirmwareHandler::handleOtaSetChannel(const CommandEnvelope& e) {
|
||||||
|
if (!e.contents["channel"].is<const char*>()) {
|
||||||
|
return CommandResult::err("ota.set_channel", "Missing required field: channel");
|
||||||
|
}
|
||||||
|
String channel = e.contents["channel"].as<String>();
|
||||||
|
|
||||||
|
// Validate against allowed channels
|
||||||
|
bool valid = false;
|
||||||
|
for (size_t i = 0; i < VALID_CHANNEL_COUNT; i++) {
|
||||||
|
if (channel == VALID_CHANNELS[i]) { valid = true; break; }
|
||||||
|
}
|
||||||
|
if (!valid) {
|
||||||
|
return CommandResult::err("ota.set_channel",
|
||||||
|
"Invalid channel. Valid values: stable, beta, development");
|
||||||
|
}
|
||||||
|
|
||||||
|
_configManager.setOtaChannel(channel);
|
||||||
|
_configManager.saveGeneralConfig();
|
||||||
|
LOG_INFO(TAG, "OTA channel set to '%s' and persisted to SD", channel.c_str());
|
||||||
|
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["channel"] = channel;
|
||||||
|
return CommandResult::ok("ota.set_channel", doc);
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
#include "../ICommandHandler.hpp"
|
||||||
|
|
||||||
|
class FirmwareValidator;
|
||||||
|
class OTAManager;
|
||||||
|
class Player;
|
||||||
|
class ConfigManager;
|
||||||
|
|
||||||
|
class FirmwareHandler : public ICommandHandler {
|
||||||
|
public:
|
||||||
|
FirmwareHandler(FirmwareValidator& firmwareValidator, OTAManager& otaManager,
|
||||||
|
Player& player, ConfigManager& configManager);
|
||||||
|
|
||||||
|
std::vector<String> commands() const override;
|
||||||
|
CommandResult execute(const CommandEnvelope& envelope) override;
|
||||||
|
|
||||||
|
private:
|
||||||
|
FirmwareValidator& _firmwareValidator;
|
||||||
|
OTAManager& _otaManager;
|
||||||
|
Player& _player;
|
||||||
|
ConfigManager& _configManager;
|
||||||
|
|
||||||
|
CommandResult handleFirmwareStatus(const CommandEnvelope& e);
|
||||||
|
CommandResult handleCommit(const CommandEnvelope& e);
|
||||||
|
CommandResult handleRollback(const CommandEnvelope& e);
|
||||||
|
CommandResult handleOtaUpdate(const CommandEnvelope& e);
|
||||||
|
CommandResult handleOtaCustom(const CommandEnvelope& e);
|
||||||
|
CommandResult handleOtaSetChannel(const CommandEnvelope& e);
|
||||||
|
};
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <vector>
|
||||||
|
#include "../CommandBus/CommandEnvelope.hpp"
|
||||||
|
#include "../CommandBus/CommandResult.hpp"
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// ICommandHandler
|
||||||
|
//
|
||||||
|
// Interface every domain handler implements.
|
||||||
|
//
|
||||||
|
// - commands() declares which command names this handler owns.
|
||||||
|
// The CommandBus iterates this list at registration time and builds
|
||||||
|
// its lookup map automatically — no manual registration per command.
|
||||||
|
//
|
||||||
|
// - execute() receives a fully-parsed CommandEnvelope and returns a
|
||||||
|
// CommandResult. It must never call envelope.reply() directly —
|
||||||
|
// the bus handles that after execute() returns.
|
||||||
|
//
|
||||||
|
// Example:
|
||||||
|
// class PlaybackHandler : public ICommandHandler {
|
||||||
|
// public:
|
||||||
|
// explicit PlaybackHandler(Player& player);
|
||||||
|
// std::vector<String> commands() const override { return { "playback" }; }
|
||||||
|
// CommandResult execute(const CommandEnvelope& envelope) override;
|
||||||
|
// private:
|
||||||
|
// Player& _player;
|
||||||
|
// };
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class ICommandHandler {
|
||||||
|
public:
|
||||||
|
virtual ~ICommandHandler() = default;
|
||||||
|
|
||||||
|
// Returns every command name this handler is responsible for.
|
||||||
|
// The bus registers all of them to the same handler instance.
|
||||||
|
virtual std::vector<String> commands() const = 0;
|
||||||
|
|
||||||
|
// Execute the command described by envelope and return the result.
|
||||||
|
// Must not throw. Must not call envelope.reply() — the bus owns that.
|
||||||
|
virtual CommandResult execute(const CommandEnvelope& envelope) = 0;
|
||||||
|
};
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
#include "LoggingHandler.hpp"
|
||||||
|
#include "../../../ConfigManager/ConfigManager.hpp"
|
||||||
|
#include "../../../Logging/Logging.hpp"
|
||||||
|
#include "../../../FileManager/FileManager.hpp"
|
||||||
|
|
||||||
|
#define TAG "LoggingHandler"
|
||||||
|
|
||||||
|
// Directory where day-rotated SD logs live — must match CommunicationRouter's
|
||||||
|
// setFileManagerReference wiring (Logging.hpp SD channel).
|
||||||
|
static const char* SD_LOG_DIR = "/logs";
|
||||||
|
|
||||||
|
// Cap a single logs.download response chunk — keeps every response small
|
||||||
|
// regardless of file size, matching the JSON-payload sizes used elsewhere
|
||||||
|
// (MQTT/WS/HTTP transports).
|
||||||
|
static constexpr size_t LOGS_DOWNLOAD_MAX_CHUNK_BYTES = 4096;
|
||||||
|
|
||||||
|
LoggingHandler::LoggingHandler(ConfigManager& configManager, FileManager* fileManager)
|
||||||
|
: _configManager(configManager), _fileManager(fileManager) {}
|
||||||
|
|
||||||
|
std::vector<String> LoggingHandler::commands() const {
|
||||||
|
return { "log.set_serial", "log.set_sd", "log.set_mqtt", "log.get_config",
|
||||||
|
"logs.list", "logs.download", "logs.clear" };
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult LoggingHandler::execute(const CommandEnvelope& envelope) {
|
||||||
|
if (envelope.command == "log.set_serial") return handleSetLevel(envelope, "serial");
|
||||||
|
if (envelope.command == "log.set_sd") return handleSetLevel(envelope, "sd");
|
||||||
|
if (envelope.command == "log.set_mqtt") return handleSetLevel(envelope, "mqtt");
|
||||||
|
if (envelope.command == "log.get_config") return handleGetConfig(envelope);
|
||||||
|
if (envelope.command == "logs.list") return handleLogsList(envelope);
|
||||||
|
if (envelope.command == "logs.download") return handleLogsDownload(envelope);
|
||||||
|
if (envelope.command == "logs.clear") return handleLogsClear(envelope);
|
||||||
|
return CommandResult::err(envelope.command, "Unknown log command");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult LoggingHandler::handleSetLevel(const CommandEnvelope& e, const String& channel) {
|
||||||
|
if (!e.contents["level"].is<uint8_t>()) {
|
||||||
|
return CommandResult::err("log.set_" + channel, "Missing or invalid 'level' (0-5 required)");
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t level = e.contents["level"].as<uint8_t>();
|
||||||
|
bool saved = false;
|
||||||
|
|
||||||
|
if (channel == "serial") {
|
||||||
|
if (!_configManager.setSerialLogLevel(level))
|
||||||
|
return CommandResult::err("log.set_serial", "Invalid log level (must be 0-5)");
|
||||||
|
Logging::setLevel((Logging::LogLevel)level);
|
||||||
|
saved = _configManager.saveGeneralConfig();
|
||||||
|
} else if (channel == "sd") {
|
||||||
|
if (!_configManager.setSdLogLevel(level))
|
||||||
|
return CommandResult::err("log.set_sd", "Invalid log level (must be 0-5)");
|
||||||
|
Logging::setSdLevel((Logging::LogLevel)level);
|
||||||
|
saved = _configManager.saveGeneralConfig();
|
||||||
|
} else if (channel == "mqtt") {
|
||||||
|
if (!_configManager.setMqttLogLevel(level))
|
||||||
|
return CommandResult::err("log.set_mqtt", "Invalid log level (must be 0-5)");
|
||||||
|
Logging::setMqttLogLevel((Logging::LogLevel)level);
|
||||||
|
saved = _configManager.saveGeneralConfig();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!saved) {
|
||||||
|
return CommandResult::err("log.set_" + channel, "Level applied but failed to save to SD");
|
||||||
|
}
|
||||||
|
|
||||||
|
LOG_INFO(TAG, "%s log level set to %d", channel.c_str(), level);
|
||||||
|
return CommandResult::ok("log.set_" + channel,
|
||||||
|
channel + " log level set to " + String(level) + " and saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult LoggingHandler::handleGetConfig(const CommandEnvelope& e) {
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["serial_level"] = _configManager.getSerialLogLevel();
|
||||||
|
doc["sd_level"] = _configManager.getSdLogLevel();
|
||||||
|
doc["mqtt_level"] = _configManager.getMqttLogLevel();
|
||||||
|
return CommandResult::ok("log.get_config", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult LoggingHandler::handleLogsList(const CommandEnvelope& e) {
|
||||||
|
if (!_fileManager) {
|
||||||
|
return CommandResult::err("logs.list", "SD card not available on this device");
|
||||||
|
}
|
||||||
|
|
||||||
|
String listJson = _fileManager->listLogFilesAsJson(SD_LOG_DIR);
|
||||||
|
JsonDocument doc;
|
||||||
|
DeserializationError err = deserializeJson(doc, listJson);
|
||||||
|
if (err) {
|
||||||
|
LOG_ERROR(TAG, "Failed to parse log file list JSON: %s", err.c_str());
|
||||||
|
return CommandResult::err("logs.list", "Failed to read log directory");
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonDocument result;
|
||||||
|
result["files"] = doc["files"];
|
||||||
|
return CommandResult::ok("logs.list", result);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult LoggingHandler::handleLogsDownload(const CommandEnvelope& e) {
|
||||||
|
if (!_fileManager) {
|
||||||
|
return CommandResult::err("logs.download", "SD card not available on this device");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!e.contents["file"].is<const char*>()) {
|
||||||
|
return CommandResult::err("logs.download", "Missing required field: file");
|
||||||
|
}
|
||||||
|
|
||||||
|
String fileName = e.contents["file"].as<String>();
|
||||||
|
size_t offset = e.contents["offset"].is<size_t>() ? e.contents["offset"].as<size_t>() : 0;
|
||||||
|
|
||||||
|
String chunkJson = _fileManager->readLogChunkAsJson(SD_LOG_DIR, fileName, offset,
|
||||||
|
LOGS_DOWNLOAD_MAX_CHUNK_BYTES);
|
||||||
|
JsonDocument doc;
|
||||||
|
DeserializationError err = deserializeJson(doc, chunkJson);
|
||||||
|
if (err || doc.isNull()) {
|
||||||
|
return CommandResult::err("logs.download", "Log file not found: " + fileName);
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonDocument result;
|
||||||
|
result["file"] = fileName;
|
||||||
|
result["data"] = doc["data"];
|
||||||
|
result["next_offset"] = doc["next_offset"];
|
||||||
|
result["eof"] = doc["eof"];
|
||||||
|
return CommandResult::ok("logs.download", result);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult LoggingHandler::handleLogsClear(const CommandEnvelope& e) {
|
||||||
|
// Deletes every day-rotated SD debug log file — a QA-to-shipping reset,
|
||||||
|
// not part of normal log rotation. Not to be confused with the day-
|
||||||
|
// rotation pruning that already runs automatically in appendLogLine()
|
||||||
|
// (that only trims oldest files once over budget, never clears everything).
|
||||||
|
if (!_fileManager) {
|
||||||
|
return CommandResult::err("logs.clear", "SD card not available on this device");
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t deleted = _fileManager->deleteAllLogFiles(SD_LOG_DIR);
|
||||||
|
LOG_WARNING(TAG, "SD debug logs cleared via logs.clear command (%u file(s))", (unsigned)deleted);
|
||||||
|
|
||||||
|
JsonDocument result;
|
||||||
|
result["deleted"] = deleted;
|
||||||
|
return CommandResult::ok("logs.clear", result);
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
#include "../ICommandHandler.hpp"
|
||||||
|
|
||||||
|
class ConfigManager;
|
||||||
|
class FileManager;
|
||||||
|
|
||||||
|
class LoggingHandler : public ICommandHandler {
|
||||||
|
public:
|
||||||
|
explicit LoggingHandler(ConfigManager& configManager, FileManager* fileManager = nullptr);
|
||||||
|
|
||||||
|
std::vector<String> commands() const override;
|
||||||
|
CommandResult execute(const CommandEnvelope& envelope) override;
|
||||||
|
|
||||||
|
private:
|
||||||
|
ConfigManager& _configManager;
|
||||||
|
FileManager* _fileManager; // nullptr on boards without SD — logs.* commands degrade gracefully
|
||||||
|
|
||||||
|
CommandResult handleSetLevel(const CommandEnvelope& e, const String& channel);
|
||||||
|
CommandResult handleGetConfig(const CommandEnvelope& e);
|
||||||
|
CommandResult handleLogsList(const CommandEnvelope& e);
|
||||||
|
CommandResult handleLogsDownload(const CommandEnvelope& e);
|
||||||
|
CommandResult handleLogsClear(const CommandEnvelope& e);
|
||||||
|
};
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
#include "MQTTHandler.hpp"
|
||||||
|
#include "../../../ConfigManager/ConfigManager.hpp"
|
||||||
|
#include "../../../Communication/Drivers/MQTTDriver/MQTTDriver.hpp"
|
||||||
|
#include "../../../Logging/Logging.hpp"
|
||||||
|
|
||||||
|
#define TAG "MQTTHandler"
|
||||||
|
|
||||||
|
MQTTHandler::MQTTHandler(ConfigManager& configManager, MQTTDriver& mqttClient)
|
||||||
|
: _configManager(configManager), _mqttClient(mqttClient) {}
|
||||||
|
|
||||||
|
std::vector<String> MQTTHandler::commands() const {
|
||||||
|
return { "mqtt.enable", "mqtt.disable", "mqtt.get_config",
|
||||||
|
"mqtt.get_topics", "mqtt.set_topics" };
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult MQTTHandler::execute(const CommandEnvelope& envelope) {
|
||||||
|
if (envelope.command == "mqtt.get_config") return handleGetConfig(envelope);
|
||||||
|
if (envelope.command == "mqtt.get_topics") return handleGetTopics(envelope);
|
||||||
|
if (envelope.command == "mqtt.set_topics") return handleSetTopics(envelope);
|
||||||
|
|
||||||
|
bool enable = (envelope.command == "mqtt.enable");
|
||||||
|
|
||||||
|
_configManager.setMqttEnabled(enable);
|
||||||
|
if (!_configManager.saveGeneralConfig()) {
|
||||||
|
return CommandResult::err(envelope.command,
|
||||||
|
"MQTT state changed but failed to save to SD");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (enable) {
|
||||||
|
_mqttClient.connect();
|
||||||
|
} else {
|
||||||
|
// Graceful: announce offline on status/heartbeat before disconnecting —
|
||||||
|
// LWT only fires on an unclean drop, so an intentional disable would
|
||||||
|
// otherwise leave a stale "online" retained heartbeat behind.
|
||||||
|
_mqttClient.disconnect(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
LOG_INFO(TAG, "MQTT %s by user command", enable ? "enabled" : "disabled");
|
||||||
|
return CommandResult::ok(envelope.command,
|
||||||
|
String("MQTT ") + (enable ? "enabled" : "disabled") + " and saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult MQTTHandler::handleGetConfig(const CommandEnvelope& e) {
|
||||||
|
const auto& mqttCfg = _configManager.getMqttConfig();
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["enabled"] = _configManager.getMqttEnabled();
|
||||||
|
doc["host"] = mqttCfg.host.toString();
|
||||||
|
doc["port"] = mqttCfg.port;
|
||||||
|
doc["user"] = mqttCfg.user;
|
||||||
|
doc["use_ssl"] = mqttCfg.useSSL;
|
||||||
|
return CommandResult::ok("mqtt.get_config", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult MQTTHandler::handleGetTopics(const CommandEnvelope& e) {
|
||||||
|
const auto& t = _configManager.getMqttTopicConfig();
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["command"] = t.command;
|
||||||
|
doc["heartbeat"] = t.heartbeat;
|
||||||
|
doc["playback"] = t.playback;
|
||||||
|
doc["reports"] = t.reports;
|
||||||
|
doc["alerts"] = t.alerts;
|
||||||
|
doc["info"] = t.info;
|
||||||
|
doc["logs"] = t.logs;
|
||||||
|
doc["metrics"] = t.metrics;
|
||||||
|
return CommandResult::ok("mqtt.get_topics", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult MQTTHandler::handleSetTopics(const CommandEnvelope& e) {
|
||||||
|
// Partial update — only fields present in contents are changed, matching
|
||||||
|
// the "at least one field, partial OK" handler convention used elsewhere
|
||||||
|
// (relay.set_durations, network.set_config, etc.). These switches only
|
||||||
|
// take effect while the mqtt.enable master switch is on.
|
||||||
|
ConfigManager::MqttTopicConfig t = _configManager.getMqttTopicConfig();
|
||||||
|
bool any = false;
|
||||||
|
|
||||||
|
if (e.contents["command"].is<bool>()) { t.command = e.contents["command"].as<bool>(); any = true; }
|
||||||
|
if (e.contents["heartbeat"].is<bool>()) { t.heartbeat = e.contents["heartbeat"].as<bool>(); any = true; }
|
||||||
|
if (e.contents["playback"].is<bool>()) { t.playback = e.contents["playback"].as<bool>(); any = true; }
|
||||||
|
if (e.contents["reports"].is<bool>()) { t.reports = e.contents["reports"].as<bool>(); any = true; }
|
||||||
|
if (e.contents["alerts"].is<bool>()) { t.alerts = e.contents["alerts"].as<bool>(); any = true; }
|
||||||
|
if (e.contents["info"].is<bool>()) { t.info = e.contents["info"].as<bool>(); any = true; }
|
||||||
|
if (e.contents["logs"].is<bool>()) { t.logs = e.contents["logs"].as<bool>(); any = true; }
|
||||||
|
if (e.contents["metrics"].is<bool>()) { t.metrics = e.contents["metrics"].as<bool>(); any = true; }
|
||||||
|
|
||||||
|
if (!any) {
|
||||||
|
return CommandResult::err("mqtt.set_topics",
|
||||||
|
"No recognised topic fields in contents (command, heartbeat, playback, reports, alerts, info, logs, metrics)");
|
||||||
|
}
|
||||||
|
|
||||||
|
bool wasCommandOn = _configManager.getMqttTopicConfig().command;
|
||||||
|
_configManager.setMqttTopicConfig(t);
|
||||||
|
|
||||||
|
if (!_configManager.saveGeneralConfig()) {
|
||||||
|
return CommandResult::err("mqtt.set_topics", "Topic switches changed but failed to save to SD");
|
||||||
|
}
|
||||||
|
|
||||||
|
// command topic switch controls the control/command subscription — flip
|
||||||
|
// the live subscription immediately rather than waiting for a reconnect.
|
||||||
|
if (wasCommandOn != t.command) {
|
||||||
|
_mqttClient.applyCommandTopicSwitch(t.command);
|
||||||
|
}
|
||||||
|
|
||||||
|
LOG_INFO(TAG, "MQTT topic switches updated");
|
||||||
|
return CommandResult::ok("mqtt.set_topics", "MQTT topic switches updated and saved");
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
#include "../ICommandHandler.hpp"
|
||||||
|
|
||||||
|
class ConfigManager;
|
||||||
|
|
||||||
|
// Forward declare the driver to avoid pulling in full MQTTDriver header.
|
||||||
|
class MQTTDriver;
|
||||||
|
|
||||||
|
class MQTTHandler : public ICommandHandler {
|
||||||
|
public:
|
||||||
|
MQTTHandler(ConfigManager& configManager, MQTTDriver& mqttClient);
|
||||||
|
|
||||||
|
std::vector<String> commands() const override;
|
||||||
|
CommandResult execute(const CommandEnvelope& envelope) override;
|
||||||
|
|
||||||
|
private:
|
||||||
|
ConfigManager& _configManager;
|
||||||
|
MQTTDriver& _mqttClient;
|
||||||
|
|
||||||
|
CommandResult handleGetConfig(const CommandEnvelope& e);
|
||||||
|
CommandResult handleGetTopics(const CommandEnvelope& e);
|
||||||
|
CommandResult handleSetTopics(const CommandEnvelope& e);
|
||||||
|
};
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
#include "NetworkHandler.hpp"
|
||||||
|
#include "../../../ConfigManager/ConfigManager.hpp"
|
||||||
|
#include "../../../Networking/Networking.hpp"
|
||||||
|
#include "../../../Logging/Logging.hpp"
|
||||||
|
#include <WiFi.h>
|
||||||
|
|
||||||
|
#define TAG "NetworkHandler"
|
||||||
|
|
||||||
|
NetworkHandler::NetworkHandler(ConfigManager& configManager, Networking& networking)
|
||||||
|
: _configManager(configManager), _networking(networking) {}
|
||||||
|
|
||||||
|
std::vector<String> NetworkHandler::commands() const {
|
||||||
|
return { "network.info", "network.status", "network.set_config" };
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult NetworkHandler::execute(const CommandEnvelope& envelope) {
|
||||||
|
if (envelope.command == "network.info") return handleInfo(envelope);
|
||||||
|
if (envelope.command == "network.status") return handleStatus(envelope);
|
||||||
|
if (envelope.command == "network.set_config") return handleSetConfig(envelope);
|
||||||
|
return CommandResult::err(envelope.command, "Unknown network command");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult NetworkHandler::handleInfo(const CommandEnvelope& e) {
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["ip"] = WiFi.localIP().toString();
|
||||||
|
doc["subnet"] = WiFi.subnetMask().toString();
|
||||||
|
doc["gateway"] = WiFi.gatewayIP().toString();
|
||||||
|
doc["dns"] = WiFi.dnsIP().toString();
|
||||||
|
doc["mac"] = WiFi.macAddress();
|
||||||
|
doc["hostname"] = _configManager.getNetworkConfig().hostname;
|
||||||
|
doc["ssid"] = WiFi.SSID();
|
||||||
|
doc["connection_type"] = _networking.isInAPMode() ? "AP" :
|
||||||
|
(_networking.getActiveConnection() == ConnectionType::ETHERNET ? "ETHERNET" : "WIFI");
|
||||||
|
return CommandResult::ok("network.info", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult NetworkHandler::handleStatus(const CommandEnvelope& e) {
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["connected"] = _networking.isConnected();
|
||||||
|
doc["ap_mode"] = _networking.isInAPMode();
|
||||||
|
doc["rssi"] = WiFi.RSSI();
|
||||||
|
doc["uptime_ms"] = millis();
|
||||||
|
|
||||||
|
const char* stateStr = "UNKNOWN";
|
||||||
|
switch (_networking.getState()) {
|
||||||
|
case NetworkState::DISCONNECTED: stateStr = "DISCONNECTED"; break;
|
||||||
|
case NetworkState::CONNECTING_WIFI: stateStr = "CONNECTING"; break;
|
||||||
|
case NetworkState::CONNECTED_WIFI: stateStr = "CONNECTED_WIFI"; break;
|
||||||
|
case NetworkState::CONNECTED_ETHERNET: stateStr = "CONNECTED_ETHERNET"; break;
|
||||||
|
case NetworkState::RECONNECTING: stateStr = "RECONNECTING"; break;
|
||||||
|
case NetworkState::AP_MODE_PERMANENT: stateStr = "AP_MODE"; break;
|
||||||
|
default: break;
|
||||||
|
}
|
||||||
|
doc["state"] = stateStr;
|
||||||
|
|
||||||
|
return CommandResult::ok("network.status", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult NetworkHandler::handleSetConfig(const CommandEnvelope& e) {
|
||||||
|
bool hasHostname = e.contents["hostname"].is<const char*>();
|
||||||
|
bool hasStaticIPCfg = e.contents["useStaticIP"].is<bool>();
|
||||||
|
bool hasAPMode = e.contents["permanent_ap_mode"].is<bool>();
|
||||||
|
|
||||||
|
if (!hasHostname && !hasStaticIPCfg && !hasAPMode) {
|
||||||
|
return CommandResult::err("network.set_config", "No network parameters provided");
|
||||||
|
}
|
||||||
|
|
||||||
|
// AP mode toggle — handled independently (no IP fields needed).
|
||||||
|
if (hasAPMode) {
|
||||||
|
bool enable = e.contents["permanent_ap_mode"].as<bool>();
|
||||||
|
_configManager.setPermanentAPMode(enable);
|
||||||
|
_configManager.saveNetworkConfig();
|
||||||
|
LOG_INFO(TAG, "Permanent AP mode %s", enable ? "enabled" : "disabled");
|
||||||
|
return CommandResult::ok("network.set_config",
|
||||||
|
enable ? "AP mode saved. Restart to apply."
|
||||||
|
: "Station mode saved. Restart to apply.");
|
||||||
|
}
|
||||||
|
|
||||||
|
auto& current = _configManager.getNetworkConfig();
|
||||||
|
bool useStatic = current.useStaticIP;
|
||||||
|
IPAddress ip = current.ip, gateway = current.gateway;
|
||||||
|
IPAddress subnet = current.subnet, dns1 = current.dns1, dns2 = current.dns2;
|
||||||
|
String hostname = current.hostname;
|
||||||
|
|
||||||
|
if (hasHostname) {
|
||||||
|
String h = e.contents["hostname"].as<String>();
|
||||||
|
if (h.isEmpty() || h.length() > 32) {
|
||||||
|
return CommandResult::err("network.set_config", "Hostname must be 1-32 characters");
|
||||||
|
}
|
||||||
|
hostname = h;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hasStaticIPCfg) {
|
||||||
|
useStatic = e.contents["useStaticIP"].as<bool>();
|
||||||
|
if (useStatic) {
|
||||||
|
if (!e.contents["ip"].is<const char*>() ||
|
||||||
|
!e.contents["gateway"].is<const char*>() ||
|
||||||
|
!e.contents["subnet"].is<const char*>()) {
|
||||||
|
return CommandResult::err("network.set_config",
|
||||||
|
"Static IP requires: ip, gateway, subnet");
|
||||||
|
}
|
||||||
|
if (!ip.fromString(e.contents["ip"].as<String>())) {
|
||||||
|
return CommandResult::err("network.set_config", "Invalid IP address format");
|
||||||
|
}
|
||||||
|
if (!gateway.fromString(e.contents["gateway"].as<String>())) {
|
||||||
|
return CommandResult::err("network.set_config", "Invalid gateway format");
|
||||||
|
}
|
||||||
|
if (!subnet.fromString(e.contents["subnet"].as<String>())) {
|
||||||
|
return CommandResult::err("network.set_config", "Invalid subnet format");
|
||||||
|
}
|
||||||
|
if (e.contents["dns1"].is<const char*>()) dns1.fromString(e.contents["dns1"].as<String>());
|
||||||
|
if (e.contents["dns2"].is<const char*>()) dns2.fromString(e.contents["dns2"].as<String>());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_configManager.updateNetworkConfig(hostname, useStatic, ip, gateway, subnet, dns1, dns2);
|
||||||
|
LOG_INFO(TAG, "Network config updated — restart required to apply");
|
||||||
|
return CommandResult::ok("network.set_config",
|
||||||
|
"Network configuration saved. Restart device to apply changes.");
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
#include "../ICommandHandler.hpp"
|
||||||
|
|
||||||
|
class ConfigManager;
|
||||||
|
class Networking;
|
||||||
|
|
||||||
|
class NetworkHandler : public ICommandHandler {
|
||||||
|
public:
|
||||||
|
NetworkHandler(ConfigManager& configManager, Networking& networking);
|
||||||
|
|
||||||
|
std::vector<String> commands() const override;
|
||||||
|
CommandResult execute(const CommandEnvelope& envelope) override;
|
||||||
|
|
||||||
|
private:
|
||||||
|
ConfigManager& _configManager;
|
||||||
|
Networking& _networking;
|
||||||
|
|
||||||
|
CommandResult handleInfo(const CommandEnvelope& e);
|
||||||
|
CommandResult handleStatus(const CommandEnvelope& e);
|
||||||
|
CommandResult handleSetConfig(const CommandEnvelope& e);
|
||||||
|
};
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
#include "PlaybackHandler.hpp"
|
||||||
|
#include "../../../Player/Player.hpp"
|
||||||
|
#include "../../../Logging/Logging.hpp"
|
||||||
|
|
||||||
|
#define TAG "PlaybackHandler"
|
||||||
|
|
||||||
|
PlaybackHandler::PlaybackHandler(Player& player) : _player(player) {}
|
||||||
|
|
||||||
|
std::vector<String> PlaybackHandler::commands() const {
|
||||||
|
return { "playback.play", "playback.stop" };
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult PlaybackHandler::execute(const CommandEnvelope& envelope) {
|
||||||
|
if (envelope.command == "playback.play") return handlePlay(envelope);
|
||||||
|
if (envelope.command == "playback.stop") return handleStop(envelope);
|
||||||
|
return CommandResult::err("playback", "Unknown playback command");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Carry the command's origin through to the Player so status/playback can
|
||||||
|
// report what triggered playback (see PlaybackState.hpp).
|
||||||
|
static PlaybackSource sourceFromOrigin(CommandEnvelope::Origin origin) {
|
||||||
|
switch (origin) {
|
||||||
|
case CommandEnvelope::Origin::APP: return PlaybackSource::APP;
|
||||||
|
case CommandEnvelope::Origin::BUTTON: return PlaybackSource::BUTTON;
|
||||||
|
case CommandEnvelope::Origin::SCHEDULE: return PlaybackSource::SCHEDULE;
|
||||||
|
default: return PlaybackSource::UNKNOWN;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult PlaybackHandler::handlePlay(const CommandEnvelope& envelope) {
|
||||||
|
// Inject action so Player::command() takes the play branch regardless of
|
||||||
|
// whether it was set by the V1 adapter or arrived as a bare V2 play command.
|
||||||
|
JsonDocument& contents = const_cast<JsonDocument&>(envelope.contents);
|
||||||
|
contents["action"] = "play";
|
||||||
|
return toResult(_player.command(contents.as<JsonVariant>(), sourceFromOrigin(envelope.origin)));
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult PlaybackHandler::handleStop(const CommandEnvelope& envelope) {
|
||||||
|
JsonDocument& contents = const_cast<JsonDocument&>(envelope.contents);
|
||||||
|
contents["action"] = "stop";
|
||||||
|
return toResult(_player.command(contents.as<JsonVariant>(), sourceFromOrigin(envelope.origin)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Player supplies the exact reply text — success wording or the specific
|
||||||
|
// rejection reason — so the ACK tells the caller *why*, not just "failed".
|
||||||
|
CommandResult PlaybackHandler::toResult(const PlayerCommandResult& r) {
|
||||||
|
return r.ok ? CommandResult::ok("playback", r.message)
|
||||||
|
: CommandResult::err("playback", r.message);
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
#include "../ICommandHandler.hpp"
|
||||||
|
|
||||||
|
class Player;
|
||||||
|
struct PlayerCommandResult;
|
||||||
|
|
||||||
|
class PlaybackHandler : public ICommandHandler {
|
||||||
|
public:
|
||||||
|
explicit PlaybackHandler(Player& player);
|
||||||
|
|
||||||
|
std::vector<String> commands() const override;
|
||||||
|
CommandResult execute(const CommandEnvelope& envelope) override;
|
||||||
|
|
||||||
|
private:
|
||||||
|
Player& _player;
|
||||||
|
|
||||||
|
CommandResult handlePlay(const CommandEnvelope& envelope);
|
||||||
|
CommandResult handleStop(const CommandEnvelope& envelope);
|
||||||
|
static CommandResult toResult(const PlayerCommandResult& r);
|
||||||
|
};
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
# Handlers
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
Domain handlers implement the `ICommandHandler` interface and contain the actual logic for each command namespace. Each handler is constructed with references to the subsystems it needs, registered onto the `CommandBus` via `CommunicationRouter::registerHandlers()`, and called synchronously by the bus when a matching command arrives. Handlers never call `envelope.reply()` directly — they return a `CommandResult` and the bus handles the reply. Handlers must not throw.
|
||||||
|
|
||||||
|
See [ICommandHandler.hpp](ICommandHandler.hpp) for the interface definition.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Handler Registry
|
||||||
|
|
||||||
|
| Handler | Commands owned | Dependencies |
|
||||||
|
|---------|---------------|--------------|
|
||||||
|
| `PlaybackHandler` | `playback` | `Player` |
|
||||||
|
| `RelayHandler` | `relay.set_durations`, `relay.set_outputs`, `relay.get_config`, `relay.test_output` | `ConfigManager`, `OutputManager`, `Player` |
|
||||||
|
| `ClockHandler` | `clock.set_outputs`, `clock.set_timings`, `clock.set_alerts`, `clock.set_backlight`, `clock.set_silence`, `clock.set_time`, `clock.set_face`, `clock.set_timezone`, `clock.get_timezone`, `clock.sync_ntp`, `clock.enable`, `clock.disable`, `clock.pause`, `clock.resume`, `clock.get_face`, `clock.get_config` | `ConfigManager`, `Timekeeper` |
|
||||||
|
| `SystemHandler` | `ping`, `identify`, `system.status`, `system.get_time`, `system.get_settings`, `system.get_device_info`, `system.health`, `system.factory_reset`, `system.restart` | `ConfigManager`, `Player`, `Telemetry`, `HealthMonitor`, `Timekeeper`, `ClientManager` |
|
||||||
|
| `FirmwareHandler` | `firmware.status`, `firmware.commit`, `firmware.rollback`, `ota.update`, `ota.custom` | `FirmwareValidator`, `OTAManager`, `Player` |
|
||||||
|
| `NetworkHandler` | `network.info`, `network.status`, `network.set_config` | `ConfigManager`, `Networking` |
|
||||||
|
| `FileHandler` | `files.list`, `files.list_builtin`, `files.download`, `files.delete` | `FileManager` |
|
||||||
|
| `LoggingHandler` | `log.set_serial`, `log.set_sd`, `log.set_mqtt` | `ConfigManager` |
|
||||||
|
| `TelemetryHandler` | `telemetry.get_strikes`, `telemetry.reset_strikes`, `telemetry.get_loads` | `Telemetry` |
|
||||||
|
| `MQTTHandler` | `mqtt.enable`, `mqtt.disable` | `ConfigManager`, `MQTTDriver` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## PlaybackHandler
|
||||||
|
|
||||||
|
Forwards the entire `contents` object to `Player::command()` as a `JsonVariant`. The Player interprets the contents internally (action, melody name, bell selection, etc.).
|
||||||
|
|
||||||
|
**Commands:**
|
||||||
|
|
||||||
|
| Command | Contents | Description |
|
||||||
|
|---------|----------|-------------|
|
||||||
|
| `playback` | Player-specific JSON | Forward to `Player::command()`. Returns error if the player rejects the command. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## RelayHandler
|
||||||
|
|
||||||
|
Manages relay output configuration (durations and output pin mappings). Persists changes to SD via `ConfigManager`. Test output is blocked while the player is active.
|
||||||
|
|
||||||
|
**Commands:**
|
||||||
|
|
||||||
|
| Command | Required contents | Description |
|
||||||
|
|---------|------------------|-------------|
|
||||||
|
| `relay.set_durations` | `{ "bells": { "0": 500, ... } }` | Update strike durations (ms) for up to 16 bells. Saves to SD. |
|
||||||
|
| `relay.set_outputs` | `{ "bells": { "0": 2, ... } }` | Update physical output pin mapping for each bell. Saves to SD. |
|
||||||
|
| `relay.get_config` | — | Returns all 16 bell durations and output assignments. |
|
||||||
|
| `relay.test_output` | `{ "output": 0–31, "duration_ms": 1–5000 }` | Fires a single output. Blocked if player is not stopped. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ClockHandler
|
||||||
|
|
||||||
|
Full control over the Timekeeper clock subsystem and its persisted configuration. Most commands save to SD via `ConfigManager`.
|
||||||
|
|
||||||
|
**Commands:**
|
||||||
|
|
||||||
|
| Command | Key contents fields | Description |
|
||||||
|
|---------|---------------------|-------------|
|
||||||
|
| `clock.set_outputs` | Clock output config object | Set C1/C2 output pins. Saves clock config. |
|
||||||
|
| `clock.set_timings` | `pulse_duration`, `pause_duration` | Set impulse clock pulse and pause durations (ms). |
|
||||||
|
| `clock.set_alerts` | Alert config object | Set hourly/half/quarter bell alert settings. |
|
||||||
|
| `clock.set_backlight` | Backlight config object | Configure backlight output and schedule. |
|
||||||
|
| `clock.set_silence` | Silence config object | Configure daytime/nighttime silence windows. |
|
||||||
|
| `clock.set_time` | `timestamp` (unix), optional `timezone_offset`, `dst_offset` | Set RTC time. Also updates timezone config if offsets provided. |
|
||||||
|
| `clock.set_face` | `hour` (0–23), `minute` (0–59) | Set the physical clock face position. Saves clock state. |
|
||||||
|
| `clock.set_timezone` | `gmt_offset_sec`, optional `dst_offset_sec` | Persist timezone config. Does not update RTC. |
|
||||||
|
| `clock.get_timezone` | — | Returns `gmt_offset_sec`, `dst_offset_sec`, `ntp_server`. |
|
||||||
|
| `clock.sync_ntp` | — | Triggers an immediate NTP sync via `Timekeeper::syncTimeWithNTP()`. |
|
||||||
|
| `clock.enable` | — | Enables clock operation. Saves to SD. |
|
||||||
|
| `clock.disable` | — | Disables clock operation. Saves to SD. |
|
||||||
|
| `clock.pause` | — | Pauses clock motor updates (in-memory only, not saved). |
|
||||||
|
| `clock.resume` | — | Resumes clock motor updates. |
|
||||||
|
| `clock.get_face` | — | Returns `clock_hour`, `clock_minute`, `last_sync_time`, `next_output_is_c1`. |
|
||||||
|
| `clock.get_config` | — | Returns the full `ClockConfig` struct as JSON. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## SystemHandler
|
||||||
|
|
||||||
|
General device management. `identify` is WebSocket-only. `system.restart` defers the actual reboot to a FreeRTOS task so the reply reaches the client first. `ping`/`identify`/all `system.*` commands here are wrapped in `#if HAS_RTC` — this handler does not exist on non-RTC variants (e.g. `agnus_mini`).
|
||||||
|
|
||||||
|
**Commands:**
|
||||||
|
|
||||||
|
| Command | Key contents | Description |
|
||||||
|
|---------|-------------|-------------|
|
||||||
|
| `ping` | `{ "ts": 1752600000123 }` (optional) | Echoes `ts` back unchanged plus `device_uptime_ms` (`millis()`), so the caller can compute round-trip time as `(time of response receipt) − ts` without needing synchronized clocks. Returns `{ "status": "SUCCESS", "type": "pong", "data": { "ts": 1752600000123, "device_uptime_ms": 184213 } }`. `ts` is omitted from the response if the caller didn't send one — fully backward compatible with callers that just want a liveness ack. |
|
||||||
|
| `identify` | `{ "device_type": "master"\|"secondary" }` | WebSocket only. Classifies the calling client in `ClientManager`. |
|
||||||
|
| `system.status` | — | Player status, time elapsed, projected run time, 16 strike counters. |
|
||||||
|
| `system.get_time` | — | Local and UTC timestamps, broken-down time fields, `rtc_available`. |
|
||||||
|
| `system.get_settings` | — | Full device settings as JSON (from `ConfigManager::getAllSettingsAsJson()`). |
|
||||||
|
| `system.get_device_info` | — | UID, hw type, hw version, fw version, uptime, free heap. |
|
||||||
|
| `system.health` | — | Triggers `HealthMonitor::performFullHealthCheck()`; returns per-subsystem status. |
|
||||||
|
| `system.factory_reset` | — | Resets all config to defaults. **Does not reboot automatically.** |
|
||||||
|
| `system.restart` | — | Schedules `ESP.restart()` 2 seconds after reply. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## FirmwareHandler
|
||||||
|
|
||||||
|
OTA update management and firmware validation control. OTA commands are blocked during active playback.
|
||||||
|
|
||||||
|
**Commands:**
|
||||||
|
|
||||||
|
| Command | Key contents | Description |
|
||||||
|
|---------|-------------|-------------|
|
||||||
|
| `firmware.status` | — | Returns validation state, version info, `can_commit`, `can_rollback`. |
|
||||||
|
| `firmware.commit` | — | Manually commits the firmware under test. Errors if not in testing mode. |
|
||||||
|
| `firmware.rollback` | — | Rolls back to previous firmware and reboots. |
|
||||||
|
| `ota.update` | optional `{ "channel": "stable" }` | Triggers OTA update from configured channel. Blocked if player is active. |
|
||||||
|
| `ota.custom` | `{ "firmware_url": "...", "checksum": "...", "file_size": N, "version": N }` | OTA from a custom URL. `firmware_url` is required. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## NetworkHandler
|
||||||
|
|
||||||
|
Network status queries and configuration. AP mode toggle via `network.set_config` with `permanent_ap_mode` is the primary use case (also called by `WebServerTransport`). Full static IP configuration is supported.
|
||||||
|
|
||||||
|
**Commands:**
|
||||||
|
|
||||||
|
| Command | Key contents | Description |
|
||||||
|
|---------|-------------|-------------|
|
||||||
|
| `network.info` | — | Returns `ip`, `gateway`, `dns` from `WiFi` directly. |
|
||||||
|
| `network.status` | — | Returns `connected`, `ip`, `ap_mode`, `rssi`, `state`, `type`. |
|
||||||
|
| `network.set_config` | `permanent_ap_mode` bool, or `hostname`/`useStaticIP`/`ip`/`gateway`/`subnet`/`dns1`/`dns2` | Saves network config. Restart required to apply. AP mode toggle is handled independently. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## FileHandler
|
||||||
|
|
||||||
|
SD card melody file management. All operations require a healthy SD card via `FileManager`.
|
||||||
|
|
||||||
|
**Commands:**
|
||||||
|
|
||||||
|
| Command | Key contents | Description |
|
||||||
|
|---------|-------------|-------------|
|
||||||
|
| `files.list` | — | Lists all `.json` files in `/melodies`. Returns `{ "files": [...] }`. |
|
||||||
|
| `files.list_builtin` | — | Returns the built-in melody list from `BuiltInMelodies`. |
|
||||||
|
| `files.download` | Melody JSON object | Downloads / saves a melody to SD via `FileManager::addMelody()`. Uses `melodys_uid` or `name` for logging. |
|
||||||
|
| `files.delete` | `{ "name": "filename.json" }` | Deletes `/melodies/{name}`. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## LoggingHandler
|
||||||
|
|
||||||
|
Runtime log level control. Changes take effect immediately and are persisted to SD via `ConfigManager::saveGeneralConfig()`.
|
||||||
|
|
||||||
|
**Commands:**
|
||||||
|
|
||||||
|
| Command | Contents | Description |
|
||||||
|
|---------|----------|-------------|
|
||||||
|
| `log.set_serial` | `{ "level": 0–5 }` | Sets serial log level. 0=NONE, 5=VERBOSE. |
|
||||||
|
| `log.set_sd` | `{ "level": 0–5 }` | Sets SD card log level. |
|
||||||
|
| `log.set_mqtt` | `{ "level": 0–5 }` | Sets MQTT log level. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## TelemetryHandler
|
||||||
|
|
||||||
|
Read-only access to bell strike counters and load measurements. Reset clears all 16 counters at once.
|
||||||
|
|
||||||
|
**Commands:**
|
||||||
|
|
||||||
|
| Command | Description |
|
||||||
|
|---------|-------------|
|
||||||
|
| `telemetry.get_strikes` | Returns strike counts for all 16 bells as `{ "strikes": { "0": N, ... } }`. |
|
||||||
|
| `telemetry.reset_strikes` | Resets all 16 strike counters to 0. |
|
||||||
|
| `telemetry.get_loads` | Returns current load values, `cooling_active` flag, and array of overloaded bell indices. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## MQTTHandler
|
||||||
|
|
||||||
|
Enables or disables the MQTT connection at runtime. The state is saved to SD and the connection is immediately opened or closed.
|
||||||
|
|
||||||
|
**Commands:**
|
||||||
|
|
||||||
|
| Command | Description |
|
||||||
|
|---------|-------------|
|
||||||
|
| `mqtt.enable` | Enables MQTT in config, saves, calls `MQTTDriver::connect()`. |
|
||||||
|
| `mqtt.disable` | Disables MQTT in config, saves, calls `MQTTDriver::disconnect()`. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## General Notes
|
||||||
|
|
||||||
|
- **All handlers are registered once** at boot in `CommunicationRouter::registerHandlers()`. Adding a new handler requires only adding a `registerHandler()` call there — the bus registration is automatic via `commands()`.
|
||||||
|
- **SD-writing commands can return partial success.** Several commands return a `CommandResult::err` with a message like `"Updated but failed to save to SD"`. The in-memory state is applied even if the SD save fails.
|
||||||
|
- **`system.factory_reset` does not reboot.** The caller must issue a separate `system.restart` to apply the reset.
|
||||||
|
- **`identify` enforces transport type.** It checks `envelope.transport == CommandEnvelope::Transport::WEBSOCKET` and returns an error for other transports. This is the only handler with transport-specific behaviour.
|
||||||
|
- **`system.restart` uses a deferred task.** `xTaskCreate` spawns a 1 KB task that waits 2 seconds then calls `ESP.restart()`. This ensures the `CommandResult::ok` reply reaches the client before the device reboots.
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
#include "RelayHandler.hpp"
|
||||||
|
#include "../../../ConfigManager/ConfigManager.hpp"
|
||||||
|
#include "../../../OutputManager/OutputManager.hpp"
|
||||||
|
#include "../../../Player/Player.hpp"
|
||||||
|
#include "../../../Logging/Logging.hpp"
|
||||||
|
|
||||||
|
#define TAG "RelayHandler"
|
||||||
|
|
||||||
|
RelayHandler::RelayHandler(ConfigManager& configManager, OutputManager& outputManager, Player& player)
|
||||||
|
: _configManager(configManager), _outputManager(outputManager), _player(player) {}
|
||||||
|
|
||||||
|
std::vector<String> RelayHandler::commands() const {
|
||||||
|
return {
|
||||||
|
"relay.set_durations", "relay.set_outputs", "relay.set_config", "relay.get_config",
|
||||||
|
"relay.test_output", "relay.test_bell", "relay.test_batch"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult RelayHandler::execute(const CommandEnvelope& envelope) {
|
||||||
|
if (envelope.command == "relay.set_durations") return handleSetDurations(envelope);
|
||||||
|
if (envelope.command == "relay.set_outputs") return handleSetOutputs(envelope);
|
||||||
|
if (envelope.command == "relay.set_config") return handleSetConfig(envelope);
|
||||||
|
if (envelope.command == "relay.get_config") return handleGetConfig(envelope);
|
||||||
|
if (envelope.command == "relay.test_output") return handleTestOutput(envelope);
|
||||||
|
if (envelope.command == "relay.test_bell") return handleTestBell(envelope);
|
||||||
|
if (envelope.command == "relay.test_batch") return handleTestBatch(envelope);
|
||||||
|
return CommandResult::err(envelope.command, "Unknown relay command");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult RelayHandler::handleSetDurations(const CommandEnvelope& e) {
|
||||||
|
JsonVariant contents = const_cast<JsonDocument&>(e.contents).as<JsonVariant>();
|
||||||
|
// Accept v2 nested {"bells":{"b1":...}} or v1 flat {"b1":...}
|
||||||
|
JsonVariant bells = contents["bells"].is<JsonObject>() ? contents["bells"].as<JsonVariant>() : contents;
|
||||||
|
if (bells.isNull()) {
|
||||||
|
return CommandResult::err("relay.set_durations", "Missing or invalid 'bells' object");
|
||||||
|
}
|
||||||
|
_configManager.updateBellDurations(bells);
|
||||||
|
if (!_configManager.saveBellDurations()) {
|
||||||
|
return CommandResult::err("relay.set_durations", "Durations updated but failed to save to SD");
|
||||||
|
}
|
||||||
|
LOG_INFO(TAG, "Bell durations updated and saved");
|
||||||
|
return CommandResult::ok("relay.set_durations", "Bell durations updated and saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult RelayHandler::handleSetOutputs(const CommandEnvelope& e) {
|
||||||
|
JsonVariant contents = const_cast<JsonDocument&>(e.contents).as<JsonVariant>();
|
||||||
|
// Accept v2 nested {"bells":{"b1":...}} or v1 flat {"b1":...}
|
||||||
|
JsonVariant bells = contents["bells"].is<JsonObject>() ? contents["bells"].as<JsonVariant>() : contents;
|
||||||
|
if (bells.isNull()) {
|
||||||
|
return CommandResult::err("relay.set_outputs", "Missing or invalid 'bells' object");
|
||||||
|
}
|
||||||
|
_configManager.updateBellOutputs(bells);
|
||||||
|
if (!_configManager.saveBellOutputs()) {
|
||||||
|
return CommandResult::err("relay.set_outputs", "Outputs updated but failed to save to SD");
|
||||||
|
}
|
||||||
|
LOG_INFO(TAG, "Bell outputs updated and saved");
|
||||||
|
return CommandResult::ok("relay.set_outputs", "Bell outputs updated and saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult RelayHandler::handleSetConfig(const CommandEnvelope& e) {
|
||||||
|
JsonVariant contents = const_cast<JsonDocument&>(e.contents).as<JsonVariant>();
|
||||||
|
|
||||||
|
bool hasDurations = contents["durations"].is<JsonObject>();
|
||||||
|
bool hasOutputs = contents["outputs"].is<JsonObject>();
|
||||||
|
|
||||||
|
if (!hasDurations && !hasOutputs) {
|
||||||
|
return CommandResult::err("relay.set_config", "Provide 'durations' and/or 'outputs' objects");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hasDurations) {
|
||||||
|
_configManager.updateBellDurations(contents["durations"].as<JsonVariant>());
|
||||||
|
if (!_configManager.saveBellDurations()) {
|
||||||
|
return CommandResult::err("relay.set_config", "Durations applied but failed to save to SD");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hasOutputs) {
|
||||||
|
_configManager.updateBellOutputs(contents["outputs"].as<JsonVariant>());
|
||||||
|
if (!_configManager.saveBellOutputs()) {
|
||||||
|
return CommandResult::err("relay.set_config", "Outputs applied but failed to save to SD");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
LOG_INFO(TAG, "relay.config applied (durations=%d outputs=%d)", hasDurations, hasOutputs);
|
||||||
|
return CommandResult::ok("relay.set_config", "Bell configuration updated and saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult RelayHandler::handleGetConfig(const CommandEnvelope& e) {
|
||||||
|
JsonDocument doc;
|
||||||
|
JsonObject durations = doc["durations"].to<JsonObject>();
|
||||||
|
JsonObject outputs = doc["outputs"].to<JsonObject>();
|
||||||
|
for (uint8_t i = 0; i < 16; i++) {
|
||||||
|
durations[String(i)] = _configManager.getBellDuration(i);
|
||||||
|
outputs[String(i)] = _configManager.getBellOutput(i);
|
||||||
|
}
|
||||||
|
return CommandResult::ok("relay.get_config", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult RelayHandler::handleTestOutput(const CommandEnvelope& e) {
|
||||||
|
if (!e.contents["output"].is<int>()) {
|
||||||
|
return CommandResult::err("relay.test_output", "Missing required field: output");
|
||||||
|
}
|
||||||
|
if (!e.contents["duration_ms"].is<int>()) {
|
||||||
|
return CommandResult::err("relay.test_output", "Missing required field: duration_ms");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!_player.isCurrentlyStopped()) {
|
||||||
|
return CommandResult::err("relay.test_output", "Player must be stopped before testing outputs");
|
||||||
|
}
|
||||||
|
|
||||||
|
int output = e.contents["output"].as<int>();
|
||||||
|
int durationMs = e.contents["duration_ms"].as<int>();
|
||||||
|
|
||||||
|
if (output < 0 || output > 31) {
|
||||||
|
return CommandResult::err("relay.test_output", "output must be 0-31");
|
||||||
|
}
|
||||||
|
if (durationMs < 1 || durationMs > 5000) {
|
||||||
|
return CommandResult::err("relay.test_output", "duration_ms must be 1-5000");
|
||||||
|
}
|
||||||
|
|
||||||
|
_outputManager.fireOutputForDuration((uint8_t)output, (uint16_t)durationMs);
|
||||||
|
LOG_INFO(TAG, "Test output %d fired for %d ms", output, durationMs);
|
||||||
|
return CommandResult::ok("relay.test_output",
|
||||||
|
"Output " + String(output) + " fired for " + String(durationMs) + " ms");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult RelayHandler::handleTestBell(const CommandEnvelope& e) {
|
||||||
|
if (!e.contents["bell"].is<int>()) {
|
||||||
|
return CommandResult::err("relay.test_bell", "Missing required field: bell (0-based bell index)");
|
||||||
|
}
|
||||||
|
int bell = e.contents["bell"].as<int>();
|
||||||
|
if (bell < 0 || bell > 15) {
|
||||||
|
return CommandResult::err("relay.test_bell", "bell must be 0-15");
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t output = _outputManager.getPhysicalOutput((uint8_t)bell);
|
||||||
|
uint16_t durationMs = _configManager.getBellDuration(bell);
|
||||||
|
|
||||||
|
if (output == 255) {
|
||||||
|
return CommandResult::err("relay.test_bell", "Bell " + String(bell) + " is disabled or unconfigured");
|
||||||
|
}
|
||||||
|
|
||||||
|
_outputManager.fireOutputForDuration(output, durationMs);
|
||||||
|
LOG_INFO(TAG, "Test bell %d → chip pin %d for %d ms", bell, output, durationMs);
|
||||||
|
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["bell"] = bell;
|
||||||
|
doc["output"] = output + 1; // 1-based for human readability
|
||||||
|
doc["duration_ms"] = durationMs;
|
||||||
|
return CommandResult::ok("relay.test_bell", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult RelayHandler::handleTestBatch(const CommandEnvelope& e) {
|
||||||
|
if (!e.contents["bells"].is<JsonArrayConst>()) {
|
||||||
|
return CommandResult::err("relay.test_batch", "Missing required field: bells (array of 0-based bell indices)");
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonArrayConst bellArr = e.contents["bells"].as<JsonArrayConst>();
|
||||||
|
if (bellArr.size() == 0) {
|
||||||
|
return CommandResult::err("relay.test_batch", "bells array must not be empty");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fire each bell for its configured duration — non-blocking (OutputManager handles timers)
|
||||||
|
// Bypasses bellsEnabled intentionally: test commands always fire
|
||||||
|
int fired = 0;
|
||||||
|
for (JsonVariantConst v : bellArr) {
|
||||||
|
if (!v.is<int>()) continue;
|
||||||
|
int bell = v.as<int>();
|
||||||
|
if (bell < 0 || bell > 15) continue;
|
||||||
|
uint8_t output = _outputManager.getPhysicalOutput((uint8_t)bell);
|
||||||
|
uint16_t durationMs = _configManager.getBellDuration((uint8_t)bell);
|
||||||
|
if (output == 255) continue; // disabled/unconfigured — skip silently
|
||||||
|
_outputManager.fireOutputForDuration(output, durationMs);
|
||||||
|
fired++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fired == 0) {
|
||||||
|
return CommandResult::err("relay.test_batch", "No valid bell indices in array");
|
||||||
|
}
|
||||||
|
|
||||||
|
LOG_INFO(TAG, "Test batch: %d bells fired", fired);
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["fired"] = fired;
|
||||||
|
return CommandResult::ok("relay.test_batch", doc);
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
#include "../ICommandHandler.hpp"
|
||||||
|
|
||||||
|
class ConfigManager;
|
||||||
|
class OutputManager;
|
||||||
|
class Player;
|
||||||
|
|
||||||
|
class RelayHandler : public ICommandHandler {
|
||||||
|
public:
|
||||||
|
RelayHandler(ConfigManager& configManager, OutputManager& outputManager, Player& player);
|
||||||
|
|
||||||
|
std::vector<String> commands() const override;
|
||||||
|
CommandResult execute(const CommandEnvelope& envelope) override;
|
||||||
|
|
||||||
|
private:
|
||||||
|
ConfigManager& _configManager;
|
||||||
|
OutputManager& _outputManager;
|
||||||
|
Player& _player;
|
||||||
|
|
||||||
|
CommandResult handleSetDurations(const CommandEnvelope& e);
|
||||||
|
CommandResult handleSetOutputs(const CommandEnvelope& e);
|
||||||
|
CommandResult handleSetConfig(const CommandEnvelope& e);
|
||||||
|
CommandResult handleGetConfig(const CommandEnvelope& e);
|
||||||
|
CommandResult handleTestOutput(const CommandEnvelope& e);
|
||||||
|
CommandResult handleTestBell(const CommandEnvelope& e);
|
||||||
|
CommandResult handleTestBatch(const CommandEnvelope& e);
|
||||||
|
};
|
||||||
@@ -0,0 +1,363 @@
|
|||||||
|
#if HAS_RTC
|
||||||
|
#include "SystemHandler.hpp"
|
||||||
|
#include "../../../ConfigManager/ConfigManager.hpp"
|
||||||
|
#include "../../../Player/Player.hpp"
|
||||||
|
#include "../../../Telemetry/Telemetry.hpp"
|
||||||
|
#include "../../../HealthMonitor/HealthMonitor.hpp"
|
||||||
|
#include "../../../TimeKeeper/TimeKeeper.hpp"
|
||||||
|
#include "../../../ClientManager/ClientManager.hpp"
|
||||||
|
#include "../../../Logging/Logging.hpp"
|
||||||
|
#include <Arduino.h>
|
||||||
|
|
||||||
|
#define TAG "SystemHandler"
|
||||||
|
|
||||||
|
SystemHandler::SystemHandler(ConfigManager& configManager, Player& player,
|
||||||
|
Telemetry& telemetry, HealthMonitor& healthMonitor,
|
||||||
|
Timekeeper& timeKeeper, ClientManager& clientManager)
|
||||||
|
: _configManager(configManager)
|
||||||
|
, _player(player)
|
||||||
|
, _telemetry(telemetry)
|
||||||
|
, _healthMonitor(healthMonitor)
|
||||||
|
, _timeKeeper(timeKeeper)
|
||||||
|
, _clientManager(clientManager) {}
|
||||||
|
|
||||||
|
std::vector<String> SystemHandler::commands() const {
|
||||||
|
return {
|
||||||
|
"ping", "identify",
|
||||||
|
"system.status", "system.get_time",
|
||||||
|
"system.get_config", // replaces system.get_settings (kept as alias below)
|
||||||
|
"system.get_settings", // backward-compat alias — routes to handleGetConfig
|
||||||
|
"system.get_device_info", "system.health",
|
||||||
|
"system.get_all", "system.get_telemetry",
|
||||||
|
"system.factory_reset", "system.restart",
|
||||||
|
"system.set_identity"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult SystemHandler::execute(const CommandEnvelope& envelope) {
|
||||||
|
if (envelope.command == "ping") return handlePing(envelope);
|
||||||
|
if (envelope.command == "identify") return handleIdentify(envelope);
|
||||||
|
if (envelope.command == "system.status") return handleStatus(envelope);
|
||||||
|
if (envelope.command == "system.get_time") return handleGetTime(envelope);
|
||||||
|
if (envelope.command == "system.get_config" ||
|
||||||
|
envelope.command == "system.get_settings") return handleGetConfig(envelope);
|
||||||
|
if (envelope.command == "system.get_device_info") return handleGetDeviceInfo(envelope);
|
||||||
|
if (envelope.command == "system.health") return handleHealth(envelope);
|
||||||
|
if (envelope.command == "system.get_all") return handleGetAll(envelope);
|
||||||
|
if (envelope.command == "system.get_telemetry") return handleGetTelemetry(envelope);
|
||||||
|
if (envelope.command == "system.factory_reset") return handleFactoryReset(envelope);
|
||||||
|
if (envelope.command == "system.restart") return handleRestart(envelope);
|
||||||
|
if (envelope.command == "system.set_identity") return handleSetIdentity(envelope);
|
||||||
|
return CommandResult::err(envelope.command, "Unknown system command");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
CommandResult SystemHandler::handlePing(const CommandEnvelope& e) {
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["type"] = "pong";
|
||||||
|
// Echo caller's timestamp back unchanged so the caller can compute RTT
|
||||||
|
// as (time_received - contents.ts) without needing symmetric clocks.
|
||||||
|
// uint64_t: epoch-millis (e.g. 1752600000123) overflows uint32_t.
|
||||||
|
if (e.contents["ts"].is<uint64_t>()) {
|
||||||
|
doc["ts"] = e.contents["ts"];
|
||||||
|
}
|
||||||
|
doc["device_uptime_ms"] = millis();
|
||||||
|
return CommandResult::ok("pong", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult SystemHandler::handleIdentify(const CommandEnvelope& e) {
|
||||||
|
if (e.transport != CommandEnvelope::Transport::WEBSOCKET) {
|
||||||
|
return CommandResult::err("identify", "identify is only available via WebSocket");
|
||||||
|
}
|
||||||
|
if (!e.contents["device_type"].is<const char*>()) {
|
||||||
|
return CommandResult::err("identify", "Missing required field: device_type");
|
||||||
|
}
|
||||||
|
|
||||||
|
String deviceTypeStr = e.contents["device_type"].as<String>();
|
||||||
|
ClientManager::DeviceType deviceType = ClientManager::DeviceType::UNKNOWN;
|
||||||
|
if (deviceTypeStr == "master") deviceType = ClientManager::DeviceType::MASTER;
|
||||||
|
if (deviceTypeStr == "secondary") deviceType = ClientManager::DeviceType::SECONDARY;
|
||||||
|
|
||||||
|
if (deviceType == ClientManager::DeviceType::UNKNOWN) {
|
||||||
|
return CommandResult::err("identify", "Invalid device_type. Use 'master' or 'secondary'");
|
||||||
|
}
|
||||||
|
|
||||||
|
_clientManager.updateClientType(e.clientId, deviceType);
|
||||||
|
LOG_INFO(TAG, "Client #%u identified as %s", e.clientId, deviceTypeStr.c_str());
|
||||||
|
return CommandResult::ok("identify", "Device identified as " + deviceTypeStr);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult SystemHandler::handleStatus(const CommandEnvelope& e) {
|
||||||
|
PlayerStatus playerStatus = _player.getStatus();
|
||||||
|
uint32_t timeElapsedMs = 0;
|
||||||
|
uint64_t projectedRunTime = 0;
|
||||||
|
|
||||||
|
if (playerStatus == PlayerStatus::PLAYING ||
|
||||||
|
playerStatus == PlayerStatus::PAUSED ||
|
||||||
|
playerStatus == PlayerStatus::STOPPING) {
|
||||||
|
timeElapsedMs = (uint32_t)(millis() - _player.startTime);
|
||||||
|
}
|
||||||
|
projectedRunTime = _player.calculateProjectedRunTime();
|
||||||
|
|
||||||
|
uint32_t strikeCounters[16] = {0};
|
||||||
|
for (uint8_t i = 0; i < 16; i++) {
|
||||||
|
strikeCounters[i] = _telemetry.getStrikeCount(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delegate to ResponseBuilder which already handles this format
|
||||||
|
// We build the result directly here to keep the handler self-contained
|
||||||
|
JsonDocument doc;
|
||||||
|
const char* statusStr = "STOPPED";
|
||||||
|
switch (playerStatus) {
|
||||||
|
case PlayerStatus::PLAYING: statusStr = "PLAYING"; break;
|
||||||
|
case PlayerStatus::PAUSED: statusStr = "PAUSED"; break;
|
||||||
|
case PlayerStatus::STOPPING: statusStr = "STOPPING"; break;
|
||||||
|
case PlayerStatus::LOADING: statusStr = "LOADING"; break;
|
||||||
|
default: break;
|
||||||
|
}
|
||||||
|
doc["player_status"] = statusStr;
|
||||||
|
doc["time_elapsed_ms"] = timeElapsedMs;
|
||||||
|
doc["projected_run_time"] = projectedRunTime;
|
||||||
|
JsonObject strikes = doc["strike_counters"].to<JsonObject>();
|
||||||
|
for (uint8_t i = 0; i < 16; i++) strikes[String(i)] = strikeCounters[i];
|
||||||
|
|
||||||
|
return CommandResult::ok("system.status", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult SystemHandler::handleGetTime(const CommandEnvelope& e) {
|
||||||
|
unsigned long localTimestamp = _timeKeeper.getTime();
|
||||||
|
const auto& timeConfig = _configManager.getTimeConfig();
|
||||||
|
long totalOffset = timeConfig.gmtOffsetSec + timeConfig.daylightOffsetSec;
|
||||||
|
unsigned long utcTimestamp = localTimestamp - totalOffset;
|
||||||
|
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["local_timestamp"] = localTimestamp;
|
||||||
|
doc["utc_timestamp"] = utcTimestamp;
|
||||||
|
doc["rtc_available"] = (localTimestamp > 0);
|
||||||
|
|
||||||
|
time_t rawTime = (time_t)localTimestamp;
|
||||||
|
struct tm* ti = gmtime(&rawTime);
|
||||||
|
doc["year"] = ti->tm_year + 1900;
|
||||||
|
doc["month"] = ti->tm_mon + 1;
|
||||||
|
doc["day"] = ti->tm_mday;
|
||||||
|
doc["hour"] = ti->tm_hour;
|
||||||
|
doc["minute"] = ti->tm_min;
|
||||||
|
doc["second"] = ti->tm_sec;
|
||||||
|
|
||||||
|
return CommandResult::ok("system.get_time", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult SystemHandler::handleGetConfig(const CommandEnvelope& e) {
|
||||||
|
String settingsJson = _configManager.getAllSettingsAsJson();
|
||||||
|
JsonDocument doc;
|
||||||
|
DeserializationError err = deserializeJson(doc, settingsJson);
|
||||||
|
if (err) {
|
||||||
|
LOG_ERROR(TAG, "Failed to parse settings JSON: %s", err.c_str());
|
||||||
|
return CommandResult::err("system.get_config", "Failed to serialize settings");
|
||||||
|
}
|
||||||
|
// Add bells_enabled which is not in getAllSettingsAsJson yet
|
||||||
|
doc["general"]["bells_enabled"] = _configManager.getBellsEnabled();
|
||||||
|
doc["general"]["mqtt_enabled"] = _configManager.getMqttEnabled();
|
||||||
|
doc["general"]["ota_channel"] = _configManager.getOtaChannel();
|
||||||
|
doc["general"]["serial_log"] = _configManager.getSerialLogLevel();
|
||||||
|
doc["general"]["sd_log"] = _configManager.getSdLogLevel();
|
||||||
|
doc["general"]["mqtt_log"] = _configManager.getMqttLogLevel();
|
||||||
|
return CommandResult::ok("system.get_config", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult SystemHandler::handleGetTelemetry(const CommandEnvelope& e) {
|
||||||
|
JsonDocument doc;
|
||||||
|
|
||||||
|
// Strike counters
|
||||||
|
JsonObject strikes = doc["strikes"].to<JsonObject>();
|
||||||
|
for (uint8_t i = 0; i < 16; i++) strikes[String(i)] = _telemetry.getStrikeCount(i);
|
||||||
|
|
||||||
|
// Bell loads
|
||||||
|
JsonObject loads = doc["loads"].to<JsonObject>();
|
||||||
|
JsonObject maxLoads = doc["max_loads"].to<JsonObject>();
|
||||||
|
for (uint8_t i = 0; i < 16; i++) {
|
||||||
|
loads[String(i)] = _telemetry.getBellLoad(i);
|
||||||
|
maxLoads[String(i)] = _telemetry.getBellMaxLoad(i);
|
||||||
|
}
|
||||||
|
doc["cooling_active"] = _telemetry.isCoolingActive();
|
||||||
|
doc["guard_enabled"] = _telemetry.isGuardEnabled();
|
||||||
|
|
||||||
|
// Runtime metrics
|
||||||
|
doc["lifetime_runtime_seconds"] = _telemetry.getLifetimeRuntimeSeconds();
|
||||||
|
doc["session_runtime_seconds"] = _telemetry.getCurrentSessionSeconds();
|
||||||
|
doc["total_playbacks"] = _telemetry.getTotalPlaybackCount();
|
||||||
|
doc["lifetime_boot_count"] = _telemetry.getLifetimeBootCount();
|
||||||
|
|
||||||
|
// Device uptime
|
||||||
|
doc["uptime_ms"] = millis();
|
||||||
|
doc["free_heap"] = (uint32_t)ESP.getFreeHeap();
|
||||||
|
|
||||||
|
return CommandResult::ok("system.get_telemetry", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult SystemHandler::handleGetAll(const CommandEnvelope& e) {
|
||||||
|
JsonDocument doc;
|
||||||
|
|
||||||
|
// ── Device identity ────────────────────────────────────────────────────
|
||||||
|
JsonObject device = doc["device"].to<JsonObject>();
|
||||||
|
device["serial"] = _configManager.getSerial();
|
||||||
|
device["hw_family"] = _configManager.getHwFamily();
|
||||||
|
device["hw_revision"] = _configManager.getHwRevision();
|
||||||
|
device["fw_version"] = _configManager.getFwVersion();
|
||||||
|
device["uptime_ms"] = millis();
|
||||||
|
device["free_heap"] = (uint32_t)ESP.getFreeHeap();
|
||||||
|
|
||||||
|
// ── Full config (reuse getAllSettingsAsJson) ────────────────────────────
|
||||||
|
{
|
||||||
|
String settingsJson = _configManager.getAllSettingsAsJson();
|
||||||
|
JsonDocument cfg;
|
||||||
|
if (!deserializeJson(cfg, settingsJson)) {
|
||||||
|
doc["config"] = cfg;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
doc["config"]["general"]["bells_enabled"] = _configManager.getBellsEnabled();
|
||||||
|
doc["config"]["general"]["mqtt_enabled"] = _configManager.getMqttEnabled();
|
||||||
|
doc["config"]["general"]["ota_channel"] = _configManager.getOtaChannel();
|
||||||
|
doc["config"]["general"]["serial_log"] = _configManager.getSerialLogLevel();
|
||||||
|
doc["config"]["general"]["sd_log"] = _configManager.getSdLogLevel();
|
||||||
|
doc["config"]["general"]["mqtt_log"] = _configManager.getMqttLogLevel();
|
||||||
|
|
||||||
|
// ── Telemetry snapshot ─────────────────────────────────────────────────
|
||||||
|
JsonObject telemetry = doc["telemetry"].to<JsonObject>();
|
||||||
|
JsonObject strikes = telemetry["strikes"].to<JsonObject>();
|
||||||
|
JsonObject loads = telemetry["loads"].to<JsonObject>();
|
||||||
|
JsonObject maxLoads = telemetry["max_loads"].to<JsonObject>();
|
||||||
|
for (uint8_t i = 0; i < 16; i++) {
|
||||||
|
strikes[String(i)] = _telemetry.getStrikeCount(i);
|
||||||
|
loads[String(i)] = _telemetry.getBellLoad(i);
|
||||||
|
maxLoads[String(i)] = _telemetry.getBellMaxLoad(i);
|
||||||
|
}
|
||||||
|
telemetry["cooling_active"] = _telemetry.isCoolingActive();
|
||||||
|
telemetry["guard_enabled"] = _telemetry.isGuardEnabled();
|
||||||
|
telemetry["lifetime_runtime_seconds"] = _telemetry.getLifetimeRuntimeSeconds();
|
||||||
|
telemetry["session_runtime_seconds"] = _telemetry.getCurrentSessionSeconds();
|
||||||
|
telemetry["total_playbacks"] = _telemetry.getTotalPlaybackCount();
|
||||||
|
telemetry["lifetime_boot_count"] = _telemetry.getLifetimeBootCount();
|
||||||
|
|
||||||
|
// ── Player status ──────────────────────────────────────────────────────
|
||||||
|
JsonObject player = doc["player"].to<JsonObject>();
|
||||||
|
PlayerStatus ps = _player.getStatus();
|
||||||
|
const char* psStr = "STOPPED";
|
||||||
|
switch (ps) {
|
||||||
|
case PlayerStatus::PLAYING: psStr = "PLAYING"; break;
|
||||||
|
case PlayerStatus::PAUSED: psStr = "PAUSED"; break;
|
||||||
|
case PlayerStatus::STOPPING: psStr = "STOPPING"; break;
|
||||||
|
case PlayerStatus::LOADING: psStr = "LOADING"; break;
|
||||||
|
default: break;
|
||||||
|
}
|
||||||
|
player["status"] = psStr;
|
||||||
|
|
||||||
|
return CommandResult::ok("system.get_all", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult SystemHandler::handleGetDeviceInfo(const CommandEnvelope& e) {
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["uid"] = _configManager.getDeviceUID();
|
||||||
|
doc["hw_type"] = _configManager.getHwType();
|
||||||
|
doc["hw_version"] = _configManager.getHwVersion();
|
||||||
|
doc["fw_version"] = _configManager.getFwVersion();
|
||||||
|
doc["uptime_ms"] = millis();
|
||||||
|
doc["free_heap"] = (uint32_t)ESP.getFreeHeap();
|
||||||
|
doc["min_free_heap"] = (uint32_t)ESP.getMinFreeHeap();
|
||||||
|
return CommandResult::ok("system.get_device_info", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult SystemHandler::handleHealth(const CommandEnvelope& e) {
|
||||||
|
_healthMonitor.performFullHealthCheck();
|
||||||
|
const auto& subsystems = _healthMonitor.getAllSubsystemHealth();
|
||||||
|
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["critical_count"] = _healthMonitor.getCriticalFailureCount();
|
||||||
|
doc["warning_count"] = _healthMonitor.getWarningCount();
|
||||||
|
doc["firmware_stable"] = _healthMonitor.isFirmwareStable();
|
||||||
|
|
||||||
|
JsonArray arr = doc["subsystems"].to<JsonArray>();
|
||||||
|
for (const auto& pair : subsystems) {
|
||||||
|
JsonObject obj = arr.add<JsonObject>();
|
||||||
|
obj["name"] = pair.second.name;
|
||||||
|
const char* s = "HEALTHY";
|
||||||
|
switch (pair.second.status) {
|
||||||
|
case HealthStatus::WARNING: s = "WARNING"; break;
|
||||||
|
case HealthStatus::CRITICAL: s = "CRITICAL"; break;
|
||||||
|
case HealthStatus::FAILED: s = "FAILED"; break;
|
||||||
|
default: break;
|
||||||
|
}
|
||||||
|
obj["status"] = s;
|
||||||
|
if (!pair.second.lastError.isEmpty()) obj["error"] = pair.second.lastError;
|
||||||
|
}
|
||||||
|
|
||||||
|
return CommandResult::ok("system.health", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult SystemHandler::handleFactoryReset(const CommandEnvelope& e) {
|
||||||
|
LOG_WARNING(TAG, "Factory reset requested");
|
||||||
|
bool ok = _configManager.resetAllToDefaults();
|
||||||
|
if (ok) {
|
||||||
|
return CommandResult::ok("system.factory_reset",
|
||||||
|
"Factory reset complete. Restart device to apply.");
|
||||||
|
}
|
||||||
|
return CommandResult::err("system.factory_reset",
|
||||||
|
"Factory reset partially applied — some settings may not have saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult SystemHandler::handleRestart(const CommandEnvelope& e) {
|
||||||
|
LOG_WARNING(TAG, "Device restart requested via command");
|
||||||
|
// Response is sent before restart via the reply lambda in the transport
|
||||||
|
// We schedule the restart after a brief delay so the reply gets out first
|
||||||
|
xTaskCreate([](void*) {
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(2000));
|
||||||
|
ESP.restart();
|
||||||
|
}, "restartTask", 1024, nullptr, 1, nullptr);
|
||||||
|
return CommandResult::ok("system.restart", "Device will restart in 2 seconds");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult SystemHandler::handleSetIdentity(const CommandEnvelope& e) {
|
||||||
|
// Sysadmin-only override of factory-set device identity. Restricted to MQTT so it can
|
||||||
|
// only be triggered from the backend/console, which is expected to update its own
|
||||||
|
// device record (and re-derive the MQTT password from the new serial) in lockstep —
|
||||||
|
// see ConfigManager::saveDeviceIdentityToNVS() for the full rationale.
|
||||||
|
if (e.transport != CommandEnvelope::Transport::MQTT) {
|
||||||
|
return CommandResult::err("system.set_identity", "system.set_identity is only available via MQTT");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!e.contents["serial"].is<const char*>() ||
|
||||||
|
!e.contents["hw_family"].is<const char*>() ||
|
||||||
|
!e.contents["hw_revision"].is<const char*>()) {
|
||||||
|
return CommandResult::err("system.set_identity",
|
||||||
|
"Missing required fields: serial, hw_family, hw_revision (all required)");
|
||||||
|
}
|
||||||
|
|
||||||
|
String serial = e.contents["serial"].as<String>();
|
||||||
|
String hwFamily = e.contents["hw_family"].as<String>();
|
||||||
|
String hwRevision = e.contents["hw_revision"].as<String>();
|
||||||
|
|
||||||
|
if (serial.isEmpty() || hwFamily.isEmpty() || hwRevision.isEmpty()) {
|
||||||
|
return CommandResult::err("system.set_identity",
|
||||||
|
"serial, hw_family and hw_revision must be non-empty");
|
||||||
|
}
|
||||||
|
|
||||||
|
LOG_WARNING(TAG, "Device identity override requested via MQTT command");
|
||||||
|
bool ok = _configManager.saveDeviceIdentityToNVS(serial, hwFamily, hwRevision);
|
||||||
|
if (!ok) {
|
||||||
|
return CommandResult::err("system.set_identity",
|
||||||
|
"Failed to persist new identity to NVS — device identity unchanged");
|
||||||
|
}
|
||||||
|
|
||||||
|
// MQTT credentials, hostname and AP SSID were derived from the OLD serial at boot
|
||||||
|
// and won't recompute without a restart, so force one after the reply goes out.
|
||||||
|
xTaskCreate([](void*) {
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(2000));
|
||||||
|
ESP.restart();
|
||||||
|
}, "setIdentityRebootTask", 1024, nullptr, 1, nullptr);
|
||||||
|
|
||||||
|
return CommandResult::ok("system.set_identity",
|
||||||
|
"Device identity updated. Restarting in 2 seconds to apply.");
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif // HAS_RTC
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#if HAS_RTC
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
#include "../ICommandHandler.hpp"
|
||||||
|
|
||||||
|
class ConfigManager;
|
||||||
|
class Player;
|
||||||
|
class Telemetry;
|
||||||
|
class HealthMonitor;
|
||||||
|
class Timekeeper;
|
||||||
|
class ClientManager;
|
||||||
|
|
||||||
|
class SystemHandler : public ICommandHandler {
|
||||||
|
public:
|
||||||
|
SystemHandler(ConfigManager& configManager, Player& player,
|
||||||
|
Telemetry& telemetry, HealthMonitor& healthMonitor,
|
||||||
|
Timekeeper& timeKeeper, ClientManager& clientManager);
|
||||||
|
|
||||||
|
std::vector<String> commands() const override;
|
||||||
|
CommandResult execute(const CommandEnvelope& envelope) override;
|
||||||
|
|
||||||
|
private:
|
||||||
|
ConfigManager& _configManager;
|
||||||
|
Player& _player;
|
||||||
|
Telemetry& _telemetry;
|
||||||
|
HealthMonitor& _healthMonitor;
|
||||||
|
Timekeeper& _timeKeeper;
|
||||||
|
ClientManager& _clientManager;
|
||||||
|
|
||||||
|
CommandResult handlePing(const CommandEnvelope& e);
|
||||||
|
CommandResult handleIdentify(const CommandEnvelope& e);
|
||||||
|
CommandResult handleStatus(const CommandEnvelope& e);
|
||||||
|
CommandResult handleGetTime(const CommandEnvelope& e);
|
||||||
|
CommandResult handleGetConfig(const CommandEnvelope& e);
|
||||||
|
CommandResult handleGetDeviceInfo(const CommandEnvelope& e);
|
||||||
|
CommandResult handleHealth(const CommandEnvelope& e);
|
||||||
|
CommandResult handleGetAll(const CommandEnvelope& e);
|
||||||
|
CommandResult handleGetTelemetry(const CommandEnvelope& e);
|
||||||
|
CommandResult handleFactoryReset(const CommandEnvelope& e);
|
||||||
|
CommandResult handleRestart(const CommandEnvelope& e);
|
||||||
|
CommandResult handleSetIdentity(const CommandEnvelope& e);
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif // HAS_RTC
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
#include "TelemetryHandler.hpp"
|
||||||
|
#include "../../../Telemetry/Telemetry.hpp"
|
||||||
|
#include "../../../OTAManager/OTAManager.hpp"
|
||||||
|
#include "../../../Networking/Networking.hpp"
|
||||||
|
#include "../../../Logging/Logging.hpp"
|
||||||
|
|
||||||
|
#define TAG "TelemetryHandler"
|
||||||
|
|
||||||
|
TelemetryHandler::TelemetryHandler(Telemetry& telemetry, OTAManager& otaManager, Networking& networking)
|
||||||
|
: _telemetry(telemetry), _otaManager(otaManager), _networking(networking) {}
|
||||||
|
|
||||||
|
std::vector<String> TelemetryHandler::commands() const {
|
||||||
|
return {
|
||||||
|
"telemetry.get_strikes", "telemetry.reset_strikes", "telemetry.get_loads",
|
||||||
|
"telemetry.set_max_loads", "telemetry.set_guard_enabled",
|
||||||
|
"telemetry.get_metrics", "telemetry.reset_metrics",
|
||||||
|
"telemetry.get_boot_history", "telemetry.get_diagnostics",
|
||||||
|
"telemetry.reset_boot_data"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult TelemetryHandler::execute(const CommandEnvelope& envelope) {
|
||||||
|
if (envelope.command == "telemetry.get_strikes") return handleGetStrikes(envelope);
|
||||||
|
if (envelope.command == "telemetry.reset_strikes") return handleResetStrikes(envelope);
|
||||||
|
if (envelope.command == "telemetry.get_loads") return handleGetLoads(envelope);
|
||||||
|
if (envelope.command == "telemetry.set_max_loads") return handleSetMaxLoads(envelope);
|
||||||
|
if (envelope.command == "telemetry.set_guard_enabled") return handleSetGuardEnabled(envelope);
|
||||||
|
if (envelope.command == "telemetry.get_metrics") return handleGetMetrics(envelope);
|
||||||
|
if (envelope.command == "telemetry.reset_metrics") return handleResetMetrics(envelope);
|
||||||
|
if (envelope.command == "telemetry.get_boot_history") return handleGetBootHistory(envelope);
|
||||||
|
if (envelope.command == "telemetry.get_diagnostics") return handleGetDiagnostics(envelope);
|
||||||
|
if (envelope.command == "telemetry.reset_boot_data") return handleResetBootData(envelope);
|
||||||
|
return CommandResult::err(envelope.command, "Unknown telemetry command");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult TelemetryHandler::handleGetStrikes(const CommandEnvelope& e) {
|
||||||
|
JsonDocument doc;
|
||||||
|
JsonObject strikes = doc["strikes"].to<JsonObject>();
|
||||||
|
for (uint8_t i = 0; i < 16; i++) {
|
||||||
|
strikes[String(i)] = _telemetry.getStrikeCount(i);
|
||||||
|
}
|
||||||
|
return CommandResult::ok("telemetry.get_strikes", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult TelemetryHandler::handleResetStrikes(const CommandEnvelope& e) {
|
||||||
|
// Telemetry currently supports resetting all counters at once.
|
||||||
|
// Per-bell reset via contents["bell"] is planned for a future Telemetry API extension.
|
||||||
|
_telemetry.resetStrikeCounters();
|
||||||
|
LOG_INFO(TAG, "All strike counts reset");
|
||||||
|
return CommandResult::ok("telemetry.reset_strikes", "All strike counts reset");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult TelemetryHandler::handleGetLoads(const CommandEnvelope& e) {
|
||||||
|
JsonDocument doc;
|
||||||
|
JsonObject loads = doc["loads"].to<JsonObject>();
|
||||||
|
JsonObject maxLoads = doc["max_loads"].to<JsonObject>();
|
||||||
|
for (uint8_t i = 0; i < 16; i++) {
|
||||||
|
loads[String(i)] = _telemetry.getBellLoad(i);
|
||||||
|
maxLoads[String(i)] = _telemetry.getBellMaxLoad(i);
|
||||||
|
}
|
||||||
|
doc["cooling_active"] = _telemetry.isCoolingActive();
|
||||||
|
doc["guard_enabled"] = _telemetry.isGuardEnabled();
|
||||||
|
|
||||||
|
JsonArray overloaded = doc["overloaded"].to<JsonArray>();
|
||||||
|
for (uint8_t i = 0; i < 16; i++) {
|
||||||
|
if (_telemetry.isOverloaded(i)) overloaded.add(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
return CommandResult::ok("telemetry.get_loads", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult TelemetryHandler::handleSetMaxLoads(const CommandEnvelope& e) {
|
||||||
|
// Accepts either: { "all": 500 } OR { "loads": { "0": 300, "3": 700 } }
|
||||||
|
if (e.contents["all"].is<uint16_t>()) {
|
||||||
|
uint16_t val = e.contents["all"].as<uint16_t>();
|
||||||
|
if (val == 0) return CommandResult::err("telemetry.set_max_loads", "max_load must be > 0");
|
||||||
|
for (uint8_t i = 0; i < 16; i++) _telemetry.setBellMaxLoad(i, val);
|
||||||
|
LOG_INFO(TAG, "All bell max loads set to %u", val);
|
||||||
|
return CommandResult::ok("telemetry.set_max_loads", "All bell max loads updated");
|
||||||
|
}
|
||||||
|
if (e.contents["loads"].is<JsonObject>()) {
|
||||||
|
JsonObjectConst loads = e.contents["loads"].as<JsonObjectConst>();
|
||||||
|
for (JsonPairConst kv : loads) {
|
||||||
|
uint8_t idx = (uint8_t)String(kv.key().c_str()).toInt();
|
||||||
|
uint16_t val = kv.value().as<uint16_t>();
|
||||||
|
if (idx < 16 && val > 0) _telemetry.setBellMaxLoad(idx, val);
|
||||||
|
}
|
||||||
|
return CommandResult::ok("telemetry.set_max_loads", "Bell max loads updated");
|
||||||
|
}
|
||||||
|
return CommandResult::err("telemetry.set_max_loads", "Provide 'all' (uint16) or 'loads' (object)");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult TelemetryHandler::handleSetGuardEnabled(const CommandEnvelope& e) {
|
||||||
|
if (!e.contents["enabled"].is<bool>()) {
|
||||||
|
return CommandResult::err("telemetry.set_guard_enabled", "Missing required field: enabled (bool)");
|
||||||
|
}
|
||||||
|
bool enabled = e.contents["enabled"].as<bool>();
|
||||||
|
_telemetry.setGuardEnabled(enabled);
|
||||||
|
LOG_WARNING(TAG, "Bell guard %s by command", enabled ? "enabled" : "disabled");
|
||||||
|
return CommandResult::ok("telemetry.set_guard_enabled",
|
||||||
|
String("Bell guard ") + (enabled ? "enabled" : "disabled"));
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult TelemetryHandler::handleGetMetrics(const CommandEnvelope& e) {
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["lifetime_runtime_seconds"] = _telemetry.getLifetimeRuntimeSeconds();
|
||||||
|
doc["session_runtime_seconds"] = _telemetry.getCurrentSessionSeconds();
|
||||||
|
doc["total_playbacks"] = _telemetry.getTotalPlaybackCount();
|
||||||
|
doc["guard_enabled"] = _telemetry.isGuardEnabled();
|
||||||
|
doc["lifetime_boot_count"] = _telemetry.getLifetimeBootCount();
|
||||||
|
return CommandResult::ok("telemetry.get_metrics", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult TelemetryHandler::handleResetMetrics(const CommandEnvelope& e) {
|
||||||
|
_telemetry.resetMetrics();
|
||||||
|
LOG_WARNING(TAG, "Telemetry metrics reset by command");
|
||||||
|
return CommandResult::ok("telemetry.reset_metrics", "Lifetime runtime and playback count reset to zero");
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult TelemetryHandler::handleGetBootHistory(const CommandEnvelope& e) {
|
||||||
|
// Optional "limit" — defaults to the full 200-entry cap. Clamped to
|
||||||
|
// [1, BOOT_LOG_MAX_ENTRIES] so a bad value can't return zero entries
|
||||||
|
// or force reading past what's actually stored.
|
||||||
|
uint16_t limit = BOOT_LOG_MAX_ENTRIES;
|
||||||
|
if (e.contents["limit"].is<uint16_t>()) {
|
||||||
|
uint16_t requested = e.contents["limit"].as<uint16_t>();
|
||||||
|
limit = (requested == 0) ? 1 : (requested > BOOT_LOG_MAX_ENTRIES ? BOOT_LOG_MAX_ENTRIES : requested);
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonDocument doc;
|
||||||
|
if (!_telemetry.getBootHistory(doc, limit)) {
|
||||||
|
return CommandResult::err("telemetry.get_boot_history",
|
||||||
|
"No boot history available (no SD card, or no boot has completed NTP sync yet)");
|
||||||
|
}
|
||||||
|
return CommandResult::ok("telemetry.get_boot_history", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult TelemetryHandler::handleGetDiagnostics(const CommandEnvelope& e) {
|
||||||
|
// On-demand mirror of CommunicationRouter::reportDiagnosticsIfDue()'s
|
||||||
|
// periodic diagnostics_report — same fields, same shape. Deliberately
|
||||||
|
// does NOT reset the temperature accumulator (unlike the periodic
|
||||||
|
// report) — this is a peek, not a consuming read, so the next scheduled
|
||||||
|
// 5-minute report still sees the full sampling window.
|
||||||
|
JsonDocument doc;
|
||||||
|
|
||||||
|
_telemetry.writeTemperatureStats(doc);
|
||||||
|
|
||||||
|
JsonObject wifiObj = doc["wifi_reconnects"].to<JsonObject>();
|
||||||
|
wifiObj["lifetime_count"] = _networking.getReconnectCount();
|
||||||
|
wifiObj["last_reason"] = _networking.getLastDisconnectReason();
|
||||||
|
wifiObj["last_at_uptime_ms"] = _networking.getLastDisconnectUptimeMs();
|
||||||
|
|
||||||
|
JsonObject otaObj = doc["ota"].to<JsonObject>();
|
||||||
|
otaObj["current_version"] = _otaManager.getCurrentVersion().toString();
|
||||||
|
otaObj["update_available"] = _otaManager.isUpdateAvailable();
|
||||||
|
if (_otaManager.isUpdateAvailable()) {
|
||||||
|
otaObj["available_version"] = _otaManager.getAvailableVersion().toString();
|
||||||
|
}
|
||||||
|
otaObj["last_check_uptime_ms"] = _otaManager.getLastCheckUptimeMs();
|
||||||
|
otaObj["last_error"] = OTAManager::errorCodeToString(_otaManager.getLastError());
|
||||||
|
|
||||||
|
JsonObject stackObj = doc["stack_high_water"].to<JsonObject>();
|
||||||
|
Telemetry::writeStackHighWaterMarks(stackObj);
|
||||||
|
|
||||||
|
return CommandResult::ok("telemetry.get_diagnostics", doc);
|
||||||
|
}
|
||||||
|
|
||||||
|
CommandResult TelemetryHandler::handleResetBootData(const CommandEnvelope& e) {
|
||||||
|
// Zeroes the lifetime boot counter (NVS) and deletes the SD boot history
|
||||||
|
// log — used before shipping a device to a customer, to clear reboot
|
||||||
|
// counts accumulated during QA/bench testing. Console-side history in
|
||||||
|
// device_boot_events (Postgres) is a separate reset, not touched here.
|
||||||
|
bool ok = _telemetry.resetBootData();
|
||||||
|
if (!ok) {
|
||||||
|
return CommandResult::err("telemetry.reset_boot_data",
|
||||||
|
"Failed to reset lifetime boot count in NVS");
|
||||||
|
}
|
||||||
|
LOG_WARNING(TAG, "Boot data reset via telemetry.reset_boot_data command");
|
||||||
|
return CommandResult::ok("telemetry.reset_boot_data", "Lifetime boot count and SD boot log reset");
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
#include "../ICommandHandler.hpp"
|
||||||
|
|
||||||
|
class Telemetry;
|
||||||
|
class OTAManager;
|
||||||
|
class Networking;
|
||||||
|
|
||||||
|
class TelemetryHandler : public ICommandHandler {
|
||||||
|
public:
|
||||||
|
// otaManager/networking are needed only for telemetry.get_diagnostics —
|
||||||
|
// the on-demand mirror of CommunicationRouter's periodic diagnostics_report.
|
||||||
|
TelemetryHandler(Telemetry& telemetry, OTAManager& otaManager, Networking& networking);
|
||||||
|
|
||||||
|
std::vector<String> commands() const override;
|
||||||
|
CommandResult execute(const CommandEnvelope& envelope) override;
|
||||||
|
|
||||||
|
private:
|
||||||
|
Telemetry& _telemetry;
|
||||||
|
OTAManager& _otaManager;
|
||||||
|
Networking& _networking;
|
||||||
|
|
||||||
|
CommandResult handleGetStrikes(const CommandEnvelope& e);
|
||||||
|
CommandResult handleResetStrikes(const CommandEnvelope& e);
|
||||||
|
CommandResult handleGetLoads(const CommandEnvelope& e);
|
||||||
|
CommandResult handleSetMaxLoads(const CommandEnvelope& e);
|
||||||
|
CommandResult handleSetGuardEnabled(const CommandEnvelope& e);
|
||||||
|
CommandResult handleGetMetrics(const CommandEnvelope& e);
|
||||||
|
CommandResult handleResetMetrics(const CommandEnvelope& e);
|
||||||
|
CommandResult handleGetBootHistory(const CommandEnvelope& e);
|
||||||
|
CommandResult handleGetDiagnostics(const CommandEnvelope& e);
|
||||||
|
CommandResult handleResetBootData(const CommandEnvelope& e);
|
||||||
|
};
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
# ResponseBuilder
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
`ResponseBuilder` is a legacy utility class that serialises responses to JSON strings for direct transmission. It predates the `CommandResult` / `CommandBus` architecture and was the primary response-building mechanism before the Stage 4 comms refactor. Its role has shrunk significantly: new handler code uses `CommandResult` factory methods, and transports serialise `CommandResult` inline. `ResponseBuilder` is still used by `WebSocketDriver` (welcome message on connect, parse error responses) and by some older code paths. It is not on the critical command-dispatch path for any handler. New code should use `CommandResult` instead.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Public API
|
||||||
|
|
||||||
|
### Bridge method (preferred for integrating with CommandBus)
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `static String fromResult(const CommandResult& result)` | Serialises a `CommandResult` to the standard wire JSON format. Used to convert `CommandResult` objects when a pre-serialised string is needed outside the transport dispatch path. |
|
||||||
|
|
||||||
|
### Generic builders
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `static String success(const String& type, const String& payload = "")` | `{ "status": "SUCCESS", "type": ..., "payload": ... }` |
|
||||||
|
| `static String success(const String& type, const JsonObject& payload)` | Success with a JSON object payload. |
|
||||||
|
| `static String error(const String& type, const String& message)` | `{ "status": "ERROR", "type": ..., "payload": ... }` |
|
||||||
|
| `static String status(const String& type, const JsonObject& data)` | Alias for `success` with JSON data. |
|
||||||
|
| `static String status(const String& type, const String& data)` | Alias for `success` with string data. |
|
||||||
|
| `static String buildResponse(Status, const String& type, const String& payload)` | Low-level builder. Reuses a static `StaticJsonDocument<512>`. |
|
||||||
|
| `static String buildResponse(Status, const String& type, const JsonObject& payload)` | Low-level builder with JSON payload. |
|
||||||
|
|
||||||
|
### Specialised builders
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `static String acknowledgment(const String& commandType)` | `success(type, "Command acknowledged")` |
|
||||||
|
| `static String pong()` | `success("pong", "")` |
|
||||||
|
| `static String deviceStatus(PlayerStatus, uint32_t elapsed, uint64_t projected, const uint32_t counters[16])` | Serialises full player status. Uses a `DynamicJsonDocument<1024>`. |
|
||||||
|
| `static String melodyList(const String& fileListJson)` | Wraps a pre-serialised file list. |
|
||||||
|
| `static String downloadResult(bool success, const String& filename)` | Download success/failure response. |
|
||||||
|
| `static String configUpdate(const String& configType)` | Generic config-saved acknowledgment. |
|
||||||
|
|
||||||
|
### Error builders
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `static String invalidCommand(const String& command)` | `error("invalid_command", "Unknown command: ...")` |
|
||||||
|
| `static String missingParameter(const String& parameter)` | `error("missing_parameter", "Required parameter missing: ...")` |
|
||||||
|
| `static String operationFailed(const String& operation, const String& reason)` | `error(operation, "... failed: ...")` |
|
||||||
|
| `static String deviceBusy()` | `error("device_busy", "Device is currently busy, try again later")` |
|
||||||
|
| `static String unauthorized()` | `error("unauthorized", "Operation not authorized for this client")` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Response Format
|
||||||
|
|
||||||
|
`buildResponse()` produces:
|
||||||
|
```json
|
||||||
|
{ "status": "SUCCESS|ERROR|INFO", "type": "command_type", "payload": "..." }
|
||||||
|
```
|
||||||
|
|
||||||
|
`fromResult()` produces:
|
||||||
|
```json
|
||||||
|
{ "status": "SUCCESS|ERROR|INFO", "type": "command_type", "message": "...", "data": { ... } }
|
||||||
|
```
|
||||||
|
|
||||||
|
Note: `buildResponse` uses the key `"payload"` while `fromResult` and all transport reply lambdas use `"message"` and `"data"`. These two formats are not identical. Prefer `fromResult` / `CommandResult` for consistency with the transport layer.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Initialization
|
||||||
|
|
||||||
|
No initialization required. All methods are static. The static member `_responseDoc` is zero-initialised.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
- `CommandResult` — used by `fromResult()`
|
||||||
|
- `Player` — `PlayerStatus` enum used by `deviceStatus()`
|
||||||
|
- `ArduinoJson`, `Logging`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Gotchas / Notes
|
||||||
|
|
||||||
|
- **`_responseDoc` is a shared static.** `buildResponse()` calls `_responseDoc.clear()` before use, but if two calls interleave (e.g. from an ISR or concurrent task), the shared document will be corrupted. All current callers are on the main loop / AsyncWebServer callback thread, so this is not currently a problem. Do not call `ResponseBuilder` methods from FreeRTOS tasks.
|
||||||
|
- **`buildResponse` vs `fromResult` key mismatch.** `buildResponse` uses `"payload"` as the JSON key; `fromResult` (and all transport reply lambdas) use `"message"`. Mixing these in a single client will require handling both keys. Prefer `CommandResult` + transport serialisation for all new code.
|
||||||
|
- **`deviceStatus()` uses `DynamicJsonDocument<1024>`.** This is a heap allocation per call. All other methods use the static `_responseDoc`. For high-frequency status polling, this is a notable allocation hotspot.
|
||||||
|
- **Prefer `CommandResult` for new handlers.** `ResponseBuilder` is retained for backward compatibility with `WebSocketDriver` and any code that needs a pre-serialised string before the bus is involved. For all command handler responses, use `CommandResult::ok()`, `CommandResult::err()`, or `CommandResult::info()`.
|
||||||
+32
-7
@@ -1,8 +1,27 @@
|
|||||||
#include "ResponseBuilder.hpp"
|
#include "ResponseBuilder.hpp"
|
||||||
|
#include "../CommandBus/CommandResult.hpp"
|
||||||
|
|
||||||
|
#define TAG "ResponseBuilder"
|
||||||
#include "../../Logging/Logging.hpp"
|
#include "../../Logging/Logging.hpp"
|
||||||
|
|
||||||
|
String ResponseBuilder::fromResult(const CommandResult& result) {
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["status"] = result.isOk() ? "SUCCESS"
|
||||||
|
: (result.status == CommandResult::Status::INFO ? "INFO" : "ERROR");
|
||||||
|
doc["type"] = result.type;
|
||||||
|
if (!result.payload.isEmpty()) {
|
||||||
|
doc["message"] = result.payload;
|
||||||
|
}
|
||||||
|
if (result.hasData) {
|
||||||
|
doc["data"] = result.data;
|
||||||
|
}
|
||||||
|
String out;
|
||||||
|
serializeJson(doc, out);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
// Static member initialization
|
// Static member initialization
|
||||||
StaticJsonDocument<512> ResponseBuilder::_responseDoc;
|
JsonDocument ResponseBuilder::_responseDoc;
|
||||||
|
|
||||||
String ResponseBuilder::success(const String& type, const String& payload) {
|
String ResponseBuilder::success(const String& type, const String& payload) {
|
||||||
return buildResponse(Status::SUCCESS, type, payload);
|
return buildResponse(Status::SUCCESS, type, payload);
|
||||||
@@ -32,14 +51,14 @@ String ResponseBuilder::pong() {
|
|||||||
return success("pong", "");
|
return success("pong", "");
|
||||||
}
|
}
|
||||||
|
|
||||||
String ResponseBuilder::deviceStatus(PlayerStatus playerStatus, uint32_t timeElapsed, uint64_t projectedRunTime) {
|
String ResponseBuilder::deviceStatus(PlayerStatus playerStatus, uint32_t timeElapsed, uint64_t projectedRunTime, const uint32_t strikeCounters[16]) {
|
||||||
StaticJsonDocument<512> statusDoc; // Increased size for additional data
|
JsonDocument statusDoc;
|
||||||
|
|
||||||
statusDoc["status"] = "SUCCESS";
|
statusDoc["status"] = "SUCCESS";
|
||||||
statusDoc["type"] = "current_status";
|
statusDoc["type"] = "current_status";
|
||||||
|
|
||||||
// Create payload object with the exact format expected by Flutter
|
// 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
|
// Convert PlayerStatus to string
|
||||||
const char* statusStr;
|
const char* statusStr;
|
||||||
@@ -63,10 +82,16 @@ String ResponseBuilder::deviceStatus(PlayerStatus playerStatus, uint32_t timeEla
|
|||||||
payload["time_elapsed"] = timeElapsed; // in milliseconds
|
payload["time_elapsed"] = timeElapsed; // in milliseconds
|
||||||
payload["projected_run_time"] = projectedRunTime; // NEW: total projected duration
|
payload["projected_run_time"] = projectedRunTime; // NEW: total projected duration
|
||||||
|
|
||||||
|
// Add strike counters array
|
||||||
|
JsonArray strikeCountersArray = payload["strike_counters"].to<JsonArray>();
|
||||||
|
for (uint8_t i = 0; i < 16; i++) {
|
||||||
|
strikeCountersArray.add(strikeCounters[i]);
|
||||||
|
}
|
||||||
|
|
||||||
String result;
|
String result;
|
||||||
serializeJson(statusDoc, result);
|
serializeJson(statusDoc, result);
|
||||||
|
|
||||||
LOG_DEBUG("Device status response: %s", result.c_str());
|
LOG_DEBUG(TAG, "Device status response: %s", result.c_str());
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -129,7 +154,7 @@ String ResponseBuilder::buildResponse(Status status, const String& type, const S
|
|||||||
String result;
|
String result;
|
||||||
serializeJson(_responseDoc, result);
|
serializeJson(_responseDoc, result);
|
||||||
|
|
||||||
LOG_DEBUG("Response built: %s", result.c_str());
|
LOG_DEBUG(TAG, "Response built: %s", result.c_str());
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,7 +168,7 @@ String ResponseBuilder::buildResponse(Status status, const String& type, const J
|
|||||||
String result;
|
String result;
|
||||||
serializeJson(_responseDoc, result);
|
serializeJson(_responseDoc, result);
|
||||||
|
|
||||||
LOG_DEBUG("Response built: %s", result.c_str());
|
LOG_DEBUG(TAG, "Response built: %s", result.c_str());
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
+9
-2
@@ -45,6 +45,9 @@
|
|||||||
#include <ArduinoJson.h>
|
#include <ArduinoJson.h>
|
||||||
#include "../../Player/Player.hpp" // For PlayerStatus enum
|
#include "../../Player/Player.hpp" // For PlayerStatus enum
|
||||||
|
|
||||||
|
// Forward declaration — CommandResult.hpp is included in the .cpp only
|
||||||
|
struct CommandResult;
|
||||||
|
|
||||||
class ResponseBuilder {
|
class ResponseBuilder {
|
||||||
public:
|
public:
|
||||||
// Response status types
|
// Response status types
|
||||||
@@ -54,6 +57,10 @@ public:
|
|||||||
INFO
|
INFO
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Factory: serialise a CommandResult into a ready-to-send JSON string.
|
||||||
|
// Produces the same {"status","type","message"/"data"} envelope used everywhere.
|
||||||
|
static String fromResult(const CommandResult& result);
|
||||||
|
|
||||||
// Main response builders
|
// Main response builders
|
||||||
static String success(const String& type, const String& payload = "");
|
static String success(const String& type, const String& payload = "");
|
||||||
static String success(const String& type, const JsonObject& payload);
|
static String success(const String& type, const JsonObject& payload);
|
||||||
@@ -64,7 +71,7 @@ public:
|
|||||||
// Specialized response builders for common scenarios
|
// Specialized response builders for common scenarios
|
||||||
static String acknowledgment(const String& commandType);
|
static String acknowledgment(const String& commandType);
|
||||||
static String pong();
|
static String pong();
|
||||||
static String deviceStatus(PlayerStatus playerStatus, uint32_t timeElapsedMs, uint64_t projectedRunTime = 0);
|
static String deviceStatus(PlayerStatus playerStatus, uint32_t timeElapsedMs, uint64_t projectedRunTime, const uint32_t strikeCounters[16]);
|
||||||
static String melodyList(const String& fileListJson);
|
static String melodyList(const String& fileListJson);
|
||||||
static String downloadResult(bool success, const String& filename = "");
|
static String downloadResult(bool success, const String& filename = "");
|
||||||
static String configUpdate(const String& configType);
|
static String configUpdate(const String& configType);
|
||||||
@@ -83,5 +90,5 @@ public:
|
|||||||
private:
|
private:
|
||||||
// Internal helper methods
|
// Internal helper methods
|
||||||
static const char* statusToString(Status status);
|
static const char* statusToString(Status status);
|
||||||
static StaticJsonDocument<512> _responseDoc; // Reusable document for efficiency
|
static JsonDocument _responseDoc; // Reusable document for efficiency
|
||||||
};
|
};
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
#include "HTTPTransport.hpp"
|
||||||
|
#include "../../CommandBus/CommandBus.hpp"
|
||||||
|
#include "../../CommandBus/CommandEnvelope.hpp"
|
||||||
|
#include "../../CommandBus/CommandResult.hpp"
|
||||||
|
#include "../../CommandBus/LegacyResponseAdapter.hpp"
|
||||||
|
#include "../../../ConfigManager/ConfigManager.hpp"
|
||||||
|
|
||||||
|
#define TAG "HTTPTransport"
|
||||||
|
#include "../../../Logging/Logging.hpp"
|
||||||
|
|
||||||
|
HTTPTransport::HTTPTransport(AsyncWebServer& server, CommandBus& bus, ConfigManager& configManager)
|
||||||
|
: _server(server)
|
||||||
|
, _bus(bus)
|
||||||
|
, _configManager(configManager) {
|
||||||
|
}
|
||||||
|
|
||||||
|
void HTTPTransport::begin() {
|
||||||
|
// POST /api/command — execute any command
|
||||||
|
_server.on("/api/command", HTTP_POST,
|
||||||
|
// Called when body-less POST completes (shouldn't happen, but guard it)
|
||||||
|
[](AsyncWebServerRequest* request) {
|
||||||
|
request->send(400, "application/json",
|
||||||
|
R"({"status":"ERROR","type":"bad_request","message":"Body required"})");
|
||||||
|
},
|
||||||
|
nullptr, // no upload handler
|
||||||
|
[this](AsyncWebServerRequest* request, uint8_t* data, size_t len,
|
||||||
|
size_t index, size_t total) {
|
||||||
|
// Wait for full body before processing
|
||||||
|
if (index + len == total) {
|
||||||
|
handleCommandRequest(request, data, len);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// GET /api/ping — lightweight health check
|
||||||
|
_server.on("/api/ping", HTTP_GET,
|
||||||
|
[this](AsyncWebServerRequest* request) {
|
||||||
|
handlePingRequest(request);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// GET /api/status — convenience shortcut for system.status
|
||||||
|
_server.on("/api/status", HTTP_GET,
|
||||||
|
[this](AsyncWebServerRequest* request) {
|
||||||
|
handleStatusRequest(request);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// CORS headers for browser clients
|
||||||
|
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*");
|
||||||
|
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
||||||
|
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Headers", "Content-Type");
|
||||||
|
|
||||||
|
_initialised = true;
|
||||||
|
LOG_INFO(TAG, "HTTPTransport initialised — POST /api/command, GET /api/ping, GET /api/status");
|
||||||
|
}
|
||||||
|
|
||||||
|
void HTTPTransport::loop() {
|
||||||
|
// AsyncWebServer is fully event-driven; nothing to poll.
|
||||||
|
}
|
||||||
|
|
||||||
|
bool HTTPTransport::isHealthy() const {
|
||||||
|
return _initialised;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
void HTTPTransport::handleCommandRequest(AsyncWebServerRequest* request,
|
||||||
|
uint8_t* data, size_t len) {
|
||||||
|
JsonDocument doc;
|
||||||
|
DeserializationError err = deserializeJson(doc, data, len);
|
||||||
|
if (err) {
|
||||||
|
LOG_WARNING(TAG, "JSON parse error: %s", err.c_str());
|
||||||
|
sendErrorJson(request, 400, "Invalid JSON");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char* cmd = doc["cmd"] | "";
|
||||||
|
if (cmd[0] == '\0') {
|
||||||
|
sendErrorJson(request, 400, "Missing 'cmd' field");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
LOG_DEBUG(TAG, "HTTP CMD: %s", cmd);
|
||||||
|
|
||||||
|
CommandEnvelope envelope;
|
||||||
|
envelope.transport = CommandEnvelope::Transport::HTTP;
|
||||||
|
envelope.origin = CommandEnvelope::Origin::APP;
|
||||||
|
envelope.clientId = 0;
|
||||||
|
envelope.command = cmd;
|
||||||
|
envelope.version = doc["v"] | 2;
|
||||||
|
|
||||||
|
if (doc["contents"].is<JsonVariant>()) {
|
||||||
|
envelope.contents.set(doc["contents"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Capture the ORIGINAL version before CommandBus::dispatch() rewrites
|
||||||
|
// envelope.version to 2 post-translation (see LegacyAdapter.hpp). HTTP
|
||||||
|
// defaults unversioned requests to v2 (unlike WS/MQTT/UART, which default
|
||||||
|
// to v1) — this only fires for a caller that explicitly sends "v":1.
|
||||||
|
bool isLegacyRequest = (envelope.version == 1);
|
||||||
|
|
||||||
|
// Capture request pointer. The reply lambda must call request->send() exactly once.
|
||||||
|
// AsyncWebServer keeps the request alive until we call send() or the connection closes.
|
||||||
|
envelope.reply = [this, request, isLegacyRequest](const CommandResult& result) {
|
||||||
|
JsonDocument resp;
|
||||||
|
if (!isLegacyRequest || !translateLegacyResponse(result, resp)) {
|
||||||
|
resp["status"] = result.isOk() ? "SUCCESS"
|
||||||
|
: (result.status == CommandResult::Status::INFO ? "INFO" : "ERROR");
|
||||||
|
resp["type"] = result.type;
|
||||||
|
if (!result.payload.isEmpty()) {
|
||||||
|
resp["message"] = result.payload;
|
||||||
|
}
|
||||||
|
if (result.hasData) {
|
||||||
|
resp["data"] = result.data;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
String out;
|
||||||
|
serializeJson(resp, out);
|
||||||
|
sendJsonResponse(request, 200, out);
|
||||||
|
};
|
||||||
|
|
||||||
|
_bus.dispatch(envelope);
|
||||||
|
}
|
||||||
|
|
||||||
|
void HTTPTransport::handlePingRequest(AsyncWebServerRequest* request) {
|
||||||
|
LOG_DEBUG(TAG, "Ping request");
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["status"] = "SUCCESS";
|
||||||
|
doc["type"] = "pong";
|
||||||
|
doc["uptime"] = millis();
|
||||||
|
String out;
|
||||||
|
serializeJson(doc, out);
|
||||||
|
sendJsonResponse(request, 200, out);
|
||||||
|
}
|
||||||
|
|
||||||
|
void HTTPTransport::handleStatusRequest(AsyncWebServerRequest* request) {
|
||||||
|
LOG_DEBUG(TAG, "Status shortcut — dispatching system.status");
|
||||||
|
|
||||||
|
CommandEnvelope envelope;
|
||||||
|
envelope.transport = CommandEnvelope::Transport::HTTP;
|
||||||
|
envelope.origin = CommandEnvelope::Origin::APP;
|
||||||
|
envelope.clientId = 0;
|
||||||
|
envelope.command = "system.status";
|
||||||
|
envelope.version = 2;
|
||||||
|
|
||||||
|
envelope.reply = [this, request](const CommandResult& result) {
|
||||||
|
JsonDocument resp;
|
||||||
|
resp["status"] = result.isOk() ? "SUCCESS" : "ERROR";
|
||||||
|
resp["type"] = result.type;
|
||||||
|
if (!result.payload.isEmpty()) {
|
||||||
|
resp["message"] = result.payload;
|
||||||
|
}
|
||||||
|
if (result.hasData) {
|
||||||
|
resp["data"] = result.data;
|
||||||
|
}
|
||||||
|
String out;
|
||||||
|
serializeJson(resp, out);
|
||||||
|
sendJsonResponse(request, 200, out);
|
||||||
|
};
|
||||||
|
|
||||||
|
_bus.dispatch(envelope);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
void HTTPTransport::sendJsonResponse(AsyncWebServerRequest* request,
|
||||||
|
int code, const String& json) {
|
||||||
|
request->send(code, "application/json", json);
|
||||||
|
}
|
||||||
|
|
||||||
|
void HTTPTransport::sendErrorJson(AsyncWebServerRequest* request,
|
||||||
|
int code, const String& message) {
|
||||||
|
JsonDocument doc;
|
||||||
|
doc["status"] = "ERROR";
|
||||||
|
doc["type"] = "bad_request";
|
||||||
|
doc["message"] = message;
|
||||||
|
String out;
|
||||||
|
serializeJson(doc, out);
|
||||||
|
sendJsonResponse(request, code, out);
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <ESPAsyncWebServer.h>
|
||||||
|
#include "../ITransport.hpp"
|
||||||
|
|
||||||
|
class CommandBus;
|
||||||
|
class ConfigManager;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// HTTPTransport
|
||||||
|
//
|
||||||
|
// ITransport implementation for HTTP — replaces HTTPRequestHandler.
|
||||||
|
//
|
||||||
|
// HTTP is now a proper first-class transport with its own identity.
|
||||||
|
// No more 0xFFFFFFFF fake WebSocket client ID.
|
||||||
|
//
|
||||||
|
// Endpoints registered:
|
||||||
|
// POST /api/command — execute any command via CommandBus
|
||||||
|
// GET /api/ping — health check (no bus involvement)
|
||||||
|
// GET /api/status — shortcut: dispatches system.status to the bus
|
||||||
|
//
|
||||||
|
// broadcast() is a no-op (HTTP is stateless; no persistent connection to push to).
|
||||||
|
//
|
||||||
|
// The reply lambda captures the AsyncWebServerRequest* and sends the HTTP
|
||||||
|
// response directly — the bus and handlers never see the HTTP layer.
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class HTTPTransport : public ITransport {
|
||||||
|
public:
|
||||||
|
HTTPTransport(AsyncWebServer& server, CommandBus& bus, ConfigManager& configManager);
|
||||||
|
|
||||||
|
void begin() override;
|
||||||
|
void loop() override; // no-op — AsyncWebServer is event-driven
|
||||||
|
bool isHealthy() const override;
|
||||||
|
String name() const override { return "HTTP"; }
|
||||||
|
|
||||||
|
// No persistent connections — broadcast is a no-op.
|
||||||
|
void broadcast(const String& message) override {}
|
||||||
|
|
||||||
|
private:
|
||||||
|
AsyncWebServer& _server;
|
||||||
|
CommandBus& _bus;
|
||||||
|
ConfigManager& _configManager;
|
||||||
|
bool _initialised = false;
|
||||||
|
|
||||||
|
// Endpoint handlers
|
||||||
|
void handleCommandRequest(AsyncWebServerRequest* request, uint8_t* data, size_t len);
|
||||||
|
void handlePingRequest(AsyncWebServerRequest* request);
|
||||||
|
void handleStatusRequest(AsyncWebServerRequest* request);
|
||||||
|
|
||||||
|
void sendJsonResponse(AsyncWebServerRequest* request, int code, const String& json);
|
||||||
|
void sendErrorJson(AsyncWebServerRequest* request, int code, const String& message);
|
||||||
|
};
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
# HTTPTransport
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
`HTTPTransport` exposes a minimal REST API over HTTP that routes commands through the `CommandBus`. It registers three endpoints on the `AsyncWebServer`: `POST /api/command` accepts any v2 command in JSON, `GET /api/ping` is a lightweight health check that bypasses the bus entirely, and `GET /api/status` is a convenience shortcut that dispatches `system.status` and returns the result. HTTP is stateless — there are no persistent connections — so `broadcast()` is a no-op. Each request's reply lambda captures the `AsyncWebServerRequest*` pointer and sends the HTTP response when the handler returns.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Public API
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `HTTPTransport(AsyncWebServer& server, CommandBus& bus, ConfigManager& configManager)` | Constructor. Does not register routes yet. |
|
||||||
|
| `void begin()` | Registers all HTTP routes and sets global CORS headers (`Access-Control-Allow-Origin: *`). Sets `_initialised = true`. |
|
||||||
|
| `void loop()` | No-op. AsyncWebServer is event-driven. |
|
||||||
|
| `bool isHealthy() const` | Returns `_initialised`. True once `begin()` has been called. |
|
||||||
|
| `String name() const` | Returns `"HTTP"`. |
|
||||||
|
| `void broadcast(const String&)` | No-op. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Endpoints
|
||||||
|
|
||||||
|
| Method | Path | Description |
|
||||||
|
|--------|------|-------------|
|
||||||
|
| `POST` | `/api/command` | Execute any command. Body must be JSON with at least a `"cmd"` field. |
|
||||||
|
| `GET` | `/api/ping` | Returns `{ "status": "SUCCESS", "type": "pong", "uptime": <ms> }`. No bus involvement. |
|
||||||
|
| `GET` | `/api/status` | Dispatches `system.status` and returns the result. |
|
||||||
|
|
||||||
|
### POST /api/command
|
||||||
|
|
||||||
|
Request body:
|
||||||
|
```json
|
||||||
|
{ "v": 2, "cmd": "relay.get_config", "contents": {} }
|
||||||
|
```
|
||||||
|
|
||||||
|
Response (success):
|
||||||
|
```json
|
||||||
|
{ "status": "SUCCESS", "type": "relay.get_config", "data": { ... } }
|
||||||
|
```
|
||||||
|
|
||||||
|
Response (error):
|
||||||
|
```json
|
||||||
|
{ "status": "ERROR", "type": "relay.set_durations", "message": "Missing or invalid 'bells' object" }
|
||||||
|
```
|
||||||
|
|
||||||
|
HTTP status code is always `200` for dispatched commands (even errors — the error is in the JSON body). HTTP `400` is returned only for malformed requests (bad JSON, missing `"cmd"`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Initialization
|
||||||
|
|
||||||
|
`CommunicationRouter::begin()` calls `_httpTransport.begin()`, then adds the transport to the bus with `_bus.addTransport(&_httpTransport)`. The underlying `AsyncWebServer` is started separately by `main.cpp` in the network-connected callback.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
- `AsyncWebServer` (ESPAsyncWebServer) — route registration and request handling
|
||||||
|
- `CommandBus` — dispatch
|
||||||
|
- `ConfigManager` — held as a reference (available for future auth/rate-limiting)
|
||||||
|
- `ArduinoJson`, `Logging`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Gotchas / Notes
|
||||||
|
|
||||||
|
- **CORS is global.** `DefaultHeaders::Instance().addHeader(...)` applies to all responses served by the `AsyncWebServer`, not just HTTP transport routes. Any other handler sharing the same server will also emit these headers.
|
||||||
|
- **Body must arrive complete.** The body callback only processes the message when `index + len == total`, i.e. when the full body has been received. Partial delivery (chunked transfer, slow clients) will be ignored until the final chunk.
|
||||||
|
- **HTTP status is always 200 for dispatched commands.** Error results from handlers still return HTTP 200. Callers must inspect `"status"` in the JSON body. Only truly malformed requests (no body, bad JSON, missing `"cmd"`) return 4xx.
|
||||||
|
- **No authentication.** Any client that can reach the device on port 80 can issue any command. This is intentional for the local-network deployment context.
|
||||||
|
- **`broadcast()` is a no-op.** HTTP has no persistent connection. The transport is registered with the bus so that `broadcast()` calls don't crash, but no data is sent.
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include "../CommandBus/CommandResult.hpp"
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// ITransport
|
||||||
|
//
|
||||||
|
// Interface every transport layer implements.
|
||||||
|
//
|
||||||
|
// Transports are responsible for:
|
||||||
|
// 1. Receiving raw input from their protocol (MQTT, WebSocket, HTTP, UART)
|
||||||
|
// 2. Parsing it into a CommandEnvelope
|
||||||
|
// 3. Injecting a reply lambda that routes the response back correctly
|
||||||
|
// 4. Calling CommandBus::dispatch()
|
||||||
|
//
|
||||||
|
// The CommandBus never knows which transport originated a command.
|
||||||
|
// The transport never knows what a handler does with it.
|
||||||
|
//
|
||||||
|
// broadcast() is used by CommunicationRouter to push unsolicited events
|
||||||
|
// (telemetry, bell strikes, status changes) to all connected clients of
|
||||||
|
// this transport.
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class ITransport {
|
||||||
|
public:
|
||||||
|
virtual ~ITransport() = default;
|
||||||
|
|
||||||
|
// Initialise the transport (called once from CommunicationRouter::begin())
|
||||||
|
virtual void begin() = 0;
|
||||||
|
|
||||||
|
// Service the transport's event loop (called from CommunicationRouter::loop())
|
||||||
|
virtual void loop() = 0;
|
||||||
|
|
||||||
|
// Health check used by HealthMonitor / CommunicationRouter::isHealthy()
|
||||||
|
virtual bool isHealthy() const = 0;
|
||||||
|
|
||||||
|
// Human-readable name for logging (e.g. "MQTT", "WebSocket", "HTTP", "UART")
|
||||||
|
virtual String name() const = 0;
|
||||||
|
|
||||||
|
// Push a pre-serialised JSON string to all clients of this transport.
|
||||||
|
// For connection-less transports (HTTP, UART) this is a no-op.
|
||||||
|
virtual void broadcast(const String& message) = 0;
|
||||||
|
};
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
#include "MQTTTransport.hpp"
|
||||||
|
#include "../../CommandBus/CommandBus.hpp"
|
||||||
|
#include "../../CommandBus/CommandEnvelope.hpp"
|
||||||
|
#include "../../CommandBus/CommandResult.hpp"
|
||||||
|
#include "../../CommandBus/LegacyResponseAdapter.hpp"
|
||||||
|
|
||||||
|
#define TAG "MQTTTransport"
|
||||||
|
#include "../../../Logging/Logging.hpp"
|
||||||
|
|
||||||
|
MQTTTransport::MQTTTransport(MQTTDriver& mqttClient, CommandBus& bus)
|
||||||
|
: _mqtt(mqttClient)
|
||||||
|
, _bus(bus) {
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTTransport::begin() {
|
||||||
|
// Wire up the message callback — any message arriving on the control topic
|
||||||
|
// is routed through here.
|
||||||
|
_mqtt.setCallback([this](const String& topic, const String& payload) {
|
||||||
|
onMessage(topic, payload);
|
||||||
|
});
|
||||||
|
|
||||||
|
_mqtt.begin();
|
||||||
|
LOG_INFO(TAG, "MQTTTransport initialised");
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTTransport::loop() {
|
||||||
|
// AsyncMqttClient drives itself; nothing to poll here.
|
||||||
|
}
|
||||||
|
|
||||||
|
bool MQTTTransport::isHealthy() const {
|
||||||
|
return _mqtt.isConnected();
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTTransport::broadcast(const String& message) {
|
||||||
|
// Unsolicited bus-wide broadcasts (e.g. CommandBus::broadcast()) go out on
|
||||||
|
// control/ack alongside command replies — control/ack is the only outbound
|
||||||
|
// channel this transport owns for arbitrary CommandResult-shaped messages.
|
||||||
|
// Purpose-specific events (playback transitions, alerts, reports) are
|
||||||
|
// published directly by CommunicationRouter to their own dedicated topics
|
||||||
|
// instead of going through this path.
|
||||||
|
_mqtt.publishAck(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTTransport::onNetworkConnected() {
|
||||||
|
_mqtt.onNetworkConnected();
|
||||||
|
}
|
||||||
|
|
||||||
|
void MQTTTransport::onNetworkDisconnected() {
|
||||||
|
_mqtt.onNetworkDisconnected();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
void MQTTTransport::onMessage(const String& topic, const String& payload) {
|
||||||
|
// Skip entirely under critical heap pressure — deserializing, dispatching, and
|
||||||
|
// replying all allocate, and this runs inline on AsyncTCP's own task. Letting a
|
||||||
|
// burst of incoming commands compound an already-low-heap condition is what led
|
||||||
|
// to an unrecoverable abort() in production (this SDK build can't even throw
|
||||||
|
// std::bad_alloc when allocation fails — see MQTTDriver::hasHeapForPublish()).
|
||||||
|
if (!_mqtt.hasHeapForPublish()) return;
|
||||||
|
|
||||||
|
LOG_DEBUG(TAG, "RX [%s]: %s", topic.c_str(), payload.c_str());
|
||||||
|
|
||||||
|
JsonDocument doc;
|
||||||
|
DeserializationError err = deserializeJson(doc, payload);
|
||||||
|
if (err) {
|
||||||
|
LOG_WARNING(TAG, "JSON parse error: %s — replying with error", err.c_str());
|
||||||
|
// Can't recover a req_id from unparseable JSON — the reply necessarily
|
||||||
|
// has none. Still worth an ack: a caller waiting on a timeout gets an
|
||||||
|
// immediate, actionable "malformed" instead of silence indistinguishable
|
||||||
|
// from a lost network message.
|
||||||
|
JsonDocument resp;
|
||||||
|
resp["status"] = "ERROR";
|
||||||
|
resp["type"] = "parse_error";
|
||||||
|
resp["message"] = String("Invalid JSON: ") + err.c_str();
|
||||||
|
String out;
|
||||||
|
serializeJson(resp, out);
|
||||||
|
_mqtt.publishAck(out);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build the envelope
|
||||||
|
CommandEnvelope envelope;
|
||||||
|
envelope.transport = CommandEnvelope::Transport::MQTT;
|
||||||
|
envelope.origin = CommandEnvelope::Origin::APP;
|
||||||
|
envelope.clientId = 0;
|
||||||
|
envelope.command = doc["cmd"].as<String>();
|
||||||
|
envelope.version = doc["v"] | 1;
|
||||||
|
|
||||||
|
// req_id is optional (see CommandEnvelope.hpp) — a v1 client, or any caller
|
||||||
|
// not fanning requests out over a shared channel, simply omits it and gets
|
||||||
|
// a reply with no req_id field, same as before this was added.
|
||||||
|
if (doc.containsKey("req_id")) {
|
||||||
|
envelope.reqId = doc["req_id"].as<String>();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (doc.containsKey("contents")) {
|
||||||
|
envelope.contents.set(doc["contents"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (envelope.command.isEmpty()) {
|
||||||
|
LOG_WARNING(TAG, "MQTT message missing 'cmd' field — replying with error");
|
||||||
|
JsonDocument resp;
|
||||||
|
resp["status"] = "ERROR";
|
||||||
|
resp["type"] = "parse_error";
|
||||||
|
resp["message"] = "Missing required field: cmd";
|
||||||
|
if (!envelope.reqId.isEmpty()) {
|
||||||
|
resp["req_id"] = envelope.reqId;
|
||||||
|
}
|
||||||
|
String out;
|
||||||
|
serializeJson(resp, out);
|
||||||
|
_mqtt.publishAck(out);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Capture the ORIGINAL version before CommandBus::dispatch() rewrites
|
||||||
|
// envelope.version to 2 post-translation (see LegacyAdapter.hpp).
|
||||||
|
bool isLegacyRequest = (envelope.version == 1);
|
||||||
|
|
||||||
|
// Reply lambda — publishes the response back to control/ack
|
||||||
|
envelope.reply = [this, isLegacyRequest](const CommandResult& result) {
|
||||||
|
JsonDocument resp;
|
||||||
|
if (!isLegacyRequest || !translateLegacyResponse(result, resp)) {
|
||||||
|
resp["status"] = result.isOk() ? "SUCCESS"
|
||||||
|
: (result.status == CommandResult::Status::INFO ? "INFO" : "ERROR");
|
||||||
|
resp["type"] = result.type;
|
||||||
|
if (!result.payload.isEmpty()) {
|
||||||
|
resp["message"] = result.payload;
|
||||||
|
}
|
||||||
|
if (result.hasData) {
|
||||||
|
resp["data"] = result.data;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Always echo req_id on the outer envelope, even for legacy-translated
|
||||||
|
// replies — translateLegacyResponse() only rewrites the v1-known shape,
|
||||||
|
// it doesn't know about req_id, and legacy clients simply ignore the
|
||||||
|
// extra field.
|
||||||
|
if (!result.reqId.isEmpty()) {
|
||||||
|
resp["req_id"] = result.reqId;
|
||||||
|
}
|
||||||
|
String out;
|
||||||
|
serializeJson(resp, out);
|
||||||
|
_mqtt.publishAck(out);
|
||||||
|
};
|
||||||
|
|
||||||
|
_bus.dispatch(envelope);
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include "../ITransport.hpp"
|
||||||
|
#include "../../Drivers/MQTTDriver/MQTTDriver.hpp"
|
||||||
|
|
||||||
|
class CommandBus;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// MQTTTransport
|
||||||
|
//
|
||||||
|
// ITransport wrapper around the existing MQTTDriver.
|
||||||
|
//
|
||||||
|
// Responsibilities:
|
||||||
|
// - Delegates connection lifecycle to MQTTDriver
|
||||||
|
// - Subscribes to control/command, parses incoming JSON into CommandEnvelopes
|
||||||
|
// (extracting the optional req_id for correlation — see CommandEnvelope.hpp)
|
||||||
|
// - Injects a reply lambda that publishes the response to control/ack
|
||||||
|
// - Dispatches to the CommandBus
|
||||||
|
// - broadcast() publishes to control/ack (bus-wide unsolicited events only —
|
||||||
|
// purpose-specific events like playback/alerts/reports go directly through
|
||||||
|
// CommunicationRouter to their own topics, not through this path)
|
||||||
|
//
|
||||||
|
// The underlying MQTTDriver (and its timers, heartbeat, reconnect logic)
|
||||||
|
// is unchanged — this transport just owns the bus glue.
|
||||||
|
// See docs/reference/vesper_mqtt_topic_spec_v2.md for the full topic table.
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class MQTTTransport : public ITransport {
|
||||||
|
public:
|
||||||
|
MQTTTransport(MQTTDriver& mqttClient, CommandBus& bus);
|
||||||
|
|
||||||
|
void begin() override;
|
||||||
|
void loop() override; // no-op — AsyncMqttClient is fully async
|
||||||
|
bool isHealthy() const override;
|
||||||
|
String name() const override { return "MQTT"; }
|
||||||
|
|
||||||
|
// Publish a pre-serialised JSON string to control/ack.
|
||||||
|
// Called by CommandBus::broadcast() for unsolicited events.
|
||||||
|
void broadcast(const String& message) override;
|
||||||
|
|
||||||
|
// Called by CommunicationRouter when the network connects / disconnects
|
||||||
|
void onNetworkConnected();
|
||||||
|
void onNetworkDisconnected();
|
||||||
|
|
||||||
|
private:
|
||||||
|
MQTTDriver& _mqtt;
|
||||||
|
CommandBus& _bus;
|
||||||
|
|
||||||
|
// Invoked by MQTTDriver's message callback
|
||||||
|
void onMessage(const String& topic, const String& payload);
|
||||||
|
};
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
# MQTTTransport
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
`MQTTTransport` wraps `MQTTDriver` and connects it to the `CommandBus`. It subscribes to `control/command`, parses incoming JSON messages into `CommandEnvelope` objects (including the optional `req_id`), and dispatches them. Command replies are published back to `control/ack`. Bus-wide unsolicited broadcasts also go through `broadcast()` to `control/ack` — but purpose-specific events (playback transitions, alerts, reports, metrics) are published directly by `CommunicationRouter` to their own dedicated topics instead, so `control/ack` stays strictly request/response. The underlying `MQTTDriver` manages the broker connection lifecycle, reconnect backoff, LWT, and heartbeat independently; `MQTTTransport` only owns the message-routing glue.
|
||||||
|
|
||||||
|
See [docs/reference/vesper_mqtt_topic_spec_v2.md](../../../../docs/reference/vesper_mqtt_topic_spec_v2.md) for the full topic table.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Public API
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `MQTTTransport(MQTTDriver& mqtt, CommandBus& bus)` | Constructor. Does not start the connection. |
|
||||||
|
| `void begin()` | Wires the message callback onto `MQTTDriver`, then calls `MQTTDriver::begin()` to configure the AsyncMqttClient. Does not connect to the broker — connection is triggered by `onNetworkConnected()`. |
|
||||||
|
| `void loop()` | No-op. AsyncMqttClient is fully event-driven. |
|
||||||
|
| `bool isHealthy() const` | Returns `MQTTDriver::isConnected()`. |
|
||||||
|
| `String name() const` | Returns `"MQTT"`. |
|
||||||
|
| `void broadcast(const String& msg)` | Publishes `msg` to `control/ack` (bus-wide broadcasts only — see summary above). |
|
||||||
|
| `void onNetworkConnected()` | Forwards to `MQTTDriver::onNetworkConnected()`, which schedules the broker connection after a 2-second stabilisation delay. |
|
||||||
|
| `void onNetworkDisconnected()` | Forwards to `MQTTDriver::onNetworkDisconnected()`. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Initialization
|
||||||
|
|
||||||
|
`CommunicationRouter::begin()` calls `_mqttTransport.begin()`, then adds the transport to the bus with `_bus.addTransport(&_mqttTransport)`. Network events from `Networking` arrive via `CommunicationRouter::onNetworkConnected()` / `onNetworkDisconnected()`, which forward to this transport.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Message Format
|
||||||
|
|
||||||
|
Incoming control messages (on `control/command`) must be JSON with at least a `"cmd"` field:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "v": 2, "cmd": "relay.set_durations", "req_id": "abc123", "contents": { "bells": { "0": 500 } } }
|
||||||
|
```
|
||||||
|
|
||||||
|
`"v"` defaults to `2` if omitted. `"v": 1` triggers legacy translation before dispatch. `"req_id"` is optional — see `CommandEnvelope.hpp` / `docs/reference/vesper_mqtt_topic_spec_v2.md` for the correlation contract.
|
||||||
|
|
||||||
|
Responses are published to `control/ack`:
|
||||||
|
```json
|
||||||
|
{ "status": "SUCCESS", "type": "relay.set_durations", "req_id": "abc123", "message": "Bell durations updated and saved" }
|
||||||
|
```
|
||||||
|
|
||||||
|
`req_id` is only present in the reply if the request included one.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
- `MQTTDriver` — broker connection, publish/subscribe, reconnect, heartbeat
|
||||||
|
- `CommandBus` — dispatch and broadcast
|
||||||
|
- `ArduinoJson`, `Logging`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Gotchas / Notes
|
||||||
|
|
||||||
|
- **`control/ack` is strictly request/response plus bus-wide broadcasts — never purpose-specific events.** The broker does not distinguish a command reply from a `CommandBus::broadcast()` fan-out; clients must inspect `"type"` and `"status"` to differentiate. But playback transitions, alerts, reports, and metrics never appear here — those go to their own topics via `CommunicationRouter` (`publishPlayback()`, `publishAlert()`, `publishReport()`, `publishMetrics()`), bypassing this transport entirely.
|
||||||
|
- **Broker connection is deferred.** `begin()` does not connect. The connection is triggered by `onNetworkConnected()`, which starts a 2-second non-blocking stabilisation timer in `MQTTDriver`.
|
||||||
|
- **MQTT must be enabled in config, and the `command` topic switch must be on.** `MQTTDriver::connect()` is a no-op if `mqttConfig.enabled` is false. Toggle the master switch with `mqtt.enable` / `mqtt.disable`. Independently, the `command` topic switch (via `mqtt.set_topics`) gates the `control/command` subscription and `control/ack` replies — turning it off while MQTT stays connected silently stops all command traffic.
|
||||||
|
- **No per-message QoS.** Command replies and broadcasts are published at QoS 1 (matching the topic table). Heartbeats use QoS 1 with `retain = true`.
|
||||||
|
- **JSON parse errors and missing `cmd` get an `ERROR` reply on `control/ack`** (`type: "parse_error"`), not a silent drop — a `LOG_WARNING` is still emitted too. A parse-error reply necessarily has no `req_id` (it can't be read from input that failed to parse); a missing-`cmd` reply echoes `req_id` if the JSON was otherwise valid and included one.
|
||||||
|
- **Incoming commands are dropped under critical heap pressure.** `onMessage()` checks `MQTTDriver::hasHeapForPublish()` (free heap ≥ 20KB) before even constructing the `JsonDocument` used to deserialize the incoming payload. Below that threshold, the message is dropped with no reply and no error response — indistinguishable from a lost network message to the caller. This exists because a rapid burst of commands (each involving deserialize + dispatch + reply, all allocation-heavy, all running inline on AsyncTCP's own task) previously fragmented the heap enough to crash the device with an unrecoverable `abort()` — see `docs/features/feature-catalog.md` F-055. A full fix (queueing incoming commands to a dedicated task, so this work never runs on AsyncTCP's task at all) is a scoped future improvement, not yet implemented.
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# Transport Layer
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
The Transport layer adapts five communication protocols — MQTT, WebSocket, HTTP, UART, and the settings web server — to a common interface consumed by the `CommandBus`. Each transport is responsible for receiving raw input from its protocol, parsing it into a `CommandEnvelope`, injecting a reply lambda that routes the response back over the same protocol, and calling `CommandBus::dispatch()`. For unsolicited events, the bus calls each transport's `broadcast()` method. Transports have no knowledge of what handlers do; handlers have no knowledge of which transport a command arrived on. The transport identity is recorded in `CommandEnvelope::transport` for the rare cases where a handler needs it (e.g. `identify` is WebSocket-only).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ITransport Interface
|
||||||
|
|
||||||
|
All transports implement `ITransport`:
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `virtual void begin() = 0` | Initialise the transport. Called once from `CommunicationRouter::begin()`. |
|
||||||
|
| `virtual void loop() = 0` | Service the event loop. No-op for event-driven transports; required for UART polling. |
|
||||||
|
| `virtual bool isHealthy() const = 0` | Health check used by `HealthMonitor` / `CommunicationRouter::isHealthy()`. |
|
||||||
|
| `virtual String name() const = 0` | Human-readable name for logging (e.g. `"MQTT"`, `"WebSocket"`). |
|
||||||
|
| `virtual void broadcast(const String& msg) = 0` | Push a pre-serialised JSON string to all clients. No-op for stateless transports (HTTP, WebServerTransport). |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Transports at a Glance
|
||||||
|
|
||||||
|
| Transport | Protocol | Endpoint / Topic | Persistent connection | Broadcast |
|
||||||
|
|-----------|----------|------------------|-----------------------|-----------|
|
||||||
|
| `MQTTTransport` | MQTT (AsyncMqttClient) | `vesper/{uid}/control` (RX), `vesper/{uid}/data` (TX) | Yes (broker) | Yes — publishes to data topic |
|
||||||
|
| `WebSocketTransport` | WebSocket | `/ws` | Yes (per client) | Yes — all or targeted clients |
|
||||||
|
| `HTTPTransport` | HTTP REST | `POST /api/command`, `GET /api/ping`, `GET /api/status` | No | No-op |
|
||||||
|
| `UARTTransport` | UART (Serial2) | GPIO 12 TX / 13 RX @ 115200 | Yes (slave device) | Yes — sends to UART slave |
|
||||||
|
| `WebServerTransport` | HTTP (settings UI) | `GET /settings`, `POST /api/set-mode`, `POST /api/reboot` | No | No-op |
|
||||||
|
|
||||||
|
See the subdirectory README for each transport for details.
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
# UARTTransport
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
`UARTTransport` wraps `UARTDriver` and connects it to the `CommandBus` for the UART slave interface (LCD panel / button board on Serial2). Unlike other transports, UART requires polling — `loop()` must be called each iteration of the Arduino main loop. A command whitelist is enforced before dispatch: only five commands are allowed from the UART slave. All other commands are silently dropped. This prevents a compromised or misbehaving slave from issuing sensitive commands (factory reset, OTA update, etc.). Replies are sent back over UART as newline-delimited JSON.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Public API
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `UARTTransport(UARTDriver& uart, CommandBus& bus)` | Constructor. |
|
||||||
|
| `void begin()` | Wires the message callback onto `UARTDriver`, then calls `UARTDriver::begin()` to initialise Serial2. |
|
||||||
|
| `void loop()` | Calls `UARTDriver::loop()` to poll for incoming bytes. **Must be called from the Arduino main loop.** |
|
||||||
|
| `bool isHealthy() const` | Returns `UARTDriver::isReady()`. |
|
||||||
|
| `String name() const` | Returns `"UART"`. |
|
||||||
|
| `void broadcast(const String& msg)` | Sends a JSON string to the UART slave (newline appended by `UARTDriver::send()`). |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Command Whitelist
|
||||||
|
|
||||||
|
Only the following commands are accepted from the UART slave:
|
||||||
|
|
||||||
|
| Command | Purpose |
|
||||||
|
|---------|---------|
|
||||||
|
| `ping` | Connection check |
|
||||||
|
| `playback` | Play / stop from physical buttons |
|
||||||
|
| `clock.pause` | Button-triggered clock pause |
|
||||||
|
| `clock.resume` | Button-triggered clock resume |
|
||||||
|
| `system.get_time` | LCD requests current time (pull model, replaces old push) |
|
||||||
|
|
||||||
|
Any command not in this list is dropped with a `LOG_WARNING` and the client receives no response.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Initialization
|
||||||
|
|
||||||
|
`CommunicationRouter::begin()` calls `_uartTransport.begin()`, then adds the transport to the bus. `CommunicationRouter::loop()` calls `_uartTransport.loop()`, which is the only mandatory polling call in the system.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Wire Protocol
|
||||||
|
|
||||||
|
Messages are newline-delimited JSON on Serial2 (TX: GPIO 12, RX: GPIO 13, 115200 baud):
|
||||||
|
|
||||||
|
```
|
||||||
|
{ "v": 2, "cmd": "playback", "contents": { ... } }\n
|
||||||
|
```
|
||||||
|
|
||||||
|
Responses are sent back immediately after dispatch:
|
||||||
|
```
|
||||||
|
{ "status": "SUCCESS", "type": "playback", "message": "Playback command executed" }\n
|
||||||
|
```
|
||||||
|
|
||||||
|
JSON parse errors on the slave side generate an error response:
|
||||||
|
```
|
||||||
|
{ "status": "ERROR", "type": "parse_error", "payload": "<ArduinoJson error string>" }\n
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
- `UARTDriver` — Serial2 I/O, line buffering, JSON parsing
|
||||||
|
- `CommandBus` — dispatch
|
||||||
|
- `ArduinoJson`, `Logging`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Gotchas / Notes
|
||||||
|
|
||||||
|
- **`loop()` must be called.** Without it, no UART messages are processed. `CommunicationRouter::loop()` handles this for you.
|
||||||
|
- **Whitelist is enforced before the bus.** Dropped commands produce a `LOG_WARNING` but no response to the slave. If the slave is polling for a response that never arrives, it will time out. Design slave firmware accordingly.
|
||||||
|
- **Buffer overflow drops the message.** `UARTDriver` has a 1024-byte receive buffer. Messages longer than this are discarded and `_errorCount` is incremented.
|
||||||
|
- **Blocking flush.** `UARTDriver::send()` calls `Serial.flush()` after each response, which blocks until the UART TX buffer drains. At 115200 baud this is typically under 1 ms for short responses.
|
||||||
|
- **No v1 translation for UART.** In practice the UART slave sends v2 commands, but `CommandBus::dispatch()` will still translate v1 envelopes if `"v": 1` is set.
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
#include "UARTTransport.hpp"
|
||||||
|
#include "../../CommandBus/CommandBus.hpp"
|
||||||
|
#include "../../CommandBus/CommandEnvelope.hpp"
|
||||||
|
#include "../../CommandBus/CommandResult.hpp"
|
||||||
|
|
||||||
|
#define TAG "UARTTransport"
|
||||||
|
#include "../../../Logging/Logging.hpp"
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Whitelist
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
const char* const UARTTransport::WHITELIST[] = {
|
||||||
|
"ping",
|
||||||
|
"playback",
|
||||||
|
"clock.pause",
|
||||||
|
"clock.resume",
|
||||||
|
"system.get_time",
|
||||||
|
};
|
||||||
|
|
||||||
|
const size_t UARTTransport::WHITELIST_SIZE =
|
||||||
|
sizeof(UARTTransport::WHITELIST) / sizeof(UARTTransport::WHITELIST[0]);
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
UARTTransport::UARTTransport(UARTDriver& uart, CommandBus& bus)
|
||||||
|
: _uart(uart)
|
||||||
|
, _bus(bus) {
|
||||||
|
}
|
||||||
|
|
||||||
|
void UARTTransport::begin() {
|
||||||
|
_uart.setCallback([this](JsonDocument& doc) {
|
||||||
|
onMessage(doc);
|
||||||
|
});
|
||||||
|
|
||||||
|
_uart.begin();
|
||||||
|
LOG_INFO(TAG, "UARTTransport initialised (whitelist: %u commands)", WHITELIST_SIZE);
|
||||||
|
}
|
||||||
|
|
||||||
|
void UARTTransport::loop() {
|
||||||
|
_uart.loop();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool UARTTransport::isHealthy() const {
|
||||||
|
return _uart.isReady();
|
||||||
|
}
|
||||||
|
|
||||||
|
void UARTTransport::broadcast(const String& message) {
|
||||||
|
_uart.send(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
bool UARTTransport::isWhitelisted(const String& command) const {
|
||||||
|
for (size_t i = 0; i < WHITELIST_SIZE; ++i) {
|
||||||
|
if (command == WHITELIST[i]) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void UARTTransport::onMessage(JsonDocument& doc) {
|
||||||
|
const char* cmd = doc["cmd"] | "";
|
||||||
|
if (cmd[0] == '\0') {
|
||||||
|
LOG_WARNING(TAG, "UART message missing 'cmd' field — dropping");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isWhitelisted(cmd)) {
|
||||||
|
LOG_WARNING(TAG, "UART command '%s' not whitelisted — silently dropped", cmd);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
LOG_DEBUG(TAG, "UART CMD (whitelisted): %s", cmd);
|
||||||
|
|
||||||
|
CommandEnvelope envelope;
|
||||||
|
envelope.transport = CommandEnvelope::Transport::UART;
|
||||||
|
envelope.origin = CommandEnvelope::Origin::BUTTON; // UART peer is the LCD/button slave board
|
||||||
|
envelope.clientId = 0;
|
||||||
|
envelope.command = cmd;
|
||||||
|
envelope.version = doc["v"] | 1;
|
||||||
|
|
||||||
|
if (doc.containsKey("contents")) {
|
||||||
|
envelope.contents.set(doc["contents"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reply routes back over UART to the slave
|
||||||
|
envelope.reply = [this](const CommandResult& result) {
|
||||||
|
JsonDocument resp;
|
||||||
|
resp["status"] = result.isOk() ? "SUCCESS"
|
||||||
|
: (result.status == CommandResult::Status::INFO ? "INFO" : "ERROR");
|
||||||
|
resp["type"] = result.type;
|
||||||
|
if (!result.payload.isEmpty()) {
|
||||||
|
resp["message"] = result.payload;
|
||||||
|
}
|
||||||
|
if (result.hasData) {
|
||||||
|
resp["data"] = result.data;
|
||||||
|
}
|
||||||
|
String out;
|
||||||
|
serializeJson(resp, out);
|
||||||
|
_uart.send(out);
|
||||||
|
};
|
||||||
|
|
||||||
|
_bus.dispatch(envelope);
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include "../ITransport.hpp"
|
||||||
|
#include "../../Drivers/UARTDriver/UARTDriver.hpp"
|
||||||
|
|
||||||
|
class CommandBus;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// UARTTransport
|
||||||
|
//
|
||||||
|
// ITransport wrapper around the existing UARTDriver.
|
||||||
|
//
|
||||||
|
// The UART port talks to a slave LCD/button board. Only a small whitelist of
|
||||||
|
// commands are accepted from this transport to prevent feedback loops and
|
||||||
|
// stop a compromised slave from issuing sensitive commands.
|
||||||
|
//
|
||||||
|
// Whitelist (v2 — see Communication-Refactor-Plan.md):
|
||||||
|
// ping — connection check
|
||||||
|
// playback — play/stop from physical buttons
|
||||||
|
// clock.pause — button-triggered pause
|
||||||
|
// clock.resume — button-triggered resume
|
||||||
|
// system.get_time — LCD requests current time (replaces old push model)
|
||||||
|
//
|
||||||
|
// All other commands are silently dropped before they reach the bus.
|
||||||
|
//
|
||||||
|
// broadcast() sends to the UART slave (unsolicited events / telemetry).
|
||||||
|
// For connection-less context this is optional; the slave may ignore messages
|
||||||
|
// it doesn't request.
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class UARTTransport : public ITransport {
|
||||||
|
public:
|
||||||
|
UARTTransport(UARTDriver& uart, CommandBus& bus);
|
||||||
|
|
||||||
|
void begin() override;
|
||||||
|
void loop() override; // polls UARTDriver::loop()
|
||||||
|
bool isHealthy() const override;
|
||||||
|
String name() const override { return "UART"; }
|
||||||
|
|
||||||
|
// Send a serialised JSON string to the UART slave (newline appended by handler).
|
||||||
|
void broadcast(const String& message) override;
|
||||||
|
|
||||||
|
private:
|
||||||
|
UARTDriver& _uart;
|
||||||
|
CommandBus& _bus;
|
||||||
|
|
||||||
|
// Commands the UART slave is allowed to issue
|
||||||
|
static const char* const WHITELIST[];
|
||||||
|
static const size_t WHITELIST_SIZE;
|
||||||
|
|
||||||
|
bool isWhitelisted(const String& command) const;
|
||||||
|
|
||||||
|
// Invoked by UARTDriver's message callback
|
||||||
|
void onMessage(JsonDocument& doc);
|
||||||
|
};
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
# WebServerTransport
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
`WebServerTransport` absorbs the old `SettingsWebServer` subsystem into the transport layer (Stage 6 of the comms refactor). It serves an on-board network configuration page at `GET /settings` and routes two form actions through the `CommandBus`: `POST /api/set-mode` (AP/station toggle via `network.set_config`) and `POST /api/reboot` (device restart via `system.restart`). By routing through the bus, the settings UI benefits from the same validation and persistence logic as every other client. Like `HTTPTransport`, it has no persistent connections, so `broadcast()` is a no-op.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Public API
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `WebServerTransport(AsyncWebServer&, CommandBus&, ConfigManager&, Networking&)` | Constructor. |
|
||||||
|
| `void begin()` | Registers the three HTTP routes. Sets `_initialised = true`. |
|
||||||
|
| `void loop()` | No-op. AsyncWebServer is event-driven. |
|
||||||
|
| `bool isHealthy() const` | Returns `_initialised`. |
|
||||||
|
| `String name() const` | Returns `"WebServer"`. |
|
||||||
|
| `void broadcast(const String&)` | No-op. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Endpoints
|
||||||
|
|
||||||
|
| Method | Path | Description |
|
||||||
|
|--------|------|-------------|
|
||||||
|
| `GET` | `/settings` | Serves the network settings HTML page with current values substituted. |
|
||||||
|
| `POST` | `/api/set-mode` | Accepts form parameter `mode=ap` or `mode=station`. Dispatches `network.set_config`, then reboots the device on success. |
|
||||||
|
| `POST` | `/api/reboot` | Dispatches `system.restart`. Sends a plain-text ack to the browser before the handler fires. |
|
||||||
|
|
||||||
|
### Settings Page Template Variables
|
||||||
|
|
||||||
|
The HTML template (`SettingsWebServer/SettingsPage.h`) uses the following substitution tokens:
|
||||||
|
|
||||||
|
| Token | Source |
|
||||||
|
|-------|--------|
|
||||||
|
| `%MODE_BADGE_CLASS%` | `networking.isInAPMode()` → `"ap"` or `"station"` |
|
||||||
|
| `%MODE_TEXT%` | `"AP Mode"` or `"Station Mode"` |
|
||||||
|
| `%CURRENT_IP%` | `networking.getLocalIP()` |
|
||||||
|
| `%DEVICE_UID%` | `configManager.getDeviceUID()` |
|
||||||
|
| `%FW_VERSION%` | `configManager.getFwVersion()` |
|
||||||
|
| `%AP_ACTIVE_CLASS%` | `"active"` if in AP mode |
|
||||||
|
| `%STATION_ACTIVE_CLASS%` | `"active"` if in station mode |
|
||||||
|
| `%SELECTED_MODE%` | `"ap"` or `"station"` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Initialization
|
||||||
|
|
||||||
|
`CommunicationRouter::begin()` calls `_webServerTransport.begin()` and adds it to the bus. The underlying `AsyncWebServer` is started by `main.cpp` in the network-connected callback.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
- `AsyncWebServer` (ESPAsyncWebServer)
|
||||||
|
- `CommandBus` — dispatches `network.set_config` and `system.restart`
|
||||||
|
- `ConfigManager` — supplies device UID, firmware version, and current network config
|
||||||
|
- `Networking` — supplies current IP and AP mode state
|
||||||
|
- `SettingsWebServer/SettingsPage.h` — HTML template (PROGMEM string `SETTINGS_PAGE_HTML`)
|
||||||
|
- `ArduinoJson`, `Logging`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Gotchas / Notes
|
||||||
|
|
||||||
|
- **AP mode change triggers a hard reboot.** The reply lambda for `POST /api/set-mode` calls `delay(3000)` followed by `ESP.restart()` on success. This is intentional — network mode changes require a full reboot to take effect. Any in-flight WebSocket connections or MQTT sessions will be dropped without notice.
|
||||||
|
- **Reboot ack is sent before the handler.** For `POST /api/reboot`, `request->send()` is called before dispatching to the bus. The `system.restart` handler schedules a 2-second delayed task reboot. The browser receives the ack and the device reboots shortly after.
|
||||||
|
- **HTML template is in PROGMEM.** `SETTINGS_PAGE_HTML` is stored in flash, not RAM. `String(FPSTR(...))` copies it to heap. On low-memory devices this allocation (~2 KB) can fail — watch heap at `/api/ping`.
|
||||||
|
- **`broadcast()` is a no-op.** This transport has no active client connections to push to.
|
||||||
|
- **Shared server with HTTPTransport.** Both transports register routes on the same `AsyncWebServer`. Route prefixes (`/settings`, `/api/set-mode`, `/api/reboot`) must not conflict with those registered by `HTTPTransport` (`/api/command`, `/api/ping`, `/api/status`).
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
#include "WebServerTransport.hpp"
|
||||||
|
#include "../../CommandBus/CommandBus.hpp"
|
||||||
|
#include "../../CommandBus/CommandEnvelope.hpp"
|
||||||
|
#include "../../CommandBus/CommandResult.hpp"
|
||||||
|
#include "../../../ConfigManager/ConfigManager.hpp"
|
||||||
|
#include "../../../Networking/Networking.hpp"
|
||||||
|
|
||||||
|
#define TAG "WebServerTransport"
|
||||||
|
#include "../../../Logging/Logging.hpp"
|
||||||
|
|
||||||
|
// HTML template lives alongside the old SettingsWebServer — include from there
|
||||||
|
// until the old directory is deleted.
|
||||||
|
#include "../../../SettingsWebServer/SettingsPage.h"
|
||||||
|
|
||||||
|
WebServerTransport::WebServerTransport(AsyncWebServer& server,
|
||||||
|
CommandBus& bus,
|
||||||
|
ConfigManager& configManager,
|
||||||
|
Networking& networking)
|
||||||
|
: _server(server)
|
||||||
|
, _bus(bus)
|
||||||
|
, _configManager(configManager)
|
||||||
|
, _networking(networking) {
|
||||||
|
}
|
||||||
|
|
||||||
|
void WebServerTransport::begin() {
|
||||||
|
// GET /settings — HTML settings page
|
||||||
|
_server.on("/settings", HTTP_GET,
|
||||||
|
[this](AsyncWebServerRequest* request) {
|
||||||
|
handleSettingsPage(request);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// POST /api/set-mode — AP / station toggle
|
||||||
|
_server.on("/api/set-mode", HTTP_POST,
|
||||||
|
[this](AsyncWebServerRequest* request) {
|
||||||
|
handleSetMode(request);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// POST /api/reboot — restart via CommandBus (system.restart)
|
||||||
|
_server.on("/api/reboot", HTTP_POST,
|
||||||
|
[this](AsyncWebServerRequest* request) {
|
||||||
|
handleReboot(request);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
_initialised = true;
|
||||||
|
LOG_INFO(TAG, "WebServerTransport initialised");
|
||||||
|
LOG_INFO(TAG, " GET /settings - Settings page");
|
||||||
|
LOG_INFO(TAG, " POST /api/set-mode - AP/station toggle");
|
||||||
|
LOG_INFO(TAG, " POST /api/reboot - Device restart");
|
||||||
|
}
|
||||||
|
|
||||||
|
void WebServerTransport::loop() {
|
||||||
|
// AsyncWebServer is fully event-driven; nothing to poll.
|
||||||
|
}
|
||||||
|
|
||||||
|
bool WebServerTransport::isHealthy() const {
|
||||||
|
return _initialised;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Endpoint handlers
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
void WebServerTransport::handleSettingsPage(AsyncWebServerRequest* request) {
|
||||||
|
LOG_DEBUG(TAG, "Settings page requested");
|
||||||
|
request->send(200, "text/html", generateSettingsHTML());
|
||||||
|
}
|
||||||
|
|
||||||
|
void WebServerTransport::handleSetMode(AsyncWebServerRequest* request) {
|
||||||
|
if (!request->hasParam("mode", true)) {
|
||||||
|
request->send(400, "text/plain", "Missing mode parameter");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String mode = request->getParam("mode", true)->value();
|
||||||
|
LOG_INFO(TAG, "Mode change requested via web: %s", mode.c_str());
|
||||||
|
|
||||||
|
if (mode != "ap" && mode != "station") {
|
||||||
|
request->send(400, "text/plain", "Invalid mode. Use 'ap' or 'station'");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool apMode = (mode == "ap");
|
||||||
|
|
||||||
|
// Route through CommandBus: network.set_config with permanent_ap_mode field.
|
||||||
|
CommandEnvelope envelope;
|
||||||
|
envelope.transport = CommandEnvelope::Transport::HTTP;
|
||||||
|
envelope.origin = CommandEnvelope::Origin::APP;
|
||||||
|
envelope.clientId = 0;
|
||||||
|
envelope.command = "network.set_config";
|
||||||
|
envelope.version = 2;
|
||||||
|
envelope.contents["permanent_ap_mode"] = apMode;
|
||||||
|
|
||||||
|
// The reply lambda sends the HTTP response, then triggers a restart.
|
||||||
|
// We capture by value to be safe (request pointer stays valid until send()).
|
||||||
|
envelope.reply = [request, apMode](const CommandResult& result) {
|
||||||
|
if (result.isOk()) {
|
||||||
|
String msg = apMode
|
||||||
|
? "AP mode enabled. Device will reboot in 3 seconds."
|
||||||
|
: "Station mode enabled. Device will reboot in 3 seconds.";
|
||||||
|
request->send(200, "text/plain", msg);
|
||||||
|
delay(3000);
|
||||||
|
ESP.restart();
|
||||||
|
} else {
|
||||||
|
request->send(500, "text/plain",
|
||||||
|
String("Failed to set mode: ") + result.payload);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
_bus.dispatch(envelope);
|
||||||
|
}
|
||||||
|
|
||||||
|
void WebServerTransport::handleReboot(AsyncWebServerRequest* request) {
|
||||||
|
LOG_INFO(TAG, "Reboot requested via web");
|
||||||
|
|
||||||
|
CommandEnvelope envelope;
|
||||||
|
envelope.transport = CommandEnvelope::Transport::HTTP;
|
||||||
|
envelope.origin = CommandEnvelope::Origin::APP;
|
||||||
|
envelope.clientId = 0;
|
||||||
|
envelope.command = "system.restart";
|
||||||
|
envelope.version = 2;
|
||||||
|
|
||||||
|
// system.restart sends its own response and then reboots.
|
||||||
|
// For the web client we send a simple text ack before the handler fires.
|
||||||
|
request->send(200, "text/plain", "Rebooting device in 2 seconds...");
|
||||||
|
|
||||||
|
envelope.reply = [](const CommandResult&) {
|
||||||
|
// Response already sent above; restart is handled by SystemHandler.
|
||||||
|
};
|
||||||
|
|
||||||
|
_bus.dispatch(envelope);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// HTML generation
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
String WebServerTransport::generateSettingsHTML() {
|
||||||
|
bool isAPMode = _networking.isInAPMode();
|
||||||
|
String currentIP = _networking.getLocalIP();
|
||||||
|
String deviceUID = _configManager.getDeviceUID();
|
||||||
|
String fwVersion = _configManager.getFwVersion();
|
||||||
|
|
||||||
|
String html = String(FPSTR(SETTINGS_PAGE_HTML));
|
||||||
|
|
||||||
|
html.replace("%MODE_BADGE_CLASS%", isAPMode ? "ap" : "station");
|
||||||
|
html.replace("%MODE_TEXT%", isAPMode ? "AP Mode" : "Station Mode");
|
||||||
|
html.replace("%CURRENT_IP%", currentIP);
|
||||||
|
html.replace("%DEVICE_UID%", deviceUID);
|
||||||
|
html.replace("%FW_VERSION%", fwVersion);
|
||||||
|
html.replace("%AP_ACTIVE_CLASS%", isAPMode ? "active" : "");
|
||||||
|
html.replace("%STATION_ACTIVE_CLASS%", !isAPMode ? "active" : "");
|
||||||
|
html.replace("%SELECTED_MODE%", isAPMode ? "ap" : "station");
|
||||||
|
|
||||||
|
return html;
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <ESPAsyncWebServer.h>
|
||||||
|
#include "../ITransport.hpp"
|
||||||
|
|
||||||
|
class CommandBus;
|
||||||
|
class ConfigManager;
|
||||||
|
class Networking;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// WebServerTransport
|
||||||
|
//
|
||||||
|
// ITransport implementation for the on-board settings web interface.
|
||||||
|
// Absorbs SettingsWebServer — Stage 6 of the comms refactor.
|
||||||
|
//
|
||||||
|
// Serves the network-mode settings page and routes form actions through
|
||||||
|
// the CommandBus, giving the settings UI the same command pipeline as
|
||||||
|
// every other transport.
|
||||||
|
//
|
||||||
|
// Endpoints:
|
||||||
|
// GET /settings — Settings page (HTML)
|
||||||
|
// POST /api/set-mode — Routes to network.set_ap_mode via CommandBus
|
||||||
|
// POST /api/reboot — Routes to system.restart via CommandBus
|
||||||
|
//
|
||||||
|
// broadcast() is a no-op (web server has no persistent client connections).
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class WebServerTransport : public ITransport {
|
||||||
|
public:
|
||||||
|
WebServerTransport(AsyncWebServer& server,
|
||||||
|
CommandBus& bus,
|
||||||
|
ConfigManager& configManager,
|
||||||
|
Networking& networking);
|
||||||
|
|
||||||
|
void begin() override;
|
||||||
|
void loop() override; // no-op — AsyncWebServer is event-driven
|
||||||
|
bool isHealthy() const override;
|
||||||
|
String name() const override { return "WebServer"; }
|
||||||
|
|
||||||
|
// No persistent connections — broadcast is a no-op.
|
||||||
|
void broadcast(const String& message) override {}
|
||||||
|
|
||||||
|
private:
|
||||||
|
AsyncWebServer& _server;
|
||||||
|
CommandBus& _bus;
|
||||||
|
ConfigManager& _configManager;
|
||||||
|
Networking& _networking;
|
||||||
|
bool _initialised = false;
|
||||||
|
|
||||||
|
// Endpoint handlers
|
||||||
|
void handleSettingsPage(AsyncWebServerRequest* request);
|
||||||
|
void handleSetMode(AsyncWebServerRequest* request);
|
||||||
|
void handleReboot(AsyncWebServerRequest* request);
|
||||||
|
|
||||||
|
// Generates the settings HTML with runtime values substituted.
|
||||||
|
String generateSettingsHTML();
|
||||||
|
};
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
# WebSocketTransport
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
`WebSocketTransport` wraps `WebSocketDriver` and connects it to the `CommandBus`. When a WebSocket client sends a JSON message, the driver parses it and invokes a callback on this transport, which builds a `CommandEnvelope` with a reply lambda that sends the response back to the originating client only. `broadcast()` sends to all connected clients. The transport also exposes targeted and role-based broadcast methods used by `CommunicationRouter`'s helpers. All client lifecycle tracking (type classification as master/secondary, heartbeat, cleanup) is handled by `ClientManager` through the driver.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Public API
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `WebSocketTransport(WebSocketDriver& ws, CommandBus& bus)` | Constructor. |
|
||||||
|
| `void begin()` | Wires the message callback onto `WebSocketDriver` and calls `WebSocketDriver::begin()`. The `AsyncWebSocket` handler must be added to `AsyncWebServer` separately (done in `CommunicationRouter::begin()`). |
|
||||||
|
| `void loop()` | No-op. AsyncWebServer is event-driven. |
|
||||||
|
| `bool isHealthy() const` | Always returns `true` — the WebSocket server is always listening once started. |
|
||||||
|
| `String name() const` | Returns `"WebSocket"`. |
|
||||||
|
| `void broadcast(const String& msg)` | Sends `msg` to all connected WebSocket clients. |
|
||||||
|
| `void sendToClient(uint32_t clientId, const String& msg)` | Sends to a single client by ID. Used by handlers that need to target the originating client directly. |
|
||||||
|
| `void broadcastToMasters(const String& msg)` | Sends to clients classified as `MASTER` type only. |
|
||||||
|
| `void broadcastToSecondary(const String& msg)` | Sends to clients classified as `SECONDARY` type only. |
|
||||||
|
| `bool hasClients() const` | True if at least one client is connected. |
|
||||||
|
| `size_t getClientCount() const` | Number of currently connected clients. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Initialization
|
||||||
|
|
||||||
|
`CommunicationRouter::begin()` does two things for WebSocket:
|
||||||
|
1. Calls `_server.addHandler(&_webSocket)` to attach the `AsyncWebSocket` instance to the HTTP server.
|
||||||
|
2. Calls `_wsTransport.begin()` to wire the message callback.
|
||||||
|
|
||||||
|
The `AsyncWebServer` itself is started later from the network-connected callback in `main.cpp`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Message Format
|
||||||
|
|
||||||
|
Incoming WebSocket messages must be JSON:
|
||||||
|
```json
|
||||||
|
{ "v": 2, "cmd": "system.status", "contents": {} }
|
||||||
|
```
|
||||||
|
|
||||||
|
Missing `"cmd"` field results in an immediate error response to that client:
|
||||||
|
```json
|
||||||
|
{ "status": "ERROR", "type": "bad_request", "message": "Missing 'cmd' field" }
|
||||||
|
```
|
||||||
|
|
||||||
|
Responses are sent only to the originating client:
|
||||||
|
```json
|
||||||
|
{ "status": "SUCCESS", "type": "system.status", "data": { ... } }
|
||||||
|
```
|
||||||
|
|
||||||
|
On connect, each client receives an unsolicited welcome message:
|
||||||
|
```json
|
||||||
|
{ "status": "SUCCESS", "type": "connection", "payload": "Connected to Vesper" }
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
- `WebSocketDriver` — client lifecycle, connection events, routing
|
||||||
|
- `ClientManager` — client type classification (master/secondary), targeted sends
|
||||||
|
- `CommandBus` — dispatch and broadcast
|
||||||
|
- `ESPAsyncWebServer`, `ArduinoJson`, `Logging`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Gotchas / Notes
|
||||||
|
|
||||||
|
- **Only single-frame, complete text messages are processed.** Fragmented or binary WebSocket frames are logged as a warning and dropped.
|
||||||
|
- **`isHealthy()` is always true.** The transport has no broker or physical connection to check — it returns `true` as long as the code is running. `CommunicationRouter::isHealthy()` accounts for this by also checking `isMqttConnected()`.
|
||||||
|
- **WebSocket cleanup must be driven externally.** `main.cpp` calls `ws.cleanupClients()` every 2 seconds to evict dead connections. Without this, ghost clients can block new connections.
|
||||||
|
- **Replies go only to the originating client.** Command responses are not broadcast. If other clients need to know about a state change, the handler or the subsystem must trigger a broadcast separately.
|
||||||
|
- **`identify` command is WebSocket-only.** If sent over HTTP or UART, `SystemHandler` returns an error. This is enforced by checking `envelope.transport`.
|
||||||
|
- **Message buffer: 2 KB.** The `StaticJsonDocument<2048>` in `WebSocketDriver::onData()` limits individual message size. Large melody or config payloads must be split by the client.
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
#include "WebSocketTransport.hpp"
|
||||||
|
#include "../../CommandBus/CommandBus.hpp"
|
||||||
|
#include "../../CommandBus/CommandEnvelope.hpp"
|
||||||
|
#include "../../CommandBus/CommandResult.hpp"
|
||||||
|
#include "../../CommandBus/LegacyResponseAdapter.hpp"
|
||||||
|
|
||||||
|
#define TAG "WebSocketTransport"
|
||||||
|
#include "../../../Logging/Logging.hpp"
|
||||||
|
|
||||||
|
WebSocketTransport::WebSocketTransport(WebSocketDriver& wsServer, CommandBus& bus)
|
||||||
|
: _ws(wsServer)
|
||||||
|
, _bus(bus) {
|
||||||
|
}
|
||||||
|
|
||||||
|
void WebSocketTransport::begin() {
|
||||||
|
_ws.setCallback([this](uint32_t clientId, const JsonDocument& doc) {
|
||||||
|
onMessage(clientId, doc);
|
||||||
|
});
|
||||||
|
|
||||||
|
_ws.begin();
|
||||||
|
LOG_INFO(TAG, "WebSocketTransport initialised");
|
||||||
|
}
|
||||||
|
|
||||||
|
void WebSocketTransport::loop() {
|
||||||
|
// AsyncWebServer drives the event loop; nothing to poll here.
|
||||||
|
}
|
||||||
|
|
||||||
|
bool WebSocketTransport::isHealthy() const {
|
||||||
|
return true; // Always healthy — WebSocket server is always listening
|
||||||
|
}
|
||||||
|
|
||||||
|
void WebSocketTransport::broadcast(const String& message) {
|
||||||
|
_ws.broadcastToAll(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
void WebSocketTransport::sendToClient(uint32_t clientId, const String& message) {
|
||||||
|
_ws.sendToClient(clientId, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
void WebSocketTransport::broadcastToMasters(const String& message) {
|
||||||
|
_ws.broadcastToMaster(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
void WebSocketTransport::broadcastToSecondary(const String& message) {
|
||||||
|
_ws.broadcastToSecondary(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool WebSocketTransport::hasClients() const {
|
||||||
|
return _ws.hasClients();
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t WebSocketTransport::getClientCount() const {
|
||||||
|
return _ws.getClientCount();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
void WebSocketTransport::onMessage(uint32_t clientId, const JsonDocument& doc) {
|
||||||
|
const char* cmd = doc["cmd"] | "";
|
||||||
|
if (cmd[0] == '\0') {
|
||||||
|
LOG_WARNING(TAG, "Client #%u: WebSocket message missing 'cmd' field — dropping", clientId);
|
||||||
|
String err = R"({"status":"ERROR","type":"bad_request","message":"Missing 'cmd' field"})";
|
||||||
|
_ws.sendToClient(clientId, err);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
LOG_DEBUG(TAG, "Client #%u CMD: %s", clientId, cmd);
|
||||||
|
|
||||||
|
CommandEnvelope envelope;
|
||||||
|
envelope.transport = CommandEnvelope::Transport::WEBSOCKET;
|
||||||
|
envelope.origin = CommandEnvelope::Origin::APP;
|
||||||
|
envelope.clientId = clientId;
|
||||||
|
envelope.command = cmd;
|
||||||
|
envelope.version = doc["v"] | 1;
|
||||||
|
|
||||||
|
if (doc.containsKey("contents")) {
|
||||||
|
envelope.contents.set(doc["contents"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Capture the ORIGINAL version before CommandBus::dispatch() rewrites
|
||||||
|
// envelope.version to 2 post-translation (see LegacyAdapter.hpp).
|
||||||
|
bool isLegacyRequest = (envelope.version == 1);
|
||||||
|
|
||||||
|
// Reply routes back to the originating WebSocket client only
|
||||||
|
envelope.reply = [this, clientId, isLegacyRequest](const CommandResult& result) {
|
||||||
|
JsonDocument resp;
|
||||||
|
if (!isLegacyRequest || !translateLegacyResponse(result, resp)) {
|
||||||
|
resp["status"] = result.isOk() ? "SUCCESS"
|
||||||
|
: (result.status == CommandResult::Status::INFO ? "INFO" : "ERROR");
|
||||||
|
resp["type"] = result.type;
|
||||||
|
if (!result.payload.isEmpty()) {
|
||||||
|
resp["message"] = result.payload;
|
||||||
|
}
|
||||||
|
if (result.hasData) {
|
||||||
|
resp["data"] = result.data;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
String out;
|
||||||
|
serializeJson(resp, out);
|
||||||
|
_ws.sendToClient(clientId, out);
|
||||||
|
};
|
||||||
|
|
||||||
|
_bus.dispatch(envelope);
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include "../ITransport.hpp"
|
||||||
|
#include "../../Drivers/WebSocketDriver/WebSocketDriver.hpp"
|
||||||
|
|
||||||
|
class CommandBus;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// WebSocketTransport
|
||||||
|
//
|
||||||
|
// ITransport wrapper around the existing WebSocketDriver.
|
||||||
|
//
|
||||||
|
// Responsibilities:
|
||||||
|
// - Delegates connection lifecycle and client management to WebSocketDriver
|
||||||
|
// - Parses incoming WebSocket JSON messages into CommandEnvelopes
|
||||||
|
// - Injects a reply lambda that sends the response back to the originating client
|
||||||
|
// - Dispatches to the CommandBus
|
||||||
|
// - broadcast() sends to all connected WebSocket clients
|
||||||
|
//
|
||||||
|
// The identify command is still handled by SystemHandler (registered on the bus),
|
||||||
|
// not special-cased here — the transport is protocol-neutral.
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class WebSocketTransport : public ITransport {
|
||||||
|
public:
|
||||||
|
WebSocketTransport(WebSocketDriver& wsServer, CommandBus& bus);
|
||||||
|
|
||||||
|
void begin() override;
|
||||||
|
void loop() override; // no-op — AsyncWebServer is event-driven
|
||||||
|
bool isHealthy() const override;
|
||||||
|
String name() const override { return "WebSocket"; }
|
||||||
|
|
||||||
|
// Send to all connected WebSocket clients.
|
||||||
|
void broadcast(const String& message) override;
|
||||||
|
|
||||||
|
// Targeted send — used by the identify handler and other per-client responses.
|
||||||
|
void sendToClient(uint32_t clientId, const String& message);
|
||||||
|
|
||||||
|
// Access for CommunicationRouter broadcast helpers
|
||||||
|
void broadcastToMasters(const String& message);
|
||||||
|
void broadcastToSecondary(const String& message);
|
||||||
|
|
||||||
|
bool hasClients() const;
|
||||||
|
size_t getClientCount() const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
WebSocketDriver& _ws;
|
||||||
|
CommandBus& _bus;
|
||||||
|
|
||||||
|
// Invoked by WebSocketDriver's message callback
|
||||||
|
void onMessage(uint32_t clientId, const JsonDocument& doc);
|
||||||
|
};
|
||||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user