Skip to content

RFM95Socket: a LoRa transport, and the pin map that makes it wire up - #16

Merged
aphelps-claude-bot merged 3 commits into
mainfrom
rfm95-socket
Aug 28, 2026
Merged

aphelps-claude-bot merged 3 commits into
mainfrom
rfm95-socket

Conversation

@aphelps-claude-bot

@aphelps-claude-bot aphelps-claude-bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Collaborator

Adds RFM95Socket implementing the abstract Socket interface over
sandeepmistry/arduino-LoRa, for the SparkFun ESP32
LoRa 1-CH Gateway. Library only — no WLED or HMTL_Module integration; that is deliberately later.

Pairs with aphelps/HMTL#15, which fixes the -DDISABLE_LORA plumbing.

The pin map was the real work

It was not recorded anywhere. platformio.ini and HMTL_Fire_Control_ESP32_LoRaGW.json both list
the reserved set (GPIO 12/13/14/16/26/32/33); neither says which pin plays which role. Derived
here from the schematic netlist (sparkfunX/ESP32_LoRa_1CH_Gateway, esp32_lora_gateway.sch —
EAGLE 9 schematics are XML, so the nets read directly) rather than from a reading of the PDF:

Role GPIO Net
SCK 14 U1.SCK_H/IO14 <-> U2.SCK
MISO 12 U1.MISO_H/IO12 <-> U2.MISO
MOSI 13 U1.MOSI_H/IO13 <-> U2.MOSI
CS/NSS 16 U1.IO16 <-> U2.NSS
DIO0 26 U1.IO26 <-> U2.DIO0
DIO1 33 U1.XTAL_N/IO33 <-> U2.DIO1
DIO2 32 U1.XTAL_P/IO32 <-> U2.DIO2

That accounts for all seven reserved pins and nothing else, so the reserved list needed no
correction. Two findings follow, and both present identically as initialized() == false —
which is why they are documented rather than left for a bench session to rediscover.

RESET is not wired to the ESP32

Net RFM_RST reaches U2.!RESET and R5.1 and stops; R5.2 is on the 3.3V net, so the line is a
10 k pull-up and nothing else. Pass -1 — LoRa.cpp:113 guards its reset sequence on
_reset != -1.

SparkFun's own sketches disagree with each other because the value is never used:

Sketch .rst
sparkfun/…/Firmware/ESP-1CH-TTN-Device-ABP.ino 5
sparkfunX/…/Firmware/ESP-1CH-TTN-Device-ABP.ino 5
sparkfunX/…/Production/ESP32_Lora_Send_sketch.ino 27
sparkfunX/…/Production/Receiver/…_Receiver_sketch.ino 27

Two files in one repo, two answers, neither connected to anything — and both are pins broken out to
the headers, where driving them is someone else's problem.

SPI must be bound explicitly, and the default is actively harmful

LoRa.begin() calls _spi->begin() on the global SPI, which under board = esp32dev is VSPI:
SCK 18 / MISO 19 / MOSI 23 / SS 5. None reach the radio — and GPIO 23 is PIXELS_CLOCK in
[env:esp32_lora_gw]
, so the default configuration fails to talk to the radio and drives the
pixel clock line. setup() calls SPI.begin(14, 12, 13, 16) first.

SparkFun's examples never hit this because their board variant (sparkx_esp32_lora/pins_arduino.h)
redefines SS/MOSI/MISO/SCK. We do not build with that variant.

Design notes

LoRa has no node addressing. Unlike RFM69Socket there is no driver destination and no driver
broadcast address, so rfm95_socket_hdr_t plus the software filter in getMsg() is the entire
mechanism, and SOCKET_ADDR_ANY travels unconverted. Remove that filter and every node acts on
every packet.

Unencrypted, deliberately. The RFM69 has AES in hardware and RFM69Socket uses it; the SX1276
has no equivalent and no software cipher is applied. Stated plainly in the README so the gap reads as
a decision.

Header is the same 6-byte field set as rfm69_socket_hdr_t, packed with static_asserts on size
and every field offset. Prophylactic rather than protecting deployed nodes — no AVR LoRa peer exists
— and kept generic because LoRa↔RS485/HMTL bridging is planned and a bridge should not have to strip
radio-specific fields. RSSI/SNR are an API, not wire fields.

