Skip to content

feat(examples): HydroPack dual EL-panel beat visualizer + ESP32 PWM duty fix + lint/test debt cleanup - #3683

Merged
zackees merged 10 commits into
masterfrom
feat/hydropack-example
Jul 16, 2026
Merged

zackees merged 10 commits into
masterfrom
feat/hydropack-example

Conversation

@zackees

@zackees zackees commented Jul 16, 2026 •

Copy link
Copy Markdown
Member

Fixes #3681

What

1. New example: examples/hydropack/hydropack.ino

HydroPack — a dual EL-panel beat visualizer targeting the ESP32-C3, also a valid FastLED WASM sketch:

  • Audio in: INMP441 I2S MEMS mic (WS=GPIO7, SD=GPIO8, SCK=GPIO4 — same wiring as examples/AudioInput). On WASM the browser supplies the audio through the same fl::UIAudio element (Sailboat pattern: UIAudio(name, config) + FastLED.add(audio_ui)).
  • Normalize: signal conditioning (DC removal / spike filter / noise gate), INMP441 mic frequency-response profile, adaptive noise-floor tracking, and the self-normalizing vibe (MilkDrop) bass analysis — thresholds mean "x times the song's running average", so they hold at any volume.
  • Select-filter: only rising bass-band energy (bassSpike) counts as a beat; two live-adjustable thresholds split beats into sensitive (inner panel, default 1.05x) and loud (outer panel, default 1.6x).
  • EL panel drive: each panel gate pin (inner=GPIO5, outer=GPIO6) runs low-frequency PWM at 50 Hz through the portable fl::setPwmFrequency() + fl::analogWrite() facade (same path as examples/ElPanelReactive), because EL inverters must be gated slowly, not chopped at kHz rates.
  • Preview: a 12-LED inner disc + 24-LED outer ring ScreenMap renders the panels in the WASM browser preview (and doubles as an optional debug strip on GPIO3).
  • Differs from examples/ElPanelReactive (continuous-envelope, browser-audio-only): HydroPack is spike-gated — panels flash on discrete beats — and wires a real INMP441 for standalone wearable use.

2. fix(esp32): fl::analogWrite() / fl::setPwm16() actually write LEDC duty

Found by this PR's code review: on ESP32 the native pin backend's analogWrite/setPwm16 were no-op stubs, so the documented setPwmFrequency() + analogWrite() PWM flow configured the LEDC timer and then never updated the duty — panels stayed dark (this also silently broke examples/ElPanelReactive's hardware path). Now duty writes route to the LEDC channel allocated by setPwmFrequencyNative() (input scaled to the channel's duty resolution, full-on quirk handled). Also clamps the pre-IDF-5.3 duty-resolution fallback to the SoC's LEDC timer width (14 bits on C3/S2/S3) instead of a fixed 16, which made 50 Hz fail ledc_timer_config on those parts.

3. Pre-existing lint debt (was failing bash lint --cpp, which template_unit_test.yml runs on every PR)

