diff --git a/wled00/bus_manager.h b/wled00/bus_manager.h index 0bec1e3f7..71cd3a6fe 100644 --- a/wled00/bus_manager.h +++ b/wled00/bus_manager.h @@ -386,7 +386,7 @@ class BusVirtual : public Bus { void show() { if (!_valid || _broadcastLock) return; _broadcastLock = true; - realtimeBoroadcast(_client, _len, _data, _rgbw); + realtimeBroadcast(_client, _len, _data, _rgbw); _broadcastLock = false; } diff --git a/wled00/fcn_declare.h b/wled00/fcn_declare.h index 3556bbd24..ea1f4897f 100644 --- a/wled00/fcn_declare.h +++ b/wled00/fcn_declare.h @@ -197,7 +197,7 @@ bool updateVal(const String* req, const char* key, byte* val, byte minv=0, byte //udp.cpp void notify(byte callMode, bool followUp=false); -void realtimeBoroadcast(IPAddress client, uint16_t length, byte *buffer, bool isRGBW); +uint8_t realtimeBroadcast(IPAddress client, uint16_t length, byte *buffer, bool isRGBW); void realtimeLock(uint32_t timeoutMs, byte md = REALTIME_MODE_GENERIC); void handleNotifications(); void setRealtimePixel(uint16_t i, byte r, byte g, byte b, byte w); diff --git a/wled00/udp.cpp b/wled00/udp.cpp index 1cb3b0845..392b2d1ff 100644 --- a/wled00/udp.cpp +++ b/wled00/udp.cpp @@ -1,523 +1,622 @@ -#include "wled.h" - -/* - * UDP sync notifier / Realtime / Hyperion / TPM2.NET - */ - -#define WLEDPACKETSIZE 37 -#define UDP_IN_MAXSIZE 1472 -#define PRESUMED_NETWORK_DELAY 3 //how many ms could it take on avg to reach the receiver? This will be added to transmitted times - -void notify(byte callMode, bool followUp) -{ - if (!udpConnected) return; - if (!syncGroups) return; - switch (callMode) - { - case CALL_MODE_INIT: return; - case CALL_MODE_DIRECT_CHANGE: if (!notifyDirect) return; break; - case CALL_MODE_BUTTON: if (!notifyButton) return; break; - case CALL_MODE_NIGHTLIGHT: if (!notifyDirect) return; break; - case CALL_MODE_HUE: if (!notifyHue) return; break; - case CALL_MODE_PRESET_CYCLE: if (!notifyDirect) return; break; - case CALL_MODE_BLYNK: if (!notifyDirect) return; break; - case CALL_MODE_ALEXA: if (!notifyAlexa) return; break; - default: return; - } - byte udpOut[WLEDPACKETSIZE]; - udpOut[0] = 0; //0: wled notifier protocol 1: WARLS protocol - udpOut[1] = callMode; - udpOut[2] = bri; - udpOut[3] = col[0]; - udpOut[4] = col[1]; - udpOut[5] = col[2]; - udpOut[6] = nightlightActive; - udpOut[7] = nightlightDelayMins; - udpOut[8] = effectCurrent; - udpOut[9] = effectSpeed; - udpOut[10] = col[3]; - //compatibilityVersionByte: - //0: old 1: supports white 2: supports secondary color - //3: supports FX intensity, 24 byte packet 4: supports transitionDelay 5: sup palette - //6: supports timebase syncing, 29 byte packet 7: supports tertiary color 8: supports sys time sync, 36 byte packet - //9: supports sync groups, 37 byte packet - udpOut[11] = 9; - udpOut[12] = colSec[0]; - udpOut[13] = colSec[1]; - udpOut[14] = colSec[2]; - udpOut[15] = colSec[3]; - udpOut[16] = effectIntensity; - udpOut[17] = (transitionDelay >> 0) & 0xFF; - udpOut[18] = (transitionDelay >> 8) & 0xFF; - udpOut[19] = effectPalette; - uint32_t colTer = strip.getSegment(strip.getMainSegmentId()).colors[2]; - udpOut[20] = (colTer >> 16) & 0xFF; - udpOut[21] = (colTer >> 8) & 0xFF; - udpOut[22] = (colTer >> 0) & 0xFF; - udpOut[23] = (colTer >> 24) & 0xFF; - - udpOut[24] = followUp; - uint32_t t = millis() + strip.timebase; - udpOut[25] = (t >> 24) & 0xFF; - udpOut[26] = (t >> 16) & 0xFF; - udpOut[27] = (t >> 8) & 0xFF; - udpOut[28] = (t >> 0) & 0xFF; - - //sync system time - udpOut[29] = toki.getTimeSource(); - Toki::Time tm = toki.getTime(); - uint32_t unix = tm.sec; - udpOut[30] = (unix >> 24) & 0xFF; - udpOut[31] = (unix >> 16) & 0xFF; - udpOut[32] = (unix >> 8) & 0xFF; - udpOut[33] = (unix >> 0) & 0xFF; - uint16_t ms = tm.ms; - udpOut[34] = (ms >> 8) & 0xFF; - udpOut[35] = (ms >> 0) & 0xFF; - - //sync groups - udpOut[36] = syncGroups; - - IPAddress broadcastIp; - broadcastIp = ~uint32_t(Network.subnetMask()) | uint32_t(Network.gatewayIP()); - - notifierUdp.beginPacket(broadcastIp, udpPort); - notifierUdp.write(udpOut, WLEDPACKETSIZE); - notifierUdp.endPacket(); - notificationSentCallMode = callMode; - notificationSentTime = millis(); - notificationTwoRequired = (followUp)? false:notifyTwice; -} - - -void realtimeBoroadcast(IPAddress client, uint16_t length, byte *buffer, bool isRGBW) -{ - -} - - -void realtimeLock(uint32_t timeoutMs, byte md) -{ - if (!realtimeMode && !realtimeOverride){ - for (uint16_t i = 0; i < ledCount; i++) - { - strip.setPixelColor(i,0,0,0,0); - } - } - - realtimeTimeout = millis() + timeoutMs; - if (timeoutMs == 255001 || timeoutMs == 65000) realtimeTimeout = UINT32_MAX; - // if strip is off (bri==0) and not already in RTM - if (bri == 0 && !realtimeMode) { - strip.setBrightness(scaledBri(briLast)); - } - realtimeMode = md; - - if (arlsForceMaxBri && !realtimeOverride) strip.setBrightness(scaledBri(255)); - if (md == REALTIME_MODE_GENERIC) strip.show(); -} - - -#define TMP2NET_OUT_PORT 65442 - -void sendTPM2Ack() { - notifierUdp.beginPacket(notifierUdp.remoteIP(), TMP2NET_OUT_PORT); - uint8_t response_ack = 0xac; - notifierUdp.write(&response_ack, 1); - notifierUdp.endPacket(); -} - - -void handleNotifications() -{ - //send second notification if enabled - if(udpConnected && notificationTwoRequired && millis()-notificationSentTime > 250){ - notify(notificationSentCallMode,true); - } - - if (e131NewData && millis() - strip.getLastShow() > 15) - { - e131NewData = false; - strip.show(); - } - - //unlock strip when realtime UDP times out - if (realtimeMode && millis() > realtimeTimeout) - { - if (realtimeOverride == REALTIME_OVERRIDE_ONCE) realtimeOverride = REALTIME_OVERRIDE_NONE; - strip.setBrightness(scaledBri(bri)); - realtimeMode = REALTIME_MODE_INACTIVE; - realtimeIP[0] = 0; - } - - //receive UDP notifications - if (!udpConnected) return; - - bool isSupp = false; - uint16_t packetSize = notifierUdp.parsePacket(); - if (!packetSize && udp2Connected) { - packetSize = notifier2Udp.parsePacket(); - isSupp = true; - } - - //hyperion / raw RGB - if (!packetSize && udpRgbConnected) { - packetSize = rgbUdp.parsePacket(); - if (packetSize) { - if (!receiveDirect) return; - if (packetSize > UDP_IN_MAXSIZE || packetSize < 3) return; - realtimeIP = rgbUdp.remoteIP(); - DEBUG_PRINTLN(rgbUdp.remoteIP()); - uint8_t lbuf[packetSize]; - rgbUdp.read(lbuf, packetSize); - realtimeLock(realtimeTimeoutMs, REALTIME_MODE_HYPERION); - if (realtimeOverride) return; - uint16_t id = 0; - for (uint16_t i = 0; i < packetSize -2; i += 3) - { - setRealtimePixel(id, lbuf[i], lbuf[i+1], lbuf[i+2], 0); - id++; if (id >= ledCount) break; - } - strip.show(); - return; - } - } - - if (!(receiveNotifications || receiveDirect)) return; - - //notifier and UDP realtime - if (!packetSize || packetSize > UDP_IN_MAXSIZE) return; - if (!isSupp && notifierUdp.remoteIP() == Network.localIP()) return; //don't process broadcasts we send ourselves - - uint8_t udpIn[packetSize +1]; - uint16_t len; - if (isSupp) len = notifier2Udp.read(udpIn, packetSize); - else len = notifierUdp.read(udpIn, packetSize); - - // WLED nodes info notifications - if (isSupp && udpIn[0] == 255 && udpIn[1] == 1 && len >= 40) { - if (!nodeListEnabled || notifier2Udp.remoteIP() == Network.localIP()) return; - - uint8_t unit = udpIn[39]; - NodesMap::iterator it = Nodes.find(unit); - if (it == Nodes.end() && Nodes.size() < WLED_MAX_NODES) { // Create a new element when not present - Nodes[unit].age = 0; - it = Nodes.find(unit); - } - - if (it != Nodes.end()) { - for (byte x = 0; x < 4; x++) { - it->second.ip[x] = udpIn[x + 2]; - } - it->second.age = 0; // reset 'age counter' - char tmpNodeName[33] = { 0 }; - memcpy(&tmpNodeName[0], reinterpret_cast(&udpIn[6]), 32); - tmpNodeName[32] = 0; - it->second.nodeName = tmpNodeName; - it->second.nodeName.trim(); - it->second.nodeType = udpIn[38]; - uint32_t build = 0; - if (len >= 44) - for (byte i=0; isecond.build = build; - } - return; - } - - //wled notifier, ignore if realtime packets active - if (udpIn[0] == 0 && !realtimeMode && receiveNotifications) - { - //ignore notification if received within a second after sending a notification ourselves - if (millis() - notificationSentTime < 1000) return; - if (udpIn[1] > 199) return; //do not receive custom versions - - //compatibilityVersionByte: - byte version = udpIn[11]; - - // if we are not part of any sync group ignore message - if (version < 9 || version > 199) { - // legacy senders are treated as if sending in sync group 1 only - if (!(receiveGroups & 0x01)) return; - } else if (!(receiveGroups & udpIn[36])) return; - - bool someSel = (receiveNotificationBrightness || receiveNotificationColor || receiveNotificationEffects); - //apply colors from notification - if (receiveNotificationColor || !someSel) - { - col[0] = udpIn[3]; - col[1] = udpIn[4]; - col[2] = udpIn[5]; - if (version > 0) //sending module's white val is intended - { - col[3] = udpIn[10]; - if (version > 1) - { - colSec[0] = udpIn[12]; - colSec[1] = udpIn[13]; - colSec[2] = udpIn[14]; - colSec[3] = udpIn[15]; - } - if (version > 6) - { - strip.setColor(2, udpIn[20], udpIn[21], udpIn[22], udpIn[23]); //tertiary color - } - } - } - - bool timebaseUpdated = false; - //apply effects from notification - if (version < 200 && (receiveNotificationEffects || !someSel)) - { - if (udpIn[8] < strip.getModeCount()) effectCurrent = udpIn[8]; - effectSpeed = udpIn[9]; - if (version > 2) effectIntensity = udpIn[16]; - if (version > 4 && udpIn[19] < strip.getPaletteCount()) effectPalette = udpIn[19]; - if (version > 5) - { - uint32_t t = (udpIn[25] << 24) | (udpIn[26] << 16) | (udpIn[27] << 8) | (udpIn[28]); - t += PRESUMED_NETWORK_DELAY; //adjust trivially for network delay - t -= millis(); - strip.timebase = t; - timebaseUpdated = true; - } - } - - //adjust system time, but only if sender is more accurate than self - if (version > 7 && version < 200) - { - Toki::Time tm; - tm.sec = (udpIn[30] << 24) | (udpIn[31] << 16) | (udpIn[32] << 8) | (udpIn[33]); - tm.ms = (udpIn[34] << 8) | (udpIn[35]); - if (udpIn[29] > toki.getTimeSource()) { //if sender's time source is more accurate - toki.adjust(tm, PRESUMED_NETWORK_DELAY); //adjust trivially for network delay - uint8_t ts = TOKI_TS_UDP; - if (udpIn[29] > 99) ts = TOKI_TS_UDP_NTP; - else if (udpIn[29] >= TOKI_TS_SEC) ts = TOKI_TS_UDP_SEC; - toki.setTime(tm, ts); - } else if (timebaseUpdated && toki.getTimeSource() > 99) { //if we both have good times, get a more accurate timebase - Toki::Time myTime = toki.getTime(); - uint32_t diff = toki.msDifference(tm, myTime); - strip.timebase -= PRESUMED_NETWORK_DELAY; //no need to presume, use difference between NTP times at send and receive points - if (toki.isLater(tm, myTime)) { - strip.timebase += diff; - } else { - strip.timebase -= diff; - } - } - } - - if (version > 3) - { - transitionDelayTemp = ((udpIn[17] << 0) & 0xFF) + ((udpIn[18] << 8) & 0xFF00); - } - - nightlightActive = udpIn[6]; - if (nightlightActive) nightlightDelayMins = udpIn[7]; - - if (receiveNotificationBrightness || !someSel) bri = udpIn[2]; - colorUpdated(CALL_MODE_NOTIFICATION); - return; - } - - if (!receiveDirect) return; - - //TPM2.NET - if (udpIn[0] == 0x9c) - { - //WARNING: this code assumes that the final TMP2.NET payload is evenly distributed if using multiple packets (ie. frame size is constant) - //if the number of LEDs in your installation doesn't allow that, please include padding bytes at the end of the last packet - byte tpmType = udpIn[1]; - if (tpmType == 0xaa) { //TPM2.NET polling, expect answer - sendTPM2Ack(); return; - } - if (tpmType != 0xda) return; //return if notTPM2.NET data - - realtimeIP = (isSupp) ? notifier2Udp.remoteIP() : notifierUdp.remoteIP(); - realtimeLock(realtimeTimeoutMs, REALTIME_MODE_TPM2NET); - if (realtimeOverride) return; - - tpmPacketCount++; //increment the packet count - if (tpmPacketCount == 1) tpmPayloadFrameSize = (udpIn[2] << 8) + udpIn[3]; //save frame size for the whole payload if this is the first packet - byte packetNum = udpIn[4]; //starts with 1! - byte numPackets = udpIn[5]; - - uint16_t id = (tpmPayloadFrameSize/3)*(packetNum-1); //start LED - for (uint16_t i = 6; i < tpmPayloadFrameSize + 4; i += 3) - { - if (id < ledCount) - { - setRealtimePixel(id, udpIn[i], udpIn[i+1], udpIn[i+2], 0); - id++; - } - else break; - } - if (tpmPacketCount == numPackets) //reset packet count and show if all packets were received - { - tpmPacketCount = 0; - strip.show(); - } - return; - } - - //UDP realtime: 1 warls 2 drgb 3 drgbw - if (udpIn[0] > 0 && udpIn[0] < 5) - { - realtimeIP = (isSupp) ? notifier2Udp.remoteIP() : notifierUdp.remoteIP(); - DEBUG_PRINTLN(realtimeIP); - if (packetSize < 2) return; - - if (udpIn[1] == 0) - { - realtimeTimeout = 0; - return; - } else { - realtimeLock(udpIn[1]*1000 +1, REALTIME_MODE_UDP); - } - if (realtimeOverride) return; - - if (udpIn[0] == 1) //warls - { - for (uint16_t i = 2; i < packetSize -3; i += 4) - { - setRealtimePixel(udpIn[i], udpIn[i+1], udpIn[i+2], udpIn[i+3], 0); - } - } else if (udpIn[0] == 2) //drgb - { - uint16_t id = 0; - for (uint16_t i = 2; i < packetSize -2; i += 3) - { - setRealtimePixel(id, udpIn[i], udpIn[i+1], udpIn[i+2], 0); - - id++; if (id >= ledCount) break; - } - } else if (udpIn[0] == 3) //drgbw - { - uint16_t id = 0; - for (uint16_t i = 2; i < packetSize -3; i += 4) - { - setRealtimePixel(id, udpIn[i], udpIn[i+1], udpIn[i+2], udpIn[i+3]); - - id++; if (id >= ledCount) break; - } - } else if (udpIn[0] == 4) //dnrgb - { - uint16_t id = ((udpIn[3] << 0) & 0xFF) + ((udpIn[2] << 8) & 0xFF00); - for (uint16_t i = 4; i < packetSize -2; i += 3) - { - if (id >= ledCount) break; - setRealtimePixel(id, udpIn[i], udpIn[i+1], udpIn[i+2], 0); - id++; - } - } else if (udpIn[0] == 5) //dnrgbw - { - uint16_t id = ((udpIn[3] << 0) & 0xFF) + ((udpIn[2] << 8) & 0xFF00); - for (uint16_t i = 4; i < packetSize -2; i += 4) - { - if (id >= ledCount) break; - setRealtimePixel(id, udpIn[i], udpIn[i+1], udpIn[i+2], udpIn[i+3]); - id++; - } - } - strip.show(); - return; - } - - // API over UDP - udpIn[packetSize] = '\0'; - - if (udpIn[0] >= 'A' && udpIn[0] <= 'Z') { //HTTP API - String apireq = "win&"; - apireq += (char*)udpIn; - handleSet(nullptr, apireq); - } else if (udpIn[0] == '{') { //JSON API - DynamicJsonDocument jsonBuffer(2048); - DeserializationError error = deserializeJson(jsonBuffer, udpIn); - JsonObject root = jsonBuffer.as(); - if (!error && !root.isNull()) deserializeState(root); - } -} - - -void setRealtimePixel(uint16_t i, byte r, byte g, byte b, byte w) -{ - uint16_t pix = i + arlsOffset; - if (pix < ledCount) - { - if (!arlsDisableGammaCorrection && strip.gammaCorrectCol) - { - strip.setPixelColor(pix, strip.gamma8(r), strip.gamma8(g), strip.gamma8(b), strip.gamma8(w)); - } else { - strip.setPixelColor(pix, r, g, b, w); - } - } -} - -/*********************************************************************************************\ - Refresh aging for remote units, drop if too old... -\*********************************************************************************************/ -void refreshNodeList() -{ - for (NodesMap::iterator it = Nodes.begin(); it != Nodes.end();) { - bool mustRemove = true; - - if (it->second.ip[0] != 0) { - if (it->second.age < 10) { - it->second.age++; - mustRemove = false; - ++it; - } - } - - if (mustRemove) { - it = Nodes.erase(it); - } - } -} - -/*********************************************************************************************\ - Broadcast system info to other nodes. (to update node lists) -\*********************************************************************************************/ -void sendSysInfoUDP() -{ - if (!udp2Connected) return; - - IPAddress ip = Network.localIP(); - - // TODO: make a nice struct of it and clean up - // 0: 1 byte 'binary token 255' - // 1: 1 byte id '1' - // 2: 4 byte ip - // 6: 32 char name - // 38: 1 byte node type id - // 39: 1 byte node id - // 40: 4 byte version ID - // 44 bytes total - - // send my info to the world... - uint8_t data[44] = {0}; - data[0] = 255; - data[1] = 1; - - for (byte x = 0; x < 4; x++) { - data[x + 2] = ip[x]; - } - memcpy((byte *)data + 6, serverDescription, 32); - #ifdef ESP8266 - data[38] = NODE_TYPE_ID_ESP8266; - #elif defined(ARDUINO_ARCH_ESP32) - data[38] = NODE_TYPE_ID_ESP32; - #else - data[38] = NODE_TYPE_ID_UNDEFINED; - #endif - data[39] = ip[3]; // unit ID == last IP number - - uint32_t build = VERSION; - for (byte i=0; i>(8*i)) & 0xFF; - - IPAddress broadcastIP(255, 255, 255, 255); - notifier2Udp.beginPacket(broadcastIP, udpPort2); - notifier2Udp.write(data, sizeof(data)); - notifier2Udp.endPacket(); -} +#include "wled.h" +#include "src/dependencies/json/ArduinoJson-v6.h" + +/* + * UDP sync notifier / Realtime / Hyperion / TPM2.NET + */ + +#define WLEDPACKETSIZE 37 +#define UDP_IN_MAXSIZE 1472 +#define PRESUMED_NETWORK_DELAY 3 //how many ms could it take on avg to reach the receiver? This will be added to transmitted times + +void notify(byte callMode, bool followUp) +{ + if (!udpConnected) return; + if (!syncGroups) return; + switch (callMode) + { + case CALL_MODE_INIT: return; + case CALL_MODE_DIRECT_CHANGE: if (!notifyDirect) return; break; + case CALL_MODE_BUTTON: if (!notifyButton) return; break; + case CALL_MODE_NIGHTLIGHT: if (!notifyDirect) return; break; + case CALL_MODE_HUE: if (!notifyHue) return; break; + case CALL_MODE_PRESET_CYCLE: if (!notifyDirect) return; break; + case CALL_MODE_BLYNK: if (!notifyDirect) return; break; + case CALL_MODE_ALEXA: if (!notifyAlexa) return; break; + default: return; + } + byte udpOut[WLEDPACKETSIZE]; + udpOut[0] = 0; //0: wled notifier protocol 1: WARLS protocol + udpOut[1] = callMode; + udpOut[2] = bri; + udpOut[3] = col[0]; + udpOut[4] = col[1]; + udpOut[5] = col[2]; + udpOut[6] = nightlightActive; + udpOut[7] = nightlightDelayMins; + udpOut[8] = effectCurrent; + udpOut[9] = effectSpeed; + udpOut[10] = col[3]; + //compatibilityVersionByte: + //0: old 1: supports white 2: supports secondary color + //3: supports FX intensity, 24 byte packet 4: supports transitionDelay 5: sup palette + //6: supports timebase syncing, 29 byte packet 7: supports tertiary color 8: supports sys time sync, 36 byte packet + //9: supports sync groups, 37 byte packet + udpOut[11] = 9; + udpOut[12] = colSec[0]; + udpOut[13] = colSec[1]; + udpOut[14] = colSec[2]; + udpOut[15] = colSec[3]; + udpOut[16] = effectIntensity; + udpOut[17] = (transitionDelay >> 0) & 0xFF; + udpOut[18] = (transitionDelay >> 8) & 0xFF; + udpOut[19] = effectPalette; + uint32_t colTer = strip.getSegment(strip.getMainSegmentId()).colors[2]; + udpOut[20] = (colTer >> 16) & 0xFF; + udpOut[21] = (colTer >> 8) & 0xFF; + udpOut[22] = (colTer >> 0) & 0xFF; + udpOut[23] = (colTer >> 24) & 0xFF; + + udpOut[24] = followUp; + uint32_t t = millis() + strip.timebase; + udpOut[25] = (t >> 24) & 0xFF; + udpOut[26] = (t >> 16) & 0xFF; + udpOut[27] = (t >> 8) & 0xFF; + udpOut[28] = (t >> 0) & 0xFF; + + //sync system time + udpOut[29] = toki.getTimeSource(); + Toki::Time tm = toki.getTime(); + uint32_t unix = tm.sec; + udpOut[30] = (unix >> 24) & 0xFF; + udpOut[31] = (unix >> 16) & 0xFF; + udpOut[32] = (unix >> 8) & 0xFF; + udpOut[33] = (unix >> 0) & 0xFF; + uint16_t ms = tm.ms; + udpOut[34] = (ms >> 8) & 0xFF; + udpOut[35] = (ms >> 0) & 0xFF; + + //sync groups + udpOut[36] = syncGroups; + + IPAddress broadcastIp; + broadcastIp = ~uint32_t(Network.subnetMask()) | uint32_t(Network.gatewayIP()); + + notifierUdp.beginPacket(broadcastIp, udpPort); + notifierUdp.write(udpOut, WLEDPACKETSIZE); + notifierUdp.endPacket(); + notificationSentCallMode = callMode; + notificationSentTime = millis(); + notificationTwoRequired = (followUp)? false:notifyTwice; +} + +void realtimeLock(uint32_t timeoutMs, byte md) +{ + if (!realtimeMode && !realtimeOverride){ + for (uint16_t i = 0; i < ledCount; i++) + { + strip.setPixelColor(i,0,0,0,0); + } + } + + realtimeTimeout = millis() + timeoutMs; + if (timeoutMs == 255001 || timeoutMs == 65000) realtimeTimeout = UINT32_MAX; + // if strip is off (bri==0) and not already in RTM + if (bri == 0 && !realtimeMode) { + strip.setBrightness(scaledBri(briLast)); + } + realtimeMode = md; + + if (arlsForceMaxBri && !realtimeOverride) strip.setBrightness(scaledBri(255)); + if (md == REALTIME_MODE_GENERIC) strip.show(); +} + + +#define TMP2NET_OUT_PORT 65442 + +void sendTPM2Ack() { + notifierUdp.beginPacket(notifierUdp.remoteIP(), TMP2NET_OUT_PORT); + uint8_t response_ack = 0xac; + notifierUdp.write(&response_ack, 1); + notifierUdp.endPacket(); +} + + +void handleNotifications() +{ + //send second notification if enabled + if(udpConnected && notificationTwoRequired && millis()-notificationSentTime > 250){ + notify(notificationSentCallMode,true); + } + + if (e131NewData && millis() - strip.getLastShow() > 15) + { + e131NewData = false; + strip.show(); + } + + //unlock strip when realtime UDP times out + if (realtimeMode && millis() > realtimeTimeout) + { + if (realtimeOverride == REALTIME_OVERRIDE_ONCE) realtimeOverride = REALTIME_OVERRIDE_NONE; + strip.setBrightness(scaledBri(bri)); + realtimeMode = REALTIME_MODE_INACTIVE; + realtimeIP[0] = 0; + } + + //receive UDP notifications + if (!udpConnected) return; + + bool isSupp = false; + uint16_t packetSize = notifierUdp.parsePacket(); + if (!packetSize && udp2Connected) { + packetSize = notifier2Udp.parsePacket(); + isSupp = true; + } + + //hyperion / raw RGB + if (!packetSize && udpRgbConnected) { + packetSize = rgbUdp.parsePacket(); + if (packetSize) { + if (!receiveDirect) return; + if (packetSize > UDP_IN_MAXSIZE || packetSize < 3) return; + realtimeIP = rgbUdp.remoteIP(); + DEBUG_PRINTLN(rgbUdp.remoteIP()); + uint8_t lbuf[packetSize]; + rgbUdp.read(lbuf, packetSize); + realtimeLock(realtimeTimeoutMs, REALTIME_MODE_HYPERION); + if (realtimeOverride) return; + uint16_t id = 0; + for (uint16_t i = 0; i < packetSize -2; i += 3) + { + setRealtimePixel(id, lbuf[i], lbuf[i+1], lbuf[i+2], 0); + id++; if (id >= ledCount) break; + } + strip.show(); + return; + } + } + + if (!(receiveNotifications || receiveDirect)) return; + + //notifier and UDP realtime + if (!packetSize || packetSize > UDP_IN_MAXSIZE) return; + if (!isSupp && notifierUdp.remoteIP() == Network.localIP()) return; //don't process broadcasts we send ourselves + + uint8_t udpIn[packetSize +1]; + uint16_t len; + if (isSupp) len = notifier2Udp.read(udpIn, packetSize); + else len = notifierUdp.read(udpIn, packetSize); + + // WLED nodes info notifications + if (isSupp && udpIn[0] == 255 && udpIn[1] == 1 && len >= 40) { + if (!nodeListEnabled || notifier2Udp.remoteIP() == Network.localIP()) return; + + uint8_t unit = udpIn[39]; + NodesMap::iterator it = Nodes.find(unit); + if (it == Nodes.end() && Nodes.size() < WLED_MAX_NODES) { // Create a new element when not present + Nodes[unit].age = 0; + it = Nodes.find(unit); + } + + if (it != Nodes.end()) { + for (byte x = 0; x < 4; x++) { + it->second.ip[x] = udpIn[x + 2]; + } + it->second.age = 0; // reset 'age counter' + char tmpNodeName[33] = { 0 }; + memcpy(&tmpNodeName[0], reinterpret_cast(&udpIn[6]), 32); + tmpNodeName[32] = 0; + it->second.nodeName = tmpNodeName; + it->second.nodeName.trim(); + it->second.nodeType = udpIn[38]; + uint32_t build = 0; + if (len >= 44) + for (byte i=0; isecond.build = build; + } + return; + } + + //wled notifier, ignore if realtime packets active + if (udpIn[0] == 0 && !realtimeMode && receiveNotifications) + { + //ignore notification if received within a second after sending a notification ourselves + if (millis() - notificationSentTime < 1000) return; + if (udpIn[1] > 199) return; //do not receive custom versions + + //compatibilityVersionByte: + byte version = udpIn[11]; + + // if we are not part of any sync group ignore message + if (version < 9 || version > 199) { + // legacy senders are treated as if sending in sync group 1 only + if (!(receiveGroups & 0x01)) return; + } else if (!(receiveGroups & udpIn[36])) return; + + bool someSel = (receiveNotificationBrightness || receiveNotificationColor || receiveNotificationEffects); + //apply colors from notification + if (receiveNotificationColor || !someSel) + { + col[0] = udpIn[3]; + col[1] = udpIn[4]; + col[2] = udpIn[5]; + if (version > 0) //sending module's white val is intended + { + col[3] = udpIn[10]; + if (version > 1) + { + colSec[0] = udpIn[12]; + colSec[1] = udpIn[13]; + colSec[2] = udpIn[14]; + colSec[3] = udpIn[15]; + } + if (version > 6) + { + strip.setColor(2, udpIn[20], udpIn[21], udpIn[22], udpIn[23]); //tertiary color + } + } + } + + bool timebaseUpdated = false; + //apply effects from notification + if (version < 200 && (receiveNotificationEffects || !someSel)) + { + if (udpIn[8] < strip.getModeCount()) effectCurrent = udpIn[8]; + effectSpeed = udpIn[9]; + if (version > 2) effectIntensity = udpIn[16]; + if (version > 4 && udpIn[19] < strip.getPaletteCount()) effectPalette = udpIn[19]; + if (version > 5) + { + uint32_t t = (udpIn[25] << 24) | (udpIn[26] << 16) | (udpIn[27] << 8) | (udpIn[28]); + t += PRESUMED_NETWORK_DELAY; //adjust trivially for network delay + t -= millis(); + strip.timebase = t; + timebaseUpdated = true; + } + } + + //adjust system time, but only if sender is more accurate than self + if (version > 7 && version < 200) + { + Toki::Time tm; + tm.sec = (udpIn[30] << 24) | (udpIn[31] << 16) | (udpIn[32] << 8) | (udpIn[33]); + tm.ms = (udpIn[34] << 8) | (udpIn[35]); + if (udpIn[29] > toki.getTimeSource()) { //if sender's time source is more accurate + toki.adjust(tm, PRESUMED_NETWORK_DELAY); //adjust trivially for network delay + uint8_t ts = TOKI_TS_UDP; + if (udpIn[29] > 99) ts = TOKI_TS_UDP_NTP; + else if (udpIn[29] >= TOKI_TS_SEC) ts = TOKI_TS_UDP_SEC; + toki.setTime(tm, ts); + } else if (timebaseUpdated && toki.getTimeSource() > 99) { //if we both have good times, get a more accurate timebase + Toki::Time myTime = toki.getTime(); + uint32_t diff = toki.msDifference(tm, myTime); + strip.timebase -= PRESUMED_NETWORK_DELAY; //no need to presume, use difference between NTP times at send and receive points + if (toki.isLater(tm, myTime)) { + strip.timebase += diff; + } else { + strip.timebase -= diff; + } + } + } + + if (version > 3) + { + transitionDelayTemp = ((udpIn[17] << 0) & 0xFF) + ((udpIn[18] << 8) & 0xFF00); + } + + nightlightActive = udpIn[6]; + if (nightlightActive) nightlightDelayMins = udpIn[7]; + + if (receiveNotificationBrightness || !someSel) bri = udpIn[2]; + colorUpdated(CALL_MODE_NOTIFICATION); + return; + } + + if (!receiveDirect) return; + + //TPM2.NET + if (udpIn[0] == 0x9c) + { + //WARNING: this code assumes that the final TMP2.NET payload is evenly distributed if using multiple packets (ie. frame size is constant) + //if the number of LEDs in your installation doesn't allow that, please include padding bytes at the end of the last packet + byte tpmType = udpIn[1]; + if (tpmType == 0xaa) { //TPM2.NET polling, expect answer + sendTPM2Ack(); return; + } + if (tpmType != 0xda) return; //return if notTPM2.NET data + + realtimeIP = (isSupp) ? notifier2Udp.remoteIP() : notifierUdp.remoteIP(); + realtimeLock(realtimeTimeoutMs, REALTIME_MODE_TPM2NET); + if (realtimeOverride) return; + + tpmPacketCount++; //increment the packet count + if (tpmPacketCount == 1) tpmPayloadFrameSize = (udpIn[2] << 8) + udpIn[3]; //save frame size for the whole payload if this is the first packet + byte packetNum = udpIn[4]; //starts with 1! + byte numPackets = udpIn[5]; + + uint16_t id = (tpmPayloadFrameSize/3)*(packetNum-1); //start LED + for (uint16_t i = 6; i < tpmPayloadFrameSize + 4; i += 3) + { + if (id < ledCount) + { + setRealtimePixel(id, udpIn[i], udpIn[i+1], udpIn[i+2], 0); + id++; + } + else break; + } + if (tpmPacketCount == numPackets) //reset packet count and show if all packets were received + { + tpmPacketCount = 0; + strip.show(); + } + return; + } + + //UDP realtime: 1 warls 2 drgb 3 drgbw + if (udpIn[0] > 0 && udpIn[0] < 5) + { + realtimeIP = (isSupp) ? notifier2Udp.remoteIP() : notifierUdp.remoteIP(); + DEBUG_PRINTLN(realtimeIP); + if (packetSize < 2) return; + + if (udpIn[1] == 0) + { + realtimeTimeout = 0; + return; + } else { + realtimeLock(udpIn[1]*1000 +1, REALTIME_MODE_UDP); + } + if (realtimeOverride) return; + + if (udpIn[0] == 1) //warls + { + for (uint16_t i = 2; i < packetSize -3; i += 4) + { + setRealtimePixel(udpIn[i], udpIn[i+1], udpIn[i+2], udpIn[i+3], 0); + } + } else if (udpIn[0] == 2) //drgb + { + uint16_t id = 0; + for (uint16_t i = 2; i < packetSize -2; i += 3) + { + setRealtimePixel(id, udpIn[i], udpIn[i+1], udpIn[i+2], 0); + + id++; if (id >= ledCount) break; + } + } else if (udpIn[0] == 3) //drgbw + { + uint16_t id = 0; + for (uint16_t i = 2; i < packetSize -3; i += 4) + { + setRealtimePixel(id, udpIn[i], udpIn[i+1], udpIn[i+2], udpIn[i+3]); + + id++; if (id >= ledCount) break; + } + } else if (udpIn[0] == 4) //dnrgb + { + uint16_t id = ((udpIn[3] << 0) & 0xFF) + ((udpIn[2] << 8) & 0xFF00); + for (uint16_t i = 4; i < packetSize -2; i += 3) + { + if (id >= ledCount) break; + setRealtimePixel(id, udpIn[i], udpIn[i+1], udpIn[i+2], 0); + id++; + } + } else if (udpIn[0] == 5) //dnrgbw + { + uint16_t id = ((udpIn[3] << 0) & 0xFF) + ((udpIn[2] << 8) & 0xFF00); + for (uint16_t i = 4; i < packetSize -2; i += 4) + { + if (id >= ledCount) break; + setRealtimePixel(id, udpIn[i], udpIn[i+1], udpIn[i+2], udpIn[i+3]); + id++; + } + } + strip.show(); + return; + } + + // API over UDP + udpIn[packetSize] = '\0'; + + if (udpIn[0] >= 'A' && udpIn[0] <= 'Z') { //HTTP API + String apireq = "win&"; + apireq += (char*)udpIn; + handleSet(nullptr, apireq); + } else if (udpIn[0] == '{') { //JSON API + DynamicJsonDocument jsonBuffer(2048); + DeserializationError error = deserializeJson(jsonBuffer, udpIn); + JsonObject root = jsonBuffer.as(); + if (!error && !root.isNull()) deserializeState(root); + } +} + + +void setRealtimePixel(uint16_t i, byte r, byte g, byte b, byte w) +{ + uint16_t pix = i + arlsOffset; + if (pix < ledCount) + { + if (!arlsDisableGammaCorrection && strip.gammaCorrectCol) + { + strip.setPixelColor(pix, strip.gamma8(r), strip.gamma8(g), strip.gamma8(b), strip.gamma8(w)); + } else { + strip.setPixelColor(pix, r, g, b, w); + } + } +} + +/*********************************************************************************************\ + Refresh aging for remote units, drop if too old... +\*********************************************************************************************/ +void refreshNodeList() +{ + for (NodesMap::iterator it = Nodes.begin(); it != Nodes.end();) { + bool mustRemove = true; + + if (it->second.ip[0] != 0) { + if (it->second.age < 10) { + it->second.age++; + mustRemove = false; + ++it; + } + } + + if (mustRemove) { + it = Nodes.erase(it); + } + } +} + +/*********************************************************************************************\ + Broadcast system info to other nodes. (to update node lists) +\*********************************************************************************************/ +void sendSysInfoUDP() +{ + if (!udp2Connected) return; + + IPAddress ip = Network.localIP(); + + // TODO: make a nice struct of it and clean up + // 0: 1 byte 'binary token 255' + // 1: 1 byte id '1' + // 2: 4 byte ip + // 6: 32 char name + // 38: 1 byte node type id + // 39: 1 byte node id + // 40: 4 byte version ID + // 44 bytes total + + // send my info to the world... + uint8_t data[44] = {0}; + data[0] = 255; + data[1] = 1; + + for (byte x = 0; x < 4; x++) { + data[x + 2] = ip[x]; + } + memcpy((byte *)data + 6, serverDescription, 32); + #ifdef ESP8266 + data[38] = NODE_TYPE_ID_ESP8266; + #elif defined(ARDUINO_ARCH_ESP32) + data[38] = NODE_TYPE_ID_ESP32; + #else + data[38] = NODE_TYPE_ID_UNDEFINED; + #endif + data[39] = ip[3]; // unit ID == last IP number + + uint32_t build = VERSION; + for (byte i=0; i>(8*i)) & 0xFF; + + IPAddress broadcastIP(255, 255, 255, 255); + notifier2Udp.beginPacket(broadcastIP, udpPort2); + notifier2Udp.write(data, sizeof(data)); + notifier2Udp.endPacket(); +} + + +/*********************************************************************************************\ + * Art-Net, DDP, E131 output - work in progress +\*********************************************************************************************/ + +#define DDP_HEADER_LEN 10 +#define DDP_SYNCPACKET_LEN 10 + +#define DDP_FLAGS1_VER 0xc0 // version mask +#define DDP_FLAGS1_VER1 0x40 // version=1 +#define DDP_FLAGS1_PUSH 0x01 +#define DDP_FLAGS1_QUERY 0x02 +#define DDP_FLAGS1_REPLY 0x04 +#define DDP_FLAGS1_STORAGE 0x08 +#define DDP_FLAGS1_TIME 0x10 + +#define DDP_ID_DISPLAY 1 +#define DDP_ID_CONFIG 250 +#define DDP_ID_STATUS 251 + +// 1440 channels per packet +#define DDP_CHANNELS_PER_PACKET 1440 // 480 leds + +// +// Send real time DDP UDP updates to the specified client +// +// client - the IP address to send to +// length - the number of pixels +// buffer - a buffer of at least length*4 bytes long +// isRGBW - true if the buffer contains 4 components per pixel + +uint8_t sequenceNumber = 0; // this needs to be shared across all outputs + +uint8_t realtimeBroadcast(IPAddress client, uint16_t length, uint8_t *buffer, bool isRGBW) { + WiFiUDP ddpUdp; + + // calclate the number of UDP packets we need to send + uint16_t channelCount = length * 3; // 1 channel for every R,G,B value + uint16_t packetCount = channelCount / DDP_CHANNELS_PER_PACKET; + if (channelCount % DDP_CHANNELS_PER_PACKET) { + packetCount++; + } + + // there are 3 channels per RGB pixel + uint16_t channel = 0; // TODO: allow specifying the start channel + // the current position in the buffer + uint16_t bufferOffset = 0; + + for (uint16_t currentPacket = 0; currentPacket < packetCount; currentPacket++) { + if (sequenceNumber > 15) sequenceNumber = 0; + + int rc = ddpUdp.beginPacket(client, DDP_PORT); + if (rc == 0) { + //DEBUG_PRINTLN("WiFiUDP.beginPacket returned an error"); + return 1; // problem + } + + // the amount of data is AFTER the header in the current packet + uint16_t packetSize = DDP_CHANNELS_PER_PACKET; + + uint8_t flags = DDP_FLAGS1_VER1; + if (currentPacket == (packetCount - 1)) { + // last packet, set the push flag + // TODO: determine if we want to send an empty push packet to each destination after sending the pixel data + flags = DDP_FLAGS1_VER1 | DDP_FLAGS1_PUSH; + if (channelCount % DDP_CHANNELS_PER_PACKET) { + packetSize = channelCount % DDP_CHANNELS_PER_PACKET; + } + } + + // write the header + /*0*/ddpUdp.write(flags); + /*1*/ddpUdp.write(sequenceNumber++ & 0xF); + /*2*/ddpUdp.write(0); + /*3*/ddpUdp.write(DDP_ID_DISPLAY); + // data offset in bytes, 32-bit number, MSB first + /*4*/ddpUdp.write((channel & 0xFF000000) >> 24); + /*5*/ddpUdp.write((channel & 0x00FF0000) >> 16); + /*6*/ddpUdp.write((channel & 0x0000FF00) >> 8); + /*7*/ddpUdp.write((channel & 0x000000FF)); + // data length in bytes, 16-bit number, MSB first + /*8*/ddpUdp.write((packetSize & 0xFF00) >> 8); + /*9*/ddpUdp.write(packetSize & 0xFF); + + // write the colors, the write write(const uint8_t *buffer, size_t size) + // function is just a loop internally too + for (uint16_t i = 0; i < packetSize; i += 3) { + ddpUdp.write(buffer[bufferOffset++]); // R + ddpUdp.write(buffer[bufferOffset++]); // G + ddpUdp.write(buffer[bufferOffset++]); // B + if (isRGBW) bufferOffset++; + } + + rc = ddpUdp.endPacket(); + if (rc == 0) { + //DEBUG_PRINTLN("WiFiUDP.endPacket returned an error"); + return 1; // problem + } + + channel += packetSize; + } + + return 0; +} diff --git a/wled00/udp.h b/wled00/udp.h new file mode 100644 index 000000000..3765cea08 --- /dev/null +++ b/wled00/udp.h @@ -0,0 +1,93 @@ +#ifndef UDP_H +#define UDP_H + +// expected to be included from wled.h where other dependencies are loaded first + +void notify(byte callMode, bool followUp); +void realtimeLock(uint32_t timeoutMs, byte md); +void sendTPM2Ack(); +void handleNotifications(); +void setRealtimePixel(uint16_t i, byte r, byte g, byte b, byte w); + +/*********************************************************************************************\ + Refresh aging for remote units, drop if too old... +\*********************************************************************************************/ +void refreshNodeList(); + +/*********************************************************************************************\ + Broadcast system info to other nodes. (to update node lists) +\*********************************************************************************************/ +void sendSysInfoUDP(); + +/*********************************************************************************************\ + * Art-Net, DDP, E131 output - work in progress +\*********************************************************************************************/ + +// Send real time DDP UDP updates to the specified client +// +// client - the IP address to send to +// buffer - a buffer of at least length*3 or length*4 bytes long +// length - the number of pixels +// isRGBW - true if the buffer contains 4 components per pixel +uint8_t realtimeBroadcast(IPAddress client, uint16_t length, uint8_t *buffer, bool isRGBW); + +#define DDP_PORT 4048 + +#define DDP_PUSH_FLAG 0x01 +#define DDP_TIMECODE_FLAG 0x10 + +#ifdef UPD_OUTPUT // just disable out for now +// Base class for all UDP output types. +class UDPOutputData { +public: + UDPOutputData(const JsonDocument& config); + virtual ~UDPOutputData(); + + virtual bool IsPingable() = 0; + + virtual void PrepareData(unsigned char* channelData /*,UDPOutputMessages& msgs*/) = 0; + virtual void PostPrepareData(unsigned char* channelData /*,UDPOutputMessages& msgs*/) { } + + int startChannel; + int channelCount; + IPAddress ipAddress; + + UDPOutputData(UDPOutputData const&) = delete; + void operator=(UDPOutputData const& x) = delete; + +protected: + // functions and settings to detect duplicate frames to avoid sending the same data as last time + void SaveFrame(unsigned char* channelData, int len); + bool NeedToOutputFrame(unsigned char* channelData, int startChannel, int savedIdx, int count); + bool deDuplicate = false; + int skippedFrames; + unsigned char* lastData; +}; + +// Art-Net - https://en.wikipedia.org/wiki/Art-Net +class ArtNetOutputData : public UDPOutputData { + // TODO +}; + +// Distributed Display Protocol (DDP) +class DDPOutputData : public UDPOutputData { +public: + explicit DDPOutputData(const JsonDocument& config); + virtual ~DDPOutputData(); + + virtual bool IsPingable() override { return true; } + virtual void PrepareData(unsigned char* channelData /*,UDPOutputMessages& msgs*/) override; +}; + +// E1.31 (Streaming-ACN) Protocol +class E131OutputData : public UDPOutputData { + // TODO +}; + +class UDPOutput { +public: + void AddOutput(UDPOutputData*); +}; +#endif // UPD_OUTPUT + +#endif \ No newline at end of file diff --git a/wled00/wled.h b/wled00/wled.h index 1e1d2db1f..ad967a9cc 100644 --- a/wled00/wled.h +++ b/wled00/wled.h @@ -149,6 +149,7 @@ using PSRAMDynamicJsonDocument = BasicJsonDocument; #include "NodeStruct.h" #include "pin_manager.h" #include "bus_manager.h" +#include "udp.h" #ifndef CLIENT_SSID #define CLIENT_SSID DEFAULT_CLIENT_SSID