Skip to content

feat(led): runtime-selectable strip type, colour order and data pin - #49

Open
bring42 wants to merge 1 commit into
mainfrom
claude/strip-type-min-runtime-selectable-30aaff
Open

bring42 wants to merge 1 commit into
mainfrom
claude/strip-type-min-runtime-selectable-30aaff

Conversation

@bring42

@bring42 bring42 commented Sep 12, 2026

Copy link
Copy Markdown
Owner

Summary

Strip chipset, colour byte order and data pin were compile-time template arguments to FastLED.addLeds<>(), so any wiring change meant a reflash. They are now device settings — persisted in NVS, editable from the web UI (Settings → 02 · Device) or POST /api/config, and bound at boot like ledCount — the way WLED does it.

How (no template explosion)

On the ESP32, FastLED's RmtController (idf4_rmt.h) takes the pin and the three bit timings as plain constructor arguments; the addLeds<CHIPSET, PIN, ORDER> template parameters only ever fed it those numbers. So:

  • src/core/led_hardware.h — pure catalog: FastLED's chipsets.h timings in ns per chipset, colour-order ids, and a per-chip usable-pin policy. No FastLED/Arduino dependency → host-testable.
  • src/core/fastled_output.h — one small CPixelLEDController<ORDER> per colour order (six) wrapping an RmtController built from the persisted LedHardware. Same RMT backend, same FASTLED_ESP32_FLASH_LOCK behaviour. Non-ESP32 / RMT5 builds fall back to the compile-time defaults path.

