Skip to content

Commit b801a74

Browse files
add touch-sync usermod: UDP sensor-event bus for cross-device effects
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]>
1 parent c6941cf commit b801a74

5 files changed

Lines changed: 290 additions & 8 deletions

File tree

‎platformio.ini‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -448,7 +448,7 @@ upload_protocol = custom
448448
upload_port = 192.168.1.55
449449
extra_scripts = pre:tools/set_build_info.py
450450
post:tools/upload_wled.py
451-
build_flags = ${env:esp32dev.build_flags} -D USERMOD_AMPWORKS -D USERMOD_MPR121 -D DEBUG_LEVEL_MPR121=0
451+
build_flags = ${env:esp32dev.build_flags} -D USERMOD_AMPWORKS -D USERMOD_MPR121 -D USERMOD_TOUCH_SYNC -D DEBUG_LEVEL_MPR121=0
452452
lib_extra_dirs = /Users/amp/Dropbox/Arduino/ArduinoLibs
453453
lib_deps = ${env:esp32dev.lib_deps}
454454
/Users/amp/Dropbox/Arduino/ArduinoLibs/MPR121

‎usermods/ampworks/ampworks.cpp‎

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22
#ifdef USERMOD_MPR121
33
#include "../usermods/mpr121/usermod_mpr121.h"
44
#endif
5+
#ifdef USERMOD_TOUCH_SYNC
6+
#include "../usermods/ampworks/usermod_touch_sync.h"
7+
#endif
58

