Skip to content

fix four RS485 receive-path defects, and give ArduinoLibs its first tests - #10

Merged
aphelps-claude-bot merged 2 commits into
mainfrom
rs485-receive-path-fixes
Jul 30, 2026
Merged

aphelps-claude-bot merged 2 commits into
mainfrom
rs485-receive-path-fixes

Conversation

@aphelps-claude-bot

Copy link
Copy Markdown
Collaborator

All four found by reading Nick Gammon's vendored RS485_non_blocking after the #5 self-review turned out to have checked byte-identity and packaging but never the logic. Every fix is in RS485Utils, the consumer — the vendored library is untouched and stays byte-identical to upstream, which is the property that review relied on.

(1) Stale-packet re-delivery — the real bug

On a good CRC, update() sets available_ and returns true without calling reset(), so haveSTX_/haveETX_/inputPos_ stay live past the packet. Any later valid-form byte then completes against a still-set haveETX_ and is tested as a CRC over the previous packet's buffer — and on a match update() returns true again and the caller re-processes a stale payload as fresh. Harmless for a colour command; not harmless for SET_ADDRESS, which the WLED bridge persists to flash on receipt.

Fixed with a deferred reset: a consumed packet is cleared at the top of the next getMsg(), not on the way out of this one. That ordering is deliberate, and the obvious alternative is a trap — resetting before returning zeroes inputPos_, and callers read getLength() after getMsg() returns to bounds-check the frame (the WLED bridge does exactly this), so a reset-too-early makes every frame look impossibly short and the receiver goes deaf while reporting itself healthy. There is now a test pinning that.

The flag is set on every path taken after update() returns true, not just the one that hands back a payload. The address-mismatch and length-rejection paths consume a packet too, and for consumers that filter on their own address (HMTL_Module, HMTL_Command_CLI) mismatch is the common case on a shared bus — arming it only on delivery would leave the window permanently open for exactly the callers that need it shut.

On likelihood, since my original note got this wrong in both directions: only 16 of 256 byte values pass the form check, and any that fails calls reset(), so uniform line noise is ~1/65536 per byte-pair position rather than ~1/256. The realistic trigger is a lost STX on the next legitimate frame — every byte of it is valid-form, so each byte pair gets an independent 1/256 shot: roughly 1-in-4 to 1-in-10 per dropped STX.

(2) begin() does not check malloc

Fails safe rather than crashing (update() returns false when data_ == NULL), but the result is a receiver silently dead for a whole boot while everything else looks fine.

No vendored edit was needed after all — my plan assumed one. getData() is already public, so channel->getData() != NULL after begin() is an exact test. initialized() now covers serial, channel and buffer, and the WLED bridge refuses to run when it is false. Also added the missing channel == NULL guard in getMsg(): unlike begin()'s malloc, a failed new RS485(...) was a null deref on first receive, not silent deafness.

(3) No timeout

Upstream leaves this to the caller and provides isPacketStarted()/getPacketStartTime() for it; nothing picked them up, so a frame truncated mid-flight held haveSTX_ set until the next STX arrived — unbounded, with every byte in between fed into the partial packet.

Now bounded by RS485_PACKET_TIMEOUT_MS, default 250 ms: a maximal frame is 64*2 + 4 = 132 bytes on the wire, ~47 ms at 28000 baud, so ~5× headroom. The check runs after the deferred reset, which matters — a delivered packet leaves startTime_ at its own STX time until the next call, so a timeout check placed first would read any long gap between polls as a truncated frame, and such gaps are routine (the bridge skips its whole loop while the LED strip updates, and blocks ~48 ms per transmitted frame). Also tested.

(4) getMsg()'s length checks were compiled out of release builds

