Compare commits
381 Commits
v0.15.0-b4
...
v0.15.1.be
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f593d404cb | ||
|
|
b75a2de485 | ||
|
|
642a9e3652 | ||
|
|
85d3f6f11c | ||
|
|
f490908278 | ||
|
|
1fc3cc83bd | ||
|
|
e96fd8ae58 | ||
|
|
c46e328b59 | ||
|
|
fa2f831044 | ||
|
|
1bf13ea525 | ||
|
|
edc6022441 | ||
|
|
2ac4d03160 | ||
|
|
cc4a4c4ae1 | ||
|
|
4e11ecda4b | ||
|
|
473700e4c0 | ||
|
|
0d5a0fb830 | ||
|
|
012143bd7b | ||
|
|
700a7076fd | ||
|
|
5fc2175dd4 | ||
|
|
c9b95e22d3 | ||
|
|
a265318037 | ||
|
|
866a4c8ab6 | ||
|
|
9dc1022010 | ||
|
|
faadb67eb0 | ||
|
|
a111a2e7a1 | ||
|
|
32864d8986 | ||
|
|
d7bebc2659 | ||
|
|
af410ae2d0 | ||
|
|
1891cc816f | ||
|
|
9a4073e606 | ||
|
|
b78229d1e2 | ||
|
|
71b242874f | ||
|
|
9328e6faca | ||
|
|
bbacc2daae | ||
|
|
3e22f9cabb | ||
|
|
a121f5b61b | ||
|
|
251062170e | ||
|
|
92e59af4d8 | ||
|
|
fa4c23b76e | ||
|
|
a0a46850f5 | ||
|
|
4cd0563a93 | ||
|
|
b83f0f461c | ||
|
|
685ad83d4b | ||
|
|
62ddb18a1a | ||
|
|
3668ede0ff | ||
|
|
6a12378475 | ||
|
|
945584384a | ||
|
|
b1dd27b516 | ||
|
|
dcba1aad10 | ||
|
|
acc8b9cdbc | ||
|
|
d26b3108da | ||
|
|
6cbdd825eb | ||
|
|
cc55f6015d | ||
|
|
c89e4576b4 | ||
|
|
bc79f44a26 | ||
|
|
7ece14ff3f | ||
|
|
95718ab6ec | ||
|
|
feab27295d | ||
|
|
ca176c7549 | ||
|
|
f8a7a0d6e8 | ||
|
|
1a8aaa3b26 | ||
|
|
cd1c13b4b1 | ||
|
|
d87c5035dd | ||
|
|
77967731d5 | ||
|
|
0b54034470 | ||
|
|
0b3643132b | ||
|
|
a5693fbf8d | ||
|
|
5c5b70f52b | ||
|
|
ae97e388a6 | ||
|
|
37cddcaacc | ||
|
|
a1b332fc78 | ||
|
|
86d7c24513 | ||
|
|
b28add3b8b | ||
|
|
5fd3a513a4 | ||
|
|
b98a8a10b0 | ||
|
|
2bee2793ef | ||
|
|
2f6fa66f4d | ||
|
|
8ad2583785 | ||
|
|
dd533a9ab4 | ||
|
|
5b989adebc | ||
|
|
5d38acd787 | ||
|
|
e607fcb5c5 | ||
|
|
8a18555ae4 | ||
|
|
beb709dc8f | ||
|
|
20f8d3c8a9 | ||
|
|
0c77dbb7ea | ||
|
|
2448e2ae3b | ||
|
|
d53d7aa2e2 | ||
|
|
7a58c69a80 | ||
|
|
0be1df7ee8 | ||
|
|
1082c85789 | ||
|
|
568d2edd96 | ||
|
|
6aef0e145c | ||
|
|
32dc54ce72 | ||
|
|
548736f432 | ||
|
|
89d587e7dd | ||
|
|
5c8b2ebf7a | ||
|
|
5ac8ba9bae | ||
|
|
49fb16e2c6 | ||
|
|
545bfa6ef9 | ||
|
|
c596b5a17d | ||
|
|
84dd26c1b7 | ||
|
|
a765903a41 | ||
|
|
25ab381916 | ||
|
|
4d3df5d98f | ||
|
|
6fe2024542 | ||
|
|
4cd4c13b2d | ||
|
|
d2d56ebbd2 | ||
|
|
86be5df475 | ||
|
|
8c5e0cd4e9 | ||
|
|
a9b0b8adc8 | ||
|
|
ba01cb82f7 | ||
|
|
223b97b884 | ||
|
|
5de86d3d91 | ||
|
|
536444f9d1 | ||
|
|
271a07a7d6 | ||
|
|
4634ace74e | ||
|
|
3733715184 | ||
|
|
bf37ac53a3 | ||
|
|
70323b9477 | ||
|
|
7d0951a08a | ||
|
|
d98ca9a202 | ||
|
|
3c2c5bedc5 | ||
|
|
749d34cd30 | ||
|
|
1898be2fe1 | ||
|
|
af34da4160 | ||
|
|
fa053b7e60 | ||
|
|
4588219e31 | ||
|
|
6e89346f00 | ||
|
|
2703c9899a | ||
|
|
d05c358fd2 | ||
|
|
7c6bc5c421 | ||
|
|
798c398f23 | ||
|
|
4cc2cc4ad4 | ||
|
|
dcfdca6351 | ||
|
|
832599b8c5 | ||
|
|
c81ef2669e | ||
|
|
19d837c222 | ||
|
|
4f48ddfaec | ||
|
|
2e01fe0b5b | ||
|
|
7d067d8c30 | ||
|
|
b3b326738c | ||
|
|
2bb2caf2d2 | ||
|
|
2a094883ad | ||
|
|
6d1126b8aa | ||
|
|
26a47537f9 | ||
|
|
01d43c69fb | ||
|
|
7db1989093 | ||
|
|
0a97e28aab | ||
|
|
98a6907976 | ||
|
|
e9d2182390 | ||
|
|
5e29f2c1b7 | ||
|
|
44e28f96e0 | ||
|
|
a0e81da8c5 | ||
|
|
85a7c3c60d | ||
|
|
01e07ca0bc | ||
|
|
1468ee5fde | ||
|
|
49f044ecde | ||
|
|
37f32ab197 | ||
|
|
a60231ba59 | ||
|
|
c8dafede6d | ||
|
|
7deea9eb75 | ||
|
|
5e9a46d54d | ||
|
|
488974dd3e | ||
|
|
5975b9125f | ||
|
|
f301296f1e | ||
|
|
407477dc68 | ||
|
|
1b0ce9a123 | ||
|
|
7b855c851d | ||
|
|
ba636b17a0 | ||
|
|
2a07eb84f6 | ||
|
|
949b9fb10e | ||
|
|
ae1b6af0d4 | ||
|
|
dd27504d30 | ||
|
|
c30a08cfc5 | ||
|
|
a4c49aa35e | ||
|
|
402fba734a | ||
|
|
262af0678f | ||
|
|
3765d558b6 | ||
|
|
4ed8ded502 | ||
|
|
7fa25ca7ae | ||
|
|
d3c401ed4e | ||
|
|
10d8cfde85 | ||
|
|
6f221852a2 | ||
|
|
6dc2c680c5 | ||
|
|
9a4b56db6e | ||
|
|
8180f2c742 | ||
|
|
c600c6da63 | ||
|
|
e789a18553 | ||
|
|
3f3c986932 | ||
|
|
3ccc5babc1 | ||
|
|
bd7cd32f91 | ||
|
|
9cb3531e2d | ||
|
|
b50e6e0d90 | ||
|
|
45cf90094a | ||
|
|
ae1df20893 | ||
|
|
71148740d4 | ||
|
|
4ef583c844 | ||
|
|
16f61ea96d | ||
|
|
32f9616b6e | ||
|
|
1346eb4f76 | ||
|
|
d4268ba070 | ||
|
|
72455ccde1 | ||
|
|
88fb860568 | ||
|
|
ceed494cf7 | ||
|
|
ac8f919304 | ||
|
|
7f1ec4802d | ||
|
|
d5777b7bce | ||
|
|
e34f179a82 | ||
|
|
6a90b9a512 | ||
|
|
65a8dbfe41 | ||
|
|
0806c7fbdb | ||
|
|
5708d7a6b8 | ||
|
|
2264cc5d10 | ||
|
|
28cb3f9d0c | ||
|
|
f16ed4697f | ||
|
|
81e412fe5b | ||
|
|
e3d9417b84 | ||
|
|
6a188033c6 | ||
|
|
df24fd7bf2 | ||
|
|
fa82e759bd | ||
|
|
daf0bcfac3 | ||
|
|
49d51c5af8 | ||
|
|
ec7f69d559 | ||
|
|
a8c5bf2573 | ||
|
|
f12de61d7f | ||
|
|
71fcd6482d | ||
|
|
e59b38a5d2 | ||
|
|
5b8d9d1510 | ||
|
|
6169c458bf | ||
|
|
23400d0449 | ||
|
|
c5435ec1fa | ||
|
|
eae5a74a11 | ||
|
|
5df1a223c2 | ||
|
|
81382a4bc0 | ||
|
|
750a429bd4 | ||
|
|
dbe78dff93 | ||
|
|
5869627b32 | ||
|
|
5bc5ef0ae8 | ||
|
|
cce5e8f811 | ||
|
|
8ae09c3d02 | ||
|
|
83699bc5c3 | ||
|
|
3a5eb8c5d2 | ||
|
|
fd00e5eaae | ||
|
|
20444ee7d5 | ||
|
|
eb06e575c2 | ||
|
|
b4315152e2 | ||
|
|
340a9f8b76 | ||
|
|
81cec6a25a | ||
|
|
c5b31e2f63 | ||
|
|
0642b17ab0 | ||
|
|
ac689a9a2e | ||
|
|
43cc4ec009 | ||
|
|
9cc333b2bd | ||
|
|
55d98ff935 | ||
|
|
b9080f9479 | ||
|
|
092a5a1ca3 | ||
|
|
d3c31c52a2 | ||
|
|
329173e145 | ||
|
|
8e4f8fcbc8 | ||
|
|
c1c707c77a | ||
|
|
b1e58dd10d | ||
|
|
2cc0aceac7 | ||
|
|
d79d5dbadd | ||
|
|
be7475fe66 | ||
|
|
85e2f7eb34 | ||
|
|
9bb979f2e8 | ||
|
|
c942345453 | ||
|
|
fcc344ba99 | ||
|
|
a3b28871c6 | ||
|
|
2ca034bfa8 | ||
|
|
0d035a08d6 | ||
|
|
6655e2664e | ||
|
|
c51ce2eec7 | ||
|
|
b2e00eb868 | ||
|
|
820df0c596 | ||
|
|
865e3dcd0c | ||
|
|
f55e2fc7b8 | ||
|
|
cb22e1933e | ||
|
|
8818a9e82a | ||
|
|
dbb47d506c | ||
|
|
e4d5d77347 | ||
|
|
dd52124765 | ||
|
|
6f3267aee9 | ||
|
|
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 | ||
|
|
3815516022 | ||
|
|
a1dfdced31 | ||
|
|
ff39a8db3f | ||
|
|
9877e899e0 | ||
|
|
bc4a6138b1 | ||
|
|
f825cab54a | ||
|
|
cec7241986 | ||
|
|
6de77293ad | ||
|
|
0ac53d8353 | ||
|
|
c8a7d44f55 |
@@ -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",
|
||||
|
||||
80
.github/workflows/build.yml
vendored
Normal file
80
.github/workflows/build.yml
vendored
Normal file
@@ -0,0 +1,80 @@
|
||||
name: WLED Build
|
||||
|
||||
# Only included into other workflows
|
||||
on:
|
||||
workflow_call:
|
||||
|
||||
jobs:
|
||||
|
||||
get_default_envs:
|
||||
name: Gather Environments
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
cache: 'pip'
|
||||
- name: Install PlatformIO
|
||||
run: pip install -r requirements.txt
|
||||
- name: Get default environments
|
||||
id: envs
|
||||
run: |
|
||||
echo "environments=$(pio project config --json-output | jq -cr '.[0][1][0][1]')" >> $GITHUB_OUTPUT
|
||||
outputs:
|
||||
environments: ${{ steps.envs.outputs.environments }}
|
||||
|
||||
|
||||
build:
|
||||
name: Build Enviornments
|
||||
runs-on: ubuntu-latest
|
||||
needs: get_default_envs
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
environment: ${{ fromJSON(needs.get_default_envs.outputs.environments) }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
cache: 'npm'
|
||||
- run: npm ci
|
||||
- name: Cache PlatformIO
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.platformio/.cache
|
||||
~/.buildcache
|
||||
build_output
|
||||
key: pio-${{ runner.os }}-${{ matrix.environment }}-${{ hashFiles('platformio.ini', 'pio-scripts/output_bins.py') }}-${{ hashFiles('wled00/**', 'usermods/**') }}
|
||||
restore-keys: pio-${{ runner.os }}-${{ matrix.environment }}-${{ hashFiles('platformio.ini', 'pio-scripts/output_bins.py') }}-
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
cache: 'pip'
|
||||
- name: Install PlatformIO
|
||||
run: pip install -r requirements.txt
|
||||
- name: Build firmware
|
||||
run: pio run -e ${{ matrix.environment }}
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: firmware-${{ matrix.environment }}
|
||||
path: |
|
||||
build_output/release/*.bin
|
||||
build_output/release/*_ESP02*.bin.gz
|
||||
|
||||
|
||||
testCdata:
|
||||
name: Test cdata.js
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Use Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20.x'
|
||||
cache: 'npm'
|
||||
- run: npm ci
|
||||
- run: npm test
|
||||
28
.github/workflows/release.yml
vendored
Normal file
28
.github/workflows/release.yml
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
name: WLED Release CI
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- '*'
|
||||
|
||||
jobs:
|
||||
|
||||
wled_build:
|
||||
uses: ./.github/workflows/build.yml
|
||||
|
||||
release:
|
||||
name: Create Release
|
||||
runs-on: ubuntu-latest
|
||||
needs: wled_build
|
||||
steps:
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
merge-multiple: true
|
||||
- name: Create draft release
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
draft: True
|
||||
files: |
|
||||
*.bin
|
||||
*.bin.gz
|
||||
|
||||
97
.github/workflows/wled-ci.yml
vendored
97
.github/workflows/wled-ci.yml
vendored
@@ -1,94 +1,11 @@
|
||||
name: WLED CI
|
||||
|
||||
on: [push, pull_request]
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- '*'
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
|
||||
get_default_envs:
|
||||
name: Gather Environments
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
cache: 'pip'
|
||||
- name: Install PlatformIO
|
||||
run: pip install -r requirements.txt
|
||||
- name: Get default environments
|
||||
id: envs
|
||||
run: |
|
||||
echo "environments=$(pio project config --json-output | jq -cr '.[0][1][0][1]')" >> $GITHUB_OUTPUT
|
||||
outputs:
|
||||
environments: ${{ steps.envs.outputs.environments }}
|
||||
|
||||
|
||||
build:
|
||||
name: Build Enviornments
|
||||
runs-on: ubuntu-latest
|
||||
needs: get_default_envs
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
environment: ${{ fromJSON(needs.get_default_envs.outputs.environments) }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
cache: 'npm'
|
||||
- run: npm ci
|
||||
- name: Cache PlatformIO
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.platformio/.cache
|
||||
~/.buildcache
|
||||
build_output
|
||||
key: pio-${{ runner.os }}-${{ matrix.environment }}-${{ hashFiles('platformio.ini', 'pio-scripts/output_bins.py') }}-${{ hashFiles('wled00/**', 'usermods/**') }}
|
||||
restore-keys: pio-${{ runner.os }}-${{ matrix.environment }}-${{ hashFiles('platformio.ini', 'pio-scripts/output_bins.py') }}-
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
cache: 'pip'
|
||||
- name: Install PlatformIO
|
||||
run: pip install -r requirements.txt
|
||||
- name: Build firmware
|
||||
run: pio run -e ${{ matrix.environment }}
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: firmware-${{ matrix.environment }}
|
||||
path: |
|
||||
build_output/release/*.bin
|
||||
build_output/release/*_ESP02*.bin.gz
|
||||
release:
|
||||
name: Create Release
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
steps:
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
merge-multiple: true
|
||||
- name: Create draft release
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
draft: True
|
||||
files: |
|
||||
*.bin
|
||||
*.bin.gz
|
||||
|
||||
|
||||
testCdata:
|
||||
name: Test cdata.js
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Use Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20.x'
|
||||
cache: 'npm'
|
||||
- run: npm ci
|
||||
- run: npm test
|
||||
wled_build:
|
||||
uses: ./.github/workflows/build.yml
|
||||
|
||||
80
CHANGELOG.md
80
CHANGELOG.md
@@ -1,8 +1,86 @@
|
||||
## WLED changelog
|
||||
|
||||
#### Build 2412100
|
||||
- WLED 0.15.0 release
|
||||
- Usermod BME280: Fix "Unit of Measurement" for temperature
|
||||
- WiFi reconnect bugfix (@blazoncek)
|
||||
|
||||
#### Build 2411250
|
||||
- WLED 0.15.0-rc1 release
|
||||
- Add support for esp32S3_wroom2 (#4243 by @softhack007)
|
||||
- Fix mixed LED SK6812 and ws2812b booloop (#4301 by @willmmiles)
|
||||
- Improved FPS calculation (by DedeHai)
|
||||
- Fix crashes when using HTTP API within MQTT (#4269 by @willmmiles)
|
||||
- Fix array overflow in exploding_fireworks (#4120 by @willmmiles)
|
||||
- Fix MQTT topic buffer length (#4293 by @WouterGritter)
|
||||
- Fix SparkFunDMX fix for possible array bounds violation in DMX.write (by @softhack007)
|
||||
- Allow TV Simulator on single LED segments (by @softhack007)
|
||||
- Fix WLED_RELEASE_NAME (by @netmindz)
|
||||
|
||||
|
||||
#### Build 2410270
|
||||
- WLED 0.15.0-b7 release
|
||||
- Re-license the WLED project from MIT to EUPL (#4194 by @Aircoookie)
|
||||
- Fix alexa devices invisible/uncontrollable (#4214 by @Svennte)
|
||||
- Add visual expand button on hover (#4172)
|
||||
- Usermod: Audioreactive tuning and performance enhancements (by @softhack007)
|
||||
- `/json/live` (JSON live data/peek) only enabled when WebSockets are disabled
|
||||
- Various bugfixes and optimisations: #4179, #4215, #4219, #4222, #4223, #4224, #4228, #4230
|
||||
|
||||
#### Build 2410140
|
||||
- WLED 0.15.0-b6 release
|
||||
- Added BRT timezone (#4188 by @LuisFadini)
|
||||
- Fixed the positioning of the "Download the latest binary" button (#4184 by @maxi4329)
|
||||
- Add WLED_AUTOSEGMENTS compile flag (#4183 by @PaoloTK)
|
||||
- New 512kB FS parition map for 4MB devices
|
||||
- Internal API change: Static PinManager & UsermodManager
|
||||
- Change in Improv chip ID and version generation
|
||||
- Various optimisations, bugfixes and enhancements (#4005, #4174 & #4175 by @Xevel, #4180, #4168, #4154, #4189 by @dosipod)
|
||||
|
||||
#### Build 2409170
|
||||
- UI: Introduce common.js in settings pages (size optimisation)
|
||||
- Add the ability to toggle the reception of palette synchronizations (#4137 by @felddy)
|
||||
- Usermod/FX: Temperature usermod added Temperature effect (example usermod effect by @blazoncek)
|
||||
- Fix AsyncWebServer version pin
|
||||
|
||||
#### Build 2409140
|
||||
- Configure different kinds of busses at compile (#4107 by @PaoloTK)
|
||||
- BREAKING: removes LEDPIN and DEFAULT_LED_TYPE compile overrides
|
||||
- Fetch LED types from Bus classes (dynamic UI) (#4129 by @netmindz, @blazoncek, @dedehai)
|
||||
- Temperature usermod: update OneWire to 2.3.8 (#4131 by @iammattcoleman)
|
||||
|
||||
#### Build 2409100
|
||||
- WLED 0.15.0-b5 release
|
||||
- Audioreactive usermod included by default in all compatible builds (including ESP8266)
|
||||
- Demystified some byte definitions of WiZmote ESP-NOW message (#4114 by @ChuckMash)
|
||||
- Update usermod "Battery" improved MQTT support (#4110 by @itCarl)
|
||||
- Added a usermod for interacting with BLE Pixels Dice (#4093 by @axlan)
|
||||
- Allow lower values for touch threshold (#4081 by @RobinMeis)
|
||||
- Added POV image effect usermod (#3539 by @Liliputech)
|
||||
- Remove repeating code to fetch audio data (#4103 by @netmindz)
|
||||
- Loxone JSON parser doesn't handle lx=0 correctly (#4104 by @FreakyJ, fixes #3809)
|
||||
- Rename wled00.ino to wled_main.cpp (#4090 by @willmmiles)
|
||||
- SM16825 chip support including WW & CW channel swap (#4092)
|
||||
- Add stress testing scripts (#4088 by @willmmiles)
|
||||
- Improve jsonBufferLock management (#4089 by @willmmiles)
|
||||
- Fix incorrect PWM bit depth on Esp32 with XTAL clock (#4082 by @PaoloTK)
|
||||
- Devcontainer args (#4073 by @axlan)
|
||||
- Effect: Fire2012 optional blur amount (#4078 by @apanteleev)
|
||||
- Effect: GEQ fix bands (#4077 by @adrianschroeter)
|
||||
- Boot delay option (#4060 by @DedeHai)
|
||||
- ESP8266 Audioreactive sync (#3962 by @gaaat98, @netmindz, @softhack007)
|
||||
- ESP8266 PWM crash fix (#4035 by @willmmiles)
|
||||
- Usermod: Battery fix (#4051 by @Nickbert7)
|
||||
- Usermod: Mpu6050 usermod crash fix (#4048 by @willmmiles)
|
||||
- Usermod: Internal Temperature V2 (#4033 by @adamsthws)
|
||||
- Various fixes and improvements (including build environments to emulate 0.14.0 for ESP8266)
|
||||
|
||||
#### Build 2407070
|
||||
- Various fixes and improvements (mainly LED settings fix)
|
||||
|
||||
#### Build 2406290
|
||||
- WLED 0.15.0-b4 release
|
||||
- LED settings bus management update (WARNING only allow available outputs)
|
||||
- LED settings bus management update (WARNING: only allows available outputs)
|
||||
- Add ETH support for LILYGO-POE-Pro (#4030 by @rorosaurus)
|
||||
- Update usermod_sn_photoresistor (#4017 by @xkvmoto)
|
||||
- Several internal fixes and optimisations
|
||||
|
||||
@@ -16,6 +16,20 @@ A good description helps us to review and understand your proposed changes. For
|
||||
|
||||
Please make all PRs against the `0_15` branch.
|
||||
|
||||
### Updating your code
|
||||
While the PR is open - and under review by maintainers - you may be asked to modify your PR source code.
|
||||
You can simply update your own branch, and push changes in response to reviewer recommendations.
|
||||
Github will pick up the changes so your PR stays up-to-date.
|
||||
|
||||
> [!CAUTION]
|
||||
> Do not use "force-push" while your PR is open!
|
||||
> It has many subtle and unexpected consequences on our github reposistory.
|
||||
> For example, we regularly lost review comments when the PR author force-pushes code changes. So, pretty please, do not force-push.
|
||||
|
||||
|
||||
You can find a collection of very useful tips and tricks here: https://github.com/Aircoookie/WLED/wiki/How-to-properly-submit-a-PR
|
||||
|
||||
|
||||
### Code style
|
||||
|
||||
When in doubt, it is easiest to replicate the code style you find in the files you want to edit :)
|
||||
@@ -37,6 +51,11 @@ if (a == b) {
|
||||
}
|
||||
```
|
||||
|
||||
```cpp
|
||||
if (a == b) doStuff(a);
|
||||
```
|
||||
|
||||
Acceptable - however the first variant is usually easier to read:
|
||||
```cpp
|
||||
if (a == b)
|
||||
{
|
||||
@@ -44,9 +63,6 @@ if (a == b)
|
||||
}
|
||||
```
|
||||
|
||||
```cpp
|
||||
if (a == b) doStuff(a);
|
||||
```
|
||||
|
||||
There should always be a space between a keyword and its condition and between the condition and brace.
|
||||
Within the condition, no space should be between the parenthesis and variables.
|
||||
|
||||
307
LICENSE
307
LICENSE
@@ -1,21 +1,294 @@
|
||||
MIT License
|
||||
Copyright (c) 2016-present Christian Schwinne and individual WLED contributors
|
||||
Licensed under the EUPL v. 1.2 or later
|
||||
|
||||
Copyright (c) 2016 Christian Schwinne
|
||||
EUROPEAN UNION PUBLIC LICENCE v. 1.2
|
||||
EUPL © the European Union 2007, 2016
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
This European Union Public Licence (the ‘EUPL’) applies to the Work (as
|
||||
defined below) which is provided under the terms of this Licence. Any use of
|
||||
the Work, other than as authorised under this Licence is prohibited (to the
|
||||
extent such use is covered by a right of the copyright holder of the Work).
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
The Work is provided under the terms of this Licence when the Licensor (as
|
||||
defined below) has placed the following notice immediately following the
|
||||
copyright notice for the Work:
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Licensed under the EUPL
|
||||
|
||||
or has expressed by any other means his willingness to license under the EUPL.
|
||||
|
||||
1. Definitions
|
||||
|
||||
In this Licence, the following terms have the following meaning:
|
||||
|
||||
- ‘The Licence’: this Licence.
|
||||
|
||||
- ‘The Original Work’: the work or software distributed or communicated by the
|
||||
Licensor under this Licence, available as Source Code and also as Executable
|
||||
Code as the case may be.
|
||||
|
||||
- ‘Derivative Works’: the works or software that could be created by the
|
||||
Licensee, based upon the Original Work or modifications thereof. This
|
||||
Licence does not define the extent of modification or dependence on the
|
||||
Original Work required in order to classify a work as a Derivative Work;
|
||||
this extent is determined by copyright law applicable in the country
|
||||
mentioned in Article 15.
|
||||
|
||||
- ‘The Work’: the Original Work or its Derivative Works.
|
||||
|
||||
- ‘The Source Code’: the human-readable form of the Work which is the most
|
||||
convenient for people to study and modify.
|
||||
|
||||
- ‘The Executable Code’: any code which has generally been compiled and which
|
||||
is meant to be interpreted by a computer as a program.
|
||||
|
||||
- ‘The Licensor’: the natural or legal person that distributes or communicates
|
||||
the Work under the Licence.
|
||||
|
||||
- ‘Contributor(s)’: any natural or legal person who modifies the Work under
|
||||
the Licence, or otherwise contributes to the creation of a Derivative Work.
|
||||
|
||||
- ‘The Licensee’ or ‘You’: any natural or legal person who makes any usage of
|
||||
the Work under the terms of the Licence.
|
||||
|
||||
- ‘Distribution’ or ‘Communication’: any act of selling, giving, lending,
|
||||
renting, distributing, communicating, transmitting, or otherwise making
|
||||
available, online or offline, copies of the Work or providing access to its
|
||||
essential functionalities at the disposal of any other natural or legal
|
||||
person.
|
||||
|
||||
2. Scope of the rights granted by the Licence
|
||||
|
||||
The Licensor hereby grants You a worldwide, royalty-free, non-exclusive,
|
||||
sublicensable licence to do the following, for the duration of copyright
|
||||
vested in the Original Work:
|
||||
|
||||
- use the Work in any circumstance and for all usage,
|
||||
- reproduce the Work,
|
||||
- modify the Work, and make Derivative Works based upon the Work,
|
||||
- communicate to the public, including the right to make available or display
|
||||
the Work or copies thereof to the public and perform publicly, as the case
|
||||
may be, the Work,
|
||||
- distribute the Work or copies thereof,
|
||||
- lend and rent the Work or copies thereof,
|
||||
- sublicense rights in the Work or copies thereof.
|
||||
|
||||
Those rights can be exercised on any media, supports and formats, whether now
|
||||
known or later invented, as far as the applicable law permits so.
|
||||
|
||||
In the countries where moral rights apply, the Licensor waives his right to
|
||||
exercise his moral right to the extent allowed by law in order to make
|
||||
effective the licence of the economic rights here above listed.
|
||||
|
||||
The Licensor grants to the Licensee royalty-free, non-exclusive usage rights
|
||||
to any patents held by the Licensor, to the extent necessary to make use of
|
||||
the rights granted on the Work under this Licence.
|
||||
|
||||
3. Communication of the Source Code
|
||||
|
||||
The Licensor may provide the Work either in its Source Code form, or as
|
||||
Executable Code. If the Work is provided as Executable Code, the Licensor
|
||||
provides in addition a machine-readable copy of the Source Code of the Work
|
||||
along with each copy of the Work that the Licensor distributes or indicates,
|
||||
in a notice following the copyright notice attached to the Work, a repository
|
||||
where the Source Code is easily and freely accessible for as long as the
|
||||
Licensor continues to distribute or communicate the Work.
|
||||
|
||||
4. Limitations on copyright
|
||||
|
||||
Nothing in this Licence is intended to deprive the Licensee of the benefits
|
||||
from any exception or limitation to the exclusive rights of the rights owners
|
||||
in the Work, of the exhaustion of those rights or of other applicable
|
||||
limitations thereto.
|
||||
|
||||
5. Obligations of the Licensee
|
||||
|
||||
The grant of the rights mentioned above is subject to some restrictions and
|
||||
obligations imposed on the Licensee. Those obligations are the following:
|
||||
|
||||
Attribution right: The Licensee shall keep intact all copyright, patent or
|
||||
trademarks notices and all notices that refer to the Licence and to the
|
||||
disclaimer of warranties. The Licensee must include a copy of such notices and
|
||||
a copy of the Licence with every copy of the Work he/she distributes or
|
||||
communicates. The Licensee must cause any Derivative Work to carry prominent
|
||||
notices stating that the Work has been modified and the date of modification.
|
||||
|
||||
Copyleft clause: If the Licensee distributes or communicates copies of the
|
||||
Original Works or Derivative Works, this Distribution or Communication will be
|
||||
done under the terms of this Licence or of a later version of this Licence
|
||||
unless the Original Work is expressly distributed only under this version of
|
||||
the Licence — for example by communicating ‘EUPL v. 1.2 only’. The Licensee
|
||||
(becoming Licensor) cannot offer or impose any additional terms or conditions
|
||||
on the Work or Derivative Work that alter or restrict the terms of the
|
||||
Licence.
|
||||
|
||||
Compatibility clause: If the Licensee Distributes or Communicates Derivative
|
||||
Works or copies thereof based upon both the Work and another work licensed
|
||||
under a Compatible Licence, this Distribution or Communication can be done
|
||||
under the terms of this Compatible Licence. For the sake of this clause,
|
||||
‘Compatible Licence’ refers to the licences listed in the appendix attached to
|
||||
this Licence. Should the Licensee's obligations under the Compatible Licence
|
||||
conflict with his/her obligations under this Licence, the obligations of the
|
||||
Compatible Licence shall prevail.
|
||||
|
||||
Provision of Source Code: When distributing or communicating copies of the
|
||||
Work, the Licensee will provide a machine-readable copy of the Source Code or
|
||||
indicate a repository where this Source will be easily and freely available
|
||||
for as long as the Licensee continues to distribute or communicate the Work.
|
||||
|
||||
Legal Protection: This Licence does not grant permission to use the trade
|
||||
names, trademarks, service marks, or names of the Licensor, except as required
|
||||
for reasonable and customary use in describing the origin of the Work and
|
||||
reproducing the content of the copyright notice.
|
||||
|
||||
6. Chain of Authorship
|
||||
|
||||
The original Licensor warrants that the copyright in the Original Work granted
|
||||
hereunder is owned by him/her or licensed to him/her and that he/she has the
|
||||
power and authority to grant the Licence.
|
||||
|
||||
Each Contributor warrants that the copyright in the modifications he/she
|
||||
brings to the Work are owned by him/her or licensed to him/her and that he/she
|
||||
has the power and authority to grant the Licence.
|
||||
|
||||
Each time You accept the Licence, the original Licensor and subsequent
|
||||
Contributors grant You a licence to their contributions to the Work, under the
|
||||
terms of this Licence.
|
||||
|
||||
7. Disclaimer of Warranty
|
||||
|
||||
The Work is a work in progress, which is continuously improved by numerous
|
||||
Contributors. It is not a finished work and may therefore contain defects or
|
||||
‘bugs’ inherent to this type of development.
|
||||
|
||||
For the above reason, the Work is provided under the Licence on an ‘as is’
|
||||
basis and without warranties of any kind concerning the Work, including
|
||||
without limitation merchantability, fitness for a particular purpose, absence
|
||||
of defects or errors, accuracy, non-infringement of intellectual property
|
||||
rights other than copyright as stated in Article 6 of this Licence.
|
||||
|
||||
This disclaimer of warranty is an essential part of the Licence and a
|
||||
condition for the grant of any rights to the Work.
|
||||
|
||||
8. Disclaimer of Liability
|
||||
|
||||
Except in the cases of wilful misconduct or damages directly caused to natural
|
||||
persons, the Licensor will in no event be liable for any direct or indirect,
|
||||
material or moral, damages of any kind, arising out of the Licence or of the
|
||||
use of the Work, including without limitation, damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, loss of data or any commercial
|
||||
damage, even if the Licensor has been advised of the possibility of such
|
||||
damage. However, the Licensor will be liable under statutory product liability
|
||||
laws as far such laws apply to the Work.
|
||||
|
||||
9. Additional agreements
|
||||
|
||||
While distributing the Work, You may choose to conclude an additional
|
||||
agreement, defining obligations or services consistent with this Licence.
|
||||
However, if accepting obligations, You may act only on your own behalf and on
|
||||
your sole responsibility, not on behalf of the original Licensor or any other
|
||||
Contributor, and only if You agree to indemnify, defend, and hold each
|
||||
Contributor harmless for any liability incurred by, or claims asserted against
|
||||
such Contributor by the fact You have accepted any warranty or additional
|
||||
liability.
|
||||
|
||||
10. Acceptance of the Licence
|
||||
|
||||
The provisions of this Licence can be accepted by clicking on an icon ‘I
|
||||
agree’ placed under the bottom of a window displaying the text of this Licence
|
||||
or by affirming consent in any other similar way, in accordance with the rules
|
||||
of applicable law. Clicking on that icon indicates your clear and irrevocable
|
||||
acceptance of this Licence and all of its terms and conditions.
|
||||
|
||||
Similarly, you irrevocably accept this Licence and all of its terms and
|
||||
conditions by exercising any rights granted to You by Article 2 of this
|
||||
Licence, such as the use of the Work, the creation by You of a Derivative Work
|
||||
or the Distribution or Communication by You of the Work or copies thereof.
|
||||
|
||||
11. Information to the public
|
||||
|
||||
In case of any Distribution or Communication of the Work by means of
|
||||
electronic communication by You (for example, by offering to download the Work
|
||||
from a remote location) the distribution channel or media (for example, a
|
||||
website) must at least provide to the public the information requested by the
|
||||
applicable law regarding the Licensor, the Licence and the way it may be
|
||||
accessible, concluded, stored and reproduced by the Licensee.
|
||||
|
||||
12. Termination of the Licence
|
||||
|
||||
The Licence and the rights granted hereunder will terminate automatically upon
|
||||
any breach by the Licensee of the terms of the Licence.
|
||||
|
||||
Such a termination will not terminate the licences of any person who has
|
||||
received the Work from the Licensee under the Licence, provided such persons
|
||||
remain in full compliance with the Licence.
|
||||
|
||||
13. Miscellaneous
|
||||
|
||||
Without prejudice of Article 9 above, the Licence represents the complete
|
||||
agreement between the Parties as to the Work.
|
||||
|
||||
If any provision of the Licence is invalid or unenforceable under applicable
|
||||
law, this will not affect the validity or enforceability of the Licence as a
|
||||
whole. Such provision will be construed or reformed so as necessary to make it
|
||||
valid and enforceable.
|
||||
|
||||
The European Commission may publish other linguistic versions or new versions
|
||||
of this Licence or updated versions of the Appendix, so far this is required
|
||||
and reasonable, without reducing the scope of the rights granted by the
|
||||
Licence. New versions of the Licence will be published with a unique version
|
||||
number.
|
||||
|
||||
All linguistic versions of this Licence, approved by the European Commission,
|
||||
have identical value. Parties can take advantage of the linguistic version of
|
||||
their choice.
|
||||
|
||||
14. Jurisdiction
|
||||
|
||||
Without prejudice to specific agreement between parties,
|
||||
|
||||
- any litigation resulting from the interpretation of this License, arising
|
||||
between the European Union institutions, bodies, offices or agencies, as a
|
||||
Licensor, and any Licensee, will be subject to the jurisdiction of the Court
|
||||
of Justice of the European Union, as laid down in article 272 of the Treaty
|
||||
on the Functioning of the European Union,
|
||||
|
||||
- any litigation arising between other parties and resulting from the
|
||||
interpretation of this License, will be subject to the exclusive
|
||||
jurisdiction of the competent court where the Licensor resides or conducts
|
||||
its primary business.
|
||||
|
||||
15. Applicable Law
|
||||
|
||||
Without prejudice to specific agreement between parties,
|
||||
|
||||
- this Licence shall be governed by the law of the European Union Member State
|
||||
where the Licensor has his seat, resides or has his registered office,
|
||||
|
||||
- this licence shall be governed by Belgian law if the Licensor has no seat,
|
||||
residence or registered office inside a European Union Member State.
|
||||
|
||||
Appendix
|
||||
|
||||
‘Compatible Licences’ according to Article 5 EUPL are:
|
||||
|
||||
- GNU General Public License (GPL) v. 2, v. 3
|
||||
- GNU Affero General Public License (AGPL) v. 3
|
||||
- Open Software License (OSL) v. 2.1, v. 3.0
|
||||
- Eclipse Public License (EPL) v. 1.0
|
||||
- CeCILL v. 2.0, v. 2.1
|
||||
- Mozilla Public Licence (MPL) v. 2
|
||||
- GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3
|
||||
- Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for
|
||||
works other than software
|
||||
- European Union Public Licence (EUPL) v. 1.1, v. 1.2
|
||||
- Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong
|
||||
Reciprocity (LiLiQ-R+).
|
||||
|
||||
The European Commission may update this Appendix to later versions of the
|
||||
above licences without producing a new version of the EUPL, as long as they
|
||||
provide the rights granted in Article 2 of this Licence and protect the
|
||||
covered Source Code from exclusive appropriation.
|
||||
|
||||
All other changes or additions to this Appendix require the production of a
|
||||
new EUPL version.
|
||||
717
lib/ESP8266PWM/src/core_esp8266_waveform_pwm.cpp
Normal file
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);
|
||||
}
|
||||
|
||||
};
|
||||
128
package-lock.json
generated
128
package-lock.json
generated
@@ -1,18 +1,21 @@
|
||||
{
|
||||
"name": "wled",
|
||||
"version": "0.15.0-b4",
|
||||
"version": "0.15.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "wled",
|
||||
"version": "0.15.0-b4",
|
||||
"version": "0.15.0",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"clean-css": "^5.3.3",
|
||||
"html-minifier-terser": "^7.2.0",
|
||||
"inliner": "^1.13.1",
|
||||
"nodemon": "^3.0.2"
|
||||
"nodemon": "^3.1.7"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@jridgewell/gen-mapping": {
|
||||
@@ -54,9 +57,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@jridgewell/sourcemap-codec": {
|
||||
"version": "1.4.15",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz",
|
||||
"integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg=="
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz",
|
||||
"integrity": "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ=="
|
||||
},
|
||||
"node_modules/@jridgewell/trace-mapping": {
|
||||
"version": "0.3.25",
|
||||
@@ -67,15 +70,10 @@
|
||||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||
}
|
||||
},
|
||||
"node_modules/abbrev": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz",
|
||||
"integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q=="
|
||||
},
|
||||
"node_modules/acorn": {
|
||||
"version": "8.11.3",
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.3.tgz",
|
||||
"integrity": "sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==",
|
||||
"version": "8.12.1",
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.12.1.tgz",
|
||||
"integrity": "sha512-tcpGyI9zbizT9JbV6oYE477V6mTlXvvi0T0G3SNIYE2apm/G5huBa1+K89VGeovbg+jycCrfhl3ADxErOuO6Jg==",
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
@@ -190,9 +188,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/aws4": {
|
||||
"version": "1.12.0",
|
||||
"resolved": "https://registry.npmjs.org/aws4/-/aws4-1.12.0.tgz",
|
||||
"integrity": "sha512-NmWvPnx0F1SfrQbYwOi7OeaNGokp9XhzNioJ/CSBs8Qa4vxug81mhJEAVZwxXuBmYB5KDRfMq/F3RR0BIU7sWg=="
|
||||
"version": "1.13.2",
|
||||
"resolved": "https://registry.npmjs.org/aws4/-/aws4-1.13.2.tgz",
|
||||
"integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw=="
|
||||
},
|
||||
"node_modules/balanced-match": {
|
||||
"version": "1.0.2",
|
||||
@@ -233,11 +231,11 @@
|
||||
}
|
||||
},
|
||||
"node_modules/braces": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz",
|
||||
"integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==",
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",
|
||||
"integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",
|
||||
"dependencies": {
|
||||
"fill-range": "^7.0.1"
|
||||
"fill-range": "^7.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
@@ -701,9 +699,9 @@
|
||||
"integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw=="
|
||||
},
|
||||
"node_modules/fill-range": {
|
||||
"version": "7.0.1",
|
||||
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz",
|
||||
"integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==",
|
||||
"version": "7.1.1",
|
||||
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
|
||||
"integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",
|
||||
"dependencies": {
|
||||
"to-regex-range": "^5.0.1"
|
||||
},
|
||||
@@ -1281,17 +1279,6 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/lru-cache": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
|
||||
"integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
|
||||
"dependencies": {
|
||||
"yallist": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/mime": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
|
||||
@@ -1375,9 +1362,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/nodemon": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.0.tgz",
|
||||
"integrity": "sha512-xqlktYlDMCepBJd43ZQhjWwMw2obW/JRvkrLxq5RCNcuDDX1DbcPT+qT1IlIIdf+DhnWs90JpTMe+Y5KxOchvA==",
|
||||
"version": "3.1.7",
|
||||
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.7.tgz",
|
||||
"integrity": "sha512-hLj7fuMow6f0lbB0cD14Lz2xNjwsyruH251Pk4t/yIitCFJbmY1myuLlHm/q06aST4jg6EgAh74PIBBrRqpVAQ==",
|
||||
"dependencies": {
|
||||
"chokidar": "^3.5.2",
|
||||
"debug": "^4",
|
||||
@@ -1402,11 +1389,11 @@
|
||||
}
|
||||
},
|
||||
"node_modules/nodemon/node_modules/debug": {
|
||||
"version": "4.3.4",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz",
|
||||
"integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==",
|
||||
"version": "4.3.7",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz",
|
||||
"integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==",
|
||||
"dependencies": {
|
||||
"ms": "2.1.2"
|
||||
"ms": "^2.1.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0"
|
||||
@@ -1418,9 +1405,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/nodemon/node_modules/ms": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
|
||||
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
|
||||
},
|
||||
"node_modules/nodemon/node_modules/supports-color": {
|
||||
"version": "5.5.0",
|
||||
@@ -1433,20 +1420,6 @@
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/nopt": {
|
||||
"version": "1.0.10",
|
||||
"resolved": "https://registry.npmjs.org/nopt/-/nopt-1.0.10.tgz",
|
||||
"integrity": "sha512-NWmpvLSqUrgrAC9HCuxEvb+PSloHpqVu+FqcO4eeF2h5qYRhA7ev6KvelyQAKtegUbC6RypJnlEOhd8vloNKYg==",
|
||||
"dependencies": {
|
||||
"abbrev": "1"
|
||||
},
|
||||
"bin": {
|
||||
"nopt": "bin/nopt.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/normalize-path": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
|
||||
@@ -1507,6 +1480,7 @@
|
||||
"version": "0.1.5",
|
||||
"resolved": "https://registry.npmjs.org/osenv/-/osenv-0.1.5.tgz",
|
||||
"integrity": "sha512-0CWcCECdMVc2Rw3U5w9ZjqX6ga6ubk1xDVKxtBQPK7wis/0F2r9T6k4ydGYhecl7YUBxBVxhL5oisPsNxAPe2g==",
|
||||
"deprecated": "This package is no longer supported.",
|
||||
"dependencies": {
|
||||
"os-homedir": "^1.0.0",
|
||||
"os-tmpdir": "^1.0.0"
|
||||
@@ -1620,6 +1594,7 @@
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/q/-/q-1.5.1.tgz",
|
||||
"integrity": "sha512-kV/CThkXo6xyFEZUugw/+pIOywXcDbFYgSct5cT3gqlbkBE1SJdwy6UQoZvodiWF/ckQLZyDE/Bu1M6gVu5lVw==",
|
||||
"deprecated": "You or someone you depend on is using Q, the JavaScript Promise library that gave JavaScript developers strong feelings about promises. They can almost certainly migrate to the native JavaScript promise now. Thank you literally everyone for joining me in this bet against the odds. Be excellent to each other.\n\n(For a CapTP with native promises, see @endo/eventual-send and @endo/captp)",
|
||||
"engines": {
|
||||
"node": ">=0.6.0",
|
||||
"teleport": ">=0.2.0"
|
||||
@@ -1826,12 +1801,9 @@
|
||||
"integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw=="
|
||||
},
|
||||
"node_modules/semver": {
|
||||
"version": "7.6.0",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.6.0.tgz",
|
||||
"integrity": "sha512-EnwXhrlwXMk9gKu5/flx5sv/an57AkRplG3hTK68W7FRDN+k+OWBj65M7719OkA82XLBxrcX0KSHj+X5COhOVg==",
|
||||
"dependencies": {
|
||||
"lru-cache": "^6.0.0"
|
||||
},
|
||||
"version": "7.6.3",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz",
|
||||
"integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==",
|
||||
"bin": {
|
||||
"semver": "bin/semver.js"
|
||||
},
|
||||
@@ -1993,9 +1965,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/terser": {
|
||||
"version": "5.29.2",
|
||||
"resolved": "https://registry.npmjs.org/terser/-/terser-5.29.2.tgz",
|
||||
"integrity": "sha512-ZiGkhUBIM+7LwkNjXYJq8svgkd+QK3UUr0wJqY4MieaezBSAIPgbSPZyIx0idM6XWK5CMzSWa8MJIzmRcB8Caw==",
|
||||
"version": "5.34.0",
|
||||
"resolved": "https://registry.npmjs.org/terser/-/terser-5.34.0.tgz",
|
||||
"integrity": "sha512-y5NUX+U9HhVsK/zihZwoq4r9dICLyV2jXGOriDAVOeKhq3LKVjgJbGO90FisozXLlJfvjHqgckGmJFBb9KYoWQ==",
|
||||
"dependencies": {
|
||||
"@jridgewell/source-map": "^0.3.3",
|
||||
"acorn": "^8.8.2",
|
||||
@@ -2042,12 +2014,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/touch": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/touch/-/touch-3.1.0.tgz",
|
||||
"integrity": "sha512-WBx8Uy5TLtOSRtIq+M03/sKDrXCLHxwDcquSP2c43Le03/9serjQBIztjRz6FkJez9D/hleyAXTBGLwwZUw9lA==",
|
||||
"dependencies": {
|
||||
"nopt": "~1.0.10"
|
||||
},
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/touch/-/touch-3.1.1.tgz",
|
||||
"integrity": "sha512-r0eojU4bI8MnHr8c5bNo7lJDdI2qXlWWJk6a9EAFG7vbhTjElYhBVS3/miuE0uOuoLdb8Mc/rVfsmm6eo5o9GA==",
|
||||
"bin": {
|
||||
"nodetouch": "bin/nodetouch.js"
|
||||
}
|
||||
@@ -2065,9 +2034,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/tslib": {
|
||||
"version": "2.6.2",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz",
|
||||
"integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q=="
|
||||
"version": "2.7.0",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz",
|
||||
"integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA=="
|
||||
},
|
||||
"node_modules/tunnel-agent": {
|
||||
"version": "0.6.0",
|
||||
@@ -2229,11 +2198,6 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/yallist": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
|
||||
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="
|
||||
},
|
||||
"node_modules/yargs": {
|
||||
"version": "3.10.0",
|
||||
"resolved": "https://registry.npmjs.org/yargs/-/yargs-3.10.0.tgz",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "wled",
|
||||
"version": "0.15.0-b4",
|
||||
"version": "0.15.1.beta1",
|
||||
"description": "Tools for WLED project",
|
||||
"main": "tools/cdata.js",
|
||||
"directories": {
|
||||
@@ -26,6 +26,9 @@
|
||||
"clean-css": "^5.3.3",
|
||||
"html-minifier-terser": "^7.2.0",
|
||||
"inliner": "^1.13.1",
|
||||
"nodemon": "^3.0.2"
|
||||
"nodemon": "^3.1.7"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,21 @@
|
||||
Import('env')
|
||||
Import("env")
|
||||
import shutil
|
||||
|
||||
env.Execute("npm run build")
|
||||
node_ex = shutil.which("node")
|
||||
# Check if Node.js is installed and present in PATH if it failed, abort the build
|
||||
if node_ex is None:
|
||||
print('\x1b[0;31;43m' + 'Node.js is not installed or missing from PATH html css js will not be processed check https://kno.wled.ge/advanced/compiling-wled/' + '\x1b[0m')
|
||||
exitCode = env.Execute("null")
|
||||
exit(exitCode)
|
||||
else:
|
||||
# Install the necessary node packages for the pre-build asset bundling script
|
||||
print('\x1b[6;33;42m' + 'Installing node packages' + '\x1b[0m')
|
||||
env.Execute("npm install")
|
||||
|
||||
# Call the bundling script
|
||||
exitCode = env.Execute("npm run build")
|
||||
|
||||
# If it failed, abort the build
|
||||
if (exitCode):
|
||||
print('\x1b[0;31;43m' + 'npm run build fails check https://kno.wled.ge/advanced/compiling-wled/' + '\x1b[0m')
|
||||
exit(exitCode)
|
||||
@@ -19,8 +19,9 @@ def _create_dirs(dirs=["map", "release", "firmware"]):
|
||||
os.makedirs(os.path.join(OUTPUT_DIR, d), exist_ok=True)
|
||||
|
||||
def create_release(source):
|
||||
release_name = _get_cpp_define_value(env, "WLED_RELEASE_NAME")
|
||||
if release_name:
|
||||
release_name_def = _get_cpp_define_value(env, "WLED_RELEASE_NAME")
|
||||
if release_name_def:
|
||||
release_name = release_name_def.replace("\\\"", "")
|
||||
version = _get_cpp_define_value(env, "WLED_VERSION")
|
||||
release_file = os.path.join(OUTPUT_DIR, "release", f"WLED_{version}_{release_name}.bin")
|
||||
release_gz_file = release_file + ".gz"
|
||||
|
||||
187
platformio.ini
187
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
|
||||
@@ -140,7 +140,7 @@ lib_deps =
|
||||
IRremoteESP8266 @ 2.8.2
|
||||
makuna/NeoPixelBus @ 2.8.0
|
||||
#https://github.com/makuna/NeoPixelBus.git#CoreShaderBeta
|
||||
https://github.com/Aircoookie/ESPAsyncWebServer.git @ 2.2.1
|
||||
https://github.com/Aircoookie/ESPAsyncWebServer.git#v2.2.1
|
||||
# for I2C interface
|
||||
;Wire
|
||||
# ESP-NOW library
|
||||
@@ -176,6 +176,7 @@ lib_deps =
|
||||
extra_scripts = ${scripts_defaults.extra_scripts}
|
||||
|
||||
[esp8266]
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags =
|
||||
-DESP8266
|
||||
-DFP_IN_IROM
|
||||
@@ -197,17 +198,52 @@ build_flags =
|
||||
; decrease code cache size and increase IRAM to fit all pixel functions
|
||||
-D PIO_FRAMEWORK_ARDUINO_MMU_CACHE16_IRAM48 ;; in case of linker errors like "section `.text1' will not fit in region `iram1_0_seg'"
|
||||
; -D PIO_FRAMEWORK_ARDUINO_MMU_CACHE16_IRAM48_SECHEAP_SHARED ;; (experimental) adds some extra heap, but may cause slowdown
|
||||
-D NON32XFER_HANDLER ;; ask forgiveness for PROGMEM misuse
|
||||
|
||||
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#v2.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
|
||||
platform_packages = framework-arduinoespressif32 @ https://github.com/Aircoookie/arduino-esp32.git#1.0.6.4
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = -g
|
||||
-DARDUINO_ARCH_ESP32
|
||||
#-DCONFIG_LITTLEFS_FOR_IDF_3_2
|
||||
@@ -226,8 +262,10 @@ lib_deps =
|
||||
https://github.com/pbolduc/AsyncTCP.git @ 1.2.0
|
||||
${env.lib_deps}
|
||||
# additional build flags for audioreactive
|
||||
AR_build_flags = -D USERMOD_AUDIOREACTIVE
|
||||
AR_build_flags = -D USERMOD_AUDIOREACTIVE
|
||||
-D sqrt_internal=sqrtf ;; -fsingle-precision-constant ;; forces ArduinoFFT to use float math (2x faster)
|
||||
AR_lib_deps = kosme/arduinoFFT @ 2.0.1
|
||||
board_build.partitions = ${esp32.default_partitions} ;; default partioning for 4MB Flash - can be overridden in build envs
|
||||
|
||||
[esp32_idf_V4]
|
||||
;; experimental build environment for ESP32 using ESP-IDF 4.4.x / arduino-esp32 v2.0.5
|
||||
@@ -237,6 +275,7 @@ AR_lib_deps = kosme/arduinoFFT @ 2.0.1
|
||||
;; You need to completely erase your device (esptool erase_flash) first, then install the "V4" build from VSCode+platformio.
|
||||
platform = espressif32@ ~6.3.2
|
||||
platform_packages = platformio/framework-arduinoespressif32 @ 3.20009.0 ;; select arduino-esp32 v2.0.9 (arduino-esp32 2.0.10 thru 2.0.14 are buggy so avoid them)
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = -g
|
||||
-Wshadow=compatible-local ;; emit warning in case a local variable "shadows" another local one
|
||||
-DARDUINO_ARCH_ESP32 -DESP32
|
||||
@@ -245,11 +284,13 @@ build_flags = -g
|
||||
lib_deps =
|
||||
https://github.com/pbolduc/AsyncTCP.git @ 1.2.0
|
||||
${env.lib_deps}
|
||||
board_build.partitions = ${esp32.default_partitions} ;; default partioning for 4MB Flash - can be overridden in build envs
|
||||
|
||||
[esp32s2]
|
||||
;; generic definitions for all ESP32-S2 boards
|
||||
platform = espressif32@ ~6.3.2
|
||||
platform_packages = platformio/framework-arduinoespressif32 @ 3.20009.0 ;; select arduino-esp32 v2.0.9 (arduino-esp32 2.0.10 thru 2.0.14 are buggy so avoid them)
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = -g
|
||||
-DARDUINO_ARCH_ESP32
|
||||
-DARDUINO_ARCH_ESP32S2
|
||||
@@ -263,11 +304,13 @@ build_flags = -g
|
||||
lib_deps =
|
||||
https://github.com/pbolduc/AsyncTCP.git @ 1.2.0
|
||||
${env.lib_deps}
|
||||
board_build.partitions = ${esp32.default_partitions} ;; default partioning for 4MB Flash - can be overridden in build envs
|
||||
|
||||
[esp32c3]
|
||||
;; generic definitions for all ESP32-C3 boards
|
||||
platform = espressif32@ ~6.3.2
|
||||
platform_packages = platformio/framework-arduinoespressif32 @ 3.20009.0 ;; select arduino-esp32 v2.0.9 (arduino-esp32 2.0.10 thru 2.0.14 are buggy so avoid them)
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = -g
|
||||
-DARDUINO_ARCH_ESP32
|
||||
-DARDUINO_ARCH_ESP32C3
|
||||
@@ -280,11 +323,13 @@ build_flags = -g
|
||||
lib_deps =
|
||||
https://github.com/pbolduc/AsyncTCP.git @ 1.2.0
|
||||
${env.lib_deps}
|
||||
board_build.partitions = ${esp32.default_partitions} ;; default partioning for 4MB Flash - can be overridden in build envs
|
||||
|
||||
[esp32s3]
|
||||
;; generic definitions for all ESP32-S3 boards
|
||||
platform = espressif32@ ~6.3.2
|
||||
platform_packages = platformio/framework-arduinoespressif32 @ 3.20009.0 ;; select arduino-esp32 v2.0.9 (arduino-esp32 2.0.10 thru 2.0.14 are buggy so avoid them)
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = -g
|
||||
-DESP32
|
||||
-DARDUINO_ARCH_ESP32
|
||||
@@ -298,6 +343,7 @@ build_flags = -g
|
||||
lib_deps =
|
||||
https://github.com/pbolduc/AsyncTCP.git @ 1.2.0
|
||||
${env.lib_deps}
|
||||
board_build.partitions = ${esp32.large_partitions} ;; default partioning for 8MB flash - can be overridden in build envs
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
@@ -310,14 +356,23 @@ platform = ${common.platform_wled_default}
|
||||
platform_packages = ${common.platform_packages}
|
||||
board_build.ldscript = ${common.ldscript_4m1m}
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D WLED_RELEASE_NAME=ESP8266 #-DWLED_DISABLE_2D
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D WLED_RELEASE_NAME=\"ESP8266\" #-DWLED_DISABLE_2D
|
||||
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
|
||||
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
|
||||
@@ -325,13 +380,21 @@ platform = ${common.platform_wled_default}
|
||||
platform_packages = ${common.platform_packages}
|
||||
board_build.ldscript = ${common.ldscript_2m512k}
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D WLED_RELEASE_NAME=ESP02
|
||||
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
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D WLED_RELEASE_NAME=\"ESP02_160\"
|
||||
-D USERMOD_AUDIOREACTIVE
|
||||
|
||||
[env:esp01_1m_full]
|
||||
board = esp01_1m
|
||||
@@ -339,14 +402,22 @@ platform = ${common.platform_wled_default}
|
||||
platform_packages = ${common.platform_packages}
|
||||
board_build.ldscript = ${common.ldscript_1m128k}
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D WLED_RELEASE_NAME=ESP01 -D WLED_DISABLE_OTA
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D WLED_RELEASE_NAME=\"ESP01\" -D WLED_DISABLE_OTA
|
||||
; -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
|
||||
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,8 +425,10 @@ 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 #-D WLED_DISABLE_BROWNOUT_DET
|
||||
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}
|
||||
|
||||
@@ -364,27 +437,46 @@ board = esp32dev
|
||||
platform = ${esp32_idf_V4.platform}
|
||||
platform_packages = ${esp32_idf_V4.platform_packages}
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp32_idf_V4.build_flags} -D WLED_RELEASE_NAME=ESP32_8M #-D WLED_DISABLE_BROWNOUT_DET
|
||||
build_flags = ${common.build_flags} ${esp32_idf_V4.build_flags} -D WLED_RELEASE_NAME=\"ESP32_8M\" #-D WLED_DISABLE_BROWNOUT_DET
|
||||
${esp32.AR_build_flags}
|
||||
lib_deps = ${esp32_idf_V4.lib_deps}
|
||||
${esp32.AR_lib_deps}
|
||||
monitor_filters = esp32_exception_decoder
|
||||
board_build.partitions = ${esp32.large_partitions}
|
||||
board_upload.flash_size = 8MB
|
||||
board_upload.maximum_size = 8388608
|
||||
; board_build.f_flash = 80000000L
|
||||
; board_build.flash_mode = qio
|
||||
|
||||
[env:esp32dev_audioreactive]
|
||||
[env:esp32dev_16M]
|
||||
board = esp32dev
|
||||
platform = ${esp32.platform}
|
||||
platform_packages = ${esp32.platform_packages}
|
||||
platform = ${esp32_idf_V4.platform}
|
||||
platform_packages = ${esp32_idf_V4.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
|
||||
build_flags = ${common.build_flags} ${esp32_idf_V4.build_flags} -D WLED_RELEASE_NAME=\"ESP32_16M\" #-D WLED_DISABLE_BROWNOUT_DET
|
||||
${esp32.AR_build_flags}
|
||||
lib_deps = ${esp32.lib_deps}
|
||||
lib_deps = ${esp32_idf_V4.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
|
||||
board_build.partitions = ${esp32.extreme_partitions}
|
||||
board_upload.flash_size = 16MB
|
||||
board_upload.maximum_size = 16777216
|
||||
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,9 +484,11 @@ platform = ${esp32.platform}
|
||||
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
|
||||
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
|
||||
${esp32.AR_build_flags}
|
||||
lib_deps = ${esp32.lib_deps}
|
||||
${esp32.AR_lib_deps}
|
||||
board_build.partitions = ${esp32.default_partitions}
|
||||
|
||||
[env:esp32_wrover]
|
||||
@@ -404,14 +498,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
|
||||
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}
|
||||
-D DATA_PINS=25
|
||||
${esp32.AR_build_flags}
|
||||
lib_deps = ${esp32_idf_V4.lib_deps}
|
||||
; ${esp32.AR_lib_deps}
|
||||
${esp32.AR_lib_deps}
|
||||
|
||||
[env:esp32c3dev]
|
||||
extends = esp32c3
|
||||
@@ -420,7 +514,7 @@ platform_packages = ${esp32c3.platform_packages}
|
||||
framework = arduino
|
||||
board = esp32-c3-devkitm-1
|
||||
board_build.partitions = ${esp32.default_partitions}
|
||||
build_flags = ${common.build_flags} ${esp32c3.build_flags} -D WLED_RELEASE_NAME=ESP32-C3
|
||||
build_flags = ${common.build_flags} ${esp32c3.build_flags} -D WLED_RELEASE_NAME=\"ESP32-C3\"
|
||||
-D WLED_WATCHDOG_TIMEOUT=0
|
||||
-DLOLIN_WIFI_FIX ; seems to work much better with this
|
||||
-DARDUINO_USB_CDC_ON_BOOT=1 ;; for virtual CDC USB
|
||||
@@ -437,7 +531,7 @@ platform = ${esp32s3.platform}
|
||||
platform_packages = ${esp32s3.platform_packages}
|
||||
upload_speed = 921600
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp32s3.build_flags} -D WLED_RELEASE_NAME=ESP32-S3_16MB_opi
|
||||
build_flags = ${common.build_flags} ${esp32s3.build_flags} -D WLED_RELEASE_NAME=\"ESP32-S3_16MB_opi\"
|
||||
-D CONFIG_LITTLEFS_FOR_IDF_3_2 -D WLED_WATCHDOG_TIMEOUT=0
|
||||
;-D ARDUINO_USB_CDC_ON_BOOT=0 ;; -D ARDUINO_USB_MODE=1 ;; for boards with serial-to-USB chip
|
||||
-D ARDUINO_USB_CDC_ON_BOOT=1 -D ARDUINO_USB_MODE=1 ;; for boards with USB-OTG connector only (USBCDC or "TinyUSB")
|
||||
@@ -446,6 +540,8 @@ build_flags = ${common.build_flags} ${esp32s3.build_flags} -D WLED_RELEASE_NAME=
|
||||
lib_deps = ${esp32s3.lib_deps}
|
||||
${esp32.AR_lib_deps}
|
||||
board_build.partitions = ${esp32.extreme_partitions}
|
||||
board_upload.flash_size = 16MB
|
||||
board_upload.maximum_size = 16777216
|
||||
board_build.f_flash = 80000000L
|
||||
board_build.flash_mode = qio
|
||||
monitor_filters = esp32_exception_decoder
|
||||
@@ -458,7 +554,7 @@ platform = ${esp32s3.platform}
|
||||
platform_packages = ${esp32s3.platform_packages}
|
||||
upload_speed = 921600
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp32s3.build_flags} -D WLED_RELEASE_NAME=ESP32-S3_8MB_opi
|
||||
build_flags = ${common.build_flags} ${esp32s3.build_flags} -D WLED_RELEASE_NAME=\"ESP32-S3_8MB_opi\"
|
||||
-D CONFIG_LITTLEFS_FOR_IDF_3_2 -D WLED_WATCHDOG_TIMEOUT=0
|
||||
;-D ARDUINO_USB_CDC_ON_BOOT=0 ;; -D ARDUINO_USB_MODE=1 ;; for boards with serial-to-USB chip
|
||||
-D ARDUINO_USB_CDC_ON_BOOT=1 -D ARDUINO_USB_MODE=1 ;; for boards with USB-OTG connector only (USBCDC or "TinyUSB")
|
||||
@@ -471,6 +567,33 @@ board_build.f_flash = 80000000L
|
||||
board_build.flash_mode = qio
|
||||
monitor_filters = esp32_exception_decoder
|
||||
|
||||
[env:esp32S3_wroom2]
|
||||
;; For ESP32-S3 WROOM-2, a.k.a. ESP32-S3 DevKitC-1 v1.1
|
||||
;; with >= 16MB FLASH and >= 8MB PSRAM (memory_type: opi_opi)
|
||||
platform = ${esp32s3.platform}
|
||||
platform_packages = ${esp32s3.platform_packages}
|
||||
board = esp32s3camlcd ;; this is the only standard board with "opi_opi"
|
||||
board_build.arduino.memory_type = opi_opi
|
||||
upload_speed = 921600
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp32s3.build_flags} -D WLED_RELEASE_NAME=\"ESP32-S3_WROOM-2\"
|
||||
-D CONFIG_LITTLEFS_FOR_IDF_3_2 -D WLED_WATCHDOG_TIMEOUT=0
|
||||
-D ARDUINO_USB_CDC_ON_BOOT=0 ;; -D ARDUINO_USB_MODE=1 ;; for boards with serial-to-USB chip
|
||||
;; -D ARDUINO_USB_CDC_ON_BOOT=1 -D ARDUINO_USB_MODE=1 ;; for boards with USB-OTG connector only (USBCDC or "TinyUSB")
|
||||
-DBOARD_HAS_PSRAM
|
||||
-D LEDPIN=38 -D DATA_PINS=38 ;; buildin WS2812b LED
|
||||
-D BTNPIN=0 -D RLYPIN=16 -D IRPIN=17 -D AUDIOPIN=-1
|
||||
-D WLED_DEBUG
|
||||
${esp32.AR_build_flags}
|
||||
-D SR_DMTYPE=1 -D I2S_SDPIN=13 -D I2S_CKPIN=14 -D I2S_WSPIN=15 -D MCLK_PIN=4 ;; I2S mic
|
||||
lib_deps = ${esp32s3.lib_deps}
|
||||
${esp32.AR_lib_deps}
|
||||
|
||||
board_build.partitions = ${esp32.extreme_partitions}
|
||||
board_upload.flash_size = 16MB
|
||||
board_upload.maximum_size = 16777216
|
||||
monitor_filters = esp32_exception_decoder
|
||||
|
||||
[env:esp32s3_4M_qspi]
|
||||
;; ESP32-S3, with 4MB FLASH and <= 4MB PSRAM (memory_type: qio_qspi)
|
||||
board = lolin_s3_mini ;; -S3 mini, 4MB flash 2MB PSRAM
|
||||
@@ -478,7 +601,7 @@ platform = ${esp32s3.platform}
|
||||
platform_packages = ${esp32s3.platform_packages}
|
||||
upload_speed = 921600
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp32s3.build_flags} -D WLED_RELEASE_NAME=ESP32-S3_4M_qspi
|
||||
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
|
||||
@@ -499,7 +622,7 @@ board_build.partitions = ${esp32.default_partitions}
|
||||
board_build.flash_mode = qio
|
||||
board_build.f_flash = 80000000L
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp32s2.build_flags} -D WLED_RELEASE_NAME=ESP32-S2
|
||||
build_flags = ${common.build_flags} ${esp32s2.build_flags} -D WLED_RELEASE_NAME=\"ESP32-S2\"
|
||||
-DARDUINO_USB_CDC_ON_BOOT=1
|
||||
-DARDUINO_USB_MSC_ON_BOOT=0
|
||||
-DARDUINO_USB_DFU_ON_BOOT=0
|
||||
@@ -507,7 +630,7 @@ build_flags = ${common.build_flags} ${esp32s2.build_flags} -D WLED_RELEASE_NAME=
|
||||
-DLOLIN_WIFI_FIX ; seems to work much better with this
|
||||
-D WLED_WATCHDOG_TIMEOUT=0
|
||||
-D CONFIG_ASYNC_TCP_USE_WDT=0
|
||||
-D LEDPIN=16
|
||||
-D DATA_PINS=16
|
||||
-D HW_PIN_SCL=35
|
||||
-D HW_PIN_SDA=33
|
||||
-D HW_PIN_CLOCKSPI=7
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
# Please visit documentation: https://docs.platformio.org/page/projectconf.html
|
||||
|
||||
[platformio]
|
||||
default_envs = WLED_tasmota_1M # define as many as you need
|
||||
default_envs = WLED_generic8266_1M, esp32dev_V4_dio80 # put the name(s) of your own build environment here. You can define as many as you need
|
||||
|
||||
#----------
|
||||
# SAMPLE
|
||||
@@ -28,14 +28,16 @@ lib_deps = ${esp8266.lib_deps}
|
||||
; robtillaart/SHT85@~0.3.3
|
||||
; ;gmag11/QuickESPNow @ ~0.7.0 # will also load QuickDebug
|
||||
; https://github.com/blazoncek/QuickESPNow.git#optional-debug ;; exludes debug library
|
||||
; ${esp32.AR_lib_deps} ;; used for USERMOD_AUDIOREACTIVE
|
||||
; bitbank2/PNGdec@^1.0.1 ;; used for POV display uncomment following
|
||||
; ${esp32.AR_lib_deps} ;; needed for USERMOD_AUDIOREACTIVE
|
||||
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags}
|
||||
;
|
||||
; *** To use the below defines/overrides, copy and paste each onto it's own line just below build_flags in the section above.
|
||||
;
|
||||
; Set a release name that may be used to distinguish required binary for flashing
|
||||
; -D WLED_RELEASE_NAME=ESP32_MULTI_USREMODS
|
||||
; -D WLED_RELEASE_NAME=\"ESP32_MULTI_USREMODS\"
|
||||
;
|
||||
; disable specific features
|
||||
; -D WLED_DISABLE_OTA
|
||||
@@ -57,7 +59,7 @@ build_flags = ${common.build_flags} ${esp8266.build_flags}
|
||||
; -D WLED_ENABLE_DMX
|
||||
;
|
||||
; PIN defines - uncomment and change, if needed:
|
||||
; -D LEDPIN=2
|
||||
; -D DATA_PINS=2
|
||||
; or use this for multiple outputs
|
||||
; -D DATA_PINS=1,3
|
||||
; -D BTNPIN=0
|
||||
@@ -109,7 +111,6 @@ build_flags = ${common.build_flags} ${esp8266.build_flags}
|
||||
;
|
||||
; Use 4 Line Display usermod with SPI display
|
||||
; -D USERMOD_FOUR_LINE_DISPLAY
|
||||
; -D USE_ALT_DISPlAY # mandatory
|
||||
; -DFLD_SPI_DEFAULT
|
||||
; -D FLD_TYPE=SSD1306_SPI64
|
||||
; -D FLD_PIN_CLOCKSPI=14
|
||||
@@ -140,7 +141,8 @@ build_flags = ${common.build_flags} ${esp8266.build_flags}
|
||||
; -D PIR_SENSOR_MAX_SENSORS=2 # max allowable sensors (uses OR logic for triggering)
|
||||
;
|
||||
; Use Audioreactive usermod and configure I2S microphone
|
||||
; -D USERMOD_AUDIOREACTIVE
|
||||
; ${esp32.AR_build_flags} ;; default flags required to properly configure ArduinoFFT
|
||||
; ;; don't forget to add ArduinoFFT to your libs_deps: ${esp32.AR_lib_deps}
|
||||
; -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
|
||||
@@ -152,19 +154,26 @@ 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
|
||||
;
|
||||
;
|
||||
; set the name of the module - make sure there is a quote-backslash-quote before the name and a backslash-quote-quote after the name
|
||||
; -D SERVERNAME="\"WLED\""
|
||||
;
|
||||
;
|
||||
; set the number of LEDs
|
||||
; -D DEFAULT_LED_COUNT=30
|
||||
; -D PIXEL_COUNTS=30
|
||||
; or this for multiple outputs
|
||||
; -D PIXEL_COUNTS=30,30
|
||||
;
|
||||
; set the default LED type
|
||||
; -D DEFAULT_LED_TYPE=22 # see const.h (TYPE_xxxx)
|
||||
; -D LED_TYPES=22 # see const.h (TYPE_xxxx)
|
||||
; or this for multiple outputs
|
||||
; -D LED_TYPES=TYPE_SK6812_RGBW,TYPE_WS2812_RGB
|
||||
;
|
||||
; set default color order of your led strip
|
||||
; -D DEFAULT_LED_COLOR_ORDER=COL_ORDER_GRB
|
||||
;
|
||||
; set milliampere limit when using ESP power pin (or inadequate PSU) to power LEDs
|
||||
; -D ABL_MILLIAMPS_DEFAULT=850
|
||||
@@ -173,9 +182,6 @@ build_flags = ${common.build_flags} ${esp8266.build_flags}
|
||||
; 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
|
||||
;
|
||||
; 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 # needed only for classic ESP32 rev.1
|
||||
;
|
||||
@@ -229,18 +235,17 @@ platform = ${common.platform_wled_default}
|
||||
platform_packages = ${common.platform_packages}
|
||||
board_build.ldscript = ${common.ldscript_4m1m}
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D LEDPIN=1 -D WLED_DISABLE_INFRARED
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D DATA_PINS=1 -D WLED_DISABLE_INFRARED
|
||||
lib_deps = ${esp8266.lib_deps}
|
||||
|
||||
[env:esp32dev_qio80]
|
||||
extends = env:esp32dev # we want to extend the existing esp32dev environment (and define only updated options)
|
||||
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_DISABLE_BROWNOUT_DET
|
||||
${esp32.AR_build_flags} ;; optional - includes USERMOD_AUDIOREACTIVE
|
||||
lib_deps = ${esp32.lib_deps}
|
||||
${esp32.AR_lib_deps} ;; needed for USERMOD_AUDIOREACTIVE
|
||||
monitor_filters = esp32_exception_decoder
|
||||
board_build.partitions = ${esp32.default_partitions}
|
||||
board_build.f_flash = 80000000L
|
||||
board_build.flash_mode = qio
|
||||
|
||||
@@ -248,26 +253,25 @@ board_build.flash_mode = qio
|
||||
;; experimental ESP32 env using ESP-IDF V4.4.x
|
||||
;; Warning: this build environment is not stable!!
|
||||
;; please erase your device before installing.
|
||||
extends = esp32_idf_V4 # based on newer "esp-idf V4" platform environment
|
||||
board = esp32dev
|
||||
platform = ${esp32_idf_V4.platform}
|
||||
platform_packages = ${esp32_idf_V4.platform_packages}
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp32_idf_V4.build_flags} #-D WLED_DISABLE_BROWNOUT_DET
|
||||
${esp32.AR_build_flags} ;; includes USERMOD_AUDIOREACTIVE
|
||||
lib_deps = ${esp32_idf_V4.lib_deps}
|
||||
${esp32.AR_lib_deps} ;; needed for USERMOD_AUDIOREACTIVE
|
||||
monitor_filters = esp32_exception_decoder
|
||||
board_build.partitions = ${esp32_idf_V4.default_partitions}
|
||||
board_build.partitions = ${esp32.default_partitions} ;; if you get errors about "out of program space", change this to ${esp32.extended_partitions} or even ${esp32.big_partitions}
|
||||
board_build.f_flash = 80000000L
|
||||
board_build.flash_mode = dio
|
||||
|
||||
[env:esp32s2_saola]
|
||||
extends = esp32s2
|
||||
board = esp32-s2-saola-1
|
||||
platform = ${esp32s2.platform}
|
||||
platform_packages = ${esp32s2.platform_packages}
|
||||
framework = arduino
|
||||
board_build.partitions = tools/WLED_ESP32_4MB_1MB_FS.csv
|
||||
board_build.flash_mode = qio
|
||||
upload_speed = 460800
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp32s2.build_flags}
|
||||
;-DLOLIN_WIFI_FIX ;; try this in case Wifi does not work
|
||||
-DARDUINO_USB_CDC_ON_BOOT=1
|
||||
@@ -304,7 +308,7 @@ platform = ${common.platform_wled_default}
|
||||
platform_packages = ${common.platform_packages}
|
||||
board_build.ldscript = ${common.ldscript_4m1m}
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D WLED_USE_SHOJO_PCB
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D WLED_USE_SHOJO_PCB ;; NB: WLED_USE_SHOJO_PCB is not used anywhere in the source code. Not sure why its needed.
|
||||
lib_deps = ${esp8266.lib_deps}
|
||||
|
||||
[env:d1_mini_debug]
|
||||
@@ -335,7 +339,7 @@ platform = ${common.platform_wled_default}
|
||||
platform_packages = ${common.platform_packages}
|
||||
board_build.ldscript = ${common.ldscript_4m1m}
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D LEDPIN=12 -D IRPIN=-1 -D RLYPIN=2
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D DATA_PINS=12 -D IRPIN=-1 -D RLYPIN=2
|
||||
lib_deps = ${esp8266.lib_deps}
|
||||
|
||||
[env:esp32c3dev_2MB]
|
||||
@@ -355,51 +359,65 @@ upload_speed = 115200
|
||||
lib_deps = ${esp32c3.lib_deps}
|
||||
board_build.partitions = tools/WLED_ESP32_2MB_noOTA.csv
|
||||
board_build.flash_mode = dio
|
||||
board_upload.flash_size = 2MB
|
||||
board_upload.maximum_size = 2097152
|
||||
|
||||
[env:wemos_shield_esp32]
|
||||
extends = esp32 ;; use default esp32 platform
|
||||
board = esp32dev
|
||||
platform = ${esp32.platform}
|
||||
platform_packages = ${esp32.platform_packages}
|
||||
upload_speed = 460800
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp32.build_flags}
|
||||
-D LEDPIN=16
|
||||
-D WLED_RELEASE_NAME=\"ESP32_wemos_shield\"
|
||||
-D DATA_PINS=16
|
||||
-D RLYPIN=19
|
||||
-D BTNPIN=17
|
||||
-D IRPIN=18
|
||||
-D UWLED_USE_MY_CONFIG
|
||||
-UWLED_USE_MY_CONFIG
|
||||
-D USERMOD_DALLASTEMPERATURE
|
||||
-D USERMOD_FOUR_LINE_DISPLAY
|
||||
-D TEMPERATURE_PIN=23
|
||||
-D USE_ALT_DISPlAY ; new versions of USERMOD_FOUR_LINE_DISPLAY and USERMOD_ROTARY_ENCODER_UI
|
||||
-D USERMOD_AUDIOREACTIVE
|
||||
${esp32.AR_build_flags} ;; includes USERMOD_AUDIOREACTIVE
|
||||
lib_deps = ${esp32.lib_deps}
|
||||
OneWire@~2.3.5
|
||||
olikraus/U8g2 @ ^2.28.8
|
||||
https://github.com/blazoncek/arduinoFFT.git
|
||||
OneWire@~2.3.5 ;; needed for USERMOD_DALLASTEMPERATURE
|
||||
olikraus/U8g2 @ ^2.28.8 ;; needed for USERMOD_FOUR_LINE_DISPLAY
|
||||
${esp32.AR_lib_deps} ;; needed for USERMOD_AUDIOREACTIVE
|
||||
board_build.partitions = ${esp32.default_partitions}
|
||||
|
||||
[env:m5atom]
|
||||
board = esp32dev
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp32.build_flags} -D LEDPIN=27 -D BTNPIN=39
|
||||
[env:esp32_pico-D4]
|
||||
extends = esp32 ;; use default esp32 platform
|
||||
board = pico32 ;; pico32-D4 is different from the standard esp32dev
|
||||
;; hardware details from https://github.com/srg74/WLED-ESP32-pico
|
||||
build_flags = ${common.build_flags} ${esp32.build_flags}
|
||||
-D WLED_RELEASE_NAME=\"pico32-D4\" -D SERVERNAME='"WLED-pico32"'
|
||||
-D WLED_DISABLE_ADALIGHT ;; no serial-to-USB chip on this board - better to disable serial protocols
|
||||
-D DATA_PINS=2,18 ;; LED pins
|
||||
-D RLYPIN=19 -D BTNPIN=0 -D IRPIN=-1 ;; no default pin for IR
|
||||
${esp32.AR_build_flags} ;; include USERMOD_AUDIOREACTIVE
|
||||
-D UM_AUDIOREACTIVE_ENABLE ;; enable AR by default
|
||||
;; Audioreactive settings for on-board microphone (ICS-43432)
|
||||
-D SR_DMTYPE=1 -D I2S_SDPIN=25 -D I2S_WSPIN=15 -D I2S_CKPIN=14
|
||||
-D SR_SQUELCH=5 -D SR_GAIN=30
|
||||
lib_deps = ${esp32.lib_deps}
|
||||
platform = ${esp32.platform}
|
||||
platform_packages = ${esp32.platform_packages}
|
||||
${esp32.AR_lib_deps} ;; needed for USERMOD_AUDIOREACTIVE
|
||||
board_build.partitions = ${esp32.default_partitions}
|
||||
board_build.f_flash = 80000000L
|
||||
|
||||
[env:m5atom]
|
||||
extends = env:esp32dev # we want to extend the existing esp32dev environment (and define only updated options)
|
||||
build_flags = ${common.build_flags} ${esp32.build_flags} -D DATA_PINS=27 -D BTNPIN=39
|
||||
|
||||
[env:sp501e]
|
||||
board = esp_wroom_02
|
||||
platform = ${common.platform_wled_default}
|
||||
board_build.ldscript = ${common.ldscript_2m512k}
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D LEDPIN=3 -D BTNPIN=1
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D DATA_PINS=3 -D BTNPIN=1
|
||||
lib_deps = ${esp8266.lib_deps}
|
||||
|
||||
[env:sp511e]
|
||||
board = esp_wroom_02
|
||||
platform = ${common.platform_wled_default}
|
||||
board_build.ldscript = ${common.ldscript_2m512k}
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D LEDPIN=3 -D BTNPIN=2 -D IRPIN=5 -D WLED_MAX_BUTTONS=3
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D DATA_PINS=3 -D BTNPIN=2 -D IRPIN=5 -D WLED_MAX_BUTTONS=3
|
||||
lib_deps = ${esp8266.lib_deps}
|
||||
|
||||
[env:Athom_RGBCW] ;7w and 5w(GU10) bulbs
|
||||
@@ -409,7 +427,7 @@ platform_packages = ${common.platform_packages}
|
||||
board_build.ldscript = ${common.ldscript_2m512k}
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D BTNPIN=-1 -D RLYPIN=-1 -D DATA_PINS=4,12,14,13,5
|
||||
-D DEFAULT_LED_TYPE=TYPE_ANALOG_5CH -D WLED_DISABLE_INFRARED -D WLED_MAX_CCT_BLEND=0
|
||||
-D LED_TYPES=TYPE_ANALOG_5CH -D WLED_DISABLE_INFRARED -D WLED_MAX_CCT_BLEND=0
|
||||
lib_deps = ${esp8266.lib_deps}
|
||||
|
||||
[env:Athom_15w_RGBCW] ;15w bulb
|
||||
@@ -419,7 +437,7 @@ platform_packages = ${common.platform_packages}
|
||||
board_build.ldscript = ${common.ldscript_2m512k}
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D BTNPIN=-1 -D RLYPIN=-1 -D DATA_PINS=4,12,14,5,13
|
||||
-D DEFAULT_LED_TYPE=TYPE_ANALOG_5CH -D WLED_DISABLE_INFRARED -D WLED_MAX_CCT_BLEND=0 -D WLED_USE_IC_CCT
|
||||
-D LED_TYPES=TYPE_ANALOG_5CH -D WLED_DISABLE_INFRARED -D WLED_MAX_CCT_BLEND=0 -D WLED_USE_IC_CCT
|
||||
lib_deps = ${esp8266.lib_deps}
|
||||
|
||||
[env:Athom_3Pin_Controller] ;small controller with only data
|
||||
@@ -428,7 +446,7 @@ platform = ${common.platform_wled_default}
|
||||
platform_packages = ${common.platform_packages}
|
||||
board_build.ldscript = ${common.ldscript_2m512k}
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D BTNPIN=0 -D RLYPIN=-1 -D LEDPIN=1 -D WLED_DISABLE_INFRARED
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D BTNPIN=0 -D RLYPIN=-1 -D DATA_PINS=1 -D WLED_DISABLE_INFRARED
|
||||
lib_deps = ${esp8266.lib_deps}
|
||||
|
||||
[env:Athom_4Pin_Controller] ; With clock and data interface
|
||||
@@ -437,7 +455,7 @@ platform = ${common.platform_wled_default}
|
||||
platform_packages = ${common.platform_packages}
|
||||
board_build.ldscript = ${common.ldscript_2m512k}
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D BTNPIN=0 -D RLYPIN=12 -D LEDPIN=1 -D WLED_DISABLE_INFRARED
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D BTNPIN=0 -D RLYPIN=12 -D DATA_PINS=1 -D WLED_DISABLE_INFRARED
|
||||
lib_deps = ${esp8266.lib_deps}
|
||||
|
||||
[env:Athom_5Pin_Controller] ;Analog light strip controller
|
||||
@@ -485,17 +503,16 @@ lib_deps = ${esp8266.lib_deps}
|
||||
# EleksTube-IPS
|
||||
# ------------------------------------------------------------------------------
|
||||
[env:elekstube_ips]
|
||||
extends = esp32 ;; use default esp32 platform
|
||||
board = esp32dev
|
||||
platform = ${esp32.platform}
|
||||
platform_packages = ${esp32.platform_packages}
|
||||
upload_speed = 921600
|
||||
build_flags = ${common.build_flags} ${esp32.build_flags} -D WLED_DISABLE_BROWNOUT_DET -D WLED_DISABLE_INFRARED
|
||||
-D USERMOD_RTC
|
||||
-D USERMOD_ELEKSTUBE_IPS
|
||||
-D LEDPIN=12
|
||||
-D DATA_PINS=12
|
||||
-D RLYPIN=27
|
||||
-D BTNPIN=34
|
||||
-D DEFAULT_LED_COUNT=6
|
||||
-D PIXEL_COUNTS=6
|
||||
# Display config
|
||||
-D ST7789_DRIVER
|
||||
-D TFT_WIDTH=135
|
||||
@@ -511,5 +528,4 @@ build_flags = ${common.build_flags} ${esp32.build_flags} -D WLED_DISABLE_BROWNOU
|
||||
monitor_filters = esp32_exception_decoder
|
||||
lib_deps =
|
||||
${esp32.lib_deps}
|
||||
TFT_eSPI @ ^2.3.70
|
||||
board_build.partitions = ${esp32.default_partitions}
|
||||
TFT_eSPI @ 2.5.33 ;; this is the last version that compiles with the WLED default framework - newer versions require platform = espressif32 @ ^6.3.2
|
||||
|
||||
@@ -61,7 +61,7 @@ See [here](https://kno.wled.ge/basics/compatible-hardware)!
|
||||
|
||||
## ✌️ Other
|
||||
|
||||
Licensed under the MIT license
|
||||
Licensed under the EUPL v1.2 license
|
||||
Credits [here](https://kno.wled.ge/about/contributors/)!
|
||||
|
||||
Join the Discord server to discuss everything about WLED!
|
||||
@@ -80,5 +80,5 @@ If WLED really brightens up your day, you can [ {
|
||||
for i in {0..10}
|
||||
do
|
||||
echo -n " http://${HOST}/settings.js?p=$i -o ${TGT_PATH}/$i.xml"
|
||||
done
|
||||
}
|
||||
read -a TARGETS <<< $(replicate)
|
||||
|
||||
mkdir -p ${TGT_PATH}
|
||||
curl ${CURL_ARGS} ${TARGETS[@]}
|
||||
@@ -101,6 +101,7 @@ function adoptVersionAndRepo(html) {
|
||||
async function minify(str, type = "plain") {
|
||||
const options = {
|
||||
collapseWhitespace: true,
|
||||
conservativeCollapse: true, // preserve spaces in text
|
||||
collapseBooleanAttributes: true,
|
||||
collapseInlineTagWhitespace: true,
|
||||
minifyCSS: true,
|
||||
@@ -116,7 +117,8 @@ async function minify(str, type = "plain") {
|
||||
} else if (type == "css-minify") {
|
||||
return new CleanCSS({}).minify(str).styles;
|
||||
} else if (type == "js-minify") {
|
||||
return await minifyHtml('<script>' + str + '</script>', options).replace(/<[\/]*script>/g, '');
|
||||
let js = await minifyHtml('<script>' + str + '</script>', options);
|
||||
return js.replace(/<[\/]*script>/g, '');
|
||||
} else if (type == "html-minify") {
|
||||
return await minifyHtml(str, options);
|
||||
}
|
||||
@@ -252,6 +254,12 @@ writeChunks(
|
||||
str
|
||||
.replace("%%", "%")
|
||||
},
|
||||
{
|
||||
file: "common.js",
|
||||
name: "JS_common",
|
||||
method: "gzip",
|
||||
filter: "js-minify",
|
||||
},
|
||||
{
|
||||
file: "settings.htm",
|
||||
name: "PAGE_settings",
|
||||
|
||||
37
tools/stress_test.sh
Normal file
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
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)
|
||||
@@ -102,9 +102,9 @@ private:
|
||||
|
||||
void secondsEffectSineFade(int16_t secondLed, Toki::Time const& time) {
|
||||
uint32_t ms = time.ms % 1000;
|
||||
uint8_t b0 = (cos8(ms * 64 / 1000) - 128) * 2;
|
||||
uint8_t b0 = (cos8_t(ms * 64 / 1000) - 128) * 2;
|
||||
setPixelColor(secondLed, gamma32(scale32(secondColor, b0)));
|
||||
uint8_t b1 = (sin8(ms * 64 / 1000) - 128) * 2;
|
||||
uint8_t b1 = (sin8_t(ms * 64 / 1000) - 128) * 2;
|
||||
setPixelColor(inc(secondLed, 1, secondsSegment), gamma32(scale32(secondColor, b1)));
|
||||
}
|
||||
|
||||
|
||||
@@ -332,7 +332,7 @@ class Animated_Staircase : public Usermod {
|
||||
};
|
||||
// NOTE: this *WILL* return TRUE if all the pins are set to -1.
|
||||
// this is *BY DESIGN*.
|
||||
if (!pinManager.allocateMultiplePins(pins, 4, PinOwner::UM_AnimatedStaircase)) {
|
||||
if (!PinManager::allocateMultiplePins(pins, 4, PinOwner::UM_AnimatedStaircase)) {
|
||||
topPIRorTriggerPin = -1;
|
||||
topEchoPin = -1;
|
||||
bottomPIRorTriggerPin = -1;
|
||||
@@ -425,10 +425,10 @@ class Animated_Staircase : public Usermod {
|
||||
}
|
||||
|
||||
void appendConfigData() {
|
||||
//oappend(SET_F("dd=addDropdown('staircase','selectfield');"));
|
||||
//oappend(SET_F("addOption(dd,'1st value',0);"));
|
||||
//oappend(SET_F("addOption(dd,'2nd value',1);"));
|
||||
//oappend(SET_F("addInfo('staircase:selectfield',1,'additional info');")); // 0 is field type, 1 is actual field
|
||||
//oappend(F("dd=addDropdown('staircase','selectfield');"));
|
||||
//oappend(F("addOption(dd,'1st value',0);"));
|
||||
//oappend(F("addOption(dd,'2nd value',1);"));
|
||||
//oappend(F("addInfo('staircase:selectfield',1,'additional info');")); // 0 is field type, 1 is actual field
|
||||
}
|
||||
|
||||
|
||||
@@ -513,10 +513,10 @@ class Animated_Staircase : public Usermod {
|
||||
(oldBottomAPin != bottomPIRorTriggerPin) ||
|
||||
(oldBottomBPin != bottomEchoPin)) {
|
||||
changed = true;
|
||||
pinManager.deallocatePin(oldTopAPin, PinOwner::UM_AnimatedStaircase);
|
||||
pinManager.deallocatePin(oldTopBPin, PinOwner::UM_AnimatedStaircase);
|
||||
pinManager.deallocatePin(oldBottomAPin, PinOwner::UM_AnimatedStaircase);
|
||||
pinManager.deallocatePin(oldBottomBPin, PinOwner::UM_AnimatedStaircase);
|
||||
PinManager::deallocatePin(oldTopAPin, PinOwner::UM_AnimatedStaircase);
|
||||
PinManager::deallocatePin(oldTopBPin, PinOwner::UM_AnimatedStaircase);
|
||||
PinManager::deallocatePin(oldBottomAPin, PinOwner::UM_AnimatedStaircase);
|
||||
PinManager::deallocatePin(oldBottomBPin, PinOwner::UM_AnimatedStaircase);
|
||||
}
|
||||
if (changed) setup();
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ Before compiling, you have to make the following modifications:
|
||||
Edit `usermods_list.cpp`:
|
||||
1. Open `wled00/usermods_list.cpp`
|
||||
2. add `#include "../usermods/Animated_Staircase/Animated_Staircase.h"` to the top of the file
|
||||
3. add `usermods.add(new Animated_Staircase());` to the end of the `void registerUsermods()` function.
|
||||
3. add `UsermodManager::add(new Animated_Staircase());` to the end of the `void registerUsermods()` function.
|
||||
|
||||
You can configure usermod using the Usermods settings page.
|
||||
Please enter GPIO pins for PIR or ultrasonic sensors (trigger and echo).
|
||||
|
||||
@@ -444,6 +444,7 @@ public:
|
||||
configComplete &= getJsonValue(top[F("PublishAlways")], PublishAlways, false);
|
||||
configComplete &= getJsonValue(top[F("UseCelsius")], UseCelsius, true);
|
||||
configComplete &= getJsonValue(top[F("HomeAssistantDiscovery")], HomeAssistantDiscovery, false);
|
||||
tempScale = UseCelsius ? "°C" : "°F";
|
||||
|
||||
DEBUG_PRINT(FPSTR(_name));
|
||||
if (!initDone) {
|
||||
|
||||
@@ -767,22 +767,22 @@ void UsermodBME68X::appendConfigData() {
|
||||
// snprintf_P(charbuffer, 127, PSTR("addInfo('%s:%s',1,'*) Set to minus to deactivate (all sensors)');"), UMOD_NAME, _nameTemp); oappend(charbuffer);
|
||||
|
||||
/* Dropdown for Celsius/Fahrenheit*/
|
||||
oappend(SET_F("dd=addDropdown('"));
|
||||
oappend(F("dd=addDropdown('"));
|
||||
oappend(UMOD_NAME);
|
||||
oappend(SET_F("','"));
|
||||
oappend(F("','"));
|
||||
oappend(_nameTempScale);
|
||||
oappend(SET_F("');"));
|
||||
oappend(SET_F("addOption(dd,'Celsius',0);"));
|
||||
oappend(SET_F("addOption(dd,'Fahrenheit',1);"));
|
||||
oappend(F("');"));
|
||||
oappend(F("addOption(dd,'Celsius',0);"));
|
||||
oappend(F("addOption(dd,'Fahrenheit',1);"));
|
||||
|
||||
/* i²C Address*/
|
||||
oappend(SET_F("dd=addDropdown('"));
|
||||
oappend(F("dd=addDropdown('"));
|
||||
oappend(UMOD_NAME);
|
||||
oappend(SET_F("','"));
|
||||
oappend(F("','"));
|
||||
oappend(_nameI2CAdr);
|
||||
oappend(SET_F("');"));
|
||||
oappend(SET_F("addOption(dd,'0x76',0x76);"));
|
||||
oappend(SET_F("addOption(dd,'0x77',0x77);"));
|
||||
oappend(F("');"));
|
||||
oappend(F("addOption(dd,'0x76',0x76);"));
|
||||
oappend(F("addOption(dd,'0x77',0x77);"));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -131,6 +131,11 @@ Specification from: [Molicel INR18650-M35A, 3500mAh 10A Lithium-ion battery, 3.6
|
||||
|
||||
## 📝 Change Log
|
||||
|
||||
2024-08-19
|
||||
|
||||
- Improved MQTT support
|
||||
- Added battery percentage & battery voltage as MQTT topic
|
||||
|
||||
2024-05-11
|
||||
|
||||
- Documentation updated
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -138,7 +200,7 @@ class UsermodBattery : public Usermod
|
||||
bool success = false;
|
||||
DEBUG_PRINTLN(F("Allocating battery pin..."));
|
||||
if (batteryPin >= 0 && digitalPinToAnalogChannel(batteryPin) >= 0)
|
||||
if (pinManager.allocatePin(batteryPin, false, PinOwner::UM_Battery)) {
|
||||
if (PinManager::allocatePin(batteryPin, false, PinOwner::UM_Battery)) {
|
||||
DEBUG_PRINTLN(F("Battery pin allocation succeeded."));
|
||||
success = true;
|
||||
}
|
||||
@@ -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,28 +478,29 @@ 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("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(F("td=addDropdown('Battery','type');")); // 34 Bytes
|
||||
oappend(F("addOption(td,'Unkown','0');")); // 28 Bytes
|
||||
oappend(F("addOption(td,'LiPo','1');")); // 26 Bytes
|
||||
oappend(F("addOption(td,'LiOn','2');")); // 26 Bytes
|
||||
oappend(F("addInfo('Battery:type',1,'<small style=\"color:orange\">requires reboot</small>');")); // 81 Bytes
|
||||
oappend(F("addInfo('Battery:min-voltage',1,'v');")); // 38 Bytes
|
||||
oappend(F("addInfo('Battery:max-voltage',1,'v');")); // 38 Bytes
|
||||
oappend(F("addInfo('Battery:interval',1,'ms');")); // 36 Bytes
|
||||
oappend(F("addInfo('Battery:HA-discovery',1,'');")); // 38 Bytes
|
||||
oappend(F("addInfo('Battery:auto-off:threshold',1,'%');")); // 45 Bytes
|
||||
oappend(F("addInfo('Battery:indicator:threshold',1,'%');")); // 46 Bytes
|
||||
oappend(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
|
||||
// oappend(SET_F("bd=addDropdown('Battery:low-power-indicator', 'preset');"));
|
||||
// the loop generates: oappend(SET_F("addOption(bd, 'preset name', preset id);"));
|
||||
// oappend(F("bd=addDropdown('Battery:low-power-indicator', 'preset');"));
|
||||
// the loop generates: oappend(F("addOption(bd, 'preset name', preset id);"));
|
||||
// for(int8_t i=1; i < 42; i++) {
|
||||
// oappend(SET_F("addOption(bd, 'Preset#"));
|
||||
// oappend(F("addOption(bd, 'Preset#"));
|
||||
// oappendi(i);
|
||||
// oappend(SET_F("',"));
|
||||
// oappend(F("',"));
|
||||
// oappendi(i);
|
||||
// oappend(SET_F(");"));
|
||||
// oappend(F(");"));
|
||||
// }
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -502,7 +561,7 @@ class UsermodBattery : public Usermod
|
||||
if (newBatteryPin != batteryPin)
|
||||
{
|
||||
// deallocate pin
|
||||
pinManager.deallocatePin(batteryPin, PinOwner::UM_Battery);
|
||||
PinManager::deallocatePin(batteryPin, PinOwner::UM_Battery);
|
||||
batteryPin = newBatteryPin;
|
||||
// initialise
|
||||
setup();
|
||||
@@ -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";
|
||||
|
||||
@@ -71,7 +71,7 @@ class MyExampleUsermod : public Usermod {
|
||||
// #endif
|
||||
// in setup()
|
||||
// #ifdef USERMOD_EXAMPLE
|
||||
// UM = (MyExampleUsermod*) usermods.lookup(USERMOD_ID_EXAMPLE);
|
||||
// UM = (MyExampleUsermod*) UsermodManager::lookup(USERMOD_ID_EXAMPLE);
|
||||
// #endif
|
||||
// somewhere in loop() or other member method
|
||||
// #ifdef USERMOD_EXAMPLE
|
||||
@@ -287,11 +287,11 @@ class MyExampleUsermod : public Usermod {
|
||||
*/
|
||||
void appendConfigData() override
|
||||
{
|
||||
oappend(SET_F("addInfo('")); oappend(String(FPSTR(_name)).c_str()); oappend(SET_F(":great")); oappend(SET_F("',1,'<i>(this is a great config value)</i>');"));
|
||||
oappend(SET_F("addInfo('")); oappend(String(FPSTR(_name)).c_str()); oappend(SET_F(":testString")); oappend(SET_F("',1,'enter any string you want');"));
|
||||
oappend(SET_F("dd=addDropdown('")); oappend(String(FPSTR(_name)).c_str()); oappend(SET_F("','testInt');"));
|
||||
oappend(SET_F("addOption(dd,'Nothing',0);"));
|
||||
oappend(SET_F("addOption(dd,'Everything',42);"));
|
||||
oappend(F("addInfo('")); oappend(String(FPSTR(_name)).c_str()); oappend(F(":great")); oappend(F("',1,'<i>(this is a great config value)</i>');"));
|
||||
oappend(F("addInfo('")); oappend(String(FPSTR(_name)).c_str()); oappend(F(":testString")); oappend(F("',1,'enter any string you want');"));
|
||||
oappend(F("dd=addDropdown('")); oappend(String(FPSTR(_name)).c_str()); oappend(F("','testInt');"));
|
||||
oappend(F("addOption(dd,'Nothing',0);"));
|
||||
oappend(F("addOption(dd,'Everything',42);"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -59,10 +59,10 @@ void registerUsermods()
|
||||
* || || ||
|
||||
* \/ \/ \/
|
||||
*/
|
||||
//usermods.add(new MyExampleUsermod());
|
||||
//usermods.add(new UsermodTemperature());
|
||||
//usermods.add(new UsermodRenameMe());
|
||||
usermods.add(new FixUnreachableNetServices());
|
||||
//UsermodManager::add(new MyExampleUsermod());
|
||||
//UsermodManager::add(new UsermodTemperature());
|
||||
//UsermodManager::add(new UsermodRenameMe());
|
||||
UsermodManager::add(new FixUnreachableNetServices());
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
BIN
usermods/Internal_Temperature_v2/assets/screenshot_info.png
Normal file
BIN
usermods/Internal_Temperature_v2/assets/screenshot_info.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 132 KiB |
BIN
usermods/Internal_Temperature_v2/assets/screenshot_settings.png
Normal file
BIN
usermods/Internal_Temperature_v2/assets/screenshot_settings.png
Normal file
Binary file not shown.
|
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(F("addInfo('Internal Temperature:Loop Interval', 1, 'ms');"));
|
||||
// Display '°C' next to the 'Activation Threshold' setting
|
||||
oappend(F("addInfo('Internal Temperature:Activation Threshold', 1, '°C');"));
|
||||
// Display '0 = Disabled' next to the 'Preset To Activate' setting
|
||||
oappend(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)
|
||||
{
|
||||
|
||||
@@ -30,7 +30,7 @@ class LDR_Dusk_Dawn_v2 : public Usermod {
|
||||
void setup() {
|
||||
// register ldrPin
|
||||
if ((ldrPin >= 0) && (digitalPinToAnalogChannel(ldrPin) >= 0)) {
|
||||
if(!pinManager.allocatePin(ldrPin, false, PinOwner::UM_LDR_DUSK_DAWN)) ldrEnabled = false; // pin already in use -> disable usermod
|
||||
if(!PinManager::allocatePin(ldrPin, false, PinOwner::UM_LDR_DUSK_DAWN)) ldrEnabled = false; // pin already in use -> disable usermod
|
||||
else pinMode(ldrPin, INPUT); // alloc success -> configure pin for input
|
||||
} else ldrEnabled = false; // invalid pin -> disable usermod
|
||||
initDone = true;
|
||||
@@ -110,7 +110,7 @@ class LDR_Dusk_Dawn_v2 : public Usermod {
|
||||
|
||||
if (initDone && (ldrPin != oldLdrPin)) {
|
||||
// pin changed - un-register previous pin, register new pin
|
||||
if (oldLdrPin >= 0) pinManager.deallocatePin(oldLdrPin, PinOwner::UM_LDR_DUSK_DAWN);
|
||||
if (oldLdrPin >= 0) PinManager::deallocatePin(oldLdrPin, PinOwner::UM_LDR_DUSK_DAWN);
|
||||
setup(); // setup new pin
|
||||
}
|
||||
return configComplete;
|
||||
@@ -139,7 +139,7 @@ class LDR_Dusk_Dawn_v2 : public Usermod {
|
||||
//LDR_Off_Count.add(ldrOffCount);
|
||||
|
||||
//bool pinValid = ((ldrPin >= 0) && (digitalPinToAnalogChannel(ldrPin) >= 0));
|
||||
//if (pinManager.getPinOwner(ldrPin) != PinOwner::UM_LDR_DUSK_DAWN) pinValid = false;
|
||||
//if (PinManager::getPinOwner(ldrPin) != PinOwner::UM_LDR_DUSK_DAWN) pinValid = false;
|
||||
//JsonArray LDR_valid = user.createNestedArray(F("LDR pin"));
|
||||
//LDR_valid.add(ldrPin);
|
||||
//LDR_valid.add(pinValid ? F(" OK"): F(" invalid"));
|
||||
|
||||
@@ -52,7 +52,7 @@ class MyUsermod : public Usermod {
|
||||
|
||||
void togglePIRSensor() {
|
||||
#ifdef USERMOD_PIR_SENSOR_SWITCH
|
||||
PIRsensorSwitch *PIRsensor = (PIRsensorSwitch::*) usermods.lookup(USERMOD_ID_PIRSWITCH);
|
||||
PIRsensorSwitch *PIRsensor = (PIRsensorSwitch::*) UsermodManager::lookup(USERMOD_ID_PIRSWITCH);
|
||||
if (PIRsensor != nullptr) {
|
||||
PIRsensor->EnablePIRsensor(!PIRsensor->PIRsensorEnabled());
|
||||
}
|
||||
|
||||
@@ -375,7 +375,7 @@ void PIRsensorSwitch::setup()
|
||||
sensorPinState[i] = LOW;
|
||||
if (PIRsensorPin[i] < 0) continue;
|
||||
// pin retrieved from cfg.json (readFromConfig()) prior to running setup()
|
||||
if (pinManager.allocatePin(PIRsensorPin[i], false, PinOwner::UM_PIR)) {
|
||||
if (PinManager::allocatePin(PIRsensorPin[i], false, PinOwner::UM_PIR)) {
|
||||
// PIR Sensor mode INPUT_PULLDOWN
|
||||
#ifdef ESP8266
|
||||
pinMode(PIRsensorPin[i], PIRsensorPin[i]==16 ? INPUT_PULLDOWN_16 : INPUT_PULLUP); // ESP8266 has INPUT_PULLDOWN on GPIO16 only
|
||||
@@ -511,8 +511,8 @@ void PIRsensorSwitch::addToConfig(JsonObject &root)
|
||||
|
||||
void PIRsensorSwitch::appendConfigData()
|
||||
{
|
||||
oappend(SET_F("addInfo('PIRsensorSwitch:HA-discovery',1,'HA=Home Assistant');")); // 0 is field type, 1 is actual field
|
||||
oappend(SET_F("addInfo('PIRsensorSwitch:override',1,'Cancel timer on change');")); // 0 is field type, 1 is actual field
|
||||
oappend(F("addInfo('PIRsensorSwitch:HA-discovery',1,'HA=Home Assistant');")); // 0 is field type, 1 is actual field
|
||||
oappend(F("addInfo('PIRsensorSwitch:override',1,'Cancel timer on change');")); // 0 is field type, 1 is actual field
|
||||
for (int i = 0; i < PIR_SENSOR_MAX_SENSORS; i++) {
|
||||
char str[128];
|
||||
sprintf_P(str, PSTR("addInfo('PIRsensorSwitch:pin[]',%d,'','#%d');"), i, i);
|
||||
@@ -564,7 +564,7 @@ bool PIRsensorSwitch::readFromConfig(JsonObject &root)
|
||||
DEBUG_PRINTLN(F(" config loaded."));
|
||||
} else {
|
||||
for (int i = 0; i < PIR_SENSOR_MAX_SENSORS; i++)
|
||||
if (oldPin[i] >= 0) pinManager.deallocatePin(oldPin[i], PinOwner::UM_PIR);
|
||||
if (oldPin[i] >= 0) PinManager::deallocatePin(oldPin[i], PinOwner::UM_PIR);
|
||||
setup();
|
||||
DEBUG_PRINTLN(F(" config (re)loaded."));
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ class PWMFanUsermod : public Usermod {
|
||||
static const char _lock[];
|
||||
|
||||
void initTacho(void) {
|
||||
if (tachoPin < 0 || !pinManager.allocatePin(tachoPin, false, PinOwner::UM_Unspecified)){
|
||||
if (tachoPin < 0 || !PinManager::allocatePin(tachoPin, false, PinOwner::UM_Unspecified)){
|
||||
tachoPin = -1;
|
||||
return;
|
||||
}
|
||||
@@ -88,7 +88,7 @@ class PWMFanUsermod : public Usermod {
|
||||
void deinitTacho(void) {
|
||||
if (tachoPin < 0) return;
|
||||
detachInterrupt(digitalPinToInterrupt(tachoPin));
|
||||
pinManager.deallocatePin(tachoPin, PinOwner::UM_Unspecified);
|
||||
PinManager::deallocatePin(tachoPin, PinOwner::UM_Unspecified);
|
||||
tachoPin = -1;
|
||||
}
|
||||
|
||||
@@ -111,7 +111,7 @@ class PWMFanUsermod : public Usermod {
|
||||
|
||||
// https://randomnerdtutorials.com/esp32-pwm-arduino-ide/
|
||||
void initPWMfan(void) {
|
||||
if (pwmPin < 0 || !pinManager.allocatePin(pwmPin, true, PinOwner::UM_Unspecified)) {
|
||||
if (pwmPin < 0 || !PinManager::allocatePin(pwmPin, true, PinOwner::UM_Unspecified)) {
|
||||
enabled = false;
|
||||
pwmPin = -1;
|
||||
return;
|
||||
@@ -121,7 +121,7 @@ class PWMFanUsermod : public Usermod {
|
||||
analogWriteRange(255);
|
||||
analogWriteFreq(WLED_PWM_FREQ);
|
||||
#else
|
||||
pwmChannel = pinManager.allocateLedc(1);
|
||||
pwmChannel = PinManager::allocateLedc(1);
|
||||
if (pwmChannel == 255) { //no more free LEDC channels
|
||||
deinitPWMfan(); return;
|
||||
}
|
||||
@@ -136,9 +136,9 @@ class PWMFanUsermod : public Usermod {
|
||||
void deinitPWMfan(void) {
|
||||
if (pwmPin < 0) return;
|
||||
|
||||
pinManager.deallocatePin(pwmPin, PinOwner::UM_Unspecified);
|
||||
PinManager::deallocatePin(pwmPin, PinOwner::UM_Unspecified);
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
pinManager.deallocateLedc(pwmChannel, 1);
|
||||
PinManager::deallocateLedc(pwmChannel, 1);
|
||||
#endif
|
||||
pwmPin = -1;
|
||||
}
|
||||
@@ -191,9 +191,9 @@ class PWMFanUsermod : public Usermod {
|
||||
void setup() override {
|
||||
#ifdef USERMOD_DALLASTEMPERATURE
|
||||
// This Usermod requires Temperature usermod
|
||||
tempUM = (UsermodTemperature*) usermods.lookup(USERMOD_ID_TEMPERATURE);
|
||||
tempUM = (UsermodTemperature*) UsermodManager::lookup(USERMOD_ID_TEMPERATURE);
|
||||
#elif defined(USERMOD_SHT)
|
||||
tempUM = (ShtUsermod*) usermods.lookup(USERMOD_ID_SHT);
|
||||
tempUM = (ShtUsermod*) UsermodManager::lookup(USERMOD_ID_SHT);
|
||||
#endif
|
||||
initTacho();
|
||||
initPWMfan();
|
||||
|
||||
@@ -9,6 +9,6 @@
|
||||
void registerUsermods()
|
||||
{
|
||||
#ifdef USERMOD_SN_PHOTORESISTOR
|
||||
usermods.add(new Usermod_SN_Photoresistor());
|
||||
UsermodManager::add(new Usermod_SN_Photoresistor());
|
||||
#endif
|
||||
}
|
||||
@@ -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
|
||||
@@ -135,10 +138,10 @@ class St7789DisplayUsermod : public Usermod {
|
||||
void setup() override
|
||||
{
|
||||
PinManagerPinType spiPins[] = { { spi_mosi, true }, { spi_miso, false}, { spi_sclk, true } };
|
||||
if (!pinManager.allocateMultiplePins(spiPins, 3, PinOwner::HW_SPI)) { enabled = false; return; }
|
||||
if (!PinManager::allocateMultiplePins(spiPins, 3, PinOwner::HW_SPI)) { enabled = false; return; }
|
||||
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);
|
||||
if (!PinManager::allocateMultiplePins(displayPins, sizeof(displayPins)/sizeof(PinManagerPinType), PinOwner::UM_FourLineDisplay)) {
|
||||
PinManager::deallocateMultiplePins(spiPins, 3, PinOwner::HW_SPI);
|
||||
enabled = false;
|
||||
return;
|
||||
}
|
||||
@@ -374,10 +377,10 @@ class St7789DisplayUsermod : public Usermod {
|
||||
|
||||
|
||||
void appendConfigData() override {
|
||||
oappend(SET_F("addInfo('ST7789:pin[]',0,'','SPI CS');"));
|
||||
oappend(SET_F("addInfo('ST7789:pin[]',1,'','SPI DC');"));
|
||||
oappend(SET_F("addInfo('ST7789:pin[]',2,'','SPI RST');"));
|
||||
oappend(SET_F("addInfo('ST7789:pin[]',2,'','SPI BL');"));
|
||||
oappend(F("addInfo('ST7789:pin[]',0,'','SPI CS');"));
|
||||
oappend(F("addInfo('ST7789:pin[]',1,'','SPI DC');"));
|
||||
oappend(F("addInfo('ST7789:pin[]',2,'','SPI RST');"));
|
||||
oappend(F("addInfo('ST7789:pin[]',3,'','SPI BL');"));
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
@@ -7,6 +7,4 @@
|
||||
extends = env:d1_mini
|
||||
build_flags = ${common.build_flags_esp8266} -D USERMOD_DALLASTEMPERATURE
|
||||
lib_deps = ${env.lib_deps}
|
||||
paulstoffregen/OneWire@~2.3.7
|
||||
# you may want to use following with ESP32
|
||||
; https://github.com/blazoncek/OneWire.git # fixes Sensor error on ESP32
|
||||
paulstoffregen/OneWire@~2.3.8
|
||||
@@ -43,10 +43,8 @@ default_envs = d1_mini
|
||||
...
|
||||
lib_deps =
|
||||
...
|
||||
#For Dallas sensor uncomment following line
|
||||
OneWire@~2.3.7
|
||||
# ... or you may want to use following with ESP32
|
||||
; https://github.com/blazoncek/OneWire.git # fixes Sensor error on ESP32...
|
||||
#For Dallas sensor uncomment following
|
||||
paulstoffregen/OneWire @ ~2.3.8
|
||||
```
|
||||
|
||||
## Change Log
|
||||
@@ -56,8 +54,14 @@ lib_deps =
|
||||
* Do not report erroneous low temperatures to MQTT
|
||||
* Disable plugin if temperature sensor not detected
|
||||
* Report the number of seconds until the first read in the info screen instead of sensor error
|
||||
|
||||
2021-04
|
||||
* Adaptation for runtime configuration.
|
||||
|
||||
2023-05
|
||||
* Rewrite to conform to newer recommendations.
|
||||
* Recommended @blazoncek fork of OneWire for ESP32 to avoid Sensor error
|
||||
* Recommended @blazoncek fork of OneWire for ESP32 to avoid Sensor error
|
||||
|
||||
2024-09
|
||||
* Update OneWire to version 2.3.8, which includes stickbreaker's and garyd9's ESP32 fixes:
|
||||
blazoncek's fork is no longer needed
|
||||
@@ -17,6 +17,8 @@
|
||||
#define USERMOD_DALLASTEMPERATURE_MEASUREMENT_INTERVAL 60000
|
||||
#endif
|
||||
|
||||
static uint16_t mode_temperature();
|
||||
|
||||
class UsermodTemperature : public Usermod {
|
||||
|
||||
private:
|
||||
@@ -60,6 +62,7 @@ class UsermodTemperature : public Usermod {
|
||||
static const char _sensor[];
|
||||
static const char _temperature[];
|
||||
static const char _Temperature[];
|
||||
static const char _data_fx[];
|
||||
|
||||
//Dallas sensor quick (& dirty) reading. Credit to - Author: Peter Scargill, August 17th, 2013
|
||||
float readDallas();
|
||||
@@ -70,8 +73,13 @@ class UsermodTemperature : public Usermod {
|
||||
void publishHomeAssistantAutodiscovery();
|
||||
#endif
|
||||
|
||||
static UsermodTemperature* _instance; // to overcome nonstatic getTemperatureC() method and avoid UsermodManager::lookup(USERMOD_ID_TEMPERATURE);
|
||||
|
||||
public:
|
||||
|
||||
UsermodTemperature() { _instance = this; }
|
||||
static UsermodTemperature *getInstance() { return UsermodTemperature::_instance; }
|
||||
|
||||
/*
|
||||
* API calls te enable data exchange between WLED modules
|
||||
*/
|
||||
@@ -113,7 +121,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 +141,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;
|
||||
}
|
||||
|
||||
@@ -215,14 +223,14 @@ void UsermodTemperature::setup() {
|
||||
// config says we are enabled
|
||||
DEBUG_PRINTLN(F("Allocating temperature pin..."));
|
||||
// pin retrieved from cfg.json (readFromConfig()) prior to running setup()
|
||||
if (temperaturePin >= 0 && pinManager.allocatePin(temperaturePin, true, PinOwner::UM_Temperature)) {
|
||||
if (temperaturePin >= 0 && PinManager::allocatePin(temperaturePin, true, PinOwner::UM_Temperature)) {
|
||||
oneWire = new OneWire(temperaturePin);
|
||||
if (oneWire->reset()) {
|
||||
while (!findSensor() && retries--) {
|
||||
delay(25); // try to find sensor
|
||||
}
|
||||
}
|
||||
if (parasite && pinManager.allocatePin(parasitePin, true, PinOwner::UM_Temperature)) {
|
||||
if (parasite && PinManager::allocatePin(parasitePin, true, PinOwner::UM_Temperature)) {
|
||||
pinMode(parasitePin, OUTPUT);
|
||||
digitalWrite(parasitePin, LOW); // deactivate power (close MOSFET)
|
||||
} else {
|
||||
@@ -234,6 +242,7 @@ void UsermodTemperature::setup() {
|
||||
}
|
||||
temperaturePin = -1; // allocation failed
|
||||
}
|
||||
if (sensorFound && !initDone) strip.addEffect(255, &mode_temperature, _data_fx);
|
||||
}
|
||||
lastMeasurement = millis() - readingInterval + 10000;
|
||||
initDone = true;
|
||||
@@ -414,9 +423,9 @@ bool UsermodTemperature::readFromConfig(JsonObject &root) {
|
||||
DEBUG_PRINTLN(F("Re-init temperature."));
|
||||
// deallocate pin and release memory
|
||||
delete oneWire;
|
||||
pinManager.deallocatePin(temperaturePin, PinOwner::UM_Temperature);
|
||||
PinManager::deallocatePin(temperaturePin, PinOwner::UM_Temperature);
|
||||
temperaturePin = newTemperaturePin;
|
||||
pinManager.deallocatePin(parasitePin, PinOwner::UM_Temperature);
|
||||
PinManager::deallocatePin(parasitePin, PinOwner::UM_Temperature);
|
||||
// initialise
|
||||
setup();
|
||||
}
|
||||
@@ -426,10 +435,10 @@ bool UsermodTemperature::readFromConfig(JsonObject &root) {
|
||||
}
|
||||
|
||||
void UsermodTemperature::appendConfigData() {
|
||||
oappend(SET_F("addInfo('")); oappend(String(FPSTR(_name)).c_str()); oappend(SET_F(":")); oappend(String(FPSTR(_parasite)).c_str());
|
||||
oappend(SET_F("',1,'<i>(if no Vcc connected)</i>');")); // 0 is field type, 1 is actual field
|
||||
oappend(SET_F("addInfo('")); oappend(String(FPSTR(_name)).c_str()); oappend(SET_F(":")); oappend(String(FPSTR(_parasitePin)).c_str());
|
||||
oappend(SET_F("',1,'<i>(for external MOSFET)</i>');")); // 0 is field type, 1 is actual field
|
||||
oappend(F("addInfo('")); oappend(String(FPSTR(_name)).c_str()); oappend(F(":")); oappend(String(FPSTR(_parasite)).c_str());
|
||||
oappend(F("',1,'<i>(if no Vcc connected)</i>');")); // 0 is field type, 1 is actual field
|
||||
oappend(F("addInfo('")); oappend(String(FPSTR(_name)).c_str()); oappend(F(":")); oappend(String(FPSTR(_parasitePin)).c_str());
|
||||
oappend(F("',1,'<i>(for external MOSFET)</i>');")); // 0 is field type, 1 is actual field
|
||||
}
|
||||
|
||||
float UsermodTemperature::getTemperature() {
|
||||
@@ -440,6 +449,8 @@ const char *UsermodTemperature::getTemperatureUnit() {
|
||||
return degC ? "°C" : "°F";
|
||||
}
|
||||
|
||||
UsermodTemperature* UsermodTemperature::_instance = nullptr;
|
||||
|
||||
// strings to reduce flash memory usage (used more than twice)
|
||||
const char UsermodTemperature::_name[] PROGMEM = "Temperature";
|
||||
const char UsermodTemperature::_enabled[] PROGMEM = "enabled";
|
||||
@@ -449,4 +460,14 @@ const char UsermodTemperature::_parasitePin[] PROGMEM = "parasite-pwr-pin";
|
||||
const char UsermodTemperature::_domoticzIDX[] PROGMEM = "domoticz-idx";
|
||||
const char UsermodTemperature::_sensor[] PROGMEM = "sensor";
|
||||
const char UsermodTemperature::_temperature[] PROGMEM = "temperature";
|
||||
const char UsermodTemperature::_Temperature[] PROGMEM = "/temperature";
|
||||
const char UsermodTemperature::_Temperature[] PROGMEM = "/temperature";
|
||||
const char UsermodTemperature::_data_fx[] PROGMEM = "Temperature@Min,Max;;!;01;pal=54,sx=255,ix=0";
|
||||
|
||||
static uint16_t mode_temperature() {
|
||||
float low = roundf(mapf((float)SEGMENT.speed, 0.f, 255.f, -150.f, 150.f)); // default: 15°C, range: -15°C to 15°C
|
||||
float high = roundf(mapf((float)SEGMENT.intensity, 0.f, 255.f, 300.f, 600.f)); // default: 30°C, range 30°C to 60°C
|
||||
float temp = constrain(UsermodTemperature::getInstance()->getTemperatureC()*10.f, low, high); // get a little better resolution (*10)
|
||||
unsigned i = map(roundf(temp), (unsigned)low, (unsigned)high, 0, 248);
|
||||
SEGMENT.fill(SEGMENT.color_from_palette(i, false, false, 255));
|
||||
return FRAMETIME;
|
||||
}
|
||||
|
||||
@@ -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.getFrameTime()
|
||||
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,47 +142,24 @@ 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 //
|
||||
////////////////////
|
||||
|
||||
// some prototypes, to ensure consistent interfaces
|
||||
static float mapf(float x, float in_min, float in_max, float out_min, float out_max); // map function for float
|
||||
static float fftAddAvg(int from, int to); // average of several FFT result bins
|
||||
void FFTcode(void * parameter); // audio processing task: read samples, run FFT, fill GEQ channels from FFT results
|
||||
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;
|
||||
@@ -181,8 +191,8 @@ constexpr uint16_t samplesFFT_2 = 256; // meaningfull part of FFT resul
|
||||
#define LOG_256 5.54517744f // log(256)
|
||||
|
||||
// These are the input and output vectors. Input vectors receive computed results from FFT.
|
||||
static float vReal[samplesFFT] = {0.0f}; // FFT sample inputs / freq output - these are our raw result bins
|
||||
static float vImag[samplesFFT] = {0.0f}; // imaginary parts
|
||||
static float* vReal = nullptr; // FFT sample inputs / freq output - these are our raw result bins
|
||||
static float* vImag = nullptr; // imaginary parts
|
||||
|
||||
// Create FFT object
|
||||
// lib_deps += https://github.com/kosme/arduinoFFT#develop @ 1.9.2
|
||||
@@ -190,21 +200,11 @@ static float vImag[samplesFFT] = {0.0f}; // imaginary parts
|
||||
// #define FFT_SPEED_OVER_PRECISION // enables use of reciprocals (1/x etc) - not faster on ESP32
|
||||
// #define FFT_SQRT_APPROXIMATION // enables "quake3" style inverse sqrt - slower on ESP32
|
||||
// Below options are forcing ArduinoFFT to use sqrtf() instead of sqrt()
|
||||
#define sqrt(x) sqrtf(x) // little hack that reduces FFT time by 10-50% on ESP32
|
||||
#define sqrt_internal sqrtf // see https://github.com/kosme/arduinoFFT/pull/83
|
||||
|
||||
#include <arduinoFFT.h>
|
||||
|
||||
/* Create FFT object with weighing factor storage */
|
||||
static ArduinoFFT<float> FFT = ArduinoFFT<float>( vReal, vImag, samplesFFT, SAMPLE_RATE, true);
|
||||
// #define sqrt_internal sqrtf // see https://github.com/kosme/arduinoFFT/pull/83 - since v2.0.0 this must be done in build_flags
|
||||
|
||||
#include <arduinoFFT.h> // FFT object is created in FFTcode
|
||||
// Helper functions
|
||||
|
||||
// float version of map()
|
||||
static float mapf(float x, float in_min, float in_max, float out_min, float out_max){
|
||||
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
|
||||
}
|
||||
|
||||
// compute average of several FFT result bins
|
||||
static float fftAddAvg(int from, int to) {
|
||||
float result = 0.0f;
|
||||
@@ -221,6 +221,18 @@ void FFTcode(void * parameter)
|
||||
{
|
||||
DEBUGSR_PRINT("FFT started on core: "); DEBUGSR_PRINTLN(xPortGetCoreID());
|
||||
|
||||
// allocate FFT buffers on first call
|
||||
if (vReal == nullptr) vReal = (float*) calloc(sizeof(float), samplesFFT);
|
||||
if (vImag == nullptr) vImag = (float*) calloc(sizeof(float), samplesFFT);
|
||||
if ((vReal == nullptr) || (vImag == nullptr)) {
|
||||
// something went wrong
|
||||
if (vReal) free(vReal); vReal = nullptr;
|
||||
if (vImag) free(vImag); vImag = nullptr;
|
||||
return;
|
||||
}
|
||||
// Create FFT object with weighing factor storage
|
||||
ArduinoFFT<float> FFT = ArduinoFFT<float>( vReal, vImag, samplesFFT, SAMPLE_RATE, true);
|
||||
|
||||
// see https://www.freertos.org/vtaskdelayuntil.html
|
||||
const TickType_t xFrequency = FFT_MIN_CYCLE * portTICK_PERIOD_MS;
|
||||
|
||||
@@ -242,6 +254,7 @@ void FFTcode(void * parameter)
|
||||
|
||||
// get a fresh batch of samples from I2S
|
||||
if (audioSource) audioSource->getSamples(vReal, samplesFFT);
|
||||
memset(vImag, 0, samplesFFT * sizeof(float)); // set imaginary parts to 0
|
||||
|
||||
#if defined(WLED_DEBUG) || defined(SR_DEBUG)
|
||||
if (start < esp_timer_get_time()) { // filter out overflows
|
||||
@@ -260,8 +273,6 @@ void FFTcode(void * parameter)
|
||||
// find highest sample in the batch
|
||||
float maxSample = 0.0f; // max sample from FFT batch
|
||||
for (int i=0; i < samplesFFT; i++) {
|
||||
// set imaginary parts to 0
|
||||
vImag[i] = 0;
|
||||
// pick our our current mic sample - we take the max value from all samples that go into FFT
|
||||
if ((vReal[i] <= (INT16_MAX - 1024)) && (vReal[i] >= (INT16_MIN + 1024))) //skip extreme values - normally these are artefacts
|
||||
if (fabsf((float)vReal[i]) > maxSample) maxSample = fabsf((float)vReal[i]);
|
||||
@@ -292,7 +303,7 @@ void FFTcode(void * parameter)
|
||||
#endif
|
||||
|
||||
} else { // noise gate closed - only clear results as FFT was skipped. MIC samples are still valid when we do this.
|
||||
memset(vReal, 0, sizeof(vReal));
|
||||
memset(vReal, 0, samplesFFT * sizeof(float));
|
||||
FFT_MajorPeak = 1;
|
||||
FFT_Magnitude = 0.001;
|
||||
}
|
||||
@@ -522,9 +533,11 @@ 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.
|
||||
uint16_t peakDelay = max(uint16_t(50), strip.getFrameTime());
|
||||
if (millis() - timeOfPeak > peakDelay) { // Auto-reset of samplePeak after at least one complete frame has passed.
|
||||
samplePeak = false;
|
||||
if (audioSyncEnabled == 0) udpSamplePeak = false; // this is normally reset by transmitAudioData
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -1782,53 +1885,61 @@ class AudioReactive : public Usermod {
|
||||
}
|
||||
|
||||
|
||||
void appendConfigData() override
|
||||
void appendConfigData(Print& uiScript) override
|
||||
{
|
||||
oappend(SET_F("dd=addDropdown('AudioReactive','digitalmic:type');"));
|
||||
uiScript.print(F("ux='AudioReactive';")); // ux = shortcut for Audioreactive - fingers crossed that "ux" isn't already used as JS var, html post parameter or css style
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
uiScript.print(F("uxp=ux+':digitalmic:pin[]';")); // uxp = shortcut for AudioReactive:digitalmic:pin[]
|
||||
uiScript.print(F("dd=addDropdown(ux,'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);"));
|
||||
uiScript.print(F("addOption(dd,'Generic Analog',0);"));
|
||||
#endif
|
||||
oappend(SET_F("addOption(dd,'Generic I2S',1);"));
|
||||
oappend(SET_F("addOption(dd,'ES7243',2);"));
|
||||
oappend(SET_F("addOption(dd,'SPH0654',3);"));
|
||||
oappend(SET_F("addOption(dd,'Generic I2S with Mclk',4);"));
|
||||
uiScript.print(F("addOption(dd,'Generic I2S',1);"));
|
||||
uiScript.print(F("addOption(dd,'ES7243',2);"));
|
||||
uiScript.print(F("addOption(dd,'SPH0654',3);"));
|
||||
uiScript.print(F("addOption(dd,'Generic I2S with Mclk',4);"));
|
||||
#if !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3)
|
||||
oappend(SET_F("addOption(dd,'Generic I2S PDM',5);"));
|
||||
uiScript.print(F("addOption(dd,'Generic I2S PDM',5);"));
|
||||
#endif
|
||||
oappend(SET_F("addOption(dd,'ES8388',6);"));
|
||||
uiScript.print(F("addOption(dd,'ES8388',6);"));
|
||||
|
||||
oappend(SET_F("dd=addDropdown('AudioReactive','config:AGC');"));
|
||||
oappend(SET_F("addOption(dd,'Off',0);"));
|
||||
oappend(SET_F("addOption(dd,'Normal',1);"));
|
||||
oappend(SET_F("addOption(dd,'Vivid',2);"));
|
||||
oappend(SET_F("addOption(dd,'Lazy',3);"));
|
||||
uiScript.print(F("dd=addDropdown(ux,'config:AGC');"));
|
||||
uiScript.print(F("addOption(dd,'Off',0);"));
|
||||
uiScript.print(F("addOption(dd,'Normal',1);"));
|
||||
uiScript.print(F("addOption(dd,'Vivid',2);"));
|
||||
uiScript.print(F("addOption(dd,'Lazy',3);"));
|
||||
|
||||
oappend(SET_F("dd=addDropdown('AudioReactive','dynamics:limiter');"));
|
||||
oappend(SET_F("addOption(dd,'Off',0);"));
|
||||
oappend(SET_F("addOption(dd,'On',1);"));
|
||||
oappend(SET_F("addInfo('AudioReactive:dynamics:limiter',0,' On ');")); // 0 is field type, 1 is actual field
|
||||
oappend(SET_F("addInfo('AudioReactive:dynamics:rise',1,'ms <i>(♪ effects only)</i>');"));
|
||||
oappend(SET_F("addInfo('AudioReactive:dynamics:fall',1,'ms <i>(♪ effects only)</i>');"));
|
||||
uiScript.print(F("dd=addDropdown(ux,'dynamics:limiter');"));
|
||||
uiScript.print(F("addOption(dd,'Off',0);"));
|
||||
uiScript.print(F("addOption(dd,'On',1);"));
|
||||
uiScript.print(F("addInfo(ux+':dynamics:limiter',0,' On ');")); // 0 is field type, 1 is actual field
|
||||
uiScript.print(F("addInfo(ux+':dynamics:rise',1,'ms <i>(♪ effects only)</i>');"));
|
||||
uiScript.print(F("addInfo(ux+':dynamics:fall',1,'ms <i>(♪ effects only)</i>');"));
|
||||
|
||||
oappend(SET_F("dd=addDropdown('AudioReactive','frequency:scale');"));
|
||||
oappend(SET_F("addOption(dd,'None',0);"));
|
||||
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);"));
|
||||
uiScript.print(F("dd=addDropdown(ux,'frequency:scale');"));
|
||||
uiScript.print(F("addOption(dd,'None',0);"));
|
||||
uiScript.print(F("addOption(dd,'Linear (Amplitude)',2);"));
|
||||
uiScript.print(F("addOption(dd,'Square Root (Energy)',3);"));
|
||||
uiScript.print(F("addOption(dd,'Logarithmic (Loudness)',1);"));
|
||||
#endif
|
||||
|
||||
oappend(SET_F("dd=addDropdown('AudioReactive','sync:mode');"));
|
||||
oappend(SET_F("addOption(dd,'Off',0);"));
|
||||
oappend(SET_F("addOption(dd,'Send',1);"));
|
||||
oappend(SET_F("addOption(dd,'Receive',2);"));
|
||||
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');"));
|
||||
oappend(SET_F("addInfo('AudioReactive:digitalmic:pin[]',2,'<i>sck/bclk</i>','I2S SCK');"));
|
||||
uiScript.print(F("dd=addDropdown(ux,'sync:mode');"));
|
||||
uiScript.print(F("addOption(dd,'Off',0);"));
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
uiScript.print(F("addOption(dd,'Send',1);"));
|
||||
#endif
|
||||
uiScript.print(F("addOption(dd,'Receive',2);"));
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
uiScript.print(F("addInfo(ux+':digitalmic:type',1,'<i>requires reboot!</i>');")); // 0 is field type, 1 is actual field
|
||||
uiScript.print(F("addInfo(uxp,0,'<i>sd/data/dout</i>','I2S SD');"));
|
||||
uiScript.print(F("addInfo(uxp,1,'<i>ws/clk/lrck</i>','I2S WS');"));
|
||||
uiScript.print(F("addInfo(uxp,2,'<i>sck/bclk</i>','I2S SCK');"));
|
||||
#if !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3) && !defined(CONFIG_IDF_TARGET_ESP32S3)
|
||||
oappend(SET_F("addInfo('AudioReactive:digitalmic:pin[]',3,'<i>only use -1, 0, 1 or 3</i>','I2S MCLK');"));
|
||||
uiScript.print(F("addInfo(uxp,3,'<i>only use -1, 0, 1 or 3</i>','I2S MCLK');"));
|
||||
#else
|
||||
oappend(SET_F("addInfo('AudioReactive:digitalmic:pin[]',3,'<i>master clock</i>','I2S MCLK');"));
|
||||
uiScript.print(F("addInfo(uxp,3,'<i>master clock</i>','I2S MCLK');"));
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
@@ -1907,8 +2018,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.
|
||||
|
||||
|
||||
@@ -194,8 +194,8 @@ class I2SSource : public AudioSource {
|
||||
virtual void initialize(int8_t i2swsPin = I2S_PIN_NO_CHANGE, int8_t i2ssdPin = I2S_PIN_NO_CHANGE, int8_t i2sckPin = I2S_PIN_NO_CHANGE, int8_t mclkPin = I2S_PIN_NO_CHANGE) {
|
||||
DEBUGSR_PRINTLN(F("I2SSource:: initialize()."));
|
||||
if (i2swsPin != I2S_PIN_NO_CHANGE && i2ssdPin != I2S_PIN_NO_CHANGE) {
|
||||
if (!pinManager.allocatePin(i2swsPin, true, PinOwner::UM_Audioreactive) ||
|
||||
!pinManager.allocatePin(i2ssdPin, false, PinOwner::UM_Audioreactive)) { // #206
|
||||
if (!PinManager::allocatePin(i2swsPin, true, PinOwner::UM_Audioreactive) ||
|
||||
!PinManager::allocatePin(i2ssdPin, false, PinOwner::UM_Audioreactive)) { // #206
|
||||
DEBUGSR_PRINTF("\nAR: Failed to allocate I2S pins: ws=%d, sd=%d\n", i2swsPin, i2ssdPin);
|
||||
return;
|
||||
}
|
||||
@@ -203,7 +203,7 @@ class I2SSource : public AudioSource {
|
||||
|
||||
// i2ssckPin needs special treatment, since it might be unused on PDM mics
|
||||
if (i2sckPin != I2S_PIN_NO_CHANGE) {
|
||||
if (!pinManager.allocatePin(i2sckPin, true, PinOwner::UM_Audioreactive)) {
|
||||
if (!PinManager::allocatePin(i2sckPin, true, PinOwner::UM_Audioreactive)) {
|
||||
DEBUGSR_PRINTF("\nAR: Failed to allocate I2S pins: sck=%d\n", i2sckPin);
|
||||
return;
|
||||
}
|
||||
@@ -249,7 +249,7 @@ class I2SSource : public AudioSource {
|
||||
// Reserve the master clock pin if provided
|
||||
_mclkPin = mclkPin;
|
||||
if (mclkPin != I2S_PIN_NO_CHANGE) {
|
||||
if(!pinManager.allocatePin(mclkPin, true, PinOwner::UM_Audioreactive)) {
|
||||
if(!PinManager::allocatePin(mclkPin, true, PinOwner::UM_Audioreactive)) {
|
||||
DEBUGSR_PRINTF("\nAR: Failed to allocate I2S pin: MCLK=%d\n", mclkPin);
|
||||
return;
|
||||
} else
|
||||
@@ -307,11 +307,11 @@ class I2SSource : public AudioSource {
|
||||
DEBUGSR_PRINTF("Failed to uninstall i2s driver: %d\n", err);
|
||||
return;
|
||||
}
|
||||
if (_pinConfig.ws_io_num != I2S_PIN_NO_CHANGE) pinManager.deallocatePin(_pinConfig.ws_io_num, PinOwner::UM_Audioreactive);
|
||||
if (_pinConfig.data_in_num != I2S_PIN_NO_CHANGE) pinManager.deallocatePin(_pinConfig.data_in_num, PinOwner::UM_Audioreactive);
|
||||
if (_pinConfig.bck_io_num != I2S_PIN_NO_CHANGE) pinManager.deallocatePin(_pinConfig.bck_io_num, PinOwner::UM_Audioreactive);
|
||||
if (_pinConfig.ws_io_num != I2S_PIN_NO_CHANGE) PinManager::deallocatePin(_pinConfig.ws_io_num, PinOwner::UM_Audioreactive);
|
||||
if (_pinConfig.data_in_num != I2S_PIN_NO_CHANGE) PinManager::deallocatePin(_pinConfig.data_in_num, PinOwner::UM_Audioreactive);
|
||||
if (_pinConfig.bck_io_num != I2S_PIN_NO_CHANGE) PinManager::deallocatePin(_pinConfig.bck_io_num, PinOwner::UM_Audioreactive);
|
||||
// Release the master clock pin
|
||||
if (_mclkPin != I2S_PIN_NO_CHANGE) pinManager.deallocatePin(_mclkPin, PinOwner::UM_Audioreactive);
|
||||
if (_mclkPin != I2S_PIN_NO_CHANGE) PinManager::deallocatePin(_mclkPin, PinOwner::UM_Audioreactive);
|
||||
}
|
||||
|
||||
virtual void getSamples(float *buffer, uint16_t num_samples) {
|
||||
@@ -589,7 +589,7 @@ class I2SAdcSource : public I2SSource {
|
||||
void initialize(int8_t audioPin, int8_t = I2S_PIN_NO_CHANGE, int8_t = I2S_PIN_NO_CHANGE, int8_t = I2S_PIN_NO_CHANGE) {
|
||||
DEBUGSR_PRINTLN(F("I2SAdcSource:: initialize()."));
|
||||
_myADCchannel = 0x0F;
|
||||
if(!pinManager.allocatePin(audioPin, false, PinOwner::UM_Audioreactive)) {
|
||||
if(!PinManager::allocatePin(audioPin, false, PinOwner::UM_Audioreactive)) {
|
||||
DEBUGSR_PRINTF("failed to allocate GPIO for audio analog input: %d\n", audioPin);
|
||||
return;
|
||||
}
|
||||
@@ -717,7 +717,7 @@ class I2SAdcSource : public I2SSource {
|
||||
}
|
||||
|
||||
void deinitialize() {
|
||||
pinManager.deallocatePin(_audioPin, PinOwner::UM_Audioreactive);
|
||||
PinManager::deallocatePin(_audioPin, PinOwner::UM_Audioreactive);
|
||||
_initialized = false;
|
||||
_myADCchannel = 0x0F;
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ There are however plans to create a lightweight audioreactive for the 8266, with
|
||||
### using latest _arduinoFFT_ library version 2.x
|
||||
The latest arduinoFFT release version should be used for audioreactive.
|
||||
|
||||
* `build_flags` = `-D USERMOD_AUDIOREACTIVE`
|
||||
* `build_flags` = `-D USERMOD_AUDIOREACTIVE -D sqrt_internal=sqrtf`
|
||||
* `lib_deps`= `kosme/arduinoFFT @ 2.0.1`
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -1,459 +1,459 @@
|
||||
#pragma once
|
||||
|
||||
#include "wled.h"
|
||||
|
||||
/*
|
||||
* Usermod that implements BobLight "ambilight" protocol
|
||||
*
|
||||
* See the accompanying README.md file for more info.
|
||||
*/
|
||||
|
||||
#ifndef BOB_PORT
|
||||
#define BOB_PORT 19333 // Default boblightd port
|
||||
#endif
|
||||
|
||||
class BobLightUsermod : public Usermod {
|
||||
typedef struct _LIGHT {
|
||||
char lightname[5];
|
||||
float hscan[2];
|
||||
float vscan[2];
|
||||
} light_t;
|
||||
|
||||
private:
|
||||
unsigned long lastTime = 0;
|
||||
bool enabled = false;
|
||||
bool initDone = false;
|
||||
|
||||
light_t *lights = nullptr;
|
||||
uint16_t numLights = 0; // 16 + 9 + 16 + 9
|
||||
uint16_t top, bottom, left, right; // will be filled in readFromConfig()
|
||||
uint16_t pct;
|
||||
|
||||
WiFiClient bobClient;
|
||||
WiFiServer *bob;
|
||||
uint16_t bobPort = BOB_PORT;
|
||||
|
||||
static const char _name[];
|
||||
static const char _enabled[];
|
||||
|
||||
/*
|
||||
# boblight
|
||||
# Copyright (C) Bob 2009
|
||||
#
|
||||
# makeboblight.sh created by Adam Boeglin <adamrb@gmail.com>
|
||||
#
|
||||
# boblight is free software: you can redistribute it and/or modify it
|
||||
# under the terms of the GNU General Public License as published by the
|
||||
# Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# boblight 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 General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License along
|
||||
# with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// fills the lights[] array with position & depth of scan for each LED
|
||||
void fillBobLights(int bottom, int left, int top, int right, float pct_scan) {
|
||||
|
||||
int lightcount = 0;
|
||||
int total = top+left+right+bottom;
|
||||
int bcount;
|
||||
|
||||
if (total > strip.getLengthTotal()) {
|
||||
DEBUG_PRINTLN(F("BobLight: Too many lights."));
|
||||
return;
|
||||
}
|
||||
|
||||
// start left part of bottom strip (clockwise direction, 1st half)
|
||||
if (bottom > 0) {
|
||||
bcount = 1;
|
||||
float brange = 100.0/bottom;
|
||||
float bcurrent = 50.0;
|
||||
if (bottom < top) {
|
||||
int diff = top - bottom;
|
||||
brange = 100.0/top;
|
||||
bcurrent -= (diff/2)*brange;
|
||||
}
|
||||
while (bcount <= bottom/2) {
|
||||
float btop = bcurrent - brange;
|
||||
String name = "b"+String(bcount);
|
||||
strncpy(lights[lightcount].lightname, name.c_str(), 4);
|
||||
lights[lightcount].hscan[0] = btop;
|
||||
lights[lightcount].hscan[1] = bcurrent;
|
||||
lights[lightcount].vscan[0] = 100 - pct_scan;
|
||||
lights[lightcount].vscan[1] = 100;
|
||||
lightcount+=1;
|
||||
bcurrent = btop;
|
||||
bcount+=1;
|
||||
}
|
||||
}
|
||||
|
||||
// left side
|
||||
if (left > 0) {
|
||||
int lcount = 1;
|
||||
float lrange = 100.0/left;
|
||||
float lcurrent = 100.0;
|
||||
while (lcount <= left) {
|
||||
float ltop = lcurrent - lrange;
|
||||
String name = "l"+String(lcount);
|
||||
strncpy(lights[lightcount].lightname, name.c_str(), 4);
|
||||
lights[lightcount].hscan[0] = 0;
|
||||
lights[lightcount].hscan[1] = pct_scan;
|
||||
lights[lightcount].vscan[0] = ltop;
|
||||
lights[lightcount].vscan[1] = lcurrent;
|
||||
lightcount+=1;
|
||||
lcurrent = ltop;
|
||||
lcount+=1;
|
||||
}
|
||||
}
|
||||
|
||||
// top side
|
||||
if (top > 0) {
|
||||
int tcount = 1;
|
||||
float trange = 100.0/top;
|
||||
float tcurrent = 0;
|
||||
while (tcount <= top) {
|
||||
float ttop = tcurrent + trange;
|
||||
String name = "t"+String(tcount);
|
||||
strncpy(lights[lightcount].lightname, name.c_str(), 4);
|
||||
lights[lightcount].hscan[0] = tcurrent;
|
||||
lights[lightcount].hscan[1] = ttop;
|
||||
lights[lightcount].vscan[0] = 0;
|
||||
lights[lightcount].vscan[1] = pct_scan;
|
||||
lightcount+=1;
|
||||
tcurrent = ttop;
|
||||
tcount+=1;
|
||||
}
|
||||
}
|
||||
|
||||
// right side
|
||||
if (right > 0) {
|
||||
int rcount = 1;
|
||||
float rrange = 100.0/right;
|
||||
float rcurrent = 0;
|
||||
while (rcount <= right) {
|
||||
float rtop = rcurrent + rrange;
|
||||
String name = "r"+String(rcount);
|
||||
strncpy(lights[lightcount].lightname, name.c_str(), 4);
|
||||
lights[lightcount].hscan[0] = 100-pct_scan;
|
||||
lights[lightcount].hscan[1] = 100;
|
||||
lights[lightcount].vscan[0] = rcurrent;
|
||||
lights[lightcount].vscan[1] = rtop;
|
||||
lightcount+=1;
|
||||
rcurrent = rtop;
|
||||
rcount+=1;
|
||||
}
|
||||
}
|
||||
|
||||
// right side of bottom strip (2nd half)
|
||||
if (bottom > 0) {
|
||||
float brange = 100.0/bottom;
|
||||
float bcurrent = 100;
|
||||
if (bottom < top) {
|
||||
brange = 100.0/top;
|
||||
}
|
||||
while (bcount <= bottom) {
|
||||
float btop = bcurrent - brange;
|
||||
String name = "b"+String(bcount);
|
||||
strncpy(lights[lightcount].lightname, name.c_str(), 4);
|
||||
lights[lightcount].hscan[0] = btop;
|
||||
lights[lightcount].hscan[1] = bcurrent;
|
||||
lights[lightcount].vscan[0] = 100 - pct_scan;
|
||||
lights[lightcount].vscan[1] = 100;
|
||||
lightcount+=1;
|
||||
bcurrent = btop;
|
||||
bcount+=1;
|
||||
}
|
||||
}
|
||||
|
||||
numLights = lightcount;
|
||||
|
||||
#if WLED_DEBUG
|
||||
DEBUG_PRINTLN(F("Fill light data: "));
|
||||
DEBUG_PRINTF_P(PSTR(" lights %d\n"), numLights);
|
||||
for (int i=0; i<numLights; i++) {
|
||||
DEBUG_PRINTF_P(PSTR(" light %s scan %2.1f %2.1f %2.1f %2.1f\n"), lights[i].lightname, lights[i].vscan[0], lights[i].vscan[1], lights[i].hscan[0], lights[i].hscan[1]);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void BobSync() { yield(); } // allow other tasks, should also be used to force pixel redraw (not with WLED)
|
||||
void BobClear() { for (size_t i=0; i<numLights; i++) setRealtimePixel(i, 0, 0, 0, 0); }
|
||||
void pollBob();
|
||||
|
||||
public:
|
||||
|
||||
void setup() override {
|
||||
uint16_t totalLights = bottom + left + top + right;
|
||||
if ( totalLights > strip.getLengthTotal() ) {
|
||||
DEBUG_PRINTLN(F("BobLight: Too many lights."));
|
||||
DEBUG_PRINTF_P(PSTR("%d+%d+%d+%d>%d\n"), bottom, left, top, right, strip.getLengthTotal());
|
||||
totalLights = strip.getLengthTotal();
|
||||
top = bottom = (uint16_t) roundf((float)totalLights * 16.0f / 50.0f);
|
||||
left = right = (uint16_t) roundf((float)totalLights * 9.0f / 50.0f);
|
||||
}
|
||||
lights = new light_t[totalLights];
|
||||
if (lights) fillBobLights(bottom, left, top, right, float(pct)); // will fill numLights
|
||||
else enable(false);
|
||||
initDone = true;
|
||||
}
|
||||
|
||||
void connected() override {
|
||||
// we can only start server when WiFi is connected
|
||||
if (!bob) bob = new WiFiServer(bobPort, 1);
|
||||
bob->begin();
|
||||
bob->setNoDelay(true);
|
||||
}
|
||||
|
||||
void loop() override {
|
||||
if (!enabled || strip.isUpdating()) return;
|
||||
if (millis() - lastTime > 10) {
|
||||
lastTime = millis();
|
||||
pollBob();
|
||||
}
|
||||
}
|
||||
|
||||
void enable(bool en) { enabled = en; }
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
/**
|
||||
* handling of MQTT message
|
||||
* topic only contains stripped topic (part after /wled/MAC)
|
||||
* topic should look like: /swipe with amessage of [up|down]
|
||||
*/
|
||||
bool onMqttMessage(char* topic, char* payload) override {
|
||||
//if (strlen(topic) == 6 && strncmp_P(topic, PSTR("/subtopic"), 6) == 0) {
|
||||
// String action = payload;
|
||||
// if (action == "on") {
|
||||
// enable(true);
|
||||
// return true;
|
||||
// } else if (action == "off") {
|
||||
// enable(false);
|
||||
// return true;
|
||||
// }
|
||||
//}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* subscribe to MQTT topic for controlling usermod
|
||||
*/
|
||||
void onMqttConnect(bool sessionPresent) override {
|
||||
//char subuf[64];
|
||||
//if (mqttDeviceTopic[0] != 0) {
|
||||
// strcpy(subuf, mqttDeviceTopic);
|
||||
// strcat_P(subuf, PSTR("/subtopic"));
|
||||
// mqtt->subscribe(subuf, 0);
|
||||
//}
|
||||
}
|
||||
#endif
|
||||
|
||||
void addToJsonInfo(JsonObject& root) override
|
||||
{
|
||||
JsonObject user = root["u"];
|
||||
if (user.isNull()) user = root.createNestedObject("u");
|
||||
|
||||
JsonArray infoArr = user.createNestedArray(FPSTR(_name));
|
||||
String uiDomString = F("<button class=\"btn btn-xs\" onclick=\"requestJson({");
|
||||
uiDomString += FPSTR(_name);
|
||||
uiDomString += F(":{");
|
||||
uiDomString += FPSTR(_enabled);
|
||||
uiDomString += enabled ? F(":false}});\">") : F(":true}});\">");
|
||||
uiDomString += F("<i class=\"icons ");
|
||||
uiDomString += enabled ? "on" : "off";
|
||||
uiDomString += F("\"></i></button>");
|
||||
infoArr.add(uiDomString);
|
||||
}
|
||||
|
||||
/*
|
||||
* 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
|
||||
{
|
||||
}
|
||||
|
||||
/*
|
||||
* 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 {
|
||||
if (!initDone) return; // prevent crash on boot applyPreset()
|
||||
bool en = enabled;
|
||||
JsonObject um = root[FPSTR(_name)];
|
||||
if (!um.isNull()) {
|
||||
if (um[FPSTR(_enabled)].is<bool>()) {
|
||||
en = um[FPSTR(_enabled)].as<bool>();
|
||||
} else {
|
||||
String str = um[FPSTR(_enabled)]; // checkbox -> off or on
|
||||
en = (bool)(str!="off"); // off is guaranteed to be present
|
||||
}
|
||||
if (en != enabled && lights) {
|
||||
enable(en);
|
||||
if (!enabled && bob && bob->hasClient()) {
|
||||
if (bobClient) bobClient.stop();
|
||||
bobClient = bob->available();
|
||||
BobClear();
|
||||
exitRealtime();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void appendConfigData() override {
|
||||
//oappend(SET_F("dd=addDropdown('usermod','selectfield');"));
|
||||
//oappend(SET_F("addOption(dd,'1st value',0);"));
|
||||
//oappend(SET_F("addOption(dd,'2nd value',1);"));
|
||||
oappend(SET_F("addInfo('BobLight:top',1,'LEDs');")); // 0 is field type, 1 is actual field
|
||||
oappend(SET_F("addInfo('BobLight:bottom',1,'LEDs');")); // 0 is field type, 1 is actual field
|
||||
oappend(SET_F("addInfo('BobLight:left',1,'LEDs');")); // 0 is field type, 1 is actual field
|
||||
oappend(SET_F("addInfo('BobLight:right',1,'LEDs');")); // 0 is field type, 1 is actual field
|
||||
oappend(SET_F("addInfo('BobLight:pct',1,'Depth of scan [%]');")); // 0 is field type, 1 is actual field
|
||||
}
|
||||
|
||||
void addToConfig(JsonObject& root) override {
|
||||
JsonObject umData = root.createNestedObject(FPSTR(_name));
|
||||
umData[FPSTR(_enabled)] = enabled;
|
||||
umData[ "port" ] = bobPort;
|
||||
umData[F("top")] = top;
|
||||
umData[F("bottom")] = bottom;
|
||||
umData[F("left")] = left;
|
||||
umData[F("right")] = right;
|
||||
umData[F("pct")] = pct;
|
||||
}
|
||||
|
||||
bool readFromConfig(JsonObject& root) override {
|
||||
JsonObject umData = root[FPSTR(_name)];
|
||||
bool configComplete = !umData.isNull();
|
||||
|
||||
bool en = enabled;
|
||||
configComplete &= getJsonValue(umData[FPSTR(_enabled)], en);
|
||||
enable(en);
|
||||
|
||||
configComplete &= getJsonValue(umData[ "port" ], bobPort);
|
||||
configComplete &= getJsonValue(umData[F("bottom")], bottom, 16);
|
||||
configComplete &= getJsonValue(umData[F("top")], top, 16);
|
||||
configComplete &= getJsonValue(umData[F("left")], left, 9);
|
||||
configComplete &= getJsonValue(umData[F("right")], right, 9);
|
||||
configComplete &= getJsonValue(umData[F("pct")], pct, 5); // Depth of scan [%]
|
||||
pct = MIN(50,MAX(1,pct));
|
||||
|
||||
uint16_t totalLights = bottom + left + top + right;
|
||||
if (initDone && numLights != totalLights) {
|
||||
if (lights) delete[] lights;
|
||||
setup();
|
||||
}
|
||||
return configComplete;
|
||||
}
|
||||
|
||||
/*
|
||||
* handleOverlayDraw() is called just before every show() (LED strip update frame) after effects have set the colors.
|
||||
* Use this to blank out some LEDs or set them to a different color regardless of the set effect mode.
|
||||
* Commonly used for custom clocks (Cronixie, 7 segment)
|
||||
*/
|
||||
void handleOverlayDraw() override {
|
||||
//strip.setPixelColor(0, RGBW32(0,0,0,0)) // set the first pixel to black
|
||||
}
|
||||
|
||||
uint16_t getId() override { return USERMOD_ID_BOBLIGHT; }
|
||||
|
||||
};
|
||||
|
||||
// strings to reduce flash memory usage (used more than twice)
|
||||
const char BobLightUsermod::_name[] PROGMEM = "BobLight";
|
||||
const char BobLightUsermod::_enabled[] PROGMEM = "enabled";
|
||||
|
||||
// main boblight handling (definition here prevents inlining)
|
||||
void BobLightUsermod::pollBob() {
|
||||
|
||||
//check if there are any new clients
|
||||
if (bob && bob->hasClient()) {
|
||||
//find free/disconnected spot
|
||||
if (!bobClient || !bobClient.connected()) {
|
||||
if (bobClient) bobClient.stop();
|
||||
bobClient = bob->available();
|
||||
DEBUG_PRINTLN(F("Boblight: Client connected."));
|
||||
}
|
||||
//no free/disconnected spot so reject
|
||||
WiFiClient bobClientTmp = bob->available();
|
||||
bobClientTmp.stop();
|
||||
BobClear();
|
||||
exitRealtime();
|
||||
}
|
||||
|
||||
//check clients for data
|
||||
if (bobClient && bobClient.connected()) {
|
||||
realtimeLock(realtimeTimeoutMs); // lock strip as we have a client connected
|
||||
|
||||
//get data from the client
|
||||
while (bobClient.available()) {
|
||||
String input = bobClient.readStringUntil('\n');
|
||||
// DEBUG_PRINT(F("Client: ")); DEBUG_PRINTLN(input); // may be to stressful on Serial
|
||||
if (input.startsWith(F("hello"))) {
|
||||
DEBUG_PRINTLN(F("hello"));
|
||||
bobClient.print(F("hello\n"));
|
||||
} else if (input.startsWith(F("ping"))) {
|
||||
DEBUG_PRINTLN(F("ping 1"));
|
||||
bobClient.print(F("ping 1\n"));
|
||||
} else if (input.startsWith(F("get version"))) {
|
||||
DEBUG_PRINTLN(F("version 5"));
|
||||
bobClient.print(F("version 5\n"));
|
||||
} else if (input.startsWith(F("get lights"))) {
|
||||
char tmp[64];
|
||||
String answer = "";
|
||||
sprintf_P(tmp, PSTR("lights %d\n"), numLights);
|
||||
DEBUG_PRINT(tmp);
|
||||
answer.concat(tmp);
|
||||
for (int i=0; i<numLights; i++) {
|
||||
sprintf_P(tmp, PSTR("light %s scan %2.1f %2.1f %2.1f %2.1f\n"), lights[i].lightname, lights[i].vscan[0], lights[i].vscan[1], lights[i].hscan[0], lights[i].hscan[1]);
|
||||
DEBUG_PRINT(tmp);
|
||||
answer.concat(tmp);
|
||||
}
|
||||
bobClient.print(answer);
|
||||
} else if (input.startsWith(F("set priority"))) {
|
||||
DEBUG_PRINTLN(F("set priority not implemented"));
|
||||
// not implemented
|
||||
} else if (input.startsWith(F("set light "))) { // <id> <cmd in rgb, speed, interpolation> <value> ...
|
||||
input.remove(0,10);
|
||||
String tmp = input.substring(0,input.indexOf(' '));
|
||||
|
||||
int light_id = -1;
|
||||
for (uint16_t i=0; i<numLights; i++) {
|
||||
if (strncmp(lights[i].lightname, tmp.c_str(), 4) == 0) {
|
||||
light_id = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (light_id == -1) return;
|
||||
|
||||
input.remove(0,input.indexOf(' ')+1);
|
||||
if (input.startsWith(F("rgb "))) {
|
||||
input.remove(0,4);
|
||||
tmp = input.substring(0,input.indexOf(' '));
|
||||
uint8_t red = (uint8_t)(255.0f*tmp.toFloat());
|
||||
input.remove(0,input.indexOf(' ')+1); // remove first float value
|
||||
tmp = input.substring(0,input.indexOf(' '));
|
||||
uint8_t green = (uint8_t)(255.0f*tmp.toFloat());
|
||||
input.remove(0,input.indexOf(' ')+1); // remove second float value
|
||||
tmp = input.substring(0,input.indexOf(' '));
|
||||
uint8_t blue = (uint8_t)(255.0f*tmp.toFloat());
|
||||
|
||||
//strip.setPixelColor(light_id, RGBW32(red, green, blue, 0));
|
||||
setRealtimePixel(light_id, red, green, blue, 0);
|
||||
} // currently no support for interpolation or speed, we just ignore this
|
||||
} else if (input.startsWith("sync")) {
|
||||
BobSync();
|
||||
} else {
|
||||
// Client sent gibberish
|
||||
DEBUG_PRINTLN(F("Client sent gibberish."));
|
||||
bobClient.stop();
|
||||
bobClient = bob->available();
|
||||
BobClear();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#pragma once
|
||||
|
||||
#include "wled.h"
|
||||
|
||||
/*
|
||||
* Usermod that implements BobLight "ambilight" protocol
|
||||
*
|
||||
* See the accompanying README.md file for more info.
|
||||
*/
|
||||
|
||||
#ifndef BOB_PORT
|
||||
#define BOB_PORT 19333 // Default boblightd port
|
||||
#endif
|
||||
|
||||
class BobLightUsermod : public Usermod {
|
||||
typedef struct _LIGHT {
|
||||
char lightname[5];
|
||||
float hscan[2];
|
||||
float vscan[2];
|
||||
} light_t;
|
||||
|
||||
private:
|
||||
unsigned long lastTime = 0;
|
||||
bool enabled = false;
|
||||
bool initDone = false;
|
||||
|
||||
light_t *lights = nullptr;
|
||||
uint16_t numLights = 0; // 16 + 9 + 16 + 9
|
||||
uint16_t top, bottom, left, right; // will be filled in readFromConfig()
|
||||
uint16_t pct;
|
||||
|
||||
WiFiClient bobClient;
|
||||
WiFiServer *bob;
|
||||
uint16_t bobPort = BOB_PORT;
|
||||
|
||||
static const char _name[];
|
||||
static const char _enabled[];
|
||||
|
||||
/*
|
||||
# boblight
|
||||
# Copyright (C) Bob 2009
|
||||
#
|
||||
# makeboblight.sh created by Adam Boeglin <adamrb@gmail.com>
|
||||
#
|
||||
# boblight is free software: you can redistribute it and/or modify it
|
||||
# under the terms of the GNU General Public License as published by the
|
||||
# Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# boblight 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 General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License along
|
||||
# with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// fills the lights[] array with position & depth of scan for each LED
|
||||
void fillBobLights(int bottom, int left, int top, int right, float pct_scan) {
|
||||
|
||||
int lightcount = 0;
|
||||
int total = top+left+right+bottom;
|
||||
int bcount;
|
||||
|
||||
if (total > strip.getLengthTotal()) {
|
||||
DEBUG_PRINTLN(F("BobLight: Too many lights."));
|
||||
return;
|
||||
}
|
||||
|
||||
// start left part of bottom strip (clockwise direction, 1st half)
|
||||
if (bottom > 0) {
|
||||
bcount = 1;
|
||||
float brange = 100.0/bottom;
|
||||
float bcurrent = 50.0;
|
||||
if (bottom < top) {
|
||||
int diff = top - bottom;
|
||||
brange = 100.0/top;
|
||||
bcurrent -= (diff/2)*brange;
|
||||
}
|
||||
while (bcount <= bottom/2) {
|
||||
float btop = bcurrent - brange;
|
||||
String name = "b"+String(bcount);
|
||||
strncpy(lights[lightcount].lightname, name.c_str(), 4);
|
||||
lights[lightcount].hscan[0] = btop;
|
||||
lights[lightcount].hscan[1] = bcurrent;
|
||||
lights[lightcount].vscan[0] = 100 - pct_scan;
|
||||
lights[lightcount].vscan[1] = 100;
|
||||
lightcount+=1;
|
||||
bcurrent = btop;
|
||||
bcount+=1;
|
||||
}
|
||||
}
|
||||
|
||||
// left side
|
||||
if (left > 0) {
|
||||
int lcount = 1;
|
||||
float lrange = 100.0/left;
|
||||
float lcurrent = 100.0;
|
||||
while (lcount <= left) {
|
||||
float ltop = lcurrent - lrange;
|
||||
String name = "l"+String(lcount);
|
||||
strncpy(lights[lightcount].lightname, name.c_str(), 4);
|
||||
lights[lightcount].hscan[0] = 0;
|
||||
lights[lightcount].hscan[1] = pct_scan;
|
||||
lights[lightcount].vscan[0] = ltop;
|
||||
lights[lightcount].vscan[1] = lcurrent;
|
||||
lightcount+=1;
|
||||
lcurrent = ltop;
|
||||
lcount+=1;
|
||||
}
|
||||
}
|
||||
|
||||
// top side
|
||||
if (top > 0) {
|
||||
int tcount = 1;
|
||||
float trange = 100.0/top;
|
||||
float tcurrent = 0;
|
||||
while (tcount <= top) {
|
||||
float ttop = tcurrent + trange;
|
||||
String name = "t"+String(tcount);
|
||||
strncpy(lights[lightcount].lightname, name.c_str(), 4);
|
||||
lights[lightcount].hscan[0] = tcurrent;
|
||||
lights[lightcount].hscan[1] = ttop;
|
||||
lights[lightcount].vscan[0] = 0;
|
||||
lights[lightcount].vscan[1] = pct_scan;
|
||||
lightcount+=1;
|
||||
tcurrent = ttop;
|
||||
tcount+=1;
|
||||
}
|
||||
}
|
||||
|
||||
// right side
|
||||
if (right > 0) {
|
||||
int rcount = 1;
|
||||
float rrange = 100.0/right;
|
||||
float rcurrent = 0;
|
||||
while (rcount <= right) {
|
||||
float rtop = rcurrent + rrange;
|
||||
String name = "r"+String(rcount);
|
||||
strncpy(lights[lightcount].lightname, name.c_str(), 4);
|
||||
lights[lightcount].hscan[0] = 100-pct_scan;
|
||||
lights[lightcount].hscan[1] = 100;
|
||||
lights[lightcount].vscan[0] = rcurrent;
|
||||
lights[lightcount].vscan[1] = rtop;
|
||||
lightcount+=1;
|
||||
rcurrent = rtop;
|
||||
rcount+=1;
|
||||
}
|
||||
}
|
||||
|
||||
// right side of bottom strip (2nd half)
|
||||
if (bottom > 0) {
|
||||
float brange = 100.0/bottom;
|
||||
float bcurrent = 100;
|
||||
if (bottom < top) {
|
||||
brange = 100.0/top;
|
||||
}
|
||||
while (bcount <= bottom) {
|
||||
float btop = bcurrent - brange;
|
||||
String name = "b"+String(bcount);
|
||||
strncpy(lights[lightcount].lightname, name.c_str(), 4);
|
||||
lights[lightcount].hscan[0] = btop;
|
||||
lights[lightcount].hscan[1] = bcurrent;
|
||||
lights[lightcount].vscan[0] = 100 - pct_scan;
|
||||
lights[lightcount].vscan[1] = 100;
|
||||
lightcount+=1;
|
||||
bcurrent = btop;
|
||||
bcount+=1;
|
||||
}
|
||||
}
|
||||
|
||||
numLights = lightcount;
|
||||
|
||||
#if WLED_DEBUG
|
||||
DEBUG_PRINTLN(F("Fill light data: "));
|
||||
DEBUG_PRINTF_P(PSTR(" lights %d\n"), numLights);
|
||||
for (int i=0; i<numLights; i++) {
|
||||
DEBUG_PRINTF_P(PSTR(" light %s scan %2.1f %2.1f %2.1f %2.1f\n"), lights[i].lightname, lights[i].vscan[0], lights[i].vscan[1], lights[i].hscan[0], lights[i].hscan[1]);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void BobSync() { yield(); } // allow other tasks, should also be used to force pixel redraw (not with WLED)
|
||||
void BobClear() { for (size_t i=0; i<numLights; i++) setRealtimePixel(i, 0, 0, 0, 0); }
|
||||
void pollBob();
|
||||
|
||||
public:
|
||||
|
||||
void setup() override {
|
||||
uint16_t totalLights = bottom + left + top + right;
|
||||
if ( totalLights > strip.getLengthTotal() ) {
|
||||
DEBUG_PRINTLN(F("BobLight: Too many lights."));
|
||||
DEBUG_PRINTF_P(PSTR("%d+%d+%d+%d>%d\n"), bottom, left, top, right, strip.getLengthTotal());
|
||||
totalLights = strip.getLengthTotal();
|
||||
top = bottom = (uint16_t) roundf((float)totalLights * 16.0f / 50.0f);
|
||||
left = right = (uint16_t) roundf((float)totalLights * 9.0f / 50.0f);
|
||||
}
|
||||
lights = new light_t[totalLights];
|
||||
if (lights) fillBobLights(bottom, left, top, right, float(pct)); // will fill numLights
|
||||
else enable(false);
|
||||
initDone = true;
|
||||
}
|
||||
|
||||
void connected() override {
|
||||
// we can only start server when WiFi is connected
|
||||
if (!bob) bob = new WiFiServer(bobPort, 1);
|
||||
bob->begin();
|
||||
bob->setNoDelay(true);
|
||||
}
|
||||
|
||||
void loop() override {
|
||||
if (!enabled || strip.isUpdating()) return;
|
||||
if (millis() - lastTime > 10) {
|
||||
lastTime = millis();
|
||||
pollBob();
|
||||
}
|
||||
}
|
||||
|
||||
void enable(bool en) { enabled = en; }
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
/**
|
||||
* handling of MQTT message
|
||||
* topic only contains stripped topic (part after /wled/MAC)
|
||||
* topic should look like: /swipe with amessage of [up|down]
|
||||
*/
|
||||
bool onMqttMessage(char* topic, char* payload) override {
|
||||
//if (strlen(topic) == 6 && strncmp_P(topic, PSTR("/subtopic"), 6) == 0) {
|
||||
// String action = payload;
|
||||
// if (action == "on") {
|
||||
// enable(true);
|
||||
// return true;
|
||||
// } else if (action == "off") {
|
||||
// enable(false);
|
||||
// return true;
|
||||
// }
|
||||
//}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* subscribe to MQTT topic for controlling usermod
|
||||
*/
|
||||
void onMqttConnect(bool sessionPresent) override {
|
||||
//char subuf[64];
|
||||
//if (mqttDeviceTopic[0] != 0) {
|
||||
// strcpy(subuf, mqttDeviceTopic);
|
||||
// strcat_P(subuf, PSTR("/subtopic"));
|
||||
// mqtt->subscribe(subuf, 0);
|
||||
//}
|
||||
}
|
||||
#endif
|
||||
|
||||
void addToJsonInfo(JsonObject& root) override
|
||||
{
|
||||
JsonObject user = root["u"];
|
||||
if (user.isNull()) user = root.createNestedObject("u");
|
||||
|
||||
JsonArray infoArr = user.createNestedArray(FPSTR(_name));
|
||||
String uiDomString = F("<button class=\"btn btn-xs\" onclick=\"requestJson({");
|
||||
uiDomString += FPSTR(_name);
|
||||
uiDomString += F(":{");
|
||||
uiDomString += FPSTR(_enabled);
|
||||
uiDomString += enabled ? F(":false}});\">") : F(":true}});\">");
|
||||
uiDomString += F("<i class=\"icons ");
|
||||
uiDomString += enabled ? "on" : "off";
|
||||
uiDomString += F("\"></i></button>");
|
||||
infoArr.add(uiDomString);
|
||||
}
|
||||
|
||||
/*
|
||||
* 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
|
||||
{
|
||||
}
|
||||
|
||||
/*
|
||||
* 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 {
|
||||
if (!initDone) return; // prevent crash on boot applyPreset()
|
||||
bool en = enabled;
|
||||
JsonObject um = root[FPSTR(_name)];
|
||||
if (!um.isNull()) {
|
||||
if (um[FPSTR(_enabled)].is<bool>()) {
|
||||
en = um[FPSTR(_enabled)].as<bool>();
|
||||
} else {
|
||||
String str = um[FPSTR(_enabled)]; // checkbox -> off or on
|
||||
en = (bool)(str!="off"); // off is guaranteed to be present
|
||||
}
|
||||
if (en != enabled && lights) {
|
||||
enable(en);
|
||||
if (!enabled && bob && bob->hasClient()) {
|
||||
if (bobClient) bobClient.stop();
|
||||
bobClient = bob->available();
|
||||
BobClear();
|
||||
exitRealtime();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void appendConfigData() override {
|
||||
//oappend(F("dd=addDropdown('usermod','selectfield');"));
|
||||
//oappend(F("addOption(dd,'1st value',0);"));
|
||||
//oappend(F("addOption(dd,'2nd value',1);"));
|
||||
oappend(F("addInfo('BobLight:top',1,'LEDs');")); // 0 is field type, 1 is actual field
|
||||
oappend(F("addInfo('BobLight:bottom',1,'LEDs');")); // 0 is field type, 1 is actual field
|
||||
oappend(F("addInfo('BobLight:left',1,'LEDs');")); // 0 is field type, 1 is actual field
|
||||
oappend(F("addInfo('BobLight:right',1,'LEDs');")); // 0 is field type, 1 is actual field
|
||||
oappend(F("addInfo('BobLight:pct',1,'Depth of scan [%]');")); // 0 is field type, 1 is actual field
|
||||
}
|
||||
|
||||
void addToConfig(JsonObject& root) override {
|
||||
JsonObject umData = root.createNestedObject(FPSTR(_name));
|
||||
umData[FPSTR(_enabled)] = enabled;
|
||||
umData[ "port" ] = bobPort;
|
||||
umData[F("top")] = top;
|
||||
umData[F("bottom")] = bottom;
|
||||
umData[F("left")] = left;
|
||||
umData[F("right")] = right;
|
||||
umData[F("pct")] = pct;
|
||||
}
|
||||
|
||||
bool readFromConfig(JsonObject& root) override {
|
||||
JsonObject umData = root[FPSTR(_name)];
|
||||
bool configComplete = !umData.isNull();
|
||||
|
||||
bool en = enabled;
|
||||
configComplete &= getJsonValue(umData[FPSTR(_enabled)], en);
|
||||
enable(en);
|
||||
|
||||
configComplete &= getJsonValue(umData[ "port" ], bobPort);
|
||||
configComplete &= getJsonValue(umData[F("bottom")], bottom, 16);
|
||||
configComplete &= getJsonValue(umData[F("top")], top, 16);
|
||||
configComplete &= getJsonValue(umData[F("left")], left, 9);
|
||||
configComplete &= getJsonValue(umData[F("right")], right, 9);
|
||||
configComplete &= getJsonValue(umData[F("pct")], pct, 5); // Depth of scan [%]
|
||||
pct = MIN(50,MAX(1,pct));
|
||||
|
||||
uint16_t totalLights = bottom + left + top + right;
|
||||
if (initDone && numLights != totalLights) {
|
||||
if (lights) delete[] lights;
|
||||
setup();
|
||||
}
|
||||
return configComplete;
|
||||
}
|
||||
|
||||
/*
|
||||
* handleOverlayDraw() is called just before every show() (LED strip update frame) after effects have set the colors.
|
||||
* Use this to blank out some LEDs or set them to a different color regardless of the set effect mode.
|
||||
* Commonly used for custom clocks (Cronixie, 7 segment)
|
||||
*/
|
||||
void handleOverlayDraw() override {
|
||||
//strip.setPixelColor(0, RGBW32(0,0,0,0)) // set the first pixel to black
|
||||
}
|
||||
|
||||
uint16_t getId() override { return USERMOD_ID_BOBLIGHT; }
|
||||
|
||||
};
|
||||
|
||||
// strings to reduce flash memory usage (used more than twice)
|
||||
const char BobLightUsermod::_name[] PROGMEM = "BobLight";
|
||||
const char BobLightUsermod::_enabled[] PROGMEM = "enabled";
|
||||
|
||||
// main boblight handling (definition here prevents inlining)
|
||||
void BobLightUsermod::pollBob() {
|
||||
|
||||
//check if there are any new clients
|
||||
if (bob && bob->hasClient()) {
|
||||
//find free/disconnected spot
|
||||
if (!bobClient || !bobClient.connected()) {
|
||||
if (bobClient) bobClient.stop();
|
||||
bobClient = bob->available();
|
||||
DEBUG_PRINTLN(F("Boblight: Client connected."));
|
||||
}
|
||||
//no free/disconnected spot so reject
|
||||
WiFiClient bobClientTmp = bob->available();
|
||||
bobClientTmp.stop();
|
||||
BobClear();
|
||||
exitRealtime();
|
||||
}
|
||||
|
||||
//check clients for data
|
||||
if (bobClient && bobClient.connected()) {
|
||||
realtimeLock(realtimeTimeoutMs); // lock strip as we have a client connected
|
||||
|
||||
//get data from the client
|
||||
while (bobClient.available()) {
|
||||
String input = bobClient.readStringUntil('\n');
|
||||
// DEBUG_PRINT(F("Client: ")); DEBUG_PRINTLN(input); // may be to stressful on Serial
|
||||
if (input.startsWith(F("hello"))) {
|
||||
DEBUG_PRINTLN(F("hello"));
|
||||
bobClient.print(F("hello\n"));
|
||||
} else if (input.startsWith(F("ping"))) {
|
||||
DEBUG_PRINTLN(F("ping 1"));
|
||||
bobClient.print(F("ping 1\n"));
|
||||
} else if (input.startsWith(F("get version"))) {
|
||||
DEBUG_PRINTLN(F("version 5"));
|
||||
bobClient.print(F("version 5\n"));
|
||||
} else if (input.startsWith(F("get lights"))) {
|
||||
char tmp[64];
|
||||
String answer = "";
|
||||
sprintf_P(tmp, PSTR("lights %d\n"), numLights);
|
||||
DEBUG_PRINT(tmp);
|
||||
answer.concat(tmp);
|
||||
for (int i=0; i<numLights; i++) {
|
||||
sprintf_P(tmp, PSTR("light %s scan %2.1f %2.1f %2.1f %2.1f\n"), lights[i].lightname, lights[i].vscan[0], lights[i].vscan[1], lights[i].hscan[0], lights[i].hscan[1]);
|
||||
DEBUG_PRINT(tmp);
|
||||
answer.concat(tmp);
|
||||
}
|
||||
bobClient.print(answer);
|
||||
} else if (input.startsWith(F("set priority"))) {
|
||||
DEBUG_PRINTLN(F("set priority not implemented"));
|
||||
// not implemented
|
||||
} else if (input.startsWith(F("set light "))) { // <id> <cmd in rgb, speed, interpolation> <value> ...
|
||||
input.remove(0,10);
|
||||
String tmp = input.substring(0,input.indexOf(' '));
|
||||
|
||||
int light_id = -1;
|
||||
for (uint16_t i=0; i<numLights; i++) {
|
||||
if (strncmp(lights[i].lightname, tmp.c_str(), 4) == 0) {
|
||||
light_id = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (light_id == -1) return;
|
||||
|
||||
input.remove(0,input.indexOf(' ')+1);
|
||||
if (input.startsWith(F("rgb "))) {
|
||||
input.remove(0,4);
|
||||
tmp = input.substring(0,input.indexOf(' '));
|
||||
uint8_t red = (uint8_t)(255.0f*tmp.toFloat());
|
||||
input.remove(0,input.indexOf(' ')+1); // remove first float value
|
||||
tmp = input.substring(0,input.indexOf(' '));
|
||||
uint8_t green = (uint8_t)(255.0f*tmp.toFloat());
|
||||
input.remove(0,input.indexOf(' ')+1); // remove second float value
|
||||
tmp = input.substring(0,input.indexOf(' '));
|
||||
uint8_t blue = (uint8_t)(255.0f*tmp.toFloat());
|
||||
|
||||
//strip.setPixelColor(light_id, RGBW32(red, green, blue, 0));
|
||||
setRealtimePixel(light_id, red, green, blue, 0);
|
||||
} // currently no support for interpolation or speed, we just ignore this
|
||||
} else if (input.startsWith("sync")) {
|
||||
BobSync();
|
||||
} else {
|
||||
// Client sent gibberish
|
||||
DEBUG_PRINTLN(F("Client sent gibberish."));
|
||||
bobClient.stop();
|
||||
bobClient = bob->available();
|
||||
BobClear();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,6 +86,6 @@ Example **usermods_list.cpp**:
|
||||
|
||||
void registerUsermods()
|
||||
{
|
||||
usermods.add(new MPU6050Driver());
|
||||
UsermodManager::add(new MPU6050Driver());
|
||||
}
|
||||
```
|
||||
|
||||
@@ -163,7 +163,7 @@ class GyroSurge : public Usermod {
|
||||
void loop() {
|
||||
// get IMU data
|
||||
um_data_t *um_data;
|
||||
if (!usermods.getUMData(&um_data, USERMOD_ID_IMU)) {
|
||||
if (!UsermodManager::getUMData(&um_data, USERMOD_ID_IMU)) {
|
||||
// Apply max
|
||||
strip.getSegment(0).fadeToBlackBy(max);
|
||||
return;
|
||||
|
||||
@@ -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,11 +157,14 @@ 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) {
|
||||
irqBound = pinManager.allocatePin(config.interruptPin, false, PinOwner::UM_IMU);
|
||||
irqBound = PinManager::allocatePin(config.interruptPin, false, PinOwner::UM_IMU);
|
||||
if (!irqBound) { DEBUG_PRINTLN(F("MPU6050: IRQ pin already in use.")); return; }
|
||||
pinMode(config.interruptPin, INPUT);
|
||||
};
|
||||
@@ -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;
|
||||
|
||||
@@ -403,12 +408,12 @@ class MPU6050Driver : public Usermod {
|
||||
// Previously loaded and config changed
|
||||
if (irqBound && ((old_cfg.interruptPin != config.interruptPin) || !config.enabled)) {
|
||||
detachInterrupt(old_cfg.interruptPin);
|
||||
pinManager.deallocatePin(old_cfg.interruptPin, PinOwner::UM_IMU);
|
||||
PinManager::deallocatePin(old_cfg.interruptPin, PinOwner::UM_IMU);
|
||||
irqBound = false;
|
||||
}
|
||||
|
||||
// Just re-init
|
||||
setup();
|
||||
// Re-call setup on the next loop()
|
||||
configDirty = true;
|
||||
}
|
||||
|
||||
return configComplete;
|
||||
|
||||
@@ -19,7 +19,7 @@ Example `usermods_list.cpp`:
|
||||
|
||||
void registerUsermods()
|
||||
{
|
||||
usermods.add(new UsermodMqttSwitch());
|
||||
UsermodManager::add(new UsermodMqttSwitch());
|
||||
}
|
||||
```
|
||||
|
||||
@@ -33,7 +33,7 @@ board = esp12e
|
||||
platform = ${common.platform_wled_default}
|
||||
board_build.ldscript = ${common.ldscript_4m1m}
|
||||
build_flags = ${common.build_flags_esp8266}
|
||||
-D LEDPIN=3
|
||||
-D DATA_PINS=3
|
||||
-D BTNPIN=4
|
||||
-D RLYPIN=12
|
||||
-D RLYMDE=1
|
||||
|
||||
@@ -41,7 +41,7 @@ When a relay is switched, a message is published:
|
||||
|
||||
## Usermod installation
|
||||
|
||||
1. Register the usermod by adding `#include "../usermods/multi_relay/usermod_multi_relay.h"` at the top and `usermods.add(new MultiRelay());` at the bottom of `usermods_list.cpp`.
|
||||
1. Register the usermod by adding `#include "../usermods/multi_relay/usermod_multi_relay.h"` at the top and `UsermodManager::add(new MultiRelay());` at the bottom of `usermods_list.cpp`.
|
||||
or
|
||||
2. Use `#define USERMOD_MULTI_RELAY` in wled.h or `-D USERMOD_MULTI_RELAY` in your platformio.ini
|
||||
|
||||
@@ -90,9 +90,9 @@ void registerUsermods()
|
||||
* || || ||
|
||||
* \/ \/ \/
|
||||
*/
|
||||
//usermods.add(new MyExampleUsermod());
|
||||
//usermods.add(new UsermodTemperature());
|
||||
usermods.add(new MultiRelay());
|
||||
//UsermodManager::add(new MyExampleUsermod());
|
||||
//UsermodManager::add(new UsermodTemperature());
|
||||
UsermodManager::add(new MultiRelay());
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
@@ -264,7 +264,7 @@ void MultiRelay::handleOffTimer() {
|
||||
void MultiRelay::InitHtmlAPIHandle() { // https://github.com/me-no-dev/ESPAsyncWebServer
|
||||
DEBUG_PRINTLN(F("Relays: Initialize HTML API"));
|
||||
|
||||
server.on(SET_F("/relays"), HTTP_GET, [this](AsyncWebServerRequest *request) {
|
||||
server.on(F("/relays"), HTTP_GET, [this](AsyncWebServerRequest *request) {
|
||||
DEBUG_PRINTLN(F("Relays: HTML API"));
|
||||
String janswer;
|
||||
String error = "";
|
||||
@@ -516,7 +516,7 @@ void MultiRelay::setup() {
|
||||
if (!_relay[i].external) _relay[i].state = !offMode;
|
||||
state |= (uint8_t)(_relay[i].invert ? !_relay[i].state : _relay[i].state) << pin;
|
||||
} else if (_relay[i].pin<100 && _relay[i].pin>=0) {
|
||||
if (pinManager.allocatePin(_relay[i].pin,true, PinOwner::UM_MultiRelay)) {
|
||||
if (PinManager::allocatePin(_relay[i].pin,true, PinOwner::UM_MultiRelay)) {
|
||||
if (!_relay[i].external) _relay[i].state = !offMode;
|
||||
switchRelay(i, _relay[i].state);
|
||||
_relay[i].active = false;
|
||||
@@ -765,10 +765,10 @@ void MultiRelay::addToConfig(JsonObject &root) {
|
||||
}
|
||||
|
||||
void MultiRelay::appendConfigData() {
|
||||
oappend(SET_F("addInfo('MultiRelay:PCF8574-address',1,'<i>(not hex!)</i>');"));
|
||||
oappend(SET_F("addInfo('MultiRelay:broadcast-sec',1,'(MQTT message)');"));
|
||||
//oappend(SET_F("addInfo('MultiRelay:relay-0:pin',1,'(use -1 for PCF8574)');"));
|
||||
oappend(SET_F("d.extra.push({'MultiRelay':{pin:[['P0',100],['P1',101],['P2',102],['P3',103],['P4',104],['P5',105],['P6',106],['P7',107]]}});"));
|
||||
oappend(F("addInfo('MultiRelay:PCF8574-address',1,'<i>(not hex!)</i>');"));
|
||||
oappend(F("addInfo('MultiRelay:broadcast-sec',1,'(MQTT message)');"));
|
||||
//oappend(F("addInfo('MultiRelay:relay-0:pin',1,'(use -1 for PCF8574)');"));
|
||||
oappend(F("d.extra.push({'MultiRelay':{pin:[['P0',100],['P1',101],['P2',102],['P3',103],['P4',104],['P5',105],['P6',106],['P7',107]]}});"));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -817,7 +817,7 @@ bool MultiRelay::readFromConfig(JsonObject &root) {
|
||||
// deallocate all pins 1st
|
||||
for (int i=0; i<MULTI_RELAY_MAX_RELAYS; i++)
|
||||
if (oldPin[i]>=0 && oldPin[i]<100) {
|
||||
pinManager.deallocatePin(oldPin[i], PinOwner::UM_MultiRelay);
|
||||
PinManager::deallocatePin(oldPin[i], PinOwner::UM_MultiRelay);
|
||||
}
|
||||
// allocate new pins
|
||||
setup();
|
||||
|
||||
254
usermods/pixels_dice_tray/README.md
Normal file
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
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
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
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
BIN
usermods/pixels_dice_tray/images/effect.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
BIN
usermods/pixels_dice_tray/images/info.webp
Normal file
BIN
usermods/pixels_dice_tray/images/info.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 24 KiB |
BIN
usermods/pixels_dice_tray/images/roll_plot.png
Normal file
BIN
usermods/pixels_dice_tray/images/roll_plot.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 9.8 KiB |
BIN
usermods/pixels_dice_tray/images/status.webp
Normal file
BIN
usermods/pixels_dice_tray/images/status.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 24 KiB |
124
usermods/pixels_dice_tray/led_effects.h
Normal file
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
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
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
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
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(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(F("ddr=addDropdown('DiceTray','rotation');"));
|
||||
oappend(F("addOption(ddr,'0 deg',0);"));
|
||||
oappend(F("addOption(ddr,'90 deg',1);"));
|
||||
oappend(F("addOption(ddr,'180 deg',2);"));
|
||||
oappend(F("addOption(ddr,'270 deg',3);"));
|
||||
oappend(F(
|
||||
"addInfo('DiceTray:rotation',1,'<br><i class=\"warn\">DO NOT CHANGE "
|
||||
"SPI PINS.</i><br><i class=\"warn\">CHANGES ARE IGNORED.</i>','');"));
|
||||
oappend(F("addInfo('TFT:pin[]',0,'','SPI CS');"));
|
||||
oappend(F("addInfo('TFT:pin[]',1,'','SPI DC');"));
|
||||
oappend(F("addInfo('TFT:pin[]',2,'','SPI RST');"));
|
||||
oappend(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
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
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
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
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() {}
|
||||
};
|
||||
@@ -29,13 +29,13 @@ class PwmOutput {
|
||||
return;
|
||||
|
||||
DEBUG_PRINTF("pwm_output[%d]: setup to freq %d\n", pin_, freq_);
|
||||
if (!pinManager.allocatePin(pin_, true, PinOwner::UM_PWM_OUTPUTS))
|
||||
if (!PinManager::allocatePin(pin_, true, PinOwner::UM_PWM_OUTPUTS))
|
||||
return;
|
||||
|
||||
channel_ = pinManager.allocateLedc(1);
|
||||
channel_ = PinManager::allocateLedc(1);
|
||||
if (channel_ == 255) {
|
||||
DEBUG_PRINTF("pwm_output[%d]: failed to quire ledc\n", pin_);
|
||||
pinManager.deallocatePin(pin_, PinOwner::UM_PWM_OUTPUTS);
|
||||
PinManager::deallocatePin(pin_, PinOwner::UM_PWM_OUTPUTS);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -49,9 +49,9 @@ class PwmOutput {
|
||||
DEBUG_PRINTF("pwm_output[%d]: close\n", pin_);
|
||||
if (!enabled_)
|
||||
return;
|
||||
pinManager.deallocatePin(pin_, PinOwner::UM_PWM_OUTPUTS);
|
||||
PinManager::deallocatePin(pin_, PinOwner::UM_PWM_OUTPUTS);
|
||||
if (channel_ != 255)
|
||||
pinManager.deallocateLedc(channel_, 1);
|
||||
PinManager::deallocateLedc(channel_, 1);
|
||||
channel_ = 255;
|
||||
duty_ = 0.0f;
|
||||
enabled_ = false;
|
||||
|
||||
@@ -129,7 +129,7 @@ class QuinLEDAnPentaUsermod : public Usermod
|
||||
void initOledDisplay()
|
||||
{
|
||||
PinManagerPinType pins[5] = { { oledSpiClk, true }, { oledSpiData, true }, { oledSpiCs, true }, { oledSpiDc, true }, { oledSpiRst, true } };
|
||||
if (!pinManager.allocateMultiplePins(pins, 5, PinOwner::UM_QuinLEDAnPenta)) {
|
||||
if (!PinManager::allocateMultiplePins(pins, 5, PinOwner::UM_QuinLEDAnPenta)) {
|
||||
DEBUG_PRINTF("[%s] OLED pin allocation failed!\n", _name);
|
||||
oledEnabled = oledInitDone = false;
|
||||
return;
|
||||
@@ -164,11 +164,11 @@ class QuinLEDAnPentaUsermod : public Usermod
|
||||
oledDisplay->clear();
|
||||
}
|
||||
|
||||
pinManager.deallocatePin(oledSpiClk, PinOwner::UM_QuinLEDAnPenta);
|
||||
pinManager.deallocatePin(oledSpiData, PinOwner::UM_QuinLEDAnPenta);
|
||||
pinManager.deallocatePin(oledSpiCs, PinOwner::UM_QuinLEDAnPenta);
|
||||
pinManager.deallocatePin(oledSpiDc, PinOwner::UM_QuinLEDAnPenta);
|
||||
pinManager.deallocatePin(oledSpiRst, PinOwner::UM_QuinLEDAnPenta);
|
||||
PinManager::deallocatePin(oledSpiClk, PinOwner::UM_QuinLEDAnPenta);
|
||||
PinManager::deallocatePin(oledSpiData, PinOwner::UM_QuinLEDAnPenta);
|
||||
PinManager::deallocatePin(oledSpiCs, PinOwner::UM_QuinLEDAnPenta);
|
||||
PinManager::deallocatePin(oledSpiDc, PinOwner::UM_QuinLEDAnPenta);
|
||||
PinManager::deallocatePin(oledSpiRst, PinOwner::UM_QuinLEDAnPenta);
|
||||
|
||||
delete oledDisplay;
|
||||
|
||||
@@ -184,7 +184,7 @@ class QuinLEDAnPentaUsermod : public Usermod
|
||||
void initSht30TempHumiditySensor()
|
||||
{
|
||||
PinManagerPinType pins[2] = { { shtSda, true }, { shtScl, true } };
|
||||
if (!pinManager.allocateMultiplePins(pins, 2, PinOwner::UM_QuinLEDAnPenta)) {
|
||||
if (!PinManager::allocateMultiplePins(pins, 2, PinOwner::UM_QuinLEDAnPenta)) {
|
||||
DEBUG_PRINTF("[%s] SHT30 pin allocation failed!\n", _name);
|
||||
shtEnabled = shtInitDone = false;
|
||||
return;
|
||||
@@ -212,8 +212,8 @@ class QuinLEDAnPentaUsermod : public Usermod
|
||||
sht30TempHumidSensor->reset();
|
||||
}
|
||||
|
||||
pinManager.deallocatePin(shtSda, PinOwner::UM_QuinLEDAnPenta);
|
||||
pinManager.deallocatePin(shtScl, PinOwner::UM_QuinLEDAnPenta);
|
||||
PinManager::deallocatePin(shtSda, PinOwner::UM_QuinLEDAnPenta);
|
||||
PinManager::deallocatePin(shtScl, PinOwner::UM_QuinLEDAnPenta);
|
||||
|
||||
delete sht30TempHumidSensor;
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ The actual / original code that controls the LED modes is from Adam Zeloof. I ta
|
||||
It was quite a bit more work than I hoped, but I got there eventually :)
|
||||
|
||||
## Requirements
|
||||
* "ESP Rotary" by Lennart Hennigs, v1.5.0 or higher: https://github.com/LennartHennigs/ESPRotary
|
||||
* "ESP Rotary" by Lennart Hennigs, v2.1.1 or higher: https://github.com/LennartHennigs/ESPRotary
|
||||
|
||||
## Usermod installation
|
||||
Simply copy the below block (build task) to your `platformio_override.ini` and compile WLED using this new build task. Or use an existing one and add the buildflag `-D RGB_ROTARY_ENCODER`.
|
||||
@@ -20,7 +20,7 @@ ESP32:
|
||||
extends = env:esp32dev
|
||||
build_flags = ${common.build_flags_esp32} -D WLED_RELEASE_NAME=ESP32 -D RGB_ROTARY_ENCODER
|
||||
lib_deps = ${esp32.lib_deps}
|
||||
lennarthennigs/ESP Rotary@^1.5.0
|
||||
lennarthennigs/ESP Rotary@^2.1.1
|
||||
```
|
||||
|
||||
ESP8266 / D1 Mini:
|
||||
@@ -29,7 +29,7 @@ ESP8266 / D1 Mini:
|
||||
extends = env:d1_mini
|
||||
build_flags = ${common.build_flags_esp8266} -D RGB_ROTARY_ENCODER
|
||||
lib_deps = ${esp8266.lib_deps}
|
||||
lennarthennigs/ESP Rotary@^1.5.0
|
||||
lennarthennigs/ESP Rotary@^2.1.1
|
||||
```
|
||||
|
||||
## How to connect the board to your ESP
|
||||
|
||||
@@ -40,7 +40,7 @@ class RgbRotaryEncoderUsermod : public Usermod
|
||||
void initRotaryEncoder()
|
||||
{
|
||||
PinManagerPinType pins[2] = { { eaIo, false }, { ebIo, false } };
|
||||
if (!pinManager.allocateMultiplePins(pins, 2, PinOwner::UM_RGBRotaryEncoder)) {
|
||||
if (!PinManager::allocateMultiplePins(pins, 2, PinOwner::UM_RGBRotaryEncoder)) {
|
||||
eaIo = -1;
|
||||
ebIo = -1;
|
||||
cleanup();
|
||||
@@ -108,11 +108,11 @@ class RgbRotaryEncoderUsermod : public Usermod
|
||||
{
|
||||
// Only deallocate pins if we allocated them ;)
|
||||
if (eaIo != -1) {
|
||||
pinManager.deallocatePin(eaIo, PinOwner::UM_RGBRotaryEncoder);
|
||||
PinManager::deallocatePin(eaIo, PinOwner::UM_RGBRotaryEncoder);
|
||||
eaIo = -1;
|
||||
}
|
||||
if (ebIo != -1) {
|
||||
pinManager.deallocatePin(ebIo, PinOwner::UM_RGBRotaryEncoder);
|
||||
PinManager::deallocatePin(ebIo, PinOwner::UM_RGBRotaryEncoder);
|
||||
ebIo = -1;
|
||||
}
|
||||
|
||||
@@ -303,8 +303,8 @@ class RgbRotaryEncoderUsermod : public Usermod
|
||||
}
|
||||
|
||||
if (eaIo != oldEaIo || ebIo != oldEbIo || stepsPerClick != oldStepsPerClick || incrementPerClick != oldIncrementPerClick) {
|
||||
pinManager.deallocatePin(oldEaIo, PinOwner::UM_RGBRotaryEncoder);
|
||||
pinManager.deallocatePin(oldEbIo, PinOwner::UM_RGBRotaryEncoder);
|
||||
PinManager::deallocatePin(oldEaIo, PinOwner::UM_RGBRotaryEncoder);
|
||||
PinManager::deallocatePin(oldEbIo, PinOwner::UM_RGBRotaryEncoder);
|
||||
|
||||
delete rotaryEncoder;
|
||||
initRotaryEncoder();
|
||||
|
||||
@@ -45,7 +45,7 @@ class UsermodSdCard : public Usermod {
|
||||
{ configPinPico, true }
|
||||
};
|
||||
|
||||
if (!pinManager.allocateMultiplePins(pins, 4, PinOwner::UM_SdCard)) {
|
||||
if (!PinManager::allocateMultiplePins(pins, 4, PinOwner::UM_SdCard)) {
|
||||
DEBUG_PRINTF("[%s] SD (SPI) pin allocation failed!\n", _name);
|
||||
sdInitDone = false;
|
||||
return;
|
||||
@@ -75,10 +75,10 @@ class UsermodSdCard : public Usermod {
|
||||
SD_ADAPTER.end();
|
||||
|
||||
DEBUG_PRINTF("[%s] deallocate pins!\n", _name);
|
||||
pinManager.deallocatePin(configPinSourceSelect, PinOwner::UM_SdCard);
|
||||
pinManager.deallocatePin(configPinSourceClock, PinOwner::UM_SdCard);
|
||||
pinManager.deallocatePin(configPinPoci, PinOwner::UM_SdCard);
|
||||
pinManager.deallocatePin(configPinPico, PinOwner::UM_SdCard);
|
||||
PinManager::deallocatePin(configPinSourceSelect, PinOwner::UM_SdCard);
|
||||
PinManager::deallocatePin(configPinSourceClock, PinOwner::UM_SdCard);
|
||||
PinManager::deallocatePin(configPinPoci, PinOwner::UM_SdCard);
|
||||
PinManager::deallocatePin(configPinPico, PinOwner::UM_SdCard);
|
||||
|
||||
sdInitDone = false;
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
@@ -383,7 +385,7 @@ public:
|
||||
_setAllFalse();
|
||||
|
||||
#ifdef USERMOD_SN_PHOTORESISTOR
|
||||
ptr = (Usermod_SN_Photoresistor*) usermods.lookup(USERMOD_ID_SN_PHOTORESISTOR);
|
||||
ptr = (Usermod_SN_Photoresistor*) UsermodManager::lookup(USERMOD_ID_SN_PHOTORESISTOR);
|
||||
#endif
|
||||
DEBUG_PRINTLN(F("Setup done"));
|
||||
}
|
||||
|
||||
@@ -310,22 +310,22 @@ void ShtUsermod::onMqttConnect(bool sessionPresent) {
|
||||
* @return void
|
||||
*/
|
||||
void ShtUsermod::appendConfigData() {
|
||||
oappend(SET_F("dd=addDropdown('"));
|
||||
oappend(F("dd=addDropdown('"));
|
||||
oappend(_name);
|
||||
oappend(SET_F("','"));
|
||||
oappend(F("','"));
|
||||
oappend(_shtType);
|
||||
oappend(SET_F("');"));
|
||||
oappend(SET_F("addOption(dd,'SHT30',0);"));
|
||||
oappend(SET_F("addOption(dd,'SHT31',1);"));
|
||||
oappend(SET_F("addOption(dd,'SHT35',2);"));
|
||||
oappend(SET_F("addOption(dd,'SHT85',3);"));
|
||||
oappend(SET_F("dd=addDropdown('"));
|
||||
oappend(F("');"));
|
||||
oappend(F("addOption(dd,'SHT30',0);"));
|
||||
oappend(F("addOption(dd,'SHT31',1);"));
|
||||
oappend(F("addOption(dd,'SHT35',2);"));
|
||||
oappend(F("addOption(dd,'SHT85',3);"));
|
||||
oappend(F("dd=addDropdown('"));
|
||||
oappend(_name);
|
||||
oappend(SET_F("','"));
|
||||
oappend(F("','"));
|
||||
oappend(_unitOfTemp);
|
||||
oappend(SET_F("');"));
|
||||
oappend(SET_F("addOption(dd,'Celsius',0);"));
|
||||
oappend(SET_F("addOption(dd,'Fahrenheit',1);"));
|
||||
oappend(F("');"));
|
||||
oappend(F("addOption(dd,'Celsius',0);"));
|
||||
oappend(F("addOption(dd,'Fahrenheit',1);"));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -96,7 +96,7 @@ void setup() {
|
||||
jsonTransitionOnce = true;
|
||||
strip.setTransition(0); //no transition
|
||||
effectCurrent = FX_MODE_COLOR_WIPE;
|
||||
resetTimebase(); //make sure wipe starts from beginning
|
||||
strip.resetTimebase(); //make sure wipe starts from beginning
|
||||
|
||||
//set wipe direction
|
||||
Segment& seg = strip.getSegment(0);
|
||||
|
||||
@@ -86,7 +86,7 @@ void startWipe()
|
||||
bri = briLast; //turn on
|
||||
transitionDelayTemp = 0; //no transition
|
||||
effectCurrent = FX_MODE_COLOR_WIPE;
|
||||
resetTimebase(); //make sure wipe starts from beginning
|
||||
strip.resetTimebase(); //make sure wipe starts from beginning
|
||||
|
||||
//set wipe direction
|
||||
Segment& seg = strip.getSegment(0);
|
||||
|
||||
@@ -93,7 +93,7 @@ After getting the URL (it can be a static file like static.json or a mylogic.php
|
||||
- -D ABL_MILLIAMPS_DEFAULT=450
|
||||
- -D DEFAULT_LED_COUNT=60 ; For a LED Ring of 60 LEDs
|
||||
- -D BTNPIN=41 ; The M5Stack Atom S3 Lite has a button on GPIO41
|
||||
- -D LEDPIN=2 ; The M5Stack Atom S3 Lite has a Grove connector on the front, we use this GPIO2
|
||||
- -D DATA_PINS=2 ; The M5Stack Atom S3 Lite has a Grove connector on the front, we use this GPIO2
|
||||
- -D STATUSLED=35 ; The M5Stack Atom S3 Lite has a Multi-Color LED on GPIO35, although I didnt managed to control it
|
||||
- -D IRPIN=4 ; The M5Stack Atom S3 Lite has a IR LED on GPIO4
|
||||
|
||||
|
||||
@@ -103,7 +103,7 @@ class AutoSaveUsermod : public Usermod {
|
||||
#ifdef USERMOD_FOUR_LINE_DISPLAY
|
||||
// This Usermod has enhanced functionality if
|
||||
// FourLineDisplayUsermod is available.
|
||||
display = (FourLineDisplayUsermod*) usermods.lookup(USERMOD_ID_FOUR_LINE_DISP);
|
||||
display = (FourLineDisplayUsermod*) UsermodManager::lookup(USERMOD_ID_FOUR_LINE_DISP);
|
||||
#endif
|
||||
initDone = true;
|
||||
if (enabled && applyAutoSaveOnBoot) applyPreset(autoSavePreset);
|
||||
|
||||
@@ -7,11 +7,12 @@ platform = ${esp32.platform}
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags =
|
||||
${common.build_flags_esp32}
|
||||
-D USERMOD_FOUR_LINE_DISPLAY -D USE_ALT_DISPlAY
|
||||
-D USERMOD_ROTARY_ENCODER_UI -D ENCODER_DT_PIN=18 -D ENCODER_CLK_PIN=5 -D ENCODER_SW_PIN=19
|
||||
upload_speed = 460800
|
||||
-D USERMOD_FOUR_LINE_DISPLAY
|
||||
-D FLD_TYPE=SH1106
|
||||
-D I2CSCLPIN=27
|
||||
-D I2CSDAPIN=26
|
||||
|
||||
lib_deps =
|
||||
${esp32.lib_deps}
|
||||
U8g2@~2.34.4
|
||||
Wire
|
||||
|
||||
@@ -1,16 +1,8 @@
|
||||
# I2C/SPI 4 Line Display Usermod ALT
|
||||
|
||||
Thank you to the authors of the original version of these usermods. It would not have been possible without them!
|
||||
"usermod_v2_four_line_display"
|
||||
"usermod_v2_rotary_encoder_ui"
|
||||
This usermod could be used in compination with `usermod_v2_rotary_encoder_ui_ALT`.
|
||||
|
||||
The core of these usermods are a copy of the originals. The main changes are to the FourLineDisplay usermod.
|
||||
The display usermod UI has been completely changed.
|
||||
|
||||
|
||||
The changes made to the RotaryEncoder usermod were made to support the new UI in the display usermod.
|
||||
Without the display, it functions identical to the original.
|
||||
The original "usermod_v2_auto_save" will not work with the display just yet.
|
||||
## Functionalities
|
||||
|
||||
Press the encoder to cycle through the options:
|
||||
* Brightness
|
||||
@@ -18,26 +10,18 @@ Press the encoder to cycle through the options:
|
||||
* Intensity
|
||||
* Palette
|
||||
* Effect
|
||||
* Main Color (only if display is used)
|
||||
* Saturation (only if display is used)
|
||||
* Main Color
|
||||
* Saturation
|
||||
|
||||
Press and hold the encoder to display Network Info. If AP is active, it will display AP, SSID and password
|
||||
Press and hold the encoder to display Network Info. If AP is active, it will display the AP, SSID and Password
|
||||
|
||||
Also shows if the timer is enabled
|
||||
Also shows if the timer is enabled.
|
||||
|
||||
[See the pair of usermods in action](https://www.youtube.com/watch?v=ulZnBt9z3TI)
|
||||
|
||||
## Installation
|
||||
|
||||
Please refer to the original `usermod_v2_rotary_encoder_ui` readme for the main instructions.
|
||||
|
||||
Copy the example `platformio_override.sample.ini` from the usermod_v2_rotary_encoder_ui_ALT folder to the root directory of your particular build and rename it to `platformio_override.ini`.
|
||||
|
||||
This file should be placed in the same directory as `platformio.ini`.
|
||||
|
||||
Then, to activate this alternative usermod, add `#define USE_ALT_DISPlAY` (NOTE: CASE SENSITIVE) to the `usermods_list.cpp` file,
|
||||
or add `-D USE_ALT_DISPlAY` to the original `platformio_override.ini.sample` file
|
||||
|
||||
Copy the example `platformio_override.sample.ini` to the root directory of your particular build.
|
||||
|
||||
## Configuration
|
||||
|
||||
|
||||
@@ -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() {
|
||||
@@ -543,7 +543,7 @@ void FourLineDisplayUsermod::setup() {
|
||||
type = NONE;
|
||||
} else {
|
||||
PinManagerPinType cspins[3] = { { ioPin[0], true }, { ioPin[1], true }, { ioPin[2], true } };
|
||||
if (!pinManager.allocateMultiplePins(cspins, 3, PinOwner::UM_FourLineDisplay)) { type = NONE; }
|
||||
if (!PinManager::allocateMultiplePins(cspins, 3, PinOwner::UM_FourLineDisplay)) { type = NONE; }
|
||||
}
|
||||
} else {
|
||||
if (i2c_scl<0 || i2c_sda<0) { type=NONE; }
|
||||
@@ -569,7 +569,7 @@ void FourLineDisplayUsermod::setup() {
|
||||
if (nullptr == u8x8) {
|
||||
DEBUG_PRINTLN(F("Display init failed."));
|
||||
if (isSPI) {
|
||||
pinManager.deallocateMultiplePins((const uint8_t*)ioPin, 3, PinOwner::UM_FourLineDisplay);
|
||||
PinManager::deallocateMultiplePins((const uint8_t*)ioPin, 3, PinOwner::UM_FourLineDisplay);
|
||||
}
|
||||
type = NONE;
|
||||
return;
|
||||
@@ -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);
|
||||
}
|
||||
@@ -1202,21 +1202,21 @@ void FourLineDisplayUsermod::onUpdateBegin(bool init) {
|
||||
//}
|
||||
|
||||
void FourLineDisplayUsermod::appendConfigData() {
|
||||
oappend(SET_F("dd=addDropdown('4LineDisplay','type');"));
|
||||
oappend(SET_F("addOption(dd,'None',0);"));
|
||||
oappend(SET_F("addOption(dd,'SSD1306',1);"));
|
||||
oappend(SET_F("addOption(dd,'SH1106',2);"));
|
||||
oappend(SET_F("addOption(dd,'SSD1306 128x64',3);"));
|
||||
oappend(SET_F("addOption(dd,'SSD1305',4);"));
|
||||
oappend(SET_F("addOption(dd,'SSD1305 128x64',5);"));
|
||||
oappend(SET_F("addOption(dd,'SSD1309 128x64',9);"));
|
||||
oappend(SET_F("addOption(dd,'SSD1306 SPI',6);"));
|
||||
oappend(SET_F("addOption(dd,'SSD1306 SPI 128x64',7);"));
|
||||
oappend(SET_F("addOption(dd,'SSD1309 SPI 128x64',8);"));
|
||||
oappend(SET_F("addInfo('4LineDisplay:type',1,'<br><i class=\"warn\">Change may require reboot</i>','');"));
|
||||
oappend(SET_F("addInfo('4LineDisplay:pin[]',0,'','SPI CS');"));
|
||||
oappend(SET_F("addInfo('4LineDisplay:pin[]',1,'','SPI DC');"));
|
||||
oappend(SET_F("addInfo('4LineDisplay:pin[]',2,'','SPI RST');"));
|
||||
oappend(F("dd=addDropdown('4LineDisplay','type');"));
|
||||
oappend(F("addOption(dd,'None',0);"));
|
||||
oappend(F("addOption(dd,'SSD1306',1);"));
|
||||
oappend(F("addOption(dd,'SH1106',2);"));
|
||||
oappend(F("addOption(dd,'SSD1306 128x64',3);"));
|
||||
oappend(F("addOption(dd,'SSD1305',4);"));
|
||||
oappend(F("addOption(dd,'SSD1305 128x64',5);"));
|
||||
oappend(F("addOption(dd,'SSD1309 128x64',9);"));
|
||||
oappend(F("addOption(dd,'SSD1306 SPI',6);"));
|
||||
oappend(F("addOption(dd,'SSD1306 SPI 128x64',7);"));
|
||||
oappend(F("addOption(dd,'SSD1309 SPI 128x64',8);"));
|
||||
oappend(F("addInfo('4LineDisplay:type',1,'<br><i class=\"warn\">Change may require reboot</i>','');"));
|
||||
oappend(F("addInfo('4LineDisplay:pin[]',0,'','SPI CS');"));
|
||||
oappend(F("addInfo('4LineDisplay:pin[]',1,'','SPI DC');"));
|
||||
oappend(F("addInfo('4LineDisplay:pin[]',2,'','SPI RST');"));
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -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,12 +1302,12 @@ 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);
|
||||
if (isSPI) {
|
||||
if (pinsChanged || !newSPI) pinManager.deallocateMultiplePins((const uint8_t*)oldPin, 3, PinOwner::UM_FourLineDisplay);
|
||||
if (pinsChanged || !newSPI) PinManager::deallocateMultiplePins((const uint8_t*)oldPin, 3, PinOwner::UM_FourLineDisplay);
|
||||
if (!newSPI) {
|
||||
// was SPI but is no longer SPI
|
||||
if (i2c_scl<0 || i2c_sda<0) { newType=NONE; }
|
||||
@@ -1315,7 +1315,7 @@ bool FourLineDisplayUsermod::readFromConfig(JsonObject& root) {
|
||||
// still SPI but pins changed
|
||||
PinManagerPinType cspins[3] = { { ioPin[0], true }, { ioPin[1], true }, { ioPin[2], true } };
|
||||
if (ioPin[0]<0 || ioPin[1]<0 || ioPin[1]<0) { newType=NONE; }
|
||||
else if (!pinManager.allocateMultiplePins(cspins, 3, PinOwner::UM_FourLineDisplay)) { newType=NONE; }
|
||||
else if (!PinManager::allocateMultiplePins(cspins, 3, PinOwner::UM_FourLineDisplay)) { newType=NONE; }
|
||||
}
|
||||
} else if (newSPI) {
|
||||
// was I2C but is now SPI
|
||||
@@ -1324,7 +1324,7 @@ bool FourLineDisplayUsermod::readFromConfig(JsonObject& root) {
|
||||
} else {
|
||||
PinManagerPinType pins[3] = { { ioPin[0], true }, { ioPin[1], true }, { ioPin[2], true } };
|
||||
if (ioPin[0]<0 || ioPin[1]<0 || ioPin[1]<0) { newType=NONE; }
|
||||
else if (!pinManager.allocateMultiplePins(pins, 3, PinOwner::UM_FourLineDisplay)) { newType=NONE; }
|
||||
else if (!PinManager::allocateMultiplePins(pins, 3, PinOwner::UM_FourLineDisplay)) { newType=NONE; }
|
||||
}
|
||||
} else {
|
||||
// just I2C type changed
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
[platformio]
|
||||
default_envs = esp32dev
|
||||
|
||||
[env:esp32dev]
|
||||
board = esp32dev
|
||||
platform = ${esp32.platform}
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags =
|
||||
${common.build_flags_esp32}
|
||||
-D USERMOD_ROTARY_ENCODER_UI
|
||||
-D USERMOD_ROTARY_ENCODER_GPIO=INPUT
|
||||
-D ENCODER_DT_PIN=21
|
||||
-D ENCODER_CLK_PIN=23
|
||||
-D ENCODER_SW_PIN=0
|
||||
@@ -1,16 +1,8 @@
|
||||
# Rotary Encoder UI Usermod ALT
|
||||
|
||||
Thank you to the authors of the original version of these usermods. It would not have been possible without them!
|
||||
"usermod_v2_four_line_display"
|
||||
"usermod_v2_rotary_encoder_ui"
|
||||
This usermod supports the UI of the `usermod_v2_rotary_encoder_ui_ALT`.
|
||||
|
||||
The core of these usermods are a copy of the originals. The main changes are to the FourLineDisplay usermod.
|
||||
The display usermod UI has been completely changed.
|
||||
|
||||
|
||||
The changes made to the RotaryEncoder usermod were made to support the new UI in the display usermod.
|
||||
Without the display, it functions identical to the original.
|
||||
The original "usermod_v2_auto_save" will not work with the display just yet.
|
||||
## Functionalities
|
||||
|
||||
Press the encoder to cycle through the options:
|
||||
* Brightness
|
||||
@@ -21,8 +13,7 @@ Press the encoder to cycle through the options:
|
||||
* Main Color (only if display is used)
|
||||
* Saturation (only if display is used)
|
||||
|
||||
Press and hold the encoder to display Network Info
|
||||
if AP is active, it will display the AP, SSID and Password
|
||||
Press and hold the encoder to display Network Info. If AP is active, it will display the AP, SSID and Password
|
||||
|
||||
Also shows if the timer is enabled.
|
||||
|
||||
@@ -30,9 +21,7 @@ Also shows if the timer is enabled.
|
||||
|
||||
## Installation
|
||||
|
||||
Copy the example `platformio_override.sample.ini` to the root directory of your particular build and rename it to `platformio_override.ini`.
|
||||
|
||||
To activate this alternative usermod, add `#define USE_ALT_DISPlAY` (NOTE: CASE SENSITIVE) to the `usermods_list.cpp` file, or add `-D USE_ALT_DISPlAY` to your `platformio_override.ini` file
|
||||
Copy the example `platformio_override.sample.ini` to the root directory of your particular build.
|
||||
|
||||
### Define Your Options
|
||||
|
||||
@@ -40,7 +29,6 @@ To activate this alternative usermod, add `#define USE_ALT_DISPlAY` (NOTE: CASE
|
||||
* `USERMOD_FOUR_LINE_DISPLAY` - define this to have this the Four Line Display mod included wled00\usermods_list.cpp
|
||||
also tells this usermod that the display is available
|
||||
(see the Four Line Display usermod `readme.md` for more details)
|
||||
* `USE_ALT_DISPlAY` - Mandatory to use Four Line Display
|
||||
* `ENCODER_DT_PIN` - defaults to 18
|
||||
* `ENCODER_CLK_PIN` - defaults to 5
|
||||
* `ENCODER_SW_PIN` - defaults to 19
|
||||
@@ -50,7 +38,7 @@ To activate this alternative usermod, add `#define USE_ALT_DISPlAY` (NOTE: CASE
|
||||
|
||||
### PlatformIO requirements
|
||||
|
||||
Note: the Four Line Display usermod requires the libraries `U8g2` and `Wire`.
|
||||
No special requirements.
|
||||
|
||||
## Change Log
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -489,7 +489,7 @@ void RotaryEncoderUIUsermod::setup()
|
||||
enabled = false;
|
||||
return;
|
||||
} else {
|
||||
if (pinIRQ >= 0 && pinManager.allocatePin(pinIRQ, false, PinOwner::UM_RotaryEncoderUI)) {
|
||||
if (pinIRQ >= 0 && PinManager::allocatePin(pinIRQ, false, PinOwner::UM_RotaryEncoderUI)) {
|
||||
pinMode(pinIRQ, INPUT_PULLUP);
|
||||
attachInterrupt(pinIRQ, i2cReadingISR, FALLING); // RISING, FALLING, CHANGE, ONLOW, ONHIGH
|
||||
DEBUG_PRINTLN(F("Interrupt attached."));
|
||||
@@ -502,7 +502,7 @@ void RotaryEncoderUIUsermod::setup()
|
||||
}
|
||||
} else {
|
||||
PinManagerPinType pins[3] = { { pinA, false }, { pinB, false }, { pinC, false } };
|
||||
if (pinA<0 || pinB<0 || !pinManager.allocateMultiplePins(pins, 3, PinOwner::UM_RotaryEncoderUI)) {
|
||||
if (pinA<0 || pinB<0 || !PinManager::allocateMultiplePins(pins, 3, PinOwner::UM_RotaryEncoderUI)) {
|
||||
pinA = pinB = pinC = -1;
|
||||
enabled = false;
|
||||
return;
|
||||
@@ -525,7 +525,7 @@ void RotaryEncoderUIUsermod::setup()
|
||||
#ifdef USERMOD_FOUR_LINE_DISPLAY
|
||||
// This Usermod uses FourLineDisplayUsermod for the best experience.
|
||||
// But it's optional. But you want it.
|
||||
display = (FourLineDisplayUsermod*) usermods.lookup(USERMOD_ID_FOUR_LINE_DISP);
|
||||
display = (FourLineDisplayUsermod*) UsermodManager::lookup(USERMOD_ID_FOUR_LINE_DISP);
|
||||
if (display != nullptr) {
|
||||
display->setMarkLine(1, 0);
|
||||
}
|
||||
@@ -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);
|
||||
@@ -1090,8 +1090,8 @@ void RotaryEncoderUIUsermod::addToConfig(JsonObject &root) {
|
||||
}
|
||||
|
||||
void RotaryEncoderUIUsermod::appendConfigData() {
|
||||
oappend(SET_F("addInfo('Rotary-Encoder:PCF8574-address',1,'<i>(not hex!)</i>');"));
|
||||
oappend(SET_F("d.extra.push({'Rotary-Encoder':{pin:[['P0',100],['P1',101],['P2',102],['P3',103],['P4',104],['P5',105],['P6',106],['P7',107]]}});"));
|
||||
oappend(F("addInfo('Rotary-Encoder:PCF8574-address',1,'<i>(not hex!)</i>');"));
|
||||
oappend(F("d.extra.push({'Rotary-Encoder':{pin:[['P0',100],['P1',101],['P2',102],['P3',103],['P4',104],['P5',105],['P6',106],['P7',107]]}});"));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1138,14 +1138,14 @@ bool RotaryEncoderUIUsermod::readFromConfig(JsonObject &root) {
|
||||
if (oldPcf8574) {
|
||||
if (pinIRQ >= 0) {
|
||||
detachInterrupt(pinIRQ);
|
||||
pinManager.deallocatePin(pinIRQ, PinOwner::UM_RotaryEncoderUI);
|
||||
PinManager::deallocatePin(pinIRQ, PinOwner::UM_RotaryEncoderUI);
|
||||
DEBUG_PRINTLN(F("Deallocated old IRQ pin."));
|
||||
}
|
||||
pinIRQ = newIRQpin<100 ? newIRQpin : -1; // ignore PCF8574 pins
|
||||
} else {
|
||||
pinManager.deallocatePin(pinA, PinOwner::UM_RotaryEncoderUI);
|
||||
pinManager.deallocatePin(pinB, PinOwner::UM_RotaryEncoderUI);
|
||||
pinManager.deallocatePin(pinC, PinOwner::UM_RotaryEncoderUI);
|
||||
PinManager::deallocatePin(pinA, PinOwner::UM_RotaryEncoderUI);
|
||||
PinManager::deallocatePin(pinB, PinOwner::UM_RotaryEncoderUI);
|
||||
PinManager::deallocatePin(pinC, PinOwner::UM_RotaryEncoderUI);
|
||||
DEBUG_PRINTLN(F("Deallocated old pins."));
|
||||
}
|
||||
pinA = newDTpin;
|
||||
|
||||
@@ -433,8 +433,8 @@ class WordClockUsermod : public Usermod
|
||||
|
||||
void appendConfigData()
|
||||
{
|
||||
oappend(SET_F("addInfo('WordClockUsermod:ledOffset', 1, 'Number of LEDs before the letters');"));
|
||||
oappend(SET_F("addInfo('WordClockUsermod:Norddeutsch', 1, 'Viertel vor instead of Dreiviertel');"));
|
||||
oappend(F("addInfo('WordClockUsermod:ledOffset', 1, 'Number of LEDs before the letters');"));
|
||||
oappend(F("addInfo('WordClockUsermod:Norddeutsch', 1, 'Viertel vor instead of Dreiviertel');"));
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
@@ -54,13 +54,13 @@ class WireguardUsermod : public Usermod {
|
||||
}
|
||||
|
||||
void appendConfigData() {
|
||||
oappend(SET_F("addInfo('WireGuard:host',1,'Server Hostname');")); // 0 is field type, 1 is actual field
|
||||
oappend(SET_F("addInfo('WireGuard:port',1,'Server Port');")); // 0 is field type, 1 is actual field
|
||||
oappend(SET_F("addInfo('WireGuard:ip',1,'Device IP');")); // 0 is field type, 1 is actual field
|
||||
oappend(SET_F("addInfo('WireGuard:psk',1,'Pre Shared Key (optional)');")); // 0 is field type, 1 is actual field
|
||||
oappend(SET_F("addInfo('WireGuard:pem',1,'Private Key');")); // 0 is field type, 1 is actual field
|
||||
oappend(SET_F("addInfo('WireGuard:pub',1,'Public Key');")); // 0 is field type, 1 is actual field
|
||||
oappend(SET_F("addInfo('WireGuard:tz',1,'POSIX timezone string');")); // 0 is field type, 1 is actual field
|
||||
oappend(F("addInfo('WireGuard:host',1,'Server Hostname');")); // 0 is field type, 1 is actual field
|
||||
oappend(F("addInfo('WireGuard:port',1,'Server Port');")); // 0 is field type, 1 is actual field
|
||||
oappend(F("addInfo('WireGuard:ip',1,'Device IP');")); // 0 is field type, 1 is actual field
|
||||
oappend(F("addInfo('WireGuard:psk',1,'Pre Shared Key (optional)');")); // 0 is field type, 1 is actual field
|
||||
oappend(F("addInfo('WireGuard:pem',1,'Private Key');")); // 0 is field type, 1 is actual field
|
||||
oappend(F("addInfo('WireGuard:pub',1,'Public Key');")); // 0 is field type, 1 is actual field
|
||||
oappend(F("addInfo('WireGuard:tz',1,'POSIX timezone string');")); // 0 is field type, 1 is actual field
|
||||
}
|
||||
|
||||
void addToConfig(JsonObject& root) {
|
||||
|
||||
695
wled00/FX.cpp
695
wled00/FX.cpp
File diff suppressed because it is too large
Load Diff
296
wled00/FX.h
296
wled00/FX.h
@@ -2,24 +2,10 @@
|
||||
WS2812FX.h - Library for WS2812 LED effects.
|
||||
Harm Aldick - 2016
|
||||
www.aldick.org
|
||||
LICENSE
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016 Harm Aldick
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
Licensed under the EUPL v. 1.2 or later
|
||||
Adapted from code originally licensed under the MIT license
|
||||
|
||||
Modified for WLED
|
||||
*/
|
||||
@@ -60,6 +46,23 @@
|
||||
#define WLED_FPS 42
|
||||
#define FRAMETIME_FIXED (1000/WLED_FPS)
|
||||
#define FRAMETIME strip.getFrameTime()
|
||||
#if defined(ARDUINO_ARCH_ESP32) && !defined(CONFIG_IDF_TARGET_ESP32C3) && !defined(CONFIG_IDF_TARGET_ESP32S2)
|
||||
#define MIN_FRAME_DELAY 2 // minimum wait between repaints, to keep other functions like WiFi alive
|
||||
#elif defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32C3)
|
||||
#define MIN_FRAME_DELAY 3 // S2/C3 are slower than normal esp32, and only have one core
|
||||
#else
|
||||
#define MIN_FRAME_DELAY 8 // 8266 legacy MIN_SHOW_DELAY
|
||||
#endif
|
||||
#define FPS_UNLIMITED 0
|
||||
|
||||
// FPS calculation (can be defined as compile flag for debugging)
|
||||
#ifndef FPS_CALC_AVG
|
||||
#define FPS_CALC_AVG 7 // average FPS calculation over this many frames (moving average)
|
||||
#endif
|
||||
#ifndef FPS_MULTIPLIER
|
||||
#define FPS_MULTIPLIER 1 // dev option: multiplier to get sub-frame FPS without floats
|
||||
#endif
|
||||
#define FPS_CALC_SHIFT 7 // bit shift for fixed point math
|
||||
|
||||
/* each segment uses 82 bytes of SRAM memory, so if you're application fails because of
|
||||
insufficient memory, decreasing MAX_NUM_SEGMENTS may help */
|
||||
@@ -82,8 +85,6 @@
|
||||
assuming each segment uses the same amount of data. 256 for ESP8266, 640 for ESP32. */
|
||||
#define FAIR_DATA_PER_SEG (MAX_SEGMENT_DATA / strip.getMaxSegments())
|
||||
|
||||
#define MIN_SHOW_DELAY (_frametime < 16 ? 8 : 15)
|
||||
|
||||
#define NUM_COLORS 3 /* number of colors per segment */
|
||||
#define SEGMENT strip._segments[strip.getCurrSegmentId()]
|
||||
#define SEGENV strip._segments[strip.getCurrSegmentId()]
|
||||
@@ -517,68 +518,68 @@ typedef struct Segment {
|
||||
#endif
|
||||
|
||||
inline bool getOption(uint8_t n) const { return ((options >> n) & 0x01); }
|
||||
inline bool isSelected(void) const { return selected; }
|
||||
inline bool isInTransition(void) const { return _t != nullptr; }
|
||||
inline bool isActive(void) const { return stop > start; }
|
||||
inline bool is2D(void) const { return (width()>1 && height()>1); }
|
||||
inline bool hasRGB(void) const { return _isRGB; }
|
||||
inline bool hasWhite(void) const { return _hasW; }
|
||||
inline bool isCCT(void) const { return _isCCT; }
|
||||
inline uint16_t width(void) const { return isActive() ? (stop - start) : 0; } // segment width in physical pixels (length if 1D)
|
||||
inline uint16_t height(void) const { return stopY - startY; } // segment height (if 2D) in physical pixels (it *is* always >=1)
|
||||
inline uint16_t length(void) const { return width() * height(); } // segment length (count) in physical pixels
|
||||
inline uint16_t groupLength(void) const { return grouping + spacing; }
|
||||
inline uint8_t getLightCapabilities(void) const { return _capabilities; }
|
||||
inline bool isSelected() const { return selected; }
|
||||
inline bool isInTransition() const { return _t != nullptr; }
|
||||
inline bool isActive() const { return stop > start; }
|
||||
inline bool is2D() const { return (width()>1 && height()>1); }
|
||||
inline bool hasRGB() const { return _isRGB; }
|
||||
inline bool hasWhite() const { return _hasW; }
|
||||
inline bool isCCT() const { return _isCCT; }
|
||||
inline uint16_t width() const { return isActive() ? (stop - start) : 0; } // segment width in physical pixels (length if 1D)
|
||||
inline uint16_t height() const { return stopY - startY; } // segment height (if 2D) in physical pixels (it *is* always >=1)
|
||||
inline uint16_t length() const { return width() * height(); } // segment length (count) in physical pixels
|
||||
inline uint16_t groupLength() const { return grouping + spacing; }
|
||||
inline uint8_t getLightCapabilities() const { return _capabilities; }
|
||||
|
||||
static uint16_t getUsedSegmentData(void) { return _usedSegmentData; }
|
||||
static void addUsedSegmentData(int len) { _usedSegmentData += len; }
|
||||
inline static uint16_t getUsedSegmentData() { return _usedSegmentData; }
|
||||
inline static void addUsedSegmentData(int len) { _usedSegmentData += len; }
|
||||
#ifndef WLED_DISABLE_MODE_BLEND
|
||||
static void modeBlend(bool blend) { _modeBlend = blend; }
|
||||
inline static void modeBlend(bool blend) { _modeBlend = blend; }
|
||||
#endif
|
||||
static void handleRandomPalette();
|
||||
inline static const CRGBPalette16 &getCurrentPalette(void) { return Segment::_currentPalette; }
|
||||
inline static const CRGBPalette16 &getCurrentPalette() { return Segment::_currentPalette; }
|
||||
|
||||
void setUp(uint16_t i1, uint16_t i2, uint8_t grp=1, uint8_t spc=0, uint16_t ofs=UINT16_MAX, uint16_t i1Y=0, uint16_t i2Y=1);
|
||||
bool setColor(uint8_t slot, uint32_t c); //returns true if changed
|
||||
void setCCT(uint16_t k);
|
||||
void setOpacity(uint8_t o);
|
||||
void setOption(uint8_t n, bool val);
|
||||
void setMode(uint8_t fx, bool loadDefaults = false);
|
||||
void setPalette(uint8_t pal);
|
||||
Segment &setColor(uint8_t slot, uint32_t c);
|
||||
Segment &setCCT(uint16_t k);
|
||||
Segment &setOpacity(uint8_t o);
|
||||
Segment &setOption(uint8_t n, bool val);
|
||||
Segment &setMode(uint8_t fx, bool loadDefaults = false);
|
||||
Segment &setPalette(uint8_t pal);
|
||||
uint8_t differs(Segment& b) const;
|
||||
void refreshLightCapabilities(void);
|
||||
void refreshLightCapabilities();
|
||||
|
||||
// runtime data functions
|
||||
inline uint16_t dataSize(void) const { return _dataLen; }
|
||||
inline uint16_t dataSize() const { return _dataLen; }
|
||||
bool allocateData(size_t len); // allocates effect data buffer in heap and clears it
|
||||
void deallocateData(void); // deallocates (frees) effect data buffer from heap
|
||||
void resetIfRequired(void); // sets all SEGENV variables to 0 and clears data buffer
|
||||
void deallocateData(); // deallocates (frees) effect data buffer from heap
|
||||
void resetIfRequired(); // sets all SEGENV variables to 0 and clears data buffer
|
||||
/**
|
||||
* Flags that before the next effect is calculated,
|
||||
* the internal segment state should be reset.
|
||||
* Call resetIfRequired before calling the next effect function.
|
||||
* Safe to call from interrupts and network requests.
|
||||
*/
|
||||
inline void markForReset(void) { reset = true; } // setOption(SEG_OPTION_RESET, true)
|
||||
inline Segment &markForReset() { reset = true; return *this; } // setOption(SEG_OPTION_RESET, true)
|
||||
|
||||
// transition functions
|
||||
void startTransition(uint16_t dur); // transition has to start before actual segment values change
|
||||
void stopTransition(void); // ends transition mode by destroying transition structure
|
||||
void handleTransition(void);
|
||||
void stopTransition(); // ends transition mode by destroying transition structure (does nothing if not in transition)
|
||||
inline void handleTransition() { if (progress() == 0xFFFFU) stopTransition(); }
|
||||
#ifndef WLED_DISABLE_MODE_BLEND
|
||||
void swapSegenv(tmpsegd_t &tmpSegD); // copies segment data into specifed buffer, if buffer is not a transition buffer, segment data is overwritten from transition buffer
|
||||
void restoreSegenv(tmpsegd_t &tmpSegD); // restores segment data from buffer, if buffer is not transition buffer, changed values are copied to transition buffer
|
||||
#endif
|
||||
uint16_t progress(void); // 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)
|
||||
[[gnu::hot]] uint16_t progress() const; // transition progression between 0-65535
|
||||
[[gnu::hot]] uint8_t currentBri(bool useCct = false) const; // current segment brightness/CCT (blended while in transition)
|
||||
uint8_t currentMode() const; // currently active effect/mode (while in transition)
|
||||
[[gnu::hot]] 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);
|
||||
void setCurrentPalette();
|
||||
|
||||
// 1D strip
|
||||
uint16_t virtualLength(void) const;
|
||||
void setPixelColor(int n, uint32_t c); // set relative pixel within segment with color
|
||||
[[gnu::hot]] uint16_t virtualLength() const;
|
||||
[[gnu::hot]] void setPixelColor(int n, uint32_t c); // set relative pixel within segment with color
|
||||
inline void setPixelColor(unsigned n, uint32_t c) { setPixelColor(int(n), c); }
|
||||
inline void setPixelColor(int n, byte r, byte g, byte b, byte w = 0) { setPixelColor(n, RGBW32(r,g,b,w)); }
|
||||
inline void setPixelColor(int n, CRGB c) { setPixelColor(n, RGBW32(c.r,c.g,c.b,0)); }
|
||||
@@ -587,7 +588,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);
|
||||
[[gnu::hot]] uint32_t getPixelColor(int i) const;
|
||||
// 1D support functions (some implement 2D as well)
|
||||
void blur(uint8_t, bool smear = false);
|
||||
void fill(uint32_t c);
|
||||
@@ -599,16 +600,32 @@ 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);
|
||||
[[gnu::hot]] uint32_t color_from_palette(uint16_t, bool mapping, bool wrap, uint8_t mcol, uint8_t pbri = 255) const;
|
||||
[[gnu::hot]] uint32_t color_wheel(uint8_t pos) const;
|
||||
|
||||
// 2D Blur: shortcuts for bluring columns or rows only (50% faster than full 2D blur)
|
||||
inline void blurCols(fract8 blur_amount, bool smear = false) { // blur all columns
|
||||
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)
|
||||
uint16_t virtualHeight(void) const; // segment height in virtual pixels (accounts for groupping and spacing)
|
||||
uint16_t nrOfVStrips(void) const; // returns number of virtual vertical strips in 2D matrix (used to expand 1D effects into 2D)
|
||||
[[gnu::hot]] unsigned virtualWidth() const; // segment width in virtual pixels (accounts for groupping and spacing)
|
||||
[[gnu::hot]] unsigned virtualHeight() const; // segment height in virtual pixels (accounts for groupping and spacing)
|
||||
inline unsigned nrOfVStrips() const { // returns number of virtual vertical strips in 2D matrix (used to expand 1D effects into 2D)
|
||||
#ifndef WLED_DISABLE_2D
|
||||
return (is2D() && map1D2D == M12_pBar) ? virtualWidth() : 1;
|
||||
#else
|
||||
return 1;
|
||||
#endif
|
||||
}
|
||||
#ifndef WLED_DISABLE_2D
|
||||
uint16_t XY(uint16_t x, uint16_t y); // support function to get relative index within segment
|
||||
void setPixelColorXY(int x, int y, uint32_t c); // set relative pixel within segment with color
|
||||
[[gnu::hot]] uint16_t XY(int x, int y); // support function to get relative index within segment
|
||||
[[gnu::hot]] void setPixelColorXY(int x, int y, uint32_t c); // set relative pixel within segment with color
|
||||
inline void setPixelColorXY(unsigned x, unsigned y, uint32_t c) { setPixelColorXY(int(x), int(y), c); }
|
||||
inline void setPixelColorXY(int x, int y, byte r, byte g, byte b, byte w = 0) { setPixelColorXY(x, y, RGBW32(r,g,b,w)); }
|
||||
inline void setPixelColorXY(int x, int y, CRGB c) { setPixelColorXY(x, y, RGBW32(c.r,c.g,c.b,0)); }
|
||||
@@ -618,7 +635,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);
|
||||
[[gnu::hot]] uint32_t getPixelColorXY(int x, int y) const;
|
||||
// 2D support functions
|
||||
inline void blendPixelColorXY(uint16_t x, uint16_t y, uint32_t color, uint8_t blend) { setPixelColorXY(x, y, color_blend(getPixelColorXY(x,y), color, blend)); }
|
||||
inline void blendPixelColorXY(uint16_t x, uint16_t y, CRGB c, uint8_t blend) { blendPixelColorXY(x, y, RGBW32(c.r,c.g,c.b,0), blend); }
|
||||
@@ -626,7 +643,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 +674,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) {}
|
||||
@@ -685,8 +704,8 @@ typedef struct Segment {
|
||||
|
||||
// main "strip" class
|
||||
class WS2812FX { // 96 bytes
|
||||
typedef uint16_t (*mode_ptr)(void); // pointer to mode function
|
||||
typedef void (*show_callback)(void); // pre show callback
|
||||
typedef uint16_t (*mode_ptr)(); // pointer to mode function
|
||||
typedef void (*show_callback)(); // pre show callback
|
||||
typedef struct ModeData {
|
||||
uint8_t _id; // mode (effect) id
|
||||
mode_ptr _fcn; // mode (effect) function
|
||||
@@ -708,6 +727,13 @@ class WS2812FX { // 96 bytes
|
||||
#ifndef WLED_DISABLE_2D
|
||||
panels(1),
|
||||
#endif
|
||||
#ifdef WLED_AUTOSEGMENTS
|
||||
autoSegments(true),
|
||||
#else
|
||||
autoSegments(false),
|
||||
#endif
|
||||
correctWB(false),
|
||||
cctFromRgb(false),
|
||||
// semi-private (just obscured) used in effect functions through macros
|
||||
_colors_t{0,0,0},
|
||||
_virtualSegmentLength(0),
|
||||
@@ -718,7 +744,7 @@ class WS2812FX { // 96 bytes
|
||||
_transitionDur(750),
|
||||
_targetFps(WLED_FPS),
|
||||
_frametime(FRAMETIME_FIXED),
|
||||
_cumulativeFps(2),
|
||||
_cumulativeFps(50 << FPS_CALC_SHIFT),
|
||||
_isServicing(false),
|
||||
_isOffRefreshRequired(false),
|
||||
_hasWhiteChannel(false),
|
||||
@@ -728,16 +754,9 @@ class WS2812FX { // 96 bytes
|
||||
customMappingTable(nullptr),
|
||||
customMappingSize(0),
|
||||
_lastShow(0),
|
||||
_lastServiceShow(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())
|
||||
@@ -757,105 +776,103 @@ class WS2812FX { // 96 bytes
|
||||
customPalettes.clear();
|
||||
}
|
||||
|
||||
static WS2812FX* getInstance(void) { return instance; }
|
||||
static WS2812FX* getInstance() { return instance; }
|
||||
|
||||
void
|
||||
#ifdef WLED_DEBUG
|
||||
printSize(), // prints memory usage for strip components
|
||||
#endif
|
||||
finalizeInit(), // initialises strip components
|
||||
service(void), // executes effect functions when due and calls strip.show()
|
||||
service(), // executes effect functions when due and calls strip.show()
|
||||
setMode(uint8_t segid, uint8_t m), // sets effect/mode for given segment (high level API)
|
||||
setColor(uint8_t slot, uint32_t c), // sets color (in slot) for given segment (high level API)
|
||||
setCCT(uint16_t k), // sets global CCT (either in relative 0-255 value or in K)
|
||||
setBrightness(uint8_t b, bool direct = false), // sets strip brightness
|
||||
setRange(uint16_t i, uint16_t i2, uint32_t col), // used for clock overlay
|
||||
purgeSegments(void), // removes inactive segments from RAM (may incure penalty and memory fragmentation but reduces vector footprint)
|
||||
purgeSegments(), // removes inactive segments from RAM (may incure penalty and memory fragmentation but reduces vector footprint)
|
||||
setSegment(uint8_t n, uint16_t start, uint16_t stop, uint8_t grouping = 1, uint8_t spacing = 0, uint16_t offset = UINT16_MAX, uint16_t startY=0, uint16_t stopY=1),
|
||||
setMainSegmentId(uint8_t n),
|
||||
resetSegments(), // marks all segments for reset
|
||||
makeAutoSegments(bool forceReset = false), // will create segments based on configured outputs
|
||||
fixInvalidSegments(), // fixes incorrect segment configuration
|
||||
setPixelColor(unsigned n, uint32_t c), // paints absolute strip pixel with index n and color c
|
||||
show(void), // initiates LED output
|
||||
show(), // initiates LED output
|
||||
setTargetFps(uint8_t fps),
|
||||
addEffect(uint8_t id, mode_ptr mode_fn, const char *mode_name), // add effect to the list; defined in FX.cpp
|
||||
setupEffectData(void); // add default effects to the list; defined in FX.cpp
|
||||
setupEffectData(); // add default effects to the list; defined in FX.cpp
|
||||
|
||||
inline void restartRuntime() { for (Segment &seg : _segments) seg.markForReset(); }
|
||||
inline void resetTimebase() { timebase = 0UL - millis(); }
|
||||
inline void restartRuntime() { for (Segment &seg : _segments) { seg.markForReset().resetIfRequired(); } }
|
||||
inline void setTransitionMode(bool t) { for (Segment &seg : _segments) seg.startTransition(t ? _transitionDur : 0); }
|
||||
inline void setColor(uint8_t slot, uint8_t r, uint8_t g, uint8_t b, uint8_t w = 0) { setColor(slot, RGBW32(r,g,b,w)); }
|
||||
inline void setPixelColor(unsigned n, uint8_t r, uint8_t g, uint8_t b, uint8_t w = 0) { setPixelColor(n, RGBW32(r,g,b,w)); }
|
||||
inline void setPixelColor(unsigned n, CRGB c) { setPixelColor(n, c.red, c.green, c.blue); }
|
||||
inline void fill(uint32_t c) { for (unsigned i = 0; i < getLengthTotal(); i++) setPixelColor(i, c); } // fill whole strip with color (inline)
|
||||
inline void trigger(void) { _triggered = true; } // Forces the next frame to be computed on all active segments.
|
||||
inline void trigger() { _triggered = true; } // Forces the next frame to be computed on all active segments.
|
||||
inline void setShowCallback(show_callback cb) { _callback = cb; }
|
||||
inline void setTransition(uint16_t t) { _transitionDur = t; } // sets transition time (in ms)
|
||||
inline void appendSegment(const Segment &seg = Segment()) { if (_segments.size() < getMaxSegments()) _segments.push_back(seg); }
|
||||
inline void suspend(void) { _suspend = true; } // will suspend (and canacel) strip.service() execution
|
||||
inline void resume(void) { _suspend = false; } // will resume strip.service() execution
|
||||
inline void suspend() { _suspend = true; } // will suspend (and canacel) strip.service() execution
|
||||
inline void resume() { _suspend = false; } // will resume strip.service() execution
|
||||
|
||||
bool
|
||||
paletteFade,
|
||||
checkSegmentAlignment(void),
|
||||
hasRGBWBus(void),
|
||||
hasCCTBus(void),
|
||||
// return true if the strip is being sent pixel updates
|
||||
isUpdating(void),
|
||||
checkSegmentAlignment(),
|
||||
hasRGBWBus() const,
|
||||
hasCCTBus() const,
|
||||
isUpdating() const, // return true if the strip is being sent pixel updates
|
||||
deserializeMap(uint8_t n=0);
|
||||
|
||||
inline bool isServicing(void) { 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() const { return _isServicing; } // returns true if strip.service() is executing
|
||||
inline bool hasWhiteChannel() const { return _hasWhiteChannel; } // returns true if strip contains separate white chanel
|
||||
inline bool isOffRefreshRequired() const { return _isOffRefreshRequired; } // returns true if strip requires regular updates (i.e. TM1814 chipset)
|
||||
inline bool isSuspended() const { return _suspend; } // returns true if strip.service() execution is suspended
|
||||
inline bool needsUpdate() const { return _triggered; } // returns true if strip received a trigger() request
|
||||
|
||||
uint8_t
|
||||
paletteBlend,
|
||||
cctBlending,
|
||||
getActiveSegmentsNum(void),
|
||||
getFirstSelectedSegId(void),
|
||||
getLastActiveSegmentId(void),
|
||||
getActiveSegsLightCapabilities(bool selectedOnly = false);
|
||||
getActiveSegmentsNum() const,
|
||||
getFirstSelectedSegId() const,
|
||||
getLastActiveSegmentId() const,
|
||||
getActiveSegsLightCapabilities(bool selectedOnly = false) const,
|
||||
addEffect(uint8_t id, mode_ptr mode_fn, const char *mode_name); // add effect to the list; defined in FX.cpp;
|
||||
|
||||
inline uint8_t getBrightness(void) { 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() const { return _brightness; } // returns current strip brightness
|
||||
inline uint8_t getMaxSegments() const { return MAX_NUM_SEGMENTS; } // returns maximum number of supported segments (fixed value)
|
||||
inline uint8_t getSegmentsNum() const { return _segments.size(); } // returns currently present segments
|
||||
inline uint8_t getCurrSegmentId() const { return _segment_index; } // returns current segment index (only valid while strip.isServicing())
|
||||
inline uint8_t getMainSegmentId() const { return _mainSegment; } // returns main segment index
|
||||
inline uint8_t getPaletteCount() const { return 13 + GRADIENT_PALETTE_COUNT + customPalettes.size(); }
|
||||
inline uint8_t getTargetFps() const { return _targetFps; } // returns rough FPS value for las 2s interval
|
||||
inline uint8_t getModeCount() const { return _modeCount; } // returns number of registered modes/effects
|
||||
|
||||
uint16_t
|
||||
getLengthPhysical(void),
|
||||
getLengthTotal(void), // will include virtual/nonexistent pixels in matrix
|
||||
getFps(),
|
||||
getMappedPixelIndex(uint16_t index);
|
||||
getLengthPhysical() const,
|
||||
getLengthTotal() 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() const { return _frametime; } // returns amount of time a frame should take (in ms)
|
||||
inline uint16_t getMinShowDelay() const { return MIN_FRAME_DELAY; } // returns minimum amount of time strip.service() can be delayed (constant)
|
||||
inline uint16_t getLength() const { return _length; } // returns actual amount of LEDs on a strip (2D matrix may have less LEDs than W*H)
|
||||
inline uint16_t getTransition() const { return _transitionDur; } // returns currently set transition time (in ms)
|
||||
|
||||
uint32_t
|
||||
now,
|
||||
timebase,
|
||||
getPixelColor(uint16_t);
|
||||
unsigned long now, timebase;
|
||||
uint32_t getPixelColor(unsigned) 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() 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
|
||||
getModeDataSrc() { return &(_modeData[0]); } // vectors use arrays for underlying data
|
||||
|
||||
Segment& getSegment(uint8_t id);
|
||||
inline Segment& getFirstSelectedSeg(void) { return _segments[getFirstSelectedSegId()]; } // returns reference to first segment that is "selected"
|
||||
inline Segment& getMainSegment(void) { return _segments[getMainSegmentId()]; } // returns reference to main segment
|
||||
inline Segment* getSegments(void) { return &(_segments[0]); } // returns pointer to segment vector structure (warning: use carefully)
|
||||
inline Segment& getFirstSelectedSeg() { return _segments[getFirstSelectedSegId()]; } // returns reference to first segment that is "selected"
|
||||
inline Segment& getMainSegment() { return _segments[getMainSegmentId()]; } // returns reference to main segment
|
||||
inline Segment* getSegments() { return &(_segments[0]); } // returns pointer to segment vector structure (warning: use carefully)
|
||||
|
||||
// 2D support (panels)
|
||||
bool
|
||||
@@ -898,13 +915,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
|
||||
void loadCustomPalettes(); // 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)
|
||||
@@ -942,17 +965,10 @@ class WS2812FX { // 96 bytes
|
||||
uint16_t customMappingSize;
|
||||
|
||||
unsigned long _lastShow;
|
||||
unsigned long _lastServiceShow;
|
||||
|
||||
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[];
|
||||
|
||||
@@ -1,24 +1,9 @@
|
||||
/*
|
||||
FX_2Dfcn.cpp contains all 2D utility functions
|
||||
|
||||
LICENSE
|
||||
The MIT License (MIT)
|
||||
Copyright (c) 2022 Blaz Kristan (https://blaz.at/home)
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
Licensed under the EUPL v. 1.2 or later
|
||||
Adapted from code originally licensed under the MIT license
|
||||
|
||||
Parts of the code adapted from WLED Sound Reactive
|
||||
*/
|
||||
@@ -161,17 +146,17 @@ 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(int x, int y)
|
||||
{
|
||||
unsigned width = virtualWidth(); // segment width in logical pixels (can be 0 if segment is inactive)
|
||||
unsigned height = virtualHeight(); // segment height in logical pixels (is always >= 1)
|
||||
return isActive() ? (x%width) + (y%height) * width : 0;
|
||||
}
|
||||
|
||||
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
|
||||
if ((unsigned)x >= virtualWidth() || (unsigned)y >= virtualHeight() || x<0 || y<0) return; // if pixel would fall out of virtual segment just exit
|
||||
|
||||
uint8_t _bri_t = currentBri();
|
||||
if (_bri_t < 255) {
|
||||
@@ -180,17 +165,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 +196,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 +249,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 ((unsigned)x >= virtualWidth() || (unsigned)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 +327,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) {
|
||||
@@ -614,11 +689,14 @@ void Segment::wu_pixel(uint32_t x, uint32_t y, CRGB c) { //awesome wu_pixel
|
||||
WU_WEIGHT(ix, yy), WU_WEIGHT(xx, yy)};
|
||||
// multiply the intensities by the colour, and saturating-add them to the pixels
|
||||
for (int i = 0; i < 4; i++) {
|
||||
CRGB led = getPixelColorXY((x >> 8) + (i & 1), (y >> 8) + ((i >> 1) & 1));
|
||||
int wu_x = (x >> 8) + (i & 1); // precalculate x
|
||||
int wu_y = (y >> 8) + ((i >> 1) & 1); // precalculate y
|
||||
CRGB led = getPixelColorXY(wu_x, wu_y);
|
||||
CRGB oldLed = led;
|
||||
led.r = qadd8(led.r, c.r * wu[i] >> 8);
|
||||
led.g = qadd8(led.g, c.g * wu[i] >> 8);
|
||||
led.b = qadd8(led.b, c.b * wu[i] >> 8);
|
||||
setPixelColorXY(int((x >> 8) + (i & 1)), int((y >> 8) + ((i >> 1) & 1)), led);
|
||||
if (led != oldLed) setPixelColorXY(wu_x, wu_y, led); // don't repaint if same color
|
||||
}
|
||||
}
|
||||
#undef WU_WEIGHT
|
||||
|
||||
@@ -2,24 +2,10 @@
|
||||
WS2812FX_fcn.cpp contains all utility functions
|
||||
Harm Aldick - 2016
|
||||
www.aldick.org
|
||||
LICENSE
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016 Harm Aldick
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
Licensed under the EUPL v. 1.2 or later
|
||||
Adapted from code originally licensed under the MIT license
|
||||
|
||||
Modified heavily for WLED
|
||||
*/
|
||||
@@ -43,21 +29,16 @@
|
||||
19, 18, 17, 16, 15, 20, 21, 22, 23, 24, 29, 28, 27, 26, 25]}
|
||||
*/
|
||||
|
||||
//factory defaults LED setup
|
||||
//#define PIXEL_COUNTS 30, 30, 30, 30
|
||||
//#define DATA_PINS 16, 1, 3, 4
|
||||
//#define DEFAULT_LED_TYPE TYPE_WS2812_RGB
|
||||
|
||||
#ifndef PIXEL_COUNTS
|
||||
#define PIXEL_COUNTS DEFAULT_LED_COUNT
|
||||
#endif
|
||||
|
||||
#ifndef DATA_PINS
|
||||
#define DATA_PINS LEDPIN
|
||||
#define DATA_PINS DEFAULT_LED_PIN
|
||||
#endif
|
||||
|
||||
#ifndef DEFAULT_LED_TYPE
|
||||
#define DEFAULT_LED_TYPE TYPE_WS2812_RGB
|
||||
#ifndef LED_TYPES
|
||||
#define LED_TYPES DEFAULT_LED_TYPE
|
||||
#endif
|
||||
|
||||
#ifndef DEFAULT_LED_COLOR_ORDER
|
||||
@@ -69,6 +50,18 @@
|
||||
#error "Max segments must be at least max number of busses!"
|
||||
#endif
|
||||
|
||||
static constexpr unsigned sumPinsRequired(const unsigned* current, size_t count) {
|
||||
return (count > 0) ? (Bus::getNumberOfPins(*current) + sumPinsRequired(current+1,count-1)) : 0;
|
||||
}
|
||||
|
||||
static constexpr bool validatePinsAndTypes(const unsigned* types, unsigned numTypes, unsigned numPins ) {
|
||||
// Pins provided < pins required -> always invalid
|
||||
// Pins provided = pins required -> always valid
|
||||
// Pins provided > pins required -> valid if excess pins are a product of last type pins since it will be repeated
|
||||
return (sumPinsRequired(types, numTypes) > numPins) ? false :
|
||||
(numPins - sumPinsRequired(types, numTypes)) % Bus::getNumberOfPins(types[numTypes-1]) == 0;
|
||||
}
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// Segment class implementation
|
||||
@@ -146,7 +139,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,17 +163,13 @@ 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
|
||||
free(data);
|
||||
} else {
|
||||
DEBUG_PRINT(F("---- Released data "));
|
||||
DEBUG_PRINTF_P(PSTR("(%p): "), this);
|
||||
DEBUG_PRINT(F("inconsistent UsedSegmentData "));
|
||||
DEBUG_PRINTF_P(PSTR("(%d/%d)"), _dataLen, Segment::getUsedSegmentData());
|
||||
DEBUG_PRINTLN(F(", cowardly refusing to free nothing."));
|
||||
DEBUG_PRINTF_P(PSTR("---- Released data (%p): inconsistent UsedSegmentData (%d/%d), cowardly refusing to free nothing.\n"), this, _dataLen, Segment::getUsedSegmentData());
|
||||
}
|
||||
data = nullptr;
|
||||
Segment::addUsedSegmentData(_dataLen <= Segment::getUsedSegmentData() ? -_dataLen : -Segment::getUsedSegmentData());
|
||||
@@ -202,7 +191,7 @@ void Segment::resetIfRequired() {
|
||||
reset = false;
|
||||
}
|
||||
|
||||
CRGBPalette16 IRAM_ATTR &Segment::loadPalette(CRGBPalette16 &targetPalette, uint8_t pal) {
|
||||
CRGBPalette16 &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 +316,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 +396,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 +406,7 @@ uint8_t IRAM_ATTR Segment::currentBri(bool useCct) {
|
||||
return (useCct ? cct : (on ? opacity : 0));
|
||||
}
|
||||
|
||||
uint8_t IRAM_ATTR Segment::currentMode() {
|
||||
uint8_t Segment::currentMode() const {
|
||||
#ifndef WLED_DISABLE_MODE_BLEND
|
||||
unsigned prog = progress();
|
||||
if (modeBlending && prog < 0xFFFFU) return _t->_modeT;
|
||||
@@ -430,7 +414,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];
|
||||
@@ -525,46 +509,53 @@ void Segment::setUp(uint16_t i1, uint16_t i2, uint8_t grp, uint8_t spc, uint16_t
|
||||
}
|
||||
|
||||
|
||||
bool Segment::setColor(uint8_t slot, uint32_t c) { //returns true if changed
|
||||
if (slot >= NUM_COLORS || c == colors[slot]) return false;
|
||||
Segment &Segment::setColor(uint8_t slot, uint32_t c) {
|
||||
if (slot >= NUM_COLORS || c == colors[slot]) return *this;
|
||||
if (!_isRGB && !_hasW) {
|
||||
if (slot == 0 && c == BLACK) return false; // on/off segment cannot have primary color black
|
||||
if (slot == 1 && c != BLACK) return false; // on/off segment cannot have secondary color non black
|
||||
if (slot == 0 && c == BLACK) return *this; // on/off segment cannot have primary color black
|
||||
if (slot == 1 && c != BLACK) return *this; // on/off segment cannot have secondary color non black
|
||||
}
|
||||
if (fadeTransition) startTransition(strip.getTransition()); // start transition prior to change
|
||||
colors[slot] = c;
|
||||
stateChanged = true; // send UDP/WS broadcast
|
||||
return true;
|
||||
return *this;
|
||||
}
|
||||
|
||||
void Segment::setCCT(uint16_t k) {
|
||||
Segment &Segment::setCCT(uint16_t k) {
|
||||
if (k > 255) { //kelvin value, convert to 0-255
|
||||
if (k < 1900) k = 1900;
|
||||
if (k > 10091) k = 10091;
|
||||
k = (k - 1900) >> 5;
|
||||
}
|
||||
if (cct == k) return;
|
||||
if (fadeTransition) startTransition(strip.getTransition()); // start transition prior to change
|
||||
cct = k;
|
||||
stateChanged = true; // send UDP/WS broadcast
|
||||
if (cct != k) {
|
||||
//DEBUGFX_PRINTF_P(PSTR("- Starting CCT transition: %d\n"), k);
|
||||
startTransition(strip.getTransition()); // start transition prior to change
|
||||
cct = k;
|
||||
stateChanged = true; // send UDP/WS broadcast
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
void Segment::setOpacity(uint8_t o) {
|
||||
if (opacity == o) return;
|
||||
if (fadeTransition) startTransition(strip.getTransition()); // start transition prior to change
|
||||
opacity = o;
|
||||
stateChanged = true; // send UDP/WS broadcast
|
||||
Segment &Segment::setOpacity(uint8_t o) {
|
||||
if (opacity != o) {
|
||||
//DEBUGFX_PRINTF_P(PSTR("- Starting opacity transition: %d\n"), o);
|
||||
startTransition(strip.getTransition()); // start transition prior to change
|
||||
opacity = o;
|
||||
stateChanged = true; // send UDP/WS broadcast
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
void Segment::setOption(uint8_t n, bool val) {
|
||||
Segment &Segment::setOption(uint8_t n, bool val) {
|
||||
bool prevOn = on;
|
||||
if (fadeTransition && n == SEG_OPTION_ON && val != prevOn) startTransition(strip.getTransition()); // start transition prior to change
|
||||
if (val) options |= 0x01 << n;
|
||||
else options &= ~(0x01 << n);
|
||||
if (!(n == SEG_OPTION_SELECTED || n == SEG_OPTION_RESET)) stateChanged = true; // send UDP/WS broadcast
|
||||
return *this;
|
||||
}
|
||||
|
||||
void Segment::setMode(uint8_t fx, bool loadDefaults) {
|
||||
Segment &Segment::setMode(uint8_t fx, bool loadDefaults) {
|
||||
// skip reserved
|
||||
while (fx < strip.getModeCount() && strncmp_P("RSVD", strip.getModeData(fx), 4) == 0) fx++;
|
||||
if (fx >= strip.getModeCount()) fx = 0; // set solid mode
|
||||
@@ -596,9 +587,10 @@ void Segment::setMode(uint8_t fx, bool loadDefaults) {
|
||||
markForReset();
|
||||
stateChanged = true; // send UDP/WS broadcast
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
void Segment::setPalette(uint8_t pal) {
|
||||
Segment &Segment::setPalette(uint8_t pal) {
|
||||
if (pal < 245 && pal > GRADIENT_PALETTE_COUNT+13) pal = 0; // built in palettes
|
||||
if (pal > 245 && (strip.customPalettes.size() == 0 || 255U-pal > strip.customPalettes.size()-1)) pal = 0; // custom palettes
|
||||
if (pal != palette) {
|
||||
@@ -606,37 +598,24 @@ void Segment::setPalette(uint8_t pal) {
|
||||
palette = pal;
|
||||
stateChanged = true; // send UDP/WS broadcast
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
// 2D matrix
|
||||
uint16_t IRAM_ATTR Segment::virtualWidth() const {
|
||||
unsigned IRAM_ATTR Segment::virtualWidth() const {
|
||||
unsigned groupLen = groupLength();
|
||||
unsigned vWidth = ((transpose ? height() : width()) + groupLen - 1) / groupLen;
|
||||
if (mirror) vWidth = (vWidth + 1) /2; // divide by 2 if mirror, leave at least a single LED
|
||||
return vWidth;
|
||||
}
|
||||
|
||||
uint16_t IRAM_ATTR Segment::virtualHeight() const {
|
||||
unsigned IRAM_ATTR Segment::virtualHeight() const {
|
||||
unsigned groupLen = groupLength();
|
||||
unsigned vHeight = ((transpose ? width() : height()) + groupLen - 1) / groupLen;
|
||||
if (mirror_y) vHeight = (vHeight + 1) /2; // divide by 2 if mirror, leave at least a single LED
|
||||
return vHeight;
|
||||
}
|
||||
|
||||
uint16_t IRAM_ATTR Segment::nrOfVStrips() const {
|
||||
unsigned vLen = 1;
|
||||
#ifndef WLED_DISABLE_2D
|
||||
if (is2D()) {
|
||||
switch (map1D2D) {
|
||||
case M12_pBar:
|
||||
vLen = virtualWidth();
|
||||
break;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return vLen;
|
||||
}
|
||||
|
||||
// Constants for mapping mode "Pinwheel"
|
||||
#ifndef WLED_DISABLE_2D
|
||||
constexpr int Pinwheel_Steps_Small = 72; // no holes up to 16x16
|
||||
@@ -679,18 +658,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 +685,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 +714,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 +879,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 +889,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 +900,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 +945,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);
|
||||
}
|
||||
|
||||
@@ -1021,10 +1011,9 @@ void Segment::refreshLightCapabilities() {
|
||||
if (bus->getStart() >= segStopIdx) continue;
|
||||
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 +1048,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 +1058,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 +1100,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 +1117,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 +1135,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 +1159,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
|
||||
@@ -1194,12 +1180,9 @@ uint32_t Segment::color_from_palette(uint16_t i, bool mapping, bool wrap, uint8_
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
//do not call this method from system context (network callback)
|
||||
void WS2812FX::finalizeInit(void) {
|
||||
void WS2812FX::finalizeInit() {
|
||||
//reset segment runtimes
|
||||
for (segment &seg : _segments) {
|
||||
seg.markForReset();
|
||||
seg.resetIfRequired();
|
||||
}
|
||||
restartRuntime();
|
||||
|
||||
// for the lack of better place enumerate ledmaps here
|
||||
// if we do it in json.cpp (serializeInfo()) we are getting flashes on LEDs
|
||||
@@ -1212,26 +1195,82 @@ void WS2812FX::finalizeInit(void) {
|
||||
//if busses failed to load, add default (fresh install, FS issue, ...)
|
||||
if (BusManager::getNumBusses() == 0) {
|
||||
DEBUG_PRINTLN(F("No busses, init default"));
|
||||
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 pinsPerBus = defNumPins / defNumBusses;
|
||||
constexpr unsigned defDataTypes[] = {LED_TYPES};
|
||||
constexpr unsigned defDataPins[] = {DATA_PINS};
|
||||
constexpr unsigned defCounts[] = {PIXEL_COUNTS};
|
||||
constexpr unsigned defNumTypes = ((sizeof defDataTypes) / (sizeof defDataTypes[0]));
|
||||
constexpr unsigned defNumPins = ((sizeof defDataPins) / (sizeof defDataPins[0]));
|
||||
constexpr unsigned defNumCounts = ((sizeof defCounts) / (sizeof defCounts[0]));
|
||||
|
||||
static_assert(validatePinsAndTypes(defDataTypes, defNumTypes, defNumPins),
|
||||
"The default pin list defined in DATA_PINS does not match the pin requirements for the default buses defined in LED_TYPES");
|
||||
|
||||
unsigned prevLen = 0;
|
||||
for (unsigned i = 0; i < defNumBusses && i < WLED_MAX_BUSSES+WLED_MIN_VIRTUAL_BUSSES; i++) {
|
||||
uint8_t defPin[5]; // max 5 pins
|
||||
for (unsigned j = 0; j < pinsPerBus; j++) defPin[j] = defDataPins[i*pinsPerBus + j];
|
||||
// when booting without config (1st boot) we need to make sure GPIOs defined for LED output don't clash with hardware
|
||||
// i.e. DEBUG (GPIO1), DMX (2), SPI RAM/FLASH (16&17 on ESP32-WROVER/PICO), etc
|
||||
if (pinManager.isPinAllocated(defPin[0])) {
|
||||
defPin[0] = 1; // start with GPIO1 and work upwards
|
||||
while (pinManager.isPinAllocated(defPin[0]) && defPin[0] < WLED_NUM_PINS) defPin[0]++;
|
||||
unsigned pinsIndex = 0;
|
||||
for (unsigned i = 0; i < WLED_MAX_BUSSES+WLED_MIN_VIRTUAL_BUSSES; i++) {
|
||||
uint8_t defPin[OUTPUT_MAX_PINS];
|
||||
// if we have less types than requested outputs and they do not align, use last known type to set current type
|
||||
unsigned dataType = defDataTypes[(i < defNumTypes) ? i : defNumTypes -1];
|
||||
unsigned busPins = Bus::getNumberOfPins(dataType);
|
||||
|
||||
// if we need more pins than available all outputs have been configured
|
||||
if (pinsIndex + busPins > defNumPins) break;
|
||||
|
||||
// Assign all pins first so we can check for conflicts on this bus
|
||||
for (unsigned j = 0; j < busPins && j < OUTPUT_MAX_PINS; j++) defPin[j] = defDataPins[pinsIndex + j];
|
||||
|
||||
for (unsigned j = 0; j < busPins && j < OUTPUT_MAX_PINS; j++) {
|
||||
bool validPin = true;
|
||||
// When booting without config (1st boot) we need to make sure GPIOs defined for LED output don't clash with hardware
|
||||
// i.e. DEBUG (GPIO1), DMX (2), SPI RAM/FLASH (16&17 on ESP32-WROVER/PICO), read/only pins, etc.
|
||||
// Pin should not be already allocated, read/only or defined for current bus
|
||||
while (PinManager::isPinAllocated(defPin[j]) || !PinManager::isPinOk(defPin[j],true)) {
|
||||
if (validPin) {
|
||||
DEBUG_PRINTLN(F("Some of the provided pins cannot be used to configure this LED output."));
|
||||
defPin[j] = 1; // start with GPIO1 and work upwards
|
||||
validPin = false;
|
||||
} else if (defPin[j] < WLED_NUM_PINS) {
|
||||
defPin[j]++;
|
||||
} else {
|
||||
DEBUG_PRINTLN(F("No available pins left! Can't configure output."));
|
||||
return;
|
||||
}
|
||||
// is the newly assigned pin already defined or used previously?
|
||||
// try next in line until there are no clashes or we run out of pins
|
||||
bool clash;
|
||||
do {
|
||||
clash = false;
|
||||
// check for conflicts on current bus
|
||||
for (const auto &pin : defPin) {
|
||||
if (&pin != &defPin[j] && pin == defPin[j]) {
|
||||
clash = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// We already have a clash on current bus, no point checking next buses
|
||||
if (!clash) {
|
||||
// check for conflicts in defined pins
|
||||
for (const auto &pin : defDataPins) {
|
||||
if (pin == defPin[j]) {
|
||||
clash = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (clash) defPin[j]++;
|
||||
if (defPin[j] >= WLED_NUM_PINS) break;
|
||||
} while (clash);
|
||||
}
|
||||
}
|
||||
pinsIndex += busPins;
|
||||
|
||||
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];
|
||||
// analog always has length 1
|
||||
if (Bus::isPWM(dataType) || Bus::isOnOff(dataType)) count = 1;
|
||||
prevLen += count;
|
||||
BusConfig defCfg = BusConfig(DEFAULT_LED_TYPE, defPin, start, count, DEFAULT_LED_COLOR_ORDER, false, 0, RGBW_MODE_MANUAL_ONLY, 0, useGlobalLedBuffer);
|
||||
BusConfig defCfg = BusConfig(dataType, defPin, start, count, DEFAULT_LED_COLOR_ORDER, false, 0, RGBW_MODE_MANUAL_ONLY, 0, useGlobalLedBuffer);
|
||||
if (BusManager::add(defCfg) == -1) break;
|
||||
}
|
||||
}
|
||||
@@ -1244,17 +1283,12 @@ void WS2812FX::finalizeInit(void) {
|
||||
//RGBW mode is enabled if at least one of the strips is RGBW
|
||||
_hasWhiteChannel |= bus->hasWhite();
|
||||
//refresh is required to remain off if at least one of the strips requires the refresh.
|
||||
_isOffRefreshRequired |= bus->isOffRefreshRequired();
|
||||
_isOffRefreshRequired |= bus->isOffRefreshRequired() && !bus->isPWM(); // use refresh bit for phase shift with analog
|
||||
unsigned busEnd = bus->getStart() + bus->getLength();
|
||||
if (busEnd > _length) _length = busEnd;
|
||||
#ifdef ESP8266
|
||||
// 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
|
||||
|
||||
// This must be done after all buses have been created, as some kinds (parallel I2S) interact
|
||||
bus->begin();
|
||||
}
|
||||
|
||||
Segment::maxWidth = _length;
|
||||
@@ -1270,7 +1304,14 @@ void WS2812FX::finalizeInit(void) {
|
||||
void WS2812FX::service() {
|
||||
unsigned long nowUp = millis(); // Be aware, millis() rolls over every 49 days
|
||||
now = nowUp + timebase;
|
||||
if (nowUp - _lastShow < MIN_SHOW_DELAY || _suspend) return;
|
||||
if (_suspend) return;
|
||||
unsigned long elapsed = nowUp - _lastServiceShow;
|
||||
|
||||
if (elapsed <= MIN_FRAME_DELAY) return; // keep wifi alive - no matter if triggered or unlimited
|
||||
if ( !_triggered && (_targetFps != FPS_UNLIMITED)) { // unlimited mode = no frametime
|
||||
if (elapsed < _frametime) return; // too early for service
|
||||
}
|
||||
|
||||
bool doShow = false;
|
||||
|
||||
_isServicing = true;
|
||||
@@ -1287,10 +1328,10 @@ void WS2812FX::service() {
|
||||
if (!seg.isActive()) continue;
|
||||
|
||||
// last condition ensures all solid segments are updated at the same time
|
||||
if (nowUp > seg.next_time || _triggered || (doShow && seg.mode == FX_MODE_STATIC))
|
||||
if (nowUp >= seg.next_time || _triggered || (doShow && seg.mode == FX_MODE_STATIC))
|
||||
{
|
||||
doShow = true;
|
||||
unsigned delay = FRAMETIME;
|
||||
unsigned frameDelay = FRAMETIME;
|
||||
|
||||
if (!seg.freeze) { //only run effect function if not frozen
|
||||
int oldCCT = BusManager::getSegmentCCT(); // store original CCT value (actually it is not Segment based)
|
||||
@@ -1310,7 +1351,7 @@ void WS2812FX::service() {
|
||||
// overwritten by later effect. To enable seamless blending for every effect, additional LED buffer
|
||||
// would need to be allocated for each effect and then blended together for each pixel.
|
||||
[[maybe_unused]] uint8_t tmpMode = seg.currentMode(); // this will return old mode while in transition
|
||||
delay = (*_mode[seg.mode])(); // run new/current mode
|
||||
frameDelay = (*_mode[seg.mode])(); // run new/current mode
|
||||
#ifndef WLED_DISABLE_MODE_BLEND
|
||||
if (modeBlending && seg.mode != tmpMode) {
|
||||
Segment::tmpsegd_t _tmpSegData;
|
||||
@@ -1319,16 +1360,16 @@ void WS2812FX::service() {
|
||||
_virtualSegmentLength = seg.virtualLength(); // update SEGLEN (mapping may have changed)
|
||||
unsigned d2 = (*_mode[tmpMode])(); // run old mode
|
||||
seg.restoreSegenv(_tmpSegData); // restore mode state (will also update transitional state)
|
||||
delay = MIN(delay,d2); // use shortest delay
|
||||
frameDelay = min(frameDelay,d2); // use shortest delay
|
||||
Segment::modeBlend(false); // unset semaphore
|
||||
}
|
||||
#endif
|
||||
seg.call++;
|
||||
if (seg.isInTransition() && delay > FRAMETIME) delay = FRAMETIME; // force faster updates during transition
|
||||
if (seg.isInTransition() && frameDelay > FRAMETIME) frameDelay = FRAMETIME; // force faster updates during transition
|
||||
BusManager::setSegmentCCT(oldCCT); // restore old CCT for ABL adjustments
|
||||
}
|
||||
|
||||
seg.next_time = nowUp + delay;
|
||||
seg.next_time = nowUp + frameDelay;
|
||||
}
|
||||
_segment_index++;
|
||||
}
|
||||
@@ -1337,15 +1378,16 @@ void WS2812FX::service() {
|
||||
_triggered = false;
|
||||
|
||||
#ifdef WLED_DEBUG
|
||||
if (millis() - nowUp > _frametime) DEBUG_PRINTF_P(PSTR("Slow effects %u/%d.\n"), (unsigned)(millis()-nowUp), (int)_frametime);
|
||||
if ((_targetFps != FPS_UNLIMITED) && (millis() - nowUp > _frametime)) DEBUG_PRINTF_P(PSTR("Slow effects %u/%d.\n"), (unsigned)(millis()-nowUp), (int)_frametime);
|
||||
#endif
|
||||
if (doShow) {
|
||||
yield();
|
||||
Segment::handleRandomPalette(); // slowly transition random palette; move it into for loop when each segment has individual random palette
|
||||
show();
|
||||
_lastServiceShow = nowUp; // update timestamp, for precise FPS control
|
||||
}
|
||||
#ifdef WLED_DEBUG
|
||||
if (millis() - nowUp > _frametime) DEBUG_PRINTF_P(PSTR("Slow strip %u/%d.\n"), (unsigned)(millis()-nowUp), (int)_frametime);
|
||||
if ((_targetFps != FPS_UNLIMITED) && (millis() - nowUp > _frametime)) DEBUG_PRINTF_P(PSTR("Slow strip %u/%d.\n"), (unsigned)(millis()-nowUp), (int)_frametime);
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -1355,35 +1397,37 @@ 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(unsigned i) const {
|
||||
i = getMappedPixelIndex(i);
|
||||
if (i >= _length) return 0;
|
||||
return BusManager::getPixelColor(i);
|
||||
}
|
||||
|
||||
void WS2812FX::show(void) {
|
||||
void WS2812FX::show() {
|
||||
// avoid race condition, capture _callback value
|
||||
show_callback callback = _callback;
|
||||
if (callback) callback();
|
||||
unsigned long showNow = millis();
|
||||
|
||||
// some buses send asynchronously and this method will return before
|
||||
// all of the data has been sent.
|
||||
// See https://github.com/Makuna/NeoPixelBus/wiki/ESP32-NeoMethods#neoesp32rmt-methods
|
||||
BusManager::show();
|
||||
|
||||
unsigned long showNow = millis();
|
||||
size_t diff = showNow - _lastShow;
|
||||
size_t fpsCurr = 200;
|
||||
if (diff > 0) fpsCurr = 1000 / diff;
|
||||
_cumulativeFps = (3 * _cumulativeFps + fpsCurr +2) >> 2; // "+2" for proper rounding (2/4 = 0.5)
|
||||
_lastShow = showNow;
|
||||
|
||||
if (diff > 0) { // skip calculation if no time has passed
|
||||
size_t fpsCurr = (1000 << FPS_CALC_SHIFT) / diff; // fixed point math
|
||||
_cumulativeFps = (FPS_CALC_AVG * _cumulativeFps + fpsCurr + FPS_CALC_AVG / 2) / (FPS_CALC_AVG + 1); // "+FPS_CALC_AVG/2" for proper rounding
|
||||
_lastShow = showNow;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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();
|
||||
}
|
||||
|
||||
@@ -1391,14 +1435,15 @@ 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;
|
||||
return (FPS_MULTIPLIER * _cumulativeFps) >> FPS_CALC_SHIFT; // _cumulativeFps is stored in fixed point
|
||||
}
|
||||
|
||||
void WS2812FX::setTargetFps(uint8_t fps) {
|
||||
if (fps > 0 && fps <= 120) _targetFps = fps;
|
||||
_frametime = 1000 / _targetFps;
|
||||
if (fps <= 250) _targetFps = fps;
|
||||
if (_targetFps > 0) _frametime = 1000 / _targetFps;
|
||||
else _frametime = MIN_FRAME_DELAY; // unlimited mode
|
||||
}
|
||||
|
||||
void WS2812FX::setMode(uint8_t segid, uint8_t m) {
|
||||
@@ -1446,21 +1491,21 @@ void WS2812FX::setBrightness(uint8_t b, bool direct) {
|
||||
BusManager::setBrightness(b);
|
||||
if (!direct) {
|
||||
unsigned long t = millis();
|
||||
if (_segments[0].next_time > t + 22 && t - _lastShow > MIN_SHOW_DELAY) trigger(); //apply brightness change immediately if no refresh soon
|
||||
if (_segments[0].next_time > t + 22 && t - _lastShow > MIN_FRAME_DELAY) trigger(); //apply brightness change immediately if no refresh soon
|
||||
}
|
||||
}
|
||||
|
||||
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() const {
|
||||
size_t i = 0;
|
||||
for (segment &seg : _segments) {
|
||||
for (const segment &seg : _segments) {
|
||||
if (seg.isActive() && seg.isSelected()) return i;
|
||||
i++;
|
||||
}
|
||||
@@ -1476,14 +1521,14 @@ void WS2812FX::setMainSegmentId(uint8_t n) {
|
||||
return;
|
||||
}
|
||||
|
||||
uint8_t WS2812FX::getLastActiveSegmentId(void) {
|
||||
uint8_t WS2812FX::getLastActiveSegmentId() const {
|
||||
for (size_t i = _segments.size() -1; i > 0; i--) {
|
||||
if (_segments[i].isActive()) return i;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint8_t WS2812FX::getActiveSegmentsNum(void) {
|
||||
uint8_t WS2812FX::getActiveSegmentsNum() const {
|
||||
uint8_t c = 0;
|
||||
for (size_t i = 0; i < _segments.size(); i++) {
|
||||
if (_segments[i].isActive()) c++;
|
||||
@@ -1491,17 +1536,17 @@ uint8_t WS2812FX::getActiveSegmentsNum(void) {
|
||||
return c;
|
||||
}
|
||||
|
||||
uint16_t WS2812FX::getLengthTotal(void) {
|
||||
uint16_t WS2812FX::getLengthTotal() const {
|
||||
unsigned len = Segment::maxWidth * Segment::maxHeight; // will be _length for 1D (see finalizeInit()) but should cover whole matrix for 2D
|
||||
if (isMatrix && _length > len) len = _length; // for 2D with trailing strip
|
||||
return len;
|
||||
}
|
||||
|
||||
uint16_t WS2812FX::getLengthPhysical(void) {
|
||||
uint16_t WS2812FX::getLengthPhysical() const {
|
||||
unsigned len = 0;
|
||||
for (size_t b = 0; b < BusManager::getNumBusses(); b++) {
|
||||
Bus *bus = BusManager::getBus(b);
|
||||
if (bus->getType() >= TYPE_NET_DDP_RGB) continue; //exclude non-physical network busses
|
||||
if (bus->isVirtual()) continue; //exclude non-physical network busses
|
||||
len += bus->getLength();
|
||||
}
|
||||
return len;
|
||||
@@ -1510,7 +1555,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() const {
|
||||
for (size_t b = 0; b < BusManager::getNumBusses(); b++) {
|
||||
Bus *bus = BusManager::getBus(b);
|
||||
if (bus == nullptr || bus->getLength()==0) break;
|
||||
@@ -1519,7 +1564,7 @@ bool WS2812FX::hasRGBWBus(void) {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool WS2812FX::hasCCTBus(void) {
|
||||
bool WS2812FX::hasCCTBus() const {
|
||||
if (cctFromRgb && !correctWB) return false;
|
||||
for (size_t b = 0; b < BusManager::getNumBusses(); b++) {
|
||||
Bus *bus = BusManager::getBus(b);
|
||||
@@ -1811,7 +1856,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);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,18 @@
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <IPAddress.h>
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
#include "driver/ledc.h"
|
||||
#include "soc/ledc_struct.h"
|
||||
#if !(defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32S3))
|
||||
#define LEDC_MUTEX_LOCK() do {} while (xSemaphoreTake(_ledc_sys_lock, portMAX_DELAY) != pdPASS)
|
||||
#define LEDC_MUTEX_UNLOCK() xSemaphoreGive(_ledc_sys_lock)
|
||||
extern xSemaphoreHandle _ledc_sys_lock;
|
||||
#else
|
||||
#define LEDC_MUTEX_LOCK()
|
||||
#define LEDC_MUTEX_UNLOCK()
|
||||
#endif
|
||||
#endif
|
||||
#include "const.h"
|
||||
#include "pin_manager.h"
|
||||
#include "bus_wrapper.h"
|
||||
@@ -48,54 +60,62 @@ uint8_t realtimeBroadcast(uint8_t type, IPAddress client, uint16_t length, byte
|
||||
#define W(c) (byte((c) >> 24))
|
||||
|
||||
|
||||
void ColorOrderMap::add(uint16_t start, uint16_t len, uint8_t colorOrder) {
|
||||
if (_count >= WLED_MAX_COLOR_ORDER_MAPPINGS) {
|
||||
return;
|
||||
}
|
||||
if (len == 0) {
|
||||
return;
|
||||
}
|
||||
// upper nibble contains W swap information
|
||||
if ((colorOrder & 0x0F) > COL_ORDER_MAX) {
|
||||
return;
|
||||
}
|
||||
_mappings[_count].start = start;
|
||||
_mappings[_count].len = len;
|
||||
_mappings[_count].colorOrder = colorOrder;
|
||||
_count++;
|
||||
bool ColorOrderMap::add(uint16_t start, uint16_t len, uint8_t colorOrder) {
|
||||
if (count() >= WLED_MAX_COLOR_ORDER_MAPPINGS || len == 0 || (colorOrder & 0x0F) > COL_ORDER_MAX) return false; // upper nibble contains W swap information
|
||||
_mappings.push_back({start,len,colorOrder});
|
||||
return true;
|
||||
}
|
||||
|
||||
uint8_t IRAM_ATTR ColorOrderMap::getPixelColorOrder(uint16_t pix, uint8_t defaultColorOrder) const {
|
||||
if (_count > 0) {
|
||||
// upper nibble contains W swap information
|
||||
// when ColorOrderMap's upper nibble contains value >0 then swap information is used from it, otherwise global swap is used
|
||||
for (unsigned i = 0; i < _count; i++) {
|
||||
if (pix >= _mappings[i].start && pix < (_mappings[i].start + _mappings[i].len)) {
|
||||
return _mappings[i].colorOrder | ((_mappings[i].colorOrder >> 4) ? 0 : (defaultColorOrder & 0xF0));
|
||||
}
|
||||
// upper nibble contains W swap information
|
||||
// when ColorOrderMap's upper nibble contains value >0 then swap information is used from it, otherwise global swap is used
|
||||
for (unsigned i = 0; i < count(); i++) {
|
||||
if (pix >= _mappings[i].start && pix < (_mappings[i].start + _mappings[i].len)) {
|
||||
return _mappings[i].colorOrder | ((_mappings[i].colorOrder >> 4) ? 0 : (defaultColorOrder & 0xF0));
|
||||
}
|
||||
}
|
||||
return defaultColorOrder;
|
||||
}
|
||||
|
||||
|
||||
uint32_t Bus::autoWhiteCalc(uint32_t c) {
|
||||
uint8_t aWM = _autoWhiteMode;
|
||||
void Bus::calculateCCT(uint32_t c, uint8_t &ww, uint8_t &cw) {
|
||||
unsigned cct = 0; //0 - full warm white, 255 - full cold white
|
||||
unsigned w = W(c);
|
||||
|
||||
if (_cct > -1) { // using RGB?
|
||||
if (_cct >= 1900) cct = (_cct - 1900) >> 5; // convert K in relative format
|
||||
else if (_cct < 256) cct = _cct; // already relative
|
||||
} else {
|
||||
cct = (approximateKelvinFromRGB(c) - 1900) >> 5; // convert K (from RGB value) to relative format
|
||||
}
|
||||
|
||||
//0 - linear (CCT 127 = 50% warm, 50% cold), 127 - additive CCT blending (CCT 127 = 100% warm, 100% cold)
|
||||
if (cct < _cctBlend) ww = 255;
|
||||
else ww = ((255-cct) * 255) / (255 - _cctBlend);
|
||||
if ((255-cct) < _cctBlend) cw = 255;
|
||||
else cw = (cct * 255) / (255 - _cctBlend);
|
||||
|
||||
ww = (w * ww) / 255; //brightness scaling
|
||||
cw = (w * cw) / 255;
|
||||
}
|
||||
|
||||
uint32_t Bus::autoWhiteCalc(uint32_t c) const {
|
||||
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
|
||||
return RGBW32(r, g, b, w);
|
||||
}
|
||||
|
||||
uint8_t *Bus::allocData(size_t size) {
|
||||
uint8_t *Bus::allocateData(size_t size) {
|
||||
if (_data) free(_data); // should not happen, but for safety
|
||||
return _data = (uint8_t *)(size>0 ? calloc(size, sizeof(uint8_t)) : nullptr);
|
||||
}
|
||||
@@ -109,12 +129,12 @@ BusDigital::BusDigital(BusConfig &bc, uint8_t nr, const ColorOrderMap &com)
|
||||
, _milliAmpsMax(bc.milliAmpsMax)
|
||||
, _colorOrderMap(com)
|
||||
{
|
||||
if (!IS_DIGITAL(bc.type) || !bc.count) return;
|
||||
if (!pinManager.allocatePin(bc.pins[0], true, PinOwner::BusDigital)) return;
|
||||
if (!isDigital(bc.type) || !bc.count) return;
|
||||
if (!PinManager::allocatePin(bc.pins[0], true, PinOwner::BusDigital)) return;
|
||||
_frequencykHz = 0U;
|
||||
_pins[0] = bc.pins[0];
|
||||
if (IS_2PIN(bc.type)) {
|
||||
if (!pinManager.allocatePin(bc.pins[1], true, PinOwner::BusDigital)) {
|
||||
if (is2Pin(bc.type)) {
|
||||
if (!PinManager::allocatePin(bc.pins[1], true, PinOwner::BusDigital)) {
|
||||
cleanup();
|
||||
return;
|
||||
}
|
||||
@@ -123,25 +143,18 @@ BusDigital::BusDigital(BusConfig &bc, uint8_t nr, const ColorOrderMap &com)
|
||||
}
|
||||
_iType = PolyBus::getI(bc.type, _pins, nr);
|
||||
if (_iType == I_NONE) return;
|
||||
if (bc.doubleBuffer && !allocData(bc.count * Bus::getNumberOfChannels(bc.type))) return;
|
||||
_hasRgb = hasRGB(bc.type);
|
||||
_hasWhite = hasWhite(bc.type);
|
||||
_hasCCT = hasCCT(bc.type);
|
||||
if (bc.doubleBuffer && !allocateData(bc.count * Bus::getNumberOfChannels(bc.type))) return;
|
||||
//_buffering = bc.doubleBuffer;
|
||||
uint16_t lenToCreate = bc.count;
|
||||
if (bc.type == TYPE_WS2812_1CH_X3) lenToCreate = NUM_ICS_WS2812_1CH_3X(bc.count); // only needs a third of "RGB" LEDs for NeoPixelBus
|
||||
_busPtr = PolyBus::create(_iType, _pins, lenToCreate + _skip, nr, _frequencykHz);
|
||||
_busPtr = PolyBus::create(_iType, _pins, lenToCreate + _skip, nr);
|
||||
_valid = (_busPtr != nullptr);
|
||||
DEBUG_PRINTF_P(PSTR("%successfully inited strip %u (len %u) with type %u and pins %u,%u (itype %u). mA=%d/%d\n"), _valid?"S":"Uns", nr, bc.count, bc.type, _pins[0], IS_2PIN(bc.type)?_pins[1]:255, _iType, _milliAmpsPerLed, _milliAmpsMax);
|
||||
DEBUG_PRINTF_P(PSTR("%successfully inited strip %u (len %u) with type %u and pins %u,%u (itype %u). mA=%d/%d\n"), _valid?"S":"Uns", nr, bc.count, bc.type, _pins[0], is2Pin(bc.type)?_pins[1]:255, _iType, _milliAmpsPerLed, _milliAmpsMax);
|
||||
}
|
||||
|
||||
//fine tune power estimation constants for your setup
|
||||
//you can set it to 0 if the ESP is powered by USB and the LEDs by external
|
||||
#ifndef MA_FOR_ESP
|
||||
#ifdef ESP8266
|
||||
#define MA_FOR_ESP 80 //how much mA does the ESP use (Wemos D1 about 80mA)
|
||||
#else
|
||||
#define MA_FOR_ESP 120 //how much mA does the ESP use (ESP32 about 120mA)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
//DISCLAIMER
|
||||
//The following function attemps to calculate the current LED power usage,
|
||||
//and will limit the brightness to stay below a set amperage threshold.
|
||||
@@ -207,7 +220,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 +228,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 +247,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 +259,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
|
||||
@@ -263,7 +276,7 @@ void BusDigital::show() {
|
||||
if (newBri < _bri) PolyBus::setBrightness(_busPtr, _iType, _bri);
|
||||
}
|
||||
|
||||
bool BusDigital::canShow() {
|
||||
bool BusDigital::canShow() const {
|
||||
if (!_valid) return true;
|
||||
return PolyBus::canShow(_busPtr, _iType);
|
||||
}
|
||||
@@ -302,9 +315,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)
|
||||
@@ -319,7 +332,7 @@ void IRAM_ATTR BusDigital::setPixelColor(uint16_t pix, uint32_t c) {
|
||||
}
|
||||
|
||||
// returns original color if global buffering is enabled, else returns lossly restored color from bus
|
||||
uint32_t IRAM_ATTR BusDigital::getPixelColor(uint16_t pix) {
|
||||
uint32_t IRAM_ATTR BusDigital::getPixelColor(uint16_t pix) const {
|
||||
if (!_valid) return 0;
|
||||
if (_data) {
|
||||
size_t offset = pix * getNumberOfChannels();
|
||||
@@ -333,12 +346,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;
|
||||
@@ -349,9 +362,9 @@ uint32_t IRAM_ATTR BusDigital::getPixelColor(uint16_t pix) {
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t BusDigital::getPins(uint8_t* pinArray) {
|
||||
uint8_t numPins = IS_2PIN(_type) ? 2 : 1;
|
||||
for (unsigned i = 0; i < numPins; i++) pinArray[i] = _pins[i];
|
||||
uint8_t BusDigital::getPins(uint8_t* pinArray) const {
|
||||
unsigned numPins = is2Pin(_type) + 1;
|
||||
if (pinArray) for (unsigned i = 0; i < numPins; i++) pinArray[i] = _pins[i];
|
||||
return numPins;
|
||||
}
|
||||
|
||||
@@ -361,9 +374,35 @@ void BusDigital::setColorOrder(uint8_t colorOrder) {
|
||||
_colorOrder = colorOrder;
|
||||
}
|
||||
|
||||
void BusDigital::reinit() {
|
||||
// credit @willmmiles & @netmindz https://github.com/Aircoookie/WLED/pull/4056
|
||||
std::vector<LEDType> BusDigital::getLEDTypes() {
|
||||
return {
|
||||
{TYPE_WS2812_RGB, "D", PSTR("WS281x")},
|
||||
{TYPE_SK6812_RGBW, "D", PSTR("SK6812/WS2814 RGBW")},
|
||||
{TYPE_TM1814, "D", PSTR("TM1814")},
|
||||
{TYPE_WS2811_400KHZ, "D", PSTR("400kHz")},
|
||||
{TYPE_TM1829, "D", PSTR("TM1829")},
|
||||
{TYPE_UCS8903, "D", PSTR("UCS8903")},
|
||||
{TYPE_APA106, "D", PSTR("APA106/PL9823")},
|
||||
{TYPE_TM1914, "D", PSTR("TM1914")},
|
||||
{TYPE_FW1906, "D", PSTR("FW1906 GRBCW")},
|
||||
{TYPE_UCS8904, "D", PSTR("UCS8904 RGBW")},
|
||||
{TYPE_WS2805, "D", PSTR("WS2805 RGBCW")},
|
||||
{TYPE_SM16825, "D", PSTR("SM16825 RGBCW")},
|
||||
{TYPE_WS2812_1CH_X3, "D", PSTR("WS2811 White")},
|
||||
//{TYPE_WS2812_2CH_X3, "D", PSTR("WS2811 CCT")}, // not implemented
|
||||
//{TYPE_WS2812_WWA, "D", PSTR("WS2811 WWA")}, // not implemented
|
||||
{TYPE_WS2801, "2P", PSTR("WS2801")},
|
||||
{TYPE_APA102, "2P", PSTR("APA102")},
|
||||
{TYPE_LPD8806, "2P", PSTR("LPD8806")},
|
||||
{TYPE_LPD6803, "2P", PSTR("LPD6803")},
|
||||
{TYPE_P9813, "2P", PSTR("PP9813")},
|
||||
};
|
||||
}
|
||||
|
||||
void BusDigital::begin() {
|
||||
if (!_valid) return;
|
||||
PolyBus::begin(_busPtr, _iType, _pins);
|
||||
PolyBus::begin(_busPtr, _iType, _pins, _frequencykHz);
|
||||
}
|
||||
|
||||
void BusDigital::cleanup() {
|
||||
@@ -373,53 +412,83 @@ void BusDigital::cleanup() {
|
||||
_valid = false;
|
||||
_busPtr = nullptr;
|
||||
if (_data != nullptr) freeData();
|
||||
pinManager.deallocatePin(_pins[1], PinOwner::BusDigital);
|
||||
pinManager.deallocatePin(_pins[0], PinOwner::BusDigital);
|
||||
PinManager::deallocatePin(_pins[1], PinOwner::BusDigital);
|
||||
PinManager::deallocatePin(_pins[0], PinOwner::BusDigital);
|
||||
}
|
||||
|
||||
|
||||
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);
|
||||
_frequency = bc.frequency ? bc.frequency : WLED_PWM_FREQ;
|
||||
#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
|
||||
// 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
|
||||
#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 14
|
||||
#endif
|
||||
#endif
|
||||
|
||||
BusPwm::BusPwm(BusConfig &bc)
|
||||
: Bus(bc.type, bc.start, bc.autoWhite, 1, bc.reversed, bc.refreshReq) // hijack Off refresh flag to indicate usage of dithering
|
||||
{
|
||||
if (!isPWM(bc.type)) return;
|
||||
unsigned numPins = numPWMPins(bc.type);
|
||||
[[maybe_unused]] const bool dithering = _needsRefresh;
|
||||
_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;
|
||||
|
||||
managed_pin_type pins[numPins];
|
||||
for (unsigned i = 0; i < numPins; i++) pins[i] = {(int8_t)bc.pins[i], true};
|
||||
if (!PinManager::allocateMultiplePins(pins, numPins, PinOwner::BusPwm)) return;
|
||||
|
||||
#ifdef ESP8266
|
||||
analogWriteRange((1<<_depth)-1);
|
||||
analogWriteFreq(_frequency);
|
||||
#else
|
||||
_ledcStart = pinManager.allocateLedc(numPins);
|
||||
#else
|
||||
// for 2 pin PWM CCT strip pinManager will make sure both LEDC channels are in the same speed group and sharing the same timer
|
||||
_ledcStart = PinManager::allocateLedc(numPins);
|
||||
if (_ledcStart == 255) { //no more free LEDC channels
|
||||
deallocatePins(); return;
|
||||
PinManager::deallocateMultiplePins(pins, numPins, PinOwner::BusPwm);
|
||||
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
|
||||
// if _needsRefresh is true (UI hack) we are using dithering (credit @dedehai & @zalatnaicsongor)
|
||||
if (dithering) _depth = 12; // fixed 8 bit depth PWM with 4 bit dithering (ESP8266 has no hardware to support dithering)
|
||||
#endif
|
||||
|
||||
for (unsigned i = 0; i < numPins; i++) {
|
||||
uint8_t currentPin = bc.pins[i];
|
||||
if (!pinManager.allocatePin(currentPin, true, PinOwner::BusPwm)) {
|
||||
deallocatePins(); return;
|
||||
}
|
||||
_pins[i] = currentPin; //store only after allocatePin() succeeds
|
||||
_pins[i] = bc.pins[i]; // store only after allocateMultiplePins() succeeded
|
||||
#ifdef ESP8266
|
||||
pinMode(_pins[i], OUTPUT);
|
||||
#else
|
||||
ledcSetup(_ledcStart + i, _frequency, _depth);
|
||||
ledcAttachPin(_pins[i], _ledcStart + i);
|
||||
unsigned channel = _ledcStart + i;
|
||||
ledcSetup(channel, _frequency, _depth - (dithering*4)); // with dithering _frequency doesn't really matter as resolution is 8 bit
|
||||
ledcAttachPin(_pins[i], channel);
|
||||
// LEDC timer reset credit @dedehai
|
||||
uint8_t group = (channel / 8), timer = ((channel / 2) % 4); // same fromula as in ledcSetup()
|
||||
ledc_timer_rst((ledc_mode_t)group, (ledc_timer_t)timer); // reset timer so all timers are almost in sync (for phase shift)
|
||||
#endif
|
||||
}
|
||||
_hasRgb = hasRGB(bc.type);
|
||||
_hasWhite = hasWhite(bc.type);
|
||||
_hasCCT = hasCCT(bc.type);
|
||||
_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) {
|
||||
@@ -459,7 +528,7 @@ void BusPwm::setPixelColor(uint16_t pix, uint32_t c) {
|
||||
}
|
||||
|
||||
//does no index check
|
||||
uint32_t BusPwm::getPixelColor(uint16_t pix) {
|
||||
uint32_t BusPwm::getPixelColor(uint16_t pix) const {
|
||||
if (!_valid) return 0;
|
||||
// TODO getting the reverse from CCT is involved (a quick approximation when CCT blending is ste to 0 implemented)
|
||||
switch (_type) {
|
||||
@@ -479,79 +548,94 @@ 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 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
|
||||
// if _needsRefresh is true (UI hack) we are using dithering (credit @dedehai & @zalatnaicsongor)
|
||||
// https://github.com/Aircoookie/WLED/pull/4115 and https://github.com/zalatnaicsongor/WLED/pull/1)
|
||||
const bool dithering = _needsRefresh; // avoid working with bitfield
|
||||
const unsigned numPins = getPins();
|
||||
const unsigned maxBri = (1<<_depth); // possible values: 16384 (14), 8192 (13), 4096 (12), 2048 (11), 1024 (10), 512 (9) and 256 (8)
|
||||
[[maybe_unused]] const unsigned bitShift = dithering * 4; // if dithering, _depth is 12 bit but LEDC channel is set to 8 bit (using 4 fractional bits)
|
||||
|
||||
// use CIE brightness formula (linear + cubic) to approximate human eye perceived brightness
|
||||
// see: https://en.wikipedia.org/wiki/Lightness
|
||||
unsigned pwmBri = _bri;
|
||||
if (pwmBri < 21) { // linear response for values [0-20]
|
||||
pwmBri = (pwmBri * maxBri + 2300 / 2) / 2300 ; // adding '0.5' before division for correct rounding, 2300 gives a good match to CIE curve
|
||||
} else { // cubic response for values [21-255]
|
||||
float temp = float(pwmBri + 41) / float(255 + 41); // 41 is to match offset & slope to linear part
|
||||
temp = temp * temp * temp * (float)maxBri;
|
||||
pwmBri = (unsigned)temp; // pwmBri is in range [0-maxBri] C
|
||||
}
|
||||
|
||||
[[maybe_unused]] unsigned hPoint = 0; // phase shift (0 - maxBri)
|
||||
// we will be phase shifting every channel by previous pulse length (plus dead time if required)
|
||||
// phase shifting is only mandatory when using H-bridge to drive reverse-polarity PWM CCT (2 wire) LED type
|
||||
// CCT additive blending must be 0 (WW & CW will not overlap) otherwise signals *will* overlap
|
||||
// for all other cases it will just try to "spread" the load on PSU
|
||||
// Phase shifting requires that LEDC timers are synchronised (see setup()). For PWM CCT (and H-bridge) it is
|
||||
// also mandatory that both channels use the same timer (pinManager takes care of that).
|
||||
for (unsigned i = 0; i < numPins; i++) {
|
||||
unsigned scaled = (_data[i] * pwmBri) / 255;
|
||||
if (_reversed) scaled = maxBri - scaled;
|
||||
unsigned duty = (_data[i] * pwmBri) / 255;
|
||||
#ifdef ESP8266
|
||||
analogWrite(_pins[i], scaled);
|
||||
if (_reversed) duty = maxBri - duty;
|
||||
analogWrite(_pins[i], duty);
|
||||
#else
|
||||
ledcWrite(_ledcStart + i, scaled);
|
||||
int deadTime = 0;
|
||||
if (_type == TYPE_ANALOG_2CH && Bus::getCCTBlend() == 0) {
|
||||
// add dead time between signals (when using dithering, two full 8bit pulses are required)
|
||||
deadTime = (1+dithering) << bitShift;
|
||||
// we only need to take care of shortening the signal at (almost) full brightness otherwise pulses may overlap
|
||||
if (_bri >= 254 && duty >= maxBri / 2 && duty < maxBri) duty -= deadTime << 1; // shorten duty of larger signal except if full on
|
||||
if (_reversed) deadTime = -deadTime; // need to invert dead time to make phaseshift go the opposite way so low signals dont overlap
|
||||
}
|
||||
if (_reversed) duty = maxBri - duty;
|
||||
unsigned channel = _ledcStart + i;
|
||||
unsigned gr = channel/8; // high/low speed group
|
||||
unsigned ch = channel%8; // group channel
|
||||
// directly write to LEDC struct as there is no HAL exposed function for dithering
|
||||
// duty has 20 bit resolution with 4 fractional bits (24 bits in total)
|
||||
LEDC.channel_group[gr].channel[ch].duty.duty = duty << ((!dithering)*4); // lowest 4 bits are used for dithering, shift by 4 bits if not using dithering
|
||||
LEDC.channel_group[gr].channel[ch].hpoint.hpoint = hPoint >> bitShift; // hPoint is at _depth resolution (needs shifting if dithering)
|
||||
ledc_update_duty((ledc_mode_t)gr, (ledc_channel_t)ch);
|
||||
hPoint += duty + deadTime; // offset to cascade the signals
|
||||
if (hPoint >= maxBri) hPoint = 0; // offset it out of bounds, reset
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t BusPwm::getPins(uint8_t* pinArray) {
|
||||
uint8_t BusPwm::getPins(uint8_t* pinArray) const {
|
||||
if (!_valid) return 0;
|
||||
uint8_t numPins = NUM_PWM_PINS(_type);
|
||||
for (unsigned i = 0; i < numPins; i++) {
|
||||
pinArray[i] = _pins[i];
|
||||
}
|
||||
unsigned numPins = numPWMPins(_type);
|
||||
if (pinArray) for (unsigned i = 0; i < numPins; i++) pinArray[i] = _pins[i];
|
||||
return numPins;
|
||||
}
|
||||
|
||||
// credit @willmmiles & @netmindz https://github.com/Aircoookie/WLED/pull/4056
|
||||
std::vector<LEDType> BusPwm::getLEDTypes() {
|
||||
return {
|
||||
{TYPE_ANALOG_1CH, "A", PSTR("PWM White")},
|
||||
{TYPE_ANALOG_2CH, "AA", PSTR("PWM CCT")},
|
||||
{TYPE_ANALOG_3CH, "AAA", PSTR("PWM RGB")},
|
||||
{TYPE_ANALOG_4CH, "AAAA", PSTR("PWM RGBW")},
|
||||
{TYPE_ANALOG_5CH, "AAAAA", PSTR("PWM RGB+CCT")},
|
||||
//{TYPE_ANALOG_6CH, "AAAAAA", PSTR("PWM RGB+DCCT")}, // unimplementable ATM
|
||||
};
|
||||
}
|
||||
|
||||
void BusPwm::deallocatePins() {
|
||||
uint8_t numPins = NUM_PWM_PINS(_type);
|
||||
unsigned numPins = getPins();
|
||||
for (unsigned i = 0; i < numPins; i++) {
|
||||
pinManager.deallocatePin(_pins[i], PinOwner::BusPwm);
|
||||
if (!pinManager.isPinOk(_pins[i])) continue;
|
||||
PinManager::deallocatePin(_pins[i], PinOwner::BusPwm);
|
||||
if (!PinManager::isPinOk(_pins[i])) continue;
|
||||
#ifdef ESP8266
|
||||
digitalWrite(_pins[i], LOW); //turn off PWM interrupt
|
||||
#else
|
||||
if (_ledcStart < 16) ledcDetachPin(_pins[i]);
|
||||
if (_ledcStart < WLED_MAX_ANALOG_CHANNELS) ledcDetachPin(_pins[i]);
|
||||
#endif
|
||||
}
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
pinManager.deallocateLedc(_ledcStart, numPins);
|
||||
PinManager::deallocateLedc(_ledcStart, numPins);
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -560,14 +644,17 @@ BusOnOff::BusOnOff(BusConfig &bc)
|
||||
: Bus(bc.type, bc.start, bc.autoWhite, 1, bc.reversed)
|
||||
, _onoffdata(0)
|
||||
{
|
||||
if (bc.type != TYPE_ONOFF) return;
|
||||
if (!Bus::isOnOff(bc.type)) return;
|
||||
|
||||
uint8_t currentPin = bc.pins[0];
|
||||
if (!pinManager.allocatePin(currentPin, true, PinOwner::BusOnOff)) {
|
||||
if (!PinManager::allocatePin(currentPin, true, PinOwner::BusOnOff)) {
|
||||
return;
|
||||
}
|
||||
_pin = currentPin; //store only after allocatePin() succeeds
|
||||
pinMode(_pin, OUTPUT);
|
||||
_hasRgb = false;
|
||||
_hasWhite = false;
|
||||
_hasCCT = false;
|
||||
_data = &_onoffdata; // avoid malloc() and use stack
|
||||
_valid = true;
|
||||
DEBUG_PRINTF_P(PSTR("%successfully inited On/Off strip with pin %u\n"), _valid?"S":"Uns", _pin);
|
||||
@@ -583,7 +670,7 @@ void BusOnOff::setPixelColor(uint16_t pix, uint32_t c) {
|
||||
_data[0] = bool(r|g|b|w) && bool(_bri) ? 0xFF : 0;
|
||||
}
|
||||
|
||||
uint32_t BusOnOff::getPixelColor(uint16_t pix) {
|
||||
uint32_t BusOnOff::getPixelColor(uint16_t pix) const {
|
||||
if (!_valid) return 0;
|
||||
return RGBW32(_data[0], _data[0], _data[0], _data[0]);
|
||||
}
|
||||
@@ -593,12 +680,18 @@ void BusOnOff::show() {
|
||||
digitalWrite(_pin, _reversed ? !(bool)_data[0] : (bool)_data[0]);
|
||||
}
|
||||
|
||||
uint8_t BusOnOff::getPins(uint8_t* pinArray) {
|
||||
uint8_t BusOnOff::getPins(uint8_t* pinArray) const {
|
||||
if (!_valid) return 0;
|
||||
pinArray[0] = _pin;
|
||||
if (pinArray) pinArray[0] = _pin;
|
||||
return 1;
|
||||
}
|
||||
|
||||
// credit @willmmiles & @netmindz https://github.com/Aircoookie/WLED/pull/4056
|
||||
std::vector<LEDType> BusOnOff::getLEDTypes() {
|
||||
return {
|
||||
{TYPE_ONOFF, "", PSTR("On/Off")},
|
||||
};
|
||||
}
|
||||
|
||||
BusNetwork::BusNetwork(BusConfig &bc)
|
||||
: Bus(bc.type, bc.start, bc.autoWhite, bc.count)
|
||||
@@ -606,59 +699,71 @@ BusNetwork::BusNetwork(BusConfig &bc)
|
||||
{
|
||||
switch (bc.type) {
|
||||
case TYPE_NET_ARTNET_RGB:
|
||||
_rgbw = false;
|
||||
_UDPtype = 2;
|
||||
break;
|
||||
case TYPE_NET_ARTNET_RGBW:
|
||||
_rgbw = true;
|
||||
_UDPtype = 2;
|
||||
break;
|
||||
case TYPE_NET_E131_RGB:
|
||||
_rgbw = false;
|
||||
_UDPtype = 1;
|
||||
break;
|
||||
default: // TYPE_NET_DDP_RGB / TYPE_NET_DDP_RGBW
|
||||
_rgbw = bc.type == TYPE_NET_DDP_RGBW;
|
||||
_UDPtype = 0;
|
||||
break;
|
||||
}
|
||||
_UDPchannels = _rgbw ? 4 : 3;
|
||||
_hasRgb = hasRGB(bc.type);
|
||||
_hasWhite = hasWhite(bc.type);
|
||||
_hasCCT = false;
|
||||
_UDPchannels = _hasWhite + 3;
|
||||
_client = IPAddress(bc.pins[0],bc.pins[1],bc.pins[2],bc.pins[3]);
|
||||
_valid = (allocData(_len * _UDPchannels) != nullptr);
|
||||
_valid = (allocateData(_len * _UDPchannels) != nullptr);
|
||||
DEBUG_PRINTF_P(PSTR("%successfully inited virtual strip with type %u and IP %u.%u.%u.%u\n"), _valid?"S":"Uns", bc.type, bc.pins[0], bc.pins[1], bc.pins[2], bc.pins[3]);
|
||||
}
|
||||
|
||||
void BusNetwork::setPixelColor(uint16_t pix, uint32_t c) {
|
||||
if (!_valid || pix >= _len) return;
|
||||
if (_rgbw) c = autoWhiteCalc(c);
|
||||
if (_hasWhite) 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);
|
||||
if (_rgbw) _data[offset+3] = W(c);
|
||||
if (_hasWhite) _data[offset+3] = W(c);
|
||||
}
|
||||
|
||||
uint32_t BusNetwork::getPixelColor(uint16_t pix) {
|
||||
uint32_t BusNetwork::getPixelColor(uint16_t pix) const {
|
||||
if (!_valid || pix >= _len) return 0;
|
||||
uint16_t offset = pix * _UDPchannels;
|
||||
return RGBW32(_data[offset], _data[offset+1], _data[offset+2], (_rgbw ? _data[offset+3] : 0));
|
||||
unsigned offset = pix * _UDPchannels;
|
||||
return RGBW32(_data[offset], _data[offset+1], _data[offset+2], (hasWhite() ? _data[offset+3] : 0));
|
||||
}
|
||||
|
||||
void BusNetwork::show() {
|
||||
if (!_valid || !canShow()) return;
|
||||
_broadcastLock = true;
|
||||
realtimeBroadcast(_UDPtype, _client, _len, _data, _bri, _rgbw);
|
||||
realtimeBroadcast(_UDPtype, _client, _len, _data, _bri, hasWhite());
|
||||
_broadcastLock = false;
|
||||
}
|
||||
|
||||
uint8_t BusNetwork::getPins(uint8_t* pinArray) {
|
||||
for (unsigned i = 0; i < 4; i++) {
|
||||
pinArray[i] = _client[i];
|
||||
}
|
||||
uint8_t BusNetwork::getPins(uint8_t* pinArray) const {
|
||||
if (pinArray) for (unsigned i = 0; i < 4; i++) pinArray[i] = _client[i];
|
||||
return 4;
|
||||
}
|
||||
|
||||
// credit @willmmiles & @netmindz https://github.com/Aircoookie/WLED/pull/4056
|
||||
std::vector<LEDType> BusNetwork::getLEDTypes() {
|
||||
return {
|
||||
{TYPE_NET_DDP_RGB, "N", PSTR("DDP RGB (network)")}, // should be "NNNN" to determine 4 "pin" fields
|
||||
{TYPE_NET_ARTNET_RGB, "N", PSTR("Art-Net RGB (network)")},
|
||||
{TYPE_NET_DDP_RGBW, "N", PSTR("DDP RGBW (network)")},
|
||||
{TYPE_NET_ARTNET_RGBW, "N", PSTR("Art-Net RGBW (network)")},
|
||||
// hypothetical extensions
|
||||
//{TYPE_VIRTUAL_I2C_W, "V", PSTR("I2C White (virtual)")}, // allows setting I2C address in _pin[0]
|
||||
//{TYPE_VIRTUAL_I2C_CCT, "V", PSTR("I2C CCT (virtual)")}, // allows setting I2C address in _pin[0]
|
||||
//{TYPE_VIRTUAL_I2C_RGB, "VVV", PSTR("I2C RGB (virtual)")}, // allows setting I2C address in _pin[0] and 2 additional values in _pin[1] & _pin[2]
|
||||
//{TYPE_USERMOD, "VVVVV", PSTR("Usermod (virtual)")}, // 5 data fields (see https://github.com/Aircoookie/WLED/pull/4123)
|
||||
};
|
||||
}
|
||||
|
||||
void BusNetwork::cleanup() {
|
||||
_type = I_NONE;
|
||||
_valid = false;
|
||||
@@ -668,13 +773,13 @@ void BusNetwork::cleanup() {
|
||||
|
||||
//utility to get the approx. memory usage of a given BusConfig
|
||||
uint32_t BusManager::memUsage(BusConfig &bc) {
|
||||
if (bc.type == TYPE_ONOFF || IS_PWM(bc.type)) return 5;
|
||||
if (Bus::isOnOff(bc.type) || Bus::isPWM(bc.type)) return OUTPUT_MAX_PINS;
|
||||
|
||||
uint16_t len = bc.count + bc.skipAmount;
|
||||
uint16_t channels = Bus::getNumberOfChannels(bc.type);
|
||||
uint16_t multiplier = 1;
|
||||
if (IS_DIGITAL(bc.type)) { // digital types
|
||||
if (IS_16BIT(bc.type)) len *= 2; // 16-bit LEDs
|
||||
unsigned len = bc.count + bc.skipAmount;
|
||||
unsigned channels = Bus::getNumberOfChannels(bc.type);
|
||||
unsigned multiplier = 1;
|
||||
if (Bus::isDigital(bc.type)) { // digital types
|
||||
if (Bus::is16bit(bc.type)) len *= 2; // 16-bit LEDs
|
||||
#ifdef ESP8266
|
||||
if (bc.pins[0] == 3) { //8266 DMA uses 5x the mem
|
||||
multiplier = 5;
|
||||
@@ -686,13 +791,19 @@ uint32_t BusManager::memUsage(BusConfig &bc) {
|
||||
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) {
|
||||
if (getNumBusses() - getNumVirtualBusses() >= WLED_MAX_BUSSES) return -1;
|
||||
if (IS_VIRTUAL(bc.type)) {
|
||||
if (Bus::isVirtual(bc.type)) {
|
||||
busses[numBusses] = new BusNetwork(bc);
|
||||
} else if (IS_DIGITAL(bc.type)) {
|
||||
} else if (Bus::isDigital(bc.type)) {
|
||||
busses[numBusses] = new BusDigital(bc, numBusses, colorOrderMap);
|
||||
} else if (bc.type == TYPE_ONOFF) {
|
||||
} else if (Bus::isOnOff(bc.type)) {
|
||||
busses[numBusses] = new BusOnOff(bc);
|
||||
} else {
|
||||
busses[numBusses] = new BusPwm(bc);
|
||||
@@ -700,7 +811,32 @@ int BusManager::add(BusConfig &bc) {
|
||||
return numBusses++;
|
||||
}
|
||||
|
||||
void BusManager::useParallelOutput(void) {
|
||||
// credit @willmmiles
|
||||
static String LEDTypesToJson(const std::vector<LEDType>& types) {
|
||||
String json;
|
||||
for (const auto &type : types) {
|
||||
// capabilities follows similar pattern as JSON API
|
||||
int capabilities = Bus::hasRGB(type.id) | Bus::hasWhite(type.id)<<1 | Bus::hasCCT(type.id)<<2 | Bus::is16bit(type.id)<<4 | Bus::mustRefresh(type.id)<<5;
|
||||
char str[256];
|
||||
sprintf_P(str, PSTR("{i:%d,c:%d,t:\"%s\",n:\"%s\"},"), type.id, capabilities, type.type, type.name);
|
||||
json += str;
|
||||
}
|
||||
return json;
|
||||
}
|
||||
|
||||
// credit @willmmiles & @netmindz https://github.com/Aircoookie/WLED/pull/4056
|
||||
String BusManager::getLEDTypesJSONString() {
|
||||
String json = "[";
|
||||
json += LEDTypesToJson(BusDigital::getLEDTypes());
|
||||
json += LEDTypesToJson(BusOnOff::getLEDTypes());
|
||||
json += LEDTypesToJson(BusPwm::getLEDTypes());
|
||||
json += LEDTypesToJson(BusNetwork::getLEDTypes());
|
||||
//json += LEDTypesToJson(BusVirtual::getLEDTypes());
|
||||
json.setCharAt(json.length()-1, ']'); // replace last comma with bracket
|
||||
return json;
|
||||
}
|
||||
|
||||
void BusManager::useParallelOutput() {
|
||||
_parallelOutputs = 8; // hardcoded since we use NPB I2S x8 methods
|
||||
PolyBus::setParallelI2S1Output();
|
||||
}
|
||||
@@ -738,7 +874,7 @@ void BusManager::esp32RMTInvertIdle() {
|
||||
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;
|
||||
if (busses[u]->getLength()==0 || !busses[u]->isDigital() || busses[u]->is2Pin()) 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;
|
||||
@@ -754,13 +890,13 @@ void BusManager::esp32RMTInvertIdle() {
|
||||
void BusManager::on() {
|
||||
#ifdef ESP8266
|
||||
//Fix for turning off onboard LED breaking bus
|
||||
if (pinManager.getPinOwner(LED_BUILTIN) == PinOwner::BusDigital) {
|
||||
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 (busses[i]->isDigital() && busses[i]->getPins(pins)) {
|
||||
if (pins[0] == LED_BUILTIN || pins[1] == LED_BUILTIN) {
|
||||
BusDigital *bus = static_cast<BusDigital*>(busses[i]);
|
||||
bus->reinit();
|
||||
bus->begin();
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -776,7 +912,7 @@ 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) {
|
||||
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);
|
||||
@@ -793,7 +929,6 @@ void BusManager::show() {
|
||||
busses[i]->show();
|
||||
_milliAmpsUsed += busses[i]->getUsedCurrent();
|
||||
}
|
||||
if (_milliAmpsUsed) _milliAmpsUsed += MA_FOR_ESP;
|
||||
}
|
||||
|
||||
void BusManager::setStatusPixel(uint32_t c) {
|
||||
@@ -828,7 +963,7 @@ void BusManager::setSegmentCCT(int16_t cct, bool allowWBCorrection) {
|
||||
uint32_t BusManager::getPixelColor(uint16_t pix) {
|
||||
for (unsigned i = 0; i < numBusses; i++) {
|
||||
unsigned bstart = busses[i]->getStart();
|
||||
if (pix < bstart || pix >= bstart + busses[i]->getLength()) continue;
|
||||
if (!busses[i]->containsPixel(pix)) continue;
|
||||
return busses[i]->getPixelColor(pix - bstart);
|
||||
}
|
||||
return 0;
|
||||
@@ -848,7 +983,7 @@ 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;
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
|
||||
#include "const.h"
|
||||
#include <vector>
|
||||
|
||||
//colors.cpp
|
||||
uint16_t approximateKelvinFromRGB(uint32_t rgb);
|
||||
@@ -21,6 +22,299 @@ 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
|
||||
|
||||
struct BusConfig; // forward declaration
|
||||
|
||||
// Defines an LED Strip and its color ordering.
|
||||
typedef struct {
|
||||
uint16_t start;
|
||||
uint16_t len;
|
||||
uint8_t colorOrder;
|
||||
} ColorOrderMapEntry;
|
||||
|
||||
struct ColorOrderMap {
|
||||
bool add(uint16_t start, uint16_t len, uint8_t colorOrder);
|
||||
|
||||
inline uint8_t count() const { return _mappings.size(); }
|
||||
inline void reserve(size_t num) { _mappings.reserve(num); }
|
||||
|
||||
void reset() {
|
||||
_mappings.clear();
|
||||
_mappings.shrink_to_fit();
|
||||
}
|
||||
|
||||
const ColorOrderMapEntry* get(uint8_t n) const {
|
||||
if (n >= count()) return nullptr;
|
||||
return &(_mappings[n]);
|
||||
}
|
||||
|
||||
[[gnu::hot]] uint8_t getPixelColorOrder(uint16_t pix, uint8_t defaultColorOrder) const;
|
||||
|
||||
private:
|
||||
std::vector<ColorOrderMapEntry> _mappings;
|
||||
};
|
||||
|
||||
|
||||
typedef struct {
|
||||
uint8_t id;
|
||||
const char *type;
|
||||
const char *name;
|
||||
} LEDType;
|
||||
|
||||
|
||||
//parent class of BusDigital, BusPwm, and BusNetwork
|
||||
class Bus {
|
||||
public:
|
||||
Bus(uint8_t type, uint16_t start, uint8_t aw, uint16_t len = 1, bool reversed = false, bool refresh = false)
|
||||
: _type(type)
|
||||
, _bri(255)
|
||||
, _start(start)
|
||||
, _len(len)
|
||||
, _reversed(reversed)
|
||||
, _valid(false)
|
||||
, _needsRefresh(refresh)
|
||||
, _data(nullptr) // keep data access consistent across all types of buses
|
||||
{
|
||||
_autoWhiteMode = Bus::hasWhite(type) ? aw : RGBW_MODE_MANUAL_ONLY;
|
||||
};
|
||||
|
||||
virtual ~Bus() {} //throw the bus under the bus
|
||||
|
||||
virtual void begin() {};
|
||||
virtual void show() = 0;
|
||||
virtual bool canShow() const { return true; }
|
||||
virtual void setStatusPixel(uint32_t c) {}
|
||||
virtual void setPixelColor(uint16_t pix, uint32_t c) = 0;
|
||||
virtual void setBrightness(uint8_t b) { _bri = b; };
|
||||
virtual void setColorOrder(uint8_t co) {}
|
||||
virtual uint32_t getPixelColor(uint16_t pix) const { return 0; }
|
||||
virtual uint8_t getPins(uint8_t* pinArray = nullptr) const { return 0; }
|
||||
virtual uint16_t getLength() const { return isOk() ? _len : 0; }
|
||||
virtual uint8_t getColorOrder() const { return COL_ORDER_RGB; }
|
||||
virtual uint8_t skippedLeds() const { return 0; }
|
||||
virtual uint16_t getFrequency() const { return 0U; }
|
||||
virtual uint16_t getLEDCurrent() const { return 0; }
|
||||
virtual uint16_t getUsedCurrent() const { return 0; }
|
||||
virtual uint16_t getMaxCurrent() const { return 0; }
|
||||
|
||||
inline bool hasRGB() const { return _hasRgb; }
|
||||
inline bool hasWhite() const { return _hasWhite; }
|
||||
inline bool hasCCT() const { return _hasCCT; }
|
||||
inline bool isDigital() const { return isDigital(_type); }
|
||||
inline bool is2Pin() const { return is2Pin(_type); }
|
||||
inline bool isOnOff() const { return isOnOff(_type); }
|
||||
inline bool isPWM() const { return isPWM(_type); }
|
||||
inline bool isVirtual() const { return isVirtual(_type); }
|
||||
inline bool is16bit() const { return is16bit(_type); }
|
||||
inline bool mustRefresh() const { return mustRefresh(_type); }
|
||||
inline void setReversed(bool reversed) { _reversed = reversed; }
|
||||
inline void setStart(uint16_t start) { _start = start; }
|
||||
inline void setAutoWhiteMode(uint8_t m) { if (m < 5) _autoWhiteMode = m; }
|
||||
inline uint8_t getAutoWhiteMode() const { return _autoWhiteMode; }
|
||||
inline uint8_t getNumberOfChannels() const { return hasWhite() + 3*hasRGB() + hasCCT(); }
|
||||
inline uint16_t getStart() const { return _start; }
|
||||
inline uint8_t getType() const { return _type; }
|
||||
inline bool isOk() const { return _valid; }
|
||||
inline bool isReversed() const { return _reversed; }
|
||||
inline bool isOffRefreshRequired() const { return _needsRefresh; }
|
||||
inline bool containsPixel(uint16_t pix) const { return pix >= _start && pix < _start + _len; }
|
||||
|
||||
static inline std::vector<LEDType> getLEDTypes() { return {{TYPE_NONE, "", PSTR("None")}}; } // not used. just for reference for derived classes
|
||||
static constexpr uint8_t getNumberOfPins(uint8_t type) { return isVirtual(type) ? 4 : isPWM(type) ? numPWMPins(type) : is2Pin(type) + 1; } // credit @PaoloTK
|
||||
static constexpr uint8_t getNumberOfChannels(uint8_t type) { return hasWhite(type) + 3*hasRGB(type) + hasCCT(type); }
|
||||
static constexpr bool hasRGB(uint8_t type) {
|
||||
return !((type >= TYPE_WS2812_1CH && type <= TYPE_WS2812_WWA) || type == TYPE_ANALOG_1CH || type == TYPE_ANALOG_2CH || type == TYPE_ONOFF);
|
||||
}
|
||||
static constexpr bool hasWhite(uint8_t type) {
|
||||
return (type >= TYPE_WS2812_1CH && type <= TYPE_WS2812_WWA) ||
|
||||
type == TYPE_SK6812_RGBW || type == TYPE_TM1814 || type == TYPE_UCS8904 ||
|
||||
type == TYPE_FW1906 || type == TYPE_WS2805 || type == TYPE_SM16825 || // digital types with white channel
|
||||
(type > TYPE_ONOFF && type <= TYPE_ANALOG_5CH && type != TYPE_ANALOG_3CH) || // analog types with white channel
|
||||
type == TYPE_NET_DDP_RGBW || type == TYPE_NET_ARTNET_RGBW; // network types with white channel
|
||||
}
|
||||
static constexpr bool hasCCT(uint8_t type) {
|
||||
return type == TYPE_WS2812_2CH_X3 || type == TYPE_WS2812_WWA ||
|
||||
type == TYPE_ANALOG_2CH || type == TYPE_ANALOG_5CH ||
|
||||
type == TYPE_FW1906 || type == TYPE_WS2805 ||
|
||||
type == TYPE_SM16825;
|
||||
}
|
||||
static constexpr bool isTypeValid(uint8_t type) { return (type > 15 && type < 128); }
|
||||
static constexpr bool isDigital(uint8_t type) { return (type >= TYPE_DIGITAL_MIN && type <= TYPE_DIGITAL_MAX) || is2Pin(type); }
|
||||
static constexpr bool is2Pin(uint8_t type) { return (type >= TYPE_2PIN_MIN && type <= TYPE_2PIN_MAX); }
|
||||
static constexpr bool isOnOff(uint8_t type) { return (type == TYPE_ONOFF); }
|
||||
static constexpr bool isPWM(uint8_t type) { return (type >= TYPE_ANALOG_MIN && type <= TYPE_ANALOG_MAX); }
|
||||
static constexpr bool isVirtual(uint8_t type) { return (type >= TYPE_VIRTUAL_MIN && type <= TYPE_VIRTUAL_MAX); }
|
||||
static constexpr bool is16bit(uint8_t type) { return type == TYPE_UCS8903 || type == TYPE_UCS8904 || type == TYPE_SM16825; }
|
||||
static constexpr bool mustRefresh(uint8_t type) { return type == TYPE_TM1814; }
|
||||
static constexpr int numPWMPins(uint8_t type) { return (type - 40); }
|
||||
|
||||
static inline int16_t getCCT() { return _cct; }
|
||||
static inline void setGlobalAWMode(uint8_t m) { if (m < 5) _gAWM = m; else _gAWM = AW_GLOBAL_DISABLED; }
|
||||
static inline uint8_t getGlobalAWMode() { return _gAWM; }
|
||||
static inline void setCCT(int16_t cct) { _cct = cct; }
|
||||
static inline uint8_t getCCTBlend() { return _cctBlend; }
|
||||
static inline void setCCTBlend(uint8_t b) {
|
||||
_cctBlend = (std::min((int)b,100) * 127) / 100;
|
||||
//compile-time limiter for hardware that can't power both white channels at max
|
||||
#ifdef WLED_MAX_CCT_BLEND
|
||||
if (_cctBlend > WLED_MAX_CCT_BLEND) _cctBlend = WLED_MAX_CCT_BLEND;
|
||||
#endif
|
||||
}
|
||||
static void calculateCCT(uint32_t c, uint8_t &ww, uint8_t &cw);
|
||||
|
||||
protected:
|
||||
uint8_t _type;
|
||||
uint8_t _bri;
|
||||
uint16_t _start;
|
||||
uint16_t _len;
|
||||
//struct { //using bitfield struct adds abour 250 bytes to binary size
|
||||
bool _reversed;// : 1;
|
||||
bool _valid;// : 1;
|
||||
bool _needsRefresh;// : 1;
|
||||
bool _hasRgb;// : 1;
|
||||
bool _hasWhite;// : 1;
|
||||
bool _hasCCT;// : 1;
|
||||
//} __attribute__ ((packed));
|
||||
uint8_t _autoWhiteMode;
|
||||
uint8_t *_data;
|
||||
// global Auto White Calculation override
|
||||
static uint8_t _gAWM;
|
||||
// _cct has the following menaings (see calculateCCT() & BusManager::setSegmentCCT()):
|
||||
// -1 means to extract approximate CCT value in K from RGB (in calcualteCCT())
|
||||
// [0,255] is the exact CCT value where 0 means warm and 255 cold
|
||||
// [1900,10060] only for color correction expressed in K (colorBalanceFromKelvin())
|
||||
static int16_t _cct;
|
||||
// _cctBlend determines WW/CW blending:
|
||||
// 0 - linear (CCT 127 => 50% warm, 50% cold)
|
||||
// 63 - semi additive/nonlinear (CCT 127 => 66% warm, 66% cold)
|
||||
// 127 - additive CCT blending (CCT 127 => 100% warm, 100% cold)
|
||||
static uint8_t _cctBlend;
|
||||
|
||||
uint32_t autoWhiteCalc(uint32_t c) const;
|
||||
uint8_t *allocateData(size_t size = 1);
|
||||
void freeData() { if (_data != nullptr) free(_data); _data = nullptr; }
|
||||
};
|
||||
|
||||
|
||||
class BusDigital : public Bus {
|
||||
public:
|
||||
BusDigital(BusConfig &bc, uint8_t nr, const ColorOrderMap &com);
|
||||
~BusDigital() { cleanup(); }
|
||||
|
||||
void show() override;
|
||||
bool canShow() const override;
|
||||
void setBrightness(uint8_t b) override;
|
||||
void setStatusPixel(uint32_t c) override;
|
||||
[[gnu::hot]] void setPixelColor(uint16_t pix, uint32_t c) override;
|
||||
void setColorOrder(uint8_t colorOrder) override;
|
||||
[[gnu::hot]] uint32_t getPixelColor(uint16_t pix) const override;
|
||||
uint8_t getColorOrder() const override { return _colorOrder; }
|
||||
uint8_t getPins(uint8_t* pinArray = nullptr) const override;
|
||||
uint8_t skippedLeds() const override { return _skip; }
|
||||
uint16_t getFrequency() const override { return _frequencykHz; }
|
||||
uint16_t getLEDCurrent() const override { return _milliAmpsPerLed; }
|
||||
uint16_t getUsedCurrent() const override { return _milliAmpsTotal; }
|
||||
uint16_t getMaxCurrent() const override { return _milliAmpsMax; }
|
||||
void begin() override;
|
||||
void cleanup();
|
||||
|
||||
static std::vector<LEDType> getLEDTypes();
|
||||
|
||||
private:
|
||||
uint8_t _skip;
|
||||
uint8_t _colorOrder;
|
||||
uint8_t _pins[2];
|
||||
uint8_t _iType;
|
||||
uint16_t _frequencykHz;
|
||||
uint8_t _milliAmpsPerLed;
|
||||
uint16_t _milliAmpsMax;
|
||||
void * _busPtr;
|
||||
const ColorOrderMap &_colorOrderMap;
|
||||
|
||||
static uint16_t _milliAmpsTotal; // is overwitten/recalculated on each show()
|
||||
|
||||
inline uint32_t restoreColorLossy(uint32_t c, uint8_t restoreBri) const {
|
||||
if (restoreBri < 255) {
|
||||
uint8_t* chan = (uint8_t*) &c;
|
||||
for (uint_fast8_t i=0; i<4; i++) {
|
||||
uint_fast16_t val = chan[i];
|
||||
chan[i] = ((val << 8) + restoreBri) / (restoreBri + 1); //adding _bri slightly improves recovery / stops degradation on re-scale
|
||||
}
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
uint8_t estimateCurrentAndLimitBri();
|
||||
};
|
||||
|
||||
|
||||
class BusPwm : public Bus {
|
||||
public:
|
||||
BusPwm(BusConfig &bc);
|
||||
~BusPwm() { cleanup(); }
|
||||
|
||||
void setPixelColor(uint16_t pix, uint32_t c) override;
|
||||
uint32_t getPixelColor(uint16_t pix) const override; //does no index check
|
||||
uint8_t getPins(uint8_t* pinArray = nullptr) const override;
|
||||
uint16_t getFrequency() const override { return _frequency; }
|
||||
void show() override;
|
||||
void cleanup() { deallocatePins(); }
|
||||
|
||||
static std::vector<LEDType> getLEDTypes();
|
||||
|
||||
private:
|
||||
uint8_t _pins[OUTPUT_MAX_PINS];
|
||||
uint8_t _pwmdata[OUTPUT_MAX_PINS];
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
uint8_t _ledcStart;
|
||||
#endif
|
||||
uint8_t _depth;
|
||||
uint16_t _frequency;
|
||||
|
||||
void deallocatePins();
|
||||
};
|
||||
|
||||
|
||||
class BusOnOff : public Bus {
|
||||
public:
|
||||
BusOnOff(BusConfig &bc);
|
||||
~BusOnOff() { cleanup(); }
|
||||
|
||||
void setPixelColor(uint16_t pix, uint32_t c) override;
|
||||
uint32_t getPixelColor(uint16_t pix) const override;
|
||||
uint8_t getPins(uint8_t* pinArray) const override;
|
||||
void show() override;
|
||||
void cleanup() { PinManager::deallocatePin(_pin, PinOwner::BusOnOff); }
|
||||
|
||||
static std::vector<LEDType> getLEDTypes();
|
||||
|
||||
private:
|
||||
uint8_t _pin;
|
||||
uint8_t _onoffdata;
|
||||
};
|
||||
|
||||
|
||||
class BusNetwork : public Bus {
|
||||
public:
|
||||
BusNetwork(BusConfig &bc);
|
||||
~BusNetwork() { cleanup(); }
|
||||
|
||||
bool canShow() const override { return !_broadcastLock; } // this should be a return value from UDP routine if it is still sending data out
|
||||
void setPixelColor(uint16_t pix, uint32_t c) override;
|
||||
uint32_t getPixelColor(uint16_t pix) const override;
|
||||
uint8_t getPins(uint8_t* pinArray = nullptr) const override;
|
||||
void show() override;
|
||||
void cleanup();
|
||||
|
||||
static std::vector<LEDType> getLEDTypes();
|
||||
|
||||
private:
|
||||
IPAddress _client;
|
||||
uint8_t _UDPtype;
|
||||
uint8_t _UDPchannels;
|
||||
bool _broadcastLock;
|
||||
};
|
||||
|
||||
|
||||
//temporary struct for passing bus configuration to bus
|
||||
struct BusConfig {
|
||||
uint8_t type;
|
||||
@@ -51,10 +345,7 @@ struct BusConfig {
|
||||
{
|
||||
refreshReq = (bool) GET_BIT(busType,7);
|
||||
type = busType & 0x7F; // bit 7 may be/is hacked to include refresh info (1=refresh in off state, 0=no refresh)
|
||||
size_t nPins = 1;
|
||||
if (IS_VIRTUAL(type)) nPins = 4; //virtual network bus. 4 "pins" store IP address
|
||||
else if (IS_2PIN(type)) nPins = 2;
|
||||
else if (IS_PWM(type)) nPins = NUM_PWM_PINS(type);
|
||||
size_t nPins = Bus::getNumberOfPins(type);
|
||||
for (size_t i = 0; i < nPins; i++) pins[i] = ppins[i];
|
||||
}
|
||||
|
||||
@@ -72,282 +363,15 @@ struct BusConfig {
|
||||
};
|
||||
|
||||
|
||||
// Defines an LED Strip and its color ordering.
|
||||
struct ColorOrderMapEntry {
|
||||
uint16_t start;
|
||||
uint16_t len;
|
||||
uint8_t colorOrder;
|
||||
};
|
||||
|
||||
struct ColorOrderMap {
|
||||
void add(uint16_t start, uint16_t len, uint8_t colorOrder);
|
||||
|
||||
uint8_t count() const { return _count; }
|
||||
|
||||
void reset() {
|
||||
_count = 0;
|
||||
memset(_mappings, 0, sizeof(_mappings));
|
||||
}
|
||||
|
||||
const ColorOrderMapEntry* get(uint8_t n) const {
|
||||
if (n > _count) {
|
||||
return nullptr;
|
||||
}
|
||||
return &(_mappings[n]);
|
||||
}
|
||||
|
||||
uint8_t getPixelColorOrder(uint16_t pix, uint8_t defaultColorOrder) const;
|
||||
|
||||
private:
|
||||
uint8_t _count;
|
||||
ColorOrderMapEntry _mappings[WLED_MAX_COLOR_ORDER_MAPPINGS];
|
||||
};
|
||||
|
||||
|
||||
//parent class of BusDigital, BusPwm, and BusNetwork
|
||||
class Bus {
|
||||
public:
|
||||
Bus(uint8_t type, uint16_t start, uint8_t aw, uint16_t len = 1, bool reversed = false, bool refresh = false)
|
||||
: _type(type)
|
||||
, _bri(255)
|
||||
, _start(start)
|
||||
, _len(len)
|
||||
, _reversed(reversed)
|
||||
, _valid(false)
|
||||
, _needsRefresh(refresh)
|
||||
, _data(nullptr) // keep data access consistent across all types of buses
|
||||
{
|
||||
_autoWhiteMode = Bus::hasWhite(type) ? aw : RGBW_MODE_MANUAL_ONLY;
|
||||
};
|
||||
|
||||
virtual ~Bus() {} //throw the bus under the bus
|
||||
|
||||
virtual void show() = 0;
|
||||
virtual bool canShow() { return true; }
|
||||
virtual void setStatusPixel(uint32_t c) {}
|
||||
virtual void setPixelColor(uint16_t pix, uint32_t c) = 0;
|
||||
virtual uint32_t getPixelColor(uint16_t pix) { return 0; }
|
||||
virtual void setBrightness(uint8_t b) { _bri = b; };
|
||||
virtual uint8_t getPins(uint8_t* pinArray) { return 0; }
|
||||
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; }
|
||||
virtual uint16_t getFrequency() { return 0U; }
|
||||
virtual uint16_t getLEDCurrent() { return 0; }
|
||||
virtual uint16_t getUsedCurrent() { return 0; }
|
||||
virtual uint16_t getMaxCurrent() { return 0; }
|
||||
virtual uint8_t getNumberOfChannels() { return hasWhite(_type) + 3*hasRGB(_type) + hasCCT(_type); }
|
||||
static inline uint8_t getNumberOfChannels(uint8_t type) { return hasWhite(type) + 3*hasRGB(type) + hasCCT(type); }
|
||||
inline void setReversed(bool reversed) { _reversed = reversed; }
|
||||
inline uint16_t getStart() { return _start; }
|
||||
inline void setStart(uint16_t start) { _start = start; }
|
||||
inline uint8_t getType() { return _type; }
|
||||
inline bool isOk() { return _valid; }
|
||||
inline bool isReversed() { return _reversed; }
|
||||
inline bool isOffRefreshRequired() { return _needsRefresh; }
|
||||
bool containsPixel(uint16_t pix) { return pix >= _start && pix < _start+_len; }
|
||||
|
||||
virtual bool hasRGB(void) { return Bus::hasRGB(_type); }
|
||||
static bool hasRGB(uint8_t type) {
|
||||
if ((type >= TYPE_WS2812_1CH && type <= TYPE_WS2812_WWA) || type == TYPE_ANALOG_1CH || type == TYPE_ANALOG_2CH || type == TYPE_ONOFF) return false;
|
||||
return true;
|
||||
}
|
||||
virtual bool hasWhite(void) { return Bus::hasWhite(_type); }
|
||||
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
|
||||
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;
|
||||
}
|
||||
virtual bool hasCCT(void) { return Bus::hasCCT(_type); }
|
||||
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;
|
||||
return false;
|
||||
}
|
||||
static int16_t getCCT() { return _cct; }
|
||||
static void setCCT(int16_t cct) {
|
||||
_cct = cct;
|
||||
}
|
||||
static void setCCTBlend(uint8_t b) {
|
||||
if (b > 100) b = 100;
|
||||
_cctBlend = (b * 127) / 100;
|
||||
//compile-time limiter for hardware that can't power both white channels at max
|
||||
#ifdef WLED_MAX_CCT_BLEND
|
||||
if (_cctBlend > WLED_MAX_CCT_BLEND) _cctBlend = WLED_MAX_CCT_BLEND;
|
||||
#endif
|
||||
}
|
||||
static void calculateCCT(uint32_t c, uint8_t &ww, uint8_t &cw) {
|
||||
uint8_t cct = 0; //0 - full warm white, 255 - full cold white
|
||||
uint8_t w = byte(c >> 24);
|
||||
|
||||
if (_cct > -1) {
|
||||
if (_cct >= 1900) cct = (_cct - 1900) >> 5;
|
||||
else if (_cct < 256) cct = _cct;
|
||||
} else {
|
||||
cct = (approximateKelvinFromRGB(c) - 1900) >> 5;
|
||||
}
|
||||
|
||||
//0 - linear (CCT 127 = 50% warm, 50% cold), 127 - additive CCT blending (CCT 127 = 100% warm, 100% cold)
|
||||
if (cct < _cctBlend) ww = 255;
|
||||
else ww = ((255-cct) * 255) / (255 - _cctBlend);
|
||||
if ((255-cct) < _cctBlend) cw = 255;
|
||||
else cw = (cct * 255) / (255 - _cctBlend);
|
||||
|
||||
ww = (w * ww) / 255; //brightness scaling
|
||||
cw = (w * cw) / 255;
|
||||
}
|
||||
inline void setAutoWhiteMode(uint8_t m) { if (m < 5) _autoWhiteMode = m; }
|
||||
inline uint8_t getAutoWhiteMode() { return _autoWhiteMode; }
|
||||
inline static void setGlobalAWMode(uint8_t m) { if (m < 5) _gAWM = m; else _gAWM = AW_GLOBAL_DISABLED; }
|
||||
inline static uint8_t getGlobalAWMode() { return _gAWM; }
|
||||
|
||||
protected:
|
||||
uint8_t _type;
|
||||
uint8_t _bri;
|
||||
uint16_t _start;
|
||||
uint16_t _len;
|
||||
bool _reversed;
|
||||
bool _valid;
|
||||
bool _needsRefresh;
|
||||
uint8_t _autoWhiteMode;
|
||||
uint8_t *_data;
|
||||
// global Auto White Calculation override
|
||||
static uint8_t _gAWM;
|
||||
// _cct has the following menaings (see calculateCCT() & BusManager::setSegmentCCT()):
|
||||
// -1 means to extract approximate CCT value in K from RGB (in calcualteCCT())
|
||||
// [0,255] is the exact CCT value where 0 means warm and 255 cold
|
||||
// [1900,10060] only for color correction expressed in K (colorBalanceFromKelvin())
|
||||
static int16_t _cct;
|
||||
// _cctBlend determines WW/CW blending:
|
||||
// 0 - linear (CCT 127 => 50% warm, 50% cold)
|
||||
// 63 - semi additive/nonlinear (CCT 127 => 66% warm, 66% cold)
|
||||
// 127 - additive CCT blending (CCT 127 => 100% warm, 100% cold)
|
||||
static uint8_t _cctBlend;
|
||||
|
||||
uint32_t autoWhiteCalc(uint32_t c);
|
||||
uint8_t *allocData(size_t size = 1);
|
||||
void freeData() { if (_data != nullptr) free(_data); _data = nullptr; }
|
||||
};
|
||||
|
||||
|
||||
class BusDigital : public Bus {
|
||||
public:
|
||||
BusDigital(BusConfig &bc, uint8_t nr, const ColorOrderMap &com);
|
||||
~BusDigital() { cleanup(); }
|
||||
|
||||
void show() override;
|
||||
bool canShow() override;
|
||||
void setBrightness(uint8_t b) override;
|
||||
void setStatusPixel(uint32_t c) override;
|
||||
void setPixelColor(uint16_t pix, uint32_t c) override;
|
||||
void setColorOrder(uint8_t colorOrder) override;
|
||||
uint32_t getPixelColor(uint16_t pix) override;
|
||||
uint8_t getColorOrder() override { return _colorOrder; }
|
||||
uint8_t getPins(uint8_t* pinArray) override;
|
||||
uint8_t skippedLeds() override { return _skip; }
|
||||
uint16_t getFrequency() override { return _frequencykHz; }
|
||||
uint8_t estimateCurrentAndLimitBri();
|
||||
uint16_t getLEDCurrent() override { return _milliAmpsPerLed; }
|
||||
uint16_t getUsedCurrent() override { return _milliAmpsTotal; }
|
||||
uint16_t getMaxCurrent() override { return _milliAmpsMax; }
|
||||
void reinit();
|
||||
void cleanup();
|
||||
|
||||
private:
|
||||
uint8_t _skip;
|
||||
uint8_t _colorOrder;
|
||||
uint8_t _pins[2];
|
||||
uint8_t _iType;
|
||||
uint16_t _frequencykHz;
|
||||
uint8_t _milliAmpsPerLed;
|
||||
uint16_t _milliAmpsMax;
|
||||
void * _busPtr;
|
||||
const ColorOrderMap &_colorOrderMap;
|
||||
|
||||
static uint16_t _milliAmpsTotal; // is overwitten/recalculated on each show()
|
||||
|
||||
inline uint32_t restoreColorLossy(uint32_t c, uint8_t restoreBri) {
|
||||
if (restoreBri < 255) {
|
||||
uint8_t* chan = (uint8_t*) &c;
|
||||
for (uint_fast8_t i=0; i<4; i++) {
|
||||
uint_fast16_t val = chan[i];
|
||||
chan[i] = ((val << 8) + restoreBri) / (restoreBri + 1); //adding _bri slightly improves recovery / stops degradation on re-scale
|
||||
}
|
||||
}
|
||||
return c;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
class BusPwm : public Bus {
|
||||
public:
|
||||
BusPwm(BusConfig &bc);
|
||||
~BusPwm() { cleanup(); }
|
||||
|
||||
void setPixelColor(uint16_t pix, uint32_t c) override;
|
||||
uint32_t getPixelColor(uint16_t pix) override; //does no index check
|
||||
uint8_t getPins(uint8_t* pinArray) override;
|
||||
uint16_t getFrequency() override { return _frequency; }
|
||||
void show() override;
|
||||
void cleanup() { deallocatePins(); }
|
||||
|
||||
private:
|
||||
uint8_t _pins[5];
|
||||
uint8_t _pwmdata[5];
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
uint8_t _ledcStart;
|
||||
#endif
|
||||
uint8_t _depth;
|
||||
uint16_t _frequency;
|
||||
|
||||
void deallocatePins();
|
||||
};
|
||||
|
||||
|
||||
class BusOnOff : public Bus {
|
||||
public:
|
||||
BusOnOff(BusConfig &bc);
|
||||
~BusOnOff() { cleanup(); }
|
||||
|
||||
void setPixelColor(uint16_t pix, uint32_t c) override;
|
||||
uint32_t getPixelColor(uint16_t pix) override;
|
||||
uint8_t getPins(uint8_t* pinArray) override;
|
||||
void show() override;
|
||||
void cleanup() { pinManager.deallocatePin(_pin, PinOwner::BusOnOff); }
|
||||
|
||||
private:
|
||||
uint8_t _pin;
|
||||
uint8_t _onoffdata;
|
||||
};
|
||||
|
||||
|
||||
class BusNetwork : public Bus {
|
||||
public:
|
||||
BusNetwork(BusConfig &bc);
|
||||
~BusNetwork() { cleanup(); }
|
||||
|
||||
bool hasRGB() override { return true; }
|
||||
bool hasWhite() override { return _rgbw; }
|
||||
bool canShow() override { return !_broadcastLock; } // this should be a return value from UDP routine if it is still sending data out
|
||||
void setPixelColor(uint16_t pix, uint32_t c) override;
|
||||
uint32_t getPixelColor(uint16_t pix) override;
|
||||
uint8_t getPins(uint8_t* pinArray) override;
|
||||
void show() override;
|
||||
void cleanup();
|
||||
|
||||
private:
|
||||
IPAddress _client;
|
||||
uint8_t _UDPtype;
|
||||
uint8_t _UDPchannels;
|
||||
bool _rgbw;
|
||||
bool _broadcastLock;
|
||||
};
|
||||
|
||||
//fine tune power estimation constants for your setup
|
||||
//you can set it to 0 if the ESP is powered by USB and the LEDs by external
|
||||
#ifndef MA_FOR_ESP
|
||||
#ifdef ESP8266
|
||||
#define MA_FOR_ESP 80 //how much mA does the ESP use (Wemos D1 about 80mA)
|
||||
#else
|
||||
#define MA_FOR_ESP 120 //how much mA does the ESP use (ESP32 about 120mA)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
class BusManager {
|
||||
public:
|
||||
@@ -355,27 +379,28 @@ class BusManager {
|
||||
|
||||
//utility to get the approx. memory usage of a given BusConfig
|
||||
static uint32_t memUsage(BusConfig &bc);
|
||||
static uint16_t currentMilliamps(void) { return _milliAmpsUsed; }
|
||||
static uint16_t ablMilliampsMax(void) { return _milliAmpsMax; }
|
||||
static uint32_t memUsage(unsigned channels, unsigned count, unsigned buses = 1);
|
||||
static uint16_t currentMilliamps() { return _milliAmpsUsed + MA_FOR_ESP; }
|
||||
static uint16_t ablMilliampsMax() { return _milliAmpsMax; }
|
||||
|
||||
static int add(BusConfig &bc);
|
||||
static void useParallelOutput(void); // workaround for inaccessible PolyBus
|
||||
static void useParallelOutput(); // 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 on();
|
||||
static void off();
|
||||
|
||||
static void show();
|
||||
static bool canAllShow();
|
||||
static void setStatusPixel(uint32_t c);
|
||||
static void setPixelColor(uint16_t pix, uint32_t c);
|
||||
[[gnu::hot]] static void setPixelColor(uint16_t pix, uint32_t c);
|
||||
static void setBrightness(uint8_t b);
|
||||
// for setSegmentCCT(), cct can only be in [-1,255] range; allowWBCorrection will convert it to K
|
||||
// WARNING: setSegmentCCT() is a misleading name!!! much better would be setGlobalCCT() or just setCCT()
|
||||
static void setSegmentCCT(int16_t cct, bool allowWBCorrection = false);
|
||||
static void setMilliampsMax(uint16_t max) { _milliAmpsMax = max;}
|
||||
static inline void setMilliampsMax(uint16_t max) { _milliAmpsMax = max;}
|
||||
static uint32_t getPixelColor(uint16_t pix);
|
||||
static inline int16_t getSegmentCCT() { return Bus::getCCT(); }
|
||||
|
||||
@@ -383,10 +408,10 @@ class BusManager {
|
||||
|
||||
//semi-duplicate of strip.getLengthTotal() (though that just returns strip._length, calculated in finalizeInit())
|
||||
static uint16_t getTotalLength();
|
||||
static uint8_t getNumBusses() { return numBusses; }
|
||||
static inline uint8_t getNumBusses() { return numBusses; }
|
||||
static String getLEDTypesJSONString();
|
||||
|
||||
static void updateColorOrderMap(const ColorOrderMap &com) { memcpy(&colorOrderMap, &com, sizeof(ColorOrderMap)); }
|
||||
static const ColorOrderMap& getColorOrderMap() { return colorOrderMap; }
|
||||
static inline ColorOrderMap& getColorOrderMap() { return colorOrderMap; }
|
||||
|
||||
private:
|
||||
static uint8_t numBusses;
|
||||
@@ -397,11 +422,11 @@ class BusManager {
|
||||
static uint8_t _parallelOutputs;
|
||||
|
||||
#ifdef ESP32_DATA_IDLE_HIGH
|
||||
static void esp32RMTInvertIdle();
|
||||
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++;
|
||||
for (int i=0; i<numBusses; i++) if (busses[i]->isVirtual()) j++;
|
||||
return j;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -84,6 +84,11 @@
|
||||
#define I_8266_U1_TM1914_3 100
|
||||
#define I_8266_DM_TM1914_3 101
|
||||
#define I_8266_BB_TM1914_3 102
|
||||
//SM16825 (RGBCW)
|
||||
#define I_8266_U0_SM16825_5 103
|
||||
#define I_8266_U1_SM16825_5 104
|
||||
#define I_8266_DM_SM16825_5 105
|
||||
#define I_8266_BB_SM16825_5 106
|
||||
|
||||
/*** ESP32 Neopixel methods ***/
|
||||
//RGB
|
||||
@@ -130,7 +135,10 @@
|
||||
#define I_32_RN_TM1914_3 96
|
||||
#define I_32_I0_TM1914_3 97
|
||||
#define I_32_I1_TM1914_3 98
|
||||
|
||||
//SM16825 (RGBCW)
|
||||
#define I_32_RN_SM16825_5 107
|
||||
#define I_32_I0_SM16825_5 108
|
||||
#define I_32_I1_SM16825_5 109
|
||||
|
||||
//APA102
|
||||
#define I_HS_DOT_3 39 //hardware SPI
|
||||
@@ -213,6 +221,11 @@
|
||||
#define B_8266_U1_TM1914_3 NeoPixelBusLg<NeoRgbTm1914Feature, NeoEsp8266Uart1Tm1914Method, NeoGammaNullMethod>
|
||||
#define B_8266_DM_TM1914_3 NeoPixelBusLg<NeoRgbTm1914Feature, NeoEsp8266DmaTm1914Method, NeoGammaNullMethod>
|
||||
#define B_8266_BB_TM1914_3 NeoPixelBusLg<NeoRgbTm1914Feature, NeoEsp8266BitBangTm1914Method, NeoGammaNullMethod>
|
||||
//Sm16825 (RGBWC)
|
||||
#define B_8266_U0_SM16825_5 NeoPixelBusLg<NeoRgbwcSm16825eFeature, NeoEsp8266Uart0Ws2813Method, NeoGammaNullMethod>
|
||||
#define B_8266_U1_SM16825_5 NeoPixelBusLg<NeoRgbwcSm16825eFeature, NeoEsp8266Uart1Ws2813Method, NeoGammaNullMethod>
|
||||
#define B_8266_DM_SM16825_5 NeoPixelBusLg<NeoRgbwcSm16825eFeature, NeoEsp8266Dma800KbpsMethod, NeoGammaNullMethod>
|
||||
#define B_8266_BB_SM16825_5 NeoPixelBusLg<NeoRgbwcSm16825eFeature, NeoEsp8266BitBangWs2813Method, NeoGammaNullMethod>
|
||||
#endif
|
||||
|
||||
/*** ESP32 Neopixel methods ***/
|
||||
@@ -272,6 +285,11 @@
|
||||
#define B_32_I0_TM1914_3 NeoPixelBusLg<NeoGrbTm1914Feature, NeoEsp32I2s0Tm1914Method, NeoGammaNullMethod>
|
||||
#define B_32_I1_TM1914_3 NeoPixelBusLg<NeoGrbTm1914Feature, NeoEsp32I2s1Tm1914Method, NeoGammaNullMethod>
|
||||
#define B_32_I1_TM1914_3P NeoPixelBusLg<NeoGrbTm1914Feature, NeoEsp32I2s1X8Tm1914Method, NeoGammaNullMethod> // parallel I2S
|
||||
//Sm16825 (RGBWC)
|
||||
#define B_32_RN_SM16825_5 NeoPixelBusLg<NeoRgbcwSm16825eFeature, NeoEsp32RmtNWs2812xMethod, NeoGammaNullMethod>
|
||||
#define B_32_I0_SM16825_5 NeoPixelBusLg<NeoRgbcwSm16825eFeature, NeoEsp32I2s0Ws2812xMethod, NeoGammaNullMethod>
|
||||
#define B_32_I1_SM16825_5 NeoPixelBusLg<NeoRgbcwSm16825eFeature, NeoEsp32I2s1Ws2812xMethod, NeoGammaNullMethod>
|
||||
#define B_32_I1_SM16825_5P NeoPixelBusLg<NeoRgbcwSm16825eFeature, NeoEsp32I2s1X8Ws2812xMethod, NeoGammaNullMethod> // parallel I2S
|
||||
#endif
|
||||
|
||||
//APA102
|
||||
@@ -318,7 +336,7 @@ class PolyBus {
|
||||
|
||||
// initialize SPI bus speed for DotStar methods
|
||||
template <class T>
|
||||
static void beginDotStar(void* busPtr, int8_t sck, int8_t miso, int8_t mosi, int8_t ss, uint16_t clock_kHz = 0U) {
|
||||
static void beginDotStar(void* busPtr, int8_t sck, int8_t miso, int8_t mosi, int8_t ss, uint16_t clock_kHz /* 0 == use default */) {
|
||||
T dotStar_strip = static_cast<T>(busPtr);
|
||||
#ifdef ESP8266
|
||||
dotStar_strip->Begin();
|
||||
@@ -345,7 +363,7 @@ class PolyBus {
|
||||
tm1914_strip->SetPixelSettings(NeoTm1914Settings()); //NeoTm1914_Mode_DinFdinAutoSwitch, NeoTm1914_Mode_DinOnly, NeoTm1914_Mode_FdinOnly
|
||||
}
|
||||
|
||||
static void begin(void* busPtr, uint8_t busType, uint8_t* pins, uint16_t clock_kHz = 0U) {
|
||||
static void begin(void* busPtr, uint8_t busType, uint8_t* pins, uint16_t clock_kHz /* only used by DotStar */) {
|
||||
switch (busType) {
|
||||
case I_NONE: break;
|
||||
#ifdef ESP8266
|
||||
@@ -398,6 +416,10 @@ class PolyBus {
|
||||
case I_8266_U1_TM1914_3: beginTM1914<B_8266_U1_TM1914_3*>(busPtr); break;
|
||||
case I_8266_DM_TM1914_3: beginTM1914<B_8266_DM_TM1914_3*>(busPtr); break;
|
||||
case I_8266_BB_TM1914_3: beginTM1914<B_8266_BB_TM1914_3*>(busPtr); break;
|
||||
case I_8266_U0_SM16825_5: (static_cast<B_8266_U0_SM16825_5*>(busPtr))->Begin(); break;
|
||||
case I_8266_U1_SM16825_5: (static_cast<B_8266_U1_SM16825_5*>(busPtr))->Begin(); break;
|
||||
case I_8266_DM_SM16825_5: (static_cast<B_8266_DM_SM16825_5*>(busPtr))->Begin(); break;
|
||||
case I_8266_BB_SM16825_5: (static_cast<B_8266_BB_SM16825_5*>(busPtr))->Begin(); break;
|
||||
#endif
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
// RMT buses
|
||||
@@ -412,6 +434,7 @@ class PolyBus {
|
||||
case I_32_RN_APA106_3: (static_cast<B_32_RN_APA106_3*>(busPtr))->Begin(); break;
|
||||
case I_32_RN_2805_5: (static_cast<B_32_RN_2805_5*>(busPtr))->Begin(); break;
|
||||
case I_32_RN_TM1914_3: beginTM1914<B_32_RN_TM1914_3*>(busPtr); break;
|
||||
case I_32_RN_SM16825_5: (static_cast<B_32_RN_SM16825_5*>(busPtr))->Begin(); break;
|
||||
// I2S1 bus or parellel buses
|
||||
#ifndef WLED_NO_I2S1_PIXELBUS
|
||||
case I_32_I1_NEO_3: if (useParallelI2S) (static_cast<B_32_I1_NEO_3P*>(busPtr))->Begin(); else (static_cast<B_32_I1_NEO_3*>(busPtr))->Begin(); break;
|
||||
@@ -425,6 +448,7 @@ class PolyBus {
|
||||
case I_32_I1_APA106_3: if (useParallelI2S) (static_cast<B_32_I1_APA106_3P*>(busPtr))->Begin(); else (static_cast<B_32_I1_APA106_3*>(busPtr))->Begin(); break;
|
||||
case I_32_I1_2805_5: if (useParallelI2S) (static_cast<B_32_I1_2805_5P*>(busPtr))->Begin(); else (static_cast<B_32_I1_2805_5*>(busPtr))->Begin(); break;
|
||||
case I_32_I1_TM1914_3: if (useParallelI2S) beginTM1914<B_32_I1_TM1914_3P*>(busPtr); else beginTM1914<B_32_I1_TM1914_3*>(busPtr); break;
|
||||
case I_32_I1_SM16825_5: if (useParallelI2S) (static_cast<B_32_I1_SM16825_5P*>(busPtr))->Begin(); else (static_cast<B_32_I1_SM16825_5*>(busPtr))->Begin(); break;
|
||||
#endif
|
||||
// I2S0 bus
|
||||
#ifndef WLED_NO_I2S0_PIXELBUS
|
||||
@@ -439,6 +463,7 @@ class PolyBus {
|
||||
case I_32_I0_APA106_3: (static_cast<B_32_I0_APA106_3*>(busPtr))->Begin(); break;
|
||||
case I_32_I0_2805_5: (static_cast<B_32_I0_2805_5*>(busPtr))->Begin(); break;
|
||||
case I_32_I0_TM1914_3: beginTM1914<B_32_I0_TM1914_3*>(busPtr); break;
|
||||
case I_32_I0_SM16825_5: (static_cast<B_32_I0_SM16825_5*>(busPtr))->Begin(); break;
|
||||
#endif
|
||||
// ESP32 can (and should, to avoid inadvertantly driving the chip select signal) specify the pins used for SPI, but only in begin()
|
||||
case I_HS_DOT_3: beginDotStar<B_HS_DOT_3*>(busPtr, pins[1], -1, pins[0], -1, clock_kHz); break;
|
||||
@@ -455,7 +480,7 @@ class PolyBus {
|
||||
}
|
||||
}
|
||||
|
||||
static void* create(uint8_t busType, uint8_t* pins, uint16_t len, uint8_t channel, uint16_t clock_kHz = 0U) {
|
||||
static void* create(uint8_t busType, uint8_t* pins, uint16_t len, uint8_t channel) {
|
||||
#if defined(ARDUINO_ARCH_ESP32) && !(defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32S3) || defined(CONFIG_IDF_TARGET_ESP32C3))
|
||||
// NOTE: "channel" is only used on ESP32 (and its variants) for RMT channel allocation
|
||||
// since 0.15.0-b3 I2S1 is favoured for classic ESP32 and moved to position 0 (channel 0) so we need to subtract 1 for correct RMT allocation
|
||||
@@ -510,6 +535,10 @@ class PolyBus {
|
||||
case I_8266_U1_TM1914_3: busPtr = new B_8266_U1_TM1914_3(len, pins[0]); break;
|
||||
case I_8266_DM_TM1914_3: busPtr = new B_8266_DM_TM1914_3(len, pins[0]); break;
|
||||
case I_8266_BB_TM1914_3: busPtr = new B_8266_BB_TM1914_3(len, pins[0]); break;
|
||||
case I_8266_U0_SM16825_5: busPtr = new B_8266_U0_SM16825_5(len, pins[0]); break;
|
||||
case I_8266_U1_SM16825_5: busPtr = new B_8266_U1_SM16825_5(len, pins[0]); break;
|
||||
case I_8266_DM_SM16825_5: busPtr = new B_8266_DM_SM16825_5(len, pins[0]); break;
|
||||
case I_8266_BB_SM16825_5: busPtr = new B_8266_BB_SM16825_5(len, pins[0]); break;
|
||||
#endif
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
// RMT buses
|
||||
@@ -524,6 +553,7 @@ class PolyBus {
|
||||
case I_32_RN_FW6_5: busPtr = new B_32_RN_FW6_5(len, pins[0], (NeoBusChannel)channel); break;
|
||||
case I_32_RN_2805_5: busPtr = new B_32_RN_2805_5(len, pins[0], (NeoBusChannel)channel); break;
|
||||
case I_32_RN_TM1914_3: busPtr = new B_32_RN_TM1914_3(len, pins[0], (NeoBusChannel)channel); break;
|
||||
case I_32_RN_SM16825_5: busPtr = new B_32_RN_SM16825_5(len, pins[0], (NeoBusChannel)channel); break;
|
||||
// I2S1 bus or paralell buses
|
||||
#ifndef WLED_NO_I2S1_PIXELBUS
|
||||
case I_32_I1_NEO_3: if (useParallelI2S) busPtr = new B_32_I1_NEO_3P(len, pins[0]); else busPtr = new B_32_I1_NEO_3(len, pins[0]); break;
|
||||
@@ -537,6 +567,7 @@ class PolyBus {
|
||||
case I_32_I1_FW6_5: if (useParallelI2S) busPtr = new B_32_I1_FW6_5P(len, pins[0]); else busPtr = new B_32_I1_FW6_5(len, pins[0]); break;
|
||||
case I_32_I1_2805_5: if (useParallelI2S) busPtr = new B_32_I1_2805_5P(len, pins[0]); else busPtr = new B_32_I1_2805_5(len, pins[0]); break;
|
||||
case I_32_I1_TM1914_3: if (useParallelI2S) busPtr = new B_32_I1_TM1914_3P(len, pins[0]); else busPtr = new B_32_I1_TM1914_3(len, pins[0]); break;
|
||||
case I_32_I1_SM16825_5: if (useParallelI2S) busPtr = new B_32_I1_SM16825_5P(len, pins[0]); else busPtr = new B_32_I1_SM16825_5(len, pins[0]); break;
|
||||
#endif
|
||||
// I2S0 bus
|
||||
#ifndef WLED_NO_I2S0_PIXELBUS
|
||||
@@ -551,6 +582,7 @@ class PolyBus {
|
||||
case I_32_I0_FW6_5: busPtr = new B_32_I0_FW6_5(len, pins[0]); break;
|
||||
case I_32_I0_2805_5: busPtr = new B_32_I0_2805_5(len, pins[0]); break;
|
||||
case I_32_I0_TM1914_3: busPtr = new B_32_I0_TM1914_3(len, pins[0]); break;
|
||||
case I_32_I0_SM16825_5: busPtr = new B_32_I0_SM16825_5(len, pins[0]); break;
|
||||
#endif
|
||||
#endif
|
||||
// for 2-wire: pins[1] is clk, pins[0] is dat. begin expects (len, clk, dat)
|
||||
@@ -565,7 +597,7 @@ class PolyBus {
|
||||
case I_HS_P98_3: busPtr = new B_HS_P98_3(len, pins[1], pins[0]); break;
|
||||
case I_SS_P98_3: busPtr = new B_SS_P98_3(len, pins[1], pins[0]); break;
|
||||
}
|
||||
begin(busPtr, busType, pins, clock_kHz);
|
||||
|
||||
return busPtr;
|
||||
}
|
||||
|
||||
@@ -617,6 +649,10 @@ class PolyBus {
|
||||
case I_8266_U1_TM1914_3: (static_cast<B_8266_U1_TM1914_3*>(busPtr))->Show(consistent); break;
|
||||
case I_8266_DM_TM1914_3: (static_cast<B_8266_DM_TM1914_3*>(busPtr))->Show(consistent); break;
|
||||
case I_8266_BB_TM1914_3: (static_cast<B_8266_BB_TM1914_3*>(busPtr))->Show(consistent); break;
|
||||
case I_8266_U0_SM16825_5: (static_cast<B_8266_U0_SM16825_5*>(busPtr))->Show(consistent); break;
|
||||
case I_8266_U1_SM16825_5: (static_cast<B_8266_U1_SM16825_5*>(busPtr))->Show(consistent); break;
|
||||
case I_8266_DM_SM16825_5: (static_cast<B_8266_DM_SM16825_5*>(busPtr))->Show(consistent); break;
|
||||
case I_8266_BB_SM16825_5: (static_cast<B_8266_BB_SM16825_5*>(busPtr))->Show(consistent); break;
|
||||
#endif
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
// RMT buses
|
||||
@@ -631,6 +667,7 @@ class PolyBus {
|
||||
case I_32_RN_FW6_5: (static_cast<B_32_RN_FW6_5*>(busPtr))->Show(consistent); break;
|
||||
case I_32_RN_2805_5: (static_cast<B_32_RN_2805_5*>(busPtr))->Show(consistent); break;
|
||||
case I_32_RN_TM1914_3: (static_cast<B_32_RN_TM1914_3*>(busPtr))->Show(consistent); break;
|
||||
case I_32_RN_SM16825_5: (static_cast<B_32_RN_SM16825_5*>(busPtr))->Show(consistent); break;
|
||||
// I2S1 bus or paralell buses
|
||||
#ifndef WLED_NO_I2S1_PIXELBUS
|
||||
case I_32_I1_NEO_3: if (useParallelI2S) (static_cast<B_32_I1_NEO_3P*>(busPtr))->Show(consistent); else (static_cast<B_32_I1_NEO_3*>(busPtr))->Show(consistent); break;
|
||||
@@ -644,6 +681,7 @@ class PolyBus {
|
||||
case I_32_I1_FW6_5: if (useParallelI2S) (static_cast<B_32_I1_FW6_5P*>(busPtr))->Show(consistent); else (static_cast<B_32_I1_FW6_5*>(busPtr))->Show(consistent); break;
|
||||
case I_32_I1_2805_5: if (useParallelI2S) (static_cast<B_32_I1_2805_5P*>(busPtr))->Show(consistent); else (static_cast<B_32_I1_2805_5*>(busPtr))->Show(consistent); break;
|
||||
case I_32_I1_TM1914_3: if (useParallelI2S) (static_cast<B_32_I1_TM1914_3P*>(busPtr))->Show(consistent); else (static_cast<B_32_I1_TM1914_3*>(busPtr))->Show(consistent); break;
|
||||
case I_32_I1_SM16825_5: if (useParallelI2S) (static_cast<B_32_I1_SM16825_5P*>(busPtr))->Show(consistent); else (static_cast<B_32_I1_SM16825_5*>(busPtr))->Show(consistent); break;
|
||||
#endif
|
||||
// I2S0 bus
|
||||
#ifndef WLED_NO_I2S0_PIXELBUS
|
||||
@@ -658,6 +696,7 @@ class PolyBus {
|
||||
case I_32_I0_FW6_5: (static_cast<B_32_I0_FW6_5*>(busPtr))->Show(consistent); break;
|
||||
case I_32_I0_2805_5: (static_cast<B_32_I0_2805_5*>(busPtr))->Show(consistent); break;
|
||||
case I_32_I0_TM1914_3: (static_cast<B_32_I0_TM1914_3*>(busPtr))->Show(consistent); break;
|
||||
case I_32_I0_SM16825_5: (static_cast<B_32_I0_SM16825_5*>(busPtr))->Show(consistent); break;
|
||||
#endif
|
||||
#endif
|
||||
case I_HS_DOT_3: (static_cast<B_HS_DOT_3*>(busPtr))->Show(consistent); break;
|
||||
@@ -720,47 +759,54 @@ class PolyBus {
|
||||
case I_8266_U1_TM1914_3: return (static_cast<B_8266_U1_TM1914_3*>(busPtr))->CanShow(); break;
|
||||
case I_8266_DM_TM1914_3: return (static_cast<B_8266_DM_TM1914_3*>(busPtr))->CanShow(); break;
|
||||
case I_8266_BB_TM1914_3: return (static_cast<B_8266_BB_TM1914_3*>(busPtr))->CanShow(); break;
|
||||
case I_8266_U0_SM16825_5: return (static_cast<B_8266_U0_SM16825_5*>(busPtr))->CanShow(); break;
|
||||
case I_8266_U1_SM16825_5: return (static_cast<B_8266_U1_SM16825_5*>(busPtr))->CanShow(); break;
|
||||
case I_8266_DM_SM16825_5: return (static_cast<B_8266_DM_SM16825_5*>(busPtr))->CanShow(); break;
|
||||
case I_8266_BB_SM16825_5: return (static_cast<B_8266_BB_SM16825_5*>(busPtr))->CanShow(); break;
|
||||
#endif
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
// RMT buses
|
||||
case I_32_RN_NEO_3: (static_cast<B_32_RN_NEO_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_RN_NEO_4: (static_cast<B_32_RN_NEO_4*>(busPtr))->CanShow(); break;
|
||||
case I_32_RN_400_3: (static_cast<B_32_RN_400_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_RN_TM1_4: (static_cast<B_32_RN_TM1_4*>(busPtr))->CanShow(); break;
|
||||
case I_32_RN_TM2_3: (static_cast<B_32_RN_TM2_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_RN_UCS_3: (static_cast<B_32_RN_UCS_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_RN_UCS_4: (static_cast<B_32_RN_UCS_4*>(busPtr))->CanShow(); break;
|
||||
case I_32_RN_APA106_3: (static_cast<B_32_RN_APA106_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_RN_FW6_5: (static_cast<B_32_RN_FW6_5*>(busPtr))->CanShow(); break;
|
||||
case I_32_RN_2805_5: (static_cast<B_32_RN_2805_5*>(busPtr))->CanShow(); break;
|
||||
case I_32_RN_TM1914_3: (static_cast<B_32_RN_TM1914_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_RN_NEO_3: return (static_cast<B_32_RN_NEO_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_RN_NEO_4: return (static_cast<B_32_RN_NEO_4*>(busPtr))->CanShow(); break;
|
||||
case I_32_RN_400_3: return (static_cast<B_32_RN_400_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_RN_TM1_4: return (static_cast<B_32_RN_TM1_4*>(busPtr))->CanShow(); break;
|
||||
case I_32_RN_TM2_3: return (static_cast<B_32_RN_TM2_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_RN_UCS_3: return (static_cast<B_32_RN_UCS_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_RN_UCS_4: return (static_cast<B_32_RN_UCS_4*>(busPtr))->CanShow(); break;
|
||||
case I_32_RN_APA106_3: return (static_cast<B_32_RN_APA106_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_RN_FW6_5: return (static_cast<B_32_RN_FW6_5*>(busPtr))->CanShow(); break;
|
||||
case I_32_RN_2805_5: return (static_cast<B_32_RN_2805_5*>(busPtr))->CanShow(); break;
|
||||
case I_32_RN_TM1914_3: return (static_cast<B_32_RN_TM1914_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_RN_SM16825_5: return (static_cast<B_32_RN_SM16825_5*>(busPtr))->CanShow(); break;
|
||||
// I2S1 bus or paralell buses
|
||||
#ifndef WLED_NO_I2S1_PIXELBUS
|
||||
case I_32_I1_NEO_3: if (useParallelI2S) (static_cast<B_32_I1_NEO_3P*>(busPtr))->CanShow(); else (static_cast<B_32_I1_NEO_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I1_NEO_4: if (useParallelI2S) (static_cast<B_32_I1_NEO_4P*>(busPtr))->CanShow(); else (static_cast<B_32_I1_NEO_4*>(busPtr))->CanShow(); break;
|
||||
case I_32_I1_400_3: if (useParallelI2S) (static_cast<B_32_I1_400_3P*>(busPtr))->CanShow(); else (static_cast<B_32_I1_400_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I1_TM1_4: if (useParallelI2S) (static_cast<B_32_I1_TM1_4P*>(busPtr))->CanShow(); else (static_cast<B_32_I1_TM1_4*>(busPtr))->CanShow(); break;
|
||||
case I_32_I1_TM2_3: if (useParallelI2S) (static_cast<B_32_I1_TM2_3P*>(busPtr))->CanShow(); else (static_cast<B_32_I1_TM2_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I1_UCS_3: if (useParallelI2S) (static_cast<B_32_I1_UCS_3P*>(busPtr))->CanShow(); else (static_cast<B_32_I1_UCS_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I1_UCS_4: if (useParallelI2S) (static_cast<B_32_I1_UCS_4P*>(busPtr))->CanShow(); else (static_cast<B_32_I1_UCS_4*>(busPtr))->CanShow(); break;
|
||||
case I_32_I1_APA106_3: if (useParallelI2S) (static_cast<B_32_I1_APA106_3P*>(busPtr))->CanShow(); else (static_cast<B_32_I1_APA106_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I1_FW6_5: if (useParallelI2S) (static_cast<B_32_I1_FW6_5P*>(busPtr))->CanShow(); else (static_cast<B_32_I1_FW6_5*>(busPtr))->CanShow(); break;
|
||||
case I_32_I1_2805_5: if (useParallelI2S) (static_cast<B_32_I1_2805_5P*>(busPtr))->CanShow(); else (static_cast<B_32_I1_2805_5*>(busPtr))->CanShow(); break;
|
||||
case I_32_I1_TM1914_3: if (useParallelI2S) (static_cast<B_32_I1_TM1914_3P*>(busPtr))->CanShow(); else (static_cast<B_32_I1_TM1914_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I1_NEO_3: if (useParallelI2S) return (static_cast<B_32_I1_NEO_3P*>(busPtr))->CanShow(); else return (static_cast<B_32_I1_NEO_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I1_NEO_4: if (useParallelI2S) return (static_cast<B_32_I1_NEO_4P*>(busPtr))->CanShow(); else return (static_cast<B_32_I1_NEO_4*>(busPtr))->CanShow(); break;
|
||||
case I_32_I1_400_3: if (useParallelI2S) return (static_cast<B_32_I1_400_3P*>(busPtr))->CanShow(); else return (static_cast<B_32_I1_400_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I1_TM1_4: if (useParallelI2S) return (static_cast<B_32_I1_TM1_4P*>(busPtr))->CanShow(); else return (static_cast<B_32_I1_TM1_4*>(busPtr))->CanShow(); break;
|
||||
case I_32_I1_TM2_3: if (useParallelI2S) return (static_cast<B_32_I1_TM2_3P*>(busPtr))->CanShow(); else return (static_cast<B_32_I1_TM2_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I1_UCS_3: if (useParallelI2S) return (static_cast<B_32_I1_UCS_3P*>(busPtr))->CanShow(); else return (static_cast<B_32_I1_UCS_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I1_UCS_4: if (useParallelI2S) return (static_cast<B_32_I1_UCS_4P*>(busPtr))->CanShow(); else return (static_cast<B_32_I1_UCS_4*>(busPtr))->CanShow(); break;
|
||||
case I_32_I1_APA106_3: if (useParallelI2S) return (static_cast<B_32_I1_APA106_3P*>(busPtr))->CanShow(); else return (static_cast<B_32_I1_APA106_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I1_FW6_5: if (useParallelI2S) return (static_cast<B_32_I1_FW6_5P*>(busPtr))->CanShow(); else return (static_cast<B_32_I1_FW6_5*>(busPtr))->CanShow(); break;
|
||||
case I_32_I1_2805_5: if (useParallelI2S) return (static_cast<B_32_I1_2805_5P*>(busPtr))->CanShow(); else return (static_cast<B_32_I1_2805_5*>(busPtr))->CanShow(); break;
|
||||
case I_32_I1_TM1914_3: if (useParallelI2S) return (static_cast<B_32_I1_TM1914_3P*>(busPtr))->CanShow(); else return (static_cast<B_32_I1_TM1914_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I1_SM16825_5: if (useParallelI2S) return (static_cast<B_32_I1_SM16825_5P*>(busPtr))->CanShow(); else return (static_cast<B_32_I1_SM16825_5*>(busPtr))->CanShow(); break;
|
||||
#endif
|
||||
// I2S0 bus
|
||||
#ifndef WLED_NO_I2S0_PIXELBUS
|
||||
case I_32_I0_NEO_3: (static_cast<B_32_I0_NEO_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I0_NEO_4: (static_cast<B_32_I0_NEO_4*>(busPtr))->CanShow(); break;
|
||||
case I_32_I0_400_3: (static_cast<B_32_I0_400_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I0_TM1_4: (static_cast<B_32_I0_TM1_4*>(busPtr))->CanShow(); break;
|
||||
case I_32_I0_TM2_3: (static_cast<B_32_I0_TM2_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I0_UCS_3: (static_cast<B_32_I0_UCS_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I0_UCS_4: (static_cast<B_32_I0_UCS_4*>(busPtr))->CanShow(); break;
|
||||
case I_32_I0_APA106_3: (static_cast<B_32_I0_APA106_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I0_FW6_5: (static_cast<B_32_I0_FW6_5*>(busPtr))->CanShow(); break;
|
||||
case I_32_I0_2805_5: (static_cast<B_32_I0_2805_5*>(busPtr))->CanShow(); break;
|
||||
case I_32_I0_TM1914_3: (static_cast<B_32_I0_TM1914_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I0_NEO_3: return (static_cast<B_32_I0_NEO_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I0_NEO_4: return (static_cast<B_32_I0_NEO_4*>(busPtr))->CanShow(); break;
|
||||
case I_32_I0_400_3: return (static_cast<B_32_I0_400_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I0_TM1_4: return (static_cast<B_32_I0_TM1_4*>(busPtr))->CanShow(); break;
|
||||
case I_32_I0_TM2_3: return (static_cast<B_32_I0_TM2_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I0_UCS_3: return (static_cast<B_32_I0_UCS_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I0_UCS_4: return (static_cast<B_32_I0_UCS_4*>(busPtr))->CanShow(); break;
|
||||
case I_32_I0_APA106_3: return (static_cast<B_32_I0_APA106_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I0_FW6_5: return (static_cast<B_32_I0_FW6_5*>(busPtr))->CanShow(); break;
|
||||
case I_32_I0_2805_5: return (static_cast<B_32_I0_2805_5*>(busPtr))->CanShow(); break;
|
||||
case I_32_I0_TM1914_3: return (static_cast<B_32_I0_TM1914_3*>(busPtr))->CanShow(); break;
|
||||
case I_32_I0_SM16825_5: return (static_cast<B_32_I0_SM16825_5*>(busPtr))->CanShow(); break;
|
||||
#endif
|
||||
#endif
|
||||
case I_HS_DOT_3: return (static_cast<B_HS_DOT_3*>(busPtr))->CanShow(); break;
|
||||
@@ -800,6 +846,7 @@ class PolyBus {
|
||||
case 1: col.W = col.B; col.B = w; break; // swap W & B
|
||||
case 2: col.W = col.G; col.G = w; break; // swap W & G
|
||||
case 3: col.W = col.R; col.R = w; break; // swap W & R
|
||||
case 4: std::swap(cctWW, cctCW); break; // swap WW & CW
|
||||
}
|
||||
|
||||
switch (busType) {
|
||||
@@ -849,6 +896,10 @@ class PolyBus {
|
||||
case I_8266_U1_TM1914_3: (static_cast<B_8266_U1_TM1914_3*>(busPtr))->SetPixelColor(pix, RgbColor(col)); break;
|
||||
case I_8266_DM_TM1914_3: (static_cast<B_8266_DM_TM1914_3*>(busPtr))->SetPixelColor(pix, RgbColor(col)); break;
|
||||
case I_8266_BB_TM1914_3: (static_cast<B_8266_BB_TM1914_3*>(busPtr))->SetPixelColor(pix, RgbColor(col)); break;
|
||||
case I_8266_U0_SM16825_5: (static_cast<B_8266_U0_SM16825_5*>(busPtr))->SetPixelColor(pix, Rgbww80Color(col.R*257, col.G*257, col.B*257, cctWW*257, cctCW*257)); break;
|
||||
case I_8266_U1_SM16825_5: (static_cast<B_8266_U1_SM16825_5*>(busPtr))->SetPixelColor(pix, Rgbww80Color(col.R*257, col.G*257, col.B*257, cctWW*257, cctCW*257)); break;
|
||||
case I_8266_DM_SM16825_5: (static_cast<B_8266_DM_SM16825_5*>(busPtr))->SetPixelColor(pix, Rgbww80Color(col.R*257, col.G*257, col.B*257, cctWW*257, cctCW*257)); break;
|
||||
case I_8266_BB_SM16825_5: (static_cast<B_8266_BB_SM16825_5*>(busPtr))->SetPixelColor(pix, Rgbww80Color(col.R*257, col.G*257, col.B*257, cctWW*257, cctCW*257)); break;
|
||||
#endif
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
// RMT buses
|
||||
@@ -863,6 +914,7 @@ class PolyBus {
|
||||
case I_32_RN_FW6_5: (static_cast<B_32_RN_FW6_5*>(busPtr))->SetPixelColor(pix, RgbwwColor(col.R, col.G, col.B, cctWW, cctCW)); break;
|
||||
case I_32_RN_2805_5: (static_cast<B_32_RN_2805_5*>(busPtr))->SetPixelColor(pix, RgbwwColor(col.R, col.G, col.B, cctWW, cctCW)); break;
|
||||
case I_32_RN_TM1914_3: (static_cast<B_32_RN_TM1914_3*>(busPtr))->SetPixelColor(pix, RgbColor(col)); break;
|
||||
case I_32_RN_SM16825_5: (static_cast<B_32_RN_SM16825_5*>(busPtr))->SetPixelColor(pix, Rgbww80Color(col.R*257, col.G*257, col.B*257, cctWW*257, cctCW*257)); break;
|
||||
// I2S1 bus or paralell buses
|
||||
#ifndef WLED_NO_I2S1_PIXELBUS
|
||||
case I_32_I1_NEO_3: if (useParallelI2S) (static_cast<B_32_I1_NEO_3P*>(busPtr))->SetPixelColor(pix, RgbColor(col)); else (static_cast<B_32_I1_NEO_3*>(busPtr))->SetPixelColor(pix, RgbColor(col)); break;
|
||||
@@ -873,9 +925,10 @@ class PolyBus {
|
||||
case I_32_I1_UCS_3: if (useParallelI2S) (static_cast<B_32_I1_UCS_3P*>(busPtr))->SetPixelColor(pix, RgbColor(col)); else (static_cast<B_32_I1_UCS_3*>(busPtr))->SetPixelColor(pix, Rgb48Color(RgbColor(col))); break;
|
||||
case I_32_I1_UCS_4: if (useParallelI2S) (static_cast<B_32_I1_UCS_4P*>(busPtr))->SetPixelColor(pix, RgbColor(col)); else (static_cast<B_32_I1_UCS_4*>(busPtr))->SetPixelColor(pix, Rgbw64Color(col)); break;
|
||||
case I_32_I1_APA106_3: if (useParallelI2S) (static_cast<B_32_I1_APA106_3P*>(busPtr))->SetPixelColor(pix, RgbColor(col)); else (static_cast<B_32_I1_APA106_3*>(busPtr))->SetPixelColor(pix, RgbColor(col)); break;
|
||||
case I_32_I1_FW6_5: if (useParallelI2S) (static_cast<B_32_I1_FW6_5P*>(busPtr))->SetPixelColor(pix, RgbColor(col)); else (static_cast<B_32_I1_FW6_5*>(busPtr))->SetPixelColor(pix, RgbwwColor(col.R, col.G, col.B, cctWW, cctCW)); break;
|
||||
case I_32_I1_2805_5: if (useParallelI2S) (static_cast<B_32_I1_2805_5P*>(busPtr))->SetPixelColor(pix, RgbColor(col)); else (static_cast<B_32_I1_2805_5*>(busPtr))->SetPixelColor(pix, RgbwwColor(col.R, col.G, col.B, cctWW, cctCW)); break;
|
||||
case I_32_I1_FW6_5: if (useParallelI2S) (static_cast<B_32_I1_FW6_5P*>(busPtr))->SetPixelColor(pix, RgbwwColor(col.R, col.G, col.B, cctWW, cctCW)); else (static_cast<B_32_I1_FW6_5*>(busPtr))->SetPixelColor(pix, RgbwwColor(col.R, col.G, col.B, cctWW, cctCW)); break;
|
||||
case I_32_I1_2805_5: if (useParallelI2S) (static_cast<B_32_I1_2805_5P*>(busPtr))->SetPixelColor(pix, RgbwwColor(col.R, col.G, col.B, cctWW, cctCW)); else (static_cast<B_32_I1_2805_5*>(busPtr))->SetPixelColor(pix, RgbwwColor(col.R, col.G, col.B, cctWW, cctCW)); break;
|
||||
case I_32_I1_TM1914_3: if (useParallelI2S) (static_cast<B_32_I1_TM1914_3P*>(busPtr))->SetPixelColor(pix, RgbColor(col)); else (static_cast<B_32_I1_TM1914_3*>(busPtr))->SetPixelColor(pix, RgbColor(col)); break;
|
||||
case I_32_I1_SM16825_5: if (useParallelI2S) (static_cast<B_32_I1_SM16825_5P*>(busPtr))->SetPixelColor(pix, Rgbww80Color(col.R*257, col.G*257, col.B*257, cctWW*257, cctCW*257)); else (static_cast<B_32_I1_SM16825_5*>(busPtr))->SetPixelColor(pix, Rgbww80Color(col.R*257, col.G*257, col.B*257, cctWW*257, cctCW*257)); break;
|
||||
#endif
|
||||
// I2S0 bus
|
||||
#ifndef WLED_NO_I2S0_PIXELBUS
|
||||
@@ -890,6 +943,7 @@ class PolyBus {
|
||||
case I_32_I0_FW6_5: (static_cast<B_32_I0_FW6_5*>(busPtr))->SetPixelColor(pix, RgbwwColor(col.R, col.G, col.B, cctWW, cctCW)); break;
|
||||
case I_32_I0_2805_5: (static_cast<B_32_I0_2805_5*>(busPtr))->SetPixelColor(pix, RgbwwColor(col.R, col.G, col.B, cctWW, cctCW)); break;
|
||||
case I_32_I0_TM1914_3: (static_cast<B_32_I0_TM1914_3*>(busPtr))->SetPixelColor(pix, RgbColor(col)); break;
|
||||
case I_32_I0_SM16825_5: (static_cast<B_32_I0_SM16825_5*>(busPtr))->SetPixelColor(pix, Rgbww80Color(col.R*257, col.G*257, col.B*257, cctWW*257, cctCW*257)); break;
|
||||
#endif
|
||||
#endif
|
||||
case I_HS_DOT_3: (static_cast<B_HS_DOT_3*>(busPtr))->SetPixelColor(pix, RgbColor(col)); break;
|
||||
@@ -953,6 +1007,10 @@ class PolyBus {
|
||||
case I_8266_U1_TM1914_3: (static_cast<B_8266_U1_TM1914_3*>(busPtr))->SetLuminance(b); break;
|
||||
case I_8266_DM_TM1914_3: (static_cast<B_8266_DM_TM1914_3*>(busPtr))->SetLuminance(b); break;
|
||||
case I_8266_BB_TM1914_3: (static_cast<B_8266_BB_TM1914_3*>(busPtr))->SetLuminance(b); break;
|
||||
case I_8266_U0_SM16825_5: (static_cast<B_8266_U0_SM16825_5*>(busPtr))->SetLuminance(b); break;
|
||||
case I_8266_U1_SM16825_5: (static_cast<B_8266_U1_SM16825_5*>(busPtr))->SetLuminance(b); break;
|
||||
case I_8266_DM_SM16825_5: (static_cast<B_8266_DM_SM16825_5*>(busPtr))->SetLuminance(b); break;
|
||||
case I_8266_BB_SM16825_5: (static_cast<B_8266_BB_SM16825_5*>(busPtr))->SetLuminance(b); break;
|
||||
#endif
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
// RMT buses
|
||||
@@ -967,6 +1025,7 @@ class PolyBus {
|
||||
case I_32_RN_FW6_5: (static_cast<B_32_RN_FW6_5*>(busPtr))->SetLuminance(b); break;
|
||||
case I_32_RN_2805_5: (static_cast<B_32_RN_2805_5*>(busPtr))->SetLuminance(b); break;
|
||||
case I_32_RN_TM1914_3: (static_cast<B_32_RN_TM1914_3*>(busPtr))->SetLuminance(b); break;
|
||||
case I_32_RN_SM16825_5: (static_cast<B_32_RN_SM16825_5*>(busPtr))->SetLuminance(b); break;
|
||||
// I2S1 bus or paralell buses
|
||||
#ifndef WLED_NO_I2S1_PIXELBUS
|
||||
case I_32_I1_NEO_3: if (useParallelI2S) (static_cast<B_32_I1_NEO_3P*>(busPtr))->SetLuminance(b); else (static_cast<B_32_I1_NEO_3*>(busPtr))->SetLuminance(b); break;
|
||||
@@ -980,6 +1039,7 @@ class PolyBus {
|
||||
case I_32_I1_FW6_5: if (useParallelI2S) (static_cast<B_32_I1_FW6_5P*>(busPtr))->SetLuminance(b); else (static_cast<B_32_I1_FW6_5*>(busPtr))->SetLuminance(b); break;
|
||||
case I_32_I1_2805_5: if (useParallelI2S) (static_cast<B_32_I1_2805_5P*>(busPtr))->SetLuminance(b); else (static_cast<B_32_I1_2805_5*>(busPtr))->SetLuminance(b); break;
|
||||
case I_32_I1_TM1914_3: if (useParallelI2S) (static_cast<B_32_I1_TM1914_3P*>(busPtr))->SetLuminance(b); else (static_cast<B_32_I1_TM1914_3*>(busPtr))->SetLuminance(b); break;
|
||||
case I_32_I1_SM16825_5: if (useParallelI2S) (static_cast<B_32_I1_SM16825_5P*>(busPtr))->SetLuminance(b); else (static_cast<B_32_I1_SM16825_5*>(busPtr))->SetLuminance(b); break;
|
||||
#endif
|
||||
// I2S0 bus
|
||||
#ifndef WLED_NO_I2S0_PIXELBUS
|
||||
@@ -994,6 +1054,7 @@ class PolyBus {
|
||||
case I_32_I0_FW6_5: (static_cast<B_32_I0_FW6_5*>(busPtr))->SetLuminance(b); break;
|
||||
case I_32_I0_2805_5: (static_cast<B_32_I0_2805_5*>(busPtr))->SetLuminance(b); break;
|
||||
case I_32_I0_TM1914_3: (static_cast<B_32_I0_TM1914_3*>(busPtr))->SetLuminance(b); break;
|
||||
case I_32_I0_SM16825_5: (static_cast<B_32_I0_SM16825_5*>(busPtr))->SetLuminance(b); break;
|
||||
#endif
|
||||
#endif
|
||||
case I_HS_DOT_3: (static_cast<B_HS_DOT_3*>(busPtr))->SetLuminance(b); break;
|
||||
@@ -1058,6 +1119,10 @@ class PolyBus {
|
||||
case I_8266_U1_TM1914_3: col = (static_cast<B_8266_U1_TM1914_3*>(busPtr))->GetPixelColor(pix); break;
|
||||
case I_8266_DM_TM1914_3: col = (static_cast<B_8266_DM_TM1914_3*>(busPtr))->GetPixelColor(pix); break;
|
||||
case I_8266_BB_TM1914_3: col = (static_cast<B_8266_BB_TM1914_3*>(busPtr))->GetPixelColor(pix); break;
|
||||
case I_8266_U0_SM16825_5: { Rgbww80Color c = (static_cast<B_8266_U0_SM16825_5*>(busPtr))->GetPixelColor(pix); col = RGBW32(c.R,c.G,c.B,max(c.WW,c.CW)); } break; // will not return original W
|
||||
case I_8266_U1_SM16825_5: { Rgbww80Color c = (static_cast<B_8266_U1_SM16825_5*>(busPtr))->GetPixelColor(pix); col = RGBW32(c.R,c.G,c.B,max(c.WW,c.CW)); } break; // will not return original W
|
||||
case I_8266_DM_SM16825_5: { Rgbww80Color c = (static_cast<B_8266_DM_SM16825_5*>(busPtr))->GetPixelColor(pix); col = RGBW32(c.R,c.G,c.B,max(c.WW,c.CW)); } break; // will not return original W
|
||||
case I_8266_BB_SM16825_5: { Rgbww80Color c = (static_cast<B_8266_BB_SM16825_5*>(busPtr))->GetPixelColor(pix); col = RGBW32(c.R,c.G,c.B,max(c.WW,c.CW)); } break; // will not return original W
|
||||
#endif
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
// RMT buses
|
||||
@@ -1072,6 +1137,7 @@ class PolyBus {
|
||||
case I_32_RN_FW6_5: { RgbwwColor c = (static_cast<B_32_RN_FW6_5*>(busPtr))->GetPixelColor(pix); col = RGBW32(c.R,c.G,c.B,max(c.WW,c.CW)); } break; // will not return original W
|
||||
case I_32_RN_2805_5: { RgbwwColor c = (static_cast<B_32_RN_2805_5*>(busPtr))->GetPixelColor(pix); col = RGBW32(c.R,c.G,c.B,max(c.WW,c.CW)); } break; // will not return original W
|
||||
case I_32_RN_TM1914_3: col = (static_cast<B_32_RN_TM1914_3*>(busPtr))->GetPixelColor(pix); break;
|
||||
case I_32_RN_SM16825_5: { Rgbww80Color c = (static_cast<B_32_RN_SM16825_5*>(busPtr))->GetPixelColor(pix); col = RGBW32(c.R/257,c.G/257,c.B/257,max(c.WW,c.CW)/257); } break; // will not return original W
|
||||
// I2S1 bus or paralell buses
|
||||
#ifndef WLED_NO_I2S1_PIXELBUS
|
||||
case I_32_I1_NEO_3: col = (useParallelI2S) ? (static_cast<B_32_I1_NEO_3P*>(busPtr))->GetPixelColor(pix) : (static_cast<B_32_I1_NEO_3*>(busPtr))->GetPixelColor(pix); break;
|
||||
@@ -1079,12 +1145,13 @@ class PolyBus {
|
||||
case I_32_I1_400_3: col = (useParallelI2S) ? (static_cast<B_32_I1_400_3P*>(busPtr))->GetPixelColor(pix) : (static_cast<B_32_I1_400_3*>(busPtr))->GetPixelColor(pix); break;
|
||||
case I_32_I1_TM1_4: col = (useParallelI2S) ? (static_cast<B_32_I1_TM1_4P*>(busPtr))->GetPixelColor(pix) : (static_cast<B_32_I1_TM1_4*>(busPtr))->GetPixelColor(pix); break;
|
||||
case I_32_I1_TM2_3: col = (useParallelI2S) ? (static_cast<B_32_I1_TM2_3P*>(busPtr))->GetPixelColor(pix) : (static_cast<B_32_I1_TM2_3*>(busPtr))->GetPixelColor(pix); break;
|
||||
case I_32_I1_UCS_3: { Rgb48Color c = (useParallelI2S) ? (static_cast<B_32_I1_UCS_3P*>(busPtr))->GetPixelColor(pix) : (static_cast<B_32_I1_UCS_3*>(busPtr))->GetPixelColor(pix); col = RGBW32(c.R>>8,c.G>>8,c.B>>8,0); } break;
|
||||
case I_32_I1_UCS_4: { Rgbw64Color c = (useParallelI2S) ? (static_cast<B_32_I1_UCS_4P*>(busPtr))->GetPixelColor(pix) : (static_cast<B_32_I1_UCS_4*>(busPtr))->GetPixelColor(pix); col = RGBW32(c.R>>8,c.G>>8,c.B>>8,c.W>>8); } break;
|
||||
case I_32_I1_UCS_3: { Rgb48Color c = (useParallelI2S) ? (static_cast<B_32_I1_UCS_3P*>(busPtr))->GetPixelColor(pix) : (static_cast<B_32_I1_UCS_3*>(busPtr))->GetPixelColor(pix); col = RGBW32(c.R/257,c.G/257,c.B/257,0); } break;
|
||||
case I_32_I1_UCS_4: { Rgbw64Color c = (useParallelI2S) ? (static_cast<B_32_I1_UCS_4P*>(busPtr))->GetPixelColor(pix) : (static_cast<B_32_I1_UCS_4*>(busPtr))->GetPixelColor(pix); col = RGBW32(c.R/257,c.G/257,c.B/257,c.W/257); } break;
|
||||
case I_32_I1_APA106_3: col = (useParallelI2S) ? (static_cast<B_32_I1_APA106_3P*>(busPtr))->GetPixelColor(pix) : (static_cast<B_32_I1_APA106_3*>(busPtr))->GetPixelColor(pix); break;
|
||||
case I_32_I1_FW6_5: { RgbwwColor c = (useParallelI2S) ? (static_cast<B_32_I1_FW6_5P*>(busPtr))->GetPixelColor(pix) : (static_cast<B_32_I1_FW6_5*>(busPtr))->GetPixelColor(pix); col = RGBW32(c.R,c.G,c.B,max(c.WW,c.CW)); } break; // will not return original W
|
||||
case I_32_I1_2805_5: { RgbwwColor c = (useParallelI2S) ? (static_cast<B_32_I1_2805_5P*>(busPtr))->GetPixelColor(pix) : (static_cast<B_32_I1_2805_5*>(busPtr))->GetPixelColor(pix); col = RGBW32(c.R,c.G,c.B,max(c.WW,c.CW)); } break; // will not return original W
|
||||
case I_32_I1_TM1914_3: col = (useParallelI2S) ? (static_cast<B_32_I1_TM1914_3P*>(busPtr))->GetPixelColor(pix) : (static_cast<B_32_I1_TM1914_3*>(busPtr))->GetPixelColor(pix); break;
|
||||
case I_32_I1_SM16825_5: { Rgbww80Color c = (useParallelI2S) ? (static_cast<B_32_I1_SM16825_5P*>(busPtr))->GetPixelColor(pix) : (static_cast<B_32_I1_SM16825_5*>(busPtr))->GetPixelColor(pix); col = RGBW32(c.R/257,c.G/257,c.B/257,max(c.WW,c.CW)/257); } break; // will not return original W
|
||||
#endif
|
||||
// I2S0 bus
|
||||
#ifndef WLED_NO_I2S0_PIXELBUS
|
||||
@@ -1093,12 +1160,13 @@ class PolyBus {
|
||||
case I_32_I0_400_3: col = (static_cast<B_32_I0_400_3*>(busPtr))->GetPixelColor(pix); break;
|
||||
case I_32_I0_TM1_4: col = (static_cast<B_32_I0_TM1_4*>(busPtr))->GetPixelColor(pix); break;
|
||||
case I_32_I0_TM2_3: col = (static_cast<B_32_I0_TM2_3*>(busPtr))->GetPixelColor(pix); break;
|
||||
case I_32_I0_UCS_3: { Rgb48Color c = (static_cast<B_32_I0_UCS_3*>(busPtr))->GetPixelColor(pix); col = RGBW32(c.R>>8,c.G>>8,c.B>>8,0); } break;
|
||||
case I_32_I0_UCS_4: { Rgbw64Color c = (static_cast<B_32_I0_UCS_4*>(busPtr))->GetPixelColor(pix); col = RGBW32(c.R>>8,c.G>>8,c.B>>8,c.W>>8); } break;
|
||||
case I_32_I0_UCS_3: { Rgb48Color c = (static_cast<B_32_I0_UCS_3*>(busPtr))->GetPixelColor(pix); col = RGBW32(c.R/257,c.G/257,c.B/257,0); } break;
|
||||
case I_32_I0_UCS_4: { Rgbw64Color c = (static_cast<B_32_I0_UCS_4*>(busPtr))->GetPixelColor(pix); col = RGBW32(c.R/257,c.G/257,c.B/257,c.W/257); } break;
|
||||
case I_32_I0_APA106_3: col = (static_cast<B_32_I0_APA106_3*>(busPtr))->GetPixelColor(pix); break;
|
||||
case I_32_I0_FW6_5: { RgbwwColor c = (static_cast<B_32_I0_FW6_5*>(busPtr))->GetPixelColor(pix); col = RGBW32(c.R,c.G,c.B,max(c.WW,c.CW)); } break; // will not return original W
|
||||
case I_32_I0_2805_5: { RgbwwColor c = (static_cast<B_32_I0_2805_5*>(busPtr))->GetPixelColor(pix); col = RGBW32(c.R,c.G,c.B,max(c.WW,c.CW)); } break; // will not return original W
|
||||
case I_32_I0_TM1914_3: col = (static_cast<B_32_I0_TM1914_3*>(busPtr))->GetPixelColor(pix); break;
|
||||
case I_32_I0_SM16825_5: { Rgbww80Color c = (static_cast<B_32_I0_SM16825_5*>(busPtr))->GetPixelColor(pix); col = RGBW32(c.R/257,c.G/257,c.B/257,max(c.WW,c.CW)/257); } break; // will not return original W
|
||||
#endif
|
||||
#endif
|
||||
case I_HS_DOT_3: col = (static_cast<B_HS_DOT_3*>(busPtr))->GetPixelColor(pix); break;
|
||||
@@ -1181,6 +1249,10 @@ class PolyBus {
|
||||
case I_8266_U1_TM1914_3: delete (static_cast<B_8266_U1_TM1914_3*>(busPtr)); break;
|
||||
case I_8266_DM_TM1914_3: delete (static_cast<B_8266_DM_TM1914_3*>(busPtr)); break;
|
||||
case I_8266_BB_TM1914_3: delete (static_cast<B_8266_BB_TM1914_3*>(busPtr)); break;
|
||||
case I_8266_U0_SM16825_5: delete (static_cast<B_8266_U0_SM16825_5*>(busPtr)); break;
|
||||
case I_8266_U1_SM16825_5: delete (static_cast<B_8266_U1_SM16825_5*>(busPtr)); break;
|
||||
case I_8266_DM_SM16825_5: delete (static_cast<B_8266_DM_SM16825_5*>(busPtr)); break;
|
||||
case I_8266_BB_SM16825_5: delete (static_cast<B_8266_BB_SM16825_5*>(busPtr)); break;
|
||||
#endif
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
// RMT buses
|
||||
@@ -1195,6 +1267,7 @@ class PolyBus {
|
||||
case I_32_RN_FW6_5: delete (static_cast<B_32_RN_FW6_5*>(busPtr)); break;
|
||||
case I_32_RN_2805_5: delete (static_cast<B_32_RN_2805_5*>(busPtr)); break;
|
||||
case I_32_RN_TM1914_3: delete (static_cast<B_32_RN_TM1914_3*>(busPtr)); break;
|
||||
case I_32_RN_SM16825_5: delete (static_cast<B_32_RN_SM16825_5*>(busPtr)); break;
|
||||
// I2S1 bus or paralell buses
|
||||
#ifndef WLED_NO_I2S1_PIXELBUS
|
||||
case I_32_I1_NEO_3: if (useParallelI2S) delete (static_cast<B_32_I1_NEO_3P*>(busPtr)); else delete (static_cast<B_32_I1_NEO_3*>(busPtr)); break;
|
||||
@@ -1208,6 +1281,7 @@ class PolyBus {
|
||||
case I_32_I1_FW6_5: if (useParallelI2S) delete (static_cast<B_32_I1_FW6_5P*>(busPtr)); else delete (static_cast<B_32_I1_FW6_5*>(busPtr)); break;
|
||||
case I_32_I1_2805_5: if (useParallelI2S) delete (static_cast<B_32_I1_2805_5P*>(busPtr)); else delete (static_cast<B_32_I1_2805_5*>(busPtr)); break;
|
||||
case I_32_I1_TM1914_3: if (useParallelI2S) delete (static_cast<B_32_I1_TM1914_3P*>(busPtr)); else delete (static_cast<B_32_I1_TM1914_3*>(busPtr)); break;
|
||||
case I_32_I1_SM16825_5: if (useParallelI2S) delete (static_cast<B_32_I1_SM16825_5P*>(busPtr)); else delete (static_cast<B_32_I1_SM16825_5*>(busPtr)); break;
|
||||
#endif
|
||||
// I2S0 bus
|
||||
#ifndef WLED_NO_I2S0_PIXELBUS
|
||||
@@ -1222,6 +1296,7 @@ class PolyBus {
|
||||
case I_32_I0_FW6_5: delete (static_cast<B_32_I0_FW6_5*>(busPtr)); break;
|
||||
case I_32_I0_2805_5: delete (static_cast<B_32_I0_2805_5*>(busPtr)); break;
|
||||
case I_32_I0_TM1914_3: delete (static_cast<B_32_I0_TM1914_3*>(busPtr)); break;
|
||||
case I_32_I0_SM16825_5: delete (static_cast<B_32_I0_SM16825_5*>(busPtr)); break;
|
||||
#endif
|
||||
#endif
|
||||
case I_HS_DOT_3: delete (static_cast<B_HS_DOT_3*>(busPtr)); break;
|
||||
@@ -1239,8 +1314,8 @@ class PolyBus {
|
||||
|
||||
//gives back the internal type index (I_XX_XXX_X above) for the input
|
||||
static uint8_t getI(uint8_t busType, uint8_t* pins, uint8_t num = 0) {
|
||||
if (!IS_DIGITAL(busType)) return I_NONE;
|
||||
if (IS_2PIN(busType)) { //SPI LED chips
|
||||
if (!Bus::isDigital(busType)) return I_NONE;
|
||||
if (Bus::is2Pin(busType)) { //SPI LED chips
|
||||
bool isHSPI = false;
|
||||
#ifdef ESP8266
|
||||
if (pins[0] == P_8266_HS_MOSI && pins[1] == P_8266_HS_CLK) isHSPI = true;
|
||||
@@ -1290,6 +1365,8 @@ class PolyBus {
|
||||
return I_8266_U0_2805_5 + offset;
|
||||
case TYPE_TM1914:
|
||||
return I_8266_U0_TM1914_3 + offset;
|
||||
case TYPE_SM16825:
|
||||
return I_8266_U0_SM16825_5 + offset;
|
||||
}
|
||||
#else //ESP32
|
||||
uint8_t offset = 0; // 0 = RMT (num 1-8), 1 = I2S0 (used by Audioreactive), 2 = I2S1
|
||||
@@ -1343,6 +1420,8 @@ class PolyBus {
|
||||
return I_32_RN_2805_5 + offset;
|
||||
case TYPE_TM1914:
|
||||
return I_32_RN_TM1914_3 + offset;
|
||||
case TYPE_SM16825:
|
||||
return I_32_RN_SM16825_5 + offset;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -215,6 +215,7 @@ void handleAnalog(uint8_t b)
|
||||
briLast = bri;
|
||||
bri = 0;
|
||||
} else {
|
||||
if (bri == 0) strip.restartRuntime();
|
||||
bri = aRead;
|
||||
}
|
||||
} else if (macroDoublePress[b] == 249) {
|
||||
@@ -260,14 +261,14 @@ 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
|
||||
if (btnPin[b]<0 || buttonType[b] == BTN_TYPE_NONE) continue;
|
||||
#endif
|
||||
|
||||
if (usermods.handleButton(b)) continue; // did usermod handle buttons
|
||||
if (UsermodManager::handleButton(b)) continue; // did usermod handle buttons
|
||||
|
||||
if (buttonType[b] == BTN_TYPE_ANALOG || buttonType[b] == BTN_TYPE_ANALOG_INVERTED) { // button is not a button but a potentiometer
|
||||
if (now - lastAnalogRead > ANALOG_BTN_READ_CYCLE) {
|
||||
@@ -308,7 +309,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
|
||||
@@ -374,6 +375,7 @@ void handleIO()
|
||||
if (rlyPin>=0) {
|
||||
pinMode(rlyPin, rlyOpenDrain ? OUTPUT_OPEN_DRAIN : OUTPUT);
|
||||
digitalWrite(rlyPin, rlyMde);
|
||||
delay(50); // wait for relay to switch and power to stabilize
|
||||
}
|
||||
offMode = false;
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user