Compare commits
185 Commits
v0.15.0-b3
...
v0.15.0-b5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3a5eb8c5d2 | ||
|
|
fd00e5eaae | ||
|
|
20444ee7d5 | ||
|
|
340a9f8b76 | ||
|
|
81cec6a25a | ||
|
|
0642b17ab0 | ||
|
|
b9080f9479 | ||
|
|
c1c707c77a | ||
|
|
cb22e1933e | ||
|
|
e4d5d77347 | ||
|
|
dd52124765 | ||
|
|
0bbd6b7c4b | ||
|
|
1cc47b02cf | ||
|
|
e7babc071d | ||
|
|
d11ca2e159 | ||
|
|
2d6365dc6a | ||
|
|
cc24119a59 | ||
|
|
b8f15333d8 | ||
|
|
e5a426419c | ||
|
|
8a1df1e700 | ||
|
|
cc298f56e2 | ||
|
|
665693a513 | ||
|
|
c35e82e59f | ||
|
|
72d38f4cff | ||
|
|
f6c47ac19c | ||
|
|
27bec89386 | ||
|
|
79b3ce141c | ||
|
|
8d00e4d31d | ||
|
|
8688777ae1 | ||
|
|
198aceee07 | ||
|
|
ee1bf1c221 | ||
|
|
24ecf1a166 | ||
|
|
5cb49c86a0 | ||
|
|
9940d2590b | ||
|
|
577fce69e2 | ||
|
|
e68375a71e | ||
|
|
fe7fb6c7a9 | ||
|
|
cec67d8eff | ||
|
|
2443e2ec7c | ||
|
|
bcf862044a | ||
|
|
b73f049484 | ||
|
|
cde5314d41 | ||
|
|
ed5eb28228 | ||
|
|
db5e66a9b0 | ||
|
|
96c7716d3e | ||
|
|
ea80c1ed83 | ||
|
|
7d7b7c1e25 | ||
|
|
9d860c265c | ||
|
|
d234b4b0f1 | ||
|
|
e82f38e277 | ||
|
|
1d27aa2f18 | ||
|
|
113dbbdf94 | ||
|
|
e701b5b5eb | ||
|
|
6f01896d04 | ||
|
|
5582bbac60 | ||
|
|
d2401a212a | ||
|
|
52548542d2 | ||
|
|
509cbdf476 | ||
|
|
5a6ebd6657 | ||
|
|
541d3f286a | ||
|
|
0191af412b | ||
|
|
abcd2a2d01 | ||
|
|
91efcb910b | ||
|
|
e9b7320d1c | ||
|
|
779744bd8e | ||
|
|
1123d85fd2 | ||
|
|
5c247d2833 | ||
|
|
17fdb4f5c9 | ||
|
|
ef8f23ce90 | ||
|
|
050f7ebddf | ||
|
|
10fdf46410 | ||
|
|
49976ae35a | ||
|
|
21afb05409 | ||
|
|
0af1ec3bde | ||
|
|
343d766ddd | ||
|
|
02cae2e61e | ||
|
|
42decbddd9 | ||
|
|
b71467b9be | ||
|
|
ac503ef72e | ||
|
|
ea608cecb0 | ||
|
|
2e266ec945 | ||
|
|
bec1adf7ad | ||
|
|
2fc2f47d06 | ||
|
|
3a8e19d1b4 | ||
|
|
cc9db0220c | ||
|
|
cd1ede38a7 | ||
|
|
1ec68c428a | ||
|
|
f6ed3bc9db | ||
|
|
34cdda2e28 | ||
|
|
4ab2c907f5 | ||
|
|
8632d99341 | ||
|
|
efa32ed4f6 | ||
|
|
551b8af76d | ||
|
|
887254f5da | ||
|
|
5874b78349 | ||
|
|
a812fc07f2 | ||
|
|
78e7312adf | ||
|
|
693bf4816b | ||
|
|
b8b11880b0 | ||
|
|
0ff4016250 | ||
|
|
e753f3849e | ||
|
|
7b248c8fb2 | ||
|
|
f0e4dd90ee | ||
|
|
c540ec5417 | ||
|
|
3615ab535b | ||
|
|
b8d6ebe882 | ||
|
|
1f27872294 | ||
|
|
3815516022 | ||
|
|
a1dfdced31 | ||
|
|
ff39a8db3f | ||
|
|
9877e899e0 | ||
|
|
bc4a6138b1 | ||
|
|
f825cab54a | ||
|
|
57b01c2711 | ||
|
|
5f3e3d7796 | ||
|
|
d13b8c8421 | ||
|
|
0af3063127 | ||
|
|
17e1975dd8 | ||
|
|
166eeacab9 | ||
|
|
017169f1a1 | ||
|
|
ed0e73803f | ||
|
|
f4475b9d2a | ||
|
|
8a1df9afee | ||
|
|
9cfb56d9c6 | ||
|
|
25ade86994 | ||
|
|
c10ec2962b | ||
|
|
1bb06106fd | ||
|
|
bc18cdbeea | ||
|
|
67df5d6dcc | ||
|
|
68a7282b27 | ||
|
|
5732b66c5a | ||
|
|
f1cce8ef46 | ||
|
|
e47932c9aa | ||
|
|
3a70fb0e15 | ||
|
|
d5da84dcb2 | ||
|
|
1bd051d703 | ||
|
|
abb55f8e4b | ||
|
|
46f6a257d0 | ||
|
|
97e4eec5be | ||
|
|
69b99abb7d | ||
|
|
08f6d5a683 | ||
|
|
627bea30ed | ||
|
|
caf0a5bbe8 | ||
|
|
501f988b0f | ||
|
|
5f0c6fce74 | ||
|
|
78089107b7 | ||
|
|
f3b0906cea | ||
|
|
9f581c6181 | ||
|
|
31b232d3f3 | ||
|
|
77e6a6de61 | ||
|
|
85702a8142 | ||
|
|
0bcdc9641d | ||
|
|
bfd1bdfc64 | ||
|
|
c1fed6d469 | ||
|
|
79ffe021e4 | ||
|
|
a1c348b365 | ||
|
|
904b1f114b | ||
|
|
63f481d498 | ||
|
|
fc5c19788e | ||
|
|
56e0bde8ab | ||
|
|
db2cdca71b | ||
|
|
faa2fba6b9 | ||
|
|
f727ea2874 | ||
|
|
4a7ef07089 | ||
|
|
0df726cdab | ||
|
|
2f6f0d2f3e | ||
|
|
075c164407 | ||
|
|
dcb5049f97 | ||
|
|
d24cf14009 | ||
|
|
3d34802ab2 | ||
|
|
19ccff9ff1 | ||
|
|
1dd9c6754c | ||
|
|
f9467ceaf1 | ||
|
|
f51da4f0c4 | ||
|
|
2eff389fff | ||
|
|
74e273274c | ||
|
|
02bf5902f0 | ||
|
|
f71d839009 | ||
|
|
68f6b3452e | ||
|
|
6b8d8bf735 | ||
|
|
cec7241986 | ||
|
|
6de77293ad | ||
|
|
0ac53d8353 | ||
|
|
c8a7d44f55 | ||
|
|
1bdf3876fc |
@@ -12,6 +12,21 @@
|
||||
}
|
||||
},
|
||||
|
||||
// To give the container access to a device serial port, you can uncomment one of the following lines.
|
||||
// Note: If running on Windows, you will have to do some additional steps:
|
||||
// https://stackoverflow.com/questions/68527888/how-can-i-use-a-usb-com-port-inside-of-a-vscode-development-container
|
||||
//
|
||||
// You can explicitly just forward the port you want to connect to. Replace `/dev/ttyACM0` with the serial port for
|
||||
// your device. This will only work if the device is plugged in from the start without reconnecting. Adding the
|
||||
// `dialout` group is needed if read/write permisions for the port are limitted to the dialout user.
|
||||
// "runArgs": ["--device=/dev/ttyACM0", "--group-add", "dialout"],
|
||||
//
|
||||
// Alternatively, you can give more comprehensive access to the host system. This will expose all the host devices to
|
||||
// the container. Adding the `dialout` group is needed if read/write permisions for the port are limitted to the
|
||||
// dialout user. This could allow the container to modify unrelated serial devices, which would be a similar level of
|
||||
// risk to running the build directly on the host.
|
||||
// "runArgs": ["--privileged", "-v", "/dev/bus/usb:/dev/bus/usb", "--group-add", "dialout"],
|
||||
|
||||
// Set *default* container specific settings.json values on container create.
|
||||
"settings": {
|
||||
"terminal.integrated.shell.linux": "/bin/bash",
|
||||
|
||||
2
.gitignore
vendored
@@ -21,4 +21,4 @@ wled-update.sh
|
||||
/wled00/my_config.h
|
||||
/wled00/Release
|
||||
/wled00/wled00.ino.cpp
|
||||
/wled00/html_*.h
|
||||
/wled00/html_*.h
|
||||
|
||||
70
CHANGELOG.md
@@ -1,8 +1,76 @@
|
||||
## 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 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
|
||||
- move LED_BUILTIN handling to BusManager class
|
||||
- reduce max panels (web server limitation)
|
||||
- edit WiFi TX power (ESP32)
|
||||
- keep current ledmap ID in UI
|
||||
- limit outputs in UI based on length
|
||||
- wifi.ap addition to JSON Info (JSON API)
|
||||
- relay pin init bugfix
|
||||
- file editor button in UI
|
||||
- ESP8266: update was restarting device on some occasions
|
||||
- a bit of throttling in UI (for ESP8266)
|
||||
|
||||
#### Build 2406120
|
||||
- Update NeoPixelBus to v2.8.0
|
||||
- Increased LED outputs one ESP32 using parallel I2S (up to 17)
|
||||
- use single/mono I2S + 4x RMT for 5 outputs or less
|
||||
- use parallel x8 I2S + 8x RMT for >5 outputs (limit of 300 LEDs per output)
|
||||
- Fixed code of Smartnest and updated documentation (#4001 by @DevilPro1)
|
||||
- ESP32-S3 WiFi fix (#4010 by @cstruck)
|
||||
- TetrisAI usermod fix (#3897 by @muebau)
|
||||
- ESP-NOW usermod hook
|
||||
- Update wled.h regarding OTA Password (#3993 by @gsieben)
|
||||
- Usermod BME68X Sensor Implementation (#3994 by @gsieben)
|
||||
- Add a usermod for AHT10, AHT15 and AHT20 temperature/humidity sensors (#3977 by @LordMike)
|
||||
- Update Battery usermod documentation (#3968 by @adamsthws)
|
||||
- Add INA226 usermod for reading current and power over i2c (#3986 by @LordMike)
|
||||
- Bugfixes: #3991
|
||||
- Several internal fixes and optimisations (WARNING: some effects may be broken that rely on overflow/narrow width)
|
||||
- replace uint8_t and uint16_t with unsigned
|
||||
- replace in8_t and int16_t with int
|
||||
- reduces code by 1kB
|
||||
|
||||
#### Build 2405180
|
||||
- WLED 0.14.4 release
|
||||
- Fix for #3978
|
||||
- Official 0.15.0-b3 release
|
||||
- Merge 0.14.3 fixes
|
||||
- Merge 0.14.3 fixes into 0_15
|
||||
- Added Pinwheel Expand 1D->2D effect mapping mode (#3961 by @Brandon502)
|
||||
- Add changeable i2c address to BME280 usermod (#3966 by @LordMike)
|
||||
- Effect: Firenoise - add palette selection
|
||||
|
||||
@@ -28,7 +28,7 @@ You are all set if you have enabled `Editor: Detect Indentation` in VS Code.
|
||||
|
||||
#### Blocks
|
||||
|
||||
Whether the opening bracket of e.g. an `if` block is in the same line as the condition or in a separate line is up to your discretion. If there is only one statement, leaving out block braches is acceptable.
|
||||
Whether the opening bracket of e.g. an `if` block is in the same line as the condition or in a separate line is up to your discretion. If there is only one statement, leaving out block brackets is acceptable.
|
||||
|
||||
Good:
|
||||
```cpp
|
||||
@@ -49,7 +49,7 @@ 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 paranthesis and variables.
|
||||
Within the condition, no space should be between the parenthesis and variables.
|
||||
Spaces between variables and operators are up to the authors discretion.
|
||||
There should be no space between function names and their argument parenthesis.
|
||||
|
||||
|
||||
717
lib/ESP8266PWM/src/core_esp8266_waveform_pwm.cpp
Normal file
@@ -0,0 +1,717 @@
|
||||
/* esp8266_waveform imported from platform source code
|
||||
Modified for WLED to work around a fault in the NMI handling,
|
||||
which can result in the system locking up and hard WDT crashes.
|
||||
|
||||
Imported from https://github.com/esp8266/Arduino/blob/7e0d20e2b9034994f573a236364e0aef17fd66de/cores/esp8266/core_esp8266_waveform_pwm.cpp
|
||||
*/
|
||||
|
||||
/*
|
||||
esp8266_waveform - General purpose waveform generation and control,
|
||||
supporting outputs on all pins in parallel.
|
||||
|
||||
Copyright (c) 2018 Earle F. Philhower, III. All rights reserved.
|
||||
|
||||
The core idea is to have a programmable waveform generator with a unique
|
||||
high and low period (defined in microseconds or CPU clock cycles). TIMER1
|
||||
is set to 1-shot mode and is always loaded with the time until the next
|
||||
edge of any live waveforms.
|
||||
|
||||
Up to one waveform generator per pin supported.
|
||||
|
||||
Each waveform generator is synchronized to the ESP clock cycle counter, not
|
||||
the timer. This allows for removing interrupt jitter and delay as the
|
||||
counter always increments once per 80MHz clock. Changes to a waveform are
|
||||
contiguous and only take effect on the next waveform transition,
|
||||
allowing for smooth transitions.
|
||||
|
||||
This replaces older tone(), analogWrite(), and the Servo classes.
|
||||
|
||||
Everywhere in the code where "cycles" is used, it means ESP.getCycleCount()
|
||||
clock cycle count, or an interval measured in CPU clock cycles, but not
|
||||
TIMER1 cycles (which may be 2 CPU clock cycles @ 160MHz).
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <coredecls.h>
|
||||
#include "ets_sys.h"
|
||||
#include "core_esp8266_waveform.h"
|
||||
#include "user_interface.h"
|
||||
|
||||
extern "C" {
|
||||
|
||||
// Linker magic
|
||||
void usePWMFixedNMI() {};
|
||||
|
||||
// Maximum delay between IRQs
|
||||
#define MAXIRQUS (10000)
|
||||
|
||||
// Waveform generator can create tones, PWM, and servos
|
||||
typedef struct {
|
||||
uint32_t nextServiceCycle; // ESP cycle timer when a transition required
|
||||
uint32_t expiryCycle; // For time-limited waveform, the cycle when this waveform must stop
|
||||
uint32_t timeHighCycles; // Actual running waveform period (adjusted using desiredCycles)
|
||||
uint32_t timeLowCycles; //
|
||||
uint32_t desiredHighCycles; // Ideal waveform period to drive the error signal
|
||||
uint32_t desiredLowCycles; //
|
||||
uint32_t lastEdge; // Cycle when this generator last changed
|
||||
} Waveform;
|
||||
|
||||
class WVFState {
|
||||
public:
|
||||
Waveform waveform[17]; // State of all possible pins
|
||||
uint32_t waveformState = 0; // Is the pin high or low, updated in NMI so no access outside the NMI code
|
||||
uint32_t waveformEnabled = 0; // Is it actively running, updated in NMI so no access outside the NMI code
|
||||
|
||||
// Enable lock-free by only allowing updates to waveformState and waveformEnabled from IRQ service routine
|
||||
uint32_t waveformToEnable = 0; // Message to the NMI handler to start a waveform on a inactive pin
|
||||
uint32_t waveformToDisable = 0; // Message to the NMI handler to disable a pin from waveform generation
|
||||
|
||||
uint32_t waveformToChange = 0; // Mask of pin to change. One bit set in main app, cleared when effected in the NMI
|
||||
uint32_t waveformNewHigh = 0;
|
||||
uint32_t waveformNewLow = 0;
|
||||
|
||||
uint32_t (*timer1CB)() = NULL;
|
||||
|
||||
// Optimize the NMI inner loop by keeping track of the min and max GPIO that we
|
||||
// are generating. In the common case (1 PWM) these may be the same pin and
|
||||
// we can avoid looking at the other pins.
|
||||
uint16_t startPin = 0;
|
||||
uint16_t endPin = 0;
|
||||
};
|
||||
static WVFState wvfState;
|
||||
|
||||
|
||||
// Ensure everything is read/written to RAM
|
||||
#define MEMBARRIER() { __asm__ volatile("" ::: "memory"); }
|
||||
|
||||
// Non-speed critical bits
|
||||
#pragma GCC optimize ("Os")
|
||||
|
||||
// Interrupt on/off control
|
||||
static IRAM_ATTR void timer1Interrupt();
|
||||
static bool timerRunning = false;
|
||||
|
||||
static __attribute__((noinline)) void initTimer() {
|
||||
if (!timerRunning) {
|
||||
timer1_disable();
|
||||
ETS_FRC_TIMER1_INTR_ATTACH(NULL, NULL);
|
||||
ETS_FRC_TIMER1_NMI_INTR_ATTACH(timer1Interrupt);
|
||||
timer1_enable(TIM_DIV1, TIM_EDGE, TIM_SINGLE);
|
||||
timerRunning = true;
|
||||
timer1_write(microsecondsToClockCycles(10));
|
||||
}
|
||||
}
|
||||
|
||||
static IRAM_ATTR void forceTimerInterrupt() {
|
||||
if (T1L > microsecondsToClockCycles(10)) {
|
||||
T1L = microsecondsToClockCycles(10);
|
||||
}
|
||||
}
|
||||
|
||||
// PWM implementation using special purpose state machine
|
||||
//
|
||||
// Keep an ordered list of pins with the delta in cycles between each
|
||||
// element, with a terminal entry making up the remainder of the PWM
|
||||
// period. With this method sum(all deltas) == PWM period clock cycles.
|
||||
//
|
||||
// At t=0 set all pins high and set the timeout for the 1st edge.
|
||||
// On interrupt, if we're at the last element reset to t=0 state
|
||||
// Otherwise, clear that pin down and set delay for next element
|
||||
// and so forth.
|
||||
|
||||
constexpr int maxPWMs = 8;
|
||||
|
||||
// PWM machine state
|
||||
typedef struct PWMState {
|
||||
uint32_t mask; // Bitmask of active pins
|
||||
uint32_t cnt; // How many entries
|
||||
uint32_t idx; // Where the state machine is along the list
|
||||
uint8_t pin[maxPWMs + 1];
|
||||
uint32_t delta[maxPWMs + 1];
|
||||
uint32_t nextServiceCycle; // Clock cycle for next step
|
||||
struct PWMState *pwmUpdate; // Set by main code, cleared by ISR
|
||||
} PWMState;
|
||||
|
||||
static PWMState pwmState;
|
||||
static uint32_t _pwmFreq = 1000;
|
||||
static uint32_t _pwmPeriod = microsecondsToClockCycles(1000000UL) / _pwmFreq;
|
||||
|
||||
|
||||
// If there are no more scheduled activities, shut down Timer 1.
|
||||
// Otherwise, do nothing.
|
||||
static IRAM_ATTR void disableIdleTimer() {
|
||||
if (timerRunning && !wvfState.waveformEnabled && !pwmState.cnt && !wvfState.timer1CB) {
|
||||
ETS_FRC_TIMER1_NMI_INTR_ATTACH(NULL);
|
||||
timer1_disable();
|
||||
timer1_isr_init();
|
||||
timerRunning = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Notify the NMI that a new PWM state is available through the mailbox.
|
||||
// Wait for mailbox to be emptied (either busy or delay() as needed)
|
||||
static IRAM_ATTR void _notifyPWM(PWMState *p, bool idle) {
|
||||
p->pwmUpdate = nullptr;
|
||||
pwmState.pwmUpdate = p;
|
||||
MEMBARRIER();
|
||||
forceTimerInterrupt();
|
||||
while (pwmState.pwmUpdate) {
|
||||
if (idle) {
|
||||
esp_yield();
|
||||
}
|
||||
MEMBARRIER();
|
||||
}
|
||||
}
|
||||
|
||||
static void _addPWMtoList(PWMState &p, int pin, uint32_t val, uint32_t range);
|
||||
|
||||
|
||||
// Called when analogWriteFreq() changed to update the PWM total period
|
||||
//extern void _setPWMFreq_weak(uint32_t freq) __attribute__((weak));
|
||||
void _setPWMFreq_weak(uint32_t freq) {
|
||||
_pwmFreq = freq;
|
||||
|
||||
// Convert frequency into clock cycles
|
||||
uint32_t cc = microsecondsToClockCycles(1000000UL) / freq;
|
||||
|
||||
// Simple static adjustment to bring period closer to requested due to overhead
|
||||
// Empirically determined as a constant PWM delay and a function of the number of PWMs
|
||||
#if F_CPU == 80000000
|
||||
cc -= ((microsecondsToClockCycles(pwmState.cnt) * 13) >> 4) + 110;
|
||||
#else
|
||||
cc -= ((microsecondsToClockCycles(pwmState.cnt) * 10) >> 4) + 75;
|
||||
#endif
|
||||
|
||||
if (cc == _pwmPeriod) {
|
||||
return; // No change
|
||||
}
|
||||
|
||||
_pwmPeriod = cc;
|
||||
|
||||
if (pwmState.cnt) {
|
||||
PWMState p; // The working copy since we can't edit the one in use
|
||||
p.mask = 0;
|
||||
p.cnt = 0;
|
||||
for (uint32_t i = 0; i < pwmState.cnt; i++) {
|
||||
auto pin = pwmState.pin[i];
|
||||
_addPWMtoList(p, pin, wvfState.waveform[pin].desiredHighCycles, wvfState.waveform[pin].desiredLowCycles);
|
||||
}
|
||||
// Update and wait for mailbox to be emptied
|
||||
initTimer();
|
||||
_notifyPWM(&p, true);
|
||||
disableIdleTimer();
|
||||
}
|
||||
}
|
||||
/*
|
||||
static void _setPWMFreq_bound(uint32_t freq) __attribute__((weakref("_setPWMFreq_weak")));
|
||||
void _setPWMFreq(uint32_t freq) {
|
||||
_setPWMFreq_bound(freq);
|
||||
}
|
||||
*/
|
||||
|
||||
// Helper routine to remove an entry from the state machine
|
||||
// and clean up any marked-off entries
|
||||
static void _cleanAndRemovePWM(PWMState *p, int pin) {
|
||||
uint32_t leftover = 0;
|
||||
uint32_t in, out;
|
||||
for (in = 0, out = 0; in < p->cnt; in++) {
|
||||
if ((p->pin[in] != pin) && (p->mask & (1<<p->pin[in]))) {
|
||||
p->pin[out] = p->pin[in];
|
||||
p->delta[out] = p->delta[in] + leftover;
|
||||
leftover = 0;
|
||||
out++;
|
||||
} else {
|
||||
leftover += p->delta[in];
|
||||
p->mask &= ~(1<<p->pin[in]);
|
||||
}
|
||||
}
|
||||
p->cnt = out;
|
||||
// Final pin is never used: p->pin[out] = 0xff;
|
||||
p->delta[out] = p->delta[in] + leftover;
|
||||
}
|
||||
|
||||
|
||||
// Disable PWM on a specific pin (i.e. when a digitalWrite or analogWrite(0%/100%))
|
||||
//extern bool _stopPWM_weak(uint8_t pin) __attribute__((weak));
|
||||
IRAM_ATTR bool _stopPWM_weak(uint8_t pin) {
|
||||
if (!((1<<pin) & pwmState.mask)) {
|
||||
return false; // Pin not actually active
|
||||
}
|
||||
|
||||
PWMState p; // The working copy since we can't edit the one in use
|
||||
p = pwmState;
|
||||
|
||||
// In _stopPWM we just clear the mask but keep everything else
|
||||
// untouched to save IRAM. The main startPWM will handle cleanup.
|
||||
p.mask &= ~(1<<pin);
|
||||
if (!p.mask) {
|
||||
// If all have been stopped, then turn PWM off completely
|
||||
p.cnt = 0;
|
||||
}
|
||||
|
||||
// Update and wait for mailbox to be emptied, no delay (could be in ISR)
|
||||
_notifyPWM(&p, false);
|
||||
// Possibly shut down the timer completely if we're done
|
||||
disableIdleTimer();
|
||||
return true;
|
||||
}
|
||||
/*
|
||||
static bool _stopPWM_bound(uint8_t pin) __attribute__((weakref("_stopPWM_weak")));
|
||||
IRAM_ATTR bool _stopPWM(uint8_t pin) {
|
||||
return _stopPWM_bound(pin);
|
||||
}
|
||||
*/
|
||||
|
||||
static void _addPWMtoList(PWMState &p, int pin, uint32_t val, uint32_t range) {
|
||||
// Stash the val and range so we can re-evaluate the fraction
|
||||
// should the user change PWM frequency. This allows us to
|
||||
// give as great a precision as possible. We know by construction
|
||||
// that the waveform for this pin will be inactive so we can borrow
|
||||
// memory from that structure.
|
||||
wvfState.waveform[pin].desiredHighCycles = val; // Numerator == high
|
||||
wvfState.waveform[pin].desiredLowCycles = range; // Denominator == low
|
||||
|
||||
uint32_t cc = (_pwmPeriod * val) / range;
|
||||
|
||||
// Clip to sane values in the case we go from OK to not-OK when adjusting frequencies
|
||||
if (cc == 0) {
|
||||
cc = 1;
|
||||
} else if (cc >= _pwmPeriod) {
|
||||
cc = _pwmPeriod - 1;
|
||||
}
|
||||
|
||||
if (p.cnt == 0) {
|
||||
// Starting up from scratch, special case 1st element and PWM period
|
||||
p.pin[0] = pin;
|
||||
p.delta[0] = cc;
|
||||
// Final pin is never used: p.pin[1] = 0xff;
|
||||
p.delta[1] = _pwmPeriod - cc;
|
||||
} else {
|
||||
uint32_t ttl = 0;
|
||||
uint32_t i;
|
||||
// Skip along until we're at the spot to insert
|
||||
for (i=0; (i <= p.cnt) && (ttl + p.delta[i] < cc); i++) {
|
||||
ttl += p.delta[i];
|
||||
}
|
||||
// Shift everything out by one to make space for new edge
|
||||
for (int32_t j = p.cnt; j >= (int)i; j--) {
|
||||
p.pin[j + 1] = p.pin[j];
|
||||
p.delta[j + 1] = p.delta[j];
|
||||
}
|
||||
int off = cc - ttl; // The delta from the last edge to the one we're inserting
|
||||
p.pin[i] = pin;
|
||||
p.delta[i] = off; // Add the delta to this new pin
|
||||
p.delta[i + 1] -= off; // And subtract it from the follower to keep sum(deltas) constant
|
||||
}
|
||||
p.cnt++;
|
||||
p.mask |= 1<<pin;
|
||||
}
|
||||
|
||||
// Called by analogWrite(1...99%) to set the PWM duty in clock cycles
|
||||
//extern bool _setPWM_weak(int pin, uint32_t val, uint32_t range) __attribute__((weak));
|
||||
bool _setPWM_weak(int pin, uint32_t val, uint32_t range) {
|
||||
stopWaveform(pin);
|
||||
PWMState p; // Working copy
|
||||
p = pwmState;
|
||||
// Get rid of any entries for this pin
|
||||
_cleanAndRemovePWM(&p, pin);
|
||||
// And add it to the list, in order
|
||||
if (p.cnt >= maxPWMs) {
|
||||
return false; // No space left
|
||||
}
|
||||
|
||||
// Sanity check for all-on/off
|
||||
uint32_t cc = (_pwmPeriod * val) / range;
|
||||
if ((cc == 0) || (cc >= _pwmPeriod)) {
|
||||
digitalWrite(pin, cc ? HIGH : LOW);
|
||||
return true;
|
||||
}
|
||||
|
||||
_addPWMtoList(p, pin, val, range);
|
||||
|
||||
// Set mailbox and wait for ISR to copy it over
|
||||
initTimer();
|
||||
_notifyPWM(&p, true);
|
||||
disableIdleTimer();
|
||||
|
||||
// Potentially recalculate the PWM period if we've added another pin
|
||||
_setPWMFreq(_pwmFreq);
|
||||
|
||||
return true;
|
||||
}
|
||||
/*
|
||||
static bool _setPWM_bound(int pin, uint32_t val, uint32_t range) __attribute__((weakref("_setPWM_weak")));
|
||||
bool _setPWM(int pin, uint32_t val, uint32_t range) {
|
||||
return _setPWM_bound(pin, val, range);
|
||||
}
|
||||
*/
|
||||
|
||||
// Start up a waveform on a pin, or change the current one. Will change to the new
|
||||
// waveform smoothly on next low->high transition. For immediate change, stopWaveform()
|
||||
// first, then it will immediately begin.
|
||||
//extern int startWaveformClockCycles_weak(uint8_t pin, uint32_t timeHighCycles, uint32_t timeLowCycles, uint32_t runTimeCycles, int8_t alignPhase, uint32_t phaseOffsetUS, bool autoPwm) __attribute__((weak));
|
||||
int startWaveformClockCycles_weak(uint8_t pin, uint32_t timeHighCycles, uint32_t timeLowCycles, uint32_t runTimeCycles,
|
||||
int8_t alignPhase, uint32_t phaseOffsetUS, bool autoPwm) {
|
||||
(void) alignPhase;
|
||||
(void) phaseOffsetUS;
|
||||
(void) autoPwm;
|
||||
|
||||
if ((pin > 16) || isFlashInterfacePin(pin) || (timeHighCycles == 0)) {
|
||||
return false;
|
||||
}
|
||||
Waveform *wave = &wvfState.waveform[pin];
|
||||
wave->expiryCycle = runTimeCycles ? ESP.getCycleCount() + runTimeCycles : 0;
|
||||
if (runTimeCycles && !wave->expiryCycle) {
|
||||
wave->expiryCycle = 1; // expiryCycle==0 means no timeout, so avoid setting it
|
||||
}
|
||||
|
||||
_stopPWM(pin); // Make sure there's no PWM live here
|
||||
|
||||
uint32_t mask = 1<<pin;
|
||||
MEMBARRIER();
|
||||
if (wvfState.waveformEnabled & mask) {
|
||||
// Make sure no waveform changes are waiting to be applied
|
||||
while (wvfState.waveformToChange) {
|
||||
esp_yield(); // Wait for waveform to update
|
||||
MEMBARRIER();
|
||||
}
|
||||
wvfState.waveformNewHigh = timeHighCycles;
|
||||
wvfState.waveformNewLow = timeLowCycles;
|
||||
MEMBARRIER();
|
||||
wvfState.waveformToChange = mask;
|
||||
// The waveform will be updated some time in the future on the next period for the signal
|
||||
} else { // if (!(wvfState.waveformEnabled & mask)) {
|
||||
wave->timeHighCycles = timeHighCycles;
|
||||
wave->desiredHighCycles = timeHighCycles;
|
||||
wave->timeLowCycles = timeLowCycles;
|
||||
wave->desiredLowCycles = timeLowCycles;
|
||||
wave->lastEdge = 0;
|
||||
wave->nextServiceCycle = ESP.getCycleCount() + microsecondsToClockCycles(1);
|
||||
wvfState.waveformToEnable |= mask;
|
||||
MEMBARRIER();
|
||||
initTimer();
|
||||
forceTimerInterrupt();
|
||||
while (wvfState.waveformToEnable) {
|
||||
esp_yield(); // Wait for waveform to update
|
||||
MEMBARRIER();
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
/*
|
||||
static int startWaveformClockCycles_bound(uint8_t pin, uint32_t timeHighCycles, uint32_t timeLowCycles, uint32_t runTimeCycles, int8_t alignPhase, uint32_t phaseOffsetUS, bool autoPwm) __attribute__((weakref("startWaveformClockCycles_weak")));
|
||||
int startWaveformClockCycles(uint8_t pin, uint32_t timeHighCycles, uint32_t timeLowCycles, uint32_t runTimeCycles, int8_t alignPhase, uint32_t phaseOffsetUS, bool autoPwm) {
|
||||
return startWaveformClockCycles_bound(pin, timeHighCycles, timeLowCycles, runTimeCycles, alignPhase, phaseOffsetUS, autoPwm);
|
||||
}
|
||||
|
||||
|
||||
// This version falls-thru to the proper startWaveformClockCycles call and is invariant across waveform generators
|
||||
int startWaveform(uint8_t pin, uint32_t timeHighUS, uint32_t timeLowUS, uint32_t runTimeUS,
|
||||
int8_t alignPhase, uint32_t phaseOffsetUS, bool autoPwm) {
|
||||
return startWaveformClockCycles_bound(pin,
|
||||
microsecondsToClockCycles(timeHighUS), microsecondsToClockCycles(timeLowUS),
|
||||
microsecondsToClockCycles(runTimeUS), alignPhase, microsecondsToClockCycles(phaseOffsetUS), autoPwm);
|
||||
}
|
||||
*/
|
||||
|
||||
// Set a callback. Pass in NULL to stop it
|
||||
//extern void setTimer1Callback_weak(uint32_t (*fn)()) __attribute__((weak));
|
||||
void setTimer1Callback_weak(uint32_t (*fn)()) {
|
||||
wvfState.timer1CB = fn;
|
||||
if (fn) {
|
||||
initTimer();
|
||||
forceTimerInterrupt();
|
||||
}
|
||||
disableIdleTimer();
|
||||
}
|
||||
/*
|
||||
static void setTimer1Callback_bound(uint32_t (*fn)()) __attribute__((weakref("setTimer1Callback_weak")));
|
||||
void setTimer1Callback(uint32_t (*fn)()) {
|
||||
setTimer1Callback_bound(fn);
|
||||
}
|
||||
*/
|
||||
|
||||
// Stops a waveform on a pin
|
||||
//extern int stopWaveform_weak(uint8_t pin) __attribute__((weak));
|
||||
IRAM_ATTR int stopWaveform_weak(uint8_t pin) {
|
||||
// Can't possibly need to stop anything if there is no timer active
|
||||
if (!timerRunning) {
|
||||
return false;
|
||||
}
|
||||
// If user sends in a pin >16 but <32, this will always point to a 0 bit
|
||||
// If they send >=32, then the shift will result in 0 and it will also return false
|
||||
uint32_t mask = 1<<pin;
|
||||
if (wvfState.waveformEnabled & mask) {
|
||||
wvfState.waveformToDisable = mask;
|
||||
// Cancel any pending updates for this waveform, too.
|
||||
if (wvfState.waveformToChange & mask) {
|
||||
wvfState.waveformToChange = 0;
|
||||
}
|
||||
forceTimerInterrupt();
|
||||
while (wvfState.waveformToDisable) {
|
||||
MEMBARRIER(); // If it wasn't written yet, it has to be by now
|
||||
/* no-op */ // Can't delay() since stopWaveform may be called from an IRQ
|
||||
}
|
||||
}
|
||||
disableIdleTimer();
|
||||
return true;
|
||||
}
|
||||
/*
|
||||
static int stopWaveform_bound(uint8_t pin) __attribute__((weakref("stopWaveform_weak")));
|
||||
IRAM_ATTR int stopWaveform(uint8_t pin) {
|
||||
return stopWaveform_bound(pin);
|
||||
}
|
||||
*/
|
||||
|
||||
// Speed critical bits
|
||||
#pragma GCC optimize ("O2")
|
||||
|
||||
// Normally would not want two copies like this, but due to different
|
||||
// optimization levels the inline attribute gets lost if we try the
|
||||
// other version.
|
||||
static inline IRAM_ATTR uint32_t GetCycleCountIRQ() {
|
||||
uint32_t ccount;
|
||||
__asm__ __volatile__("rsr %0,ccount":"=a"(ccount));
|
||||
return ccount;
|
||||
}
|
||||
|
||||
// Find the earliest cycle as compared to right now
|
||||
static inline IRAM_ATTR uint32_t earliest(uint32_t a, uint32_t b) {
|
||||
uint32_t now = GetCycleCountIRQ();
|
||||
int32_t da = a - now;
|
||||
int32_t db = b - now;
|
||||
return (da < db) ? a : b;
|
||||
}
|
||||
|
||||
// ----- @willmmiles begin patch -----
|
||||
// NMI crash workaround
|
||||
// Sometimes the NMI fails to return, stalling the CPU. When this happens,
|
||||
// the next NMI gets a return address /inside the NMI handler function/.
|
||||
// We work around this by caching the last NMI return address, and restoring
|
||||
// the epc3 and eps3 registers to the previous values if the observed epc3
|
||||
// happens to be pointing to the _NMILevelVector function.
|
||||
extern void _NMILevelVector();
|
||||
extern void _UserExceptionVector_1(); // the next function after _NMILevelVector
|
||||
static inline IRAM_ATTR void nmiCrashWorkaround() {
|
||||
static uintptr_t epc3_backup, eps3_backup;
|
||||
|
||||
uintptr_t epc3, eps3;
|
||||
__asm__ __volatile__("rsr %0,epc3; rsr %1,eps3":"=a"(epc3),"=a" (eps3));
|
||||
if ((epc3 < (uintptr_t) &_NMILevelVector) || (epc3 >= (uintptr_t) &_UserExceptionVector_1)) {
|
||||
// Address is good; save backup
|
||||
epc3_backup = epc3;
|
||||
eps3_backup = eps3;
|
||||
} else {
|
||||
// Address is inside the NMI handler -- restore from backup
|
||||
__asm__ __volatile__("wsr %0,epc3; wsr %1,eps3"::"a"(epc3_backup),"a"(eps3_backup));
|
||||
}
|
||||
}
|
||||
// ----- @willmmiles end patch -----
|
||||
|
||||
|
||||
// The SDK and hardware take some time to actually get to our NMI code, so
|
||||
// decrement the next IRQ's timer value by a bit so we can actually catch the
|
||||
// real CPU cycle counter we want for the waveforms.
|
||||
|
||||
// The SDK also sometimes is running at a different speed the the Arduino core
|
||||
// so the ESP cycle counter is actually running at a variable speed.
|
||||
// adjust(x) takes care of adjusting a delta clock cycle amount accordingly.
|
||||
#if F_CPU == 80000000
|
||||
#define DELTAIRQ (microsecondsToClockCycles(9)/4)
|
||||
#define adjust(x) ((x) << (turbo ? 1 : 0))
|
||||
#else
|
||||
#define DELTAIRQ (microsecondsToClockCycles(9)/8)
|
||||
#define adjust(x) ((x) >> 0)
|
||||
#endif
|
||||
|
||||
// When the time to the next edge is greater than this, RTI and set another IRQ to minimize CPU usage
|
||||
#define MINIRQTIME microsecondsToClockCycles(6)
|
||||
|
||||
static IRAM_ATTR void timer1Interrupt() {
|
||||
// ----- @willmmiles begin patch -----
|
||||
nmiCrashWorkaround();
|
||||
// ----- @willmmiles end patch -----
|
||||
|
||||
// Flag if the core is at 160 MHz, for use by adjust()
|
||||
bool turbo = (*(uint32_t*)0x3FF00014) & 1 ? true : false;
|
||||
|
||||
uint32_t nextEventCycle = GetCycleCountIRQ() + microsecondsToClockCycles(MAXIRQUS);
|
||||
uint32_t timeoutCycle = GetCycleCountIRQ() + microsecondsToClockCycles(14);
|
||||
|
||||
if (wvfState.waveformToEnable || wvfState.waveformToDisable) {
|
||||
// Handle enable/disable requests from main app
|
||||
wvfState.waveformEnabled = (wvfState.waveformEnabled & ~wvfState.waveformToDisable) | wvfState.waveformToEnable; // Set the requested waveforms on/off
|
||||
wvfState.waveformState &= ~wvfState.waveformToEnable; // And clear the state of any just started
|
||||
wvfState.waveformToEnable = 0;
|
||||
wvfState.waveformToDisable = 0;
|
||||
// No mem barrier. Globals must be written to RAM on ISR exit.
|
||||
// Find the first GPIO being generated by checking GCC's find-first-set (returns 1 + the bit of the first 1 in an int32_t)
|
||||
wvfState.startPin = __builtin_ffs(wvfState.waveformEnabled) - 1;
|
||||
// Find the last bit by subtracting off GCC's count-leading-zeros (no offset in this one)
|
||||
wvfState.endPin = 32 - __builtin_clz(wvfState.waveformEnabled);
|
||||
} else if (!pwmState.cnt && pwmState.pwmUpdate) {
|
||||
// Start up the PWM generator by copying from the mailbox
|
||||
pwmState.cnt = 1;
|
||||
pwmState.idx = 1; // Ensure copy this cycle, cause it to start at t=0
|
||||
pwmState.nextServiceCycle = GetCycleCountIRQ(); // Do it this loop!
|
||||
// No need for mem barrier here. Global must be written by IRQ exit
|
||||
}
|
||||
|
||||
bool done = false;
|
||||
if (wvfState.waveformEnabled || pwmState.cnt) {
|
||||
do {
|
||||
nextEventCycle = GetCycleCountIRQ() + microsecondsToClockCycles(MAXIRQUS);
|
||||
|
||||
// PWM state machine implementation
|
||||
if (pwmState.cnt) {
|
||||
int32_t cyclesToGo;
|
||||
do {
|
||||
cyclesToGo = pwmState.nextServiceCycle - GetCycleCountIRQ();
|
||||
if (cyclesToGo < 0) {
|
||||
if (pwmState.idx == pwmState.cnt) { // Start of pulses, possibly copy new
|
||||
if (pwmState.pwmUpdate) {
|
||||
// Do the memory copy from temp to global and clear mailbox
|
||||
pwmState = *(PWMState*)pwmState.pwmUpdate;
|
||||
}
|
||||
GPOS = pwmState.mask; // Set all active pins high
|
||||
if (pwmState.mask & (1<<16)) {
|
||||
GP16O = 1;
|
||||
}
|
||||
pwmState.idx = 0;
|
||||
} else {
|
||||
do {
|
||||
// Drop the pin at this edge
|
||||
if (pwmState.mask & (1<<pwmState.pin[pwmState.idx])) {
|
||||
GPOC = 1<<pwmState.pin[pwmState.idx];
|
||||
if (pwmState.pin[pwmState.idx] == 16) {
|
||||
GP16O = 0;
|
||||
}
|
||||
}
|
||||
pwmState.idx++;
|
||||
// Any other pins at this same PWM value will have delta==0, drop them too.
|
||||
} while (pwmState.delta[pwmState.idx] == 0);
|
||||
}
|
||||
// Preserve duty cycle over PWM period by using now+xxx instead of += delta
|
||||
cyclesToGo = adjust(pwmState.delta[pwmState.idx]);
|
||||
pwmState.nextServiceCycle = GetCycleCountIRQ() + cyclesToGo;
|
||||
}
|
||||
nextEventCycle = earliest(nextEventCycle, pwmState.nextServiceCycle);
|
||||
} while (pwmState.cnt && (cyclesToGo < 100));
|
||||
}
|
||||
|
||||
for (auto i = wvfState.startPin; i <= wvfState.endPin; i++) {
|
||||
uint32_t mask = 1<<i;
|
||||
|
||||
// If it's not on, ignore!
|
||||
if (!(wvfState.waveformEnabled & mask)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Waveform *wave = &wvfState.waveform[i];
|
||||
uint32_t now = GetCycleCountIRQ();
|
||||
|
||||
// Disable any waveforms that are done
|
||||
if (wave->expiryCycle) {
|
||||
int32_t expiryToGo = wave->expiryCycle - now;
|
||||
if (expiryToGo < 0) {
|
||||
// Done, remove!
|
||||
if (i == 16) {
|
||||
GP16O = 0;
|
||||
}
|
||||
GPOC = mask;
|
||||
wvfState.waveformEnabled &= ~mask;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Check for toggles
|
||||
int32_t cyclesToGo = wave->nextServiceCycle - now;
|
||||
if (cyclesToGo < 0) {
|
||||
uint32_t nextEdgeCycles;
|
||||
uint32_t desired = 0;
|
||||
uint32_t *timeToUpdate;
|
||||
wvfState.waveformState ^= mask;
|
||||
if (wvfState.waveformState & mask) {
|
||||
if (i == 16) {
|
||||
GP16O = 1;
|
||||
}
|
||||
GPOS = mask;
|
||||
|
||||
if (wvfState.waveformToChange & mask) {
|
||||
// Copy over next full-cycle timings
|
||||
wave->timeHighCycles = wvfState.waveformNewHigh;
|
||||
wave->desiredHighCycles = wvfState.waveformNewHigh;
|
||||
wave->timeLowCycles = wvfState.waveformNewLow;
|
||||
wave->desiredLowCycles = wvfState.waveformNewLow;
|
||||
wave->lastEdge = 0;
|
||||
wvfState.waveformToChange = 0;
|
||||
}
|
||||
if (wave->lastEdge) {
|
||||
desired = wave->desiredLowCycles;
|
||||
timeToUpdate = &wave->timeLowCycles;
|
||||
}
|
||||
nextEdgeCycles = wave->timeHighCycles;
|
||||
} else {
|
||||
if (i == 16) {
|
||||
GP16O = 0;
|
||||
}
|
||||
GPOC = mask;
|
||||
desired = wave->desiredHighCycles;
|
||||
timeToUpdate = &wave->timeHighCycles;
|
||||
nextEdgeCycles = wave->timeLowCycles;
|
||||
}
|
||||
if (desired) {
|
||||
desired = adjust(desired);
|
||||
int32_t err = desired - (now - wave->lastEdge);
|
||||
if (abs(err) < desired) { // If we've lost > the entire phase, ignore this error signal
|
||||
err /= 2;
|
||||
*timeToUpdate += err;
|
||||
}
|
||||
}
|
||||
nextEdgeCycles = adjust(nextEdgeCycles);
|
||||
wave->nextServiceCycle = now + nextEdgeCycles;
|
||||
wave->lastEdge = now;
|
||||
}
|
||||
nextEventCycle = earliest(nextEventCycle, wave->nextServiceCycle);
|
||||
}
|
||||
|
||||
// Exit the loop if we've hit the fixed runtime limit or the next event is known to be after that timeout would occur
|
||||
uint32_t now = GetCycleCountIRQ();
|
||||
int32_t cycleDeltaNextEvent = nextEventCycle - now;
|
||||
int32_t cyclesLeftTimeout = timeoutCycle - now;
|
||||
done = (cycleDeltaNextEvent > MINIRQTIME) || (cyclesLeftTimeout < 0);
|
||||
} while (!done);
|
||||
} // if (wvfState.waveformEnabled)
|
||||
|
||||
if (wvfState.timer1CB) {
|
||||
nextEventCycle = earliest(nextEventCycle, GetCycleCountIRQ() + wvfState.timer1CB());
|
||||
}
|
||||
|
||||
int32_t nextEventCycles = nextEventCycle - GetCycleCountIRQ();
|
||||
|
||||
if (nextEventCycles < MINIRQTIME) {
|
||||
nextEventCycles = MINIRQTIME;
|
||||
}
|
||||
nextEventCycles -= DELTAIRQ;
|
||||
|
||||
// Do it here instead of global function to save time and because we know it's edge-IRQ
|
||||
T1L = nextEventCycles >> (turbo ? 1 : 0);
|
||||
}
|
||||
|
||||
};
|
||||
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "wled",
|
||||
"version": "0.15.0-b3",
|
||||
"version": "0.15.0-b5",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "wled",
|
||||
"version": "0.15.0-b3",
|
||||
"version": "0.15.0-b5",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"clean-css": "^5.3.3",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "wled",
|
||||
"version": "0.15.0-b3",
|
||||
"version": "0.15.0-b5",
|
||||
"description": "Tools for WLED project",
|
||||
"main": "tools/cdata.js",
|
||||
"directories": {
|
||||
|
||||
102
platformio.ini
@@ -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
|
||||
@@ -138,7 +138,8 @@ lib_compat_mode = strict
|
||||
lib_deps =
|
||||
fastled/FastLED @ 3.6.0
|
||||
IRremoteESP8266 @ 2.8.2
|
||||
makuna/NeoPixelBus @ 2.7.9
|
||||
makuna/NeoPixelBus @ 2.8.0
|
||||
#https://github.com/makuna/NeoPixelBus.git#CoreShaderBeta
|
||||
https://github.com/Aircoookie/ESPAsyncWebServer.git @ 2.2.1
|
||||
# for I2C interface
|
||||
;Wire
|
||||
@@ -201,8 +202,41 @@ lib_deps =
|
||||
#https://github.com/lorol/LITTLEFS.git
|
||||
ESPAsyncTCP @ 1.2.2
|
||||
ESPAsyncUDP
|
||||
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
|
||||
@@ -313,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
|
||||
@@ -327,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
|
||||
@@ -342,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]
|
||||
@@ -354,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}
|
||||
|
||||
@@ -371,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
|
||||
@@ -392,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]
|
||||
@@ -403,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
|
||||
@@ -480,6 +543,7 @@ build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp32s3.build_flags} -D WLED_RELEASE_NAME=ESP32-S3_4M_qspi
|
||||
-DARDUINO_USB_CDC_ON_BOOT=1 -DARDUINO_USB_MODE=1 ;; for boards with USB-OTG connector only (USBCDC or "TinyUSB")
|
||||
-DBOARD_HAS_PSRAM
|
||||
-DLOLIN_WIFI_FIX ; seems to work much better with this
|
||||
-D WLED_WATCHDOG_TIMEOUT=0
|
||||
${esp32.AR_build_flags}
|
||||
lib_deps = ${esp32s3.lib_deps}
|
||||
|
||||
@@ -10,7 +10,7 @@ default_envs = WLED_tasmota_1M # define as many as you need
|
||||
#----------
|
||||
# SAMPLE
|
||||
#----------
|
||||
[env:WLED_tasmota_1M]
|
||||
[env:WLED_generic8266_1M]
|
||||
extends = env:esp01_1m_full # when you want to extend the existing environment (define only updated options)
|
||||
; board = esp01_1m # uncomment when ou need different board
|
||||
; platform = ${common.platform_wled_default} # uncomment and change when you want particular platform
|
||||
@@ -26,9 +26,11 @@ lib_deps = ${esp8266.lib_deps}
|
||||
; adafruit/Adafruit BME280 Library@^2.2.2
|
||||
; Wire
|
||||
; robtillaart/SHT85@~0.3.3
|
||||
; gmag11/QuickESPNow ;@ 0.6.2
|
||||
; ;gmag11/QuickESPNow @ ~0.7.0 # will also load QuickDebug
|
||||
; https://github.com/blazoncek/QuickESPNow.git#optional-debug ;; exludes debug library
|
||||
; https://github.com/kosme/arduinoFFT#develop @ 2.0.1 ;; used for USERMOD_AUDIOREACTIVE
|
||||
; ${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}
|
||||
;
|
||||
@@ -51,6 +53,11 @@ build_flags = ${common.build_flags} ${esp8266.build_flags}
|
||||
; -D WLED_DISABLE_ESPNOW
|
||||
; -D WLED_DISABLE_BROWNOUT_DET
|
||||
;
|
||||
; enable optional built-in features
|
||||
; -D WLED_ENABLE_PIXART
|
||||
; -D WLED_ENABLE_USERMOD_PAGE # if created
|
||||
; -D WLED_ENABLE_DMX
|
||||
;
|
||||
; PIN defines - uncomment and change, if needed:
|
||||
; -D LEDPIN=2
|
||||
; or use this for multiple outputs
|
||||
@@ -64,6 +71,8 @@ build_flags = ${common.build_flags} ${esp8266.build_flags}
|
||||
;
|
||||
; Limit max buses
|
||||
; -D WLED_MAX_BUSSES=2
|
||||
; -D WLED_MAX_ANALOG_CHANNELS=3 # only 3 PWM HW pins available
|
||||
; -D WLED_MAX_DIGITAL_CHANNELS=2 # only 2 HW accelerated pins available
|
||||
;
|
||||
; Configure default WiFi
|
||||
; -D CLIENT_SSID='"MyNetwork"'
|
||||
@@ -94,6 +103,12 @@ build_flags = ${common.build_flags} ${esp8266.build_flags}
|
||||
; -D USERMOD_AUTO_SAVE
|
||||
; -D AUTOSAVE_AFTER_SEC=90
|
||||
;
|
||||
; Use AHT10/AHT15/AHT20 usermod
|
||||
; -D USERMOD_AHT10
|
||||
;
|
||||
; Use INA226 usermod
|
||||
; -D USERMOD_INA226
|
||||
;
|
||||
; Use 4 Line Display usermod with SPI display
|
||||
; -D USERMOD_FOUR_LINE_DISPLAY
|
||||
; -D USE_ALT_DISPlAY # mandatory
|
||||
@@ -122,12 +137,12 @@ build_flags = ${common.build_flags} ${esp8266.build_flags}
|
||||
;
|
||||
; Use PIR sensor usermod and configure it to use GPIO4 and timer of 60s
|
||||
; -D USERMOD_PIRSWITCH
|
||||
; -D PIR_SENSOR_PIN=4
|
||||
; -D PIR_SENSOR_PIN=4 # use -1 to disable usermod
|
||||
; -D PIR_SENSOR_OFF_SEC=60
|
||||
; -D PIR_SENSOR_MAX_SENSORS=2 # max allowable sensors (uses OR logic for triggering)
|
||||
;
|
||||
; Use Audioreactive usermod and configure I2S microphone
|
||||
; -D USERMOD_AUDIOREACTIVE
|
||||
; -D UM_AUDIOREACTIVE_USE_NEW_FFT
|
||||
; -D AUDIOPIN=-1
|
||||
; -D DMTYPE=1 # 0-analog/disabled, 1-I2S generic, 2-ES7243, 3-SPH0645, 4-I2S+mclk, 5-I2S PDM
|
||||
; -D I2S_SDPIN=36
|
||||
@@ -139,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
|
||||
;
|
||||
@@ -149,18 +166,22 @@ build_flags = ${common.build_flags} ${esp8266.build_flags}
|
||||
; -D DEFAULT_LED_COUNT=30
|
||||
; or this for multiple outputs
|
||||
; -D PIXEL_COUNTS=30,30
|
||||
;
|
||||
; set milliampere limit when using ESP pin to power leds
|
||||
;
|
||||
; set the default LED type
|
||||
; -D DEFAULT_LED_TYPE=22 # see const.h (TYPE_xxxx)
|
||||
;
|
||||
; set milliampere limit when using ESP power pin (or inadequate PSU) to power LEDs
|
||||
; -D ABL_MILLIAMPS_DEFAULT=850
|
||||
; -D LED_MILLIAMPS_DEFAULT=55
|
||||
;
|
||||
; enable IR by setting remote type
|
||||
; -D IRTYPE=0 ;0 Remote disabled | 1 24-key RGB | 2 24-key with CT | 3 40-key blue | 4 40-key RGB | 5 21-key RGB | 6 6-key black | 7 9-key red | 8 JSON remote
|
||||
; -D IRTYPE=0 # 0 Remote disabled | 1 24-key RGB | 2 24-key with CT | 3 40-key blue | 4 40-key RGB | 5 21-key RGB | 6 6-key black | 7 9-key red | 8 JSON remote
|
||||
;
|
||||
; set default color order of your led strip
|
||||
; -D DEFAULT_LED_COLOR_ORDER=COL_ORDER_GRB
|
||||
;
|
||||
; use PSRAM on classic ESP32 rev.1 (rev.3 or above has no issues)
|
||||
; -DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue
|
||||
; -DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue # needed only for classic ESP32 rev.1
|
||||
;
|
||||
; configure I2C and SPI interface (for various hardware)
|
||||
; -D I2CSDAPIN=33 # initialise interface
|
||||
|
||||
@@ -42,7 +42,7 @@ pyelftools==0.29
|
||||
# via platformio
|
||||
pyserial==3.5
|
||||
# via platformio
|
||||
requests==2.31.0
|
||||
requests==2.32.0
|
||||
# via platformio
|
||||
semantic-version==2.10.0
|
||||
# via platformio
|
||||
@@ -54,7 +54,7 @@ tabulate==0.9.0
|
||||
# via platformio
|
||||
typing-extensions==4.11.0
|
||||
# via starlette
|
||||
urllib3==1.26.18
|
||||
urllib3==1.26.19
|
||||
# via requests
|
||||
uvicorn==0.20.0
|
||||
# via platformio
|
||||
|
||||
37
tools/stress_test.sh
Normal file
@@ -0,0 +1,37 @@
|
||||
#!/bin/bash
|
||||
# Some web server stress tests
|
||||
#
|
||||
# Perform a large number of parallel requests, stress testing the web server
|
||||
# TODO: some kind of performance metrics
|
||||
|
||||
# Accepts three command line arguments:
|
||||
# - first argument - mandatory - IP or hostname of target server
|
||||
# - second argument - target type (optional)
|
||||
# - third argument - xfer count (for replicated targets) (optional)
|
||||
HOST=$1
|
||||
declare -n TARGET_STR="${2:-JSON_LARGER}_TARGETS"
|
||||
REPLICATE_COUNT=$(("${3:-10}"))
|
||||
|
||||
PARALLEL_MAX=${PARALLEL_MAX:-50}
|
||||
|
||||
CURL_ARGS="--compressed --parallel --parallel-immediate --parallel-max ${PARALLEL_MAX}"
|
||||
CURL_PRINT_RESPONSE_ARGS="-w %{http_code}\n"
|
||||
|
||||
JSON_TARGETS=('json/state' 'json/info' 'json/si', 'json/palettes' 'json/fxdata' 'settings/s.js?p=2')
|
||||
FILE_TARGETS=('' 'iro.js' 'rangetouch.js' 'settings' 'settings/wifi')
|
||||
# Replicate one target many times
|
||||
function replicate() {
|
||||
printf "${1}?%d " $(seq 1 ${REPLICATE_COUNT})
|
||||
}
|
||||
read -a JSON_TINY_TARGETS <<< $(replicate "json/nodes")
|
||||
read -a JSON_SMALL_TARGETS <<< $(replicate "json/info")
|
||||
read -a JSON_LARGE_TARGETS <<< $(replicate "json/si")
|
||||
read -a JSON_LARGER_TARGETS <<< $(replicate "json/fxdata")
|
||||
|
||||
# Expand target URLS to full arguments for curl
|
||||
TARGETS=(${TARGET_STR[@]})
|
||||
#echo "${TARGETS[@]}"
|
||||
FULL_TGT_OPTIONS=$(printf "http://${HOST}/%s -o /dev/null " "${TARGETS[@]}")
|
||||
#echo ${FULL_TGT_OPTIONS}
|
||||
|
||||
time curl ${CURL_ARGS} ${FULL_TGT_OPTIONS}
|
||||
46
tools/udp_test.py
Normal file
@@ -0,0 +1,46 @@
|
||||
import numpy as np
|
||||
import socket
|
||||
|
||||
class WledRealtimeClient:
|
||||
def __init__(self, wled_controller_ip, num_pixels, udp_port=21324, max_pixels_per_packet=126):
|
||||
self.wled_controller_ip = wled_controller_ip
|
||||
self.num_pixels = num_pixels
|
||||
self.udp_port = udp_port
|
||||
self.max_pixels_per_packet = max_pixels_per_packet
|
||||
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
self._prev_pixels = np.full((3, self.num_pixels), 253, dtype=np.uint8)
|
||||
self.pixels = np.full((3, self.num_pixels), 1, dtype=np.uint8)
|
||||
|
||||
def update(self):
|
||||
# Truncate values and cast to integer
|
||||
self.pixels = np.clip(self.pixels, 0, 255).astype(np.uint8)
|
||||
p = np.copy(self.pixels)
|
||||
|
||||
idx = np.where(~np.all(p == self._prev_pixels, axis=0))[0]
|
||||
num_pixels = len(idx)
|
||||
n_packets = (num_pixels + self.max_pixels_per_packet - 1) // self.max_pixels_per_packet
|
||||
idx_split = np.array_split(idx, n_packets)
|
||||
|
||||
header = bytes([1, 2]) # WARLS protocol header
|
||||
for packet_indices in idx_split:
|
||||
data = bytearray(header)
|
||||
for i in packet_indices:
|
||||
data.extend([i, *p[:, i]]) # Index and RGB values
|
||||
self._sock.sendto(bytes(data), (self.wled_controller_ip, self.udp_port))
|
||||
|
||||
self._prev_pixels = np.copy(p)
|
||||
|
||||
|
||||
|
||||
################################## LED blink test ##################################
|
||||
if __name__ == "__main__":
|
||||
WLED_CONTROLLER_IP = "192.168.1.153"
|
||||
NUM_PIXELS = 255 # Amount of LEDs on your strip
|
||||
import time
|
||||
wled = WledRealtimeClient(WLED_CONTROLLER_IP, NUM_PIXELS)
|
||||
print('Starting LED blink test')
|
||||
while True:
|
||||
for i in range(NUM_PIXELS):
|
||||
wled.pixels[1, i] = 255 if wled.pixels[1, i] == 0 else 0
|
||||
wled.update()
|
||||
time.sleep(.01)
|
||||
36
usermods/AHT10_v2/README.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# Usermod AHT10
|
||||
This Usermod is designed to read a `AHT10`, `AHT15` or `AHT20` sensor and output the following:
|
||||
- Temperature
|
||||
- Humidity
|
||||
|
||||
Configuration is performed via the Usermod menu. The following settings can be configured in the Usermod Menu:
|
||||
- I2CAddress: The i2c address in decimal. Set it to either 56 (0x38, the default) or 57 (0x39).
|
||||
- SensorType, one of:
|
||||
- 0 - AHT10
|
||||
- 1 - AHT15
|
||||
- 2 - AHT20
|
||||
- CheckInterval: Number of seconds between readings
|
||||
- Decimals: Number of decimals to put in the output
|
||||
|
||||
Dependencies, These must be added under `lib_deps` in your `platform.ini` (or `platform_override.ini`).
|
||||
- Libraries
|
||||
- `enjoyneering/AHT10@~1.1.0` (by [enjoyneering](https://registry.platformio.org/libraries/enjoyneering/AHT10))
|
||||
- `Wire`
|
||||
|
||||
## Author
|
||||
[@LordMike](https://github.com/LordMike)
|
||||
|
||||
# Compiling
|
||||
|
||||
To enable, compile with `USERMOD_AHT10` defined (e.g. in `platformio_override.ini`)
|
||||
```ini
|
||||
[env:aht10_example]
|
||||
extends = env:esp32dev
|
||||
build_flags =
|
||||
${common.build_flags} ${esp32.build_flags}
|
||||
-D USERMOD_AHT10
|
||||
; -D USERMOD_AHT10_DEBUG ; -- add a debug status to the info modal
|
||||
lib_deps =
|
||||
${esp32.lib_deps}
|
||||
enjoyneering/AHT10@~1.1.0
|
||||
```
|
||||
9
usermods/AHT10_v2/platformio_override.ini
Normal file
@@ -0,0 +1,9 @@
|
||||
[env:aht10_example]
|
||||
extends = env:esp32dev
|
||||
build_flags =
|
||||
${common.build_flags} ${esp32.build_flags}
|
||||
-D USERMOD_AHT10
|
||||
; -D USERMOD_AHT10_DEBUG ; -- add a debug status to the info modal
|
||||
lib_deps =
|
||||
${esp32.lib_deps}
|
||||
enjoyneering/AHT10@~1.1.0
|
||||
327
usermods/AHT10_v2/usermod_aht10.h
Normal file
@@ -0,0 +1,327 @@
|
||||
#pragma once
|
||||
|
||||
#include "wled.h"
|
||||
#include <AHT10.h>
|
||||
|
||||
#define AHT10_SUCCESS 1
|
||||
|
||||
class UsermodAHT10 : public Usermod
|
||||
{
|
||||
private:
|
||||
static const char _name[];
|
||||
|
||||
unsigned long _lastLoopCheck = 0;
|
||||
|
||||
bool _settingEnabled : 1; // Enable the usermod
|
||||
bool _mqttPublish : 1; // Publish mqtt values
|
||||
bool _mqttPublishAlways : 1; // Publish always, regardless if there is a change
|
||||
bool _mqttHomeAssistant : 1; // Enable Home Assistant docs
|
||||
bool _initDone : 1; // Initialization is done
|
||||
|
||||
// Settings. Some of these are stored in a different format than they're user settings - so we don't have to convert at runtime
|
||||
uint8_t _i2cAddress = AHT10_ADDRESS_0X38;
|
||||
ASAIR_I2C_SENSOR _ahtType = AHT10_SENSOR;
|
||||
uint16_t _checkInterval = 60000; // milliseconds, user settings is in seconds
|
||||
float _decimalFactor = 100; // a power of 10 factor. 1 would be no change, 10 is one decimal, 100 is two etc. User sees a power of 10 (0, 1, 2, ..)
|
||||
|
||||
uint8_t _lastStatus = 0;
|
||||
float _lastHumidity = 0;
|
||||
float _lastTemperature = 0;
|
||||
|
||||
#ifndef WLED_MQTT_DISABLE
|
||||
float _lastHumiditySent = 0;
|
||||
float _lastTemperatureSent = 0;
|
||||
#endif
|
||||
|
||||
AHT10 *_aht = nullptr;
|
||||
|
||||
float truncateDecimals(float val)
|
||||
{
|
||||
return roundf(val * _decimalFactor) / _decimalFactor;
|
||||
}
|
||||
|
||||
void initializeAht()
|
||||
{
|
||||
if (_aht != nullptr)
|
||||
{
|
||||
delete _aht;
|
||||
}
|
||||
|
||||
_aht = new AHT10(_i2cAddress, _ahtType);
|
||||
|
||||
_lastStatus = 0;
|
||||
_lastHumidity = 0;
|
||||
_lastTemperature = 0;
|
||||
}
|
||||
|
||||
~UsermodAHT10()
|
||||
{
|
||||
delete _aht;
|
||||
_aht = nullptr;
|
||||
}
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
void mqttInitialize()
|
||||
{
|
||||
// This is a generic "setup mqtt" function, So we must abort if we're not to do mqtt
|
||||
if (!WLED_MQTT_CONNECTED || !_mqttPublish || !_mqttHomeAssistant)
|
||||
return;
|
||||
|
||||
char topic[128];
|
||||
snprintf_P(topic, 127, "%s/temperature", mqttDeviceTopic);
|
||||
mqttCreateHassSensor(F("Temperature"), topic, F("temperature"), F("°C"));
|
||||
|
||||
snprintf_P(topic, 127, "%s/humidity", mqttDeviceTopic);
|
||||
mqttCreateHassSensor(F("Humidity"), topic, F("humidity"), F("%"));
|
||||
}
|
||||
|
||||
void mqttPublishIfChanged(const __FlashStringHelper *topic, float &lastState, float state, float minChange)
|
||||
{
|
||||
// Check if MQTT Connected, otherwise it will crash the 8266
|
||||
// Only report if the change is larger than the required diff
|
||||
if (WLED_MQTT_CONNECTED && _mqttPublish && (_mqttPublishAlways || fabsf(lastState - state) > minChange))
|
||||
{
|
||||
char subuf[128];
|
||||
snprintf_P(subuf, 127, PSTR("%s/%s"), mqttDeviceTopic, (const char *)topic);
|
||||
mqtt->publish(subuf, 0, false, String(state).c_str());
|
||||
|
||||
lastState = state;
|
||||
}
|
||||
}
|
||||
|
||||
// Create an MQTT Sensor for Home Assistant Discovery purposes, this includes a pointer to the topic that is published to in the Loop.
|
||||
void mqttCreateHassSensor(const String &name, const String &topic, const String &deviceClass, const String &unitOfMeasurement)
|
||||
{
|
||||
String t = String(F("homeassistant/sensor/")) + mqttClientID + "/" + name + F("/config");
|
||||
|
||||
StaticJsonDocument<600> doc;
|
||||
|
||||
doc[F("name")] = name;
|
||||
doc[F("state_topic")] = topic;
|
||||
doc[F("unique_id")] = String(mqttClientID) + name;
|
||||
if (unitOfMeasurement != "")
|
||||
doc[F("unit_of_measurement")] = unitOfMeasurement;
|
||||
if (deviceClass != "")
|
||||
doc[F("device_class")] = deviceClass;
|
||||
doc[F("expire_after")] = 1800;
|
||||
|
||||
JsonObject device = doc.createNestedObject(F("device")); // attach the sensor to the same device
|
||||
device[F("name")] = serverDescription;
|
||||
device[F("identifiers")] = "wled-sensor-" + String(mqttClientID);
|
||||
device[F("manufacturer")] = F(WLED_BRAND);
|
||||
device[F("model")] = F(WLED_PRODUCT_NAME);
|
||||
device[F("sw_version")] = versionString;
|
||||
|
||||
String temp;
|
||||
serializeJson(doc, temp);
|
||||
DEBUG_PRINTLN(t);
|
||||
DEBUG_PRINTLN(temp);
|
||||
|
||||
mqtt->publish(t.c_str(), 0, true, temp.c_str());
|
||||
}
|
||||
#endif
|
||||
|
||||
public:
|
||||
void setup()
|
||||
{
|
||||
initializeAht();
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
// if usermod is disabled or called during strip updating just exit
|
||||
// NOTE: on very long strips strip.isUpdating() may always return true so update accordingly
|
||||
if (!_settingEnabled || strip.isUpdating())
|
||||
return;
|
||||
|
||||
// do your magic here
|
||||
unsigned long currentTime = millis();
|
||||
|
||||
if (currentTime - _lastLoopCheck < _checkInterval)
|
||||
return;
|
||||
_lastLoopCheck = currentTime;
|
||||
|
||||
_lastStatus = _aht->readRawData();
|
||||
|
||||
if (_lastStatus == AHT10_ERROR)
|
||||
{
|
||||
// Perform softReset and retry
|
||||
DEBUG_PRINTLN(F("AHTxx returned error, doing softReset"));
|
||||
if (!_aht->softReset())
|
||||
{
|
||||
DEBUG_PRINTLN(F("softReset failed"));
|
||||
return;
|
||||
}
|
||||
|
||||
_lastStatus = _aht->readRawData();
|
||||
}
|
||||
|
||||
if (_lastStatus == AHT10_SUCCESS)
|
||||
{
|
||||
float temperature = truncateDecimals(_aht->readTemperature(AHT10_USE_READ_DATA));
|
||||
float humidity = truncateDecimals(_aht->readHumidity(AHT10_USE_READ_DATA));
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
// Push to MQTT
|
||||
|
||||
// We can avoid reporting if the change is insignificant. The threshold chosen is below the level of accuracy, but way above 0.01 which is the precision of the value provided.
|
||||
// The AHT10/15/20 has an accuracy of 0.3C in the temperature readings
|
||||
mqttPublishIfChanged(F("temperature"), _lastTemperatureSent, temperature, 0.1f);
|
||||
|
||||
// The AHT10/15/20 has an accuracy in the humidity sensor of 2%
|
||||
mqttPublishIfChanged(F("humidity"), _lastHumiditySent, humidity, 0.5f);
|
||||
#endif
|
||||
|
||||
// Store
|
||||
_lastTemperature = temperature;
|
||||
_lastHumidity = humidity;
|
||||
}
|
||||
}
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
void onMqttConnect(bool sessionPresent)
|
||||
{
|
||||
mqttInitialize();
|
||||
}
|
||||
#endif
|
||||
|
||||
uint16_t getId()
|
||||
{
|
||||
return USERMOD_ID_AHT10;
|
||||
}
|
||||
|
||||
void addToJsonInfo(JsonObject &root) override
|
||||
{
|
||||
// if "u" object does not exist yet wee need to create it
|
||||
JsonObject user = root["u"];
|
||||
if (user.isNull())
|
||||
user = root.createNestedObject("u");
|
||||
|
||||
#ifdef USERMOD_AHT10_DEBUG
|
||||
JsonArray temp = user.createNestedArray(F("AHT last loop"));
|
||||
temp.add(_lastLoopCheck);
|
||||
|
||||
temp = user.createNestedArray(F("AHT last status"));
|
||||
temp.add(_lastStatus);
|
||||
#endif
|
||||
|
||||
JsonArray jsonTemp = user.createNestedArray(F("Temperature"));
|
||||
JsonArray jsonHumidity = user.createNestedArray(F("Humidity"));
|
||||
|
||||
if (_lastLoopCheck == 0)
|
||||
{
|
||||
// Before first run
|
||||
jsonTemp.add(F("Not read yet"));
|
||||
jsonHumidity.add(F("Not read yet"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (_lastStatus != AHT10_SUCCESS)
|
||||
{
|
||||
jsonTemp.add(F("An error occurred"));
|
||||
jsonHumidity.add(F("An error occurred"));
|
||||
return;
|
||||
}
|
||||
|
||||
jsonTemp.add(_lastTemperature);
|
||||
jsonTemp.add(F("°C"));
|
||||
|
||||
jsonHumidity.add(_lastHumidity);
|
||||
jsonHumidity.add(F("%"));
|
||||
}
|
||||
|
||||
void addToConfig(JsonObject &root)
|
||||
{
|
||||
JsonObject top = root.createNestedObject(FPSTR(_name));
|
||||
top[F("Enabled")] = _settingEnabled;
|
||||
top[F("I2CAddress")] = static_cast<uint8_t>(_i2cAddress);
|
||||
top[F("SensorType")] = _ahtType;
|
||||
top[F("CheckInterval")] = _checkInterval / 1000;
|
||||
top[F("Decimals")] = log10f(_decimalFactor);
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
top[F("MqttPublish")] = _mqttPublish;
|
||||
top[F("MqttPublishAlways")] = _mqttPublishAlways;
|
||||
top[F("MqttHomeAssistantDiscovery")] = _mqttHomeAssistant;
|
||||
#endif
|
||||
|
||||
DEBUG_PRINTLN(F("AHT10 config saved."));
|
||||
}
|
||||
|
||||
bool readFromConfig(JsonObject &root) override
|
||||
{
|
||||
// default settings values could be set here (or below using the 3-argument getJsonValue()) instead of in the class definition or constructor
|
||||
// setting them inside readFromConfig() is slightly more robust, handling the rare but plausible use case of single value being missing after boot (e.g. if the cfg.json was manually edited and a value was removed)
|
||||
|
||||
JsonObject top = root[FPSTR(_name)];
|
||||
|
||||
bool configComplete = !top.isNull();
|
||||
if (!configComplete)
|
||||
return false;
|
||||
|
||||
bool tmpBool = false;
|
||||
configComplete &= getJsonValue(top[F("Enabled")], tmpBool);
|
||||
if (configComplete)
|
||||
_settingEnabled = tmpBool;
|
||||
|
||||
configComplete &= getJsonValue(top[F("I2CAddress")], _i2cAddress);
|
||||
configComplete &= getJsonValue(top[F("CheckInterval")], _checkInterval);
|
||||
if (configComplete)
|
||||
{
|
||||
if (1 <= _checkInterval && _checkInterval <= 600)
|
||||
_checkInterval *= 1000;
|
||||
else
|
||||
// Invalid input
|
||||
_checkInterval = 60000;
|
||||
}
|
||||
|
||||
configComplete &= getJsonValue(top[F("Decimals")], _decimalFactor);
|
||||
if (configComplete)
|
||||
{
|
||||
if (0 <= _decimalFactor && _decimalFactor <= 5)
|
||||
_decimalFactor = pow10f(_decimalFactor);
|
||||
else
|
||||
// Invalid input
|
||||
_decimalFactor = 100;
|
||||
}
|
||||
|
||||
uint8_t tmpAhtType;
|
||||
configComplete &= getJsonValue(top[F("SensorType")], tmpAhtType);
|
||||
if (configComplete)
|
||||
{
|
||||
if (0 <= tmpAhtType && tmpAhtType <= 2)
|
||||
_ahtType = static_cast<ASAIR_I2C_SENSOR>(tmpAhtType);
|
||||
else
|
||||
// Invalid input
|
||||
_ahtType = ASAIR_I2C_SENSOR::AHT10_SENSOR;
|
||||
}
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
configComplete &= getJsonValue(top[F("MqttPublish")], tmpBool);
|
||||
if (configComplete)
|
||||
_mqttPublish = tmpBool;
|
||||
|
||||
configComplete &= getJsonValue(top[F("MqttPublishAlways")], tmpBool);
|
||||
if (configComplete)
|
||||
_mqttPublishAlways = tmpBool;
|
||||
|
||||
configComplete &= getJsonValue(top[F("MqttHomeAssistantDiscovery")], tmpBool);
|
||||
if (configComplete)
|
||||
_mqttHomeAssistant = tmpBool;
|
||||
#endif
|
||||
|
||||
if (_initDone)
|
||||
{
|
||||
// Reloading config
|
||||
initializeAht();
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
mqttInitialize();
|
||||
#endif
|
||||
}
|
||||
|
||||
_initDone = true;
|
||||
return configComplete;
|
||||
}
|
||||
};
|
||||
|
||||
const char UsermodAHT10::_name[] PROGMEM = "AHTxx";
|
||||
BIN
usermods/BME68X_v2/BME680.pdf
Normal file
152
usermods/BME68X_v2/README.md
Normal file
@@ -0,0 +1,152 @@
|
||||
# Usermod BME68X
|
||||
This usermod was developed for a BME680/BME68X sensor. The BME68X is not compatible with the BME280/BMP280 chip. It has its own library. The original 'BSEC Software Library' from Bosch was used to develop the code. The measured values are displayed on the WLED info page.
|
||||
|
||||
<p align="center"><img src="pics/pic1.png" style="width:60%;"></p>
|
||||
|
||||
In addition, the values are published on MQTT if this is active. The topic used for this is: 'wled/[MQTT Client ID]'. The Client ID is set in the WLED MQTT settings.
|
||||
<p align="center"><img src="pics/pic2.png"></p>
|
||||
|
||||
If you use HomeAssistance discovery, the device tree for HomeAssistance is created. This is published under the topic 'homeassistant/sensor/[MQTT Client ID]' via MQTT.
|
||||
<p align="center"><img src="pics/pic3.png"></p>
|
||||
|
||||
A device with the following sensors appears in HomeAssistant. Please note that MQTT must be activated in HomeAssistant.
|
||||
<p align="center"><img src="pics/pic4.png" style="width:60%;"></p>
|
||||
|
||||
|
||||
## Features
|
||||
Raw sensor types
|
||||
|
||||
Sensor Accuracy Scale Range
|
||||
--------------------------------------------------------------------------------------------------
|
||||
Temperature +/- 1.0 °C/°F -40 to 85 °C
|
||||
Humidity +/- 3 % 0 to 100 %
|
||||
Pressure +/- 1 hPa 300 to 1100 hPa
|
||||
Gas Resistance Ohm
|
||||
|
||||
The BSEC Library calculates the following values via the gas resistance
|
||||
|
||||
Sensor Accuracy Scale Range
|
||||
--------------------------------------------------------------------------------------------------
|
||||
IAQ value between 0 and 500
|
||||
Static IAQ same as IAQ but for permanently installed devices
|
||||
CO2 PPM
|
||||
VOC PPM
|
||||
Gas-Percentage %
|
||||
|
||||
|
||||
In addition the usermod calculates
|
||||
|
||||
Sensor Accuracy Scale Range
|
||||
--------------------------------------------------------------------------------------------------
|
||||
Absolute humidity g/m³
|
||||
Dew point °C/°F
|
||||
|
||||
### IAQ (Indoor Air Quality)
|
||||
The IAQ is divided into the following value groups.
|
||||
<p align="center"><img src="pics/pic5.png"></p>
|
||||
|
||||
For more detailed information, please consult the enclosed Bosch product description (BME680.pdf).
|
||||
|
||||
|
||||
## Calibration of the device
|
||||
|
||||
The gas sensor of the BME68X must be calibrated. This differs from the BME280, which does not require any calibration.
|
||||
There is a range of additional information for this, which the driver also provides. These values can be found in HomeAssistant under Diagnostics.
|
||||
|
||||
- **STABILIZATION_STATUS**: Gas sensor stabilization status [boolean] Indicates initial stabilization status of the gas sensor element: stabilization is ongoing (0) or stabilization is finished (1).
|
||||
- **RUN_IN_STATUS**: Gas sensor run-in status [boolean] Indicates power-on stabilization status of the gas sensor element: stabilization is ongoing (0) or stabilization is finished (1)
|
||||
|
||||
Furthermore, all GAS based values have their own accuracy value. These have the following meaning:
|
||||
|
||||
- **Accuracy = 0** means the sensor is being stabilized (this can take a while on the first run)
|
||||
- **Accuracy = 1** means that the previous measured values show too few differences and cannot be used for calibration. If the sensor is at accuracy 1 for too long, you must ensure that the ambient air is chaning. Opening the windows is fine. Or sometimes it is sufficient to breathe on the sensor for approx. 5 minutes.
|
||||
- **Accuracy = 2** means the sensor is currently calibrating.
|
||||
- **Accuracy = 3** means that the sensor has been successfully calibrated. Once accuracy 3 is reached, the calibration data is automatically written to the file system. This calibration data will be used again at the next start and will speed up the calibration.
|
||||
|
||||
The IAQ index is therefore only meaningful if IAQ Accuracy = 3. In addition to the value for IAQ, BSEC also provides us with CO2 and VOC equivalent values. When using the sensor, the calibration value should also always be read out and displayed or transmitted.
|
||||
|
||||
Reasonably reliable values are therefore only achieved when accuracy displays the value 3.
|
||||
|
||||
|
||||
|
||||
## Settings
|
||||
The settings of the usermods are set in the usermod section of wled.
|
||||
<p align="center"><img src="pics/pic6.png"></p>
|
||||
|
||||
The possible settings are
|
||||
|
||||
- **Enable:** Enables / disables the usermod
|
||||
- **I2C address:** I2C address of the sensor. You can choose between 0X77 & 0X76. The default is 0x77.
|
||||
- **Interval:** Specifies the interval of seconds at which the usermod should be executed. The default is every second.
|
||||
- **Pub Chages Only:** If this item is active, the values are only published if they have changed since the last publication.
|
||||
- **Pub Accuracy:** The Accuracy values associated with the gas values are also published.
|
||||
- **Pub Calib State:** If this item is active, STABILIZATION_STATUS& RUN_IN_STATUS are also published.
|
||||
- **Temp Scale:** Here you can choose between °C and °F.
|
||||
- **Temp Offset:** The temperature offset is always set in °C. It must be converted for Fahrenheit.
|
||||
- **HA Discovery:** If this item is active, the HomeAssistant sensor tree is created.
|
||||
- **Pause While WLED Active:** If WLED has many LEDs to calculate, the computing power may no longer be sufficient to calculate the LEDs and read the sensor data. The LEDs then hang for a few microseconds, which can be seen. If this point is active, no sensor data is fetched as long as WLED is running.
|
||||
- **Del Calibration Hist:** If a check mark is set here, the calibration file saved in the file system is deleted when the settings are saved.
|
||||
|
||||
### Sensors
|
||||
Applies to all sensors. The number of decimal places is set here. If the sensor is set to -1, it will no longer be published. In addition, the IAQ values can be activated here in verbal form.
|
||||
|
||||
It is recommended to use the Static IAQ for the IAQ values. This is recommended by Bosch for statically placed devices.
|
||||
|
||||
## Output
|
||||
|
||||
Data is published over MQTT - make sure you've enabled the MQTT sync interface.
|
||||
|
||||
In addition to outputting via MQTT, you can read the values from the Info Screen on the dashboard page of the device's web interface.
|
||||
|
||||
Methods also exist to read the read/calculated values from other WLED modules through code.
|
||||
- getTemperature(); The scale °C/°F is depended to the settings
|
||||
- getHumidity();
|
||||
- getPressure();
|
||||
- getGasResistance();
|
||||
- getAbsoluteHumidity();
|
||||
- getDewPoint(); The scale °C/°F is depended to the settings
|
||||
- getIaq();
|
||||
- getStaticIaq();
|
||||
- getCo2();
|
||||
- getVoc();
|
||||
- getGasPerc();
|
||||
- getIaqAccuracy();
|
||||
- getStaticIaqAccuracy();
|
||||
- getCo2Accuracy();
|
||||
- getVocAccuracy();
|
||||
- getGasPercAccuracy();
|
||||
- getStabStatus();
|
||||
- getRunInStatus();
|
||||
|
||||
|
||||
## Compiling
|
||||
|
||||
To enable, compile with `USERMOD_BME68X` defined (e.g. in `platformio_override.ini`) and add the `BSEC Software Library` to the lib_deps.
|
||||
|
||||
```
|
||||
[env:esp32-BME680]
|
||||
board = esp32dev
|
||||
platform = ${esp32.platform}
|
||||
platform_packages = ${esp32.platform_packages}
|
||||
lib_deps = ${esp32.lib_deps}
|
||||
boschsensortec/BSEC Software Library @ ^1.8.1492 ; USERMOD: BME680
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags_esp32}
|
||||
-D USERMOD_BME68X ; USERMOD: BME680
|
||||
```
|
||||
|
||||
## Revision History
|
||||
### Version 1.0.0
|
||||
- First version of the BME68X_v user module
|
||||
### Version 1.0.1
|
||||
- Rebased to WELD Version 0.15
|
||||
- Reworked some default settings
|
||||
- A problem with the default settings has been fixed
|
||||
|
||||
## Known problems
|
||||
- MQTT goes online at device start. Shortly afterwards it goes offline and takes quite a while until it goes online again. The problem does not come from this user module, but from the WLED core.
|
||||
- If you save the settings often, WLED can get stuck.
|
||||
- If many LEDS are connected to WLED, reading the sensor can cause a small but noticeable hang. The "Pause While WLED Active" option was introduced as a workaround.
|
||||
|
||||
<div><img src="pics/GeoGab.svg" width="20%"/> </div>
|
||||
Gabriel Sieben (gsieben@geogab.net)
|
||||
76
usermods/BME68X_v2/pics/GeoGab.svg
Normal file
@@ -0,0 +1,76 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
xmlns:osb="http://www.openswatchbook.org/uri/2009/osb"
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xml:space="preserve"
|
||||
style="enable-background:new 0 0 595.28 127.56;"
|
||||
viewBox="0 0 600 135"
|
||||
y="0px"
|
||||
x="0px"
|
||||
id="Layer_1"
|
||||
version="1.1"><metadata
|
||||
id="metadata2372"><rdf:RDF><cc:Work
|
||||
rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title></dc:title></cc:Work></rdf:RDF></metadata><defs
|
||||
id="defs2370"><linearGradient
|
||||
osb:paint="solid"
|
||||
id="linearGradient3877"><stop
|
||||
id="stop3875"
|
||||
offset="0"
|
||||
style="stop-color:#808285;stop-opacity:1;" /></linearGradient><clipPath
|
||||
id="clipPath2379"
|
||||
clipPathUnits="userSpaceOnUse"><g
|
||||
style="fill:#808285;fill-opacity:1;fill-rule:nonzero;stroke:#230065;stroke-width:0;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0.99607843"
|
||||
id="use2381"><path
|
||||
style="fill:#808285;fill-opacity:1;fill-rule:nonzero;stroke:#230065;stroke-width:0;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0.99607843"
|
||||
class="st0"
|
||||
d="m 588.34,94.29 c 0,13.28 -10.77,24.04 -24.04,24.04 H 31.38 C 18.1,118.33 7.34,107.57 7.34,94.29 V 32.38 C 7.34,19.1 18.1,8.34 31.38,8.34 h 532.91 c 13.28,0 24.04,10.76 24.04,24.04 V 94.29 Z M 159.44,69.66 c 0,17.15 11.68,19.07 21.89,19.07 h 14.23 c 14.6,0 23.44,-3.2 23.44,-13.87 v -0.91 h -7.84 c -0.45,7.11 -4.47,8.39 -14.32,8.39 h -10.76 c -13.68,0 -18.79,-2.74 -18.79,-13.32 V 66.65 H 219 V 60.9 C 219,44.3 208.88,40.74 194.83,40.74 h -12.59 c -11.12,0 -22.8,1.92 -22.8,18.79 z m 51.72,-9.95 h -43.87 c 0.73,-10.58 3.65,-12.59 16.05,-12.59 h 11.49 c 12.77,0 16.33,4.74 16.33,9.49 z m 18.62,10.13 c 0,15.33 10.86,18.88 25.73,18.88 h 11.22 c 14.87,0 25.72,-3.56 25.72,-18.88 V 59.62 c 0,-15.32 -10.85,-18.88 -25.72,-18.88 h -11.22 c -14.87,0 -25.73,3.56 -25.73,18.88 z m 54.82,-0.46 c 0,10.86 -6.38,12.95 -15.51,12.95 h -15.96 c -9.12,0 -15.51,-2.09 -15.51,-12.95 v -9.31 c 0,-10.85 6.39,-12.95 15.51,-12.95 h 15.96 c 9.12,0 15.51,2.1 15.51,12.95 z m 173.79,18.61 v -31.2 c 0,-13.87 -9.85,-16.06 -24.45,-16.06 h -12.41 c -14.05,0 -19.43,3.47 -19.43,11.95 v 2.28 h 7.84 v -1.64 c 0,-3.83 1.92,-6.2 11.77,-6.2 h 11.49 c 12.04,0 17.33,1.09 17.33,9.49 v 8.76 h -0.18 c -2.74,-4.47 -6.39,-5.56 -16.6,-5.56 H 421.16 C 407.48,59.81 400,61.09 400,71.67 v 3.1 c 0,8.76 3.1,13.96 14.96,13.96 h 18.79 z m -7.84,-12.5 c 0,5.84 -5.47,6.84 -19.7,6.84 h -10.4 c -10.76,0 -12.59,-2.19 -12.59,-7.39 v -1.46 c 0,-5.84 2.83,-7.3 12.95,-7.3 h 12.04 c 12.04,0 17.7,0.82 17.7,7.2 z M 73.6,66.69 h 10.88 l 5.03,0.01 h 48.67 v 2.41 c 0,9.12 -5.47,12.23 -14.41,12.23 H 88.83 c -8.58,0 -15.51,-2.55 -15.51,-14.05 v -0.35 -0.26 z m -9.16,-0.01 c 0,0.06 0,0.14 0,0.2 0.67,14.68 6.68,21.76 23.47,21.76 h 36.85 c 16.51,0 22.35,-6.39 22.35,-24.36 V 59.4 H 89.51 L 85.39,59.39 H 73.32 v -0.01 -16.9 c 0,-11.49 6.93,-14.05 15.51,-14.05 H 112 c 22.07,0 25.81,0.91 25.81,13.23 h 8.39 v -2.37 c 0,-15.23 -12.68,-18.15 -24.54,-18.15 H 87.92 c -17.88,0 -23.53,8.03 -23.53,24.72 V 59.39 L 64.38,59.4 H 44.6 c -11.86,0 -24.54,2.92 -24.54,18.15 v 2.37 5.02 2.37 c 0,15.24 12.68,18.16 24.54,18.16 h 40.79 432.59 34.03 c 17.88,0 23.54,-8.03 23.54,-24.72 V 45.88 c 0,-16.69 -5.65,-24.72 -23.54,-24.72 l -0.16,-0.02 h -223 c -17.88,0 -23.53,8.03 -23.53,24.72 v 18.06 c 0,16.69 5.65,24.72 23.53,24.72 h 36.85 c 16.51,0 22.35,-6.39 22.35,-24.36 V 59.4 h -42.78 v 7.3 h 33.84 v 2.41 c 0,9.12 -5.47,12.23 -14.41,12.23 h -34.94 c -8.58,0 -15.5,-2.55 -15.5,-14.05 V 42.48 c 0,-11.49 6.93,-14.05 15.5,-14.05 l 142.5,0.02 v 61.24 l 24.35,0.73 h 10.95 c 14.23,0 24.18,-3.56 24.18,-19.61 V 62.6 c 0,-14.87 -5.75,-20.16 -24.63,-20.16 h -11.95 -14.88 -0.17 l -0.02,-14.01 h 71.75 l -0.75,0.02 c 8.58,0 15.51,2.55 15.51,14.04 v 41.62 c 0,11.49 -6.93,14.05 -15.51,14.05 H 518.97 86.87 54.27 c -22.08,0 -25.81,-0.91 -25.81,-13.23 v -5.02 c 0,-12.31 3.74,-13.23 25.81,-13.23 h 9.84 z m 459.45,4.04 c 0,9.03 -2.83,13.32 -15.6,13.32 h -12.77 c -11.67,0 -15.42,-4.93 -15.42,-13.41 v -8.85 c 0,-11.13 6.48,-12.95 17.06,-12.95 h 10.58 c 10.76,0 16.14,2.01 16.14,12.77 v 9.12 z"
|
||||
id="path3935" /><path
|
||||
style="opacity:1;fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:#230065;stroke-width:0;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0.99607843"
|
||||
class="st0"
|
||||
d="m 611.07375,-48.387188 c 0,13.28 -10.77,24.039999 -24.04,24.039999 H 54.113747 c -13.27999,0 -24.04,-10.76 -24.04,-24.039999 v -61.910002 c 0,-13.28 10.76001,-24.04 24.04,-24.04 H 587.02375 c 13.28,0 24.04,10.76 24.04,24.04 v 61.910002 z"
|
||||
id="path3937" /></g></clipPath><clipPath
|
||||
id="clipPath2398"
|
||||
clipPathUnits="userSpaceOnUse"><g
|
||||
id="use2400"
|
||||
style="fill:#268298;fill-opacity:1"><g
|
||||
id="g3959"
|
||||
clip-path="url(#clipPath2407)"
|
||||
style="fill:#268298;fill-opacity:1"><g
|
||||
id="g3957"
|
||||
style="fill:#268298;fill-opacity:1"><rect
|
||||
style="opacity:1;fill:#268298;fill-opacity:1;stroke:#000000;stroke-opacity:1"
|
||||
id="rect3955"
|
||||
width="350.98587"
|
||||
height="147.57361"
|
||||
x="95.224861"
|
||||
y="-97.290329" /></g></g></g></clipPath><clipPath
|
||||
id="clipPath2407"
|
||||
clipPathUnits="userSpaceOnUse"><g
|
||||
id="use2409"
|
||||
style="fill:#268298;fill-opacity:1"><rect
|
||||
style="opacity:1;fill:#268298;fill-opacity:1;stroke:#000000;stroke-opacity:1"
|
||||
id="rect3963"
|
||||
width="350.98587"
|
||||
height="147.57361"
|
||||
x="95.224861"
|
||||
y="-97.290329" /></g></clipPath></defs>
|
||||
<style
|
||||
id="style2363"
|
||||
type="text/css">
|
||||
.st0{fill:#808285;}
|
||||
</style>
|
||||
<path
|
||||
style="opacity:1;fill:#ffffff;fill-opacity:0.9859813;fill-rule:nonzero;stroke:#5c7823;stroke-width:0;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0.99607843"
|
||||
class="st0"
|
||||
d="M 600,103.51782 C 600,116.79902 588.8778,127.56 575.17384,127.56 H 24.826163 C 11.111876,127.56 5.1635108e-7,116.79902 5.1635108e-7,103.51782 V 41.602186 C 5.1635108e-7,28.320979 11.111876,17.560001 24.826163,17.560001 H 575.16351 c 13.71429,0 24.82616,10.760978 24.82616,24.042185 v 61.915634 z"
|
||||
id="path2365-0" /><path
|
||||
style="fill:#808285;fill-opacity:1;fill-rule:nonzero;stroke:#230065;stroke-width:0;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0.99607843"
|
||||
class="st0"
|
||||
d="M 600,103.51782 C 600,116.79902 588.8778,127.56 575.17384,127.56 H 24.826162 C 11.111877,127.56 5.1635111e-7,116.79902 5.1635111e-7,103.51782 V 41.602187 C 5.1635111e-7,28.320977 11.111876,17.559997 24.826162,17.559997 H 575.16351 c 13.71429,0 24.82616,10.76098 24.82616,24.04219 V 103.51782 Z M 157.07401,78.885567 c 0,17.15156 12.06196,19.07173 22.60585,19.07173 h 14.69535 c 15.07745,0 24.20654,-3.20029 24.20654,-13.87125 v -0.91009 h -8.09638 c -0.46472,7.11065 -4.61618,8.39076 -14.7883,8.39076 h -11.11188 c -14.12736,0 -19.40447,-2.74024 -19.40447,-13.3212 v -2.37022 h 53.40103 v -5.75052 c 0,-16.60151 -10.45094,-20.16183 -24.96041,-20.16183 h -13.00172 c -11.48365,0 -23.54561,1.92017 -23.54561,18.79171 z m 53.41136,-9.9509 h -45.30465 c 0.75387,-10.58096 3.76936,-12.59114 16.57487,-12.59114 h 11.86575 c 13.18761,0 16.86403,4.74043 16.86403,9.49086 z m 19.22891,10.13092 c 0,15.33139 11.21515,18.88171 26.57143,18.88171 h 11.58692 c 15.35629,0 26.56111,-3.56032 26.56111,-18.88171 v -10.22093 c 0,-15.32139 -11.20482,-18.88171 -26.56111,-18.88171 h -11.58692 c -15.35628,0 -26.57143,3.56032 -26.57143,18.88171 z m 56.61275,-0.46004 c 0,10.86098 -6.58865,12.95117 -16.01722,12.95117 h -16.48193 c -9.41825,0 -16.01721,-2.09019 -16.01721,-12.95117 v -9.31085 c 0,-10.85098 6.59896,-12.95117 16.01721,-12.95117 h 16.48193 c 9.41824,0 16.01722,2.10019 16.01722,12.95117 z m 179.47332,18.61169 v -31.20283 c 0,-13.87126 -10.17212,-16.06146 -25.24957,-16.06146 h -12.81584 c -14.50946,0 -20.0654,3.47031 -20.0654,11.95108 v 2.28021 h 8.09638 v -1.64015 c 0,-3.83035 1.98279,-6.20056 12.15491,-6.20056 h 11.86575 c 12.43373,0 17.89673,1.0901 17.89673,9.49086 v 8.7608 h -0.18589 c -2.8296,-4.47041 -6.59897,-5.56051 -17.14286,-5.56051 h -13.00172 c -14.12736,0 -21.85198,1.28012 -21.85198,11.86108 v 3.10028 c 0,8.76079 3.20138,13.96126 15.44923,13.96126 h 19.40447 z m -8.09639,-12.50114 c 0,5.84053 -5.64888,6.84062 -20.34423,6.84062 h -10.74011 c -11.11187,0 -13.00172,-2.19019 -13.00172,-7.39067 v -1.46013 c 0,-5.84053 2.92255,-7.30066 13.3735,-7.30066 h 12.43373 c 12.43374,0 18.27883,0.82007 18.27883,7.20065 z m -389.27711,-8.8008 h 11.2358 l 5.194492,0.01 h 50.261618 v 2.41021 c 0,9.12083 -5.64888,12.23111 -14.88124,12.23111 H 84.154905 c -8.860585,0 -16.017212,-2.55023 -16.017212,-14.05127 v -0.35003 -0.26003 z m -9.459552,-0.01 c 0,0.06 0,0.14002 0,0.20002 0.69191,14.68133 6.898451,21.76198 24.237521,21.76198 h 38.055071 c 17.04992,0 23.0809,-6.39058 23.0809,-24.36221 v -4.88045 H 84.857142 l -4.254733,-0.01 H 68.137693 v -0.01 -16.90153 c 0,-11.49104 7.156627,-14.05129 16.017212,-14.05129 h 23.927705 c 22.79174,0 26.65405,0.91009 26.65405,13.23121 h 8.66437 v -2.37021 c 0,-15.23139 -13.09466,-18.15166 -25.34251,-18.15166 H 83.215146 c -18.464717,0 -24.299483,8.03073 -24.299483,24.72226 v 13.53122 l -0.01033,0.01 h -20.42685 c -12.247849,0 -25.342513,2.92027 -25.342513,18.15165 v 2.37022 5.02045 2.37022 c 0,15.241393 13.094664,18.161653 25.342513,18.161653 h 42.123923 446.736664 35.14286 c 18.46471,0 24.30981,-8.03073 24.30981,-24.722253 v -34.87316 c 0,-16.69153 -5.83477,-24.72226 -24.30981,-24.72226 l -0.16523,-0.02 H 332.0241 c -18.46471,0 -24.29948,8.03073 -24.29948,24.72226 v 18.06163 c 0,16.69152 5.83477,24.72225 24.29948,24.72225 h 38.05508 c 17.04991,0 23.08089,-6.39058 23.08089,-24.36221 v -4.88045 h -44.179 v 7.30067 h 34.94664 v 2.41021 c 0,9.12083 -5.64888,12.23111 -14.88123,12.23111 h -36.08262 c -8.86059,0 -16.00688,-2.55023 -16.00688,-14.05127 v -24.81225 c 0,-11.49104 7.15662,-14.05129 16.00688,-14.05129 l 147.16007,0.02 v 61.24556 l 25.14629,0.73007 h 11.30809 c 14.69536,0 24.97074,-3.56033 24.97074,-19.61178 v -8.21075 c 0,-14.87135 -5.93803,-20.16183 -25.43545,-20.16183 h -12.34079 -15.36661 -0.17556 l -0.0207,-14.01128 h 74.09639 l -0.77453,0.02 c 8.86059,0 16.01721,2.55024 16.01721,14.04128 v 41.62378 c 0,11.491053 -7.15662,14.051283 -16.01721,14.051283 H 528.36145 82.130808 48.464716 c -22.802065,0 -26.654044,-0.91008 -26.654044,-13.231213 v -5.02046 c 0,-12.31111 3.862306,-13.2312 26.654044,-13.2312 h 10.161789 z m 474.475042,4.04037 c 0,9.03082 -2.92255,13.32121 -16.11015,13.32121 h -13.18761 c -12.05164,0 -15.92427,-4.93045 -15.92427,-13.41122 v -8.8508 c 0,-11.13101 6.69191,-12.95118 17.6179,-12.95118 h 10.92599 c 11.11188,0 16.66781,2.01019 16.66781,12.77116 v 9.12083 z"
|
||||
id="path2365" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 11 KiB |
BIN
usermods/BME68X_v2/pics/pic1.png
Normal file
|
After Width: | Height: | Size: 135 KiB |
BIN
usermods/BME68X_v2/pics/pic2.png
Normal file
|
After Width: | Height: | Size: 23 KiB |
BIN
usermods/BME68X_v2/pics/pic3.png
Normal file
|
After Width: | Height: | Size: 44 KiB |
BIN
usermods/BME68X_v2/pics/pic4.png
Normal file
|
After Width: | Height: | Size: 134 KiB |
BIN
usermods/BME68X_v2/pics/pic5.png
Normal file
|
After Width: | Height: | Size: 14 KiB |
BIN
usermods/BME68X_v2/pics/pic6.png
Normal file
|
After Width: | Height: | Size: 35 KiB |
1114
usermods/BME68X_v2/usermod_bme68x.h
Normal file
BIN
usermods/Battery/assets/battery_connection_schematic_esp32.png
Normal file
|
After Width: | Height: | Size: 129 KiB |
|
After Width: | Height: | Size: 64 KiB |
BIN
usermods/Battery/assets/installation_my_config_h.png
Normal file
|
After Width: | Height: | Size: 49 KiB |
BIN
usermods/Battery/assets/installation_platformio_override_ini.png
Normal file
|
After Width: | Height: | Size: 54 KiB |
@@ -6,54 +6,79 @@
|
||||
|
||||
Enables battery level monitoring of your project.
|
||||
|
||||
For this to work, the positive side of the (18650) battery must be connected to pin `A0` of the d1 mini/esp8266 with a 100k Ohm resistor (see [Useful Links](#useful-links)).
|
||||
|
||||
If you have an ESP32 board, connect the positive side of the battery to ADC1 (GPIO32 - GPIO39)
|
||||
|
||||
<p align="center">
|
||||
<img width="500" src="assets/battery_info_screen.png">
|
||||
<p align="left">
|
||||
<img width="700" src="assets/battery_info_screen.png">
|
||||
</p>
|
||||
|
||||
<br>
|
||||
|
||||
## ⚙️ Features
|
||||
|
||||
- 💯 Displays current battery voltage
|
||||
- 💯 Displays current battery voltage
|
||||
- 🚥 Displays battery level
|
||||
- 🚫 Auto-off with configurable Threshold
|
||||
- 🚫 Auto-off with configurable threshold
|
||||
- 🚨 Low power indicator with many configuration possibilities
|
||||
|
||||
<br><br>
|
||||
|
||||
## 🎈 Installation
|
||||
|
||||
define `USERMOD_BATTERY` in `wled00/my_config.h`
|
||||
| **Option 1** | **Option 2** |
|
||||
|--------------|--------------|
|
||||
| In `wled00/my_config.h`<br>Add the line: `#define USERMOD_BATTERY`<br><br>[Example: my_config.h](assets/installation_my_config_h.png) | In `platformio_override.ini` (or `platformio.ini`)<br>Under: `build_flags =`, add the line: `-D USERMOD_BATTERY`<br><br>[Example: platformio_override.ini](assets/installation_platformio_override_ini.png) |
|
||||
|
||||
### Example wiring
|
||||
<br><br>
|
||||
|
||||
<p align="center">
|
||||
<img width="300" src="assets/battery_connection_schematic_01.png">
|
||||
</p>
|
||||
## 🔌 Example wiring
|
||||
|
||||
### Define Your Options
|
||||
- (see [Useful Links](#useful-links)).
|
||||
|
||||
<table style="width: 100%; table-layout: fixed;">
|
||||
<tr>
|
||||
<!-- Column for the first image -->
|
||||
<td style="width: 50%; vertical-align: bottom;">
|
||||
<img width="300" src="assets/battery_connection_schematic_01.png" style="display: block;">
|
||||
<p><strong>ESP8266</strong><br>
|
||||
With a 100k Ohm resistor, connect the positive<br>
|
||||
side of the battery to pin `A0`.</p>
|
||||
</td>
|
||||
<!-- Column for the second image -->
|
||||
<td style="width: 50%; vertical-align: bottom;">
|
||||
<img width="250" src="assets/battery_connection_schematic_esp32.png" style="display: block;">
|
||||
<p><strong>ESP32</strong> (+S2, S3, C3 etc...)<br>
|
||||
Use a voltage divider (two resistors of equal value).<br>
|
||||
Connect to ADC1 (GPIO32 - GPIO39). GPIO35 is Default.</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<br><br>
|
||||
|
||||
## Define Your Options
|
||||
|
||||
| Name | Unit | Description |
|
||||
| ----------------------------------------------- | ----------- |-------------------------------------------------------------------------------------- |
|
||||
| `USERMOD_BATTERY` | | define this (in `my_config.h`) to have this usermod included wled00\usermods_list.cpp |
|
||||
| `USERMOD_BATTERY_MEASUREMENT_PIN` | | defaults to A0 on ESP8266 and GPIO35 on ESP32 |
|
||||
| `USERMOD_BATTERY_INITIAL_DELAY` | ms | delay before initial reading. defaults to 10 seconds to allow voltage stabilization
|
||||
| `USERMOD_BATTERY_MEASUREMENT_INTERVAL` | ms | battery check interval. defaults to 30 seconds |
|
||||
| `USERMOD_BATTERY_{TYPE}_MIN_VOLTAGE` | v | minimum battery voltage. default is 2.6 (18650 battery standard) |
|
||||
| `USERMOD_BATTERY_{TYPE}_MAX_VOLTAGE` | v | maximum battery voltage. default is 4.2 (18650 battery standard) |
|
||||
| `USERMOD_BATTERY_{TYPE}_TOTAL_CAPACITY` | mAh | the capacity of all cells in parallel summed up |
|
||||
| `USERMOD_BATTERY_{TYPE}_CALIBRATION` | | offset / calibration number, fine tune the measured voltage by the microcontroller |
|
||||
| `USERMOD_BATTERY` | | Define this (in `my_config.h`) to have this usermod included wled00\usermods_list.cpp |
|
||||
| `USERMOD_BATTERY_MEASUREMENT_PIN` | | Defaults to A0 on ESP8266 and GPIO35 on ESP32 |
|
||||
| `USERMOD_BATTERY_MEASUREMENT_INTERVAL` | ms | Battery check interval. defaults to 30 seconds |
|
||||
| `USERMOD_BATTERY_INITIAL_DELAY` | ms | Delay before initial reading. defaults to 10 seconds to allow voltage stabilization |
|
||||
| `USERMOD_BATTERY_{TYPE}_MIN_VOLTAGE` | v | Minimum battery voltage. default is 2.6 (18650 battery standard) |
|
||||
| `USERMOD_BATTERY_{TYPE}_MAX_VOLTAGE` | v | Maximum battery voltage. default is 4.2 (18650 battery standard) |
|
||||
| `USERMOD_BATTERY_{TYPE}_TOTAL_CAPACITY` | mAh | The capacity of all cells in parallel summed up |
|
||||
| `USERMOD_BATTERY_{TYPE}_CALIBRATION` | | Offset / calibration number, fine tune the measured voltage by the microcontroller |
|
||||
| Auto-Off | --- | --- |
|
||||
| `USERMOD_BATTERY_AUTO_OFF_ENABLED` | true/false | enables auto-off |
|
||||
| `USERMOD_BATTERY_AUTO_OFF_THRESHOLD` | % (0-100) | when this threshold is reached master power turns off |
|
||||
| `USERMOD_BATTERY_AUTO_OFF_ENABLED` | true/false | Enables auto-off |
|
||||
| `USERMOD_BATTERY_AUTO_OFF_THRESHOLD` | % (0-100) | When this threshold is reached master power turns off |
|
||||
| Low-Power-Indicator | --- | --- |
|
||||
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_ENABLED` | true/false | enables low power indication |
|
||||
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_PRESET` | preset id | when low power is detected then use this preset to indicate low power |
|
||||
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_THRESHOLD` | % (0-100) | when this threshold is reached low power gets indicated |
|
||||
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_DURATION` | seconds | for this long the configured preset is played |
|
||||
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_ENABLED` | true/false | Enables low power indication |
|
||||
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_PRESET` | preset id | When low power is detected then use this preset to indicate low power |
|
||||
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_THRESHOLD` | % (0-100) | When this threshold is reached low power gets indicated |
|
||||
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_DURATION` | seconds | For this long the configured preset is played |
|
||||
|
||||
All parameters can be configured at runtime via the Usermods settings page.
|
||||
|
||||
<br>
|
||||
|
||||
**NOTICE:** Each Battery type can be pre-configured individualy (in `my_config.h`)
|
||||
|
||||
| Name | Alias | `my_config.h` example |
|
||||
@@ -61,66 +86,91 @@ All parameters can be configured at runtime via the Usermods settings page.
|
||||
| Lithium Polymer | lipo (Li-Po) | `USERMOD_BATTERY_lipo_MIN_VOLTAGE` |
|
||||
| Lithium Ionen | lion (Li-Ion) | `USERMOD_BATTERY_lion_TOTAL_CAPACITY` |
|
||||
|
||||
<br><br>
|
||||
|
||||
## 🔧 Calibration
|
||||
|
||||
The calibration number is a value that is added to the final computed voltage after it has been scaled by the voltage multiplier.
|
||||
|
||||
It fine-tunes the voltage reading so that it more closely matches the actual battery voltage, compensating for inaccuracies inherent in the voltage divider resistors or the ESP's ADC measurements.
|
||||
|
||||
Set calibration either in the Usermods settings page or at compile time in `my_config.h` or `platformio_override.ini`.
|
||||
|
||||
It can be either a positive or negative number.
|
||||
|
||||
<br><br>
|
||||
|
||||
## ⚠️ Important
|
||||
|
||||
- Make sure you know your battery specifications! All batteries are **NOT** the same!
|
||||
- Example:
|
||||
Make sure you know your battery specifications! All batteries are **NOT** the same!
|
||||
|
||||
| Your battery specification table | | Options you can define |
|
||||
| :-------------------------------- |:--------------- | :---------------------------- |
|
||||
| Capacity | 3500mAh 12,5 Wh | |
|
||||
| Minimum capacity | 3350mAh 11,9 Wh | |
|
||||
Example:
|
||||
|
||||
| Your battery specification table | | Options you can define |
|
||||
| --------------------------------- | --------------- | ----------------------------- |
|
||||
| Capacity | 3500mAh 12.5Wh | |
|
||||
| Minimum capacity | 3350mAh 11.9Wh | |
|
||||
| Rated voltage | 3.6V - 3.7V | |
|
||||
| **Charging end voltage** | **4,2V ± 0,05** | `USERMOD_BATTERY_MAX_VOLTAGE` |
|
||||
| **Discharge voltage** | **2,5V** | `USERMOD_BATTERY_MIN_VOLTAGE` |
|
||||
| **Charging end voltage** | **4.2V ± 0.05** | `USERMOD_BATTERY_MAX_VOLTAGE` |
|
||||
| **Discharge voltage** | **2.5V** | `USERMOD_BATTERY_MIN_VOLTAGE` |
|
||||
| Max. discharge current (constant) | 10A (10000mA) | |
|
||||
| max. charging current | 1.7A (1700mA) | |
|
||||
| ... | ... | ... |
|
||||
| .. | .. | .. |
|
||||
|
||||
Specification from: [Molicel INR18650-M35A, 3500mAh 10A Lithium-ion battery, 3.6V - 3.7V](https://www.akkuteile.de/lithium-ionen-akkus/18650/molicel/molicel-inr18650-m35a-3500mah-10a-lithium-ionen-akku-3-6v-3-7v_100833)
|
||||
Specification from: [Molicel INR18650-M35A, 3500mAh 10A Lithium-ion battery, 3.6V - 3.7V](https://www.akkuteile.de/lithium-ionen-akkus/18650/molicel/molicel-inr18650-m35a-3500mah-10a-lithium-ionen-akku-3-6v-3-7v_100833)
|
||||
|
||||
<br><br>
|
||||
|
||||
## 🌐 Useful Links
|
||||
|
||||
- https://lazyzero.de/elektronik/esp8266/wemos_d1_mini_a0/start
|
||||
- https://arduinodiy.wordpress.com/2016/12/25/monitoring-lipo-battery-voltage-with-wemos-d1-minibattery-shield-and-thingspeak/
|
||||
|
||||
<br><br>
|
||||
|
||||
## 📝 Change Log
|
||||
|
||||
2024-04-30
|
||||
2024-08-19
|
||||
|
||||
- improved initial reading accuracy by delaying initial measurement to allow voltage to stabilize at power-on
|
||||
- Improved MQTT support
|
||||
- Added battery percentage & battery voltage as MQTT topic
|
||||
|
||||
2024-05-11
|
||||
|
||||
- Documentation updated
|
||||
|
||||
2024-04-30
|
||||
|
||||
- integrate factory pattern to make it easier to add other / custom battery types
|
||||
- update readme
|
||||
- Integrate factory pattern to make it easier to add other / custom battery types
|
||||
- Update readme
|
||||
- Improved initial reading accuracy by delaying initial measurement to allow voltage to stabilize at power-on
|
||||
|
||||
2023-01-04
|
||||
|
||||
- basic support for LiPo rechargeable batteries ( `-D USERMOD_BATTERY_USE_LIPO`)
|
||||
- improved support for esp32 (read calibrated voltage)
|
||||
- corrected config saving (measurement pin, and battery min/max were lost)
|
||||
- various bugfixes
|
||||
- Basic support for LiPo rechargeable batteries (`-D USERMOD_BATTERY_USE_LIPO`)
|
||||
- Improved support for ESP32 (read calibrated voltage)
|
||||
- Corrected config saving (measurement pin, and battery min/max were lost)
|
||||
- Various bugfixes
|
||||
|
||||
2022-12-25
|
||||
|
||||
- added "auto-off" feature
|
||||
- added "low-power-indication" feature
|
||||
- added "calibration/offset" field to configuration page
|
||||
- added getter and setter, so that user usermods could interact with this one
|
||||
- update readme (added new options, made it markdownlint compliant)
|
||||
- Added "auto-off" feature
|
||||
- Added "low-power-indication" feature
|
||||
- Added "calibration/offset" field to configuration page
|
||||
- Added getter and setter, so that user usermods could interact with this one
|
||||
- Update readme (added new options, made it markdownlint compliant)
|
||||
|
||||
2021-09-02
|
||||
|
||||
- added "Battery voltage" to info
|
||||
- added circuit diagram to readme
|
||||
- added MQTT support, sending battery voltage
|
||||
- minor fixes
|
||||
- Added "Battery voltage" to info
|
||||
- Added circuit diagram to readme
|
||||
- Added MQTT support, sending battery voltage
|
||||
- Minor fixes
|
||||
|
||||
2021-08-15
|
||||
|
||||
- changed `USERMOD_BATTERY_MIN_VOLTAGE` to 2.6 volt as default for 18650 batteries
|
||||
- Changed `USERMOD_BATTERY_MIN_VOLTAGE` to 2.6 volt as default for 18650 batteries
|
||||
- Updated readme, added specification table
|
||||
|
||||
2021-08-10
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
#include "UMBattery.h"
|
||||
#include "types/UnkownUMBattery.h"
|
||||
#include "types/LionUMBattery.h"
|
||||
#include "types/LiPoUMBattery.h"
|
||||
#include "types/LipoUMBattery.h"
|
||||
|
||||
/*
|
||||
* Usermod by Maximilian Mewes
|
||||
@@ -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";
|
||||
|
||||
77
usermods/INA226_v2/README.md
Normal file
@@ -0,0 +1,77 @@
|
||||
# Usermod INA226
|
||||
|
||||
This Usermod is designed to read values from an INA226 sensor and output the following:
|
||||
- Current
|
||||
- Voltage
|
||||
- Power
|
||||
- Shunt Voltage
|
||||
- Overflow status
|
||||
|
||||
## Configuration
|
||||
|
||||
The following settings can be configured in the Usermod Menu:
|
||||
- **Enabled**: Enable or disable the usermod.
|
||||
- **I2CAddress**: The I2C address in decimal. Default is 64 (0x40).
|
||||
- **CheckInterval**: Number of seconds between readings. This should be higher than the time it takes to make a reading, determined by the two next options.
|
||||
- **INASamples**: The number of samples to configure the INA226 to use for a measurement. Higher counts provide more accuracy. See the 'Understanding Samples and Conversion Times' section for more details.
|
||||
- **INAConversionTime**: The time to use on converting and preparing readings on the INA226. Higher times provide more precision. See the 'Understanding Samples and Conversion Times' section for more details.
|
||||
- **Decimals**: Number of decimals in the output.
|
||||
- **ShuntResistor**: Shunt resistor value in milliohms. An R100 shunt resistor should be written as "100", while R010 should be "10".
|
||||
- **CurrentRange**: Expected maximum current in milliamps (e.g., 5 A = 5000 mA).
|
||||
- **MqttPublish**: Enable or disable MQTT publishing.
|
||||
- **MqttPublishAlways**: Publish always, regardless if there is a change.
|
||||
- **MqttHomeAssistantDiscovery**: Enable Home Assistant discovery.
|
||||
|
||||
## Dependencies
|
||||
|
||||
These must be added under `lib_deps` in your `platform.ini` (or `platform_override.ini`).
|
||||
|
||||
- Libraries
|
||||
- `wollewald/INA226_WE@~1.2.9` (by [wollewald](https://registry.platformio.org/libraries/wollewald/INA226_WE))
|
||||
- `Wire`
|
||||
|
||||
## Understanding Samples and Conversion Times
|
||||
|
||||
The INA226 uses a programmable ADC with configurable conversion times and averaging to optimize the measurement accuracy and speed. The conversion time and number of samples are determined based on the `INASamples` and `INAConversionTime` settings. The following table outlines the possible combinations:
|
||||
|
||||
| Conversion Time (μs) | 1 Sample | 4 Samples | 16 Samples | 64 Samples | 128 Samples | 256 Samples | 512 Samples | 1024 Samples |
|
||||
|----------------------|----------|-----------|------------|------------|-------------|-------------|-------------|--------------|
|
||||
| 140 | 0.28 ms | 1.12 ms | 4.48 ms | 17.92 ms | 35.84 ms | 71.68 ms | 143.36 ms | 286.72 ms |
|
||||
| 204 | 0.408 ms | 1.632 ms | 6.528 ms | 26.112 ms | 52.224 ms | 104.448 ms | 208.896 ms | 417.792 ms |
|
||||
| 332 | 0.664 ms | 2.656 ms | 10.624 ms | 42.496 ms | 84.992 ms | 169.984 ms | 339.968 ms | 679.936 ms |
|
||||
| 588 | 1.176 ms | 4.704 ms | 18.816 ms | 75.264 ms | 150.528 ms | 301.056 ms | 602.112 ms | 1204.224 ms |
|
||||
| 1100 | 2.2 ms | 8.8 ms | 35.2 ms | 140.8 ms | 281.6 ms | 563.2 ms | 1126.4 ms | 2252.8 ms |
|
||||
| 2116 | 4.232 ms | 16.928 ms | 67.712 ms | 270.848 ms | 541.696 ms | 1083.392 ms | 2166.784 ms | 4333.568 ms |
|
||||
| 4156 | 8.312 ms | 33.248 ms | 132.992 ms | 531.968 ms | 1063.936 ms | 2127.872 ms | 4255.744 ms | 8511.488 ms |
|
||||
| 8244 | 16.488 ms| 65.952 ms | 263.808 ms | 1055.232 ms| 2110.464 ms | 4220.928 ms | 8441.856 ms | 16883.712 ms |
|
||||
|
||||
It is important to pick a combination that provides the needed balance between accuracy and precision while ensuring new readings within the `CheckInterval` setting. When `USERMOD_INA226_DEBUG` is defined, the info pane contains the expected time to make a reading, which can be seen in the table above.
|
||||
|
||||
As an example, if you want a new reading every 5 seconds (`CheckInterval`), a valid combination is `256 samples` and `4156 μs` which would provide new values every 2.1 seconds.
|
||||
|
||||
The picked values also slightly affect power usage. If the `CheckInterval` is set to more than 20 seconds, the INA226 is configured in `triggered` reading mode, where it only uses power as long as it's working. Then the conversion time and average samples counts determine how long the chip stays turned on every `CheckInterval` time.
|
||||
|
||||
### Calculating Current and Power
|
||||
|
||||
The INA226 calculates current by measuring the differential voltage across a shunt resistor and using the calibration register value to convert this measurement into current. Power is calculated by multiplying the current by the bus voltage.
|
||||
|
||||
For detailed programming information and register configurations, refer to the [INA226 datasheet](https://www.ti.com/product/INA226).
|
||||
|
||||
## Author
|
||||
[@LordMike](https://github.com/LordMike)
|
||||
|
||||
## Compiling
|
||||
|
||||
To enable, compile with `USERMOD_INA226` defined (e.g. in `platformio_override.ini`).
|
||||
|
||||
```ini
|
||||
[env:ina226_example]
|
||||
extends = env:esp32dev
|
||||
build_flags =
|
||||
${common.build_flags} ${esp32.build_flags}
|
||||
-D USERMOD_INA226
|
||||
; -D USERMOD_INA226_DEBUG ; -- add a debug status to the info modal
|
||||
lib_deps =
|
||||
${esp32.lib_deps}
|
||||
wollewald/INA226_WE@~1.2.9
|
||||
```
|
||||
9
usermods/INA226_v2/platformio_override.ini
Normal file
@@ -0,0 +1,9 @@
|
||||
[env:ina226_example]
|
||||
extends = env:esp32dev
|
||||
build_flags =
|
||||
${common.build_flags} ${esp32.build_flags}
|
||||
-D USERMOD_INA226
|
||||
; -D USERMOD_INA226_DEBUG ; -- add a debug status to the info modal
|
||||
lib_deps =
|
||||
${esp32.lib_deps}
|
||||
wollewald/INA226_WE@~1.2.9
|
||||
556
usermods/INA226_v2/usermod_ina226.h
Normal file
@@ -0,0 +1,556 @@
|
||||
#pragma once
|
||||
|
||||
#include "wled.h"
|
||||
#include <INA226_WE.h>
|
||||
|
||||
#define INA226_ADDRESS 0x40 // Default I2C address for INA226
|
||||
|
||||
#define DEFAULT_CHECKINTERVAL 60000
|
||||
#define DEFAULT_INASAMPLES 128
|
||||
#define DEFAULT_INASAMPLESENUM AVERAGE_128
|
||||
#define DEFAULT_INACONVERSIONTIME 1100
|
||||
#define DEFAULT_INACONVERSIONTIMEENUM CONV_TIME_1100
|
||||
|
||||
// A packed version of all INA settings enums and their human friendly counterparts packed into a 32 bit structure
|
||||
// Some values are shifted and need to be preprocessed before usage
|
||||
struct InaSettingLookup
|
||||
{
|
||||
uint16_t avgSamples : 11; // Max 1024, which could be in 10 bits if we shifted by 1; if we somehow handle the edge case with "1"
|
||||
uint8_t avgEnum : 4; // Shift by 8 to get the INA226_AVERAGES value, accepts 0x00 to 0x0F, we need 0x00 to 0x0E
|
||||
uint16_t convTimeUs : 14; // We could save 2 bits by shifting this, but we won't save anything at present.
|
||||
INA226_CONV_TIME convTimeEnum : 3; // Only the lowest 3 bits are defined in the conversion time enumerations
|
||||
};
|
||||
|
||||
const InaSettingLookup _inaSettingsLookup[] = {
|
||||
{1024, AVERAGE_1024 >> 8, 8244, CONV_TIME_8244},
|
||||
{512, AVERAGE_512 >> 8, 4156, CONV_TIME_4156},
|
||||
{256, AVERAGE_256 >> 8, 2116, CONV_TIME_2116},
|
||||
{128, AVERAGE_128 >> 8, 1100, CONV_TIME_1100},
|
||||
{64, AVERAGE_64 >> 8, 588, CONV_TIME_588},
|
||||
{16, AVERAGE_16 >> 8, 332, CONV_TIME_332},
|
||||
{4, AVERAGE_4 >> 8, 204, CONV_TIME_204},
|
||||
{1, AVERAGE_1 >> 8, 140, CONV_TIME_140}};
|
||||
|
||||
// Note: Will update the provided arg to be the correct value
|
||||
INA226_AVERAGES getAverageEnum(uint16_t &samples)
|
||||
{
|
||||
for (const auto &setting : _inaSettingsLookup)
|
||||
{
|
||||
// If a user supplies 2000 samples, we serve up the highest possible value
|
||||
if (samples >= setting.avgSamples)
|
||||
{
|
||||
samples = setting.avgSamples;
|
||||
return static_cast<INA226_AVERAGES>(setting.avgEnum << 8);
|
||||
}
|
||||
}
|
||||
// Default value if not found
|
||||
samples = DEFAULT_INASAMPLES;
|
||||
return DEFAULT_INASAMPLESENUM;
|
||||
}
|
||||
|
||||
INA226_CONV_TIME getConversionTimeEnum(uint16_t &timeUs)
|
||||
{
|
||||
for (const auto &setting : _inaSettingsLookup)
|
||||
{
|
||||
// If a user supplies 9000 μs, we serve up the highest possible value
|
||||
if (timeUs >= setting.convTimeUs)
|
||||
{
|
||||
timeUs = setting.convTimeUs;
|
||||
return setting.convTimeEnum;
|
||||
}
|
||||
}
|
||||
// Default value if not found
|
||||
timeUs = DEFAULT_INACONVERSIONTIME;
|
||||
return DEFAULT_INACONVERSIONTIMEENUM;
|
||||
}
|
||||
|
||||
class UsermodINA226 : public Usermod
|
||||
{
|
||||
private:
|
||||
static const char _name[];
|
||||
|
||||
unsigned long _lastLoopCheck = 0;
|
||||
unsigned long _lastTriggerTime = 0;
|
||||
|
||||
bool _settingEnabled : 1; // Enable the usermod
|
||||
bool _mqttPublish : 1; // Publish MQTT values
|
||||
bool _mqttPublishAlways : 1; // Publish always, regardless if there is a change
|
||||
bool _mqttHomeAssistant : 1; // Enable Home Assistant docs
|
||||
bool _initDone : 1; // Initialization is done
|
||||
bool _isTriggeredOperationMode : 1; // false = continuous, true = triggered
|
||||
bool _measurementTriggered : 1; // if triggered mode, then true indicates we're waiting for measurements
|
||||
uint16_t _settingInaConversionTimeUs : 12; // Conversion time, shift by 2
|
||||
uint16_t _settingInaSamples : 11; // Number of samples for averaging, max 1024
|
||||
|
||||
uint8_t _i2cAddress;
|
||||
uint16_t _checkInterval; // milliseconds, user settings is in seconds
|
||||
float _decimalFactor; // a power of 10 factor. 1 would be no change, 10 is one decimal, 100 is two etc. User sees a power of 10 (0, 1, 2, ..)
|
||||
uint16_t _shuntResistor; // Shunt resistor value in milliohms
|
||||
uint16_t _currentRange; // Expected maximum current in milliamps
|
||||
|
||||
uint8_t _lastStatus = 0;
|
||||
float _lastCurrent = 0;
|
||||
float _lastVoltage = 0;
|
||||
float _lastPower = 0;
|
||||
float _lastShuntVoltage = 0;
|
||||
bool _lastOverflow = false;
|
||||
|
||||
#ifndef WLED_MQTT_DISABLE
|
||||
float _lastCurrentSent = 0;
|
||||
float _lastVoltageSent = 0;
|
||||
float _lastPowerSent = 0;
|
||||
float _lastShuntVoltageSent = 0;
|
||||
bool _lastOverflowSent = false;
|
||||
#endif
|
||||
|
||||
INA226_WE *_ina226 = nullptr;
|
||||
|
||||
float truncateDecimals(float val)
|
||||
{
|
||||
return roundf(val * _decimalFactor) / _decimalFactor;
|
||||
}
|
||||
|
||||
void initializeINA226()
|
||||
{
|
||||
if (_ina226 != nullptr)
|
||||
{
|
||||
delete _ina226;
|
||||
}
|
||||
|
||||
_ina226 = new INA226_WE(_i2cAddress);
|
||||
if (!_ina226->init())
|
||||
{
|
||||
DEBUG_PRINTLN(F("INA226 initialization failed!"));
|
||||
return;
|
||||
}
|
||||
_ina226->setCorrectionFactor(1.0);
|
||||
|
||||
uint16_t tmpShort = _settingInaSamples;
|
||||
_ina226->setAverage(getAverageEnum(tmpShort));
|
||||
|
||||
tmpShort = _settingInaConversionTimeUs << 2;
|
||||
_ina226->setConversionTime(getConversionTimeEnum(tmpShort));
|
||||
|
||||
if (_checkInterval >= 20000)
|
||||
{
|
||||
_isTriggeredOperationMode = true;
|
||||
_ina226->setMeasureMode(TRIGGERED);
|
||||
}
|
||||
else
|
||||
{
|
||||
_isTriggeredOperationMode = false;
|
||||
_ina226->setMeasureMode(CONTINUOUS);
|
||||
}
|
||||
|
||||
_ina226->setResistorRange(static_cast<float>(_shuntResistor) / 1000.0, static_cast<float>(_currentRange) / 1000.0);
|
||||
}
|
||||
|
||||
void fetchAndPushValues()
|
||||
{
|
||||
_lastStatus = _ina226->getI2cErrorCode();
|
||||
|
||||
if (_lastStatus != 0)
|
||||
return;
|
||||
|
||||
float current = truncateDecimals(_ina226->getCurrent_mA() / 1000.0);
|
||||
float voltage = truncateDecimals(_ina226->getBusVoltage_V());
|
||||
float power = truncateDecimals(_ina226->getBusPower() / 1000.0);
|
||||
float shuntVoltage = truncateDecimals(_ina226->getShuntVoltage_V());
|
||||
bool overflow = _ina226->overflow;
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
mqttPublishIfChanged(F("current"), _lastCurrentSent, current, 0.01f);
|
||||
mqttPublishIfChanged(F("voltage"), _lastVoltageSent, voltage, 0.01f);
|
||||
mqttPublishIfChanged(F("power"), _lastPowerSent, power, 0.1f);
|
||||
mqttPublishIfChanged(F("shunt_voltage"), _lastShuntVoltageSent, shuntVoltage, 0.01f);
|
||||
mqttPublishIfChanged(F("overflow"), _lastOverflowSent, overflow);
|
||||
#endif
|
||||
|
||||
_lastCurrent = current;
|
||||
_lastVoltage = voltage;
|
||||
_lastPower = power;
|
||||
_lastShuntVoltage = shuntVoltage;
|
||||
_lastOverflow = overflow;
|
||||
}
|
||||
|
||||
void handleTriggeredMode(unsigned long currentTime)
|
||||
{
|
||||
if (_measurementTriggered)
|
||||
{
|
||||
// Test if we have a measurement every 400ms
|
||||
if (currentTime - _lastTriggerTime >= 400)
|
||||
{
|
||||
_lastTriggerTime = currentTime;
|
||||
if (_ina226->isBusy())
|
||||
return;
|
||||
|
||||
fetchAndPushValues();
|
||||
_measurementTriggered = false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (currentTime - _lastLoopCheck >= _checkInterval)
|
||||
{
|
||||
// Start a measurement and use isBusy() later to determine when it is done
|
||||
_ina226->startSingleMeasurementNoWait();
|
||||
_lastLoopCheck = currentTime;
|
||||
_lastTriggerTime = currentTime;
|
||||
_measurementTriggered = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void handleContinuousMode(unsigned long currentTime)
|
||||
{
|
||||
if (currentTime - _lastLoopCheck >= _checkInterval)
|
||||
{
|
||||
_lastLoopCheck = currentTime;
|
||||
fetchAndPushValues();
|
||||
}
|
||||
}
|
||||
|
||||
~UsermodINA226()
|
||||
{
|
||||
delete _ina226;
|
||||
_ina226 = nullptr;
|
||||
}
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
void mqttInitialize()
|
||||
{
|
||||
if (!WLED_MQTT_CONNECTED || !_mqttPublish || !_mqttHomeAssistant)
|
||||
return;
|
||||
|
||||
char topic[128];
|
||||
snprintf_P(topic, 127, "%s/current", mqttDeviceTopic);
|
||||
mqttCreateHassSensor(F("Current"), topic, F("current"), F("A"));
|
||||
|
||||
snprintf_P(topic, 127, "%s/voltage", mqttDeviceTopic);
|
||||
mqttCreateHassSensor(F("Voltage"), topic, F("voltage"), F("V"));
|
||||
|
||||
snprintf_P(topic, 127, "%s/power", mqttDeviceTopic);
|
||||
mqttCreateHassSensor(F("Power"), topic, F("power"), F("W"));
|
||||
|
||||
snprintf_P(topic, 127, "%s/shunt_voltage", mqttDeviceTopic);
|
||||
mqttCreateHassSensor(F("Shunt Voltage"), topic, F("voltage"), F("V"));
|
||||
|
||||
snprintf_P(topic, 127, "%s/overflow", mqttDeviceTopic);
|
||||
mqttCreateHassBinarySensor(F("Overflow"), topic);
|
||||
}
|
||||
|
||||
void mqttPublishIfChanged(const __FlashStringHelper *topic, float &lastState, float state, float minChange)
|
||||
{
|
||||
if (WLED_MQTT_CONNECTED && _mqttPublish && (_mqttPublishAlways || fabsf(lastState - state) > minChange))
|
||||
{
|
||||
char subuf[128];
|
||||
snprintf_P(subuf, 127, PSTR("%s/%s"), mqttDeviceTopic, (const char *)topic);
|
||||
mqtt->publish(subuf, 0, false, String(state).c_str());
|
||||
|
||||
lastState = state;
|
||||
}
|
||||
}
|
||||
|
||||
void mqttPublishIfChanged(const __FlashStringHelper *topic, bool &lastState, bool state)
|
||||
{
|
||||
if (WLED_MQTT_CONNECTED && _mqttPublish && (_mqttPublishAlways || lastState != state))
|
||||
{
|
||||
char subuf[128];
|
||||
snprintf_P(subuf, 127, PSTR("%s/%s"), mqttDeviceTopic, (const char *)topic);
|
||||
mqtt->publish(subuf, 0, false, state ? "true" : "false");
|
||||
|
||||
lastState = state;
|
||||
}
|
||||
}
|
||||
|
||||
void mqttCreateHassSensor(const String &name, const String &topic, const String &deviceClass, const String &unitOfMeasurement)
|
||||
{
|
||||
String t = String(F("homeassistant/sensor/")) + mqttClientID + "/" + name + F("/config");
|
||||
|
||||
StaticJsonDocument<600> doc;
|
||||
|
||||
doc[F("name")] = name;
|
||||
doc[F("state_topic")] = topic;
|
||||
doc[F("unique_id")] = String(mqttClientID) + name;
|
||||
if (unitOfMeasurement != "")
|
||||
doc[F("unit_of_measurement")] = unitOfMeasurement;
|
||||
if (deviceClass != "")
|
||||
doc[F("device_class")] = deviceClass;
|
||||
doc[F("expire_after")] = 1800;
|
||||
|
||||
JsonObject device = doc.createNestedObject(F("device"));
|
||||
device[F("name")] = serverDescription;
|
||||
device[F("identifiers")] = "wled-sensor-" + String(mqttClientID);
|
||||
device[F("manufacturer")] = F(WLED_BRAND);
|
||||
device[F("model")] = F(WLED_PRODUCT_NAME);
|
||||
device[F("sw_version")] = versionString;
|
||||
|
||||
String temp;
|
||||
serializeJson(doc, temp);
|
||||
DEBUG_PRINTLN(t);
|
||||
DEBUG_PRINTLN(temp);
|
||||
|
||||
mqtt->publish(t.c_str(), 0, true, temp.c_str());
|
||||
}
|
||||
|
||||
void mqttCreateHassBinarySensor(const String &name, const String &topic)
|
||||
{
|
||||
String t = String(F("homeassistant/binary_sensor/")) + mqttClientID + "/" + name + F("/config");
|
||||
|
||||
StaticJsonDocument<600> doc;
|
||||
|
||||
doc[F("name")] = name;
|
||||
doc[F("state_topic")] = topic;
|
||||
doc[F("unique_id")] = String(mqttClientID) + name;
|
||||
|
||||
JsonObject device = doc.createNestedObject(F("device"));
|
||||
device[F("name")] = serverDescription;
|
||||
device[F("identifiers")] = "wled-sensor-" + String(mqttClientID);
|
||||
device[F("manufacturer")] = F(WLED_BRAND);
|
||||
device[F("model")] = F(WLED_PRODUCT_NAME);
|
||||
device[F("sw_version")] = versionString;
|
||||
|
||||
String temp;
|
||||
serializeJson(doc, temp);
|
||||
DEBUG_PRINTLN(t);
|
||||
DEBUG_PRINTLN(temp);
|
||||
|
||||
mqtt->publish(t.c_str(), 0, true, temp.c_str());
|
||||
}
|
||||
#endif
|
||||
|
||||
public:
|
||||
UsermodINA226()
|
||||
{
|
||||
// Default values
|
||||
_settingInaSamples = DEFAULT_INASAMPLES;
|
||||
_settingInaConversionTimeUs = DEFAULT_INACONVERSIONTIME;
|
||||
|
||||
_i2cAddress = INA226_ADDRESS;
|
||||
_checkInterval = DEFAULT_CHECKINTERVAL;
|
||||
_decimalFactor = 100;
|
||||
_shuntResistor = 1000;
|
||||
_currentRange = 1000;
|
||||
}
|
||||
|
||||
void setup()
|
||||
{
|
||||
initializeINA226();
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
if (!_settingEnabled || strip.isUpdating())
|
||||
return;
|
||||
|
||||
unsigned long currentTime = millis();
|
||||
|
||||
if (_isTriggeredOperationMode)
|
||||
{
|
||||
handleTriggeredMode(currentTime);
|
||||
}
|
||||
else
|
||||
{
|
||||
handleContinuousMode(currentTime);
|
||||
}
|
||||
}
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
void onMqttConnect(bool sessionPresent)
|
||||
{
|
||||
mqttInitialize();
|
||||
}
|
||||
#endif
|
||||
|
||||
uint16_t getId()
|
||||
{
|
||||
return USERMOD_ID_INA226;
|
||||
}
|
||||
|
||||
void addToJsonInfo(JsonObject &root) override
|
||||
{
|
||||
JsonObject user = root["u"];
|
||||
if (user.isNull())
|
||||
user = root.createNestedObject("u");
|
||||
|
||||
#ifdef USERMOD_INA226_DEBUG
|
||||
JsonArray temp = user.createNestedArray(F("INA226 last loop"));
|
||||
temp.add(_lastLoopCheck);
|
||||
|
||||
temp = user.createNestedArray(F("INA226 last status"));
|
||||
temp.add(_lastStatus);
|
||||
|
||||
temp = user.createNestedArray(F("INA226 average samples"));
|
||||
temp.add(_settingInaSamples);
|
||||
temp.add(F("samples"));
|
||||
|
||||
temp = user.createNestedArray(F("INA226 conversion time"));
|
||||
temp.add(_settingInaConversionTimeUs << 2);
|
||||
temp.add(F("μs"));
|
||||
|
||||
// INA226 uses (2 * conversion time * samples) time to take a reading.
|
||||
temp = user.createNestedArray(F("INA226 expected sample time"));
|
||||
uint32_t sampleTimeNeededUs = (static_cast<uint32_t>(_settingInaConversionTimeUs) << 2) * _settingInaSamples * 2;
|
||||
temp.add(truncateDecimals(sampleTimeNeededUs / 1000.0));
|
||||
temp.add(F("ms"));
|
||||
|
||||
temp = user.createNestedArray(F("INA226 mode"));
|
||||
temp.add(_isTriggeredOperationMode ? F("triggered") : F("continuous"));
|
||||
|
||||
if (_isTriggeredOperationMode)
|
||||
{
|
||||
temp = user.createNestedArray(F("INA226 triggered"));
|
||||
temp.add(_measurementTriggered ? F("waiting for measurement") : F(""));
|
||||
}
|
||||
#endif
|
||||
|
||||
JsonArray jsonCurrent = user.createNestedArray(F("Current"));
|
||||
JsonArray jsonVoltage = user.createNestedArray(F("Voltage"));
|
||||
JsonArray jsonPower = user.createNestedArray(F("Power"));
|
||||
JsonArray jsonShuntVoltage = user.createNestedArray(F("Shunt Voltage"));
|
||||
JsonArray jsonOverflow = user.createNestedArray(F("Overflow"));
|
||||
|
||||
if (_lastLoopCheck == 0)
|
||||
{
|
||||
jsonCurrent.add(F("Not read yet"));
|
||||
jsonVoltage.add(F("Not read yet"));
|
||||
jsonPower.add(F("Not read yet"));
|
||||
jsonShuntVoltage.add(F("Not read yet"));
|
||||
jsonOverflow.add(F("Not read yet"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (_lastStatus != 0)
|
||||
{
|
||||
jsonCurrent.add(F("An error occurred"));
|
||||
jsonVoltage.add(F("An error occurred"));
|
||||
jsonPower.add(F("An error occurred"));
|
||||
jsonShuntVoltage.add(F("An error occurred"));
|
||||
jsonOverflow.add(F("An error occurred"));
|
||||
return;
|
||||
}
|
||||
|
||||
jsonCurrent.add(_lastCurrent);
|
||||
jsonCurrent.add(F("A"));
|
||||
|
||||
jsonVoltage.add(_lastVoltage);
|
||||
jsonVoltage.add(F("V"));
|
||||
|
||||
jsonPower.add(_lastPower);
|
||||
jsonPower.add(F("W"));
|
||||
|
||||
jsonShuntVoltage.add(_lastShuntVoltage);
|
||||
jsonShuntVoltage.add(F("V"));
|
||||
|
||||
jsonOverflow.add(_lastOverflow ? F("true") : F("false"));
|
||||
}
|
||||
|
||||
void addToConfig(JsonObject &root)
|
||||
{
|
||||
JsonObject top = root.createNestedObject(FPSTR(_name));
|
||||
top[F("Enabled")] = _settingEnabled;
|
||||
top[F("I2CAddress")] = static_cast<uint8_t>(_i2cAddress);
|
||||
top[F("CheckInterval")] = _checkInterval / 1000;
|
||||
top[F("INASamples")] = _settingInaSamples;
|
||||
top[F("INAConversionTime")] = _settingInaConversionTimeUs << 2;
|
||||
top[F("Decimals")] = log10f(_decimalFactor);
|
||||
top[F("ShuntResistor")] = _shuntResistor;
|
||||
top[F("CurrentRange")] = _currentRange;
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
top[F("MqttPublish")] = _mqttPublish;
|
||||
top[F("MqttPublishAlways")] = _mqttPublishAlways;
|
||||
top[F("MqttHomeAssistantDiscovery")] = _mqttHomeAssistant;
|
||||
#endif
|
||||
|
||||
DEBUG_PRINTLN(F("INA226 config saved."));
|
||||
}
|
||||
|
||||
bool readFromConfig(JsonObject &root) override
|
||||
{
|
||||
JsonObject top = root[FPSTR(_name)];
|
||||
|
||||
bool configComplete = !top.isNull();
|
||||
if (!configComplete)
|
||||
return false;
|
||||
|
||||
bool tmpBool;
|
||||
if (getJsonValue(top[F("Enabled")], tmpBool))
|
||||
_settingEnabled = tmpBool;
|
||||
else
|
||||
configComplete = false;
|
||||
|
||||
configComplete &= getJsonValue(top[F("I2CAddress")], _i2cAddress);
|
||||
if (getJsonValue(top[F("CheckInterval")], _checkInterval))
|
||||
{
|
||||
if (1 <= _checkInterval && _checkInterval <= 600)
|
||||
_checkInterval *= 1000;
|
||||
else
|
||||
_checkInterval = DEFAULT_CHECKINTERVAL;
|
||||
}
|
||||
else
|
||||
configComplete = false;
|
||||
|
||||
uint16_t tmpShort;
|
||||
if (getJsonValue(top[F("INASamples")], tmpShort))
|
||||
{
|
||||
// The method below will fix the provided value to a valid one
|
||||
getAverageEnum(tmpShort);
|
||||
_settingInaSamples = tmpShort;
|
||||
}
|
||||
else
|
||||
configComplete = false;
|
||||
|
||||
if (getJsonValue(top[F("INAConversionTime")], tmpShort))
|
||||
{
|
||||
// The method below will fix the provided value to a valid one
|
||||
getConversionTimeEnum(tmpShort);
|
||||
_settingInaConversionTimeUs = tmpShort >> 2;
|
||||
}
|
||||
else
|
||||
configComplete = false;
|
||||
|
||||
if (getJsonValue(top[F("Decimals")], _decimalFactor))
|
||||
{
|
||||
if (0 <= _decimalFactor && _decimalFactor <= 5)
|
||||
_decimalFactor = pow10f(_decimalFactor);
|
||||
else
|
||||
_decimalFactor = 100;
|
||||
}
|
||||
else
|
||||
configComplete = false;
|
||||
|
||||
configComplete &= getJsonValue(top[F("ShuntResistor")], _shuntResistor);
|
||||
configComplete &= getJsonValue(top[F("CurrentRange")], _currentRange);
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
if (getJsonValue(top[F("MqttPublish")], tmpBool))
|
||||
_mqttPublish = tmpBool;
|
||||
else
|
||||
configComplete = false;
|
||||
|
||||
if (getJsonValue(top[F("MqttPublishAlways")], tmpBool))
|
||||
_mqttPublishAlways = tmpBool;
|
||||
else
|
||||
configComplete = false;
|
||||
|
||||
if (getJsonValue(top[F("MqttHomeAssistantDiscovery")], tmpBool))
|
||||
_mqttHomeAssistant = tmpBool;
|
||||
else
|
||||
configComplete = false;
|
||||
#endif
|
||||
|
||||
if (_initDone)
|
||||
{
|
||||
initializeINA226();
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
mqttInitialize();
|
||||
#endif
|
||||
}
|
||||
|
||||
_initDone = true;
|
||||
return configComplete;
|
||||
}
|
||||
};
|
||||
|
||||
const char UsermodINA226::_name[] PROGMEM = "INA226";
|
||||
BIN
usermods/Internal_Temperature_v2/assets/screenshot_info.png
Normal file
|
After Width: | Height: | Size: 132 KiB |
BIN
usermods/Internal_Temperature_v2/assets/screenshot_settings.png
Normal file
|
After Width: | Height: | Size: 59 KiB |
@@ -1,17 +1,44 @@
|
||||
# Internal Temperature Usermod
|
||||
This usermod adds the temperature readout to the Info tab and also publishes that over the topic `mcutemp` topic.
|
||||
|
||||
## Important
|
||||
A shown temp of 53,33°C might indicate that the internal temp is not supported.
|
||||

|
||||
|
||||
ESP8266 does not have a internal temp sensor
|
||||

|
||||
|
||||
|
||||
## Features
|
||||
- 🌡️ Adds the internal temperature readout of the chip to the `Info` tab
|
||||
- 🥵 High temperature indicator/action. (Configurable threshold and preset)
|
||||
- 📣 Publishes the internal temperature over the MQTT topic: `mcutemp`
|
||||
|
||||
|
||||
## Use Examples
|
||||
- Warn of excessive/damaging temperatures by the triggering of a 'warning' preset
|
||||
- Activate a cooling fan (when used with the multi-relay usermod)
|
||||
|
||||
|
||||
## Compatibility
|
||||
- A shown temp of 53,33°C might indicate that the internal temp is not supported
|
||||
- ESP8266 does not have a internal temp sensor -> Disabled (Indicated with a readout of '-1')
|
||||
- ESP32S2 seems to crash on reading the sensor -> Disabled (Indicated with a readout of '-1')
|
||||
|
||||
ESP32S2 seems to crash on reading the sensor -> disabled
|
||||
|
||||
## Installation
|
||||
Add a build flag `-D USERMOD_INTERNAL_TEMPERATURE` to your `platformio.ini` (or `platformio_override.ini`).
|
||||
- Add a build flag `-D USERMOD_INTERNAL_TEMPERATURE` to your `platformio.ini` (or `platformio_override.ini`).
|
||||
|
||||
|
||||
## 📝 Change Log
|
||||
|
||||
2024-06-26
|
||||
|
||||
- Added "high-temperature-indication" feature
|
||||
- Documentation updated
|
||||
|
||||
2023-09-01
|
||||
|
||||
* "Internal Temperature" usermod created
|
||||
|
||||
|
||||
## Authors
|
||||
Soeren Willrodt [@lost-hope](https://github.com/lost-hope)
|
||||
|
||||
Dimitry Zhemkov [@dima-zhemkov](https://github.com/dima-zhemkov)
|
||||
- Soeren Willrodt [@lost-hope](https://github.com/lost-hope)
|
||||
- Dimitry Zhemkov [@dima-zhemkov](https://github.com/dima-zhemkov)
|
||||
- Adam Matthews [@adamsthws](https://github.com/adamsthws)
|
||||
|
||||
@@ -6,14 +6,23 @@ class InternalTemperatureUsermod : public Usermod
|
||||
{
|
||||
|
||||
private:
|
||||
static constexpr unsigned long minLoopInterval = 1000; // minimum allowable interval (ms)
|
||||
unsigned long loopInterval = 10000;
|
||||
unsigned long lastTime = 0;
|
||||
bool isEnabled = false;
|
||||
float temperature = 0;
|
||||
float temperature = 0.0f;
|
||||
uint8_t previousPlaylist = 0; // Stores the playlist that was active before high-temperature activation
|
||||
uint8_t previousPreset = 0; // Stores the preset that was active before high-temperature activation
|
||||
uint8_t presetToActivate = 0; // Preset to activate when temp goes above threshold (0 = disabled)
|
||||
float activationThreshold = 95.0f; // Temperature threshold to trigger high-temperature actions
|
||||
float resetMargin = 2.0f; // Margin below the activation threshold (Prevents frequent toggling when close to threshold)
|
||||
bool isAboveThreshold = false; // Flag to track if the high temperature preset is currently active
|
||||
|
||||
static const char _name[];
|
||||
static const char _enabled[];
|
||||
static const char _loopInterval[];
|
||||
static const char _activationThreshold[];
|
||||
static const char _presetToActivate[];
|
||||
|
||||
// any private methods should go here (non-inline method should be defined out of class)
|
||||
void publishMqtt(const char *state, bool retain = false); // example for publishing MQTT message
|
||||
@@ -32,6 +41,7 @@ public:
|
||||
|
||||
lastTime = millis();
|
||||
|
||||
// Measure the temperature
|
||||
#ifdef ESP8266 // ESP8266
|
||||
// does not seem possible
|
||||
temperature = -1;
|
||||
@@ -41,6 +51,57 @@ public:
|
||||
temperature = roundf(temperatureRead() * 10) / 10;
|
||||
#endif
|
||||
|
||||
// Check if temperature has exceeded the activation threshold
|
||||
if (temperature >= activationThreshold) {
|
||||
// Update the state flag if not already set
|
||||
if (!isAboveThreshold) {
|
||||
isAboveThreshold = true;
|
||||
}
|
||||
// Check if a 'high temperature' preset is configured and it's not already active
|
||||
if (presetToActivate != 0 && currentPreset != presetToActivate) {
|
||||
// If a playlist is active, store it for reactivation later
|
||||
if (currentPlaylist > 0) {
|
||||
previousPlaylist = currentPlaylist;
|
||||
}
|
||||
// If a preset is active, store it for reactivation later
|
||||
else if (currentPreset > 0) {
|
||||
previousPreset = currentPreset;
|
||||
// If no playlist or preset is active, save current state for reactivation later
|
||||
} else {
|
||||
saveTemporaryPreset();
|
||||
}
|
||||
// Activate the 'high temperature' preset
|
||||
applyPreset(presetToActivate);
|
||||
}
|
||||
}
|
||||
// Check if temperature is back below the threshold
|
||||
else if (temperature <= (activationThreshold - resetMargin)) {
|
||||
// Update the state flag if not already set
|
||||
if (isAboveThreshold){
|
||||
isAboveThreshold = false;
|
||||
}
|
||||
// Check if the 'high temperature' preset is active
|
||||
if (currentPreset == presetToActivate) {
|
||||
// Check if a previous playlist was stored
|
||||
if (previousPlaylist > 0) {
|
||||
// Reactivate the stored playlist
|
||||
applyPreset(previousPlaylist);
|
||||
// Clear the stored playlist
|
||||
previousPlaylist = 0;
|
||||
}
|
||||
// Check if a previous preset was stored
|
||||
else if (previousPreset > 0) {
|
||||
// Reactivate the stored preset
|
||||
applyPreset(previousPreset);
|
||||
// Clear the stored preset
|
||||
previousPreset = 0;
|
||||
// If no previous playlist or preset was stored, revert to the stored state
|
||||
} else {
|
||||
applyTemporaryPreset();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
if (WLED_MQTT_CONNECTED)
|
||||
{
|
||||
@@ -80,15 +141,30 @@ public:
|
||||
JsonObject top = root.createNestedObject(FPSTR(_name));
|
||||
top[FPSTR(_enabled)] = isEnabled;
|
||||
top[FPSTR(_loopInterval)] = loopInterval;
|
||||
top[FPSTR(_activationThreshold)] = activationThreshold;
|
||||
top[FPSTR(_presetToActivate)] = presetToActivate;
|
||||
}
|
||||
|
||||
// Append useful info to the usermod settings gui
|
||||
void appendConfigData()
|
||||
{
|
||||
// Display 'ms' next to the 'Loop Interval' setting
|
||||
oappend(SET_F("addInfo('Internal Temperature:Loop Interval', 1, 'ms');"));
|
||||
// Display '°C' next to the 'Activation Threshold' setting
|
||||
oappend(SET_F("addInfo('Internal Temperature:Activation Threshold', 1, '°C');"));
|
||||
// Display '0 = Disabled' next to the 'Preset To Activate' setting
|
||||
oappend(SET_F("addInfo('Internal Temperature:Preset To Activate', 1, '0 = unused');"));
|
||||
}
|
||||
|
||||
bool readFromConfig(JsonObject &root)
|
||||
{
|
||||
JsonObject top = root[FPSTR(_name)];
|
||||
bool configComplete = !top.isNull();
|
||||
configComplete &= getJsonValue(top[FPSTR(_enabled)], isEnabled);
|
||||
configComplete &= getJsonValue(top[FPSTR(_loopInterval)], loopInterval);
|
||||
|
||||
loopInterval = max(loopInterval, minLoopInterval); // Makes sure the loop interval isn't too small.
|
||||
configComplete &= getJsonValue(top[FPSTR(_presetToActivate)], presetToActivate);
|
||||
configComplete &= getJsonValue(top[FPSTR(_activationThreshold)], activationThreshold);
|
||||
return configComplete;
|
||||
}
|
||||
|
||||
@@ -101,6 +177,8 @@ public:
|
||||
const char InternalTemperatureUsermod::_name[] PROGMEM = "Internal Temperature";
|
||||
const char InternalTemperatureUsermod::_enabled[] PROGMEM = "Enabled";
|
||||
const char InternalTemperatureUsermod::_loopInterval[] PROGMEM = "Loop Interval";
|
||||
const char InternalTemperatureUsermod::_activationThreshold[] PROGMEM = "Activation Threshold";
|
||||
const char InternalTemperatureUsermod::_presetToActivate[] PROGMEM = "Preset To Activate";
|
||||
|
||||
void InternalTemperatureUsermod::publishMqtt(const char *state, bool retain)
|
||||
{
|
||||
|
||||
36
usermods/LD2410_v2/readme.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# BH1750 usermod
|
||||
|
||||
> This usermod requires a second UART and was only tested on the ESP32
|
||||
|
||||
|
||||
This usermod will read from a LD2410 movement/presence sensor.
|
||||
|
||||
The movement and presence state are displayed in both the Info section of the web UI, as well as published to the `/movement` and `/stationary` MQTT topics respectively.
|
||||
|
||||
## Dependencies
|
||||
- Libraries
|
||||
- `ncmreynolds/ld2410@^0.1.3`
|
||||
- This must be added under `lib_deps` in your `platformio.ini` (or `platformio_override.ini`).
|
||||
- Data is published over MQTT - make sure you've enabled the MQTT sync interface.
|
||||
|
||||
## Compilation
|
||||
|
||||
To enable, compile with `USERMOD_LD2410` defined (e.g. in `platformio_override.ini`)
|
||||
```ini
|
||||
[env:usermod_USERMOD_LD2410_esp32dev]
|
||||
extends = env:esp32dev
|
||||
build_flags =
|
||||
${common.build_flags_esp32}
|
||||
-D USERMOD_LD2410
|
||||
lib_deps =
|
||||
${esp32.lib_deps}
|
||||
ncmreynolds/ld2410@^0.1.3
|
||||
```
|
||||
|
||||
### Configuration Options
|
||||
The Usermod screen allows you to:
|
||||
- enable/disable the usermod
|
||||
- Configure the RX/TX pins
|
||||
|
||||
## Change log
|
||||
- 2024-06 Created by @wesleygas (https://github.com/wesleygas/)
|
||||
237
usermods/LD2410_v2/usermod_ld2410.h
Normal file
@@ -0,0 +1,237 @@
|
||||
#warning **** Included USERMOD_LD2410 ****
|
||||
|
||||
#ifndef WLED_ENABLE_MQTT
|
||||
#error "This user mod requires MQTT to be enabled."
|
||||
#endif
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "wled.h"
|
||||
#include <ld2410.h>
|
||||
|
||||
class LD2410Usermod : public Usermod {
|
||||
|
||||
private:
|
||||
|
||||
bool enabled = true;
|
||||
bool initDone = false;
|
||||
bool sensorFound = false;
|
||||
unsigned long lastTime = 0;
|
||||
unsigned long last_mqtt_sent = 0;
|
||||
|
||||
int8_t default_uart_rx = 19;
|
||||
int8_t default_uart_tx = 18;
|
||||
|
||||
|
||||
String mqttMovementTopic = F("");
|
||||
String mqttStationaryTopic = F("");
|
||||
bool mqttInitialized = false;
|
||||
bool HomeAssistantDiscovery = true; // Publish Home Assistant Discovery messages
|
||||
|
||||
|
||||
ld2410 radar;
|
||||
bool stationary_detected = false;
|
||||
bool last_stationary_state = false;
|
||||
bool movement_detected = false;
|
||||
bool last_movement_state = false;
|
||||
|
||||
// These config variables have defaults set inside readFromConfig()
|
||||
int8_t uart_rx_pin;
|
||||
int8_t uart_tx_pin;
|
||||
|
||||
// string that are used multiple time (this will save some flash memory)
|
||||
static const char _name[];
|
||||
static const char _enabled[];
|
||||
|
||||
void publishMqtt(const char* topic, const char* state, bool retain); // example for publishing MQTT message
|
||||
|
||||
void _mqttInitialize()
|
||||
{
|
||||
mqttMovementTopic = String(mqttDeviceTopic) + F("/ld2410/movement");
|
||||
mqttStationaryTopic = String(mqttDeviceTopic) + F("/ld2410/stationary");
|
||||
if (HomeAssistantDiscovery){
|
||||
_createMqttSensor(F("Movement"), mqttMovementTopic, F("motion"), F(""));
|
||||
_createMqttSensor(F("Stationary"), mqttStationaryTopic, F("occupancy"), F(""));
|
||||
}
|
||||
}
|
||||
|
||||
// Create an MQTT Sensor for Home Assistant Discovery purposes, this includes a pointer to the topic that is published to in the Loop.
|
||||
void _createMqttSensor(const String &name, const String &topic, const String &deviceClass, const String &unitOfMeasurement)
|
||||
{
|
||||
String t = String(F("homeassistant/binary_sensor/")) + mqttClientID + F("/") + name + F("/config");
|
||||
|
||||
StaticJsonDocument<600> doc;
|
||||
|
||||
doc[F("name")] = String(serverDescription) + F(" Module");
|
||||
doc[F("state_topic")] = topic;
|
||||
doc[F("unique_id")] = String(mqttClientID) + name;
|
||||
if (unitOfMeasurement != "")
|
||||
doc[F("unit_of_measurement")] = unitOfMeasurement;
|
||||
if (deviceClass != "")
|
||||
doc[F("device_class")] = deviceClass;
|
||||
doc[F("expire_after")] = 1800;
|
||||
doc[F("payload_off")] = "OFF";
|
||||
doc[F("payload_on")] = "ON";
|
||||
|
||||
JsonObject device = doc.createNestedObject(F("device")); // attach the sensor to the same device
|
||||
device[F("name")] = serverDescription;
|
||||
device[F("identifiers")] = "wled-sensor-" + String(mqttClientID);
|
||||
device[F("manufacturer")] = F("WLED");
|
||||
device[F("model")] = F("FOSS");
|
||||
device[F("sw_version")] = versionString;
|
||||
|
||||
String temp;
|
||||
serializeJson(doc, temp);
|
||||
DEBUG_PRINTLN(t);
|
||||
DEBUG_PRINTLN(temp);
|
||||
|
||||
mqtt->publish(t.c_str(), 0, true, temp.c_str());
|
||||
}
|
||||
|
||||
public:
|
||||
|
||||
inline bool isEnabled() { return enabled; }
|
||||
|
||||
void setup() {
|
||||
Serial1.begin(256000, SERIAL_8N1, uart_rx_pin, uart_tx_pin);
|
||||
Serial.print(F("\nLD2410 radar sensor initialising: "));
|
||||
if(radar.begin(Serial1)){
|
||||
Serial.println(F("OK"));
|
||||
} else {
|
||||
Serial.println(F("not connected"));
|
||||
}
|
||||
initDone = true;
|
||||
}
|
||||
|
||||
|
||||
void loop() {
|
||||
// NOTE: on very long strips strip.isUpdating() may always return true so update accordingly
|
||||
if (!enabled || strip.isUpdating()) return;
|
||||
radar.read();
|
||||
unsigned long curr_time = millis();
|
||||
if(curr_time - lastTime > 1000) //Try to Report every 1000ms
|
||||
{
|
||||
lastTime = curr_time;
|
||||
sensorFound = radar.isConnected();
|
||||
if(!sensorFound) return;
|
||||
stationary_detected = radar.presenceDetected();
|
||||
if(stationary_detected != last_stationary_state){
|
||||
if (WLED_MQTT_CONNECTED){
|
||||
publishMqtt("/ld2410/stationary", stationary_detected ? "ON":"OFF", false);
|
||||
last_stationary_state = stationary_detected;
|
||||
}
|
||||
}
|
||||
movement_detected = radar.movingTargetDetected();
|
||||
if(movement_detected != last_movement_state){
|
||||
if (WLED_MQTT_CONNECTED){
|
||||
publishMqtt("/ld2410/movement", movement_detected ? "ON":"OFF", false);
|
||||
last_movement_state = movement_detected;
|
||||
}
|
||||
}
|
||||
// If there hasn't been any activity, send current state to confirm sensor is alive
|
||||
if(curr_time - last_mqtt_sent > 1000*60*5 && WLED_MQTT_CONNECTED){
|
||||
publishMqtt("/ld2410/stationary", stationary_detected ? "ON":"OFF", false);
|
||||
publishMqtt("/ld2410/movement", movement_detected ? "ON":"OFF", false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void addToJsonInfo(JsonObject& root)
|
||||
{
|
||||
// if "u" object does not exist yet wee need to create it
|
||||
JsonObject user = root[F("u")];
|
||||
if (user.isNull()) user = root.createNestedObject(F("u"));
|
||||
|
||||
JsonArray ld2410_sta_json = user.createNestedArray(F("LD2410 Stationary"));
|
||||
JsonArray ld2410_mov_json = user.createNestedArray(F("LD2410 Movement"));
|
||||
if (!enabled){
|
||||
ld2410_sta_json.add(F("disabled"));
|
||||
ld2410_mov_json.add(F("disabled"));
|
||||
} else if(!sensorFound){
|
||||
ld2410_sta_json.add(F("LD2410"));
|
||||
ld2410_sta_json.add(" Not Found");
|
||||
} else {
|
||||
ld2410_sta_json.add("Sta ");
|
||||
ld2410_sta_json.add(stationary_detected ? "ON":"OFF");
|
||||
ld2410_mov_json.add("Mov ");
|
||||
ld2410_mov_json.add(movement_detected ? "ON":"OFF");
|
||||
}
|
||||
}
|
||||
|
||||
void addToConfig(JsonObject& root)
|
||||
{
|
||||
JsonObject top = root.createNestedObject(FPSTR(_name));
|
||||
top[FPSTR(_enabled)] = enabled;
|
||||
//save these vars persistently whenever settings are saved
|
||||
top["uart_rx_pin"] = default_uart_rx;
|
||||
top["uart_tx_pin"] = default_uart_tx;
|
||||
}
|
||||
|
||||
|
||||
bool readFromConfig(JsonObject& root)
|
||||
{
|
||||
// default settings values could be set here (or below using the 3-argument getJsonValue()) instead of in the class definition or constructor
|
||||
// setting them inside readFromConfig() is slightly more robust, handling the rare but plausible use case of single value being missing after boot (e.g. if the cfg.json was manually edited and a value was removed)
|
||||
|
||||
JsonObject top = root[FPSTR(_name)];
|
||||
|
||||
bool configComplete = !top.isNull();
|
||||
if (!configComplete)
|
||||
{
|
||||
DEBUG_PRINT(FPSTR(_name));
|
||||
DEBUG_PRINT(F("LD2410"));
|
||||
DEBUG_PRINTLN(F(": No config found. (Using defaults.)"));
|
||||
return false;
|
||||
}
|
||||
|
||||
configComplete &= getJsonValue(top["uart_rx_pin"], uart_rx_pin, default_uart_rx);
|
||||
configComplete &= getJsonValue(top["uart_tx_pin"], uart_tx_pin, default_uart_tx);
|
||||
|
||||
return configComplete;
|
||||
}
|
||||
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
/**
|
||||
* onMqttConnect() is called when MQTT connection is established
|
||||
*/
|
||||
void onMqttConnect(bool sessionPresent) {
|
||||
// do any MQTT related initialisation here
|
||||
if(!radar.isConnected()) return;
|
||||
publishMqtt("/ld2410/status", "I am alive!", false);
|
||||
if (!mqttInitialized)
|
||||
{
|
||||
_mqttInitialize();
|
||||
mqttInitialized = true;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
uint16_t getId()
|
||||
{
|
||||
return USERMOD_ID_LD2410;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// add more strings here to reduce flash memory usage
|
||||
const char LD2410Usermod::_name[] PROGMEM = "LD2410Usermod";
|
||||
const char LD2410Usermod::_enabled[] PROGMEM = "enabled";
|
||||
|
||||
|
||||
// implementation of non-inline member methods
|
||||
|
||||
void LD2410Usermod::publishMqtt(const char* topic, const char* state, bool retain)
|
||||
{
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
//Check if MQTT Connected, otherwise it will crash
|
||||
if (WLED_MQTT_CONNECTED) {
|
||||
last_mqtt_sent = millis();
|
||||
char subuf[64];
|
||||
strcpy(subuf, mqttDeviceTopic);
|
||||
strcat(subuf, topic);
|
||||
mqtt->publish(subuf, 0, retain, state);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -58,7 +58,11 @@ private:
|
||||
bool sensorPinState[PIR_SENSOR_MAX_SENSORS] = {LOW}; // current PIR sensor pin state
|
||||
|
||||
// configurable parameters
|
||||
#if PIR_SENSOR_PIN < 0
|
||||
bool enabled = false; // PIR sensor disabled
|
||||
#else
|
||||
bool enabled = true; // PIR sensor enabled
|
||||
#endif
|
||||
int8_t PIRsensorPin[PIR_SENSOR_MAX_SENSORS] = {PIR_SENSOR_PIN}; // PIR sensor pin
|
||||
uint32_t m_switchOffDelay = PIR_SENSOR_OFF_SEC*1000; // delay before switch off after the sensor state goes LOW (10min)
|
||||
uint8_t m_onPreset = 0; // on preset
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
#include "wled.h"
|
||||
|
||||
//Pin defaults for QuinLed Dig-Uno (A0)
|
||||
#ifndef PHOTORESISTOR_PIN
|
||||
#define PHOTORESISTOR_PIN A0
|
||||
#endif
|
||||
|
||||
// the frequency to check photoresistor, 10 seconds
|
||||
#ifndef USERMOD_SN_PHOTORESISTOR_MEASUREMENT_INTERVAL
|
||||
@@ -207,4 +209,4 @@ const char Usermod_SN_Photoresistor::_readInterval[] PROGMEM = "read-interval-s"
|
||||
const char Usermod_SN_Photoresistor::_referenceVoltage[] PROGMEM = "supplied-voltage";
|
||||
const char Usermod_SN_Photoresistor::_resistorValue[] PROGMEM = "resistor-value";
|
||||
const char Usermod_SN_Photoresistor::_adcPrecision[] PROGMEM = "adc-precision";
|
||||
const char Usermod_SN_Photoresistor::_offset[] PROGMEM = "offset";
|
||||
const char Usermod_SN_Photoresistor::_offset[] PROGMEM = "offset";
|
||||
|
||||
@@ -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');"));
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
@@ -113,7 +113,7 @@ float UsermodTemperature::readDallas() {
|
||||
#ifdef WLED_DEBUG
|
||||
if (OneWire::crc8(data,8) != data[8]) {
|
||||
DEBUG_PRINTLN(F("CRC error reading temperature."));
|
||||
for (byte i=0; i < 9; i++) DEBUG_PRINTF_P(PSTR("0x%02X "), data[i]);
|
||||
for (unsigned i=0; i < 9; i++) DEBUG_PRINTF_P(PSTR("0x%02X "), data[i]);
|
||||
DEBUG_PRINT(F(" => "));
|
||||
DEBUG_PRINTF_P(PSTR("0x%02X\n"), OneWire::crc8(data,8));
|
||||
}
|
||||
@@ -133,7 +133,7 @@ float UsermodTemperature::readDallas() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (byte i=1; i<9; i++) data[0] &= data[i];
|
||||
for (unsigned i=1; i<9; i++) data[0] &= data[i];
|
||||
return data[0]==0xFF ? -127.0f : retVal;
|
||||
}
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ public:
|
||||
{
|
||||
if (width > 32)
|
||||
{
|
||||
throw std::invalid_argument("maximal width is 32");
|
||||
this->width = 32;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,6 +112,17 @@ public:
|
||||
{
|
||||
return pixels[y] == (uint32_t)((1 << width) - 1);
|
||||
}
|
||||
|
||||
void reset()
|
||||
{
|
||||
if (width > 32)
|
||||
{
|
||||
width = 32;
|
||||
}
|
||||
|
||||
pixels.clear();
|
||||
pixels.resize(height);
|
||||
}
|
||||
};
|
||||
|
||||
#endif /* __GRIDBW_H__ */
|
||||
@@ -127,6 +127,14 @@ public:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void reset()
|
||||
{
|
||||
gridBW.reset();
|
||||
pixels.clear();
|
||||
pixels.resize(width* height);
|
||||
clear();
|
||||
}
|
||||
};
|
||||
|
||||
#endif /* __GRIDCOLOR_H__ */
|
||||
@@ -32,7 +32,7 @@ public:
|
||||
uint8_t fullLines;
|
||||
uint16_t bumpiness;
|
||||
uint16_t aggregatedHeight;
|
||||
double score;
|
||||
float score;
|
||||
uint8_t width;
|
||||
std::vector<uint8_t> lineHights;
|
||||
|
||||
@@ -57,7 +57,7 @@ public:
|
||||
this->fullLines = 0;
|
||||
this->bumpiness = 0;
|
||||
this->aggregatedHeight = 0;
|
||||
this->score = -DBL_MAX;
|
||||
this->score = -FLT_MAX;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
# Tetris AI effect usermod
|
||||
|
||||
This usermod brings you a effect brings a self playing Tetris game. The mod needs version 0.14 or above as it is based on matrix support. The effect was tested on an ESP32 with a WS2812B 16x16 matrix.
|
||||
This usermod adds a self-playing Tetris game as an 'effect'. The mod requires version 0.14 or higher as it relies on matrix support. The effect was tested on an ESP32 4MB with a WS2812B 16x16 matrix.
|
||||
|
||||
Version 1.0
|
||||
|
||||
## Installation
|
||||
|
||||
Just activate the usermod with `-D USERMOD_TETRISAI` and the effect will become available under the name 'Tetris AI'.
|
||||
Just activate the usermod with `-D USERMOD_TETRISAI` and the effect will become available under the name 'Tetris AI'. If you are running out of flash memory, use a different memory layout (e.g. [WLED_ESP32_4MB_256KB_FS.csv](https://github.com/Aircoookie/WLED/blob/main/tools/WLED_ESP32_4MB_256KB_FS.csv)).
|
||||
|
||||
If needed simply add to `platformio_override.ini` (or `platformio_override.ini`):
|
||||
|
||||
```ini
|
||||
board_build.partitions = tools/WLED_ESP32_4MB_256KB_FS.csv
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
It is best to set the background color to black, the border color to light grey and the game over color (foreground) to dark grey.
|
||||
It is best to set the background color to black 🖤, the border color to light grey 🤍, the game over color (foreground) to dark grey 🩶, and color palette to 'Rainbow' 🌈.
|
||||
|
||||
### Sliders and boxes
|
||||
|
||||
@@ -19,15 +25,18 @@ It is best to set the background color to black, the border color to light grey
|
||||
* speed: speed the game plays
|
||||
* look ahead: how many pieces is the AI allowed to know the next pieces (0 - 2)
|
||||
* intelligence: how good the AI will play
|
||||
* Rotate color: make the colors shift (rotate) every few cicles
|
||||
* Mistakes free: how many good moves between mistakes (if activated)
|
||||
* Rotate color: make the colors shift (rotate) every few moves
|
||||
* Mistakes free: how many good moves between mistakes (if enabled)
|
||||
|
||||
#### Checkboxes
|
||||
|
||||
* show next: if true a space of 5 pixels from the right is used to show the next pieces. The whole segment is used for the grid otherwise.
|
||||
* show next: if true, a space of 5 pixels from the right will be used to show the next pieces. Otherwise the whole segment is used for the grid.
|
||||
* show border: if true an additional column of 1 pixel is used to draw a border between the grid and the next pieces
|
||||
* mistakes: if true the worst instead of the best move is choosen every few moves (read above)
|
||||
* mistakes: if true, the worst decision will be made every few moves instead of the best (see above).
|
||||
|
||||
## Best results
|
||||
|
||||
If the speed is set to be a little bit faster than a good human could play with maximal intelligence and very few mistakes it makes people furious/happy at a party.
|
||||
If the speed is set to be a little bit faster than a good human could play with maximal intelligence and very few mistakes it makes people furious/happy at a party 😉.
|
||||
|
||||
## Limits
|
||||
The game grid is limited to a maximum width of 32 and a maximum height of 255 due to the internal structure of the code. The canvas of the effect will be centred in the segment if the segment exceeds the maximum width or height.
|
||||
@@ -22,10 +22,10 @@ class TetrisAI
|
||||
{
|
||||
private:
|
||||
public:
|
||||
double aHeight;
|
||||
double fullLines;
|
||||
double holes;
|
||||
double bumpiness;
|
||||
float aHeight;
|
||||
float fullLines;
|
||||
float holes;
|
||||
float bumpiness;
|
||||
bool findWorstMove = false;
|
||||
|
||||
uint8_t countOnes(uint32_t vector)
|
||||
@@ -107,10 +107,10 @@ public:
|
||||
rating->score = (aHeight * (rating->aggregatedHeight)) + (fullLines * (rating->fullLines)) + (holes * (rating->holes)) + (bumpiness * (rating->bumpiness));
|
||||
}
|
||||
|
||||
TetrisAI(): TetrisAI(-0.510066, 0.760666, -0.35663, -0.184483)
|
||||
TetrisAI(): TetrisAI(-0.510066f, 0.760666f, -0.35663f, -0.184483f)
|
||||
{}
|
||||
|
||||
TetrisAI(double aHeight, double fullLines, double holes, double bumpiness):
|
||||
TetrisAI(float aHeight, float fullLines, float holes, float bumpiness):
|
||||
aHeight(aHeight),
|
||||
fullLines(fullLines),
|
||||
holes(holes),
|
||||
@@ -178,9 +178,9 @@ public:
|
||||
if(findWorstMove)
|
||||
{
|
||||
//init rating for worst
|
||||
if(bestRating->score == -DBL_MAX)
|
||||
if(bestRating->score == -FLT_MAX)
|
||||
{
|
||||
bestRating->score = DBL_MAX;
|
||||
bestRating->score = FLT_MAX;
|
||||
}
|
||||
|
||||
// update if we found a worse one
|
||||
@@ -202,101 +202,6 @@ public:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool findBestMoveNonBlocking(GridBW grid, std::vector<Piece>::iterator start, std::vector<Piece>::iterator end, Rating* bestRating)
|
||||
{
|
||||
//vector with pieces
|
||||
//for every piece
|
||||
//for every
|
||||
switch (expression)
|
||||
{
|
||||
case INIT:
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
bool findBestMoveNonBlocking(GridBW grid, std::vector<Piece>::iterator start, std::vector<Piece>::iterator end, Rating* bestRating)
|
||||
{
|
||||
//INIT
|
||||
grid.cleanupFullLines();
|
||||
Rating curRating(grid.width);
|
||||
Rating deeperRating(grid.width);
|
||||
Piece piece = *start;
|
||||
|
||||
// for every rotation of the piece
|
||||
piece.rotation = 0;
|
||||
|
||||
//HANDLE
|
||||
while (piece.rotation < piece.pieceData->rotCount)
|
||||
{
|
||||
// put piece to top left corner
|
||||
piece.x = 0;
|
||||
piece.y = 0;
|
||||
|
||||
//test for every column
|
||||
piece.x = 0;
|
||||
while (piece.x <= grid.width - piece.getRotation().width)
|
||||
{
|
||||
|
||||
//todo optimise by the use of the previous grids height
|
||||
piece.landingY = 0;
|
||||
//will set landingY to final position
|
||||
grid.findLandingPosition(&piece);
|
||||
|
||||
// draw piece
|
||||
grid.placePiece(&piece, piece.x, piece.landingY);
|
||||
|
||||
if(start == end - 1)
|
||||
{
|
||||
//at the deepest level
|
||||
updateRating(grid, &curRating);
|
||||
}
|
||||
else
|
||||
{
|
||||
//go deeper to take another piece into account
|
||||
findBestMove(grid, start + 1, end, &deeperRating);
|
||||
curRating = deeperRating;
|
||||
}
|
||||
|
||||
// eraese piece
|
||||
grid.erasePiece(&piece, piece.x, piece.landingY);
|
||||
|
||||
if(findWorstMove)
|
||||
{
|
||||
//init rating for worst
|
||||
if(bestRating->score == -DBL_MAX)
|
||||
{
|
||||
bestRating->score = DBL_MAX;
|
||||
}
|
||||
|
||||
// update if we found a worse one
|
||||
if (bestRating->score > curRating.score)
|
||||
{
|
||||
*bestRating = curRating;
|
||||
(*start) = piece;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// update if we found a better one
|
||||
if (bestRating->score < curRating.score)
|
||||
{
|
||||
*bestRating = curRating;
|
||||
(*start) = piece;
|
||||
}
|
||||
}
|
||||
piece.x++;
|
||||
}
|
||||
piece.rotation++;
|
||||
}
|
||||
|
||||
//EXIT
|
||||
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
#endif /* __AI_H__ */
|
||||
@@ -54,6 +54,7 @@ public:
|
||||
uint8_t width;
|
||||
uint8_t height;
|
||||
uint8_t nLookAhead;
|
||||
uint8_t nPieces;
|
||||
TetrisBag bag;
|
||||
GridColor grid;
|
||||
TetrisAI ai;
|
||||
@@ -65,6 +66,7 @@ public:
|
||||
width(width),
|
||||
height(height),
|
||||
nLookAhead(nLookAhead),
|
||||
nPieces(nPieces),
|
||||
bag(nPieces, 1, nLookAhead),
|
||||
grid(width, height + 4),
|
||||
ai(),
|
||||
@@ -142,8 +144,10 @@ public:
|
||||
|
||||
void reset()
|
||||
{
|
||||
grid.clear();
|
||||
bag.init();
|
||||
grid.width = width;
|
||||
grid.height = height + 4;
|
||||
grid.reset();
|
||||
bag.reset();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ private:
|
||||
public:
|
||||
uint8_t nPieces;
|
||||
uint8_t nBagLength;
|
||||
uint8_t queueLength;
|
||||
uint8_t bagIdx;
|
||||
std::vector<uint8_t> bag;
|
||||
std::vector<Piece> piecesQueue;
|
||||
@@ -32,6 +33,7 @@ public:
|
||||
TetrisBag(uint8_t nPieces, uint8_t nBagLength, uint8_t queueLength):
|
||||
nPieces(nPieces),
|
||||
nBagLength(nBagLength),
|
||||
queueLength(queueLength),
|
||||
bag(nPieces * nBagLength),
|
||||
piecesQueue(queueLength)
|
||||
{
|
||||
@@ -95,6 +97,15 @@ public:
|
||||
std::rotate(piecesQueue.begin(), piecesQueue.begin() + 1, piecesQueue.end());
|
||||
piecesQueue[piecesQueue.size() - 1] = Piece(idx % nPieces);
|
||||
}
|
||||
|
||||
void reset()
|
||||
{
|
||||
bag.clear();
|
||||
bag.resize(nPieces * nBagLength);
|
||||
piecesQueue.clear();
|
||||
piecesQueue.resize(queueLength);
|
||||
init();
|
||||
}
|
||||
};
|
||||
|
||||
#endif /* __TETRISBAG_H__ */
|
||||
|
||||
@@ -18,6 +18,12 @@ typedef struct TetrisAI_data
|
||||
uint8_t colorOffset;
|
||||
uint8_t colorInc;
|
||||
uint8_t mistaceCountdown;
|
||||
uint16_t segcols;
|
||||
uint16_t segrows;
|
||||
uint16_t segOffsetX;
|
||||
uint16_t segOffsetY;
|
||||
uint16_t effectWidth;
|
||||
uint16_t effectHeight;
|
||||
} tetrisai_data;
|
||||
|
||||
void drawGrid(TetrisAIGame* tetris, TetrisAI_data* tetrisai_data)
|
||||
@@ -49,7 +55,7 @@ void drawGrid(TetrisAIGame* tetris, TetrisAI_data* tetrisai_data)
|
||||
color = ColorFromPalette(SEGPALETTE, colorIndex, 255, NOBLEND);
|
||||
}
|
||||
|
||||
SEGMENT.setPixelColorXY(index_x, index_y - 4, color);
|
||||
SEGMENT.setPixelColorXY(tetrisai_data->segOffsetX + index_x, tetrisai_data->segOffsetY + index_y - 4, color);
|
||||
}
|
||||
}
|
||||
tetrisai_data->colorOffset += tetrisai_data->colorInc;
|
||||
@@ -61,14 +67,14 @@ void drawGrid(TetrisAIGame* tetris, TetrisAI_data* tetrisai_data)
|
||||
if (tetrisai_data->showBorder)
|
||||
{
|
||||
//draw a line 6 pixels from right with the border color
|
||||
for (auto index_y = 0; index_y < SEGMENT.virtualHeight(); index_y++)
|
||||
for (auto index_y = 0; index_y < tetrisai_data->effectHeight; index_y++)
|
||||
{
|
||||
SEGMENT.setPixelColorXY(SEGMENT.virtualWidth() - 6, index_y, SEGCOLOR(2));
|
||||
SEGMENT.setPixelColorXY(tetrisai_data->segOffsetX + tetrisai_data->effectWidth - 6, tetrisai_data->segOffsetY + index_y, SEGCOLOR(2));
|
||||
}
|
||||
}
|
||||
|
||||
//NEXT PIECE
|
||||
int piecesOffsetX = SEGMENT.virtualWidth() - 4;
|
||||
int piecesOffsetX = tetrisai_data->effectWidth - 4;
|
||||
int piecesOffsetY = 1;
|
||||
for (uint8_t nextPieceIdx = 1; nextPieceIdx < tetris->nLookAhead; nextPieceIdx++)
|
||||
{
|
||||
@@ -83,7 +89,7 @@ void drawGrid(TetrisAIGame* tetris, TetrisAI_data* tetrisai_data)
|
||||
if (piece.getPixel(pieceX, pieceY))
|
||||
{
|
||||
uint8_t colIdx = ((piece.pieceData->colorIndex * 32) + tetrisai_data->colorOffset);
|
||||
SEGMENT.setPixelColorXY(piecesOffsetX + pieceX, piecesOffsetY + pieceNbrOffsetY + pieceY, ColorFromPalette(SEGPALETTE, colIdx, 255, NOBLEND));
|
||||
SEGMENT.setPixelColorXY(tetrisai_data->segOffsetX + piecesOffsetX + pieceX, tetrisai_data->segOffsetY + piecesOffsetY + pieceNbrOffsetY + pieceY, ColorFromPalette(SEGPALETTE, colIdx, 255, NOBLEND));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -116,62 +122,86 @@ uint16_t mode_2DTetrisAI()
|
||||
//range 0 - 16
|
||||
tetrisai_data->colorInc = SEGMENT.custom2 >> 4;
|
||||
|
||||
if (!tetrisai_data->tetris || (tetrisai_data->tetris.nLookAhead != nLookAhead
|
||||
if (tetrisai_data->tetris.nLookAhead != nLookAhead
|
||||
|| tetrisai_data->segcols != cols
|
||||
|| tetrisai_data->segrows != rows
|
||||
|| tetrisai_data->showNext != SEGMENT.check1
|
||||
|| tetrisai_data->showBorder != SEGMENT.check2
|
||||
)
|
||||
)
|
||||
)
|
||||
{
|
||||
tetrisai_data->segcols = cols;
|
||||
tetrisai_data->segrows = rows;
|
||||
tetrisai_data->showNext = SEGMENT.check1;
|
||||
tetrisai_data->showBorder = SEGMENT.check2;
|
||||
|
||||
//not more than 32 as this is the limit of this implementation
|
||||
uint8_t gridWidth = cols < 32 ? cols : 32;
|
||||
uint8_t gridHeight = rows;
|
||||
//not more than 32 columns and 255 rows as this is the limit of this implementation
|
||||
uint8_t gridWidth = cols > 32 ? 32 : cols;
|
||||
uint8_t gridHeight = rows > 255 ? 255 : rows;
|
||||
|
||||
tetrisai_data->effectWidth = 0;
|
||||
tetrisai_data->effectHeight = 0;
|
||||
|
||||
// do we need space for the 'next' section?
|
||||
if (tetrisai_data->showNext)
|
||||
{
|
||||
// make space for the piece and one pixel of space
|
||||
gridWidth = gridWidth - 5;
|
||||
//does it get to tight?
|
||||
if (gridWidth + 5 > cols)
|
||||
{
|
||||
// yes, so make the grid smaller
|
||||
// make space for the piece and one pixel of space
|
||||
gridWidth = (gridWidth - ((gridWidth + 5) - cols));
|
||||
}
|
||||
tetrisai_data->effectWidth += 5;
|
||||
|
||||
// do we need space for a border?
|
||||
if (tetrisai_data->showBorder)
|
||||
{
|
||||
gridWidth = gridWidth - 1;
|
||||
if (gridWidth + 5 + 1 > cols)
|
||||
{
|
||||
gridWidth -= 1;
|
||||
}
|
||||
tetrisai_data->effectWidth += 1;
|
||||
}
|
||||
}
|
||||
|
||||
tetrisai_data->effectWidth += gridWidth;
|
||||
tetrisai_data->effectHeight += gridHeight;
|
||||
|
||||
tetrisai_data->segOffsetX = cols > tetrisai_data->effectWidth ? ((cols - tetrisai_data->effectWidth) / 2) : 0;
|
||||
tetrisai_data->segOffsetY = rows > tetrisai_data->effectHeight ? ((rows - tetrisai_data->effectHeight) / 2) : 0;
|
||||
|
||||
tetrisai_data->tetris = TetrisAIGame(gridWidth, gridHeight, nLookAhead, piecesData, numPieces);
|
||||
tetrisai_data->tetris.state = TetrisAIGame::States::INIT;
|
||||
SEGMENT.fill(SEGCOLOR(1));
|
||||
}
|
||||
|
||||
if (tetrisai_data->intelligence != SEGMENT.custom1)
|
||||
{
|
||||
tetrisai_data->intelligence = SEGMENT.custom1;
|
||||
double dui = 0.2 - (0.2 * (tetrisai_data->intelligence / 255.0));
|
||||
float dui = 0.2f - (0.2f * (tetrisai_data->intelligence / 255.0f));
|
||||
|
||||
tetrisai_data->tetris.ai.aHeight = -0.510066 + dui;
|
||||
tetrisai_data->tetris.ai.fullLines = 0.760666 - dui;
|
||||
tetrisai_data->tetris.ai.holes = -0.35663 + dui;
|
||||
tetrisai_data->tetris.ai.bumpiness = -0.184483 + dui;
|
||||
tetrisai_data->tetris.ai.aHeight = -0.510066f + dui;
|
||||
tetrisai_data->tetris.ai.fullLines = 0.760666f - dui;
|
||||
tetrisai_data->tetris.ai.holes = -0.35663f + dui;
|
||||
tetrisai_data->tetris.ai.bumpiness = -0.184483f + dui;
|
||||
}
|
||||
|
||||
if (tetrisai_data->tetris.state == TetrisAIGame::ANIMATE_MOVE)
|
||||
{
|
||||
if (millis() - tetrisai_data->lastTime > msDelayMove)
|
||||
|
||||
if (strip.now - tetrisai_data->lastTime > msDelayMove)
|
||||
{
|
||||
drawGrid(&tetrisai_data->tetris, tetrisai_data);
|
||||
tetrisai_data->lastTime = millis();
|
||||
tetrisai_data->lastTime = strip.now;
|
||||
tetrisai_data->tetris.poll();
|
||||
}
|
||||
}
|
||||
else if (tetrisai_data->tetris.state == TetrisAIGame::ANIMATE_GAME_OVER)
|
||||
{
|
||||
if (millis() - tetrisai_data->lastTime > msDelayGameOver)
|
||||
if (strip.now - tetrisai_data->lastTime > msDelayGameOver)
|
||||
{
|
||||
drawGrid(&tetrisai_data->tetris, tetrisai_data);
|
||||
tetrisai_data->lastTime = millis();
|
||||
tetrisai_data->lastTime = strip.now;
|
||||
tetrisai_data->tetris.poll();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#include "wled.h"
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
|
||||
#include <driver/i2s.h>
|
||||
#include <driver/adc.h>
|
||||
|
||||
@@ -8,11 +11,9 @@
|
||||
#error This audio reactive usermod is not compatible with DMX Out.
|
||||
#endif
|
||||
|
||||
#ifndef ARDUINO_ARCH_ESP32
|
||||
#error This audio reactive usermod does not support the ESP8266.
|
||||
#endif
|
||||
|
||||
#if defined(WLED_DEBUG) || defined(SR_DEBUG)
|
||||
#if defined(ARDUINO_ARCH_ESP32) && (defined(WLED_DEBUG) || defined(SR_DEBUG))
|
||||
#include <esp_timer.h>
|
||||
#endif
|
||||
|
||||
@@ -57,6 +58,50 @@
|
||||
|
||||
#define MAX_PALETTES 3
|
||||
|
||||
static volatile bool disableSoundProcessing = false; // if true, sound processing (FFT, filters, AGC) will be suspended. "volatile" as its shared between tasks.
|
||||
static uint8_t audioSyncEnabled = 0; // bit field: bit 0 - send, bit 1 - receive (config value)
|
||||
static bool udpSyncConnected = false; // UDP connection status -> true if connected to multicast group
|
||||
|
||||
#define NUM_GEQ_CHANNELS 16 // number of frequency channels. Don't change !!
|
||||
|
||||
// audioreactive variables
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
static float micDataReal = 0.0f; // MicIn data with full 24bit resolution - lowest 8bit after decimal point
|
||||
static float multAgc = 1.0f; // sample * multAgc = sampleAgc. Our AGC multiplier
|
||||
static float sampleAvg = 0.0f; // Smoothed Average sample - sampleAvg < 1 means "quiet" (simple noise gate)
|
||||
static float sampleAgc = 0.0f; // Smoothed AGC sample
|
||||
static uint8_t soundAgc = 0; // Automagic gain control: 0 - none, 1 - normal, 2 - vivid, 3 - lazy (config value)
|
||||
#endif
|
||||
//static float volumeSmth = 0.0f; // either sampleAvg or sampleAgc depending on soundAgc; smoothed sample
|
||||
static float FFT_MajorPeak = 1.0f; // FFT: strongest (peak) frequency
|
||||
static float FFT_Magnitude = 0.0f; // FFT: volume (magnitude) of peak frequency
|
||||
static bool samplePeak = false; // Boolean flag for peak - used in effects. Responding routine may reset this flag. Auto-reset after strip.getMinShowDelay()
|
||||
static bool udpSamplePeak = false; // Boolean flag for peak. Set at the same time as samplePeak, but reset by transmitAudioData
|
||||
static unsigned long timeOfPeak = 0; // time of last sample peak detection.
|
||||
static uint8_t fftResult[NUM_GEQ_CHANNELS]= {0};// Our calculated freq. channel result table to be used by effects
|
||||
|
||||
// TODO: probably best not used by receive nodes
|
||||
//static float agcSensitivity = 128; // AGC sensitivity estimation, based on agc gain (multAgc). calculated by getSensitivity(). range 0..255
|
||||
|
||||
// user settable parameters for limitSoundDynamics()
|
||||
#ifdef UM_AUDIOREACTIVE_DYNAMICS_LIMITER_OFF
|
||||
static bool limiterOn = false; // bool: enable / disable dynamics limiter
|
||||
#else
|
||||
static bool limiterOn = true;
|
||||
#endif
|
||||
static uint16_t attackTime = 80; // int: attack time in milliseconds. Default 0.08sec
|
||||
static uint16_t decayTime = 1400; // int: decay time in milliseconds. Default 1.40sec
|
||||
|
||||
// peak detection
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
static void detectSamplePeak(void); // peak detection function (needs scaled FFT results in vReal[]) - no used for 8266 receive-only mode
|
||||
#endif
|
||||
static void autoResetPeak(void); // peak auto-reset function
|
||||
static uint8_t maxVol = 31; // (was 10) Reasonable value for constant volume for 'peak detector', as it won't always trigger (deprecated)
|
||||
static uint8_t binNum = 8; // Used to select the bin for FFT based beat detection (deprecated)
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
|
||||
// use audio source class (ESP32 specific)
|
||||
#include "audio_source.h"
|
||||
constexpr i2s_port_t I2S_PORT = I2S_NUM_0; // I2S port to use (do not change !)
|
||||
@@ -74,18 +119,6 @@ static uint8_t inputLevel = 128; // UI slider value
|
||||
#else
|
||||
uint8_t sampleGain = SR_GAIN; // sample gain (config value)
|
||||
#endif
|
||||
static uint8_t soundAgc = 1; // Automagic gain control: 0 - none, 1 - normal, 2 - vivid, 3 - lazy (config value)
|
||||
static uint8_t audioSyncEnabled = 0; // bit field: bit 0 - send, bit 1 - receive (config value)
|
||||
static bool udpSyncConnected = false; // UDP connection status -> true if connected to multicast group
|
||||
|
||||
// user settable parameters for limitSoundDynamics()
|
||||
#ifdef UM_AUDIOREACTIVE_DYNAMICS_LIMITER_OFF
|
||||
static bool limiterOn = false; // bool: enable / disable dynamics limiter
|
||||
#else
|
||||
static bool limiterOn = true;
|
||||
#endif
|
||||
static uint16_t attackTime = 80; // int: attack time in milliseconds. Default 0.08sec
|
||||
static uint16_t decayTime = 1400; // int: decay time in milliseconds. Default 1.40sec
|
||||
// user settable options for FFTResult scaling
|
||||
static uint8_t FFTScalingMode = 3; // 0 none; 1 optimized logarithmic; 2 optimized linear; 3 optimized square root
|
||||
|
||||
@@ -109,25 +142,8 @@ const float agcSampleSmooth[AGC_NUM_PRESETS] = { 1/12.f, 1/6.f, 1/16.f}; //
|
||||
// AGC presets end
|
||||
|
||||
static AudioSource *audioSource = nullptr;
|
||||
static volatile bool disableSoundProcessing = false; // if true, sound processing (FFT, filters, AGC) will be suspended. "volatile" as its shared between tasks.
|
||||
static bool useBandPassFilter = false; // if true, enables a bandpass filter 80Hz-16Khz to remove noise. Applies before FFT.
|
||||
|
||||
// audioreactive variables shared with FFT task
|
||||
static float micDataReal = 0.0f; // MicIn data with full 24bit resolution - lowest 8bit after decimal point
|
||||
static float multAgc = 1.0f; // sample * multAgc = sampleAgc. Our AGC multiplier
|
||||
static float sampleAvg = 0.0f; // Smoothed Average sample - sampleAvg < 1 means "quiet" (simple noise gate)
|
||||
static float sampleAgc = 0.0f; // Smoothed AGC sample
|
||||
|
||||
// peak detection
|
||||
static bool samplePeak = false; // Boolean flag for peak - used in effects. Responding routine may reset this flag. Auto-reset after strip.getMinShowDelay()
|
||||
static uint8_t maxVol = 31; // Reasonable value for constant volume for 'peak detector', as it won't always trigger (deprecated)
|
||||
static uint8_t binNum = 8; // Used to select the bin for FFT based beat detection (deprecated)
|
||||
static bool udpSamplePeak = false; // Boolean flag for peak. Set at the same time as samplePeak, but reset by transmitAudioData
|
||||
static unsigned long timeOfPeak = 0; // time of last sample peak detection.
|
||||
static void detectSamplePeak(void); // peak detection function (needs scaled FFT results in vReal[])
|
||||
static void autoResetPeak(void); // peak auto-reset function
|
||||
|
||||
|
||||
////////////////////
|
||||
// Begin FFT Code //
|
||||
////////////////////
|
||||
@@ -139,17 +155,12 @@ void FFTcode(void * parameter); // audio processing task: read samples, run
|
||||
static void runMicFilter(uint16_t numSamples, float *sampleBuffer); // pre-filtering of raw samples (band-pass)
|
||||
static void postProcessFFTResults(bool noiseGateOpen, int numberOfChannels); // post-processing and post-amp of GEQ channels
|
||||
|
||||
#define NUM_GEQ_CHANNELS 16 // number of frequency channels. Don't change !!
|
||||
|
||||
static TaskHandle_t FFT_Task = nullptr;
|
||||
|
||||
// Table of multiplication factors so that we can even out the frequency response.
|
||||
static float fftResultPink[NUM_GEQ_CHANNELS] = { 1.70f, 1.71f, 1.73f, 1.78f, 1.68f, 1.56f, 1.55f, 1.63f, 1.79f, 1.62f, 1.80f, 2.06f, 2.47f, 3.35f, 6.83f, 9.55f };
|
||||
|
||||
// globals and FFT Output variables shared with animations
|
||||
static float FFT_MajorPeak = 1.0f; // FFT: strongest (peak) frequency
|
||||
static float FFT_Magnitude = 0.0f; // FFT: volume (magnitude) of peak frequency
|
||||
static uint8_t fftResult[NUM_GEQ_CHANNELS]= {0};// Our calculated freq. channel result table to be used by effects
|
||||
#if defined(WLED_DEBUG) || defined(SR_DEBUG)
|
||||
static uint64_t fftTime = 0;
|
||||
static uint64_t sampleTime = 0;
|
||||
@@ -522,6 +533,8 @@ static void detectSamplePeak(void) {
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
static void autoResetPeak(void) {
|
||||
uint16_t MinShowDelay = MAX(50, strip.getMinShowDelay()); // Fixes private class variable compiler error. Unsure if this is the correct way of fixing the root problem. -THATDONFC
|
||||
if (millis() - timeOfPeak > MinShowDelay) { // Auto-reset of samplePeak after a complete frame has passed.
|
||||
@@ -539,6 +552,8 @@ static void autoResetPeak(void) {
|
||||
class AudioReactive : public Usermod {
|
||||
|
||||
private:
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
|
||||
#ifndef AUDIOPIN
|
||||
int8_t audioPin = -1;
|
||||
#else
|
||||
@@ -570,20 +585,23 @@ class AudioReactive : public Usermod {
|
||||
#else
|
||||
int8_t mclkPin = MCLK_PIN;
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// new "V2" audiosync struct - 40 Bytes
|
||||
struct audioSyncPacket {
|
||||
char header[6]; // 06 Bytes
|
||||
float sampleRaw; // 04 Bytes - either "sampleRaw" or "rawSampleAgc" depending on soundAgc setting
|
||||
float sampleSmth; // 04 Bytes - either "sampleAvg" or "sampleAgc" depending on soundAgc setting
|
||||
uint8_t samplePeak; // 01 Bytes - 0 no peak; >=1 peak detected. In future, this will also provide peak Magnitude
|
||||
uint8_t reserved1; // 01 Bytes - for future extensions - not used yet
|
||||
uint8_t fftResult[16]; // 16 Bytes
|
||||
float FFT_Magnitude; // 04 Bytes
|
||||
float FFT_MajorPeak; // 04 Bytes
|
||||
// new "V2" audiosync struct - 44 Bytes
|
||||
struct __attribute__ ((packed)) audioSyncPacket { // "packed" ensures that there are no additional gaps
|
||||
char header[6]; // 06 Bytes offset 0
|
||||
uint8_t reserved1[2]; // 02 Bytes, offset 6 - gap required by the compiler - not used yet
|
||||
float sampleRaw; // 04 Bytes offset 8 - either "sampleRaw" or "rawSampleAgc" depending on soundAgc setting
|
||||
float sampleSmth; // 04 Bytes offset 12 - either "sampleAvg" or "sampleAgc" depending on soundAgc setting
|
||||
uint8_t samplePeak; // 01 Bytes offset 16 - 0 no peak; >=1 peak detected. In future, this will also provide peak Magnitude
|
||||
uint8_t reserved2; // 01 Bytes offset 17 - for future extensions - not used yet
|
||||
uint8_t fftResult[16]; // 16 Bytes offset 18
|
||||
uint16_t reserved3; // 02 Bytes, offset 34 - gap required by the compiler - not used yet
|
||||
float FFT_Magnitude; // 04 Bytes offset 36
|
||||
float FFT_MajorPeak; // 04 Bytes offset 40
|
||||
};
|
||||
|
||||
// old "V1" audiosync struct - 83 Bytes - for backwards compatibility
|
||||
// old "V1" audiosync struct - 83 Bytes payload, 88 bytes total (with padding added by compiler) - for backwards compatibility
|
||||
struct audioSyncPacket_v1 {
|
||||
char header[6]; // 06 Bytes
|
||||
uint8_t myVals[32]; // 32 Bytes
|
||||
@@ -596,6 +614,8 @@ class AudioReactive : public Usermod {
|
||||
double FFT_MajorPeak; // 08 Bytes
|
||||
};
|
||||
|
||||
#define UDPSOUND_MAX_PACKET 88 // max packet size for audiosync
|
||||
|
||||
// set your config variables to their boot default value (this can also be done in readFromConfig() or a constructor if you prefer)
|
||||
#ifdef UM_AUDIOREACTIVE_ENABLE
|
||||
bool enabled = true;
|
||||
@@ -613,10 +633,14 @@ class AudioReactive : public Usermod {
|
||||
const uint16_t delayMs = 10; // I don't want to sample too often and overload WLED
|
||||
uint16_t audioSyncPort= 11988;// default port for UDP sound sync
|
||||
|
||||
bool updateIsRunning = false; // true during OTA.
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
// used for AGC
|
||||
int last_soundAgc = -1; // used to detect AGC mode change (for resetting AGC internal error buffers)
|
||||
double control_integrated = 0.0; // persistent across calls to agcAvg(); "integrator control" = accumulated error
|
||||
|
||||
|
||||
// variables used by getSample() and agcAvg()
|
||||
int16_t micIn = 0; // Current sample starts with negative values and large values, which is why it's 16 bit signed
|
||||
double sampleMax = 0.0; // Max sample over a few seconds. Needed for AGC controller.
|
||||
@@ -625,6 +649,7 @@ class AudioReactive : public Usermod {
|
||||
float sampleReal = 0.0f; // "sampleRaw" as float, to provide bits that are lost otherwise (before amplification by sampleGain or inputLevel). Needed for AGC.
|
||||
int16_t sampleRaw = 0; // Current sample. Must only be updated ONCE!!! (amplified mic value by sampleGain and inputLevel)
|
||||
int16_t rawSampleAgc = 0; // not smoothed AGC sample
|
||||
#endif
|
||||
|
||||
// variables used in effects
|
||||
float volumeSmth = 0.0f; // either sampleAvg or sampleAgc depending on soundAgc; smoothed sample
|
||||
@@ -645,7 +670,9 @@ class AudioReactive : public Usermod {
|
||||
static const char _dynamics[];
|
||||
static const char _frequency[];
|
||||
static const char _inputLvl[];
|
||||
#if defined(ARDUINO_ARCH_ESP32) && !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3) && !defined(CONFIG_IDF_TARGET_ESP32S3)
|
||||
static const char _analogmic[];
|
||||
#endif
|
||||
static const char _digitalmic[];
|
||||
static const char _addPalettes[];
|
||||
static const char UDP_SYNC_HEADER[];
|
||||
@@ -672,11 +699,13 @@ class AudioReactive : public Usermod {
|
||||
//PLOT_PRINT("sampleAgc:"); PLOT_PRINT(sampleAgc); PLOT_PRINT("\t");
|
||||
//PLOT_PRINT("sampleAvg:"); PLOT_PRINT(sampleAvg); PLOT_PRINT("\t");
|
||||
//PLOT_PRINT("sampleReal:"); PLOT_PRINT(sampleReal); PLOT_PRINT("\t");
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
//PLOT_PRINT("micIn:"); PLOT_PRINT(micIn); PLOT_PRINT("\t");
|
||||
//PLOT_PRINT("sample:"); PLOT_PRINT(sample); PLOT_PRINT("\t");
|
||||
//PLOT_PRINT("sampleMax:"); PLOT_PRINT(sampleMax); PLOT_PRINT("\t");
|
||||
//PLOT_PRINT("samplePeak:"); PLOT_PRINT((samplePeak!=0) ? 128:0); PLOT_PRINT("\t");
|
||||
//PLOT_PRINT("multAgc:"); PLOT_PRINT(multAgc, 4); PLOT_PRINT("\t");
|
||||
#endif
|
||||
PLOT_PRINTLN();
|
||||
#endif
|
||||
|
||||
@@ -732,6 +761,7 @@ class AudioReactive : public Usermod {
|
||||
} // logAudio()
|
||||
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
//////////////////////
|
||||
// Audio Processing //
|
||||
//////////////////////
|
||||
@@ -902,6 +932,7 @@ class AudioReactive : public Usermod {
|
||||
sampleAvg = fabsf(sampleAvg); // make sure we have a positive value
|
||||
} // getSample()
|
||||
|
||||
#endif
|
||||
|
||||
/* Limits the dynamics of volumeSmth (= sampleAvg or sampleAgc).
|
||||
* does not affect FFTResult[] or volumeRaw ( = sample or rawSampleAgc)
|
||||
@@ -948,12 +979,14 @@ class AudioReactive : public Usermod {
|
||||
if (udpSyncConnected) return; // already connected
|
||||
if (!(apActive || interfacesInited)) return; // neither AP nor other connections availeable
|
||||
if (millis() - last_connection_attempt < 15000) return; // only try once in 15 seconds
|
||||
if (updateIsRunning) return;
|
||||
|
||||
// if we arrive here, we need a UDP connection but don't have one
|
||||
last_connection_attempt = millis();
|
||||
connected(); // try to start UDP
|
||||
}
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
void transmitAudioData()
|
||||
{
|
||||
if (!udpSyncConnected) return;
|
||||
@@ -968,7 +1001,6 @@ class AudioReactive : public Usermod {
|
||||
transmitData.sampleSmth = (soundAgc) ? sampleAgc : sampleAvg;
|
||||
transmitData.samplePeak = udpSamplePeak ? 1:0;
|
||||
udpSamplePeak = false; // Reset udpSamplePeak after we've transmitted it
|
||||
transmitData.reserved1 = 0;
|
||||
|
||||
for (int i = 0; i < NUM_GEQ_CHANNELS; i++) {
|
||||
transmitData.fftResult[i] = (uint8_t)constrain(fftResult[i], 0, 254);
|
||||
@@ -984,37 +1016,44 @@ class AudioReactive : public Usermod {
|
||||
return;
|
||||
} // transmitAudioData()
|
||||
|
||||
#endif
|
||||
|
||||
static bool isValidUdpSyncVersion(const char *header) {
|
||||
return strncmp_P(header, PSTR(UDP_SYNC_HEADER), 6) == 0;
|
||||
return strncmp_P(header, UDP_SYNC_HEADER, 6) == 0;
|
||||
}
|
||||
static bool isValidUdpSyncVersion_v1(const char *header) {
|
||||
return strncmp_P(header, PSTR(UDP_SYNC_HEADER_v1), 6) == 0;
|
||||
return strncmp_P(header, UDP_SYNC_HEADER_v1, 6) == 0;
|
||||
}
|
||||
|
||||
void decodeAudioData(int packetSize, uint8_t *fftBuff) {
|
||||
audioSyncPacket *receivedPacket = reinterpret_cast<audioSyncPacket*>(fftBuff);
|
||||
audioSyncPacket receivedPacket;
|
||||
memset(&receivedPacket, 0, sizeof(receivedPacket)); // start clean
|
||||
memcpy(&receivedPacket, fftBuff, min((unsigned)packetSize, (unsigned)sizeof(receivedPacket))); // don't violate alignment - thanks @willmmiles#
|
||||
|
||||
// update samples for effects
|
||||
volumeSmth = fmaxf(receivedPacket->sampleSmth, 0.0f);
|
||||
volumeRaw = fmaxf(receivedPacket->sampleRaw, 0.0f);
|
||||
volumeSmth = fmaxf(receivedPacket.sampleSmth, 0.0f);
|
||||
volumeRaw = fmaxf(receivedPacket.sampleRaw, 0.0f);
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
// update internal samples
|
||||
sampleRaw = volumeRaw;
|
||||
sampleAvg = volumeSmth;
|
||||
rawSampleAgc = volumeRaw;
|
||||
sampleAgc = volumeSmth;
|
||||
multAgc = 1.0f;
|
||||
#endif
|
||||
// Only change samplePeak IF it's currently false.
|
||||
// If it's true already, then the animation still needs to respond.
|
||||
autoResetPeak();
|
||||
if (!samplePeak) {
|
||||
samplePeak = receivedPacket->samplePeak >0 ? true:false;
|
||||
samplePeak = receivedPacket.samplePeak >0 ? true:false;
|
||||
if (samplePeak) timeOfPeak = millis();
|
||||
//userVar1 = samplePeak;
|
||||
}
|
||||
//These values are only available on the ESP32
|
||||
for (int i = 0; i < NUM_GEQ_CHANNELS; i++) fftResult[i] = receivedPacket->fftResult[i];
|
||||
my_magnitude = fmaxf(receivedPacket->FFT_Magnitude, 0.0f);
|
||||
//These values are only computed by ESP32
|
||||
for (int i = 0; i < NUM_GEQ_CHANNELS; i++) fftResult[i] = receivedPacket.fftResult[i];
|
||||
my_magnitude = fmaxf(receivedPacket.FFT_Magnitude, 0.0f);
|
||||
FFT_Magnitude = my_magnitude;
|
||||
FFT_MajorPeak = constrain(receivedPacket->FFT_MajorPeak, 1.0f, 11025.0f); // restrict value to range expected by effects
|
||||
FFT_MajorPeak = constrain(receivedPacket.FFT_MajorPeak, 1.0f, 11025.0f); // restrict value to range expected by effects
|
||||
}
|
||||
|
||||
void decodeAudioData_v1(int packetSize, uint8_t *fftBuff) {
|
||||
@@ -1022,12 +1061,14 @@ class AudioReactive : public Usermod {
|
||||
// update samples for effects
|
||||
volumeSmth = fmaxf(receivedPacket->sampleAgc, 0.0f);
|
||||
volumeRaw = volumeSmth; // V1 format does not have "raw" AGC sample
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
// update internal samples
|
||||
sampleRaw = fmaxf(receivedPacket->sampleRaw, 0.0f);
|
||||
sampleAvg = fmaxf(receivedPacket->sampleAvg, 0.0f);;
|
||||
sampleAgc = volumeSmth;
|
||||
rawSampleAgc = volumeRaw;
|
||||
multAgc = 1.0f;
|
||||
multAgc = 1.0f;
|
||||
#endif
|
||||
// Only change samplePeak IF it's currently false.
|
||||
// If it's true already, then the animation still needs to respond.
|
||||
autoResetPeak();
|
||||
@@ -1049,9 +1090,12 @@ class AudioReactive : public Usermod {
|
||||
bool haveFreshData = false;
|
||||
|
||||
size_t packetSize = fftUdp.parsePacket();
|
||||
if (packetSize > 5) {
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
if ((packetSize > 0) && ((packetSize < 5) || (packetSize > UDPSOUND_MAX_PACKET))) fftUdp.flush(); // discard invalid packets (too small or too big) - only works on esp32
|
||||
#endif
|
||||
if ((packetSize > 5) && (packetSize <= UDPSOUND_MAX_PACKET)) {
|
||||
//DEBUGSR_PRINTLN("Received UDP Sync Packet");
|
||||
uint8_t fftBuff[packetSize];
|
||||
uint8_t fftBuff[UDPSOUND_MAX_PACKET+1] = { 0 }; // fixed-size buffer for receiving (stack), to avoid heap fragmentation caused by variable sized arrays
|
||||
fftUdp.read(fftBuff, packetSize);
|
||||
|
||||
// VERIFY THAT THIS IS A COMPATIBLE PACKET
|
||||
@@ -1113,6 +1157,9 @@ class AudioReactive : public Usermod {
|
||||
um_data->u_type[7] = UMT_BYTE;
|
||||
}
|
||||
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
|
||||
// Reset I2S peripheral for good measure
|
||||
i2s_driver_uninstall(I2S_NUM_0); // E (696) I2S: i2s_driver_uninstall(2006): I2S port 0 has not installed
|
||||
#if !defined(CONFIG_IDF_TARGET_ESP32C3)
|
||||
@@ -1190,10 +1237,12 @@ class AudioReactive : public Usermod {
|
||||
delay(250); // give microphone enough time to initialise
|
||||
|
||||
if (!audioSource) enabled = false; // audio failed to initialise
|
||||
if (enabled) onUpdateBegin(false); // create FFT task
|
||||
if (FFT_Task == nullptr) enabled = false; // FFT task creation failed
|
||||
if (enabled) disableSoundProcessing = false; // all good - enable audio processing
|
||||
#endif
|
||||
if (enabled) onUpdateBegin(false); // create FFT task, and initialize network
|
||||
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
if (FFT_Task == nullptr) enabled = false; // FFT task creation failed
|
||||
if((!audioSource) || (!audioSource->isInitialized())) { // audio source failed to initialize. Still stay "enabled", as there might be input arriving via UDP Sound Sync
|
||||
#ifdef WLED_DEBUG
|
||||
DEBUG_PRINTLN(F("AR: Failed to initialize sound input driver. Please check input PIN settings."));
|
||||
@@ -1202,7 +1251,8 @@ class AudioReactive : public Usermod {
|
||||
#endif
|
||||
disableSoundProcessing = true;
|
||||
}
|
||||
|
||||
#endif
|
||||
if (enabled) disableSoundProcessing = false; // all good - enable audio processing
|
||||
if (enabled) connectUDPSoundSync();
|
||||
if (enabled && addPalettes) createAudioPalettes();
|
||||
initDone = true;
|
||||
@@ -1221,7 +1271,7 @@ class AudioReactive : public Usermod {
|
||||
}
|
||||
|
||||
if (audioSyncPort > 0 && (audioSyncEnabled & 0x03)) {
|
||||
#ifndef ESP8266
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
udpSyncConnected = fftUdp.beginMulticast(IPAddress(239, 0, 0, 1), audioSyncPort);
|
||||
#else
|
||||
udpSyncConnected = fftUdp.beginMulticast(WiFi.localIP(), IPAddress(239, 0, 0, 1), audioSyncPort);
|
||||
@@ -1260,7 +1310,7 @@ class AudioReactive : public Usermod {
|
||||
||(realtimeMode == REALTIME_MODE_ADALIGHT)
|
||||
||(realtimeMode == REALTIME_MODE_ARTNET) ) ) // please add other modes here if needed
|
||||
{
|
||||
#ifdef WLED_DEBUG
|
||||
#if defined(ARDUINO_ARCH_ESP32) && defined(WLED_DEBUG)
|
||||
if ((disableSoundProcessing == false) && (audioSyncEnabled == 0)) { // we just switched to "disabled"
|
||||
DEBUG_PRINTLN(F("[AR userLoop] realtime mode active - audio processing suspended."));
|
||||
DEBUG_PRINTF_P(PSTR(" RealtimeMode = %d; RealtimeOverride = %d\n"), int(realtimeMode), int(realtimeOverride));
|
||||
@@ -1268,7 +1318,7 @@ class AudioReactive : public Usermod {
|
||||
#endif
|
||||
disableSoundProcessing = true;
|
||||
} else {
|
||||
#ifdef WLED_DEBUG
|
||||
#if defined(ARDUINO_ARCH_ESP32) && defined(WLED_DEBUG)
|
||||
if ((disableSoundProcessing == true) && (audioSyncEnabled == 0) && audioSource->isInitialized()) { // we just switched to "enabled"
|
||||
DEBUG_PRINTLN(F("[AR userLoop] realtime mode ended - audio processing resumed."));
|
||||
DEBUG_PRINTF_P(PSTR(" RealtimeMode = %d; RealtimeOverride = %d\n"), int(realtimeMode), int(realtimeOverride));
|
||||
@@ -1280,6 +1330,7 @@ class AudioReactive : public Usermod {
|
||||
|
||||
if (audioSyncEnabled & 0x02) disableSoundProcessing = true; // make sure everything is disabled IF in audio Receive mode
|
||||
if (audioSyncEnabled & 0x01) disableSoundProcessing = false; // keep running audio IF we're in audio Transmit mode
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
if (!audioSource->isInitialized()) disableSoundProcessing = true; // no audio source
|
||||
|
||||
|
||||
@@ -1319,6 +1370,7 @@ class AudioReactive : public Usermod {
|
||||
|
||||
limitSampleDynamics();
|
||||
} // if (!disableSoundProcessing)
|
||||
#endif
|
||||
|
||||
autoResetPeak(); // auto-reset sample peak after strip minShowDelay
|
||||
if (!udpSyncConnected) udpSamplePeak = false; // reset UDP samplePeak while UDP is unconnected
|
||||
@@ -1352,6 +1404,7 @@ class AudioReactive : public Usermod {
|
||||
#endif
|
||||
|
||||
// Info Page: keep max sample from last 5 seconds
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
if ((millis() - sampleMaxTimer) > CYCLE_SAMPLEMAX) {
|
||||
sampleMaxTimer = millis();
|
||||
maxSample5sec = (0.15f * maxSample5sec) + 0.85f *((soundAgc) ? sampleAgc : sampleAvg); // reset, and start with some smoothing
|
||||
@@ -1359,13 +1412,25 @@ class AudioReactive : public Usermod {
|
||||
} else {
|
||||
if ((sampleAvg >= 1)) maxSample5sec = fmaxf(maxSample5sec, (soundAgc) ? rawSampleAgc : sampleRaw); // follow maximum volume
|
||||
}
|
||||
#else // similar functionality for 8266 receive only - use VolumeSmth instead of raw sample data
|
||||
if ((millis() - sampleMaxTimer) > CYCLE_SAMPLEMAX) {
|
||||
sampleMaxTimer = millis();
|
||||
maxSample5sec = (0.15 * maxSample5sec) + 0.85 * volumeSmth; // reset, and start with some smoothing
|
||||
if (volumeSmth < 1.0f) maxSample5sec = 0; // noise gate
|
||||
if (maxSample5sec < 0.0f) maxSample5sec = 0; // avoid negative values
|
||||
} else {
|
||||
if (volumeSmth >= 1.0f) maxSample5sec = fmaxf(maxSample5sec, volumeRaw); // follow maximum volume
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
//UDP Microphone Sync - transmit mode
|
||||
if ((audioSyncEnabled & 0x01) && (millis() - lastTime > 20)) {
|
||||
// Only run the transmit code IF we're in Transmit mode
|
||||
transmitAudioData();
|
||||
lastTime = millis();
|
||||
}
|
||||
#endif
|
||||
|
||||
fillAudioPalettes();
|
||||
}
|
||||
@@ -1378,7 +1443,7 @@ class AudioReactive : public Usermod {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
void onUpdateBegin(bool init) override
|
||||
{
|
||||
#ifdef WLED_DEBUG
|
||||
@@ -1427,9 +1492,32 @@ class AudioReactive : public Usermod {
|
||||
}
|
||||
micDataReal = 0.0f; // just to be sure
|
||||
if (enabled) disableSoundProcessing = false;
|
||||
updateIsRunning = init;
|
||||
}
|
||||
|
||||
#else // reduced function for 8266
|
||||
void onUpdateBegin(bool init)
|
||||
{
|
||||
// gracefully suspend audio (if running)
|
||||
disableSoundProcessing = true;
|
||||
// reset sound data
|
||||
volumeRaw = 0; volumeSmth = 0;
|
||||
for(int i=(init?0:1); i<NUM_GEQ_CHANNELS; i+=2) fftResult[i] = 16; // make a tiny pattern
|
||||
autoResetPeak();
|
||||
if (init) {
|
||||
if (udpSyncConnected) { // close UDP sync connection (if open)
|
||||
udpSyncConnected = false;
|
||||
fftUdp.stop();
|
||||
DEBUGSR_PRINTLN(F("AR onUpdateBegin(true): UDP connection closed."));
|
||||
receivedFormat = 0;
|
||||
}
|
||||
}
|
||||
if (enabled) disableSoundProcessing = init; // init = true means that OTA is just starting --> don't process audio
|
||||
updateIsRunning = init;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
/**
|
||||
* handleButton() can be used to override default button behaviour. Returning true
|
||||
* will prevent button working in a default way.
|
||||
@@ -1447,7 +1535,7 @@ class AudioReactive : public Usermod {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
#endif
|
||||
////////////////////////////
|
||||
// Settings and Info Page //
|
||||
////////////////////////////
|
||||
@@ -1459,7 +1547,9 @@ class AudioReactive : public Usermod {
|
||||
*/
|
||||
void addToJsonInfo(JsonObject& root) override
|
||||
{
|
||||
char myStringBuffer[16]; // buffer for snprintf()
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
char myStringBuffer[16]; // buffer for snprintf() - not used yet on 8266
|
||||
#endif
|
||||
JsonObject user = root["u"];
|
||||
if (user.isNull()) user = root.createNestedObject("u");
|
||||
|
||||
@@ -1477,6 +1567,7 @@ class AudioReactive : public Usermod {
|
||||
infoArr.add(uiDomString);
|
||||
|
||||
if (enabled) {
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
// Input Level Slider
|
||||
if (disableSoundProcessing == false) { // only show slider when audio processing is running
|
||||
if (soundAgc > 0) {
|
||||
@@ -1493,7 +1584,7 @@ class AudioReactive : public Usermod {
|
||||
uiDomString += F(" /><div class=\"sliderdisplay\"></div></div></div>"); //<output class=\"sliderbubble\"></output>
|
||||
infoArr.add(uiDomString);
|
||||
}
|
||||
|
||||
#endif
|
||||
// The following can be used for troubleshooting user errors and is so not enclosed in #ifdef WLED_DEBUG
|
||||
|
||||
// current Audio input
|
||||
@@ -1509,6 +1600,11 @@ class AudioReactive : public Usermod {
|
||||
} else {
|
||||
infoArr.add(F(" - no connection"));
|
||||
}
|
||||
#ifndef ARDUINO_ARCH_ESP32 // substitute for 8266
|
||||
} else {
|
||||
infoArr.add(F("sound sync Off"));
|
||||
}
|
||||
#else // ESP32 only
|
||||
} else {
|
||||
// Analog or I2S digital input
|
||||
if (audioSource && (audioSource->isInitialized())) {
|
||||
@@ -1553,7 +1649,7 @@ class AudioReactive : public Usermod {
|
||||
infoArr.add(roundf(multAgc*100.0f) / 100.0f);
|
||||
infoArr.add("x");
|
||||
}
|
||||
|
||||
#endif
|
||||
// UDP Sound Sync status
|
||||
infoArr = user.createNestedArray(F("UDP Sound Sync"));
|
||||
if (audioSyncEnabled) {
|
||||
@@ -1572,6 +1668,7 @@ class AudioReactive : public Usermod {
|
||||
}
|
||||
|
||||
#if defined(WLED_DEBUG) || defined(SR_DEBUG)
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
infoArr = user.createNestedArray(F("Sampling time"));
|
||||
infoArr.add(float(sampleTime)/100.0f);
|
||||
infoArr.add(" ms");
|
||||
@@ -1588,6 +1685,7 @@ class AudioReactive : public Usermod {
|
||||
DEBUGSR_PRINTF("AR Sampling time: %5.2f ms\n", float(sampleTime)/100.0f);
|
||||
DEBUGSR_PRINTF("AR FFT time : %5.2f ms\n", float(fftTime)/100.0f);
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1626,9 +1724,11 @@ class AudioReactive : public Usermod {
|
||||
if (!prevEnabled && enabled) createAudioPalettes();
|
||||
}
|
||||
}
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
if (usermod[FPSTR(_inputLvl)].is<int>()) {
|
||||
inputLevel = min(255,max(0,usermod[FPSTR(_inputLvl)].as<int>()));
|
||||
}
|
||||
#endif
|
||||
}
|
||||
if (root.containsKey(F("rmcpal")) && root[F("rmcpal")].as<bool>()) {
|
||||
// handle removal of custom palettes from JSON call so we don't break things
|
||||
@@ -1684,6 +1784,7 @@ class AudioReactive : public Usermod {
|
||||
top[FPSTR(_enabled)] = enabled;
|
||||
top[FPSTR(_addPalettes)] = addPalettes;
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
#if !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3) && !defined(CONFIG_IDF_TARGET_ESP32S3)
|
||||
JsonObject amic = top.createNestedObject(FPSTR(_analogmic));
|
||||
amic["pin"] = audioPin;
|
||||
@@ -1702,14 +1803,15 @@ class AudioReactive : public Usermod {
|
||||
cfg[F("gain")] = sampleGain;
|
||||
cfg[F("AGC")] = soundAgc;
|
||||
|
||||
JsonObject freqScale = top.createNestedObject(FPSTR(_frequency));
|
||||
freqScale[F("scale")] = FFTScalingMode;
|
||||
#endif
|
||||
|
||||
JsonObject dynLim = top.createNestedObject(FPSTR(_dynamics));
|
||||
dynLim[F("limiter")] = limiterOn;
|
||||
dynLim[F("rise")] = attackTime;
|
||||
dynLim[F("fall")] = decayTime;
|
||||
|
||||
JsonObject freqScale = top.createNestedObject(FPSTR(_frequency));
|
||||
freqScale[F("scale")] = FFTScalingMode;
|
||||
|
||||
JsonObject sync = top.createNestedObject("sync");
|
||||
sync["port"] = audioSyncPort;
|
||||
sync["mode"] = audioSyncEnabled;
|
||||
@@ -1741,6 +1843,7 @@ class AudioReactive : public Usermod {
|
||||
configComplete &= getJsonValue(top[FPSTR(_enabled)], enabled);
|
||||
configComplete &= getJsonValue(top[FPSTR(_addPalettes)], addPalettes);
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
#if !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3) && !defined(CONFIG_IDF_TARGET_ESP32S3)
|
||||
configComplete &= getJsonValue(top[FPSTR(_analogmic)]["pin"], audioPin);
|
||||
#else
|
||||
@@ -1764,12 +1867,12 @@ class AudioReactive : public Usermod {
|
||||
configComplete &= getJsonValue(top[FPSTR(_config)][F("gain")], sampleGain);
|
||||
configComplete &= getJsonValue(top[FPSTR(_config)][F("AGC")], soundAgc);
|
||||
|
||||
configComplete &= getJsonValue(top[FPSTR(_frequency)][F("scale")], FFTScalingMode);
|
||||
|
||||
configComplete &= getJsonValue(top[FPSTR(_dynamics)][F("limiter")], limiterOn);
|
||||
configComplete &= getJsonValue(top[FPSTR(_dynamics)][F("rise")], attackTime);
|
||||
configComplete &= getJsonValue(top[FPSTR(_dynamics)][F("fall")], decayTime);
|
||||
|
||||
configComplete &= getJsonValue(top[FPSTR(_frequency)][F("scale")], FFTScalingMode);
|
||||
|
||||
#endif
|
||||
configComplete &= getJsonValue(top["sync"]["port"], audioSyncPort);
|
||||
configComplete &= getJsonValue(top["sync"]["mode"], audioSyncEnabled);
|
||||
|
||||
@@ -1784,6 +1887,7 @@ class AudioReactive : public Usermod {
|
||||
|
||||
void appendConfigData() override
|
||||
{
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
oappend(SET_F("dd=addDropdown('AudioReactive','digitalmic:type');"));
|
||||
#if !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3) && !defined(CONFIG_IDF_TARGET_ESP32S3)
|
||||
oappend(SET_F("addOption(dd,'Generic Analog',0);"));
|
||||
@@ -1815,11 +1919,15 @@ class AudioReactive : public Usermod {
|
||||
oappend(SET_F("addOption(dd,'Linear (Amplitude)',2);"));
|
||||
oappend(SET_F("addOption(dd,'Square Root (Energy)',3);"));
|
||||
oappend(SET_F("addOption(dd,'Logarithmic (Loudness)',1);"));
|
||||
#endif
|
||||
|
||||
oappend(SET_F("dd=addDropdown('AudioReactive','sync:mode');"));
|
||||
oappend(SET_F("addOption(dd,'Off',0);"));
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
oappend(SET_F("addOption(dd,'Send',1);"));
|
||||
#endif
|
||||
oappend(SET_F("addOption(dd,'Receive',2);"));
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
oappend(SET_F("addInfo('AudioReactive:digitalmic:type',1,'<i>requires reboot!</i>');")); // 0 is field type, 1 is actual field
|
||||
oappend(SET_F("addInfo('AudioReactive:digitalmic:pin[]',0,'<i>sd/data/dout</i>','I2S SD');"));
|
||||
oappend(SET_F("addInfo('AudioReactive:digitalmic:pin[]',1,'<i>ws/clk/lrck</i>','I2S WS');"));
|
||||
@@ -1829,6 +1937,7 @@ class AudioReactive : public Usermod {
|
||||
#else
|
||||
oappend(SET_F("addInfo('AudioReactive:digitalmic:pin[]',3,'<i>master clock</i>','I2S MCLK');"));
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
@@ -1907,8 +2016,8 @@ CRGB AudioReactive::getCRGBForBand(int x, int pal) {
|
||||
void AudioReactive::fillAudioPalettes() {
|
||||
if (!palettes) return;
|
||||
size_t lastCustPalette = strip.customPalettes.size();
|
||||
if (lastCustPalette >= palettes) lastCustPalette -= palettes;
|
||||
for (size_t pal=0; pal<palettes; pal++) {
|
||||
if (int(lastCustPalette) >= palettes) lastCustPalette -= palettes;
|
||||
for (int pal=0; pal<palettes; pal++) {
|
||||
uint8_t tcp[16]; // Needs to be 4 times however many colors are being used.
|
||||
// 3 colors = 12, 4 colors = 16, etc.
|
||||
|
||||
|
||||
@@ -87,11 +87,11 @@ class MPU6050Driver : public Usermod {
|
||||
int16_t accel_offset[3];
|
||||
};
|
||||
config_t config;
|
||||
bool configDirty = true; // does the configuration need an update?
|
||||
|
||||
// MPU control/status vars
|
||||
bool irqBound = false; // set true if we have bound the IRQ pin
|
||||
bool dmpReady = false; // set true if DMP init was successful
|
||||
uint8_t devStatus; // return status after each device operation (0 = success, !0 = error)
|
||||
uint16_t packetSize; // expected DMP packet size (default is 42 bytes)
|
||||
uint16_t fifoCount; // count of all bytes currently in FIFO
|
||||
uint8_t fifoBuffer[64]; // FIFO storage buffer
|
||||
@@ -157,7 +157,10 @@ class MPU6050Driver : public Usermod {
|
||||
um_data.u_type[8] = UMT_UINT32;
|
||||
}
|
||||
|
||||
configDirty = false; // we have now accepted the current configuration, success or not
|
||||
|
||||
if (!config.enabled) return;
|
||||
// TODO: notice if these have changed ??
|
||||
if (i2c_scl<0 || i2c_sda<0) { DEBUG_PRINTLN(F("MPU6050: I2C is no good.")); return; }
|
||||
// Check the interrupt pin
|
||||
if (config.interruptPin >= 0) {
|
||||
@@ -182,7 +185,7 @@ class MPU6050Driver : public Usermod {
|
||||
|
||||
// load and configure the DMP
|
||||
DEBUG_PRINTLN(F("Initializing DMP..."));
|
||||
devStatus = mpu.dmpInitialize();
|
||||
auto devStatus = mpu.dmpInitialize();
|
||||
|
||||
// set offsets (from config)
|
||||
mpu.setXGyroOffset(config.gyro_offset[0]);
|
||||
@@ -241,6 +244,8 @@ class MPU6050Driver : public Usermod {
|
||||
* loop() is called continuously. Here you can check for events, read sensors, etc.
|
||||
*/
|
||||
void loop() {
|
||||
if (configDirty) setup();
|
||||
|
||||
// if programming failed, don't try to do anything
|
||||
if (!config.enabled || !dmpReady || strip.isUpdating()) return;
|
||||
|
||||
@@ -407,8 +412,8 @@ class MPU6050Driver : public Usermod {
|
||||
irqBound = false;
|
||||
}
|
||||
|
||||
// Just re-init
|
||||
setup();
|
||||
// Re-call setup on the next loop()
|
||||
configDirty = true;
|
||||
}
|
||||
|
||||
return configComplete;
|
||||
|
||||
254
usermods/pixels_dice_tray/README.md
Normal 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
|
||||
[](https://youtu.be/VNsHq1TbiW8)
|
||||
|
||||
<!-- TOC --><a name="multiple-die-controlling-different-segments"></a>
|
||||
### Multiple Die Controlling Different Segments
|
||||
[](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).
|
||||
6
usermods/pixels_dice_tray/WLED_ESP32_4MB_64KB_FS.csv
Normal 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,
|
||||
|
76
usermods/pixels_dice_tray/dice_state.h
Normal 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};
|
||||
230
usermods/pixels_dice_tray/generate_roll_info.py
Normal 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()
|
||||
BIN
usermods/pixels_dice_tray/images/effect.webp
Normal file
|
After Width: | Height: | Size: 14 KiB |
BIN
usermods/pixels_dice_tray/images/info.webp
Normal file
|
After Width: | Height: | Size: 24 KiB |
BIN
usermods/pixels_dice_tray/images/roll_plot.png
Normal file
|
After Width: | Height: | Size: 9.8 KiB |
BIN
usermods/pixels_dice_tray/images/status.webp
Normal file
|
After Width: | Height: | Size: 24 KiB |
124
usermods/pixels_dice_tray/led_effects.h
Normal 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";
|
||||
104
usermods/pixels_dice_tray/mqtt_client/mqtt_logger.py
Normal 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()
|
||||
69
usermods/pixels_dice_tray/mqtt_client/mqtt_plotter.py
Normal 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()
|
||||
2
usermods/pixels_dice_tray/mqtt_client/requirements.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
plotly-express
|
||||
paho-mqtt
|
||||
535
usermods/pixels_dice_tray/pixels_dice_tray.h
Normal 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!
|
||||
};
|
||||
115
usermods/pixels_dice_tray/platformio_override.ini.sample
Normal 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
|
||||
107
usermods/pixels_dice_tray/roll_info.h
Normal 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;
|
||||
479
usermods/pixels_dice_tray/tft_menu.h
Normal 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
|
||||
85
usermods/pov_display/usermod_pov_display.h
Normal 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() {}
|
||||
};
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,61 +1,41 @@
|
||||
# Smartnest
|
||||
|
||||
Enables integration with `smartnest.cz` service which provides MQTT integration with voice assistants.
|
||||
Enables integration with `smartnest.cz` service which provides MQTT integration with voice assistants, for example Google Home, Alexa, Siri, Home Assistant and more!
|
||||
|
||||
In order to setup Smartnest follow the [documentation](https://www.docu.smartnest.cz/).
|
||||
- You can create up to 5 different devices
|
||||
- To add the project to Google Home you can find the information [here](https://www.docu.smartnest.cz/google-home-integration)
|
||||
- To add the project to Alexa you can find the information [here](https://www.docu.smartnest.cz/alexa-integration)
|
||||
|
||||
## MQTT API
|
||||
|
||||
The API is described in the Smartnest [Github repo](https://github.com/aososam/Smartnest/blob/master/Devices/lightRgb/lightRgb.ino).
|
||||
|
||||
|
||||
## Usermod installation
|
||||
|
||||
1. Register the usermod by adding `#include "../usermods/smartnest/usermod_smartnest.h"` at the top and `usermods.add(new Smartnest());` at the bottom of `usermods_list.cpp`.
|
||||
or
|
||||
2. Use `#define USERMOD_SMARTNEST` in wled.h or `-D USERMOD_SMARTNEST` in your platformio.ini
|
||||
|
||||
|
||||
Example **usermods_list.cpp**:
|
||||
|
||||
```cpp
|
||||
#include "wled.h"
|
||||
/*
|
||||
* Register your v2 usermods here!
|
||||
* (for v1 usermods using just usermod.cpp, you can ignore this file)
|
||||
*/
|
||||
|
||||
/*
|
||||
* Add/uncomment your usermod filename here (and once more below)
|
||||
* || || ||
|
||||
* \/ \/ \/
|
||||
*/
|
||||
//#include "usermod_v2_example.h"
|
||||
//#include "usermod_temperature.h"
|
||||
#include "../usermods/usermod_smartnest.h"
|
||||
|
||||
void registerUsermods()
|
||||
{
|
||||
/*
|
||||
* Add your usermod class name here
|
||||
* || || ||
|
||||
* \/ \/ \/
|
||||
*/
|
||||
//usermods.add(new MyExampleUsermod());
|
||||
//usermods.add(new UsermodTemperature());
|
||||
usermods.add(new Smartnest());
|
||||
|
||||
}
|
||||
```
|
||||
1. Use `#define USERMOD_SMARTNEST` in wled.h or `-D USERMOD_SMARTNEST` in your platformio.ini (recommended).
|
||||
|
||||
## Configuration
|
||||
|
||||
Usermod has no configuration, but it relies on the MQTT configuration.\
|
||||
Under Config > Sync Interfaces > MQTT:
|
||||
* Enable MQTT check box
|
||||
* Set the `Broker` field to: `smartnest.cz`
|
||||
* The `Username` and `Password` fields are the login information from the `smartnest.cz` website.
|
||||
|
||||
* Enable `MQTT` check box.
|
||||
* Set the `Broker` field to: `smartnest.cz` or `3.122.209.170`(both work).
|
||||
* Set the `Port` field to: `1883`
|
||||
* The `Username` and `Password` fields are the login information from the `smartnest.cz` website (It is located above in the 3 points).
|
||||
* `Client ID` field is obtained from the device configuration panel in `smartnest.cz`.
|
||||
* `Device Topic` is obtained by entering the ClientID/report , remember to replace ClientId with your real information (Because they can ban your device).
|
||||
* `Group Topic` keep the same Group Topic.
|
||||
|
||||
Wait `1 minute` after turning it on, as it usually takes a while.
|
||||
|
||||
## Change log
|
||||
|
||||
2022-09
|
||||
* First implementation.
|
||||
* First implementation.
|
||||
|
||||
2024-05
|
||||
* Solved code.
|
||||
* Updated documentation.
|
||||
* Second implementation.
|
||||
|
||||
@@ -9,6 +9,10 @@
|
||||
class Smartnest : public Usermod
|
||||
{
|
||||
private:
|
||||
bool initialized = false;
|
||||
unsigned long lastMqttReport = 0;
|
||||
unsigned long mqttReportInterval = 60000; // Report every minute
|
||||
|
||||
void sendToBroker(const char *const topic, const char *const message)
|
||||
{
|
||||
if (!WLED_MQTT_CONNECTED)
|
||||
@@ -61,7 +65,7 @@ private:
|
||||
int position = 0;
|
||||
|
||||
// We need to copy the string in order to keep it read only as strtok_r function requires mutable string
|
||||
color_ = (char *)malloc(strlen(color));
|
||||
color_ = (char *)malloc(strlen(color) + 1);
|
||||
if (NULL == color_) {
|
||||
return -1;
|
||||
}
|
||||
@@ -150,7 +154,7 @@ public:
|
||||
delay(100);
|
||||
sendToBroker("report/firmware", versionString); // Reports the firmware version
|
||||
delay(100);
|
||||
sendToBroker("report/ip", (char *)WiFi.localIP().toString().c_str()); // Reports the ip
|
||||
sendToBroker("report/ip", (char *)WiFi.localIP().toString().c_str()); // Reports the IP
|
||||
delay(100);
|
||||
sendToBroker("report/network", (char *)WiFi.SSID().c_str()); // Reports the network name
|
||||
delay(100);
|
||||
@@ -168,4 +172,34 @@ public:
|
||||
{
|
||||
return USERMOD_ID_SMARTNEST;
|
||||
}
|
||||
|
||||
/**
|
||||
* setup() is called once at startup to initialize the usermod.
|
||||
*/
|
||||
void setup() {
|
||||
DEBUG_PRINTF("Smartnest usermod setup initializing...");
|
||||
|
||||
// Publish initial status
|
||||
sendToBroker("report/status", "Smartnest usermod initialized");
|
||||
}
|
||||
|
||||
/**
|
||||
* loop() is called continuously to keep the usermod running.
|
||||
*/
|
||||
void loop() {
|
||||
// Periodically report status to MQTT broker
|
||||
unsigned long currentMillis = millis();
|
||||
if (currentMillis - lastMqttReport >= mqttReportInterval) {
|
||||
lastMqttReport = currentMillis;
|
||||
|
||||
// Report current brightness
|
||||
char brightnessMsg[11];
|
||||
sprintf(brightnessMsg, "%u", bri);
|
||||
sendToBroker("report/brightness", brightnessMsg);
|
||||
|
||||
// Report current signal strength
|
||||
String signal(WiFi.RSSI(), 10);
|
||||
sendToBroker("report/signal", signal.c_str());
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -122,9 +122,9 @@ class AutoSaveUsermod : public Usermod {
|
||||
* Da loop.
|
||||
*/
|
||||
void loop() {
|
||||
if (!autoSaveAfterSec || !enabled || strip.isUpdating() || currentPreset>0) return; // setting 0 as autosave seconds disables autosave
|
||||
|
||||
static unsigned long lastRun = 0;
|
||||
unsigned long now = millis();
|
||||
if (!autoSaveAfterSec || !enabled || currentPreset>0 || (strip.isUpdating() && now - lastRun < 240)) return; // setting 0 as autosave seconds disables autosave
|
||||
uint8_t currentMode = strip.getMainSegment().mode;
|
||||
uint8_t currentPalette = strip.getMainSegment().palette;
|
||||
|
||||
|
||||
@@ -445,8 +445,8 @@ void FourLineDisplayUsermod::setPowerSave(uint8_t save) {
|
||||
|
||||
void FourLineDisplayUsermod::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 += ' ';
|
||||
if (len<width) for (unsigned i=(width-len)/2; i>0; i--) line = ' ' + line;
|
||||
for (unsigned i=line.length(); i<width; i++) line += ' ';
|
||||
}
|
||||
|
||||
void FourLineDisplayUsermod::draw2x2GlyphIcons() {
|
||||
@@ -819,28 +819,28 @@ void FourLineDisplayUsermod::showCurrentEffectOrPalette(int inputEffPal, const c
|
||||
if (overlayUntil == 0) {
|
||||
lockRedraw = true;
|
||||
// Find the mode name in JSON
|
||||
uint8_t printedChars = extractModeName(inputEffPal, qstring, lineBuffer, MAX_JSON_CHARS-1);
|
||||
unsigned printedChars = extractModeName(inputEffPal, qstring, lineBuffer, MAX_JSON_CHARS-1);
|
||||
if (lineBuffer[0]=='*' && lineBuffer[1]==' ') {
|
||||
// remove "* " from dynamic palettes
|
||||
for (byte i=2; i<=printedChars; i++) lineBuffer[i-2] = lineBuffer[i]; //include '\0'
|
||||
for (unsigned i=2; i<=printedChars; i++) lineBuffer[i-2] = lineBuffer[i]; //include '\0'
|
||||
printedChars -= 2;
|
||||
} else if ((lineBuffer[0]==' ' && lineBuffer[1]>127)) {
|
||||
// remove note symbol from effect names
|
||||
for (byte i=5; i<=printedChars; i++) lineBuffer[i-5] = lineBuffer[i]; //include '\0'
|
||||
for (unsigned i=5; i<=printedChars; i++) lineBuffer[i-5] = lineBuffer[i]; //include '\0'
|
||||
printedChars -= 5;
|
||||
}
|
||||
if (lineHeight == 2) { // use this code for 8 line display
|
||||
char smallBuffer1[MAX_MODE_LINE_SPACE];
|
||||
char smallBuffer2[MAX_MODE_LINE_SPACE];
|
||||
uint8_t smallChars1 = 0;
|
||||
uint8_t smallChars2 = 0;
|
||||
unsigned smallChars1 = 0;
|
||||
unsigned smallChars2 = 0;
|
||||
if (printedChars < MAX_MODE_LINE_SPACE) { // use big font if the text fits
|
||||
while (printedChars < (MAX_MODE_LINE_SPACE-1)) lineBuffer[printedChars++]=' ';
|
||||
lineBuffer[printedChars] = 0;
|
||||
drawString(1, row*lineHeight, lineBuffer);
|
||||
} else { // for long names divide the text into 2 lines and print them small
|
||||
bool spaceHit = false;
|
||||
for (uint8_t i = 0; i < printedChars; i++) {
|
||||
for (unsigned i = 0; i < printedChars; i++) {
|
||||
switch (lineBuffer[i]) {
|
||||
case ' ':
|
||||
if (i > 4 && !spaceHit) {
|
||||
@@ -865,8 +865,8 @@ void FourLineDisplayUsermod::showCurrentEffectOrPalette(int inputEffPal, const c
|
||||
}
|
||||
} else { // use this code for 4 ling displays
|
||||
char smallBuffer3[MAX_MODE_LINE_SPACE+1]; // uses 1x1 icon for mode/palette
|
||||
uint8_t smallChars3 = 0;
|
||||
for (uint8_t i = 0; i < MAX_MODE_LINE_SPACE; i++) smallBuffer3[smallChars3++] = (i >= printedChars) ? ' ' : lineBuffer[i];
|
||||
unsigned smallChars3 = 0;
|
||||
for (unsigned i = 0; i < MAX_MODE_LINE_SPACE; i++) smallBuffer3[smallChars3++] = (i >= printedChars) ? ' ' : lineBuffer[i];
|
||||
smallBuffer3[smallChars3] = 0;
|
||||
drawString(1, row*lineHeight, smallBuffer3, true);
|
||||
}
|
||||
@@ -1265,7 +1265,7 @@ void FourLineDisplayUsermod::addToConfig(JsonObject& root) {
|
||||
bool FourLineDisplayUsermod::readFromConfig(JsonObject& root) {
|
||||
bool needsRedraw = false;
|
||||
DisplayType newType = type;
|
||||
int8_t oldPin[3]; for (byte i=0; i<3; i++) oldPin[i] = ioPin[i];
|
||||
int8_t oldPin[3]; for (unsigned i=0; i<3; i++) oldPin[i] = ioPin[i];
|
||||
|
||||
JsonObject top = root[FPSTR(_name)];
|
||||
if (top.isNull()) {
|
||||
@@ -1276,7 +1276,7 @@ bool FourLineDisplayUsermod::readFromConfig(JsonObject& root) {
|
||||
|
||||
enabled = top[FPSTR(_enabled)] | enabled;
|
||||
newType = top["type"] | newType;
|
||||
for (byte i=0; i<3; i++) ioPin[i] = top["pin"][i] | ioPin[i];
|
||||
for (unsigned i=0; i<3; i++) ioPin[i] = top["pin"][i] | ioPin[i];
|
||||
flip = top[FPSTR(_flip)] | flip;
|
||||
contrast = top[FPSTR(_contrast)] | contrast;
|
||||
#ifndef ARDUINO_ARCH_ESP32
|
||||
@@ -1302,7 +1302,7 @@ bool FourLineDisplayUsermod::readFromConfig(JsonObject& root) {
|
||||
DEBUG_PRINTLN(F(" config (re)loaded."));
|
||||
// changing parameters from settings page
|
||||
bool pinsChanged = false;
|
||||
for (byte i=0; i<3; i++) if (ioPin[i] != oldPin[i]) { pinsChanged = true; break; }
|
||||
for (unsigned i=0; i<3; i++) if (ioPin[i] != oldPin[i]) { pinsChanged = true; break; }
|
||||
if (pinsChanged || type!=newType) {
|
||||
bool isSPI = (type == SSD1306_SPI || type == SSD1306_SPI64 || type == SSD1309_SPI64);
|
||||
bool newSPI = (newType == SSD1306_SPI || newType == SSD1306_SPI64 || newType == SSD1309_SPI64);
|
||||
|
||||
@@ -416,7 +416,7 @@ void RotaryEncoderUIUsermod::sortModesAndPalettes() {
|
||||
|
||||
byte *RotaryEncoderUIUsermod::re_initIndexArray(int numModes) {
|
||||
byte *indexes = (byte *)malloc(sizeof(byte) * numModes);
|
||||
for (byte i = 0; i < numModes; i++) {
|
||||
for (unsigned i = 0; i < numModes; i++) {
|
||||
indexes[i] = i;
|
||||
}
|
||||
return indexes;
|
||||
@@ -700,7 +700,7 @@ void RotaryEncoderUIUsermod::findCurrentEffectAndPalette() {
|
||||
|
||||
effectPaletteIndex = 0;
|
||||
DEBUG_PRINTLN(effectPalette);
|
||||
for (uint8_t i = 0; i < strip.getPaletteCount()+strip.customPalettes.size(); i++) {
|
||||
for (unsigned i = 0; i < strip.getPaletteCount()+strip.customPalettes.size(); i++) {
|
||||
if (palettes_alpha_indexes[i] == effectPalette) {
|
||||
effectPaletteIndex = i;
|
||||
DEBUG_PRINTLN(F("Found palette."));
|
||||
@@ -764,7 +764,7 @@ void RotaryEncoderUIUsermod::changeEffect(bool increase) {
|
||||
effectCurrent = modes_alpha_indexes[effectCurrentIndex];
|
||||
stateChanged = true;
|
||||
if (applyToAll) {
|
||||
for (byte i=0; i<strip.getSegmentsNum(); i++) {
|
||||
for (unsigned i=0; i<strip.getSegmentsNum(); i++) {
|
||||
Segment& seg = strip.getSegment(i);
|
||||
if (!seg.isActive()) continue;
|
||||
seg.setMode(effectCurrent);
|
||||
@@ -792,7 +792,7 @@ void RotaryEncoderUIUsermod::changeEffectSpeed(bool increase) {
|
||||
effectSpeed = max(min((increase ? effectSpeed+fadeAmount : effectSpeed-fadeAmount), 255), 0);
|
||||
stateChanged = true;
|
||||
if (applyToAll) {
|
||||
for (byte i=0; i<strip.getSegmentsNum(); i++) {
|
||||
for (unsigned i=0; i<strip.getSegmentsNum(); i++) {
|
||||
Segment& seg = strip.getSegment(i);
|
||||
if (!seg.isActive()) continue;
|
||||
seg.speed = effectSpeed;
|
||||
@@ -820,7 +820,7 @@ void RotaryEncoderUIUsermod::changeEffectIntensity(bool increase) {
|
||||
effectIntensity = max(min((increase ? effectIntensity+fadeAmount : effectIntensity-fadeAmount), 255), 0);
|
||||
stateChanged = true;
|
||||
if (applyToAll) {
|
||||
for (byte i=0; i<strip.getSegmentsNum(); i++) {
|
||||
for (unsigned i=0; i<strip.getSegmentsNum(); i++) {
|
||||
Segment& seg = strip.getSegment(i);
|
||||
if (!seg.isActive()) continue;
|
||||
seg.intensity = effectIntensity;
|
||||
@@ -855,7 +855,7 @@ void RotaryEncoderUIUsermod::changeCustom(uint8_t par, bool increase) {
|
||||
case 2: val = sid.custom2 = max(min((increase ? sid.custom2+fadeAmount : sid.custom2-fadeAmount), 255), 0); break;
|
||||
default: val = sid.custom1 = max(min((increase ? sid.custom1+fadeAmount : sid.custom1-fadeAmount), 255), 0); break;
|
||||
}
|
||||
for (byte i=0; i<strip.getSegmentsNum(); i++) {
|
||||
for (unsigned i=0; i<strip.getSegmentsNum(); i++) {
|
||||
Segment& seg = strip.getSegment(i);
|
||||
if (!seg.isActive() || i == id) continue;
|
||||
switch (par) {
|
||||
@@ -894,7 +894,7 @@ void RotaryEncoderUIUsermod::changePalette(bool increase) {
|
||||
effectPalette = palettes_alpha_indexes[effectPaletteIndex];
|
||||
stateChanged = true;
|
||||
if (applyToAll) {
|
||||
for (byte i=0; i<strip.getSegmentsNum(); i++) {
|
||||
for (unsigned i=0; i<strip.getSegmentsNum(); i++) {
|
||||
Segment& seg = strip.getSegment(i);
|
||||
if (!seg.isActive()) continue;
|
||||
seg.setPalette(effectPalette);
|
||||
@@ -923,7 +923,7 @@ void RotaryEncoderUIUsermod::changeHue(bool increase){
|
||||
colorHStoRGB(currentHue1*256, currentSat1, col);
|
||||
stateChanged = true;
|
||||
if (applyToAll) {
|
||||
for (byte i=0; i<strip.getSegmentsNum(); i++) {
|
||||
for (unsigned i=0; i<strip.getSegmentsNum(); i++) {
|
||||
Segment& seg = strip.getSegment(i);
|
||||
if (!seg.isActive()) continue;
|
||||
seg.colors[0] = RGBW32(col[0], col[1], col[2], col[3]);
|
||||
@@ -952,7 +952,7 @@ void RotaryEncoderUIUsermod::changeSat(bool increase){
|
||||
currentSat1 = max(min((increase ? currentSat1+fadeAmount : currentSat1-fadeAmount), 255), 0);
|
||||
colorHStoRGB(currentHue1*256, currentSat1, col);
|
||||
if (applyToAll) {
|
||||
for (byte i=0; i<strip.getSegmentsNum(); i++) {
|
||||
for (unsigned i=0; i<strip.getSegmentsNum(); i++) {
|
||||
Segment& seg = strip.getSegment(i);
|
||||
if (!seg.isActive()) continue;
|
||||
seg.colors[0] = RGBW32(col[0], col[1], col[2], col[3]);
|
||||
@@ -1012,7 +1012,7 @@ void RotaryEncoderUIUsermod::changeCCT(bool increase){
|
||||
#endif
|
||||
currentCCT = max(min((increase ? currentCCT+fadeAmount : currentCCT-fadeAmount), 255), 0);
|
||||
// if (applyToAll) {
|
||||
for (byte i=0; i<strip.getSegmentsNum(); i++) {
|
||||
for (unsigned i=0; i<strip.getSegmentsNum(); i++) {
|
||||
Segment& seg = strip.getSegment(i);
|
||||
if (!seg.isActive()) continue;
|
||||
seg.setCCT(currentCCT);
|
||||
|
||||
1571
wled00/FX.cpp
136
wled00/FX.h
@@ -563,16 +563,16 @@ typedef struct Segment {
|
||||
|
||||
// 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
|
||||
void handleTransition(void);
|
||||
void stopTransition(void); // ends transition mode by destroying transition structure (does nothing if not in transition)
|
||||
inline void handleTransition(void) { 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); // transition progression between 0-65535
|
||||
uint8_t currentBri(bool useCct = false); // current segment brightness/CCT (blended while in transition)
|
||||
uint8_t currentMode(void); // currently active effect/mode (while in transition)
|
||||
uint32_t currentColor(uint8_t slot); // currently active segment color (blended while in transition)
|
||||
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)
|
||||
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);
|
||||
|
||||
@@ -587,7 +587,7 @@ typedef struct Segment {
|
||||
inline void setPixelColor(float i, uint8_t r, uint8_t g, uint8_t b, uint8_t w = 0, bool aa = true) { setPixelColor(i, RGBW32(r,g,b,w), aa); }
|
||||
inline void setPixelColor(float i, CRGB c, bool aa = true) { setPixelColor(i, RGBW32(c.r,c.g,c.b,0), aa); }
|
||||
#endif
|
||||
uint32_t getPixelColor(int i);
|
||||
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);
|
||||
@@ -599,8 +599,18 @@ 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);
|
||||
uint32_t color_wheel(uint8_t pos);
|
||||
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;
|
||||
|
||||
// 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
|
||||
const unsigned cols = virtualWidth();
|
||||
for (unsigned k = 0; k < cols; k++) blurCol(k, blur_amount, smear);
|
||||
}
|
||||
inline void blurRows(fract8 blur_amount, bool smear = false) { // blur all rows
|
||||
const unsigned rows = virtualHeight();
|
||||
for ( unsigned i = 0; i < rows; i++) blurRow(i, blur_amount, smear);
|
||||
}
|
||||
|
||||
// 2D matrix
|
||||
uint16_t virtualWidth(void) const; // segment width in virtual pixels (accounts for groupping and spacing)
|
||||
@@ -618,7 +628,7 @@ 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
|
||||
uint32_t getPixelColorXY(int x, int y);
|
||||
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); }
|
||||
@@ -626,7 +636,8 @@ typedef struct Segment {
|
||||
inline void addPixelColorXY(int x, int y, byte r, byte g, byte b, byte w = 0, bool fast = false) { addPixelColorXY(x, y, RGBW32(r,g,b,w), fast); }
|
||||
inline void addPixelColorXY(int x, int y, CRGB c, bool fast = false) { addPixelColorXY(x, y, RGBW32(c.r,c.g,c.b,0), fast); }
|
||||
inline void fadePixelColorXY(uint16_t x, uint16_t y, uint8_t fade) { setPixelColorXY(x, y, color_fade(getPixelColorXY(x,y), fade, true)); }
|
||||
void box_blur(uint16_t i, bool vertical, fract8 blur_amount); // 1D box blur (with weight)
|
||||
void box_blur(unsigned r = 1U, bool smear = false); // 2D box blur
|
||||
void blur2D(uint8_t blur_amount, bool smear = false);
|
||||
void blurRow(uint32_t row, fract8 blur_amount, bool smear = false);
|
||||
void blurCol(uint32_t col, fract8 blur_amount, bool smear = false);
|
||||
void moveX(int8_t delta, bool wrap = false);
|
||||
@@ -656,14 +667,15 @@ typedef struct Segment {
|
||||
inline void setPixelColorXY(float x, float y, byte r, byte g, byte b, byte w = 0, bool aa = true) { setPixelColor(x, RGBW32(r,g,b,w), aa); }
|
||||
inline void setPixelColorXY(float x, float y, CRGB c, bool aa = true) { setPixelColor(x, RGBW32(c.r,c.g,c.b,0), aa); }
|
||||
#endif
|
||||
inline uint32_t getPixelColorXY(uint16_t x, uint16_t y) { return getPixelColor(x); }
|
||||
inline uint32_t getPixelColorXY(int x, int y) { return getPixelColor(x); }
|
||||
inline void blendPixelColorXY(uint16_t x, uint16_t y, uint32_t c, uint8_t blend) { blendPixelColor(x, c, blend); }
|
||||
inline void blendPixelColorXY(uint16_t x, uint16_t y, CRGB c, uint8_t blend) { blendPixelColor(x, RGBW32(c.r,c.g,c.b,0), blend); }
|
||||
inline void addPixelColorXY(int x, int y, uint32_t color, bool fast = false) { addPixelColor(x, color, fast); }
|
||||
inline void addPixelColorXY(int x, int y, byte r, byte g, byte b, byte w = 0, bool fast = false) { addPixelColor(x, RGBW32(r,g,b,w), fast); }
|
||||
inline void addPixelColorXY(int x, int y, CRGB c, bool fast = false) { addPixelColor(x, RGBW32(c.r,c.g,c.b,0), fast); }
|
||||
inline void fadePixelColorXY(uint16_t x, uint16_t y, uint8_t fade) { fadePixelColor(x, fade); }
|
||||
inline void box_blur(uint16_t i, bool vertical, fract8 blur_amount) {}
|
||||
inline void box_blur(unsigned i, bool vertical, fract8 blur_amount) {}
|
||||
inline void blur2D(uint8_t blur_amount, bool smear = false) {}
|
||||
inline void blurRow(uint32_t row, fract8 blur_amount, bool smear = false) {}
|
||||
inline void blurCol(uint32_t col, fract8 blur_amount, bool smear = false) {}
|
||||
inline void moveX(int8_t delta, bool wrap = false) {}
|
||||
@@ -708,6 +720,9 @@ class WS2812FX { // 96 bytes
|
||||
#ifndef WLED_DISABLE_2D
|
||||
panels(1),
|
||||
#endif
|
||||
autoSegments(false),
|
||||
correctWB(false),
|
||||
cctFromRgb(false),
|
||||
// semi-private (just obscured) used in effect functions through macros
|
||||
_colors_t{0,0,0},
|
||||
_virtualSegmentLength(0),
|
||||
@@ -729,15 +744,7 @@ class WS2812FX { // 96 bytes
|
||||
customMappingSize(0),
|
||||
_lastShow(0),
|
||||
_segment_index(0),
|
||||
_mainSegment(0),
|
||||
_queuedChangesSegId(255),
|
||||
_qStart(0),
|
||||
_qStop(0),
|
||||
_qStartY(0),
|
||||
_qStopY(0),
|
||||
_qGrouping(0),
|
||||
_qSpacing(0),
|
||||
_qOffset(0)
|
||||
_mainSegment(0)
|
||||
{
|
||||
WS2812FX::instance = this;
|
||||
_mode.reserve(_modeCount); // allocate memory to prevent initial fragmentation (does not increase size())
|
||||
@@ -779,7 +786,6 @@ class WS2812FX { // 96 bytes
|
||||
setPixelColor(unsigned n, uint32_t c), // paints absolute strip pixel with index n and color c
|
||||
show(void), // initiates LED output
|
||||
setTargetFps(uint8_t fps),
|
||||
addEffect(uint8_t id, mode_ptr mode_fn, const char *mode_name), // add effect to the list; defined in FX.cpp
|
||||
setupEffectData(void); // add default effects to the list; defined in FX.cpp
|
||||
|
||||
inline void restartRuntime() { for (Segment &seg : _segments) seg.markForReset(); }
|
||||
@@ -798,56 +804,56 @@ class WS2812FX { // 96 bytes
|
||||
bool
|
||||
paletteFade,
|
||||
checkSegmentAlignment(void),
|
||||
hasRGBWBus(void),
|
||||
hasCCTBus(void),
|
||||
// return true if the strip is being sent pixel updates
|
||||
isUpdating(void),
|
||||
hasRGBWBus(void) const,
|
||||
hasCCTBus(void) const,
|
||||
isUpdating(void) const, // return true if the strip is being sent pixel updates
|
||||
deserializeMap(uint8_t n=0);
|
||||
|
||||
inline bool isServicing(void) { return _isServicing; } // returns true if strip.service() is executing
|
||||
inline bool hasWhiteChannel(void) { return _hasWhiteChannel; } // returns true if strip contains separate white chanel
|
||||
inline bool isOffRefreshRequired(void) { return _isOffRefreshRequired; } // returns true if strip requires regular updates (i.e. TM1814 chipset)
|
||||
inline bool isSuspended(void) { return _suspend; } // returns true if strip.service() execution is suspended
|
||||
inline bool needsUpdate(void) { return _triggered; } // returns true if strip received a trigger() request
|
||||
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
|
||||
|
||||
uint8_t
|
||||
paletteBlend,
|
||||
cctBlending,
|
||||
getActiveSegmentsNum(void),
|
||||
getFirstSelectedSegId(void),
|
||||
getLastActiveSegmentId(void),
|
||||
getActiveSegsLightCapabilities(bool selectedOnly = false);
|
||||
getActiveSegmentsNum(void) const,
|
||||
getFirstSelectedSegId(void) const,
|
||||
getLastActiveSegmentId(void) 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) { return _brightness; } // returns current strip brightness
|
||||
inline uint8_t getMaxSegments(void) { return MAX_NUM_SEGMENTS; } // returns maximum number of supported segments (fixed value)
|
||||
inline uint8_t getSegmentsNum(void) { return _segments.size(); } // returns currently present segments
|
||||
inline uint8_t getCurrSegmentId(void) { return _segment_index; } // returns current segment index (only valid while strip.isServicing())
|
||||
inline uint8_t getMainSegmentId(void) { return _mainSegment; } // returns main segment index
|
||||
inline uint8_t getPaletteCount() { return 13 + GRADIENT_PALETTE_COUNT + customPalettes.size(); }
|
||||
inline uint8_t getTargetFps() { return _targetFps; } // returns rough FPS value for las 2s interval
|
||||
inline uint8_t getModeCount() { return _modeCount; } // returns number of registered modes/effects
|
||||
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
|
||||
|
||||
uint16_t
|
||||
getLengthPhysical(void),
|
||||
getLengthTotal(void), // will include virtual/nonexistent pixels in matrix
|
||||
getFps(),
|
||||
getMappedPixelIndex(uint16_t index);
|
||||
getLengthPhysical(void) const,
|
||||
getLengthTotal(void) const, // will include virtual/nonexistent pixels in matrix
|
||||
getFps() const,
|
||||
getMappedPixelIndex(uint16_t index) const;
|
||||
|
||||
inline uint16_t getFrameTime(void) { return _frametime; } // returns amount of time a frame should take (in ms)
|
||||
inline uint16_t getMinShowDelay(void) { return MIN_SHOW_DELAY; } // returns minimum amount of time strip.service() can be delayed (constant)
|
||||
inline uint16_t getLength(void) { return _length; } // returns actual amount of LEDs on a strip (2D matrix may have less LEDs than W*H)
|
||||
inline uint16_t getTransition(void) { return _transitionDur; } // returns currently set transition time (in ms)
|
||||
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)
|
||||
|
||||
uint32_t
|
||||
now,
|
||||
timebase,
|
||||
getPixelColor(uint16_t);
|
||||
getPixelColor(uint16_t) const;
|
||||
|
||||
inline uint32_t getLastShow(void) { return _lastShow; } // returns millis() timestamp of last strip.show() call
|
||||
inline uint32_t segColor(uint8_t i) { return _colors_t[i]; } // returns currently valid color (for slot i) AKA SEGCOLOR(); may be blended between two colors while in transition
|
||||
inline uint32_t getLastShow(void) 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) { return (id && id<_modeCount) ? _modeData[id] : PSTR("Solid"); }
|
||||
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
|
||||
@@ -862,7 +868,7 @@ class WS2812FX { // 96 bytes
|
||||
isMatrix;
|
||||
|
||||
#ifndef WLED_DISABLE_2D
|
||||
#define WLED_MAX_PANELS 64
|
||||
#define WLED_MAX_PANELS 18
|
||||
uint8_t
|
||||
panels;
|
||||
|
||||
@@ -898,13 +904,19 @@ class WS2812FX { // 96 bytes
|
||||
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)); }
|
||||
|
||||
inline uint32_t getPixelColorXY(uint16_t x, uint16_t y) { return getPixelColor(isMatrix ? y * Segment::maxWidth + x : x);}
|
||||
inline uint32_t getPixelColorXY(int x, int y) const { return getPixelColor(isMatrix ? y * Segment::maxWidth + x : x); }
|
||||
|
||||
// end 2D support
|
||||
|
||||
void loadCustomPalettes(void); // loads custom palettes from JSON
|
||||
std::vector<CRGBPalette16> customPalettes; // TODO: move custom palettes out of WS2812FX class
|
||||
|
||||
struct {
|
||||
bool autoSegments : 1;
|
||||
bool correctWB : 1;
|
||||
bool cctFromRgb : 1;
|
||||
};
|
||||
|
||||
// using public variables to reduce code size increase due to inline function getSegment() (with bounds checking)
|
||||
// and color transitions
|
||||
uint32_t _colors_t[3]; // color used for effect (includes transition)
|
||||
@@ -945,14 +957,6 @@ class WS2812FX { // 96 bytes
|
||||
|
||||
uint8_t _segment_index;
|
||||
uint8_t _mainSegment;
|
||||
uint8_t _queuedChangesSegId;
|
||||
uint16_t _qStart, _qStop, _qStartY, _qStopY;
|
||||
uint8_t _qGrouping, _qSpacing;
|
||||
uint16_t _qOffset;
|
||||
/*
|
||||
void
|
||||
setUpSegmentFromQueuedChanges(void);
|
||||
*/
|
||||
};
|
||||
|
||||
extern const char JSON_mode_names[];
|
||||
|
||||
@@ -161,14 +161,14 @@ 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(uint16_t x, uint16_t y)
|
||||
uint16_t IRAM_ATTR_YN Segment::XY(uint16_t x, uint16_t 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;
|
||||
}
|
||||
|
||||
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
|
||||
if (x >= virtualWidth() || y >= virtualHeight() || x<0 || y<0) return; // if pixel would fall out of virtual segment just exit
|
||||
@@ -180,17 +180,20 @@ void IRAM_ATTR Segment::setPixelColorXY(int x, int y, uint32_t col)
|
||||
|
||||
if (reverse ) x = virtualWidth() - x - 1;
|
||||
if (reverse_y) y = virtualHeight() - y - 1;
|
||||
if (transpose) { unsigned t = x; x = y; y = t; } // swap X & Y if segment transposed
|
||||
if (transpose) { std::swap(x,y); } // swap X & Y if segment transposed
|
||||
|
||||
x *= groupLength(); // expand to physical pixels
|
||||
y *= groupLength(); // expand to physical pixels
|
||||
if (x >= width() || y >= height()) return; // if pixel would fall out of segment just exit
|
||||
|
||||
int W = width();
|
||||
int H = height();
|
||||
if (x >= W || y >= H) return; // if pixel would fall out of segment just exit
|
||||
|
||||
uint32_t tmpCol = col;
|
||||
for (int j = 0; j < grouping; j++) { // groupping vertically
|
||||
for (int g = 0; g < grouping; g++) { // groupping horizontally
|
||||
unsigned xX = (x+g), yY = (y+j);
|
||||
if (xX >= width() || yY >= height()) continue; // we have reached one dimension's end
|
||||
int xX = (x+g), yY = (y+j);
|
||||
if (xX >= W || yY >= H) continue; // we have reached one dimension's end
|
||||
|
||||
#ifndef WLED_DISABLE_MODE_BLEND
|
||||
// if blending modes, blend with underlying pixel
|
||||
@@ -208,7 +211,7 @@ void IRAM_ATTR Segment::setPixelColorXY(int x, int y, uint32_t col)
|
||||
else strip.setPixelColorXY(start + xX, startY + height() - yY - 1, tmpCol);
|
||||
}
|
||||
if (mirror_y && mirror) { //set the corresponding vertically AND horizontally mirrored pixel
|
||||
strip.setPixelColorXY(width() - xX - 1, height() - yY - 1, tmpCol);
|
||||
strip.setPixelColorXY(start + width() - xX - 1, startY + height() - yY - 1, tmpCol);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -261,12 +264,12 @@ 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) {
|
||||
uint32_t IRAM_ATTR_YN Segment::getPixelColorXY(int x, int y) const {
|
||||
if (!isActive()) return 0; // not active
|
||||
if (x >= virtualWidth() || y >= virtualHeight() || x<0 || y<0) return 0; // if pixel would fall out of virtual segment just exit
|
||||
if (reverse ) x = virtualWidth() - x - 1;
|
||||
if (reverse_y) y = virtualHeight() - y - 1;
|
||||
if (transpose) { unsigned t = x; x = y; y = t; } // swap X & Y if segment transposed
|
||||
if (transpose) { std::swap(x,y); } // swap X & Y if segment transposed
|
||||
x *= groupLength(); // expand to physical pixels
|
||||
y *= groupLength(); // expand to physical pixels
|
||||
if (x >= width() || y >= height()) return 0;
|
||||
@@ -339,39 +342,126 @@ void Segment::blurCol(uint32_t col, fract8 blur_amount, bool smear) {
|
||||
setPixelColorXY(col, rows - 1, curnew);
|
||||
}
|
||||
|
||||
// 1D Box blur (with added weight - blur_amount: [0=no blur, 255=max blur])
|
||||
void Segment::box_blur(uint16_t i, bool vertical, fract8 blur_amount) {
|
||||
void Segment::blur2D(uint8_t blur_amount, bool smear) {
|
||||
if (!isActive() || blur_amount == 0) return; // not active
|
||||
const int cols = virtualWidth();
|
||||
const int rows = virtualHeight();
|
||||
const int dim1 = vertical ? rows : cols;
|
||||
const int dim2 = vertical ? cols : rows;
|
||||
if (i >= dim2) return;
|
||||
const float seep = blur_amount/255.f;
|
||||
const float keep = 3.f - 2.f*seep;
|
||||
// 1D box blur
|
||||
uint32_t out[dim1], in[dim1];
|
||||
for (int j = 0; j < dim1; j++) {
|
||||
int x = vertical ? i : j;
|
||||
int y = vertical ? j : i;
|
||||
in[j] = getPixelColorXY(x, y);
|
||||
const unsigned cols = virtualWidth();
|
||||
const unsigned rows = virtualHeight();
|
||||
|
||||
const uint8_t keep = smear ? 255 : 255 - blur_amount;
|
||||
const uint8_t seep = blur_amount >> (1 + smear);
|
||||
uint32_t lastnew;
|
||||
uint32_t last;
|
||||
for (unsigned row = 0; row < rows; row++) {
|
||||
uint32_t carryover = BLACK;
|
||||
uint32_t curnew = BLACK;
|
||||
for (unsigned x = 0; x < cols; x++) {
|
||||
uint32_t cur = getPixelColorXY(x, row);
|
||||
uint32_t part = color_fade(cur, seep);
|
||||
curnew = color_fade(cur, keep);
|
||||
if (x > 0) {
|
||||
if (carryover) curnew = color_add(curnew, carryover, true);
|
||||
uint32_t prev = color_add(lastnew, part, true);
|
||||
// optimization: only set pixel if color has changed
|
||||
if (last != prev) setPixelColorXY(x - 1, row, prev);
|
||||
} else setPixelColorXY(x, row, curnew); // first pixel
|
||||
lastnew = curnew;
|
||||
last = cur; // save original value for comparison on next iteration
|
||||
carryover = part;
|
||||
}
|
||||
setPixelColorXY(cols-1, row, curnew); // set last pixel
|
||||
}
|
||||
for (int j = 0; j < dim1; j++) {
|
||||
uint32_t curr = in[j];
|
||||
uint32_t prev = j > 0 ? in[j-1] : BLACK;
|
||||
uint32_t next = j < dim1-1 ? in[j+1] : BLACK;
|
||||
uint8_t r, g, b, w;
|
||||
r = (R(curr)*keep + (R(prev) + R(next))*seep) / 3;
|
||||
g = (G(curr)*keep + (G(prev) + G(next))*seep) / 3;
|
||||
b = (B(curr)*keep + (B(prev) + B(next))*seep) / 3;
|
||||
w = (W(curr)*keep + (W(prev) + W(next))*seep) / 3;
|
||||
out[j] = RGBW32(r,g,b,w);
|
||||
for (unsigned col = 0; col < cols; col++) {
|
||||
uint32_t carryover = BLACK;
|
||||
uint32_t curnew = BLACK;
|
||||
for (unsigned y = 0; y < rows; y++) {
|
||||
uint32_t cur = getPixelColorXY(col, y);
|
||||
uint32_t part = color_fade(cur, seep);
|
||||
curnew = color_fade(cur, keep);
|
||||
if (y > 0) {
|
||||
if (carryover) curnew = color_add(curnew, carryover, true);
|
||||
uint32_t prev = color_add(lastnew, part, true);
|
||||
// optimization: only set pixel if color has changed
|
||||
if (last != prev) setPixelColorXY(col, y - 1, prev);
|
||||
} else setPixelColorXY(col, y, curnew); // first pixel
|
||||
lastnew = curnew;
|
||||
last = cur; //save original value for comparison on next iteration
|
||||
carryover = part;
|
||||
}
|
||||
setPixelColorXY(col, rows - 1, curnew);
|
||||
}
|
||||
for (int j = 0; j < dim1; j++) {
|
||||
int x = vertical ? i : j;
|
||||
int y = vertical ? j : i;
|
||||
setPixelColorXY(x, y, out[j]);
|
||||
}
|
||||
|
||||
// 2D Box blur
|
||||
void Segment::box_blur(unsigned radius, bool smear) {
|
||||
if (!isActive() || radius == 0) return; // not active
|
||||
if (radius > 3) radius = 3;
|
||||
const unsigned d = (1 + 2*radius) * (1 + 2*radius); // averaging divisor
|
||||
const unsigned cols = virtualWidth();
|
||||
const unsigned rows = virtualHeight();
|
||||
uint16_t *tmpRSum = new uint16_t[cols*rows];
|
||||
uint16_t *tmpGSum = new uint16_t[cols*rows];
|
||||
uint16_t *tmpBSum = new uint16_t[cols*rows];
|
||||
uint16_t *tmpWSum = new uint16_t[cols*rows];
|
||||
// fill summed-area table (https://en.wikipedia.org/wiki/Summed-area_table)
|
||||
for (unsigned x = 0; x < cols; x++) {
|
||||
unsigned rS, gS, bS, wS;
|
||||
unsigned index;
|
||||
rS = gS = bS = wS = 0;
|
||||
for (unsigned y = 0; y < rows; y++) {
|
||||
index = x * cols + y;
|
||||
if (x > 0) {
|
||||
unsigned index2 = (x - 1) * cols + y;
|
||||
tmpRSum[index] = tmpRSum[index2];
|
||||
tmpGSum[index] = tmpGSum[index2];
|
||||
tmpBSum[index] = tmpBSum[index2];
|
||||
tmpWSum[index] = tmpWSum[index2];
|
||||
} else {
|
||||
tmpRSum[index] = 0;
|
||||
tmpGSum[index] = 0;
|
||||
tmpBSum[index] = 0;
|
||||
tmpWSum[index] = 0;
|
||||
}
|
||||
uint32_t c = getPixelColorXY(x, y);
|
||||
rS += R(c);
|
||||
gS += G(c);
|
||||
bS += B(c);
|
||||
wS += W(c);
|
||||
tmpRSum[index] += rS;
|
||||
tmpGSum[index] += gS;
|
||||
tmpBSum[index] += bS;
|
||||
tmpWSum[index] += wS;
|
||||
}
|
||||
}
|
||||
// do a box blur using pre-calculated sums
|
||||
for (unsigned x = 0; x < cols; x++) {
|
||||
for (unsigned y = 0; y < rows; y++) {
|
||||
// sum = D + A - B - C where k = (x,y)
|
||||
// +----+-+---- (x)
|
||||
// | | |
|
||||
// +----A-B
|
||||
// | |k|
|
||||
// +----C-D
|
||||
// |
|
||||
//(y)
|
||||
unsigned x0 = x < radius ? 0 : x - radius;
|
||||
unsigned y0 = y < radius ? 0 : y - radius;
|
||||
unsigned x1 = x >= cols - radius ? cols - 1 : x + radius;
|
||||
unsigned y1 = y >= rows - radius ? rows - 1 : y + radius;
|
||||
unsigned A = x0 * cols + y0;
|
||||
unsigned B = x1 * cols + y0;
|
||||
unsigned C = x0 * cols + y1;
|
||||
unsigned D = x1 * cols + y1;
|
||||
unsigned r = tmpRSum[D] + tmpRSum[A] - tmpRSum[C] - tmpRSum[B];
|
||||
unsigned g = tmpGSum[D] + tmpGSum[A] - tmpGSum[C] - tmpGSum[B];
|
||||
unsigned b = tmpBSum[D] + tmpBSum[A] - tmpBSum[C] - tmpBSum[B];
|
||||
unsigned w = tmpWSum[D] + tmpWSum[A] - tmpWSum[C] - tmpWSum[B];
|
||||
setPixelColorXY(x, y, RGBW32(r/d, g/d, b/d, w/d));
|
||||
}
|
||||
}
|
||||
delete[] tmpRSum;
|
||||
delete[] tmpGSum;
|
||||
delete[] tmpBSum;
|
||||
delete[] tmpWSum;
|
||||
}
|
||||
|
||||
void Segment::moveX(int8_t delta, bool wrap) {
|
||||
|
||||
@@ -146,7 +146,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
|
||||
@@ -170,7 +170,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
|
||||
@@ -202,7 +202,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
|
||||
@@ -327,13 +327,8 @@ void Segment::stopTransition() {
|
||||
}
|
||||
}
|
||||
|
||||
void Segment::handleTransition() {
|
||||
unsigned _progress = progress();
|
||||
if (_progress == 0xFFFFU) stopTransition();
|
||||
}
|
||||
|
||||
// transition progression between 0-65535
|
||||
uint16_t IRAM_ATTR Segment::progress() {
|
||||
uint16_t IRAM_ATTR Segment::progress() const {
|
||||
if (isInTransition()) {
|
||||
unsigned diff = millis() - _t->_start;
|
||||
if (_t->_dur > 0 && diff < _t->_dur) return diff * 0xFFFFU / _t->_dur;
|
||||
@@ -412,7 +407,7 @@ void Segment::restoreSegenv(tmpsegd_t &tmpSeg) {
|
||||
}
|
||||
#endif
|
||||
|
||||
uint8_t IRAM_ATTR Segment::currentBri(bool useCct) {
|
||||
uint8_t IRAM_ATTR Segment::currentBri(bool useCct) const {
|
||||
unsigned prog = progress();
|
||||
if (prog < 0xFFFFU) {
|
||||
unsigned curBri = (useCct ? cct : (on ? opacity : 0)) * prog;
|
||||
@@ -422,7 +417,7 @@ uint8_t IRAM_ATTR Segment::currentBri(bool useCct) {
|
||||
return (useCct ? cct : (on ? opacity : 0));
|
||||
}
|
||||
|
||||
uint8_t IRAM_ATTR Segment::currentMode() {
|
||||
uint8_t IRAM_ATTR_YN Segment::currentMode() const {
|
||||
#ifndef WLED_DISABLE_MODE_BLEND
|
||||
unsigned prog = progress();
|
||||
if (modeBlending && prog < 0xFFFFU) return _t->_modeT;
|
||||
@@ -430,7 +425,7 @@ uint8_t IRAM_ATTR Segment::currentMode() {
|
||||
return mode;
|
||||
}
|
||||
|
||||
uint32_t IRAM_ATTR Segment::currentColor(uint8_t slot) {
|
||||
uint32_t IRAM_ATTR_YN Segment::currentColor(uint8_t slot) const {
|
||||
if (slot >= NUM_COLORS) slot = 0;
|
||||
#ifndef WLED_DISABLE_MODE_BLEND
|
||||
return isInTransition() ? color_blend(_t->_segT._colorT[slot], colors[slot], progress(), true) : colors[slot];
|
||||
@@ -623,7 +618,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()) {
|
||||
@@ -679,18 +674,23 @@ uint16_t IRAM_ATTR Segment::virtualLength() const {
|
||||
if (is2D()) {
|
||||
unsigned vW = virtualWidth();
|
||||
unsigned vH = virtualHeight();
|
||||
unsigned vLen = vW * vH; // use all pixels from segment
|
||||
unsigned vLen;
|
||||
switch (map1D2D) {
|
||||
case M12_pBar:
|
||||
vLen = vH;
|
||||
break;
|
||||
case M12_pCorner:
|
||||
case M12_pArc:
|
||||
vLen = max(vW,vH); // get the longest dimension
|
||||
break;
|
||||
case M12_pArc:
|
||||
vLen = sqrt16(vH*vH + vW*vW); // use diagonal
|
||||
break;
|
||||
case M12_sPinwheel:
|
||||
vLen = getPinwheelLength(vW, vH);
|
||||
break;
|
||||
default:
|
||||
vLen = vW * vH; // use all pixels from segment
|
||||
break;
|
||||
}
|
||||
return vLen;
|
||||
}
|
||||
@@ -701,7 +701,7 @@ uint16_t IRAM_ATTR Segment::virtualLength() const {
|
||||
return vLength;
|
||||
}
|
||||
|
||||
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
|
||||
@@ -730,12 +730,14 @@ void IRAM_ATTR Segment::setPixelColor(int i, uint32_t col)
|
||||
if (i==0)
|
||||
setPixelColorXY(0, 0, col);
|
||||
else {
|
||||
float step = HALF_PI / (2.85f*i);
|
||||
for (float rad = 0.0f; rad <= HALF_PI+step/2; rad += step) {
|
||||
// may want to try float version as well (with or without antialiasing)
|
||||
int x = roundf(sin_t(rad) * i);
|
||||
int y = roundf(cos_t(rad) * i);
|
||||
float r = i;
|
||||
float step = HALF_PI / (2.8284f * r + 4); // we only need (PI/4)/(r/sqrt(2)+1) steps
|
||||
for (float rad = 0.0f; rad <= (HALF_PI/2)+step/2; rad += step) {
|
||||
int x = roundf(sin_t(rad) * r);
|
||||
int y = roundf(cos_t(rad) * r);
|
||||
// exploit symmetry
|
||||
setPixelColorXY(x, y, col);
|
||||
setPixelColorXY(y, x, col);
|
||||
}
|
||||
// Bresenham’s Algorithm (may not fill every pixel)
|
||||
//int d = 3 - (2*i);
|
||||
@@ -893,7 +895,7 @@ void Segment::setPixelColor(float i, uint32_t col, bool aa)
|
||||
}
|
||||
#endif
|
||||
|
||||
uint32_t IRAM_ATTR Segment::getPixelColor(int i)
|
||||
uint32_t IRAM_ATTR_YN Segment::getPixelColor(int i) const
|
||||
{
|
||||
if (!isActive()) return 0; // not active
|
||||
#ifndef WLED_DISABLE_2D
|
||||
@@ -903,8 +905,8 @@ uint32_t IRAM_ATTR Segment::getPixelColor(int i)
|
||||
|
||||
#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);
|
||||
@@ -914,6 +916,10 @@ uint32_t IRAM_ATTR Segment::getPixelColor(int i)
|
||||
else return getPixelColorXY(0, vH - i -1);
|
||||
break;
|
||||
case M12_pArc:
|
||||
if (i >= vW && i >= vH) {
|
||||
unsigned vI = sqrt16(i*i/2);
|
||||
return getPixelColorXY(vI,vI); // use diagonal
|
||||
}
|
||||
case M12_pCorner:
|
||||
// use longest dimension
|
||||
return vW>vH ? getPixelColorXY(i, 0) : getPixelColorXY(0, i);
|
||||
@@ -955,9 +961,9 @@ uint32_t IRAM_ATTR Segment::getPixelColor(int i)
|
||||
if (reverse) i = virtualLength() - i - 1;
|
||||
i *= groupLength();
|
||||
i += start;
|
||||
/* offset/phase */
|
||||
// offset/phase
|
||||
i += offset;
|
||||
if ((i >= stop) && (stop>0)) i -= length(); // avoids negative pixel index (stop = 0 is a possible value)
|
||||
if (i >= stop) i -= length();
|
||||
return strip.getPixelColor(i);
|
||||
}
|
||||
|
||||
@@ -1022,9 +1028,9 @@ void Segment::refreshLightCapabilities() {
|
||||
if (bus->getStart() + bus->getLength() <= segStartIdx) continue;
|
||||
|
||||
//uint8_t type = bus->getType();
|
||||
if (bus->hasRGB() || (cctFromRgb && bus->hasCCT())) capabilities |= SEG_CAPABILITY_RGB;
|
||||
if (!cctFromRgb && bus->hasCCT()) capabilities |= SEG_CAPABILITY_CCT;
|
||||
if (correctWB && (bus->hasRGB() || bus->hasCCT())) capabilities |= SEG_CAPABILITY_CCT; //white balance correction (CCT slider)
|
||||
if (bus->hasRGB() || (strip.cctFromRgb && bus->hasCCT())) capabilities |= SEG_CAPABILITY_RGB;
|
||||
if (!strip.cctFromRgb && bus->hasCCT()) capabilities |= SEG_CAPABILITY_CCT;
|
||||
if (strip.correctWB && (bus->hasRGB() || bus->hasCCT())) capabilities |= SEG_CAPABILITY_CCT; //white balance correction (CCT slider)
|
||||
if (bus->hasWhite()) {
|
||||
unsigned aWM = Bus::getGlobalAWMode() == AW_GLOBAL_DISABLED ? bus->getAutoWhiteMode() : Bus::getGlobalAWMode();
|
||||
bool whiteSlider = (aWM == RGBW_MODE_DUAL || aWM == RGBW_MODE_MANUAL_ONLY); // white slider allowed
|
||||
@@ -1059,7 +1065,7 @@ void Segment::fade_out(uint8_t rate) {
|
||||
const int rows = virtualHeight(); // will be 1 for 1D
|
||||
|
||||
rate = (255-rate) >> 1;
|
||||
float mappedRate = float(rate) +1.1f;
|
||||
float mappedRate = 1.0f / (float(rate) + 1.1f);
|
||||
|
||||
uint32_t color = colors[1]; // SEGCOLOR(1); // target color
|
||||
int w2 = W(color);
|
||||
@@ -1069,15 +1075,16 @@ void Segment::fade_out(uint8_t rate) {
|
||||
|
||||
for (int y = 0; y < rows; y++) for (int x = 0; x < cols; x++) {
|
||||
color = is2D() ? getPixelColorXY(x, y) : getPixelColor(x);
|
||||
if (color == colors[1]) continue; // already at target color
|
||||
int w1 = W(color);
|
||||
int r1 = R(color);
|
||||
int g1 = G(color);
|
||||
int b1 = B(color);
|
||||
|
||||
int wdelta = (w2 - w1) / mappedRate;
|
||||
int rdelta = (r2 - r1) / mappedRate;
|
||||
int gdelta = (g2 - g1) / mappedRate;
|
||||
int bdelta = (b2 - b1) / mappedRate;
|
||||
int wdelta = (w2 - w1) * mappedRate;
|
||||
int rdelta = (r2 - r1) * mappedRate;
|
||||
int gdelta = (g2 - g1) * mappedRate;
|
||||
int bdelta = (b2 - b1) * mappedRate;
|
||||
|
||||
// if fade isn't complete, make sure delta is at least 1 (fixes rounding issues)
|
||||
wdelta += (w2 == w1) ? 0 : (w2 > w1) ? 1 : -1;
|
||||
@@ -1110,15 +1117,13 @@ void Segment::blur(uint8_t blur_amount, bool smear) {
|
||||
#ifndef WLED_DISABLE_2D
|
||||
if (is2D()) {
|
||||
// compatibility with 2D
|
||||
const unsigned cols = virtualWidth();
|
||||
const unsigned rows = virtualHeight();
|
||||
for (unsigned i = 0; i < rows; i++) blurRow(i, blur_amount, smear); // blur all rows
|
||||
for (unsigned k = 0; k < cols; k++) blurCol(k, blur_amount, smear); // blur all columns
|
||||
blur2D(blur_amount, smear);
|
||||
//box_blur(map(blur_amount,1,255,1,3), smear);
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
uint8_t keep = smear ? 255 : 255 - blur_amount;
|
||||
uint8_t seep = blur_amount >> 1;
|
||||
uint8_t seep = blur_amount >> (1 + smear);
|
||||
unsigned vlength = virtualLength();
|
||||
uint32_t carryover = BLACK;
|
||||
uint32_t lastnew;
|
||||
@@ -1129,13 +1134,11 @@ void Segment::blur(uint8_t blur_amount, bool smear) {
|
||||
uint32_t part = color_fade(cur, seep);
|
||||
curnew = color_fade(cur, keep);
|
||||
if (i > 0) {
|
||||
if (carryover)
|
||||
curnew = color_add(curnew, carryover, true);
|
||||
if (carryover) curnew = color_add(curnew, carryover, true);
|
||||
uint32_t prev = color_add(lastnew, part, true);
|
||||
if (last != prev) // optimization: only set pixel if color has changed
|
||||
setPixelColor(i - 1, prev);
|
||||
}
|
||||
else // first pixel
|
||||
// optimization: only set pixel if color has changed
|
||||
if (last != prev) setPixelColor(i - 1, prev);
|
||||
} else // first pixel
|
||||
setPixelColor(i, curnew);
|
||||
lastnew = curnew;
|
||||
last = cur; // save original value for comparison on next iteration
|
||||
@@ -1149,7 +1152,7 @@ void Segment::blur(uint8_t blur_amount, bool smear) {
|
||||
* The colours are a transition r -> g -> b -> back to r
|
||||
* Inspired by the Adafruit examples.
|
||||
*/
|
||||
uint32_t Segment::color_wheel(uint8_t pos) {
|
||||
uint32_t Segment::color_wheel(uint8_t pos) const {
|
||||
if (palette) return color_from_palette(pos, false, true, 0); // perhaps "strip.paletteBlend < 2" should be better instead of "true"
|
||||
uint8_t w = W(currentColor(0));
|
||||
pos = 255 - pos;
|
||||
@@ -1173,7 +1176,7 @@ uint32_t Segment::color_wheel(uint8_t pos) {
|
||||
* @param pbri Value to scale the brightness of the returned color by. Default is 255. (no scaling)
|
||||
* @returns Single color from palette
|
||||
*/
|
||||
uint32_t Segment::color_from_palette(uint16_t i, bool mapping, bool wrap, uint8_t mcol, uint8_t pbri) {
|
||||
uint32_t Segment::color_from_palette(uint16_t i, bool mapping, bool wrap, uint8_t mcol, uint8_t pbri) const {
|
||||
uint32_t color = gamma32(currentColor(mcol));
|
||||
|
||||
// default palette or no RGB support on segment
|
||||
@@ -1204,6 +1207,7 @@ void WS2812FX::finalizeInit(void) {
|
||||
// for the lack of better place enumerate ledmaps here
|
||||
// if we do it in json.cpp (serializeInfo()) we are getting flashes on LEDs
|
||||
// unfortunately this means we do not get updates after uploads
|
||||
// the other option is saving UI settings which will cause enumeration
|
||||
enumerateLedmaps();
|
||||
|
||||
_hasWhiteChannel = _isOffRefreshRequired = false;
|
||||
@@ -1214,8 +1218,9 @@ void WS2812FX::finalizeInit(void) {
|
||||
const unsigned defDataPins[] = {DATA_PINS};
|
||||
const unsigned defCounts[] = {PIXEL_COUNTS};
|
||||
const unsigned defNumPins = ((sizeof defDataPins) / (sizeof defDataPins[0]));
|
||||
const unsigned defNumCounts = ((sizeof defCounts) / (sizeof defCounts[0]));
|
||||
const unsigned defNumBusses = defNumPins > defNumCounts && defNumCounts > 1 && defNumPins%defNumCounts == 0 ? defNumCounts : defNumPins;
|
||||
const unsigned defNumCounts = ((sizeof defCounts) / (sizeof defCounts[0]));
|
||||
// if number of pins is divisible by counts, use number of counts to determine number of buses, otherwise use pins
|
||||
const unsigned defNumBusses = defNumPins > defNumCounts && defNumPins%defNumCounts == 0 ? defNumCounts : defNumPins;
|
||||
const unsigned pinsPerBus = defNumPins / defNumBusses;
|
||||
unsigned prevLen = 0;
|
||||
for (unsigned i = 0; i < defNumBusses && i < WLED_MAX_BUSSES+WLED_MIN_VIRTUAL_BUSSES; i++) {
|
||||
@@ -1228,9 +1233,10 @@ void WS2812FX::finalizeInit(void) {
|
||||
while (pinManager.isPinAllocated(defPin[0]) && defPin[0] < WLED_NUM_PINS) defPin[0]++;
|
||||
}
|
||||
unsigned start = prevLen;
|
||||
// if we have less counts than pins and they do not align, use last known count to set current count
|
||||
unsigned count = defCounts[(i < defNumCounts) ? i : defNumCounts -1];
|
||||
prevLen += count;
|
||||
BusConfig defCfg = BusConfig(DEFAULT_LED_TYPE, defPin, start, count, DEFAULT_LED_COLOR_ORDER, false, 0, RGBW_MODE_MANUAL_ONLY);
|
||||
BusConfig defCfg = BusConfig(DEFAULT_LED_TYPE, defPin, start, count, DEFAULT_LED_COLOR_ORDER, false, 0, RGBW_MODE_MANUAL_ONLY, 0, useGlobalLedBuffer);
|
||||
if (BusManager::add(defCfg) == -1) break;
|
||||
}
|
||||
}
|
||||
@@ -1247,11 +1253,12 @@ void WS2812FX::finalizeInit(void) {
|
||||
unsigned busEnd = bus->getStart() + bus->getLength();
|
||||
if (busEnd > _length) _length = busEnd;
|
||||
#ifdef ESP8266
|
||||
if ((!IS_DIGITAL(bus->getType()) || IS_2PIN(bus->getType()))) continue;
|
||||
uint8_t pins[5];
|
||||
if (!bus->getPins(pins)) continue;
|
||||
BusDigital* bd = static_cast<BusDigital*>(bus);
|
||||
if (pins[0] == 3) bd->reinit();
|
||||
// why do we need to reinitialise GPIO3???
|
||||
//if ((!IS_DIGITAL(bus->getType()) || IS_2PIN(bus->getType()))) continue;
|
||||
//uint8_t pins[5];
|
||||
//if (!bus->getPins(pins)) continue;
|
||||
//BusDigital* bd = static_cast<BusDigital*>(bus);
|
||||
//if (pins[0] == 3) bd->reinit();
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -1353,7 +1360,7 @@ void IRAM_ATTR WS2812FX::setPixelColor(unsigned i, uint32_t col) {
|
||||
BusManager::setPixelColor(i, col);
|
||||
}
|
||||
|
||||
uint32_t IRAM_ATTR WS2812FX::getPixelColor(uint16_t i) {
|
||||
uint32_t IRAM_ATTR WS2812FX::getPixelColor(uint16_t i) const {
|
||||
i = getMappedPixelIndex(i);
|
||||
if (i >= _length) return 0;
|
||||
return BusManager::getPixelColor(i);
|
||||
@@ -1381,7 +1388,7 @@ void WS2812FX::show(void) {
|
||||
* Returns a true value if any of the strips are still being updated.
|
||||
* On some hardware (ESP32), strip updates are done asynchronously.
|
||||
*/
|
||||
bool WS2812FX::isUpdating() {
|
||||
bool WS2812FX::isUpdating() const {
|
||||
return !BusManager::canAllShow();
|
||||
}
|
||||
|
||||
@@ -1389,7 +1396,7 @@ bool WS2812FX::isUpdating() {
|
||||
* Returns the refresh rate of the LED strip. Useful for finding out whether a given setup is fast enough.
|
||||
* Only updates on show() or is set to 0 fps if last show is more than 2 secs ago, so accuracy varies
|
||||
*/
|
||||
uint16_t WS2812FX::getFps() {
|
||||
uint16_t WS2812FX::getFps() const {
|
||||
if (millis() - _lastShow > 2000) return 0;
|
||||
return _cumulativeFps +1;
|
||||
}
|
||||
@@ -1448,17 +1455,17 @@ void WS2812FX::setBrightness(uint8_t b, bool direct) {
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t WS2812FX::getActiveSegsLightCapabilities(bool selectedOnly) {
|
||||
uint8_t WS2812FX::getActiveSegsLightCapabilities(bool selectedOnly) const {
|
||||
uint8_t totalLC = 0;
|
||||
for (segment &seg : _segments) {
|
||||
for (const segment &seg : _segments) {
|
||||
if (seg.isActive() && (!selectedOnly || seg.isSelected())) totalLC |= seg.getLightCapabilities();
|
||||
}
|
||||
return totalLC;
|
||||
}
|
||||
|
||||
uint8_t WS2812FX::getFirstSelectedSegId(void) {
|
||||
uint8_t WS2812FX::getFirstSelectedSegId(void) const {
|
||||
size_t i = 0;
|
||||
for (segment &seg : _segments) {
|
||||
for (const segment &seg : _segments) {
|
||||
if (seg.isActive() && seg.isSelected()) return i;
|
||||
i++;
|
||||
}
|
||||
@@ -1474,14 +1481,14 @@ void WS2812FX::setMainSegmentId(uint8_t n) {
|
||||
return;
|
||||
}
|
||||
|
||||
uint8_t WS2812FX::getLastActiveSegmentId(void) {
|
||||
uint8_t WS2812FX::getLastActiveSegmentId(void) const {
|
||||
for (size_t i = _segments.size() -1; i > 0; i--) {
|
||||
if (_segments[i].isActive()) return i;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint8_t WS2812FX::getActiveSegmentsNum(void) {
|
||||
uint8_t WS2812FX::getActiveSegmentsNum(void) const {
|
||||
uint8_t c = 0;
|
||||
for (size_t i = 0; i < _segments.size(); i++) {
|
||||
if (_segments[i].isActive()) c++;
|
||||
@@ -1489,13 +1496,13 @@ uint8_t WS2812FX::getActiveSegmentsNum(void) {
|
||||
return c;
|
||||
}
|
||||
|
||||
uint16_t WS2812FX::getLengthTotal(void) {
|
||||
uint16_t WS2812FX::getLengthTotal(void) 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) {
|
||||
uint16_t WS2812FX::getLengthPhysical(void) const {
|
||||
unsigned len = 0;
|
||||
for (size_t b = 0; b < BusManager::getNumBusses(); b++) {
|
||||
Bus *bus = BusManager::getBus(b);
|
||||
@@ -1508,7 +1515,7 @@ uint16_t WS2812FX::getLengthPhysical(void) {
|
||||
//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) {
|
||||
bool WS2812FX::hasRGBWBus(void) const {
|
||||
for (size_t b = 0; b < BusManager::getNumBusses(); b++) {
|
||||
Bus *bus = BusManager::getBus(b);
|
||||
if (bus == nullptr || bus->getLength()==0) break;
|
||||
@@ -1517,7 +1524,7 @@ bool WS2812FX::hasRGBWBus(void) {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool WS2812FX::hasCCTBus(void) {
|
||||
bool WS2812FX::hasCCTBus(void) const {
|
||||
if (cctFromRgb && !correctWB) return false;
|
||||
for (size_t b = 0; b < BusManager::getNumBusses(); b++) {
|
||||
Bus *bus = BusManager::getBus(b);
|
||||
@@ -1704,8 +1711,6 @@ void WS2812FX::printSize() {
|
||||
DEBUG_PRINTF_P(PSTR("Modes: %d*%d=%uB\n"), sizeof(mode_ptr), _mode.size(), (_mode.capacity()*sizeof(mode_ptr)));
|
||||
DEBUG_PRINTF_P(PSTR("Data: %d*%d=%uB\n"), sizeof(const char *), _modeData.size(), (_modeData.capacity()*sizeof(const char *)));
|
||||
DEBUG_PRINTF_P(PSTR("Map: %d*%d=%uB\n"), sizeof(uint16_t), (int)customMappingSize, customMappingSize*sizeof(uint16_t));
|
||||
size = getLengthTotal();
|
||||
if (useGlobalLedBuffer) DEBUG_PRINTF_P(PSTR("Buffer: %d*%u=%uB\n"), sizeof(CRGB), size, size*sizeof(CRGB));
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -1769,13 +1774,15 @@ bool WS2812FX::deserializeMap(uint8_t n) {
|
||||
bool isFile = WLED_FS.exists(fileName);
|
||||
|
||||
customMappingSize = 0; // prevent use of mapping if anything goes wrong
|
||||
currentLedmap = 0;
|
||||
if (n == 0 || isFile) interfaceUpdateCallMode = CALL_MODE_WS_SEND; // schedule WS update (to inform UI)
|
||||
|
||||
if (!isFile && n==0 && isMatrix) {
|
||||
setUpMatrix();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!isFile || !requestJSONBufferLock(7)) return false; // this will trigger setUpMatrix() when called from wled.cpp
|
||||
if (!isFile || !requestJSONBufferLock(7)) return false;
|
||||
|
||||
if (!readObjectFromFile(fileName, nullptr, pDoc)) {
|
||||
DEBUG_PRINT(F("ERROR Invalid ledmap in ")); DEBUG_PRINTLN(fileName);
|
||||
@@ -1799,6 +1806,7 @@ bool WS2812FX::deserializeMap(uint8_t n) {
|
||||
if (!map.isNull() && map.size()) { // not an empty map
|
||||
customMappingSize = min((unsigned)map.size(), (unsigned)getLengthTotal());
|
||||
for (unsigned i=0; i<customMappingSize; i++) customMappingTable[i] = (uint16_t) (map[i]<0 ? 0xFFFFU : map[i]);
|
||||
currentLedmap = n;
|
||||
}
|
||||
} else {
|
||||
DEBUG_PRINTLN(F("ERROR LED map allocation error."));
|
||||
@@ -1808,7 +1816,7 @@ bool WS2812FX::deserializeMap(uint8_t n) {
|
||||
return (customMappingSize > 0);
|
||||
}
|
||||
|
||||
uint16_t IRAM_ATTR WS2812FX::getMappedPixelIndex(uint16_t index) {
|
||||
uint16_t IRAM_ATTR WS2812FX::getMappedPixelIndex(uint16_t index) const {
|
||||
// convert logical address to physical
|
||||
if (index < customMappingSize
|
||||
&& (realtimeMode == REALTIME_MODE_INACTIVE || realtimeRespectLedMaps)) index = customMappingTable[index];
|
||||
|
||||
@@ -34,7 +34,7 @@ struct NodeStruct
|
||||
|
||||
NodeStruct() : age(0), nodeType(0), build(0)
|
||||
{
|
||||
for (uint8_t i = 0; i < 4; ++i) { ip[i] = 0; }
|
||||
for (unsigned i = 0; i < 4; ++i) { ip[i] = 0; }
|
||||
}
|
||||
};
|
||||
typedef std::map<uint8_t, NodeStruct> NodesMap;
|
||||
|
||||
@@ -25,7 +25,7 @@ void alexaInit()
|
||||
// names are identical as the preset names, switching off can be done by switching off any of them
|
||||
if (alexaNumPresets) {
|
||||
String name = "";
|
||||
for (byte presetIndex = 1; presetIndex <= alexaNumPresets; presetIndex++)
|
||||
for (unsigned presetIndex = 1; presetIndex <= alexaNumPresets; presetIndex++)
|
||||
{
|
||||
if (!getPresetName(presetIndex, name)) break; // no more presets
|
||||
EspalexaDevice* dev = new EspalexaDevice(name.c_str(), onAlexaChange, EspalexaDeviceType::extendedcolor);
|
||||
@@ -64,7 +64,7 @@ void onAlexaChange(EspalexaDevice* dev)
|
||||
} else // switch-on behavior for preset devices
|
||||
{
|
||||
// turn off other preset devices
|
||||
for (byte i = 1; i < espalexa.getDeviceCount(); i++)
|
||||
for (unsigned i = 1; i < espalexa.getDeviceCount(); i++)
|
||||
{
|
||||
if (i == dev->getId()) continue;
|
||||
espalexa.getDevice(i)->setValue(0); // turn off other presets
|
||||
@@ -87,7 +87,7 @@ void onAlexaChange(EspalexaDevice* dev)
|
||||
applyPreset(macroAlexaOff, CALL_MODE_ALEXA);
|
||||
// below for loop stops Alexa from complaining if macroAlexaOff does not actually turn off
|
||||
}
|
||||
for (byte i = 0; i < espalexa.getDeviceCount(); i++)
|
||||
for (unsigned i = 0; i < espalexa.getDeviceCount(); i++)
|
||||
{
|
||||
espalexa.getDevice(i)->setValue(0);
|
||||
}
|
||||
|
||||
@@ -80,15 +80,15 @@ uint8_t IRAM_ATTR ColorOrderMap::getPixelColorOrder(uint16_t pix, uint8_t defaul
|
||||
|
||||
|
||||
uint32_t Bus::autoWhiteCalc(uint32_t c) {
|
||||
uint8_t aWM = _autoWhiteMode;
|
||||
unsigned aWM = _autoWhiteMode;
|
||||
if (_gAWM < AW_GLOBAL_DISABLED) aWM = _gAWM;
|
||||
if (aWM == RGBW_MODE_MANUAL_ONLY) return c;
|
||||
uint8_t w = W(c);
|
||||
unsigned w = W(c);
|
||||
//ignore auto-white calculation if w>0 and mode DUAL (DUAL behaves as BRIGHTER if w==0)
|
||||
if (w > 0 && aWM == RGBW_MODE_DUAL) return c;
|
||||
uint8_t r = R(c);
|
||||
uint8_t g = G(c);
|
||||
uint8_t b = B(c);
|
||||
unsigned r = R(c);
|
||||
unsigned g = G(c);
|
||||
unsigned b = B(c);
|
||||
if (aWM == RGBW_MODE_MAX) return RGBW32(r, g, b, r > g ? (r > b ? r : b) : (g > b ? g : b)); // brightest RGB channel
|
||||
w = r < g ? (r < b ? r : b) : (g < b ? g : b);
|
||||
if (aWM == RGBW_MODE_AUTO_ACCURATE) { r -= w; g -= w; b -= w; } //subtract w in ACCURATE mode
|
||||
@@ -207,7 +207,7 @@ void BusDigital::show() {
|
||||
if (!_valid) return;
|
||||
|
||||
uint8_t cctWW = 0, cctCW = 0;
|
||||
uint8_t newBri = estimateCurrentAndLimitBri(); // will fill _milliAmpsTotal
|
||||
unsigned newBri = estimateCurrentAndLimitBri(); // will fill _milliAmpsTotal
|
||||
if (newBri < _bri) PolyBus::setBrightness(_busPtr, _iType, newBri); // limit brightness to stay within current limits
|
||||
|
||||
if (_data) {
|
||||
@@ -215,7 +215,7 @@ void BusDigital::show() {
|
||||
int16_t oldCCT = Bus::_cct; // temporarily save bus CCT
|
||||
for (size_t i=0; i<_len; i++) {
|
||||
size_t offset = i * channels;
|
||||
uint8_t co = _colorOrderMap.getPixelColorOrder(i+_start, _colorOrder);
|
||||
unsigned co = _colorOrderMap.getPixelColorOrder(i+_start, _colorOrder);
|
||||
uint32_t c;
|
||||
if (_type == TYPE_WS2812_1CH_X3) { // map to correct IC, each controls 3 LEDs (_len is always a multiple of 3)
|
||||
switch (i%3) {
|
||||
@@ -234,7 +234,7 @@ void BusDigital::show() {
|
||||
Bus::_cct = _data[offset+channels-1];
|
||||
Bus::calculateCCT(c, cctWW, cctCW);
|
||||
}
|
||||
uint16_t pix = i;
|
||||
unsigned pix = i;
|
||||
if (_reversed) pix = _len - pix -1;
|
||||
pix += _skip;
|
||||
PolyBus::setPixelColor(_busPtr, _iType, pix, c, co, (cctCW<<8) | cctWW);
|
||||
@@ -246,7 +246,7 @@ void BusDigital::show() {
|
||||
Bus::_cct = oldCCT;
|
||||
} else {
|
||||
if (newBri < _bri) {
|
||||
uint16_t hwLen = _len;
|
||||
unsigned hwLen = _len;
|
||||
if (_type == TYPE_WS2812_1CH_X3) hwLen = NUM_ICS_WS2812_1CH_3X(_len); // only needs a third of "RGB" LEDs for NeoPixelBus
|
||||
for (unsigned i = 0; i < hwLen; i++) {
|
||||
// use 0 as color order, actual order does not matter here as we just update the channel values as-is
|
||||
@@ -270,12 +270,6 @@ bool BusDigital::canShow() {
|
||||
|
||||
void BusDigital::setBrightness(uint8_t b) {
|
||||
if (_bri == b) return;
|
||||
//Fix for turning off onboard LED breaking bus
|
||||
#ifdef LED_BUILTIN
|
||||
if (_bri == 0) { // && b > 0, covered by guard if above
|
||||
if (_pins[0] == LED_BUILTIN || _pins[1] == LED_BUILTIN) reinit();
|
||||
}
|
||||
#endif
|
||||
Bus::setBrightness(b);
|
||||
PolyBus::setBrightness(_busPtr, _iType, b);
|
||||
}
|
||||
@@ -308,9 +302,9 @@ void IRAM_ATTR BusDigital::setPixelColor(uint16_t pix, uint32_t c) {
|
||||
} else {
|
||||
if (_reversed) pix = _len - pix -1;
|
||||
pix += _skip;
|
||||
uint8_t co = _colorOrderMap.getPixelColorOrder(pix+_start, _colorOrder);
|
||||
unsigned co = _colorOrderMap.getPixelColorOrder(pix+_start, _colorOrder);
|
||||
if (_type == TYPE_WS2812_1CH_X3) { // map to correct IC, each controls 3 LEDs
|
||||
uint16_t pOld = pix;
|
||||
unsigned pOld = pix;
|
||||
pix = IC_INDEX_WS2812_1CH_3X(pix);
|
||||
uint32_t cOld = restoreColorLossy(PolyBus::getPixelColor(_busPtr, _iType, pix, co),_bri);
|
||||
switch (pOld % 3) { // change only the single channel (TODO: this can cause loss because of get/set)
|
||||
@@ -339,12 +333,12 @@ uint32_t IRAM_ATTR BusDigital::getPixelColor(uint16_t pix) {
|
||||
} else {
|
||||
if (_reversed) pix = _len - pix -1;
|
||||
pix += _skip;
|
||||
uint8_t co = _colorOrderMap.getPixelColorOrder(pix+_start, _colorOrder);
|
||||
unsigned co = _colorOrderMap.getPixelColorOrder(pix+_start, _colorOrder);
|
||||
uint32_t c = restoreColorLossy(PolyBus::getPixelColor(_busPtr, _iType, (_type==TYPE_WS2812_1CH_X3) ? IC_INDEX_WS2812_1CH_3X(pix) : pix, co),_bri);
|
||||
if (_type == TYPE_WS2812_1CH_X3) { // map to correct IC, each controls 3 LEDs
|
||||
uint8_t r = R(c);
|
||||
uint8_t g = _reversed ? B(c) : G(c); // should G and B be switched if _reversed?
|
||||
uint8_t b = _reversed ? G(c) : B(c);
|
||||
unsigned r = R(c);
|
||||
unsigned g = _reversed ? B(c) : G(c); // should G and B be switched if _reversed?
|
||||
unsigned b = _reversed ? G(c) : B(c);
|
||||
switch (pix % 3) { // get only the single channel
|
||||
case 0: c = RGBW32(g, g, g, g); break;
|
||||
case 1: c = RGBW32(r, r, r, r); break;
|
||||
@@ -356,7 +350,7 @@ uint32_t IRAM_ATTR BusDigital::getPixelColor(uint16_t pix) {
|
||||
}
|
||||
|
||||
uint8_t BusDigital::getPins(uint8_t* pinArray) {
|
||||
uint8_t numPins = IS_2PIN(_type) ? 2 : 1;
|
||||
unsigned numPins = IS_2PIN(_type) ? 2 : 1;
|
||||
for (unsigned i = 0; i < numPins; i++) pinArray[i] = _pins[i];
|
||||
return numPins;
|
||||
}
|
||||
@@ -384,31 +378,49 @@ void BusDigital::cleanup() {
|
||||
}
|
||||
|
||||
|
||||
#ifdef ESP8266
|
||||
// 1 MHz clock
|
||||
#define CLOCK_FREQUENCY 1000000UL
|
||||
#else
|
||||
// Use XTAL clock if possible to avoid timer frequency error when setting APB clock < 80 Mhz
|
||||
// https://github.com/espressif/arduino-esp32/blob/2.0.2/cores/esp32/esp32-hal-ledc.c
|
||||
#ifdef SOC_LEDC_SUPPORT_XTAL_CLOCK
|
||||
#define CLOCK_FREQUENCY 40000000UL
|
||||
#else
|
||||
#define CLOCK_FREQUENCY 80000000UL
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef ESP8266
|
||||
#define MAX_BIT_WIDTH 10
|
||||
#else
|
||||
#ifdef SOC_LEDC_TIMER_BIT_WIDE_NUM
|
||||
// C6/H2/P4: 20 bit, S2/S3/C2/C3: 14 bit
|
||||
#define MAX_BIT_WIDTH SOC_LEDC_TIMER_BIT_WIDE_NUM
|
||||
#else
|
||||
// ESP32: 20 bit (but in reality we would never go beyond 16 bit as the frequency would be to low)
|
||||
#define MAX_BIT_WIDTH 20
|
||||
#endif
|
||||
#endif
|
||||
|
||||
BusPwm::BusPwm(BusConfig &bc)
|
||||
: Bus(bc.type, bc.start, bc.autoWhite, 1, bc.reversed)
|
||||
{
|
||||
if (!IS_PWM(bc.type)) return;
|
||||
uint8_t numPins = NUM_PWM_PINS(bc.type);
|
||||
unsigned numPins = NUM_PWM_PINS(bc.type);
|
||||
_frequency = bc.frequency ? bc.frequency : WLED_PWM_FREQ;
|
||||
// duty cycle resolution (_depth) can be extracted from this formula: CLOCK_FREQUENCY > _frequency * 2^_depth
|
||||
for (_depth = MAX_BIT_WIDTH; _depth > 8; _depth--) if (((CLOCK_FREQUENCY/_frequency) >> _depth) > 0) break;
|
||||
|
||||
#ifdef ESP8266
|
||||
// duty cycle resolution (_depth) can be extracted from this formula: 1MHz > _frequency * 2^_depth
|
||||
if (_frequency > 1760) _depth = 8;
|
||||
else if (_frequency > 880) _depth = 9;
|
||||
else _depth = 10; // WLED_PWM_FREQ <= 880Hz
|
||||
#ifdef ESP8266
|
||||
analogWriteRange((1<<_depth)-1);
|
||||
analogWriteFreq(_frequency);
|
||||
#else
|
||||
#else
|
||||
_ledcStart = pinManager.allocateLedc(numPins);
|
||||
if (_ledcStart == 255) { //no more free LEDC channels
|
||||
deallocatePins(); return;
|
||||
}
|
||||
// duty cycle resolution (_depth) can be extracted from this formula: 80MHz > _frequency * 2^_depth
|
||||
if (_frequency > 78124) _depth = 9;
|
||||
else if (_frequency > 39062) _depth = 10;
|
||||
else if (_frequency > 19531) _depth = 11;
|
||||
else _depth = 12; // WLED_PWM_FREQ <= 19531Hz
|
||||
#endif
|
||||
#endif
|
||||
|
||||
for (unsigned i = 0; i < numPins; i++) {
|
||||
uint8_t currentPin = bc.pins[i];
|
||||
@@ -425,7 +437,7 @@ BusPwm::BusPwm(BusConfig &bc)
|
||||
}
|
||||
_data = _pwmdata; // avoid malloc() and use stack
|
||||
_valid = true;
|
||||
DEBUG_PRINTF_P(PSTR("%successfully inited PWM strip with type %u and pins %u,%u,%u,%u,%u\n"), _valid?"S":"Uns", bc.type, _pins[0], _pins[1], _pins[2], _pins[3], _pins[4]);
|
||||
DEBUG_PRINTF_P(PSTR("%successfully inited PWM strip with type %u, frequency %u, bit depth %u and pins %u,%u,%u,%u,%u\n"), _valid?"S":"Uns", bc.type, _frequency, _depth, _pins[0], _pins[1], _pins[2], _pins[3], _pins[4]);
|
||||
}
|
||||
|
||||
void BusPwm::setPixelColor(uint16_t pix, uint32_t c) {
|
||||
@@ -485,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;
|
||||
uint8_t numPins = NUM_PWM_PINS(_type);
|
||||
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;
|
||||
@@ -538,7 +523,7 @@ void BusPwm::show() {
|
||||
|
||||
uint8_t BusPwm::getPins(uint8_t* pinArray) {
|
||||
if (!_valid) return 0;
|
||||
uint8_t numPins = NUM_PWM_PINS(_type);
|
||||
unsigned numPins = NUM_PWM_PINS(_type);
|
||||
for (unsigned i = 0; i < numPins; i++) {
|
||||
pinArray[i] = _pins[i];
|
||||
}
|
||||
@@ -546,7 +531,7 @@ uint8_t BusPwm::getPins(uint8_t* pinArray) {
|
||||
}
|
||||
|
||||
void BusPwm::deallocatePins() {
|
||||
uint8_t numPins = NUM_PWM_PINS(_type);
|
||||
unsigned numPins = NUM_PWM_PINS(_type);
|
||||
for (unsigned i = 0; i < numPins; i++) {
|
||||
pinManager.deallocatePin(_pins[i], PinOwner::BusPwm);
|
||||
if (!pinManager.isPinOk(_pins[i])) continue;
|
||||
@@ -638,7 +623,7 @@ void BusNetwork::setPixelColor(uint16_t pix, uint32_t c) {
|
||||
if (!_valid || pix >= _len) return;
|
||||
if (_rgbw) c = autoWhiteCalc(c);
|
||||
if (Bus::_cct >= 1900) c = colorBalanceFromKelvin(Bus::_cct, c); //color correction from CCT
|
||||
uint16_t offset = pix * _UDPchannels;
|
||||
unsigned offset = pix * _UDPchannels;
|
||||
_data[offset] = R(c);
|
||||
_data[offset+1] = G(c);
|
||||
_data[offset+2] = B(c);
|
||||
@@ -647,7 +632,7 @@ void BusNetwork::setPixelColor(uint16_t pix, uint32_t c) {
|
||||
|
||||
uint32_t BusNetwork::getPixelColor(uint16_t pix) {
|
||||
if (!_valid || pix >= _len) return 0;
|
||||
uint16_t offset = pix * _UDPchannels;
|
||||
unsigned offset = pix * _UDPchannels;
|
||||
return RGBW32(_data[offset], _data[offset+1], _data[offset+2], (_rgbw ? _data[offset+3] : 0));
|
||||
}
|
||||
|
||||
@@ -676,20 +661,26 @@ void BusNetwork::cleanup() {
|
||||
uint32_t BusManager::memUsage(BusConfig &bc) {
|
||||
if (bc.type == TYPE_ONOFF || IS_PWM(bc.type)) return 5;
|
||||
|
||||
uint16_t len = bc.count + bc.skipAmount;
|
||||
uint16_t channels = Bus::getNumberOfChannels(bc.type);
|
||||
uint16_t multiplier = 1;
|
||||
unsigned len = bc.count + bc.skipAmount;
|
||||
unsigned channels = Bus::getNumberOfChannels(bc.type);
|
||||
unsigned multiplier = 1;
|
||||
if (IS_DIGITAL(bc.type)) { // digital types
|
||||
if (IS_16BIT(bc.type)) len *= 2; // 16-bit LEDs
|
||||
#ifdef ESP8266
|
||||
if (bc.pins[0] == 3) { //8266 DMA uses 5x the mem
|
||||
multiplier = 5;
|
||||
}
|
||||
#else //ESP32 RMT uses double buffer, I2S uses 5x buffer
|
||||
multiplier = 2;
|
||||
#else //ESP32 RMT uses double buffer, parallel I2S uses 8x buffer (3 times)
|
||||
multiplier = PolyBus::isParallelI2S1Output() ? 24 : 2;
|
||||
#endif
|
||||
}
|
||||
return len * channels * multiplier; //RGB
|
||||
return (len * multiplier + bc.doubleBuffer * (bc.count + bc.skipAmount)) * channels;
|
||||
}
|
||||
|
||||
uint32_t BusManager::memUsage(unsigned maxChannels, unsigned maxCount, unsigned minBuses) {
|
||||
//ESP32 RMT uses double buffer, parallel I2S uses 8x buffer (3 times)
|
||||
unsigned multiplier = PolyBus::isParallelI2S1Output() ? 3 : 2;
|
||||
return (maxChannels * maxCount * minBuses * multiplier);
|
||||
}
|
||||
|
||||
int BusManager::add(BusConfig &bc) {
|
||||
@@ -706,6 +697,11 @@ int BusManager::add(BusConfig &bc) {
|
||||
return numBusses++;
|
||||
}
|
||||
|
||||
void BusManager::useParallelOutput(void) {
|
||||
_parallelOutputs = 8; // hardcoded since we use NPB I2S x8 methods
|
||||
PolyBus::setParallelI2S1Output();
|
||||
}
|
||||
|
||||
//do not call this method from system context (network callback)
|
||||
void BusManager::removeAll() {
|
||||
DEBUG_PRINTLN(F("Removing all."));
|
||||
@@ -713,6 +709,79 @@ void BusManager::removeAll() {
|
||||
while (!canAllShow()) yield();
|
||||
for (unsigned i = 0; i < numBusses; i++) delete busses[i];
|
||||
numBusses = 0;
|
||||
_parallelOutputs = 1;
|
||||
PolyBus::setParallelI2S1Output(false);
|
||||
}
|
||||
|
||||
#ifdef ESP32_DATA_IDLE_HIGH
|
||||
// #2478
|
||||
// If enabled, RMT idle level is set to HIGH when off
|
||||
// to prevent leakage current when using an N-channel MOSFET to toggle LED power
|
||||
void BusManager::esp32RMTInvertIdle() {
|
||||
bool idle_out;
|
||||
unsigned rmt = 0;
|
||||
for (unsigned u = 0; u < numBusses(); u++) {
|
||||
#if defined(CONFIG_IDF_TARGET_ESP32C3) // 2 RMT, only has 1 I2S but NPB does not support it ATM
|
||||
if (u > 1) return;
|
||||
rmt = u;
|
||||
#elif defined(CONFIG_IDF_TARGET_ESP32S2) // 4 RMT, only has 1 I2S bus, supported in NPB
|
||||
if (u > 3) return;
|
||||
rmt = u;
|
||||
#elif defined(CONFIG_IDF_TARGET_ESP32S3) // 4 RMT, has 2 I2S but NPB does not support them ATM
|
||||
if (u > 3) return;
|
||||
rmt = u;
|
||||
#else
|
||||
if (u < _parallelOutputs) continue;
|
||||
if (u >= _parallelOutputs + 8) return; // only 8 RMT channels
|
||||
rmt = u - _parallelOutputs;
|
||||
#endif
|
||||
if (busses[u]->getLength()==0 || !IS_DIGITAL(busses[u]->getType()) || IS_2PIN(busses[u]->getType())) continue;
|
||||
//assumes that bus number to rmt channel mapping stays 1:1
|
||||
rmt_channel_t ch = static_cast<rmt_channel_t>(rmt);
|
||||
rmt_idle_level_t lvl;
|
||||
rmt_get_idle_level(ch, &idle_out, &lvl);
|
||||
if (lvl == RMT_IDLE_LEVEL_HIGH) lvl = RMT_IDLE_LEVEL_LOW;
|
||||
else if (lvl == RMT_IDLE_LEVEL_LOW) lvl = RMT_IDLE_LEVEL_HIGH;
|
||||
else continue;
|
||||
rmt_set_idle_level(ch, idle_out, lvl);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
void BusManager::on() {
|
||||
#ifdef ESP8266
|
||||
//Fix for turning off onboard LED breaking bus
|
||||
if (pinManager.getPinOwner(LED_BUILTIN) == PinOwner::BusDigital) {
|
||||
for (unsigned i = 0; i < numBusses; i++) {
|
||||
uint8_t pins[2] = {255,255};
|
||||
if (IS_DIGITAL(busses[i]->getType()) && busses[i]->getPins(pins)) {
|
||||
if (pins[0] == LED_BUILTIN || pins[1] == LED_BUILTIN) {
|
||||
BusDigital *bus = static_cast<BusDigital*>(busses[i]);
|
||||
bus->reinit();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#ifdef ESP32_DATA_IDLE_HIGH
|
||||
esp32RMTInvertIdle();
|
||||
#endif
|
||||
}
|
||||
|
||||
void BusManager::off() {
|
||||
#ifdef ESP8266
|
||||
// turn off built-in LED if strip is turned off
|
||||
// this will break digital bus so will need to be re-initialised on On
|
||||
if (pinManager.getPinOwner(LED_BUILTIN) == PinOwner::BusDigital) {
|
||||
for (unsigned i = 0; i < numBusses; i++) if (busses[i]->isOffRefreshRequired()) return;
|
||||
pinMode(LED_BUILTIN, OUTPUT);
|
||||
digitalWrite(LED_BUILTIN, HIGH);
|
||||
}
|
||||
#endif
|
||||
#ifdef ESP32_DATA_IDLE_HIGH
|
||||
esp32RMTInvertIdle();
|
||||
#endif
|
||||
}
|
||||
|
||||
void BusManager::show() {
|
||||
@@ -776,11 +845,13 @@ Bus* BusManager::getBus(uint8_t busNr) {
|
||||
|
||||
//semi-duplicate of strip.getLengthTotal() (though that just returns strip._length, calculated in finalizeInit())
|
||||
uint16_t BusManager::getTotalLength() {
|
||||
uint16_t len = 0;
|
||||
unsigned len = 0;
|
||||
for (unsigned i=0; i<numBusses; i++) len += busses[i]->getLength();
|
||||
return len;
|
||||
}
|
||||
|
||||
bool PolyBus::useParallelI2S = false;
|
||||
|
||||
// Bus static member definition
|
||||
int16_t Bus::_cct = -1;
|
||||
uint8_t Bus::_cctBlend = 0;
|
||||
@@ -792,4 +863,5 @@ uint8_t BusManager::numBusses = 0;
|
||||
Bus* BusManager::busses[WLED_MAX_BUSSES+WLED_MIN_VIRTUAL_BUSSES];
|
||||
ColorOrderMap BusManager::colorOrderMap = {};
|
||||
uint16_t BusManager::_milliAmpsUsed = 0;
|
||||
uint16_t BusManager::_milliAmpsMax = ABL_MILLIAMPS_DEFAULT;
|
||||
uint16_t BusManager::_milliAmpsMax = ABL_MILLIAMPS_DEFAULT;
|
||||
uint8_t BusManager::_parallelOutputs = 1;
|
||||
|
||||
@@ -21,10 +21,6 @@ uint16_t approximateKelvinFromRGB(uint32_t rgb);
|
||||
#define IC_INDEX_WS2812_2CH_3X(i) ((i)*2/3)
|
||||
#define WS2812_2CH_3X_SPANS_2_ICS(i) ((i)&0x01) // every other LED zone is on two different ICs
|
||||
|
||||
// flag for using double buffering in BusDigital
|
||||
extern bool useGlobalLedBuffer;
|
||||
|
||||
|
||||
//temporary struct for passing bus configuration to bus
|
||||
struct BusConfig {
|
||||
uint8_t type;
|
||||
@@ -41,7 +37,7 @@ struct BusConfig {
|
||||
uint8_t milliAmpsPerLed;
|
||||
uint16_t milliAmpsMax;
|
||||
|
||||
BusConfig(uint8_t busType, uint8_t* ppins, uint16_t pstart, uint16_t len = 1, uint8_t pcolorOrder = COL_ORDER_GRB, bool rev = false, uint8_t skip = 0, byte aw=RGBW_MODE_MANUAL_ONLY, uint16_t clock_kHz=0U, bool dblBfr=false, uint8_t maPerLed=55, uint16_t maMax=ABL_MILLIAMPS_DEFAULT)
|
||||
BusConfig(uint8_t busType, uint8_t* ppins, uint16_t pstart, uint16_t len = 1, uint8_t pcolorOrder = COL_ORDER_GRB, bool rev = false, uint8_t skip = 0, byte aw=RGBW_MODE_MANUAL_ONLY, uint16_t clock_kHz=0U, bool dblBfr=false, uint8_t maPerLed=LED_MILLIAMPS_DEFAULT, uint16_t maMax=ABL_MILLIAMPS_DEFAULT)
|
||||
: count(len)
|
||||
, start(pstart)
|
||||
, colorOrder(pcolorOrder)
|
||||
@@ -133,7 +129,7 @@ class Bus {
|
||||
virtual uint32_t getPixelColor(uint16_t pix) { return 0; }
|
||||
virtual void setBrightness(uint8_t b) { _bri = b; };
|
||||
virtual uint8_t getPins(uint8_t* pinArray) { return 0; }
|
||||
virtual uint16_t getLength() { return _len; }
|
||||
virtual uint16_t getLength() { return isOk() ? _len : 0; }
|
||||
virtual void setColorOrder(uint8_t co) {}
|
||||
virtual uint8_t getColorOrder() { return COL_ORDER_RGB; }
|
||||
virtual uint8_t skippedLeds() { return 0; }
|
||||
@@ -161,7 +157,7 @@ class Bus {
|
||||
static bool hasWhite(uint8_t type) {
|
||||
if ((type >= TYPE_WS2812_1CH && type <= TYPE_WS2812_WWA) ||
|
||||
type == TYPE_SK6812_RGBW || type == TYPE_TM1814 || type == TYPE_UCS8904 ||
|
||||
type == TYPE_FW1906 || type == TYPE_WS2805) return true; // digital types with white channel
|
||||
type == TYPE_FW1906 || type == TYPE_WS2805 || type == TYPE_SM16825) return true; // digital types with white channel
|
||||
if (type > TYPE_ONOFF && type <= TYPE_ANALOG_5CH && type != TYPE_ANALOG_3CH) return true; // analog types with white channel
|
||||
if (type == TYPE_NET_DDP_RGBW || type == TYPE_NET_ARTNET_RGBW) return true; // network types with white channel
|
||||
return false;
|
||||
@@ -170,13 +166,15 @@ class Bus {
|
||||
static bool hasCCT(uint8_t type) {
|
||||
if (type == TYPE_WS2812_2CH_X3 || type == TYPE_WS2812_WWA ||
|
||||
type == TYPE_ANALOG_2CH || type == TYPE_ANALOG_5CH ||
|
||||
type == TYPE_FW1906 || type == TYPE_WS2805 ) return true;
|
||||
type == TYPE_FW1906 || type == TYPE_WS2805 ||
|
||||
type == TYPE_SM16825) return true;
|
||||
return false;
|
||||
}
|
||||
static int16_t getCCT() { return _cct; }
|
||||
static inline int16_t getCCT() { return _cct; }
|
||||
static void setCCT(int16_t cct) {
|
||||
_cct = cct;
|
||||
}
|
||||
static inline uint8_t getCCTBlend() { return _cctBlend; }
|
||||
static void setCCTBlend(uint8_t b) {
|
||||
if (b > 100) b = 100;
|
||||
_cctBlend = (b * 127) / 100;
|
||||
@@ -359,14 +357,19 @@ class BusManager {
|
||||
|
||||
//utility to get the approx. memory usage of a given BusConfig
|
||||
static uint32_t memUsage(BusConfig &bc);
|
||||
static uint32_t memUsage(unsigned channels, unsigned count, unsigned buses = 1);
|
||||
static uint16_t currentMilliamps(void) { return _milliAmpsUsed; }
|
||||
static uint16_t ablMilliampsMax(void) { return _milliAmpsMax; }
|
||||
|
||||
static int add(BusConfig &bc);
|
||||
static void useParallelOutput(void); // workaround for inaccessible PolyBus
|
||||
|
||||
//do not call this method from system context (network callback)
|
||||
static void removeAll();
|
||||
|
||||
static void on(void);
|
||||
static void off(void);
|
||||
|
||||
static void show();
|
||||
static bool canAllShow();
|
||||
static void setStatusPixel(uint32_t c);
|
||||
@@ -394,7 +397,11 @@ class BusManager {
|
||||
static ColorOrderMap colorOrderMap;
|
||||
static uint16_t _milliAmpsUsed;
|
||||
static uint16_t _milliAmpsMax;
|
||||
static uint8_t _parallelOutputs;
|
||||
|
||||
#ifdef ESP32_DATA_IDLE_HIGH
|
||||
static void esp32RMTInvertIdle();
|
||||
#endif
|
||||
static uint8_t getNumVirtualBusses() {
|
||||
int j = 0;
|
||||
for (int i=0; i<numBusses; i++) if (busses[i]->getType() >= TYPE_NET_DDP_RGB && busses[i]->getType() < 96) j++;
|
||||
|
||||
@@ -93,7 +93,7 @@ void doublePressAction(uint8_t b)
|
||||
bool isButtonPressed(uint8_t i)
|
||||
{
|
||||
if (btnPin[i]<0) return false;
|
||||
uint8_t pin = btnPin[i];
|
||||
unsigned pin = btnPin[i];
|
||||
|
||||
switch (buttonType[i]) {
|
||||
case BTN_TYPE_NONE:
|
||||
@@ -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);}
|
||||
@@ -171,20 +171,20 @@ void handleAnalog(uint8_t b)
|
||||
{
|
||||
static uint8_t oldRead[WLED_MAX_BUTTONS] = {0};
|
||||
static float filteredReading[WLED_MAX_BUTTONS] = {0.0f};
|
||||
uint16_t rawReading; // raw value from analogRead, scaled to 12bit
|
||||
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
|
||||
#else
|
||||
if ((btnPin[b] < 0) || (digitalPinToAnalogChannel(btnPin[b]) < 0)) return; // pin must support analog ADC - newer esp32 frameworks throw lots of warnings otherwise
|
||||
if ((btnPin[b] < 0) /*|| (digitalPinToAnalogChannel(btnPin[b]) < 0)*/) return; // pin must support analog ADC - newer esp32 frameworks throw lots of warnings otherwise
|
||||
rawReading = analogRead(btnPin[b]); // collect at full 12bit resolution
|
||||
#endif
|
||||
yield(); // keep WiFi task running - analog read may take several millis on ESP8266
|
||||
|
||||
filteredReading[b] += POT_SMOOTHING * ((float(rawReading) / 16.0f) - filteredReading[b]); // filter raw input, and scale to [0..255]
|
||||
uint16_t aRead = max(min(int(filteredReading[b]), 255), 0); // squash into 8bit
|
||||
unsigned aRead = max(min(int(filteredReading[b]), 255), 0); // squash into 8bit
|
||||
if(aRead <= POT_SENSITIVITY) aRead = 0; // make sure that 0 and 255 are used
|
||||
if(aRead >= 255-POT_SENSITIVITY) aRead = 255;
|
||||
|
||||
@@ -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
|
||||
@@ -260,7 +260,7 @@ void handleButton()
|
||||
if (strip.isUpdating() && (now - lastRun < ANALOG_BTN_READ_CYCLE+1)) return; // don't interfere with strip update (unless strip is updating continuously, e.g. very long strips)
|
||||
lastRun = now;
|
||||
|
||||
for (uint8_t b=0; b<WLED_MAX_BUTTONS; b++) {
|
||||
for (unsigned b=0; b<WLED_MAX_BUTTONS; b++) {
|
||||
#ifdef ESP8266
|
||||
if ((btnPin[b]<0 && !(buttonType[b] == BTN_TYPE_ANALOG || buttonType[b] == BTN_TYPE_ANALOG_INVERTED)) || buttonType[b] == BTN_TYPE_NONE) continue;
|
||||
#else
|
||||
@@ -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
|
||||
@@ -358,69 +358,35 @@ void handleButton()
|
||||
}
|
||||
}
|
||||
|
||||
// If enabled, RMT idle level is set to HIGH when off
|
||||
// to prevent leakage current when using an N-channel MOSFET to toggle LED power
|
||||
#ifdef ESP32_DATA_IDLE_HIGH
|
||||
void esp32RMTInvertIdle()
|
||||
{
|
||||
bool idle_out;
|
||||
for (uint8_t u = 0; u < BusManager::getNumBusses(); u++)
|
||||
{
|
||||
if (u > 7) return; // only 8 RMT channels, TODO: ESP32 variants have less RMT channels
|
||||
Bus *bus = BusManager::getBus(u);
|
||||
if (!bus || bus->getLength()==0 || !IS_DIGITAL(bus->getType()) || IS_2PIN(bus->getType())) continue;
|
||||
//assumes that bus number to rmt channel mapping stays 1:1
|
||||
rmt_channel_t ch = static_cast<rmt_channel_t>(u);
|
||||
rmt_idle_level_t lvl;
|
||||
rmt_get_idle_level(ch, &idle_out, &lvl);
|
||||
if (lvl == RMT_IDLE_LEVEL_HIGH) lvl = RMT_IDLE_LEVEL_LOW;
|
||||
else if (lvl == RMT_IDLE_LEVEL_LOW) lvl = RMT_IDLE_LEVEL_HIGH;
|
||||
else continue;
|
||||
rmt_set_idle_level(ch, idle_out, lvl);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// handleIO() happens *after* handleTransitions() (see wled.cpp) which may change bri/briT but *before* strip.service()
|
||||
// where actual LED painting occurrs
|
||||
// this is important for relay control and in the event of turning off on-board LED
|
||||
void handleIO()
|
||||
{
|
||||
handleButton();
|
||||
|
||||
//set relay when LEDs turn on
|
||||
if (strip.getBrightness())
|
||||
{
|
||||
// if we want to control on-board LED (ESP8266) or relay we have to do it here as the final show() may not happen until
|
||||
// next loop() cycle
|
||||
if (strip.getBrightness()) {
|
||||
lastOnTime = millis();
|
||||
if (offMode)
|
||||
{
|
||||
#ifdef ESP32_DATA_IDLE_HIGH
|
||||
esp32RMTInvertIdle();
|
||||
#endif
|
||||
if (offMode) {
|
||||
BusManager::on();
|
||||
if (rlyPin>=0) {
|
||||
pinMode(rlyPin, rlyOpenDrain ? OUTPUT_OPEN_DRAIN : OUTPUT);
|
||||
digitalWrite(rlyPin, rlyMde);
|
||||
}
|
||||
offMode = false;
|
||||
}
|
||||
} else if (millis() - lastOnTime > 600)
|
||||
{
|
||||
} else if (millis() - lastOnTime > 600 && !strip.needsUpdate()) {
|
||||
// for turning LED or relay off we need to wait until strip no longer needs updates (strip.trigger())
|
||||
if (!offMode) {
|
||||
#ifdef ESP8266
|
||||
// turn off built-in LED if strip is turned off
|
||||
// this will break digital bus so will need to be re-initialised on On
|
||||
PinOwner ledPinOwner = pinManager.getPinOwner(LED_BUILTIN);
|
||||
if (!strip.isOffRefreshRequired() && (ledPinOwner == PinOwner::None || ledPinOwner == PinOwner::BusDigital)) {
|
||||
pinMode(LED_BUILTIN, OUTPUT);
|
||||
digitalWrite(LED_BUILTIN, HIGH);
|
||||
}
|
||||
#endif
|
||||
#ifdef ESP32_DATA_IDLE_HIGH
|
||||
esp32RMTInvertIdle();
|
||||
#endif
|
||||
BusManager::off();
|
||||
if (rlyPin>=0) {
|
||||
pinMode(rlyPin, rlyOpenDrain ? OUTPUT_OPEN_DRAIN : OUTPUT);
|
||||
digitalWrite(rlyPin, !rlyMde);
|
||||
}
|
||||
offMode = true;
|
||||
}
|
||||
offMode = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
170
wled00/cfg.cpp
@@ -20,17 +20,19 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
|
||||
|
||||
//long vid = doc[F("vid")]; // 2010020
|
||||
|
||||
#ifdef WLED_USE_ETHERNET
|
||||
#ifdef WLED_USE_ETHERNET
|
||||
JsonObject ethernet = doc[F("eth")];
|
||||
CJSON(ethernetType, ethernet["type"]);
|
||||
// NOTE: Ethernet configuration takes priority over other use of pins
|
||||
WLED::instance().initEthernet();
|
||||
#endif
|
||||
#endif
|
||||
|
||||
JsonObject id = doc["id"];
|
||||
getStringFromJson(cmDNS, id[F("mdns")], 33);
|
||||
getStringFromJson(serverDescription, id[F("name")], 33);
|
||||
#ifndef WLED_DISABLE_ALEXA
|
||||
getStringFromJson(alexaInvocationName, id[F("inv")], 33);
|
||||
#endif
|
||||
CJSON(simplifiedUI, id[F("sui")]);
|
||||
|
||||
JsonObject nw = doc["nw"];
|
||||
@@ -79,25 +81,26 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
|
||||
getStringFromJson(apSSID, ap[F("ssid")], 33);
|
||||
getStringFromJson(apPass, ap["psk"] , 65); //normally not present due to security
|
||||
//int ap_pskl = ap[F("pskl")];
|
||||
|
||||
CJSON(apChannel, ap[F("chan")]);
|
||||
if (apChannel > 13 || apChannel < 1) apChannel = 1;
|
||||
|
||||
CJSON(apHide, ap[F("hide")]);
|
||||
if (apHide > 1) apHide = 1;
|
||||
|
||||
CJSON(apBehavior, ap[F("behav")]);
|
||||
|
||||
/*
|
||||
JsonArray ap_ip = ap["ip"];
|
||||
for (byte i = 0; i < 4; i++) {
|
||||
for (unsigned i = 0; i < 4; i++) {
|
||||
apIP[i] = ap_ip;
|
||||
}
|
||||
*/
|
||||
|
||||
noWifiSleep = doc[F("wifi")][F("sleep")] | !noWifiSleep; // inverted
|
||||
noWifiSleep = !noWifiSleep;
|
||||
force802_3g = doc[F("wifi")][F("phy")] | force802_3g; //force phy mode g?
|
||||
JsonObject wifi = doc[F("wifi")];
|
||||
noWifiSleep = !(wifi[F("sleep")] | !noWifiSleep); // inverted
|
||||
//noWifiSleep = !noWifiSleep;
|
||||
CJSON(force802_3g, wifi[F("phy")]); //force phy mode g?
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
CJSON(txPower, wifi[F("txpwr")]);
|
||||
txPower = min(max((int)txPower, (int)WIFI_POWER_2dBm), (int)WIFI_POWER_19_5dBm);
|
||||
#endif
|
||||
|
||||
JsonObject hw = doc[F("hw")];
|
||||
|
||||
@@ -108,8 +111,8 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
|
||||
uint16_t ablMilliampsMax = hw_led[F("maxpwr")] | BusManager::ablMilliampsMax();
|
||||
BusManager::setMilliampsMax(ablMilliampsMax);
|
||||
Bus::setGlobalAWMode(hw_led[F("rgbwm")] | AW_GLOBAL_DISABLED);
|
||||
CJSON(correctWB, hw_led["cct"]);
|
||||
CJSON(cctFromRgb, hw_led[F("cr")]);
|
||||
CJSON(strip.correctWB, hw_led["cct"]);
|
||||
CJSON(strip.cctFromRgb, hw_led[F("cr")]);
|
||||
CJSON(cctICused, hw_led[F("ic")]);
|
||||
CJSON(strip.cctBlending, hw_led[F("cb")]);
|
||||
Bus::setCCTBlend(strip.cctBlending);
|
||||
@@ -156,23 +159,49 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
|
||||
JsonArray ins = hw_led["ins"];
|
||||
|
||||
if (fromFS || !ins.isNull()) {
|
||||
DEBUG_PRINTF_P(PSTR("Heap before buses: %d\n"), ESP.getFreeHeap());
|
||||
int s = 0; // bus iterator
|
||||
if (fromFS) BusManager::removeAll(); // can't safely manipulate busses directly in network callback
|
||||
uint32_t mem = 0, globalBufMem = 0;
|
||||
uint16_t maxlen = 0;
|
||||
bool busesChanged = false;
|
||||
unsigned mem = 0;
|
||||
|
||||
// determine if it is sensible to use parallel I2S outputs on ESP32 (i.e. more than 5 outputs = 1 I2S + 4 RMT)
|
||||
bool useParallel = false;
|
||||
#if defined(ARDUINO_ARCH_ESP32) && !defined(ARDUINO_ARCH_ESP32S2) && !defined(ARDUINO_ARCH_ESP32S3) && !defined(ARDUINO_ARCH_ESP32C3)
|
||||
unsigned digitalCount = 0;
|
||||
unsigned maxLedsOnBus = 0;
|
||||
unsigned maxChannels = 0;
|
||||
for (JsonObject elm : ins) {
|
||||
unsigned type = elm["type"] | TYPE_WS2812_RGB;
|
||||
unsigned len = elm["len"] | DEFAULT_LED_COUNT;
|
||||
if (!IS_DIGITAL(type)) continue;
|
||||
if (!IS_2PIN(type)) {
|
||||
digitalCount++;
|
||||
unsigned channels = Bus::getNumberOfChannels(type);
|
||||
if (len > maxLedsOnBus) maxLedsOnBus = len;
|
||||
if (channels > maxChannels) maxChannels = channels;
|
||||
}
|
||||
}
|
||||
DEBUG_PRINTF_P(PSTR("Maximum LEDs on a bus: %u\nDigital buses: %u\n"), maxLedsOnBus, digitalCount);
|
||||
// we may remove 300 LEDs per bus limit when NeoPixelBus is updated beyond 2.9.0
|
||||
if (maxLedsOnBus <= 300 && digitalCount > 5) {
|
||||
DEBUG_PRINTLN(F("Switching to parallel I2S."));
|
||||
useParallel = true;
|
||||
BusManager::useParallelOutput();
|
||||
mem = BusManager::memUsage(maxChannels, maxLedsOnBus, 8); // use alternate memory calculation
|
||||
}
|
||||
#endif
|
||||
|
||||
for (JsonObject elm : ins) {
|
||||
if (s >= WLED_MAX_BUSSES+WLED_MIN_VIRTUAL_BUSSES) break;
|
||||
uint8_t pins[5] = {255, 255, 255, 255, 255};
|
||||
JsonArray pinArr = elm["pin"];
|
||||
if (pinArr.size() == 0) continue;
|
||||
pins[0] = pinArr[0];
|
||||
uint8_t i = 0;
|
||||
//pins[0] = pinArr[0];
|
||||
unsigned i = 0;
|
||||
for (int p : pinArr) {
|
||||
pins[i++] = p;
|
||||
if (i>4) break;
|
||||
}
|
||||
|
||||
uint16_t length = elm["len"] | 1;
|
||||
uint8_t colorOrder = (int)elm[F("order")]; // contains white channel swap option in upper nibble
|
||||
uint8_t skipFirst = elm[F("skip")];
|
||||
@@ -183,7 +212,7 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
|
||||
bool refresh = elm["ref"] | false;
|
||||
uint16_t freqkHz = elm[F("freq")] | 0; // will be in kHz for DotStar and Hz for PWM
|
||||
uint8_t AWmode = elm[F("rgbwm")] | RGBW_MODE_MANUAL_ONLY;
|
||||
uint8_t maPerLed = elm[F("ledma")] | 55;
|
||||
uint8_t maPerLed = elm[F("ledma")] | LED_MILLIAMPS_DEFAULT;
|
||||
uint16_t maMax = elm[F("maxpwr")] | (ablMilliampsMax * length) / total; // rough (incorrect?) per strip ABL calculation when no config exists
|
||||
// To disable brightness limiter we either set output max current to 0 or single LED current to 0 (we choose output max current)
|
||||
if (IS_PWM(ledType) || IS_ONOFF(ledType) || IS_VIRTUAL(ledType)) { // analog and virtual
|
||||
@@ -193,21 +222,22 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
|
||||
ledType |= refresh << 7; // hack bit 7 to indicate strip requires off refresh
|
||||
if (fromFS) {
|
||||
BusConfig bc = BusConfig(ledType, pins, start, length, colorOrder, reversed, skipFirst, AWmode, freqkHz, useGlobalLedBuffer, maPerLed, maMax);
|
||||
mem += BusManager::memUsage(bc);
|
||||
if (useGlobalLedBuffer && start + length > maxlen) {
|
||||
maxlen = start + length;
|
||||
globalBufMem = maxlen * 4;
|
||||
}
|
||||
if (mem + globalBufMem <= MAX_LED_MEMORY) if (BusManager::add(bc) == -1) break; // finalization will be done in WLED::beginStrip()
|
||||
if (useParallel && s < 8) {
|
||||
// if for some unexplained reason the above pre-calculation was wrong, update
|
||||
unsigned memT = BusManager::memUsage(bc); // includes x8 memory allocation for parallel I2S
|
||||
if (memT > mem) mem = memT; // if we have unequal LED count use the largest
|
||||
} else
|
||||
mem += BusManager::memUsage(bc); // includes global buffer
|
||||
if (mem <= MAX_LED_MEMORY) if (BusManager::add(bc) == -1) break; // finalization will be done in WLED::beginStrip()
|
||||
} else {
|
||||
if (busConfigs[s] != nullptr) delete busConfigs[s];
|
||||
busConfigs[s] = new BusConfig(ledType, pins, start, length, colorOrder, reversed, skipFirst, AWmode, freqkHz, useGlobalLedBuffer, maPerLed, maMax);
|
||||
busesChanged = true;
|
||||
doInitBusses = true; // finalization done in beginStrip()
|
||||
}
|
||||
s++;
|
||||
}
|
||||
doInitBusses = busesChanged;
|
||||
// finalization done in beginStrip()
|
||||
DEBUG_PRINTF_P(PSTR("LED buffer size: %uB\n"), mem);
|
||||
DEBUG_PRINTF_P(PSTR("Heap after buses: %d\n"), ESP.getFreeHeap());
|
||||
}
|
||||
if (hw_led["rev"]) BusManager::getBus(0)->setReversed(true); //set 0.11 global reversed setting for first bus
|
||||
|
||||
@@ -215,7 +245,7 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
|
||||
JsonArray hw_com = hw[F("com")];
|
||||
if (!hw_com.isNull()) {
|
||||
ColorOrderMap com = {};
|
||||
uint8_t s = 0;
|
||||
unsigned s = 0;
|
||||
for (JsonObject entry : hw_com) {
|
||||
if (s > WLED_MAX_COLOR_ORDER_MAPPINGS) break;
|
||||
uint16_t start = entry["start"] | 0;
|
||||
@@ -234,10 +264,9 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
|
||||
disablePullUp = !pull;
|
||||
JsonArray hw_btn_ins = btn_obj["ins"];
|
||||
if (!hw_btn_ins.isNull()) {
|
||||
for (uint8_t b = 0; b < WLED_MAX_BUTTONS; b++) { // deallocate existing button pins
|
||||
pinManager.deallocatePin(btnPin[b], PinOwner::Button); // does nothing if trying to deallocate a pin with PinOwner != Button
|
||||
}
|
||||
uint8_t s = 0;
|
||||
// deallocate existing button pins
|
||||
for (unsigned b = 0; b < WLED_MAX_BUTTONS; b++) pinManager.deallocatePin(btnPin[b], PinOwner::Button); // does nothing if trying to deallocate a pin with PinOwner != Button
|
||||
unsigned s = 0;
|
||||
for (JsonObject btn : hw_btn_ins) {
|
||||
CJSON(buttonType[s], btn["type"]);
|
||||
int8_t pin = btn["pin"][0] | -1;
|
||||
@@ -245,22 +274,32 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
|
||||
btnPin[s] = pin;
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
// ESP32 only: check that analog button pin is a valid ADC gpio
|
||||
if (((buttonType[s] == BTN_TYPE_ANALOG) || (buttonType[s] == BTN_TYPE_ANALOG_INVERTED)) && (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!"));
|
||||
btnPin[s] = -1;
|
||||
pinManager.deallocatePin(pin,PinOwner::Button);
|
||||
if ((buttonType[s] == BTN_TYPE_ANALOG) || (buttonType[s] == BTN_TYPE_ANALOG_INVERTED)) {
|
||||
if (digitalPinToAnalogChannel(btnPin[s]) < 0) {
|
||||
// not an ADC 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 {
|
||||
analogReadResolution(12); // see #4040
|
||||
}
|
||||
}
|
||||
//if touch pin, enable the touch interrupt on ESP32 S2 & S3
|
||||
#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
|
||||
if ((buttonType[s] == BTN_TYPE_TOUCH || buttonType[s] == BTN_TYPE_TOUCH_SWITCH))
|
||||
else if ((buttonType[s] == BTN_TYPE_TOUCH || buttonType[s] == BTN_TYPE_TOUCH_SWITCH))
|
||||
{
|
||||
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)
|
||||
if (digitalPinToTouchChannel(btnPin[s]) < 0) {
|
||||
// not a touch pin
|
||||
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);
|
||||
}
|
||||
//if touch pin, enable the touch interrupt on ESP32 S2 & S3
|
||||
#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, touchThreshold << 4); // threshold on Touch V2 is much higher (1500 is a value given by Espressif example, I measured changes of over 5000)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
else
|
||||
#endif
|
||||
{
|
||||
@@ -392,7 +431,7 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
|
||||
JsonObject light = doc[F("light")];
|
||||
CJSON(briMultiplier, light[F("scale-bri")]);
|
||||
CJSON(strip.paletteBlend, light[F("pal-mode")]);
|
||||
CJSON(autoSegments, light[F("aseg")]);
|
||||
CJSON(strip.autoSegments, light[F("aseg")]);
|
||||
|
||||
CJSON(gammaCorrectVal, light["gc"]["val"]); // default 2.8
|
||||
float light_gc_bri = light["gc"]["bri"];
|
||||
@@ -491,14 +530,14 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
|
||||
CJSON(arlsDisableGammaCorrection, if_live[F("no-gc")]); // false
|
||||
CJSON(arlsOffset, if_live[F("offset")]); // 0
|
||||
|
||||
#ifndef WLED_DISABLE_ALEXA
|
||||
CJSON(alexaEnabled, interfaces["va"][F("alexa")]); // false
|
||||
|
||||
CJSON(macroAlexaOn, interfaces["va"]["macros"][0]);
|
||||
CJSON(macroAlexaOff, interfaces["va"]["macros"][1]);
|
||||
|
||||
CJSON(alexaNumPresets, interfaces["va"]["p"]);
|
||||
#endif
|
||||
|
||||
#ifdef WLED_ENABLE_MQTT
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
JsonObject if_mqtt = interfaces["mqtt"];
|
||||
CJSON(mqttEnabled, if_mqtt["en"]);
|
||||
getStringFromJson(mqttServer, if_mqtt[F("broker")], MQTT_MAX_SERVER_LEN+1);
|
||||
@@ -526,7 +565,7 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
|
||||
|
||||
JsonArray if_hue_ip = if_hue["ip"];
|
||||
|
||||
for (byte i = 0; i < 4; i++)
|
||||
for (unsigned i = 0; i < 4; i++)
|
||||
CJSON(hueIP[i], if_hue_ip[i]);
|
||||
#endif
|
||||
|
||||
@@ -700,7 +739,9 @@ void serializeConfig() {
|
||||
JsonObject id = root.createNestedObject("id");
|
||||
id[F("mdns")] = cmDNS;
|
||||
id[F("name")] = serverDescription;
|
||||
#ifndef WLED_DISABLE_ALEXA
|
||||
id[F("inv")] = alexaInvocationName;
|
||||
#endif
|
||||
id[F("sui")] = simplifiedUI;
|
||||
|
||||
JsonObject nw = root.createNestedObject("nw");
|
||||
@@ -745,13 +786,16 @@ void serializeConfig() {
|
||||
JsonObject wifi = root.createNestedObject(F("wifi"));
|
||||
wifi[F("sleep")] = !noWifiSleep;
|
||||
wifi[F("phy")] = force802_3g;
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
wifi[F("txpwr")] = txPower;
|
||||
#endif
|
||||
|
||||
#ifdef WLED_USE_ETHERNET
|
||||
#ifdef WLED_USE_ETHERNET
|
||||
JsonObject ethernet = root.createNestedObject("eth");
|
||||
ethernet["type"] = ethernetType;
|
||||
if (ethernetType != WLED_ETH_NONE && ethernetType < WLED_NUM_ETH_TYPES) {
|
||||
JsonArray pins = ethernet.createNestedArray("pin");
|
||||
for (uint8_t p=0; p<WLED_ETH_RSVD_PINS_COUNT; p++) pins.add(esp32_nonconfigurable_ethernet_pins[p].pin);
|
||||
for (unsigned p=0; p<WLED_ETH_RSVD_PINS_COUNT; p++) pins.add(esp32_nonconfigurable_ethernet_pins[p].pin);
|
||||
if (ethernetBoards[ethernetType].eth_power>=0) pins.add(ethernetBoards[ethernetType].eth_power);
|
||||
if (ethernetBoards[ethernetType].eth_mdc>=0) pins.add(ethernetBoards[ethernetType].eth_mdc);
|
||||
if (ethernetBoards[ethernetType].eth_mdio>=0) pins.add(ethernetBoards[ethernetType].eth_mdio);
|
||||
@@ -768,7 +812,7 @@ void serializeConfig() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
JsonObject hw = root.createNestedObject(F("hw"));
|
||||
|
||||
@@ -776,8 +820,8 @@ void serializeConfig() {
|
||||
hw_led[F("total")] = strip.getLengthTotal(); //provided for compatibility on downgrade and per-output ABL
|
||||
hw_led[F("maxpwr")] = BusManager::ablMilliampsMax();
|
||||
hw_led[F("ledma")] = 0; // no longer used
|
||||
hw_led["cct"] = correctWB;
|
||||
hw_led[F("cr")] = cctFromRgb;
|
||||
hw_led["cct"] = strip.correctWB;
|
||||
hw_led[F("cr")] = strip.cctFromRgb;
|
||||
hw_led[F("ic")] = cctICused;
|
||||
hw_led[F("cb")] = strip.cctBlending;
|
||||
hw_led["fps"] = strip.getTargetFps();
|
||||
@@ -889,7 +933,7 @@ void serializeConfig() {
|
||||
JsonObject light = root.createNestedObject(F("light"));
|
||||
light[F("scale-bri")] = briMultiplier;
|
||||
light[F("pal-mode")] = strip.paletteBlend;
|
||||
light[F("aseg")] = autoSegments;
|
||||
light[F("aseg")] = strip.autoSegments;
|
||||
|
||||
JsonObject light_gc = light.createNestedObject("gc");
|
||||
light_gc["bri"] = (gammaCorrectBri) ? gammaCorrectVal : 1.0f; // keep compatibility
|
||||
@@ -977,7 +1021,7 @@ void serializeConfig() {
|
||||
if_va["p"] = alexaNumPresets;
|
||||
#endif
|
||||
|
||||
#ifdef WLED_ENABLE_MQTT
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
JsonObject if_mqtt = interfaces.createNestedObject("mqtt");
|
||||
if_mqtt["en"] = mqttEnabled;
|
||||
if_mqtt[F("broker")] = mqttServer;
|
||||
@@ -1004,7 +1048,7 @@ void serializeConfig() {
|
||||
if_hue_recv["col"] = hueApplyColor;
|
||||
|
||||
JsonArray if_hue_ip = if_hue.createNestedArray("ip");
|
||||
for (byte i = 0; i < 4; i++) {
|
||||
for (unsigned i = 0; i < 4; i++) {
|
||||
if_hue_ip.add(hueIP[i]);
|
||||
}
|
||||
#endif
|
||||
@@ -1039,7 +1083,7 @@ void serializeConfig() {
|
||||
|
||||
JsonArray timers_ins = timers.createNestedArray("ins");
|
||||
|
||||
for (byte i = 0; i < 10; i++) {
|
||||
for (unsigned i = 0; i < 10; i++) {
|
||||
if (timerMacro[i] == 0 && timerHours[i] == 0 && timerMinutes[i] == 0) continue; // sunrise/sunset get saved always (timerHours=255)
|
||||
JsonObject timers_ins0 = timers_ins.createNestedObject();
|
||||
timers_ins0["en"] = (timerWeekday[i] & 0x01);
|
||||
@@ -1071,7 +1115,7 @@ void serializeConfig() {
|
||||
dmx[F("start-led")] = DMXStartLED;
|
||||
|
||||
JsonArray dmx_fixmap = dmx.createNestedArray(F("fixmap"));
|
||||
for (byte i = 0; i < 15; i++) {
|
||||
for (unsigned i = 0; i < 15; i++) {
|
||||
dmx_fixmap.add(DMXFixtureMap[i]);
|
||||
}
|
||||
|
||||
@@ -1123,7 +1167,7 @@ bool deserializeConfigSec() {
|
||||
|
||||
[[maybe_unused]] JsonObject interfaces = root["if"];
|
||||
|
||||
#ifdef WLED_ENABLE_MQTT
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
JsonObject if_mqtt = interfaces["mqtt"];
|
||||
getStringFromJson(mqttPass, if_mqtt["psk"], 65);
|
||||
#endif
|
||||
@@ -1164,7 +1208,7 @@ void serializeConfigSec() {
|
||||
ap["psk"] = apPass;
|
||||
|
||||
[[maybe_unused]] JsonObject interfaces = root.createNestedObject("if");
|
||||
#ifdef WLED_ENABLE_MQTT
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
JsonObject if_mqtt = interfaces.createNestedObject("mqtt");
|
||||
if_mqtt["psk"] = mqttPass;
|
||||
#endif
|
||||
|
||||
@@ -8,10 +8,10 @@
|
||||
* color blend function
|
||||
*/
|
||||
uint32_t color_blend(uint32_t color1, uint32_t color2, uint16_t blend, bool b16) {
|
||||
if(blend == 0) return color1;
|
||||
uint16_t blendmax = b16 ? 0xFFFF : 0xFF;
|
||||
if(blend == blendmax) return color2;
|
||||
uint8_t shift = b16 ? 16 : 8;
|
||||
if (blend == 0) return color1;
|
||||
unsigned blendmax = b16 ? 0xFFFF : 0xFF;
|
||||
if (blend == blendmax) return color2;
|
||||
unsigned shift = b16 ? 16 : 8;
|
||||
|
||||
uint32_t w1 = W(color1);
|
||||
uint32_t r1 = R(color1);
|
||||
@@ -52,7 +52,7 @@ uint32_t color_add(uint32_t c1, uint32_t c2, bool fast)
|
||||
uint32_t g = G(c1) + G(c2);
|
||||
uint32_t b = B(c1) + B(c2);
|
||||
uint32_t w = W(c1) + W(c2);
|
||||
uint16_t max = r;
|
||||
unsigned max = r;
|
||||
if (g > max) max = g;
|
||||
if (b > max) max = b;
|
||||
if (w > max) max = w;
|
||||
@@ -73,22 +73,19 @@ uint32_t color_fade(uint32_t c1, uint8_t amount, bool video)
|
||||
uint32_t g = G(c1);
|
||||
uint32_t b = B(c1);
|
||||
uint32_t w = W(c1);
|
||||
if (video) {
|
||||
uint32_t scale = amount; // 32bit for faster calculation
|
||||
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);
|
||||
uint32_t scale = amount + !video; // 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);
|
||||
return scaledcolor;
|
||||
}
|
||||
else {
|
||||
uint32_t scale = 1 + amount;
|
||||
scaledcolor = ((r * scale) >> 8) << 16;
|
||||
} else {
|
||||
scaledcolor = ((r * scale) >> 8) << 16;
|
||||
scaledcolor |= ((g * scale) >> 8) << 8;
|
||||
scaledcolor |= (b * scale) >> 8;
|
||||
scaledcolor |= (b * scale) >> 8;
|
||||
scaledcolor |= ((w * scale) >> 8) << 24;
|
||||
return scaledcolor;
|
||||
}
|
||||
return scaledcolor;
|
||||
}
|
||||
|
||||
void setRandomColor(byte* rgb)
|
||||
@@ -140,25 +137,25 @@ CRGBPalette16 generateHarmonicRandomPalette(CRGBPalette16 &basepalette)
|
||||
case 1: // triadic
|
||||
harmonics[0] = basehue + 113 + random8(15);
|
||||
harmonics[1] = basehue + 233 + random8(15);
|
||||
harmonics[2] = basehue -7 + random8(15);
|
||||
harmonics[2] = basehue - 7 + random8(15);
|
||||
break;
|
||||
|
||||
case 2: // split-complementary
|
||||
harmonics[0] = basehue + 145 + random8(10);
|
||||
harmonics[1] = basehue + 205 + random8(10);
|
||||
harmonics[2] = basehue - 5 + random8(10);
|
||||
harmonics[2] = basehue - 5 + random8(10);
|
||||
break;
|
||||
|
||||
case 3: // square
|
||||
harmonics[0] = basehue + 85 + random8(10);
|
||||
harmonics[0] = basehue + 85 + random8(10);
|
||||
harmonics[1] = basehue + 175 + random8(10);
|
||||
harmonics[2] = basehue + 265 + random8(10);
|
||||
break;
|
||||
|
||||
case 4: // tetradic
|
||||
harmonics[0] = basehue + 80 + random8(20);
|
||||
harmonics[0] = basehue + 80 + random8(20);
|
||||
harmonics[1] = basehue + 170 + random8(20);
|
||||
harmonics[2] = basehue + random8(30)-15;
|
||||
harmonics[2] = basehue - 15 + random8(30);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -208,13 +205,13 @@ CRGBPalette16 generateRandomPalette(void) //generate fully random palette
|
||||
|
||||
void colorHStoRGB(uint16_t hue, byte sat, byte* rgb) //hue, sat to rgb
|
||||
{
|
||||
float h = ((float)hue)/65535.0f;
|
||||
float h = ((float)hue)/10922.5f; // hue*6/65535
|
||||
float s = ((float)sat)/255.0f;
|
||||
int i = floorf(h*6);
|
||||
float f = h * 6.0f - i;
|
||||
int i = int(h);
|
||||
float f = h - i;
|
||||
int p = int(255.0f * (1.0f-s));
|
||||
int q = int(255.0f * (1.0f-f*s));
|
||||
int t = int(255.0f * (1.0f-(1.0f-f)*s));
|
||||
int q = int(255.0f * (1.0f-s*f));
|
||||
int t = int(255.0f * (1.0f-s*(1.0f-f)));
|
||||
p = constrain(p, 0, 255);
|
||||
q = constrain(q, 0, 255);
|
||||
t = constrain(t, 0, 255);
|
||||
@@ -384,13 +381,13 @@ bool colorFromHexString(byte* rgb, const char* in) {
|
||||
return true;
|
||||
}
|
||||
|
||||
float minf (float v, float w)
|
||||
static inline float minf(float v, float w)
|
||||
{
|
||||
if (w > v) return v;
|
||||
return w;
|
||||
}
|
||||
|
||||
float maxf (float v, float w)
|
||||
static inline float maxf(float v, float w)
|
||||
{
|
||||
if (w > v) return w;
|
||||
return v;
|
||||
|
||||
@@ -46,40 +46,58 @@
|
||||
|
||||
#ifndef WLED_MAX_BUSSES
|
||||
#ifdef ESP8266
|
||||
#define WLED_MAX_BUSSES 3
|
||||
#define WLED_MAX_DIGITAL_CHANNELS 3
|
||||
#define WLED_MAX_ANALOG_CHANNELS 5
|
||||
#define WLED_MAX_BUSSES 4 // will allow 3 digital & 1 analog RGB
|
||||
#define WLED_MIN_VIRTUAL_BUSSES 2
|
||||
#else
|
||||
#if defined(CONFIG_IDF_TARGET_ESP32C3) // 2 RMT, 6 LEDC, only has 1 I2S but NPB does not support it ATM
|
||||
#define WLED_MAX_BUSSES 3 // will allow 2 digital & 1 analog (or the other way around)
|
||||
#define WLED_MAX_BUSSES 4 // will allow 2 digital & 2 analog RGB
|
||||
#define WLED_MAX_DIGITAL_CHANNELS 2
|
||||
#define WLED_MAX_ANALOG_CHANNELS 6
|
||||
#define WLED_MIN_VIRTUAL_BUSSES 3
|
||||
#elif defined(CONFIG_IDF_TARGET_ESP32S2) // 4 RMT, 8 LEDC, only has 1 I2S bus, supported in NPB
|
||||
// the 5th bus (I2S) will prevent Audioreactive usermod from functioning (it is last used though)
|
||||
#define WLED_MAX_BUSSES 7 // will allow 5 digital & 2 analog
|
||||
#define WLED_MAX_BUSSES 7 // will allow 5 digital & 2 analog RGB
|
||||
#define WLED_MAX_DIGITAL_CHANNELS 5
|
||||
#define WLED_MAX_ANALOG_CHANNELS 8
|
||||
#define WLED_MIN_VIRTUAL_BUSSES 3
|
||||
#elif defined(CONFIG_IDF_TARGET_ESP32S3) // 4 RMT, 8 LEDC, has 2 I2S but NPB does not support them ATM
|
||||
#define WLED_MAX_BUSSES 6 // will allow 4 digital & 2 analog
|
||||
#define WLED_MAX_BUSSES 6 // will allow 4 digital & 2 analog RGB
|
||||
#define WLED_MAX_DIGITAL_CHANNELS 4
|
||||
#define WLED_MAX_ANALOG_CHANNELS 8
|
||||
#define WLED_MIN_VIRTUAL_BUSSES 4
|
||||
#else
|
||||
// the last digital bus (I2S0) will prevent Audioreactive usermod from functioning
|
||||
#ifndef WLED_USE_PARALLEL_I2S
|
||||
#define WLED_MAX_BUSSES 10
|
||||
#else
|
||||
#define WLED_MAX_BUSSES 17
|
||||
#endif
|
||||
#define WLED_MIN_VIRTUAL_BUSSES 0
|
||||
#define WLED_MAX_BUSSES 20 // will allow 17 digital & 3 analog RGB
|
||||
#define WLED_MAX_DIGITAL_CHANNELS 17
|
||||
#define WLED_MAX_ANALOG_CHANNELS 10
|
||||
#define WLED_MIN_VIRTUAL_BUSSES 4
|
||||
#endif
|
||||
#endif
|
||||
#else
|
||||
#ifdef ESP8266
|
||||
#if WLED_MAX_BUSES > 5
|
||||
#if WLED_MAX_BUSSES > 5
|
||||
#error Maximum number of buses is 5.
|
||||
#endif
|
||||
#ifndef WLED_MAX_ANALOG_CHANNELS
|
||||
#error You must also define WLED_MAX_ANALOG_CHANNELS.
|
||||
#endif
|
||||
#ifndef WLED_MAX_DIGITAL_CHANNELS
|
||||
#error You must also define WLED_MAX_DIGITAL_CHANNELS.
|
||||
#endif
|
||||
#define WLED_MIN_VIRTUAL_BUSSES (5-WLED_MAX_BUSSES)
|
||||
#else
|
||||
#if WLED_MAX_BUSES > 10
|
||||
#error Maximum number of buses is 10.
|
||||
#if WLED_MAX_BUSSES > 20
|
||||
#error Maximum number of buses is 20.
|
||||
#endif
|
||||
#define WLED_MIN_VIRTUAL_BUSSES (10-WLED_MAX_BUSSES)
|
||||
#ifndef WLED_MAX_ANALOG_CHANNELS
|
||||
#error You must also define WLED_MAX_ANALOG_CHANNELS.
|
||||
#endif
|
||||
#ifndef WLED_MAX_DIGITAL_CHANNELS
|
||||
#error You must also define WLED_MAX_DIGITAL_CHANNELS.
|
||||
#endif
|
||||
#define WLED_MIN_VIRTUAL_BUSSES (20-WLED_MAX_BUSSES)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -178,6 +196,12 @@
|
||||
#define USERMOD_ID_HTTP_PULL_LIGHT_CONTROL 46 //usermod "usermod_v2_HttpPullLightControl.h"
|
||||
#define USERMOD_ID_TETRISAI 47 //Usermod "usermod_v2_tetris.h"
|
||||
#define USERMOD_ID_MAX17048 48 //Usermod "usermod_max17048.h"
|
||||
#define USERMOD_ID_BME68X 49 //Usermod "usermod_bme68x.h
|
||||
#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
|
||||
@@ -193,9 +217,9 @@
|
||||
#define CALL_MODE_INIT 0 //no updates on init, can be used to disable updates
|
||||
#define CALL_MODE_DIRECT_CHANGE 1
|
||||
#define CALL_MODE_BUTTON 2 //default button actions applied to selected segments
|
||||
#define CALL_MODE_NOTIFICATION 3
|
||||
#define CALL_MODE_NIGHTLIGHT 4
|
||||
#define CALL_MODE_NO_NOTIFY 5
|
||||
#define CALL_MODE_NOTIFICATION 3 //caused by incoming notification (UDP or DMX preset)
|
||||
#define CALL_MODE_NIGHTLIGHT 4 //nightlight progress
|
||||
#define CALL_MODE_NO_NOTIFY 5 //change state but do not send notifications (UDP)
|
||||
#define CALL_MODE_FX_CHANGED 6 //no longer used
|
||||
#define CALL_MODE_HUE 7
|
||||
#define CALL_MODE_PRESET_CYCLE 8 //no longer used
|
||||
@@ -273,6 +297,7 @@
|
||||
#define TYPE_TM1814 31
|
||||
#define TYPE_WS2805 32 //RGB + WW + CW
|
||||
#define TYPE_TM1914 33 //RGB
|
||||
#define TYPE_SM16825 34 //RGB + WW + CW
|
||||
//"Analog" types (40-47)
|
||||
#define TYPE_ONOFF 40 //binary output (relays etc.; NOT PWM)
|
||||
#define TYPE_ANALOG_1CH 41 //single channel PWM. Uses value of brightest RGBW channel
|
||||
@@ -329,7 +354,7 @@
|
||||
#define BTN_TYPE_TOUCH_SWITCH 9
|
||||
|
||||
//Ethernet board types
|
||||
#define WLED_NUM_ETH_TYPES 12
|
||||
#define WLED_NUM_ETH_TYPES 13
|
||||
|
||||
#define WLED_ETH_NONE 0
|
||||
#define WLED_ETH_WT32_ETH01 1
|
||||
@@ -343,6 +368,7 @@
|
||||
#define WLED_ETH_ABCWLEDV43ETH 9
|
||||
#define WLED_ETH_SERG74 10
|
||||
#define WLED_ETH_ESP32_POE_WROVER 11
|
||||
#define WLED_ETH_LILYGO_T_POE_PRO 12
|
||||
|
||||
//Hue error codes
|
||||
#define HUE_ERROR_INACTIVE 0
|
||||
@@ -479,6 +505,16 @@
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef LED_MILLIAMPS_DEFAULT
|
||||
#define LED_MILLIAMPS_DEFAULT 55 // common WS2812B
|
||||
#else
|
||||
#if LED_MILLIAMPS_DEFAULT < 1 || LED_MILLIAMPS_DEFAULT > 100
|
||||
#warning "Unusual LED mA current, overriding with default value."
|
||||
#undef LED_MILLIAMPS_DEFAULT
|
||||
#define LED_MILLIAMPS_DEFAULT 55
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// PWM settings
|
||||
#ifndef WLED_PWM_FREQ
|
||||
#ifdef ESP8266
|
||||
@@ -592,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
|
||||
|
||||
@@ -923,6 +923,7 @@ select.sel-p, select.sel-pl, select.sel-ple {
|
||||
margin: 5px 0;
|
||||
width: 100%;
|
||||
height: 40px;
|
||||
padding: 0 20px 0 8px;
|
||||
}
|
||||
div.sel-p {
|
||||
position: relative;
|
||||
|
||||
@@ -126,9 +126,10 @@
|
||||
<button id="hexcnf" class="btn btn-xs" onclick="fromHex();"><i class="icons btn-icon"></i></button>
|
||||
</div>
|
||||
<div style="padding: 8px 0;" id="btns">
|
||||
<button class="btn btn-xs" title="File editor" type="button" id="edit" onclick="window.location.href=getURL('/edit')"><i class="icons btn-icon"></i></button>
|
||||
<button class="btn btn-xs" title="Pixel Magic Tool" type="button" id="pxmb" onclick="window.location.href=getURL('/pxmagic.htm')"><i class="icons btn-icon"></i></button>
|
||||
<button class="btn btn-xs" title="Add custom palette" type="button" onclick="window.location.href=getURL('/cpal.htm')"><i class="icons btn-icon"></i></button>
|
||||
<button class="btn btn-xs" title="Remove custom palette" type="button" id="rmPal" onclick="palettesData=null;localStorage.removeItem('wledPalx');requestJson({rmcpal:true});setTimeout(loadPalettes,250,loadPalettesData);"><i class="icons btn-icon"></i></button>
|
||||
<button class="btn btn-xs" title="Remove last custom palette" type="button" id="rmPal" onclick="palettesData=null;localStorage.removeItem('wledPalx');requestJson({rmcpal:true});setTimeout(loadPalettes,250,loadPalettesData);"><i class="icons btn-icon"></i></button>
|
||||
</div>
|
||||
<p class="labels hd" id="pall"><i class="icons sel-icon" onclick="tglHex()"></i> Color palette</p>
|
||||
<div id="palw" class="il">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//page js
|
||||
var loc = false, locip, locproto = "http:";
|
||||
var isOn = false, nlA = false, isLv = false, isInfo = false, isNodes = false, syncSend = false/*, syncTglRecv = true*/;
|
||||
var hasWhite = false, hasRGB = false, hasCCT = false;
|
||||
var hasWhite = false, hasRGB = false, hasCCT = false, has2D = false;
|
||||
var nlDur = 60, nlTar = 0;
|
||||
var nlMode = false;
|
||||
var segLmax = 0; // size (in pixels) of largest selected segment
|
||||
@@ -282,12 +282,12 @@ function onLoad()
|
||||
// fill effect extra data array
|
||||
loadFXData(()=>{
|
||||
// load and populate effects
|
||||
loadFX(()=>{
|
||||
setTimeout(()=>{loadFX(()=>{
|
||||
loadPalettesData(()=>{
|
||||
requestJson();// will load presets and create WS
|
||||
if (cfg.comp.css) setTimeout(()=>{loadSkinCSS('skinCss')},50);
|
||||
});
|
||||
});
|
||||
})},50);
|
||||
});
|
||||
});
|
||||
resetUtil();
|
||||
@@ -588,7 +588,7 @@ function loadFXData(callback = null)
|
||||
fxdata = [];
|
||||
if (!retry) {
|
||||
retry = true;
|
||||
setTimeout(loadFXData, 500); // retry
|
||||
setTimeout(()=>{loadFXData(loadFX);}, 500); // retry
|
||||
}
|
||||
showToast(e, true);
|
||||
})
|
||||
@@ -669,18 +669,15 @@ function parseInfo(i) {
|
||||
//syncTglRecv = i.str;
|
||||
maxSeg = i.leds.maxseg;
|
||||
pmt = i.fs.pmt;
|
||||
if (pcMode && !i.wifi.ap) gId('edit').classList.remove("hide"); else gId('edit').classList.add("hide");
|
||||
gId('buttonNodes').style.display = lastinfo.ndc > 0 ? null:"none";
|
||||
// do we have a matrix set-up
|
||||
mw = i.leds.matrix ? i.leds.matrix.w : 0;
|
||||
mh = i.leds.matrix ? i.leds.matrix.h : 0;
|
||||
isM = mw>0 && mh>0;
|
||||
if (!isM) {
|
||||
//gId("filter0D").classList.remove('hide');
|
||||
//gId("filter1D").classList.add('hide');
|
||||
gId("filter2D").classList.add('hide');
|
||||
} else {
|
||||
//gId("filter0D").classList.add('hide');
|
||||
//gId("filter1D").classList.remove('hide');
|
||||
gId("filter2D").classList.remove('hide');
|
||||
}
|
||||
// if (i.noaudio) {
|
||||
@@ -745,10 +742,10 @@ ${inforow("Environment",i.arch + " " + i.core + " (" + i.lwip + ")")}
|
||||
</table>`;
|
||||
gId('kv').innerHTML = cn;
|
||||
// update all sliders in Info
|
||||
for (let sd of (d.querySelectorAll('#kv .sliderdisplay')||[])) {
|
||||
d.querySelectorAll('#kv .sliderdisplay').forEach((sd,i) => {
|
||||
let s = sd.previousElementSibling;
|
||||
if (s) updateTrail(s);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function populateSegments(s)
|
||||
@@ -895,8 +892,8 @@ function populateSegments(s)
|
||||
gId('segutil2').style.display = (segCount > 1) ? "block":"none"; // rsbtn parent
|
||||
|
||||
if (Array.isArray(li.maps) && li.maps.length>1) {
|
||||
let cont = `Ledmap: <select class="sel-sg" onchange="requestJson({'ledmap':parseInt(this.value)})"><option value="" selected>Unchanged</option>`;
|
||||
for (const k of (li.maps||[])) cont += `<option value="${k.id}">${k.id==0?'Default':(k.n?k.n:'ledmap'+k.id+'.json')}</option>`;
|
||||
let cont = `Ledmap: <select class="sel-sg" onchange="requestJson({'ledmap':parseInt(this.value)})">`;
|
||||
for (const k of li.maps) cont += `<option ${s.ledmap===k.id?"selected":""} value="${k.id}">${k.id==0?'Default':(k.n?k.n:'ledmap'+k.id+'.json')}</option>`;
|
||||
cont += "</select></div>";
|
||||
gId("ledmap").innerHTML = cont;
|
||||
gId("ledmap").classList.remove('hide');
|
||||
@@ -991,13 +988,12 @@ function populatePalettes()
|
||||
|
||||
function redrawPalPrev()
|
||||
{
|
||||
let palettes = d.querySelectorAll('#pallist .lstI');
|
||||
for (var pal of (palettes||[])) {
|
||||
d.querySelectorAll('#pallist .lstI').forEach((pal,i) =>{
|
||||
let lP = pal.querySelector('.lstIprev');
|
||||
if (lP) {
|
||||
lP.style = genPalPrevCss(pal.dataset.id);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function genPalPrevCss(id)
|
||||
@@ -1343,7 +1339,7 @@ function updateSelectedFx()
|
||||
if (ds.id>0) {
|
||||
if (segLmax==0) fx.classList.add('hide'); // none of the segments selected (hide all effects)
|
||||
else {
|
||||
if ((segLmax==1 && (!opts[3] || opts[3].indexOf("0")<0)) || (!isM && opts[3] && ((opts[3].indexOf("2")>=0 && opts[3].indexOf("1")<0)))) fx.classList.add('hide');
|
||||
if ((segLmax==1 && (!opts[3] || opts[3].indexOf("0")<0)) || (!has2D && opts[3] && ((opts[3].indexOf("2")>=0 && opts[3].indexOf("1")<0)))) fx.classList.add('hide');
|
||||
else fx.classList.remove('hide');
|
||||
}
|
||||
}
|
||||
@@ -1358,10 +1354,12 @@ function updateSelectedFx()
|
||||
}
|
||||
|
||||
// hide 2D mapping and/or sound simulation options
|
||||
var segs = gId("segcont").querySelectorAll(`div[data-map="map2D"]`);
|
||||
for (const seg of segs) if (selectedName.indexOf("\u25A6")<0) seg.classList.remove('hide'); else seg.classList.add('hide');
|
||||
var segs = gId("segcont").querySelectorAll(`div[data-snd="si"]`);
|
||||
for (const seg of segs) if (selectedName.indexOf("\u266A")<0 && selectedName.indexOf("\u266B")<0) seg.classList.add('hide'); else seg.classList.remove('hide'); // also "♫ "?
|
||||
gId("segcont").querySelectorAll(`div[data-map="map2D"]`).forEach((seg)=>{
|
||||
if (selectedName.indexOf("\u25A6")<0) seg.classList.remove('hide'); else seg.classList.add('hide');
|
||||
});
|
||||
gId("segcont").querySelectorAll(`div[data-snd="si"]`).forEach((seg)=>{
|
||||
if (selectedName.indexOf("\u266A")<0 && selectedName.indexOf("\u266B")<0) seg.classList.add('hide'); else seg.classList.remove('hide'); // also "♫ "?
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1443,7 +1441,7 @@ function readState(s,command=false)
|
||||
populateSegments(s);
|
||||
var selc=0;
|
||||
var sellvl=0; // 0: selc is invalid, 1: selc is mainseg, 2: selc is first selected
|
||||
hasRGB = hasWhite = hasCCT = false;
|
||||
hasRGB = hasWhite = hasCCT = has2D = false;
|
||||
segLmax = 0;
|
||||
for (let i = 0; i < (s.seg||[]).length; i++)
|
||||
{
|
||||
@@ -1454,20 +1452,23 @@ function readState(s,command=false)
|
||||
if (s.seg[i].sel) {
|
||||
if (sellvl < 2) selc = i; // get first selected segment
|
||||
sellvl = 2;
|
||||
var lc = lastinfo.leds.seglc[i];
|
||||
let w = (s.seg[i].stop - s.seg[i].start);
|
||||
let h = s.seg[i].stopY ? (s.seg[i].stopY - s.seg[i].startY) : 1;
|
||||
let lc = lastinfo.leds.seglc[i];
|
||||
hasRGB |= !!(lc & 0x01);
|
||||
hasWhite |= !!(lc & 0x02);
|
||||
hasCCT |= !!(lc & 0x04);
|
||||
let sLen = (s.seg[i].stop - s.seg[i].start)*(s.seg[i].stopY?(s.seg[i].stopY - s.seg[i].startY):1);
|
||||
segLmax = segLmax < sLen ? sLen : segLmax;
|
||||
has2D |= w > 1 && h > 1;
|
||||
if (w*h > segLmax) segLmax = w*h;
|
||||
}
|
||||
}
|
||||
var i=s.seg[selc];
|
||||
if (sellvl == 1) {
|
||||
var lc = lastinfo.leds.seglc[selc];
|
||||
let lc = lastinfo.leds.seglc[selc];
|
||||
hasRGB = !!(lc & 0x01);
|
||||
hasWhite = !!(lc & 0x02);
|
||||
hasCCT = !!(lc & 0x04);
|
||||
has2D = (i.stop - i.start) > 1 && (i.stopY ? (i.stopY - i.startY) : 1) > 1;
|
||||
}
|
||||
if (!i) {
|
||||
showToast('No Segments!', true);
|
||||
@@ -1498,6 +1499,12 @@ function readState(s,command=false)
|
||||
if (s.error && s.error != 0) {
|
||||
var errstr = "";
|
||||
switch (s.error) {
|
||||
case 1:
|
||||
errstr = "Denied!";
|
||||
break;
|
||||
case 3:
|
||||
errstr = "Buffer locked!";
|
||||
break;
|
||||
case 8:
|
||||
errstr = "Effect RAM depleted!";
|
||||
break;
|
||||
@@ -1562,8 +1569,7 @@ function setEffectParameters(idx)
|
||||
var paOnOff = (effectPars.length<3 || effectPars[2]=='')?[]:effectPars[2].split(",");
|
||||
|
||||
// set html slider items on/off
|
||||
let sliders = d.querySelectorAll("#sliders .sliderwrap");
|
||||
sliders.forEach((slider, i)=>{
|
||||
d.querySelectorAll("#sliders .sliderwrap").forEach((slider, i)=>{
|
||||
let text = slider.getAttribute("title");
|
||||
if ((!controlDefined && i<((idx<128)?2:nSliders)) || (slOnOff.length>i && slOnOff[i]!="")) {
|
||||
if (slOnOff.length>i && slOnOff[i]!="!") text = slOnOff[i];
|
||||
@@ -1577,8 +1583,7 @@ function setEffectParameters(idx)
|
||||
|
||||
if (slOnOff.length > 5) { // up to 3 checkboxes
|
||||
gId('fxopt').classList.remove('fade');
|
||||
let checks = d.querySelectorAll("#sliders .ochkl");
|
||||
checks.forEach((check, i)=>{
|
||||
d.querySelectorAll("#sliders .ochkl").forEach((check, i)=>{
|
||||
let text = check.getAttribute("title");
|
||||
if (5+i<slOnOff.length && slOnOff[5+i]!=='') {
|
||||
if (slOnOff.length>5+i && slOnOff[5+i]!="!") text = slOnOff[5+i];
|
||||
@@ -1705,9 +1710,7 @@ function requestJson(command=null)
|
||||
|
||||
fetch(getURL('/json/si'), {
|
||||
method: type,
|
||||
headers: {
|
||||
"Content-type": "application/json; charset=UTF-8"
|
||||
},
|
||||
headers: {"Content-Type": "application/json; charset=UTF-8"},
|
||||
body: req
|
||||
})
|
||||
.then(res => {
|
||||
@@ -2025,7 +2028,7 @@ ${makePlSel(plJson[i].end?plJson[i].end:0, true)}
|
||||
</label>`;
|
||||
if (Array.isArray(lastinfo.maps) && lastinfo.maps.length>1) {
|
||||
content += `<div class="lbl-l">Ledmap: <div class="sel-p"><select class="sel-p" id="p${i}lmp"><option value="">Unchanged</option>`;
|
||||
for (const k of (lastinfo.maps||[])) content += `<option value="${k.id}"${(i>0 && pJson[i].ledmap==k.id)?" selected":""}>${k.id==0?'Default':(k.n?k.n:'ledmap'+k.id+'.json')}</option>`;
|
||||
for (const k of lastinfo.maps) content += `<option value="${k.id}"${(i>0 && pJson[i].ledmap==k.id)?" selected":""}>${k.id==0?'Default':(k.n?k.n:'ledmap'+k.id+'.json')}</option>`;
|
||||
content += "</select></div></div>";
|
||||
}
|
||||
}
|
||||
@@ -2173,13 +2176,12 @@ function selGrp(g)
|
||||
{
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
var sel = gId(`segcont`).querySelectorAll(`div[data-set="${g}"]`);
|
||||
var obj = {"seg":[]};
|
||||
for (let i=0; i<=lSeg; i++) if (gId(`seg${i}`)) obj.seg.push({"id":i,"sel":false});
|
||||
for (let s of (sel||[])) {
|
||||
gId(`segcont`).querySelectorAll(`div[data-set="${g}"]`).forEach((s)=>{
|
||||
let i = parseInt(s.id.substring(3));
|
||||
obj.seg[i] = {"id":i,"sel":true};
|
||||
}
|
||||
});
|
||||
if (obj.seg.length) requestJson(obj);
|
||||
}
|
||||
|
||||
@@ -2691,7 +2693,9 @@ function setBalance(b)
|
||||
function rmtTgl(ip,i) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
fetch(`http://${ip}/win&T=2`, {method: 'get'})
|
||||
fetch(`http://${ip}/win&T=2`, {
|
||||
method: 'get'
|
||||
})
|
||||
.then((r)=>{
|
||||
return r.text();
|
||||
})
|
||||
@@ -2783,21 +2787,23 @@ function loadPalettesData(callback = null)
|
||||
function getPalettesData(page, callback)
|
||||
{
|
||||
fetch(getURL(`/json/palx?page=${page}`), {
|
||||
method: 'get',
|
||||
headers: {
|
||||
"Content-type": "application/json; charset=UTF-8"
|
||||
}
|
||||
method: 'get'
|
||||
})
|
||||
.then(res => {
|
||||
if (!res.ok) showErrorToast();
|
||||
return res.json();
|
||||
})
|
||||
.then(json => {
|
||||
retry = false;
|
||||
palettesData = Object.assign({}, palettesData, json.p);
|
||||
if (page < json.m) setTimeout(()=>{ getPalettesData(page + 1, callback); }, 50);
|
||||
if (page < json.m) setTimeout(()=>{ getPalettesData(page + 1, callback); }, 75);
|
||||
else callback();
|
||||
})
|
||||
.catch((error)=>{
|
||||
if (!retry) {
|
||||
retry = true;
|
||||
setTimeout(()=>{getPalettesData(page,callback);}, 500); // retry
|
||||
}
|
||||
showToast(error, true);
|
||||
});
|
||||
}
|
||||
@@ -2820,9 +2826,9 @@ function search(field, listId = null) {
|
||||
const search = field.value !== '';
|
||||
|
||||
// restore default preset sorting if no search term is entered
|
||||
if (listId === 'pcont' && !search) {
|
||||
populatePresets();
|
||||
return;
|
||||
if (!search) {
|
||||
if (listId === 'pcont') { populatePresets(); return; }
|
||||
if (listId === 'pallist') { populatePalettes(); return; }
|
||||
}
|
||||
|
||||
// clear filter if searching in fxlist
|
||||
@@ -2833,15 +2839,15 @@ function search(field, listId = null) {
|
||||
// do not search if filter is active
|
||||
if (gId("filters").querySelectorAll("input[type=checkbox]:checked").length) return;
|
||||
|
||||
const listItems = gId(listId).querySelectorAll('.lstI');
|
||||
// filter list items but leave (Default & Solid) always visible
|
||||
for (i = (listId === 'pcont' ? 0 : 1); i < listItems.length; i++) {
|
||||
const listItem = listItems[i];
|
||||
const listItems = gId(listId).querySelectorAll('.lstI');
|
||||
listItems.forEach((listItem,i)=>{
|
||||
if (listId!=='pcont' && i===0) return;
|
||||
const listItemName = listItem.querySelector('.lstIname').innerText.toUpperCase();
|
||||
const searchIndex = listItemName.indexOf(field.value.toUpperCase());
|
||||
listItem.style.display = (searchIndex < 0) ? 'none' : '';
|
||||
listItem.dataset.searchIndex = searchIndex;
|
||||
}
|
||||
});
|
||||
|
||||
// sort list items by search index and name
|
||||
const sortedListItems = Array.from(listItems).sort((a, b) => {
|
||||
@@ -2902,14 +2908,12 @@ function filterFx() {
|
||||
inputField.value = '';
|
||||
inputField.focus();
|
||||
clean(inputField.nextElementSibling);
|
||||
const listItems = gId("fxlist").querySelectorAll('.lstI');
|
||||
for (let i = 1; i < listItems.length; i++) {
|
||||
const listItem = listItems[i];
|
||||
gId("fxlist").querySelectorAll('.lstI').forEach((listItem,i) => {
|
||||
const listItemName = listItem.querySelector('.lstIname').innerText;
|
||||
let hide = false;
|
||||
gId("filters").querySelectorAll("input[type=checkbox]").forEach((e) => { if (e.checked && !listItemName.includes(e.dataset.flt)) hide = true; });
|
||||
listItem.style.display = hide ? 'none' : '';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function preventBlur(e) {
|
||||
@@ -3060,6 +3064,7 @@ function size()
|
||||
|
||||
function togglePcMode(fromB = false)
|
||||
{
|
||||
let ap = (fromB && !lastinfo) || (lastinfo && lastinfo.wifi && lastinfo.wifi.ap);
|
||||
if (fromB) {
|
||||
pcModeA = !pcModeA;
|
||||
localStorage.setItem('pcm', pcModeA);
|
||||
@@ -3069,6 +3074,7 @@ function togglePcMode(fromB = false)
|
||||
if (!fromB && ((wW < 1024 && lastw < 1024) || (wW >= 1024 && lastw >= 1024))) return; // no change in size and called from size()
|
||||
if (pcMode) openTab(0, true);
|
||||
gId('buttonPcm').className = (pcMode) ? "active":"";
|
||||
if (pcMode && !ap) gId('edit').classList.remove("hide"); else gId('edit').classList.add("hide");
|
||||
gId('bot').style.height = (pcMode && !cfg.comp.pcmbot) ? "0":"auto";
|
||||
sCol('--bh', gId('bot').clientHeight + "px");
|
||||
_C.style.width = (pcMode || simplifiedUI)?'100%':'400%';
|
||||
@@ -3094,8 +3100,7 @@ function mergeDeep(target, ...sources)
|
||||
|
||||
function tooltip(cont=null)
|
||||
{
|
||||
const elements = d.querySelectorAll((cont?cont+" ":"")+"[title]");
|
||||
elements.forEach((element)=>{
|
||||
d.querySelectorAll((cont?cont+" ":"")+"[title]").forEach((element)=>{
|
||||
element.addEventListener("mouseover", ()=>{
|
||||
// save title
|
||||
element.setAttribute("data-title", element.getAttribute("title"));
|
||||
@@ -3122,8 +3127,7 @@ function tooltip(cont=null)
|
||||
});
|
||||
|
||||
element.addEventListener("mouseout", ()=>{
|
||||
const tooltips = d.querySelectorAll('.tooltip');
|
||||
tooltips.forEach((tooltip)=>{
|
||||
d.querySelectorAll('.tooltip').forEach((tooltip)=>{
|
||||
tooltip.classList.remove("visible");
|
||||
d.body.removeChild(tooltip);
|
||||
});
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport">
|
||||
<title>LED Settings</title>
|
||||
<script>
|
||||
var d=document,laprev=55,maxB=1,maxV=0,maxM=4000,maxPB=4096,maxL=1333,maxCO=10,maxLbquot=0; //maximum bytes for LED allocation: 4kB for 8266, 32kB for 32
|
||||
var d=document,laprev=55,maxB=1,maxD=1,maxA=1,maxV=0,maxM=4000,maxPB=4096,maxL=1333,maxCO=10,maxLbquot=0; //maximum bytes for LED allocation: 4kB for 8266, 32kB for 32
|
||||
var oMaxB=1;
|
||||
d.um_p = [];
|
||||
d.rsvd = [];
|
||||
d.ro_gpio = [];
|
||||
@@ -21,10 +22,10 @@
|
||||
function isAna(t) { return t == 40 || isPWM(t); } // is analog type
|
||||
function isDig(t) { return (t > 15 && t < 40) || isD2P(t); } // is digital type
|
||||
function isD2P(t) { return t > 47 && t < 64; } // is digital 2 pin type
|
||||
function is16b(t) { return t == 26 || t == 29 } // is digital 16 bit type
|
||||
function is16b(t) { return t == 26 || t == 29 || t == 34; } // is digital 16 bit type
|
||||
function isVir(t) { return t >= 80 && t < 96; } // is virtual type
|
||||
function hasW(t) { return (t >= 18 && t <= 21) || (t >= 28 && t <= 32) || (t >= 44 && t <= 45) || (t >= 88 && t <= 89); }
|
||||
function hasCCT(t) { return t == 20 || t == 21 || t == 42 || t == 45 || t == 28 || t == 32; }
|
||||
function hasW(t) { return (t >= 18 && t <= 21) || (t >= 28 && t <= 32) || t == 34 || (t >= 44 && t <= 45) || (t >= 88 && t <= 89); }
|
||||
function hasCCT(t) { return t == 20 || t == 21 || t == 42 || t == 45 || t == 28 || t == 32 || t == 34; }
|
||||
// https://www.educative.io/edpresso/how-to-dynamically-load-a-js-file-in-javascript
|
||||
function loadJS(FILE_URL, async = true) {
|
||||
let scE = d.createElement("script");
|
||||
@@ -57,8 +58,16 @@
|
||||
x.style.animation = 'none';
|
||||
timeout = setTimeout(function(){ x.className = x.className.replace("show", ""); }, 2900);
|
||||
}
|
||||
function bLimits(b,v,p,m,l,o) {
|
||||
maxB = b; maxV = v; maxM = m; maxPB = p; maxL = l; maxCO = o;
|
||||
function bLimits(b,v,p,m,l,o=5,d=2,a=6) {
|
||||
// maxB - max buses (can be changed if using ESP32 parallel I2S)
|
||||
// maxD - max digital channels (can be changed if using ESP32 parallel I2S)
|
||||
// maxA - max analog channels
|
||||
// maxV - min virtual buses
|
||||
// maxPB - max LEDs per bus
|
||||
// maxM - max LED memory
|
||||
// maxL - max LEDs
|
||||
// maxCO - max Color Order mappings
|
||||
oMaxB = maxB = b; maxD = d, maxA = a, maxV = v; maxM = m; maxPB = p; maxL = l; maxCO = o;
|
||||
}
|
||||
function pinsOK() {
|
||||
var ok = true;
|
||||
@@ -117,7 +126,10 @@
|
||||
if (!pinsOK()) {e.stopPropagation();return false;} // Prevent form submission and contact with server
|
||||
if (bquot > 100) {var msg = "Too many LEDs for me to handle!"; if (maxM < 10000) msg += "\n\rConsider using an ESP32."; alert(msg);}
|
||||
if (!d.Sf.ABL.checked || d.Sf.PPL.checked) d.Sf.MA.value = 0; // submit 0 as ABL (PPL will handle it)
|
||||
if (d.Sf.checkValidity()) d.Sf.submit(); //https://stackoverflow.com/q/37323914
|
||||
if (d.Sf.checkValidity()) {
|
||||
d.Sf.querySelectorAll("#mLC select[name^=LT]").forEach((s)=>{s.disabled=false;}); // just in case
|
||||
d.Sf.submit(); //https://stackoverflow.com/q/37323914
|
||||
}
|
||||
}
|
||||
function enABL()
|
||||
{
|
||||
@@ -211,9 +223,12 @@
|
||||
let busMA = 0;
|
||||
let sLC = 0, sPC = 0, sDI = 0, maxLC = 0;
|
||||
const ablEN = d.Sf.ABL.checked;
|
||||
maxB = oMaxB; // TODO make sure we start with all possible buses
|
||||
|
||||
// enable/disable LED fields
|
||||
d.Sf.querySelectorAll("#mLC select[name^=LT]").forEach((s)=>{
|
||||
let LTs = d.Sf.querySelectorAll("#mLC select[name^=LT]");
|
||||
LTs.forEach((s,i)=>{
|
||||
if (i < LTs.length-1) s.disabled = true; // prevent changing type (as we can't update options)
|
||||
// is the field a LED type?
|
||||
var n = s.name.substring(2);
|
||||
var t = parseInt(s.value);
|
||||
@@ -249,7 +264,8 @@
|
||||
gId("rf"+n).onclick = (t == 31) ? (()=>{return false}) : (()=>{}); // prevent change for TM1814
|
||||
gRGBW |= hasW(t); // RGBW checkbox, TYPE_xxxx values from const.h
|
||||
gId("co"+n).style.display = (isVir(t) || isAna(t)) ? "none":"inline"; // hide color order for PWM
|
||||
gId("dig"+n+"w").style.display = (isDig(t) && hasW(t)) ? "inline":"none"; // show swap channels dropdown
|
||||
gId("dig"+n+"w").style.display = (isDig(t) && hasW(t)) ? "inline":"none"; // show swap channels dropdown
|
||||
gId("dig"+n+"w").querySelector("[data-opt=CCT]").disabled = !hasCCT(t); // disable WW/CW swapping
|
||||
if (!(isDig(t) && hasW(t))) d.Sf["WO"+n].value = 0; // reset swapping
|
||||
gId("dig"+n+"c").style.display = (isAna(t)) ? "none":"inline"; // hide count for analog
|
||||
gId("dig"+n+"r").style.display = (isVir(t)) ? "none":"inline"; // hide reversed for virtual
|
||||
@@ -275,6 +291,7 @@
|
||||
// do we have a led count field
|
||||
if (nm=="LC") {
|
||||
let c = parseInt(LC.value,10); //get LED count
|
||||
if (c > 300 && i < 8) maxB = oMaxB - Math.max(maxD-7,0); //TODO: hard limit for buses when using ESP32 parallel I2S
|
||||
if (!customStarts || !startsDirty[n]) gId("ls"+n).value=sLC; //update start value
|
||||
gId("ls"+n).disabled = !customStarts; //enable/disable field editing
|
||||
if (c) {
|
||||
@@ -365,53 +382,63 @@
|
||||
v = parseInt(d.getElementsByName("LS"+s)[0].value) + parseInt(d.getElementsByName("LC"+s)[0].value);
|
||||
var t = parseInt(d.getElementsByName("LT"+s)[0].value);
|
||||
if (isPWM(t)) v = 1; //PWM busses
|
||||
if (isNaN(v)) return 0;
|
||||
return v;
|
||||
return isNaN(v) ? 0 : v;
|
||||
}
|
||||
function addLEDs(n,init=true)
|
||||
{
|
||||
var o = d.getElementsByClassName("iST");
|
||||
var i = o.length;
|
||||
let disable = (sel,opt) => { sel.querySelectorAll(opt).forEach((o)=>{o.disabled=true;}); }
|
||||
|
||||
var f = gId("mLC");
|
||||
let digitalB = 0, analogB = 0, twopinB = 0, virtB = 0;
|
||||
f.querySelectorAll("select[name^=LT]").forEach((s)=>{
|
||||
let t = s.value;
|
||||
if (isDig(t) && !isD2P(t)) digitalB++;
|
||||
if (isD2P(t)) twopinB++;
|
||||
if (isPWM(t)) analogB += t-40; // type defines PWM pins
|
||||
if (isVir(t)) virtB++;
|
||||
});
|
||||
|
||||
if ((n==1 && i>=maxB+maxV) || (n==-1 && i==0)) return;
|
||||
var s = String.fromCharCode((i<10?48:55)+i);
|
||||
|
||||
var f = gId("mLC");
|
||||
if (n==1) {
|
||||
// npm run build has trouble minimizing spaces inside string
|
||||
var cn = `<div class="iST">
|
||||
<hr class="sml">
|
||||
${i+1}:
|
||||
<select name="LT${s}" onchange="UI(true)">${i>=maxB ? '' :
|
||||
'<option value="22" selected>WS281x</option>\
|
||||
<option value="30">SK6812/WS2814 RGBW</option>\
|
||||
<option value="31">TM1814</option>\
|
||||
<option value="24">400kHz</option>\
|
||||
<option value="25">TM1829</option>\
|
||||
<option value="26">UCS8903</option>\
|
||||
<option value="27">APA106/PL9823</option>\
|
||||
<option value="33">TM1914</option>\
|
||||
<option value="28">FW1906 GRBCW</option>\
|
||||
<option value="29">UCS8904 RGBW</option>\
|
||||
<option value="32">WS2805 RGBCW</option>\
|
||||
<option value="50">WS2801</option>\
|
||||
<option value="51">APA102</option>\
|
||||
<option value="52">LPD8806</option>\
|
||||
<option value="54">LPD6803</option>\
|
||||
<option value="53">P9813</option>\
|
||||
<option value="19">WS2811 White</option>\
|
||||
<select name="LT${s}" onchange="UI(true)">${i>=maxB && false ? '' :
|
||||
'<option value="22" data-type="D">WS281x</option>\
|
||||
<option value="30" data-type="D">SK6812/WS2814 RGBW</option>\
|
||||
<option value="31" data-type="D">TM1814</option>\
|
||||
<option value="24" data-type="D">400kHz</option>\
|
||||
<option value="25" data-type="D">TM1829</option>\
|
||||
<option value="26" data-type="D">UCS8903</option>\
|
||||
<option value="27" data-type="D">APA106/PL9823</option>\
|
||||
<option value="33" data-type="D">TM1914</option>\
|
||||
<option value="28" data-type="D">FW1906 GRBCW</option>\
|
||||
<option value="29" data-type="D">UCS8904 RGBW</option>\
|
||||
<option value="32" data-type="D">WS2805 RGBCW</option>\
|
||||
<option value="34" data-type="D">SM16825 RGBCW</option>\
|
||||
<option value="50" data-type="2P">WS2801</option>\
|
||||
<option value="51" data-type="2P">APA102</option>\
|
||||
<option value="52" data-type="2P">LPD8806</option>\
|
||||
<option value="54" data-type="2P">LPD6803</option>\
|
||||
<option value="53" data-type="2P">P9813</option>\
|
||||
<option value="19" data-type="D">WS2811 White</option>\
|
||||
<option value="40">On/Off</option>\
|
||||
<option value="41">PWM White</option>\
|
||||
<option value="42">PWM CCT</option>\
|
||||
<option value="43">PWM RGB</option>\
|
||||
<option value="44">PWM RGBW</option>\
|
||||
<option value="45">PWM RGB+CCT</option>\
|
||||
<!--option value="46">PWM RGB+DCCT</option-->'}
|
||||
<option value="80">DDP RGB (network)</option>
|
||||
<!--option value="81">E1.31 RGB (network)</option-->
|
||||
<option value="82">Art-Net RGB (network)</option>
|
||||
<option value="88">DDP RGBW (network)</option>
|
||||
<option value="89">Art-Net RGBW (network)</option>
|
||||
<option value="41" data-type="A">PWM White</option>\
|
||||
<option value="42" data-type="AA">PWM CCT</option>\
|
||||
<option value="43" data-type="AAA">PWM RGB</option>\
|
||||
<option value="44" data-type="AAAA">PWM RGBW</option>\
|
||||
<option value="45" data-type="AAAAA">PWM RGB+CCT</option>\
|
||||
<!--option value="46" data-type="AAAAAA">PWM RGB+DCCT</option-->'}
|
||||
<option value="80" data-type="V">DDP RGB (network)</option>
|
||||
<!--option value="81" data-type="V">E1.31 RGB (network)</option-->
|
||||
<option value="82" data-type="V">Art-Net RGB (network)</option>
|
||||
<option value="88" data-type="V">DDP RGBW (network)</option>
|
||||
<option value="89" data-type="V">Art-Net RGBW (network)</option>
|
||||
</select><br>
|
||||
<div id="abl${s}">
|
||||
mA/LED: <select name="LAsel${s}" onchange="enLA(this,'${s}');UI();">
|
||||
@@ -434,7 +461,7 @@ mA/LED: <select name="LAsel${s}" onchange="enLA(this,'${s}');UI();">
|
||||
<option value="4">BGR</option>
|
||||
<option value="5">GBR</option>
|
||||
</select></div>
|
||||
<div id="dig${s}w" style="display:none">Swap: <select name="WO${s}"><option value="0">None</option><option value="1">W & B</option><option value="2">W & G</option><option value="3">W & R</option></select></div>
|
||||
<div id="dig${s}w" style="display:none">Swap: <select name="WO${s}"><option value="0">None</option><option value="1">W & B</option><option value="2">W & G</option><option value="3">W & R</option><option data-opt="CCT" value="4">WW & CW</option></select></div>
|
||||
<div id="dig${s}l" style="display:none">Clock: <select name="SP${s}"><option value="0">Slowest</option><option value="1">Slow</option><option value="2">Normal</option><option value="3">Fast</option><option value="4">Fastest</option></select></div>
|
||||
<div>
|
||||
<span id="psd${s}">Start:</span> <input type="number" name="LS${s}" id="ls${s}" class="l starts" min="0" max="8191" value="${lastEnd(i)}" oninput="startsDirty[${i}]=true;UI();" required />
|
||||
@@ -451,9 +478,15 @@ mA/LED: <select name="LAsel${s}" onchange="enLA(this,'${s}');UI();">
|
||||
<div id="dig${s}a" style="display:inline"><br>Auto-calculate white channel from RGB:<br><select name="AW${s}"><option value=0>None</option><option value=1>Brighter</option><option value=2>Accurate</option><option value=3>Dual</option><option value=4>Max</option></select> </div>
|
||||
</div>`;
|
||||
f.insertAdjacentHTML("beforeend", cn);
|
||||
let sel = d.getElementsByName("LT"+s)[0]
|
||||
if (i >= maxB || digitalB >= maxD) disable(sel,'option[data-type="D"]');
|
||||
if (i >= maxB || twopinB >= 1) disable(sel,'option[data-type="2P"]');
|
||||
disable(sel,`option[data-type^="${'A'.repeat(maxA-analogB+1)}"]`);
|
||||
sel.selectedIndex = sel.querySelector('option:not(:disabled)').index;
|
||||
}
|
||||
if (n==-1) {
|
||||
o[--i].remove();--i;
|
||||
o[i].querySelector("[name^=LT]").disabled = false;
|
||||
}
|
||||
|
||||
gId("+").style.display = (i<maxB+maxV-1) ? "inline":"none";
|
||||
@@ -772,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 <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;">
|
||||
⚠ Your power supply provides high current.<br>
|
||||
@@ -791,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;">
|
||||
⚠ You might run into stability or lag issues.<br>
|
||||
@@ -813,6 +847,7 @@ Swap: <select id="xw${s}" name="XW${s}">
|
||||
<div id="btns"></div>
|
||||
Disable internal pull-up/down: <input type="checkbox" name="IP"><br>
|
||||
Touch threshold: <input type="number" class="s" min="0" max="100" name="TT" required><br>
|
||||
<hr class="sml">
|
||||
IR GPIO: <input type="number" min="-1" max="48" name="IR" onchange="UI()" class="xs"><select name="IT" onchange="UI()">
|
||||
<option value=0>Remote disabled</option>
|
||||
<option value=1>24-key RGB</option>
|
||||
@@ -827,13 +862,14 @@ Swap: <select id="xw${s}" name="XW${s}">
|
||||
Apply IR change to main segment only: <input type="checkbox" name="MSO"><br>
|
||||
<div id="json" style="display:none;">JSON file: <input type="file" name="data" accept=".json"><button type="button" class="sml" onclick="uploadFile('/ir.json')">Upload</button><br></div>
|
||||
<a href="https://kno.wled.ge/interfaces/infrared/" target="_blank">IR info</a><br>
|
||||
Relay GPIO: <input type="number" min="-1" max="48" name="RL" onchange="UI()" class="xs"><span style="cursor: pointer;" onclick="off('RL')"> ✕</span> Invert <input type="checkbox" name="RM"> Open drain <input type="checkbox" name="RO"><br>
|
||||
<hr class="sml">
|
||||
Relay GPIO: <input type="number" min="-1" max="48" name="RL" onchange="UI()" class="xs"><span style="cursor: pointer;" onclick="off('RL')"> ✕</span><br>
|
||||
Invert <input type="checkbox" name="RM"> Open drain <input type="checkbox" name="RO"><br>
|
||||
<hr class="sml">
|
||||
<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="0" max="255" required> (0-255)<br><br>
|
||||
Apply preset <input name="BP" type="number" class="m" min="0" max="250" required> at boot (0 uses defaults)
|
||||
<br><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 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>
|
||||
@@ -842,14 +878,14 @@ Swap: <select id="xw${s}" name="XW${s}">
|
||||
Enable transitions: <input type="checkbox" name="TF" onchange="gId('tran').style.display=this.checked?'inline':'none';"><br>
|
||||
<span id="tran">
|
||||
Effect blending: <input type="checkbox" name="EB"><br>
|
||||
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>
|
||||
Palette transitions: <input type="checkbox" name="PF"><br>
|
||||
</span>
|
||||
<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>
|
||||
@@ -875,7 +911,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>
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
if (d.um_p[0]==-1) d.um_p.shift(); // remove filler
|
||||
d.Sf.SDA.max = d.Sf.SCL.max = d.Sf.MOSI.max = d.Sf.SCLK.max = d.Sf.MISO.max = d.max_gpio;
|
||||
//for (let i of d.getElementsByTagName("input")) if (i.type === "number" && i.name.replace("[]","").substr(-3) === "pin") i.max = d.max_gpio;
|
||||
pinDropdowns(); // convert INPUT to SELECT for pins
|
||||
pinDD(); // convert INPUT to SELECT for pins
|
||||
});
|
||||
// error event
|
||||
scE.addEventListener("error", (ev) => {
|
||||
@@ -165,25 +165,25 @@
|
||||
urows += `<input type="${t==="int"?"number":t}" name="${k}:${f}${a?"[]":""}" ${c} oninput="check(this,'${k.substr(k.indexOf(":")+1)}')"><br>`;
|
||||
}
|
||||
}
|
||||
function pinDropdowns() {
|
||||
function pinDD() {
|
||||
for (let i of d.Sf.elements) {
|
||||
if (i.type === "number" && (i.name.includes("pin") || ["SDA","SCL","MOSI","MISO","SCLK"].includes(i.name))) { //select all pin select elements
|
||||
let v = parseInt(i.value);
|
||||
let sel = addDropdown(i.name,0);
|
||||
let sel = addDD(i.name,0);
|
||||
for (var j = -1; j <= d.max_gpio; j++) {
|
||||
if (d.rsvd.includes(j)) continue;
|
||||
let foundPin = pins.indexOf(j);
|
||||
let txt = (j === -1) ? "unused" : `${j}`;
|
||||
if (foundPin >= 0 && j !== v) txt += ` ${pinO[foundPin]=="if"?"global":pinO[foundPin]}`; // already reserved pin
|
||||
if (d.ro_gpio.includes(j)) txt += " (R/O)";
|
||||
let opt = addOption(sel, txt, j);
|
||||
let opt = addO(sel, txt, j);
|
||||
if (j === v) opt.selected = true; // this is "our" pin
|
||||
else if (pins.includes(j)) opt.disabled = true; // someone else's pin
|
||||
}
|
||||
let um = i.name.split(":")[0];
|
||||
d.extra.forEach((o)=>{
|
||||
if (o[um] && o[um].pin) o[um].pin.forEach((e)=>{
|
||||
let opt = addOption(sel,e[0],e[1]);
|
||||
let opt = addO(sel,e[0],e[1]);
|
||||
if (e[1]==v) opt.selected = true;
|
||||
});
|
||||
});
|
||||
@@ -219,7 +219,7 @@
|
||||
}
|
||||
}
|
||||
// https://stackoverflow.com/questions/39729741/javascript-change-input-text-to-select-option
|
||||
function addDropdown(um,fld) {
|
||||
function addDD(um,fld) {
|
||||
let sel = d.createElement('select');
|
||||
if (typeof(fld) === "string") { // parameter from usermod (field name)
|
||||
if (fld.includes("pin")) sel.classList.add("pin");
|
||||
@@ -255,7 +255,8 @@
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function addOption(sel,txt,val) {
|
||||
var addDropdown = addDD; // backwards compatibility
|
||||
function addO(sel,txt,val) {
|
||||
if (sel===null) return; // select object missing
|
||||
let opt = d.createElement("option");
|
||||
opt.value = val;
|
||||
@@ -267,8 +268,9 @@
|
||||
}
|
||||
return opt;
|
||||
}
|
||||
var addOption = addO; // backwards compatibility
|
||||
// https://stackoverflow.com/questions/26440494/insert-text-after-this-input-element-with-javascript
|
||||
function addInfo(name,el,txt, txt2="") {
|
||||
function addI(name,el,txt, txt2="") {
|
||||
let obj = d.getElementsByName(name);
|
||||
if (!obj.length) return;
|
||||
if (typeof el === "string" && obj[0]) obj[0].placeholder = el;
|
||||
@@ -277,9 +279,10 @@
|
||||
if (txt2!="") obj[el].insertAdjacentHTML('beforebegin', txt2 + ' '); //add pre texts
|
||||
}
|
||||
}
|
||||
var addInfo = addI; // backwards compatibility
|
||||
// add Help Button
|
||||
function addHB(um) {
|
||||
addInfo(um + ':help',0,`<button onclick="location.href='https://kno.wled.ge/usermods/${um}'" type="button">?</button>`);
|
||||
addI(um + ':help',0,`<button onclick="location.href='https://kno.wled.ge/usermods/${um}'" type="button">?</button>`);
|
||||
}
|
||||
// load settings and insert values into DOM
|
||||
function ldS() {
|
||||
|
||||
@@ -224,8 +224,23 @@ Static subnet mask:<br>
|
||||
<h3>Experimental</h3>
|
||||
Force 802.11g mode (ESP8266 only): <input type="checkbox" name="FG"><br>
|
||||
Disable WiFi sleep: <input type="checkbox" name="WS"><br>
|
||||
<i>Can help with connectivity issues.<br>
|
||||
Do not enable if WiFi is working correctly, increases power consumption.</i>
|
||||
<i>Can help with connectivity issues and Audioreactive sync.<br>
|
||||
Disabling WiFi sleep increases power consumption.</i><br>
|
||||
<div id="tx">TX power: <select name="TX">
|
||||
<option value="78">19.5 dBm</option>
|
||||
<option value="76">19 dBm</option>
|
||||
<option value="74">18.5 dBm</option>
|
||||
<option value="68">17 dBm</option>
|
||||
<option value="60">15 dBm</option>
|
||||
<option value="52">13 dBm</option>
|
||||
<option value="44">11 dBm</option>
|
||||
<option value="34">8.5 dBm</option>
|
||||
<option value="28">7 dBm</option>
|
||||
<option value="20">5 dBm</option>
|
||||
<option value="8">2 dBm</option>
|
||||
</select><br>
|
||||
<i class="warn">WARNING: Modifying TX power may render device unreachable.</i>
|
||||
</div>
|
||||
|
||||
<h3>ESP-NOW Wireless</h3>
|
||||
<div id="NoESPNOW" class="hide">
|
||||
@@ -248,6 +263,7 @@ Static subnet mask:<br>
|
||||
<option value="11">ESP32-POE-WROVER</option>
|
||||
<option value="6">ESP32Deux/RGB2Go Tetra</option>
|
||||
<option value="7">KIT-VE</option>
|
||||
<option value="12">LILYGO T-POE Pro</option>
|
||||
<option value="8">QuinLED-Dig-Octa & T-ETH-POE</option>
|
||||
<option value="4">QuinLED-ESP32</option>
|
||||
<option value="10">Serg74-ETH32</option>
|
||||
|
||||
@@ -22,7 +22,7 @@ void handleDMX()
|
||||
bool calc_brightness = true;
|
||||
|
||||
// check if no shutter channel is set
|
||||
for (byte i = 0; i < DMXChannels; i++)
|
||||
for (unsigned i = 0; i < DMXChannels; i++)
|
||||
{
|
||||
if (DMXFixtureMap[i] == 5) calc_brightness = false;
|
||||
}
|
||||
|
||||
@@ -26,22 +26,21 @@ void handleDDPPacket(e131_packet_t* p) {
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t ddpChannelsPerLed = ((p->dataType & 0b00111000)>>3 == 0b011) ? 4 : 3; // data type 0x1B (formerly 0x1A) is RGBW (type 3, 8 bit/channel)
|
||||
unsigned ddpChannelsPerLed = ((p->dataType & 0b00111000)>>3 == 0b011) ? 4 : 3; // data type 0x1B (formerly 0x1A) is RGBW (type 3, 8 bit/channel)
|
||||
|
||||
uint32_t start = htonl(p->channelOffset) / ddpChannelsPerLed;
|
||||
start += DMXAddress / ddpChannelsPerLed;
|
||||
uint16_t stop = start + htons(p->dataLen) / ddpChannelsPerLed;
|
||||
unsigned stop = start + htons(p->dataLen) / ddpChannelsPerLed;
|
||||
uint8_t* data = p->data;
|
||||
uint16_t c = 0;
|
||||
unsigned c = 0;
|
||||
if (p->flags & DDP_TIMECODE_FLAG) c = 4; //packet has timecode flag, we do not support it, but data starts 4 bytes later
|
||||
|
||||
if (realtimeMode != REALTIME_MODE_DDP) ddpSeenPush = false; // just starting, no push yet
|
||||
realtimeLock(realtimeTimeoutMs, REALTIME_MODE_DDP);
|
||||
|
||||
if (!realtimeOverride || (realtimeMode && useMainSegmentOnly)) {
|
||||
for (uint16_t i = start; i < stop; i++) {
|
||||
for (unsigned i = start; i < stop; i++, c += ddpChannelsPerLed) {
|
||||
setRealtimePixel(i, data[c], data[c+1], data[c+2], ddpChannelsPerLed >3 ? data[c+3] : 0);
|
||||
c += ddpChannelsPerLed;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,7 +48,7 @@ void handleDDPPacket(e131_packet_t* p) {
|
||||
ddpSeenPush |= push;
|
||||
if (!ddpSeenPush || push) { // if we've never seen a push, or this is one, render display
|
||||
e131NewData = true;
|
||||
byte sn = p->sequenceNum & 0xF;
|
||||
int sn = p->sequenceNum & 0xF;
|
||||
if (sn) e131LastSequenceNumber[0] = sn;
|
||||
}
|
||||
}
|
||||
@@ -57,9 +56,9 @@ void handleDDPPacket(e131_packet_t* p) {
|
||||
//E1.31 and Art-Net protocol support
|
||||
void handleE131Packet(e131_packet_t* p, IPAddress clientIP, byte protocol){
|
||||
|
||||
uint16_t uni = 0, dmxChannels = 0;
|
||||
int uni = 0, dmxChannels = 0;
|
||||
uint8_t* e131_data = nullptr;
|
||||
uint8_t seq = 0, mde = REALTIME_MODE_E131;
|
||||
int seq = 0, mde = REALTIME_MODE_E131;
|
||||
|
||||
if (protocol == P_ARTNET)
|
||||
{
|
||||
@@ -105,17 +104,11 @@ void handleE131Packet(e131_packet_t* p, IPAddress clientIP, byte protocol){
|
||||
// only listen for universes we're handling & allocated memory
|
||||
if (uni < e131Universe || uni >= (e131Universe + E131_MAX_UNIVERSE_COUNT)) return;
|
||||
|
||||
uint8_t previousUniverses = uni - e131Universe;
|
||||
unsigned previousUniverses = uni - e131Universe;
|
||||
|
||||
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;
|
||||
@@ -123,12 +116,12 @@ void handleE131Packet(e131_packet_t* p, IPAddress clientIP, byte protocol){
|
||||
// update status info
|
||||
realtimeIP = clientIP;
|
||||
byte wChannel = 0;
|
||||
uint16_t totalLen = strip.getLengthTotal();
|
||||
uint16_t availDMXLen = 0;
|
||||
uint16_t dataOffset = DMXAddress;
|
||||
unsigned totalLen = strip.getLengthTotal();
|
||||
unsigned availDMXLen = 0;
|
||||
unsigned dataOffset = DMXAddress;
|
||||
|
||||
// For legacy DMX start address 0 the available DMX length offset is 0
|
||||
const uint16_t dmxLenOffset = (DMXAddress == 0) ? 0 : 1;
|
||||
const unsigned dmxLenOffset = (DMXAddress == 0) ? 0 : 1;
|
||||
|
||||
// Check if DMX start address fits in available channels
|
||||
if (dmxChannels >= DMXAddress) {
|
||||
@@ -154,7 +147,7 @@ void handleE131Packet(e131_packet_t* p, IPAddress clientIP, byte protocol){
|
||||
if (realtimeOverride && !(realtimeMode && useMainSegmentOnly)) return;
|
||||
|
||||
wChannel = (availDMXLen > 3) ? e131_data[dataOffset+3] : 0;
|
||||
for (uint16_t i = 0; i < totalLen; i++)
|
||||
for (unsigned i = 0; i < totalLen; i++)
|
||||
setRealtimePixel(i, e131_data[dataOffset+0], e131_data[dataOffset+1], e131_data[dataOffset+2], wChannel);
|
||||
break;
|
||||
|
||||
@@ -171,7 +164,7 @@ void handleE131Packet(e131_packet_t* p, IPAddress clientIP, byte protocol){
|
||||
strip.setBrightness(bri, true);
|
||||
}
|
||||
|
||||
for (uint16_t i = 0; i < totalLen; i++)
|
||||
for (unsigned i = 0; i < totalLen; i++)
|
||||
setRealtimePixel(i, e131_data[dataOffset+1], e131_data[dataOffset+2], e131_data[dataOffset+3], wChannel);
|
||||
break;
|
||||
|
||||
@@ -180,7 +173,7 @@ void handleE131Packet(e131_packet_t* p, IPAddress clientIP, byte protocol){
|
||||
if (uni != e131Universe || availDMXLen < 2) return;
|
||||
|
||||
// limit max. selectable preset to 250, even though DMX max. val is 255
|
||||
uint8_t dmxValPreset = (e131_data[dataOffset+1] > 250 ? 250 : e131_data[dataOffset+1]);
|
||||
int dmxValPreset = (e131_data[dataOffset+1] > 250 ? 250 : e131_data[dataOffset+1]);
|
||||
|
||||
// only apply preset if value changed
|
||||
if (dmxValPreset != 0 && dmxValPreset != currentPreset &&
|
||||
@@ -207,8 +200,8 @@ void handleE131Packet(e131_packet_t* p, IPAddress clientIP, byte protocol){
|
||||
{
|
||||
if (uni != e131Universe) return;
|
||||
bool isSegmentMode = DMXMode == DMX_MODE_EFFECT_SEGMENT || DMXMode == DMX_MODE_EFFECT_SEGMENT_W;
|
||||
uint8_t dmxEffectChannels = (DMXMode == DMX_MODE_EFFECT || DMXMode == DMX_MODE_EFFECT_SEGMENT) ? 15 : 18;
|
||||
for (uint8_t id = 0; id < strip.getSegmentsNum(); id++) {
|
||||
unsigned dmxEffectChannels = (DMXMode == DMX_MODE_EFFECT || DMXMode == DMX_MODE_EFFECT_SEGMENT) ? 15 : 18;
|
||||
for (unsigned id = 0; id < strip.getSegmentsNum(); id++) {
|
||||
Segment& seg = strip.getSegment(id);
|
||||
if (isSegmentMode)
|
||||
dataOffset = DMXAddress + id * (dmxEffectChannels + DMXSegmentSpacing);
|
||||
@@ -255,7 +248,7 @@ void handleE131Packet(e131_packet_t* p, IPAddress clientIP, byte protocol){
|
||||
// Set segment opacity or global brightness
|
||||
if (isSegmentMode) {
|
||||
if (e131_data[dataOffset] != seg.opacity) seg.setOpacity(e131_data[dataOffset]);
|
||||
} else if ( id == strip.getSegmentsNum()-1 ) {
|
||||
} else if ( id == strip.getSegmentsNum()-1U ) {
|
||||
if (bri != e131_data[dataOffset]) {
|
||||
bri = e131_data[dataOffset];
|
||||
strip.setBrightness(bri, true);
|
||||
@@ -271,10 +264,10 @@ void handleE131Packet(e131_packet_t* p, IPAddress clientIP, byte protocol){
|
||||
case DMX_MODE_MULTIPLE_RGBW:
|
||||
{
|
||||
bool is4Chan = (DMXMode == DMX_MODE_MULTIPLE_RGBW);
|
||||
const uint16_t dmxChannelsPerLed = is4Chan ? 4 : 3;
|
||||
const uint16_t ledsPerUniverse = is4Chan ? MAX_4_CH_LEDS_PER_UNIVERSE : MAX_3_CH_LEDS_PER_UNIVERSE;
|
||||
const unsigned dmxChannelsPerLed = is4Chan ? 4 : 3;
|
||||
const unsigned ledsPerUniverse = is4Chan ? MAX_4_CH_LEDS_PER_UNIVERSE : MAX_3_CH_LEDS_PER_UNIVERSE;
|
||||
uint8_t stripBrightness = bri;
|
||||
uint16_t previousLeds, dmxOffset, ledsTotal;
|
||||
unsigned previousLeds, dmxOffset, ledsTotal;
|
||||
|
||||
if (previousUniverses == 0) {
|
||||
if (availDMXLen < 1) return;
|
||||
@@ -290,8 +283,8 @@ void handleE131Packet(e131_packet_t* p, IPAddress clientIP, byte protocol){
|
||||
} else {
|
||||
// All subsequent universes start at the first channel.
|
||||
dmxOffset = (protocol == P_ARTNET) ? 0 : 1;
|
||||
const uint16_t dimmerOffset = (DMXMode == DMX_MODE_MULTIPLE_DRGB) ? 1 : 0;
|
||||
uint16_t ledsInFirstUniverse = (((MAX_CHANNELS_PER_UNIVERSE - DMXAddress) + dmxLenOffset) - dimmerOffset) / dmxChannelsPerLed;
|
||||
const unsigned dimmerOffset = (DMXMode == DMX_MODE_MULTIPLE_DRGB) ? 1 : 0;
|
||||
unsigned ledsInFirstUniverse = (((MAX_CHANNELS_PER_UNIVERSE - DMXAddress) + dmxLenOffset) - dimmerOffset) / dmxChannelsPerLed;
|
||||
previousLeds = ledsInFirstUniverse + (previousUniverses - 1) * ledsPerUniverse;
|
||||
ledsTotal = previousLeds + (dmxChannels / dmxChannelsPerLed);
|
||||
}
|
||||
@@ -316,12 +309,12 @@ void handleE131Packet(e131_packet_t* p, IPAddress clientIP, byte protocol){
|
||||
}
|
||||
|
||||
if (!is4Chan) {
|
||||
for (uint16_t i = previousLeds; i < ledsTotal; i++) {
|
||||
for (unsigned i = previousLeds; i < ledsTotal; i++) {
|
||||
setRealtimePixel(i, e131_data[dmxOffset], e131_data[dmxOffset+1], e131_data[dmxOffset+2], 0);
|
||||
dmxOffset+=3;
|
||||
}
|
||||
} else {
|
||||
for (uint16_t i = previousLeds; i < ledsTotal; i++) {
|
||||
for (unsigned i = previousLeds; i < ledsTotal; i++) {
|
||||
setRealtimePixel(i, e131_data[dmxOffset], e131_data[dmxOffset+1], e131_data[dmxOffset+2], e131_data[dmxOffset+3]);
|
||||
dmxOffset+=4;
|
||||
}
|
||||
@@ -341,8 +334,8 @@ void handleArtnetPollReply(IPAddress ipAddress) {
|
||||
ArtPollReply artnetPollReply;
|
||||
prepareArtnetPollReply(&artnetPollReply);
|
||||
|
||||
uint16_t startUniverse = e131Universe;
|
||||
uint16_t endUniverse = e131Universe;
|
||||
unsigned startUniverse = e131Universe;
|
||||
unsigned endUniverse = e131Universe;
|
||||
|
||||
switch (DMXMode) {
|
||||
case DMX_MODE_DISABLED:
|
||||
@@ -362,15 +355,15 @@ void handleArtnetPollReply(IPAddress ipAddress) {
|
||||
case DMX_MODE_MULTIPLE_RGBW:
|
||||
{
|
||||
bool is4Chan = (DMXMode == DMX_MODE_MULTIPLE_RGBW);
|
||||
const uint16_t dmxChannelsPerLed = is4Chan ? 4 : 3;
|
||||
const uint16_t dimmerOffset = (DMXMode == DMX_MODE_MULTIPLE_DRGB) ? 1 : 0;
|
||||
const uint16_t dmxLenOffset = (DMXAddress == 0) ? 0 : 1; // For legacy DMX start address 0
|
||||
const uint16_t ledsInFirstUniverse = (((MAX_CHANNELS_PER_UNIVERSE - DMXAddress) + dmxLenOffset) - dimmerOffset) / dmxChannelsPerLed;
|
||||
const uint16_t totalLen = strip.getLengthTotal();
|
||||
const unsigned dmxChannelsPerLed = is4Chan ? 4 : 3;
|
||||
const unsigned dimmerOffset = (DMXMode == DMX_MODE_MULTIPLE_DRGB) ? 1 : 0;
|
||||
const unsigned dmxLenOffset = (DMXAddress == 0) ? 0 : 1; // For legacy DMX start address 0
|
||||
const unsigned ledsInFirstUniverse = (((MAX_CHANNELS_PER_UNIVERSE - DMXAddress) + dmxLenOffset) - dimmerOffset) / dmxChannelsPerLed;
|
||||
const unsigned totalLen = strip.getLengthTotal();
|
||||
|
||||
if (totalLen > ledsInFirstUniverse) {
|
||||
const uint16_t ledsPerUniverse = is4Chan ? MAX_4_CH_LEDS_PER_UNIVERSE : MAX_3_CH_LEDS_PER_UNIVERSE;
|
||||
const uint16_t remainLED = totalLen - ledsInFirstUniverse;
|
||||
const unsigned ledsPerUniverse = is4Chan ? MAX_4_CH_LEDS_PER_UNIVERSE : MAX_3_CH_LEDS_PER_UNIVERSE;
|
||||
const unsigned remainLED = totalLen - ledsInFirstUniverse;
|
||||
|
||||
endUniverse += (remainLED / ledsPerUniverse);
|
||||
|
||||
@@ -391,7 +384,7 @@ void handleArtnetPollReply(IPAddress ipAddress) {
|
||||
}
|
||||
|
||||
if (DMXMode != DMX_MODE_DISABLED) {
|
||||
for (uint16_t i = startUniverse; i <= endUniverse; ++i) {
|
||||
for (unsigned i = startUniverse; i <= endUniverse; ++i) {
|
||||
sendArtnetPollReply(&artnetPollReply, ipAddress, i);
|
||||
}
|
||||
}
|
||||
@@ -417,7 +410,7 @@ void prepareArtnetPollReply(ArtPollReply *reply) {
|
||||
reply->reply_opcode = ARTNET_OPCODE_OPPOLLREPLY;
|
||||
|
||||
IPAddress localIP = Network.localIP();
|
||||
for (uint8_t i = 0; i < 4; i++) {
|
||||
for (unsigned i = 0; i < 4; i++) {
|
||||
reply->reply_ip[i] = localIP[i];
|
||||
}
|
||||
|
||||
@@ -493,7 +486,7 @@ void prepareArtnetPollReply(ArtPollReply *reply) {
|
||||
|
||||
Network.localMAC(reply->reply_mac);
|
||||
|
||||
for (uint8_t i = 0; i < 4; i++) {
|
||||
for (unsigned i = 0; i < 4; i++) {
|
||||
reply->reply_bind_ip[i] = localIP[i];
|
||||
}
|
||||
|
||||
@@ -517,7 +510,7 @@ void prepareArtnetPollReply(ArtPollReply *reply) {
|
||||
// Node does not support fail-over
|
||||
reply->reply_status_3 = 0x00;
|
||||
|
||||
for (uint8_t i = 0; i < 21; i++) {
|
||||
for (unsigned i = 0; i < 21; i++) {
|
||||
reply->reply_filler[i] = 0x00;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -310,6 +310,7 @@ class Usermod {
|
||||
virtual bool readFromConfig(JsonObject& obj) { return true; } // Note as of 2021-06 readFromConfig() now needs to return a bool, see usermod_v2_example.h
|
||||
virtual void onMqttConnect(bool sessionPresent) {} // fired when MQTT connection is established (so usermod can subscribe)
|
||||
virtual bool onMqttMessage(char* topic, char* payload) { return false; } // fired upon MQTT message received (wled topic)
|
||||
virtual bool onEspNowMessage(uint8_t* sender, uint8_t* payload, uint8_t len) { return false; } // fired upon ESP-NOW message received
|
||||
virtual void onUpdateBegin(bool) {} // fired prior to and after unsuccessful firmware update
|
||||
virtual void onStateChange(uint8_t mode) {} // fired upon WLED state change
|
||||
virtual uint16_t getId() {return USERMOD_ID_UNSPECIFIED;}
|
||||
@@ -333,8 +334,13 @@ class UsermodManager {
|
||||
void readFromJsonState(JsonObject& obj);
|
||||
void addToConfig(JsonObject& obj);
|
||||
bool readFromConfig(JsonObject& obj);
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
void onMqttConnect(bool sessionPresent);
|
||||
bool onMqttMessage(char* topic, char* payload);
|
||||
#endif
|
||||
#ifndef WLED_DISABLE_ESPNOW
|
||||
bool onEspNowMessage(uint8_t* sender, uint8_t* payload, uint8_t len);
|
||||
#endif
|
||||
void onUpdateBegin(bool);
|
||||
void onStateChange(uint8_t);
|
||||
bool add(Usermod* um);
|
||||
|
||||
@@ -138,7 +138,7 @@ static bool bufferedFindObjectEnd() {
|
||||
|
||||
if (!f || !f.size()) return false;
|
||||
|
||||
uint16_t objDepth = 0; //num of '{' minus num of '}'. return once 0
|
||||
unsigned objDepth = 0; //num of '{' minus num of '}'. return once 0
|
||||
//size_t start = f.position();
|
||||
byte buf[FS_BUFSIZE];
|
||||
|
||||
|
||||