They sat inside #if DEBUG_LEVEL >= DEBUG_TRACE. So a release build dereferenced msg->hdr.address out of a possibly-sub-header buffer and returned *retlen = msg->hdr.length — a sender-declared byte, up to 255 — pointing into a buffer of only recvLimit (64). Hoisted out; the ERROR_OUT label they goto'd was itself inside the conditional, so this needed restructuring into plain early returns. No third "payload ≤ buffer" check: the second already implies it, since getLength() returns inputPos_, which update() bounds by bufferSize_.

Rejections are counted in a new getRejectCount(), because getMsg() returning NULL now means either "nothing arrived" or "something arrived and was malformed", and consumers reasonably read NULL as an empty bus. Without that counter this would have traded a memory-safety hole for a silent one.

Being precise about severity: the legacy HMTL path is only partially exposed. hmtl_socket_getmsg applies three length checks of its own, none debug-gated, and the last is an exact-equality test between the socket-declared and HMTL-declared lengths — which line noise will essentially never satisfy. So this is a crafted-frame / correctness defect, not a live fleet-wide over-read.

Tests — ArduinoLibs had none at all

test/ now has an Arduino.h shim and 28 assertions over the four defects. Three shim decisions are load-bearing rather than incidental:

  • millis() is a settable counter, so the timeout tests jump time by a known amount and give the same answer every run
  • HardwareSerial is a byte queue, so a case reads as "these bytes arrived on the wire" rather than "some hardware did something"
  • malloc can be forced to fail, which is the only way to exercise defect (2) at all

Every assertion is a negative — "the bad thing no longer happens" — so each fix is paired with a negative control: disabling it must turn its tests red. Verified per fix:

fix disabled tests that go red
deferred reset stale re-delivery ×2, address-mismatch re-delivery ×2, and the timeout-ordering case
timeout stalled partial packet not abandoned
length checks over-long declared length accepted, retlen left at 255
alloc check failed allocation reports itself initialised

That control caught a bad test of my own: the address-mismatch case originally polled with the same filtered address, so it returned NULL whether or not the stale packet was re-parsed — it passed with the fix disabled, proving nothing. It polls promiscuously now.

Two things the harness had to get right, both commented in place: it must define RS485_HARDWARE_SERIAL or RS485UTILS_SUPPORTED preprocesses the whole library away and the suite silently tests nothing; and DEBUG_LEVEL stays undefined, because that is the configuration in which defect (4) exists at all.

The suite also anchors Socket's virtuals: Socket declares ten and ships no Socket.cpp, so its vtable has no home translation unit. The firmware never notices (-fno-rtti, and RS485Socket overrides all of them) but a host link does — a useful canary, since giving RS485Socket a signature that stops overriding one of them breaks the link in a way -fsyntax-only cannot catch.

Wired into the super-repo's make test, which previously reported success without running any ArduinoLibs test (there were none) or the rs485_bridge suite.

Verification

  • 28/28 host assertions, each with its negative control
  • avr-g++ 9.5 -mmcu=atmega328p compiles the changed library clean — the AVR fleet still builds
  • pio run -e ampworks and -e usermods both SUCCESS against it

Not fixed here

A full 64-byte payload still goes on the wire as 71 bytes and overflows a default 64-byte receive buffer, so the real payload ceiling is 57. Pre-existing, found while reviewing the socket-header packing PR, and tracked separately — the remedy is a behaviour choice (shrink the slot vs. cost AVR SRAM), and getRejectCount() here gives it somewhere to be counted when it lands.

Paired with aphelps/WLED#15 for the consumer side.

🤖 Generated with Claude Code

https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ

…ests

All four were found by reading Nick Gammon's vendored RS485_non_blocking after the
#5 self-review turned out to have checked byte-identity and packaging but never the
logic. Every fix is in RS485Utils, the consumer: the vendored library stays
byte-identical to upstream, which is the property that review relied on.