69
/*
710
* AMP's initial test mode
@@ -323,7 +326,12 @@ struct TouchRippleData {
323326
* c2 → background fade rate (low=short trail, high=long trail)
324327
*/
325328
#ifdef USERMOD_MPR121
326-
static void spawnTouchWave(TouchRippleData *data, uint8_t e, uint16_t segLen, uint8_t maxAge, uint8_t ghostBri) {
329+
// Default palette hue for an electrode's wave (local/ghost/audio waves).
330+
static inline uint8_t touchWaveColor(uint8_t e) {
331+
return (uint8_t)(e * (256 / MPR121::MAX_SENSORS));
332+
}
333+
334+
static void spawnTouchWave(TouchRippleData *data, uint8_t e, uint16_t segLen, uint8_t maxAge, uint8_t ghostBri, uint8_t color) {
327335
int slot = -1;
328336
uint8_t oldestAge = 0; int oldestSlot = 0;
329337
for (int w = 0; w < MAX_TOUCH_WAVES; w++) {
@@ -334,7 +342,7 @@ static void spawnTouchWave(TouchRippleData *data, uint8_t e, uint16_t segLen, ui
334342
data->waves[slot] = {
335343
(uint16_t)((uint32_t)e * segLen / MPR121::MAX_SENSORS),
336344
0, maxAge,
337-
(uint8_t)(e * (256 / MPR121::MAX_SENSORS)),
345+
color,
338346
ghostBri
339347
};
340348
}
@@ -346,10 +354,12 @@ uint16_t mode_touch_ripple(void) {
346354
#else
347355
if (SEGLEN == 0) return FRAMETIME;
348356

357+
// mpr may report no physical sensor (display-only node): the touched() wrappers then
358+
// return false, so local-touch logic is inert but remote/audio waves still render.
349359
UsermodMPR121 *mpr = (UsermodMPR121*) UsermodManager::lookup(USERMOD_ID_MPR121);
350-
if (!mpr || !mpr->isSensorFound()) return FRAMETIME;
360+
if (!mpr) return FRAMETIME;
351361

352-
mpr->setUpdateHz(map8(SEGMENT.custom1, 1, 100));
362+
if (mpr->isSensorFound()) mpr->setUpdateHz(map8(SEGMENT.custom1, 1, 100));
353363

354364
if (!SEGENV.allocateData(sizeof(TouchRippleData))) return FRAMETIME;
355365
TouchRippleData *data = reinterpret_cast<TouchRippleData*>(SEGENV.data);
@@ -378,8 +388,24 @@ uint16_t mode_touch_ripple(void) {
378388
data->history[data->histHead] = {e, delta};
379389
data->histHead = (data->histHead + 1) % MAX_HISTORY;
380390
if (data->histCount < MAX_HISTORY) data->histCount++;
381-
spawnTouchWave(data, e, SEGLEN, maxAge, 255);
391+
spawnTouchWave(data, e, SEGLEN, maxAge, 255, touchWaveColor(e));
392+
}
393+
394+
// Remote touches from other devices (touch-sync usermod): spawn a wave with a
395+
// distinct hue (offset half the palette) so remote interaction is visibly different.
396+
// M0 limitation: drains a single global queue — correct for one active Touch Pond segment.
397+
#ifdef USERMOD_TOUCH_SYNC
398+
{
399+
UsermodTouchSync *ts = (UsermodTouchSync*) UsermodManager::lookup(USERMOD_ID_TOUCH_SYNC);
400+
if (ts) {
401+
RemoteSensorEvent ev;
402+
while (ts->popRemoteEvent(ev)) {
403+
if (ev.sensorType == TS_SENSOR_TOUCH && ev.value && ev.channel < MPR121::MAX_SENSORS)
404+
spawnTouchWave(data, ev.channel, SEGLEN, maxAge, 255, (uint8_t)(touchWaveColor(ev.channel) + 128));
405+
}
406+
}
382407
}
408+
#endif
383409

384410
// Update idle counter; reset and cancel replay on any new real touch
385411
if (newTouches) {
@@ -397,7 +423,7 @@ uint16_t mode_touch_ripple(void) {
397423
} else {
398424
uint8_t oldest = (data->histHead + MAX_HISTORY - data->histCount) % MAX_HISTORY;
399425
uint8_t idx = (oldest + data->replayIdx) % MAX_HISTORY;
400-
spawnTouchWave(data, data->history[idx].electrode, SEGLEN, maxAge, 80);
426+
spawnTouchWave(data, data->history[idx].electrode, SEGLEN, maxAge, 80, touchWaveColor(data->history[idx].electrode));
401427

402428
uint8_t nextIdx = (data->replayIdx + 1) % data->histCount;
403429
if (nextIdx == 0) {
@@ -447,7 +473,8 @@ uint16_t mode_touch_ripple(void) {
447473
} else if (normVol > threshold) {
448474
// Brightness scales with amplitude: louder = brighter (80-220 range)
449475
uint8_t audioBri = 80 + scale8(normVol, scale8(curvedMix, 140));
450-
spawnTouchWave(data, random8(MPR121::MAX_SENSORS), SEGLEN, maxAge, audioBri);
476+
uint8_t audioE = random8(MPR121::MAX_SENSORS);
477+
spawnTouchWave(data, audioE, SEGLEN, maxAge, audioBri, touchWaveColor(audioE));
451478
SEGENV.aux0 = map8(255 - curvedMix, 8, 40);
452479
}
453480
}
Lines changed: 246 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,246 @@
1+
#pragma once
2+
3+
#include "wled.h"
4+
#ifdef USERMOD_MPR121
5+
#include "../usermods/mpr121/usermod_mpr121.h"
6+
#endif
7+
8+
/*
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).
11+
*
12+
* M0 prototype scope (see todo_plans/multi-device-wled-mesh-sync-with-shared-touch-input.md):
13+
* - Transport: UDP limited broadcast (255.255.255.255) on TOUCH_SYNC_PORT. Works over a
14+
* 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.
19+
*
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.
22+
*
23+
* 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.
25+
*
26+
* Other code accesses received events by looking up this usermod directly:
27+
* #ifdef USERMOD_TOUCH_SYNC
28+
* UsermodTouchSync *ts = (UsermodTouchSync*) UsermodManager::lookup(USERMOD_ID_TOUCH_SYNC);
29+
* RemoteSensorEvent ev;
30+
* while (ts && ts->popRemoteEvent(ev)) { ... }
31+
* #endif
32+
*
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.
36+
*
37+
* Config (cfg.json):
38+
* enabled — run the sync usermod (default true)
39+
* port — UDP port (default 21330; avoids 21324 notifier / 65506 node-list)
40+
* id — device id override; 0 = auto-derive from MAC (default 0)
41+
*/
42+
43+
#ifndef TOUCH_SYNC_PORT
44+
#define TOUCH_SYNC_PORT 21330
45+
#endif
46+
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)
58+
uint16_t deviceId; // origin device id
59+
uint16_t seq; // per-sender sequence number (for future dedup/loss tracking)
60+
uint32_t timestamp; // millis() + strip.timebase at origin
61+
};
62+
63+
#define TOUCH_SYNC_VERSION 1
64+
#define TOUCH_SYNC_MSG_EVENT 0
65+
66+
// What effects/consumers see after draining the receive queue.
67+
struct RemoteSensorEvent {
68+
uint8_t sensorType;
69+
uint8_t channel;
70+
uint8_t value;
71+
uint16_t deviceId;
72+
uint32_t timestamp;
73+
};
74+
75+
class UsermodTouchSync : public Usermod {
76+
public:
77+
static const char _name[];
78+
static const char _enabled[];
79+
80+
void setup() override {
81+
deviceId = configId ? configId : deriveDeviceId();
82+
initDone = true;
83+
}
84+
85+
void connected() override {
86+
// Re-bind on (re)connection; lazy begin in loop() also covers SoftAP-only bring-up.
87+
udpStarted = false;
88+
}
89+
90+
void loop() override {
91+
if (!enabled || strip.isUpdating()) return;
92+
93+
// Need a usable network (station connected OR SoftAP active) before any UDP.
94+
if (!(Network.isConnected() || apActive)) { udpStarted = false; return; }
95+
if (!udpStarted) {
96+
if (!udp.begin(port)) return;
97+
udpStarted = true;
98+
}
99+
100+
receiveLoop();
101+
broadcastLocalEdges();
102+
}
103+
104+
// ── Consumer API ────────────────────────────────────────────────────────────
105+
// Pops the oldest received remote event. Returns false when the queue is empty.
106+
bool popRemoteEvent(RemoteSensorEvent &out) {
107+
if (rxCount == 0) return false;
108+
out = rxQueue[rxTail];
109+
rxTail = (rxTail + 1) % RX_QUEUE_LEN;
110+
rxCount--;
111+
return true;
112+
}
113+
114+
uint16_t getDeviceId() const { return deviceId; }
115+
116+
uint16_t getId() override { return USERMOD_ID_TOUCH_SYNC; }
117+
118+
void addToJsonInfo(JsonObject &root) override {
119+
JsonObject user = root["u"];
120+
if (user.isNull()) user = root.createNestedObject("u");
121+
JsonArray arr = user.createNestedArray("Touch Sync");
122+
arr.add(udpStarted ? txCount : 0);
123+
arr.add(udpStarted ? " sent" : " (offline)");
124+
}
125+
126+
void addToConfig(JsonObject &root) override {
127+
JsonObject top = root.createNestedObject(FPSTR(_name));
128+
top[FPSTR(_enabled)] = enabled;
129+
top["port"] = port;
130+
top["id"] = configId;
131+
}
132+
133+
bool readFromConfig(JsonObject &root) override {
134+
JsonObject top = root[FPSTR(_name)];
135+
if (top.isNull()) return false;
136+
uint16_t portPrev = port;
137+
getJsonValue(top[FPSTR(_enabled)], enabled);
138+
getJsonValue(top["port"], port);
139+
getJsonValue(top["id"], configId);
140+
if (initDone) {
141+
deviceId = configId ? configId : deriveDeviceId();
142+
if (port != portPrev) udpStarted = false; // rebind on next loop
143+
}
144+
return true;
145+
}
146+
147+
private:
148+
static const uint8_t RX_QUEUE_LEN = 32;
149+
150+
bool initDone = false;
151+
bool enabled = true;
152+
uint16_t port = TOUCH_SYNC_PORT;
153+
uint16_t configId = 0; // 0 = auto-derive
154+
uint16_t deviceId = 0;
155+
156+
WiFiUDP udp;
157+
bool udpStarted = false;
158+
uint16_t txSeq = 0;
159+
uint32_t txCount = 0;
160+
161+
RemoteSensorEvent rxQueue[RX_QUEUE_LEN];
162+
uint8_t rxHead = 0; // next write
163+
uint8_t rxTail = 0; // next read
164+
uint8_t rxCount = 0;
165+
166+
uint16_t prevTouched = 0; // MPR121 edge-detection state
167+
168+
static uint16_t deriveDeviceId() {
169+
uint8_t mac[6] = {0};
170+
WiFi.macAddress(mac);
171+
uint16_t id = ((uint16_t)mac[4] << 8) | mac[5];
172+
return id ? id : 1; // never 0 (0 means "auto")
173+
}
174+
175+
void pushRemoteEvent(const TouchSyncPacket &pkt) {
176+
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;
182+
rxHead = (rxHead + 1) % RX_QUEUE_LEN;
183+
if (rxCount < RX_QUEUE_LEN) rxCount++;
184+
else rxTail = (rxTail + 1) % RX_QUEUE_LEN; // overwrite oldest
185+
}
186+
187+
void receiveLoop() {
188+
int sz = udp.parsePacket();
189+
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);
197+
}
198+
} else {
199+
udp.flush();
200+
}
201+
sz = udp.parsePacket();
202+
}
203+
}
204+
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;
216+
217+
if (udp.beginPacket(IPAddress(255, 255, 255, 255), port)) {
218+
udp.write((uint8_t*)&pkt, sizeof(pkt));
219+
udp.endPacket();
220+
txCount++;
221+
}
222+
}
223+
224+
void broadcastLocalEdges() {
225+
#ifdef USERMOD_MPR121
226+
UsermodMPR121 *mpr = (UsermodMPR121*) UsermodManager::lookup(USERMOD_ID_MPR121);
227+
if (!mpr || !mpr->isSensorFound()) return;
228+
229+
uint16_t cur = 0;
230+
for (uint8_t e = 0; e < MPR121::MAX_SENSORS; e++)
231+
if (mpr->touched(e)) cur |= (1u << e);
232+
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;
240+
}
241+
#endif
242+
}
243+
};
244+
245+
const char UsermodTouchSync::_name[] PROGMEM = "TouchSync";
246+
const char UsermodTouchSync::_enabled[] PROGMEM = "enabled";

