diff --git a/docs/README.md b/docs/README.md index 3f6d0c4..7dfc846 100644 --- a/docs/README.md +++ b/docs/README.md @@ -22,7 +22,8 @@ Bell automation firmware for ESP32 (Kincony KC868-A6). | File | Description | |---|---| -| [features/heartbeat.md](features/heartbeat.md) | MQTT heartbeat — retained 30s status publish | +| [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 @@ -38,3 +39,44 @@ Bell automation firmware for ESP32 (Kincony KC868-A6). |---|---| | [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 \ No newline at end of file diff --git a/docs/features/feature-catalog.md b/docs/features/feature-catalog.md new file mode 100644 index 0000000..4521adb --- /dev/null +++ b/docs/features/feature-catalog.md @@ -0,0 +1,248 @@ +# Feature Catalog + +This is the single source of truth for "what does this device actually do?" +Every feature — user-facing or significant internal mechanism — is listed here. +**Rule: every new feature or observable behaviour change gets an entry before or with its commit.** + +--- + +## Index + +| ID | Feature | Since | Status | +|---|---|---|---| +| F-001 | Relay-driven melody playback | pre-v2 | Stable | +| F-002 | Built-in melody library (PROGMEM) | pre-v2 | Stable | +| F-003 | SD-card melody download & storage | pre-v2 | Stable | +| F-004 | MQTT transport | pre-v2 | Stable | +| F-005 | WebSocket transport | pre-v2 | Stable | +| F-006 | UART/Serial transport | pre-v2 | Stable | +| F-007 | HTTP / AsyncWebServer transport | pre-v2 | Stable | +| F-008 | MQTT heartbeat (retained, 30 s) | v130 | Stable | +| F-009 | SemVer firmware versioning | v2.0.0 | Stable | +| F-010 | OTA update (FastAPI backend, safe-mode boot check) | v2.0.1 | Stable | +| F-011 | MQTT dynamic auth (HMAC-SHA256 device password) | v2.x | Stable | +| F-012 | HAL variant system (multi-board build flags) | v2.x | Stable | +| F-013 | RF Remote subsystem (HAS_RF variant) | v2.x | Stable | +| F-014 | NVS migration scaffold | v2.x | Stable | +| F-015 | Two-tier factory reset (5 s WiFi wipe / 10 s full reset) | v2.0.3 | Stable | +| F-016 | WiFi credential fallback chain (saved → failsafe → portal) | v2.0.3 | Stable | +| F-017 | SettingsWebServer (captive-portal config UI) | v2.0.3 | Stable | +| F-018 | Built-in melody `builtin_*` UID aliases (backward compat) | v2.0.3 | Stable | +| F-019 | NTP sync — fetch UTC, apply stored offsets manually | v2.0.3 | Stable | +| F-020 | Command envelope version default changed to v1 | v2.0.3 | Stable | +| F-021 | RelayHandler v1/v2 dual-format compatibility | v2.0.3 | Stable | +| F-022 | Player speed guard (zero-speed defaults to 300 ms) | v2.0.3 | Stable | +| F-023 | Telemetry bell max load default raised to 500 | v2.0.3 | Stable | + +--- + +## Feature Details + +--- + +### F-001 — Relay-driven melody playback + +The core function of the device. The Player subsystem reads a sequence of 16-bit bitmasks (one per step) from either a `.bsm` file on SD or the built-in PROGMEM library. Each bit maps to a relay output (bell). Relays fire at a configurable `speed` (ms per step). + +Key config: `speed` (ms/step), `note_assignments[16]` (relay index per note), `total_duration`, `continuous_loop`. +Subsystem: `src/Player/Player.cpp` + +--- + +### F-002 — Built-in melody library (PROGMEM) + +A set of hardcoded melodies stored in flash (PROGMEM) inside `src/BuiltInMelodies/BuiltInMelodies.hpp`. No SD card required to play these. Looked up by PID string. + +Lookup: `BuiltInMelodies::findMelodyByPID(pid)` and `BuiltInMelodies::isBuiltInMelody(pid)`. + +--- + +### F-003 — SD-card melody download & storage + +Melodies not found in the built-in library are downloaded from a URL (Firebase Storage) and stored as `.bsm` files on the SD card. FileManager handles download, write, and lookup. If the melody PID matches a built-in, the download is skipped entirely. + +Subsystem: `src/FileManager/FileManager.cpp` + +--- + +### F-004 — MQTT transport + +The device connects to a broker (VPS) and subscribes to `vesper/{deviceUID}/cmd`. Commands arrive as JSON envelopes. Responses are published back. Auth uses dynamic HMAC passwords (see F-011). + +Subsystem: `src/Communication/Transport/MQTTTransport/` + +--- + +### F-005 — WebSocket transport + +AsyncWebSocket on `/ws`. Commands arrive as JSON envelopes from browser or Node-RED. `clientId` is the WebSocket client ID for per-client responses. + +Subsystem: `src/Communication/Transport/WebSocketTransport/` + +--- + +### F-006 — UART/Serial transport + +Commands can be sent over Serial (USB). Useful for lab/dev work. JSON envelope format, same as other transports. + +Subsystem: `src/Communication/Transport/UARTTransport/` + +--- + +### F-007 — HTTP / AsyncWebServer transport + +REST-style HTTP endpoints via AsyncWebServer on port 80. Also hosts the SettingsWebServer (F-017). + +--- + +### F-008 — MQTT heartbeat (retained, 30 s) + +Every 30 seconds while MQTT is connected, a retained message is published to `vesper/{deviceUID}/status/heartbeat` with uptime, IP, firmware version, and gateway. Clients get the last status immediately on subscribe. + +See full details: [heartbeat.md](heartbeat.md) +Since: firmware v130 + +--- + +### F-009 — SemVer firmware versioning + +Version defined as `FW_VERSION` string in `src/Version.hpp`. Format `MAJOR.MINOR.PATCH`. Also exposes a `SemVer` struct for programmatic comparison. Changelog embedded in the same file. + +--- + +### F-010 — OTA update (FastAPI backend, safe-mode boot check) + +On every boot, before starting normal operation, the device queries the backend for a pending OTA. If one exists, it is applied immediately (boot-phase OTA, safe-mode). OTA can also be triggered via MQTT/WebSocket command at runtime. + +Backend: FastAPI on VPS. Binary served from Firebase Storage. + +--- + +### F-011 — MQTT dynamic auth (HMAC-SHA256 device password) + +Each device authenticates to the MQTT broker with: +- username: `deviceUID` (e.g. `PV000000000000`) +- password: `HMAC-SHA256(MQTT_SECRET, deviceUID).hexdigest()[:32]` + +`MQTT_SECRET` is compiled in via `platformio.ini`. The backend verifies the same derivation. Legacy password `vesper` still accepted but will be removed in Stage 7. + +--- + +### F-012 — HAL variant system (multi-board build flags) + +PlatformIO build flags (`HAS_RF`, `HAS_RTC`, `HAS_LCD`, etc.) select hardware capabilities at compile time. Code is guarded with `#if HAS_RF` etc. to produce board-specific binaries from a single codebase. + +Environments: `vesper-v1` (standard), others in progress. + +--- + +### F-013 — RF Remote subsystem (HAS_RF variant) + +When compiled with `HAS_RF`, the device can receive IR/RF remote control signals and map them to bell actions. + +--- + +### F-014 — NVS migration scaffold + +Versioned NVS key layout with a migration path. Allows future changes to stored settings without wiping existing devices. Migration code in `src/NvsMigration/`. + +--- + +### F-015 — Two-tier factory reset (5 s / 10 s button hold) + +The BOOT button (GPIO 0) supports two hold durations: + +| Hold | Action | +|---|---| +| < 5 s, then release | Short press — no action (reserved) | +| 5 s (while held) | WiFi credentials wiped immediately | +| Release between 5–10 s | Device restarts (WiFi-only reset complete) | +| 10 s (while held) | Full factory reset — all settings cleared, then restart | + +**Why two tiers:** A deployed device that loses WiFi connectivity needs a way to re-provision without losing all its bell configuration and schedule. The 5 s gesture wipes only the WiFi credentials (so WiFiManager will open the captive portal on next boot). The 10 s gesture is a last resort that wipes everything. + +Subsystem: `src/InputManager/InputManager.cpp` — `MEDIUM_PRESSED` state, `mediumPressMs = 5000`. +main.cpp callbacks: `handleWiFiCredsReset()`, `handleWiFiCredsResetRelease()`, `handleFactoryReset()`. + +--- + +### F-016 — WiFi credential fallback chain + +On WiFi connect attempt, the device tries credentials in order: + +1. **Saved credentials** (stored by WiFiManager from previous captive portal session) — `WiFi.begin()` +2. **Hardcoded failsafe** (compiled-in `defaultWifiSsid` / `defaultWifiPsk` from config) — after `MAX_WIFI_FAILURES = 2` on stage 1 +3. **Captive portal** (WiFiManager AP, boot-phase only) — after `MAX_WIFI_FAILURES = 2` on stage 2 + +Post-boot: if all credentials fail, cycle restarts from stage 1 indefinitely (no portal after boot). +After portal saves credentials: device **reboots** (not continues) so AsyncWebServer can bind port 80 cleanly. + +`_triedSavedCredentials` flag tracks which stage is active. +Subsystem: `src/Networking/Networking.cpp` + +--- + +### F-017 — SettingsWebServer (captive-portal config UI) + +A web UI served on port 80 that allows local configuration of the device (network settings, bell config, etc.) without needing MQTT or a mobile app. + +Instantiated as `settingsWebServer` in `main.cpp`. `begin()` called when network becomes ready. +Subsystem: `src/SettingsWebServer/SettingsWebServer.hpp` + +--- + +### F-018 — Built-in melody `builtin_*` UID aliases + +24 backward-compatibility PID aliases prefixed with `builtin_` that map to existing melody arrays. Devices shipped with old firmware used these PIDs in their schedules. The alias table ensures those schedules continue to work without SD downloads. + +Two new PROGMEM arrays added: `builtin_catehetical`, `bulitin_mournfull_toll_alternative`. +`isBuiltInMelody(pid)` helper added for O(n) lookup without needing the full `MelodyInfo*`. +Subsystem: `src/BuiltInMelodies/BuiltInMelodies.hpp` + +--- + +### F-019 — NTP sync: fetch UTC, apply stored offsets manually + +Previous behaviour: `configTime(gmtOffset, dstOffset, ntpServer)` let the ESP-IDF SDK apply offsets internally, which caused double-application bugs when the SDK also read stored timezone state. + +Current behaviour: `configTime(0, 0, ntpServer)` fetches raw UTC. Stored `gmtOffsetSec + daylightOffsetSec` are added manually to the UTC epoch before writing to RTC. Logged as both UTC and local time. + +Subsystem: `src/TimeKeeper/TimeKeeper.cpp:syncTimeWithNTP()` + +--- + +### F-020 — Command envelope version default changed to v1 + +When an incoming JSON command does not include a `"v"` field, the envelope version defaults to **1** (was 2). This matches the actual format sent by the mobile app and Node-RED flows, fixing a regression where the v2 default caused the legacy adapter to reject commands from these clients. + +Affected transports: MQTT, UART, WebSocket. + +--- + +### F-021 — RelayHandler v1/v2 dual-format compatibility + +`relay.set_durations` and `relay.set_outputs` now accept two payload shapes: +- **v2:** `{ "bells": { "b1": ..., "b2": ... } }` — bells nested under a `"bells"` key +- **v1:** `{ "b1": ..., "b2": ... }` — bells at the top level of `contents` + +The handler checks `contents["bells"].is()` and unpacks accordingly. + +Subsystem: `src/Communication/Handlers/RelayHandler/RelayHandler.cpp` + +--- + +### F-022 — Player speed guard + +If the incoming playback command contains `"speed": 0` (or omits it and JSON parsing produces 0), the Player now defaults to `300 ms` per step instead of dividing by zero / producing silent playback. + +Also guards `calculateProjectedRunTime()` against `singleLoopDuration == 0`. + +Subsystem: `src/Player/Player.cpp:setMelodyAttributes()` + +--- + +### F-023 — Telemetry bell max load default raised to 500 + +`bellMaxLoad[i]` initialised to `500` (was `200`). This is the denominator used to calculate bell load percentage in telemetry reports. The old value caused false "overload" warnings on normal use patterns. + +Subsystem: `src/Telemetry/Telemetry.cpp:begin()`