Skip to content

feat(rx/lpc): WS2812 byte-match loopback plumbing (refs #3021 Phase 2) - #3031

Merged
zackees merged 1 commit into
masterfrom
feat/3021-lpc-sct-rx-phase2
Jun 14, 2026
Merged

zackees merged 1 commit into
masterfrom
feat/3021-lpc-sct-rx-phase2

Conversation

@zackees

@zackees zackees commented Jun 14, 2026 •

Copy link
Copy Markdown
Member

Summary

Phase 2 of FastLED #3021 — adds the ws2812SctTest JSON-RPC handler, --ws2812-loopback autoresearch subcommand, and Python orchestrator for the WS2812 byte-match loopback. Replaces previously-closed PR #3025 (auto-closed when its base branch feat/3021-lpc-sct-rx-phase1 was deleted on merge of #3024).

What ships

Sketch — examples/AutoResearchLpc/AutoResearchLpc.ino

New ws2812SctTest handler doubly-gated behind #if defined(FL_IS_ARM_LPC) && defined(FASTLED_LPC_RX_SCT_WS2812). Patterns mirror flexioObjectFledTest:

Case LEDs Content
0 1 Red (0xFF, 0x00, 0x00)
1 3 R, G, B chain
2 1 All zeros (T0H/T0L fidelity)
3 1 All ones (T1H/T1L fidelity)
4 100 Alternating R/G/B (watchdog safety)

TX uses the existing bit-bang clockless_arm_lpc.h driver via FastLED.show(). RX uses the Phase-1 polling-mode LpcSctRxChannel. Decode goes through fl::make4PhaseTiming + LpcSctRxChannel::decode(). Returns CSV success,test_case,num_leds,exp_bytes,dec_bytes,matched,mismatched,edges.

Orchestrator — ci/autoresearch/test_lpc_ws2812_loopback.py

Mirrors test_flexio_rx_objectfled.py. Sends each case, parses CSV, asserts mismatched == 0. Final summary prints a polling-vs-DMA reminder when fails are non-zero.

Runner wiring — ci/autoresearch/{args,phases}.py

  • New --ws2812-loopback CLI flag.
  • _run_lpc_ws2812_loopback_tests() dispatcher routing lpc845brk + --ws2812-loopback to 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_WS2812 is therefore default OFF until #3002 lands fully. Once #3030 lands (retire AutoResearchLpc.ino into a low-memory mode of the main AutoResearch.ino), this whole RPC moves with it.

Test plan

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added WS2812 loopback testing capability for LPC845/LPC804 boards.
    • Introduced new validation tests for WS2812 byte transmission and reception accuracy.
    • Added comprehensive test suite with multiple validation scenarios to verify FastLED compatibility.

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.
@coderabbitai

coderabbitai Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds Phase-2 WS2812 SCT-RX byte-match loopback validation for LPC845/LPC804 targets. A new --ws2812-loopback CLI flag dispatches to a dedicated runner in phases.py, which invokes a new Python test script that drives five fixed LED-count test cases via JSON-RPC over serial, parsing and validating CSV results returned by a new conditionally-compiled ws2812SctTest firmware handler.

Changes

WS2812 SCT-RX Loopback Bench (Phase 2)

Layer / File(s) Summary
CLI flag and phase dispatch
ci/autoresearch/args.py, ci/autoresearch/phases.py
Adds ws2812_loopback: bool to Args, wires --ws2812-loopback into the LPC845 argument group, propagates the field through parse_args(), and adds a conditional branch in _run_tests_or_special_mode plus the _run_lpc_ws2812_loopback_tests() runner that invokes the bench script via uv run python.
Python loopback test harness
ci/autoresearch/test_lpc_ws2812_loopback.py
New script with TestCase dataclass, five-entry CASES table, send_rpc JSON-RPC-over-serial helper, parse_csv_result for firmware CSV replies, evaluate for per-case pass/fail logic, and main() that runs all cases and exits 0/1/2.
Firmware ws2812SctTest RPC handler
examples/AutoResearchLpc/AutoResearchLpc.ino
Conditionally compiled (under FASTLED_LPC_RX_SCT_WS2812) JSON-RPC handler that builds CRGB test patterns, configures SCT capture, calls FastLED.show(), decodes captured edges with 4-phase timing traits, counts byte matches, and returns a CSV result. Adds related docs, macro comments, and conditional header includes.

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)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Possibly related PRs

  • FastLED/FastLED#3016: The firmware's ws2812SctTest handler depends on the LPC SCT capture/WS2812 byte-decoding RX backend (LpcSctRxChannel, edge decode) introduced in this PR.
  • FastLED/FastLED#3009: This PR extends the same LPC bring-up framework and AutoResearchLpc JSON-RPC infrastructure established in #3009 by adding a new phase-2 runner path.

Poem

🐇 Hop along the data wire,
Bits fly out and come back higher!
SCT captures every edge,
Loopback bench fulfils the pledge.
GRB bytes matched in a row —
FastLED.show() puts on a show! ✨

🚥 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 clearly and specifically describes the main change: adding WS2812 byte-match loopback plumbing infrastructure (CLI flag, test orchestrator, and firmware RPC handler). It references the relevant issue (#3021) and phase, providing sufficient context for code history scanning.
Docstring Coverage ✅ Passed Docstring coverage is 80.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/3021-lpc-sct-rx-phase2

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7383315 and f37ec0d.

📒 Files selected for processing (4)
  • ci/autoresearch/args.py
  • ci/autoresearch/phases.py
  • ci/autoresearch/test_lpc_ws2812_loopback.py
  • examples/AutoResearchLpc/AutoResearchLpc.ino

Comment thread ci/autoresearch/phases.py
Comment on lines +1184 to +1189
# 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Comment thread ci/autoresearch/phases.py
Comment on lines +1656 to +1669
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Comment on lines +73 to +79
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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ 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

Comment on lines +111 to +133
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 {}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ 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

Comment on lines +319 to +320
case 4: num_leds = 100; break;
default: num_leds = 1; break;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

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.

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