‎wled00/const.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,7 @@
204204
#define USERMOD_ID_POV_DISPLAY 53 //Usermod "usermod_pov_display.h"
205205
#define USERMOD_ID_PIXELS_DICE_TRAY 54 //Usermod "pixels_dice_tray.h"
206206
#define USERMOD_ID_MPR121 55 //Usermod "usermods/mpr121/usermod_mpr121.h"
207+
#define USERMOD_ID_TOUCH_SYNC 56 //Usermod "usermods/ampworks/usermod_touch_sync.h"
207208

208209
//Access point behavior
209210
#define AP_BEHAVIOR_BOOT_NO_CONN 0 //Open AP when no connection after boot

‎wled00/usermods_list.cpp‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,10 @@
163163
#include "../usermods/mpr121/usermod_mpr121.h"
164164
#endif
165165

166+
#ifdef USERMOD_TOUCH_SYNC
167+
#include "../usermods/ampworks/usermod_touch_sync.h"
168+
#endif
169+
166170
#ifdef USERMOD_ANALOG_CLOCK
167171
#include "../usermods/Analog_Clock/Analog_Clock.h"
168172
#endif
@@ -404,6 +408,10 @@ void registerUsermods()
404408
UsermodManager::add(new UsermodMPR121());
405409
#endif
406410

411+
#ifdef USERMOD_TOUCH_SYNC
412+
UsermodManager::add(new UsermodTouchSync());
413+
#endif
414+
407415
#ifdef USERMOD_ANALOG_CLOCK
408416
UsermodManager::add(new AnalogClockUsermod());
409417
#endif

0 commit comments

Comments
 (0)