Skip to content

refactor(rmt4): extract IRMT4Peripheral lifecycle wrapper (#3458) - #3461

Merged
zackees merged 1 commit into
masterfrom
feat/3458-rmt4-peripheral-wrapper
Jun 30, 2026
Merged

zackees merged 1 commit into
masterfrom
feat/3458-rmt4-peripheral-wrapper

Conversation

@zackees

@zackees zackees commented Jun 30, 2026 •

Copy link
Copy Markdown
Member

Summary

Brings the classic-ESP32 RMT (rmt_4) driver in line with the ChannelEngine + Peripheral API-object pattern that UART, FlexIO, and RMT5 already use. This is Phase 1 + Phase 3 of the plan in #3458 — peripheral wrapper + bus-holder shape cleanup. Phase 2 (the actual ESP-IDF lifecycle calls) was already implemented; the stale "Stubs (to be implemented in Phase 3B)" comment misled the survey.

Closes #3458.

What changes

New files

  • irmt4_peripheral.h — IRMT4Peripheral virtual interface + Rmt4ChannelConfig. Companion to IRMT5Peripheral / IUartPeripheral.
  • rmt4_peripheral_esp.h / rmt4_peripheral_esp.cpp.hpp — Rmt4PeripheralESP, the real-hardware wrapper around driver/rmt.h.

Edited files

  • channel_driver_rmt4.h — engine now holds shared_ptr<IRMT4Peripheral>; added overloaded factory create(peripheral) and an injecting constructor for the holder.
  • channel_driver_rmt4.cpp.hpp — every ESP-IDF lifecycle call (rmt_config, rmt_driver_install, rmt_set_tx_intr_en, rmt_set_tx_thr_intr_en, rmt_set_gpio / rmt_set_pin, esp_intr_alloc / esp_intr_free) is routed through mPeripheral. Removed the stale "Phase 3B stubs" banner.
  • bus_traits.h — uses detail::Rmt4BusHolder { peripheral, driver }, mirroring detail::UartBusHolder exactly.
  • _build.cpp.hpp — includes the new peripheral .cpp.hpp.
  • README.md — documents the new abstraction + ISR carve-out.

What stays inline IRAM (NOT virtualised)

The IRAM ISR hot path stays exactly where it was — virtual dispatch from an ISR defeats the FL_NO_INLINE literal-pool placement guarantees that #2247 / #2252 established. The interface header's docblock spells this out under "Interface scope — what's OUT":

  • direct RMT.* register reads/writes
  • gpio_matrix_out() disconnect
  • fillNextBuffer() double-buffer refill
  • tx_start() per-platform register kicks

Validation

  • bash test --cpp — 340/340 pass on this branch.
  • clang-format --dry-run --Werror clean on all new + edited files.
  • bash compile esp32dev --examples AutoResearch — currently blocked on this Windows box by a separate fbuild spec-file backslash regression (cc1plus: fatal error: C:Usersniteris.fbuild...) that also reproduces on plain master. Not introduced by this PR. CI on Linux exercises the build.

Out of scope (called out explicitly)

  • Rmt4PeripheralMock for host-side unit tests of the engine's channel-management strategies — straightforward follow-up, but not in this PR.
  • RMT5 (S3/C3/C6/H2/P4) — separate driver, already conforms.
  • The TX (rmt_4) + RX (rmt_rx) peripheral merge — flagged in the survey, explicitly deferred.
  • No Bus::RMT_SPI enum, no SPI mode work — RMT is not a parallel-IO peripheral, so the agents/docs/cpp-standards.md unified-engine rule does not apply.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Improved ESP32 RMT4 support with a more robust driver lifecycle, helping the platform manage channels and interrupts more reliably.
    • Expanded build support to include the updated RMT4 implementation in unified builds.
  • Bug Fixes

    • Added stricter safeguards for channel setup and release to reduce misconfiguration and improve reuse.
    • Improved handling of interrupt and transmission shutdown paths for better stability on supported ESP32 targets.
  • Documentation

    • Updated the RMT4 README to reflect the latest driver capabilities and behavior.

Brings the classic-ESP32 RMT (rmt_4) driver in line with the
ChannelEngine + Peripheral API-object pattern that UART, FlexIO, and
RMT5 already use. This is Phase 1 + Phase 3 of the plan in #3458:
peripheral wrapper + bus-holder shape cleanup. Phase 2 (the actual
ESP-IDF lifecycle calls) was already implemented — the stale
"Stubs (to be implemented in Phase 3B)" comment misled the survey.

## What moved through the wrapper

The new `IRMT4Peripheral` virtual interface (`irmt4_peripheral.h`)
covers exactly the ESP-IDF lifecycle/control surface:

  - rmt_config()
  - rmt_driver_install() / rmt_driver_uninstall()
  - rmt_set_tx_thr_intr_en()
  - rmt_set_tx_intr_en()
  - rmt_set_gpio() / rmt_set_pin()
  - esp_intr_alloc() / esp_intr_free()

`Rmt4PeripheralESP` is the real-hardware concrete impl. The engine
holds a `shared_ptr<IRMT4Peripheral>` and routes those calls through
it.

## What does NOT go through the wrapper

The IRAM ISR hot path stays inline in the engine header. Virtual
dispatch from the ISR would defeat the `FL_NO_INLINE` literal-pool
placement guarantees on Xtensa (#2247 / #2252):

  - direct RMT.* register reads/writes
  - gpio_matrix_out() disconnect
  - fillNextBuffer() double-buffer refill
  - tx_start() per-platform register kicks

The interface header's docblock spells this out explicitly under
"Interface scope — what's OUT".

## BusTraits<Bus::RMT> uses the holder pattern

`bus_traits.h` now constructs a `detail::Rmt4BusHolder { peripheral,
driver }`, mirroring `detail::UartBusHolder` exactly. The static
`gHolder` keeps both lifetimes paired and the function-local-static
guard means we still only emit one `BusTraits<Bus::RMT>` definition
per program.

## Stale comment removed

`channel_driver_rmt4.cpp.hpp` had a "Stubs (to be implemented in
Phase 3B)" banner above `acquireChannel()` / `releaseChannel()` /
`configureChannel()`. Those are all implemented — they install the
driver, configure the channel, allocate the hardware buffer, etc.
The banner was a leftover from the Phase-3A scaffolding and gave a
misleading impression of the driver's completeness.

## Tests + validation

- `bash test --cpp` — 340/340 pass on this branch.
- `clang-format --dry-run --Werror` clean on all new + edited files.
- `bash compile esp32dev --examples AutoResearch` is currently
  blocked on this Windows box by a separate fbuild spec-file
  backslash regression (`cc1plus: fatal error: C:Usersniteris...`)
  that also reproduces on plain master. Tracked separately —
  not introduced by this PR. CI on Linux will exercise the build.

## Out of scope

- `Rmt4PeripheralMock` for host-side unit tests of the engine's
  channel acquire/reconfigure/release strategies — straightforward
  follow-up but not in this PR.
- RMT5 (S3/C3/C6/H2/P4) — separate driver, already conforms.
- The TX/RX `rmt_4` + `rmt_rx` peripheral merge — flagged in the
  survey, explicitly out of scope.

Closes #3458.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 30, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The ESP32 classic RMT4 driver is refactored to route ESP-IDF lifecycle calls through a new IRMT4Peripheral interface implemented by Rmt4PeripheralESP. ChannelEngineRMT4/Impl now accept an injected peripheral, replacing direct interrupt handle/register manipulation in most code paths. BusTraits<Bus::RMT> is updated to construct the driver via a new holder, and the README documents the change.

Changes

RMT4 ChannelEngine Peripheral Abstraction

Layer / File(s) Summary
IRMT4Peripheral interface and config types
src/platforms/esp/32/drivers/rmt/rmt_4/irmt4_peripheral.h
Defines Rmt4ChannelConfig, Rmt4IsrHandler, and the pure-virtual IRMT4Peripheral interface for channel configuration, driver install/uninstall, interrupt control, GPIO assignment, and ISR install/free.
Rmt4PeripheralESP implementation
src/platforms/esp/32/drivers/rmt/rmt_4/rmt4_peripheral_esp.h, rmt4_peripheral_esp.cpp.hpp
Declares and implements fl::Rmt4PeripheralESP, wrapping rmt_config, rmt_driver_install/uninstall, threshold/TX interrupt control, GPIO assignment, and esp_intr_alloc/free-based ISR management.
ChannelEngineRMT4 header restructuring
src/platforms/esp/32/drivers/rmt/rmt_4/channel_driver_rmt4.h
Adds a peripheral-injecting factory/constructor, replaces the direct interrupt handle with mPeripheral and an opaque void pointer, adds an RMT5-only #error guard, and reformats helper signatures.
ChannelEngineRMT4 lifecycle/channel management
src/platforms/esp/32/drivers/rmt/rmt_4/channel_driver_rmt4.cpp.hpp
Reworks construction, destruction, channel acquisition/release/configuration, scheduling, transmission start, polling, and flash-lock handling to route through mPeripheral instead of direct ESP-IDF calls.
BusTraits wiring and docs
src/platforms/esp/32/drivers/rmt/rmt_4/bus_traits.h, _build.cpp.hpp, README.md
Introduces Rmt4BusHolder owning the peripheral and driver, adds the unity-build include, and documents the IRMT4Peripheral abstraction in the README.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant ChannelEngineRMT4Impl
  participant Rmt4PeripheralESP
  participant ESPIDF as ESP-IDF RMT driver

  Caller->>ChannelEngineRMT4Impl: beginTransmission(channelData)
  ChannelEngineRMT4Impl->>ChannelEngineRMT4Impl: acquireChannel()
  ChannelEngineRMT4Impl->>Rmt4PeripheralESP: configureChannel(Rmt4ChannelConfig)
  Rmt4PeripheralESP->>ESPIDF: rmt_config(...)
  ChannelEngineRMT4Impl->>Rmt4PeripheralESP: installDriver(channel)
  Rmt4PeripheralESP->>ESPIDF: rmt_driver_install(...)
  ChannelEngineRMT4Impl->>Rmt4PeripheralESP: setGpio(channel, gpio_pin)
  ChannelEngineRMT4Impl->>Rmt4PeripheralESP: setTxIntrEnable(channel, true)
  ChannelEngineRMT4Impl->>ChannelEngineRMT4Impl: tx_start (critical section)
  ChannelEngineRMT4Impl->>Rmt4PeripheralESP: poll()/releaseChannel() on completion
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • FastLED/FastLED#2252: Earlier refactor of the same ChannelEngineRMT4Impl ISR/helper functions (handleInterrupt, fillNextBuffer, convertByteToRMT, tx_start) that this PR further restructures under the peripheral abstraction.
  • FastLED/FastLED#2429: Introduced the fl::Bus/BusTraits foundation that this PR's BusTraits<Bus::RMT> and Rmt4BusHolder changes build upon.
  • FastLED/FastLED#3229: Related FASTLED_RMT5 gating logic for selecting RMT backend variants, overlapping with this PR's RMT5-only compile guards.

Poem

A peripheral born, a wrapper so neat,
Hiding the IDF calls, making code sweet.
Channels now hop through an interface clean,
ISRs still hum where the hot path is seen.
Thump-thump says this rabbit, the driver's refined! 🐇⚡

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The peripheral wrapper refactor is present, but the required fillNextBuffer stub removal and symbol-encoding tests are not evidenced here. Finish the refill path, add the symbol-encoding/timing tests, and verify the modern Channel::create() path still passes.
Docstring Coverage ⚠️ Warning Docstring coverage is 23.81% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and accurately summarizes the main RMT4 peripheral-wrapper refactor.
Out of Scope Changes check ✅ Passed The diff stays within the RMT4 refactor scope and only adds the new peripheral abstraction, wiring, and supporting docs/build includes.
✨ 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/3458-rmt4-peripheral-wrapper

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.

🧹 Nitpick comments (1)
src/platforms/esp/32/drivers/rmt/rmt_4/rmt4_peripheral_esp.cpp.hpp (1)

13-21: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reuse FASTLED_ESP32_RMT5_ONLY_PLATFORM in the RMT4 .cpp.hpp guards. rmt4_peripheral_esp.cpp.hpp and channel_driver_rmt4.cpp.hpp still duplicate the C6/C5/P4/H2 list inline, while the matching headers already gate on the shared macro. Using the macro here keeps the header/implementation split aligned and avoids future drift.

🤖 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/platforms/esp/32/drivers/rmt/rmt_4/rmt4_peripheral_esp.cpp.hpp` around
lines 13 - 21, The RMT4 guard logic in rmt4_peripheral_esp.cpp.hpp still
hardcodes the C6/C5/P4/H2 chip list instead of using the shared
FASTLED_ESP32_RMT5_ONLY_PLATFORM macro. Update the preprocessor conditions
around the rmt4_peripheral_esp include to reuse that macro, matching the pattern
already used in channel_driver_rmt4.cpp.hpp and the related headers so the RMT4
path stays consistent with the shared platform gating.
🤖 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.

Nitpick comments:
In `@src/platforms/esp/32/drivers/rmt/rmt_4/rmt4_peripheral_esp.cpp.hpp`:
- Around line 13-21: The RMT4 guard logic in rmt4_peripheral_esp.cpp.hpp still
hardcodes the C6/C5/P4/H2 chip list instead of using the shared
FASTLED_ESP32_RMT5_ONLY_PLATFORM macro. Update the preprocessor conditions
around the rmt4_peripheral_esp include to reuse that macro, matching the pattern
already used in channel_driver_rmt4.cpp.hpp and the related headers so the RMT4
path stays consistent with the shared platform gating.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: e6d46c90-1522-43f9-914c-157694c0e1ee

📥 Commits

Reviewing files that changed from the base of the PR and between 5f2f1bc and f2dd745.

📒 Files selected for processing (8)
  • src/platforms/esp/32/drivers/rmt/rmt_4/README.md
  • src/platforms/esp/32/drivers/rmt/rmt_4/_build.cpp.hpp
  • src/platforms/esp/32/drivers/rmt/rmt_4/bus_traits.h
  • src/platforms/esp/32/drivers/rmt/rmt_4/channel_driver_rmt4.cpp.hpp
  • src/platforms/esp/32/drivers/rmt/rmt_4/channel_driver_rmt4.h
  • src/platforms/esp/32/drivers/rmt/rmt_4/irmt4_peripheral.h
  • src/platforms/esp/32/drivers/rmt/rmt_4/rmt4_peripheral_esp.cpp.hpp
  • src/platforms/esp/32/drivers/rmt/rmt_4/rmt4_peripheral_esp.h

@zackees
zackees merged commit 7d6cce8 into master Jun 30, 2026
8 of 11 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 30, 2026
zackees added a commit that referenced this pull request Jul 1, 2026
#3469) (#3470)

Ports the RMT5 `RmtMemoryManager` accounting ledger + adaptive
buffer-block strategy to the classic-ESP32 / IDF 4.x RMT driver,
following the rmt_4/rmt_5 split precedent from #3461 and #3467.

## What's in

- `rmt/rmt_4/rmt_memory_manager_4.h`   - header-inline class body
- `rmt/rmt_4/rmt_memory_manager_4.cpp.hpp` - platform-default singleton
- `rmt/rmt_4/network_state_tracker_4.{h,cpp.hpp}` - v1 stub returning
  `false`. Follow-up PR wires this to the shared network detector once
  it's lifted out of the FASTLED_RMT5 guard.

The manager tracks:
- Global word-pool (512 words on classic ESP32, 256 on S2 — 8 or 4
  channels × 64 words per block).
- Per-channel allocations (TX or RX distinguished by `is_tx` flag).
- `hasActiveRxChannels()` for TX-side coordination.
- Adaptive `calculateMemoryBlocks(network_active)` that returns 3 when
  the network is active AND the pool has room for the extra 64-word
  block, else 2 (RMT4 historic default).

## What's out (deliberately)

- No DMA accounting: RMT4 hardware has no DMA channel. The RMT5
  manager's DMA slot ledger is not ported.
- No dedicated TX/RX pools: RMT4 is always a global-pool platform.
- Real network detection: `NetworkStateTracker4::isActive()` is a
  stub `return false` for v1. That means today's behaviour is
  bit-for-bit identical to pre-#3469 — the manager plumbing is in
  place, but the driver still allocates 2 mem blocks per TX channel.
  Follow-up PR flips the stub to poll the (shared) network detector.
- No ISR-side refactor: the `PULSES_PER_FILL_RMT4` refill threshold
  stays fixed. Higher `mem_block_num` values in `rmt_config()` give
  the ISR more headroom before it misses its deadline; the reactive
  `checkTime` truncation in `fillNextBuffer` stays as a belt-and-
  braces safety net.

## Wiring

- `ChannelEngineRMT4Impl::configureChannel`: calls the manager's
  free-then-tryAllocateTx idiom. Failure returns false; caller
  (acquireChannel) treats this the same as HW-channel-count-miss and
  defers the strip to the pending queue. Uses
  `calculateMemoryBlocks(network_active)` to fill in
  `Rmt4ChannelConfig::mMemBlocks`.
- `ChannelEngineRMT4Impl::~ChannelEngineRMT4Impl`: releases every
  in-use channel's allocation.
- `rmt_rx_4/RmtRxChannelImpl` constructor: pre-registers a 64-symbol
  RX reservation with channel-id `128 + (pin & 0x7F)` so TX (using
  raw 0..N-1 IDs) never collides.
- `rmt_rx_4/RmtRxChannelImpl` destructor: releases the RX reservation.

## Tests

19 host `FL_TEST_CASE`s in
`tests/platforms/esp/32/drivers/rmt/rmt_4/rmt_memory_manager_4.cpp`,
covering:
  - pool starts empty
  - TX idle allocation = 128 words, network-active = 192 words
  - graceful demotion to 128 when 192 doesn't fit
  - pool-exhausted refusals
  - duplicate-alloc refusals
  - RX symbol-count recording, zero-symbol rejection
  - free() releases correctly; wrong is_tx and unknown-channel misses
  - free-then-realloc reconfigure idiom
  - hasActiveRxChannels tracks RX lifetime, ignores TX
  - calculateMemoryBlocks 2/3 selection + fallback when the extra
    block doesn't fit
  - reset() clears the ledger
  - 4 concurrent TX up to pool limit, 5th refused

Local results:
  - `bash test rmt_memory_manager_4 --cpp --clean`:
      [doctest] test cases: 19 | 19 passed | 0 failed
  - `bash test --cpp`: 342/342 pass (no regression).
  - `clang-format --dry-run --Werror` clean on every touched file.

The manager class body is header-inline on purpose so host tests
build it directly without needing the ESP-IDF headers. Only the
platform-default `instance()` singleton lives in the .cpp.hpp behind
the usual `FL_IS_ESP32 && !FASTLED_RMT5` guard.

`bash compile esp32dev` is still blocked on the pre-existing fbuild
Windows spec-file backslash regression (`cc1plus: fatal error:
C:Usersniteris.fbuild...`) that reproduces on plain master, so
on-device WROOM validation of the network-active bump rides on that
blocker as before. CI on Linux exercises the cross-compile.

Closes #3469.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@zackees
zackees deleted the feat/3458-rmt4-peripheral-wrapper branch August 21, 2026 19:15
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.

Refactor classic-ESP32 RMT (rmt_4) into the ChannelEngine + Peripheral API-object pattern

1 participant