Compare commits
698 Commits
ld2410_arr
...
api_read_m
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bb8a92ed3a | ||
|
|
88302201eb | ||
|
|
8afb172e83 | ||
|
|
562d024623 | ||
|
|
50b094547c | ||
|
|
a6c1e50985 | ||
|
|
96772bdfc6 | ||
|
|
ed154d373c | ||
|
|
ae55964bd9 | ||
|
|
c162309f41 | ||
|
|
62c667f1a0 | ||
|
|
86c0fb48a3 | ||
|
|
3d08eae8e4 | ||
|
|
2af5a0a6dd | ||
|
|
6d24b04235 | ||
|
|
3ee8103353 | ||
|
|
1296165fce | ||
|
|
7100c22dc4 | ||
|
|
3f1f99cf37 | ||
|
|
13d4823db6 | ||
|
|
30f61b26ff | ||
|
|
5718c0f5b8 | ||
|
|
25ebddfa1c | ||
|
|
2c0558fe23 | ||
|
|
7192108fc1 | ||
|
|
847696c342 | ||
|
|
912ae1fc87 | ||
|
|
a86f75d31d | ||
|
|
fe1e25b5c7 | ||
|
|
9b241b596a | ||
|
|
53b9c8d5bb | ||
|
|
2946bc9d72 | ||
|
|
67a20e212d | ||
|
|
a9ace366eb | ||
|
|
df3469efba | ||
|
|
0a3bbb8554 | ||
|
|
a15b9f5d3b | ||
|
|
e6334b0716 | ||
|
|
7a835baa5a | ||
|
|
c9c21a5728 | ||
|
|
956959fc32 | ||
|
|
6f67f74638 | ||
|
|
58b7d0b412 | ||
|
|
d37f5b87bd | ||
|
|
3f65cee17c | ||
|
|
094bf19ec4 | ||
|
|
f8d59b5aeb | ||
|
|
e9870c2922 | ||
|
|
50b7349fe0 | ||
|
|
61b3379f48 | ||
|
|
5010a0f5e7 | ||
|
|
52ca8deb10 | ||
|
|
156a9160ba | ||
|
|
b3dd4543b7 | ||
|
|
4f17a28ac5 | ||
|
|
90736f367a | ||
|
|
9af88bd482 | ||
|
|
13b89f4934 | ||
|
|
d00a00d142 | ||
|
|
e662c39e16 | ||
|
|
95ef131285 | ||
|
|
7476f170f6 | ||
|
|
3b6bd55d1e | ||
|
|
10dbc9e884 | ||
|
|
860f619dfe | ||
|
|
17ddc9ee0c | ||
|
|
949689c318 | ||
|
|
86a2aac011 | ||
|
|
d0a402f201 | ||
|
|
68d66c873e | ||
|
|
05772d5365 | ||
|
|
c2a68f5147 | ||
|
|
697ca1c7be | ||
|
|
409346952f | ||
|
|
f4b3539d77 | ||
|
|
c12166c1a1 | ||
|
|
8d20f003cb | ||
|
|
88f857a2f0 | ||
|
|
fb7faadd99 | ||
|
|
5c8d6752fb | ||
|
|
c40dff5d63 | ||
|
|
6f07b54772 | ||
|
|
ce0f1dfcb6 | ||
|
|
948aa13fb9 | ||
|
|
9e993ac603 | ||
|
|
9f3f4ead4f | ||
|
|
068aa0ff1e | ||
|
|
e146c0796a | ||
|
|
cceab26bfb | ||
|
|
c0b1f32889 | ||
|
|
837dd46adf | ||
|
|
13512440ac | ||
|
|
7931423e8c | ||
|
|
62f28902c5 | ||
|
|
1f94e4cc14 | ||
|
|
61dfd5541f | ||
|
|
9a3a5d48eb | ||
|
|
4a759eda02 | ||
|
|
87321ce10b | ||
|
|
4f5aacdb3a | ||
|
|
26badf201d | ||
|
|
384f27cd6d | ||
|
|
ac1c5f9f58 | ||
|
|
8ad058fdf4 | ||
|
|
9024c3c67a | ||
|
|
fc81a47499 | ||
|
|
a331452076 | ||
|
|
b1c6e8168e | ||
|
|
b41cc0226e | ||
|
|
450429ddd5 | ||
|
|
f7b24f4b4b | ||
|
|
294c985380 | ||
|
|
720964b901 | ||
|
|
b182f2d544 | ||
|
|
4fac8e9cd5 | ||
|
|
d94896c0fb | ||
|
|
15c5dd222f | ||
|
|
8895c8a987 | ||
|
|
740dcd72a2 | ||
|
|
ffd442624f | ||
|
|
2930c8e9a8 | ||
|
|
b12b9b97f4 | ||
|
|
088fd85694 | ||
|
|
d5b68d69d3 | ||
|
|
bb0f7bb393 | ||
|
|
d86a108f18 | ||
|
|
7828ed2d9e | ||
|
|
ebf14f50fb | ||
|
|
1546ff615b | ||
|
|
46cf1fb597 | ||
|
|
8bf8655054 | ||
|
|
a6d84948e2 | ||
|
|
fac20a1f97 | ||
|
|
c65586b5e1 | ||
|
|
b27b018b06 | ||
|
|
403da1e632 | ||
|
|
2371ec1f9e | ||
|
|
5e3ec2d34b | ||
|
|
78d84644c9 | ||
|
|
0cd0f8015a | ||
|
|
4b5424f695 | ||
|
|
a1d59040f7 | ||
|
|
0306398072 | ||
|
|
a7e0bf9013 | ||
|
|
ddb988cd83 | ||
|
|
04b54353f1 | ||
|
|
f058107c05 | ||
|
|
6b5b0815d7 | ||
|
|
8388497038 | ||
|
|
825b1113b6 | ||
|
|
9074ef792f | ||
|
|
0946f28511 | ||
|
|
23765cd4f5 | ||
|
|
e20c6468d0 | ||
|
|
b90516de1d | ||
|
|
ec5cc0f00f | ||
|
|
5dda5a976e | ||
|
|
915da9ae13 | ||
|
|
8652464f4e | ||
|
|
ce6ce1c1f8 | ||
|
|
39efe67e55 | ||
|
|
748ffa00f3 | ||
|
|
e8d9df2b0e | ||
|
|
17396d67de | ||
|
|
edd6a86714 | ||
|
|
85b4012c56 | ||
|
|
7d98433502 | ||
|
|
23774ae03b | ||
|
|
0dedbcdd71 | ||
|
|
4bdd08887e | ||
|
|
1fd8ebf386 | ||
|
|
d2fc3e749c | ||
|
|
71fbcbceaf | ||
|
|
27347b2088 | ||
|
|
599993d1a5 | ||
|
|
bf359cb8e3 | ||
|
|
509a704410 | ||
|
|
1f48e2b01f | ||
|
|
8b25b1eee6 | ||
|
|
3bbf30ff5f | ||
|
|
83613726d1 | ||
|
|
254b6a17f3 | ||
|
|
796e12bd70 | ||
|
|
ddbe17d3f6 | ||
|
|
591ec36f4a | ||
|
|
41eceb72ef | ||
|
|
0a5f094025 | ||
|
|
ca0f3ba262 | ||
|
|
30f4e782db | ||
|
|
192158ef1a | ||
|
|
602456db40 | ||
|
|
536e45668f | ||
|
|
10bf05ab0d | ||
|
|
5ad1af69e4 | ||
|
|
48f2911434 | ||
|
|
dbb0d6349a | ||
|
|
ac3598f12a | ||
|
|
66201be5ca | ||
|
|
ac0b0b652e | ||
|
|
d89ee2df42 | ||
|
|
418e248e5e | ||
|
|
8c2b141049 | ||
|
|
2f8e07302b | ||
|
|
c3776240b6 | ||
|
|
e370872ec1 | ||
|
|
d4e978369a | ||
|
|
8d5d7f5237 | ||
|
|
5cd498fbe9 | ||
|
|
250f515f08 | ||
|
|
0ec0a9e313 | ||
|
|
184f42ef03 | ||
|
|
499517418d | ||
|
|
606b9c1a6d | ||
|
|
971e954a54 | ||
|
|
e3aaf3219d | ||
|
|
0eea1c0e40 | ||
|
|
0773819778 | ||
|
|
170869b7db | ||
|
|
5dc54782e5 | ||
|
|
97b26fbefe | ||
|
|
686cc58d6c | ||
|
|
76a59759b2 | ||
|
|
93245a24b5 | ||
|
|
6a22ea1c7d | ||
|
|
56a02409c8 | ||
|
|
edeafd5a53 | ||
|
|
f67490b69b | ||
|
|
b76e34fb7b | ||
|
|
ddbda5032b | ||
|
|
5898d34b0a | ||
|
|
b0c02341ff | ||
|
|
19cbc8c33b | ||
|
|
02e61ef5d3 | ||
|
|
8d5d18064d | ||
|
|
c5ef7ebd27 | ||
|
|
047a3e0e8c | ||
|
|
13b23f840b | ||
|
|
147f6012b2 | ||
|
|
2c315595f0 | ||
|
|
20405c84ac | ||
|
|
0bc59b97de | ||
|
|
a3a3bdc7eb | ||
|
|
e767f30886 | ||
|
|
e8c250a03c | ||
|
|
d6725fc1ca | ||
|
|
8ec998ff30 | ||
|
|
23cc0c7f39 | ||
|
|
19b8bd6aa8 | ||
|
|
ed57e7c6b0 | ||
|
|
9f489c9f27 | ||
|
|
f036989361 | ||
|
|
6afa8141c0 | ||
|
|
587964c6f1 | ||
|
|
7aea82a273 | ||
|
|
20f946ccaf | ||
|
|
e5e972231c | ||
|
|
bfa80157f2 | ||
|
|
99b1b079d0 | ||
|
|
5697d549a8 | ||
|
|
754d2874e7 | ||
|
|
06de58ff8b | ||
|
|
a0b3527710 | ||
|
|
df24f48fa1 | ||
|
|
13d53590b2 | ||
|
|
5857f7b9a7 | ||
|
|
a5ea0cd41f | ||
|
|
d677934417 | ||
|
|
ba87a0b63c | ||
|
|
b725bb3dd1 | ||
|
|
c34ba3deb5 | ||
|
|
68b13340fb | ||
|
|
8831999ea6 | ||
|
|
c1853f8b84 | ||
|
|
2b9b7e2853 | ||
|
|
d3b18debf9 | ||
|
|
b01eb28d42 | ||
|
|
02019dd16c | ||
|
|
7be12f5ff6 | ||
|
|
a90d59b6ba | ||
|
|
e7fa156254 | ||
|
|
a8ab6b1c43 | ||
|
|
25ed7c890b | ||
|
|
85e3b63f05 | ||
|
|
a37bac1956 | ||
|
|
818a978dfc | ||
|
|
180aeb7d8e | ||
|
|
0764fa7292 | ||
|
|
17bf533ed7 | ||
|
|
d7eae1c1a0 | ||
|
|
7f2d979255 | ||
|
|
46b419ea8b | ||
|
|
b30b527ff9 | ||
|
|
41b1bfc504 | ||
|
|
f4f14a7507 | ||
|
|
61c29213a7 | ||
|
|
e6d7639209 | ||
|
|
3c07a186b2 | ||
|
|
8a725250a9 | ||
|
|
502b8a6073 | ||
|
|
6212c6f80f | ||
|
|
b03e3b8d4a | ||
|
|
a98e34d190 | ||
|
|
bf8d8b6e63 | ||
|
|
57599f7a98 | ||
|
|
ffccce7ffc | ||
|
|
bbd5d050a9 | ||
|
|
71a96fdcbf | ||
|
|
221e3c6c9c | ||
|
|
fb1679d572 | ||
|
|
c19065f112 | ||
|
|
f2b04a077e | ||
|
|
8e7841c880 | ||
|
|
1873490b24 | ||
|
|
4d231953f4 | ||
|
|
aa4c399657 | ||
|
|
1f99d18982 | ||
|
|
be37178ef8 | ||
|
|
fad86c655e | ||
|
|
4a7958586e | ||
|
|
f44ecd0891 | ||
|
|
3d0392d668 | ||
|
|
d300d2605b | ||
|
|
66cce6a2f2 | ||
|
|
65e3c6bfbb | ||
|
|
2a39060912 | ||
|
|
8714e80978 | ||
|
|
98de53f60b | ||
|
|
41e11e9a0e | ||
|
|
e7a4eac8bd | ||
|
|
1589a131db | ||
|
|
7d84f0e650 | ||
|
|
86fb0e317f | ||
|
|
32088d5ef7 | ||
|
|
63de88dd57 | ||
|
|
153a6440dc | ||
|
|
8937ed2269 | ||
|
|
02e922b56f | ||
|
|
bf9e901ab9 | ||
|
|
1234ef8de2 | ||
|
|
41697a7b1b | ||
|
|
912e265bc0 | ||
|
|
96ee6fb064 | ||
|
|
788dba8ef3 | ||
|
|
fdde9c4681 | ||
|
|
f195e73d38 | ||
|
|
b0d9ffc6a1 | ||
|
|
e17619841d | ||
|
|
eb6a7cf3b9 | ||
|
|
9901e2d72e | ||
|
|
bcf961c0b0 | ||
|
|
f84a4c9753 | ||
|
|
df56ca0236 | ||
|
|
de0cd0ec67 | ||
|
|
67c30245c4 | ||
|
|
1f72757591 | ||
|
|
35c2fdf6af | ||
|
|
d1ecd841be | ||
|
|
828a49697c | ||
|
|
0551495501 | ||
|
|
2bbffe4a68 | ||
|
|
281ad90e39 | ||
|
|
ed50976a07 | ||
|
|
a3400037d9 | ||
|
|
f0d82f75bc | ||
|
|
349cb80e90 | ||
|
|
c263ee39af | ||
|
|
e99bc52756 | ||
|
|
7944b2b8e9 | ||
|
|
ca6ae746c1 | ||
|
|
deabac18b2 | ||
|
|
5cf8681c61 | ||
|
|
ca7ede8f96 | ||
|
|
4969682d52 | ||
|
|
8002fe0dd5 | ||
|
|
7dfdf965b7 | ||
|
|
b408795dd6 | ||
|
|
a5a099336b | ||
|
|
4ae56fc004 | ||
|
|
3f71c09b7b | ||
|
|
bd50a7f1ab | ||
|
|
51e4c45e5c | ||
|
|
e3fae49add | ||
|
|
610215ab60 | ||
|
|
74acbda435 | ||
|
|
25c4af777c | ||
|
|
ec186e6324 | ||
|
|
150b7a98f3 | ||
|
|
8ae7c1cff0 | ||
|
|
7f1d0eef98 | ||
|
|
1179ab33f2 | ||
|
|
a09faa1c10 | ||
|
|
c0319d9b2f | ||
|
|
4870cd2921 | ||
|
|
d4280ec68b | ||
|
|
52cdc11927 | ||
|
|
8345b8c9ce | ||
|
|
c56f0677c3 | ||
|
|
00e9e1421e | ||
|
|
93c72c6e6c | ||
|
|
9cea930dbd | ||
|
|
7b9bd70729 | ||
|
|
5115c7a100 | ||
|
|
5634494e64 | ||
|
|
aa8bd4abf1 | ||
|
|
17fd69dd7f | ||
|
|
1d9dae374b | ||
|
|
cb2241ad91 | ||
|
|
d8a7e9abc8 | ||
|
|
969abc3f29 | ||
|
|
766fdc8a1f | ||
|
|
4c37c20d76 | ||
|
|
7d314398e1 | ||
|
|
b69191e3a8 | ||
|
|
b27c6b3596 | ||
|
|
5453835963 | ||
|
|
4d55ba057c | ||
|
|
325c01242c | ||
|
|
45b32bca89 | ||
|
|
7620049214 | ||
|
|
3553495a60 | ||
|
|
3ce6db61d5 | ||
|
|
798ff32c40 | ||
|
|
430cee8bda | ||
|
|
1fe3fb25a6 | ||
|
|
685ed87581 | ||
|
|
ea3ea1eee7 | ||
|
|
c9edcb909b | ||
|
|
35bfc9f069 | ||
|
|
c4aec194b9 | ||
|
|
e8547b16f6 | ||
|
|
2bbe08cee0 | ||
|
|
0a0c369b88 | ||
|
|
5d2f454a94 | ||
|
|
04bcc5c879 | ||
|
|
d4db16665f | ||
|
|
20b7a494f6 | ||
|
|
fbdce3ad89 | ||
|
|
4fc8807f02 | ||
|
|
83075bfb5c | ||
|
|
4074ec0425 | ||
|
|
8e1694dd0f | ||
|
|
911df18855 | ||
|
|
6b049e93f8 | ||
|
|
a335dcc379 | ||
|
|
c6478c8a79 | ||
|
|
cc9d40cb60 | ||
|
|
0a6b7f9a1b | ||
|
|
daa1fb9a7a | ||
|
|
b7d543290b | ||
|
|
ea852b60ac | ||
|
|
ed341988ea | ||
|
|
057b6c8e30 | ||
|
|
44444fe071 | ||
|
|
797330d6ab | ||
|
|
a630d5b5f5 | ||
|
|
eb3dc82b5d | ||
|
|
34ed18d562 | ||
|
|
1ce02ee313 | ||
|
|
2a26a0188c | ||
|
|
50cb05d1b1 | ||
|
|
6e739ac453 | ||
|
|
7aa2fd9f0e | ||
|
|
8e254e1b03 | ||
|
|
1ad9d717ff | ||
|
|
104658e43a | ||
|
|
e7e4b995bf | ||
|
|
b35b54f2c2 | ||
|
|
f80aeb1d1d | ||
|
|
6a756ab3b6 | ||
|
|
58a697bed1 | ||
|
|
280960ac18 | ||
|
|
0640ff13aa | ||
|
|
545505691f | ||
|
|
11fcf81321 | ||
|
|
c565b37dc8 | ||
|
|
3d18495270 | ||
|
|
419e4e63e9 | ||
|
|
724aa2bf65 | ||
|
|
573fa8aeb3 | ||
|
|
8a672e34c5 | ||
|
|
bc49211dab | ||
|
|
4ef9c3667e | ||
|
|
6babe516ac | ||
|
|
e0b258ef7e | ||
|
|
ff0c3a89b1 | ||
|
|
2511b81048 | ||
|
|
6ffcd94edc | ||
|
|
2fcf73c812 | ||
|
|
dee0608af9 | ||
|
|
d11860a383 | ||
|
|
1c05115bf5 | ||
|
|
d7e7382d0b | ||
|
|
872388f6e3 | ||
|
|
1215ef920b | ||
|
|
d19d5a23ea | ||
|
|
f49a779f1d | ||
|
|
d8bf5b80e1 | ||
|
|
69483b9353 | ||
|
|
14e8548989 | ||
|
|
4abd93b661 | ||
|
|
5d925af76f | ||
|
|
b999c6064a | ||
|
|
94e3576978 | ||
|
|
7a22406a2d | ||
|
|
e60684494f | ||
|
|
9db28ed779 | ||
|
|
6fd8c5cee7 | ||
|
|
787ec43266 | ||
|
|
a4efc63bf2 | ||
|
|
80a8f1437e | ||
|
|
fcca94169d | ||
|
|
d1924088e3 | ||
|
|
fd31afe09c | ||
|
|
7a763712c5 | ||
|
|
7216be5da7 | ||
|
|
711b0a291b | ||
|
|
dfc96496c8 | ||
|
|
2a1c5ef333 | ||
|
|
9755209499 | ||
|
|
0b26e537d4 | ||
|
|
98c6233ec3 | ||
|
|
f711706b1a | ||
|
|
cee7789ab6 | ||
|
|
8a06c4380d | ||
|
|
72ecf7a288 | ||
|
|
ef98c7502d | ||
|
|
03d0e74b65 | ||
|
|
5b8fdc0364 | ||
|
|
593b4bd137 | ||
|
|
267e12d058 | ||
|
|
4a5e39b651 | ||
|
|
ea24fa5b78 | ||
|
|
bb2bb128f7 | ||
|
|
94e8a856d7 | ||
|
|
4c19fbf98e | ||
|
|
60f8938bfa | ||
|
|
55679662b5 | ||
|
|
53df959e49 | ||
|
|
8e6ef9966f | ||
|
|
1d52fceafa | ||
|
|
99186ed864 | ||
|
|
383931d484 | ||
|
|
0b49a54cb3 | ||
|
|
705c0f1891 | ||
|
|
544c3ffc95 | ||
|
|
33f252a45d | ||
|
|
f55d82a015 | ||
|
|
8cf33fdef0 | ||
|
|
f858d98811 | ||
|
|
2a6165d440 | ||
|
|
4586528c40 | ||
|
|
23a07baa19 | ||
|
|
f9040ca932 | ||
|
|
4cea7f0237 | ||
|
|
b1847d5e98 | ||
|
|
9ce4d2e952 | ||
|
|
247078e06d | ||
|
|
a0cd72de28 | ||
|
|
e467f569f0 | ||
|
|
e31c7b7dfc | ||
|
|
dc2e0c832b | ||
|
|
7ddf51bb51 | ||
|
|
8fb3856665 | ||
|
|
183dd74f3e | ||
|
|
4f29039b41 | ||
|
|
102fcbec20 | ||
|
|
d00e5212c7 | ||
|
|
0e6bfb62cd | ||
|
|
aa930fb6b6 | ||
|
|
f327ed87e9 | ||
|
|
2de9be0589 | ||
|
|
345cde8645 | ||
|
|
cf152af9ae | ||
|
|
d6333dcfd9 | ||
|
|
0121f799f0 | ||
|
|
82c39580df | ||
|
|
53a578a46f | ||
|
|
62612ef80b | ||
|
|
61ac874c4c | ||
|
|
976b200ff6 | ||
|
|
852343b6d8 | ||
|
|
c56af9d52b | ||
|
|
05f18e2828 | ||
|
|
72804caab2 | ||
|
|
80cbe5c7c9 | ||
|
|
21892d1236 | ||
|
|
13824624f8 | ||
|
|
0fd72ecbab | ||
|
|
f848cb1546 | ||
|
|
633854081a | ||
|
|
4fed9a581b | ||
|
|
e9c1202aaa | ||
|
|
0a7ae279d0 | ||
|
|
0de2696543 | ||
|
|
a7dc239b71 | ||
|
|
fe0e6990f5 | ||
|
|
5ba65e92d9 | ||
|
|
a1452b52c9 | ||
|
|
dd2aa23a5f | ||
|
|
0e0359ba7d | ||
|
|
93b1b7aded | ||
|
|
9472dc6a53 | ||
|
|
67b681854e | ||
|
|
7b5990833e | ||
|
|
b6d5d04589 | ||
|
|
fdfbb3e944 | ||
|
|
faa7a3e37f | ||
|
|
23748b82bb | ||
|
|
bccb6f578a | ||
|
|
de8a5d6e9e | ||
|
|
a8eb3f7961 | ||
|
|
0877b3e2af | ||
|
|
99a54369bf | ||
|
|
f7533dfc5c | ||
|
|
ee7d95272d | ||
|
|
2b9b1d12e6 | ||
|
|
2cbb5c7d8e | ||
|
|
9686c7babe | ||
|
|
66bd4c96c4 | ||
|
|
dc47faa4b6 | ||
|
|
55ee0b116d | ||
|
|
c6957c08bc | ||
|
|
8fe6a323d8 | ||
|
|
8e51590c32 | ||
|
|
ae066d5627 | ||
|
|
6760279916 | ||
|
|
3c208050b0 | ||
|
|
bbc7c9fb37 | ||
|
|
e1c3862586 | ||
|
|
c24b7cb7bd | ||
|
|
c91e16549d | ||
|
|
6e70aca458 | ||
|
|
d9ffd0ac8e | ||
|
|
4641f73d19 | ||
|
|
9f0051c21f | ||
|
|
0331cb09e8 | ||
|
|
2f8946f86c | ||
|
|
88a3df4008 | ||
|
|
0adf514bd6 | ||
|
|
a1b5a2abcb | ||
|
|
068c62c6fe | ||
|
|
0e9f14f969 | ||
|
|
78315fd388 | ||
|
|
0ab69002df | ||
|
|
1eec1239ec | ||
|
|
57f4067fbf | ||
|
|
f4a9221232 | ||
|
|
3d4a75148d | ||
|
|
c2c5bd844d | ||
|
|
98a2f23024 | ||
|
|
c955897d1b | ||
|
|
9624efa21e | ||
|
|
831638210d | ||
|
|
cfdb0925ce | ||
|
|
83db3eddd9 | ||
|
|
cc2c5a544e | ||
|
|
8fba8c2800 | ||
|
|
51d1da8460 | ||
|
|
2f1257056d | ||
|
|
2f8f6967bf | ||
|
|
246527e618 | ||
|
|
3857cc9c83 | ||
|
|
a59a8c563e | ||
|
|
856829bcbb | ||
|
|
dd2b931f61 | ||
|
|
39beccbbb0 | ||
|
|
ff626b428f | ||
|
|
3915e1f012 | ||
|
|
7b460b6224 | ||
|
|
8fb8e79730 | ||
|
|
79bbc475f4 | ||
|
|
cef023283b | ||
|
|
d4fda79ada | ||
|
|
ff0bdcf4cd | ||
|
|
bfbc313144 | ||
|
|
31f2376f15 | ||
|
|
f76ecb6604 | ||
|
|
298cc58433 | ||
|
|
825c0593e1 | ||
|
|
87ed1dc3e3 | ||
|
|
67e9db021c | ||
|
|
3922950951 | ||
|
|
9c4aa0ba53 | ||
|
|
f5f1651b31 | ||
|
|
32f4e4ca13 | ||
|
|
962e0c4c33 | ||
|
|
2c01bc5795 | ||
|
|
0651f7cb3c | ||
|
|
01ac59ce2a | ||
|
|
c1fd597757 | ||
|
|
e79e244eee | ||
|
|
68ecc08111 | ||
|
|
3b5fbc359f | ||
|
|
583e5ea47f | ||
|
|
7b647c3fae | ||
|
|
a8b76c617c | ||
|
|
1bd8985dff | ||
|
|
25b5a6c4ae |
@@ -4,7 +4,7 @@
|
||||
repos:
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
# Ruff version.
|
||||
rev: v0.12.0
|
||||
rev: v0.12.1
|
||||
hooks:
|
||||
# Run the linter.
|
||||
- id: ruff
|
||||
|
||||
@@ -146,6 +146,7 @@ esphome/components/esp32_ble_client/* @jesserockz
|
||||
esphome/components/esp32_ble_server/* @Rapsssito @clydebarrow @jesserockz
|
||||
esphome/components/esp32_camera_web_server/* @ayufan
|
||||
esphome/components/esp32_can/* @Sympatron
|
||||
esphome/components/esp32_hosted/* @swoboda1337
|
||||
esphome/components/esp32_improv/* @jesserockz
|
||||
esphome/components/esp32_rmt/* @jesserockz
|
||||
esphome/components/esp32_rmt_led_strip/* @jesserockz
|
||||
@@ -491,7 +492,7 @@ esphome/components/vbus/* @ssieb
|
||||
esphome/components/veml3235/* @kbx81
|
||||
esphome/components/veml7700/* @latonita
|
||||
esphome/components/version/* @esphome/core
|
||||
esphome/components/voice_assistant/* @jesserockz
|
||||
esphome/components/voice_assistant/* @jesserockz @kahrendt
|
||||
esphome/components/wake_on_lan/* @clydebarrow @willwill2will54
|
||||
esphome/components/watchdog/* @oarcher
|
||||
esphome/components/waveshare_epaper/* @clydebarrow
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include <cmath>
|
||||
#include <numbers>
|
||||
|
||||
#ifdef USE_ESP8266
|
||||
#include <core_esp8266_waveform.h>
|
||||
@@ -203,7 +204,7 @@ void AcDimmer::setup() {
|
||||
#endif
|
||||
}
|
||||
void AcDimmer::write_state(float state) {
|
||||
state = std::acos(1 - (2 * state)) / 3.14159; // RMS power compensation
|
||||
state = std::acos(1 - (2 * state)) / std::numbers::pi; // RMS power compensation
|
||||
auto new_value = static_cast<uint16_t>(roundf(state * 65535));
|
||||
if (new_value != 0 && this->store_.value == 0)
|
||||
this->store_.init_cycle = this->init_with_half_cycle_;
|
||||
|
||||
@@ -177,7 +177,11 @@ async def to_code(config):
|
||||
# and plaintext disabled. Only a factory reset can remove it.
|
||||
cg.add_define("USE_API_PLAINTEXT")
|
||||
cg.add_define("USE_API_NOISE")
|
||||
cg.add_library("esphome/noise-c", "0.1.6")
|
||||
cg.add_library(
|
||||
None,
|
||||
None,
|
||||
"https://github.com/esphome/noise-c.git#libsodium_update",
|
||||
)
|
||||
else:
|
||||
cg.add_define("USE_API_PLAINTEXT")
|
||||
|
||||
|
||||
@@ -65,10 +65,6 @@ uint32_t APIConnection::get_batch_delay_ms_() const { return this->parent_->get_
|
||||
void APIConnection::start() {
|
||||
this->last_traffic_ = App.get_loop_component_start_time();
|
||||
|
||||
// Set next_ping_retry_ to prevent immediate ping
|
||||
// This ensures the first ping happens after the keepalive period
|
||||
this->next_ping_retry_ = this->last_traffic_ + KEEPALIVE_TIMEOUT_MS;
|
||||
|
||||
APIError err = this->helper_->init();
|
||||
if (err != APIError::OK) {
|
||||
on_fatal_error();
|
||||
@@ -94,11 +90,24 @@ APIConnection::~APIConnection() {
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
void APIConnection::log_batch_item_(const DeferredBatch::BatchItem &item) {
|
||||
// Set log-only mode
|
||||
this->flags_.log_only_mode = true;
|
||||
|
||||
// Call the creator - it will create the message and log it via encode_message_to_buffer
|
||||
item.creator(item.entity, this, std::numeric_limits<uint16_t>::max(), true, item.message_type);
|
||||
|
||||
// Clear log-only mode
|
||||
this->flags_.log_only_mode = false;
|
||||
}
|
||||
#endif
|
||||
|
||||
void APIConnection::loop() {
|
||||
if (this->next_close_) {
|
||||
if (this->flags_.next_close) {
|
||||
// requested a disconnect
|
||||
this->helper_->close();
|
||||
this->remove_ = true;
|
||||
this->flags_.remove = true;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -139,15 +148,14 @@ void APIConnection::loop() {
|
||||
} else {
|
||||
this->read_message(0, buffer.type, nullptr);
|
||||
}
|
||||
if (this->remove_)
|
||||
if (this->flags_.remove)
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Process deferred batch if scheduled
|
||||
if (this->deferred_batch_.batch_scheduled &&
|
||||
now - this->deferred_batch_.batch_start_time >= this->get_batch_delay_ms_()) {
|
||||
if (this->flags_.batch_scheduled && now - this->deferred_batch_.batch_start_time >= this->get_batch_delay_ms_()) {
|
||||
this->process_batch_();
|
||||
}
|
||||
|
||||
@@ -157,26 +165,21 @@ void APIConnection::loop() {
|
||||
this->initial_state_iterator_.advance();
|
||||
}
|
||||
|
||||
if (this->sent_ping_) {
|
||||
if (this->flags_.sent_ping) {
|
||||
// Disconnect if not responded within 2.5*keepalive
|
||||
if (now - this->last_traffic_ > KEEPALIVE_DISCONNECT_TIMEOUT) {
|
||||
on_fatal_error();
|
||||
ESP_LOGW(TAG, "%s is unresponsive; disconnecting", this->get_client_combined_info().c_str());
|
||||
}
|
||||
} else if (now - this->last_traffic_ > KEEPALIVE_TIMEOUT_MS && now > this->next_ping_retry_) {
|
||||
} else if (now - this->last_traffic_ > KEEPALIVE_TIMEOUT_MS) {
|
||||
ESP_LOGVV(TAG, "Sending keepalive PING");
|
||||
this->sent_ping_ = this->send_message(PingRequest());
|
||||
if (!this->sent_ping_) {
|
||||
this->next_ping_retry_ = now + PING_RETRY_INTERVAL;
|
||||
this->ping_retries_++;
|
||||
if (this->ping_retries_ >= MAX_PING_RETRIES) {
|
||||
on_fatal_error();
|
||||
ESP_LOGE(TAG, "%s: Ping failed %u times", this->get_client_combined_info().c_str(), this->ping_retries_);
|
||||
} else if (this->ping_retries_ >= 10) {
|
||||
ESP_LOGW(TAG, "%s: Ping retry %u", this->get_client_combined_info().c_str(), this->ping_retries_);
|
||||
} else {
|
||||
ESP_LOGD(TAG, "%s: Ping retry %u", this->get_client_combined_info().c_str(), this->ping_retries_);
|
||||
}
|
||||
this->flags_.sent_ping = this->send_message(PingRequest());
|
||||
if (!this->flags_.sent_ping) {
|
||||
// If we can't send the ping request directly (tx_buffer full),
|
||||
// schedule it at the front of the batch so it will be sent with priority
|
||||
ESP_LOGW(TAG, "Buffer full, ping queued");
|
||||
this->schedule_message_front_(nullptr, &APIConnection::try_send_ping_request, PingRequest::MESSAGE_TYPE);
|
||||
this->flags_.sent_ping = true; // Mark as sent to avoid scheduling multiple pings
|
||||
}
|
||||
}
|
||||
|
||||
@@ -236,19 +239,27 @@ DisconnectResponse APIConnection::disconnect(const DisconnectRequest &msg) {
|
||||
// don't close yet, we still need to send the disconnect response
|
||||
// close will happen on next loop
|
||||
ESP_LOGD(TAG, "%s disconnected", this->get_client_combined_info().c_str());
|
||||
this->next_close_ = true;
|
||||
this->flags_.next_close = true;
|
||||
DisconnectResponse resp;
|
||||
return resp;
|
||||
}
|
||||
void APIConnection::on_disconnect_response(const DisconnectResponse &value) {
|
||||
this->helper_->close();
|
||||
this->remove_ = true;
|
||||
this->flags_.remove = true;
|
||||
}
|
||||
|
||||
// Encodes a message to the buffer and returns the total number of bytes used,
|
||||
// including header and footer overhead. Returns 0 if the message doesn't fit.
|
||||
uint16_t APIConnection::encode_message_to_buffer(ProtoMessage &msg, uint16_t message_type, APIConnection *conn,
|
||||
uint32_t remaining_size, bool is_single) {
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
// If in log-only mode, just log and return
|
||||
if (conn->flags_.log_only_mode) {
|
||||
conn->log_send_message_(msg.message_name(), msg.dump());
|
||||
return 1; // Return non-zero to indicate "success" for logging
|
||||
}
|
||||
#endif
|
||||
|
||||
// Calculate size
|
||||
uint32_t calculated_size = 0;
|
||||
msg.calculate_size(calculated_size);
|
||||
@@ -276,11 +287,6 @@ uint16_t APIConnection::encode_message_to_buffer(ProtoMessage &msg, uint16_t mes
|
||||
// Encode directly into buffer
|
||||
msg.encode(buffer);
|
||||
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
// Log the message for VV debugging
|
||||
conn->log_send_message_(msg.message_name(), msg.dump());
|
||||
#endif
|
||||
|
||||
// Calculate actual encoded size (not including header that was already added)
|
||||
size_t actual_payload_size = shared_buf.size() - size_before_encode;
|
||||
|
||||
@@ -297,10 +303,6 @@ bool APIConnection::send_binary_sensor_state(binary_sensor::BinarySensor *binary
|
||||
return this->schedule_message_(binary_sensor, &APIConnection::try_send_binary_sensor_state,
|
||||
BinarySensorStateResponse::MESSAGE_TYPE);
|
||||
}
|
||||
void APIConnection::send_binary_sensor_info(binary_sensor::BinarySensor *binary_sensor) {
|
||||
this->schedule_message_(binary_sensor, &APIConnection::try_send_binary_sensor_info,
|
||||
ListEntitiesBinarySensorResponse::MESSAGE_TYPE);
|
||||
}
|
||||
|
||||
uint16_t APIConnection::try_send_binary_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
|
||||
bool is_single) {
|
||||
@@ -328,9 +330,6 @@ uint16_t APIConnection::try_send_binary_sensor_info(EntityBase *entity, APIConne
|
||||
bool APIConnection::send_cover_state(cover::Cover *cover) {
|
||||
return this->schedule_message_(cover, &APIConnection::try_send_cover_state, CoverStateResponse::MESSAGE_TYPE);
|
||||
}
|
||||
void APIConnection::send_cover_info(cover::Cover *cover) {
|
||||
this->schedule_message_(cover, &APIConnection::try_send_cover_info, ListEntitiesCoverResponse::MESSAGE_TYPE);
|
||||
}
|
||||
uint16_t APIConnection::try_send_cover_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
|
||||
bool is_single) {
|
||||
auto *cover = static_cast<cover::Cover *>(entity);
|
||||
@@ -392,9 +391,6 @@ void APIConnection::cover_command(const CoverCommandRequest &msg) {
|
||||
bool APIConnection::send_fan_state(fan::Fan *fan) {
|
||||
return this->schedule_message_(fan, &APIConnection::try_send_fan_state, FanStateResponse::MESSAGE_TYPE);
|
||||
}
|
||||
void APIConnection::send_fan_info(fan::Fan *fan) {
|
||||
this->schedule_message_(fan, &APIConnection::try_send_fan_info, ListEntitiesFanResponse::MESSAGE_TYPE);
|
||||
}
|
||||
uint16_t APIConnection::try_send_fan_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
|
||||
bool is_single) {
|
||||
auto *fan = static_cast<fan::Fan *>(entity);
|
||||
@@ -454,9 +450,6 @@ void APIConnection::fan_command(const FanCommandRequest &msg) {
|
||||
bool APIConnection::send_light_state(light::LightState *light) {
|
||||
return this->schedule_message_(light, &APIConnection::try_send_light_state, LightStateResponse::MESSAGE_TYPE);
|
||||
}
|
||||
void APIConnection::send_light_info(light::LightState *light) {
|
||||
this->schedule_message_(light, &APIConnection::try_send_light_info, ListEntitiesLightResponse::MESSAGE_TYPE);
|
||||
}
|
||||
uint16_t APIConnection::try_send_light_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
|
||||
bool is_single) {
|
||||
auto *light = static_cast<light::LightState *>(entity);
|
||||
@@ -549,9 +542,6 @@ void APIConnection::light_command(const LightCommandRequest &msg) {
|
||||
bool APIConnection::send_sensor_state(sensor::Sensor *sensor) {
|
||||
return this->schedule_message_(sensor, &APIConnection::try_send_sensor_state, SensorStateResponse::MESSAGE_TYPE);
|
||||
}
|
||||
void APIConnection::send_sensor_info(sensor::Sensor *sensor) {
|
||||
this->schedule_message_(sensor, &APIConnection::try_send_sensor_info, ListEntitiesSensorResponse::MESSAGE_TYPE);
|
||||
}
|
||||
|
||||
uint16_t APIConnection::try_send_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
|
||||
bool is_single) {
|
||||
@@ -584,9 +574,6 @@ uint16_t APIConnection::try_send_sensor_info(EntityBase *entity, APIConnection *
|
||||
bool APIConnection::send_switch_state(switch_::Switch *a_switch) {
|
||||
return this->schedule_message_(a_switch, &APIConnection::try_send_switch_state, SwitchStateResponse::MESSAGE_TYPE);
|
||||
}
|
||||
void APIConnection::send_switch_info(switch_::Switch *a_switch) {
|
||||
this->schedule_message_(a_switch, &APIConnection::try_send_switch_info, ListEntitiesSwitchResponse::MESSAGE_TYPE);
|
||||
}
|
||||
|
||||
uint16_t APIConnection::try_send_switch_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
|
||||
bool is_single) {
|
||||
@@ -625,10 +612,6 @@ bool APIConnection::send_text_sensor_state(text_sensor::TextSensor *text_sensor)
|
||||
return this->schedule_message_(text_sensor, &APIConnection::try_send_text_sensor_state,
|
||||
TextSensorStateResponse::MESSAGE_TYPE);
|
||||
}
|
||||
void APIConnection::send_text_sensor_info(text_sensor::TextSensor *text_sensor) {
|
||||
this->schedule_message_(text_sensor, &APIConnection::try_send_text_sensor_info,
|
||||
ListEntitiesTextSensorResponse::MESSAGE_TYPE);
|
||||
}
|
||||
|
||||
uint16_t APIConnection::try_send_text_sensor_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
|
||||
bool is_single) {
|
||||
@@ -689,9 +672,6 @@ uint16_t APIConnection::try_send_climate_state(EntityBase *entity, APIConnection
|
||||
resp.target_humidity = climate->target_humidity;
|
||||
return encode_message_to_buffer(resp, ClimateStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
|
||||
}
|
||||
void APIConnection::send_climate_info(climate::Climate *climate) {
|
||||
this->schedule_message_(climate, &APIConnection::try_send_climate_info, ListEntitiesClimateResponse::MESSAGE_TYPE);
|
||||
}
|
||||
uint16_t APIConnection::try_send_climate_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
|
||||
bool is_single) {
|
||||
auto *climate = static_cast<climate::Climate *>(entity);
|
||||
@@ -759,9 +739,6 @@ void APIConnection::climate_command(const ClimateCommandRequest &msg) {
|
||||
bool APIConnection::send_number_state(number::Number *number) {
|
||||
return this->schedule_message_(number, &APIConnection::try_send_number_state, NumberStateResponse::MESSAGE_TYPE);
|
||||
}
|
||||
void APIConnection::send_number_info(number::Number *number) {
|
||||
this->schedule_message_(number, &APIConnection::try_send_number_info, ListEntitiesNumberResponse::MESSAGE_TYPE);
|
||||
}
|
||||
|
||||
uint16_t APIConnection::try_send_number_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
|
||||
bool is_single) {
|
||||
@@ -813,9 +790,6 @@ uint16_t APIConnection::try_send_date_state(EntityBase *entity, APIConnection *c
|
||||
fill_entity_state_base(date, resp);
|
||||
return encode_message_to_buffer(resp, DateStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
|
||||
}
|
||||
void APIConnection::send_date_info(datetime::DateEntity *date) {
|
||||
this->schedule_message_(date, &APIConnection::try_send_date_info, ListEntitiesDateResponse::MESSAGE_TYPE);
|
||||
}
|
||||
uint16_t APIConnection::try_send_date_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
|
||||
bool is_single) {
|
||||
auto *date = static_cast<datetime::DateEntity *>(entity);
|
||||
@@ -850,9 +824,6 @@ uint16_t APIConnection::try_send_time_state(EntityBase *entity, APIConnection *c
|
||||
fill_entity_state_base(time, resp);
|
||||
return encode_message_to_buffer(resp, TimeStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
|
||||
}
|
||||
void APIConnection::send_time_info(datetime::TimeEntity *time) {
|
||||
this->schedule_message_(time, &APIConnection::try_send_time_info, ListEntitiesTimeResponse::MESSAGE_TYPE);
|
||||
}
|
||||
uint16_t APIConnection::try_send_time_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
|
||||
bool is_single) {
|
||||
auto *time = static_cast<datetime::TimeEntity *>(entity);
|
||||
@@ -889,9 +860,6 @@ uint16_t APIConnection::try_send_datetime_state(EntityBase *entity, APIConnectio
|
||||
fill_entity_state_base(datetime, resp);
|
||||
return encode_message_to_buffer(resp, DateTimeStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
|
||||
}
|
||||
void APIConnection::send_datetime_info(datetime::DateTimeEntity *datetime) {
|
||||
this->schedule_message_(datetime, &APIConnection::try_send_datetime_info, ListEntitiesDateTimeResponse::MESSAGE_TYPE);
|
||||
}
|
||||
uint16_t APIConnection::try_send_datetime_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
|
||||
bool is_single) {
|
||||
auto *datetime = static_cast<datetime::DateTimeEntity *>(entity);
|
||||
@@ -915,9 +883,6 @@ void APIConnection::datetime_command(const DateTimeCommandRequest &msg) {
|
||||
bool APIConnection::send_text_state(text::Text *text) {
|
||||
return this->schedule_message_(text, &APIConnection::try_send_text_state, TextStateResponse::MESSAGE_TYPE);
|
||||
}
|
||||
void APIConnection::send_text_info(text::Text *text) {
|
||||
this->schedule_message_(text, &APIConnection::try_send_text_info, ListEntitiesTextResponse::MESSAGE_TYPE);
|
||||
}
|
||||
|
||||
uint16_t APIConnection::try_send_text_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
|
||||
bool is_single) {
|
||||
@@ -956,9 +921,6 @@ void APIConnection::text_command(const TextCommandRequest &msg) {
|
||||
bool APIConnection::send_select_state(select::Select *select) {
|
||||
return this->schedule_message_(select, &APIConnection::try_send_select_state, SelectStateResponse::MESSAGE_TYPE);
|
||||
}
|
||||
void APIConnection::send_select_info(select::Select *select) {
|
||||
this->schedule_message_(select, &APIConnection::try_send_select_info, ListEntitiesSelectResponse::MESSAGE_TYPE);
|
||||
}
|
||||
|
||||
uint16_t APIConnection::try_send_select_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
|
||||
bool is_single) {
|
||||
@@ -992,9 +954,6 @@ void APIConnection::select_command(const SelectCommandRequest &msg) {
|
||||
#endif
|
||||
|
||||
#ifdef USE_BUTTON
|
||||
void esphome::api::APIConnection::send_button_info(button::Button *button) {
|
||||
this->schedule_message_(button, &APIConnection::try_send_button_info, ListEntitiesButtonResponse::MESSAGE_TYPE);
|
||||
}
|
||||
uint16_t APIConnection::try_send_button_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
|
||||
bool is_single) {
|
||||
auto *button = static_cast<button::Button *>(entity);
|
||||
@@ -1017,9 +976,6 @@ void esphome::api::APIConnection::button_command(const ButtonCommandRequest &msg
|
||||
bool APIConnection::send_lock_state(lock::Lock *a_lock) {
|
||||
return this->schedule_message_(a_lock, &APIConnection::try_send_lock_state, LockStateResponse::MESSAGE_TYPE);
|
||||
}
|
||||
void APIConnection::send_lock_info(lock::Lock *a_lock) {
|
||||
this->schedule_message_(a_lock, &APIConnection::try_send_lock_info, ListEntitiesLockResponse::MESSAGE_TYPE);
|
||||
}
|
||||
|
||||
uint16_t APIConnection::try_send_lock_state(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
|
||||
bool is_single) {
|
||||
@@ -1073,9 +1029,6 @@ uint16_t APIConnection::try_send_valve_state(EntityBase *entity, APIConnection *
|
||||
fill_entity_state_base(valve, resp);
|
||||
return encode_message_to_buffer(resp, ValveStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
|
||||
}
|
||||
void APIConnection::send_valve_info(valve::Valve *valve) {
|
||||
this->schedule_message_(valve, &APIConnection::try_send_valve_info, ListEntitiesValveResponse::MESSAGE_TYPE);
|
||||
}
|
||||
uint16_t APIConnection::try_send_valve_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
|
||||
bool is_single) {
|
||||
auto *valve = static_cast<valve::Valve *>(entity);
|
||||
@@ -1121,10 +1074,6 @@ uint16_t APIConnection::try_send_media_player_state(EntityBase *entity, APIConne
|
||||
fill_entity_state_base(media_player, resp);
|
||||
return encode_message_to_buffer(resp, MediaPlayerStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
|
||||
}
|
||||
void APIConnection::send_media_player_info(media_player::MediaPlayer *media_player) {
|
||||
this->schedule_message_(media_player, &APIConnection::try_send_media_player_info,
|
||||
ListEntitiesMediaPlayerResponse::MESSAGE_TYPE);
|
||||
}
|
||||
uint16_t APIConnection::try_send_media_player_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
|
||||
bool is_single) {
|
||||
auto *media_player = static_cast<media_player::MediaPlayer *>(entity);
|
||||
@@ -1168,7 +1117,7 @@ void APIConnection::media_player_command(const MediaPlayerCommandRequest &msg) {
|
||||
|
||||
#ifdef USE_ESP32_CAMERA
|
||||
void APIConnection::set_camera_state(std::shared_ptr<esp32_camera::CameraImage> image) {
|
||||
if (!this->state_subscription_)
|
||||
if (!this->flags_.state_subscription)
|
||||
return;
|
||||
if (this->image_reader_.available())
|
||||
return;
|
||||
@@ -1176,9 +1125,6 @@ void APIConnection::set_camera_state(std::shared_ptr<esp32_camera::CameraImage>
|
||||
image->was_requested_by(esphome::esp32_camera::IDLE))
|
||||
this->image_reader_.set_image(std::move(image));
|
||||
}
|
||||
void APIConnection::send_camera_info(esp32_camera::ESP32Camera *camera) {
|
||||
this->schedule_message_(camera, &APIConnection::try_send_camera_info, ListEntitiesCameraResponse::MESSAGE_TYPE);
|
||||
}
|
||||
uint16_t APIConnection::try_send_camera_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
|
||||
bool is_single) {
|
||||
auto *camera = static_cast<esp32_camera::ESP32Camera *>(entity);
|
||||
@@ -1385,10 +1331,6 @@ uint16_t APIConnection::try_send_alarm_control_panel_state(EntityBase *entity, A
|
||||
fill_entity_state_base(a_alarm_control_panel, resp);
|
||||
return encode_message_to_buffer(resp, AlarmControlPanelStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
|
||||
}
|
||||
void APIConnection::send_alarm_control_panel_info(alarm_control_panel::AlarmControlPanel *a_alarm_control_panel) {
|
||||
this->schedule_message_(a_alarm_control_panel, &APIConnection::try_send_alarm_control_panel_info,
|
||||
ListEntitiesAlarmControlPanelResponse::MESSAGE_TYPE);
|
||||
}
|
||||
uint16_t APIConnection::try_send_alarm_control_panel_info(EntityBase *entity, APIConnection *conn,
|
||||
uint32_t remaining_size, bool is_single) {
|
||||
auto *a_alarm_control_panel = static_cast<alarm_control_panel::AlarmControlPanel *>(entity);
|
||||
@@ -1439,9 +1381,6 @@ void APIConnection::alarm_control_panel_command(const AlarmControlPanelCommandRe
|
||||
void APIConnection::send_event(event::Event *event, const std::string &event_type) {
|
||||
this->schedule_message_(event, MessageCreator(event_type), EventResponse::MESSAGE_TYPE);
|
||||
}
|
||||
void APIConnection::send_event_info(event::Event *event) {
|
||||
this->schedule_message_(event, &APIConnection::try_send_event_info, ListEntitiesEventResponse::MESSAGE_TYPE);
|
||||
}
|
||||
uint16_t APIConnection::try_send_event_response(event::Event *event, const std::string &event_type, APIConnection *conn,
|
||||
uint32_t remaining_size, bool is_single) {
|
||||
EventResponse resp;
|
||||
@@ -1487,9 +1426,6 @@ uint16_t APIConnection::try_send_update_state(EntityBase *entity, APIConnection
|
||||
fill_entity_state_base(update, resp);
|
||||
return encode_message_to_buffer(resp, UpdateStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
|
||||
}
|
||||
void APIConnection::send_update_info(update::UpdateEntity *update) {
|
||||
this->schedule_message_(update, &APIConnection::try_send_update_info, ListEntitiesUpdateResponse::MESSAGE_TYPE);
|
||||
}
|
||||
uint16_t APIConnection::try_send_update_info(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
|
||||
bool is_single) {
|
||||
auto *update = static_cast<update::UpdateEntity *>(entity);
|
||||
@@ -1522,7 +1458,7 @@ void APIConnection::update_command(const UpdateCommandRequest &msg) {
|
||||
#endif
|
||||
|
||||
bool APIConnection::try_send_log_message(int level, const char *tag, const char *line) {
|
||||
if (this->log_subscription_ < level)
|
||||
if (this->flags_.log_subscription < level)
|
||||
return false;
|
||||
|
||||
// Pre-calculate message size to avoid reallocations
|
||||
@@ -1563,7 +1499,7 @@ HelloResponse APIConnection::hello(const HelloRequest &msg) {
|
||||
resp.server_info = App.get_name() + " (esphome v" ESPHOME_VERSION ")";
|
||||
resp.name = App.get_name();
|
||||
|
||||
this->connection_state_ = ConnectionState::CONNECTED;
|
||||
this->flags_.connection_state = static_cast<uint8_t>(ConnectionState::CONNECTED);
|
||||
return resp;
|
||||
}
|
||||
ConnectResponse APIConnection::connect(const ConnectRequest &msg) {
|
||||
@@ -1574,7 +1510,7 @@ ConnectResponse APIConnection::connect(const ConnectRequest &msg) {
|
||||
resp.invalid_password = !correct;
|
||||
if (correct) {
|
||||
ESP_LOGD(TAG, "%s connected", this->get_client_combined_info().c_str());
|
||||
this->connection_state_ = ConnectionState::AUTHENTICATED;
|
||||
this->flags_.connection_state = static_cast<uint8_t>(ConnectionState::AUTHENTICATED);
|
||||
this->parent_->get_client_connected_trigger()->trigger(this->client_info_, this->client_peername_);
|
||||
#ifdef USE_HOMEASSISTANT_TIME
|
||||
if (homeassistant::global_homeassistant_time != nullptr) {
|
||||
@@ -1688,7 +1624,7 @@ void APIConnection::subscribe_home_assistant_states(const SubscribeHomeAssistant
|
||||
state_subs_at_ = 0;
|
||||
}
|
||||
bool APIConnection::try_to_clear_buffer(bool log_out_of_space) {
|
||||
if (this->remove_)
|
||||
if (this->flags_.remove)
|
||||
return false;
|
||||
if (this->helper_->can_write_without_blocking())
|
||||
return true;
|
||||
@@ -1738,7 +1674,7 @@ void APIConnection::on_no_setup_connection() {
|
||||
}
|
||||
void APIConnection::on_fatal_error() {
|
||||
this->helper_->close();
|
||||
this->remove_ = true;
|
||||
this->flags_.remove = true;
|
||||
}
|
||||
|
||||
void APIConnection::DeferredBatch::add_item(EntityBase *entity, MessageCreator creator, uint16_t message_type) {
|
||||
@@ -1757,9 +1693,14 @@ void APIConnection::DeferredBatch::add_item(EntityBase *entity, MessageCreator c
|
||||
items.emplace_back(entity, std::move(creator), message_type);
|
||||
}
|
||||
|
||||
void APIConnection::DeferredBatch::add_item_front(EntityBase *entity, MessageCreator creator, uint16_t message_type) {
|
||||
// Insert at front for high priority messages (no deduplication check)
|
||||
items.insert(items.begin(), BatchItem(entity, std::move(creator), message_type));
|
||||
}
|
||||
|
||||
bool APIConnection::schedule_batch_() {
|
||||
if (!this->deferred_batch_.batch_scheduled) {
|
||||
this->deferred_batch_.batch_scheduled = true;
|
||||
if (!this->flags_.batch_scheduled) {
|
||||
this->flags_.batch_scheduled = true;
|
||||
this->deferred_batch_.batch_start_time = App.get_loop_component_start_time();
|
||||
}
|
||||
return true;
|
||||
@@ -1768,14 +1709,14 @@ bool APIConnection::schedule_batch_() {
|
||||
ProtoWriteBuffer APIConnection::allocate_single_message_buffer(uint16_t size) { return this->create_buffer(size); }
|
||||
|
||||
ProtoWriteBuffer APIConnection::allocate_batch_message_buffer(uint16_t size) {
|
||||
ProtoWriteBuffer result = this->prepare_message_buffer(size, this->batch_first_message_);
|
||||
this->batch_first_message_ = false;
|
||||
ProtoWriteBuffer result = this->prepare_message_buffer(size, this->flags_.batch_first_message);
|
||||
this->flags_.batch_first_message = false;
|
||||
return result;
|
||||
}
|
||||
|
||||
void APIConnection::process_batch_() {
|
||||
if (this->deferred_batch_.empty()) {
|
||||
this->deferred_batch_.batch_scheduled = false;
|
||||
this->flags_.batch_scheduled = false;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1828,7 +1769,7 @@ void APIConnection::process_batch_() {
|
||||
|
||||
// Reserve based on estimated size (much more accurate than 24-byte worst-case)
|
||||
this->parent_->get_shared_buffer_ref().reserve(total_estimated_size + total_overhead);
|
||||
this->batch_first_message_ = true;
|
||||
this->flags_.batch_first_message = true;
|
||||
|
||||
size_t items_processed = 0;
|
||||
uint16_t remaining_size = std::numeric_limits<uint16_t>::max();
|
||||
@@ -1891,6 +1832,15 @@ void APIConnection::process_batch_() {
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
// Log messages after send attempt for VV debugging
|
||||
// It's safe to use the buffer for logging at this point regardless of send result
|
||||
for (size_t i = 0; i < items_processed; i++) {
|
||||
const auto &item = this->deferred_batch_.items[i];
|
||||
this->log_batch_item_(item);
|
||||
}
|
||||
#endif
|
||||
|
||||
// Handle remaining items more efficiently
|
||||
if (items_processed < this->deferred_batch_.items.size()) {
|
||||
// Remove processed items from the beginning
|
||||
@@ -1938,6 +1888,12 @@ uint16_t APIConnection::try_send_disconnect_request(EntityBase *entity, APIConne
|
||||
return encode_message_to_buffer(req, DisconnectRequest::MESSAGE_TYPE, conn, remaining_size, is_single);
|
||||
}
|
||||
|
||||
uint16_t APIConnection::try_send_ping_request(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
|
||||
bool is_single) {
|
||||
PingRequest req;
|
||||
return encode_message_to_buffer(req, PingRequest::MESSAGE_TYPE, conn, remaining_size, is_single);
|
||||
}
|
||||
|
||||
uint16_t APIConnection::get_estimated_message_size(uint16_t message_type) {
|
||||
// Use generated ESTIMATED_SIZE constants from each message type
|
||||
switch (message_type) {
|
||||
|
||||
@@ -22,6 +22,7 @@ static constexpr uint32_t KEEPALIVE_TIMEOUT_MS = 60000;
|
||||
class APIConnection : public APIServerConnection {
|
||||
public:
|
||||
friend class APIServer;
|
||||
friend class ListEntitiesIterator;
|
||||
APIConnection(std::unique_ptr<socket::Socket> socket, APIServer *parent);
|
||||
virtual ~APIConnection();
|
||||
|
||||
@@ -34,98 +35,79 @@ class APIConnection : public APIServerConnection {
|
||||
}
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
bool send_binary_sensor_state(binary_sensor::BinarySensor *binary_sensor);
|
||||
void send_binary_sensor_info(binary_sensor::BinarySensor *binary_sensor);
|
||||
#endif
|
||||
#ifdef USE_COVER
|
||||
bool send_cover_state(cover::Cover *cover);
|
||||
void send_cover_info(cover::Cover *cover);
|
||||
void cover_command(const CoverCommandRequest &msg) override;
|
||||
#endif
|
||||
#ifdef USE_FAN
|
||||
bool send_fan_state(fan::Fan *fan);
|
||||
void send_fan_info(fan::Fan *fan);
|
||||
void fan_command(const FanCommandRequest &msg) override;
|
||||
#endif
|
||||
#ifdef USE_LIGHT
|
||||
bool send_light_state(light::LightState *light);
|
||||
void send_light_info(light::LightState *light);
|
||||
void light_command(const LightCommandRequest &msg) override;
|
||||
#endif
|
||||
#ifdef USE_SENSOR
|
||||
bool send_sensor_state(sensor::Sensor *sensor);
|
||||
void send_sensor_info(sensor::Sensor *sensor);
|
||||
#endif
|
||||
#ifdef USE_SWITCH
|
||||
bool send_switch_state(switch_::Switch *a_switch);
|
||||
void send_switch_info(switch_::Switch *a_switch);
|
||||
void switch_command(const SwitchCommandRequest &msg) override;
|
||||
#endif
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
bool send_text_sensor_state(text_sensor::TextSensor *text_sensor);
|
||||
void send_text_sensor_info(text_sensor::TextSensor *text_sensor);
|
||||
#endif
|
||||
#ifdef USE_ESP32_CAMERA
|
||||
void set_camera_state(std::shared_ptr<esp32_camera::CameraImage> image);
|
||||
void send_camera_info(esp32_camera::ESP32Camera *camera);
|
||||
void camera_image(const CameraImageRequest &msg) override;
|
||||
#endif
|
||||
#ifdef USE_CLIMATE
|
||||
bool send_climate_state(climate::Climate *climate);
|
||||
void send_climate_info(climate::Climate *climate);
|
||||
void climate_command(const ClimateCommandRequest &msg) override;
|
||||
#endif
|
||||
#ifdef USE_NUMBER
|
||||
bool send_number_state(number::Number *number);
|
||||
void send_number_info(number::Number *number);
|
||||
void number_command(const NumberCommandRequest &msg) override;
|
||||
#endif
|
||||
#ifdef USE_DATETIME_DATE
|
||||
bool send_date_state(datetime::DateEntity *date);
|
||||
void send_date_info(datetime::DateEntity *date);
|
||||
void date_command(const DateCommandRequest &msg) override;
|
||||
#endif
|
||||
#ifdef USE_DATETIME_TIME
|
||||
bool send_time_state(datetime::TimeEntity *time);
|
||||
void send_time_info(datetime::TimeEntity *time);
|
||||
void time_command(const TimeCommandRequest &msg) override;
|
||||
#endif
|
||||
#ifdef USE_DATETIME_DATETIME
|
||||
bool send_datetime_state(datetime::DateTimeEntity *datetime);
|
||||
void send_datetime_info(datetime::DateTimeEntity *datetime);
|
||||
void datetime_command(const DateTimeCommandRequest &msg) override;
|
||||
#endif
|
||||
#ifdef USE_TEXT
|
||||
bool send_text_state(text::Text *text);
|
||||
void send_text_info(text::Text *text);
|
||||
void text_command(const TextCommandRequest &msg) override;
|
||||
#endif
|
||||
#ifdef USE_SELECT
|
||||
bool send_select_state(select::Select *select);
|
||||
void send_select_info(select::Select *select);
|
||||
void select_command(const SelectCommandRequest &msg) override;
|
||||
#endif
|
||||
#ifdef USE_BUTTON
|
||||
void send_button_info(button::Button *button);
|
||||
void button_command(const ButtonCommandRequest &msg) override;
|
||||
#endif
|
||||
#ifdef USE_LOCK
|
||||
bool send_lock_state(lock::Lock *a_lock);
|
||||
void send_lock_info(lock::Lock *a_lock);
|
||||
void lock_command(const LockCommandRequest &msg) override;
|
||||
#endif
|
||||
#ifdef USE_VALVE
|
||||
bool send_valve_state(valve::Valve *valve);
|
||||
void send_valve_info(valve::Valve *valve);
|
||||
void valve_command(const ValveCommandRequest &msg) override;
|
||||
#endif
|
||||
#ifdef USE_MEDIA_PLAYER
|
||||
bool send_media_player_state(media_player::MediaPlayer *media_player);
|
||||
void send_media_player_info(media_player::MediaPlayer *media_player);
|
||||
void media_player_command(const MediaPlayerCommandRequest &msg) override;
|
||||
#endif
|
||||
bool try_send_log_message(int level, const char *tag, const char *line);
|
||||
void send_homeassistant_service_call(const HomeassistantServiceResponse &call) {
|
||||
if (!this->service_call_subscription_)
|
||||
if (!this->flags_.service_call_subscription)
|
||||
return;
|
||||
this->send_message(call);
|
||||
}
|
||||
@@ -167,26 +149,22 @@ class APIConnection : public APIServerConnection {
|
||||
|
||||
#ifdef USE_ALARM_CONTROL_PANEL
|
||||
bool send_alarm_control_panel_state(alarm_control_panel::AlarmControlPanel *a_alarm_control_panel);
|
||||
void send_alarm_control_panel_info(alarm_control_panel::AlarmControlPanel *a_alarm_control_panel);
|
||||
void alarm_control_panel_command(const AlarmControlPanelCommandRequest &msg) override;
|
||||
#endif
|
||||
|
||||
#ifdef USE_EVENT
|
||||
void send_event(event::Event *event, const std::string &event_type);
|
||||
void send_event_info(event::Event *event);
|
||||
#endif
|
||||
|
||||
#ifdef USE_UPDATE
|
||||
bool send_update_state(update::UpdateEntity *update);
|
||||
void send_update_info(update::UpdateEntity *update);
|
||||
void update_command(const UpdateCommandRequest &msg) override;
|
||||
#endif
|
||||
|
||||
void on_disconnect_response(const DisconnectResponse &value) override;
|
||||
void on_ping_response(const PingResponse &value) override {
|
||||
// we initiated ping
|
||||
this->ping_retries_ = 0;
|
||||
this->sent_ping_ = false;
|
||||
this->flags_.sent_ping = false;
|
||||
}
|
||||
void on_home_assistant_state_response(const HomeAssistantStateResponse &msg) override;
|
||||
#ifdef USE_HOMEASSISTANT_TIME
|
||||
@@ -199,16 +177,16 @@ class APIConnection : public APIServerConnection {
|
||||
DeviceInfoResponse device_info(const DeviceInfoRequest &msg) override;
|
||||
void list_entities(const ListEntitiesRequest &msg) override { this->list_entities_iterator_.begin(); }
|
||||
void subscribe_states(const SubscribeStatesRequest &msg) override {
|
||||
this->state_subscription_ = true;
|
||||
this->flags_.state_subscription = true;
|
||||
this->initial_state_iterator_.begin();
|
||||
}
|
||||
void subscribe_logs(const SubscribeLogsRequest &msg) override {
|
||||
this->log_subscription_ = msg.level;
|
||||
this->flags_.log_subscription = msg.level;
|
||||
if (msg.dump_config)
|
||||
App.schedule_dump_config();
|
||||
}
|
||||
void subscribe_homeassistant_services(const SubscribeHomeassistantServicesRequest &msg) override {
|
||||
this->service_call_subscription_ = true;
|
||||
this->flags_.service_call_subscription = true;
|
||||
}
|
||||
void subscribe_home_assistant_states(const SubscribeHomeAssistantStatesRequest &msg) override;
|
||||
GetTimeResponse get_time(const GetTimeRequest &msg) override {
|
||||
@@ -220,9 +198,12 @@ class APIConnection : public APIServerConnection {
|
||||
NoiseEncryptionSetKeyResponse noise_encryption_set_key(const NoiseEncryptionSetKeyRequest &msg) override;
|
||||
#endif
|
||||
|
||||
bool is_authenticated() override { return this->connection_state_ == ConnectionState::AUTHENTICATED; }
|
||||
bool is_authenticated() override {
|
||||
return static_cast<ConnectionState>(this->flags_.connection_state) == ConnectionState::AUTHENTICATED;
|
||||
}
|
||||
bool is_connection_setup() override {
|
||||
return this->connection_state_ == ConnectionState ::CONNECTED || this->is_authenticated();
|
||||
return static_cast<ConnectionState>(this->flags_.connection_state) == ConnectionState::CONNECTED ||
|
||||
this->is_authenticated();
|
||||
}
|
||||
void on_fatal_error() override;
|
||||
void on_unauthenticated_access() override;
|
||||
@@ -441,45 +422,32 @@ class APIConnection : public APIServerConnection {
|
||||
// Helper function to get estimated message size for buffer pre-allocation
|
||||
static uint16_t get_estimated_message_size(uint16_t message_type);
|
||||
|
||||
// Pointers first (4 bytes each, naturally aligned)
|
||||
// Batch message method for ping requests
|
||||
static uint16_t try_send_ping_request(EntityBase *entity, APIConnection *conn, uint32_t remaining_size,
|
||||
bool is_single);
|
||||
|
||||
// === Optimal member ordering for 32-bit systems ===
|
||||
|
||||
// Group 1: Pointers (4 bytes each on 32-bit)
|
||||
std::unique_ptr<APIFrameHelper> helper_;
|
||||
APIServer *parent_;
|
||||
|
||||
// 4-byte aligned types
|
||||
uint32_t last_traffic_;
|
||||
uint32_t next_ping_retry_{0};
|
||||
int state_subs_at_ = -1;
|
||||
|
||||
// Strings (12 bytes each on 32-bit)
|
||||
std::string client_info_;
|
||||
std::string client_peername_;
|
||||
|
||||
// 2-byte aligned types
|
||||
uint16_t client_api_version_major_{0};
|
||||
uint16_t client_api_version_minor_{0};
|
||||
|
||||
// Group all 1-byte types together to minimize padding
|
||||
enum class ConnectionState : uint8_t {
|
||||
WAITING_FOR_HELLO,
|
||||
CONNECTED,
|
||||
AUTHENTICATED,
|
||||
} connection_state_{ConnectionState::WAITING_FOR_HELLO};
|
||||
uint8_t log_subscription_{ESPHOME_LOG_LEVEL_NONE};
|
||||
bool remove_{false};
|
||||
bool state_subscription_{false};
|
||||
bool sent_ping_{false};
|
||||
bool service_call_subscription_{false};
|
||||
bool next_close_ = false;
|
||||
uint8_t ping_retries_{0};
|
||||
// 8 bytes used, no padding needed
|
||||
|
||||
// Larger objects at the end
|
||||
// Group 2: Larger objects (must be 4-byte aligned)
|
||||
// These contain vectors/pointers internally, so putting them early ensures good alignment
|
||||
InitialStateIterator initial_state_iterator_;
|
||||
ListEntitiesIterator list_entities_iterator_;
|
||||
#ifdef USE_ESP32_CAMERA
|
||||
esp32_camera::CameraImageReader image_reader_;
|
||||
#endif
|
||||
|
||||
// Group 3: Strings (12 bytes each on 32-bit, 4-byte aligned)
|
||||
std::string client_info_;
|
||||
std::string client_peername_;
|
||||
|
||||
// Group 4: 4-byte types
|
||||
uint32_t last_traffic_;
|
||||
int state_subs_at_ = -1;
|
||||
|
||||
// Function pointer type for message encoding
|
||||
using MessageCreatorPtr = uint16_t (*)(EntityBase *, APIConnection *, uint32_t remaining_size, bool is_single);
|
||||
|
||||
@@ -589,7 +557,6 @@ class APIConnection : public APIServerConnection {
|
||||
|
||||
std::vector<BatchItem> items;
|
||||
uint32_t batch_start_time{0};
|
||||
bool batch_scheduled{false};
|
||||
|
||||
DeferredBatch() {
|
||||
// Pre-allocate capacity for typical batch sizes to avoid reallocation
|
||||
@@ -598,15 +565,51 @@ class APIConnection : public APIServerConnection {
|
||||
|
||||
// Add item to the batch
|
||||
void add_item(EntityBase *entity, MessageCreator creator, uint16_t message_type);
|
||||
// Add item to the front of the batch (for high priority messages like ping)
|
||||
void add_item_front(EntityBase *entity, MessageCreator creator, uint16_t message_type);
|
||||
void clear() {
|
||||
items.clear();
|
||||
batch_scheduled = false;
|
||||
batch_start_time = 0;
|
||||
}
|
||||
bool empty() const { return items.empty(); }
|
||||
};
|
||||
|
||||
// DeferredBatch here (16 bytes, 4-byte aligned)
|
||||
DeferredBatch deferred_batch_;
|
||||
|
||||
// ConnectionState enum for type safety
|
||||
enum class ConnectionState : uint8_t {
|
||||
WAITING_FOR_HELLO = 0,
|
||||
CONNECTED = 1,
|
||||
AUTHENTICATED = 2,
|
||||
};
|
||||
|
||||
// Group 5: Pack all small members together to minimize padding
|
||||
// This group starts at a 4-byte boundary after DeferredBatch
|
||||
struct APIFlags {
|
||||
// Connection state only needs 2 bits (3 states)
|
||||
uint8_t connection_state : 2;
|
||||
// Log subscription needs 3 bits (log levels 0-7)
|
||||
uint8_t log_subscription : 3;
|
||||
// Boolean flags (1 bit each)
|
||||
uint8_t remove : 1;
|
||||
uint8_t state_subscription : 1;
|
||||
uint8_t sent_ping : 1;
|
||||
|
||||
uint8_t service_call_subscription : 1;
|
||||
uint8_t next_close : 1;
|
||||
uint8_t batch_scheduled : 1;
|
||||
uint8_t batch_first_message : 1; // For batch buffer allocation
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
uint8_t log_only_mode : 1;
|
||||
#endif
|
||||
} flags_{}; // 2 bytes total
|
||||
|
||||
// 2-byte types immediately after flags_ (no padding between them)
|
||||
uint16_t client_api_version_major_{0};
|
||||
uint16_t client_api_version_minor_{0};
|
||||
// Total: 2 (flags) + 2 + 2 = 6 bytes, then 2 bytes padding to next 4-byte boundary
|
||||
|
||||
uint32_t get_batch_delay_ms_() const;
|
||||
// Message will use 8 more bytes than the minimum size, and typical
|
||||
// MTU is 1500. Sometimes users will see as low as 1460 MTU.
|
||||
@@ -624,8 +627,9 @@ class APIConnection : public APIServerConnection {
|
||||
bool schedule_batch_();
|
||||
void process_batch_();
|
||||
|
||||
// State for batch buffer allocation
|
||||
bool batch_first_message_{false};
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
void log_batch_item_(const DeferredBatch::BatchItem &item);
|
||||
#endif
|
||||
|
||||
// Helper function to schedule a deferred message with known message type
|
||||
bool schedule_message_(EntityBase *entity, MessageCreator creator, uint16_t message_type) {
|
||||
@@ -637,6 +641,12 @@ class APIConnection : public APIServerConnection {
|
||||
bool schedule_message_(EntityBase *entity, MessageCreatorPtr function_ptr, uint16_t message_type) {
|
||||
return schedule_message_(entity, MessageCreator(function_ptr), message_type);
|
||||
}
|
||||
|
||||
// Helper function to schedule a high priority message at the front of the batch
|
||||
bool schedule_message_front_(EntityBase *entity, MessageCreatorPtr function_ptr, uint16_t message_type) {
|
||||
this->deferred_batch_.add_item_front(entity, MessageCreator(function_ptr), message_type);
|
||||
return this->schedule_batch_();
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace api
|
||||
|
||||
@@ -14,7 +14,7 @@ void APIServerConnectionBase::log_send_message_(const char *name, const std::str
|
||||
}
|
||||
#endif
|
||||
|
||||
bool APIServerConnectionBase::read_message(uint32_t msg_size, uint32_t msg_type, uint8_t *msg_data) {
|
||||
void APIServerConnectionBase::read_message(uint32_t msg_size, uint32_t msg_type, uint8_t *msg_data) {
|
||||
switch (msg_type) {
|
||||
case 1: {
|
||||
HelloRequest msg;
|
||||
@@ -106,50 +106,50 @@ bool APIServerConnectionBase::read_message(uint32_t msg_size, uint32_t msg_type,
|
||||
this->on_subscribe_logs_request(msg);
|
||||
break;
|
||||
}
|
||||
case 30: {
|
||||
#ifdef USE_COVER
|
||||
case 30: {
|
||||
CoverCommandRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_cover_command_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_cover_command_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 31: {
|
||||
#endif
|
||||
#ifdef USE_FAN
|
||||
case 31: {
|
||||
FanCommandRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_fan_command_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_fan_command_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 32: {
|
||||
#endif
|
||||
#ifdef USE_LIGHT
|
||||
case 32: {
|
||||
LightCommandRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_light_command_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_light_command_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 33: {
|
||||
#endif
|
||||
#ifdef USE_SWITCH
|
||||
case 33: {
|
||||
SwitchCommandRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_switch_command_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_switch_command_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
#endif
|
||||
case 34: {
|
||||
SubscribeHomeassistantServicesRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
@@ -204,395 +204,394 @@ bool APIServerConnectionBase::read_message(uint32_t msg_size, uint32_t msg_type,
|
||||
this->on_execute_service_request(msg);
|
||||
break;
|
||||
}
|
||||
case 45: {
|
||||
#ifdef USE_ESP32_CAMERA
|
||||
case 45: {
|
||||
CameraImageRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_camera_image_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_camera_image_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 48: {
|
||||
#endif
|
||||
#ifdef USE_CLIMATE
|
||||
case 48: {
|
||||
ClimateCommandRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_climate_command_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_climate_command_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 51: {
|
||||
#endif
|
||||
#ifdef USE_NUMBER
|
||||
case 51: {
|
||||
NumberCommandRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_number_command_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_number_command_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 54: {
|
||||
#endif
|
||||
#ifdef USE_SELECT
|
||||
case 54: {
|
||||
SelectCommandRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_select_command_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_select_command_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 57: {
|
||||
#endif
|
||||
#ifdef USE_SIREN
|
||||
case 57: {
|
||||
SirenCommandRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_siren_command_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_siren_command_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 60: {
|
||||
#endif
|
||||
#ifdef USE_LOCK
|
||||
case 60: {
|
||||
LockCommandRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_lock_command_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_lock_command_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 62: {
|
||||
#endif
|
||||
#ifdef USE_BUTTON
|
||||
case 62: {
|
||||
ButtonCommandRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_button_command_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_button_command_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 65: {
|
||||
#endif
|
||||
#ifdef USE_MEDIA_PLAYER
|
||||
case 65: {
|
||||
MediaPlayerCommandRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_media_player_command_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_media_player_command_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 66: {
|
||||
#endif
|
||||
#ifdef USE_BLUETOOTH_PROXY
|
||||
case 66: {
|
||||
SubscribeBluetoothLEAdvertisementsRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_subscribe_bluetooth_le_advertisements_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_subscribe_bluetooth_le_advertisements_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 68: {
|
||||
#endif
|
||||
#ifdef USE_BLUETOOTH_PROXY
|
||||
case 68: {
|
||||
BluetoothDeviceRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_bluetooth_device_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_bluetooth_device_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 70: {
|
||||
#endif
|
||||
#ifdef USE_BLUETOOTH_PROXY
|
||||
case 70: {
|
||||
BluetoothGATTGetServicesRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_bluetooth_gatt_get_services_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_bluetooth_gatt_get_services_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 73: {
|
||||
#endif
|
||||
#ifdef USE_BLUETOOTH_PROXY
|
||||
case 73: {
|
||||
BluetoothGATTReadRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_bluetooth_gatt_read_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_bluetooth_gatt_read_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 75: {
|
||||
#endif
|
||||
#ifdef USE_BLUETOOTH_PROXY
|
||||
case 75: {
|
||||
BluetoothGATTWriteRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_bluetooth_gatt_write_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_bluetooth_gatt_write_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 76: {
|
||||
#endif
|
||||
#ifdef USE_BLUETOOTH_PROXY
|
||||
case 76: {
|
||||
BluetoothGATTReadDescriptorRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_bluetooth_gatt_read_descriptor_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_bluetooth_gatt_read_descriptor_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 77: {
|
||||
#endif
|
||||
#ifdef USE_BLUETOOTH_PROXY
|
||||
case 77: {
|
||||
BluetoothGATTWriteDescriptorRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_bluetooth_gatt_write_descriptor_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_bluetooth_gatt_write_descriptor_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 78: {
|
||||
#endif
|
||||
#ifdef USE_BLUETOOTH_PROXY
|
||||
case 78: {
|
||||
BluetoothGATTNotifyRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_bluetooth_gatt_notify_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_bluetooth_gatt_notify_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 80: {
|
||||
#endif
|
||||
#ifdef USE_BLUETOOTH_PROXY
|
||||
case 80: {
|
||||
SubscribeBluetoothConnectionsFreeRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_subscribe_bluetooth_connections_free_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_subscribe_bluetooth_connections_free_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 87: {
|
||||
#endif
|
||||
#ifdef USE_BLUETOOTH_PROXY
|
||||
case 87: {
|
||||
UnsubscribeBluetoothLEAdvertisementsRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_unsubscribe_bluetooth_le_advertisements_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_unsubscribe_bluetooth_le_advertisements_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 89: {
|
||||
#endif
|
||||
#ifdef USE_VOICE_ASSISTANT
|
||||
case 89: {
|
||||
SubscribeVoiceAssistantRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_subscribe_voice_assistant_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_subscribe_voice_assistant_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 91: {
|
||||
#endif
|
||||
#ifdef USE_VOICE_ASSISTANT
|
||||
case 91: {
|
||||
VoiceAssistantResponse msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_voice_assistant_response: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_voice_assistant_response(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 92: {
|
||||
#endif
|
||||
#ifdef USE_VOICE_ASSISTANT
|
||||
case 92: {
|
||||
VoiceAssistantEventResponse msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_voice_assistant_event_response: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_voice_assistant_event_response(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 96: {
|
||||
#endif
|
||||
#ifdef USE_ALARM_CONTROL_PANEL
|
||||
case 96: {
|
||||
AlarmControlPanelCommandRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_alarm_control_panel_command_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_alarm_control_panel_command_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 99: {
|
||||
#endif
|
||||
#ifdef USE_TEXT
|
||||
case 99: {
|
||||
TextCommandRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_text_command_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_text_command_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 102: {
|
||||
#endif
|
||||
#ifdef USE_DATETIME_DATE
|
||||
case 102: {
|
||||
DateCommandRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_date_command_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_date_command_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 105: {
|
||||
#endif
|
||||
#ifdef USE_DATETIME_TIME
|
||||
case 105: {
|
||||
TimeCommandRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_time_command_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_time_command_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 106: {
|
||||
#endif
|
||||
#ifdef USE_VOICE_ASSISTANT
|
||||
case 106: {
|
||||
VoiceAssistantAudio msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_voice_assistant_audio: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_voice_assistant_audio(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 111: {
|
||||
#endif
|
||||
#ifdef USE_VALVE
|
||||
case 111: {
|
||||
ValveCommandRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_valve_command_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_valve_command_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 114: {
|
||||
#endif
|
||||
#ifdef USE_DATETIME_DATETIME
|
||||
case 114: {
|
||||
DateTimeCommandRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_date_time_command_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_date_time_command_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 115: {
|
||||
#endif
|
||||
#ifdef USE_VOICE_ASSISTANT
|
||||
case 115: {
|
||||
VoiceAssistantTimerEventResponse msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_voice_assistant_timer_event_response: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_voice_assistant_timer_event_response(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 118: {
|
||||
#endif
|
||||
#ifdef USE_UPDATE
|
||||
case 118: {
|
||||
UpdateCommandRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_update_command_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_update_command_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 119: {
|
||||
#endif
|
||||
#ifdef USE_VOICE_ASSISTANT
|
||||
case 119: {
|
||||
VoiceAssistantAnnounceRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_voice_assistant_announce_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_voice_assistant_announce_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 121: {
|
||||
#endif
|
||||
#ifdef USE_VOICE_ASSISTANT
|
||||
case 121: {
|
||||
VoiceAssistantConfigurationRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_voice_assistant_configuration_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_voice_assistant_configuration_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 123: {
|
||||
#endif
|
||||
#ifdef USE_VOICE_ASSISTANT
|
||||
case 123: {
|
||||
VoiceAssistantSetConfiguration msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_voice_assistant_set_configuration: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_voice_assistant_set_configuration(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 124: {
|
||||
#endif
|
||||
#ifdef USE_API_NOISE
|
||||
case 124: {
|
||||
NoiseEncryptionSetKeyRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_noise_encryption_set_key_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_noise_encryption_set_key_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
case 127: {
|
||||
#endif
|
||||
#ifdef USE_BLUETOOTH_PROXY
|
||||
case 127: {
|
||||
BluetoothScannerSetModeRequest msg;
|
||||
msg.decode(msg_data, msg_size);
|
||||
#ifdef HAS_PROTO_MESSAGE_DUMP
|
||||
ESP_LOGVV(TAG, "on_bluetooth_scanner_set_mode_request: %s", msg.dump().c_str());
|
||||
#endif
|
||||
this->on_bluetooth_scanner_set_mode_request(msg);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
#endif
|
||||
default:
|
||||
return false;
|
||||
break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void APIServerConnection::on_hello_request(const HelloRequest &msg) {
|
||||
|
||||
@@ -199,7 +199,7 @@ class APIServerConnectionBase : public ProtoService {
|
||||
virtual void on_update_command_request(const UpdateCommandRequest &value){};
|
||||
#endif
|
||||
protected:
|
||||
bool read_message(uint32_t msg_size, uint32_t msg_type, uint8_t *msg_data) override;
|
||||
void read_message(uint32_t msg_size, uint32_t msg_type, uint8_t *msg_data) override;
|
||||
};
|
||||
|
||||
class APIServerConnection : public APIServerConnectionBase {
|
||||
|
||||
@@ -104,7 +104,7 @@ void APIServer::setup() {
|
||||
return;
|
||||
}
|
||||
for (auto &c : this->clients_) {
|
||||
if (!c->remove_)
|
||||
if (!c->flags_.remove)
|
||||
c->try_send_log_message(level, tag, message);
|
||||
}
|
||||
});
|
||||
@@ -116,7 +116,7 @@ void APIServer::setup() {
|
||||
esp32_camera::global_esp32_camera->add_image_callback(
|
||||
[this](const std::shared_ptr<esp32_camera::CameraImage> &image) {
|
||||
for (auto &c : this->clients_) {
|
||||
if (!c->remove_)
|
||||
if (!c->flags_.remove)
|
||||
c->set_camera_state(image);
|
||||
}
|
||||
});
|
||||
@@ -176,7 +176,7 @@ void APIServer::loop() {
|
||||
while (client_index < this->clients_.size()) {
|
||||
auto &client = this->clients_[client_index];
|
||||
|
||||
if (!client->remove_) {
|
||||
if (!client->flags_.remove) {
|
||||
// Common case: process active client
|
||||
client->loop();
|
||||
client_index++;
|
||||
@@ -502,7 +502,7 @@ bool APIServer::save_noise_psk(psk_t psk, bool make_active) {
|
||||
#ifdef USE_HOMEASSISTANT_TIME
|
||||
void APIServer::request_time() {
|
||||
for (auto &client : this->clients_) {
|
||||
if (!client->remove_ && client->is_authenticated())
|
||||
if (!client->flags_.remove && client->is_authenticated())
|
||||
client->send_time_request();
|
||||
}
|
||||
}
|
||||
@@ -526,8 +526,8 @@ void APIServer::on_shutdown() {
|
||||
for (auto &c : this->clients_) {
|
||||
if (!c->send_message(DisconnectRequest())) {
|
||||
// If we can't send the disconnect request directly (tx_buffer full),
|
||||
// schedule it in the batch so it will be sent with the 5ms timer
|
||||
c->schedule_message_(nullptr, &APIConnection::try_send_disconnect_request, DisconnectRequest::MESSAGE_TYPE);
|
||||
// schedule it at the front of the batch so it will be sent with priority
|
||||
c->schedule_message_front_(nullptr, &APIConnection::try_send_disconnect_request, DisconnectRequest::MESSAGE_TYPE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,9 +4,15 @@ import asyncio
|
||||
from datetime import datetime
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Any
|
||||
import warnings
|
||||
|
||||
from aioesphomeapi import APIClient, parse_log_message
|
||||
from aioesphomeapi.log_runner import async_run
|
||||
# Suppress protobuf version warnings
|
||||
with warnings.catch_warnings():
|
||||
warnings.filterwarnings(
|
||||
"ignore", category=UserWarning, message=".*Protobuf gencode version.*"
|
||||
)
|
||||
from aioesphomeapi import APIClient, parse_log_message
|
||||
from aioesphomeapi.log_runner import async_run
|
||||
|
||||
from esphome.const import CONF_KEY, CONF_PASSWORD, CONF_PORT, __version__
|
||||
from esphome.core import CORE
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include "list_entities.h"
|
||||
#ifdef USE_API
|
||||
#include "api_connection.h"
|
||||
#include "api_pb2.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/util.h"
|
||||
@@ -10,62 +11,62 @@ namespace api {
|
||||
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
bool ListEntitiesIterator::on_binary_sensor(binary_sensor::BinarySensor *binary_sensor) {
|
||||
this->client_->send_binary_sensor_info(binary_sensor);
|
||||
return true;
|
||||
return this->client_->schedule_message_(binary_sensor, &APIConnection::try_send_binary_sensor_info,
|
||||
ListEntitiesBinarySensorResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_COVER
|
||||
bool ListEntitiesIterator::on_cover(cover::Cover *cover) {
|
||||
this->client_->send_cover_info(cover);
|
||||
return true;
|
||||
return this->client_->schedule_message_(cover, &APIConnection::try_send_cover_info,
|
||||
ListEntitiesCoverResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_FAN
|
||||
bool ListEntitiesIterator::on_fan(fan::Fan *fan) {
|
||||
this->client_->send_fan_info(fan);
|
||||
return true;
|
||||
return this->client_->schedule_message_(fan, &APIConnection::try_send_fan_info,
|
||||
ListEntitiesFanResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_LIGHT
|
||||
bool ListEntitiesIterator::on_light(light::LightState *light) {
|
||||
this->client_->send_light_info(light);
|
||||
return true;
|
||||
return this->client_->schedule_message_(light, &APIConnection::try_send_light_info,
|
||||
ListEntitiesLightResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_SENSOR
|
||||
bool ListEntitiesIterator::on_sensor(sensor::Sensor *sensor) {
|
||||
this->client_->send_sensor_info(sensor);
|
||||
return true;
|
||||
return this->client_->schedule_message_(sensor, &APIConnection::try_send_sensor_info,
|
||||
ListEntitiesSensorResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_SWITCH
|
||||
bool ListEntitiesIterator::on_switch(switch_::Switch *a_switch) {
|
||||
this->client_->send_switch_info(a_switch);
|
||||
return true;
|
||||
return this->client_->schedule_message_(a_switch, &APIConnection::try_send_switch_info,
|
||||
ListEntitiesSwitchResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_BUTTON
|
||||
bool ListEntitiesIterator::on_button(button::Button *button) {
|
||||
this->client_->send_button_info(button);
|
||||
return true;
|
||||
return this->client_->schedule_message_(button, &APIConnection::try_send_button_info,
|
||||
ListEntitiesButtonResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
bool ListEntitiesIterator::on_text_sensor(text_sensor::TextSensor *text_sensor) {
|
||||
this->client_->send_text_sensor_info(text_sensor);
|
||||
return true;
|
||||
return this->client_->schedule_message_(text_sensor, &APIConnection::try_send_text_sensor_info,
|
||||
ListEntitiesTextSensorResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_LOCK
|
||||
bool ListEntitiesIterator::on_lock(lock::Lock *a_lock) {
|
||||
this->client_->send_lock_info(a_lock);
|
||||
return true;
|
||||
return this->client_->schedule_message_(a_lock, &APIConnection::try_send_lock_info,
|
||||
ListEntitiesLockResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_VALVE
|
||||
bool ListEntitiesIterator::on_valve(valve::Valve *valve) {
|
||||
this->client_->send_valve_info(valve);
|
||||
return true;
|
||||
return this->client_->schedule_message_(valve, &APIConnection::try_send_valve_info,
|
||||
ListEntitiesValveResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -78,82 +79,82 @@ bool ListEntitiesIterator::on_service(UserServiceDescriptor *service) {
|
||||
|
||||
#ifdef USE_ESP32_CAMERA
|
||||
bool ListEntitiesIterator::on_camera(esp32_camera::ESP32Camera *camera) {
|
||||
this->client_->send_camera_info(camera);
|
||||
return true;
|
||||
return this->client_->schedule_message_(camera, &APIConnection::try_send_camera_info,
|
||||
ListEntitiesCameraResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_CLIMATE
|
||||
bool ListEntitiesIterator::on_climate(climate::Climate *climate) {
|
||||
this->client_->send_climate_info(climate);
|
||||
return true;
|
||||
return this->client_->schedule_message_(climate, &APIConnection::try_send_climate_info,
|
||||
ListEntitiesClimateResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_NUMBER
|
||||
bool ListEntitiesIterator::on_number(number::Number *number) {
|
||||
this->client_->send_number_info(number);
|
||||
return true;
|
||||
return this->client_->schedule_message_(number, &APIConnection::try_send_number_info,
|
||||
ListEntitiesNumberResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_DATETIME_DATE
|
||||
bool ListEntitiesIterator::on_date(datetime::DateEntity *date) {
|
||||
this->client_->send_date_info(date);
|
||||
return true;
|
||||
return this->client_->schedule_message_(date, &APIConnection::try_send_date_info,
|
||||
ListEntitiesDateResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_DATETIME_TIME
|
||||
bool ListEntitiesIterator::on_time(datetime::TimeEntity *time) {
|
||||
this->client_->send_time_info(time);
|
||||
return true;
|
||||
return this->client_->schedule_message_(time, &APIConnection::try_send_time_info,
|
||||
ListEntitiesTimeResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_DATETIME_DATETIME
|
||||
bool ListEntitiesIterator::on_datetime(datetime::DateTimeEntity *datetime) {
|
||||
this->client_->send_datetime_info(datetime);
|
||||
return true;
|
||||
return this->client_->schedule_message_(datetime, &APIConnection::try_send_datetime_info,
|
||||
ListEntitiesDateTimeResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_TEXT
|
||||
bool ListEntitiesIterator::on_text(text::Text *text) {
|
||||
this->client_->send_text_info(text);
|
||||
return true;
|
||||
return this->client_->schedule_message_(text, &APIConnection::try_send_text_info,
|
||||
ListEntitiesTextResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_SELECT
|
||||
bool ListEntitiesIterator::on_select(select::Select *select) {
|
||||
this->client_->send_select_info(select);
|
||||
return true;
|
||||
return this->client_->schedule_message_(select, &APIConnection::try_send_select_info,
|
||||
ListEntitiesSelectResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USE_MEDIA_PLAYER
|
||||
bool ListEntitiesIterator::on_media_player(media_player::MediaPlayer *media_player) {
|
||||
this->client_->send_media_player_info(media_player);
|
||||
return true;
|
||||
return this->client_->schedule_message_(media_player, &APIConnection::try_send_media_player_info,
|
||||
ListEntitiesMediaPlayerResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_ALARM_CONTROL_PANEL
|
||||
bool ListEntitiesIterator::on_alarm_control_panel(alarm_control_panel::AlarmControlPanel *a_alarm_control_panel) {
|
||||
this->client_->send_alarm_control_panel_info(a_alarm_control_panel);
|
||||
return true;
|
||||
return this->client_->schedule_message_(a_alarm_control_panel, &APIConnection::try_send_alarm_control_panel_info,
|
||||
ListEntitiesAlarmControlPanelResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_EVENT
|
||||
bool ListEntitiesIterator::on_event(event::Event *event) {
|
||||
this->client_->send_event_info(event);
|
||||
return true;
|
||||
return this->client_->schedule_message_(event, &APIConnection::try_send_event_info,
|
||||
ListEntitiesEventResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#endif
|
||||
#ifdef USE_UPDATE
|
||||
bool ListEntitiesIterator::on_update(update::UpdateEntity *update) {
|
||||
this->client_->send_update_info(update);
|
||||
return true;
|
||||
return this->client_->schedule_message_(update, &APIConnection::try_send_update_info,
|
||||
ListEntitiesUpdateResponse::MESSAGE_TYPE);
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include "atm90e32.h"
|
||||
#include <cinttypes>
|
||||
#include <cmath>
|
||||
#include <numbers>
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome {
|
||||
@@ -848,7 +849,7 @@ uint16_t ATM90E32Component::calculate_voltage_threshold(int line_freq, uint16_t
|
||||
float nominal_voltage = (line_freq == 60) ? 120.0f : 220.0f;
|
||||
float target_voltage = nominal_voltage * multiplier;
|
||||
|
||||
float peak_01v = target_voltage * 100.0f * std::sqrt(2.0f); // convert RMS → peak, scale to 0.01V
|
||||
float peak_01v = target_voltage * 100.0f * std::numbers::sqrt2_v<float>; // convert RMS → peak, scale to 0.01V
|
||||
float divider = (2.0f * ugain) / 32768.0f;
|
||||
|
||||
float threshold = peak_01v / divider;
|
||||
|
||||
@@ -312,7 +312,7 @@ FileDecoderState AudioDecoder::decode_mp3_() {
|
||||
if (err) {
|
||||
switch (err) {
|
||||
case esp_audio_libs::helix_decoder::ERR_MP3_OUT_OF_MEMORY:
|
||||
// Intentional fallthrough
|
||||
[[fallthrough]];
|
||||
case esp_audio_libs::helix_decoder::ERR_MP3_NULL_POINTER:
|
||||
return FileDecoderState::FAILED;
|
||||
break;
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
#if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
|
||||
#include "esp_crt_bundle.h"
|
||||
@@ -16,13 +17,13 @@ namespace audio {
|
||||
static const uint32_t READ_WRITE_TIMEOUT_MS = 20;
|
||||
|
||||
static const uint32_t CONNECTION_TIMEOUT_MS = 5000;
|
||||
|
||||
// The number of times the http read times out with no data before throwing an error
|
||||
static const uint32_t ERROR_COUNT_NO_DATA_READ_TIMEOUT = 100;
|
||||
static const uint8_t MAX_FETCHING_HEADER_ATTEMPTS = 6;
|
||||
|
||||
static const size_t HTTP_STREAM_BUFFER_SIZE = 2048;
|
||||
|
||||
static const uint8_t MAX_REDIRECTION = 5;
|
||||
static const uint8_t MAX_REDIRECTIONS = 5;
|
||||
|
||||
static const char *const TAG = "audio_reader";
|
||||
|
||||
// Some common HTTP status codes - borrowed from http_request component accessed 20241224
|
||||
enum HttpStatus {
|
||||
@@ -94,7 +95,7 @@ esp_err_t AudioReader::start(const std::string &uri, AudioFileType &file_type) {
|
||||
client_config.url = uri.c_str();
|
||||
client_config.cert_pem = nullptr;
|
||||
client_config.disable_auto_redirect = false;
|
||||
client_config.max_redirection_count = 10;
|
||||
client_config.max_redirection_count = MAX_REDIRECTIONS;
|
||||
client_config.event_handler = http_event_handler;
|
||||
client_config.user_data = this;
|
||||
client_config.buffer_size = HTTP_STREAM_BUFFER_SIZE;
|
||||
@@ -116,12 +117,29 @@ esp_err_t AudioReader::start(const std::string &uri, AudioFileType &file_type) {
|
||||
esp_err_t err = esp_http_client_open(this->client_, 0);
|
||||
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Failed to open URL");
|
||||
this->cleanup_connection_();
|
||||
return err;
|
||||
}
|
||||
|
||||
int64_t header_length = esp_http_client_fetch_headers(this->client_);
|
||||
uint8_t reattempt_count = 0;
|
||||
while ((header_length < 0) && (reattempt_count < MAX_FETCHING_HEADER_ATTEMPTS)) {
|
||||
this->cleanup_connection_();
|
||||
if (header_length != -ESP_ERR_HTTP_EAGAIN) {
|
||||
// Serious error, no recovery
|
||||
return ESP_FAIL;
|
||||
} else {
|
||||
// Reconnect from a fresh state to avoid a bug where it never reads the headers even if made available
|
||||
this->client_ = esp_http_client_init(&client_config);
|
||||
esp_http_client_open(this->client_, 0);
|
||||
header_length = esp_http_client_fetch_headers(this->client_);
|
||||
++reattempt_count;
|
||||
}
|
||||
}
|
||||
|
||||
if (header_length < 0) {
|
||||
ESP_LOGE(TAG, "Failed to fetch headers");
|
||||
this->cleanup_connection_();
|
||||
return ESP_FAIL;
|
||||
}
|
||||
@@ -135,7 +153,7 @@ esp_err_t AudioReader::start(const std::string &uri, AudioFileType &file_type) {
|
||||
|
||||
ssize_t redirect_count = 0;
|
||||
|
||||
while ((esp_http_client_set_redirection(this->client_) == ESP_OK) && (redirect_count < MAX_REDIRECTION)) {
|
||||
while ((esp_http_client_set_redirection(this->client_) == ESP_OK) && (redirect_count < MAX_REDIRECTIONS)) {
|
||||
err = esp_http_client_open(this->client_, 0);
|
||||
if (err != ESP_OK) {
|
||||
this->cleanup_connection_();
|
||||
@@ -267,27 +285,29 @@ AudioReaderState AudioReader::http_read_() {
|
||||
return AudioReaderState::FINISHED;
|
||||
}
|
||||
} else if (this->output_transfer_buffer_->free() > 0) {
|
||||
size_t bytes_to_read = this->output_transfer_buffer_->free();
|
||||
int received_len =
|
||||
esp_http_client_read(this->client_, (char *) this->output_transfer_buffer_->get_buffer_end(), bytes_to_read);
|
||||
int received_len = esp_http_client_read(this->client_, (char *) this->output_transfer_buffer_->get_buffer_end(),
|
||||
this->output_transfer_buffer_->free());
|
||||
|
||||
if (received_len > 0) {
|
||||
this->output_transfer_buffer_->increase_buffer_length(received_len);
|
||||
this->last_data_read_ms_ = millis();
|
||||
} else if (received_len < 0) {
|
||||
return AudioReaderState::READING;
|
||||
} else if (received_len <= 0) {
|
||||
// HTTP read error
|
||||
this->cleanup_connection_();
|
||||
return AudioReaderState::FAILED;
|
||||
} else {
|
||||
if (bytes_to_read > 0) {
|
||||
// Read timed out
|
||||
if ((millis() - this->last_data_read_ms_) > CONNECTION_TIMEOUT_MS) {
|
||||
this->cleanup_connection_();
|
||||
return AudioReaderState::FAILED;
|
||||
}
|
||||
|
||||
delay(READ_WRITE_TIMEOUT_MS);
|
||||
if (received_len == -1) {
|
||||
// A true connection error occured, no chance at recovery
|
||||
this->cleanup_connection_();
|
||||
return AudioReaderState::FAILED;
|
||||
}
|
||||
|
||||
// Read timed out, manually verify if it has been too long since the last successful read
|
||||
if ((millis() - this->last_data_read_ms_) > MAX_FETCHING_HEADER_ATTEMPTS * CONNECTION_TIMEOUT_MS) {
|
||||
ESP_LOGE(TAG, "Timed out");
|
||||
this->cleanup_connection_();
|
||||
return AudioReaderState::FAILED;
|
||||
}
|
||||
|
||||
delay(READ_WRITE_TIMEOUT_MS);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "display.h"
|
||||
#include <utility>
|
||||
#include <numbers>
|
||||
#include "display_color_utils.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/log.h"
|
||||
@@ -424,15 +425,15 @@ void HOT Display::get_regular_polygon_vertex(int vertex_id, int *vertex_x, int *
|
||||
// hence we rotate the shape by 270° to orient the polygon up.
|
||||
rotation_degrees += ROTATION_270_DEGREES;
|
||||
// Convert the rotation to radians, easier to use in trigonometrical calculations
|
||||
float rotation_radians = rotation_degrees * PI / 180;
|
||||
float rotation_radians = rotation_degrees * std::numbers::pi / 180;
|
||||
// A pointy top variation means the first vertex of the polygon is at the top center of the shape, this requires no
|
||||
// additional rotation of the shape.
|
||||
// A flat top variation means the first point of the polygon has to be rotated so that the first edge is horizontal,
|
||||
// this requires to rotate the shape by π/edges radians counter-clockwise so that the first point is located on the
|
||||
// left side of the first horizontal edge.
|
||||
rotation_radians -= (variation == VARIATION_FLAT_TOP) ? PI / edges : 0.0;
|
||||
rotation_radians -= (variation == VARIATION_FLAT_TOP) ? std::numbers::pi / edges : 0.0;
|
||||
|
||||
float vertex_angle = ((float) vertex_id) / edges * 2 * PI + rotation_radians;
|
||||
float vertex_angle = ((float) vertex_id) / edges * 2 * std::numbers::pi + rotation_radians;
|
||||
*vertex_x = (int) round(cos(vertex_angle) * radius) + center_x;
|
||||
*vertex_y = (int) round(sin(vertex_angle) * radius) + center_y;
|
||||
}
|
||||
|
||||
@@ -138,8 +138,6 @@ enum DisplayRotation {
|
||||
DISPLAY_ROTATION_270_DEGREES = 270,
|
||||
};
|
||||
|
||||
#define PI 3.1415926535897932384626433832795
|
||||
|
||||
const int EDGES_TRIGON = 3;
|
||||
const int EDGES_TRIANGLE = 3;
|
||||
const int EDGES_TETRAGON = 4;
|
||||
|
||||
@@ -341,6 +341,7 @@ SUPPORTED_PLATFORMIO_ESP_IDF_5X = [
|
||||
# List based on https://github.com/pioarduino/esp-idf/releases
|
||||
SUPPORTED_PIOARDUINO_ESP_IDF_5X = [
|
||||
cv.Version(5, 5, 0),
|
||||
cv.Version(5, 4, 2),
|
||||
cv.Version(5, 4, 1),
|
||||
cv.Version(5, 4, 0),
|
||||
cv.Version(5, 3, 3),
|
||||
@@ -610,7 +611,7 @@ ESP_IDF_FRAMEWORK_SCHEMA = cv.All(
|
||||
CONF_ENABLE_LWIP_DHCP_SERVER, "wifi", default=False
|
||||
): cv.boolean,
|
||||
cv.Optional(
|
||||
CONF_ENABLE_LWIP_MDNS_QUERIES, default=False
|
||||
CONF_ENABLE_LWIP_MDNS_QUERIES, default=True
|
||||
): cv.boolean,
|
||||
cv.Optional(
|
||||
CONF_ENABLE_LWIP_BRIDGE_INTERFACE, default=False
|
||||
@@ -704,7 +705,7 @@ FINAL_VALIDATE_SCHEMA = cv.Schema(final_validate)
|
||||
async def to_code(config):
|
||||
cg.add_platformio_option("board", config[CONF_BOARD])
|
||||
cg.add_platformio_option("board_upload.flash_size", config[CONF_FLASH_SIZE])
|
||||
cg.set_cpp_standard("gnu++17")
|
||||
cg.set_cpp_standard("gnu++20")
|
||||
cg.add_build_flag("-DUSE_ESP32")
|
||||
cg.add_define("ESPHOME_BOARD", config[CONF_BOARD])
|
||||
cg.add_build_flag(f"-DUSE_ESP32_VARIANT_{config[CONF_VARIANT]}")
|
||||
@@ -758,6 +759,9 @@ async def to_code(config):
|
||||
add_idf_sdkconfig_option("CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0", False)
|
||||
add_idf_sdkconfig_option("CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU1", False)
|
||||
|
||||
# Disable dynamic log level control to save memory
|
||||
add_idf_sdkconfig_option("CONFIG_LOG_DYNAMIC_LEVEL_CONTROL", False)
|
||||
|
||||
# Set default CPU frequency
|
||||
add_idf_sdkconfig_option(f"CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_{freq}", True)
|
||||
|
||||
@@ -770,7 +774,7 @@ async def to_code(config):
|
||||
and not advanced[CONF_ENABLE_LWIP_DHCP_SERVER]
|
||||
):
|
||||
add_idf_sdkconfig_option("CONFIG_LWIP_DHCPS", False)
|
||||
if not advanced.get(CONF_ENABLE_LWIP_MDNS_QUERIES, False):
|
||||
if not advanced.get(CONF_ENABLE_LWIP_MDNS_QUERIES, True):
|
||||
add_idf_sdkconfig_option("CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES", False)
|
||||
if not advanced.get(CONF_ENABLE_LWIP_BRIDGE_INTERFACE, False):
|
||||
add_idf_sdkconfig_option("CONFIG_LWIP_BRIDGEIF_MAX_PORTS", 0)
|
||||
|
||||
@@ -29,9 +29,9 @@ class ESP32InternalGPIOPin : public InternalGPIOPin {
|
||||
void attach_interrupt(void (*func)(void *), void *arg, gpio::InterruptType type) const override;
|
||||
|
||||
gpio_num_t pin_;
|
||||
bool inverted_;
|
||||
gpio_drive_cap_t drive_strength_;
|
||||
gpio::Flags flags_;
|
||||
bool inverted_;
|
||||
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
|
||||
static bool isr_service_installed;
|
||||
};
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
#ifdef USE_ESP32
|
||||
|
||||
#include "ble.h"
|
||||
#include "ble_event_pool.h"
|
||||
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
|
||||
@@ -12,8 +12,8 @@
|
||||
#include "esphome/core/helpers.h"
|
||||
|
||||
#include "ble_event.h"
|
||||
#include "ble_event_pool.h"
|
||||
#include "queue.h"
|
||||
#include "esphome/core/lock_free_queue.h"
|
||||
#include "esphome/core/event_pool.h"
|
||||
|
||||
#ifdef USE_ESP32
|
||||
|
||||
@@ -148,8 +148,8 @@ class ESP32BLE : public Component {
|
||||
std::vector<BLEStatusEventHandler *> ble_status_event_handlers_;
|
||||
BLEComponentState state_{BLE_COMPONENT_STATE_OFF};
|
||||
|
||||
LockFreeQueue<BLEEvent, MAX_BLE_QUEUE_SIZE> ble_events_;
|
||||
BLEEventPool<MAX_BLE_QUEUE_SIZE> ble_event_pool_;
|
||||
esphome::LockFreeQueue<BLEEvent, MAX_BLE_QUEUE_SIZE> ble_events_;
|
||||
esphome::EventPool<BLEEvent, MAX_BLE_QUEUE_SIZE> ble_event_pool_;
|
||||
BLEAdvertising *advertising_{};
|
||||
esp_ble_io_cap_t io_cap_{ESP_IO_CAP_NONE};
|
||||
uint32_t advertising_cycle_time_{};
|
||||
|
||||
@@ -134,13 +134,13 @@ class BLEEvent {
|
||||
}
|
||||
|
||||
// Destructor to clean up heap allocations
|
||||
~BLEEvent() { this->cleanup_heap_data(); }
|
||||
~BLEEvent() { this->release(); }
|
||||
|
||||
// Default constructor for pre-allocation in pool
|
||||
BLEEvent() : type_(GAP) {}
|
||||
|
||||
// Clean up any heap-allocated data
|
||||
void cleanup_heap_data() {
|
||||
// Invoked on return to EventPool - clean up any heap-allocated data
|
||||
void release() {
|
||||
if (this->type_ == GAP) {
|
||||
return;
|
||||
}
|
||||
@@ -161,19 +161,19 @@ class BLEEvent {
|
||||
|
||||
// Load new event data for reuse (replaces previous event data)
|
||||
void load_gap_event(esp_gap_ble_cb_event_t e, esp_ble_gap_cb_param_t *p) {
|
||||
this->cleanup_heap_data();
|
||||
this->release();
|
||||
this->type_ = GAP;
|
||||
this->init_gap_data_(e, p);
|
||||
}
|
||||
|
||||
void load_gattc_event(esp_gattc_cb_event_t e, esp_gatt_if_t i, esp_ble_gattc_cb_param_t *p) {
|
||||
this->cleanup_heap_data();
|
||||
this->release();
|
||||
this->type_ = GATTC;
|
||||
this->init_gattc_data_(e, i, p);
|
||||
}
|
||||
|
||||
void load_gatts_event(esp_gatts_cb_event_t e, esp_gatt_if_t i, esp_ble_gatts_cb_param_t *p) {
|
||||
this->cleanup_heap_data();
|
||||
this->release();
|
||||
this->type_ = GATTS;
|
||||
this->init_gatts_data_(e, i, p);
|
||||
}
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#ifdef USE_ESP32
|
||||
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include "ble_event.h"
|
||||
#include "queue.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
|
||||
namespace esphome {
|
||||
namespace esp32_ble {
|
||||
|
||||
// BLE Event Pool - On-demand pool of BLEEvent objects to avoid heap fragmentation
|
||||
// Events are allocated on first use and reused thereafter, growing to peak usage
|
||||
template<uint8_t SIZE> class BLEEventPool {
|
||||
public:
|
||||
BLEEventPool() : total_created_(0) {}
|
||||
|
||||
~BLEEventPool() {
|
||||
// Clean up any remaining events in the free list
|
||||
BLEEvent *event;
|
||||
while ((event = this->free_list_.pop()) != nullptr) {
|
||||
delete event;
|
||||
}
|
||||
}
|
||||
|
||||
// Allocate an event from the pool
|
||||
// Returns nullptr if pool is full
|
||||
BLEEvent *allocate() {
|
||||
// Try to get from free list first
|
||||
BLEEvent *event = this->free_list_.pop();
|
||||
if (event != nullptr)
|
||||
return event;
|
||||
|
||||
// Need to create a new event
|
||||
if (this->total_created_ >= SIZE) {
|
||||
// Pool is at capacity
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Use internal RAM for better performance
|
||||
RAMAllocator<BLEEvent> allocator(RAMAllocator<BLEEvent>::ALLOC_INTERNAL);
|
||||
event = allocator.allocate(1);
|
||||
|
||||
if (event == nullptr) {
|
||||
// Memory allocation failed
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Placement new to construct the object
|
||||
new (event) BLEEvent();
|
||||
this->total_created_++;
|
||||
return event;
|
||||
}
|
||||
|
||||
// Return an event to the pool for reuse
|
||||
void release(BLEEvent *event) {
|
||||
if (event != nullptr) {
|
||||
this->free_list_.push(event);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
LockFreeQueue<BLEEvent, SIZE> free_list_; // Free events ready for reuse
|
||||
uint8_t total_created_; // Total events created (high water mark)
|
||||
};
|
||||
|
||||
} // namespace esp32_ble
|
||||
} // namespace esphome
|
||||
|
||||
#endif
|
||||
@@ -1,85 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#ifdef USE_ESP32
|
||||
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
|
||||
/*
|
||||
* BLE events come in from a separate Task (thread) in the ESP32 stack. Rather
|
||||
* than using mutex-based locking, this lock-free queue allows the BLE
|
||||
* task to enqueue events without blocking. The main loop() then processes
|
||||
* these events at a safer time.
|
||||
*
|
||||
* This is a Single-Producer Single-Consumer (SPSC) lock-free ring buffer.
|
||||
* The BLE task is the only producer, and the main loop() is the only consumer.
|
||||
*/
|
||||
|
||||
namespace esphome {
|
||||
namespace esp32_ble {
|
||||
|
||||
template<class T, uint8_t SIZE> class LockFreeQueue {
|
||||
public:
|
||||
LockFreeQueue() : head_(0), tail_(0), dropped_count_(0) {}
|
||||
|
||||
bool push(T *element) {
|
||||
if (element == nullptr)
|
||||
return false;
|
||||
|
||||
uint8_t current_tail = tail_.load(std::memory_order_relaxed);
|
||||
uint8_t next_tail = (current_tail + 1) % SIZE;
|
||||
|
||||
if (next_tail == head_.load(std::memory_order_acquire)) {
|
||||
// Buffer full
|
||||
dropped_count_.fetch_add(1, std::memory_order_relaxed);
|
||||
return false;
|
||||
}
|
||||
|
||||
buffer_[current_tail] = element;
|
||||
tail_.store(next_tail, std::memory_order_release);
|
||||
return true;
|
||||
}
|
||||
|
||||
T *pop() {
|
||||
uint8_t current_head = head_.load(std::memory_order_relaxed);
|
||||
|
||||
if (current_head == tail_.load(std::memory_order_acquire)) {
|
||||
return nullptr; // Empty
|
||||
}
|
||||
|
||||
T *element = buffer_[current_head];
|
||||
head_.store((current_head + 1) % SIZE, std::memory_order_release);
|
||||
return element;
|
||||
}
|
||||
|
||||
size_t size() const {
|
||||
uint8_t tail = tail_.load(std::memory_order_acquire);
|
||||
uint8_t head = head_.load(std::memory_order_acquire);
|
||||
return (tail - head + SIZE) % SIZE;
|
||||
}
|
||||
|
||||
uint16_t get_and_reset_dropped_count() { return dropped_count_.exchange(0, std::memory_order_relaxed); }
|
||||
|
||||
void increment_dropped_count() { dropped_count_.fetch_add(1, std::memory_order_relaxed); }
|
||||
|
||||
bool empty() const { return head_.load(std::memory_order_acquire) == tail_.load(std::memory_order_acquire); }
|
||||
|
||||
bool full() const {
|
||||
uint8_t next_tail = (tail_.load(std::memory_order_relaxed) + 1) % SIZE;
|
||||
return next_tail == head_.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
protected:
|
||||
T *buffer_[SIZE];
|
||||
// Atomic: written by producer (push/increment), read+reset by consumer (get_and_reset)
|
||||
std::atomic<uint16_t> dropped_count_; // 65535 max - more than enough for drop tracking
|
||||
// Atomic: written by consumer (pop), read by producer (push) to check if full
|
||||
std::atomic<uint8_t> head_;
|
||||
// Atomic: written by producer (push), read by consumer (pop) to check if empty
|
||||
std::atomic<uint8_t> tail_;
|
||||
};
|
||||
|
||||
} // namespace esp32_ble
|
||||
} // namespace esphome
|
||||
|
||||
#endif
|
||||
@@ -496,17 +496,17 @@ float BLEClientBase::parse_char_value(uint8_t *value, uint16_t length) {
|
||||
if (length > 2) {
|
||||
return (float) encode_uint16(value[1], value[2]);
|
||||
}
|
||||
// fall through
|
||||
[[fallthrough]];
|
||||
case 0x7: // uint24.
|
||||
if (length > 3) {
|
||||
return (float) encode_uint24(value[1], value[2], value[3]);
|
||||
}
|
||||
// fall through
|
||||
[[fallthrough]];
|
||||
case 0x8: // uint32.
|
||||
if (length > 4) {
|
||||
return (float) encode_uint32(value[1], value[2], value[3], value[4]);
|
||||
}
|
||||
// fall through
|
||||
[[fallthrough]];
|
||||
case 0xC: // int8.
|
||||
return (float) ((int8_t) value[1]);
|
||||
case 0xD: // int12.
|
||||
@@ -514,12 +514,12 @@ float BLEClientBase::parse_char_value(uint8_t *value, uint16_t length) {
|
||||
if (length > 2) {
|
||||
return (float) ((int16_t) (value[1] << 8) + (int16_t) value[2]);
|
||||
}
|
||||
// fall through
|
||||
[[fallthrough]];
|
||||
case 0xF: // int24.
|
||||
if (length > 3) {
|
||||
return (float) ((int32_t) (value[1] << 16) + (int32_t) (value[2] << 8) + (int32_t) (value[3]));
|
||||
}
|
||||
// fall through
|
||||
[[fallthrough]];
|
||||
case 0x10: // int32.
|
||||
if (length > 4) {
|
||||
return (float) ((int32_t) (value[1] << 24) + (int32_t) (value[2] << 16) + (int32_t) (value[3] << 8) +
|
||||
|
||||
@@ -310,11 +310,7 @@ async def to_code(config):
|
||||
cg.add_define("USE_ESP32_CAMERA")
|
||||
|
||||
if CORE.using_esp_idf:
|
||||
add_idf_component(
|
||||
name="esp32-camera",
|
||||
repo="https://github.com/espressif/esp32-camera.git",
|
||||
ref="v2.0.15",
|
||||
)
|
||||
add_idf_component(name="espressif/esp32-camera", ref="2.0.15")
|
||||
|
||||
for conf in config.get(CONF_ON_STREAM_START, []):
|
||||
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
|
||||
|
||||
101
esphome/components/esp32_hosted/__init__.py
Normal file
101
esphome/components/esp32_hosted/__init__.py
Normal file
@@ -0,0 +1,101 @@
|
||||
import os
|
||||
|
||||
from esphome import pins
|
||||
from esphome.components import esp32
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import (
|
||||
CONF_CLK_PIN,
|
||||
CONF_RESET_PIN,
|
||||
CONF_VARIANT,
|
||||
KEY_CORE,
|
||||
KEY_FRAMEWORK_VERSION,
|
||||
)
|
||||
from esphome.core import CORE
|
||||
|
||||
CODEOWNERS = ["@swoboda1337"]
|
||||
|
||||
CONF_ACTIVE_HIGH = "active_high"
|
||||
CONF_CMD_PIN = "cmd_pin"
|
||||
CONF_D0_PIN = "d0_pin"
|
||||
CONF_D1_PIN = "d1_pin"
|
||||
CONF_D2_PIN = "d2_pin"
|
||||
CONF_D3_PIN = "d3_pin"
|
||||
CONF_SLOT = "slot"
|
||||
|
||||
CONFIG_SCHEMA = cv.All(
|
||||
cv.Schema(
|
||||
{
|
||||
cv.Required(CONF_VARIANT): cv.one_of(*esp32.VARIANTS, upper=True),
|
||||
cv.Required(CONF_ACTIVE_HIGH): cv.boolean,
|
||||
cv.Required(CONF_CLK_PIN): pins.internal_gpio_output_pin_number,
|
||||
cv.Required(CONF_CMD_PIN): pins.internal_gpio_output_pin_number,
|
||||
cv.Required(CONF_D0_PIN): pins.internal_gpio_output_pin_number,
|
||||
cv.Required(CONF_D1_PIN): pins.internal_gpio_output_pin_number,
|
||||
cv.Required(CONF_D2_PIN): pins.internal_gpio_output_pin_number,
|
||||
cv.Required(CONF_D3_PIN): pins.internal_gpio_output_pin_number,
|
||||
cv.Required(CONF_RESET_PIN): pins.internal_gpio_output_pin_number,
|
||||
cv.Optional(CONF_SLOT, default=1): cv.int_range(min=0, max=1),
|
||||
}
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config):
|
||||
if config[CONF_ACTIVE_HIGH]:
|
||||
esp32.add_idf_sdkconfig_option(
|
||||
"CONFIG_ESP_HOSTED_SDIO_RESET_ACTIVE_HIGH",
|
||||
True,
|
||||
)
|
||||
else:
|
||||
esp32.add_idf_sdkconfig_option(
|
||||
"CONFIG_ESP_HOSTED_SDIO_RESET_ACTIVE_LOW",
|
||||
True,
|
||||
)
|
||||
esp32.add_idf_sdkconfig_option(
|
||||
"CONFIG_ESP_HOSTED_SDIO_GPIO_RESET_SLAVE", # NOLINT
|
||||
config[CONF_RESET_PIN],
|
||||
)
|
||||
esp32.add_idf_sdkconfig_option(
|
||||
f"CONFIG_SLAVE_IDF_TARGET_{config[CONF_VARIANT]}", # NOLINT
|
||||
True,
|
||||
)
|
||||
esp32.add_idf_sdkconfig_option(
|
||||
f"CONFIG_ESP_HOSTED_SDIO_SLOT_{config[CONF_SLOT]}",
|
||||
True,
|
||||
)
|
||||
esp32.add_idf_sdkconfig_option(
|
||||
f"CONFIG_ESP_HOSTED_PRIV_SDIO_PIN_CLK_SLOT_{config[CONF_SLOT]}",
|
||||
config[CONF_CLK_PIN],
|
||||
)
|
||||
esp32.add_idf_sdkconfig_option(
|
||||
f"CONFIG_ESP_HOSTED_PRIV_SDIO_PIN_CMD_SLOT_{config[CONF_SLOT]}",
|
||||
config[CONF_CMD_PIN],
|
||||
)
|
||||
esp32.add_idf_sdkconfig_option(
|
||||
f"CONFIG_ESP_HOSTED_PRIV_SDIO_PIN_D0_SLOT_{config[CONF_SLOT]}",
|
||||
config[CONF_D0_PIN],
|
||||
)
|
||||
esp32.add_idf_sdkconfig_option(
|
||||
f"CONFIG_ESP_HOSTED_PRIV_SDIO_PIN_D1_4BIT_BUS_SLOT_{config[CONF_SLOT]}",
|
||||
config[CONF_D1_PIN],
|
||||
)
|
||||
esp32.add_idf_sdkconfig_option(
|
||||
f"CONFIG_ESP_HOSTED_PRIV_SDIO_PIN_D2_4BIT_BUS_SLOT_{config[CONF_SLOT]}",
|
||||
config[CONF_D2_PIN],
|
||||
)
|
||||
esp32.add_idf_sdkconfig_option(
|
||||
f"CONFIG_ESP_HOSTED_PRIV_SDIO_PIN_D3_4BIT_BUS_SLOT_{config[CONF_SLOT]}",
|
||||
config[CONF_D3_PIN],
|
||||
)
|
||||
esp32.add_idf_sdkconfig_option("CONFIG_ESP_HOSTED_CUSTOM_SDIO_PINS", True)
|
||||
|
||||
framework_ver: cv.Version = CORE.data[KEY_CORE][KEY_FRAMEWORK_VERSION]
|
||||
os.environ["ESP_IDF_VERSION"] = f"{framework_ver.major}.{framework_ver.minor}"
|
||||
esp32.add_idf_component(name="espressif/esp_wifi_remote", ref="0.10.2")
|
||||
esp32.add_idf_component(name="espressif/eppp_link", ref="0.2.0")
|
||||
esp32.add_idf_component(name="espressif/esp_hosted", ref="2.0.11")
|
||||
esp32.add_extra_script(
|
||||
"post",
|
||||
"esp32_hosted.py",
|
||||
os.path.join(os.path.dirname(__file__), "esp32_hosted.py.script"),
|
||||
)
|
||||
12
esphome/components/esp32_hosted/esp32_hosted.py.script
Normal file
12
esphome/components/esp32_hosted/esp32_hosted.py.script
Normal file
@@ -0,0 +1,12 @@
|
||||
# pylint: disable=E0602
|
||||
Import("env") # noqa
|
||||
|
||||
# Workaround whole archive issue
|
||||
if "__LIB_DEPS" in env and "libespressif__esp_hosted.a" in env["__LIB_DEPS"]:
|
||||
env.Append(
|
||||
LINKFLAGS=[
|
||||
"-Wl,--whole-archive",
|
||||
env["BUILD_DIR"] + "/esp-idf/espressif__esp_hosted/libespressif__esp_hosted.a",
|
||||
"-Wl,--no-whole-archive",
|
||||
]
|
||||
)
|
||||
@@ -183,7 +183,7 @@ async def to_code(config):
|
||||
|
||||
cg.add_platformio_option("board", config[CONF_BOARD])
|
||||
cg.add_build_flag("-DUSE_ESP8266")
|
||||
cg.set_cpp_standard("gnu++17")
|
||||
cg.set_cpp_standard("gnu++20")
|
||||
cg.add_define("ESPHOME_BOARD", config[CONF_BOARD])
|
||||
cg.add_define("ESPHOME_VARIANT", "ESP8266")
|
||||
|
||||
|
||||
@@ -129,9 +129,9 @@ void IRAM_ATTR ISRInternalGPIOPin::digital_write(bool value) {
|
||||
}
|
||||
} else {
|
||||
if (value != arg->inverted) {
|
||||
*arg->out_set_reg |= 1;
|
||||
*arg->out_set_reg = *arg->out_set_reg | 1;
|
||||
} else {
|
||||
*arg->out_set_reg &= ~1;
|
||||
*arg->out_set_reg = *arg->out_set_reg & ~1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -147,7 +147,7 @@ void IRAM_ATTR ISRInternalGPIOPin::pin_mode(gpio::Flags flags) {
|
||||
if (flags & gpio::FLAG_OUTPUT) {
|
||||
*arg->mode_set_reg = arg->mask;
|
||||
if (flags & gpio::FLAG_OPEN_DRAIN) {
|
||||
*arg->control_reg |= 1 << GPCD;
|
||||
*arg->control_reg = *arg->control_reg | (1 << GPCD);
|
||||
} else {
|
||||
*arg->control_reg &= ~(1 << GPCD);
|
||||
}
|
||||
@@ -155,21 +155,21 @@ void IRAM_ATTR ISRInternalGPIOPin::pin_mode(gpio::Flags flags) {
|
||||
*arg->mode_clr_reg = arg->mask;
|
||||
}
|
||||
if (flags & gpio::FLAG_PULLUP) {
|
||||
*arg->func_reg |= 1 << GPFPU;
|
||||
*arg->control_reg |= 1 << GPCD;
|
||||
*arg->func_reg = *arg->func_reg | (1 << GPFPU);
|
||||
*arg->control_reg = *arg->control_reg | (1 << GPCD);
|
||||
} else {
|
||||
*arg->func_reg &= ~(1 << GPFPU);
|
||||
*arg->func_reg = *arg->func_reg & ~(1 << GPFPU);
|
||||
}
|
||||
} else {
|
||||
if (flags & gpio::FLAG_OUTPUT) {
|
||||
*arg->mode_set_reg |= 1;
|
||||
*arg->mode_set_reg = *arg->mode_set_reg | 1;
|
||||
} else {
|
||||
*arg->mode_set_reg &= ~1;
|
||||
*arg->mode_set_reg = *arg->mode_set_reg & ~1;
|
||||
}
|
||||
if (flags & gpio::FLAG_PULLDOWN) {
|
||||
*arg->func_reg |= 1 << GP16FPD;
|
||||
*arg->func_reg = *arg->func_reg | (1 << GP16FPD);
|
||||
} else {
|
||||
*arg->func_reg &= ~(1 << GP16FPD);
|
||||
*arg->func_reg = *arg->func_reg & ~(1 << GP16FPD);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
namespace esphome {
|
||||
namespace ethernet {
|
||||
|
||||
enum EthernetType {
|
||||
enum EthernetType : uint8_t {
|
||||
ETHERNET_TYPE_UNKNOWN = 0,
|
||||
ETHERNET_TYPE_LAN8720,
|
||||
ETHERNET_TYPE_RTL8201,
|
||||
@@ -42,7 +42,7 @@ struct PHYRegister {
|
||||
uint32_t page;
|
||||
};
|
||||
|
||||
enum class EthernetComponentState {
|
||||
enum class EthernetComponentState : uint8_t {
|
||||
STOPPED,
|
||||
CONNECTING,
|
||||
CONNECTED,
|
||||
@@ -119,25 +119,31 @@ class EthernetComponent : public Component {
|
||||
uint32_t polling_interval_{0};
|
||||
#endif
|
||||
#else
|
||||
uint8_t phy_addr_{0};
|
||||
// Group all 32-bit members first
|
||||
int power_pin_{-1};
|
||||
uint8_t mdc_pin_{23};
|
||||
uint8_t mdio_pin_{18};
|
||||
emac_rmii_clock_mode_t clk_mode_{EMAC_CLK_EXT_IN};
|
||||
emac_rmii_clock_gpio_t clk_gpio_{EMAC_CLK_IN_GPIO};
|
||||
std::vector<PHYRegister> phy_registers_{};
|
||||
#endif
|
||||
EthernetType type_{ETHERNET_TYPE_UNKNOWN};
|
||||
optional<ManualIP> manual_ip_{};
|
||||
|
||||
// Group all 8-bit members together
|
||||
uint8_t phy_addr_{0};
|
||||
uint8_t mdc_pin_{23};
|
||||
uint8_t mdio_pin_{18};
|
||||
#endif
|
||||
optional<ManualIP> manual_ip_{};
|
||||
uint32_t connect_begin_;
|
||||
|
||||
// Group all uint8_t types together (enums and bools)
|
||||
EthernetType type_{ETHERNET_TYPE_UNKNOWN};
|
||||
EthernetComponentState state_{EthernetComponentState::STOPPED};
|
||||
bool started_{false};
|
||||
bool connected_{false};
|
||||
bool got_ipv4_address_{false};
|
||||
#if LWIP_IPV6
|
||||
uint8_t ipv6_count_{0};
|
||||
#endif /* LWIP_IPV6 */
|
||||
EthernetComponentState state_{EthernetComponentState::STOPPED};
|
||||
uint32_t connect_begin_;
|
||||
|
||||
// Pointers at the end (naturally aligned)
|
||||
esp_netif_t *eth_netif_{nullptr};
|
||||
esp_eth_handle_t eth_handle_;
|
||||
esp_eth_phy_t *phy_{nullptr};
|
||||
|
||||
@@ -10,11 +10,24 @@ GPIOBinarySensor = gpio_ns.class_(
|
||||
"GPIOBinarySensor", binary_sensor.BinarySensor, cg.Component
|
||||
)
|
||||
|
||||
CONF_USE_INTERRUPT = "use_interrupt"
|
||||
CONF_INTERRUPT_TYPE = "interrupt_type"
|
||||
|
||||
INTERRUPT_TYPES = {
|
||||
"RISING": gpio_ns.INTERRUPT_RISING_EDGE,
|
||||
"FALLING": gpio_ns.INTERRUPT_FALLING_EDGE,
|
||||
"ANY": gpio_ns.INTERRUPT_ANY_EDGE,
|
||||
}
|
||||
|
||||
CONFIG_SCHEMA = (
|
||||
binary_sensor.binary_sensor_schema(GPIOBinarySensor)
|
||||
.extend(
|
||||
{
|
||||
cv.Required(CONF_PIN): pins.gpio_input_pin_schema,
|
||||
cv.Optional(CONF_USE_INTERRUPT, default=True): cv.boolean,
|
||||
cv.Optional(CONF_INTERRUPT_TYPE, default="ANY"): cv.enum(
|
||||
INTERRUPT_TYPES, upper=True
|
||||
),
|
||||
}
|
||||
)
|
||||
.extend(cv.COMPONENT_SCHEMA)
|
||||
@@ -27,3 +40,7 @@ async def to_code(config):
|
||||
|
||||
pin = await cg.gpio_pin_expression(config[CONF_PIN])
|
||||
cg.add(var.set_pin(pin))
|
||||
|
||||
cg.add(var.set_use_interrupt(config[CONF_USE_INTERRUPT]))
|
||||
if config[CONF_USE_INTERRUPT]:
|
||||
cg.add(var.set_interrupt_type(INTERRUPT_TYPES[config[CONF_INTERRUPT_TYPE]]))
|
||||
|
||||
@@ -6,17 +6,91 @@ namespace gpio {
|
||||
|
||||
static const char *const TAG = "gpio.binary_sensor";
|
||||
|
||||
void IRAM_ATTR GPIOBinarySensorStore::gpio_intr(GPIOBinarySensorStore *arg) {
|
||||
bool new_state = arg->isr_pin_.digital_read();
|
||||
if (new_state != arg->last_state_) {
|
||||
arg->state_ = new_state;
|
||||
arg->last_state_ = new_state;
|
||||
arg->changed_ = true;
|
||||
// Wake up the component from its disabled loop state
|
||||
if (arg->component_ != nullptr) {
|
||||
arg->component_->enable_loop_soon_any_context();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void GPIOBinarySensorStore::setup(InternalGPIOPin *pin, gpio::InterruptType type, Component *component) {
|
||||
pin->setup();
|
||||
this->isr_pin_ = pin->to_isr();
|
||||
this->component_ = component;
|
||||
|
||||
// Read initial state
|
||||
this->last_state_ = pin->digital_read();
|
||||
this->state_ = this->last_state_;
|
||||
|
||||
// Attach interrupt - from this point on, any changes will be caught by the interrupt
|
||||
pin->attach_interrupt(&GPIOBinarySensorStore::gpio_intr, this, type);
|
||||
}
|
||||
|
||||
void GPIOBinarySensor::setup() {
|
||||
this->pin_->setup();
|
||||
this->publish_initial_state(this->pin_->digital_read());
|
||||
if (this->use_interrupt_ && !this->pin_->is_internal()) {
|
||||
ESP_LOGD(TAG, "GPIO is not internal, falling back to polling mode");
|
||||
this->use_interrupt_ = false;
|
||||
}
|
||||
|
||||
if (this->use_interrupt_) {
|
||||
auto *internal_pin = static_cast<InternalGPIOPin *>(this->pin_);
|
||||
this->store_.setup(internal_pin, this->interrupt_type_, this);
|
||||
this->publish_initial_state(this->store_.get_state());
|
||||
} else {
|
||||
this->pin_->setup();
|
||||
this->publish_initial_state(this->pin_->digital_read());
|
||||
}
|
||||
}
|
||||
|
||||
void GPIOBinarySensor::dump_config() {
|
||||
LOG_BINARY_SENSOR("", "GPIO Binary Sensor", this);
|
||||
LOG_PIN(" Pin: ", this->pin_);
|
||||
const char *mode = this->use_interrupt_ ? "interrupt" : "polling";
|
||||
ESP_LOGCONFIG(TAG, " Mode: %s", mode);
|
||||
if (this->use_interrupt_) {
|
||||
const char *interrupt_type;
|
||||
switch (this->interrupt_type_) {
|
||||
case gpio::INTERRUPT_RISING_EDGE:
|
||||
interrupt_type = "RISING_EDGE";
|
||||
break;
|
||||
case gpio::INTERRUPT_FALLING_EDGE:
|
||||
interrupt_type = "FALLING_EDGE";
|
||||
break;
|
||||
case gpio::INTERRUPT_ANY_EDGE:
|
||||
interrupt_type = "ANY_EDGE";
|
||||
break;
|
||||
default:
|
||||
interrupt_type = "UNKNOWN";
|
||||
break;
|
||||
}
|
||||
ESP_LOGCONFIG(TAG, " Interrupt Type: %s", interrupt_type);
|
||||
}
|
||||
}
|
||||
|
||||
void GPIOBinarySensor::loop() { this->publish_state(this->pin_->digital_read()); }
|
||||
void GPIOBinarySensor::loop() {
|
||||
if (this->use_interrupt_) {
|
||||
if (this->store_.is_changed()) {
|
||||
// Clear the flag immediately to minimize the window where we might miss changes
|
||||
this->store_.clear_changed();
|
||||
// Read the state and publish it
|
||||
// Note: If the ISR fires between clear_changed() and get_state(), that's fine -
|
||||
// we'll process the new change on the next loop iteration
|
||||
bool state = this->store_.get_state();
|
||||
this->publish_state(state);
|
||||
} else {
|
||||
// No changes, disable the loop until the next interrupt
|
||||
this->disable_loop();
|
||||
}
|
||||
} else {
|
||||
this->publish_state(this->pin_->digital_read());
|
||||
}
|
||||
}
|
||||
|
||||
float GPIOBinarySensor::get_setup_priority() const { return setup_priority::HARDWARE; }
|
||||
|
||||
|
||||
@@ -2,14 +2,51 @@
|
||||
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/components/binary_sensor/binary_sensor.h"
|
||||
|
||||
namespace esphome {
|
||||
namespace gpio {
|
||||
|
||||
// Store class for ISR data (no vtables, ISR-safe)
|
||||
class GPIOBinarySensorStore {
|
||||
public:
|
||||
void setup(InternalGPIOPin *pin, gpio::InterruptType type, Component *component);
|
||||
|
||||
static void gpio_intr(GPIOBinarySensorStore *arg);
|
||||
|
||||
bool get_state() const {
|
||||
// No lock needed: state_ is atomically updated by ISR
|
||||
// Volatile ensures we read the latest value
|
||||
return this->state_;
|
||||
}
|
||||
|
||||
bool is_changed() const {
|
||||
// Simple read of volatile bool - no clearing here
|
||||
return this->changed_;
|
||||
}
|
||||
|
||||
void clear_changed() {
|
||||
// Separate method to clear the flag
|
||||
this->changed_ = false;
|
||||
}
|
||||
|
||||
protected:
|
||||
ISRInternalGPIOPin isr_pin_;
|
||||
volatile bool state_{false};
|
||||
volatile bool last_state_{false};
|
||||
volatile bool changed_{false};
|
||||
Component *component_{nullptr}; // Pointer to the component for enable_loop_soon_any_context()
|
||||
};
|
||||
|
||||
class GPIOBinarySensor : public binary_sensor::BinarySensor, public Component {
|
||||
public:
|
||||
// No destructor needed: ESPHome components are created at boot and live forever.
|
||||
// Interrupts are only detached on reboot when memory is cleared anyway.
|
||||
|
||||
void set_pin(GPIOPin *pin) { pin_ = pin; }
|
||||
void set_use_interrupt(bool use_interrupt) { use_interrupt_ = use_interrupt; }
|
||||
void set_interrupt_type(gpio::InterruptType type) { interrupt_type_ = type; }
|
||||
// ========== INTERNAL METHODS ==========
|
||||
// (In most use cases you won't need these)
|
||||
/// Setup pin
|
||||
@@ -22,6 +59,9 @@ class GPIOBinarySensor : public binary_sensor::BinarySensor, public Component {
|
||||
|
||||
protected:
|
||||
GPIOPin *pin_;
|
||||
bool use_interrupt_{true};
|
||||
gpio::InterruptType interrupt_type_{gpio::INTERRUPT_ANY_EDGE};
|
||||
GPIOBinarySensorStore store_;
|
||||
};
|
||||
|
||||
} // namespace gpio
|
||||
|
||||
@@ -41,6 +41,6 @@ CONFIG_SCHEMA = cv.All(
|
||||
async def to_code(config):
|
||||
cg.add_build_flag("-DUSE_HOST")
|
||||
cg.add_define("USE_ESPHOME_HOST_MAC_ADDRESS", config[CONF_MAC_ADDRESS].parts)
|
||||
cg.add_build_flag("-std=gnu++17")
|
||||
cg.add_build_flag("-std=gnu++20")
|
||||
cg.add_define("ESPHOME_BOARD", "host")
|
||||
cg.add_platformio_option("platform", "platformio/native")
|
||||
|
||||
@@ -258,7 +258,7 @@ bool OtaHttpRequestComponent::http_get_md5_() {
|
||||
}
|
||||
|
||||
bool OtaHttpRequestComponent::validate_url_(const std::string &url) {
|
||||
if ((url.length() < 8) || (url.find("http") != 0) || (url.find("://") == std::string::npos)) {
|
||||
if ((url.length() < 8) || !url.starts_with("http") || (url.find("://") == std::string::npos)) {
|
||||
ESP_LOGE(TAG, "URL is invalid and/or must be prefixed with 'http://' or 'https://'");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -159,12 +159,6 @@ void HydreonRGxxComponent::schedule_reboot_() {
|
||||
});
|
||||
}
|
||||
|
||||
bool HydreonRGxxComponent::buffer_starts_with_(const std::string &prefix) {
|
||||
return this->buffer_starts_with_(prefix.c_str());
|
||||
}
|
||||
|
||||
bool HydreonRGxxComponent::buffer_starts_with_(const char *prefix) { return buffer_.rfind(prefix, 0) == 0; }
|
||||
|
||||
void HydreonRGxxComponent::process_line_() {
|
||||
ESP_LOGV(TAG, "Read from serial: %s", this->buffer_.substr(0, this->buffer_.size() - 2).c_str());
|
||||
|
||||
@@ -191,7 +185,7 @@ void HydreonRGxxComponent::process_line_() {
|
||||
ESP_LOGW(TAG, "Received EmSat!");
|
||||
this->em_sat_ = true;
|
||||
}
|
||||
if (this->buffer_starts_with_("PwrDays")) {
|
||||
if (buffer_.starts_with("PwrDays")) {
|
||||
if (this->boot_count_ <= 0) {
|
||||
this->boot_count_ = 1;
|
||||
} else {
|
||||
@@ -220,7 +214,7 @@ void HydreonRGxxComponent::process_line_() {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (this->buffer_starts_with_("SW")) {
|
||||
if (buffer_.starts_with("SW")) {
|
||||
std::string::size_type majend = this->buffer_.find('.');
|
||||
std::string::size_type endversion = this->buffer_.find(' ', 3);
|
||||
if (majend == std::string::npos || endversion == std::string::npos || majend > endversion) {
|
||||
@@ -282,7 +276,7 @@ void HydreonRGxxComponent::process_line_() {
|
||||
}
|
||||
} else {
|
||||
for (const auto *ignore : IGNORE_STRINGS) {
|
||||
if (this->buffer_starts_with_(ignore)) {
|
||||
if (buffer_.starts_with(ignore)) {
|
||||
ESP_LOGI(TAG, "Ignoring %s", this->buffer_.substr(0, this->buffer_.size() - 2).c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import logging
|
||||
|
||||
from esphome import pins
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import esp32
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import (
|
||||
CONF_ADDRESS,
|
||||
@@ -12,6 +15,8 @@ from esphome.const import (
|
||||
CONF_SCL,
|
||||
CONF_SDA,
|
||||
CONF_TIMEOUT,
|
||||
KEY_CORE,
|
||||
KEY_FRAMEWORK_VERSION,
|
||||
PLATFORM_ESP32,
|
||||
PLATFORM_ESP8266,
|
||||
PLATFORM_RP2040,
|
||||
@@ -19,6 +24,7 @@ from esphome.const import (
|
||||
from esphome.core import CORE, coroutine_with_priority
|
||||
import esphome.final_validate as fv
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
CODEOWNERS = ["@esphome/core"]
|
||||
i2c_ns = cg.esphome_ns.namespace("i2c")
|
||||
I2CBus = i2c_ns.class_("I2CBus")
|
||||
@@ -41,6 +47,32 @@ def _bus_declare_type(value):
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
def validate_config(config):
|
||||
if (
|
||||
config[CONF_SCAN]
|
||||
and CORE.is_esp32
|
||||
and CORE.using_esp_idf
|
||||
and esp32.get_esp32_variant()
|
||||
in [
|
||||
esp32.const.VARIANT_ESP32C5,
|
||||
esp32.const.VARIANT_ESP32C6,
|
||||
esp32.const.VARIANT_ESP32P4,
|
||||
]
|
||||
):
|
||||
version: cv.Version = CORE.data[KEY_CORE][KEY_FRAMEWORK_VERSION]
|
||||
if version.major == 5 and (
|
||||
(version.minor == 3 and version.patch <= 3)
|
||||
or (version.minor == 4 and version.patch <= 1)
|
||||
):
|
||||
LOGGER.warning(
|
||||
"There is a bug in esp-idf version %s that breaks I2C scan, I2C scan "
|
||||
"has been disabled, see https://github.com/esphome/issues/issues/7128",
|
||||
str(version),
|
||||
)
|
||||
config[CONF_SCAN] = False
|
||||
return config
|
||||
|
||||
|
||||
pin_with_input_and_output_support = pins.internal_gpio_pin_number(
|
||||
{CONF_OUTPUT: True, CONF_INPUT: True}
|
||||
)
|
||||
@@ -66,6 +98,7 @@ CONFIG_SCHEMA = cv.All(
|
||||
}
|
||||
).extend(cv.COMPONENT_SCHEMA),
|
||||
cv.only_on([PLATFORM_ESP32, PLATFORM_ESP8266, PLATFORM_RP2040]),
|
||||
validate_config,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
|
||||
#include "esphome/core/application.h"
|
||||
|
||||
#define CHECK_BIT(var, pos) (((var) >> (pos)) & 1)
|
||||
#define highbyte(val) (uint8_t)((val) >> 8)
|
||||
#define lowbyte(val) (uint8_t)((val) &0xff)
|
||||
|
||||
@@ -17,8 +18,162 @@ namespace esphome {
|
||||
namespace ld2410 {
|
||||
|
||||
static const char *const TAG = "ld2410";
|
||||
static const char *const NO_MAC = "08:05:04:03:02:01";
|
||||
static const char *const UNKNOWN_MAC = "unknown";
|
||||
static const char *const VERSION_FMT = "%u.%02X.%02X%02X%02X%02X";
|
||||
|
||||
LD2410Component::LD2410Component() {}
|
||||
enum BaudRateStructure : uint8_t {
|
||||
BAUD_RATE_9600 = 1,
|
||||
BAUD_RATE_19200 = 2,
|
||||
BAUD_RATE_38400 = 3,
|
||||
BAUD_RATE_57600 = 4,
|
||||
BAUD_RATE_115200 = 5,
|
||||
BAUD_RATE_230400 = 6,
|
||||
BAUD_RATE_256000 = 7,
|
||||
BAUD_RATE_460800 = 8,
|
||||
};
|
||||
|
||||
enum DistanceResolutionStructure : uint8_t {
|
||||
DISTANCE_RESOLUTION_0_2 = 0x01,
|
||||
DISTANCE_RESOLUTION_0_75 = 0x00,
|
||||
};
|
||||
|
||||
enum LightFunctionStructure : uint8_t {
|
||||
LIGHT_FUNCTION_OFF = 0x00,
|
||||
LIGHT_FUNCTION_BELOW = 0x01,
|
||||
LIGHT_FUNCTION_ABOVE = 0x02,
|
||||
};
|
||||
|
||||
enum OutPinLevelStructure : uint8_t {
|
||||
OUT_PIN_LEVEL_LOW = 0x00,
|
||||
OUT_PIN_LEVEL_HIGH = 0x01,
|
||||
};
|
||||
|
||||
enum PeriodicDataStructure : uint8_t {
|
||||
DATA_TYPES = 6,
|
||||
TARGET_STATES = 8,
|
||||
MOVING_TARGET_LOW = 9,
|
||||
MOVING_TARGET_HIGH = 10,
|
||||
MOVING_ENERGY = 11,
|
||||
STILL_TARGET_LOW = 12,
|
||||
STILL_TARGET_HIGH = 13,
|
||||
STILL_ENERGY = 14,
|
||||
DETECT_DISTANCE_LOW = 15,
|
||||
DETECT_DISTANCE_HIGH = 16,
|
||||
MOVING_SENSOR_START = 19,
|
||||
STILL_SENSOR_START = 28,
|
||||
LIGHT_SENSOR = 37,
|
||||
OUT_PIN_SENSOR = 38,
|
||||
};
|
||||
|
||||
enum PeriodicDataValue : uint8_t {
|
||||
HEAD = 0xAA,
|
||||
END = 0x55,
|
||||
CHECK = 0x00,
|
||||
};
|
||||
|
||||
enum AckDataStructure : uint8_t {
|
||||
COMMAND = 6,
|
||||
COMMAND_STATUS = 7,
|
||||
};
|
||||
|
||||
// Memory-efficient lookup tables
|
||||
struct StringToUint8 {
|
||||
const char *str;
|
||||
uint8_t value;
|
||||
};
|
||||
|
||||
struct Uint8ToString {
|
||||
uint8_t value;
|
||||
const char *str;
|
||||
};
|
||||
|
||||
constexpr StringToUint8 BAUD_RATES_BY_STR[] = {
|
||||
{"9600", BAUD_RATE_9600}, {"19200", BAUD_RATE_19200}, {"38400", BAUD_RATE_38400},
|
||||
{"57600", BAUD_RATE_57600}, {"115200", BAUD_RATE_115200}, {"230400", BAUD_RATE_230400},
|
||||
{"256000", BAUD_RATE_256000}, {"460800", BAUD_RATE_460800},
|
||||
};
|
||||
|
||||
constexpr StringToUint8 DISTANCE_RESOLUTIONS_BY_STR[] = {
|
||||
{"0.2m", DISTANCE_RESOLUTION_0_2},
|
||||
{"0.75m", DISTANCE_RESOLUTION_0_75},
|
||||
};
|
||||
|
||||
constexpr Uint8ToString DISTANCE_RESOLUTIONS_BY_UINT[] = {
|
||||
{DISTANCE_RESOLUTION_0_2, "0.2m"},
|
||||
{DISTANCE_RESOLUTION_0_75, "0.75m"},
|
||||
};
|
||||
|
||||
constexpr StringToUint8 LIGHT_FUNCTIONS_BY_STR[] = {
|
||||
{"off", LIGHT_FUNCTION_OFF},
|
||||
{"below", LIGHT_FUNCTION_BELOW},
|
||||
{"above", LIGHT_FUNCTION_ABOVE},
|
||||
};
|
||||
|
||||
constexpr Uint8ToString LIGHT_FUNCTIONS_BY_UINT[] = {
|
||||
{LIGHT_FUNCTION_OFF, "off"},
|
||||
{LIGHT_FUNCTION_BELOW, "below"},
|
||||
{LIGHT_FUNCTION_ABOVE, "above"},
|
||||
};
|
||||
|
||||
constexpr StringToUint8 OUT_PIN_LEVELS_BY_STR[] = {
|
||||
{"low", OUT_PIN_LEVEL_LOW},
|
||||
{"high", OUT_PIN_LEVEL_HIGH},
|
||||
};
|
||||
|
||||
constexpr Uint8ToString OUT_PIN_LEVELS_BY_UINT[] = {
|
||||
{OUT_PIN_LEVEL_LOW, "low"},
|
||||
{OUT_PIN_LEVEL_HIGH, "high"},
|
||||
};
|
||||
|
||||
// Helper functions for lookups
|
||||
template<size_t N> uint8_t find_uint8(const StringToUint8 (&arr)[N], const std::string &str) {
|
||||
for (const auto &entry : arr) {
|
||||
if (str == entry.str)
|
||||
return entry.value;
|
||||
}
|
||||
return 0xFF; // Not found
|
||||
}
|
||||
|
||||
template<size_t N> const char *find_str(const Uint8ToString (&arr)[N], uint8_t value) {
|
||||
for (const auto &entry : arr) {
|
||||
if (value == entry.value)
|
||||
return entry.str;
|
||||
}
|
||||
return ""; // Not found
|
||||
}
|
||||
|
||||
// Commands
|
||||
static const uint8_t CMD_ENABLE_CONF = 0xFF;
|
||||
static const uint8_t CMD_DISABLE_CONF = 0xFE;
|
||||
static const uint8_t CMD_ENABLE_ENG = 0x62;
|
||||
static const uint8_t CMD_DISABLE_ENG = 0x63;
|
||||
static const uint8_t CMD_MAXDIST_DURATION = 0x60;
|
||||
static const uint8_t CMD_QUERY = 0x61;
|
||||
static const uint8_t CMD_GATE_SENS = 0x64;
|
||||
static const uint8_t CMD_VERSION = 0xA0;
|
||||
static const uint8_t CMD_QUERY_DISTANCE_RESOLUTION = 0xAB;
|
||||
static const uint8_t CMD_SET_DISTANCE_RESOLUTION = 0xAA;
|
||||
static const uint8_t CMD_QUERY_LIGHT_CONTROL = 0xAE;
|
||||
static const uint8_t CMD_SET_LIGHT_CONTROL = 0xAD;
|
||||
static const uint8_t CMD_SET_BAUD_RATE = 0xA1;
|
||||
static const uint8_t CMD_BT_PASSWORD = 0xA9;
|
||||
static const uint8_t CMD_MAC = 0xA5;
|
||||
static const uint8_t CMD_RESET = 0xA2;
|
||||
static const uint8_t CMD_RESTART = 0xA3;
|
||||
static const uint8_t CMD_BLUETOOTH = 0xA4;
|
||||
// Commands values
|
||||
static const uint8_t CMD_MAX_MOVE_VALUE = 0x00;
|
||||
static const uint8_t CMD_MAX_STILL_VALUE = 0x01;
|
||||
static const uint8_t CMD_DURATION_VALUE = 0x02;
|
||||
// Command Header & Footer
|
||||
static const uint8_t CMD_FRAME_HEADER[4] = {0xFD, 0xFC, 0xFB, 0xFA};
|
||||
static const uint8_t CMD_FRAME_END[4] = {0x04, 0x03, 0x02, 0x01};
|
||||
// Data Header & Footer
|
||||
static const uint8_t DATA_FRAME_HEADER[4] = {0xF4, 0xF3, 0xF2, 0xF1};
|
||||
static const uint8_t DATA_FRAME_END[4] = {0xF8, 0xF7, 0xF6, 0xF5};
|
||||
|
||||
static inline int two_byte_to_int(char firstbyte, char secondbyte) { return (int16_t) (secondbyte << 8) + firstbyte; }
|
||||
|
||||
void LD2410Component::dump_config() {
|
||||
ESP_LOGCONFIG(TAG, "LD2410:");
|
||||
@@ -78,7 +233,7 @@ void LD2410Component::dump_config() {
|
||||
" Throttle: %ums\n"
|
||||
" MAC address: %s\n"
|
||||
" Firmware version: %s",
|
||||
this->throttle_, const_cast<char *>(this->mac_.c_str()), const_cast<char *>(this->version_.c_str()));
|
||||
this->throttle_, this->mac_ == NO_MAC ? UNKNOWN_MAC : this->mac_.c_str(), this->version_.c_str());
|
||||
}
|
||||
|
||||
void LD2410Component::setup() {
|
||||
@@ -200,7 +355,7 @@ void LD2410Component::handle_periodic_data_(uint8_t *buffer, int len) {
|
||||
*/
|
||||
#ifdef USE_SENSOR
|
||||
if (this->moving_target_distance_sensor_ != nullptr) {
|
||||
int new_moving_target_distance = this->two_byte_to_int_(buffer[MOVING_TARGET_LOW], buffer[MOVING_TARGET_HIGH]);
|
||||
int new_moving_target_distance = ld2410::two_byte_to_int(buffer[MOVING_TARGET_LOW], buffer[MOVING_TARGET_HIGH]);
|
||||
if (this->moving_target_distance_sensor_->get_state() != new_moving_target_distance)
|
||||
this->moving_target_distance_sensor_->publish_state(new_moving_target_distance);
|
||||
}
|
||||
@@ -210,7 +365,7 @@ void LD2410Component::handle_periodic_data_(uint8_t *buffer, int len) {
|
||||
this->moving_target_energy_sensor_->publish_state(new_moving_target_energy);
|
||||
}
|
||||
if (this->still_target_distance_sensor_ != nullptr) {
|
||||
int new_still_target_distance = this->two_byte_to_int_(buffer[STILL_TARGET_LOW], buffer[STILL_TARGET_HIGH]);
|
||||
int new_still_target_distance = ld2410::two_byte_to_int(buffer[STILL_TARGET_LOW], buffer[STILL_TARGET_HIGH]);
|
||||
if (this->still_target_distance_sensor_->get_state() != new_still_target_distance)
|
||||
this->still_target_distance_sensor_->publish_state(new_still_target_distance);
|
||||
}
|
||||
@@ -220,7 +375,7 @@ void LD2410Component::handle_periodic_data_(uint8_t *buffer, int len) {
|
||||
this->still_target_energy_sensor_->publish_state(new_still_target_energy);
|
||||
}
|
||||
if (this->detection_distance_sensor_ != nullptr) {
|
||||
int new_detect_distance = this->two_byte_to_int_(buffer[DETECT_DISTANCE_LOW], buffer[DETECT_DISTANCE_HIGH]);
|
||||
int new_detect_distance = ld2410::two_byte_to_int(buffer[DETECT_DISTANCE_LOW], buffer[DETECT_DISTANCE_HIGH]);
|
||||
if (this->detection_distance_sensor_->get_state() != new_detect_distance)
|
||||
this->detection_distance_sensor_->publish_state(new_detect_distance);
|
||||
}
|
||||
@@ -282,25 +437,6 @@ void LD2410Component::handle_periodic_data_(uint8_t *buffer, int len) {
|
||||
#endif
|
||||
}
|
||||
|
||||
const char VERSION_FMT[] = "%u.%02X.%02X%02X%02X%02X";
|
||||
|
||||
std::string format_version(uint8_t *buffer) {
|
||||
std::string::size_type version_size = 256;
|
||||
std::string version;
|
||||
do {
|
||||
version.resize(version_size + 1);
|
||||
version_size = std::snprintf(&version[0], version.size(), VERSION_FMT, buffer[13], buffer[12], buffer[17],
|
||||
buffer[16], buffer[15], buffer[14]);
|
||||
} while (version_size + 1 > version.size());
|
||||
version.resize(version_size);
|
||||
return version;
|
||||
}
|
||||
|
||||
const char MAC_FMT[] = "%02X:%02X:%02X:%02X:%02X:%02X";
|
||||
|
||||
const std::string UNKNOWN_MAC("unknown");
|
||||
const std::string NO_MAC("08:05:04:03:02:01");
|
||||
|
||||
#ifdef USE_NUMBER
|
||||
std::function<void(void)> set_number_value(number::Number *n, float value) {
|
||||
float normalized_value = value * 1.0;
|
||||
@@ -326,7 +462,7 @@ bool LD2410Component::handle_ack_data_(uint8_t *buffer, int len) {
|
||||
ESP_LOGE(TAG, "Invalid status");
|
||||
return true;
|
||||
}
|
||||
if (this->two_byte_to_int_(buffer[8], buffer[9]) != 0x00) {
|
||||
if (ld2410::two_byte_to_int(buffer[8], buffer[9]) != 0x00) {
|
||||
ESP_LOGE(TAG, "Invalid command: %u, %u", buffer[8], buffer[9]);
|
||||
return true;
|
||||
}
|
||||
@@ -347,8 +483,8 @@ bool LD2410Component::handle_ack_data_(uint8_t *buffer, int len) {
|
||||
#endif
|
||||
break;
|
||||
case lowbyte(CMD_VERSION):
|
||||
this->version_ = format_version(buffer);
|
||||
ESP_LOGV(TAG, "Firmware version: %s", const_cast<char *>(this->version_.c_str()));
|
||||
this->version_ = str_sprintf(VERSION_FMT, buffer[13], buffer[12], buffer[17], buffer[16], buffer[15], buffer[14]);
|
||||
ESP_LOGV(TAG, "Firmware version: %s", this->version_.c_str());
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
if (this->version_text_sensor_ != nullptr) {
|
||||
this->version_text_sensor_->publish_state(this->version_);
|
||||
@@ -357,8 +493,8 @@ bool LD2410Component::handle_ack_data_(uint8_t *buffer, int len) {
|
||||
break;
|
||||
case lowbyte(CMD_QUERY_DISTANCE_RESOLUTION): {
|
||||
std::string distance_resolution =
|
||||
DISTANCE_RESOLUTION_INT_TO_ENUM.at(this->two_byte_to_int_(buffer[10], buffer[11]));
|
||||
ESP_LOGV(TAG, "Distance resolution: %s", const_cast<char *>(distance_resolution.c_str()));
|
||||
find_str(DISTANCE_RESOLUTIONS_BY_UINT, ld2410::two_byte_to_int(buffer[10], buffer[11]));
|
||||
ESP_LOGV(TAG, "Distance resolution: %s", distance_resolution.c_str());
|
||||
#ifdef USE_SELECT
|
||||
if (this->distance_resolution_select_ != nullptr &&
|
||||
this->distance_resolution_select_->state != distance_resolution) {
|
||||
@@ -367,9 +503,9 @@ bool LD2410Component::handle_ack_data_(uint8_t *buffer, int len) {
|
||||
#endif
|
||||
} break;
|
||||
case lowbyte(CMD_QUERY_LIGHT_CONTROL): {
|
||||
this->light_function_ = LIGHT_FUNCTION_INT_TO_ENUM.at(buffer[10]);
|
||||
this->light_function_ = find_str(LIGHT_FUNCTIONS_BY_UINT, buffer[10]);
|
||||
this->light_threshold_ = buffer[11] * 1.0;
|
||||
this->out_pin_level_ = OUT_PIN_LEVEL_INT_TO_ENUM.at(buffer[12]);
|
||||
this->out_pin_level_ = find_str(OUT_PIN_LEVELS_BY_UINT, buffer[12]);
|
||||
ESP_LOGV(TAG, "Light function: %s", const_cast<char *>(this->light_function_.c_str()));
|
||||
ESP_LOGV(TAG, "Light threshold: %f", this->light_threshold_);
|
||||
ESP_LOGV(TAG, "Out pin level: %s", const_cast<char *>(this->out_pin_level_.c_str()));
|
||||
@@ -402,7 +538,7 @@ bool LD2410Component::handle_ack_data_(uint8_t *buffer, int len) {
|
||||
#endif
|
||||
#ifdef USE_SWITCH
|
||||
if (this->bluetooth_switch_ != nullptr) {
|
||||
this->bluetooth_switch_->publish_state(this->mac_ != UNKNOWN_MAC);
|
||||
this->bluetooth_switch_->publish_state(this->mac_ != NO_MAC);
|
||||
}
|
||||
#endif
|
||||
break;
|
||||
@@ -448,7 +584,7 @@ bool LD2410Component::handle_ack_data_(uint8_t *buffer, int len) {
|
||||
/*
|
||||
None Duration: 33~34th bytes
|
||||
*/
|
||||
updates.push_back(set_number_value(this->timeout_number_, this->two_byte_to_int_(buffer[32], buffer[33])));
|
||||
updates.push_back(set_number_value(this->timeout_number_, ld2410::two_byte_to_int(buffer[32], buffer[33])));
|
||||
for (auto &update : updates) {
|
||||
update();
|
||||
}
|
||||
@@ -505,14 +641,14 @@ void LD2410Component::set_bluetooth(bool enable) {
|
||||
|
||||
void LD2410Component::set_distance_resolution(const std::string &state) {
|
||||
this->set_config_mode_(true);
|
||||
uint8_t cmd_value[2] = {DISTANCE_RESOLUTION_ENUM_TO_INT.at(state), 0x00};
|
||||
uint8_t cmd_value[2] = {find_uint8(DISTANCE_RESOLUTIONS_BY_STR, state), 0x00};
|
||||
this->send_command_(CMD_SET_DISTANCE_RESOLUTION, cmd_value, 2);
|
||||
this->set_timeout(200, [this]() { this->restart_and_read_all_info(); });
|
||||
}
|
||||
|
||||
void LD2410Component::set_baud_rate(const std::string &state) {
|
||||
this->set_config_mode_(true);
|
||||
uint8_t cmd_value[2] = {BAUD_RATE_ENUM_TO_INT.at(state), 0x00};
|
||||
uint8_t cmd_value[2] = {find_uint8(BAUD_RATES_BY_STR, state), 0x00};
|
||||
this->send_command_(CMD_SET_BAUD_RATE, cmd_value, 2);
|
||||
this->set_timeout(200, [this]() { this->restart_(); });
|
||||
}
|
||||
@@ -646,9 +782,9 @@ void LD2410Component::set_light_out_control() {
|
||||
return;
|
||||
}
|
||||
this->set_config_mode_(true);
|
||||
uint8_t light_function = LIGHT_FUNCTION_ENUM_TO_INT.at(this->light_function_);
|
||||
uint8_t light_function = find_uint8(LIGHT_FUNCTIONS_BY_STR, this->light_function_);
|
||||
uint8_t light_threshold = static_cast<uint8_t>(this->light_threshold_);
|
||||
uint8_t out_pin_level = OUT_PIN_LEVEL_ENUM_TO_INT.at(this->out_pin_level_);
|
||||
uint8_t out_pin_level = find_uint8(OUT_PIN_LEVELS_BY_STR, this->out_pin_level_);
|
||||
uint8_t value[4] = {light_function, light_threshold, out_pin_level, 0x00};
|
||||
this->send_command_(CMD_SET_LIGHT_CONTROL, value, 4);
|
||||
delay(50); // NOLINT
|
||||
|
||||
@@ -26,114 +26,9 @@
|
||||
#include "esphome/core/automation.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
|
||||
#include <map>
|
||||
|
||||
namespace esphome {
|
||||
namespace ld2410 {
|
||||
|
||||
#define CHECK_BIT(var, pos) (((var) >> (pos)) & 1)
|
||||
|
||||
// Commands
|
||||
static const uint8_t CMD_ENABLE_CONF = 0x00FF;
|
||||
static const uint8_t CMD_DISABLE_CONF = 0x00FE;
|
||||
static const uint8_t CMD_ENABLE_ENG = 0x0062;
|
||||
static const uint8_t CMD_DISABLE_ENG = 0x0063;
|
||||
static const uint8_t CMD_MAXDIST_DURATION = 0x0060;
|
||||
static const uint8_t CMD_QUERY = 0x0061;
|
||||
static const uint8_t CMD_GATE_SENS = 0x0064;
|
||||
static const uint8_t CMD_VERSION = 0x00A0;
|
||||
static const uint8_t CMD_QUERY_DISTANCE_RESOLUTION = 0x00AB;
|
||||
static const uint8_t CMD_SET_DISTANCE_RESOLUTION = 0x00AA;
|
||||
static const uint8_t CMD_QUERY_LIGHT_CONTROL = 0x00AE;
|
||||
static const uint8_t CMD_SET_LIGHT_CONTROL = 0x00AD;
|
||||
static const uint8_t CMD_SET_BAUD_RATE = 0x00A1;
|
||||
static const uint8_t CMD_BT_PASSWORD = 0x00A9;
|
||||
static const uint8_t CMD_MAC = 0x00A5;
|
||||
static const uint8_t CMD_RESET = 0x00A2;
|
||||
static const uint8_t CMD_RESTART = 0x00A3;
|
||||
static const uint8_t CMD_BLUETOOTH = 0x00A4;
|
||||
|
||||
enum BaudRateStructure : uint8_t {
|
||||
BAUD_RATE_9600 = 1,
|
||||
BAUD_RATE_19200 = 2,
|
||||
BAUD_RATE_38400 = 3,
|
||||
BAUD_RATE_57600 = 4,
|
||||
BAUD_RATE_115200 = 5,
|
||||
BAUD_RATE_230400 = 6,
|
||||
BAUD_RATE_256000 = 7,
|
||||
BAUD_RATE_460800 = 8
|
||||
};
|
||||
|
||||
static const std::map<std::string, uint8_t> BAUD_RATE_ENUM_TO_INT{
|
||||
{"9600", BAUD_RATE_9600}, {"19200", BAUD_RATE_19200}, {"38400", BAUD_RATE_38400},
|
||||
{"57600", BAUD_RATE_57600}, {"115200", BAUD_RATE_115200}, {"230400", BAUD_RATE_230400},
|
||||
{"256000", BAUD_RATE_256000}, {"460800", BAUD_RATE_460800}};
|
||||
|
||||
enum DistanceResolutionStructure : uint8_t { DISTANCE_RESOLUTION_0_2 = 0x01, DISTANCE_RESOLUTION_0_75 = 0x00 };
|
||||
|
||||
static const std::map<std::string, uint8_t> DISTANCE_RESOLUTION_ENUM_TO_INT{{"0.2m", DISTANCE_RESOLUTION_0_2},
|
||||
{"0.75m", DISTANCE_RESOLUTION_0_75}};
|
||||
static const std::map<uint8_t, std::string> DISTANCE_RESOLUTION_INT_TO_ENUM{{DISTANCE_RESOLUTION_0_2, "0.2m"},
|
||||
{DISTANCE_RESOLUTION_0_75, "0.75m"}};
|
||||
|
||||
enum LightFunctionStructure : uint8_t {
|
||||
LIGHT_FUNCTION_OFF = 0x00,
|
||||
LIGHT_FUNCTION_BELOW = 0x01,
|
||||
LIGHT_FUNCTION_ABOVE = 0x02
|
||||
};
|
||||
|
||||
static const std::map<std::string, uint8_t> LIGHT_FUNCTION_ENUM_TO_INT{
|
||||
{"off", LIGHT_FUNCTION_OFF}, {"below", LIGHT_FUNCTION_BELOW}, {"above", LIGHT_FUNCTION_ABOVE}};
|
||||
static const std::map<uint8_t, std::string> LIGHT_FUNCTION_INT_TO_ENUM{
|
||||
{LIGHT_FUNCTION_OFF, "off"}, {LIGHT_FUNCTION_BELOW, "below"}, {LIGHT_FUNCTION_ABOVE, "above"}};
|
||||
|
||||
enum OutPinLevelStructure : uint8_t { OUT_PIN_LEVEL_LOW = 0x00, OUT_PIN_LEVEL_HIGH = 0x01 };
|
||||
|
||||
static const std::map<std::string, uint8_t> OUT_PIN_LEVEL_ENUM_TO_INT{{"low", OUT_PIN_LEVEL_LOW},
|
||||
{"high", OUT_PIN_LEVEL_HIGH}};
|
||||
static const std::map<uint8_t, std::string> OUT_PIN_LEVEL_INT_TO_ENUM{{OUT_PIN_LEVEL_LOW, "low"},
|
||||
{OUT_PIN_LEVEL_HIGH, "high"}};
|
||||
|
||||
// Commands values
|
||||
static const uint8_t CMD_MAX_MOVE_VALUE = 0x0000;
|
||||
static const uint8_t CMD_MAX_STILL_VALUE = 0x0001;
|
||||
static const uint8_t CMD_DURATION_VALUE = 0x0002;
|
||||
// Command Header & Footer
|
||||
static const uint8_t CMD_FRAME_HEADER[4] = {0xFD, 0xFC, 0xFB, 0xFA};
|
||||
static const uint8_t CMD_FRAME_END[4] = {0x04, 0x03, 0x02, 0x01};
|
||||
// Data Header & Footer
|
||||
static const uint8_t DATA_FRAME_HEADER[4] = {0xF4, 0xF3, 0xF2, 0xF1};
|
||||
static const uint8_t DATA_FRAME_END[4] = {0xF8, 0xF7, 0xF6, 0xF5};
|
||||
/*
|
||||
Data Type: 6th byte
|
||||
Target states: 9th byte
|
||||
Moving target distance: 10~11th bytes
|
||||
Moving target energy: 12th byte
|
||||
Still target distance: 13~14th bytes
|
||||
Still target energy: 15th byte
|
||||
Detect distance: 16~17th bytes
|
||||
*/
|
||||
enum PeriodicDataStructure : uint8_t {
|
||||
DATA_TYPES = 6,
|
||||
TARGET_STATES = 8,
|
||||
MOVING_TARGET_LOW = 9,
|
||||
MOVING_TARGET_HIGH = 10,
|
||||
MOVING_ENERGY = 11,
|
||||
STILL_TARGET_LOW = 12,
|
||||
STILL_TARGET_HIGH = 13,
|
||||
STILL_ENERGY = 14,
|
||||
DETECT_DISTANCE_LOW = 15,
|
||||
DETECT_DISTANCE_HIGH = 16,
|
||||
MOVING_SENSOR_START = 19,
|
||||
STILL_SENSOR_START = 28,
|
||||
LIGHT_SENSOR = 37,
|
||||
OUT_PIN_SENSOR = 38,
|
||||
};
|
||||
enum PeriodicDataValue : uint8_t { HEAD = 0xAA, END = 0x55, CHECK = 0x00 };
|
||||
|
||||
enum AckDataStructure : uint8_t { COMMAND = 6, COMMAND_STATUS = 7 };
|
||||
|
||||
// char cmd[2] = {enable ? 0xFF : 0xFE, 0x00};
|
||||
class LD2410Component : public Component, public uart::UARTDevice {
|
||||
#ifdef USE_SENSOR
|
||||
SUB_SENSOR(moving_target_distance)
|
||||
@@ -176,7 +71,6 @@ class LD2410Component : public Component, public uart::UARTDevice {
|
||||
#endif
|
||||
|
||||
public:
|
||||
LD2410Component();
|
||||
void setup() override;
|
||||
void dump_config() override;
|
||||
void loop() override;
|
||||
@@ -202,7 +96,6 @@ class LD2410Component : public Component, public uart::UARTDevice {
|
||||
void factory_reset();
|
||||
|
||||
protected:
|
||||
int two_byte_to_int_(char firstbyte, char secondbyte) { return (int16_t) (secondbyte << 8) + firstbyte; }
|
||||
void send_command_(uint8_t command_str, const uint8_t *command_value, int command_value_len);
|
||||
void set_config_mode_(bool enable);
|
||||
void handle_periodic_data_(uint8_t *buffer, int len);
|
||||
@@ -215,14 +108,14 @@ class LD2410Component : public Component, public uart::UARTDevice {
|
||||
void get_light_control_();
|
||||
void restart_();
|
||||
|
||||
int32_t last_periodic_millis_ = millis();
|
||||
int32_t last_engineering_mode_change_millis_ = millis();
|
||||
int32_t last_periodic_millis_ = 0;
|
||||
int32_t last_engineering_mode_change_millis_ = 0;
|
||||
uint16_t throttle_;
|
||||
float light_threshold_ = -1;
|
||||
std::string version_;
|
||||
std::string mac_;
|
||||
std::string out_pin_level_;
|
||||
std::string light_function_;
|
||||
float light_threshold_ = -1;
|
||||
#ifdef USE_NUMBER
|
||||
std::vector<number::Number *> gate_still_threshold_numbers_ = std::vector<number::Number *>(9);
|
||||
std::vector<number::Number *> gate_move_threshold_numbers_ = std::vector<number::Number *>(9);
|
||||
|
||||
@@ -21,20 +21,105 @@ static const char *const NO_MAC = "08:05:04:03:02:01";
|
||||
static const char *const UNKNOWN_MAC = "unknown";
|
||||
static const char *const VERSION_FMT = "%u.%02X.%02X%02X%02X%02X";
|
||||
|
||||
enum BaudRateStructure : uint8_t {
|
||||
BAUD_RATE_9600 = 1,
|
||||
BAUD_RATE_19200 = 2,
|
||||
BAUD_RATE_38400 = 3,
|
||||
BAUD_RATE_57600 = 4,
|
||||
BAUD_RATE_115200 = 5,
|
||||
BAUD_RATE_230400 = 6,
|
||||
BAUD_RATE_256000 = 7,
|
||||
BAUD_RATE_460800 = 8
|
||||
};
|
||||
|
||||
// Zone type struct
|
||||
enum ZoneTypeStructure : uint8_t {
|
||||
ZONE_DISABLED = 0,
|
||||
ZONE_DETECTION = 1,
|
||||
ZONE_FILTER = 2,
|
||||
};
|
||||
|
||||
enum PeriodicDataStructure : uint8_t {
|
||||
TARGET_X = 4,
|
||||
TARGET_Y = 6,
|
||||
TARGET_SPEED = 8,
|
||||
TARGET_RESOLUTION = 10,
|
||||
};
|
||||
|
||||
enum PeriodicDataValue : uint8_t {
|
||||
HEAD = 0xAA,
|
||||
END = 0x55,
|
||||
CHECK = 0x00,
|
||||
};
|
||||
|
||||
enum AckDataStructure : uint8_t {
|
||||
COMMAND = 6,
|
||||
COMMAND_STATUS = 7,
|
||||
};
|
||||
|
||||
// Memory-efficient lookup tables
|
||||
struct StringToUint8 {
|
||||
const char *str;
|
||||
uint8_t value;
|
||||
};
|
||||
|
||||
struct Uint8ToString {
|
||||
uint8_t value;
|
||||
const char *str;
|
||||
};
|
||||
|
||||
constexpr StringToUint8 BAUD_RATES_BY_STR[] = {
|
||||
{"9600", BAUD_RATE_9600}, {"19200", BAUD_RATE_19200}, {"38400", BAUD_RATE_38400},
|
||||
{"57600", BAUD_RATE_57600}, {"115200", BAUD_RATE_115200}, {"230400", BAUD_RATE_230400},
|
||||
{"256000", BAUD_RATE_256000}, {"460800", BAUD_RATE_460800},
|
||||
};
|
||||
|
||||
constexpr Uint8ToString ZONE_TYPE_BY_UINT[] = {
|
||||
{ZONE_DISABLED, "Disabled"},
|
||||
{ZONE_DETECTION, "Detection"},
|
||||
{ZONE_FILTER, "Filter"},
|
||||
};
|
||||
|
||||
constexpr StringToUint8 ZONE_TYPE_BY_STR[] = {
|
||||
{"Disabled", ZONE_DISABLED},
|
||||
{"Detection", ZONE_DETECTION},
|
||||
{"Filter", ZONE_FILTER},
|
||||
};
|
||||
|
||||
// Helper functions for lookups
|
||||
template<size_t N> uint8_t find_uint8(const StringToUint8 (&arr)[N], const std::string &str) {
|
||||
for (const auto &entry : arr) {
|
||||
if (str == entry.str)
|
||||
return entry.value;
|
||||
}
|
||||
return 0xFF; // Not found
|
||||
}
|
||||
|
||||
template<size_t N> const char *find_str(const Uint8ToString (&arr)[N], uint8_t value) {
|
||||
for (const auto &entry : arr) {
|
||||
if (value == entry.value)
|
||||
return entry.str;
|
||||
}
|
||||
return ""; // Not found
|
||||
}
|
||||
|
||||
// LD2450 serial command header & footer
|
||||
static const uint8_t CMD_FRAME_HEADER[4] = {0xFD, 0xFC, 0xFB, 0xFA};
|
||||
static const uint8_t CMD_FRAME_END[4] = {0x04, 0x03, 0x02, 0x01};
|
||||
// LD2450 UART Serial Commands
|
||||
static const uint8_t CMD_ENABLE_CONF = 0x00FF;
|
||||
static const uint8_t CMD_DISABLE_CONF = 0x00FE;
|
||||
static const uint8_t CMD_VERSION = 0x00A0;
|
||||
static const uint8_t CMD_MAC = 0x00A5;
|
||||
static const uint8_t CMD_RESET = 0x00A2;
|
||||
static const uint8_t CMD_RESTART = 0x00A3;
|
||||
static const uint8_t CMD_BLUETOOTH = 0x00A4;
|
||||
static const uint8_t CMD_SINGLE_TARGET_MODE = 0x0080;
|
||||
static const uint8_t CMD_MULTI_TARGET_MODE = 0x0090;
|
||||
static const uint8_t CMD_QUERY_TARGET_MODE = 0x0091;
|
||||
static const uint8_t CMD_SET_BAUD_RATE = 0x00A1;
|
||||
static const uint8_t CMD_QUERY_ZONE = 0x00C1;
|
||||
static const uint8_t CMD_SET_ZONE = 0x00C2;
|
||||
static const uint8_t CMD_ENABLE_CONF = 0xFF;
|
||||
static const uint8_t CMD_DISABLE_CONF = 0xFE;
|
||||
static const uint8_t CMD_VERSION = 0xA0;
|
||||
static const uint8_t CMD_MAC = 0xA5;
|
||||
static const uint8_t CMD_RESET = 0xA2;
|
||||
static const uint8_t CMD_RESTART = 0xA3;
|
||||
static const uint8_t CMD_BLUETOOTH = 0xA4;
|
||||
static const uint8_t CMD_SINGLE_TARGET_MODE = 0x80;
|
||||
static const uint8_t CMD_MULTI_TARGET_MODE = 0x90;
|
||||
static const uint8_t CMD_QUERY_TARGET_MODE = 0x91;
|
||||
static const uint8_t CMD_SET_BAUD_RATE = 0xA1;
|
||||
static const uint8_t CMD_QUERY_ZONE = 0xC1;
|
||||
static const uint8_t CMD_SET_ZONE = 0xC2;
|
||||
|
||||
static inline uint16_t convert_seconds_to_ms(uint16_t value) { return value * 1000; };
|
||||
|
||||
@@ -720,7 +805,7 @@ void LD2450Component::set_bluetooth(bool enable) {
|
||||
// Set Baud rate
|
||||
void LD2450Component::set_baud_rate(const std::string &state) {
|
||||
this->set_config_mode_(true);
|
||||
uint8_t cmd_value[2] = {BAUD_RATE_ENUM_TO_INT.at(state), 0x00};
|
||||
uint8_t cmd_value[2] = {find_uint8(BAUD_RATES_BY_STR, state), 0x00};
|
||||
this->send_command_(CMD_SET_BAUD_RATE, cmd_value, 2);
|
||||
this->set_timeout(200, [this]() { this->restart_(); });
|
||||
}
|
||||
@@ -728,7 +813,7 @@ void LD2450Component::set_baud_rate(const std::string &state) {
|
||||
// Set Zone Type - one of: Disabled, Detection, Filter
|
||||
void LD2450Component::set_zone_type(const std::string &state) {
|
||||
ESP_LOGV(TAG, "Set zone type: %s", state.c_str());
|
||||
uint8_t zone_type = ZONE_TYPE_ENUM_TO_INT.at(state);
|
||||
uint8_t zone_type = find_uint8(ZONE_TYPE_BY_STR, state);
|
||||
this->zone_type_ = zone_type;
|
||||
this->send_set_zone_command_();
|
||||
}
|
||||
@@ -736,7 +821,7 @@ void LD2450Component::set_zone_type(const std::string &state) {
|
||||
// Publish Zone Type to Select component
|
||||
void LD2450Component::publish_zone_type() {
|
||||
#ifdef USE_SELECT
|
||||
std::string zone_type = ZONE_TYPE_INT_TO_ENUM.at(static_cast<ZoneTypeStructure>(this->zone_type_));
|
||||
std::string zone_type = find_str(ZONE_TYPE_BY_UINT, this->zone_type_);
|
||||
if (this->zone_type_select_ != nullptr) {
|
||||
this->zone_type_select_->publish_state(zone_type);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
#pragma once
|
||||
|
||||
#include <iomanip>
|
||||
#include <map>
|
||||
#include "esphome/components/uart/uart.h"
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/defines.h"
|
||||
@@ -66,49 +64,6 @@ struct ZoneOfNumbers {
|
||||
};
|
||||
#endif
|
||||
|
||||
enum BaudRateStructure : uint8_t {
|
||||
BAUD_RATE_9600 = 1,
|
||||
BAUD_RATE_19200 = 2,
|
||||
BAUD_RATE_38400 = 3,
|
||||
BAUD_RATE_57600 = 4,
|
||||
BAUD_RATE_115200 = 5,
|
||||
BAUD_RATE_230400 = 6,
|
||||
BAUD_RATE_256000 = 7,
|
||||
BAUD_RATE_460800 = 8
|
||||
};
|
||||
|
||||
// Convert baud rate enum to int
|
||||
static const std::map<std::string, uint8_t> BAUD_RATE_ENUM_TO_INT{
|
||||
{"9600", BAUD_RATE_9600}, {"19200", BAUD_RATE_19200}, {"38400", BAUD_RATE_38400},
|
||||
{"57600", BAUD_RATE_57600}, {"115200", BAUD_RATE_115200}, {"230400", BAUD_RATE_230400},
|
||||
{"256000", BAUD_RATE_256000}, {"460800", BAUD_RATE_460800}};
|
||||
|
||||
// Zone type struct
|
||||
enum ZoneTypeStructure : uint8_t { ZONE_DISABLED = 0, ZONE_DETECTION = 1, ZONE_FILTER = 2 };
|
||||
|
||||
// Convert zone type int to enum
|
||||
static const std::map<ZoneTypeStructure, std::string> ZONE_TYPE_INT_TO_ENUM{
|
||||
{ZONE_DISABLED, "Disabled"}, {ZONE_DETECTION, "Detection"}, {ZONE_FILTER, "Filter"}};
|
||||
|
||||
// Convert zone type enum to int
|
||||
static const std::map<std::string, uint8_t> ZONE_TYPE_ENUM_TO_INT{
|
||||
{"Disabled", ZONE_DISABLED}, {"Detection", ZONE_DETECTION}, {"Filter", ZONE_FILTER}};
|
||||
|
||||
// LD2450 serial command header & footer
|
||||
static const uint8_t CMD_FRAME_HEADER[4] = {0xFD, 0xFC, 0xFB, 0xFA};
|
||||
static const uint8_t CMD_FRAME_END[4] = {0x04, 0x03, 0x02, 0x01};
|
||||
|
||||
enum PeriodicDataStructure : uint8_t {
|
||||
TARGET_X = 4,
|
||||
TARGET_Y = 6,
|
||||
TARGET_SPEED = 8,
|
||||
TARGET_RESOLUTION = 10,
|
||||
};
|
||||
|
||||
enum PeriodicDataValue : uint8_t { HEAD = 0xAA, END = 0x55, CHECK = 0x00 };
|
||||
|
||||
enum AckDataStructure : uint8_t { COMMAND = 6, COMMAND_STATUS = 7 };
|
||||
|
||||
class LD2450Component : public Component, public uart::UARTDevice {
|
||||
#ifdef USE_SENSOR
|
||||
SUB_SENSOR(target_count)
|
||||
|
||||
@@ -264,7 +264,7 @@ async def component_to_code(config):
|
||||
# force using arduino framework
|
||||
cg.add_platformio_option("framework", "arduino")
|
||||
cg.add_build_flag("-DUSE_ARDUINO")
|
||||
cg.set_cpp_standard("gnu++17")
|
||||
cg.set_cpp_standard("gnu++20")
|
||||
|
||||
# disable library compatibility checks
|
||||
cg.add_platformio_option("lib_ldf_mode", "off")
|
||||
|
||||
@@ -10,9 +10,11 @@ namespace libretiny {
|
||||
static const char *const TAG = "lt.component";
|
||||
|
||||
void LTComponent::dump_config() {
|
||||
ESP_LOGCONFIG(TAG, "LibreTiny:");
|
||||
ESP_LOGCONFIG(TAG, " Version: %s", LT_BANNER_STR + 10);
|
||||
ESP_LOGCONFIG(TAG, " Loglevel: %u", LT_LOGLEVEL);
|
||||
ESP_LOGCONFIG(TAG,
|
||||
"LibreTiny:\n"
|
||||
" Version: %s\n"
|
||||
" Loglevel: %u",
|
||||
LT_BANNER_STR + 10, LT_LOGLEVEL);
|
||||
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
if (this->version_ != nullptr) {
|
||||
|
||||
@@ -6,7 +6,11 @@ namespace mcp23xxx_base {
|
||||
|
||||
float MCP23XXXBase::get_setup_priority() const { return setup_priority::IO; }
|
||||
|
||||
void MCP23XXXGPIOPin::setup() { pin_mode(flags_); }
|
||||
void MCP23XXXGPIOPin::setup() {
|
||||
pin_mode(flags_);
|
||||
this->parent_->pin_interrupt_mode(this->pin_, this->interrupt_mode_);
|
||||
}
|
||||
|
||||
void MCP23XXXGPIOPin::pin_mode(gpio::Flags flags) { this->parent_->pin_mode(this->pin_, flags); }
|
||||
bool MCP23XXXGPIOPin::digital_read() { return this->parent_->digital_read(this->pin_) != this->inverted_; }
|
||||
void MCP23XXXGPIOPin::digital_write(bool value) { this->parent_->digital_write(this->pin_, value != this->inverted_); }
|
||||
|
||||
@@ -88,12 +88,7 @@ async def to_code(config):
|
||||
if CORE.using_esp_idf and CORE.data[KEY_CORE][KEY_FRAMEWORK_VERSION] >= cv.Version(
|
||||
5, 0, 0
|
||||
):
|
||||
add_idf_component(
|
||||
name="mdns",
|
||||
repo="https://github.com/espressif/esp-protocols.git",
|
||||
ref="mdns-v1.8.2",
|
||||
path="components/mdns",
|
||||
)
|
||||
add_idf_component(name="espressif/mdns", ref="1.8.2")
|
||||
|
||||
cg.add_define("USE_MDNS")
|
||||
|
||||
|
||||
@@ -449,11 +449,7 @@ async def to_code(config):
|
||||
cg.add_define("USE_MICRO_WAKE_WORD")
|
||||
cg.add_define("USE_OTA_STATE_CALLBACK")
|
||||
|
||||
esp32.add_idf_component(
|
||||
name="esp-tflite-micro",
|
||||
repo="https://github.com/espressif/esp-tflite-micro",
|
||||
ref="v1.3.3.1",
|
||||
)
|
||||
esp32.add_idf_component(name="espressif/esp-tflite-micro", ref="1.3.3~1")
|
||||
|
||||
cg.add_build_flag("-DTF_LITE_STATIC_MEMORY")
|
||||
cg.add_build_flag("-DTF_LITE_DISABLE_X86_NEON")
|
||||
|
||||
@@ -344,7 +344,7 @@ void OnlineImage::end_connection_() {
|
||||
}
|
||||
|
||||
bool OnlineImage::validate_url_(const std::string &url) {
|
||||
if ((url.length() < 8) || (url.find("http") != 0) || (url.find("://") == std::string::npos)) {
|
||||
if ((url.length() < 8) || !url.starts_with("http") || (url.find("://") == std::string::npos)) {
|
||||
ESP_LOGE(TAG, "URL is invalid and/or must be prefixed with 'http://' or 'https://'");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -584,7 +584,7 @@ void PN7150::nci_fsm_transition_() {
|
||||
} else {
|
||||
this->nci_fsm_set_state_(NCIState::NFCC_INIT);
|
||||
}
|
||||
// fall through
|
||||
[[fallthrough]];
|
||||
|
||||
case NCIState::NFCC_INIT:
|
||||
if (this->init_core_() != nfc::STATUS_OK) {
|
||||
@@ -594,7 +594,7 @@ void PN7150::nci_fsm_transition_() {
|
||||
} else {
|
||||
this->nci_fsm_set_state_(NCIState::NFCC_CONFIG);
|
||||
}
|
||||
// fall through
|
||||
[[fallthrough]];
|
||||
|
||||
case NCIState::NFCC_CONFIG:
|
||||
if (this->send_init_config_() != nfc::STATUS_OK) {
|
||||
@@ -605,7 +605,7 @@ void PN7150::nci_fsm_transition_() {
|
||||
this->config_refresh_pending_ = false;
|
||||
this->nci_fsm_set_state_(NCIState::NFCC_SET_DISCOVER_MAP);
|
||||
}
|
||||
// fall through
|
||||
[[fallthrough]];
|
||||
|
||||
case NCIState::NFCC_SET_DISCOVER_MAP:
|
||||
if (this->set_discover_map_() != nfc::STATUS_OK) {
|
||||
@@ -615,7 +615,7 @@ void PN7150::nci_fsm_transition_() {
|
||||
} else {
|
||||
this->nci_fsm_set_state_(NCIState::NFCC_SET_LISTEN_MODE_ROUTING);
|
||||
}
|
||||
// fall through
|
||||
[[fallthrough]];
|
||||
|
||||
case NCIState::NFCC_SET_LISTEN_MODE_ROUTING:
|
||||
if (this->set_listen_mode_routing_() != nfc::STATUS_OK) {
|
||||
@@ -625,7 +625,7 @@ void PN7150::nci_fsm_transition_() {
|
||||
} else {
|
||||
this->nci_fsm_set_state_(NCIState::RFST_IDLE);
|
||||
}
|
||||
// fall through
|
||||
[[fallthrough]];
|
||||
|
||||
case NCIState::RFST_IDLE:
|
||||
if (this->nci_state_error_ == NCIState::RFST_DISCOVERY) {
|
||||
@@ -650,14 +650,14 @@ void PN7150::nci_fsm_transition_() {
|
||||
|
||||
case NCIState::RFST_W4_HOST_SELECT:
|
||||
select_endpoint_();
|
||||
// fall through
|
||||
[[fallthrough]];
|
||||
|
||||
// All cases below are waiting for NOTIFICATION messages
|
||||
case NCIState::RFST_DISCOVERY:
|
||||
if (this->config_refresh_pending_) {
|
||||
this->refresh_core_config_();
|
||||
}
|
||||
// fall through
|
||||
[[fallthrough]];
|
||||
|
||||
case NCIState::RFST_LISTEN_ACTIVE:
|
||||
case NCIState::RFST_LISTEN_SLEEP:
|
||||
|
||||
@@ -609,7 +609,7 @@ void PN7160::nci_fsm_transition_() {
|
||||
} else {
|
||||
this->nci_fsm_set_state_(NCIState::NFCC_INIT);
|
||||
}
|
||||
// fall through
|
||||
[[fallthrough]];
|
||||
|
||||
case NCIState::NFCC_INIT:
|
||||
if (this->init_core_() != nfc::STATUS_OK) {
|
||||
@@ -619,7 +619,7 @@ void PN7160::nci_fsm_transition_() {
|
||||
} else {
|
||||
this->nci_fsm_set_state_(NCIState::NFCC_CONFIG);
|
||||
}
|
||||
// fall through
|
||||
[[fallthrough]];
|
||||
|
||||
case NCIState::NFCC_CONFIG:
|
||||
if (this->send_init_config_() != nfc::STATUS_OK) {
|
||||
@@ -630,7 +630,7 @@ void PN7160::nci_fsm_transition_() {
|
||||
this->config_refresh_pending_ = false;
|
||||
this->nci_fsm_set_state_(NCIState::NFCC_SET_DISCOVER_MAP);
|
||||
}
|
||||
// fall through
|
||||
[[fallthrough]];
|
||||
|
||||
case NCIState::NFCC_SET_DISCOVER_MAP:
|
||||
if (this->set_discover_map_() != nfc::STATUS_OK) {
|
||||
@@ -640,7 +640,7 @@ void PN7160::nci_fsm_transition_() {
|
||||
} else {
|
||||
this->nci_fsm_set_state_(NCIState::NFCC_SET_LISTEN_MODE_ROUTING);
|
||||
}
|
||||
// fall through
|
||||
[[fallthrough]];
|
||||
|
||||
case NCIState::NFCC_SET_LISTEN_MODE_ROUTING:
|
||||
if (this->set_listen_mode_routing_() != nfc::STATUS_OK) {
|
||||
@@ -650,7 +650,7 @@ void PN7160::nci_fsm_transition_() {
|
||||
} else {
|
||||
this->nci_fsm_set_state_(NCIState::RFST_IDLE);
|
||||
}
|
||||
// fall through
|
||||
[[fallthrough]];
|
||||
|
||||
case NCIState::RFST_IDLE:
|
||||
if (this->nci_state_error_ == NCIState::RFST_DISCOVERY) {
|
||||
@@ -675,14 +675,14 @@ void PN7160::nci_fsm_transition_() {
|
||||
|
||||
case NCIState::RFST_W4_HOST_SELECT:
|
||||
select_endpoint_();
|
||||
// fall through
|
||||
[[fallthrough]];
|
||||
|
||||
// All cases below are waiting for NOTIFICATION messages
|
||||
case NCIState::RFST_DISCOVERY:
|
||||
if (this->config_refresh_pending_) {
|
||||
this->refresh_core_config_();
|
||||
}
|
||||
// fall through
|
||||
[[fallthrough]];
|
||||
|
||||
case NCIState::RFST_LISTEN_ACTIVE:
|
||||
case NCIState::RFST_LISTEN_SLEEP:
|
||||
|
||||
@@ -63,7 +63,7 @@ void PulseMeterSensor::loop() {
|
||||
// If an edge was peeked, repay the debt
|
||||
if (this->peeked_edge_ && this->get_->count_ > 0) {
|
||||
this->peeked_edge_ = false;
|
||||
this->get_->count_--;
|
||||
this->get_->count_--; // NOLINT(clang-diagnostic-deprecated-volatile)
|
||||
}
|
||||
|
||||
// If there is an unprocessed edge, and filter_us_ has passed since, count this edge early
|
||||
@@ -71,7 +71,7 @@ void PulseMeterSensor::loop() {
|
||||
now - this->get_->last_rising_edge_us_ >= this->filter_us_) {
|
||||
this->peeked_edge_ = true;
|
||||
this->get_->last_detected_edge_us_ = this->get_->last_rising_edge_us_;
|
||||
this->get_->count_++;
|
||||
this->get_->count_++; // NOLINT(clang-diagnostic-deprecated-volatile)
|
||||
}
|
||||
|
||||
// Check if we detected a pulse this loop
|
||||
@@ -146,7 +146,7 @@ void IRAM_ATTR PulseMeterSensor::edge_intr(PulseMeterSensor *sensor) {
|
||||
state.last_sent_edge_us_ = now;
|
||||
set.last_detected_edge_us_ = now;
|
||||
set.last_rising_edge_us_ = now;
|
||||
set.count_++;
|
||||
set.count_++; // NOLINT(clang-diagnostic-deprecated-volatile)
|
||||
}
|
||||
|
||||
// This ISR is bound to rising edges, so the pin is high
|
||||
@@ -169,7 +169,7 @@ void IRAM_ATTR PulseMeterSensor::pulse_intr(PulseMeterSensor *sensor) {
|
||||
} else if (length && !state.latched_ && sensor->last_pin_val_) { // Long enough high edge
|
||||
state.latched_ = true;
|
||||
set.last_detected_edge_us_ = state.last_intr_;
|
||||
set.count_++;
|
||||
set.count_++; // NOLINT(clang-diagnostic-deprecated-volatile)
|
||||
}
|
||||
|
||||
// Due to order of operations this includes
|
||||
|
||||
@@ -17,7 +17,7 @@ bool RadonEyeListener::parse_device(const esp32_ble_tracker::ESPBTDevice &device
|
||||
|
||||
// Check if the device name starts with any of the prefixes
|
||||
if (std::any_of(prefixes.begin(), prefixes.end(),
|
||||
[&](const std::string &prefix) { return device.get_name().rfind(prefix, 0) == 0; })) {
|
||||
[&](const std::string &prefix) { return device.get_name().starts_with(prefix); })) {
|
||||
// Device found
|
||||
ESP_LOGD(TAG, "Found Radon Eye device Name: %s (MAC: %s)", device.get_name().c_str(),
|
||||
device.address_str().c_str());
|
||||
|
||||
@@ -27,7 +27,7 @@ void IRAM_ATTR HOT RemoteReceiverComponentStore::gpio_intr(RemoteReceiverCompone
|
||||
if (time_since_change <= arg->filter_us)
|
||||
return;
|
||||
|
||||
arg->buffer[arg->buffer_write_at = next] = now;
|
||||
arg->buffer[arg->buffer_write_at = next] = now; // NOLINT(clang-diagnostic-deprecated-volatile)
|
||||
}
|
||||
|
||||
void RemoteReceiverComponent::setup() {
|
||||
|
||||
@@ -167,7 +167,7 @@ async def to_code(config):
|
||||
cg.add_platformio_option("lib_ldf_mode", "chain+")
|
||||
cg.add_platformio_option("board", config[CONF_BOARD])
|
||||
cg.add_build_flag("-DUSE_RP2040")
|
||||
cg.set_cpp_standard("gnu++17")
|
||||
cg.set_cpp_standard("gnu++20")
|
||||
cg.add_define("ESPHOME_BOARD", config[CONF_BOARD])
|
||||
cg.add_define("ESPHOME_VARIANT", "RP2040")
|
||||
|
||||
|
||||
26
esphome/components/runtime_stats/__init__.py
Normal file
26
esphome/components/runtime_stats/__init__.py
Normal file
@@ -0,0 +1,26 @@
|
||||
"""
|
||||
Runtime statistics component for ESPHome.
|
||||
"""
|
||||
|
||||
import esphome.codegen as cg
|
||||
import esphome.config_validation as cv
|
||||
|
||||
DEPENDENCIES = []
|
||||
|
||||
CONF_ENABLED = "enabled"
|
||||
CONF_LOG_INTERVAL = "log_interval"
|
||||
|
||||
CONFIG_SCHEMA = cv.Schema(
|
||||
{
|
||||
cv.Optional(CONF_ENABLED, default=True): cv.boolean,
|
||||
cv.Optional(
|
||||
CONF_LOG_INTERVAL, default=60000
|
||||
): cv.positive_time_period_milliseconds,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config):
|
||||
"""Generate code for the runtime statistics component."""
|
||||
cg.add(cg.App.set_runtime_stats_enabled(config[CONF_ENABLED]))
|
||||
cg.add(cg.App.set_runtime_stats_log_interval(config[CONF_LOG_INTERVAL]))
|
||||
@@ -33,12 +33,15 @@ class SafeModeComponent : public Component {
|
||||
void write_rtc_(uint32_t val);
|
||||
uint32_t read_rtc_();
|
||||
|
||||
bool boot_successful_{false}; ///< set to true after boot is considered successful
|
||||
// Group all 4-byte aligned members together to avoid padding
|
||||
uint32_t safe_mode_boot_is_good_after_{60000}; ///< The amount of time after which the boot is considered successful
|
||||
uint32_t safe_mode_enable_time_{60000}; ///< The time safe mode should remain active for
|
||||
uint32_t safe_mode_rtc_value_{0};
|
||||
uint32_t safe_mode_start_time_{0}; ///< stores when safe mode was enabled
|
||||
// Group 1-byte members together to minimize padding
|
||||
bool boot_successful_{false}; ///< set to true after boot is considered successful
|
||||
uint8_t safe_mode_num_attempts_{0};
|
||||
// Larger objects at the end
|
||||
ESPPreferenceObject rtc_;
|
||||
CallbackManager<void()> safe_mode_callback_{};
|
||||
|
||||
|
||||
@@ -445,8 +445,7 @@ template<typename T> stm32_err_t stm32_check_ack_timeout(const stm32_err_t s_err
|
||||
return STM32_ERR_OK;
|
||||
case STM32_ERR_NACK:
|
||||
log();
|
||||
// TODO: c++17 [[fallthrough]]
|
||||
/* fallthrough */
|
||||
[[fallthrough]];
|
||||
default:
|
||||
return STM32_ERR_UNKNOWN;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "sn74hc595.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include <ranges>
|
||||
|
||||
namespace esphome {
|
||||
namespace sn74hc595 {
|
||||
@@ -55,9 +56,9 @@ void SN74HC595Component::digital_write_(uint16_t pin, bool value) {
|
||||
}
|
||||
|
||||
void SN74HC595GPIOComponent::write_gpio() {
|
||||
for (auto byte = this->output_bytes_.rbegin(); byte != this->output_bytes_.rend(); byte++) {
|
||||
for (uint8_t &output_byte : std::ranges::reverse_view(this->output_bytes_)) {
|
||||
for (int8_t i = 7; i >= 0; i--) {
|
||||
bool bit = (*byte >> i) & 1;
|
||||
bool bit = (output_byte >> i) & 1;
|
||||
this->data_pin_->digital_write(bit);
|
||||
this->clock_pin_->digital_write(true);
|
||||
this->clock_pin_->digital_write(false);
|
||||
@@ -68,9 +69,9 @@ void SN74HC595GPIOComponent::write_gpio() {
|
||||
|
||||
#ifdef USE_SPI
|
||||
void SN74HC595SPIComponent::write_gpio() {
|
||||
for (auto byte = this->output_bytes_.rbegin(); byte != this->output_bytes_.rend(); byte++) {
|
||||
for (uint8_t &output_byte : std::ranges::reverse_view(this->output_bytes_)) {
|
||||
this->enable();
|
||||
this->transfer_byte(*byte);
|
||||
this->transfer_byte(output_byte);
|
||||
this->disable();
|
||||
}
|
||||
SN74HC595Component::write_gpio();
|
||||
|
||||
@@ -343,13 +343,12 @@ void AudioPipeline::read_task(void *params) {
|
||||
xEventGroupSetBits(this_pipeline->event_group_, EventGroupBits::READER_MESSAGE_FINISHED);
|
||||
|
||||
// Wait until the pipeline notifies us the source of the media file
|
||||
EventBits_t event_bits =
|
||||
xEventGroupWaitBits(this_pipeline->event_group_,
|
||||
EventGroupBits::READER_COMMAND_INIT_FILE | EventGroupBits::READER_COMMAND_INIT_HTTP |
|
||||
EventGroupBits::PIPELINE_COMMAND_STOP, // Bit message to read
|
||||
pdFALSE, // Clear the bit on exit
|
||||
pdFALSE, // Wait for all the bits,
|
||||
portMAX_DELAY); // Block indefinitely until bit is set
|
||||
EventBits_t event_bits = xEventGroupWaitBits(
|
||||
this_pipeline->event_group_,
|
||||
EventGroupBits::READER_COMMAND_INIT_FILE | EventGroupBits::READER_COMMAND_INIT_HTTP, // Bit message to read
|
||||
pdFALSE, // Clear the bit on exit
|
||||
pdFALSE, // Wait for all the bits,
|
||||
portMAX_DELAY); // Block indefinitely until bit is set
|
||||
|
||||
if (!(event_bits & EventGroupBits::PIPELINE_COMMAND_STOP)) {
|
||||
xEventGroupClearBits(this_pipeline->event_group_, EventGroupBits::READER_MESSAGE_FINISHED |
|
||||
@@ -434,12 +433,12 @@ void AudioPipeline::decode_task(void *params) {
|
||||
xEventGroupSetBits(this_pipeline->event_group_, EventGroupBits::DECODER_MESSAGE_FINISHED);
|
||||
|
||||
// Wait until the reader notifies us that the media type is available
|
||||
EventBits_t event_bits = xEventGroupWaitBits(this_pipeline->event_group_,
|
||||
EventGroupBits::READER_MESSAGE_LOADED_MEDIA_TYPE |
|
||||
EventGroupBits::PIPELINE_COMMAND_STOP, // Bit message to read
|
||||
pdFALSE, // Clear the bit on exit
|
||||
pdFALSE, // Wait for all the bits,
|
||||
portMAX_DELAY); // Block indefinitely until bit is set
|
||||
EventBits_t event_bits =
|
||||
xEventGroupWaitBits(this_pipeline->event_group_,
|
||||
EventGroupBits::READER_MESSAGE_LOADED_MEDIA_TYPE, // Bit message to read
|
||||
pdFALSE, // Clear the bit on exit
|
||||
pdFALSE, // Wait for all the bits,
|
||||
portMAX_DELAY); // Block indefinitely until bit is set
|
||||
|
||||
xEventGroupClearBits(this_pipeline->event_group_,
|
||||
EventGroupBits::DECODER_MESSAGE_FINISHED | EventGroupBits::READER_MESSAGE_LOADED_MEDIA_TYPE);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "sun.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include <numbers>
|
||||
|
||||
/*
|
||||
The formulas/algorithms in this module are based on the book
|
||||
@@ -18,14 +19,12 @@ using namespace esphome::sun::internal;
|
||||
|
||||
static const char *const TAG = "sun";
|
||||
|
||||
#undef PI
|
||||
#undef degrees
|
||||
#undef radians
|
||||
#undef sq
|
||||
|
||||
static const num_t PI = 3.141592653589793;
|
||||
inline num_t degrees(num_t rad) { return rad * 180 / PI; }
|
||||
inline num_t radians(num_t deg) { return deg * PI / 180; }
|
||||
inline num_t degrees(num_t rad) { return rad * 180 / std::numbers::pi; }
|
||||
inline num_t radians(num_t deg) { return deg * std::numbers::pi / 180; }
|
||||
inline num_t arcdeg(num_t deg, num_t minutes, num_t seconds) { return deg + minutes / 60 + seconds / 3600; }
|
||||
inline num_t sq(num_t x) { return x * x; }
|
||||
inline num_t cb(num_t x) { return x * x * x; }
|
||||
|
||||
@@ -152,7 +152,7 @@ void IRAM_ATTR Tx20ComponentStore::gpio_intr(Tx20ComponentStore *arg) {
|
||||
}
|
||||
arg->buffer[arg->buffer_index] = 1;
|
||||
arg->start_time = now;
|
||||
arg->buffer_index++;
|
||||
arg->buffer_index++; // NOLINT(clang-diagnostic-deprecated-volatile)
|
||||
return;
|
||||
}
|
||||
const uint32_t delay = now - arg->start_time;
|
||||
@@ -183,7 +183,7 @@ void IRAM_ATTR Tx20ComponentStore::gpio_intr(Tx20ComponentStore *arg) {
|
||||
}
|
||||
arg->spent_time += delay;
|
||||
arg->start_time = now;
|
||||
arg->buffer_index++;
|
||||
arg->buffer_index++; // NOLINT(clang-diagnostic-deprecated-volatile)
|
||||
}
|
||||
void IRAM_ATTR Tx20ComponentStore::reset() {
|
||||
tx20_available = false;
|
||||
|
||||
@@ -17,10 +17,11 @@ from esphome.const import (
|
||||
AUTO_LOAD = ["socket"]
|
||||
DEPENDENCIES = ["api", "microphone"]
|
||||
|
||||
CODEOWNERS = ["@jesserockz"]
|
||||
CODEOWNERS = ["@jesserockz", "@kahrendt"]
|
||||
|
||||
CONF_ON_END = "on_end"
|
||||
CONF_ON_INTENT_END = "on_intent_end"
|
||||
CONF_ON_INTENT_PROGRESS = "on_intent_progress"
|
||||
CONF_ON_INTENT_START = "on_intent_start"
|
||||
CONF_ON_LISTENING = "on_listening"
|
||||
CONF_ON_START = "on_start"
|
||||
@@ -136,6 +137,9 @@ CONFIG_SCHEMA = cv.All(
|
||||
cv.Optional(CONF_ON_INTENT_START): automation.validate_automation(
|
||||
single=True
|
||||
),
|
||||
cv.Optional(CONF_ON_INTENT_PROGRESS): automation.validate_automation(
|
||||
single=True
|
||||
),
|
||||
cv.Optional(CONF_ON_INTENT_END): automation.validate_automation(
|
||||
single=True
|
||||
),
|
||||
@@ -282,6 +286,13 @@ async def to_code(config):
|
||||
config[CONF_ON_INTENT_START],
|
||||
)
|
||||
|
||||
if CONF_ON_INTENT_PROGRESS in config:
|
||||
await automation.build_automation(
|
||||
var.get_intent_progress_trigger(),
|
||||
[(cg.std_string, "x")],
|
||||
config[CONF_ON_INTENT_PROGRESS],
|
||||
)
|
||||
|
||||
if CONF_ON_INTENT_END in config:
|
||||
await automation.build_automation(
|
||||
var.get_intent_end_trigger(),
|
||||
|
||||
@@ -555,7 +555,7 @@ void VoiceAssistant::request_stop() {
|
||||
break;
|
||||
case State::AWAITING_RESPONSE:
|
||||
this->signal_stop_();
|
||||
break;
|
||||
// Fallthrough intended to stop a streaming TTS announcement that has potentially started
|
||||
case State::STREAMING_RESPONSE:
|
||||
#ifdef USE_MEDIA_PLAYER
|
||||
// Stop any ongoing media player announcement
|
||||
@@ -599,6 +599,14 @@ void VoiceAssistant::on_event(const api::VoiceAssistantEventResponse &msg) {
|
||||
switch (msg.event_type) {
|
||||
case api::enums::VOICE_ASSISTANT_RUN_START:
|
||||
ESP_LOGD(TAG, "Assist Pipeline running");
|
||||
#ifdef USE_MEDIA_PLAYER
|
||||
this->started_streaming_tts_ = false;
|
||||
for (auto arg : msg.data) {
|
||||
if (arg.name == "url") {
|
||||
this->tts_response_url_ = std::move(arg.value);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
this->defer([this]() { this->start_trigger_->trigger(); });
|
||||
break;
|
||||
case api::enums::VOICE_ASSISTANT_WAKE_WORD_START:
|
||||
@@ -622,6 +630,8 @@ void VoiceAssistant::on_event(const api::VoiceAssistantEventResponse &msg) {
|
||||
if (text.empty()) {
|
||||
ESP_LOGW(TAG, "No text in STT_END event");
|
||||
return;
|
||||
} else if (text.length() > 500) {
|
||||
text = text.substr(0, 497) + "...";
|
||||
}
|
||||
ESP_LOGD(TAG, "Speech recognised as: \"%s\"", text.c_str());
|
||||
this->defer([this, text]() { this->stt_end_trigger_->trigger(text); });
|
||||
@@ -631,6 +641,27 @@ void VoiceAssistant::on_event(const api::VoiceAssistantEventResponse &msg) {
|
||||
ESP_LOGD(TAG, "Intent started");
|
||||
this->defer([this]() { this->intent_start_trigger_->trigger(); });
|
||||
break;
|
||||
case api::enums::VOICE_ASSISTANT_INTENT_PROGRESS: {
|
||||
ESP_LOGD(TAG, "Intent progress");
|
||||
std::string tts_url_for_trigger = "";
|
||||
#ifdef USE_MEDIA_PLAYER
|
||||
if (this->media_player_ != nullptr) {
|
||||
for (const auto &arg : msg.data) {
|
||||
if ((arg.name == "tts_start_streaming") && (arg.value == "1") && !this->tts_response_url_.empty()) {
|
||||
this->media_player_->make_call().set_media_url(this->tts_response_url_).set_announcement(true).perform();
|
||||
|
||||
this->media_player_wait_for_announcement_start_ = true;
|
||||
this->media_player_wait_for_announcement_end_ = false;
|
||||
this->started_streaming_tts_ = true;
|
||||
tts_url_for_trigger = this->tts_response_url_;
|
||||
this->tts_response_url_.clear(); // Reset streaming URL
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
this->defer([this, tts_url_for_trigger]() { this->intent_progress_trigger_->trigger(tts_url_for_trigger); });
|
||||
break;
|
||||
}
|
||||
case api::enums::VOICE_ASSISTANT_INTENT_END: {
|
||||
for (auto arg : msg.data) {
|
||||
if (arg.name == "conversation_id") {
|
||||
@@ -653,6 +684,9 @@ void VoiceAssistant::on_event(const api::VoiceAssistantEventResponse &msg) {
|
||||
ESP_LOGW(TAG, "No text in TTS_START event");
|
||||
return;
|
||||
}
|
||||
if (text.length() > 500) {
|
||||
text = text.substr(0, 497) + "...";
|
||||
}
|
||||
ESP_LOGD(TAG, "Response: \"%s\"", text.c_str());
|
||||
this->defer([this, text]() {
|
||||
this->tts_start_trigger_->trigger(text);
|
||||
@@ -678,7 +712,7 @@ void VoiceAssistant::on_event(const api::VoiceAssistantEventResponse &msg) {
|
||||
ESP_LOGD(TAG, "Response URL: \"%s\"", url.c_str());
|
||||
this->defer([this, url]() {
|
||||
#ifdef USE_MEDIA_PLAYER
|
||||
if (this->media_player_ != nullptr) {
|
||||
if ((this->media_player_ != nullptr) && (!this->started_streaming_tts_)) {
|
||||
this->media_player_->make_call().set_media_url(url).set_announcement(true).perform();
|
||||
|
||||
this->media_player_wait_for_announcement_start_ = true;
|
||||
|
||||
@@ -177,6 +177,7 @@ class VoiceAssistant : public Component {
|
||||
|
||||
Trigger<> *get_intent_end_trigger() const { return this->intent_end_trigger_; }
|
||||
Trigger<> *get_intent_start_trigger() const { return this->intent_start_trigger_; }
|
||||
Trigger<std::string> *get_intent_progress_trigger() const { return this->intent_progress_trigger_; }
|
||||
Trigger<> *get_listening_trigger() const { return this->listening_trigger_; }
|
||||
Trigger<> *get_end_trigger() const { return this->end_trigger_; }
|
||||
Trigger<> *get_start_trigger() const { return this->start_trigger_; }
|
||||
@@ -233,6 +234,7 @@ class VoiceAssistant : public Component {
|
||||
Trigger<> *tts_stream_start_trigger_ = new Trigger<>();
|
||||
Trigger<> *tts_stream_end_trigger_ = new Trigger<>();
|
||||
#endif
|
||||
Trigger<std::string> *intent_progress_trigger_ = new Trigger<std::string>();
|
||||
Trigger<> *wake_word_detected_trigger_ = new Trigger<>();
|
||||
Trigger<std::string> *stt_end_trigger_ = new Trigger<std::string>();
|
||||
Trigger<std::string> *tts_end_trigger_ = new Trigger<std::string>();
|
||||
@@ -268,6 +270,8 @@ class VoiceAssistant : public Component {
|
||||
#endif
|
||||
#ifdef USE_MEDIA_PLAYER
|
||||
media_player::MediaPlayer *media_player_{nullptr};
|
||||
std::string tts_response_url_{""};
|
||||
bool started_streaming_tts_{false};
|
||||
bool media_player_wait_for_announcement_start_{false};
|
||||
bool media_player_wait_for_announcement_end_{false};
|
||||
#endif
|
||||
|
||||
@@ -211,6 +211,7 @@ async def add_entity_config(entity, config):
|
||||
sorting_weight = config.get(CONF_SORTING_WEIGHT, 50)
|
||||
sorting_group_hash = hash(config.get(CONF_SORTING_GROUP_ID))
|
||||
|
||||
cg.add_define("USE_WEBSERVER_SORTING")
|
||||
cg.add(
|
||||
web_server.add_entity_config(
|
||||
entity,
|
||||
@@ -296,4 +297,5 @@ async def to_code(config):
|
||||
cg.add_define("USE_WEBSERVER_LOCAL")
|
||||
|
||||
if (sorting_group_config := config.get(CONF_SORTING_GROUPS)) is not None:
|
||||
cg.add_define("USE_WEBSERVER_SORTING")
|
||||
add_sorting_groups(var, sorting_group_config)
|
||||
|
||||
@@ -184,6 +184,7 @@ void DeferredUpdateEventSourceList::on_client_connect_(WebServer *ws, DeferredUp
|
||||
std::string message = ws->get_config_json();
|
||||
source->try_send_nodefer(message.c_str(), "ping", millis(), 30000);
|
||||
|
||||
#ifdef USE_WEBSERVER_SORTING
|
||||
for (auto &group : ws->sorting_groups_) {
|
||||
message = json::build_json([group](JsonObject root) {
|
||||
root["name"] = group.second.name;
|
||||
@@ -193,6 +194,7 @@ void DeferredUpdateEventSourceList::on_client_connect_(WebServer *ws, DeferredUp
|
||||
// up to 31 groups should be able to be queued initially without defer
|
||||
source->try_send_nodefer(message.c_str(), "sorting_group");
|
||||
}
|
||||
#endif
|
||||
|
||||
source->entities_iterator_.begin(ws->include_internal_);
|
||||
|
||||
@@ -411,12 +413,7 @@ std::string WebServer::sensor_json(sensor::Sensor *obj, float value, JsonDetail
|
||||
}
|
||||
set_json_icon_state_value(root, obj, "sensor-" + obj->get_object_id(), state, value, start_config);
|
||||
if (start_config == DETAIL_ALL) {
|
||||
if (this->sorting_entitys_.find(obj) != this->sorting_entitys_.end()) {
|
||||
root["sorting_weight"] = this->sorting_entitys_[obj].weight;
|
||||
if (this->sorting_groups_.find(this->sorting_entitys_[obj].group_id) != this->sorting_groups_.end()) {
|
||||
root["sorting_group"] = this->sorting_groups_[this->sorting_entitys_[obj].group_id].name;
|
||||
}
|
||||
}
|
||||
this->add_sorting_info_(root, obj);
|
||||
if (!obj->get_unit_of_measurement().empty())
|
||||
root["uom"] = obj->get_unit_of_measurement();
|
||||
}
|
||||
@@ -460,12 +457,7 @@ std::string WebServer::text_sensor_json(text_sensor::TextSensor *obj, const std:
|
||||
return json::build_json([this, obj, value, start_config](JsonObject root) {
|
||||
set_json_icon_state_value(root, obj, "text_sensor-" + obj->get_object_id(), value, value, start_config);
|
||||
if (start_config == DETAIL_ALL) {
|
||||
if (this->sorting_entitys_.find(obj) != this->sorting_entitys_.end()) {
|
||||
root["sorting_weight"] = this->sorting_entitys_[obj].weight;
|
||||
if (this->sorting_groups_.find(this->sorting_entitys_[obj].group_id) != this->sorting_groups_.end()) {
|
||||
root["sorting_group"] = this->sorting_groups_[this->sorting_entitys_[obj].group_id].name;
|
||||
}
|
||||
}
|
||||
this->add_sorting_info_(root, obj);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -517,12 +509,7 @@ std::string WebServer::switch_json(switch_::Switch *obj, bool value, JsonDetail
|
||||
set_json_icon_state_value(root, obj, "switch-" + obj->get_object_id(), value ? "ON" : "OFF", value, start_config);
|
||||
if (start_config == DETAIL_ALL) {
|
||||
root["assumed_state"] = obj->assumed_state();
|
||||
if (this->sorting_entitys_.find(obj) != this->sorting_entitys_.end()) {
|
||||
root["sorting_weight"] = this->sorting_entitys_[obj].weight;
|
||||
if (this->sorting_groups_.find(this->sorting_entitys_[obj].group_id) != this->sorting_groups_.end()) {
|
||||
root["sorting_group"] = this->sorting_groups_[this->sorting_entitys_[obj].group_id].name;
|
||||
}
|
||||
}
|
||||
this->add_sorting_info_(root, obj);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -562,12 +549,7 @@ std::string WebServer::button_json(button::Button *obj, JsonDetail start_config)
|
||||
return json::build_json([this, obj, start_config](JsonObject root) {
|
||||
set_json_id(root, obj, "button-" + obj->get_object_id(), start_config);
|
||||
if (start_config == DETAIL_ALL) {
|
||||
if (this->sorting_entitys_.find(obj) != this->sorting_entitys_.end()) {
|
||||
root["sorting_weight"] = this->sorting_entitys_[obj].weight;
|
||||
if (this->sorting_groups_.find(this->sorting_entitys_[obj].group_id) != this->sorting_groups_.end()) {
|
||||
root["sorting_group"] = this->sorting_groups_[this->sorting_entitys_[obj].group_id].name;
|
||||
}
|
||||
}
|
||||
this->add_sorting_info_(root, obj);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -609,12 +591,7 @@ std::string WebServer::binary_sensor_json(binary_sensor::BinarySensor *obj, bool
|
||||
set_json_icon_state_value(root, obj, "binary_sensor-" + obj->get_object_id(), value ? "ON" : "OFF", value,
|
||||
start_config);
|
||||
if (start_config == DETAIL_ALL) {
|
||||
if (this->sorting_entitys_.find(obj) != this->sorting_entitys_.end()) {
|
||||
root["sorting_weight"] = this->sorting_entitys_[obj].weight;
|
||||
if (this->sorting_groups_.find(this->sorting_entitys_[obj].group_id) != this->sorting_groups_.end()) {
|
||||
root["sorting_group"] = this->sorting_groups_[this->sorting_entitys_[obj].group_id].name;
|
||||
}
|
||||
}
|
||||
this->add_sorting_info_(root, obj);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -699,12 +676,7 @@ std::string WebServer::fan_json(fan::Fan *obj, JsonDetail start_config) {
|
||||
if (obj->get_traits().supports_oscillation())
|
||||
root["oscillation"] = obj->oscillating;
|
||||
if (start_config == DETAIL_ALL) {
|
||||
if (this->sorting_entitys_.find(obj) != this->sorting_entitys_.end()) {
|
||||
root["sorting_weight"] = this->sorting_entitys_[obj].weight;
|
||||
if (this->sorting_groups_.find(this->sorting_entitys_[obj].group_id) != this->sorting_groups_.end()) {
|
||||
root["sorting_group"] = this->sorting_groups_[this->sorting_entitys_[obj].group_id].name;
|
||||
}
|
||||
}
|
||||
this->add_sorting_info_(root, obj);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -824,12 +796,7 @@ std::string WebServer::light_json(light::LightState *obj, JsonDetail start_confi
|
||||
for (auto const &option : obj->get_effects()) {
|
||||
opt.add(option->get_name());
|
||||
}
|
||||
if (this->sorting_entitys_.find(obj) != this->sorting_entitys_.end()) {
|
||||
root["sorting_weight"] = this->sorting_entitys_[obj].weight;
|
||||
if (this->sorting_groups_.find(this->sorting_entitys_[obj].group_id) != this->sorting_groups_.end()) {
|
||||
root["sorting_group"] = this->sorting_groups_[this->sorting_entitys_[obj].group_id].name;
|
||||
}
|
||||
}
|
||||
this->add_sorting_info_(root, obj);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -914,12 +881,7 @@ std::string WebServer::cover_json(cover::Cover *obj, JsonDetail start_config) {
|
||||
if (obj->get_traits().get_supports_tilt())
|
||||
root["tilt"] = obj->tilt;
|
||||
if (start_config == DETAIL_ALL) {
|
||||
if (this->sorting_entitys_.find(obj) != this->sorting_entitys_.end()) {
|
||||
root["sorting_weight"] = this->sorting_entitys_[obj].weight;
|
||||
if (this->sorting_groups_.find(this->sorting_entitys_[obj].group_id) != this->sorting_groups_.end()) {
|
||||
root["sorting_group"] = this->sorting_groups_[this->sorting_entitys_[obj].group_id].name;
|
||||
}
|
||||
}
|
||||
this->add_sorting_info_(root, obj);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -984,12 +946,7 @@ std::string WebServer::number_json(number::Number *obj, float value, JsonDetail
|
||||
root["mode"] = (int) obj->traits.get_mode();
|
||||
if (!obj->traits.get_unit_of_measurement().empty())
|
||||
root["uom"] = obj->traits.get_unit_of_measurement();
|
||||
if (this->sorting_entitys_.find(obj) != this->sorting_entitys_.end()) {
|
||||
root["sorting_weight"] = this->sorting_entitys_[obj].weight;
|
||||
if (this->sorting_groups_.find(this->sorting_entitys_[obj].group_id) != this->sorting_groups_.end()) {
|
||||
root["sorting_group"] = this->sorting_groups_[this->sorting_entitys_[obj].group_id].name;
|
||||
}
|
||||
}
|
||||
this->add_sorting_info_(root, obj);
|
||||
}
|
||||
if (std::isnan(value)) {
|
||||
root["value"] = "\"NaN\"";
|
||||
@@ -1062,12 +1019,7 @@ std::string WebServer::date_json(datetime::DateEntity *obj, JsonDetail start_con
|
||||
root["value"] = value;
|
||||
root["state"] = value;
|
||||
if (start_config == DETAIL_ALL) {
|
||||
if (this->sorting_entitys_.find(obj) != this->sorting_entitys_.end()) {
|
||||
root["sorting_weight"] = this->sorting_entitys_[obj].weight;
|
||||
if (this->sorting_groups_.find(this->sorting_entitys_[obj].group_id) != this->sorting_groups_.end()) {
|
||||
root["sorting_group"] = this->sorting_groups_[this->sorting_entitys_[obj].group_id].name;
|
||||
}
|
||||
}
|
||||
this->add_sorting_info_(root, obj);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1129,12 +1081,7 @@ std::string WebServer::time_json(datetime::TimeEntity *obj, JsonDetail start_con
|
||||
root["value"] = value;
|
||||
root["state"] = value;
|
||||
if (start_config == DETAIL_ALL) {
|
||||
if (this->sorting_entitys_.find(obj) != this->sorting_entitys_.end()) {
|
||||
root["sorting_weight"] = this->sorting_entitys_[obj].weight;
|
||||
if (this->sorting_groups_.find(this->sorting_entitys_[obj].group_id) != this->sorting_groups_.end()) {
|
||||
root["sorting_group"] = this->sorting_groups_[this->sorting_entitys_[obj].group_id].name;
|
||||
}
|
||||
}
|
||||
this->add_sorting_info_(root, obj);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1197,12 +1144,7 @@ std::string WebServer::datetime_json(datetime::DateTimeEntity *obj, JsonDetail s
|
||||
root["value"] = value;
|
||||
root["state"] = value;
|
||||
if (start_config == DETAIL_ALL) {
|
||||
if (this->sorting_entitys_.find(obj) != this->sorting_entitys_.end()) {
|
||||
root["sorting_weight"] = this->sorting_entitys_[obj].weight;
|
||||
if (this->sorting_groups_.find(this->sorting_entitys_[obj].group_id) != this->sorting_groups_.end()) {
|
||||
root["sorting_group"] = this->sorting_groups_[this->sorting_entitys_[obj].group_id].name;
|
||||
}
|
||||
}
|
||||
this->add_sorting_info_(root, obj);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1267,12 +1209,7 @@ std::string WebServer::text_json(text::Text *obj, const std::string &value, Json
|
||||
root["value"] = value;
|
||||
if (start_config == DETAIL_ALL) {
|
||||
root["mode"] = (int) obj->traits.get_mode();
|
||||
if (this->sorting_entitys_.find(obj) != this->sorting_entitys_.end()) {
|
||||
root["sorting_weight"] = this->sorting_entitys_[obj].weight;
|
||||
if (this->sorting_groups_.find(this->sorting_entitys_[obj].group_id) != this->sorting_groups_.end()) {
|
||||
root["sorting_group"] = this->sorting_groups_[this->sorting_entitys_[obj].group_id].name;
|
||||
}
|
||||
}
|
||||
this->add_sorting_info_(root, obj);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1332,12 +1269,7 @@ std::string WebServer::select_json(select::Select *obj, const std::string &value
|
||||
for (auto &option : obj->traits.get_options()) {
|
||||
opt.add(option);
|
||||
}
|
||||
if (this->sorting_entitys_.find(obj) != this->sorting_entitys_.end()) {
|
||||
root["sorting_weight"] = this->sorting_entitys_[obj].weight;
|
||||
if (this->sorting_groups_.find(this->sorting_entitys_[obj].group_id) != this->sorting_groups_.end()) {
|
||||
root["sorting_group"] = this->sorting_groups_[this->sorting_entitys_[obj].group_id].name;
|
||||
}
|
||||
}
|
||||
this->add_sorting_info_(root, obj);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1458,12 +1390,7 @@ std::string WebServer::climate_json(climate::Climate *obj, JsonDetail start_conf
|
||||
for (auto const &custom_preset : traits.get_supported_custom_presets())
|
||||
opt.add(custom_preset);
|
||||
}
|
||||
if (this->sorting_entitys_.find(obj) != this->sorting_entitys_.end()) {
|
||||
root["sorting_weight"] = this->sorting_entitys_[obj].weight;
|
||||
if (this->sorting_groups_.find(this->sorting_entitys_[obj].group_id) != this->sorting_groups_.end()) {
|
||||
root["sorting_group"] = this->sorting_groups_[this->sorting_entitys_[obj].group_id].name;
|
||||
}
|
||||
}
|
||||
this->add_sorting_info_(root, obj);
|
||||
}
|
||||
|
||||
bool has_state = false;
|
||||
@@ -1560,12 +1487,7 @@ std::string WebServer::lock_json(lock::Lock *obj, lock::LockState value, JsonDet
|
||||
set_json_icon_state_value(root, obj, "lock-" + obj->get_object_id(), lock::lock_state_to_string(value), value,
|
||||
start_config);
|
||||
if (start_config == DETAIL_ALL) {
|
||||
if (this->sorting_entitys_.find(obj) != this->sorting_entitys_.end()) {
|
||||
root["sorting_weight"] = this->sorting_entitys_[obj].weight;
|
||||
if (this->sorting_groups_.find(this->sorting_entitys_[obj].group_id) != this->sorting_groups_.end()) {
|
||||
root["sorting_group"] = this->sorting_groups_[this->sorting_entitys_[obj].group_id].name;
|
||||
}
|
||||
}
|
||||
this->add_sorting_info_(root, obj);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1641,12 +1563,7 @@ std::string WebServer::valve_json(valve::Valve *obj, JsonDetail start_config) {
|
||||
if (obj->get_traits().get_supports_position())
|
||||
root["position"] = obj->position;
|
||||
if (start_config == DETAIL_ALL) {
|
||||
if (this->sorting_entitys_.find(obj) != this->sorting_entitys_.end()) {
|
||||
root["sorting_weight"] = this->sorting_entitys_[obj].weight;
|
||||
if (this->sorting_groups_.find(this->sorting_entitys_[obj].group_id) != this->sorting_groups_.end()) {
|
||||
root["sorting_group"] = this->sorting_groups_[this->sorting_entitys_[obj].group_id].name;
|
||||
}
|
||||
}
|
||||
this->add_sorting_info_(root, obj);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1718,12 +1635,7 @@ std::string WebServer::alarm_control_panel_json(alarm_control_panel::AlarmContro
|
||||
set_json_icon_state_value(root, obj, "alarm-control-panel-" + obj->get_object_id(),
|
||||
PSTR_LOCAL(alarm_control_panel_state_to_string(value)), value, start_config);
|
||||
if (start_config == DETAIL_ALL) {
|
||||
if (this->sorting_entitys_.find(obj) != this->sorting_entitys_.end()) {
|
||||
root["sorting_weight"] = this->sorting_entitys_[obj].weight;
|
||||
if (this->sorting_groups_.find(this->sorting_entitys_[obj].group_id) != this->sorting_groups_.end()) {
|
||||
root["sorting_group"] = this->sorting_groups_[this->sorting_entitys_[obj].group_id].name;
|
||||
}
|
||||
}
|
||||
this->add_sorting_info_(root, obj);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1772,12 +1684,7 @@ std::string WebServer::event_json(event::Event *obj, const std::string &event_ty
|
||||
event_types.add(event_type);
|
||||
}
|
||||
root["device_class"] = obj->get_device_class();
|
||||
if (this->sorting_entitys_.find(obj) != this->sorting_entitys_.end()) {
|
||||
root["sorting_weight"] = this->sorting_entitys_[obj].weight;
|
||||
if (this->sorting_groups_.find(this->sorting_entitys_[obj].group_id) != this->sorting_groups_.end()) {
|
||||
root["sorting_group"] = this->sorting_groups_[this->sorting_entitys_[obj].group_id].name;
|
||||
}
|
||||
}
|
||||
this->add_sorting_info_(root, obj);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1845,12 +1752,7 @@ std::string WebServer::update_json(update::UpdateEntity *obj, JsonDetail start_c
|
||||
root["title"] = obj->update_info.title;
|
||||
root["summary"] = obj->update_info.summary;
|
||||
root["release_url"] = obj->update_info.release_url;
|
||||
if (this->sorting_entitys_.find(obj) != this->sorting_entitys_.end()) {
|
||||
root["sorting_weight"] = this->sorting_entitys_[obj].weight;
|
||||
if (this->sorting_groups_.find(this->sorting_entitys_[obj].group_id) != this->sorting_groups_.end()) {
|
||||
root["sorting_group"] = this->sorting_groups_[this->sorting_entitys_[obj].group_id].name;
|
||||
}
|
||||
}
|
||||
this->add_sorting_info_(root, obj);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -2160,6 +2062,18 @@ void WebServer::handleRequest(AsyncWebServerRequest *request) {
|
||||
|
||||
bool WebServer::isRequestHandlerTrivial() const { return false; }
|
||||
|
||||
void WebServer::add_sorting_info_(JsonObject &root, EntityBase *entity) {
|
||||
#ifdef USE_WEBSERVER_SORTING
|
||||
if (this->sorting_entitys_.find(entity) != this->sorting_entitys_.end()) {
|
||||
root["sorting_weight"] = this->sorting_entitys_[entity].weight;
|
||||
if (this->sorting_groups_.find(this->sorting_entitys_[entity].group_id) != this->sorting_groups_.end()) {
|
||||
root["sorting_group"] = this->sorting_groups_[this->sorting_entitys_[entity].group_id].name;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef USE_WEBSERVER_SORTING
|
||||
void WebServer::add_entity_config(EntityBase *entity, float weight, uint64_t group) {
|
||||
this->sorting_entitys_[entity] = SortingComponents{weight, group};
|
||||
}
|
||||
@@ -2167,6 +2081,7 @@ void WebServer::add_entity_config(EntityBase *entity, float weight, uint64_t gro
|
||||
void WebServer::add_sorting_group(uint64_t group_id, const std::string &group_name, float weight) {
|
||||
this->sorting_groups_[group_id] = SortingGroup{group_name, weight};
|
||||
}
|
||||
#endif
|
||||
|
||||
void WebServer::schedule_(std::function<void()> &&f) {
|
||||
#ifdef USE_ESP32
|
||||
|
||||
@@ -46,6 +46,7 @@ struct UrlMatch {
|
||||
bool valid; ///< Whether this match is valid
|
||||
};
|
||||
|
||||
#ifdef USE_WEBSERVER_SORTING
|
||||
struct SortingComponents {
|
||||
float weight;
|
||||
uint64_t group_id;
|
||||
@@ -55,6 +56,7 @@ struct SortingGroup {
|
||||
std::string name;
|
||||
float weight;
|
||||
};
|
||||
#endif
|
||||
|
||||
enum JsonDetail { DETAIL_ALL, DETAIL_STATE };
|
||||
|
||||
@@ -474,14 +476,18 @@ class WebServer : public Controller, public Component, public AsyncWebHandler {
|
||||
/// This web handle is not trivial.
|
||||
bool isRequestHandlerTrivial() const override; // NOLINT(readability-identifier-naming)
|
||||
|
||||
#ifdef USE_WEBSERVER_SORTING
|
||||
void add_entity_config(EntityBase *entity, float weight, uint64_t group);
|
||||
void add_sorting_group(uint64_t group_id, const std::string &group_name, float weight);
|
||||
|
||||
std::map<EntityBase *, SortingComponents> sorting_entitys_;
|
||||
std::map<uint64_t, SortingGroup> sorting_groups_;
|
||||
#endif
|
||||
|
||||
bool include_internal_{false};
|
||||
|
||||
protected:
|
||||
void add_sorting_info_(JsonObject &root, EntityBase *entity);
|
||||
void schedule_(std::function<void()> &&f);
|
||||
web_server_base::WebServerBase *base_;
|
||||
#ifdef USE_ARDUINO
|
||||
|
||||
@@ -338,6 +338,7 @@ AsyncEventSourceResponse::AsyncEventSourceResponse(const AsyncWebServerRequest *
|
||||
std::string message = ws->get_config_json();
|
||||
this->try_send_nodefer(message.c_str(), "ping", millis(), 30000);
|
||||
|
||||
#ifdef USE_WEBSERVER_SORTING
|
||||
for (auto &group : ws->sorting_groups_) {
|
||||
message = json::build_json([group](JsonObject root) {
|
||||
root["name"] = group.second.name;
|
||||
@@ -348,6 +349,7 @@ AsyncEventSourceResponse::AsyncEventSourceResponse(const AsyncWebServerRequest *
|
||||
// since the only thing in the send buffer at this point is the initial ping/config
|
||||
this->try_send_nodefer(message.c_str(), "sorting_group");
|
||||
}
|
||||
#endif
|
||||
|
||||
this->entities_iterator_->begin(ws->include_internal_);
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ static const char *const KEYS = "0123456789*#";
|
||||
void IRAM_ATTR HOT WiegandStore::d0_gpio_intr(WiegandStore *arg) {
|
||||
if (arg->d0.digital_read())
|
||||
return;
|
||||
arg->count++;
|
||||
arg->count++; // NOLINT(clang-diagnostic-deprecated-volatile)
|
||||
arg->value <<= 1;
|
||||
arg->last_bit_time = millis();
|
||||
arg->done = false;
|
||||
@@ -20,7 +20,7 @@ void IRAM_ATTR HOT WiegandStore::d0_gpio_intr(WiegandStore *arg) {
|
||||
void IRAM_ATTR HOT WiegandStore::d1_gpio_intr(WiegandStore *arg) {
|
||||
if (arg->d1.digital_read())
|
||||
return;
|
||||
arg->count++;
|
||||
arg->count++; // NOLINT(clang-diagnostic-deprecated-volatile)
|
||||
arg->value = (arg->value << 1) | 1;
|
||||
arg->last_bit_time = millis();
|
||||
arg->done = false;
|
||||
|
||||
@@ -62,7 +62,7 @@ struct SavedWifiFastConnectSettings {
|
||||
uint8_t channel;
|
||||
} PACKED; // NOLINT
|
||||
|
||||
enum WiFiComponentState {
|
||||
enum WiFiComponentState : uint8_t {
|
||||
/** Nothing has been initialized yet. Internal AP, if configured, is disabled at this point. */
|
||||
WIFI_COMPONENT_STATE_OFF = 0,
|
||||
/** WiFi is disabled. */
|
||||
@@ -146,14 +146,14 @@ class WiFiAP {
|
||||
|
||||
protected:
|
||||
std::string ssid_;
|
||||
optional<bssid_t> bssid_;
|
||||
std::string password_;
|
||||
optional<bssid_t> bssid_;
|
||||
#ifdef USE_WIFI_WPA2_EAP
|
||||
optional<EAPAuth> eap_;
|
||||
#endif // USE_WIFI_WPA2_EAP
|
||||
optional<uint8_t> channel_;
|
||||
float priority_{0};
|
||||
optional<ManualIP> manual_ip_;
|
||||
float priority_{0};
|
||||
optional<uint8_t> channel_;
|
||||
bool hidden_{false};
|
||||
};
|
||||
|
||||
@@ -177,14 +177,14 @@ class WiFiScanResult {
|
||||
bool operator==(const WiFiScanResult &rhs) const;
|
||||
|
||||
protected:
|
||||
bool matches_{false};
|
||||
bssid_t bssid_;
|
||||
std::string ssid_;
|
||||
float priority_{0.0f};
|
||||
uint8_t channel_;
|
||||
int8_t rssi_;
|
||||
bool matches_{false};
|
||||
bool with_auth_;
|
||||
bool is_hidden_;
|
||||
float priority_{0.0f};
|
||||
};
|
||||
|
||||
struct WiFiSTAPriority {
|
||||
@@ -192,7 +192,7 @@ struct WiFiSTAPriority {
|
||||
float priority;
|
||||
};
|
||||
|
||||
enum WiFiPowerSaveMode {
|
||||
enum WiFiPowerSaveMode : uint8_t {
|
||||
WIFI_POWER_SAVE_NONE = 0,
|
||||
WIFI_POWER_SAVE_LIGHT,
|
||||
WIFI_POWER_SAVE_HIGH,
|
||||
@@ -383,28 +383,36 @@ class WiFiComponent : public Component {
|
||||
std::string use_address_;
|
||||
std::vector<WiFiAP> sta_;
|
||||
std::vector<WiFiSTAPriority> sta_priorities_;
|
||||
std::vector<WiFiScanResult> scan_result_;
|
||||
WiFiAP selected_ap_;
|
||||
bool fast_connect_{false};
|
||||
bool retry_hidden_{false};
|
||||
|
||||
bool has_ap_{false};
|
||||
WiFiAP ap_;
|
||||
WiFiComponentState state_{WIFI_COMPONENT_STATE_OFF};
|
||||
bool handled_connected_state_{false};
|
||||
optional<float> output_power_;
|
||||
ESPPreferenceObject pref_;
|
||||
ESPPreferenceObject fast_connect_pref_;
|
||||
|
||||
// Group all 32-bit integers together
|
||||
uint32_t action_started_;
|
||||
uint8_t num_retried_{0};
|
||||
uint32_t last_connected_{0};
|
||||
uint32_t reboot_timeout_{};
|
||||
uint32_t ap_timeout_{};
|
||||
|
||||
// Group all 8-bit values together
|
||||
WiFiComponentState state_{WIFI_COMPONENT_STATE_OFF};
|
||||
WiFiPowerSaveMode power_save_{WIFI_POWER_SAVE_NONE};
|
||||
uint8_t num_retried_{0};
|
||||
#if USE_NETWORK_IPV6
|
||||
uint8_t num_ipv6_addresses_{0};
|
||||
#endif /* USE_NETWORK_IPV6 */
|
||||
|
||||
// Group all boolean values together
|
||||
bool fast_connect_{false};
|
||||
bool retry_hidden_{false};
|
||||
bool has_ap_{false};
|
||||
bool handled_connected_state_{false};
|
||||
bool error_from_callback_{false};
|
||||
std::vector<WiFiScanResult> scan_result_;
|
||||
bool scan_done_{false};
|
||||
bool ap_setup_{false};
|
||||
optional<float> output_power_;
|
||||
bool passive_scan_{false};
|
||||
ESPPreferenceObject pref_;
|
||||
ESPPreferenceObject fast_connect_pref_;
|
||||
bool has_saved_wifi_settings_{false};
|
||||
#ifdef USE_WIFI_11KV_SUPPORT
|
||||
bool btm_{false};
|
||||
@@ -412,10 +420,8 @@ class WiFiComponent : public Component {
|
||||
#endif
|
||||
bool enable_on_boot_;
|
||||
bool got_ipv4_address_{false};
|
||||
#if USE_NETWORK_IPV6
|
||||
uint8_t num_ipv6_addresses_{0};
|
||||
#endif /* USE_NETWORK_IPV6 */
|
||||
|
||||
// Pointers at the end (naturally aligned)
|
||||
Trigger<> *connect_trigger_{new Trigger<>()};
|
||||
Trigger<> *disconnect_trigger_{new Trigger<>()};
|
||||
};
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include "esphome/core/version.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include <algorithm>
|
||||
#include <ranges>
|
||||
|
||||
#ifdef USE_STATUS_LED
|
||||
#include "esphome/components/status_led/status_led.h"
|
||||
@@ -136,6 +137,10 @@ void Application::loop() {
|
||||
this->in_loop_ = false;
|
||||
this->app_state_ = new_app_state;
|
||||
|
||||
// Process any pending runtime stats printing after all components have run
|
||||
// This ensures stats printing doesn't affect component timing measurements
|
||||
runtime_stats.process_pending_stats(last_op_end_time);
|
||||
|
||||
// Use the last component's end time instead of calling millis() again
|
||||
auto elapsed = last_op_end_time - this->last_loop_;
|
||||
if (elapsed >= this->loop_interval_ || HighFrequencyLoopRequester::is_high_frequency()) {
|
||||
@@ -184,8 +189,8 @@ void IRAM_ATTR HOT Application::feed_wdt(uint32_t time) {
|
||||
}
|
||||
void Application::reboot() {
|
||||
ESP_LOGI(TAG, "Forcing a reboot");
|
||||
for (auto it = this->components_.rbegin(); it != this->components_.rend(); ++it) {
|
||||
(*it)->on_shutdown();
|
||||
for (auto &component : std::ranges::reverse_view(this->components_)) {
|
||||
component->on_shutdown();
|
||||
}
|
||||
arch_restart();
|
||||
}
|
||||
@@ -198,17 +203,17 @@ void Application::safe_reboot() {
|
||||
}
|
||||
|
||||
void Application::run_safe_shutdown_hooks() {
|
||||
for (auto it = this->components_.rbegin(); it != this->components_.rend(); ++it) {
|
||||
(*it)->on_safe_shutdown();
|
||||
for (auto &component : std::ranges::reverse_view(this->components_)) {
|
||||
component->on_safe_shutdown();
|
||||
}
|
||||
for (auto it = this->components_.rbegin(); it != this->components_.rend(); ++it) {
|
||||
(*it)->on_shutdown();
|
||||
for (auto &component : std::ranges::reverse_view(this->components_)) {
|
||||
component->on_shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
void Application::run_powerdown_hooks() {
|
||||
for (auto it = this->components_.rbegin(); it != this->components_.rend(); ++it) {
|
||||
(*it)->on_powerdown();
|
||||
for (auto &component : std::ranges::reverse_view(this->components_)) {
|
||||
component->on_powerdown();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/preferences.h"
|
||||
#include "esphome/core/runtime_stats.h"
|
||||
#include "esphome/core/scheduler.h"
|
||||
|
||||
#ifdef USE_DEVICES
|
||||
@@ -348,6 +349,18 @@ class Application {
|
||||
|
||||
uint32_t get_loop_interval() const { return static_cast<uint32_t>(this->loop_interval_); }
|
||||
|
||||
/** Enable or disable runtime statistics collection.
|
||||
*
|
||||
* @param enable Whether to enable runtime statistics collection.
|
||||
*/
|
||||
void set_runtime_stats_enabled(bool enable) { runtime_stats.set_enabled(enable); }
|
||||
|
||||
/** Set the interval at which runtime statistics are logged.
|
||||
*
|
||||
* @param interval The interval in milliseconds between logging of runtime statistics.
|
||||
*/
|
||||
void set_runtime_stats_log_interval(uint32_t interval) { runtime_stats.set_log_interval(interval); }
|
||||
|
||||
void schedule_dump_config() { this->dump_config_at_ = 0; }
|
||||
|
||||
void feed_wdt(uint32_t time = 0);
|
||||
|
||||
@@ -60,10 +60,18 @@ void Component::set_interval(const std::string &name, uint32_t interval, std::fu
|
||||
App.scheduler.set_interval(this, name, interval, std::move(f));
|
||||
}
|
||||
|
||||
void Component::set_interval(const char *name, uint32_t interval, std::function<void()> &&f) { // NOLINT
|
||||
App.scheduler.set_interval(this, name, interval, std::move(f));
|
||||
}
|
||||
|
||||
bool Component::cancel_interval(const std::string &name) { // NOLINT
|
||||
return App.scheduler.cancel_interval(this, name);
|
||||
}
|
||||
|
||||
bool Component::cancel_interval(const char *name) { // NOLINT
|
||||
return App.scheduler.cancel_interval(this, name);
|
||||
}
|
||||
|
||||
void Component::set_retry(const std::string &name, uint32_t initial_wait_time, uint8_t max_attempts,
|
||||
std::function<RetryResult(uint8_t)> &&f, float backoff_increase_factor) { // NOLINT
|
||||
App.scheduler.set_retry(this, name, initial_wait_time, max_attempts, std::move(f), backoff_increase_factor);
|
||||
@@ -77,10 +85,18 @@ void Component::set_timeout(const std::string &name, uint32_t timeout, std::func
|
||||
App.scheduler.set_timeout(this, name, timeout, std::move(f));
|
||||
}
|
||||
|
||||
void Component::set_timeout(const char *name, uint32_t timeout, std::function<void()> &&f) { // NOLINT
|
||||
App.scheduler.set_timeout(this, name, timeout, std::move(f));
|
||||
}
|
||||
|
||||
bool Component::cancel_timeout(const std::string &name) { // NOLINT
|
||||
return App.scheduler.cancel_timeout(this, name);
|
||||
}
|
||||
|
||||
bool Component::cancel_timeout(const char *name) { // NOLINT
|
||||
return App.scheduler.cancel_timeout(this, name);
|
||||
}
|
||||
|
||||
void Component::call_loop() { this->loop(); }
|
||||
void Component::call_setup() { this->setup(); }
|
||||
void Component::call_dump_config() {
|
||||
@@ -189,7 +205,7 @@ bool Component::is_in_loop_state() const {
|
||||
return (this->component_state_ & COMPONENT_STATE_MASK) == COMPONENT_STATE_LOOP;
|
||||
}
|
||||
void Component::defer(std::function<void()> &&f) { // NOLINT
|
||||
App.scheduler.set_timeout(this, "", 0, std::move(f));
|
||||
App.scheduler.set_timeout(this, static_cast<const char *>(nullptr), 0, std::move(f));
|
||||
}
|
||||
bool Component::cancel_defer(const std::string &name) { // NOLINT
|
||||
return App.scheduler.cancel_timeout(this, name);
|
||||
@@ -303,6 +319,9 @@ uint32_t WarnIfComponentBlockingGuard::finish() {
|
||||
uint32_t curr_time = millis();
|
||||
|
||||
uint32_t blocking_time = curr_time - this->started_;
|
||||
|
||||
// Record component runtime stats
|
||||
runtime_stats.record_component_time(this->component_, blocking_time, curr_time);
|
||||
bool should_warn;
|
||||
if (this->component_ != nullptr) {
|
||||
should_warn = this->component_->should_warn_of_blocking(blocking_time);
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
#include <string>
|
||||
|
||||
#include "esphome/core/optional.h"
|
||||
#include "esphome/core/runtime_stats.h"
|
||||
|
||||
namespace esphome {
|
||||
|
||||
@@ -260,6 +261,22 @@ class Component {
|
||||
*/
|
||||
void set_interval(const std::string &name, uint32_t interval, std::function<void()> &&f); // NOLINT
|
||||
|
||||
/** Set an interval function with a const char* name.
|
||||
*
|
||||
* IMPORTANT: The provided name pointer must remain valid for the lifetime of the scheduler item.
|
||||
* This means the name should be:
|
||||
* - A string literal (e.g., "update")
|
||||
* - A static const char* variable
|
||||
* - A pointer with lifetime >= the scheduled task
|
||||
*
|
||||
* For dynamic strings, use the std::string overload instead.
|
||||
*
|
||||
* @param name The identifier for this interval function (must have static lifetime)
|
||||
* @param interval The interval in ms
|
||||
* @param f The function to call
|
||||
*/
|
||||
void set_interval(const char *name, uint32_t interval, std::function<void()> &&f); // NOLINT
|
||||
|
||||
void set_interval(uint32_t interval, std::function<void()> &&f); // NOLINT
|
||||
|
||||
/** Cancel an interval function.
|
||||
@@ -268,6 +285,7 @@ class Component {
|
||||
* @return Whether an interval functions was deleted.
|
||||
*/
|
||||
bool cancel_interval(const std::string &name); // NOLINT
|
||||
bool cancel_interval(const char *name); // NOLINT
|
||||
|
||||
/** Set an retry function with a unique name. Empty name means no cancelling possible.
|
||||
*
|
||||
@@ -328,6 +346,22 @@ class Component {
|
||||
*/
|
||||
void set_timeout(const std::string &name, uint32_t timeout, std::function<void()> &&f); // NOLINT
|
||||
|
||||
/** Set a timeout function with a const char* name.
|
||||
*
|
||||
* IMPORTANT: The provided name pointer must remain valid for the lifetime of the scheduler item.
|
||||
* This means the name should be:
|
||||
* - A string literal (e.g., "init")
|
||||
* - A static const char* variable
|
||||
* - A pointer with lifetime >= the timeout duration
|
||||
*
|
||||
* For dynamic strings, use the std::string overload instead.
|
||||
*
|
||||
* @param name The identifier for this timeout function (must have static lifetime)
|
||||
* @param timeout The timeout in ms
|
||||
* @param f The function to call
|
||||
*/
|
||||
void set_timeout(const char *name, uint32_t timeout, std::function<void()> &&f); // NOLINT
|
||||
|
||||
void set_timeout(uint32_t timeout, std::function<void()> &&f); // NOLINT
|
||||
|
||||
/** Cancel a timeout function.
|
||||
@@ -336,6 +370,7 @@ class Component {
|
||||
* @return Whether a timeout functions was deleted.
|
||||
*/
|
||||
bool cancel_timeout(const std::string &name); // NOLINT
|
||||
bool cancel_timeout(const char *name); // NOLINT
|
||||
|
||||
/** Defer a callback to the next loop() call.
|
||||
*
|
||||
|
||||
@@ -375,7 +375,7 @@ void ComponentIterator::advance() {
|
||||
}
|
||||
|
||||
if (advance_platform) {
|
||||
this->state_ = static_cast<IteratorState>(static_cast<uint32_t>(this->state_) + 1);
|
||||
this->state_ = static_cast<IteratorState>(static_cast<uint8_t>(this->state_) + 1);
|
||||
this->at_ = 0;
|
||||
} else if (success) {
|
||||
this->at_++;
|
||||
|
||||
@@ -93,7 +93,9 @@ class ComponentIterator {
|
||||
virtual bool on_end();
|
||||
|
||||
protected:
|
||||
enum class IteratorState {
|
||||
// Iterates over all ESPHome entities (sensors, switches, lights, etc.)
|
||||
// Supports up to 256 entity types and up to 65,535 entities of each type
|
||||
enum class IteratorState : uint8_t {
|
||||
NONE = 0,
|
||||
BEGIN,
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
@@ -167,7 +169,7 @@ class ComponentIterator {
|
||||
#endif
|
||||
MAX,
|
||||
} state_{IteratorState::NONE};
|
||||
size_t at_{0};
|
||||
uint16_t at_{0}; // Supports up to 65,535 entities per type
|
||||
bool include_internal_{false};
|
||||
};
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ namespace internal {
|
||||
/// Wrapper class for memory using big endian data layout, transparently converting it to native order.
|
||||
template<typename T> class BigEndianLayout {
|
||||
public:
|
||||
constexpr14 operator T() { return convert_big_endian(val_); }
|
||||
constexpr operator T() { return convert_big_endian(val_); }
|
||||
|
||||
private:
|
||||
T val_;
|
||||
@@ -20,7 +20,7 @@ template<typename T> class BigEndianLayout {
|
||||
/// Wrapper class for memory using big endian data layout, transparently converting it to native order.
|
||||
template<typename T> class LittleEndianLayout {
|
||||
public:
|
||||
constexpr14 operator T() { return convert_little_endian(val_); }
|
||||
constexpr operator T() { return convert_little_endian(val_); }
|
||||
|
||||
private:
|
||||
T val_;
|
||||
|
||||
@@ -151,6 +151,7 @@
|
||||
#define USE_VOICE_ASSISTANT
|
||||
#define USE_WEBSERVER
|
||||
#define USE_WEBSERVER_PORT 80 // NOLINT
|
||||
#define USE_WEBSERVER_SORTING
|
||||
#define USE_WIFI_11KV_SUPPORT
|
||||
|
||||
#ifdef USE_ARDUINO
|
||||
|
||||
81
esphome/core/event_pool.h
Normal file
81
esphome/core/event_pool.h
Normal file
@@ -0,0 +1,81 @@
|
||||
#pragma once
|
||||
|
||||
#if defined(USE_ESP32) || defined(USE_LIBRETINY)
|
||||
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/lock_free_queue.h"
|
||||
|
||||
namespace esphome {
|
||||
|
||||
// Event Pool - On-demand pool of objects to avoid heap fragmentation
|
||||
// Events are allocated on first use and reused thereafter, growing to peak usage
|
||||
// @tparam T The type of objects managed by the pool (must have a release() method)
|
||||
// @tparam SIZE The maximum number of objects in the pool (1-255, limited by uint8_t)
|
||||
template<class T, uint8_t SIZE> class EventPool {
|
||||
public:
|
||||
EventPool() : total_created_(0) {}
|
||||
|
||||
~EventPool() {
|
||||
// Clean up any remaining events in the free list
|
||||
// IMPORTANT: This destructor assumes no concurrent access. The EventPool must not
|
||||
// be destroyed while any thread might still call allocate() or release().
|
||||
// In practice, this is typically ensured by destroying the pool only during
|
||||
// component shutdown when all producer/consumer threads have been stopped.
|
||||
T *event;
|
||||
RAMAllocator<T> allocator(RAMAllocator<T>::ALLOC_INTERNAL);
|
||||
while ((event = this->free_list_.pop()) != nullptr) {
|
||||
// Call destructor
|
||||
event->~T();
|
||||
// Deallocate using RAMAllocator
|
||||
allocator.deallocate(event, 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Allocate an event from the pool
|
||||
// Returns nullptr if pool is full
|
||||
T *allocate() {
|
||||
// Try to get from free list first
|
||||
T *event = this->free_list_.pop();
|
||||
if (event != nullptr)
|
||||
return event;
|
||||
|
||||
// Need to create a new event
|
||||
if (this->total_created_ >= SIZE) {
|
||||
// Pool is at capacity
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Use internal RAM for better performance
|
||||
RAMAllocator<T> allocator(RAMAllocator<T>::ALLOC_INTERNAL);
|
||||
event = allocator.allocate(1);
|
||||
|
||||
if (event == nullptr) {
|
||||
// Memory allocation failed
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Placement new to construct the object
|
||||
new (event) T();
|
||||
this->total_created_++;
|
||||
return event;
|
||||
}
|
||||
|
||||
// Return an event to the pool for reuse
|
||||
void release(T *event) {
|
||||
if (event != nullptr) {
|
||||
// Clean up the event's allocated memory
|
||||
event->release();
|
||||
this->free_list_.push(event);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
LockFreeQueue<T, SIZE> free_list_; // Free events ready for reuse
|
||||
uint8_t total_created_; // Total events created (high water mark, max 255)
|
||||
};
|
||||
|
||||
} // namespace esphome
|
||||
|
||||
#endif // defined(USE_ESP32) || defined(USE_LIBRETINY)
|
||||
@@ -76,23 +76,8 @@ static const uint16_t CRC16_1021_BE_LUT_H[] = {0x0000, 0x1231, 0x2462, 0x3653, 0
|
||||
0x9188, 0x83b9, 0xb5ea, 0xa7db, 0xd94c, 0xcb7d, 0xfd2e, 0xef1f};
|
||||
#endif
|
||||
|
||||
// STL backports
|
||||
|
||||
#if _GLIBCXX_RELEASE < 8
|
||||
std::string to_string(int value) { return str_snprintf("%d", 32, value); } // NOLINT
|
||||
std::string to_string(long value) { return str_snprintf("%ld", 32, value); } // NOLINT
|
||||
std::string to_string(long long value) { return str_snprintf("%lld", 32, value); } // NOLINT
|
||||
std::string to_string(unsigned value) { return str_snprintf("%u", 32, value); } // NOLINT
|
||||
std::string to_string(unsigned long value) { return str_snprintf("%lu", 32, value); } // NOLINT
|
||||
std::string to_string(unsigned long long value) { return str_snprintf("%llu", 32, value); } // NOLINT
|
||||
std::string to_string(float value) { return str_snprintf("%f", 32, value); }
|
||||
std::string to_string(double value) { return str_snprintf("%f", 32, value); }
|
||||
std::string to_string(long double value) { return str_snprintf("%Lf", 32, value); }
|
||||
#endif
|
||||
|
||||
// Mathematics
|
||||
|
||||
float lerp(float completion, float start, float end) { return start + (end - start) * completion; }
|
||||
uint8_t crc8(const uint8_t *data, uint8_t len) {
|
||||
uint8_t crc = 0;
|
||||
|
||||
|
||||
@@ -37,89 +37,18 @@
|
||||
#define ESPHOME_ALWAYS_INLINE __attribute__((always_inline))
|
||||
#define PACKED __attribute__((packed))
|
||||
|
||||
// Various functions can be constexpr in C++14, but not in C++11 (because their body isn't just a return statement).
|
||||
// Define a substitute constexpr keyword for those functions, until we can drop C++11 support.
|
||||
#if __cplusplus >= 201402L
|
||||
#define constexpr14 constexpr
|
||||
#else
|
||||
#define constexpr14 inline // constexpr implies inline
|
||||
#endif
|
||||
|
||||
namespace esphome {
|
||||
|
||||
/// @name STL backports
|
||||
///@{
|
||||
|
||||
// Backports for various STL features we like to use. Pull in the STL implementation wherever available, to avoid
|
||||
// ambiguity and to provide a uniform API.
|
||||
|
||||
// std::to_string() from C++11, available from libstdc++/g++ 8
|
||||
// See https://github.com/espressif/esp-idf/issues/1445
|
||||
#if _GLIBCXX_RELEASE >= 8
|
||||
// Keep "using" even after the removal of our backports, to avoid breaking existing code.
|
||||
using std::to_string;
|
||||
#else
|
||||
std::string to_string(int value); // NOLINT
|
||||
std::string to_string(long value); // NOLINT
|
||||
std::string to_string(long long value); // NOLINT
|
||||
std::string to_string(unsigned value); // NOLINT
|
||||
std::string to_string(unsigned long value); // NOLINT
|
||||
std::string to_string(unsigned long long value); // NOLINT
|
||||
std::string to_string(float value);
|
||||
std::string to_string(double value);
|
||||
std::string to_string(long double value);
|
||||
#endif
|
||||
|
||||
// std::is_trivially_copyable from C++11, implemented in libstdc++/g++ 5.1 (but minor releases can't be detected)
|
||||
#if _GLIBCXX_RELEASE >= 6
|
||||
using std::is_trivially_copyable;
|
||||
#else
|
||||
// Implementing this is impossible without compiler intrinsics, so don't bother. Invalid usage will be detected on
|
||||
// other variants that use a newer compiler anyway.
|
||||
// NOLINTNEXTLINE(readability-identifier-naming)
|
||||
template<typename T> struct is_trivially_copyable : public std::integral_constant<bool, true> {};
|
||||
#endif
|
||||
|
||||
// std::make_unique() from C++14
|
||||
#if __cpp_lib_make_unique >= 201304
|
||||
using std::make_unique;
|
||||
#else
|
||||
template<typename T, typename... Args> std::unique_ptr<T> make_unique(Args &&...args) {
|
||||
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
|
||||
}
|
||||
#endif
|
||||
|
||||
// std::enable_if_t from C++14
|
||||
#if __cplusplus >= 201402L
|
||||
using std::enable_if_t;
|
||||
#else
|
||||
template<bool B, class T = void> using enable_if_t = typename std::enable_if<B, T>::type;
|
||||
#endif
|
||||
|
||||
// std::clamp from C++17
|
||||
#if __cpp_lib_clamp >= 201603
|
||||
using std::clamp;
|
||||
#else
|
||||
template<typename T, typename Compare> constexpr const T &clamp(const T &v, const T &lo, const T &hi, Compare comp) {
|
||||
return comp(v, lo) ? lo : comp(hi, v) ? hi : v;
|
||||
}
|
||||
template<typename T> constexpr const T &clamp(const T &v, const T &lo, const T &hi) {
|
||||
return clamp(v, lo, hi, std::less<T>{});
|
||||
}
|
||||
#endif
|
||||
|
||||
// std::is_invocable from C++17
|
||||
#if __cpp_lib_is_invocable >= 201703
|
||||
using std::is_invocable;
|
||||
#else
|
||||
// https://stackoverflow.com/a/37161919/8924614
|
||||
template<class T, class... Args> struct is_invocable { // NOLINT(readability-identifier-naming)
|
||||
template<class U> static auto test(U *p) -> decltype((*p)(std::declval<Args>()...), void(), std::true_type());
|
||||
template<class U> static auto test(...) -> decltype(std::false_type());
|
||||
static constexpr auto value = decltype(test<T>(nullptr))::value; // NOLINT
|
||||
};
|
||||
#endif
|
||||
|
||||
// std::bit_cast from C++20
|
||||
#if __cpp_lib_bit_cast >= 201806
|
||||
using std::bit_cast;
|
||||
#else
|
||||
@@ -134,31 +63,29 @@ To bit_cast(const From &src) {
|
||||
return dst;
|
||||
}
|
||||
#endif
|
||||
using std::lerp;
|
||||
|
||||
// std::byteswap from C++23
|
||||
template<typename T> constexpr14 T byteswap(T n) {
|
||||
template<typename T> constexpr T byteswap(T n) {
|
||||
T m;
|
||||
for (size_t i = 0; i < sizeof(T); i++)
|
||||
reinterpret_cast<uint8_t *>(&m)[i] = reinterpret_cast<uint8_t *>(&n)[sizeof(T) - 1 - i];
|
||||
return m;
|
||||
}
|
||||
template<> constexpr14 uint8_t byteswap(uint8_t n) { return n; }
|
||||
template<> constexpr14 uint16_t byteswap(uint16_t n) { return __builtin_bswap16(n); }
|
||||
template<> constexpr14 uint32_t byteswap(uint32_t n) { return __builtin_bswap32(n); }
|
||||
template<> constexpr14 uint64_t byteswap(uint64_t n) { return __builtin_bswap64(n); }
|
||||
template<> constexpr14 int8_t byteswap(int8_t n) { return n; }
|
||||
template<> constexpr14 int16_t byteswap(int16_t n) { return __builtin_bswap16(n); }
|
||||
template<> constexpr14 int32_t byteswap(int32_t n) { return __builtin_bswap32(n); }
|
||||
template<> constexpr14 int64_t byteswap(int64_t n) { return __builtin_bswap64(n); }
|
||||
template<> constexpr uint8_t byteswap(uint8_t n) { return n; }
|
||||
template<> constexpr uint16_t byteswap(uint16_t n) { return __builtin_bswap16(n); }
|
||||
template<> constexpr uint32_t byteswap(uint32_t n) { return __builtin_bswap32(n); }
|
||||
template<> constexpr uint64_t byteswap(uint64_t n) { return __builtin_bswap64(n); }
|
||||
template<> constexpr int8_t byteswap(int8_t n) { return n; }
|
||||
template<> constexpr int16_t byteswap(int16_t n) { return __builtin_bswap16(n); }
|
||||
template<> constexpr int32_t byteswap(int32_t n) { return __builtin_bswap32(n); }
|
||||
template<> constexpr int64_t byteswap(int64_t n) { return __builtin_bswap64(n); }
|
||||
|
||||
///@}
|
||||
|
||||
/// @name Mathematics
|
||||
///@{
|
||||
|
||||
/// Linearly interpolate between \p start and \p end by \p completion (between 0 and 1).
|
||||
float lerp(float completion, float start, float end);
|
||||
|
||||
/// Remap \p value from the range (\p min, \p max) to (\p min_out, \p max_out).
|
||||
template<typename T, typename U> T remap(U value, U min, U max, T min_out, T max_out) {
|
||||
return (value - min) * (max_out - min_out) / (max - min) + min_out;
|
||||
@@ -203,8 +130,7 @@ constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, ui
|
||||
}
|
||||
|
||||
/// Encode a value from its constituent bytes (from most to least significant) in an array with length sizeof(T).
|
||||
template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
|
||||
constexpr14 T encode_value(const uint8_t *bytes) {
|
||||
template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0> constexpr T encode_value(const uint8_t *bytes) {
|
||||
T val = 0;
|
||||
for (size_t i = 0; i < sizeof(T); i++) {
|
||||
val <<= 8;
|
||||
@@ -214,12 +140,12 @@ constexpr14 T encode_value(const uint8_t *bytes) {
|
||||
}
|
||||
/// Encode a value from its constituent bytes (from most to least significant) in an std::array with length sizeof(T).
|
||||
template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
|
||||
constexpr14 T encode_value(const std::array<uint8_t, sizeof(T)> bytes) {
|
||||
constexpr T encode_value(const std::array<uint8_t, sizeof(T)> bytes) {
|
||||
return encode_value<T>(bytes.data());
|
||||
}
|
||||
/// Decode a value into its constituent bytes (from most to least significant).
|
||||
template<typename T, enable_if_t<std::is_unsigned<T>::value, int> = 0>
|
||||
constexpr14 std::array<uint8_t, sizeof(T)> decode_value(T val) {
|
||||
constexpr std::array<uint8_t, sizeof(T)> decode_value(T val) {
|
||||
std::array<uint8_t, sizeof(T)> ret{};
|
||||
for (size_t i = sizeof(T); i > 0; i--) {
|
||||
ret[i - 1] = val & 0xFF;
|
||||
@@ -246,7 +172,7 @@ inline uint32_t reverse_bits(uint32_t x) {
|
||||
}
|
||||
|
||||
/// Convert a value between host byte order and big endian (most significant byte first) order.
|
||||
template<typename T> constexpr14 T convert_big_endian(T val) {
|
||||
template<typename T> constexpr T convert_big_endian(T val) {
|
||||
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
|
||||
return byteswap(val);
|
||||
#else
|
||||
@@ -255,7 +181,7 @@ template<typename T> constexpr14 T convert_big_endian(T val) {
|
||||
}
|
||||
|
||||
/// Convert a value between host byte order and little endian (least significant byte first) order.
|
||||
template<typename T> constexpr14 T convert_little_endian(T val) {
|
||||
template<typename T> constexpr T convert_little_endian(T val) {
|
||||
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
|
||||
return val;
|
||||
#else
|
||||
@@ -276,9 +202,6 @@ bool str_startswith(const std::string &str, const std::string &start);
|
||||
/// Check whether a string ends with a value.
|
||||
bool str_endswith(const std::string &str, const std::string &end);
|
||||
|
||||
/// Convert the value to a string (added as extra overload so that to_string() can be used on all stringifiable types).
|
||||
inline std::string to_string(const std::string &val) { return val; }
|
||||
|
||||
/// Truncate a string to a specific length.
|
||||
std::string str_truncate(const std::string &str, size_t length);
|
||||
|
||||
|
||||
132
esphome/core/lock_free_queue.h
Normal file
132
esphome/core/lock_free_queue.h
Normal file
@@ -0,0 +1,132 @@
|
||||
#pragma once
|
||||
|
||||
#if defined(USE_ESP32) || defined(USE_LIBRETINY)
|
||||
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
|
||||
#if defined(USE_ESP32)
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/task.h>
|
||||
#elif defined(USE_LIBRETINY)
|
||||
#include <FreeRTOS.h>
|
||||
#include <task.h>
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Lock-free queue for single-producer single-consumer scenarios.
|
||||
* This allows one thread to push items and another to pop them without
|
||||
* blocking each other.
|
||||
*
|
||||
* This is a Single-Producer Single-Consumer (SPSC) lock-free ring buffer.
|
||||
* Available on platforms with FreeRTOS support (ESP32, LibreTiny).
|
||||
*
|
||||
* Common use cases:
|
||||
* - BLE events: BLE task produces, main loop consumes
|
||||
* - MQTT messages: main task produces, MQTT thread consumes
|
||||
*
|
||||
* @tparam T The type of elements stored in the queue (must be a pointer type)
|
||||
* @tparam SIZE The maximum number of elements (1-255, limited by uint8_t indices)
|
||||
*/
|
||||
|
||||
namespace esphome {
|
||||
|
||||
template<class T, uint8_t SIZE> class LockFreeQueue {
|
||||
public:
|
||||
LockFreeQueue() : head_(0), tail_(0), dropped_count_(0), task_to_notify_(nullptr) {}
|
||||
|
||||
bool push(T *element) {
|
||||
if (element == nullptr)
|
||||
return false;
|
||||
|
||||
uint8_t current_tail = tail_.load(std::memory_order_relaxed);
|
||||
uint8_t next_tail = (current_tail + 1) % SIZE;
|
||||
|
||||
// Read head before incrementing tail
|
||||
uint8_t head_before = head_.load(std::memory_order_acquire);
|
||||
|
||||
if (next_tail == head_before) {
|
||||
// Buffer full
|
||||
dropped_count_.fetch_add(1, std::memory_order_relaxed);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if queue was empty before push
|
||||
bool was_empty = (current_tail == head_before);
|
||||
|
||||
buffer_[current_tail] = element;
|
||||
tail_.store(next_tail, std::memory_order_release);
|
||||
|
||||
// Notify optimization: only notify if we need to
|
||||
if (task_to_notify_ != nullptr) {
|
||||
if (was_empty) {
|
||||
// Queue was empty - consumer might be going to sleep, must notify
|
||||
xTaskNotifyGive(task_to_notify_);
|
||||
} else {
|
||||
// Queue wasn't empty - check if consumer has caught up to previous tail
|
||||
uint8_t head_after = head_.load(std::memory_order_acquire);
|
||||
if (head_after == current_tail) {
|
||||
// Consumer just caught up to where tail was - might go to sleep, must notify
|
||||
// Note: There's a benign race here - between reading head_after and calling
|
||||
// xTaskNotifyGive(), the consumer could advance further. This would result
|
||||
// in an unnecessary wake-up, but is harmless and extremely rare in practice.
|
||||
xTaskNotifyGive(task_to_notify_);
|
||||
}
|
||||
// Otherwise: consumer is still behind, no need to notify
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
T *pop() {
|
||||
uint8_t current_head = head_.load(std::memory_order_relaxed);
|
||||
|
||||
if (current_head == tail_.load(std::memory_order_acquire)) {
|
||||
return nullptr; // Empty
|
||||
}
|
||||
|
||||
T *element = buffer_[current_head];
|
||||
head_.store((current_head + 1) % SIZE, std::memory_order_release);
|
||||
return element;
|
||||
}
|
||||
|
||||
size_t size() const {
|
||||
uint8_t tail = tail_.load(std::memory_order_acquire);
|
||||
uint8_t head = head_.load(std::memory_order_acquire);
|
||||
return (tail - head + SIZE) % SIZE;
|
||||
}
|
||||
|
||||
uint16_t get_and_reset_dropped_count() { return dropped_count_.exchange(0, std::memory_order_relaxed); }
|
||||
|
||||
void increment_dropped_count() { dropped_count_.fetch_add(1, std::memory_order_relaxed); }
|
||||
|
||||
bool empty() const { return head_.load(std::memory_order_acquire) == tail_.load(std::memory_order_acquire); }
|
||||
|
||||
bool full() const {
|
||||
uint8_t next_tail = (tail_.load(std::memory_order_relaxed) + 1) % SIZE;
|
||||
return next_tail == head_.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
// Set the FreeRTOS task handle to notify when items are pushed to the queue
|
||||
// This enables efficient wake-up of a consumer task that's waiting for data
|
||||
// @param task The FreeRTOS task handle to notify, or nullptr to disable notifications
|
||||
void set_task_to_notify(TaskHandle_t task) { task_to_notify_ = task; }
|
||||
|
||||
protected:
|
||||
T *buffer_[SIZE];
|
||||
// Atomic: written by producer (push/increment), read+reset by consumer (get_and_reset)
|
||||
std::atomic<uint16_t> dropped_count_; // 65535 max - more than enough for drop tracking
|
||||
// Atomic: written by consumer (pop), read by producer (push) to check if full
|
||||
// Using uint8_t limits queue size to 255 elements but saves memory and ensures
|
||||
// atomic operations are efficient on all platforms
|
||||
std::atomic<uint8_t> head_;
|
||||
// Atomic: written by producer (push), read by consumer (pop) to check if empty
|
||||
std::atomic<uint8_t> tail_;
|
||||
// Task handle for notification (optional)
|
||||
TaskHandle_t task_to_notify_;
|
||||
};
|
||||
|
||||
} // namespace esphome
|
||||
|
||||
#endif // defined(USE_ESP32) || defined(USE_LIBRETINY)
|
||||
92
esphome/core/runtime_stats.cpp
Normal file
92
esphome/core/runtime_stats.cpp
Normal file
@@ -0,0 +1,92 @@
|
||||
#include "esphome/core/runtime_stats.h"
|
||||
#include "esphome/core/component.h"
|
||||
#include <algorithm>
|
||||
|
||||
namespace esphome {
|
||||
|
||||
RuntimeStatsCollector runtime_stats;
|
||||
|
||||
void RuntimeStatsCollector::record_component_time(Component *component, uint32_t duration_ms, uint32_t current_time) {
|
||||
if (!this->enabled_ || component == nullptr)
|
||||
return;
|
||||
|
||||
// Check if we have cached the name for this component
|
||||
auto name_it = this->component_names_cache_.find(component);
|
||||
if (name_it == this->component_names_cache_.end()) {
|
||||
// First time seeing this component, cache its name
|
||||
const char *source = component->get_component_source();
|
||||
this->component_names_cache_[component] = source;
|
||||
this->component_stats_[source].record_time(duration_ms);
|
||||
} else {
|
||||
// Use cached name - no string operations, just map lookup
|
||||
this->component_stats_[name_it->second].record_time(duration_ms);
|
||||
}
|
||||
|
||||
// If next_log_time_ is 0, initialize it
|
||||
if (this->next_log_time_ == 0) {
|
||||
this->next_log_time_ = current_time + this->log_interval_;
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't print stats here anymore - let process_pending_stats handle it
|
||||
}
|
||||
|
||||
void RuntimeStatsCollector::log_stats_() {
|
||||
ESP_LOGI(RUNTIME_TAG, "Component Runtime Statistics");
|
||||
ESP_LOGI(RUNTIME_TAG, "Period stats (last %" PRIu32 "ms):", this->log_interval_);
|
||||
|
||||
// First collect stats we want to display
|
||||
std::vector<ComponentStatPair> stats_to_display;
|
||||
|
||||
for (const auto &it : this->component_stats_) {
|
||||
const ComponentRuntimeStats &stats = it.second;
|
||||
if (stats.get_period_count() > 0) {
|
||||
ComponentStatPair pair = {it.first, &stats};
|
||||
stats_to_display.push_back(pair);
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by period runtime (descending)
|
||||
std::sort(stats_to_display.begin(), stats_to_display.end(), std::greater<ComponentStatPair>());
|
||||
|
||||
// Log top components by period runtime
|
||||
for (const auto &it : stats_to_display) {
|
||||
const std::string &source = it.name;
|
||||
const ComponentRuntimeStats *stats = it.stats;
|
||||
|
||||
ESP_LOGI(RUNTIME_TAG, " %s: count=%" PRIu32 ", avg=%.2fms, max=%" PRIu32 "ms, total=%" PRIu32 "ms", source.c_str(),
|
||||
stats->get_period_count(), stats->get_period_avg_time_ms(), stats->get_period_max_time_ms(),
|
||||
stats->get_period_time_ms());
|
||||
}
|
||||
|
||||
// Log total stats since boot
|
||||
ESP_LOGI(RUNTIME_TAG, "Total stats (since boot):");
|
||||
|
||||
// Re-sort by total runtime for all-time stats
|
||||
std::sort(stats_to_display.begin(), stats_to_display.end(),
|
||||
[](const ComponentStatPair &a, const ComponentStatPair &b) {
|
||||
return a.stats->get_total_time_ms() > b.stats->get_total_time_ms();
|
||||
});
|
||||
|
||||
for (const auto &it : stats_to_display) {
|
||||
const std::string &source = it.name;
|
||||
const ComponentRuntimeStats *stats = it.stats;
|
||||
|
||||
ESP_LOGI(RUNTIME_TAG, " %s: count=%" PRIu32 ", avg=%.2fms, max=%" PRIu32 "ms, total=%" PRIu32 "ms", source.c_str(),
|
||||
stats->get_total_count(), stats->get_total_avg_time_ms(), stats->get_total_max_time_ms(),
|
||||
stats->get_total_time_ms());
|
||||
}
|
||||
}
|
||||
|
||||
void RuntimeStatsCollector::process_pending_stats(uint32_t current_time) {
|
||||
if (!this->enabled_ || this->next_log_time_ == 0)
|
||||
return;
|
||||
|
||||
if (current_time >= this->next_log_time_) {
|
||||
this->log_stats_();
|
||||
this->reset_stats_();
|
||||
this->next_log_time_ = current_time + this->log_interval_;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace esphome
|
||||
121
esphome/core/runtime_stats.h
Normal file
121
esphome/core/runtime_stats.h
Normal file
@@ -0,0 +1,121 @@
|
||||
#pragma once
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <cstdint>
|
||||
#include <algorithm>
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome {
|
||||
|
||||
static const char *const RUNTIME_TAG = "runtime";
|
||||
|
||||
class Component; // Forward declaration
|
||||
|
||||
class ComponentRuntimeStats {
|
||||
public:
|
||||
ComponentRuntimeStats()
|
||||
: period_count_(0),
|
||||
total_count_(0),
|
||||
period_time_ms_(0),
|
||||
total_time_ms_(0),
|
||||
period_max_time_ms_(0),
|
||||
total_max_time_ms_(0) {}
|
||||
|
||||
void record_time(uint32_t duration_ms) {
|
||||
// Update period counters
|
||||
this->period_count_++;
|
||||
this->period_time_ms_ += duration_ms;
|
||||
if (duration_ms > this->period_max_time_ms_)
|
||||
this->period_max_time_ms_ = duration_ms;
|
||||
|
||||
// Update total counters
|
||||
this->total_count_++;
|
||||
this->total_time_ms_ += duration_ms;
|
||||
if (duration_ms > this->total_max_time_ms_)
|
||||
this->total_max_time_ms_ = duration_ms;
|
||||
}
|
||||
|
||||
void reset_period_stats() {
|
||||
this->period_count_ = 0;
|
||||
this->period_time_ms_ = 0;
|
||||
this->period_max_time_ms_ = 0;
|
||||
}
|
||||
|
||||
// Period stats (reset each logging interval)
|
||||
uint32_t get_period_count() const { return this->period_count_; }
|
||||
uint32_t get_period_time_ms() const { return this->period_time_ms_; }
|
||||
uint32_t get_period_max_time_ms() const { return this->period_max_time_ms_; }
|
||||
float get_period_avg_time_ms() const {
|
||||
return this->period_count_ > 0 ? this->period_time_ms_ / static_cast<float>(this->period_count_) : 0.0f;
|
||||
}
|
||||
|
||||
// Total stats (persistent until reboot)
|
||||
uint32_t get_total_count() const { return this->total_count_; }
|
||||
uint32_t get_total_time_ms() const { return this->total_time_ms_; }
|
||||
uint32_t get_total_max_time_ms() const { return this->total_max_time_ms_; }
|
||||
float get_total_avg_time_ms() const {
|
||||
return this->total_count_ > 0 ? this->total_time_ms_ / static_cast<float>(this->total_count_) : 0.0f;
|
||||
}
|
||||
|
||||
protected:
|
||||
// Period stats (reset each logging interval)
|
||||
uint32_t period_count_;
|
||||
uint32_t period_time_ms_;
|
||||
uint32_t period_max_time_ms_;
|
||||
|
||||
// Total stats (persistent until reboot)
|
||||
uint32_t total_count_;
|
||||
uint32_t total_time_ms_;
|
||||
uint32_t total_max_time_ms_;
|
||||
};
|
||||
|
||||
// For sorting components by run time
|
||||
struct ComponentStatPair {
|
||||
std::string name;
|
||||
const ComponentRuntimeStats *stats;
|
||||
|
||||
bool operator>(const ComponentStatPair &other) const {
|
||||
// Sort by period time as that's what we're displaying in the logs
|
||||
return stats->get_period_time_ms() > other.stats->get_period_time_ms();
|
||||
}
|
||||
};
|
||||
|
||||
class RuntimeStatsCollector {
|
||||
public:
|
||||
RuntimeStatsCollector() : log_interval_(60000), next_log_time_(0), enabled_(true) {}
|
||||
|
||||
void set_log_interval(uint32_t log_interval) { this->log_interval_ = log_interval; }
|
||||
uint32_t get_log_interval() const { return this->log_interval_; }
|
||||
|
||||
void set_enabled(bool enabled) { this->enabled_ = enabled; }
|
||||
bool is_enabled() const { return this->enabled_; }
|
||||
|
||||
void record_component_time(Component *component, uint32_t duration_ms, uint32_t current_time);
|
||||
|
||||
// Process any pending stats printing (should be called after component loop)
|
||||
void process_pending_stats(uint32_t current_time);
|
||||
|
||||
protected:
|
||||
void log_stats_();
|
||||
|
||||
void reset_stats_() {
|
||||
for (auto &it : this->component_stats_) {
|
||||
it.second.reset_period_stats();
|
||||
}
|
||||
}
|
||||
|
||||
// Back to string keys, but we'll cache the source name per component
|
||||
std::map<std::string, ComponentRuntimeStats> component_stats_;
|
||||
std::map<Component *, std::string> component_names_cache_;
|
||||
uint32_t log_interval_;
|
||||
uint32_t next_log_time_;
|
||||
bool enabled_;
|
||||
};
|
||||
|
||||
// Global instance for runtime stats collection
|
||||
extern RuntimeStatsCollector runtime_stats;
|
||||
|
||||
} // namespace esphome
|
||||
@@ -7,6 +7,7 @@
|
||||
#include "esphome/core/log.h"
|
||||
#include <algorithm>
|
||||
#include <cinttypes>
|
||||
#include <cstring>
|
||||
|
||||
namespace esphome {
|
||||
|
||||
@@ -17,75 +18,138 @@ static const uint32_t MAX_LOGICALLY_DELETED_ITEMS = 10;
|
||||
// Uncomment to debug scheduler
|
||||
// #define ESPHOME_DEBUG_SCHEDULER
|
||||
|
||||
#ifdef ESPHOME_DEBUG_SCHEDULER
|
||||
// Helper to validate that a pointer looks like it's in static memory
|
||||
static void validate_static_string(const char *name) {
|
||||
if (name == nullptr)
|
||||
return;
|
||||
|
||||
// This is a heuristic check - stack and heap pointers are typically
|
||||
// much higher in memory than static data
|
||||
uintptr_t addr = reinterpret_cast<uintptr_t>(name);
|
||||
|
||||
// Create a stack variable to compare against
|
||||
int stack_var;
|
||||
uintptr_t stack_addr = reinterpret_cast<uintptr_t>(&stack_var);
|
||||
|
||||
// If the string pointer is near our stack variable, it's likely on the stack
|
||||
// Using 8KB range as ESP32 main task stack is typically 8192 bytes
|
||||
if (addr > (stack_addr - 0x2000) && addr < (stack_addr + 0x2000)) {
|
||||
ESP_LOGW(TAG,
|
||||
"WARNING: Scheduler name '%s' at %p appears to be on the stack - this is unsafe!\n"
|
||||
" Stack reference at %p",
|
||||
name, name, &stack_var);
|
||||
}
|
||||
|
||||
// Also check if it might be on the heap by seeing if it's in a very different range
|
||||
// This is platform-specific but generally heap is allocated far from static memory
|
||||
static const char *static_str = "test";
|
||||
uintptr_t static_addr = reinterpret_cast<uintptr_t>(static_str);
|
||||
|
||||
// If the address is very far from known static memory, it might be heap
|
||||
if (addr > static_addr + 0x100000 || (static_addr > 0x100000 && addr < static_addr - 0x100000)) {
|
||||
ESP_LOGW(TAG, "WARNING: Scheduler name '%s' at %p might be on heap (static ref at %p)", name, name, static_str);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// A note on locking: the `lock_` lock protects the `items_` and `to_add_` containers. It must be taken when writing to
|
||||
// them (i.e. when adding/removing items, but not when changing items). As items are only deleted from the loop task,
|
||||
// iterating over them from the loop task is fine; but iterating from any other context requires the lock to be held to
|
||||
// avoid the main thread modifying the list while it is being accessed.
|
||||
|
||||
void HOT Scheduler::set_timeout(Component *component, const std::string &name, uint32_t timeout,
|
||||
std::function<void()> func) {
|
||||
const auto now = this->millis_();
|
||||
// Common implementation for both timeout and interval
|
||||
void HOT Scheduler::set_timer_common_(Component *component, SchedulerItem::Type type, bool is_static_string,
|
||||
const void *name_ptr, uint32_t delay, std::function<void()> func) {
|
||||
// Get the name as const char*
|
||||
const char *name_cstr =
|
||||
is_static_string ? static_cast<const char *>(name_ptr) : static_cast<const std::string *>(name_ptr)->c_str();
|
||||
|
||||
if (!name.empty())
|
||||
this->cancel_timeout(component, name);
|
||||
// Cancel existing timer if name is not empty
|
||||
if (name_cstr != nullptr && name_cstr[0] != '\0') {
|
||||
this->cancel_item_(component, name_cstr, type);
|
||||
}
|
||||
|
||||
if (timeout == SCHEDULER_DONT_RUN)
|
||||
if (delay == SCHEDULER_DONT_RUN)
|
||||
return;
|
||||
|
||||
const auto now = this->millis_();
|
||||
|
||||
// Create and populate the scheduler item
|
||||
auto item = make_unique<SchedulerItem>();
|
||||
item->component = component;
|
||||
item->name = name;
|
||||
item->type = SchedulerItem::TIMEOUT;
|
||||
item->next_execution_ = now + timeout;
|
||||
item->set_name(name_cstr, !is_static_string);
|
||||
item->type = type;
|
||||
item->callback = std::move(func);
|
||||
item->remove = false;
|
||||
|
||||
// Type-specific setup
|
||||
if (type == SchedulerItem::INTERVAL) {
|
||||
item->interval = delay;
|
||||
// Calculate random offset (0 to interval/2)
|
||||
uint32_t offset = (delay != 0) ? (random_uint32() % delay) / 2 : 0;
|
||||
item->next_execution_ = now + offset;
|
||||
} else {
|
||||
item->interval = 0;
|
||||
item->next_execution_ = now + delay;
|
||||
}
|
||||
|
||||
#ifdef ESPHOME_DEBUG_SCHEDULER
|
||||
ESP_LOGD(TAG, "set_timeout(name='%s/%s', timeout=%" PRIu32 ")", item->get_source(), name.c_str(), timeout);
|
||||
// Validate static strings in debug mode
|
||||
if (is_static_string && name_cstr != nullptr) {
|
||||
validate_static_string(name_cstr);
|
||||
}
|
||||
|
||||
// Debug logging
|
||||
const char *type_str = (type == SchedulerItem::TIMEOUT) ? "timeout" : "interval";
|
||||
if (type == SchedulerItem::TIMEOUT) {
|
||||
ESP_LOGD(TAG, "set_%s(name='%s/%s', %s=%" PRIu32 ")", type_str, item->get_source(),
|
||||
name_cstr ? name_cstr : "(null)", type_str, delay);
|
||||
} else {
|
||||
ESP_LOGD(TAG, "set_%s(name='%s/%s', %s=%" PRIu32 ", offset=%" PRIu32 ")", type_str, item->get_source(),
|
||||
name_cstr ? name_cstr : "(null)", type_str, delay, static_cast<uint32_t>(item->next_execution_ - now));
|
||||
}
|
||||
#endif
|
||||
|
||||
this->push_(std::move(item));
|
||||
}
|
||||
|
||||
void HOT Scheduler::set_timeout(Component *component, const char *name, uint32_t timeout, std::function<void()> func) {
|
||||
this->set_timer_common_(component, SchedulerItem::TIMEOUT, true, name, timeout, std::move(func));
|
||||
}
|
||||
|
||||
void HOT Scheduler::set_timeout(Component *component, const std::string &name, uint32_t timeout,
|
||||
std::function<void()> func) {
|
||||
this->set_timer_common_(component, SchedulerItem::TIMEOUT, false, &name, timeout, std::move(func));
|
||||
}
|
||||
bool HOT Scheduler::cancel_timeout(Component *component, const std::string &name) {
|
||||
return this->cancel_item_(component, name, SchedulerItem::TIMEOUT);
|
||||
}
|
||||
bool HOT Scheduler::cancel_timeout(Component *component, const char *name) {
|
||||
return this->cancel_item_(component, name, SchedulerItem::TIMEOUT);
|
||||
}
|
||||
void HOT Scheduler::set_interval(Component *component, const std::string &name, uint32_t interval,
|
||||
std::function<void()> func) {
|
||||
const auto now = this->millis_();
|
||||
this->set_timer_common_(component, SchedulerItem::INTERVAL, false, &name, interval, std::move(func));
|
||||
}
|
||||
|
||||
if (!name.empty())
|
||||
this->cancel_interval(component, name);
|
||||
|
||||
if (interval == SCHEDULER_DONT_RUN)
|
||||
return;
|
||||
|
||||
// only put offset in lower half
|
||||
uint32_t offset = 0;
|
||||
if (interval != 0)
|
||||
offset = (random_uint32() % interval) / 2;
|
||||
|
||||
auto item = make_unique<SchedulerItem>();
|
||||
item->component = component;
|
||||
item->name = name;
|
||||
item->type = SchedulerItem::INTERVAL;
|
||||
item->interval = interval;
|
||||
item->next_execution_ = now + offset;
|
||||
item->callback = std::move(func);
|
||||
item->remove = false;
|
||||
#ifdef ESPHOME_DEBUG_SCHEDULER
|
||||
ESP_LOGD(TAG, "set_interval(name='%s/%s', interval=%" PRIu32 ", offset=%" PRIu32 ")", item->get_source(),
|
||||
name.c_str(), interval, offset);
|
||||
#endif
|
||||
this->push_(std::move(item));
|
||||
void HOT Scheduler::set_interval(Component *component, const char *name, uint32_t interval,
|
||||
std::function<void()> func) {
|
||||
this->set_timer_common_(component, SchedulerItem::INTERVAL, true, name, interval, std::move(func));
|
||||
}
|
||||
bool HOT Scheduler::cancel_interval(Component *component, const std::string &name) {
|
||||
return this->cancel_item_(component, name, SchedulerItem::INTERVAL);
|
||||
}
|
||||
bool HOT Scheduler::cancel_interval(Component *component, const char *name) {
|
||||
return this->cancel_item_(component, name, SchedulerItem::INTERVAL);
|
||||
}
|
||||
|
||||
struct RetryArgs {
|
||||
std::function<RetryResult(uint8_t)> func;
|
||||
uint8_t retry_countdown;
|
||||
uint32_t current_interval;
|
||||
Component *component;
|
||||
std::string name;
|
||||
std::string name; // Keep as std::string since retry uses it dynamically
|
||||
float backoff_increase_factor;
|
||||
Scheduler *scheduler;
|
||||
};
|
||||
@@ -154,7 +218,7 @@ void HOT Scheduler::call() {
|
||||
if (now - last_print > 2000) {
|
||||
last_print = now;
|
||||
std::vector<std::unique_ptr<SchedulerItem>> old_items;
|
||||
ESP_LOGD(TAG, "Items: count=%u, now=%" PRIu64 " (%u, %" PRIu32 ")", this->items_.size(), now, this->millis_major_,
|
||||
ESP_LOGD(TAG, "Items: count=%zu, now=%" PRIu64 " (%u, %" PRIu32 ")", this->items_.size(), now, this->millis_major_,
|
||||
this->last_millis_);
|
||||
while (!this->empty_()) {
|
||||
this->lock_.lock();
|
||||
@@ -162,8 +226,9 @@ void HOT Scheduler::call() {
|
||||
this->pop_raw_();
|
||||
this->lock_.unlock();
|
||||
|
||||
const char *name = item->get_name();
|
||||
ESP_LOGD(TAG, " %s '%s/%s' interval=%" PRIu32 " next_execution in %" PRIu64 "ms at %" PRIu64,
|
||||
item->get_type_str(), item->get_source(), item->name.c_str(), item->interval,
|
||||
item->get_type_str(), item->get_source(), name ? name : "(null)", item->interval,
|
||||
item->next_execution_ - now, item->next_execution_);
|
||||
|
||||
old_items.push_back(std::move(item));
|
||||
@@ -220,9 +285,10 @@ void HOT Scheduler::call() {
|
||||
App.set_current_component(item->component);
|
||||
|
||||
#ifdef ESPHOME_DEBUG_SCHEDULER
|
||||
const char *item_name = item->get_name();
|
||||
ESP_LOGV(TAG, "Running %s '%s/%s' with interval=%" PRIu32 " next_execution=%" PRIu64 " (now=%" PRIu64 ")",
|
||||
item->get_type_str(), item->get_source(), item->name.c_str(), item->interval, item->next_execution_,
|
||||
now);
|
||||
item->get_type_str(), item->get_source(), item_name ? item_name : "(null)", item->interval,
|
||||
item->next_execution_, now);
|
||||
#endif
|
||||
|
||||
// Warning: During callback(), a lot of stuff can happen, including:
|
||||
@@ -298,19 +364,33 @@ void HOT Scheduler::push_(std::unique_ptr<Scheduler::SchedulerItem> item) {
|
||||
LockGuard guard{this->lock_};
|
||||
this->to_add_.push_back(std::move(item));
|
||||
}
|
||||
bool HOT Scheduler::cancel_item_(Component *component, const std::string &name, Scheduler::SchedulerItem::Type type) {
|
||||
// Common implementation for cancel operations
|
||||
bool HOT Scheduler::cancel_item_common_(Component *component, bool is_static_string, const void *name_ptr,
|
||||
SchedulerItem::Type type) {
|
||||
// Get the name as const char*
|
||||
const char *name_cstr =
|
||||
is_static_string ? static_cast<const char *>(name_ptr) : static_cast<const std::string *>(name_ptr)->c_str();
|
||||
|
||||
// Handle null or empty names
|
||||
if (name_cstr == nullptr)
|
||||
return false;
|
||||
|
||||
// obtain lock because this function iterates and can be called from non-loop task context
|
||||
LockGuard guard{this->lock_};
|
||||
bool ret = false;
|
||||
|
||||
for (auto &it : this->items_) {
|
||||
if (it->component == component && it->name == name && it->type == type && !it->remove) {
|
||||
const char *item_name = it->get_name();
|
||||
if (it->component == component && item_name != nullptr && strcmp(name_cstr, item_name) == 0 && it->type == type &&
|
||||
!it->remove) {
|
||||
to_remove_++;
|
||||
it->remove = true;
|
||||
ret = true;
|
||||
}
|
||||
}
|
||||
for (auto &it : this->to_add_) {
|
||||
if (it->component == component && it->name == name && it->type == type) {
|
||||
const char *item_name = it->get_name();
|
||||
if (it->component == component && item_name != nullptr && strcmp(name_cstr, item_name) == 0 && it->type == type) {
|
||||
it->remove = true;
|
||||
ret = true;
|
||||
}
|
||||
@@ -318,6 +398,15 @@ bool HOT Scheduler::cancel_item_(Component *component, const std::string &name,
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool HOT Scheduler::cancel_item_(Component *component, const std::string &name, Scheduler::SchedulerItem::Type type) {
|
||||
return this->cancel_item_common_(component, false, &name, type);
|
||||
}
|
||||
|
||||
bool HOT Scheduler::cancel_item_(Component *component, const char *name, SchedulerItem::Type type) {
|
||||
return this->cancel_item_common_(component, true, name, type);
|
||||
}
|
||||
|
||||
uint64_t Scheduler::millis_() {
|
||||
// Get the current 32-bit millis value
|
||||
const uint32_t now = millis();
|
||||
|
||||
@@ -12,11 +12,40 @@ class Component;
|
||||
|
||||
class Scheduler {
|
||||
public:
|
||||
// Public API - accepts std::string for backward compatibility
|
||||
void set_timeout(Component *component, const std::string &name, uint32_t timeout, std::function<void()> func);
|
||||
bool cancel_timeout(Component *component, const std::string &name);
|
||||
void set_interval(Component *component, const std::string &name, uint32_t interval, std::function<void()> func);
|
||||
bool cancel_interval(Component *component, const std::string &name);
|
||||
|
||||
/** Set a timeout with a const char* name.
|
||||
*
|
||||
* IMPORTANT: The provided name pointer must remain valid for the lifetime of the scheduler item.
|
||||
* This means the name should be:
|
||||
* - A string literal (e.g., "update")
|
||||
* - A static const char* variable
|
||||
* - A pointer with lifetime >= the scheduled task
|
||||
*
|
||||
* For dynamic strings, use the std::string overload instead.
|
||||
*/
|
||||
void set_timeout(Component *component, const char *name, uint32_t timeout, std::function<void()> func);
|
||||
|
||||
bool cancel_timeout(Component *component, const std::string &name);
|
||||
bool cancel_timeout(Component *component, const char *name);
|
||||
|
||||
void set_interval(Component *component, const std::string &name, uint32_t interval, std::function<void()> func);
|
||||
|
||||
/** Set an interval with a const char* name.
|
||||
*
|
||||
* IMPORTANT: The provided name pointer must remain valid for the lifetime of the scheduler item.
|
||||
* This means the name should be:
|
||||
* - A string literal (e.g., "update")
|
||||
* - A static const char* variable
|
||||
* - A pointer with lifetime >= the scheduled task
|
||||
*
|
||||
* For dynamic strings, use the std::string overload instead.
|
||||
*/
|
||||
void set_interval(Component *component, const char *name, uint32_t interval, std::function<void()> func);
|
||||
|
||||
bool cancel_interval(Component *component, const std::string &name);
|
||||
bool cancel_interval(Component *component, const char *name);
|
||||
void set_retry(Component *component, const std::string &name, uint32_t initial_wait_time, uint8_t max_attempts,
|
||||
std::function<RetryResult(uint8_t)> func, float backoff_increase_factor = 1.0f);
|
||||
bool cancel_retry(Component *component, const std::string &name);
|
||||
@@ -36,32 +65,86 @@ class Scheduler {
|
||||
// with a 16-bit rollover counter to create a 64-bit time that won't roll over for
|
||||
// billions of years. This ensures correct scheduling even when devices run for months.
|
||||
uint64_t next_execution_;
|
||||
std::string name;
|
||||
std::function<void()> callback;
|
||||
enum Type : uint8_t { TIMEOUT, INTERVAL } type;
|
||||
bool remove;
|
||||
|
||||
static bool cmp(const std::unique_ptr<SchedulerItem> &a, const std::unique_ptr<SchedulerItem> &b);
|
||||
const char *get_type_str() {
|
||||
switch (this->type) {
|
||||
case SchedulerItem::INTERVAL:
|
||||
return "interval";
|
||||
case SchedulerItem::TIMEOUT:
|
||||
return "timeout";
|
||||
default:
|
||||
return "";
|
||||
// Optimized name storage using tagged union
|
||||
union {
|
||||
const char *static_name; // For string literals (no allocation)
|
||||
char *dynamic_name; // For allocated strings
|
||||
} name_;
|
||||
|
||||
std::function<void()> callback;
|
||||
|
||||
// Bit-packed fields to minimize padding
|
||||
enum Type : uint8_t { TIMEOUT, INTERVAL } type : 1;
|
||||
bool remove : 1;
|
||||
bool name_is_dynamic : 1; // True if name was dynamically allocated (needs delete[])
|
||||
// 5 bits padding
|
||||
|
||||
// Constructor
|
||||
SchedulerItem()
|
||||
: component(nullptr), interval(0), next_execution_(0), type(TIMEOUT), remove(false), name_is_dynamic(false) {
|
||||
name_.static_name = nullptr;
|
||||
}
|
||||
|
||||
// Destructor to clean up dynamic names
|
||||
~SchedulerItem() {
|
||||
if (name_is_dynamic) {
|
||||
delete[] name_.dynamic_name;
|
||||
}
|
||||
}
|
||||
const char *get_source() {
|
||||
return this->component != nullptr ? this->component->get_component_source() : "unknown";
|
||||
|
||||
// Delete copy operations to prevent accidental copies
|
||||
SchedulerItem(const SchedulerItem &) = delete;
|
||||
SchedulerItem &operator=(const SchedulerItem &) = delete;
|
||||
|
||||
// Default move operations
|
||||
SchedulerItem(SchedulerItem &&) = default;
|
||||
SchedulerItem &operator=(SchedulerItem &&) = default;
|
||||
|
||||
// Helper to get the name regardless of storage type
|
||||
const char *get_name() const { return name_is_dynamic ? name_.dynamic_name : name_.static_name; }
|
||||
|
||||
// Helper to set name with proper ownership
|
||||
void set_name(const char *name, bool make_copy = false) {
|
||||
// Clean up old dynamic name if any
|
||||
if (name_is_dynamic && name_.dynamic_name) {
|
||||
delete[] name_.dynamic_name;
|
||||
name_is_dynamic = false;
|
||||
}
|
||||
|
||||
if (!name || !name[0]) {
|
||||
name_.static_name = nullptr;
|
||||
} else if (make_copy) {
|
||||
// Make a copy for dynamic strings
|
||||
size_t len = strlen(name);
|
||||
name_.dynamic_name = new char[len + 1];
|
||||
memcpy(name_.dynamic_name, name, len + 1);
|
||||
name_is_dynamic = true;
|
||||
} else {
|
||||
// Use static string directly
|
||||
name_.static_name = name;
|
||||
}
|
||||
}
|
||||
|
||||
static bool cmp(const std::unique_ptr<SchedulerItem> &a, const std::unique_ptr<SchedulerItem> &b);
|
||||
const char *get_type_str() const { return (type == TIMEOUT) ? "timeout" : "interval"; }
|
||||
const char *get_source() const { return component ? component->get_component_source() : "unknown"; }
|
||||
};
|
||||
|
||||
// Common implementation for both timeout and interval
|
||||
void set_timer_common_(Component *component, SchedulerItem::Type type, bool is_static_string, const void *name_ptr,
|
||||
uint32_t delay, std::function<void()> func);
|
||||
|
||||
uint64_t millis_();
|
||||
void cleanup_();
|
||||
void pop_raw_();
|
||||
void push_(std::unique_ptr<SchedulerItem> item);
|
||||
// Common implementation for cancel operations
|
||||
bool cancel_item_common_(Component *component, bool is_static_string, const void *name_ptr, SchedulerItem::Type type);
|
||||
|
||||
bool cancel_item_(Component *component, const std::string &name, SchedulerItem::Type type);
|
||||
bool cancel_item_(Component *component, const char *name, SchedulerItem::Type type);
|
||||
|
||||
bool empty_() {
|
||||
this->cleanup_();
|
||||
return this->items_.empty();
|
||||
|
||||
@@ -617,7 +617,7 @@ def set_cpp_standard(standard: str) -> None:
|
||||
"""Set C++ standard with compiler flag `-std={standard}`."""
|
||||
CORE.add_build_unflag("-std=gnu++11")
|
||||
CORE.add_build_unflag("-std=gnu++14")
|
||||
CORE.add_build_unflag("-std=gnu++20")
|
||||
CORE.add_build_unflag("-std=gnu++17")
|
||||
CORE.add_build_unflag("-std=gnu++23")
|
||||
CORE.add_build_unflag("-std=gnu++2a")
|
||||
CORE.add_build_unflag("-std=gnu++2b")
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
dependencies:
|
||||
esp-tflite-micro:
|
||||
git: https://github.com/espressif/esp-tflite-micro.git
|
||||
version: v1.3.1
|
||||
esp32_camera:
|
||||
git: https://github.com/espressif/esp32-camera.git
|
||||
version: v2.0.15
|
||||
mdns:
|
||||
git: https://github.com/espressif/esp-protocols.git
|
||||
version: mdns-v1.8.2
|
||||
path: components/mdns
|
||||
espressif/esp-tflite-micro:
|
||||
version: 1.3.3~1
|
||||
espressif/esp32-camera:
|
||||
version: 2.0.15
|
||||
espressif/mdns:
|
||||
version: 1.8.2
|
||||
espressif/esp_wifi_remote:
|
||||
version: 0.10.2
|
||||
rules:
|
||||
- if: "idf_version >=5.0"
|
||||
- if: "target in [esp32h2, esp32p4]"
|
||||
espressif/eppp_link:
|
||||
version: 0.2.0
|
||||
rules:
|
||||
- if: "target in [esp32h2, esp32p4]"
|
||||
espressif/esp_hosted:
|
||||
version: 2.0.11
|
||||
rules:
|
||||
- if: "target in [esp32h2, esp32p4]"
|
||||
|
||||
@@ -47,11 +47,11 @@ lib_deps =
|
||||
lvgl/lvgl@8.4.0 ; lvgl
|
||||
build_flags =
|
||||
-DESPHOME_LOG_LEVEL=ESPHOME_LOG_LEVEL_VERY_VERBOSE
|
||||
-std=gnu++17
|
||||
-std=gnu++20
|
||||
build_unflags =
|
||||
-std=gnu++11
|
||||
-std=gnu++14
|
||||
-std=gnu++20
|
||||
-std=gnu++17
|
||||
-std=gnu++23
|
||||
-std=gnu++2a
|
||||
-std=gnu++2b
|
||||
@@ -560,7 +560,7 @@ lib_deps =
|
||||
build_flags =
|
||||
${common.build_flags}
|
||||
-DUSE_HOST
|
||||
-std=c++17
|
||||
-std=c++20
|
||||
build_unflags =
|
||||
${common.build_unflags}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
pylint==3.3.7
|
||||
flake8==7.3.0 # also change in .pre-commit-config.yaml when updating
|
||||
ruff==0.12.0 # also change in .pre-commit-config.yaml when updating
|
||||
ruff==0.12.1 # also change in .pre-commit-config.yaml when updating
|
||||
pyupgrade==3.20.0 # also change in .pre-commit-config.yaml when updating
|
||||
pre-commit
|
||||
|
||||
|
||||
@@ -1034,7 +1034,7 @@ SOURCE_BOTH = 0
|
||||
SOURCE_SERVER = 1
|
||||
SOURCE_CLIENT = 2
|
||||
|
||||
RECEIVE_CASES: dict[int, str] = {}
|
||||
RECEIVE_CASES: dict[int, tuple[str, str | None]] = {}
|
||||
|
||||
ifdefs: dict[str, str] = {}
|
||||
|
||||
@@ -1208,8 +1208,6 @@ def build_service_message_type(
|
||||
func = f"on_{snake}"
|
||||
hout += f"virtual void {func}(const {mt.name} &value){{}};\n"
|
||||
case = ""
|
||||
if ifdef is not None:
|
||||
case += f"#ifdef {ifdef}\n"
|
||||
case += f"{mt.name} msg;\n"
|
||||
case += "msg.decode(msg_data, msg_size);\n"
|
||||
if log:
|
||||
@@ -1217,10 +1215,9 @@ def build_service_message_type(
|
||||
case += f'ESP_LOGVV(TAG, "{func}: %s", msg.dump().c_str());\n'
|
||||
case += "#endif\n"
|
||||
case += f"this->{func}(msg);\n"
|
||||
if ifdef is not None:
|
||||
case += "#endif\n"
|
||||
case += "break;"
|
||||
RECEIVE_CASES[id_] = case
|
||||
# Store the ifdef with the case for later use
|
||||
RECEIVE_CASES[id_] = (case, ifdef)
|
||||
|
||||
# Only close ifdef if we opened it
|
||||
if ifdef is not None:
|
||||
@@ -1379,18 +1376,21 @@ def main() -> None:
|
||||
cases = list(RECEIVE_CASES.items())
|
||||
cases.sort()
|
||||
hpp += " protected:\n"
|
||||
hpp += " bool read_message(uint32_t msg_size, uint32_t msg_type, uint8_t *msg_data) override;\n"
|
||||
out = f"bool {class_name}::read_message(uint32_t msg_size, uint32_t msg_type, uint8_t *msg_data) {{\n"
|
||||
hpp += " void read_message(uint32_t msg_size, uint32_t msg_type, uint8_t *msg_data) override;\n"
|
||||
out = f"void {class_name}::read_message(uint32_t msg_size, uint32_t msg_type, uint8_t *msg_data) {{\n"
|
||||
out += " switch (msg_type) {\n"
|
||||
for i, case in cases:
|
||||
c = f"case {i}: {{\n"
|
||||
c += indent(case) + "\n"
|
||||
c += "}"
|
||||
out += indent(c, " ") + "\n"
|
||||
for i, (case, ifdef) in cases:
|
||||
if ifdef is not None:
|
||||
out += f"#ifdef {ifdef}\n"
|
||||
c = f" case {i}: {{\n"
|
||||
c += indent(case, " ") + "\n"
|
||||
c += " }"
|
||||
out += c + "\n"
|
||||
if ifdef is not None:
|
||||
out += "#endif\n"
|
||||
out += " default:\n"
|
||||
out += " return false;\n"
|
||||
out += " break;\n"
|
||||
out += " }\n"
|
||||
out += " return true;\n"
|
||||
out += "}\n"
|
||||
cpp += out
|
||||
hpp += "};\n"
|
||||
|
||||
15
tests/components/esp32_hosted/common.yaml
Normal file
15
tests/components/esp32_hosted/common.yaml
Normal file
@@ -0,0 +1,15 @@
|
||||
esp32_hosted:
|
||||
variant: ESP32C6
|
||||
slot: 1
|
||||
active_high: true
|
||||
reset_pin: GPIO15
|
||||
cmd_pin: GPIO13
|
||||
clk_pin: GPIO12
|
||||
d0_pin: GPIO11
|
||||
d1_pin: GPIO10
|
||||
d2_pin: GPIO9
|
||||
d3_pin: GPIO8
|
||||
|
||||
wifi:
|
||||
ssid: MySSID
|
||||
password: password1
|
||||
1
tests/components/esp32_hosted/test.esp32-p4-idf.yaml
Normal file
1
tests/components/esp32_hosted/test.esp32-p4-idf.yaml
Normal file
@@ -0,0 +1 @@
|
||||
<<: !include common.yaml
|
||||
89
tests/integration/fixtures/api_vv_logging.yaml
Normal file
89
tests/integration/fixtures/api_vv_logging.yaml
Normal file
@@ -0,0 +1,89 @@
|
||||
esphome:
|
||||
name: vv-logging-test
|
||||
|
||||
host:
|
||||
|
||||
api:
|
||||
|
||||
logger:
|
||||
level: VERY_VERBOSE
|
||||
# Enable VV logging for API components where the issue occurs
|
||||
logs:
|
||||
api.connection: VERY_VERBOSE
|
||||
api.service: VERY_VERBOSE
|
||||
api.proto: VERY_VERBOSE
|
||||
sensor: VERY_VERBOSE
|
||||
|
||||
# Create many sensors that update frequently to generate API traffic
|
||||
# This will cause many messages to be batched and sent, triggering the
|
||||
# code path where VV logging could cause buffer corruption
|
||||
sensor:
|
||||
- platform: template
|
||||
name: "Test Sensor 1"
|
||||
lambda: 'return millis() / 1000.0;'
|
||||
update_interval: 50ms
|
||||
unit_of_measurement: "s"
|
||||
|
||||
- platform: template
|
||||
name: "Test Sensor 2"
|
||||
lambda: 'return (millis() / 1000.0) + 10;'
|
||||
update_interval: 50ms
|
||||
unit_of_measurement: "s"
|
||||
|
||||
- platform: template
|
||||
name: "Test Sensor 3"
|
||||
lambda: 'return (millis() / 1000.0) + 20;'
|
||||
update_interval: 50ms
|
||||
unit_of_measurement: "s"
|
||||
|
||||
- platform: template
|
||||
name: "Test Sensor 4"
|
||||
lambda: 'return (millis() / 1000.0) + 30;'
|
||||
update_interval: 50ms
|
||||
unit_of_measurement: "s"
|
||||
|
||||
- platform: template
|
||||
name: "Test Sensor 5"
|
||||
lambda: 'return (millis() / 1000.0) + 40;'
|
||||
update_interval: 50ms
|
||||
unit_of_measurement: "s"
|
||||
|
||||
- platform: template
|
||||
name: "Test Sensor 6"
|
||||
lambda: 'return (millis() / 1000.0) + 50;'
|
||||
update_interval: 50ms
|
||||
unit_of_measurement: "s"
|
||||
|
||||
- platform: template
|
||||
name: "Test Sensor 7"
|
||||
lambda: 'return (millis() / 1000.0) + 60;'
|
||||
update_interval: 50ms
|
||||
unit_of_measurement: "s"
|
||||
|
||||
- platform: template
|
||||
name: "Test Sensor 8"
|
||||
lambda: 'return (millis() / 1000.0) + 70;'
|
||||
update_interval: 50ms
|
||||
unit_of_measurement: "s"
|
||||
|
||||
- platform: template
|
||||
name: "Test Sensor 9"
|
||||
lambda: 'return (millis() / 1000.0) + 80;'
|
||||
update_interval: 50ms
|
||||
unit_of_measurement: "s"
|
||||
|
||||
- platform: template
|
||||
name: "Test Sensor 10"
|
||||
lambda: 'return (millis() / 1000.0) + 90;'
|
||||
update_interval: 50ms
|
||||
unit_of_measurement: "s"
|
||||
|
||||
# Add some binary sensors too for variety
|
||||
binary_sensor:
|
||||
- platform: template
|
||||
name: "Test Binary 1"
|
||||
lambda: 'return (millis() / 1000) % 2 == 0;'
|
||||
|
||||
- platform: template
|
||||
name: "Test Binary 2"
|
||||
lambda: 'return (millis() / 1000) % 3 == 0;'
|
||||
164
tests/integration/fixtures/scheduler_string_test.yaml
Normal file
164
tests/integration/fixtures/scheduler_string_test.yaml
Normal file
@@ -0,0 +1,164 @@
|
||||
esphome:
|
||||
name: scheduler-string-test
|
||||
on_boot:
|
||||
priority: -100
|
||||
then:
|
||||
- logger.log: "Starting scheduler string tests"
|
||||
platformio_options:
|
||||
build_flags:
|
||||
- "-DESPHOME_DEBUG_SCHEDULER" # Enable scheduler debug logging
|
||||
|
||||
host:
|
||||
api:
|
||||
logger:
|
||||
level: VERBOSE
|
||||
|
||||
globals:
|
||||
- id: timeout_counter
|
||||
type: int
|
||||
initial_value: '0'
|
||||
- id: interval_counter
|
||||
type: int
|
||||
initial_value: '0'
|
||||
- id: dynamic_counter
|
||||
type: int
|
||||
initial_value: '0'
|
||||
- id: static_tests_done
|
||||
type: bool
|
||||
initial_value: 'false'
|
||||
- id: dynamic_tests_done
|
||||
type: bool
|
||||
initial_value: 'false'
|
||||
- id: results_reported
|
||||
type: bool
|
||||
initial_value: 'false'
|
||||
|
||||
script:
|
||||
- id: test_static_strings
|
||||
then:
|
||||
- logger.log: "Testing static string timeouts and intervals"
|
||||
- lambda: |-
|
||||
auto *component1 = id(test_sensor1);
|
||||
// Test 1: Static string literals with set_timeout
|
||||
App.scheduler.set_timeout(component1, "static_timeout_1", 50, []() {
|
||||
ESP_LOGI("test", "Static timeout 1 fired");
|
||||
id(timeout_counter) += 1;
|
||||
});
|
||||
|
||||
// Test 2: Static const char* with set_timeout
|
||||
static const char* TIMEOUT_NAME = "static_timeout_2";
|
||||
App.scheduler.set_timeout(component1, TIMEOUT_NAME, 100, []() {
|
||||
ESP_LOGI("test", "Static timeout 2 fired");
|
||||
id(timeout_counter) += 1;
|
||||
});
|
||||
|
||||
// Test 3: Static string literal with set_interval
|
||||
App.scheduler.set_interval(component1, "static_interval_1", 200, []() {
|
||||
ESP_LOGI("test", "Static interval 1 fired, count: %d", id(interval_counter));
|
||||
id(interval_counter) += 1;
|
||||
if (id(interval_counter) >= 3) {
|
||||
App.scheduler.cancel_interval(id(test_sensor1), "static_interval_1");
|
||||
ESP_LOGI("test", "Cancelled static interval 1");
|
||||
}
|
||||
});
|
||||
|
||||
// Test 4: Empty string (should be handled safely)
|
||||
App.scheduler.set_timeout(component1, "", 150, []() {
|
||||
ESP_LOGI("test", "Empty string timeout fired");
|
||||
});
|
||||
|
||||
// Test 5: Cancel timeout with const char* literal
|
||||
App.scheduler.set_timeout(component1, "cancel_static_timeout", 5000, []() {
|
||||
ESP_LOGI("test", "This static timeout should be cancelled");
|
||||
});
|
||||
// Cancel using const char* directly
|
||||
App.scheduler.cancel_timeout(component1, "cancel_static_timeout");
|
||||
ESP_LOGI("test", "Cancelled static timeout using const char*");
|
||||
|
||||
- id: test_dynamic_strings
|
||||
then:
|
||||
- logger.log: "Testing dynamic string timeouts and intervals"
|
||||
- lambda: |-
|
||||
auto *component2 = id(test_sensor2);
|
||||
|
||||
// Test 6: Dynamic string with set_timeout (std::string)
|
||||
std::string dynamic_name = "dynamic_timeout_" + std::to_string(id(dynamic_counter)++);
|
||||
App.scheduler.set_timeout(component2, dynamic_name, 100, []() {
|
||||
ESP_LOGI("test", "Dynamic timeout fired");
|
||||
id(timeout_counter) += 1;
|
||||
});
|
||||
|
||||
// Test 7: Dynamic string with set_interval
|
||||
std::string interval_name = "dynamic_interval_" + std::to_string(id(dynamic_counter)++);
|
||||
App.scheduler.set_interval(component2, interval_name, 250, [interval_name]() {
|
||||
ESP_LOGI("test", "Dynamic interval fired: %s", interval_name.c_str());
|
||||
id(interval_counter) += 1;
|
||||
if (id(interval_counter) >= 6) {
|
||||
App.scheduler.cancel_interval(id(test_sensor2), interval_name);
|
||||
ESP_LOGI("test", "Cancelled dynamic interval");
|
||||
}
|
||||
});
|
||||
|
||||
// Test 8: Cancel with different string object but same content
|
||||
std::string cancel_name = "cancel_test";
|
||||
App.scheduler.set_timeout(component2, cancel_name, 2000, []() {
|
||||
ESP_LOGI("test", "This should be cancelled");
|
||||
});
|
||||
|
||||
// Cancel using a different string object
|
||||
std::string cancel_name_2 = "cancel_test";
|
||||
App.scheduler.cancel_timeout(component2, cancel_name_2);
|
||||
ESP_LOGI("test", "Cancelled timeout using different string object");
|
||||
|
||||
- id: report_results
|
||||
then:
|
||||
- lambda: |-
|
||||
ESP_LOGI("test", "Final results - Timeouts: %d, Intervals: %d",
|
||||
id(timeout_counter), id(interval_counter));
|
||||
|
||||
sensor:
|
||||
- platform: template
|
||||
name: Test Sensor 1
|
||||
id: test_sensor1
|
||||
lambda: return 1.0;
|
||||
update_interval: never
|
||||
|
||||
- platform: template
|
||||
name: Test Sensor 2
|
||||
id: test_sensor2
|
||||
lambda: return 2.0;
|
||||
update_interval: never
|
||||
|
||||
interval:
|
||||
# Run static string tests after boot - using script to run once
|
||||
- interval: 0.1s
|
||||
then:
|
||||
- if:
|
||||
condition:
|
||||
lambda: 'return id(static_tests_done) == false;'
|
||||
then:
|
||||
- lambda: 'id(static_tests_done) = true;'
|
||||
- script.execute: test_static_strings
|
||||
- logger.log: "Started static string tests"
|
||||
|
||||
# Run dynamic string tests after static tests
|
||||
- interval: 0.2s
|
||||
then:
|
||||
- if:
|
||||
condition:
|
||||
lambda: 'return id(static_tests_done) && !id(dynamic_tests_done);'
|
||||
then:
|
||||
- lambda: 'id(dynamic_tests_done) = true;'
|
||||
- delay: 0.2s
|
||||
- script.execute: test_dynamic_strings
|
||||
|
||||
# Report results after all tests
|
||||
- interval: 0.2s
|
||||
then:
|
||||
- if:
|
||||
condition:
|
||||
lambda: 'return id(dynamic_tests_done) && !id(results_reported);'
|
||||
then:
|
||||
- lambda: 'id(results_reported) = true;'
|
||||
- delay: 1s
|
||||
- script.execute: report_results
|
||||
83
tests/integration/test_api_vv_logging.py
Normal file
83
tests/integration/test_api_vv_logging.py
Normal file
@@ -0,0 +1,83 @@
|
||||
"""Integration test for API with VERY_VERBOSE logging to verify no buffer corruption."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from typing import Any
|
||||
|
||||
from aioesphomeapi import LogLevel
|
||||
import pytest
|
||||
|
||||
from .types import APIClientConnectedFactory, RunCompiledFunction
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_api_vv_logging(
|
||||
yaml_config: str,
|
||||
run_compiled: RunCompiledFunction,
|
||||
api_client_connected: APIClientConnectedFactory,
|
||||
) -> None:
|
||||
"""Test that VERY_VERBOSE logging doesn't cause buffer corruption with API messages."""
|
||||
|
||||
# Track that we're receiving VV log messages and sensor updates
|
||||
vv_logs_received = 0
|
||||
sensor_updates_received = 0
|
||||
errors_detected = []
|
||||
|
||||
def on_log(msg: Any) -> None:
|
||||
"""Capture log messages."""
|
||||
nonlocal vv_logs_received
|
||||
# msg is a SubscribeLogsResponse object with 'message' attribute
|
||||
# The message field is always bytes
|
||||
message_text = msg.message.decode("utf-8", errors="replace")
|
||||
|
||||
# Only count VV logs specifically
|
||||
if "[VV]" in message_text:
|
||||
vv_logs_received += 1
|
||||
|
||||
# Check for assertion or error messages
|
||||
if "assert" in message_text.lower() or "error" in message_text.lower():
|
||||
errors_detected.append(message_text)
|
||||
|
||||
# Write, compile and run the ESPHome device
|
||||
async with run_compiled(yaml_config), api_client_connected() as client:
|
||||
# Subscribe to VERY_VERBOSE logs - this enables the code path that could cause corruption
|
||||
client.subscribe_logs(on_log, log_level=LogLevel.LOG_LEVEL_VERY_VERBOSE)
|
||||
|
||||
# Wait for device to be ready
|
||||
device_info = await client.device_info()
|
||||
assert device_info is not None
|
||||
assert device_info.name == "vv-logging-test"
|
||||
|
||||
# Subscribe to sensor states
|
||||
states = {}
|
||||
|
||||
def on_state(state):
|
||||
nonlocal sensor_updates_received
|
||||
sensor_updates_received += 1
|
||||
states[state.key] = state
|
||||
|
||||
client.subscribe_states(on_state)
|
||||
|
||||
# List entities to find our test sensors
|
||||
entity_info, _ = await client.list_entities_services()
|
||||
|
||||
# Count sensors
|
||||
sensor_count = sum(1 for e in entity_info if hasattr(e, "unit_of_measurement"))
|
||||
assert sensor_count >= 10, f"Expected at least 10 sensors, got {sensor_count}"
|
||||
|
||||
# Wait for sensor updates to flow with VV logging active
|
||||
# The sensors update every 50ms, so we should get many updates
|
||||
await asyncio.sleep(0.25)
|
||||
|
||||
# Verify we received both VV logs and sensor updates
|
||||
assert vv_logs_received > 0, "Expected to receive VERY_VERBOSE log messages"
|
||||
assert sensor_updates_received > 10, (
|
||||
f"Expected many sensor updates, got {sensor_updates_received}"
|
||||
)
|
||||
|
||||
# Check for any errors
|
||||
if errors_detected:
|
||||
pytest.fail(f"Errors detected during test: {errors_detected}")
|
||||
|
||||
# The test passes if we didn't hit any assertions or buffer corruption
|
||||
166
tests/integration/test_scheduler_string_test.py
Normal file
166
tests/integration/test_scheduler_string_test.py
Normal file
@@ -0,0 +1,166 @@
|
||||
"""Test scheduler string optimization with static and dynamic strings."""
|
||||
|
||||
import asyncio
|
||||
import re
|
||||
|
||||
import pytest
|
||||
|
||||
from .types import APIClientConnectedFactory, RunCompiledFunction
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_scheduler_string_test(
|
||||
yaml_config: str,
|
||||
run_compiled: RunCompiledFunction,
|
||||
api_client_connected: APIClientConnectedFactory,
|
||||
) -> None:
|
||||
"""Test that scheduler handles both static and dynamic strings correctly."""
|
||||
# Track counts
|
||||
timeout_count = 0
|
||||
interval_count = 0
|
||||
|
||||
# Events for each test completion
|
||||
static_timeout_1_fired = asyncio.Event()
|
||||
static_timeout_2_fired = asyncio.Event()
|
||||
static_interval_fired = asyncio.Event()
|
||||
static_interval_cancelled = asyncio.Event()
|
||||
empty_string_timeout_fired = asyncio.Event()
|
||||
static_timeout_cancelled = asyncio.Event()
|
||||
dynamic_timeout_fired = asyncio.Event()
|
||||
dynamic_interval_fired = asyncio.Event()
|
||||
cancel_test_done = asyncio.Event()
|
||||
final_results_logged = asyncio.Event()
|
||||
|
||||
# Track interval counts
|
||||
static_interval_count = 0
|
||||
dynamic_interval_count = 0
|
||||
|
||||
def on_log_line(line: str) -> None:
|
||||
nonlocal \
|
||||
timeout_count, \
|
||||
interval_count, \
|
||||
static_interval_count, \
|
||||
dynamic_interval_count
|
||||
|
||||
# Strip ANSI color codes
|
||||
clean_line = re.sub(r"\x1b\[[0-9;]*m", "", line)
|
||||
|
||||
# Check for static timeout completions
|
||||
if "Static timeout 1 fired" in clean_line:
|
||||
static_timeout_1_fired.set()
|
||||
timeout_count += 1
|
||||
|
||||
elif "Static timeout 2 fired" in clean_line:
|
||||
static_timeout_2_fired.set()
|
||||
timeout_count += 1
|
||||
|
||||
# Check for static interval
|
||||
elif "Static interval 1 fired" in clean_line:
|
||||
match = re.search(r"count: (\d+)", clean_line)
|
||||
if match:
|
||||
static_interval_count = int(match.group(1))
|
||||
static_interval_fired.set()
|
||||
|
||||
elif "Cancelled static interval 1" in clean_line:
|
||||
static_interval_cancelled.set()
|
||||
|
||||
# Check for empty string timeout
|
||||
elif "Empty string timeout fired" in clean_line:
|
||||
empty_string_timeout_fired.set()
|
||||
|
||||
# Check for static timeout cancellation
|
||||
elif "Cancelled static timeout using const char*" in clean_line:
|
||||
static_timeout_cancelled.set()
|
||||
|
||||
# Check for dynamic string tests
|
||||
elif "Dynamic timeout fired" in clean_line:
|
||||
dynamic_timeout_fired.set()
|
||||
timeout_count += 1
|
||||
|
||||
elif "Dynamic interval fired" in clean_line:
|
||||
dynamic_interval_count += 1
|
||||
dynamic_interval_fired.set()
|
||||
|
||||
# Check for cancel test
|
||||
elif "Cancelled timeout using different string object" in clean_line:
|
||||
cancel_test_done.set()
|
||||
|
||||
# Check for final results
|
||||
elif "Final results" in clean_line:
|
||||
match = re.search(r"Timeouts: (\d+), Intervals: (\d+)", clean_line)
|
||||
if match:
|
||||
timeout_count = int(match.group(1))
|
||||
interval_count = int(match.group(2))
|
||||
final_results_logged.set()
|
||||
|
||||
async with (
|
||||
run_compiled(yaml_config, line_callback=on_log_line),
|
||||
api_client_connected() as client,
|
||||
):
|
||||
# Verify we can connect
|
||||
device_info = await client.device_info()
|
||||
assert device_info is not None
|
||||
assert device_info.name == "scheduler-string-test"
|
||||
|
||||
# Wait for static string tests
|
||||
try:
|
||||
await asyncio.wait_for(static_timeout_1_fired.wait(), timeout=0.5)
|
||||
except asyncio.TimeoutError:
|
||||
pytest.fail("Static timeout 1 did not fire within 0.5 seconds")
|
||||
|
||||
try:
|
||||
await asyncio.wait_for(static_timeout_2_fired.wait(), timeout=0.5)
|
||||
except asyncio.TimeoutError:
|
||||
pytest.fail("Static timeout 2 did not fire within 0.5 seconds")
|
||||
|
||||
try:
|
||||
await asyncio.wait_for(static_interval_fired.wait(), timeout=1.0)
|
||||
except asyncio.TimeoutError:
|
||||
pytest.fail("Static interval did not fire within 1 second")
|
||||
|
||||
try:
|
||||
await asyncio.wait_for(static_interval_cancelled.wait(), timeout=2.0)
|
||||
except asyncio.TimeoutError:
|
||||
pytest.fail("Static interval was not cancelled within 2 seconds")
|
||||
|
||||
# Verify static interval ran at least 3 times
|
||||
assert static_interval_count >= 2, (
|
||||
f"Expected static interval to run at least 3 times, got {static_interval_count + 1}"
|
||||
)
|
||||
|
||||
# Verify static timeout was cancelled
|
||||
assert static_timeout_cancelled.is_set(), (
|
||||
"Static timeout should have been cancelled"
|
||||
)
|
||||
|
||||
# Wait for dynamic string tests
|
||||
try:
|
||||
await asyncio.wait_for(dynamic_timeout_fired.wait(), timeout=1.0)
|
||||
except asyncio.TimeoutError:
|
||||
pytest.fail("Dynamic timeout did not fire within 1 second")
|
||||
|
||||
try:
|
||||
await asyncio.wait_for(dynamic_interval_fired.wait(), timeout=1.5)
|
||||
except asyncio.TimeoutError:
|
||||
pytest.fail("Dynamic interval did not fire within 1.5 seconds")
|
||||
|
||||
# Wait for cancel test
|
||||
try:
|
||||
await asyncio.wait_for(cancel_test_done.wait(), timeout=1.0)
|
||||
except asyncio.TimeoutError:
|
||||
pytest.fail("Cancel test did not complete within 1 second")
|
||||
|
||||
# Wait for final results
|
||||
try:
|
||||
await asyncio.wait_for(final_results_logged.wait(), timeout=4.0)
|
||||
except asyncio.TimeoutError:
|
||||
pytest.fail("Final results were not logged within 4 seconds")
|
||||
|
||||
# Verify results
|
||||
assert timeout_count >= 3, f"Expected at least 3 timeouts, got {timeout_count}"
|
||||
assert interval_count >= 3, (
|
||||
f"Expected at least 3 interval fires, got {interval_count}"
|
||||
)
|
||||
|
||||
# Empty string timeout DOES fire (scheduler accepts empty names)
|
||||
assert empty_string_timeout_fired.is_set(), "Empty string timeout should fire"
|
||||
@@ -15,4 +15,3 @@ packages:
|
||||
file: $component_test_file
|
||||
vars:
|
||||
component_test_file: $component_test_file
|
||||
|
||||
|
||||
Reference in New Issue
Block a user