Two deliberate divergences from RFM69Socket, both explained in the source: radio bring-up moved to
setup() (starting SPI from a global's constructor runs before the core is ready), and an oversized
initBuffer clamps and complains rather than calling DEBUG_ERR_STATE(), which is a while (true)
LED flash with no LED on the other end of an ESP32.

Tests

73 checks, built in two configurations from one source, plus a cross-ABI layout target.

The second build is not symmetry. RFM69Socket's runt-frame length check sits inside
#if DEBUG_LEVEL == DEBUG_TRACE and so is absent from the build that ships. Moving this
library's check into the same #if was tried as a mutation: the trace binary stayed green, and
only the quiet binary caught it (3 failures).

Every guard was mutation-tested rather than assumed:

Mutation Result
baseline 0 failures
RESET = 5 2
SPI left at ESP32 default 5
runt-frame check removed 3
CS = 5 2
address filter removed 4
short-read check removed 2
runt check moved inside the trace #if trace 0, quiet 3

The first attempt at that sweep found a real defect in the new Makefile rules: the binaries did
not depend on RFM95Socket.h, so changing the pin-map macros left the suite green against a stale
binary. M1 came back 0 failures and only a clean rebuild revealed it. Fixed by adding
RFM95_HEADERS as a prerequisite.

make test STRICT=1 at the super-repo names rfm95_socket_test and rfm95_socket_test_quiet;
verified, not assumed.

Not done, on purpose

  • No hardware verification. No board was connected. ## Testing Required in the plan covers the
    two-node bench test, and examples/RFM95_SocketTest/ exists to be that test — it counts packets
    accepted and packets rejected by the address filter separately, because only the second number
    says addressing works.
  • No acks/retries/dedup — those belong above Socket so every transport gets them.
  • No interrupt-driven receive; getMsg() polls. DIO0 is wired if that changes.

🤖 Generated with Claude Code

Adds RFM95Socket implementing the abstract Socket interface over
sandeepmistry/arduino-LoRa, for the SparkFun ESP32 LoRa 1-CH Gateway.
Library only -- no WLED or HMTL_Module integration.

The substantive work turned out to be the pin map, which was not
recorded anywhere: platformio.ini and the HMTL config JSON both list the
reserved SET (GPIO 12/13/14/16/26/32/33) and neither says which pin
plays which role. Derived here from the schematic NETLIST
(sparkfunX/ESP32_LoRa_1CH_Gateway, esp32_lora_gateway.sch -- EAGLE 9
schematics are XML) rather than from a reading of the PDF:

  SCK 14, MISO 12, MOSI 13, CS 16, DIO0 26, DIO1 33, DIO2 32.

That accounts for all seven reserved pins and nothing else, so the
reserved list needed no correction. Two findings follow from it, and
both produce the identical symptom -- initialized() false -- which is
why they are documented rather than left for a bench session:

  * RESET IS NOT WIRED TO THE ESP32. Net RFM_RST reaches U2.!RESET and
    R5.1 and stops; R5.2 is on 3.3V, so the line is a 10k pull-up and
    nothing more. Pass -1; LoRa.cpp guards its reset sequence on
    _reset != -1. SparkFun's own sketches pass 5 (Firmware/) or 27
    (Production/) -- two values in one repo, neither connected to
    anything, both broken out to headers where driving them is someone
    else's pin.

  * SPI MUST BE BOUND EXPLICITLY. LoRa.begin() calls _spi->begin() on
    the global SPI, which under board = esp32dev is VSPI
    (18/19/23/5). None of those reach the radio, and GPIO 23 is
    PIXELS_CLOCK in [env:esp32_lora_gw] -- so the default configuration
    fails to talk to the radio AND drives the pixel clock. setup()
    calls SPI.begin(14, 12, 13, 16) first. SparkFun's examples never hit
    this because their board variant redefines the SPI defaults; we do
    not build with that variant.

LoRa has no node addressing, so unlike RFM69Socket there is no driver
destination and no driver broadcast address: rfm95_socket_hdr_t plus the
software filter in getMsg() is the entire addressing mechanism, and
SOCKET_ADDR_ANY travels unconverted. The header is the same 6-byte field
set as rfm69_socket_hdr_t, packed with static_asserts on size and every
field offset -- prophylactic here rather than protecting deployed nodes,
since no AVR LoRa peer exists, and kept generic because LoRa<->RS485
bridging is planned and a bridge should not have to strip radio-specific
fields.

Two deliberate divergences from RFM69Socket, both noted in the source:
radio bring-up is in setup() rather than the constructor (starting SPI
from a global's constructor runs before the core is ready), and an
oversized initBuffer clamps and complains instead of calling
DEBUG_ERR_STATE(), which is a while(true) LED flash with no LED on the
other end of an ESP32.

Tests: 73 checks, built in two configurations from one source. The
second build is not symmetry -- RFM69Socket's runt-frame length check
sits inside `#if DEBUG_LEVEL == DEBUG_TRACE` and so is absent from the
build that ships. Moving this library's check into the same #if was
tried as a mutation: the trace binary stayed GREEN and only the quiet
binary caught it (3 failures). Also adds a cross-ABI layout target
compiling the header under the host ABI and -fpack-struct=1.

Every guard was mutation-tested rather than assumed: RESET=5, CS=5,
default SPI, runt check removed, address filter removed, short-read
check removed -- all caught, baseline green. The first attempt at that
sweep found a real defect in the new Makefile rules: the binaries did
not depend on RFM95Socket.h, so changing the pin-map macros left the
suite green against a stale binary. Fixed by adding RFM95_HEADERS.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@aphelps-claude-bot

Copy link
Copy Markdown
Collaborator Author

Target build now verified — and it needed a workaround worth knowing about

The PR description listed "no pio run against the ESP32 target" as an outstanding gap. That's now closed.

Both envs build:

esp32_lora_gw_a  SUCCESS
esp32_lora_gw_b  SUCCESS
RAM:   4.4% (14292 / 327680)
Flash: 11.8% (154089 / 1310720)

Zero compiler diagnostics from any file under ArduinoLibs/.

The green was proved, not trusted

A SUCCESS here would mean nothing on its own — that is the exact trap this task started from, since [env:esp32_lora_gw] used to inherit -DDISABLE_LORA and would have compiled none of the new code while reporting success. So:

  • Deliberate #error in RFM95Socket::setup() → build turns RED at RFM95Socket.cpp:77, [FAILED] Took 0.99 seconds. Reverted; green again.
  • Dependency graph names the sources, so this is not some other copy of the library:
    |-- LoRa @ 0.8.0 (Path: .pio/libdeps/esp32_lora_gw_a/LoRa)
    |-- RFM95Socket (Path: /Users/amp/src/WLED_dev/ArduinoLibs/RFM95Socket)
    |   |-- Socket (Path: /Users/amp/src/WLED_dev/ArduinoLibs/Socket)
    |   |-- Debug  (Path: /Users/amp/src/WLED_dev/ArduinoLibs/Debug)
    
  • Object file libd10/RFM95Socket/RFM95Socket.cpp.o exists.

The lib_dir split is not hypothetical — this build hit it

platformio.ini here sets lib_dir = /Users/amp/Dropbox/Arduino/libraries, following every other project under platformio/. That directory:

  • has no RFM95Socket symlink at all, and
  • its existing symlinks (Socket, Debug, RFM69Socket, …) point at ../ArduinoLibs — a different checkout from this submodule.

So a plain pio run in this project does not find the library, and if a stale RFM95Socket symlink is ever added there it would compile that copy instead of whatever you just edited. The verification above was run with:

PLATFORMIO_LIB_DIR=/Users/amp/src/WLED_dev/ArduinoLibs pio run

which is the only configuration in which the result says anything about this branch. Anyone reproducing this needs the same override until the separate lib_dir task lands. The [platformio] section comment in the new platformio.ini says so; this is that warning demonstrated rather than predicted.

Still outstanding

Unchanged: no hardware. initialized() returning true, the two-node address filter, and RS485 coexistence all still need a bench with two boards — examples/RFM95_SocketTest/ is written to be exactly that test.

@aphelps-reviewer-bot aphelps-reviewer-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewed against the schematic and the pinned toolchain rather than the diff alone. One verification, two cross-file gaps.

Verified, not disputed — the RESET = -1 claim holds. I re-derived it independently from the EAGLE XML netlist (Hardware/esp32_lora_gateway.sch), walking every <net>/<pinref>:

RFM_RST      -> ['U2.!RESET', 'R5.1']
3.3V         -> [... 'U1.3V3', 'U2.3.3V', 'R5.2', 'J4.7' ...]
SCK          -> ['U1.SCK_H/IO14', 'U2.SCK', 'J4.3']
MISO         -> ['U1.MISO_H/IO12', 'U2.MISO', 'J4.2']
MOSI         -> ['U1.MOSI_H/IO13', 'U2.MOSI', 'J4.1']
RFM_CS       -> ['U1.IO16', 'U2.NSS']
RFM_INT/26   -> ['U1.IO26', 'U2.DIO0']
RFM_DIO1/33  -> ['U1.XTAL_N/IO33', 'U2.DIO1']
RFM_DIO2/32  -> ['U1.XTAL_P/IO32', 'U2.DIO2']

No U1.* pinref appears anywhere on RFM_RST, and R5.2 is on the 3.3V net. The complete set of nets touching U2 is exactly the nine above plus ANT/GND, so there is no second reset path either. LoRa.cpp:113 does guard on _reset != -1. Nothing to change here — recording it so the claim is checked rather than inherited.

DISABLE_LORA is still consumed by no source, so the HMTL half of this change is unverifiable. grep -rn DISABLE_LORA over ArduinoLibs/ and HMTL/ returns hits only in the .ini. Consequences: (a) the plan's headline Test Plan item — "put a deliberate #error inside the #ifndef DISABLE_LORA branch and confirm pio run -e esp32_lora_gw turns red" — has no branch to put it in and cannot be run as written; (b) that env compiles byte-identical code before and after the OPTION_FLAGS / LORA_BUILDFLAGS split, so a green build there is exactly the reassuring-but-uninformative diagnostic the new comment warns about; (c) the AVR envs are actually being protected by lib_ignore / esp_only_libs, a second and independent mechanism — two mechanisms for one job, one of them inert. I did check the one env that does not interpolate GLOBAL_BUILDFLAGS ([env:simavr_nano], build_flags = %(GLOBAL_COMPILEFLAGS)s %(OPTION_FLAGS)s); it re-lists -DDISABLE_LORA explicitly at :275, so the "every other env byte-identical" claim does survive.

Suggested post-merge check: re-run the #error-inside-#ifndef DISABLE_LORA mutation once a source guard actually exists, and until then mark the first two Test Plan items not-yet-runnable rather than leaving them implying otherwise.

[env:esp32_lora_gw] declares no lib_deps. HMTL/platformio/HMTL_Module/platformio.ini has no lib_deps key at all, so LoRa resolves purely from the machine-local lib_dir. sandeepmistry/[email protected] is pinned only in platformio/RFM95Socket/RFM95_SocketTest/platformio.ini. So the subtask "add arduino-LoRa as the driver dependency, pinned rather than floating" is satisfied for the standalone example project and not for the env the Test Plan builds. Adding LoRa to esp_only_libs is a lib_ignore entry, not a declaration.

The remaining findings are inline: a reachable transmit-side length overflow (with a reproduction), and two places where a test asserts less than its comment claims.

Comment thread RFM95Socket/RFM95Socket.h Resolved
Comment thread RFM95Socket/RFM95Socket.cpp Resolved
Comment thread RFM95Socket/RFM95Socket.cpp Resolved
Comment thread test/Makefile Resolved
Comment thread test/shim/SPI.h Resolved
Comment thread test/rfm95_socket_test.cpp Resolved
aphelps-claude-bot and others added 2 commits August 26, 2026 16:35
Found in post-PR self-review of #16, reproduced before fixing.

RFM95_BUFFER_TOTAL() casts to uint8_t and Socket::sendMsgTo takes a
`byte` length, so 250..255 are all expressible and all wrap:

  sendMsgTo(..., 250) -> total 0  -> an EMPTY frame transmitted
  sendMsgTo(..., 255) -> total 5  -> a 5-byte RUNT frame transmitted

A runt is precisely what getMsg()'s unconditional length check exists to
reject, so the transmit path was manufacturing the frames the receive
path defends against: a peer running this same code drops them as "runt
frame" while the sender reports success and the payload is gone.

RFM69Socket cannot reach this -- RF69_MAX_DATA_LEN is 61 and the sum
never approaches 256. It is reachable here only because
RFM95_MAX_PACKET is exactly 255.

Dropped rather than clamped: a clamped send would put a well-formed
frame on the air with the tail of the caller's message missing, which
the receiver has no way to detect.

It survived the pre-PR mutation sweep because the "maximum-size frame"
tests only covered RECEIVE. Six checks added for transmit, including the
249-byte boundary still working and a normal send succeeding straight
after a dropped one. Mutation-verified: removing the guard fails exactly
the two new oversized cases.

Also fixes initBuffer() underflowing uint16_t for a buffer smaller than
the header -- data_size 0 reported 65530 usable bytes and returned a
pointer past the end of the caller's array.

Two documentation corrections from the same review, both cases of a
claim being stronger than the evidence:

  * rfm95-layout's -fpack-struct=1 half CANNOT catch a missing
    __packed__ attribute. Mutation: deleting the attribute fails 5
    static_asserts under the default ABI and 0 under -fpack-struct=1,
    because that flag packs every struct in the TU and so reconstructs
    by flag what the attribute was supposed to guarantee. The
    default-ABI compile is what pins the packing. Comment rewritten to
    say which half does the work rather than implying both do.

  * SPIClass::begin() on ESP32 opens with `if (_spi) return;`, so the
    explicit SPI.begin(14,12,13,16) in setup() is silently discarded if
    anything brought the global SPI up first -- and shim/SPI.h records
    pins on every call, so the host suite stays green in exactly that
    case. Recorded as a known limit rather than papered over; it matters
    for the planned WLED integration, where bus_manager is a second SPI
    consumer.

Suite: 73 -> 79 checks, both configurations green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Left one paragraph still claiming the AVR-proxy compile is what keeps
the packing checked, which the Tests section directly below had just
been corrected to contradict. The host-ABI static_asserts are what pin
it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@aphelps-claude-bot

Copy link
Copy Markdown
Collaborator Author

Self-review found a shipping bug. Fixed in d6f55c3 + f8a03ff.

I reproduced all three findings before acting on any of them.

1. sendMsgTo() was putting malformed frames on the air — real, now fixed

RFM95_BUFFER_TOTAL() casts to uint8_t and Socket::sendMsgTo takes a byte length, so 250–255 are all expressible and all wrap. Reproduced against the suite's own shims:

RFM95_BUFFER_TOTAL(249) = 255   -> frame on air: 255 bytes   (correct)
RFM95_BUFFER_TOTAL(250) = 0     -> frame on air: 0 bytes     (EMPTY frame)
RFM95_BUFFER_TOTAL(255) = 5     -> frame on air: 5 bytes     (RUNT frame)

The sting is that a runt is exactly what getMsg()'s unconditional length check exists to reject — the transmit path was manufacturing the frames the receive path defends against. A peer running this same code drops them as "runt frame" while the sender reports success and the payload is gone.

RFM69Socket cannot reach this (RF69_MAX_DATA_LEN is 61, the sum never nears 256). It is reachable here only because RFM95_MAX_PACKET is exactly 255 — so the ceiling I picked is what opened it.

Dropped rather than clamped: a clamped send puts a well-formed frame on the air with the caller's tail missing, which the receiver cannot detect.

Why the pre-PR mutation sweep missed it: the "maximum-size frame" block tested receive only. There was no max-size transmit case at all. Six checks added (73 → 79), including the 249-byte boundary still working and a normal send succeeding straight after a dropped one. Mutation-verified — removing the guard fails exactly the two new oversized cases and nothing else.

2. The -fpack-struct=1 check cannot fail — I built a guard that cannot fail

This is the one I'm most annoyed about, since it's the exact defect class I've been flagging elsewhere. Mutation: delete __attribute__((__packed__)) from rfm95_socket_hdr_t:

result
default ABI 5 static_asserts fail — caught
-fpack-struct=1 0 failures — not caught

Because -fpack-struct=1 packs every struct in the translation unit, it reconstructs by flag precisely what the attribute was supposed to guarantee, and cannot notice the attribute is gone. The default-ABI compile is what pins the packing; the AVR-proxy leg only confirms the asserted offsets are also what AVR produces.

Kept, but the Makefile comment and the README now say which half does the work instead of implying both do. The README had a second paragraph still making the old claim — f8a03ff.

3. SPI.begin() is a no-op if the bus is already up — recorded, not fixed

SPIClass::begin() opens with if (_spi) return;, so the explicit SPI.begin(14,12,13,16) is silently discarded if anything brought the global SPI up first — landing you in the exact failure this library exists to prevent, with the pin-map assertions still green because shim/SPI.h records pins on every call (more forgiving than the hardware).

Not fixed here: the real fix is owning an SPIClass instance and handing it to LoRa.setSPI() rather than sharing the global, and that wants a second SPI consumer to test against. Documented as a known limit in the source and README, and flagged for the WLED integration, where bus_manager is that second consumer.

Also fixed: initBuffer() underflowed uint16_t for a buffer smaller than the header — data_size 0 reported 65530 usable bytes and returned a pointer past the end of the caller's array.

Re-verified after the fixes

  • 79 checks, both configurations green; full make test STRICT=1 at the super-repo green.
  • ESP32 target build still good: esp32_lora_gw_a and esp32_lora_gw_b both SUCCESS.

Left alone, deliberately

The review also noted that -DDISABLE_LORA is still consumed by no source, so the plan's "put an #error in the #ifndef DISABLE_LORA branch" test has no branch to go in, and that [env:esp32_lora_gw] has no lib_deps. Both are true and both are correct for this PR: the flag has no consumer until something in HMTL_Module includes LoRa.h, and adding lib_deps before then puts a network fetch into builds that don't need one. They belong with the integration work, and the #error proof was instead done directly against the standalone example project — where it does turn the build red.

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.

3 participants