Repository navigation
feat(rx/lpc): WS2812 byte-match loopback plumbing (refs #3021 Phase 2) - #3031
Conversation
Adds the Phase-2 surface area for FastLED #3021 — the ws2812SctTest JSON-RPC handler in the LPC845-BRK sketch (gated behind FASTLED_LPC_RX_SCT_WS2812 + FL_IS_ARM_LPC), the --ws2812-loopback autoresearch subcommand, and the Python orchestrator that exercises the 5 fixed WS2812 patterns mirroring flexioObjectFledTest. Hardware acceptance for this RPC is blocked on two pre-existing follow-ups (independent of #3021 itself): 1. SCT->DMA RX upgrade — polling-mode pollOnce() on M0+ can't keep up with WS2812 800 kHz edge rate (300-700 ns per poll vs 400-850 ns sub-pulses). DMA upgrade tracked as a follow-up. 2. fl::json soft-FP flash bloat (#3002) — #include <FastLED.h> overflows the LPC845 64 KB budget alongside fl::Remote until #3002 lands. FASTLED_LPC_RX_SCT_WS2812 is therefore default OFF in the sketch; the flag flips on for the lpc845brk fbuild target once #3002 closes. Rebased onto master after #3024 (Phase 1) was squash-merged.
📝 WalkthroughWalkthroughAdds Phase-2 WS2812 SCT-RX byte-match loopback validation for LPC845/LPC804 targets. A new ChangesWS2812 SCT-RX Loopback Bench (Phase 2)
Sequence Diagram(s)sequenceDiagram
participant CI as CI Runner (phases.py)
participant Bench as test_lpc_ws2812_loopback.py
participant FW as AutoResearchLpc Firmware
CI->>Bench: uv run python ... --port --tx-pin --rx-pin
Bench->>FW: JSON-RPC echo (pre-check)
FW-->>Bench: echo response
loop 5 TestCases
Bench->>FW: JSON-RPC ws2812SctTest(index, tx, rx, capture_ms)
FW->>FW: build CRGB pattern, FastLED.show(), SCT capture, decode edges
FW-->>Bench: CSV (success, num_leds, num_bytes, matched, mismatched, edges)
Bench->>Bench: parse_csv_result + evaluate → PASS/FAIL
end
Bench-->>CI: exit 0 (all pass) / 1 (failures) / 2 (setup error)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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: 5
🤖 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/phases.py`:
- Around line 1656-1669: Add a timeout parameter to the subprocess.run(cmd) call
in the WS2812 harness test execution to prevent indefinite blocking if the child
script hangs or the device becomes wedged. Specify an appropriate timeout value,
and wrap the call in a try-except block to catch subprocess.TimeoutExpired
exceptions, converting timeout expiry into a controlled non-zero exit code
return path rather than allowing the subprocess to hang indefinitely.
- Around line 1184-1189: The code currently allows both --pin-toggle-rx and
--ws2812-loopback arguments to be set simultaneously, causing the pin-toggle-rx
branch to silently win and ignore the ws2812-loopback mode. Add explicit
conflict validation logic during argument parsing or context validation to
reject this combination and raise a clear error when users attempt to specify
both flags together. This ensures the mode selection is deterministic and
user-visible rather than silently ignoring one option.
In `@ci/autoresearch/test_lpc_ws2812_loopback.py`:
- Around line 73-79: Remove all default parameter values from the send_rpc
function signature (the args=None, request_id=1, and timeout=10.0 assignments
must be deleted), making all parameters required. Then locate all call sites
throughout the file where send_rpc is invoked and update each call to explicitly
pass values for args, request_id, and timeout parameters instead of relying on
defaults.
- Around line 111-133: The parse_csv_result function currently returns a generic
dict[str, int] which lacks type safety and validation. Create a typed dataclass
with fields corresponding to the CSV fields (success, test_case, num_leds,
exp_bytes, dec_bytes, matched, mismatched, edges) and decorate it with both
`@dataclass` and `@typechecked` for runtime type validation. Update parse_csv_result
to return an instance of this dataclass instead of a dict, handling the empty
case with a dataclass instance containing default/None values as appropriate.
Apply the same dataclass pattern to the evaluate function (mentioned at lines
136-161) to replace its current tuple or dict return type with an explicit typed
dataclass.
In `@examples/AutoResearchLpc/AutoResearchLpc.ino`:
- Around line 319-320: Case 4 in the switch statement sets num_leds to 100,
which when multiplied by 24 bits per LED and 2 edges per bit in the
expected_edges calculation results in 4800 expected edges. However, the buffer
clamping logic immediately after constrains the capture buffer to a maximum of
2048 bytes, causing data truncation and making byte-perfect validation
impossible for case 4. Either reduce the num_leds value for case 4 to fit within
the 2048-byte buffer constraint (approximately 42 LEDs maximum), or redesign the
capture and validation mechanism to handle streaming or chunked processing.
After making changes to the case 4 LED count or the capture design, update the
corresponding case 4 expectations in the test file
ci/autoresearch/test_lpc_ws2812_loopback.py to match the new behavior.
🪄 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: 077852eb-c4ed-4bc1-95f9-3d89f0bd9d1f
📒 Files selected for processing (4)
ci/autoresearch/args.pyci/autoresearch/phases.pyci/autoresearch/test_lpc_ws2812_loopback.pyexamples/AutoResearchLpc/AutoResearchLpc.ino
| # FastLED #3021 Phase 2: --ws2812-loopback runs the WS2812 | ||
| # byte-match loopback bench. Requires the sketch to be | ||
| # rebuilt with -DFASTLED_LPC_RX_SCT_WS2812=1 (gated due to | ||
| # flash budget — see issue #3002). | ||
| if getattr(ctx.args, "ws2812_loopback", False): | ||
| return await _run_lpc_ws2812_loopback_tests(ctx) |
There was a problem hiding this comment.
Add explicit conflict handling for --pin-toggle-rx and --ws2812-loopback.
Right now, when both are set, Line 1182’s branch wins and WS2812 mode is silently ignored. Please reject this combination during arg/context validation so mode selection is deterministic and user-visible.
🤖 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/phases.py` around lines 1184 - 1189, The code currently
allows both --pin-toggle-rx and --ws2812-loopback arguments to be set
simultaneously, causing the pin-toggle-rx branch to silently win and ignore the
ws2812-loopback mode. Add explicit conflict validation logic during argument
parsing or context validation to reject this combination and raise a clear error
when users attempt to specify both flags together. This ensures the mode
selection is deterministic and user-visible rather than silently ignoring one
option.
| cmd = [ | ||
| "uv", | ||
| "run", | ||
| "python", | ||
| "ci/autoresearch/test_lpc_ws2812_loopback.py", | ||
| "--port", | ||
| upload_port, | ||
| "--tx-pin", | ||
| str(tx_pin), | ||
| "--rx-pin", | ||
| str(rx_pin), | ||
| ] | ||
| result = subprocess.run(cmd) | ||
| return 0 if result.returncode == 0 else 1 |
There was a problem hiding this comment.
Add a timeout to the WS2812 harness subprocess call.
subprocess.run(cmd) at Line 1668 can block indefinitely if the child script hangs (serial stalls, device wedged, etc.), which can wedge CI runs. Use a bounded timeout and convert timeout expiry to a controlled non-zero exit path.
🧰 Tools
🪛 ast-grep (0.43.0)
[error] 1667-1667: Command coming from incoming request
Context: subprocess.run(cmd)
Note: [CWE-20].
(subprocess-from-request)
[error] 1667-1667: Use of unsanitized data to create processes
Context: subprocess.run(cmd)
Note: [CWE-78].
(os-system-unsanitized-data)
🪛 Ruff (0.15.15)
[error] 1668-1668: subprocess call: check for execution of untrusted input
(S603)
🤖 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/phases.py` around lines 1656 - 1669, Add a timeout parameter
to the subprocess.run(cmd) call in the WS2812 harness test execution to prevent
indefinite blocking if the child script hangs or the device becomes wedged.
Specify an appropriate timeout value, and wrap the call in a try-except block to
catch subprocess.TimeoutExpired exceptions, converting timeout expiry into a
controlled non-zero exit code return path rather than allowing the subprocess to
hang indefinitely.
| def send_rpc( | ||
| s: "serial.Serial", | ||
| method: str, | ||
| args: list[Any] | None = None, | ||
| request_id: int = 1, | ||
| timeout: float = 10.0, | ||
| ) -> dict[str, Any] | None: |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Remove default parameter values from send_rpc to match repo Python rules.
send_rpc currently uses defaulted parameters (args, request_id, timeout), which violates the project’s Python signature policy. Make all parameters explicit at call sites.
As per coding guidelines, “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_lpc_ws2812_loopback.py` around lines 73 - 79, Remove all
default parameter values from the send_rpc function signature (the args=None,
request_id=1, and timeout=10.0 assignments must be deleted), making all
parameters required. Then locate all call sites throughout the file where
send_rpc is invoked and update each call to explicitly pass values for args,
request_id, and timeout parameters instead of relying on defaults.
Source: Coding guidelines
| def parse_csv_result(csv: str) -> dict[str, int]: | ||
| """Parse the AutoResearchLpc ws2812SctTest CSV reply. | ||
|
|
||
| Format (must match the sketch handler): | ||
| success,test_case,num_leds,exp_bytes,dec_bytes,matched,mismatched,edges | ||
| """ | ||
| fields = ( | ||
| "success", | ||
| "test_case", | ||
| "num_leds", | ||
| "exp_bytes", | ||
| "dec_bytes", | ||
| "matched", | ||
| "mismatched", | ||
| "edges", | ||
| ) | ||
| parts = csv.split(",") | ||
| if len(parts) != len(fields): | ||
| return {} | ||
| try: | ||
| return {k: int(v) for k, v in zip(fields, parts)} | ||
| except ValueError: | ||
| return {} |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | 🏗️ Heavy lift
Use typed dataclass result objects instead of dict/tuple multi-value returns.
parse_csv_result and evaluate return multi-field dict/tuple payloads; convert these to explicit dataclass return types for stronger contracts and easier validation.
As per coding guidelines, “Return dataclass structs instead of tuples or dicts for functions with multiple return values” and “Use @typechecked decorator with @dataclass for runtime type validation.”
Also applies to: 136-161
🧰 Tools
🪛 Ruff (0.15.15)
[warning] 131-131: zip() without an explicit strict= parameter
Add explicit value for parameter strict=
(B905)
🤖 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_lpc_ws2812_loopback.py` around lines 111 - 133, The
parse_csv_result function currently returns a generic dict[str, int] which lacks
type safety and validation. Create a typed dataclass with fields corresponding
to the CSV fields (success, test_case, num_leds, exp_bytes, dec_bytes, matched,
mismatched, edges) and decorate it with both `@dataclass` and `@typechecked` for
runtime type validation. Update parse_csv_result to return an instance of this
dataclass instead of a dict, handling the empty case with a dataclass instance
containing default/None values as appropriate. Apply the same dataclass pattern
to the evaluate function (mentioned at lines 136-161) to replace its current
tuple or dict return type with an explicit typed dataclass.
Source: Coding guidelines
| case 4: num_leds = 100; break; | ||
| default: num_leds = 1; break; |
There was a problem hiding this comment.
Case 4 is currently over-specified for the capture buffer budget.
Line 319 sets num_leds = 100, but Line 363 computes expected_edges = num_leds * 24 * 2, and Lines 365-367 clamp buffer size to 2048. That guarantees capture truncation for case 4 and makes byte-perfect pass structurally unattainable under this implementation.
Please either reduce case-4 LED count to fit the capture budget or redesign capture/validation to stream/chunk, then align ci/autoresearch/test_lpc_ws2812_loopback.py case expectations accordingly.
Also applies to: 363-367
🤖 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 `@examples/AutoResearchLpc/AutoResearchLpc.ino` around lines 319 - 320, Case 4
in the switch statement sets num_leds to 100, which when multiplied by 24 bits
per LED and 2 edges per bit in the expected_edges calculation results in 4800
expected edges. However, the buffer clamping logic immediately after constrains
the capture buffer to a maximum of 2048 bytes, causing data truncation and
making byte-perfect validation impossible for case 4. Either reduce the num_leds
value for case 4 to fit within the 2048-byte buffer constraint (approximately 42
LEDs maximum), or redesign the capture and validation mechanism to handle
streaming or chunked processing. After making changes to the case 4 LED count or
the capture design, update the corresponding case 4 expectations in the test
file ci/autoresearch/test_lpc_ws2812_loopback.py to match the new behavior.
Summary
Phase 2 of FastLED #3021 — adds the
ws2812SctTestJSON-RPC handler,--ws2812-loopbackautoresearch subcommand, and Python orchestrator for the WS2812 byte-match loopback. Replaces previously-closed PR #3025 (auto-closed when its base branchfeat/3021-lpc-sct-rx-phase1was deleted on merge of #3024).What ships
Sketch —
examples/AutoResearchLpc/AutoResearchLpc.inoNew
ws2812SctTesthandler doubly-gated behind#if defined(FL_IS_ARM_LPC) && defined(FASTLED_LPC_RX_SCT_WS2812). Patterns mirrorflexioObjectFledTest:TX uses the existing bit-bang
clockless_arm_lpc.hdriver viaFastLED.show(). RX uses the Phase-1 polling-modeLpcSctRxChannel. Decode goes throughfl::make4PhaseTiming+LpcSctRxChannel::decode(). Returns CSVsuccess,test_case,num_leds,exp_bytes,dec_bytes,matched,mismatched,edges.Orchestrator —
ci/autoresearch/test_lpc_ws2812_loopback.pyMirrors
test_flexio_rx_objectfled.py. Sends each case, parses CSV, assertsmismatched == 0. Final summary prints a polling-vs-DMA reminder when fails are non-zero.Runner wiring —
ci/autoresearch/{args,phases}.py--ws2812-loopbackCLI flag._run_lpc_ws2812_loopback_tests()dispatcher routinglpc845brk + --ws2812-loopbackto the orchestrator.Two documented blockers for hardware acceptance
Both pre-existing, independent of #3021 itself:
Blocker 1 — Polling SCT capture can't keep up with 800 kHz WS2812
Phase-1's
pollOnce()measures ~2 µs/poll on M0+ @ 30 MHz; WS2812 sub-pulses are 400–850 ns. SCT→DMA upgrade is required for the WS2812 byte-match. Tracked as a separate follow-up.Blocker 2 — fl::json flash bloat (FastLED #3002 + retire-AutoResearchLpc #3030)
#include <FastLED.h>adds 2–4 KB on top of the already-97%-full LPC845 bring-up sketch.FASTLED_LPC_RX_SCT_WS2812is therefore default OFF until #3002 lands fully. Once #3030 lands (retireAutoResearchLpc.inointo a low-memory mode of the mainAutoResearch.ino), this whole RPC moves with it.Test plan
bash lintclean on all touched files (C++ + Python).ws2812SctTestis doubly-gated behind FL_IS_ARM_LPC so the host stub compiles past it cleanly (same fix that unblocked feat(rx/lpc): SCT input-capture + pin-toggle loopback (refs #3021) #3024 CI).bash autoresearch lpc845brk --ws2812-loopback --upload-port COM10withFASTLED_LPC_RX_SCT_WS2812=1in the firmware build. Closes Phase 2 of feat(lpc): RX backend for LPC8xx via SCT input-capture — two-phase rollout #3021 once both blockers are resolved.🤖 Generated with Claude Code
Summary by CodeRabbit