Skip to content

vendor Gammon's RS485_non_blocking + make RS485Utils portable - #5

Merged
aphelps-claude-bot merged 1 commit into
mainfrom
rs485-bridge-usermod
Jul 30, 2026
Merged

aphelps-claude-bot merged 1 commit into
mainfrom
rs485-bridge-usermod

Conversation

@aphelps-claude-bot

@aphelps-claude-bot aphelps-claude-bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Collaborator

Part of aphelps/WLED_dev#20 in the parent repo.

Summary

Makes RS485Utils usable from a portable PlatformIO build — prerequisite for the new
rs485_bridge WLED usermod.

  • Vendor Nick Gammon's RS485_non_blocking 1.0 verbatim into RS485_non_blocking/.
    RS485Utils hard-includes <RS485_non_blocking.h>, which previously only existed in a
    machine-local Arduino libraries folder, so every consumer had to point lib_dir at it.
    LICENSE.txt records the upstream author, source URL and the "Released for public use."
    notice reproduced verbatim, and states that there are no local modifications.
  • Add library.json manifests for Socket, RS485Utils and RS485_non_blocking, each
    declaring platforms: ["atmelavr", "espressif32"] — required under lib_compat_mode = strict
    (which WLED uses), matching the existing MPR121/Debug manifests.
  • Drop the machine-specific lib_dir from the three RS485 example projects
    (RS485SocketTool, SocketTestMaster, SocketTestSlave) in favour of a repo-relative
    lib_extra_dirs = ${PROJECT_DIR}/../...
  • New RS485UTILS_SUPPORTED guard. SoftwareSerial is AVR-only, so on a non-AVR target
    without RS485_HARDWARE_SERIAL the library used to fail to compile. It now compiles to
    nothing instead. This matters because WLED's CI puts all of ArduinoLibs on
    PLATFORMIO_LIB_EXTRA_DIRS, and PlatformIO's chain LDF does not evaluate preprocessor
    conditionals — so it pulls RS485Utils into build matrix targets that set none of the RS485
    flags. Guard any use of RS485Socket with #if RS485UTILS_SUPPORTED.
  • Give the file-scope serial pointer internal linkage. A bare global named serial with
    external linkage is a link-time collision hazard once RS485Utils.cpp is compiled into a
    larger firmware image. Only this translation unit's static callbacks use it.

No behavioural change on AVR or on ESP32 with RS485_HARDWARE_SERIAL defined.

Test plan

Automated (run from the parent WLED_dev super-repo, which consumes this via
lib_extra_dirs):

  • cd WLED && pio run -e ampworks — firmware links RS485Utils, Socket and
    RS485_non_blocking from ArduinoLibs; no new warnings.
    RAM: [=== ] 25.3% (used 82856 bytes from 327680 bytes) Flash: [======== ] 83.6% (used 1315033 bytes from 1572864 bytes) ampworks SUCCESS 00:00:27.376
  • pio pkg list -e ampworks — dependencies resolve from repo-relative paths, no
    machine-local lib_dir.
    ├── RS485Utils @ 0.0.0+... (required: .../ArduinoLibs/RS485Utils) │ ├── RS485_non_blocking @ 1.0.0 (required: RS485_non_blocking) │ └── Socket @ 0.0.0+... (required: Socket)
  • grep -rnE '/Users/|/home/|\blib_dir\b' ArduinoLibs/RS485Utils WLED/platformio.ini —
    no matches (exit 1).
  • The RS485UTILS_SUPPORTED guard verified against the exact failure it prevents: with
    PLATFORMIO_LIB_EXTRA_DIRS pointed at ArduinoLibs (what WLED CI does), the
    pre-guard tree failed with 'SoftwareSerial' has not been declared in
    RS485Utils.h:42; post-guard, pio run -e usermods, usermods_esp32,
    usermods_esp32c3, usermods_esp32s2 and usermods_esp32s3 are all green.
    usermods_esp32 SUCCESS usermods_esp32c3 SUCCESS usermods_esp32s2 SUCCESS usermods_esp32s3 SUCCESS