bash lint failed on master with 27 C++ violations plus a Python DCT002, left over from the recent RP2040 driver work (#3663–#3665, #3675):

  • Move the UART waveN encoder to the channel layer (fl/channels/uart_wave_encoder.{h,cpp.hpp}): the impl is platform-neutral and was already compiled on every platform through a forbidden cross-directory _build include. It now compiles once in fl/channels/_build.cpp.hpp; all (repo-internal) includers were updated and the ESP-path header deleted; the unit test moved to tests/fl/channels/ to mirror the source. Clears CppHppIncludes / PlatformIncludes / PlatformTrampoline / IwyuPragmaBlock / UnityBuild violations.
  • RP peripheral impls: add missing platforms/arm/rp/is_rp.h includes, uint32_t → u32, sanctioned suppressions for the deliberate DMA ProgramStorage new/delete pair and the static DMA capture buffer; the flagged reinterpret_cast turned out to be a no-op cast between identical types and was removed outright.
  • RP engine host tests: drop the banned *.cpp.hpp includes — the engines are already compiled into the library on every platform.
  • ci/autoresearch/test_rp_spi_loopback.py: tuple[int, int, int] → frozen slotted SpiPins dataclass (DCT002), plus ruff-format autofixes in five ci/ files.

4. Pre-existing test failures on master (fl_chipsets_encoders)

Commit 34a86a7 (#3669) switched the SK9822/APA102 encoders to datasheet-required all-ones end clocks but left the unit tests asserting the old 0x00 end frames — 11 assertions failing on master. Tests updated to the actual contract; stale ceil(num_leds/32) doc comments corrected to the real (num_leds / 32) + 1 formula across the encoder headers.

Code review (multi-agent, 10 finder angles + adversarial verify + gap sweep)

Applied: library PWM facade reuse (replacing a hand-rolled LEDC fork), the ESP32 analogWrite no-op fix above, dedup of the beat handler, PWM duty caching + frame pacing for battery use, millis-wrap sentinel fix, ASCII-only compliance in moved files, forwarding-header removal, doc-formula corrections.

Deferred with rationale:

Validation

  • bash lint — clean (was failing on master).
  • bash test --cpp — full suite passes, including a --clean rebuild after the test-file move (was failing on master: fl_chipsets_encoders).
  • bash compile wasm --examples hydropack — passes.
  • fastled examples/hydropack --just-compile — passes (FastLED WASM CLI proof, per issue acceptance criteria).
  • bash compile esp32c3 --examples hydropack — passes.
  • bash compile rp2040 --examples Blink — passes (validates the rpcommon _build restructure).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added a Hydropack Arduino example featuring dual EL-panel beat visualization, adjustable thresholds, fade timing, and LED preview support.
    • Improved UART-based LED output with timing-aware encoding that works across supported platforms and baud-rate limits.
    • Improved ESP32 PWM output by scaling duty cycles to the configured hardware resolution.
  • Bug Fixes

    • Corrected SK9822 end-frame output to use the required all-ones clocks.
    • Updated APA102 and SK9822 empty-frame handling and protocol expectations.
  • Documentation

    • Clarified APA102, SK9822, and UART encoder guidance and examples.

zackees and others added 10 commits July 15, 2026 22:25
Dual EL-panel audio-reactive example for ESP32-C3 that is also a valid
FastLED WASM sketch. INMP441 audio is normalized (signal conditioning,
mic profile, self-normalizing vibe analysis), then bass beats are split
by loudness: the inner panel fires on sensitive beats, the outer panel
only on loud ones. Panels are gated with low-frequency 50 Hz PWM
(LEDC, 12-bit) as required by EL inverter hardware. A ScreenMap disc +
ring preview renders the panels in the browser.

Refs #3681

Co-Authored-By: Claude Fable 5 <[email protected]>
The encoder is platform-neutral (inverted UART frame model plus
ChipsetTimingConfig only) but lived under platforms/esp/32 and was
pulled into the RP build through a forbidden cross-directory _build
include. Move the implementation to fl/channels/uart_wave_encoder.*,
compile it once via fl/channels/_build.cpp.hpp, keep the ESP-path
header as a forwarder, sort rpcommon/_build.cpp.hpp alphabetically,
and drop the banned *.cpp.hpp includes from the RP engine host tests
(the engines are already compiled into the library on every platform).

Clears the CppHppIncludes, PlatformIncludes, PlatformTrampoline,
IwyuPragmaBlock, and UnityBuild lint violations that were failing
`bash lint --cpp` on every PR.

Co-Authored-By: Claude Fable 5 <[email protected]>
- Add missing platforms/arm/rp/is_rp.h includes to the RP peripheral
  impls that gate on FL_IS_RP2040/FL_IS_RP2350
- uint32_t -> u32 in RP DMA transfer-count casts
- Annotate the deliberate ProgramStorage new/delete pair, the PIO
  instruction reinterpret_cast, and the static DMA capture buffer with
  the sanctioned lint suppressions
- Replace the tuple[int, int, int] return in test_rp_spi_loopback.py
  with a frozen slotted SpiPins dataclass (DCT002)
- ruff-format autofixes in five ci/ files

Together with the encoder move this returns `bash lint` to green.

Co-Authored-By: Claude Fable 5 <[email protected]>
Commit 34a86a7 (#3669) switched the SK9822 encoders to the
datasheet-required all-ones end clock frames and gave the zero-LED
paths a complete start+end frame, but left the unit tests asserting
the old 0x00 end frames. Update the expectations, helper, and test
names to the actual contract; fl_chipsets_encoders passes again.

Co-Authored-By: Claude Fable 5 <[email protected]>
…facade

Code-review follow-up: replace the hand-rolled LEDC wrapper (with its
Arduino core 2.x/3.x fork) with fl::setPwmFrequency + fl::analogWrite,
the same 50 Hz EL-inverter gating path examples/ElPanelReactive uses.
Also dedupe the inner/outer beat handler into firePanel(), cache the
last written duty (50 Hz PWM only latches once per 20 ms period), pace
the frame loop for battery use, fix the millis-wrap first-frame
sentinel, and cross-reference ElPanelReactive.

Refs #3681

Co-Authored-By: Claude Fable 5 <[email protected]>
All includers of the legacy ESP-path header were repo-internal, so
update them to fl/channels/uart_wave_encoder.h and delete the
forwarder instead of keeping permanent indirection. Move the encoder
unit test to tests/fl/channels/ to mirror the source location (and
update the placement example in agents/tests.md). Replace the
non-ASCII doc glyphs the moved files inherited with ASCII per
cpp-standards.

Co-Authored-By: Claude Fable 5 <[email protected]>
pio_instr is a typedef of fl::u16 and mProgramInstructions is already
u16[16], so plain pointer decay compiles without any cast; keeping the
reinterpret_cast (even suppressed) would silently reinterpret the
buffer if pio_instr ever changed width.

Co-Authored-By: Claude Fable 5 <[email protected]>
The encoders write (num_leds / 32) + 1 end DWords, not ceil(num_leds/32)
as the doc comments claimed (they differ at 0 and exact multiples of
32), and SK9822 no longer has a different end frame from APA102 since
the #3669 all-ones fix. Also replaces the non-ASCII ceiling glyphs.

Co-Authored-By: Claude Fable 5 <[email protected]>
The ESP32 native pin backend left analogWrite() and setPwm16() as
no-op stubs, so the documented setPwmFrequency() + analogWrite() PWM
flow configured the LEDC timer and then never updated the duty - the
output stayed at 0 (this silently broke the ElPanelReactive example
hardware path, and hydropack would have hit the same wall). Duty
writes now scale onto the LEDC channel allocated by
setPwmFrequencyNative(), with the full-on duty quirk handled.

Also clamp the pre-IDF-5.3 duty-resolution fallback to the SoC LEDC
timer width (14 bits on C3/S2/S3) instead of a fixed 16, which made
low frequencies like 50 Hz fail ledc_timer_config on those parts.

Found by the multi-agent code review for #3681.

Co-Authored-By: Claude Fable 5 <[email protected]>
The include-swap edits were applied through a PowerShell 5.1
Get-Content/Set-Content round trip, which added a UTF-8 BOM and
double-encoded the existing multibyte comment glyphs into mojibake.
Restore both files byte-for-byte from master and reapply only the
intended include swap.

Co-Authored-By: Claude Fable 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds a shared UART wave encoder, a HydroPack dual-panel audio visualizer, resolution-aware ESP32 PWM writes, revised APA102/SK9822 end-frame tests and documentation, and CI/RP platform integration updates.

Changes

Platform-neutral UART wave encoder

Layer / File(s) Summary
UART encoder API and implementation
src/fl/channels/uart_wave_encoder.h, src/fl/channels/uart_wave_encoder.cpp.hpp
Adds timing-fit, LUT construction, feasibility, encoding, and buffer-sizing APIs for wave10 UART output.
Shared build and driver migration
src/fl/channels/_build.cpp.hpp, src/platforms/esp/32/drivers/uart/..., tests/fl/channels/uart_wave_encoder.cpp, tests/fl/platforms/esp/32/drivers/uart/..., agents/tests.md
Compiles the shared implementation and updates ESP32 UART drivers, tests, and placement guidance to use the shared header.

HydroPack audio visualizer

Layer / File(s) Summary
Audio-reactive panel controller
examples/hydropack/hydropack.ino
Adds audio beat detection, adjustable thresholds and fade timing, 50 Hz EL-panel PWM, and a WASM circular LED preview.

ESP32 native PWM scaling

Layer / File(s) Summary
Resolution-aware LEDC writes
src/platforms/esp/32/pin_esp32_native_impl.hpp
Tracks LEDC duty resolution and scales analogWrite() and setPwm16() values into the configured hardware range.

APA102 and SK9822 end-frame contracts

Layer / File(s) Summary
Protocol documentation and expectations
src/fl/chipsets/encoders/{apa102.h,pixel_iterator.h,sk9822.h}, src/fl/chipsets/spi.h, tests/fl/chipsets/encoders/{apa102.hpp,sk9822.hpp}
Updates end-frame formulas and validates SK9822 all-ones end clocks, including empty-range and boundary cases.

CI and RP platform integration

Layer / File(s) Summary
CI harness data and formatting
ci/autoresearch/..., ci/esbuild_frontend.py, ci/rpc_schema_validator.py, ci/tests/...
Uses a structured SPI pin container and applies equivalent formatting-only changes to CI scripts and tests.
RP unity-build and DMA updates
src/platforms/arm/rp/rpcommon/..., tests/platforms/arm/rp/rpcommon/...
Adjusts unity-build ordering, platform includes, DMA casts, allocation annotations, pointer handling, and public-header test dependencies.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related issues

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is specific and accurately reflects the PR's main feature work plus supporting fixes.
Linked Issues check ✅ Passed The HydroPack example, 50 Hz dual-panel control, ESP32-C3 support, and WASM preview align with issue #3681.
Out of Scope Changes check ✅ Passed The PWM, encoder, docs, and test changes are described in the PR objectives and support the feature work.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/hydropack-example

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/fl/channels/uart_wave_encoder.h (1)

143-210: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider fl::span instead of raw (ptr, size) pairs for this new public API.

detail::encodeUart2Bits/encodeUartByte and both encodeLedsToUart() overloads take raw pointer+length pairs. FastLED's own conventions favor non-owning fl::span<T> views over raw (ptr, size) parameters for exactly this kind of buffer API, and this is a brand-new shared entry point about to be adopted by additional backends (RP2040 per the PR stack). Changing the signature now, before more call sites exist, is cheaper than later.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fl/channels/uart_wave_encoder.h` around lines 143 - 210, Update the new
buffer APIs to use FastLED’s fl::span views instead of separate raw pointer and
size parameters, including detail::encodeUartByte and the Wave10-lut
encodeLedsToUart overload; preserve the existing encoding behavior and leave the
legacy overload’s compatibility contract unchanged unless required to align its
buffer parameters.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/fl/channels/uart_wave_encoder.h`:
- Around line 77-103: Guard the infeasible zero-pulse sentinel consistently:
update Wave10Lut::dataBits() in src/fl/channels/uart_wave_encoder.h:77-103 to
return 0 when pulses_per_bit is zero, and update encodeLedsToUart() in
src/fl/channels/uart_wave_encoder.cpp.hpp:242-259 to return 0 before encoding
when lut.pulses_per_bit is zero.

---

Nitpick comments:
In `@src/fl/channels/uart_wave_encoder.h`:
- Around line 143-210: Update the new buffer APIs to use FastLED’s fl::span
views instead of separate raw pointer and size parameters, including
detail::encodeUartByte and the Wave10-lut encodeLedsToUart overload; preserve
the existing encoding behavior and leave the legacy overload’s compatibility
contract unchanged unless required to align its buffer parameters.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 8f4421b0-e9b0-4b02-a36b-e310b88c2628

📥 Commits

Reviewing files that changed from the base of the PR and between b443b98 and 59f0172.

📒 Files selected for processing (32)
  • agents/tests.md
  • ci/autoresearch/phases.py
  • ci/autoresearch/test_rp_spi_loopback.py
  • ci/esbuild_frontend.py
  • ci/rpc_schema_validator.py
  • ci/tests/test_autoresearch_phases.py
  • ci/tests/test_esbuild_frontend.py
  • examples/hydropack/hydropack.ino
  • src/fl/channels/_build.cpp.hpp
  • src/fl/channels/uart_wave_encoder.cpp.hpp
  • src/fl/channels/uart_wave_encoder.h
  • src/fl/chipsets/encoders/apa102.h
  • src/fl/chipsets/encoders/pixel_iterator.h
  • src/fl/chipsets/encoders/sk9822.h
  • src/fl/chipsets/spi.h
  • src/platforms/arm/rp/rpcommon/_build.cpp.hpp
  • src/platforms/arm/rp/rpcommon/rp_pio_tx_peripheral.cpp.hpp
  • src/platforms/arm/rp/rpcommon/rp_spi_peripheral.cpp.hpp
  • src/platforms/arm/rp/rpcommon/rp_uart_peripheral.cpp.hpp
  • src/platforms/arm/rp/rpcommon/rx_pio_channel.cpp.hpp
  • src/platforms/esp/32/drivers/uart/_build.cpp.hpp
  • src/platforms/esp/32/drivers/uart/channel_driver_uart.h
  • src/platforms/esp/32/drivers/uart/wave8_encoder_uart.cpp.hpp
  • src/platforms/esp/32/drivers/uart/wave8_encoder_uart.h
  • src/platforms/esp/32/pin_esp32_native_impl.hpp
  • tests/fl/channels/uart_wave_encoder.cpp
  • tests/fl/chipsets/encoders/apa102.hpp
  • tests/fl/chipsets/encoders/sk9822.hpp
  • tests/platforms/arm/rp/rpcommon/channel_engine_rp_pio.cpp
  • tests/platforms/arm/rp/rpcommon/channel_engine_rp_spi.cpp
  • tests/platforms/arm/rp/rpcommon/channel_engine_rp_uart.cpp
  • tests/platforms/esp/32/drivers/uart/channel_driver_uart.cpp
💤 Files with no reviewable changes (4)
  • tests/platforms/arm/rp/rpcommon/channel_engine_rp_pio.cpp
  • tests/platforms/arm/rp/rpcommon/channel_engine_rp_spi.cpp
  • src/platforms/esp/32/drivers/uart/wave8_encoder_uart.h
  • src/platforms/esp/32/drivers/uart/wave8_encoder_uart.cpp.hpp

Comment on lines +77 to +103
struct Wave10Lut {
u8 lut[4]; ///< 2-bit input -> UART data byte
u8 pulses_per_bit; ///< Frame geometry: 5 (wave10) or 4 (wave8-frame); 0 = infeasible

/// @brief UART word length for this geometry (2P - 2 data bits)
u8 dataBits() const FL_NO_EXCEPT {
return static_cast<u8>(2 * pulses_per_bit - 2);
}

/// @brief Baud rate this LUT's geometry requires for the timing
/// (baud = P / bit_period; one UART bit per pulse).
u32 baudRate(const ChipsetTimingConfig& timing) const FL_NO_EXCEPT {
const u32 period_ns = timing.total_period_ns();
if (period_ns == 0 || pulses_per_bit == 0) return 0;
return static_cast<u32>(
static_cast<u64>(pulses_per_bit) * 1000000000ULL / period_ns);
}

/// @brief Legacy fixed-wave10 baud computation (P = 5)
/// @deprecated Prefer the instance `baudRate()` which respects the
/// selected geometry.
static u32 computeBaudRate(const ChipsetTimingConfig& timing) FL_NO_EXCEPT {
const u32 period_ns = timing.total_period_ns();
if (period_ns == 0) return 0;
return static_cast<u32>(5000000000ULL / period_ns);
}
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Guard Wave10Lut's infeasible sentinel in all consumers. dataBits() should return 0 when pulses_per_bit == 0, and encodeLedsToUart() should reject that LUT instead of emitting garbage output.

  • src/fl/channels/uart_wave_encoder.h#L77-L103: add the zero guard (or a small isFeasible() helper) so the sentinel behaves consistently with baudRate().
  • src/fl/channels/uart_wave_encoder.cpp.hpp#L242-L259: return 0 when lut.pulses_per_bit == 0 before encoding.
📍 Affects 2 files
  • src/fl/channels/uart_wave_encoder.h#L77-L103 (this comment)
  • src/fl/channels/uart_wave_encoder.cpp.hpp#L242-L259
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fl/channels/uart_wave_encoder.h` around lines 77 - 103, Guard the
infeasible zero-pulse sentinel consistently: update Wave10Lut::dataBits() in
src/fl/channels/uart_wave_encoder.h:77-103 to return 0 when pulses_per_bit is
zero, and update encodeLedsToUart() in
src/fl/channels/uart_wave_encoder.cpp.hpp:242-259 to return 0 before encoding
when lut.pulses_per_bit is zero.

@zackees
zackees merged commit 214d499 into master Jul 16, 2026
12 of 13 checks passed
@zackees
zackees deleted the feat/hydropack-example branch July 16, 2026 06:20
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jul 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

feat(examples): HydroPack - dual EL-panel beat visualizer (INMP441, normalized bass detection, 50 Hz PWM, ESP32-C3 + WASM)

1 participant