diff --git a/.github/workflows/wled-ci.yml b/.github/workflows/wled-ci.yml index 2b599e6f6..7d27717dd 100644 --- a/.github/workflows/wled-ci.yml +++ b/.github/workflows/wled-ci.yml @@ -39,6 +39,11 @@ jobs: environment: ${{ fromJSON(needs.get_default_envs.outputs.environments) }} steps: - uses: actions/checkout@v3 + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + cache: 'npm' + - run: npm install - name: Cache pip uses: actions/cache@v3 with: diff --git a/.gitignore b/.gitignore index c85fae0c2..8a2319a72 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,6 @@ .clang-format .direnv .DS_Store -.gitignore .idea .pio .pioenvs @@ -22,3 +21,4 @@ wled-update.sh /wled00/my_config.h /wled00/Release /wled00/wled00.ino.cpp +/wled00/html_*.h \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index a285f1fe0..17c37c530 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,19 +1,42 @@ ## WLED changelog -#### Build 2309120 till build 2311120 +#### Build 2309120 till build 2201060 - WLED version 0.15.0-a0 +- Global JSON buffer guarding (#3648 by @willmmiles, resolves #3641, #3312, #3367, #3637, #3646, #3447) +- Effect: Fireworks 1D (fix for matrix trailing strip) +- BREAKING: Reduced number of segments (12) on ESP8266 due to less available RAM +- Increased available effect data buffer (increases more if board has PSRAM) +- Custom palette editor mobile UI enhancement (by @imeszaros) +- Per port Auto Brightness Limiter (ABL) +- Use PSRAM for JSON buffer (double size, larger ledmaps, up to 2k) +- Reduced heap fragmentation by allocating ledmap array only once and not deallocating effect buffer +- HTTP retries on failed UI load +- UI Search: scroll to top (#3587 by @WoodyLetsCode) +- Return to inline iro.js and rangetouch.js (#3597 by @WoodyLetsCode) +- Better caching (#3591 by @WoodyLetsCode) +- Do not send 404 for missing `skin.css` (#3590 by @WoodyLetsCode) +- Simplified UI rework (#3511 by @WoodyLetsCode) +- Domoticz device ID for PIR and Temperature usermods +- Bugfix for UCS8904 `hasWhite()` +- Better search in UI (#3540 by @WoodyLetsCode) +- Seeding FastLED PRNG (#3552 by @TripleWhy) +- WIZ Smart Button support (#3547 by @micw) +- New button type (button switch, fix for #3537) +- Pixel Magic Tool update (#3483 by @ajotanc) +- Effect: 2D Matrix fix for gaps +- Bugfix #3526, #3533, #3561 - Spookier Halloween Eyes (#3501) - Compile time options for Multi Relay usermod (#3498) -- Fix for Dissolve (#3502) +- Effect: Fix for Dissolve (#3502) - Better reverse proxy support (nested paths) - Implement global JSON API boolean toggle (i.e. instead of "var":true or "var":false -> "var":"t"). - Sort presets by ID -- Fix #3496 +- Fix for #3641, #3312, #3367, #3637, #3646, #3447, #3632, #3496, #2922, #3593, #3514, #3522, #3578 (partial), #3606 (@WoodyLetsCode) - Improved random bg image and added random bg image options (@WoodyLetsCode, #3481) - Audio palettes (Audioreactive usermod, credit @netmindz) - Better UI tooltips (@ajotnac, #3464) - Better effect filters (filter dropdown) -- Fix udp sync (fix for #3487) +- UDP sync fix (for #3487) - Power button override (solves #3431) - Additional HTTP request throttling (ESP8266) - Additional UI/UX improvements diff --git a/pio-scripts/build_ui.py b/pio-scripts/build_ui.py new file mode 100644 index 000000000..f3688a5d4 --- /dev/null +++ b/pio-scripts/build_ui.py @@ -0,0 +1,3 @@ +Import('env') + +env.Execute("npm run build") \ No newline at end of file diff --git a/platformio.ini b/platformio.ini index fa6bf3bb8..9279f2727 100644 --- a/platformio.ini +++ b/platformio.ini @@ -137,6 +137,7 @@ build_flags = ; -D USERMOD_SENSORSTOMQTT #For ADS1115 sensor uncomment following ; -D USERMOD_ADS1115 + ; -D USERMOD_ANIMARTRIX build_unflags = @@ -155,6 +156,7 @@ extra_scripts = post:pio-scripts/output_bins.py post:pio-scripts/strip-floats.py pre:pio-scripts/user_config_copy.py + pre:pio-scripts/build_ui.py # ------------------------------------------------------------------------------ # COMMON SETTINGS: @@ -198,6 +200,11 @@ lib_deps = #For ADS1115 sensor uncomment following ; adafruit/Adafruit BusIO @ 1.13.2 ; adafruit/Adafruit ADS1X15 @ 2.4.0 + #For MPU6050 IMU uncomment follwoing + ; electroniccats/MPU6050 @1.0.1 + # For -D USERMOD_ANIMARTRIX + # CC BY-NC 3.0 licensed effects by Stefan Petrick, include this usermod only if you accept the terms! + ; https://github.com/netmindz/animartrix.git#18bf17389e57c69f11bc8d04ebe1d215422c7fb7 extra_scripts = ${scripts_defaults.extra_scripts} diff --git a/tools/cdata.js b/tools/cdata.js index 90619ba67..4b0d15d4f 100644 --- a/tools/cdata.js +++ b/tools/cdata.js @@ -16,12 +16,15 @@ */ const fs = require("fs"); +const path = require('path'); const inliner = require("inliner"); const zlib = require("zlib"); const CleanCSS = require("clean-css"); const MinifyHTML = require("html-minifier-terser").minify; const packageJson = require("../package.json"); +const output = ["wled00/html_ui.h", "wled00/html_pixart.h", "wled00/html_cpal.h", "wled00/html_pxmagic.h", "wled00/html_settings.h", "wled00/html_other.h"] + /** * */ @@ -182,7 +185,7 @@ ${result} const result = hexdump(buf); const chunk = ` // Autogenerated from ${srcDir}/${s.file}, do not edit!! -const uint16_t ${s.name}_length = ${result.length}; +const uint16_t ${s.name}_length = ${buf.length}; const uint8_t ${s.name}[] PROGMEM = { ${result} }; @@ -204,12 +207,13 @@ function writeChunks(srcDir, specs, resultFile) { */ `; specs.forEach((s) => { + const file = srcDir + "/" + s.file; try { - console.info("Reading " + srcDir + "/" + s.file + " as " + s.name); + console.info("Reading " + file + " as " + s.name); src += specToChunk(srcDir, s); } catch (e) { console.warn( - "Failed " + s.name + " from " + srcDir + "/" + s.file, + "Failed " + s.name + " from " + file, e.message.length > 60 ? e.message.substring(0, 60) : e.message ); } @@ -218,37 +222,57 @@ function writeChunks(srcDir, specs, resultFile) { fs.writeFileSync(resultFile, src); } +// Check if a file is newer than a given time +function isFileNewerThan(filePath, time) { + try { + const stats = fs.statSync(filePath); + return stats.mtimeMs > time; + } catch (e) { + console.error(`Failed to get stats for file ${filePath}:`, e); + return false; + } +} + +// Check if any file in a folder (or its subfolders) is newer than a given time +function isAnyFileInFolderNewerThan(folderPath, time) { + const files = fs.readdirSync(folderPath, { withFileTypes: true }); + for (const file of files) { + const filePath = path.join(folderPath, file.name); + if (isFileNewerThan(filePath, time)) { + return true; + } + if (file.isDirectory() && isAnyFileInFolderNewerThan(filePath, time)) { + return true; + } + } + return false; +} + +function isAlreadyBuilt(folderPath) { + let lastBuildTime = Infinity; + + for (const file of output) { + try { + lastBuildTime = Math.min(lastBuildTime, fs.statSync(file).mtimeMs); + } + catch (e) { + return false; + } + } + + return !isAnyFileInFolderNewerThan(folderPath, lastBuildTime); +} + +if (isAlreadyBuilt("wled00/data") && process.argv[2] !== '--force' && process.argv[2] !== '-f') { + console.info("Web UI is already built"); + return; +} + writeHtmlGzipped("wled00/data/index.htm", "wled00/html_ui.h", 'index'); -writeHtmlGzipped("wled00/data/simple.htm", "wled00/html_simple.h", 'simple'); writeHtmlGzipped("wled00/data/pixart/pixart.htm", "wled00/html_pixart.h", 'pixart'); writeHtmlGzipped("wled00/data/cpal/cpal.htm", "wled00/html_cpal.h", 'cpal'); writeHtmlGzipped("wled00/data/pxmagic/pxmagic.htm", "wled00/html_pxmagic.h", 'pxmagic'); -/* -writeChunks( - "wled00/data", - [ - { - file: "simple.css", - name: "PAGE_simpleCss", - method: "gzip", - filter: "css-minify", - }, - { - file: "simple.js", - name: "PAGE_simpleJs", - method: "gzip", - filter: "js-minify", - }, - { - file: "simple.htm", - name: "PAGE_simple", - method: "gzip", - filter: "html-minify-ui", - } - ], - "wled00/html_simplex.h" -); -*/ + writeChunks( "wled00/data", [ @@ -406,16 +430,6 @@ const char PAGE_dmxmap[] PROGMEM = R"=====()====="; file: "favicon.ico", name: "favicon", method: "binary", - }, - { - file: "iro.js", - name: "iroJs", - method: "gzip" - }, - { - file: "rangetouch.js", - name: "rangetouchJs", - method: "gzip" } ], "wled00/html_other.h" diff --git a/usermods/EXAMPLE_v2/usermod_v2_example.h b/usermods/EXAMPLE_v2/usermod_v2_example.h index 43648b588..910e0cae2 100644 --- a/usermods/EXAMPLE_v2/usermod_v2_example.h +++ b/usermods/EXAMPLE_v2/usermod_v2_example.h @@ -87,7 +87,7 @@ class MyExampleUsermod : public Usermod { * readFromConfig() is called prior to setup() * You can use it to initialize variables, sensors or similar. */ - void setup() { + void setup() override { // do your set-up here //Serial.println("Hello from my usermod!"); initDone = true; @@ -98,7 +98,7 @@ class MyExampleUsermod : public Usermod { * connected() is called every time the WiFi is (re)connected * Use it to initialize network interfaces */ - void connected() { + void connected() override { //Serial.println("Connected to WiFi!"); } @@ -113,7 +113,7 @@ class MyExampleUsermod : public Usermod { * 2. Try to avoid using the delay() function. NEVER use delays longer than 10 milliseconds. * Instead, use a timer check as shown here. */ - void loop() { + void loop() override { // if usermod is disabled or called during strip updating just exit // NOTE: on very long strips strip.isUpdating() may always return true so update accordingly if (!enabled || strip.isUpdating()) return; @@ -131,7 +131,7 @@ class MyExampleUsermod : public Usermod { * Creating an "u" object allows you to add custom key/value pairs to the Info section of the WLED web UI. * Below it is shown how this could be used for e.g. a light sensor */ - void addToJsonInfo(JsonObject& root) + void addToJsonInfo(JsonObject& root) override { // if "u" object does not exist yet wee need to create it JsonObject user = root["u"]; @@ -156,7 +156,7 @@ class MyExampleUsermod : public Usermod { * addToJsonState() can be used to add custom entries to the /json/state part of the JSON API (state object). * Values in the state object may be modified by connected clients */ - void addToJsonState(JsonObject& root) + void addToJsonState(JsonObject& root) override { if (!initDone || !enabled) return; // prevent crash on boot applyPreset() @@ -171,7 +171,7 @@ class MyExampleUsermod : public Usermod { * readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object). * Values in the state object may be modified by connected clients */ - void readFromJsonState(JsonObject& root) + void readFromJsonState(JsonObject& root) override { if (!initDone) return; // prevent crash on boot applyPreset() @@ -220,7 +220,7 @@ class MyExampleUsermod : public Usermod { * * I highly recommend checking out the basics of ArduinoJson serialization and deserialization in order to use custom settings! */ - void addToConfig(JsonObject& root) + void addToConfig(JsonObject& root) override { JsonObject top = root.createNestedObject(FPSTR(_name)); top[FPSTR(_enabled)] = enabled; @@ -253,7 +253,7 @@ class MyExampleUsermod : public Usermod { * * This function is guaranteed to be called on boot, but could also be called every time settings are updated */ - bool readFromConfig(JsonObject& root) + bool readFromConfig(JsonObject& root) override { // default settings values could be set here (or below using the 3-argument getJsonValue()) instead of in the class definition or constructor // setting them inside readFromConfig() is slightly more robust, handling the rare but plausible use case of single value being missing after boot (e.g. if the cfg.json was manually edited and a value was removed) @@ -285,7 +285,7 @@ class MyExampleUsermod : public Usermod { * it may add additional metadata for certain entry fields (adding drop down is possible) * be careful not to add too much as oappend() buffer is limited to 3k */ - void appendConfigData() + void appendConfigData() override { oappend(SET_F("addInfo('")); oappend(String(FPSTR(_name)).c_str()); oappend(SET_F(":great")); oappend(SET_F("',1,'(this is a great config value)');")); oappend(SET_F("addInfo('")); oappend(String(FPSTR(_name)).c_str()); oappend(SET_F(":testString")); oappend(SET_F("',1,'enter any string you want');")); @@ -300,7 +300,7 @@ class MyExampleUsermod : public Usermod { * Use this to blank out some LEDs or set them to a different color regardless of the set effect mode. * Commonly used for custom clocks (Cronixie, 7 segment) */ - void handleOverlayDraw() + void handleOverlayDraw() override { //strip.setPixelColor(0, RGBW32(0,0,0,0)) // set the first pixel to black } @@ -311,7 +311,7 @@ class MyExampleUsermod : public Usermod { * will prevent button working in a default way. * Replicating button.cpp */ - bool handleButton(uint8_t b) { + bool handleButton(uint8_t b) override { yield(); // ignore certain button types as they may have other consequences if (!enabled @@ -334,7 +334,7 @@ class MyExampleUsermod : public Usermod { * handling of MQTT message * topic only contains stripped topic (part after /wled/MAC) */ - bool onMqttMessage(char* topic, char* payload) { + bool onMqttMessage(char* topic, char* payload) override { // check if we received a command //if (strlen(topic) == 8 && strncmp_P(topic, PSTR("/command"), 8) == 0) { // String action = payload; @@ -355,7 +355,7 @@ class MyExampleUsermod : public Usermod { /** * onMqttConnect() is called when MQTT connection is established */ - void onMqttConnect(bool sessionPresent) { + void onMqttConnect(bool sessionPresent) override { // do any MQTT related initialisation here //publishMqtt("I am alive!"); } @@ -366,7 +366,7 @@ class MyExampleUsermod : public Usermod { * onStateChanged() is used to detect WLED state change * @mode parameter is CALL_MODE_... parameter used for notifications */ - void onStateChange(uint8_t mode) { + void onStateChange(uint8_t mode) override { // do something if WLED state changed (color, brightness, effect, preset, etc) } @@ -375,7 +375,7 @@ class MyExampleUsermod : public Usermod { * getId() allows you to optionally give your V2 usermod an unique ID (please define it in const.h!). * This could be used in the future for the system to determine whether your usermod is installed. */ - uint16_t getId() + uint16_t getId() override { return USERMOD_ID_EXAMPLE; } diff --git a/usermods/PIR_sensor_switch/usermod_PIR_sensor_switch.h b/usermods/PIR_sensor_switch/usermod_PIR_sensor_switch.h index 62bf3d9df..2e909ae0e 100644 --- a/usermods/PIR_sensor_switch/usermod_PIR_sensor_switch.h +++ b/usermods/PIR_sensor_switch/usermod_PIR_sensor_switch.h @@ -50,8 +50,7 @@ private: volatile unsigned long offTimerStart = 0; // off timer start time volatile bool PIRtriggered = false; // did PIR trigger? - byte NotifyUpdateMode = CALL_MODE_NO_NOTIFY; // notification mode for stateUpdated(): CALL_MODE_NO_NOTIFY or CALL_MODE_DIRECT_CHANGE - byte sensorPinState = LOW; // current PIR sensor pin state + bool sensorPinState = LOW; // current PIR sensor pin state bool initDone = false; // status of initialization unsigned long lastLoop = 0; @@ -82,7 +81,6 @@ private: static const char _mqttOnly[]; static const char _offOnly[]; static const char _haDiscovery[]; - static const char _notify[]; static const char _override[]; static const char _domoticzIDX[]; @@ -96,7 +94,7 @@ private: * switch strip on/off */ void switchStrip(bool switchOn); - void publishMqtt(const char* state); + void publishMqtt(bool switchOn); // Create an MQTT Binary Sensor for Home Assistant Discovery purposes, this includes a pointer to the topic that is published to in the Loop. void publishHomeAssistantAutodiscovery(); @@ -119,7 +117,7 @@ public: * setup() is called once at boot. WiFi is not yet connected at this point. * You can use it to initialize variables, sensors or similar. */ - void setup(); + void setup() override; /** * connected() is called every time the WiFi is (re)connected @@ -130,24 +128,24 @@ public: /** * onMqttConnect() is called when MQTT connection is established */ - void onMqttConnect(bool sessionPresent); + void onMqttConnect(bool sessionPresent) override; /** * loop() is called continuously. Here you can check for events, read sensors, etc. */ - void loop(); + void loop() override; /** * addToJsonInfo() can be used to add custom entries to the /json/info part of the JSON API. * * Add PIR sensor state and switch off timer duration to jsoninfo */ - void addToJsonInfo(JsonObject &root); + void addToJsonInfo(JsonObject &root) override; /** * onStateChanged() is used to detect WLED state change */ - void onStateChange(uint8_t mode); + void onStateChange(uint8_t mode) override; /** * addToJsonState() can be used to add custom entries to the /json/state part of the JSON API (state object). @@ -159,17 +157,17 @@ public: * readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object). * Values in the state object may be modified by connected clients */ - void readFromJsonState(JsonObject &root); + void readFromJsonState(JsonObject &root) override; /** * provide the changeable values */ - void addToConfig(JsonObject &root); + void addToConfig(JsonObject &root) override; /** * provide UI information and allow extending UI options */ - void appendConfigData(); + void appendConfigData() override; /** * restore the changeable values @@ -177,13 +175,13 @@ public: * * The function should return true if configuration was successfully loaded or false if there was no configuration. */ - bool readFromConfig(JsonObject &root); + bool readFromConfig(JsonObject &root) override; /** * getId() allows you to optionally give your V2 usermod an unique ID (please define it in const.h!). * This could be used in the future for the system to determine whether your usermod is installed. */ - uint16_t getId() { return USERMOD_ID_PIRSWITCH; } + uint16_t getId() override { return USERMOD_ID_PIRSWITCH; } }; // strings to reduce flash memory usage (used more than twice) @@ -196,7 +194,6 @@ const char PIRsensorSwitch::_nightTime[] PROGMEM = "nighttime-only"; const char PIRsensorSwitch::_mqttOnly[] PROGMEM = "mqtt-only"; const char PIRsensorSwitch::_offOnly[] PROGMEM = "off-only"; const char PIRsensorSwitch::_haDiscovery[] PROGMEM = "HA-discovery"; -const char PIRsensorSwitch::_notify[] PROGMEM = "notifications"; const char PIRsensorSwitch::_override[] PROGMEM = "override"; const char PIRsensorSwitch::_domoticzIDX[] PROGMEM = "domoticz-idx"; @@ -238,24 +235,24 @@ void PIRsensorSwitch::switchStrip(bool switchOn) prevPlaylist = 0; prevPreset = 255; } - applyPreset(m_onPreset, NotifyUpdateMode); + applyPreset(m_onPreset, CALL_MODE_BUTTON_PRESET); return; } // preset not assigned if (bri == 0) { bri = briLast; - stateUpdated(NotifyUpdateMode); + stateUpdated(CALL_MODE_BUTTON); } } else { if (m_offPreset) { - applyPreset(m_offPreset, NotifyUpdateMode); + applyPreset(m_offPreset, CALL_MODE_BUTTON_PRESET); return; } else if (prevPlaylist) { - if (currentPreset==m_onPreset || currentPlaylist==m_onPreset) applyPreset(prevPlaylist, NotifyUpdateMode); + if (currentPreset==m_onPreset || currentPlaylist==m_onPreset) applyPreset(prevPlaylist, CALL_MODE_BUTTON_PRESET); prevPlaylist = 0; return; } else if (prevPreset) { - if (prevPreset<255) { if (currentPreset==m_onPreset || currentPlaylist==m_onPreset) applyPreset(prevPreset, NotifyUpdateMode); } + if (prevPreset<255) { if (currentPreset==m_onPreset || currentPlaylist==m_onPreset) applyPreset(prevPreset, CALL_MODE_BUTTON_PRESET); } else { if (currentPreset==m_onPreset || currentPlaylist==m_onPreset) applyTemporaryPreset(); } prevPreset = 0; return; @@ -264,28 +261,27 @@ void PIRsensorSwitch::switchStrip(bool switchOn) if (bri != 0) { briLast = bri; bri = 0; - stateUpdated(NotifyUpdateMode); + stateUpdated(CALL_MODE_BUTTON); } } } -void PIRsensorSwitch::publishMqtt(const char* state) +void PIRsensorSwitch::publishMqtt(bool switchOn) { #ifndef WLED_DISABLE_MQTT //Check if MQTT Connected, otherwise it will crash the 8266 if (WLED_MQTT_CONNECTED) { char buf[128]; sprintf_P(buf, PSTR("%s/motion"), mqttDeviceTopic); //max length: 33 + 7 = 40 - mqtt->publish(buf, 0, false, state); + mqtt->publish(buf, 0, false, switchOn?"on":"off"); // Domoticz formatted message if (idx > 0) { StaticJsonDocument <128> msg; msg[F("idx")] = idx; msg[F("RSSI")] = WiFi.RSSI(); msg[F("command")] = F("switchlight"); - strcpy(buf, state); buf[0] = toupper(buf[0]); - msg[F("switchcmd")] = (const char *)buf; - serializeJson(msg, buf, 127); + msg[F("switchcmd")] = switchOn ? F("On") : F("Off"); + serializeJson(msg, buf, 128); mqtt->publish("domoticz/in", 0, false, buf); } } @@ -336,13 +332,11 @@ bool PIRsensorSwitch::updatePIRsensorState() if (sensorPinState == HIGH) { offTimerStart = 0; if (!m_mqttOnly && (!m_nightTimeOnly || (m_nightTimeOnly && !isDayTime()))) switchStrip(true); - else if (NotifyUpdateMode != CALL_MODE_NO_NOTIFY) updateInterfaces(CALL_MODE_WS_SEND); - publishMqtt("on"); } else { // start switch off timer offTimerStart = millis(); - if (NotifyUpdateMode != CALL_MODE_NO_NOTIFY) updateInterfaces(CALL_MODE_WS_SEND); } + publishMqtt(sensorPinState == HIGH); return true; } return false; @@ -352,11 +346,7 @@ bool PIRsensorSwitch::handleOffTimer() { if (offTimerStart > 0 && millis() - offTimerStart > m_switchOffDelay) { offTimerStart = 0; - if (enabled == true) { - if (!m_mqttOnly && (!m_nightTimeOnly || (m_nightTimeOnly && !isDayTime()) || PIRtriggered)) switchStrip(false); - else if (NotifyUpdateMode != CALL_MODE_NO_NOTIFY) updateInterfaces(CALL_MODE_WS_SEND); - publishMqtt("off"); - } + if (!m_mqttOnly && (!m_nightTimeOnly || (m_nightTimeOnly && !isDayTime()) || PIRtriggered)) switchStrip(false); return true; } return false; @@ -497,14 +487,12 @@ void PIRsensorSwitch::addToConfig(JsonObject &root) top[FPSTR(_override)] = m_override; top[FPSTR(_haDiscovery)] = HomeAssistantDiscovery; top[FPSTR(_domoticzIDX)] = idx; - top[FPSTR(_notify)] = (NotifyUpdateMode != CALL_MODE_NO_NOTIFY); DEBUG_PRINTLN(F("PIR config saved.")); } void PIRsensorSwitch::appendConfigData() { oappend(SET_F("addInfo('PIRsensorSwitch:HA-discovery',1,'HA=Home Assistant');")); // 0 is field type, 1 is actual field - oappend(SET_F("addInfo('PIRsensorSwitch:notifications',1,'Periodic WS updates');")); // 0 is field type, 1 is actual field oappend(SET_F("addInfo('PIRsensorSwitch:override',1,'Cancel timer on change');")); // 0 is field type, 1 is actual field } @@ -538,8 +526,6 @@ bool PIRsensorSwitch::readFromConfig(JsonObject &root) HomeAssistantDiscovery = top[FPSTR(_haDiscovery)] | HomeAssistantDiscovery; idx = top[FPSTR(_domoticzIDX)] | idx; - NotifyUpdateMode = top[FPSTR(_notify)] ? CALL_MODE_DIRECT_CHANGE : CALL_MODE_NO_NOTIFY; - if (!initDone) { // reading config prior to setup() DEBUG_PRINTLN(F(" config loaded.")); diff --git a/usermods/PWM_fan/usermod_PWM_fan.h b/usermods/PWM_fan/usermod_PWM_fan.h index 05b6d9b3b..1b78cfd4c 100644 --- a/usermods/PWM_fan/usermod_PWM_fan.h +++ b/usermods/PWM_fan/usermod_PWM_fan.h @@ -188,7 +188,7 @@ class PWMFanUsermod : public Usermod { // gets called once at boot. Do all initialization that doesn't depend on // network here - void setup() { + void setup() override { #ifdef USERMOD_DALLASTEMPERATURE // This Usermod requires Temperature usermod tempUM = (UsermodTemperature*) usermods.lookup(USERMOD_ID_TEMPERATURE); @@ -203,12 +203,12 @@ class PWMFanUsermod : public Usermod { // gets called every time WiFi is (re-)connected. Initialize own network // interfaces here - void connected() {} + void connected() override {} /* * Da loop. */ - void loop() { + void loop() override { if (!enabled || strip.isUpdating()) return; unsigned long now = millis(); @@ -223,7 +223,7 @@ class PWMFanUsermod : public Usermod { * Creating an "u" object allows you to add custom key/value pairs to the Info section of the WLED web UI. * Below it is shown how this could be used for e.g. a light sensor */ - void addToJsonInfo(JsonObject& root) { + void addToJsonInfo(JsonObject& root) override { JsonObject user = root["u"]; if (user.isNull()) user = root.createNestedObject("u"); @@ -272,7 +272,7 @@ class PWMFanUsermod : public Usermod { * readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object). * Values in the state object may be modified by connected clients */ - void readFromJsonState(JsonObject& root) { + void readFromJsonState(JsonObject& root) override { if (!initDone) return; // prevent crash on boot applyPreset() JsonObject usermod = root[FPSTR(_name)]; if (!usermod.isNull()) { @@ -305,7 +305,7 @@ class PWMFanUsermod : public Usermod { * * I highly recommend checking out the basics of ArduinoJson serialization and deserialization in order to use custom settings! */ - void addToConfig(JsonObject& root) { + void addToConfig(JsonObject& root) override { JsonObject top = root.createNestedObject(FPSTR(_name)); // usermodname top[FPSTR(_enabled)] = enabled; top[FPSTR(_pwmPin)] = pwmPin; @@ -328,7 +328,7 @@ class PWMFanUsermod : public Usermod { * * The function should return true if configuration was successfully loaded or false if there was no configuration. */ - bool readFromConfig(JsonObject& root) { + bool readFromConfig(JsonObject& root) override { int8_t newTachoPin = tachoPin; int8_t newPwmPin = pwmPin; @@ -380,7 +380,7 @@ class PWMFanUsermod : public Usermod { * getId() allows you to optionally give your V2 usermod an unique ID (please define it in const.h!). * This could be used in the future for the system to determine whether your usermod is installed. */ - uint16_t getId() { + uint16_t getId() override { return USERMOD_ID_PWM_FAN; } }; diff --git a/usermods/ST7789_display/ST7789_display.h b/usermods/ST7789_display/ST7789_display.h index 144cccbfa..281fba25d 100644 --- a/usermods/ST7789_display/ST7789_display.h +++ b/usermods/ST7789_display/ST7789_display.h @@ -132,7 +132,7 @@ class St7789DisplayUsermod : public Usermod { * setup() is called once at boot. WiFi is not yet connected at this point. * You can use it to initialize variables, sensors or similar. */ - void setup() + void setup() override { PinManagerPinType spiPins[] = { { spi_mosi, true }, { spi_miso, false}, { spi_sclk, true } }; if (!pinManager.allocateMultiplePins(spiPins, 3, PinOwner::HW_SPI)) { enabled = false; return; } @@ -162,7 +162,7 @@ class St7789DisplayUsermod : public Usermod { * connected() is called every time the WiFi is (re)connected * Use it to initialize network interfaces */ - void connected() { + void connected() override { //Serial.println("Connected to WiFi!"); } @@ -176,7 +176,7 @@ class St7789DisplayUsermod : public Usermod { * 2. Try to avoid using the delay() function. NEVER use delays longer than 10 milliseconds. * Instead, use a timer check as shown here. */ - void loop() { + void loop() override { char buff[LINE_BUFFER_SIZE]; // Check if we time interval for redrawing passes. @@ -307,7 +307,7 @@ class St7789DisplayUsermod : public Usermod { // Print estimated milliamp usage (must specify the LED type in LED prefs for this to be a reasonable estimate). tft.print("Current: "); tft.setTextColor(TFT_ORANGE); - tft.print(strip.currentMilliamps); + tft.print(BusManager::currentMilliamps()); tft.print("mA"); } @@ -316,7 +316,7 @@ class St7789DisplayUsermod : public Usermod { * Creating an "u" object allows you to add custom key/value pairs to the Info section of the WLED web UI. * Below it is shown how this could be used for e.g. a light sensor */ - void addToJsonInfo(JsonObject& root) + void addToJsonInfo(JsonObject& root) override { JsonObject user = root["u"]; if (user.isNull()) user = root.createNestedObject("u"); @@ -330,7 +330,7 @@ class St7789DisplayUsermod : public Usermod { * addToJsonState() can be used to add custom entries to the /json/state part of the JSON API (state object). * Values in the state object may be modified by connected clients */ - void addToJsonState(JsonObject& root) + void addToJsonState(JsonObject& root) override { //root["user0"] = userVar0; } @@ -340,7 +340,7 @@ class St7789DisplayUsermod : public Usermod { * readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object). * Values in the state object may be modified by connected clients */ - void readFromJsonState(JsonObject& root) + void readFromJsonState(JsonObject& root) override { //userVar0 = root["user0"] | userVar0; //if "user0" key exists in JSON, update, else keep old value //if (root["bri"] == 255) Serial.println(F("Don't burn down your garage!")); @@ -361,7 +361,7 @@ class St7789DisplayUsermod : public Usermod { * * I highly recommend checking out the basics of ArduinoJson serialization and deserialization in order to use custom settings! */ - void addToConfig(JsonObject& root) + void addToConfig(JsonObject& root) override { JsonObject top = root.createNestedObject("ST7789"); JsonArray pins = top.createNestedArray("pin"); @@ -373,7 +373,7 @@ class St7789DisplayUsermod : public Usermod { } - void appendConfigData() { + void appendConfigData() override { oappend(SET_F("addInfo('ST7789:pin[]',0,'','SPI CS');")); oappend(SET_F("addInfo('ST7789:pin[]',1,'','SPI DC');")); oappend(SET_F("addInfo('ST7789:pin[]',2,'','SPI RST');")); @@ -388,7 +388,7 @@ class St7789DisplayUsermod : public Usermod { * but also that if you want to write persistent values to a dynamic buffer, you'd need to allocate it here instead of in setup. * If you don't know what that is, don't fret. It most likely doesn't affect your use case :) */ - bool readFromConfig(JsonObject& root) + bool readFromConfig(JsonObject& root) override { //JsonObject top = root["top"]; //userVar0 = top["great"] | 42; //The value right of the pipe "|" is the default value in case your setting was not present in cfg.json (e.g. first boot) @@ -400,7 +400,7 @@ class St7789DisplayUsermod : public Usermod { * getId() allows you to optionally give your V2 usermod an unique ID (please define it in const.h!). * This could be used in the future for the system to determine whether your usermod is installed. */ - uint16_t getId() + uint16_t getId() override { return USERMOD_ID_ST7789_DISPLAY; } diff --git a/usermods/Temperature/usermod_temperature.h b/usermods/Temperature/usermod_temperature.h index 0b9bbbda7..4d4f04368 100644 --- a/usermods/Temperature/usermod_temperature.h +++ b/usermods/Temperature/usermod_temperature.h @@ -76,26 +76,26 @@ class UsermodTemperature : public Usermod { inline float getTemperatureF() { return temperature * 1.8f + 32.0f; } float getTemperature(); const char *getTemperatureUnit(); - uint16_t getId() { return USERMOD_ID_TEMPERATURE; } + uint16_t getId() override { return USERMOD_ID_TEMPERATURE; } - void setup(); - void loop(); - //void connected(); + void setup() override; + void loop() override; + //void connected() override; #ifndef WLED_DISABLE_MQTT - void onMqttConnect(bool sessionPresent); + void onMqttConnect(bool sessionPresent) override; #endif - //void onUpdateBegin(bool init); + //void onUpdateBegin(bool init) override; - //bool handleButton(uint8_t b); - //void handleOverlayDraw(); + //bool handleButton(uint8_t b) override; + //void handleOverlayDraw() override; - void addToJsonInfo(JsonObject& root); - //void addToJsonState(JsonObject &root); - //void readFromJsonState(JsonObject &root); - void addToConfig(JsonObject &root); - bool readFromConfig(JsonObject &root); + void addToJsonInfo(JsonObject& root) override; + //void addToJsonState(JsonObject &root) override; + //void readFromJsonState(JsonObject &root) override; + void addToConfig(JsonObject &root) override; + bool readFromConfig(JsonObject &root) override; - void appendConfigData(); + void appendConfigData() override; }; //Dallas sensor quick (& dirty) reading. Credit to - Author: Peter Scargill, August 17th, 2013 @@ -283,7 +283,6 @@ void UsermodTemperature::loop() { msg[F("nvalue")] = 0; msg[F("svalue")] = String(getTemperatureC()); serializeJson(msg, subuf, 127); - DEBUG_PRINTLN(subuf); mqtt->publish("domoticz/in", 0, false, subuf); } } else { diff --git a/usermods/audioreactive/audio_reactive.h b/usermods/audioreactive/audio_reactive.h index 55fe0169d..50555ca54 100644 --- a/usermods/audioreactive/audio_reactive.h +++ b/usermods/audioreactive/audio_reactive.h @@ -1094,7 +1094,7 @@ class AudioReactive : public Usermod { * You can use it to initialize variables, sensors or similar. * It is called *AFTER* readFromConfig() */ - void setup() + void setup() override { disableSoundProcessing = true; // just to be sure if (!initDone) { @@ -1217,7 +1217,7 @@ class AudioReactive : public Usermod { * connected() is called every time the WiFi is (re)connected * Use it to initialize network interfaces */ - void connected() + void connected() override { if (udpSyncConnected) { // clean-up: if open, close old UDP sync connection udpSyncConnected = false; @@ -1244,7 +1244,7 @@ class AudioReactive : public Usermod { * 2. Try to avoid using the delay() function. NEVER use delays longer than 10 milliseconds. * Instead, use a timer check as shown here. */ - void loop() + void loop() override { static unsigned long lastUMRun = millis(); @@ -1375,7 +1375,7 @@ class AudioReactive : public Usermod { } - bool getUMData(um_data_t **data) + bool getUMData(um_data_t **data) override { if (!data || !enabled) return false; // no pointer provided by caller or not enabled -> exit *data = um_data; @@ -1383,7 +1383,7 @@ class AudioReactive : public Usermod { } - void onUpdateBegin(bool init) + void onUpdateBegin(bool init) override { #ifdef WLED_DEBUG fftTime = sampleTime = 0; @@ -1438,7 +1438,7 @@ class AudioReactive : public Usermod { * handleButton() can be used to override default button behaviour. Returning true * will prevent button working in a default way. */ - bool handleButton(uint8_t b) { + bool handleButton(uint8_t b) override { yield(); // crude way of determining if audio input is analog // better would be for AudioSource to implement getType() @@ -1461,7 +1461,7 @@ class AudioReactive : public Usermod { * Creating an "u" object allows you to add custom key/value pairs to the Info section of the WLED web UI. * Below it is shown how this could be used for e.g. a light sensor */ - void addToJsonInfo(JsonObject& root) + void addToJsonInfo(JsonObject& root) override { char myStringBuffer[16]; // buffer for snprintf() JsonObject user = root["u"]; @@ -1600,7 +1600,7 @@ class AudioReactive : public Usermod { * addToJsonState() can be used to add custom entries to the /json/state part of the JSON API (state object). * Values in the state object may be modified by connected clients */ - void addToJsonState(JsonObject& root) + void addToJsonState(JsonObject& root) override { if (!initDone) return; // prevent crash on boot applyPreset() JsonObject usermod = root[FPSTR(_name)]; @@ -1615,7 +1615,7 @@ class AudioReactive : public Usermod { * readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object). * Values in the state object may be modified by connected clients */ - void readFromJsonState(JsonObject& root) + void readFromJsonState(JsonObject& root) override { if (!initDone) return; // prevent crash on boot applyPreset() bool prevEnabled = enabled; @@ -1640,7 +1640,7 @@ class AudioReactive : public Usermod { } } - void onStateChange(uint8_t callMode) { + void onStateChange(uint8_t callMode) override { if (initDone && enabled && addPalettes && palettes==0 && strip.customPalettes.size()<10) { // if palettes were removed during JSON call re-add them createAudioPalettes(); @@ -1682,7 +1682,7 @@ class AudioReactive : public Usermod { * * I highly recommend checking out the basics of ArduinoJson serialization and deserialization in order to use custom settings! */ - void addToConfig(JsonObject& root) + void addToConfig(JsonObject& root) override { JsonObject top = root.createNestedObject(FPSTR(_name)); top[FPSTR(_enabled)] = enabled; @@ -1735,7 +1735,7 @@ class AudioReactive : public Usermod { * * This function is guaranteed to be called on boot, but could also be called every time settings are updated */ - bool readFromConfig(JsonObject& root) + bool readFromConfig(JsonObject& root) override { JsonObject top = root[FPSTR(_name)]; bool configComplete = !top.isNull(); @@ -1786,7 +1786,7 @@ class AudioReactive : public Usermod { } - void appendConfigData() + void appendConfigData() override { oappend(SET_F("dd=addDropdown('AudioReactive','digitalmic:type');")); #if !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3) && !defined(CONFIG_IDF_TARGET_ESP32S3) @@ -1841,7 +1841,7 @@ class AudioReactive : public Usermod { * Use this to blank out some LEDs or set them to a different color regardless of the set effect mode. * Commonly used for custom clocks (Cronixie, 7 segment) */ - //void handleOverlayDraw() + //void handleOverlayDraw() override //{ //strip.setPixelColor(0, RGBW32(0,0,0,0)) // set the first pixel to black //} @@ -1851,7 +1851,7 @@ class AudioReactive : public Usermod { * getId() allows you to optionally give your V2 usermod an unique ID (please define it in const.h!). * This could be used in the future for the system to determine whether your usermod is installed. */ - uint16_t getId() + uint16_t getId() override { return USERMOD_ID_AUDIOREACTIVE; } diff --git a/usermods/boblight/boblight.h b/usermods/boblight/boblight.h index a1e257758..55803a24d 100644 --- a/usermods/boblight/boblight.h +++ b/usermods/boblight/boblight.h @@ -187,7 +187,7 @@ class BobLightUsermod : public Usermod { public: - void setup() { + void setup() override { uint16_t totalLights = bottom + left + top + right; if ( totalLights > strip.getLengthTotal() ) { DEBUG_PRINTLN(F("BobLight: Too many lights.")); @@ -202,14 +202,14 @@ class BobLightUsermod : public Usermod { initDone = true; } - void connected() { + void connected() override { // we can only start server when WiFi is connected if (!bob) bob = new WiFiServer(bobPort, 1); bob->begin(); bob->setNoDelay(true); } - void loop() { + void loop() override { if (!enabled || strip.isUpdating()) return; if (millis() - lastTime > 10) { lastTime = millis(); @@ -225,7 +225,7 @@ class BobLightUsermod : public Usermod { * topic only contains stripped topic (part after /wled/MAC) * topic should look like: /swipe with amessage of [up|down] */ - bool onMqttMessage(char* topic, char* payload) { + bool onMqttMessage(char* topic, char* payload) override { //if (strlen(topic) == 6 && strncmp_P(topic, PSTR("/subtopic"), 6) == 0) { // String action = payload; // if (action == "on") { @@ -242,7 +242,7 @@ class BobLightUsermod : public Usermod { /** * subscribe to MQTT topic for controlling usermod */ - void onMqttConnect(bool sessionPresent) { + void onMqttConnect(bool sessionPresent) override { //char subuf[64]; //if (mqttDeviceTopic[0] != 0) { // strcpy(subuf, mqttDeviceTopic); @@ -252,7 +252,7 @@ class BobLightUsermod : public Usermod { } #endif - void addToJsonInfo(JsonObject& root) + void addToJsonInfo(JsonObject& root) override { JsonObject user = root["u"]; if (user.isNull()) user = root.createNestedObject("u"); @@ -273,7 +273,7 @@ class BobLightUsermod : public Usermod { * addToJsonState() can be used to add custom entries to the /json/state part of the JSON API (state object). * Values in the state object may be modified by connected clients */ - void addToJsonState(JsonObject& root) + void addToJsonState(JsonObject& root) override { } @@ -281,7 +281,7 @@ class BobLightUsermod : public Usermod { * readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object). * Values in the state object may be modified by connected clients */ - void readFromJsonState(JsonObject& root) { + void readFromJsonState(JsonObject& root) override { if (!initDone) return; // prevent crash on boot applyPreset() bool en = enabled; JsonObject um = root[FPSTR(_name)]; @@ -304,7 +304,7 @@ class BobLightUsermod : public Usermod { } } - void appendConfigData() { + void appendConfigData() override { //oappend(SET_F("dd=addDropdown('usermod','selectfield');")); //oappend(SET_F("addOption(dd,'1st value',0);")); //oappend(SET_F("addOption(dd,'2nd value',1);")); @@ -315,7 +315,7 @@ class BobLightUsermod : public Usermod { oappend(SET_F("addInfo('BobLight:pct',1,'Depth of scan [%]');")); // 0 is field type, 1 is actual field } - void addToConfig(JsonObject& root) { + void addToConfig(JsonObject& root) override { JsonObject umData = root.createNestedObject(FPSTR(_name)); umData[FPSTR(_enabled)] = enabled; umData[F("port")] = bobPort; @@ -326,7 +326,7 @@ class BobLightUsermod : public Usermod { umData[F("pct")] = pct; } - bool readFromConfig(JsonObject& root) { + bool readFromConfig(JsonObject& root) override { JsonObject umData = root[FPSTR(_name)]; bool configComplete = !umData.isNull(); @@ -355,11 +355,11 @@ class BobLightUsermod : public Usermod { * Use this to blank out some LEDs or set them to a different color regardless of the set effect mode. * Commonly used for custom clocks (Cronixie, 7 segment) */ - void handleOverlayDraw() { + void handleOverlayDraw() override { //strip.setPixelColor(0, RGBW32(0,0,0,0)) // set the first pixel to black } - uint16_t getId() { return USERMOD_ID_BOBLIGHT; } + uint16_t getId() override { return USERMOD_ID_BOBLIGHT; } }; @@ -445,7 +445,7 @@ void BobLightUsermod::pollBob() { //strip.setPixelColor(light_id, RGBW32(red, green, blue, 0)); setRealtimePixel(light_id, red, green, blue, 0); } // currently no support for interpolation or speed, we just ignore this - } else if (input.startsWith(F("sync"))) { + } else if (input.startsWith("sync")) { BobSync(); } else { // Client sent gibberish diff --git a/usermods/mpu6050_imu/readme.md b/usermods/mpu6050_imu/readme.md index 412004151..b804ba602 100644 --- a/usermods/mpu6050_imu/readme.md +++ b/usermods/mpu6050_imu/readme.md @@ -20,14 +20,11 @@ react to the globes orientation. See the blog post on building it + +constexpr auto ESTIMATED_G = 9.801; // m/s^2 +constexpr auto ESTIMATED_G_COUNTS = 8350.; +constexpr auto ESTIMATED_ANGULAR_RATE = (M_PI * 2000) / (INT16_MAX * 180); // radians per second + +// Horribly lame digital filter code +// Currently implements a static IIR filter. +template +class xir_filter { + typedef Eigen::Array array_t; + const array_t a_coeff, b_coeff; + const T gain; + array_t x, y; + + public: + xir_filter(T gain_, array_t a, array_t b) : a_coeff(std::move(a)), b_coeff(std::move(b)), gain(gain_), x(array_t::Zero()), y(array_t::Zero()) {}; + + T operator()(T input) { + x.head(C-1) = x.tail(C-1); // shift by one + x(C-1) = input / gain; + y.head(C-1) = y.tail(C-1); // shift by one + y(C-1) = (x * b_coeff).sum(); + y(C-1) -= (y.head(C-1) * a_coeff.head(C-1)).sum(); + return y(C-1); + } + + T last() { return y(C-1); }; +}; + + + +class GyroSurge : public Usermod { + private: + static const char _name[]; + bool enabled = true; + + // Params + uint8_t max = 0; + float sensitivity = 0; + + // State + uint32_t last_sample; + // 100hz input + // butterworth low pass filter at 20hz + xir_filter filter = { 1., { -0.36952738, 0.19581571, 1.}, {0.20657208, 0.41314417, 0.20657208} }; + // { 1., { 0., 0., 1.}, { 0., 0., 1. } }; // no filter + + + public: + + /* + * setup() is called once at boot. WiFi is not yet connected at this point. + */ + void setup() {}; + + + /* + * addToConfig() can be used to add custom persistent settings to the cfg.json file in the "um" (usermod) object. + * It will be called by WLED when settings are actually saved (for example, LED settings are saved) + * I highly recommend checking out the basics of ArduinoJson serialization and deserialization in order to use custom settings! + */ + void addToConfig(JsonObject& root) + { + JsonObject top = root.createNestedObject(FPSTR(_name)); + + //save these vars persistently whenever settings are saved + top["max"] = max; + top["sensitivity"] = sensitivity; + } + + + /* + * readFromConfig() can be used to read back the custom settings you added with addToConfig(). + * This is called by WLED when settings are loaded (currently this only happens immediately after boot, or after saving on the Usermod Settings page) + * + * readFromConfig() is called BEFORE setup(). This means you can use your persistent values in setup() (e.g. pin assignments, buffer sizes), + * but also that if you want to write persistent values to a dynamic buffer, you'd need to allocate it here instead of in setup. + * If you don't know what that is, don't fret. It most likely doesn't affect your use case :) + * + * Return true in case the config values returned from Usermod Settings were complete, or false if you'd like WLED to save your defaults to disk (so any missing values are editable in Usermod Settings) + * + * getJsonValue() returns false if the value is missing, or copies the value into the variable provided and returns true if the value is present + * The configComplete variable is true only if the "exampleUsermod" object and all values are present. If any values are missing, WLED will know to call addToConfig() to save them + * + * This function is guaranteed to be called on boot, but could also be called every time settings are updated + */ + bool readFromConfig(JsonObject& root) + { + // default settings values could be set here (or below using the 3-argument getJsonValue()) instead of in the class definition or constructor + // setting them inside readFromConfig() is slightly more robust, handling the rare but plausible use case of single value being missing after boot (e.g. if the cfg.json was manually edited and a value was removed) + + JsonObject top = root[FPSTR(_name)]; + + bool configComplete = !top.isNull(); + + configComplete &= getJsonValue(top["max"], max, 0); + configComplete &= getJsonValue(top["sensitivity"], sensitivity, 10); + + return configComplete; + } + + void loop() { + // get IMU data + um_data_t *um_data; + if (!usermods.getUMData(&um_data, USERMOD_ID_IMU)) { + // Apply max + strip.getSegment(0).fadeToBlackBy(max); + return; + } + uint32_t sample_count = *(uint32_t*)(um_data->u_data[8]); + + if (sample_count != last_sample) { + last_sample = sample_count; + // Calculate based on new data + // We use the raw gyro data (angular rate) + auto gyros = (int16_t*)um_data->u_data[4]; // 16384 == 2000 deg/s + + // Compute the overall rotation rate + // For my application (a plasma sword) we ignore X axis rotations (eg. around the long axis) + auto gyro_q = Eigen::AngleAxis { + //Eigen::AngleAxis(ESTIMATED_ANGULAR_RATE * gyros[0], Eigen::Vector3f::UnitX()) * + Eigen::AngleAxis(ESTIMATED_ANGULAR_RATE * gyros[1], Eigen::Vector3f::UnitY()) * + Eigen::AngleAxis(ESTIMATED_ANGULAR_RATE * gyros[2], Eigen::Vector3f::UnitZ()) }; + + // Filter the results + filter(std::min(sensitivity * gyro_q.angle(), 1.0f)); // radians per second +/* + Serial.printf("[%lu] Gy: %d, %d, %d -- ", millis(), (int)gyros[0], (int)gyros[1], (int)gyros[2]); + Serial.print(gyro_q.angle()); + Serial.print(", "); + Serial.print(sensitivity * gyro_q.angle()); + Serial.print(" --> "); + Serial.println(filter.last()); +*/ + } + }; // noop + + /* + * handleOverlayDraw() is called just before every show() (LED strip update frame) after effects have set the colors. + * Use this to blank out some LEDs or set them to a different color regardless of the set effect mode. + * Commonly used for custom clocks (Cronixie, 7 segment) + */ + void handleOverlayDraw() + { + + // TODO: some kind of timing analysis for filtering ... + + // Calculate brightness boost + auto r_float = std::max(std::min(filter.last(), 1.0f), 0.f); + auto result = (uint8_t) (r_float * max); + //Serial.printf("[%lu] %d -- ", millis(), result); + //Serial.println(r_float); + // TODO - multiple segment handling?? + strip.getSegment(0).fadeToBlackBy(max - result); + } +}; + +const char GyroSurge::_name[] PROGMEM = "GyroSurge"; \ No newline at end of file diff --git a/usermods/mpu6050_imu/usermod_mpu6050_imu.h b/usermods/mpu6050_imu/usermod_mpu6050_imu.h index 748ddf1a6..a3301bfff 100644 --- a/usermods/mpu6050_imu/usermod_mpu6050_imu.h +++ b/usermods/mpu6050_imu/usermod_mpu6050_imu.h @@ -20,11 +20,11 @@ XCL not connected AD0 not connected INT D8 (GPIO15) Interrupt pin - + Using usermod: 1. Copy the usermod into the sketch folder (same folder as wled00.ino) 2. Register the usermod by adding #include "usermod_filename.h" in the top and registerUsermod(new MyUsermodClass()) in the bottom of usermods_list.cpp - 3. I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h file + 3. I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h file for both classes must be in the include path of your project. To install the libraries add I2Cdevlib-MPU6050@fbde122cc5 to lib_deps in the platformio.ini file. 4. You also need to change lib_compat_mode from strict to soft in platformio.ini (This ignores that I2Cdevlib-MPU6050 doesn't list platform compatibility) @@ -33,6 +33,9 @@ #include "I2Cdev.h" +#undef DEBUG_PRINT +#undef DEBUG_PRINTLN +#undef DEBUG_PRINTF #include "MPU6050_6Axis_MotionApps20.h" //#include "MPU6050.h" // not necessary if using MotionApps include file @@ -42,6 +45,23 @@ #include "Wire.h" #endif +// Restore debug macros +// MPU6050 unfortunately uses the same macro names as WLED :( +#undef DEBUG_PRINT +#undef DEBUG_PRINTLN +#undef DEBUG_PRINTF +#ifdef WLED_DEBUG + #define DEBUG_PRINT(x) DEBUGOUT.print(x) + #define DEBUG_PRINTLN(x) DEBUGOUT.println(x) + #define DEBUG_PRINTF(x...) DEBUGOUT.printf(x) +#else + #define DEBUG_PRINT(x) + #define DEBUG_PRINTLN(x) + #define DEBUG_PRINTF(x...) +#endif + + + // ================================================================ // === INTERRUPT DETECTION ROUTINE === // ================================================================ @@ -52,21 +72,31 @@ void IRAM_ATTR dmpDataReady() { } + class MPU6050Driver : public Usermod { private: MPU6050 mpu; - bool enabled = true; + + // configuration state + // default values are set in readFromConfig + // By making this a struct, we enable easy backup and comparison in the readFromConfig class + struct config_t { + bool enabled; + int8_t interruptPin; + int16_t gyro_offset[3]; + int16_t accel_offset[3]; + }; + config_t config; // MPU control/status vars + bool irqBound = false; // set true if we have bound the IRQ pin bool dmpReady = false; // set true if DMP init was successful - uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU uint8_t devStatus; // return status after each device operation (0 = success, !0 = error) uint16_t packetSize; // expected DMP packet size (default is 42 bytes) uint16_t fifoCount; // count of all bytes currently in FIFO uint8_t fifoBuffer[64]; // FIFO storage buffer - //NOTE: some of these can be removed to save memory, processing time - // if the measurement isn't needed + // TODO: some of these can be removed to save memory, processing time if the measurement isn't needed Quaternion qat; // [w, x, y, z] quaternion container float euler[3]; // [psi, theta, phi] Euler angle container float ypr[3]; // [yaw, pitch, roll] yaw/pitch/roll container @@ -75,17 +105,67 @@ class MPU6050Driver : public Usermod { VectorInt16 aaReal; // [x, y, z] gravity-free accel sensor measurements VectorInt16 aaWorld; // [x, y, z] world-frame accel sensor measurements VectorFloat gravity; // [x, y, z] gravity vector + uint32 sample_count; - static const int INTERRUPT_PIN = 15; // use pin 15 on ESP8266 + // Usermod output + um_data_t um_data; + + // config element names as progmem strs + static const char _name[]; + static const char _enabled[]; + static const char _interrupt_pin[]; + static const char _x_acc_bias[]; + static const char _y_acc_bias[]; + static const char _z_acc_bias[]; + static const char _x_gyro_bias[]; + static const char _y_gyro_bias[]; + static const char _z_gyro_bias[]; public: - //Functions called by WLED + inline bool initDone() { return um_data.u_size != 0; }; // recycle this instead of storing an extra variable + + //Functions called by WLED /* * setup() is called once at boot. WiFi is not yet connected at this point. */ void setup() { - if (i2c_scl<0 || i2c_sda<0) { enabled = false; return; } + dmpReady = false; // Start clean + + // one time init + if (!initDone()) { + um_data.u_size = 9; + um_data.u_type = new um_types_t[um_data.u_size]; + um_data.u_data = new void*[um_data.u_size]; + um_data.u_data[0] = &qat; + um_data.u_type[0] = UMT_FLOAT_ARR; + um_data.u_data[1] = &euler; + um_data.u_type[1] = UMT_FLOAT_ARR; + um_data.u_data[2] = &ypr; + um_data.u_type[2] = UMT_FLOAT_ARR; + um_data.u_data[3] = &aa; + um_data.u_type[3] = UMT_INT16_ARR; + um_data.u_data[4] = &gy; + um_data.u_type[4] = UMT_INT16_ARR; + um_data.u_data[5] = &aaReal; + um_data.u_type[5] = UMT_INT16_ARR; + um_data.u_data[6] = &aaWorld; + um_data.u_type[6] = UMT_INT16_ARR; + um_data.u_data[7] = &gravity; + um_data.u_type[7] = UMT_FLOAT_ARR; + um_data.u_data[8] = &sample_count; + um_data.u_type[8] = UMT_UINT32; + } + + if (!config.enabled) return; + if (i2c_scl<0 || i2c_sda<0) { DEBUG_PRINTLN(F("MPU6050: I2C is no good.")); return; } + // Check the interrupt pin + if (config.interruptPin >= 0) { + irqBound = pinManager.allocatePin(config.interruptPin, false, PinOwner::UM_IMU); + if (!irqBound) { DEBUG_PRINTLN(F("MPU6050: IRQ pin already in use.")); return; } + pinMode(config.interruptPin, INPUT); + }; + #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE Wire.setClock(400000U); // 400kHz I2C clock. Comment this line if having compilation difficulties #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE @@ -95,7 +175,6 @@ class MPU6050Driver : public Usermod { // initialize device DEBUG_PRINTLN(F("Initializing I2C devices...")); mpu.initialize(); - pinMode(INTERRUPT_PIN, INPUT); // verify connection DEBUG_PRINTLN(F("Testing device connections...")); @@ -105,11 +184,16 @@ class MPU6050Driver : public Usermod { DEBUG_PRINTLN(F("Initializing DMP...")); devStatus = mpu.dmpInitialize(); - // supply your own gyro offsets here, scaled for min sensitivity - mpu.setXGyroOffset(220); - mpu.setYGyroOffset(76); - mpu.setZGyroOffset(-85); - mpu.setZAccelOffset(1788); // 1688 factory default for my test chip + // set offsets (from config) + mpu.setXGyroOffset(config.gyro_offset[0]); + mpu.setYGyroOffset(config.gyro_offset[1]); + mpu.setZGyroOffset(config.gyro_offset[2]); + mpu.setXAccelOffset(config.accel_offset[0]); + mpu.setYAccelOffset(config.accel_offset[1]); + mpu.setZAccelOffset(config.accel_offset[2]); + + // set sample rate + mpu.setRate(16); // ~100Hz // make sure it worked (returns 0 if so) if (devStatus == 0) { @@ -117,17 +201,19 @@ class MPU6050Driver : public Usermod { DEBUG_PRINTLN(F("Enabling DMP...")); mpu.setDMPEnabled(true); - // enable Arduino interrupt detection - DEBUG_PRINTLN(F("Enabling interrupt detection (Arduino external interrupt 0)...")); - attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING); - mpuIntStatus = mpu.getIntStatus(); - - // set our DMP Ready flag so the main loop() function knows it's okay to use it - DEBUG_PRINTLN(F("DMP ready! Waiting for first interrupt...")); - dmpReady = true; + mpuInterrupt = true; + if (irqBound) { + // enable Arduino interrupt detection + DEBUG_PRINTLN(F("Enabling interrupt detection (Arduino external interrupt 0)...")); + attachInterrupt(digitalPinToInterrupt(config.interruptPin), dmpDataReady, RISING); + } // get expected DMP packet size for later comparison packetSize = mpu.dmpGetFIFOPacketSize(); + + // set our DMP Ready flag so the main loop() function knows it's okay to use it + DEBUG_PRINTLN(F("DMP ready!")); + dmpReady = true; } else { // ERROR! // 1 = initial memory load failed @@ -137,6 +223,9 @@ class MPU6050Driver : public Usermod { DEBUG_PRINT(devStatus); DEBUG_PRINTLN(")"); } + + fifoCount = 0; + sample_count = 0; } /* @@ -153,28 +242,31 @@ class MPU6050Driver : public Usermod { */ void loop() { // if programming failed, don't try to do anything - if (!enabled || !dmpReady || strip.isUpdating()) return; + if (!config.enabled || !dmpReady || strip.isUpdating()) return; // wait for MPU interrupt or extra packet(s) available + // mpuInterrupt is fixed on if interrupt pin is disabled if (!mpuInterrupt && fifoCount < packetSize) return; // reset interrupt flag and get INT_STATUS byte - mpuInterrupt = false; - mpuIntStatus = mpu.getIntStatus(); - - // get current FIFO count + auto mpuIntStatus = mpu.getIntStatus(); + // Update current FIFO count fifoCount = mpu.getFIFOCount(); // check for overflow (this should never happen unless our code is too inefficient) if ((mpuIntStatus & 0x10) || fifoCount == 1024) { // reset so we can continue cleanly mpu.resetFIFO(); - DEBUG_PRINTLN(F("FIFO overflow!")); + DEBUG_PRINTLN(F("MPU6050: FIFO overflow!")); - // otherwise, check for DMP data ready interrupt (this should happen frequently) - } else if (mpuIntStatus & 0x02) { - // wait for correct available data length, should be a VERY short wait - while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount(); + // otherwise, check for data ready + } else if (fifoCount >= packetSize) { + // clear local interrupt pending status, if not polling + mpuInterrupt = !irqBound; + + // DEBUG_PRINT(F("MPU6050: Processing packet: ")); + // DEBUG_PRINT(fifoCount); + // DEBUG_PRINTLN(F(" bytes in FIFO")); // read a packet from FIFO mpu.getFIFOBytes(fifoBuffer, packetSize); @@ -183,7 +275,6 @@ class MPU6050Driver : public Usermod { // (this lets us immediately read more without waiting for an interrupt) fifoCount -= packetSize; - //NOTE: some of these can be removed to save memory, processing time // if the measurement isn't needed mpu.dmpGetQuaternion(&qat, fifoBuffer); @@ -194,87 +285,141 @@ class MPU6050Driver : public Usermod { mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity); mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &qat); mpu.dmpGetYawPitchRoll(ypr, &qat, &gravity); + ++sample_count; } } - - void addToJsonInfo(JsonObject& root) { - int reading = 20; - //this code adds "u":{"Light":[20," lux"]} to the info object JsonObject user = root["u"]; if (user.isNull()) user = root.createNestedObject("u"); - JsonObject imu_meas = user.createNestedObject("IMU"); - JsonArray quat_json = imu_meas.createNestedArray("Quat"); + // Unfortunately the web UI doesn't know how to print sub-objects: you just see '[object Object]' + // For now, we just put everything in the root userdata object. + //auto imu_meas = user.createNestedObject("IMU"); + auto& imu_meas = user; + + // If an element is an array, the UI expects two elements in the form [value, unit] + // Since our /value/ is an array, wrap it, eg. [[a, b, c]] + JsonArray quat_json = imu_meas.createNestedArray("Quat").createNestedArray(); quat_json.add(qat.w); quat_json.add(qat.x); quat_json.add(qat.y); quat_json.add(qat.z); - JsonArray euler_json = imu_meas.createNestedArray("Euler"); + JsonArray euler_json = imu_meas.createNestedArray("Euler").createNestedArray(); euler_json.add(euler[0]); euler_json.add(euler[1]); euler_json.add(euler[2]); - JsonArray accel_json = imu_meas.createNestedArray("Accel"); + JsonArray accel_json = imu_meas.createNestedArray("Accel").createNestedArray(); accel_json.add(aa.x); accel_json.add(aa.y); accel_json.add(aa.z); - JsonArray gyro_json = imu_meas.createNestedArray("Gyro"); + JsonArray gyro_json = imu_meas.createNestedArray("Gyro").createNestedArray(); gyro_json.add(gy.x); gyro_json.add(gy.y); gyro_json.add(gy.z); - JsonArray world_json = imu_meas.createNestedArray("WorldAccel"); + JsonArray world_json = imu_meas.createNestedArray("WorldAccel").createNestedArray(); world_json.add(aaWorld.x); world_json.add(aaWorld.y); world_json.add(aaWorld.z); - JsonArray real_json = imu_meas.createNestedArray("RealAccel"); + JsonArray real_json = imu_meas.createNestedArray("RealAccel").createNestedArray(); real_json.add(aaReal.x); real_json.add(aaReal.y); real_json.add(aaReal.z); - JsonArray grav_json = imu_meas.createNestedArray("Gravity"); + JsonArray grav_json = imu_meas.createNestedArray("Gravity").createNestedArray(); grav_json.add(gravity.x); grav_json.add(gravity.y); grav_json.add(gravity.z); - JsonArray orient_json = imu_meas.createNestedArray("Orientation"); + JsonArray orient_json = imu_meas.createNestedArray("Orientation").createNestedArray(); orient_json.add(ypr[0]); orient_json.add(ypr[1]); orient_json.add(ypr[2]); } - /* - * addToJsonState() can be used to add custom entries to the /json/state part of the JSON API (state object). - * Values in the state object may be modified by connected clients - */ - //void addToJsonState(JsonObject& root) - //{ - //root["user0"] = userVar0; - //} - - - /* - * readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object). - * Values in the state object may be modified by connected clients - */ - //void readFromJsonState(JsonObject& root) - //{ - //if (root["bri"] == 255) DEBUG_PRINTLN(F("Don't burn down your garage!")); - //} - - /* * addToConfig() can be used to add custom persistent settings to the cfg.json file in the "um" (usermod) object. * It will be called by WLED when settings are actually saved (for example, LED settings are saved) * I highly recommend checking out the basics of ArduinoJson serialization and deserialization in order to use custom settings! */ -// void addToConfig(JsonObject& root) -// { -// JsonObject top = root.createNestedObject("MPU6050_IMU"); -// JsonArray pins = top.createNestedArray("pin"); -// pins.add(HW_PIN_SCL); -// pins.add(HW_PIN_SDA); -// } + void addToConfig(JsonObject& root) + { + JsonObject top = root.createNestedObject(FPSTR(_name)); + + //save these vars persistently whenever settings are saved + top[FPSTR(_enabled)] = config.enabled; + top[FPSTR(_interrupt_pin)] = config.interruptPin; + top[FPSTR(_x_acc_bias)] = config.accel_offset[0]; + top[FPSTR(_y_acc_bias)] = config.accel_offset[1]; + top[FPSTR(_z_acc_bias)] = config.accel_offset[2]; + top[FPSTR(_x_gyro_bias)] = config.gyro_offset[0]; + top[FPSTR(_y_gyro_bias)] = config.gyro_offset[1]; + top[FPSTR(_z_gyro_bias)] = config.gyro_offset[2]; + } + + /* + * readFromConfig() can be used to read back the custom settings you added with addToConfig(). + * This is called by WLED when settings are loaded (currently this only happens immediately after boot, or after saving on the Usermod Settings page) + * + * readFromConfig() is called BEFORE setup(). This means you can use your persistent values in setup() (e.g. pin assignments, buffer sizes), + * but also that if you want to write persistent values to a dynamic buffer, you'd need to allocate it here instead of in setup. + * If you don't know what that is, don't fret. It most likely doesn't affect your use case :) + * + * Return true in case the config values returned from Usermod Settings were complete, or false if you'd like WLED to save your defaults to disk (so any missing values are editable in Usermod Settings) + * + * getJsonValue() returns false if the value is missing, or copies the value into the variable provided and returns true if the value is present + * The configComplete variable is true only if the "exampleUsermod" object and all values are present. If any values are missing, WLED will know to call addToConfig() to save them + * + * This function is guaranteed to be called on boot, but could also be called every time settings are updated + */ + bool readFromConfig(JsonObject& root) + { + // default settings values could be set here (or below using the 3-argument getJsonValue()) instead of in the class definition or constructor + // setting them inside readFromConfig() is slightly more robust, handling the rare but plausible use case of single value being missing after boot (e.g. if the cfg.json was manually edited and a value was removed) + auto old_cfg = config; + + JsonObject top = root[FPSTR(_name)]; + + bool configComplete = top.isNull(); + // Ensure default configuration is loaded + configComplete &= getJsonValue(top[FPSTR(_enabled)], config.enabled, true); + configComplete &= getJsonValue(top[FPSTR(_interrupt_pin)], config.interruptPin, -1); + configComplete &= getJsonValue(top[FPSTR(_x_acc_bias)], config.accel_offset[0], 0); + configComplete &= getJsonValue(top[FPSTR(_y_acc_bias)], config.accel_offset[1], 0); + configComplete &= getJsonValue(top[FPSTR(_z_acc_bias)], config.accel_offset[2], 0); + configComplete &= getJsonValue(top[FPSTR(_x_gyro_bias)], config.gyro_offset[0], 0); + configComplete &= getJsonValue(top[FPSTR(_y_gyro_bias)], config.gyro_offset[1], 0); + configComplete &= getJsonValue(top[FPSTR(_z_gyro_bias)], config.gyro_offset[2], 0); + + DEBUG_PRINT(FPSTR(_name)); + if (top.isNull()) { + DEBUG_PRINTLN(F(": No config found. (Using defaults.)")); + } else if (!initDone()) { + DEBUG_PRINTLN(F(": config loaded.")); + } else if (memcmp(&config, &old_cfg, sizeof(config)) == 0) { + DEBUG_PRINTLN(F(": config unchanged.")); + } else { + DEBUG_PRINTLN(F(": config updated.")); + // Previously loaded and config changed + if (irqBound && ((old_cfg.interruptPin != config.interruptPin) || !config.enabled)) { + detachInterrupt(old_cfg.interruptPin); + pinManager.deallocatePin(old_cfg.interruptPin, PinOwner::UM_IMU); + irqBound = false; + } + + // Just re-init + setup(); + } + + return configComplete; + } + + bool getUMData(um_data_t **data) + { + if (!data || !config.enabled || !dmpReady) return false; // no pointer provided by caller or not enabled -> exit + *data = &um_data; + return true; + } /* * getId() allows you to optionally give your V2 usermod an unique ID (please define it in const.h!). @@ -285,3 +430,14 @@ class MPU6050Driver : public Usermod { } }; + + +const char MPU6050Driver::_name[] PROGMEM = "MPU6050_IMU"; +const char MPU6050Driver::_enabled[] PROGMEM = "enabled"; +const char MPU6050Driver::_interrupt_pin[] PROGMEM = "interrupt_pin"; +const char MPU6050Driver::_x_acc_bias[] PROGMEM = "x_acc_bias"; +const char MPU6050Driver::_y_acc_bias[] PROGMEM = "y_acc_bias"; +const char MPU6050Driver::_z_acc_bias[] PROGMEM = "z_acc_bias"; +const char MPU6050Driver::_x_gyro_bias[] PROGMEM = "x_gyro_bias"; +const char MPU6050Driver::_y_gyro_bias[] PROGMEM = "y_gyro_bias"; +const char MPU6050Driver::_z_gyro_bias[] PROGMEM = "z_gyro_bias"; diff --git a/usermods/multi_relay/usermod_multi_relay.h b/usermods/multi_relay/usermod_multi_relay.h index 7c8456f0e..22fa6496d 100644 --- a/usermods/multi_relay/usermod_multi_relay.h +++ b/usermods/multi_relay/usermod_multi_relay.h @@ -143,7 +143,7 @@ class MultiRelay : public Usermod { * getId() allows you to optionally give your V2 usermod an unique ID (please define it in const.h!). * This could be used in the future for the system to determine whether your usermod is installed. */ - inline uint16_t getId() { return USERMOD_ID_MULTI_RELAY; } + inline uint16_t getId() override { return USERMOD_ID_MULTI_RELAY; } /** * switch relay on/off @@ -161,22 +161,22 @@ class MultiRelay : public Usermod { * setup() is called once at boot. WiFi is not yet connected at this point. * You can use it to initialize variables, sensors or similar. */ - void setup(); + void setup() override; /** * connected() is called every time the WiFi is (re)connected * Use it to initialize network interfaces */ - inline void connected() { InitHtmlAPIHandle(); } + inline void connected() override { InitHtmlAPIHandle(); } /** * loop() is called continuously. Here you can check for events, read sensors, etc. */ - void loop(); + void loop() override; #ifndef WLED_DISABLE_MQTT - bool onMqttMessage(char* topic, char* payload); - void onMqttConnect(bool sessionPresent); + bool onMqttMessage(char* topic, char* payload) override; + void onMqttConnect(bool sessionPresent) override; #endif /** @@ -184,31 +184,31 @@ class MultiRelay : public Usermod { * will prevent button working in a default way. * Replicating button.cpp */ - bool handleButton(uint8_t b); + bool handleButton(uint8_t b) override; /** * addToJsonInfo() can be used to add custom entries to the /json/info part of the JSON API. */ - void addToJsonInfo(JsonObject &root); + void addToJsonInfo(JsonObject &root) override; /** * addToJsonState() can be used to add custom entries to the /json/state part of the JSON API (state object). * Values in the state object may be modified by connected clients */ - void addToJsonState(JsonObject &root); + void addToJsonState(JsonObject &root) override; /** * readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object). * Values in the state object may be modified by connected clients */ - void readFromJsonState(JsonObject &root); + void readFromJsonState(JsonObject &root) override; /** * provide the changeable values */ - void addToConfig(JsonObject &root); + void addToConfig(JsonObject &root) override; - void appendConfigData(); + void appendConfigData() override; /** * restore the changeable values @@ -216,7 +216,7 @@ class MultiRelay : public Usermod { * * The function should return true if configuration was successfully loaded or false if there was no configuration. */ - bool readFromConfig(JsonObject &root); + bool readFromConfig(JsonObject &root) override; }; @@ -534,10 +534,10 @@ void MultiRelay::setup() { * loop() is called continuously. Here you can check for events, read sensors, etc. */ void MultiRelay::loop() { - yield(); - if (!enabled || strip.isUpdating()) return; - static unsigned long lastUpdate = 0; + yield(); + if (!enabled || (strip.isUpdating() && millis() - lastUpdate < 100)) return; + if (millis() - lastUpdate < 100) return; // update only 10 times/s lastUpdate = millis(); diff --git a/usermods/quinled-an-penta/quinled-an-penta.h b/usermods/quinled-an-penta/quinled-an-penta.h index 5153ee58a..10b784334 100644 --- a/usermods/quinled-an-penta/quinled-an-penta.h +++ b/usermods/quinled-an-penta/quinled-an-penta.h @@ -84,11 +84,11 @@ class QuinLEDAnPentaUsermod : public Usermod void getCurrentUsedLedPins() { for (int8_t lp = 0; lp <= 4; lp++) currentLedPins[lp] = 0; - byte numBusses = busses.getNumBusses(); + byte numBusses = BusManager::getNumBusses(); byte numUsedPins = 0; for (int8_t b = 0; b < numBusses; b++) { - Bus* curBus = busses.getBus(b); + Bus* curBus = BusManager::getBus(b); if (curBus != nullptr) { uint8_t pins[5] = {0, 0, 0, 0, 0}; currentBussesNumPins[b] = curBus->getPins(pins); @@ -104,11 +104,11 @@ class QuinLEDAnPentaUsermod : public Usermod void getCurrentLedcValues() { - byte numBusses = busses.getNumBusses(); + byte numBusses = BusManager::getNumBusses(); byte numLedc = 0; for (int8_t b = 0; b < numBusses; b++) { - Bus* curBus = busses.getBus(b); + Bus* curBus = BusManager::getBus(b); if (curBus != nullptr) { uint32_t curPixColor = curBus->getPixelColor(0); uint8_t _data[5] = {255, 255, 255, 255, 255}; diff --git a/usermods/usermod_v2_animartrix/readme.md b/usermods/usermod_v2_animartrix/readme.md new file mode 100644 index 000000000..42d463c50 --- /dev/null +++ b/usermods/usermod_v2_animartrix/readme.md @@ -0,0 +1,14 @@ +# ANIMartRIX + +Addes the effects from ANIMartRIX to WLED + +CC BY-NC 3.0 licensed effects by Stefan Petrick, include this usermod only if you accept the terms! + +## Installation + +Please uncomment the two references to ANIMartRIX in your platform.ini + +lib_dep to a version of https://github.com/netmindz/animartrix.git +and the build_flags -D USERMOD_ANIMARTRIX + + diff --git a/usermods/usermod_v2_animartrix/usermod_v2_animartrix.h b/usermods/usermod_v2_animartrix/usermod_v2_animartrix.h new file mode 100644 index 000000000..d91cf6c96 --- /dev/null +++ b/usermods/usermod_v2_animartrix/usermod_v2_animartrix.h @@ -0,0 +1,456 @@ +#pragma once + +#include "wled.h" +#include + +#warning WLED usermod: CC BY-NC 3.0 licensed effects by Stefan Petrick, include this usermod only if you accept the terms! +//======================================================================================================================== + + +static const char _data_FX_mode_Module_Experiment10[] PROGMEM = "Z💡Module_Experiment10@Speed;;1;2"; +static const char _data_FX_mode_Module_Experiment9[] PROGMEM = "Z💡Module_Experiment9@Speed;;1;2"; +static const char _data_FX_mode_Module_Experiment8[] PROGMEM = "Z💡Module_Experiment8@Speed;;1;2"; +static const char _data_FX_mode_Module_Experiment7[] PROGMEM = "Z💡Module_Experiment7@Speed;;1;2"; +static const char _data_FX_mode_Module_Experiment6[] PROGMEM = "Z💡Module_Experiment6@Speed;;1;2"; +static const char _data_FX_mode_Module_Experiment5[] PROGMEM = "Z💡Module_Experiment5@Speed;;1;2"; +static const char _data_FX_mode_Module_Experiment4[] PROGMEM = "Z💡Module_Experiment4@Speed;;1;2"; +static const char _data_FX_mode_Zoom2[] PROGMEM = "Z💡Zoom2@Speed;;1;2"; +static const char _data_FX_mode_Module_Experiment3[] PROGMEM = "Z💡Module_Experiment3@Speed;;1;2"; +static const char _data_FX_mode_Module_Experiment2[] PROGMEM = "Z💡Module_Experiment2@Speed;;1;2"; +static const char _data_FX_mode_Module_Experiment1[] PROGMEM = "Z💡Module_Experiment1@Speed;;1;2"; +static const char _data_FX_mode_Parametric_Water[] PROGMEM = "Z💡Parametric_Water@Speed;;1;2"; +static const char _data_FX_mode_Water[] PROGMEM = "Z💡Water@Speed;;1;2"; +static const char _data_FX_mode_Complex_Kaleido_6[] PROGMEM = "Z💡Complex_Kaleido_6@Speed;;1;2"; +static const char _data_FX_mode_Complex_Kaleido_5[] PROGMEM = "Z💡Complex_Kaleido_5@Speed;;1;2"; +static const char _data_FX_mode_Complex_Kaleido_4[] PROGMEM = "Z💡Complex_Kaleido_4@Speed;;1;2"; +static const char _data_FX_mode_Complex_Kaleido_3[] PROGMEM = "Z💡Complex_Kaleido_3@Speed;;1;2"; +static const char _data_FX_mode_Complex_Kaleido_2[] PROGMEM = "Z💡Complex_Kaleido_2@Speed;;1;2"; +static const char _data_FX_mode_Complex_Kaleido[] PROGMEM = "Z💡Complex_Kaleido@Speed;;1;2"; +static const char _data_FX_mode_SM10[] PROGMEM = "Z💡SM10@Speed;;1;2"; +static const char _data_FX_mode_SM9[] PROGMEM = "Z💡SM9@Speed;;1;2"; +static const char _data_FX_mode_SM8[] PROGMEM = "Z💡SM8@Speed;;1;2"; +static const char _data_FX_mode_SM7[] PROGMEM = "Z💡SM7@Speed;;1;2"; +static const char _data_FX_mode_SM6[] PROGMEM = "Z💡SM6@Speed;;1;2"; +static const char _data_FX_mode_SM5[] PROGMEM = "Z💡SM5@Speed;;1;2"; +static const char _data_FX_mode_SM4[] PROGMEM = "Z💡SM4@Speed;;1;2"; +static const char _data_FX_mode_SM3[] PROGMEM = "Z💡SM3@Speed;;1;2"; +static const char _data_FX_mode_SM2[] PROGMEM = "Z💡SM2@Speed;;1;2"; +static const char _data_FX_mode_SM1[] PROGMEM = "Z💡SM1@Speed;;1;2"; +static const char _data_FX_mode_Big_Caleido[] PROGMEM = "Z💡Big_Caleido@Speed;;1;2"; +static const char _data_FX_mode_RGB_Blobs5[] PROGMEM = "Z💡RGB_Blobs5@Speed;;1;2"; +static const char _data_FX_mode_RGB_Blobs4[] PROGMEM = "Z💡RGB_Blobs4@Speed;;1;2"; +static const char _data_FX_mode_RGB_Blobs3[] PROGMEM = "Z💡RGB_Blobs3@Speed;;1;2"; +static const char _data_FX_mode_RGB_Blobs2[] PROGMEM = "Z💡RGB_Blobs2@Speed;;1;2"; +static const char _data_FX_mode_RGB_Blobs[] PROGMEM = "Z💡RGB_Blobs@Speed;;1;2"; +static const char _data_FX_mode_Polar_Waves[] PROGMEM = "Z💡Polar_Waves@Speed;;1;2"; +static const char _data_FX_mode_Slow_Fade[] PROGMEM = "Z💡Slow_Fade@Speed;;1;2"; +static const char _data_FX_mode_Zoom[] PROGMEM = "Z💡Zoom@Speed;;1;2"; +static const char _data_FX_mode_Hot_Blob[] PROGMEM = "Z💡Hot_Blob@Speed;;1;2"; +static const char _data_FX_mode_Spiralus2[] PROGMEM = "Z💡Spiralus2@Speed;;1;2"; +static const char _data_FX_mode_Spiralus[] PROGMEM = "Z💡Spiralus@Speed;;1;2"; +static const char _data_FX_mode_Yves[] PROGMEM = "Z💡Yves@Speed;;1;2"; +static const char _data_FX_mode_Scaledemo1[] PROGMEM = "Z💡Scaledemo1@Speed;;1;2"; +static const char _data_FX_mode_Lava1[] PROGMEM = "Z💡Lava1@Speed;;1;2"; +static const char _data_FX_mode_Caleido3[] PROGMEM = "Z💡Caleido3@Speed;;1;2"; +static const char _data_FX_mode_Caleido2[] PROGMEM = "Z💡Caleido2@Speed;;1;2"; +static const char _data_FX_mode_Caleido1[] PROGMEM = "Z💡Caleido1@Speed;;1;2"; +static const char _data_FX_mode_Distance_Experiment[] PROGMEM = "Z💡Distance_Experiment@Speed;;1;2"; +static const char _data_FX_mode_Center_Field[] PROGMEM = "Z💡Center_Field@Speed;;1;2"; +static const char _data_FX_mode_Waves[] PROGMEM = "Z💡Waves@Speed;;1;2"; +static const char _data_FX_mode_Chasing_Spirals[] PROGMEM = "Z💡Chasing_Spirals@Speed;;1;2"; +static const char _data_FX_mode_Rotating_Blob[] PROGMEM = "Z💡Rotating_Blob@Speed;;1;2"; + + +class ANIMartRIXMod:public ANIMartRIX { + public: + void initEffect() { + if (SEGENV.call == 0) { + init(SEGMENT.virtualWidth(), SEGMENT.virtualHeight(), false); + } + float speedFactor = 1.0; + if (SEGMENT.speed < 128) { + speedFactor = (float) map(SEGMENT.speed, 0, 127, 1, 10) / 10.0f; + } + else{ + speedFactor = map(SEGMENT.speed, 128, 255, 10, 100) / 10; + } + setSpeedFactor(speedFactor); + } + void setPixelColor(int x, int y, rgb pixel) { + SEGMENT.setPixelColorXY(x, y, CRGB(pixel.red, pixel.green, pixel.blue)); + } + void setPixelColor(int index, rgb pixel) { + SEGMENT.setPixelColor(index, CRGB(pixel.red, pixel.green, pixel.blue)); + } + + // Add any extra custom effects not part of the ANIMartRIX libary here +}; +ANIMartRIXMod anim; + +uint16_t mode_Module_Experiment10() { + anim.initEffect(); + anim.Module_Experiment10(); + return FRAMETIME; +} +uint16_t mode_Module_Experiment9() { + anim.initEffect(); + anim.Module_Experiment9(); + return FRAMETIME; +} +uint16_t mode_Module_Experiment8() { + anim.initEffect(); + anim.Module_Experiment8(); + return FRAMETIME; +} +uint16_t mode_Module_Experiment7() { + anim.initEffect(); + anim.Module_Experiment7(); + return FRAMETIME; +} +uint16_t mode_Module_Experiment6() { + anim.initEffect(); + anim.Module_Experiment6(); + return FRAMETIME; +} +uint16_t mode_Module_Experiment5() { + anim.initEffect(); + anim.Module_Experiment5(); + return FRAMETIME; +} +uint16_t mode_Module_Experiment4() { + anim.initEffect(); + anim.Module_Experiment4(); + return FRAMETIME; +} +uint16_t mode_Zoom2() { + anim.initEffect(); + anim.Zoom2(); + return FRAMETIME; +} +uint16_t mode_Module_Experiment3() { + anim.initEffect(); + anim.Module_Experiment3(); + return FRAMETIME; +} +uint16_t mode_Module_Experiment2() { + anim.initEffect(); + anim.Module_Experiment2(); + return FRAMETIME; +} +uint16_t mode_Module_Experiment1() { + anim.initEffect(); + anim.Module_Experiment1(); + return FRAMETIME; +} +uint16_t mode_Parametric_Water() { + anim.initEffect(); + anim.Parametric_Water(); + return FRAMETIME; +} +uint16_t mode_Water() { + anim.initEffect(); + anim.Water(); + return FRAMETIME; +} +uint16_t mode_Complex_Kaleido_6() { + anim.initEffect(); + anim.Complex_Kaleido_6(); + return FRAMETIME; +} +uint16_t mode_Complex_Kaleido_5() { + anim.initEffect(); + anim.Complex_Kaleido_5(); + return FRAMETIME; +} +uint16_t mode_Complex_Kaleido_4() { + anim.initEffect(); + anim.Complex_Kaleido_4(); + return FRAMETIME; +} +uint16_t mode_Complex_Kaleido_3() { + anim.initEffect(); + anim.Complex_Kaleido_3(); + return FRAMETIME; +} +uint16_t mode_Complex_Kaleido_2() { + anim.initEffect(); + anim.Complex_Kaleido_2(); + return FRAMETIME; +} +uint16_t mode_Complex_Kaleido() { + anim.initEffect(); + anim.Complex_Kaleido(); + return FRAMETIME; +} +uint16_t mode_SM10() { + anim.initEffect(); + anim.SM10(); + return FRAMETIME; +} +uint16_t mode_SM9() { + anim.initEffect(); + anim.SM9(); + return FRAMETIME; +} +uint16_t mode_SM8() { + anim.initEffect(); + anim.SM8(); + return FRAMETIME; +} +// uint16_t mode_SM7() { +// anim.initEffect(); +// anim.SM7(); +// +// return FRAMETIME; +// } +uint16_t mode_SM6() { + anim.initEffect(); + anim.SM6(); + return FRAMETIME; +} +uint16_t mode_SM5() { + anim.initEffect(); + anim.SM5(); + return FRAMETIME; +} +uint16_t mode_SM4() { + anim.initEffect(); + anim.SM4(); + return FRAMETIME; +} +uint16_t mode_SM3() { + anim.initEffect(); + anim.SM3(); + return FRAMETIME; +} +uint16_t mode_SM2() { + anim.initEffect(); + anim.SM2(); + return FRAMETIME; +} +uint16_t mode_SM1() { + anim.initEffect(); + anim.SM1(); + return FRAMETIME; +} +uint16_t mode_Big_Caleido() { + anim.initEffect(); + anim.Big_Caleido(); + return FRAMETIME; +} +uint16_t mode_RGB_Blobs5() { + anim.initEffect(); + anim.RGB_Blobs5(); + return FRAMETIME; +} +uint16_t mode_RGB_Blobs4() { + anim.initEffect(); + anim.RGB_Blobs4(); + return FRAMETIME; +} +uint16_t mode_RGB_Blobs3() { + anim.initEffect(); + anim.RGB_Blobs3(); + return FRAMETIME; +} +uint16_t mode_RGB_Blobs2() { + anim.initEffect(); + anim.RGB_Blobs2(); + return FRAMETIME; +} +uint16_t mode_RGB_Blobs() { + anim.initEffect(); + anim.RGB_Blobs(); + return FRAMETIME; +} +uint16_t mode_Polar_Waves() { + anim.initEffect(); + anim.Polar_Waves(); + return FRAMETIME; +} +uint16_t mode_Slow_Fade() { + anim.initEffect(); + anim.Slow_Fade(); + return FRAMETIME; +} +uint16_t mode_Zoom() { + anim.initEffect(); + anim.Zoom(); + return FRAMETIME; +} +uint16_t mode_Hot_Blob() { + anim.initEffect(); + anim.Hot_Blob(); + return FRAMETIME; +} +uint16_t mode_Spiralus2() { + anim.initEffect(); + anim.Spiralus2(); + return FRAMETIME; +} +uint16_t mode_Spiralus() { + anim.initEffect(); + anim.Spiralus(); + return FRAMETIME; +} +uint16_t mode_Yves() { + anim.initEffect(); + anim.Yves(); + return FRAMETIME; +} +uint16_t mode_Scaledemo1() { + anim.initEffect(); + anim.Scaledemo1(); + return FRAMETIME; +} +uint16_t mode_Lava1() { + anim.initEffect(); + anim.Lava1(); + return FRAMETIME; +} +uint16_t mode_Caleido3() { + anim.initEffect(); + anim.Caleido3(); + return FRAMETIME; +} +uint16_t mode_Caleido2() { + anim.initEffect(); + anim.Caleido2(); + return FRAMETIME; +} +uint16_t mode_Caleido1() { + anim.initEffect(); + anim.Caleido1(); + return FRAMETIME; +} +uint16_t mode_Distance_Experiment() { + anim.initEffect(); + anim.Distance_Experiment(); + return FRAMETIME; +} +uint16_t mode_Center_Field() { + anim.initEffect(); + anim.Center_Field(); + return FRAMETIME; +} +uint16_t mode_Waves() { + anim.initEffect(); + anim.Waves(); + return FRAMETIME; +} +uint16_t mode_Chasing_Spirals() { + anim.initEffect(); + anim.Chasing_Spirals(); + return FRAMETIME; +} +uint16_t mode_Rotating_Blob() { + anim.initEffect(); + anim.Rotating_Blob(); + return FRAMETIME; +} + + +class AnimartrixUsermod : public Usermod { + protected: + bool enabled = false; //WLEDMM + const char *_name; //WLEDMM + bool initDone = false; //WLEDMM + unsigned long lastTime = 0; //WLEDMM + + public: + + AnimartrixUsermod(const char *name, bool enabled) { + this->_name = name; + this->enabled = enabled; + } //WLEDMM + + + void setup() { + + strip.addEffect(255, &mode_Module_Experiment10, _data_FX_mode_Module_Experiment10); + strip.addEffect(255, &mode_Module_Experiment9, _data_FX_mode_Module_Experiment9); + strip.addEffect(255, &mode_Module_Experiment8, _data_FX_mode_Module_Experiment8); + strip.addEffect(255, &mode_Module_Experiment7, _data_FX_mode_Module_Experiment7); + strip.addEffect(255, &mode_Module_Experiment6, _data_FX_mode_Module_Experiment6); + strip.addEffect(255, &mode_Module_Experiment5, _data_FX_mode_Module_Experiment5); + strip.addEffect(255, &mode_Module_Experiment4, _data_FX_mode_Module_Experiment4); + strip.addEffect(255, &mode_Zoom2, _data_FX_mode_Zoom2); + strip.addEffect(255, &mode_Module_Experiment3, _data_FX_mode_Module_Experiment3); + strip.addEffect(255, &mode_Module_Experiment2, _data_FX_mode_Module_Experiment2); + strip.addEffect(255, &mode_Module_Experiment1, _data_FX_mode_Module_Experiment1); + strip.addEffect(255, &mode_Parametric_Water, _data_FX_mode_Parametric_Water); + strip.addEffect(255, &mode_Water, _data_FX_mode_Water); + strip.addEffect(255, &mode_Complex_Kaleido_6, _data_FX_mode_Complex_Kaleido_6); + strip.addEffect(255, &mode_Complex_Kaleido_5, _data_FX_mode_Complex_Kaleido_5); + strip.addEffect(255, &mode_Complex_Kaleido_4, _data_FX_mode_Complex_Kaleido_4); + strip.addEffect(255, &mode_Complex_Kaleido_3, _data_FX_mode_Complex_Kaleido_3); + strip.addEffect(255, &mode_Complex_Kaleido_2, _data_FX_mode_Complex_Kaleido_2); + strip.addEffect(255, &mode_Complex_Kaleido, _data_FX_mode_Complex_Kaleido); + strip.addEffect(255, &mode_SM10, _data_FX_mode_SM10); + strip.addEffect(255, &mode_SM9, _data_FX_mode_SM9); + strip.addEffect(255, &mode_SM8, _data_FX_mode_SM8); + // strip.addEffect(255, &mode_SM7, _data_FX_mode_SM7); + strip.addEffect(255, &mode_SM6, _data_FX_mode_SM6); + strip.addEffect(255, &mode_SM5, _data_FX_mode_SM5); + strip.addEffect(255, &mode_SM4, _data_FX_mode_SM4); + strip.addEffect(255, &mode_SM3, _data_FX_mode_SM3); + strip.addEffect(255, &mode_SM2, _data_FX_mode_SM2); + strip.addEffect(255, &mode_SM1, _data_FX_mode_SM1); + strip.addEffect(255, &mode_Big_Caleido, _data_FX_mode_Big_Caleido); + strip.addEffect(255, &mode_RGB_Blobs5, _data_FX_mode_RGB_Blobs5); + strip.addEffect(255, &mode_RGB_Blobs4, _data_FX_mode_RGB_Blobs4); + strip.addEffect(255, &mode_RGB_Blobs3, _data_FX_mode_RGB_Blobs3); + strip.addEffect(255, &mode_RGB_Blobs2, _data_FX_mode_RGB_Blobs2); + strip.addEffect(255, &mode_RGB_Blobs, _data_FX_mode_RGB_Blobs); + strip.addEffect(255, &mode_Polar_Waves, _data_FX_mode_Polar_Waves); + strip.addEffect(255, &mode_Slow_Fade, _data_FX_mode_Slow_Fade); + strip.addEffect(255, &mode_Zoom, _data_FX_mode_Zoom); + strip.addEffect(255, &mode_Hot_Blob, _data_FX_mode_Hot_Blob); + strip.addEffect(255, &mode_Spiralus2, _data_FX_mode_Spiralus2); + strip.addEffect(255, &mode_Spiralus, _data_FX_mode_Spiralus); + strip.addEffect(255, &mode_Yves, _data_FX_mode_Yves); + strip.addEffect(255, &mode_Scaledemo1, _data_FX_mode_Scaledemo1); + strip.addEffect(255, &mode_Lava1, _data_FX_mode_Lava1); + strip.addEffect(255, &mode_Caleido3, _data_FX_mode_Caleido3); + strip.addEffect(255, &mode_Caleido2, _data_FX_mode_Caleido2); + strip.addEffect(255, &mode_Caleido1, _data_FX_mode_Caleido1); + strip.addEffect(255, &mode_Distance_Experiment, _data_FX_mode_Distance_Experiment); + strip.addEffect(255, &mode_Center_Field, _data_FX_mode_Center_Field); + strip.addEffect(255, &mode_Waves, _data_FX_mode_Waves); + strip.addEffect(255, &mode_Chasing_Spirals, _data_FX_mode_Chasing_Spirals); + strip.addEffect(255, &mode_Rotating_Blob, _data_FX_mode_Rotating_Blob); + + initDone = true; + } + + void loop() { + if (!enabled || strip.isUpdating()) return; + + // do your magic here + if (millis() - lastTime > 1000) { + //USER_PRINTLN("I'm alive!"); + lastTime = millis(); + } + } + + void addToJsonInfo(JsonObject& root) + { + char myStringBuffer[16]; // buffer for snprintf() + JsonObject user = root["u"]; + if (user.isNull()) user = root.createNestedObject("u"); + + JsonArray infoArr = user.createNestedArray(FPSTR(_name)); + + String uiDomString = F("Animartrix requires the Creative Commons Attribution License CC BY-NC 3.0"); + infoArr.add(uiDomString); + } + + uint16_t getId() + { + return USERMOD_ID_ANIMARTRIX; + } + +}; + + + diff --git a/usermods/usermod_v2_four_line_display_ALT/usermod_v2_four_line_display_ALT.h b/usermods/usermod_v2_four_line_display_ALT/usermod_v2_four_line_display_ALT.h index 48dab8f0c..40136a92d 100644 --- a/usermods/usermod_v2_four_line_display_ALT/usermod_v2_four_line_display_ALT.h +++ b/usermods/usermod_v2_four_line_display_ALT/usermod_v2_four_line_display_ALT.h @@ -211,16 +211,16 @@ class FourLineDisplayUsermod : public Usermod { // gets called once at boot. Do all initialization that doesn't depend on // network here - void setup(); + void setup() override; // gets called every time WiFi is (re-)connected. Initialize own network // interfaces here - void connected(); + void connected() override; /** * Da loop. */ - void loop(); + void loop() override; //function to update lastredraw inline void updateRedrawTime() { lastRedraw = millis(); } @@ -287,28 +287,28 @@ class FourLineDisplayUsermod : public Usermod { */ bool handleButton(uint8_t b); - void onUpdateBegin(bool init); + void onUpdateBegin(bool init) override; /* * addToJsonInfo() can be used to add custom entries to the /json/info part of the JSON API. * Creating an "u" object allows you to add custom key/value pairs to the Info section of the WLED web UI. * Below it is shown how this could be used for e.g. a light sensor */ - //void addToJsonInfo(JsonObject& root); + //void addToJsonInfo(JsonObject& root) override; /* * addToJsonState() can be used to add custom entries to the /json/state part of the JSON API (state object). * Values in the state object may be modified by connected clients */ - //void addToJsonState(JsonObject& root); + //void addToJsonState(JsonObject& root) override; /* * readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object). * Values in the state object may be modified by connected clients */ - //void readFromJsonState(JsonObject& root); + //void readFromJsonState(JsonObject& root) override; - void appendConfigData(); + void appendConfigData() override; /* * addToConfig() can be used to add custom persistent settings to the cfg.json file in the "um" (usermod) object. @@ -324,7 +324,7 @@ class FourLineDisplayUsermod : public Usermod { * * I highly recommend checking out the basics of ArduinoJson serialization and deserialization in order to use custom settings! */ - void addToConfig(JsonObject& root); + void addToConfig(JsonObject& root) override; /* * readFromConfig() can be used to read back the custom settings you added with addToConfig(). @@ -334,13 +334,13 @@ class FourLineDisplayUsermod : public Usermod { * but also that if you want to write persistent values to a dynamic buffer, you'd need to allocate it here instead of in setup. * If you don't know what that is, don't fret. It most likely doesn't affect your use case :) */ - bool readFromConfig(JsonObject& root); + bool readFromConfig(JsonObject& root) override; /* * getId() allows you to optionally give your V2 usermod an unique ID (please define it in const.h!). * This could be used in the future for the system to determine whether your usermod is installed. */ - uint16_t getId() { + uint16_t getId() override { return USERMOD_ID_FOUR_LINE_DISP; } }; diff --git a/usermods/usermod_v2_rotary_encoder_ui_ALT/usermod_v2_rotary_encoder_ui_ALT.h b/usermods/usermod_v2_rotary_encoder_ui_ALT/usermod_v2_rotary_encoder_ui_ALT.h index 858e16540..adea86774 100644 --- a/usermods/usermod_v2_rotary_encoder_ui_ALT/usermod_v2_rotary_encoder_ui_ALT.h +++ b/usermods/usermod_v2_rotary_encoder_ui_ALT/usermod_v2_rotary_encoder_ui_ALT.h @@ -285,7 +285,7 @@ class RotaryEncoderUIUsermod : public Usermod { * getId() allows you to optionally give your V2 usermod an unique ID (please define it in const.h!). * This could be used in the future for the system to determine whether your usermod is installed. */ - uint16_t getId() { return USERMOD_ID_ROTARY_ENC_UI; } + uint16_t getId() override { return USERMOD_ID_ROTARY_ENC_UI; } /** * Enable/Disable the usermod */ @@ -300,7 +300,7 @@ class RotaryEncoderUIUsermod : public Usermod { * setup() is called once at boot. WiFi is not yet connected at this point. * You can use it to initialize variables, sensors or similar. */ - void setup(); + void setup() override; /** * connected() is called every time the WiFi is (re)connected @@ -311,11 +311,11 @@ class RotaryEncoderUIUsermod : public Usermod { /** * loop() is called continuously. Here you can check for events, read sensors, etc. */ - void loop(); + void loop() override; #ifndef WLED_DISABLE_MQTT - //bool onMqttMessage(char* topic, char* payload); - //void onMqttConnect(bool sessionPresent); + //bool onMqttMessage(char* topic, char* payload) override; + //void onMqttConnect(bool sessionPresent) override; #endif /** @@ -323,31 +323,31 @@ class RotaryEncoderUIUsermod : public Usermod { * will prevent button working in a default way. * Replicating button.cpp */ - //bool handleButton(uint8_t b); + //bool handleButton(uint8_t b) override; /** * addToJsonInfo() can be used to add custom entries to the /json/info part of the JSON API. */ - //void addToJsonInfo(JsonObject &root); + //void addToJsonInfo(JsonObject &root) override; /** * addToJsonState() can be used to add custom entries to the /json/state part of the JSON API (state object). * Values in the state object may be modified by connected clients */ - //void addToJsonState(JsonObject &root); + //void addToJsonState(JsonObject &root) override; /** * readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object). * Values in the state object may be modified by connected clients */ - //void readFromJsonState(JsonObject &root); + //void readFromJsonState(JsonObject &root) override; /** * provide the changeable values */ - void addToConfig(JsonObject &root); + void addToConfig(JsonObject &root) override; - void appendConfigData(); + void appendConfigData() override; /** * restore the changeable values @@ -355,7 +355,7 @@ class RotaryEncoderUIUsermod : public Usermod { * * The function should return true if configuration was successfully loaded or false if there was no configuration. */ - bool readFromConfig(JsonObject &root); + bool readFromConfig(JsonObject &root) override; // custom methods void displayNetworkInfo(); diff --git a/usermods/wireguard/wireguard.h b/usermods/wireguard/wireguard.h index a83b9fe78..c4e1fd504 100644 --- a/usermods/wireguard/wireguard.h +++ b/usermods/wireguard/wireguard.h @@ -67,8 +67,8 @@ class WireguardUsermod : public Usermod { JsonObject top = root.createNestedObject(F("WireGuard")); top[F("host")] = endpoint_address; top[F("port")] = endpoint_port; - top[F("ip")] = local_ip.toString(); - top[F("psk")] = preshared_key; + top["ip"] = local_ip.toString(); + top["psk"] = preshared_key; top[F("pem")] = private_key; top[F("pub")] = public_key; top[F("tz")] = posix_tz; @@ -77,11 +77,11 @@ class WireguardUsermod : public Usermod { bool readFromConfig(JsonObject& root) { JsonObject top = root[F("WireGuard")]; - if (top["host"].isNull() || top["port"].isNull() || top["ip"].isNull() || top["pem"].isNull() || top["pub"].isNull() || top["tz"].isNull()) { + if (top[F("host")].isNull() || top[F("port")].isNull() || top["ip"].isNull() || top[F("pem")].isNull() || top[F("pub")].isNull() || top[F("tz")].isNull()) { is_enabled = false; return false; } else { - const char* host = top["host"]; + const char* host = top[F("host")]; strncpy(endpoint_address, host, 100); const char* ip_s = top["ip"]; @@ -89,16 +89,16 @@ class WireguardUsermod : public Usermod { sscanf(ip_s, "%u.%u.%u.%u", &ip[0], &ip[1], &ip[2], &ip[3]); local_ip = IPAddress(ip[0], ip[1], ip[2], ip[3]); - const char* pem = top["pem"]; + const char* pem = top[F("pem")]; strncpy(private_key, pem, 45); - const char* pub = top["pub"]; + const char* pub = top[F("pub")]; strncpy(public_key, pub, 45); - const char* tz = top["tz"]; + const char* tz = top[F("tz")]; strncpy(posix_tz, tz, 150); - endpoint_port = top["port"]; + endpoint_port = top[F("port")]; if (!top["psk"].isNull()) { const char* psk = top["psk"]; diff --git a/usermods/word-clock-matrix/usermod_word_clock_matrix.h b/usermods/word-clock-matrix/usermod_word_clock_matrix.h index 582563004..506c1275e 100644 --- a/usermods/word-clock-matrix/usermod_word_clock_matrix.h +++ b/usermods/word-clock-matrix/usermod_word_clock_matrix.h @@ -325,8 +325,8 @@ public: void addToConfig(JsonObject& root) { JsonObject modName = root.createNestedObject("id"); - modName["mdns"] = "wled-word-clock"; - modName["name"] = "WLED WORD CLOCK"; + modName[F("mdns")] = "wled-word-clock"; + modName[F("name")] = "WLED WORD CLOCK"; } uint16_t getId() diff --git a/wled00/FX.cpp b/wled00/FX.cpp index 865c1ebac..a27fc4fbe 100644 --- a/wled00/FX.cpp +++ b/wled00/FX.cpp @@ -3444,8 +3444,8 @@ static const char _data_FX_MODE_STARBURST[] PROGMEM = "Fireworks Starburst@Chanc uint16_t mode_exploding_fireworks(void) { if (SEGLEN == 1) return mode_static(); - const uint16_t cols = strip.isMatrix ? SEGMENT.virtualWidth() : 1; - const uint16_t rows = strip.isMatrix ? SEGMENT.virtualHeight() : SEGMENT.virtualLength(); + const uint16_t cols = SEGMENT.is2D() ? SEGMENT.virtualWidth() : 1; + const uint16_t rows = SEGMENT.is2D() ? SEGMENT.virtualHeight() : SEGMENT.virtualLength(); //allocate segment data uint16_t maxData = FAIR_DATA_PER_SEG; //ESP8266: 256 ESP32: 640 @@ -3476,11 +3476,11 @@ uint16_t mode_exploding_fireworks(void) if (SEGENV.aux0 < 2) { //FLARE if (SEGENV.aux0 == 0) { //init flare flare->pos = 0; - flare->posX = strip.isMatrix ? random16(2,cols-3) : (SEGMENT.intensity > random8()); // will enable random firing side on 1D + flare->posX = SEGMENT.is2D() ? random16(2,cols-3) : (SEGMENT.intensity > random8()); // will enable random firing side on 1D uint16_t peakHeight = 75 + random8(180); //0-255 peakHeight = (peakHeight * (rows -1)) >> 8; flare->vel = sqrtf(-2.0f * gravity * peakHeight); - flare->velX = strip.isMatrix ? (random8(9)-4)/32.f : 0; // no X velocity on 1D + flare->velX = SEGMENT.is2D() ? (random8(9)-4)/64.0f : 0; // no X velocity on 1D flare->col = 255; //brightness SEGENV.aux0 = 1; } @@ -3488,12 +3488,14 @@ uint16_t mode_exploding_fireworks(void) // launch if (flare->vel > 12 * gravity) { // flare - if (strip.isMatrix) SEGMENT.setPixelColorXY(int(flare->posX), rows - uint16_t(flare->pos) - 1, flare->col, flare->col, flare->col); - else SEGMENT.setPixelColor(int(flare->posX) ? rows - int(flare->pos) - 1 : int(flare->pos), flare->col, flare->col, flare->col); + if (SEGMENT.is2D()) SEGMENT.setPixelColorXY(int(flare->posX), rows - uint16_t(flare->pos) - 1, flare->col, flare->col, flare->col); + else SEGMENT.setPixelColor((flare->posX > 0.0f) ? rows - int(flare->pos) - 1 : int(flare->pos), flare->col, flare->col, flare->col); flare->pos += flare->vel; - flare->posX += flare->velX; flare->pos = constrain(flare->pos, 0, rows-1); - flare->posX = constrain(flare->posX, 0, cols-strip.isMatrix); + if (SEGMENT.is2D()) { + flare->posX += flare->velX; + flare->posX = constrain(flare->posX, 0, cols-1); + } flare->vel += gravity; flare->col -= 2; } else { @@ -3516,12 +3518,12 @@ uint16_t mode_exploding_fireworks(void) sparks[i].posX = flare->posX; sparks[i].vel = (float(random16(20001)) / 10000.0f) - 0.9f; // from -0.9 to 1.1 sparks[i].vel *= rows<32 ? 0.5f : 1; // reduce velocity for smaller strips - sparks[i].velX = strip.isMatrix ? (float(random16(10001)) / 10000.0f) - 0.5f : 0; // from -0.5 to 0.5 + sparks[i].velX = SEGMENT.is2D() ? (float(random16(20001)) / 10000.0f) - 1.0f : 0; // from -1 to 1 sparks[i].col = 345;//abs(sparks[i].vel * 750.0); // set colors before scaling velocity to keep them bright //sparks[i].col = constrain(sparks[i].col, 0, 345); sparks[i].colIndex = random8(); sparks[i].vel *= flare->pos/rows; // proportional to height - sparks[i].velX *= strip.isMatrix ? flare->posX/cols : 0; // proportional to width + sparks[i].velX *= SEGMENT.is2D() ? flare->posX/cols : 0; // proportional to width sparks[i].vel *= -gravity *50; } //sparks[1].col = 345; // this will be our known spark @@ -3534,11 +3536,11 @@ uint16_t mode_exploding_fireworks(void) sparks[i].pos += sparks[i].vel; sparks[i].posX += sparks[i].velX; sparks[i].vel += *dying_gravity; - sparks[i].velX += strip.isMatrix ? *dying_gravity : 0; + sparks[i].velX += SEGMENT.is2D() ? *dying_gravity : 0; if (sparks[i].col > 3) sparks[i].col -= 4; if (sparks[i].pos > 0 && sparks[i].pos < rows) { - if (strip.isMatrix && !(sparks[i].posX >= 0 && sparks[i].posX < cols)) continue; + if (SEGMENT.is2D() && !(sparks[i].posX >= 0 && sparks[i].posX < cols)) continue; uint16_t prog = sparks[i].col; uint32_t spColor = (SEGMENT.palette) ? SEGMENT.color_wheel(sparks[i].colIndex) : SEGCOLOR(0); CRGB c = CRGB::Black; //HeatColor(sparks[i].col); @@ -3550,7 +3552,7 @@ uint16_t mode_exploding_fireworks(void) c.g = qsub8(c.g, cooling); c.b = qsub8(c.b, cooling * 2); } - if (strip.isMatrix) SEGMENT.setPixelColorXY(int(sparks[i].posX), rows - int(sparks[i].pos) - 1, c.red, c.green, c.blue); + if (SEGMENT.is2D()) SEGMENT.setPixelColorXY(int(sparks[i].posX), rows - int(sparks[i].pos) - 1, c.red, c.green, c.blue); else SEGMENT.setPixelColor(int(sparks[i].posX) ? rows - int(sparks[i].pos) - 1 : int(sparks[i].pos), c.red, c.green, c.blue); } } @@ -5292,7 +5294,6 @@ uint16_t mode_2Dmatrix(void) { // Matrix2D. By Jeremy Williams. if (!SEGENV.allocateData(dataSize)) return mode_static(); //allocation failed if (SEGENV.call == 0) { - memset(SEGMENT.data, 0, dataSize); // no falling spawns SEGMENT.fill(BLACK); SEGENV.step = 0; } diff --git a/wled00/FX.h b/wled00/FX.h index 1b5b00dae..b053c8492 100644 --- a/wled00/FX.h +++ b/wled00/FX.h @@ -62,10 +62,10 @@ //#define FRAMETIME _frametime #define FRAMETIME strip.getFrameTime() -/* each segment uses 52 bytes of SRAM memory, so if you're application fails because of +/* each segment uses 82 bytes of SRAM memory, so if you're application fails because of insufficient memory, decreasing MAX_NUM_SEGMENTS may help */ #ifdef ESP8266 - #define MAX_NUM_SEGMENTS 16 + #define MAX_NUM_SEGMENTS 12 /* How much data bytes all segments combined may allocate */ #define MAX_SEGMENT_DATA 5120 #else @@ -73,9 +73,13 @@ #define MAX_NUM_SEGMENTS 32 #endif #if defined(ARDUINO_ARCH_ESP32S2) - #define MAX_SEGMENT_DATA 24576 + #if defined(BOARD_HAS_PSRAM) && defined(WLED_USE_PSRAM) + #define MAX_SEGMENT_DATA MAX_NUM_SEGMENTS*1024 // 32k by default + #else + #define MAX_SEGMENT_DATA MAX_NUM_SEGMENTS*768 // 24k by default + #endif #else - #define MAX_SEGMENT_DATA 32767 + #define MAX_SEGMENT_DATA MAX_NUM_SEGMENTS*1280 // 40k by default #endif #endif @@ -278,7 +282,7 @@ #define FX_MODE_RIPPLEPEAK 148 #define FX_MODE_2DFIRENOISE 149 #define FX_MODE_2DSQUAREDSWIRL 150 -#define FX_MODE_2DFIRE2012 151 +// #define FX_MODE_2DFIRE2012 151 #define FX_MODE_2DDNA 152 #define FX_MODE_2DMATRIX 153 #define FX_MODE_2DMETABALLS 154 @@ -288,7 +292,7 @@ #define FX_MODE_GRAVFREQ 158 #define FX_MODE_DJLIGHT 159 #define FX_MODE_2DFUNKYPLANK 160 -#define FX_MODE_2DCENTERBARS 161 +//#define FX_MODE_2DCENTERBARS 161 #define FX_MODE_2DPULSER 162 #define FX_MODE_BLURZ 163 #define FX_MODE_2DDRIFT 164 @@ -531,7 +535,7 @@ typedef struct Segment { #endif static void handleRandomPalette(); - void setUp(uint16_t i1, uint16_t i2, uint8_t grp=1, uint8_t spc=0, uint16_t ofs=UINT16_MAX, uint16_t i1Y=0, uint16_t i2Y=1, uint8_t segId = 255); + void setUp(uint16_t i1, uint16_t i2, uint8_t grp=1, uint8_t spc=0, uint16_t ofs=UINT16_MAX, uint16_t i1Y=0, uint16_t i2Y=1); bool setColor(uint8_t slot, uint32_t c); //returns true if changed void setCCT(uint16_t k); void setOpacity(uint8_t o); @@ -543,9 +547,9 @@ typedef struct Segment { // runtime data functions inline uint16_t dataSize(void) const { return _dataLen; } - bool allocateData(size_t len); - void deallocateData(void); - void resetIfRequired(void); + bool allocateData(size_t len); // allocates effect data buffer in heap and clears it + void deallocateData(void); // deallocates (frees) effect data buffer from heap + void resetIfRequired(void); // sets all SEGENV variables to 0 and clears data buffer /** * Flags that before the next effect is calculated, * the internal segment state should be reset. @@ -555,17 +559,17 @@ typedef struct Segment { inline void markForReset(void) { reset = true; } // setOption(SEG_OPTION_RESET, true) // transition functions - void startTransition(uint16_t dur); // transition has to start before actual segment values change - void stopTransition(void); + void startTransition(uint16_t dur); // transition has to start before actual segment values change + void stopTransition(void); // ends transition mode by destroying transition structure void handleTransition(void); #ifndef WLED_DISABLE_MODE_BLEND - void swapSegenv(tmpsegd_t &tmpSegD); - void restoreSegenv(tmpsegd_t &tmpSegD); + void swapSegenv(tmpsegd_t &tmpSegD); // copies segment data into specifed buffer, if buffer is not a transition buffer, segment data is overwritten from transition buffer + void restoreSegenv(tmpsegd_t &tmpSegD); // restores segment data from buffer, if buffer is not transition buffer, changed values are copied to transition buffer #endif - uint16_t progress(void); //transition progression between 0-65535 - uint8_t currentBri(bool useCct = false); - uint8_t currentMode(void); - uint32_t currentColor(uint8_t slot); + uint16_t progress(void); // transition progression between 0-65535 + uint8_t currentBri(bool useCct = false); // current segment brightness/CCT (blended while in transition) + uint8_t currentMode(void); // currently active effect/mode (while in transition) + uint32_t currentColor(uint8_t slot); // currently active segment color (blended while in transition) CRGBPalette16 &loadPalette(CRGBPalette16 &tgt, uint8_t pal); CRGBPalette16 ¤tPalette(CRGBPalette16 &tgt, uint8_t paletteID); @@ -594,9 +598,9 @@ typedef struct Segment { uint32_t color_wheel(uint8_t pos); // 2D matrix - uint16_t virtualWidth(void) const; - uint16_t virtualHeight(void) const; - uint16_t nrOfVStrips(void) const; + uint16_t virtualWidth(void) const; // segment width in virtual pixels (accounts for groupping and spacing) + uint16_t virtualHeight(void) const; // segment height in virtual pixels (accounts for groupping and spacing) + uint16_t nrOfVStrips(void) const; // returns number of virtual vertical strips in 2D matrix (used to expand 1D effects into 2D) #ifndef WLED_DISABLE_2D uint16_t XY(uint16_t x, uint16_t y); // support function to get relative index within segment void setPixelColorXY(int x, int y, uint32_t c); // set relative pixel within segment with color @@ -682,10 +686,7 @@ class WS2812FX { // 96 bytes WS2812FX() : paletteFade(0), paletteBlend(0), - milliampsPerLed(55), cctBlending(0), - ablMilliampsMax(ABL_MILLIAMPS_DEFAULT), - currentMilliamps(0), now(millis()), timebase(0), isMatrix(false), @@ -697,6 +698,7 @@ class WS2812FX { // 96 bytes _colors_t{0,0,0}, _virtualSegmentLength(0), // true private variables + _suspend(false), _length(DEFAULT_LED_COUNT), _brightness(DEFAULT_BRIGHTNESS), _transitionDur(750), @@ -745,38 +747,39 @@ class WS2812FX { // 96 bytes void #ifdef WLED_DEBUG - printSize(), + printSize(), // prints memory usage for strip components #endif - finalizeInit(), - service(void), - setMode(uint8_t segid, uint8_t m), - setColor(uint8_t slot, uint32_t c), - setCCT(uint16_t k), - setBrightness(uint8_t b, bool direct = false), - setRange(uint16_t i, uint16_t i2, uint32_t col), - purgeSegments(bool force = false), + finalizeInit(), // initialises strip components + service(void), // executes effect functions when due and calls strip.show() + setMode(uint8_t segid, uint8_t m), // sets effect/mode for given segment (high level API) + setColor(uint8_t slot, uint32_t c), // sets color (in slot) for given segment (high level API) + setCCT(uint16_t k), // sets global CCT (either in relative 0-255 value or in K) + setBrightness(uint8_t b, bool direct = false), // sets strip brightness + setRange(uint16_t i, uint16_t i2, uint32_t col), // used for clock overlay + purgeSegments(void), // removes inactive segments from RAM (may incure penalty and memory fragmentation but reduces vector footprint) setSegment(uint8_t n, uint16_t start, uint16_t stop, uint8_t grouping = 1, uint8_t spacing = 0, uint16_t offset = UINT16_MAX, uint16_t startY=0, uint16_t stopY=1), setMainSegmentId(uint8_t n), - resetSegments(), - makeAutoSegments(bool forceReset = false), - fixInvalidSegments(), - setPixelColor(int n, uint32_t c), - show(void), + resetSegments(), // marks all segments for reset + makeAutoSegments(bool forceReset = false), // will create segments based on configured outputs + fixInvalidSegments(), // fixes incorrect segment configuration + setPixelColor(unsigned n, uint32_t c), // paints absolute strip pixel with index n and color c + show(void), // initiates LED output setTargetFps(uint8_t fps), addEffect(uint8_t id, mode_ptr mode_fn, const char *mode_name), // add effect to the list; defined in FX.cpp - setupEffectData(void); // add default effects to the list; defined in FX.cpp + setupEffectData(void); // add default effects to the list; defined in FX.cpp - inline void restartRuntime() { for (Segment &seg : _segments) seg.markForReset(); } + inline void restartRuntime() { for (Segment &seg : _segments) seg.markForReset(); } inline void setTransitionMode(bool t) { for (Segment &seg : _segments) seg.startTransition(t ? _transitionDur : 0); } - inline void setColor(uint8_t slot, uint8_t r, uint8_t g, uint8_t b, uint8_t w = 0) { setColor(slot, RGBW32(r,g,b,w)); } - inline void fill(uint32_t c) { for (int i = 0; i < getLengthTotal(); i++) setPixelColor(i, c); } // fill whole strip with color (inline) - // outsmart the compiler :) by correctly overloading - inline void setPixelColor(int n, uint8_t r, uint8_t g, uint8_t b, uint8_t w = 0) { setPixelColor(n, RGBW32(r,g,b,w)); } - inline void setPixelColor(int n, CRGB c) { setPixelColor(n, c.red, c.green, c.blue); } - inline void trigger(void) { _triggered = true; } // Forces the next frame to be computed on all active segments. - inline void setShowCallback(show_callback cb) { _callback = cb; } - inline void setTransition(uint16_t t) { _transitionDur = t; } + inline void setColor(uint8_t slot, uint8_t r, uint8_t g, uint8_t b, uint8_t w = 0) { setColor(slot, RGBW32(r,g,b,w)); } + inline void setPixelColor(unsigned n, uint8_t r, uint8_t g, uint8_t b, uint8_t w = 0) { setPixelColor(n, RGBW32(r,g,b,w)); } + inline void setPixelColor(unsigned n, CRGB c) { setPixelColor(n, c.red, c.green, c.blue); } + inline void fill(uint32_t c) { for (unsigned i = 0; i < getLengthTotal(); i++) setPixelColor(i, c); } // fill whole strip with color (inline) + inline void trigger(void) { _triggered = true; } // Forces the next frame to be computed on all active segments. + inline void setShowCallback(show_callback cb) { _callback = cb; } + inline void setTransition(uint16_t t) { _transitionDur = t; } // sets transition time (in ms) inline void appendSegment(const Segment &seg = Segment()) { if (_segments.size() < getMaxSegments()) _segments.push_back(seg); } + inline void suspend(void) { _suspend = true; } // will suspend (and canacel) strip.service() execution + inline void resume(void) { _suspend = false; } // will resume strip.service() execution bool paletteFade, @@ -787,48 +790,47 @@ class WS2812FX { // 96 bytes isUpdating(void), deserializeMap(uint8_t n=0); - inline bool isServicing(void) { return _isServicing; } - inline bool hasWhiteChannel(void) {return _hasWhiteChannel;} - inline bool isOffRefreshRequired(void) {return _isOffRefreshRequired;} + inline bool isServicing(void) { return _isServicing; } // returns true if strip.service() is executing + inline bool hasWhiteChannel(void) { return _hasWhiteChannel; } // returns true if strip contains separate white chanel + inline bool isOffRefreshRequired(void) { return _isOffRefreshRequired; } // returns true if strip requires regular updates (i.e. TM1814 chipset) + inline bool isSuspended(void) { return _suspend; } // returns true if strip.service() execution is suspended + inline bool needsUpdate(void) { return _triggered; } // returns true if strip received a trigger() request uint8_t paletteBlend, - milliampsPerLed, cctBlending, getActiveSegmentsNum(void), getFirstSelectedSegId(void), getLastActiveSegmentId(void), - getActiveSegsLightCapabilities(bool selectedOnly = false), - setPixelSegment(uint8_t n); + getActiveSegsLightCapabilities(bool selectedOnly = false); - inline uint8_t getBrightness(void) { return _brightness; } - inline uint8_t getMaxSegments(void) { return MAX_NUM_SEGMENTS; } // returns maximum number of supported segments (fixed value) - inline uint8_t getSegmentsNum(void) { return _segments.size(); } // returns currently present segments - inline uint8_t getCurrSegmentId(void) { return _segment_index; } - inline uint8_t getMainSegmentId(void) { return _mainSegment; } - inline uint8_t getPaletteCount() { return 13 + GRADIENT_PALETTE_COUNT; } // will only return built-in palette count - inline uint8_t getTargetFps() { return _targetFps; } - inline uint8_t getModeCount() { return _modeCount; } + inline uint8_t getBrightness(void) { return _brightness; } // returns current strip brightness + inline uint8_t getMaxSegments(void) { return MAX_NUM_SEGMENTS; } // returns maximum number of supported segments (fixed value) + inline uint8_t getSegmentsNum(void) { return _segments.size(); } // returns currently present segments + inline uint8_t getCurrSegmentId(void) { return _segment_index; } // returns current segment index (only valid while strip.isServicing()) + inline uint8_t getMainSegmentId(void) { return _mainSegment; } // returns main segment index + inline uint8_t getPaletteCount() { return 13 + GRADIENT_PALETTE_COUNT; } // will only return built-in palette count + inline uint8_t getTargetFps() { return _targetFps; } // returns rough FPS value for las 2s interval + inline uint8_t getModeCount() { return _modeCount; } // returns number of registered modes/effects uint16_t - ablMilliampsMax, - currentMilliamps, getLengthPhysical(void), getLengthTotal(void), // will include virtual/nonexistent pixels in matrix - getFps(); + getFps(), + getMappedPixelIndex(uint16_t index); - inline uint16_t getFrameTime(void) { return _frametime; } - inline uint16_t getMinShowDelay(void) { return MIN_SHOW_DELAY; } - inline uint16_t getLength(void) { return _length; } // 2D matrix may have less pixels than W*H - inline uint16_t getTransition(void) { return _transitionDur; } + inline uint16_t getFrameTime(void) { return _frametime; } // returns amount of time a frame should take (in ms) + inline uint16_t getMinShowDelay(void) { return MIN_SHOW_DELAY; } // returns minimum amount of time strip.service() can be delayed (constant) + inline uint16_t getLength(void) { return _length; } // returns actual amount of LEDs on a strip (2D matrix may have less LEDs than W*H) + inline uint16_t getTransition(void) { return _transitionDur; } // returns currently set transition time (in ms) uint32_t now, timebase, getPixelColor(uint16_t); - inline uint32_t getLastShow(void) { return _lastShow; } - inline uint32_t segColor(uint8_t i) { return _colors_t[i]; } + inline uint32_t getLastShow(void) { return _lastShow; } // returns millis() timestamp of last strip.show() call + inline uint32_t segColor(uint8_t i) { return _colors_t[i]; } // returns currently valid color (for slot i) AKA SEGCOLOR(); may be blended between two colors while in transition const char * getModeData(uint8_t id = 0) { return (id && id<_modeCount) ? _modeData[id] : PSTR("Solid"); } @@ -837,9 +839,9 @@ class WS2812FX { // 96 bytes getModeDataSrc(void) { return &(_modeData[0]); } // vectors use arrays for underlying data Segment& getSegment(uint8_t id); - inline Segment& getFirstSelectedSeg(void) { return _segments[getFirstSelectedSegId()]; } - inline Segment& getMainSegment(void) { return _segments[getMainSegmentId()]; } - inline Segment* getSegments(void) { return &(_segments[0]); } + inline Segment& getFirstSelectedSeg(void) { return _segments[getFirstSelectedSegId()]; } // returns reference to first segment that is "selected" + inline Segment& getMainSegment(void) { return _segments[getMainSegmentId()]; } // returns reference to main segment + inline Segment* getSegments(void) { return &(_segments[0]); } // returns pointer to segment vector structure (warning: use carefully) // 2D support (panels) bool @@ -875,10 +877,10 @@ class WS2812FX { // 96 bytes std::vector panel; #endif - void setUpMatrix(); + void setUpMatrix(); // sets up automatic matrix ledmap from panel configuration // outsmart the compiler :) by correctly overloading - inline void setPixelColorXY(int x, int y, uint32_t c) { setPixelColor(y * Segment::maxWidth + x, c); } + inline void setPixelColorXY(int x, int y, uint32_t c) { setPixelColor((unsigned)(y * Segment::maxWidth + x), c); } inline void setPixelColorXY(int x, int y, byte r, byte g, byte b, byte w = 0) { setPixelColorXY(x, y, RGBW32(r,g,b,w)); } inline void setPixelColorXY(int x, int y, CRGB c) { setPixelColorXY(x, y, RGBW32(c.r,c.g,c.b,0)); } @@ -899,6 +901,8 @@ class WS2812FX { // 96 bytes friend class Segment; private: + volatile bool _suspend; + uint16_t _length; uint8_t _brightness; uint16_t _transitionDur; @@ -932,9 +936,10 @@ class WS2812FX { // 96 bytes uint16_t _qStart, _qStop, _qStartY, _qStopY; uint8_t _qGrouping, _qSpacing; uint16_t _qOffset; - +/* void setUpSegmentFromQueuedChanges(void); +*/ }; extern const char JSON_mode_names[]; diff --git a/wled00/FX_2Dfcn.cpp b/wled00/FX_2Dfcn.cpp index d2622f901..6f5075d08 100644 --- a/wled00/FX_2Dfcn.cpp +++ b/wled00/FX_2Dfcn.cpp @@ -36,14 +36,9 @@ // so matrix should disable regular ledmap processing void WS2812FX::setUpMatrix() { #ifndef WLED_DISABLE_2D - // erase old ledmap, just in case. - if (customMappingTable != nullptr) delete[] customMappingTable; - customMappingTable = nullptr; - customMappingSize = 0; - // isMatrix is set in cfg.cpp or set.cpp if (isMatrix) { - // calculate width dynamically because it will have gaps + // calculate width dynamically because it may have gaps Segment::maxWidth = 1; Segment::maxHeight = 1; for (size_t i = 0; i < panel.size(); i++) { @@ -68,15 +63,17 @@ void WS2812FX::setUpMatrix() { return; } - customMappingTable = new uint16_t[Segment::maxWidth * Segment::maxHeight]; + customMappingSize = 0; // prevent use of mapping if anything goes wrong + + if (customMappingTable == nullptr) customMappingTable = new uint16_t[getLengthTotal()]; if (customMappingTable != nullptr) { - customMappingSize = Segment::maxWidth * Segment::maxHeight; + customMappingSize = getLengthTotal(); // fill with empty in case we don't fill the entire matrix - for (size_t i = 0; i< customMappingSize; i++) { - customMappingTable[i] = (uint16_t)-1; - } + unsigned matrixSize = Segment::maxWidth * Segment::maxHeight; + for (unsigned i = 0; i(); + JsonArray map = pDoc->as(); gapSize = map.size(); - if (!map.isNull() && gapSize >= customMappingSize) { // not an empty map + if (!map.isNull() && gapSize >= matrixSize) { // not an empty map gapTable = new int8_t[gapSize]; if (gapTable) for (size_t i = 0; i < gapSize; i++) { gapTable[i] = constrain(map[i], -1, 1); diff --git a/wled00/FX_fcn.cpp b/wled00/FX_fcn.cpp index 42984a051..c67967f40 100644 --- a/wled00/FX_fcn.cpp +++ b/wled00/FX_fcn.cpp @@ -143,27 +143,28 @@ Segment& Segment::operator= (Segment &&orig) noexcept { return *this; } +// allocates effect data buffer on heap and initialises (erases) it bool IRAM_ATTR Segment::allocateData(size_t len) { + if (len == 0) return false; // nothing to do if (data && _dataLen >= len) { // already allocated enough (reduce fragmentation) if (call == 0) memset(data, 0, len); // erase buffer if called during effect initialisation return true; } //DEBUG_PRINTF("-- Allocating data (%d): %p\n", len, this); - deallocateData(); - if (len == 0) return false; // nothing to do + deallocateData(); // if the old buffer was smaller release it first if (Segment::getUsedSegmentData() + len > MAX_SEGMENT_DATA) { // not enough memory DEBUG_PRINT(F("!!! Effect RAM depleted: ")); DEBUG_PRINTF("%d/%d !!!\n", len, Segment::getUsedSegmentData()); + errorFlag = ERR_NORAM; return false; } // do not use SPI RAM on ESP32 since it is slow - data = (byte*) malloc(len); + data = (byte*)calloc(len, sizeof(byte)); if (!data) { DEBUG_PRINTLN(F("!!! Allocation failed. !!!")); return false; } // allocation failed Segment::addUsedSegmentData(len); //DEBUG_PRINTF("--- Allocated data (%p): %d/%d -> %p\n", this, len, Segment::getUsedSegmentData(), data); _dataLen = len; - memset(data, 0, len); return true; } @@ -194,7 +195,7 @@ void IRAM_ATTR Segment::deallocateData() { void Segment::resetIfRequired() { if (!reset) return; //DEBUG_PRINTF("-- Segment reset: %p\n", this); - deallocateData(); + if (data && _dataLen > 0) memset(data, 0, _dataLen); // prevent heap fragmentation (just erase buffer instead of deallocateData()) next_time = 0; step = 0; call = 0; aux0 = 0; aux1 = 0; reset = false; } @@ -424,7 +425,7 @@ uint8_t IRAM_ATTR Segment::currentBri(bool useCct) { uint32_t prog = progress(); if (prog < 0xFFFFU) { uint32_t curBri = (useCct ? cct : (on ? opacity : 0)) * prog; - curBri += (useCct ? _t->_cctT : (on ? _t->_briT : 0)) * (0xFFFFU - prog); + curBri += (useCct ? _t->_cctT : _t->_briT) * (0xFFFFU - prog); return curBri / 0xFFFFU; } return (useCct ? cct : (on ? opacity : 0)); @@ -439,6 +440,7 @@ uint8_t IRAM_ATTR Segment::currentMode() { } uint32_t IRAM_ATTR Segment::currentColor(uint8_t slot) { + if (slot >= NUM_COLORS) slot = 0; #ifndef WLED_DISABLE_MODE_BLEND return isInTransition() ? color_blend(_t->_segT._colorT[slot], colors[slot], progress(), true) : colors[slot]; #else @@ -468,7 +470,7 @@ void Segment::handleRandomPalette() { } // segId is given when called from network callback, changes are queued if that segment is currently in its effect function -void Segment::setUp(uint16_t i1, uint16_t i2, uint8_t grp, uint8_t spc, uint16_t ofs, uint16_t i1Y, uint16_t i2Y, uint8_t segId) { +void Segment::setUp(uint16_t i1, uint16_t i2, uint8_t grp, uint8_t spc, uint16_t ofs, uint16_t i1Y, uint16_t i2Y) { // return if neither bounds nor grouping have changed bool boundsUnchanged = (start == i1 && stop == i2); #ifndef WLED_DISABLE_2D @@ -561,35 +563,36 @@ void Segment::setOption(uint8_t n, bool val) { } void Segment::setMode(uint8_t fx, bool loadDefaults) { + // skip reserved + while (fx < strip.getModeCount() && strncmp_P("RSVD", strip.getModeData(fx), 4) == 0) fx++; + if (fx >= strip.getModeCount()) fx = 0; // set solid mode // if we have a valid mode & is not reserved - if (fx < strip.getModeCount() && strncmp_P("RSVD", strip.getModeData(fx), 4)) { - if (fx != mode) { + if (fx != mode) { #ifndef WLED_DISABLE_MODE_BLEND - if (modeBlending) startTransition(strip.getTransition()); // set effect transitions + if (modeBlending) startTransition(strip.getTransition()); // set effect transitions #endif - mode = fx; - // load default values from effect string - if (loadDefaults) { - int16_t sOpt; - sOpt = extractModeDefaults(fx, "sx"); speed = (sOpt >= 0) ? sOpt : DEFAULT_SPEED; - sOpt = extractModeDefaults(fx, "ix"); intensity = (sOpt >= 0) ? sOpt : DEFAULT_INTENSITY; - sOpt = extractModeDefaults(fx, "c1"); custom1 = (sOpt >= 0) ? sOpt : DEFAULT_C1; - sOpt = extractModeDefaults(fx, "c2"); custom2 = (sOpt >= 0) ? sOpt : DEFAULT_C2; - sOpt = extractModeDefaults(fx, "c3"); custom3 = (sOpt >= 0) ? sOpt : DEFAULT_C3; - sOpt = extractModeDefaults(fx, "o1"); check1 = (sOpt >= 0) ? (bool)sOpt : false; - sOpt = extractModeDefaults(fx, "o2"); check2 = (sOpt >= 0) ? (bool)sOpt : false; - sOpt = extractModeDefaults(fx, "o3"); check3 = (sOpt >= 0) ? (bool)sOpt : false; - sOpt = extractModeDefaults(fx, "m12"); if (sOpt >= 0) map1D2D = constrain(sOpt, 0, 7); else map1D2D = M12_Pixels; // reset mapping if not defined (2D FX may not work) - sOpt = extractModeDefaults(fx, "si"); if (sOpt >= 0) soundSim = constrain(sOpt, 0, 3); - sOpt = extractModeDefaults(fx, "rev"); if (sOpt >= 0) reverse = (bool)sOpt; - sOpt = extractModeDefaults(fx, "mi"); if (sOpt >= 0) mirror = (bool)sOpt; // NOTE: setting this option is a risky business - sOpt = extractModeDefaults(fx, "rY"); if (sOpt >= 0) reverse_y = (bool)sOpt; - sOpt = extractModeDefaults(fx, "mY"); if (sOpt >= 0) mirror_y = (bool)sOpt; // NOTE: setting this option is a risky business - sOpt = extractModeDefaults(fx, "pal"); if (sOpt >= 0) setPalette(sOpt); //else setPalette(0); - } - markForReset(); - stateChanged = true; // send UDP/WS broadcast + mode = fx; + // load default values from effect string + if (loadDefaults) { + int16_t sOpt; + sOpt = extractModeDefaults(fx, "sx"); speed = (sOpt >= 0) ? sOpt : DEFAULT_SPEED; + sOpt = extractModeDefaults(fx, "ix"); intensity = (sOpt >= 0) ? sOpt : DEFAULT_INTENSITY; + sOpt = extractModeDefaults(fx, "c1"); custom1 = (sOpt >= 0) ? sOpt : DEFAULT_C1; + sOpt = extractModeDefaults(fx, "c2"); custom2 = (sOpt >= 0) ? sOpt : DEFAULT_C2; + sOpt = extractModeDefaults(fx, "c3"); custom3 = (sOpt >= 0) ? sOpt : DEFAULT_C3; + sOpt = extractModeDefaults(fx, "o1"); check1 = (sOpt >= 0) ? (bool)sOpt : false; + sOpt = extractModeDefaults(fx, "o2"); check2 = (sOpt >= 0) ? (bool)sOpt : false; + sOpt = extractModeDefaults(fx, "o3"); check3 = (sOpt >= 0) ? (bool)sOpt : false; + sOpt = extractModeDefaults(fx, "m12"); if (sOpt >= 0) map1D2D = constrain(sOpt, 0, 7); else map1D2D = M12_Pixels; // reset mapping if not defined (2D FX may not work) + sOpt = extractModeDefaults(fx, "si"); if (sOpt >= 0) soundSim = constrain(sOpt, 0, 3); + sOpt = extractModeDefaults(fx, "rev"); if (sOpt >= 0) reverse = (bool)sOpt; + sOpt = extractModeDefaults(fx, "mi"); if (sOpt >= 0) mirror = (bool)sOpt; // NOTE: setting this option is a risky business + sOpt = extractModeDefaults(fx, "rY"); if (sOpt >= 0) reverse_y = (bool)sOpt; + sOpt = extractModeDefaults(fx, "mY"); if (sOpt >= 0) mirror_y = (bool)sOpt; // NOTE: setting this option is a risky business + sOpt = extractModeDefaults(fx, "pal"); if (sOpt >= 0) setPalette(sOpt); //else setPalette(0); } + markForReset(); + stateChanged = true; // send UDP/WS broadcast } } @@ -751,10 +754,10 @@ void IRAM_ATTR Segment::setPixelColor(int i, uint32_t col) uint32_t tmpCol = col; // set all the pixels in the group for (int j = 0; j < grouping; j++) { - uint16_t indexSet = i + ((reverse) ? -j : j); + unsigned indexSet = i + ((reverse) ? -j : j); if (indexSet >= start && indexSet < stop) { if (mirror) { //set the corresponding mirrored pixel - uint16_t indexMir = stop - indexSet + start - 1; + unsigned indexMir = stop - indexSet + start - 1; indexMir += offset; // offset/phase if (indexMir >= stop) indexMir -= len; // wrap #ifndef WLED_DISABLE_MODE_BLEND @@ -884,8 +887,7 @@ void Segment::refreshLightCapabilities() { if (start < Segment::maxWidth * Segment::maxHeight) { // we are withing 2D matrix (includes 1D segments) for (int y = startY; y < stopY; y++) for (int x = start; x < stop; x++) { - uint16_t index = x + Segment::maxWidth * y; - if (index < strip.customMappingSize) index = strip.customMappingTable[index]; // convert logical address to physical + uint16_t index = strip.getMappedPixelIndex(x + Segment::maxWidth * y); // convert logical address to physical if (index < 0xFFFFU) { if (segStartIdx > index) segStartIdx = index; if (segStopIdx < index) segStopIdx = index; @@ -898,8 +900,8 @@ void Segment::refreshLightCapabilities() { segStopIdx = stop; } - for (unsigned b = 0; b < busses.getNumBusses(); b++) { - Bus *bus = busses.getBus(b); + for (unsigned b = 0; b < BusManager::getNumBusses(); b++) { + Bus *bus = BusManager::getBus(b); if (bus == nullptr || bus->getLength()==0) break; if (!bus->isOk()) continue; if (bus->getStart() >= segStopIdx) continue; @@ -1024,7 +1026,7 @@ void Segment::blur(uint8_t blur_amount) { * Inspired by the Adafruit examples. */ uint32_t Segment::color_wheel(uint8_t pos) { - if (palette) return color_from_palette(pos, false, true, 0); + if (palette) return color_from_palette(pos, false, true, 0); // perhaps "strip.paletteBlend < 2" should be better instead of "true" uint8_t w = W(currentColor(0)); pos = 255 - pos; if (pos < 85) { @@ -1055,6 +1057,7 @@ uint32_t Segment::color_from_palette(uint16_t i, bool mapping, bool wrap, uint8_ uint8_t paletteIndex = i; if (mapping && virtualLength() > 1) paletteIndex = (i*255)/(virtualLength() -1); + // paletteBlend: 0 - wrap when moving, 1 - always wrap, 2 - never wrap, 3 - none (undefined) if (!wrap && strip.paletteBlend != 3) paletteIndex = scale8(paletteIndex, 240); //cut off blend at palette "end" CRGBPalette16 curPal; curPal = currentPalette(curPal, palette); @@ -1084,7 +1087,7 @@ void WS2812FX::finalizeInit(void) { _hasWhiteChannel = _isOffRefreshRequired = false; //if busses failed to load, add default (fresh install, FS issue, ...) - if (busses.getNumBusses() == 0) { + if (BusManager::getNumBusses() == 0) { DEBUG_PRINTLN(F("No busses, init default")); const uint8_t defDataPins[] = {DATA_PINS}; const uint16_t defCounts[] = {PIXEL_COUNTS}; @@ -1097,13 +1100,13 @@ void WS2812FX::finalizeInit(void) { uint16_t count = defCounts[(i < defNumCounts) ? i : defNumCounts -1]; prevLen += count; BusConfig defCfg = BusConfig(DEFAULT_LED_TYPE, defPin, start, count, DEFAULT_LED_COLOR_ORDER, false, 0, RGBW_MODE_MANUAL_ONLY); - if (busses.add(defCfg) == -1) break; + if (BusManager::add(defCfg) == -1) break; } } _length = 0; - for (int i=0; igetStart() + bus->getLength() > MAX_LEDS) break; //RGBW mode is enabled if at least one of the strips is RGBW @@ -1121,29 +1124,28 @@ void WS2812FX::finalizeInit(void) { #endif } - if (isMatrix) setUpMatrix(); - else { - Segment::maxWidth = _length; - Segment::maxHeight = 1; - } + Segment::maxWidth = _length; + Segment::maxHeight = 1; //segments are created in makeAutoSegments(); DEBUG_PRINTLN(F("Loading custom palettes")); loadCustomPalettes(); // (re)load all custom palettes DEBUG_PRINTLN(F("Loading custom ledmaps")); - deserializeMap(); // (re)load default ledmap + deserializeMap(); // (re)load default ledmap (will also setUpMatrix() if ledmap does not exist) } void WS2812FX::service() { unsigned long nowUp = millis(); // Be aware, millis() rolls over every 49 days now = nowUp + timebase; - if (nowUp - _lastShow < MIN_SHOW_DELAY) return; + if (nowUp - _lastShow < MIN_SHOW_DELAY || _suspend) return; bool doShow = false; _isServicing = true; _segment_index = 0; Segment::handleRandomPalette(); // move it into for loop when each segment has individual random palette for (segment &seg : _segments) { + if (_suspend) return; // immediately stop processing segments if suspend requested during service() + // process transition (mode changes in the middle of transition) seg.handleTransition(); // reset the segment runtime data if needed @@ -1163,7 +1165,7 @@ void WS2812FX::service() { _colors_t[1] = gamma32(seg.currentColor(1)); _colors_t[2] = gamma32(seg.currentColor(2)); seg.currentPalette(_currentPalette, seg.palette); // we need to pass reference - if (!cctFromRgb || correctWB) busses.setSegmentCCT(seg.currentBri(true), correctWB); + if (!cctFromRgb || correctWB) BusManager::setSegmentCCT(seg.currentBri(true), correctWB); // Effect blending // When two effects are being blended, each may have different segment data, this // data needs to be saved first and then restored before running previous mode. @@ -1190,11 +1192,11 @@ void WS2812FX::service() { seg.next_time = nowUp + delay; } - if (_segment_index == _queuedChangesSegId) setUpSegmentFromQueuedChanges(); +// if (_segment_index == _queuedChangesSegId) setUpSegmentFromQueuedChanges(); _segment_index++; } _virtualSegmentLength = 0; - busses.setSegmentCCT(-1); + BusManager::setSegmentCCT(-1); _isServicing = false; _triggered = false; @@ -1210,16 +1212,16 @@ void WS2812FX::service() { #endif } -void IRAM_ATTR WS2812FX::setPixelColor(int i, uint32_t col) { - if (i < customMappingSize) i = customMappingTable[i]; +void IRAM_ATTR WS2812FX::setPixelColor(unsigned i, uint32_t col) { + i = getMappedPixelIndex(i); if (i >= _length) return; - busses.setPixelColor(i, col); + BusManager::setPixelColor(i, col); } uint32_t IRAM_ATTR WS2812FX::getPixelColor(uint16_t i) { - if (i < customMappingSize) i = customMappingTable[i]; + i = getMappedPixelIndex(i); if (i >= _length) return 0; - return busses.getPixelColor(i); + return BusManager::getPixelColor(i); } void WS2812FX::show(void) { @@ -1230,7 +1232,7 @@ void WS2812FX::show(void) { // some buses send asynchronously and this method will return before // all of the data has been sent. // See https://github.com/Makuna/NeoPixelBus/wiki/ESP32-NeoMethods#neoesp32rmt-methods - busses.show(); + BusManager::show(); unsigned long showNow = millis(); size_t diff = showNow - _lastShow; @@ -1245,7 +1247,7 @@ void WS2812FX::show(void) { * On some hardware (ESP32), strip updates are done asynchronously. */ bool WS2812FX::isUpdating() { - return !busses.canAllShow(); + return !BusManager::canAllShow(); } /** @@ -1304,7 +1306,7 @@ void WS2812FX::setBrightness(uint8_t b, bool direct) { } // setting brightness with NeoPixelBusLg has no effect on already painted pixels, // so we need to force an update to existing buffer - busses.setBrightness(b); + BusManager::setBrightness(b); if (!direct) { unsigned long t = millis(); if (_segments[0].next_time > t + 22 && t - _lastShow > MIN_SHOW_DELAY) trigger(); //apply brightness change immediately if no refresh soon @@ -1360,8 +1362,8 @@ uint16_t WS2812FX::getLengthTotal(void) { uint16_t WS2812FX::getLengthPhysical(void) { uint16_t len = 0; - for (size_t b = 0; b < busses.getNumBusses(); b++) { - Bus *bus = busses.getBus(b); + for (size_t b = 0; b < BusManager::getNumBusses(); b++) { + Bus *bus = BusManager::getBus(b); if (bus->getType() >= TYPE_NET_DDP_RGB) continue; //exclude non-physical network busses len += bus->getLength(); } @@ -1372,8 +1374,8 @@ uint16_t WS2812FX::getLengthPhysical(void) { //returns if there is an RGBW bus (supports RGB and White, not only white) //not influenced by auto-white mode, also true if white slider does not affect output white channel bool WS2812FX::hasRGBWBus(void) { - for (size_t b = 0; b < busses.getNumBusses(); b++) { - Bus *bus = busses.getBus(b); + for (size_t b = 0; b < BusManager::getNumBusses(); b++) { + Bus *bus = BusManager::getBus(b); if (bus == nullptr || bus->getLength()==0) break; if (bus->hasRGB() && bus->hasWhite()) return true; } @@ -1382,8 +1384,8 @@ bool WS2812FX::hasRGBWBus(void) { bool WS2812FX::hasCCTBus(void) { if (cctFromRgb && !correctWB) return false; - for (size_t b = 0; b < busses.getNumBusses(); b++) { - Bus *bus = busses.getBus(b); + for (size_t b = 0; b < BusManager::getNumBusses(); b++) { + Bus *bus = BusManager::getBus(b); if (bus == nullptr || bus->getLength()==0) break; switch (bus->getType()) { case TYPE_ANALOG_5CH: @@ -1394,18 +1396,18 @@ bool WS2812FX::hasCCTBus(void) { return false; } -void WS2812FX::purgeSegments(bool force) { +void WS2812FX::purgeSegments() { // remove all inactive segments (from the back) int deleted = 0; if (_segments.size() <= 1) return; for (size_t i = _segments.size()-1; i > 0; i--) - if (_segments[i].stop == 0 || force) { + if (_segments[i].stop == 0) { deleted++; _segments.erase(_segments.begin() + i); } if (deleted) { _segments.shrink_to_fit(); - /*if (_mainSegment >= _segments.size())*/ setMainSegmentId(0); + setMainSegmentId(0); } } @@ -1420,7 +1422,7 @@ void WS2812FX::setSegment(uint8_t segId, uint16_t i1, uint16_t i2, uint8_t group appendSegment(Segment(0, strip.getLengthTotal())); segId = getSegmentsNum()-1; // segments are added at the end of list } - +/* if (_queuedChangesSegId == segId) _queuedChangesSegId = 255; // cancel queued change if already queued for this segment if (segId < getMaxSegments() && segId == getCurrSegmentId() && isServicing()) { // queue change to prevent concurrent access @@ -1432,17 +1434,19 @@ void WS2812FX::setSegment(uint8_t segId, uint16_t i1, uint16_t i2, uint8_t group DEBUG_PRINT(F("Segment queued: ")); DEBUG_PRINTLN(segId); return; // queued changes are applied immediately after effect function returns } - +*/ + suspend(); _segments[segId].setUp(i1, i2, grouping, spacing, offset, startY, stopY); + resume(); if (segId > 0 && segId == getSegmentsNum()-1 && i2 <= i1) _segments.pop_back(); // if last segment was deleted remove it from vector } - +/* void WS2812FX::setUpSegmentFromQueuedChanges() { if (_queuedChangesSegId >= getSegmentsNum()) return; - getSegment(_queuedChangesSegId).setUp(_qStart, _qStop, _qGrouping, _qSpacing, _qOffset, _qStartY, _qStopY); + _segments[_queuedChangesSegId].setUp(_qStart, _qStop, _qGrouping, _qSpacing, _qOffset, _qStartY, _qStopY); _queuedChangesSegId = 255; } - +*/ void WS2812FX::resetSegments() { _segments.clear(); // destructs all Segment as part of clearing #ifndef WLED_DISABLE_2D @@ -1469,8 +1473,8 @@ void WS2812FX::makeAutoSegments(bool forceReset) { } #endif - for (size_t i = s; i < busses.getNumBusses(); i++) { - Bus* b = busses.getBus(i); + for (size_t i = s; i < BusManager::getNumBusses(); i++) { + Bus* b = BusManager::getBus(i); segStarts[s] = b->getStart(); segStops[s] = segStarts[s] + b->getLength(); @@ -1559,8 +1563,8 @@ void WS2812FX::fixInvalidSegments() { bool WS2812FX::checkSegmentAlignment() { bool aligned = false; for (segment &seg : _segments) { - for (unsigned b = 0; bgetStart() && seg.stop == bus->getStart() + bus->getLength()) aligned = true; } if (seg.start == 0 && seg.stop == _length) aligned = true; @@ -1569,18 +1573,7 @@ bool WS2812FX::checkSegmentAlignment() { return true; } -//After this function is called, setPixelColor() will use that segment (offsets, grouping, ... will apply) -//Note: If called in an interrupt (e.g. JSON API), original segment must be restored, -//otherwise it can lead to a crash on ESP32 because _segment_index is modified while in use by the main thread -uint8_t WS2812FX::setPixelSegment(uint8_t n) { - uint8_t prevSegId = _segment_index; - if (n < _segments.size()) { - _segment_index = n; - _virtualSegmentLength = _segments[_segment_index].virtualLength(); - } - return prevSegId; -} - +// used by analog clock overlay void WS2812FX::setRange(uint16_t i, uint16_t i2, uint32_t col) { if (i2 < i) std::swap(i,i2); for (unsigned x = i; x <= i2; x++) setPixelColor(x, col); @@ -1658,46 +1651,44 @@ bool WS2812FX::deserializeMap(uint8_t n) { strcat_P(fileName, PSTR(".json")); bool isFile = WLED_FS.exists(fileName); - if (!isFile) { - // erase custom mapping if selecting nonexistent ledmap.json (n==0) - if (!isMatrix && !n && customMappingTable != nullptr) { - customMappingSize = 0; - delete[] customMappingTable; - customMappingTable = nullptr; - } + customMappingSize = 0; // prevent use of mapping if anything goes wrong + + if (!isFile && n==0 && isMatrix) { + setUpMatrix(); return false; } - if (!requestJSONBufferLock(7)) return false; + if (!isFile || !requestJSONBufferLock(7)) return false; // this will trigger setUpMatrix() when called from wled.cpp - if (!readObjectFromFile(fileName, nullptr, &doc)) { + if (!readObjectFromFile(fileName, nullptr, pDoc)) { + DEBUG_PRINT(F("ERROR Invalid ledmap in ")); DEBUG_PRINTLN(fileName); releaseJSONBufferLock(); - return false; //if file does not exist just exit + return false; // if file does not load properly then exit } - DEBUG_PRINT(F("Reading LED map from ")); - DEBUG_PRINTLN(fileName); + DEBUG_PRINT(F("Reading LED map from ")); DEBUG_PRINTLN(fileName); - // erase old custom ledmap - if (customMappingTable != nullptr) { - customMappingSize = 0; - delete[] customMappingTable; - customMappingTable = nullptr; - } + if (customMappingTable == nullptr) customMappingTable = new uint16_t[getLengthTotal()]; - JsonArray map = doc[F("map")]; + JsonObject root = pDoc->as(); + JsonArray map = root[F("map")]; if (!map.isNull() && map.size()) { // not an empty map - customMappingSize = map.size(); - customMappingTable = new uint16_t[customMappingSize]; - for (unsigned i=0; i COL_ORDER_MAX) { + // upper nibble contains W swap information + if ((colorOrder & 0x0F) > COL_ORDER_MAX) { return; } _mappings[_count].start = start; @@ -63,12 +64,13 @@ void ColorOrderMap::add(uint16_t start, uint16_t len, uint8_t colorOrder) { } uint8_t IRAM_ATTR ColorOrderMap::getPixelColorOrder(uint16_t pix, uint8_t defaultColorOrder) const { - if (_count == 0) return defaultColorOrder; - // upper nibble containd W swap information - uint8_t swapW = defaultColorOrder >> 4; - for (unsigned i = 0; i < _count; i++) { - if (pix >= _mappings[i].start && pix < (_mappings[i].start + _mappings[i].len)) { - return _mappings[i].colorOrder | (swapW << 4); + if (_count > 0) { + // upper nibble contains W swap information + // when ColorOrderMap's upper nibble contains value >0 then swap information is used from it, otherwise global swap is used + for (unsigned i = 0; i < _count; i++) { + if (pix >= _mappings[i].start && pix < (_mappings[i].start + _mappings[i].len)) { + return _mappings[i].colorOrder | ((_mappings[i].colorOrder >> 4) ? 0 : (defaultColorOrder & 0xF0)); + } } } return defaultColorOrder; @@ -125,7 +127,7 @@ BusDigital::BusDigital(BusConfig &bc, uint8_t nr, const ColorOrderMap &com) if (bc.type == TYPE_WS2812_1CH_X3) lenToCreate = NUM_ICS_WS2812_1CH_3X(bc.count); // only needs a third of "RGB" LEDs for NeoPixelBus _busPtr = PolyBus::create(_iType, _pins, lenToCreate + _skip, nr, _frequencykHz); _valid = (_busPtr != nullptr); - DEBUG_PRINTF("%successfully inited strip %u (len %u) with type %u and pins %u,%u (itype %u)\n", _valid?"S":"Uns", nr, bc.count, bc.type, _pins[0], _pins[1], _iType); + DEBUG_PRINTF("%successfully inited strip %u (len %u) with type %u and pins %u,%u (itype %u). mA=%d/%d\n", _valid?"S":"Uns", nr, bc.count, bc.type, _pins[0], _pins[1], _iType, _milliAmpsPerLed, _milliAmpsMax); } //fine tune power estimation constants for your setup @@ -150,7 +152,7 @@ uint8_t BusDigital::estimateCurrentAndLimitBri() { bool useWackyWS2815PowerModel = false; byte actualMilliampsPerLed = _milliAmpsPerLed; - if (_milliAmpsMax < MA_FOR_ESP || actualMilliampsPerLed == 0) { //0 mA per LED and too low numbers turn off calculation + if (_milliAmpsMax < MA_FOR_ESP/BusManager::getNumBusses() || actualMilliampsPerLed == 0) { //0 mA per LED and too low numbers turn off calculation return _bri; } @@ -159,7 +161,12 @@ uint8_t BusDigital::estimateCurrentAndLimitBri() { actualMilliampsPerLed = 12; // from testing an actual strip } - size_t powerBudget = (_milliAmpsMax - MA_FOR_ESP); //100mA for ESP power + size_t powerBudget = (_milliAmpsMax - MA_FOR_ESP/BusManager::getNumBusses()); //80/120mA for ESP power + if (powerBudget > getLength()) { //each LED uses about 1mA in standby, exclude that from power budget + powerBudget -= getLength(); + } else { + powerBudget = 0; + } uint32_t busPowerSum = 0; for (unsigned i = 0; i < getLength(); i++) { //sum up the usage of each LED @@ -178,29 +185,26 @@ uint8_t BusDigital::estimateCurrentAndLimitBri() { busPowerSum >>= 2; //same as /= 4 } - if (powerBudget > getLength()) { //each LED uses about 1mA in standby, exclude that from power budget - powerBudget -= getLength(); - } else { - powerBudget = 0; - } - // powerSum has all the values of channels summed (max would be getLength()*765 as white is excluded) so convert to milliAmps busPowerSum = (busPowerSum * actualMilliampsPerLed) / 765; + _milliAmpsTotal = busPowerSum * _bri / 255; uint8_t newBri = _bri; if (busPowerSum * _bri / 255 > powerBudget) { //scale brightness down to stay in current limit float scale = (float)(powerBudget * 255) / (float)(busPowerSum * _bri); - uint16_t scaleI = scale * 255; - uint8_t scaleB = (scaleI > 255) ? 255 : scaleI; + if (scale >= 1.0f) return _bri; + _milliAmpsTotal = ceilf((float)_milliAmpsTotal * scale); + uint8_t scaleB = min((int)(scale * 255), 255); newBri = unsigned(_bri * scaleB) / 256 + 1; } return newBri; } void BusDigital::show() { + _milliAmpsTotal = 0; if (!_valid) return; - uint8_t newBri = estimateCurrentAndLimitBri(); + uint8_t newBri = estimateCurrentAndLimitBri(); // will fill _milliAmpsTotal if (newBri < _bri) PolyBus::setBrightness(_busPtr, _iType, newBri); // limit brightness to stay within current limits if (_data) { // use _buffering this causes ~20% FPS drop @@ -258,23 +262,8 @@ void BusDigital::setBrightness(uint8_t b) { if (_pins[0] == LED_BUILTIN || _pins[1] == LED_BUILTIN) reinit(); } #endif - uint8_t prevBri = _bri; Bus::setBrightness(b); PolyBus::setBrightness(_busPtr, _iType, b); -/* - if (_data) return; // use _buffering this causes ~20% FPS drop - - // must update/repaint every LED in the NeoPixelBus buffer to the new brightness - // the only case where repainting is unnecessary is when all pixels are set after the brightness change but before the next show - // (which we can't rely on) - uint16_t hwLen = _len; - if (_type == TYPE_WS2812_1CH_X3) hwLen = NUM_ICS_WS2812_1CH_3X(_len); // only needs a third of "RGB" LEDs for NeoPixelBus - for (unsigned i = 0; i < hwLen; i++) { - // use 0 as color order, actual order does not matter here as we just update the channel values as-is - uint32_t c = restoreColorLossy(PolyBus::getPixelColor(_busPtr, _iType, i, 0), prevBri); - PolyBus::setPixelColor(_busPtr, _iType, i, c, 0); - } -*/ } //If LEDs are skipped, it is possible to use the first as a status LED. @@ -617,29 +606,34 @@ void BusNetwork::cleanup() { //utility to get the approx. memory usage of a given BusConfig uint32_t BusManager::memUsage(BusConfig &bc) { - uint8_t type = bc.type; + if (bc.type == TYPE_ONOFF || IS_PWM(bc.type)) return 5; + uint16_t len = bc.count + bc.skipAmount; - if (type > 15 && type < 32) { // digital types - if (type == TYPE_UCS8903 || type == TYPE_UCS8904) len *= 2; // 16-bit LEDs + uint16_t channels = 3; + uint16_t multiplier = 1; + if (IS_DIGITAL(bc.type)) { // digital types + if (IS_16BIT(bc.type)) len *= 2; // 16-bit LEDs #ifdef ESP8266 + if (bc.type > 28) channels = 4; //RGBW if (bc.pins[0] == 3) { //8266 DMA uses 5x the mem - if (type > 28) return len*20; //RGBW - return len*15; + multiplier = 5; } - if (type > 28) return len*4; //RGBW - return len*3; - #else //ESP32 RMT uses double buffer? - if (type > 28) return len*8; //RGBW - return len*6; + #else //ESP32 RMT uses double buffer, I2S uses 5x buffer + if (bc.type > 28) channels = 4; //RGBW + multiplier = 2; #endif } - if (type > 31 && type < 48) return 5; - return len*3; //RGB + if (IS_VIRTUAL(bc.type)) { + switch (bc.type) { + case TYPE_NET_DDP_RGBW: channels = 4; break; + } + } + return len * channels * multiplier; //RGB } int BusManager::add(BusConfig &bc) { if (getNumBusses() - getNumVirtualBusses() >= WLED_MAX_BUSSES) return -1; - if (bc.type >= TYPE_NET_DDP_RGB && bc.type < 96) { + if (IS_VIRTUAL(bc.type)) { busses[numBusses] = new BusNetwork(bc); } else if (IS_DIGITAL(bc.type)) { busses[numBusses] = new BusDigital(bc, numBusses, colorOrderMap); @@ -661,9 +655,12 @@ void BusManager::removeAll() { } void BusManager::show() { + _milliAmpsUsed = 0; for (unsigned i = 0; i < numBusses; i++) { busses[i]->show(); + _milliAmpsUsed += busses[i]->getUsedCurrent(); } + if (_milliAmpsUsed) _milliAmpsUsed += MA_FOR_ESP; } void BusManager::setStatusPixel(uint32_t c) { @@ -729,3 +726,11 @@ uint16_t BusManager::getTotalLength() { int16_t Bus::_cct = -1; uint8_t Bus::_cctBlend = 0; uint8_t Bus::_gAWM = 255; + +uint16_t BusDigital::_milliAmpsTotal = 0; + +uint8_t BusManager::numBusses = 0; +Bus* BusManager::busses[WLED_MAX_BUSSES+WLED_MIN_VIRTUAL_BUSSES]; +ColorOrderMap BusManager::colorOrderMap = {}; +uint16_t BusManager::_milliAmpsUsed = 0; +uint16_t BusManager::_milliAmpsMax = ABL_MILLIAMPS_DEFAULT; \ No newline at end of file diff --git a/wled00/bus_manager.h b/wled00/bus_manager.h index 9d322749c..b2dbd50fa 100644 --- a/wled00/bus_manager.h +++ b/wled00/bus_manager.h @@ -129,14 +129,14 @@ class Bus { virtual void setPixelColor(uint16_t pix, uint32_t c) = 0; virtual uint32_t getPixelColor(uint16_t pix) { return 0; } virtual void setBrightness(uint8_t b) { _bri = b; }; - virtual void cleanup() = 0; virtual uint8_t getPins(uint8_t* pinArray) { return 0; } virtual uint16_t getLength() { return _len; } - virtual void setColorOrder() {} + virtual void setColorOrder(uint8_t co) {} virtual uint8_t getColorOrder() { return COL_ORDER_RGB; } virtual uint8_t skippedLeds() { return 0; } virtual uint16_t getFrequency() { return 0U; } virtual uint16_t getLEDCurrent() { return 0; } + virtual uint16_t getUsedCurrent() { return 0; } virtual uint16_t getMaxCurrent() { return 0; } inline void setReversed(bool reversed) { _reversed = reversed; } inline uint16_t getStart() { return _start; } @@ -206,20 +206,21 @@ class BusDigital : public Bus { BusDigital(BusConfig &bc, uint8_t nr, const ColorOrderMap &com); ~BusDigital() { cleanup(); } - void show(); - bool canShow(); - void setBrightness(uint8_t b); - void setStatusPixel(uint32_t c); - void setPixelColor(uint16_t pix, uint32_t c); - void setColorOrder(uint8_t colorOrder); - uint32_t getPixelColor(uint16_t pix); - uint8_t getColorOrder() { return _colorOrder; } - uint8_t getPins(uint8_t* pinArray); - uint8_t skippedLeds() { return _skip; } - uint16_t getFrequency() { return _frequencykHz; } + void show() override; + bool canShow() override; + void setBrightness(uint8_t b) override; + void setStatusPixel(uint32_t c) override; + void setPixelColor(uint16_t pix, uint32_t c) override; + void setColorOrder(uint8_t colorOrder) override; + uint32_t getPixelColor(uint16_t pix) override; + uint8_t getColorOrder() override { return _colorOrder; } + uint8_t getPins(uint8_t* pinArray) override; + uint8_t skippedLeds() override { return _skip; } + uint16_t getFrequency() override { return _frequencykHz; } uint8_t estimateCurrentAndLimitBri(); - uint16_t getLEDCurrent() { return _milliAmpsPerLed; } - uint16_t getMaxCurrent() { return _milliAmpsMax; } + uint16_t getLEDCurrent() override { return _milliAmpsPerLed; } + uint16_t getUsedCurrent() override { return _milliAmpsTotal; } + uint16_t getMaxCurrent() override { return _milliAmpsMax; } void reinit(); void cleanup(); @@ -233,7 +234,8 @@ class BusDigital : public Bus { uint16_t _milliAmpsMax; void * _busPtr; const ColorOrderMap &_colorOrderMap; - //bool _buffering; // temporary until we figure out why comparison "_data" causes severe FPS drop + + static uint16_t _milliAmpsTotal; // is overwitten/recalculated on each show() inline uint32_t restoreColorLossy(uint32_t c, uint8_t restoreBri) { if (restoreBri < 255) { @@ -253,11 +255,11 @@ class BusPwm : public Bus { BusPwm(BusConfig &bc); ~BusPwm() { cleanup(); } - void setPixelColor(uint16_t pix, uint32_t c); - uint32_t getPixelColor(uint16_t pix); //does no index check - uint8_t getPins(uint8_t* pinArray); - uint16_t getFrequency() { return _frequency; } - void show(); + void setPixelColor(uint16_t pix, uint32_t c) override; + uint32_t getPixelColor(uint16_t pix) override; //does no index check + uint8_t getPins(uint8_t* pinArray) override; + uint16_t getFrequency() override { return _frequency; } + void show() override; void cleanup() { deallocatePins(); } private: @@ -277,10 +279,10 @@ class BusOnOff : public Bus { BusOnOff(BusConfig &bc); ~BusOnOff() { cleanup(); } - void setPixelColor(uint16_t pix, uint32_t c); - uint32_t getPixelColor(uint16_t pix); - uint8_t getPins(uint8_t* pinArray); - void show(); + void setPixelColor(uint16_t pix, uint32_t c) override; + uint32_t getPixelColor(uint16_t pix) override; + uint8_t getPins(uint8_t* pinArray) override; + void show() override; void cleanup() { pinManager.deallocatePin(_pin, PinOwner::BusOnOff); } private: @@ -294,13 +296,13 @@ class BusNetwork : public Bus { BusNetwork(BusConfig &bc); ~BusNetwork() { cleanup(); } - bool hasRGB() { return true; } - bool hasWhite() { return _rgbw; } - bool canShow() { return !_broadcastLock; } // this should be a return value from UDP routine if it is still sending data out - void setPixelColor(uint16_t pix, uint32_t c); - uint32_t getPixelColor(uint16_t pix); - uint8_t getPins(uint8_t* pinArray); - void show(); + bool hasRGB() override { return true; } + bool hasWhite() override { return _rgbw; } + bool canShow() override { return !_broadcastLock; } // this should be a return value from UDP routine if it is still sending data out + void setPixelColor(uint16_t pix, uint32_t c) override; + uint32_t getPixelColor(uint16_t pix) override; + uint8_t getPins(uint8_t* pinArray) override; + void show() override; void cleanup(); private: @@ -314,39 +316,44 @@ class BusNetwork : public Bus { class BusManager { public: - BusManager() : numBusses(0) {}; + BusManager() {}; //utility to get the approx. memory usage of a given BusConfig static uint32_t memUsage(BusConfig &bc); + static uint16_t currentMilliamps(void) { return _milliAmpsUsed; } + static uint16_t ablMilliampsMax(void) { return _milliAmpsMax; } - int add(BusConfig &bc); + static int add(BusConfig &bc); //do not call this method from system context (network callback) - void removeAll(); + static void removeAll(); - void show(); - bool canAllShow(); - void setStatusPixel(uint32_t c); - void setPixelColor(uint16_t pix, uint32_t c); - void setBrightness(uint8_t b); - void setSegmentCCT(int16_t cct, bool allowWBCorrection = false); - uint32_t getPixelColor(uint16_t pix); + static void show(); + static bool canAllShow(); + static void setStatusPixel(uint32_t c); + static void setPixelColor(uint16_t pix, uint32_t c); + static void setBrightness(uint8_t b); + static void setSegmentCCT(int16_t cct, bool allowWBCorrection = false); + static void setMilliampsMax(uint16_t max) { _milliAmpsMax = max;} + static uint32_t getPixelColor(uint16_t pix); - Bus* getBus(uint8_t busNr); + static Bus* getBus(uint8_t busNr); //semi-duplicate of strip.getLengthTotal() (though that just returns strip._length, calculated in finalizeInit()) - uint16_t getTotalLength(); - inline uint8_t getNumBusses() const { return numBusses; } + static uint16_t getTotalLength(); + static uint8_t getNumBusses() { return numBusses; } - inline void updateColorOrderMap(const ColorOrderMap &com) { memcpy(&colorOrderMap, &com, sizeof(ColorOrderMap)); } - inline const ColorOrderMap& getColorOrderMap() const { return colorOrderMap; } + static void updateColorOrderMap(const ColorOrderMap &com) { memcpy(&colorOrderMap, &com, sizeof(ColorOrderMap)); } + static const ColorOrderMap& getColorOrderMap() { return colorOrderMap; } private: - uint8_t numBusses; - Bus* busses[WLED_MAX_BUSSES+WLED_MIN_VIRTUAL_BUSSES]; - ColorOrderMap colorOrderMap; + static uint8_t numBusses; + static Bus* busses[WLED_MAX_BUSSES+WLED_MIN_VIRTUAL_BUSSES]; + static ColorOrderMap colorOrderMap; + static uint16_t _milliAmpsUsed; + static uint16_t _milliAmpsMax; - inline uint8_t getNumVirtualBusses() { + static uint8_t getNumVirtualBusses() { int j = 0; for (int i=0; igetType() >= TYPE_NET_DDP_RGB && busses[i]->getType() < 96) j++; return j; diff --git a/wled00/button.cpp b/wled00/button.cpp index f1487396a..b1e7f2a79 100644 --- a/wled00/button.cpp +++ b/wled00/button.cpp @@ -347,10 +347,10 @@ void handleButton() void esp32RMTInvertIdle() { bool idle_out; - for (uint8_t u = 0; u < busses.getNumBusses(); u++) + for (uint8_t u = 0; u < BusManager::getNumBusses(); u++) { if (u > 7) return; // only 8 RMT channels, TODO: ESP32 variants have less RMT channels - Bus *bus = busses.getBus(u); + Bus *bus = BusManager::getBus(u); if (!bus || bus->getLength()==0 || !IS_DIGITAL(bus->getType()) || IS_2PIN(bus->getType())) continue; //assumes that bus number to rmt channel mapping stays 1:1 rmt_channel_t ch = static_cast(u); diff --git a/wled00/cfg.cpp b/wled00/cfg.cpp old mode 100644 new mode 100755 index fdb70099c..1234a1c5f --- a/wled00/cfg.cpp +++ b/wled00/cfg.cpp @@ -31,9 +31,7 @@ bool deserializeConfig(JsonObject doc, bool fromFS) { getStringFromJson(cmDNS, id[F("mdns")], 33); getStringFromJson(serverDescription, id[F("name")], 33); getStringFromJson(alexaInvocationName, id[F("inv")], 33); -#ifdef WLED_ENABLE_SIMPLE_UI CJSON(simplifiedUI, id[F("sui")]); -#endif JsonObject nw = doc["nw"]; #ifndef WLED_DISABLE_ESPNOW @@ -81,7 +79,7 @@ bool deserializeConfig(JsonObject doc, bool fromFS) { noWifiSleep = doc[F("wifi")][F("sleep")] | !noWifiSleep; // inverted noWifiSleep = !noWifiSleep; - //int wifi_phy = doc[F("wifi")][F("phy")]; //force phy mode n? + force802_3g = doc[F("wifi")][F("phy")] | force802_3g; //force phy mode g? JsonObject hw = doc[F("hw")]; @@ -89,8 +87,8 @@ bool deserializeConfig(JsonObject doc, bool fromFS) { JsonObject hw_led = hw["led"]; uint16_t total = hw_led[F("total")] | strip.getLengthTotal(); - CJSON(strip.ablMilliampsMax, hw_led[F("maxpwr")]); - CJSON(strip.milliampsPerLed, hw_led[F("ledma")]); // no longer used + uint16_t ablMilliampsMax = hw_led[F("maxpwr")] | BusManager::ablMilliampsMax(); + BusManager::setMilliampsMax(ablMilliampsMax); Bus::setGlobalAWMode(hw_led[F("rgbwm")] | AW_GLOBAL_DISABLED); CJSON(correctWB, hw_led["cct"]); CJSON(cctFromRgb, hw_led[F("cr")]); @@ -140,7 +138,7 @@ bool deserializeConfig(JsonObject doc, bool fromFS) { if (fromFS || !ins.isNull()) { uint8_t s = 0; // bus iterator - if (fromFS) busses.removeAll(); // can't safely manipulate busses directly in network callback + if (fromFS) BusManager::removeAll(); // can't safely manipulate busses directly in network callback uint32_t mem = 0, globalBufMem = 0; uint16_t maxlen = 0; bool busesChanged = false; @@ -166,8 +164,8 @@ bool deserializeConfig(JsonObject doc, bool fromFS) { bool refresh = elm["ref"] | false; uint16_t freqkHz = elm[F("freq")] | 0; // will be in kHz for DotStar and Hz for PWM (not yet implemented fully) uint8_t AWmode = elm[F("rgbwm")] | RGBW_MODE_MANUAL_ONLY; - uint8_t maPerLed = elm[F("ledma")] | strip.milliampsPerLed; // replace with 55 when removing strip.milliampsPerLed - uint16_t maMax = elm[F("maxpwr")] | (strip.ablMilliampsMax * length) / total; // rough (incorrect?) per strip ABL calculation when no config exists + uint8_t maPerLed = elm[F("ledma")] | 55; + uint16_t maMax = elm[F("maxpwr")] | (ablMilliampsMax * length) / total; // rough (incorrect?) per strip ABL calculation when no config exists // To disable brightness limiter we either set output max current to 0 or single LED current to 0 (we choose output max current) if ((ledType > TYPE_TM1814 && ledType < TYPE_WS2801) || ledType >= TYPE_NET_DDP_RGB) { // analog and virtual maPerLed = 0; @@ -181,7 +179,7 @@ bool deserializeConfig(JsonObject doc, bool fromFS) { maxlen = start + length; globalBufMem = maxlen * 4; } - if (mem + globalBufMem <= MAX_LED_MEMORY) if (busses.add(bc) == -1) break; // finalization will be done in WLED::beginStrip() + if (mem + globalBufMem <= MAX_LED_MEMORY) if (BusManager::add(bc) == -1) break; // finalization will be done in WLED::beginStrip() } else { if (busConfigs[s] != nullptr) delete busConfigs[s]; busConfigs[s] = new BusConfig(ledType, pins, start, length, colorOrder, reversed, skipFirst, AWmode, freqkHz, useGlobalLedBuffer, maPerLed, maMax); @@ -192,7 +190,7 @@ bool deserializeConfig(JsonObject doc, bool fromFS) { doInitBusses = busesChanged; // finalization done in beginStrip() } - if (hw_led["rev"]) busses.getBus(0)->setReversed(true); //set 0.11 global reversed setting for first bus + if (hw_led["rev"]) BusManager::getBus(0)->setReversed(true); //set 0.11 global reversed setting for first bus // read color order map configuration JsonArray hw_com = hw[F("com")]; @@ -207,7 +205,7 @@ bool deserializeConfig(JsonObject doc, bool fromFS) { com.add(start, len, colorOrder); s++; } - busses.updateColorOrderMap(com); + BusManager::updateColorOrderMap(com); } // read multiple button configuration @@ -419,7 +417,6 @@ bool deserializeConfig(JsonObject doc, bool fromFS) { CJSON(notifyButton, if_sync_send["btn"]); CJSON(notifyAlexa, if_sync_send["va"]); CJSON(notifyHue, if_sync_send["hue"]); -// CJSON(notifyMacro, if_sync_send["macro"]); CJSON(syncGroups, if_sync_send["grp"]); if (if_sync_send[F("twice")]) udpNumRetries = 1; // import setting from 0.13 and earlier CJSON(udpNumRetries, if_sync_send["ret"]); @@ -431,6 +428,7 @@ bool deserializeConfig(JsonObject doc, bool fromFS) { JsonObject if_live = interfaces["live"]; CJSON(receiveDirect, if_live["en"]); // UDP/Hyperion realtime CJSON(useMainSegmentOnly, if_live[F("mso")]); + CJSON(realtimeRespectLedMaps, if_live[F("rlm")]); CJSON(e131Port, if_live["port"]); // 5568 if (e131Port == DDP_DEFAULT_PORT) e131Port = E131_DEFAULT_PORT; // prevent double DDP port allocation CJSON(e131Multicast, if_live[F("mc")]); @@ -611,7 +609,7 @@ void deserializeConfigFromFS() { DEBUG_PRINTLN(F("Reading settings from /cfg.json...")); - success = readObjectFromFile("/cfg.json", nullptr, &doc); + success = readObjectFromFile("/cfg.json", nullptr, pDoc); if (!success) { // if file does not exist, optionally try reading from EEPROM and then save defaults to FS releaseJSONBufferLock(); #ifdef WLED_ADD_EEPROM_SUPPORT @@ -632,7 +630,8 @@ void deserializeConfigFromFS() { // NOTE: This routine deserializes *and* applies the configuration // Therefore, must also initialize ethernet from this function - bool needsSave = deserializeConfig(doc.as(), true); + JsonObject root = pDoc->as(); + bool needsSave = deserializeConfig(root, true); releaseJSONBufferLock(); if (needsSave) serializeConfig(); // usermods required new parameters @@ -645,21 +644,21 @@ void serializeConfig() { if (!requestJSONBufferLock(2)) return; - JsonArray rev = doc.createNestedArray("rev"); + JsonObject root = pDoc->to(); + + JsonArray rev = root.createNestedArray("rev"); rev.add(1); //major settings revision rev.add(0); //minor settings revision - doc[F("vid")] = VERSION; + root[F("vid")] = VERSION; - JsonObject id = doc.createNestedObject("id"); + JsonObject id = root.createNestedObject("id"); id[F("mdns")] = cmDNS; id[F("name")] = serverDescription; id[F("inv")] = alexaInvocationName; -#ifdef WLED_ENABLE_SIMPLE_UI id[F("sui")] = simplifiedUI; -#endif - JsonObject nw = doc.createNestedObject("nw"); + JsonObject nw = root.createNestedObject("nw"); #ifndef WLED_DISABLE_ESPNOW nw[F("espnow")] = enableESPNow; nw[F("linked_remote")] = linked_remote; @@ -681,7 +680,7 @@ void serializeConfig() { nw_ins_0_sn.add(staticSubnet[i]); } - JsonObject ap = doc.createNestedObject("ap"); + JsonObject ap = root.createNestedObject("ap"); ap[F("ssid")] = apSSID; ap[F("pskl")] = strlen(apPass); ap[F("chan")] = apChannel; @@ -694,12 +693,12 @@ void serializeConfig() { ap_ip.add(2); ap_ip.add(1); - JsonObject wifi = doc.createNestedObject("wifi"); + JsonObject wifi = root.createNestedObject("wifi"); wifi[F("sleep")] = !noWifiSleep; - //wifi[F("phy")] = 1; + wifi[F("phy")] = force802_3g; #ifdef WLED_USE_ETHERNET - JsonObject ethernet = doc.createNestedObject("eth"); + JsonObject ethernet = root.createNestedObject("eth"); ethernet["type"] = ethernetType; if (ethernetType != WLED_ETH_NONE && ethernetType < WLED_NUM_ETH_TYPES) { JsonArray pins = ethernet.createNestedArray("pin"); @@ -722,12 +721,12 @@ void serializeConfig() { } #endif - JsonObject hw = doc.createNestedObject("hw"); + JsonObject hw = root.createNestedObject("hw"); JsonObject hw_led = hw.createNestedObject("led"); hw_led[F("total")] = strip.getLengthTotal(); //provided for compatibility on downgrade and per-output ABL - hw_led[F("maxpwr")] = strip.ablMilliampsMax; - hw_led[F("ledma")] = strip.milliampsPerLed; // no longer used + hw_led[F("maxpwr")] = BusManager::ablMilliampsMax(); + hw_led[F("ledma")] = 0; // no longer used hw_led["cct"] = correctWB; hw_led[F("cr")] = cctFromRgb; hw_led[F("cb")] = strip.cctBlending; @@ -757,8 +756,8 @@ void serializeConfig() { JsonArray hw_led_ins = hw_led.createNestedArray("ins"); - for (uint8_t s = 0; s < busses.getNumBusses(); s++) { - Bus *bus = busses.getBus(s); + for (uint8_t s = 0; s < BusManager::getNumBusses(); s++) { + Bus *bus = BusManager::getBus(s); if (!bus || bus->getLength()==0) break; JsonObject ins = hw_led_ins.createNestedObject(); ins["start"] = bus->getStart(); @@ -779,7 +778,7 @@ void serializeConfig() { } JsonArray hw_com = hw.createNestedArray(F("com")); - const ColorOrderMap& com = busses.getColorOrderMap(); + const ColorOrderMap& com = BusManager::getColorOrderMap(); for (uint8_t s = 0; s < com.count(); s++) { const ColorOrderMapEntry *entry = com.get(s); if (!entry) break; @@ -834,7 +833,7 @@ void serializeConfig() { //JsonObject hw_status = hw.createNestedObject("status"); //hw_status["pin"] = -1; - JsonObject light = doc.createNestedObject(F("light")); + JsonObject light = root.createNestedObject(F("light")); light[F("scale-bri")] = briMultiplier; light[F("pal-mode")] = strip.paletteBlend; light[F("aseg")] = autoSegments; @@ -857,12 +856,12 @@ void serializeConfig() { light_nl[F("tbri")] = nightlightTargetBri; light_nl["macro"] = macroNl; - JsonObject def = doc.createNestedObject("def"); + JsonObject def = root.createNestedObject("def"); def["ps"] = bootPreset; def["on"] = turnOnAtBoot; def["bri"] = briS; - JsonObject interfaces = doc.createNestedObject("if"); + JsonObject interfaces = root.createNestedObject("if"); JsonObject if_sync = interfaces.createNestedObject("sync"); if_sync[F("port0")] = udpPort; @@ -886,7 +885,6 @@ void serializeConfig() { if_sync_send["btn"] = notifyButton; if_sync_send["va"] = notifyAlexa; if_sync_send["hue"] = notifyHue; -// if_sync_send["macro"] = notifyMacro; if_sync_send["grp"] = syncGroups; if_sync_send["ret"] = udpNumRetries; @@ -897,6 +895,7 @@ void serializeConfig() { JsonObject if_live = interfaces.createNestedObject("live"); if_live["en"] = receiveDirect; // UDP/Hyperion realtime if_live[F("mso")] = useMainSegmentOnly; + if_live[F("rlm")] = realtimeRespectLedMaps; if_live["port"] = e131Port; if_live[F("mc")] = e131Multicast; @@ -965,7 +964,7 @@ void serializeConfig() { if_ntp[F("ln")] = longitude; if_ntp[F("lt")] = latitude; - JsonObject ol = doc.createNestedObject("ol"); + JsonObject ol = root.createNestedObject("ol"); ol[F("clock")] = overlayCurrent; ol[F("cntdwn")] = countdownMode; @@ -975,7 +974,7 @@ void serializeConfig() { ol[F("o5m")] = analogClock5MinuteMarks; ol[F("osec")] = analogClockSecondsTrail; - JsonObject timers = doc.createNestedObject(F("timers")); + JsonObject timers = root.createNestedObject(F("timers")); JsonObject cntdwn = timers.createNestedObject(F("cntdwn")); JsonArray goal = cntdwn.createNestedArray(F("goal")); @@ -1003,14 +1002,14 @@ void serializeConfig() { } } - JsonObject ota = doc.createNestedObject("ota"); + JsonObject ota = root.createNestedObject("ota"); ota[F("lock")] = otaLock; ota[F("lock-wifi")] = wifiLock; ota[F("pskl")] = strlen(otaPass); ota[F("aota")] = aOtaEnabled; #ifdef WLED_ENABLE_DMX - JsonObject dmx = doc.createNestedObject("dmx"); + JsonObject dmx = root.createNestedObject("dmx"); dmx[F("chan")] = DMXChannels; dmx[F("gap")] = DMXGap; dmx["start"] = DMXStart; @@ -1024,11 +1023,11 @@ void serializeConfig() { dmx[F("e131proxy")] = e131ProxyUniverse; #endif - JsonObject usermods_settings = doc.createNestedObject("um"); + JsonObject usermods_settings = root.createNestedObject("um"); usermods.addToConfig(usermods_settings); File f = WLED_FS.open("/cfg.json", "w"); - if (f) serializeJson(doc, f); + if (f) serializeJson(root, f); f.close(); releaseJSONBufferLock(); @@ -1041,19 +1040,21 @@ bool deserializeConfigSec() { if (!requestJSONBufferLock(3)) return false; - bool success = readObjectFromFile("/wsec.json", nullptr, &doc); + bool success = readObjectFromFile("/wsec.json", nullptr, pDoc); if (!success) { releaseJSONBufferLock(); return false; } - JsonObject nw_ins_0 = doc["nw"]["ins"][0]; + JsonObject root = pDoc->as(); + + JsonObject nw_ins_0 = root["nw"]["ins"][0]; getStringFromJson(clientPass, nw_ins_0["psk"], 65); - JsonObject ap = doc["ap"]; + JsonObject ap = root["ap"]; getStringFromJson(apPass, ap["psk"] , 65); - [[maybe_unused]] JsonObject interfaces = doc["if"]; + [[maybe_unused]] JsonObject interfaces = root["if"]; #ifdef WLED_ENABLE_MQTT JsonObject if_mqtt = interfaces["mqtt"]; @@ -1064,10 +1065,10 @@ bool deserializeConfigSec() { getStringFromJson(hueApiKey, interfaces["hue"][F("key")], 47); #endif - getStringFromJson(settingsPIN, doc["pin"], 5); + getStringFromJson(settingsPIN, root["pin"], 5); correctPIN = !strlen(settingsPIN); - JsonObject ota = doc["ota"]; + JsonObject ota = root["ota"]; getStringFromJson(otaPass, ota[F("pwd")], 33); CJSON(otaLock, ota[F("lock")]); CJSON(wifiLock, ota[F("lock-wifi")]); @@ -1082,17 +1083,19 @@ void serializeConfigSec() { if (!requestJSONBufferLock(4)) return; - JsonObject nw = doc.createNestedObject("nw"); + JsonObject root = pDoc->to(); + + JsonObject nw = root.createNestedObject("nw"); JsonArray nw_ins = nw.createNestedArray("ins"); JsonObject nw_ins_0 = nw_ins.createNestedObject(); nw_ins_0["psk"] = clientPass; - JsonObject ap = doc.createNestedObject("ap"); + JsonObject ap = root.createNestedObject("ap"); ap["psk"] = apPass; - [[maybe_unused]] JsonObject interfaces = doc.createNestedObject("if"); + [[maybe_unused]] JsonObject interfaces = root.createNestedObject("if"); #ifdef WLED_ENABLE_MQTT JsonObject if_mqtt = interfaces.createNestedObject("mqtt"); if_mqtt["psk"] = mqttPass; @@ -1102,16 +1105,16 @@ void serializeConfigSec() { if_hue[F("key")] = hueApiKey; #endif - doc["pin"] = settingsPIN; + root["pin"] = settingsPIN; - JsonObject ota = doc.createNestedObject("ota"); + JsonObject ota = root.createNestedObject("ota"); ota[F("pwd")] = otaPass; ota[F("lock")] = otaLock; ota[F("lock-wifi")] = wifiLock; ota[F("aota")] = aOtaEnabled; File f = WLED_FS.open("/wsec.json", "w"); - if (f) serializeJson(doc, f); + if (f) serializeJson(root, f); f.close(); releaseJSONBufferLock(); } diff --git a/wled00/const.h b/wled00/const.h index 492fa778e..645859e8d 100644 --- a/wled00/const.h +++ b/wled00/const.h @@ -150,6 +150,7 @@ #define USERMOD_ID_KLIPPER 40 //Usermod Klipper percentage #define USERMOD_ID_WIREGUARD 41 //Usermod "wireguard.h" #define USERMOD_ID_INTERNAL_TEMPERATURE 42 //Usermod "usermod_internal_temperature.h" +#define USERMOD_ID_ANIMARTRIX 44 //Usermod "usermod_v2_animartrix.h" //Access point behavior #define AP_BEHAVIOR_BOOT_NO_CONN 0 //Open AP when no connection after boot @@ -225,7 +226,7 @@ #define TYPE_NONE 0 //light is not configured #define TYPE_RESERVED 1 //unused. Might indicate a "virtual" light -//Digital types (data pin only) (16-31) +//Digital types (data pin only) (16-39) #define TYPE_WS2812_1CH 18 //white-only chips (1 channel per IC) (unused) #define TYPE_WS2812_1CH_X3 19 //white-only chips (3 channels per IC) #define TYPE_WS2812_2CH_X3 20 //CCT chips (1st IC controls WW + CW of 1st zone and CW of 2nd zone, 2nd IC controls WW of 2nd zone and WW + CW of 3rd zone) @@ -235,11 +236,11 @@ #define TYPE_WS2811_400KHZ 24 //half-speed WS2812 protocol, used by very old WS2811 units #define TYPE_TM1829 25 #define TYPE_UCS8903 26 -#define TYPE_UCS8904 29 +#define TYPE_UCS8904 29 //first RGBW digital type (hardcoded in busmanager.cpp, memUsage()) #define TYPE_SK6812_RGBW 30 #define TYPE_TM1814 31 -//"Analog" types (PWM) (32-47) -#define TYPE_ONOFF 40 //binary output (relays etc.) +//"Analog" types (40-47) +#define TYPE_ONOFF 40 //binary output (relays etc.; NOT PWM) #define TYPE_ANALOG_1CH 41 //single channel PWM. Uses value of brightest RGBW channel #define TYPE_ANALOG_2CH 42 //analog WW + CW #define TYPE_ANALOG_3CH 43 //analog RGB @@ -257,10 +258,13 @@ #define TYPE_NET_ARTNET_RGB 82 //network ArtNet RGB bus (master broadcast bus, unused) #define TYPE_NET_DDP_RGBW 88 //network DDP RGBW bus (master broadcast bus) -#define IS_DIGITAL(t) ((t) & 0x10) //digital are 16-31 and 48-63 -#define IS_PWM(t) ((t) > 40 && (t) < 46) -#define NUM_PWM_PINS(t) ((t) - 40) //for analog PWM 41-45 only -#define IS_2PIN(t) ((t) > 47) +#define IS_TYPE_VALID(t) ((t) > 15 && (t) < 128) +#define IS_DIGITAL(t) (((t) > 15 && (t) < 40) || ((t) > 47 && (t) < 64)) //digital are 16-39 and 48-63 +#define IS_2PIN(t) ((t) > 47 && (t) < 64) +#define IS_16BIT(t) ((t) == TYPE_UCS8903 || (t) == TYPE_UCS8904) +#define IS_PWM(t) ((t) > 40 && (t) < 46) //does not include on/Off type +#define NUM_PWM_PINS(t) ((t) - 40) //for analog PWM 41-45 only +#define IS_VIRTUAL(t) ((t) >= 80 && (t) < 96) //this was a poor choice a better would be 96-111 //Color orders #define COL_ORDER_GRB 0 //GRB(w),defaut @@ -346,6 +350,7 @@ #define ERR_CONCURRENCY 2 // Conurrency (client active) #define ERR_NOBUF 3 // JSON buffer was not released in time, request cannot be handled at this time #define ERR_NOT_IMPL 4 // Not implemented +#define ERR_NORAM 8 // effect RAM depleted #define ERR_JSON 9 // JSON parsing failed (input too large?) #define ERR_FS_BEGIN 10 // Could not init filesystem (no partition?) #define ERR_FS_QUOTA 11 // The FS is full or the maximum file size is reached @@ -450,7 +455,11 @@ #ifdef ESP8266 #define JSON_BUFFER_SIZE 10240 #else - #define JSON_BUFFER_SIZE 24576 + #if defined(ARDUINO_ARCH_ESP32S2) + #define JSON_BUFFER_SIZE 24576 + #else + #define JSON_BUFFER_SIZE 32767 + #endif #endif //#define MIN_HEAP_SIZE (8k for AsyncWebServer) diff --git a/wled00/data/cpal/cpal.htm b/wled00/data/cpal/cpal.htm index 5a8c801e5..852641ec3 100644 --- a/wled00/data/cpal/cpal.htm +++ b/wled00/data/cpal/cpal.htm @@ -1,6 +1,7 @@ + @@ -45,6 +46,7 @@ width: 7px; top: 50%; transform: translateY(-50%); + touch-action: none; } .color-picker-marker { height: 7px; @@ -94,9 +96,14 @@ line-height: 1; } .wrap { - width: 800px; + width: 100%; margin: 0 auto; } + @media (min-width: 800px) { + .wrap { + width: 800px; + } + } .palette { height: 20px; } @@ -136,6 +143,9 @@ .sendSpan, .editSpan{ cursor: pointer; } + h1 { + font-size: 1.6rem; + } @@ -191,6 +201,7 @@ var gradientLength = rect.width; var mOffs = Math.round((gradientLength / 256) / 2) - 5; var paletteArray = []; //Holds the palettes after load. + var paletteName = []; // Holds the names of the palettes after load. var svgSave = '' var svgEdit = '' @@ -349,24 +360,31 @@ var gradientLength = maxX - minX + 1; elmnt.onmousedown = dragMouseDown; + elmnt.ontouchstart = dragMouseDown; function dragMouseDown(e) { removeTrashcan(event) e = e || window.event; - e.preventDefault(); + var isTouch = e.type.startsWith('touch'); + if (!isTouch) e.preventDefault(); // get the mouse cursor position at startup: - mousePos = e.clientX; + mousePos = isTouch ? e.touches[0].clientX : e.clientX; d.onmouseup = closeDragElement; + d.ontouchcancel = closeDragElement; + d.ontouchend = closeDragElement; // call a function whenever the cursor moves: d.onmousemove = elementDrag; + d.ontouchmove = elementDrag; } function elementDrag(e) { e = e || window.event; - e.preventDefault(); + var isTouch = e.type.startsWith('touch'); + if (!isTouch) e.preventDefault(); // calculate the new cursor position: - posNew = mousePos - e.clientX; - mousePos = e.clientX; + var clientX = isTouch ? e.touches[0].clientX : e.clientX; + posNew = mousePos - clientX; + mousePos = clientX; mousePosInGradient = mousePos - (minX + 1) truePos = Math.round((mousePosInGradient/gradientLength)*256); @@ -393,7 +411,10 @@ function closeDragElement() { /* stop moving when mouse button is released:*/ d.onmouseup = null; + d.ontouchcancel = null; + d.ontouchend = null; d.onmousemove = null; + d.ontouchmove = null; } } @@ -500,8 +521,10 @@ if (hst.length > 0 ) { try { var arr = []; - const response = await fetch('http://'+hst+'/json/info'); - const json = await response.json(); + const responseInfo = await fetch('http://'+hst+'/json/info'); + const responsePalettes = await fetch('http://'+hst+'/json/palettes'); + const json = await responseInfo.json(); + paletteName = await responsePalettes.json(); cpalc = json.cpalcount; fetchPalettes(cpalc-1); } catch (error) { @@ -521,6 +544,7 @@ const json = await response.json(); paletteArray.push(json); } catch (error) { + cpalc--; //remove audio/dynamically generated palettes console.error(`Error fetching JSON from ${url}: `, error); } } @@ -540,6 +564,7 @@ alert("The cache of palettes are missig from your browser. You should probably return to the main page and let it load properly for the palettes cache to regenerate before returning here.","Missing cached palettes!") } else { for (const key in wledPalx.p) { + wledPalx.p[key].name = paletteName[key]; if (key > 245) { delete wledPalx.p[key]; continue; @@ -571,8 +596,11 @@ } const pArray = Object.entries(wledPalx.p).map(([key, value]) => ({ - [key]: value.flat() + [key]: value.flat(), + name: value.name })); + // Sort pArray by name + pArray.sort((a, b) => a.name.localeCompare(b.name)); paletteArray.push( ...pArray); } @@ -614,6 +642,9 @@ editSpan.id = `editSpan${i}`; editSpan.onclick = function() {loadForEdit(i)}; editSpan.setAttribute('title', `Copy slot ${i} palette to editor`); + if (paletteArray[i].name) { + editSpan.setAttribute('title', `Copy ${paletteArray[i].name} palette to editor`); + } editSpan.innerHTML = svgEdit; editSpan.classList.add("editSpan") diff --git a/wled00/data/index.css b/wled00/data/index.css index 7faaeb47e..095de572a 100644 --- a/wled00/data/index.css +++ b/wled00/data/index.css @@ -370,6 +370,16 @@ button { padding: 5px 0 0; } +/* Quick load magin for simplified UI */ +.simplified #pql { + margin-bottom: 8px; +} + +/* Button margin for simplified UI */ +.simplified #fx .btn, .simplified #palw .btn { + margin-top: 0; +} + .smooth { transition: transform calc(var(--f, 1)*.5s) ease-out } .tab-label { @@ -413,6 +423,7 @@ button { position: sticky; bottom: 0; max-width: 300px; + z-index: 2; } #sliders .labels { @@ -754,13 +765,17 @@ input[type=range]::-moz-range-thumb { } #Colors .sliderwrap { - margin: 4px 0 0; + margin: 2px 0 0; } -/* Dynamically hide brightness slider label */ +/* Dynamically hide labels */ .hd { display: var(--bhd); } +/* Do not hide quick load label in simplified mode on small screen widths */ +.simplified #pql .hd { + display: var(--bhd) !important; +} #briwrap { min-width: 300px; @@ -770,7 +785,7 @@ input[type=range]::-moz-range-thumb { #picker { margin-top: 8px !important; - max-width: 260px; + max-width: max-content; } /* buttons */ @@ -1284,6 +1299,12 @@ TD .checkmark, TD .radiomark { margin-top: 0; } +/* Simplify segments */ +.simplified #segcont .lstI { + margin-top: 4px; + min-height: unset; +} + /* selected item/element */ .selected { /* has to be after .lstI since !important is not ok */ background: var(--c-4); @@ -1324,6 +1345,19 @@ TD .checkmark, TD .radiomark { top: calc(var(--sti) + 42px); } +dialog::backdrop { + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); +} +dialog { + max-height: 70%; + border: 0; + border-radius: 10px; + background: linear-gradient(rgba(0, 0, 0, 0.15), rgba(0, 0, 0, 0.1)), var(--c-3); + box-shadow: 4px 4px 10px 4px var(--c-1); + color: var(--c-f); +} + #fxlist .lstI.sticky, #pallist .lstI.sticky { top: var(--sti); @@ -1532,9 +1566,6 @@ TD .checkmark, TD .radiomark { max-width: 280px; font-size: 18px; } - #picker { - width: 230px; - } #putil .btn-s { width: 114px; } diff --git a/wled00/data/index.htm b/wled00/data/index.htm index 21aa28d6d..ae685bdb9 100644 --- a/wled00/data/index.htm +++ b/wled00/data/index.htm @@ -7,52 +7,9 @@ WLED - - +
Loading WLED UI...
@@ -168,7 +125,7 @@ -
+
@@ -351,7 +308,7 @@