(1) STALE-PACKET RE-DELIVERY -- the real bug. On a good CRC, update() sets
available_ and returns true WITHOUT calling reset(), so haveSTX_/haveETX_/inputPos_
stay live past the packet. Any later valid-form byte then completes against a
still-set haveETX_ and is tested as a CRC over the PREVIOUS packet's buffer -- and on
a match update() returns true again and the caller re-processes a stale payload as
fresh. Harmless for a colour command; not harmless for SET_ADDRESS, which the WLED
bridge persists to flash on receipt.

Fixed with a DEFERRED reset: a consumed packet is cleared at the top of the next
getMsg() rather than on the way out of this one. That ordering is deliberate and the
obvious alternative is a trap -- resetting before returning would zero inputPos_,
and callers read getLength() AFTER getMsg() returns to bounds-check the frame (the
WLED bridge does exactly this), so a reset-too-early makes every frame look
impossibly short and the receiver goes deaf while reporting itself healthy. There is
now a test pinning that.

The flag is set on EVERY path taken after update() returns true, not just the one
that hands back a payload. The address-mismatch and length-rejection paths consume a
packet too, and for consumers that filter on their own address (HMTL_Module,
HMTL_Command_CLI) mismatch is the COMMON case on a shared bus -- arming it only on
delivery would leave the window permanently open for exactly the callers that need it
shut.

On likelihood, since the original note got this wrong in both directions: only 16 of
256 byte values pass the form check and any that fails calls reset(), so uniform line
noise is ~1/65536 per byte-pair position, not ~1/256. The realistic trigger is a lost
STX on the NEXT legitimate frame -- every byte of it is valid-form, so each byte pair
gets an independent 1/256 shot, i.e. roughly 1-in-4 to 1-in-10 per dropped STX.

(2) begin() DOES NOT CHECK malloc. It fails safe rather than crashing (update()
returns false when data_ == NULL) but the result is a receiver silently dead for a
whole boot while everything else looks fine. No vendored edit was needed after all:
getData() is already public, so `channel->getData() != NULL` after begin() is an
exact test. initialized() now covers serial, channel and buffer, and the WLED bridge
refuses to run when it is false. Also added the missing channel == NULL guard in
getMsg() -- unlike begin()'s malloc, a failed `new RS485(...)` was a null deref on
first receive rather than silent deafness.

(3) NO TIMEOUT. Upstream leaves this to the caller and provides isPacketStarted() /
getPacketStartTime() for it; nothing picked them up, so a frame truncated mid-flight
held haveSTX_ set until the next STX arrived -- unbounded, with every byte in between
fed into the partial packet. Now bounded by RS485_PACKET_TIMEOUT_MS, default 250 ms:
a maximal frame is 64*2 + 4 = 132 bytes on the wire, ~47 ms at 28000 baud, so ~5x
headroom. The check runs AFTER the deferred reset, which matters -- a delivered packet
leaves startTime_ at its own STX time until the next call, so a timeout check placed
first would read any long gap between polls as a truncated frame, and such gaps are
routine (the bridge skips its whole loop while the LED strip updates and blocks ~48 ms
per transmitted frame). Also tested.

(4) getMsg()'s LENGTH CHECKS WERE COMPILED OUT OF RELEASE BUILDS -- they sat inside
`#if DEBUG_LEVEL >= DEBUG_TRACE`. So a release build dereferenced msg->hdr.address out
of a possibly-sub-header buffer and returned *retlen = msg->hdr.length, a
sender-declared byte up to 255, pointing into a buffer of only recvLimit (64). Hoisted
out (the ERROR_OUT label they goto'd was itself inside the conditional, so this needed
restructuring into plain early returns). No third "payload <= buffer" check: the second
already implies it, since getLength() returns inputPos_ which update() bounds by
bufferSize_.

Rejections are counted in a new getRejectCount(), because getMsg() returning NULL now
means either "nothing arrived" or "something arrived and was malformed" and consumers
reasonably read NULL as an empty bus. Without that counter this would have traded a
memory-safety hole for a silent one.

