Compare commits
78
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
290445e3ad | ||
|
|
b121560b1f | ||
|
|
71ced6bf0e | ||
|
|
9d69733257 | ||
|
|
009cefcb90 | ||
|
|
c43d9ae11c | ||
|
|
cec4db4894 | ||
|
|
09f562cf1d | ||
|
|
bf4a04d6f4 | ||
|
|
83b2b2547f | ||
|
|
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 |
+18
-7
@@ -1,10 +1,21 @@
|
||||
.vscode/
|
||||
docs/
|
||||
html/
|
||||
vesper/build/
|
||||
vesper/sd_settings/
|
||||
vesper/CLAUDE.md
|
||||
vesper/flutter/
|
||||
vesper/docs_manual/
|
||||
build/
|
||||
sd_settings/
|
||||
CLAUDE.md
|
||||
flutter/
|
||||
docs_manual/
|
||||
Doxyfile
|
||||
vesper/.claude/
|
||||
.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/
|
||||
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
# 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. Every change bumps the firmware version.**
|
||||
`FW_VERSION` in `src/Version.hpp` is `MAJOR.MINOR.PATCH` and is what devices report and what OTA compares, so two different builds must never share a number.
|
||||
- **PATCH** (`2.4.0 → 2.4.1`) — bug fixes, internal changes, log/latency tweaks with no new API or behaviour contract.
|
||||
- **MINOR** (`2.4.x → 2.5.0`) — new commands, fields, topics or features, or a change to observable behaviour (timings, QoS, defaults).
|
||||
- **MAJOR** (`2.x → 3.0.0`) — breaking changes for apps/backend. **Discuss with the owner before bumping major.**
|
||||
|
||||
The bump goes in the same commit as the change (or one commit covering a batch that ships together): update `FW_VERSION`, add a line to the `VERSION HISTORY` comment above it, and set the feature catalog's "Since" column to the new version. Doc-only commits don't bump.
|
||||
|
||||
**7. 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
@@ -22,7 +22,8 @@ vesper/{deviceID}/status/heartbeat
|
||||
"timestamp": "Uptime: 5h 23m 45s",
|
||||
"ip_address": "192.168.1.100",
|
||||
"gateway": "192.168.1.1",
|
||||
"uptime_ms": 19425000
|
||||
"uptime_ms": 19425000,
|
||||
"rssi": -62
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -101,19 +102,10 @@ void heartbeatTimerCallback(); // Timer callback handler
|
||||
|
||||
### Possible Additions:
|
||||
- Add actual RTC timestamp (instead of just uptime)
|
||||
- Add WiFi signal strength (RSSI) for WiFi connections
|
||||
- Add free heap memory
|
||||
- Add current playback status
|
||||
- Add bell configuration version/hash
|
||||
|
||||
### Implementation Example:
|
||||
```cpp
|
||||
// In publishHeartbeat()
|
||||
payload["rssi"] = WiFi.RSSI(); // WiFi signal strength
|
||||
payload["free_heap"] = ESP.getFreeHeap();
|
||||
payload["playback_active"] = player.isPlaying;
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### Current Settings (can be changed in MQTTAsyncClient.hpp):
|
||||
@@ -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,968 @@
|
||||
# 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`: vesper-std, bespoke-rs485 — only agnus has it) | `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 (confirmed) | Playback transitions |
|
||||
| MQTT | `vesper/{device_id}/system/alerts` | Outbound, retained until cleared, QoS 0 | Subsystem state-change events |
|
||||
| MQTT | `vesper/{device_id}/system/info` | Outbound, retained, QoS 0 | 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 — agnus)
|
||||
|
||||
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.status`
|
||||
|
||||
Connection health since boot — works on every transport, so it's the command to send over WebSocket when the cloud shows a device offline but the local app still works.
|
||||
Returns `data: { "enabled", "connected", "connected_for_ms", "connects", "disconnects", "reconnect_attempts", "last_disconnect_reason", "last_disconnect_ago_ms", "forced_resets", "last_forced_reset_reason", "last_forced_reset_ago_ms", "resent_messages", "wifi_connected", "free_heap" }`.
|
||||
`*_ago_ms` and `connected_for_ms` are `0` when the event never happened / not connected. `last_forced_reset_reason` is `"connect attempt stuck"`, `"heartbeat PUBACK timeout"`, `"playback PUBACK timeout"` or `"report PUBACK timeout"` (empty if self-recovery never fired). `resent_messages` counts `control/reports` messages republished after a reconnect because their PUBACK never came. No errors.
|
||||
|
||||
### `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 | 0 | yes, until cleared | `alerts` |
|
||||
| `vesper/{id}/system/info` | Discrete device events (e.g. boot report) | 0 | 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). Replies are published at QoS 0.
|
||||
|
||||
QoS 1 is used only for the heartbeat, `status/playback` and `control/reports`, and the firmware tracks their PUBACKs: a missing one makes the device reset the connection, republish the current playback state, and resend unconfirmed reports. Everything else is QoS 0 — see F-071/F-073 in the feature catalog.
|
||||
|
||||
---
|
||||
|
||||
## 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 — agnus)* |
|
||||
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,410 @@
|
||||
# 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 | 0 | 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 | 0 | yes, until cleared | `alerts` | Subsystem state-change events |
|
||||
| `vesper/{id}/system/info` | Outbound | 0 | 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 (PUBACK tracked; current state republished on every reconnect) — **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 (PUBACK tracked; resent after a reconnect if unconfirmed) — **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:** 0 — **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:** 0 — **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": "async_tcp", "pc": 1074282197, "exc_cause": 29, "exc_vaddr": 0,
|
||||
"backtrace": [1074282194, 1074340312, 1074348122, 1074606712],
|
||||
"backtrace_corrupted": false,
|
||||
"elf_sha256": "3f9a1c0be7d2a441"
|
||||
},
|
||||
"pre_crash": {
|
||||
"uptime_ms": 5412000, "free_heap": 21480, "largest_block": 9716, "min_free_heap": 18112,
|
||||
"abort_msg": "abort() was called at PC 0x400d8a3f on core 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). `backtrace` (up to 16 PCs, decimal) and `elf_sha256` (first 16 hex chars of the crashing build's ELF SHA-256) identify the call chain; decode with `addr2line` against that exact `.elf`.
|
||||
|
||||
`pre_crash` (F-070) is present only on a fault reset where RTC memory survived (not power-on/brownout): the last once-per-second heap/uptime snapshot before the reset, plus `abort_msg` when the reset came from `abort()`/`assert`/a stack-overflow check. For those resets `pc`/`exc_cause 29`/`exc_vaddr 0` are the abort mechanism itself; `abort_msg` and the later `backtrace` frames are the real cause. 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 inbound (`control/command`), 0 outbound (`control/ack`) — **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,88 @@
|
||||
# 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.
|
||||
- **Replies are never deferred.** `CommandBus::dispatch()` sends the reply synchronously, on the transport's own task, right after the handler returns — no command replies from another task/context, so `req_id` can't be lost. This includes `playback.play` when a download is needed: the ACK (`Melody download started — …`, with `req_id`) goes out immediately, and the later outcome is reported on `status/playback` (`loading` → `playing`/`idle`) and, on failure, `control/reports` `playback_failed` — neither of which carries `req_id` (match by `pid`).
|
||||
- **When no reply arrives at all:** the MQTT heap guard drops incoming commands silently under critical heap pressure, and a reply is dropped if the `command` switch is off or the broker link is down at reply time. A client should still time out.
|
||||
- **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,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015-2021 Marvin Roger
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,33 @@
|
||||
# AsyncMqttClient (vendored, patched)
|
||||
|
||||
This is a copy of the library kept in the repo, not downloaded at build time.
|
||||
PlatformIO builds it from `lib/` automatically. Do not add it back to `lib_deps`.
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Upstream | https://github.com/marvinroger/async-mqtt-client |
|
||||
| Commit | `3d93fc7f662e65366f8e2b0d88b108f874f035b9` (2024-09-25, "Merge pull request #310") |
|
||||
| Copied | `src/`, `LICENSE`, `library.json` (dependencies removed — AsyncTCP comes from `lib_deps`) |
|
||||
| Version | `0.9.0+vesper.1` |
|
||||
|
||||
## Why vendored
|
||||
|
||||
1. We patch it (below).
|
||||
2. It used to come from the repo's default branch with no pin, so any upstream push could change the
|
||||
firmware on the next clean build. Upstream is unmaintained, so updates are unlikely, but a copy here
|
||||
means nothing changes unless someone changes it in a commit.
|
||||
|
||||
## Patches
|
||||
|
||||
Every patched line is marked `[vesper patch]` — `grep -rn "vesper patch" lib/AsyncMqttClient`.
|
||||
|
||||
1. **`_onPubAck()` / `_onPubComp()` call `_handleQueue()`.** The outbound queue is sent strictly in order
|
||||
and stops after each QoS 1/2 PUBLISH until its acknowledgement arrives. Upstream releases the packet
|
||||
on the ack but doesn't restart sending, so the next queued packet waited for the next lwIP poll
|
||||
(~500 ms). Every QoS 1 message therefore delayed whatever was behind it by a round trip plus up to
|
||||
half a second. Now it's just the round trip. See feature catalog F-072/F-073.
|
||||
|
||||
## Updating
|
||||
|
||||
Don't just copy a newer upstream over this folder. Diff upstream against the commit above, re-apply the
|
||||
patches, bump the `+vesper.N` suffix in `library.json`, update this file, and test MQTT on hardware.
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "AsyncMqttClient",
|
||||
"keywords": "iot, home, automation, async, mqtt, client, esp8266",
|
||||
"description": "An Arduino for ESP8266 / ESP32 asynchronous MQTT client implementation",
|
||||
"authors": {
|
||||
"name": "Marvin ROGER",
|
||||
"url": "https://www.marvinroger.fr"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/marvinroger/async-mqtt-client.git"
|
||||
},
|
||||
"version": "0.9.0+vesper.1",
|
||||
"frameworks": "arduino",
|
||||
"platforms": [
|
||||
"espressif8266",
|
||||
"espressif32"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,757 @@
|
||||
#include "AsyncMqttClient.hpp"
|
||||
|
||||
AsyncMqttClient::AsyncMqttClient()
|
||||
: _client()
|
||||
, _head(nullptr)
|
||||
, _tail(nullptr)
|
||||
, _sent(0)
|
||||
, _state(DISCONNECTED)
|
||||
, _disconnectReason(AsyncMqttClientDisconnectReason::TCP_DISCONNECTED)
|
||||
, _lastClientActivity(0)
|
||||
, _lastServerActivity(0)
|
||||
, _lastPingRequestTime(0)
|
||||
, _generatedClientId{0}
|
||||
, _ip()
|
||||
, _host(nullptr)
|
||||
, _useIp(false)
|
||||
#if ASYNC_TCP_SSL_ENABLED
|
||||
, _secure(false)
|
||||
#endif
|
||||
, _port(0)
|
||||
, _keepAlive(15)
|
||||
, _cleanSession(true)
|
||||
, _clientId(nullptr)
|
||||
, _username(nullptr)
|
||||
, _password(nullptr)
|
||||
, _willTopic(nullptr)
|
||||
, _willPayload(nullptr)
|
||||
, _willPayloadLength(0)
|
||||
, _willQos(0)
|
||||
, _willRetain(false)
|
||||
#if ASYNC_TCP_SSL_ENABLED
|
||||
, _secureServerFingerprints()
|
||||
#endif
|
||||
, _onConnectUserCallbacks()
|
||||
, _onDisconnectUserCallbacks()
|
||||
, _onSubscribeUserCallbacks()
|
||||
, _onUnsubscribeUserCallbacks()
|
||||
, _onMessageUserCallbacks()
|
||||
, _onPublishUserCallbacks()
|
||||
, _parsingInformation { .bufferState = AsyncMqttClientInternals::BufferState::NONE }
|
||||
, _currentParsedPacket(nullptr)
|
||||
, _remainingLengthBufferPosition(0)
|
||||
, _remainingLengthBuffer{0}
|
||||
, _pendingPubRels() {
|
||||
_client.onConnect([](void* obj, AsyncClient* c) { (static_cast<AsyncMqttClient*>(obj))->_onConnect(); }, this);
|
||||
_client.onDisconnect([](void* obj, AsyncClient* c) { (static_cast<AsyncMqttClient*>(obj))->_onDisconnect(); }, this);
|
||||
// _client.onError([](void* obj, AsyncClient* c, int8_t error) { (static_cast<AsyncMqttClient*>(obj))->_onError(error); }, this);
|
||||
// _client.onTimeout([](void* obj, AsyncClient* c, uint32_t time) { (static_cast<AsyncMqttClient*>(obj))->_onTimeout(); }, this);
|
||||
_client.onAck([](void* obj, AsyncClient* c, size_t len, uint32_t time) { (static_cast<AsyncMqttClient*>(obj))->_onAck(len); }, this);
|
||||
_client.onData([](void* obj, AsyncClient* c, void* data, size_t len) { (static_cast<AsyncMqttClient*>(obj))->_onData(static_cast<char*>(data), len); }, this);
|
||||
_client.onPoll([](void* obj, AsyncClient* c) { (static_cast<AsyncMqttClient*>(obj))->_onPoll(); }, this);
|
||||
_client.setNoDelay(true); // send small packets immediately (PINGREQ/DISCONN are only 2 bytes)
|
||||
#ifdef ESP32
|
||||
sprintf(_generatedClientId, "esp32-%06llx", ESP.getEfuseMac());
|
||||
_xSemaphore = xSemaphoreCreateMutex();
|
||||
#elif defined(ESP8266)
|
||||
sprintf(_generatedClientId, "esp8266-%06x", ESP.getChipId());
|
||||
#endif
|
||||
_clientId = _generatedClientId;
|
||||
|
||||
setMaxTopicLength(128);
|
||||
}
|
||||
|
||||
AsyncMqttClient::~AsyncMqttClient() {
|
||||
delete _currentParsedPacket;
|
||||
delete[] _parsingInformation.topicBuffer;
|
||||
_clear();
|
||||
_pendingPubRels.clear();
|
||||
_pendingPubRels.shrink_to_fit();
|
||||
_clearQueue(false); // _clear() doesn't clear session data
|
||||
#ifdef ESP32
|
||||
vSemaphoreDelete(_xSemaphore);
|
||||
#endif
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::setKeepAlive(uint16_t keepAlive) {
|
||||
_keepAlive = keepAlive;
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::setClientId(const char* clientId) {
|
||||
_clientId = clientId;
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::setCleanSession(bool cleanSession) {
|
||||
_cleanSession = cleanSession;
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::setMaxTopicLength(uint16_t maxTopicLength) {
|
||||
_parsingInformation.maxTopicLength = maxTopicLength;
|
||||
delete[] _parsingInformation.topicBuffer;
|
||||
_parsingInformation.topicBuffer = new char[maxTopicLength + 1];
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::setCredentials(const char* username, const char* password) {
|
||||
_username = username;
|
||||
_password = password;
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::setWill(const char* topic, uint8_t qos, bool retain, const char* payload, size_t length) {
|
||||
_willTopic = topic;
|
||||
_willQos = qos;
|
||||
_willRetain = retain;
|
||||
_willPayload = payload;
|
||||
_willPayloadLength = length;
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::setServer(IPAddress ip, uint16_t port) {
|
||||
_useIp = true;
|
||||
_ip = ip;
|
||||
_port = port;
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::setServer(const char* host, uint16_t port) {
|
||||
_useIp = false;
|
||||
_host = host;
|
||||
_port = port;
|
||||
return *this;
|
||||
}
|
||||
|
||||
#if ASYNC_TCP_SSL_ENABLED
|
||||
AsyncMqttClient& AsyncMqttClient::setSecure(bool secure) {
|
||||
_secure = secure;
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::addServerFingerprint(const uint8_t* fingerprint) {
|
||||
std::array<uint8_t, SHA1_SIZE> newFingerprint;
|
||||
memcpy(newFingerprint.data(), fingerprint, SHA1_SIZE);
|
||||
_secureServerFingerprints.push_back(newFingerprint);
|
||||
return *this;
|
||||
}
|
||||
#endif
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::onConnect(AsyncMqttClientInternals::OnConnectUserCallback callback) {
|
||||
_onConnectUserCallbacks.push_back(callback);
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::onDisconnect(AsyncMqttClientInternals::OnDisconnectUserCallback callback) {
|
||||
_onDisconnectUserCallbacks.push_back(callback);
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::onSubscribe(AsyncMqttClientInternals::OnSubscribeUserCallback callback) {
|
||||
_onSubscribeUserCallbacks.push_back(callback);
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::onUnsubscribe(AsyncMqttClientInternals::OnUnsubscribeUserCallback callback) {
|
||||
_onUnsubscribeUserCallbacks.push_back(callback);
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::onMessage(AsyncMqttClientInternals::OnMessageUserCallback callback) {
|
||||
_onMessageUserCallbacks.push_back(callback);
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncMqttClient& AsyncMqttClient::onPublish(AsyncMqttClientInternals::OnPublishUserCallback callback) {
|
||||
_onPublishUserCallbacks.push_back(callback);
|
||||
return *this;
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_freeCurrentParsedPacket() {
|
||||
delete _currentParsedPacket;
|
||||
_currentParsedPacket = nullptr;
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_clear() {
|
||||
_lastPingRequestTime = 0;
|
||||
_freeCurrentParsedPacket();
|
||||
_clearQueue(true); // keep session data for now
|
||||
|
||||
_parsingInformation.bufferState = AsyncMqttClientInternals::BufferState::NONE;
|
||||
|
||||
_client.setRxTimeout(0);
|
||||
}
|
||||
|
||||
/* TCP */
|
||||
void AsyncMqttClient::_onConnect() {
|
||||
log_i("TCP conn, MQTT CONNECT");
|
||||
#if ASYNC_TCP_SSL_ENABLED
|
||||
if (_secure && _secureServerFingerprints.size() > 0) {
|
||||
SSL* clientSsl = _client.getSSL();
|
||||
|
||||
bool sslFoundFingerprint = false;
|
||||
for (std::array<uint8_t, SHA1_SIZE> fingerprint : _secureServerFingerprints) {
|
||||
if (ssl_match_fingerprint(clientSsl, fingerprint.data()) == SSL_OK) {
|
||||
sslFoundFingerprint = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!sslFoundFingerprint) {
|
||||
_disconnectReason = AsyncMqttClientDisconnectReason::TLS_BAD_FINGERPRINT;
|
||||
_client.close(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
AsyncMqttClientInternals::OutPacket* msg =
|
||||
new AsyncMqttClientInternals::ConnectOutPacket(_cleanSession,
|
||||
_username,
|
||||
_password,
|
||||
_willTopic,
|
||||
_willRetain,
|
||||
_willQos,
|
||||
_willPayload,
|
||||
_willPayloadLength,
|
||||
_keepAlive,
|
||||
_clientId);
|
||||
_addFront(msg);
|
||||
_handleQueue();
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onDisconnect() {
|
||||
log_i("TCP disconn");
|
||||
_state = DISCONNECTED;
|
||||
|
||||
_clear();
|
||||
|
||||
for (auto callback : _onDisconnectUserCallbacks) callback(_disconnectReason);
|
||||
}
|
||||
|
||||
/*
|
||||
void AsyncMqttClient::_onError(int8_t error) {
|
||||
(void)error;
|
||||
// _onDisconnect called anyway
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onTimeout() {
|
||||
// disconnection will be handled by ping/pong management
|
||||
}
|
||||
*/
|
||||
|
||||
void AsyncMqttClient::_onAck(size_t len) {
|
||||
log_i("ack %u", len);
|
||||
_handleQueue();
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onData(char* data, size_t len) {
|
||||
log_i("data rcv (%u)", len);
|
||||
size_t currentBytePosition = 0;
|
||||
char currentByte;
|
||||
_lastServerActivity = millis();
|
||||
do {
|
||||
switch (_parsingInformation.bufferState) {
|
||||
case AsyncMqttClientInternals::BufferState::NONE:
|
||||
currentByte = data[currentBytePosition++];
|
||||
_parsingInformation.packetType = currentByte >> 4;
|
||||
_parsingInformation.packetFlags = (currentByte << 4) >> 4;
|
||||
_parsingInformation.bufferState = AsyncMqttClientInternals::BufferState::REMAINING_LENGTH;
|
||||
switch (_parsingInformation.packetType) {
|
||||
case AsyncMqttClientInternals::PacketType.CONNACK:
|
||||
log_i("rcv CONNACK");
|
||||
_currentParsedPacket = new AsyncMqttClientInternals::ConnAckPacket(&_parsingInformation, std::bind(&AsyncMqttClient::_onConnAck, this, std::placeholders::_1, std::placeholders::_2));
|
||||
_client.setRxTimeout(0);
|
||||
break;
|
||||
case AsyncMqttClientInternals::PacketType.PINGRESP:
|
||||
log_i("rcv PINGRESP");
|
||||
_currentParsedPacket = new AsyncMqttClientInternals::PingRespPacket(&_parsingInformation, std::bind(&AsyncMqttClient::_onPingResp, this));
|
||||
break;
|
||||
case AsyncMqttClientInternals::PacketType.SUBACK:
|
||||
log_i("rcv SUBACK");
|
||||
_currentParsedPacket = new AsyncMqttClientInternals::SubAckPacket(&_parsingInformation, std::bind(&AsyncMqttClient::_onSubAck, this, std::placeholders::_1, std::placeholders::_2));
|
||||
break;
|
||||
case AsyncMqttClientInternals::PacketType.UNSUBACK:
|
||||
log_i("rcv UNSUBACK");
|
||||
_currentParsedPacket = new AsyncMqttClientInternals::UnsubAckPacket(&_parsingInformation, std::bind(&AsyncMqttClient::_onUnsubAck, this, std::placeholders::_1));
|
||||
break;
|
||||
case AsyncMqttClientInternals::PacketType.PUBLISH:
|
||||
log_i("rcv PUBLISH");
|
||||
_currentParsedPacket = new AsyncMqttClientInternals::PublishPacket(&_parsingInformation, std::bind(&AsyncMqttClient::_onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5, std::placeholders::_6, std::placeholders::_7, std::placeholders::_8, std::placeholders::_9), std::bind(&AsyncMqttClient::_onPublish, this, std::placeholders::_1, std::placeholders::_2));
|
||||
break;
|
||||
case AsyncMqttClientInternals::PacketType.PUBREL:
|
||||
log_i("rcv PUBREL");
|
||||
_currentParsedPacket = new AsyncMqttClientInternals::PubRelPacket(&_parsingInformation, std::bind(&AsyncMqttClient::_onPubRel, this, std::placeholders::_1));
|
||||
break;
|
||||
case AsyncMqttClientInternals::PacketType.PUBACK:
|
||||
log_i("rcv PUBACK");
|
||||
_currentParsedPacket = new AsyncMqttClientInternals::PubAckPacket(&_parsingInformation, std::bind(&AsyncMqttClient::_onPubAck, this, std::placeholders::_1));
|
||||
break;
|
||||
case AsyncMqttClientInternals::PacketType.PUBREC:
|
||||
log_i("rcv PUBREC");
|
||||
_currentParsedPacket = new AsyncMqttClientInternals::PubRecPacket(&_parsingInformation, std::bind(&AsyncMqttClient::_onPubRec, this, std::placeholders::_1));
|
||||
break;
|
||||
case AsyncMqttClientInternals::PacketType.PUBCOMP:
|
||||
log_i("rcv PUBCOMP");
|
||||
_currentParsedPacket = new AsyncMqttClientInternals::PubCompPacket(&_parsingInformation, std::bind(&AsyncMqttClient::_onPubComp, this, std::placeholders::_1));
|
||||
break;
|
||||
default:
|
||||
log_i("rcv PROTOCOL VIOLATION");
|
||||
disconnect(true);
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case AsyncMqttClientInternals::BufferState::REMAINING_LENGTH:
|
||||
currentByte = data[currentBytePosition++];
|
||||
_remainingLengthBuffer[_remainingLengthBufferPosition++] = currentByte;
|
||||
if (currentByte >> 7 == 0) {
|
||||
_parsingInformation.remainingLength = AsyncMqttClientInternals::Helpers::decodeRemainingLength(_remainingLengthBuffer);
|
||||
_remainingLengthBufferPosition = 0;
|
||||
if (_parsingInformation.remainingLength > 0) {
|
||||
_parsingInformation.bufferState = AsyncMqttClientInternals::BufferState::VARIABLE_HEADER;
|
||||
} else {
|
||||
// PINGRESP is a special case where it has no variable header, so the packet ends right here
|
||||
_parsingInformation.bufferState = AsyncMqttClientInternals::BufferState::NONE;
|
||||
_onPingResp();
|
||||
}
|
||||
}
|
||||
break;
|
||||
case AsyncMqttClientInternals::BufferState::VARIABLE_HEADER:
|
||||
_currentParsedPacket->parseVariableHeader(data, len, ¤tBytePosition);
|
||||
break;
|
||||
case AsyncMqttClientInternals::BufferState::PAYLOAD:
|
||||
_currentParsedPacket->parsePayload(data, len, ¤tBytePosition);
|
||||
break;
|
||||
default:
|
||||
currentBytePosition = len;
|
||||
}
|
||||
} while (currentBytePosition != len);
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onPoll() {
|
||||
// if there is too much time the client has sent a ping request without a response, disconnect client to avoid half open connections
|
||||
if (_lastPingRequestTime != 0 && (millis() - _lastPingRequestTime) >= (_keepAlive * 1000 * 2)) {
|
||||
log_w("PING t/o, disconnecting");
|
||||
disconnect(true);
|
||||
return;
|
||||
}
|
||||
// send ping to ensure the server will receive at least one message inside keepalive window
|
||||
if (_state == CONNECTED && _lastPingRequestTime == 0 && (millis() - _lastClientActivity) >= (_keepAlive * 1000 * 0.7)) {
|
||||
_sendPing();
|
||||
// send ping to verify if the server is still there (ensure this is not a half connection)
|
||||
} else if (_state == CONNECTED && _lastPingRequestTime == 0 && (millis() - _lastServerActivity) >= (_keepAlive * 1000 * 0.7)) {
|
||||
_sendPing();
|
||||
}
|
||||
_handleQueue();
|
||||
}
|
||||
|
||||
/* QUEUE */
|
||||
|
||||
void AsyncMqttClient::_insert(AsyncMqttClientInternals::OutPacket* packet) {
|
||||
// We only use this for QoS2 PUBREL so there must be a PUBLISH packet present.
|
||||
// The queue therefore cannot be empty and _head points to this PUBLISH packet.
|
||||
SEMAPHORE_TAKE();
|
||||
log_i("new insert #%u", packet->packetType());
|
||||
packet->next = _head->next;
|
||||
_head->next = packet;
|
||||
if (_head == _tail) { // PUB packet is the only one in the queue
|
||||
_tail = packet;
|
||||
}
|
||||
SEMAPHORE_GIVE();
|
||||
_handleQueue();
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_addFront(AsyncMqttClientInternals::OutPacket* packet) {
|
||||
// This is only used for the CONNECT packet, to be able to establish a connection
|
||||
// before anything else. The queue can be empty or has packets from the continued session.
|
||||
// In both cases, _head should always point to the CONNECT packet afterwards.
|
||||
SEMAPHORE_TAKE();
|
||||
log_i("new front #%u", packet->packetType());
|
||||
if (_head == nullptr) {
|
||||
_tail = packet;
|
||||
} else {
|
||||
packet->next = _head;
|
||||
}
|
||||
_head = packet;
|
||||
SEMAPHORE_GIVE();
|
||||
_handleQueue();
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_addBack(AsyncMqttClientInternals::OutPacket* packet) {
|
||||
SEMAPHORE_TAKE();
|
||||
log_i("new back #%u", packet->packetType());
|
||||
if (!_tail) {
|
||||
_head = packet;
|
||||
} else {
|
||||
_tail->next = packet;
|
||||
}
|
||||
_tail = packet;
|
||||
_tail->next = nullptr;
|
||||
SEMAPHORE_GIVE();
|
||||
_handleQueue();
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_handleQueue() {
|
||||
SEMAPHORE_TAKE();
|
||||
// On ESP32, onDisconnect is called within the close()-call. So we need to make sure we don't lock
|
||||
bool disconnect = false;
|
||||
|
||||
while (_head && _client.space() > 10) { // safe but arbitrary value, send at least 10 bytes
|
||||
// 1. try to send
|
||||
if (_head->size() > _sent) {
|
||||
// On SSL the TCP library returns the total amount of bytes, not just the unencrypted payload length.
|
||||
// So we calculate the amount to be written ourselves.
|
||||
size_t willSend = std::min(_head->size() - _sent, _client.space());
|
||||
size_t realSent = _client.add(reinterpret_cast<const char*>(_head->data(_sent)), willSend, ASYNC_WRITE_FLAG_COPY); // flag is set by LWIP anyway, added for clarity
|
||||
_sent += willSend;
|
||||
(void)realSent;
|
||||
_client.send();
|
||||
_lastClientActivity = millis();
|
||||
_lastPingRequestTime = 0;
|
||||
#if ASYNC_TCP_SSL_ENABLED
|
||||
log_i("snd #%u: (tls: %u) %u/%u", _head->packetType(), realSent, _sent, _head->size());
|
||||
#else
|
||||
log_i("snd #%u: %u/%u", _head->packetType(), _sent, _head->size());
|
||||
#endif
|
||||
if (_head->packetType() == AsyncMqttClientInternals::PacketType.DISCONNECT) {
|
||||
disconnect = true;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. stop processing when we have to wait for an MQTT acknowledgment
|
||||
if (_head->size() == _sent) {
|
||||
if (_head->released()) {
|
||||
log_i("p #%d rel", _head->packetType());
|
||||
AsyncMqttClientInternals::OutPacket* tmp = _head;
|
||||
_head = _head->next;
|
||||
if (!_head) _tail = nullptr;
|
||||
delete tmp;
|
||||
_sent = 0;
|
||||
} else {
|
||||
break; // sending is complete however send next only after mqtt confirmation
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SEMAPHORE_GIVE();
|
||||
if (disconnect) {
|
||||
log_i("snd DISCONN, disconnecting");
|
||||
_client.close();
|
||||
}
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_clearQueue(bool keepSessionData) {
|
||||
SEMAPHORE_TAKE();
|
||||
AsyncMqttClientInternals::OutPacket* packet = _head;
|
||||
_head = nullptr;
|
||||
_tail = nullptr;
|
||||
|
||||
while (packet) {
|
||||
/* MQTT spec 3.1.2.4 Clean Session:
|
||||
* - QoS 1 and QoS 2 messages which have been sent to the Server, but have not been completely acknowledged.
|
||||
* - QoS 2 messages which have been received from the Server, but have not been completely acknowledged.
|
||||
* + (unsent PUB messages with QoS > 0)
|
||||
*
|
||||
* To be kept:
|
||||
* - possibly first message (sent to server but not acked)
|
||||
* - PUBREC messages (QoS 2 PUB received but not acked)
|
||||
* - PUBCOMP messages (QoS 2 PUBREL received but not acked)
|
||||
*/
|
||||
if (keepSessionData) {
|
||||
if (packet->qos() > 0 && packet->size() <= _sent) { // check for qos includes check for PUB-packet type
|
||||
reinterpret_cast<AsyncMqttClientInternals::PublishOutPacket*>(packet)->setDup();
|
||||
AsyncMqttClientInternals::OutPacket* next = packet->next;
|
||||
log_i("keep #%u", packet->packetType());
|
||||
SEMAPHORE_GIVE();
|
||||
_addBack(packet);
|
||||
SEMAPHORE_TAKE();
|
||||
packet = next;
|
||||
} else if (packet->qos() > 0 ||
|
||||
packet->packetType() == AsyncMqttClientInternals::PacketType.PUBREC ||
|
||||
packet->packetType() == AsyncMqttClientInternals::PacketType.PUBCOMP) {
|
||||
AsyncMqttClientInternals::OutPacket* next = packet->next;
|
||||
log_i("keep #%u", packet->packetType());
|
||||
SEMAPHORE_GIVE();
|
||||
_addBack(packet);
|
||||
SEMAPHORE_TAKE();
|
||||
packet = next;
|
||||
} else {
|
||||
AsyncMqttClientInternals::OutPacket* next = packet->next;
|
||||
delete packet;
|
||||
packet = next;
|
||||
}
|
||||
/* Delete everything when not keeping session data
|
||||
*/
|
||||
} else {
|
||||
AsyncMqttClientInternals::OutPacket* next = packet->next;
|
||||
delete packet;
|
||||
packet = next;
|
||||
}
|
||||
}
|
||||
_sent = 0;
|
||||
SEMAPHORE_GIVE();
|
||||
}
|
||||
|
||||
/* MQTT */
|
||||
void AsyncMqttClient::_onPingResp() {
|
||||
log_i("PINGRESP");
|
||||
_freeCurrentParsedPacket();
|
||||
_lastPingRequestTime = 0;
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onConnAck(bool sessionPresent, uint8_t connectReturnCode) {
|
||||
log_i("CONNACK");
|
||||
_freeCurrentParsedPacket();
|
||||
|
||||
if (!sessionPresent) {
|
||||
_pendingPubRels.clear();
|
||||
_pendingPubRels.shrink_to_fit();
|
||||
_clearQueue(false); // remove session data
|
||||
}
|
||||
|
||||
if (connectReturnCode == 0) {
|
||||
_state = CONNECTED;
|
||||
for (auto callback : _onConnectUserCallbacks) callback(sessionPresent);
|
||||
} else {
|
||||
// Callbacks are handled by the onDisconnect function which is called from the AsyncTcp lib
|
||||
_disconnectReason = static_cast<AsyncMqttClientDisconnectReason>(connectReturnCode);
|
||||
return;
|
||||
}
|
||||
_handleQueue(); // send any remaining data from continued session
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onSubAck(uint16_t packetId, char status) {
|
||||
log_i("SUBACK");
|
||||
_freeCurrentParsedPacket();
|
||||
SEMAPHORE_TAKE();
|
||||
if (_head && _head->packetId() == packetId) {
|
||||
_head->release();
|
||||
log_i("SUB released");
|
||||
}
|
||||
SEMAPHORE_GIVE();
|
||||
|
||||
for (auto callback : _onSubscribeUserCallbacks) callback(packetId, status);
|
||||
|
||||
_handleQueue(); // subscribe confirmed, ready to send next queued item
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onUnsubAck(uint16_t packetId) {
|
||||
log_i("UNSUBACK");
|
||||
_freeCurrentParsedPacket();
|
||||
SEMAPHORE_TAKE();
|
||||
if (_head && _head->packetId() == packetId) {
|
||||
_head->release();
|
||||
log_i("UNSUB released");
|
||||
}
|
||||
SEMAPHORE_GIVE();
|
||||
|
||||
for (auto callback : _onUnsubscribeUserCallbacks) callback(packetId);
|
||||
|
||||
_handleQueue(); // unsubscribe confirmed, ready to send next queued item
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onMessage(char* topic, char* payload, uint8_t qos, bool dup, bool retain, size_t len, size_t index, size_t total, uint16_t packetId) {
|
||||
bool notifyPublish = true;
|
||||
|
||||
if (qos == 2) {
|
||||
for (AsyncMqttClientInternals::PendingPubRel pendingPubRel : _pendingPubRels) {
|
||||
if (pendingPubRel.packetId == packetId) {
|
||||
notifyPublish = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (notifyPublish) {
|
||||
AsyncMqttClientMessageProperties properties;
|
||||
properties.qos = qos;
|
||||
properties.dup = dup;
|
||||
properties.retain = retain;
|
||||
|
||||
for (auto callback : _onMessageUserCallbacks) callback(topic, payload, properties, len, index, total);
|
||||
}
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onPublish(uint16_t packetId, uint8_t qos) {
|
||||
AsyncMqttClientInternals::PendingAck pendingAck;
|
||||
|
||||
if (qos == 1) {
|
||||
pendingAck.packetType = AsyncMqttClientInternals::PacketType.PUBACK;
|
||||
pendingAck.headerFlag = AsyncMqttClientInternals::HeaderFlag.PUBACK_RESERVED;
|
||||
pendingAck.packetId = packetId;
|
||||
AsyncMqttClientInternals::OutPacket* msg = new AsyncMqttClientInternals::PubAckOutPacket(pendingAck);
|
||||
_addBack(msg);
|
||||
} else if (qos == 2) {
|
||||
pendingAck.packetType = AsyncMqttClientInternals::PacketType.PUBREC;
|
||||
pendingAck.headerFlag = AsyncMqttClientInternals::HeaderFlag.PUBREC_RESERVED;
|
||||
pendingAck.packetId = packetId;
|
||||
AsyncMqttClientInternals::OutPacket* msg = new AsyncMqttClientInternals::PubAckOutPacket(pendingAck);
|
||||
_addBack(msg);
|
||||
|
||||
bool pubRelAwaiting = false;
|
||||
for (AsyncMqttClientInternals::PendingPubRel pendingPubRel : _pendingPubRels) {
|
||||
if (pendingPubRel.packetId == packetId) {
|
||||
pubRelAwaiting = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!pubRelAwaiting) {
|
||||
AsyncMqttClientInternals::PendingPubRel pendingPubRel;
|
||||
pendingPubRel.packetId = packetId;
|
||||
_pendingPubRels.push_back(pendingPubRel);
|
||||
}
|
||||
}
|
||||
|
||||
_freeCurrentParsedPacket();
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onPubRel(uint16_t packetId) {
|
||||
_freeCurrentParsedPacket();
|
||||
|
||||
AsyncMqttClientInternals::PendingAck pendingAck;
|
||||
pendingAck.packetType = AsyncMqttClientInternals::PacketType.PUBCOMP;
|
||||
pendingAck.headerFlag = AsyncMqttClientInternals::HeaderFlag.PUBCOMP_RESERVED;
|
||||
pendingAck.packetId = packetId;
|
||||
if (_head && _head->packetId() == packetId) {
|
||||
AsyncMqttClientInternals::OutPacket* msg = new AsyncMqttClientInternals::PubAckOutPacket(pendingAck);
|
||||
_head->release();
|
||||
_insert(msg);
|
||||
log_i("PUBREC released");
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < _pendingPubRels.size(); i++) {
|
||||
if (_pendingPubRels[i].packetId == packetId) {
|
||||
_pendingPubRels.erase(_pendingPubRels.begin() + i);
|
||||
_pendingPubRels.shrink_to_fit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onPubAck(uint16_t packetId) {
|
||||
_freeCurrentParsedPacket();
|
||||
if (_head && _head->packetId() == packetId) {
|
||||
_head->release();
|
||||
log_i("PUB released");
|
||||
}
|
||||
|
||||
for (auto callback : _onPublishUserCallbacks) callback(packetId);
|
||||
_handleQueue(); // [vesper patch] send the next queued packet now, not on the next ~500ms poll
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onPubRec(uint16_t packetId) {
|
||||
_freeCurrentParsedPacket();
|
||||
|
||||
// We will only be sending 1 QoS>0 PUB message at a time (to honor message
|
||||
// ordering). So no need to store ACKS in a separate container as it will
|
||||
// be stored in the outgoing queue until a PUBCOMP comes in.
|
||||
AsyncMqttClientInternals::PendingAck pendingAck;
|
||||
pendingAck.packetType = AsyncMqttClientInternals::PacketType.PUBREL;
|
||||
pendingAck.headerFlag = AsyncMqttClientInternals::HeaderFlag.PUBREL_RESERVED;
|
||||
pendingAck.packetId = packetId;
|
||||
log_i("snd PUBREL");
|
||||
|
||||
AsyncMqttClientInternals::OutPacket* msg = new AsyncMqttClientInternals::PubAckOutPacket(pendingAck);
|
||||
if (_head && _head->packetId() == packetId) {
|
||||
_head->release();
|
||||
log_i("PUB released");
|
||||
}
|
||||
_insert(msg);
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_onPubComp(uint16_t packetId) {
|
||||
_freeCurrentParsedPacket();
|
||||
|
||||
// _head points to the PUBREL package
|
||||
if (_head && _head->packetId() == packetId) {
|
||||
_head->release();
|
||||
log_i("PUBREL released");
|
||||
}
|
||||
|
||||
for (auto callback : _onPublishUserCallbacks) callback(packetId);
|
||||
_handleQueue(); // [vesper patch] send the next queued packet now, not on the next ~500ms poll
|
||||
}
|
||||
|
||||
void AsyncMqttClient::_sendPing() {
|
||||
log_i("PING");
|
||||
_lastPingRequestTime = millis();
|
||||
AsyncMqttClientInternals::OutPacket* msg = new AsyncMqttClientInternals::PingReqOutPacket;
|
||||
_addBack(msg);
|
||||
}
|
||||
|
||||
bool AsyncMqttClient::connected() const {
|
||||
return _state == CONNECTED;
|
||||
}
|
||||
|
||||
void AsyncMqttClient::connect() {
|
||||
if (_state != DISCONNECTED) return;
|
||||
log_i("CONNECTING");
|
||||
_state = CONNECTING;
|
||||
_disconnectReason = AsyncMqttClientDisconnectReason::TCP_DISCONNECTED; // reset any previous
|
||||
|
||||
_client.setRxTimeout(_keepAlive);
|
||||
|
||||
#if ASYNC_TCP_SSL_ENABLED
|
||||
if (_useIp) {
|
||||
_client.connect(_ip, _port, _secure);
|
||||
} else {
|
||||
_client.connect(_host, _port, _secure);
|
||||
}
|
||||
#else
|
||||
if (_useIp) {
|
||||
_client.connect(_ip, _port);
|
||||
} else {
|
||||
_client.connect(_host, _port);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void AsyncMqttClient::disconnect(bool force) {
|
||||
if (_state == DISCONNECTED) return;
|
||||
log_i("DISCONNECT (f:%d)", force);
|
||||
if (force) {
|
||||
_state = DISCONNECTED;
|
||||
_client.close(true);
|
||||
} else if (_state != DISCONNECTING) {
|
||||
_state = DISCONNECTING;
|
||||
AsyncMqttClientInternals::OutPacket* msg = new AsyncMqttClientInternals::DisconnOutPacket;
|
||||
_addBack(msg);
|
||||
}
|
||||
}
|
||||
|
||||
uint16_t AsyncMqttClient::subscribe(const char* topic, uint8_t qos) {
|
||||
if (_state != CONNECTED) return 0;
|
||||
log_i("SUBSCRIBE");
|
||||
|
||||
AsyncMqttClientInternals::OutPacket* msg = new AsyncMqttClientInternals::SubscribeOutPacket(topic, qos);
|
||||
_addBack(msg);
|
||||
return msg->packetId();
|
||||
}
|
||||
|
||||
uint16_t AsyncMqttClient::unsubscribe(const char* topic) {
|
||||
if (_state != CONNECTED) return 0;
|
||||
log_i("UNSUBSCRIBE");
|
||||
|
||||
AsyncMqttClientInternals::OutPacket* msg = new AsyncMqttClientInternals::UnsubscribeOutPacket(topic);
|
||||
_addBack(msg);
|
||||
return msg->packetId();
|
||||
}
|
||||
|
||||
uint16_t AsyncMqttClient::publish(const char* topic, uint8_t qos, bool retain, const char* payload, size_t length, bool dup, uint16_t message_id) {
|
||||
if (_state != CONNECTED || GET_FREE_MEMORY() < MQTT_MIN_FREE_MEMORY) return 0;
|
||||
log_i("PUBLISH");
|
||||
|
||||
AsyncMqttClientInternals::OutPacket* msg = new AsyncMqttClientInternals::PublishOutPacket(topic, qos, retain, payload, length);
|
||||
_addBack(msg);
|
||||
return msg->packetId();
|
||||
}
|
||||
|
||||
bool AsyncMqttClient::clearQueue() {
|
||||
if (_state != DISCONNECTED) return false;
|
||||
_clearQueue(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
const char* AsyncMqttClient::getClientId() const {
|
||||
return _clientId;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
#ifndef SRC_ASYNCMQTTCLIENT_H_
|
||||
#define SRC_ASYNCMQTTCLIENT_H_
|
||||
|
||||
#include "AsyncMqttClient.hpp"
|
||||
|
||||
#endif // SRC_ASYNCMQTTCLIENT_H_
|
||||
@@ -0,0 +1,179 @@
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
#include <vector>
|
||||
|
||||
#include "Arduino.h"
|
||||
|
||||
#ifndef MQTT_MIN_FREE_MEMORY
|
||||
#define MQTT_MIN_FREE_MEMORY 4096
|
||||
#endif
|
||||
|
||||
#ifdef ESP32
|
||||
#include <AsyncTCP.h>
|
||||
#include <freertos/semphr.h>
|
||||
#elif defined(ESP8266)
|
||||
#include <ESPAsyncTCP.h>
|
||||
#else
|
||||
#error Platform not supported
|
||||
#endif
|
||||
|
||||
#if ASYNC_TCP_SSL_ENABLED
|
||||
#include <tcp_axtls.h>
|
||||
#define SHA1_SIZE 20
|
||||
#endif
|
||||
|
||||
#include "AsyncMqttClient/Flags.hpp"
|
||||
#include "AsyncMqttClient/ParsingInformation.hpp"
|
||||
#include "AsyncMqttClient/MessageProperties.hpp"
|
||||
#include "AsyncMqttClient/Helpers.hpp"
|
||||
#include "AsyncMqttClient/Callbacks.hpp"
|
||||
#include "AsyncMqttClient/DisconnectReasons.hpp"
|
||||
#include "AsyncMqttClient/Storage.hpp"
|
||||
|
||||
#include "AsyncMqttClient/Packets/Packet.hpp"
|
||||
#include "AsyncMqttClient/Packets/ConnAckPacket.hpp"
|
||||
#include "AsyncMqttClient/Packets/PingRespPacket.hpp"
|
||||
#include "AsyncMqttClient/Packets/SubAckPacket.hpp"
|
||||
#include "AsyncMqttClient/Packets/UnsubAckPacket.hpp"
|
||||
#include "AsyncMqttClient/Packets/PublishPacket.hpp"
|
||||
#include "AsyncMqttClient/Packets/PubRelPacket.hpp"
|
||||
#include "AsyncMqttClient/Packets/PubAckPacket.hpp"
|
||||
#include "AsyncMqttClient/Packets/PubRecPacket.hpp"
|
||||
#include "AsyncMqttClient/Packets/PubCompPacket.hpp"
|
||||
|
||||
#include "AsyncMqttClient/Packets/Out/Connect.hpp"
|
||||
#include "AsyncMqttClient/Packets/Out/PingReq.hpp"
|
||||
#include "AsyncMqttClient/Packets/Out/PubAck.hpp"
|
||||
#include "AsyncMqttClient/Packets/Out/Disconn.hpp"
|
||||
#include "AsyncMqttClient/Packets/Out/Subscribe.hpp"
|
||||
#include "AsyncMqttClient/Packets/Out/Unsubscribe.hpp"
|
||||
#include "AsyncMqttClient/Packets/Out/Publish.hpp"
|
||||
|
||||
class AsyncMqttClient {
|
||||
public:
|
||||
AsyncMqttClient();
|
||||
~AsyncMqttClient();
|
||||
|
||||
AsyncMqttClient& setKeepAlive(uint16_t keepAlive);
|
||||
AsyncMqttClient& setClientId(const char* clientId);
|
||||
AsyncMqttClient& setCleanSession(bool cleanSession);
|
||||
AsyncMqttClient& setMaxTopicLength(uint16_t maxTopicLength);
|
||||
AsyncMqttClient& setCredentials(const char* username, const char* password = nullptr);
|
||||
AsyncMqttClient& setWill(const char* topic, uint8_t qos, bool retain, const char* payload = nullptr, size_t length = 0);
|
||||
AsyncMqttClient& setServer(IPAddress ip, uint16_t port);
|
||||
AsyncMqttClient& setServer(const char* host, uint16_t port);
|
||||
#if ASYNC_TCP_SSL_ENABLED
|
||||
AsyncMqttClient& setSecure(bool secure);
|
||||
AsyncMqttClient& addServerFingerprint(const uint8_t* fingerprint);
|
||||
#endif
|
||||
|
||||
AsyncMqttClient& onConnect(AsyncMqttClientInternals::OnConnectUserCallback callback);
|
||||
AsyncMqttClient& onDisconnect(AsyncMqttClientInternals::OnDisconnectUserCallback callback);
|
||||
AsyncMqttClient& onSubscribe(AsyncMqttClientInternals::OnSubscribeUserCallback callback);
|
||||
AsyncMqttClient& onUnsubscribe(AsyncMqttClientInternals::OnUnsubscribeUserCallback callback);
|
||||
AsyncMqttClient& onMessage(AsyncMqttClientInternals::OnMessageUserCallback callback);
|
||||
AsyncMqttClient& onPublish(AsyncMqttClientInternals::OnPublishUserCallback callback);
|
||||
|
||||
bool connected() const;
|
||||
void connect();
|
||||
void disconnect(bool force = false);
|
||||
uint16_t subscribe(const char* topic, uint8_t qos);
|
||||
uint16_t unsubscribe(const char* topic);
|
||||
uint16_t publish(const char* topic, uint8_t qos, bool retain, const char* payload = nullptr, size_t length = 0, bool dup = false, uint16_t message_id = 0);
|
||||
bool clearQueue(); // Not MQTT compliant!
|
||||
|
||||
const char* getClientId() const;
|
||||
|
||||
private:
|
||||
AsyncClient _client;
|
||||
AsyncMqttClientInternals::OutPacket* _head;
|
||||
AsyncMqttClientInternals::OutPacket* _tail;
|
||||
size_t _sent;
|
||||
enum {
|
||||
CONNECTING,
|
||||
CONNECTED,
|
||||
DISCONNECTING,
|
||||
DISCONNECTED
|
||||
} _state;
|
||||
AsyncMqttClientDisconnectReason _disconnectReason;
|
||||
uint32_t _lastClientActivity;
|
||||
uint32_t _lastServerActivity;
|
||||
uint32_t _lastPingRequestTime;
|
||||
|
||||
char _generatedClientId[18 + 1]; // esp8266-abc123 and esp32-abcdef123456
|
||||
IPAddress _ip;
|
||||
const char* _host;
|
||||
bool _useIp;
|
||||
#if ASYNC_TCP_SSL_ENABLED
|
||||
bool _secure;
|
||||
#endif
|
||||
uint16_t _port;
|
||||
uint16_t _keepAlive;
|
||||
bool _cleanSession;
|
||||
const char* _clientId;
|
||||
const char* _username;
|
||||
const char* _password;
|
||||
const char* _willTopic;
|
||||
const char* _willPayload;
|
||||
uint16_t _willPayloadLength;
|
||||
uint8_t _willQos;
|
||||
bool _willRetain;
|
||||
|
||||
#if ASYNC_TCP_SSL_ENABLED
|
||||
std::vector<std::array<uint8_t, SHA1_SIZE>> _secureServerFingerprints;
|
||||
#endif
|
||||
|
||||
std::vector<AsyncMqttClientInternals::OnConnectUserCallback> _onConnectUserCallbacks;
|
||||
std::vector<AsyncMqttClientInternals::OnDisconnectUserCallback> _onDisconnectUserCallbacks;
|
||||
std::vector<AsyncMqttClientInternals::OnSubscribeUserCallback> _onSubscribeUserCallbacks;
|
||||
std::vector<AsyncMqttClientInternals::OnUnsubscribeUserCallback> _onUnsubscribeUserCallbacks;
|
||||
std::vector<AsyncMqttClientInternals::OnMessageUserCallback> _onMessageUserCallbacks;
|
||||
std::vector<AsyncMqttClientInternals::OnPublishUserCallback> _onPublishUserCallbacks;
|
||||
|
||||
AsyncMqttClientInternals::ParsingInformation _parsingInformation;
|
||||
AsyncMqttClientInternals::Packet* _currentParsedPacket;
|
||||
uint8_t _remainingLengthBufferPosition;
|
||||
char _remainingLengthBuffer[4];
|
||||
|
||||
std::vector<AsyncMqttClientInternals::PendingPubRel> _pendingPubRels;
|
||||
|
||||
#if defined(ESP32)
|
||||
SemaphoreHandle_t _xSemaphore = nullptr;
|
||||
#elif defined(ESP8266)
|
||||
bool _xSemaphore = false;
|
||||
#endif
|
||||
|
||||
void _clear();
|
||||
void _freeCurrentParsedPacket();
|
||||
|
||||
// TCP
|
||||
void _onConnect();
|
||||
void _onDisconnect();
|
||||
// void _onError(int8_t error);
|
||||
// void _onTimeout();
|
||||
void _onAck(size_t len);
|
||||
void _onData(char* data, size_t len);
|
||||
void _onPoll();
|
||||
|
||||
// QUEUE
|
||||
void _insert(AsyncMqttClientInternals::OutPacket* packet); // for PUBREL
|
||||
void _addFront(AsyncMqttClientInternals::OutPacket* packet); // for CONNECT
|
||||
void _addBack(AsyncMqttClientInternals::OutPacket* packet); // all the rest
|
||||
void _handleQueue();
|
||||
void _clearQueue(bool keepSessionData);
|
||||
|
||||
// MQTT
|
||||
void _onPingResp();
|
||||
void _onConnAck(bool sessionPresent, uint8_t connectReturnCode);
|
||||
void _onSubAck(uint16_t packetId, char status);
|
||||
void _onUnsubAck(uint16_t packetId);
|
||||
void _onMessage(char* topic, char* payload, uint8_t qos, bool dup, bool retain, size_t len, size_t index, size_t total, uint16_t packetId);
|
||||
void _onPublish(uint16_t packetId, uint8_t qos);
|
||||
void _onPubRel(uint16_t packetId);
|
||||
void _onPubAck(uint16_t packetId);
|
||||
void _onPubRec(uint16_t packetId);
|
||||
void _onPubComp(uint16_t packetId);
|
||||
|
||||
void _sendPing();
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
|
||||
#include "DisconnectReasons.hpp"
|
||||
#include "MessageProperties.hpp"
|
||||
#include "Errors.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
// user callbacks
|
||||
typedef std::function<void(bool sessionPresent)> OnConnectUserCallback;
|
||||
typedef std::function<void(AsyncMqttClientDisconnectReason reason)> OnDisconnectUserCallback;
|
||||
typedef std::function<void(uint16_t packetId, uint8_t qos)> OnSubscribeUserCallback;
|
||||
typedef std::function<void(uint16_t packetId)> OnUnsubscribeUserCallback;
|
||||
typedef std::function<void(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total)> OnMessageUserCallback;
|
||||
typedef std::function<void(uint16_t packetId)> OnPublishUserCallback;
|
||||
typedef std::function<void(uint16_t packetId, AsyncMqttClientError error)> OnErrorUserCallback;
|
||||
|
||||
// internal callbacks
|
||||
typedef std::function<void(bool sessionPresent, uint8_t connectReturnCode)> OnConnAckInternalCallback;
|
||||
typedef std::function<void()> OnPingRespInternalCallback;
|
||||
typedef std::function<void(uint16_t packetId, char status)> OnSubAckInternalCallback;
|
||||
typedef std::function<void(uint16_t packetId)> OnUnsubAckInternalCallback;
|
||||
typedef std::function<void(char* topic, char* payload, uint8_t qos, bool dup, bool retain, size_t len, size_t index, size_t total, uint16_t packetId)> OnMessageInternalCallback;
|
||||
typedef std::function<void(uint16_t packetId, uint8_t qos)> OnPublishInternalCallback;
|
||||
typedef std::function<void(uint16_t packetId)> OnPubRelInternalCallback;
|
||||
typedef std::function<void(uint16_t packetId)> OnPubAckInternalCallback;
|
||||
typedef std::function<void(uint16_t packetId)> OnPubRecInternalCallback;
|
||||
typedef std::function<void(uint16_t packetId)> OnPubCompInternalCallback;
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
enum class AsyncMqttClientDisconnectReason : uint8_t {
|
||||
TCP_DISCONNECTED = 0,
|
||||
|
||||
MQTT_UNACCEPTABLE_PROTOCOL_VERSION = 1,
|
||||
MQTT_IDENTIFIER_REJECTED = 2,
|
||||
MQTT_SERVER_UNAVAILABLE = 3,
|
||||
MQTT_MALFORMED_CREDENTIALS = 4,
|
||||
MQTT_NOT_AUTHORIZED = 5,
|
||||
|
||||
ESP8266_NOT_ENOUGH_SPACE = 6,
|
||||
|
||||
TLS_BAD_FINGERPRINT = 7
|
||||
};
|
||||
@@ -0,0 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
enum class AsyncMqttClientError : uint8_t {
|
||||
MAX_RETRIES = 0,
|
||||
OUT_OF_MEMORY = 1
|
||||
};
|
||||
@@ -0,0 +1,57 @@
|
||||
#pragma once
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
constexpr struct {
|
||||
const uint8_t RESERVED = 0;
|
||||
const uint8_t CONNECT = 1;
|
||||
const uint8_t CONNACK = 2;
|
||||
const uint8_t PUBLISH = 3;
|
||||
const uint8_t PUBACK = 4;
|
||||
const uint8_t PUBREC = 5;
|
||||
const uint8_t PUBREL = 6;
|
||||
const uint8_t PUBCOMP = 7;
|
||||
const uint8_t SUBSCRIBE = 8;
|
||||
const uint8_t SUBACK = 9;
|
||||
const uint8_t UNSUBSCRIBE = 10;
|
||||
const uint8_t UNSUBACK = 11;
|
||||
const uint8_t PINGREQ = 12;
|
||||
const uint8_t PINGRESP = 13;
|
||||
const uint8_t DISCONNECT = 14;
|
||||
const uint8_t RESERVED2 = 1;
|
||||
} PacketType;
|
||||
|
||||
constexpr struct {
|
||||
const uint8_t CONNECT_RESERVED = 0x00;
|
||||
const uint8_t CONNACK_RESERVED = 0x00;
|
||||
const uint8_t PUBLISH_DUP = 0x08;
|
||||
const uint8_t PUBLISH_QOS0 = 0x00;
|
||||
const uint8_t PUBLISH_QOS1 = 0x02;
|
||||
const uint8_t PUBLISH_QOS2 = 0x04;
|
||||
const uint8_t PUBLISH_QOSRESERVED = 0x06;
|
||||
const uint8_t PUBLISH_RETAIN = 0x01;
|
||||
const uint8_t PUBACK_RESERVED = 0x00;
|
||||
const uint8_t PUBREC_RESERVED = 0x00;
|
||||
const uint8_t PUBREL_RESERVED = 0x02;
|
||||
const uint8_t PUBCOMP_RESERVED = 0x00;
|
||||
const uint8_t SUBSCRIBE_RESERVED = 0x02;
|
||||
const uint8_t SUBACK_RESERVED = 0x00;
|
||||
const uint8_t UNSUBSCRIBE_RESERVED = 0x02;
|
||||
const uint8_t UNSUBACK_RESERVED = 0x00;
|
||||
const uint8_t PINGREQ_RESERVED = 0x00;
|
||||
const uint8_t PINGRESP_RESERVED = 0x00;
|
||||
const uint8_t DISCONNECT_RESERVED = 0x00;
|
||||
const uint8_t RESERVED2_RESERVED = 0x00;
|
||||
} HeaderFlag;
|
||||
|
||||
constexpr struct {
|
||||
const uint8_t USERNAME = 0x80;
|
||||
const uint8_t PASSWORD = 0x40;
|
||||
const uint8_t WILL_RETAIN = 0x20;
|
||||
const uint8_t WILL_QOS0 = 0x00;
|
||||
const uint8_t WILL_QOS1 = 0x08;
|
||||
const uint8_t WILL_QOS2 = 0x10;
|
||||
const uint8_t WILL = 0x04;
|
||||
const uint8_t CLEAN_SESSION = 0x02;
|
||||
const uint8_t RESERVED = 0x00;
|
||||
} ConnectFlag;
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,61 @@
|
||||
#pragma once
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class Helpers {
|
||||
public:
|
||||
static uint32_t decodeRemainingLength(char* bytes) {
|
||||
uint32_t multiplier = 1;
|
||||
uint32_t value = 0;
|
||||
uint8_t currentByte = 0;
|
||||
uint8_t encodedByte;
|
||||
do {
|
||||
encodedByte = bytes[currentByte++];
|
||||
value += (encodedByte & 127) * multiplier;
|
||||
multiplier *= 128;
|
||||
} while ((encodedByte & 128) != 0);
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
static uint8_t encodeRemainingLength(uint32_t remainingLength, char* destination) {
|
||||
uint8_t currentByte = 0;
|
||||
uint8_t bytesNeeded = 0;
|
||||
|
||||
do {
|
||||
uint8_t encodedByte = remainingLength % 128;
|
||||
remainingLength /= 128;
|
||||
if (remainingLength > 0) {
|
||||
encodedByte = encodedByte | 128;
|
||||
}
|
||||
|
||||
destination[currentByte++] = encodedByte;
|
||||
bytesNeeded++;
|
||||
} while (remainingLength > 0);
|
||||
|
||||
return bytesNeeded;
|
||||
}
|
||||
};
|
||||
|
||||
#if defined(ARDUINO_ARCH_ESP32)
|
||||
#define SEMAPHORE_TAKE() xSemaphoreTake(_xSemaphore, portMAX_DELAY)
|
||||
#define SEMAPHORE_GIVE() xSemaphoreGive(_xSemaphore)
|
||||
#define GET_FREE_MEMORY() ESP.getMaxAllocHeap()
|
||||
#include <esp32-hal-log.h>
|
||||
#elif defined(ARDUINO_ARCH_ESP8266)
|
||||
#define SEMAPHORE_TAKE(X) while (_xSemaphore) { /*ESP.wdtFeed();*/ } _xSemaphore = true
|
||||
#define SEMAPHORE_GIVE() _xSemaphore = false
|
||||
#define GET_FREE_MEMORY() ESP.getMaxFreeBlockSize()
|
||||
#if defined(DEBUG_ESP_PORT) && defined(DEBUG_ASYNC_MQTT_CLIENT)
|
||||
#define log_i(...) DEBUG_ESP_PORT.printf(__VA_ARGS__); DEBUG_ESP_PORT.print("\n")
|
||||
#define log_e(...) DEBUG_ESP_PORT.printf(__VA_ARGS__); DEBUG_ESP_PORT.print("\n")
|
||||
#define log_w(...) DEBUG_ESP_PORT.printf(__VA_ARGS__); DEBUG_ESP_PORT.print("\n")
|
||||
#else
|
||||
#define log_i(...)
|
||||
#define log_e(...)
|
||||
#define log_w(...)
|
||||
#endif
|
||||
#else
|
||||
#pragma error "No valid architecture"
|
||||
#endif
|
||||
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
struct AsyncMqttClientMessageProperties {
|
||||
uint8_t qos;
|
||||
bool dup;
|
||||
bool retain;
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
#include "ConnAckPacket.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::ConnAckPacket;
|
||||
|
||||
ConnAckPacket::ConnAckPacket(ParsingInformation* parsingInformation, OnConnAckInternalCallback callback)
|
||||
: _parsingInformation(parsingInformation)
|
||||
, _callback(callback)
|
||||
, _bytePosition(0)
|
||||
, _sessionPresent(false)
|
||||
, _connectReturnCode(0) {
|
||||
}
|
||||
|
||||
ConnAckPacket::~ConnAckPacket() {
|
||||
}
|
||||
|
||||
void ConnAckPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition) {
|
||||
char currentByte = data[(*currentBytePosition)++];
|
||||
if (_bytePosition++ == 0) {
|
||||
_sessionPresent = (currentByte << 7) >> 7;
|
||||
} else {
|
||||
_connectReturnCode = currentByte;
|
||||
_parsingInformation->bufferState = BufferState::NONE;
|
||||
_callback(_sessionPresent, _connectReturnCode);
|
||||
}
|
||||
}
|
||||
|
||||
void ConnAckPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition) {
|
||||
(void)data;
|
||||
(void)currentBytePosition;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include "Arduino.h"
|
||||
#include "Packet.hpp"
|
||||
#include "../ParsingInformation.hpp"
|
||||
#include "../Callbacks.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class ConnAckPacket : public Packet {
|
||||
public:
|
||||
explicit ConnAckPacket(ParsingInformation* parsingInformation, OnConnAckInternalCallback callback);
|
||||
~ConnAckPacket();
|
||||
|
||||
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
|
||||
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
|
||||
|
||||
private:
|
||||
ParsingInformation* _parsingInformation;
|
||||
OnConnAckInternalCallback _callback;
|
||||
|
||||
uint8_t _bytePosition;
|
||||
bool _sessionPresent;
|
||||
uint8_t _connectReturnCode;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,162 @@
|
||||
#include "Connect.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::ConnectOutPacket;
|
||||
|
||||
ConnectOutPacket::ConnectOutPacket(bool cleanSession,
|
||||
const char* username,
|
||||
const char* password,
|
||||
const char* willTopic,
|
||||
bool willRetain,
|
||||
uint8_t willQos,
|
||||
const char* willPayload,
|
||||
uint16_t willPayloadLength,
|
||||
uint16_t keepAlive,
|
||||
const char* clientId) {
|
||||
char fixedHeader[5];
|
||||
fixedHeader[0] = AsyncMqttClientInternals::PacketType.CONNECT;
|
||||
fixedHeader[0] = fixedHeader[0] << 4;
|
||||
fixedHeader[0] = fixedHeader[0] | AsyncMqttClientInternals::HeaderFlag.CONNECT_RESERVED;
|
||||
|
||||
uint16_t protocolNameLength = 4;
|
||||
char protocolNameLengthBytes[2];
|
||||
protocolNameLengthBytes[0] = protocolNameLength >> 8;
|
||||
protocolNameLengthBytes[1] = protocolNameLength & 0xFF;
|
||||
|
||||
char protocolLevel[1];
|
||||
protocolLevel[0] = 0x04;
|
||||
|
||||
char connectFlags[1];
|
||||
connectFlags[0] = 0;
|
||||
if (cleanSession) connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.CLEAN_SESSION;
|
||||
if (username != nullptr) connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.USERNAME;
|
||||
if (password != nullptr) connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.PASSWORD;
|
||||
if (willTopic != nullptr) {
|
||||
connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.WILL;
|
||||
if (willRetain) connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.WILL_RETAIN;
|
||||
switch (willQos) {
|
||||
case 0:
|
||||
connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.WILL_QOS0;
|
||||
break;
|
||||
case 1:
|
||||
connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.WILL_QOS1;
|
||||
break;
|
||||
case 2:
|
||||
connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.WILL_QOS2;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
char keepAliveBytes[2];
|
||||
keepAliveBytes[0] = keepAlive >> 8;
|
||||
keepAliveBytes[1] = keepAlive & 0xFF;
|
||||
|
||||
uint16_t clientIdLength = strlen(clientId);
|
||||
char clientIdLengthBytes[2];
|
||||
clientIdLengthBytes[0] = clientIdLength >> 8;
|
||||
clientIdLengthBytes[1] = clientIdLength & 0xFF;
|
||||
|
||||
// Optional fields
|
||||
uint16_t willTopicLength = 0;
|
||||
char willTopicLengthBytes[2];
|
||||
char willPayloadLengthBytes[2];
|
||||
if (willTopic != nullptr) {
|
||||
willTopicLength = strlen(willTopic);
|
||||
willTopicLengthBytes[0] = willTopicLength >> 8;
|
||||
willTopicLengthBytes[1] = willTopicLength & 0xFF;
|
||||
|
||||
if (willPayload != nullptr && willPayloadLength == 0) willPayloadLength = strlen(willPayload);
|
||||
|
||||
willPayloadLengthBytes[0] = willPayloadLength >> 8;
|
||||
willPayloadLengthBytes[1] = willPayloadLength & 0xFF;
|
||||
}
|
||||
|
||||
uint16_t usernameLength = 0;
|
||||
char usernameLengthBytes[2];
|
||||
if (username != nullptr) {
|
||||
usernameLength = strlen(username);
|
||||
usernameLengthBytes[0] = usernameLength >> 8;
|
||||
usernameLengthBytes[1] = usernameLength & 0xFF;
|
||||
}
|
||||
|
||||
uint16_t passwordLength = 0;
|
||||
char passwordLengthBytes[2];
|
||||
if (password != nullptr) {
|
||||
passwordLength = strlen(password);
|
||||
passwordLengthBytes[0] = passwordLength >> 8;
|
||||
passwordLengthBytes[1] = passwordLength & 0xFF;
|
||||
}
|
||||
|
||||
uint32_t remainingLength = 2 + protocolNameLength + 1 + 1 + 2 + 2 + clientIdLength; // always present
|
||||
if (willTopic != nullptr) remainingLength += 2 + willTopicLength + 2 + willPayloadLength;
|
||||
if (username != nullptr) remainingLength += 2 + usernameLength;
|
||||
if (password != nullptr) remainingLength += 2 + passwordLength;
|
||||
uint8_t remainingLengthLength = AsyncMqttClientInternals::Helpers::encodeRemainingLength(remainingLength, fixedHeader + 1);
|
||||
|
||||
uint32_t neededSpace = 1 + remainingLengthLength;
|
||||
neededSpace += 2;
|
||||
neededSpace += protocolNameLength;
|
||||
neededSpace += 1;
|
||||
neededSpace += 1;
|
||||
neededSpace += 2;
|
||||
neededSpace += 2;
|
||||
neededSpace += clientIdLength;
|
||||
if (willTopic != nullptr) {
|
||||
neededSpace += 2;
|
||||
neededSpace += willTopicLength;
|
||||
|
||||
neededSpace += 2;
|
||||
if (willPayload != nullptr) neededSpace += willPayloadLength;
|
||||
}
|
||||
if (username != nullptr) {
|
||||
neededSpace += 2;
|
||||
neededSpace += usernameLength;
|
||||
}
|
||||
if (password != nullptr) {
|
||||
neededSpace += 2;
|
||||
neededSpace += passwordLength;
|
||||
}
|
||||
|
||||
_data.reserve(neededSpace);
|
||||
|
||||
_data.insert(_data.end(), fixedHeader, fixedHeader + 1 + remainingLengthLength);
|
||||
|
||||
_data.push_back(protocolNameLengthBytes[0]);
|
||||
_data.push_back(protocolNameLengthBytes[1]);
|
||||
|
||||
_data.push_back('M');
|
||||
_data.push_back('Q');
|
||||
_data.push_back('T');
|
||||
_data.push_back('T');
|
||||
|
||||
_data.push_back(protocolLevel[0]);
|
||||
_data.push_back(connectFlags[0]);
|
||||
_data.push_back(keepAliveBytes[0]);
|
||||
_data.push_back(keepAliveBytes[1]);
|
||||
_data.push_back(clientIdLengthBytes[0]);
|
||||
_data.push_back(clientIdLengthBytes[1]);
|
||||
|
||||
_data.insert(_data.end(), clientId, clientId + clientIdLength);
|
||||
if (willTopic != nullptr) {
|
||||
_data.insert(_data.end(), willTopicLengthBytes, willTopicLengthBytes + 2);
|
||||
_data.insert(_data.end(), willTopic, willTopic + willTopicLength);
|
||||
|
||||
_data.insert(_data.end(), willPayloadLengthBytes, willPayloadLengthBytes + 2);
|
||||
if (willPayload != nullptr) _data.insert(_data.end(), willPayload, willPayload + willPayloadLength);
|
||||
}
|
||||
if (username != nullptr) {
|
||||
_data.insert(_data.end(), usernameLengthBytes, usernameLengthBytes + 2);
|
||||
_data.insert(_data.end(), username, username + usernameLength);
|
||||
}
|
||||
if (password != nullptr) {
|
||||
_data.insert(_data.end(), passwordLengthBytes, passwordLengthBytes + 2);
|
||||
_data.insert(_data.end(), password, password + passwordLength);
|
||||
}
|
||||
}
|
||||
|
||||
const uint8_t* ConnectOutPacket::data(size_t index) const {
|
||||
return &_data.data()[index];
|
||||
}
|
||||
|
||||
size_t ConnectOutPacket::size() const {
|
||||
return _data.size();
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
#include <cstring> // strlen
|
||||
|
||||
#include "OutPacket.hpp"
|
||||
#include "../../Flags.hpp"
|
||||
#include "../../Helpers.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class ConnectOutPacket : public OutPacket {
|
||||
public:
|
||||
ConnectOutPacket(bool cleanSession,
|
||||
const char* username,
|
||||
const char* password,
|
||||
const char* willTopic,
|
||||
bool willRetain,
|
||||
uint8_t willQos,
|
||||
const char* willPayload,
|
||||
uint16_t willPayloadLength,
|
||||
uint16_t keepAlive,
|
||||
const char* clientId);
|
||||
const uint8_t* data(size_t index = 0) const;
|
||||
size_t size() const;
|
||||
|
||||
private:
|
||||
std::vector<uint8_t> _data;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,18 @@
|
||||
#include "Disconn.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::DisconnOutPacket;
|
||||
|
||||
DisconnOutPacket::DisconnOutPacket() {
|
||||
_data[0] = AsyncMqttClientInternals::PacketType.DISCONNECT;
|
||||
_data[0] = _data[0] << 4;
|
||||
_data[0] = _data[0] | AsyncMqttClientInternals::HeaderFlag.DISCONNECT_RESERVED;
|
||||
_data[1] = 0;
|
||||
}
|
||||
|
||||
const uint8_t* DisconnOutPacket::data(size_t index) const {
|
||||
return &_data[index];
|
||||
}
|
||||
|
||||
size_t DisconnOutPacket::size() const {
|
||||
return 2;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include "OutPacket.hpp"
|
||||
#include "../../Flags.hpp"
|
||||
#include "../../Helpers.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class DisconnOutPacket : public OutPacket {
|
||||
public:
|
||||
DisconnOutPacket();
|
||||
const uint8_t* data(size_t index = 0) const;
|
||||
size_t size() const;
|
||||
|
||||
private:
|
||||
uint8_t _data[2];
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,44 @@
|
||||
#include "OutPacket.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::OutPacket;
|
||||
|
||||
OutPacket::OutPacket()
|
||||
: next(nullptr)
|
||||
, timeout(0)
|
||||
, noTries(0)
|
||||
, _released(true)
|
||||
, _packetId(0) {}
|
||||
|
||||
OutPacket::~OutPacket() {}
|
||||
|
||||
bool OutPacket::released() const {
|
||||
return _released;
|
||||
}
|
||||
|
||||
uint8_t OutPacket::packetType() const {
|
||||
return data(0)[0] >> 4;
|
||||
}
|
||||
|
||||
uint16_t OutPacket::packetId() const {
|
||||
return _packetId;
|
||||
}
|
||||
|
||||
uint8_t OutPacket::qos() const {
|
||||
if (packetType() == AsyncMqttClientInternals::PacketType.PUBLISH) {
|
||||
return (data()[1] & 0x06) >> 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void OutPacket::release() {
|
||||
_released = true;
|
||||
}
|
||||
|
||||
uint16_t OutPacket::_nextPacketId = 0;
|
||||
|
||||
uint16_t OutPacket::_getNextPacketId() {
|
||||
if (++_nextPacketId == 0) {
|
||||
++_nextPacketId;
|
||||
}
|
||||
return _nextPacketId;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h> // uint*_t
|
||||
#include <stddef.h> // size_t
|
||||
#include <algorithm> // std::min
|
||||
|
||||
#include "../../Flags.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class OutPacket {
|
||||
public:
|
||||
OutPacket();
|
||||
virtual ~OutPacket();
|
||||
virtual const uint8_t* data(size_t index = 0) const = 0;
|
||||
virtual size_t size() const = 0;
|
||||
bool released() const;
|
||||
uint8_t packetType() const;
|
||||
uint16_t packetId() const;
|
||||
uint8_t qos() const;
|
||||
void release();
|
||||
|
||||
public:
|
||||
OutPacket* next;
|
||||
uint32_t timeout;
|
||||
uint8_t noTries;
|
||||
|
||||
protected:
|
||||
static uint16_t _getNextPacketId();
|
||||
bool _released;
|
||||
uint16_t _packetId;
|
||||
|
||||
private:
|
||||
static uint16_t _nextPacketId;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,18 @@
|
||||
#include "PingReq.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::PingReqOutPacket;
|
||||
|
||||
PingReqOutPacket::PingReqOutPacket() {
|
||||
_data[0] = AsyncMqttClientInternals::PacketType.PINGREQ;
|
||||
_data[0] = _data[0] << 4;
|
||||
_data[0] = _data[0] | AsyncMqttClientInternals::HeaderFlag.PINGREQ_RESERVED;
|
||||
_data[1] = 0;
|
||||
}
|
||||
|
||||
const uint8_t* PingReqOutPacket::data(size_t index) const {
|
||||
return &_data[index];;
|
||||
}
|
||||
|
||||
size_t PingReqOutPacket::size() const {
|
||||
return 2;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include "OutPacket.hpp"
|
||||
#include "../../Flags.hpp"
|
||||
#include "../../Helpers.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class PingReqOutPacket : public OutPacket {
|
||||
public:
|
||||
PingReqOutPacket();
|
||||
const uint8_t* data(size_t index = 0) const;
|
||||
size_t size() const;
|
||||
|
||||
private:
|
||||
uint8_t _data[2];
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,25 @@
|
||||
#include "PubAck.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::PubAckOutPacket;
|
||||
|
||||
PubAckOutPacket::PubAckOutPacket(PendingAck pendingAck) {
|
||||
_data[0] = pendingAck.packetType;
|
||||
_data[0] = _data[0] << 4;
|
||||
_data[0] = _data[0] | pendingAck.headerFlag;
|
||||
_data[1] = 2;
|
||||
_packetId = pendingAck.packetId;
|
||||
_data[2] = pendingAck.packetId >> 8;
|
||||
_data[3] = pendingAck.packetId & 0xFF;
|
||||
if (packetType() == AsyncMqttClientInternals::PacketType.PUBREL ||
|
||||
packetType() == AsyncMqttClientInternals::PacketType.PUBREC) {
|
||||
_released = false;
|
||||
}
|
||||
}
|
||||
|
||||
const uint8_t* PubAckOutPacket::data(size_t index) const {
|
||||
return &_data[index];
|
||||
}
|
||||
|
||||
size_t PubAckOutPacket::size() const {
|
||||
return 4;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
|
||||
#include "OutPacket.hpp"
|
||||
#include "../../Flags.hpp"
|
||||
#include "../../Helpers.hpp"
|
||||
#include "../../Storage.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class PubAckOutPacket : public OutPacket {
|
||||
public:
|
||||
explicit PubAckOutPacket(PendingAck pendingAck);
|
||||
const uint8_t* data(size_t index = 0) const;
|
||||
size_t size() const;
|
||||
|
||||
private:
|
||||
uint8_t _data[4];
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,69 @@
|
||||
#include "Publish.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::PublishOutPacket;
|
||||
|
||||
PublishOutPacket::PublishOutPacket(const char* topic, uint8_t qos, bool retain, const char* payload, size_t length) {
|
||||
char fixedHeader[5];
|
||||
fixedHeader[0] = AsyncMqttClientInternals::PacketType.PUBLISH;
|
||||
fixedHeader[0] = fixedHeader[0] << 4;
|
||||
// if (dup) fixedHeader[0] |= AsyncMqttClientInternals::HeaderFlag.PUBLISH_DUP;
|
||||
if (retain) fixedHeader[0] |= AsyncMqttClientInternals::HeaderFlag.PUBLISH_RETAIN;
|
||||
switch (qos) {
|
||||
case 0:
|
||||
fixedHeader[0] |= AsyncMqttClientInternals::HeaderFlag.PUBLISH_QOS0;
|
||||
break;
|
||||
case 1:
|
||||
fixedHeader[0] |= AsyncMqttClientInternals::HeaderFlag.PUBLISH_QOS1;
|
||||
break;
|
||||
case 2:
|
||||
fixedHeader[0] |= AsyncMqttClientInternals::HeaderFlag.PUBLISH_QOS2;
|
||||
break;
|
||||
}
|
||||
|
||||
uint16_t topicLength = strlen(topic);
|
||||
char topicLengthBytes[2];
|
||||
topicLengthBytes[0] = topicLength >> 8;
|
||||
topicLengthBytes[1] = topicLength & 0xFF;
|
||||
|
||||
uint32_t payloadLength = length;
|
||||
if (payload != nullptr && payloadLength == 0) payloadLength = strlen(payload);
|
||||
|
||||
uint32_t remainingLength = 2 + topicLength + payloadLength;
|
||||
if (qos != 0) remainingLength += 2;
|
||||
uint8_t remainingLengthLength = AsyncMqttClientInternals::Helpers::encodeRemainingLength(remainingLength, fixedHeader + 1);
|
||||
|
||||
size_t neededSpace = 0;
|
||||
neededSpace += 1 + remainingLengthLength;
|
||||
neededSpace += 2;
|
||||
neededSpace += topicLength;
|
||||
if (qos != 0) neededSpace += 2;
|
||||
if (payload != nullptr) neededSpace += payloadLength;
|
||||
|
||||
_data.reserve(neededSpace);
|
||||
|
||||
_packetId = (qos !=0) ? _getNextPacketId() : 1;
|
||||
char packetIdBytes[2];
|
||||
packetIdBytes[0] = _packetId >> 8;
|
||||
packetIdBytes[1] = _packetId & 0xFF;
|
||||
|
||||
_data.insert(_data.end(), fixedHeader, fixedHeader + 1 + remainingLengthLength);
|
||||
_data.insert(_data.end(), topicLengthBytes, topicLengthBytes + 2);
|
||||
_data.insert(_data.end(), topic, topic + topicLength);
|
||||
if (qos != 0) {
|
||||
_data.insert(_data.end(), packetIdBytes, packetIdBytes + 2);
|
||||
_released = false;
|
||||
}
|
||||
if (payload != nullptr) _data.insert(_data.end(), payload, payload + payloadLength);
|
||||
}
|
||||
|
||||
const uint8_t* PublishOutPacket::data(size_t index) const {
|
||||
return &_data.data()[index];
|
||||
}
|
||||
|
||||
size_t PublishOutPacket::size() const {
|
||||
return _data.size();
|
||||
}
|
||||
|
||||
void PublishOutPacket::setDup() {
|
||||
_data[0] |= AsyncMqttClientInternals::HeaderFlag.PUBLISH_DUP;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstring> // strlen
|
||||
#include <vector>
|
||||
|
||||
#include "OutPacket.hpp"
|
||||
#include "../../Flags.hpp"
|
||||
#include "../../Helpers.hpp"
|
||||
#include "../../Storage.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class PublishOutPacket : public OutPacket {
|
||||
public:
|
||||
PublishOutPacket(const char* topic, uint8_t qos, bool retain, const char* payload, size_t length);
|
||||
const uint8_t* data(size_t index = 0) const;
|
||||
size_t size() const;
|
||||
|
||||
void setDup(); // you cannot unset dup
|
||||
|
||||
private:
|
||||
std::vector<uint8_t> _data;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,49 @@
|
||||
#include "Subscribe.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::SubscribeOutPacket;
|
||||
|
||||
SubscribeOutPacket::SubscribeOutPacket(const char* topic, uint8_t qos) {
|
||||
char fixedHeader[5];
|
||||
fixedHeader[0] = AsyncMqttClientInternals::PacketType.SUBSCRIBE;
|
||||
fixedHeader[0] = fixedHeader[0] << 4;
|
||||
fixedHeader[0] = fixedHeader[0] | AsyncMqttClientInternals::HeaderFlag.SUBSCRIBE_RESERVED;
|
||||
|
||||
uint16_t topicLength = strlen(topic);
|
||||
char topicLengthBytes[2];
|
||||
topicLengthBytes[0] = topicLength >> 8;
|
||||
topicLengthBytes[1] = topicLength & 0xFF;
|
||||
|
||||
char qosByte[1];
|
||||
qosByte[0] = qos;
|
||||
|
||||
uint8_t remainingLengthLength = AsyncMqttClientInternals::Helpers::encodeRemainingLength(2 + 2 + topicLength + 1, fixedHeader + 1);
|
||||
|
||||
size_t neededSpace = 0;
|
||||
neededSpace += 1 + remainingLengthLength;
|
||||
neededSpace += 2;
|
||||
neededSpace += 2;
|
||||
neededSpace += topicLength;
|
||||
neededSpace += 1;
|
||||
|
||||
_data.reserve(neededSpace);
|
||||
|
||||
_packetId = _getNextPacketId();
|
||||
char packetIdBytes[2];
|
||||
packetIdBytes[0] = _packetId >> 8;
|
||||
packetIdBytes[1] = _packetId & 0xFF;
|
||||
|
||||
_data.insert(_data.end(), fixedHeader, fixedHeader + 1 + remainingLengthLength);
|
||||
_data.insert(_data.end(), packetIdBytes, packetIdBytes + 2);
|
||||
_data.insert(_data.end(), topicLengthBytes, topicLengthBytes + 2);
|
||||
_data.insert(_data.end(), topic, topic + topicLength);
|
||||
_data.push_back(qosByte[0]);
|
||||
_released = false;
|
||||
}
|
||||
|
||||
const uint8_t* SubscribeOutPacket::data(size_t index) const {
|
||||
return &_data.data()[index];
|
||||
}
|
||||
|
||||
size_t SubscribeOutPacket::size() const {
|
||||
return _data.size();
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstring> // strlen
|
||||
#include <vector>
|
||||
|
||||
#include "OutPacket.hpp"
|
||||
#include "../../Flags.hpp"
|
||||
#include "../../Helpers.hpp"
|
||||
#include "../../Storage.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class SubscribeOutPacket : public OutPacket {
|
||||
public:
|
||||
SubscribeOutPacket(const char* topic, uint8_t qos);
|
||||
const uint8_t* data(size_t index = 0) const;
|
||||
size_t size() const;
|
||||
|
||||
private:
|
||||
std::vector<uint8_t> _data;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,42 @@
|
||||
#include "Unsubscribe.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::UnsubscribeOutPacket;
|
||||
|
||||
UnsubscribeOutPacket::UnsubscribeOutPacket(const char* topic) {
|
||||
char fixedHeader[5];
|
||||
fixedHeader[0] = AsyncMqttClientInternals::PacketType.UNSUBSCRIBE;
|
||||
fixedHeader[0] = fixedHeader[0] << 4;
|
||||
fixedHeader[0] = fixedHeader[0] | AsyncMqttClientInternals::HeaderFlag.UNSUBSCRIBE_RESERVED;
|
||||
|
||||
uint16_t topicLength = strlen(topic);
|
||||
char topicLengthBytes[2];
|
||||
topicLengthBytes[0] = topicLength >> 8;
|
||||
topicLengthBytes[1] = topicLength & 0xFF;
|
||||
|
||||
uint8_t remainingLengthLength = AsyncMqttClientInternals::Helpers::encodeRemainingLength(2 + 2 + topicLength, fixedHeader + 1);
|
||||
|
||||
size_t neededSpace = 0;
|
||||
neededSpace += 1 + remainingLengthLength;
|
||||
neededSpace += 2;
|
||||
neededSpace += 2;
|
||||
neededSpace += topicLength;
|
||||
|
||||
_packetId = _getNextPacketId();
|
||||
char packetIdBytes[2];
|
||||
packetIdBytes[0] = _packetId >> 8;
|
||||
packetIdBytes[1] = _packetId & 0xFF;
|
||||
|
||||
_data.insert(_data.end(), fixedHeader, fixedHeader + 1 + remainingLengthLength);
|
||||
_data.insert(_data.end(), packetIdBytes, packetIdBytes + 2);
|
||||
_data.insert(_data.end(), topicLengthBytes, topicLengthBytes + 2);
|
||||
_data.insert(_data.end(), topic, topic + topicLength);
|
||||
_released = false;
|
||||
}
|
||||
|
||||
const uint8_t* UnsubscribeOutPacket::data(size_t index) const {
|
||||
return &_data.data()[index];
|
||||
}
|
||||
|
||||
size_t UnsubscribeOutPacket::size() const {
|
||||
return _data.size();
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstring> // strlen
|
||||
#include <vector>
|
||||
|
||||
#include "OutPacket.hpp"
|
||||
#include "../../Flags.hpp"
|
||||
#include "../../Helpers.hpp"
|
||||
#include "../../Storage.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class UnsubscribeOutPacket : public OutPacket {
|
||||
public:
|
||||
explicit UnsubscribeOutPacket(const char* topic);
|
||||
const uint8_t* data(size_t index = 0) const;
|
||||
size_t size() const;
|
||||
|
||||
private:
|
||||
std::vector<uint8_t> _data;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class Packet {
|
||||
public:
|
||||
virtual ~Packet() {}
|
||||
|
||||
virtual void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition) = 0;
|
||||
virtual void parsePayload(char* data, size_t len, size_t* currentBytePosition) = 0;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,21 @@
|
||||
#include "PingRespPacket.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::PingRespPacket;
|
||||
|
||||
PingRespPacket::PingRespPacket(ParsingInformation* parsingInformation, OnPingRespInternalCallback callback)
|
||||
: _parsingInformation(parsingInformation)
|
||||
, _callback(callback) {
|
||||
}
|
||||
|
||||
PingRespPacket::~PingRespPacket() {
|
||||
}
|
||||
|
||||
void PingRespPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition) {
|
||||
(void)data;
|
||||
(void)currentBytePosition;
|
||||
}
|
||||
|
||||
void PingRespPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition) {
|
||||
(void)data;
|
||||
(void)currentBytePosition;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
|
||||
#include "Arduino.h"
|
||||
#include "Packet.hpp"
|
||||
#include "../ParsingInformation.hpp"
|
||||
#include "../Callbacks.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class PingRespPacket : public Packet {
|
||||
public:
|
||||
explicit PingRespPacket(ParsingInformation* parsingInformation, OnPingRespInternalCallback callback);
|
||||
~PingRespPacket();
|
||||
|
||||
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
|
||||
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
|
||||
|
||||
private:
|
||||
ParsingInformation* _parsingInformation;
|
||||
OnPingRespInternalCallback _callback;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,30 @@
|
||||
#include "PubAckPacket.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::PubAckPacket;
|
||||
|
||||
PubAckPacket::PubAckPacket(ParsingInformation* parsingInformation, OnPubAckInternalCallback callback)
|
||||
: _parsingInformation(parsingInformation)
|
||||
, _callback(callback)
|
||||
, _bytePosition(0)
|
||||
, _packetIdMsb(0)
|
||||
, _packetId(0) {
|
||||
}
|
||||
|
||||
PubAckPacket::~PubAckPacket() {
|
||||
}
|
||||
|
||||
void PubAckPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition) {
|
||||
char currentByte = data[(*currentBytePosition)++];
|
||||
if (_bytePosition++ == 0) {
|
||||
_packetIdMsb = currentByte;
|
||||
} else {
|
||||
_packetId = currentByte | _packetIdMsb << 8;
|
||||
_parsingInformation->bufferState = BufferState::NONE;
|
||||
_callback(_packetId);
|
||||
}
|
||||
}
|
||||
|
||||
void PubAckPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition) {
|
||||
(void)data;
|
||||
(void)currentBytePosition;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include "Arduino.h"
|
||||
#include "Packet.hpp"
|
||||
#include "../ParsingInformation.hpp"
|
||||
#include "../Callbacks.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class PubAckPacket : public Packet {
|
||||
public:
|
||||
explicit PubAckPacket(ParsingInformation* parsingInformation, OnPubAckInternalCallback callback);
|
||||
~PubAckPacket();
|
||||
|
||||
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
|
||||
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
|
||||
|
||||
private:
|
||||
ParsingInformation* _parsingInformation;
|
||||
OnPubAckInternalCallback _callback;
|
||||
|
||||
uint8_t _bytePosition;
|
||||
char _packetIdMsb;
|
||||
uint16_t _packetId;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,30 @@
|
||||
#include "PubCompPacket.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::PubCompPacket;
|
||||
|
||||
PubCompPacket::PubCompPacket(ParsingInformation* parsingInformation, OnPubCompInternalCallback callback)
|
||||
: _parsingInformation(parsingInformation)
|
||||
, _callback(callback)
|
||||
, _bytePosition(0)
|
||||
, _packetIdMsb(0)
|
||||
, _packetId(0) {
|
||||
}
|
||||
|
||||
PubCompPacket::~PubCompPacket() {
|
||||
}
|
||||
|
||||
void PubCompPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition) {
|
||||
char currentByte = data[(*currentBytePosition)++];
|
||||
if (_bytePosition++ == 0) {
|
||||
_packetIdMsb = currentByte;
|
||||
} else {
|
||||
_packetId = currentByte | _packetIdMsb << 8;
|
||||
_parsingInformation->bufferState = BufferState::NONE;
|
||||
_callback(_packetId);
|
||||
}
|
||||
}
|
||||
|
||||
void PubCompPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition) {
|
||||
(void)data;
|
||||
(void)currentBytePosition;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include "Arduino.h"
|
||||
#include "Packet.hpp"
|
||||
#include "../ParsingInformation.hpp"
|
||||
#include "../Callbacks.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class PubCompPacket : public Packet {
|
||||
public:
|
||||
explicit PubCompPacket(ParsingInformation* parsingInformation, OnPubCompInternalCallback callback);
|
||||
~PubCompPacket();
|
||||
|
||||
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
|
||||
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
|
||||
|
||||
private:
|
||||
ParsingInformation* _parsingInformation;
|
||||
OnPubCompInternalCallback _callback;
|
||||
|
||||
uint8_t _bytePosition;
|
||||
char _packetIdMsb;
|
||||
uint16_t _packetId;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,30 @@
|
||||
#include "PubRecPacket.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::PubRecPacket;
|
||||
|
||||
PubRecPacket::PubRecPacket(ParsingInformation* parsingInformation, OnPubRecInternalCallback callback)
|
||||
: _parsingInformation(parsingInformation)
|
||||
, _callback(callback)
|
||||
, _bytePosition(0)
|
||||
, _packetIdMsb(0)
|
||||
, _packetId(0) {
|
||||
}
|
||||
|
||||
PubRecPacket::~PubRecPacket() {
|
||||
}
|
||||
|
||||
void PubRecPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition) {
|
||||
char currentByte = data[(*currentBytePosition)++];
|
||||
if (_bytePosition++ == 0) {
|
||||
_packetIdMsb = currentByte;
|
||||
} else {
|
||||
_packetId = currentByte | _packetIdMsb << 8;
|
||||
_parsingInformation->bufferState = BufferState::NONE;
|
||||
_callback(_packetId);
|
||||
}
|
||||
}
|
||||
|
||||
void PubRecPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition) {
|
||||
(void)data;
|
||||
(void)currentBytePosition;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include "Arduino.h"
|
||||
#include "Packet.hpp"
|
||||
#include "../ParsingInformation.hpp"
|
||||
#include "../Callbacks.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class PubRecPacket : public Packet {
|
||||
public:
|
||||
explicit PubRecPacket(ParsingInformation* parsingInformation, OnPubRecInternalCallback callback);
|
||||
~PubRecPacket();
|
||||
|
||||
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
|
||||
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
|
||||
|
||||
private:
|
||||
ParsingInformation* _parsingInformation;
|
||||
OnPubRecInternalCallback _callback;
|
||||
|
||||
uint8_t _bytePosition;
|
||||
char _packetIdMsb;
|
||||
uint16_t _packetId;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,30 @@
|
||||
#include "PubRelPacket.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::PubRelPacket;
|
||||
|
||||
PubRelPacket::PubRelPacket(ParsingInformation* parsingInformation, OnPubRelInternalCallback callback)
|
||||
: _parsingInformation(parsingInformation)
|
||||
, _callback(callback)
|
||||
, _bytePosition(0)
|
||||
, _packetIdMsb(0)
|
||||
, _packetId(0) {
|
||||
}
|
||||
|
||||
PubRelPacket::~PubRelPacket() {
|
||||
}
|
||||
|
||||
void PubRelPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition) {
|
||||
char currentByte = data[(*currentBytePosition)++];
|
||||
if (_bytePosition++ == 0) {
|
||||
_packetIdMsb = currentByte;
|
||||
} else {
|
||||
_packetId = currentByte | _packetIdMsb << 8;
|
||||
_parsingInformation->bufferState = BufferState::NONE;
|
||||
_callback(_packetId);
|
||||
}
|
||||
}
|
||||
|
||||
void PubRelPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition) {
|
||||
(void)data;
|
||||
(void)currentBytePosition;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include "Arduino.h"
|
||||
#include "Packet.hpp"
|
||||
#include "../ParsingInformation.hpp"
|
||||
#include "../Callbacks.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class PubRelPacket : public Packet {
|
||||
public:
|
||||
explicit PubRelPacket(ParsingInformation* parsingInformation, OnPubRelInternalCallback callback);
|
||||
~PubRelPacket();
|
||||
|
||||
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
|
||||
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
|
||||
|
||||
private:
|
||||
ParsingInformation* _parsingInformation;
|
||||
OnPubRelInternalCallback _callback;
|
||||
|
||||
uint8_t _bytePosition;
|
||||
char _packetIdMsb;
|
||||
uint16_t _packetId;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,91 @@
|
||||
#include "PublishPacket.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::PublishPacket;
|
||||
|
||||
PublishPacket::PublishPacket(ParsingInformation* parsingInformation, OnMessageInternalCallback dataCallback, OnPublishInternalCallback completeCallback)
|
||||
: _parsingInformation(parsingInformation)
|
||||
, _dataCallback(dataCallback)
|
||||
, _completeCallback(completeCallback)
|
||||
, _dup(false)
|
||||
, _qos(0)
|
||||
, _retain(0)
|
||||
, _bytePosition(0)
|
||||
, _topicLengthMsb(0)
|
||||
, _topicLength(0)
|
||||
, _ignore(false)
|
||||
, _packetIdMsb(0)
|
||||
, _packetId(0)
|
||||
, _payloadLength(0)
|
||||
, _payloadBytesRead(0) {
|
||||
_dup = _parsingInformation->packetFlags & HeaderFlag.PUBLISH_DUP;
|
||||
_retain = _parsingInformation->packetFlags & HeaderFlag.PUBLISH_RETAIN;
|
||||
char qosMasked = _parsingInformation->packetFlags & 0x06;
|
||||
switch (qosMasked) {
|
||||
case HeaderFlag.PUBLISH_QOS0:
|
||||
_qos = 0;
|
||||
break;
|
||||
case HeaderFlag.PUBLISH_QOS1:
|
||||
_qos = 1;
|
||||
break;
|
||||
case HeaderFlag.PUBLISH_QOS2:
|
||||
_qos = 2;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
PublishPacket::~PublishPacket() {
|
||||
}
|
||||
|
||||
void PublishPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition) {
|
||||
char currentByte = data[(*currentBytePosition)++];
|
||||
if (_bytePosition == 0) {
|
||||
_topicLengthMsb = currentByte;
|
||||
} else if (_bytePosition == 1) {
|
||||
_topicLength = currentByte | _topicLengthMsb << 8;
|
||||
if (_topicLength > _parsingInformation->maxTopicLength) {
|
||||
_ignore = true;
|
||||
} else {
|
||||
_parsingInformation->topicBuffer[_topicLength] = '\0';
|
||||
}
|
||||
} else if (_bytePosition >= 2 && _bytePosition < 2 + _topicLength) {
|
||||
// Starting from here, _ignore might be true
|
||||
if (!_ignore) _parsingInformation->topicBuffer[_bytePosition - 2] = currentByte;
|
||||
if (_bytePosition == 2 + _topicLength - 1 && _qos == 0) {
|
||||
_preparePayloadHandling(_parsingInformation->remainingLength - (_bytePosition + 1));
|
||||
return;
|
||||
}
|
||||
} else if (_bytePosition == 2 + _topicLength) {
|
||||
_packetIdMsb = currentByte;
|
||||
} else {
|
||||
_packetId = currentByte | _packetIdMsb << 8;
|
||||
_preparePayloadHandling(_parsingInformation->remainingLength - (_bytePosition + 1));
|
||||
}
|
||||
_bytePosition++;
|
||||
}
|
||||
|
||||
void PublishPacket::_preparePayloadHandling(uint32_t payloadLength) {
|
||||
_payloadLength = payloadLength;
|
||||
if (payloadLength == 0) {
|
||||
_parsingInformation->bufferState = BufferState::NONE;
|
||||
if (!_ignore) {
|
||||
_dataCallback(_parsingInformation->topicBuffer, nullptr, _qos, _dup, _retain, 0, 0, 0, _packetId);
|
||||
_completeCallback(_packetId, _qos);
|
||||
}
|
||||
} else {
|
||||
_parsingInformation->bufferState = BufferState::PAYLOAD;
|
||||
}
|
||||
}
|
||||
|
||||
void PublishPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition) {
|
||||
size_t remainToRead = len - (*currentBytePosition);
|
||||
if (_payloadBytesRead + remainToRead > _payloadLength) remainToRead = _payloadLength - _payloadBytesRead;
|
||||
|
||||
if (!_ignore) _dataCallback(_parsingInformation->topicBuffer, data + (*currentBytePosition), _qos, _dup, _retain, remainToRead, _payloadBytesRead, _payloadLength, _packetId);
|
||||
_payloadBytesRead += remainToRead;
|
||||
(*currentBytePosition) += remainToRead;
|
||||
|
||||
if (_payloadBytesRead == _payloadLength) {
|
||||
_parsingInformation->bufferState = BufferState::NONE;
|
||||
if (!_ignore) _completeCallback(_packetId, _qos);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
#pragma once
|
||||
|
||||
#include "Arduino.h"
|
||||
#include "Packet.hpp"
|
||||
#include "../Flags.hpp"
|
||||
#include "../ParsingInformation.hpp"
|
||||
#include "../Callbacks.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class PublishPacket : public Packet {
|
||||
public:
|
||||
explicit PublishPacket(ParsingInformation* parsingInformation, OnMessageInternalCallback dataCallback, OnPublishInternalCallback completeCallback);
|
||||
~PublishPacket();
|
||||
|
||||
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
|
||||
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
|
||||
|
||||
private:
|
||||
ParsingInformation* _parsingInformation;
|
||||
OnMessageInternalCallback _dataCallback;
|
||||
OnPublishInternalCallback _completeCallback;
|
||||
|
||||
void _preparePayloadHandling(uint32_t payloadLength);
|
||||
|
||||
bool _dup;
|
||||
uint8_t _qos;
|
||||
bool _retain;
|
||||
|
||||
uint8_t _bytePosition;
|
||||
char _topicLengthMsb;
|
||||
uint16_t _topicLength;
|
||||
bool _ignore;
|
||||
char _packetIdMsb;
|
||||
uint16_t _packetId;
|
||||
uint32_t _payloadLength;
|
||||
uint32_t _payloadBytesRead;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,46 @@
|
||||
#include "SubAckPacket.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::SubAckPacket;
|
||||
|
||||
SubAckPacket::SubAckPacket(ParsingInformation* parsingInformation, OnSubAckInternalCallback callback)
|
||||
: _parsingInformation(parsingInformation)
|
||||
, _callback(callback)
|
||||
, _bytePosition(0)
|
||||
, _packetIdMsb(0)
|
||||
, _packetId(0) {
|
||||
}
|
||||
|
||||
SubAckPacket::~SubAckPacket() {
|
||||
}
|
||||
|
||||
void SubAckPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition) {
|
||||
char currentByte = data[(*currentBytePosition)++];
|
||||
if (_bytePosition++ == 0) {
|
||||
_packetIdMsb = currentByte;
|
||||
} else {
|
||||
_packetId = currentByte | _packetIdMsb << 8;
|
||||
_parsingInformation->bufferState = BufferState::PAYLOAD;
|
||||
}
|
||||
}
|
||||
|
||||
void SubAckPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition) {
|
||||
char status = data[(*currentBytePosition)++];
|
||||
|
||||
/* switch (status) {
|
||||
case 0:
|
||||
Serial.println("Success QoS 0");
|
||||
break;
|
||||
case 1:
|
||||
Serial.println("Success QoS 1");
|
||||
break;
|
||||
case 2:
|
||||
Serial.println("Success QoS 2");
|
||||
break;
|
||||
case 0x80:
|
||||
Serial.println("Failure");
|
||||
break;
|
||||
} */
|
||||
|
||||
_parsingInformation->bufferState = BufferState::NONE;
|
||||
_callback(_packetId, status);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include "Arduino.h"
|
||||
#include "Packet.hpp"
|
||||
#include "../ParsingInformation.hpp"
|
||||
#include "../Callbacks.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class SubAckPacket : public Packet {
|
||||
public:
|
||||
explicit SubAckPacket(ParsingInformation* parsingInformation, OnSubAckInternalCallback callback);
|
||||
~SubAckPacket();
|
||||
|
||||
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
|
||||
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
|
||||
|
||||
private:
|
||||
ParsingInformation* _parsingInformation;
|
||||
OnSubAckInternalCallback _callback;
|
||||
|
||||
uint8_t _bytePosition;
|
||||
char _packetIdMsb;
|
||||
uint16_t _packetId;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,30 @@
|
||||
#include "UnsubAckPacket.hpp"
|
||||
|
||||
using AsyncMqttClientInternals::UnsubAckPacket;
|
||||
|
||||
UnsubAckPacket::UnsubAckPacket(ParsingInformation* parsingInformation, OnUnsubAckInternalCallback callback)
|
||||
: _parsingInformation(parsingInformation)
|
||||
, _callback(callback)
|
||||
, _bytePosition(0)
|
||||
, _packetIdMsb(0)
|
||||
, _packetId(0) {
|
||||
}
|
||||
|
||||
UnsubAckPacket::~UnsubAckPacket() {
|
||||
}
|
||||
|
||||
void UnsubAckPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition) {
|
||||
char currentByte = data[(*currentBytePosition)++];
|
||||
if (_bytePosition++ == 0) {
|
||||
_packetIdMsb = currentByte;
|
||||
} else {
|
||||
_packetId = currentByte | _packetIdMsb << 8;
|
||||
_parsingInformation->bufferState = BufferState::NONE;
|
||||
_callback(_packetId);
|
||||
}
|
||||
}
|
||||
|
||||
void UnsubAckPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition) {
|
||||
(void)data;
|
||||
(void)currentBytePosition;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include "Arduino.h"
|
||||
#include "Packet.hpp"
|
||||
#include "../ParsingInformation.hpp"
|
||||
#include "../Callbacks.hpp"
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
class UnsubAckPacket : public Packet {
|
||||
public:
|
||||
explicit UnsubAckPacket(ParsingInformation* parsingInformation, OnUnsubAckInternalCallback callback);
|
||||
~UnsubAckPacket();
|
||||
|
||||
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
|
||||
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
|
||||
|
||||
private:
|
||||
ParsingInformation* _parsingInformation;
|
||||
OnUnsubAckInternalCallback _callback;
|
||||
|
||||
uint8_t _bytePosition;
|
||||
char _packetIdMsb;
|
||||
uint16_t _packetId;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
enum class BufferState : uint8_t {
|
||||
NONE = 0,
|
||||
REMAINING_LENGTH = 2,
|
||||
VARIABLE_HEADER = 3,
|
||||
PAYLOAD = 4
|
||||
};
|
||||
|
||||
struct ParsingInformation {
|
||||
BufferState bufferState;
|
||||
|
||||
uint16_t maxTopicLength;
|
||||
char* topicBuffer;
|
||||
|
||||
uint8_t packetType;
|
||||
uint16_t packetFlags;
|
||||
uint32_t remainingLength;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -0,0 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
namespace AsyncMqttClientInternals {
|
||||
struct PendingPubRel {
|
||||
uint16_t packetId;
|
||||
};
|
||||
|
||||
struct PendingAck {
|
||||
uint8_t packetType;
|
||||
uint8_t headerFlag;
|
||||
uint16_t packetId;
|
||||
};
|
||||
} // namespace AsyncMqttClientInternals
|
||||
@@ -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,
|
||||
|
+244
@@ -0,0 +1,244 @@
|
||||
; ═══════════════════════════════════════════════════════════════════════════════
|
||||
; 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]
|
||||
; Everything below is pinned to an exact version on purpose — like the Arduino
|
||||
; IDE asking before it updates a library. Nothing changes on a clean build
|
||||
; unless someone edits a version here in a commit. To update one: change the
|
||||
; pin, rebuild all envs, test on hardware, note it in the commit message.
|
||||
; Platform 6.12.0 = Arduino-ESP32 core 2.0.17 (ESP-IDF 4.4).
|
||||
platform = espressif32 @ 6.12.0
|
||||
framework = arduino
|
||||
monitor_speed = 115200
|
||||
|
||||
; All external library dependencies.
|
||||
; Not listed here: AsyncMqttClient — vendored and patched in lib/AsyncMqttClient
|
||||
; (see lib/AsyncMqttClient/VENDORED.md). PlatformIO picks it up from lib/.
|
||||
lib_deps =
|
||||
; WiFi provisioning portal
|
||||
tzapu/WiFiManager @ 2.0.17
|
||||
|
||||
; Async web server + WebSocket support, and its TCP layer (also used by
|
||||
; AsyncMqttClient). Git sources are pinned to the exact commit after '#'.
|
||||
; me-no-dev/* now redirects to the ESP32Async forks (v3.6.0 / v3.3.2).
|
||||
https://github.com/me-no-dev/ESPAsyncWebServer.git#ad3741d159f9cfd50c567e81b67f3bef1dc6d89f
|
||||
https://github.com/me-no-dev/AsyncTCP.git#ef448a8a1dffe4ec1b72326dd5a26211ff227b49
|
||||
|
||||
; JSON parsing
|
||||
bblanchon/ArduinoJson @ 7.4.3
|
||||
|
||||
; I2C GPIO expanders (relay control) — PCF8575 header is bundled in same library
|
||||
adafruit/Adafruit PCF8574 @ 1.1.2
|
||||
; Pulled in by the Adafruit libraries; pinned so it can't float either
|
||||
adafruit/Adafruit BusIO @ 1.17.4
|
||||
|
||||
; Real-time clock
|
||||
adafruit/RTClib @ 2.1.4
|
||||
|
||||
; 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
|
||||
; F-070: route every abort()/assert/stack-overflow through our wrapper so the
|
||||
; reason string survives the reboot (src/Telemetry/CrashBreadcrumbs.cpp)
|
||||
-Wl,--wrap=esp_system_abort
|
||||
|
||||
; ───────────────────────────────────────────────────────────────────────────────
|
||||
; 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
|
||||
|
||||
; NOTE: the FreeRTOS timer service task (Tmr Svc) stack is fixed at 2048 bytes in
|
||||
; Arduino builds — the SDK is precompiled, so it can't be raised from here (a
|
||||
; `board_build.cmake_extra_args` line used to claim 4096; it only works for
|
||||
; ESP-IDF framework builds and never had any effect). Timer callbacks must stay
|
||||
; tiny: set a flag or notify a task, never LOG / JSON / network / xTaskCreate.
|
||||
|
||||
; 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
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
#include "BellEngine.hpp" // Header file with class definition
|
||||
|
||||
#define TAG "BellEngine"
|
||||
#include "../Player/Player.hpp" // Melody playback controller
|
||||
#include "../ConfigManager/ConfigManager.hpp" // Configuration and settings
|
||||
#include "../Telemetry/Telemetry.hpp" // System monitoring and analytics
|
||||
@@ -74,7 +76,7 @@ BellEngine::~BellEngine() {
|
||||
*
|
||||
*/
|
||||
void BellEngine::begin() {
|
||||
LOG_DEBUG("Initializing BellEngine...");
|
||||
LOG_DEBUG(TAG, "Initializing BellEngine...");
|
||||
|
||||
// Create engine task with HIGHEST priority on dedicated Core 1
|
||||
// This ensures maximum performance and timing precision
|
||||
@@ -88,7 +90,7 @@ void BellEngine::begin() {
|
||||
1 // 💻 Pin to Core 1 (dedicated)
|
||||
);
|
||||
|
||||
LOG_INFO("BellEngine initialized !");
|
||||
LOG_INFO(TAG, "BellEngine initialized !");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -96,7 +98,7 @@ void BellEngine::begin() {
|
||||
*/
|
||||
void BellEngine::setCommunicationManager(CommunicationRouter* commManager) {
|
||||
_communicationManager = commManager;
|
||||
LOG_DEBUG("BellEngine: Communication manager %s",
|
||||
LOG_DEBUG(TAG, "BellEngine: Communication manager %s",
|
||||
commManager ? "connected" : "disconnected");
|
||||
}
|
||||
|
||||
@@ -104,6 +106,10 @@ void BellEngine::setCommunicationManager(CommunicationRouter* commManager) {
|
||||
// ENGINE CONTROL IMPLEMENTATION (Thread-safe)
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
bool BellEngine::areBellsEnabled() const {
|
||||
return _configManager.getBellsEnabled();
|
||||
}
|
||||
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
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()) {
|
||||
LOG_ERROR("Cannot start BellEngine: No melody data loaded");
|
||||
return; // ⛔ Early exit if no melody data
|
||||
LOG_ERROR(TAG, "Cannot start BellEngine: No melody data loaded");
|
||||
return;
|
||||
}
|
||||
|
||||
LOG_INFO("🚀 BellEngine Ignition - Starting precision playback");
|
||||
_emergencyStop.store(false); // ✅ Clear any emergency stop state
|
||||
_engineRunning.store(true); // ✅ Activate the engine atomically
|
||||
LOG_INFO(TAG, "🚀 BellEngine Ignition - Starting precision playback");
|
||||
_emergencyStop.store(false);
|
||||
_engineRunning.store(true);
|
||||
}
|
||||
|
||||
void BellEngine::stop() {
|
||||
LOG_INFO("BellEngine - Stopping Gracefully");
|
||||
LOG_INFO(TAG, "BellEngine - Stopping Gracefully");
|
||||
_engineRunning.store(false);
|
||||
}
|
||||
|
||||
void BellEngine::emergencyStop() {
|
||||
LOG_INFO("BellEngine - 🛑 Forcing Stop Immediately");
|
||||
LOG_INFO(TAG, "BellEngine - 🛑 Forcing Stop Immediately");
|
||||
_emergencyStop.store(true);
|
||||
_engineRunning.store(false);
|
||||
emergencyShutdown();
|
||||
@@ -142,7 +151,7 @@ void BellEngine::setMelodyData(const std::vector<uint16_t>& melodySteps) {
|
||||
_melodySteps = melodySteps;
|
||||
_melodyDataReady.store(true);
|
||||
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() {
|
||||
@@ -150,7 +159,7 @@ void BellEngine::clearMelodyData() {
|
||||
_melodySteps.clear();
|
||||
_melodyDataReady.store(false);
|
||||
portEXIT_CRITICAL(&_melodyMutex);
|
||||
LOG_DEBUG("BellEngine - Melody data cleared");
|
||||
LOG_DEBUG(TAG, "BellEngine - Melody data cleared");
|
||||
}
|
||||
|
||||
// ================== CRITICAL TIMING SECTION ==================
|
||||
@@ -158,7 +167,7 @@ void BellEngine::clearMelodyData() {
|
||||
|
||||
void BellEngine::engineTask(void* parameter) {
|
||||
BellEngine* engine = static_cast<BellEngine*>(parameter);
|
||||
LOG_DEBUG("BellEngine - 🔥 Engine 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) {
|
||||
if (engine->_engineRunning.load() && !engine->_emergencyStop.load()) {
|
||||
@@ -186,7 +195,7 @@ void BellEngine::engineLoop() {
|
||||
|
||||
// Pause handling AFTER complete loop - never interrupt mid-melody!
|
||||
while (_player.isPaused && _player.isPlaying && !_player.hardStop) {
|
||||
LOG_VERBOSE("BellEngine - ⏸️ Pausing between melody loops");
|
||||
LOG_VERBOSE(TAG, "BellEngine - ⏸️ Pausing between melody loops");
|
||||
vTaskDelay(pdMS_TO_TICKS(10)); // Wait during pause
|
||||
}
|
||||
|
||||
@@ -207,17 +216,17 @@ void BellEngine::playbackLoop() {
|
||||
portEXIT_CRITICAL(&_melodyMutex);
|
||||
|
||||
if (melodySteps.empty()) {
|
||||
LOG_ERROR("BellEngine - ❌ Empty melody in playback loop!");
|
||||
LOG_ERROR(TAG, "BellEngine - ❌ Empty melody in playback loop!");
|
||||
return;
|
||||
}
|
||||
|
||||
LOG_DEBUG("BellEngine - 🎵 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
|
||||
for (uint16_t note : melodySteps) {
|
||||
// Emergency exit check (only emergency stops can interrupt mid-loop)
|
||||
if (_emergencyStop.load() || _player.hardStop) {
|
||||
LOG_DEBUG("BellEngine - Emergency exit from playback loop");
|
||||
LOG_DEBUG(TAG, "BellEngine - Emergency exit from playback loop");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -227,7 +236,7 @@ void BellEngine::playbackLoop() {
|
||||
// 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("BellEngine - ❌ Invalid Speed (0) detected, stopping playback");
|
||||
LOG_ERROR(TAG, "BellEngine - ❌ Invalid Speed (0) detected, stopping playback");
|
||||
_player.hardStop = true;
|
||||
_engineRunning.store(false);
|
||||
return;
|
||||
@@ -242,9 +251,9 @@ void BellEngine::playbackLoop() {
|
||||
_player.onMelodyLoopCompleted(); // 🔥 Notify Player that melody actually finished!
|
||||
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("BellEngine - Loop completed in SINGLE Mode - waiting for Player to handle pause/stop");
|
||||
LOG_VERBOSE(TAG, "BellEngine - Loop completed in SINGLE Mode - waiting for Player to handle pause/stop");
|
||||
}
|
||||
LOG_DEBUG("BellEngine - 🎵 Melody loop completed with PRECISION");
|
||||
LOG_DEBUG(TAG, "BellEngine - 🎵 Melody loop completed with PRECISION");
|
||||
|
||||
}
|
||||
|
||||
@@ -268,26 +277,26 @@ void BellEngine::activateNote(uint16_t note) {
|
||||
|
||||
// Additional safety check to prevent underflow crashes
|
||||
if (bellIndex >= 255) {
|
||||
LOG_ERROR("BellEngine - 🚨 UNDERFLOW ERROR: bellIndex underflow for noteIndex %d", noteIndex);
|
||||
LOG_ERROR(TAG, "BellEngine - 🚨 UNDERFLOW ERROR: bellIndex underflow for noteIndex %d", noteIndex);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Bounds check (CRITICAL SAFETY)
|
||||
if (bellIndex >= 16) {
|
||||
LOG_ERROR("BellEngine - 🚨 BOUNDS ERROR: bellIndex %d >= 16", bellIndex);
|
||||
LOG_ERROR(TAG, "BellEngine - 🚨 BOUNDS ERROR: bellIndex %d >= 16", bellIndex);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check for duplicate bell firing in this note
|
||||
if (bellFired[bellIndex]) {
|
||||
LOG_DEBUG("BellEngine - ⚠️ 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;
|
||||
}
|
||||
|
||||
// Check if bell is configured (OutputManager will validate this)
|
||||
uint8_t physicalOutput = _outputManager.getPhysicalOutput(bellIndex);
|
||||
if (physicalOutput == 255) {
|
||||
LOG_DEBUG("BellEngine - ⚠️ UNCONFIGURED: Bell %d not configured, skipping", bellIndex);
|
||||
LOG_DEBUG(TAG, "BellEngine - ⚠️ UNCONFIGURED: Bell %d not configured, skipping", bellIndex);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -306,18 +315,14 @@ void BellEngine::activateNote(uint16_t note) {
|
||||
// Record telemetry
|
||||
_telemetry.recordBellStrike(bellIndex);
|
||||
|
||||
LOG_VERBOSE("BellEngine - 🔨 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!
|
||||
if (!bellDurations.empty()) {
|
||||
_outputManager.fireOutputsBatchForDuration(bellDurations);
|
||||
LOG_VERBOSE("BellEngine - 🔥 Batch Fired %d bells Simultaneously !", bellDurations.size());
|
||||
|
||||
// 🔔 NOTIFY WEBSOCKET CLIENTS OF BELL DINGS!
|
||||
// * deactivated currently, since unstable and causes performance issues *
|
||||
// notifyBellsFired(firedBellIndices);
|
||||
LOG_VERBOSE(TAG, "BellEngine - 🔥 Batch Fired %d bells Simultaneously !", bellDurations.size());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -339,38 +344,10 @@ void BellEngine::preciseDelay(uint32_t microseconds) {
|
||||
}
|
||||
|
||||
void BellEngine::emergencyShutdown() {
|
||||
LOG_INFO("BellEngine - 🚨 Emergency Shutdown - Notifying OutputManager");
|
||||
LOG_INFO(TAG, "BellEngine - 🚨 Emergency Shutdown - Notifying OutputManager");
|
||||
_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("BellEngine - 🔔 DING notification sent for %d bells", bellIndices.size());
|
||||
|
||||
} catch (...) {
|
||||
LOG_WARNING("BellEngine - ❌ Failed to send ding notification");
|
||||
}
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// HEALTH CHECK IMPLEMENTATION
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
@@ -378,20 +355,20 @@ void BellEngine::notifyBellsFired(const std::vector<uint8_t>& bellIndices) {
|
||||
bool BellEngine::isHealthy() const {
|
||||
// Check if engine task is created and running
|
||||
if (_engineTaskHandle == NULL) {
|
||||
LOG_DEBUG("BellEngine: Unhealthy - Task not created");
|
||||
LOG_DEBUG(TAG, "BellEngine: Unhealthy - Task not created");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if task is still alive
|
||||
eTaskState taskState = eTaskGetState(_engineTaskHandle);
|
||||
if (taskState == eDeleted || taskState == eInvalid) {
|
||||
LOG_DEBUG("BellEngine: Unhealthy - Task deleted or invalid");
|
||||
LOG_DEBUG(TAG, "BellEngine: Unhealthy - Task deleted or invalid");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if OutputManager is properly connected and healthy
|
||||
if (!_outputManager.isInitialized()) {
|
||||
LOG_DEBUG("BellEngine: Unhealthy - OutputManager not initialized");
|
||||
LOG_DEBUG(TAG, "BellEngine: Unhealthy - OutputManager not initialized");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -205,6 +205,13 @@ public:
|
||||
*/
|
||||
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
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
@@ -357,13 +364,6 @@ private:
|
||||
*/
|
||||
void checkAndNotifyOverloads();
|
||||
|
||||
/**
|
||||
* @brief Notify WebSocket clients of fired bells
|
||||
* @param bellIndices Vector of bell indices that were fired (1-indexed)
|
||||
*
|
||||
* Sends INFO/ding message to WebSocket clients only (not MQTT)
|
||||
*/
|
||||
void notifyBellsFired(const std::vector<uint8_t>& bellIndices);
|
||||
};
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,31 +1,33 @@
|
||||
#include "ClientManager.hpp"
|
||||
|
||||
#define TAG "ClientManager"
|
||||
#include "../Logging/Logging.hpp"
|
||||
|
||||
ClientManager::ClientManager() {
|
||||
LOG_INFO("Client Manager initialized !");
|
||||
LOG_INFO(TAG, "Client Manager initialized !");
|
||||
}
|
||||
|
||||
ClientManager::~ClientManager() {
|
||||
_clients.clear();
|
||||
LOG_INFO("Client Manager destroyed");
|
||||
LOG_INFO(TAG, "Client Manager destroyed");
|
||||
}
|
||||
|
||||
void ClientManager::addClient(AsyncWebSocketClient* client, DeviceType deviceType) {
|
||||
if (!isValidClient(client)) {
|
||||
LOG_WARNING("Client Manager - Cannot add invalid client");
|
||||
LOG_WARNING(TAG, "Client Manager - Cannot add invalid client");
|
||||
return;
|
||||
}
|
||||
|
||||
uint32_t clientId = client->id();
|
||||
_clients[clientId] = ClientInfo(client, deviceType);
|
||||
|
||||
LOG_INFO("Client Manager - 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) {
|
||||
auto it = _clients.find(clientId);
|
||||
if (it != _clients.end()) {
|
||||
LOG_INFO("Client Manager - Client #%u removed (%s device)", clientId,
|
||||
LOG_INFO(TAG, "Client Manager - Client #%u removed (%s device)", clientId,
|
||||
deviceTypeToString(it->second.deviceType));
|
||||
_clients.erase(it);
|
||||
}
|
||||
@@ -36,7 +38,7 @@ void ClientManager::updateClientType(uint32_t clientId, DeviceType deviceType) {
|
||||
if (it != _clients.end()) {
|
||||
DeviceType oldType = it->second.deviceType;
|
||||
it->second.deviceType = deviceType;
|
||||
LOG_INFO("Client Manager - 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));
|
||||
}
|
||||
}
|
||||
@@ -72,11 +74,11 @@ bool ClientManager::sendToClient(uint32_t clientId, const String& message) {
|
||||
if (it != _clients.end() && isValidClient(it->second.client)) {
|
||||
it->second.client->text(message);
|
||||
updateClientLastSeen(clientId);
|
||||
LOG_DEBUG("Client Manager - 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;
|
||||
}
|
||||
|
||||
LOG_WARNING("Client Manager - 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;
|
||||
}
|
||||
|
||||
@@ -90,7 +92,7 @@ void ClientManager::sendToMasterClients(const String& message) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
LOG_DEBUG("Client Manager - 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) {
|
||||
@@ -103,7 +105,7 @@ void ClientManager::sendToSecondaryClients(const String& message) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
LOG_DEBUG("Client Manager - 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) {
|
||||
@@ -115,14 +117,14 @@ void ClientManager::broadcastToAll(const String& message) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
LOG_DEBUG("Client Manager - 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() {
|
||||
auto it = _clients.begin();
|
||||
while (it != _clients.end()) {
|
||||
if (!isValidClient(it->second.client)) {
|
||||
LOG_DEBUG("Client Manager - Cleaning up disconnected client #%u", it->first);
|
||||
LOG_DEBUG(TAG, "Client Manager - Cleaning up disconnected client #%u", it->first);
|
||||
it->second.isConnected = false;
|
||||
it = _clients.erase(it);
|
||||
} else {
|
||||
@@ -132,11 +134,11 @@ void ClientManager::cleanupDisconnectedClients() {
|
||||
}
|
||||
|
||||
String ClientManager::getClientListJson() const {
|
||||
StaticJsonDocument<512> doc;
|
||||
JsonArray clients = doc.createNestedArray("clients");
|
||||
JsonDocument doc;
|
||||
JsonArray clients = doc["clients"].to<JsonArray>();
|
||||
|
||||
for (const auto& pair : _clients) {
|
||||
JsonObject client = clients.createNestedObject();
|
||||
JsonObject client = clients.add<JsonObject>();
|
||||
client["id"] = pair.first;
|
||||
client["type"] = deviceTypeToString(pair.second.deviceType);
|
||||
client["connected"] = isValidClient(pair.second.client);
|
||||
@@ -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,91 @@
|
||||
#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);
|
||||
// The reply always goes out here, synchronously, on the transport's own task —
|
||||
// which is what guarantees req_id is echoed. Work that finishes later (e.g. a
|
||||
// playback.play that must download first, F-068) must NOT defer the reply;
|
||||
// its outcome is published on its own topic (status/playback, control/reports).
|
||||
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, 0, 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) _telemetry->writeCrashJson(payload["crash"].to<JsonObject>());
|
||||
if (_telemetry->getPreCrashSnapshot().available) {
|
||||
_telemetry->writePreCrashJson(payload["pre_crash"].to<JsonObject>());
|
||||
}
|
||||
|
||||
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, 0, 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);
|
||||
// QoS 1 + PUBACK tracking: playback is what the apps act on. Not resent on
|
||||
// reconnect — onConnect republishes the *current* snapshot instead (F-073).
|
||||
_mqttClient.publishConfirmed(_mqttClient.getPlaybackTopic(), out, true, false);
|
||||
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.
|
||||
// QoS 1 + PUBACK tracking, resent after a reconnect if unconfirmed (F-073).
|
||||
_mqttClient.publishConfirmed(_mqttClient.getReportsTopic(), out, false, true);
|
||||
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 via `publishConfirmed()`, 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 via `publishConfirmed()`, resent after reconnect if unconfirmed, 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 0, 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 0, 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,619 @@
|
||||
/*
|
||||
* 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)
|
||||
, _supervisorTask(nullptr)
|
||||
, _reconnectAttempts(0)
|
||||
, _nextConnectAtMs(0)
|
||||
, _connectAttemptMs(0)
|
||||
, _netUpSinceMs(0)
|
||||
, _heartbeatDue(false)
|
||||
, _lastHeartbeatMs(0)
|
||||
, _pendingMutex(xSemaphoreCreateRecursiveMutex())
|
||||
, _resendDue(false) {
|
||||
|
||||
_instance = this; // Set static instance pointer
|
||||
_pending.reserve(MAX_PENDING_ACKS);
|
||||
}
|
||||
|
||||
MQTTDriver::~MQTTDriver() {
|
||||
if (_supervisorTask) {
|
||||
vTaskDelete(_supervisorTask);
|
||||
}
|
||||
_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.
|
||||
_willPayload = buildOfflinePayload();
|
||||
_mqttClient.setWill(_heartbeatTopic.c_str(), 1, true, _willPayload.c_str());
|
||||
|
||||
// Created once at boot, while the heap is still unfragmented, and never
|
||||
// deleted — nothing in the reconnect/heartbeat path allocates a task again.
|
||||
if (!_supervisorTask) {
|
||||
xTaskCreate(supervisorTaskFn, "mqttSup", 4096, this, 3, &_supervisorTask);
|
||||
}
|
||||
|
||||
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() {
|
||||
_reconnectAttempts = 0;
|
||||
_nextConnectAtMs = millis();
|
||||
wakeSupervisor();
|
||||
}
|
||||
|
||||
// Supervisor-task only. AsyncMqttClient::connect() is a no-op unless the
|
||||
// library is DISCONNECTED; if it's stuck in CONNECTING/DISCONNECTING the
|
||||
// supervisor notices via _connectAttemptMs and forces a reset.
|
||||
void MQTTDriver::doConnect() {
|
||||
if (_mqttClient.connected()) return;
|
||||
|
||||
unsigned long now = millis();
|
||||
_connectAttemptMs = now ? now : 1;
|
||||
LOG_INFO(TAG, "Connecting to MQTT broker (attempt #%d, free heap %u bytes)...",
|
||||
_reconnectAttempts + 1, (unsigned)ESP.getFreeHeap());
|
||||
_mqttClient.connect();
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
uint16_t MQTTDriver::publishConfirmed(const String& fullTopic, const String& payload, bool retain, bool resendOnReconnect) {
|
||||
if (!_mqttClient.connected()) return 0;
|
||||
if (!hasHeapForPublish()) return 0;
|
||||
|
||||
uint16_t packetId = publishTracked(fullTopic, payload, retain, CONFIRMED_ACK_TIMEOUT,
|
||||
resendOnReconnect ? "report PUBACK timeout" : "playback PUBACK timeout",
|
||||
resendOnReconnect);
|
||||
if (packetId > 0) {
|
||||
LOG_DEBUG(TAG, "Published (confirmed) to %s (packetId=%d)", fullTopic.c_str(), packetId);
|
||||
}
|
||||
return packetId;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// PUBACK TRACKING
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
uint16_t MQTTDriver::publishTracked(const String& topic, const String& payload, bool retain,
|
||||
unsigned long timeoutMs, const char* label, bool resend) {
|
||||
PendingAck p;
|
||||
p.label = label;
|
||||
p.resend = resend;
|
||||
if (resend) {
|
||||
p.topic = topic;
|
||||
p.payload = payload;
|
||||
}
|
||||
p.retain = retain;
|
||||
|
||||
// Publish and register under the same lock: the PUBACK can come back on
|
||||
// the async_tcp task before publish() even returns here, and onMqttPublish
|
||||
// must find the entry or it would time out and force a needless reset.
|
||||
// Recursive: publish() can synchronously end in onMqttDisconnect →
|
||||
// abandonPending() on this same task.
|
||||
xSemaphoreTakeRecursive(_pendingMutex, portMAX_DELAY);
|
||||
uint16_t packetId = _mqttClient.publish(topic.c_str(), 1, retain, payload.c_str());
|
||||
if (packetId > 0) {
|
||||
p.id = packetId;
|
||||
p.deadlineMs = millis() + timeoutMs;
|
||||
if (_pending.size() >= MAX_PENDING_ACKS) {
|
||||
// Eight unacked QoS 1 messages means the connection is already
|
||||
// stalled; keep the oldest — its deadline triggers the reset anyway.
|
||||
_pending.erase(_pending.begin() + 1);
|
||||
}
|
||||
_pending.push_back(std::move(p));
|
||||
}
|
||||
xSemaphoreGiveRecursive(_pendingMutex);
|
||||
return packetId;
|
||||
}
|
||||
|
||||
const char* MQTTDriver::expiredPendingLabel(unsigned long now) {
|
||||
const char* label = nullptr;
|
||||
xSemaphoreTakeRecursive(_pendingMutex, portMAX_DELAY);
|
||||
for (const auto& p : _pending) {
|
||||
if ((long)(now - p.deadlineMs) >= 0) { label = p.label; break; }
|
||||
}
|
||||
xSemaphoreGiveRecursive(_pendingMutex);
|
||||
return label;
|
||||
}
|
||||
|
||||
void MQTTDriver::abandonPending() {
|
||||
xSemaphoreTakeRecursive(_pendingMutex, portMAX_DELAY);
|
||||
for (auto& p : _pending) {
|
||||
if (p.resend) _resendQueue.push_back(std::move(p));
|
||||
}
|
||||
_pending.clear();
|
||||
while (_resendQueue.size() > MAX_RESEND) {
|
||||
_resendQueue.erase(_resendQueue.begin()); // keep the newest
|
||||
}
|
||||
xSemaphoreGiveRecursive(_pendingMutex);
|
||||
}
|
||||
|
||||
void MQTTDriver::flushResendQueue() {
|
||||
std::vector<PendingAck> toSend;
|
||||
xSemaphoreTakeRecursive(_pendingMutex, portMAX_DELAY);
|
||||
toSend.swap(_resendQueue);
|
||||
xSemaphoreGiveRecursive(_pendingMutex);
|
||||
|
||||
for (const auto& p : toSend) {
|
||||
if (publishConfirmed(p.topic, p.payload, p.retain, true) > 0) {
|
||||
_diag.resentMessages++;
|
||||
LOG_INFO(TAG, "Resent unconfirmed message to %s after reconnect", p.topic.c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MQTTDriver::setCallback(MessageCallback callback) {
|
||||
_messageCallback = callback;
|
||||
}
|
||||
|
||||
bool MQTTDriver::isConnected() const {
|
||||
return _mqttClient.connected();
|
||||
}
|
||||
|
||||
void MQTTDriver::onNetworkConnected() {
|
||||
// The supervisor tracks WiFi itself (it doesn't depend on this callback
|
||||
// ever arriving) — this just resets backoff and wakes it up promptly.
|
||||
LOG_DEBUG(TAG, "Network connected - MQTT connect after %lums stabilization", NETWORK_STABILIZATION_DELAY);
|
||||
_reconnectAttempts = 0;
|
||||
_nextConnectAtMs = millis();
|
||||
wakeSupervisor();
|
||||
}
|
||||
|
||||
void MQTTDriver::onNetworkDisconnected() {
|
||||
LOG_DEBUG(TAG, "Network disconnected - MQTT will 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;
|
||||
_connectAttemptMs = 0;
|
||||
_diag.connects++;
|
||||
|
||||
// Anything still tracked belongs to the previous connection (e.g. registered
|
||||
// after a disconnect that fired inside publish()) and would time out here.
|
||||
// Before the onConnect callback below republishes playback.
|
||||
abandonPending();
|
||||
_diag.connectedSinceMs = millis();
|
||||
|
||||
// Subscribe to control topic
|
||||
subscribe();
|
||||
|
||||
// First heartbeat (and any resends) go out from the supervisor right away,
|
||||
// not from here — this callback runs on the async_tcp task.
|
||||
_heartbeatDue = true;
|
||||
_resendDue = true;
|
||||
wakeSupervisor();
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
_diag.disconnects++;
|
||||
_diag.lastDisconnectReason = reasonStr;
|
||||
_diag.lastDisconnectMs = millis();
|
||||
_diag.connectedSinceMs = 0;
|
||||
_connectAttemptMs = 0;
|
||||
abandonPending();
|
||||
|
||||
if (!mqttConfig.enabled) {
|
||||
LOG_INFO(TAG, "❌ Disconnected from MQTT broker - Reason: %s (%d) - MQTT disabled, not reconnecting",
|
||||
reasonStr, static_cast<int>(reason));
|
||||
return;
|
||||
}
|
||||
|
||||
_reconnectAttempts++;
|
||||
unsigned long reconnectDelay = getReconnectDelay();
|
||||
_nextConnectAtMs = millis() + reconnectDelay;
|
||||
|
||||
LOG_ERROR(TAG, "❌ Disconnected from MQTT broker - Reason: %s (%d) - reconnect #%d in %lus",
|
||||
reasonStr, static_cast<int>(reason), _reconnectAttempts, reconnectDelay / 1000);
|
||||
wakeSupervisor();
|
||||
}
|
||||
|
||||
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) {
|
||||
xSemaphoreTakeRecursive(_pendingMutex, portMAX_DELAY);
|
||||
for (auto it = _pending.begin(); it != _pending.end(); ++it) {
|
||||
if (it->id == packetId) { _pending.erase(it); break; }
|
||||
}
|
||||
xSemaphoreGiveRecursive(_pendingMutex);
|
||||
LOG_DEBUG(TAG, "MQTT publish acknowledged (packetId=%d)", packetId);
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// SUPERVISOR TASK
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void MQTTDriver::supervisorTaskFn(void* param) {
|
||||
MQTTDriver* self = static_cast<MQTTDriver*>(param);
|
||||
for (;;) {
|
||||
// Woken early by connect/disconnect/network events; otherwise ticks.
|
||||
ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(SUPERVISOR_TICK_MS));
|
||||
self->supervise();
|
||||
}
|
||||
}
|
||||
|
||||
void MQTTDriver::wakeSupervisor() {
|
||||
if (_supervisorTask) xTaskNotifyGive(_supervisorTask);
|
||||
}
|
||||
|
||||
void MQTTDriver::supervise() {
|
||||
if (!_configManager.getMqttConfig().enabled) {
|
||||
_connectAttemptMs = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
unsigned long now = millis();
|
||||
|
||||
if (_mqttClient.connected()) {
|
||||
if (_heartbeatDue || now - _lastHeartbeatMs >= HEARTBEAT_INTERVAL) {
|
||||
_heartbeatDue = false;
|
||||
_lastHeartbeatMs = now;
|
||||
publishHeartbeat();
|
||||
}
|
||||
if (_resendDue) {
|
||||
_resendDue = false;
|
||||
flushResendQueue();
|
||||
}
|
||||
if (const char* expired = expiredPendingLabel(now)) {
|
||||
forceReset(expired);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// WiFi status straight from the driver rather than Networking's state
|
||||
// machine, so a missed network callback can't strand MQTT offline.
|
||||
if (WiFi.status() != WL_CONNECTED) {
|
||||
_netUpSinceMs = 0;
|
||||
return;
|
||||
}
|
||||
if (_netUpSinceMs == 0) _netUpSinceMs = now ? now : 1;
|
||||
if (now - _netUpSinceMs < NETWORK_STABILIZATION_DELAY) return;
|
||||
|
||||
unsigned long attemptStart = _connectAttemptMs;
|
||||
if (attemptStart != 0) {
|
||||
if (now - attemptStart > CONNECT_STUCK_TIMEOUT) {
|
||||
forceReset("connect attempt stuck");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if ((long)(now - _nextConnectAtMs) >= 0) {
|
||||
doConnect();
|
||||
}
|
||||
}
|
||||
|
||||
void MQTTDriver::forceReset(const char* reason) {
|
||||
_diag.forcedResets++;
|
||||
_diag.lastForcedResetReason = reason;
|
||||
_diag.lastForcedResetMs = millis();
|
||||
LOG_WARNING(TAG, "⚠️ MQTT connection wedged (%s) - forcing reset #%lu",
|
||||
reason, (unsigned long)_diag.forcedResets);
|
||||
|
||||
// Forced close: drops the socket and resets the library to DISCONNECTED
|
||||
// even when it's stuck mid-connect, so the next connect() isn't a no-op.
|
||||
// onMqttDisconnect may or may not fire from inside this call.
|
||||
_mqttClient.disconnect(true);
|
||||
|
||||
abandonPending();
|
||||
_connectAttemptMs = 0;
|
||||
unsigned long earliest = millis() + MQTT_RECONNECT_BASE_DELAY;
|
||||
if ((long)(_nextConnectAtMs - earliest) < 0) _nextConnectAtMs = earliest;
|
||||
}
|
||||
|
||||
void MQTTDriver::writeStatus(JsonObject out) const {
|
||||
unsigned long now = millis();
|
||||
out["enabled"] = _configManager.getMqttConfig().enabled;
|
||||
out["connected"] = _mqttClient.connected();
|
||||
out["connected_for_ms"] = _diag.connectedSinceMs ? now - _diag.connectedSinceMs : 0;
|
||||
out["connects"] = _diag.connects;
|
||||
out["disconnects"] = _diag.disconnects;
|
||||
out["reconnect_attempts"] = _reconnectAttempts;
|
||||
out["last_disconnect_reason"] = _diag.lastDisconnectReason;
|
||||
out["last_disconnect_ago_ms"] = _diag.lastDisconnectMs ? now - _diag.lastDisconnectMs : 0;
|
||||
out["forced_resets"] = _diag.forcedResets;
|
||||
out["last_forced_reset_reason"] = _diag.lastForcedResetReason;
|
||||
out["last_forced_reset_ago_ms"] = _diag.lastForcedResetMs ? now - _diag.lastForcedResetMs : 0;
|
||||
out["resent_messages"] = _diag.resentMessages;
|
||||
out["wifi_connected"] = WiFi.status() == WL_CONNECTED;
|
||||
out["free_heap"] = ESP.getFreeHeap();
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// HEARTBEAT FUNCTIONALITY
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void MQTTDriver::publishHeartbeat() {
|
||||
if (!_mqttClient.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
|
||||
// QoS 1 on purpose — its PUBACK is the liveness probe (HEARTBEAT_ACK_TIMEOUT).
|
||||
uint16_t packetId = publishTracked(_heartbeatTopic, heartbeatMessage, true,
|
||||
HEARTBEAT_ACK_TIMEOUT, "heartbeat PUBACK timeout", false);
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// 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, 60s (capped at 1 minute)
|
||||
uint8_t backoffPower = _reconnectAttempts - MQTT_MAX_QUICK_RETRIES;
|
||||
if (backoffPower > 8) backoffPower = 8; // already past the cap; avoids shift overflow
|
||||
unsigned long delay = MQTT_RECONNECT_BASE_DELAY * (1 << backoffPower); // 2^backoffPower
|
||||
|
||||
// Cap at maximum delay (1 minute)
|
||||
if (delay > MQTT_RECONNECT_MAX_DELAY) {
|
||||
delay = MQTT_RECONNECT_MAX_DELAY;
|
||||
}
|
||||
|
||||
return delay;
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* 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.
|
||||
*
|
||||
* QoS policy (F-072/F-073): QoS 1 only where losing a message matters —
|
||||
* the heartbeat, status/playback and control/reports — and those go through
|
||||
* publishConfirmed(), which tracks the PUBACK. A missing PUBACK means the
|
||||
* connection is dead, so the supervisor resets it; playback state is then
|
||||
* republished fresh on reconnect, reports are resent. Plain QoS 1 alone would
|
||||
* not recover anything here: with cleanSession=true the library drops unacked
|
||||
* packets on reconnect. Everything else (acks, alerts, info, logs, metrics)
|
||||
* is QoS 0. The queue is sent strictly in order and each QoS 1 message holds
|
||||
* what's behind it for one round trip (the vendored library is patched so it
|
||||
* no longer adds a ~500ms poll wait on top — lib/AsyncMqttClient/VENDORED.md).
|
||||
*
|
||||
* 📋 VERSION: 3.0 (AsyncMqttClient-based)
|
||||
* 📅 DATE: 2025-01-04
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <AsyncMqttClient.h>
|
||||
#include <functional>
|
||||
#include <ArduinoJson.h>
|
||||
#include <vector>
|
||||
|
||||
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 Request a connection to the broker now (resets backoff). The
|
||||
* supervisor task performs the actual connect on its next tick.
|
||||
*/
|
||||
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 = 0, 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 QoS 1 publish whose PUBACK is tracked. No PUBACK within
|
||||
* CONFIRMED_ACK_TIMEOUT means the connection is dead: the supervisor
|
||||
* resets it and reconnects. Same heap guard as publishDirect(); the
|
||||
* caller still does topic-switch gating.
|
||||
* @param resendOnReconnect true for event topics (control/reports): the
|
||||
* message is kept and republished after the reconnect. false for
|
||||
* retained state topics (status/playback) whose owner republishes the
|
||||
* *current* state on every connect — resending the old one would
|
||||
* overwrite fresh state with stale.
|
||||
* @return Packet ID (0 if not sent)
|
||||
*/
|
||||
uint16_t publishConfirmed(const String& fullTopic, const String& payload, bool retain, bool resendOnReconnect);
|
||||
|
||||
/**
|
||||
* @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);
|
||||
|
||||
/**
|
||||
* @brief Connection-health counters since boot, for post-mortem of "MQTT
|
||||
* went silent" incidents. Exposed via mqtt.status — which works over
|
||||
* WebSocket too, exactly when MQTT itself can't be asked.
|
||||
*/
|
||||
struct Diagnostics {
|
||||
uint32_t connects = 0;
|
||||
uint32_t disconnects = 0;
|
||||
uint32_t forcedResets = 0;
|
||||
const char* lastDisconnectReason = "";
|
||||
unsigned long lastDisconnectMs = 0;
|
||||
const char* lastForcedResetReason = "";
|
||||
unsigned long lastForcedResetMs = 0;
|
||||
unsigned long connectedSinceMs = 0; // 0 = not connected
|
||||
uint32_t resentMessages = 0; // reports republished after a reconnect
|
||||
};
|
||||
void writeStatus(JsonObject out) const;
|
||||
|
||||
// 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();
|
||||
void doConnect();
|
||||
|
||||
/**
|
||||
* @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);
|
||||
|
||||
// ── Supervisor ────────────────────────────────────────────────────────────
|
||||
// ONE persistent task owns everything time-driven: (re)connect with backoff,
|
||||
// network stabilization, the 30s heartbeat, and wedge detection. It replaced
|
||||
// three FreeRTOS timers that each spawned a short-lived task per firing —
|
||||
// a single failed xTaskCreate() (fragmented heap after days of uptime) ended
|
||||
// a one-shot reconnect chain for good, leaving MQTT dead until reboot while
|
||||
// WebSocket kept working. See docs/features/feature-catalog.md F-071.
|
||||
TaskHandle_t _supervisorTask;
|
||||
static void supervisorTaskFn(void* param);
|
||||
void supervise();
|
||||
void wakeSupervisor();
|
||||
void forceReset(const char* reason);
|
||||
|
||||
static const unsigned long SUPERVISOR_TICK_MS = 500;
|
||||
static const unsigned long NETWORK_STABILIZATION_DELAY = 2000; // 2 seconds after WiFi is up
|
||||
static const unsigned long MQTT_RECONNECT_BASE_DELAY = 5000; // 5 seconds base
|
||||
static const unsigned long MQTT_RECONNECT_MAX_DELAY = 60000; // 1 minute max
|
||||
static const uint8_t MQTT_MAX_QUICK_RETRIES = 3; // Try 3 times quickly
|
||||
// A connect() that produces neither CONNACK nor a disconnect callback within
|
||||
// this window means AsyncMqttClient is wedged in CONNECTING/DISCONNECTING
|
||||
// (it ignores AsyncClient::connect()'s return value, and a failed tcp_close
|
||||
// never fires onDisconnect) — every later connect() would silently no-op.
|
||||
static const unsigned long CONNECT_STUCK_TIMEOUT = 30000;
|
||||
// PUBACK deadlines for tracked QoS 1 publishes. No PUBACK in time = the
|
||||
// connection is dead even if the library still says CONNECTED (half-open
|
||||
// socket, stalled send queue). The heartbeat is the background probe;
|
||||
// playback/reports get a tighter window because they're what the apps wait on.
|
||||
static const unsigned long HEARTBEAT_ACK_TIMEOUT = 20000;
|
||||
static const unsigned long CONFIRMED_ACK_TIMEOUT = 8000;
|
||||
|
||||
volatile uint8_t _reconnectAttempts;
|
||||
volatile unsigned long _nextConnectAtMs; // earliest time the next connect may start
|
||||
volatile unsigned long _connectAttemptMs; // 0 = no attempt in flight
|
||||
unsigned long _netUpSinceMs; // 0 = network down
|
||||
unsigned long getReconnectDelay();
|
||||
|
||||
// Heartbeat (30 seconds)
|
||||
static const unsigned long HEARTBEAT_INTERVAL = 30000; // 30 seconds
|
||||
volatile bool _heartbeatDue;
|
||||
unsigned long _lastHeartbeatMs;
|
||||
void publishHeartbeat();
|
||||
|
||||
// Tracked QoS 1 publishes awaiting PUBACK. Touched from the async_tcp task
|
||||
// (onMqttPublish), the supervisor, and whichever task publishes — guarded
|
||||
// by a recursive mutex (not a spinlock: entries own Strings, which allocate).
|
||||
struct PendingAck {
|
||||
uint16_t id;
|
||||
unsigned long deadlineMs;
|
||||
const char* label; // static string, used as forced-reset reason
|
||||
bool resend;
|
||||
String topic; // only kept when resend == true
|
||||
String payload;
|
||||
bool retain;
|
||||
};
|
||||
static const size_t MAX_PENDING_ACKS = 8;
|
||||
static const size_t MAX_RESEND = 4;
|
||||
SemaphoreHandle_t _pendingMutex;
|
||||
std::vector<PendingAck> _pending;
|
||||
std::vector<PendingAck> _resendQueue; // waiting for the next CONNACK
|
||||
volatile bool _resendDue;
|
||||
uint16_t publishTracked(const String& topic, const String& payload, bool retain,
|
||||
unsigned long timeoutMs, const char* label, bool resend);
|
||||
const char* expiredPendingLabel(unsigned long now); // nullptr if none
|
||||
void abandonPending(); // connection gone: drop, or keep for resend
|
||||
void flushResendQueue();
|
||||
|
||||
// Must outlive every CONNECT — AsyncMqttClient::setWill() stores the raw
|
||||
// pointer, so a temporary String here sent freed heap as the LWT payload
|
||||
// (the "gibberish on status/heartbeat" seen when a connection dropped).
|
||||
String _willPayload;
|
||||
|
||||
Diagnostics _diag;
|
||||
};
|
||||
@@ -0,0 +1,138 @@
|
||||
# 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`. All time-driven work runs on one persistent supervisor task (see Initialization).
|
||||
|
||||
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 = 0, 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 publishConfirmed(const String& fullTopic, const String& payload, bool retain, bool resendOnReconnect)` | QoS 1 publish with PUBACK tracking (8 s deadline). A missed deadline makes the supervisor reset the connection. `resendOnReconnect=true` keeps the message and republishes it after the reconnect (event topics); `false` for retained state the caller republishes itself on connect. Used for `status/playback` (false) and `control/reports` (true). |
|
||||
| `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 connect()` | Requests a connect now (resets backoff) and wakes the supervisor. Used by `mqtt.enable`. |
|
||||
| `void writeStatus(JsonObject out) const` | Fills the `mqtt.status` diagnostics object (connect/disconnect counters, last reasons, forced resets). |
|
||||
| `void onNetworkConnected()` | Resets `_reconnectAttempts` and wakes the supervisor, which connects once WiFi has been up for 2 s. Not required for reconnects — the supervisor polls `WiFi.status()` itself. |
|
||||
| `void onNetworkDisconnected()` | Force-disconnects the client if connected. The supervisor reconnects once WiFi is back. |
|
||||
|
||||
---
|
||||
|
||||
## 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
|
||||
```
|
||||
|
||||
`begin()` creates one persistent **supervisor task** (`mqttSup`, 4 KB, priority 3) that owns everything time-driven: connect/reconnect with backoff, the 2 s network stabilisation, the 30 s heartbeat, and wedge detection. It replaced three FreeRTOS timers that each spawned a short-lived task per firing; one failed `xTaskCreate()` on a fragmented heap used to end the reconnect chain for good. See F-071.
|
||||
|
||||
---
|
||||
|
||||
## Reconnect Behaviour
|
||||
|
||||
| Attempts | Delay |
|
||||
|----------|-------|
|
||||
| 1–3 (quick retries) | 5 seconds each |
|
||||
| 4 | 10 seconds |
|
||||
| 5 | 20 seconds |
|
||||
| 6 | 40 seconds |
|
||||
| 7+ | Capped at 60 seconds |
|
||||
|
||||
Reconnect attempts are reset to 0 on a successful connection or a new `onNetworkConnected()` event.
|
||||
|
||||
### Self-recovery (wedge detection)
|
||||
|
||||
The supervisor forces a reset (`AsyncMqttClient::disconnect(true)`, then a normal reconnect) when:
|
||||
|
||||
| Condition | Why it happens |
|
||||
|---|---|
|
||||
| A connect attempt produced neither CONNACK nor a disconnect callback within 30 s (`"connect attempt stuck"`) | AsyncMqttClient ignores `AsyncClient::connect()`'s return value and stays in CONNECTING forever if it fails (e.g. lwIP out of PCBs); a failed `tcp_close` never fires onDisconnect. Every later `connect()` is then a silent no-op. |
|
||||
| A tracked QoS 1 publish has no PUBACK by its deadline: heartbeat 20 s (`"heartbeat PUBACK timeout"`), playback / report 8 s (`"playback PUBACK timeout"`, `"report PUBACK timeout"`) | Half-open socket or stalled send queue while the library still reports CONNECTED. |
|
||||
|
||||
Counters and last reasons are reported by `mqtt.status`.
|
||||
|
||||
### QoS policy
|
||||
|
||||
QoS 1 only for the heartbeat, `status/playback` and `control/reports`, all with PUBACK tracking; everything else QoS 0. The library sends its queue strictly in order and holds later packets until a QoS 1 PUBACK arrives, so each QoS 1 message costs whatever is behind it one round trip. Upstream also waited for the next ~500 ms TCP poll after each PUBACK; the vendored copy in `lib/AsyncMqttClient` is patched to send immediately (see its `VENDORED.md`). Plain QoS 1 recovers nothing here — with `cleanSession=true` the library drops unacked packets on reconnect — which is why delivery is guaranteed by the tracking + reset + republish/resend path instead.
|
||||
|
||||
---
|
||||
|
||||
## 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}`. The payload is kept in the `_willPayload` member: `setWill()` stores the raw pointer, and before F-071 it pointed at a freed temporary, so the broker published garbage as the LWT. `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 supervisor publishes the first heartbeat right after CONNACK, then every 30 s while connected. It is QoS 1 on purpose: if its PUBACK is missing after 20 s, the connection is treated as dead (see Self-recovery).
|
||||
|
||||
---
|
||||
|
||||
## Dependencies
|
||||
|
||||
- `AsyncMqttClient` — broker protocol
|
||||
- `ConfigManager` — MQTT host, port, credentials, enabled flag, device UID, per-topic switches (`MqttTopicConfig`)
|
||||
- `Networking` — IP and gateway for heartbeat (reconnect gating uses `WiFi.status()` directly)
|
||||
- FreeRTOS — one persistent supervisor task, woken by task notifications
|
||||
- `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.
|
||||
- **No per-event tasks.** Earlier versions spawned a short-lived task from every timer firing (reconnect, stabilisation, heartbeat). `xTaskCreate()` return values weren't checked, so on a fragmented heap a single failure silently ended MQTT until reboot. The supervisor task is allocated once at boot instead.
|
||||
- **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);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user