Manual (hardware, tracked on the parent PR): RS485 transceiver bring-up on an ESP32.

RS485Utils hard-includes <RS485_non_blocking.h>, which previously only existed
in a machine-local Arduino libraries folder — every PlatformIO project using it
had to point lib_dir there, so the build was not portable.

- Vendor Nick Gammon's RS485_non_blocking 1.0 verbatim (LICENSE.txt records the
  upstream author, source URL and the "Released for public use." notice; no
  local modifications), with a library.json declaring atmelavr + espressif32.
- Add library.json manifests for Socket and RS485Utils so they resolve under
  lib_compat_mode = strict.
- Drop the machine-specific lib_dir from the three RS485 example projects in
  favour of a repo-relative lib_extra_dirs.
- Guard RS485Utils with RS485UTILS_SUPPORTED: SoftwareSerial is AVR-only, so
  without RS485_HARDWARE_SERIAL on a non-AVR target the library now compiles to
  nothing instead of failing. That keeps this directory harmless for projects
  that merely have ArduinoLibs on lib_extra_dirs (e.g. WLED's build matrix).
- Give the file-scope `serial` pointer internal linkage; a bare global of that
  name is a link-time collision hazard inside a larger firmware image.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ

@aphelps-claude-bot aphelps-claude-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Follow-up self-review of this PR's commit (b805d19, vendor RS485_non_blocking + make RS485Utils portable), reviewed standalone; the prior combined-set review lives on WLED_dev#20.

Prior issues:

  • Findings 1-7 of the prior review all concern WLED#11 usermod code; nothing in this commit touches them, so they remain open on WLED#11.
  • Addressed here: the bare-global serial link-collision hazard (flagged in the plan notes) - RS485Utils.cpp now gives it internal linkage (static), and a grep confirms no other TU declares an extern for it.

Verified clean in this commit:

  • The vendored RS485_non_blocking is byte-identical to the machine-local copy previous builds actually linked (diff against /Users/amp/Dropbox/Arduino/libraries/RS485_non_blocking/ - both files identical), so beyond LICENSE.txt's upstream-fidelity claim there is no behavioral drift vs. the framing the deployed HMTL modules speak.
  • The RS485UTILS_SUPPORTED guard strands no in-repo consumer: all three touched example projects define RS485_HARDWARE_SERIAL=2 in their esp32 envs and their nano envs are __AVR__; and the unsupported-case includes (Socket.h, RS485_non_blocking.h) stay resolvable because any platform that lib_compat_mode = strict would filter out of those manifests also filters out RS485Utils itself.
  • The new library.json manifests follow the existing MPR121/Debug pattern (include, platforms: ["atmelavr", "espressif32"]), which strict compat mode requires.

New issues: one minor, posted inline (registry-fallback hazard of name-only manifest dependencies).

  • Nice-to-have (pre-existing, out of scope): six other platformio/* projects still carry the machine-specific lib_dir (ExampleCLI, DebugExample, MPR121Multiple, MPR121BasicUse, PixelExample, XBeeSocketTest) - LICENSE.txt acknowledges this; fine to leave, none are on this task's build path.

Comment thread RS485Utils/library.json Resolved
aphelps-claude-bot added a commit to aphelps/WLED that referenced this pull request Jul 30, 2026
`Build Environments (usermods)` failed with

    _temp/ArduinoLibs/RS485Utils/RS485Utils.cpp:17:10:
      fatal error: RS485_non_blocking.h: No such file or directory

The rs485_bridge translation unit is correctly guarded and compiles to
nothing in `[env:usermods]`, but PlatformIO's Library Dependency Finder
runs in `chain` mode, which scans `#include` lines without evaluating
preprocessor conditionals. It sees `#include "RS485Utils.h"` inside the
disabled `#if RS485_BRIDGE_BUILD` block anyway, pulls RS485Utils out of
ArduinoLibs and compiles it — a library nothing in this env links
against. RS485Utils.cpp then includes <RS485_non_blocking.h> above its
own RS485UTILS_SUPPORTED guard, and the CI workflows clone ArduinoLibs'
*default* branch, which does not carry that vendored sibling library
(it lands with aphelps/ArduinoLibs#5). So the build died on a dependency
of a dependency this env never asked for, and LDF fell through to a
registry lookup for it.

`lib_ignore = RS485Utils` drops it from the dependency graph, which is
what actually matches reality here: with the bridge compiled out, no
translation unit in this env can reference an RS485Utils symbol. This
holds in both layouts — the super-repo checkout where
`${PROJECT_DIR}/../ArduinoLibs` resolves, and the standalone CI clone
that appends PLATFORMIO_LIB_EXTRA_DIRS — and it does not depend on
which ArduinoLibs revision CI happens to clone.

Verified by reproducing CI exactly: a standalone clone of this branch
with no `../ArduinoLibs` sibling, built against a clone of ArduinoLibs'
default branch on PLATFORMIO_LIB_EXTRA_DIRS. Fails with the identical
error before this commit; clean-builds after. `pio run -e usermods`,
`-e ampworks`, `-e esp32dev`, `-e apa102_mpr121` and all four
`usermods_esp32*` matrix envs still pass from the super-repo layout.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ
@aphelps-claude-bot
aphelps-claude-bot merged commit fb9c957 into main Jul 30, 2026
@aphelps-claude-bot
aphelps-claude-bot deleted the rs485-bridge-usermod branch July 30, 2026 00:24
aphelps-claude-bot added a commit to aphelps/WLED that referenced this pull request Jul 30, 2026
* add rs485_bridge usermod: wifi <-> RS485 HMTL bridge

New usermod that gives a WLED ESP32 an RS485 port (ArduinoLibs' RS485Socket over
hardware serial) and bridges the HMTL protocol in both directions:

- Master (WiFi -> RS485): a UDP listener on port 21331 accepts raw HMTL frames,
  validates them and transmits them onto the bus. sendMsgTo blocks while it
  flushes the UART (~48 ms for a 64 B payload at 28000 baud), so at most one
  frame goes out per loop() and the rest sit in a 4-slot drop-oldest ring — a
  UDP flood cannot stall the LED refresh.
- Slave (RS485 -> WLED): frames addressed to this node or broadcast drive the
  main segment (RGB / VALUE / a small program-to-effect map) and answer POLL and
  SET_ADDRESS so the bridge is a proper HMTL bus citizen. Sensor broadcasts and
  frames for other nodes are relayed to the last WiFi peer. Everything else is
  counted and ignored.

The wire format and every parsing/queueing decision live in the dependency-free
rs485_bridge_protocol.h (host unit-tested in tests/), mirroring the
sensor_sync_protocol.h split. HMTL's own libraries stay off the build path:
they transitively pull FastLED/PixelUtil/EEPromUtils/MPR121/XBeeSocket, so only
the framing (header, type codes, CRC-8 poly 0xD8) is vendored.

Bounds checking is done in the usermod because RS485Utils' own length checks sit
inside `#if DEBUG_LEVEL >= DEBUG_TRACE` and vanish in release builds. GPIOs are
reserved through PinManager (new PinOwner::UM_RS485_BRIDGE) all-or-nothing, so
the UART is never opened on a half-allocated pin set; note isPinOk() rejects the
default GPIO 16/17 on PSRAM boards, which the readme calls out. UART/pin/baud
changes apply on reboot only — RS485Utils leaks on re-init().

The whole translation unit is guarded on USERMOD_RS485_BRIDGE +
RS485_HARDWARE_SERIAL + ESP32, with an inert placeholder usermod standing in
elsewhere so the `usermods` wildcard env and the per-usermod CI matrix (which
set none of those flags, and have no UART 2 on C3/S2) still build and still get
compile coverage of the protocol header. `[env:usermods]` gains lib_extra_dirs
so the AMPWorks usermods can resolve ArduinoLibs there at all.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ

* document every rs485_bridge function and the reasoning behind its checks

Addresses the CHANGES_REQUESTED review on #11: every function now
carries a description covering what it does, its params/return where those are
not obvious, and the protocol or hardware constraint a reader needs to follow
it. Inline commentary explains rationale rather than restating the next line.

Particular attention, as requested:

* HMTL wire format — why the CRC must stay a byte-for-byte transcription of
  ArduinoLibs' EEPROM_crc, why rs485b_hmtl_crc() substitutes a zero at offset 1
  (idempotent stamping), why rs485b_hmtl_fmt() needs the payload in place first
  and why sendPollResponse() therefore re-stamps, and the little-endian
  bitfield assumption behind HmtlMsgValue.
* Bounds/validation — rs485b_validate()'s check ordering documented as never
  reading a byte it has not already justified; the per-payload length re-checks
  in rs485b_decide() explained as non-redundant with validation; the three
  socket-layer tests in serviceRs485() spelled out, including that RS485Utils'
  own checks are compiled out of release builds; rs485b_next_sensor()'s two
  bounds tests framed as what makes a hostile data_len harmless.
* Blocking-send rate limiting — why sendMsgTo() cannot release DE early on a
  half-duplex bus, the ~48 ms figure it implies, why that makes one frame per
  loop() the safe budget, and why the queue is drop-oldest (freshest lighting
  command is the one worth delivering) and fixed-size (no heap in a usermod
  running for months).
* PinManager path — why an unregistered pin is one the LED-bus settings page
  will hand to a strip, why allocateMultiplePins()' all-or-nothing rollback
  matters, and the isPinOk()/PSRAM interaction that makes the RX16/TX17
  defaults fail on WROVER boards.

Comments only; no behaviour change. Host tests pass, ampworks and usermods
envs build clean.

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

* import the HMTL wire format instead of vendoring it

Answers the review question on rs485_bridge_protocol.h: "Why isn't this
imported from the HMTL libraries? Seems like a lot of unnecessary copy
and paste."

The header no longer declares the wire format at all. It includes
HMTLWireFormat.h from the HMTL submodule -- extracted upstream in
aphelps/HMTL#6 for exactly this purpose -- and all ~150 vendored lines
are gone: msg_hdr_t, output_hdr_t, config_hdr_t, the msg_* payload
structs, MSG_TYPE_* / MSG_FLAG_*, HMTL_OUTPUT_*, HMTL_PROGRAM_*,
HMTL_SENSOR_*, HMTL_MSG_START / _VERSION / _MAX_MSG_LEN. There is now
one definition of the format, in the repo that owns it, and the local
Hmtl* struct spellings are replaced by HMTL's own names throughout the
usermod and the test.

What stays in rs485_bridge_protocol.h is bridge-specific: frame
validation, the pure receive-path decision function, the bounded
transmit queue and the counters -- plus two algorithm reimplementations
that cannot be linked rather than declarations that were copied:

  * rs485b_crc8() -- ArduinoLibs' EEPROM_crc lives in EEPromUtils.cpp
    behind AVR-only EEPROM.h and is not inline, so neither the ESP32
    firmware nor the host test can link it.
  * rs485b_hmtl_fmt() / rs485b_next_sensor() -- the HMTL equivalents
    (hmtl_msg_fmt, hmtl_next_sensor) live in HMTLMessaging.cpp behind
    Debug.h and HMTLPrograms.h -> FastLED.h.

Both are pinned by the host test, which now compiles the real HMTL and
ArduinoLibs headers with a plain c++ -- making it the standing check
that HMTLWireFormat.h stays free of Arduino.h / RS485Utils.h.

Behaviour notes:

  * The POLL response length is now HMTL's own HMTL_MSG_POLL_MIN_LEN,
    i.e. exactly what hmtl_poll_fmt() puts on the wire for this target:
    24 bytes on ESP32 where uint16_t alignment adds a trailing pad byte
    to msg_poll_response_t, versus the 23 the packed vendored copy
    emitted. Only trailing padding differs, so every field still lands
    at the same offset for a legacy master.
  * rs485_bridge_protocol.h is no longer compiled in the flagless
    builds ([env:usermods] and the per-usermod CI matrix): it now
    depends on the HMTL submodule, which is only on the build path in
    the ampworks env and is not cloned by the CI workflows. The inert
    placeholder usermod still provides the DWARF compilation unit that
    validate_modules.py requires, and the wire-layout static_asserts are
    covered by `pio run -e ampworks` and the host test instead.

Build wiring: ../HMTL/Libraries added to lib_extra_dirs and
../HMTL/Libraries/HMTLprotocol to lib_deps in [env:ampworks] only, with
a comment on [env:usermods] explaining why it is deliberately absent
there.

Also fixes the four comment-accuracy points from review 4793843525:

  * loop() -- the receive/transmit/ingest order is not what enforces the
    rate limit; serviceTx()'s one-frame budget is. Reworded.
  * handleDecision() -- rs485Handled is weaker than "a v1 command was
    executed against local state"; the PROGRAM-bails-inside-applyProgram
    and SENSOR-only-relays caveats are now stated.
  * rs485b_next_sensor() -- the no-wrap guarantee comes from the operand
    ranges under size_t arithmetic, not from signed int promotion.
  * getId() -- described, on both the main class and the placeholder.

Test: host test 50-odd assertions pass under
  c++ -std=c++11 -Wall -Wextra -I HMTL/Libraries/HMTLprotocol \
      -I ArduinoLibs/Socket ...
sensor_sync host test still passes; pio run green for ampworks,
esp32dev, usermods, apa102_mpr121 and the usermods_esp32{c3,s2,s3} CI
matrix; no new warnings.

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

* pin msg_poll_response_t layout in the host test; correct the packed-struct comment

Two review nits from wled#11 self-review 4794753753.

Comment accuracy: the static_assert block claimed HMTL declares all eight
asserted structs without __attribute__((packed)). False for output_hdr_t,
which HMTLWireFormat.h:130 does declare packed -- and which is embedded in
msg_value_t / msg_rgb_t / msg_program_t, so the wrong claim covered exactly
the structs a reader cares most about. The assertions themselves are
unchanged; only the rationale was wrong.

Suggested test, routed into the plan's Test Plan and run: msg_poll_response_t
is the one wire struct the assert block deliberately omits, because its size
is ABI-dependent (config_hdr_t is 10 B with align 1 on AVR, align 2 where
uint16_t demands it, so the struct is 15 B or 16 B). The claim that only
trailing padding differs and every field offset is identical was prose in the
header and in the plan's hardware-test note. Group 1 of the host test now
asserts offsetof for all five fields (0/10/12/14/15), bounds sizeof to 15 or
16, and ties HMTL_MSG_POLL_MIN_LEN to the two struct sizes. An upstream
HMTLWireFormat.h edit that moves a field now fails the host test; legitimate
padding drift still passes. Verified on both ABIs -- plain c++ and the same
build with -fpack-struct=1 -- both ALL TESTS PASSED.

Comments and tests only, zero behaviour change.

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

* pin the wire layout to the now-uniform packed sizes

HMTL now declares every wire struct __attribute__((__packed__))
(aphelps/HMTL#6, per Adam's directive that one format has to serve both an
ATMega328 and an ESP32 because they are communicating), which changes struct
sizes on this side.

rs485_bridge_protocol.h's static_assert block is updated to the uniform
values and its rationale rewritten. It used to say output_hdr_t was the only
packed struct, that the other seven relied on their field ordering happening
to avoid padding, and that msg_poll_response_t was "the one struct whose size
is ABI-dependent" and therefore exempt. None of that is true any more: there
is no struct left to exempt, so msg_poll_response_t (15 B) and
HMTL_MSG_POLL_MIN_LEN (23) are asserted like the rest, along with
config_hdr_v1/v2_t and the two zero-size FAM structs. The wire-visible
consequence is that the bridge's POLL response is 23 B rather than 24 B -
byte-for-byte what a deployed AVR module emits and length-checks.

Host test group 1 now pins the exact size and every field offset of every
wire struct rather than bounding msg_poll_response_t to 15-or-16, adds
config_hdr_v2_t (the interior-padding case: address at offset 3, not 4), and
checks the msg_value_t 13/3 bitfield split at byte level - packing a struct
containing bitfields is the one case where the attribute could have moved
more than padding.

Two changes to keep the new "compile with g++ >= 9 as well as clang" gate
warning-free, both zero-behaviour:

* dropped the dead `frameLen > 255` test in rs485b_validate_udp_ingress
  (frameLen is a uint8_t, so g++ -Wtype-limits is right that it can never
  fire; the 255 ceiling sendMsgTo's `byte` length imposes is enforced by the
  type). The maxPayload bound it sat next to is unchanged.
* removed the line continuations from a // comment block (-Wcomment).

readme gains the packing rationale and a local-edit gotcha worth knowing:
HMTLprotocol is a file:// lib_dep, so PlatformIO caches a copy under
.pio/libdeps/<env>/ and an edit to HMTLWireFormat.h has no effect until that
copy is cleared - which means a stale copy silently checks the old layout.

Verified: rs485_bridge_test passes under clang 21 and g++ 16, each with and
without -fpack-struct=1, all four warning-free and reporting identical sizes
and offsets. pio run -e ampworks / esp32dev / usermods / apa102_mpr121 and
the usermods_esp32c3/s2/s3 CI matrix envs all build clean.

Part of aphelps/WLED_dev#20

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

* keep RS485Utils out of the usermods wildcard env

`Build Environments (usermods)` failed with

    _temp/ArduinoLibs/RS485Utils/RS485Utils.cpp:17:10:
      fatal error: RS485_non_blocking.h: No such file or directory

The rs485_bridge translation unit is correctly guarded and compiles to
nothing in `[env:usermods]`, but PlatformIO's Library Dependency Finder
runs in `chain` mode, which scans `#include` lines without evaluating
preprocessor conditionals. It sees `#include "RS485Utils.h"` inside the
disabled `#if RS485_BRIDGE_BUILD` block anyway, pulls RS485Utils out of
ArduinoLibs and compiles it — a library nothing in this env links
against. RS485Utils.cpp then includes <RS485_non_blocking.h> above its
own RS485UTILS_SUPPORTED guard, and the CI workflows clone ArduinoLibs'
*default* branch, which does not carry that vendored sibling library
(it lands with aphelps/ArduinoLibs#5). So the build died on a dependency
of a dependency this env never asked for, and LDF fell through to a
registry lookup for it.

`lib_ignore = RS485Utils` drops it from the dependency graph, which is
what actually matches reality here: with the bridge compiled out, no
translation unit in this env can reference an RS485Utils symbol. This
holds in both layouts — the super-repo checkout where
`${PROJECT_DIR}/../ArduinoLibs` resolves, and the standalone CI clone
that appends PLATFORMIO_LIB_EXTRA_DIRS — and it does not depend on
which ArduinoLibs revision CI happens to clone.

Verified by reproducing CI exactly: a standalone clone of this branch
with no `../ArduinoLibs` sibling, built against a clone of ArduinoLibs'
default branch on PLATFORMIO_LIB_EXTRA_DIRS. Fails with the identical
error before this commit; clean-builds after. `pio run -e usermods`,
`-e ampworks`, `-e esp32dev`, `-e apa102_mpr121` and all four
`usermods_esp32*` matrix envs still pass from the super-repo layout.

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 Fable 5 <[email protected]>
aphelps-claude-bot added a commit that referenced this pull request Jul 30, 2026
…ests (#10)

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

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

* address self-review: the packet timeout could lose frames that used to 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

---------

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.

2 participants