To be precise about severity: the legacy HMTL path is only PARTIALLY exposed.
hmtl_socket_getmsg applies three length checks of its own, none debug-gated, and the
last is an exact-equality test between the socket-declared and HMTL-declared lengths
-- which line noise will essentially never satisfy. So this is a crafted-frame /
correctness defect, not a live fleet-wide over-read.

TESTS: ArduinoLibs had no test infrastructure at all. test/ now has an Arduino.h shim
(settable millis() so the timeout tests are deterministic, HardwareSerial as a byte
queue so a case reads as "these bytes arrived", forceable malloc failure for defect 2)
and 28 assertions over the four defects.

Every one is a negative -- "the bad thing no longer happens" -- so each is paired with
a negative control: disabling a fix must turn its tests red. Verified per fix. That
caught a bad test of my own: the address-mismatch re-delivery case originally polled
with the same filtered address and so returned NULL whether or not the stale packet
was re-parsed, passing even with the fix disabled. It polls promiscuously now.

Two things the harness had to get right, both noted in the files: it MUST define
RS485_HARDWARE_SERIAL or RS485UTILS_SUPPORTED preprocesses the whole library away and
the suite silently tests nothing; and DEBUG_LEVEL stays undefined, because that is the
configuration in which defect (4) exists at all.

The suite also has to anchor Socket's virtuals: Socket declares ten and ships no
Socket.cpp, so its vtable has no home TU. The firmware never notices (-fno-rtti, and
RS485Socket overrides all of them) but a host link does -- which is a useful canary,
since giving RS485Socket a signature that stops overriding one of them breaks the link
in a way -fsyntax-only cannot catch.

Verified: 28/28 host assertions, each with its negative control; avr-g++ 9.5
-mmcu=atmega328p compiles the changed library clean (the AVR fleet still builds);
`pio run -e ampworks` and `-e usermods` both SUCCESS against it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ
…o work

The worst of five findings, and a regression I introduced rather than a
pre-existing bug.

startTime_ is stamped when update() *parses* the STX, not when the bytes hit the
UART -- so the elapsed time the timeout measures is POLL LATENCY, not wire time. With
the check running before update(), a caller that parsed a partial frame and then got
busy for longer than the timeout would come back, discard that frame, and only then
drain the FIFO -- throwing away a frame whose remaining bytes had already arrived and
which would have completed fine before the timeout existed. Those stalls are routine
in the consumer this was written for: WLED skips the usermod's whole loop while the
LED strip updates, blocks ~48 ms per transmitted frame, and writes flash on
SET_ADDRESS.

Now the check runs AFTER update() returns false: drain first, so anything that can
complete does, and only a genuinely stalled frame is abandoned. Test 13 pins it, and
reordering the two back the wrong way turns it red.

The same finding exposed a second half. RS485_PACKET_TIMEOUT_MS is compile-time but
baud is runtime-configurable from the bridge's settings page, and a maximal frame at
4800 baud is 275 ms on the wire -- longer than the 250 ms default. Every full-size
frame would have been killed mid-flight while small ones got through, with no way to
raise the bound short of a rebuild. Added setPacketTimeoutForBaud(), which derives
5x the wire time and floors it at the default; the bridge calls it with its configured
baud. Test 15 covers both directions.

Also from the review:

* The channel == NULL guard in getMsg() was unreachable on the path it was written
  for: setup() dereferences channel first, so a failed `new RS485(...)` (which returns
  NULL on AVR -- the case that matters, since ESP32 aborts instead) crashed one line
  before initialized() could report it. Guarded setup() and getLength() too.

* Counters are uint16_t, not unsigned long. The plan said the new state must not grow
  RS485Socket in a way that matters on a 2 KB-SRAM part; two longs plus a bool is 9
  bytes per socket, and 5 does the same job. Wrapping is harmless for a diagnostic,
  and the bridge's before/after comparison survives it.

