Merge branch '0_15' into blending-styles

This commit is contained in:
Blaz Kristan 2024-09-11 17:28:48 +02:00
commit 1cee1c3562
57 changed files with 2739 additions and 387 deletions

View File

@ -1,8 +1,37 @@
## WLED changelog
#### Build 2409100
- WLED 0.15.0-b5 release
- Audioreactive usermod included by default in all compatible builds (including ESP8266)
- Demystified some byte definitions of WiZmote ESP-NOW message (#4114 by @ChuckMash)
- Update usermod "Battery" improved MQTT support (#4110 by @itCarl)
- Added a usermod for interacting with BLE Pixels Dice (#4093 by @axlan)
- Allow lower values for touch threshold (#4081 by @RobinMeis)
- Added POV image effect usermod (#3539 by @Liliputech)
- Remove repeating code to fetch audio data (#4103 by @netmindz)
- Loxone JSON parser doesn't handle lx=0 correctly (#4104 by @FreakyJ, fixes #3809)
- Rename wled00.ino to wled_main.cpp (#4090 by @willmmiles)
- SM16825 chip support including WW & CW channel swap (#4092)
- Add stress testing scripts (#4088 by @willmmiles)
- Improve jsonBufferLock management (#4089 by @willmmiles)
- Fix incorrect PWM bit depth on Esp32 with XTAL clock (#4082 by @PaoloTK)
- Devcontainer args (#4073 by @axlan)
- Effect: Fire2012 optional blur amount (#4078 by @apanteleev)
- Effect: GEQ fix bands (#4077 by @adrianschroeter)
- Boot delay option (#4060 by @DedeHai)
- ESP8266 Audioreactive sync (#3962 by @gaaat98, @netmindz, @softhack007)
- ESP8266 PWM crash fix (#4035 by @willmmiles)
- Usermod: Battery fix (#4051 by @Nickbert7)
- Usermod: Mpu6050 usermod crash fix (#4048 by @willmmiles)
- Usermod: Internal Temperature V2 (#4033 by @adamsthws)
- Various fixes and improvements (including build environments to emulate 0.14.0 for ESP8266)
#### Build 2407070
- Various fixes and improvements (mainly LED settings fix)
#### Build 2406290
- WLED 0.15.0-b4 release
- LED settings bus management update (WARNING only allow available outputs)
- LED settings bus management update (WARNING: only allows available outputs)
- Add ETH support for LILYGO-POE-Pro (#4030 by @rorosaurus)
- Update usermod_sn_photoresistor (#4017 by @xkvmoto)
- Several internal fixes and optimisations

View File

@ -16,6 +16,20 @@ A good description helps us to review and understand your proposed changes. For
Please make all PRs against the `0_15` branch.
### Updating your code
While the PR is open - and under review by maintainers - you may be asked to modify your PR source code.
You can simply update your own branch, and push changes in response to reviewer recommendations.
Github will pick up the changes so your PR stays up-to-date.
> [!CAUTION]
> Do not use "force-push" while your PR is open!
> It has many subtle and unexpected consequences on our github reposistory.
> For example, we regularly lost review comments when the PR author force-pushes code changes. So, pretty please, do not force-push.
You can find a collection of very useful tips and tricks here: https://github.com/Aircoookie/WLED/wiki/How-to-properly-submit-a-PR
### Code style
When in doubt, it is easiest to replicate the code style you find in the files you want to edit :)
@ -37,6 +51,11 @@ if (a == b) {
}
```
```cpp
if (a == b) doStuff(a);
```
Acceptable - however the first variant is usually easier to read:
```cpp
if (a == b)
{
@ -44,9 +63,6 @@ if (a == b)
}
```
```cpp
if (a == b) doStuff(a);
```
There should always be a space between a keyword and its condition and between the condition and brace.
Within the condition, no space should be between the parenthesis and variables.

4
package-lock.json generated
View File

@ -1,12 +1,12 @@
{
"name": "wled",
"version": "0.15.0-b4",
"version": "0.15.0-b5",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "wled",
"version": "0.15.0-b4",
"version": "0.15.0-b5",
"license": "ISC",
"dependencies": {
"clean-css": "^5.3.3",

View File

@ -1,6 +1,6 @@
{
"name": "wled",
"version": "0.15.0-b4",
"version": "0.15.0-b5",
"description": "Tools for WLED project",
"main": "tools/cdata.js",
"directories": {

View File

@ -10,7 +10,7 @@
# ------------------------------------------------------------------------------
# CI/release binaries
default_envs = nodemcuv2, esp8266_2m, esp01_1m_full, nodemcuv2_160, esp8266_2m_160, esp01_1m_full_160, esp32dev, esp32_eth, esp32dev_audioreactive, lolin_s2_mini, esp32c3dev, esp32s3dev_16MB_opi, esp32s3dev_8MB_opi, esp32s3_4M_qspi, esp32_wrover
default_envs = nodemcuv2, esp8266_2m, esp01_1m_full, nodemcuv2_160, esp8266_2m_160, esp01_1m_full_160, nodemcuv2_compat, esp8266_2m_compat, esp01_1m_full_compat, esp32dev, esp32_eth, lolin_s2_mini, esp32c3dev, esp32s3dev_16MB_opi, esp32s3dev_8MB_opi, esp32s3_4M_qspi, esp32_wrover
src_dir = ./wled00
data_dir = ./wled00/data
@ -205,6 +205,38 @@ lib_deps =
ESP8266PWM
${env.lib_deps}
;; compatibilty flags - same as 0.14.0 which seems to work better on some 8266 boards. Not using PIO_FRAMEWORK_ARDUINO_MMU_CACHE16_IRAM48
build_flags_compat =
-DESP8266
-DFP_IN_IROM
;;-Wno-deprecated-declarations
-Wno-misleading-indentation
;;-Wno-attributes ;; silence warnings about unknown attribute 'maybe_unused' in NeoPixelBus
-DPIO_FRAMEWORK_ARDUINO_ESPRESSIF_SDK22x_190703
-DPIO_FRAMEWORK_ARDUINO_LWIP_HIGHER_BANDWIDTH
-DVTABLES_IN_FLASH
-DMIMETYPE_MINIMAL
-DWLED_SAVE_IRAM ;; needed to prevent linker error
;; this platform version was used for WLED 0.14.0
platform_compat = espressif8266@4.2.0
platform_packages_compat =
platformio/toolchain-xtensa @ ~2.100300.220621 #2.40802.200502
platformio/tool-esptool #@ ~1.413.0
platformio/tool-esptoolpy #@ ~1.30000.0
;; experimental - for using older NeoPixelBus 2.7.9
lib_deps_compat =
ESPAsyncTCP @ 1.2.2
ESPAsyncUDP
ESP8266PWM
fastled/FastLED @ 3.6.0
IRremoteESP8266 @ 2.8.2
makuna/NeoPixelBus @ 2.7.9
https://github.com/blazoncek/QuickESPNow.git#optional-debug
https://github.com/Aircoookie/ESPAsyncWebServer.git @ 2.2.1
[esp32]
#platform = https://github.com/tasmota/platform-espressif32/releases/download/v2.0.2.3/platform-espressif32-2.0.2.3.zip
platform = espressif32@3.5.0
@ -315,10 +347,19 @@ build_flags = ${common.build_flags} ${esp8266.build_flags} -D WLED_RELEASE_NAME=
lib_deps = ${esp8266.lib_deps}
monitor_filters = esp8266_exception_decoder
[env:nodemcuv2_compat]
extends = env:nodemcuv2
;; using platform version and build options from WLED 0.14.0
platform = ${esp8266.platform_compat}
platform_packages = ${esp8266.platform_packages_compat}
build_flags = ${common.build_flags} ${esp8266.build_flags_compat} -D WLED_RELEASE_NAME=ESP8266_compat #-DWLED_DISABLE_2D
;; lib_deps = ${esp8266.lib_deps_compat} ;; experimental - use older NeoPixelBus 2.7.9
[env:nodemcuv2_160]
extends = env:nodemcuv2
board_build.f_cpu = 160000000L
build_flags = ${common.build_flags} ${esp8266.build_flags} -D WLED_RELEASE_NAME=ESP8266_160 #-DWLED_DISABLE_2D
-D USERMOD_AUDIOREACTIVE
[env:esp8266_2m]
board = esp_wroom_02
@ -329,10 +370,18 @@ build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags} ${esp8266.build_flags} -D WLED_RELEASE_NAME=ESP02
lib_deps = ${esp8266.lib_deps}
[env:esp8266_2m_compat]
extends = env:esp8266_2m
;; using platform version and build options from WLED 0.14.0
platform = ${esp8266.platform_compat}
platform_packages = ${esp8266.platform_packages_compat}
build_flags = ${common.build_flags} ${esp8266.build_flags_compat} -D WLED_RELEASE_NAME=ESP02_compat #-DWLED_DISABLE_2D
[env:esp8266_2m_160]
extends = env:esp8266_2m
board_build.f_cpu = 160000000L
build_flags = ${common.build_flags} ${esp8266.build_flags} -D WLED_RELEASE_NAME=ESP02_160
-D USERMOD_AUDIOREACTIVE
[env:esp01_1m_full]
board = esp01_1m
@ -344,10 +393,18 @@ build_flags = ${common.build_flags} ${esp8266.build_flags} -D WLED_RELEASE_NAME=
; -D WLED_USE_REAL_MATH ;; may fix wrong sunset/sunrise times, at the cost of 7064 bytes FLASH and 975 bytes RAM
lib_deps = ${esp8266.lib_deps}
[env:esp01_1m_full_compat]
extends = env:esp01_1m_full
;; using platform version and build options from WLED 0.14.0
platform = ${esp8266.platform_compat}
platform_packages = ${esp8266.platform_packages_compat}
build_flags = ${common.build_flags} ${esp8266.build_flags_compat} -D WLED_RELEASE_NAME=ESP01_compat -D WLED_DISABLE_OTA #-DWLED_DISABLE_2D
[env:esp01_1m_full_160]
extends = env:esp01_1m_full
board_build.f_cpu = 160000000L
build_flags = ${common.build_flags} ${esp8266.build_flags} -D WLED_RELEASE_NAME=ESP01_160 -D WLED_DISABLE_OTA
-D USERMOD_AUDIOREACTIVE
; -D WLED_USE_REAL_MATH ;; may fix wrong sunset/sunrise times, at the cost of 7064 bytes FLASH and 975 bytes RAM
[env:esp32dev]
@ -356,7 +413,9 @@ platform = ${esp32.platform}
platform_packages = ${esp32.platform_packages}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags} ${esp32.build_flags} -D WLED_RELEASE_NAME=ESP32 #-D WLED_DISABLE_BROWNOUT_DET
${esp32.AR_build_flags}
lib_deps = ${esp32.lib_deps}
${esp32.AR_lib_deps}
monitor_filters = esp32_exception_decoder
board_build.partitions = ${esp32.default_partitions}
@ -373,19 +432,19 @@ monitor_filters = esp32_exception_decoder
board_build.partitions = ${esp32.large_partitions}
; board_build.f_flash = 80000000L
[env:esp32dev_audioreactive]
board = esp32dev
platform = ${esp32.platform}
platform_packages = ${esp32.platform_packages}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags} ${esp32.build_flags} -D WLED_RELEASE_NAME=ESP32_audioreactive #-D WLED_DISABLE_BROWNOUT_DET
${esp32.AR_build_flags}
lib_deps = ${esp32.lib_deps}
${esp32.AR_lib_deps}
monitor_filters = esp32_exception_decoder
board_build.partitions = ${esp32.default_partitions}
; board_build.f_flash = 80000000L
; board_build.flash_mode = dio
;[env:esp32dev_audioreactive]
;board = esp32dev
;platform = ${esp32.platform}
;platform_packages = ${esp32.platform_packages}
;build_unflags = ${common.build_unflags}
;build_flags = ${common.build_flags} ${esp32.build_flags} -D WLED_RELEASE_NAME=ESP32_audioreactive #-D WLED_DISABLE_BROWNOUT_DET
; ${esp32.AR_build_flags}
;lib_deps = ${esp32.lib_deps}
; ${esp32.AR_lib_deps}
;monitor_filters = esp32_exception_decoder
;board_build.partitions = ${esp32.default_partitions}
;; board_build.f_flash = 80000000L
;; board_build.flash_mode = dio
[env:esp32_eth]
board = esp32-poe
@ -394,8 +453,10 @@ platform_packages = ${esp32.platform_packages}
upload_speed = 921600
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags} ${esp32.build_flags} -D WLED_RELEASE_NAME=ESP32_Ethernet -D RLYPIN=-1 -D WLED_USE_ETHERNET -D BTNPIN=-1
-D WLED_DISABLE_ESPNOW ;; ESP-NOW requires wifi, may crash with ethernet only
; -D WLED_DISABLE_ESPNOW ;; ESP-NOW requires wifi, may crash with ethernet only
${esp32.AR_build_flags}
lib_deps = ${esp32.lib_deps}
${esp32.AR_lib_deps}
board_build.partitions = ${esp32.default_partitions}
[env:esp32_wrover]
@ -405,14 +466,14 @@ platform_packages = ${esp32_idf_V4.platform_packages}
board = ttgo-t7-v14-mini32
board_build.f_flash = 80000000L
board_build.flash_mode = qio
board_build.partitions = ${esp32.default_partitions}
board_build.partitions = ${esp32.extended_partitions}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags} ${esp32_idf_V4.build_flags} -D WLED_RELEASE_NAME=ESP32_WROVER
-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue ;; Older ESP32 (rev.<3) need a PSRAM fix (increases static RAM used) https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-guides/external-ram.html
-D LEDPIN=25
; ${esp32.AR_build_flags}
${esp32.AR_build_flags}
lib_deps = ${esp32_idf_V4.lib_deps}
; ${esp32.AR_lib_deps}
${esp32.AR_lib_deps}
[env:esp32c3dev]
extends = esp32c3

View File

@ -29,6 +29,8 @@ lib_deps = ${esp8266.lib_deps}
; ;gmag11/QuickESPNow @ ~0.7.0 # will also load QuickDebug
; https://github.com/blazoncek/QuickESPNow.git#optional-debug ;; exludes debug library
; ${esp32.AR_lib_deps} ;; used for USERMOD_AUDIOREACTIVE
; bitbank2/PNGdec@^1.0.1 ;; used for POV display uncomment following
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags} ${esp8266.build_flags}
;
@ -152,6 +154,8 @@ build_flags = ${common.build_flags} ${esp8266.build_flags}
; -D TACHO_PIN=33
; -D PWM_PIN=32
;
; Use POV Display usermod
; -D USERMOD_POV_DISPLAY
; Use built-in or custom LED as a status indicator (assumes LED is connected to GPIO16)
; -D STATUSLED=16
;

View File

@ -131,6 +131,11 @@ Specification from: [Molicel INR18650-M35A, 3500mAh 10A Lithium-ion battery, 3.6
## 📝 Change Log
2024-08-19
- Improved MQTT support
- Added battery percentage & battery voltage as MQTT topic
2024-05-11
- Documentation updated

View File

@ -50,6 +50,7 @@ class UsermodBattery : public Usermod
//
bool initDone = false;
bool initializing = true;
bool HomeAssistantDiscovery = false;
// strings to reduce flash memory usage (used more than twice)
static const char _name[];
@ -59,6 +60,7 @@ class UsermodBattery : public Usermod
static const char _preset[];
static const char _duration[];
static const char _init[];
static const char _haDiscovery[];
/**
* Helper for rounding floating point values
@ -69,6 +71,17 @@ class UsermodBattery : public Usermod
return (float)(nx / 100);
}
/**
* Helper for converting a string to lowercase
*/
String stringToLower(String str)
{
for(int i = 0; i < str.length(); i++)
if(str[i] >= 'A' && str[i] <= 'Z')
str[i] += 32;
return str;
}
/**
* Turn off all leds
*/
@ -115,6 +128,55 @@ class UsermodBattery : public Usermod
#endif
}
#ifndef WLED_DISABLE_MQTT
void addMqttSensor(const String &name, const String &type, const String &topic, const String &deviceClass, const String &unitOfMeasurement = "", const bool &isDiagnostic = false)
{
StaticJsonDocument<600> doc;
char uid[128], json_str[1024], buf[128];
doc[F("name")] = name;
doc[F("stat_t")] = topic;
sprintf_P(uid, PSTR("%s_%s_%s"), escapedMac.c_str(), stringToLower(name).c_str(), type);
doc[F("uniq_id")] = uid;
doc[F("dev_cla")] = deviceClass;
doc[F("exp_aft")] = 1800;
if(type == "binary_sensor") {
doc[F("pl_on")] = "on";
doc[F("pl_off")] = "off";
}
if(unitOfMeasurement != "")
doc[F("unit_of_measurement")] = unitOfMeasurement;
if(isDiagnostic)
doc[F("entity_category")] = "diagnostic";
JsonObject device = doc.createNestedObject(F("device")); // attach the sensor to the same device
device[F("name")] = serverDescription;
device[F("ids")] = String(F("wled-sensor-")) + mqttClientID;
device[F("mf")] = F(WLED_BRAND);
device[F("mdl")] = F(WLED_PRODUCT_NAME);
device[F("sw")] = versionString;
sprintf_P(buf, PSTR("homeassistant/%s/%s/%s/config"), type, mqttClientID, uid);
DEBUG_PRINTLN(buf);
size_t payload_size = serializeJson(doc, json_str);
DEBUG_PRINTLN(json_str);
mqtt->publish(buf, 0, true, json_str, payload_size);
}
void publishMqtt(const char* topic, const char* state)
{
if (WLED_MQTT_CONNECTED) {
char buf[128];
snprintf_P(buf, 127, PSTR("%s/%s"), mqttDeviceTopic, topic);
mqtt->publish(buf, 0, false, state);
}
}
#endif
public:
//Functions called by WLED
@ -223,13 +285,8 @@ class UsermodBattery : public Usermod
turnOff();
#ifndef WLED_DISABLE_MQTT
// SmartHome stuff
// still don't know much about MQTT and/or HA
if (WLED_MQTT_CONNECTED) {
char buf[64]; // buffer for snprintf()
snprintf_P(buf, 63, PSTR("%s/voltage"), mqttDeviceTopic);
mqtt->publish(buf, 0, false, String(bat->getVoltage()).c_str());
}
publishMqtt("battery", String(bat->getLevel(), 0).c_str());
publishMqtt("voltage", String(bat->getVoltage()).c_str());
#endif
}
@ -288,6 +345,7 @@ class UsermodBattery : public Usermod
battery[F("calibration")] = bat->getCalibration();
battery[F("voltage-multiplier")] = bat->getVoltageMultiplier();
battery[FPSTR(_readInterval)] = readingInterval;
battery[FPSTR(_haDiscovery)] = HomeAssistantDiscovery;
JsonObject ao = battery.createNestedObject(F("auto-off")); // auto off section
ao[FPSTR(_enabled)] = autoOffEnabled;
@ -307,8 +365,8 @@ class UsermodBattery : public Usermod
getJsonValue(battery[F("max-voltage")], cfg.maxVoltage);
getJsonValue(battery[F("calibration")], cfg.calibration);
getJsonValue(battery[F("voltage-multiplier")], cfg.voltageMultiplier);
setReadingInterval(battery[FPSTR(_readInterval)] | readingInterval);
setHomeAssistantDiscovery(battery[FPSTR(_haDiscovery)] | HomeAssistantDiscovery);
JsonObject ao = battery[F("auto-off")];
setAutoOffEnabled(ao[FPSTR(_enabled)] | autoOffEnabled);
@ -420,17 +478,18 @@ class UsermodBattery : public Usermod
void appendConfigData()
{
// Total: 462 Bytes
oappend(SET_F("td=addDropdown('Battery', 'type');")); // 35 Bytes
oappend(SET_F("addOption(td, 'Unkown', '0');")); // 30 Bytes
oappend(SET_F("addOption(td, 'LiPo', '1');")); // 28 Bytes
oappend(SET_F("addOption(td, 'LiOn', '2');")); // 28 Bytes
oappend(SET_F("td=addDropdown('Battery','type');")); // 34 Bytes
oappend(SET_F("addOption(td,'Unkown','0');")); // 28 Bytes
oappend(SET_F("addOption(td,'LiPo','1');")); // 26 Bytes
oappend(SET_F("addOption(td,'LiOn','2');")); // 26 Bytes
oappend(SET_F("addInfo('Battery:type',1,'<small style=\"color:orange\">requires reboot</small>');")); // 81 Bytes
oappend(SET_F("addInfo('Battery:min-voltage', 1, 'v');")); // 40 Bytes
oappend(SET_F("addInfo('Battery:max-voltage', 1, 'v');")); // 40 Bytes
oappend(SET_F("addInfo('Battery:interval', 1, 'ms');")); // 38 Bytes
oappend(SET_F("addInfo('Battery:auto-off:threshold', 1, '%');")); // 47 Bytes
oappend(SET_F("addInfo('Battery:indicator:threshold', 1, '%');")); // 48 Bytes
oappend(SET_F("addInfo('Battery:indicator:duration', 1, 's');")); // 47 Bytes
oappend(SET_F("addInfo('Battery:min-voltage',1,'v');")); // 38 Bytes
oappend(SET_F("addInfo('Battery:max-voltage',1,'v');")); // 38 Bytes
oappend(SET_F("addInfo('Battery:interval',1,'ms');")); // 36 Bytes
oappend(SET_F("addInfo('Battery:HA-discovery',1,'');")); // 38 Bytes
oappend(SET_F("addInfo('Battery:auto-off:threshold',1,'%');")); // 45 Bytes
oappend(SET_F("addInfo('Battery:indicator:threshold',1,'%');")); // 46 Bytes
oappend(SET_F("addInfo('Battery:indicator:duration',1,'s');")); // 45 Bytes
// this option list would exeed the oappend() buffer
// a list of all presets to select one from
@ -478,12 +537,12 @@ class UsermodBattery : public Usermod
#ifdef ARDUINO_ARCH_ESP32
newBatteryPin = battery[F("pin")] | newBatteryPin;
#endif
// calculateTimeLeftEnabled = battery[F("time-left")] | calculateTimeLeftEnabled;
setMinBatteryVoltage(battery[F("min-voltage")] | bat->getMinVoltage());
setMaxBatteryVoltage(battery[F("max-voltage")] | bat->getMaxVoltage());
setCalibration(battery[F("calibration")] | bat->getCalibration());
setVoltageMultiplier(battery[F("voltage-multiplier")] | bat->getVoltageMultiplier());
setReadingInterval(battery[FPSTR(_readInterval)] | readingInterval);
setHomeAssistantDiscovery(battery[FPSTR(_haDiscovery)] | HomeAssistantDiscovery);
getUsermodConfigFromJsonObject(battery);
@ -513,38 +572,24 @@ class UsermodBattery : public Usermod
return !battery[FPSTR(_readInterval)].isNull();
}
/**
* TBD: Generate a preset sample for low power indication
* a button on the config page would be cool, currently not possible
*/
void generateExamplePreset()
#ifndef WLED_DISABLE_MQTT
void onMqttConnect(bool sessionPresent)
{
// StaticJsonDocument<300> j;
// JsonObject preset = j.createNestedObject();
// preset["mainseg"] = 0;
// JsonArray seg = preset.createNestedArray("seg");
// JsonObject seg0 = seg.createNestedObject();
// seg0["id"] = 0;
// seg0["start"] = 0;
// seg0["stop"] = 60;
// seg0["grp"] = 0;
// seg0["spc"] = 0;
// seg0["on"] = true;
// seg0["bri"] = 255;
// Home Assistant Autodiscovery
if (!HomeAssistantDiscovery)
return;
// JsonArray col0 = seg0.createNestedArray("col");
// JsonArray col00 = col0.createNestedArray();
// col00.add(255);
// col00.add(0);
// col00.add(0);
// battery percentage
char mqttBatteryTopic[128];
snprintf_P(mqttBatteryTopic, 127, PSTR("%s/battery"), mqttDeviceTopic);
this->addMqttSensor(F("Battery"), "sensor", mqttBatteryTopic, "battery", "%", true);
// seg0["fx"] = 1;
// seg0["sx"] = 128;
// seg0["ix"] = 128;
// savePreset(199, "Low power Indicator", preset);
// voltage
char mqttVoltageTopic[128];
snprintf_P(mqttVoltageTopic, 127, PSTR("%s/voltage"), mqttDeviceTopic);
this->addMqttSensor(F("Voltage"), "sensor", mqttVoltageTopic, "voltage", "V", true);
}
#endif
/*
*
@ -785,6 +830,22 @@ class UsermodBattery : public Usermod
{
return lowPowerIndicationDone;
}
/**
* Set Home Assistant auto discovery
*/
void setHomeAssistantDiscovery(bool enable)
{
HomeAssistantDiscovery = enable;
}
/**
* Get Home Assistant auto discovery
*/
bool getHomeAssistantDiscovery()
{
return HomeAssistantDiscovery;
}
};
// strings to reduce flash memory usage (used more than twice)
@ -795,3 +856,4 @@ const char UsermodBattery::_threshold[] PROGMEM = "threshold";
const char UsermodBattery::_preset[] PROGMEM = "preset";
const char UsermodBattery::_duration[] PROGMEM = "duration";
const char UsermodBattery::_init[] PROGMEM = "init";
const char UsermodBattery::_haDiscovery[] PROGMEM = "HA-discovery";

View File

@ -23,6 +23,9 @@
#ifndef TFT_RST
#error Please define TFT_RST
#endif
#ifndef TFT_CS
#error Please define TFT_CS
#endif
#ifndef LOAD_GLCD
#error Please define LOAD_GLCD
#endif
@ -377,7 +380,7 @@ class St7789DisplayUsermod : public Usermod {
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');"));
oappend(SET_F("addInfo('ST7789:pin[]',2,'','SPI BL');"));
oappend(SET_F("addInfo('ST7789:pin[]',3,'','SPI BL');"));
}
/*

View File

@ -7,6 +7,4 @@
extends = env:d1_mini
build_flags = ${common.build_flags_esp8266} -D USERMOD_DALLASTEMPERATURE
lib_deps = ${env.lib_deps}
paulstoffregen/OneWire@~2.3.7
# you may want to use following with ESP32
; https://github.com/blazoncek/OneWire.git # fixes Sensor error on ESP32
paulstoffregen/OneWire@~2.3.8

View File

@ -43,10 +43,8 @@ default_envs = d1_mini
...
lib_deps =
...
#For Dallas sensor uncomment following line
OneWire@~2.3.7
# ... or you may want to use following with ESP32
; https://github.com/blazoncek/OneWire.git # fixes Sensor error on ESP32...
#For Dallas sensor uncomment following
paulstoffregen/OneWire @ ~2.3.8
```
## Change Log
@ -56,8 +54,14 @@ lib_deps =
* Do not report erroneous low temperatures to MQTT
* Disable plugin if temperature sensor not detected
* Report the number of seconds until the first read in the info screen instead of sensor error
2021-04
* Adaptation for runtime configuration.
2023-05
* Rewrite to conform to newer recommendations.
* Recommended @blazoncek fork of OneWire for ESP32 to avoid Sensor error
* Recommended @blazoncek fork of OneWire for ESP32 to avoid Sensor error
2024-09
* Update OneWire to version 2.3.8, which includes stickbreaker's and garyd9's ESP32 fixes:
blazoncek's fork is no longer needed

View File

@ -0,0 +1,254 @@
# A mod for using Pixel Dice with ESP32S3 boards
A usermod to connect to and handle rolls from [Pixels Dice](https://gamewithpixels.com/). WLED acts as both an display controller, and a gateway to connect the die to the Wifi network.
High level features:
* Several LED effects that respond to die rolls
* Effect color and parameters can be modified like any other effect
* Different die can be set to control different segments
* An optional GUI on a TFT screen with custom button controls
* Gives die connection and roll status
* Can do basic LED effect controls
* Can display custom info for different roll types (ie. RPG stats/spell info)
* Publish MQTT events from die rolls
* Also report the selected roll type
* Control settings through the WLED web
See <https://www.robopenguins.com/pixels-dice-box/> for a write up of the design process of the hardware and software I used this with.
I also set up a custom web installer for the usermod at <https://axlan.github.io/WLED-WebInstaller/> for 8MB ESP32-S3 boards.
## Table of Contents
<!-- TOC start (generated with https://github.com/derlin/bitdowntoc) -->
* [Demos](#demos)
+ [TFT GUI](#tft-gui)
+ [Multiple Die Controlling Different Segments](#multiple-die-controlling-different-segments)
* [Hardware](#hardware)
* [Library used](#library-used)
* [Compiling](#compiling)
+ [platformio_override.ini](#platformio_overrideini)
+ [Manual platformio.ini changes](#manual-platformioini-changes)
* [Configuration](#configuration)
+ [Controlling Dice Connections](#controlling-dice-connections)
+ [Controlling Effects](#controlling-effects)
- [DieSimple](#diesimple)
- [DiePulse](#diepulse)
- [DieCheck](#diecheck)
* [TFT GUI](#tft-gui-1)
+ [Status](#status)
+ [Effect Menu](#effect-menu)
+ [Roll Info](#roll-info)
* [MQTT](#mqtt)
* [Potential Modifications and Additional Features](#potential-modifications-and-additional-features)
* [ESP32 Issues](#esp32-issues)
<!-- TOC end -->
<!-- TOC --><a name="demos"></a>
## Demos
<!-- TOC --><a name="tft-gui"></a>
### TFT GUI
[![Watch the video](https://img.youtube.com/vi/VNsHq1TbiW8/0.jpg)](https://youtu.be/VNsHq1TbiW8)
<!-- TOC --><a name="multiple-die-controlling-different-segments"></a>
### Multiple Die Controlling Different Segments
[![Watch the video](https://img.youtube.com/vi/oCDr44C-qwM/0.jpg)](https://youtu.be/oCDr44C-qwM)
<!-- TOC --><a name="hardware"></a>
## Hardware
The main purpose of this mod is to support [Pixels Dice](https://gamewithpixels.com/). The board acts as a BLE central for the dice acting as peripherals. While any ESP32 variant with BLE capabilities should be able to support this usermod, in practice I found that the original ESP32 did not work. See [ESP32 Issues](#esp32-issues) for a deeper dive.
The only other ESP32 variant I tested was the ESP32-S3, which worked without issue. While there's still concern over the contention between BLE and WiFi for the radio, I haven't noticed any performance impact in practice. The only special behavior that was needed was setting `noWifiSleep = false;` to allow the OS to sleep the WiFi when the BLE is active.
In addition, the BLE stack requires a lot of flash. This build takes 1.9MB with the TFT code, or 1.85MB without it. This makes it too big to fit in the `tools/WLED_ESP32_4MB_256KB_FS.csv` partition layout, and I needed to make a `WLED_ESP32_4MB_64KB_FS.csv` to even fit on 4MB devices. This only has 64KB of file system space, which is functional, but users with more than a handful of presets would run into problems with 64KB only. This means that while 4MB can be supported, larger flash sizes are needed for full functionality.
The basic build of this usermod doesn't require any special hardware. However, the LCD status GUI was specifically designed for the [LILYGO T-QT Pro](https://www.lilygo.cc/products/t-qt-pro).
It should be relatively easy to support other displays, though the positioning of the text may need to be adjusted.
<!-- TOC --><a name="library-used"></a>
## Library used
[axlan/pixels-dice-interface](https://github.com/axlan/arduino-pixels-dice)
Optional: [Bodmer/TFT_eSPI](https://github.com/Bodmer/TFT_eSPI)
<!-- TOC --><a name="compiling"></a>
## Compiling
<!-- TOC --><a name="platformio_overrideini"></a>
### platformio_override.ini
Copy and update the example `platformio_override.ini.sample` to the root directory of your particular build (renaming it `platformio_override.ini`).
This file should be placed in the same directory as `platformio.ini`. This file is set up for the [LILYGO T-QT Pro](https://www.lilygo.cc/products/t-qt-pro). Specifically, the 8MB flash version. See the next section for notes on setting the build flags. For other boards, you may want to use a different environment as the basis.
<!-- TOC --><a name="manual-platformioini-changes"></a>
### Manual platformio.ini changes
Using the `platformio_override.ini.sample` as a reference, you'll need to update the `build_flags` and `lib_deps` of the target you're building for.
If you don't need the TFT GUI, you just need to add
```ini
...
build_flags =
...
-D USERMOD_PIXELS_DICE_TRAY ;; Enables this UserMod
lib_deps =
...
ESP32 BLE Arduino
axlan/pixels-dice-interface @ 1.2.0
...
```
For the TFT support you'll need to add `Bodmer/TFT_eSPI` to `lib_deps`, and all of the required TFT parameters to `build_flags` (see `platformio_override.ini.sample`).
Save the `platformio.ini` file, and perform the desired build.
<!-- TOC --><a name="configuration"></a>
## Configuration
In addition to configuring which dice to connect to, this mod uses a lot of the built in WLED features:
* The LED segments, effects, and customization parameters
* The buttons for the UI
* The MQTT settings for reporting the dice rolls
<!-- TOC --><a name="controlling-dice-connections"></a>
### Controlling Dice Connections
**NOTE:** To configure the die itself (set its name, the die LEDs, etc.), you still need to use the Pixels Dice phone App.
The usermods settings page has the configuration for controlling the dice and the display:
* Ble Scan Duration - The time to look for BLE broadcasts before taking a break
* Rotation - If display used, set this parameter to rotate the display.
The main setting here though are the Die 0 and 1 settings. A slot is disabled if it's left blank. Putting the name of a die will make that slot only connect to die with that name. Alteratively, if the name is set to `*` the slot will use the first unassociated die it sees. Saving the configuration while a wildcard slot is connected to a die will replace the `*` with that die's name.
**NOTE:** The slot a die is in is important since that's how they're identified for controlling LED effects. Effects can be set to respond to die 0, 1, or any.
The configuration also includes the pins configured in the TFT build flags. These are just so the UI recognizes that these pins are being used. The [Bodmer/TFT_eSPI](https://github.com/Bodmer/TFT_eSPI) requires that these are set at build time and changing these values is ignored.
<!-- TOC --><a name="controlling-effects"></a>
### Controlling Effects
The die effects for rolls take advantage of most of the normal WLED effect features: <https://kno.wled.ge/features/effects/>.
If you have different segments, they can have different effects driven by the same die, or different dice.
<!-- TOC --><a name="diesimple"></a>
#### DieSimple
Turn off LEDs while rolling, than light up solid LEDs in proportion to die roll.
* Color 1 - Selects the "good" color that increases based on the die roll
* Color 2 - Selects the "background" color for the rest of the segment
* Custom 1 - Sets which die should control this effect. If the value is greater then 1, it will respond to both dice.
<!-- TOC --><a name="diepulse"></a>
#### DiePulse
Play `breath` effect while rolling, than apply `blend` effect in proportion to die roll.
* Color 1 - See `breath` and `blend`
* Color 2 - Selects the "background" color for the rest of the segment
* Palette - See `breath` and `blend`
* Custom 1 - Sets which die should control this effect. If the value is greater then 1, it will respond to both dice.
<!-- TOC --><a name="diecheck"></a>
#### DieCheck
Play `running` effect while rolling, than apply `glitter` effect if roll passes threshold, or `gravcenter` if roll is below.
* Color 1 - See `glitter` and `gravcenter`, used as first color for `running`
* Color 2 - See `glitter` and `gravcenter`
* Color 3 - Used as second color for `running`
* Palette - See `glitter` and `gravcenter`
* Custom 1 - Sets which die should control this effect. If the value is greater then 1, it will respond to both dice.
* Custom 2 - Sets the threshold for success animation. For example if 10, success plays on rolls of 10 or above.
<!-- TOC --><a name="tft-gui-1"></a>
## TFT GUI
The optional TFT GUI currently supports 3 "screens":
1. Status
2. Effect Control
3. Roll Info
Double pressing the right button goes forward through the screens, and double pressing left goes back (with rollover).
<!-- TOC --><a name="status"></a>
### Status
<img src="images/status.webp" alt="Status Menu" width="200"/>
Shows the status of each die slot (0 on top and 1 on the bottom).
If a die is connected, its roll stats and battery status are shown. The rolls will continue to be tracked even when viewing other screens.
Long press either button to clear the roll stats.
<!-- TOC --><a name="effect-menu"></a>
### Effect Menu
<img src="images/effect.webp" alt="Effect Menu" width="200"/>
Allows limited customization of the die effect for the currently selected LED segment.
The left button moves the cursor (blue box) up and down the options for the current field.
The right button updates the value for the field.
The first field is the effect. Updating it will switch between the die effects.
The DieCheck effect has an additional field "PASS". Pressing the right button on this field will copy the current face up value from the most recently rolled die.
Long pressing either value will set the effect parameters (color, palette, controlling dice, etc.) to a default set of values.
<!-- TOC --><a name="roll-info"></a>
### Roll Info
<img src="images/info.webp" alt="Roll Info Menu" width="200"/>
Sets the "roll type" reported by MQTT events and can show additional info.
Pressing the right button goes forward through the rolls, and double pressing left goes back (with rollover).
The names and info for the rolls are generated from the `usermods/pixels_dice_tray/generate_roll_info.py` script. It updates `usermods/pixels_dice_tray/roll_info.h` with code generated from a simple markdown language.
<!-- TOC --><a name="mqtt"></a>
## MQTT
See <https://kno.wled.ge/interfaces/mqtt/> for general MQTT configuration for WLED.
The usermod produces two types of events
* `$mqttDeviceTopic/dice/roll` - JSON that reports each die roll event with the following keys.
- name - The name of the die that triggered the event
- state - Integer indicating the die state `[UNKNOWN = 0, ON_FACE = 1, HANDLING = 2, ROLLING = 3, CROOKED = 4]`
- val - The value on the die's face. For d20 1-20
- time - The uptime timestamp the roll was received in milliseconds.
* `$mqttDeviceTopic/dice/roll_label` - A string that indicates the roll type selected in the [Roll Info](#roll-info) TFT menu.
Where `$mqttDeviceTopic` is the topic set in the WLED MQTT configuration.
Events can be logged to a CSV file using the script `usermods/pixels_dice_tray/mqtt_client/mqtt_logger.py`. These can then be used to generate interactive HTML plots with `usermods/pixels_dice_tray/mqtt_client/mqtt_plotter.py`.
<img src="images/roll_plot.png" alt="Roll Plot"/>
<!-- TOC --><a name="potential-modifications-and-additional-features"></a>
## Potential Modifications and Additional Features
This usermod is in support of a particular dice box project, but it would be fairly straightforward to extend for other applications.
* Add more dice - There's no reason that several more dice slots couldn't be allowed. In addition LED effects that use multiple dice could be added (e.g. a contested roll).
* Better support for die other then d20's. There's a few places where I assume the die is a d20. It wouldn't be that hard to support arbitrary die sizes.
* TFT Menu - The menu system is pretty extensible. I put together some basic things I found useful, and was mainly limited by the screen size.
* Die controlled UI - I originally planned to make an alternative UI that used the die directly. You'd press a button, and the current face up on the die would trigger an action. This was an interesting idea, but didn't seem to practical since I could more flexibly reproduce this by responding to the dice MQTT events.
<!-- TOC --><a name="esp32-issues"></a>
## ESP32 Issues
I really wanted to have this work on the original ESP32 boards to lower the barrier to entry, but there were several issues.
First there are the issues with the partition sizes for 4MB mentioned in the [Hardware](#hardware) section.
The bigger issue is that the build consistently crashes if the BLE scan task starts up. It's a bit unclear to me exactly what is failing since the backtrace is showing an exception in `new[]` memory allocation in the UDP stack. There appears to be a ton of heap available, so my guess is that this is a synchronization issue of some sort from the tasks running in parallel. I tried messing with the task core affinity a bit but didn't make much progress. It's not really clear what difference between the ESP32S3 and ESP32 would cause this difference.
At the end of the day, its generally not advised to run the BLE and Wifi at the same time anyway (though it appears to work without issue on the ESP32S3). Probably the best path forward would be to switch between them. This would actually not be too much of an issue, since discovering and getting data from the die should be possible to do in bursts (at least in theory).

View File

@ -0,0 +1,6 @@
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, 0x9000, 0x5000,
otadata, data, ota, 0xe000, 0x2000,
app0, app, ota_0, 0x10000, 0x1F0000,
app1, app, ota_1, 0x200000,0x1F0000,
spiffs, data, spiffs, 0x3F0000,0x10000,
1 # Name Type SubType Offset Size Flags
2 nvs data nvs 0x9000 0x5000
3 otadata data ota 0xe000 0x2000
4 app0 app ota_0 0x10000 0x1F0000
5 app1 app ota_1 0x200000 0x1F0000
6 spiffs data spiffs 0x3F0000 0x10000

View File

@ -0,0 +1,76 @@
/**
* Structs for passing around usermod state
*/
#pragma once
#include <pixels_dice_interface.h> // https://github.com/axlan/arduino-pixels-dice
/**
* Here's how the rolls are tracked in this usermod.
* 1. The arduino-pixels-dice library reports rolls and state mapped to
* PixelsDieID.
* 2. The "configured_die_names" sets which die to connect to and their order.
* 3. The rest of the usermod references the die by this order (ie. the LED
* effect is triggered for rolls for die 0).
*/
static constexpr size_t MAX_NUM_DICE = 2;
static constexpr uint8_t INVALID_ROLL_VALUE = 0xFF;
/**
* The state of the connected die, and new events since the last update.
*/
struct DiceUpdate {
// The vectors to hold results queried from the library
// Since vectors allocate data, it's more efficient to keep reusing an instance
// instead of declaring them on the stack.
std::vector<pixels::PixelsDieID> dice_list;
pixels::RollUpdates roll_updates;
pixels::BatteryUpdates battery_updates;
// The PixelsDieID for each dice index. 0 if the die isn't connected.
// The ordering here matches configured_die_names.
std::array<pixels::PixelsDieID, MAX_NUM_DICE> connected_die_ids{0, 0};
};
struct DiceSettings {
// The mapping of dice names, to the index of die used for effects (ie. The
// die named "Cat" is die 0). BLE discovery will stop when all the dice are
// found. The die slot is disabled if the name is empty. If the name is "*",
// the slot will use the first unassociated die it sees.
std::array<std::string, MAX_NUM_DICE> configured_die_names{"*", "*"};
// A label set to describe the next die roll. Index into GetRollName().
uint8_t roll_label = INVALID_ROLL_VALUE;
};
// These are updated in the main loop, but accessed by the effect functions as
// well. My understand is that both of these accesses should be running on the
// same "thread/task" since WLED doesn't directly create additional threads. The
// exception would be network callbacks and interrupts, but I don't believe
// these accesses are triggered by those. If synchronization was needed, I could
// look at the example in `requestJSONBufferLock()`.
std::array<pixels::RollEvent, MAX_NUM_DICE> last_die_events;
static pixels::RollEvent GetLastRoll() {
pixels::RollEvent last_roll;
for (const auto& event : last_die_events) {
if (event.timestamp > last_roll.timestamp) {
last_roll = event;
}
}
return last_roll;
}
/**
* Returns true if the container has an item that matches the value.
*/
template <typename C, typename T>
static bool Contains(const C& container, T value) {
return std::find(container.begin(), container.end(), value) !=
container.end();
}
// These aren't known until runtime since they're being added dynamically.
static uint8_t FX_MODE_SIMPLE_D20 = 0xFF;
static uint8_t FX_MODE_PULSE_D20 = 0xFF;
static uint8_t FX_MODE_CHECK_D20 = 0xFF;
std::array<uint8_t, 3> DIE_LED_MODES = {0xFF, 0xFF, 0xFF};

View File

@ -0,0 +1,230 @@
'''
File for generating roll labels and info text for the InfoMenu.
Uses a very limited markdown language for styling text.
'''
import math
from pathlib import Path
import re
from textwrap import indent
# Variables for calculating values in info text
CASTER_LEVEL = 9
SPELL_ABILITY_MOD = 6
BASE_ATK_BONUS = 6
SIZE_BONUS = 1
STR_BONUS = 2
DEX_BONUS = -1
# TFT library color values
TFT_BLACK =0x0000
TFT_NAVY =0x000F
TFT_DARKGREEN =0x03E0
TFT_DARKCYAN =0x03EF
TFT_MAROON =0x7800
TFT_PURPLE =0x780F
TFT_OLIVE =0x7BE0
TFT_LIGHTGREY =0xD69A
TFT_DARKGREY =0x7BEF
TFT_BLUE =0x001F
TFT_GREEN =0x07E0
TFT_CYAN =0x07FF
TFT_RED =0xF800
TFT_MAGENTA =0xF81F
TFT_YELLOW =0xFFE0
TFT_WHITE =0xFFFF
TFT_ORANGE =0xFDA0
TFT_GREENYELLOW =0xB7E0
TFT_PINK =0xFE19
TFT_BROWN =0x9A60
TFT_GOLD =0xFEA0
TFT_SILVER =0xC618
TFT_SKYBLUE =0x867D
TFT_VIOLET =0x915C
class Size:
def __init__(self, w, h):
self.w = w
self.h = h
# Font 1 6x8
# Font 2 12x16
CHAR_SIZE = {
1: Size(6, 8),
2: Size(12, 16),
}
SCREEN_SIZE = Size(128, 128)
# Calculates distance for short range spell.
def short_range() -> int:
return 25 + 5 * CASTER_LEVEL
# Entries in markdown language.
# Parameter 0 of the tuple is the roll name
# Parameter 1 of the tuple is the roll info.
# The text will be shown when the roll type is selected. An error will be raised
# if the text would unexpectedly goes past the end of the screen. There are a
# few styling parameters that need to be on their own lines:
# $COLOR - The color for the text
# $SIZE - Sets the text size (see CHAR_SIZE)
# $WRAP - By default text won't wrap and generate an error. This enables text wrapping. Lines will wrap mid-word.
ENTRIES = [
tuple(["Barb Chain", f'''\
$COLOR({TFT_RED})
Barb Chain
$COLOR({TFT_WHITE})
Atk/CMD {BASE_ATK_BONUS + SPELL_ABILITY_MOD}
Range: {short_range()}
$WRAP(1)
$SIZE(1)
Summon {1 + math.floor((CASTER_LEVEL-1)/3)} chains. Make a melee atk 1d6 or a trip CMD=AT. On a hit make Will save or shaken 1d4 rnds.
''']),
tuple(["Saves", f'''\
$COLOR({TFT_GREEN})
Saves
$COLOR({TFT_WHITE})
FORT 8
REFLEX 8
WILL 9
''']),
tuple(["Skill", f'''\
Skill
''']),
tuple(["Attack", f'''\
Attack
Melee +{BASE_ATK_BONUS + SIZE_BONUS + STR_BONUS}
Range +{BASE_ATK_BONUS + SIZE_BONUS + DEX_BONUS}
''']),
tuple(["Cure", f'''\
Cure
Lit 1d8+{min(5, CASTER_LEVEL)}
Mod 2d8+{min(10, CASTER_LEVEL)}
Ser 3d8+{min(15, CASTER_LEVEL)}
''']),
tuple(["Concentrate", f'''\
Concentrat
+{CASTER_LEVEL + SPELL_ABILITY_MOD}
$SIZE(1)
Defensive 15+2*SP_LV
Dmg 10+DMG+SP_LV
Grapple 10+CMB+SP_LV
''']),
]
RE_SIZE = re.compile(r'\$SIZE\(([0-9])\)')
RE_COLOR = re.compile(r'\$COLOR\(([0-9]+)\)')
RE_WRAP = re.compile(r'\$WRAP\(([0-9])\)')
END_HEADER_TXT = '// GENERATED\n'
def main():
roll_info_file = Path(__file__).parent / 'roll_info.h'
old_contents = open(roll_info_file, 'r').read()
end_header = old_contents.index(END_HEADER_TXT)
with open(roll_info_file, 'w') as fd:
fd.write(old_contents[:end_header+len(END_HEADER_TXT)])
for key, entry in enumerate(ENTRIES):
size = 2
wrap = False
y_loc = 0
results = []
for line in entry[1].splitlines():
if line.startswith('$'):
m_size = RE_SIZE.match(line)
m_color = RE_COLOR.match(line)
m_wrap = RE_WRAP.match(line)
if m_size:
size = int(m_size.group(1))
results.append(f'tft.setTextSize({size});')
elif m_color:
results.append(
f'tft.setTextColor({int(m_color.group(1))});')
elif m_wrap:
wrap = bool(int(m_wrap.group(1)))
else:
print(f'Entry {key} unknown modifier "{line}".')
exit(1)
else:
max_chars_per_line = math.floor(
SCREEN_SIZE.w / CHAR_SIZE[size].w)
if len(line) > max_chars_per_line:
if wrap:
while len(line) > max_chars_per_line:
results.append(
f'tft.println("{line[:max_chars_per_line]}");')
line = line[max_chars_per_line:].lstrip()
y_loc += CHAR_SIZE[size].h
else:
print(f'Entry {key} line "{line}" too long.')
exit(1)
if len(line) > 0:
y_loc += CHAR_SIZE[size].h
results.append(f'tft.println("{line}");')
if y_loc > SCREEN_SIZE.h:
print(
f'Entry {key} line "{line}" went past bottom of screen.')
exit(1)
result = indent('\n'.join(results), ' ')
fd.write(f'''\
static void PrintRoll{key}() {{
{result}
}}
''')
results = []
for key, entry in enumerate(ENTRIES):
results.append(f'''\
case {key}:
return "{entry[0]}";''')
cases = indent('\n'.join(results), ' ')
fd.write(f'''\
static const char* GetRollName(uint8_t key) {{
switch (key) {{
{cases}
}}
return "";
}}
''')
results = []
for key, entry in enumerate(ENTRIES):
results.append(f'''\
case {key}:
PrintRoll{key}();
return;''')
cases = indent('\n'.join(results), ' ')
fd.write(f'''\
static void PrintRollInfo(uint8_t key) {{
tft.setTextColor(TFT_WHITE);
tft.setCursor(0, 0);
tft.setTextSize(2);
switch (key) {{
{cases}
}}
tft.setTextColor(TFT_RED);
tft.setCursor(0, 60);
tft.println("Unknown");
}}
''')
fd.write(f'static constexpr size_t NUM_ROLL_INFOS = {len(ENTRIES)};\n')
main()

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

View File

@ -0,0 +1,124 @@
/**
* The LED effects influenced by dice rolls.
*/
#pragma once
#include "wled.h"
#include "dice_state.h"
// Reuse FX display functions.
extern uint16_t mode_breath();
extern uint16_t mode_blends();
extern uint16_t mode_glitter();
extern uint16_t mode_gravcenter();
static constexpr uint8_t USER_ANY_DIE = 0xFF;
/**
* Two custom effect parameters are used.
* c1 - Source Die. Sets which die from [0 - MAX_NUM_DICE) controls this effect.
* If this is set to 0xFF, use the latest event regardless of which die it
* came from.
* c2 - Target Roll. Sets the "success" criteria for a roll to >= this value.
*/
/**
* Return the last die roll based on the custom1 effect setting.
*/
static pixels::RollEvent GetLastRollForSegment() {
// If an invalid die is selected, fallback to using the most recent roll from
// any die.
if (SEGMENT.custom1 >= MAX_NUM_DICE) {
return GetLastRoll();
} else {
return last_die_events[SEGMENT.custom1];
}
}
/*
* Alternating pixels running function (copied static function).
*/
// paletteBlend: 0 - wrap when moving, 1 - always wrap, 2 - never wrap, 3 - none (undefined)
#define PALETTE_SOLID_WRAP (strip.paletteBlend == 1 || strip.paletteBlend == 3)
static uint16_t running_copy(uint32_t color1, uint32_t color2, bool theatre = false) {
int width = (theatre ? 3 : 1) + (SEGMENT.intensity >> 4); // window
uint32_t cycleTime = 50 + (255 - SEGMENT.speed);
uint32_t it = strip.now / cycleTime;
bool usePalette = color1 == SEGCOLOR(0);
for (int i = 0; i < SEGLEN; i++) {
uint32_t col = color2;
if (usePalette) color1 = SEGMENT.color_from_palette(i, true, PALETTE_SOLID_WRAP, 0);
if (theatre) {
if ((i % width) == SEGENV.aux0) col = color1;
} else {
int pos = (i % (width<<1));
if ((pos < SEGENV.aux0-width) || ((pos >= SEGENV.aux0) && (pos < SEGENV.aux0+width))) col = color1;
}
SEGMENT.setPixelColor(i,col);
}
if (it != SEGENV.step) {
SEGENV.aux0 = (SEGENV.aux0 +1) % (theatre ? width : (width<<1));
SEGENV.step = it;
}
return FRAMETIME;
}
static uint16_t simple_roll() {
auto roll = GetLastRollForSegment();
if (roll.state != pixels::RollState::ON_FACE) {
SEGMENT.fill(0);
} else {
uint16_t num_segments = float(roll.current_face + 1) / 20.0 * SEGLEN;
for (int i = 0; i <= num_segments; i++) {
SEGMENT.setPixelColor(i, SEGCOLOR(0));
}
for (int i = num_segments; i < SEGLEN; i++) {
SEGMENT.setPixelColor(i, SEGCOLOR(1));
}
}
return FRAMETIME;
}
// See https://kno.wled.ge/interfaces/json-api/#effect-metadata
// Name - DieSimple
// Parameters -
// * Selected Die (custom1)
// Colors - Uses color1 and color2
// Palette - Not used
// Flags - Effect is optimized for use on 1D LED strips.
// Defaults - Selected Die set to 0xFF (USER_ANY_DIE)
static const char _data_FX_MODE_SIMPLE_DIE[] PROGMEM =
"DieSimple@,,Selected Die;!,!;;1;c1=255";
static uint16_t pulse_roll() {
auto roll = GetLastRollForSegment();
if (roll.state != pixels::RollState::ON_FACE) {
return mode_breath();
} else {
uint16_t ret = mode_blends();
uint16_t num_segments = float(roll.current_face + 1) / 20.0 * SEGLEN;
for (int i = num_segments; i < SEGLEN; i++) {
SEGMENT.setPixelColor(i, SEGCOLOR(1));
}
return ret;
}
}
static const char _data_FX_MODE_PULSE_DIE[] PROGMEM =
"DiePulse@!,!,Selected Die;!,!;!;1;sx=24,pal=50,c1=255";
static uint16_t check_roll() {
auto roll = GetLastRollForSegment();
if (roll.state != pixels::RollState::ON_FACE) {
return running_copy(SEGCOLOR(0), SEGCOLOR(2));
} else {
if (roll.current_face + 1 >= SEGMENT.custom2) {
return mode_glitter();
} else {
return mode_gravcenter();
}
}
}
static const char _data_FX_MODE_CHECK_DIE[] PROGMEM =
"DieCheck@!,!,Selected Die,Target Roll;1,2,3;!;1;pal=0,ix=128,m12=2,si=0,c1=255,c2=10";

View File

@ -0,0 +1,104 @@
#!/usr/bin/env python
import argparse
import json
import os
from pathlib import Path
import time
# Dependency installed with `pip install paho-mqtt`.
# https://pypi.org/project/paho-mqtt/
import paho.mqtt.client as mqtt
state = {"label": "None"}
# Define MQTT callbacks
def on_connect(client, userdata, connect_flags, reason_code, properties):
print("Connected with result code " + str(reason_code))
state["start_time"] = None
client.subscribe(f"{state['root_topic']}#")
def on_message(client, userdata, msg):
if msg.topic.endswith("roll_label"):
state["label"] = msg.payload.decode("ascii")
print(f"Label set to {state['label']}")
elif msg.topic.endswith("roll"):
json_str = msg.payload.decode("ascii")
msg_data = json.loads(json_str)
# Convert the relative timestamps reported to the dice to an approximate absolute time.
# The "last_time" check is to detect if the ESP32 was restarted or the counter rolled over.
if state["start_time"] is None or msg_data["time"] < state["last_time"]:
state["start_time"] = time.time() - (msg_data["time"] / 1000.0)
state["last_time"] = msg_data["time"]
timestamp = state["start_time"] + (msg_data["time"] / 1000.0)
state["csv_fd"].write(
f"{timestamp:.3f}, {msg_data['name']}, {state['label']}, {msg_data['state']}, {msg_data['val']}\n"
)
state["csv_fd"].flush()
if msg_data["state"] == 1:
print(
f"{timestamp:.3f}: {msg_data['name']} rolled {msg_data['val']}")
def main():
parser = argparse.ArgumentParser(
description="Log die rolls from WLED MQTT events to CSV.")
# IP address (with a default value)
parser.add_argument(
"--host",
type=str,
default="127.0.0.1",
help="Host address of broker (default: 127.0.0.1)",
)
parser.add_argument(
"--port", type=int, default=1883, help="Broker TCP port (default: 1883)"
)
parser.add_argument("--user", type=str, help="Optional MQTT username")
parser.add_argument("--password", type=str, help="Optional MQTT password")
parser.add_argument(
"--topic",
type=str,
help="Optional MQTT topic to listen to. For example if topic is 'wled/e5a658/dice/', subscript to to 'wled/e5a658/dice/#'. By default, listen to all topics looking for ones that end in 'roll_label' and 'roll'.",
)
parser.add_argument(
"-o",
"--output-dir",
type=Path,
default=Path(__file__).absolute().parent / "logs",
help="Directory to log to",
)
args = parser.parse_args()
timestr = time.strftime("%Y-%m-%d")
os.makedirs(args.output_dir, exist_ok=True)
state["csv_fd"] = open(args.output_dir / f"roll_log_{timestr}.csv", "a")
# Create `an MQTT client
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
# Set MQTT callbacks
client.on_connect = on_connect
client.on_message = on_message
if args.user and args.password:
client.username_pw_set(args.user, args.password)
state["root_topic"] = ""
# Connect to the MQTT broker
client.connect(args.host, args.port, 60)
try:
while client.loop(timeout=1.0) == mqtt.MQTT_ERR_SUCCESS:
time.sleep(0.1)
except KeyboardInterrupt:
exit(0)
print("Connection Failure")
exit(1)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,69 @@
import argparse
from http import server
import os
from pathlib import Path
import socketserver
import pandas as pd
import plotly.express as px
# python -m http.server 8000 --directory /tmp/
def main():
parser = argparse.ArgumentParser(
description="Generate an html plot of rolls captured by mqtt_logger.py")
parser.add_argument("input_file", type=Path, help="Log file to plot")
parser.add_argument(
"-s",
"--start-server",
action="store_true",
help="After generating the plot, run a webserver pointing to it",
)
parser.add_argument(
"-o",
"--output-dir",
type=Path,
default=Path(__file__).absolute().parent / "logs",
help="Directory to log to",
)
args = parser.parse_args()
df = pd.read_csv(
args.input_file, names=["timestamp", "die", "label", "state", "roll"]
)
df_filt = df[df["state"] == 1]
time = (df_filt["timestamp"] - df_filt["timestamp"].min()) / 60 / 60
fig = px.bar(
df_filt,
x=time,
y="roll",
color="label",
labels={
"x": "Game Time (min)",
},
title=f"Roll Report: {args.input_file.name}",
)
output_path = args.output_dir / (args.input_file.stem + ".html")
fig.write_html(output_path)
if args.start_server:
PORT = 8000
os.chdir(args.output_dir)
try:
with socketserver.TCPServer(
("", PORT), server.SimpleHTTPRequestHandler
) as httpd:
print(
f"Serving HTTP on http://0.0.0.0:{PORT}/{output_path.name}")
httpd.serve_forever()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()

View File

@ -0,0 +1,2 @@
plotly-express
paho-mqtt

View File

@ -0,0 +1,535 @@
#pragma once
#include <pixels_dice_interface.h> // https://github.com/axlan/arduino-pixels-dice
#include "wled.h"
#include "dice_state.h"
#include "led_effects.h"
#include "tft_menu.h"
// Set this parameter to rotate the display. 1-3 rotate by 90,180,270 degrees.
#ifndef USERMOD_PIXELS_DICE_TRAY_ROTATION
#define USERMOD_PIXELS_DICE_TRAY_ROTATION 0
#endif
// How often we are redrawing screen
#ifndef USERMOD_PIXELS_DICE_TRAY_REFRESH_RATE_MS
#define USERMOD_PIXELS_DICE_TRAY_REFRESH_RATE_MS 200
#endif
// Time with no updates before screen turns off (-1 to disable)
#ifndef USERMOD_PIXELS_DICE_TRAY_TIMEOUT_MS
#define USERMOD_PIXELS_DICE_TRAY_TIMEOUT_MS 5 * 60 * 1000
#endif
// Duration of each search for BLE devices.
#ifndef BLE_SCAN_DURATION_SEC
#define BLE_SCAN_DURATION_SEC 4
#endif
// Time between searches for BLE devices.
#ifndef BLE_TIME_BETWEEN_SCANS_SEC
#define BLE_TIME_BETWEEN_SCANS_SEC 5
#endif
#define WLED_DEBOUNCE_THRESHOLD \
50 // only consider button input of at least 50ms as valid (debouncing)
#define WLED_LONG_PRESS \
600 // long press if button is released after held for at least 600ms
#define WLED_DOUBLE_PRESS \
350 // double press if another press within 350ms after a short press
class PixelsDiceTrayUsermod : public Usermod {
private:
bool enabled = true;
DiceUpdate dice_update;
// Settings
uint32_t ble_scan_duration_sec = BLE_SCAN_DURATION_SEC;
unsigned rotation = USERMOD_PIXELS_DICE_TRAY_ROTATION;
DiceSettings dice_settings;
#if USING_TFT_DISPLAY
MenuController menu_ctrl;
#endif
static void center(String& line, uint8_t width) {
int len = line.length();
if (len < width)
for (byte i = (width - len) / 2; i > 0; i--)
line = ' ' + line;
for (byte i = line.length(); i < width; i++)
line += ' ';
}
// NOTE: THIS MOD DOES NOT SUPPORT CHANGING THE SPI PINS FROM THE UI! The
// TFT_eSPI library requires that they are compiled in.
static void SetSPIPinsFromMacros() {
#if USING_TFT_DISPLAY
spi_mosi = TFT_MOSI;
// Done in TFT library.
if (TFT_MISO == TFT_MOSI) {
spi_miso = -1;
}
spi_sclk = TFT_SCLK;
#endif
}
void UpdateDieNames(
const std::array<const std::string, MAX_NUM_DICE>& new_die_names) {
for (size_t i = 0; i < MAX_NUM_DICE; i++) {
// If the saved setting was a wildcard, and that connected to a die, use
// the new name instead of the wildcard. Saving this "locks" the name in.
bool overriden_wildcard =
new_die_names[i] == "*" && dice_update.connected_die_ids[i] != 0;
if (!overriden_wildcard &&
new_die_names[i] != dice_settings.configured_die_names[i]) {
dice_settings.configured_die_names[i] = new_die_names[i];
dice_update.connected_die_ids[i] = 0;
last_die_events[i] = pixels::RollEvent();
}
}
}
public:
PixelsDiceTrayUsermod()
#if USING_TFT_DISPLAY
: menu_ctrl(&dice_settings)
#endif
{
}
// 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() override {
DEBUG_PRINTLN(F("DiceTray: init"));
#if USING_TFT_DISPLAY
SetSPIPinsFromMacros();
PinManagerPinType spiPins[] = {
{spi_mosi, true}, {spi_miso, false}, {spi_sclk, true}};
if (!pinManager.allocateMultiplePins(spiPins, 3, PinOwner::HW_SPI)) {
enabled = false;
} else {
PinManagerPinType displayPins[] = {
{TFT_CS, true}, {TFT_DC, true}, {TFT_RST, true}, {TFT_BL, true}};
if (!pinManager.allocateMultiplePins(
displayPins, sizeof(displayPins) / sizeof(PinManagerPinType),
PinOwner::UM_FourLineDisplay)) {
pinManager.deallocateMultiplePins(spiPins, 3, PinOwner::HW_SPI);
enabled = false;
}
}
if (!enabled) {
DEBUG_PRINTLN(F("DiceTray: TFT Display pin allocations failed."));
return;
}
#endif
// Need to enable WiFi sleep:
// "E (1513) wifi:Error! Should enable WiFi modem sleep when both WiFi and Bluetooth are enabled!!!!!!"
noWifiSleep = false;
// Get the mode indexes that the effects are registered to.
FX_MODE_SIMPLE_D20 = strip.addEffect(255, &simple_roll, _data_FX_MODE_SIMPLE_DIE);
FX_MODE_PULSE_D20 = strip.addEffect(255, &pulse_roll, _data_FX_MODE_PULSE_DIE);
FX_MODE_CHECK_D20 = strip.addEffect(255, &check_roll, _data_FX_MODE_CHECK_DIE);
DIE_LED_MODES = {FX_MODE_SIMPLE_D20, FX_MODE_PULSE_D20, FX_MODE_CHECK_D20};
// Start a background task scanning for dice.
// On completion the discovered dice are connected to.
pixels::ScanForDice(ble_scan_duration_sec, BLE_TIME_BETWEEN_SCANS_SEC);
#if USING_TFT_DISPLAY
menu_ctrl.Init(rotation);
#endif
}
/*
* connected() is called every time the WiFi is (re)connected
* Use it to initialize network interfaces
*/
void connected() override {
// Serial.println("Connected to WiFi!");
}
/*
* loop() is called continuously. Here you can check for events, read sensors,
* etc.
*
* Tips:
* 1. You can use "if (WLED_CONNECTED)" to check for a successful network
* connection. Additionally, "if (WLED_MQTT_CONNECTED)" is available to check
* for a connection to an MQTT broker.
*
* 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() override {
static long last_loop_time = 0;
static long last_die_connected_time = millis();
char mqtt_topic_buffer[MQTT_MAX_TOPIC_LEN + 16];
char mqtt_data_buffer[128];
// Check if we time interval for redrawing passes.
if (millis() - last_loop_time < USERMOD_PIXELS_DICE_TRAY_REFRESH_RATE_MS) {
return;
}
last_loop_time = millis();
// Update dice_list with the connected dice
pixels::ListDice(dice_update.dice_list);
// Get all the roll/battery updates since the last loop
pixels::GetDieRollUpdates(dice_update.roll_updates);
pixels::GetDieBatteryUpdates(dice_update.battery_updates);
// Go through list of connected die.
// TODO: Blacklist die that are connected to, but don't match the configured
// names.
std::array<bool, MAX_NUM_DICE> die_connected = {false, false};
for (auto die_id : dice_update.dice_list) {
bool matched = false;
// First check if we've already matched this ID to a connected die.
for (size_t i = 0; i < MAX_NUM_DICE; i++) {
if (die_id == dice_update.connected_die_ids[i]) {
die_connected[i] = true;
matched = true;
break;
}
}
// If this isn't already matched, check if its name matches an expected name.
if (!matched) {
auto die_name = pixels::GetDieDescription(die_id).name;
for (size_t i = 0; i < MAX_NUM_DICE; i++) {
if (0 == dice_update.connected_die_ids[i] &&
die_name == dice_settings.configured_die_names[i]) {
dice_update.connected_die_ids[i] = die_id;
die_connected[i] = true;
matched = true;
DEBUG_PRINTF_P(PSTR("DiceTray: %u (%s) connected.\n"), i,
die_name.c_str());
break;
}
}
// If it doesn't match any expected names, check if there's any wildcards to match.
if (!matched) {
auto description = pixels::GetDieDescription(die_id);
for (size_t i = 0; i < MAX_NUM_DICE; i++) {
if (dice_settings.configured_die_names[i] == "*") {
dice_update.connected_die_ids[i] = die_id;
die_connected[i] = true;
dice_settings.configured_die_names[i] = die_name;
DEBUG_PRINTF_P(PSTR("DiceTray: %u (%s) connected as wildcard.\n"),
i, die_name.c_str());
break;
}
}
}
}
}
// Clear connected die that aren't still present.
bool all_found = true;
bool none_found = true;
for (size_t i = 0; i < MAX_NUM_DICE; i++) {
if (!die_connected[i]) {
if (dice_update.connected_die_ids[i] != 0) {
dice_update.connected_die_ids[i] = 0;
last_die_events[i] = pixels::RollEvent();
DEBUG_PRINTF_P(PSTR("DiceTray: %u disconnected.\n"), i);
}
if (!dice_settings.configured_die_names[i].empty()) {
all_found = false;
}
} else {
none_found = false;
}
}
// Update last_die_events
for (const auto& roll : dice_update.roll_updates) {
for (size_t i = 0; i < MAX_NUM_DICE; i++) {
if (dice_update.connected_die_ids[i] == roll.first) {
last_die_events[i] = roll.second;
}
}
if (WLED_MQTT_CONNECTED) {
snprintf(mqtt_topic_buffer, sizeof(mqtt_topic_buffer), PSTR("%s/%s"),
mqttDeviceTopic, "dice/roll");
const char* name = pixels::GetDieDescription(roll.first).name.c_str();
snprintf(mqtt_data_buffer, sizeof(mqtt_data_buffer),
"{\"name\":\"%s\",\"state\":%d,\"val\":%d,\"time\":%d}", name,
int(roll.second.state), roll.second.current_face + 1,
roll.second.timestamp);
mqtt->publish(mqtt_topic_buffer, 0, false, mqtt_data_buffer);
}
}
#if USERMOD_PIXELS_DICE_TRAY_TIMEOUT_MS > 0 && USING_TFT_DISPLAY
// If at least one die is configured, but none are found
if (none_found) {
if (millis() - last_die_connected_time >
USERMOD_PIXELS_DICE_TRAY_TIMEOUT_MS) {
// Turn off LEDs and backlight and go to sleep.
// Since none of the wake up pins are wired up, expect to sleep
// until power cycle or reset, so don't need to handle normal
// wakeup.
bri = 0;
applyFinalBri();
menu_ctrl.EnableBacklight(false);
gpio_hold_en((gpio_num_t)TFT_BL);
gpio_deep_sleep_hold_en();
esp_deep_sleep_start();
}
} else {
last_die_connected_time = millis();
}
#endif
if (pixels::IsScanning() && all_found) {
DEBUG_PRINTF_P(PSTR("DiceTray: All dice found. Stopping search.\n"));
pixels::StopScanning();
} else if (!pixels::IsScanning() && !all_found) {
DEBUG_PRINTF_P(PSTR("DiceTray: Resuming dice search.\n"));
pixels::ScanForDice(ble_scan_duration_sec, BLE_TIME_BETWEEN_SCANS_SEC);
}
#if USING_TFT_DISPLAY
menu_ctrl.Update(dice_update);
#endif
}
/*
* 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) override {
JsonObject user = root["u"];
if (user.isNull())
user = root.createNestedObject("u");
JsonArray lightArr = user.createNestedArray("DiceTray"); // name
lightArr.add(enabled ? F("installed") : F("disabled")); // unit
}
/*
* 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) override {
// 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) 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!"));
}
/*
* 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) If you want to
* force saving the current state, use serializeConfig() in your loop().
*
* CAUTION: serializeConfig() will initiate a filesystem write operation.
* It might cause the LEDs to stutter and will cause flash wear if called too
* often. Use it sparingly and always in the loop, never in network callbacks!
*
* addToConfig() will also not yet add your setting to one of the settings
* pages automatically. To make that work you still have to add the setting to
* the HTML, xml.cpp and set.cpp manually.
*
* I highly recommend checking out the basics of ArduinoJson serialization and
* deserialization in order to use custom settings!
*/
void addToConfig(JsonObject& root) override {
JsonObject top = root.createNestedObject("DiceTray");
top["ble_scan_duration"] = ble_scan_duration_sec;
top["die_0"] = dice_settings.configured_die_names[0];
top["die_1"] = dice_settings.configured_die_names[1];
#if USING_TFT_DISPLAY
top["rotation"] = rotation;
JsonArray pins = top.createNestedArray("pin");
pins.add(TFT_CS);
pins.add(TFT_DC);
pins.add(TFT_RST);
pins.add(TFT_BL);
#endif
}
void appendConfigData() override {
// Slightly annoying that you can't put text before an element.
// The an item on the usermod config page has the following HTML:
// ```html
// Die 0
// <input type="hidden" name="DiceTray:die_0" value="text">
// <input type="text" name="DiceTray:die_0" value="*" style="width:250px;" oninput="check(this,'DiceTray')">
// ```
// addInfo let's you add data before or after the two input fields.
//
// To work around this, add info text to the end of the preceding item.
//
// See addInfo in wled00/data/settings_um.htm for details on what this function does.
oappend(SET_F(
"addInfo('DiceTray:ble_scan_duration',1,'<br><br><i>Set to \"*\" to "
"connect to any die.<br>Leave Blank to disable.</i><br><i "
"class=\"warn\">Saving will replace \"*\" with die names.</i>','');"));
#if USING_TFT_DISPLAY
oappend(SET_F("ddr=addDropdown('DiceTray','rotation');"));
oappend(SET_F("addOption(ddr,'0 deg',0);"));
oappend(SET_F("addOption(ddr,'90 deg',1);"));
oappend(SET_F("addOption(ddr,'180 deg',2);"));
oappend(SET_F("addOption(ddr,'270 deg',3);"));
oappend(SET_F(
"addInfo('DiceTray:rotation',1,'<br><i class=\"warn\">DO NOT CHANGE "
"SPI PINS.</i><br><i class=\"warn\">CHANGES ARE IGNORED.</i>','');"));
oappend(SET_F("addInfo('TFT:pin[]',0,'','SPI CS');"));
oappend(SET_F("addInfo('TFT:pin[]',1,'','SPI DC');"));
oappend(SET_F("addInfo('TFT:pin[]',2,'','SPI RST');"));
oappend(SET_F("addInfo('TFT:pin[]',3,'','SPI BL');"));
#endif
}
/*
* 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 once immediately after boot)
*
* 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 :)
*/
bool readFromConfig(JsonObject& root) override {
// we look for JSON object:
// {"DiceTray":{"rotation":0,"font_size":1}}
JsonObject top = root["DiceTray"];
if (top.isNull()) {
DEBUG_PRINTLN(F("DiceTray: No config found. (Using defaults.)"));
return false;
}
if (top.containsKey("die_0") && top.containsKey("die_1")) {
const std::array<const std::string, MAX_NUM_DICE> new_die_names{
top["die_0"], top["die_1"]};
UpdateDieNames(new_die_names);
} else {
DEBUG_PRINTLN(F("DiceTray: No die names found."));
}
#if USING_TFT_DISPLAY
unsigned new_rotation = min(top["rotation"] | rotation, 3u);
// Restore the SPI pins to their compiled in defaults.
SetSPIPinsFromMacros();
if (new_rotation != rotation) {
rotation = new_rotation;
menu_ctrl.Init(rotation);
}
// Update with any modified settings.
menu_ctrl.Redraw();
#endif
// use "return !top["newestParameter"].isNull();" when updating Usermod with
// new features
return !top["DiceTray"].isNull();
}
/**
* handleButton() can be used to override default button behaviour. Returning true
* will prevent button working in a default way.
* Replicating button.cpp
*/
#if USING_TFT_DISPLAY
bool handleButton(uint8_t b) override {
if (!enabled || b > 1 // buttons 0,1 only
|| buttonType[b] == BTN_TYPE_SWITCH || buttonType[b] == BTN_TYPE_NONE ||
buttonType[b] == BTN_TYPE_RESERVED ||
buttonType[b] == BTN_TYPE_PIR_SENSOR ||
buttonType[b] == BTN_TYPE_ANALOG ||
buttonType[b] == BTN_TYPE_ANALOG_INVERTED) {
return false;
}
unsigned long now = millis();
static bool buttonPressedBefore[2] = {false};
static bool buttonLongPressed[2] = {false};
static unsigned long buttonPressedTime[2] = {0};
static unsigned long buttonWaitTime[2] = {0};
//momentary button logic
if (!buttonLongPressed[b] && isButtonPressed(b)) { //pressed
if (!buttonPressedBefore[b]) {
buttonPressedTime[b] = now;
}
buttonPressedBefore[b] = true;
if (now - buttonPressedTime[b] > WLED_LONG_PRESS) { //long press
menu_ctrl.HandleButton(ButtonType::LONG, b);
buttonLongPressed[b] = true;
return true;
}
} else if (!isButtonPressed(b) && buttonPressedBefore[b]) { //released
long dur = now - buttonPressedTime[b];
if (dur < WLED_DEBOUNCE_THRESHOLD) {
buttonPressedBefore[b] = false;
return true;
} //too short "press", debounce
bool doublePress = buttonWaitTime[b]; //did we have short press before?
buttonWaitTime[b] = 0;
if (!buttonLongPressed[b]) { //short press
// if this is second release within 350ms it is a double press (buttonWaitTime!=0)
if (doublePress) {
menu_ctrl.HandleButton(ButtonType::DOUBLE, b);
} else {
buttonWaitTime[b] = now;
}
}
buttonPressedBefore[b] = false;
buttonLongPressed[b] = false;
}
// if 350ms elapsed since last press/release it is a short press
if (buttonWaitTime[b] && now - buttonWaitTime[b] > WLED_DOUBLE_PRESS &&
!buttonPressedBefore[b]) {
buttonWaitTime[b] = 0;
menu_ctrl.HandleButton(ButtonType::SINGLE, b);
}
return true;
}
#endif
/*
* 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_PIXELS_DICE_TRAY; }
// More methods can be added in the future, this example will then be
// extended. Your usermod will remain compatible as it does not need to
// implement all methods from the Usermod base class!
};

View File

@ -0,0 +1,115 @@
[platformio]
default_envs = t_qt_pro_8MB_dice, esp32s3dev_8MB_qspi_dice
# ------------------------------------------------------------------------------
# T-QT Pro 8MB with integrated 128x128 TFT screen
# ------------------------------------------------------------------------------
[env:t_qt_pro_8MB_dice]
board = esp32-s3-devkitc-1 ;; generic dev board;
platform = ${esp32s3.platform}
upload_speed = 921600
build_unflags = ${common.build_unflags}
board_build.partitions = ${esp32.large_partitions}
board_build.f_flash = 80000000L
board_build.flash_mode = qio
monitor_filters = esp32_exception_decoder
build_flags = ${common.build_flags} ${esp32s3.build_flags} -D WLED_RELEASE_NAME=T-QT-PRO-8MB
-D CONFIG_LITTLEFS_FOR_IDF_3_2 -D WLED_WATCHDOG_TIMEOUT=0
-D ARDUINO_USB_CDC_ON_BOOT=1 -D ARDUINO_USB_MODE=1 ;; for boards with USB-OTG connector only (USBCDC or "TinyUSB")
-D USERMOD_PIXELS_DICE_TRAY ;; Enables this UserMod
-D USERMOD_PIXELS_DICE_TRAY_BL_ACTIVE_LOW=1
-D USERMOD_PIXELS_DICE_TRAY_ROTATION=2
;-D WLED_DEBUG
;;;;;;;;;;;;;;;;;; TFT_eSPI Settings ;;;;;;;;;;;;;;;;;;;;;;;;
;-DCORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_DEBUG
-D USER_SETUP_LOADED=1
; Define the TFT driver, pins etc. from: https://github.com/Bodmer/TFT_eSPI/blob/master/User_Setups/Setup211_LilyGo_T_QT_Pro_S3.h
; GC9A01 128 x 128 display with no chip select line
-D USER_SETUP_ID=211
-D GC9A01_DRIVER=1
-D TFT_WIDTH=128
-D TFT_HEIGHT=128
-D TFT_BACKLIGHT_ON=0
-D TFT_ROTATION=3
-D CGRAM_OFFSET=1
-D TFT_MISO=-1
-D TFT_MOSI=2
-D TFT_SCLK=3
-D TFT_CS=5
-D TFT_DC=6
-D TFT_RST=1
-D TFT_BL=10
-D LOAD_GLCD=1
-D LOAD_FONT2=1
-D LOAD_FONT4=1
-D LOAD_FONT6=1
-D LOAD_FONT7=1
-D LOAD_FONT8=1
-D LOAD_GFXFF=1
; Avoid SPIFFS dependancy that was causing compile issues.
;-D SMOOTH_FONT=1
-D SPI_FREQUENCY=40000000
-D SPI_READ_FREQUENCY=20000000
-D SPI_TOUCH_FREQUENCY=2500000
lib_deps = ${esp32s3.lib_deps}
${esp32.AR_lib_deps}
ESP32 BLE Arduino
bodmer/TFT_eSPI @ 2.5.43
axlan/pixels-dice-interface @ 1.2.0
# ------------------------------------------------------------------------------
# ESP32S3 dev board with 8MB flash and no extended RAM.
# ------------------------------------------------------------------------------
[env:esp32s3dev_8MB_qspi_dice]
board = esp32-s3-devkitc-1 ;; generic dev board;
platform = ${esp32s3.platform}
upload_speed = 921600
build_unflags = ${common.build_unflags}
board_build.partitions = ${esp32.large_partitions}
board_build.f_flash = 80000000L
board_build.flash_mode = qio
monitor_filters = esp32_exception_decoder
build_flags = ${common.build_flags} ${esp32s3.build_flags} -D WLED_RELEASE_NAME=ESP32-S3_8MB_qspi
-D CONFIG_LITTLEFS_FOR_IDF_3_2 -D WLED_WATCHDOG_TIMEOUT=0
-D ARDUINO_USB_CDC_ON_BOOT=1 -D ARDUINO_USB_MODE=1 ;; for boards with USB-OTG connector only (USBCDC or "TinyUSB")
-D USERMOD_PIXELS_DICE_TRAY ;; Enables this UserMod
;-D WLED_DEBUG
lib_deps = ${esp32s3.lib_deps}
${esp32.AR_lib_deps}
ESP32 BLE Arduino
axlan/pixels-dice-interface @ 1.2.0
# ------------------------------------------------------------------------------
# ESP32 dev board without screen
# ------------------------------------------------------------------------------
# THIS DOES NOT WORK!!!!!!
# While it builds and programs onto the device, I ran into a series of issues
# trying to actually run.
# Right after the AP init there's an allocation exception which claims to be in
# the UDP server. There seems to be a ton of heap remaining, so the exact error
# might be a red herring.
# It appears that the BLE scanning task is conflicting with the networking tasks.
# I was successfully running simple applications with the pixels-dice-interface
# on ESP32 dev boards, so it may be an issue with too much being scheduled in
# parallel. Also not clear exactly what difference between the ESP32 and the
# ESP32S3 would be causing this, though they do run different BLE versions.
# May be related to some of the issues discussed in:
# https://github.com/Aircoookie/WLED/issues/1382
; [env:esp32dev_dice]
; extends = env:esp32dev
; build_flags = ${common.build_flags} ${esp32.build_flags} -D WLED_RELEASE_NAME=ESP32
; ; Enable Pixels dice mod
; -D USERMOD_PIXELS_DICE_TRAY
; lib_deps = ${esp32.lib_deps}
; ESP32 BLE Arduino
; axlan/pixels-dice-interface @ 1.2.0
; ; Tiny file system partition, no core dump to fit BLE library.
; board_build.partitions = usermods/pixels_dice_tray/WLED_ESP32_4MB_64KB_FS.csv

View File

@ -0,0 +1,107 @@
#pragma once
#include <TFT_eSPI.h>
extern TFT_eSPI tft;
// The following functions are generated by:
// usermods/pixels_dice_tray/generate_roll_info.py
// GENERATED
static void PrintRoll0() {
tft.setTextColor(63488);
tft.println("Barb Chain");
tft.setTextColor(65535);
tft.println("Atk/CMD 12");
tft.println("Range: 70");
tft.setTextSize(1);
tft.println("Summon 3 chains. Make");
tft.println("a melee atk 1d6 or a ");
tft.println("trip CMD=AT. On a hit");
tft.println("make Will save or sha");
tft.println("ken 1d4 rnds.");
}
static void PrintRoll1() {
tft.setTextColor(2016);
tft.println("Saves");
tft.setTextColor(65535);
tft.println("FORT 8");
tft.println("REFLEX 8");
tft.println("WILL 9");
}
static void PrintRoll2() {
tft.println("Skill");
}
static void PrintRoll3() {
tft.println("Attack");
tft.println("Melee +9");
tft.println("Range +6");
}
static void PrintRoll4() {
tft.println("Cure");
tft.println("Lit 1d8+5");
tft.println("Mod 2d8+9");
tft.println("Ser 3d8+9");
}
static void PrintRoll5() {
tft.println("Concentrat");
tft.println("+15");
tft.setTextSize(1);
tft.println("Defensive 15+2*SP_LV");
tft.println("Dmg 10+DMG+SP_LV");
tft.println("Grapple 10+CMB+SP_LV");
}
static const char* GetRollName(uint8_t key) {
switch (key) {
case 0:
return "Barb Chain";
case 1:
return "Saves";
case 2:
return "Skill";
case 3:
return "Attack";
case 4:
return "Cure";
case 5:
return "Concentrate";
}
return "";
}
static void PrintRollInfo(uint8_t key) {
tft.setTextColor(TFT_WHITE);
tft.setCursor(0, 0);
tft.setTextSize(2);
switch (key) {
case 0:
PrintRoll0();
return;
case 1:
PrintRoll1();
return;
case 2:
PrintRoll2();
return;
case 3:
PrintRoll3();
return;
case 4:
PrintRoll4();
return;
case 5:
PrintRoll5();
return;
}
tft.setTextColor(TFT_RED);
tft.setCursor(0, 60);
tft.println("Unknown");
}
static constexpr size_t NUM_ROLL_INFOS = 6;

View File

@ -0,0 +1,479 @@
/**
* Code for using the 128x128 LCD and two buttons on the T-QT Pro as a GUI.
*/
#pragma once
#ifndef TFT_WIDTH
#warning TFT parameters not specified, not using screen.
#else
#include <TFT_eSPI.h>
#include <pixels_dice_interface.h> // https://github.com/axlan/arduino-pixels-dice
#include "wled.h"
#include "dice_state.h"
#include "roll_info.h"
#define USING_TFT_DISPLAY 1
#ifndef TFT_BL
#define TFT_BL -1
#endif
// Bitmask for icon
const uint8_t LIGHTNING_ICON_8X8[] PROGMEM = {
0b00001111, 0b00010010, 0b00100100, 0b01001111,
0b10000001, 0b11110010, 0b00010100, 0b00011000,
};
TFT_eSPI tft = TFT_eSPI(TFT_WIDTH, TFT_HEIGHT);
/**
* Print text with box surrounding it.
*
* @param txt Text to draw
* @param color Color for box lines
*/
static void PrintLnInBox(const char* txt, uint32_t color) {
int16_t sx = tft.getCursorX();
int16_t sy = tft.getCursorY();
tft.setCursor(sx + 2, sy);
tft.print(txt);
int16_t w = tft.getCursorX() - sx + 1;
tft.println();
int16_t h = tft.getCursorY() - sy - 1;
tft.drawRect(sx, sy, w, h, color);
}
/**
* Override the current colors for the selected segment to the defaults for the
* selected die effect.
*/
void SetDefaultColors(uint8_t mode) {
Segment& seg = strip.getFirstSelectedSeg();
if (mode == FX_MODE_SIMPLE_D20) {
seg.setColor(0, GREEN);
seg.setColor(1, 0);
} else if (mode == FX_MODE_PULSE_D20) {
seg.setColor(0, GREEN);
seg.setColor(1, RED);
} else if (mode == FX_MODE_CHECK_D20) {
seg.setColor(0, RED);
seg.setColor(1, 0);
seg.setColor(2, GREEN);
}
}
/**
* Get the pointer to the custom2 value for the current LED segment. This is
* used to set the target roll for relevant effects.
*/
static uint8_t* GetCurrentRollTarget() {
return &strip.getFirstSelectedSeg().custom2;
}
/**
* Class for drawing a histogram of roll results.
*/
class RollCountWidget {
private:
int16_t xs = 0;
int16_t ys = 0;
uint16_t border_color = TFT_RED;
uint16_t bar_color = TFT_GREEN;
uint16_t bar_width = 6;
uint16_t max_bar_height = 60;
unsigned roll_counts[20] = {0};
unsigned total = 0;
unsigned max_count = 0;
public:
RollCountWidget(int16_t xs = 0, int16_t ys = 0,
uint16_t border_color = TFT_RED,
uint16_t bar_color = TFT_GREEN, uint16_t bar_width = 6,
uint16_t max_bar_height = 60)
: xs(xs),
ys(ys),
border_color(border_color),
bar_color(bar_color),
bar_width(bar_width),
max_bar_height(max_bar_height) {}
void Clear() {
memset(roll_counts, 0, sizeof(roll_counts));
total = 0;
max_count = 0;
}
unsigned GetNumRolls() const { return total; }
void AddRoll(unsigned val) {
if (val > 19) {
return;
}
roll_counts[val]++;
total++;
max_count = max(roll_counts[val], max_count);
}
void Draw() {
// Add 2 pixels to lengths for boarder width.
tft.drawRect(xs, ys, bar_width * 20 + 2, max_bar_height + 2, border_color);
for (size_t i = 0; i < 20; i++) {
if (roll_counts[i] > 0) {
// Scale bar by highest count.
uint16_t bar_height = round(float(roll_counts[i]) / float(max_count) *
float(max_bar_height));
// Add space between bars
uint16_t padding = (bar_width > 1) ? 1 : 0;
// Need to start from top of bar and draw down
tft.fillRect(xs + 1 + bar_width * i,
ys + 1 + max_bar_height - bar_height, bar_width - padding,
bar_height, bar_color);
}
}
}
};
enum class ButtonType { SINGLE, DOUBLE, LONG };
// Base class for different menu pages.
class MenuBase {
public:
/**
* Handle new die events and connections. Called even when menu isn't visible.
*/
virtual void Update(const DiceUpdate& dice_update) = 0;
/**
* Draw menu to the screen.
*/
virtual void Draw(const DiceUpdate& dice_update, bool force_redraw) = 0;
/**
* Handle button presses if the menu is currently active.
*/
virtual void HandleButton(ButtonType type, uint8_t b) = 0;
protected:
static DiceSettings* settings;
friend class MenuController;
};
DiceSettings* MenuBase::settings = nullptr;
/**
* Menu to show connection status and roll histograms.
*/
class DiceStatusMenu : public MenuBase {
public:
DiceStatusMenu()
: die_roll_counts{RollCountWidget{0, 20, TFT_BLUE, TFT_GREEN, 6, 40},
RollCountWidget{0, SECTION_HEIGHT + 20, TFT_BLUE,
TFT_GREEN, 6, 40}} {}
void Update(const DiceUpdate& dice_update) override {
for (size_t i = 0; i < MAX_NUM_DICE; i++) {
const auto die_id = dice_update.connected_die_ids[i];
const auto connected = die_id != 0;
// Redraw if connection status changed.
die_updated[i] |= die_id != last_die_ids[i];
last_die_ids[i] = die_id;
if (connected) {
bool charging = false;
for (const auto& battery : dice_update.battery_updates) {
if (battery.first == die_id) {
if (die_battery[i].battery_level == INVALID_BATTERY ||
battery.second.is_charging != die_battery[i].is_charging) {
die_updated[i] = true;
}
die_battery[i] = battery.second;
}
}
for (const auto& roll : dice_update.roll_updates) {
if (roll.first == die_id &&
roll.second.state == pixels::RollState::ON_FACE) {
die_roll_counts[i].AddRoll(roll.second.current_face);
die_updated[i] = true;
}
}
}
}
}
void Draw(const DiceUpdate& dice_update, bool force_redraw) override {
// This could probably be optimized for partial redraws.
for (size_t i = 0; i < MAX_NUM_DICE; i++) {
const int16_t ys = SECTION_HEIGHT * i;
const auto die_id = dice_update.connected_die_ids[i];
const auto connected = die_id != 0;
// Screen updates might be slow, yield in case network task needs to do
// work.
yield();
bool battery_update =
connected && (millis() - last_update[i] > BATTERY_REFRESH_RATE_MS);
if (force_redraw || die_updated[i] || battery_update) {
last_update[i] = millis();
tft.fillRect(0, ys, TFT_WIDTH, SECTION_HEIGHT, TFT_BLACK);
tft.drawRect(0, ys, TFT_WIDTH, SECTION_HEIGHT, TFT_BLUE);
if (settings->configured_die_names[i].empty()) {
tft.setTextColor(TFT_RED);
tft.setCursor(2, ys + 4);
tft.setTextSize(2);
tft.println("Connection");
tft.setCursor(2, tft.getCursorY());
tft.println("Disabled");
} else if (!connected) {
tft.setTextColor(TFT_RED);
tft.setCursor(2, ys + 4);
tft.setTextSize(2);
tft.println(settings->configured_die_names[i].c_str());
tft.setCursor(2, tft.getCursorY());
tft.print("Waiting...");
} else {
tft.setTextColor(TFT_WHITE);
tft.setCursor(0, ys + 2);
tft.setTextSize(1);
tft.println(settings->configured_die_names[i].c_str());
tft.print("Cnt ");
tft.print(die_roll_counts[i].GetNumRolls());
if (die_battery[i].battery_level != INVALID_BATTERY) {
tft.print(" Bat ");
tft.print(die_battery[i].battery_level);
tft.print("%");
if (die_battery[i].is_charging) {
tft.drawBitmap(tft.getCursorX(), tft.getCursorY(),
LIGHTNING_ICON_8X8, 8, 8, TFT_YELLOW);
}
}
die_roll_counts[i].Draw();
}
die_updated[i] = false;
}
}
}
void HandleButton(ButtonType type, uint8_t b) override {
if (type == ButtonType::LONG) {
for (size_t i = 0; i < MAX_NUM_DICE; i++) {
die_roll_counts[i].Clear();
die_updated[i] = true;
}
}
};
private:
static constexpr long BATTERY_REFRESH_RATE_MS = 60 * 1000;
static constexpr int16_t SECTION_HEIGHT = TFT_HEIGHT / MAX_NUM_DICE;
static constexpr uint8_t INVALID_BATTERY = 0xFF;
std::array<long, MAX_NUM_DICE> last_update{0, 0};
std::array<pixels::PixelsDieID, MAX_NUM_DICE> last_die_ids{0, 0};
std::array<bool, MAX_NUM_DICE> die_updated{false, false};
std::array<pixels::BatteryEvent, MAX_NUM_DICE> die_battery = {
pixels::BatteryEvent{INVALID_BATTERY, false},
pixels::BatteryEvent{INVALID_BATTERY, false}};
std::array<RollCountWidget, MAX_NUM_DICE> die_roll_counts;
};
/**
* Some limited controls for setting the die effects on the current LED
* segment.
*/
class EffectMenu : public MenuBase {
public:
EffectMenu() = default;
void Update(const DiceUpdate& dice_update) override {}
void Draw(const DiceUpdate& dice_update, bool force_redraw) override {
// NOTE: This doesn't update automatically if the effect is updated on the
// web UI and vice-versa.
if (force_redraw) {
tft.fillScreen(TFT_BLACK);
uint8_t mode = strip.getFirstSelectedSeg().mode;
if (Contains(DIE_LED_MODES, mode)) {
char lineBuffer[CHAR_WIDTH_BIG + 1];
extractModeName(mode, JSON_mode_names, lineBuffer, CHAR_WIDTH_BIG);
tft.setTextColor(TFT_WHITE);
tft.setCursor(0, 0);
tft.setTextSize(2);
PrintLnInBox(lineBuffer, (field_idx == 0) ? TFT_BLUE : TFT_BLACK);
if (mode == FX_MODE_CHECK_D20) {
snprintf(lineBuffer, sizeof(lineBuffer), "PASS: %u",
*GetCurrentRollTarget());
PrintLnInBox(lineBuffer, (field_idx == 1) ? TFT_BLUE : TFT_BLACK);
}
} else {
char lineBuffer[CHAR_WIDTH_SMALL + 1];
extractModeName(mode, JSON_mode_names, lineBuffer, CHAR_WIDTH_SMALL);
tft.setTextColor(TFT_WHITE);
tft.setCursor(0, 0);
tft.setTextSize(1);
tft.println(lineBuffer);
}
}
}
/**
* Button 0 navigates up and down the settings for the effect.
* Button 1 changes the value for the selected settings.
* Long pressing a button resets the effect parameters to their defaults for
* the current die effect.
*/
void HandleButton(ButtonType type, uint8_t b) override {
Segment& seg = strip.getFirstSelectedSeg();
auto mode_itr =
std::find(DIE_LED_MODES.begin(), DIE_LED_MODES.end(), seg.mode);
if (mode_itr != DIE_LED_MODES.end()) {
mode_idx = mode_itr - DIE_LED_MODES.begin();
}
if (mode_itr == DIE_LED_MODES.end()) {
seg.setMode(DIE_LED_MODES[mode_idx]);
} else {
if (type == ButtonType::LONG) {
// Need to set mode to different value so defaults are actually loaded.
seg.setMode(0);
seg.setMode(DIE_LED_MODES[mode_idx], true);
SetDefaultColors(DIE_LED_MODES[mode_idx]);
} else if (b == 0) {
field_idx = (field_idx + 1) % DIE_LED_MODE_NUM_FIELDS[mode_idx];
} else {
if (field_idx == 0) {
mode_idx = (mode_idx + 1) % DIE_LED_MODES.size();
seg.setMode(DIE_LED_MODES[mode_idx]);
} else if (DIE_LED_MODES[mode_idx] == FX_MODE_CHECK_D20 &&
field_idx == 1) {
*GetCurrentRollTarget() = GetLastRoll().current_face + 1;
}
}
}
};
private:
static constexpr std::array<uint8_t, 3> DIE_LED_MODE_NUM_FIELDS = {1, 1, 2};
static constexpr size_t CHAR_WIDTH_BIG = 10;
static constexpr size_t CHAR_WIDTH_SMALL = 21;
size_t mode_idx = 0;
size_t field_idx = 0;
};
constexpr std::array<uint8_t, 3> EffectMenu::DIE_LED_MODE_NUM_FIELDS;
/**
* Menu for setting the roll label and some info for that roll type.
*/
class InfoMenu : public MenuBase {
public:
InfoMenu() = default;
void Update(const DiceUpdate& dice_update) override {}
void Draw(const DiceUpdate& dice_update, bool force_redraw) override {
if (force_redraw) {
tft.fillScreen(TFT_BLACK);
if (settings->roll_label != INVALID_ROLL_VALUE) {
PrintRollInfo(settings->roll_label);
} else {
tft.setTextColor(TFT_RED);
tft.setCursor(0, 60);
tft.setTextSize(2);
tft.println("Set Roll");
}
}
}
/**
* Single clicking navigates through the roll types. Button 0 goes down, and
* button 1 goes up with wrapping.
*/
void HandleButton(ButtonType type, uint8_t b) override {
if (settings->roll_label >= NUM_ROLL_INFOS) {
settings->roll_label = 0;
} else if (b == 0) {
settings->roll_label = (settings->roll_label == 0)
? NUM_ROLL_INFOS - 1
: settings->roll_label - 1;
} else if (b == 1) {
settings->roll_label = (settings->roll_label + 1) % NUM_ROLL_INFOS;
}
if (WLED_MQTT_CONNECTED) {
char mqtt_topic_buffer[MQTT_MAX_TOPIC_LEN + 16];
snprintf(mqtt_topic_buffer, sizeof(mqtt_topic_buffer), PSTR("%s/%s"),
mqttDeviceTopic, "dice/settings->roll_label");
mqtt->publish(mqtt_topic_buffer, 0, false,
GetRollName(settings->roll_label));
}
};
};
/**
* Interface for the rest of the app to update the menus.
*/
class MenuController {
public:
MenuController(DiceSettings* settings) { MenuBase::settings = settings; }
void Init(unsigned rotation) {
tft.init();
tft.setRotation(rotation);
tft.fillScreen(TFT_BLACK);
tft.setTextColor(TFT_RED);
tft.setCursor(0, 60);
tft.setTextDatum(MC_DATUM);
tft.setTextSize(2);
EnableBacklight(true);
force_redraw = true;
}
// Set the pin to turn the backlight on or off if available.
static void EnableBacklight(bool enable) {
#if TFT_BL > 0
#if USERMOD_PIXELS_DICE_TRAY_BL_ACTIVE_LOW
enable = !enable;
#endif
digitalWrite(TFT_BL, enable);
#endif
}
/**
* Double clicking navigates between menus. Button 0 goes down, and button 1
* goes up with wrapping.
*/
void HandleButton(ButtonType type, uint8_t b) {
force_redraw = true;
// Switch menus with double click
if (ButtonType::DOUBLE == type) {
if (b == 0) {
current_index =
(current_index == 0) ? menu_ptrs.size() - 1 : current_index - 1;
} else {
current_index = (current_index + 1) % menu_ptrs.size();
}
} else {
menu_ptrs[current_index]->HandleButton(type, b);
}
}
void Update(const DiceUpdate& dice_update) {
for (auto menu_ptr : menu_ptrs) {
menu_ptr->Update(dice_update);
}
menu_ptrs[current_index]->Draw(dice_update, force_redraw);
force_redraw = false;
}
void Redraw() { force_redraw = true; }
private:
size_t current_index = 0;
bool force_redraw = true;
DiceStatusMenu status_menu;
EffectMenu effect_menu;
InfoMenu info_menu;
const std::array<MenuBase*, 3> menu_ptrs = {&status_menu, &effect_menu,
&info_menu};
};
#endif

View File

@ -0,0 +1,85 @@
#pragma once
#include "wled.h"
#include <PNGdec.h>
void * openFile(const char *filename, int32_t *size) {
f = WLED_FS.open(filename);
*size = f.size();
return &f;
}
void closeFile(void *handle) {
if (f) f.close();
}
int32_t readFile(PNGFILE *pFile, uint8_t *pBuf, int32_t iLen)
{
int32_t iBytesRead;
iBytesRead = iLen;
File *f = static_cast<File *>(pFile->fHandle);
// Note: If you read a file all the way to the last byte, seek() stops working
if ((pFile->iSize - pFile->iPos) < iLen)
iBytesRead = pFile->iSize - pFile->iPos - 1; // <-- ugly work-around
if (iBytesRead <= 0)
return 0;
iBytesRead = (int32_t)f->read(pBuf, iBytesRead);
pFile->iPos = f->position();
return iBytesRead;
}
int32_t seekFile(PNGFILE *pFile, int32_t iPosition)
{
int i = micros();
File *f = static_cast<File *>(pFile->fHandle);
f->seek(iPosition);
pFile->iPos = (int32_t)f->position();
i = micros() - i;
return pFile->iPos;
}
void draw(PNGDRAW *pDraw) {
uint16_t usPixels[SEGLEN];
png.getLineAsRGB565(pDraw, usPixels, PNG_RGB565_LITTLE_ENDIAN, 0xffffffff);
for(int x=0; x < SEGLEN; x++) {
uint16_t color = usPixels[x];
byte r = ((color >> 11) & 0x1F);
byte g = ((color >> 5) & 0x3F);
byte b = (color & 0x1F);
SEGMENT.setPixelColor(x, RGBW32(r,g,b,0));
}
strip.show();
}
uint16_t mode_pov_image(void) {
const char * filepath = SEGMENT.name;
int rc = png.open(filepath, openFile, closeFile, readFile, seekFile, draw);
if (rc == PNG_SUCCESS) {
rc = png.decode(NULL, 0);
png.close();
return FRAMETIME;
}
return FRAMETIME;
}
class PovDisplayUsermod : public Usermod
{
public:
static const char _data_FX_MODE_POV_IMAGE[] PROGMEM = "POV Image@!;;;1";
PNG png;
File f;
void setup() {
strip.addEffect(255, &mode_pov_image, _data_FX_MODE_POV_IMAGE);
}
void loop() {
}
uint16_t getId()
{
return USERMOD_ID_POV_DISPLAY;
}
void connected() {}
};

View File

@ -165,7 +165,7 @@ private:
void _showElements(String *map, int timevar, bool isColon, bool removeZero
) {
if (!(*map).equals("") && !(*map) == NULL) {
if ((map != nullptr) && (*map != nullptr) && !(*map).equals("")) {
int length = String(timevar).length();
bool addZero = false;
if (length == 1) {
@ -236,11 +236,13 @@ private:
}
void _setLeds(int lednr, int lastSeenLedNr, bool range, int countSegments, int number, bool colon) {
if ((lednr < 0) || (lednr >= umSSDRLength)) return; // prevent array bounds violation
if (!(colon && umSSDRColonblink) && ((number < 0) || (countSegments < 0))) return;
if ((colon && umSSDRColonblink) || umSSDRNumbers[number][countSegments]) {
if (range) {
for(int i = lastSeenLedNr; i <= lednr; i++) {
for(int i = max(0, lastSeenLedNr); i <= lednr; i++) {
umSSDRMask[i] = true;
}
} else {

View File

@ -7805,18 +7805,23 @@ static const char _data_RESERVED[] PROGMEM = "RSVD";
// add (or replace reserved) effect mode and data into vector
// use id==255 to find unallocated gaps (with "Reserved" data string)
// if vector size() is smaller than id (single) data is appended at the end (regardless of id)
void WS2812FX::addEffect(uint8_t id, mode_ptr mode_fn, const char *mode_name) {
// return the actual id used for the effect or 255 if the add failed.
uint8_t WS2812FX::addEffect(uint8_t id, mode_ptr mode_fn, const char *mode_name) {
if (id == 255) { // find empty slot
for (size_t i=1; i<_mode.size(); i++) if (_modeData[i] == _data_RESERVED) { id = i; break; }
}
if (id < _mode.size()) {
if (_modeData[id] != _data_RESERVED) return; // do not overwrite alerady added effect
if (_modeData[id] != _data_RESERVED) return 255; // do not overwrite an already added effect
_mode[id] = mode_fn;
_modeData[id] = mode_name;
} else {
return id;
} else if(_mode.size() < 255) { // 255 is reserved for indicating the effect wasn't added
_mode.push_back(mode_fn);
_modeData.push_back(mode_name);
if (_modeCount < _mode.size()) _modeCount++;
return _mode.size() - 1;
} else {
return 255; // The vector is full so return 255
}
}

View File

@ -544,26 +544,26 @@ typedef struct Segment {
#endif
inline bool getOption(uint8_t n) const { return ((options >> n) & 0x01); }
inline bool isSelected(void) const { return selected; }
inline bool isInTransition(void) const { return _t != nullptr; }
inline bool isActive(void) const { return stop > start; }
inline bool is2D(void) const { return (width()>1 && height()>1); }
inline bool hasRGB(void) const { return _isRGB; }
inline bool hasWhite(void) const { return _hasW; }
inline bool isCCT(void) const { return _isCCT; }
inline uint16_t width(void) const { return isActive() ? (stop - start) : 0; } // segment width in physical pixels (length if 1D)
inline uint16_t height(void) const { return stopY - startY; } // segment height (if 2D) in physical pixels (it *is* always >=1)
inline uint16_t length(void) const { return width() * height(); } // segment length (count) in physical pixels
inline uint16_t groupLength(void) const { return grouping + spacing; }
inline uint8_t getLightCapabilities(void) const { return _capabilities; }
inline bool isSelected() const { return selected; }
inline bool isInTransition() const { return _t != nullptr; }
inline bool isActive() const { return stop > start; }
inline bool is2D() const { return (width()>1 && height()>1); }
inline bool hasRGB() const { return _isRGB; }
inline bool hasWhite() const { return _hasW; }
inline bool isCCT() const { return _isCCT; }
inline uint16_t width() const { return isActive() ? (stop - start) : 0; } // segment width in physical pixels (length if 1D)
inline uint16_t height() const { return stopY - startY; } // segment height (if 2D) in physical pixels (it *is* always >=1)
inline uint16_t length() const { return width() * height(); } // segment length (count) in physical pixels
inline uint16_t groupLength() const { return grouping + spacing; }
inline uint8_t getLightCapabilities() const { return _capabilities; }
static uint16_t getUsedSegmentData(void) { return _usedSegmentData; }
static void addUsedSegmentData(int len) { _usedSegmentData += len; }
inline static uint16_t getUsedSegmentData() { return _usedSegmentData; }
inline static void addUsedSegmentData(int len) { _usedSegmentData += len; }
#ifndef WLED_DISABLE_MODE_BLEND
static void modeBlend(bool blend) { _modeBlend = blend; }
inline static void modeBlend(bool blend) { _modeBlend = blend; }
#endif
static void handleRandomPalette();
inline static const CRGBPalette16 &getCurrentPalette(void) { return Segment::_currentPalette; }
inline static const CRGBPalette16 &getCurrentPalette() { return Segment::_currentPalette; }
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
@ -573,40 +573,40 @@ typedef struct Segment {
void setMode(uint8_t fx, bool loadDefaults = false);
void setPalette(uint8_t pal);
uint8_t differs(Segment& b) const;
void refreshLightCapabilities(void);
void refreshLightCapabilities();
// runtime data functions
inline uint16_t dataSize(void) const { return _dataLen; }
inline uint16_t dataSize() const { return _dataLen; }
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
void deallocateData(); // deallocates (frees) effect data buffer from heap
void resetIfRequired(); // 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.
* Call resetIfRequired before calling the next effect function.
* Safe to call from interrupts and network requests.
*/
inline void markForReset(void) { reset = true; } // setOption(SEG_OPTION_RESET, true)
inline void markForReset() { 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); // ends transition mode by destroying transition structure (does nothing if not in transition)
inline void handleTransition(void) { if (progress() == 0xFFFFU) stopTransition(); }
void stopTransition(); // ends transition mode by destroying transition structure (does nothing if not in transition)
inline void handleTransition() { if (progress() == 0xFFFFU) stopTransition(); }
#ifndef WLED_DISABLE_MODE_BLEND
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) const; // transition progression between 0-65535
uint8_t currentBri(bool useCct = false) const; // current segment brightness/CCT (blended while in transition)
uint8_t currentMode(void) const; // currently active effect/mode (while in transition)
uint8_t currentPalette(void) const; // currently active palette (while in transition)
uint32_t currentColor(uint8_t slot) const; // currently active segment color (blended while in transition)
CRGBPalette16 &loadPalette(CRGBPalette16 &tgt, uint8_t pal);
void setCurrentPalette(void);
[[gnu::hot]] uint16_t progress() const; // transition progression between 0-65535
[[gnu::hot]] uint8_t currentBri(bool useCct = false) const; // current segment brightness/CCT (blended while in transition)
uint8_t currentMode() const; // currently active effect/mode (while in transition)
[[gnu::hot]] uint8_t currentPalette(void) const; // currently active palette (while in transition)
[[gnu::hot]] uint32_t currentColor(uint8_t slot) const; // currently active segment color (blended while in transition)
[[gnu::hot]] CRGBPalette16 &loadPalette(CRGBPalette16 &tgt, uint8_t pal);
void setCurrentPalette();
// 1D strip
uint16_t virtualLength(void) const;
void setPixelColor(int n, uint32_t c); // set relative pixel within segment with color
[[gnu::hot]] uint16_t virtualLength() const;
[[gnu::hot]] void setPixelColor(int n, uint32_t c); // set relative pixel within segment with color
inline void setPixelColor(unsigned n, uint32_t c) { setPixelColor(int(n), c); }
inline void setPixelColor(int n, byte r, byte g, byte b, byte w = 0) { setPixelColor(n, RGBW32(r,g,b,w)); }
inline void setPixelColor(int n, CRGB c) { setPixelColor(n, RGBW32(c.r,c.g,c.b,0)); }
@ -619,7 +619,7 @@ typedef struct Segment {
static inline void setClippingRect(int startX, int stopX, int startY = 0, int stopY = 1) { _clipStart = startX; _clipStop = stopX; _clipStartY = startY; _clipStopY = stopY; };
#endif
bool isPixelClipped(int i) const;
uint32_t getPixelColor(int i) const;
[[gnu::hot]] uint32_t getPixelColor(int i) const;
// 1D support functions (some implement 2D as well)
void blur(uint8_t, bool smear = false);
void fill(uint32_t c);
@ -631,8 +631,8 @@ typedef struct Segment {
inline void addPixelColor(int n, byte r, byte g, byte b, byte w = 0, bool fast = false) { addPixelColor(n, RGBW32(r,g,b,w), fast); }
inline void addPixelColor(int n, CRGB c, bool fast = false) { addPixelColor(n, RGBW32(c.r,c.g,c.b,0), fast); }
inline void fadePixelColor(uint16_t n, uint8_t fade) { setPixelColor(n, color_fade(getPixelColor(n), fade, true)); }
uint32_t color_from_palette(uint16_t, bool mapping, bool wrap, uint8_t mcol, uint8_t pbri = 255) const;
uint32_t color_wheel(uint8_t pos) const;
[[gnu::hot]] uint32_t color_from_palette(uint16_t, bool mapping, bool wrap, uint8_t mcol, uint8_t pbri = 255) const;
[[gnu::hot]] uint32_t color_wheel(uint8_t pos) const;
// 2D Blur: shortcuts for bluring columns or rows only (50% faster than full 2D blur)
inline void blurCols(fract8 blur_amount, bool smear = false) { // blur all columns
@ -645,12 +645,12 @@ typedef struct Segment {
}
// 2D matrix
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)
[[gnu::hot]] uint16_t virtualWidth() const; // segment width in virtual pixels (accounts for groupping and spacing)
[[gnu::hot]] uint16_t virtualHeight() const; // segment height in virtual pixels (accounts for groupping and spacing)
[[gnu::hot]] uint16_t nrOfVStrips() const; // returns number of virtual vertical strips in 2D matrix (used to expand 1D effects into 2D)
#ifndef WLED_DISABLE_2D
uint16_t XY(int x, int 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
[[gnu::hot]] uint16_t XY(int x, int y); // support function to get relative index within segment
[[gnu::hot]] void setPixelColorXY(int x, int y, uint32_t c); // set relative pixel within segment with color
inline void setPixelColorXY(unsigned x, unsigned y, uint32_t c) { setPixelColorXY(int(x), int(y), 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)); }
@ -660,8 +660,8 @@ typedef struct Segment {
inline void setPixelColorXY(float x, float y, byte r, byte g, byte b, byte w = 0, bool aa = true) { setPixelColorXY(x, y, RGBW32(r,g,b,w), aa); }
inline void setPixelColorXY(float x, float y, CRGB c, bool aa = true) { setPixelColorXY(x, y, RGBW32(c.r,c.g,c.b,0), aa); }
#endif
bool isPixelXYClipped(int x, int y) const;
uint32_t getPixelColorXY(int x, int y) const;
[[gnu::hot]] bool isPixelXYClipped(int x, int y) const;
[[gnu::hot]] uint32_t getPixelColorXY(int x, int y) const;
// 2D support functions
inline void blendPixelColorXY(uint16_t x, uint16_t y, uint32_t color, uint8_t blend) { setPixelColorXY(x, y, color_blend(getPixelColorXY(x,y), color, blend)); }
inline void blendPixelColorXY(uint16_t x, uint16_t y, CRGB c, uint8_t blend) { blendPixelColorXY(x, y, RGBW32(c.r,c.g,c.b,0), blend); }
@ -731,8 +731,8 @@ typedef struct Segment {
// main "strip" class
class WS2812FX { // 96 bytes
typedef uint16_t (*mode_ptr)(void); // pointer to mode function
typedef void (*show_callback)(void); // pre show callback
typedef uint16_t (*mode_ptr)(); // pointer to mode function
typedef void (*show_callback)(); // pre show callback
typedef struct ModeData {
uint8_t _id; // mode (effect) id
mode_ptr _fcn; // mode (effect) function
@ -796,30 +796,29 @@ class WS2812FX { // 96 bytes
customPalettes.clear();
}
static WS2812FX* getInstance(void) { return instance; }
static WS2812FX* getInstance() { return instance; }
void
#ifdef WLED_DEBUG
printSize(), // prints memory usage for strip components
#endif
finalizeInit(), // initialises strip components
service(void), // executes effect functions when due and calls strip.show()
service(), // 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)
purgeSegments(), // 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(), // 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
show(), // 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(); // add default effects to the list; defined in FX.cpp
inline void resetTimebase() { timebase = 0U - millis(); }
inline void restartRuntime() { for (Segment &seg : _segments) seg.markForReset(); }
@ -828,71 +827,72 @@ class WS2812FX { // 96 bytes
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 trigger() { _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
inline void suspend() { _suspend = true; } // will suspend (and canacel) strip.service() execution
inline void resume() { _suspend = false; } // will resume strip.service() execution
bool
checkSegmentAlignment(void),
hasRGBWBus(void) const,
hasCCTBus(void) const,
isUpdating(void) const, // return true if the strip is being sent pixel updates
checkSegmentAlignment(),
hasRGBWBus() const,
hasCCTBus() const,
isUpdating() const, // return true if the strip is being sent pixel updates
deserializeMap(uint8_t n=0);
inline bool isServicing(void) const { return _isServicing; } // returns true if strip.service() is executing
inline bool hasWhiteChannel(void) const { return _hasWhiteChannel; } // returns true if strip contains separate white chanel
inline bool isOffRefreshRequired(void) const { return _isOffRefreshRequired; } // returns true if strip requires regular updates (i.e. TM1814 chipset)
inline bool isSuspended(void) const { return _suspend; } // returns true if strip.service() execution is suspended
inline bool needsUpdate(void) const { return _triggered; } // returns true if strip received a trigger() request
inline bool isServicing() const { return _isServicing; } // returns true if strip.service() is executing
inline bool hasWhiteChannel() const { return _hasWhiteChannel; } // returns true if strip contains separate white chanel
inline bool isOffRefreshRequired() const { return _isOffRefreshRequired; } // returns true if strip requires regular updates (i.e. TM1814 chipset)
inline bool isSuspended() const { return _suspend; } // returns true if strip.service() execution is suspended
inline bool needsUpdate() const { return _triggered; } // returns true if strip received a trigger() request
uint8_t
paletteBlend,
getActiveSegmentsNum(void) const,
getFirstSelectedSegId(void) const,
getLastActiveSegmentId(void) const,
getActiveSegsLightCapabilities(bool selectedOnly = false) const;
getActiveSegmentsNum() const,
getFirstSelectedSegId() const,
getLastActiveSegmentId() const,
getActiveSegsLightCapabilities(bool selectedOnly = false) const,
addEffect(uint8_t id, mode_ptr mode_fn, const char *mode_name); // add effect to the list; defined in FX.cpp;
inline uint8_t getBrightness(void) const { return _brightness; } // returns current strip brightness
inline uint8_t getMaxSegments(void) const { return MAX_NUM_SEGMENTS; } // returns maximum number of supported segments (fixed value)
inline uint8_t getSegmentsNum(void) const { return _segments.size(); } // returns currently present segments
inline uint8_t getCurrSegmentId(void) const { return _segment_index; } // returns current segment index (only valid while strip.isServicing())
inline uint8_t getMainSegmentId(void) const { return _mainSegment; } // returns main segment index
inline uint8_t getPaletteCount() const { return 13 + GRADIENT_PALETTE_COUNT + customPalettes.size(); }
inline uint8_t getTargetFps() const { return _targetFps; } // returns rough FPS value for las 2s interval
inline uint8_t getModeCount() const { return _modeCount; } // returns number of registered modes/effects
inline uint8_t getBrightness() const { return _brightness; } // returns current strip brightness
inline uint8_t getMaxSegments() const { return MAX_NUM_SEGMENTS; } // returns maximum number of supported segments (fixed value)
inline uint8_t getSegmentsNum() const { return _segments.size(); } // returns currently present segments
inline uint8_t getCurrSegmentId() const { return _segment_index; } // returns current segment index (only valid while strip.isServicing())
inline uint8_t getMainSegmentId() const { return _mainSegment; } // returns main segment index
inline uint8_t getPaletteCount() const { return 13 + GRADIENT_PALETTE_COUNT + customPalettes.size(); }
inline uint8_t getTargetFps() const { return _targetFps; } // returns rough FPS value for las 2s interval
inline uint8_t getModeCount() const { return _modeCount; } // returns number of registered modes/effects
uint16_t
getLengthPhysical(void) const,
getLengthTotal(void) const, // will include virtual/nonexistent pixels in matrix
getLengthPhysical() const,
getLengthTotal() const, // will include virtual/nonexistent pixels in matrix
getFps() const,
getMappedPixelIndex(uint16_t index) const;
inline uint16_t getFrameTime(void) const { return _frametime; } // returns amount of time a frame should take (in ms)
inline uint16_t getMinShowDelay(void) const { return MIN_SHOW_DELAY; } // returns minimum amount of time strip.service() can be delayed (constant)
inline uint16_t getLength(void) const { return _length; } // returns actual amount of LEDs on a strip (2D matrix may have less LEDs than W*H)
inline uint16_t getTransition(void) const { return _transitionDur; } // returns currently set transition time (in ms)
inline uint16_t getFrameTime() const { return _frametime; } // returns amount of time a frame should take (in ms)
inline uint16_t getMinShowDelay() const { return MIN_SHOW_DELAY; } // returns minimum amount of time strip.service() can be delayed (constant)
inline uint16_t getLength() const { return _length; } // returns actual amount of LEDs on a strip (2D matrix may have less LEDs than W*H)
inline uint16_t getTransition() const { return _transitionDur; } // returns currently set transition time (in ms)
uint32_t
now,
timebase,
getPixelColor(uint16_t) const;
inline uint32_t getLastShow(void) const { return _lastShow; } // returns millis() timestamp of last strip.show() call
inline uint32_t getLastShow() const { return _lastShow; } // returns millis() timestamp of last strip.show() call
inline uint32_t segColor(uint8_t i) const { 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) const { return (id && id<_modeCount) ? _modeData[id] : PSTR("Solid"); }
const char **
getModeDataSrc(void) { return &(_modeData[0]); } // vectors use arrays for underlying data
getModeDataSrc() { return &(_modeData[0]); } // vectors use arrays for underlying data
Segment& getSegment(uint8_t id);
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)
inline Segment& getFirstSelectedSeg() { return _segments[getFirstSelectedSegId()]; } // returns reference to first segment that is "selected"
inline Segment& getMainSegment() { return _segments[getMainSegmentId()]; } // returns reference to main segment
inline Segment* getSegments() { return &(_segments[0]); } // returns pointer to segment vector structure (warning: use carefully)
// 2D support (panels)
bool
@ -939,7 +939,7 @@ class WS2812FX { // 96 bytes
// end 2D support
void loadCustomPalettes(void); // loads custom palettes from JSON
void loadCustomPalettes(); // loads custom palettes from JSON
std::vector<CRGBPalette16> customPalettes; // TODO: move custom palettes out of WS2812FX class
struct {

View File

@ -161,7 +161,7 @@ void WS2812FX::setUpMatrix() {
#ifndef WLED_DISABLE_2D
// XY(x,y) - gets pixel index within current segment (often used to reference leds[] array element)
uint16_t IRAM_ATTR Segment::XY(int x, int y) {
uint16_t IRAM_ATTR_YN Segment::XY(int x, int y) {
unsigned width = virtualWidth(); // segment width in logical pixels (can be 0 if segment is inactive)
unsigned height = virtualHeight(); // segment height in logical pixels (is always >= 1)
return isActive() ? (x%width) + (y%height) * width : 0;
@ -171,7 +171,7 @@ uint16_t IRAM_ATTR Segment::XY(int x, int y) {
// if clipping start > stop the clipping range is inverted
// _modeBlend==true -> old effect during transition
// _modeBlend==false -> new effect during transition
bool IRAM_ATTR Segment::isPixelXYClipped(int x, int y) const {
bool IRAM_ATTR_YN Segment::isPixelXYClipped(int x, int y) const {
#ifndef WLED_DISABLE_MODE_BLEND
if (_clipStart != _clipStop && blendingStyle > BLEND_STYLE_FADE) {
const bool invertX = _clipStart > _clipStop;
@ -198,7 +198,7 @@ bool IRAM_ATTR Segment::isPixelXYClipped(int x, int y) const {
return false;
}
void IRAM_ATTR Segment::setPixelColorXY(int x, int y, uint32_t col)
void IRAM_ATTR_YN Segment::setPixelColorXY(int x, int y, uint32_t col)
{
if (!isActive()) return; // not active
@ -265,7 +265,7 @@ void IRAM_ATTR Segment::setPixelColorXY(int x, int y, uint32_t col)
else strip.setPixelColorXY(start + xX, startY + H - yY - 1, tmpCol);
}
if (mirror_y && mirror) { //set the corresponding vertically AND horizontally mirrored pixel
strip.setPixelColorXY(W - xX - 1, H - yY - 1, tmpCol);
strip.setPixelColorXY(start + W - xX - 1, startY + H - yY - 1, tmpCol);
}
}
}
@ -318,7 +318,7 @@ void Segment::setPixelColorXY(float x, float y, uint32_t col, bool aa)
#endif
// returns RGBW values of pixel
uint32_t IRAM_ATTR Segment::getPixelColorXY(int x, int y) const {
uint32_t IRAM_ATTR_YN Segment::getPixelColorXY(int x, int y) const {
if (!isActive()) return 0; // not active
int vW = virtualWidth();

View File

@ -150,7 +150,7 @@ Segment& Segment::operator= (Segment &&orig) noexcept {
}
// allocates effect data buffer on heap and initialises (erases) it
bool IRAM_ATTR Segment::allocateData(size_t len) {
bool IRAM_ATTR_YN 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
@ -174,7 +174,7 @@ bool IRAM_ATTR Segment::allocateData(size_t len) {
return true;
}
void IRAM_ATTR Segment::deallocateData() {
void IRAM_ATTR_YN Segment::deallocateData() {
if (!data) { _dataLen = 0; return; }
//DEBUG_PRINTF_P(PSTR("--- Released data (%p): %d/%d -> %p\n"), this, _dataLen, Segment::getUsedSegmentData(), data);
if ((Segment::getUsedSegmentData() > 0) && (_dataLen > 0)) { // check that we don't have a dangling / inconsistent data pointer
@ -206,7 +206,7 @@ void Segment::resetIfRequired() {
reset = false;
}
CRGBPalette16 IRAM_ATTR &Segment::loadPalette(CRGBPalette16 &targetPalette, uint8_t pal) {
CRGBPalette16 IRAM_ATTR_YN &Segment::loadPalette(CRGBPalette16 &targetPalette, uint8_t pal) {
if (pal < 245 && pal > GRADIENT_PALETTE_COUNT+13) pal = 0;
if (pal > 245 && (strip.customPalettes.size() == 0 || 255U-pal > strip.customPalettes.size()-1)) pal = 0; // TODO remove strip dependency by moving customPalettes out of strip
//default palette. Differs depending on effect
@ -425,7 +425,7 @@ uint8_t IRAM_ATTR Segment::currentBri(bool useCct) const {
return curBri;
}
uint8_t IRAM_ATTR Segment::currentMode() const {
uint8_t IRAM_ATTR_YN Segment::currentMode() const {
#ifndef WLED_DISABLE_MODE_BLEND
unsigned prog = progress();
if (prog == 0xFFFFU) return mode;
@ -441,7 +441,7 @@ uint8_t IRAM_ATTR Segment::currentMode() const {
#endif
}
uint32_t IRAM_ATTR Segment::currentColor(uint8_t slot) const {
uint32_t IRAM_ATTR_YN Segment::currentColor(uint8_t slot) const {
if (slot >= NUM_COLORS) slot = 0;
uint32_t prog = progress();
if (prog == 0xFFFFU) return colors[slot];
@ -664,7 +664,7 @@ uint16_t IRAM_ATTR Segment::virtualHeight() const {
return vHeight;
}
uint16_t IRAM_ATTR Segment::nrOfVStrips() const {
uint16_t IRAM_ATTR_YN Segment::nrOfVStrips() const {
unsigned vLen = 1;
#ifndef WLED_DISABLE_2D
if (is2D()) {
@ -751,7 +751,7 @@ uint16_t IRAM_ATTR Segment::virtualLength() const {
// if clipping start > stop the clipping range is inverted
// _modeBlend==true -> old effect during transition
// _modeBlend==false -> new effect during transition
bool IRAM_ATTR Segment::isPixelClipped(int i) const {
bool IRAM_ATTR_YN Segment::isPixelClipped(int i) const {
#ifndef WLED_DISABLE_MODE_BLEND
if (_clipStart != _clipStop && blendingStyle > BLEND_STYLE_FADE) {
bool invert = _clipStart > _clipStop; // ineverted start & stop
@ -774,7 +774,7 @@ bool IRAM_ATTR Segment::isPixelClipped(int i) const {
return false;
}
void IRAM_ATTR Segment::setPixelColor(int i, uint32_t col)
void IRAM_ATTR_YN Segment::setPixelColor(int i, uint32_t col)
{
if (!isActive()) return; // not active
#ifndef WLED_DISABLE_2D
@ -983,7 +983,7 @@ void Segment::setPixelColor(float i, uint32_t col, bool aa)
}
#endif
uint32_t IRAM_ATTR Segment::getPixelColor(int i) const
uint32_t IRAM_ATTR_YN Segment::getPixelColor(int i) const
{
if (!isActive()) return 0; // not active
#ifndef WLED_DISABLE_2D
@ -996,8 +996,8 @@ uint32_t IRAM_ATTR Segment::getPixelColor(int i) const
#ifndef WLED_DISABLE_2D
if (is2D()) {
unsigned vH = virtualHeight(); // segment height in logical pixels
unsigned vW = virtualWidth();
int vH = virtualHeight(); // segment height in logical pixels
int vW = virtualWidth();
switch (map1D2D) {
case M12_Pixels:
return getPixelColorXY(i % vW, i / vW);
@ -1299,7 +1299,7 @@ uint32_t Segment::color_from_palette(uint16_t i, bool mapping, bool wrap, uint8_
///////////////////////////////////////////////////////////////////////////////
//do not call this method from system context (network callback)
void WS2812FX::finalizeInit(void) {
void WS2812FX::finalizeInit() {
//reset segment runtimes
for (segment &seg : _segments) {
seg.markForReset();
@ -1535,7 +1535,7 @@ uint32_t IRAM_ATTR WS2812FX::getPixelColor(uint16_t i) const {
return BusManager::getPixelColor(i);
}
void WS2812FX::show(void) {
void WS2812FX::show() {
// avoid race condition, capture _callback value
show_callback callback = _callback;
if (callback) callback();
@ -1632,7 +1632,7 @@ uint8_t WS2812FX::getActiveSegsLightCapabilities(bool selectedOnly) const {
return totalLC;
}
uint8_t WS2812FX::getFirstSelectedSegId(void) const {
uint8_t WS2812FX::getFirstSelectedSegId() const {
size_t i = 0;
for (const segment &seg : _segments) {
if (seg.isActive() && seg.isSelected()) return i;
@ -1650,14 +1650,14 @@ void WS2812FX::setMainSegmentId(uint8_t n) {
return;
}
uint8_t WS2812FX::getLastActiveSegmentId(void) const {
uint8_t WS2812FX::getLastActiveSegmentId() const {
for (size_t i = _segments.size() -1; i > 0; i--) {
if (_segments[i].isActive()) return i;
}
return 0;
}
uint8_t WS2812FX::getActiveSegmentsNum(void) const {
uint8_t WS2812FX::getActiveSegmentsNum() const {
uint8_t c = 0;
for (size_t i = 0; i < _segments.size(); i++) {
if (_segments[i].isActive()) c++;
@ -1665,13 +1665,13 @@ uint8_t WS2812FX::getActiveSegmentsNum(void) const {
return c;
}
uint16_t WS2812FX::getLengthTotal(void) const {
uint16_t WS2812FX::getLengthTotal() const {
unsigned len = Segment::maxWidth * Segment::maxHeight; // will be _length for 1D (see finalizeInit()) but should cover whole matrix for 2D
if (isMatrix && _length > len) len = _length; // for 2D with trailing strip
return len;
}
uint16_t WS2812FX::getLengthPhysical(void) const {
uint16_t WS2812FX::getLengthPhysical() const {
unsigned len = 0;
for (size_t b = 0; b < BusManager::getNumBusses(); b++) {
Bus *bus = BusManager::getBus(b);
@ -1684,7 +1684,7 @@ uint16_t WS2812FX::getLengthPhysical(void) const {
//used for JSON API info.leds.rgbw. Little practical use, deprecate with info.leds.rgbw.
//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) const {
bool WS2812FX::hasRGBWBus() const {
for (size_t b = 0; b < BusManager::getNumBusses(); b++) {
Bus *bus = BusManager::getBus(b);
if (bus == nullptr || bus->getLength()==0) break;
@ -1693,7 +1693,7 @@ bool WS2812FX::hasRGBWBus(void) const {
return false;
}
bool WS2812FX::hasCCTBus(void) const {
bool WS2812FX::hasCCTBus() const {
if (cctFromRgb && !correctWB) return false;
for (size_t b = 0; b < BusManager::getNumBusses(); b++) {
Bus *bus = BusManager::getBus(b);

View File

@ -497,46 +497,19 @@ uint32_t BusPwm::getPixelColor(uint16_t pix) {
return RGBW32(_data[0], _data[0], _data[0], _data[0]);
}
#ifndef ESP8266
static const uint16_t cieLUT[256] = {
0, 2, 4, 5, 7, 9, 11, 13, 15, 16,
18, 20, 22, 24, 26, 27, 29, 31, 33, 35,
34, 36, 37, 39, 41, 43, 45, 47, 49, 52,
54, 56, 59, 61, 64, 67, 69, 72, 75, 78,
81, 84, 87, 90, 94, 97, 100, 104, 108, 111,
115, 119, 123, 127, 131, 136, 140, 144, 149, 154,
158, 163, 168, 173, 178, 183, 189, 194, 200, 205,
211, 217, 223, 229, 235, 241, 247, 254, 261, 267,
274, 281, 288, 295, 302, 310, 317, 325, 333, 341,
349, 357, 365, 373, 382, 391, 399, 408, 417, 426,
436, 445, 455, 464, 474, 484, 494, 505, 515, 526,
536, 547, 558, 569, 580, 592, 603, 615, 627, 639,
651, 663, 676, 689, 701, 714, 727, 741, 754, 768,
781, 795, 809, 824, 838, 853, 867, 882, 897, 913,
928, 943, 959, 975, 991, 1008, 1024, 1041, 1058, 1075,
1092, 1109, 1127, 1144, 1162, 1180, 1199, 1217, 1236, 1255,
1274, 1293, 1312, 1332, 1352, 1372, 1392, 1412, 1433, 1454,
1475, 1496, 1517, 1539, 1561, 1583, 1605, 1628, 1650, 1673,
1696, 1719, 1743, 1767, 1791, 1815, 1839, 1864, 1888, 1913,
1939, 1964, 1990, 2016, 2042, 2068, 2095, 2121, 2148, 2176,
2203, 2231, 2259, 2287, 2315, 2344, 2373, 2402, 2431, 2461,
2491, 2521, 2551, 2581, 2612, 2643, 2675, 2706, 2738, 2770,
2802, 2835, 2867, 2900, 2934, 2967, 3001, 3035, 3069, 3104,
3138, 3174, 3209, 3244, 3280, 3316, 3353, 3389, 3426, 3463,
3501, 3539, 3576, 3615, 3653, 3692, 3731, 3770, 3810, 3850,
3890, 3930, 3971, 4012, 4053, 4095
};
#endif
void BusPwm::show() {
if (!_valid) return;
unsigned numPins = NUM_PWM_PINS(_type);
unsigned maxBri = (1<<_depth) - 1;
#ifdef ESP8266
unsigned pwmBri = (unsigned)(roundf(powf((float)_bri / 255.0f, 1.7f) * (float)maxBri)); // using gamma 1.7 to extrapolate PWM duty cycle
#else
unsigned pwmBri = cieLUT[_bri] >> (12 - _depth); // use CIE LUT
#endif
// use CIE brightness formula
unsigned pwmBri = (unsigned)_bri * 100;
if(pwmBri < 2040) pwmBri = ((pwmBri << _depth) + 115043) / 230087; //adding '0.5' before division for correct rounding
else {
pwmBri += 4080;
float temp = (float)pwmBri / 29580;
temp = temp * temp * temp * (1<<_depth) - 1;
pwmBri = (unsigned)temp;
}
for (unsigned i = 0; i < numPins; i++) {
unsigned scaled = (_data[i] * pwmBri) / 255;
if (_reversed) scaled = maxBri - scaled;

View File

@ -125,7 +125,7 @@ void handleSwitch(uint8_t b)
{
// isButtonPressed() handles inverted/noninverted logic
if (buttonPressedBefore[b] != isButtonPressed(b)) {
DEBUG_PRINT(F("Switch: State changed ")); DEBUG_PRINTLN(b);
DEBUG_PRINTF_P(PSTR("Switch: State changed %u\n"), b);
buttonPressedTime[b] = millis();
buttonPressedBefore[b] = !buttonPressedBefore[b];
}
@ -133,15 +133,15 @@ void handleSwitch(uint8_t b)
if (buttonLongPressed[b] == buttonPressedBefore[b]) return;
if (millis() - buttonPressedTime[b] > WLED_DEBOUNCE_THRESHOLD) { //fire edge event only after 50ms without change (debounce)
DEBUG_PRINT(F("Switch: Activating ")); DEBUG_PRINTLN(b);
DEBUG_PRINTF_P(PSTR("Switch: Activating %u\n"), b);
if (!buttonPressedBefore[b]) { // on -> off
DEBUG_PRINT(F("Switch: On -> Off ")); DEBUG_PRINTLN(b);
DEBUG_PRINTF_P(PSTR("Switch: On -> Off (%u)\n"), b);
if (macroButton[b]) applyPreset(macroButton[b], CALL_MODE_BUTTON_PRESET);
else { //turn on
if (!bri) {toggleOnOff(); stateUpdated(CALL_MODE_BUTTON);}
}
} else { // off -> on
DEBUG_PRINT(F("Switch: Off -> On ")); DEBUG_PRINTLN(b);
DEBUG_PRINTF_P(PSTR("Switch: Off -> On (%u)\n"), b);
if (macroLongPress[b]) applyPreset(macroLongPress[b], CALL_MODE_BUTTON_PRESET);
else { //turn off
if (bri) {toggleOnOff(); stateUpdated(CALL_MODE_BUTTON);}
@ -173,7 +173,7 @@ void handleAnalog(uint8_t b)
static float filteredReading[WLED_MAX_BUTTONS] = {0.0f};
unsigned rawReading; // raw value from analogRead, scaled to 12bit
DEBUG_PRINT(F("Analog: Reading button ")); DEBUG_PRINTLN(b);
DEBUG_PRINTF_P(PSTR("Analog: Reading button %u\n"), b);
#ifdef ESP8266
rawReading = analogRead(A0) << 2; // convert 10bit read to 12bit
@ -193,8 +193,8 @@ void handleAnalog(uint8_t b)
// remove noise & reduce frequency of UI updates
if (abs(int(aRead) - int(oldRead[b])) <= POT_SENSITIVITY) return; // no significant change in reading
DEBUG_PRINT(F("Analog: Raw = ")); DEBUG_PRINT(rawReading);
DEBUG_PRINT(F(" Filtered = ")); DEBUG_PRINTLN(aRead);
DEBUG_PRINTF_P(PSTR("Analog: Raw = %u\n"), rawReading);
DEBUG_PRINTF_P(PSTR(" Filtered = %u\n"), aRead);
// Unomment the next lines if you still see flickering related to potentiometer
// This waits until strip finishes updating (why: strip was not updating at the start of handleButton() but may have started during analogRead()?)
@ -207,7 +207,7 @@ void handleAnalog(uint8_t b)
// if no macro for "short press" and "long press" is defined use brightness control
if (!macroButton[b] && !macroLongPress[b]) {
DEBUG_PRINT(F("Analog: Action = ")); DEBUG_PRINTLN(macroDoublePress[b]);
DEBUG_PRINTF_P(PSTR("Analog: Action = %u\n"), macroDoublePress[b]);
// if "double press" macro defines which option to change
if (macroDoublePress[b] >= 250) {
// global brightness
@ -308,7 +308,7 @@ void handleButton()
buttonLongPressed[b] = true;
}
} else if (!isButtonPressed(b) && buttonPressedBefore[b]) { //released
} else if (buttonPressedBefore[b]) { //released
long dur = now - buttonPressedTime[b];
// released after rising-edge short press action

View File

@ -277,9 +277,7 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
if ((buttonType[s] == BTN_TYPE_ANALOG) || (buttonType[s] == BTN_TYPE_ANALOG_INVERTED)) {
if (digitalPinToAnalogChannel(btnPin[s]) < 0) {
// not an ADC analog pin
DEBUG_PRINT(F("PIN ALLOC error: GPIO")); DEBUG_PRINT(btnPin[s]);
DEBUG_PRINT(F("for analog button #")); DEBUG_PRINT(s);
DEBUG_PRINTLN(F(" is not an analog pin!"));
DEBUG_PRINTF_P(PSTR("PIN ALLOC error: GPIO%d for analog button #%d is not an analog pin!\n"), btnPin[s], s);
btnPin[s] = -1;
pinManager.deallocatePin(pin,PinOwner::Button);
} else {
@ -290,7 +288,7 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
{
if (digitalPinToTouchChannel(btnPin[s]) < 0) {
// not a touch pin
DEBUG_PRINTF_P(PSTR("PIN ALLOC error: GPIO%d for touch button #%d is not an touch pin!\n"), btnPin[s], s);
DEBUG_PRINTF_P(PSTR("PIN ALLOC error: GPIO%d for touch button #%d is not a touch pin!\n"), btnPin[s], s);
btnPin[s] = -1;
pinManager.deallocatePin(pin,PinOwner::Button);
}
@ -298,7 +296,7 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
#ifdef SOC_TOUCH_VERSION_2 // ESP32 S2 and S3 have a function to check touch state but need to attach an interrupt to do so
else
{
touchAttachInterrupt(btnPin[s], touchButtonISR, 256 + (touchThreshold << 4)); // threshold on Touch V2 is much higher (1500 is a value given by Espressif example, I measured changes of over 5000)
touchAttachInterrupt(btnPin[s], touchButtonISR, touchThreshold << 4); // threshold on Touch V2 is much higher (1500 is a value given by Espressif example, I measured changes of over 5000)
}
#endif
}

View File

@ -37,6 +37,8 @@ uint32_t color_blend(uint32_t color1, uint32_t color2, uint16_t blend, bool b16)
*/
uint32_t color_add(uint32_t c1, uint32_t c2, bool fast)
{
if (c1 == BLACK) return c2;
if (c2 == BLACK) return c1;
if (fast) {
uint8_t r = R(c1);
uint8_t g = G(c1);
@ -68,17 +70,18 @@ uint32_t color_add(uint32_t c1, uint32_t c2, bool fast)
uint32_t color_fade(uint32_t c1, uint8_t amount, bool video)
{
if (c1 == BLACK || amount + video == 0) return BLACK;
uint32_t scaledcolor; // color order is: W R G B from MSB to LSB
uint32_t r = R(c1);
uint32_t g = G(c1);
uint32_t b = B(c1);
uint32_t w = W(c1);
uint32_t scale = amount + !video; // 32bit for faster calculation
uint32_t scale = amount; // 32bit for faster calculation
if (video) {
scaledcolor = (((r * scale) >> 8) << 16) + ((r && scale) ? 1 : 0);
scaledcolor |= (((g * scale) >> 8) << 8) + ((g && scale) ? 1 : 0);
scaledcolor |= ((b * scale) >> 8) + ((b && scale) ? 1 : 0);
scaledcolor |= (((w * scale) >> 8) << 24) + ((w && scale) ? 1 : 0);
scaledcolor = (((r * scale) >> 8) + ((r && scale) ? 1 : 0)) << 16;
scaledcolor |= (((g * scale) >> 8) + ((g && scale) ? 1 : 0)) << 8;
scaledcolor |= ((b * scale) >> 8) + ((b && scale) ? 1 : 0);
scaledcolor |= (((w * scale) >> 8) + ((w && scale) ? 1 : 0)) << 24;
} else {
scaledcolor = ((r * scale) >> 8) << 16;
scaledcolor |= ((g * scale) >> 8) << 8;
@ -195,7 +198,7 @@ CRGBPalette16 generateHarmonicRandomPalette(CRGBPalette16 &basepalette)
RGBpalettecolors[3]);
}
CRGBPalette16 generateRandomPalette(void) //generate fully random palette
CRGBPalette16 generateRandomPalette() //generate fully random palette
{
return CRGBPalette16(CHSV(random8(), random8(160, 255), random8(128, 255)),
CHSV(random8(), random8(160, 255), random8(128, 255)),
@ -476,14 +479,14 @@ void NeoGammaWLEDMethod::calcGammaTable(float gamma)
}
}
uint8_t NeoGammaWLEDMethod::Correct(uint8_t value)
uint8_t IRAM_ATTR NeoGammaWLEDMethod::Correct(uint8_t value)
{
if (!gammaCorrectCol) return value;
return gammaT[value];
}
// used for color gamma correction
uint32_t NeoGammaWLEDMethod::Correct32(uint32_t color)
uint32_t IRAM_ATTR NeoGammaWLEDMethod::Correct32(uint32_t color)
{
if (!gammaCorrectCol) return color;
uint8_t w = W(color);

View File

@ -200,6 +200,8 @@
#define USERMOD_ID_INA226 50 //Usermod "usermod_ina226.h"
#define USERMOD_ID_AHT10 51 //Usermod "usermod_aht10.h"
#define USERMOD_ID_LD2410 52 //Usermod "usermod_ld2410.h"
#define USERMOD_ID_POV_DISPLAY 53 //Usermod "usermod_pov_display.h"
#define USERMOD_ID_PIXELS_DICE_TRAY 54 //Usermod "pixels_dice_tray.h"
//Access point behavior
#define AP_BEHAVIOR_BOOT_NO_CONN 0 //Open AP when no connection after boot
@ -626,4 +628,12 @@
#define HW_PIN_MISOSPI MISO
#endif
// IRAM_ATTR for 8266 with 32Kb IRAM causes error: section `.text1' will not fit in region `iram1_0_seg'
// this hack removes the IRAM flag for some 1D/2D functions - somewhat slower, but it solves problems with some older 8266 chips
#ifdef WLED_SAVE_IRAM
#define IRAM_ATTR_YN
#else
#define IRAM_ATTR_YN IRAM_ATTR
#endif
#endif

View File

@ -805,12 +805,13 @@ Swap: <select id="xw${s}" name="XW${s}">
<div id="abl">
<i>Automatically limits brightness to stay close to the limit.<br>
Keep at &lt;1A if poweing LEDs directly from the ESP 5V pin!<br>
If using multiple outputs it is recommended to use per-output limiter.<br>
Analog (PWM) and virtual LEDs cannot use automatic brightness limiter.<br></i>
<div id="psuMA">Maximum PSU Current: <input name="MA" type="number" class="xl" min="250" max="65000" oninput="UI()" required> mA<br></div>
Use per-output limiter: <input type="checkbox" name="PPL" onchange="UI()"><br>
<div id="ppldis" style="display:none;">
<i>Make sure you enter correct values in each LED output.<br>
If using multiple outputs with only one PSU, distribute its power proportionally amongst ouputs.</i><br>
<i>Make sure you enter correct value for each LED output.<br>
If using multiple outputs with only one PSU, distribute its power proportionally amongst outputs.</i><br>
</div>
<div id="ampwarning" class="warn" style="display: none;">
&#9888; Your power supply provides high current.<br>
@ -824,7 +825,7 @@ Swap: <select id="xw${s}" name="XW${s}">
<hr class="sml">
<button type="button" id="+" onclick="addLEDs(1,false)">+</button>
<button type="button" id="-" onclick="addLEDs(-1,false)">-</button><br>
LED Memory Usage: <span id="m0">0</span> / <span id="m1">?</span> B<br>
LED memory usage: <span id="m0">0</span> / <span id="m1">?</span> B<br>
<div id="dbar" style="display:inline-block; width: 100px; height: 10px; border-radius: 20px;"></div><br>
<div id="ledwarning" class="warn" style="display: none;">
&#9888; You might run into stability or lag issues.<br>
@ -868,19 +869,18 @@ Swap: <select id="xw${s}" name="XW${s}">
<h3>Defaults</h3>
Turn LEDs on after power up/reset: <input type="checkbox" name="BO"><br>
Default brightness: <input name="CA" type="number" class="m" min="1" max="255" required> (1-255)<br><br>
Apply preset <input name="BP" type="number" class="m" min="0" max="250" required> at boot (0 uses defaults)
<br><br>
Apply preset <input name="BP" type="number" class="m" min="0" max="250" required> at boot (0 uses values from above)<br><br>
Use Gamma correction for color: <input type="checkbox" name="GC"> (strongly recommended)<br>
Use Gamma correction for brightness: <input type="checkbox" name="GB"> (not recommended)<br>
Use Gamma value: <input name="GV" type="number" class="m" placeholder="2.8" min="1" max="3" step="0.1" required><br><br>
Brightness factor: <input name="BF" type="number" class="m" min="1" max="255" required> %
<h3>Transitions</h3>
Transition Time: <input name="TD" type="number" class="xl" min="0" max="65500"> ms<br>
Default transition time: <input name="TD" type="number" class="xl" min="0" max="65500"> ms<br>
<i>Random Cycle</i> Palette Time: <input name="TP" type="number" class="m" min="1" max="255"> s<br>
Use harmonic <i>Random Cycle</i> Palette: <input type="checkbox" name="TH"><br>
<h3>Timed light</h3>
Default Duration: <input name="TL" type="number" class="m" min="1" max="255" required> min<br>
Default Target brightness: <input name="TB" type="number" class="m" min="0" max="255" required><br>
Default duration: <input name="TL" type="number" class="m" min="1" max="255" required> min<br>
Default target brightness: <input name="TB" type="number" class="m" min="0" max="255" required><br>
Mode:
<select name="TW">
<option value="0">Wait and set</option>
@ -906,7 +906,7 @@ Swap: <select id="xw${s}" name="XW${s}">
CCT additive blending: <input type="number" class="s" min="0" max="100" name="CB" required> %
</div>
<h3>Advanced</h3>
Palette blending:
Palette wrapping:
<select name="PB">
<option value="0">Linear (wrap if moving)</option>
<option value="1">Linear (always wrap)</option>

View File

@ -108,13 +108,7 @@ void handleE131Packet(e131_packet_t* p, IPAddress clientIP, byte protocol){
if (e131SkipOutOfSequence)
if (seq < e131LastSequenceNumber[previousUniverses] && seq > 20 && e131LastSequenceNumber[previousUniverses] < 250){
DEBUG_PRINT(F("skipping E1.31 frame (last seq="));
DEBUG_PRINT(e131LastSequenceNumber[previousUniverses]);
DEBUG_PRINT(F(", current seq="));
DEBUG_PRINT(seq);
DEBUG_PRINT(F(", universe="));
DEBUG_PRINT(uni);
DEBUG_PRINTLN(")");
DEBUG_PRINTF_P(PSTR("skipping E1.31 frame (last seq=%d, current seq=%d, universe=%d)\n"), e131LastSequenceNumber[previousUniverses], seq, uni);
return;
}
e131LastSequenceNumber[previousUniverses] = seq;

View File

@ -69,20 +69,20 @@ typedef struct WiFiConfig {
// similar to NeoPixelBus NeoGammaTableMethod but allows dynamic changes (superseded by NPB::NeoGammaDynamicTableMethod)
class NeoGammaWLEDMethod {
public:
static uint8_t Correct(uint8_t value); // apply Gamma to single channel
static uint32_t Correct32(uint32_t color); // apply Gamma to RGBW32 color (WLED specific, not used by NPB)
static void calcGammaTable(float gamma); // re-calculates & fills gamma table
[[gnu::hot]] static uint8_t Correct(uint8_t value); // apply Gamma to single channel
[[gnu::hot]] static uint32_t Correct32(uint32_t color); // apply Gamma to RGBW32 color (WLED specific, not used by NPB)
static void calcGammaTable(float gamma); // re-calculates & fills gamma table
static inline uint8_t rawGamma8(uint8_t val) { return gammaT[val]; } // get value from Gamma table (WLED specific, not used by NPB)
private:
static uint8_t gammaT[];
};
#define gamma32(c) NeoGammaWLEDMethod::Correct32(c)
#define gamma8(c) NeoGammaWLEDMethod::rawGamma8(c)
uint32_t color_blend(uint32_t,uint32_t,uint16_t,bool b16=false);
uint32_t color_add(uint32_t,uint32_t, bool fast=false);
uint32_t color_fade(uint32_t c1, uint8_t amount, bool video=false);
[[gnu::hot]] uint32_t color_blend(uint32_t,uint32_t,uint16_t,bool b16=false);
[[gnu::hot]] uint32_t color_add(uint32_t,uint32_t, bool fast=false);
[[gnu::hot]] uint32_t color_fade(uint32_t c1, uint8_t amount, bool video=false);
CRGBPalette16 generateHarmonicRandomPalette(CRGBPalette16 &basepalette);
CRGBPalette16 generateRandomPalette(void);
CRGBPalette16 generateRandomPalette();
inline uint32_t colorFromRgbw(byte* rgbw) { return uint32_t((byte(rgbw[3]) << 24) | (byte(rgbw[0]) << 16) | (byte(rgbw[1]) << 8) | (byte(rgbw[2]))); }
void colorHStoRGB(uint16_t hue, byte sat, byte* rgb); //hue, sat to rgb
void colorKtoRGB(uint16_t kelvin, byte* rgb);

View File

@ -210,7 +210,7 @@ void sendImprovInfoResponse() {
//Use serverDescription if it has been changed from the default "WLED", else mDNS name
bool useMdnsName = (strcmp(serverDescription, "WLED") == 0 && strlen(cmDNS) > 0);
char vString[20];
sprintf_P(vString, PSTR("0.15.0-b4/%i"), VERSION);
sprintf_P(vString, PSTR("0.15.0-b5/%i"), VERSION);
const char *str[4] = {"WLED", vString, bString, useMdnsName ? cmDNS : serverDescription};
sendImprovRPCResult(ImprovRPCType::Request_Info, 4, str);

View File

@ -1152,11 +1152,8 @@ void serveJson(AsyncWebServerRequest* request)
DEBUG_PRINTF_P(PSTR("JSON buffer size: %u for request: %d\n"), lDoc.memoryUsage(), subJson);
#ifdef WLED_DEBUG
size_t len =
#endif
response->setLength();
DEBUG_PRINT(F("JSON content length: ")); DEBUG_PRINTLN(len);
[[maybe_unused]] size_t len = response->setLength();
DEBUG_PRINTF_P(PSTR("JSON content length: %u\n"), len);
request->send(response);
}

View File

@ -55,8 +55,7 @@ static void onMqttConnect(bool sessionPresent)
static void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
static char *payloadStr;
DEBUG_PRINT(F("MQTT msg: "));
DEBUG_PRINTLN(topic);
DEBUG_PRINTF_P(PSTR("MQTT msg: %s\n"), topic);
// paranoia check to avoid npe if no payload
if (payload==nullptr) {

View File

@ -246,8 +246,7 @@ bool checkNTPResponse()
}
uint32_t ntpPacketReceivedTime = millis();
DEBUG_PRINT(F("NTP recv, l="));
DEBUG_PRINTLN(cb);
DEBUG_PRINTF_P(PSTR("NTP recv, l=%d\n"), cb);
byte pbuf[NTP_PACKET_SIZE];
ntpUdp.read(pbuf, NTP_PACKET_SIZE); // read the packet into the buffer
if (!isValidNtpResponse(pbuf)) return false; // verify we have a valid response to client
@ -493,7 +492,7 @@ void calculateSunriseAndSunset() {
do {
time_t theDay = localTime - retryCount * 86400; // one day back = 86400 seconds
minUTC = getSunriseUTC(year(theDay), month(theDay), day(theDay), latitude, longitude, false);
DEBUG_PRINT(F("* sunrise (minutes from UTC) = ")); DEBUG_PRINTLN(minUTC);
DEBUG_PRINTF_P(PSTR("* sunrise (minutes from UTC) = %d\n"), minUTC);
retryCount ++;
} while ((abs(minUTC) > SUNSET_MAX) && (retryCount <= 3));
@ -512,7 +511,7 @@ void calculateSunriseAndSunset() {
do {
time_t theDay = localTime - retryCount * 86400; // one day back = 86400 seconds
minUTC = getSunriseUTC(year(theDay), month(theDay), day(theDay), latitude, longitude, true);
DEBUG_PRINT(F("* sunset (minutes from UTC) = ")); DEBUG_PRINTLN(minUTC);
DEBUG_PRINTF_P(PSTR("* sunset (minutes from UTC) = %d\n"), minUTC);
retryCount ++;
} while ((abs(minUTC) > SUNSET_MAX) && (retryCount <= 3));

View File

@ -63,7 +63,8 @@ enum struct PinOwner : uint8_t {
UM_PWM_OUTPUTS = USERMOD_ID_PWM_OUTPUTS, // 0x26 // Usermod "usermod_pwm_outputs.h"
UM_LDR_DUSK_DAWN = USERMOD_ID_LDR_DUSK_DAWN, // 0x2B // Usermod "usermod_LDR_Dusk_Dawn_v2.h"
UM_MAX17048 = USERMOD_ID_MAX17048, // 0x2F // Usermod "usermod_max17048.h"
UM_BME68X = USERMOD_ID_BME68X // 0x31 // Usermod "usermod_bme68x.h -- Uses "standard" HW_I2C pins
UM_BME68X = USERMOD_ID_BME68X, // 0x31 // Usermod "usermod_bme68x.h -- Uses "standard" HW_I2C pins
UM_PIXELS_DICE_TRAY = USERMOD_ID_PIXELS_DICE_TRAY, // 0x35 // Usermod "pixels_dice_tray.h" -- Needs compile time specified 6 pins for display including SPI.
};
static_assert(0u == static_cast<uint8_t>(PinOwner::None), "PinOwner::None must be zero, so default array initialization works as expected");

View File

@ -117,8 +117,7 @@ void initPresetsFile()
bool applyPresetFromPlaylist(byte index)
{
DEBUG_PRINT(F("Request to apply preset: "));
DEBUG_PRINTLN(index);
DEBUG_PRINTF_P(PSTR("Request to apply preset: %d\n"), index);
presetToApply = index;
callModeToApply = CALL_MODE_DIRECT_CHANGE;
return true;
@ -127,8 +126,7 @@ bool applyPresetFromPlaylist(byte index)
bool applyPreset(byte index, byte callMode)
{
unloadPlaylist(); // applying a preset unloads the playlist (#3827)
DEBUG_PRINT(F("Request to apply preset: "));
DEBUG_PRINTLN(index);
DEBUG_PRINTF_P(PSTR("Request to apply preset: %u\n"), index);
presetToApply = index;
callModeToApply = callMode;
return true;
@ -163,8 +161,7 @@ void handlePresets()
presetToApply = 0; //clear request for preset
callModeToApply = 0;
DEBUG_PRINT(F("Applying preset: "));
DEBUG_PRINTLN(tmpPreset);
DEBUG_PRINTF_P(PSTR("Applying preset: %u\n"), (unsigned)tmpPreset);
#ifdef ARDUINO_ARCH_ESP32
if (tmpPreset==255 && tmpRAMbuffer!=nullptr) {
@ -222,7 +219,7 @@ void savePreset(byte index, const char* pname, JsonObject sObj)
else sprintf_P(saveName, PSTR("Preset %d"), index);
}
DEBUG_PRINT(F("Saving preset (")); DEBUG_PRINT(index); DEBUG_PRINT(F(") ")); DEBUG_PRINTLN(saveName);
DEBUG_PRINTF_P(PSTR("Saving preset (%d) %s\n"), index, saveName);
presetToSave = index;
playlistSave = false;

View File

@ -25,11 +25,11 @@
typedef struct WizMoteMessageStructure {
uint8_t program; // 0x91 for ON button, 0x81 for all others
uint8_t seq[4]; // Incremetal sequence number 32 bit unsigned integer LSB first
uint8_t byte5; // Unknown (seen 0x20)
uint8_t dt1; // Button Data Type (0x32)
uint8_t button; // Identifies which button is being pressed
uint8_t byte8; // Unknown, but always 0x01
uint8_t byte9; // Unnkown, but always 0x64
uint8_t dt2; // Battery Level Data Type (0x01)
uint8_t batLevel; // Battery Level 0-100
uint8_t byte10; // Unknown, maybe checksum
uint8_t byte11; // Unknown, maybe checksum
uint8_t byte12; // Unknown, maybe checksum
@ -186,8 +186,7 @@ void handleRemote(uint8_t *incomingData, size_t len) {
}
if (len != sizeof(message_structure_t)) {
DEBUG_PRINT(F("Unknown incoming ESP Now message received of length "));
DEBUG_PRINTLN(len);
DEBUG_PRINTF_P(PSTR("Unknown incoming ESP Now message received of length %u\n"), len);
return;
}
@ -225,4 +224,4 @@ void handleRemote(uint8_t *incomingData, size_t len) {
#else
void handleRemote(uint8_t *incomingData, size_t len) {}
#endif
#endif

View File

@ -157,8 +157,7 @@ void handleSettingsSet(AsyncWebServerRequest *request, byte subPage)
char la[4] = "LA"; la[2] = offset+s; la[3] = 0; //LED mA
char ma[4] = "MA"; ma[2] = offset+s; ma[3] = 0; //max mA
if (!request->hasArg(lp)) {
DEBUG_PRINT(F("No data for "));
DEBUG_PRINTLN(s);
DEBUG_PRINTF_P(PSTR("No data for %d\n"), s);
break;
}
for (int i = 0; i < 5; i++) {
@ -289,7 +288,7 @@ void handleSettingsSet(AsyncWebServerRequest *request, byte subPage)
#ifdef SOC_TOUCH_VERSION_2 // ESP32 S2 and S3 have a fucntion to check touch state but need to attach an interrupt to do so
else
{
touchAttachInterrupt(btnPin[i], touchButtonISR, 256 + (touchThreshold << 4)); // threshold on Touch V2 is much higher (1500 is a value given by Espressif example, I measured changes of over 5000)
touchAttachInterrupt(btnPin[i], touchButtonISR, touchThreshold << 4); // threshold on Touch V2 is much higher (1500 is a value given by Espressif example, I measured changes of over 5000)
}
#endif
}
@ -726,7 +725,7 @@ void handleSettingsSet(AsyncWebServerRequest *request, byte subPage)
else subObj[name].add(value.toInt()); // we may have an int
j++;
}
DEBUG_PRINT(F("[")); DEBUG_PRINT(j); DEBUG_PRINT(F("] = ")); DEBUG_PRINTLN(value);
DEBUG_PRINTF_P(PSTR("[%d] = %s\n"), j, value.c_str());
} else {
// we are using a hidden field with the same name as our parameter (!before the actual parameter!)
// to describe the type of parameter (text,float,int), for boolean parameters the first field contains "off"
@ -745,7 +744,7 @@ void handleSettingsSet(AsyncWebServerRequest *request, byte subPage)
} else if (type == "int") subObj[name] = value.toInt();
else subObj[name] = value; // text fields
}
DEBUG_PRINT(F(" = ")); DEBUG_PRINTLN(value);
DEBUG_PRINTF_P(PSTR(" = %s\n"), value.c_str());
}
}
usermods.readFromConfig(um); // force change of usermod parameters
@ -806,8 +805,7 @@ bool handleSet(AsyncWebServerRequest *request, const String& req, bool apply)
if (!(req.indexOf("win") >= 0)) return false;
int pos = 0;
DEBUG_PRINT(F("API req: "));
DEBUG_PRINTLN(req);
DEBUG_PRINTF_P(PSTR("API req: %s\n"), req.c_str());
//segment select (sets main segment)
pos = req.indexOf(F("SM="));

View File

@ -155,7 +155,7 @@ class Toki {
return (tick == TickT::active);
}
void printTime(const Time& t) {
Serial.printf_P(PSTR("%u,%03u\n"),t.sec,t.ms);
void printTime(const Time& t, Print &dest = Serial) {
dest.printf_P(PSTR("%u,%03u\n"),t.sec,t.ms);
}
};

View File

@ -213,7 +213,7 @@ void parseNotifyPacket(uint8_t *udpIn) {
//compatibilityVersionByte:
byte version = udpIn[11];
DEBUG_PRINT(F("UDP packet version: ")); DEBUG_PRINTLN(version);
DEBUG_PRINTF_P(PSTR("UDP packet version: %d\n"), (int)version);
// if we are not part of any sync group ignore message
if (version < 9) {
@ -254,7 +254,7 @@ void parseNotifyPacket(uint8_t *udpIn) {
if (applyEffects && currentPlaylist >= 0) unloadPlaylist();
if (version > 10 && (receiveSegmentOptions || receiveSegmentBounds)) {
unsigned numSrcSegs = udpIn[39];
DEBUG_PRINT(F("UDP segments: ")); DEBUG_PRINTLN(numSrcSegs);
DEBUG_PRINTF_P(PSTR("UDP segments: %d\n"), numSrcSegs);
// are we syncing bounds and slave has more active segments than master?
if (receiveSegmentBounds && numSrcSegs < strip.getActiveSegmentsNum()) {
DEBUG_PRINTLN(F("Removing excessive segments."));
@ -268,13 +268,13 @@ void parseNotifyPacket(uint8_t *udpIn) {
for (size_t i = 0; i < numSrcSegs && i < strip.getMaxSegments(); i++) {
unsigned ofs = 41 + i*udpIn[40]; //start of segment offset byte
unsigned id = udpIn[0 +ofs];
DEBUG_PRINT(F("UDP segment received: ")); DEBUG_PRINTLN(id);
DEBUG_PRINTF_P(PSTR("UDP segment received: %u\n"), id);
if (id > strip.getSegmentsNum()) break;
else if (id == strip.getSegmentsNum()) {
if (receiveSegmentBounds && id < strip.getMaxSegments()) strip.appendSegment();
else break;
}
DEBUG_PRINT(F("UDP segment check: ")); DEBUG_PRINTLN(id);
DEBUG_PRINTF_P(PSTR("UDP segment check: %u\n"), id);
Segment& selseg = strip.getSegment(id);
// if we are not syncing bounds skip unselected segments
if (selseg.isActive() && !(selseg.isSelected() || receiveSegmentBounds)) continue;
@ -288,7 +288,7 @@ void parseNotifyPacket(uint8_t *udpIn) {
id += inactiveSegs; // adjust id
}
}
DEBUG_PRINT(F("UDP segment processing: ")); DEBUG_PRINTLN(id);
DEBUG_PRINTF_P(PSTR("UDP segment processing: %u\n"), id);
uint16_t start = (udpIn[1+ofs] << 8 | udpIn[2+ofs]);
uint16_t stop = (udpIn[3+ofs] << 8 | udpIn[4+ofs]);
@ -305,14 +305,14 @@ void parseNotifyPacket(uint8_t *udpIn) {
selseg.options = (selseg.options & 0x0071U) | (udpIn[9 +ofs] & 0x0E); // ignore selected, freeze, reset & transitional
selseg.setOpacity(udpIn[10+ofs]);
if (applyEffects) {
DEBUG_PRINT(F("Apply effect: ")); DEBUG_PRINTLN(id);
DEBUG_PRINTF_P(PSTR("Apply effect: %u\n"), id);
selseg.setMode(udpIn[11+ofs]);
selseg.speed = udpIn[12+ofs];
selseg.intensity = udpIn[13+ofs];
selseg.palette = udpIn[14+ofs];
}
if (receiveNotificationColor || !someSel) {
DEBUG_PRINT(F("Apply color: ")); DEBUG_PRINTLN(id);
DEBUG_PRINTF_P(PSTR("Apply color: %u\n"), id);
selseg.setColor(0, RGBW32(udpIn[15+ofs],udpIn[16+ofs],udpIn[17+ofs],udpIn[18+ofs]));
selseg.setColor(1, RGBW32(udpIn[19+ofs],udpIn[20+ofs],udpIn[21+ofs],udpIn[22+ofs]));
selseg.setColor(2, RGBW32(udpIn[23+ofs],udpIn[24+ofs],udpIn[25+ofs],udpIn[26+ofs]));
@ -322,10 +322,10 @@ void parseNotifyPacket(uint8_t *udpIn) {
// when applying synced options ignore selected as it may be used as indicator of which segments to sync
// freeze, reset should never be synced
// LSB to MSB: select, reverse, on, mirror, freeze, reset, reverse_y, mirror_y, transpose, map1d2d (3), ssim (2), set (2)
DEBUG_PRINT(F("Apply options: ")); DEBUG_PRINTLN(id);
DEBUG_PRINTF_P(PSTR("Apply options: %u\n"), id);
selseg.options = (selseg.options & 0b0000000000110001U) | (udpIn[28+ofs]<<8) | (udpIn[9 +ofs] & 0b11001110U); // ignore selected, freeze, reset
if (applyEffects) {
DEBUG_PRINT(F("Apply sliders: ")); DEBUG_PRINTLN(id);
DEBUG_PRINTF_P(PSTR("Apply sliders: %u\n"), id);
selseg.custom1 = udpIn[29+ofs];
selseg.custom2 = udpIn[30+ofs];
selseg.custom3 = udpIn[31+ofs] & 0x1F;
@ -559,7 +559,7 @@ void handleNotifications()
//wled notifier, ignore if realtime packets active
if (udpIn[0] == 0 && !realtimeMode && receiveGroups)
{
DEBUG_PRINT(F("UDP notification from: ")); DEBUG_PRINTLN(notifierUdp.remoteIP());
DEBUG_PRINTF_P(PSTR("UDP notification from: %d.%d.%d.%d\n"), notifierUdp.remoteIP()[0], notifierUdp.remoteIP()[1], notifierUdp.remoteIP()[2], notifierUdp.remoteIP()[3]);
parseNotifyPacket(udpIn);
return;
}

View File

@ -106,6 +106,10 @@
#include "../usermods/ST7789_display/ST7789_Display.h"
#endif
#ifdef USERMOD_PIXELS_DICE_TRAY
#include "../usermods/pixels_dice_tray/pixels_dice_tray.h"
#endif
#ifdef USERMOD_SEVEN_SEGMENT
#include "../usermods/seven_segment_display/usermod_v2_seven_segment_display.h"
#endif
@ -210,6 +214,10 @@
#include "../usermods/LDR_Dusk_Dawn_v2/usermod_LDR_Dusk_Dawn_v2.h"
#endif
#ifdef USERMOD_POV_DISPLAY
#include "../usermods/pov_display/usermod_pov_display.h"
#endif
#ifdef USERMOD_STAIRCASE_WIPE
#include "../usermods/stairway_wipe_basic/stairway-wipe-usermod-v2.h"
#endif
@ -331,6 +339,10 @@ void registerUsermods()
usermods.add(new St7789DisplayUsermod());
#endif
#ifdef USERMOD_PIXELS_DICE_TRAY
usermods.add(new PixelsDiceTrayUsermod());
#endif
#ifdef USERMOD_SEVEN_SEGMENT
usermods.add(new SevenSegmentDisplay());
#endif
@ -454,4 +466,8 @@ void registerUsermods()
#ifdef USERMOD_LD2410
usermods.add(new LD2410Usermod());
#endif
#ifdef USERMOD_POV_DISPLAY
usermods.add(new PovDisplayUsermod());
#endif
}

View File

@ -159,7 +159,7 @@ void WLED::loop()
if (millis() - heapTime > 15000) {
uint32_t heap = ESP.getFreeHeap();
if (heap < MIN_HEAP_SIZE && lastHeap < MIN_HEAP_SIZE) {
DEBUG_PRINT(F("Heap too low! ")); DEBUG_PRINTLN(heap);
DEBUG_PRINTF_P(PSTR("Heap too low! %u\n"), heap);
forceReconnect = true;
strip.resetSegments(); // remove all but one segments from memory
} else if (heap < MIN_HEAP_SIZE) {
@ -264,9 +264,9 @@ void WLED::loop()
if (loopMillis > maxLoopMillis) maxLoopMillis = loopMillis;
if (millis() - debugTime > 29999) {
DEBUG_PRINTLN(F("---DEBUG INFO---"));
DEBUG_PRINT(F("Runtime: ")); DEBUG_PRINTLN(millis());
DEBUG_PRINT(F("Unix time: ")); toki.printTime(toki.getTime());
DEBUG_PRINT(F("Free heap: ")); DEBUG_PRINTLN(ESP.getFreeHeap());
DEBUG_PRINTF_P(PSTR("Runtime: %u\n"), millis());
DEBUG_PRINTF_P(PSTR("Unix time: %u,%03u\n"), toki.getTime().sec, toki.getTime().ms);
DEBUG_PRINTF_P(PSTR("Free heap: %u\n"), ESP.getFreeHeap());
#if defined(ARDUINO_ARCH_ESP32)
if (psramFound()) {
DEBUG_PRINTF_P(PSTR("PSRAM: %dkB/%dkB\n"), ESP.getFreePsram()/1024, ESP.getPsramSize()/1024);
@ -276,21 +276,21 @@ void WLED::loop()
#endif
DEBUG_PRINTF_P(PSTR("Wifi state: %d\n"), WiFi.status());
#ifndef WLED_DISABLE_ESPNOW
DEBUG_PRINT(F("ESP-NOW state: ")); DEBUG_PRINTLN(statusESPNow);
DEBUG_PRINTF_P(PSTR("ESP-NOW state: %u\n"), statusESPNow);
#endif
if (WiFi.status() != lastWifiState) {
wifiStateChangedTime = millis();
}
lastWifiState = WiFi.status();
DEBUG_PRINT(F("State time: ")); DEBUG_PRINTLN(wifiStateChangedTime);
DEBUG_PRINT(F("NTP last sync: ")); DEBUG_PRINTLN(ntpLastSyncTime);
DEBUG_PRINT(F("Client IP: ")); DEBUG_PRINTLN(Network.localIP());
DEBUG_PRINTF_P(PSTR("State time: %u\n"), wifiStateChangedTime);
DEBUG_PRINTF_P(PSTR("NTP last sync: %u\n"), ntpLastSyncTime);
DEBUG_PRINTF_P(PSTR("Client IP: %u.%u.%u.%u\n"), Network.localIP()[0], Network.localIP()[1], Network.localIP()[2], Network.localIP()[3]);
if (loops > 0) { // avoid division by zero
DEBUG_PRINT(F("Loops/sec: ")); DEBUG_PRINTLN(loops / 30);
DEBUG_PRINT(F("Loop time[ms]: ")); DEBUG_PRINT(avgLoopMillis/loops); DEBUG_PRINT("/");DEBUG_PRINTLN(maxLoopMillis);
DEBUG_PRINT(F("UM time[ms]: ")); DEBUG_PRINT(avgUsermodMillis/loops); DEBUG_PRINT("/");DEBUG_PRINTLN(maxUsermodMillis);
DEBUG_PRINT(F("Strip time[ms]: ")); DEBUG_PRINT(avgStripMillis/loops); DEBUG_PRINT("/"); DEBUG_PRINTLN(maxStripMillis);
DEBUG_PRINTF_P(PSTR("Loops/sec: %u\n"), loops / 30);
DEBUG_PRINTF_P(PSTR("Loop time[ms]: %u/%u\n"), avgLoopMillis/loops, maxLoopMillis);
DEBUG_PRINTF_P(PSTR("UM time[ms]: %u/%u\n"), avgUsermodMillis/loops, maxUsermodMillis);
DEBUG_PRINTF_P(PSTR("Strip time[ms]:%u/%u\n"), avgStripMillis/loops, maxStripMillis);
}
strip.printSize();
loops = 0;
@ -358,45 +358,38 @@ void WLED::setup()
Serial.setDebugOutput(false); // switch off kernel messages when using USBCDC
#endif
DEBUG_PRINTLN();
DEBUG_PRINT(F("---WLED "));
DEBUG_PRINT(versionString);
DEBUG_PRINT(F(" "));
DEBUG_PRINT(VERSION);
DEBUG_PRINTLN(F(" INIT---"));
DEBUG_PRINTF_P(PSTR("---WLED %s %u INIT---\n"), versionString, VERSION);
DEBUG_PRINTLN();
#ifdef ARDUINO_ARCH_ESP32
DEBUG_PRINT(F("esp32 "));
DEBUG_PRINTLN(ESP.getSdkVersion());
DEBUG_PRINTF_P(PSTR("esp32 %s\n"), ESP.getSdkVersion());
#if defined(ESP_ARDUINO_VERSION)
//DEBUG_PRINTF_P(PSTR("arduino-esp32 0x%06x\n"), ESP_ARDUINO_VERSION);
DEBUG_PRINTF_P(PSTR("arduino-esp32 v%d.%d.%d\n"), int(ESP_ARDUINO_VERSION_MAJOR), int(ESP_ARDUINO_VERSION_MINOR), int(ESP_ARDUINO_VERSION_PATCH)); // availeable since v2.0.0
DEBUG_PRINTF_P(PSTR("arduino-esp32 v%d.%d.%d\n"), int(ESP_ARDUINO_VERSION_MAJOR), int(ESP_ARDUINO_VERSION_MINOR), int(ESP_ARDUINO_VERSION_PATCH)); // available since v2.0.0
#else
DEBUG_PRINTLN(F("arduino-esp32 v1.0.x\n")); // we can't say in more detail.
#endif
DEBUG_PRINT(F("CPU: ")); DEBUG_PRINT(ESP.getChipModel());
DEBUG_PRINT(F(" rev.")); DEBUG_PRINT(ESP.getChipRevision());
DEBUG_PRINT(F(", ")); DEBUG_PRINT(ESP.getChipCores()); DEBUG_PRINT(F(" core(s)"));
DEBUG_PRINT(F(", ")); DEBUG_PRINT(ESP.getCpuFreqMHz()); DEBUG_PRINTLN(F("MHz."));
DEBUG_PRINT(F("FLASH: ")); DEBUG_PRINT((ESP.getFlashChipSize()/1024)/1024);
DEBUG_PRINT(F("MB, Mode ")); DEBUG_PRINT(ESP.getFlashChipMode());
DEBUG_PRINTF_P(PSTR("CPU: "), ESP.getChipModel());
DEBUG_PRINTF_P(PSTR(" rev."), ESP.getChipRevision());
DEBUG_PRINTF_P(PSTR(", %d core(s)"), ESP.getChipCores());
DEBUG_PRINTF_P(PSTR(", %d MHz.\n"), ESP.getCpuFreqMHz());
DEBUG_PRINTF_P(PSTR("FLASH: %dMB, Mode %d "), (ESP.getFlashChipSize()/1024)/1024, ESP.getFlashChipMode());
#ifdef WLED_DEBUG
switch (ESP.getFlashChipMode()) {
// missing: Octal modes
case FM_QIO: DEBUG_PRINT(F(" (QIO)")); break;
case FM_QOUT: DEBUG_PRINT(F(" (QOUT)"));break;
case FM_DIO: DEBUG_PRINT(F(" (DIO)")); break;
case FM_DOUT: DEBUG_PRINT(F(" (DOUT)"));break;
case FM_QIO: DEBUG_PRINT(F("(QIO)")); break;
case FM_QOUT: DEBUG_PRINT(F("(QOUT)"));break;
case FM_DIO: DEBUG_PRINT(F("(DIO)")); break;
case FM_DOUT: DEBUG_PRINT(F("(DOUT)"));break;
default: break;
}
#endif
DEBUG_PRINT(F(", speed ")); DEBUG_PRINT(ESP.getFlashChipSpeed()/1000000);DEBUG_PRINTLN(F("MHz."));
DEBUG_PRINTF_P(PSTR(", speed %u MHz.\n"), ESP.getFlashChipSpeed()/1000000);
#else
DEBUG_PRINT(F("esp8266 @ ")); DEBUG_PRINT(ESP.getCpuFreqMHz()); DEBUG_PRINT(F("MHz.\nCore: "));
DEBUG_PRINTLN(ESP.getCoreVersion());
DEBUG_PRINT(F("FLASH: ")); DEBUG_PRINT((ESP.getFlashChipSize()/1024)/1024); DEBUG_PRINTLN(F(" MB"));
DEBUG_PRINTF_P(PSTR("esp8266 @ %u MHz.\nCore: %s\n"), ESP.getCpuFreqMHz(), ESP.getCoreVersion());
DEBUG_PRINTF_P(PSTR("FLASH: %u MB\n"), (ESP.getFlashChipSize()/1024)/1024);
#endif
DEBUG_PRINT(F("heap ")); DEBUG_PRINTLN(ESP.getFreeHeap());
DEBUG_PRINTF_P(PSTR("heap %u\n"), ESP.getFreeHeap());
#if defined(ARDUINO_ARCH_ESP32)
// BOARD_HAS_PSRAM also means that a compiler flag "-mfix-esp32-psram-cache-issue" was used and so PSRAM is safe to use on rev.1 ESP32
@ -405,7 +398,7 @@ void WLED::setup()
if (!psramSafe) DEBUG_PRINTLN(F("Not using PSRAM."));
#endif
pDoc = new PSRAMDynamicJsonDocument((psramSafe && psramFound() ? 2 : 1)*JSON_BUFFER_SIZE);
DEBUG_PRINT(F("JSON buffer allocated: ")); DEBUG_PRINTLN((psramSafe && psramFound() ? 2 : 1)*JSON_BUFFER_SIZE);
DEBUG_PRINTF_P(PSTR("JSON buffer allocated: %u\n"), (psramSafe && psramFound() ? 2 : 1)*JSON_BUFFER_SIZE);
// if the above fails requestJsonBufferLock() will always return false preventing crashes
if (psramFound()) {
DEBUG_PRINTF_P(PSTR("PSRAM: %dkB/%dkB\n"), ESP.getFreePsram()/1024, ESP.getPsramSize()/1024);
@ -427,7 +420,7 @@ void WLED::setup()
DEBUG_PRINTLN(F("Registering usermods ..."));
registerUsermods();
DEBUG_PRINT(F("heap ")); DEBUG_PRINTLN(ESP.getFreeHeap());
DEBUG_PRINTF_P(PSTR("heap %u\n"), ESP.getFreeHeap());
bool fsinit = false;
DEBUGFS_PRINTLN(F("Mount FS"));
@ -457,7 +450,7 @@ void WLED::setup()
DEBUG_PRINTLN(F("Reading config"));
deserializeConfigFromFS();
DEBUG_PRINT(F("heap ")); DEBUG_PRINTLN(ESP.getFreeHeap());
DEBUG_PRINTF_P(PSTR("heap %u\n"), ESP.getFreeHeap());
#if defined(STATUSLED) && STATUSLED>=0
if (!pinManager.isPinAllocated(STATUSLED)) {
@ -469,12 +462,12 @@ void WLED::setup()
DEBUG_PRINTLN(F("Initializing strip"));
beginStrip();
DEBUG_PRINT(F("heap ")); DEBUG_PRINTLN(ESP.getFreeHeap());
DEBUG_PRINTF_P(PSTR("heap %u\n"), ESP.getFreeHeap());
DEBUG_PRINTLN(F("Usermods setup"));
userSetup();
usermods.setup();
DEBUG_PRINT(F("heap ")); DEBUG_PRINTLN(ESP.getFreeHeap());
DEBUG_PRINTF_P(PSTR("heap %u\n"), ESP.getFreeHeap());
if (strcmp(multiWiFi[0].clientSSID, DEFAULT_CLIENT_SSID) == 0)
showWelcomePage = true;
@ -537,13 +530,13 @@ void WLED::setup()
// HTTP server page init
DEBUG_PRINTLN(F("initServer"));
initServer();
DEBUG_PRINT(F("heap ")); DEBUG_PRINTLN(ESP.getFreeHeap());
DEBUG_PRINTF_P(PSTR("heap %u\n"), ESP.getFreeHeap());
#ifndef WLED_DISABLE_INFRARED
// init IR
DEBUG_PRINTLN(F("initIR"));
initIR();
DEBUG_PRINT(F("heap ")); DEBUG_PRINTLN(ESP.getFreeHeap());
DEBUG_PRINTF_P(PSTR("heap %u\n"), ESP.getFreeHeap());
#endif
// Seed FastLED random functions with an esp random value, which already works properly at this point.
@ -654,11 +647,11 @@ bool WLED::initEthernet()
return false;
}
if (ethernetType >= WLED_NUM_ETH_TYPES) {
DEBUG_PRINT(F("initE: Ignoring attempt for invalid ethernetType ")); DEBUG_PRINTLN(ethernetType);
DEBUG_PRINTF_P(PSTR("initE: Ignoring attempt for invalid ethernetType (%d)\n"), ethernetType);
return false;
}
DEBUG_PRINT(F("initE: Attempting ETH config: ")); DEBUG_PRINTLN(ethernetType);
DEBUG_PRINTF_P(PSTR("initE: Attempting ETH config: %d\n"), ethernetType);
// Ethernet initialization should only succeed once -- else reboot required
ethernet_settings es = ethernetBoards[ethernetType];
@ -689,9 +682,7 @@ bool WLED::initEthernet()
pinsToAllocate[9].pin = 17;
pinsToAllocate[9].isOutput = true;
} else {
DEBUG_PRINT(F("initE: Failing due to invalid eth_clk_mode ("));
DEBUG_PRINT(es.eth_clk_mode);
DEBUG_PRINTLN(")");
DEBUG_PRINTF_P(PSTR("initE: Failing due to invalid eth_clk_mode (%d)\n"), es.eth_clk_mode);
return false;
}

View File

@ -3,12 +3,12 @@
/*
Main sketch, global variable declarations
@title WLED project sketch
@version 0.15.0-b4
@version 0.15.0-b5
@author Christian Schwinne
*/
// version code in format yymmddb (b = daily build)
#define VERSION 2407070
#define VERSION 2409100
//uncomment this if you have a "my_config.h" file you'd like to use
//#define WLED_USE_MY_CONFIG
@ -36,7 +36,7 @@
#undef WLED_ENABLE_ADALIGHT // disable has priority over enable
#endif
//#define WLED_ENABLE_DMX // uses 3.5kb (use LEDPIN other than 2)
#define WLED_ENABLE_JSONLIVE // peek LED output via /json/live (WS binary peek is always enabled)
//#define WLED_ENABLE_JSONLIVE // peek LED output via /json/live (WS binary peek is always enabled)
#ifndef WLED_DISABLE_LOXONE
#define WLED_ENABLE_LOXONE // uses 1.2kb
#endif
@ -331,7 +331,7 @@ typedef class WiFiOptions {
struct {
uint8_t selectedWiFi : 4; // max 16 SSIDs
uint8_t apChannel : 4;
bool apHide : 1;
uint8_t apHide : 3;
uint8_t apBehavior : 3;
bool noWifiSleep : 1;
bool force802_3g : 1;

View File

@ -163,8 +163,7 @@ static void handleUpload(AsyncWebServerRequest *request, const String& filename,
}
request->_tempFile = WLED_FS.open(finalname, "w");
DEBUG_PRINT(F("Uploading "));
DEBUG_PRINTLN(finalname);
DEBUG_PRINTF_P(PSTR("Uploading %s\n"), finalname.c_str());
if (finalname.equals(FPSTR(getPresetsFileName()))) presetsModifiedTime = toki.second();
}
if (len) {
@ -466,7 +465,7 @@ void initServer()
//called when the url is not defined here, ajax-in; get-settings
server.onNotFound([](AsyncWebServerRequest *request){
DEBUG_PRINT(F("Not-Found HTTP call: ")); DEBUG_PRINTLN(request->url());
DEBUG_PRINTF_P(PSTR("Not-Found HTTP call: %s\n"), request->url().c_str());
if (captivePortal(request)) return;
//make API CORS compatible

View File

@ -96,6 +96,8 @@ void wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventTyp
//pong message was received (in response to a ping request maybe)
DEBUG_PRINTLN(F("WS pong."));
} else {
DEBUG_PRINTLN(F("WS unknown event."));
}
}
@ -104,10 +106,11 @@ void sendDataWs(AsyncWebSocketClient * client)
if (!ws.count()) return;
if (!requestJSONBufferLock(12)) {
const char* error = PSTR("{\"error\":3}");
if (client) {
client->text(F("{\"error\":3}")); // ERR_NOBUF
client->text(FPSTR(error)); // ERR_NOBUF
} else {
ws.textAll(F("{\"error\":3}")); // ERR_NOBUF
ws.textAll(FPSTR(error)); // ERR_NOBUF
}
return;
}
@ -120,8 +123,9 @@ void sendDataWs(AsyncWebSocketClient * client)
size_t len = measureJson(*pDoc);
DEBUG_PRINTF_P(PSTR("JSON buffer size: %u for WS request (%u).\n"), pDoc->memoryUsage(), len);
// the following may no longer be necessary as heap management has been fixed by @willmmiles in AWS
size_t heap1 = ESP.getFreeHeap();
DEBUG_PRINT(F("heap ")); DEBUG_PRINTLN(ESP.getFreeHeap());
DEBUG_PRINTF_P(PSTR("heap %u\n"), ESP.getFreeHeap());
#ifdef ESP8266
if (len>heap1) {
DEBUG_PRINTLN(F("Out of memory (WS)!"));
@ -131,7 +135,7 @@ void sendDataWs(AsyncWebSocketClient * client)
AsyncWebSocketBuffer buffer(len);
#ifdef ESP8266
size_t heap2 = ESP.getFreeHeap();
DEBUG_PRINT(F("heap ")); DEBUG_PRINTLN(ESP.getFreeHeap());
DEBUG_PRINTF_P(PSTR("heap %u\n"), ESP.getFreeHeap());
#else
size_t heap2 = 0; // ESP32 variants do not have the same issue and will work without checking heap allocation
#endif
@ -146,11 +150,11 @@ void sendDataWs(AsyncWebSocketClient * client)
DEBUG_PRINT(F("Sending WS data "));
if (client) {
client->text(std::move(buffer));
DEBUG_PRINTLN(F("to a single client."));
client->text(std::move(buffer));
} else {
ws.textAll(std::move(buffer));
DEBUG_PRINTLN(F("to multiple clients."));
ws.textAll(std::move(buffer));
}
releaseJSONBufferLock();

View File

@ -224,8 +224,7 @@ void appendGPIOinfo() {
void getSettingsJS(byte subPage, char* dest)
{
//0: menu 1: wifi 2: leds 3: ui 4: sync 5: time 6: sec
DEBUG_PRINT(F("settings resp"));
DEBUG_PRINTLN(subPage);
DEBUG_PRINTF_P(PSTR("settings resp %u\n"), (unsigned)subPage);
obuf = dest;
olen = 0;