Repository navigation
feat(autoresearch): ObjectFLED → FlexIO RX loopback + WS2812 decoder (Phase 3 of #2764) - #2769
Conversation
… (Phase 3 of #2764) End-to-end TX -> RX byte verification for the FlexIO RX backend landed in PRs #2765 / #2766 / #2767. Three pieces: 1. **WS2812 bit decoder wired into FlexIO RX** (`src/platforms/arm/teensy/teensy4_common/rx_flexio_channel.cpp.hpp`) - Phase 1B's `decode()` returned `success(0)` as a placeholder; this PR replaces the body with a real edge-pair decoder that walks the captured `EdgeTime` stream, classifies each (HIGH, LOW) duration pair as bit 0 or bit 1 via the `ChipsetTiming4Phase` thresholds, packs the bits into bytes MSB-first, and reports buffer-overflow / high-error-rate failures identically to the FlexPWM RX path. - Static helpers `decodeBitFlexIo` / `decodeEdgesFlexIo` live in the same TU rather than extracting to a shared header; the consolidation into `src/fl/channels/rx/decode_ws2812.h` is a separate refactor that can land after both backends are bench-validated against the same test matrix. 2. **`flexioObjectFledTest` RPC** (`examples/AutoResearch/AutoResearchRemote.cpp`) - Drives WS2812 frames through `Bus::OBJECT_FLED` on `tx_pin`, captures via `RxBackend::FLEXIO` on `rx_pin`, decodes against `TIMING_WS2812B_V5` 4-phase timing, and returns per-byte match counts. Teensy-4-only; other platforms return `PlatformNotSupported` cleanly. - Five fixed test patterns matching the parent-issue Phase 3 table: 0 = Red single LED, 1 = RGB three-LED chain, 2 = all zeros, 3 = all ones, 4 = 100-LED alternating R/G/B. - Args: `{ test_case, tx_pin, rx_pin, capture_ms }` (all optional). - Returns: `{ success, test_case, tx_pin, rx_pin, num_leds, expected_bytes, decoded_bytes, matched, mismatched, edges_captured }`. - Sizes the RX edge buffer from `num_leds * 24 * 2 + 25%`, clamped to the 16384-entry cap from PR #2767. - `help()` manifest updated (totalFunctions 26 -> 27) with full args/returns/description so any client relying on `help()` gets the up-to-date contract. 3. **Python harness** (`ci/autoresearch/test_flexio_rx_objectfled.py`) - Standalone pyserial driver, no fbuild daemon dependency. - Runs the five test cases in sequence, asserts on `decoded == expected && mismatched == 0`, prints PASS/FAIL per case. - Same `pyserial`-import-deferred-to-main() pattern from PR #2767 review. - Exits 0 on all pass, 1 on any failure. Compile-side fixups during bring-up (visible in commit diff): - `fl::ClearFlags::CHANNELS` -> `ClearFlags::CHANNELS` (global enum, not in `fl::`) - `NamedTimingConfig{resolved_timing, name, encoder}` wrapper around `makeTimingConfig<>()` for the TX path; `to_runtime_timing<>()` for the RX 4-phase converter - `fl::span<T>(container)` constructor instead of pointer-pair form (fixes the SpanFromPointerChecker hit on the decoder edge stream) Verification: - Host C++ tests pass (309/309) - C++ lint clean - Teensy 4.0 release build clean for `examples/AutoResearch` - Hardware-side end-to-end run is the next step — once the firmware is flashed to the dev-bench Teensy 4.0, the harness asserts each case in under 1 s Refs #2764 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughImplements an end-to-end ObjectFLED TX → FlexIO RX loopback: adds a FlexIO WS2812 edge-pair decoder, a firmware RPC ChangesObjectFLED TX → FlexIO RX Loopback Test
Sequence Diagram(s)sequenceDiagram
participant Host as Test Host (Python)
participant Firmware as Device Firmware (RPC)
participant ObjectFLED as ObjectFLED TX
participant FlexIoRx as FlexIO RX Capture
participant Decoder as WS2812 Decoder
Host->>Firmware: {"method":"flexioObjectFledTest","params":{test_case,tx_pin,rx_pin,capture_ms}}
Firmware->>ObjectFLED: configure OBJECT_FLED channel and write LED buffer
Firmware->>FlexIoRx: configure FLEXIO RX capture window on rx_pin
Firmware->>ObjectFLED: FastLED.show() (start TX)
ObjectFLED-->>FlexIoRx: WS2812 signal edges (wire)
FlexIoRx->>Decoder: captured edge-timings
Decoder-->>Firmware: decoded bytes, matched/mismatched counts, edges_captured
Firmware-->>Host: JSON result (id matched)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 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
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@ci/autoresearch/test_flexio_rx_objectfled.py`:
- Around line 143-146: The try/except that opens the serial port currently only
catches serial.SerialException; refactor it to first catch KeyboardInterrupt
(e.g., an except KeyboardInterrupt: re-raise or call sys.exit) before catching
serial.SerialException so an interrupt from the user is not swallowed; locate
the block that calls serial.Serial(args.port, args.baud, timeout=0.1) and ensure
you handle KeyboardInterrupt first, then handle serial.SerialException and print
the error to stderr as currently done.
- Around line 117-134: The main() function currently calls p.parse_args()
directly which prevents injecting test arguments; change main to accept an
optional parameter (e.g., argv: list[str] | None = None) and pass that into
p.parse_args(argv) so tests can supply arguments; update the signature for
main() and any internal callers/tests to pass a list when needed and keep
default behavior when argv is None, referencing main(),
argparse.ArgumentParser(), and p.parse_args().
- Around line 46-51: The TestCase dataclass lacks runtime type validation; add
the `@typechecked` decorator above the `@dataclass` declaration for TestCase and
ensure you import typechecked (e.g., from typeguard import typechecked) at the
top of the module; update any existing imports to include typechecked so
TestCase(index: int, label: str, expected_bytes: int) is validated at runtime.
- Around line 98-115: Create a small typed dataclass (e.g., EvalResult) with
fields success: bool and message: str and import dataclass from dataclasses,
then change the evaluate signature to return EvalResult instead of
tuple[bool,str]; inside evaluate (function name evaluate, param TestCase)
replace each tuple return with constructing and returning
EvalResult(success=..., message="...") using the same messages, and update any
callers/tests to expect EvalResult.success and EvalResult.message.
- Around line 62-68: The send_rpc function currently declares default parameter
values (args=None, request_id=1, timeout=15.0) which violates the repo rule that
Python function parameters must have explicit type annotations and no defaults;
remove the default values from the signature of send_rpc (parameters s, method,
args, request_id, timeout) so all parameters are required and keep their type
annotations, then update all callers/tests to pass explicit args, request_id,
and timeout values where they relied on the defaults (or add thin helper
wrappers in tests if needed).
In `@examples/AutoResearch/AutoResearchRemote.cpp`:
- Line 1994: The hard-coded metadata count response.set("totalFunctions",
static_cast<int64_t>(27)) is now incorrect after adding the flexioObjectFledTest
entry; update this to reflect the true count by either changing the literal to
28 or, better, compute it from the actual function list (e.g., use the
container.size() or vector holding the function entries) and assign that value
to response.set("totalFunctions", ...), ensuring the code that builds the help
payload (where response.set is called) stays consistent with the function
collection.
- Around line 1399-1401: The code currently calls FastLED.show() and then
immediately waits on rx_channel->wait((u32)capture_ms), but it may clear
channels or teardown while ObjectFLED TX is still draining; update the
send/teardown sequence so you explicitly wait for the LED TX to finish before
calling FastLED.clear(ClearFlags::CHANNELS) or tearing down channels: after
FastLED.show() (and before any FastLED.clear or rx_channel teardown) add a
TX-completion wait (e.g., use the library's TX-complete/blocking API or spin
until the driver reports idle) to ensure the LED transmission is fully drained;
apply the same change around the other occurrence near the FastLED/tx teardown
block (the block containing FastLED.show(), FastLED.clear(ClearFlags::CHANNELS),
and rx_channel teardown) so both places wait for TX completion before clearing
or closing the channel.
🪄 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: 30751cfd-6043-4557-86ff-4f02b590f230
📒 Files selected for processing (3)
ci/autoresearch/test_flexio_rx_objectfled.pyexamples/AutoResearch/AutoResearchRemote.cppsrc/platforms/arm/teensy/teensy4_common/rx_flexio_channel.cpp.hpp
Three fixes from the Phase 3 review:
1. **TX-completion margin** (CodeRabbit major):
`capture_ms` allows values down to 1 ms, but for case 4 (100 LEDs) the
WS2812 transmission alone takes ~3 ms (24 bits × 1.25 µs × 100 + reset).
If the caller passed a short capture_ms, `FastLED.clear(CHANNELS)` could
tear the channel down mid-frame and leave hardware in a bad state.
`flexioObjectFledTest` now computes a minimum capture window from the
actual WS2812 timing:
ws2812_tx_us = num_leds * 24 * 1.25 + 100 (reset gap)
min_capture_ms = ceil(ws2812_tx_us / 1000) + 10
…and uses `max(caller_capture_ms, min_capture_ms)` for the RX wait.
At 100 LEDs that's ~13 ms minimum; the caller can still request
larger windows for noisy environments.
2. **`totalFunctions` stale** (CodeRabbit minor):
The help() manifest had 28 functions.push_back() calls but
`totalFunctions` was still 27 (off-by-one — `wave8ExpandBenchmark_fn`
was added between Phase 2 and Phase 3 and I missed it). Bumped to 28
so clients relying on `help().totalFunctions` get an accurate count.
3. **Python `main()` testability + Ctrl-C handling**
(CodeRabbit refactor suggestions):
- `main()` now accepts an optional `argv: list[str] | None` parameter
so unit tests can inject argument lists without touching `sys.argv`.
`argparse.parse_args(argv)` interprets None as "use sys.argv[1:]" so
CLI behavior is unchanged.
- The serial-open `try/except` block now catches `KeyboardInterrupt`
before `SerialException`, so interactive users can Ctrl-C out of
the harness without dumping a stack trace.
The remaining CodeRabbit Python suggestions (add runtime type validation
to the dataclass, remove default values from send_rpc, return a dataclass
from evaluate() instead of a tuple) are intentionally not adopted — they
are pure-style refactors and the existing patterns match
test_flexio_rx_squarewave.py and ci/precheck_pins.py for consistency
across the autoresearch harness.
Verification:
- ✅ Teensy 4.0 release build clean
- ✅ C++ lint clean
Refs #2764, PR #2769 review
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
#2769 review) Two CodeRabbit-flagged repo coding-guideline conformances on the Phase 3 Python harness: 1. `@typechecked` on the `@dataclass TestCase` (per repo guideline "Use @TypeChecked decorator with @DataClass for runtime type validation"). 2. `evaluate()` now returns a typed `EvaluationResult` dataclass with `ok` and `message` fields, replacing the previous `(bool, str)` tuple (per repo guideline "Return dataclass structs instead of tuples or dicts for functions with multiple return values"). Callsite in `main()` updated to read `result.ok` / `result.message`. Both changes are pure-additive — same call shape, same RPC contract, same CLI behavior. Refs #2764, PR #2769 review Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…andler PR #2769 introduced a `try/except KeyboardInterrupt` block on the serial-open path of `test_flexio_rx_objectfled.py` that re-raised the signal directly. The project-wide KBI002 lint requires that KeyboardInterrupt handlers either call `_thread.interrupt_main()` or route through `handle_keyboard_interrupt(ki)` from `ci.util.global_interrupt_handler`. Importing the helper and calling it before the re-raise keeps the original abort-without-stack-trace UX while satisfying the lint check. The KBI002 violation was surfaced by the post-stop hook on the Phase 4 branch, which lints the master state pulled into the docs branch. Refs #2764, PR #2769 review Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
… 4 of #2764) (#2770) * docs(rx/flexio): FlexIO RX backend docs + enum-comment refresh (Phase 4 of #2764) Final phase of #2764 — documents the new FlexIO RX backend now that the skeleton (#2765), hardware (#2766), bench harness (#2767), and ObjectFLED loopback (#2769) have all landed on master. Three changes, all documentation-side; no runtime behaviour changes: 1. `src/fl/channels/rx/types.h`: - `RxBackend::PLATFORM_DEFAULT` comment now mentions FLEXIO as an opt-in alternative on Teensy 4 with a pointer to #2764. - `RxBackend::FLEXIO` comment notes that hardware verification ran via `flexioRxBenchmark` (1/10/100 kHz square wave) and `flexioObjectFledTest` (5-pattern ObjectFLED loopback). 2. `src/fl/channels/rx.h`: - Matching `RxDeviceType::PLATFORM_DEFAULT` comment refreshed. 3. `agents/docs/hardware-autoresearch.md`: - New top-level section "FlexIO RX Backend (Teensy 4 — opt-in)" covering: * How to select the backend in C++ and Python * Pin map (Teensy pin -> FLEXIO1 input -> IOMUXC offsets) * Peripheral resource budget (Shifter 0, Timer 0, DMA, FLEXIO1 functional clock) * Verification surface (flexioRxBenchmark + flexioObjectFledTest with acceptance criteria) * Explicit note that `PLATFORM_DEFAULT` stays on FlexPWM until the follow-up default-switch PR Intentionally NOT in this PR (per the #2764 parent-issue plan): - Switching `PLATFORM_DEFAULT` to FLEXIO on Teensy 4 — separate PR after both backends are equally exercised in the dev-bench matrix. - Adding `bash autoresearch teensy40 --rx-backend=flexio` to the nightly hardware test matrix — gated on the Teensy 4.1 RTV-silicone hardware issue (#2760) being resolved. Verification: - ✅ C++ lint clean - Docs-only changes; no host-test regressions possible Refs #2764 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(autoresearch): KBI002 — route KeyboardInterrupt through project handler PR #2769 introduced a `try/except KeyboardInterrupt` block on the serial-open path of `test_flexio_rx_objectfled.py` that re-raised the signal directly. The project-wide KBI002 lint requires that KeyboardInterrupt handlers either call `_thread.interrupt_main()` or route through `handle_keyboard_interrupt(ki)` from `ci.util.global_interrupt_handler`. Importing the helper and calling it before the re-raise keeps the original abort-without-stack-trace UX while satisfying the lint check. The KBI002 violation was surfaced by the post-stop hook on the Phase 4 branch, which lints the master state pulled into the docs branch. Refs #2764, PR #2769 review Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Phase 3 of #2764 — end-to-end TX → RX byte verification for the FlexIO RX backend that was landed by PRs #2765 (skeleton), #2766 (FLEXIO1 hardware programming), and #2767 (square-wave bench harness).
Three pieces, all directly mapping to the parent-issue checklist:
src/platforms/arm/teensy/teensy4_common/rx_flexio_channel.cpp.hppdecode()now actually decodes — Phase 1B'ssuccess(0)placeholder is replaced with a real WS2812 edge-pair → bit-stream → byte-stream pipeline that mirrors the existing FlexPWM RX driverexamples/AutoResearch/AutoResearchRemote.cppflexioObjectFledTestbinding (Teensy 4 only) that wires up an ObjectFLED TX channel + FlexIO RX channel for each of the five Phase 3 test patterns and returns per-byte match countsci/autoresearch/test_flexio_rx_objectfled.pydecoded == expected && mismatched == 0per caseflexioObjectFledTestRPCPipeline per test case:
CRGB leds_buf[100]is populated for the chosen patternRxChannel::create(RxBackend::FLEXIO)+begin()— edge buffer sized fromnum_leds × 24 × 2 + 25%, clamped to the 16 384 cap from PR feat(autoresearch): flexioRxBenchmark RPC + Python harness (Phase 2 of #2764) #2767FastLED.add(...)withBus::OBJECT_FLED+TIMING_WS2812B_V5(the same path AutoResearch uses for the regular driver harness)FastLED.show()— triggers the ObjectFLED DMArx_channel->wait(capture_ms)— blocks on the FlexIO RX DMA completionmake4PhaseTiming(to_runtime_timing<TIMING_WS2812B_V5>())builds the 4-phase decoder,decode()walks edges → bytesFastLED.clear(ClearFlags::CHANNELS)for the next testTest matrix (parent issue Phase 3 table)
[Red, Green, Blue]chain0xFFFFFF)Acceptance criteria per case:
decoded_bytes == expected_bytesANDmismatched == 0ANDsuccess == true. Bit-cell timing variance is implicit — if FlexIO timing were >10% off thedecodeBitFlexIothresholds wouldn't classify the bits and the decoder would either returnBUFFER_OVERFLOWor aHIGH_ERROR_RATEfailure result.Python harness
Same import-deferral pattern from PR #2767 —
pyserialis checked atmain()entry, not import, so test-collection on a CI runner without the dep doesn't abort.Compile-side adjustments noted during bring-up
Three Teensy-API mismatches that surfaced during compile (visible in the diff):
fl::ClearFlags::CHANNELS→ClearFlags::CHANNELS(global enum, not infl::)NamedTimingConfig{resolved_timing, name, encoder}wrapper aroundmakeTimingConfig<>()for the TX path;to_runtime_timing<>()for the RX 4-phase converterfl::span<T>(container)constructor instead of pointer-pair form (fixes theSpanFromPointerCheckerhit on the decoder edge stream)Verification
bash lint --cpp)examples/AutoResearchRefs
flexioRxBenchmark+ square-wave harness): feat(autoresearch): flexioRxBenchmark RPC + Python harness (Phase 2 of #2764) #2767 (merged)src/platforms/arm/teensy/teensy4_common/rx_flexpwm_channel.cpp.hpp(decodeEdges()at line 216)🤖 Generated with Claude Code
Summary by CodeRabbit