* Two tests proved nothing and are now deterministic. The valid-form-noise case
  started at byte 0x00, which mismatches the stale CRC and makes the UNFIXED library
  call reset() by itself -- it passed with the fix disabled. It starts at the stale
  CRC value now. The runt-frame case read hdr.address out of a freshly-malloc'd
  buffer, so on a clean heap the garbage rarely matched and the test passed without
  the fix; it now primes the buffer with a real frame first.

  That is two bad negative controls found in one review, both of the same shape: the
  test could not distinguish the fix from the absence of the fix.

* Three uncovered paths now tested: two complete frames in one burst (the commonest
  real sequence, and the one the deferred reset most directly serves), a frame
  completing across a long poll gap (the regression above), and interleaving the two
  getMsg() overloads, which share the msgPending contract.

45 assertions, up from 28. Every fix still has a negative control that turns its tests
red; re-verified per fix after these changes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ
@aphelps-claude-bot

Copy link
Copy Markdown
Collaborator Author

Self-review found a regression I introduced — fixed in 538a01b

Worth stating plainly: the worst of these is my own regression, not a pre-existing bug.

startTime_ is stamped when update() parses the STX, not when bytes hit the UART — so the elapsed time the timeout measures is poll latency, not wire time. With the check running before update(), a caller that parsed a partial frame and then got busy for longer than the timeout would come back, discard that frame, and only then drain the FIFO — throwing away a frame whose remaining bytes had already arrived, and which would have completed fine before the timeout existed.

Those stalls are routine in the consumer this was written for: WLED skips the usermod's whole loop while the LED strip updates, blocks ~48 ms per transmitted frame, and writes flash on SET_ADDRESS. So this would have shown up on the bench as intermittent frame loss under load — and it would have looked like a wiring or noise problem.

The check now runs after update() returns false: drain first, so anything that can complete does, and only a genuinely stalled frame is abandoned. Test 13 pins it, and reordering the two back the wrong way turns it red.

The same finding had a second half

RS485_PACKET_TIMEOUT_MS is compile-time, but baud is runtime-configurable from the bridge's settings page — and a maximal frame at 4800 baud is 275 ms on the wire, longer than the 250 ms default. Every full-size frame would have been killed mid-flight while small ones got through, with no way to raise the bound short of a rebuild. setPacketTimeoutForBaud() derives 5× the wire time and floors it at the default; the bridge calls it with its configured baud. Test 15 covers both directions.

Also fixed

  • The channel == NULL guard was unreachable on the path it was written for. setup() dereferences channel first, so a failed new RS485(...) — which returns NULL on AVR, the case that actually matters, since ESP32 aborts instead — crashed one line before initialized() could report it. setup() and getLength() are guarded too now.
  • Counters are uint16_t. The plan said the new state must not grow RS485Socket in a way that matters on a 2 KB-SRAM part; two unsigned longs plus a bool is 9 bytes per socket, and 5 does the same job. Wrapping is harmless for a diagnostic, and the bridge's before/after comparison survives it.

Two of my tests proved nothing

Both of the same shape — the test could not distinguish the fix from the absence of the fix:

  • the valid-form-noise case started at byte 0x00, which mismatches the stale CRC and makes the unfixed library call reset() all by itself. It passed with the fix disabled. It starts at the stale CRC value now, so the unfixed code re-delivers on the first pair.
  • the runt-frame case read hdr.address out of a freshly-malloc'd buffer, so on a clean heap the garbage rarely matched MY_ADDR and it passed without the fix. It primes the buffer with a real frame first now.

That is the second review in a row to catch a test of mine that couldn't fail. The pattern I'm taking from it: writing the negative control is not optional, and "the suite is green" is not evidence until I've watched it go red.

Three uncovered paths added

Two complete frames in one burst (the commonest real sequence, and the one the deferred reset most directly serves); a frame completing across a long poll gap (the regression above); and interleaving the two getMsg() overloads, which share the msgPending contract.

