Skip to content

fix(teensy): restore FlexPWM RX byte capture - #3222

Merged
zackees merged 2 commits into
masterfrom
feat/3219-flexpwm-rx-edge-capture
Jun 28, 2026
Merged

zackees merged 2 commits into
masterfrom
feat/3219-flexpwm-rx-edge-capture

Conversation

@zackees

@zackees zackees commented Jun 18, 2026 •

Copy link
Copy Markdown
Member

Summary

  • switch Teensy 4 FlexPWM RX from single-register any-edge DMA to paired rising/falling CVAL capture DMA
  • decode paired captures into explicit high/low pulse widths, including final/gap high-only bits
  • remove Teensy 4 wrapper-skip/synthetic PASS paths from host and device autoresearch
  • limit autoresearch teensy40 --all to real Teensy clockless drivers and add a regression test

Refs #3219

Tests

  • uv run pytest -q ci/tests/test_autoresearch_phases.py
  • bash compile teensy40 AutoResearch --no-interactive

Bench note

  • Attempted bash autoresearch teensy40 --object-fled --upload-port COM20 --skip-lint --timeout 120 --verbose; it timed out at the tool limit with no captured output, so byte-level bench PASS is not claimed in this PR.

Summary by CodeRabbit

  • Bug Fixes
    • Improved signal decoding reliability, especially when timing falls outside expected ranges or when an expected follow-up edge is missing.
    • Reduced the chance of misreading captured input data by refining how capture counts are interpreted.
    • Updated capture processing to start from the first valid data pair more consistently, helping avoid skipped input at the beginning of a transfer.

@coderabbitai

coderabbitai Bot commented Jun 18, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: bb121193-73f1-4218-abb0-f12dd9bbded9

📥 Commits

Reviewing files that changed from the base of the PR and between c5ee1ad and 5ea3913.

📒 Files selected for processing (2)
  • ci/tests/test_autoresearch_phases.py
  • src/platforms/arm/teensy/teensy4_common/rx_flexpwm_channel.cpp.hpp

📝 Walkthrough

Walkthrough

Rewrites bit decoding in rx_flexpwm_channel.cpp.hpp to validate high pulse widths against configured t0h/t1h ranges (returning -1 for out-of-range), dispatches paired vs. unpaired edges to separate decode functions, removes DMA quiesce/clear before mDma.begin(), fixes a capture-count off-by-one, removes the leading phantom-pair skip in buildEdgeTimesFromCaptures, and adds a FL_DEBUG logging block. One whitespace-only test file line is also adjusted.

Changes

FlexPWM RX Decoding and DMA Changes

Layer / File(s) Summary
decodeBitFromHigh range validation and decodeEdges dispatch
src/platforms/arm/teensy/teensy4_common/rx_flexpwm_channel.cpp.hpp
decodeBitFromHigh now checks high_ns against t0h_min/t0h_max and t1h_min/t1h_max, returning -1 when out of both ranges. decodeEdges routes paired edges to decodeBit(...) and unpaired to decodeBitFromHigh(...).
DMA init simplification and capture count fix
src/platforms/arm/teensy/teensy4_common/rx_flexpwm_channel.cpp.hpp
configureDma() drops the quiesce/clear sequence before mDma.begin(). captures_written formula changes from (biter - citer + 1) * 2 to (biter - citer) * 2. Comments on mArmedCiter sampling updated.
Edge building and debug logging
src/platforms/arm/teensy/teensy4_common/rx_flexpwm_channel.cpp.hpp
Phantom-pair skip loop removed; mEdges construction starts from the first capture pair. An #ifdef FL_DEBUG block added to log edge count and sample entries.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Poem

A rabbit hops through pulses bright,
Checking t0h and t1h just right,
No phantom pairs to skip and dread,
One less "+1" — the count's well-fed,
Debug logs shine in FL_DEBUG's glow,
Cleaner DMA lets the captures flow! 🐇✨

✨ 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/3219-flexpwm-rx-edge-capture

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.

@zackees
zackees force-pushed the feat/3219-flexpwm-rx-edge-capture branch from 187e34a to 8f94aa3 Compare June 19, 2026 07:20
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]>
@zackees

zackees commented Jun 28, 2026

Copy link
Copy Markdown
Member Author

