Skip to content

rs485_bridge: accept HMTL commands over HTTP, with a real reply - #19

Merged
aphelps-claude-bot merged 3 commits into
mainfrom
hmtl-http-endpoint
Aug 22, 2026
Merged

aphelps-claude-bot merged 3 commits into
mainfrom
hmtl-http-endpoint

Conversation

@aphelps-claude-bot

Copy link
Copy Markdown
Collaborator

Adds POST /hmtl to the rs485_bridge usermod, so HMTL commands do not require a raw-UDP client.

Why. A UDP command is unacknowledged and unretried, and one was observed lost in a four-frame burst during the 2026-08-19 bench validation. The loss is silent. This gives the caller a status to check and, where the frame asks for an answer, the module's actual reply. UDP is unchanged and stays the right choice for streaming or low-latency use.

Both protocol decisions were Adam's (2026-08-22): deferred response with a hard timeout, on the usermod's own path rather than under WLED's /json namespace.

What the response promises

The body always says which guarantee the caller got — without that, HTTP is UDP with extra steps.

status Meaning
applied-locally Addressed to this node; applied here, nothing went on the bus
replied Forwarded and the module answered; frame holds the reply as hex. The only status meaning the device acted.
accepted-unconfirmed Reached the transmit queue; reason says why there is no confirmation
rejected Never reached the bus (400 / 413 / 503)

Structure

The split is at the line where testing stops being possible. rs485_bridge_http.h holds decoding and the pending-reply table with no AsyncWebServer dependency, because that is where every interesting failure lives: a reply attributed to the wrong request, a request completed after its client vanished, a deadline that never fires.

Ingress reuses rs485b_validate_udp_ingress and rs485b_decide — the same calls as the UDP path, not copies, so the two cannot drift.

Verification

  • Host suite mutation-tested, 8 of 8 killed: arrival-order matching, ignoring message type, LIFO ordering, unsigned deadline comparison (the millis()-wrap bug), cancel-without-release, odd hex digit counts accepted, ignored buffer capacity, eviction instead of refusal.
  • make test-bridge green (native ABI, -fpack-struct=1 AVR-like ABI, and the new suite).
  • Builds: ampworks SUCCESS (flash 84.1%, 1322557 B) and usermods SUCCESS (the env that compiles the bridge out, covering the guarded path).

What I could not verify, stated plainly

The handler and disconnect callback run on the AsyncTCP task, loop() completes responses on the Arduino task, and the request object is deleted on the AsyncTCP task. Every table access is therefore under a portMUX critical section, and the slot is released inside the lock before responding so no two paths hold the same request handle. That reasoning is sound and it compiles — but "no use-after-free under a real disconnect race" is a property of two FreeRTOS tasks, not of the table, and no host test can make that claim. It is written into the plan's Testing Required with a concrete reproduction (kill a client mid-reply ~50 times; a failure shows as a LoadProhibited panic with AsyncTCP on the backtrace).

Deliberately not included

The HMTL_ALL_OUTPUTS exclusion rule, which the sibling pilot-flame plan owns. This endpoint is another way to deliver such a frame, so it must mirror that rule rather than invent one — this should not ship ahead of that decision.

Security is out of scope by decision, not oversight: trusted senders assumed, matching the bridge's existing unauthenticated UDP port. Recorded in the readme so it can be revisited as a decision.

Pairs with aphelps/WLED_dev#33.

A one-shot UDP frame is unacknowledged and unretried, and one was observed
lost in a four-frame burst during the 2026-08-19 bench validation. The loss
is silent — the sender cannot tell. POST /hmtl gives the caller a status to
check and, where the frame asks for an answer, the module's actual reply.
The UDP path is unchanged and remains the right choice for streaming use.

Same validation and the same routing decision as UDP: rs485b_validate_udp_ingress
and rs485b_decide are called, not reimplemented, so the two ingest paths cannot
drift apart.

The response always says WHICH guarantee the caller got. `replied` is the only
status meaning the device acted; `accepted-unconfirmed` means the frame reached
the wire and carries a `reason`. That distinction is the whole point of
preferring HTTP here — without it the caller has UDP's guarantee with extra steps.

Structure follows where testing stops being possible. rs485_bridge_http.h holds
the decoding and the pending-reply table with no AsyncWebServer dependency,
because that is where every interesting failure lives: a reply attributed to the
wrong request, a request completed after its client vanished, a deadline that
never fires. Its suite mutation-kills all eight: arrival-order matching, ignoring
message type, LIFO ordering, unsigned deadline comparison (the millis()-wrap
bug), cancel-without-release, odd hex digit counts, ignored buffer capacity, and
eviction instead of refusal.

Concurrency is deliberate rather than incidental. The route handler and the
disconnect callback run on the AsyncTCP task, loop() completes responses on the
Arduino task, and the request object is deleted on the AsyncTCP task, so every
access to the table is under a portMUX critical section and the slot is released
inside the lock before responding — no two paths can hold the same request
handle. That reasoning is sound and it compiles, but freedom from a use-after-free
under a real disconnect race is a hardware claim, and is recorded in the plan's
Testing Required rather than asserted here.

Replies correlate on source address + message type, oldest-first: HMTL's 8-byte
header carries no request id, so two simultaneous requests to the same address
for the same type are genuinely indistinguishable on the wire. A reply nothing
is waiting for is never attributed to a waiting request — it relays to the UDP
peer exactly as before, so an existing UDP client sees no change.

Not included: the HMTL_ALL_OUTPUTS exclusion rule, which the sibling pilot-flame
plan owns. Inventing it here would create a second definition to reconcile, so
this must not ship ahead of that decision.

@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 — POST /hmtl

Re-read the diff cold against the plan. Verified before posting: make test-bridge green across all three runs, ampworks and usermods both SUCCESS, and 8/8 mutations killed on the new suite.

Three things I want a reviewer to push on

1. The auto-detect order is load-bearing and easy to get backwards. Hex is tried before base64 because the hex alphabet is a subset of the base64 alphabet — "0a1b2c" is valid base64 and decodes to different bytes. Reversing those two lines silently mis-decodes every hex frame into a plausible-looking wrong frame that then fails CRC, so the symptom would be "the endpoint rejects everything" with nothing pointing at the decoder. There is a test pinning hex behaviour, but not one that would catch the reversal specifically. Worth adding if a reviewer agrees the risk is real.

2. request->_tempObject is doing double duty as a "handled" flag. ESPAsyncWebServer fires the body callback and then the request callback, and there is no first-class way to say "already answered" between them. I used _tempObject as a marker, which works but abuses a field the library intends for user payloads. If a future WLED handler on the same path uses _tempObject for its documented purpose, these two silently interfere. A dedicated small struct allocated per request would be cleaner at the cost of an allocation on the async task.

3. Local frames answer immediately, which means a POLL addressed to this node returns applied-locally rather than the poll data. handleDecision routes a local POLL into sendPollResponse(address) — addressed to ourselves, so it goes nowhere useful. The HTTP caller gets "applied" and no data. Arguably a local POLL should return the config block in the HTTP body. I left it alone because the plan scoped v1 to routing parity with UDP and inventing a response shape here would pre-empt the reply-relay design, but it is a rough edge a user will hit.

What is deliberately absent

  • The HMTL_ALL_OUTPUTS exclusion rule. The sibling pilot-flame plan owns it. This endpoint is another delivery route for such a frame, so it must mirror that rule rather than invent a second definition — this should not ship ahead of that decision.
  • Auth. Out of scope by Adam's decision, recorded in the readme as a decision rather than an omission, alongside the bridge's existing unauthenticated UDP port.

The claim I am not making

The concurrency is reasoned, not demonstrated. Handler and disconnect callback on the AsyncTCP task, completion from loop() on the Arduino task, request deleted on the AsyncTCP task — so the table is under a portMUX critical section and the slot is released inside the lock before responding, meaning no two paths can hold the same request handle. I believe that is correct. But it is a property of two FreeRTOS tasks, and the host suite cannot test it, so it is in Testing Required with a concrete reproduction rather than being called done.

One related design note a reviewer should sanity-check: completeHttpReply calls req->send() from loop(), i.e. outside the AsyncTCP task. ESPAsyncWebServer is generally used from its own task. The request object's lifetime is safe here (it lives until client disconnect, and we hold the lock across the release), but whether send() itself is safe to call cross-task in this fork's version is the specific thing hardware needs to prove.

Smaller notes

  • Route registration moved from setup() to loop(): the bridge is not running at usermod setup time (pins allocate first), and a route that 503s every caller is worse than one appearing a moment later. httpRoutesUp makes it once-only.
  • A claimed reply is also relayed to the UDP peer, so adding this endpoint changes nothing observable for an existing UDP client.
  • led_driver is named in the plan's build list but is not an env on this branch — it belongs to the separate led-driver-board-profile task still in Pending. I built usermods instead, which is the env that compiles the bridge out, and recorded the discrepancy in the plan.

My own review flagged that the auto-detect order is load-bearing and had no
test that would catch reversing it. The hex alphabet is a subset of base64's,
so a hex string is also valid base64 — decoding to entirely different bytes.
Trying base64 first would silently turn every hex frame into a plausible wrong
frame that then fails CRC, and the symptom ("it rejects everything") points
nowhere near the decoder.

The new case asserts the property that makes the order matter — that the two
decoders genuinely disagree on the same input — so it also fails if either is
ever changed such that they stop disagreeing, which is what would make the
ordering look safe when it is not.
Ran the endpoint on real hardware for the first time (bench board as the
bridge at RS485 address 96, frames built by the Python HMTLprotocol encoder
rather than by the code under test). The routing works — a frame addressed to
the node returns applied-locally, one addressed elsewhere returns
accepted-unconfirmed, and a POLL parks and falls back on timeout — but two
rejection paths named the wrong thing, which is the kind of defect that turns
a two-minute fix into an hour of looking in the wrong place.

1. A non-JSON body reported `missing "frame"`.

ArduinoJson will parse a bare scalar, so `this is not json` does not
necessarily set the error flag; it just yields a document with no "frame" key.
The handler then blamed the missing key. Now requires doc.is<JsonObject>() and
says "body is not a JSON object".

2. An all-hex string that fails hex decoding was reported as a bad FRAME.

The auto-detect tried hex, failed, and fell through to base64 — which accepted
it, because the hex alphabet is a subset of base64's. The garbage bytes then
failed frame validation, so "abc" came back as `frame failed validation`,
pointing the caller at their frame when the fault was their encoding.

The fallback is now guarded: an input made only of hex characters that will
not decode as hex is broken hex, and is reported as such. Anything containing
a non-hex character still falls through, so genuinely base64 input is
unaffected — including "zzzz", which really is valid base64 and correctly
reports a frame-validation failure rather than an encoding one.

rs485b_looks_like_hex is host-tested, including the property that makes the
guard necessary: for "abc", hex rejects it and base64 accepts it. Mutating the
guard to accept non-hex characters kills two assertions.

@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.

As a start this is ok. How would a person use this, seems like it needs some script updates in the HMTL repo?

Also I'd though this would let us have a json based way to have WLED send out HMTL messages over RS485 to connected devices, and it does, but not in a human usable way.

Lets add a P1 task (get it planned so I can approve development soon), to add additional usable endpoint heres that acts like the HMTLClient script, but via JSON (possibly REST styled?). It should let a human, scripts, a web UI, etc to send "set outputs to RGB value XXX" or "send sparkle program to device XYZ", etc. Include the API spec in the plan

@aphelps-claude-bot
aphelps-claude-bot merged commit cfe86c5 into main Aug 22, 2026
76 of 77 checks passed
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