45 assertions, up from 28. Every fix still has a negative control that turns its tests red, re-verified per fix after these changes. avr-g++ -mmcu=atmega328p still compiles the library clean, pio run -e ampworks SUCCESS, make test green across all four suites.

Checked and clean, recorded so it isn't re-litigated

millis() rollover is handled (unsigned subtraction, gated on isPacketStarted() so the post-reset() startTime_ == 0 can't be misread). The rejectCount before/after comparison is reliable — getMsg() can increment it at most once per call. delete port after port->begin() is safe on the pinned core (~HardwareSerial() → end() → uartEnd() detaches pins and deletes the driver), and setup() cannot be called twice.

@aphelps-claude-bot
aphelps-claude-bot merged commit bceedb3 into main Jul 30, 2026
@aphelps-claude-bot
aphelps-claude-bot deleted the rs485-receive-path-fixes branch July 30, 2026 02:53
aphelps-claude-bot added a commit to aphelps/WLED_dev that referenced this pull request Jul 30, 2026
)

* bump submodules: RS485 receive-path fixes + first ArduinoLibs tests

ArduinoLibs 6d1de81 -- fixes the four receive-path defects found auditing the
vendored RS485_non_blocking (stale-packet re-delivery, unchecked malloc, no packet
timeout, length checks compiled out of release builds) and adds test/, the first test
infrastructure in that repo: an Arduino.h shim plus 28 assertions, each paired with a
negative control that confirms disabling the fix turns them red.
WLED 0cf79a01 -- bridge side: refuse to run on a failed socket alloc, and keep
rejected frames counted now that a NULL from getMsg() no longer means "bus empty".

Also extends `make test` to cover two suites it silently skipped: the new ArduinoLibs
receive-path tests, and the rs485_bridge wire-format tests, which had to be run by
hand and are now run on BOTH ABIs (native and -fpack-struct=1) since the point of most
of those assertions is that the two agree.

  make test  ->  ampworks sensor-sync + rs485_bridge (x2 ABIs) + ArduinoLibs + router

  aphelps/ArduinoLibs#10
  aphelps/WLED#15

Submodule PRs merge first; these pointers are re-pointed at the merged shas before
this lands.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ

* bump submodules: self-review fixes on the receive-path stack

ArduinoLibs 538a01b -- the packet timeout measured poll latency rather than wire
time, so with the check running before update() it could discard a frame whose
remaining bytes were already in the FIFO: a regression against pre-timeout behaviour,
not a pre-existing bug. Now checked after update(), plus a baud-derived timeout
(fixed 250 ms killed every full-size frame at 4800 baud), reachable NULL guards, and
uint16_t counters to keep the ATmega328 footprint down. Two of the new tests turned
out to pass with their fix disabled and are now deterministic; three uncovered paths
added. 45 assertions, up from 28.
WLED 2b5baa2c -- scale the timeout to the configured baud, surface timeouts on the
info page (the counter existed but nothing read it), and correct two comments that
still said the library's length checks are compiled out of release builds.

Makefile: test-bridge guards HMTL and ArduinoLibs too, not just WLED. It compiles
against headers from all three, so on a fresh clone with uninitialised submodules a
bare `make` failed with a confusing missing-header error from the compiler instead of
the "run ./setup.sh" message require_submodule exists to print.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ

* re-point submodules at the merged receive-path commits

ArduinoLibs bceedb3 (#10) -- four receive-path defects fixed, plus test/: the first
test infrastructure in that repo (45 assertions, each with a verified negative
control).
WLED cdfef9c0 (#15) -- bridge side: refuse to run on a failed socket alloc, scale the
receive timeout to the configured baud, surface timeouts on the info page, keep
rejected frames counted.

Both squash-merged, so this replaces the branch-tip pointers this PR opened with.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ

---------

Co-authored-by: aphelps-claude-bot <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant