# 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 Ds3231Driver rtcDriver; #endif #if HAS_SD_CARD #include SdCardDriver storageDriver; #else #include 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*