From 42585f7eb78e76636734757036d1c2464b2739b7 Mon Sep 17 00:00:00 2001 From: bring42 Date: Sat, 12 Sep 2026 21:10:42 +0200 Subject: [PATCH] feat(led): runtime-selectable strip type, colour order and data pin MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The strip chipset, byte order and GPIO were compile-time template arguments to FastLED.addLeds<>(), so every wiring change meant a reflash. They are now device settings — persisted in NVS, editable from the web UI (Settings → Device) or POST /api/config, and bound at boot like ledCount. No template explosion: on the ESP32 FastLED's RmtController takes the pin and the three bit timings as plain constructor arguments; the addLeds<> template parameters only ever fed it those numbers. core/led_hardware.h is a pure catalog (FastLED's chipsets.h timings in ns + a per-chip usable-pin policy), and FastLedOutput builds one small CPixelLEDController per colour order from it. Non-ESP32 / RMT5 builds keep the compile-time defaults path. - 13 chipsets: WS2812B, WS2811, WS2813, WS2815, SK6812, SK6812_RGBW (4-byte, W derived by FastLED's default Rgbw mode), SK6822, WS2811_400, UCS1903, UCS1904, SM16703, TM1809, PL9823; orders RGB/RBG/GRB/GBR/BRG/BGR. - Pin policy per target (S3 / C3 / classic): flash & PSRAM bus, native USB pair and unbonded numbers are refused with 400; strapping pins are offered but flagged. Values are validated BEFORE any config field is applied, and again on NVS load (fallback to the build defaults, never a flash pin). - GET /api/config gains ledType/ledColorOrder/ledPin, the per-chip option lists (ledOptions) and what the running firmware is bound to (ledActive); /api/v2/info reports the bound hardware too. - POST /api/restart: auth-gated, replies 202, reboots from the loop task after flushing the segment layout — so boot-time settings apply without a power cycle. - Web UI: Strip Type / Color Order / Data Pin selects populated from the device, an amber "Restart to apply: …" notice whenever persisted ≠ active (ledCount included), and a Restart device button. - LED_STRIP_TYPE / LED_COLOR_MODE / LED_DATA_PIN (and -DLUME_LED_DATA_PIN) now set only the factory default; docs updated accordingly. - Native tests: test_led_hardware (catalog round-trips, FastLED timing parity, pin policies). 91/91 pass; S3 and C3 firmware build clean. Co-Authored-By: Claude Fable 5.1 --- data/assets/app.css | 39 ++++ data/assets/app.js | 81 +++++++- data/assets/engine.js | 20 ++ data/index.html | 27 +++ docs/API_V2.md | 50 ++++- docs/HARDWARE.md | 105 ++++++---- platformio.ini | 5 +- src/api/config.cpp | 67 ++++++- src/api/config.h | 2 + src/api/segments.cpp | 6 + src/constants.h | 22 ++- src/core/README.md | 9 +- src/core/controller.cpp | 8 +- src/core/controller.h | 13 +- src/core/fastled_output.h | 94 ++++++++- src/core/led_hardware.h | 196 +++++++++++++++++++ src/core/led_output.h | 7 +- src/main.cpp | 29 ++- src/main.h | 5 + src/network/server.cpp | 2 + src/secrets.h.example | 3 +- src/storage.cpp | 58 +++++- src/storage.h | 9 +- test/test_command_bus/test_command_bus.cpp | 2 +- test/test_led_hardware/test_led_hardware.cpp | 144 ++++++++++++++ 25 files changed, 920 insertions(+), 83 deletions(-) create mode 100644 src/core/led_hardware.h create mode 100644 test/test_led_hardware/test_led_hardware.cpp diff --git a/data/assets/app.css b/data/assets/app.css index 6685fe5..9b2a030 100644 --- a/data/assets/app.css +++ b/data/assets/app.css @@ -1385,6 +1385,45 @@ input, button, textarea{ font-family: inherit; color: inherit; } } .jack-input:disabled{ opacity: 0.4; } +/* + +
+ Strip Type +
+ +
+
+
+
+ Color Order +
+ +
+
+
+ Data Pin +
+ +
+
+
+
+ Strip settings apply after a restart + +
Firmware
diff --git a/docs/API_V2.md b/docs/API_V2.md index aad2e93..999b7a8 100644 --- a/docs/API_V2.md +++ b/docs/API_V2.md @@ -375,12 +375,15 @@ Lightweight metadata for UIs to discover firmware details and capability limits. "aiPrompts": true, "ota": true }, - "controller": { "ledCount": 160, "power": true } + "controller": { "ledCount": 160, "ledType": "WS2812B", "ledColorOrder": "GRB", "ledPin": 2, "power": true } } ``` `limits.maxLeds` is the compile-time `MAX_LED_COUNT` (default 1000). `features.sacn` and `features.mqtt` reflect the current config (whether each is enabled), not just build support. +`controller.ledType` / `ledColorOrder` / `ledPin` are the strip hardware the output driver is +**bound to this boot**; the persisted selection (which may differ until a restart) is in +`GET /api/config`. --- @@ -416,6 +419,17 @@ Get device configuration (passwords/API keys masked). { "wifiSSID": "MyNetwork", "ledCount": 160, + "ledType": "WS2812B", + "ledColorOrder": "GRB", + "ledPin": 2, + "ledActive": { "ledType": "WS2812B", "ledColorOrder": "GRB", "ledPin": 2, "ledCount": 160 }, + "ledOptions": { + "types": [ { "id": "WS2812B", "name": "WS2812B / WS2812 (800 kHz)" }, + { "id": "SK6812_RGBW", "name": "SK6812 RGBW", "rgbw": true }, "..." ], + "colorOrders": [ "RGB", "RBG", "GRB", "GBR", "BRG", "BGR" ], + "pins": [ 0, 1, 2, "..." ], + "strappingPins": [ 0, 3, 45, 46 ] + }, "aiApiKey": "****", "aiApiKeySet": true, "aiModel": "claude-haiku-4-5", @@ -426,6 +440,23 @@ Get device configuration (passwords/API keys masked). } ``` +**LED hardware** — the strip chipset, colour byte order and data pin are runtime settings +(persisted in NVS, no reflash): + +- `ledType` — one of `ledOptions.types[].id`: `WS2812B` (also WS2812 / WS2852 / GS1903), + `WS2811`, `WS2813`, `WS2815`, `SK6812`, `SK6812_RGBW`, `SK6822` (also APA106), + `WS2811_400`, `UCS1903`, `UCS1904`, `SM16703`, `TM1809`, `PL9823`. Bit timings mirror FastLED's + `chipsets.h`. `rgbw: true` entries drive 4-byte pixels; white is derived from RGB + (FastLED's default Rgbw mode) — the pipeline is RGB-only upstream. +- `ledColorOrder` — the byte order on the wire (`GRB` for WS2812B, `RGB` for most WS2811). +- `ledPin` — must be one of `ledOptions.pins`: the GPIOs this chip may drive, excluding the + flash/PSRAM bus, the native-USB pair and unbonded numbers. Strapping pins are listed (they + work once booted) and flagged in `strappingPins`. +- `ledActive` — what the running firmware is **actually bound to**; differs from the persisted + values above until the next restart (`POST /api/restart`). +- `ledOptions` is per build/chip (the S3 and C3 pin lists differ). A UI should populate its + controls from it rather than hardcoding. + ### POST /api/config Update device configuration. @@ -436,6 +467,9 @@ Update device configuration. "wifiSSID": "NewNetwork", "wifiPassword": "newpass", "ledCount": 160, + "ledType": "SK6812", + "ledColorOrder": "GRB", + "ledPin": 4, "aiApiKey": "sk-ant-...", "aiModel": "claude-haiku-4-5", "sacnEnabled": true, @@ -448,8 +482,18 @@ Update device configuration. - Omit password fields to leave unchanged. - Protocol changes (sACN/MQTT) are re-applied through the bus via a `ReconfigureProtocols` command on the render loop — not live from the web task. -- `ledCount` changes are deferred and take effect on reboot (P0.8). WiFi changes restart the - device. +- `ledCount`, `ledType`, `ledColorOrder` and `ledPin` are deferred and take effect on reboot + (P0.8 — the output driver binds pins/peripherals once, at boot). Use `POST /api/restart`. + WiFi changes make the device try the new network immediately. +- An unknown `ledType`/`ledColorOrder`, or a `ledPin` outside `ledOptions.pins`, is rejected + with **400** `{"error": "ledPin: not a usable LED data pin on this chip"}` before *any* + field of the request is applied. + +### POST /api/restart + +Reboot the device so boot-time settings (LED hardware, `ledCount`) take effect. Requires auth +when a token is configured. Replies **202** `{"status":"restarting"}` first; the reboot runs +from the loop task ~250 ms later (a pending segment-layout save is flushed on the way out). ### POST /api/pixels diff --git a/docs/HARDWARE.md b/docs/HARDWARE.md index 6c1a5a0..193fda7 100644 --- a/docs/HARDWARE.md +++ b/docs/HARDWARE.md @@ -50,19 +50,22 @@ Then either: **Can't find your exact board?** Use `esp32-s3-devkitc-1` or `esp32-c3-devkitm-1` as generic fallbacks — they usually work. -#### 2. Set LED Data Pin in `src/constants.h` +#### 2. Pick the LED Data Pin (no code change needed) -Check your board's pinout diagram and choose a free GPIO pin: -```cpp -#define LED_DATA_PIN 8 // ← Default for ESP32-C3 (change to match your wiring) -``` +The data pin, strip type and colour order are **runtime settings**: after the first flash, open +the web UI → Settings → *02 · Device* and pick them, then *Restart device*. The pin list the UI +offers is generated by the firmware for your chip (flash/PSRAM and USB pins are never offered). + +The compile-time **default** (what a factory-fresh board boots with) is GPIO 2 on the S3 envs and +GPIO 4 on the C3 envs (`-DLUME_LED_DATA_PIN` in `platformio.ini`; falls back to `LED_DATA_PIN` +in `src/constants.h`). Change it only if you want a different out-of-the-box pin. -**ESP32-C3 safe pins:** GPIO 0-1, 4-7, 10, 18-21 (avoid GPIO 2-3, 8-9, 11-17 used for flash/strapping) +**ESP32-C3 safe pins:** GPIO 0-1, 4-7, 10, 20-21 (2-3, 8-9 are strapping; 11-17 flash; 18-19 USB) **ESP32-S3 safe pins:** Most GPIO pins work, common choices: 2, 5, 16, 21, 48 **Safe GPIO choices for ESP32-S3:** -- ✅ Good: 2, 5, 12-14, 16-21, 35-37, 47-48 -- ⚠️ Avoid: 0 (boot button), 19-20 (USB), 45-46 (strapping pins) +- ✅ Good: 2, 5, 12-14, 16-18, 21, 38-44, 47-48 +- ⚠️ Avoid: 0 (boot button), 3/45/46 (strapping pins), 19-20 (USB), 26-37 (flash / PSRAM — refused) #### 3. Adjust Build Flags (If Needed) @@ -198,32 +201,36 @@ FastLED will automatically dim LEDs to stay within the power budget. ## GPIO Pin Configuration -**Default data pin: GPIO 21** +**Default data pin: GPIO 2 (S3 envs) / GPIO 4 (C3 envs)** -To use a different GPIO pin: +The data pin is a **runtime setting** — no rebuild, no reflash: -1. Edit [constants.h](../src/constants.h) -2. Change `LED_DATA_PIN` to your desired GPIO: - ```cpp - #define LED_DATA_PIN 16 // Example: use GPIO 16 instead - ``` -3. Rebuild and flash: `pio run -t upload` +1. Open the web UI → Settings → *02 · Device* → **Data Pin** +2. Pick the GPIO (the list is generated for your chip; strapping pins are marked) +3. Click **Restart device** — the pin binds at boot + +Or over the API: `POST /api/config {"ledPin": 16}` then `POST /api/restart` +(see [API_V2.md](API_V2.md#get-apiconfig)). Pins on the flash/PSRAM bus, the native USB pair and +unbonded numbers are refused with a 400 — the firmware will never bind them. -> **Note:** The pin is set at compile time (FastLED requirement). Changing it requires reflashing. +To change the **factory default** instead (what a fresh board boots with before anyone opens the +UI), set `-DLUME_LED_DATA_PIN=` in the board's `build_flags` in `platformio.ini`. ### Recommended GPIOs for ESP32-S3 | GPIO | Safe? | Notes | |------|-------|-------| -| 2, 5 | ✅ Good | Commonly available, safe choices | +| 2 | ✅ Default | Current default pin | +| 5 | ✅ Good | Commonly available, safe choice | | 12-14 | ✅ Good | General purpose | | 16-18 | ✅ Good | General purpose | -| 21 | ✅ Default | Current default pin | -| 35-37 | ✅ Good | General purpose | +| 21 | ✅ Good | General purpose | +| 38-44 | ✅ Good | General purpose, but check your board | | 47-48 | ✅ Good | General purpose, but check your board | -| 0 | ⚠️ Avoid | Boot button | -| 19-20 | ⚠️ Avoid | USB D- and D+ | -| 45-46 | ⚠️ Avoid | Strapping pins, can cause boot issues | +| 0 | ⚠️ Offered, marked | Boot button / strapping | +| 3, 45-46 | ⚠️ Offered, marked | Strapping pins, can cause boot issues | +| 19-20 | ❌ Refused | USB D- and D+ (console + upload) | +| 26-37 | ❌ Refused | SPI flash (26-32) / octal PSRAM (33-37) | **Check your board's pinout!** Some boards use certain GPIOs for onboard peripherals (display, buttons, SD card, etc.). Consult your board's documentation or schematic. @@ -231,23 +238,36 @@ To use a different GPIO pin: ## LED Strip Types -The firmware is configured for **WS2812B (GRB)** strips. To use other types: - -Edit [core/controller.cpp](../src/core/controller.cpp): - -```cpp -// WS2812B (most common, GRB order) -FastLED.addLeds(leds_, ledCount_); - -// WS2811 (12V strips, RGB order) -FastLED.addLeds(leds_, ledCount_); - -// SK6812 (RGBW - note: W channel not yet supported) -FastLED.addLeds(leds_, ledCount_); - -// APA102/SK9822 (2-wire, needs clock pin) -FastLED.addLeds(leds_, ledCount_); -``` +The strip **chipset** and **colour order** are runtime settings too (Settings → *02 · Device* → +*Strip Type* / *Color Order*, then *Restart device*), or `POST /api/config {"ledType": "...", +"ledColorOrder": "..."}` + `POST /api/restart`. Factory default: **WS2812B, GRB**. + +Available types (bit timings mirror FastLED's `chipsets.h`): + +| `ledType` | Strips | Typical order | +|-----------|--------|---------------| +| `WS2812B` | WS2812B, WS2812, WS2852, GS1903, most "NeoPixel" strips | GRB | +| `WS2811` | 12 V WS2811 "bullet"/string pixels | RGB | +| `WS2813` | WS2813 (backup data line) | GRB | +| `WS2815` | 12 V WS2815 (backup data line) | GRB | +| `SK6812` | SK6812 RGB | GRB | +| `SK6812_RGBW` | SK6812 RGBW (4-channel) | GRB | +| `SK6822` | SK6822, APA106 | RGB | +| `WS2811_400` | 400 kHz WS2811 | RGB | +| `UCS1903` | UCS1903 (400 kHz) | RGB | +| `UCS1904` | UCS1904 | RGB | +| `SM16703` | SM16703 | RGB | +| `TM1809` | TM1809 | RGB | +| `PL9823` | PL9823 | RGB | + +Notes: +- **RGBW:** `SK6812_RGBW` drives 4-byte pixels. The render pipeline is RGB throughout; the + white channel is derived per pixel by FastLED's default Rgbw mode (W = min(R,G,B), subtracted + from the colour). Untested on hardware at the time of writing — report what you see. +- **Clocked strips** (APA102 / SK9822 / WS2801, 2-wire with a clock pin) are not selectable — + the runtime backend is the ESP32 RMT (single-wire clockless) driver. +- The **factory default** can be changed with `-DLED_STRIP_TYPE= -DLED_COLOR_MODE=` in + `build_flags` (the ids above; orders `RGB RBG GRB GBR BRG BGR`). --- @@ -284,8 +304,9 @@ FastLED.addLeds(leds_, ledCount_); ### Colors are wrong -- Check color order (GRB vs RGB) -- Edit `FastLED.addLeds` → try `RGB` or `BRG` +- Check color order (GRB vs RGB): Settings → *02 · Device* → **Color Order**, try `RGB` or `BRG`, + then *Restart device* — no reflash needed +- Set a solid red via the UI first: if it shows green, you have GRB↔RGB swapped; blue means BRG ### Random flickering diff --git a/platformio.ini b/platformio.ini index c9f37f3..f4a06f1 100644 --- a/platformio.ini +++ b/platformio.ini @@ -5,7 +5,9 @@ ; - Default: esp32-s3-devkitc-1 (generic ESP32-S3 DevKit) ; - For LILYGO T-Display S3: Change 'default_envs' to 'lilygo-t-display-s3' ; - For other boards: Add your own [env:...] section or modify existing ones -; - Set LED_DATA_PIN, LED_STRIP_TYPE and LED_COLOR_MODE in src/constants.h for your wiring +; - Strip type / colour order / data pin are RUNTIME settings (web UI -> Device, or +; POST /api/config). LED_DATA_PIN / LED_STRIP_TYPE / LED_COLOR_MODE in src/constants.h +; (or -DLUME_LED_DATA_PIN etc. in build_flags) only set the factory DEFAULT. ; - Run: pio boards esp32-s3 (to list available boards) ; ; 🚀 UPLOAD COMMANDS: @@ -201,6 +203,7 @@ test_filter = ; run these suites (skip the stubs/ helper dir) test_scratchpad test_transition test_render16 + test_led_hardware test_build_src = no ; tests include the headers/sources under test directly build_flags = -std=c++17 diff --git a/src/api/config.cpp b/src/api/config.cpp index 7e05603..8837068 100644 --- a/src/api/config.cpp +++ b/src/api/config.cpp @@ -17,7 +17,40 @@ static String configBodyBuffer; void handleApiConfig(AsyncWebServerRequest* request) { JsonDocument doc; storage.configToJson(config, doc, true); - + + // The selectable LED hardware for THIS build/chip, so the UI never has to + // hardcode the catalog: strip types (with the RGBW flag), colour orders and + // the data pins this chip may drive (strapping pins flagged, not hidden). + JsonObject options = doc["ledOptions"].to(); + JsonArray types = options["types"].to(); + size_t n; + const lume::LedChipsetInfo* cat = lume::ledChipsetCatalog(n); + for (size_t i = 0; i < n; i++) { + JsonObject t = types.add(); + t["id"] = cat[i].key; + t["name"] = cat[i].name; + if (cat[i].rgbw) t["rgbw"] = true; + } + JsonArray orders = options["colorOrders"].to(); + for (uint8_t i = 0; i < (uint8_t)lume::LedColorOrder::COUNT; i++) { + orders.add(lume::ledColorOrderKey((lume::LedColorOrder)i)); + } + JsonArray pins = options["pins"].to(); + JsonArray strapping = options["strappingPins"].to(); + for (int pin = 0; pin < 64; pin++) { + if (!lume::isUsableLedPin(pin)) continue; + pins.add(pin); + if (lume::isStrappingLedPin(pin)) strapping.add(pin); + } + // What the output driver is ACTUALLY bound to right now (differs from the + // persisted values above until the next reboot) — lets the UI say so. + const lume::LedHardware& active = lume::controller.getLedHardware(); + JsonObject act = doc["ledActive"].to(); + act["ledType"] = lume::ledChipsetKey(active.chipset); + act["ledColorOrder"] = lume::ledColorOrderKey(active.order); + act["ledPin"] = active.pin; + act["ledCount"] = lume::controller.getLedCount(); + String response; serializeJson(doc, response); request->send(200, "application/json", response); @@ -65,16 +98,27 @@ void handleApiConfigPost(AsyncWebServerRequest* request, uint8_t* data, size_t l // while the provisioning phone sits on the SoftAP. String prevWifiSsid = config.wifiSSID; String prevWifiPass = config.wifiPassword; - storage.configFromJson(config, doc); + String fieldError; + if (!storage.configFromJson(config, doc, &fieldError)) { + // Rejected before anything was applied (LED hardware validation). + JsonDocument errDoc; + errDoc["error"] = fieldError; + String body; + serializeJson(errDoc, body); + request->send(400, "application/json", body); + return; + } bool wifiCredsChanged = (config.wifiSSID != prevWifiSsid || config.wifiPassword != prevWifiPass); // Save to storage if (storage.saveConfig(config)) { - // ledCount is NOT applied live: it's bound to FastLED at boot via - // controller.begin(config.ledCount), so changing it live raced the - // render loop and never re-ran addLeds anyway (P0.8). It now takes - // effect on the next reboot, from the value just persisted above. + // ledCount and the LED hardware (ledType / ledColorOrder / ledPin) + // are NOT applied live: they're bound to FastLED at boot via + // controller.begin(count, hardware) — FastLED's controller list has + // no remove, and re-binding live raced the render loop (P0.8). They + // take effect on the next reboot (POST /api/restart), from the + // values just persisted above. // sACN/MQTT are NOT reconfigured from this (AsyncTCP) task either — // stop()/setConfig() tore down sockets / swapped Strings that @@ -105,3 +149,14 @@ void handleApiConfigPost(AsyncWebServerRequest* request, uint8_t* data, size_t l } } } + +void handleApiRestart(AsyncWebServerRequest* request) { + if (!checkAuth(request)) { + sendUnauthorized(request); + return; + } + // Reply first, reboot from the loop task: ESP.restart() on this (AsyncTCP) + // task would tear the socket down under the response. + request->send(202, "application/json", "{\"status\":\"restarting\"}"); + requestRestart(); +} diff --git a/src/api/config.h b/src/api/config.h index ecbc86d..33aeb99 100644 --- a/src/api/config.h +++ b/src/api/config.h @@ -5,3 +5,5 @@ // System configuration management void handleApiConfig(AsyncWebServerRequest* request); void handleApiConfigPost(AsyncWebServerRequest* request, uint8_t* data, size_t len, size_t index, size_t total); +// POST /api/restart — reboot so boot-time settings (LED hardware, ledCount) apply. +void handleApiRestart(AsyncWebServerRequest* request); diff --git a/src/api/segments.cpp b/src/api/segments.cpp index 5b50611..917d07a 100644 --- a/src/api/segments.cpp +++ b/src/api/segments.cpp @@ -492,6 +492,12 @@ void handleApiV2Info(AsyncWebServerRequest* request) { JsonObject controllerInfo = doc["controller"].to(); controllerInfo["ledCount"] = lume::controller.getLedCount(); + // The hardware the output driver is bound to (what's actually driving the + // wire this boot — the persisted selection lives in GET /api/config). + const lume::LedHardware& hw = lume::controller.getLedHardware(); + controllerInfo["ledType"] = lume::ledChipsetKey(hw.chipset); + controllerInfo["ledColorOrder"] = lume::ledColorOrderKey(hw.order); + controllerInfo["ledPin"] = hw.pin; controllerInfo["power"] = lume::controller.getTargetPower(); String output; diff --git a/src/constants.h b/src/constants.h index 35dabcd..d8aabdb 100644 --- a/src/constants.h +++ b/src/constants.h @@ -7,12 +7,15 @@ // ═══════════════════════════════════════════════════════════════════════════ // ⚠️ LED CONFIGURATION // ═══════════════════════════════════════════════════════════════════════════ -// Settings used to configure FastLED in controller.cpp -// Customize these for your specific hardware setup - -// Pick a free GPIO for the LED data line (board-dependent): -// ESP32-C3: safe 0-1, 4-7, 10, 18-21; avoid 2-3, 8-9 (strapping), 11-17 (flash) -// ESP32-S3: most GPIOs are free; avoid 0/3/45/46 (strapping) and 26-32 (flash) +// The LED hardware (strip chipset, colour byte order, data pin) is a RUNTIME +// setting: persisted in NVS, editable from the web UI / POST /api/config, and +// applied at boot (see core/led_hardware.h + core/fastled_output.h). The values +// below are only the compile-time DEFAULTS — what a factory-fresh board runs, +// and what an invalid persisted value falls back to. + +// Default data pin (board-dependent): +// ESP32-C3: safe 0-1, 4-7, 10, 20-21; avoid 2-3, 8-9 (strapping), 11-17 (flash), 18-19 (USB) +// ESP32-S3: most GPIOs are free; avoid 0/3/45/46 (strapping), 19-20 (USB), 26-37 (flash/PSRAM) // Override per-env with -DLUME_LED_DATA_PIN= in platformio.ini's build_flags // (e.g. the C3 boards need a non-strapping pin; GPIO2 is fine on S3/T-Display S3). #ifdef LUME_LED_DATA_PIN @@ -20,8 +23,11 @@ #else #define LED_DATA_PIN 2 // GPIO2 (T-Display S3: broken out, not a strapping pin) #endif -// Strip type + byte order. Guarded so a board env (or local build) can retarget -// other hardware via build_flags without editing the defaults, e.g.: +// Default strip type + byte order. The names are lume::LedChipset / +// lume::LedColorOrder enumerators (core/led_hardware.h lists them: WS2812B, +// WS2811, WS2813, WS2815, SK6812, SK6812_RGBW, SK6822, WS2811_400, UCS1903, +// UCS1904, SM16703, TM1809, PL9823; RGB, RBG, GRB, GBR, BRG, BGR). Guarded so a +// board env (or local build) can change the factory default via build_flags: // build_flags = -DLED_STRIP_TYPE=SM16703 -DLED_COLOR_MODE=BRG #ifndef LED_STRIP_TYPE #define LED_STRIP_TYPE WS2812B // Common addressable RGB LED diff --git a/src/core/README.md b/src/core/README.md index 33421f8..aa9ac9d 100644 --- a/src/core/README.md +++ b/src/core/README.md @@ -54,9 +54,14 @@ void effectSolid(SegmentView& view, const ParamValues& params, runtime values effects read by slot. `param_codec.h` is the single schema-aware (de)serializer shared by the API and persistence (P1.1). -### Output HAL ([led_output.h](led_output.h), [fastled_output.h](fastled_output.h)) +### Output HAL ([led_output.h](led_output.h), [fastled_output.h](fastled_output.h), [led_hardware.h](led_hardware.h)) The controller presents finished frames through the `ILedOutput` interface; `FastLedOutput` -(RMT) is the default backend (RFC 0001 §6). +(RMT) is the default backend (RFC 0001 §6). The strip hardware it binds — chipset, colour +order, data pin — is a runtime `LedHardware` (persisted config, applied at boot): on the ESP32 +FastLED's `RmtController` takes pin and bit timings as constructor arguments, so +`led_hardware.h` is a plain catalog (FastLED's timings in ns + a per-chip usable-pin policy) +and `FastLedOutput` builds one small `CPixelLEDController` per colour order from it — no +per-pin/per-chipset template explosion. ## Architecture diff --git a/src/core/controller.cpp b/src/core/controller.cpp index bc1c85d..2120e8f 100644 --- a/src/core/controller.cpp +++ b/src/core/controller.cpp @@ -47,14 +47,16 @@ LumeController::LumeController() , segmentsDirty_(false) , suppressDirty_(false) , lastSegmentChange_(0) - , output_(&g_fastLedOutput) { + , output_(&g_fastLedOutput) + , hardware_(LedHardware::defaults()) { memset(leds, 0, sizeof(leds)); memset(protocols_, 0, sizeof(protocols_)); } -void LumeController::begin(uint16_t count) { +void LumeController::begin(uint16_t count, const LedHardware& hw) { ledCount = min(count, (uint16_t)MAX_LED_COUNT); + hardware_ = hw; // Initialize command queue if (!commandQueue.begin()) { @@ -62,7 +64,7 @@ void LumeController::begin(uint16_t count) { } // Initialize the LED output driver (FastLED by default; see RFC 0001 §6). - output_->begin(leds, ledCount); + output_->begin(leds, ledCount, hardware_); // The 16-bit pipeline owns all brightness/gamma/correction/dither, so the // driver's own scaling is pinned to identity (255) once and never touched // again — master brightness is applied per-pixel in renderOutput16(). diff --git a/src/core/controller.h b/src/core/controller.h index 3ca89ec..685cef6 100644 --- a/src/core/controller.h +++ b/src/core/controller.h @@ -50,8 +50,16 @@ class LumeController { // --- Initialization --- - // Initialize with LED count (uses LED_DATA_PIN from constants.h) - void begin(uint16_t count); + // Initialize with LED count and the hardware selection (chipset / colour + // order / data pin) the output driver binds to. Hardware is bound ONCE: + // changing it later takes a reboot (drivers own pins and peripherals). + void begin(uint16_t count, const LedHardware& hw); + // Compile-time defaults (constants.h) — host tests and legacy callers. + void begin(uint16_t count) { begin(count, LedHardware::defaults()); } + + // The hardware the output driver was bound to at begin(). The API reports + // it next to the persisted config so a UI can flag "restart to apply". + const LedHardware& getLedHardware() const { return hardware_; } // Swap the LED-output driver (RFC 0001 §6). Defaults to FastLED; call before // begin() to inject a different ILedOutput (ESP-IDF led_strip, emulator, a @@ -360,6 +368,7 @@ class LumeController { // LED output driver (RFC 0001 §6). Defaults to a FastLED impl in the ctor. ILedOutput* output_; + LedHardware hardware_; // what output_ was bound to at begin() // Segments Segment segments[MAX_SEGMENTS]; diff --git a/src/core/fastled_output.h b/src/core/fastled_output.h index 725085d..7f164f3 100644 --- a/src/core/fastled_output.h +++ b/src/core/fastled_output.h @@ -3,18 +3,102 @@ #include #include "led_output.h" +#include "led_hardware.h" #include "../constants.h" +#include "../logging.h" + +// On the ESP32 family FastLED's clockless driver is the RMT peripheral, and its +// RmtController (idf4_rmt.h) takes the data pin and the three bit timings as +// plain constructor arguments — the chipset/pin template parameters of +// FastLED.addLeds<...>() exist only to feed it those numbers. So the runtime +// strip selection needs no template explosion: one small CPixelLEDController +// per colour order (six, a few hundred bytes each) wraps an RmtController built +// from the persisted LedHardware at boot. +#if defined(ESP32) && !FASTLED_RMT5 +#define LUME_RUNTIME_LED_HARDWARE 1 +#else +#define LUME_RUNTIME_LED_HARDWARE 0 +#endif namespace lume { -// The default ILedOutput: FastLED's RMT driver for WS2812B (RFC 0001 §6). The -// strip type / pin / color order / power limits come from constants.h. This is -// the only place the render core touches the FastLED *driver* (as opposed to its -// math); swapping platforms means providing a different ILedOutput. +#if LUME_RUNTIME_LED_HARDWARE +// Mirror of FastLED's ESP32 ClocklessController (idf4_clockless_rmt_esp32.h), +// minus the compile-time pin/timing: same RMT backend, same showPixels path, +// same FASTLED_ESP32_FLASH_LOCK / FASTLED_RMT_MAX_CHANNELS behaviour. +template +class RuntimeRmtController : public CPixelLEDController { +public: + RuntimeRmtController(int pin, int t1, int t2, int t3) + : rmt_(pin, t1, t2, t3, FASTLED_RMT_MAX_CHANNELS, FASTLED_RMT_BUILTIN_DRIVER) {} + void init() override {} + uint16_t getMaxRefreshRate() const override { return 400; } +protected: + void showPixels(PixelController& pixels) override { + PixelIterator iterator = pixels.as_iterator(this->getRgbw()); + rmt_.showPixels(iterator); + } +private: + RmtController rmt_; +}; + +template +static CLEDController* makeRuntimeRmt(int pin, int t1, int t2, int t3) { + // Allocated once at boot and bound into FastLED's controller list, which + // has no remove — hence "hardware changes apply on reboot". + return new RuntimeRmtController(pin, t1, t2, t3); +} + +inline CLEDController* makeRuntimeRmt(LedColorOrder order, int pin, int t1, int t2, int t3) { + switch (order) { + case LedColorOrder::RGB: return makeRuntimeRmt(pin, t1, t2, t3); + case LedColorOrder::RBG: return makeRuntimeRmt(pin, t1, t2, t3); + case LedColorOrder::GBR: return makeRuntimeRmt(pin, t1, t2, t3); + case LedColorOrder::BRG: return makeRuntimeRmt(pin, t1, t2, t3); + case LedColorOrder::BGR: return makeRuntimeRmt(pin, t1, t2, t3); + case LedColorOrder::GRB: + default: return makeRuntimeRmt(pin, t1, t2, t3); + } +} +#endif // LUME_RUNTIME_LED_HARDWARE + +// The default ILedOutput: FastLED's RMT driver (RFC 0001 §6). The strip type / +// pin / colour order come from the persisted config (LedHardware); the power +// limits from constants.h. This is the only place the render core touches the +// FastLED *driver* (as opposed to its math); swapping platforms means providing +// a different ILedOutput. class FastLedOutput : public ILedOutput { public: - void begin(CRGB* leds, uint16_t count) override { + void begin(CRGB* leds, uint16_t count, const LedHardware& hw) override { + LedHardware bound = hw; +#if LUME_RUNTIME_LED_HARDWARE + if (!isUsableLedPin(bound.pin)) { + // Persisted config is validated on every write path, so this only + // fires for NVS written by an older/foreign build. Never bind the + // flash or USB pins: fall back to the compile-time default. + LOG_ERROR(LogTag::LED, "LED data pin %u is not usable on this chip; using GPIO %d", + bound.pin, (int)LED_DATA_PIN); + bound.pin = static_cast(LED_DATA_PIN); + } + const LedChipsetInfo& chip = ledChipsetInfo(bound.chipset); + // C_NS(): ns -> CPU cycles, exactly what FastLED's own chipset classes + // hand the RMT controller (it converts back to RMT ticks internally). + CLEDController* ctrl = makeRuntimeRmt(bound.order, bound.pin, + C_NS(chip.t1Ns), C_NS(chip.t2Ns), C_NS(chip.t3Ns)); + if (chip.rgbw) { + // 4-byte pixels; white is derived from the RGB triplet by FastLED's + // default Rgbw mode (W = min(R,G,B), subtracted from the colour). + ctrl->setRgbw(RgbwDefault()); + } + FastLED.addLeds(ctrl, leds, count); + LOG_INFO(LogTag::LED, "LED output: %s, %s order, GPIO %u, %u px", + chip.name, ledColorOrderKey(bound.order), bound.pin, count); +#else + // Non-ESP32 (host tests; other MCUs): FastLED's driver here needs the + // pin and chipset at compile time, so the build-flag defaults apply. + (void)bound; FastLED.addLeds(leds, count); +#endif FastLED.setMaxPowerInVoltsAndMilliamps(LED_VOLTAGE, LED_MAX_MILLIAMPS); // The premium 16-bit render pipeline (render16.h, driven in // LumeController::update()) owns ALL signal shaping: gamma, WS2812B white- diff --git a/src/core/led_hardware.h b/src/core/led_hardware.h new file mode 100644 index 0000000..dd324ce --- /dev/null +++ b/src/core/led_hardware.h @@ -0,0 +1,196 @@ +#ifndef LUME_LED_HARDWARE_H +#define LUME_LED_HARDWARE_H + +#include +#include +#include "../constants.h" // LED_STRIP_TYPE / LED_COLOR_MODE / LED_DATA_PIN (compile-time defaults) + +// Runtime-selectable LED hardware: strip chipset, colour byte order and data +// pin. This header is pure data + parsing (no FastLED, no Arduino) so the +// catalog is host-testable; the FastLED backend (fastled_output.h) maps a +// LedHardware onto the driver at boot. +// +// The catalog mirrors FastLED's ESP32 clockless timings (chipsets.h, the +// `C_NS(...)` branch) in nanoseconds. On the ESP32 the RMT driver takes pin and +// bit timings as plain constructor arguments, so every chipset here is one row +// of data rather than one template instantiation — that is what makes the +// selection a runtime setting instead of a build flag. +namespace lume { + +enum class LedChipset : uint8_t { + WS2812B = 0, // also WS2812, WS2852, GS1903, APA104-800 (same timing) + WS2811, // 12 V "bullet"/string pixels, usually RGB order + WS2813, // WS2812B + backup data line + WS2815, // 12 V WS28xx, backup data line + SK6812, // RGB variant + SK6812_RGBW, // 4-channel: white derived from RGB (FastLED Rgbw default) + SK6822, // also APA106 + WS2811_400, // 400 kHz WS2811 + UCS1903, // 400 kHz + UCS1904, + SM16703, + TM1809, + PL9823, + COUNT +}; + +enum class LedColorOrder : uint8_t { + RGB = 0, RBG, GRB, GBR, BRG, BGR, + COUNT +}; + +struct LedChipsetInfo { + LedChipset id; + const char* key; // stable id used in JSON / NVS (never renumber-sensitive) + const char* name; // human label + uint16_t t1Ns; // bit timing, ns (FastLED T1/T2/T3 convention) + uint16_t t2Ns; + uint16_t t3Ns; + bool rgbw; // 4 bytes per pixel on the wire +}; + +// Order matters only for presentation (the UI lists them in this order). +// Timings copied from FastLED 3.9.4 chipsets.h (ESP32 / C_NS branch). +inline const LedChipsetInfo* ledChipsetCatalog(size_t& count) { + static const LedChipsetInfo kCatalog[] = { + { LedChipset::WS2812B, "WS2812B", "WS2812B / WS2812 (800 kHz)", 250, 625, 375, false }, + { LedChipset::WS2811, "WS2811", "WS2811 (800 kHz, 12 V)", 320, 320, 640, false }, + { LedChipset::WS2813, "WS2813", "WS2813", 320, 320, 640, false }, + { LedChipset::WS2815, "WS2815", "WS2815 (12 V)", 250, 1090, 550, false }, + { LedChipset::SK6812, "SK6812", "SK6812 (RGB)", 300, 300, 600, false }, + { LedChipset::SK6812_RGBW, "SK6812_RGBW", "SK6812 RGBW", 300, 300, 600, true }, + { LedChipset::SK6822, "SK6822", "SK6822 / APA106", 375, 1000, 375, false }, + { LedChipset::WS2811_400, "WS2811_400", "WS2811 (400 kHz)", 800, 800, 900, false }, + { LedChipset::UCS1903, "UCS1903", "UCS1903 (400 kHz)", 500, 1500, 500, false }, + { LedChipset::UCS1904, "UCS1904", "UCS1904", 400, 400, 450, false }, + { LedChipset::SM16703, "SM16703", "SM16703", 300, 600, 300, false }, + { LedChipset::TM1809, "TM1809", "TM1809", 350, 350, 450, false }, + { LedChipset::PL9823, "PL9823", "PL9823", 350, 1010, 350, false }, + }; + count = sizeof(kCatalog) / sizeof(kCatalog[0]); + return kCatalog; +} + +inline const LedChipsetInfo& ledChipsetInfo(LedChipset id) { + size_t n; + const LedChipsetInfo* cat = ledChipsetCatalog(n); + for (size_t i = 0; i < n; i++) { + if (cat[i].id == id) return cat[i]; + } + return cat[0]; // WS2812B — the catalog always has it first +} + +inline const char* ledChipsetKey(LedChipset id) { return ledChipsetInfo(id).key; } + +// Parse a JSON/NVS key ("WS2812B", "SK6812_RGBW", ...). Case-sensitive on +// purpose: these are ids, not user prose. Returns false and leaves `out` +// untouched on an unknown key. +inline bool parseLedChipset(const char* key, LedChipset& out) { + if (!key) return false; + size_t n; + const LedChipsetInfo* cat = ledChipsetCatalog(n); + for (size_t i = 0; i < n; i++) { + if (strcmp(cat[i].key, key) == 0) { out = cat[i].id; return true; } + } + return false; +} + +inline const char* ledColorOrderKey(LedColorOrder o) { + static const char* const kKeys[] = { "RGB", "RBG", "GRB", "GBR", "BRG", "BGR" }; + uint8_t i = static_cast(o); + return i < static_cast(LedColorOrder::COUNT) ? kKeys[i] : kKeys[2]; +} + +inline bool parseLedColorOrder(const char* key, LedColorOrder& out) { + if (!key) return false; + for (uint8_t i = 0; i < static_cast(LedColorOrder::COUNT); i++) { + LedColorOrder o = static_cast(i); + if (strcmp(ledColorOrderKey(o), key) == 0) { out = o; return true; } + } + return false; +} + +// ── Data-pin policy ───────────────────────────────────────────────────────── +// Which GPIOs may carry the LED data line. Excluded outright: pins that don't +// exist, input-only pins, the SPI flash / PSRAM bus (touching those crashes the +// chip) and the native USB pair (the console + upload path with +// ARDUINO_USB_CDC_ON_BOOT=1). Strapping pins are ALLOWED — they work fine once +// booted — but the UI flags them so a user with a stubborn boot loop knows why. +// Each target's rule is its own function so the host tests can pin them down. + +inline bool isUsableLedPinEsp32S3(int pin) { + if (pin < 0 || pin > 48) return false; + if (pin >= 22 && pin <= 25) return false; // not bonded out + if (pin >= 26 && pin <= 32) return false; // SPI flash + if (pin >= 33 && pin <= 37) return false; // octal PSRAM/flash (N8R8, T-Display S3) + if (pin == 19 || pin == 20) return false; // USB D- / D+ + return true; +} + +inline bool isUsableLedPinEsp32C3(int pin) { + if (pin < 0 || pin > 21) return false; + if (pin >= 11 && pin <= 17) return false; // SPI flash (11 = VDD_SPI) + if (pin == 18 || pin == 19) return false; // USB D- / D+ + return true; +} + +inline bool isUsableLedPinEsp32Classic(int pin) { + if (pin < 0 || pin > 33) return false; // 34-39 are input-only + if (pin >= 6 && pin <= 11) return false; // SPI flash + if (pin == 20 || pin == 24 || pin == 28 || pin == 29 || pin == 30 || pin == 31) return false; // absent + return true; +} + +inline bool isStrappingLedPinEsp32S3(int pin) { return pin == 0 || pin == 3 || pin == 45 || pin == 46; } +inline bool isStrappingLedPinEsp32C3(int pin) { return pin == 2 || pin == 8 || pin == 9; } +inline bool isStrappingLedPinEsp32Classic(int pin) { return pin == 0 || pin == 2 || pin == 5 || pin == 12 || pin == 15; } + +inline bool isUsableLedPin(int pin) { +#if defined(CONFIG_IDF_TARGET_ESP32S3) + return isUsableLedPinEsp32S3(pin); +#elif defined(CONFIG_IDF_TARGET_ESP32C3) + return isUsableLedPinEsp32C3(pin); +#elif defined(CONFIG_IDF_TARGET_ESP32) + return isUsableLedPinEsp32Classic(pin); +#else + return isUsableLedPinEsp32S3(pin); // host tests / unknown: the widest table +#endif +} + +inline bool isStrappingLedPin(int pin) { +#if defined(CONFIG_IDF_TARGET_ESP32S3) + return isStrappingLedPinEsp32S3(pin); +#elif defined(CONFIG_IDF_TARGET_ESP32C3) + return isStrappingLedPinEsp32C3(pin); +#elif defined(CONFIG_IDF_TARGET_ESP32) + return isStrappingLedPinEsp32Classic(pin); +#else + return isStrappingLedPinEsp32S3(pin); +#endif +} + +// The selection the output driver is bound to at boot. +struct LedHardware { + LedChipset chipset; + LedColorOrder order; + uint8_t pin; + + // Compile-time defaults (constants.h / build_flags): what a factory-fresh + // board runs, and what an invalid persisted value falls back to. + static LedHardware defaults() { + LedHardware hw; + hw.chipset = LedChipset::LED_STRIP_TYPE; + hw.order = LedColorOrder::LED_COLOR_MODE; + hw.pin = static_cast(LED_DATA_PIN); + return hw; + } + + bool operator==(const LedHardware& o) const { + return chipset == o.chipset && order == o.order && pin == o.pin; + } + bool operator!=(const LedHardware& o) const { return !(*this == o); } +}; + +} // namespace lume + +#endif // LUME_LED_HARDWARE_H diff --git a/src/core/led_output.h b/src/core/led_output.h index 6fcedf0..75c8510 100644 --- a/src/core/led_output.h +++ b/src/core/led_output.h @@ -2,6 +2,7 @@ #define LUME_LED_OUTPUT_H #include // CRGB +#include "led_hardware.h" namespace lume { @@ -18,8 +19,10 @@ class ILedOutput { public: virtual ~ILedOutput() = default; - // Bind the controller-owned pixel buffer + length (once, at startup). - virtual void begin(CRGB* leds, uint16_t count) = 0; + // Bind the controller-owned pixel buffer + length to the selected hardware + // (chipset / colour order / data pin) — once, at startup. Changing the + // hardware later means a reboot: drivers bind pins and peripherals here. + virtual void begin(CRGB* leds, uint16_t count, const LedHardware& hw) = 0; // Push the current buffer contents to the physical strip. virtual void show() = 0; diff --git a/src/main.cpp b/src/main.cpp index ac8a7c0..eaac93f 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -10,10 +10,13 @@ * * Hardware: * - LILYGO T-Display S3 - * - WS2812B LED strip (default 160 LEDs on GPIO 2, see LED_DATA_PIN) + * - Addressable LED strip. Chipset / colour order / data pin are runtime + * settings (web UI → Device, or POST /api/config), applied at boot; the + * factory defaults are WS2812B, GRB, GPIO 2 (constants.h). */ #include +#include #include #include #include @@ -87,6 +90,12 @@ void endBody(AsyncWebServerRequest* request) { g_bodyGuard.end(request); } +static std::atomic g_restartRequested{false}; + +void requestRestart() { + g_restartRequested.store(true); +} + bool checkAuth(AsyncWebServerRequest* request) { // If no auth token configured, allow all requests if (config.authToken.length() == 0) { @@ -176,14 +185,15 @@ void setup() { String devModel = DEV_AI_MODEL; if (devModel.length() > 0) config.aiModel = devModel; normalizeAiModel(config.aiModel); // a secrets.h copied from an older example may hold a retired id - // Note: LED pin is configured in constants.h (LED_DATA_PIN) + // Note: strip type / colour order / data pin are runtime settings (NVS via + // the web UI); secrets.h only overrides the count and brightness. config.ledCount = DEV_LED_COUNT; config.defaultBrightness = DEV_DEFAULT_BRIGHTNESS; #endif // Initialize v2 LED controller LOG_INFO(LogTag::LED, "Initializing LED controller..."); - lume::controller.begin(config.ledCount); + lume::controller.begin(config.ledCount, config.ledHardware); lume::controller.setBrightness(config.defaultBrightness); lume::controller.setGamma(config.gamma); // seed runtime gamma from persisted config lume::controller.setWarmth(config.warmth); // seed dim-to-warm from persisted config @@ -284,6 +294,19 @@ void loop() { LOG_DEBUG(LogTag::STORAGE, "Segment layout persisted"); } + // Deferred reboot (POST /api/restart): boot-time settings such as the LED + // hardware and ledCount apply on the way back up. Persist the segment + // layout first, unconditionally — the debounced save above may not be due + // yet for a change made seconds ago, and it would otherwise be lost. + if (g_restartRequested.load()) { + JsonDocument stateDoc; + lume::controller.serializeSegments(stateDoc); + storage.saveLedState(stateDoc); + LOG_INFO(LogTag::MAIN, "Restart requested via API; rebooting"); + delay(250); // let the 202 leave the socket + ESP.restart(); + } + // Reset watchdog - proves loop is still running esp_task_wdt_reset(); diff --git a/src/main.h b/src/main.h index 2fb5121..db873e3 100644 --- a/src/main.h +++ b/src/main.h @@ -42,6 +42,11 @@ void sendUnauthorized(AsyncWebServerRequest* request); bool beginBody(AsyncWebServerRequest* request); void endBody(AsyncWebServerRequest* request); +// Deferred reboot: set from a web handler (POST /api/restart), honoured by the +// loop task at the end of its next pass — after the response has gone out and +// with no render/protocol code mid-frame. +void requestRestart(); + // =========================================================================== // API Handler Functions - Main Routes // =========================================================================== diff --git a/src/network/server.cpp b/src/network/server.cpp index 67bc927..e58c7e6 100644 --- a/src/network/server.cpp +++ b/src/network/server.cpp @@ -188,6 +188,8 @@ void setupServer() { NULL, handleApiConfigPost ); + // Reboot so boot-time settings (LED hardware, ledCount) take effect. + server.on("/api/restart", HTTP_POST, handleApiRestart); // Direct pixel control endpoint server.on("/api/pixels", HTTP_POST, diff --git a/src/secrets.h.example b/src/secrets.h.example index ae33b1d..d8c5201 100644 --- a/src/secrets.h.example +++ b/src/secrets.h.example @@ -22,7 +22,8 @@ #define DEV_AI_MODEL "claude-haiku-4-5" // AI model to use // LED configuration (optional overrides) -// Note: LED data pin is configured in constants.h (LED_DATA_PIN) +// Note: strip type, colour order and data pin are runtime settings (web UI -> +// Device / POST /api/config, persisted in NVS); constants.h holds the defaults. #define DEV_LED_COUNT 160 // Number of LEDs in strip #define DEV_DEFAULT_BRIGHTNESS 128 // Default brightness (0-255) diff --git a/src/storage.cpp b/src/storage.cpp index cc45f7a..05bd82f 100644 --- a/src/storage.cpp +++ b/src/storage.cpp @@ -1,5 +1,6 @@ #include "storage.h" #include "constants.h" // MAX_LED_COUNT (ledCount clamp, P0.2) +#include "logging.h" const char* Storage::NAMESPACE_CONFIG = "config"; const char* Storage::NAMESPACE_LED = "ledstate"; @@ -55,6 +56,29 @@ bool Storage::loadConfig(Config& config) { config.authToken = prefs.getString("authtoken", ""); // Clamp on load too, in case NVS holds an out-of-range value (P0.2). config.ledCount = constrain((int)prefs.getUShort("ledcount", 160), 1, (int)MAX_LED_COUNT); + // LED hardware: stored as the catalog KEYS (not enum ordinals) so a future + // reorder of the catalog can't silently retarget a strip. Unknown/invalid + // values fall back to the compile-time defaults field-by-field. + { + lume::LedHardware hw = lume::LedHardware::defaults(); + String type = prefs.getString("ledtype", ""); + if (type.length() > 0 && !lume::parseLedChipset(type.c_str(), hw.chipset)) { + LOG_WARN(LogTag::STORAGE, "Unknown LED type '%s' in NVS; using %s", + type.c_str(), lume::ledChipsetKey(hw.chipset)); + } + String order = prefs.getString("ledorder", ""); + if (order.length() > 0 && !lume::parseLedColorOrder(order.c_str(), hw.order)) { + LOG_WARN(LogTag::STORAGE, "Unknown LED colour order '%s' in NVS; using %s", + order.c_str(), lume::ledColorOrderKey(hw.order)); + } + int pin = prefs.getUChar("ledpin", hw.pin); + if (lume::isUsableLedPin(pin)) { + hw.pin = (uint8_t)pin; + } else { + LOG_WARN(LogTag::STORAGE, "LED pin %d in NVS not usable on this chip; using GPIO %u", pin, hw.pin); + } + config.ledHardware = hw; + } config.defaultBrightness = prefs.getUChar("brightness", 128); // Clamp on load too, in case NVS holds an out-of-range value. config.gamma = constrain(prefs.getFloat("gamma", LED_GAMMA), LED_GAMMA_MIN, LED_GAMMA_MAX); @@ -89,6 +113,9 @@ bool Storage::saveConfig(const Config& config) { prefs.putString("ai_model", config.aiModel); prefs.putString("authtoken", config.authToken); prefs.putUShort("ledcount", config.ledCount); + prefs.putString("ledtype", lume::ledChipsetKey(config.ledHardware.chipset)); + prefs.putString("ledorder", lume::ledColorOrderKey(config.ledHardware.order)); + prefs.putUChar("ledpin", config.ledHardware.pin); prefs.putUChar("brightness", config.defaultBrightness); prefs.putFloat("gamma", config.gamma); prefs.putFloat("warmth", config.warmth); @@ -184,6 +211,9 @@ void Storage::configToJson(const Config& config, JsonDocument& doc, bool maskApi doc["authToken"] = config.authToken.length() > 0 ? "****" : ""; doc["authEnabled"] = config.authToken.length() > 0; doc["ledCount"] = config.ledCount; + doc["ledType"] = lume::ledChipsetKey(config.ledHardware.chipset); + doc["ledColorOrder"] = lume::ledColorOrderKey(config.ledHardware.order); + doc["ledPin"] = config.ledHardware.pin; doc["defaultBrightness"] = config.defaultBrightness; doc["gamma"] = config.gamma; doc["warmth"] = config.warmth; @@ -202,7 +232,33 @@ void Storage::configToJson(const Config& config, JsonDocument& doc, bool maskApi doc["mqttTopicPrefix"] = config.mqttTopicPrefix; } -bool Storage::configFromJson(Config& config, const JsonDocument& doc) { +bool Storage::configFromJson(Config& config, const JsonDocument& doc, String* error) { + // LED hardware is validated up front, before ANY field is applied: a bad + // strip type must not leave half a request applied in RAM with nothing + // persisted. The pin is checked against this chip's usable-pin policy + // (never the flash/USB pins). All three apply on the next reboot. + lume::LedHardware hw = config.ledHardware; + if (!doc["ledType"].isNull()) { + if (!doc["ledType"].is() || !lume::parseLedChipset(doc["ledType"].as(), hw.chipset)) { + if (error) *error = "ledType: unknown strip type"; + return false; + } + } + if (!doc["ledColorOrder"].isNull()) { + if (!doc["ledColorOrder"].is() || !lume::parseLedColorOrder(doc["ledColorOrder"].as(), hw.order)) { + if (error) *error = "ledColorOrder: expected one of RGB RBG GRB GBR BRG BGR"; + return false; + } + } + if (!doc["ledPin"].isNull()) { + if (!doc["ledPin"].is() || !lume::isUsableLedPin(doc["ledPin"].as())) { + if (error) *error = "ledPin: not a usable LED data pin on this chip"; + return false; + } + hw.pin = (uint8_t)doc["ledPin"].as(); + } + config.ledHardware = hw; + // Only update fields that are present // "wifiSSID" is the one canonical key, and the spelling is load-bearing: // ArduinoJson is case-sensitive, and a UI sending anything else (PR #29 diff --git a/src/storage.h b/src/storage.h index bd02e6f..efa9a31 100644 --- a/src/storage.h +++ b/src/storage.h @@ -7,6 +7,7 @@ #include #include #include "constants.h" // LED_GAMMA (seed for the persisted gamma default) +#include "core/led_hardware.h" // LedHardware (runtime strip type / order / pin) // RAII guard for Storage's NVS access. The single Preferences object is shared // across tasks (saveLastEffect from the web/AI task vs saveLedState from the @@ -32,6 +33,7 @@ struct Config { String aiModel; // AI model selection String authToken; // Optional API auth token (empty = no auth) uint16_t ledCount; + lume::LedHardware ledHardware; // strip chipset / colour order / data pin (applied at boot) uint8_t defaultBrightness; float gamma; // Perceptual-dimming exponent (see LED_GAMMA) float warmth; // Dim-to-warm strength [0..1] (see LED_WARMTH_*) @@ -57,6 +59,7 @@ struct Config { aiModel(AI_MODEL_DEFAULT), authToken(""), ledCount(160), + ledHardware(lume::LedHardware::defaults()), defaultBrightness(128), gamma(LED_GAMMA), warmth(LED_WARMTH_DEFAULT), @@ -100,8 +103,10 @@ class Storage { // Export config to JSON (with optional API key masking) void configToJson(const Config& config, JsonDocument& doc, bool maskApiKey = true); - // Import config from JSON - bool configFromJson(Config& config, const JsonDocument& doc); + // Import config from JSON. Validates the LED hardware fields (ledType / + // ledColorOrder / ledPin) BEFORE touching `config`: returns false, with the + // offending field named in `error`, and leaves the config untouched. + bool configFromJson(Config& config, const JsonDocument& doc, String* error = nullptr); private: Preferences prefs; diff --git a/test/test_command_bus/test_command_bus.cpp b/test/test_command_bus/test_command_bus.cpp index a500320..13c1b9c 100644 --- a/test/test_command_bus/test_command_bus.cpp +++ b/test/test_command_bus/test_command_bus.cpp @@ -608,7 +608,7 @@ struct MockOutput : ILedOutput { uint8_t lastBrightness = 0; CRGB lastCorrection = CRGB(255, 255, 255); CRGB lastTemperature = CRGB(255, 255, 255); - void begin(CRGB*, uint16_t) override { begins++; } + void begin(CRGB*, uint16_t, const LedHardware&) override { begins++; } void show() override { shows++; } void setBrightness(uint8_t b) override { lastBrightness = b; } void setCorrection(CRGB c) override { lastCorrection = c; } diff --git a/test/test_led_hardware/test_led_hardware.cpp b/test/test_led_hardware/test_led_hardware.cpp new file mode 100644 index 0000000..6b91b56 --- /dev/null +++ b/test/test_led_hardware/test_led_hardware.cpp @@ -0,0 +1,144 @@ +// Native (host-compiled) tests for the runtime LED hardware catalog +// (core/led_hardware.h): the strip chipset / colour order / data pin selection +// that the web UI and POST /api/config write, NVS persists, and the FastLED +// backend binds at boot. Pure data + parsing, so it runs without FastLED. +#include + +#include "core/led_hardware.h" + +using namespace lume; + +void setUp() {} +void tearDown() {} + +// Every catalog entry round-trips through its key: what the API emits is +// exactly what it accepts back, and what NVS stores survives a reload. +void test_chipset_keys_round_trip() { + size_t n; + const LedChipsetInfo* cat = ledChipsetCatalog(n); + TEST_ASSERT_EQUAL_size_t((size_t)LedChipset::COUNT, n); + for (size_t i = 0; i < n; i++) { + LedChipset parsed = LedChipset::COUNT; + TEST_ASSERT_TRUE_MESSAGE(parseLedChipset(cat[i].key, parsed), cat[i].key); + TEST_ASSERT_EQUAL_UINT8((uint8_t)cat[i].id, (uint8_t)parsed); + TEST_ASSERT_EQUAL_STRING(cat[i].key, ledChipsetKey(cat[i].id)); + // Every enumerator appears exactly once, in enum order. + TEST_ASSERT_EQUAL_UINT8((uint8_t)i, (uint8_t)cat[i].id); + } +} + +// Timings are what feed the RMT driver: none may be zero, and the well-known +// ones must match FastLED's chipsets.h (WS2812B 250/625/375, SK6812 300/300/600). +void test_chipset_timings_are_sane_and_match_fastled() { + size_t n; + const LedChipsetInfo* cat = ledChipsetCatalog(n); + for (size_t i = 0; i < n; i++) { + TEST_ASSERT_TRUE_MESSAGE(cat[i].t1Ns > 0 && cat[i].t2Ns > 0 && cat[i].t3Ns > 0, cat[i].key); + } + const LedChipsetInfo& ws = ledChipsetInfo(LedChipset::WS2812B); + TEST_ASSERT_EQUAL_UINT16(250, ws.t1Ns); + TEST_ASSERT_EQUAL_UINT16(625, ws.t2Ns); + TEST_ASSERT_EQUAL_UINT16(375, ws.t3Ns); + TEST_ASSERT_FALSE(ws.rgbw); + const LedChipsetInfo& sk = ledChipsetInfo(LedChipset::SK6812_RGBW); + TEST_ASSERT_EQUAL_UINT16(300, sk.t1Ns); + TEST_ASSERT_EQUAL_UINT16(300, sk.t2Ns); + TEST_ASSERT_EQUAL_UINT16(600, sk.t3Ns); + TEST_ASSERT_TRUE(sk.rgbw); + // The RGB SK6812 shares timing with the RGBW part; only the wire width differs. + TEST_ASSERT_FALSE(ledChipsetInfo(LedChipset::SK6812).rgbw); +} + +// Unknown / empty / case-mismatched keys are rejected and leave the output alone +// (the caller keeps its current value or default — never a garbage enum). +void test_chipset_parse_rejects_unknown() { + LedChipset c = LedChipset::WS2811; + TEST_ASSERT_FALSE(parseLedChipset("WS9999", c)); + TEST_ASSERT_FALSE(parseLedChipset("", c)); + TEST_ASSERT_FALSE(parseLedChipset(nullptr, c)); + TEST_ASSERT_FALSE(parseLedChipset("ws2812b", c)); // ids, not prose + TEST_ASSERT_EQUAL_UINT8((uint8_t)LedChipset::WS2811, (uint8_t)c); + // An out-of-range enum value resolves to the catalog's first row (WS2812B) + // rather than reading past the table. + TEST_ASSERT_EQUAL_STRING("WS2812B", ledChipsetKey(LedChipset::COUNT)); +} + +void test_color_order_keys_round_trip() { + const char* keys[] = { "RGB", "RBG", "GRB", "GBR", "BRG", "BGR" }; + for (uint8_t i = 0; i < 6; i++) { + LedColorOrder o = LedColorOrder::COUNT; + TEST_ASSERT_TRUE(parseLedColorOrder(keys[i], o)); + TEST_ASSERT_EQUAL_UINT8(i, (uint8_t)o); + TEST_ASSERT_EQUAL_STRING(keys[i], ledColorOrderKey(o)); + } + LedColorOrder o = LedColorOrder::BRG; + TEST_ASSERT_FALSE(parseLedColorOrder("RGBW", o)); + TEST_ASSERT_FALSE(parseLedColorOrder("grb", o)); + TEST_ASSERT_FALSE(parseLedColorOrder(nullptr, o)); + TEST_ASSERT_EQUAL_UINT8((uint8_t)LedColorOrder::BRG, (uint8_t)o); + TEST_ASSERT_EQUAL_STRING("GRB", ledColorOrderKey(LedColorOrder::COUNT)); // out of range -> GRB +} + +// The compile-time defaults (constants.h, unless a build flag overrides them) +// seed a fresh board and every invalid-value fallback. +void test_defaults_come_from_constants() { + LedHardware hw = LedHardware::defaults(); + TEST_ASSERT_EQUAL_UINT8((uint8_t)LedChipset::LED_STRIP_TYPE, (uint8_t)hw.chipset); + TEST_ASSERT_EQUAL_UINT8((uint8_t)LedColorOrder::LED_COLOR_MODE, (uint8_t)hw.order); + TEST_ASSERT_EQUAL_UINT8((uint8_t)LED_DATA_PIN, hw.pin); + LedHardware other = hw; + TEST_ASSERT_TRUE(hw == other); + other.pin = (uint8_t)(hw.pin + 1); + TEST_ASSERT_TRUE(hw != other); +} + +// ESP32-S3: flash (26-32), octal PSRAM (33-37), USB (19-20) and the unbonded +// 22-25 are refused; ordinary GPIOs — strapping ones included — are allowed. +void test_pin_policy_esp32_s3() { + const int refused[] = { -1, 19, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 49, 100 }; + for (int p : refused) TEST_ASSERT_FALSE_MESSAGE(isUsableLedPinEsp32S3(p), "S3 refused pin accepted"); + const int allowed[] = { 0, 1, 2, 3, 4, 5, 8, 12, 16, 18, 21, 38, 45, 46, 47, 48 }; + for (int p : allowed) TEST_ASSERT_TRUE_MESSAGE(isUsableLedPinEsp32S3(p), "S3 usable pin refused"); + TEST_ASSERT_TRUE(isStrappingLedPinEsp32S3(0)); + TEST_ASSERT_TRUE(isStrappingLedPinEsp32S3(45)); + TEST_ASSERT_FALSE(isStrappingLedPinEsp32S3(2)); +} + +// ESP32-C3: only GPIO 0-21 exist; 11-17 are the flash bus, 18-19 the USB pair. +void test_pin_policy_esp32_c3() { + const int refused[] = { -1, 11, 12, 13, 14, 15, 16, 17, 18, 19, 22, 48 }; + for (int p : refused) TEST_ASSERT_FALSE_MESSAGE(isUsableLedPinEsp32C3(p), "C3 refused pin accepted"); + const int allowed[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 21 }; + for (int p : allowed) TEST_ASSERT_TRUE_MESSAGE(isUsableLedPinEsp32C3(p), "C3 usable pin refused"); + TEST_ASSERT_TRUE(isStrappingLedPinEsp32C3(8)); + TEST_ASSERT_TRUE(isStrappingLedPinEsp32C3(9)); + TEST_ASSERT_FALSE(isStrappingLedPinEsp32C3(4)); +} + +// Classic ESP32: 6-11 flash, 34-39 input-only, and the never-bonded numbers. +void test_pin_policy_esp32_classic() { + const int refused[] = { -1, 6, 7, 8, 9, 10, 11, 20, 24, 28, 34, 35, 36, 39 }; + for (int p : refused) TEST_ASSERT_FALSE_MESSAGE(isUsableLedPinEsp32Classic(p), "ESP32 refused pin accepted"); + const int allowed[] = { 0, 2, 4, 5, 12, 13, 16, 17, 18, 21, 22, 23, 25, 26, 27, 32, 33 }; + for (int p : allowed) TEST_ASSERT_TRUE_MESSAGE(isUsableLedPinEsp32Classic(p), "ESP32 usable pin refused"); +} + +// The compile-time default pin must pass the policy it is validated against — +// otherwise a fresh board would "fall back" from its own default. +void test_default_pin_is_usable() { + TEST_ASSERT_TRUE(isUsableLedPin(LED_DATA_PIN)); +} + +int main(int, char**) { + UNITY_BEGIN(); + RUN_TEST(test_chipset_keys_round_trip); + RUN_TEST(test_chipset_timings_are_sane_and_match_fastled); + RUN_TEST(test_chipset_parse_rejects_unknown); + RUN_TEST(test_color_order_keys_round_trip); + RUN_TEST(test_defaults_come_from_constants); + RUN_TEST(test_pin_policy_esp32_s3); + RUN_TEST(test_pin_policy_esp32_c3); + RUN_TEST(test_pin_policy_esp32_classic); + RUN_TEST(test_default_pin_is_usable); + return UNITY_END(); +}