66#endif
77
88/*
9- * UsermodTouchSync — broadcasts local sensor events to, and receives remote sensor
10- * events from, other WLED devices on the same local network (no router required).
9+ * UsermodTouchSync — broadcasts local sensor state to, and receives remote sensor state
10+ * from, other WLED devices on the same local network (no router required).
1111 *
1212 * M0 prototype scope (see todo_plans/multi-device-wled-mesh-sync-with-shared-touch-input.md):
1313 * - Transport: UDP limited broadcast (255.255.255.255) on TOUCH_SYNC_PORT. Works over a
1414 * WiFi SoftAP + stations setup with no internet/router. ESP-NOW + multi-hop mesh come later.
15- * - Producer: polls the MPR121 usermod each loop and broadcasts a packet on every
16- * press/release edge.
17- * - Consumer: receives remote packets into an in-RAM ring buffer that effects drain via
18- * popRemoteEvent(). Touch Pond (ampworks.cpp) spawns a distinct-colored wave per remote press.
15+ * - Producer: polls the MPR121 usermod each loop and, whenever the full touch state changes,
16+ * broadcasts ALL sensors of that device in a single message (one snapshot, not per-edge).
17+ * - Consumer: receives remote snapshots, derives per-device rising/falling edges, and enqueues
18+ * discrete RemoteSensorEvents into an in-RAM ring buffer that effects drain via popRemoteEvent().
19+ * Touch Pond (ampworks.cpp) spawns a distinct-colored wave per remote press.
1920 *
20- * The packet layout is deliberately a TYPED SENSOR EVENT (sensorType + channel + value), not
21- * touch-specific, so M1 can add switches/proximity/temperature producers without a wire change.
21+ * Wire format (little-endian; all devices are ESP32, same ABI):
22+ * [ TouchSyncHeader (16 B, 4-byte aligned) ][ sensor-data struct, header.dataLen bytes ]
23+ * The header is GENERIC across sensor types; header.sensorType selects which data struct follows
24+ * and header.dataLen is its byte length. To add a sensor type (switch/proximity/temp), define a
25+ * new TS_SENSOR_* tag + a packed data struct and handle it in dispatchMessage() — no header change.
2226 *
2327 * Device ID is derived from the low 2 bytes of the station MAC (override via config "id", 0=auto).
24- * A device ignores packets bearing its own ID, so broadcast loopback is harmless.
28+ * A device ignores messages bearing its own ID, so broadcast loopback is harmless.
2529 *
26- * Other code accesses received events by looking up this usermod directly:
30+ * Consumers look this usermod up directly:
2731 * #ifdef USERMOD_TOUCH_SYNC
2832 * UsermodTouchSync *ts = (UsermodTouchSync*) UsermodManager::lookup(USERMOD_ID_TOUCH_SYNC);
2933 * RemoteSensorEvent ev;
3034 * while (ts && ts->popRemoteEvent(ev)) { ... }
3135 * #endif
3236 *
33- * NOTE (M0 limitation): popRemoteEvent() drains a single global queue. With one active segment
34- * running Touch Pond this is correct; with multiple consuming segments the first to run would
35- * drain the others. Generalize to per-consumer cursors in M1.
37+ * NOTE (M0 limitation): popRemoteEvent() drains a single global queue — correct for one active
38+ * Touch Pond segment; generalize to per-consumer cursors in M1.
3639 *
3740 * Config (cfg.json):
3841 * enabled — run the sync usermod (default true)
39- * port — UDP port (default 21330; avoids 21324 notifier / 65506 node-list)
42+ * port — UDP port (default 21330; no external/standard meaning, chosen to avoid WLED's
43+ * 21324 notifier and 65506 node-list ports)
4044 * id — device id override; 0 = auto-derive from MAC (default 0)
4145 */
4246
4347#ifndef TOUCH_SYNC_PORT
4448 #define TOUCH_SYNC_PORT 21330
4549#endif
4650
47- // Sensor type tags (extend in M1)
48- #define TS_SENSOR_TOUCH 0 // MPR121 electrode; value = 1 press / 0 release
49-
50- // Wire packet — fixed layout, packed so it is identical across all devices.
51- struct __attribute__ ((packed)) TouchSyncPacket {
52- uint8_t magic[3 ]; // 'A','T','S'
53- uint8_t version; // protocol version (1)
54- uint8_t msgType; // 0 = sensor event
55- uint8_t sensorType; // TS_SENSOR_* (which kind of sensor)
56- uint8_t channel; // electrode / channel index
57- uint8_t value; // event value (e.g. 1=press, 0=release)
51+ #define TOUCH_SYNC_VERSION 2 // wire protocol version (bumped for the generic-header layout)
52+ #define TOUCH_SYNC_MSG_EVENT 0 // msgType: a sensor-state snapshot
53+
54+ // Sensor type tags — one packed data struct per type (extend in M1).
55+ #define TS_SENSOR_TOUCH 0 // MPR121: TsTouchData (bitmask of all electrodes + proximity)
56+
57+ // Generic header, common to every sensor type. 16 bytes, naturally 4-byte aligned
58+ // (4-byte magic first keeps the whole struct and the uint32 timestamp aligned).
59+ struct __attribute__ ((packed)) TouchSyncHeader {
60+ char magic[4 ]; // {'A','T','S','1'} — AMPWorks Touch Sync, v1 wire family
61+ uint8_t version; // TOUCH_SYNC_VERSION
62+ uint8_t msgType; // TOUCH_SYNC_MSG_*
63+ uint8_t sensorType; // TS_SENSOR_* — selects the data struct that follows
64+ uint8_t dataLen; // number of sensor-data bytes following the header
5865 uint16_t deviceId; // origin device id
59- uint16_t seq; // per-sender sequence number (for future dedup/loss tracking)
66+ uint16_t seq; // per-sender sequence number (future dedup/loss tracking)
6067 uint32_t timestamp; // millis() + strip.timebase at origin
6168};
6269
63- #define TOUCH_SYNC_VERSION 1
64- #define TOUCH_SYNC_MSG_EVENT 0
70+ // Sensor-data struct for TS_SENSOR_TOUCH: one snapshot covers all MPR121 channels at once.
71+ struct __attribute__ ((packed)) TsTouchData {
72+ uint16_t touched; // bit e set = channel e currently touched (0..MPR121::TOTAL_SENSORS-1)
73+ };
6574
66- // What effects/consumers see after draining the receive queue .
75+ // What effects/consumers see after the receiver derives an edge from a remote snapshot .
6776struct RemoteSensorEvent {
6877 uint8_t sensorType;
6978 uint8_t channel;
70- uint8_t value;
79+ uint8_t value; // 1 = became active (press), 0 = became inactive (release)
7180 uint16_t deviceId;
7281 uint32_t timestamp;
7382};
@@ -83,26 +92,23 @@ class UsermodTouchSync : public Usermod {
8392 }
8493
8594 void connected () override {
86- // Re-bind on (re)connection; lazy begin in loop() also covers SoftAP-only bring-up.
87- udpStarted = false ;
95+ udpStarted = false ; // re-bind on (re)connection; lazy begin in loop() also covers SoftAP-only
8896 }
8997
9098 void loop () override {
9199 if (!enabled || strip.isUpdating ()) return ;
92100
93- // Need a usable network (station connected OR SoftAP active) before any UDP.
94101 if (!(Network.isConnected () || apActive)) { udpStarted = false ; return ; }
95102 if (!udpStarted) {
96103 if (!udp.begin (port)) return ;
97104 udpStarted = true ;
98105 }
99106
100107 receiveLoop ();
101- broadcastLocalEdges ();
108+ broadcastLocalState ();
102109 }
103110
104111 // ── Consumer API ────────────────────────────────────────────────────────────
105- // Pops the oldest received remote event. Returns false when the queue is empty.
106112 bool popRemoteEvent (RemoteSensorEvent &out) {
107113 if (rxCount == 0 ) return false ;
108114 out = rxQueue[rxTail];
@@ -146,6 +152,8 @@ class UsermodTouchSync : public Usermod {
146152
147153 private:
148154 static const uint8_t RX_QUEUE_LEN = 32 ;
155+ static const uint8_t MAX_PEERS = 8 ; // per-device snapshot state for edge detection
156+ static const uint8_t RX_BUF_LEN = sizeof (TouchSyncHeader) + 64 ; // header + largest data struct
149157
150158 bool initDone = false ;
151159 bool enabled = true ;
@@ -157,13 +165,14 @@ class UsermodTouchSync : public Usermod {
157165 bool udpStarted = false ;
158166 uint16_t txSeq = 0 ;
159167 uint32_t txCount = 0 ;
168+ uint16_t prevLocalTouched = 0 ; // last broadcast local snapshot (change detection)
160169
161170 RemoteSensorEvent rxQueue[RX_QUEUE_LEN ];
162- uint8_t rxHead = 0 ; // next write
163- uint8_t rxTail = 0 ; // next read
164- uint8_t rxCount = 0 ;
171+ uint8_t rxHead = 0 , rxTail = 0 , rxCount = 0 ;
165172
166- uint16_t prevTouched = 0 ; // MPR121 edge-detection state
173+ // Per-peer previous touch snapshot, so we can derive edges from full-state messages.
174+ struct PeerTouch { uint16_t deviceId; uint16_t touched; bool used; };
175+ PeerTouch peers[MAX_PEERS ] = {};
167176
168177 static uint16_t deriveDeviceId () {
169178 uint8_t mac[6 ] = {0 };
@@ -172,28 +181,57 @@ class UsermodTouchSync : public Usermod {
172181 return id ? id : 1 ; // never 0 (0 means "auto")
173182 }
174183
175- void pushRemoteEvent ( const TouchSyncPacket &pkt ) {
184+ void enqueue ( uint8_t sensorType, uint8_t channel, uint8_t value, uint16_t dev, uint32_t ts ) {
176185 RemoteSensorEvent &slot = rxQueue[rxHead];
177- slot.sensorType = pkt. sensorType ;
178- slot.channel = pkt. channel ;
179- slot.value = pkt. value ;
180- slot.deviceId = pkt. deviceId ;
181- slot.timestamp = pkt. timestamp ;
186+ slot.sensorType = sensorType;
187+ slot.channel = channel;
188+ slot.value = value;
189+ slot.deviceId = dev ;
190+ slot.timestamp = ts ;
182191 rxHead = (rxHead + 1 ) % RX_QUEUE_LEN ;
183192 if (rxCount < RX_QUEUE_LEN ) rxCount++;
184193 else rxTail = (rxTail + 1 ) % RX_QUEUE_LEN ; // overwrite oldest
185194 }
186195
196+ // Find (or allocate) the stored snapshot for a peer. Overwrites the first free/LRU slot.
197+ PeerTouch *peerSlot (uint16_t dev) {
198+ for (uint8_t i = 0 ; i < MAX_PEERS ; i++)
199+ if (peers[i].used && peers[i].deviceId == dev) return &peers[i];
200+ for (uint8_t i = 0 ; i < MAX_PEERS ; i++)
201+ if (!peers[i].used ) { peers[i] = {dev, 0 , true }; return &peers[i]; }
202+ peers[0 ] = {dev, 0 , true }; // all full: evict slot 0 (rare at M0 scale; revisit for fleet)
203+ return &peers[0 ];
204+ }
205+
206+ void dispatchMessage (const TouchSyncHeader &h, const uint8_t *data, int dataLen) {
207+ if (h.sensorType == TS_SENSOR_TOUCH && dataLen >= (int )sizeof (TsTouchData)) {
208+ TsTouchData td;
209+ memcpy (&td, data, sizeof (td));
210+ PeerTouch *p = peerSlot (h.deviceId );
211+ uint16_t changed = td.touched ^ p->touched ;
212+ for (uint8_t e = 0 ; e < MPR121 ::TOTAL_SENSORS ; e++) {
213+ if (!(changed & (1u << e))) continue ;
214+ enqueue (TS_SENSOR_TOUCH , e, (td.touched & (1u << e)) ? 1 : 0 , h.deviceId , h.timestamp );
215+ }
216+ p->touched = td.touched ;
217+ }
218+ }
219+
187220 void receiveLoop () {
188221 int sz = udp.parsePacket ();
189222 while (sz > 0 ) {
190- if (sz >= (int )sizeof (TouchSyncPacket)) {
191- TouchSyncPacket pkt;
192- udp.read ((uint8_t *)&pkt, sizeof (pkt));
193- if (pkt.magic [0 ] == ' A' && pkt.magic [1 ] == ' T' && pkt.magic [2 ] == ' S' &&
194- pkt.version == TOUCH_SYNC_VERSION && pkt.msgType == TOUCH_SYNC_MSG_EVENT &&
195- pkt.deviceId != deviceId) {
196- pushRemoteEvent (pkt);
223+ if (sz >= (int )sizeof (TouchSyncHeader) && sz <= (int )RX_BUF_LEN ) {
224+ uint8_t buf[RX_BUF_LEN ];
225+ int n = udp.read (buf, sizeof (buf));
226+ TouchSyncHeader h;
227+ if (n >= (int )sizeof (h)) {
228+ memcpy (&h, buf, sizeof (h));
229+ if (h.magic [0 ] == ' A' && h.magic [1 ] == ' T' && h.magic [2 ] == ' S' && h.magic [3 ] == ' 1' &&
230+ h.version == TOUCH_SYNC_VERSION && h.msgType == TOUCH_SYNC_MSG_EVENT &&
231+ h.deviceId != deviceId &&
232+ (int )sizeof (h) + (int )h.dataLen <= n) {
233+ dispatchMessage (h, buf + sizeof (h), h.dataLen );
234+ }
197235 }
198236 } else {
199237 udp.flush ();
@@ -202,41 +240,40 @@ class UsermodTouchSync : public Usermod {
202240 }
203241 }
204242
205- void sendEvent (uint8_t sensorType, uint8_t channel, uint8_t value) {
206- TouchSyncPacket pkt;
207- pkt.magic [0 ] = ' A' ; pkt.magic [1 ] = ' T' ; pkt.magic [2 ] = ' S' ;
208- pkt.version = TOUCH_SYNC_VERSION ;
209- pkt.msgType = TOUCH_SYNC_MSG_EVENT ;
210- pkt.sensorType = sensorType;
211- pkt.channel = channel;
212- pkt.value = value;
213- pkt.deviceId = deviceId;
214- pkt.seq = txSeq++;
215- pkt.timestamp = millis () + strip.timebase ;
243+ void sendTouchSnapshot (uint16_t touched) {
244+ uint8_t buf[sizeof (TouchSyncHeader) + sizeof (TsTouchData)];
245+ TouchSyncHeader h;
246+ h.magic [0 ] = ' A' ; h.magic [1 ] = ' T' ; h.magic [2 ] = ' S' ; h.magic [3 ] = ' 1' ;
247+ h.version = TOUCH_SYNC_VERSION ;
248+ h.msgType = TOUCH_SYNC_MSG_EVENT ;
249+ h.sensorType = TS_SENSOR_TOUCH ;
250+ h.dataLen = sizeof (TsTouchData);
251+ h.deviceId = deviceId;
252+ h.seq = txSeq++;
253+ h.timestamp = millis () + strip.timebase ;
254+ TsTouchData td; td.touched = touched;
255+ memcpy (buf, &h, sizeof (h));
256+ memcpy (buf + sizeof (h), &td, sizeof (td));
216257
217258 if (udp.beginPacket (IPAddress (255 , 255 , 255 , 255 ), port)) {
218- udp.write (( uint8_t *)&pkt , sizeof (pkt ));
259+ udp.write (buf , sizeof (buf ));
219260 udp.endPacket ();
220261 txCount++;
221262 }
222263 }
223264
224- void broadcastLocalEdges () {
265+ void broadcastLocalState () {
225266#ifdef USERMOD_MPR121
226267 UsermodMPR121 *mpr = (UsermodMPR121*) UsermodManager::lookup (USERMOD_ID_MPR121 );
227268 if (!mpr || !mpr->isSensorFound ()) return ;
228269
229270 uint16_t cur = 0 ;
230- for (uint8_t e = 0 ; e < MPR121 ::MAX_SENSORS ; e++)
271+ for (uint8_t e = 0 ; e < MPR121 ::TOTAL_SENSORS ; e++)
231272 if (mpr->touched (e)) cur |= (1u << e);
232273
233- uint16_t changed = cur ^ prevTouched;
234- if (changed) {
235- for (uint8_t e = 0 ; e < MPR121 ::MAX_SENSORS ; e++) {
236- if (!(changed & (1u << e))) continue ;
237- sendEvent (TS_SENSOR_TOUCH , e, (cur & (1u << e)) ? 1 : 0 );
238- }
239- prevTouched = cur;
274+ if (cur != prevLocalTouched) {
275+ sendTouchSnapshot (cur); // one message carries all sensors of this device
276+ prevLocalTouched = cur;
240277 }
241278#endif
242279 }
0 commit comments