Skip to content

Commit 67f21fe

Browse files
add touch-sync usermod: UDP sensor-event bus for cross-device effects (#3)
* 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]> * redesign touch-sync wire format: generic header + per-sensor data 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]> * rename touch-sync -> sensor-sync; producer-side edges; split .h/.cpp 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]> * revert to producer-snapshot + consumer-side edge derivation 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]> * widen deviceId to 32-bit FNV-1a hash of full MAC 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]> --------- Co-authored-by: aphelps-claude-bot <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
1 parent c6941cf commit 67f21fe

6 files changed

Lines changed: 358 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_SENSOR_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_SENSOR_SYNC
6+
#include "../usermods/ampworks/usermod_sensor_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 (sensor-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_SENSOR_SYNC
398+
{
399+
UsermodSensorSync *ss = (UsermodSensorSync*) UsermodManager::lookup(USERMOD_ID_SENSOR_SYNC);
400+
if (ss) {
401+
RemoteSensorEvent ev;
402+
while (ss->popRemoteEvent(ev)) {
403+
if (ev.sensorType == SS_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: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,191 @@
1+
#include "usermod_sensor_sync.h"
2+
#ifdef USERMOD_MPR121
3+
#include "../usermods/mpr121/usermod_mpr121.h"
4+
#endif
5+
6+
// RX_BUF_LEN reserves 64 bytes for sensor data after the header; the largest per-type data
7+
// struct must fit that allowance (oversized datagrams are flushed in receiveLoop()).
8+
static_assert(sizeof(SensorSnapshot) <= 64, "sensor data struct exceeds RX_BUF_LEN data allowance");
9+
10+
const char UsermodSensorSync::_name[] PROGMEM = "SensorSync";
11+
const char UsermodSensorSync::_enabled[] PROGMEM = "enabled";
12+
13+
void UsermodSensorSync::setup() {
14+
deviceId = configId ? configId : deriveDeviceId();
15+
initDone = true;
16+
}
17+
18+
void UsermodSensorSync::connected() {
19+
udpStarted = false; // re-bind on (re)connection; lazy begin in loop() also covers SoftAP-only
20+
}
21+
22+
void UsermodSensorSync::loop() {
23+
if (!enabled || strip.isUpdating()) return;
24+
25+
if (!(Network.isConnected() || apActive)) { udpStarted = false; return; }
26+
if (!udpStarted) {
27+
if (!udp.begin(port)) return;
28+
udpStarted = true;
29+
}
30+
31+
receiveLoop();
32+
broadcastLocalState();
33+
}
34+
35+
bool UsermodSensorSync::popRemoteEvent(RemoteSensorEvent &out) {
36+
if (rxCount == 0) return false;
37+
out = rxQueue[rxTail];
38+
rxTail = (rxTail + 1) % RX_QUEUE_LEN;
39+
rxCount--;
40+
return true;
41+
}
42+
43+
uint32_t UsermodSensorSync::getDeviceId() const { return deviceId; }
44+
45+
uint16_t UsermodSensorSync::getId() { return USERMOD_ID_SENSOR_SYNC; }
46+
47+
void UsermodSensorSync::addToJsonInfo(JsonObject &root) {
48+
JsonObject user = root["u"];
49+
if (user.isNull()) user = root.createNestedObject("u");
50+
JsonArray arr = user.createNestedArray("Sensor Sync");
51+
arr.add(udpStarted ? txCount : 0);
52+
arr.add(udpStarted ? " sent" : " (offline)");
53+
}
54+
55+
void UsermodSensorSync::addToConfig(JsonObject &root) {
56+
JsonObject top = root.createNestedObject(FPSTR(_name));
57+
top[FPSTR(_enabled)] = enabled;
58+
top["port"] = port;
59+
top["id"] = configId;
60+
}
61+
62+
bool UsermodSensorSync::readFromConfig(JsonObject &root) {
63+
JsonObject top = root[FPSTR(_name)];
64+
if (top.isNull()) return false;
65+
uint16_t portPrev = port;
66+
getJsonValue(top[FPSTR(_enabled)], enabled);
67+
getJsonValue(top["port"], port);
68+
getJsonValue(top["id"], configId);
69+
if (initDone) {
70+
deviceId = configId ? configId : deriveDeviceId();
71+
if (port != portPrev) udpStarted = false; // rebind on next loop
72+
}
73+
return true;
74+
}
75+
76+
uint32_t UsermodSensorSync::deriveDeviceId() {
77+
// 32-bit FNV-1a hash of the full 6-byte MAC: folds in all device-unique entropy (incl.
78+
// mac[3], which a low-bytes scheme discards) so auto-IDs are effectively collision-free
79+
// at fleet scale. Override deterministically via the `id` config field if desired.
80+
uint8_t mac[6] = {0};
81+
WiFi.macAddress(mac);
82+
uint32_t h = 2166136261u; // FNV offset basis
83+
for (uint8_t i = 0; i < 6; i++) {
84+
h ^= mac[i];
85+
h *= 16777619u; // FNV prime
86+
}
87+
return h ? h : 1; // never 0 (0 means "auto")
88+
}
89+
90+
void UsermodSensorSync::enqueue(uint8_t sensorType, uint8_t channel, uint8_t value,
91+
uint32_t dev, uint32_t ts) {
92+
RemoteSensorEvent &slot = rxQueue[rxHead];
93+
slot.sensorType = sensorType;
94+
slot.channel = channel;
95+
slot.value = value;
96+
slot.deviceId = dev;
97+
slot.timestamp = ts;
98+
rxHead = (rxHead + 1) % RX_QUEUE_LEN;
99+
if (rxCount < RX_QUEUE_LEN) rxCount++;
100+
else rxTail = (rxTail + 1) % RX_QUEUE_LEN; // overwrite oldest
101+
}
102+
103+
// Find (or allocate) the stored snapshot for a peer. Reuses a free slot; if all are in use
104+
// it evicts slot 0 (a re-added peer then resyncs from mask=0 — see dispatchMessage). Fine at
105+
// M0's handful of devices; revisit with a real last-seen LRU for the fleet milestone.
106+
UsermodSensorSync::PeerSnapshot *UsermodSensorSync::peerSlot(uint32_t dev) {
107+
for (uint8_t i = 0; i < MAX_PEERS; i++)
108+
if (peers[i].used && peers[i].deviceId == dev) return &peers[i];
109+
for (uint8_t i = 0; i < MAX_PEERS; i++)
110+
if (!peers[i].used) { peers[i] = {dev, 0, true}; return &peers[i]; }
111+
peers[0] = {dev, 0, true};
112+
return &peers[0];
113+
}
114+
115+
// Consumer-side edge derivation: diff the incoming snapshot against the peer's last snapshot
116+
// and enqueue one event per changed channel. First message from a peer (mask 0) resyncs by
117+
// emitting a press for every already-active channel.
118+
void UsermodSensorSync::dispatchMessage(const SensorSyncHeader &h, const uint8_t *data, int dataLen) {
119+
if (h.sensorType == SS_SENSOR_TOUCH && dataLen >= (int)sizeof(SensorSnapshot)) {
120+
SensorSnapshot snap;
121+
memcpy(&snap, data, sizeof(snap));
122+
PeerSnapshot *p = peerSlot(h.deviceId);
123+
uint16_t changed = snap.mask ^ p->mask;
124+
for (uint8_t e = 0; e < 16; e++) {
125+
if (!(changed & (1u << e))) continue;
126+
enqueue(SS_SENSOR_TOUCH, e, (snap.mask & (1u << e)) ? 1 : 0, h.deviceId, h.timestamp);
127+
}
128+
p->mask = snap.mask;
129+
}
130+
}
131+
132+
void UsermodSensorSync::receiveLoop() {
133+
int sz = udp.parsePacket();
134+
while (sz > 0) {
135+
if (sz >= (int)sizeof(SensorSyncHeader) && sz <= (int)RX_BUF_LEN) {
136+
uint8_t buf[RX_BUF_LEN];
137+
int rd = udp.read(buf, sizeof(buf));
138+
SensorSyncHeader h;
139+
if (rd >= (int)sizeof(h)) {
140+
memcpy(&h, buf, sizeof(h));
141+
if (h.magic[0] == 'A' && h.magic[1] == 'M' && h.magic[2] == 'P' && h.magic[3] == 'S' &&
142+
h.version == SENSOR_SYNC_VERSION && h.msgType == SENSOR_SYNC_MSG_SNAPSHOT &&
143+
h.deviceId != deviceId &&
144+
(int)sizeof(h) + (int)h.dataLen <= rd) {
145+
dispatchMessage(h, buf + sizeof(h), h.dataLen);
146+
}
147+
}
148+
} else {
149+
udp.flush();
150+
}
151+
sz = udp.parsePacket();
152+
}
153+
}
154+
155+
bool UsermodSensorSync::sendSnapshot(uint8_t sensorType, uint16_t mask) {
156+
uint8_t buf[sizeof(SensorSyncHeader) + sizeof(SensorSnapshot)];
157+
SensorSyncHeader h;
158+
h.magic[0] = 'A'; h.magic[1] = 'M'; h.magic[2] = 'P'; h.magic[3] = 'S';
159+
h.version = SENSOR_SYNC_VERSION;
160+
h.msgType = SENSOR_SYNC_MSG_SNAPSHOT;
161+
h.sensorType = sensorType;
162+
h.dataLen = sizeof(SensorSnapshot);
163+
h.deviceId = deviceId;
164+
h.seq = txSeq++;
165+
h.reserved = 0;
166+
h.timestamp = millis() + strip.timebase;
167+
SensorSnapshot snap; snap.mask = mask;
168+
memcpy(buf, &h, sizeof(h));
169+
memcpy(buf + sizeof(h), &snap, sizeof(snap));
170+
171+
if (!udp.beginPacket(IPAddress(255, 255, 255, 255), port)) return false;
172+
udp.write(buf, sizeof(buf));
173+
if (!udp.endPacket()) return false;
174+
txCount++;
175+
return true;
176+
}
177+
178+
void UsermodSensorSync::broadcastLocalState() {
179+
#ifdef USERMOD_MPR121
180+
UsermodMPR121 *mpr = (UsermodMPR121*) UsermodManager::lookup(USERMOD_ID_MPR121);
181+
if (!mpr || !mpr->isSensorFound()) { prevLocalMask = 0; return; }
182+
183+
uint16_t cur = 0;
184+
for (uint8_t e = 0; e < MPR121::TOTAL_SENSORS; e++)
185+
if (mpr->touched(e)) cur |= (1u << e);
186+
187+
if (cur == prevLocalMask) return;
188+
// Only advance prevLocalMask on a successful send, so a failed send retries next loop.
189+
if (sendSnapshot(SS_SENSOR_TOUCH, cur)) prevLocalMask = cur;
190+
#endif
191+
}

0 commit comments

Comments
 (0)