Repository navigation
feat(esp32-s3): ISR-driven chunked DMA for LCD_CAM SPI and clockless drivers - #2260
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds an ISR-driven, chunked DMA streaming implementation for ESP32 LCD_SPI (SPI and new clockless paths), introduces a new LCD_CAM clockless channel driver and factory, registers the clockless engine before the legacy I2S path, and expands mocks and unit tests for multi-chunk flows. Changes
Sequence Diagram(s)sequenceDiagram
participant App as Application
participant CM as ChannelManager
participant Driver as LCD_CLOCKLESS Driver
participant Periph as LCD Peripheral
participant DMA as DMA Engine
participant ISR as ISR Callback
App->>CM: register/create engine
CM->>Driver: createLcdClocklessEngine()
App->>Driver: enqueue(channelData)
App->>Driver: show()
Driver->>Periph: registerIsrCallback(isrChunkDone)
Driver->>Periph: startTransmit(ring[0])
Periph->>DMA: submit(ring[0])
DMA->>ISR: onTransmitComplete()
ISR->>Driver: transpose next chunk -> ring[next]
ISR->>Periph: scheduleTransmit(ring[next])
alt more chunks
loop
DMA->>ISR: onTransmitComplete()
ISR->>Driver: prepare/schedule next chunk
end
else all done
ISR->>Driver: set mStreamComplete = true
end
App->>Driver: poll()
Driver-->>App: READY (when stream complete or peripheral idle)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~65 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 7
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_spi.cpp.hpp (2)
299-340:⚠️ Potential issue | 🟠 MajorReinitialize on pin/clock changes, not only on lane-count changes.
config.data_gpios[],config.clock_gpio, andconfig.clock_hzare rebuilt from the current channels, butneedPeripheralInitonly checksnumLanes. Reusing this driver for a different SPI pinout or bitrate with the same lane count will keep the old LCD_CAM wiring/clock and transmit with stale hardware settings.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_spi.cpp.hpp` around lines 299 - 340, The code only reinitializes the peripheral when numLanes changes (needPeripheralInit) but must also detect changes to the actual pin/clock configuration: compare the newly-built config.data_gpios[], config.clock_gpio and config.clock_hz against the driver's currently-active values (e.g., stored fields like mNumLanes, mDataGpios, mClockGpio, mClockHz) and set needPeripheralInit = true if any entry differs; then continue to call freeRingBuffers(), mPeripheral->deinitialize(), mPeripheral->initialize(config) and update the stored mDataGpios/mClockGpio/mClockHz/mNumLanes/mInitialized after successful init so future comparisons are correct.
182-210:⚠️ Potential issue | 🟠 MajorThe ISR path is still using the slow transpose.
isrChunkDone()callstransposeToWords()for every chunk, and this implementation is still a byte × bit × lane loop in the callback path. At the default 408-byte chunk size that is a large amount of per-bit work in ISR context, which defeats the stated ISR budget and the LUT-based transpose objective of this refactor.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_spi.cpp.hpp` around lines 182 - 210, The ISR path still does per-byte×per-bit×per-lane work in transposeToWords(), which is too slow for isrChunkDone(); replace the bit-loop with a LUT-based transpose: precompute a static u16 lookup table lookup[256][8] where lookup[b][k] contains the 8 u16 words for byte value b with bits placed for lane 0 (MSB->words[0]..words[7]); then in ChannelDriverLcdSpi::transposeToWords() iterate bytes and lanes, and for each lane OR (lookup[lane_byte][7 - bit_index] << lane) into the corresponding 8 output words (or better: for k=0..7 do output[k] |= lookup[byte][k] << lane); this removes the per-bit branch and inner bit loop in transposeToWords() called from isrChunkDone() and keeps the heavy work table-driven and ISR-safe (store LUT in flash/const) or move preparation outside the ISR if needed.
🧹 Nitpick comments (2)
src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.h (2)
98-100: Wrap ring-buffer ownership in an RAII type.
allocateRingBuffers()/freeRingBuffers()plusu16 *mRingBuffers[kRingBufferCount]makes DMA slot lifetime manual and easy to miss on partial-allocation or future early-return paths. A small buffer wrapper orfl::unique_ptrwith the right deleter would make ownership explicit and self-cleaning. As per coding guidelines, "Use proper RAII patterns with smart pointers (fl::shared_ptr, fl::unique_ptr) or moveable wrapper objects instead of raw pointers".Also applies to: 140-141
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.h` around lines 98 - 100, The mRingBuffers array and manual allocateRingBuffers()/freeRingBuffers() must be converted to an RAII-managed type to ensure deterministic cleanup on partial failures; replace raw u16* mRingBuffers[kRingBufferCount] with a moveable RAII wrapper (e.g., fl::unique_ptr<u16[]> with a custom deleter or a small RingBuffer class owning the buffer and capacity) and update allocateRingBuffers and freeRingBuffers to construct/assign or reset those RAII objects instead of doing manual new/free; ensure allocateRingBuffers returns false on any allocation failure without leaking by relying on the RAII wrapper and update any code paths that accessed mRingBuffers directly to use the wrapper's data()/get() accessor or member functions.
25-29: Replace raw#pragma oncewith the project’s approved header-guard/compiler-control pattern.This header already includes
fl/stl/compiler_control.h, so the raw pragma is the remaining guideline violation here. As per coding guidelines, "Use FastLED compiler control macros from fl/stl/compiler_control.h instead of raw#pragmadirectives".🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.h` around lines 25 - 29, Replace the raw "#pragma once" in channel_driver_lcd_clockless.h with the project's approved FastLED compiler-control header macros (the macros provided by fl/stl/compiler_control.h), i.e., remove the pragma and wrap the header contents with the begin/end compiler-control macros (use the FL_* header-guard macros such as the FL_BEGIN_HEADER/FL_END_HEADER pattern provided in compiler_control.h) so the file follows the project's header-guard convention.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/platforms/esp/32/drivers/channel_manager_esp32.cpp.hpp`:
- Around line 128-132: Channel selection is nondeterministic because
PRIORITY_LCD_CLOCKLESS and the legacy I2S priority are equal; update the
constants so LCD_CLOCKLESS has a strictly higher value than the I2S legacy
driver (e.g., increment PRIORITY_LCD_CLOCKLESS above PRIORITY_I2S) or
alternatively guard the legacy I2S registration so ChannelManager::addDriver()
never registers the I2S driver when the LCD clockless path
(FASTLED_ESP32_FORCE_LCD_CLOCKLESS or the LCD_CLOCKLESS availability check) is
enabled; apply the same fix for the other occurrence of these priority
definitions so LCD_CLOCKLESS always outranks I2S deterministically.
In `@src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp.hpp`:
- Around line 376-378: The call to
mPeripheral->registerTransmitCallback(reinterpret_cast<void *>(&isrChunkDone),
this) can fail and currently is ignored, causing only the first DMA chunk to be
sent; update the start/stream initialization path (where
registerTransmitCallback is invoked in the channel_driver_lcd_clockless code) to
check the return/result of registerTransmitCallback, and if it fails abort the
streaming startup: undo any started DMA/tx state, log an error with context
(including that registerTransmitCallback failed), set the channel/state to
not-streaming/ERROR or READY as appropriate, and return/propagate an error so
the caller does not assume streaming will proceed; ensure cleanup of resources
allocated before the call so no partial state remains.
- Around line 66-72: The destructor
ChannelDriverLcdClockless::~ChannelDriverLcdClockless currently clears mBusy and
calls freeRingBuffers even if mPeripheral->waitTransmitDone(2000) times out;
change the logic so you only clear mBusy and call freeRingBuffers when
waitTransmitDone indicates success, and do not free the DMA/ring buffers on
timeout (leave mBusy set and retain buffers) to avoid the LCD_CAM continuing to
read freed memory; update the flow around mPeripheral->waitTransmitDone, mBusy,
and freeRingBuffers accordingly (and optionally log or take a safe abort path if
waitTransmitDone fails).
- Around line 278-301: The peripheral reinit logic must consider timing and pin
changes, not just numLanes: update the code that loops channels (the block
computing maxSize, chipsetTiming, firstPin from channels using getSize,
getTiming, getPin) so it computes a deterministic signature/hash (or compares
per-lane timing and pin values) and set needPeripheralInit when that signature
differs from the previous configuration in addition to numLanes; stop using only
the first channel's timing (ChipsetTiming and timingFound) — either enforce all
channels share identical getTiming() and fail/normalize if not, or
aggregate/compare each channel.getTiming() and channel.getPin() so mixed-timing
lanes are detected and trigger full reconfigure prior to recomputing mClockHz,
wave mode and GPIO assignments used by show(). Ensure the signature is stored
and compared across calls to show() and used to decide peripheral
reinitialization.
In `@src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.h`:
- Around line 112-116: The ISR/task handoff currently relies on volatile fields
in struct IsrContext (mStreamComplete, mNextByteOffset, mRingWriteIdx) and the
volatile mBusy, which is unsafe because volatile doesn't provide atomicity or
ordering; change these to properly synchronized accesses by either (a) replacing
the volatile fields with atomic types (e.g., std::atomic<bool> for
mStreamComplete/mBusy and std::atomic<size_t> for mNextByteOffset/mRingWriteIdx)
and use atomic read/modify operations in isrChunkDone(), show(), and poll(), or
(b) wrap all accesses and compound updates to those fields in a critical section
using the ESP32 port macros (e.g., portENTER_CRITICAL/portEXIT_CRITICAL or an
appropriate spinlock) so read-modify-write sequences in isrChunkDone(), show(),
and poll() are atomic and ordered.
In `@src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_spi.cpp.hpp`:
- Around line 61-69: Destructor ChannelDriverLcdSpi::~ChannelDriverLcdSpi()
clears mBusy and calls freeRingBuffers() even if
mPeripheral->waitTransmitDone(2000) timed out; change it to check the result of
waitTransmitDone and only clear mBusy and call freeRingBuffers() when
waitTransmitDone indicates success/completion, otherwise leave mBusy true and do
not free the DMA ring buffers (optionally log or attempt a safe abort/retry
path), referencing mBusy, mPeripheral->waitTransmitDone, and freeRingBuffers()
to locate the code to change.
- Around line 347-349: The transmit callback registration can fail and currently
isn't checked; update the initialization where
mPeripheral->registerTransmitCallback(reinterpret_cast<void *>(&isrChunkDone),
this) is called to verify its boolean return and fail early on false (e.g.,
log/error and abort init or set an error state and return false) so the driver
never starts the first DMA chunk without a working callback; ensure any cleanup
is performed and that poll() will not attempt to send chunks when registration
failed.
---
Outside diff comments:
In `@src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_spi.cpp.hpp`:
- Around line 299-340: The code only reinitializes the peripheral when numLanes
changes (needPeripheralInit) but must also detect changes to the actual
pin/clock configuration: compare the newly-built config.data_gpios[],
config.clock_gpio and config.clock_hz against the driver's currently-active
values (e.g., stored fields like mNumLanes, mDataGpios, mClockGpio, mClockHz)
and set needPeripheralInit = true if any entry differs; then continue to call
freeRingBuffers(), mPeripheral->deinitialize(), mPeripheral->initialize(config)
and update the stored mDataGpios/mClockGpio/mClockHz/mNumLanes/mInitialized
after successful init so future comparisons are correct.
- Around line 182-210: The ISR path still does per-byte×per-bit×per-lane work in
transposeToWords(), which is too slow for isrChunkDone(); replace the bit-loop
with a LUT-based transpose: precompute a static u16 lookup table lookup[256][8]
where lookup[b][k] contains the 8 u16 words for byte value b with bits placed
for lane 0 (MSB->words[0]..words[7]); then in
ChannelDriverLcdSpi::transposeToWords() iterate bytes and lanes, and for each
lane OR (lookup[lane_byte][7 - bit_index] << lane) into the corresponding 8
output words (or better: for k=0..7 do output[k] |= lookup[byte][k] << lane);
this removes the per-bit branch and inner bit loop in transposeToWords() called
from isrChunkDone() and keeps the heavy work table-driven and ISR-safe (store
LUT in flash/const) or move preparation outside the ISR if needed.
---
Nitpick comments:
In `@src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.h`:
- Around line 98-100: The mRingBuffers array and manual
allocateRingBuffers()/freeRingBuffers() must be converted to an RAII-managed
type to ensure deterministic cleanup on partial failures; replace raw u16*
mRingBuffers[kRingBufferCount] with a moveable RAII wrapper (e.g.,
fl::unique_ptr<u16[]> with a custom deleter or a small RingBuffer class owning
the buffer and capacity) and update allocateRingBuffers and freeRingBuffers to
construct/assign or reset those RAII objects instead of doing manual new/free;
ensure allocateRingBuffers returns false on any allocation failure without
leaking by relying on the RAII wrapper and update any code paths that accessed
mRingBuffers directly to use the wrapper's data()/get() accessor or member
functions.
- Around line 25-29: Replace the raw "#pragma once" in
channel_driver_lcd_clockless.h with the project's approved FastLED
compiler-control header macros (the macros provided by
fl/stl/compiler_control.h), i.e., remove the pragma and wrap the header contents
with the begin/end compiler-control macros (use the FL_* header-guard macros
such as the FL_BEGIN_HEADER/FL_END_HEADER pattern provided in
compiler_control.h) so the file follows the project's header-guard convention.
🪄 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: defaults
Review profile: CHILL
Plan: Pro
Run ID: e3d7449c-2ac9-4be8-9ceb-712b912f3ec6
📒 Files selected for processing (9)
src/platforms/esp/32/drivers/channel_manager_esp32.cpp.hppsrc/platforms/esp/32/drivers/lcd_spi/_build.cpp.hppsrc/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp.hppsrc/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.hsrc/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_spi.cpp.hppsrc/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_spi.hsrc/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_mock.cpp.hpptests/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpptests/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_spi.cpp
…drivers Refactor the LCD_CAM SPI driver (ChannelDriverLcdSpi) and add a new clockless driver (ChannelDriverLcdClockless) for ESP32-S3. Both use ISR-driven 3-buffer ring architecture for chunked DMA streaming, modeled after the PARLIO driver. Key changes: - SPI driver: ISR callback transposes next chunk on DMA completion - Clockless driver: wave3/wave8 auto-select via canUseWave3(), uses wave3Transpose_16/wave8Transpose_16 for encoding in ISR context - Mock simulateTransmitComplete() drains full ISR callback chain - Chunk size capped at ~100 LEDs (SPI) / ~30 LEDs (clockless) - LCD clockless registered in channel manager, replacing misnamed "I2S" driver on ESP32-S3 22 new test cases across both drivers. All 299 tests pass, ASAN/LSAN/UBSAN clean, lint clean. Closes #2258 Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
4a0fa7e to
2320b2f
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (4)
src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp.hpp (3)
376-378:⚠️ Potential issue | 🟠 MajorCallback registration failure still silently ignored.
The return value of
registerTransmitCallbackis discarded. If registration fails, the initialtransmit()below will still send the first chunk,mBusywill be set, and then no ISR will ever advance the stream — subsequent chunks never ship andpoll()will eventually reportREADYoff theperipheralIdlepath (see related comment onpoll). Check the result, abort the stream (clearsetInUse, don't setmBusy), and returnfalse.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp.hpp` around lines 376 - 378, Check the boolean/return result of mPeripheral->registerTransmitCallback(reinterpret_cast<void *>(&isrChunkDone), this) and if it fails abort the stream: call the same cleanup used when a stream cannot start (clear setInUse on this stream), do not set mBusy, and make transmit() immediately return false so the caller knows start failed; this prevents starting the first chunk without an ISR and avoids leaving the stream stuck for poll()/peripheralIdle. Ensure you reference registerTransmitCallback, isrChunkDone, transmit(), mBusy, setInUse, and poll in the fix.
66-72:⚠️ Potential issue | 🟠 MajorDestructor still frees DMA ring buffers after a failed wait.
If
waitTransmitDone(2000)times out,mBusyis still cleared andfreeRingBuffers()proceeds unconditionally, so a stuck LCD_CAM transfer would continue DMA-reading freed memory. On timeout, leavemBusyset and skip freeing ring buffers (or take a hard-reset path on the peripheral first).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp.hpp` around lines 66 - 72, The destructor ChannelDriverLcdClockless::~ChannelDriverLcdClockless currently clears mBusy and always calls freeRingBuffers() even if mPeripheral->waitTransmitDone(2000) times out; change the flow so that you check the return/timeout result of waitTransmitDone and only clear mBusy and call freeRingBuffers() when waitTransmitDone succeeded, otherwise leave mBusy true and skip freeRingBuffers() (or attempt a safe peripheral hard-reset via mPeripheral before freeing); use the wait result to decide whether to freeRingBuffers() to avoid the DMA reading freed memory.
278-370:⚠️ Potential issue | 🟠 MajorReinit trigger still ignores timing and pin changes.
needPeripheralInitat line 334 is still keyed only offmNumLanes. A subsequentshow()with the same lane count but different per-channel timing (getTiming()) or different data GPIOs (getPin()) will skipdeinitialize()/initialize()and keep the previousconfig.clock_hzandconfig.data_gpios[]. Additionally, only lane 0's timing feedscanUseWave3,mWave3Lut, andmClockHz(lines 289–297), so mixed-timing lanes are silently encoded with lane 0's waveform. Build a signature over(numLanes, all pins, all timings)and compare — or enforce uniform timing across channels and fail otherwise.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp.hpp` around lines 278 - 370, The peripheral reinit logic only checks mNumLanes so changes in per-channel timing or pins are ignored, causing stale mClockHz/mWave*Lut and config.data_gpios; update the reinit condition in the init path (where needPeripheralInit is computed) to also consider a signature of all channels' getPin() and getTiming() (or alternatively validate that all channels share identical timing and fail early), and when the signature differs force deinitialize()/initialize() and recompute canUseWave3(chipsetTiming), mClockHz, mWave3Lut/mWave8Lut, and populate config.data_gpios[] from each channels[i]->getPin(); ensure mNumLanes/mInitialized are updated as before after successful init.src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.h (1)
112-145:⚠️ Potential issue | 🟠 Major
volatileis not sufficient for ISR↔task handoff on ESP32.
mStreamComplete,mNextByteOffset,mRingWriteIdx, andmBusyarevolatilebut accessed from both ISR (isrChunkDone) and task contexts (show,poll, dtor).volatileguarantees neither atomicity nor ordering; compound updates likectx.mNextByteOffset += chunkBytesin the ISR combined with unsynchronized task reads create real race windows on Xtensa/RISC-V with caches and OoO stores. Usefl::atomic<...>with explicit memory orders, or wrap the handoff inportENTER_CRITICAL_ISR/portENTER_CRITICALspinlocks.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.h` around lines 112 - 145, The ISR/task shared flags and counters (IsrContext::mStreamComplete, mNextByteOffset, mRingWriteIdx and the member mBusy) are declared volatile but need atomicity and ordering for safe handoff between isrChunkDone and task methods (show, poll, destructor); replace these volatile fields with fl::atomic<T> (e.g. fl::atomic<bool> for mStreamComplete/mBusy and fl::atomic<size_t> for offsets) and use appropriate memory_order (release in ISR updates, acquire in task reads) or alternatively protect all accesses in isrChunkDone and task paths with portENTER_CRITICAL_ISR/portEXIT_CRITICAL_ISR and portENTER_CRITICAL/portEXIT_CRITICAL critical sections to eliminate races. Ensure all compound updates (like ctx.mNextByteOffset += chunkBytes) are done using atomic fetch_add or inside the same critical section so isr and task views are consistent.
🧹 Nitpick comments (1)
src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp.hpp (1)
419-466:EspWrapperis a shared singleton bridge; consider hoisting out of the factory.Defining
EspWrapperas a local class insidecreateLcdClocklessEngine()and allocating a fresh one per call is fine functionally, but it duplicates the identical wrapper pattern used forChannelDriverLcdSpiagainst the sameLcdSpiPeripheralEsp::instance(). Consider extracting a single reusableLcdSpiPeripheralEspBridge(or similar) so both clockless and SPI factories share one bridge type and allocation. Non-blocking.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp.hpp` around lines 419 - 466, The local class EspWrapper inside createLcdClocklessEngine should be hoisted into a shared bridge type (e.g. LcdSpiPeripheralEspBridge) implemented once (wrapping detail::LcdSpiPeripheralEsp::instance()) and placed at namespace scope so both createLcdClocklessEngine and the ChannelDriverLcdSpi factory can reuse it; replace the local EspWrapper with fl::make_shared<LcdSpiPeripheralEspBridge>() when constructing ChannelDriverLcdClockless (and update the other factory to use the same bridge), keeping the same overridden methods (initialize, deinitialize, allocateBuffer, transmit, registerTransmitCallback, getConfig, getMicroseconds, delay, etc.) and preserving FL_NOEXCEPT and return types.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp.hpp`:
- Around line 307-352: The code sets numLanes =
static_cast<int>(channels.size()) and writes it to config.num_lanes while only
populating config.data_gpios[0..15], which can leave lanes >16 uninitialized;
clamp or reject extras. Update the initialization path (before using config) to
enforce a hard limit: compute an effectiveNumLanes =
std::min(static_cast<int>(channels.size()), 16) and use effectiveNumLanes for
config.num_lanes and any size calculations (e.g., slotCapacityBytes,
config.num_lanes), and either log/warn and ignore any channels beyond 16 or
return/fail early; ensure the for loop that fills config.data_gpios still
iterates up to effectiveNumLanes (or 16) so no data_gpios entries remain unset.
- Around line 157-176: The poll() method currently treats peripheralIdle
(mPeripheral->isBusy()) as a completion signal which can race with ISR chunking;
change the termination condition to rely only on the ISR-driven signals: use
mIsrCtx.mStreamComplete or mBusy (i.e., check streamDone || !mBusy) instead of
peripheralIdle, then only clear mBusy, reset mIsrCtx.mStreamComplete, mark
channels free via channel->setInUse(false) and clear mTransmittingChannels when
that ISR-driven condition is met (leave the rest of poll() behavior unchanged).
---
Duplicate comments:
In `@src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp.hpp`:
- Around line 376-378: Check the boolean/return result of
mPeripheral->registerTransmitCallback(reinterpret_cast<void *>(&isrChunkDone),
this) and if it fails abort the stream: call the same cleanup used when a stream
cannot start (clear setInUse on this stream), do not set mBusy, and make
transmit() immediately return false so the caller knows start failed; this
prevents starting the first chunk without an ISR and avoids leaving the stream
stuck for poll()/peripheralIdle. Ensure you reference registerTransmitCallback,
isrChunkDone, transmit(), mBusy, setInUse, and poll in the fix.
- Around line 66-72: The destructor
ChannelDriverLcdClockless::~ChannelDriverLcdClockless currently clears mBusy and
always calls freeRingBuffers() even if mPeripheral->waitTransmitDone(2000) times
out; change the flow so that you check the return/timeout result of
waitTransmitDone and only clear mBusy and call freeRingBuffers() when
waitTransmitDone succeeded, otherwise leave mBusy true and skip
freeRingBuffers() (or attempt a safe peripheral hard-reset via mPeripheral
before freeing); use the wait result to decide whether to freeRingBuffers() to
avoid the DMA reading freed memory.
- Around line 278-370: The peripheral reinit logic only checks mNumLanes so
changes in per-channel timing or pins are ignored, causing stale
mClockHz/mWave*Lut and config.data_gpios; update the reinit condition in the
init path (where needPeripheralInit is computed) to also consider a signature of
all channels' getPin() and getTiming() (or alternatively validate that all
channels share identical timing and fail early), and when the signature differs
force deinitialize()/initialize() and recompute canUseWave3(chipsetTiming),
mClockHz, mWave3Lut/mWave8Lut, and populate config.data_gpios[] from each
channels[i]->getPin(); ensure mNumLanes/mInitialized are updated as before after
successful init.
In `@src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.h`:
- Around line 112-145: The ISR/task shared flags and counters
(IsrContext::mStreamComplete, mNextByteOffset, mRingWriteIdx and the member
mBusy) are declared volatile but need atomicity and ordering for safe handoff
between isrChunkDone and task methods (show, poll, destructor); replace these
volatile fields with fl::atomic<T> (e.g. fl::atomic<bool> for
mStreamComplete/mBusy and fl::atomic<size_t> for offsets) and use appropriate
memory_order (release in ISR updates, acquire in task reads) or alternatively
protect all accesses in isrChunkDone and task paths with
portENTER_CRITICAL_ISR/portEXIT_CRITICAL_ISR and
portENTER_CRITICAL/portEXIT_CRITICAL critical sections to eliminate races.
Ensure all compound updates (like ctx.mNextByteOffset += chunkBytes) are done
using atomic fetch_add or inside the same critical section so isr and task views
are consistent.
---
Nitpick comments:
In `@src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp.hpp`:
- Around line 419-466: The local class EspWrapper inside
createLcdClocklessEngine should be hoisted into a shared bridge type (e.g.
LcdSpiPeripheralEspBridge) implemented once (wrapping
detail::LcdSpiPeripheralEsp::instance()) and placed at namespace scope so both
createLcdClocklessEngine and the ChannelDriverLcdSpi factory can reuse it;
replace the local EspWrapper with fl::make_shared<LcdSpiPeripheralEspBridge>()
when constructing ChannelDriverLcdClockless (and update the other factory to use
the same bridge), keeping the same overridden methods (initialize, deinitialize,
allocateBuffer, transmit, registerTransmitCallback, getConfig, getMicroseconds,
delay, etc.) and preserving FL_NOEXCEPT and return types.
🪄 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: defaults
Review profile: CHILL
Plan: Pro
Run ID: 92ef3bd4-6d50-4988-952b-f759089b0e51
📒 Files selected for processing (9)
src/platforms/esp/32/drivers/channel_manager_esp32.cpp.hppsrc/platforms/esp/32/drivers/lcd_spi/_build.cpp.hppsrc/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp.hppsrc/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.hsrc/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_spi.cpp.hppsrc/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_spi.hsrc/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_mock.cpp.hpptests/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpptests/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_spi.cpp
✅ Files skipped from review due to trivial changes (2)
- src/platforms/esp/32/drivers/lcd_spi/_build.cpp.hpp
- tests/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_spi.cpp
🚧 Files skipped from review as they are similar to previous changes (5)
- src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_mock.cpp.hpp
- tests/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp
- src/platforms/esp/32/drivers/channel_manager_esp32.cpp.hpp
- src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_spi.h
- src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_spi.cpp.hpp
📊 Header Compilation PerformanceTotal Time: 1005.40ms Top 5 Slowest Headers
Warnings
Full Report |
…t retry When RPC ping fails (device already booted, no serial output), the tool now attempts a DTR reset to reboot the device and retries. This fixes the common case where the device is idle and not producing output. Error messages now distinguish between: - RPC communication failure (not a jumper wire issue) - Wrong pin pair (suggest --auto-discover-pins) - No jumper wire connected - Driver/DMA failure (0 edges captured despite electrical connection) This helps AI agents correctly diagnose issues instead of always defaulting to "connect a jumper wire". Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
📊 Header Compilation PerformanceTotal Time: 947.91ms Top 5 Slowest Headers
Warnings
Full Report |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (1)
ci/autoresearch/gpio.py (1)
62-105: Consider extracting the DTR-reset helper — it is duplicated verbatim.The DTR-reset + reconnect sequence at lines 62–90 is ~30 lines and is duplicated in
run_pin_discoveryat lines 252–281 with only atimeout=30.0difference on the retryping. Extracting something likeasync def _dtr_reset_and_reconnect(port, serial_interface, timeout, ping_timeout=None) -> RpcClientwould deduplicate and make the (currently inconsistent)client = Nonehandling uniform across both call sites.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@ci/autoresearch/gpio.py` around lines 62 - 105, Extract the duplicated DTR-reset + reconnect block into an async helper named _dtr_reset_and_reconnect(port, serial_interface, timeout, ping_retries=3, ping_wait=3.0) that performs the serial DTR toggle, reopens RpcClient, calls connect(boot_wait=ping_wait, drain_boot=True), sends a "ping" with the given retries, and returns the connected RpcClient (or raises the caught exception); update both call sites (the current code using client, and run_pin_discovery) to call this helper, pass ping_retries/ ping_wait to preserve the different retry behavior (e.g., ping_timeout/timeout difference), ensure KeyboardInterrupt is still handled by delegating to handle_keyboard_interrupt before re-raising, and make sure client variable handling is consistent (assign returned RpcClient to client or return False on handled failures as existing logic expects).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@ci/autoresearch/gpio.py`:
- Around line 64-105: The DTR-reset block calls await client.close() then later
reassigns client to a new RpcClient, but doesn't set client = None after closing
— so if an exception occurs before the reassignment the outer finally will
double-close the already-closed RpcClient; to fix, after calling await
client.close() in the DTR-reset branch (the block that creates pyserial and
constructs RpcClient), set client = None immediately, then only reassign client
when you successfully create the new RpcClient and connect (the RpcClient(...) +
await client.connect(...) sequence); follow the same pattern used in
run_pin_discovery (set client = None after close) so the outer finally can
safely skip closing when client is None.
- Around line 62-105: Hoist the missing imports (import serial as pyserial and
import asyncio) to the top of the module with the other third-party imports,
then wrap the pyserial.Serial(...) usage in the DTR-reset block in a try/finally
that ensures the serial handle (s) is closed even if await asyncio.sleep or
other awaits raise; update the except block where RpcClient is recreated and
handle_keyboard_interrupt is used to reference the same s variable scope and
ensure s.close() runs in the finally before any return or re-raise.
- Around line 68-75: The current DTR-only pulse using s = pyserial.Serial(...),
s.dtr and awaits does not reliably reset ESP32-S3; update the sequence to mirror
esptool: start with s.rts=False, s.dtr=False (idle), then s.dtr=True (GPIO0 low)
while s.rts stays False, then pulse s.rts=True (EN low) briefly, then
s.rts=False (release EN so GPIO0 state is sampled), and finally s.dtr=False; use
the existing asyncio.sleep timing around each transition and s.close() as
before; if the goal was only USB-CDC re-enumeration rather than hardware reset,
instead leave DTR-only logic but change the "DTR reset" log messages to clarify
re-enumeration intent.
In `@ci/autoresearch/phases.py`:
- Around line 1011-1016: The diagnostic prints can show "TX=None, RX=None"
because ctx.effective_tx_pin and ctx.effective_rx_pin are int | None; change the
prints to use the same fallback as run_gpio_pretest by computing tested_tx =
ctx.effective_tx_pin or PIN_TX and tested_rx = ctx.effective_rx_pin or PIN_RX
(or similar) once before the diagnostic block, then use tested_tx/tested_rx in
the f-strings for the lines referencing tested pins; update both the "tested
TX=…" message and the "between GPIO … and GPIO …" line to use those variables
instead of ctx.effective_tx_pin/ctx.effective_rx_pin.
---
Nitpick comments:
In `@ci/autoresearch/gpio.py`:
- Around line 62-105: Extract the duplicated DTR-reset + reconnect block into an
async helper named _dtr_reset_and_reconnect(port, serial_interface, timeout,
ping_retries=3, ping_wait=3.0) that performs the serial DTR toggle, reopens
RpcClient, calls connect(boot_wait=ping_wait, drain_boot=True), sends a "ping"
with the given retries, and returns the connected RpcClient (or raises the
caught exception); update both call sites (the current code using client, and
run_pin_discovery) to call this helper, pass ping_retries/ ping_wait to preserve
the different retry behavior (e.g., ping_timeout/timeout difference), ensure
KeyboardInterrupt is still handled by delegating to handle_keyboard_interrupt
before re-raising, and make sure client variable handling is consistent (assign
returned RpcClient to client or return False on handled failures as existing
logic expects).
🪄 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: defaults
Review profile: CHILL
Plan: Pro
Run ID: 87be055c-7390-457c-bb21-b68bed2c19ea
📒 Files selected for processing (2)
ci/autoresearch/gpio.pyci/autoresearch/phases.py
…w pyserial workaround - Add reset_device(board) to SerialInterface protocol - FbuildSerialAdapter delegates to fbuild 2.1.15's SerialMonitor.reset_device() - PySerialAdapter uses direct DTR toggle as fallback - gpio.py now uses serial_interface.reset_device() instead of raw pyserial - FbuildSerialAdapter falls back to pyserial for older fbuild versions Closes #2264 Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
📊 Header Compilation PerformanceTotal Time: 1012.59ms Top 5 Slowest Headers
Warnings
Full Report |
There was a problem hiding this comment.
Actionable comments posted: 6
♻️ Duplicate comments (1)
ci/autoresearch/gpio.py (1)
62-115:⚠️ Potential issue | 🟡 MinorKnown issues from prior review still present in the fallback branch.
The previously-flagged concerns on this block still apply to the fallback path (
serial_interface is None):
import serial as pyserial(Line 73) andimport asyncio(Lines 77 and 83) are inside the handler. As per coding guidelines, "All system imports must be at the top of the file in proper order: standard library, third-party, local."- The pyserial handle
s(Lines 75–81) is not wrapped intry/finally; a cancellation or error duringawait asyncio.sleep(0.1)leaks the port.clientis not set toNoneafterawait client.close()on Line 65. Unlikerun_pin_discovery(Line 267), this function does not clearclientafter closing it. If any statement at Lines 68–86 raises before the newRpcClientis fully constructed on Line 87, the outerfinallyat Line 173 callsawait client.close()on the already-closed client. This is inconsistent withrun_pin_discoveryand a latent foot-gun ifRpcClient.close()ever becomes non-idempotent.♻️ Proposed fix (client = None in run_gpio_pretest only)
except Exception as e: # Try DTR reset and retry — device may be booted but idle print(f"\u26a0\ufe0f Ping failed ({e}), attempting DTR reset...") try: await client.close() + client = None # type: ignore[assignment] # Use SerialInterface.reset_device() if available if serial_interface is not None:And in the outer
finallyat Line 172–173:finally: - await client.close() + if client is not None: + await client.close()🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@ci/autoresearch/gpio.py` around lines 62 - 115, In the fallback branch of the DTR-reset handler inside run_gpio_pretest (the block that executes when serial_interface is None) fix three issues: move the local imports (import serial as pyserial and import asyncio) to the top-level imports; wrap the pyserial.Serial(...) usage (variable s) in a try/finally so s.close() always runs even if await asyncio.sleep(0.1) is cancelled or raises; and after await client.close() set client = None (like run_pin_discovery does) so the outer finally won't attempt to close the already-closed RpcClient instance; keep existing calls to SerialInterface.reset_device() and RpcClient(...) unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@ci/autoresearch/gpio.py`:
- Around line 137-169: The diagnosis branch uses integer comparisons against
rx_low and rx_high (rx_low == 1 / rx_high == 0) but the firmware returns the
strings "LOW"/"HIGH"; update the conditions to compare those string values
(e.g., if rx_low == "HIGH" and rx_high == "HIGH": for stuck HIGH, and if rx_low
== "LOW" and rx_high == "LOW": for stuck LOW) and keep the existing diagnostic
messages that reference rx_pin and tx_pin (rx_low, rx_high, rx_pin, tx_pin).
In `@ci/tests/test_serial_interface_reset.py`:
- Around line 1-30: Move these three small checks into the existing
serial_interface test module and replace weak presence checks with stronger
signature/behavior assertions: import inspect and assert that SerialInterface,
FbuildSerialAdapter, and PySerialAdapter each expose a callable reset_device
(use callable(...) or inspect.iscoroutinefunction(...) if it should be async),
then use inspect.signature(reset_device) to assert it accepts a parameter named
"board" and (if your APIs annotate return types) that the return annotation is
bool; alternatively add a small behavioral test that calls reset_device on a
test adapter with a mocked board and asserts a boolean result. Ensure you update
the existing serial_interface test file rather than creating this new test file
and reference the classes SerialInterface, FbuildSerialAdapter, PySerialAdapter
and the method reset_device when editing.
In `@ci/util/serial_interface.py`:
- Around line 203-223: The reset_device method currently catches AttributeError
broadly and uses a leaky pyserial fallback; change it to first check for the
presence of reset_device via reset_fn = getattr(self._monitor, "reset_device",
None) and only call _run_in_thread(reset_fn, board) if reset_fn is not None,
wrapping that call to re-raise KeyboardInterrupt and return False on other
exceptions; if reset_fn is None, perform the pyserial fallback but move the
import out (or at least avoid importing inside the try), ensure the Serial
handle (pyserial.Serial(...)) is closed in a finally block, catch and re-raise
KeyboardInterrupt separately, and only catch other exceptions to return False so
unrelated AttributeError from within reset_device is not mistaken for a missing
method.
- Line 53: The method signature for reset_device and the two adapter
implementations currently use a default parameter value (board: str | None =
None); remove the default so the parameter is non-defaulted (e.g., board: str |
None) and keep the explicit type annotation, then update all callers to pass the
board argument explicitly (pass None when unknown). Locate and change the
reset_device definition and the two adapter method definitions that mirror it
(the adapter implementations referenced in the review) to the non-defaulted
signature and run tests to ensure callers were updated to supply the argument.
- Around line 98-111: The reset_device fallback in reset_device (and
FbuildSerialAdapter.reset_device) must hoist the third-party import (serial as
pyserial) to the module top, handle KeyboardInterrupt/asyncio.CancelledError
before a broad Exception, ensure the Serial instance is always closed by
wrapping usage of s in try/finally, and avoid silently swallowing errors: on
unexpected exceptions log the full exception (exc_info) and re-raise or let
non-recoverable errors propagate while only returning False for defined
reset-failure conditions; update the async awaits to properly propagate
CancelledError so the finally block still closes s.
- Around line 54-63: The Protocol.reset docstring and the two adapter
implementations are inconsistent and lack the proper RTS/DTR sequence required
for ESP32-S3; update Protocol.reset to accurately describe both behaviors
(generic DTR-only fallback and a platform-specific RTS/DTR sequence) and modify
PySerialAdapter.reset and FbuildSerialAdapter.reset to implement the correct
hardware reset sequence for ESP32-S3: assert RTS=True (hold EN low for reset),
toggle DTR as needed to drive GPIO0 (boot mode), then deassert RTS=False to
release EN so the chip actually resets and boots; use the existing board
parameter to choose the esp32s3 sequence vs. generic DTR toggle, and ensure you
use the adapters’ serial control methods (e.g., setRTS/setDTR or the equivalent
wrapper calls) and preserve existing timing/delays around the toggles.
---
Duplicate comments:
In `@ci/autoresearch/gpio.py`:
- Around line 62-115: In the fallback branch of the DTR-reset handler inside
run_gpio_pretest (the block that executes when serial_interface is None) fix
three issues: move the local imports (import serial as pyserial and import
asyncio) to the top-level imports; wrap the pyserial.Serial(...) usage (variable
s) in a try/finally so s.close() always runs even if await asyncio.sleep(0.1) is
cancelled or raises; and after await client.close() set client = None (like
run_pin_discovery does) so the outer finally won't attempt to close the
already-closed RpcClient instance; keep existing calls to
SerialInterface.reset_device() and RpcClient(...) unchanged.
🪄 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: 6011fa0d-7cf0-47e1-9239-69f13e4aa2d7
📒 Files selected for processing (3)
ci/autoresearch/gpio.pyci/tests/test_serial_interface_reset.pyci/util/serial_interface.py
- Move pyserial import to top of serial_interface.py - Extract _pyserial_dtr_reset() helper using proper ClassicReset sequence (DTR/RTS toggling matching esptool's default-reset) - Remove default parameter values from reset_device (board: str | None) - Use hasattr() check instead of broad except AttributeError - Set client = None after close to prevent double-close in finally - Fix None pin display in abort message (fall back to PIN_TX/PIN_RX) - Remove inline imports from gpio.py DTR reset blocks Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
📊 Header Compilation PerformanceTotal Time: 1201.29ms Top 5 Slowest Headers
Warnings
Full Report |
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
ci/autoresearch/gpio.py (1)
77-77:⚠️ Potential issue | 🔴 CriticalCritical:
asynciois not imported — both reset-retry paths will crash withNameError.Lines 77 and 271 call
await asyncio.sleep(3.0), butasynciois not imported anywhere in this module (Ruff F821 confirms). The moment a ping fails and the DTR-reset recovery path is taken, Python will raiseNameError: name 'asyncio' is not defined, which is then caught by the outerexcept Exception as e2:and reported as "Ping failed after DTR reset" — masking the real bug and making the reset-retry logic completely non-functional.As per coding guidelines: "All system imports must be at the top of the file in proper order: standard library, third-party, local."
🐛 Proposed fix
from __future__ import annotations +import asyncio from dataclasses import dataclass from typing import TYPE_CHECKING🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@ci/autoresearch/gpio.py` at line 77, The module calls await asyncio.sleep(...) (seen in gpio.py around the retry logic for DTR reset) but never imports asyncio, causing a NameError during retry paths; fix by adding "import asyncio" to the top-level imports in gpio.py (under standard-library imports before third-party/local), so the functions that reference asyncio.sleep (the DTR-reset retry blocks where await asyncio.sleep(3.0) is used) will run correctly.ci/util/serial_interface.py (1)
221-225:⚠️ Potential issue | 🟠 MajorHandle
KeyboardInterruptfirst and avoid silent swallow.The
except Exception:on Line 224 catchesKeyboardInterrupt-adjacent cancellation patterns and silently returnsFalse, hiding the root cause of fbuild reset failures.As per coding guidelines: "All Python try-catch blocks must handle KeyboardInterrupt before other exceptions" and "Never use silent fallbacks for missing critical resources - always fail fast with descriptive errors".
♻️ Proposed fix
try: result = await self._run_in_thread(self._monitor.reset_device, board) return bool(result) + except KeyboardInterrupt: + raise except Exception as exc: + warnings.warn( + f"FbuildSerialAdapter.reset_device failed: {exc}", stacklevel=2 + ) return False🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@ci/util/serial_interface.py` around lines 221 - 225, The try/except currently swallows all exceptions (including KeyboardInterrupt) and returns False; change it to handle KeyboardInterrupt first by catching KeyboardInterrupt and re-raising it, and then catch other Exceptions as e to either log a descriptive error and raise a new RuntimeError (or propagate e) instead of silently returning False; apply this around the call to self._run_in_thread(self._monitor.reset_device, board) so that KeyboardInterrupt isn't suppressed and other failures fail fast with a clear message.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@ci/autoresearch/gpio.py`:
- Around line 285-297: The except blocks that currently read "except Exception
as e2:" and print a generic diagnosis swallow useful error context; update both
the DTR-reset handler (the block that prints "Ping failed after DTR reset") and
the pretest branch exception handler to include the caught exception details and
traceback in the output (e.g., include the exception object e2 in the printed
message and log or print the full exception info/traceback via exc_info or
traceback.print_exc()), and avoid silently concealing unexpected errors—ensure
any client.close() remains awaited and then return the PinDiscoveryResult as
before after logging the detailed error information so root causes are visible
for debugging.
---
Duplicate comments:
In `@ci/autoresearch/gpio.py`:
- Line 77: The module calls await asyncio.sleep(...) (seen in gpio.py around the
retry logic for DTR reset) but never imports asyncio, causing a NameError during
retry paths; fix by adding "import asyncio" to the top-level imports in gpio.py
(under standard-library imports before third-party/local), so the functions that
reference asyncio.sleep (the DTR-reset retry blocks where await
asyncio.sleep(3.0) is used) will run correctly.
In `@ci/util/serial_interface.py`:
- Around line 221-225: The try/except currently swallows all exceptions
(including KeyboardInterrupt) and returns False; change it to handle
KeyboardInterrupt first by catching KeyboardInterrupt and re-raising it, and
then catch other Exceptions as e to either log a descriptive error and raise a
new RuntimeError (or propagate e) instead of silently returning False; apply
this around the call to self._run_in_thread(self._monitor.reset_device, board)
so that KeyboardInterrupt isn't suppressed and other failures fail fast with a
clear message.
🪄 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: 9e479daa-935d-4460-b9e8-ba2f70a7733c
📒 Files selected for processing (3)
ci/autoresearch/gpio.pyci/autoresearch/phases.pyci/util/serial_interface.py
🚧 Files skipped from review as they are similar to previous changes (1)
- ci/autoresearch/phases.py
…priority - LCD_CLOCKLESS priority 1→2 to deterministically outrank legacy I2S - Don't free DMA ring buffers after timed-out shutdown wait (both clockless and SPI drivers) — prevents use-after-free while DMA active - Check registerTransmitCallback() return value, fail early if false - Fix poll() completion: require streamDone AND peripheralIdle (not OR) to prevent premature completion between DMA send and callback register - Add channels.size() > 16 bounds check with early return - Remove dead mDmaBytesPerChunk field from IsrContext - Add config change detection for peripheral reconfigure on timing/pin changes Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
📊 Header Compilation PerformanceTotal Time: 943.47ms Top 5 Slowest Headers
Warnings
Full Report |
…-spi Hardware bring-up for PR #2260 (LCD_CAM ISR-driven chunked DMA). Crash fix ChannelDriverLcdClockless defaulted dc_gpio=22 and clock_gpio=21. GPIO 22 does not exist on common ESP32-S3 packages, so esp_lcd_new_i80_bus -> lcd_i80_bus_configure_gpio -> gpio_func_sel hit an error-log path that detected heap poisoning and triggered a Guru Meditation panic. Changed both defaults to GPIO 0 (same convention as the legacy I2S LCD_CAM driver this replaces). autoresearch CLI --lcd now maps to LCD_CLOCKLESS (was the legacy I2S name). Added --lcd-spi mapping to LCD_SPI (APA102/SK9822 via LCD_CAM I80). Both auto-select the esp32s3 environment and are included in --all. autoresearch RX decoder AutoResearchTest.cpp recognises LCD_CLOCKLESS and reconstructs the RX timing for wave3 or wave8 encoding using the same fl::canUseWave3() eligibility check the firmware uses at runtime. GPIO pre-test timing Bumped RpcClient boot_wait from 3s to 8s and enabled drain_boot in gpio.py. The ESP32-S3 AutoResearch setup() takes ~5-7s before the RPC dispatcher is ready, so the old 3s wait raced the first ping against setup and produced intermittent GPIO PRE-TEST timeouts. Hardware verification (ESP32-S3 @ COM13, jumper GPIO 1 -> GPIO 2) LCD_SPI: 4/4 patterns pass (passed:true) LCD_CLOCKLESS: 4/4 patterns pass (passed:true, after GPIO fix) Host unit tests: 299/299 pass. Lint clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…-spi Hardware bring-up for PR #2260 (LCD_CAM ISR-driven chunked DMA). Crash fix ChannelDriverLcdClockless defaulted dc_gpio=22 and clock_gpio=21. GPIO 22 does not exist on common ESP32-S3 packages, so esp_lcd_new_i80_bus -> lcd_i80_bus_configure_gpio -> gpio_func_sel hit an error-log path that detected heap poisoning and triggered a Guru Meditation panic. Changed both defaults to GPIO 0 (same convention as the legacy I2S LCD_CAM driver this replaces). autoresearch CLI --lcd now maps to LCD_CLOCKLESS (was the legacy I2S name). Added --lcd-spi mapping to LCD_SPI (APA102/SK9822 via LCD_CAM I80). Both auto-select the esp32s3 environment and are included in --all. autoresearch RX decoder AutoResearchTest.cpp recognises LCD_CLOCKLESS and reconstructs the RX timing for wave3 or wave8 encoding using the same fl::canUseWave3() eligibility check the firmware uses at runtime. GPIO pre-test timing Bumped RpcClient boot_wait from 3s to 8s and enabled drain_boot in gpio.py. The ESP32-S3 AutoResearch setup() takes ~5-7s before the RPC dispatcher is ready, so the old 3s wait raced the first ping against setup and produced intermittent GPIO PRE-TEST timeouts. Hardware verification (ESP32-S3 @ COM13, jumper GPIO 1 -> GPIO 2) LCD_SPI: 4/4 patterns pass (passed:true) LCD_CLOCKLESS: 4/4 patterns pass (passed:true, after GPIO fix) Host unit tests: 299/299 pass. Lint clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…d-spi (#2273) * fix(esp32-s3): LCD_CLOCKLESS GPIO defaults + autoresearch --lcd/--lcd-spi Hardware bring-up for PR #2260 (LCD_CAM ISR-driven chunked DMA). Crash fix ChannelDriverLcdClockless defaulted dc_gpio=22 and clock_gpio=21. GPIO 22 does not exist on common ESP32-S3 packages, so esp_lcd_new_i80_bus -> lcd_i80_bus_configure_gpio -> gpio_func_sel hit an error-log path that detected heap poisoning and triggered a Guru Meditation panic. Changed both defaults to GPIO 0 (same convention as the legacy I2S LCD_CAM driver this replaces). autoresearch CLI --lcd now maps to LCD_CLOCKLESS (was the legacy I2S name). Added --lcd-spi mapping to LCD_SPI (APA102/SK9822 via LCD_CAM I80). Both auto-select the esp32s3 environment and are included in --all. autoresearch RX decoder AutoResearchTest.cpp recognises LCD_CLOCKLESS and reconstructs the RX timing for wave3 or wave8 encoding using the same fl::canUseWave3() eligibility check the firmware uses at runtime. GPIO pre-test timing Bumped RpcClient boot_wait from 3s to 8s and enabled drain_boot in gpio.py. The ESP32-S3 AutoResearch setup() takes ~5-7s before the RPC dispatcher is ready, so the old 3s wait raced the first ping against setup and produced intermittent GPIO PRE-TEST timeouts. Hardware verification (ESP32-S3 @ COM13, jumper GPIO 1 -> GPIO 2) LCD_SPI: 4/4 patterns pass (passed:true) LCD_CLOCKLESS: 4/4 patterns pass (passed:true, after GPIO fix) Host unit tests: 299/299 pass. Lint clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * chore: ignore autoresearch + claude transient files .autoresearch_last.log is rewritten by every autoresearch run and .claude/scheduled_tasks.lock is a lockfile managed by Claude Code's background-task system. Neither should be tracked. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(esp32-s3): always free ring buffers in LCD driver dtors (LSan fix) Both ChannelDriverLcdClockless and ChannelDriverLcdSpi destructors had an "intentional leak" branch that skipped freeRingBuffers() whenever waitTransmitDone() returned false, on the theory that DMA might still be reading the buffers. In the unit-test mocks (LcdSpiPeripheralMock), waitTransmitDone() returns false immediately whenever mPendingTransmits > 0 — so any test that does not explicitly drain via simulateTransmitComplete() hits the leak path, and LeakSanitizer (active in CI --debug runs) rejects the test. A 2 s stall on real hardware already indicates the DMA is lost; the leak-to-be-safe strategy never actually helps production code and it strictly breaks tests. Free unconditionally and log a warning instead. Both failing CI jobs pass locally: bash test channel_driver_lcd_clockless --debug --clean PASS bash test channel_driver_lcd_spi --debug PASS Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Changes
SPI driver (
ChannelDriverLcdSpi):isrChunkDone) transposes next chunk on DMA completionClockless driver (
ChannelDriverLcdClockless):canUseWave3()wave3Transpose_16/wave8Transpose_16for ISR-safe encodingMock (
LcdSpiPeripheralMock):simulateTransmitComplete()now drains entire ISR callback chain in one callChannel manager:
addLcdClocklessIfPossible()registered for ESP32-S3FASTLED_ESP32_FORCE_LCD_CLOCKLESSforce macro availableTest plan
Closes #2258
Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes
Tests