Skip to content

feat(flexpwm-rx): enable Phase 4 raw-capture dumps by default (#3066) - #3216

Merged
zackees merged 1 commit into
masterfrom
feat/3066-phase4-flexpwm-rx-diagnostics
Jun 18, 2026
Merged

zackees merged 1 commit into
masterfrom
feat/3066-phase4-flexpwm-rx-diagnostics

Conversation

@zackees

@zackees zackees commented Jun 18, 2026 •

Copy link
Copy Markdown
Member

Summary

Concrete step on Phase 4 of the #3066 ledger: the FlexPWM RX driver's FL_DEBUG-gated dumps have been written but never visible to bench operators because FL_DEBUG was never set on production builds. This change file-locally enables them by default — exactly what Phase 4 sub-task 2 asks for.

Why this matters

The iter-9 cross-check recommended pivoting from FlexIO RX (architecturally blocked per NXP docs) to FlexPWM RX (has dedicated input-capture silicon). FlexPWM RX captures non-zero data today; the open question is whether the bimodal pulse widths (940/640 ns HIGH, 286/586 ns LOW) come from a FIFO-watermark / merging bug or DMA dropping requests. Without visibility into mCaptureBuffer[0..7] and CITER/BITER deltas on a per-frame basis, nobody can answer that question on the bench.

Changes

  • src/platforms/arm/teensy/teensy4_common/rx_flexpwm_channel.cpp.hpp:
    • Top: #define FL_DEBUG 1 (guarded by #ifndef FL_DEBUG so upstream -DFL_DEBUG=1 users aren't affected).
    • Bottom: #undef FL_DEBUG (only if this file set it) so the macro doesn't leak into other TUs.
    • New FL_RX_FLEXPWM_QUIET escape hatch for users who want a silent FlexPWM RX.
    • Latent compile fix at line 516: mDma.TCD->DADDR is volatile void* and needed an explicit reinterpret_cast<uintptr_t>(const_cast<void*>(...)) — the error was hidden by FL_DEBUG being off.

Test plan

Related

  • #3066 Phase 4 sub-task 2 ("Enable #define FL_DEBUG in rx_flexpwm_channel.cpp.hpp and dump the raw u16 capture buffer values").
  • #3066 comment 4740201201 — iter-9 NXP cross-check recommending the FlexPWM-RX pivot.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Chores
    • Enhanced internal debugging capabilities for ARM Teensy 4 hardware PWM capture functionality.

#3066 Phase 4 sub-task 2 explicitly asks: 'Enable #define FL_DEBUG in
rx_flexpwm_channel.cpp.hpp and dump the raw u16 capture buffer values'.

The diagnostic dumps for FlexPWM RX have been gated behind #ifdef FL_DEBUG
since they were added — they're never visible to a bench operator unless
they manually rebuild with -DFL_DEBUG=1. That's been blocking iteration
on the Phase 4 bimodal-edge bug (940/640 ns HIGH, 286/586 ns LOW from an
OBJECT_FLED frame on the dev-bench Teensy 4).

This change enables them by default, file-locally:
- #define FL_DEBUG 1 at top of the .cpp.hpp (guarded by #ifndef so
  upstream -DFL_DEBUG users aren't affected).
- #undef at the bottom so FL_DEBUG doesn't leak into other TUs.
- New FL_RX_FLEXPWM_QUIET escape hatch for users who want silent FlexPWM RX.

Also fixes a latent compile error in the FL_DEBUG block at line 516 that
was hidden by FL_DEBUG being off by default — DMASetting::TCD->DADDR is
volatile void* and needs an explicit reinterpret_cast<uintptr_t>(const_cast).

Validated: bash compile teensy40 --examples AutoResearch succeeds (1m25s).
bash lint --cpp clean.

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

coderabbitai Bot commented Jun 18, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 18900fc3-65dd-45a2-9628-7c200045ce25

📥 Commits

Reviewing files that changed from the base of the PR and between 6bb90e1 and 99a1dc2.

📒 Files selected for processing (1)
  • src/platforms/arm/teensy/teensy4_common/rx_flexpwm_channel.cpp.hpp

📝 Walkthrough

Walkthrough

rx_flexpwm_channel.cpp.hpp gains a scoped FL_DEBUG macro: it is defined (with a guard macro FL_DEBUG_DEFINED_BY_RX_FLEXPWM) unless FL_RX_FLEXPWM_QUIET is already set, and both macros are undefined at the end of the file. Inside configureDma(), the DMA destination address log read is changed to use reinterpret_cast/const_cast from mDma.TCD->DADDR.

Changes

FlexPWM Debug Scoping and Cast Fix

Layer / File(s) Summary
Scoped FL_DEBUG macro and DADDR cast fix
src/platforms/arm/teensy/teensy4_common/rx_flexpwm_channel.cpp.hpp
Conditionally defines FL_DEBUG at file top with a guard macro unless FL_RX_FLEXPWM_QUIET is set; fixes dma_daddr in configureDma() to read mDma.TCD->DADDR via reinterpret_cast; undefines both macros at end-of-file to prevent leakage.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~5 minutes

Possibly related issues

Poem

🐇 A macro appears, then vanishes clean,
No debug flag left where it shouldn't be seen.
The DADDR cast right, the pointer reads true,
The FlexPWM rabbit debugs right on through!
Hop hop hooray for scoped macros today! 🎉

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: enabling raw-capture dumps by default in the FlexPWM RX driver via FL_DEBUG macro, and references the related issue #3066.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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/3066-phase4-flexpwm-rx-diagnostics

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 and usage tips.

@zackees
zackees merged commit fa3ef42 into master Jun 18, 2026
9 checks passed
@zackees
zackees deleted the feat/3066-phase4-flexpwm-rx-diagnostics branch June 18, 2026 11:28
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 18, 2026
zackees added a commit that referenced this pull request Jun 22, 2026
…chdog (closes #3219) (#3341)

* fix(teensy): restore FlexPWM RX byte capture

Refs #3219

* fix(teensy4/flexpwm-rx): wait() honest + skip leading phantom edge pair (#3219)

Two related fixes uncovered on a live Teensy 4.0 bench session after
PR #3222's dual-circuit capture refactor exposed the wrapper-skip
cheating. Both were masking real RX-decode failures as success.

1) `wait()` always returned `RxWaitResult::SUCCESS` even on timeout
   with zero captures. Caller (`capture()` in AutoResearchTest.cpp:428)
   trusts SUCCESS to mean "RX got data" and proceeds to decode the
   buffer -- which on a no-data timeout is stale or zero. Result was
   indistinguishable from real decode errors. Track CITER's initial
   value and return TIMEOUT when DMA never moved.

2) `buildEdgeTimesFromCaptures()` pushed the first HIGH edge
   unconditionally, then skipped only the subsequent gap LOW when
   `low_ns > 5000`. On Teensy 4.0 the IOMUXC pad-mux switch + DMA arm
   sometimes latches a phantom rising+falling pair whose HIGH duration
   looks like a real T0H (~226 ns) but is followed by a multi-us idle
   before the real frame starts. That leftover HIGH then shifted every
   downstream bit by one. Add a leading-phantom-skip pass that drops
   any pair whose trailing LOW is a reset/idle gap.

Bench result (100-LED OBJECT_FLED frame, MSB_LSB_A pattern A):
- Before: First decode error at LED[0], 86/100 LEDs corrupt
  Edge sequence starts: H226 H580 L640 H586 (double-HIGH at start)
- After:  First decode error at LED[35], 65/100 LEDs corrupt
  Edge sequence starts: H580 L640 H586 L640 (clean alternation)

LED[0]..LED[34] now decode correctly. Remaining mid-strip failures
have a different signature (LSB-only errors, occasional 1-byte
shifts) and are tracked separately under #3219 Phase 4 follow-up.

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

* feat(ci): blocker_alert + debug_object_fled_capture helpers (#3219 bench tooling)

Two small helpers used during the #3219 FlexPWM-RX bring-up session:

- `ci/util/blocker_alert.py` — bold-red ANSI banner + distinctive
  3-tone falling-rising chirp via `winsound.Beep` so the user notices
  when automation is blocked on a physical action (cable swap, power
  cycle). Falls back to POSIX terminal bell on non-Windows. Tones
  picked outside the Windows system-sound band (1175/440 Hz x2) so
  it doesn't get confused with Outlook/Slack notifications.

- `ci/autoresearch/debug_object_fled_capture.py` — direct pyserial
  monitor that bypasses the autoresearch wrapper's `RESULT:`-only
  serial filter. Sends `runSingleTest` to a flashed Teensy and dumps
  every line the device emits (FL_WARN, REMOTE:, RESULT:) for a
  configurable window. Used to inspect FlexPWM RAW captures and
  edge-time dumps that the wrapper otherwise swallows.

Both files include KBI001-compliant KeyboardInterrupt handlers.

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

* fix(teensy4/flexpwm-rx): midpoint bit classification eliminates cascading byte shifts (#3219)

Bench evidence on a live Teensy 4.0 (5-LED Pattern B):
- BEFORE: one bit lands at high=580ns -- in neither T0H_max nor T1H_min
  range, so decodeBit() returns -1, decoder `continue`s past it without
  pushing to current_byte, every subsequent bit shifts forward by one
  position. Result: 1 decoder error -> 5 of 5 LEDs corrupt with
  R: 0x55 -> 0xAB (left-shift-by-one signature) propagated through the
  whole strip.
- AFTER:  classify by midpoint between t0h_max and t1h_min. Marginal
  bits still get classified (might be wrong by one bit), but byte
  alignment is preserved and the error is contained to that bit's
  byte instead of poisoning the rest of the frame.

100-LED OBJECT_FLED frame, 4 patterns (MSB_LSB_A/B/C/D):
- BEFORE phantom-skip (the original wrapper-skip cheat removed):
  86/100, 87/100, 80/100, 64/100 LEDs corrupt.
- AFTER phantom-skip only (commit e3026d9):
  65/100, 79/100, 87/100, 79/100 LEDs corrupt -- LED 0..34 clean.
- AFTER midpoint classifier (this commit):
  1-8/100 LEDs corrupt across 4 patterns, decoder errors = 0.
  3 consecutive runs show non-deterministic per-LED errors, confirming
  the remaining failures are TX/RX clock-jitter at WS2812 timing
  tolerances -- not a software algorithm bug.

The LOW-time check in the original decoder added no robustness for
this protocol (both T0L and T1L overlap heavily at the FlexPWM-RX
sample resolution); HIGH-only classification is more skew-tolerant.

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

* fix(autoresearch): wrapper RPC response-miss race + post-ACK budget honesty (#3219)

Two wrapper-side cheat #5 fixes that together prevent the wrapper from
silently dropping the device's REMOTE response line and waiting 720 s
for a response that arrived in milliseconds.

ci/rpc_client.py::_wait_for_response:
  - Don't recurse into a fresh `_wait_for_response` on ACK -- that
    spawned a 2nd `read_lines()` producer behind the 1st in the
    single-worker `FbuildSerialAdapter._executor`. The 1st producer
    kept reading the serial port (including the final REMOTE response
    line) into a queue whose async consumer had already returned, and
    the 2nd producer never saw the line. Keep the SAME `async for`
    open and extend `current_deadline` on ACK instead.
  - Stop inflating `producer_budget = max(timeout, 600)`. The caller's
    `timeout` is the wall; the watchdog enforces the hard ceiling.

ci/util/serial_interface.py::FbuildSerialAdapter.read_lines:
  - Signal the producer thread to exit promptly when the async
    generator consumer breaks/returns. Without this, the producer
    kept running for its full `timeout` window after the consumer was
    done, leaving zombie producers in the single-worker executor that
    blocked the NEXT call's producer.

Together these eliminate the original 20-minute-wrapper-hang on a
~30 ms device-side test. Validated end-to-end against a Teensy 4.0
running OBJECT_FLED autoresearch: wrapper now reports the real
PASS/FAIL within seconds and the previously-invisible per-pattern
REMOTE messages flow through cleanly.

Closes the wrapper half of #3219. The daemon-side throughput cap is
fixed upstream in FastLED/fbuild#750.

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

* feat(autoresearch): deadline-epoch --timeout + daemon-thread watchdog (#3219)

Two coupled changes turning `--timeout N` into an honest hard wall:

ci/autoresearch/context.py:
  - Add `deadline_epoch` (set by `start_timeout_epoch()` right after
    deploy succeeds) and `remaining_seconds()` helper. Every
    downstream RPC call computes its per-call budget as
    `ctx.remaining_seconds(minimum=1.0)` so the user's `--timeout` is
    a TOTAL wall-clock budget, not a silently-multiplied per-call
    value. Pre-fix `--timeout 60` ran ~15 min wall-clock because
    `client.send(..., timeout=120.0)` was hardcoded at the call site
    and the wrapper's post-ACK extension added another 600 s on top.

ci/autoresearch/phases.py:
  - Stamp `ctx.deadline_epoch` post-flash, pre-connect. Replace the
    hardcoded `timeout=120.0` at the runSingleTest call site with
    `ctx.remaining_seconds(minimum=1.0)`. Print a one-line advisory
    so the user sees the deadline armed.
  - Spawn a daemon `threading.Thread` watchdog at deadline+20s
    (NOT an asyncio task -- a wedged event loop or starved
    single-worker executor cannot starve a real OS thread).
    On expiry: emit a red `blocker_alert` banner, dump stack traces
    across every live thread (top 4 frames each via
    `sys._current_frames()`), best-effort close the serial port from
    a side-thread with a 2 s join cap, then `os._exit(2)` to bypass
    any stuck asyncio teardown.
  - `extend_autoresearch_watchdog_deadline(ctx, N)` grants extra
    runway to known-slow cleanup phases without disarming the bomb.
    Used in the run finally-block (10 s extension covering
    `await client.close()`); the safety net stays armed in case
    cleanup itself wedges.

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

* chore(teensy4/flexpwm-rx): remove per-frame FL_WARN debug dumps (#3219)

PR #3216 enabled `[FlexPWM CFG] / DMA / RAW / EDGE / E / DECODE`
FL_WARN_F sites by default in this file to surface the bimodal-edge
symptom during the #3066 Phase 4 investigation. The dual-circuit
capture refactor + midpoint classifier fix in this PR series
eliminated the bug those dumps were diagnosing.

Now those 18 dump lines per frame are pure UART output volume:
  - on a 100-LED OBJECT_FLED autoresearch test they accounted for
    ~24 % of the device's per-pattern serial output;
  - the device's UART TX FIFO blocks once it fills, stalling the
    test between patterns;
  - even with the wrapper-side fix removing serial-bandwidth as the
    bottleneck, the device-side FL_WARN-induced TX backpressure
    remained measurable on bursty tests.

Removed:
  - `#ifndef FL_RX_FLEXPWM_QUIET` opt-in block at file top
    (+ matching trailing `#undef FL_DEBUG`).
  - All 6 `#ifdef FL_DEBUG` blocks inside
    `decodeEdges`, `configureFlexPwm`, `configureDma`, and
    `buildEdgeTimesFromCaptures` (8 dump-line WARN sites total).

If diagnostic dumps are needed again, gate them behind a new
`-DFL_RX_FLEXPWM_VERBOSE=1` compile flag rather than hardcoded
`#define FL_DEBUG 1` in this header (the latter caused header-pollution
problems for downstream files that also test `#ifdef FL_DEBUG`).

The two legitimate "Pin not supported on Teensy 4.x" FL_WARN_F sites
in `factory_create_flexpwm_rx_channel` are preserved.

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

* feat(ci): tiny pyserial bench helpers for autoresearch RPC debugging (#3219)

Two narrow scripts used during the #3219 bring-up session. Both bypass
the autoresearch wrapper's serial filter so you can see every line
the device emits in real time -- useful for diff'ing direct serial
behavior against the wrapper's stream.

- `ci/autoresearch/debug_find_pins.py` -- sends `ping` + `findConnectedPins`
  via direct pyserial and times the round-trip. Used to confirm
  device-side firmware was healthy when the wrapper was hanging.
- `ci/autoresearch/debug_object_fled_small.py` -- sends `runSingleTest`
  with a configurable lane size. Used to isolate buffer-position-
  dependent decode failures (5-LED passes proved the bug was in the
  shared-register FIFO race, not a per-bit timing issue).

Both keep their own KBI-001-compliant interrupt handlers and dump
raw bytes for forensic analysis. Companion to the earlier
`debug_object_fled_capture.py` helper.

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

* chore(deps): bump fbuild 2.2.28 -> 2.3.0 for daemon serial WS batching (#3219)

Pulls in FastLED/fbuild#750 (closes FastLED/fbuild#749) -- the daemon-
side fix for the serial WebSocket bridge that silently dropped lines
under sustained TX bursts. Pre-#750 the daemon sent one WS frame per
serial line, the broadcast channel lagged on ~320-line bursts (e.g.
4-pattern OBJECT_FLED autoresearch), and lines vanished via
RecvError::Lagged.

This is the upstream half of the FastLED #3219 fix. The wrapper-side
half landed in the prior commits on this branch (rpc_client.py,
serial_interface.py, autoresearch/{context,phases}.py).

Verified: `uv run fbuild --version` -> `fbuild 2.3.0`, lint stays green,
`bash autoresearch teensy40 --object-fled --strip-sizes 5` completes
end-to-end with 4/4 patterns through the wrapper.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
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.

1 participant