- Made with ❤︎ by Aircoookie and the WLED community + Made with ❤︎ by Aircoookie and the WLED community

+ + + + diff --git a/wled00/data/index.js b/wled00/data/index.js index 02bb07ff9..bdaa3ed60 100644 --- a/wled00/data/index.js +++ b/wled00/data/index.js @@ -12,8 +12,11 @@ var currentPreset = -1; var lastUpdate = 0; var segCount = 0, ledCount = 0, lowestUnused = 0, maxSeg = 0, lSeg = 0; var pcMode = false, pcModeA = false, lastw = 0, wW; +var simplifiedUI = false; var tr = 7; var d = document; +const ranges = RangeTouch.setup('input[type="range"]', {}); +var retry = false; var palettesData; var fxdata = []; var pJson = {}, eJson = {}, lJson = {}; @@ -22,22 +25,34 @@ var pN = "", pI = 0, pNum = 0; var pmt = 1, pmtLS = 0, pmtLast = 0; var lastinfo = {}; var isM = false, mw = 0, mh=0; -var ws, cpick, ranges, wsRpt=0; +var ws, wsRpt=0; var cfg = { theme:{base:"dark", bg:{url:"", rnd: false, rndGrayscale: false, rndBlur: false}, alpha:{bg:0.6,tab:0.8}, color:{bg:""}}, comp :{colors:{picker: true, rgb: false, quick: true, hex: false}, labels:true, pcmbot:false, pid:true, seglen:false, segpwr:false, segexp:false, css:true, hdays:false, fxdef:true, on:0, off:0, idsort: false} }; +// [year, month (0 -> January, 11 -> December), day, duration in days, image url] var hol = [ - [0,11,24,4,"https://aircoookie.github.io/xmas.png"], // christmas - [0,2,17,1,"https://images.alphacoders.com/491/491123.jpg"], // st. Patrick's day - [2025,3,20,2,"https://aircoookie.github.io/easter.png"], - [2024,2,31,2,"https://aircoookie.github.io/easter.png"], - [0,6,4,1,"https://images.alphacoders.com/516/516792.jpg"], // 4th of July - [0,0,1,1,"https://images.alphacoders.com/119/1198800.jpg"] // new year + [0, 11, 24, 4, "https://aircoookie.github.io/xmas.png"], // christmas + [0, 2, 17, 1, "https://images.alphacoders.com/491/491123.jpg"], // st. Patrick's day + [2025, 3, 20, 2, "https://aircoookie.github.io/easter.png"], // easter 2025 + [2024, 2, 31, 2, "https://aircoookie.github.io/easter.png"], // easter 2024 + [0, 6, 4, 1, "https://images.alphacoders.com/516/516792.jpg"], // 4th of July + [0, 0, 1, 1, "https://images.alphacoders.com/119/1198800.jpg"] // new year ]; +var cpick = new iro.ColorPicker("#picker", { + width: 260, + wheelLightness: false, + wheelAngle: 270, + wheelDirection: "clockwise", + layout: [{ + component: iro.ui.Wheel, + options: {} + }] +}); + function handleVisibilityChange() {if (!d.hidden && new Date () - lastUpdate > 3000) requestJson();} function sCol(na, col) {d.documentElement.style.setProperty(na, col);} function gId(c) {return d.getElementById(c);} @@ -161,19 +176,19 @@ function cTheme(light) { } } -function loadBg(iUrl) -{ - let bg = gId('bg'); - let img = d.createElement("img"); +function loadBg() { + const { url: iUrl, rnd: iRnd } = cfg.theme.bg; + const bg = gId('bg'); + const img = d.createElement("img"); img.src = iUrl; - if (iUrl == "" || iUrl==="https://picsum.photos/1920/1080") { - var today = new Date(); - for (var h of (hol||[])) { - var yr = h[0]==0 ? today.getFullYear() : h[0]; - var hs = new Date(yr,h[1],h[2]); - var he = new Date(hs); - he.setDate(he.getDate() + h[3]); - if (today>=hs && today<=he) img.src = h[4]; + if (!iUrl || iRnd) { + const today = new Date(); + for (const holiday of (hol || [])) { + const year = holiday[0] == 0 ? today.getFullYear() : holiday[0]; + const holidayStart = new Date(year, holiday[1], holiday[2]); + const holidayEnd = new Date(holidayStart); + holidayEnd.setDate(holidayEnd.getDate() + holiday[3]); + if (today >= holidayStart && today <= holidayEnd) img.src = holiday[4]; } } img.addEventListener('load', (e) => { @@ -181,7 +196,6 @@ function loadBg(iUrl) if (isNaN(a)) a = 0.6; bg.style.opacity = a; bg.style.backgroundImage = `url(${img.src})`; - img = null; gId('namelabel').style.color = "var(--c-c)"; // improve namelabel legibility on background image }); } @@ -252,31 +266,37 @@ function onLoad() console.log("No array of holidays in holidays.json. Defaults loaded."); }) .finally(()=>{ - loadBg(cfg.theme.bg.url); + loadBg(); }); } else - loadBg(cfg.theme.bg.url); + loadBg(); selectSlot(0); updateTablinks(0); + cpick.on("input:end", () => {setColor(1);}); + cpick.on("color:change", () => {updatePSliders()}); pmtLS = localStorage.getItem('wledPmt'); // Load initial data + // Once we figure out why ESP8266 sometimes corrupts JSON responses if they are made in quick succession + // we can remove all setTimeout() throttling loadPalettes(()=>{ - // fill effect extra data array - loadFXData(()=>{ - setTimeout(()=>{ // ESP8266 can't handle quick requests - // load and populate effects - loadFX(()=>{ - setTimeout(()=>{ // ESP8266 can't handle quick requests - loadPalettesData(()=>{ - requestJson();// will load presets and create WS - if (cfg.comp.css) setTimeout(()=>{loadSkinCSS('skinCss')},100); - }); - },100); - }); - },100); - }); + setTimeout(()=>{ // ESP8266 can't handle quick requests + // fill effect extra data array + loadFXData(()=>{ + setTimeout(()=>{ // ESP8266 can't handle quick requests + // load and populate effects + loadFX(()=>{ + setTimeout(()=>{ // ESP8266 can't handle quick requests + loadPalettesData(()=>{ + requestJson();// will load presets and create WS + if (cfg.comp.css) setTimeout(()=>{loadSkinCSS('skinCss')},100); + }); + },50); + }); + },50); + }); + },50); }); resetUtil(); @@ -309,7 +329,6 @@ function openTab(tabI, force = false) var timeout; function showToast(text, error = false) { - if (error) gId('connind').style.backgroundColor = "var(--c-r)"; var x = gId('toast'); //if (error) text += ''; x.innerHTML = text; @@ -322,6 +341,7 @@ function showToast(text, error = false) function showErrorToast() { + gId('connind').style.backgroundColor = "var(--c-r)"; showToast('Connection to light failed!', true); } @@ -500,8 +520,13 @@ function loadPalettes(callback = null) .then((json)=>{ lJson = Object.entries(json); populatePalettes(); + retry = false; }) .catch((e)=>{ + if (!retry) { + retry = true; + setTimeout(loadPalettes, 500); // retry + } showToast(e, true); }) .finally(()=>{ @@ -522,9 +547,13 @@ function loadFX(callback = null) .then((json)=>{ eJson = Object.entries(json); populateEffects(); + retry = false; }) .catch((e)=>{ - //setTimeout(loadFX, 250); // retry + if (!retry) { + retry = true; + setTimeout(loadFX, 500); // retry + } showToast(e, true); }) .finally(()=>{ @@ -547,10 +576,14 @@ function loadFXData(callback = null) // add default value for Solid fxdata.shift() fxdata.unshift(";!;"); + retry = false; }) .catch((e)=>{ fxdata = []; - //setTimeout(loadFXData, 250); // retry + if (!retry) { + retry = true; + setTimeout(loadFXData, 500); // retry + } showToast(e, true); }) .finally(()=>{ @@ -624,11 +657,12 @@ function parseInfo(i) { if (name === "Dinnerbone") d.documentElement.style.transform = "rotate(180deg)"; // Minecraft easter egg if (i.live) name = "(Live) " + name; if (loc) name = "(L) " + name; - d.title = name; - ledCount = i.leds.count; - //syncTglRecv = i.str; - maxSeg = i.leds.maxseg; - pmt = i.fs.pmt; + d.title = name; + simplifiedUI = i.simplifiedui; + ledCount = i.leds.count; + //syncTglRecv = i.str; + maxSeg = i.leds.maxseg; + pmt = i.fs.pmt; gId('buttonNodes').style.display = lastinfo.ndc > 0 ? null:"none"; // do we have a matrix set-up mw = i.leds.matrix ? i.leds.matrix.w : 0; @@ -750,6 +784,7 @@ function populateSegments(s) let rvXck = ``; let miXck = ``; let rvYck = "", miYck =""; + let smpl = simplifiedUI ? 'hide' : ''; if (isMSeg) { rvYck = ``; miYck = ``; @@ -768,23 +803,23 @@ function populateSegments(s) ``+ ``+ ``; - cn += `
`+ - `