|
| 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"; |
0 commit comments