Multi-board variant support: - variants/vesper.hpp: enable HAS_RF=1, define RF_RX_PIN=22 - variants/agnus.hpp: enable HAS_RF=1, RF_RX_PIN=22, correct HAS_RTC=0 - main.cpp, Player, HealthMonitor, OTAManager, ConfigManager: wrap all RTC/SD/RF-dependent code in #if HAS_RTC / HAS_SD_CARD / HAS_RF guards so Agnus builds cleanly without those peripherals RFRemote subsystem (new): - src/RFRemote/: RF receiver driver (GPIO RF_RX_PIN) + command handler - Registered with HealthMonitor and CommunicationRouter when HAS_RF=1 Player improvements: - uid -> pid rename throughout (Player, BuiltInMelodies, api-reference) - loadMelodyInRAM() now returns bool - playerControlTaskFn task added — defers stop/pause/resume out of timer callback (Tmr Svc) to avoid stack overflows - setDependencies() accepts nullptr FileManager for SD-less boards OTAManager: - Consume download_url from server metadata response instead of constructing firmware path locally - HTTP redirect following enabled (setFollowRedirects) - HAS_RTC guards on TimeKeeper references platformio.ini: - Add rc-switch library for RF remote support - Remove BOARD_TYPE/BOARD_NAME/BOARD_VERSION flags (moved to variant headers) - MQTT_SECRET placeholders only — no secrets in source Docs: - docs/architecture/codebase-refactor-plan.md: new migration strategy doc - docs/reference/api-reference.md: updated for pid, note_assignments, download_url - Remove stale docs: ota-telemetry-api.md, platformio-commands.md, firmware-variants.md Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
16 KiB
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, noWire, noSPI, no SDK includes. - Calls hardware only through HAL interfaces (pointers/references to abstract classes).
- No
#ifdef BOARD_Xanywhere 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:
IOutputDriverdeclaresvirtual 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:
RfRemoteonly compiles when-D HAS_RF=1is 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.hlives (pins, output counts, feature flags). board_init.cppinstantiates the concrete drivers and passes them to core systems.- This is intentionally thin — just wiring, no logic.
5. platformio.ini Structure
; ── 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:
- Create
lib/features/Rs485RelayBridge/— the driver that talks to the Waveshare board over RS485/Modbus. - Create
boards/bespoke_rs485/— extends Vesper config, enablesFEATURE_RS485. - In
boards/bespoke_rs485/board_init.cpp, wire the RS485 driver toIOutputDriverinstead of the PCF8574 driver. - Ship this client a binary built from
env:bespoke_rs485. They always get OTA updates from this environment only. - 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:
// 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:
BellEnginedepends directly onConfigManager,Telemetry,OutputManager, andPlayer— all injected via constructor. Clean, butOutputManageris a concrete class, not an interface. In the new project it becomesIOutputDriver.ConfigManagerdoes too much: NVS factory settings, SD user settings, and MQTT auth derivation. In the new project these separate intoDeviceConfig(NVS, read-only),UserConfig(storage driver), andMqttAuth(core utility).FileManageris tightly coupled to SD. In the new project it becomesIStorageDriverwithSdCardDriverandNvsOnlyDriverimplementations.HealthMonitorhas hardcoded knowledge of which subsystems are critical vs warning. In the new project subsystems register themselves with a severity level.main.cppis the wiring layer but also contains NTP sync logic, UDP discovery, and loop management. In the new projectmain.cppis pure board init wiring; everything else moves to its module.variants/vesper.hpp/variants/agnus.hppare capability flag headers — good pattern, wrong location. In the new project these becomeboard_config.hinside each board folder.CommunicationRouter+CommandBus+ITransportpattern 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:
- Scaffold — new PlatformIO project, folder structure,
platformio.iniwith all envs (empty builds that compile clean). - HAL interfaces — write all
IXxxDriver.habstract classes first, before any implementation. - Port core modules — migrate
BellEngine,Player,ConfigManager,CommunicationRouter+CommandBus+handlers one by one. Compile-check against HAL interfaces only. - Port drivers — migrate concrete hardware code into
lib/drivers/. One driver at a time:Pcf8574OutputDriver(fromOutputManager)Ds3231Driver(fromTimekeeper)SdCardDriver(fromFileManager)NvsOnlyDriver(new, from Agnus config path inConfigManager)WifiDriver(fromNetworking)
- Wire Vesper first —
boards/vesper/board_init.cpp. Get one full board building and running before touching others. - Wire Agnus — derive from Vesper wiring, remove RTC/SD, verify Agnus env compiles and runs correctly.
- Port features —
RfRemote,UdpDiscoveryintolib/features/. - Add bespoke_rs485 — implement RS485 feature module, wire into its board env.
- 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_VESPERinsidelib/core/. If you feel the urge to do this, it means a feature belongs inlib/features/orboards/. - Do not share a single
main.cppacross boards. Each board has its own. The shared code is inlib/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.iniare the branching mechanism for hardware. - Do not reinvent the
CommunicationRouter/CommandBus/ITransportpattern — 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/andlib/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