What's selectable

  • 13 chipsets: WS2812B (also WS2812/WS2852/GS1903), WS2811, WS2813, WS2815, SK6812, SK6812 RGBW (4-byte pixels, white derived by FastLED's default Rgbw mode — untested on hardware, flagged in docs), SK6822/APA106, WS2811 400 kHz, UCS1903, UCS1904, SM16703, TM1809, PL9823.
  • Colour order: RGB / RBG / GRB / GBR / BRG / BGR.
  • Data pin: per-target policy (S3 / C3 / classic ESP32). Flash & PSRAM bus, native USB pair and unbonded numbers are refused (400 before any field is applied; fallback to build defaults on NVS load). Strapping pins are offered but flagged.

API

  • GET /api/config → ledType, ledColorOrder, ledPin, plus ledOptions (per-chip lists: types, colorOrders, pins, strappingPins) and ledActive (what the running firmware is bound to).
  • POST /api/config accepts the three fields; invalid values → 400 {"error":"ledPin: not a usable LED data pin on this chip"} with nothing applied.
  • New POST /api/restart (auth-gated): 202, then reboots from the loop task after flushing the segment layout — so boot-time settings apply without a power cycle.
  • /api/v2/info controller reports the bound hardware.

Web UI

Strip Type / Color Order / Data Pin selects populated from the device (never hardcoded), an amber "Restart to apply: strip type, data pin…" notice whenever persisted ≠ active (now covers ledCount too), and a Restart device button.

Compile-time knobs

LED_STRIP_TYPE / LED_COLOR_MODE / LED_DATA_PIN (and -DLUME_LED_DATA_PIN) now set only the factory default. Existing build_flags overrides keep working (the names are the enum's).

Test plan

  • pio test -e native: 91/91 pass, incl. new test_led_hardware (catalog key round-trips, FastLED timing parity, chipset parse rejection, S3/C3/classic pin policies, default pin is usable).
  • pio run -e esp32-s3-devkitc-1 and -e esp32-c3-devkitm-1 build clean, no new warnings.
  • Web UI checked in the in-app browser (demo mode): selects populate, pending-restart notice + toast on change, light-theme chevron.
  • Hardware: flash an S3/C3, confirm boot log LED output: WS2812B, GRB order, GPIO 2, N px, change pin/order in the UI → Restart → strip follows. SK6812 RGBW is untested on real hardware.

🤖 Generated with Claude Code

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 <noreply@anthropic.com>
Copilot AI lite review requested due to automatic review settings September 12, 2026 19:10

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved moderate and critical findings remain in runtime binding, fallback compilation, persistence, restart handling, and UI state management.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

Adds persisted runtime selection of LED chipset, color order, and data pin through the API and web UI, with deferred restart support.

Changes:

  • Adds hardware catalog, validation, persistence, and runtime FastLED binding.
  • Adds active hardware reporting and POST /api/restart.
  • Updates UI, documentation, and native tests.
File summaries
File Reviewed changes and final findings
test/test_led_hardware/test_led_hardware.cpp Catalog and pin-policy tests. Nit (1 vote, L120): cover GPIO 37 and 38. Nit (1 vote, L30): add timing and RGBW assertions for every catalog entry.
test/test_command_bus/test_command_bus.cpp Updates output mock interface. No final findings.
src/storage.h Adds persisted hardware configuration. No final findings.
src/storage.cpp Loads, saves, serializes, and validates settings. Moderate (1 vote each, L241/L247/L253): explicitly provided null values bypass validation; use member-presence checks for ledType, ledColorOrder, and ledPin.
src/secrets.h.example Documents runtime LED settings. No final findings.
src/network/server.cpp Registers the restart route. No final findings.
src/main.h Declares deferred restart. No final findings.
src/main.cpp Binds hardware and performs deferred reboot. Moderate (1 vote, L301): abort or report restart when saveLedState fails.
src/core/README.md Documents runtime output architecture. No final findings.
src/core/led_output.h Extends the output binding interface. No final findings.
src/core/led_hardware.h Adds chipset, color-order, and pin catalogs. Moderate (1 vote, L137): exclude or distinguish GPIO 16/17 for ESP32-WROVER PSRAM use.
src/core/fastled_output.h Implements runtime RMT binding. Moderate (3 votes, L97): RMT5 reports persisted settings as active while using compile-time defaults. Critical (1 vote, L100): the non-runtime fallback cannot compile the advertised SK6812_RGBW type.
src/core/controller.h Adds hardware-aware initialization. No final findings.
src/core/controller.cpp Stores and passes bound hardware. No final findings.
src/constants.h Reframes compile-time values as defaults. No final findings.
src/api/segments.cpp Reports active hardware. No final findings.
src/api/config.h Declares restart handling. No final findings.
src/api/config.cpp Adds options, validation, and restart handling. No final findings.
platformio.ini Includes the native test suite. No final findings.
docs/HARDWARE.md Documents runtime hardware configuration. No final findings.
docs/API_V2.md Documents new API fields and endpoint. No final findings.
data/index.html Adds hardware controls. Moderate (1 vote, L269): regenerate and commit updated asset cache-busting stamps.
data/assets/engine.js Adds restart API and demo state. Nit (1 vote, L976): document restart and deferred LED-setting semantics in docs/ENGINE_API.md.
data/assets/app.js Implements hardware settings UI. Moderate (1 vote each, L1162/L1213/L1149/L1174): rejected selects are not reset while focused; failed saves leave LED-count state optimistic; restart can race an in-flight save; and the single post-reboot refresh can leave stale active state.
data/assets/app.css Styles selectors and restart notice. No final findings.
Review details

Suppressed comments (13)

data/assets/app.js:1162

  • The rejection path refreshes state but renderLedHardware() intentionally refuses to assign a focused select. The select normally remains focused after its change event, so a rejected value stays displayed despite the "snap the select back" comment. Blur/reset this field explicitly on failure or provide a forced render.
      engine.getConfig().then(renderSettingsFromState);   // snap the select back

data/assets/app.js:1214

  • saveConfig() updates both local LED-count values before the POST completes; if the request fails, this handler only re-renders them, so the input and restart notice continue to show an unsaved count. Refresh/revert the local count on the !res.ok path before rendering.
    showToast(res.ok ? "LED count saved — restart to apply" : "Failed to save LED count");
    renderSettingsFromState();   // refresh the "restart to apply" notice

data/assets/app.js:1149

  • This button can become enabled from optimistic state before persistence completes: engine.saveConfig({ledCount}) notifies immediately, while its /api/config POST is still in flight. A quick click can let /api/restart reboot the loop before that write is handled, losing the requested count; track pending saves and disable restart until the save promise resolves.
  strip.classList.toggle("show", pending.length > 0);

data/assets/app.js:1176

  • The device is expected to be unreachable during reboot, so a single GET exactly 8 seconds later is not reliable. engine.getConfig() swallows failures, and the status/WebSocket paths do not refresh state.config; if this request races boot or Wi-Fi reconnection, ledActive stays stale and the pending banner never clears. Retry until the config fetch succeeds or refresh it on reconnect.
    // The status poll re-syncs when the device is back; refresh the pending
    // notice then (ledActive catches up to the persisted values).
    if (res.ok) setTimeout(() => engine.getConfig().then(renderSettingsFromState), 8000);

data/assets/engine.js:976

  • restart is a new exported engine method, but docs/ENGINE_API.md is the public method contract and does not list it or the deferred LED-hardware/LED-count semantics. Add the method and its reboot behavior there so consumers can discover the required save-then-restart flow.
      restart: restart,

data/index.html:271

  • These UI changes modify engine.js, app.js, and app.css, but the ?v= stamps in index.html remain unchanged. Because /assets/ is long-cacheable and this repository requires committed stamps, existing browsers/devices can continue loading the previous UI after this PR. Run scripts/gzip_web_files.py and commit the regenerated index.html stamps.
        <!-- Strip hardware: chipset / colour order / data pin. Options come from
             GET /api/config (ledOptions) so the list always matches this
             firmware + chip. All three (and LED Count) bind at boot. -->

src/core/led_hardware.h:141

  • The generic classic-ESP32 policy marks GPIO16 and GPIO17 as usable, but ESP32-WROVER modules use those pins for external PSRAM. That contradicts the stated promise to refuse flash/PSRAM bus pins and can break the heap on a WROVER; distinguish PSRAM-capable classic targets or exclude 16/17 from this generic policy.
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;

src/main.cpp:304

  • saveLedState is fallible (it returns false if NVS cannot be opened or the serialized layout exceeds its 4000-byte limit), but the restart proceeds unconditionally. If this save fails, rebooting here loses the latest segment layout, despite the endpoint's contract/comment that it flushes layout before restart. Handle the failure before calling ESP.restart (or surface/abort the restart).
    if (g_restartRequested.load()) {
        JsonDocument stateDoc;
        lume::controller.serializeSegments(stateDoc);
        storage.saveLedState(stateDoc);

src/storage.cpp:241

  • isNull() is true for both an absent member and an explicit JSON null, so {"ledType":null} skips the type check and the rest of the request can still be applied. The API contract says invalid LED values must return 400 with no fields applied; gate on member presence (doc.containsKey("ledType")) so null reaches the existing validation.
    if (!doc["ledType"].isNull()) {

src/storage.cpp:247

  • The same omission/null conflation occurs here: an explicit {"ledColorOrder":null} is accepted as if the field were omitted, allowing other fields in the request to be applied instead of returning the promised 400. Test member presence rather than isNull() before validating the value.
    if (!doc["ledColorOrder"].isNull()) {

src/storage.cpp:253

  • An explicit {"ledPin":null} also bypasses validation because isNull() cannot distinguish it from an omitted key. That violates the documented invalid-value/atomicity contract; use a presence check so null is rejected by the existing type check.
    if (!doc["ledPin"].isNull()) {

test/test_led_hardware/test_led_hardware.cpp:120

  • The classic ESP32 policy rejects every GPIO 34–39, but this regression test omits GPIO 37 and 38 from the refused cases. A future change could accidentally allow either input-only pin without this suite catching it; include all six pins (34, 35, 36, 37, 38, 39) here.
    const int refused[] = { -1, 6, 7, 8, 9, 10, 11, 20, 24, 28, 34, 35, 36, 39 };

test/test_led_hardware/test_led_hardware.cpp:36

  • This only verifies FastLED timing parity for WS2812B and SK6812; the other 11 manually copied timing rows can be wrong while all tests pass. Add table-driven expected T1/T2/T3 (and rgbw) assertions for every catalog entry, since these values directly determine the runtime wire protocol.
// 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);
  • Files reviewed: 25/25 changed files
  • Comments generated: 2
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/core/fastled_output.h
// 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<LED_STRIP_TYPE, LED_DATA_PIN, LED_COLOR_MODE>(leds, count);
Comment thread src/core/fastled_output.h
Comment on lines +97 to 100
// 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<LED_STRIP_TYPE, LED_DATA_PIN, LED_COLOR_MODE>(leds, count);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants