Skip to content

feat(autoresearch): flexioRxBenchmark RPC + Python harness (Phase 2 of #2764) - #2767

Merged
zackees merged 2 commits into
masterfrom
feat/flexio-rx-benchmark-rpc
Jun 5, 2026
Merged

zackees merged 2 commits into
masterfrom
feat/flexio-rx-benchmark-rpc

Conversation

@zackees

@zackees zackees commented Jun 5, 2026 •

Copy link
Copy Markdown
Member

Summary

Phase 2 of #2764 — the bench-validation surface for the FlexIO RX backend landed by PRs #2765 (skeleton) and #2766 (FLEXIO1 hardware programming).

Two parts, both lining up directly with the parent-issue checklist:

Side File What it does
Firmware (Teensy 4.x) examples/AutoResearch/AutoResearchRemote.cpp New flexioRxBenchmark JSON-RPC method that drives a square wave on the TX pin, captures via the new FlexIO RX, and returns timing statistics
Host (Python) ci/autoresearch/test_flexio_rx_squarewave.py Standalone pyserial driver that runs the three rates (1/10/100 kHz) and asserts σ + mean tolerances against the firmware

flexioRxBenchmark RPC

Teensy 4.x only — other platforms return PlatformNotSupported cleanly so cross-platform CI doesn't break.

// Request
{ "method": "flexioRxBenchmark",
  "params": [{
    "frequency_hz": 100000,   // default 1000
    "duration_ms":  100,      // default 100
    "tx_pin":       3,        // default 3 — matches GPIO 3↔4 jumper
    "rx_pin":       4         // default 4 — must be in kFlexIo1Pins[]
  }] }

// Response
{ "success":          true,
  "frequency_hz":     100000,
  "duration_ms":      100,
  "tx_pin":           3,
  "rx_pin":           4,
  "edges_captured":   20000,
  "periods":          10000,
  "period_mean_ns":   10005,
  "period_sigma_ns":  47,
  "period_min_ns":    9880,
  "period_max_ns":    10130 }

Pipeline (firmware side):

  1. analogWriteFrequency(tx_pin, frequency_hz) + analogWrite(tx_pin, 128) — Teensy core PWM at 50 % duty
  2. fl::RxChannel::create(RxChannelConfig{rx_pin, RxBackend::FLEXIO}) + begin() — wires the FLEXIO1 pipeline from feat(rx): FlexIO RX hardware programming (Phase 1B of #2764) #2766
  3. wait(duration_ms) — polls the DMA-completion flag
  4. analogWrite(tx_pin, 0) — quiet the line
  5. getRawEdgeTimes(...) → pair adjacent entries → period = high_segment_ns + low_segment_ns
  6. Compute count / mean / σ / min / max. Integer sqrt is used for σ — adequate for the tolerance ranges below.

Python harness — three cases mirroring the issue's Phase 2 table

$ uv run python ci/autoresearch/test_flexio_rx_squarewave.py --port COM20
Case Frequency Period Tolerance (σ) Tolerance (mean)
2.1 1 kHz 1 000 000 ns < 1 000 ns ±1 %
2.2 10 kHz 100 000 ns < 500 ns ±1 %
2.3 100 kHz 10 000 ns < 100 ns ±1 %

Exits 0 on all pass, 1 on any failure. Each case prints either PASS: periods=N, mean=X ns, sigma=Y ns, ... or FAIL: <reason> plus the raw firmware response for debugging.

The harness intentionally does NOT depend on fbuild's WebSocket daemon — uses raw pyserial with the same REMOTE:/RESULT: prefix-strip framing that worked for the precheck script earlier in #2764. Self-contained = one less thing to keep up.

Verification

  • ✅ Teensy 4.0 release build clean (examples/AutoResearch, ~1m 05s via fbuild)
  • ✅ Host C++ tests pass (309/309)
  • ✅ C++ lint clean (bash lint --cpp) — fixed SpanFromPointerChecker violation by switching to fl::span<T>(container) constructor
  • ⏳ Live bench-validation on the dev-bench Teensy 4.0 lands once the firmware is reflashed with this RPC — that's a separate hardware step held out of this PR to keep the diff focused on the software surface

Note on Phase 1B's decode() returning 0

The FlexIO RX impl in #2766 emits captured EdgeTime segments via getRawEdgeTimes() but currently returns 0 from decode() (the WS2812 4-phase byte decoder gets re-wired through the channel layer in a follow-up — see #2766 description). For this PR's purpose that's the right thing: flexioRxBenchmark operates on the raw edge stream from getRawEdgeTimes(), exactly the surface Phase 2 needs.

Refs

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added a device-accessible benchmark to generate a square wave and report period/timing statistics.
    • Increased capture capacity for edge/timing measurements to support longer or higher-resolution runs.
  • Tests
    • Added an automated bench test that validates recovered periods across multiple frequency cases with pass/fail reporting.
  • Documentation
    • Exposed the new benchmark in the device RPC help/schema.

…s (Phase 2 of #2764)

Adds the bench-validation surface for the FlexIO RX backend from PRs #2765
(skeleton) and #2766 (FLEXIO1 hardware programming).

Firmware side — new `flexioRxBenchmark` RPC binding in AutoResearchRemote.cpp
(Teensy 4.x only; other platforms return `PlatformNotSupported` cleanly):

  Args:
    { "frequency_hz": int = 1000,
      "duration_ms":  int = 100,
      "tx_pin":       int = 3,   // matches GPIO 3↔4 jumper
      "rx_pin":       int = 4 }

  Behavior:
    1. Drives tx_pin with a square wave via analogWriteFrequency() +
       analogWrite(pin, 128) (Teensy core PWM, 50% duty)
    2. Creates an RxChannel with backend = RxBackend::FLEXIO on rx_pin
    3. Captures for duration_ms
    4. Stops the PWM
    5. Pulls captured edges via getRawEdgeTimes() and pairs them into
       periods (period = high_segment_ns + low_segment_ns)
    6. Returns { edges_captured, periods, period_mean_ns, period_sigma_ns,
                 period_min_ns, period_max_ns }

  Integer sqrt is used for σ — adequate for the Phase 2 tolerance ranges
  (σ < 100 ns at 100 kHz).

Python harness side — `ci/autoresearch/test_flexio_rx_squarewave.py`:

  Standalone pyserial-based test driver (no fbuild WebSocket daemon
  needed). Runs three cases matching the parent-issue table:

    | Frequency | Period      | σ tolerance | Mean tolerance |
    |-----------|-------------|-------------|----------------|
    | 1   kHz   | 1 000 000ns | < 1 000 ns  | ±1 %           |
    | 10  kHz   |   100 000ns | <   500 ns  | ±1 %           |
    | 100 kHz   |    10 000ns | <   100 ns  | ±1 %           |

  Exits 0 on all pass, 1 on any failure. Default port COM20 + tx/rx
  pins 3/4 match the dev-bench Teensy 4.0 setup.

Verification:
- ✅ Teensy 4.0 release build clean (`examples/AutoResearch`, ~1m 05s)
- ✅ Host C++ tests pass (309/309)
- ✅ C++ lint clean
- ⏳ Live bench-validation on the dev Teensy 4.0 lands once the firmware
     is reflashed with this RPC

Note: the firmware still has to be flashed onto the Teensy 4.0 before the
Python harness can validate the FlexIO RX capture path end-to-end. That's
a separate hardware step held out of this PR to keep the diff focused on
the software surface.

Refs #2764

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

coderabbitai Bot commented Jun 5, 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: 79fafd5e-ccfc-430d-9f3e-cda8362576fa

📥 Commits

Reviewing files that changed from the base of the PR and between e821a25 and 794acaa.

📒 Files selected for processing (3)
  • ci/autoresearch/test_flexio_rx_squarewave.py
  • examples/AutoResearch/AutoResearchRemote.cpp
  • src/platforms/arm/teensy/teensy4_common/rx_flexio_channel.cpp.hpp

📝 Walkthrough

Walkthrough

Adds a Python bench script and a Teensy 4.x RPC handler to generate a square wave, capture FlexIO RX edge timestamps, compute period statistics (mean, sigma, min, max), and validate results against per-case tolerances; also raises the FlexIO capture buffer cap and documents the new RPC in help.

Changes

FlexIO RX Benchmark Validation

Layer / File(s) Summary
Test infra & RPC comms
ci/autoresearch/test_flexio_rx_squarewave.py
Adds module docstring, imports, DEFAULT_PORT/DEFAULT_BAUD, BenchCase dataclass, CASES list, and send_rpc helper to send JSON-RPC over serial and match responses by request id.
Firmware flexioRxBenchmark RPC
examples/AutoResearch/AutoResearchRemote.cpp (lines 1091–1245)
Registers flexioRxBenchmark RPC on Teensy 4.x: parse optional frequency_hz/duration_ms/tx_pin/rx_pin, generate 50% duty square wave on TX pin, configure FlexIO RxChannel for RX pin, capture edges for duration, compute period statistics (mean, integer-sqrt sigma, min, max), and return capture counts and metrics.
FlexIO capture buffer cap increase
src/platforms/arm/teensy/teensy4_common/rx_flexio_channel.cpp.hpp
Increases the capture buffer cap used when sizing mBufferSize from 4096 to 16384 entries in the FlexIO RX channel begin() allocation logic.
RPC help entry
examples/AutoResearch/AutoResearchRemote.cpp (lines 1768–1778)
Adds flexioRxBenchmark to the RPC help output and increments totalFunctions.
Test evaluation & CLI
ci/autoresearch/test_flexio_rx_squarewave.py (evaluate, main)
Adds evaluate to validate minimum captured periods, mean within per-case ±tolerance percent, and sigma below per-case max; main() handles CLI, serial open/ping, runs benchmark cases with timeouts, prints per-case PASS/FAIL and summary, and returns exit codes (0 success, 1 benchmark/RPC failure, 2 startup/ping failure).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Possibly related PRs

  • FastLED/FastLED#2765: Touches the Teensy 4.x FlexIO RX implementation and is related to the capture/channel code changes made here.

Poem

🐰 I hop a pulse from Teensy's pin so bright,
Edges caught in FlexIO's careful sight,
Python counts the beats and checks the score,
Mean and sigma measured, tests explore —
A happy rabbit nods: the bench is right! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main changes: adding flexioRxBenchmark RPC method and a Python test harness, with explicit phase reference to the parent issue.
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/flexio-rx-benchmark-rpc

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Infer (1.2.0)
examples/AutoResearch/AutoResearchRemote.cpp

In file included from examples/AutoResearch/AutoResearchRemote.cpp:14:
examples/AutoResearch/AutoResearchRemote.h:14:10: fatal error: 'fl/stl/stdint.h' file not found
14 | #include "fl/stl/stdint.h" // for uint32_t, uint8_t
| ^~~~~~~~~~~~~~~~~
1 error generated.
examples/AutoResearch/AutoResearchRemote.cpp:2955:5-12: ERROR translating statement 'ReturnStmt'
Aborting translation of method 'AutoResearchRemoteControl::startBleRemote' in file 'examples/AutoResearch/AutoResearchRemote.cpp': "Assert_failure src/clang/cAst_utils.ml:249:53"
Uncaught Internal Error: "Assert_failure src/clang/cAst_utils.ml:249:53"
Error backtrace:
Raised at ClangFrontend__CAst_utils.get_decl_from_typ_ptr in file "src/clang/cAst_utils.ml", line 249, characters 53-65
Called from ClangFrontend__CTrans.CTrans_funct.get_destructor_decl_ref in file "src/clang/cTrans.ml", line 658, characters 12-59
Called from ClangFrontend__CTrans.CTrans_funct.destructor_calls.(fun) in file "src/clang/cTrans.ml", li

... [truncated 2200 characters] ...

in file "src/istd/IExn.ml" (inlined), line 13, characters 2-50
Called from ClangFrontend__CTrans.CTrans_funct.instruction_log.(fun) in file "src/clang/cTrans.ml", line 4784, characters 10-1023
Called from ClangFrontend__CTrans.CTrans_funct.instruction in file "src/clang/cTrans.ml" (inlined), line 4765, characters 38-71
Called from ClangFrontend__CTrans.CTrans_funct.exec_with_node_creation in file "src/clang/cTrans.ml" (inlined), line 104, characters 20-38
Called from ClangFrontend__CTrans.CTrans_funct.get_clang_stmt_trans in file "src/clang/cTrans.ml" (inlined), line 5395, characters 4-69
Called from ClangFrontend__CTrans.CTrans_funct.get_custom_stmt_trans in file "src/clang/cTrans.ml", line 5401, characters 8-55
Called from ClangFrontend__CTrans.CTrans_funct.exec_trans_instrs.exec_trans_


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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (4)
ci/autoresearch/test_flexio_rx_squarewave.py (4)

129-146: ⚡ Quick win

Extract parse_args(argv) instead of parsing inside main().

Hard-wiring p.parse_args() here forces tests to patch sys.argv. A small parse_args(argv: list[str] | None) helper keeps the CLI testable and matches the repo rule.

As per coding guidelines, "**/*.py: parse_args functions MUST accept an optional list[str] parameter for testing flexibility".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ci/autoresearch/test_flexio_rx_squarewave.py` around lines 129 - 146, Extract
CLI parsing into a new helper function parse_args(argv: list[str] | None) ->
argparse.Namespace and move the ArgumentParser setup currently in main() into
that function; make parse_args accept an optional argv so tests can pass a list
instead of patching sys.argv, then call args = parse_args(None) inside main()
(or pass through any received argv) and keep the rest of main() unchanged;
update references to args in main() to use the returned Namespace from
parse_args.

49-56: ⚡ Quick win

Add runtime type validation to BenchCase.

This config object is missing the required @typechecked wrapper on top of @dataclass.

As per coding guidelines, "**/*.py: Use @typechecked decorator with @dataclass for runtime type validation".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ci/autoresearch/test_flexio_rx_squarewave.py` around lines 49 - 56, BenchCase
is missing runtime type validation; add the `@typechecked` decorator immediately
above the `@dataclass` declaration for BenchCase and import it (e.g., from
typeguard import typechecked) so the dataclass fields (label, frequency_hz,
duration_ms, expected_period_ns, sigma_max_ns, mean_tolerance_pct) are validated
at runtime; ensure the import is added to the file and that `@typechecked`
precedes `@dataclass` on the BenchCase class.

102-126: ⚡ Quick win

Return a typed evaluation object instead of (ok, msg).

evaluate() returns two positional values, which makes the call site brittle and breaks the repo rule for multi-value returns.

Suggested shape
+@dataclass
+class EvaluationResult:
+    ok: bool
+    message: str
+
-def evaluate(case: BenchCase, result: dict[str, Any]) -> tuple[bool, str]:
+def evaluate(case: BenchCase, result: dict[str, Any]) -> EvaluationResult:
     ...
-        return False, "..."
+        return EvaluationResult(False, "...")
     ...
-    return True, "..."
+    return EvaluationResult(True, "...")

As per coding guidelines, "**/*.py: Return dataclass structs instead of tuples or dicts for functions with multiple return values".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ci/autoresearch/test_flexio_rx_squarewave.py` around lines 102 - 126, Change
evaluate(case: BenchCase, result: dict[str, Any]) to return a typed dataclass
(e.g., EvaluationResult) instead of a (bool, str) tuple: define a small
dataclass with fields like ok: bool and message: str (and optionally fields for
periods, mean_ns, sigma_ns if helpful), update the evaluate function to
construct and return that dataclass (use the existing symbol evaluate and
BenchCase to locate the function), and update all call sites that unpack the
tuple to use the dataclass fields (e.g., result.ok / result.message) so the
multi-value return is strongly typed and follows the repo guideline.

66-72: ⚡ Quick win

Remove defaulted parameters from send_rpc().

The helper currently hides request behavior in default arguments (args, request_id, timeout), which violates the repo's Python signature rules and makes call-site intent less explicit.

As per coding guidelines, "**/*.py: All function parameters MUST have explicit type annotations and MUST NOT have default values".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ci/autoresearch/test_flexio_rx_squarewave.py` around lines 66 - 72, The
send_rpc helper uses defaulted parameters (args, request_id, timeout) which
violates the rule that Python function parameters must not have defaults; update
the send_rpc signature in ci/autoresearch/test_flexio_rx_squarewave.py by
removing the default values so it becomes send_rpc(s: "serial.Serial", method:
str, args: dict[str, Any] | None, request_id: int, timeout: float) -> dict[str,
Any] | None (keep the existing type annotations, including args as possibly
None), then find and update all call sites/tests to pass explicit args,
request_id and timeout values (or pass None for args when appropriate) so
callers no longer rely on implicit defaults; ensure any downstream logic that
assumed those defaults still behaves correctly after callers supply the values.
🤖 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_squarewave.py`:
- Around line 36-42: The module currently calls sys.exit(2) at import time when
pyserial is missing, which aborts test discovery; move the pyserial import and
its try/except into the test entrypoint (the main() function) so the module no
longer terminates on import. Inside main(), attempt "import serial" and on
ImportError print the same error to sys.stderr and return 2 (not call sys.exit),
allowing callers to decide skip/fail behavior; remove the top-level
try/except/sys.exit block so test discovery can import the file safely.

In `@examples/AutoResearch/AutoResearchRemote.cpp`:
- Around line 1091-1236: The help() RPC metadata is stale after adding the
flexioRxBenchmark binding: update the help() implementation to include
"flexioRxBenchmark" in the disclosed function list and increment the reported
totalFunctions from 25 to 26 (or compute it dynamically); ensure the
string/array that lists RPC names and the integer totalFunctions value (used by
clients) are updated to match the new binding so clients receive an accurate
contract.
- Around line 1154-1158: The hardcoded small capture buffer
(rx_cfg.edge_capacity = 1024) truncates samples for the requested 100 ms
benchmarks; change rx_cfg.edge_capacity to be computed from the benchmark window
and expected edges per ms (use the same edges_needed_per_ms or a constant for
10/100 kHz and the duration_ms used by the harness) so the buffer >= duration_ms
* edges_per_ms + small slack (or clamp to a safe upper bound) — update the
allocation where fl::RxChannelConfig rx_cfg(...) and rx_cfg.edge_capacity are
set so the capture covers the full requested 100 ms at 10/100 kHz.

---

Nitpick comments:
In `@ci/autoresearch/test_flexio_rx_squarewave.py`:
- Around line 129-146: Extract CLI parsing into a new helper function
parse_args(argv: list[str] | None) -> argparse.Namespace and move the
ArgumentParser setup currently in main() into that function; make parse_args
accept an optional argv so tests can pass a list instead of patching sys.argv,
then call args = parse_args(None) inside main() (or pass through any received
argv) and keep the rest of main() unchanged; update references to args in main()
to use the returned Namespace from parse_args.
- Around line 49-56: BenchCase is missing runtime type validation; add the
`@typechecked` decorator immediately above the `@dataclass` declaration for
BenchCase and import it (e.g., from typeguard import typechecked) so the
dataclass fields (label, frequency_hz, duration_ms, expected_period_ns,
sigma_max_ns, mean_tolerance_pct) are validated at runtime; ensure the import is
added to the file and that `@typechecked` precedes `@dataclass` on the BenchCase
class.
- Around line 102-126: Change evaluate(case: BenchCase, result: dict[str, Any])
to return a typed dataclass (e.g., EvaluationResult) instead of a (bool, str)
tuple: define a small dataclass with fields like ok: bool and message: str (and
optionally fields for periods, mean_ns, sigma_ns if helpful), update the
evaluate function to construct and return that dataclass (use the existing
symbol evaluate and BenchCase to locate the function), and update all call sites
that unpack the tuple to use the dataclass fields (e.g., result.ok /
result.message) so the multi-value return is strongly typed and follows the repo
guideline.
- Around line 66-72: The send_rpc helper uses defaulted parameters (args,
request_id, timeout) which violates the rule that Python function parameters
must not have defaults; update the send_rpc signature in
ci/autoresearch/test_flexio_rx_squarewave.py by removing the default values so
it becomes send_rpc(s: "serial.Serial", method: str, args: dict[str, Any] |
None, request_id: int, timeout: float) -> dict[str, Any] | None (keep the
existing type annotations, including args as possibly None), then find and
update all call sites/tests to pass explicit args, request_id and timeout values
(or pass None for args when appropriate) so callers no longer rely on implicit
defaults; ensure any downstream logic that assumed those defaults still behaves
correctly after callers supply the values.
🪄 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: e0d6d0c7-35a5-4007-8ccf-6976d1ac8d61

📥 Commits

Reviewing files that changed from the base of the PR and between b2934f2 and e821a25.

📒 Files selected for processing (2)
  • ci/autoresearch/test_flexio_rx_squarewave.py
  • examples/AutoResearch/AutoResearchRemote.cpp

Three fixes from the review:

1. **Help registry sync** (CodeRabbit minor):
   - Added `flexioRxBenchmark` to the `help()` function manifest with args,
     returns, phase, and description fields matching the binding above
   - Bumped `totalFunctions` 25 → 26 so any client that relies on `help()`
     gets the up-to-date contract

2. **Capture buffer too small at 10/100 kHz** (CodeRabbit major):
   - At 100 kHz × 100 ms the harness expects ~20 000 edges but the buffer
     was capped at 1024 — sample set was being truncated to ~5 ms.
   - `flexioRxBenchmark` now sizes `edge_capacity` from
     `2 * frequency_hz * duration_ms / 1000` with 50 % headroom, clamped
     to `[1024, 16384]` so RAM use is bounded but the requested window is
     honored.
   - Raised the matching internal cap in `rx_flexio_channel.cpp.hpp`
     `begin()` from 4096 → 16384 (64 KiB, comfortably fits 100 ms at
     100 kHz with headroom) so the channel honors the new larger requests.

3. **`sys.exit(2)` at module import** (CodeRabbit minor):
   - Moved the pyserial dependency check from the import block into
     `main()` so that test-collection (e.g. pytest on a CI runner without
     `pyserial`) doesn't abort the interpreter before the caller can
     decide to skip the hardware bench. The check now reports the same
     error and returns 2 from `main()` instead.

Verification:
- ✅ Teensy 4.0 release build clean (`examples/AutoResearch`, ~1m 10s)
- ✅ C++ lint clean
- Pyright still flags a handful of pre-existing type-narrowing warnings
  on the pyserial wrapper; left as-is since they're not from this change.

Refs #2764, PR #2767 review

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@zackees
zackees merged commit 511730e into master Jun 5, 2026
18 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 5, 2026
zackees added a commit that referenced this pull request Jun 5, 2026
…(Phase 3 of #2764) (#2769)

* feat(autoresearch): ObjectFLED -> FlexIO RX loopback + WS2812 decoder (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]>

* fix(autoresearch): address CodeRabbit review on PR #2769

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]>

* fix(autoresearch): Python @TypeChecked + EvaluationResult dataclass (PR #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]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
zackees added a commit that referenced this pull request Jun 5, 2026
… 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]>
@zackees
zackees deleted the feat/flexio-rx-benchmark-rpc branch August 21, 2026 19:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant