Repository navigation
Description
Summary
WLED-to-WLED UDP sync (the "notifier" on port 21324) started as a simple way to make other instances follow a change made in the UI. Over 12 protocol versions it has become a hybrid:
- It sends a full snapshot when something changes.
- It may blindly re-send that snapshot (
udpNumRetries). - It has no sequence numbers, acknowledgements or periodic refresh.
So it is neither a stream (like Art-Net or E1.31) nor a reliable state-replication protocol. The packet is an implicit byte layout rather than a defined struct. There is no magic, no length field and no sender identity, which makes it hard to parse safely and hard to extend.
This issue does two things:
- It lists concrete problems in the current implementation. Some of them are bugs worth fixing now, whatever else we decide.
- It proposes a direction for a "sync v2" for discussion.
All line references are to main @ fce41f2.
What works well (to keep)
- Zero configuration. It's broadcast on a default port and just works.
- Backward compatibility. Twelve protocol versions still interoperate, because receivers check the version byte before reading each field.
- Loop prevention. State applied from a notification uses
CALL_MODE_NOTIFICATION, which is never re-sent. - Receive filters. Brightness, color, effects, palette, segment options and bounds can each be accepted or ignored, and there are 8 sync groups.
- Timebase and system-time sync.
Problems in the current implementation
Bugs (verified in code)
- The receive parser reads past the end of its buffer.
parseNotifyPacket()is never given the packet length (udp.cpp#L206, caller at #L562).- Any packet whose first byte is
0x00has bytes 0–40 read, even a 1-byte packet. - The segment loop uses the sender-supplied segment count and record stride (
udpIn[39]/udpIn[40]). It is bounded againstUDP_IN_MAXSIZE(1472), not against the actual packet size (#L266-L268). - The receive buffer is a stack VLA (#L522).
- The result is that stale stack bytes can be applied as LED state.
- Uninitialised stack memory is broadcast.
- PSRAM builds emit a second, garbage datagram.
- With
BOARD_HAS_PSRAM,MAX_NUM_SEGMENTSis 64 (FX.h#L94), so the packet is 2345 bytes. - arduino-esp32's
WiFiUDP::write()uses a fixed 1460-byte tx buffer. When the buffer is full it sends what it has as its own datagram and starts again. - So the tail goes out as a separate ~885-byte packet that starts at an arbitrary byte of
udpOut, usually uninitialised. - Depending on that first byte, receivers treat it as a notifier packet (
0), a UDP realtime packet (1–5) or input to the UDP HTTP/JSON API. - This affects e.g. the wrover and ESP32-S3 PSRAM builds.
- With
- Retries make the sender ignore everyone else.
- ESP-NOW sync changes segments from another task.
- On ESP32, QuickEspNow delivers receive callbacks from its own
receive_handleFreeRTOS task. That task has the same priority and core asloopTask, so the two are time-sliced. espNowReceiveCB()callsparseNotifyPacket()directly (#L976), which changes segments.strip.suspend()isn't a lock.
- On ESP32, QuickEspNow delivers receive callbacks from its own
- Retries never happen over ESP-NOW alone. The retry path is gated on
udpConnected(#L471). - Nightlight ignores the receive filters. Nightlight state is always applied, whatever the receive filters say (#L400-L401).
Design limitations
- No real sender identity.
- There is no sender id in the notifier packet.
- In the node list (port 65506) the node id is the last IP octet, which can collide.
- The node list takes the IP from the payload, not from the datagram's source address.
- Retries aren't replays.
- A retry re-reads the current state and re-encodes it. It is not the same message again, so a late "retry" may carry different data.
- The
followUpflag (byte 24) is sent but no receiver uses it.
- No sequence numbers. A delayed or duplicated packet simply overwrites newer state.
- Late joiners never catch up. A node that boots or reconnects stays out of sync until someone changes something. There is no periodic state and no "send me the current state" request.
- Segments are identified by position among active segments, not by real id. This causes fix-up logic on receive (#L281-L289).
- Group membership is invisible. Nodes don't announce which groups they send to or receive from.
- Echo suppression is a timer, not a check of who sent the packet.
- The packet format is a "version ladder".
- Every new field means another version byte and more
if (version > N)branches. - The fixed 41-byte header has no spare bytes.
- The documented layout comment is already out of date (#L58).
- Every new field means another version byte and more
Not listed as problems
- Authentication.
docs/hardening.instructions.mdanddocs/securecode.instructions.mdexplicitly exempt broadcast/multicast sync from needing it. - Application-level checksums. They add little over the UDP checksum and the 802.11 and ESP-NOW link-layer CRCs. What is actually missing is structural validation (magic, length, version) and sequencing.
Proposal
Phase 0: harden the existing (legacy) path now
This is a small, separate PR. It is needed whatever happens with v2, because new firmware should keep receiving legacy packets for a while.
- Pass the length to
parseNotifyPacket():- Enforce a minimum length per version.
- Require a sane segment stride.
- Bound every segment record by the real packet length.
- Replace the VLA with a fixed-size buffer.
notify():- Zero the buffer.
- Send only the header plus the active segments.
- Cap at one MTU-safe datagram. This fixes the PSRAM split.
- Track the echo-suppression time separately from the retry timer, and allow retries over ESP-NOW alone.
- ESP-NOW: copy the reassembled packet into a buffer, then parse it on the main loop instead of in the callback.
Phase 1/2: "sync v2" (design doc + prototype)
New firmware would send only v2, but receive both v2 and legacy v12 during a transition period.
Two models were considered.
A. Soft-state replication. This is the recommended option.
- Each node has a stable
nodeId, derived from its MAC address. - State is versioned with
(epoch, seq).epochchanges each time the node boots;seqincreases with each change. - When something changes, the node sends a
STATEmessage. - Every N seconds (e.g. 10–30 s) it sends a full
STATEheartbeat. The heartbeat also acts as the membership/discovery beacon, replacing the 65506 node-info packet over time. - Receivers apply a message only if it is newer than the last state they applied for that group (last writer wins, ties broken by
nodeId).- Duplicates and retries are therefore harmless.
- Retries become exact replays of the same
seq. - Echo suppression becomes simply "
nodeId == self". The 1-second deaf window disappears.
- Late joiners converge at the next heartbeat, or immediately via a
STATE_REQmessage (state transfer on join).
B. A JGroups-style stack. This would mean implementing each JGroups protocol in WLED:
- PING for discovery.
- GMS for a coordinator and membership views.
- NAKACK2 for per-sender sequence numbers with retransmission on NAK.
- STABLE for gossip so retransmit buffers can be freed.
- FD_ALL for heartbeat-based failure detection.
- STATE_TRANSFER for bringing a joining node up to date.
It gives ordered, reliable delivery, but it costs:
- Every sender needs a retransmit buffer.
- Coordinator election and view changes add complexity.
- NAKs need unicast replies.
- ESP8266 RAM is already tight; the node list is capped at 24 there (const.h#L702).
Why A. LED state is last-writer-wins, idempotent state, not a log of commands. Guaranteed gap-free delivery of intermediate states has no value; only convergence to the latest state matters. So the proposal is to borrow JGroups' ideas without its reliable-delivery machinery:
- Borrow: identity,
seq/epoch, membership via heartbeats, failure detection by heartbeat age, and state transfer on join. - Leave out: NAKACK, GMS and a coordinator.
Wire format sketch (v2)
Defined as packed structs in a new header, with static_assert on the sizes.
| Field | Size | Notes |
|---|---|---|
magic |
4 | e.g. 0xA5 'W' 'S' '2'. The first byte is non-ASCII and outside the values existing receivers dispatch on (0, 1–5, 0x9C, 255, {, A–Z), so legacy nodes ignore it |
ver |
1 | protocol version |
msgType |
1 | STATE, STATE_REQ, BEACON |
flags |
1 | |
groupMask |
1 | sync groups |
nodeId |
4 | stable sender id |
epoch |
2 | changes each time the sender boots |
seq |
2 | increases with each state change |
payloadLen |
2 | explicit length |
The header is followed by TLV sections, so adding fields doesn't need another version-byte ladder:
- Global state: brightness, transition, nightlight, timebase, time.
- Per-segment records keyed by the real segment id.
- Node info: name, build, board.
The receiver takes the sender's IP from the datagram's source address, not the payload.
Other parts of the sketch:
- Datagram size. A hard limit of about 1400 bytes per datagram. Larger states are split by segment into numbered parts that share the same
(epoch, seq). - ESP-NOW. It carries the same datagrams. An optional CRC16 covers reassembly of fragments across ESP-NOW packets.
- Settings. The existing send/receive flags and groups are reused. No new UI is planned initially, apart from perhaps a heartbeat interval.
Out of scope
The audio-reactive sync usermod (multicast 11988) is genuinely a stream and is better served as such.
Questions for discussion
- Should v2 stay on port 21324, dispatched by magic, or move to a new port?
- How long should the legacy send path be kept, if at all? The current proposal is to receive legacy only.
- Should the heartbeat beacon fully replace the 65506 node-info packet, or should both be sent for a release or two?
- Is a configurable heartbeat interval needed, or is a fixed one enough?
This analysis and proposal were prepared with AI assistance (Claude Code). The defects listed were checked against the source at the referenced lines.
Activity