Repository navigation
add rs485_bridge usermod: wifi <-> RS485 HMTL bridge - #11
Conversation
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
aphelps
left a comment
There was a problem hiding this comment.
This PR doesn't look like it has had a self-review. If thats correct investigate if a new todo-handler task should be added to fix this.
aphelps-claude-bot
left a comment
There was a problem hiding this comment.
Good catch, and your read is right from this PR's vantage point — though the review did happen, it just isn't here.
The combined self-review lives entirely on the base PR: WLED_dev#20 review 4783222046. It opens by naming this PR explicitly ("Self-review of the combined change set: this PR plus submodule PRs ArduinoLibs#5 and wled#11"), and all 7 of its findings are about the rs485_bridge usermod code in this PR — none are about #20's own diff, which is just submodule pointers, the CLAUDE.md table, and setup.sh strings. Findings 1, 2 and 4 were verified against the reference HMTL/Libraries/HMTLMessaging/ implementation at the pinned submodule commit.
That placement is what SKILL.md currently mandates — Task Execution step 9 reviews base + all submodule diffs together but says to "post the review on the base repo PR only." For a change whose substance is in a submodule, that's backwards: this PR carries the actual implementation, it merges first (submodule PRs before the parent), and it shows no review at all. The findings also can't be inline-anchored or resolved as threads against the diff lines they describe.
Filed as a todo-handler task: "Post self-review findings on the submodule PR that owns the code, not only the base PR" — post each finding on the PR owning the file, with the base PR carrying a linking summary. It's noted as interacting with the existing track-reviewed-sha-per-pr task, since both come from multi-repo tasks being modelled as a single PR.
For this PR right now: the 7 findings on #20 are the review — worth reading there before approving here. This PR is also still unapproved, which blocks the whole stack, since submodule PRs merge ahead of the parent.
aphelps
left a comment
There was a problem hiding this comment.
This does not have my usual requested level of commenting. My standard is that every function should have a description, and enough inline comments so that a reader can understand what is being done just from the comments
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
aphelps-claude-bot
left a comment
There was a problem hiding this comment.
Fair — the commenting was uneven: the tricky spots had notes but a lot of functions had no description at all, and several comments said what the next line did rather than why it was there. Fixed in 87ac5e2 (new commit, nothing squashed).
Every function across the four files now carries a description — what it does, params/return where they aren't obvious, and the protocol or hardware constraint a reader needs to follow it. That includes the ones that previously had nothing: effectiveDeviceId, releasePins, setup, connected, loop, serviceRs485, serviceUdp, handleDecision, applyRgb, applyProgram, sendPollResponse, relayToPeer, addToJsonInfo, addToConfig, readFromConfig, rs485b_crc8, countError, the RS485BTxQueue accessors, and all seven test-frame builders. The declarations in the header got one-line summaries too, so the class reads as an index.
On the four areas you'd want the reasoning for:
HMTL wire format. Why rs485b_crc8 must stay a byte-for-byte transcription of ArduinoLibs' EEPROM_crc (poly 0xD8, init 0, MSB-first, no reflection) and what a plausible-looking substitution would cost — frames legacy hardware silently discards. Why rs485b_hmtl_crc substitutes a zero at offset 1 rather than checksumming as-is: the crc byte lives inside the checksummed region, and the substitution is what makes stamping idempotent so a receiver can verify without a scratch copy. Why rs485b_hmtl_fmt needs the payload in place before it runs, and why sendPollResponse consequently has to re-stamp frame[1] — that line previously just said "re-stamp" without saying what breaks otherwise. Also the little-endian bitfield assumption behind HmtlMsgValue's 13/3 split.
Bounds and validation. rs485b_validate's check ordering is now documented as an ordering: each step only reads bytes an earlier step justified, ending with the CRC because it needs hdr.length to be trustworthy first. The per-payload length re-checks in rs485b_decide are called out as not redundant with validation — validation proved the bytes are present, not that the declared length matches the message type claimed, and without them an HMTL_OUTPUT_RGB frame carrying two payload bytes reads past the end. The three socket-layer tests in serviceRs485 are spelled out individually, including the reason they exist at all (RS485Utils' own checks sit inside #if DEBUG_LEVEL >= DEBUG_TRACE and are compiled out of exactly the builds this ships as). rs485b_next_sensor's two bounds tests are framed as what makes a hostile data_len harmless. And rs485b_validate_udp_ingress now explains that its size bound is memory safety rather than policy: sendMsgTo writes the socket header in front of the caller's pointer, into the same array, so an oversized frame overruns what initBuffer reserved — and that this is the last point where the caller still has the information to refuse.
Blocking-send rate limiting. The queue comment now explains why sendMsgTo blocks at all — it can't drop DE before the last bit is out without truncating the frame on a half-duplex bus — where the ~48 ms comes from, and why that makes one frame per loop() the budget rather than draining the queue. Plus why the queue is drop-oldest (these are live lighting commands; a backlog of stale ones is worse than useless) and fixed-size (no heap in a usermod running for months). serviceTx explains why the frame must be copied into txData specifically, and loop explains the strip.isUpdating() bail-out and the receive→transmit→ingest ordering.
PinManager. allocatePins now says why registering matters — an unregistered pin is one the LED-bus settings page will happily hand to a strip, after which two drivers fight over it and it looks like dead output rather than a conflict — why allocateMultiplePins' all-or-nothing rollback is load-bearing (a UART begun on a half-owned pin set drives a line another peripheral thinks it owns, with no clean way to give it back), and the isPinOk/PSRAM interaction that makes the documented RX16/TX17 defaults fail on WROVER boards, and why the code doesn't try to pick alternatives on the board's behalf. setup explains why UART 0 is rejected and that SOC_UART_NUM is what excludes the C3/S2 parts, and readFromConfig now states which fields can be applied live and which are reboot-only, with the init_general leak as the reason.
Comments only — no behaviour change. Test Plan re-run before pushing: both host tests pass (rs485_bridge_test, sensor_sync_test), pio run -e ampworks builds clean, and I also re-ran pio run -e usermods since the protocol header is compiled in the guarded path too. validate-commit-subjects.py against base-wled-16.0.1 is clean.
The separate thread about vendoring vs. importing from HMTL is left open — that's a design question, not a commenting one, and it's being answered separately.
aphelps-claude-bot
left a comment
There was a problem hiding this comment.
You're right, and the reasoning I recorded for vendoring was wrong. I re-checked it rather than defending it, and it doesn't hold up.
The plan (and the submodule table I wrote into CLAUDE.md) justified copying with: "HMTL/Libraries/* transitively pulls FastLED/PixelUtil, EEPromUtils, MPR121 and XBeeSocket, which WLED 16 cannot build." That conflated header dependencies with implementation dependencies. What's actually there:
HMTLprotocol/HMTLProtocol.h— 36 lines, zero#includes. Pure command/terminator constants.HMTLTypes/HMTLTypes.h— zero#includes.HMTLMessaging/HMTLMessaging.h— includes onlySocket.h,RS485Utils.h,HMTLTypes.h. The first two are already on this build's path; this very PR stack vendors and compiles them fromArduinoLibs.- Every heavy dependency —
PixelUtil.h,EEPromUtils.h,MPR121.h,XBeeSocket.h— appears inHMTLTypes.cpp, an implementation file we would never need to compile to consume the wire format.
So the headers defining msg_hdr_t, the msg_value_t / msg_rgb_t / msg_program_t / msg_poll_response_t / msg_set_addr_t payloads, HMTL_MSG_START, HMTL_MSG_VERSION and the HMTL_MSG_*_LEN macros are either dependency-free or depend only on libraries already being built here. The 656-line rs485_bridge_protocol.h is duplicating declarations that could be included directly, and CLAUDE.md even codifies the cost — "Keep it in sync with HMTL/Libraries/HMTLMessaging/HMTLMessaging.h" — a standing manual-sync obligation against a wire format shared with deployed hardware. That's exactly the drift risk worth removing.
Concretely, importing instead of copying looks like: add ${PROJECT_DIR}/../HMTL/Libraries to lib_extra_dirs, give HMTLprotocol/HMTLTypes/HMTLMessaging library.json manifests with "platforms": ["atmelavr", "espressif32"] (needed because WLED sets lib_compat_mode = strict) and an srcFilter that excludes the .cpp files we don't want compiled, then include the real headers and delete the vendored copy. On this evidence it may need no HMTL code changes at all — only packaging. If compiling HMTLMessaging.cpp turns out to be wanted for the CRC/parse helpers, that's the one place a real HMTL change (splitting the POD wire format from the object model) would be worth doing, and I'd rather do that than keep a copy.
I haven't started this rework — it reshapes a PR you've already reviewed, and it may add an HMTL PR to the stack, so I'd rather you say go first. Two things worth deciding: whether to do it in this PR now or as a follow-up, and whether you want HMTL on the firmware build path permanently (right now it's deliberately reference-only).
Separately: the commenting CR is addressed in 87ac5e2 — every function in all four files now has a description plus WHY-level inline commentary. That commit documents the vendored header; if we import instead, that file goes away and the documentation effort moves to the call sites.
aphelps-claude-bot
left a comment
There was a problem hiding this comment.
Follow-up review of 87ac5e22 (documentation-only, answering the CHANGES_REQUESTED review 4793697335 asking for a description on every function and comments a reader can follow on their own).
Verified comments-only: stripping comments from all four touched files at ab014dcb vs 87ac5e22 yields token-identical sources — zero behaviour change, as the commit message claims.
Coverage: every function in the four files now carries a description (protocol helpers, queue/counter methods, all usermod members, the placeholder, and every test builder). The single omission is getId() (main class and placeholder) — trivial, noted inline.
Accuracy spot-checks (all pass):
- CRC comments match
EEPromUtils.cppexactly (poly0xD8, init 0, MSB-first, no reflection/final XOR); the offset-1 zero-substitution and the stale-stamp/re-stamp story insendPollResponse()match the code. - "stock HMTL transmits crc == 0" is correct:
HMTL_USE_CRCis commented out (HMTLMessaging.h:17) andhmtl_msg_fmtzeroes the field (HMTLMessaging.cpp:237). - The
serviceRs485()claims check out againstRS485Utils.cpp:*retlen = msg->hdr.length(declared payload) vsgetLength()(received bytes), and the library's own length checks sit inside#if DEBUG_LEVEL >= DEBUG_TRACE(lines 238–262), compiled out of release. - PinManager comments are right: GPIO 16/17 return
!psramFound()inisPinOk()(pin_manager.cpp:249-255, modulo the D0WDR2-V3 carve-out on 17, which the cited lines show), anddeallocatePinreally does refuse a mismatched owner tag. SOC_UART_NUMbound,rs485_socket_hdr_t== 8 bytes,msg_value_t/msg_program_tstatic_asserts (4/35 bytes) matching the test-builder comments, and the UDP-truncation →RS485B_ERR_SHORTbring-up note all verified.
Prior issues: the 7 findings from the combined-set review (WLED_dev#20 review 4783222046) all concern code, and this commit deliberately changes none — all 7 remain open (POLL|ACK re-answering, poll response HMTL-addressed to self, runtime disable / releasePins() caller, broadcast-poll stagger, golden wire vectors, self-addressed UDP datagrams, dead frameLen > 255 check). No new comment papers over them — e.g. the new "ACK marks this as a response to a poll rather than a poll of our own" line documents precisely the flag the receive path does not yet check, which should make the fix round straightforward. The HMTL vendor-vs-import design thread also remains open, as agreed.
New issues (all comment-accuracy, minor): three inaccurate/overstated comments and the getId() description gap, inline below. An inaccurate rationale is worth fixing even in a doc pass — it is the kind of comment a future reader will trust.
aphelps
left a comment
There was a problem hiding this comment.
Please go forward with the refactor to not vendor the HMTL code
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
Bumps both submodule pointers for the rework Adam asked for on WLED#11
("Why isn't this imported from the HMTL libraries? ... We should do this
right, even if that means changes to HMTL code."):
HMTL 838a6be -> 7ca6637 aphelps/HMTL#6 -- extract the wire format
into HMTLprotocol/HMTLWireFormat.h, a
dependency-free header (<stdint.h> +
Socket.h, never Arduino.h). Pure move:
every relocated line byte-identical.
WLED 87ac5e22 -> 1beb4f83 aphelps/WLED#11 -- rs485_bridge_protocol.h
now includes that header instead of
declaring ~150 lines of its own, plus the
lib_extra_dirs/lib_deps wiring and the four
comment-accuracy fixes from re-review
4793843525.
CLAUDE.md's HMTL/ submodule row is rewritten: it claimed "Reference only
-- deliberately NOT on the PlatformIO build path" and gave a
transitive-dependency rationale that turned out to be about the .cpp
files, not the headers. HMTL/Libraries is now on the build path via
lib_extra_dirs in [env:ampworks], with only HMTLprotocol ever compiled
in, and the "keep it in sync" instruction is gone because there is no
longer a second copy.
Test: full plan Test Plan green -- host tests (rs485_bridge with the
real HMTL/ArduinoLibs headers under plain c++, sensor_sync), pio run for
ampworks / esp32dev / usermods / apa102_mpr121 and the
usermods_esp32{c3,s2,s3} CI matrix, portability grep, bash -n setup.sh.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ
aphelps-claude-bot
left a comment
There was a problem hiding this comment.
Already done — our messages crossed. Your review landed at 06:35 UTC; the refactor was pushed at 07:00–07:03.
The vendored copy is gone. What landed:
- New PR aphelps/HMTL#6 (
7ca6637) — extracts the block already titled "Transport-agnostic message types" out ofHMTLMessaging.hinto a dependency-freeHMTLprotocol/HMTLWireFormat.h.HMTLMessaging.hnow includes it, so existing HMTL code compiles unchanged. Verified a pure move: 5 of 5 relocated blocks byte-identical, and HMTL's ownpio test -e nativepasses 50/50. - wled#11 ←
1beb4f83— deletes the 656-line duplicated header, includes the real HMTL header, and fixes the four comment-accuracy nits from the last re-review. - WLED_dev#20 ←
dc10058—HMTL/Librariesontolib_extra_dirs, HMTL submodule pointer bumped, and theCLAUDE.mdHMTL row rewritten (it had claimed "reference only — deliberately NOT on the build path" on a transitive-dependency rationale that turned out to be wrong, plus a keep-in-sync instruction this change exists to delete).
The proof it's genuinely dependency-free: the host tests still compile under plain c++ -std=c++11 while including the real HMTL and ArduinoLibs headers, so any Arduino.h leak fails there. All seven PlatformIO envs build clean.
Two deviations from the spec worth knowing, both documented in #6: the extraction also had to move output_hdr_t / config_hdr_* / HMTL_PROGRAM_* because the message structs embed them, and the planned srcFilter exclusions turned out unnecessary — they would have broken HMTL's own module builds, and nothing outside HMTLprotocol is on the WLED path anyway.
One real wrinkle: msg_poll_response_t is unpacked upstream, so it is 23 B on AVR and 24 B on ESP32 where uint16_t forces alignment — trailing padding only, every field offset identical. The bridge emits HMTL_MSG_POLL_MIN_LEN, which is exactly what HMTL's own hmtl_poll_fmt() emits on the same platform, and the inbound path is unaffected (a poll request carries no payload, so nothing validates against that length). But an AVR master that length-checks a poll response against its own 23 B constant could reject ours. I added a ## Testing Required item to check both directions on the bus; if outbound fails, the fix is to pack the struct or emit 23 explicitly. A static_assert block now pins every other wire struct, so that is the only size that can drift.
aphelps-claude-bot
left a comment
There was a problem hiding this comment.
Follow-up review of 1beb4f83 (the rework: delete the 656-line vendored wire format from rs485_bridge_protocol.h, include HMTL's real HMTLprotocol/HMTLWireFormat.h extracted upstream instead).
Wire behaviour preserved — verified, not assumed:
- Pure move re-verified independently: a difflib opcode walk over the HMTL extraction commit (
7ca6637) confirms every non-comment line deleted fromHMTLTypes.h/HMTLMessaging.h/HMTLPrograms.happears verbatim inHMTLWireFormat.h— zero missing, zero edited. - static_assert values match deployed AVR hardware: compiled the imported structs under both natural alignment and align-1 (AVR-like,
-fpack-struct=1): all 8 asserted structs are byte-identical in both ABIs (msg_hdr_t8,output_hdr_t2,msg_value_t4,msg_rgb_t5,msg_program_t35,msg_set_addr_t4,config_hdr_v3_t10,msg_sensor_data_t2), so the asserted values are exactly what AVR emits.msg_poll_response_tis the sole divergence (15 vs 16 B, trailing pad only;object_type@10,recv_buffer_size@12,msg_version@14 in both) — precisely as the new comment block claims. - Constant-for-constant match: every deleted
HMTL_MSG_*/HMTL_OUTPUT_*/HMTL_PROGRAM_*/flag/magic value equals its imported counterpart (MSG_TYPE_*0x01–0x05/0xE0, flags 1<<0..3, start 0xFC, version 2, max len 128, magic 0x5C,PROGRAM_BRIGHTNESS/_COLOR0x30/0x31);SOCKET_ADDR_ANY=(socket_addr_t)-1= 0xFFFF = the oldHMTL_ADDR_BROADCAST.BAUD_TO_BYTEdrops the vendored(uint8_t)cast but assigns to auint8_tfield — identical truncation. - Acceptance check passes at this SHA:
grep '^\s*#include' HMTLWireFormat.hshows exactly<stdint.h>+"Socket.h", and the host test compiles with plainc++against the real HMTL/ArduinoLibs headers and printsALL TESTS PASSED(run on a clean checkout of1beb4f83).
Poll-response 23B/24B handling — safe on both paths:
- Emit:
sendPollResponse()sendsHMTL_MSG_POLL_MIN_LEN(24 B here) withmemsetzeroing the pad byte,hdr.length= 24 = the CRC span — internally consistent and exactly whathmtl_poll_fmt()emits for this target. HMTL's Python master tooling parses poll responses withstruct.unpack_from(offset-based, trailing-byte-tolerant), so the pad byte is ignored there; a strict AVR C master remains the hardware-gated risk the plan's Testing Required item already covers. - Parse: the bridge never reads
sizeof(msg_poll_response_t)from received data — an inbound 23 B AVR poll response passes only through length-agnosticrs485b_validate()and verbatim relay, so the ABI difference cannot corrupt the receive path. (It does still trigger the known POLL|ACK re-answer bug — prior finding, below.)
No validation/bounds logic lost: the deletion removed declarations only. rs485b_validate, rs485b_validate_udp_ingress, rs485b_decide's per-payload re-checks, rs485b_next_sensor's two bounds checks, the queue and counters all survive check-for-check. The two behaviour-adjacent rewrites are equivalent: rs485b_next_sensor switches from memcpy into a struct to direct byte indexing (forced by the imported struct's flexible array member; sizeof = 2 either way, asserted), and the socket-header size is now cross-checked by the existing static_assert in the .cpp.
Coverage change (documented, acceptable): the flagless builds ([env:usermods], CI matrix) no longer compile rs485_bridge_protocol.h — the placeholder's #include was removed because the header now needs the HMTL submodule, which CI does not clone. The wire-layout asserts are covered by pio run -e ampworks + the host test instead; readme and placeholder comments both state this accurately.
Prior issues:
- The 4 comment-accuracy nits from review 4793843525 are all fixed: the loop-ordering rationale no longer claims the order prevents back-to-back sends (now correctly credits
serviceTx()'s one-frame budget),rs485Handledis described with the PROGRAM/SENSOR caveat (mirrored athandleDecision()), the wrong int-promotion claim is replaced with the correctsize_t-arithmetic explanation, andgetId()now carries a description in both the main class and the placeholder. - The 7 code findings from WLED_dev#20 review 4783222046 all remain open (POLL|ACK re-answering, poll response HMTL-addressed to self, runtime disable /
releasePins()caller, broadcast-poll stagger, golden wire vectors, self-addressed UDP datagrams, deadframeLen > 255check) — this commit deliberately changes no behaviour beyond the import, and none of them regressed. - The vendor-vs-import design thread this rework answers can now be resolved: the duplication it questioned no longer exists.
New issues (minor): one comment inaccuracy and one suggested host-test addition, inline.
aphelps
left a comment
There was a problem hiding this comment.
This seems fine. Please make sure to respond to the most recent round of self-review
…truct 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
aphelps-claude-bot
left a comment
There was a problem hiding this comment.
Comment round 2 addressed — 501e2503, a new commit on rs485-bridge-usermod (not squashed, not rebased; the approval on 1beb4f83 stands and the diff since it is comments + tests only, zero behaviour change).
All 7 unresolved threads are now closed:
| Thread | Disposition |
|---|---|
| Vendoring vs importing the HMTL wire format (yours) | Landed in 1beb4f83; re-verified this round, resolved |
| Loop-ordering rationale | Verified fixed in 1beb4f83, resolved |
Overstated rs485Handled invariant |
Verified fixed in 1beb4f83, resolved |
| Int-promotion mechanism | Verified fixed in 1beb4f83, resolved |
Missing getId() description |
Verified fixed in 1beb4f83, resolved |
static_assert block says the structs are unpacked |
Fixed here — output_hdr_t is packed |
Suggested test: pin msg_poll_response_t |
Added here — routed into the plan's Test Plan, run, ticked |
The two substantive ones:
Packed-struct claim. The block asserted that HMTL declares all eight structs without __attribute__((packed)). output_hdr_t is the exception (HMTLWireFormat.h:130), and it is embedded in msg_value_t / msg_rgb_t / msg_program_t — so the wrong sentence covered exactly the structs a reader would most want it to be right about. The assertions were always correct; only the rationale was.
msg_poll_response_t is no longer prose-only. It 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 wherever uint16_t demands it, so the struct is 15 B or 16 B and HMTL_MSG_POLL_MIN_LEN is 23 or 24. The claim that only trailing padding differs is now executable: group 1 of the host test pins all five field offsets, bounds sizeof, and ties the emitted length to the two struct sizes. Because the claim is specifically about two alignment models, the plan item runs the test under both — plain c++ and -fpack-struct=1. Measured offsets 0/10/12/14/15 identical on both, ALL TESTS PASSED twice. An upstream HMTLWireFormat.h edit that moves a field now fails the host test; legitimate padding drift still passes.
Test Plan: 13/13 green (was 12/12; the routed suggestion is the 13th).
- Host tests:
rs485_bridge_testPASS on both ABIs,sensor_sync_testPASS pio run:ampworks,esp32dev,usermods,apa102_mpr121— all SUCCESS- Per-usermod CI matrix:
usermods_esp32c3/_esp32s2/_esp32s3— all SUCCESS HMTLWireFormat.hinclude list still exactly<stdint.h>+"Socket.h"; portability grep clean;RS485_non_blockingresolving repo-relative via${PROJECT_DIR}/../ArduinoLibsvalidate-commit-subjects.pyvsorigin/base-wled-16.0.1: exit 0
The 5 ## Testing Required items stay hardware-gated. One of them is the interop half of the poll-response question above — whether a real legacy master accepts the bridge's 24 B response — which the host test cannot answer and does not claim to.
Unchanged and still pending for the parent: aphelps/WLED_dev#20's submodule pointer needs re-bumping to this tip before it merges. Deliberately not touched in this round.
aphelps-claude-bot
left a comment
There was a problem hiding this comment.
Follow-up review of 501e2503 (comments + host-test only, zero behaviour change; addresses the two items from self-review 4794753753). Both changes were verified against the tree, not just the diff.
- Prior issue addressed — packed-struct comment corrected, and the new wording is TRUE.
grep packed HMTL/Libraries/HMTLprotocol/HMTLWireFormat.hhas exactly one hit:output_hdr_tatHMTLWireFormat.h:130is declared__attribute__((__packed__)); none of the other seven structs asserted inrs485_bridge_protocol.h:556-563(msg_hdr_t,msg_value_t,msg_rgb_t,msg_program_t,msg_set_addr_t,config_hdr_v3_t,msg_sensor_data_t) carry it. "Of the eight asserted here only output_hdr_t" is exact. - Prior issue addressed — the poll-response layout claim is now executable, and it pins the RIGHT invariant. Independently probed the real header on both ABIs: plain
c++gives offsets 0/10/12/14/15,sizeof16,HMTL_MSG_POLL_MIN_LEN24; with-fpack-struct=1the offsets are identically 0/10/12/14/15,sizeof15,MIN_LEN23. The fiveoffsetofCHECKs plus the 15-or-16 bound therefore pass on both layouts, exactly as the "only trailing padding differs" claim requires. - Mutation-tested the failure direction. Inserting a
uint8_tbeforeobject_typein a copy ofHMTLWireFormat.hfails five CHECKs (object_type at 10through the size bound) and the test printsSOME TESTS FAILED— so an upstream edit that moves a field is caught, not just asserted about. A padding-only change (e.g. packing the struct to 15 B everywhere) keeps all offsets and stays inside the bound, as intended. - The
MIN_LENtie-down closes the loop to the wire.CHECK(HMTL_MSG_POLL_MIN_LEN == sizeof(msg_hdr_t) + sizeof(msg_poll_response_t))matches the macro's definition atHMTLWireFormat.h:225, andsendPollResponse()(usermod_rs485_bridge.cpp:399-400) sizes its frame from that same macro — so the offsets the test pins are the offsets a legacy master parses. - Both test commands re-run: PASS.
c++ -std=c++11 -Wall -Wextra -I HMTL/Libraries/HMTLprotocol -I ArduinoLibs/Socket …printsALL TESTS PASSED, and the same command with-fpack-struct=1also printsALL TESTS PASSED. - Plan Test Plan entry is accurate (local-only file,
todo_plans/is gitignored): the new item describes exactly what group 1 now does — five offsets 0/10/12/14/15, size bounded to 15/16,MIN_LENtied to the two struct sizes, run under both packing models. - No new issues. The 7 behaviour-change findings from WLED_dev#20 review 4783222046 (POLL|ACK re-answering, poll response addressed to self, runtime-disable/releasePins, broadcast-poll stagger, golden vectors, self-addressed UDP, dead frameLen check) remain open and are unaffected by this commit; the AVR-master 23 B vs 24 B interop question remains hardware-gated in
## Testing Required.
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
aphelps-claude-bot
left a comment
There was a problem hiding this comment.
Heads-up on a new commit here — ab8163cd, pushed on top of the approved tip, not squashed or rebased. It is the downstream half of aphelps/HMTL#6 CR 4813374061.
Why it exists. Adam's directive on HMTLWireFormat.h: "The same format needs to work on an Arduino with ATMega328 and an ESP32 since they will be communicating." HMTL now declares every wire struct __attribute__((__packed__)) (HMTL 41a27ea), which changes struct sizes on this side, so this branch's compile-time guards had to move with it.
Wire-visible change: the bridge's POLL response is now 23 B, not 24 B — byte-for-byte what a deployed AVR module emits and length-checks. That was the one real interop risk in this usermod.
What changed
rs485_bridge_protocol.h— thestatic_assertblock's rationale was rewritten, not just extended. It used to sayoutput_hdr_twas the only packed struct, that the other seven relied on their field ordering happening to avoid padding, and thatmsg_poll_response_twas "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, somsg_poll_response_t(15 B) andHMTL_MSG_POLL_MIN_LEN(23) are asserted like the rest, plusconfig_hdr_v1/v2_tand the two zero-size FAM structs.tests/rs485_bridge_test.cppgroup 1 — exact sizes and every field offset for every wire struct, instead of boundingmsg_poll_response_tto 15-or-16. Addsconfig_hdr_v2_t(the interior-padding case:addressat 3, not 4) and a byte-level check of themsg_value_t13/3 bitfield split, since packing a struct containing bitfields is the one case where the attribute could move more than padding.sendPollResponse()'s 24-vs-23 comment corrected.- Two zero-behaviour cleanups so the new "compile with g++ >= 9 as well as clang" gate is warning-free: dropped the dead
frameLen > 255test inrs485b_validate_udp_ingress(frameLenis auint8_t, so-Wtype-limitsis right; the 255 ceilingsendMsgTo'sbytelength imposes is enforced by the type, and themaxPayloadbound beside it is unchanged), and removed line continuations from a//comment block (-Wcomment). readme.md— the packing rationale, plus a local-development trap worth knowing:HMTLprotocolis afile://lib_dep, so PlatformIO caches a copy under.pio/libdeps/<env>/and an edit toHMTLWireFormat.hhas no effect until that copy is cleared (rm -rf .pio/libdeps/*/HMTLprotocol). This bit during verification — the firstpio run -e ampworkscompiled the stale unpacked header, so a stale copy silently checks the old layout. Fresh clones and CI copy the current file.
Verification. Host test PASS under clang 21 and g++ 16, each with and without -fpack-struct=1, all four warning-free and reporting identical sizes and offsets — that symmetry is the whole claim. pio run -e ampworks (flash 83.6%) / esp32dev / usermods / apa102_mpr121 and the usermods_esp32c3/s2/s3 CI matrix envs all SUCCESS, no new warnings. sensor_sync_test PASS.
Plan bookkeeping. The ## Testing Required poll-response item was reworded rather than deleted: the size question it described is now compile-time enforced (static_assert(HMTL_MSG_POLL_MIN_LEN == 23) here and in HMTL's test_wire_format), so nothing on hardware can disagree about the length. What survives as a hardware gate is the ordinary end-to-end check that the poll exchange carries the right field values — a failure there is now a content bug, not a padding mismatch, so the old "if it fails, pack the struct" remedy no longer applies.
Still open on this branch, unchanged by this commit: the 7 behaviour-change findings from WLED_dev#20 review 4783222046 (POLL|ACK re-answering, poll response addressed to self, runtime-disable/releasePins, broadcast-poll stagger, golden wire vectors, self-addressed UDP datagrams) — one of which, the dead frameLen > 255 check, is closed by this commit.
`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
left a comment
There was a problem hiding this comment.
CI fix pushed as f243548 — Build Environments (usermods) is green again.
What failed
_temp/ArduinoLibs/RS485Utils/RS485Utils.cpp:17:10: fatal error: RS485_non_blocking.h: No such file or directory
* Looking for RS485_non_blocking.h dependency? Check our library registry!
Why. The usermod's build guard was doing its job — usermod_rs485_bridge.cpp 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 saw
#include "RS485Utils.h" inside the disabled #if RS485_BRIDGE_BUILD block regardless, pulled
RS485Utils out of the ArduinoLibs clone on PLATFORMIO_LIB_EXTRA_DIRS and compiled it — a library
nothing in that env links against. RS485Utils.cpp includes <RS485_non_blocking.h> above its
own RS485UTILS_SUPPORTED guard, and the workflows clone ArduinoLibs' default branch, which
does not carry that vendored sibling library yet (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. [env:ampworks] was unaffected only because it names
../ArduinoLibs/RS485_non_blocking explicitly in lib_deps.
Fix. lib_ignore = RS485Utils on [env:usermods], with the reasoning recorded in
platformio.ini and in usermods/rs485_bridge/readme.md ("Why the build guard exists"). That is
what actually matches reality here: with the bridge compiled out, no translation unit in that env
can reference an RS485Utils symbol. It 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 clones, so
it is immune to the merge order of the remaining PRs.
Considered and rejected: lib_ldf_mode = chain+ on that env (would honor the guard, but changes
dependency discovery for all ~55 usermods in the wildcard env — far more blast radius for the same
result), and hardening the name-only RS485_non_blocking dep in RS485Utils/library.json (cannot
help while CI clones a branch that has no such directory).
Verification. CI was reproduced exactly before fixing it: a standalone clone of this branch
with no ../ArduinoLibs sibling, built against a clone of ArduinoLibs' default branch on
PLATFORMIO_LIB_EXTRA_DIRS. It fails with the identical error before the commit and clean-builds
after. The plan's full 17-item test plan was re-run and is still green, including
pio run -e usermods, -e ampworks, -e esp32dev, -e apa102_mpr121, all four
usermods_esp32* matrix envs, the host tests under clang/g++-16 at both packings, the 7-toolchain
wire-layout check, HMTL's native suite (54/54) and the HMTL_Module nano build (85.5% flash).
Unrelated check: Test cdata.js. Known-flaky and not caused by this branch — the branch
touches zero web-UI files (no wled00/data, no cdata, no html_*), the base branch's CI is
green across its last five runs, and this same check passed in a sibling run of this very PR. It
was deliberately left alone, and it passed on its own in this run.
The full WLED CI run for this commit is green end to end
(30501939718).
* extract the HMTL wire format into HMTLprotocol/HMTLWireFormat.h Consumers that only need to speak the HMTL protocol previously had to copy-and-paste the declarations, because every header that carried them also dragged in the module runtime: HMTLMessaging.h pulls RS485Utils.h -> Arduino.h, HMTLPrograms.h pulls FastLED.h/PixelUtil.h, and HMTLTypes.h comes with HMTLTypes.cpp (EEPromUtils, MPR121, XBeeSocket). The WLED RS485 bridge usermod (aphelps/WLED#11) vendored ~150 lines for exactly this reason; this is the fix for that. HMTLWireFormat.h now holds everything that appears on a wire or in EEPROM and nothing else: - from HMTLTypes.h: HMTL_CONFIG_MAGIC/VERSION, config_hdr_v1..v3_t, config_hdr_t, HMTL_NO_ADDRESS, BYTE_TO_BAUD / BAUD_TO_BYTE, HMTL_OUTPUT_*, IS_HMTL_*_OUTPUT, HMTL_FLAG_*, HMTL_NO_OUTPUT / HMTL_ALL_OUTPUTS, output_hdr_t - from HMTLMessaging.h: the block already titled "Transport-agnostic message types" -- msg_hdr_t, MSG_TYPE_* / MSG_FLAG_*, msg_value_t / msg_rgb_t / msg_program_t / msg_poll_response_t / msg_set_addr_t / msg_sensor_*, HMTL_MSG_START, HMTL_MSG_VERSION, HMTL_MAX_MSG_LEN and the HMTL_MSG_*_LEN macros - from HMTLPrograms.h: the HMTL_PROGRAM_* / PROGRAM_* codes, which travel in msg_program_t.type This is a pure move: every relocated line is byte-identical, verified block-by-block against HEAD. No field, code point or layout changes -- deployed hardware speaks this format. The three source headers now include HMTLWireFormat.h, so existing code that includes them is unaffected. The header takes only <stdint.h> and Socket.h (itself include-free, socket_addr_t) and supplies the Arduino `byte`/`boolean` aliases when built off-Arduino, so it compiles with a plain host compiler. Also adds library.json manifests to HMTLprotocol, HMTLTypes and HMTLMessaging declaring atmelavr + espressif32, which PlatformIO's lib_compat_mode = strict (used by WLED) requires. No srcFilter exclusions: nothing outside HMTLprotocol is on the WLED build path now, and excluding HMTLTypes.cpp / HMTLMessaging.cpp would break HMTL's own module builds. Test: pio test -e native -- 50/50 pass (HMTL_Test gains -I ../../Libraries/HMTLprotocol); HMTLTypes.h + HMTLMessaging.h parse clean against the desktop stub with and without ARDUINO defined; HMTLWireFormat.h compiles standalone under c++ -std=c++11 -Wall -Wextra with no Arduino headers. Part of aphelps/WLED_dev#20 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ * pack every wire struct so AVR and ESP32 layouts agree An ATMega328 module and an ESP32 module share one RS485 bus and read each other's EEPROM config blobs, so a struct in this header must have the same size AND the same field offsets under avr-gcc and under a 32-bit compiler. Unpacked it did not: avr-gcc aligns everything to 1 byte, while xtensa/x86 align uint16_t to 2. Two structs drifted for real: config_hdr_v2_t 8 B on AVR, address at offset 3 10 B on 32-bit, address at offset 4 <- INTERIOR pad msg_poll_response_t 15 B on AVR vs 16 B on 32-bit, making HMTL_MSG_POLL_MIN_LEN 23 or 24 by target The second one is a live interop bug, not just untidiness: an AVR master that length-checks a poll response against its own constant would reject a structurally valid 24 B response from the ESP32 bridge. __attribute__((__packed__)) on all 13 structs is layout-neutral on AVR (alignment is already 1, so deployed modules see no change) and corrective everywhere else - it makes the 32-bit layout equal the AVR layout that is already on the wire. HMTL_MSG_POLL_MIN_LEN is now 23 on every target. Also in this header, since it is now consumed off-Arduino: * msg_sensor_response_t::data[] -> data[0]. A C99 flexible array member in an otherwise-empty struct is rejected by g++ >= 9 in C++ mode (verified: avr-g++ 9.5 errors, avr-g++ 8.5 and Apple clang accept), which would stop host consumers building on a typical Linux box. Both spellings give sizeof == 0, so HMTL_MSG_SENSOR_MIN_LEN and the wire layout are unchanged. Same change to msg_sensor_data_t for consistency. * Copyright date updated. * The <Arduino.h> include-order contract is now stated explicitly: on Arduino builds the byte/boolean guard is skipped and Socket.h's usage needs Arduino.h earlier in the TU. Deliberately NOT fixed by including <Arduino.h> under a guard - the entire point of the file is that a host consumer can include it with no Arduino toolchain present. Verified: sizes and offsets for all 13 structs plus all seven HMTL_MSG_*_LEN macros are identical under host clang 21, host clang 21 -fpack-struct=1, host g++ 16, host g++ 16 -fpack-struct=1, avr-g++ 9.5 -mmcu=atmega328p, PlatformIO's avr-g++ 8.5 -mmcu=atmega328p and PlatformIO's xtensa-esp32-elf-g++ 8.4. Before this change the same check failed on every 32-bit configuration. Part of aphelps/WLED_dev#20 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ * pin every wire size and offset in a portable native test Two problems with the native suite as the acceptance check for the wire header. It could not run on a fresh clone: Socket.h was resolved solely through a hardcoded absolute -I into one developer's Arduino libraries directory, and this PR makes Socket.h a hard dependency of HMTLWireFormat.h (and therefore of HMTLTypes.h) rather than only of HMTLMessaging.h. Vendored a stubs/Socket.h alongside the Arduino/RS485Utils/PixelUtil/FastLED stubs already there - its body is byte-identical to ArduinoLibs' Socket.h - and dropped the absolute path. Every include path in [env:native] is now repo-relative. It checked nothing about layout: the packing invariant the previous commit introduced was prose. test/test_wire_format/ static_asserts the size of all 13 structs, the offset of every named field and all seven HMTL_MSG_*_LEN macros, so it holds for whatever target the file is compiled for - running the native suite proves the 32-bit layout, building any module firmware proves the AVR one. Four runtime cases cover what static_assert cannot: the byte image of msg_hdr_t, config_hdr_v2_t's interior-padding-free address at offset 3, the msg_value_t 13/3 bitfield split (packing a struct with bitfields is the one case where the attribute could move more than padding), and the 23 B poll response. pio test -e native: 54 test cases, 54 succeeded (was 50), with no external include paths. Part of aphelps/WLED_dev#20 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ * document the HMTLprotocol linking requirement and the packing invariant HMTLTypes.h used to be include-free and HMTLMessaging reached socket_addr_t through RS485Utils; both now include HMTLWireFormat.h, so HMTLprotocol and Socket must also be linked into the Arduino libraries directory wherever HMTLTypes or HMTLMessaging is used. The Arduino IDE and the PlatformIO LDF resolve the transitive include automatically, but only if the library is present - someone following the "linked individually" instruction with just the old set gets a missing-header error. Also records why the wire structs are packed, what drifted without it, and how to run the layout test. Part of aphelps/WLED_dev#20 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]>
* add HMTL submodule + bump ArduinoLibs/WLED for the RS485 bridge usermod Adds aphelps/HMTL as a third submodule at the repo root. It is a reference checkout, deliberately NOT on the PlatformIO build path: HMTL/Libraries transitively pulls FastLED/PixelUtil, EEPromUtils, MPR121 and XBeeSocket, none of which build under WLED 16, so the rs485_bridge usermod vendors just the HMTL wire format instead. Keeping the submodule gives us the protocol source of truth and the Python tooling. setup.sh needs no logic change — `git submodule update --init --recursive` already picks up the new .gitmodules entry; only its descriptive strings and CLAUDE.md's submodule documentation are updated. Submodule pointers: - ArduinoLibs: vendored Gammon RS485_non_blocking, Socket/RS485Utils manifests, portable example projects, RS485UTILS_SUPPORTED guard. - WLED: the rs485_bridge usermod itself. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ * import the HMTL wire format instead of vendoring it Bumps both submodule pointers for the rework Adam asked for on WLED#11 ("Why isn't this imported from the HMTL libraries? ... We should do this right, even if that means changes to HMTL code."): HMTL 838a6be -> 7ca6637 aphelps/HMTL#6 -- extract the wire format into HMTLprotocol/HMTLWireFormat.h, a dependency-free header (<stdint.h> + Socket.h, never Arduino.h). Pure move: every relocated line byte-identical. WLED 87ac5e22 -> 1beb4f83 aphelps/WLED#11 -- rs485_bridge_protocol.h now includes that header instead of declaring ~150 lines of its own, plus the lib_extra_dirs/lib_deps wiring and the four comment-accuracy fixes from re-review 4793843525. CLAUDE.md's HMTL/ submodule row is rewritten: it claimed "Reference only -- deliberately NOT on the PlatformIO build path" and gave a transitive-dependency rationale that turned out to be about the .cpp files, not the headers. HMTL/Libraries is now on the build path via lib_extra_dirs in [env:ampworks], with only HMTLprotocol ever compiled in, and the "keep it in sync" instruction is gone because there is no longer a second copy. Test: full plan Test Plan green -- host tests (rs485_bridge with the real HMTL/ArduinoLibs headers under plain c++, sensor_sync), pio run for ampworks / esp32dev / usermods / apa102_mpr121 and the usermods_esp32{c3,s2,s3} CI matrix, portability grep, bash -n setup.sh. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ * fix stale setup.sh note claiming HMTL is off the build path * bump ArduinoLibs/HMTL/WLED pointers to their merged rs485-bridge commits --------- Co-authored-by: aphelps-claude-bot <[email protected]> Co-authored-by: Claude Fable 5 <[email protected]>
Part of aphelps/WLED_dev#20 in the parent repo.
Summary
New
rs485_bridgeusermod: a WLED ESP32 becomes a WiFi ↔ RS485 bridge for legacyHMTL modules, using
RS485Socketfrom ArduinoLibs.datagrams, validates them, and transmits them onto the bus.
segment — RGB / VALUE sets and a small HMTL-program → WLED-effect map — and answer
POLLandSET_ADDRESSso the bridge behaves as a proper HMTL bus citizen. Sensor broadcasts and framesfor other nodes are relayed back to the last WiFi peer. Everything else is counted and ignored.
SensorSync-over-RS485 is explicitly out of scope (follow-up task
sensorsync-rs485-transport).Full wiring, config reference, HMTL subset table and bridge semantics:
usermods/rs485_bridge/readme.md.Design notes worth reviewing
transmit ring buffer and the counters all live in
rs485_bridge_protocol.h, which has zeroWLED/Arduino dependencies and is host unit-tested (19 test groups,
tests/rs485_bridge_test.cpp). Same pattern assensor_sync_protocol.h.HMTLTypes.cpppulls inDebug.h,EEPromUtils.h,PixelUtil.h,MPR121.h,XBeeSocket.h;HMTLMessaging.cpppulls inHMTLPrograms.h→FastLED.h, which WLED 16 removed. Only the wire format is vendored(header layout, type codes, CRC-8 poly
0xD8), withstatic_asserts guarding layout drift.sendMsgToblocks. It callsserial->flush()while holding DE high — ≈48 ms for a 64-bytepayload at 28000 baud once Gammon's byte-stuffing is counted. So the bridge transmits at most
one frame per
loop()and queues the rest in a 4-slot drop-oldest ring; a UDP flood cannotstall the LED refresh or trip the watchdog. Oversized datagrams are rejected before
sendMsgTo(itsdatalengthis abyte, and it writes the socket header in front of thecaller's buffer).
#if DEBUG_LEVEL >= DEBUG_TRACEand are compiled out in release builds.PinManagerunder a newPinOwner::UM_RS485_BRIDGE, all-or-nothing, so theUART is never opened on a half-allocated pin set.
isPinOk()rejects the default GPIO 16/17 onPSRAM boards — the pins stay user-configurable and the readme calls this out.
init_general()re-news the channel without freeing the old one, so re-init()leaks.setup()is the sole caller ofHardwareSerial::begin()/RS485Socket::init(). The RS485address is the exception (it lives in
RS485Socket::sourceAddress), which is what makesSET_ADDRESSwork.library.jsonauto-enrols this directory in[env:usermods](custom_usermods = *) and the per-usermod CI matrix, neither of which setsUSERMOD_RS485_BRIDGE/RS485_HARDWARE_SERIAL— and UART 2 does not exist on ESP32-C3/S2. Thewhole TU is therefore guarded, and an inert placeholder usermod stands in. The placeholder is
load-bearing:
pio-scripts/validate_modules.pyfails the build for any enrolled usermod with noDWARF CU in the linked ELF, and
--gc-sectionsdrops a TU whose only symbol is unreferenced.The dependency-free protocol header is still compiled there, so its
static_asserts run in allfour CI targets.
[env:usermods]gainslib_extra_dirs. That env could not build from a super-repo checkoutat all before this (
mpr121→fatal error: MPR121.h: No such file or directory).PLATFORMIO_LIB_EXTRA_DIRSis appended to the ini value rather than overriding it (verified),so the CI clone still works when the relative path is absent.
Core-file changes
Two, both additive:
USERMOD_ID_RS485_BRIDGE = 62inwled00/const.handUM_RS485_BRIDGEin thePinOwnerenum inwled00/pin_manager.h.Test plan
Automated:
c++ -std=c++11 -Wall -Wextra -o /tmp/rs485_test usermods/rs485_bridge/tests/rs485_bridge_test.cpp && /tmp/rs485_testALL TESTS PASSEDc++ -std=c++11 -Wall -Wextra -o /tmp/ss_test usermods/ampworks/tests/sensor_sync_test.cpp && /tmp/ss_test— existing host test still passesALL TESTS PASSEDpio run -e ampworks/-e esp32dev/-e usermods/-e apa102_mpr121esp32dev SUCCESS 00:00:04.043 ampworks SUCCESS 00:00:27.376 apa102_mpr121 SUCCESS 00:00:27.011 usermods SUCCESS 00:00:18.630platformio_override.usermods.ini+custom_usermods = rs485_bridge,PLATFORMIO_LIB_EXTRA_DIRSset as CI does):usermods_esp32 SUCCESS usermods_esp32c3 SUCCESS usermods_esp32s2 SUCCESS usermods_esp32s3 SUCCESSusermod_rs485_bridge.cpp(forced recompile, filtered buildlog: only pre-existing framework/audioreactive/GifDecoder warnings remain).
grep -rnE '/Users/|/home/|\blib_dir\b' … WLED/platformio.ini— no matches.Manual (hardware — tracked on the parent PR):
ampworksto an ESP32 with an RS485 transceiver (Serial2 RX16/TX17/EN18); clean bootwith the usermod enabled and disabled.
respond.
persistence via
curl -s http://<ip>/json/cfg.