Repository navigation
add touch-sync usermod: UDP sensor-event bus for cross-device effects - #3
Conversation
New usermods/ampworks/usermod_touch_sync.h (USERMOD_ID_TOUCH_SYNC=56) broadcasts MPR121 press/release edges as typed sensor-event packets over UDP broadcast and receives remote events into a ring buffer. Touch Pond drains the queue and spawns distinct-hue waves for remote touches; the effect now also runs on sensor-less display-only nodes. Registered behind -D USERMOD_TOUCH_SYNC in the ampworks env. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
aphelps
left a comment
There was a problem hiding this comment.
Since we detect all 12+1 sensors of the MPR121 the data for all of them should be sent in a single message.
| */ | ||
|
|
||
| #ifndef TOUCH_SYNC_PORT | ||
| #define TOUCH_SYNC_PORT 21330 |
There was a problem hiding this comment.
Does 21330 have any existing meaning?
There was a problem hiding this comment.
No external/standard meaning — 21330 is arbitrary, chosen to sit clear of WLED's own UDP ports (21324 notifier, 65506 node-list). It's documented in the header comment and overridable via the port cfg field. Fixed in 7019b71.
|
|
||
| // Wire packet — fixed layout, packed so it is identical across all devices. | ||
| struct __attribute__((packed)) TouchSyncPacket { | ||
| uint8_t magic[3]; // 'A','T','S' |
There was a problem hiding this comment.
Why "ATS"? Also is there a reason for not making this an easily aligned 4-byte thing?
There was a problem hiding this comment.
"ATS" = AMPWorks Touch Sync. Good call on alignment — switched to a 4-byte magic {'A','T','S','1'} so the header and its uint32 timestamp are naturally 4-byte aligned. The header is now a fixed 16 bytes with every field on its natural boundary. Fixed in 7019b71.
| struct __attribute__((packed)) TouchSyncPacket { | ||
| uint8_t magic[3]; // 'A','T','S' | ||
| uint8_t version; // protocol version (1) | ||
| uint8_t msgType; // 0 = sensor event | ||
| uint8_t sensorType; // TS_SENSOR_* (which kind of sensor) | ||
| uint8_t channel; // electrode / channel index | ||
| uint8_t value; // event value (e.g. 1=press, 0=release) | ||
| uint16_t deviceId; // origin device id | ||
| uint16_t seq; // per-sender sequence number (for future dedup/loss tracking) | ||
| uint32_t timestamp; // millis() + strip.timebase at origin |
There was a problem hiding this comment.
This should be refactored into a header that applies to all sensor types, and then sensor data. The amount of sensor data should be a field in the header. The data should have its own struct type, one for each sensor type
There was a problem hiding this comment.
Done in 7019b71. Split into a generic TouchSyncHeader (magic, version, msgType, sensorType, dataLen, deviceId, seq, timestamp) plus a per-sensor-type data struct — TsTouchData for TS_SENSOR_TOUCH. header.dataLen carries the sensor-data byte count; adding a sensor type = new TS_SENSOR_* tag + packed struct + a dispatchMessage() branch, no header change. MPR121 now sends all 13 channels (12 electrodes + proximity) in one snapshot bitmask rather than per-edge packets; the receiver derives per-device edges.
Addresses review on PR #3: - Generic 4-byte-aligned TouchSyncHeader (magic 'ATS1', version, msgType, sensorType, dataLen, deviceId, seq, timestamp) common to all sensor types; per-type data struct follows, length carried in header.dataLen. - Send ALL MPR121 sensors (12 electrodes + proximity) in one snapshot message (TsTouchData bitmask) instead of one packet per electrode edge. - Receiver derives per-device rising/falling edges from successive snapshots and enqueues discrete RemoteSensorEvents; consumer API (popRemoteEvent) unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
aphelps-claude-bot
left a comment
There was a problem hiding this comment.
Re-review of 7019b71 — CR addressed: all four requested changes are in. (1) One snapshot message now carries every channel via TsTouchData.touched (bitmask over MPR121::TOTAL_SENSORS = 13, i.e. 12 electrodes + proximity), replacing the per-edge packets. (2) The wire format is split into a generic TouchSyncHeader plus a per-sensor-type data struct, with dataLen carried in the header and a dispatchMessage() switch on sensorType — adding a sensor type needs no header change. (3) The magic is now a 4-byte {'A','T','S','1'} placed first so the struct and the uint32 timestamp stay 4-byte aligned. (4) Port question was answered in the header comment.
The variable-length receive parse looks correct: n is capped by udp.read(buf, RX_BUF_LEN), and the guard sizeof(h) + h.dataLen <= n makes a hostile dataLen (max 255) fail rather than over-read, since RX_BUF_LEN (80) < 255. Endianness is fine for the all-ESP32 fleet and is documented.
Findings below are minor / non-blocking — mostly behavioral notes and forward-looking nits, no memory-safety bugs.
aphelps-claude-bot
left a comment
There was a problem hiding this comment.
ℹ️ Note on the red ampworks build check: it fails at library install with VCSBaseException: VCS: Unknown repository type /Users/amp/Dropbox/Arduino/ArduinoLibs/MPR121 — the ampworks env's lib_deps/lib_extra_dirs are absolute local paths that don't exist on CI runners. This is pre-existing and environmental (it fails the same way on every ampworks PR, before any compilation), not caused by this change: the touch-sync code builds clean locally via pio run -e ampworks and the CI esp32dev env passes. No action taken on it here — making ampworks CI-buildable (vendor libs / relative paths / exclude from the matrix) is a separate call.
aphelps
left a comment
There was a problem hiding this comment.
This needs a better name than "touch_sync" as we'll be syncing all sorts of sensor data.
There was a problem hiding this comment.
Stylistically I prefer to have the .h file only contain structure definitions and function prototypes, please put the actual function definition code in a .cpp file
There was a problem hiding this comment.
Done in a33d7c7 — split into usermod_sensor_sync.h (struct defs + method prototypes only) and usermod_sensor_sync.cpp (all method bodies + the _name/_enabled definitions). usermods_list.cpp includes both, matching the existing ampworks.h/ampworks.cpp pattern.
| * - Consumer: receives remote snapshots, derives per-device rising/falling edges, and enqueues | ||
| * discrete RemoteSensorEvents into an in-RAM ring buffer that effects drain via popRemoteEvent(). | ||
| * Touch Pond (ampworks.cpp) spawns a distinct-colored wave per remote press. |
There was a problem hiding this comment.
It should be the producer that derives rising/falling edges and that is part of the transmission. It is better to do that once at the producer than many times at each consumer.
There was a problem hiding this comment.
Done in a33d7c7 — the producer now derives edges once in broadcastLocalState() (diffing its own previous state) and transmits SensorEdge records; consumers read them directly via popRemoteEvent(). All channels that change in a tick go in a single message. This removed the per-consumer peer-snapshot state entirely (and with it the earlier LRU-eviction / first-message-prev=0 concerns).
Addresses review on PR #3: - Rename usermod touch_sync -> sensor_sync (file, class UsermodSensorSync, USERMOD_ID_SENSOR_SYNC, -D USERMOD_SENSOR_SYNC, structs, magic 'AMPS') since the bus carries all sensor types, not just touch. - Producer derives rising/falling edges once and transmits them (SensorEdge records, all changed channels in one message); consumers read edges directly, removing per-consumer peer-snapshot state and the associated edge re-derivation. - Split into usermod_sensor_sync.h (struct defs + prototypes) and usermod_sensor_sync.cpp (implementations), per the .h-decls-only preference. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
aphelps-claude-bot
left a comment
There was a problem hiding this comment.
Re: "better name than touch_sync" — renamed in a33d7c7 across the board: usermod_sensor_sync.{h,cpp}, class UsermodSensorSync, USERMOD_ID_SENSOR_SYNC, -D USERMOD_SENSOR_SYNC, structs SensorSyncHeader/SensorEdge, magic AMPS, config key SensorSync. (Left the git branch name touch-sync as-is to avoid breaking this PR.)
aphelps-claude-bot
left a comment
There was a problem hiding this comment.
Re-review of a33d7c7 — rename/split/producer-edges all addressed correctly; 4 minor findings (1 dead assert, 1 real regression from the rework, 2 notes).
Verified addressed:
- (1) Rename touch_sync -> sensor_sync is complete and consistent: file
usermod_sensor_sync.{h,cpp}, classUsermodSensorSync,USERMOD_ID_SENSOR_SYNC=56(const.h),-D USERMOD_SENSOR_SYNC(platformio.ini),SensorSyncHeader/SensorEdge, magicAMPS,SS_SENSOR_TOUCH. ampworks.cpp consumer and usermods_list.cpp registration updated. No staletouch_sync/TS_/ATS1references remain. - (2) Header/impl split is clean:
.his declarations only;.cppholds all method bodies + the two PROGMEM statics. usermods_list.cpp#includes BOTH .h and .cpp inside the same#ifdef, so the .cpp becomes part of that single translation unit (not separately linked) — no ODR/duplicate-definition risk, and the PROGMEM statics are defined exactly once. - (3) Edge derivation moved to the producer:
broadcastLocalState()diffscur ^ prevLocalTouched, packs all changed channels into oneSensorEdge[]message;dispatchMessage()just forwards each edge to the queue. Per-peer snapshot state (PeerTouch/peerSlot/MAX_PEERS) is gone.prevLocalTouchedis reset to 0 when the sensor is lost (line 155) so a re-found sensor re-emits its current presses as fresh edges. Receive bounds look correct:avail = dataLen/sizeof(SensorEdge)andn = min(h.count, avail)(the uint8_tcountpromotes to int, so no signedness trap),dataLen = rd - sizeof(h) >= 0is guaranteed by therd >= sizeof(h)check. Magic/version/msgType/own-deviceId checks all present.
Findings:
- (blocking-ish, regression from this rework) Packet loss now drops an edge permanently. With per-peer snapshots removed, the protocol is pure deltas with no resync. A single dropped UDP broadcast (and limited broadcast is unreliable, especially over SoftAP) leaves the consumer's view of that channel stuck inverted until the next change on that channel. The old snapshot design self-healed on the next packet. This is an inherent tradeoff of producer-side edges; at minimum document it, and consider periodic full-state keyframes or carrying the current bitmask in the header for reconciliation. See inline.
- (minor)
prevLocalTouched = curis committed even when the send failed. InsendEdges(), ifudp.beginPacket()returns false the packet is never transmitted, butbroadcastLocalState()still advancesprevLocalTouchedunconditionally — so those edges are lost with no retry. Combined with the no-resync point above, this is a second silent-loss path. Consider havingsendEdges()report success and only advancingprevLocalTouchedon a real send. - (minor) static_assert is a tautology.
sizeof(SensorSyncHeader) + 255*sizeof(SensorEdge) >= sizeof(SensorSyncHeader)is always true (LHS adds a non-negative term), so it never fires. The comment says the largest message must fit the receive buffer, but the assert never referencesRX_BUF_LEN. RX_BUF_LEN=80 holds only 32 edges; TOTAL_SENSORS=13 fits fine, so there's no live bug, but the guard is dead. See inline for the intended check. - (note) Producer emits proximity channel 12, consumer silently drops it.
broadcastLocalState()loopsTOTAL_SENSORS(13, incl. proximity ch 12), but the ampworks consumer filtersev.channel < MPR121::MAX_SENSORS(12), so proximity edges are broadcast, queued, then discarded — wasted bandwidth/queue slots. Pre-existing intent, but the producer/consumer channel ranges should agree (either don't broadcast ch 12, or handle it).
|
"(blocking-ish, regression from this rework) Packet loss now drops an edge permanently. With per-peer snapshots removed, the protocol is pure deltas with no resync. A single dropped UDP broadcast (and limited broadcast is unreliable, especially over SoftAP) leaves the consumer's view of that channel stuck inverted until the next change on that channel. The old snapshot design self-healed on the next packet. This is an inherent tradeoff of producer-side edges; at minimum document it, and consider periodic full-state keyframes or carrying the current bitmask in the header for reconciliation. See inline." Ok, lets discuss this then. |
Per follow-up on PR #3: move edge derivation back to the consumer. The producer broadcasts a full SensorSnapshot (channel bitmask) whenever its state changes; each consumer keeps the last snapshot per origin device and diffs to derive edges. This restores self-healing resync (a dropped datagram is corrected by the next snapshot) that the producer-side-edge approach lost. Keeps the sensor_sync rename and .h/.cpp split. Also: send only advances prevLocalMask on success; meaningful static_assert on the data-struct size. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
aphelps-claude-bot
left a comment
There was a problem hiding this comment.
Per follow-up: reverted the producer-side edge derivation (commit 02a5c5e). The producer now broadcasts a full SensorSnapshot (channel bitmask) on state change, and each consumer diffs against the last snapshot it saw from that device to derive edges — restoring self-healing resync (a dropped datagram is corrected by the next snapshot). The sensor_sync rename and the .h/.cpp split are retained. pio run -e ampworks passes.
Per follow-up on PR #3: the 16-bit low-2-MAC-byte id discarded mac[3] and was birthday-limited (~0.3% collision at 20 devices). deviceId is now a 32-bit FNV-1a hash of the full 6-byte MAC, collision-free in practice at fleet scale; explicit `id` config override retained. Wire-format change: header grows to 20 bytes (added a reserved u16 to keep timestamp 4-byte aligned), version bumped to 5; deviceId fields in the header, RemoteSensorEvent, and per-peer state widened to u32. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
aphelps-claude-bot
left a comment
There was a problem hiding this comment.
Per follow-up: widened deviceId to 32-bit (commit 34d6625). It's now a 32-bit FNV-1a hash of the full 6-byte MAC — folds in mac[3] (which the old low-2-bytes scheme discarded) and is collision-free in practice at fleet scale; the explicit id config override is retained. Wire-format change: header is now 20 bytes (a reserved u16 keeps timestamp 4-byte aligned), protocol version bumped to 5. Also decided: proximity channel stays in (transmitted, Touch Pond ignores it); a configurable-period keyframe re-broadcast is planned for M1. pio run -e ampworks passes.
aphelps
left a comment
There was a problem hiding this comment.
All functions should include docs-style headers on what they do, and in general more inline comments describing what is going on with the code. My general rule is that someone should be able to understand what the code is doing by reading nothing but the comments.
Summary
M0 prototype of the multi-device mesh-sync project. Adds
usermods/ampworks/usermod_touch_sync.h(USERMOD_ID_TOUCH_SYNC=56), a cross-device sensor event bus:popRemoteEvent().sensorType/channel/value) so M1 can add switches/proximity/temperature producers with no wire change.-D USERMOD_TOUCH_SYNCin theampworksenv.Context: this commit was briefly fast-forwarded onto
mainthen backed out; it now goes through review per the todo-handler workflow.Test plan
pio run -e ampworks— SUCCESS (compiles; flash 87.4%)pio run -e esp32dev— SUCCESS (base env unaffected)Manual (hardware, pending — tracked in the plan's Testing Required):
🤖 Generated with Claude Code