diff --git a/CHANGELOG.md b/CHANGELOG.md index 6751de2c2..e2ef83e61 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ### Builds after release 0.12.0 +#### Build 2112080 + +- Version bump to 0.13.0-b6 "Toki" +- Added "ESP02" (ESP8266 with 2M of flash) to PIO/release binaries + #### Build 2112070 - Added new effect "Fairy", replacing "Police All" diff --git a/package-lock.json b/package-lock.json index 0d381c7c3..892cb480f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "wled", - "version": "0.13.1-bl5", + "version": "0.13.1-bl6", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/package.json b/package.json index eda9a00dc..e5967ccf2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "wled", - "version": "0.13.1-bl5", + "version": "0.13.1-bl6", "description": "Tools for WLED project", "main": "tools/cdata.js", "directories": { diff --git a/platformio.ini b/platformio.ini index d45f52be6..0ac1432b0 100644 --- a/platformio.ini +++ b/platformio.ini @@ -12,7 +12,7 @@ ; default_envs = travis_esp8266, travis_esp32 # Release binaries -default_envs = nodemcuv2, esp01_1m_full, esp32dev, esp32_eth +default_envs = nodemcuv2, esp8266_2m, esp01_1m_full, esp32dev, esp32_eth # Build everything ; default_envs = esp32dev, esp8285_4CH_MagicHome, esp8285_4CH_H801, codm-controller-0.6-rev2, codm-controller-0.6, esp32s2_saola, d1_mini_5CH_Shojo_PCB, d1_mini, sp501e, travis_esp8266, travis_esp32, nodemcuv2, esp32_eth, anavi_miracle_controller, esp07, esp01_1m_full, m5atom, h803wf, d1_mini_ota, heltec_wifi_kit_8, esp8285_5CH_H801, d1_mini_debug, wemos_shield_esp32, elekstube_ips @@ -20,6 +20,7 @@ default_envs = nodemcuv2, esp01_1m_full, esp32dev, esp32_eth # Single binaries (uncomment your board) ; default_envs = elekstube_ips ; default_envs = nodemcuv2 +; default_envs = esp8266_2m ; default_envs = esp01_1m_full ; default_envs = esp07 ; default_envs = d1_mini @@ -53,14 +54,14 @@ extra_configs = arduino_core_2_6_3 = espressif8266@2.3.3 arduino_core_2_7_4 = espressif8266@2.6.2 arduino_core_3_0_0 = espressif8266@3.0.0 -;arduino_core_3_2_0 = espressif8266@3.2.0 +arduino_core_3_2_0 = espressif8266@3.2.0 # Development platforms arduino_core_develop = https://github.com/platformio/platform-espressif8266#develop arduino_core_git = https://github.com/platformio/platform-espressif8266#feature/stage # Platform to use for ESP8266 -platform_wled_default = ${common.arduino_core_2_7_4} +platform_wled_default = ${common.arduino_core_3_2_0} # We use 2.7.4.7 for all, includes PWM flicker fix and Wstring optimization platform_packages = tasmota/framework-arduinoespressif8266 @ 3.20704.7 platformio/toolchain-xtensa @ ~2.40802.200502 @@ -105,6 +106,7 @@ build_flags = -DBEARSSL_SSL_BASIC -D CORE_DEBUG_LEVEL=0 -D NDEBUG + -Dregister= #build_flags for the IRremoteESP8266 library (enabled decoders have to appear here) -D _IR_ENABLE_DEFAULT_=false -D DECODE_HASH=true @@ -242,6 +244,13 @@ build_unflags = ${common.build_unflags} build_flags = ${common.build_flags_esp8266} -D WLED_RELEASE_NAME=ESP8266 lib_deps = ${esp8266.lib_deps} +[env:esp8266_2m] +board = esp_wroom_02 +platform = ${common.platform_wled_default} +board_build.ldscript = ${common.ldscript_2m512k} +build_flags = ${common.build_flags_esp8266} -D WLED_RELEASE_NAME=ESP02 +lib_deps = ${esp8266.lib_deps} + [env:esp01_1m_full] board = esp01_1m platform = ${common.platform_wled_default} diff --git a/usermods/PIR_sensor_switch/usermod_PIR_sensor_switch.h b/usermods/PIR_sensor_switch/usermod_PIR_sensor_switch.h index 8e683a497..99ce209ad 100644 --- a/usermods/PIR_sensor_switch/usermod_PIR_sensor_switch.h +++ b/usermods/PIR_sensor_switch/usermod_PIR_sensor_switch.h @@ -118,7 +118,8 @@ private: */ void switchStrip(bool switchOn) { - if (m_offOnly && bri && (switchOn || (!PIRtriggered && !switchOn))) return; + if (m_offOnly && bri && (switchOn || (!PIRtriggered && !switchOn))) return; //if lights on and off only, do nothing + if (PIRtriggered && switchOn) return; //if already on and triggered before, do nothing PIRtriggered = switchOn; if (switchOn) { if (m_onPreset) { @@ -188,10 +189,12 @@ private: 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 /*if (bri != 0)*/ { + } else { // start switch off timer offTimerStart = millis(); + if (NotifyUpdateMode != CALL_MODE_NO_NOTIFY) updateInterfaces(CALL_MODE_WS_SEND); } return true; } @@ -203,14 +206,13 @@ private: */ bool handleOffTimer() { - if (offTimerStart > 0 && millis() - offTimerStart > m_switchOffDelay) - { - if (enabled == true) - { + if (offTimerStart > 0 && millis() - offTimerStart > m_switchOffDelay) { + offTimerStart = 0; + if (enabled == true) { if (!m_mqttOnly && (!m_nightTimeOnly || (m_nightTimeOnly && !isDayTime()))) switchStrip(false); + else if (NotifyUpdateMode != CALL_MODE_NO_NOTIFY) updateInterfaces(CALL_MODE_WS_SEND); publishMqtt("off"); } - offTimerStart = 0; return true; } return false; diff --git a/usermods/PWM_fan/usermod_PWM_fan.h b/usermods/PWM_fan/usermod_PWM_fan.h index 82aa917bb..5cd79ef25 100644 --- a/usermods/PWM_fan/usermod_PWM_fan.h +++ b/usermods/PWM_fan/usermod_PWM_fan.h @@ -148,7 +148,7 @@ class PWMFanUsermod : public Usermod { int pwmStep = ((100 - minPWMValuePct) * newPWMvalue) / (7*100); int pwmMinimumValue = (minPWMValuePct * newPWMvalue) / 100; - if ((temp == NAN) || (temp <= 0.0)) { + if ((temp == NAN) || (temp <= -100.0)) { DEBUG_PRINTLN(F("WARNING: no temperature value available. Cannot do temperature control. Will set PWM fan to 255.")); } else if (difftemp <= 0.0) { // Temperature is below target temperature. Run fan at minimum speed. diff --git a/usermods/SN_Photoresistor/usermod_sn_photoresistor.h b/usermods/SN_Photoresistor/usermod_sn_photoresistor.h index 3b785fada..6a7e9f5ac 100644 --- a/usermods/SN_Photoresistor/usermod_sn_photoresistor.h +++ b/usermods/SN_Photoresistor/usermod_sn_photoresistor.h @@ -123,6 +123,11 @@ public: } } + uint16_t getLastLDRValue() + { + return lastLDRValue; + } + void addToJsonInfo(JsonObject &root) { JsonObject user = root[F("u")]; diff --git a/usermods/Temperature/usermod_temperature.h b/usermods/Temperature/usermod_temperature.h index 4762cb25f..413448d05 100644 --- a/usermods/Temperature/usermod_temperature.h +++ b/usermods/Temperature/usermod_temperature.h @@ -37,7 +37,7 @@ class UsermodTemperature : public Usermod { // used to determine when we can read the sensors temperature // we have to wait at least 93.75 ms after requestTemperatures() is called unsigned long lastTemperaturesRequest; - float temperature = -100.0f; // default to -100, DS18B20 only goes down to -50C + float temperature = -127.0f; // default to -127, DS18B20 only goes down to -50C // indicates requestTemperatures has been called but the sensor measurement is not complete bool waitingForConversion = false; // flag set at startup if DS18B20 sensor not found, avoids trying to keep getting @@ -60,7 +60,6 @@ class UsermodTemperature : public Usermod { if (oneWire->reset()) { // if reset() fails there are no OneWire devices oneWire->skip(); // skip ROM oneWire->write(0xBE); // read (temperature) from EEPROM - delayMicroseconds(250); oneWire->read_bytes(data, 9); // first 2 bytes contain temperature #ifdef WLED_DEBUG if (OneWire::crc8(data,8) != data[8]) { @@ -85,7 +84,8 @@ class UsermodTemperature : public Usermod { break; } } - return retVal; + for (byte i=1; i<9; i++) data[0] &= data[i]; + return data[0]==0xFF ? -127.0f : retVal; } void requestTemperatures() { @@ -176,7 +176,7 @@ class UsermodTemperature : public Usermod { } // we were waiting for a conversion to complete, have we waited log enough? - if (now - lastTemperaturesRequest >= 100 /* 93.75ms per the datasheet but can be up to 750ms */) { + if (now - lastTemperaturesRequest >= 750 /* 93.75ms per the datasheet but can be up to 750ms */) { readTemperature(); if (WLED_MQTT_CONNECTED) { diff --git a/usermods/quinled-an-penta/quinled-an-penta.h b/usermods/quinled-an-penta/quinled-an-penta.h index 10777e36c..5153ee58a 100644 --- a/usermods/quinled-an-penta/quinled-an-penta.h +++ b/usermods/quinled-an-penta/quinled-an-penta.h @@ -61,10 +61,10 @@ class QuinLEDAnPentaUsermod : public Usermod float shtLastKnownHumidity = 0; // Pin/IO vars - const int8_t anPentaPins[5] = {14, 13, 12, 4, 2}; + const int8_t anPentaLEDPins[5] = {14, 13, 12, 4, 2}; int8_t oledSpiClk = 15; int8_t oledSpiData = 16; - int8_t oledSpiCs = 0; + int8_t oledSpiCs = 27; int8_t oledSpiDc = 32; int8_t oledSpiRst = 33; int8_t shtSda = 1; @@ -75,7 +75,7 @@ class QuinLEDAnPentaUsermod : public Usermod { for(int8_t i = 0; i <= 4; i++) { - if(anPentaPins[i] == pin) + if(anPentaLEDPins[i] == pin) return true; } return false; @@ -313,7 +313,7 @@ class QuinLEDAnPentaUsermod : public Usermod byte drawnLines = 0; for (int8_t app = 0; app <= 4; app++) { for (int8_t clp = 0; clp <= 4; clp++) { - if (anPentaPins[app] == currentLedPins[clp]) { + if (anPentaLEDPins[app] == currentLedPins[clp]) { char charCurrentLedcReads[17]; sprintf(charCurrentLedcReads, "LED %d:", app+1); if (oledUseProgressBars) { diff --git a/usermods/quinled-an-penta/readme.md b/usermods/quinled-an-penta/readme.md index c292736c8..4a4c0290a 100644 --- a/usermods/quinled-an-penta/readme.md +++ b/usermods/quinled-an-penta/readme.md @@ -1,12 +1,12 @@ # QuinLED-An-Penta -The (un)official usermod to get the best out of the QuinLED-An-Penta, like using the OLED and the SHT30 temperature/humidity sensor. +The (un)official usermod to get the best out of the QuinLED-An-Penta (https://quinled.info/quinled-an-penta/), like using the OLED and the SHT30 temperature/humidity sensor. ## Requirements * "u8gs" by olikraus, v2.28 or higher: https://github.com/olikraus/u8g2 * "SHT85" by Rob Tillaart, v0.2 or higher: https://github.com/RobTillaart/SHT85 ## Usermod installation -Simply copy the below block (build task) to your `platformio_override.ini` and compile WLED using this new build task. Or use an existing one and add the buildflag `-D QUINLED_AN_PENTA`. +Simply copy the below block (build task) to your `platformio_override.ini` and compile WLED using this new build task. Or use an existing one, add the buildflag `-D QUINLED_AN_PENTA` and the below library dependencies. ESP32 (**without** ethernet): ``` @@ -33,14 +33,19 @@ This mod has been optimized for an SSD1306 driven 128x64 OLED. Using a smaller O I highly recommend using these "two color monochromatic OLEDs", which have the first 16 pixels in a different color than the other 48, e.g. a yellow/blue OLED. Also note, you need to have an **SPI** driven OLED, **not i2c**! +### Limitations combined with Ethernet +The initial development of this mod had been done with a beta version of the QuinLED-An-Penta, which had a different IO layout for the OLED: The CS pin used to be IO_0, but has been changed to IO27 with the first v1 public release. Unfortunately, IO27 is used by the Ethernet boards, so WLED will not let you enable the OLED screen, if you're using it with Ethernet. This unfortunately makes the development I've done to support/show Ethernet information void, as it cannot be used. +However (and I've not tried this, as I don't own a v1 board): You can try to modify this mod and try to use IO27 for the OLED and share it with the Ethernet board. It is "just" the chip select pin, so there is a chance that both can coexist and use the same IO. You need to skip WLEDs PinManager for the CS pin, so WLED will not block using it. If you don't know how this works: Leave it. If you know what I'm talking about: Try it and please let me know on the Intermit.Tech (QuinLED) Discord server: https://discord.gg/WdbAauG + ### My OLED flickers after some time, what should I do? -That's a tricky one: During development I saw that the OLED sometimes starts to "bug out" / flicker and won't work anymore. This seems to be caused by the high PWM interference the board produces. It seems to loose it's settings and then doesn't know how to draw anymore. Turns out the only way to fix this is to call the libraries `begin()` method again which will re-initialize the display. +That's a tricky one: During development I saw that the OLED sometimes starts to "bug out" / flicker and won't work anymore. This seems to be caused by the high PWM interference the board produces. It seems to loose its settings and then doesn't know how to draw anymore. Turns out the only way to fix this is to call the libraries `begin()` method again which will re-initialize the display. If you're facing this issue, you can enable a setting I've added which will call the `begin()` roughly every 60 seconds between a page change. This will make the page change take ~500ms, but will fix the display. + ## Configuration Navigate to the "Config" and then to the "Usermods" section. If you compiled WLED with `-D QUINLED_AN_PENTA`, you will see the config for it there: * Enable-OLED: - * What it does: Enabled the optional SPI driven OLED that can be mounted to the 7-pin female header + * What it does: Enables the optional SPI driven OLED that can be mounted to the 7-pin female header. Won't work with Ethernet, read above. * Possible values: Enabled/Disabled * Default: Disabled * OLED-Use-Progress-Bars: @@ -60,10 +65,15 @@ Navigate to the "Config" and then to the "Usermods" section. If you compiled WLE * Possible values: Enabled/Disabled * Default: Disabled * Enable-SHT30-Temp-Humidity-Sensor: - * What it does: Enabled the onboard SHT30 temperature and humidity sensor + * What it does: Enables the onboard SHT30 temperature and humidity sensor * Possible values: Enabled/Disabled * Default: Disabled ## Change log +2021-12 +* Adjusted IO layout to match An-Penta v1r1 2021-10 -* First implementation. \ No newline at end of file +* First implementation. + +## Credits +ezcGman | Andy: Find me on the Intermit.Tech (QuinLED) Discord server: https://discord.gg/WdbAauG \ No newline at end of file diff --git a/usermods/seven_segment_display_reloaded/readme.md b/usermods/seven_segment_display_reloaded/readme.md new file mode 100644 index 000000000..09479754c --- /dev/null +++ b/usermods/seven_segment_display_reloaded/readme.md @@ -0,0 +1,129 @@ +# Seven Segment Display Reloaded + +Usermod that uses the overlay feature to create a configurable seven segment display. +Optimized for maximum configurability and use with seven segment clocks by parallyze (https://www.instructables.com/member/parallyze/instructables/) +Very loosely based on the existing usermod "seven segment display". + + +## Installation + +Add the compile-time option `-D USERMOD_SSDR` to your `platformio.ini` (or `platformio_override.ini`) or use `#define USERMOD_SSDR` in `my_config.h`. + +For the auto brightness option, the usermod SN_Photoresistor has to be installed as well. See SN_Photoresistor/readme.md for instructions. + +## Settings +All settings can be controlled the usermod setting page. +Part of the settings can be controlled through MQTT with a raw payload or through a json request to /json/state. + +### enabled +Enables/disables this overlay usermod + +### inverted +Enables the inverted mode in which the background should be enabled and the digits should be black (leds off) + +### Colon-blinking +Enables the blinking colon(s) if they are defined + +### enable-auto-brightness +Enables the auto brightness feature. Can be only used with the usermod SN_Photoresistor installed. + +### auto-brightness-min / auto-brightness-max +The lux value calculated from usermod SN_Photoresistor will be mapped to the values defined here. +The mapping is 0 - 1000 lux will be mapped to auto-brightness-min - auto-brightness-max + +The mA current protection of WLED will override the calculated value if it is too high. + +### Display-Mask +Defines the type of the time/date display. +For example "H:m" (default) +- H - 00-23 hours +- h - 01-12 hours +- k - 01-24 hours +- m - 00-59 minutes +- s - 00-59 seconds +- d - 01-31 day of month +- M - 01-12 month +- y - 21 last two positions of year +- Y - 2021 year +- : for a colon + +### LED-Numbers +- LED-Numbers-Hours +- LED-Numbers-Minutes +- LED-Numbers-Seconds +- LED-Numbers-Colons +- LED-Numbers-Day +- LED-Numbers-Month +- LED-Numbers-Year + +See following example for usage. + + +## Example + +Example for Leds definition +``` + < A > +/\ /\ +F B +\/ \/ + < G > +/\ /\ +E C +\/ \/ + < D > +``` + +Leds or Range of Leds are seperated by a comma "," + +Segments are seperated by a semicolon ";" and are read as A;B;C;D;E;F;G + +Digits are seperated by colon ":" -> A;B;C;D;E;F;G:A;B;C;D;E;F;G + +Ranges are defined as lower to higher (lower first) + +For example, an clock definition for the following clock (https://www.instructables.com/Lazy-7-Quick-Build-Edition/) is + +- hour "59,46;47-48;50-51;52-53;54-55;57-58;49,56:0,13;1-2;4-5;6-7;8-9;11-12;3,10" + +- minute "37-38;39-40;42-43;44,31;32-33;35-36;34,41:21-22;23-24;26-27;28,15;16-17;19-20;18,25" + +or + +- hour "6,7;8,9;11,12;13,0;1,2;4,5;3,10:52,53;54,55;57,58;59,46;47,48;50,51;49,56" + +- minute "15,28;16,17;19,20;21,22;23,24;26,27;18,25:31,44;32,33;35,36;37,38;39,40;42,43;34,41" + +depending on the orientation. + +# The example detailed: +hour "59,46;47-48;50-51;52-53;54-55;57-58;49,56:0,13;1-2;4-5;6-7;8-9;11-12;3,10" + +there are two digits seperated by ":" + +- 59,46;47-48;50-51;52-53;54-55;57-58;49,56 +- 0,13;1-2;4-5;6-7;8-9;11-12;3,10 + +In the first digit, +the **segment A** consists of the leds number **59 and 46**., **segment B** consists of the leds number **47, 48** and so on + +The second digit starts again with **segment A** and leds **0 and 13**, **segment B** consists of the leds number **1 and 2** and so on + +### first digit of the hour +- Segment A: 59, 46 +- Segment B: 47, 48 +- Segment C: 50, 51 +- Segment D: 52, 53 +- Segment E: 54, 55 +- Segment F: 57, 58 +- Segment G: 49, 56 + +### second digit of the hour + +- Segment A: 0, 13 +- Segment B: 1, 2 +- Segment C: 4, 5 +- Segment D: 6, 7 +- Segment E: 8, 9 +- Segment F: 11, 12 +- Segment G: 3, 10 \ No newline at end of file diff --git a/usermods/seven_segment_display_reloaded/usermod_seven_segment_reloaded.h b/usermods/seven_segment_display_reloaded/usermod_seven_segment_reloaded.h new file mode 100644 index 000000000..7b89c8d7d --- /dev/null +++ b/usermods/seven_segment_display_reloaded/usermod_seven_segment_reloaded.h @@ -0,0 +1,555 @@ +#pragma once + +#include "wled.h" + +class UsermodSSDR : public Usermod { + +//#define REFRESHTIME 497 + +private: + //Runtime variables. + unsigned long umSSDRLastRefresh = 0; + unsigned long umSSDRResfreshTime = 3000; + bool umSSDRDisplayTime = false; + bool umSSDRInverted = false; + bool umSSDRColonblink = true; + bool umSSDREnableLDR = false; + String umSSDRHours = ""; + String umSSDRMinutes = ""; + String umSSDRSeconds = ""; + String umSSDRColons = ""; + String umSSDRDays = ""; + String umSSDRMonths = ""; + String umSSDRYears = ""; + uint16_t umSSDRLength = 0; + uint16_t umSSDRBrightnessMin = 0; + uint16_t umSSDRBrightnessMax = 255; + + bool* umSSDRMask = 0; + + /*// H - 00-23 hours + // h - 01-12 hours + // k - 01-24 hours + // m - 00-59 minutes + // s - 00-59 seconds + // d - 01-31 day of month + // M - 01-12 month + // y - 21 last two positions of year + // Y - 2021 year + // : for a colon + */ + String umSSDRDisplayMask = "H:m"; //This should reflect physical equipment. + + /* Segment order, seen from the front: + + < A > + /\ /\ + F B + \/ \/ + < G > + /\ /\ + E C + \/ \/ + < D > + + */ + + uint8_t umSSDRNumbers[11][7] = { + // A B C D E F G + { 1, 1, 1, 1, 1, 1, 0 }, // 0 + { 0, 1, 1, 0, 0, 0, 0 }, // 1 + { 1, 1, 0, 1, 1, 0, 1 }, // 2 + { 1, 1, 1, 1, 0, 0, 1 }, // 3 + { 0, 1, 1, 0, 0, 1, 1 }, // 4 + { 1, 0, 1, 1, 0, 1, 1 }, // 5 + { 1, 0, 1, 1, 1, 1, 1 }, // 6 + { 1, 1, 1, 0, 0, 0, 0 }, // 7 + { 1, 1, 1, 1, 1, 1, 1 }, // 8 + { 1, 1, 1, 1, 0, 1, 1 }, // 9 + { 0, 0, 0, 0, 0, 0, 0 } // blank + }; + + //String to reduce flash memory usage + static const char _str_name[]; + static const char _str_ldrEnabled[]; + static const char _str_timeEnabled[]; + static const char _str_inverted[]; + static const char _str_colonblink[]; + static const char _str_displayMask[]; + static const char _str_hours[]; + static const char _str_minutes[]; + static const char _str_seconds[]; + static const char _str_colons[]; + static const char _str_days[]; + static const char _str_months[]; + static const char _str_years[]; + static const char _str_minBrightness[]; + static const char _str_maxBrightness[]; + +#ifdef USERMOD_ID_SN_PHOTORESISTOR + Usermod_SN_Photoresistor *ptr; +#else + void* ptr = nullptr; +#endif + + void _overlaySevenSegmentDraw() { + int displayMaskLen = static_cast(umSSDRDisplayMask.length()); + bool colonsDone = false; + _setAllFalse(); + for (int index = 0; index < displayMaskLen; index++) { + int timeVar = 0; + switch (umSSDRDisplayMask[index]) { + case 'h': + timeVar = hourFormat12(localTime); + _showElements(&umSSDRHours, timeVar, 0, 1); + break; + case 'H': + timeVar = hour(localTime); + _showElements(&umSSDRHours, timeVar, 0, 1); + break; + case 'k': + timeVar = hour(localTime) + 1; + _showElements(&umSSDRHours, timeVar, 0, 0); + break; + case 'm': + timeVar = minute(localTime); + _showElements(&umSSDRMinutes, timeVar, 0, 0); + break; + case 's': + timeVar = second(localTime); + _showElements(&umSSDRSeconds, timeVar, 0, 0); + break; + case 'd': + timeVar = day(localTime); + _showElements(&umSSDRDays, timeVar, 0, 0); + break; + case 'M': + timeVar = month(localTime); + _showElements(&umSSDRMonths, timeVar, 0, 0); + break; + case 'y': + timeVar = second(localTime); + _showElements(&umSSDRYears, timeVar, 0, 0); + break; + case 'Y': + timeVar = year(localTime); + _showElements(&umSSDRYears, timeVar, 0, 0); + break; + case ':': + if (!colonsDone) { // only call _setColons once as all colons are printed when the first colon is found + _setColons(); + colonsDone = true; + } + break; + } + } + _setMaskToLeds(); + } + + void _setColons() { + if ( umSSDRColonblink ) { + if ( second(localTime) % 2 == 0 ) { + _showElements(&umSSDRColons, 0, 1, 0); + } + } else { + _showElements(&umSSDRColons, 0, 1, 0); + } + } + + void _showElements(String *map, int timevar, bool isColon, bool removeZero + +) { + if (!(*map).equals("") && !(*map) == NULL) { + int length = String(timevar).length(); + bool addZero = false; + if (length == 1) { + length = 2; + addZero = true; + } + int timeArr[length]; + if(addZero) { + if(removeZero) + { + timeArr[1] = 10; + timeArr[0] = timevar; + } + else + { + timeArr[1] = 0; + timeArr[0] = timevar; + } + } else { + int count = 0; + while (timevar) { + timeArr[count] = timevar%10; + timevar /= 10; + count++; + }; + } + + + int colonsLen = static_cast((*map).length()); + int count = 0; + int countSegments = 0; + int countDigit = 0; + bool range = false; + int lastSeenLedNr = 0; + + for (int index = 0; index < colonsLen; index++) { + switch ((*map)[index]) { + case '-': + lastSeenLedNr = _checkForNumber(count, index, map); + count = 0; + range = true; + break; + case ':': + _setLeds(_checkForNumber(count, index, map), lastSeenLedNr, range, countSegments, timeArr[countDigit], isColon); + count = 0; + range = false; + countDigit++; + countSegments = 0; + break; + case ';': + _setLeds(_checkForNumber(count, index, map), lastSeenLedNr, range, countSegments, timeArr[countDigit], isColon); + count = 0; + range = false; + countSegments++; + break; + case ',': + _setLeds(_checkForNumber(count, index, map), lastSeenLedNr, range, countSegments, timeArr[countDigit], isColon); + count = 0; + range = false; + break; + default: + count++; + break; + } + } + _setLeds(_checkForNumber(count, colonsLen, map), lastSeenLedNr, range, countSegments, timeArr[countDigit], isColon); + } + } + + void _setLeds(int lednr, int lastSeenLedNr, bool range, int countSegments, int number, bool colon) { + + if ((colon && umSSDRColonblink) || umSSDRNumbers[number][countSegments]) { + + if (range) { + for(int i = lastSeenLedNr; i <= lednr; i++) { + umSSDRMask[i] = true; + } + } else { + umSSDRMask[lednr] = true; + } + } + } + + void _setMaskToLeds() { + for(int i = 0; i <= umSSDRLength; i++) { + if ((!umSSDRInverted && !umSSDRMask[i]) || (umSSDRInverted && umSSDRMask[i])) { + strip.setPixelColor(i, 0x000000); + } + } + } + + void _setAllFalse() { + for(int i = 0; i <= umSSDRLength; i++) { + umSSDRMask[i] = false; + } + } + + int _checkForNumber(int count, int index, String *map) { + String number = (*map).substring(index - count, index); + return number.toInt(); + } + + void _publishMQTTint_P(const char *subTopic, int value) + { + if(mqtt == NULL) return; + + char buffer[64]; + char valBuffer[12]; + sprintf_P(buffer, PSTR("%s/%S/%S"), mqttDeviceTopic, _str_name, subTopic); + sprintf_P(valBuffer, PSTR("%d"), value); + mqtt->publish(buffer, 2, true, valBuffer); + } + + void _publishMQTTstr_P(const char *subTopic, String Value) + { + if(mqtt == NULL) return; + char buffer[64]; + sprintf_P(buffer, PSTR("%s/%S/%S"), mqttDeviceTopic, _str_name, subTopic); + mqtt->publish(buffer, 2, true, Value.c_str(), Value.length()); + } + + bool _cmpIntSetting_P(char *topic, char *payload, const char *setting, void *value) + { + if (strcmp_P(topic, setting) == 0) + { + *((int *)value) = strtol(payload, NULL, 10); + _publishMQTTint_P(setting, *((int *)value)); + return true; + } + return false; + } + + bool _handleSetting(char *topic, char *payload) { + if (_cmpIntSetting_P(topic, payload, _str_timeEnabled, &umSSDRDisplayTime)) { + return true; + } + if (_cmpIntSetting_P(topic, payload, _str_ldrEnabled, &umSSDREnableLDR)) { + return true; + } + if (_cmpIntSetting_P(topic, payload, _str_inverted, &umSSDRInverted)) { + return true; + } + if (_cmpIntSetting_P(topic, payload, _str_colonblink, &umSSDRColonblink)) { + return true; + } + if (strcmp_P(topic, _str_displayMask) == 0) { + umSSDRDisplayMask = String(payload); + _publishMQTTstr_P(_str_displayMask, umSSDRDisplayMask); + return true; + } + return false; + } + + void _updateMQTT() + { + _publishMQTTint_P(_str_timeEnabled, umSSDRDisplayTime); + _publishMQTTint_P(_str_ldrEnabled, umSSDREnableLDR); + _publishMQTTint_P(_str_inverted, umSSDRInverted); + _publishMQTTint_P(_str_colonblink, umSSDRColonblink); + + _publishMQTTstr_P(_str_hours, umSSDRHours); + _publishMQTTstr_P(_str_minutes, umSSDRMinutes); + _publishMQTTstr_P(_str_seconds, umSSDRSeconds); + _publishMQTTstr_P(_str_colons, umSSDRColons); + _publishMQTTstr_P(_str_days, umSSDRDays); + _publishMQTTstr_P(_str_months, umSSDRMonths); + _publishMQTTstr_P(_str_years, umSSDRYears); + _publishMQTTstr_P(_str_displayMask, umSSDRDisplayMask); + + _publishMQTTint_P(_str_minBrightness, umSSDRBrightnessMin); + _publishMQTTint_P(_str_maxBrightness, umSSDRBrightnessMax); + } + + void _addJSONObject(JsonObject& root) { + JsonObject ssdrObj = root[FPSTR(_str_name)]; + if (ssdrObj.isNull()) { + ssdrObj = root.createNestedObject(FPSTR(_str_name)); + } + + ssdrObj[FPSTR(_str_timeEnabled)] = umSSDRDisplayTime; + ssdrObj[FPSTR(_str_ldrEnabled)] = umSSDREnableLDR; + ssdrObj[FPSTR(_str_inverted)] = umSSDRInverted; + ssdrObj[FPSTR(_str_colonblink)] = umSSDRColonblink; + ssdrObj[FPSTR(_str_displayMask)] = umSSDRDisplayMask; + ssdrObj[FPSTR(_str_hours)] = umSSDRHours; + ssdrObj[FPSTR(_str_minutes)] = umSSDRMinutes; + ssdrObj[FPSTR(_str_seconds)] = umSSDRSeconds; + ssdrObj[FPSTR(_str_colons)] = umSSDRColons; + ssdrObj[FPSTR(_str_days)] = umSSDRDays; + ssdrObj[FPSTR(_str_months)] = umSSDRMonths; + ssdrObj[FPSTR(_str_years)] = umSSDRYears; + ssdrObj[FPSTR(_str_minBrightness)] = umSSDRBrightnessMin; + ssdrObj[FPSTR(_str_maxBrightness)] = umSSDRBrightnessMax; + } + +public: + //Functions called by WLED + + /* + * 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() { + umSSDRLength = strip.getLengthTotal(); + if (umSSDRMask != 0) { + umSSDRMask = (bool*) realloc(umSSDRMask, umSSDRLength * sizeof(bool)); + } else { + umSSDRMask = (bool*) malloc(umSSDRLength * sizeof(bool)); + } + _setAllFalse(); + + #ifdef USERMOD_ID_SN_PHOTORESISTOR + ptr = (Usermod_SN_Photoresistor*) usermods.lookup(USERMOD_ID_SN_PHOTORESISTOR); + #endif + DEBUG_PRINTLN(F("Setup done")); + } + + /* + * loop() is called continuously. Here you can check for events, read sensors, etc. + */ + void loop() { + if (!umSSDRDisplayTime || strip.isUpdating()) { + return; + } + #ifdef USERMOD_ID_SN_PHOTORESISTOR + if(bri != 0 && umSSDREnableLDR && (millis() - umSSDRLastRefresh > umSSDRResfreshTime)) { + if (ptr != nullptr) { + uint16_t lux = ptr->getLastLDRValue(); + uint16_t brightness = map(lux, 0, 1000, umSSDRBrightnessMin, umSSDRBrightnessMax); + if (bri != brightness) { + bri = brightness; + colorUpdated(1); + } + } + umSSDRLastRefresh = millis(); + } + #endif + } + + void handleOverlayDraw() { + if (umSSDRDisplayTime) { + _overlaySevenSegmentDraw(); + } + } + +/* + * 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) { + JsonObject user = root[F("u")]; + if (user.isNull()) { + user = root.createNestedObject(F("u")); + } + JsonArray enabled = user.createNestedArray("Time enabled"); + enabled.add(umSSDRDisplayTime); + JsonArray invert = user.createNestedArray("Time inverted"); + invert.add(umSSDRInverted); + JsonArray blink = user.createNestedArray("Blinking colon"); + blink.add(umSSDRColonblink); + JsonArray ldrEnable = user.createNestedArray("Auto Brightness enabled"); + ldrEnable.add(umSSDREnableLDR); + + } + + /* + * 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) { + JsonObject user = root[F("u")]; + if (user.isNull()) { + user = root.createNestedObject(F("u")); + } + _addJSONObject(user); + } + + /* + * 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) { + JsonObject user = root[F("u")]; + if (!user.isNull()) { + JsonObject ssdrObj = user[FPSTR(_str_name)]; + umSSDRDisplayTime = ssdrObj[FPSTR(_str_timeEnabled)] | umSSDRDisplayTime; + umSSDREnableLDR = ssdrObj[FPSTR(_str_ldrEnabled)] | umSSDREnableLDR; + umSSDRInverted = ssdrObj[FPSTR(_str_inverted)] | umSSDRInverted; + umSSDRColonblink = ssdrObj[FPSTR(_str_colonblink)] | umSSDRColonblink; + umSSDRDisplayMask = ssdrObj[FPSTR(_str_displayMask)] | umSSDRDisplayMask; + } + } + + void onMqttConnect(bool sessionPresent) { + char subBuffer[48]; + if (mqttDeviceTopic[0] != 0) + { + _updateMQTT(); + //subscribe for sevenseg messages on the device topic + sprintf_P(subBuffer, PSTR("%s/%S/+/set"), mqttDeviceTopic, _str_name); + mqtt->subscribe(subBuffer, 2); + } + + if (mqttGroupTopic[0] != 0) + { + //subcribe for sevenseg messages on the group topic + sprintf_P(subBuffer, PSTR("%s/%S/+/set"), mqttGroupTopic, _str_name); + mqtt->subscribe(subBuffer, 2); + } + } + + bool onMqttMessage(char *topic, char *payload) { + //If topic beings iwth sevenSeg cut it off, otherwise not our message. + size_t topicPrefixLen = strlen_P(PSTR("/wledSS/")); + if (strncmp_P(topic, PSTR("/wledSS/"), topicPrefixLen) == 0) { + topic += topicPrefixLen; + } else { + return false; + } + //We only care if the topic ends with /set + size_t topicLen = strlen(topic); + if (topicLen > 4 && + topic[topicLen - 4] == '/' && + topic[topicLen - 3] == 's' && + topic[topicLen - 2] == 'e' && + topic[topicLen - 1] == 't') + { + //Trim /set and handle it + topic[topicLen - 4] = '\0'; + _handleSetting(topic, payload); + } + return true; + } + + void addToConfig(JsonObject &root) { + _addJSONObject(root); + } + + bool readFromConfig(JsonObject &root) { + JsonObject top = root[FPSTR(_str_name)]; + + if (top.isNull()) { + DEBUG_PRINT(FPSTR(_str_name)); + DEBUG_PRINTLN(F(": No config found. (Using defaults.)")); + return false; + } + + umSSDRDisplayTime = (top[FPSTR(_str_timeEnabled)] | umSSDRDisplayTime); + umSSDREnableLDR = (top[FPSTR(_str_ldrEnabled)] | umSSDREnableLDR); + umSSDRInverted = (top[FPSTR(_str_inverted)] | umSSDRInverted); + umSSDRColonblink = (top[FPSTR(_str_colonblink)] | umSSDRColonblink); + + umSSDRDisplayMask = top[FPSTR(_str_displayMask)] | umSSDRDisplayMask; + umSSDRHours = top[FPSTR(_str_hours)] | umSSDRHours; + umSSDRMinutes = top[FPSTR(_str_minutes)] | umSSDRMinutes; + umSSDRSeconds = top[FPSTR(_str_seconds)] | umSSDRSeconds; + umSSDRColons = top[FPSTR(_str_colons)] | umSSDRColons; + umSSDRDays = top[FPSTR(_str_days)] | umSSDRDays; + umSSDRMonths = top[FPSTR(_str_months)] | umSSDRMonths; + umSSDRYears = top[FPSTR(_str_years)] | umSSDRYears; + umSSDRBrightnessMin = top[FPSTR(_str_minBrightness)] | umSSDRBrightnessMin; + umSSDRBrightnessMax = top[FPSTR(_str_maxBrightness)] | umSSDRBrightnessMax; + + DEBUG_PRINT(FPSTR(_str_name)); + DEBUG_PRINTLN(F(" config (re)loaded.")); + + return true; + } + /* + * 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_SSDR; + } +}; + +const char UsermodSSDR::_str_name[] PROGMEM = "UsermodSSDR"; +const char UsermodSSDR::_str_timeEnabled[] PROGMEM = "enabled"; +const char UsermodSSDR::_str_inverted[] PROGMEM = "inverted"; +const char UsermodSSDR::_str_colonblink[] PROGMEM = "Colon-blinking"; +const char UsermodSSDR::_str_displayMask[] PROGMEM = "Display-Mask"; +const char UsermodSSDR::_str_hours[] PROGMEM = "LED-Numbers-Hours"; +const char UsermodSSDR::_str_minutes[] PROGMEM = "LED-Numbers-Minutes"; +const char UsermodSSDR::_str_seconds[] PROGMEM = "LED-Numbers-Seconds"; +const char UsermodSSDR::_str_colons[] PROGMEM = "LED-Numbers-Colons"; +const char UsermodSSDR::_str_days[] PROGMEM = "LED-Numbers-Day"; +const char UsermodSSDR::_str_months[] PROGMEM = "LED-Numbers-Month"; +const char UsermodSSDR::_str_years[] PROGMEM = "LED-Numbers-Year"; +const char UsermodSSDR::_str_ldrEnabled[] PROGMEM = "enable-auto-brightness"; +const char UsermodSSDR::_str_minBrightness[] PROGMEM = "auto-brightness-min"; +const char UsermodSSDR::_str_maxBrightness[] PROGMEM = "auto-brightness-max"; 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 c8d235c96..9f1298180 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 @@ -264,7 +264,7 @@ class FourLineDisplayUsermod : public Usermod { bool enabled = true; // needRedraw marks if redraw is required to prevent often redrawing. - bool needRedraw = true; + //bool needRedraw = true; // Next variables hold the previous known values to determine if redraw is // required. @@ -386,7 +386,8 @@ class FourLineDisplayUsermod : public Usermod { setFlipMode(flip); setContrast(contrast); //Contrast setup will help to preserve OLED lifetime. In case OLED need to be brighter increase number up to 255 setPowerSave(0); - drawString(0, 0, "Loading..."); + //drawString(0, 0, "Loading..."); + overlay(PSTR("Loading..."),3000,0); } // gets called every time WiFi is (re-)connected. Initialize own network @@ -465,6 +466,7 @@ class FourLineDisplayUsermod : public Usermod { * or if forceRedraw). */ void redraw(bool forceRedraw) { + bool needRedraw = false; unsigned long now = millis(); if (type == NONE || !enabled) return; @@ -484,9 +486,11 @@ class FourLineDisplayUsermod : public Usermod { if (forceRedraw) { knownHour = 99; needRedraw = true; + clear(); } else if ((bri == 0 && powerON) || (bri > 0 && !powerON)) { //trigger power icon powerON = !powerON; drawStatusIcons(); + updateBrightness(); lastRedraw = millis(); return; } else if (knownnightlight != nightlightActive) { //trigger moon icon @@ -503,21 +507,21 @@ class FourLineDisplayUsermod : public Usermod { } else if (knownMode != effectCurrent) { knownMode = effectCurrent; if (displayTurnedOff) needRedraw = true; - else showCurrentEffectOrPalette(knownMode, JSON_mode_names, 3); + else { showCurrentEffectOrPalette(knownMode, JSON_mode_names, 3); return; } } else if (knownPalette != effectPalette) { - knownPalette = effectPalette; - if (displayTurnedOff) needRedraw = true; - else showCurrentEffectOrPalette(knownPalette, JSON_palette_names, 2); + knownPalette = effectPalette; + if (displayTurnedOff) needRedraw = true; + else { showCurrentEffectOrPalette(knownPalette, JSON_palette_names, 2); return; } } else if (knownBrightness != bri) { - if (displayTurnedOff && nightlightActive){needRedraw = false; knownBrightness = bri;} - else if(displayTurnedOff) needRedraw = true; - else updateBrightness(); + if (displayTurnedOff && nightlightActive) { needRedraw = false; knownBrightness = bri; } + else if (displayTurnedOff) needRedraw = true; + else { updateBrightness(); return; } } else if (knownEffectSpeed != effectSpeed) { if (displayTurnedOff) needRedraw = true; - else updateSpeed(); + else { updateSpeed(); return; } } else if (knownEffectIntensity != effectIntensity) { if (displayTurnedOff) needRedraw = true; - else updateIntensity(); + else { updateIntensity(); return; } } if (!needRedraw) { @@ -526,22 +530,18 @@ class FourLineDisplayUsermod : public Usermod { if (sleepMode && !displayTurnedOff && (millis() - lastRedraw > screenTimeout)) { // We will still check if there is a change in redraw() // and turn it back on if it changed. + clear(); sleepOrClock(true); } else if (displayTurnedOff && clockMode) { showTime(); } return; - } else { - clear(); } - needRedraw = false; - lastRedraw = millis(); + lastRedraw = now; - if (displayTurnedOff) { - // Turn the display back on - sleepOrClock(false); - } + // Turn the display back on + wakeDisplay(); // Update last known values. knownBrightness = bri; @@ -647,24 +647,19 @@ class FourLineDisplayUsermod : public Usermod { knownMode = effectCurrent; knownPalette = effectPalette; if (overlayUntil == 0) { - char smallBuffer1[MAX_MODE_LINE_SPACE]; - char smallBuffer2[MAX_MODE_LINE_SPACE]; - char smallBuffer3[MAX_MODE_LINE_SPACE+1]; - bool spaceHit = false; - uint8_t printedChars = 0; - uint8_t smallChars1 = 0; - uint8_t smallChars2 = 0; - uint8_t smallChars3 = 0; - // Find the mode name in JSON - printedChars = extractModeName(inputEffPal, qstring, lineBuffer, MAX_JSON_CHARS-1); - + uint8_t printedChars = extractModeName(inputEffPal, qstring, lineBuffer, MAX_JSON_CHARS-1); if (lineHeight == 2) { // use this code for 8 line display + char smallBuffer1[MAX_MODE_LINE_SPACE]; + char smallBuffer2[MAX_MODE_LINE_SPACE]; + uint8_t smallChars1 = 0; + uint8_t smallChars2 = 0; if (printedChars < MAX_MODE_LINE_SPACE) { // use big font if the text fits for (;printedChars < (MAX_MODE_LINE_SPACE-1); printedChars++) lineBuffer[printedChars]=' '; lineBuffer[printedChars] = 0; drawString(1, row*lineHeight, lineBuffer); } else { // for long names divide the text into 2 lines and print them small + bool spaceHit = false; for (uint8_t i = 0; i < printedChars; i++) { switch (lineBuffer[i]) { case ' ': @@ -689,6 +684,8 @@ class FourLineDisplayUsermod : public Usermod { drawString(1, row*lineHeight+1, smallBuffer2, true); } } else { // use this code for 4 ling displays + char smallBuffer3[MAX_MODE_LINE_SPACE+1]; + uint8_t smallChars3 = 0; if (printedChars > MAX_MODE_LINE_SPACE) printedChars = MAX_MODE_LINE_SPACE; for (uint8_t i = 0; i < printedChars; i++) smallBuffer3[smallChars3++] = lineBuffer[i]; for (; smallChars3 < (MAX_MODE_LINE_SPACE); smallChars3++) smallBuffer3[smallChars3]=' '; @@ -707,11 +704,10 @@ class FourLineDisplayUsermod : public Usermod { */ bool wakeDisplay() { if (type == NONE || !enabled) return false; - knownHour = 99; if (displayTurnedOff) { + clear(); // Turn the display back on sleepOrClock(false); - redraw(true); return true; } return false; @@ -723,29 +719,23 @@ class FourLineDisplayUsermod : public Usermod { * Clears the screen and prints. */ void overlay(const char* line1, long showHowLong, byte glyphType) { - if (displayTurnedOff) { - // Turn the display back on - sleepOrClock(false); - } - + // Turn the display back on + wakeDisplay(); // Print the overlay - clear(); if (glyphType > 0) { if (lineHeight == 2) drawGlyph(5, 0, glyphType, u8x8_font_benji_custom_icons_6x6, true); else drawGlyph(7, lineHeight, glyphType, u8x8_font_benji_custom_icons_2x2, true); + if (line1) drawString(0, 3*lineHeight, line1); + } else { + if (line1) drawString(0, 2*(lineHeight-1), line1); } - if (line1) drawString(0, 3*lineHeight, line1); overlayUntil = millis() + showHowLong; } void networkOverlay(const char* line1, long showHowLong) { - if (displayTurnedOff) { - // Turn the display back on - sleepOrClock(false); - } + // Turn the display back on + wakeDisplay(); // Print the overlay - clear(); - // First row string if (line1) { String l1 = line1; l1.trim(); @@ -782,16 +772,15 @@ class FourLineDisplayUsermod : public Usermod { */ void sleepOrClock(bool enabled) { if (enabled) { + displayTurnedOff = true; if (clockMode) { - clear(); knownMinute = knownHour = 99; showTime(); } else setPowerSave(1); - displayTurnedOff = true; } else { - setPowerSave(0); displayTurnedOff = false; + setPowerSave(0); } } @@ -801,7 +790,7 @@ class FourLineDisplayUsermod : public Usermod { * the useAMPM configuration. */ void showTime() { - if (type == NONE || !enabled) return; + if (type == NONE || !enabled || !displayTurnedOff) return; char lineBuffer[LINE_BUFFER_SIZE]; static byte lastSecond; 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 dcf62464e..9d2873c2e 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 @@ -19,17 +19,20 @@ // Change between modes by pressing a button. // // Dependencies -// * This usermod REQURES the ModeSortUsermod // * This Usermod works best coupled with // FourLineDisplayUsermod. // -// If FourLineDisplayUsermod is used the folowing options are also inabled +// If FourLineDisplayUsermod is used the folowing options are also enabled // // * main color // * saturation of main color // * display network (long press buttion) // +#ifdef USERMOD_MODE_SORT + #error "Usermod Mode Sort is no longer required. Remove -D USERMOD_MODE_SORT from platformio.ini" +#endif + #ifndef ENCODER_DT_PIN #define ENCODER_DT_PIN 18 #endif @@ -49,10 +52,70 @@ #define LAST_UI_STATE 4 #endif +// Number of modes at the start of the list to not sort +#define MODE_SORT_SKIP_COUNT 1 + +// Which list is being sorted +static char **listBeingSorted; + +/** + * Modes and palettes are stored as strings that + * end in a quote character. Compare two of them. + * We are comparing directly within either + * JSON_mode_names or JSON_palette_names. + */ +static int re_qstringCmp(const void *ap, const void *bp) { + char *a = listBeingSorted[*((byte *)ap)]; + char *b = listBeingSorted[*((byte *)bp)]; + int i = 0; + do { + char aVal = pgm_read_byte_near(a + i); + if (aVal >= 97 && aVal <= 122) { + // Lowercase + aVal -= 32; + } + char bVal = pgm_read_byte_near(b + i); + if (bVal >= 97 && bVal <= 122) { + // Lowercase + bVal -= 32; + } + // Relly we shouldn't ever get to '\0' + if (aVal == '"' || bVal == '"' || aVal == '\0' || bVal == '\0') { + // We're done. one is a substring of the other + // or something happenend and the quote didn't stop us. + if (aVal == bVal) { + // Same value, probably shouldn't happen + // with this dataset + return 0; + } + else if (aVal == '"' || aVal == '\0') { + return -1; + } + else { + return 1; + } + } + if (aVal == bVal) { + // Same characters. Move to the next. + i++; + continue; + } + // We're done + if (aVal < bVal) { + return -1; + } + else { + return 1; + } + } while (true); + // We shouldn't get here. + return 0; +} + class RotaryEncoderUIUsermod : public Usermod { private: - int fadeAmount = 5; // Amount to change every step (brightness) + int fadeAmount = 5; // Amount to change every step (brightness) unsigned long currentTime; unsigned long loopTime; unsigned long buttonHoldTime; @@ -72,7 +135,16 @@ private: void* display = nullptr; #endif + // Pointers the start of the mode names within JSON_mode_names + char **modes_qstrings = nullptr; + + // Array of mode indexes in alphabetical order. byte *modes_alpha_indexes = nullptr; + + // Pointers the start of the palette names within JSON_palette_names + char **palettes_qstrings = nullptr; + + // Array of palette indexes in alphabetical order. byte *palettes_alpha_indexes = nullptr; unsigned char Enc_A; @@ -95,6 +167,82 @@ private: static const char _CLK_pin[]; static const char _SW_pin[]; + /** + * Sort the modes and palettes to the index arrays + * modes_alpha_indexes and palettes_alpha_indexes. + */ + void sortModesAndPalettes() { + modes_qstrings = re_findModeStrings(JSON_mode_names, strip.getModeCount()); + modes_alpha_indexes = re_initIndexArray(strip.getModeCount()); + re_sortModes(modes_qstrings, modes_alpha_indexes, strip.getModeCount(), MODE_SORT_SKIP_COUNT); + + palettes_qstrings = re_findModeStrings(JSON_palette_names, strip.getPaletteCount()); + palettes_alpha_indexes = re_initIndexArray(strip.getPaletteCount()); + + // How many palette names start with '*' and should not be sorted? + // (Also skipping the first one, 'Default'). + int skipPaletteCount = 1; + while (pgm_read_byte_near(palettes_qstrings[skipPaletteCount++]) == '*') ; + re_sortModes(palettes_qstrings, palettes_alpha_indexes, strip.getPaletteCount(), skipPaletteCount); + } + + byte *re_initIndexArray(int numModes) { + byte *indexes = (byte *)malloc(sizeof(byte) * numModes); + for (byte i = 0; i < numModes; i++) { + indexes[i] = i; + } + return indexes; + } + + /** + * Return an array of mode or palette names from the JSON string. + * They don't end in '\0', they end in '"'. + */ + char **re_findModeStrings(const char json[], int numModes) { + char **modeStrings = (char **)malloc(sizeof(char *) * numModes); + uint8_t modeIndex = 0; + bool insideQuotes = false; + // advance past the mark for markLineNum that may exist. + char singleJsonSymbol; + + // Find the mode name in JSON + bool complete = false; + for (size_t i = 0; i < strlen_P(json); i++) { + singleJsonSymbol = pgm_read_byte_near(json + i); + if (singleJsonSymbol == '\0') break; + switch (singleJsonSymbol) { + case '"': + insideQuotes = !insideQuotes; + if (insideQuotes) { + // We have a new mode or palette + modeStrings[modeIndex] = (char *)(json + i + 1); + } + break; + case '[': + break; + case ']': + if (!insideQuotes) complete = true; + break; + case ',': + if (!insideQuotes) modeIndex++; + default: + if (!insideQuotes) break; + } + if (complete) break; + } + return modeStrings; + } + + /** + * Sort either the modes or the palettes using quicksort. + */ + void re_sortModes(char **modeNames, byte *indexes, int count, int numSkip) { + listBeingSorted = modeNames; + qsort(indexes + numSkip, count - numSkip, sizeof(byte), re_qstringCmp); + listBeingSorted = nullptr; + } + + public: /* * setup() is called once at boot. WiFi is not yet connected at this point. @@ -121,9 +269,7 @@ public: currentTime = millis(); loopTime = currentTime; - ModeSortUsermod *modeSortUsermod = (ModeSortUsermod*) usermods.lookup(USERMOD_ID_MODE_SORT); - modes_alpha_indexes = modeSortUsermod->getModesAlphaIndexes(); - palettes_alpha_indexes = modeSortUsermod->getPalettesAlphaIndexes(); + if (!initDone) sortModesAndPalettes(); #ifdef USERMOD_FOUR_LINE_DISPLAY // This Usermod uses FourLineDisplayUsermod for the best experience. @@ -350,7 +496,7 @@ public: } #endif if (increase) bri = (bri + fadeAmount <= 255) ? (bri + fadeAmount) : 255; - else bri = (bri - fadeAmount >= 0) ? (bri - fadeAmount) : 0; + else bri = (bri - fadeAmount >= 0) ? (bri - fadeAmount) : 0; lampUdated(); #ifdef USERMOD_FOUR_LINE_DISPLAY display->updateBrightness(); @@ -365,8 +511,7 @@ public: return; } #endif - if (increase) effectCurrentIndex = (effectCurrentIndex + 1 >= strip.getModeCount()) ? 0 : (effectCurrentIndex + 1); - else effectCurrentIndex = (effectCurrentIndex - 1 < 0) ? (strip.getModeCount() - 1) : (effectCurrentIndex - 1); + effectCurrentIndex = max(min((increase ? effectCurrentIndex+1 : effectCurrentIndex-1), strip.getModeCount()-1), 0); effectCurrent = modes_alpha_indexes[effectCurrentIndex]; lampUdated(); #ifdef USERMOD_FOUR_LINE_DISPLAY @@ -382,8 +527,7 @@ public: return; } #endif - if (increase) effectSpeed = (effectSpeed + fadeAmount <= 255) ? (effectSpeed + fadeAmount) : 255; - else effectSpeed = (effectSpeed - fadeAmount >= 0) ? (effectSpeed - fadeAmount) : 0; + effectSpeed = max(min((increase ? effectSpeed+fadeAmount : effectSpeed-fadeAmount), 255), 0); lampUdated(); #ifdef USERMOD_FOUR_LINE_DISPLAY display->updateSpeed(); @@ -398,8 +542,7 @@ public: return; } #endif - if (increase) effectIntensity = (effectIntensity + fadeAmount <= 255) ? (effectIntensity + fadeAmount) : 255; - else effectIntensity = (effectIntensity - fadeAmount >= 0) ? (effectIntensity - fadeAmount) : 0; + effectIntensity = max(min((increase ? effectIntensity+fadeAmount : effectIntensity-fadeAmount), 255), 0); lampUdated(); #ifdef USERMOD_FOUR_LINE_DISPLAY display->updateIntensity(); @@ -414,8 +557,7 @@ public: return; } #endif - if (increase) effectPaletteIndex = (effectPaletteIndex + 1 >= strip.getPaletteCount()) ? 0 : (effectPaletteIndex + 1); - else effectPaletteIndex = (effectPaletteIndex - 1 < 0) ? (strip.getPaletteCount() - 1) : (effectPaletteIndex - 1); + effectPaletteIndex = max(min((increase ? effectPaletteIndex+1 : effectPaletteIndex-1), strip.getPaletteCount()-1), 0); effectPalette = palettes_alpha_indexes[effectPaletteIndex]; lampUdated(); #ifdef USERMOD_FOUR_LINE_DISPLAY @@ -449,8 +591,7 @@ public: return; } #endif - if (increase) { if (currentSat1<252) currentSat1 += 4; } - else { if (currentSat1>3) currentSat1 -= 4; } + currentSat1 = max(min((increase ? currentSat1+fadeAmount : currentSat1-fadeAmount), 255), 0); colorHStoRGB(currentHue1*256, currentSat1, col); strip.applyToAllSelected = true; strip.setColor(0, colorFromRgbw(col)); diff --git a/wled00/FX.cpp b/wled00/FX.cpp index de7ecc5dd..bad85e5ac 100644 --- a/wled00/FX.cpp +++ b/wled00/FX.cpp @@ -2091,7 +2091,7 @@ uint16_t WS2812FX::mode_colortwinkle() } } } - return FRAMETIME; + return FRAMETIME_FIXED; } @@ -2876,7 +2876,7 @@ uint16_t WS2812FX::candle(bool multi) } } - return FRAMETIME; + return FRAMETIME_FIXED; } uint16_t WS2812FX::mode_candle() @@ -3904,18 +3904,24 @@ uint16_t WS2812FX::mode_washing_machine(void) { Modified, originally by Mark Kriegsman https://gist.github.com/kriegsman/1f7ccbbfa492a73c015e */ uint16_t WS2812FX::mode_blends(void) { - uint16_t dataSize = sizeof(uint32_t) * SEGLEN; // max segment length of 56 pixels on 16 segment ESP8266 + uint16_t pixelLen = SEGLEN > UINT8_MAX ? UINT8_MAX : SEGLEN; + uint16_t dataSize = sizeof(uint32_t) * (pixelLen + 1); // max segment length of 56 pixels on 16 segment ESP8266 if (!SEGENV.allocateData(dataSize)) return mode_static(); //allocation failed uint32_t* pixels = reinterpret_cast(SEGENV.data); uint8_t blendSpeed = map(SEGMENT.intensity, 0, UINT8_MAX, 10, 128); - uint8_t shift = (now * ((SEGMENT.speed >> 3) +1)) >> 8; + uint8_t shift = (now * ((SEGMENT.speed >> 3) +1)) >> 8; - for (int i = 0; i < SEGLEN; i++) { + for (int i = 0; i < pixelLen; i++) { pixels[i] = color_blend(pixels[i], color_from_palette(shift + quadwave8((i + 1) * 16), false, PALETTE_SOLID_WRAP, 255), blendSpeed); - setPixelColor(i, pixels[i]); shift += 3; } + uint16_t offset = 0; + for (int i = 0; i < SEGLEN; i++) { + setPixelColor(i, pixels[offset++]); + if (offset > pixelLen) offset = 0; + } + return FRAMETIME; } diff --git a/wled00/FX.h b/wled00/FX.h index 034293098..7ea54fe9d 100644 --- a/wled00/FX.h +++ b/wled00/FX.h @@ -48,7 +48,8 @@ /* Not used in all effects yet */ #define WLED_FPS 42 -#define FRAMETIME (1000/WLED_FPS) +#define FRAMETIME_FIXED (1000/WLED_FPS) +#define FRAMETIME _frametime /* each segment uses 52 bytes of SRAM memory, so if you're application fails because of insufficient memory, decreasing MAX_NUM_SEGMENTS may help */ @@ -71,7 +72,7 @@ #define FAIR_DATA_PER_SEG (MAX_SEGMENT_DATA / MAX_NUM_SEGMENTS) #define LED_SKIP_AMOUNT 1 -#define MIN_SHOW_DELAY 15 +#define MIN_SHOW_DELAY (_frametime < 16 ? 8 : 15) #define NUM_COLORS 3 /* number of colors per segment */ #define SEGMENT _segments[_segment_index] @@ -655,6 +656,7 @@ class WS2812FX { setPixelColor(uint16_t n, uint32_t c), setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b, uint8_t w = 0), show(void), + setTargetFps(uint8_t fps), setPixelSegment(uint8_t n), deserializeMap(uint8_t n=0); @@ -685,6 +687,7 @@ class WS2812FX { getActiveSegmentsNum(void), //getFirstSelectedSegment(void), getMainSegmentId(void), + getTargetFps(void), gamma8(uint8_t), gamma8_cal(uint8_t, float), sin_gap(uint16_t), @@ -856,6 +859,8 @@ class WS2812FX { uint16_t _usedSegmentData = 0; uint16_t _transitionDur = 750; + uint8_t _targetFps = 42; + uint16_t _frametime = (1000/42); uint16_t _cumulativeFps = 2; bool @@ -922,6 +927,11 @@ class WS2812FX { transitionProgress(uint8_t tNr); }; +extern const char JSON_mode_names[]; +extern const char JSON_palette_names[]; + +// the following has been moved to FX_fcn.cpp instead +/* // WLEDSR: extensions // Technical notes // =============== @@ -1009,9 +1019,9 @@ const char JSON_mode_names[] PROGMEM = R"=====([ "Stream 2", "Oscillate", "Pride 2015", -"Juggle@!,Trail;!,!,;!", +"Juggle@!=16,Trail=240;!,!,;!", "Palette@!,;;!", -"Fire 2012@Spark rate,Decay;;!", +"Fire 2012@Spark rate=120,Decay=64;;!", "Colorwaves", "Bpm", "Fill Noise", @@ -1033,7 +1043,7 @@ const char JSON_mode_names[] PROGMEM = R"=====([ "Spots@Spread,Width;!,!,;!", "Spots Fade@Spread,Width;!,!,;!", "Glitter", -"Candle@Flicker rate,Flicker intensity;!,!,;0", +"Candle@Flicker rate=96,Flicker intensity=224;!,!,;0", "Fireworks Starburst", "Fireworks 1D@Gravity,Firing side;!,!,;!", "Bouncing Balls@Gravity,# of balls;!,!,;!", @@ -1047,9 +1057,9 @@ const char JSON_mode_names[] PROGMEM = R"=====([ "Ripple Rainbow", "Heartbeat", "Pacifica", -"Candle Multi@Flicker rate,Flicker intensity;!,!,;0", +"Candle Multi@Flicker rate=96,Flicker intensity=224;!,!,;0", "Solid Glitter@,!;!,,;0", -"Sunrise@Time [min],;;0", +"Sunrise@Time [min]=60,;;0", "Phased", "Twinkleup@!,Intensity;!,!,;!", "Noise Pal", @@ -1076,5 +1086,5 @@ const char JSON_palette_names[] PROGMEM = R"=====([ "Semi Blue","Pink Candy","Red Reaf","Aqua Flash","Yelblu Hot","Lite Light","Red Flash","Blink Red","Red Shift","Red Tide", "Candy2" ])====="; - +*/ #endif diff --git a/wled00/FX_fcn.cpp b/wled00/FX_fcn.cpp index 9ab756635..16a0efbeb 100644 --- a/wled00/FX_fcn.cpp +++ b/wled00/FX_fcn.cpp @@ -165,12 +165,12 @@ void WS2812FX::service() { _triggered = false; } -void WS2812FX::setPixelColor(uint16_t n, uint32_t c) { +void IRAM_ATTR WS2812FX::setPixelColor(uint16_t n, uint32_t c) { setPixelColor(n, R(c), G(c), B(c), W(c)); } //used to map from segment index to physical pixel, taking into account grouping, offsets, reverse and mirroring -uint16_t WS2812FX::realPixelIndex(uint16_t i) { +uint16_t IRAM_ATTR WS2812FX::realPixelIndex(uint16_t i) { int16_t iGroup = i * SEGMENT.groupLength(); /* reverse just an individual segment */ @@ -187,7 +187,7 @@ uint16_t WS2812FX::realPixelIndex(uint16_t i) { return realIndex; } -void WS2812FX::setPixelColor(uint16_t i, byte r, byte g, byte b, byte w) +void IRAM_ATTR WS2812FX::setPixelColor(uint16_t i, byte r, byte g, byte b, byte w) { if (SEGLEN) {//from segment uint16_t realIndex = realPixelIndex(i); @@ -350,6 +350,15 @@ uint16_t WS2812FX::getFps() { return _cumulativeFps +1; } +uint8_t WS2812FX::getTargetFps() { + return _targetFps; +} + +void WS2812FX::setTargetFps(uint8_t fps) { + if (fps > 0 && fps <= 120) _targetFps = fps; + _frametime = 1000 / _targetFps; +} + /** * Forces the next frame to be computed on all active segments. */ @@ -775,7 +784,7 @@ void WS2812FX::setTransitionMode(bool t) /* * color blend function */ -uint32_t WS2812FX::color_blend(uint32_t color1, uint32_t color2, uint16_t blend, bool b16) { +uint32_t IRAM_ATTR WS2812FX::color_blend(uint32_t color1, uint32_t color2, uint16_t blend, bool b16) { if(blend == 0) return color1; uint16_t blendmax = b16 ? 0xFFFF : 0xFF; if(blend == blendmax) return color2; @@ -878,13 +887,13 @@ void WS2812FX::blur(uint8_t blur_amount) } } -uint16_t WS2812FX::triwave16(uint16_t in) +uint16_t IRAM_ATTR WS2812FX::triwave16(uint16_t in) { if (in < 0x8000) return in *2; return 0xFFFF - (in - 0x8000)*2; } -uint8_t WS2812FX::sin_gap(uint16_t in) { +uint8_t IRAM_ATTR WS2812FX::sin_gap(uint16_t in) { if (in & 0x100) return 0; //if (in > 255) return 0; return sin8(in + 192); //correct phase shift of sine so that it starts and stops at 0 @@ -951,13 +960,13 @@ uint8_t WS2812FX::get_random_wheel_index(uint8_t pos) { } -uint32_t WS2812FX::crgb_to_col(CRGB fastled) +uint32_t IRAM_ATTR WS2812FX::crgb_to_col(CRGB fastled) { return RGBW32(fastled.red, fastled.green, fastled.blue, 0); } -CRGB WS2812FX::col_to_crgb(uint32_t color) +CRGB IRAM_ATTR WS2812FX::col_to_crgb(uint32_t color) { CRGB fastled_col; fastled_col.red = R(color); @@ -1080,7 +1089,7 @@ void WS2812FX::handle_palette(void) * @param pbri Value to scale the brightness of the returned color by. Default is 255. (no scaling) * @returns Single color from palette */ -uint32_t WS2812FX::color_from_palette(uint16_t i, bool mapping, bool wrap, uint8_t mcol, uint8_t pbri) +uint32_t IRAM_ATTR WS2812FX::color_from_palette(uint16_t i, bool mapping, bool wrap, uint8_t mcol, uint8_t pbri) { if (SEGMENT.palette == 0 && mcol < 3) { uint32_t color = SEGCOLOR(mcol); @@ -1121,11 +1130,7 @@ void WS2812FX::deserializeMap(uint8_t n) { return; } - #ifdef WLED_USE_DYNAMIC_JSON - DynamicJsonDocument doc(JSON_BUFFER_SIZE); - #else if (!requestJSONBufferLock(7)) return; - #endif DEBUG_PRINT(F("Reading LED map from ")); DEBUG_PRINTLN(fileName); @@ -1208,4 +1213,159 @@ WS2812FX* WS2812FX::instance = nullptr; //Bus static member definition, would belong in bus_manager.cpp int16_t Bus::_cct = -1; uint8_t Bus::_cctBlend = 0; -uint8_t Bus::_autoWhiteMode = RGBW_MODE_DUAL; \ No newline at end of file +uint8_t Bus::_autoWhiteMode = RGBW_MODE_DUAL; + + +// WLEDSR: extensions +// Technical notes +// =============== +// If an effect name is followed by an @, slider and color control is effective. +// See setSliderAndColorControl in index.js for implementation +// If not effective then: +// - For AC effects (id<128) 2 sliders and 3 colors and the palette will be shown +// - For SR effects (id>128) 5 sliders and 3 colors and the palette will be shown +// If effective (@) +// - a ; seperates slider controls (left) from color controls (middle) and palette control (right) +// - if left, middle or right is empty no controls are shown +// - a , seperates slider controls (max 5) or color controls (max 3). Palette has only one value +// - a ! means that the default is used. +// - For sliders: Effect speeds, Effect intensity, Custom 1, Custom 2, Custom 3 +// - For colors: Fx color, Background color, Custom +// - For palette: prompt for color palette OR palette ID if numeric (will hide palette selection) +// +// Note: If palette is on and no colors are specified 1,2 and 3 is shown in each color circle. +// If a color is specified, the 1,2 or 3 is replaced by that specification. +// Note: Effects can override default pattern behaviour +// - FadeToBlack can override the background setting +// - Defining SEGCOL() can override a specific palette using these values (e.g. Color Gradient) +const char JSON_mode_names[] PROGMEM = R"=====([ +"Solid", +"Blink@!,;!,!,;!", +"Breathe@!,;!,!;!", +"Wipe@!,!;!,!,;!", +"Wipe Random@!,;;!", +"Random Colors@!,Fade time;;!", +"Sweep@!,!;!,!,;!", +"Dynamic", +"Colorloop@!,Saturation;;!", +"Rainbow", +"Scan@!,# of dots;!,!,;!", +"Scan Dual@!,# of dots;!,!,;!", +"Fade", +"Theater@!,Gap size;!,!,;!", +"Theater Rainbow", +"Running@!,Wave width;!,!,;!", +"Saw@!,Width;!,!,;!", +"Twinkle", +"Dissolve", +"Dissolve Rnd", +"Sparkle", +"Sparkle Dark", +"Sparkle+", +"Strobe", +"Strobe Rainbow", +"Strobe Mega", +"Blink Rainbow", +"Android", +"Chase", +"Chase Random", +"Chase Rainbow", +"Chase Flash", +"Chase Flash Rnd", +"Rainbow Runner", +"Colorful", +"Traffic Light", +"Sweep Random", +"Chase 2@!,Width;!,!,;!", +"Aurora", +"Stream", +"Scanner", +"Lighthouse", +"Fireworks", +"Rain", +"Tetrix@!,Width;!,!,;!", +"Fire Flicker", +"Gradient", +"Loading", +"Police@!,Width;;0", +"Fairy", +"Two Dots@!,Dot size;1,2,Bg;!", +"Fairy Twinkle", +"Running Dual", +"Halloween", +"Chase 3@!,Size;1,2,3;0", +"Tri Wipe@!,Width;1,2,3;0", +"Tri Fade", +"Lightning", +"ICU", +"Multi Comet", +"Scanner Dual", +"Stream 2", +"Oscillate", +"Pride 2015", +"Juggle@!=16,Trail=240;!,!,;!", +"Palette@!,;;!", +"Fire 2012@Spark rate=120,Decay=64;;!", +"Colorwaves", +"Bpm", +"Fill Noise", +"Noise 1", +"Noise 2", +"Noise 3", +"Noise 4", +"Colortwinkles", +"Lake", +"Meteor@!,Trail length;!,!,;!", +"Meteor Smooth@!,Trail length;!,!,;!", +"Railway", +"Ripple", +"Twinklefox", +"Twinklecat", +"Halloween Eyes", +"Solid Pattern@Fg size,Bg size;Fg,Bg,;!=0", +"Solid Pattern Tri@,Size;1,2,3;!=0", +"Spots@Spread,Width;!,!,;!", +"Spots Fade@Spread,Width;!,!,;!", +"Glitter", +"Candle@Flicker rate=96,Flicker intensity=224;!,!,;0", +"Fireworks Starburst", +"Fireworks 1D@Gravity,Firing side;!,!,;!", +"Bouncing Balls@Gravity,# of balls;!,!,;!", +"Sinelon", +"Sinelon Dual", +"Sinelon Rainbow", +"Popcorn@", +"Drip@Gravity,# of drips;!,!;!", +"Plasma@Phase,;1,2,3;!", +"Percent@,% of fill;!,!,;!", +"Ripple Rainbow", +"Heartbeat", +"Pacifica", +"Candle Multi@Flicker rate=96,Flicker intensity=224;!,!,;0", +"Solid Glitter@,!;!,,;0", +"Sunrise@Time [min]=60,;;0", +"Phased", +"Twinkleup@!,Intensity;!,!,;!", +"Noise Pal", +"Sine", +"Phased Noise", +"Flow", +"Chunchun@!,Gap size;!,!,;!", +"Dancing Shadows", +"Washing Machine", +"Candy Cane", +"Blends", +"TV Simulator", +"Dynamic Smooth" +])====="; + +const char JSON_palette_names[] PROGMEM = R"=====([ +"Default","* Random Cycle","* Color 1","* Colors 1&2","* Color Gradient","* Colors Only","Party","Cloud","Lava","Ocean", +"Forest","Rainbow","Rainbow Bands","Sunset","Rivendell","Breeze","Red & Blue","Yellowout","Analogous","Splash", +"Pastel","Sunset 2","Beech","Vintage","Departure","Landscape","Beach","Sherbet","Hult","Hult 64", +"Drywet","Jul","Grintage","Rewhi","Tertiary","Fire","Icefire","Cyane","Light Pink","Autumn", +"Magenta","Magred","Yelmag","Yelblu","Orange & Teal","Tiamat","April Night","Orangery","C9","Sakura", +"Aurora","Atlantica","C9 2","C9 New","Temperature","Aurora 2","Retro Clown","Candy","Toxy Reaf","Fairy Reaf", +"Semi Blue","Pink Candy","Red Reaf","Aqua Flash","Yelblu Hot","Lite Light","Red Flash","Blink Red","Red Shift","Red Tide", +"Candy2" +])====="; diff --git a/wled00/bus_manager.h b/wled00/bus_manager.h index 00f4993f0..4cf56c795 100644 --- a/wled00/bus_manager.h +++ b/wled00/bus_manager.h @@ -288,7 +288,7 @@ class BusPwm : public Bus { if (!pinManager.allocatePin(currentPin, true, PinOwner::BusPwm)) { deallocatePins(); return; } - _pins[i] = currentPin; // store only after allocatePin() succeeds + _pins[i] = currentPin; //store only after allocatePin() succeeds #ifdef ESP8266 pinMode(_pins[i], OUTPUT); #else @@ -396,7 +396,7 @@ class BusPwm : public Bus { private: uint8_t _pins[5] = {255, 255, 255, 255, 255}; - uint8_t _data[5] = {255, 255, 255, 255, 255}; + uint8_t _data[5] = {0}; #ifdef ARDUINO_ARCH_ESP32 uint8_t _ledcStart = 255; #endif diff --git a/wled00/button.cpp b/wled00/button.cpp index aef18c77e..96cdfed5a 100644 --- a/wled00/button.cpp +++ b/wled00/button.cpp @@ -20,7 +20,7 @@ void shortPressAction(uint8_t b) default: ++effectCurrent %= strip.getModeCount(); colorUpdated(CALL_MODE_BUTTON); break; } } else { - applyPreset(macroButton[b], CALL_MODE_BUTTON); + applyPreset(macroButton[b], CALL_MODE_BUTTON_PRESET); } // publish MQTT message @@ -39,7 +39,7 @@ void longPressAction(uint8_t b) default: bri += 8; colorUpdated(CALL_MODE_BUTTON); buttonPressedTime[b] = millis(); break; // repeatable action } } else { - applyPreset(macroLongPress[b], CALL_MODE_BUTTON); + applyPreset(macroLongPress[b], CALL_MODE_BUTTON_PRESET); } // publish MQTT message @@ -58,7 +58,7 @@ void doublePressAction(uint8_t b) default: ++effectPalette %= strip.getPaletteCount(); colorUpdated(CALL_MODE_BUTTON); break; } } else { - applyPreset(macroDoublePress[b], CALL_MODE_BUTTON); + applyPreset(macroDoublePress[b], CALL_MODE_BUTTON_PRESET); } // publish MQTT message @@ -105,12 +105,12 @@ void handleSwitch(uint8_t b) if (millis() - buttonPressedTime[b] > WLED_DEBOUNCE_THRESHOLD) { //fire edge event only after 50ms without change (debounce) if (!buttonPressedBefore[b]) { // on -> off - if (macroButton[b]) applyPreset(macroButton[b], CALL_MODE_BUTTON); + if (macroButton[b]) applyPreset(macroButton[b], CALL_MODE_BUTTON_PRESET); else { //turn on if (!bri) {toggleOnOff(); colorUpdated(CALL_MODE_BUTTON);} } } else { // off -> on - if (macroLongPress[b]) applyPreset(macroLongPress[b], CALL_MODE_BUTTON); + if (macroLongPress[b]) applyPreset(macroLongPress[b], CALL_MODE_BUTTON_PRESET); else { //turn off if (bri) {toggleOnOff(); colorUpdated(CALL_MODE_BUTTON);} } diff --git a/wled00/cfg.cpp b/wled00/cfg.cpp index 5784469a7..1136ace92 100644 --- a/wled00/cfg.cpp +++ b/wled00/cfg.cpp @@ -86,8 +86,9 @@ bool deserializeConfig(JsonObject doc, bool fromFS) { Bus::setAutoWhiteMode(hw_led[F("rgbwm")] | Bus::getAutoWhiteMode()); CJSON(correctWB, hw_led["cct"]); CJSON(cctFromRgb, hw_led[F("cr")]); - CJSON(strip.cctBlending, hw_led[F("cb")]); - Bus::setCCTBlend(strip.cctBlending); + CJSON(strip.cctBlending, hw_led[F("cb")]); + Bus::setCCTBlend(strip.cctBlending); + strip.setTargetFps(hw_led["fps"]); //NOP if 0, default 42 FPS JsonArray ins = hw_led["ins"]; @@ -369,7 +370,7 @@ bool deserializeConfig(JsonObject doc, bool fromFS) { CJSON(timerMinutes[it], timer["min"]); CJSON(timerMacro[it], timer["macro"]); - byte dowPrev = timerWeekday[it]; + byte dowPrev = timerWeekday[it]; //note: act is currently only 0 or 1. //the reason we are not using bool is that the on-disk type in 0.11.0 was already int int actPrev = timerWeekday[it] & 0x01; @@ -379,7 +380,17 @@ bool deserializeConfig(JsonObject doc, bool fromFS) { int act = timer["en"] | actPrev; if (act) timerWeekday[it]++; } - + if (it<8) { + JsonObject start = timer["start"]; + byte startm = start["mon"]; + if (startm) timerMonth[it] = (startm << 4); + CJSON(timerDay[it], start["day"]); + JsonObject end = timer["end"]; + CJSON(timerDayEnd[it], end["day"]); + byte endm = end["mon"]; + if (startm) timerMonth[it] += endm & 0x0F; + if (!(timerMonth[it] & 0x0F)) timerMonth[it] += 12; //default end month to 12 + } it++; } @@ -430,11 +441,7 @@ void deserializeConfigFromFS() { return; } - #ifdef WLED_USE_DYNAMIC_JSON - DynamicJsonDocument doc(JSON_BUFFER_SIZE); - #else if (!requestJSONBufferLock(1)) return; - #endif DEBUG_PRINTLN(F("Reading settings from /cfg.json...")); @@ -458,11 +465,7 @@ void serializeConfig() { DEBUG_PRINTLN(F("Writing settings to /cfg.json...")); - #ifdef WLED_USE_DYNAMIC_JSON - DynamicJsonDocument doc(JSON_BUFFER_SIZE); - #else if (!requestJSONBufferLock(2)) return; - #endif JsonArray rev = doc.createNestedArray("rev"); rev.add(1); //major settings revision @@ -543,8 +546,9 @@ void serializeConfig() { hw_led[F("ledma")] = strip.milliampsPerLed; hw_led["cct"] = correctWB; hw_led[F("cr")] = cctFromRgb; - hw_led[F("cb")] = strip.cctBlending; - hw_led[F("rgbwm")] = Bus::getAutoWhiteMode(); + hw_led[F("cb")] = strip.cctBlending; + hw_led["fps"] = strip.getTargetFps(); + hw_led[F("rgbwm")] = Bus::getAutoWhiteMode(); JsonArray hw_led_ins = hw_led.createNestedArray("ins"); @@ -746,6 +750,14 @@ void serializeConfig() { timers_ins0["min"] = timerMinutes[i]; timers_ins0["macro"] = timerMacro[i]; timers_ins0[F("dow")] = timerWeekday[i] >> 1; + if (i<8) { + JsonObject start = timers_ins0.createNestedObject("start"); + start["mon"] = (timerMonth[i] >> 4) & 0xF; + start["day"] = timerDay[i]; + JsonObject end = timers_ins0.createNestedObject("end"); + end["mon"] = timerMonth[i] & 0xF; + end["day"] = timerDayEnd[i]; + } } JsonObject ota = doc.createNestedObject("ota"); @@ -782,11 +794,7 @@ void serializeConfig() { bool deserializeConfigSec() { DEBUG_PRINTLN(F("Reading settings from /wsec.json...")); - #ifdef WLED_USE_DYNAMIC_JSON - DynamicJsonDocument doc(JSON_BUFFER_SIZE); - #else if (!requestJSONBufferLock(3)) return false; - #endif bool success = readObjectFromFile("/wsec.json", nullptr, &doc); if (!success) { @@ -831,11 +839,7 @@ bool deserializeConfigSec() { void serializeConfigSec() { DEBUG_PRINTLN(F("Writing settings to /wsec.json...")); - #ifdef WLED_USE_DYNAMIC_JSON - DynamicJsonDocument doc(JSON_BUFFER_SIZE); - #else if (!requestJSONBufferLock(4)) return; - #endif JsonObject nw = doc.createNestedObject("nw"); diff --git a/wled00/const.h b/wled00/const.h index 902521ae5..928913965 100644 --- a/wled00/const.h +++ b/wled00/const.h @@ -64,6 +64,7 @@ #define USERMOD_ID_SEVEN_SEGMENT_DISPLAY 21 //Usermod "usermod_v2_seven_segment_display.h" #define USERMOD_RGB_ROTARY_ENCODER 22 //Usermod "rgb-rotary-encoder.h" #define USERMOD_ID_QUINLED_AN_PENTA 23 //Usermod "quinled-an-penta.h" +#define USERMOD_ID_SSDR 24 //Usermod "usermod_v2_seven_segment_display_reloaded.h" //Access point behavior #define AP_BEHAVIOR_BOOT_NO_CONN 0 //Open AP when no connection after boot @@ -74,7 +75,7 @@ //Notifier callMode #define CALL_MODE_INIT 0 //no updates on init, can be used to disable updates #define CALL_MODE_DIRECT_CHANGE 1 -#define CALL_MODE_BUTTON 2 +#define CALL_MODE_BUTTON 2 //default button actions applied to selected segments #define CALL_MODE_NOTIFICATION 3 #define CALL_MODE_NIGHTLIGHT 4 #define CALL_MODE_NO_NOTIFY 5 @@ -84,6 +85,7 @@ #define CALL_MODE_BLYNK 9 #define CALL_MODE_ALEXA 10 #define CALL_MODE_WS_SEND 11 //special call mode, not for notifier, updates websocket only +#define CALL_MODE_BUTTON_PRESET 12 //button/IR JSON preset/macro //RGB to RGBW conversion mode #define RGBW_MODE_MANUAL_ONLY 0 //No automatic white channel calculation. Manual white channel slider @@ -301,11 +303,7 @@ #define JSON_BUFFER_SIZE 20480 #endif -#ifdef WLED_USE_DYNAMIC_JSON - #define MIN_HEAP_SIZE (JSON_BUFFER_SIZE+512) -#else - #define MIN_HEAP_SIZE (MAX_LED_MEMORY+2048) -#endif +#define MIN_HEAP_SIZE (MAX_LED_MEMORY+2048) // Maximum size of node map (list of other WLED instances) #ifdef ESP8266 diff --git a/wled00/data/index.js b/wled00/data/index.js index 31739255f..d520469fa 100644 --- a/wled00/data/index.js +++ b/wled00/data/index.js @@ -8,11 +8,11 @@ var expanded = [false]; var powered = [true]; var nlDur = 60, nlTar = 0; var nlMode = false; -var selectedFx = 0; +var selectedFx = 0, prevFx = -1; var selectedPal = 0; var sliderControl = ""; //WLEDSR: used by togglePcMode var csel = 0; -var currentPreset = -1; +var currentPreset = -1, prevPS = -1; var lastUpdate = 0; var segCount = 0, ledCount = 0, lowestUnused = 0, maxSeg = 0, lSeg = 0; var pcMode = false, pcModeA = false, lastw = 0; @@ -1048,8 +1048,10 @@ function updateSelectedFx() var selectedEffect = parent.querySelector(`.lstI[data-id="${selectedFx}"]`); if (selectedEffect) { selectedEffect.classList.add('selected'); + var fx = (selectedFx != prevFx) && currentPreset==-1; //effect changed & preset==none + var ps = (prevPS != currentPreset) && currentPreset==-1; // preset changed & preset==none // WLEDSR: extract the Slider and color control string from the HTML element and set it. - setSliderAndColorControl(selectedFx); + setSliderAndColorControl(selectedFx, (fx || ps)); } } @@ -1115,6 +1117,7 @@ function readState(s,command=false) nlTar = s.nl.tbri; nlFade = s.nl.fade; syncSend = s.udpn.send; + prevPS = currentPreset; if (s.pl<0) currentPreset = s.ps; else currentPreset = s.pl; @@ -1178,6 +1181,7 @@ function readState(s,command=false) showToast('Error ' + s.error + ": " + errstr, true); } + prevFx = selectedFx; selectedPal = i.pal; selectedFx = i.fx; redrawPalPrev(); // if any color changed (random palette did at least) @@ -1185,7 +1189,27 @@ function readState(s,command=false) } // WLEDSR: control HTML elements for Slider and Color Control -function setSliderAndColorControl(idx) +// Technical notes +// =============== +// If an effect name is followed by an @, slider and color control is effective. +// If not effective then: +// - For AC effects (id<128) 2 sliders and 3 colors and the palette will be shown +// - For SR effects (id>128) 5 sliders and 3 colors and the palette will be shown +// If effective (@) +// - a ; seperates slider controls (left) from color controls (middle) and palette control (right) +// - if left, middle or right is empty no controls are shown +// - a , seperates slider controls (max 5) or color controls (max 3). Palette has only one value +// - a ! means that the default is used. +// - For sliders: Effect speeds, Effect intensity, Custom 1, Custom 2, Custom 3 +// - For colors: Fx color, Background color, Custom +// - For palette: prompt for color palette OR palette ID if numeric (will hide palette selection) +// +// Note: If palette is on and no colors are specified 1,2 and 3 is shown in each color circle. +// If a color is specified, the 1,2 or 3 is replaced by that specification. +// Note: Effects can override default pattern behaviour +// - FadeToBlack can override the background setting +// - Defining SEGCOL() can override a specific palette using these values (e.g. Color Gradient) +function setSliderAndColorControl(idx, applyDef=false) { if (!(Array.isArray(fxdata) && fxdata.length>idx)) return; var topPosition = 0; @@ -1195,15 +1219,25 @@ function setSliderAndColorControl(idx) var slOnOff = (extras.length==0 || extras[0]=='')?[]:extras[0].split(","); var coOnOff = (extras.length<2 || extras[1]=='')?[]:extras[1].split(","); var paOnOff = (extras.length<3 || extras[2]=='')?[]:extras[2].split(","); + var obj = {"seg":{}}; // set html slider items on/off - var nSliders = Math.floor((gId("Effects").children.length - 1) / 2); // p (label) & div for each slider + FX list + var nSliders = Math.min(5,Math.floor((gId("Effects").children.length - 1) / 2)); // p (label) & div for each slider + FX list for (let i=0; ii && slOnOff[i] != "")) { label.style.display = "block"; + if (slOnOff.length>i && slOnOff[i].indexOf("=")>0) { + //embeded default values + var dPos = slOnOff[i].indexOf("="); + var v = Math.max(0,Math.min(255,parseInt(slOnOff[i].substr(dPos+1)))); + if (i==0) { if (applyDef) gId("sliderSpeed").value = v; obj.seg.sx = v; } + else if (i==1) { if (applyDef) gId("sliderIntensity").value = v; obj.seg.ix = v; } + else { if (applyDef) gId("sliderC"+(i-1)).value = v; obj.seg["C"+(i-1)] = v} + slOnOff[i] = slOnOff[i].substring(0,dPos-1); + } if (slOnOff.length>i && slOnOff[i]!="!") label.innerHTML = slOnOff[i]; else if (i==0) label.innerHTML = "Effect speed"; else if (i==1) label.innerHTML = "Effect intensity"; @@ -1263,20 +1297,9 @@ function setSliderAndColorControl(idx) hide = false; } else { btn.style.display = "none"; + if (i>0 && csel==i) selectSlot(0); } } - selectSlot(0); -/* - // perhaps too aggressive - var ccfg = cfg.comp.colors; - gId("picker").style.display = hide && ccfg.picker ? "none" : "block"; - gId("vwrap").style.display = hide && ccfg.picker ? "none" : "block"; - gId("kwrap").style.display = hide && ccfg.picker && cct ? "none" : "block"; - gId("wwrap").style.display = hide ? "none" : "block"; - gId("wbal").style.display = hide && !cct ? "none" : "block"; - gId("rgbwrap").style.display = hide && ccfg.rgb ? "none" : "block"; - gId("qcs-w").style.display = hide && ccfg.quick ? "none" : "block"; -*/ gId("cslLabel").innerHTML = cslLabel; // set palette on/off @@ -1285,14 +1308,26 @@ function setSliderAndColorControl(idx) // if not controlDefined or palette has a value if ((!controlDefined) || (paOnOff.length>0 && paOnOff[0]!="" && isNaN(paOnOff[0]))) { palw.style.display = "inline-block"; + if (paOnOff.length>0 && paOnOff[0].indexOf("=")>0) { + //embeded default values + var dPos = paOnOff[0].indexOf("="); + var v = Math.max(0,Math.min(255,parseInt(paOnOff[0].substr(dPos+1)))); + var p = d.querySelector(`#pallist input[name="palette"][value="${v}"]`); + if (applyDef && p) { + p.checked = true; + obj.seg.pal = v; + } + paOnOff[0] = paOnOff[0].substring(0,dPos-1); + } if (paOnOff.length>0 && paOnOff[0] != "!") pall.innerHTML = paOnOff[0]; else pall.innerHTML = ' Color palette'; } else { // disable label and slider palw.style.display = "none"; // if numeric set as selected palette - if (paOnOff.length>0 && paOnOff[0]!="" && !isNaN(paOnOff[0]) && parseInt(paOnOff[0])!=selectedPal) setPalette(parseInt(paOnOff[0])); + if (paOnOff.length>0 && paOnOff[0]!="" && !isNaN(paOnOff[0]) && parseInt(paOnOff[0])!=selectedPal) obj.seg.pal = parseInt(paOnOff[0]); } + if (!isEmpty(obj.seg) && applyDef) requestJson(obj); //update default values (may need throttling on ESP8266) } var jsonTimeout; @@ -1308,7 +1343,7 @@ function requestJson(command=null) var useWs = (ws && ws.readyState === WebSocket.OPEN); var type = command ? 'post':'get'; if (command) { - command.v = true; // force complete /json/si API response + if (useWs || !command.ps) command.v = true; // force complete /json/si API response (ps is async so no point) command.time = Math.floor(Date.now() / 1000); var t = gId('tt'); if (t.validity.valid && command.transition==null) { @@ -1322,6 +1357,8 @@ function requestJson(command=null) if (useWs) { ws.send(req?req:'{"v":true}'); return; + } else if (command && command.ps) { //refresh UI if we don't use WS (async loading of presets) + setTimeout(requestJson,200); } fetch(url, { @@ -1698,7 +1735,8 @@ function rptSeg(s) if (stop == 0) {return;} var rev = gId(`seg${s}rev`).checked; var mi = gId(`seg${s}mi`).checked; - var obj = {"seg": {"id": 0, "n": name, "start": start, "stop": (cfg.comp.seglen?start:0)+stop}, "rev": rev, "mi": mi, "on": !powered[s], "bri": parseInt(gId(`seg${s}bri`).value)}; + var sel = gId(`seg${s}sel`).checked; + var obj = {"seg": {"id": 0, "n": name, "start": start, "stop": (cfg.comp.seglen?start:0)+stop, "rev": rev, "mi": mi, "on": !powered[s], "bri": parseInt(gId(`seg${s}bri`).value), "sel": sel}}; if (gId(`seg${s}grp`)) { var grp = parseInt(gId(`seg${s}grp`).value); var spc = parseInt(gId(`seg${s}spc`).value); diff --git a/wled00/data/settings_leds.htm b/wled00/data/settings_leds.htm index 35a13629d..9e4634049 100644 --- a/wled00/data/settings_leds.htm +++ b/wled00/data/settings_leds.htm @@ -353,7 +353,7 @@ ${i+1}: c += ``; c += ``; c += ``; - c += ` ×
`; + c += ` ✕
`; gId("btns").innerHTML = c; } function tglSi(cs) { @@ -515,10 +515,10 @@ ${i+1}: -  ×
- +  ✕
+ IR info
- Relay GPIO: Invert  ×
+ Relay GPIO: Invert  ✕

Defaults

Turn LEDs on after power up/reset:
@@ -563,8 +563,9 @@ ${i+1}:
+ Target refresh rate: FPS
-
Config template:
+
Config template:

diff --git a/wled00/data/settings_time.htm b/wled00/data/settings_time.htm index dfa91fa52..5a54ea81c 100644 --- a/wled00/data/settings_time.htm +++ b/wled00/data/settings_time.htm @@ -7,6 +7,7 @@ Time Settings