Repository navigation
fix(autoresearch/lpc): assert DTR=True + VID:PID port detection (#3300) - #3339
Conversation
bash autoresearch lpc845brk has been silently failing because of three
independent bugs in the host-side serial stack -- none of them in
firmware. The device transmits correctly; the host throws the bytes
away. This change makes autoresearch work with LPC again.
ROOT CAUSE A -- DTR/RTS default
================================
LPC845-BRK uses an LPC11U35 as a USB-VCOM bridge. Like a standard CDC
ACM modem, it uses host DTR as a "host ready, please forward bytes"
signal. With DTR=False, the bridge silently drops every byte the
LPC845 transmits.
Three host-side sites were leaving DTR=False:
1. _pyserial_dtr_reset() (serial_interface.py) ends with dtr=False
(esptool ClassicReset convention -- correct for ESP32 native USB
CDC, fatal for LPC).
2. SerialMonitor.__enter__ (pyserial_monitor.py) opened with
pyserial's Windows default (DTR=False), never re-asserting.
3. _run_bring_up_tests (phases.py) explicitly hardcoded
ser.dtr=False; ser.rts=False before the echo round-trip.
Fix:
- SerialMonitor.__enter__ now sets dtr=True+rts=True after open.
Safe for ESP32 (idle state, not a reset), required for LPC11U35.
- _run_bring_up_tests now also opens with dtr=True+rts=True.
NOT touched: _pyserial_dtr_reset itself. The reset sequence is correct
for its purpose; the bug was consumers not re-asserting after.
ROOT CAUSE B -- port auto-detection picks the wrong COM
========================================================
port_utils.auto_detect_upload_port() walked USB ports, preferred ones
whose description matched CP2102/CH340/FTDI/uart, and fell through to
usb_ports[0]. The LPC enumerates as a generic "USB Serial Device" on
Windows -- no CDC chip name -- so it lost the preference race against
any ESP board and the fallback grabbed whichever the OS enumerated
first (an ESP32 board on COM25 that was already locked).
Fix:
- New ENVIRONMENT_TO_VCOM_VID_PID map in port_utils.py keys LPC8xx
envs to (0x16C0, 0x0483) -- the LPC11U35 VCOM fingerprint.
- When an env has a fingerprint, VID:PID match takes precedence over
chip-probe and description heuristics.
- If the expected fingerprint isn't detected, return a clear error
(board not plugged in?) instead of silently picking a different
board's port.
- ESP environments still go through the existing esptool chip-probe
path; the LPC short-circuit is an additive early-exit.
VERIFICATION
============
Before: bash autoresearch lpc845brk --timeout 30 failed with
"could not open port COM25: PermissionError" because
port_utils picked the wrong COM and the monitor / bring-up
test never received bytes.
After: Same command flashes the device, opens COM20 (correct LPC
VCOM), and the bring-up test reports the actual device state:
remote_ok=True -- REMOTE: response received
log_ok=True -- FL_DBG "Stored request ID" reached host
echo_ok=False -- device returns -32601 (the real #3300 bug)
warn_ok=False -- handler never fires (echo unbound)
The echo_ok=False is the real FastLED-side regression in #3300, now
properly surfaced instead of masked by "zero bytes". Previously this
led to false assumptions in #3325 that the Arduino-core LPC8xx commits
were the regression axis (they aren't -- see #3325 update
comment 4757727203).
ALSO IN THIS COMMIT
====================
- ci/util/serial_probe.py -- new agent-facing helper. Replaces the
forbidden pwsh SerialPort pattern (#3336). Subcommands:
list -- enumerate ports with VID:PID + board hints
read <port> [--send X] -- open with DTR/RTS=True and dump bytes
find-lpc -- print the LPC845-BRK VCOM port device path
Uses the same DTR/RTS=True default so ad-hoc agent probes match what
autoresearch's pipeline does.
- ci/hooks/check_forbidden_commands.py -- new ban for the actual pwsh
SerialPort invocation pattern. The error message points at
bash autoresearch and the new serial_probe helper as replacements.
Regex requires a real invocation token (powershell + -Command /
-NoProfile) so commit messages, docs, and error strings that mention
the pattern don't false-positive. Closes #3336.
ESP32 IMPACT
============
Sanity-checked esp32c6 -> COM9, esp32s3 -> COM22, lpc845brk -> COM20
all resolve correctly. DTR/RTS=True on monitor open is the ESP32
post-reset idle state -- not a reset trigger.
Refs: #3300, #3325, #3336.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughFixes silent byte-loss on LPC845-BRK by setting ChangesDTR/RTS Serial Handshake Fix and Tooling
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes 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 |
The parent commit used a loose match (any pwsh.*System.IO.Ports.SerialPort substring) which false-flagged this PR's own commit message body and the existing checker docstrings. Tightening to require an actual ps invocation token between the two literals -- the binary name plus -Command / -NoProfile / -c -- so it matches real invocations while leaving commit messages, docs, error strings, and grep output that merely mention the pattern alone. Also dropped the redundant second pattern; the first one is now specific enough to catch both forms. Smoke-tested: - real invocation -> BLOCKED with the expected message - benign mention -> PASSED Refs: #3336. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 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/hooks/check_forbidden_commands.py`:
- Line 110: The regex pattern on line 110 uses `-c` without word boundaries,
which can accidentally match flag prefixes like `-config` instead of just the
standalone `-c` flag. Add word boundaries around the `-c` token to ensure it
matches only as a complete flag. Use regex boundary anchors (such as `\b` or
similar word boundary markers) before and after the `-c` to prevent partial
prefix matches while maintaining the intended pattern matching for the forbidden
command detection.
In `@ci/util/serial_probe.py`:
- Around line 51-70: The BOARD_FINGERPRINTS dictionary contains a duplicate key
(0x16C0, 0x0483) defined at two locations: once for the LPC11U35 VCOM bridge
mapping and again for the PJRC/Teensy USB-Serial mapping. The second definition
silently overrides the first, causing the LPC fingerprint to be discarded.
Consolidate these two entries by either merging them into a single descriptive
string that encompasses both device identities, or verify which VID:PID pairing
is correct and remove the duplicate entry while keeping only the accurate
mapping.
- Around line 128-134: The logic in the condition checking `if len(matches) > 1`
and `if cmsis_dap_ports` does not actually use the CMSIS-DAP information to
disambiguate which board to select; it still returns `matches[0]` in both cases,
making the disambiguation attempt ineffective. When multiple matches exist, the
code should filter the matches to find the one that corresponds to an available
CMSIS-DAP port, or if the CMSIS-DAP check does not resolve the ambiguity, raise
a descriptive error instead of silently falling back to `matches[0]`. This
ensures the function fails fast with clear error messaging rather than silently
selecting an incorrect board by port enumeration order.
🪄 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: a8de7aad-04db-4bfe-b6c9-ccc0c3ec5bbd
📒 Files selected for processing (5)
ci/autoresearch/phases.pyci/hooks/check_forbidden_commands.pyci/util/port_utils.pyci/util/pyserial_monitor.pyci/util/serial_probe.py
1. ci/hooks/check_forbidden_commands.py: anchor -c flag with \b so the regex doesn't false-positive on "-config" / "-Confirm" / similar ps flag prefixes. 2. ci/util/serial_probe.py: BOARD_FINGERPRINTS had two entries with the same VID:PID key (16C0:0483) -- LPC11U35 VCOM and PJRC Teensy -- so Python's dict literal silently dropped the LPC mapping at runtime. Merged into a single joint-hint entry; callers that need to disambiguate inspect manufacturer / sibling-port presence. 3. ci/util/serial_probe.py:find_lpc845brk_vcom: with multiple 16C0:0483 matches the function previously returned matches[0] regardless of the CMSIS-DAP check (dead disambiguation). Now it filters by manufacturer (lpc-like = not "Teensy*"); falls through to None when the filter doesn't reduce to exactly one. Matches the "no silent fallbacks" guideline cited in the review. Smoke-tested: regex matches real `powershell -Command ...SerialPort` invocations; does not match `-config` / `-Confirm` / `-ConfigFile`. find-lpc still returns COM20 on this machine. Refs: PR #3339 review. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ssert (#684) (#685) #684 mirrors the FastLED-side fix in FastLED/FastLED#3339 (the LPC845-BRK "silence" that cost two debugging sessions). The Python side ended with DTR=False on three independent code paths; that's "host not ready" for CDC-ACM USB-VCOM bridges (LPC11U35, FTDI CDC, some CH340 revs) and the bridge silently drops every byte the target MCU transmits. fbuild's `hard_reset_blocking` is the structural mirror of one of those bugs — currently latent because it's only called from ESP paths, but the generic name and trait surface would let a future contributor add an LPC- or FTDI-CDC flow that accidentally calls it. Three required acceptance criteria from #684: 1. **Rename `hard_reset_blocking` → `esp_hard_reset_blocking`.** The file is already `esp_reset.rs`; the symbol now matches. Pure documentation-as-code, no behavior change. Updated the two callers in `manager.rs` (one in a doc-comment, one in the actual call from `SharedSerialManager::esp_hard_reset`) and the doc-comment reference in `boot_mode.rs`. 2. **Add `cdc_vcom_safe_assert(port)` companion.** Sets DTR=true + RTS=true — the universal "host attached, please forward bytes" idle state for CDC-ACM bridges. Same `DtrRtsControl` trait surface as `esp_hard_reset_blocking`, same blocking calling convention so a `tokio::task::spawn_blocking` wrap stays trivial. Doc-comment names the LPC11U35 / FTDI / CH340 audience explicitly and links the FastLED #3300 / #3339 history. 3. **Module-level doc-comment warning in `esp_reset.rs`.** Explicit "Do NOT call `esp_hard_reset_blocking` for CDC-ACM bridge boards" callout with the LPC11U35 / FTDI / CH340 list, the failure mode (silent byte drop), the FastLED #3300 reference, and the recommended alternative (SWD/CMSIS-DAP reset, or call `cdc_vcom_safe_assert` after if re-using on a CDC board). Tests (in `daemon::server::tests::compiler_hash`-style flat module): * All 4 pre-existing reset-sequence tests renamed in step with the function. Coverage unchanged. * New `cdc_vcom_safe_assert_sets_both_lines_high` — pins the (DTR=true, RTS=true) post-condition so a future refactor can't silently regress the "host ready" contract for CDC bridges. * New `cdc_vcom_safe_assert_dtr_failure_short_circuits_before_rts` — early-error short-circuit, matches the `esp_hard_reset_blocking` shape. * New `cdc_vcom_safe_assert_rts_failure_surfaces` — error propagation. Optional Phase 2 from #684 (a `BoardFamily` enum gating DTR/RTS per family at `manager::open_port` time) is deliberately out of scope — the issue itself flags it as "non-trivial refactor; not strictly required for the current bug surface." File a follow-up if/when an LPC-family deploy path lands and the convention needs to be enforced at type level. Closes #684.
…700) #686 mirrors two artifacts that landed on the FastLED side in FastLED/FastLED#3339: a vendored `(vid, pid) → human hint` table and a port-probe CLI that opens with the correct DTR/RTS for the inferred board family. Both close gaps the closed #684 surfaced: with the rename to `esp_hard_reset_blocking` and the new `cdc_vcom_safe_assert` on the library side, the next missing piece was data + tooling. ## What this PR ships ### `crates/fbuild-serial/src/boards.rs` - `BOARD_FINGERPRINTS: &[(u16, u16, &str)]` — vendored from FastLED's `ci/util/serial_probe.py`. Covers NXP (LPC8xx CMSIS-DAP + LPC11U35), Espressif native USB + USB JTAG/serial, Silicon Labs CP210x, WCH CH340/CH9102, FTDI FT232R/FT231X, Arduino official, RP2040/Pico. - `ENVIRONMENT_TO_VCOM: &[(&str, u16, u16)]` — env-name → VCOM (vid, pid) for boards where the data port is NOT the primary USB endpoint (LPC845-BRK, LPC804, LPCXpresso845-MAX, LPCXpresso804 → LPC11U35). - `pub fn board_hint(vid, pid) -> Option<&'static str>` — exact-match lookup. - `pub fn vcom_for_env(env) -> Option<(u16, u16)>` — env-keyed lookup. - `pub fn family_for_vid_pid(vid, pid) -> Option<BoardFamily>` — classifier that returns the right `BoardFamily` so probe / monitor open paths can pick the right DTR/RTS via `idle_dtr_rts()` instead of the ESP-default that drops bytes on CDC-ACM bridges. - `pub enum BoardFamily { Esp32NativeUsbCdc, Esp32ExternalUart, CdcAcmBridge, Arduino }` with `idle_dtr_rts(&self) -> (bool, bool)`. Minimal scope per the #687 follow-up that owns the polymorphic `ResetMethod` registry. ### `crates/fbuild-cli/src/cli/serial_probe.rs` New `fbuild serial probe …` subcommand tree: * `fbuild serial probe list` — enumerate every visible serial port with VID:PID + board hint. Verified locally — output matches FastLED's `serial_probe.py list` shape exactly: ``` COM25 303A:1001 ser=… USB Serial Device (COM25) [Espressif native USB CDC …] COM20 16C0:0483 ser=… USB Serial Device (COM20) [LPC11U35 VCOM bridge …] COM10 1FC9:0132 ser=… USB Serial Device (COM10) [NXP CMSIS-DAP debug …] ``` * `fbuild serial probe find --vid-pid V:P | --env <name>` — return one port path on stdout (exit 0) or exit 1 when no match. Verified locally: `--env lpc845brk` → `COM20` (the VCOM bridge), NOT `COM10` (the CMSIS-DAP debug probe) — the disambiguation step that FastLED's `port_utils.py` had to add post-#3300. * `fbuild serial probe read PORT [--baud N] [--seconds N] [--send STR]` — open with `family_for_vid_pid(...).idle_dtr_rts()` so CDC-ACM bridges see DTR=true / RTS=true instead of the ESP-default that silently drops every byte the target MCU transmits. Supports a small set of `\n`/`\r`/`\t`/`\0`/`\xHH` escapes in the `--send` payload so scripted probes don't need shell-quoting gymnastics. ### Tests * 9 boards-module tests — every public API + a regression test pinning that `family_for_vid_pid(0x16C0, 0x0483).idle_dtr_rts()` == `(true, true)` (the LPC11U35 VCOM bridge MUST end at host-ready, or we reintroduce the FastLED/FastLED#3300 silent-byte-drop bug). * 6 CLI tests covering `parse_vid_pid` (colon + comma forms, malformed rejection) and `unescape_send` (common escapes, hex bytes, unknown escape pass-through, trailing backslash edge case). * No new tests for the hardware-touching paths (`list`, `find`, `read`) — those need a board attached. Manually smoke-verified locally against a multi-board host (LPC845-BRK on COM20, three ESP32-S3 on COM9 / COM22 / COM25, LPC CMSIS-DAP on COM10) and the disambiguation works. `cargo clippy -p fbuild-serial -p fbuild-cli --all-targets -- -D warnings` clean. `cargo fmt --all --check` clean. ## Out of scope (deferred to siblings of #686) - Cross-repo sync (acceptance criterion 3) — the data table is now in fbuild and the FastLED side could load it directly in a follow-up PR (option a from #686), OR a CI diff check could compare the two tables (option b). Neither is in this PR; both options remain open. - Polymorphic `ResetMethod` / `BootModeClassifier` dispatch registry — scope of #687, #688 respectively. `BoardFamily` here is the minimum needed by #686 criterion 4; the polymorphic dispatch comes next. Closes #686.
…#704) #691. Pins LPC845-BRK numbers from FastLED/FastLED#3339 plus observed ESP/Teensy/RP2040/Arduino values in one place so Deployer::post_deploy_recovery (#605) can stop hardcoding magic numbers per-deployer. - HandoffTiming struct: post_reset_settle_ms, boot_drain_ms, port_reappear_timeout_ms, open_retry_count. - BoardFamily::handoff_timing() — concrete table. - 4 new tests pinning the LPC numbers + ESP/1200-bps/Arduino invariants. - Doc table in docs/usb-cdc-control-line-matrix.md. Out of scope (follow-up): each Deployer reading the settings instead of inline magic numbers; FastLED Python-side adoption via shared helper. Closes #691.
#690 — catch too-large firmware at fbuild time instead of mid-flash when half the bytes have already been written. - New FbuildError::FirmwareTooLarge { board, actual, max, percent_used } — structured fields so CI / bash autoresearch can pinpoint overflow without parsing strings - New fbuild_deploy::size_check::check_artifact_fits_flash(artifact, max_size, board) — soft warning at 90% (FastLED/FastLED#3339's LPC bring-up sat at 84%, ~6% headroom); hard error above max - max_size: None (e.g. esp32 catch-all) skips with debug log; esptool's own check runs at deploy time - Defensive: max=0 in a malformed board JSON treats any artifact as overflow instead of dividing by zero 11 unit tests covering: under/at/over flash size with structured error inspection, LPC845-BRK at FastLED's 84%, LPC845 at 92% warn threshold, LPC804 32 KB overflow, Teensy 4.0 / RP2040 Pico fits, ESP32 catch-all skip, missing artifact IO error, zero max_size defense. Out of scope (follow-ups): wiring check_artifact_fits_flash into each Deployer's pre-deploy hook (esp32, lpc, avr, teensy) — needs board JSON lookup per orchestrator and is its own integration PR. Closes #690.
…714) #698. Centralizes the rpc.discover host-side validator that today lives ad-hoc on the FastLED Python side. Folded into fbuild-serial (per the project's 'never add a new crate' essential rule) since it sits next to messages.rs's JSON-RPC types and the bring-up orchestrator (#697) is the canonical consumer. What ships: - RpcSchema + MethodDecl — typed shape of rpc.discover's response - parse_schema_response(&str) -> Result<RpcSchema, SchemaParseError> — distinguishes InvalidJson, MissingJsonRpc, MissingMethods, DeviceError variants so callers get actionable failures instead of the cryptic '2 validation errors for RpcSchema: jsonrpc required, methods required' pydantic message FastLED's autoresearch emits today (FastLED/FastLED#3339) - Accepts both canonical envelope shape (result wrapper) AND bare schema shape (no envelope) — different firmwares emit different shapes; pin both - ValidationReport + MethodStatus { Present { params, returns } | Missing } — structured per-method status with the device's signature surfaced when bound - validate_against_expected(&schema, expected) — builds the report; is_passing() iff every expected method is Present - Display renders the actionable diagnostic the issue specifies: 'Expected method 'echo' bound — present (signature: int(int))' / 'Expected method 'ghost' bound — NOT FOUND in device schema.' / 'Device returned N methods total; harness expects M.' 12 unit tests covering: canonical envelope + bare schema parses, MissingJsonRpc / MissingMethods / DeviceError / InvalidJson typed errors, all-present passing report, missing-method failing report, device-method-count surfacing for extras, actionable Display for both pass + fail, empty-expected trivial pass. Out of scope (follow-up): - fetch_schema() doing the actual serial round-trip — lives in the bring-up orchestrator (#697) where the connection is already established - Strict signature checking (today the report surfaces the device signature but doesn't auto-fail; over-fires on int vs int32_t - FastLED's autoresearch migrated to consume this module Closes #698.
Summary
`bash autoresearch lpc845brk` works again. Three independent host-side bugs in the autoresearch serial stack — none of them in firmware — were combining to make the LPC845-BRK look silent. Each fix is isolated and small; together they restore end-to-end autoresearch on LPC and unblock #3300's diagnostic.
Plus two pieces from FastLED #3336:
Verification
Before: `bash autoresearch lpc845brk --timeout 30` failed with `could not open port COM25: PermissionError(13, 'Access is denied.')` because port_utils picked the wrong COM, and even on the right port the monitor / bring-up test never received bytes.
After: Same command flashes the device, opens COM20 (correct LPC VCOM), and the bring-up test now reports the actual device state:
```
TX: {"jsonrpc":"2.0","method":"echo","params":[4242],"id":1}
RX: b'src/fl/remote/remote.cpp.hpp(151): INFO: Stored request ID for echo (id=1)
src/fl/remote/rpc/rpc.cpp.hpp(102): WARN: RPC: Method not found: echo
REMOTE: {"id":1,"error":{"code":-32601,"message":"Method not found: echo"},"jsonrpc":"2.0"}\r\n
RESULT: {"type":"status","ready":true,"uptimeMs":154644031}\r\n'
remote_ok=True -- REMOTE: response received
log_ok=True -- FL_DBG "Stored request ID" reached host
echo_ok=False -- real #3300 bug now properly surfaced
warn_ok=False -- handler never fires (because echo unbound)
```
The `echo_ok=False` / `warn_ok=False` results are the real FastLED-side regression in #3300, finally visible instead of masked by "zero bytes" silence. The diagnosis path now hands the user a clean signal: transport works, dispatch works, the binding is missing. That's actionable. Previous behavior had two whole sessions chasing a fictitious Arduino-core LPC8xx regression (see #3325 update comment 4757727203).
ESP32 sanity
Each env resolves to its own correct port and DTR/RTS=True on monitor open is the ESP32 post-reset idle state — not a reset trigger:
```
esp32c6 -> ok=True port=COM9
esp32s3 -> ok=True port=COM22
lpc845brk -> ok=True port=COM20
```
Test plan
Refs
🤖 Generated with Claude Code
Summary by CodeRabbit