Skip to content

Commit a33d7c7

Browse files
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]>
1 parent 7019b71 commit a33d7c7

7 files changed

Lines changed: 304 additions & 297 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 USERMOD_TOUCH_SYNC -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: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
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"
5+
#ifdef USERMOD_SENSOR_SYNC
6+
#include "../usermods/ampworks/usermod_sensor_sync.h"
77
#endif
88

99
/*
@@ -391,16 +391,16 @@ uint16_t mode_touch_ripple(void) {
391391
spawnTouchWave(data, e, SEGLEN, maxAge, 255, touchWaveColor(e));
392392
}
393393

394-
// Remote touches from other devices (touch-sync usermod): spawn a wave with a
394+
// Remote touches from other devices (sensor-sync usermod): spawn a wave with a
395395
// distinct hue (offset half the palette) so remote interaction is visibly different.
396396
// M0 limitation: drains a single global queue — correct for one active Touch Pond segment.
397-
#ifdef USERMOD_TOUCH_SYNC
397+
#ifdef USERMOD_SENSOR_SYNC
398398
{
399-
UsermodTouchSync *ts = (UsermodTouchSync*) UsermodManager::lookup(USERMOD_ID_TOUCH_SYNC);
400-
if (ts) {
399+
UsermodSensorSync *ss = (UsermodSensorSync*) UsermodManager::lookup(USERMOD_ID_SENSOR_SYNC);
400+
if (ss) {
401401
RemoteSensorEvent ev;
402-
while (ts->popRemoteEvent(ev)) {
403-
if (ev.sensorType == TS_SENSOR_TOUCH && ev.value && ev.channel < MPR121::MAX_SENSORS)
402+
while (ss->popRemoteEvent(ev)) {
403+
if (ev.sensorType == SS_SENSOR_TOUCH && ev.value && ev.channel < MPR121::MAX_SENSORS)
404404
spawnTouchWave(data, ev.channel, SEGLEN, maxAge, 255, (uint8_t)(touchWaveColor(ev.channel) + 128));
405405
}
406406
}
Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
#include "usermod_sensor_sync.h"
2+
#ifdef USERMOD_MPR121
3+
#include "../usermods/mpr121/usermod_mpr121.h"
4+
#endif
5+
6+
// The largest single message must fit the receive buffer (oversized datagrams are flushed).
7+
static_assert(sizeof(SensorSyncHeader) + 255 * sizeof(SensorEdge) >= sizeof(SensorSyncHeader),
8+
"edge batch size sanity");
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+
uint16_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+
uint16_t UsermodSensorSync::deriveDeviceId() {
77+
uint8_t mac[6] = {0};
78+
WiFi.macAddress(mac);
79+
uint16_t id = ((uint16_t)mac[4] << 8) | mac[5];
80+
return id ? id : 1; // never 0 (0 means "auto")
81+
}
82+
83+
void UsermodSensorSync::enqueue(uint8_t sensorType, uint8_t channel, uint8_t value,
84+
uint16_t dev, uint32_t ts) {
85+
RemoteSensorEvent &slot = rxQueue[rxHead];
86+
slot.sensorType = sensorType;
87+
slot.channel = channel;
88+
slot.value = value;
89+
slot.deviceId = dev;
90+
slot.timestamp = ts;
91+
rxHead = (rxHead + 1) % RX_QUEUE_LEN;
92+
if (rxCount < RX_QUEUE_LEN) rxCount++;
93+
else rxTail = (rxTail + 1) % RX_QUEUE_LEN; // overwrite oldest
94+
}
95+
96+
// Edges are derived at the producer, so the consumer just forwards each record to the queue.
97+
void UsermodSensorSync::dispatchMessage(const SensorSyncHeader &h, const uint8_t *data, int dataLen) {
98+
int avail = dataLen / (int)sizeof(SensorEdge);
99+
int n = (h.count < avail) ? h.count : avail;
100+
for (int i = 0; i < n; i++) {
101+
SensorEdge e;
102+
memcpy(&e, data + i * sizeof(SensorEdge), sizeof(e));
103+
enqueue(h.sensorType, e.channel, e.value, h.deviceId, h.timestamp);
104+
}
105+
}
106+
107+
void UsermodSensorSync::receiveLoop() {
108+
int sz = udp.parsePacket();
109+
while (sz > 0) {
110+
if (sz >= (int)sizeof(SensorSyncHeader) && sz <= (int)RX_BUF_LEN) {
111+
uint8_t buf[RX_BUF_LEN];
112+
int rd = udp.read(buf, sizeof(buf));
113+
SensorSyncHeader h;
114+
if (rd >= (int)sizeof(h)) {
115+
memcpy(&h, buf, sizeof(h));
116+
if (h.magic[0] == 'A' && h.magic[1] == 'M' && h.magic[2] == 'P' && h.magic[3] == 'S' &&
117+
h.version == SENSOR_SYNC_VERSION && h.msgType == SENSOR_SYNC_MSG_EDGES &&
118+
h.deviceId != deviceId) {
119+
dispatchMessage(h, buf + sizeof(h), rd - (int)sizeof(h));
120+
}
121+
}
122+
} else {
123+
udp.flush();
124+
}
125+
sz = udp.parsePacket();
126+
}
127+
}
128+
129+
void UsermodSensorSync::sendEdges(uint8_t sensorType, const SensorEdge *edges, uint8_t n) {
130+
if (n == 0) return;
131+
uint8_t buf[RX_BUF_LEN];
132+
if (sizeof(SensorSyncHeader) + (size_t)n * sizeof(SensorEdge) > sizeof(buf)) return;
133+
SensorSyncHeader h;
134+
h.magic[0] = 'A'; h.magic[1] = 'M'; h.magic[2] = 'P'; h.magic[3] = 'S';
135+
h.version = SENSOR_SYNC_VERSION;
136+
h.msgType = SENSOR_SYNC_MSG_EDGES;
137+
h.sensorType = sensorType;
138+
h.count = n;
139+
h.deviceId = deviceId;
140+
h.seq = txSeq++;
141+
h.timestamp = millis() + strip.timebase;
142+
memcpy(buf, &h, sizeof(h));
143+
memcpy(buf + sizeof(h), edges, (size_t)n * sizeof(SensorEdge));
144+
145+
if (udp.beginPacket(IPAddress(255, 255, 255, 255), port)) {
146+
udp.write(buf, sizeof(h) + (size_t)n * sizeof(SensorEdge));
147+
udp.endPacket();
148+
txCount++;
149+
}
150+
}
151+
152+
void UsermodSensorSync::broadcastLocalState() {
153+
#ifdef USERMOD_MPR121
154+
UsermodMPR121 *mpr = (UsermodMPR121*) UsermodManager::lookup(USERMOD_ID_MPR121);
155+
if (!mpr || !mpr->isSensorFound()) { prevLocalTouched = 0; return; }
156+
157+
uint16_t cur = 0;
158+
for (uint8_t e = 0; e < MPR121::TOTAL_SENSORS; e++)
159+
if (mpr->touched(e)) cur |= (1u << e);
160+
161+
uint16_t changed = cur ^ prevLocalTouched;
162+
if (!changed) return;
163+
164+
// Producer derives edges once and sends all changed channels in one message.
165+
SensorEdge edges[MPR121::TOTAL_SENSORS];
166+
uint8_t n = 0;
167+
for (uint8_t e = 0; e < MPR121::TOTAL_SENSORS; e++) {
168+
if (!(changed & (1u << e))) continue;
169+
edges[n].channel = e;
170+
edges[n].value = (cur & (1u << e)) ? 1 : 0;
171+
n++;
172+
}
173+
sendEdges(SS_SENSOR_TOUCH, edges, n);
174+
prevLocalTouched = cur;
175+
#endif
176+
}
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
#pragma once
2+
3+
#include "wled.h"
4+
5+
/*
6+
* UsermodSensorSync — broadcasts local sensor *edge events* to, and receives them from, other
7+
* WLED devices on the same local network (no router required). Renamed from "touch_sync": the
8+
* bus is sensor-agnostic (touch, switches, proximity, temperature, …), so the name reflects that.
9+
*
10+
* Design (per review on WLED#3):
11+
* - The PRODUCER derives rising/falling edges once (diffing its own previous state) and
12+
* transmits the edges. Consumers do NOT re-derive edges — they read them directly. This is
13+
* cheaper (one diff at the source vs. one per consumer) and removes per-peer snapshot state.
14+
* - All sensors that changed in a given tick are sent in ONE message (a list of edge records),
15+
* not one packet per channel.
16+
* - GENERIC header common to all sensor types + a per-type record; header.count = number of
17+
* edge records following. Add a sensor type = new SS_SENSOR_* tag (+ handling) — no header change.
18+
* - Transport: UDP limited broadcast on SENSOR_SYNC_PORT. ESP-NOW / multi-hop come in later milestones.
19+
*
20+
* Implementation lives in usermod_sensor_sync.cpp (this header is declarations only).
21+
*
22+
* Consumers look this usermod up directly:
23+
* #ifdef USERMOD_SENSOR_SYNC
24+
* UsermodSensorSync *ss = (UsermodSensorSync*) UsermodManager::lookup(USERMOD_ID_SENSOR_SYNC);
25+
* RemoteSensorEvent ev;
26+
* while (ss && ss->popRemoteEvent(ev)) { ... }
27+
* #endif
28+
*
29+
* Config (cfg.json): enabled (default true), port (default 21330, no external meaning — chosen
30+
* to avoid WLED's 21324 notifier / 65506 node-list), id (device id override; 0 = auto from MAC).
31+
*/
32+
33+
#ifndef SENSOR_SYNC_PORT
34+
#define SENSOR_SYNC_PORT 21330
35+
#endif
36+
37+
#define SENSOR_SYNC_VERSION 3 // wire protocol version (producer-side edges)
38+
#define SENSOR_SYNC_MSG_EDGES 0 // msgType: a batch of sensor edge records
39+
40+
// Sensor type tags (extend as new producers are added).
41+
#define SS_SENSOR_TOUCH 0 // MPR121 electrode/proximity channel; value = 1 active / 0 inactive
42+
43+
// Generic header, common to every sensor type. 16 bytes, naturally 4-byte aligned.
44+
struct __attribute__((packed)) SensorSyncHeader {
45+
char magic[4]; // {'A','M','P','S'} — AMPWorks sensor sync
46+
uint8_t version; // SENSOR_SYNC_VERSION
47+
uint8_t msgType; // SENSOR_SYNC_MSG_*
48+
uint8_t sensorType; // SS_SENSOR_* — what kind of sensor these edges are from
49+
uint8_t count; // number of SensorEdge records following the header
50+
uint16_t deviceId; // origin device id
51+
uint16_t seq; // per-sender sequence number (future dedup/loss tracking)
52+
uint32_t timestamp; // millis() + strip.timebase at origin
53+
};
54+
55+
// One edge: channel changed to `value`. Producer emits these; consumers read them directly.
56+
struct __attribute__((packed)) SensorEdge {
57+
uint8_t channel; // sensor channel index
58+
uint8_t value; // 1 = became active (press), 0 = became inactive (release)
59+
};
60+
61+
// What effects/consumers see after draining the receive queue.
62+
struct RemoteSensorEvent {
63+
uint8_t sensorType;
64+
uint8_t channel;
65+
uint8_t value;
66+
uint16_t deviceId;
67+
uint32_t timestamp;
68+
};
69+
70+
class UsermodSensorSync : public Usermod {
71+
public:
72+
static const char _name[];
73+
static const char _enabled[];
74+
75+
void setup() override;
76+
void connected() override;
77+
void loop() override;
78+
79+
// Consumer API: pop the oldest received remote event; false when the queue is empty.
80+
bool popRemoteEvent(RemoteSensorEvent &out);
81+
uint16_t getDeviceId() const;
82+
83+
uint16_t getId() override;
84+
void addToJsonInfo(JsonObject &root) override;
85+
void addToConfig(JsonObject &root) override;
86+
bool readFromConfig(JsonObject &root) override;
87+
88+
private:
89+
static const uint8_t RX_QUEUE_LEN = 32;
90+
static const uint8_t RX_BUF_LEN = sizeof(SensorSyncHeader) + 64; // header + max edge batch
91+
92+
bool initDone = false;
93+
bool enabled = true;
94+
uint16_t port = SENSOR_SYNC_PORT;
95+
uint16_t configId = 0; // 0 = auto-derive
96+
uint16_t deviceId = 0;
97+
98+
WiFiUDP udp;
99+
bool udpStarted = false;
100+
uint16_t txSeq = 0;
101+
uint32_t txCount = 0;
102+
uint16_t prevLocalTouched = 0; // producer-side previous state for edge derivation
103+
104+
RemoteSensorEvent rxQueue[RX_QUEUE_LEN];
105+
uint8_t rxHead = 0, rxTail = 0, rxCount = 0;
106+
107+
static uint16_t deriveDeviceId();
108+
void enqueue(uint8_t sensorType, uint8_t channel, uint8_t value, uint16_t dev, uint32_t ts);
109+
void dispatchMessage(const SensorSyncHeader &h, const uint8_t *data, int dataLen);
110+
void receiveLoop();
111+
void sendEdges(uint8_t sensorType, const SensorEdge *edges, uint8_t n);
112+
void broadcastLocalState();
113+
};

0 commit comments

Comments
 (0)