Skip to content

extract the HMTL wire format into a dependency-free header - #6

Merged
aphelps-claude-bot merged 4 commits into
mainfrom
rs485-bridge-wire-format
Jul 30, 2026
Merged

aphelps-claude-bot merged 4 commits into
mainfrom
rs485-bridge-wire-format

Conversation

@aphelps-claude-bot

Copy link
Copy Markdown
Collaborator

Summary

Extracts the HMTL wire format into a new dependency-free header, Libraries/HMTLprotocol/HMTLWireFormat.h, so consumers that only need to speak the protocol can import it instead of copy-pasting the declarations.

This is the upstream half of the RS485/HMTL bridge stack in aphelps/WLED_dev#20 — it exists because of a review comment on aphelps/WLED#11:

Why isn't this imported from the HMTL libraries? Seems like a lot of unnecessary copy and paste. We should do this right, even if that means changes to HMTL code.

Why the wire format was un-importable

Every header that carried a piece of it also dragged in the module runtime:

Header Also pulls in
HMTLMessaging.h RS485Utils.h → Arduino.h
HMTLPrograms.h FastLED.h, PixelUtil.h, ProgramManager.h
HMTLTypes.h (header is clean, but HMTLTypes.cpp needs EEPromUtils, MPR121, XBeeSocket, PixelUtil)

So a non-Arduino consumer — a host tool, a native unit test, a WLED usermod — could not include any of them, and the WLED bridge ended up vendoring ~150 lines of declarations.

What moved

HMTLWireFormat.h now holds everything that appears on a wire or in EEPROM, and nothing else:

  • from HMTLTypes.h — HMTL_CONFIG_MAGIC/HMTL_CONFIG_VERSION, config_hdr_v1_t..config_hdr_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, the MSG_TYPE_*/MSG_FLAG_* codes, msg_value_t/msg_rgb_t/msg_program_t/msg_poll_response_t/msg_dumpconfig_response_t/msg_set_addr_t/msg_sensor_*, HMTL_MSG_START, HMTL_MSG_VERSION, HMTL_MAX_MSG_LEN, HMTL_MSG_SIZE and the HMTL_MSG_*_LEN macros
  • from HMTLPrograms.h — the HMTL_PROGRAM_* / PROGRAM_SENSOR_DATA / PROGRAM_BRIGHTNESS / PROGRAM_COLOR codes, which travel in msg_program_t.type

This is a pure move. Every relocated line is byte-identical to main, verified block-by-block with a difflib opcode walk over the three source files (each deleted block is checked to appear verbatim in the new header). No field, code point, ordering or layout change — deployed hardware speaks this format.

The three source headers now #include "HMTLWireFormat.h", so all existing code that includes them compiles unchanged.

Dependency rules for the new header

HMTLWireFormat.h includes exactly two things:

#include <stdint.h>
#include "Socket.h"   // socket_addr_t; itself include-free

