Compare commits
673 Commits
v0.15.0-b2
...
AR-MoonMod
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6678ad22d5 | ||
|
|
2cb8e32236 | ||
|
|
27e98147ef | ||
|
|
48958cc638 | ||
|
|
ae4de2782a | ||
|
|
6a1d3de75b | ||
|
|
3fc8c7d560 | ||
|
|
88738327fd | ||
|
|
0ad65f4748 | ||
|
|
9dad436f72 | ||
|
|
ebdc38fff2 | ||
|
|
97bbe6f305 | ||
|
|
2f0dbef1e5 | ||
|
|
1711286ef0 | ||
|
|
099d3f7b41 | ||
|
|
5f77478841 | ||
|
|
07cc3aa5c0 | ||
|
|
ff26f54bfd | ||
|
|
3323d2ed37 | ||
|
|
7b9b3f1ee2 | ||
|
|
cae98451e3 | ||
|
|
83da7569f5 | ||
|
|
26397ee8ad | ||
|
|
217d2aeb7f | ||
|
|
e57c701837 | ||
|
|
b4aa8376de | ||
|
|
d4976ac47a | ||
|
|
b8a96d9a77 | ||
|
|
f75d582eee | ||
|
|
18e0ec9a55 | ||
|
|
68b80cdadc | ||
|
|
3d3c475d1b | ||
|
|
6668e72351 | ||
|
|
b72695f01a | ||
|
|
65f98c1f30 | ||
|
|
c6fd4c51cf | ||
|
|
3c11c8441f | ||
|
|
3261c5b071 | ||
|
|
c8625c70dd | ||
|
|
396e9d0c39 | ||
|
|
2c58a87982 | ||
|
|
a705ae5278 | ||
|
|
a426e93011 | ||
|
|
1c220d25ca | ||
|
|
039858dca2 | ||
|
|
4758b5efe8 | ||
|
|
36e065ab4d | ||
|
|
076497e14d | ||
|
|
e8d9891d13 | ||
|
|
4902d7fb9e | ||
|
|
a873ca6a3e | ||
|
|
a86cb27cfe | ||
|
|
d620930f10 | ||
|
|
8db8ecfef3 | ||
|
|
a0f99393f5 | ||
|
|
ae8c3b02d0 | ||
|
|
99427c2ef7 | ||
|
|
334f16c0b6 | ||
|
|
7a80a772c1 | ||
|
|
8b1d712e1e | ||
|
|
a121f5b61b | ||
|
|
251062170e | ||
|
|
92e59af4d8 | ||
|
|
fa4c23b76e | ||
|
|
a0a46850f5 | ||
|
|
4cd0563a93 | ||
|
|
b83f0f461c | ||
|
|
3668ede0ff | ||
|
|
945584384a | ||
|
|
b1dd27b516 | ||
|
|
dcba1aad10 | ||
|
|
acc8b9cdbc | ||
|
|
6cbdd825eb | ||
|
|
cc55f6015d | ||
|
|
95718ab6ec | ||
|
|
feab27295d | ||
|
|
ca176c7549 | ||
|
|
f8a7a0d6e8 | ||
|
|
0a05611e1d | ||
|
|
1a8aaa3b26 | ||
|
|
cd1c13b4b1 | ||
|
|
d87c5035dd | ||
|
|
77967731d5 | ||
|
|
0b54034470 | ||
|
|
8ad2583785 | ||
|
|
dd533a9ab4 | ||
|
|
5b989adebc | ||
|
|
20f8d3c8a9 | ||
|
|
0c77dbb7ea | ||
|
|
2448e2ae3b | ||
|
|
d53d7aa2e2 | ||
|
|
0be1df7ee8 | ||
|
|
6aef0e145c | ||
|
|
32dc54ce72 | ||
|
|
548736f432 | ||
|
|
6790f8af08 | ||
|
|
89d587e7dd | ||
|
|
5c8b2ebf7a | ||
|
|
5ac8ba9bae | ||
|
|
49fb16e2c6 | ||
|
|
545bfa6ef9 | ||
|
|
c596b5a17d | ||
|
|
84dd26c1b7 | ||
|
|
a765903a41 | ||
|
|
25ab381916 | ||
|
|
4d3df5d98f | ||
|
|
6fe2024542 | ||
|
|
7f69a0bc5e | ||
|
|
5b829adedb | ||
|
|
4cd4c13b2d | ||
|
|
86be5df475 | ||
|
|
8c5e0cd4e9 | ||
|
|
a9b0b8adc8 | ||
|
|
ba01cb82f7 | ||
|
|
223b97b884 | ||
|
|
d437027f26 | ||
|
|
9a564ee204 | ||
|
|
5de86d3d91 | ||
|
|
536444f9d1 | ||
|
|
5c2bac4b9d | ||
|
|
ef1e24cec2 | ||
|
|
001e2ad287 | ||
|
|
0404ec9881 | ||
|
|
6ff5c88ebf | ||
|
|
1e761c31bd | ||
|
|
ab7b2d729e | ||
|
|
271a07a7d6 | ||
|
|
029293a086 | ||
|
|
cf1630a94a | ||
|
|
4634ace74e | ||
|
|
3733715184 | ||
|
|
bf37ac53a3 | ||
|
|
50934e6840 | ||
|
|
891ea48e11 | ||
|
|
70323b9477 | ||
|
|
451cd4c74a | ||
|
|
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 | ||
|
|
4fa8a3898a | ||
|
|
caa997fff1 | ||
|
|
bd68b977d5 | ||
|
|
98a6907976 | ||
|
|
e9d2182390 | ||
|
|
5e29f2c1b7 | ||
|
|
44e28f96e0 | ||
|
|
a0e81da8c5 | ||
|
|
85a7c3c60d | ||
|
|
01e07ca0bc | ||
|
|
1468ee5fde | ||
|
|
49f044ecde | ||
|
|
37f32ab197 | ||
|
|
a60231ba59 | ||
|
|
c8dafede6d | ||
|
|
210191b251 | ||
|
|
7deea9eb75 | ||
|
|
5e9a46d54d | ||
|
|
be64930ebb | ||
|
|
488974dd3e | ||
|
|
5975b9125f | ||
|
|
f301296f1e | ||
|
|
407477dc68 | ||
|
|
eb5ad232a0 | ||
|
|
1b0ce9a123 | ||
|
|
7b855c851d | ||
|
|
ca062140f3 | ||
|
|
a15c391e6c | ||
|
|
ba636b17a0 | ||
|
|
2a07eb84f6 | ||
|
|
949b9fb10e | ||
|
|
ae1b6af0d4 | ||
|
|
dd27504d30 | ||
|
|
c30a08cfc5 | ||
|
|
a4c49aa35e | ||
|
|
ba3a61f623 | ||
|
|
402fba734a | ||
|
|
262af0678f | ||
|
|
3765d558b6 | ||
|
|
4ed8ded502 | ||
|
|
ee380c5377 | ||
|
|
7fa25ca7ae | ||
|
|
d3c401ed4e | ||
|
|
0ae73296cf | ||
|
|
8e78fb4caa | ||
|
|
336da25463 | ||
|
|
ffbc8c5f70 | ||
|
|
10d8cfde85 | ||
|
|
9114867578 | ||
|
|
6f221852a2 | ||
|
|
c842994df5 | ||
|
|
202901b09f | ||
|
|
7c0fe1285a | ||
|
|
6dc2c680c5 | ||
|
|
9a4b56db6e | ||
|
|
8180f2c742 | ||
|
|
a76a895f1d | ||
|
|
b404458369 | ||
|
|
c44b9f8659 | ||
|
|
bef1ac2668 | ||
|
|
906f8fc2e7 | ||
|
|
c600c6da63 | ||
|
|
e789a18553 | ||
|
|
3f3c986932 | ||
|
|
3ccc5babc1 | ||
|
|
33cf82a982 | ||
|
|
bd7cd32f91 | ||
|
|
0a5400263b | ||
|
|
17d59d3337 | ||
|
|
9cb3531e2d | ||
|
|
b50e6e0d90 | ||
|
|
a88436c620 | ||
|
|
45cf90094a | ||
|
|
ae1df20893 | ||
|
|
71148740d4 | ||
|
|
4ef583c844 | ||
|
|
16f61ea96d | ||
|
|
32f9616b6e | ||
|
|
1346eb4f76 | ||
|
|
d4268ba070 | ||
|
|
696290527a | ||
|
|
686866c6f9 | ||
|
|
72455ccde1 | ||
|
|
88fb860568 | ||
|
|
ceed494cf7 | ||
|
|
ac8f919304 | ||
|
|
7f1ec4802d | ||
|
|
d5777b7bce | ||
|
|
e34f179a82 | ||
|
|
6a90b9a512 | ||
|
|
65a8dbfe41 | ||
|
|
1ff667b7ef | ||
|
|
0806c7fbdb | ||
|
|
5708d7a6b8 | ||
|
|
2264cc5d10 | ||
|
|
28cb3f9d0c | ||
|
|
f16ed4697f | ||
|
|
81e412fe5b | ||
|
|
f3137eb0a9 | ||
|
|
0e5bd4ed74 | ||
|
|
6a37f25c5d | ||
|
|
2afff05014 | ||
|
|
e3d9417b84 | ||
|
|
6a188033c6 | ||
|
|
df24fd7bf2 | ||
|
|
d45b4ad134 | ||
|
|
ec938f254c | ||
|
|
fa82e759bd | ||
|
|
daf0bcfac3 | ||
|
|
09428dcade | ||
|
|
49d51c5af8 | ||
|
|
ec7f69d559 | ||
|
|
a8c5bf2573 | ||
|
|
f12de61d7f | ||
|
|
71fcd6482d | ||
|
|
e59b38a5d2 | ||
|
|
b07658b460 | ||
|
|
5b8d9d1510 | ||
|
|
6169c458bf | ||
|
|
23400d0449 | ||
|
|
992d11be10 | ||
|
|
feac45fd0a | ||
|
|
934176818f | ||
|
|
c5435ec1fa | ||
|
|
c3f472fbcb | ||
|
|
eae5a74a11 | ||
|
|
5df1a223c2 | ||
|
|
81382a4bc0 | ||
|
|
750a429bd4 | ||
|
|
dbe78dff93 | ||
|
|
5869627b32 | ||
|
|
5bc5ef0ae8 | ||
|
|
2cfd2e1410 | ||
|
|
cce5e8f811 | ||
|
|
058e66c7fc | ||
|
|
8ae09c3d02 | ||
|
|
83699bc5c3 | ||
|
|
3a5eb8c5d2 | ||
|
|
fd00e5eaae | ||
|
|
20444ee7d5 | ||
|
|
eb06e575c2 | ||
|
|
b4315152e2 | ||
|
|
340a9f8b76 | ||
|
|
81cec6a25a | ||
|
|
c5b31e2f63 | ||
|
|
0642b17ab0 | ||
|
|
ac689a9a2e | ||
|
|
43cc4ec009 | ||
|
|
9cc333b2bd | ||
|
|
55d98ff935 | ||
|
|
dc90a4ed42 | ||
|
|
ef80abd885 | ||
|
|
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 | ||
|
|
b8b11880b0 | ||
|
|
0ff4016250 | ||
|
|
e753f3849e | ||
|
|
7b248c8fb2 | ||
|
|
f0e4dd90ee | ||
|
|
c540ec5417 | ||
|
|
3615ab535b | ||
|
|
b8d6ebe882 | ||
|
|
1f27872294 | ||
|
|
3815516022 | ||
|
|
a1dfdced31 | ||
|
|
ff39a8db3f | ||
|
|
9877e899e0 | ||
|
|
bc4a6138b1 | ||
|
|
f825cab54a | ||
|
|
57b01c2711 | ||
|
|
5f3e3d7796 | ||
|
|
d13b8c8421 | ||
|
|
0af3063127 | ||
|
|
17e1975dd8 | ||
|
|
166eeacab9 | ||
|
|
017169f1a1 | ||
|
|
ed0e73803f | ||
|
|
f4475b9d2a | ||
|
|
8a1df9afee | ||
|
|
9cfb56d9c6 | ||
|
|
25ade86994 | ||
|
|
c10ec2962b | ||
|
|
1bb06106fd | ||
|
|
bc18cdbeea | ||
|
|
67df5d6dcc | ||
|
|
68a7282b27 | ||
|
|
5732b66c5a | ||
|
|
f1cce8ef46 | ||
|
|
e47932c9aa | ||
|
|
3a70fb0e15 | ||
|
|
d5da84dcb2 | ||
|
|
1bd051d703 | ||
|
|
abb55f8e4b | ||
|
|
46f6a257d0 | ||
|
|
97e4eec5be | ||
|
|
69b99abb7d | ||
|
|
08f6d5a683 | ||
|
|
627bea30ed | ||
|
|
caf0a5bbe8 | ||
|
|
501f988b0f | ||
|
|
5f0c6fce74 | ||
|
|
78089107b7 | ||
|
|
f3b0906cea | ||
|
|
9f581c6181 | ||
|
|
31b232d3f3 | ||
|
|
77e6a6de61 | ||
|
|
85702a8142 | ||
|
|
0bcdc9641d | ||
|
|
bfd1bdfc64 | ||
|
|
c1fed6d469 | ||
|
|
79ffe021e4 | ||
|
|
a1c348b365 | ||
|
|
904b1f114b | ||
|
|
63f481d498 | ||
|
|
fc5c19788e | ||
|
|
56e0bde8ab | ||
|
|
db2cdca71b | ||
|
|
faa2fba6b9 | ||
|
|
f727ea2874 | ||
|
|
4a7ef07089 | ||
|
|
0df726cdab | ||
|
|
2f6f0d2f3e | ||
|
|
fae5938b0a | ||
|
|
2ec3639900 | ||
|
|
4513404629 | ||
|
|
13bfda56ef | ||
|
|
075c164407 | ||
|
|
dcb5049f97 | ||
|
|
d24cf14009 | ||
|
|
3d34802ab2 | ||
|
|
2aec21a6d0 | ||
|
|
19ccff9ff1 | ||
|
|
1dd9c6754c | ||
|
|
f9467ceaf1 | ||
|
|
f51da4f0c4 | ||
|
|
2eff389fff | ||
|
|
77ca2ec0e9 | ||
|
|
77e6ea8a6f | ||
|
|
e33299bbd7 | ||
|
|
74e273274c | ||
|
|
02bf5902f0 | ||
|
|
5f41de8938 | ||
|
|
f71d839009 | ||
|
|
3cb6b17316 | ||
|
|
c0cb677a4c | ||
|
|
a5a6a8eaee | ||
|
|
ecb861de56 | ||
|
|
1d20f18d3f | ||
|
|
68f6b3452e | ||
|
|
60075f6e8c | ||
|
|
1d7789f544 | ||
|
|
bd10a9aa26 | ||
|
|
1ceeed38bc | ||
|
|
2e1e917952 | ||
|
|
9e0b91ac17 | ||
|
|
ea83ec496b | ||
|
|
f26bb26ffa | ||
|
|
28348f919b | ||
|
|
c84d4c637d | ||
|
|
04706cfa9c | ||
|
|
3078bea7cc | ||
|
|
c91e0fc988 | ||
|
|
5183af4e8a | ||
|
|
1ff5cb0596 | ||
|
|
522e5e7957 | ||
|
|
9e468bd059 | ||
|
|
ecc9443677 | ||
|
|
6b8d8bf735 | ||
|
|
43d024fe42 | ||
|
|
c016dedea4 | ||
|
|
b9ca2cfe90 | ||
|
|
d3492b5b6c | ||
|
|
3682cd6a5e | ||
|
|
b209b1e481 | ||
|
|
4afed48f58 | ||
|
|
6a18ce078e | ||
|
|
bc5aadff7d | ||
|
|
de89b516dc | ||
|
|
4dbe9a7015 | ||
|
|
a320f16404 | ||
|
|
cec7241986 | ||
|
|
6de77293ad | ||
|
|
0ac53d8353 | ||
|
|
da79b93387 | ||
|
|
b88c300d04 | ||
|
|
88372cd516 | ||
|
|
b3206121cc | ||
|
|
5bccb5fc42 | ||
|
|
47e1cbdaff | ||
|
|
52020cbe26 | ||
|
|
d33651c25b | ||
|
|
18e9f9c304 | ||
|
|
2607c44fbb | ||
|
|
c8a7d44f55 | ||
|
|
a6e536189c | ||
|
|
3f9a6cae53 | ||
|
|
cd5494fdd2 | ||
|
|
5ab1b14d6b | ||
|
|
379f181362 | ||
|
|
dd19aa63d0 | ||
|
|
6df3b417a9 | ||
|
|
fa76431dd6 | ||
|
|
6504fb68b6 | ||
|
|
2ff49cf657 | ||
|
|
fa1aa1fe80 | ||
|
|
85b95a2940 | ||
|
|
5e38039c4d | ||
|
|
4df936a437 | ||
|
|
736a8b1b80 | ||
|
|
22f6128bc4 | ||
|
|
db475b6998 | ||
|
|
6daf7f6322 | ||
|
|
16086c0961 | ||
|
|
e88c81ad0d | ||
|
|
a2b9aed40d | ||
|
|
caa4fe1ec4 | ||
|
|
25fb878e54 | ||
|
|
a1d6ffadad | ||
|
|
3b89814b69 | ||
|
|
071e0be445 | ||
|
|
bed364d75e | ||
|
|
d2984e9e16 | ||
|
|
05a8c692f2 | ||
|
|
fd9570e782 | ||
|
|
35d26afcb4 | ||
|
|
2245ee6fce | ||
|
|
ff10130176 | ||
|
|
a13f1a9bee | ||
|
|
3cc60fa4d4 | ||
|
|
bd69c24231 | ||
|
|
c7d292a716 | ||
|
|
74bc159a52 | ||
|
|
9f99a1896d | ||
|
|
8110259d1c | ||
|
|
1048bf993a | ||
|
|
3eba0f4e0d | ||
|
|
d7e0b364d1 | ||
|
|
25dd43b949 | ||
|
|
69da2f4b23 | ||
|
|
d48bab02a1 | ||
|
|
886120fe9f | ||
|
|
bdd4d9f3ff | ||
|
|
6276c2f1f5 | ||
|
|
b3acc97d03 | ||
|
|
24bd1db4fc | ||
|
|
e83d3cb4a3 | ||
|
|
674481f0d1 | ||
|
|
5d271d21bc | ||
|
|
4e4493e627 | ||
|
|
1154905818 | ||
|
|
0d3ea848c2 | ||
|
|
8ffe1e65fd | ||
|
|
127ea7e351 | ||
|
|
34b16f1919 | ||
|
|
fa32faf759 | ||
|
|
6f3d7e76c9 | ||
|
|
57665e8964 | ||
|
|
5c502b1fe4 | ||
|
|
6d1410741d | ||
|
|
3e20724058 | ||
|
|
197f47befe | ||
|
|
d126611e87 | ||
|
|
1b75be5710 | ||
|
|
6272969983 | ||
|
|
084fc2fcd1 | ||
|
|
b2e68db380 | ||
|
|
459156fe57 | ||
|
|
7abfe68458 | ||
|
|
442d7a7226 | ||
|
|
80ebcb2c28 | ||
|
|
cd928bc586 | ||
|
|
d2b4d25317 | ||
|
|
a418cd2a2a | ||
|
|
94cdd88474 | ||
|
|
1bdf3876fc | ||
|
|
8358272b9a | ||
|
|
c3787af29d | ||
|
|
00f5471270 | ||
|
|
bff6697690 | ||
|
|
02405b4856 | ||
|
|
6d278994ec | ||
|
|
a9d6a15924 | ||
|
|
b8c61b5236 | ||
|
|
b77e1eb94b | ||
|
|
f78f8b6b12 | ||
|
|
f97b79bc16 | ||
|
|
42c8a77755 | ||
|
|
bb82bf762f | ||
|
|
d16f9efeec | ||
|
|
8ba5dfe447 | ||
|
|
3759071449 | ||
|
|
85d59945a0 | ||
|
|
4c8b490c89 | ||
|
|
8dd1745149 |
@@ -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",
|
||||
|
||||
20
.github/stale.yml
vendored
@@ -1,20 +0,0 @@
|
||||
# Number of days of inactivity before an issue becomes stale
|
||||
daysUntilStale: 120
|
||||
# Number of days of inactivity before a stale issue is closed
|
||||
daysUntilClose: 7
|
||||
# Issues with these labels will never be considered stale
|
||||
exemptLabels:
|
||||
- pinned
|
||||
- keep
|
||||
- enhancement
|
||||
- confirmed
|
||||
# Label to use when marking an issue as stale
|
||||
staleLabel: stale
|
||||
# Comment to post when marking an issue as stale. Set to `false` to disable
|
||||
markComment: >
|
||||
Hey! This issue has been open for quite some time without any new comments now.
|
||||
It will be closed automatically in a week if no further activity occurs.
|
||||
|
||||
Thank you for using WLED!
|
||||
# Comment to post when closing a stale issue. Set to `false` to disable
|
||||
closeComment: false
|
||||
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
@@ -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
|
||||
|
||||
30
.github/workflows/stale.yml
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
name: 'Close stale issues and PRs'
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 12 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
stale:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/stale@v9
|
||||
with:
|
||||
days-before-stale: 120
|
||||
days-before-close: 7
|
||||
stale-issue-label: 'stale'
|
||||
stale-pr-label: 'stale'
|
||||
exempt-issue-labels: 'pinned,keep,enhancement,confirmed'
|
||||
exempt-pr-labels: 'pinned,keep,enhancement,confirmed'
|
||||
exempt-all-milestones: true
|
||||
operations-per-run: 1000
|
||||
stale-issue-message: >
|
||||
Hey! This issue has been open for quite some time without any new comments now.
|
||||
It will be closed automatically in a week if no further activity occurs.
|
||||
|
||||
Thank you for using WLED! ✨
|
||||
stale-pr-message: >
|
||||
Hey! This pull request has been open for quite some time without any new comments now.
|
||||
It will be closed automatically in a week if no further activity occurs.
|
||||
|
||||
Thank you for contributing to WLED! ❤️
|
||||
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
|
||||
|
||||
2
.gitignore
vendored
@@ -21,4 +21,4 @@ wled-update.sh
|
||||
/wled00/my_config.h
|
||||
/wled00/Release
|
||||
/wled00/wled00.ino.cpp
|
||||
/wled00/html_*.h
|
||||
/wled00/html_*.h
|
||||
|
||||
140
CHANGELOG.md
@@ -1,5 +1,140 @@
|
||||
## WLED changelog
|
||||
|
||||
#### 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 allows available outputs)
|
||||
- Add ETH support for LILYGO-POE-Pro (#4030 by @rorosaurus)
|
||||
- Update usermod_sn_photoresistor (#4017 by @xkvmoto)
|
||||
- Several internal fixes and optimisations
|
||||
- move LED_BUILTIN handling to BusManager class
|
||||
- reduce max panels (web server limitation)
|
||||
- edit WiFi TX power (ESP32)
|
||||
- keep current ledmap ID in UI
|
||||
- limit outputs in UI based on length
|
||||
- wifi.ap addition to JSON Info (JSON API)
|
||||
- relay pin init bugfix
|
||||
- file editor button in UI
|
||||
- ESP8266: update was restarting device on some occasions
|
||||
- a bit of throttling in UI (for ESP8266)
|
||||
|
||||
#### Build 2406120
|
||||
- Update NeoPixelBus to v2.8.0
|
||||
- Increased LED outputs one ESP32 using parallel I2S (up to 17)
|
||||
- use single/mono I2S + 4x RMT for 5 outputs or less
|
||||
- use parallel x8 I2S + 8x RMT for >5 outputs (limit of 300 LEDs per output)
|
||||
- Fixed code of Smartnest and updated documentation (#4001 by @DevilPro1)
|
||||
- ESP32-S3 WiFi fix (#4010 by @cstruck)
|
||||
- TetrisAI usermod fix (#3897 by @muebau)
|
||||
- ESP-NOW usermod hook
|
||||
- Update wled.h regarding OTA Password (#3993 by @gsieben)
|
||||
- Usermod BME68X Sensor Implementation (#3994 by @gsieben)
|
||||
- Add a usermod for AHT10, AHT15 and AHT20 temperature/humidity sensors (#3977 by @LordMike)
|
||||
- Update Battery usermod documentation (#3968 by @adamsthws)
|
||||
- Add INA226 usermod for reading current and power over i2c (#3986 by @LordMike)
|
||||
- Bugfixes: #3991
|
||||
- Several internal fixes and optimisations (WARNING: some effects may be broken that rely on overflow/narrow width)
|
||||
- replace uint8_t and uint16_t with unsigned
|
||||
- replace in8_t and int16_t with int
|
||||
- reduces code by 1kB
|
||||
|
||||
#### Build 2405180
|
||||
- WLED 0.14.4 release
|
||||
- Fix for #3978
|
||||
- Official 0.15.0-b3 release
|
||||
- Merge 0.14.3 fixes into 0_15
|
||||
- Added Pinwheel Expand 1D->2D effect mapping mode (#3961 by @Brandon502)
|
||||
- Add changeable i2c address to BME280 usermod (#3966 by @LordMike)
|
||||
- Effect: Firenoise - add palette selection
|
||||
- Experimental parallel I2S support for ESP32 (compile time option)
|
||||
- increased outputs to 17
|
||||
- increased max possible color order overrides
|
||||
- use WLED_USE_PARALLEL_I2S during compile
|
||||
WARNING: Do not set up more than 256 LEDs per output when using parallel I2S with NeoPixelBus less than 2.9.0
|
||||
- Update Usermod: Battery (#3964 by @adamsthws)
|
||||
- Update Usermod: BME280 (#3965 by @LordMike)
|
||||
- TM1914 chip support (#3913)
|
||||
- Ignore brightness in Peek
|
||||
- Antialiased line & circle drawing functions
|
||||
- Enabled some audioreactive effects for single pixel strips/segments (#3942 by @gaaat98)
|
||||
- Usermod Battery: Added Support for different battery types, Optimized file structure (#3003 by @itCarl)
|
||||
- Skip playlist entry API (#3946 by @freakintoddles2)
|
||||
- various optimisations and bugfixes (#3987, #3978)
|
||||
|
||||
#### Build 2405030
|
||||
- Using brightness in analog clock overlay (#3944 by @paspiz85)
|
||||
- Add Webpage shortcuts (#3945 by @w00000dy)
|
||||
- ArtNet Poll reply (#3892 by @askask)
|
||||
- Improved brightness change via long button presses (#3933 by @gaaat98)
|
||||
- Relay open drain output (#3920 by @Suxsem)
|
||||
- NEW JSON API: release info (update page, `info.release`)
|
||||
- update esp32 platform to arduino-esp32 v2.0.9 (#3902)
|
||||
- various optimisations and bugfixes (#3952, #3922, #3878, #3926, #3919, #3904 @DedeHai)
|
||||
|
||||
#### Build 2404120
|
||||
- v0.15.0-b3
|
||||
- fix for #3896 & WS2815 current saving
|
||||
- conditional compile for AA setPixelColor()
|
||||
|
||||
#### Build 2404100
|
||||
- Internals: #3859, #3862, #3873, #3875
|
||||
- Prefer I2S1 over RMT on ESP32
|
||||
@@ -17,6 +152,11 @@
|
||||
- Fix for #3889
|
||||
- BREAKING: Effect: modified KITT (Scanner) (#3763)
|
||||
|
||||
#### Build 2404040
|
||||
- WLED 0.14.3 release
|
||||
- Fix for transition 0 (#3854, #3832, #3720)
|
||||
- Fix for #3855 via #3873 (by @willmmiles)
|
||||
|
||||
#### Build 2403280
|
||||
- Individual color channel control for JSON API (fixes #3860)
|
||||
- "col":[int|string|object|array, int|string|object|array, int|string|object|array]
|
||||
|
||||
@@ -14,7 +14,21 @@ A good description helps us to review and understand your proposed changes. For
|
||||
|
||||
### Target branch for pull requests
|
||||
|
||||
Please make all PRs against the `0_15` branch.
|
||||
Please make all PRs against the `main` 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
|
||||
|
||||
@@ -28,7 +42,7 @@ You are all set if you have enabled `Editor: Detect Indentation` in VS Code.
|
||||
|
||||
#### Blocks
|
||||
|
||||
Whether the opening bracket of e.g. an `if` block is in the same line as the condition or in a separate line is up to your discretion. If there is only one statement, leaving out block braches is acceptable.
|
||||
Whether the opening bracket of e.g. an `if` block is in the same line as the condition or in a separate line is up to your discretion. If there is only one statement, leaving out block brackets is acceptable.
|
||||
|
||||
Good:
|
||||
```cpp
|
||||
@@ -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,12 +63,9 @@ 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 paranthesis and variables.
|
||||
Within the condition, no space should be between the parenthesis and variables.
|
||||
Spaces between variables and operators are up to the authors discretion.
|
||||
There should be no space between function names and their argument parenthesis.
|
||||
|
||||
@@ -89,4 +105,4 @@ Good:
|
||||
|
||||
There is no hard character limit for a comment within a line,
|
||||
though as a rule of thumb consider wrapping after 120 characters.
|
||||
Inline comments are OK if they describe that line only and are not exceedingly wide.
|
||||
Inline comments are OK if they describe that line only and are not exceedingly wide.
|
||||
|
||||
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
@@ -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
@@ -1,18 +1,21 @@
|
||||
{
|
||||
"name": "wled",
|
||||
"version": "0.15.0-b2",
|
||||
"version": "0.16.0-dev",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "wled",
|
||||
"version": "0.15.0-b2",
|
||||
"version": "0.16.0-dev",
|
||||
"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-b2",
|
||||
"version": "0.16.0-alpha",
|
||||
"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,9 +1,24 @@
|
||||
# Little convenience script to get an object dump
|
||||
# You may add "-S" to the objdump commandline (i.e. replace "-D -C " with "-d -S -C ")
|
||||
# to get source code intermixed with disassembly (SLOW !)
|
||||
|
||||
Import('env')
|
||||
|
||||
def obj_dump_after_elf(source, target, env):
|
||||
platform = env.PioPlatform()
|
||||
board = env.BoardConfig()
|
||||
mcu = board.get("build.mcu", "esp32")
|
||||
|
||||
print("Create firmware.asm")
|
||||
env.Execute("xtensa-lx106-elf-objdump "+ "-D " + str(target[0]) + " > "+ "${PROGNAME}.asm")
|
||||
|
||||
if mcu == "esp8266":
|
||||
env.Execute("xtensa-lx106-elf-objdump "+ "-D -C " + str(target[0]) + " > "+ "$BUILD_DIR/${PROGNAME}.asm")
|
||||
if mcu == "esp32":
|
||||
env.Execute("xtensa-esp32-elf-objdump "+ "-D -C " + str(target[0]) + " > "+ "$BUILD_DIR/${PROGNAME}.asm")
|
||||
if mcu == "esp32s2":
|
||||
env.Execute("xtensa-esp32s2-elf-objdump "+ "-D -C " + str(target[0]) + " > "+ "$BUILD_DIR/${PROGNAME}.asm")
|
||||
if mcu == "esp32s3":
|
||||
env.Execute("xtensa-esp32s3-elf-objdump "+ "-D -C " + str(target[0]) + " > "+ "$BUILD_DIR/${PROGNAME}.asm")
|
||||
if mcu == "esp32c3":
|
||||
env.Execute("riscv32-esp-elf-objdump "+ "-D -C " + str(target[0]) + " > "+ "$BUILD_DIR/${PROGNAME}.asm")
|
||||
|
||||
env.AddPostAction("$BUILD_DIR/${PROGNAME}.elf", [obj_dump_after_elf])
|
||||
|
||||
@@ -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"
|
||||
@@ -36,6 +37,8 @@ def create_release(source):
|
||||
def bin_rename_copy(source, target, env):
|
||||
_create_dirs()
|
||||
variant = env["PIOENV"]
|
||||
builddir = os.path.join(env["PROJECT_BUILD_DIR"], variant)
|
||||
source_map = os.path.join(builddir, env["PROGNAME"] + ".map")
|
||||
|
||||
# create string with location and file names based on variant
|
||||
map_file = "{}map{}{}.map".format(OUTPUT_DIR, os.path.sep, variant)
|
||||
@@ -44,7 +47,11 @@ def bin_rename_copy(source, target, env):
|
||||
|
||||
# copy firmware.map to map/<variant>.map
|
||||
if os.path.isfile("firmware.map"):
|
||||
shutil.move("firmware.map", map_file)
|
||||
print("Found linker mapfile firmware.map")
|
||||
shutil.copy("firmware.map", map_file)
|
||||
if os.path.isfile(source_map):
|
||||
print(f"Found linker mapfile {source_map}")
|
||||
shutil.copy(source_map, map_file)
|
||||
|
||||
def bin_gzip(source, target):
|
||||
# only create gzip for esp8266
|
||||
|
||||
311
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_8MB, esp32s3dev_8MB_PSRAM_opi, esp32s3_4M_PSRAM_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
|
||||
@@ -86,7 +86,6 @@ debug_flags = -D DEBUG=1 -D WLED_DEBUG
|
||||
# This reduces the OTA size with ~45KB, so it's especially useful on low memory boards (512k/1m).
|
||||
# ------------------------------------------------------------------------------
|
||||
build_flags =
|
||||
-Wno-attributes
|
||||
-DMQTT_MAX_PACKET_SIZE=1024
|
||||
-DSECURE_CLIENT=SECURE_CLIENT_BEARSSL
|
||||
-DBEARSSL_SSL_BASIC
|
||||
@@ -104,10 +103,6 @@ build_flags =
|
||||
|
||||
build_unflags =
|
||||
|
||||
build_flags_esp8266 = ${common.build_flags} ${esp8266.build_flags}
|
||||
build_flags_esp32 = ${common.build_flags} ${esp32.build_flags}
|
||||
build_flags_esp32_V4= ${common.build_flags} ${esp32_idf_V4.build_flags}
|
||||
|
||||
ldscript_1m128k = eagle.flash.1m128.ld
|
||||
ldscript_2m512k = eagle.flash.2m512.ld
|
||||
ldscript_2m1m = eagle.flash.2m1m.ld
|
||||
@@ -120,6 +115,7 @@ extra_scripts =
|
||||
post:pio-scripts/strip-floats.py
|
||||
pre:pio-scripts/user_config_copy.py
|
||||
pre:pio-scripts/build_ui.py
|
||||
; post:pio-scripts/obj-dump.py ;; convenience script to create a disassembly dump of the firmware (hardcore debugging)
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# COMMON SETTINGS:
|
||||
@@ -142,8 +138,9 @@ lib_compat_mode = strict
|
||||
lib_deps =
|
||||
fastled/FastLED @ 3.6.0
|
||||
IRremoteESP8266 @ 2.8.2
|
||||
makuna/NeoPixelBus @ 2.7.9
|
||||
https://github.com/Aircoookie/ESPAsyncWebServer.git @ 2.2.1
|
||||
makuna/NeoPixelBus @ 2.8.0
|
||||
#https://github.com/makuna/NeoPixelBus.git#CoreShaderBeta
|
||||
https://github.com/Aircoookie/ESPAsyncWebServer.git#v2.2.1
|
||||
# for I2C interface
|
||||
;Wire
|
||||
# ESP-NOW library
|
||||
@@ -174,11 +171,12 @@ lib_deps =
|
||||
# SHT85
|
||||
;robtillaart/SHT85@~0.3.3
|
||||
# Audioreactive usermod
|
||||
;kosme/arduinoFFT @ 2.0.0
|
||||
;kosme/arduinoFFT @ 2.0.1
|
||||
|
||||
extra_scripts = ${scripts_defaults.extra_scripts}
|
||||
|
||||
[esp8266]
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags =
|
||||
-DESP8266
|
||||
-DFP_IN_IROM
|
||||
@@ -200,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
|
||||
@@ -218,14 +251,21 @@ build_flags = -g
|
||||
#use LITTLEFS library by lorol in ESP32 core 1.x.x instead of built-in in 2.x.x
|
||||
-D LOROL_LITTLEFS
|
||||
; -DARDUINO_USB_CDC_ON_BOOT=0 ;; this flag is mandatory for "classic ESP32" when building with arduino-esp32 >=2.0.3
|
||||
tiny_partitions = tools/WLED_ESP32_2MB_noOTA.csv
|
||||
default_partitions = tools/WLED_ESP32_4MB_1MB_FS.csv
|
||||
extended_partitions = tools/WLED_ESP32_4MB_700k_FS.csv
|
||||
big_partitions = tools/WLED_ESP32_4MB_256KB_FS.csv ;; 1.8MB firmware, 256KB filesystem, coredump support
|
||||
large_partitions = tools/WLED_ESP32_8MB.csv
|
||||
extreme_partitions = tools/WLED_ESP32_16MB_9MB_FS.csv
|
||||
lib_deps =
|
||||
https://github.com/lorol/LITTLEFS.git
|
||||
https://github.com/pbolduc/AsyncTCP.git @ 1.2.0
|
||||
${env.lib_deps}
|
||||
# additional build flags for audioreactive
|
||||
AR_build_flags = -D USERMOD_AUDIOREACTIVE
|
||||
AR_lib_deps = kosme/arduinoFFT @ 2.0.0
|
||||
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
|
||||
@@ -233,24 +273,24 @@ AR_lib_deps = kosme/arduinoFFT @ 2.0.0
|
||||
;;
|
||||
;; please note that you can NOT update existing ESP32 installs with a "V4" build. Also updating by OTA will not work properly.
|
||||
;; You need to completely erase your device (esptool erase_flash) first, then install the "V4" build from VSCode+platformio.
|
||||
platform = espressif32@5.3.0
|
||||
platform_packages =
|
||||
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
|
||||
#-DCONFIG_LITTLEFS_FOR_IDF_3_2
|
||||
-D CONFIG_ASYNC_TCP_USE_WDT=0
|
||||
-DARDUINO_USB_CDC_ON_BOOT=0 ;; this flag is mandatory for "classic ESP32" when building with arduino-esp32 >=2.0.3
|
||||
default_partitions = tools/WLED_ESP32_4MB_1MB_FS.csv
|
||||
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@5.3.0
|
||||
platform_packages =
|
||||
default_partitions = tools/WLED_ESP32_4MB_1MB_FS.csv
|
||||
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
|
||||
@@ -264,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@5.3.0
|
||||
platform_packages =
|
||||
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
|
||||
@@ -281,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@5.3.0
|
||||
platform_packages =
|
||||
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
|
||||
@@ -296,10 +340,10 @@ build_flags = -g
|
||||
-DCO
|
||||
;; please make sure that the following flags are properly set (to 0 or 1) by your board.json, or included in your custom platformio_override.ini entry:
|
||||
;; ARDUINO_USB_MODE, ARDUINO_USB_CDC_ON_BOOT
|
||||
|
||||
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
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
@@ -312,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} -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} -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
|
||||
@@ -327,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} -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} -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
|
||||
@@ -341,39 +402,81 @@ 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} -D WLED_RELEASE_NAME=ESP01 -D WLED_DISABLE_OTA
|
||||
; -D WLED_USE_UNREAL_MATH ;; may cause wrong sunset/sunrise times, but saves 7064 bytes FLASH and 975 bytes RAM
|
||||
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} -D WLED_RELEASE_NAME=ESP01_160 -D WLED_DISABLE_OTA
|
||||
; -D WLED_USE_UNREAL_MATH ;; may cause wrong sunset/sunrise times, but saves 7064 bytes FLASH and 975 bytes RAM
|
||||
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]
|
||||
board = esp32dev
|
||||
platform = ${esp32.platform}
|
||||
platform_packages = ${esp32.platform_packages}
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags_esp32} -D WLED_RELEASE_NAME=ESP32 #-D WLED_DISABLE_BROWNOUT_DET
|
||||
lib_deps = ${esp32.lib_deps}
|
||||
monitor_filters = esp32_exception_decoder
|
||||
board_build.partitions = ${esp32.default_partitions}
|
||||
|
||||
[env:esp32dev_audioreactive]
|
||||
board = esp32dev
|
||||
platform = ${esp32.platform}
|
||||
platform_packages = ${esp32.platform_packages}
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags_esp32} -D WLED_RELEASE_NAME=ESP32_audioreactive #-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}
|
||||
|
||||
[env:esp32dev_8M]
|
||||
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
|
||||
${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 = dio
|
||||
; board_build.flash_mode = qio
|
||||
|
||||
[env:esp32dev_16M]
|
||||
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_16M\" #-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.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
|
||||
@@ -381,22 +484,28 @@ platform = ${esp32.platform}
|
||||
platform_packages = ${esp32.platform_packages}
|
||||
upload_speed = 921600
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags_esp32} -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]
|
||||
platform = ${esp32.platform}
|
||||
extends = esp32_idf_V4
|
||||
platform = ${esp32_idf_V4.platform}
|
||||
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 = tools/WLED_ESP32-wrover_4MB.csv
|
||||
board_build.partitions = ${esp32.extended_partitions}
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags_esp32} -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
|
||||
lib_deps = ${esp32.lib_deps}
|
||||
-D DATA_PINS=25
|
||||
${esp32.AR_build_flags}
|
||||
lib_deps = ${esp32_idf_V4.lib_deps}
|
||||
${esp32.AR_lib_deps}
|
||||
|
||||
[env:esp32c3dev]
|
||||
extends = esp32c3
|
||||
@@ -404,8 +513,8 @@ platform = ${esp32c3.platform}
|
||||
platform_packages = ${esp32c3.platform_packages}
|
||||
framework = arduino
|
||||
board = esp32-c3-devkitm-1
|
||||
board_build.partitions = tools/WLED_ESP32_4MB_1MB_FS.csv
|
||||
build_flags = ${common.build_flags} ${esp32c3.build_flags} -D WLED_RELEASE_NAME=ESP32-C3
|
||||
board_build.partitions = ${esp32.default_partitions}
|
||||
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
|
||||
@@ -414,35 +523,15 @@ upload_speed = 460800
|
||||
build_unflags = ${common.build_unflags}
|
||||
lib_deps = ${esp32c3.lib_deps}
|
||||
|
||||
[env:esp32s3dev_8MB]
|
||||
;; ESP32-S3-DevKitC-1 development board, with 8MB FLASH, no PSRAM (flash_mode: qio)
|
||||
board = esp32-s3-devkitc-1
|
||||
platform = ${esp32s3.platform}
|
||||
platform_packages = ${esp32s3.platform_packages}
|
||||
upload_speed = 921600 ; or 460800
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp32s3.build_flags} -D WLED_RELEASE_NAME=ESP32-S3_8MB
|
||||
-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")
|
||||
${esp32.AR_build_flags}
|
||||
lib_deps = ${esp32s3.lib_deps}
|
||||
${esp32.AR_lib_deps}
|
||||
board_build.partitions = tools/WLED_ESP32_8MB.csv
|
||||
board_build.f_flash = 80000000L
|
||||
board_build.flash_mode = qio
|
||||
; board_build.flash_mode = dio ;; try this if you have problems at startup
|
||||
monitor_filters = esp32_exception_decoder
|
||||
|
||||
[env:esp32s3dev_8MB_PSRAM_opi]
|
||||
;; ESP32-S3 development board, with 8MB FLASH and >= 8MB PSRAM (memory_type: qio_opi)
|
||||
[env:esp32s3dev_16MB_opi]
|
||||
;; ESP32-S3 development board, with 16MB FLASH and >= 8MB PSRAM (memory_type: qio_opi)
|
||||
board = esp32-s3-devkitc-1 ;; generic dev board; the next line adds PSRAM support
|
||||
board_build.arduino.memory_type = qio_opi ;; use with PSRAM: 8MB or 16MB
|
||||
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_PSRAM_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")
|
||||
@@ -450,27 +539,77 @@ build_flags = ${common.build_flags} ${esp32s3.build_flags} -D WLED_RELEASE_NAME=
|
||||
${esp32.AR_build_flags}
|
||||
lib_deps = ${esp32s3.lib_deps}
|
||||
${esp32.AR_lib_deps}
|
||||
board_build.partitions = tools/WLED_ESP32_8MB.csv
|
||||
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
|
||||
|
||||
[env:esp32s3_4M_PSRAM_qspi]
|
||||
;; ESP32-S3, with 4MB FLASH and <= 4MB PSRAM (memory_type: qio_qspi)
|
||||
[env:esp32s3dev_8MB_opi]
|
||||
;; ESP32-S3 development board, with 8MB FLASH and >= 8MB PSRAM (memory_type: qio_opi)
|
||||
board = esp32-s3-devkitc-1 ;; generic dev board; the next line adds PSRAM support
|
||||
board_build.arduino.memory_type = qio_qspi ;; use with PSRAM: 2MB or 4MB
|
||||
board_build.arduino.memory_type = qio_opi ;; use with PSRAM: 8MB or 16MB
|
||||
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_PSRAM_qspi
|
||||
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")
|
||||
-DBOARD_HAS_PSRAM
|
||||
${esp32.AR_build_flags}
|
||||
lib_deps = ${esp32s3.lib_deps}
|
||||
${esp32.AR_lib_deps}
|
||||
board_build.partitions = ${esp32.large_partitions}
|
||||
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
|
||||
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\"
|
||||
-DARDUINO_USB_CDC_ON_BOOT=1 -DARDUINO_USB_MODE=1 ;; for boards with USB-OTG connector only (USBCDC or "TinyUSB")
|
||||
-DBOARD_HAS_PSRAM
|
||||
-DLOLIN_WIFI_FIX ; seems to work much better with this
|
||||
-D WLED_WATCHDOG_TIMEOUT=0
|
||||
${esp32.AR_build_flags}
|
||||
lib_deps = ${esp32s3.lib_deps}
|
||||
${esp32.AR_lib_deps}
|
||||
board_build.partitions = tools/WLED_ESP32_4MB_1MB_FS.csv
|
||||
board_build.partitions = ${esp32.default_partitions}
|
||||
board_build.f_flash = 80000000L
|
||||
board_build.flash_mode = qio
|
||||
monitor_filters = esp32_exception_decoder
|
||||
@@ -479,11 +618,11 @@ monitor_filters = esp32_exception_decoder
|
||||
platform = ${esp32s2.platform}
|
||||
platform_packages = ${esp32s2.platform_packages}
|
||||
board = lolin_s2_mini
|
||||
board_build.partitions = tools/WLED_ESP32_4MB_1MB_FS.csv
|
||||
;board_build.flash_mode = qio
|
||||
;board_build.f_flash = 80000000L
|
||||
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
|
||||
@@ -491,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,12 +5,12 @@
|
||||
# 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
|
||||
#----------
|
||||
[env:WLED_tasmota_1M]
|
||||
[env:WLED_generic8266_1M]
|
||||
extends = env:esp01_1m_full # when you want to extend the existing environment (define only updated options)
|
||||
; board = esp01_1m # uncomment when ou need different board
|
||||
; platform = ${common.platform_wled_default} # uncomment and change when you want particular platform
|
||||
@@ -26,14 +26,19 @@ lib_deps = ${esp8266.lib_deps}
|
||||
; adafruit/Adafruit BME280 Library@^2.2.2
|
||||
; Wire
|
||||
; robtillaart/SHT85@~0.3.3
|
||||
; gmag11/QuickESPNow ;@ 0.6.2
|
||||
; ;gmag11/QuickESPNow @ ~0.7.0 # will also load QuickDebug
|
||||
; https://github.com/blazoncek/QuickESPNow.git#optional-debug ;; exludes debug library
|
||||
; https://github.com/kosme/arduinoFFT#develop @ 1.9.2+sha.419d7b0 ;; used for USERMOD_AUDIOREACTIVE - using "known working" hash
|
||||
; build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags_esp8266}
|
||||
; 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\"
|
||||
;
|
||||
; disable specific features
|
||||
; -D WLED_DISABLE_OTA
|
||||
; -D WLED_DISABLE_ALEXA
|
||||
@@ -48,18 +53,26 @@ build_flags = ${common.build_flags_esp8266}
|
||||
; -D WLED_DISABLE_ESPNOW
|
||||
; -D WLED_DISABLE_BROWNOUT_DET
|
||||
;
|
||||
; enable optional built-in features
|
||||
; -D WLED_ENABLE_PIXART
|
||||
; -D WLED_ENABLE_USERMOD_PAGE # if created
|
||||
; -D WLED_ENABLE_DMX
|
||||
;
|
||||
; PIN defines - uncomment and change, if needed:
|
||||
; -D LEDPIN=2
|
||||
; -D DATA_PINS=2
|
||||
; or use this for multiple outputs
|
||||
; -D DATA_PINS=1,3
|
||||
; -D BTNPIN=0
|
||||
; -D IRPIN=4
|
||||
; -D RLYPIN=12
|
||||
; -D RLYMDE=1
|
||||
; -D RLYODRAIN=0
|
||||
; -D LED_BUILTIN=2 # GPIO of built-in LED
|
||||
;
|
||||
; Limit max buses
|
||||
; -D WLED_MAX_BUSSES=2
|
||||
; -D WLED_MAX_ANALOG_CHANNELS=3 # only 3 PWM HW pins available
|
||||
; -D WLED_MAX_DIGITAL_CHANNELS=2 # only 2 HW accelerated pins available
|
||||
;
|
||||
; Configure default WiFi
|
||||
; -D CLIENT_SSID='"MyNetwork"'
|
||||
@@ -90,9 +103,14 @@ build_flags = ${common.build_flags_esp8266}
|
||||
; -D USERMOD_AUTO_SAVE
|
||||
; -D AUTOSAVE_AFTER_SEC=90
|
||||
;
|
||||
; Use AHT10/AHT15/AHT20 usermod
|
||||
; -D USERMOD_AHT10
|
||||
;
|
||||
; Use INA226 usermod
|
||||
; -D USERMOD_INA226
|
||||
;
|
||||
; Use 4 Line Display usermod with SPI display
|
||||
; -D USERMOD_FOUR_LINE_DISPLAY
|
||||
; -D USE_ALT_DISPlAY # mandatory
|
||||
; -DFLD_SPI_DEFAULT
|
||||
; -D FLD_TYPE=SSD1306_SPI64
|
||||
; -D FLD_PIN_CLOCKSPI=14
|
||||
@@ -118,12 +136,13 @@ build_flags = ${common.build_flags_esp8266}
|
||||
;
|
||||
; Use PIR sensor usermod and configure it to use GPIO4 and timer of 60s
|
||||
; -D USERMOD_PIRSWITCH
|
||||
; -D PIR_SENSOR_PIN=4
|
||||
; -D PIR_SENSOR_PIN=4 # use -1 to disable usermod
|
||||
; -D PIR_SENSOR_OFF_SEC=60
|
||||
; -D PIR_SENSOR_MAX_SENSORS=2 # max allowable sensors (uses OR logic for triggering)
|
||||
;
|
||||
; Use Audioreactive usermod and configure I2S microphone
|
||||
; -D USERMOD_AUDIOREACTIVE
|
||||
; -D UM_AUDIOREACTIVE_USE_NEW_FFT
|
||||
; ${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
|
||||
@@ -135,28 +154,36 @@ build_flags = ${common.build_flags_esp8266}
|
||||
; -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 milliampere limit when using ESP pin to power leds
|
||||
; -D ABL_MILLIAMPS_DEFAULT=850
|
||||
;
|
||||
; 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 the default LED type
|
||||
; -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
|
||||
; -D LED_MILLIAMPS_DEFAULT=55
|
||||
;
|
||||
; enable IR by setting remote type
|
||||
; -D IRTYPE=0 # 0 Remote disabled | 1 24-key RGB | 2 24-key with CT | 3 40-key blue | 4 40-key RGB | 5 21-key RGB | 6 6-key black | 7 9-key red | 8 JSON remote
|
||||
;
|
||||
; use PSRAM on classic ESP32 rev.1 (rev.3 or above has no issues)
|
||||
; -DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue
|
||||
; -DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue # needed only for classic ESP32 rev.1
|
||||
;
|
||||
; configure I2C and SPI interface (for various hardware)
|
||||
; -D I2CSDAPIN=33 # initialise interface
|
||||
@@ -179,7 +206,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 = ${common.build_flags} ${esp8266.build_flags}
|
||||
lib_deps = ${esp8266.lib_deps}
|
||||
|
||||
[env:d1_mini]
|
||||
@@ -189,7 +216,7 @@ platform_packages = ${common.platform_packages}
|
||||
upload_speed = 921600
|
||||
board_build.ldscript = ${common.ldscript_4m1m}
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags_esp8266}
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags}
|
||||
lib_deps = ${esp8266.lib_deps}
|
||||
monitor_filters = esp8266_exception_decoder
|
||||
|
||||
@@ -199,7 +226,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 = ${common.build_flags} ${esp8266.build_flags}
|
||||
lib_deps = ${esp8266.lib_deps}
|
||||
|
||||
[env:h803wf]
|
||||
@@ -208,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} -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} -D WLED_RELEASE_NAME=ESP32_qio80 #-D WLED_DISABLE_BROWNOUT_DET
|
||||
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
|
||||
|
||||
@@ -227,27 +253,26 @@ 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_RELEASE_NAME=ESP32_V4_qio80 #-D WLED_DISABLE_BROWNOUT_DET
|
||||
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 = https://github.com/tasmota/platform-espressif32/releases/download/v2.0.2.2/platform-tasmota-espressif32-2.0.2.zip
|
||||
platform_packages =
|
||||
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} #-D WLED_RELEASE_NAME=S2_saola
|
||||
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
|
||||
lib_deps = ${esp32s2.lib_deps}
|
||||
@@ -265,7 +290,7 @@ 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} -D WLED_DISABLE_OTA
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D WLED_DISABLE_OTA
|
||||
lib_deps = ${esp8266.lib_deps}
|
||||
|
||||
[env:esp8285_H801]
|
||||
@@ -274,7 +299,7 @@ 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} -D WLED_DISABLE_OTA
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D WLED_DISABLE_OTA
|
||||
lib_deps = ${esp8266.lib_deps}
|
||||
|
||||
[env:d1_mini_5CH_Shojo_PCB]
|
||||
@@ -283,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} -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]
|
||||
@@ -293,7 +318,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} ${common.debug_flags}
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} ${common.debug_flags}
|
||||
lib_deps = ${esp8266.lib_deps}
|
||||
|
||||
[env:d1_mini_ota]
|
||||
@@ -305,7 +330,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 = ${common.build_flags} ${esp8266.build_flags}
|
||||
lib_deps = ${esp8266.lib_deps}
|
||||
|
||||
[env:anavi_miracle_controller]
|
||||
@@ -314,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} -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]
|
||||
@@ -324,7 +349,7 @@ extends = esp32c3
|
||||
platform = ${esp32c3.platform}
|
||||
platform_packages = ${esp32c3.platform_packages}
|
||||
board = esp32-c3-devkitm-1
|
||||
build_flags = ${common.build_flags} ${esp32c3.build_flags} #-D WLED_RELEASE_NAME=ESP32-C3
|
||||
build_flags = ${common.build_flags} ${esp32c3.build_flags}
|
||||
-D WLED_WATCHDOG_TIMEOUT=0
|
||||
-D WLED_DISABLE_OTA
|
||||
; -DARDUINO_USB_CDC_ON_BOOT=1 ;; for virtual CDC USB
|
||||
@@ -334,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}
|
||||
-D LEDPIN=16
|
||||
build_flags = ${common.build_flags} ${esp32.build_flags}
|
||||
-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} -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} -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} -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
|
||||
@@ -387,8 +426,8 @@ 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} -D WLED_RELEASE_NAME=ESP8266 -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
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D BTNPIN=-1 -D RLYPIN=-1 -D DATA_PINS=4,12,14,13,5
|
||||
-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
|
||||
@@ -397,8 +436,8 @@ 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} -D WLED_RELEASE_NAME=ESP8266 -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
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D BTNPIN=-1 -D RLYPIN=-1 -D DATA_PINS=4,12,14,5,13
|
||||
-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
|
||||
@@ -407,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} -D WLED_RELEASE_NAME=ESP8266 -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
|
||||
@@ -416,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} -D WLED_RELEASE_NAME=ESP8266 -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
|
||||
@@ -425,7 +464,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} -D WLED_RELEASE_NAME=ESP8266 -D BTNPIN=0 -D RLYPIN=-1 DATA_PINS=4,12,14,13 -D WLED_DISABLE_INFRARED
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D BTNPIN=0 -D RLYPIN=-1 DATA_PINS=4,12,14,13 -D WLED_DISABLE_INFRARED
|
||||
lib_deps = ${esp8266.lib_deps}
|
||||
|
||||
[env:MY9291]
|
||||
@@ -434,7 +473,7 @@ 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} -D WLED_RELEASE_NAME=ESP01 -D WLED_DISABLE_OTA -D USERMOD_MY9291
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags} -D WLED_DISABLE_OTA -D USERMOD_MY9291
|
||||
lib_deps = ${esp8266.lib_deps}
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
@@ -448,7 +487,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 = ${common.build_flags} ${esp8266.build_flags}
|
||||
lib_deps = ${esp8266.lib_deps}
|
||||
|
||||
[env:codm-controller-0_6-rev2]
|
||||
@@ -457,24 +496,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 = ${common.build_flags} ${esp8266.build_flags}
|
||||
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} -D WLED_DISABLE_BROWNOUT_DET -D WLED_DISABLE_INFRARED
|
||||
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
|
||||
@@ -490,5 +528,4 @@ build_flags = ${common.build_flags_esp32} -D WLED_DISABLE_BROWNOUT_DET -D WLED_D
|
||||
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
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
|
||||
# Welcome to my project WLED! ✨
|
||||
|
||||
A fast and feature-rich implementation of an ESP8266/ESP32 webserver to control NeoPixel (WS2812B, WS2811, SK6812) LEDs or also SPI based chipsets like the WS2801 and APA102!
|
||||
A fast and feature-rich implementation of an ESP32 and ESP8266 webserver to control NeoPixel (WS2812B, WS2811, SK6812) LEDs or also SPI based chipsets like the WS2801 and APA102!
|
||||
|
||||
## ⚙️ Features
|
||||
- WS2812FX library with more than 100 special effects
|
||||
@@ -21,7 +21,7 @@ A fast and feature-rich implementation of an ESP8266/ESP32 webserver to control
|
||||
- Segments to set different effects and colors to user defined parts of the LED string
|
||||
- Settings page - configuration via the network
|
||||
- Access Point and station mode - automatic failsafe AP
|
||||
- Up to 10 LED outputs per instance
|
||||
- [Up to 10 LED outputs](https://kno.wled.ge/features/multi-strip/#esp32) per instance
|
||||
- Support for RGBW strips
|
||||
- Up to 250 user presets to save and load colors/effects easily, supports cycling through them.
|
||||
- Presets can be used to automatically execute API calls
|
||||
@@ -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
@@ -0,0 +1,37 @@
|
||||
#!/bin/bash
|
||||
# Some web server stress tests
|
||||
#
|
||||
# Perform a large number of parallel requests, stress testing the web server
|
||||
# TODO: some kind of performance metrics
|
||||
|
||||
# Accepts three command line arguments:
|
||||
# - first argument - mandatory - IP or hostname of target server
|
||||
# - second argument - target type (optional)
|
||||
# - third argument - xfer count (for replicated targets) (optional)
|
||||
HOST=$1
|
||||
declare -n TARGET_STR="${2:-JSON_LARGER}_TARGETS"
|
||||
REPLICATE_COUNT=$(("${3:-10}"))
|
||||
|
||||
PARALLEL_MAX=${PARALLEL_MAX:-50}
|
||||
|
||||
CURL_ARGS="--compressed --parallel --parallel-immediate --parallel-max ${PARALLEL_MAX}"
|
||||
CURL_PRINT_RESPONSE_ARGS="-w %{http_code}\n"
|
||||
|
||||
JSON_TARGETS=('json/state' 'json/info' 'json/si', 'json/palettes' 'json/fxdata' 'settings/s.js?p=2')
|
||||
FILE_TARGETS=('' 'iro.js' 'rangetouch.js' 'settings' 'settings/wifi')
|
||||
# Replicate one target many times
|
||||
function replicate() {
|
||||
printf "${1}?%d " $(seq 1 ${REPLICATE_COUNT})
|
||||
}
|
||||
read -a JSON_TINY_TARGETS <<< $(replicate "json/nodes")
|
||||
read -a JSON_SMALL_TARGETS <<< $(replicate "json/info")
|
||||
read -a JSON_LARGE_TARGETS <<< $(replicate "json/si")
|
||||
read -a JSON_LARGER_TARGETS <<< $(replicate "json/fxdata")
|
||||
|
||||
# Expand target URLS to full arguments for curl
|
||||
TARGETS=(${TARGET_STR[@]})
|
||||
#echo "${TARGETS[@]}"
|
||||
FULL_TGT_OPTIONS=$(printf "http://${HOST}/%s -o /dev/null " "${TARGETS[@]}")
|
||||
#echo ${FULL_TGT_OPTIONS}
|
||||
|
||||
time curl ${CURL_ARGS} ${FULL_TGT_OPTIONS}
|
||||
46
tools/udp_test.py
Normal file
@@ -0,0 +1,46 @@
|
||||
import numpy as np
|
||||
import socket
|
||||
|
||||
class WledRealtimeClient:
|
||||
def __init__(self, wled_controller_ip, num_pixels, udp_port=21324, max_pixels_per_packet=126):
|
||||
self.wled_controller_ip = wled_controller_ip
|
||||
self.num_pixels = num_pixels
|
||||
self.udp_port = udp_port
|
||||
self.max_pixels_per_packet = max_pixels_per_packet
|
||||
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
self._prev_pixels = np.full((3, self.num_pixels), 253, dtype=np.uint8)
|
||||
self.pixels = np.full((3, self.num_pixels), 1, dtype=np.uint8)
|
||||
|
||||
def update(self):
|
||||
# Truncate values and cast to integer
|
||||
self.pixels = np.clip(self.pixels, 0, 255).astype(np.uint8)
|
||||
p = np.copy(self.pixels)
|
||||
|
||||
idx = np.where(~np.all(p == self._prev_pixels, axis=0))[0]
|
||||
num_pixels = len(idx)
|
||||
n_packets = (num_pixels + self.max_pixels_per_packet - 1) // self.max_pixels_per_packet
|
||||
idx_split = np.array_split(idx, n_packets)
|
||||
|
||||
header = bytes([1, 2]) # WARLS protocol header
|
||||
for packet_indices in idx_split:
|
||||
data = bytearray(header)
|
||||
for i in packet_indices:
|
||||
data.extend([i, *p[:, i]]) # Index and RGB values
|
||||
self._sock.sendto(bytes(data), (self.wled_controller_ip, self.udp_port))
|
||||
|
||||
self._prev_pixels = np.copy(p)
|
||||
|
||||
|
||||
|
||||
################################## LED blink test ##################################
|
||||
if __name__ == "__main__":
|
||||
WLED_CONTROLLER_IP = "192.168.1.153"
|
||||
NUM_PIXELS = 255 # Amount of LEDs on your strip
|
||||
import time
|
||||
wled = WledRealtimeClient(WLED_CONTROLLER_IP, NUM_PIXELS)
|
||||
print('Starting LED blink test')
|
||||
while True:
|
||||
for i in range(NUM_PIXELS):
|
||||
wled.pixels[1, i] = 255 if wled.pixels[1, i] == 0 else 0
|
||||
wled.update()
|
||||
time.sleep(.01)
|
||||
36
usermods/AHT10_v2/README.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# Usermod AHT10
|
||||
This Usermod is designed to read a `AHT10`, `AHT15` or `AHT20` sensor and output the following:
|
||||
- Temperature
|
||||
- Humidity
|
||||
|
||||
Configuration is performed via the Usermod menu. The following settings can be configured in the Usermod Menu:
|
||||
- I2CAddress: The i2c address in decimal. Set it to either 56 (0x38, the default) or 57 (0x39).
|
||||
- SensorType, one of:
|
||||
- 0 - AHT10
|
||||
- 1 - AHT15
|
||||
- 2 - AHT20
|
||||
- CheckInterval: Number of seconds between readings
|
||||
- Decimals: Number of decimals to put in the output
|
||||
|
||||
Dependencies, These must be added under `lib_deps` in your `platform.ini` (or `platform_override.ini`).
|
||||
- Libraries
|
||||
- `enjoyneering/AHT10@~1.1.0` (by [enjoyneering](https://registry.platformio.org/libraries/enjoyneering/AHT10))
|
||||
- `Wire`
|
||||
|
||||
## Author
|
||||
[@LordMike](https://github.com/LordMike)
|
||||
|
||||
# Compiling
|
||||
|
||||
To enable, compile with `USERMOD_AHT10` defined (e.g. in `platformio_override.ini`)
|
||||
```ini
|
||||
[env:aht10_example]
|
||||
extends = env:esp32dev
|
||||
build_flags =
|
||||
${common.build_flags} ${esp32.build_flags}
|
||||
-D USERMOD_AHT10
|
||||
; -D USERMOD_AHT10_DEBUG ; -- add a debug status to the info modal
|
||||
lib_deps =
|
||||
${esp32.lib_deps}
|
||||
enjoyneering/AHT10@~1.1.0
|
||||
```
|
||||
9
usermods/AHT10_v2/platformio_override.ini
Normal file
@@ -0,0 +1,9 @@
|
||||
[env:aht10_example]
|
||||
extends = env:esp32dev
|
||||
build_flags =
|
||||
${common.build_flags} ${esp32.build_flags}
|
||||
-D USERMOD_AHT10
|
||||
; -D USERMOD_AHT10_DEBUG ; -- add a debug status to the info modal
|
||||
lib_deps =
|
||||
${esp32.lib_deps}
|
||||
enjoyneering/AHT10@~1.1.0
|
||||
327
usermods/AHT10_v2/usermod_aht10.h
Normal file
@@ -0,0 +1,327 @@
|
||||
#pragma once
|
||||
|
||||
#include "wled.h"
|
||||
#include <AHT10.h>
|
||||
|
||||
#define AHT10_SUCCESS 1
|
||||
|
||||
class UsermodAHT10 : public Usermod
|
||||
{
|
||||
private:
|
||||
static const char _name[];
|
||||
|
||||
unsigned long _lastLoopCheck = 0;
|
||||
|
||||
bool _settingEnabled : 1; // Enable the usermod
|
||||
bool _mqttPublish : 1; // Publish mqtt values
|
||||
bool _mqttPublishAlways : 1; // Publish always, regardless if there is a change
|
||||
bool _mqttHomeAssistant : 1; // Enable Home Assistant docs
|
||||
bool _initDone : 1; // Initialization is done
|
||||
|
||||
// Settings. Some of these are stored in a different format than they're user settings - so we don't have to convert at runtime
|
||||
uint8_t _i2cAddress = AHT10_ADDRESS_0X38;
|
||||
ASAIR_I2C_SENSOR _ahtType = AHT10_SENSOR;
|
||||
uint16_t _checkInterval = 60000; // milliseconds, user settings is in seconds
|
||||
float _decimalFactor = 100; // a power of 10 factor. 1 would be no change, 10 is one decimal, 100 is two etc. User sees a power of 10 (0, 1, 2, ..)
|
||||
|
||||
uint8_t _lastStatus = 0;
|
||||
float _lastHumidity = 0;
|
||||
float _lastTemperature = 0;
|
||||
|
||||
#ifndef WLED_MQTT_DISABLE
|
||||
float _lastHumiditySent = 0;
|
||||
float _lastTemperatureSent = 0;
|
||||
#endif
|
||||
|
||||
AHT10 *_aht = nullptr;
|
||||
|
||||
float truncateDecimals(float val)
|
||||
{
|
||||
return roundf(val * _decimalFactor) / _decimalFactor;
|
||||
}
|
||||
|
||||
void initializeAht()
|
||||
{
|
||||
if (_aht != nullptr)
|
||||
{
|
||||
delete _aht;
|
||||
}
|
||||
|
||||
_aht = new AHT10(_i2cAddress, _ahtType);
|
||||
|
||||
_lastStatus = 0;
|
||||
_lastHumidity = 0;
|
||||
_lastTemperature = 0;
|
||||
}
|
||||
|
||||
~UsermodAHT10()
|
||||
{
|
||||
delete _aht;
|
||||
_aht = nullptr;
|
||||
}
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
void mqttInitialize()
|
||||
{
|
||||
// This is a generic "setup mqtt" function, So we must abort if we're not to do mqtt
|
||||
if (!WLED_MQTT_CONNECTED || !_mqttPublish || !_mqttHomeAssistant)
|
||||
return;
|
||||
|
||||
char topic[128];
|
||||
snprintf_P(topic, 127, "%s/temperature", mqttDeviceTopic);
|
||||
mqttCreateHassSensor(F("Temperature"), topic, F("temperature"), F("°C"));
|
||||
|
||||
snprintf_P(topic, 127, "%s/humidity", mqttDeviceTopic);
|
||||
mqttCreateHassSensor(F("Humidity"), topic, F("humidity"), F("%"));
|
||||
}
|
||||
|
||||
void mqttPublishIfChanged(const __FlashStringHelper *topic, float &lastState, float state, float minChange)
|
||||
{
|
||||
// Check if MQTT Connected, otherwise it will crash the 8266
|
||||
// Only report if the change is larger than the required diff
|
||||
if (WLED_MQTT_CONNECTED && _mqttPublish && (_mqttPublishAlways || fabsf(lastState - state) > minChange))
|
||||
{
|
||||
char subuf[128];
|
||||
snprintf_P(subuf, 127, PSTR("%s/%s"), mqttDeviceTopic, (const char *)topic);
|
||||
mqtt->publish(subuf, 0, false, String(state).c_str());
|
||||
|
||||
lastState = state;
|
||||
}
|
||||
}
|
||||
|
||||
// Create an MQTT Sensor for Home Assistant Discovery purposes, this includes a pointer to the topic that is published to in the Loop.
|
||||
void mqttCreateHassSensor(const String &name, const String &topic, const String &deviceClass, const String &unitOfMeasurement)
|
||||
{
|
||||
String t = String(F("homeassistant/sensor/")) + mqttClientID + "/" + name + F("/config");
|
||||
|
||||
StaticJsonDocument<600> doc;
|
||||
|
||||
doc[F("name")] = name;
|
||||
doc[F("state_topic")] = topic;
|
||||
doc[F("unique_id")] = String(mqttClientID) + name;
|
||||
if (unitOfMeasurement != "")
|
||||
doc[F("unit_of_measurement")] = unitOfMeasurement;
|
||||
if (deviceClass != "")
|
||||
doc[F("device_class")] = deviceClass;
|
||||
doc[F("expire_after")] = 1800;
|
||||
|
||||
JsonObject device = doc.createNestedObject(F("device")); // attach the sensor to the same device
|
||||
device[F("name")] = serverDescription;
|
||||
device[F("identifiers")] = "wled-sensor-" + String(mqttClientID);
|
||||
device[F("manufacturer")] = F(WLED_BRAND);
|
||||
device[F("model")] = F(WLED_PRODUCT_NAME);
|
||||
device[F("sw_version")] = versionString;
|
||||
|
||||
String temp;
|
||||
serializeJson(doc, temp);
|
||||
DEBUG_PRINTLN(t);
|
||||
DEBUG_PRINTLN(temp);
|
||||
|
||||
mqtt->publish(t.c_str(), 0, true, temp.c_str());
|
||||
}
|
||||
#endif
|
||||
|
||||
public:
|
||||
void setup()
|
||||
{
|
||||
initializeAht();
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
// if usermod is disabled or called during strip updating just exit
|
||||
// NOTE: on very long strips strip.isUpdating() may always return true so update accordingly
|
||||
if (!_settingEnabled || strip.isUpdating())
|
||||
return;
|
||||
|
||||
// do your magic here
|
||||
unsigned long currentTime = millis();
|
||||
|
||||
if (currentTime - _lastLoopCheck < _checkInterval)
|
||||
return;
|
||||
_lastLoopCheck = currentTime;
|
||||
|
||||
_lastStatus = _aht->readRawData();
|
||||
|
||||
if (_lastStatus == AHT10_ERROR)
|
||||
{
|
||||
// Perform softReset and retry
|
||||
DEBUG_PRINTLN(F("AHTxx returned error, doing softReset"));
|
||||
if (!_aht->softReset())
|
||||
{
|
||||
DEBUG_PRINTLN(F("softReset failed"));
|
||||
return;
|
||||
}
|
||||
|
||||
_lastStatus = _aht->readRawData();
|
||||
}
|
||||
|
||||
if (_lastStatus == AHT10_SUCCESS)
|
||||
{
|
||||
float temperature = truncateDecimals(_aht->readTemperature(AHT10_USE_READ_DATA));
|
||||
float humidity = truncateDecimals(_aht->readHumidity(AHT10_USE_READ_DATA));
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
// Push to MQTT
|
||||
|
||||
// We can avoid reporting if the change is insignificant. The threshold chosen is below the level of accuracy, but way above 0.01 which is the precision of the value provided.
|
||||
// The AHT10/15/20 has an accuracy of 0.3C in the temperature readings
|
||||
mqttPublishIfChanged(F("temperature"), _lastTemperatureSent, temperature, 0.1f);
|
||||
|
||||
// The AHT10/15/20 has an accuracy in the humidity sensor of 2%
|
||||
mqttPublishIfChanged(F("humidity"), _lastHumiditySent, humidity, 0.5f);
|
||||
#endif
|
||||
|
||||
// Store
|
||||
_lastTemperature = temperature;
|
||||
_lastHumidity = humidity;
|
||||
}
|
||||
}
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
void onMqttConnect(bool sessionPresent)
|
||||
{
|
||||
mqttInitialize();
|
||||
}
|
||||
#endif
|
||||
|
||||
uint16_t getId()
|
||||
{
|
||||
return USERMOD_ID_AHT10;
|
||||
}
|
||||
|
||||
void addToJsonInfo(JsonObject &root) override
|
||||
{
|
||||
// if "u" object does not exist yet wee need to create it
|
||||
JsonObject user = root["u"];
|
||||
if (user.isNull())
|
||||
user = root.createNestedObject("u");
|
||||
|
||||
#ifdef USERMOD_AHT10_DEBUG
|
||||
JsonArray temp = user.createNestedArray(F("AHT last loop"));
|
||||
temp.add(_lastLoopCheck);
|
||||
|
||||
temp = user.createNestedArray(F("AHT last status"));
|
||||
temp.add(_lastStatus);
|
||||
#endif
|
||||
|
||||
JsonArray jsonTemp = user.createNestedArray(F("Temperature"));
|
||||
JsonArray jsonHumidity = user.createNestedArray(F("Humidity"));
|
||||
|
||||
if (_lastLoopCheck == 0)
|
||||
{
|
||||
// Before first run
|
||||
jsonTemp.add(F("Not read yet"));
|
||||
jsonHumidity.add(F("Not read yet"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (_lastStatus != AHT10_SUCCESS)
|
||||
{
|
||||
jsonTemp.add(F("An error occurred"));
|
||||
jsonHumidity.add(F("An error occurred"));
|
||||
return;
|
||||
}
|
||||
|
||||
jsonTemp.add(_lastTemperature);
|
||||
jsonTemp.add(F("°C"));
|
||||
|
||||
jsonHumidity.add(_lastHumidity);
|
||||
jsonHumidity.add(F("%"));
|
||||
}
|
||||
|
||||
void addToConfig(JsonObject &root)
|
||||
{
|
||||
JsonObject top = root.createNestedObject(FPSTR(_name));
|
||||
top[F("Enabled")] = _settingEnabled;
|
||||
top[F("I2CAddress")] = static_cast<uint8_t>(_i2cAddress);
|
||||
top[F("SensorType")] = _ahtType;
|
||||
top[F("CheckInterval")] = _checkInterval / 1000;
|
||||
top[F("Decimals")] = log10f(_decimalFactor);
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
top[F("MqttPublish")] = _mqttPublish;
|
||||
top[F("MqttPublishAlways")] = _mqttPublishAlways;
|
||||
top[F("MqttHomeAssistantDiscovery")] = _mqttHomeAssistant;
|
||||
#endif
|
||||
|
||||
DEBUG_PRINTLN(F("AHT10 config saved."));
|
||||
}
|
||||
|
||||
bool readFromConfig(JsonObject &root) override
|
||||
{
|
||||
// default settings values could be set here (or below using the 3-argument getJsonValue()) instead of in the class definition or constructor
|
||||
// setting them inside readFromConfig() is slightly more robust, handling the rare but plausible use case of single value being missing after boot (e.g. if the cfg.json was manually edited and a value was removed)
|
||||
|
||||
JsonObject top = root[FPSTR(_name)];
|
||||
|
||||
bool configComplete = !top.isNull();
|
||||
if (!configComplete)
|
||||
return false;
|
||||
|
||||
bool tmpBool = false;
|
||||
configComplete &= getJsonValue(top[F("Enabled")], tmpBool);
|
||||
if (configComplete)
|
||||
_settingEnabled = tmpBool;
|
||||
|
||||
configComplete &= getJsonValue(top[F("I2CAddress")], _i2cAddress);
|
||||
configComplete &= getJsonValue(top[F("CheckInterval")], _checkInterval);
|
||||
if (configComplete)
|
||||
{
|
||||
if (1 <= _checkInterval && _checkInterval <= 600)
|
||||
_checkInterval *= 1000;
|
||||
else
|
||||
// Invalid input
|
||||
_checkInterval = 60000;
|
||||
}
|
||||
|
||||
configComplete &= getJsonValue(top[F("Decimals")], _decimalFactor);
|
||||
if (configComplete)
|
||||
{
|
||||
if (0 <= _decimalFactor && _decimalFactor <= 5)
|
||||
_decimalFactor = pow10f(_decimalFactor);
|
||||
else
|
||||
// Invalid input
|
||||
_decimalFactor = 100;
|
||||
}
|
||||
|
||||
uint8_t tmpAhtType;
|
||||
configComplete &= getJsonValue(top[F("SensorType")], tmpAhtType);
|
||||
if (configComplete)
|
||||
{
|
||||
if (0 <= tmpAhtType && tmpAhtType <= 2)
|
||||
_ahtType = static_cast<ASAIR_I2C_SENSOR>(tmpAhtType);
|
||||
else
|
||||
// Invalid input
|
||||
_ahtType = ASAIR_I2C_SENSOR::AHT10_SENSOR;
|
||||
}
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
configComplete &= getJsonValue(top[F("MqttPublish")], tmpBool);
|
||||
if (configComplete)
|
||||
_mqttPublish = tmpBool;
|
||||
|
||||
configComplete &= getJsonValue(top[F("MqttPublishAlways")], tmpBool);
|
||||
if (configComplete)
|
||||
_mqttPublishAlways = tmpBool;
|
||||
|
||||
configComplete &= getJsonValue(top[F("MqttHomeAssistantDiscovery")], tmpBool);
|
||||
if (configComplete)
|
||||
_mqttHomeAssistant = tmpBool;
|
||||
#endif
|
||||
|
||||
if (_initDone)
|
||||
{
|
||||
// Reloading config
|
||||
initializeAht();
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
mqttInitialize();
|
||||
#endif
|
||||
}
|
||||
|
||||
_initDone = true;
|
||||
return configComplete;
|
||||
}
|
||||
};
|
||||
|
||||
const char UsermodAHT10::_name[] PROGMEM = "AHTxx";
|
||||
@@ -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).
|
||||
|
||||
@@ -59,7 +59,7 @@ private:
|
||||
bool sensorFound = false;
|
||||
|
||||
// Home Assistant and MQTT
|
||||
String mqttLuminanceTopic = F("");
|
||||
String mqttLuminanceTopic;
|
||||
bool mqttInitialized = false;
|
||||
bool HomeAssistantDiscovery = true; // Publish Home Assistant Discovery messages
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ This Usermod is designed to read a `BME280` or `BMP280` sensor and output the fo
|
||||
- Dew Point (`BME280` only)
|
||||
|
||||
Configuration is performed via the Usermod menu. There are no parameters to set in code! The following settings can be configured in the Usermod Menu:
|
||||
- The i2c address in decimal. Set it to either 118 (0x76, the default) or 119 (0x77).
|
||||
- Temperature Decimals (number of decimal places to output)
|
||||
- Humidity Decimals
|
||||
- Pressure Decimals
|
||||
|
||||
@@ -24,6 +24,7 @@ private:
|
||||
uint8_t PressureDecimals = 0; // Number of decimal places in published pressure values
|
||||
uint16_t TemperatureInterval = 5; // Interval to measure temperature (and humidity, dew point if available) in seconds
|
||||
uint16_t PressureInterval = 300; // Interval to measure pressure in seconds
|
||||
BME280I2C::I2CAddr I2CAddress = BME280I2C::I2CAddr_0x76; // i2c address, defaults to 0x76
|
||||
bool PublishAlways = false; // Publish values even when they have not changed
|
||||
bool UseCelsius = true; // Use Celsius for Reporting
|
||||
bool HomeAssistantDiscovery = false; // Publish Home Assistant Device Information
|
||||
@@ -35,20 +36,7 @@ private:
|
||||
#endif
|
||||
bool initDone = false;
|
||||
|
||||
// BME280 sensor settings
|
||||
BME280I2C::Settings settings{
|
||||
BME280::OSR_X16, // Temperature oversampling x16
|
||||
BME280::OSR_X16, // Humidity oversampling x16
|
||||
BME280::OSR_X16, // Pressure oversampling x16
|
||||
// Defaults
|
||||
BME280::Mode_Forced,
|
||||
BME280::StandbyTime_1000ms,
|
||||
BME280::Filter_Off,
|
||||
BME280::SpiEnable_False,
|
||||
BME280I2C::I2CAddr_0x76 // I2C address. I2C specific. Default 0x76
|
||||
};
|
||||
|
||||
BME280I2C bme{settings};
|
||||
BME280I2C bme;
|
||||
|
||||
uint8_t sensorType;
|
||||
|
||||
@@ -181,34 +169,52 @@ private:
|
||||
}
|
||||
}
|
||||
|
||||
void initializeBmeComms()
|
||||
{
|
||||
BME280I2C::Settings settings{
|
||||
BME280::OSR_X16, // Temperature oversampling x16
|
||||
BME280::OSR_X16, // Humidity oversampling x16
|
||||
BME280::OSR_X16, // Pressure oversampling x16
|
||||
BME280::Mode_Forced,
|
||||
BME280::StandbyTime_1000ms,
|
||||
BME280::Filter_Off,
|
||||
BME280::SpiEnable_False,
|
||||
I2CAddress
|
||||
};
|
||||
|
||||
bme.setSettings(settings);
|
||||
|
||||
if (!bme.begin())
|
||||
{
|
||||
sensorType = 0;
|
||||
DEBUG_PRINTLN(F("Could not find BME280 I2C sensor!"));
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (bme.chipModel())
|
||||
{
|
||||
case BME280::ChipModel_BME280:
|
||||
sensorType = 1;
|
||||
DEBUG_PRINTLN(F("Found BME280 sensor! Success."));
|
||||
break;
|
||||
case BME280::ChipModel_BMP280:
|
||||
sensorType = 2;
|
||||
DEBUG_PRINTLN(F("Found BMP280 sensor! No Humidity available."));
|
||||
break;
|
||||
default:
|
||||
sensorType = 0;
|
||||
DEBUG_PRINTLN(F("Found UNKNOWN sensor! Error!"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public:
|
||||
void setup()
|
||||
{
|
||||
if (i2c_scl<0 || i2c_sda<0) { enabled = false; sensorType = 0; return; }
|
||||
|
||||
if (!bme.begin())
|
||||
{
|
||||
sensorType = 0;
|
||||
DEBUG_PRINTLN(F("Could not find BME280 I2C sensor!"));
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (bme.chipModel())
|
||||
{
|
||||
case BME280::ChipModel_BME280:
|
||||
sensorType = 1;
|
||||
DEBUG_PRINTLN(F("Found BME280 sensor! Success."));
|
||||
break;
|
||||
case BME280::ChipModel_BMP280:
|
||||
sensorType = 2;
|
||||
DEBUG_PRINTLN(F("Found BMP280 sensor! No Humidity available."));
|
||||
break;
|
||||
default:
|
||||
sensorType = 0;
|
||||
DEBUG_PRINTLN(F("Found UNKNOWN sensor! Error!"));
|
||||
}
|
||||
}
|
||||
initDone=true;
|
||||
initializeBmeComms();
|
||||
initDone = true;
|
||||
}
|
||||
|
||||
void loop()
|
||||
@@ -365,12 +371,11 @@ public:
|
||||
}
|
||||
else if (sensorType==2) //BMP280
|
||||
{
|
||||
|
||||
JsonArray temperature_json = user.createNestedArray(F("Temperature"));
|
||||
JsonArray pressure_json = user.createNestedArray(F("Pressure"));
|
||||
temperature_json.add(roundf(sensorTemperature * powf(10, TemperatureDecimals)));
|
||||
temperature_json.add(roundf(sensorTemperature * powf(10, TemperatureDecimals)) / powf(10, TemperatureDecimals));
|
||||
temperature_json.add(tempScale);
|
||||
pressure_json.add(roundf(sensorPressure * powf(10, PressureDecimals)));
|
||||
pressure_json.add(roundf(sensorPressure * powf(10, PressureDecimals)) / powf(10, PressureDecimals));
|
||||
pressure_json.add(F("hPa"));
|
||||
}
|
||||
else if (sensorType==1) //BME280
|
||||
@@ -382,9 +387,9 @@ public:
|
||||
JsonArray dewpoint_json = user.createNestedArray(F("Dew Point"));
|
||||
temperature_json.add(roundf(sensorTemperature * powf(10, TemperatureDecimals)) / powf(10, TemperatureDecimals));
|
||||
temperature_json.add(tempScale);
|
||||
humidity_json.add(roundf(sensorHumidity * powf(10, HumidityDecimals)));
|
||||
humidity_json.add(roundf(sensorHumidity * powf(10, HumidityDecimals)) / powf(10, HumidityDecimals));
|
||||
humidity_json.add(F("%"));
|
||||
pressure_json.add(roundf(sensorPressure * powf(10, PressureDecimals)));
|
||||
pressure_json.add(roundf(sensorPressure * powf(10, PressureDecimals)) / powf(10, PressureDecimals));
|
||||
pressure_json.add(F("hPa"));
|
||||
heatindex_json.add(roundf(sensorHeatIndex * powf(10, TemperatureDecimals)) / powf(10, TemperatureDecimals));
|
||||
heatindex_json.add(tempScale);
|
||||
@@ -399,6 +404,7 @@ public:
|
||||
{
|
||||
JsonObject top = root.createNestedObject(FPSTR(_name));
|
||||
top[FPSTR(_enabled)] = enabled;
|
||||
top[F("I2CAddress")] = static_cast<uint8_t>(I2CAddress);
|
||||
top[F("TemperatureDecimals")] = TemperatureDecimals;
|
||||
top[F("HumidityDecimals")] = HumidityDecimals;
|
||||
top[F("PressureDecimals")] = PressureDecimals;
|
||||
@@ -426,6 +432,10 @@ public:
|
||||
|
||||
configComplete &= getJsonValue(top[FPSTR(_enabled)], enabled);
|
||||
// A 3-argument getJsonValue() assigns the 3rd argument as a default value if the Json value is missing
|
||||
uint8_t tmpI2cAddress;
|
||||
configComplete &= getJsonValue(top[F("I2CAddress")], tmpI2cAddress, 0x76);
|
||||
I2CAddress = static_cast<BME280I2C::I2CAddr>(tmpI2cAddress);
|
||||
|
||||
configComplete &= getJsonValue(top[F("TemperatureDecimals")], TemperatureDecimals, 1);
|
||||
configComplete &= getJsonValue(top[F("HumidityDecimals")], HumidityDecimals, 0);
|
||||
configComplete &= getJsonValue(top[F("PressureDecimals")], PressureDecimals, 0);
|
||||
@@ -440,8 +450,23 @@ public:
|
||||
// first run: reading from cfg.json
|
||||
DEBUG_PRINTLN(F(" config loaded."));
|
||||
} else {
|
||||
DEBUG_PRINTLN(F(" config (re)loaded."));
|
||||
// changing parameters from settings page
|
||||
DEBUG_PRINTLN(F(" config (re)loaded."));
|
||||
|
||||
// Reset all known values
|
||||
sensorType = 0;
|
||||
sensorTemperature = 0;
|
||||
sensorHumidity = 0;
|
||||
sensorHeatIndex = 0;
|
||||
sensorDewPoint = 0;
|
||||
sensorPressure = 0;
|
||||
lastTemperature = 0;
|
||||
lastHumidity = 0;
|
||||
lastHeatIndex = 0;
|
||||
lastDewPoint = 0;
|
||||
lastPressure = 0;
|
||||
|
||||
initializeBmeComms();
|
||||
}
|
||||
|
||||
return configComplete;
|
||||
|
||||
BIN
usermods/BME68X_v2/BME680.pdf
Normal file
152
usermods/BME68X_v2/README.md
Normal file
@@ -0,0 +1,152 @@
|
||||
# Usermod BME68X
|
||||
This usermod was developed for a BME680/BME68X sensor. The BME68X is not compatible with the BME280/BMP280 chip. It has its own library. The original 'BSEC Software Library' from Bosch was used to develop the code. The measured values are displayed on the WLED info page.
|
||||
|
||||
<p align="center"><img src="pics/pic1.png" style="width:60%;"></p>
|
||||
|
||||
In addition, the values are published on MQTT if this is active. The topic used for this is: 'wled/[MQTT Client ID]'. The Client ID is set in the WLED MQTT settings.
|
||||
<p align="center"><img src="pics/pic2.png"></p>
|
||||
|
||||
If you use HomeAssistance discovery, the device tree for HomeAssistance is created. This is published under the topic 'homeassistant/sensor/[MQTT Client ID]' via MQTT.
|
||||
<p align="center"><img src="pics/pic3.png"></p>
|
||||
|
||||
A device with the following sensors appears in HomeAssistant. Please note that MQTT must be activated in HomeAssistant.
|
||||
<p align="center"><img src="pics/pic4.png" style="width:60%;"></p>
|
||||
|
||||
|
||||
## Features
|
||||
Raw sensor types
|
||||
|
||||
Sensor Accuracy Scale Range
|
||||
--------------------------------------------------------------------------------------------------
|
||||
Temperature +/- 1.0 °C/°F -40 to 85 °C
|
||||
Humidity +/- 3 % 0 to 100 %
|
||||
Pressure +/- 1 hPa 300 to 1100 hPa
|
||||
Gas Resistance Ohm
|
||||
|
||||
The BSEC Library calculates the following values via the gas resistance
|
||||
|
||||
Sensor Accuracy Scale Range
|
||||
--------------------------------------------------------------------------------------------------
|
||||
IAQ value between 0 and 500
|
||||
Static IAQ same as IAQ but for permanently installed devices
|
||||
CO2 PPM
|
||||
VOC PPM
|
||||
Gas-Percentage %
|
||||
|
||||
|
||||
In addition the usermod calculates
|
||||
|
||||
Sensor Accuracy Scale Range
|
||||
--------------------------------------------------------------------------------------------------
|
||||
Absolute humidity g/m³
|
||||
Dew point °C/°F
|
||||
|
||||
### IAQ (Indoor Air Quality)
|
||||
The IAQ is divided into the following value groups.
|
||||
<p align="center"><img src="pics/pic5.png"></p>
|
||||
|
||||
For more detailed information, please consult the enclosed Bosch product description (BME680.pdf).
|
||||
|
||||
|
||||
## Calibration of the device
|
||||
|
||||
The gas sensor of the BME68X must be calibrated. This differs from the BME280, which does not require any calibration.
|
||||
There is a range of additional information for this, which the driver also provides. These values can be found in HomeAssistant under Diagnostics.
|
||||
|
||||
- **STABILIZATION_STATUS**: Gas sensor stabilization status [boolean] Indicates initial stabilization status of the gas sensor element: stabilization is ongoing (0) or stabilization is finished (1).
|
||||
- **RUN_IN_STATUS**: Gas sensor run-in status [boolean] Indicates power-on stabilization status of the gas sensor element: stabilization is ongoing (0) or stabilization is finished (1)
|
||||
|
||||
Furthermore, all GAS based values have their own accuracy value. These have the following meaning:
|
||||
|
||||
- **Accuracy = 0** means the sensor is being stabilized (this can take a while on the first run)
|
||||
- **Accuracy = 1** means that the previous measured values show too few differences and cannot be used for calibration. If the sensor is at accuracy 1 for too long, you must ensure that the ambient air is chaning. Opening the windows is fine. Or sometimes it is sufficient to breathe on the sensor for approx. 5 minutes.
|
||||
- **Accuracy = 2** means the sensor is currently calibrating.
|
||||
- **Accuracy = 3** means that the sensor has been successfully calibrated. Once accuracy 3 is reached, the calibration data is automatically written to the file system. This calibration data will be used again at the next start and will speed up the calibration.
|
||||
|
||||
The IAQ index is therefore only meaningful if IAQ Accuracy = 3. In addition to the value for IAQ, BSEC also provides us with CO2 and VOC equivalent values. When using the sensor, the calibration value should also always be read out and displayed or transmitted.
|
||||
|
||||
Reasonably reliable values are therefore only achieved when accuracy displays the value 3.
|
||||
|
||||
|
||||
|
||||
## Settings
|
||||
The settings of the usermods are set in the usermod section of wled.
|
||||
<p align="center"><img src="pics/pic6.png"></p>
|
||||
|
||||
The possible settings are
|
||||
|
||||
- **Enable:** Enables / disables the usermod
|
||||
- **I2C address:** I2C address of the sensor. You can choose between 0X77 & 0X76. The default is 0x77.
|
||||
- **Interval:** Specifies the interval of seconds at which the usermod should be executed. The default is every second.
|
||||
- **Pub Chages Only:** If this item is active, the values are only published if they have changed since the last publication.
|
||||
- **Pub Accuracy:** The Accuracy values associated with the gas values are also published.
|
||||
- **Pub Calib State:** If this item is active, STABILIZATION_STATUS& RUN_IN_STATUS are also published.
|
||||
- **Temp Scale:** Here you can choose between °C and °F.
|
||||
- **Temp Offset:** The temperature offset is always set in °C. It must be converted for Fahrenheit.
|
||||
- **HA Discovery:** If this item is active, the HomeAssistant sensor tree is created.
|
||||
- **Pause While WLED Active:** If WLED has many LEDs to calculate, the computing power may no longer be sufficient to calculate the LEDs and read the sensor data. The LEDs then hang for a few microseconds, which can be seen. If this point is active, no sensor data is fetched as long as WLED is running.
|
||||
- **Del Calibration Hist:** If a check mark is set here, the calibration file saved in the file system is deleted when the settings are saved.
|
||||
|
||||
### Sensors
|
||||
Applies to all sensors. The number of decimal places is set here. If the sensor is set to -1, it will no longer be published. In addition, the IAQ values can be activated here in verbal form.
|
||||
|
||||
It is recommended to use the Static IAQ for the IAQ values. This is recommended by Bosch for statically placed devices.
|
||||
|
||||
## Output
|
||||
|
||||
Data is published over MQTT - make sure you've enabled the MQTT sync interface.
|
||||
|
||||
In addition to outputting via MQTT, you can read the values from the Info Screen on the dashboard page of the device's web interface.
|
||||
|
||||
Methods also exist to read the read/calculated values from other WLED modules through code.
|
||||
- getTemperature(); The scale °C/°F is depended to the settings
|
||||
- getHumidity();
|
||||
- getPressure();
|
||||
- getGasResistance();
|
||||
- getAbsoluteHumidity();
|
||||
- getDewPoint(); The scale °C/°F is depended to the settings
|
||||
- getIaq();
|
||||
- getStaticIaq();
|
||||
- getCo2();
|
||||
- getVoc();
|
||||
- getGasPerc();
|
||||
- getIaqAccuracy();
|
||||
- getStaticIaqAccuracy();
|
||||
- getCo2Accuracy();
|
||||
- getVocAccuracy();
|
||||
- getGasPercAccuracy();
|
||||
- getStabStatus();
|
||||
- getRunInStatus();
|
||||
|
||||
|
||||
## Compiling
|
||||
|
||||
To enable, compile with `USERMOD_BME68X` defined (e.g. in `platformio_override.ini`) and add the `BSEC Software Library` to the lib_deps.
|
||||
|
||||
```
|
||||
[env:esp32-BME680]
|
||||
board = esp32dev
|
||||
platform = ${esp32.platform}
|
||||
platform_packages = ${esp32.platform_packages}
|
||||
lib_deps = ${esp32.lib_deps}
|
||||
boschsensortec/BSEC Software Library @ ^1.8.1492 ; USERMOD: BME680
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags_esp32}
|
||||
-D USERMOD_BME68X ; USERMOD: BME680
|
||||
```
|
||||
|
||||
## Revision History
|
||||
### Version 1.0.0
|
||||
- First version of the BME68X_v user module
|
||||
### Version 1.0.1
|
||||
- Rebased to WELD Version 0.15
|
||||
- Reworked some default settings
|
||||
- A problem with the default settings has been fixed
|
||||
|
||||
## Known problems
|
||||
- MQTT goes online at device start. Shortly afterwards it goes offline and takes quite a while until it goes online again. The problem does not come from this user module, but from the WLED core.
|
||||
- If you save the settings often, WLED can get stuck.
|
||||
- If many LEDS are connected to WLED, reading the sensor can cause a small but noticeable hang. The "Pause While WLED Active" option was introduced as a workaround.
|
||||
|
||||
<div><img src="pics/GeoGab.svg" width="20%"/> </div>
|
||||
Gabriel Sieben (gsieben@geogab.net)
|
||||
76
usermods/BME68X_v2/pics/GeoGab.svg
Normal file
@@ -0,0 +1,76 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
xmlns:osb="http://www.openswatchbook.org/uri/2009/osb"
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xml:space="preserve"
|
||||
style="enable-background:new 0 0 595.28 127.56;"
|
||||
viewBox="0 0 600 135"
|
||||
y="0px"
|
||||
x="0px"
|
||||
id="Layer_1"
|
||||
version="1.1"><metadata
|
||||
id="metadata2372"><rdf:RDF><cc:Work
|
||||
rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title></dc:title></cc:Work></rdf:RDF></metadata><defs
|
||||
id="defs2370"><linearGradient
|
||||
osb:paint="solid"
|
||||
id="linearGradient3877"><stop
|
||||
id="stop3875"
|
||||
offset="0"
|
||||
style="stop-color:#808285;stop-opacity:1;" /></linearGradient><clipPath
|
||||
id="clipPath2379"
|
||||
clipPathUnits="userSpaceOnUse"><g
|
||||
style="fill:#808285;fill-opacity:1;fill-rule:nonzero;stroke:#230065;stroke-width:0;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0.99607843"
|
||||
id="use2381"><path
|
||||
style="fill:#808285;fill-opacity:1;fill-rule:nonzero;stroke:#230065;stroke-width:0;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0.99607843"
|
||||
class="st0"
|
||||
d="m 588.34,94.29 c 0,13.28 -10.77,24.04 -24.04,24.04 H 31.38 C 18.1,118.33 7.34,107.57 7.34,94.29 V 32.38 C 7.34,19.1 18.1,8.34 31.38,8.34 h 532.91 c 13.28,0 24.04,10.76 24.04,24.04 V 94.29 Z M 159.44,69.66 c 0,17.15 11.68,19.07 21.89,19.07 h 14.23 c 14.6,0 23.44,-3.2 23.44,-13.87 v -0.91 h -7.84 c -0.45,7.11 -4.47,8.39 -14.32,8.39 h -10.76 c -13.68,0 -18.79,-2.74 -18.79,-13.32 V 66.65 H 219 V 60.9 C 219,44.3 208.88,40.74 194.83,40.74 h -12.59 c -11.12,0 -22.8,1.92 -22.8,18.79 z m 51.72,-9.95 h -43.87 c 0.73,-10.58 3.65,-12.59 16.05,-12.59 h 11.49 c 12.77,0 16.33,4.74 16.33,9.49 z m 18.62,10.13 c 0,15.33 10.86,18.88 25.73,18.88 h 11.22 c 14.87,0 25.72,-3.56 25.72,-18.88 V 59.62 c 0,-15.32 -10.85,-18.88 -25.72,-18.88 h -11.22 c -14.87,0 -25.73,3.56 -25.73,18.88 z m 54.82,-0.46 c 0,10.86 -6.38,12.95 -15.51,12.95 h -15.96 c -9.12,0 -15.51,-2.09 -15.51,-12.95 v -9.31 c 0,-10.85 6.39,-12.95 15.51,-12.95 h 15.96 c 9.12,0 15.51,2.1 15.51,12.95 z m 173.79,18.61 v -31.2 c 0,-13.87 -9.85,-16.06 -24.45,-16.06 h -12.41 c -14.05,0 -19.43,3.47 -19.43,11.95 v 2.28 h 7.84 v -1.64 c 0,-3.83 1.92,-6.2 11.77,-6.2 h 11.49 c 12.04,0 17.33,1.09 17.33,9.49 v 8.76 h -0.18 c -2.74,-4.47 -6.39,-5.56 -16.6,-5.56 H 421.16 C 407.48,59.81 400,61.09 400,71.67 v 3.1 c 0,8.76 3.1,13.96 14.96,13.96 h 18.79 z m -7.84,-12.5 c 0,5.84 -5.47,6.84 -19.7,6.84 h -10.4 c -10.76,0 -12.59,-2.19 -12.59,-7.39 v -1.46 c 0,-5.84 2.83,-7.3 12.95,-7.3 h 12.04 c 12.04,0 17.7,0.82 17.7,7.2 z M 73.6,66.69 h 10.88 l 5.03,0.01 h 48.67 v 2.41 c 0,9.12 -5.47,12.23 -14.41,12.23 H 88.83 c -8.58,0 -15.51,-2.55 -15.51,-14.05 v -0.35 -0.26 z m -9.16,-0.01 c 0,0.06 0,0.14 0,0.2 0.67,14.68 6.68,21.76 23.47,21.76 h 36.85 c 16.51,0 22.35,-6.39 22.35,-24.36 V 59.4 H 89.51 L 85.39,59.39 H 73.32 v -0.01 -16.9 c 0,-11.49 6.93,-14.05 15.51,-14.05 H 112 c 22.07,0 25.81,0.91 25.81,13.23 h 8.39 v -2.37 c 0,-15.23 -12.68,-18.15 -24.54,-18.15 H 87.92 c -17.88,0 -23.53,8.03 -23.53,24.72 V 59.39 L 64.38,59.4 H 44.6 c -11.86,0 -24.54,2.92 -24.54,18.15 v 2.37 5.02 2.37 c 0,15.24 12.68,18.16 24.54,18.16 h 40.79 432.59 34.03 c 17.88,0 23.54,-8.03 23.54,-24.72 V 45.88 c 0,-16.69 -5.65,-24.72 -23.54,-24.72 l -0.16,-0.02 h -223 c -17.88,0 -23.53,8.03 -23.53,24.72 v 18.06 c 0,16.69 5.65,24.72 23.53,24.72 h 36.85 c 16.51,0 22.35,-6.39 22.35,-24.36 V 59.4 h -42.78 v 7.3 h 33.84 v 2.41 c 0,9.12 -5.47,12.23 -14.41,12.23 h -34.94 c -8.58,0 -15.5,-2.55 -15.5,-14.05 V 42.48 c 0,-11.49 6.93,-14.05 15.5,-14.05 l 142.5,0.02 v 61.24 l 24.35,0.73 h 10.95 c 14.23,0 24.18,-3.56 24.18,-19.61 V 62.6 c 0,-14.87 -5.75,-20.16 -24.63,-20.16 h -11.95 -14.88 -0.17 l -0.02,-14.01 h 71.75 l -0.75,0.02 c 8.58,0 15.51,2.55 15.51,14.04 v 41.62 c 0,11.49 -6.93,14.05 -15.51,14.05 H 518.97 86.87 54.27 c -22.08,0 -25.81,-0.91 -25.81,-13.23 v -5.02 c 0,-12.31 3.74,-13.23 25.81,-13.23 h 9.84 z m 459.45,4.04 c 0,9.03 -2.83,13.32 -15.6,13.32 h -12.77 c -11.67,0 -15.42,-4.93 -15.42,-13.41 v -8.85 c 0,-11.13 6.48,-12.95 17.06,-12.95 h 10.58 c 10.76,0 16.14,2.01 16.14,12.77 v 9.12 z"
|
||||
id="path3935" /><path
|
||||
style="opacity:1;fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:#230065;stroke-width:0;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0.99607843"
|
||||
class="st0"
|
||||
d="m 611.07375,-48.387188 c 0,13.28 -10.77,24.039999 -24.04,24.039999 H 54.113747 c -13.27999,0 -24.04,-10.76 -24.04,-24.039999 v -61.910002 c 0,-13.28 10.76001,-24.04 24.04,-24.04 H 587.02375 c 13.28,0 24.04,10.76 24.04,24.04 v 61.910002 z"
|
||||
id="path3937" /></g></clipPath><clipPath
|
||||
id="clipPath2398"
|
||||
clipPathUnits="userSpaceOnUse"><g
|
||||
id="use2400"
|
||||
style="fill:#268298;fill-opacity:1"><g
|
||||
id="g3959"
|
||||
clip-path="url(#clipPath2407)"
|
||||
style="fill:#268298;fill-opacity:1"><g
|
||||
id="g3957"
|
||||
style="fill:#268298;fill-opacity:1"><rect
|
||||
style="opacity:1;fill:#268298;fill-opacity:1;stroke:#000000;stroke-opacity:1"
|
||||
id="rect3955"
|
||||
width="350.98587"
|
||||
height="147.57361"
|
||||
x="95.224861"
|
||||
y="-97.290329" /></g></g></g></clipPath><clipPath
|
||||
id="clipPath2407"
|
||||
clipPathUnits="userSpaceOnUse"><g
|
||||
id="use2409"
|
||||
style="fill:#268298;fill-opacity:1"><rect
|
||||
style="opacity:1;fill:#268298;fill-opacity:1;stroke:#000000;stroke-opacity:1"
|
||||
id="rect3963"
|
||||
width="350.98587"
|
||||
height="147.57361"
|
||||
x="95.224861"
|
||||
y="-97.290329" /></g></clipPath></defs>
|
||||
<style
|
||||
id="style2363"
|
||||
type="text/css">
|
||||
.st0{fill:#808285;}
|
||||
</style>
|
||||
<path
|
||||
style="opacity:1;fill:#ffffff;fill-opacity:0.9859813;fill-rule:nonzero;stroke:#5c7823;stroke-width:0;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0.99607843"
|
||||
class="st0"
|
||||
d="M 600,103.51782 C 600,116.79902 588.8778,127.56 575.17384,127.56 H 24.826163 C 11.111876,127.56 5.1635108e-7,116.79902 5.1635108e-7,103.51782 V 41.602186 C 5.1635108e-7,28.320979 11.111876,17.560001 24.826163,17.560001 H 575.16351 c 13.71429,0 24.82616,10.760978 24.82616,24.042185 v 61.915634 z"
|
||||
id="path2365-0" /><path
|
||||
style="fill:#808285;fill-opacity:1;fill-rule:nonzero;stroke:#230065;stroke-width:0;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0.99607843"
|
||||
class="st0"
|
||||
d="M 600,103.51782 C 600,116.79902 588.8778,127.56 575.17384,127.56 H 24.826162 C 11.111877,127.56 5.1635111e-7,116.79902 5.1635111e-7,103.51782 V 41.602187 C 5.1635111e-7,28.320977 11.111876,17.559997 24.826162,17.559997 H 575.16351 c 13.71429,0 24.82616,10.76098 24.82616,24.04219 V 103.51782 Z M 157.07401,78.885567 c 0,17.15156 12.06196,19.07173 22.60585,19.07173 h 14.69535 c 15.07745,0 24.20654,-3.20029 24.20654,-13.87125 v -0.91009 h -8.09638 c -0.46472,7.11065 -4.61618,8.39076 -14.7883,8.39076 h -11.11188 c -14.12736,0 -19.40447,-2.74024 -19.40447,-13.3212 v -2.37022 h 53.40103 v -5.75052 c 0,-16.60151 -10.45094,-20.16183 -24.96041,-20.16183 h -13.00172 c -11.48365,0 -23.54561,1.92017 -23.54561,18.79171 z m 53.41136,-9.9509 h -45.30465 c 0.75387,-10.58096 3.76936,-12.59114 16.57487,-12.59114 h 11.86575 c 13.18761,0 16.86403,4.74043 16.86403,9.49086 z m 19.22891,10.13092 c 0,15.33139 11.21515,18.88171 26.57143,18.88171 h 11.58692 c 15.35629,0 26.56111,-3.56032 26.56111,-18.88171 v -10.22093 c 0,-15.32139 -11.20482,-18.88171 -26.56111,-18.88171 h -11.58692 c -15.35628,0 -26.57143,3.56032 -26.57143,18.88171 z m 56.61275,-0.46004 c 0,10.86098 -6.58865,12.95117 -16.01722,12.95117 h -16.48193 c -9.41825,0 -16.01721,-2.09019 -16.01721,-12.95117 v -9.31085 c 0,-10.85098 6.59896,-12.95117 16.01721,-12.95117 h 16.48193 c 9.41824,0 16.01722,2.10019 16.01722,12.95117 z m 179.47332,18.61169 v -31.20283 c 0,-13.87126 -10.17212,-16.06146 -25.24957,-16.06146 h -12.81584 c -14.50946,0 -20.0654,3.47031 -20.0654,11.95108 v 2.28021 h 8.09638 v -1.64015 c 0,-3.83035 1.98279,-6.20056 12.15491,-6.20056 h 11.86575 c 12.43373,0 17.89673,1.0901 17.89673,9.49086 v 8.7608 h -0.18589 c -2.8296,-4.47041 -6.59897,-5.56051 -17.14286,-5.56051 h -13.00172 c -14.12736,0 -21.85198,1.28012 -21.85198,11.86108 v 3.10028 c 0,8.76079 3.20138,13.96126 15.44923,13.96126 h 19.40447 z m -8.09639,-12.50114 c 0,5.84053 -5.64888,6.84062 -20.34423,6.84062 h -10.74011 c -11.11187,0 -13.00172,-2.19019 -13.00172,-7.39067 v -1.46013 c 0,-5.84053 2.92255,-7.30066 13.3735,-7.30066 h 12.43373 c 12.43374,0 18.27883,0.82007 18.27883,7.20065 z m -389.27711,-8.8008 h 11.2358 l 5.194492,0.01 h 50.261618 v 2.41021 c 0,9.12083 -5.64888,12.23111 -14.88124,12.23111 H 84.154905 c -8.860585,0 -16.017212,-2.55023 -16.017212,-14.05127 v -0.35003 -0.26003 z m -9.459552,-0.01 c 0,0.06 0,0.14002 0,0.20002 0.69191,14.68133 6.898451,21.76198 24.237521,21.76198 h 38.055071 c 17.04992,0 23.0809,-6.39058 23.0809,-24.36221 v -4.88045 H 84.857142 l -4.254733,-0.01 H 68.137693 v -0.01 -16.90153 c 0,-11.49104 7.156627,-14.05129 16.017212,-14.05129 h 23.927705 c 22.79174,0 26.65405,0.91009 26.65405,13.23121 h 8.66437 v -2.37021 c 0,-15.23139 -13.09466,-18.15166 -25.34251,-18.15166 H 83.215146 c -18.464717,0 -24.299483,8.03073 -24.299483,24.72226 v 13.53122 l -0.01033,0.01 h -20.42685 c -12.247849,0 -25.342513,2.92027 -25.342513,18.15165 v 2.37022 5.02045 2.37022 c 0,15.241393 13.094664,18.161653 25.342513,18.161653 h 42.123923 446.736664 35.14286 c 18.46471,0 24.30981,-8.03073 24.30981,-24.722253 v -34.87316 c 0,-16.69153 -5.83477,-24.72226 -24.30981,-24.72226 l -0.16523,-0.02 H 332.0241 c -18.46471,0 -24.29948,8.03073 -24.29948,24.72226 v 18.06163 c 0,16.69152 5.83477,24.72225 24.29948,24.72225 h 38.05508 c 17.04991,0 23.08089,-6.39058 23.08089,-24.36221 v -4.88045 h -44.179 v 7.30067 h 34.94664 v 2.41021 c 0,9.12083 -5.64888,12.23111 -14.88123,12.23111 h -36.08262 c -8.86059,0 -16.00688,-2.55023 -16.00688,-14.05127 v -24.81225 c 0,-11.49104 7.15662,-14.05129 16.00688,-14.05129 l 147.16007,0.02 v 61.24556 l 25.14629,0.73007 h 11.30809 c 14.69536,0 24.97074,-3.56033 24.97074,-19.61178 v -8.21075 c 0,-14.87135 -5.93803,-20.16183 -25.43545,-20.16183 h -12.34079 -15.36661 -0.17556 l -0.0207,-14.01128 h 74.09639 l -0.77453,0.02 c 8.86059,0 16.01721,2.55024 16.01721,14.04128 v 41.62378 c 0,11.491053 -7.15662,14.051283 -16.01721,14.051283 H 528.36145 82.130808 48.464716 c -22.802065,0 -26.654044,-0.91008 -26.654044,-13.231213 v -5.02046 c 0,-12.31111 3.862306,-13.2312 26.654044,-13.2312 h 10.161789 z m 474.475042,4.04037 c 0,9.03082 -2.92255,13.32121 -16.11015,13.32121 h -13.18761 c -12.05164,0 -15.92427,-4.93045 -15.92427,-13.41122 v -8.8508 c 0,-11.13101 6.69191,-12.95118 17.6179,-12.95118 h 10.92599 c 11.11188,0 16.66781,2.01019 16.66781,12.77116 v 9.12083 z"
|
||||
id="path2365" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 11 KiB |
BIN
usermods/BME68X_v2/pics/pic1.png
Normal file
|
After Width: | Height: | Size: 135 KiB |
BIN
usermods/BME68X_v2/pics/pic2.png
Normal file
|
After Width: | Height: | Size: 23 KiB |
BIN
usermods/BME68X_v2/pics/pic3.png
Normal file
|
After Width: | Height: | Size: 44 KiB |
BIN
usermods/BME68X_v2/pics/pic4.png
Normal file
|
After Width: | Height: | Size: 134 KiB |
BIN
usermods/BME68X_v2/pics/pic5.png
Normal file
|
After Width: | Height: | Size: 14 KiB |
BIN
usermods/BME68X_v2/pics/pic6.png
Normal file
|
After Width: | Height: | Size: 35 KiB |
1114
usermods/BME68X_v2/usermod_bme68x.h
Normal file
160
usermods/Battery/UMBattery.h
Normal file
@@ -0,0 +1,160 @@
|
||||
#ifndef UMBBattery_h
|
||||
#define UMBBattery_h
|
||||
|
||||
#include "battery_defaults.h"
|
||||
|
||||
/**
|
||||
* Battery base class
|
||||
* all other battery classes should inherit from this
|
||||
*/
|
||||
class UMBattery
|
||||
{
|
||||
private:
|
||||
|
||||
protected:
|
||||
float minVoltage;
|
||||
float maxVoltage;
|
||||
float voltage;
|
||||
int8_t level = 100;
|
||||
float calibration; // offset or calibration value to fine tune the calculated voltage
|
||||
float voltageMultiplier; // ratio for the voltage divider
|
||||
|
||||
float linearMapping(float v, float min, float max, float oMin = 0.0f, float oMax = 100.0f)
|
||||
{
|
||||
return (v-min) * (oMax-oMin) / (max-min) + oMin;
|
||||
}
|
||||
|
||||
public:
|
||||
UMBattery()
|
||||
{
|
||||
this->setVoltageMultiplier(USERMOD_BATTERY_VOLTAGE_MULTIPLIER);
|
||||
this->setCalibration(USERMOD_BATTERY_CALIBRATION);
|
||||
}
|
||||
|
||||
virtual void update(batteryConfig cfg)
|
||||
{
|
||||
if(cfg.minVoltage) this->setMinVoltage(cfg.minVoltage);
|
||||
if(cfg.maxVoltage) this->setMaxVoltage(cfg.maxVoltage);
|
||||
if(cfg.level) this->setLevel(cfg.level);
|
||||
if(cfg.calibration) this->setCalibration(cfg.calibration);
|
||||
if(cfg.voltageMultiplier) this->setVoltageMultiplier(cfg.voltageMultiplier);
|
||||
}
|
||||
|
||||
/**
|
||||
* Corresponding battery curves
|
||||
* calculates the level in % (0-100) with given voltage and possible voltage range
|
||||
*/
|
||||
virtual float mapVoltage(float v, float min, float max) = 0;
|
||||
// {
|
||||
// example implementation, linear mapping
|
||||
// return (v-min) * 100 / (max-min);
|
||||
// };
|
||||
|
||||
virtual void calculateAndSetLevel(float voltage) = 0;
|
||||
|
||||
|
||||
|
||||
/*
|
||||
*
|
||||
* Getter and Setter
|
||||
*
|
||||
*/
|
||||
|
||||
/*
|
||||
* Get lowest configured battery voltage
|
||||
*/
|
||||
virtual float getMinVoltage()
|
||||
{
|
||||
return this->minVoltage;
|
||||
}
|
||||
|
||||
/*
|
||||
* Set lowest battery voltage
|
||||
* can't be below 0 volt
|
||||
*/
|
||||
virtual void setMinVoltage(float voltage)
|
||||
{
|
||||
this->minVoltage = max(0.0f, voltage);
|
||||
}
|
||||
|
||||
/*
|
||||
* Get highest configured battery voltage
|
||||
*/
|
||||
virtual float getMaxVoltage()
|
||||
{
|
||||
return this->maxVoltage;
|
||||
}
|
||||
|
||||
/*
|
||||
* Set highest battery voltage
|
||||
* can't be below minVoltage
|
||||
*/
|
||||
virtual void setMaxVoltage(float voltage)
|
||||
{
|
||||
this->maxVoltage = max(getMinVoltage()+.5f, voltage);
|
||||
}
|
||||
|
||||
float getVoltage()
|
||||
{
|
||||
return this->voltage;
|
||||
}
|
||||
|
||||
/**
|
||||
* check if voltage is within specified voltage range, allow 10% over/under voltage
|
||||
*/
|
||||
void setVoltage(float voltage)
|
||||
{
|
||||
// this->voltage = ( (voltage < this->getMinVoltage() * 0.85f) || (voltage > this->getMaxVoltage() * 1.1f) )
|
||||
// ? -1.0f
|
||||
// : voltage;
|
||||
this->voltage = voltage;
|
||||
}
|
||||
|
||||
float getLevel()
|
||||
{
|
||||
return this->level;
|
||||
}
|
||||
|
||||
void setLevel(float level)
|
||||
{
|
||||
this->level = constrain(level, 0.0f, 110.0f);
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the configured calibration value
|
||||
* a offset value to fine-tune the calculated voltage.
|
||||
*/
|
||||
virtual float getCalibration()
|
||||
{
|
||||
return calibration;
|
||||
}
|
||||
|
||||
/*
|
||||
* Set the voltage calibration offset value
|
||||
* a offset value to fine-tune the calculated voltage.
|
||||
*/
|
||||
virtual void setCalibration(float offset)
|
||||
{
|
||||
calibration = offset;
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the configured calibration value
|
||||
* a value to set the voltage divider ratio
|
||||
*/
|
||||
virtual float getVoltageMultiplier()
|
||||
{
|
||||
return voltageMultiplier;
|
||||
}
|
||||
|
||||
/*
|
||||
* Set the voltage multiplier value
|
||||
* a value to set the voltage divider ratio.
|
||||
*/
|
||||
virtual void setVoltageMultiplier(float multiplier)
|
||||
{
|
||||
voltageMultiplier = multiplier;
|
||||
}
|
||||
};
|
||||
|
||||
#endif
|
||||
BIN
usermods/Battery/assets/battery_connection_schematic_esp32.png
Normal file
|
After Width: | Height: | Size: 129 KiB |
|
After Width: | Height: | Size: 64 KiB |
BIN
usermods/Battery/assets/installation_my_config_h.png
Normal file
|
After Width: | Height: | Size: 49 KiB |
BIN
usermods/Battery/assets/installation_platformio_override_ini.png
Normal file
|
After Width: | Height: | Size: 54 KiB |
@@ -1,3 +1,8 @@
|
||||
#ifndef UMBDefaults_h
|
||||
#define UMBDefaults_h
|
||||
|
||||
#include "wled.h"
|
||||
|
||||
// pin defaults
|
||||
// for the esp32 it is best to use the ADC1: GPIO32 - GPIO39
|
||||
// https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/adc.html
|
||||
@@ -9,24 +14,66 @@
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// The initial delay before the first battery voltage reading after power-on.
|
||||
// This allows the voltage to stabilize before readings are taken, improving accuracy of initial reading.
|
||||
#ifndef USERMOD_BATTERY_INITIAL_DELAY
|
||||
#define USERMOD_BATTERY_INITIAL_DELAY 10000 // (milliseconds)
|
||||
#endif
|
||||
|
||||
// the frequency to check the battery, 30 sec
|
||||
#ifndef USERMOD_BATTERY_MEASUREMENT_INTERVAL
|
||||
#define USERMOD_BATTERY_MEASUREMENT_INTERVAL 30000
|
||||
#endif
|
||||
|
||||
// default for 18650 battery
|
||||
// https://batterybro.com/blogs/18650-wholesale-battery-reviews/18852515-when-to-recycle-18650-batteries-and-how-to-start-a-collection-center-in-your-vape-shop
|
||||
// Discharge voltage: 2.5 volt + .1 for personal safety
|
||||
#ifndef USERMOD_BATTERY_MIN_VOLTAGE
|
||||
#ifdef USERMOD_BATTERY_USE_LIPO
|
||||
// LiPo "1S" Batteries should not be dischared below 3V !!
|
||||
#define USERMOD_BATTERY_MIN_VOLTAGE 3.2f
|
||||
#else
|
||||
#define USERMOD_BATTERY_MIN_VOLTAGE 2.6f
|
||||
#endif
|
||||
|
||||
/* Default Battery Type
|
||||
* 0 = unkown
|
||||
* 1 = Lipo
|
||||
* 2 = Lion
|
||||
*/
|
||||
#ifndef USERMOD_BATTERY_DEFAULT_TYPE
|
||||
#define USERMOD_BATTERY_DEFAULT_TYPE 0
|
||||
#endif
|
||||
/*
|
||||
*
|
||||
* Unkown 'Battery' defaults
|
||||
*
|
||||
*/
|
||||
#ifndef USERMOD_BATTERY_UNKOWN_MIN_VOLTAGE
|
||||
// Extra save defaults
|
||||
#define USERMOD_BATTERY_UNKOWN_MIN_VOLTAGE 3.3f
|
||||
#endif
|
||||
#ifndef USERMOD_BATTERY_UNKOWN_MAX_VOLTAGE
|
||||
#define USERMOD_BATTERY_UNKOWN_MAX_VOLTAGE 4.2f
|
||||
#endif
|
||||
|
||||
//the default ratio for the voltage divider
|
||||
/*
|
||||
*
|
||||
* Lithium polymer (Li-Po) defaults
|
||||
*
|
||||
*/
|
||||
#ifndef USERMOD_BATTERY_LIPO_MIN_VOLTAGE
|
||||
// LiPo "1S" Batteries should not be dischared below 3V !!
|
||||
#define USERMOD_BATTERY_LIPO_MIN_VOLTAGE 3.2f
|
||||
#endif
|
||||
#ifndef USERMOD_BATTERY_LIPO_MAX_VOLTAGE
|
||||
#define USERMOD_BATTERY_LIPO_MAX_VOLTAGE 4.2f
|
||||
#endif
|
||||
|
||||
/*
|
||||
*
|
||||
* Lithium-ion (Li-Ion) defaults
|
||||
*
|
||||
*/
|
||||
#ifndef USERMOD_BATTERY_LION_MIN_VOLTAGE
|
||||
// default for 18650 battery
|
||||
#define USERMOD_BATTERY_LION_MIN_VOLTAGE 2.6f
|
||||
#endif
|
||||
#ifndef USERMOD_BATTERY_LION_MAX_VOLTAGE
|
||||
#define USERMOD_BATTERY_LION_MAX_VOLTAGE 4.2f
|
||||
#endif
|
||||
|
||||
// the default ratio for the voltage divider
|
||||
#ifndef USERMOD_BATTERY_VOLTAGE_MULTIPLIER
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
#define USERMOD_BATTERY_VOLTAGE_MULTIPLIER 2.0f
|
||||
@@ -35,13 +82,8 @@
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef USERMOD_BATTERY_MAX_VOLTAGE
|
||||
#define USERMOD_BATTERY_MAX_VOLTAGE 4.2f
|
||||
#endif
|
||||
|
||||
// a common capacity for single 18650 battery cells is between 2500 and 3600 mAh
|
||||
#ifndef USERMOD_BATTERY_TOTAL_CAPACITY
|
||||
#define USERMOD_BATTERY_TOTAL_CAPACITY 3100
|
||||
#ifndef USERMOD_BATTERY_AVERAGING_ALPHA
|
||||
#define USERMOD_BATTERY_AVERAGING_ALPHA 0.1f
|
||||
#endif
|
||||
|
||||
// offset or calibration value to fine tune the calculated voltage
|
||||
@@ -49,11 +91,6 @@
|
||||
#define USERMOD_BATTERY_CALIBRATION 0
|
||||
#endif
|
||||
|
||||
// calculate remaining time / the time that is left before the battery runs out of power
|
||||
// #ifndef USERMOD_BATTERY_CALCULATE_TIME_LEFT_ENABLED
|
||||
// #define USERMOD_BATTERY_CALCULATE_TIME_LEFT_ENABLED false
|
||||
// #endif
|
||||
|
||||
// auto-off feature
|
||||
#ifndef USERMOD_BATTERY_AUTO_OFF_ENABLED
|
||||
#define USERMOD_BATTERY_AUTO_OFF_ENABLED true
|
||||
@@ -78,4 +115,26 @@
|
||||
|
||||
#ifndef USERMOD_BATTERY_LOW_POWER_INDICATOR_DURATION
|
||||
#define USERMOD_BATTERY_LOW_POWER_INDICATOR_DURATION 5
|
||||
#endif
|
||||
|
||||
// battery types
|
||||
typedef enum
|
||||
{
|
||||
unknown=0,
|
||||
lipo=1,
|
||||
lion=2
|
||||
} batteryType;
|
||||
|
||||
// used for initial configuration after boot
|
||||
typedef struct bconfig_t
|
||||
{
|
||||
batteryType type;
|
||||
float minVoltage;
|
||||
float maxVoltage;
|
||||
float voltage; // current voltage
|
||||
int8_t level; // current level
|
||||
float calibration; // offset or calibration value to fine tune the calculated voltage
|
||||
float voltageMultiplier;
|
||||
} batteryConfig;
|
||||
|
||||
#endif
|
||||
@@ -6,105 +6,171 @@
|
||||
|
||||
Enables battery level monitoring of your project.
|
||||
|
||||
For this to work, the positive side of the (18650) battery must be connected to pin `A0` of the d1 mini/esp8266 with a 100k Ohm resistor (see [Useful Links](#useful-links)).
|
||||
|
||||
If you have an ESP32 board, connect the positive side of the battery to ADC1 (GPIO32 - GPIO39)
|
||||
|
||||
<p align="center">
|
||||
<img width="500" src="assets/battery_info_screen.png">
|
||||
<p align="left">
|
||||
<img width="700" src="assets/battery_info_screen.png">
|
||||
</p>
|
||||
|
||||
<br>
|
||||
|
||||
## ⚙️ Features
|
||||
|
||||
- 💯 Displays current battery voltage
|
||||
- 💯 Displays current battery voltage
|
||||
- 🚥 Displays battery level
|
||||
- 🚫 Auto-off with configurable Threshold
|
||||
- 🚫 Auto-off with configurable threshold
|
||||
- 🚨 Low power indicator with many configuration possibilities
|
||||
|
||||
<br><br>
|
||||
|
||||
## 🎈 Installation
|
||||
|
||||
define `USERMOD_BATTERY` in `wled00/my_config.h`
|
||||
| **Option 1** | **Option 2** |
|
||||
|--------------|--------------|
|
||||
| In `wled00/my_config.h`<br>Add the line: `#define USERMOD_BATTERY`<br><br>[Example: my_config.h](assets/installation_my_config_h.png) | In `platformio_override.ini` (or `platformio.ini`)<br>Under: `build_flags =`, add the line: `-D USERMOD_BATTERY`<br><br>[Example: platformio_override.ini](assets/installation_platformio_override_ini.png) |
|
||||
|
||||
### Example wiring
|
||||
<br><br>
|
||||
|
||||
<p align="center">
|
||||
<img width="300" src="assets/battery_connection_schematic_01.png">
|
||||
</p>
|
||||
## 🔌 Example wiring
|
||||
|
||||
### Define Your Options
|
||||
- (see [Useful Links](#useful-links)).
|
||||
|
||||
<table style="width: 100%; table-layout: fixed;">
|
||||
<tr>
|
||||
<!-- Column for the first image -->
|
||||
<td style="width: 50%; vertical-align: bottom;">
|
||||
<img width="300" src="assets/battery_connection_schematic_01.png" style="display: block;">
|
||||
<p><strong>ESP8266</strong><br>
|
||||
With a 100k Ohm resistor, connect the positive<br>
|
||||
side of the battery to pin `A0`.</p>
|
||||
</td>
|
||||
<!-- Column for the second image -->
|
||||
<td style="width: 50%; vertical-align: bottom;">
|
||||
<img width="250" src="assets/battery_connection_schematic_esp32.png" style="display: block;">
|
||||
<p><strong>ESP32</strong> (+S2, S3, C3 etc...)<br>
|
||||
Use a voltage divider (two resistors of equal value).<br>
|
||||
Connect to ADC1 (GPIO32 - GPIO39). GPIO35 is Default.</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<br><br>
|
||||
|
||||
## Define Your Options
|
||||
|
||||
| Name | Unit | Description |
|
||||
| ----------------------------------------------- | ----------- |-------------------------------------------------------------------------------------- |
|
||||
| `USERMOD_BATTERY` | | define this (in `my_config.h`) to have this usermod included wled00\usermods_list.cpp |
|
||||
| `USERMOD_BATTERY_USE_LIPO` | | define this (in `my_config.h`) if you use LiPo rechargeables (1S) |
|
||||
| `USERMOD_BATTERY_MEASUREMENT_PIN` | | defaults to A0 on ESP8266 and GPIO35 on ESP32 |
|
||||
| `USERMOD_BATTERY_MEASUREMENT_INTERVAL` | ms | battery check interval. defaults to 30 seconds |
|
||||
| `USERMOD_BATTERY_MIN_VOLTAGE` | v | minimum battery voltage. default is 2.6 (18650 battery standard) |
|
||||
| `USERMOD_BATTERY_MAX_VOLTAGE` | v | maximum battery voltage. default is 4.2 (18650 battery standard) |
|
||||
| `USERMOD_BATTERY_TOTAL_CAPACITY` | mAh | the capacity of all cells in parallel summed up |
|
||||
| `USERMOD_BATTERY_CALIBRATION` | | offset / calibration number, fine tune the measured voltage by the microcontroller |
|
||||
| `USERMOD_BATTERY` | | Define this (in `my_config.h`) to have this usermod included wled00\usermods_list.cpp |
|
||||
| `USERMOD_BATTERY_MEASUREMENT_PIN` | | Defaults to A0 on ESP8266 and GPIO35 on ESP32 |
|
||||
| `USERMOD_BATTERY_MEASUREMENT_INTERVAL` | ms | Battery check interval. defaults to 30 seconds |
|
||||
| `USERMOD_BATTERY_INITIAL_DELAY` | ms | Delay before initial reading. defaults to 10 seconds to allow voltage stabilization |
|
||||
| `USERMOD_BATTERY_{TYPE}_MIN_VOLTAGE` | v | Minimum battery voltage. default is 2.6 (18650 battery standard) |
|
||||
| `USERMOD_BATTERY_{TYPE}_MAX_VOLTAGE` | v | Maximum battery voltage. default is 4.2 (18650 battery standard) |
|
||||
| `USERMOD_BATTERY_{TYPE}_TOTAL_CAPACITY` | mAh | The capacity of all cells in parallel summed up |
|
||||
| `USERMOD_BATTERY_{TYPE}_CALIBRATION` | | Offset / calibration number, fine tune the measured voltage by the microcontroller |
|
||||
| Auto-Off | --- | --- |
|
||||
| `USERMOD_BATTERY_AUTO_OFF_ENABLED` | true/false | enables auto-off |
|
||||
| `USERMOD_BATTERY_AUTO_OFF_THRESHOLD` | % (0-100) | when this threshold is reached master power turns off |
|
||||
| `USERMOD_BATTERY_AUTO_OFF_ENABLED` | true/false | Enables auto-off |
|
||||
| `USERMOD_BATTERY_AUTO_OFF_THRESHOLD` | % (0-100) | When this threshold is reached master power turns off |
|
||||
| Low-Power-Indicator | --- | --- |
|
||||
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_ENABLED` | true/false | enables low power indication |
|
||||
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_PRESET` | preset id | when low power is detected then use this preset to indicate low power |
|
||||
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_THRESHOLD` | % (0-100) | when this threshold is reached low power gets indicated |
|
||||
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_DURATION` | seconds | for this long the configured preset is played |
|
||||
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_ENABLED` | true/false | Enables low power indication |
|
||||
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_PRESET` | preset id | When low power is detected then use this preset to indicate low power |
|
||||
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_THRESHOLD` | % (0-100) | When this threshold is reached low power gets indicated |
|
||||
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_DURATION` | seconds | For this long the configured preset is played |
|
||||
|
||||
All parameters can be configured at runtime via the Usermods settings page.
|
||||
|
||||
<br>
|
||||
|
||||
**NOTICE:** Each Battery type can be pre-configured individualy (in `my_config.h`)
|
||||
|
||||
| Name | Alias | `my_config.h` example |
|
||||
| --------------- | ------------- | ------------------------------------- |
|
||||
| Lithium Polymer | lipo (Li-Po) | `USERMOD_BATTERY_lipo_MIN_VOLTAGE` |
|
||||
| Lithium Ionen | lion (Li-Ion) | `USERMOD_BATTERY_lion_TOTAL_CAPACITY` |
|
||||
|
||||
<br><br>
|
||||
|
||||
## 🔧 Calibration
|
||||
|
||||
The calibration number is a value that is added to the final computed voltage after it has been scaled by the voltage multiplier.
|
||||
|
||||
It fine-tunes the voltage reading so that it more closely matches the actual battery voltage, compensating for inaccuracies inherent in the voltage divider resistors or the ESP's ADC measurements.
|
||||
|
||||
Set calibration either in the Usermods settings page or at compile time in `my_config.h` or `platformio_override.ini`.
|
||||
|
||||
It can be either a positive or negative number.
|
||||
|
||||
<br><br>
|
||||
|
||||
## ⚠️ Important
|
||||
|
||||
- Make sure you know your battery specifications! All batteries are **NOT** the same!
|
||||
- Example:
|
||||
Make sure you know your battery specifications! All batteries are **NOT** the same!
|
||||
|
||||
| Your battery specification table | | Options you can define |
|
||||
| :-------------------------------- |:--------------- | :---------------------------- |
|
||||
| Capacity | 3500mAh 12,5 Wh | |
|
||||
| Minimum capacity | 3350mAh 11,9 Wh | |
|
||||
Example:
|
||||
|
||||
| Your battery specification table | | Options you can define |
|
||||
| --------------------------------- | --------------- | ----------------------------- |
|
||||
| Capacity | 3500mAh 12.5Wh | |
|
||||
| Minimum capacity | 3350mAh 11.9Wh | |
|
||||
| Rated voltage | 3.6V - 3.7V | |
|
||||
| **Charging end voltage** | **4,2V ± 0,05** | `USERMOD_BATTERY_MAX_VOLTAGE` |
|
||||
| **Discharge voltage** | **2,5V** | `USERMOD_BATTERY_MIN_VOLTAGE` |
|
||||
| **Charging end voltage** | **4.2V ± 0.05** | `USERMOD_BATTERY_MAX_VOLTAGE` |
|
||||
| **Discharge voltage** | **2.5V** | `USERMOD_BATTERY_MIN_VOLTAGE` |
|
||||
| Max. discharge current (constant) | 10A (10000mA) | |
|
||||
| max. charging current | 1.7A (1700mA) | |
|
||||
| ... | ... | ... |
|
||||
| .. | .. | .. |
|
||||
|
||||
Specification from: [Molicel INR18650-M35A, 3500mAh 10A Lithium-ion battery, 3.6V - 3.7V](https://www.akkuteile.de/lithium-ionen-akkus/18650/molicel/molicel-inr18650-m35a-3500mah-10a-lithium-ionen-akku-3-6v-3-7v_100833)
|
||||
Specification from: [Molicel INR18650-M35A, 3500mAh 10A Lithium-ion battery, 3.6V - 3.7V](https://www.akkuteile.de/lithium-ionen-akkus/18650/molicel/molicel-inr18650-m35a-3500mah-10a-lithium-ionen-akku-3-6v-3-7v_100833)
|
||||
|
||||
<br><br>
|
||||
|
||||
## 🌐 Useful Links
|
||||
|
||||
- https://lazyzero.de/elektronik/esp8266/wemos_d1_mini_a0/start
|
||||
- https://arduinodiy.wordpress.com/2016/12/25/monitoring-lipo-battery-voltage-with-wemos-d1-minibattery-shield-and-thingspeak/
|
||||
|
||||
<br><br>
|
||||
|
||||
## 📝 Change Log
|
||||
|
||||
2024-08-19
|
||||
|
||||
- Improved MQTT support
|
||||
- Added battery percentage & battery voltage as MQTT topic
|
||||
|
||||
2024-05-11
|
||||
|
||||
- Documentation updated
|
||||
|
||||
2024-04-30
|
||||
|
||||
- Integrate factory pattern to make it easier to add other / custom battery types
|
||||
- Update readme
|
||||
- Improved initial reading accuracy by delaying initial measurement to allow voltage to stabilize at power-on
|
||||
|
||||
2023-01-04
|
||||
|
||||
- basic support for LiPo rechargeable batteries ( `-D USERMOD_BATTERY_USE_LIPO`)
|
||||
- improved support for esp32 (read calibrated voltage)
|
||||
- corrected config saving (measurement pin, and battery min/max were lost)
|
||||
- various bugfixes
|
||||
- Basic support for LiPo rechargeable batteries (`-D USERMOD_BATTERY_USE_LIPO`)
|
||||
- Improved support for ESP32 (read calibrated voltage)
|
||||
- Corrected config saving (measurement pin, and battery min/max were lost)
|
||||
- Various bugfixes
|
||||
|
||||
2022-12-25
|
||||
|
||||
- added "auto-off" feature
|
||||
- added "low-power-indication" feature
|
||||
- added "calibration/offset" field to configuration page
|
||||
- added getter and setter, so that user usermods could interact with this one
|
||||
- update readme (added new options, made it markdownlint compliant)
|
||||
- Added "auto-off" feature
|
||||
- Added "low-power-indication" feature
|
||||
- Added "calibration/offset" field to configuration page
|
||||
- Added getter and setter, so that user usermods could interact with this one
|
||||
- Update readme (added new options, made it markdownlint compliant)
|
||||
|
||||
2021-09-02
|
||||
|
||||
- added "Battery voltage" to info
|
||||
- added circuit diagram to readme
|
||||
- added MQTT support, sending battery voltage
|
||||
- minor fixes
|
||||
- Added "Battery voltage" to info
|
||||
- Added circuit diagram to readme
|
||||
- Added MQTT support, sending battery voltage
|
||||
- Minor fixes
|
||||
|
||||
2021-08-15
|
||||
|
||||
- changed `USERMOD_BATTERY_MIN_VOLTAGE` to 2.6 volt as default for 18650 batteries
|
||||
- Changed `USERMOD_BATTERY_MIN_VOLTAGE` to 2.6 volt as default for 18650 batteries
|
||||
- Updated readme, added specification table
|
||||
|
||||
2021-08-10
|
||||
|
||||
38
usermods/Battery/types/LionUMBattery.h
Normal file
@@ -0,0 +1,38 @@
|
||||
#ifndef UMBLion_h
|
||||
#define UMBLion_h
|
||||
|
||||
#include "../battery_defaults.h"
|
||||
#include "../UMBattery.h"
|
||||
|
||||
/**
|
||||
* LiOn Battery
|
||||
*
|
||||
*/
|
||||
class LionUMBattery : public UMBattery
|
||||
{
|
||||
private:
|
||||
|
||||
public:
|
||||
LionUMBattery() : UMBattery()
|
||||
{
|
||||
this->setMinVoltage(USERMOD_BATTERY_LION_MIN_VOLTAGE);
|
||||
this->setMaxVoltage(USERMOD_BATTERY_LION_MAX_VOLTAGE);
|
||||
}
|
||||
|
||||
float mapVoltage(float v, float min, float max) override
|
||||
{
|
||||
return this->linearMapping(v, min, max); // basic mapping
|
||||
};
|
||||
|
||||
void calculateAndSetLevel(float voltage) override
|
||||
{
|
||||
this->setLevel(this->mapVoltage(voltage, this->getMinVoltage(), this->getMaxVoltage()));
|
||||
};
|
||||
|
||||
virtual void setMaxVoltage(float voltage) override
|
||||
{
|
||||
this->maxVoltage = max(getMinVoltage()+1.0f, voltage);
|
||||
}
|
||||
};
|
||||
|
||||
#endif
|
||||
54
usermods/Battery/types/LipoUMBattery.h
Normal file
@@ -0,0 +1,54 @@
|
||||
#ifndef UMBLipo_h
|
||||
#define UMBLipo_h
|
||||
|
||||
#include "../battery_defaults.h"
|
||||
#include "../UMBattery.h"
|
||||
|
||||
/**
|
||||
* LiPo Battery
|
||||
*
|
||||
*/
|
||||
class LipoUMBattery : public UMBattery
|
||||
{
|
||||
private:
|
||||
|
||||
public:
|
||||
LipoUMBattery() : UMBattery()
|
||||
{
|
||||
this->setMinVoltage(USERMOD_BATTERY_LIPO_MIN_VOLTAGE);
|
||||
this->setMaxVoltage(USERMOD_BATTERY_LIPO_MAX_VOLTAGE);
|
||||
}
|
||||
|
||||
/**
|
||||
* LiPo batteries have a differnt discharge curve, see
|
||||
* https://blog.ampow.com/lipo-voltage-chart/
|
||||
*/
|
||||
float mapVoltage(float v, float min, float max) override
|
||||
{
|
||||
float lvl = 0.0f;
|
||||
lvl = this->linearMapping(v, min, max); // basic mapping
|
||||
|
||||
if (lvl < 40.0f)
|
||||
lvl = this->linearMapping(lvl, 0, 40, 0, 12); // last 45% -> drops very quickly
|
||||
else {
|
||||
if (lvl < 90.0f)
|
||||
lvl = this->linearMapping(lvl, 40, 90, 12, 95); // 90% ... 40% -> almost linear drop
|
||||
else // level > 90%
|
||||
lvl = this->linearMapping(lvl, 90, 105, 95, 100); // highest 15% -> drop slowly
|
||||
}
|
||||
|
||||
return lvl;
|
||||
};
|
||||
|
||||
void calculateAndSetLevel(float voltage) override
|
||||
{
|
||||
this->setLevel(this->mapVoltage(voltage, this->getMinVoltage(), this->getMaxVoltage()));
|
||||
};
|
||||
|
||||
virtual void setMaxVoltage(float voltage) override
|
||||
{
|
||||
this->maxVoltage = max(getMinVoltage()+0.7f, voltage);
|
||||
}
|
||||
};
|
||||
|
||||
#endif
|
||||
39
usermods/Battery/types/UnkownUMBattery.h
Normal file
@@ -0,0 +1,39 @@
|
||||
#ifndef UMBUnkown_h
|
||||
#define UMBUnkown_h
|
||||
|
||||
#include "../battery_defaults.h"
|
||||
#include "../UMBattery.h"
|
||||
|
||||
/**
|
||||
* Unkown / Default Battery
|
||||
*
|
||||
*/
|
||||
class UnkownUMBattery : public UMBattery
|
||||
{
|
||||
private:
|
||||
|
||||
public:
|
||||
UnkownUMBattery() : UMBattery()
|
||||
{
|
||||
this->setMinVoltage(USERMOD_BATTERY_UNKOWN_MIN_VOLTAGE);
|
||||
this->setMaxVoltage(USERMOD_BATTERY_UNKOWN_MAX_VOLTAGE);
|
||||
}
|
||||
|
||||
void update(batteryConfig cfg)
|
||||
{
|
||||
if(cfg.minVoltage) this->setMinVoltage(cfg.minVoltage); else this->setMinVoltage(USERMOD_BATTERY_UNKOWN_MIN_VOLTAGE);
|
||||
if(cfg.maxVoltage) this->setMaxVoltage(cfg.maxVoltage); else this->setMaxVoltage(USERMOD_BATTERY_UNKOWN_MAX_VOLTAGE);
|
||||
}
|
||||
|
||||
float mapVoltage(float v, float min, float max) override
|
||||
{
|
||||
return this->linearMapping(v, min, max); // basic mapping
|
||||
};
|
||||
|
||||
void calculateAndSetLevel(float voltage) override
|
||||
{
|
||||
this->setLevel(this->mapVoltage(voltage, this->getMinVoltage(), this->getMaxVoltage()));
|
||||
};
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -2,12 +2,15 @@
|
||||
|
||||
#include "wled.h"
|
||||
#include "battery_defaults.h"
|
||||
#include "UMBattery.h"
|
||||
#include "types/UnkownUMBattery.h"
|
||||
#include "types/LionUMBattery.h"
|
||||
#include "types/LipoUMBattery.h"
|
||||
|
||||
/*
|
||||
* Usermod by Maximilian Mewes
|
||||
* Mail: mewes.maximilian@gmx.de
|
||||
* GitHub: itCarl
|
||||
* Date: 25.12.2022
|
||||
* E-mail: mewes.maximilian@gmx.de
|
||||
* Created at: 25.12.2022
|
||||
* If you have any questions, please feel free to contact me.
|
||||
*/
|
||||
class UsermodBattery : public Usermod
|
||||
@@ -15,49 +18,39 @@ class UsermodBattery : public Usermod
|
||||
private:
|
||||
// battery pin can be defined in my_config.h
|
||||
int8_t batteryPin = USERMOD_BATTERY_MEASUREMENT_PIN;
|
||||
|
||||
UMBattery* bat = new UnkownUMBattery();
|
||||
batteryConfig cfg;
|
||||
|
||||
// Initial delay before first reading to allow voltage stabilization
|
||||
unsigned long initialDelay = USERMOD_BATTERY_INITIAL_DELAY;
|
||||
bool initialDelayComplete = false;
|
||||
bool isFirstVoltageReading = true;
|
||||
// how often to read the battery voltage
|
||||
unsigned long readingInterval = USERMOD_BATTERY_MEASUREMENT_INTERVAL;
|
||||
unsigned long nextReadTime = 0;
|
||||
unsigned long lastReadTime = 0;
|
||||
// battery min. voltage
|
||||
float minBatteryVoltage = USERMOD_BATTERY_MIN_VOLTAGE;
|
||||
// battery max. voltage
|
||||
float maxBatteryVoltage = USERMOD_BATTERY_MAX_VOLTAGE;
|
||||
// all battery cells summed up
|
||||
unsigned int totalBatteryCapacity = USERMOD_BATTERY_TOTAL_CAPACITY;
|
||||
// raw analog reading
|
||||
float rawValue = 0.0f;
|
||||
// calculated voltage
|
||||
float voltage = maxBatteryVoltage;
|
||||
// between 0 and 1, to control strength of voltage smoothing filter
|
||||
float alpha = 0.05f;
|
||||
// multiplier for the voltage divider that is in place between ADC pin and battery, default will be 2 but might be adapted to readout voltages over ~5v ESP32 or ~6.6v ESP8266
|
||||
float voltageMultiplier = USERMOD_BATTERY_VOLTAGE_MULTIPLIER;
|
||||
// mapped battery level based on voltage
|
||||
int8_t batteryLevel = 100;
|
||||
// offset or calibration value to fine tune the calculated voltage
|
||||
float calibration = USERMOD_BATTERY_CALIBRATION;
|
||||
|
||||
// time left estimation feature
|
||||
// bool calculateTimeLeftEnabled = USERMOD_BATTERY_CALCULATE_TIME_LEFT_ENABLED;
|
||||
// float estimatedTimeLeft = 0.0;
|
||||
float alpha = USERMOD_BATTERY_AVERAGING_ALPHA;
|
||||
|
||||
// auto shutdown/shutoff/master off feature
|
||||
bool autoOffEnabled = USERMOD_BATTERY_AUTO_OFF_ENABLED;
|
||||
int8_t autoOffThreshold = USERMOD_BATTERY_AUTO_OFF_THRESHOLD;
|
||||
uint8_t autoOffThreshold = USERMOD_BATTERY_AUTO_OFF_THRESHOLD;
|
||||
|
||||
// low power indicator feature
|
||||
bool lowPowerIndicatorEnabled = USERMOD_BATTERY_LOW_POWER_INDICATOR_ENABLED;
|
||||
int8_t lowPowerIndicatorPreset = USERMOD_BATTERY_LOW_POWER_INDICATOR_PRESET;
|
||||
int8_t lowPowerIndicatorThreshold = USERMOD_BATTERY_LOW_POWER_INDICATOR_THRESHOLD;
|
||||
int8_t lowPowerIndicatorReactivationThreshold = lowPowerIndicatorThreshold+10;
|
||||
int8_t lowPowerIndicatorDuration = USERMOD_BATTERY_LOW_POWER_INDICATOR_DURATION;
|
||||
uint8_t lowPowerIndicatorPreset = USERMOD_BATTERY_LOW_POWER_INDICATOR_PRESET;
|
||||
uint8_t lowPowerIndicatorThreshold = USERMOD_BATTERY_LOW_POWER_INDICATOR_THRESHOLD;
|
||||
uint8_t lowPowerIndicatorReactivationThreshold = lowPowerIndicatorThreshold+10;
|
||||
uint8_t lowPowerIndicatorDuration = USERMOD_BATTERY_LOW_POWER_INDICATOR_DURATION;
|
||||
bool lowPowerIndicationDone = false;
|
||||
unsigned long lowPowerActivationTime = 0; // used temporary during active time
|
||||
int8_t lastPreset = 0;
|
||||
uint8_t lastPreset = 0;
|
||||
|
||||
//
|
||||
bool initDone = false;
|
||||
bool initializing = true;
|
||||
bool HomeAssistantDiscovery = false;
|
||||
|
||||
// strings to reduce flash memory usage (used more than twice)
|
||||
static const char _name[];
|
||||
@@ -67,22 +60,29 @@ class UsermodBattery : public Usermod
|
||||
static const char _preset[];
|
||||
static const char _duration[];
|
||||
static const char _init[];
|
||||
|
||||
|
||||
// custom map function
|
||||
// https://forum.arduino.cc/t/floating-point-using-map-function/348113/2
|
||||
double mapf(double x, double in_min, double in_max, double out_min, double out_max)
|
||||
{
|
||||
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
|
||||
}
|
||||
static const char _haDiscovery[];
|
||||
|
||||
/**
|
||||
* Helper for rounding floating point values
|
||||
*/
|
||||
float dot2round(float x)
|
||||
{
|
||||
float nx = (int)(x * 100 + .5);
|
||||
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
|
||||
*/
|
||||
void turnOff()
|
||||
@@ -91,15 +91,15 @@ class UsermodBattery : public Usermod
|
||||
stateUpdated(CALL_MODE_DIRECT_CHANGE);
|
||||
}
|
||||
|
||||
/*
|
||||
/**
|
||||
* Indicate low power by activating a configured preset for a given time and then switching back to the preset that was selected previously
|
||||
*/
|
||||
void lowPowerIndicator()
|
||||
{
|
||||
if (!lowPowerIndicatorEnabled) return;
|
||||
if (batteryPin < 0) return; // no measurement
|
||||
if (lowPowerIndicationDone && lowPowerIndicatorReactivationThreshold <= batteryLevel) lowPowerIndicationDone = false;
|
||||
if (lowPowerIndicatorThreshold <= batteryLevel) return;
|
||||
if (lowPowerIndicationDone && lowPowerIndicatorReactivationThreshold <= bat->getLevel()) lowPowerIndicationDone = false;
|
||||
if (lowPowerIndicatorThreshold <= bat->getLevel()) return;
|
||||
if (lowPowerIndicationDone) return;
|
||||
if (lowPowerActivationTime <= 1) {
|
||||
lowPowerActivationTime = millis();
|
||||
@@ -114,34 +114,95 @@ class UsermodBattery : public Usermod
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* read the battery voltage in different ways depending on the architecture
|
||||
*/
|
||||
float readVoltage()
|
||||
{
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
// use calibrated millivolts analogread on esp32 (150 mV ~ 2450 mV default attentuation) and divide by 1000 to get from milivolts to volts and multiply by voltage multiplier and apply calibration value
|
||||
return (analogReadMilliVolts(batteryPin) / 1000.0f) * voltageMultiplier + calibration;
|
||||
return (analogReadMilliVolts(batteryPin) / 1000.0f) * bat->getVoltageMultiplier() + bat->getCalibration();
|
||||
#else
|
||||
// use analog read on esp8266 ( 0V ~ 1V no attenuation options) and divide by ADC precision 1023 and multiply by voltage multiplier and apply calibration value
|
||||
return (analogRead(batteryPin) / 1023.0f) * voltageMultiplier + calibration;
|
||||
return (analogRead(batteryPin) / 1023.0f) * bat->getVoltageMultiplier() + bat->getCalibration();
|
||||
#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
|
||||
|
||||
/*
|
||||
/**
|
||||
* 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()
|
||||
{
|
||||
// plug in the right battery type
|
||||
if(cfg.type == (batteryType)lipo) {
|
||||
bat = new LipoUMBattery();
|
||||
} else if(cfg.type == (batteryType)lion) {
|
||||
bat = new LionUMBattery();
|
||||
}
|
||||
|
||||
// update the choosen battery type with configured values
|
||||
bat->update(cfg);
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
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;
|
||||
voltage = readVoltage();
|
||||
}
|
||||
|
||||
if (!success) {
|
||||
@@ -152,17 +213,17 @@ class UsermodBattery : public Usermod
|
||||
}
|
||||
#else //ESP8266 boards have only one analog input pin A0
|
||||
pinMode(batteryPin, INPUT);
|
||||
voltage = readVoltage();
|
||||
#endif
|
||||
|
||||
nextReadTime = millis() + readingInterval;
|
||||
// First voltage reading is delayed to allow voltage stabilization after powering up
|
||||
nextReadTime = millis() + initialDelay;
|
||||
lastReadTime = millis();
|
||||
|
||||
initDone = true;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
/**
|
||||
* connected() is called every time the WiFi is (re)connected
|
||||
* Use it to initialize network interfaces
|
||||
*/
|
||||
@@ -182,6 +243,25 @@ class UsermodBattery : public Usermod
|
||||
|
||||
lowPowerIndicator();
|
||||
|
||||
// Handling the initial delay
|
||||
if (!initialDelayComplete && millis() < nextReadTime)
|
||||
return; // Continue to return until the initial delay is over
|
||||
|
||||
// Once the initial delay is over, set it as complete
|
||||
if (!initialDelayComplete)
|
||||
{
|
||||
initialDelayComplete = true;
|
||||
// Set the regular interval after initial delay
|
||||
nextReadTime = millis() + readingInterval;
|
||||
}
|
||||
|
||||
// Make the first voltage reading after the initial delay has elapsed
|
||||
if (isFirstVoltageReading)
|
||||
{
|
||||
bat->setVoltage(readVoltage());
|
||||
isFirstVoltageReading = false;
|
||||
}
|
||||
|
||||
// check the battery level every USERMOD_BATTERY_MEASUREMENT_INTERVAL (ms)
|
||||
if (millis() < nextReadTime) return;
|
||||
|
||||
@@ -191,58 +271,27 @@ class UsermodBattery : public Usermod
|
||||
if (batteryPin < 0) return; // nothing to read
|
||||
|
||||
initializing = false;
|
||||
float rawValue = readVoltage();
|
||||
|
||||
rawValue = readVoltage();
|
||||
// filter with exponential smoothing because ADC in esp32 is fluctuating too much for a good single readout
|
||||
voltage = voltage + alpha * (rawValue - voltage);
|
||||
|
||||
// check if voltage is within specified voltage range, allow 10% over/under voltage - removed cause this just makes it hard for people to troubleshoot as the voltage in the web gui will say invalid instead of displaying a voltage
|
||||
//voltage = ((voltage < minBatteryVoltage * 0.85f) || (voltage > maxBatteryVoltage * 1.1f)) ? -1.0f : voltage;
|
||||
float filteredVoltage = bat->getVoltage() + alpha * (rawValue - bat->getVoltage());
|
||||
|
||||
bat->setVoltage(filteredVoltage);
|
||||
// translate battery voltage into percentage
|
||||
/*
|
||||
the standard "map" function doesn't work
|
||||
https://www.arduino.cc/reference/en/language/functions/math/map/ notes and warnings at the bottom
|
||||
*/
|
||||
#ifdef USERMOD_BATTERY_USE_LIPO
|
||||
batteryLevel = mapf(voltage, minBatteryVoltage, maxBatteryVoltage, 0, 100); // basic mapping
|
||||
// LiPo batteries have a differnt dischargin curve, see
|
||||
// https://blog.ampow.com/lipo-voltage-chart/
|
||||
if (batteryLevel < 40.0f)
|
||||
batteryLevel = mapf(batteryLevel, 0, 40, 0, 12); // last 45% -> drops very quickly
|
||||
else {
|
||||
if (batteryLevel < 90.0f)
|
||||
batteryLevel = mapf(batteryLevel, 40, 90, 12, 95); // 90% ... 40% -> almost linear drop
|
||||
else // level > 90%
|
||||
batteryLevel = mapf(batteryLevel, 90, 105, 95, 100); // highest 15% -> drop slowly
|
||||
}
|
||||
#else
|
||||
batteryLevel = mapf(voltage, minBatteryVoltage, maxBatteryVoltage, 0, 100);
|
||||
#endif
|
||||
if (voltage > -1.0f) batteryLevel = constrain(batteryLevel, 0.0f, 110.0f);
|
||||
|
||||
// if (calculateTimeLeftEnabled) {
|
||||
// float currentBatteryCapacity = totalBatteryCapacity;
|
||||
// estimatedTimeLeft = (currentBatteryCapacity/strip.currentMilliamps)*60;
|
||||
// }
|
||||
bat->calculateAndSetLevel(filteredVoltage);
|
||||
|
||||
// Auto off -- Master power off
|
||||
if (autoOffEnabled && (autoOffThreshold >= batteryLevel))
|
||||
if (autoOffEnabled && (autoOffThreshold >= bat->getLevel()))
|
||||
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(voltage).c_str());
|
||||
}
|
||||
publishMqtt("battery", String(bat->getLevel(), 0).c_str());
|
||||
publishMqtt("voltage", String(bat->getVoltage()).c_str());
|
||||
#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
|
||||
@@ -262,16 +311,6 @@ class UsermodBattery : public Usermod
|
||||
// info modal display names
|
||||
JsonArray infoPercentage = user.createNestedArray(F("Battery level"));
|
||||
JsonArray infoVoltage = user.createNestedArray(F("Battery voltage"));
|
||||
// if (calculateTimeLeftEnabled)
|
||||
// {
|
||||
// JsonArray infoEstimatedTimeLeft = user.createNestedArray(F("Estimated time left"));
|
||||
// if (initializing) {
|
||||
// infoEstimatedTimeLeft.add(FPSTR(_init));
|
||||
// } else {
|
||||
// infoEstimatedTimeLeft.add(estimatedTimeLeft);
|
||||
// infoEstimatedTimeLeft.add(F(" min"));
|
||||
// }
|
||||
// }
|
||||
JsonArray infoNextUpdate = user.createNestedArray(F("Next update"));
|
||||
|
||||
infoNextUpdate.add((nextReadTime - millis()) / 1000);
|
||||
@@ -283,46 +322,105 @@ class UsermodBattery : public Usermod
|
||||
return;
|
||||
}
|
||||
|
||||
if (batteryLevel < 0) {
|
||||
if (bat->getLevel() < 0) {
|
||||
infoPercentage.add(F("invalid"));
|
||||
} else {
|
||||
infoPercentage.add(batteryLevel);
|
||||
infoPercentage.add(bat->getLevel());
|
||||
}
|
||||
infoPercentage.add(F(" %"));
|
||||
|
||||
if (voltage < 0) {
|
||||
if (bat->getVoltage() < 0) {
|
||||
infoVoltage.add(F("invalid"));
|
||||
} else {
|
||||
infoVoltage.add(dot2round(voltage));
|
||||
infoVoltage.add(dot2round(bat->getVoltage()));
|
||||
}
|
||||
infoVoltage.add(F(" V"));
|
||||
}
|
||||
|
||||
void addBatteryToJsonObject(JsonObject& battery, bool forJsonState)
|
||||
{
|
||||
if(forJsonState) { battery[F("type")] = cfg.type; } else {battery[F("type")] = (String)cfg.type; } // has to be a String otherwise it won't get converted to a Dropdown
|
||||
battery[F("min-voltage")] = bat->getMinVoltage();
|
||||
battery[F("max-voltage")] = bat->getMaxVoltage();
|
||||
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;
|
||||
ao[FPSTR(_threshold)] = autoOffThreshold;
|
||||
|
||||
JsonObject lp = battery.createNestedObject(F("indicator")); // low power section
|
||||
lp[FPSTR(_enabled)] = lowPowerIndicatorEnabled;
|
||||
lp[FPSTR(_preset)] = lowPowerIndicatorPreset; // dropdown trickery (String)lowPowerIndicatorPreset;
|
||||
lp[FPSTR(_threshold)] = lowPowerIndicatorThreshold;
|
||||
lp[FPSTR(_duration)] = lowPowerIndicatorDuration;
|
||||
}
|
||||
|
||||
void getUsermodConfigFromJsonObject(JsonObject& battery)
|
||||
{
|
||||
getJsonValue(battery[F("type")], cfg.type);
|
||||
getJsonValue(battery[F("min-voltage")], cfg.minVoltage);
|
||||
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);
|
||||
setAutoOffThreshold(ao[FPSTR(_threshold)] | autoOffThreshold);
|
||||
|
||||
JsonObject lp = battery[F("indicator")];
|
||||
setLowPowerIndicatorEnabled(lp[FPSTR(_enabled)] | lowPowerIndicatorEnabled);
|
||||
setLowPowerIndicatorPreset(lp[FPSTR(_preset)] | lowPowerIndicatorPreset);
|
||||
setLowPowerIndicatorThreshold(lp[FPSTR(_threshold)] | lowPowerIndicatorThreshold);
|
||||
lowPowerIndicatorReactivationThreshold = lowPowerIndicatorThreshold+10;
|
||||
setLowPowerIndicatorDuration(lp[FPSTR(_duration)] | lowPowerIndicatorDuration);
|
||||
|
||||
if(initDone)
|
||||
bat->update(cfg);
|
||||
}
|
||||
|
||||
/**
|
||||
* addToJsonState() can be used to add custom entries to the /json/state part of the JSON API (state object).
|
||||
* Values in the state object may be modified by connected clients
|
||||
*/
|
||||
/*
|
||||
void addToJsonState(JsonObject& root)
|
||||
{
|
||||
JsonObject battery = root.createNestedObject(FPSTR(_name));
|
||||
|
||||
if (battery.isNull())
|
||||
battery = root.createNestedObject(FPSTR(_name));
|
||||
|
||||
addBatteryToJsonObject(battery, true);
|
||||
|
||||
DEBUG_PRINTLN(F("Battery state exposed in JSON API."));
|
||||
}
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
/**
|
||||
* readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object).
|
||||
* Values in the state object may be modified by connected clients
|
||||
*/
|
||||
/*
|
||||
void readFromJsonState(JsonObject& root)
|
||||
{
|
||||
if (!initDone) return; // prevent crash on boot applyPreset()
|
||||
|
||||
JsonObject battery = root[FPSTR(_name)];
|
||||
|
||||
if (!battery.isNull()) {
|
||||
getUsermodConfigFromJsonObject(battery);
|
||||
|
||||
DEBUG_PRINTLN(F("Battery state read from JSON API."));
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
/**
|
||||
* 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().
|
||||
@@ -359,60 +457,55 @@ class UsermodBattery : public Usermod
|
||||
*/
|
||||
void addToConfig(JsonObject& root)
|
||||
{
|
||||
JsonObject battery = root.createNestedObject(FPSTR(_name)); // usermodname
|
||||
JsonObject battery = root.createNestedObject(FPSTR(_name));
|
||||
|
||||
if (battery.isNull()) {
|
||||
battery = root.createNestedObject(FPSTR(_name));
|
||||
}
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
battery[F("pin")] = batteryPin;
|
||||
#endif
|
||||
|
||||
// battery[F("time-left")] = calculateTimeLeftEnabled;
|
||||
battery[F("min-voltage")] = minBatteryVoltage;
|
||||
battery[F("max-voltage")] = maxBatteryVoltage;
|
||||
battery[F("capacity")] = totalBatteryCapacity;
|
||||
battery[F("calibration")] = calibration;
|
||||
battery[F("voltage-multiplier")] = voltageMultiplier;
|
||||
battery[FPSTR(_readInterval)] = readingInterval;
|
||||
|
||||
JsonObject ao = battery.createNestedObject(F("auto-off")); // auto off section
|
||||
ao[FPSTR(_enabled)] = autoOffEnabled;
|
||||
ao[FPSTR(_threshold)] = autoOffThreshold;
|
||||
|
||||
JsonObject lp = battery.createNestedObject(F("indicator")); // low power section
|
||||
lp[FPSTR(_enabled)] = lowPowerIndicatorEnabled;
|
||||
lp[FPSTR(_preset)] = lowPowerIndicatorPreset; // dropdown trickery (String)lowPowerIndicatorPreset;
|
||||
lp[FPSTR(_threshold)] = lowPowerIndicatorThreshold;
|
||||
lp[FPSTR(_duration)] = lowPowerIndicatorDuration;
|
||||
addBatteryToJsonObject(battery, false);
|
||||
|
||||
// read voltage in case calibration or voltage multiplier changed to see immediate effect
|
||||
voltage = readVoltage();
|
||||
bat->setVoltage(readVoltage());
|
||||
|
||||
DEBUG_PRINTLN(F("Battery config saved."));
|
||||
}
|
||||
|
||||
void appendConfigData()
|
||||
{
|
||||
oappend(SET_F("addInfo('Battery:min-voltage', 1, 'v');"));
|
||||
oappend(SET_F("addInfo('Battery:max-voltage', 1, 'v');"));
|
||||
oappend(SET_F("addInfo('Battery:capacity', 1, 'mAh');"));
|
||||
oappend(SET_F("addInfo('Battery:interval', 1, 'ms');"));
|
||||
oappend(SET_F("addInfo('Battery:auto-off:threshold', 1, '%');"));
|
||||
oappend(SET_F("addInfo('Battery:indicator:threshold', 1, '%');"));
|
||||
oappend(SET_F("addInfo('Battery:indicator:duration', 1, 's');"));
|
||||
// Total: 462 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
|
||||
|
||||
// cannot quite get this mf to work. its exeeding some buffer limit i think
|
||||
// what i wanted is 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);"));
|
||||
// this option list would exeed the oappend() buffer
|
||||
// a list of all presets to select one from
|
||||
// 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(");"));
|
||||
// }
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
/**
|
||||
* readFromConfig() can be used to read back the custom settings you added with addToConfig().
|
||||
* This is called by WLED when settings are loaded (currently this only happens immediately after boot, or after saving on the Usermod Settings page)
|
||||
*
|
||||
@@ -444,26 +537,14 @@ 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")] | minBatteryVoltage);
|
||||
setMaxBatteryVoltage(battery[F("max-voltage")] | maxBatteryVoltage);
|
||||
setTotalBatteryCapacity(battery[F("capacity")] | totalBatteryCapacity);
|
||||
setCalibration(battery[F("calibration")] | calibration);
|
||||
setVoltageMultiplier(battery[F("voltage-multiplier")] | voltageMultiplier);
|
||||
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);
|
||||
|
||||
JsonObject ao = battery[F("auto-off")];
|
||||
setAutoOffEnabled(ao[FPSTR(_enabled)] | autoOffEnabled);
|
||||
setAutoOffThreshold(ao[FPSTR(_threshold)] | autoOffThreshold);
|
||||
|
||||
JsonObject lp = battery[F("indicator")];
|
||||
setLowPowerIndicatorEnabled(lp[FPSTR(_enabled)] | lowPowerIndicatorEnabled);
|
||||
setLowPowerIndicatorPreset(lp[FPSTR(_preset)] | lowPowerIndicatorPreset); // dropdown trickery (int)lp["preset"]
|
||||
setLowPowerIndicatorThreshold(lp[FPSTR(_threshold)] | lowPowerIndicatorThreshold);
|
||||
lowPowerIndicatorReactivationThreshold = lowPowerIndicatorThreshold+10;
|
||||
setLowPowerIndicatorDuration(lp[FPSTR(_duration)] | lowPowerIndicatorDuration);
|
||||
|
||||
DEBUG_PRINT(FPSTR(_name));
|
||||
getUsermodConfigFromJsonObject(battery);
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
if (!initDone)
|
||||
@@ -480,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();
|
||||
@@ -491,37 +572,24 @@ class UsermodBattery : public Usermod
|
||||
return !battery[FPSTR(_readInterval)].isNull();
|
||||
}
|
||||
|
||||
/*
|
||||
* Generate a preset sample for low power indication
|
||||
*/
|
||||
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
|
||||
|
||||
/*
|
||||
*
|
||||
@@ -529,7 +597,7 @@ class UsermodBattery : public Usermod
|
||||
*
|
||||
*/
|
||||
|
||||
/*
|
||||
/**
|
||||
* getId() allows you to optionally give your V2 usermod an unique ID (please define it in const.h!).
|
||||
* This could be used in the future for the system to determine whether your usermod is installed.
|
||||
*/
|
||||
@@ -538,13 +606,23 @@ class UsermodBattery : public Usermod
|
||||
return USERMOD_ID_BATTERY;
|
||||
}
|
||||
|
||||
/**
|
||||
* get currently active battery type
|
||||
*/
|
||||
batteryType getBatteryType()
|
||||
{
|
||||
return cfg.type;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
unsigned long getReadingInterval()
|
||||
{
|
||||
return readingInterval;
|
||||
}
|
||||
|
||||
/*
|
||||
/**
|
||||
* minimum repetition is 3000ms (3s)
|
||||
*/
|
||||
void setReadingInterval(unsigned long newReadingInterval)
|
||||
@@ -552,105 +630,84 @@ class UsermodBattery : public Usermod
|
||||
readingInterval = max((unsigned long)3000, newReadingInterval);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
/**
|
||||
* Get lowest configured battery voltage
|
||||
*/
|
||||
float getMinBatteryVoltage()
|
||||
{
|
||||
return minBatteryVoltage;
|
||||
return bat->getMinVoltage();
|
||||
}
|
||||
|
||||
/*
|
||||
/**
|
||||
* Set lowest battery voltage
|
||||
* can't be below 0 volt
|
||||
*/
|
||||
void setMinBatteryVoltage(float voltage)
|
||||
{
|
||||
minBatteryVoltage = max(0.0f, voltage);
|
||||
bat->setMinVoltage(voltage);
|
||||
}
|
||||
|
||||
/*
|
||||
/**
|
||||
* Get highest configured battery voltage
|
||||
*/
|
||||
float getMaxBatteryVoltage()
|
||||
{
|
||||
return maxBatteryVoltage;
|
||||
return bat->getMaxVoltage();
|
||||
}
|
||||
|
||||
/*
|
||||
/**
|
||||
* Set highest battery voltage
|
||||
* can't be below minBatteryVoltage
|
||||
*/
|
||||
void setMaxBatteryVoltage(float voltage)
|
||||
{
|
||||
#ifdef USERMOD_BATTERY_USE_LIPO
|
||||
maxBatteryVoltage = max(getMinBatteryVoltage()+0.7f, voltage);
|
||||
#else
|
||||
maxBatteryVoltage = max(getMinBatteryVoltage()+1.0f, voltage);
|
||||
#endif
|
||||
bat->setMaxVoltage(voltage);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Get the capacity of all cells in parralel sumed up
|
||||
* unit: mAh
|
||||
*/
|
||||
unsigned int getTotalBatteryCapacity()
|
||||
{
|
||||
return totalBatteryCapacity;
|
||||
}
|
||||
|
||||
void setTotalBatteryCapacity(unsigned int capacity)
|
||||
{
|
||||
totalBatteryCapacity = capacity;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*
|
||||
/**
|
||||
* Get the calculated voltage
|
||||
* formula: (adc pin value / adc precision * max voltage) + calibration
|
||||
*/
|
||||
float getVoltage()
|
||||
{
|
||||
return voltage;
|
||||
return bat->getVoltage();
|
||||
}
|
||||
|
||||
/*
|
||||
/**
|
||||
* Get the mapped battery level (0 - 100) based on voltage
|
||||
* important: voltage can drop when a load is applied, so its only an estimate
|
||||
*/
|
||||
int8_t getBatteryLevel()
|
||||
{
|
||||
return batteryLevel;
|
||||
return bat->getLevel();
|
||||
}
|
||||
|
||||
/*
|
||||
/**
|
||||
* Get the configured calibration value
|
||||
* a offset value to fine-tune the calculated voltage.
|
||||
*/
|
||||
float getCalibration()
|
||||
{
|
||||
return calibration;
|
||||
return bat->getCalibration();
|
||||
}
|
||||
|
||||
/*
|
||||
/**
|
||||
* Set the voltage calibration offset value
|
||||
* a offset value to fine-tune the calculated voltage.
|
||||
*/
|
||||
void setCalibration(float offset)
|
||||
{
|
||||
calibration = offset;
|
||||
bat->setCalibration(offset);
|
||||
}
|
||||
|
||||
/*
|
||||
/**
|
||||
* Set the voltage multiplier value
|
||||
* A multiplier that may need adjusting for different voltage divider setups
|
||||
*/
|
||||
void setVoltageMultiplier(float multiplier)
|
||||
{
|
||||
voltageMultiplier = multiplier;
|
||||
bat->setVoltageMultiplier(multiplier);
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -659,10 +716,10 @@ class UsermodBattery : public Usermod
|
||||
*/
|
||||
float getVoltageMultiplier()
|
||||
{
|
||||
return voltageMultiplier;
|
||||
return bat->getVoltageMultiplier();
|
||||
}
|
||||
|
||||
/*
|
||||
/**
|
||||
* Get auto-off feature enabled status
|
||||
* is auto-off enabled, true/false
|
||||
*/
|
||||
@@ -671,7 +728,7 @@ class UsermodBattery : public Usermod
|
||||
return autoOffEnabled;
|
||||
}
|
||||
|
||||
/*
|
||||
/**
|
||||
* Set auto-off feature status
|
||||
*/
|
||||
void setAutoOffEnabled(bool enabled)
|
||||
@@ -679,7 +736,7 @@ class UsermodBattery : public Usermod
|
||||
autoOffEnabled = enabled;
|
||||
}
|
||||
|
||||
/*
|
||||
/**
|
||||
* Get auto-off threshold in percent (0-100)
|
||||
*/
|
||||
int8_t getAutoOffThreshold()
|
||||
@@ -687,7 +744,7 @@ class UsermodBattery : public Usermod
|
||||
return autoOffThreshold;
|
||||
}
|
||||
|
||||
/*
|
||||
/**
|
||||
* Set auto-off threshold in percent (0-100)
|
||||
*/
|
||||
void setAutoOffThreshold(int8_t threshold)
|
||||
@@ -697,8 +754,7 @@ class UsermodBattery : public Usermod
|
||||
autoOffThreshold = lowPowerIndicatorEnabled /*&& autoOffEnabled*/ ? min(lowPowerIndicatorThreshold-1, (int)autoOffThreshold) : autoOffThreshold;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
/**
|
||||
* Get low-power-indicator feature enabled status
|
||||
* is the low-power-indicator enabled, true/false
|
||||
*/
|
||||
@@ -707,7 +763,7 @@ class UsermodBattery : public Usermod
|
||||
return lowPowerIndicatorEnabled;
|
||||
}
|
||||
|
||||
/*
|
||||
/**
|
||||
* Set low-power-indicator feature status
|
||||
*/
|
||||
void setLowPowerIndicatorEnabled(bool enabled)
|
||||
@@ -715,7 +771,7 @@ class UsermodBattery : public Usermod
|
||||
lowPowerIndicatorEnabled = enabled;
|
||||
}
|
||||
|
||||
/*
|
||||
/**
|
||||
* Get low-power-indicator preset to activate when low power is detected
|
||||
*/
|
||||
int8_t getLowPowerIndicatorPreset()
|
||||
@@ -723,7 +779,7 @@ class UsermodBattery : public Usermod
|
||||
return lowPowerIndicatorPreset;
|
||||
}
|
||||
|
||||
/*
|
||||
/**
|
||||
* Set low-power-indicator preset to activate when low power is detected
|
||||
*/
|
||||
void setLowPowerIndicatorPreset(int8_t presetId)
|
||||
@@ -741,7 +797,7 @@ class UsermodBattery : public Usermod
|
||||
return lowPowerIndicatorThreshold;
|
||||
}
|
||||
|
||||
/*
|
||||
/**
|
||||
* Set low-power-indicator threshold in percent (0-100)
|
||||
*/
|
||||
void setLowPowerIndicatorThreshold(int8_t threshold)
|
||||
@@ -751,7 +807,7 @@ class UsermodBattery : public Usermod
|
||||
lowPowerIndicatorThreshold = autoOffEnabled /*&& lowPowerIndicatorEnabled*/ ? max(autoOffThreshold+1, (int)lowPowerIndicatorThreshold) : max(5, (int)lowPowerIndicatorThreshold);
|
||||
}
|
||||
|
||||
/*
|
||||
/**
|
||||
* Get low-power-indicator duration in seconds
|
||||
*/
|
||||
int8_t getLowPowerIndicatorDuration()
|
||||
@@ -759,7 +815,7 @@ class UsermodBattery : public Usermod
|
||||
return lowPowerIndicatorDuration;
|
||||
}
|
||||
|
||||
/*
|
||||
/**
|
||||
* Set low-power-indicator duration in seconds
|
||||
*/
|
||||
void setLowPowerIndicatorDuration(int8_t duration)
|
||||
@@ -767,14 +823,29 @@ class UsermodBattery : public Usermod
|
||||
lowPowerIndicatorDuration = duration;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Get low-power-indicator status when the indication is done thsi returns true
|
||||
/**
|
||||
* Get low-power-indicator status when the indication is done this returns true
|
||||
*/
|
||||
bool getLowPowerIndicatorDone()
|
||||
{
|
||||
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)
|
||||
@@ -785,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());
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
77
usermods/INA226_v2/README.md
Normal file
@@ -0,0 +1,77 @@
|
||||
# Usermod INA226
|
||||
|
||||
This Usermod is designed to read values from an INA226 sensor and output the following:
|
||||
- Current
|
||||
- Voltage
|
||||
- Power
|
||||
- Shunt Voltage
|
||||
- Overflow status
|
||||
|
||||
## Configuration
|
||||
|
||||
The following settings can be configured in the Usermod Menu:
|
||||
- **Enabled**: Enable or disable the usermod.
|
||||
- **I2CAddress**: The I2C address in decimal. Default is 64 (0x40).
|
||||
- **CheckInterval**: Number of seconds between readings. This should be higher than the time it takes to make a reading, determined by the two next options.
|
||||
- **INASamples**: The number of samples to configure the INA226 to use for a measurement. Higher counts provide more accuracy. See the 'Understanding Samples and Conversion Times' section for more details.
|
||||
- **INAConversionTime**: The time to use on converting and preparing readings on the INA226. Higher times provide more precision. See the 'Understanding Samples and Conversion Times' section for more details.
|
||||
- **Decimals**: Number of decimals in the output.
|
||||
- **ShuntResistor**: Shunt resistor value in milliohms. An R100 shunt resistor should be written as "100", while R010 should be "10".
|
||||
- **CurrentRange**: Expected maximum current in milliamps (e.g., 5 A = 5000 mA).
|
||||
- **MqttPublish**: Enable or disable MQTT publishing.
|
||||
- **MqttPublishAlways**: Publish always, regardless if there is a change.
|
||||
- **MqttHomeAssistantDiscovery**: Enable Home Assistant discovery.
|
||||
|
||||
## Dependencies
|
||||
|
||||
These must be added under `lib_deps` in your `platform.ini` (or `platform_override.ini`).
|
||||
|
||||
- Libraries
|
||||
- `wollewald/INA226_WE@~1.2.9` (by [wollewald](https://registry.platformio.org/libraries/wollewald/INA226_WE))
|
||||
- `Wire`
|
||||
|
||||
## Understanding Samples and Conversion Times
|
||||
|
||||
The INA226 uses a programmable ADC with configurable conversion times and averaging to optimize the measurement accuracy and speed. The conversion time and number of samples are determined based on the `INASamples` and `INAConversionTime` settings. The following table outlines the possible combinations:
|
||||
|
||||
| Conversion Time (μs) | 1 Sample | 4 Samples | 16 Samples | 64 Samples | 128 Samples | 256 Samples | 512 Samples | 1024 Samples |
|
||||
|----------------------|----------|-----------|------------|------------|-------------|-------------|-------------|--------------|
|
||||
| 140 | 0.28 ms | 1.12 ms | 4.48 ms | 17.92 ms | 35.84 ms | 71.68 ms | 143.36 ms | 286.72 ms |
|
||||
| 204 | 0.408 ms | 1.632 ms | 6.528 ms | 26.112 ms | 52.224 ms | 104.448 ms | 208.896 ms | 417.792 ms |
|
||||
| 332 | 0.664 ms | 2.656 ms | 10.624 ms | 42.496 ms | 84.992 ms | 169.984 ms | 339.968 ms | 679.936 ms |
|
||||
| 588 | 1.176 ms | 4.704 ms | 18.816 ms | 75.264 ms | 150.528 ms | 301.056 ms | 602.112 ms | 1204.224 ms |
|
||||
| 1100 | 2.2 ms | 8.8 ms | 35.2 ms | 140.8 ms | 281.6 ms | 563.2 ms | 1126.4 ms | 2252.8 ms |
|
||||
| 2116 | 4.232 ms | 16.928 ms | 67.712 ms | 270.848 ms | 541.696 ms | 1083.392 ms | 2166.784 ms | 4333.568 ms |
|
||||
| 4156 | 8.312 ms | 33.248 ms | 132.992 ms | 531.968 ms | 1063.936 ms | 2127.872 ms | 4255.744 ms | 8511.488 ms |
|
||||
| 8244 | 16.488 ms| 65.952 ms | 263.808 ms | 1055.232 ms| 2110.464 ms | 4220.928 ms | 8441.856 ms | 16883.712 ms |
|
||||
|
||||
It is important to pick a combination that provides the needed balance between accuracy and precision while ensuring new readings within the `CheckInterval` setting. When `USERMOD_INA226_DEBUG` is defined, the info pane contains the expected time to make a reading, which can be seen in the table above.
|
||||
|
||||
As an example, if you want a new reading every 5 seconds (`CheckInterval`), a valid combination is `256 samples` and `4156 μs` which would provide new values every 2.1 seconds.
|
||||
|
||||
The picked values also slightly affect power usage. If the `CheckInterval` is set to more than 20 seconds, the INA226 is configured in `triggered` reading mode, where it only uses power as long as it's working. Then the conversion time and average samples counts determine how long the chip stays turned on every `CheckInterval` time.
|
||||
|
||||
### Calculating Current and Power
|
||||
|
||||
The INA226 calculates current by measuring the differential voltage across a shunt resistor and using the calibration register value to convert this measurement into current. Power is calculated by multiplying the current by the bus voltage.
|
||||
|
||||
For detailed programming information and register configurations, refer to the [INA226 datasheet](https://www.ti.com/product/INA226).
|
||||
|
||||
## Author
|
||||
[@LordMike](https://github.com/LordMike)
|
||||
|
||||
## Compiling
|
||||
|
||||
To enable, compile with `USERMOD_INA226` defined (e.g. in `platformio_override.ini`).
|
||||
|
||||
```ini
|
||||
[env:ina226_example]
|
||||
extends = env:esp32dev
|
||||
build_flags =
|
||||
${common.build_flags} ${esp32.build_flags}
|
||||
-D USERMOD_INA226
|
||||
; -D USERMOD_INA226_DEBUG ; -- add a debug status to the info modal
|
||||
lib_deps =
|
||||
${esp32.lib_deps}
|
||||
wollewald/INA226_WE@~1.2.9
|
||||
```
|
||||
9
usermods/INA226_v2/platformio_override.ini
Normal file
@@ -0,0 +1,9 @@
|
||||
[env:ina226_example]
|
||||
extends = env:esp32dev
|
||||
build_flags =
|
||||
${common.build_flags} ${esp32.build_flags}
|
||||
-D USERMOD_INA226
|
||||
; -D USERMOD_INA226_DEBUG ; -- add a debug status to the info modal
|
||||
lib_deps =
|
||||
${esp32.lib_deps}
|
||||
wollewald/INA226_WE@~1.2.9
|
||||
556
usermods/INA226_v2/usermod_ina226.h
Normal file
@@ -0,0 +1,556 @@
|
||||
#pragma once
|
||||
|
||||
#include "wled.h"
|
||||
#include <INA226_WE.h>
|
||||
|
||||
#define INA226_ADDRESS 0x40 // Default I2C address for INA226
|
||||
|
||||
#define DEFAULT_CHECKINTERVAL 60000
|
||||
#define DEFAULT_INASAMPLES 128
|
||||
#define DEFAULT_INASAMPLESENUM AVERAGE_128
|
||||
#define DEFAULT_INACONVERSIONTIME 1100
|
||||
#define DEFAULT_INACONVERSIONTIMEENUM CONV_TIME_1100
|
||||
|
||||
// A packed version of all INA settings enums and their human friendly counterparts packed into a 32 bit structure
|
||||
// Some values are shifted and need to be preprocessed before usage
|
||||
struct InaSettingLookup
|
||||
{
|
||||
uint16_t avgSamples : 11; // Max 1024, which could be in 10 bits if we shifted by 1; if we somehow handle the edge case with "1"
|
||||
uint8_t avgEnum : 4; // Shift by 8 to get the INA226_AVERAGES value, accepts 0x00 to 0x0F, we need 0x00 to 0x0E
|
||||
uint16_t convTimeUs : 14; // We could save 2 bits by shifting this, but we won't save anything at present.
|
||||
INA226_CONV_TIME convTimeEnum : 3; // Only the lowest 3 bits are defined in the conversion time enumerations
|
||||
};
|
||||
|
||||
const InaSettingLookup _inaSettingsLookup[] = {
|
||||
{1024, AVERAGE_1024 >> 8, 8244, CONV_TIME_8244},
|
||||
{512, AVERAGE_512 >> 8, 4156, CONV_TIME_4156},
|
||||
{256, AVERAGE_256 >> 8, 2116, CONV_TIME_2116},
|
||||
{128, AVERAGE_128 >> 8, 1100, CONV_TIME_1100},
|
||||
{64, AVERAGE_64 >> 8, 588, CONV_TIME_588},
|
||||
{16, AVERAGE_16 >> 8, 332, CONV_TIME_332},
|
||||
{4, AVERAGE_4 >> 8, 204, CONV_TIME_204},
|
||||
{1, AVERAGE_1 >> 8, 140, CONV_TIME_140}};
|
||||
|
||||
// Note: Will update the provided arg to be the correct value
|
||||
INA226_AVERAGES getAverageEnum(uint16_t &samples)
|
||||
{
|
||||
for (const auto &setting : _inaSettingsLookup)
|
||||
{
|
||||
// If a user supplies 2000 samples, we serve up the highest possible value
|
||||
if (samples >= setting.avgSamples)
|
||||
{
|
||||
samples = setting.avgSamples;
|
||||
return static_cast<INA226_AVERAGES>(setting.avgEnum << 8);
|
||||
}
|
||||
}
|
||||
// Default value if not found
|
||||
samples = DEFAULT_INASAMPLES;
|
||||
return DEFAULT_INASAMPLESENUM;
|
||||
}
|
||||
|
||||
INA226_CONV_TIME getConversionTimeEnum(uint16_t &timeUs)
|
||||
{
|
||||
for (const auto &setting : _inaSettingsLookup)
|
||||
{
|
||||
// If a user supplies 9000 μs, we serve up the highest possible value
|
||||
if (timeUs >= setting.convTimeUs)
|
||||
{
|
||||
timeUs = setting.convTimeUs;
|
||||
return setting.convTimeEnum;
|
||||
}
|
||||
}
|
||||
// Default value if not found
|
||||
timeUs = DEFAULT_INACONVERSIONTIME;
|
||||
return DEFAULT_INACONVERSIONTIMEENUM;
|
||||
}
|
||||
|
||||
class UsermodINA226 : public Usermod
|
||||
{
|
||||
private:
|
||||
static const char _name[];
|
||||
|
||||
unsigned long _lastLoopCheck = 0;
|
||||
unsigned long _lastTriggerTime = 0;
|
||||
|
||||
bool _settingEnabled : 1; // Enable the usermod
|
||||
bool _mqttPublish : 1; // Publish MQTT values
|
||||
bool _mqttPublishAlways : 1; // Publish always, regardless if there is a change
|
||||
bool _mqttHomeAssistant : 1; // Enable Home Assistant docs
|
||||
bool _initDone : 1; // Initialization is done
|
||||
bool _isTriggeredOperationMode : 1; // false = continuous, true = triggered
|
||||
bool _measurementTriggered : 1; // if triggered mode, then true indicates we're waiting for measurements
|
||||
uint16_t _settingInaConversionTimeUs : 12; // Conversion time, shift by 2
|
||||
uint16_t _settingInaSamples : 11; // Number of samples for averaging, max 1024
|
||||
|
||||
uint8_t _i2cAddress;
|
||||
uint16_t _checkInterval; // milliseconds, user settings is in seconds
|
||||
float _decimalFactor; // a power of 10 factor. 1 would be no change, 10 is one decimal, 100 is two etc. User sees a power of 10 (0, 1, 2, ..)
|
||||
uint16_t _shuntResistor; // Shunt resistor value in milliohms
|
||||
uint16_t _currentRange; // Expected maximum current in milliamps
|
||||
|
||||
uint8_t _lastStatus = 0;
|
||||
float _lastCurrent = 0;
|
||||
float _lastVoltage = 0;
|
||||
float _lastPower = 0;
|
||||
float _lastShuntVoltage = 0;
|
||||
bool _lastOverflow = false;
|
||||
|
||||
#ifndef WLED_MQTT_DISABLE
|
||||
float _lastCurrentSent = 0;
|
||||
float _lastVoltageSent = 0;
|
||||
float _lastPowerSent = 0;
|
||||
float _lastShuntVoltageSent = 0;
|
||||
bool _lastOverflowSent = false;
|
||||
#endif
|
||||
|
||||
INA226_WE *_ina226 = nullptr;
|
||||
|
||||
float truncateDecimals(float val)
|
||||
{
|
||||
return roundf(val * _decimalFactor) / _decimalFactor;
|
||||
}
|
||||
|
||||
void initializeINA226()
|
||||
{
|
||||
if (_ina226 != nullptr)
|
||||
{
|
||||
delete _ina226;
|
||||
}
|
||||
|
||||
_ina226 = new INA226_WE(_i2cAddress);
|
||||
if (!_ina226->init())
|
||||
{
|
||||
DEBUG_PRINTLN(F("INA226 initialization failed!"));
|
||||
return;
|
||||
}
|
||||
_ina226->setCorrectionFactor(1.0);
|
||||
|
||||
uint16_t tmpShort = _settingInaSamples;
|
||||
_ina226->setAverage(getAverageEnum(tmpShort));
|
||||
|
||||
tmpShort = _settingInaConversionTimeUs << 2;
|
||||
_ina226->setConversionTime(getConversionTimeEnum(tmpShort));
|
||||
|
||||
if (_checkInterval >= 20000)
|
||||
{
|
||||
_isTriggeredOperationMode = true;
|
||||
_ina226->setMeasureMode(TRIGGERED);
|
||||
}
|
||||
else
|
||||
{
|
||||
_isTriggeredOperationMode = false;
|
||||
_ina226->setMeasureMode(CONTINUOUS);
|
||||
}
|
||||
|
||||
_ina226->setResistorRange(static_cast<float>(_shuntResistor) / 1000.0, static_cast<float>(_currentRange) / 1000.0);
|
||||
}
|
||||
|
||||
void fetchAndPushValues()
|
||||
{
|
||||
_lastStatus = _ina226->getI2cErrorCode();
|
||||
|
||||
if (_lastStatus != 0)
|
||||
return;
|
||||
|
||||
float current = truncateDecimals(_ina226->getCurrent_mA() / 1000.0);
|
||||
float voltage = truncateDecimals(_ina226->getBusVoltage_V());
|
||||
float power = truncateDecimals(_ina226->getBusPower() / 1000.0);
|
||||
float shuntVoltage = truncateDecimals(_ina226->getShuntVoltage_V());
|
||||
bool overflow = _ina226->overflow;
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
mqttPublishIfChanged(F("current"), _lastCurrentSent, current, 0.01f);
|
||||
mqttPublishIfChanged(F("voltage"), _lastVoltageSent, voltage, 0.01f);
|
||||
mqttPublishIfChanged(F("power"), _lastPowerSent, power, 0.1f);
|
||||
mqttPublishIfChanged(F("shunt_voltage"), _lastShuntVoltageSent, shuntVoltage, 0.01f);
|
||||
mqttPublishIfChanged(F("overflow"), _lastOverflowSent, overflow);
|
||||
#endif
|
||||
|
||||
_lastCurrent = current;
|
||||
_lastVoltage = voltage;
|
||||
_lastPower = power;
|
||||
_lastShuntVoltage = shuntVoltage;
|
||||
_lastOverflow = overflow;
|
||||
}
|
||||
|
||||
void handleTriggeredMode(unsigned long currentTime)
|
||||
{
|
||||
if (_measurementTriggered)
|
||||
{
|
||||
// Test if we have a measurement every 400ms
|
||||
if (currentTime - _lastTriggerTime >= 400)
|
||||
{
|
||||
_lastTriggerTime = currentTime;
|
||||
if (_ina226->isBusy())
|
||||
return;
|
||||
|
||||
fetchAndPushValues();
|
||||
_measurementTriggered = false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (currentTime - _lastLoopCheck >= _checkInterval)
|
||||
{
|
||||
// Start a measurement and use isBusy() later to determine when it is done
|
||||
_ina226->startSingleMeasurementNoWait();
|
||||
_lastLoopCheck = currentTime;
|
||||
_lastTriggerTime = currentTime;
|
||||
_measurementTriggered = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void handleContinuousMode(unsigned long currentTime)
|
||||
{
|
||||
if (currentTime - _lastLoopCheck >= _checkInterval)
|
||||
{
|
||||
_lastLoopCheck = currentTime;
|
||||
fetchAndPushValues();
|
||||
}
|
||||
}
|
||||
|
||||
~UsermodINA226()
|
||||
{
|
||||
delete _ina226;
|
||||
_ina226 = nullptr;
|
||||
}
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
void mqttInitialize()
|
||||
{
|
||||
if (!WLED_MQTT_CONNECTED || !_mqttPublish || !_mqttHomeAssistant)
|
||||
return;
|
||||
|
||||
char topic[128];
|
||||
snprintf_P(topic, 127, "%s/current", mqttDeviceTopic);
|
||||
mqttCreateHassSensor(F("Current"), topic, F("current"), F("A"));
|
||||
|
||||
snprintf_P(topic, 127, "%s/voltage", mqttDeviceTopic);
|
||||
mqttCreateHassSensor(F("Voltage"), topic, F("voltage"), F("V"));
|
||||
|
||||
snprintf_P(topic, 127, "%s/power", mqttDeviceTopic);
|
||||
mqttCreateHassSensor(F("Power"), topic, F("power"), F("W"));
|
||||
|
||||
snprintf_P(topic, 127, "%s/shunt_voltage", mqttDeviceTopic);
|
||||
mqttCreateHassSensor(F("Shunt Voltage"), topic, F("voltage"), F("V"));
|
||||
|
||||
snprintf_P(topic, 127, "%s/overflow", mqttDeviceTopic);
|
||||
mqttCreateHassBinarySensor(F("Overflow"), topic);
|
||||
}
|
||||
|
||||
void mqttPublishIfChanged(const __FlashStringHelper *topic, float &lastState, float state, float minChange)
|
||||
{
|
||||
if (WLED_MQTT_CONNECTED && _mqttPublish && (_mqttPublishAlways || fabsf(lastState - state) > minChange))
|
||||
{
|
||||
char subuf[128];
|
||||
snprintf_P(subuf, 127, PSTR("%s/%s"), mqttDeviceTopic, (const char *)topic);
|
||||
mqtt->publish(subuf, 0, false, String(state).c_str());
|
||||
|
||||
lastState = state;
|
||||
}
|
||||
}
|
||||
|
||||
void mqttPublishIfChanged(const __FlashStringHelper *topic, bool &lastState, bool state)
|
||||
{
|
||||
if (WLED_MQTT_CONNECTED && _mqttPublish && (_mqttPublishAlways || lastState != state))
|
||||
{
|
||||
char subuf[128];
|
||||
snprintf_P(subuf, 127, PSTR("%s/%s"), mqttDeviceTopic, (const char *)topic);
|
||||
mqtt->publish(subuf, 0, false, state ? "true" : "false");
|
||||
|
||||
lastState = state;
|
||||
}
|
||||
}
|
||||
|
||||
void mqttCreateHassSensor(const String &name, const String &topic, const String &deviceClass, const String &unitOfMeasurement)
|
||||
{
|
||||
String t = String(F("homeassistant/sensor/")) + mqttClientID + "/" + name + F("/config");
|
||||
|
||||
StaticJsonDocument<600> doc;
|
||||
|
||||
doc[F("name")] = name;
|
||||
doc[F("state_topic")] = topic;
|
||||
doc[F("unique_id")] = String(mqttClientID) + name;
|
||||
if (unitOfMeasurement != "")
|
||||
doc[F("unit_of_measurement")] = unitOfMeasurement;
|
||||
if (deviceClass != "")
|
||||
doc[F("device_class")] = deviceClass;
|
||||
doc[F("expire_after")] = 1800;
|
||||
|
||||
JsonObject device = doc.createNestedObject(F("device"));
|
||||
device[F("name")] = serverDescription;
|
||||
device[F("identifiers")] = "wled-sensor-" + String(mqttClientID);
|
||||
device[F("manufacturer")] = F(WLED_BRAND);
|
||||
device[F("model")] = F(WLED_PRODUCT_NAME);
|
||||
device[F("sw_version")] = versionString;
|
||||
|
||||
String temp;
|
||||
serializeJson(doc, temp);
|
||||
DEBUG_PRINTLN(t);
|
||||
DEBUG_PRINTLN(temp);
|
||||
|
||||
mqtt->publish(t.c_str(), 0, true, temp.c_str());
|
||||
}
|
||||
|
||||
void mqttCreateHassBinarySensor(const String &name, const String &topic)
|
||||
{
|
||||
String t = String(F("homeassistant/binary_sensor/")) + mqttClientID + "/" + name + F("/config");
|
||||
|
||||
StaticJsonDocument<600> doc;
|
||||
|
||||
doc[F("name")] = name;
|
||||
doc[F("state_topic")] = topic;
|
||||
doc[F("unique_id")] = String(mqttClientID) + name;
|
||||
|
||||
JsonObject device = doc.createNestedObject(F("device"));
|
||||
device[F("name")] = serverDescription;
|
||||
device[F("identifiers")] = "wled-sensor-" + String(mqttClientID);
|
||||
device[F("manufacturer")] = F(WLED_BRAND);
|
||||
device[F("model")] = F(WLED_PRODUCT_NAME);
|
||||
device[F("sw_version")] = versionString;
|
||||
|
||||
String temp;
|
||||
serializeJson(doc, temp);
|
||||
DEBUG_PRINTLN(t);
|
||||
DEBUG_PRINTLN(temp);
|
||||
|
||||
mqtt->publish(t.c_str(), 0, true, temp.c_str());
|
||||
}
|
||||
#endif
|
||||
|
||||
public:
|
||||
UsermodINA226()
|
||||
{
|
||||
// Default values
|
||||
_settingInaSamples = DEFAULT_INASAMPLES;
|
||||
_settingInaConversionTimeUs = DEFAULT_INACONVERSIONTIME;
|
||||
|
||||
_i2cAddress = INA226_ADDRESS;
|
||||
_checkInterval = DEFAULT_CHECKINTERVAL;
|
||||
_decimalFactor = 100;
|
||||
_shuntResistor = 1000;
|
||||
_currentRange = 1000;
|
||||
}
|
||||
|
||||
void setup()
|
||||
{
|
||||
initializeINA226();
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
if (!_settingEnabled || strip.isUpdating())
|
||||
return;
|
||||
|
||||
unsigned long currentTime = millis();
|
||||
|
||||
if (_isTriggeredOperationMode)
|
||||
{
|
||||
handleTriggeredMode(currentTime);
|
||||
}
|
||||
else
|
||||
{
|
||||
handleContinuousMode(currentTime);
|
||||
}
|
||||
}
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
void onMqttConnect(bool sessionPresent)
|
||||
{
|
||||
mqttInitialize();
|
||||
}
|
||||
#endif
|
||||
|
||||
uint16_t getId()
|
||||
{
|
||||
return USERMOD_ID_INA226;
|
||||
}
|
||||
|
||||
void addToJsonInfo(JsonObject &root) override
|
||||
{
|
||||
JsonObject user = root["u"];
|
||||
if (user.isNull())
|
||||
user = root.createNestedObject("u");
|
||||
|
||||
#ifdef USERMOD_INA226_DEBUG
|
||||
JsonArray temp = user.createNestedArray(F("INA226 last loop"));
|
||||
temp.add(_lastLoopCheck);
|
||||
|
||||
temp = user.createNestedArray(F("INA226 last status"));
|
||||
temp.add(_lastStatus);
|
||||
|
||||
temp = user.createNestedArray(F("INA226 average samples"));
|
||||
temp.add(_settingInaSamples);
|
||||
temp.add(F("samples"));
|
||||
|
||||
temp = user.createNestedArray(F("INA226 conversion time"));
|
||||
temp.add(_settingInaConversionTimeUs << 2);
|
||||
temp.add(F("μs"));
|
||||
|
||||
// INA226 uses (2 * conversion time * samples) time to take a reading.
|
||||
temp = user.createNestedArray(F("INA226 expected sample time"));
|
||||
uint32_t sampleTimeNeededUs = (static_cast<uint32_t>(_settingInaConversionTimeUs) << 2) * _settingInaSamples * 2;
|
||||
temp.add(truncateDecimals(sampleTimeNeededUs / 1000.0));
|
||||
temp.add(F("ms"));
|
||||
|
||||
temp = user.createNestedArray(F("INA226 mode"));
|
||||
temp.add(_isTriggeredOperationMode ? F("triggered") : F("continuous"));
|
||||
|
||||
if (_isTriggeredOperationMode)
|
||||
{
|
||||
temp = user.createNestedArray(F("INA226 triggered"));
|
||||
temp.add(_measurementTriggered ? F("waiting for measurement") : F(""));
|
||||
}
|
||||
#endif
|
||||
|
||||
JsonArray jsonCurrent = user.createNestedArray(F("Current"));
|
||||
JsonArray jsonVoltage = user.createNestedArray(F("Voltage"));
|
||||
JsonArray jsonPower = user.createNestedArray(F("Power"));
|
||||
JsonArray jsonShuntVoltage = user.createNestedArray(F("Shunt Voltage"));
|
||||
JsonArray jsonOverflow = user.createNestedArray(F("Overflow"));
|
||||
|
||||
if (_lastLoopCheck == 0)
|
||||
{
|
||||
jsonCurrent.add(F("Not read yet"));
|
||||
jsonVoltage.add(F("Not read yet"));
|
||||
jsonPower.add(F("Not read yet"));
|
||||
jsonShuntVoltage.add(F("Not read yet"));
|
||||
jsonOverflow.add(F("Not read yet"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (_lastStatus != 0)
|
||||
{
|
||||
jsonCurrent.add(F("An error occurred"));
|
||||
jsonVoltage.add(F("An error occurred"));
|
||||
jsonPower.add(F("An error occurred"));
|
||||
jsonShuntVoltage.add(F("An error occurred"));
|
||||
jsonOverflow.add(F("An error occurred"));
|
||||
return;
|
||||
}
|
||||
|
||||
jsonCurrent.add(_lastCurrent);
|
||||
jsonCurrent.add(F("A"));
|
||||
|
||||
jsonVoltage.add(_lastVoltage);
|
||||
jsonVoltage.add(F("V"));
|
||||
|
||||
jsonPower.add(_lastPower);
|
||||
jsonPower.add(F("W"));
|
||||
|
||||
jsonShuntVoltage.add(_lastShuntVoltage);
|
||||
jsonShuntVoltage.add(F("V"));
|
||||
|
||||
jsonOverflow.add(_lastOverflow ? F("true") : F("false"));
|
||||
}
|
||||
|
||||
void addToConfig(JsonObject &root)
|
||||
{
|
||||
JsonObject top = root.createNestedObject(FPSTR(_name));
|
||||
top[F("Enabled")] = _settingEnabled;
|
||||
top[F("I2CAddress")] = static_cast<uint8_t>(_i2cAddress);
|
||||
top[F("CheckInterval")] = _checkInterval / 1000;
|
||||
top[F("INASamples")] = _settingInaSamples;
|
||||
top[F("INAConversionTime")] = _settingInaConversionTimeUs << 2;
|
||||
top[F("Decimals")] = log10f(_decimalFactor);
|
||||
top[F("ShuntResistor")] = _shuntResistor;
|
||||
top[F("CurrentRange")] = _currentRange;
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
top[F("MqttPublish")] = _mqttPublish;
|
||||
top[F("MqttPublishAlways")] = _mqttPublishAlways;
|
||||
top[F("MqttHomeAssistantDiscovery")] = _mqttHomeAssistant;
|
||||
#endif
|
||||
|
||||
DEBUG_PRINTLN(F("INA226 config saved."));
|
||||
}
|
||||
|
||||
bool readFromConfig(JsonObject &root) override
|
||||
{
|
||||
JsonObject top = root[FPSTR(_name)];
|
||||
|
||||
bool configComplete = !top.isNull();
|
||||
if (!configComplete)
|
||||
return false;
|
||||
|
||||
bool tmpBool;
|
||||
if (getJsonValue(top[F("Enabled")], tmpBool))
|
||||
_settingEnabled = tmpBool;
|
||||
else
|
||||
configComplete = false;
|
||||
|
||||
configComplete &= getJsonValue(top[F("I2CAddress")], _i2cAddress);
|
||||
if (getJsonValue(top[F("CheckInterval")], _checkInterval))
|
||||
{
|
||||
if (1 <= _checkInterval && _checkInterval <= 600)
|
||||
_checkInterval *= 1000;
|
||||
else
|
||||
_checkInterval = DEFAULT_CHECKINTERVAL;
|
||||
}
|
||||
else
|
||||
configComplete = false;
|
||||
|
||||
uint16_t tmpShort;
|
||||
if (getJsonValue(top[F("INASamples")], tmpShort))
|
||||
{
|
||||
// The method below will fix the provided value to a valid one
|
||||
getAverageEnum(tmpShort);
|
||||
_settingInaSamples = tmpShort;
|
||||
}
|
||||
else
|
||||
configComplete = false;
|
||||
|
||||
if (getJsonValue(top[F("INAConversionTime")], tmpShort))
|
||||
{
|
||||
// The method below will fix the provided value to a valid one
|
||||
getConversionTimeEnum(tmpShort);
|
||||
_settingInaConversionTimeUs = tmpShort >> 2;
|
||||
}
|
||||
else
|
||||
configComplete = false;
|
||||
|
||||
if (getJsonValue(top[F("Decimals")], _decimalFactor))
|
||||
{
|
||||
if (0 <= _decimalFactor && _decimalFactor <= 5)
|
||||
_decimalFactor = pow10f(_decimalFactor);
|
||||
else
|
||||
_decimalFactor = 100;
|
||||
}
|
||||
else
|
||||
configComplete = false;
|
||||
|
||||
configComplete &= getJsonValue(top[F("ShuntResistor")], _shuntResistor);
|
||||
configComplete &= getJsonValue(top[F("CurrentRange")], _currentRange);
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
if (getJsonValue(top[F("MqttPublish")], tmpBool))
|
||||
_mqttPublish = tmpBool;
|
||||
else
|
||||
configComplete = false;
|
||||
|
||||
if (getJsonValue(top[F("MqttPublishAlways")], tmpBool))
|
||||
_mqttPublishAlways = tmpBool;
|
||||
else
|
||||
configComplete = false;
|
||||
|
||||
if (getJsonValue(top[F("MqttHomeAssistantDiscovery")], tmpBool))
|
||||
_mqttHomeAssistant = tmpBool;
|
||||
else
|
||||
configComplete = false;
|
||||
#endif
|
||||
|
||||
if (_initDone)
|
||||
{
|
||||
initializeINA226();
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
mqttInitialize();
|
||||
#endif
|
||||
}
|
||||
|
||||
_initDone = true;
|
||||
return configComplete;
|
||||
}
|
||||
};
|
||||
|
||||
const char UsermodINA226::_name[] PROGMEM = "INA226";
|
||||
BIN
usermods/Internal_Temperature_v2/assets/screenshot_info.png
Normal file
|
After Width: | Height: | Size: 132 KiB |
BIN
usermods/Internal_Temperature_v2/assets/screenshot_settings.png
Normal file
|
After Width: | Height: | Size: 59 KiB |
@@ -1,17 +1,44 @@
|
||||
# Internal Temperature Usermod
|
||||
This usermod adds the temperature readout to the Info tab and also publishes that over the topic `mcutemp` topic.
|
||||
|
||||
## Important
|
||||
A shown temp of 53,33°C might indicate that the internal temp is not supported.
|
||||

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

|
||||
|
||||
|
||||
## Features
|
||||
- 🌡️ Adds the internal temperature readout of the chip to the `Info` tab
|
||||
- 🥵 High temperature indicator/action. (Configurable threshold and preset)
|
||||
- 📣 Publishes the internal temperature over the MQTT topic: `mcutemp`
|
||||
|
||||
|
||||
## Use Examples
|
||||
- Warn of excessive/damaging temperatures by the triggering of a 'warning' preset
|
||||
- Activate a cooling fan (when used with the multi-relay usermod)
|
||||
|
||||
|
||||
## Compatibility
|
||||
- A shown temp of 53,33°C might indicate that the internal temp is not supported
|
||||
- ESP8266 does not have a internal temp sensor -> Disabled (Indicated with a readout of '-1')
|
||||
- ESP32S2 seems to crash on reading the sensor -> Disabled (Indicated with a readout of '-1')
|
||||
|
||||
ESP32S2 seems to crash on reading the sensor -> disabled
|
||||
|
||||
## Installation
|
||||
Add a build flag `-D USERMOD_INTERNAL_TEMPERATURE` to your `platformio.ini` (or `platformio_override.ini`).
|
||||
- Add a build flag `-D USERMOD_INTERNAL_TEMPERATURE` to your `platformio.ini` (or `platformio_override.ini`).
|
||||
|
||||
|
||||
## 📝 Change Log
|
||||
|
||||
2024-06-26
|
||||
|
||||
- Added "high-temperature-indication" feature
|
||||
- Documentation updated
|
||||
|
||||
2023-09-01
|
||||
|
||||
* "Internal Temperature" usermod created
|
||||
|
||||
|
||||
## Authors
|
||||
Soeren Willrodt [@lost-hope](https://github.com/lost-hope)
|
||||
|
||||
Dimitry Zhemkov [@dima-zhemkov](https://github.com/dima-zhemkov)
|
||||
- Soeren Willrodt [@lost-hope](https://github.com/lost-hope)
|
||||
- Dimitry Zhemkov [@dima-zhemkov](https://github.com/dima-zhemkov)
|
||||
- Adam Matthews [@adamsthws](https://github.com/adamsthws)
|
||||
|
||||
@@ -6,14 +6,23 @@ class InternalTemperatureUsermod : public Usermod
|
||||
{
|
||||
|
||||
private:
|
||||
static constexpr unsigned long minLoopInterval = 1000; // minimum allowable interval (ms)
|
||||
unsigned long loopInterval = 10000;
|
||||
unsigned long lastTime = 0;
|
||||
bool isEnabled = false;
|
||||
float temperature = 0;
|
||||
float temperature = 0.0f;
|
||||
uint8_t previousPlaylist = 0; // Stores the playlist that was active before high-temperature activation
|
||||
uint8_t previousPreset = 0; // Stores the preset that was active before high-temperature activation
|
||||
uint8_t presetToActivate = 0; // Preset to activate when temp goes above threshold (0 = disabled)
|
||||
float activationThreshold = 95.0f; // Temperature threshold to trigger high-temperature actions
|
||||
float resetMargin = 2.0f; // Margin below the activation threshold (Prevents frequent toggling when close to threshold)
|
||||
bool isAboveThreshold = false; // Flag to track if the high temperature preset is currently active
|
||||
|
||||
static const char _name[];
|
||||
static const char _enabled[];
|
||||
static const char _loopInterval[];
|
||||
static const char _activationThreshold[];
|
||||
static const char _presetToActivate[];
|
||||
|
||||
// any private methods should go here (non-inline method should be defined out of class)
|
||||
void publishMqtt(const char *state, bool retain = false); // example for publishing MQTT message
|
||||
@@ -32,6 +41,7 @@ public:
|
||||
|
||||
lastTime = millis();
|
||||
|
||||
// Measure the temperature
|
||||
#ifdef ESP8266 // ESP8266
|
||||
// does not seem possible
|
||||
temperature = -1;
|
||||
@@ -40,6 +50,58 @@ public:
|
||||
#else // ESP32 ESP32S3 and ESP32C3
|
||||
temperature = roundf(temperatureRead() * 10) / 10;
|
||||
#endif
|
||||
if(presetToActivate != 0){
|
||||
// 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 (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 +142,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 +178,8 @@ public:
|
||||
const char InternalTemperatureUsermod::_name[] PROGMEM = "Internal Temperature";
|
||||
const char InternalTemperatureUsermod::_enabled[] PROGMEM = "Enabled";
|
||||
const char InternalTemperatureUsermod::_loopInterval[] PROGMEM = "Loop Interval";
|
||||
const char InternalTemperatureUsermod::_activationThreshold[] PROGMEM = "Activation Threshold";
|
||||
const char InternalTemperatureUsermod::_presetToActivate[] PROGMEM = "Preset To Activate";
|
||||
|
||||
void InternalTemperatureUsermod::publishMqtt(const char *state, bool retain)
|
||||
{
|
||||
|
||||
36
usermods/LD2410_v2/readme.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# BH1750 usermod
|
||||
|
||||
> This usermod requires a second UART and was only tested on the ESP32
|
||||
|
||||
|
||||
This usermod will read from a LD2410 movement/presence sensor.
|
||||
|
||||
The movement and presence state are displayed in both the Info section of the web UI, as well as published to the `/movement` and `/stationary` MQTT topics respectively.
|
||||
|
||||
## Dependencies
|
||||
- Libraries
|
||||
- `ncmreynolds/ld2410@^0.1.3`
|
||||
- This must be added under `lib_deps` in your `platformio.ini` (or `platformio_override.ini`).
|
||||
- Data is published over MQTT - make sure you've enabled the MQTT sync interface.
|
||||
|
||||
## Compilation
|
||||
|
||||
To enable, compile with `USERMOD_LD2410` defined (e.g. in `platformio_override.ini`)
|
||||
```ini
|
||||
[env:usermod_USERMOD_LD2410_esp32dev]
|
||||
extends = env:esp32dev
|
||||
build_flags =
|
||||
${common.build_flags_esp32}
|
||||
-D USERMOD_LD2410
|
||||
lib_deps =
|
||||
${esp32.lib_deps}
|
||||
ncmreynolds/ld2410@^0.1.3
|
||||
```
|
||||
|
||||
### Configuration Options
|
||||
The Usermod screen allows you to:
|
||||
- enable/disable the usermod
|
||||
- Configure the RX/TX pins
|
||||
|
||||
## Change log
|
||||
- 2024-06 Created by @wesleygas (https://github.com/wesleygas/)
|
||||
237
usermods/LD2410_v2/usermod_ld2410.h
Normal file
@@ -0,0 +1,237 @@
|
||||
#warning **** Included USERMOD_LD2410 ****
|
||||
|
||||
#ifndef WLED_ENABLE_MQTT
|
||||
#error "This user mod requires MQTT to be enabled."
|
||||
#endif
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "wled.h"
|
||||
#include <ld2410.h>
|
||||
|
||||
class LD2410Usermod : public Usermod {
|
||||
|
||||
private:
|
||||
|
||||
bool enabled = true;
|
||||
bool initDone = false;
|
||||
bool sensorFound = false;
|
||||
unsigned long lastTime = 0;
|
||||
unsigned long last_mqtt_sent = 0;
|
||||
|
||||
int8_t default_uart_rx = 19;
|
||||
int8_t default_uart_tx = 18;
|
||||
|
||||
|
||||
String mqttMovementTopic = F("");
|
||||
String mqttStationaryTopic = F("");
|
||||
bool mqttInitialized = false;
|
||||
bool HomeAssistantDiscovery = true; // Publish Home Assistant Discovery messages
|
||||
|
||||
|
||||
ld2410 radar;
|
||||
bool stationary_detected = false;
|
||||
bool last_stationary_state = false;
|
||||
bool movement_detected = false;
|
||||
bool last_movement_state = false;
|
||||
|
||||
// These config variables have defaults set inside readFromConfig()
|
||||
int8_t uart_rx_pin;
|
||||
int8_t uart_tx_pin;
|
||||
|
||||
// string that are used multiple time (this will save some flash memory)
|
||||
static const char _name[];
|
||||
static const char _enabled[];
|
||||
|
||||
void publishMqtt(const char* topic, const char* state, bool retain); // example for publishing MQTT message
|
||||
|
||||
void _mqttInitialize()
|
||||
{
|
||||
mqttMovementTopic = String(mqttDeviceTopic) + F("/ld2410/movement");
|
||||
mqttStationaryTopic = String(mqttDeviceTopic) + F("/ld2410/stationary");
|
||||
if (HomeAssistantDiscovery){
|
||||
_createMqttSensor(F("Movement"), mqttMovementTopic, F("motion"), F(""));
|
||||
_createMqttSensor(F("Stationary"), mqttStationaryTopic, F("occupancy"), F(""));
|
||||
}
|
||||
}
|
||||
|
||||
// Create an MQTT Sensor for Home Assistant Discovery purposes, this includes a pointer to the topic that is published to in the Loop.
|
||||
void _createMqttSensor(const String &name, const String &topic, const String &deviceClass, const String &unitOfMeasurement)
|
||||
{
|
||||
String t = String(F("homeassistant/binary_sensor/")) + mqttClientID + F("/") + name + F("/config");
|
||||
|
||||
StaticJsonDocument<600> doc;
|
||||
|
||||
doc[F("name")] = String(serverDescription) + F(" Module");
|
||||
doc[F("state_topic")] = topic;
|
||||
doc[F("unique_id")] = String(mqttClientID) + name;
|
||||
if (unitOfMeasurement != "")
|
||||
doc[F("unit_of_measurement")] = unitOfMeasurement;
|
||||
if (deviceClass != "")
|
||||
doc[F("device_class")] = deviceClass;
|
||||
doc[F("expire_after")] = 1800;
|
||||
doc[F("payload_off")] = "OFF";
|
||||
doc[F("payload_on")] = "ON";
|
||||
|
||||
JsonObject device = doc.createNestedObject(F("device")); // attach the sensor to the same device
|
||||
device[F("name")] = serverDescription;
|
||||
device[F("identifiers")] = "wled-sensor-" + String(mqttClientID);
|
||||
device[F("manufacturer")] = F("WLED");
|
||||
device[F("model")] = F("FOSS");
|
||||
device[F("sw_version")] = versionString;
|
||||
|
||||
String temp;
|
||||
serializeJson(doc, temp);
|
||||
DEBUG_PRINTLN(t);
|
||||
DEBUG_PRINTLN(temp);
|
||||
|
||||
mqtt->publish(t.c_str(), 0, true, temp.c_str());
|
||||
}
|
||||
|
||||
public:
|
||||
|
||||
inline bool isEnabled() { return enabled; }
|
||||
|
||||
void setup() {
|
||||
Serial1.begin(256000, SERIAL_8N1, uart_rx_pin, uart_tx_pin);
|
||||
Serial.print(F("\nLD2410 radar sensor initialising: "));
|
||||
if(radar.begin(Serial1)){
|
||||
Serial.println(F("OK"));
|
||||
} else {
|
||||
Serial.println(F("not connected"));
|
||||
}
|
||||
initDone = true;
|
||||
}
|
||||
|
||||
|
||||
void loop() {
|
||||
// NOTE: on very long strips strip.isUpdating() may always return true so update accordingly
|
||||
if (!enabled || strip.isUpdating()) return;
|
||||
radar.read();
|
||||
unsigned long curr_time = millis();
|
||||
if(curr_time - lastTime > 1000) //Try to Report every 1000ms
|
||||
{
|
||||
lastTime = curr_time;
|
||||
sensorFound = radar.isConnected();
|
||||
if(!sensorFound) return;
|
||||
stationary_detected = radar.presenceDetected();
|
||||
if(stationary_detected != last_stationary_state){
|
||||
if (WLED_MQTT_CONNECTED){
|
||||
publishMqtt("/ld2410/stationary", stationary_detected ? "ON":"OFF", false);
|
||||
last_stationary_state = stationary_detected;
|
||||
}
|
||||
}
|
||||
movement_detected = radar.movingTargetDetected();
|
||||
if(movement_detected != last_movement_state){
|
||||
if (WLED_MQTT_CONNECTED){
|
||||
publishMqtt("/ld2410/movement", movement_detected ? "ON":"OFF", false);
|
||||
last_movement_state = movement_detected;
|
||||
}
|
||||
}
|
||||
// If there hasn't been any activity, send current state to confirm sensor is alive
|
||||
if(curr_time - last_mqtt_sent > 1000*60*5 && WLED_MQTT_CONNECTED){
|
||||
publishMqtt("/ld2410/stationary", stationary_detected ? "ON":"OFF", false);
|
||||
publishMqtt("/ld2410/movement", movement_detected ? "ON":"OFF", false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void addToJsonInfo(JsonObject& root)
|
||||
{
|
||||
// if "u" object does not exist yet wee need to create it
|
||||
JsonObject user = root[F("u")];
|
||||
if (user.isNull()) user = root.createNestedObject(F("u"));
|
||||
|
||||
JsonArray ld2410_sta_json = user.createNestedArray(F("LD2410 Stationary"));
|
||||
JsonArray ld2410_mov_json = user.createNestedArray(F("LD2410 Movement"));
|
||||
if (!enabled){
|
||||
ld2410_sta_json.add(F("disabled"));
|
||||
ld2410_mov_json.add(F("disabled"));
|
||||
} else if(!sensorFound){
|
||||
ld2410_sta_json.add(F("LD2410"));
|
||||
ld2410_sta_json.add(" Not Found");
|
||||
} else {
|
||||
ld2410_sta_json.add("Sta ");
|
||||
ld2410_sta_json.add(stationary_detected ? "ON":"OFF");
|
||||
ld2410_mov_json.add("Mov ");
|
||||
ld2410_mov_json.add(movement_detected ? "ON":"OFF");
|
||||
}
|
||||
}
|
||||
|
||||
void addToConfig(JsonObject& root)
|
||||
{
|
||||
JsonObject top = root.createNestedObject(FPSTR(_name));
|
||||
top[FPSTR(_enabled)] = enabled;
|
||||
//save these vars persistently whenever settings are saved
|
||||
top["uart_rx_pin"] = default_uart_rx;
|
||||
top["uart_tx_pin"] = default_uart_tx;
|
||||
}
|
||||
|
||||
|
||||
bool readFromConfig(JsonObject& root)
|
||||
{
|
||||
// default settings values could be set here (or below using the 3-argument getJsonValue()) instead of in the class definition or constructor
|
||||
// setting them inside readFromConfig() is slightly more robust, handling the rare but plausible use case of single value being missing after boot (e.g. if the cfg.json was manually edited and a value was removed)
|
||||
|
||||
JsonObject top = root[FPSTR(_name)];
|
||||
|
||||
bool configComplete = !top.isNull();
|
||||
if (!configComplete)
|
||||
{
|
||||
DEBUG_PRINT(FPSTR(_name));
|
||||
DEBUG_PRINT(F("LD2410"));
|
||||
DEBUG_PRINTLN(F(": No config found. (Using defaults.)"));
|
||||
return false;
|
||||
}
|
||||
|
||||
configComplete &= getJsonValue(top["uart_rx_pin"], uart_rx_pin, default_uart_rx);
|
||||
configComplete &= getJsonValue(top["uart_tx_pin"], uart_tx_pin, default_uart_tx);
|
||||
|
||||
return configComplete;
|
||||
}
|
||||
|
||||
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
/**
|
||||
* onMqttConnect() is called when MQTT connection is established
|
||||
*/
|
||||
void onMqttConnect(bool sessionPresent) {
|
||||
// do any MQTT related initialisation here
|
||||
if(!radar.isConnected()) return;
|
||||
publishMqtt("/ld2410/status", "I am alive!", false);
|
||||
if (!mqttInitialized)
|
||||
{
|
||||
_mqttInitialize();
|
||||
mqttInitialized = true;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
uint16_t getId()
|
||||
{
|
||||
return USERMOD_ID_LD2410;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// add more strings here to reduce flash memory usage
|
||||
const char LD2410Usermod::_name[] PROGMEM = "LD2410Usermod";
|
||||
const char LD2410Usermod::_enabled[] PROGMEM = "enabled";
|
||||
|
||||
|
||||
// implementation of non-inline member methods
|
||||
|
||||
void LD2410Usermod::publishMqtt(const char* topic, const char* state, bool retain)
|
||||
{
|
||||
#ifndef WLED_DISABLE_MQTT
|
||||
//Check if MQTT Connected, otherwise it will crash
|
||||
if (WLED_MQTT_CONNECTED) {
|
||||
last_mqtt_sent = millis();
|
||||
char subuf[64];
|
||||
strcpy(subuf, mqttDeviceTopic);
|
||||
strcat(subuf, topic);
|
||||
mqtt->publish(subuf, 0, retain, state);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -58,7 +58,11 @@ private:
|
||||
bool sensorPinState[PIR_SENSOR_MAX_SENSORS] = {LOW}; // current PIR sensor pin state
|
||||
|
||||
// configurable parameters
|
||||
#if PIR_SENSOR_PIN < 0
|
||||
bool enabled = false; // PIR sensor disabled
|
||||
#else
|
||||
bool enabled = true; // PIR sensor enabled
|
||||
#endif
|
||||
int8_t PIRsensorPin[PIR_SENSOR_MAX_SENSORS] = {PIR_SENSOR_PIN}; // PIR sensor pin
|
||||
uint32_t m_switchOffDelay = PIR_SENSOR_OFF_SEC*1000; // delay before switch off after the sensor state goes LOW (10min)
|
||||
uint8_t m_onPreset = 0; // on preset
|
||||
@@ -371,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
|
||||
@@ -507,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);
|
||||
@@ -560,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();
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
#include "wled.h"
|
||||
|
||||
//Pin defaults for QuinLed Dig-Uno (A0)
|
||||
#ifndef PHOTORESISTOR_PIN
|
||||
#define PHOTORESISTOR_PIN A0
|
||||
#endif
|
||||
|
||||
// the frequency to check photoresistor, 10 seconds
|
||||
#ifndef USERMOD_SN_PHOTORESISTOR_MEASUREMENT_INTERVAL
|
||||
@@ -207,4 +209,4 @@ const char Usermod_SN_Photoresistor::_readInterval[] PROGMEM = "read-interval-s"
|
||||
const char Usermod_SN_Photoresistor::_referenceVoltage[] PROGMEM = "supplied-voltage";
|
||||
const char Usermod_SN_Photoresistor::_resistorValue[] PROGMEM = "resistor-value";
|
||||
const char Usermod_SN_Photoresistor::_adcPrecision[] PROGMEM = "adc-precision";
|
||||
const char Usermod_SN_Photoresistor::_offset[] PROGMEM = "offset";
|
||||
const char Usermod_SN_Photoresistor::_offset[] PROGMEM = "offset";
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ public:
|
||||
{
|
||||
if (width > 32)
|
||||
{
|
||||
throw std::invalid_argument("maximal width is 32");
|
||||
this->width = 32;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,6 +112,17 @@ public:
|
||||
{
|
||||
return pixels[y] == (uint32_t)((1 << width) - 1);
|
||||
}
|
||||
|
||||
void reset()
|
||||
{
|
||||
if (width > 32)
|
||||
{
|
||||
width = 32;
|
||||
}
|
||||
|
||||
pixels.clear();
|
||||
pixels.resize(height);
|
||||
}
|
||||
};
|
||||
|
||||
#endif /* __GRIDBW_H__ */
|
||||
@@ -127,6 +127,14 @@ public:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void reset()
|
||||
{
|
||||
gridBW.reset();
|
||||
pixels.clear();
|
||||
pixels.resize(width* height);
|
||||
clear();
|
||||
}
|
||||
};
|
||||
|
||||
#endif /* __GRIDCOLOR_H__ */
|
||||
@@ -32,7 +32,7 @@ public:
|
||||
uint8_t fullLines;
|
||||
uint16_t bumpiness;
|
||||
uint16_t aggregatedHeight;
|
||||
double score;
|
||||
float score;
|
||||
uint8_t width;
|
||||
std::vector<uint8_t> lineHights;
|
||||
|
||||
@@ -57,7 +57,7 @@ public:
|
||||
this->fullLines = 0;
|
||||
this->bumpiness = 0;
|
||||
this->aggregatedHeight = 0;
|
||||
this->score = -DBL_MAX;
|
||||
this->score = -FLT_MAX;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
# Tetris AI effect usermod
|
||||
|
||||
This usermod brings you a effect brings a self playing Tetris game. The mod needs version 0.14 or above as it is based on matrix support. The effect was tested on an ESP32 with a WS2812B 16x16 matrix.
|
||||
This usermod adds a self-playing Tetris game as an 'effect'. The mod requires version 0.14 or higher as it relies on matrix support. The effect was tested on an ESP32 4MB with a WS2812B 16x16 matrix.
|
||||
|
||||
Version 1.0
|
||||
|
||||
## Installation
|
||||
|
||||
Just activate the usermod with `-D USERMOD_TETRISAI` and the effect will become available under the name 'Tetris AI'.
|
||||
Just activate the usermod with `-D USERMOD_TETRISAI` and the effect will become available under the name 'Tetris AI'. If you are running out of flash memory, use a different memory layout (e.g. [WLED_ESP32_4MB_256KB_FS.csv](https://github.com/Aircoookie/WLED/blob/main/tools/WLED_ESP32_4MB_256KB_FS.csv)).
|
||||
|
||||
If needed simply add to `platformio_override.ini` (or `platformio_override.ini`):
|
||||
|
||||
```ini
|
||||
board_build.partitions = tools/WLED_ESP32_4MB_256KB_FS.csv
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
It is best to set the background color to black, the border color to light grey and the game over color (foreground) to dark grey.
|
||||
It is best to set the background color to black 🖤, the border color to light grey 🤍, the game over color (foreground) to dark grey 🩶, and color palette to 'Rainbow' 🌈.
|
||||
|
||||
### Sliders and boxes
|
||||
|
||||
@@ -19,15 +25,18 @@ It is best to set the background color to black, the border color to light grey
|
||||
* speed: speed the game plays
|
||||
* look ahead: how many pieces is the AI allowed to know the next pieces (0 - 2)
|
||||
* intelligence: how good the AI will play
|
||||
* Rotate color: make the colors shift (rotate) every few cicles
|
||||
* Mistakes free: how many good moves between mistakes (if activated)
|
||||
* Rotate color: make the colors shift (rotate) every few moves
|
||||
* Mistakes free: how many good moves between mistakes (if enabled)
|
||||
|
||||
#### Checkboxes
|
||||
|
||||
* show next: if true a space of 5 pixels from the right is used to show the next pieces. The whole segment is used for the grid otherwise.
|
||||
* show next: if true, a space of 5 pixels from the right will be used to show the next pieces. Otherwise the whole segment is used for the grid.
|
||||
* show border: if true an additional column of 1 pixel is used to draw a border between the grid and the next pieces
|
||||
* mistakes: if true the worst instead of the best move is choosen every few moves (read above)
|
||||
* mistakes: if true, the worst decision will be made every few moves instead of the best (see above).
|
||||
|
||||
## Best results
|
||||
|
||||
If the speed is set to be a little bit faster than a good human could play with maximal intelligence and very few mistakes it makes people furious/happy at a party.
|
||||
If the speed is set to be a little bit faster than a good human could play with maximal intelligence and very few mistakes it makes people furious/happy at a party 😉.
|
||||
|
||||
## Limits
|
||||
The game grid is limited to a maximum width of 32 and a maximum height of 255 due to the internal structure of the code. The canvas of the effect will be centred in the segment if the segment exceeds the maximum width or height.
|
||||
@@ -22,10 +22,10 @@ class TetrisAI
|
||||
{
|
||||
private:
|
||||
public:
|
||||
double aHeight;
|
||||
double fullLines;
|
||||
double holes;
|
||||
double bumpiness;
|
||||
float aHeight;
|
||||
float fullLines;
|
||||
float holes;
|
||||
float bumpiness;
|
||||
bool findWorstMove = false;
|
||||
|
||||
uint8_t countOnes(uint32_t vector)
|
||||
@@ -107,10 +107,10 @@ public:
|
||||
rating->score = (aHeight * (rating->aggregatedHeight)) + (fullLines * (rating->fullLines)) + (holes * (rating->holes)) + (bumpiness * (rating->bumpiness));
|
||||
}
|
||||
|
||||
TetrisAI(): TetrisAI(-0.510066, 0.760666, -0.35663, -0.184483)
|
||||
TetrisAI(): TetrisAI(-0.510066f, 0.760666f, -0.35663f, -0.184483f)
|
||||
{}
|
||||
|
||||
TetrisAI(double aHeight, double fullLines, double holes, double bumpiness):
|
||||
TetrisAI(float aHeight, float fullLines, float holes, float bumpiness):
|
||||
aHeight(aHeight),
|
||||
fullLines(fullLines),
|
||||
holes(holes),
|
||||
@@ -178,9 +178,9 @@ public:
|
||||
if(findWorstMove)
|
||||
{
|
||||
//init rating for worst
|
||||
if(bestRating->score == -DBL_MAX)
|
||||
if(bestRating->score == -FLT_MAX)
|
||||
{
|
||||
bestRating->score = DBL_MAX;
|
||||
bestRating->score = FLT_MAX;
|
||||
}
|
||||
|
||||
// update if we found a worse one
|
||||
@@ -202,101 +202,6 @@ public:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool findBestMoveNonBlocking(GridBW grid, std::vector<Piece>::iterator start, std::vector<Piece>::iterator end, Rating* bestRating)
|
||||
{
|
||||
//vector with pieces
|
||||
//for every piece
|
||||
//for every
|
||||
switch (expression)
|
||||
{
|
||||
case INIT:
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
bool findBestMoveNonBlocking(GridBW grid, std::vector<Piece>::iterator start, std::vector<Piece>::iterator end, Rating* bestRating)
|
||||
{
|
||||
//INIT
|
||||
grid.cleanupFullLines();
|
||||
Rating curRating(grid.width);
|
||||
Rating deeperRating(grid.width);
|
||||
Piece piece = *start;
|
||||
|
||||
// for every rotation of the piece
|
||||
piece.rotation = 0;
|
||||
|
||||
//HANDLE
|
||||
while (piece.rotation < piece.pieceData->rotCount)
|
||||
{
|
||||
// put piece to top left corner
|
||||
piece.x = 0;
|
||||
piece.y = 0;
|
||||
|
||||
//test for every column
|
||||
piece.x = 0;
|
||||
while (piece.x <= grid.width - piece.getRotation().width)
|
||||
{
|
||||
|
||||
//todo optimise by the use of the previous grids height
|
||||
piece.landingY = 0;
|
||||
//will set landingY to final position
|
||||
grid.findLandingPosition(&piece);
|
||||
|
||||
// draw piece
|
||||
grid.placePiece(&piece, piece.x, piece.landingY);
|
||||
|
||||
if(start == end - 1)
|
||||
{
|
||||
//at the deepest level
|
||||
updateRating(grid, &curRating);
|
||||
}
|
||||
else
|
||||
{
|
||||
//go deeper to take another piece into account
|
||||
findBestMove(grid, start + 1, end, &deeperRating);
|
||||
curRating = deeperRating;
|
||||
}
|
||||
|
||||
// eraese piece
|
||||
grid.erasePiece(&piece, piece.x, piece.landingY);
|
||||
|
||||
if(findWorstMove)
|
||||
{
|
||||
//init rating for worst
|
||||
if(bestRating->score == -DBL_MAX)
|
||||
{
|
||||
bestRating->score = DBL_MAX;
|
||||
}
|
||||
|
||||
// update if we found a worse one
|
||||
if (bestRating->score > curRating.score)
|
||||
{
|
||||
*bestRating = curRating;
|
||||
(*start) = piece;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// update if we found a better one
|
||||
if (bestRating->score < curRating.score)
|
||||
{
|
||||
*bestRating = curRating;
|
||||
(*start) = piece;
|
||||
}
|
||||
}
|
||||
piece.x++;
|
||||
}
|
||||
piece.rotation++;
|
||||
}
|
||||
|
||||
//EXIT
|
||||
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
#endif /* __AI_H__ */
|
||||
@@ -54,6 +54,7 @@ public:
|
||||
uint8_t width;
|
||||
uint8_t height;
|
||||
uint8_t nLookAhead;
|
||||
uint8_t nPieces;
|
||||
TetrisBag bag;
|
||||
GridColor grid;
|
||||
TetrisAI ai;
|
||||
@@ -65,6 +66,7 @@ public:
|
||||
width(width),
|
||||
height(height),
|
||||
nLookAhead(nLookAhead),
|
||||
nPieces(nPieces),
|
||||
bag(nPieces, 1, nLookAhead),
|
||||
grid(width, height + 4),
|
||||
ai(),
|
||||
@@ -142,8 +144,10 @@ public:
|
||||
|
||||
void reset()
|
||||
{
|
||||
grid.clear();
|
||||
bag.init();
|
||||
grid.width = width;
|
||||
grid.height = height + 4;
|
||||
grid.reset();
|
||||
bag.reset();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ private:
|
||||
public:
|
||||
uint8_t nPieces;
|
||||
uint8_t nBagLength;
|
||||
uint8_t queueLength;
|
||||
uint8_t bagIdx;
|
||||
std::vector<uint8_t> bag;
|
||||
std::vector<Piece> piecesQueue;
|
||||
@@ -32,6 +33,7 @@ public:
|
||||
TetrisBag(uint8_t nPieces, uint8_t nBagLength, uint8_t queueLength):
|
||||
nPieces(nPieces),
|
||||
nBagLength(nBagLength),
|
||||
queueLength(queueLength),
|
||||
bag(nPieces * nBagLength),
|
||||
piecesQueue(queueLength)
|
||||
{
|
||||
@@ -95,6 +97,15 @@ public:
|
||||
std::rotate(piecesQueue.begin(), piecesQueue.begin() + 1, piecesQueue.end());
|
||||
piecesQueue[piecesQueue.size() - 1] = Piece(idx % nPieces);
|
||||
}
|
||||
|
||||
void reset()
|
||||
{
|
||||
bag.clear();
|
||||
bag.resize(nPieces * nBagLength);
|
||||
piecesQueue.clear();
|
||||
piecesQueue.resize(queueLength);
|
||||
init();
|
||||
}
|
||||
};
|
||||
|
||||
#endif /* __TETRISBAG_H__ */
|
||||
|
||||
@@ -18,6 +18,12 @@ typedef struct TetrisAI_data
|
||||
uint8_t colorOffset;
|
||||
uint8_t colorInc;
|
||||
uint8_t mistaceCountdown;
|
||||
uint16_t segcols;
|
||||
uint16_t segrows;
|
||||
uint16_t segOffsetX;
|
||||
uint16_t segOffsetY;
|
||||
uint16_t effectWidth;
|
||||
uint16_t effectHeight;
|
||||
} tetrisai_data;
|
||||
|
||||
void drawGrid(TetrisAIGame* tetris, TetrisAI_data* tetrisai_data)
|
||||
@@ -49,7 +55,7 @@ void drawGrid(TetrisAIGame* tetris, TetrisAI_data* tetrisai_data)
|
||||
color = ColorFromPalette(SEGPALETTE, colorIndex, 255, NOBLEND);
|
||||
}
|
||||
|
||||
SEGMENT.setPixelColorXY(index_x, index_y - 4, color);
|
||||
SEGMENT.setPixelColorXY(tetrisai_data->segOffsetX + index_x, tetrisai_data->segOffsetY + index_y - 4, color);
|
||||
}
|
||||
}
|
||||
tetrisai_data->colorOffset += tetrisai_data->colorInc;
|
||||
@@ -61,14 +67,14 @@ void drawGrid(TetrisAIGame* tetris, TetrisAI_data* tetrisai_data)
|
||||
if (tetrisai_data->showBorder)
|
||||
{
|
||||
//draw a line 6 pixels from right with the border color
|
||||
for (auto index_y = 0; index_y < SEGMENT.virtualHeight(); index_y++)
|
||||
for (auto index_y = 0; index_y < tetrisai_data->effectHeight; index_y++)
|
||||
{
|
||||
SEGMENT.setPixelColorXY(SEGMENT.virtualWidth() - 6, index_y, SEGCOLOR(2));
|
||||
SEGMENT.setPixelColorXY(tetrisai_data->segOffsetX + tetrisai_data->effectWidth - 6, tetrisai_data->segOffsetY + index_y, SEGCOLOR(2));
|
||||
}
|
||||
}
|
||||
|
||||
//NEXT PIECE
|
||||
int piecesOffsetX = SEGMENT.virtualWidth() - 4;
|
||||
int piecesOffsetX = tetrisai_data->effectWidth - 4;
|
||||
int piecesOffsetY = 1;
|
||||
for (uint8_t nextPieceIdx = 1; nextPieceIdx < tetris->nLookAhead; nextPieceIdx++)
|
||||
{
|
||||
@@ -83,7 +89,7 @@ void drawGrid(TetrisAIGame* tetris, TetrisAI_data* tetrisai_data)
|
||||
if (piece.getPixel(pieceX, pieceY))
|
||||
{
|
||||
uint8_t colIdx = ((piece.pieceData->colorIndex * 32) + tetrisai_data->colorOffset);
|
||||
SEGMENT.setPixelColorXY(piecesOffsetX + pieceX, piecesOffsetY + pieceNbrOffsetY + pieceY, ColorFromPalette(SEGPALETTE, colIdx, 255, NOBLEND));
|
||||
SEGMENT.setPixelColorXY(tetrisai_data->segOffsetX + piecesOffsetX + pieceX, tetrisai_data->segOffsetY + piecesOffsetY + pieceNbrOffsetY + pieceY, ColorFromPalette(SEGPALETTE, colIdx, 255, NOBLEND));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -116,62 +122,86 @@ uint16_t mode_2DTetrisAI()
|
||||
//range 0 - 16
|
||||
tetrisai_data->colorInc = SEGMENT.custom2 >> 4;
|
||||
|
||||
if (!tetrisai_data->tetris || (tetrisai_data->tetris.nLookAhead != nLookAhead
|
||||
if (tetrisai_data->tetris.nLookAhead != nLookAhead
|
||||
|| tetrisai_data->segcols != cols
|
||||
|| tetrisai_data->segrows != rows
|
||||
|| tetrisai_data->showNext != SEGMENT.check1
|
||||
|| tetrisai_data->showBorder != SEGMENT.check2
|
||||
)
|
||||
)
|
||||
)
|
||||
{
|
||||
tetrisai_data->segcols = cols;
|
||||
tetrisai_data->segrows = rows;
|
||||
tetrisai_data->showNext = SEGMENT.check1;
|
||||
tetrisai_data->showBorder = SEGMENT.check2;
|
||||
|
||||
//not more than 32 as this is the limit of this implementation
|
||||
uint8_t gridWidth = cols < 32 ? cols : 32;
|
||||
uint8_t gridHeight = rows;
|
||||
//not more than 32 columns and 255 rows as this is the limit of this implementation
|
||||
uint8_t gridWidth = cols > 32 ? 32 : cols;
|
||||
uint8_t gridHeight = rows > 255 ? 255 : rows;
|
||||
|
||||
tetrisai_data->effectWidth = 0;
|
||||
tetrisai_data->effectHeight = 0;
|
||||
|
||||
// do we need space for the 'next' section?
|
||||
if (tetrisai_data->showNext)
|
||||
{
|
||||
// make space for the piece and one pixel of space
|
||||
gridWidth = gridWidth - 5;
|
||||
//does it get to tight?
|
||||
if (gridWidth + 5 > cols)
|
||||
{
|
||||
// yes, so make the grid smaller
|
||||
// make space for the piece and one pixel of space
|
||||
gridWidth = (gridWidth - ((gridWidth + 5) - cols));
|
||||
}
|
||||
tetrisai_data->effectWidth += 5;
|
||||
|
||||
// do we need space for a border?
|
||||
if (tetrisai_data->showBorder)
|
||||
{
|
||||
gridWidth = gridWidth - 1;
|
||||
if (gridWidth + 5 + 1 > cols)
|
||||
{
|
||||
gridWidth -= 1;
|
||||
}
|
||||
tetrisai_data->effectWidth += 1;
|
||||
}
|
||||
}
|
||||
|
||||
tetrisai_data->effectWidth += gridWidth;
|
||||
tetrisai_data->effectHeight += gridHeight;
|
||||
|
||||
tetrisai_data->segOffsetX = cols > tetrisai_data->effectWidth ? ((cols - tetrisai_data->effectWidth) / 2) : 0;
|
||||
tetrisai_data->segOffsetY = rows > tetrisai_data->effectHeight ? ((rows - tetrisai_data->effectHeight) / 2) : 0;
|
||||
|
||||
tetrisai_data->tetris = TetrisAIGame(gridWidth, gridHeight, nLookAhead, piecesData, numPieces);
|
||||
tetrisai_data->tetris.state = TetrisAIGame::States::INIT;
|
||||
SEGMENT.fill(SEGCOLOR(1));
|
||||
}
|
||||
|
||||
if (tetrisai_data->intelligence != SEGMENT.custom1)
|
||||
{
|
||||
tetrisai_data->intelligence = SEGMENT.custom1;
|
||||
double dui = 0.2 - (0.2 * (tetrisai_data->intelligence / 255.0));
|
||||
float dui = 0.2f - (0.2f * (tetrisai_data->intelligence / 255.0f));
|
||||
|
||||
tetrisai_data->tetris.ai.aHeight = -0.510066 + dui;
|
||||
tetrisai_data->tetris.ai.fullLines = 0.760666 - dui;
|
||||
tetrisai_data->tetris.ai.holes = -0.35663 + dui;
|
||||
tetrisai_data->tetris.ai.bumpiness = -0.184483 + dui;
|
||||
tetrisai_data->tetris.ai.aHeight = -0.510066f + dui;
|
||||
tetrisai_data->tetris.ai.fullLines = 0.760666f - dui;
|
||||
tetrisai_data->tetris.ai.holes = -0.35663f + dui;
|
||||
tetrisai_data->tetris.ai.bumpiness = -0.184483f + dui;
|
||||
}
|
||||
|
||||
if (tetrisai_data->tetris.state == TetrisAIGame::ANIMATE_MOVE)
|
||||
{
|
||||
if (millis() - tetrisai_data->lastTime > msDelayMove)
|
||||
|
||||
if (strip.now - tetrisai_data->lastTime > msDelayMove)
|
||||
{
|
||||
drawGrid(&tetrisai_data->tetris, tetrisai_data);
|
||||
tetrisai_data->lastTime = millis();
|
||||
tetrisai_data->lastTime = strip.now;
|
||||
tetrisai_data->tetris.poll();
|
||||
}
|
||||
}
|
||||
else if (tetrisai_data->tetris.state == TetrisAIGame::ANIMATE_GAME_OVER)
|
||||
{
|
||||
if (millis() - tetrisai_data->lastTime > msDelayGameOver)
|
||||
if (strip.now - tetrisai_data->lastTime > msDelayGameOver)
|
||||
{
|
||||
drawGrid(&tetrisai_data->tetris, tetrisai_data);
|
||||
tetrisai_data->lastTime = millis();
|
||||
tetrisai_data->lastTime = strip.now;
|
||||
tetrisai_data->tetris.poll();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,18 @@
|
||||
#pragma once
|
||||
|
||||
/*
|
||||
@title MoonModules WLED - audioreactive usermod
|
||||
@file audio_source.h
|
||||
@repo https://github.com/MoonModules/WLED, submit changes to this file as PRs to MoonModules/WLED
|
||||
@Authors https://github.com/MoonModules/WLED/commits/mdev/
|
||||
@Copyright © 2024 Github MoonModules Commit Authors (contact moonmodules@icloud.com for details)
|
||||
@license Licensed under the EUPL-1.2 or later
|
||||
|
||||
*/
|
||||
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
#include <Wire.h>
|
||||
#include "wled.h"
|
||||
#include <driver/i2s.h>
|
||||
#include <driver/adc.h>
|
||||
@@ -15,6 +28,9 @@
|
||||
#define SRate_t int
|
||||
#endif
|
||||
|
||||
constexpr i2s_port_t AR_I2S_PORT = I2S_NUM_0; // I2S port to use (do not change! I2S_NUM_1 possible but this has
|
||||
// strong limitations -> no MCLK routing, no ADC support, no PDM support
|
||||
|
||||
//#include <driver/i2s_std.h>
|
||||
//#include <driver/i2s_pdm.h>
|
||||
//#include <driver/i2s_tdm.h>
|
||||
@@ -22,7 +38,7 @@
|
||||
|
||||
// see https://docs.espressif.com/projects/esp-idf/en/latest/esp32s3/hw-reference/chip-series-comparison.html#related-documents
|
||||
// and https://docs.espressif.com/projects/esp-idf/en/latest/esp32s3/api-reference/peripherals/i2s.html#overview-of-all-modes
|
||||
#if defined(CONFIG_IDF_TARGET_ESP32C2) || defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C5) || defined(CONFIG_IDF_TARGET_ESP32C6) || defined(CONFIG_IDF_TARGET_ESP32H2) || defined(ESP8266) || defined(ESP8265)
|
||||
#if defined(CONFIG_IDF_TARGET_ESP32C2) || defined(CONFIG_IDF_TARGET_ESP32C5) || defined(CONFIG_IDF_TARGET_ESP32C6) || defined(CONFIG_IDF_TARGET_ESP32H2) || defined(ESP8266) || defined(ESP8265)
|
||||
// there are two things in these MCUs that could lead to problems with audio processing:
|
||||
// * no floating point hardware (FPU) support - FFT uses float calculations. If done in software, a strong slow-down can be expected (between 8x and 20x)
|
||||
// * single core, so FFT task might slow down other things like LED updates
|
||||
@@ -49,6 +65,11 @@
|
||||
// data type requested from the I2S driver - currently we always use 32bit
|
||||
//#define I2S_USE_16BIT_SAMPLES // (experimental) define this to request 16bit - more efficient but possibly less compatible
|
||||
|
||||
#if defined(WLED_ENABLE_HUB75MATRIX) && defined(CONFIG_IDF_TARGET_ESP32)
|
||||
// this is bitter, but necessary to survive
|
||||
#define I2S_USE_16BIT_SAMPLES
|
||||
#endif
|
||||
|
||||
#ifdef I2S_USE_16BIT_SAMPLES
|
||||
#define I2S_SAMPLE_RESOLUTION I2S_BITS_PER_SAMPLE_16BIT
|
||||
#define I2S_datatype int16_t
|
||||
@@ -71,7 +92,7 @@
|
||||
* if you want to receive two channels, one is the actual data from microphone and another channel is suppose to receive 0, it's different data in two channels, you need to choose I2S_CHANNEL_FMT_RIGHT_LEFT in this case.
|
||||
*/
|
||||
|
||||
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 4, 0)) && (ESP_IDF_VERSION <= ESP_IDF_VERSION_VAL(4, 4, 4))
|
||||
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 4, 0)) && (ESP_IDF_VERSION <= ESP_IDF_VERSION_VAL(4, 4, 8)) // should be fixed in IDF 4.4.5, however arduino-esp32 2.0.14 - 2.0.17 did an "I2S rollback" to 4.4.4
|
||||
// espressif bug: only_left has no sound, left and right are swapped
|
||||
// https://github.com/espressif/esp-idf/issues/9635 I2S mic not working since 4.4 (IDFGH-8138)
|
||||
// https://github.com/espressif/esp-idf/issues/8538 I2S channel selection issue? (IDFGH-6918)
|
||||
@@ -105,6 +126,9 @@
|
||||
#endif
|
||||
|
||||
|
||||
// max number of samples for a single i2s_read --> size of global buffer.
|
||||
#define I2S_SAMPLES_MAX 512 // same as samplesFFT
|
||||
|
||||
/* Interface class
|
||||
AudioSource serves as base class for all microphone types
|
||||
This enables accessing all microphones with one single interface
|
||||
@@ -148,38 +172,61 @@ class AudioSource {
|
||||
virtual I2S_datatype postProcessSample(I2S_datatype sample_in) {return(sample_in);} // default method can be overriden by instances (ADC) that need sample postprocessing
|
||||
|
||||
// Private constructor, to make sure it is not callable except from derived classes
|
||||
AudioSource(SRate_t sampleRate, int blockSize, float sampleScale) :
|
||||
AudioSource(SRate_t sampleRate, int blockSize, float sampleScale, bool i2sMaster) :
|
||||
_sampleRate(sampleRate),
|
||||
_blockSize(blockSize),
|
||||
_initialized(false),
|
||||
_i2sMaster(i2sMaster),
|
||||
_sampleScale(sampleScale)
|
||||
{};
|
||||
|
||||
SRate_t _sampleRate; // Microphone sampling rate
|
||||
int _blockSize; // I2S block size
|
||||
bool _initialized; // Gets set to true if initialization is successful
|
||||
bool _i2sMaster; // when false, ESP32 will be in I2S SLAVE mode (for devices that only operate in MASTER mode). Only works in newer IDF >= 4.4.x
|
||||
float _sampleScale; // pre-scaling factor for I2S samples
|
||||
I2S_datatype newSampleBuffer[I2S_SAMPLES_MAX+4] = { 0 }; // global buffer for i2s_read
|
||||
};
|
||||
|
||||
/* Basic I2S microphone source
|
||||
All functions are marked virtual, so derived classes can replace them
|
||||
WARNING: i2sMaster = false is experimental, and most likely will not work
|
||||
*/
|
||||
class I2SSource : public AudioSource {
|
||||
public:
|
||||
I2SSource(SRate_t sampleRate, int blockSize, float sampleScale = 1.0f) :
|
||||
AudioSource(sampleRate, blockSize, sampleScale) {
|
||||
I2SSource(SRate_t sampleRate, int blockSize, float sampleScale = 1.0f, bool i2sMaster=true) :
|
||||
AudioSource(sampleRate, blockSize, sampleScale, i2sMaster) {
|
||||
_config = {
|
||||
.mode = i2s_mode_t(I2S_MODE_MASTER | I2S_MODE_RX),
|
||||
.mode = i2sMaster ? i2s_mode_t(I2S_MODE_MASTER | I2S_MODE_RX) : i2s_mode_t(I2S_MODE_SLAVE | I2S_MODE_RX),
|
||||
.sample_rate = _sampleRate,
|
||||
.bits_per_sample = I2S_SAMPLE_RESOLUTION,
|
||||
.bits_per_sample = I2S_SAMPLE_RESOLUTION, // slave mode: may help to set this to 96000, as the other side (master) controls sample rates
|
||||
.channel_format = I2S_MIC_CHANNEL,
|
||||
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 2, 0)
|
||||
.communication_format = i2s_comm_format_t(I2S_COMM_FORMAT_STAND_I2S),
|
||||
//.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
|
||||
#ifdef WLEDMM_FASTPATH
|
||||
#ifdef WLED_ENABLE_HUB75MATRIX
|
||||
.intr_alloc_flags = ESP_INTR_FLAG_IRAM|ESP_INTR_FLAG_LEVEL1, // HUB75 seems to get into trouble if we allocate a higher priority interrupt
|
||||
.dma_buf_count = 18, // 100ms buffer (128 * dma_buf_count / sampleRate)
|
||||
#else
|
||||
#if CONFIG_IDF_TARGET_ESP32 && !defined(BOARD_HAS_PSRAM) // still need to test on boards with PSRAM
|
||||
.intr_alloc_flags = ESP_INTR_FLAG_IRAM|ESP_INTR_FLAG_LEVEL2|ESP_INTR_FLAG_LEVEL3, // IRAM flag reduces missed samples
|
||||
#else
|
||||
.intr_alloc_flags = ESP_INTR_FLAG_LEVEL2|ESP_INTR_FLAG_LEVEL3, // seems to reduce noise
|
||||
#endif
|
||||
.dma_buf_count = 24, // 140ms buffer (128 * dma_buf_count / sampleRate)
|
||||
#endif
|
||||
#else
|
||||
#ifdef WLED_ENABLE_HUB75MATRIX
|
||||
.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1, // HUB75 seems to get into trouble if we allocate a higher priority interrupt
|
||||
#else
|
||||
.intr_alloc_flags = ESP_INTR_FLAG_LEVEL2,
|
||||
#endif
|
||||
.dma_buf_count = 8,
|
||||
#endif
|
||||
.dma_buf_len = _blockSize,
|
||||
.use_apll = 0,
|
||||
//.fixed_mclk = 0,
|
||||
.bits_per_chan = I2S_data_size,
|
||||
#else
|
||||
.communication_format = i2s_comm_format_t(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB),
|
||||
@@ -194,17 +241,17 @@ 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
|
||||
DEBUGSR_PRINTF("\nAR: Failed to allocate I2S pins: ws=%d, sd=%d\n", i2swsPin, i2ssdPin);
|
||||
if (!PinManager::allocatePin(i2swsPin, true, PinOwner::UM_Audioreactive) ||
|
||||
!PinManager::allocatePin(i2ssdPin, false, PinOwner::UM_Audioreactive)) { // #206
|
||||
ERRORSR_PRINTF("\nAR: Failed to allocate I2S pins: ws=%d, sd=%d\n", i2swsPin, i2ssdPin);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 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)) {
|
||||
DEBUGSR_PRINTF("\nAR: Failed to allocate I2S pins: sck=%d\n", i2sckPin);
|
||||
if (!PinManager::allocatePin(i2sckPin, true, PinOwner::UM_Audioreactive)) {
|
||||
ERRORSR_PRINTF("\nAR: Failed to allocate I2S pins: sck=%d\n", i2sckPin);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
@@ -226,10 +273,17 @@ class I2SSource : public AudioSource {
|
||||
_config.mode = i2s_mode_t(I2S_MODE_MASTER | I2S_MODE_RX | I2S_MODE_PDM); // Change mode to pdm if clock pin not provided. PDM is not supported on ESP32-S2. PDM RX not supported on ESP32-C3
|
||||
_config.channel_format =I2S_PDM_MIC_CHANNEL; // seems that PDM mono mode always uses left channel.
|
||||
_config.use_apll = true; // experimental - use aPLL clock source to improve sampling quality
|
||||
//_config.bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT; // not needed
|
||||
#endif
|
||||
}
|
||||
|
||||
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 2, 0)
|
||||
if ((_i2sMaster == false) && (_config.mode & I2S_MODE_SLAVE)) { // I2S slave mode (experimental).
|
||||
// Seems we need to drive clocks in slave mode
|
||||
_config.use_apll = true;
|
||||
_config.fixed_mclk = 512 * int(_config.sample_rate);
|
||||
}
|
||||
|
||||
if (mclkPin != I2S_PIN_NO_CHANGE) {
|
||||
_config.use_apll = true; // experimental - use aPLL clock source to improve sampling quality, and to avoid glitches.
|
||||
// //_config.fixed_mclk = 512 * _sampleRate;
|
||||
@@ -244,13 +298,28 @@ class I2SSource : public AudioSource {
|
||||
#if defined(ARDUINO_ARCH_ESP32) && !defined(CONFIG_IDF_TARGET_ESP32S3) && !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3)
|
||||
if (ESP.getChipRevision() == 0) _config.use_apll = false; // APLL is broken on ESP32 revision 0
|
||||
#endif
|
||||
#if defined(WLED_ENABLE_HUB75MATRIX)
|
||||
_config.use_apll = false; // APLL needed for HUB75 DMA driver ?
|
||||
#endif
|
||||
#endif
|
||||
|
||||
if (_i2sMaster == false) {
|
||||
DEBUG_PRINTLN(F("AR: Warning - i2S SLAVE mode is experimental!"));
|
||||
if (_config.mode & I2S_MODE_PDM) {
|
||||
// APLL does not work in DAC or PDM "Slave Mode": https://github.com/espressif/esp-idf/issues/1244, https://github.com/espressif/esp-idf/issues/2634
|
||||
_config.use_apll = false;
|
||||
_config.fixed_mclk = 0;
|
||||
}
|
||||
if ((_config.mode & I2S_MODE_MASTER) != 0) {
|
||||
DEBUG_PRINTLN("AR: (oops) I2S SLAVE mode requested but not configured!");
|
||||
}
|
||||
}
|
||||
|
||||
// Reserve the master clock pin if provided
|
||||
_mclkPin = mclkPin;
|
||||
if (mclkPin != I2S_PIN_NO_CHANGE) {
|
||||
if(!pinManager.allocatePin(mclkPin, true, PinOwner::UM_Audioreactive)) {
|
||||
DEBUGSR_PRINTF("\nAR: Failed to allocate I2S pin: MCLK=%d\n", mclkPin);
|
||||
if(!PinManager::allocatePin(mclkPin, true, PinOwner::UM_Audioreactive)) {
|
||||
ERRORSR_PRINTF("\nAR: Failed to allocate I2S pin: MCLK=%d\n", mclkPin);
|
||||
return;
|
||||
} else
|
||||
_routeMclk(mclkPin);
|
||||
@@ -268,32 +337,36 @@ class I2SSource : public AudioSource {
|
||||
|
||||
//DEBUGSR_PRINTF("[AR] I2S: SD=%d, WS=%d, SCK=%d, MCLK=%d\n", i2ssdPin, i2swsPin, i2sckPin, mclkPin);
|
||||
|
||||
esp_err_t err = i2s_driver_install(I2S_NUM_0, &_config, 0, nullptr);
|
||||
esp_err_t err = i2s_driver_install(AR_I2S_PORT, &_config, 0, nullptr);
|
||||
if (err != ESP_OK) {
|
||||
DEBUGSR_PRINTF("AR: Failed to install i2s driver: %d\n", err);
|
||||
ERRORSR_PRINTF("AR: Failed to install i2s driver: %d\n", err);
|
||||
return;
|
||||
}
|
||||
|
||||
DEBUGSR_PRINTF("AR: I2S#0 driver %s aPLL; fixed_mclk=%d.\n", _config.use_apll? "uses":"without", _config.fixed_mclk);
|
||||
DEBUGSR_PRINTF("AR: %d bits, Sample scaling factor = %6.4f\n", _config.bits_per_sample, _sampleScale);
|
||||
if (_config.mode & I2S_MODE_PDM) {
|
||||
if(_config.mode & I2S_MODE_MASTER) {
|
||||
if (_config.mode & I2S_MODE_PDM) {
|
||||
DEBUGSR_PRINTLN(F("AR: I2S#0 driver installed in PDM MASTER mode."));
|
||||
} else {
|
||||
} else {
|
||||
DEBUGSR_PRINTLN(F("AR: I2S#0 driver installed in MASTER mode."));
|
||||
}
|
||||
} else {
|
||||
DEBUGSR_PRINTLN(F("AR: I2S#0 driver installed in SLAVE mode."));
|
||||
}
|
||||
|
||||
err = i2s_set_pin(I2S_NUM_0, &_pinConfig);
|
||||
err = i2s_set_pin(AR_I2S_PORT, &_pinConfig);
|
||||
if (err != ESP_OK) {
|
||||
DEBUGSR_PRINTF("AR: Failed to set i2s pin config: %d\n", err);
|
||||
i2s_driver_uninstall(I2S_NUM_0); // uninstall already-installed driver
|
||||
ERRORSR_PRINTF("AR: Failed to set i2s pin config: %d\n", err);
|
||||
i2s_driver_uninstall(AR_I2S_PORT); // uninstall already-installed driver
|
||||
return;
|
||||
}
|
||||
|
||||
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 2, 0)
|
||||
err = i2s_set_clk(I2S_NUM_0, _sampleRate, I2S_SAMPLE_RESOLUTION, I2S_CHANNEL_MONO); // set bit clocks. Also takes care of MCLK routing if needed.
|
||||
err = i2s_set_clk(AR_I2S_PORT, _sampleRate, I2S_SAMPLE_RESOLUTION, I2S_CHANNEL_MONO); // set bit clocks. Also takes care of MCLK routing if needed.
|
||||
if (err != ESP_OK) {
|
||||
DEBUGSR_PRINTF("AR: Failed to configure i2s clocks: %d\n", err);
|
||||
i2s_driver_uninstall(I2S_NUM_0); // uninstall already-installed driver
|
||||
ERRORSR_PRINTF("AR: Failed to configure i2s clocks: %d\n", err);
|
||||
i2s_driver_uninstall(AR_I2S_PORT); // uninstall already-installed driver
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
@@ -302,33 +375,36 @@ class I2SSource : public AudioSource {
|
||||
|
||||
virtual void deinitialize() {
|
||||
_initialized = false;
|
||||
esp_err_t err = i2s_driver_uninstall(I2S_NUM_0);
|
||||
esp_err_t err = i2s_driver_uninstall(AR_I2S_PORT);
|
||||
if (err != ESP_OK) {
|
||||
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) {
|
||||
if (_initialized) {
|
||||
esp_err_t err;
|
||||
size_t bytes_read = 0; /* Counter variable to check if we actually got enough data */
|
||||
I2S_datatype newSamples[num_samples]; /* Intermediary sample storage */
|
||||
|
||||
err = i2s_read(I2S_NUM_0, (void *)newSamples, sizeof(newSamples), &bytes_read, portMAX_DELAY);
|
||||
memset(buffer, 0, sizeof(float) * num_samples); // clear output buffer
|
||||
I2S_datatype *newSamples = newSampleBuffer; // use global input buffer
|
||||
if (num_samples > I2S_SAMPLES_MAX) num_samples = I2S_SAMPLES_MAX; // protect the buffer from overflow
|
||||
|
||||
err = i2s_read(AR_I2S_PORT, (void *)newSamples, num_samples * sizeof(I2S_datatype), &bytes_read, portMAX_DELAY);
|
||||
if (err != ESP_OK) {
|
||||
DEBUGSR_PRINTF("Failed to get samples: %d\n", err);
|
||||
return;
|
||||
}
|
||||
|
||||
// For correct operation, we need to read exactly sizeof(samples) bytes from i2s
|
||||
if (bytes_read != sizeof(newSamples)) {
|
||||
DEBUGSR_PRINTF("Failed to get enough samples: wanted: %d read: %d\n", sizeof(newSamples), bytes_read);
|
||||
if (bytes_read != (num_samples * sizeof(I2S_datatype))) {
|
||||
DEBUGSR_PRINTF("Failed to get enough samples: wanted: %d read: %d\n", num_samples * sizeof(I2S_datatype), bytes_read);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -383,6 +459,10 @@ class I2SSource : public AudioSource {
|
||||
*/
|
||||
class ES7243 : public I2SSource {
|
||||
private:
|
||||
// I2C initialization functions for ES7243
|
||||
void _es7243I2cBegin() {
|
||||
Wire.setClock(100000);
|
||||
}
|
||||
|
||||
void _es7243I2cWrite(uint8_t reg, uint8_t val) {
|
||||
#ifndef ES7243_ADDR
|
||||
@@ -398,6 +478,7 @@ class ES7243 : public I2SSource {
|
||||
}
|
||||
|
||||
void _es7243InitAdc() {
|
||||
_es7243I2cBegin();
|
||||
_es7243I2cWrite(0x00, 0x01);
|
||||
_es7243I2cWrite(0x06, 0x00);
|
||||
_es7243I2cWrite(0x05, 0x1B);
|
||||
@@ -407,17 +488,26 @@ class ES7243 : public I2SSource {
|
||||
}
|
||||
|
||||
public:
|
||||
ES7243(SRate_t sampleRate, int blockSize, float sampleScale = 1.0f) :
|
||||
I2SSource(sampleRate, blockSize, sampleScale) {
|
||||
ES7243(SRate_t sampleRate, int blockSize, float sampleScale = 1.0f, bool i2sMaster=true) :
|
||||
I2SSource(sampleRate, blockSize, sampleScale, i2sMaster) {
|
||||
_config.channel_format = I2S_CHANNEL_FMT_ONLY_RIGHT;
|
||||
};
|
||||
|
||||
void initialize(int8_t i2swsPin, int8_t i2ssdPin, int8_t i2sckPin, int8_t mclkPin) {
|
||||
DEBUGSR_PRINTLN(F("ES7243:: initialize();"));
|
||||
if ((i2sckPin < 0) || (mclkPin < 0)) {
|
||||
DEBUGSR_PRINTF("\nAR: invalid I2S pin: SCK=%d, MCLK=%d\n", i2sckPin, mclkPin);
|
||||
DEBUGSR_PRINTLN("ES7243:: initialize();");
|
||||
|
||||
// if ((i2sckPin < 0) || (mclkPin < 0)) { // WLEDMM not sure if this check is needed here, too
|
||||
// ERRORSR_PRINTF("\nAR: invalid I2S pin: SCK=%d, MCLK=%d\n", i2sckPin, mclkPin);
|
||||
// return;
|
||||
// }
|
||||
if ((i2c_sda < 0) || (i2c_scl < 0)) { // check that global I2C pins are not "undefined"
|
||||
ERRORSR_PRINTF("\nAR: invalid ES7243 global I2C pins: SDA=%d, SCL=%d\n", i2c_sda, i2c_scl);
|
||||
return;
|
||||
}
|
||||
// if (!PinManager::joinWire(i2c_sda, i2c_scl)) { // WLEDMM specific: start I2C with globally defined pins
|
||||
// ERRORSR_PRINTF("\nAR: failed to join I2C bus with SDA=%d, SCL=%d\n", i2c_sda, i2c_scl);
|
||||
// return;
|
||||
// }
|
||||
|
||||
// First route mclk, then configure ADC over I2C, then configure I2S
|
||||
_es7243InitAdc();
|
||||
@@ -435,14 +525,16 @@ public:
|
||||
*/
|
||||
class ES8388Source : public I2SSource {
|
||||
private:
|
||||
// I2C initialization functions for ES8388
|
||||
void _es8388I2cBegin() {
|
||||
Wire.setClock(100000);
|
||||
}
|
||||
|
||||
void _es8388I2cWrite(uint8_t reg, uint8_t val) {
|
||||
#ifndef ES8388_ADDR
|
||||
Wire.beginTransmission(0x10);
|
||||
#define ES8388_ADDR 0x10 // default address
|
||||
#else
|
||||
#ifndef ES8388_ADDR
|
||||
#define ES8388_ADDR 0x10 // default address
|
||||
#endif
|
||||
Wire.beginTransmission(ES8388_ADDR);
|
||||
#endif
|
||||
Wire.write((uint8_t)reg);
|
||||
Wire.write((uint8_t)val);
|
||||
uint8_t i2cErr = Wire.endTransmission(); // i2cErr == 0 means OK
|
||||
@@ -459,6 +551,7 @@ class ES8388Source : public I2SSource {
|
||||
// Registries are decimal, settings are binary as that's how everything is listed in the docs
|
||||
// ...which makes it easier to reference the docs.
|
||||
//
|
||||
_es8388I2cBegin();
|
||||
_es8388I2cWrite( 8,0b00000000); // I2S to slave
|
||||
_es8388I2cWrite( 2,0b11110011); // Power down DEM and STM
|
||||
_es8388I2cWrite(43,0b10000000); // Set same LRCK
|
||||
@@ -524,16 +617,28 @@ class ES8388Source : public I2SSource {
|
||||
|
||||
public:
|
||||
ES8388Source(SRate_t sampleRate, int blockSize, float sampleScale = 1.0f, bool i2sMaster=true) :
|
||||
I2SSource(sampleRate, blockSize, sampleScale) {
|
||||
I2SSource(sampleRate, blockSize, sampleScale, i2sMaster) {
|
||||
_config.channel_format = I2S_CHANNEL_FMT_ONLY_LEFT;
|
||||
};
|
||||
|
||||
void initialize(int8_t i2swsPin, int8_t i2ssdPin, int8_t i2sckPin, int8_t mclkPin) {
|
||||
DEBUGSR_PRINTLN(F("ES8388Source:: initialize();"));
|
||||
if ((i2sckPin < 0) || (mclkPin < 0)) {
|
||||
DEBUGSR_PRINTF("\nAR: invalid I2S pin: SCK=%d, MCLK=%d\n", i2sckPin, mclkPin);
|
||||
DEBUGSR_PRINTLN("ES8388Source:: initialize();");
|
||||
|
||||
// if ((i2sckPin < 0) || (mclkPin < 0)) { // WLEDMM not sure if this check is needed here, too
|
||||
// ERRORSR_PRINTF("\nAR: invalid I2S ES8388 pin: SCK=%d, MCLK=%d\n", i2sckPin, mclkPin);
|
||||
// return;
|
||||
// }
|
||||
// BUG: "use global I2C pins" are valid as -1, and -1 is seen as invalid here.
|
||||
// Workaround: Set I2C pins here, which will also set them globally.
|
||||
// Bug also exists in ES7243.
|
||||
if ((i2c_sda < 0) || (i2c_scl < 0)) { // check that global I2C pins are not "undefined"
|
||||
ERRORSR_PRINTF("\nAR: invalid ES8388 global I2C pins: SDA=%d, SCL=%d\n", i2c_sda, i2c_scl);
|
||||
return;
|
||||
}
|
||||
// if (!PinManager::joinWire(i2c_sda, i2c_scl)) { // WLEDMM specific: start I2C with globally defined pins
|
||||
// ERRORSR_PRINTF("\nAR: failed to join I2C bus with SDA=%d, SCL=%d\n", i2c_sda, i2c_scl);
|
||||
// return;
|
||||
// }
|
||||
|
||||
// First route mclk, then configure ADC over I2C, then configure I2S
|
||||
_es8388InitAdc();
|
||||
@@ -546,6 +651,302 @@ class ES8388Source : public I2SSource {
|
||||
|
||||
};
|
||||
|
||||
/* ES8311 Sound Module
|
||||
This is an I2S sound processing unit that requires initialization over
|
||||
I2C before I2S data can be received.
|
||||
*/
|
||||
class ES8311Source : public I2SSource {
|
||||
private:
|
||||
// I2C initialization functions for es8311
|
||||
void _es8311I2cBegin() {
|
||||
Wire.setClock(100000);
|
||||
}
|
||||
|
||||
void _es8311I2cWrite(uint8_t reg, uint8_t val) {
|
||||
#ifndef ES8311_ADDR
|
||||
#define ES8311_ADDR 0x18 // default address is... foggy
|
||||
#endif
|
||||
Wire.beginTransmission(ES8311_ADDR);
|
||||
Wire.write((uint8_t)reg);
|
||||
Wire.write((uint8_t)val);
|
||||
uint8_t i2cErr = Wire.endTransmission(); // i2cErr == 0 means OK
|
||||
if (i2cErr != 0) {
|
||||
DEBUGSR_PRINTF("AR: ES8311 I2C write failed with error=%d (addr=0x%X, reg 0x%X, val 0x%X).\n", i2cErr, ES8311_ADDR, reg, val);
|
||||
}
|
||||
}
|
||||
|
||||
void _es8311InitAdc() {
|
||||
//
|
||||
// Currently only tested with the ESP32-P4 boards with the onboard mic.
|
||||
// Datasheet with I2C commands: https://dl.xkwy2018.com/downloads/RK3588/01_Official%20Release/04_Product%20Line%20Branch_NVR/02_Key%20Device%20Specifications/ES8311%20DS.pdf
|
||||
//
|
||||
_es8311I2cBegin();
|
||||
_es8311I2cWrite(0x00, 0b00011111); // RESET, default value
|
||||
_es8311I2cWrite(0x45, 0b00000000); // GP, default value
|
||||
_es8311I2cWrite(0x01, 0b00111010); // CLOCK MANAGER was 0b00110000 trying 0b00111010 (MCLK enable?)
|
||||
|
||||
_es8311I2cWrite(0x02, 0b00000000); // 22050hz calculated
|
||||
_es8311I2cWrite(0x05, 0b00000000); // 22050hz calculated
|
||||
_es8311I2cWrite(0x03, 0b00010000); // 22050hz calculated
|
||||
_es8311I2cWrite(0x04, 0b00010000); // 22050hz calculated
|
||||
_es8311I2cWrite(0x07, 0b00000000); // 22050hz calculated
|
||||
_es8311I2cWrite(0x08, 0b11111111); // 22050hz calculated
|
||||
_es8311I2cWrite(0x06, 0b11100011); // 22050hz calculated
|
||||
|
||||
_es8311I2cWrite(0x16, 0b00100100); // ADC was 0b00000011 trying 0b00100100 was good
|
||||
_es8311I2cWrite(0x0B, 0b00000000); // SYSTEM at default
|
||||
_es8311I2cWrite(0x0C, 0b00100000); // SYSTEM was 0b00001111 trying 0b00100000
|
||||
_es8311I2cWrite(0x10, 0b00010011); // SYSTEM was 0b00011111 trying 0b00010011
|
||||
_es8311I2cWrite(0x11, 0b01111100); // SYSTEM was 0b01111111 trying 0b01111100
|
||||
_es8311I2cWrite(0x00, 0b11000000); // *** RESET (again - seems important?)
|
||||
_es8311I2cWrite(0x01, 0b00111010); // *** CLOCK MANAGER was 0b00111111 trying 0b00111010 (again?? seems important)
|
||||
_es8311I2cWrite(0x14, 0b00010000); // *** SYSTEM was 0b00011010 trying 0b00010000 (PGA gain)
|
||||
_es8311I2cWrite(0x0A, 0b00001000); // *** SDP OUT, was 0b00001100 trying 0b00001000 (I2S 32-bit)
|
||||
_es8311I2cWrite(0x0E, 0b00000010); // *** SYSTEM was 0b00000010 trying 0b00000010
|
||||
_es8311I2cWrite(0x0F, 0b01000100); // SYSTEM was 0b01000100
|
||||
_es8311I2cWrite(0x15, 0b00010000); // ADC soft ramp (disabled 0000xxxx)
|
||||
_es8311I2cWrite(0x1B, 0b00000101); // ADC soft-mute was 0b00000101
|
||||
_es8311I2cWrite(0x1C, 0b01100101); // ADC EQ and offset freeze at 0b01100101 (bad at 0b00101100)
|
||||
_es8311I2cWrite(0x17, 0b10111111); // ADC volume was 0b11111111 trying ADC volume 0b10111111 = 0db (maxgain)
|
||||
_es8311I2cWrite(0x18, 0b10000001); // ADC ALC enabled and AutoMute disabled.
|
||||
// _es8311I2cWrite(0x19, 0b11110100); // ADC ALC max and min - not sure how best to use this, default seems fine
|
||||
}
|
||||
|
||||
public:
|
||||
ES8311Source(SRate_t sampleRate, int blockSize, float sampleScale = 1.0f, bool i2sMaster=true) :
|
||||
I2SSource(sampleRate, blockSize, sampleScale, i2sMaster) {
|
||||
_config.channel_format = I2S_CHANNEL_FMT_ONLY_LEFT;
|
||||
};
|
||||
|
||||
void initialize(int8_t i2swsPin, int8_t i2ssdPin, int8_t i2sckPin, int8_t mclkPin) {
|
||||
DEBUGSR_PRINTLN("es8311Source:: initialize();");
|
||||
|
||||
// if ((i2sckPin < 0) || (mclkPin < 0)) { // WLEDMM not sure if this check is needed here, too
|
||||
// ERRORSR_PRINTF("\nAR: invalid I2S es8311 pin: SCK=%d, MCLK=%d\n", i2sckPin, mclkPin);
|
||||
// return;
|
||||
// }
|
||||
// BUG: "use global I2C pins" are valid as -1, and -1 is seen as invalid here.
|
||||
// Workaround: Set I2C pins here, which will also set them globally.
|
||||
// Bug also exists in ES7243.
|
||||
if ((i2c_sda < 0) || (i2c_scl < 0)) { // check that global I2C pins are not "undefined"
|
||||
ERRORSR_PRINTF("\nAR: invalid es8311 global I2C pins: SDA=%d, SCL=%d\n", i2c_sda, i2c_scl);
|
||||
return;
|
||||
}
|
||||
// if (!PinManager::joinWire(i2c_sda, i2c_scl)) { // WLEDMM specific: start I2C with globally defined pins
|
||||
// ERRORSR_PRINTF("\nAR: failed to join I2C bus with SDA=%d, SCL=%d\n", i2c_sda, i2c_scl);
|
||||
// return;
|
||||
// }
|
||||
|
||||
// First route mclk, then configure ADC over I2C, then configure I2S
|
||||
_es8311InitAdc();
|
||||
I2SSource::initialize(i2swsPin, i2ssdPin, i2sckPin, mclkPin);
|
||||
}
|
||||
|
||||
void deinitialize() {
|
||||
I2SSource::deinitialize();
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
class WM8978Source : public I2SSource {
|
||||
private:
|
||||
// I2C initialization functions for WM8978
|
||||
void _wm8978I2cBegin() {
|
||||
Wire.setClock(400000);
|
||||
}
|
||||
|
||||
void _wm8978I2cWrite(uint8_t reg, uint16_t val) {
|
||||
#ifndef WM8978_ADDR
|
||||
#define WM8978_ADDR 0x1A
|
||||
#endif
|
||||
char buf[2];
|
||||
buf[0] = (reg << 1) | ((val >> 8) & 0X01);
|
||||
buf[1] = val & 0XFF;
|
||||
Wire.beginTransmission(WM8978_ADDR);
|
||||
Wire.write((const uint8_t*)buf, 2);
|
||||
uint8_t i2cErr = Wire.endTransmission(); // i2cErr == 0 means OK
|
||||
if (i2cErr != 0) {
|
||||
DEBUGSR_PRINTF("AR: WM8978 I2C write failed with error=%d (addr=0x%X, reg 0x%X, val 0x%X).\n", i2cErr, WM8978_ADDR, reg, val);
|
||||
}
|
||||
}
|
||||
|
||||
void _wm8978InitAdc() {
|
||||
// https://www.mouser.com/datasheet/2/76/WM8978_v4.5-1141768.pdf
|
||||
// Sets ADC to around what AudioReactive expects, and loops line-in to line-out/headphone for monitoring.
|
||||
// Registries are decimal, settings are 9-bit binary as that's how everything is listed in the docs
|
||||
// ...which makes it easier to reference the docs.
|
||||
//
|
||||
_wm8978I2cBegin();
|
||||
|
||||
_wm8978I2cWrite( 0,0b000000000); // Reset all settings
|
||||
_wm8978I2cWrite( 1,0b000111110); // Power Management 1 - power off most things, but enable mic bias and I/O tie-off to help mitigate mic leakage.
|
||||
_wm8978I2cWrite( 2,0b110111111); // Power Management 2 - enable output and amp stages (amps may lift signal but it works better on the ADCs)
|
||||
_wm8978I2cWrite( 3,0b000001100); // Power Management 3 - enable L&R output mixers
|
||||
|
||||
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 2, 0)
|
||||
_wm8978I2cWrite( 4,0b001010000); // Audio Interface - standard I2S, 24-bit
|
||||
#else
|
||||
_wm8978I2cWrite( 4,0b001001000); // Audio Interface - left-justified I2S, 24-bit
|
||||
#endif
|
||||
|
||||
_wm8978I2cWrite( 6,0b000000000); // Clock generation control - use external mclk
|
||||
_wm8978I2cWrite( 7,0b000000100); // Sets sample rate to ~24kHz (only used for internal calculations, not I2S)
|
||||
_wm8978I2cWrite(14,0b010001000); // 128x ADC oversampling - high pass filter disabled as it kills the bass response
|
||||
_wm8978I2cWrite(43,0b000110000); // Mute signal paths we don't use
|
||||
_wm8978I2cWrite(44,0b100000000); // Disconnect microphones
|
||||
_wm8978I2cWrite(45,0b111000000); // Mute signal paths we don't use
|
||||
_wm8978I2cWrite(46,0b111000000); // Mute signal paths we don't use
|
||||
_wm8978I2cWrite(47,0b001000000); // 0dB gain on left line-in
|
||||
_wm8978I2cWrite(48,0b001000000); // 0dB gain on right line-in
|
||||
_wm8978I2cWrite(49,0b000000011); // Mixer thermal shutdown enable and unused IOs to 30kΩ
|
||||
_wm8978I2cWrite(50,0b000010110); // Output mixer enable only left bypass at 0dB gain
|
||||
_wm8978I2cWrite(51,0b000010110); // Output mixer enable only right bypass at 0dB gain
|
||||
_wm8978I2cWrite(52,0b110111001); // Left line-out enabled at 0dB gain
|
||||
_wm8978I2cWrite(53,0b110111001); // Right line-out enabled at 0db gain
|
||||
_wm8978I2cWrite(54,0b111000000); // Mute left speaker output
|
||||
_wm8978I2cWrite(55,0b111000000); // Mute right speaker output
|
||||
|
||||
}
|
||||
|
||||
public:
|
||||
WM8978Source(SRate_t sampleRate, int blockSize, float sampleScale = 1.0f, bool i2sMaster=true) :
|
||||
I2SSource(sampleRate, blockSize, sampleScale, i2sMaster) {
|
||||
_config.channel_format = I2S_CHANNEL_FMT_ONLY_LEFT;
|
||||
};
|
||||
|
||||
void initialize(int8_t i2swsPin, int8_t i2ssdPin, int8_t i2sckPin, int8_t mclkPin) {
|
||||
DEBUGSR_PRINTLN("WM8978Source:: initialize();");
|
||||
|
||||
// if ((i2sckPin < 0) || (mclkPin < 0)) { // WLEDMM not sure if this check is needed here, too
|
||||
// ERRORSR_PRINTF("\nAR: invalid I2S WM8978 pin: SCK=%d, MCLK=%d\n", i2sckPin, mclkPin);
|
||||
// return;
|
||||
// }
|
||||
// BUG: "use global I2C pins" are valid as -1, and -1 is seen as invalid here.
|
||||
// Workaround: Set I2C pins here, which will also set them globally.
|
||||
// Bug also exists in ES7243.
|
||||
if ((i2c_sda < 0) || (i2c_scl < 0)) { // check that global I2C pins are not "undefined"
|
||||
ERRORSR_PRINTF("\nAR: invalid WM8978 global I2C pins: SDA=%d, SCL=%d\n", i2c_sda, i2c_scl);
|
||||
return;
|
||||
}
|
||||
// if (!PinManager::joinWire(i2c_sda, i2c_scl)) { // WLEDMM specific: start I2C with globally defined pins
|
||||
// ERRORSR_PRINTF("\nAR: failed to join I2C bus with SDA=%d, SCL=%d\n", i2c_sda, i2c_scl);
|
||||
// return;
|
||||
// }
|
||||
|
||||
// First route mclk, then configure ADC over I2C, then configure I2S
|
||||
_wm8978InitAdc();
|
||||
I2SSource::initialize(i2swsPin, i2ssdPin, i2sckPin, mclkPin);
|
||||
}
|
||||
|
||||
void deinitialize() {
|
||||
I2SSource::deinitialize();
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
class AC101Source : public I2SSource {
|
||||
private:
|
||||
// I2C initialization functions for WM8978
|
||||
void _ac101I2cBegin() {
|
||||
Wire.setClock(400000);
|
||||
}
|
||||
|
||||
void _ac101I2cWrite(uint8_t reg_addr, uint16_t val) {
|
||||
#ifndef AC101_ADDR
|
||||
#define AC101_ADDR 0x1A
|
||||
#endif
|
||||
char send_buff[3];
|
||||
send_buff[0] = reg_addr;
|
||||
send_buff[1] = uint8_t((val >> 8) & 0xff);
|
||||
send_buff[2] = uint8_t(val & 0xff);
|
||||
Wire.beginTransmission(AC101_ADDR);
|
||||
Wire.write((const uint8_t*)send_buff, 3);
|
||||
uint8_t i2cErr = Wire.endTransmission(); // i2cErr == 0 means OK
|
||||
if (i2cErr != 0) {
|
||||
DEBUGSR_PRINTF("AR: AC101 I2C write failed with error=%d (addr=0x%X, reg 0x%X, val 0x%X).\n", i2cErr, AC101_ADDR, reg_addr, val);
|
||||
}
|
||||
}
|
||||
|
||||
void _ac101InitAdc() {
|
||||
// https://files.seeedstudio.com/wiki/ReSpeaker_6-Mics_Circular_Array_kit_for_Raspberry_Pi/reg/AC101_User_Manual_v1.1.pdf
|
||||
// This supports mostly the older AI Thinkier AudioKit A1S that has an AC101 chip
|
||||
// Newer versions use the ES3833 chip - which we also support.
|
||||
|
||||
_ac101I2cBegin();
|
||||
|
||||
#define CHIP_AUDIO_RS 0x00
|
||||
#define SYSCLK_CTRL 0x03
|
||||
#define MOD_CLK_ENA 0x04
|
||||
#define MOD_RST_CTRL 0x05
|
||||
#define I2S_SR_CTRL 0x06
|
||||
#define I2S1LCK_CTRL 0x10
|
||||
#define I2S1_SDOUT_CTRL 0x11
|
||||
#define I2S1_MXR_SRC 0x13
|
||||
#define ADC_DIG_CTRL 0x40
|
||||
#define ADC_APC_CTRL 0x50
|
||||
#define ADC_SRC 0x51
|
||||
#define ADC_SRCBST_CTRL 0x52
|
||||
#define OMIXER_DACA_CTRL 0x53
|
||||
#define OMIXER_SR 0x54
|
||||
#define HPOUT_CTRL 0x56
|
||||
|
||||
_ac101I2cWrite(CHIP_AUDIO_RS, 0x123); // I think anything written here is a reset as 0x123 is kinda suss.
|
||||
|
||||
delay(100);
|
||||
|
||||
_ac101I2cWrite(SYSCLK_CTRL, 0b0000100000001000); // System Clock is I2S MCLK
|
||||
_ac101I2cWrite(MOD_CLK_ENA, 0b1000000000001000); // I2S and ADC Clock Enable
|
||||
_ac101I2cWrite(MOD_RST_CTRL, 0b1000000000001000); // I2S and ADC Clock Enable
|
||||
_ac101I2cWrite(I2S_SR_CTRL, 0b0100000000000000); // set to 22050hz just in case
|
||||
_ac101I2cWrite(I2S1LCK_CTRL, 0b1000000000110000); // set I2S slave mode, 24-bit word size
|
||||
_ac101I2cWrite(I2S1_SDOUT_CTRL, 0b1100000000000000); // I2S enable Left/Right channels
|
||||
_ac101I2cWrite(I2S1_MXR_SRC, 0b0010001000000000); // I2S digital Mixer, ADC L/R data
|
||||
_ac101I2cWrite(ADC_SRCBST_CTRL, 0b0000000000000100); // mute all boosts. last 3 bits are reserved/default
|
||||
_ac101I2cWrite(OMIXER_SR, 0b0000010000001000); // Line L/R to output mixer
|
||||
_ac101I2cWrite(ADC_SRC, 0b0000010000001000); // Line L/R to ADC
|
||||
_ac101I2cWrite(ADC_DIG_CTRL, 0b1000000000000000); // Enable ADC
|
||||
_ac101I2cWrite(ADC_APC_CTRL, 0b1011100100000000); // ADC L/R enabled, 0dB gain
|
||||
_ac101I2cWrite(OMIXER_DACA_CTRL, 0b0011111110000000); // L/R Analog Output Mixer enabled, headphone DC offset default
|
||||
_ac101I2cWrite(HPOUT_CTRL, 0b1111101111110001); // Headphone out from Analog Mixer stage, no reduction in volume
|
||||
|
||||
}
|
||||
|
||||
public:
|
||||
AC101Source(SRate_t sampleRate, int blockSize, float sampleScale = 1.0f, bool i2sMaster=true) :
|
||||
I2SSource(sampleRate, blockSize, sampleScale, i2sMaster) {
|
||||
_config.channel_format = I2S_CHANNEL_FMT_ONLY_LEFT;
|
||||
};
|
||||
|
||||
void initialize(int8_t i2swsPin, int8_t i2ssdPin, int8_t i2sckPin, int8_t mclkPin) {
|
||||
DEBUGSR_PRINTLN("AC101Source:: initialize();");
|
||||
|
||||
// if ((i2sckPin < 0) || (mclkPin < 0)) { // WLEDMM not sure if this check is needed here, too
|
||||
// ERRORSR_PRINTF("\nAR: invalid I2S WM8978 pin: SCK=%d, MCLK=%d\n", i2sckPin, mclkPin);
|
||||
// return;
|
||||
// }
|
||||
// BUG: "use global I2C pins" are valid as -1, and -1 is seen as invalid here.
|
||||
// Workaround: Set I2C pins here, which will also set them globally.
|
||||
// Bug also exists in ES7243.
|
||||
if ((i2c_sda < 0) || (i2c_scl < 0)) { // check that global I2C pins are not "undefined"
|
||||
ERRORSR_PRINTF("\nAR: invalid AC101 global I2C pins: SDA=%d, SCL=%d\n", i2c_sda, i2c_scl);
|
||||
return;
|
||||
}
|
||||
// if (!PinManager::joinWire(i2c_sda, i2c_scl)) { // WLEDMM specific: start I2C with globally defined pins
|
||||
// ERRORSR_PRINTF("\nAR: failed to join I2C bus with SDA=%d, SCL=%d\n", i2c_sda, i2c_scl);
|
||||
// return;
|
||||
// }
|
||||
|
||||
// First route mclk, then configure ADC over I2C, then configure I2S
|
||||
_ac101InitAdc();
|
||||
I2SSource::initialize(i2swsPin, i2ssdPin, i2sckPin, mclkPin);
|
||||
}
|
||||
|
||||
void deinitialize() {
|
||||
I2SSource::deinitialize();
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 2, 0)
|
||||
#if !defined(SOC_I2S_SUPPORTS_ADC) && !defined(SOC_I2S_SUPPORTS_ADC_DAC)
|
||||
#warning this MCU does not support analog sound input
|
||||
@@ -553,7 +954,7 @@ class ES8388Source : public I2SSource {
|
||||
#endif
|
||||
|
||||
#if !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3) && !defined(CONFIG_IDF_TARGET_ESP32S3)
|
||||
// ADC over I2S is only availeable in "classic" ESP32
|
||||
// ADC over I2S is only available in "classic" ESP32
|
||||
|
||||
/* ADC over I2S Microphone
|
||||
This microphone is an ADC pin sampled via the I2S interval
|
||||
@@ -563,7 +964,7 @@ class ES8388Source : public I2SSource {
|
||||
class I2SAdcSource : public I2SSource {
|
||||
public:
|
||||
I2SAdcSource(SRate_t sampleRate, int blockSize, float sampleScale = 1.0f) :
|
||||
I2SSource(sampleRate, blockSize, sampleScale) {
|
||||
I2SSource(sampleRate, blockSize, sampleScale, true) {
|
||||
_config = {
|
||||
.mode = i2s_mode_t(I2S_MODE_MASTER | I2S_MODE_RX | I2S_MODE_ADC_BUILT_IN),
|
||||
.sample_rate = _sampleRate,
|
||||
@@ -587,18 +988,18 @@ class I2SAdcSource : public I2SSource {
|
||||
AudioSourceType getType(void) {return(Type_I2SAdc);}
|
||||
|
||||
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()."));
|
||||
DEBUGSR_PRINTLN("I2SAdcSource:: initialize().");
|
||||
_myADCchannel = 0x0F;
|
||||
if(!pinManager.allocatePin(audioPin, false, PinOwner::UM_Audioreactive)) {
|
||||
DEBUGSR_PRINTF("failed to allocate GPIO for audio analog input: %d\n", audioPin);
|
||||
if(!PinManager::allocatePin(audioPin, false, PinOwner::UM_Audioreactive)) {
|
||||
ERRORSR_PRINTF("failed to allocate GPIO for audio analog input: %d\n", audioPin);
|
||||
return;
|
||||
}
|
||||
_audioPin = audioPin;
|
||||
|
||||
// Determine Analog channel. Only Channels on ADC1 are supported
|
||||
int8_t channel = digitalPinToAnalogChannel(_audioPin);
|
||||
if (channel > 9) {
|
||||
DEBUGSR_PRINTF("Incompatible GPIO used for analog audio input: %d\n", _audioPin);
|
||||
if ((channel < 0) || (channel > 9)) { // channel == -1 means "not an ADC pin"
|
||||
DEBUGSR_PRINTF("AR: Incompatible GPIO used for analog audio input: %d\n", _audioPin);
|
||||
return;
|
||||
} else {
|
||||
adc_gpio_init(ADC_UNIT_1, adc_channel_t(channel));
|
||||
@@ -608,16 +1009,16 @@ class I2SAdcSource : public I2SSource {
|
||||
// Install Driver
|
||||
esp_err_t err = i2s_driver_install(I2S_NUM_0, &_config, 0, nullptr);
|
||||
if (err != ESP_OK) {
|
||||
DEBUGSR_PRINTF("Failed to install i2s driver: %d\n", err);
|
||||
ERRORSR_PRINTF("Failed to install i2s driver: %d\n", err);
|
||||
return;
|
||||
}
|
||||
|
||||
adc1_config_width(ADC_WIDTH_BIT_12); // ensure that ADC runs with 12bit resolution
|
||||
// adc1_config_width(ADC_WIDTH_BIT_12); // ensure that ADC runs with 12bit resolution - should not be needed, because i2s_set_adc_mode does that any way
|
||||
|
||||
// Enable I2S mode of ADC
|
||||
err = i2s_set_adc_mode(ADC_UNIT_1, adc1_channel_t(channel));
|
||||
if (err != ESP_OK) {
|
||||
DEBUGSR_PRINTF("Failed to set i2s adc mode: %d\n", err);
|
||||
DEBUGSR_PRINTF("AR: Failed to set i2s adc mode: %d\n", err);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -717,7 +1118,7 @@ class I2SAdcSource : public I2SSource {
|
||||
}
|
||||
|
||||
void deinitialize() {
|
||||
pinManager.deallocatePin(_audioPin, PinOwner::UM_Audioreactive);
|
||||
PinManager::deallocatePin(_audioPin, PinOwner::UM_Audioreactive);
|
||||
_initialized = false;
|
||||
_myADCchannel = 0x0F;
|
||||
|
||||
@@ -754,20 +1155,20 @@ class I2SAdcSource : public I2SSource {
|
||||
// a user recommended this: Try to set .communication_format to I2S_COMM_FORMAT_STAND_I2S and call i2s_set_clk() after i2s_set_pin().
|
||||
class SPH0654 : public I2SSource {
|
||||
public:
|
||||
SPH0654(SRate_t sampleRate, int blockSize, float sampleScale = 1.0f) :
|
||||
I2SSource(sampleRate, blockSize, sampleScale)
|
||||
SPH0654(SRate_t sampleRate, int blockSize, float sampleScale = 1.0f, bool i2sMaster=true) :
|
||||
I2SSource(sampleRate, blockSize, sampleScale, i2sMaster)
|
||||
{}
|
||||
|
||||
void initialize(int8_t i2swsPin, int8_t i2ssdPin, int8_t i2sckPin, int8_t = I2S_PIN_NO_CHANGE) {
|
||||
DEBUGSR_PRINTLN(F("SPH0654:: initialize();"));
|
||||
DEBUGSR_PRINTLN("SPH0654:: initialize();");
|
||||
I2SSource::initialize(i2swsPin, i2ssdPin, i2sckPin);
|
||||
#if !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3) && !defined(CONFIG_IDF_TARGET_ESP32S3)
|
||||
// these registers are only existing in "classic" ESP32
|
||||
REG_SET_BIT(I2S_TIMING_REG(I2S_NUM_0), BIT(9));
|
||||
REG_SET_BIT(I2S_CONF_REG(I2S_NUM_0), I2S_RX_MSB_SHIFT);
|
||||
REG_SET_BIT(I2S_TIMING_REG(AR_I2S_PORT), BIT(9));
|
||||
REG_SET_BIT(I2S_CONF_REG(AR_I2S_PORT), I2S_RX_MSB_SHIFT);
|
||||
#else
|
||||
#warning FIX ME! Please.
|
||||
#endif
|
||||
}
|
||||
};
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -27,18 +27,11 @@ Currently ESP8266 is not supported, due to low speed and small RAM of this chip.
|
||||
There are however plans to create a lightweight audioreactive for the 8266, with reduced features.
|
||||
## Installation
|
||||
|
||||
### using customised _arduinoFFT_ library for use with this usermod
|
||||
Add `-D USERMOD_AUDIOREACTIVE` to your PlatformIO environment `build_flags`, as well as `https://github.com/blazoncek/arduinoFFT.git` to your `lib_deps`.
|
||||
If you are not using PlatformIO (which you should) try adding `#define USERMOD_AUDIOREACTIVE` to *my_config.h* and make sure you have _arduinoFFT_ library downloaded and installed.
|
||||
### using latest _arduinoFFT_ library version 2.x
|
||||
The latest arduinoFFT release version should be used for audioreactive.
|
||||
|
||||
Customised _arduinoFFT_ library for use with this usermod can be found at https://github.com/blazoncek/arduinoFFT.git
|
||||
|
||||
### using latest (develop) _arduinoFFT_ library
|
||||
Alternatively, you can use the latest arduinoFFT development version.
|
||||
ArduinoFFT `develop` library is slightly more accurate, and slightly faster than our customised library, however also needs additional 2kB RAM.
|
||||
|
||||
* `build_flags` = `-D USERMOD_AUDIOREACTIVE` `-D UM_AUDIOREACTIVE_USE_NEW_FFT`
|
||||
* `lib_deps`= `https://github.com/kosme/arduinoFFT#develop @ 1.9.2`
|
||||
* `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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
84
usermods/deep_sleep/readme.md
Normal file
@@ -0,0 +1,84 @@
|
||||
# Deep Sleep usermod
|
||||
|
||||
This usermod unleashes the low power capabilities of th ESP: when you power off your LEDs (using the UI power button or a macro) the ESP will be put into deep sleep mode, reducing power consumption to a minimum.
|
||||
During deep sleep the ESP is shut down completely: no WiFi, no CPU, no outputs. The only way to wake it up is to use an external signal or a button. Once it wakes from deep sleep it reboots so ***make sure to use a boot-up preset.***
|
||||
|
||||
# A word of warning
|
||||
|
||||
When you disable the WLED option 'Turn LEDs on after power up/reset' and 'DelaySleep' is set to zero the ESP will go into deep sleep directly after power-up and only start WLED after it has been woken up.
|
||||
If the ESP can not be awoken from deep sleep due to a wrong configuration it has to be factory reset, disabling sleep at power-up. There is no other way to wake it up.
|
||||
|
||||
# Power Consumption in deep sleep
|
||||
|
||||
The current drawn by the ESP in deep sleep mode depends on the type and is in the range of 5uA-20uA (as in micro Amperes):
|
||||
- ESP32: 10uA
|
||||
- ESP32 S3: 8uA
|
||||
- ESP32 S2: 20uA
|
||||
- ESP32 C3: 5uA
|
||||
- ESP8266: 20uA (not supported in this usermod)
|
||||
|
||||
However, there is usually additional components on a controller that increase the value:
|
||||
- Power LED: the power LED on a ESP board draws 500uA - 1mA
|
||||
- LDO: the voltage regulator also draws idle current. Depending on the type used this can be around 50uA up to 10mA (LM1117). Special low power LDOs with very low idle currents do exist
|
||||
- Digital LEDs: WS2812 for example draw a current of about 1mA per LED. To make good use of this usermod it is required to power them off using MOSFETs or a Relay
|
||||
|
||||
For lowest power consumption, remove the Power LED and make sure your board does not use an LM1117. On a ESP32 C3 Supermini with the power LED removed (no other modifications) powered through the 5V pin I measured a current draw of 50uA in deep sleep.
|
||||
|
||||
# Useable GPIOs
|
||||
|
||||
The GPIOs that can be used to wake the ESP from deep sleep are limited. Only pins connected to the internal RTC unit can be used:
|
||||
|
||||
- ESP32: GPIO 0, 2, 4, 12-15, 25-39
|
||||
- ESP32 S3: GPIO 0-21
|
||||
- ESP32 S2: GPIO 0-21
|
||||
- ESP32 C3: GPIO 0-5
|
||||
- ESP8266 is not supported in this usermod
|
||||
|
||||
You can however use the selected wake-up pin normally in WLED, it only gets activated as a wake-up pin when your LEDs are powered down.
|
||||
|
||||
# Limitations
|
||||
|
||||
To keep this usermod simple and easy to use, it is a very basic implementation of the low-power capabilities provided by the ESP. If you need more advanced control you are welcome to implement your own version based on this usermod.
|
||||
|
||||
## Usermod installation
|
||||
|
||||
Use `#define USERMOD_DEEP_SLEEP` in wled.h or `-D USERMOD_DEEP_SLEEP` in your platformio.ini. Settings can be changed in the usermod config UI.
|
||||
|
||||
### Define Settings
|
||||
|
||||
There are five parameters you can set:
|
||||
|
||||
- GPIO: the pin to use for wake-up
|
||||
- WakeWhen High/Low: the pin state that triggers the wake-up
|
||||
- Pull-up/down disable: enable or disable the internal pullup resistors during sleep (does not affect normal use while running)
|
||||
- Wake after: if set larger than 0, ESP will automatically wake-up after this many seconds (Turn LEDs on after power up/reset is overriden, it will always turn on)
|
||||
- Delay sleep: if set larger than 0, ESP will not go to sleep for this many seconds after you power it off. Timer is reset when switched back on during this time.
|
||||
|
||||
To override the default settings, place the `#define` in wled.h or add `-D DEEPSLEEP_xxx` to your platformio_override.ini build flags
|
||||
|
||||
* `DEEPSLEEP_WAKEUPPIN x` - define the pin to be used for wake-up, see list of useable pins above. The pin can be used normally as a button pin in WLED.
|
||||
* `DEEPSLEEP_WAKEWHENHIGH` - if defined, wakes up when pin goes high (default is low)
|
||||
* `DEEPSLEEP_DISABLEPULL` - if defined, internal pullup/pulldown is disabled in deep sleep (default is ebnabled)
|
||||
* `DEEPSLEEP_WAKEUPINTERVAL` - number of seconds after which a wake-up happens automatically, sooner if button is pressed. 0 = never. accuracy is about 2%
|
||||
* `DEEPSLEEP_DELAY` - delay between power-off and sleep
|
||||
|
||||
example for env build flags:
|
||||
`-D USERMOD_DEEP_SLEEP`
|
||||
`-D DEEPSLEEP_WAKEUPPIN=4`
|
||||
`-D DEEPSLEEP_DISABLEPULL=0` ;enable pull-up/down resistors by default
|
||||
`-D DEEPSLEEP_WAKEUPINTERVAL=43200` ;wake up after 12 hours (or when button is pressed)
|
||||
|
||||
### Hardware Setup
|
||||
|
||||
To wake from deep-sleep an external trigger signal on the configured GPIO is required. When using timed-only wake-up, use a GPIO that has an on-board pull-up resistor (GPIO0 on most boards). When using push-buttons it is highly recommended to use an external pull-up resistor: not all IO's on all devices have properly working internal resistors.
|
||||
|
||||
Using sensors like PIR, IR, touch sensors or any other sensor with a digital output can be used instead of a button.
|
||||
|
||||
now go on and save some power
|
||||
@dedehai
|
||||
|
||||
## Change log
|
||||
2024-09
|
||||
* Initial version
|
||||
2024-10
|
||||
* Changed from #define configuration to UI configuration
|
||||
227
usermods/deep_sleep/usermod_deep_sleep.h
Normal file
@@ -0,0 +1,227 @@
|
||||
#pragma once
|
||||
|
||||
#include "wled.h"
|
||||
#include "driver/rtc_io.h"
|
||||
|
||||
#ifdef ESP8266
|
||||
#error The "Deep Sleep" usermod does not support ESP8266
|
||||
#endif
|
||||
|
||||
#ifndef DEEPSLEEP_WAKEUPPIN
|
||||
#define DEEPSLEEP_WAKEUPPIN 0
|
||||
#endif
|
||||
#ifndef DEEPSLEEP_WAKEWHENHIGH
|
||||
#define DEEPSLEEP_WAKEWHENHIGH 0
|
||||
#endif
|
||||
#ifndef DEEPSLEEP_DISABLEPULL
|
||||
#define DEEPSLEEP_DISABLEPULL 1
|
||||
#endif
|
||||
#ifndef DEEPSLEEP_WAKEUPINTERVAL
|
||||
#define DEEPSLEEP_WAKEUPINTERVAL 0
|
||||
#endif
|
||||
#ifndef DEEPSLEEP_DELAY
|
||||
#define DEEPSLEEP_DELAY 1
|
||||
#endif
|
||||
|
||||
RTC_DATA_ATTR bool powerup = true; // variable in RTC data persists on a reboot
|
||||
|
||||
class DeepSleepUsermod : public Usermod {
|
||||
|
||||
private:
|
||||
|
||||
bool enabled = true;
|
||||
bool initDone = false;
|
||||
uint8_t wakeupPin = DEEPSLEEP_WAKEUPPIN;
|
||||
uint8_t wakeWhenHigh = DEEPSLEEP_WAKEWHENHIGH; // wake up when pin goes high if 1, triggers on low if 0
|
||||
bool noPull = true; // use pullup/pulldown resistor
|
||||
int wakeupAfter = DEEPSLEEP_WAKEUPINTERVAL; // in seconds, <=0: button only
|
||||
int sleepDelay = DEEPSLEEP_DELAY; // in seconds, 0 = immediate
|
||||
int delaycounter = 5; // delay deep sleep at bootup until preset settings are applied
|
||||
uint32_t lastLoopTime = 0;
|
||||
// string that are used multiple time (this will save some flash memory)
|
||||
static const char _name[];
|
||||
static const char _enabled[];
|
||||
|
||||
bool pin_is_valid(uint8_t wakePin) {
|
||||
#ifdef CONFIG_IDF_TARGET_ESP32 //ESP32: GPIOs 0,2,4, 12-15, 25-39 can be used for wake-up
|
||||
if (wakePin == 0 || wakePin == 2 || wakePin == 4 || (wakePin >= 12 && wakePin <= 15) || (wakePin >= 25 && wakePin <= 27) || (wakePin >= 32 && wakePin <= 39)) {
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
#if defined(CONFIG_IDF_TARGET_ESP32S3) || defined(CONFIG_IDF_TARGET_ESP32S2) //ESP32 S3 & S3: GPIOs 0-21 can be used for wake-up
|
||||
if (wakePin <= 21) {
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
#ifdef CONFIG_IDF_TARGET_ESP32C3 // ESP32 C3: GPIOs 0-5 can be used for wake-up
|
||||
if (wakePin <= 5) {
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
DEBUG_PRINTLN(F("Error: unsupported deep sleep wake-up pin"));
|
||||
return false;
|
||||
}
|
||||
|
||||
public:
|
||||
|
||||
inline void enable(bool enable) { enabled = enable; } // Enable/Disable the usermod
|
||||
inline bool isEnabled() { return enabled; } //Get usermod enabled/disabled state
|
||||
|
||||
// setup is called at boot (or in this case after every exit of sleep mode)
|
||||
void setup() {
|
||||
//TODO: if the de-init of RTC pins is required to do it could be done here
|
||||
//rtc_gpio_deinit(wakeupPin);
|
||||
initDone = true;
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if (!enabled || !offMode) { // disabled or LEDs are on
|
||||
lastLoopTime = 0; // reset timer
|
||||
return;
|
||||
}
|
||||
|
||||
if (sleepDelay > 0) {
|
||||
if(lastLoopTime == 0) lastLoopTime = millis(); // initialize
|
||||
if (millis() - lastLoopTime < sleepDelay * 1000) {
|
||||
return; // wait until delay is over
|
||||
}
|
||||
}
|
||||
|
||||
if(powerup == false && delaycounter) { // delay sleep in case a preset is being loaded and turnOnAtBoot is disabled (handleIO() does enable offMode temporarily in this case)
|
||||
delaycounter--;
|
||||
if(delaycounter == 2 && offMode) { // force turn on, no matter the settings (device is bricked if user set sleepDelay=0, no bootup preset and turnOnAtBoot=false)
|
||||
if (briS == 0) bri = 10; // turn on at low brightness
|
||||
else bri = briS;
|
||||
strip.setBrightness(bri); // needed to make handleIO() not turn off LEDs (really? does not help in bootup preset)
|
||||
offMode = false;
|
||||
applyPresetWithFallback(0, CALL_MODE_INIT, FX_MODE_STATIC, 0); // try to apply preset 0, fallback to static
|
||||
if (rlyPin >= 0) {
|
||||
digitalWrite(rlyPin, (rlyMde ? HIGH : LOW)); // turn relay on TODO: this should be done by wled, what function to call?
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
DEBUG_PRINTLN(F("DeepSleep UM: entering deep sleep..."));
|
||||
powerup = false; // turn leds on in all subsequent bootups (overrides Turn LEDs on after power up/reset' at reboot)
|
||||
if(!pin_is_valid(wakeupPin)) return;
|
||||
esp_err_t halerror = ESP_OK;
|
||||
pinMode(wakeupPin, INPUT); // make sure GPIO is input with pullup/pulldown disabled
|
||||
esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_ALL); //disable all wake-up sources (just in case)
|
||||
|
||||
if(wakeupAfter)
|
||||
esp_sleep_enable_timer_wakeup((uint64_t)wakeupAfter * (uint64_t)1e6); //sleep for x seconds
|
||||
|
||||
#if defined(CONFIG_IDF_TARGET_ESP32C3) // ESP32 C3
|
||||
if(noPull)
|
||||
gpio_sleep_set_pull_mode((gpio_num_t)wakeupPin, GPIO_FLOATING);
|
||||
else { // enable pullup/pulldown resistor
|
||||
if(wakeWhenHigh)
|
||||
gpio_sleep_set_pull_mode((gpio_num_t)wakeupPin, GPIO_PULLDOWN_ONLY);
|
||||
else
|
||||
gpio_sleep_set_pull_mode((gpio_num_t)wakeupPin, GPIO_PULLUP_ONLY);
|
||||
}
|
||||
if(wakeWhenHigh)
|
||||
halerror = esp_deep_sleep_enable_gpio_wakeup(1<<wakeupPin, ESP_GPIO_WAKEUP_GPIO_HIGH);
|
||||
else
|
||||
halerror = esp_deep_sleep_enable_gpio_wakeup(1<<wakeupPin, ESP_GPIO_WAKEUP_GPIO_LOW);
|
||||
#else // ESP32, S2, S3
|
||||
gpio_pulldown_dis((gpio_num_t)wakeupPin); // disable internal pull resistors for GPIO use
|
||||
gpio_pullup_dis((gpio_num_t)wakeupPin);
|
||||
if(noPull) {
|
||||
rtc_gpio_pullup_dis((gpio_num_t)wakeupPin);
|
||||
rtc_gpio_pulldown_dis((gpio_num_t)wakeupPin);
|
||||
}
|
||||
else { // enable pullup/pulldown resistor for RTC use
|
||||
if(wakeWhenHigh)
|
||||
rtc_gpio_pulldown_en((gpio_num_t)wakeupPin);
|
||||
else
|
||||
rtc_gpio_pullup_en((gpio_num_t)wakeupPin);
|
||||
}
|
||||
if(wakeWhenHigh)
|
||||
halerror = esp_sleep_enable_ext0_wakeup((gpio_num_t)wakeupPin, HIGH); // only RTC pins can be used
|
||||
else
|
||||
halerror = esp_sleep_enable_ext0_wakeup((gpio_num_t)wakeupPin, LOW);
|
||||
#endif
|
||||
|
||||
delay(1); // wait for pin to be ready
|
||||
if(halerror == ESP_OK) esp_deep_sleep_start(); // go into deep sleep
|
||||
else DEBUG_PRINTLN(F("sleep failed"));
|
||||
}
|
||||
|
||||
//void connected() {} //unused, this is called every time the WiFi is (re)connected
|
||||
|
||||
void addToConfig(JsonObject& root) override
|
||||
{
|
||||
JsonObject top = root.createNestedObject(FPSTR(_name));
|
||||
top[FPSTR(_enabled)] = enabled;
|
||||
//save these vars persistently whenever settings are saved
|
||||
top["gpio"] = wakeupPin;
|
||||
top["wakeWhen"] = wakeWhenHigh;
|
||||
top["pull"] = noPull;
|
||||
top["wakeAfter"] = wakeupAfter;
|
||||
top["delaySleep"] = sleepDelay;
|
||||
}
|
||||
|
||||
bool readFromConfig(JsonObject& root) override
|
||||
{
|
||||
// default settings values could be set here (or below using the 3-argument getJsonValue()) instead of in the class definition or constructor
|
||||
// setting them inside readFromConfig() is slightly more robust, handling the rare but plausible use case of single value being missing after boot (e.g. if the cfg.json was manually edited and a value was removed)
|
||||
JsonObject top = root[FPSTR(_name)];
|
||||
bool configComplete = !top.isNull();
|
||||
|
||||
configComplete &= getJsonValue(top[FPSTR(_enabled)], enabled);
|
||||
configComplete &= getJsonValue(top["gpio"], wakeupPin, DEEPSLEEP_WAKEUPPIN);
|
||||
if (!pin_is_valid(wakeupPin)) {
|
||||
wakeupPin = 0; // set to 0 if invalid
|
||||
configComplete = false; // Mark config as incomplete if pin is invalid
|
||||
}
|
||||
configComplete &= getJsonValue(top["wakeWhen"], wakeWhenHigh, DEEPSLEEP_WAKEWHENHIGH); // default to wake on low
|
||||
configComplete &= getJsonValue(top["pull"], noPull, DEEPSLEEP_DISABLEPULL); // default to no pullup/pulldown
|
||||
configComplete &= getJsonValue(top["wakeAfter"], wakeupAfter, DEEPSLEEP_WAKEUPINTERVAL);
|
||||
configComplete &= getJsonValue(top["delaySleep"], sleepDelay, DEEPSLEEP_DELAY);
|
||||
|
||||
return configComplete;
|
||||
}
|
||||
|
||||
/*
|
||||
* appendConfigData() is called when user enters usermod settings page
|
||||
* it may add additional metadata for certain entry fields (adding drop down is possible)
|
||||
* be careful not to add too much as oappend() buffer is limited to 3k
|
||||
*/
|
||||
void appendConfigData() override
|
||||
{
|
||||
// dropdown for wakeupPin
|
||||
oappend(SET_F("dd=addDropdown('DeepSleep','gpio');"));
|
||||
for (int pin = 0; pin < 40; pin++) { // possible pins are in range 0-39
|
||||
if (pin_is_valid(pin)) {
|
||||
oappend(SET_F("addOption(dd,'"));
|
||||
oappend(String(pin).c_str());
|
||||
oappend(SET_F("',"));
|
||||
oappend(String(pin).c_str());
|
||||
oappend(SET_F(");"));
|
||||
}
|
||||
}
|
||||
|
||||
oappend(SET_F("dd=addDropdown('DeepSleep','wakeWhen');"));
|
||||
oappend(SET_F("addOption(dd,'Low',0);"));
|
||||
oappend(SET_F("addOption(dd,'High',1);"));
|
||||
|
||||
oappend(SET_F("addInfo('DeepSleep:pull',1,'','-up/down disable: ');")); // first string is suffix, second string is prefix
|
||||
oappend(SET_F("addInfo('DeepSleep:wakeAfter',1,'seconds <i>(0 = never)<i>');"));
|
||||
oappend(SET_F("addInfo('DeepSleep:delaySleep',1,'seconds <i>(0 = sleep at powerup)<i>');")); // first string is suffix, second string is prefix
|
||||
}
|
||||
|
||||
/*
|
||||
* 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_DEEP_SLEEP;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
// add more strings here to reduce flash memory usage
|
||||
const char DeepSleepUsermod::_name[] PROGMEM = "DeepSleep";
|
||||
const char DeepSleepUsermod::_enabled[] PROGMEM = "enabled";
|
||||
@@ -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;
|
||||
@@ -667,7 +667,7 @@ void MultiRelay::addToJsonInfo(JsonObject &root) {
|
||||
for (int i=0; i<MULTI_RELAY_MAX_RELAYS; i++) {
|
||||
if (_relay[i].pin<0 || !_relay[i].external) continue;
|
||||
uiDomString = F("Relay "); uiDomString += i;
|
||||
JsonArray infoArr = user.createNestedArray(uiDomString); // timer value
|
||||
infoArr = user.createNestedArray(uiDomString); // timer value
|
||||
|
||||
uiDomString = F("<button class=\"btn btn-xs\" onclick=\"requestJson({");
|
||||
uiDomString += FPSTR(_name);
|
||||
@@ -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
@@ -0,0 +1,254 @@
|
||||
# A mod for using Pixel Dice with ESP32S3 boards
|
||||
|
||||
A usermod to connect to and handle rolls from [Pixels Dice](https://gamewithpixels.com/). WLED acts as both an display controller, and a gateway to connect the die to the Wifi network.
|
||||
|
||||
High level features:
|
||||
|
||||
* Several LED effects that respond to die rolls
|
||||
* Effect color and parameters can be modified like any other effect
|
||||
* Different die can be set to control different segments
|
||||
* An optional GUI on a TFT screen with custom button controls
|
||||
* Gives die connection and roll status
|
||||
* Can do basic LED effect controls
|
||||
* Can display custom info for different roll types (ie. RPG stats/spell info)
|
||||
* Publish MQTT events from die rolls
|
||||
* Also report the selected roll type
|
||||
* Control settings through the WLED web
|
||||
|
||||
See <https://www.robopenguins.com/pixels-dice-box/> for a write up of the design process of the hardware and software I used this with.
|
||||
|
||||
I also set up a custom web installer for the usermod at <https://axlan.github.io/WLED-WebInstaller/> for 8MB ESP32-S3 boards.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
<!-- TOC start (generated with https://github.com/derlin/bitdowntoc) -->
|
||||
* [Demos](#demos)
|
||||
+ [TFT GUI](#tft-gui)
|
||||
+ [Multiple Die Controlling Different Segments](#multiple-die-controlling-different-segments)
|
||||
* [Hardware](#hardware)
|
||||
* [Library used](#library-used)
|
||||
* [Compiling](#compiling)
|
||||
+ [platformio_override.ini](#platformio_overrideini)
|
||||
+ [Manual platformio.ini changes](#manual-platformioini-changes)
|
||||
* [Configuration](#configuration)
|
||||
+ [Controlling Dice Connections](#controlling-dice-connections)
|
||||
+ [Controlling Effects](#controlling-effects)
|
||||
- [DieSimple](#diesimple)
|
||||
- [DiePulse](#diepulse)
|
||||
- [DieCheck](#diecheck)
|
||||
* [TFT GUI](#tft-gui-1)
|
||||
+ [Status](#status)
|
||||
+ [Effect Menu](#effect-menu)
|
||||
+ [Roll Info](#roll-info)
|
||||
* [MQTT](#mqtt)
|
||||
* [Potential Modifications and Additional Features](#potential-modifications-and-additional-features)
|
||||
* [ESP32 Issues](#esp32-issues)
|
||||
<!-- TOC end -->
|
||||
|
||||
<!-- TOC --><a name="demos"></a>
|
||||
## Demos
|
||||
|
||||
<!-- TOC --><a name="tft-gui"></a>
|
||||
### TFT GUI
|
||||
[](https://youtu.be/VNsHq1TbiW8)
|
||||
|
||||
<!-- TOC --><a name="multiple-die-controlling-different-segments"></a>
|
||||
### Multiple Die Controlling Different Segments
|
||||
[](https://youtu.be/oCDr44C-qwM)
|
||||
|
||||
<!-- TOC --><a name="hardware"></a>
|
||||
## Hardware
|
||||
|
||||
The main purpose of this mod is to support [Pixels Dice](https://gamewithpixels.com/). The board acts as a BLE central for the dice acting as peripherals. While any ESP32 variant with BLE capabilities should be able to support this usermod, in practice I found that the original ESP32 did not work. See [ESP32 Issues](#esp32-issues) for a deeper dive.
|
||||
|
||||
The only other ESP32 variant I tested was the ESP32-S3, which worked without issue. While there's still concern over the contention between BLE and WiFi for the radio, I haven't noticed any performance impact in practice. The only special behavior that was needed was setting `noWifiSleep = false;` to allow the OS to sleep the WiFi when the BLE is active.
|
||||
|
||||
In addition, the BLE stack requires a lot of flash. This build takes 1.9MB with the TFT code, or 1.85MB without it. This makes it too big to fit in the `tools/WLED_ESP32_4MB_256KB_FS.csv` partition layout, and I needed to make a `WLED_ESP32_4MB_64KB_FS.csv` to even fit on 4MB devices. This only has 64KB of file system space, which is functional, but users with more than a handful of presets would run into problems with 64KB only. This means that while 4MB can be supported, larger flash sizes are needed for full functionality.
|
||||
|
||||
The basic build of this usermod doesn't require any special hardware. However, the LCD status GUI was specifically designed for the [LILYGO T-QT Pro](https://www.lilygo.cc/products/t-qt-pro).
|
||||
|
||||
It should be relatively easy to support other displays, though the positioning of the text may need to be adjusted.
|
||||
|
||||
<!-- TOC --><a name="library-used"></a>
|
||||
## Library used
|
||||
|
||||
[axlan/pixels-dice-interface](https://github.com/axlan/arduino-pixels-dice)
|
||||
|
||||
Optional: [Bodmer/TFT_eSPI](https://github.com/Bodmer/TFT_eSPI)
|
||||
|
||||
<!-- TOC --><a name="compiling"></a>
|
||||
## Compiling
|
||||
|
||||
<!-- TOC --><a name="platformio_overrideini"></a>
|
||||
### platformio_override.ini
|
||||
|
||||
Copy and update the example `platformio_override.ini.sample` to the root directory of your particular build (renaming it `platformio_override.ini`).
|
||||
This file should be placed in the same directory as `platformio.ini`. This file is set up for the [LILYGO T-QT Pro](https://www.lilygo.cc/products/t-qt-pro). Specifically, the 8MB flash version. See the next section for notes on setting the build flags. For other boards, you may want to use a different environment as the basis.
|
||||
|
||||
<!-- TOC --><a name="manual-platformioini-changes"></a>
|
||||
### Manual platformio.ini changes
|
||||
|
||||
Using the `platformio_override.ini.sample` as a reference, you'll need to update the `build_flags` and `lib_deps` of the target you're building for.
|
||||
|
||||
If you don't need the TFT GUI, you just need to add
|
||||
|
||||
|
||||
```ini
|
||||
...
|
||||
build_flags =
|
||||
...
|
||||
-D USERMOD_PIXELS_DICE_TRAY ;; Enables this UserMod
|
||||
lib_deps =
|
||||
...
|
||||
ESP32 BLE Arduino
|
||||
axlan/pixels-dice-interface @ 1.2.0
|
||||
...
|
||||
```
|
||||
|
||||
For the TFT support you'll need to add `Bodmer/TFT_eSPI` to `lib_deps`, and all of the required TFT parameters to `build_flags` (see `platformio_override.ini.sample`).
|
||||
|
||||
Save the `platformio.ini` file, and perform the desired build.
|
||||
|
||||
<!-- TOC --><a name="configuration"></a>
|
||||
## Configuration
|
||||
|
||||
In addition to configuring which dice to connect to, this mod uses a lot of the built in WLED features:
|
||||
* The LED segments, effects, and customization parameters
|
||||
* The buttons for the UI
|
||||
* The MQTT settings for reporting the dice rolls
|
||||
|
||||
<!-- TOC --><a name="controlling-dice-connections"></a>
|
||||
### Controlling Dice Connections
|
||||
|
||||
**NOTE:** To configure the die itself (set its name, the die LEDs, etc.), you still need to use the Pixels Dice phone App.
|
||||
|
||||
The usermods settings page has the configuration for controlling the dice and the display:
|
||||
* Ble Scan Duration - The time to look for BLE broadcasts before taking a break
|
||||
* Rotation - If display used, set this parameter to rotate the display.
|
||||
|
||||
The main setting here though are the Die 0 and 1 settings. A slot is disabled if it's left blank. Putting the name of a die will make that slot only connect to die with that name. Alteratively, if the name is set to `*` the slot will use the first unassociated die it sees. Saving the configuration while a wildcard slot is connected to a die will replace the `*` with that die's name.
|
||||
|
||||
**NOTE:** The slot a die is in is important since that's how they're identified for controlling LED effects. Effects can be set to respond to die 0, 1, or any.
|
||||
|
||||
The configuration also includes the pins configured in the TFT build flags. These are just so the UI recognizes that these pins are being used. The [Bodmer/TFT_eSPI](https://github.com/Bodmer/TFT_eSPI) requires that these are set at build time and changing these values is ignored.
|
||||
|
||||
<!-- TOC --><a name="controlling-effects"></a>
|
||||
### Controlling Effects
|
||||
|
||||
The die effects for rolls take advantage of most of the normal WLED effect features: <https://kno.wled.ge/features/effects/>.
|
||||
|
||||
If you have different segments, they can have different effects driven by the same die, or different dice.
|
||||
|
||||
<!-- TOC --><a name="diesimple"></a>
|
||||
#### DieSimple
|
||||
Turn off LEDs while rolling, than light up solid LEDs in proportion to die roll.
|
||||
|
||||
* Color 1 - Selects the "good" color that increases based on the die roll
|
||||
* Color 2 - Selects the "background" color for the rest of the segment
|
||||
* Custom 1 - Sets which die should control this effect. If the value is greater then 1, it will respond to both dice.
|
||||
|
||||
<!-- TOC --><a name="diepulse"></a>
|
||||
#### DiePulse
|
||||
Play `breath` effect while rolling, than apply `blend` effect in proportion to die roll.
|
||||
|
||||
* Color 1 - See `breath` and `blend`
|
||||
* Color 2 - Selects the "background" color for the rest of the segment
|
||||
* Palette - See `breath` and `blend`
|
||||
* Custom 1 - Sets which die should control this effect. If the value is greater then 1, it will respond to both dice.
|
||||
|
||||
<!-- TOC --><a name="diecheck"></a>
|
||||
#### DieCheck
|
||||
Play `running` effect while rolling, than apply `glitter` effect if roll passes threshold, or `gravcenter` if roll is below.
|
||||
|
||||
* Color 1 - See `glitter` and `gravcenter`, used as first color for `running`
|
||||
* Color 2 - See `glitter` and `gravcenter`
|
||||
* Color 3 - Used as second color for `running`
|
||||
* Palette - See `glitter` and `gravcenter`
|
||||
* Custom 1 - Sets which die should control this effect. If the value is greater then 1, it will respond to both dice.
|
||||
* Custom 2 - Sets the threshold for success animation. For example if 10, success plays on rolls of 10 or above.
|
||||
|
||||
<!-- TOC --><a name="tft-gui-1"></a>
|
||||
## TFT GUI
|
||||
|
||||
The optional TFT GUI currently supports 3 "screens":
|
||||
1. Status
|
||||
2. Effect Control
|
||||
3. Roll Info
|
||||
|
||||
Double pressing the right button goes forward through the screens, and double pressing left goes back (with rollover).
|
||||
|
||||
<!-- TOC --><a name="status"></a>
|
||||
### Status
|
||||
<img src="images/status.webp" alt="Status Menu" width="200"/>
|
||||
|
||||
Shows the status of each die slot (0 on top and 1 on the bottom).
|
||||
|
||||
If a die is connected, its roll stats and battery status are shown. The rolls will continue to be tracked even when viewing other screens.
|
||||
|
||||
Long press either button to clear the roll stats.
|
||||
|
||||
<!-- TOC --><a name="effect-menu"></a>
|
||||
### Effect Menu
|
||||
<img src="images/effect.webp" alt="Effect Menu" width="200"/>
|
||||
|
||||
Allows limited customization of the die effect for the currently selected LED segment.
|
||||
|
||||
The left button moves the cursor (blue box) up and down the options for the current field.
|
||||
|
||||
The right button updates the value for the field.
|
||||
|
||||
The first field is the effect. Updating it will switch between the die effects.
|
||||
|
||||
The DieCheck effect has an additional field "PASS". Pressing the right button on this field will copy the current face up value from the most recently rolled die.
|
||||
|
||||
Long pressing either value will set the effect parameters (color, palette, controlling dice, etc.) to a default set of values.
|
||||
|
||||
<!-- TOC --><a name="roll-info"></a>
|
||||
### Roll Info
|
||||
<img src="images/info.webp" alt="Roll Info Menu" width="200"/>
|
||||
|
||||
Sets the "roll type" reported by MQTT events and can show additional info.
|
||||
|
||||
Pressing the right button goes forward through the rolls, and double pressing left goes back (with rollover).
|
||||
|
||||
The names and info for the rolls are generated from the `usermods/pixels_dice_tray/generate_roll_info.py` script. It updates `usermods/pixels_dice_tray/roll_info.h` with code generated from a simple markdown language.
|
||||
|
||||
<!-- TOC --><a name="mqtt"></a>
|
||||
## MQTT
|
||||
|
||||
See <https://kno.wled.ge/interfaces/mqtt/> for general MQTT configuration for WLED.
|
||||
|
||||
The usermod produces two types of events
|
||||
|
||||
* `$mqttDeviceTopic/dice/roll` - JSON that reports each die roll event with the following keys.
|
||||
- name - The name of the die that triggered the event
|
||||
- state - Integer indicating the die state `[UNKNOWN = 0, ON_FACE = 1, HANDLING = 2, ROLLING = 3, CROOKED = 4]`
|
||||
- val - The value on the die's face. For d20 1-20
|
||||
- time - The uptime timestamp the roll was received in milliseconds.
|
||||
* `$mqttDeviceTopic/dice/roll_label` - A string that indicates the roll type selected in the [Roll Info](#roll-info) TFT menu.
|
||||
|
||||
Where `$mqttDeviceTopic` is the topic set in the WLED MQTT configuration.
|
||||
|
||||
Events can be logged to a CSV file using the script `usermods/pixels_dice_tray/mqtt_client/mqtt_logger.py`. These can then be used to generate interactive HTML plots with `usermods/pixels_dice_tray/mqtt_client/mqtt_plotter.py`.
|
||||
|
||||
<img src="images/roll_plot.png" alt="Roll Plot"/>
|
||||
|
||||
<!-- TOC --><a name="potential-modifications-and-additional-features"></a>
|
||||
## Potential Modifications and Additional Features
|
||||
|
||||
This usermod is in support of a particular dice box project, but it would be fairly straightforward to extend for other applications.
|
||||
* Add more dice - There's no reason that several more dice slots couldn't be allowed. In addition LED effects that use multiple dice could be added (e.g. a contested roll).
|
||||
* Better support for die other then d20's. There's a few places where I assume the die is a d20. It wouldn't be that hard to support arbitrary die sizes.
|
||||
* TFT Menu - The menu system is pretty extensible. I put together some basic things I found useful, and was mainly limited by the screen size.
|
||||
* Die controlled UI - I originally planned to make an alternative UI that used the die directly. You'd press a button, and the current face up on the die would trigger an action. This was an interesting idea, but didn't seem to practical since I could more flexibly reproduce this by responding to the dice MQTT events.
|
||||
|
||||
<!-- TOC --><a name="esp32-issues"></a>
|
||||
## ESP32 Issues
|
||||
|
||||
I really wanted to have this work on the original ESP32 boards to lower the barrier to entry, but there were several issues.
|
||||
|
||||
First there are the issues with the partition sizes for 4MB mentioned in the [Hardware](#hardware) section.
|
||||
|
||||
The bigger issue is that the build consistently crashes if the BLE scan task starts up. It's a bit unclear to me exactly what is failing since the backtrace is showing an exception in `new[]` memory allocation in the UDP stack. There appears to be a ton of heap available, so my guess is that this is a synchronization issue of some sort from the tasks running in parallel. I tried messing with the task core affinity a bit but didn't make much progress. It's not really clear what difference between the ESP32S3 and ESP32 would cause this difference.
|
||||
|
||||
At the end of the day, its generally not advised to run the BLE and Wifi at the same time anyway (though it appears to work without issue on the ESP32S3). Probably the best path forward would be to switch between them. This would actually not be too much of an issue, since discovering and getting data from the die should be possible to do in bursts (at least in theory).
|
||||
6
usermods/pixels_dice_tray/WLED_ESP32_4MB_64KB_FS.csv
Normal file
@@ -0,0 +1,6 @@
|
||||
# Name, Type, SubType, Offset, Size, Flags
|
||||
nvs, data, nvs, 0x9000, 0x5000,
|
||||
otadata, data, ota, 0xe000, 0x2000,
|
||||
app0, app, ota_0, 0x10000, 0x1F0000,
|
||||
app1, app, ota_1, 0x200000,0x1F0000,
|
||||
spiffs, data, spiffs, 0x3F0000,0x10000,
|
||||
|
76
usermods/pixels_dice_tray/dice_state.h
Normal file
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* Structs for passing around usermod state
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <pixels_dice_interface.h> // https://github.com/axlan/arduino-pixels-dice
|
||||
|
||||
/**
|
||||
* Here's how the rolls are tracked in this usermod.
|
||||
* 1. The arduino-pixels-dice library reports rolls and state mapped to
|
||||
* PixelsDieID.
|
||||
* 2. The "configured_die_names" sets which die to connect to and their order.
|
||||
* 3. The rest of the usermod references the die by this order (ie. the LED
|
||||
* effect is triggered for rolls for die 0).
|
||||
*/
|
||||
|
||||
static constexpr size_t MAX_NUM_DICE = 2;
|
||||
static constexpr uint8_t INVALID_ROLL_VALUE = 0xFF;
|
||||
|
||||
/**
|
||||
* The state of the connected die, and new events since the last update.
|
||||
*/
|
||||
struct DiceUpdate {
|
||||
// The vectors to hold results queried from the library
|
||||
// Since vectors allocate data, it's more efficient to keep reusing an instance
|
||||
// instead of declaring them on the stack.
|
||||
std::vector<pixels::PixelsDieID> dice_list;
|
||||
pixels::RollUpdates roll_updates;
|
||||
pixels::BatteryUpdates battery_updates;
|
||||
// The PixelsDieID for each dice index. 0 if the die isn't connected.
|
||||
// The ordering here matches configured_die_names.
|
||||
std::array<pixels::PixelsDieID, MAX_NUM_DICE> connected_die_ids{0, 0};
|
||||
};
|
||||
|
||||
struct DiceSettings {
|
||||
// The mapping of dice names, to the index of die used for effects (ie. The
|
||||
// die named "Cat" is die 0). BLE discovery will stop when all the dice are
|
||||
// found. The die slot is disabled if the name is empty. If the name is "*",
|
||||
// the slot will use the first unassociated die it sees.
|
||||
std::array<std::string, MAX_NUM_DICE> configured_die_names{"*", "*"};
|
||||
// A label set to describe the next die roll. Index into GetRollName().
|
||||
uint8_t roll_label = INVALID_ROLL_VALUE;
|
||||
};
|
||||
|
||||
// These are updated in the main loop, but accessed by the effect functions as
|
||||
// well. My understand is that both of these accesses should be running on the
|
||||
// same "thread/task" since WLED doesn't directly create additional threads. The
|
||||
// exception would be network callbacks and interrupts, but I don't believe
|
||||
// these accesses are triggered by those. If synchronization was needed, I could
|
||||
// look at the example in `requestJSONBufferLock()`.
|
||||
std::array<pixels::RollEvent, MAX_NUM_DICE> last_die_events;
|
||||
|
||||
static pixels::RollEvent GetLastRoll() {
|
||||
pixels::RollEvent last_roll;
|
||||
for (const auto& event : last_die_events) {
|
||||
if (event.timestamp > last_roll.timestamp) {
|
||||
last_roll = event;
|
||||
}
|
||||
}
|
||||
return last_roll;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the container has an item that matches the value.
|
||||
*/
|
||||
template <typename C, typename T>
|
||||
static bool Contains(const C& container, T value) {
|
||||
return std::find(container.begin(), container.end(), value) !=
|
||||
container.end();
|
||||
}
|
||||
|
||||
// These aren't known until runtime since they're being added dynamically.
|
||||
static uint8_t FX_MODE_SIMPLE_D20 = 0xFF;
|
||||
static uint8_t FX_MODE_PULSE_D20 = 0xFF;
|
||||
static uint8_t FX_MODE_CHECK_D20 = 0xFF;
|
||||
std::array<uint8_t, 3> DIE_LED_MODES = {0xFF, 0xFF, 0xFF};
|
||||