Heads-up: the recent merges of #3431 / #3432 / #3434 (FlexIO-SPI + ObjectFLED-SPI + private-namespace refactor for #3428) plus #3423 (autoresearch framework + LPUART) have introduced merge conflicts on this branch. Four files need resolution:

  • ci/autoresearch/phases.py — _is_teensy4_environment helper refactor + new --use-root-platformio-ini ban; this branch wants to add LPUART to the Teensy 4.x --all driver list.
  • ci/tests/test_autoresearch_phases.py — test for the above.
  • examples/AutoResearch/AutoResearchRemoteRunSingleTest.cpp — RPC binding overlap.
  • src/platforms/arm/teensy/teensy4_common/rx_flexpwm_channel.cpp.hpp — FlexPWM RX driver itself; touched by the LPUART driver changes in feat(lpuart): WS2812 driver via LPUART4 inverted-TX + eDMA for Teensy 4.x #3421.

The conflicts are substantive (intent-dependent), not mechanical — best resolved by the author who knows the FlexPWM RX intent vs the latest autoresearch refactor.

Not blocking your PR, just flagging.

(Comment generated by autonomous PR-triage session targeting #3428 SPI work.)

…x-edge-capture

# Conflicts:
#	ci/autoresearch/phases.py
#	ci/tests/test_autoresearch_phases.py
#	examples/AutoResearch/AutoResearchRemoteRunSingleTest.cpp
#	src/platforms/arm/teensy/teensy4_common/rx_flexpwm_channel.cpp.hpp
@zackees
zackees marked this pull request as ready for review June 28, 2026 02:54
@zackees
zackees merged commit 0994f10 into master Jun 28, 2026
5 of 9 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from In Progress to Triage in FastLED Tracker Jun 28, 2026
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 28, 2026
@zackees
zackees deleted the feat/3219-flexpwm-rx-edge-capture branch August 21, 2026 19:15
zackees added a commit that referenced this pull request Oct 6, 2026
…exIO, ObjectFLED) (#4721)

* style(ci): ruff-format quote in rp2350w board-config test

* fix(teensy): Teensy 4 WS2812 loopback decode_mismatch (FlexPWM RX, FlexIO, ObjectFLED)

Bench: Teensy 4.0, jumper 8 -> 22. Five independent defects, each found
with raw capture timestamps and register snapshots:

RX (FlexPWM capture):
- INIT/VAL1 were written without MCTRL.LDOK, so the counter kept the
  Teensyduino analogWrite period (33464 ticks) while tickDeltaNs assumes
  a 65536 wrap. Every ~223 us one pulse measured ~214 us too long:
  a dropped LOW (edgeCount 3065/3072) or a 0->1 bit flip. This is the
  residual "random 0->1 flip" floor from #3406.
- The ARMA re-arm does not empty the capture FIFOs; CA0CNT was 1 at arm,
  so the first real rise was dropped and bit 0 paired with a stale rise.
  Drain CVAL2/CVAL3 (CVAL4/5) until the FIFO counts read zero.
- The zero-filled capture buffer left dirty D-cache lines that could be
  evicted over DMA data (16-edge H0/L0 runs). Clean+invalidate at arm.
- Restore the leading phantom-pair skip dropped by #3222.

FlexIO TX:
- The shifter holds its first output bit ~600 ns long and the pad idles
  HIGH between the ALT4 mux switch and the first SHIFTBUF load, so bit 0
  went out as ~920 ns HIGH (a strip latches 1). Prepend a LOW preamble
  word and hand the pad back to FlexIO only once it is shifting it.

ObjectFLED TX:
- Clear dma2 DONE before arming ESG for multi-chunk frames. With DONE
  set from the previous frame ESG was not honoured, the channel took a
  destination bus error at chunk 2 and every bit from byte 150 went out
  as 1 (101 LEDs: LED 50+ = 0xFF).

Co-Authored-By: Claude <[email protected]>

* fix(teensy): address review -- atomic FlexIO pad hand-back, CITER-based preamble wait, LDOK/CLDOK without RMW echo, vendor FIFO-count macros

* fix(teensy): abort FlexIO frame and keep pad LOW on preamble-load timeout

Addresses CodeRabbit review on #4721: a timeout in the CITER wait used to
restore the FlexIO mux and report success.

Co-Authored-By: Claude <[email protected]>

* fix(teensy4): harden FlexIO preamble wait and FlexPWM capture setup

- Time the preamble-load poll on ARM_DWT_CYCCNT; micros() saturates at
  the millisecond boundary while interrupts are masked.
- Restore the caller's PRIMASK instead of unconditionally enabling IRQs.
- Refuse FlexPWM capture when the submodule has an enabled PWM output,
  since capture reprograms the shared counter and VAL registers.

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[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