It must never include Arduino.h, RS485Utils.h, PixelUtil.h, FastLED.h or EEPromUtils.h — the file header says so explicitly. It also supplies the Arduino byte/boolean aliases when built off-Arduino (#if !defined(ARDUINO) && !defined(Arduino_h)), since Socket.h uses them without including <Arduino.h>; re-declaring an identical typedef is legal, so this is a no-op under Arduino and alongside the existing desktop stub.

PlatformIO manifests

Adds library.json to HMTLprotocol, HMTLTypes and HMTLMessaging declaring "platforms": ["atmelavr", "espressif32"] — required by WLED's lib_compat_mode = strict, which silently drops any library that does not declare the target platform.

No srcFilter exclusions: with the extraction done, nothing outside HMTLprotocol is on the WLED build path, and excluding HMTLTypes.cpp / HMTLMessaging.cpp would break HMTL's own module builds, which need them.

Test plan

  • cd platformio/HMTL_Test && pio test -e native — 50/50 pass. (platformio.ini gains -I ../../Libraries/HMTLprotocol, since HMTLTypes.h now includes it.)
  • HMTLTypes.h + HMTLMessaging.h parse clean against the desktop stub, both with and without ARDUINO defined.
  • HMTLWireFormat.h compiles standalone with c++ -std=c++11 -Wall -Wextra and no Arduino headers, and the struct sizes come out right (msg_hdr_t 8B, output_hdr_t 2B, msg_program_t 35B).
  • Downstream: pio run -e ampworks in WLED_dev builds clean with the bridge importing this header, and the bridge's host unit test compiles the real HMTLWireFormat.h with a plain c++ — that test is the standing regression check that this header stays dependency-free.

Not exercised locally: platformio/HMTL_Module and friends, whose platformio.ini sets lib_dir = /Users/amp/Dropbox/Arduino/libraries (symlinks into a different HMTL checkout). They pick HMTLprotocol up from the same symlink set, and the header-parse checks above cover the compile surface.

🤖 Generated with Claude Code

https://claude.ai/code/session_013HqzdRdTRnreSvevaQGQSJ

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
aphelps-claude-bot added a commit to aphelps/WLED that referenced this pull request Jul 28, 2026
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
aphelps-claude-bot added a commit to aphelps/WLED_dev that referenced this pull request Jul 28, 2026
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 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.

Self-review of 7ca6637 (wire-format extraction). Verification performed against the actual tree, results first, findings below as inline comments.

1. Pure move — CONFIRMED. A difflib opcode walk over HMTLTypes.h, HMTLMessaging.h and HMTLPrograms.h at 7ca6637^ vs 7ca6637 shows all 5 deleted blocks (191 non-blank lines) present byte-identical and contiguous in HMTLWireFormat.h. The only content in the new header that is not a verbatim relocation is the include guard, #include <stdint.h>, #include "Socket.h", and the guarded byte/boolean aliases. Nothing was dropped, altered, or duplicated; no field, code point, or layout change to the format deployed hardware speaks.

2. Dependency-freedom — CONFIRMED. HMTLWireFormat.h includes exactly <stdint.h> and Socket.h (itself include-free); it compiles standalone with c++ -std=c++11 -Wall -Wextra and the WLED bridge host test passes against the real header. Existing consumers still compile: pio test -e native in platformio/HMTL_Test passes 50/50 at this commit (exercising HMTLTypes.h, HMTLMessaging.h, HMTLPrograms.h through their new transitive include).

3. Manifests — OK for both sides. "platforms": ["atmelavr", "espressif32"] satisfies WLED's lib_compat_mode = strict; HMTL's own module envs (HMTL_Module, HMTL_Bringup, etc.) use PlatformIO's default soft compat mode (framework check only) and Arduino IDE ignores library.json entirely, so the AVR module builds are unaffected. Two nits, no action required: the top-level "include" key is not a field in the current library.json spec (ignored, harmless), and dependencies declared by bare name (Socket, RS485Utils) resolve from lib_dir/lib_extra_dirs when present but would fall through to a PlatformIO registry lookup on a machine without them — a version/URL pin is worth considering eventually.

4. Struct packing — verified empirically (avr-g++ 8.5, -mmcu=atmega328p vs host clang, whose layout matches ESP32 for these types). Identical size and offsets on both: msg_hdr_t (8), msg_value_t (4), msg_rgb_t (5), msg_program_t (35), config_hdr_v1_t (5), config_hdr_v3_t (10), msg_set_addr_t (4), msg_sensor_data_t (2). Two structs differ across platforms — see the inline comments on msg_poll_response_t (trailing padding only, 15 vs 16 B; already tracked as the poll-response interop item in WLED_dev#20's Testing Required) and config_hdr_v2_t (interior padding — field offsets actually differ).

Note on the inline suggestions: they are comment/documentation additions. If applied, land them as a follow-up commit on this branch rather than amending 7ca6637, so the extraction commit itself stays byte-verifiable as a pure move.

Comment thread Libraries/HMTLprotocol/HMTLWireFormat.h Resolved
Comment thread Libraries/HMTLprotocol/HMTLWireFormat.h Resolved
Comment thread Libraries/HMTLprotocol/HMTLWireFormat.h Resolved
Comment thread Libraries/HMTLprotocol/HMTLWireFormat.h Resolved
Comment thread Libraries/HMTLprotocol/HMTLWireFormat.h Resolved
Comment thread Libraries/README.md Resolved
Comment thread platformio/HMTL_Test/platformio.ini Resolved

@aphelps aphelps left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

There appear to be unaddressed self-review comments. Please follow up and get all threads closed either by changes or counter argument.

Comment thread Libraries/HMTLprotocol/HMTLWireFormat.h Resolved
Comment thread Libraries/HMTLprotocol/HMTLWireFormat.h Resolved
aphelps-claude-bot and others added 3 commits July 29, 2026 15:58
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
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
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
aphelps-claude-bot added a commit to aphelps/WLED that referenced this pull request Jul 29, 2026
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 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.

Addressed CHANGES_REQUESTED review 4813374061. All 8 threads are now resolved — each one either by a code change or, in the one case where I disagreed with both suggested fixes, by a documented counter-argument. Three new commits, no squash and no rebase:

commit what
41a27ea pack every wire struct so AVR and ESP32 layouts agree; data[] → data[0]; copyright date; <Arduino.h> include-order contract
70cf315 stubs/Socket.h so pio test -e native runs on a fresh clone; new test/test_wire_format pinning every size and offset
cfd8af3 Libraries/README.md: the new linking requirement and the packing invariant

The load-bearing one

The same format needs to work on an Arduino with ATMega328 and an ESP32 since they will be communicating

Taken as a general invariant for this header rather than a note about config_hdr_v2_t: every wire struct must have identical size and identical field offsets under avr-gcc and under a 32-bit compiler. All 13 structs are now __attribute__((__packed__)). Two actually drifted:

  • config_hdr_v2_t — 8 B with address at offset 3 on AVR, 10 B with address at offset 4 on 32-bit. Interior padding, so a v2 EEPROM blob written by a deployed module misparses.
  • msg_poll_response_t — 15 B vs 16 B, which made HMTL_MSG_POLL_MIN_LEN 23 or 24 depending on target. An AVR master length-checking a poll response against its own constant could reject the ESP32 bridge's.

Packing is layout-neutral on avr-gcc (alignment is already 1), so no deployed module changes a byte; it is corrective on 32-bit, making that side match the AVR layout already on the wire.

Proof, seven ABI/toolchain combinations. A scratch layout_check.cpp static_asserts the size of all 13 structs, the offset of every named field and all seven HMTL_MSG_*_LEN macros; one differing number is a compile error:

host-clang21                   PASS      host-g++16                     PASS
host-clang21-fpack1            PASS      host-g++16-fpack1              PASS
avr-g++9.5(atmega328p)         PASS      avr-g++8.5-pio(atmega328p)     PASS
xtensa-esp32-g++8.4            PASS

Before 41a27ea the identical check failed on all four 32-bit configurations and passed on both AVR ones — the AVR layout was the correct one, which is the direction the fix had to go. Permanent equivalents now live in test/test_wire_format (this repo) and rs485_bridge_protocol.h's static_assert block (WLED#11), so a future edit fails a build rather than a bus.

Regression checks

  • pio test -e native — 54/54 (was 50), and now with no external include paths at all.
  • HMTL_Module nano (AVR, avr-g++ 8.5) built against this branch via a PLATFORMIO_LIB_DIR override — SUCCESS, flash 85.5%, no new warnings and no -Waddress-of-packed-member fallout.
  • WLED#11 ab8163cd updated to the uniform sizes: pio run -e ampworks / esp32dev / usermods / apa102_mpr121 plus the usermods_esp32c3/s2/s3 CI matrix envs all SUCCESS; host test PASS under clang 21 and g++ 16, each with and without -fpack-struct=1, all four warning-free. Full Test Plan 17/17 green.

Worth your attention (not changed here)

The program payloads that travel inside msg_program_t.values[] live in HMTLMessaging/HMTLPrograms.h — behind FastLED.h, so outside the extraction — and have the same bug. Measured: hmtl_program_blink_t 10 B with off_period @5 on AVR vs 12 B @6 on 32-bit (interior), timed_change 10/12, fade 11/12, sparkle 13/14, circular 9/10, and TimeSync.h's msg_time_sync_t 5 B with timestamp @1 vs 8 B @4 (interior). sequence, brightness and color are clean. Left alone deliberately — HMTLPrograms.h is covered by three native suites and deserves its own change, not a drive-by. Details in the config_hdr_v2_t thread; say the word and I will do it the same way.

@aphelps-claude-bot
aphelps-claude-bot merged commit 023e7b9 into main Jul 30, 2026
@aphelps-claude-bot
aphelps-claude-bot deleted the rs485-bridge-wire-format 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 to aphelps/WLED_dev that referenced this pull request Jul 30, 2026
* 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]>
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