Compare commits
742
Commits
repeater-v1.17.1
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
95be305143 | ||
|
|
0d72bcd44c | ||
|
|
e3c54039fe | ||
|
|
9652199464 | ||
|
|
cbb830b2b3 | ||
|
|
66a01a227f | ||
|
|
19728e43a5 | ||
|
|
6ec03df241 | ||
|
|
b30cda7936 | ||
|
|
ac49cd6621 | ||
|
|
1f9bbc71d8 | ||
|
|
6e47ba6fa6 | ||
|
|
b7249f449a | ||
|
|
769139999d | ||
|
|
cac3249e41 | ||
|
|
dcf10d1c86 | ||
|
|
ad701588d7 | ||
|
|
dad7186c5b | ||
|
|
54a88a307a | ||
|
|
6c45b94783 | ||
|
|
ce02d5a787 | ||
|
|
98f9e81681 | ||
|
|
69b335d700 | ||
|
|
1ad8ca230a | ||
|
|
b72fd0dd5e | ||
|
|
26ae484af8 | ||
|
|
961547c7d2 | ||
|
|
dbdae14566 | ||
|
|
de92ca9ba2 | ||
|
|
d05ed2122c | ||
|
|
84f6fa03b2 | ||
|
|
c8d75947f8 | ||
|
|
1171d8f972 | ||
|
|
0b38bfd81a | ||
|
|
7949fb4274 | ||
|
|
41d3ba93ea | ||
|
|
0a88dda5f8 | ||
|
|
4b2da2924f | ||
|
|
27949062df | ||
|
|
a69e97583e | ||
|
|
f6e792f1bb | ||
|
|
a80e68186d | ||
|
|
7216a50ec3 | ||
|
|
f8476f94f2 | ||
|
|
8c11154a3a | ||
|
|
2b35435aae | ||
|
|
04afba03ba | ||
|
|
6cba768181 | ||
|
|
391ddfcef2 | ||
|
|
df445548ad | ||
|
|
0153ad1b6f | ||
|
|
21efb56ae7 | ||
|
|
fe520673ae | ||
|
|
d1c71522b8 | ||
|
|
3a3f69fb5d | ||
|
|
7416193a76 | ||
|
|
4a4d4b169f | ||
|
|
9c4bdcae42 | ||
|
|
65f7965955 | ||
|
|
63e0bb2a36 | ||
|
|
cc0598b1a4 | ||
|
|
da8310ed0d | ||
|
|
96cbd7333a | ||
|
|
166863f690 | ||
|
|
a6f2a3050e | ||
|
|
f7bd88c1c8 | ||
|
|
d9c7b9c008 | ||
|
|
01d66a66ce | ||
|
|
2e8aea5c44 | ||
|
|
5970edc99c | ||
|
|
fbefa417b9 | ||
|
|
de721bcb4b | ||
|
|
562b93364d | ||
|
|
d15c057c4f | ||
|
|
ec55b7e8c3 | ||
|
|
f2dd7e8082 | ||
|
|
14550b5d66 | ||
|
|
0c760a65ac | ||
|
|
415bd01e4e | ||
|
|
60e7d1f868 | ||
|
|
05a2beb229 | ||
|
|
d23fa74642 | ||
|
|
d22005a6fd | ||
|
|
97618f223f | ||
|
|
41dfcef65f | ||
|
|
fe44e9a6cd | ||
|
|
51e733e500 | ||
|
|
287b562c47 | ||
|
|
0caecba931 | ||
|
|
cf70a95da4 | ||
|
|
0b38eab008 | ||
|
|
c93f5d906d | ||
|
|
81d7f600d8 | ||
|
|
845a228209 | ||
|
|
9165590d13 | ||
|
|
9080d8339d | ||
|
|
ee935a9fc7 | ||
|
|
73c1a7beb2 | ||
|
|
46d33bd2b0 | ||
|
|
fb210a8441 | ||
|
|
407cb9abac | ||
|
|
a029863d66 | ||
|
|
227edb9c63 | ||
|
|
b8ce87c6ff | ||
|
|
0c06994d1f | ||
|
|
b4d2601c8f | ||
|
|
3a7140fd51 | ||
|
|
232c2bb791 | ||
|
|
dc13c5b286 | ||
|
|
d1e893f692 | ||
|
|
4813340a69 | ||
|
|
637b0d78b7 | ||
|
|
5f8788c4b4 | ||
|
|
228e7a129b | ||
|
|
aaca10958e | ||
|
|
8d3e554ca3 | ||
|
|
3cb3a458ce | ||
|
|
b7b397b9b1 | ||
|
|
e6a3184423 | ||
|
|
a2dacb805d | ||
|
|
d4afea1eb3 | ||
|
|
9e70d32f79 | ||
|
|
8ec702e9b6 | ||
|
|
0d3cb6051d | ||
|
|
03d06d5176 | ||
|
|
e3200086c4 | ||
|
|
b06fd957b9 | ||
|
|
daaf0c2267 | ||
|
|
507842cea2 | ||
|
|
ad4f53016c | ||
|
|
b1e4e65c52 | ||
|
|
6fe0c0f8e1 | ||
|
|
d1d04f98ef | ||
|
|
3c7d947887 | ||
|
|
be9d278a96 | ||
|
|
84e4136a84 | ||
|
|
8d0b0dd164 | ||
|
|
40b6ccc0f2 | ||
|
|
7762588e58 | ||
|
|
bf0ccfe2eb | ||
|
|
6ff32a57da | ||
|
|
75737f548e | ||
|
|
8c06b34156 | ||
|
|
87679ba526 | ||
|
|
cb09798408 | ||
|
|
d1be1cbef0 | ||
|
|
8c88340e82 | ||
|
|
ace5230ff0 | ||
|
|
0ed9ba5724 | ||
|
|
65eca34c5a | ||
|
|
798b719caf | ||
|
|
f349ead541 | ||
|
|
092da136dc | ||
|
|
7de440c0d3 | ||
|
|
d901822bdf | ||
|
|
cefd4c76cf | ||
|
|
5662e79a78 | ||
|
|
067fb64994 | ||
|
|
b3b227b773 | ||
|
|
401fd6c037 | ||
|
|
f02d9d9e47 | ||
|
|
e1a445b967 | ||
|
|
06719e6877 | ||
|
|
790f4d3f08 | ||
|
|
8f0da87099 | ||
|
|
084a0700b2 | ||
|
|
66d404eac8 | ||
|
|
1c4b237d73 | ||
|
|
095bd8c311 | ||
|
|
474021f10a | ||
|
|
684d960e6f | ||
|
|
6ce010fbfe | ||
|
|
3e84250e44 | ||
|
|
41540f1642 | ||
|
|
98cfba42b9 | ||
|
|
573037fd77 | ||
|
|
46606a4b03 | ||
|
|
be36c02d5b | ||
|
|
8d56dcc877 | ||
|
|
d4fcba9dd0 | ||
|
|
f40e13a425 | ||
|
|
9cafb91f7f | ||
|
|
16d4cbfd1d | ||
|
|
8b16d8eb5e | ||
|
|
822bea7b7c | ||
|
|
41eb344511 | ||
|
|
3da13dd91a | ||
|
|
8363b347b7 | ||
|
|
6291f9156a | ||
|
|
ca5ccddc85 | ||
|
|
faabf34950 | ||
|
|
f5cbc18b83 | ||
|
|
1c9adb46cb | ||
|
|
6b3da8a2b1 | ||
|
|
978f2662c6 | ||
|
|
aa30e3734e | ||
|
|
3f23ba9b2d | ||
|
|
64f75005b5 | ||
|
|
017005d1cf | ||
|
|
b2e46335e5 | ||
|
|
6b34ae96df | ||
|
|
93d165dd8c | ||
|
|
539b55b772 | ||
|
|
d41aee832e | ||
|
|
a134188c62 | ||
|
|
bd21096ce0 | ||
|
|
47959b8960 | ||
|
|
5303703750 | ||
|
|
a0c5854b59 | ||
|
|
e9d197cf79 | ||
|
|
e58be9ab11 | ||
|
|
dea38936d7 | ||
|
|
81afafcb35 | ||
|
|
0243af712e | ||
|
|
9f10793f7a | ||
|
|
2f00b0e83a | ||
|
|
5c40bf745a | ||
|
|
9ea4b83ed1 | ||
|
|
5f63ba303c | ||
|
|
4b4f1b25ef | ||
|
|
02081ba500 | ||
|
|
7474e0c036 | ||
|
|
c0ccb9c7ff | ||
|
|
7d5499e9eb | ||
|
|
683680d83b | ||
|
|
c5a0673d67 | ||
|
|
1e135e0bd2 | ||
|
|
a8518433e2 | ||
|
|
4343409886 | ||
|
|
9af19c870c | ||
|
|
afb56bb976 | ||
|
|
287c5e21cf | ||
|
|
a8f0c3dca6 | ||
|
|
2ced8502a0 | ||
|
|
7159a00f05 | ||
|
|
278c1b8c8a | ||
|
|
38eb3d99e4 | ||
|
|
10f0349207 | ||
|
|
c1eaa6f98b | ||
|
|
1cfa726cdd | ||
|
|
654d53f34c | ||
|
|
94a5526b66 | ||
|
|
ea1cf46cf4 | ||
|
|
f0c48e2b46 | ||
|
|
5dd6e7ac6a | ||
|
|
548b96d15c | ||
|
|
e3029de6e4 | ||
|
|
88ef08c6d5 | ||
|
|
f7887324e5 | ||
|
|
7508a94415 | ||
|
|
d652164151 | ||
|
|
922e2e9ce9 | ||
|
|
59ecf9b72a | ||
|
|
910bee899a | ||
|
|
8d755a2fff | ||
|
|
dae56e1bbd | ||
|
|
221e1bd7ba | ||
|
|
af1714db08 | ||
|
|
90ffa57c5f | ||
|
|
978b6e01be | ||
|
|
d32c8caa37 | ||
|
|
65ff32a10a | ||
|
|
439d40ac04 | ||
|
|
b53558c3a7 | ||
|
|
9a076ee5c6 | ||
|
|
d7d17dd230 | ||
|
|
93254adbca | ||
|
|
0676aeb201 | ||
|
|
351a1ad20c | ||
|
|
fee7a5a4c1 | ||
|
|
b09b12d4ef | ||
|
|
54b90cbdfa | ||
|
|
e184a81423 | ||
|
|
d8b5724c38 | ||
|
|
bd4be350c5 | ||
|
|
1d88a709bd | ||
|
|
54b18df118 | ||
|
|
f39fa53aea | ||
|
|
180c22ba79 | ||
|
|
33eb7434f9 | ||
|
|
ce4c755308 | ||
|
|
790cf23466 | ||
|
|
65c6a42627 | ||
|
|
022ca93c8f | ||
|
|
322427e815 | ||
|
|
8fa4ef8b65 | ||
|
|
a1528cc36f | ||
|
|
7ab21ebe2d | ||
|
|
b2997ef0d3 | ||
|
|
b714aa2419 | ||
|
|
d1e27f5b21 | ||
|
|
c60490f741 | ||
|
|
15c58df0d9 | ||
|
|
4d93dfbc04 | ||
|
|
8a33082b59 | ||
|
|
40f2ed331a | ||
|
|
2270b931fa | ||
|
|
f889b7d8a2 | ||
|
|
ab64c87c38 | ||
|
|
d5ad9e38e9 | ||
|
|
8e0e5b8110 | ||
|
|
4d3178d82a | ||
|
|
a36ab23469 | ||
|
|
e258ebc98f | ||
|
|
6f9b3ba155 | ||
|
|
dd61005f3a | ||
|
|
ad6f6a92f2 | ||
|
|
3ecc0f45d4 | ||
|
|
d65a6b9667 | ||
|
|
81fa5d7f5a | ||
|
|
f0ea4620ca | ||
|
|
e8be1ad6b2 | ||
|
|
2797dd7ba1 | ||
|
|
8723caf0df | ||
|
|
ff4c28985c | ||
|
|
fded88ac6a | ||
|
|
ff0ce69c16 | ||
|
|
e97de59b57 | ||
|
|
97a6ff714c | ||
|
|
4558890275 | ||
|
|
dace1a32d4 | ||
|
|
afbab2de16 | ||
|
|
d1d06b92ab | ||
|
|
8c4769d1ed | ||
|
|
730056bd88 | ||
|
|
75ea17ea46 | ||
|
|
2e6c8824eb | ||
|
|
99b4114627 | ||
|
|
e296c49580 | ||
|
|
24778ac957 | ||
|
|
3412bf3a0f | ||
|
|
adb01c473e | ||
|
|
c2d01f3c41 | ||
|
|
1a582db63d | ||
|
|
dcb67b9a5e | ||
|
|
8b55e36f95 | ||
|
|
ad0324d354 | ||
|
|
edb94d3fdc | ||
|
|
b9fa77ed69 | ||
|
|
36f2b1d163 | ||
|
|
bae1b189d4 | ||
|
|
99656142f1 | ||
|
|
80edef6c02 | ||
|
|
1754c7964e | ||
|
|
c7aa648a14 | ||
|
|
2f6ed76b84 | ||
|
|
5f967d818a | ||
|
|
b2bde37fe4 | ||
|
|
757e84647c | ||
|
|
3cc3dd49a9 | ||
|
|
277cae93ac | ||
|
|
c9fa617c38 | ||
|
|
b3043807c3 | ||
|
|
c2c5de52be | ||
|
|
a763fd4c91 | ||
|
|
6dc7f2b047 | ||
|
|
7bbc19b010 | ||
|
|
da9329b096 | ||
|
|
0769d68ed6 | ||
|
|
bb84f293b7 | ||
|
|
05cd36d2ec | ||
|
|
04a6bb3318 | ||
|
|
df8e962998 | ||
|
|
a4f1601df3 | ||
|
|
77889e61dc | ||
|
|
59663042a8 | ||
|
|
69313d98ae | ||
|
|
da15d8e685 | ||
|
|
ac25e7d956 | ||
|
|
3448d06943 | ||
|
|
bcc5ccfbf0 | ||
|
|
18acb44839 | ||
|
|
cafc5b3bb4 | ||
|
|
174582e8a1 | ||
|
|
5ec71b8abf | ||
|
|
1726ff0e99 | ||
|
|
5f2deeb875 | ||
|
|
3012453c86 | ||
|
|
1c3d50fce7 | ||
|
|
e18b3855ce | ||
|
|
47c550bedd | ||
|
|
d288425ebf | ||
|
|
513b77a8a8 | ||
|
|
f4b0a50580 | ||
|
|
58721ae6fb | ||
|
|
223389e936 | ||
|
|
7369c64752 | ||
|
|
68b8163fe7 | ||
|
|
83b1dccc13 | ||
|
|
f7b2acf2a0 | ||
|
|
aa2ba5aea7 | ||
|
|
4a2d84c7a8 | ||
|
|
c35be853c7 | ||
|
|
04db619dc7 | ||
|
|
c073b0db0d | ||
|
|
4de1151d1a | ||
|
|
02cda9f9e3 | ||
|
|
2546d47055 | ||
|
|
f14517029c | ||
|
|
aaf44308af | ||
|
|
48aae4072d | ||
|
|
2b5da0785b | ||
|
|
c10ea278ff | ||
|
|
ec565e06bf | ||
|
|
a531441def | ||
|
|
e77c10976f | ||
|
|
bad907cf02 | ||
|
|
e616e3c942 | ||
|
|
3b126edd48 | ||
|
|
f0140e0a6c | ||
|
|
92ef99de94 | ||
|
|
49a79dc8db | ||
|
|
63166e9aa4 | ||
|
|
e54fb5275a | ||
|
|
63924e7f7c | ||
|
|
cd9565be3a | ||
|
|
67ecf94491 | ||
|
|
556140c802 | ||
|
|
f352ceaf3e | ||
|
|
d07e11d7ed | ||
|
|
ed1a763c49 | ||
|
|
58dac7899b | ||
|
|
3f1057c9a0 | ||
|
|
b463f4dbd1 | ||
|
|
74d290f40c | ||
|
|
02821f140c | ||
|
|
0335245362 | ||
|
|
76e64d87df | ||
|
|
f993bc25fe | ||
|
|
a1b5655af1 | ||
|
|
971b509f4f | ||
|
|
3d583d1a94 | ||
|
|
c7d398781f | ||
|
|
699bdf78d0 | ||
|
|
2a26f08d74 | ||
|
|
5d689196c9 | ||
|
|
90d30b67f5 | ||
|
|
c760aaca6a | ||
|
|
990ea55e2d | ||
|
|
5c8ee09635 | ||
|
|
49d0dd3141 | ||
|
|
bc4d0227fe | ||
|
|
09ee2e1223 | ||
|
|
7652ec5c26 | ||
|
|
8cefda9612 | ||
|
|
0d648e4a18 | ||
|
|
a087a5198f | ||
|
|
fa18757f2c | ||
|
|
107b37b5f4 | ||
|
|
772edc1fcd | ||
|
|
caff7790c4 | ||
|
|
56b3c62e99 | ||
|
|
0812e09b40 | ||
|
|
c0124624c9 | ||
|
|
deaacca580 | ||
|
|
ba345d486c | ||
|
|
30b3ab1203 | ||
|
|
3eabf14df3 | ||
|
|
e7fdec8404 | ||
|
|
871f75d246 | ||
|
|
793c309a4b | ||
|
|
b0a2776be1 | ||
|
|
e1877c015b | ||
|
|
8c7c8f9150 | ||
|
|
7fe8287a32 | ||
|
|
7b391a107e | ||
|
|
191e5ee2f7 | ||
|
|
10e94e605d | ||
|
|
2fe0d8bab3 | ||
|
|
05638d36b1 | ||
|
|
ea2d2f36ce | ||
|
|
7fe4e78dc1 | ||
|
|
789eefe5ff | ||
|
|
8485a51c18 | ||
|
|
d1f1af18e9 | ||
|
|
ba0f4ec753 | ||
|
|
f630267587 | ||
|
|
e5dff422f3 | ||
|
|
1a54413514 | ||
|
|
66f2d49db6 | ||
|
|
7043fb6db5 | ||
|
|
1777d82ff9 | ||
|
|
9456aac555 | ||
|
|
39ba9ddb15 | ||
|
|
98a2f07fa5 | ||
|
|
10f19b3cda | ||
|
|
d7365a9d3a | ||
|
|
6d2dcafdd0 | ||
|
|
ab315cae30 | ||
|
|
e8e4213c48 | ||
|
|
6a711d0d6e | ||
|
|
8e21a7cf3b | ||
|
|
083c2d6277 | ||
|
|
7eb5e85581 | ||
|
|
5ce6657546 | ||
|
|
e72c9c3759 | ||
|
|
70d0997901 | ||
|
|
ab3cb11a18 | ||
|
|
86bbc119b2 | ||
|
|
01c649ced9 | ||
|
|
84373573eb | ||
|
|
b0317bb3bb | ||
|
|
29de3be4d8 | ||
|
|
2afb5af26c | ||
|
|
e27c46342b | ||
|
|
f189c7450c | ||
|
|
da225c0c5e | ||
|
|
5da02cd478 | ||
|
|
e0c08b12a7 | ||
|
|
fb8ec74a1c | ||
|
|
1c43df5cad | ||
|
|
ecdbb9ccf6 | ||
|
|
5f8b300404 | ||
|
|
62a1a4c461 | ||
|
|
b074e4f992 | ||
|
|
b86ae06288 | ||
|
|
c0f3bdeb60 | ||
|
|
074ec3fff1 | ||
|
|
d91de3386e | ||
|
|
d52dd3214d | ||
|
|
de2759f71c | ||
|
|
133ef6ff54 | ||
|
|
d5b4315672 | ||
|
|
9350f1dced | ||
|
|
7840179324 | ||
|
|
8adad96e86 | ||
|
|
bc333d89fa | ||
|
|
85ad99599d | ||
|
|
5be7b3c4ba | ||
|
|
0fa156f30d | ||
|
|
a3ba885753 | ||
|
|
a4efe91fe8 | ||
|
|
24b2e5e03d | ||
|
|
7eb95d62b1 | ||
|
|
170491b34c | ||
|
|
db07f52349 | ||
|
|
d683b178ed | ||
|
|
d0f96becb1 | ||
|
|
1a664ab6c6 | ||
|
|
ca3adef039 | ||
|
|
0bb10d3902 | ||
|
|
fe8d6147d4 | ||
|
|
233a46efeb | ||
|
|
b0e7bc385a | ||
|
|
5344e73dec | ||
|
|
dd3a8c1d22 | ||
|
|
552351457c | ||
|
|
b9fbf072ab | ||
|
|
02cc250fc2 | ||
|
|
0f0c1dc75a | ||
|
|
48cc30777d | ||
|
|
676169b777 | ||
|
|
37598793a0 | ||
|
|
3073c26c73 | ||
|
|
33af8ecc05 | ||
|
|
6f90c80dcc | ||
|
|
96866be339 | ||
|
|
0549a9f943 | ||
|
|
5933636214 | ||
|
|
9c592b7ace | ||
|
|
a4d1854a77 | ||
|
|
dbb2aeee00 | ||
|
|
595bf44beb | ||
|
|
fa0c7b8a5a | ||
|
|
7624acb28a | ||
|
|
90c6be0cbf | ||
|
|
1d87776c02 | ||
|
|
c2860177dd | ||
|
|
e98254afdc | ||
|
|
e00f1b5451 | ||
|
|
f163c49339 | ||
|
|
de5bd52bd9 | ||
|
|
5fe3367aaa | ||
|
|
26ab83a4b7 | ||
|
|
bd60aa4322 | ||
|
|
7ca13ed404 | ||
|
|
49e6701601 | ||
|
|
0524c78459 | ||
|
|
5230f5efb2 | ||
|
|
f6e47f062b | ||
|
|
4606918fad | ||
|
|
2cad3e1561 | ||
|
|
ca9f1211d1 | ||
|
|
7e330c4e3f | ||
|
|
6a8044a36f | ||
|
|
8da4bb7eb3 | ||
|
|
c9e5cc15ba | ||
|
|
d51bd9acca | ||
|
|
dcd931fa2e | ||
|
|
3739ce91cf | ||
|
|
30821dc3fb | ||
|
|
5c32c46219 | ||
|
|
599ecfcb65 | ||
|
|
5edc936301 | ||
|
|
8536390800 | ||
|
|
3d4eadd2cd | ||
|
|
6239b462f2 | ||
|
|
55855f4cae | ||
|
|
e6d9abee21 | ||
|
|
a0bcdb2438 | ||
|
|
71deb27b7e | ||
|
|
5a7bc507d1 | ||
|
|
b880ab1cb6 | ||
|
|
2136978378 | ||
|
|
41d63f83eb | ||
|
|
b5b20a7738 | ||
|
|
8c73c948b4 | ||
|
|
a9c977db51 | ||
|
|
ae61e1a61c | ||
|
|
644e68d0ff | ||
|
|
2c43bf1ba1 | ||
|
|
a29ccab178 | ||
|
|
df507deac9 | ||
|
|
f66ed7ca88 | ||
|
|
414e91fd5d | ||
|
|
1266fc058f | ||
|
|
9d256a5ca3 | ||
|
|
906c675b4b | ||
|
|
89f08f76b7 | ||
|
|
219a5d1cc1 | ||
|
|
f58c7293e2 | ||
|
|
2678be75bd | ||
|
|
93bd279d34 | ||
|
|
5eaf5a86fb | ||
|
|
1a8d860d8d | ||
|
|
acc68d4fd4 | ||
|
|
1e2e577885 | ||
|
|
1f8a227e4b | ||
|
|
d225d29384 | ||
|
|
480582f344 | ||
|
|
48dea09a0c | ||
|
|
cdff1a5f4f | ||
|
|
0c72b517e8 | ||
|
|
a5de8624d7 | ||
|
|
cedc9977c2 | ||
|
|
b123971e21 | ||
|
|
0927801deb | ||
|
|
eea89dfd1c | ||
|
|
6d8f16fabb | ||
|
|
deb5e735b8 | ||
|
|
3f2751ac50 | ||
|
|
5a6e12200c | ||
|
|
0c96a4fa98 | ||
|
|
ed227b9cb6 | ||
|
|
d9c63d4b43 | ||
|
|
24b3119bc8 | ||
|
|
d1a2a0c20b | ||
|
|
053fa3eb83 | ||
|
|
630fa35604 | ||
|
|
94a4c0b0ed | ||
|
|
974564b89c | ||
|
|
44bbf74fbf | ||
|
|
b4917d6027 | ||
|
|
1a82394d72 | ||
|
|
cec44c05dd | ||
|
|
c54139f7db | ||
|
|
22bc13804c | ||
|
|
debbbb81c0 | ||
|
|
11a02eeaba | ||
|
|
3f4be26003 | ||
|
|
f73da0492d | ||
|
|
aa2292459f | ||
|
|
f34e1fcb9b | ||
|
|
c382f05c30 | ||
|
|
a6c4100711 | ||
|
|
f15e7fd8a9 | ||
|
|
3c155e4cce | ||
|
|
c1143fdf14 | ||
|
|
ae9c16efce | ||
|
|
d86cb7355b | ||
|
|
ad33137b71 | ||
|
|
109ed685b2 | ||
|
|
692573e8d0 | ||
|
|
78ff4d0470 | ||
|
|
22f31c1335 | ||
|
|
774676248b | ||
|
|
bbd4fbc358 | ||
|
|
49319023e5 | ||
|
|
5ee9758b75 | ||
|
|
df66bc8711 | ||
|
|
eb4c3498fe | ||
|
|
1362b8a1f4 | ||
|
|
7ca5ba286a | ||
|
|
5486cc5439 | ||
|
|
4d96ff9e2f | ||
|
|
b022b022f9 | ||
|
|
82cbe85864 | ||
|
|
e6e9fd427b | ||
|
|
8b90582870 | ||
|
|
2d7af07867 | ||
|
|
2603053779 | ||
|
|
be074b3bda | ||
|
|
da36e0503e | ||
|
|
8dc4448e89 | ||
|
|
50b94bdb21 | ||
|
|
614f9f4941 | ||
|
|
4ad170c03e | ||
|
|
d3f327c158 | ||
|
|
d3f27cd844 | ||
|
|
c6467a2451 | ||
|
|
747700d5aa | ||
|
|
f748911b48 | ||
|
|
a7674c6327 | ||
|
|
5c6dc91714 | ||
|
|
8c0d5aee92 | ||
|
|
75bb7fd01a | ||
|
|
7e8aa94647 | ||
|
|
b6f20133d2 | ||
|
|
a8dc73f368 | ||
|
|
e8ace69fc0 | ||
|
|
718b770f21 | ||
|
|
5afeca1b76 | ||
|
|
75b4434d61 | ||
|
|
9812e567e6 | ||
|
|
8afa7242c2 | ||
|
|
b6c0bb4978 | ||
|
|
4d9648ba90 | ||
|
|
0ddda8cb6c | ||
|
|
d1ed2e9657 | ||
|
|
6c4f7af41f | ||
|
|
8f602facb2 | ||
|
|
26cbe0d8b7 | ||
|
|
95b60cd3da | ||
|
|
c0f5c57c91 | ||
|
|
a0d1dd4055 | ||
|
|
9307940d04 | ||
|
|
1ca85f8071 | ||
|
|
0250816a40 | ||
|
|
434e306430 | ||
|
|
dcd18c4384 | ||
|
|
16f5c2889d | ||
|
|
b4212ab6fc | ||
|
|
da49f31d1b | ||
|
|
b6c768aa98 | ||
|
|
86d33ec100 | ||
|
|
cff3b4c6e7 | ||
|
|
9c60a4a217 | ||
|
|
faed93543f | ||
|
|
0d3d5ed619 | ||
|
|
7c9a74cb06 | ||
|
|
5461450bfa | ||
|
|
26885ded29 |
No files matched your search
@@ -12,10 +12,37 @@ runs:
|
||||
key: ${{ runner.os }}-pio
|
||||
|
||||
- name: Install Python
|
||||
id: python
|
||||
continue-on-error: true
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: '3.13'
|
||||
|
||||
# CUSTOM (TeTeHacko): setup-python's build for the runner OS can need a
|
||||
# newer CPU than the runner host has ("CPU ISA level is lower than
|
||||
# required"); fall back to the image's own python3 in a venv
|
||||
- name: Python fallback
|
||||
if: steps.python.outcome == 'failure'
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
venv="$RUNNER_TEMP/pyenv"
|
||||
if ! python3 -m venv "$venv"; then
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq python3 python3-venv
|
||||
python3 -m venv --clear "$venv"
|
||||
fi
|
||||
# The image's python is often newer than the wheels on PyPI (detools
|
||||
# 0.53.0 has none for 3.14): pip then builds from source and needs the
|
||||
# headers, which the image does not ship.
|
||||
inc="$("$venv/bin/python" -c 'import sysconfig; print(sysconfig.get_paths()["include"])')"
|
||||
if [ ! -e "$inc/Python.h" ]; then
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq python3-dev
|
||||
fi
|
||||
echo "$venv/bin" >>"$GITHUB_PATH"
|
||||
"$venv/bin/python" --version
|
||||
|
||||
- name: Install PlatformIO
|
||||
shell: bash
|
||||
run: |
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# shellcheck shell=bash
|
||||
# Build flags of the public firmware, sourced by pub-release.yml -- and by the
|
||||
# private mast release, which builds the very same observer image, so what the
|
||||
# fork publishes is what runs on its own nodes. PlatformIO appends
|
||||
# PLATFORMIO_BUILD_FLAGS after each env's flags: last -D wins.
|
||||
#
|
||||
# 869.432/62.5/SF7/CR5; repeater + room server: zero-hop advert off, flood
|
||||
# advert 25 h, AIRTIME_FACTOR 9 (= `dutycycle` 10 %); repeater: regions cz,cs next to *.
|
||||
# Path hash 2 B is this fork's default anyway. TX power stays the board's.
|
||||
# FILTER_CHANNEL_PSKS = [channel_filter] in platformio.ini (#meshcore, Public,
|
||||
# #test -- public keys): compiles the repeater's `filter` (deny-forward by
|
||||
# sender name); inert until an operator adds a name.
|
||||
# WITH_RX_POWERSAVING compiles `set radio.rxps` (SX1262 RX duty cycle); off
|
||||
# until an operator sets it.
|
||||
PUB_FLAGS='-D WITH_RX_POWERSAVING
|
||||
-D LORA_FREQ=869.432 -D LORA_BW=62.5 -D LORA_SF=7 -D LORA_CR=5
|
||||
-D ADVERT_INTERVAL_DEFAULT=0 -D FLOOD_ADVERT_INTERVAL_DEFAULT=25
|
||||
-D AIRTIME_FACTOR_DEFAULT=9.0 -D DEFAULT_REGIONS=\"cz,cs\"
|
||||
-D FILTER_CHANNEL_PSKS=\"2fa78a5aef618e7c2a78f0ab5c8869b3,8b3387e9c5cdea6ac9e5edbaa115cd72,9cd8fcf22a47333b591d96a2b848b73f\"'
|
||||
# Observer variants of the nRF52 repeaters: BLE console (starts OFF,
|
||||
# RPT_BLE_DEFAULT_OFF -- placeholder PIN), `rxlog`/`nodes` and the `pktlog`
|
||||
# raw-frame ring that the repeater observer reads over BLE or USB.
|
||||
OBS_FLAGS='-D BLE_PIN_CODE=123456 -D RPT_BLE_DEFAULT_OFF=1
|
||||
-D MAX_HEARD_NODES=128 -D RXLOG_SIZE=512 -D PKTFEED_SIZE=64'
|
||||
# one line each, as the YAML folded scalars they replace were
|
||||
PUB_FLAGS=${PUB_FLAGS//$'\n'/ }
|
||||
OBS_FLAGS=${OBS_FLAGS//$'\n'/ }
|
||||
export PUB_FLAGS OBS_FLAGS
|
||||
@@ -40,6 +40,11 @@ jobs:
|
||||
- PicoW_repeater
|
||||
# STM32
|
||||
- wio-e5-mini_repeater
|
||||
- LilyGo_T3_STM32_repeater
|
||||
- LilyGo_T3_STM32_companion_radio_usb
|
||||
- LilyGo_T3_STM32_repeater_ina219
|
||||
- LilyGo_T3_STM32_companion_radio_usb_ina219
|
||||
- nucleo_wl55jc_repeater
|
||||
# ESP32-C6
|
||||
- LilyGo_Tlora_C6_repeater_
|
||||
# LR1110 (nRF52)
|
||||
|
||||
@@ -0,0 +1,436 @@
|
||||
# Public firmware builds of this fork -- runs only in the published repo
|
||||
# (git.rfa.cz tth-pub/meshcore-tth), skipped anywhere else.
|
||||
#
|
||||
# Generic envs only: upstream's placeholder BLE PIN (123456) and admin
|
||||
# password ("password") -- change both on the node after flashing. Nothing
|
||||
# here carries a site's identity or real secrets.
|
||||
#
|
||||
# Defaults follow the Czech mesh (meshcore.cz wiki: nastaveni_site_meshcore_cz,
|
||||
# instalace_repeateru, regiony), PUB_FLAGS below. They apply to a node with
|
||||
# no saved settings (fresh, or after an erase); a reflash keeps what is set.
|
||||
#
|
||||
# Runs on a push to main that touches the firmware -- the export pushes there
|
||||
# after every upstream sync (private repo, tth-upstream-sync) -- and by hand.
|
||||
# Documentation, the enclosure and CI files alone build nothing (paths-ignore):
|
||||
# a release would only make every -ota node update itself to the same code.
|
||||
# tools/ is NOT ignored: build_version.py and ota_ramlib.py are build inputs.
|
||||
# Release tag v1.18.0+tth.<commit date>[.n] (the n-th release of that day),
|
||||
# titled "v1.18.0+tth · 12. 11. 2026"; assets carry the tag in their names, the
|
||||
# body the version the node reports (`ver`: v1.18.0-tth<sha>). Until 12. 11.
|
||||
# 2026 the tags were tth-<sha8>; pruning and the changelog know both;
|
||||
# the newest KEEP releases stay, older ones are deleted. The body is a
|
||||
# changelog since the previous release: our own firmware commits, our docs /
|
||||
# tools / CI commits folded, then the upstream PRs the upstream merges brought
|
||||
# in. A "Changelog: <text>" line in a commit body replaces its subject there.
|
||||
# nRF52: .uf2 (drag onto the bootloader drive) and .zip (DFU over BLE or
|
||||
# serial); ESP32: -merged.bin (fresh install at 0x0) and .bin (update).
|
||||
#
|
||||
# EXPERIMENTAL -ota images (docs/ota-public-plan.md): every nRF52 env with a
|
||||
# text console (OTA_ENVS) is built once more with -D FW_OTA=1 (admin-pushed
|
||||
# update, FwUpdate), the observer ones as -observer-ota too. Each comes with a
|
||||
# full .mcfw package and a delta from the same image of every kept earlier
|
||||
# release (its zip's firmware.bin, checked against that release's SHA256SUMS);
|
||||
# over the mesh a node takes only deltas, and none older than itself.
|
||||
# Packages and SHA256SUMS are signed with OTA_SIGNING_KEY (meshcore-ota@tth-pub,
|
||||
# tools/ota_allowed_signers); manifest.json lists what is there.
|
||||
#
|
||||
# dry_run: the same build anywhere (the private repo too), no release -- the
|
||||
# result goes up as a workflow artifact. Delta bases always come from the
|
||||
# public repo's releases.
|
||||
name: pub-release
|
||||
|
||||
"on":
|
||||
push:
|
||||
branches: [main]
|
||||
paths-ignore:
|
||||
- "**/*.md"
|
||||
- "docs/**"
|
||||
- "hardware/**"
|
||||
- ".github/**"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
ref:
|
||||
description: "commit to build: FULL sha, branch or tag (checkout takes no short sha)"
|
||||
required: false
|
||||
default: "main"
|
||||
replace:
|
||||
description: "replace an existing release of this commit"
|
||||
required: false
|
||||
default: "false"
|
||||
dry_run:
|
||||
description: "build and package only, no release (runs in the private repo too)"
|
||||
required: false
|
||||
default: "false"
|
||||
bases_repo:
|
||||
description: "dry run only: take delta bases from this repo's releases instead (testing the delta path)"
|
||||
required: false
|
||||
default: ""
|
||||
only:
|
||||
description: "dry run only: build just these artifacts (e.g. Xiao_nrf52_repeater-ota), space separated"
|
||||
required: false
|
||||
default: ""
|
||||
|
||||
concurrency:
|
||||
group: pub-release
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
GITEA: https://git.rfa.cz
|
||||
KEEP: 5
|
||||
# PUB_FLAGS / OBS_FLAGS: .github/fw-flags.sh (shared with the private mast
|
||||
# release, which builds the same observer image). RAM 37-39 %, flash 41-58 %.
|
||||
OBS_ENVS: >-
|
||||
Xiao_nrf52_repeater SenseCap_Solar_repeater RAK_4631_repeater t1000e_repeater Heltec_t114_repeater
|
||||
# nRF52 envs with a text console: also released as experimental -ota images
|
||||
OTA_ENVS: >-
|
||||
Xiao_nrf52_repeater Xiao_nrf52_room_server Xiao_nrf52_sensor SenseCap_Solar_repeater
|
||||
RAK_4631_repeater RAK_4631_room_server t1000e_repeater Heltec_t114_repeater
|
||||
PUB_REPO: tth-pub/meshcore-tth # where delta bases come from, dry run or not
|
||||
ENVS: >-
|
||||
Xiao_nrf52_repeater Xiao_nrf52_companion_radio_ble Xiao_nrf52_room_server Xiao_nrf52_sensor
|
||||
SenseCap_Solar_repeater SenseCap_Solar_companion_radio_ble
|
||||
RAK_4631_repeater RAK_4631_companion_radio_ble RAK_4631_room_server
|
||||
t1000e_repeater t1000e_companion_radio_ble
|
||||
Heltec_t114_repeater Heltec_t114_companion_radio_ble
|
||||
Heltec_v3_repeater Heltec_v3_companion_radio_ble
|
||||
|
||||
jobs:
|
||||
release:
|
||||
if: github.repository == 'tth-pub/meshcore-tth' || github.event.inputs.dry_run == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ github.event.inputs.ref || github.sha }}
|
||||
|
||||
- name: Commit and tag
|
||||
id: src
|
||||
env:
|
||||
TOKEN: ${{ secrets.GITEA_TOKEN || github.token }}
|
||||
REPLACE: ${{ github.event.inputs.replace }}
|
||||
DRY: ${{ github.event.inputs.dry_run }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git fetch -q --tags
|
||||
# the private repo carries no upstream release tags (the export brings
|
||||
# them along): a dry run there fetches them, or the version base is "nover"
|
||||
if [ "$DRY" = "true" ]; then
|
||||
git fetch -q --no-tags https://github.com/meshcore-dev/MeshCore.git 'refs/tags/*:refs/tags/*'
|
||||
fi
|
||||
sha=$(git rev-parse HEAD)
|
||||
# upstream base as tools/build_version.py finds it: "companion-v1.18.0" -> v1.18.0
|
||||
desc=$(git describe --tags --abbrev=0 --match '*v[0-9]*' --exclude '*+tth*' --exclude 'backup/*' HEAD)
|
||||
[[ $desc =~ v[0-9].* ]] && base=${BASH_REMATCH[0]} || base=$desc
|
||||
# the COMMIT's date (Prague), so a rebuild of the same commit keeps its tag
|
||||
day=$(TZ=Europe/Prague git show -s --format=%cd --date=format-local:%Y%m%d HEAD)
|
||||
human=$(TZ=Europe/Prague git show -s --format=%cd --date=format-local:'%-d. %-m. %Y' HEAD)
|
||||
api="$GITEA/api/v1/repos/$GITHUB_REPOSITORY"
|
||||
auth="header = \"Authorization: token $TOKEN\""
|
||||
enc() { jq -rn --arg s "$1" '$s|@uri'; }
|
||||
# v1.18.0+tth.20261112, a second release of the day .2, ...
|
||||
n=1
|
||||
while :; do
|
||||
tag="$base+tth.$day"
|
||||
[ "$n" -eq 1 ] || tag="$tag.$n"
|
||||
rel=$(curl -sS --config - "$api/releases/tags/$(enc "$tag")" <<<"$auth")
|
||||
id=$(jq -r '.id // empty' <<<"$rel")
|
||||
[ -n "$id" ] || break
|
||||
if [ "$(jq -r .target_commitish <<<"$rel")" = "$sha" ]; then
|
||||
if [ "$REPLACE" != "true" ]; then
|
||||
echo "::error::release $tag already exists (id $id); set replace=true to rebuild it"
|
||||
exit 1
|
||||
fi
|
||||
curl -sSf --config - -X DELETE "$api/releases/$id" <<<"$auth"
|
||||
curl -sSf --config - -X DELETE "$api/tags/$(enc "$tag")" <<<"$auth" || true
|
||||
echo "removed old $tag"
|
||||
break
|
||||
fi
|
||||
n=$((n + 1))
|
||||
done
|
||||
title="$base+tth · $human"
|
||||
[ "$n" -eq 1 ] || title="$title ($n)"
|
||||
echo "release $tag: $title (commit $sha)"
|
||||
{
|
||||
echo "sha=$sha"
|
||||
echo "tag=$tag"
|
||||
echo "title=$title"
|
||||
} >>"$GITHUB_OUTPUT"
|
||||
|
||||
- name: Setup Build Environment
|
||||
uses: ./.github/actions/setup-build-environment
|
||||
|
||||
- name: Build and package
|
||||
id: build
|
||||
env:
|
||||
TAG: ${{ steps.src.outputs.tag }}
|
||||
OTA_SIGNING_KEY: ${{ secrets.OTA_SIGNING_KEY }}
|
||||
TOKEN: ${{ secrets.GITEA_TOKEN || github.token }}
|
||||
DRY: ${{ github.event.inputs.dry_run }}
|
||||
BASES_REPO: ${{ github.event.inputs.bases_repo }}
|
||||
ONLY: ${{ github.event.inputs.only }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
source .github/fw-flags.sh
|
||||
sha=$(git rev-parse --short=8 HEAD)
|
||||
dist="$GITHUB_WORKSPACE/dist"
|
||||
mkdir -p "$dist"
|
||||
version=""
|
||||
[ -n "$OTA_SIGNING_KEY" ] || { echo "::error::OTA_SIGNING_KEY secret missing"; exit 1; }
|
||||
okey="$RUNNER_TEMP/ota_signing_key"
|
||||
(umask 077 && printf '%s\n' "$OTA_SIGNING_KEY" >"$okey")
|
||||
trap 'rm -f "$okey"' EXIT
|
||||
pip install -q detools==0.53.0 cryptography
|
||||
echo '{}' >"$dist/manifest.json"
|
||||
# earlier public releases (newest first): delta bases for the -ota images
|
||||
[ "$DRY" = "true" ] && [ -n "$BASES_REPO" ] && PUB_REPO=$BASES_REPO
|
||||
[ "$DRY" = "true" ] || ONLY="" # a real release always builds everything
|
||||
api="$GITEA/api/v1/repos/$PUB_REPO"
|
||||
auth="header = \"Authorization: token $TOKEN\""
|
||||
bases="$RUNNER_TEMP/bases"
|
||||
mkdir -p "$bases"
|
||||
curl -sSf --config - "$api/releases?limit=50" <<<"$auth" |
|
||||
jq -c --arg t "$TAG" '[.[] | select(.tag_name | startswith("tth-") or test("[+]tth[.]")) | select(.tag_name != $t)]
|
||||
| sort_by(.created_at) | reverse | .[]' >"$bases/releases.jsonl" || : >"$bases/releases.jsonl"
|
||||
asset() { jq -r --arg n "$2" '.assets[] | select(.name == $n) | .browser_download_url' <<<"$1"; }
|
||||
# ota_package <env> <artifact>: full package + deltas from earlier releases
|
||||
ota_package() {
|
||||
local env=$1 art=$2 b=".pio/build/$1" tags img rel ptag url dir out
|
||||
tools/ota_check_ramfunc.sh "$env"
|
||||
tags=$(grep -aoE 'MCFW-TAGS target=[!-~]+ epoch=[0-9]+' "$b/firmware.elf" | head -1)
|
||||
img=$(sha256sum <"$b/firmware.bin" | cut -d' ' -f1)
|
||||
python3 tools/ota_pack.py pack "$env" --key "$okey" --out "$dist/$art-$TAG.mcfw"
|
||||
jq --arg a "$art" --arg z "$art-$TAG.zip" --arg f "$art-$TAG.mcfw" --arg i "$img" --arg t "${tags#MCFW-TAGS }" \
|
||||
'.envs[$a] = {zip: $z, ota: {image_sha256: $i, tags: $t, full: $f, deltas: {}}}' \
|
||||
"$dist/manifest.json" >"$dist/m.tmp" && mv "$dist/m.tmp" "$dist/manifest.json"
|
||||
while read -r rel; do
|
||||
ptag=$(jq -r .tag_name <<<"$rel")
|
||||
url=$(asset "$rel" "$art-$ptag.zip")
|
||||
[ -n "$url" ] || continue # that release had no such -ota image yet
|
||||
dir="$bases/$ptag"
|
||||
mkdir -p "$dir"
|
||||
[ -f "$dir/SHA256SUMS" ] || curl -sSfL --config - -o "$dir/SHA256SUMS" "$(asset "$rel" SHA256SUMS)" <<<"$auth"
|
||||
curl -sSfL --config - -o "$dir/$art-$ptag.zip" "$url" <<<"$auth"
|
||||
(cd "$dir" && grep " $art-$ptag.zip\$" SHA256SUMS | sha256sum -c --quiet -)
|
||||
unzip -p "$dir/$art-$ptag.zip" firmware.bin >"$dir/$art.bin"
|
||||
out="$art-$TAG.from-$ptag.mcfw"
|
||||
if python3 tools/ota_pack.py diff "$env" --base "$dir/$art.bin" --key "$okey" --out "$dist/$out"; then
|
||||
jq --arg a "$art" --arg p "$ptag" --arg f "$out" --arg s "$(sha256sum <"$dir/$art.bin" | cut -d' ' -f1)" \
|
||||
'.envs[$a].ota.deltas[$p] = {file: $f, base_sha256: $s}' \
|
||||
"$dist/manifest.json" >"$dist/m.tmp" && mv "$dist/m.tmp" "$dist/manifest.json"
|
||||
else
|
||||
echo "::warning::$art: no delta from $ptag, full package only"
|
||||
rm -f "$dist/$out"
|
||||
fi
|
||||
done <"$bases/releases.jsonl"
|
||||
}
|
||||
# build <env> <extra flags> <name suffix> [ota variant]; PlatformIO
|
||||
# appends PLATFORMIO_BUILD_FLAGS after each env's flags: last -D wins
|
||||
build() {
|
||||
local env=$1 suffix=$3 variant=${4:-} b v
|
||||
if [ -n "$ONLY" ] && [[ " $ONLY " != *" $env$suffix "* ]]; then return 0; fi
|
||||
echo "::group::$env$suffix"
|
||||
FW_OTA_VARIANT=$variant PLATFORMIO_BUILD_FLAGS="$PUB_FLAGS $2" pio run -e "$env"
|
||||
b=".pio/build/$env"
|
||||
if [ -f "$b/firmware.zip" ]; then # nRF52
|
||||
python3 bin/uf2conv/uf2conv.py "$b/firmware.hex" -c -o "$b/firmware.uf2" -f 0xADA52840
|
||||
cp "$b/firmware.uf2" "$dist/$env$suffix-$TAG.uf2"
|
||||
cp "$b/firmware.zip" "$dist/$env$suffix-$TAG.zip"
|
||||
v=$(grep -m1 -aoE 'v[0-9]+\.[0-9]+\.[0-9]+-tth[0-9a-f]+\+?' "$b/firmware.elf" || true)
|
||||
case "$v" in *+) echo "::error::$env is dirty ($v)"; exit 1 ;; esac
|
||||
[ -n "$version" ] || version="$v"
|
||||
[ -z "$variant" ] || { unzip -p "$b/firmware.zip" firmware.bin >"$b/firmware.bin"; ota_package "$env" "$env$suffix"; }
|
||||
else # ESP32
|
||||
PLATFORMIO_BUILD_FLAGS="$PUB_FLAGS $2" pio run -t mergebin -e "$env"
|
||||
cp "$b/firmware.bin" "$dist/$env$suffix-$TAG.bin"
|
||||
cp "$b/firmware-merged.bin" "$dist/$env$suffix-$TAG-merged.bin"
|
||||
fi
|
||||
echo "::endgroup::"
|
||||
}
|
||||
for env in $ENVS; do build "$env" "" ""; done
|
||||
for env in $OBS_ENVS; do build "$env" "$OBS_FLAGS" "-observer"; done
|
||||
for env in $OTA_ENVS; do build "$env" "-D FW_OTA=1" "-ota" ota; done
|
||||
for env in $OBS_ENVS; do build "$env" "$OBS_FLAGS -D FW_OTA=1" "-observer-ota" observer-ota; done
|
||||
jq --arg c "$(git rev-parse HEAD)" --arg t "$TAG" '.commit = $c | .tag = $t' \
|
||||
"$dist/manifest.json" >"$dist/m.tmp" && mv "$dist/m.tmp" "$dist/manifest.json"
|
||||
cd "$dist"
|
||||
sha256sum -- * >SHA256SUMS
|
||||
ssh-keygen -q -Y sign -f "$okey" -n meshcore-ota SHA256SUMS
|
||||
ssh-keygen -Y verify -f "$GITHUB_WORKSPACE/tools/ota_allowed_signers" -I meshcore-ota@tth-pub \
|
||||
-n meshcore-ota -s SHA256SUMS.sig <SHA256SUMS
|
||||
cat SHA256SUMS
|
||||
echo "version=${version:-tth-$sha}" >>"$GITHUB_OUTPUT"
|
||||
|
||||
- name: Dry run artifact
|
||||
if: github.event.inputs.dry_run == 'true'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: pub-release-dry-run
|
||||
path: dist/
|
||||
|
||||
- name: Release
|
||||
if: github.event.inputs.dry_run != 'true'
|
||||
env:
|
||||
TOKEN: ${{ secrets.GITEA_TOKEN || github.token }}
|
||||
SHA: ${{ steps.src.outputs.sha }}
|
||||
TAG: ${{ steps.src.outputs.tag }}
|
||||
TITLE: ${{ steps.src.outputs.title }}
|
||||
VERSION: ${{ steps.build.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
api="$GITEA/api/v1/repos/$GITHUB_REPOSITORY"
|
||||
auth="header = \"Authorization: token $TOKEN\""
|
||||
readme="$GITEA/$GITHUB_REPOSITORY#o-tomto-forku-meshcore-tth"
|
||||
note=$(cat <<EOF
|
||||
- **BLE PIN \`123456\` a admin heslo \`password\` jsou zástupné.** Po nahrání je změň: \`password <nové>\` (nejvýš 15
|
||||
znaků), \`ble pin <6 číslic>\`.
|
||||
- **Výchozí nastavení pro český mesh** ([meshcore.cz](https://meshcore.cz/)): 869,432 MHz / 62,5 kHz / SF7 / CR5;
|
||||
repeater a room server: zero-hop advert vypnutý, flood advert á 25 h, duty cycle 10 % (\`get dutycycle\`); repeater:
|
||||
regiony \`cz\` a \`cs\`. **Platí jen pro nový nebo smazaný uzel** – nové nahrání ponechá uložené nastavení.
|
||||
- **\`*-observer\`**: repeater s BLE konzolí a buffery \`rxlog\` / \`pktlog\` pro repeater observer. BLE je po nahrání
|
||||
vypnuté: nejdřív \`ble pin\`, pak \`ble on\`.
|
||||
- **RX duty cycle** (\`set radio.rxps\`, jen SX1262) je zabudovaný a vypnutý.
|
||||
- **EXPERIMENTÁLNÍ \`*-ota\` / \`*-observer-ota\`**: totéž s aktualizací firmwaru od admina (\`fw ...\`, i přes
|
||||
mesh). Ke každému plný balíček \`.mcfw\` (USB/BLE) a delta \`.from-<vydání>.mcfw\` od předchozích vydání –
|
||||
přes mesh uzel přijme jen deltu a nikdy starší verzi. Balíčky i \`SHA256SUMS\` jsou podepsané klíčem
|
||||
\`meshcore-ota@tth-pub\` (\`tools/ota_allowed_signers\`).
|
||||
- Ověření: \`ver\` ukáže verzi z řádku *Verze v uzlu* výše. Co fork mění proti upstreamu: [README]($readme).
|
||||
|
||||
<details><summary>English</summary>
|
||||
|
||||
- **BLE PIN \`123456\` and admin password \`password\` are placeholders.** Change them after flashing: \`password
|
||||
<new>\` (15 characters at most), \`ble pin <6 digits>\`.
|
||||
- **Czech mesh defaults** ([meshcore.cz](https://meshcore.cz/)): 869.432 MHz / 62.5 kHz / SF7 / CR5; repeater and room
|
||||
server: zero-hop advert off, flood advert every 25 h, 10 % duty cycle (\`get dutycycle\`); repeater: regions \`cz\`
|
||||
and \`cs\`. **A fresh or erased node only** – a reflash keeps the saved settings.
|
||||
- **\`*-observer\`**: repeater with a BLE console and the \`rxlog\` / \`pktlog\` rings for the repeater observer. BLE
|
||||
is off after flashing: \`ble pin\` first, then \`ble on\`.
|
||||
- **RX duty cycle** (\`set radio.rxps\`, SX1262 only) is built in and off.
|
||||
- **EXPERIMENTAL \`*-ota\` / \`*-observer-ota\`**: the same with admin-pushed firmware update (\`fw ...\`, over the
|
||||
mesh too). Each with a full \`.mcfw\` package (USB/BLE) and a delta \`.from-<release>.mcfw\` from earlier
|
||||
releases -- over the mesh a node takes only a delta and never an older version. Packages and \`SHA256SUMS\`
|
||||
are signed by \`meshcore-ota@tth-pub\` (\`tools/ota_allowed_signers\`).
|
||||
- Check: \`ver\` shows the version from the *Verze v uzlu* (node version) line above. What the fork changes against
|
||||
upstream: [README]($readme).
|
||||
|
||||
</details>
|
||||
EOF
|
||||
)
|
||||
web="$GITEA/$GITHUB_REPOSITORY"
|
||||
gh=https://github.com/meshcore-dev/MeshCore
|
||||
max=60
|
||||
# changelog against the newest older release that HEAD descends from
|
||||
prev="" base=""
|
||||
while read -r t c; do
|
||||
if [ "$c" != "$SHA" ] && git merge-base --is-ancestor "$c" "$SHA" 2>/dev/null; then
|
||||
prev=$t base=$c
|
||||
break
|
||||
fi
|
||||
done < <(curl -sSf --config - "$api/releases?limit=50" <<<"$auth" |
|
||||
jq -r --arg t "$TAG" 'map(select(.tag_name | startswith("tth-") or test("[+]tth[.]")) | select(.tag_name != $t))
|
||||
| sort_by(.created_at) | reverse | .[] | "\(.tag_name) \(.target_commitish)"')
|
||||
# no older release: the last 20 commits of our own line
|
||||
[ -n "$base" ] || base=$(git rev-list --first-parent --max-count=21 "$SHA" | tail -1)
|
||||
# ours: commits on our main itself (first parent); a merge of one of
|
||||
# our own branches (feat/...) is unfolded into the branch's commits,
|
||||
# an upstream merge is left to the upstream list below
|
||||
ourc=()
|
||||
for c in $(git log --first-parent --format=%H "$base..$SHA"); do
|
||||
if git rev-parse -q --verify "$c^2" >/dev/null; then
|
||||
git log -1 --format=%s "$c" | grep -q '^Merge upstream' && continue
|
||||
# ^base: a merge of main into a branch carries what is released already
|
||||
mapfile -t -O "${#ourc[@]}" ourc < <(git log --no-merges --format=%H "$c^1..$c^2" "^$base")
|
||||
else
|
||||
ourc+=("$c")
|
||||
fi
|
||||
done
|
||||
# Firmware changes first; docs, CI, tools and tests folded away. Sorted
|
||||
# by the files a commit touches, so it holds even for a poor subject.
|
||||
# A "Changelog: <text>" line in the body replaces the subject in the
|
||||
# notes ("Changelog: -" leaves the commit out), so the subject can stay
|
||||
# technical while the notes say what changes for the node.
|
||||
fw="" other="" nother=0
|
||||
for c in "${ourc[@]}"; do
|
||||
line=$(git log -1 --format=%b "$c" | sed -n 's/^Changelog: *//p' | head -1)
|
||||
[ "$line" = "-" ] && continue
|
||||
[ -n "$line" ] || line=$(git log -1 --format=%s "$c")
|
||||
line="- $line ([${c:0:8}]($web/commit/$c))"
|
||||
if git diff-tree --no-commit-id --name-only -r "$c" |
|
||||
grep -qE '^(src|examples|variants|lib|boards|arch)/|^platformio\.ini$'; then
|
||||
fw+="$line"$'\n'
|
||||
else
|
||||
other+="$line"$'\n'
|
||||
nother=$((nother + 1))
|
||||
fi
|
||||
done
|
||||
fw=${fw%$'\n'} other=${other%$'\n'}
|
||||
# upstream: the first-parent line of each merged upstream branch,
|
||||
# PR merges as their title, direct commits as their subject
|
||||
declare -A seen=()
|
||||
ups=()
|
||||
for m in $(git log --first-parent --merges --grep='^Merge upstream' --format=%H "$base..$SHA"); do
|
||||
for c in $(git log --first-parent --format=%H "$m^1..$m^2"); do
|
||||
s=$(git log -1 --format=%s "$c")
|
||||
if [[ $s =~ ^Merge\ pull\ request\ \#([0-9]+)\ from\ ([^/]+)/(.*)$ ]]; then
|
||||
pr=${BASH_REMATCH[1]}
|
||||
[ -z "${seen[$pr]:-}" ] || continue
|
||||
seen[$pr]=1
|
||||
t=$(git log -1 --format=%b "$c" | sed -n '/./{p;q}')
|
||||
ups+=("- ${t:-${BASH_REMATCH[3]}} ([#$pr]($gh/pull/$pr), ${BASH_REMATCH[2]})")
|
||||
elif [[ $s != Merge* ]]; then
|
||||
[ -z "${seen[$c]:-}" ] || continue
|
||||
seen[$c]=1
|
||||
ups+=("- $s ([${c:0:7}]($gh/commit/$c))")
|
||||
fi
|
||||
done
|
||||
done
|
||||
n=${#ups[@]}
|
||||
body=$(
|
||||
echo "$TITLE"
|
||||
echo
|
||||
echo "Verze v uzlu · \`ver\`: $VERSION"
|
||||
echo
|
||||
if [ -n "$prev" ]; then
|
||||
echo "Od předchozího vydání · since [$prev]($web/releases/tag/$(jq -rn --arg s "$prev" '$s|@uri'))"
|
||||
echo
|
||||
fi
|
||||
echo "### Změny firmwaru · firmware changes"
|
||||
echo "${fw:-- žádné · none}"
|
||||
echo
|
||||
if [ "$nother" -gt 0 ]; then
|
||||
echo "<details><summary>Dokumentace, nástroje, CI · docs, tools, CI ($nother)</summary>"
|
||||
echo
|
||||
echo "$other"
|
||||
echo
|
||||
echo "</details>"
|
||||
echo
|
||||
fi
|
||||
echo "### Z upstreamu MeshCore · from upstream ($n)"
|
||||
[ "$n" -gt 0 ] && printf '%s\n' "${ups[@]:0:$max}" || echo "- žádné · none"
|
||||
[ "$n" -le "$max" ] || echo "- … a dalších $((n - max)) · and $((n - max)) more"
|
||||
echo
|
||||
echo "### Po flashi · after flashing"
|
||||
echo
|
||||
echo "$note"
|
||||
echo
|
||||
echo "commit $SHA, run $GITHUB_RUN_NUMBER"
|
||||
)
|
||||
jq -n --arg t "$TAG" --arg c "$SHA" --arg n "$TITLE" --arg b "$body" \
|
||||
'{tag_name: $t, target_commitish: $c, name: $n, body: $b}' >"$RUNNER_TEMP/rel.json"
|
||||
id=$(curl -sSf --config - -X POST -H 'Content-Type: application/json' \
|
||||
--data-binary "@$RUNNER_TEMP/rel.json" "$api/releases" <<<"$auth" | jq -r .id)
|
||||
for f in dist/*; do
|
||||
curl -sSf --config - -X POST -F "attachment=@$f" \
|
||||
"$api/releases/$id/assets?name=$(jq -rn --arg s "${f##*/}" '$s|@uri')" <<<"$auth" >/dev/null
|
||||
echo "uploaded $(basename "$f")"
|
||||
done
|
||||
echo "released $TAG = $VERSION (id $id)"
|
||||
# keep the newest $KEEP, oldest go (with their tags)
|
||||
curl -sSf --config - "$api/releases?limit=50" <<<"$auth" |
|
||||
jq -r --argjson k "$KEEP" 'map(select(.tag_name | startswith("tth-") or test("[+]tth[.]")))
|
||||
| sort_by(.created_at) | reverse | .[$k:][] | "\(.id) \(.tag_name)"' |
|
||||
while read -r old_id old_tag; do
|
||||
curl -sSf --config - -X DELETE "$api/releases/$old_id" <<<"$auth"
|
||||
curl -sSf --config - -X DELETE "$api/tags/$(jq -rn --arg s "$old_tag" '$s|@uri')" <<<"$auth" || true
|
||||
echo "pruned $old_tag"
|
||||
done
|
||||
@@ -20,7 +20,12 @@ jobs:
|
||||
uses: ./.github/actions/setup-build-environment
|
||||
|
||||
- name: Run Unit Tests
|
||||
run: pio test -e native -e native_kiss_modem -vv
|
||||
# native_asan MUSI byt v seznamu. Bounds guardy v Packet::readFrom
|
||||
# zamerne nemeni navratovou hodnotu (odmitnou presne to, co upstream
|
||||
# odmitne az po precteni), takze pod `native` projdou i BEZ nich -- rika
|
||||
# to i hlavicka test_packet_readfrom.cpp. Bez tohohle envu slo ty ctyri
|
||||
# kontroly z Packet.cpp odstranit a CI zustalo zelene.
|
||||
run: pio test -e native -e native_asan -e native_kiss_modem -vv
|
||||
|
||||
- name: Upload Test Results
|
||||
# Upload test results even if the test step failed.
|
||||
|
||||
+14
@@ -17,3 +17,17 @@ compile_commands.json
|
||||
.venv/
|
||||
venv/
|
||||
platformio.local.ini
|
||||
|
||||
# Python bytecode from tools/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Claude Code: lokální stav, nepatří do repa (settings.json a skills/ ANO)
|
||||
.claude/settings.local.json
|
||||
.claude/RESUME.md
|
||||
|
||||
# PID soubor lokálního helperu (běhový balast, ne konfigurace)
|
||||
ether.pid
|
||||
|
||||
# data z pochůzkových testů (.tth/tools/walk.sh fetch) — polohy, necommitovat
|
||||
walk-data/
|
||||
@@ -18,6 +18,15 @@ Thanks for considering contributing to this project!
|
||||
|
||||
### 3. Submitting Code Changes (Pull Requests)
|
||||
|
||||
The project receives far more code than it is able to process.
|
||||
To increase the likelihood of your PR being accepted, please consider
|
||||
the following:
|
||||
|
||||
- **Keep it small.** Changes of about 10 lines or fewer were merged 64% of the time; changes over 1000 lines, 10%.
|
||||
- **Keep the description short.** A few sentences on what changed and why is enough. Longer descriptions were merged less often.
|
||||
- **Build a track record with small fixes first.** First-time contributors were merged 31% of the time, rising to 74% after 10 merged PRs.
|
||||
- **Open the PR when it is ready for review, not as a draft.**
|
||||
|
||||
#### Small fixes (typos, comments, examples, small bug fixes)
|
||||
→ Just open a pull request — no prior issue needed
|
||||
|
||||
@@ -52,6 +61,15 @@ Please follow the existing C++ style (per the .clang-format)
|
||||
|
||||
(But consistency with existing code is more important than strict rules)
|
||||
|
||||
## LLM Agent Specific Advice
|
||||
|
||||
- **Have a human read and understand every line before opening the PR.** Check every claim in the description against the code.
|
||||
- **Search open PRs first** so you don't duplicate one that's already waiting.
|
||||
- **Pick a subsystem maintainers are actively merging in.** If several PRs for the same board or feature have sat for weeks with no response, a new one will likely sit too.
|
||||
- **Prefer low-risk changes.** Build fixes and documentation fixes merge most often (about 61% and 64%). Changes to protocol or behavior, and crash or overflow fixes, get much more scrutiny.
|
||||
- **Make a minimal diff in the existing style.** Don't reformat, rename, or "tidy" code next to your change.
|
||||
- **Don't use a templated description.** Lots of headings and boilerplate on a small change reads as generated. Just say what changed, why, and what hardware you tested on.
|
||||
|
||||
## Thank You!
|
||||
|
||||
> [!NOTE]
|
||||
|
||||
@@ -1,3 +1,650 @@
|
||||
## O tomto forku (meshcore-tth)
|
||||
|
||||
*English version [below](#about-this-fork-meshcore-tth) -- experimental
|
||||
firmware, not meant for regular users.*
|
||||
|
||||
> [!WARNING]
|
||||
> **Experimentální firmware – není určený pro běžné uživatele.** Tenhle fork
|
||||
> i všechny jeho releasy jsou osobní vývojová větev pro uzly jedné malé sítě:
|
||||
> rolling release nad upstreamovou větví `dev`, sestavovaný automaticky
|
||||
> zhruba dvakrát denně, bez stabilního kanálu, bez podpory a vyzkoušený jen
|
||||
> na našich deskách. Může obsahovat chyby, které uzel vyřadí z provozu,
|
||||
> a vrátit ho pak jde jen s USB nebo BLE v ruce. Pro běžný provoz nahrajte
|
||||
> oficiální MeshCore ([flasher.meshcore.io](https://flasher.meshcore.io)).
|
||||
|
||||
Fork projektu [meshcore-dev/MeshCore](https://github.com/meshcore-dev/MeshCore),
|
||||
na kterém běží repeatery, senzory a testovací desky malé české sítě na CZ
|
||||
meshi (869,432 MHz). Upstreamové větve `main` a `dev` se slučují automaticky
|
||||
dvakrát denně; všechno níže je navíc nad nimi. Náš kód je ve zdrojácích
|
||||
označený `CUSTOM (TeTeHacko)`. Nic z toho nemění protokol na rádiu.
|
||||
|
||||
### Repeater: antispam (všechno vypínatelné, nic z toho není v upstreamu)
|
||||
|
||||
**Po nahrání je zapnutý jen FairnessLimiter**, s limity se zhruba
|
||||
dvojnásobnou rezervou nad 30 dní skutečného provozu CZ meshe: na kanál dávka
|
||||
100 zpráv a pak jedna za 30 s, na odesílatele 150 a jedna za 10 s, na
|
||||
původce advertu 30 a jeden za 10 min. Je to síť na utržené floody, ne kvóta;
|
||||
`fairness off` ho vypne natrvalo. Okno na adverty, filtry a dry-run jsou
|
||||
vypnuté, dokud je nezapnete.
|
||||
|
||||
* **FairnessLimiter** – token buckety na přeposílané floody podle 1bajtových
|
||||
identifikátorů, které jsou v paketu stejně v čitelné podobě (hash kanálu,
|
||||
hash odesílatele, původce advertu). Port návrhu Beanowa
|
||||
[#1502](https://github.com/meshcore-dev/MeshCore/pull/1502), limity
|
||||
přepočítané z 30 dní skutečného provozu CZ meshe.
|
||||
`fairness [on|off|grid|cap|refill]`; přímo směrovaný provoz se neomezuje nikdy.
|
||||
* **Okno na adverty podle původce** – flood advert každého uzlu se přepošle
|
||||
nejvýš jednou za N hodin (`fairness advert <h>|clear`), převzato
|
||||
z AdvertLimiteru [DutchMeshCore](https://github.com/Dutch-MeshCore/MeshCore).
|
||||
Míří na uzly, které advertují každou minutu.
|
||||
* **Dry-run** – `fairness dryrun on` započítá každý verdikt, ale přepošle
|
||||
i tak; `fairness air` ukáže ušetřený (nebo ušetřitelný) airtime podle důvodu.
|
||||
* **Filtr kanálů** – na kanálech, jejichž klíč repeater zná (Public
|
||||
a `#hashtag` kanály), přestane přeposílat zprávy uvedených jmen odesílatelů
|
||||
(`filter add|del|list`). Jméno se dá podvrhnout: je to brzda na utrženého
|
||||
bota, ne bezpečnost.
|
||||
* **Blokace přeposílání podle hashe kanálu** – `filter hash add <hex> [s]`:
|
||||
bez klíče, takže funguje i na soukromých kanálech; příjem se nemění, jen
|
||||
přeposílání. S `s` se kanál neodřízne, ale přiškrtí (jeden paket za `s`
|
||||
sekund).
|
||||
* **Limit stáří zprávy** – `filter age <min>|off` (volitelné, 1–10080 min):
|
||||
nepřeposílá skupinové zprávy na dešifrovaných kanálech, jejichž čas od
|
||||
odesílatele je starší; bez nastavených hodin repeateru neplatí. Posuzuje
|
||||
hodiny odesílatele, takže zahodí i companiony bez synchronizace času –
|
||||
nastavuj ho na dny.
|
||||
* `filter dryrun on` započítá každý verdikt `filter`, ale přepošle i tak.
|
||||
|
||||
### Diagnostika a provoz
|
||||
|
||||
Všechny příkazy forku, kde je který build má a výchozí hodnoty:
|
||||
[docs/tth-commands.md](docs/tth-commands.md).
|
||||
|
||||
Repeater, room server i senzor (všechno s textovou konzolí) mají:
|
||||
|
||||
* **Watchdogy rádia.** Hardwarový watchdog chytí jen zamrzlou smyčku; dva naše
|
||||
uzly ale byly nalezeny hluché s běžící smyčkou a pomohl až restart.
|
||||
* `set radio.silence <min>` – **hluchý přijímač**: když se za `<min>` minut
|
||||
nepohne čítač přijatých rámců (počítá se i rámec s chybou CRC), uzel
|
||||
napřed znovu nahodí příjem, a když ani to nepomůže, restartuje se. Každý
|
||||
takový restart zdvojnásobí práh pro příští start (až 16×), první přijatý
|
||||
rámec ho vrátí, takže tiché místo neskončí ve smyčce restartů. Uloží se;
|
||||
**ve výchozím stavu vypnutý** (`0`) – práh volte s rezervou nad nejdelší
|
||||
běžné ticho na místě.
|
||||
* **Zaseknuté vysílání** (jen repeater): pakety čekají ve frontě a čítač
|
||||
odeslaných se nehýbe → znovu nahodí rádio, pak restart. Prázdná fronta se
|
||||
nepočítá. **Zapnutý, 15 min** (`RADIO_TXSTALL_MIN`); `set radio.txstall
|
||||
<min>|off` platí jen do restartu.
|
||||
* `get radio.reboots` – kolik restartů watchdogy udělaly (přežije i výpadek
|
||||
napájení); `get boot` – proč se deska naposledy resetovala a záznam
|
||||
o hardfaultu (vypíše se i při startu).
|
||||
* `dfu [uf2|serial|ota]` – spolehlivý reboot do bootloaderu (jen z lokální
|
||||
konzole); `i2c` – sken sběrnice.
|
||||
|
||||
Repeater navíc:
|
||||
|
||||
* `blink` (rozbliká LED, i přes mesh – najdete uzel na stožáru), `txpwr`
|
||||
(vysílací výkon do restartu, s verdiktem RadioLibu), čítače chyb vysílání
|
||||
ve stavové odpovědi.
|
||||
* Jen observer varianty (`*-observer`): textová konzole přes BLE vedle USB,
|
||||
`ble on|off` uložené přes reboot (`RPT_BLE_DEFAULT_OFF`: startuje vypnuté),
|
||||
vlastní BLE PIN (`ble pin`), uložený vysílací výkon spojení (`blepwr`),
|
||||
`bleconn`, neblokující BLE vysílání a parametry spojení, které vydrží i na
|
||||
slabém linku.
|
||||
* Taky jen observer varianty: pasivní analyzátor v konzoli – `nodes`
|
||||
(slyšené repeatery a roomy, klíč pro spojení více cest), `rxlog` (každý
|
||||
slyšený rámec: typ, cesta, SNR, RSSI), `pktlog` (surové rámce pro feed
|
||||
observeru), velké stránkované odpovědi.
|
||||
* Jen vlastní buildy, ne releasy:
|
||||
* kanálový bot (`BOT_CHANNEL_PSK`: `!link`, `!path`, `!snr`, `!heard`,
|
||||
`!noise`, `!ping`, `!help`, výběr přes `BOT_COMMANDS`, cooldown na
|
||||
odesílatele, ignore list) – odpovídá, aniž by přeposílal;
|
||||
* `RADIO_DIAG`: `radiostat` (stav přijímače SX1262 bez zásahu) a
|
||||
`radiokick rx|clrirq|standby|agc` (jeden krok obnovy, od nejjemnějšího –
|
||||
první, který pomůže, ukáže rozbitou vrstvu);
|
||||
* `PIN_DIAG`: `dio1` (stav přerušení v čipu proti úrovni na pinu – který
|
||||
konec mrtvé linky DIO1 je přerušený);
|
||||
* `LORA_POLL_IRQ`: provoz bez DIO1 pro desku s mrtvou linkou přerušení.
|
||||
|
||||
### Opravy jádra
|
||||
|
||||
* **Ochrana proti přehrání admin příkazů přežije reboot.** Upstream si
|
||||
poslední timestamp klienta drží jen v RAM, takže po každém restartu projde
|
||||
libovolný zachycený příkaz znovu – zachycený `reboot` uzel restartuje
|
||||
pořád dokola. Repeater, room server i sensor ho teď zapíšou do flash dřív,
|
||||
než příkaz provedou (`/s_acl_ts0|1`, střídavě s kontrolním součtem, takže
|
||||
ho nesmaže ani výpadek napájení při zápisu). Timestamp víc než den před
|
||||
hodinami uzlu (`ACL_TS_MAX_AHEAD`) se přijme, ale neuloží, aby companion
|
||||
s rozhozenými hodinami nezamkl admina. Ukládá se jen u adminů: host smí
|
||||
jen číst a s prázdným guest heslem se jím stane kdokoli, takže by každý
|
||||
jeho dotaz znamenal zápis do flash. Klientů se to nijak netýká.
|
||||
* **Hesla nejde hádat přes éter plnou rychlostí.** Upstream kontroluje každý
|
||||
login bez omezení a na špatné heslo ani neodpoví. Po 4 špatných heslech
|
||||
během 3 minut (`LOGIN_FAIL_MAX`, `LOGIN_FAIL_SECS`) se hesla do konce okna
|
||||
nekontrolují. Klient, který už je v ACL jako admin, projde vždy – login
|
||||
jeho jménem nikdo jiný poslat nedokáže, takže útok adminy nezamkne.
|
||||
* **Přehraný login bez hesla už nevyvolá flood odpověď.** Login klienta z ACL
|
||||
s prázdným heslem neměl ochranu proti přehrání; útočník tím nic nezískal,
|
||||
ale každá kopie donutila uzel poslat odpověď floodem přes celý mesh.
|
||||
* TRACE už nepřipisuje cestu za konec payloadu; parsování TRACE/PATH
|
||||
a `Packet::readFrom` hlídají meze.
|
||||
* `markSeen` je zase idempotentní (odesílací cesta ujídala okno deduplikace).
|
||||
* Záložní výpočet v `calcMaxPacketMillis` už nepodteče (uzel na tom ohluchl).
|
||||
* Šířka path hashe se bere z nastavení uzlu na všech cestách vysílání včetně
|
||||
`sendZeroHop`; výchozí jsou 2bajtové path hashe (`PATH_HASH_MODE_DEFAULT`).
|
||||
* Nepovedené vysílání se zařadí znovu s odstupem, místo aby se zahodilo.
|
||||
* RSSI každého paketu se zaznamená při příjmu; `ContactInfo` se před
|
||||
částečným vyplněním vynuluje.
|
||||
|
||||
### Napájení, hodiny, GPS
|
||||
|
||||
* GPS duty cycle (`gps duty`), i na T1000-E, kde nebyl: přijímač běží jen
|
||||
kolem synchronizace hodin (jednou denně, po neúspěšném okně znovu za 6 h).
|
||||
Dotaz na polohu přijímač probudí pro příští dotaz.
|
||||
* Uzel bez GPS startuje na čase sestavení firmwaru, ne v roce 2024; hodiny
|
||||
a záznam o hardfaultu přežijí teplý reset (`.noinit`); `clkreboot`.
|
||||
* Na solárních uzlech žádná blikající LED a pomalejší BLE advertising.
|
||||
* Stav baterie jako ikona na konci advertovaného jména: `set batt.icon on`,
|
||||
prahy `set batt.icon.lo|hi <mV>` (výchozí vypnuté; dlouhé jméno ikonu
|
||||
nepojme a příkaz na to upozorní).
|
||||
* Volitelný RX duty cycle (`set radio.rxps off|on|balanced|max`, jemněji
|
||||
`level <1-10>`; port PowerSaving z EasySkyMesh): SX1262 mezi krátkými okny
|
||||
poslechu spí. Ve veřejných buildech je zabudovaný a **vypnutý**; `max` na
|
||||
lavici ušetřil ~2,3 mA bez ztráty paketů ([docs/power.md](docs/power.md)),
|
||||
na ostrém meshi ale jeden náš stožár ztratil 16 % příjmu – zapínat s rozmyslem. Jen
|
||||
SX1262, ne LR1110 (T1000-E).
|
||||
* Podpěťová pojistka při startu (`PWRMGT_VOLTAGE_BOOTLOCK`) je na nRF52
|
||||
**vypnutá**, stejně jako v upstreamu od v1.18.0
|
||||
([#2377](https://github.com/meshcore-dev/MeshCore/pull/2377)): pevný práh
|
||||
3,3 V nepouštěl k životu uzly na LiFePO4 nebo LTO. Firmware tak naběhne na
|
||||
jakékoli chemii článku; před hlubokým vybitím má chránit BMS nebo ochranná
|
||||
destička článku. Konfigurovatelná pojistka podle chemie čeká na upstream
|
||||
([#2088](https://github.com/meshcore-dev/MeshCore/pull/2088)).
|
||||
|
||||
### Senzory a companiony
|
||||
|
||||
* `simple_sensor`: telemetrie z externí stanice po UART
|
||||
(`BudkaLinkSensorManager`, jeden LPP kanál na veličinu), `sensor read`.
|
||||
* Senzory, které jinak měří nepřetržitě (INA219, INA226, INA260, INA3221,
|
||||
BMP280), mezi čteními telemetrie spí a měří jen na vyžádání (nápad a první
|
||||
patch pro INA219: Alkel Brostl). Čipy INA se rozlišují podle ID, takže
|
||||
INA226 už se nedetekuje jako INA219. Odpor bočníku se nastavuje za běhu
|
||||
a ukládá se: `sensor set ina.shunt <mΩ>`.
|
||||
* Companion: `gps duty` přežije reboot, kopie data sestavení má hlídanou
|
||||
délku. Export privátního klíče, čtení BLE PINu a jeho změna (i přes CLI
|
||||
`set pin`) jdou jen přes spárované BLE, ne přes USB, UART ani WiFi/TCP,
|
||||
a odpověď s klíčem či PINem jde jen tam, odkud přišel dotaz. (Merge v1.17
|
||||
tu kontrolu potichu vyřadil; build bez BLE bere své jediné rozhraní dál
|
||||
jako důvěryhodné.) KISS modem: oprava o jedna vedle při zkracování jména.
|
||||
|
||||
### Veřejné buildy: výchozí nastavení pro český mesh
|
||||
|
||||
Releasy z tohoto repozitáře (`pub-release`) jsou přednastavené pro český
|
||||
mesh podle wiki [meshcore.cz](https://meshcore.cz/), takže čerstvě nahraný
|
||||
uzel nepotřebuje obvyklé kolečko nastavování:
|
||||
|
||||
* rádio 869,432 MHz / 62,5 kHz / SF7 / CR5 (všechny buildy);
|
||||
* repeater a room server: zero-hop advert vypnutý, flood advert každých 25 h,
|
||||
duty cycle 10 % (`get dutycycle` → `10.0%`; zastaralé `af` je 9);
|
||||
* repeater: regiony `cz` a `cs` vedle `*` – vlastní `cz-<kraj>` přidáš přes
|
||||
`region put cz-xxx cz` + `region save`;
|
||||
* 2bajtové path hashe (výchozí v tomto forku);
|
||||
* repeater: filtr kanálů (`filter add <jméno>`) je zabudovaný pro Public,
|
||||
`#meshcore` a `#test`, s prázdným seznamem – nedělá nic, dokud do něj
|
||||
nepřidáš jméno.
|
||||
|
||||
Platí jen pro uzel bez uloženého nastavení (nový nebo po `erase`): nové
|
||||
nahrání ponechá, co už uzel má, a regiony, které jsi smazal a uložil,
|
||||
zůstanou smazané. Jméno a admin heslo si nastav sám.
|
||||
|
||||
**BLE PIN companionu je veřejný `123456`** (desky s displejem si losují
|
||||
vlastní a ukážou ho). Kdo se s ním spáruje, má companion celý: zprávy,
|
||||
kontakty, export privátního klíče. Po prvním spárování ho proto změň
|
||||
v aplikaci. A s deskou v ruce nechrání nic ani PIN, ani heslo: flash není
|
||||
zamčená a bootloader přijme jakýkoli firmware. Ztracený nebo ukradený uzel
|
||||
ber jako vyzrazený – u repeateru změň admin heslo všude, kde bylo stejné,
|
||||
a vyhoď jeho klíč z ACL; u companionu ber kanály, které na něm byly, jako
|
||||
známé.
|
||||
|
||||
Varianty observer (`*_repeater-observer-*`) nRF52 repeaterů (XIAO, SenseCAP
|
||||
Solar, RAK4631, T1000-E, Heltec T114) přidávají buffery `nodes` / `rxlog` /
|
||||
`pktlog` a textovou konzoli přes BLE, aby šel repeater číst přes USB nebo BLE
|
||||
([meshcore-repeater-observer](https://git.rfa.cz/tth-pub/meshcore-repeater-observer)).
|
||||
BLE konzole je po nahrání **vypnutá** (`RPT_BLE_DEFAULT_OFF`). Nemá vlastní
|
||||
přihlášení, jen BLE PIN, a PIN v buildu je veřejný zástupný `123456`. Nejdřív
|
||||
si proto nastav vlastní – v USB konzoli, nebo jako admin přes mesh (vzdálené
|
||||
CLI v aplikaci): `ble pin <6 číslic>` (uloží se a přežije reboot i nové
|
||||
nahrání; zároveň smaže všechny bondy, takže spárovaná zařízení se párují
|
||||
znovu). Teprve pak `ble on` – dokud je PIN zástupný, tyhle buildy ho odmítnou.
|
||||
`ble` ukáže, jestli je PIN `own` nebo `build default`, samotný PIN nikdy.
|
||||
Releasy do `tth-654d53f3` `ble pin` nemají: BLE tam nech vypnuté a používej USB.
|
||||
|
||||
### Nahrání releasu
|
||||
|
||||
Každý release je automatický build nad upstreamovým `dev` (viz upozornění
|
||||
nahoře), ne stabilní verze. Nahrávejte ho jen na uzly, na které dosáhnete,
|
||||
a nový release vždy nejdřív na jeden z nich.
|
||||
|
||||
Soubory jsou v [Releases](https://git.rfa.cz/tth-pub/meshcore-tth/releases).
|
||||
Release se jmenuje podle upstreamové verze a data, např.
|
||||
`v1.18.0+tth.20261112` (druhý téhož dne `.2`), a v popisu má změny od
|
||||
předchozího releasu. Pro každou desku a roli je jedna sada
|
||||
(`<deska>_<role>-<release>`, např. `Xiao_nrf52_repeater-v1.18.0+tth.20261112.zip`):
|
||||
`.zip` a `.uf2` pro nRF52, `.bin` pro ESP32 (`-merged.bin` je celý obraz pro
|
||||
prázdnou desku, obyčejný `.bin` aktualizace). Kontrolní součty jsou
|
||||
v `SHA256SUMS`. Releasy do 12. 11. 2026 se jmenovaly `tth-<sha>`.
|
||||
|
||||
**nRF52 (XIAO, RAK4631, SenseCAP Solar, T1000-E, T114) přes
|
||||
[webový flasher MeshCore](https://flasher.meshcore.io)** – Chrome, Edge nebo
|
||||
Chromium na počítači (Web Serial; ne Firefox ani Safari):
|
||||
|
||||
1. Připoj desku přes USB.
|
||||
2. Klikni na **Custom Firmware** a vyber `.zip` pro svou desku.
|
||||
3. Klikni na **Enter DFU mode** a vyber sériový port desky. Deska se
|
||||
restartuje do bootloaderu a objeví se jako nový port.
|
||||
4. Klikni na **Flash!** a vyber ten nový port. Zhruba 30 s, pak se deska
|
||||
restartuje do nového firmwaru.
|
||||
5. **Console** ve flasheru (nebo jakýkoli sériový terminál, 115200) ověří
|
||||
výsledek: `ver` ukáže `v1.xx.x-tth<sha>`, stejně jako řádek „Verze v uzlu“
|
||||
v popisu releasu.
|
||||
|
||||
**Neklikej na Erase Flash**, pokud nechceš nový uzel: smaže identitu (klíč
|
||||
uzlu a všechno, co ho zná) i veškeré nastavení. Obyčejné nahrání je zachová.
|
||||
|
||||
Vyzkoušeno na XIAO (repeater-observer, 3. 11. 2026). ESP32 `.bin` přes stejné
|
||||
tlačítko Custom Firmware tu vyzkoušené není.
|
||||
|
||||
Bez webového flasheru: na většině desek otevře dvojí stisk resetu bootloader
|
||||
jako USB disk; zkopíruj na něj `.uf2`. Nebo
|
||||
`adafruit-nrfutil dfu serial -pkg <soubor>.zip -p <port> -b 115200` s deskou
|
||||
v bootloaderu.
|
||||
|
||||
Nový uzel po nahrání nastav v konzoli: `set name <jméno>`,
|
||||
`password <admin heslo>` (nejvýš 15 znaků), vlastní region přes
|
||||
`region put cz-<kraj> cz` + `region save`. Repeater přeposílá od prvního
|
||||
startu (výchozí v upstreamu) a tyhle buildy jsou na ostré CZ frekvenci: na
|
||||
stole bez antény dej `set repeat off`, dokud není na místě.
|
||||
|
||||
### Experimentální: aktualizace firmwaru od admina (`*-ota`)
|
||||
|
||||
Každý nRF52 build s textovou konzolí (repeater, observer, room server,
|
||||
senzor) je v releasu ještě jednou jako **experimentální** `*-ota` /
|
||||
`*-observer-ota`. Ten umí přijmout nový firmware od admina příkazy `fw …`:
|
||||
v USB nebo BLE konzoli, nebo **přes mesh jako vzdálené admin CLI**. Bez změny
|
||||
bootloaderu a bez druhé banky: uzel si balíček uloží do volné flash,
|
||||
zkontroluje ho celý (podpis, hashe, nanečisto provedená delta) a přepíše se
|
||||
až na `fw apply`, rutinou běžící z RAM. Když během přepisu vypadne napájení,
|
||||
zůstane v bootloaderu a vrátí se přes USB/BLE DFU.
|
||||
|
||||
* V releasu je ke každému `*-ota` obrazu plný balíček
|
||||
`<deska>_<role>-ota-<release>.mcfw` (jen přes USB/BLE) a delta
|
||||
`….from-<starší release>.mcfw` od každého drženého předchozího releasu,
|
||||
typicky jednotky kB.
|
||||
* **Přes mesh uzel přijme jen deltu, a nikdy ne starší verzi, než má** –
|
||||
vynucuje to uzel, ne nástroj. Plný obraz nebo návrat ke starší verzi jen
|
||||
lokálně (`fw apply downgrade`). `fw apply` čeká na baterii ≥ 3,8 V, pokud
|
||||
uzel neběží z USB.
|
||||
* Balíčky i `SHA256SUMS` jsou podepsané klíčem `meshcore-ota@tth-pub`
|
||||
a `*-ota` obraz jiný podpis nepřijme. Ověření stažených souborů:
|
||||
`ssh-keygen -Y verify -f tools/ota_allowed_signers -I meshcore-ota@tth-pub
|
||||
-n meshcore-ota -s SHA256SUMS.sig < SHA256SUMS`. Vlastní build s vlastním
|
||||
klíčem: `[ota] pubkey` v `platformio.local.ini`.
|
||||
* První `*-ota` obraz se nahraje obyčejně (viz výše), další už jako delta.
|
||||
Nástroje: `tools/ota_push.py` (USB), `tools/ota_mesh_push.py` (přes mesh
|
||||
skrz companion; potřebuje pythonovou knihovnu `meshcore`, admin heslo bere
|
||||
z `[secrets] admin_pw` v `platformio.local.ini`; s `--side` jde přenos po
|
||||
vedlejším kanálu mimo sdílený mesh), `tools/ota_pack.py info`. Přenos samotný
|
||||
je OTA engine kolekce
|
||||
[tth.meshcore](https://git.rfa.cz/tth-pub/meshcore-ansible) (modul
|
||||
`meshcore_fw_ota`), stejný kód pro nástroje i Ansible. Z telefonu: fork
|
||||
aplikace [meshcore-open](https://git.rfa.cz/tth-pub/meshcore-open), správa
|
||||
repeateru → Firmware update (OTA), deltu si najde v releasu sám.
|
||||
Postup a čísla: [docs/ota.md](docs/ota.md).
|
||||
* **Experimentální i v rámci tohoto forku**: obrazy přicházejí s každým
|
||||
releasem (viz upozornění nahoře) a nemají druhou banku ani automatický
|
||||
návrat. Vadný firmware, který nabootuje, běží, dokud nepošlete další;
|
||||
takový, který nenabootuje, chce USB/BLE DFU v ruce. Vyzkoušeno na lavici
|
||||
(XIAO, USB, mesh, vedlejší kanál) a od 13. 11. 2026 na dvou našich
|
||||
stožárech. Proti obrazu, který nabootuje s mrtvým rádiem, jsou watchdogy
|
||||
rádia (viz Diagnostika a provoz): pro uzly, kam posíláte OTA, zapněte
|
||||
`set radio.silence`. Stojí ~10 kB RAM navíc.
|
||||
|
||||
### Sestavení
|
||||
|
||||
* Razítko verze v každém nRF52 envu (`v1.18.0-tth<sha>`, `+` = neuklizený
|
||||
strom), základní verze z upstreamového tagu (`tools/build_version.py`).
|
||||
* `tools/`: nástroje na uzly – konzole (USB, BLE), flashování, testy na
|
||||
lavici, diagnostika ([tools/README.md](tools/README.md)). Desky podle jména
|
||||
bere z lokálního configu mimo repo (`tools/config.example.ini`).
|
||||
* `hardware/cavity-box`: parametrická krabička pro dutinový filtr na stožár.
|
||||
|
||||
---
|
||||
|
||||
## About this fork (meshcore-tth)
|
||||
|
||||
*Česká verze [výše](#o-tomto-forku-meshcore-tth).*
|
||||
|
||||
> [!WARNING]
|
||||
> **Experimental firmware -- not meant for regular users.** This fork and all
|
||||
> its releases are a personal development branch for the nodes of one small
|
||||
> network: a rolling release on upstream `dev`, built automatically about
|
||||
> twice a day, with no stable channel, no support, and tried only on our own
|
||||
> boards. It may carry bugs that take a node out of service, and getting one
|
||||
> back then needs USB or BLE in hand. For everyday use flash the official
|
||||
> MeshCore ([flasher.meshcore.io](https://flasher.meshcore.io)).
|
||||
|
||||
A fork of [meshcore-dev/MeshCore](https://github.com/meshcore-dev/MeshCore)
|
||||
that runs the repeaters, sensors and bench boards of a small Czech network on
|
||||
the CZ mesh (869.432 MHz). Upstream `main` and `dev` are merged automatically
|
||||
twice a day; everything below is on top of that. Our code is marked
|
||||
`CUSTOM (TeTeHacko)` in the source. Nothing here changes the wire protocol.
|
||||
|
||||
### Repeater: antispam (all of it off-switchable, none of it upstream)
|
||||
|
||||
**After flashing only the FairnessLimiter is on**, with limits about twice
|
||||
above 30 days of real CZ mesh traffic: per channel a burst of 100 messages,
|
||||
then one per 30 s; per sender 150 and one per 10 s; per advert origin 30 and
|
||||
one per 10 min. It is a net for runaway floods, not a quota; `fairness off`
|
||||
switches it off for good. The advert window, the filters and dry-run stay
|
||||
off until you turn them on.
|
||||
|
||||
* **FairnessLimiter** -- token buckets on forwarded floods, keyed on the 1-byte
|
||||
ids already in the clear (channel hash, sender hash, advert origin). Port of
|
||||
Beanow's proposal [#1502](https://github.com/meshcore-dev/MeshCore/pull/1502),
|
||||
limits re-sized from 30 days of real CZ traffic.
|
||||
`fairness [on|off|grid|cap|refill]`; direct-routed traffic is never limited.
|
||||
* **Per-origin advert window** -- each node's flood advert forwarded at most
|
||||
once per N hours (`fairness advert <h>|clear`), ported from
|
||||
[DutchMeshCore](https://github.com/Dutch-MeshCore/MeshCore)'s AdvertLimiter.
|
||||
Aimed at nodes that re-advertise every minute.
|
||||
* **Dry-run** -- `fairness dryrun on` counts every verdict but forwards anyway;
|
||||
`fairness air` reports the airtime shed (or that would be) per reason.
|
||||
* **Channel filter** -- on channels whose key the repeater knows (Public and
|
||||
`#hashtag` channels), stop forwarding messages of listed sender names
|
||||
(`filter add|del|list`). Names are spoofable: it contains a runaway bot,
|
||||
it is not security.
|
||||
* **Channel-hash deny-forward** -- `filter hash add <hex> [secs]`: keyless,
|
||||
works on private channels too; reception is unaffected, only forwarding.
|
||||
With `secs` the channel is throttled (one packet per `secs`) instead of cut.
|
||||
* **Message age limit** -- `filter age <min>|off` (opt-in, 1-10080 min): do not
|
||||
forward group texts on the decrypted channels whose sender timestamp is
|
||||
older; inactive while the repeater clock is unset. It judges the sender's
|
||||
clock, so companions without a time sync are dropped too -- keep it in days.
|
||||
* `filter dryrun on` counts every `filter` verdict but forwards anyway.
|
||||
|
||||
### Diagnostics and operations
|
||||
|
||||
Every command of the fork, which builds have it and the defaults:
|
||||
[docs/tth-commands.md](docs/tth-commands.md).
|
||||
|
||||
Repeater, room server and sensor (everything with a text console) have:
|
||||
|
||||
* **Radio watchdogs.** The hardware watchdog only catches a frozen loop; two
|
||||
of our nodes were found deaf with the loop running, and only a reboot
|
||||
helped.
|
||||
* `set radio.silence <min>` -- **deaf receiver**: when the received-frame
|
||||
counter does not move for `<min>` minutes (a frame with a CRC error
|
||||
counts), the node re-arms its receiver first and reboots if that does not
|
||||
help either. Each such reboot doubles the threshold for the next boot (up
|
||||
to 16x) and the first frame received resets it, so a quiet site does not
|
||||
end in a reboot loop. Saved; **off by default** (`0`) -- pick a threshold
|
||||
well above the longest normal quiet spell of the site.
|
||||
* **Stalled TX** (repeater only): packets wait in the queue and the sent
|
||||
counter does not move -> re-arm the radio, then reboot. An empty queue
|
||||
never counts. **On, 15 min** (`RADIO_TXSTALL_MIN`); `set radio.txstall
|
||||
<min>|off` holds until the next reboot.
|
||||
* `get radio.reboots` -- reboots done by the watchdogs (survives power
|
||||
loss); `get boot` -- why the board last reset, and the hardfault record
|
||||
(also printed at boot).
|
||||
* `dfu [uf2|serial|ota]` -- a deterministic reboot into the bootloader (local
|
||||
console only); `i2c` -- bus scan.
|
||||
|
||||
The repeater also has:
|
||||
|
||||
* `blink` (flashes the LED, also over the mesh -- finds a node on a mast),
|
||||
`txpwr` (TX power until reboot, with RadioLib's verdict), TX-failure
|
||||
counters in the status reply.
|
||||
* Observer variants only (`*-observer`): text console over BLE next to USB,
|
||||
`ble on|off` saved across reboots (`RPT_BLE_DEFAULT_OFF`: starts off), own
|
||||
BLE PIN (`ble pin`), persisted connection TX power (`blepwr`), `bleconn`, a
|
||||
non-blocking BLE TX pump and connection parameters that hold on a weak
|
||||
link.
|
||||
* Also observer variants only: a passive analyzer in the console --
|
||||
`nodes` (heard repeaters/rooms, multi-path join key), `rxlog` (every frame
|
||||
heard, type/path/SNR/RSSI), `pktlog` (raw frames for an observer feed), big
|
||||
paged replies.
|
||||
* Own builds only, not in the releases:
|
||||
* channel bot (`BOT_CHANNEL_PSK`: `!link`, `!path`, `!snr`, `!heard`,
|
||||
`!noise`, `!ping`, `!help`, narrowed by `BOT_COMMANDS`, per-sender
|
||||
cooldown, ignore list) -- answers without repeating;
|
||||
* `RADIO_DIAG`: `radiostat` (SX1262 receiver state, hands off) and
|
||||
`radiokick rx|clrirq|standby|agc` (one recovery step at a time, gentlest
|
||||
first -- the first that helps names the broken layer);
|
||||
* `PIN_DIAG`: `dio1` (the chip's IRQ status against the level on the pin --
|
||||
which end of a dead DIO1 line is broken);
|
||||
* `LORA_POLL_IRQ`: DIO1-less operation for a board with a dead IRQ line.
|
||||
|
||||
### Core fixes
|
||||
|
||||
* **Replay protection of admin commands survives a reboot.** Upstream keeps a
|
||||
client's last timestamp in RAM only, so after every restart any captured
|
||||
command is accepted again -- a captured `reboot` reboots the node forever.
|
||||
Repeater, room server and sensor now write it to flash before acting on the
|
||||
command (`/s_acl_ts0|1`, alternating with a checksum, so a power cut mid-write
|
||||
does not lose it). A timestamp more than a day ahead of the node's clock
|
||||
(`ACL_TS_MAX_AHEAD`) is accepted but not stored, so a companion with a runaway
|
||||
clock cannot lock its admin out. Only admins are stored: a guest can only
|
||||
read, and with the empty guest password anybody is one, so its every
|
||||
request would be a flash write. Nothing changes for clients.
|
||||
* **Passwords can no longer be guessed over the air at full speed.** Upstream
|
||||
checks every login without a limit and does not even answer a wrong one.
|
||||
After 4 wrong passwords within 3 minutes (`LOGIN_FAIL_MAX`,
|
||||
`LOGIN_FAIL_SECS`) no password is checked until the window ends. A client
|
||||
that is already an admin in the ACL always gets through -- nobody else can
|
||||
send a login in its name, so the attack cannot lock the admins out.
|
||||
* **A replayed blank-password login no longer floods a reply.** A login from a
|
||||
client in the ACL with an empty password had no replay check; replayed, it
|
||||
gained nothing, but every copy made the node flood its reply over the mesh.
|
||||
* TRACE no longer appends its path past the end of the payload; TRACE/PATH
|
||||
parsing and `Packet::readFrom` are bounds-checked.
|
||||
* `markSeen` is idempotent again (the send path was eating the dedup window).
|
||||
* `calcMaxPacketMillis` fallback no longer underflows (a node went deaf on it).
|
||||
* Path-hash width comes from the node's prefs on every TX path, including
|
||||
`sendZeroHop`; 2-byte path hashes are the default (`PATH_HASH_MODE_DEFAULT`).
|
||||
* Failed transmits are re-queued with backoff instead of dropped.
|
||||
* Per-packet RSSI captured at RX; `ContactInfo` zeroed before a partial fill.
|
||||
|
||||
### Power, clock, GPS
|
||||
|
||||
* GPS duty cycle (`gps duty`), also on the T1000-E, which had none: the
|
||||
receiver runs only around a clock sync (once a day, after a window without
|
||||
a fix again in 6 h). A position request warms it for the next request.
|
||||
* A node without GPS starts at its build epoch, not in 2024; the clock and a
|
||||
hardfault record survive a warm reset (`.noinit`); `clkreboot`.
|
||||
* No blinking LED and slower BLE advertising on solar nodes.
|
||||
* Battery level as an icon at the end of the advertised name: `set batt.icon
|
||||
on`, thresholds `set batt.icon.lo|hi <mV>` (off by default; a long name has
|
||||
no room for it and the command says so).
|
||||
* Optional RX duty cycle (`set radio.rxps off|on|balanced|max`, finer
|
||||
`level <1-10>`; ported from EasySkyMesh PowerSaving): the SX1262 sleeps
|
||||
between short listening windows. Built into the public releases and
|
||||
**off**; `max` saved ~2.3 mA on the bench with no packet loss
|
||||
([docs/power.md](docs/power.md)), but on the live mesh one of our masts lost
|
||||
16 % of its reception -- switch it on with care. SX1262 only, not the LR1110
|
||||
(T1000-E).
|
||||
* The nRF52 boot undervoltage lock (`PWRMGT_VOLTAGE_BOOTLOCK`) is **off**,
|
||||
as in upstream since v1.18.0
|
||||
([#2377](https://github.com/meshcore-dev/MeshCore/pull/2377)): its fixed
|
||||
3.3 V threshold kept LiFePO4 and LTO nodes from booting. The firmware boots
|
||||
on any cell chemistry; deep-discharge protection is up to the BMS or the
|
||||
cell's protection board. A configurable, chemistry-aware lock is waiting
|
||||
for upstream ([#2088](https://github.com/meshcore-dev/MeshCore/pull/2088)).
|
||||
|
||||
### Sensors and companions
|
||||
|
||||
* `simple_sensor`: telemetry from an external station over UART
|
||||
(`BudkaLinkSensorManager`, one LPP channel per meter), `sensor read`.
|
||||
* Sensors that would otherwise convert continuously (INA219, INA226, INA260,
|
||||
INA3221, BMP280) sleep between telemetry reads and measure on demand (idea
|
||||
and first INA219 patch: Alkel Brostl). INA chips are told apart by their ID,
|
||||
so an INA226 is no longer taken for an INA219. The shunt is set at runtime
|
||||
and saved: `sensor set ina.shunt <mOhm>`.
|
||||
* Companion: `gps duty` persists, bounded build-date copy. Private key
|
||||
export, reading the BLE PIN and changing it (CLI `set pin` included) work
|
||||
only over paired BLE, never over USB, a UART or WiFi/TCP, and the reply that
|
||||
carries the key or PIN goes back only where the request came from. (The
|
||||
v1.17 merge had silently disabled that gate; a build without BLE still
|
||||
trusts its one transport.) KISS modem: off-by-one in the name clamp.
|
||||
|
||||
### Public builds: Czech mesh defaults
|
||||
|
||||
Releases built from this repository (`pub-release`) come preset for the
|
||||
Czech mesh, following the [meshcore.cz](https://meshcore.cz/) wiki, so a
|
||||
freshly flashed node does not need the usual round of settings:
|
||||
|
||||
* radio 869.432 MHz / 62.5 kHz / SF7 / CR5 (all builds);
|
||||
* repeater and room server: zero-hop advert off, flood advert every 25 h,
|
||||
10 % duty cycle (`get dutycycle` → `10.0%`; the deprecated `af` reads 9);
|
||||
* repeater: regions `cz` and `cs` next to `*` -- add your own `cz-<kraj>`
|
||||
with `region put cz-xxx cz` + `region save`;
|
||||
* 2-byte path hashes (this fork's default);
|
||||
* repeater: the channel filter (`filter add <name>`) is built in for Public,
|
||||
`#meshcore` and `#test`, with an empty list -- it does nothing until you
|
||||
add a name.
|
||||
|
||||
They apply only to a node with no saved settings (new, or after an erase):
|
||||
a reflash keeps whatever the node already has, and regions you removed and
|
||||
saved stay removed. Set a name and an admin password yourself.
|
||||
|
||||
**The companion's BLE PIN is the public `123456`** (boards with a display
|
||||
draw their own and show it). Whoever pairs with it owns the companion:
|
||||
messages, contacts, private key export. So change it in the app after the
|
||||
first pairing. And with the board in hand neither the PIN nor a password
|
||||
protects anything: the flash is not locked and the bootloader takes any
|
||||
firmware. Treat a lost or stolen node as compromised -- for a repeater,
|
||||
change the admin password wherever it was the same and drop its key from
|
||||
ACLs; for a companion, treat the channels it held as known.
|
||||
|
||||
Observer variants (`*_repeater-observer-*`) of the nRF52 repeaters (XIAO,
|
||||
SenseCAP Solar, RAK4631, T1000-E, Heltec T114) add the `nodes` / `rxlog` /
|
||||
`pktlog` rings and a text console over BLE, for reading the repeater over
|
||||
USB or BLE ([meshcore-repeater-observer](https://git.rfa.cz/tth-pub/meshcore-repeater-observer)).
|
||||
The BLE console is **off** after flashing (`RPT_BLE_DEFAULT_OFF`). It has no
|
||||
login of its own, only the BLE PIN, and the build's PIN is the public
|
||||
placeholder `123456`. So first set your own -- in the USB console, or as
|
||||
admin over the mesh (remote CLI in the app): `ble pin <6 digits>` (saved, survives a reboot and a reflash; it also drops
|
||||
every existing bond, so paired devices pair again). Only then `ble on` --
|
||||
these builds refuse it while the PIN is still the placeholder. `ble` shows
|
||||
whether the PIN is `own` or `build default`, never the PIN itself. Releases
|
||||
up to `tth-654d53f3` do not have `ble pin`: keep BLE off there and use USB.
|
||||
|
||||
### Flashing a release
|
||||
|
||||
Every release is an automatic build on upstream `dev` (see the warning
|
||||
above), not a stable version. Flash it only on nodes you can reach, and each
|
||||
new release on one of them first.
|
||||
|
||||
Files are in [Releases](https://git.rfa.cz/tth-pub/meshcore-tth/releases).
|
||||
A release is named after the upstream version and the date, e.g.
|
||||
`v1.18.0+tth.20261112` (a second one that day `.2`), and its notes list the
|
||||
changes since the previous release. One set per board and role
|
||||
(`<board>_<role>-<release>`, e.g. `Xiao_nrf52_repeater-v1.18.0+tth.20261112.zip`):
|
||||
`.zip` and `.uf2` for nRF52 boards, `.bin` for ESP32 (`-merged.bin` is the
|
||||
full image for a blank board, the plain `.bin` an update). `SHA256SUMS` lists
|
||||
the checksums. Releases up to 12. 11. 2026 were named `tth-<sha>`.
|
||||
|
||||
**nRF52 (XIAO, RAK4631, SenseCAP Solar, T1000-E, T114) with the
|
||||
[MeshCore web flasher](https://flasher.meshcore.io)** -- Chrome, Edge or
|
||||
Chromium on a computer (Web Serial; not Firefox or Safari):
|
||||
|
||||
1. Connect the board over USB.
|
||||
2. Click **Custom Firmware** and choose the `.zip` for your board.
|
||||
3. Click **Enter DFU mode** and pick the board's serial port. The board
|
||||
restarts into its bootloader and shows up as a new port.
|
||||
4. Click **Flash!** and pick that new port. About 30 s, then the board
|
||||
restarts into the new firmware.
|
||||
5. **Console** in the flasher (or any serial terminal, 115200) checks the
|
||||
result: `ver` shows `v1.xx.x-tth<sha>`, the same as the "Verze v uzlu"
|
||||
(node version) line in the release notes.
|
||||
|
||||
**Do not click Erase Flash** unless you want a new node: it wipes the
|
||||
identity (the node's key and everything that knows it) together with all
|
||||
settings. A plain flash keeps them.
|
||||
|
||||
Tried on a XIAO (repeater-observer, 3. 11. 2026). ESP32 `.bin` through the
|
||||
same Custom Firmware button is untested here.
|
||||
|
||||
Without the web flasher: on most boards a double-tap of reset opens the
|
||||
bootloader as a USB drive; copy the `.uf2` onto it. Or
|
||||
`adafruit-nrfutil dfu serial -pkg <file>.zip -p <port> -b 115200` with the
|
||||
board in the bootloader.
|
||||
|
||||
After flashing a new node, set it up in the console: `set name <name>`,
|
||||
`password <admin password>` (at most 15 characters), your own region with
|
||||
`region put cz-<kraj> cz` + `region save`. A repeater forwards from its
|
||||
first boot (upstream default) and these builds are on the live CZ frequency:
|
||||
on a desk without its antenna, `set repeat off` until it is in place.
|
||||
|
||||
### Experimental: firmware update pushed by the admin (`*-ota`)
|
||||
|
||||
Every nRF52 build with a text console (repeater, observer, room server,
|
||||
sensor) is in the release once more as an **experimental** `*-ota` /
|
||||
`*-observer-ota` image. It takes a new firmware from its admin with the
|
||||
`fw …` commands: on the USB or BLE console, or **over the mesh as remote admin
|
||||
CLI**. No bootloader change, no second bank: the node stores the package in
|
||||
free flash, checks all of it (signature, hashes, the delta applied dry) and
|
||||
rewrites itself only on `fw apply`, from a routine running in RAM. A power
|
||||
cut during the rewrite leaves it in the bootloader, back via USB/BLE DFU.
|
||||
|
||||
* Each `*-ota` image comes with a full package
|
||||
`<board>_<role>-ota-<release>.mcfw` (USB/BLE only) and a delta
|
||||
`….from-<earlier release>.mcfw` from every kept earlier release, typically
|
||||
a few kB.
|
||||
* **Over the mesh a node takes only a delta, and never an older version than
|
||||
it runs** -- enforced by the node, not by the tool. A full image or a step
|
||||
back only locally (`fw apply downgrade`). `fw apply` wants the battery at
|
||||
3.8 V or more unless the node runs on USB.
|
||||
* Packages and `SHA256SUMS` are signed by `meshcore-ota@tth-pub`, and an
|
||||
`*-ota` image accepts no other signature. Checking the downloads:
|
||||
`ssh-keygen -Y verify -f tools/ota_allowed_signers -I meshcore-ota@tth-pub
|
||||
-n meshcore-ota -s SHA256SUMS.sig < SHA256SUMS`. Your own build with your own
|
||||
key: `[ota] pubkey` in `platformio.local.ini`.
|
||||
* The first `*-ota` image is flashed the usual way (above), later ones go as
|
||||
deltas. Tools: `tools/ota_push.py` (USB), `tools/ota_mesh_push.py` (over the
|
||||
mesh through a companion; needs the `meshcore` Python library, takes the
|
||||
admin password from `[secrets] admin_pw` in `platformio.local.ini`; `--side`
|
||||
carries the transfer on a side channel, off the shared mesh),
|
||||
`tools/ota_pack.py info`. The transfer itself is the OTA engine of the
|
||||
[tth.meshcore](https://git.rfa.cz/tth-pub/meshcore-ansible) Ansible
|
||||
collection (module `meshcore_fw_ota`), one code for the tools and Ansible.
|
||||
From a phone: the [meshcore-open](https://git.rfa.cz/tth-pub/meshcore-open)
|
||||
fork, repeater management → Firmware update (OTA), which finds the delta in
|
||||
the release by itself. How it works and bench numbers:
|
||||
[docs/ota.md](docs/ota.md).
|
||||
* **Experimental even within this fork**: the images come with every
|
||||
release (see the warning above) and have no second bank and no automatic
|
||||
rollback. A bad firmware that boots keeps running until you push the next
|
||||
one; one that does not boot needs USB/BLE DFU in hand. Tried on the bench
|
||||
(XIAO, USB, mesh, side channel) and on two of our masts since 13. 11. 2026.
|
||||
The radio watchdogs (see Diagnostics and operations) catch an image that
|
||||
boots with a dead radio: switch `set radio.silence` on for nodes you push
|
||||
to. Costs ~10 kB of RAM.
|
||||
|
||||
### Build
|
||||
|
||||
* Version stamping in every nRF52 env (`v1.18.0-tth<sha>`, `+` = dirty tree),
|
||||
base version from the upstream tag (`tools/build_version.py`).
|
||||
* `tools/`: host tools for the nodes -- consoles (USB, BLE), flashing, bench
|
||||
tests, diagnostics ([tools/README.md](tools/README.md)). Board names come
|
||||
from a local config outside the repo (`tools/config.example.ini`).
|
||||
* `hardware/cavity-box`: parametric enclosure for a cavity filter on a mast.
|
||||
|
||||
---
|
||||
|
||||
*Níže je README upstreamového MeshCore. Jeho flasher, klienti a návody se
|
||||
týkají oficiálního firmwaru, ne releasů tohoto forku. / Below is upstream
|
||||
MeshCore's README: its flasher, clients and guides refer to the official
|
||||
firmware, not to this fork's releases.*
|
||||
|
||||
## About MeshCore
|
||||
|
||||
MeshCore is a lightweight, portable C++ library that enables multi-hop packet routing for embedded projects using LoRa and other packet radios. It is designed for developers who want to create resilient, decentralized communication networks that work without the internet.
|
||||
@@ -38,6 +685,7 @@ For developers:
|
||||
|
||||
- Install [PlatformIO](https://docs.platformio.org) in [Visual Studio Code](https://code.visualstudio.com).
|
||||
- Clone and open the MeshCore repository in Visual Studio Code.
|
||||
- For the LilyGO T3 STM32, see the [board build and flashing guide](./variants/lilygo_t3_stm32/README.md).
|
||||
- See the example applications you can modify and run:
|
||||
- [Companion Radio](./examples/companion_radio) - For use with an external chat app, over BLE, USB or Wi-Fi.
|
||||
- [KISS Modem](./examples/kiss_modem) - Serial KISS protocol bridge for host applications. ([protocol docs](./docs/kiss_modem_protocol.md))
|
||||
@@ -123,6 +771,6 @@ There are a number of fairly major features in the pipeline, with no particular
|
||||
|
||||
## 📞 Get Support
|
||||
|
||||
- Report bugs and request features on the [GitHub Issues](https://github.com/ripplebiz/MeshCore/issues) page.
|
||||
- Report bugs and request features on the [GitHub Issues](https://github.com/meshcore-dev/meshcore/issues) page.
|
||||
- Find additional guides and components on [my site](https://buymeacoffee.com/ripplebiz).
|
||||
- Join [MeshCore Discord](https://meshcore.gg) to chat with the developers and get help from the community.
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"build": {
|
||||
"arduino": {
|
||||
"ldscript": "esp32s3_out.ld"
|
||||
},
|
||||
"core": "esp32",
|
||||
"extra_flags": [
|
||||
"-D ARDUINO_USB_CDC_ON_BOOT=0",
|
||||
"-D ARDUINO_USB_MSC_ON_BOOT=0",
|
||||
"-D ARDUINO_USB_DFU_ON_BOOT=0",
|
||||
"-D ARDUINO_USB_MODE=0",
|
||||
"-D ARDUINO_RUNNING_CORE=1",
|
||||
"-D ARDUINO_EVENT_RUNNING_CORE=1"
|
||||
],
|
||||
"f_cpu": "240000000L",
|
||||
"f_flash": "80000000L",
|
||||
"flash_mode": "qio",
|
||||
"hwids": [["0x303A", "0x1001"]],
|
||||
"mcu": "esp32s3",
|
||||
"variant": "esp32s3"
|
||||
},
|
||||
"connectivity": ["wifi", "bluetooth", "lora"],
|
||||
"debug": {
|
||||
"default_tool": "esp-builtin",
|
||||
"onboard_tools": ["esp-builtin"],
|
||||
"openocd_target": "esp32s3.cfg"
|
||||
},
|
||||
"frameworks": ["arduino", "espidf"],
|
||||
"name": "DFRobot LoRaWAN ESP32-S3 (4 MB Flash, No PSRAM)",
|
||||
"upload": {
|
||||
"flash_size": "4MB",
|
||||
"maximum_ram_size": 524288,
|
||||
"maximum_size": 4194304,
|
||||
"require_upload_port": true,
|
||||
"speed": 921600
|
||||
},
|
||||
"url": "https://www.dfrobot.com",
|
||||
"vendor": "DFRobot"
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"build": {
|
||||
"arduino": {
|
||||
"ldscript": "nrf52840_s140_v6.ld"
|
||||
},
|
||||
"core": "nRF5",
|
||||
"cpu": "cortex-m4",
|
||||
"extra_flags": "-DNRF52840_XXAA",
|
||||
"f_cpu": "64000000L",
|
||||
"hwids": [
|
||||
["0x239A", "0x8071"],
|
||||
["0x239A", "0x0071"],
|
||||
["0x239A", "0x8072"]
|
||||
],
|
||||
"usb_product": "HT-n5262",
|
||||
"mcu": "nrf52840",
|
||||
"variant": "heltec_rc52",
|
||||
"bsp": {
|
||||
"name": "adafruit"
|
||||
},
|
||||
"softdevice": {
|
||||
"sd_flags": "-DS140",
|
||||
"sd_name": "s140",
|
||||
"sd_version": "6.1.1",
|
||||
"sd_fwid": "0x00B6"
|
||||
},
|
||||
"bootloader": {
|
||||
"settings_addr": "0xFF000"
|
||||
}
|
||||
},
|
||||
"connectivity": [
|
||||
"bluetooth",
|
||||
"lora"
|
||||
],
|
||||
"debug": {
|
||||
"jlink_device": "nRF52840_xxAA",
|
||||
"svd_path": "nrf52840.svd",
|
||||
"openocd_target": "nrf52.cfg"
|
||||
},
|
||||
"frameworks": [
|
||||
"arduino"
|
||||
],
|
||||
"name": "Heltec RC52",
|
||||
"upload": {
|
||||
"maximum_ram_size": 237568,
|
||||
"maximum_size": 815104,
|
||||
"speed": 115200,
|
||||
"protocol": "nrfutil",
|
||||
"protocols": [
|
||||
"jlink",
|
||||
"nrfjprog",
|
||||
"nrfutil",
|
||||
"stlink"
|
||||
],
|
||||
"use_1200bps_touch": true,
|
||||
"require_upload_port": true,
|
||||
"wait_for_upload_port": true
|
||||
},
|
||||
"url": "https://heltec.org/",
|
||||
"vendor": "Heltec"
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"build": {
|
||||
"arduino": {
|
||||
"variant_h": "variant_generic.h"
|
||||
},
|
||||
"core": "stm32",
|
||||
"cpu": "cortex-m4",
|
||||
"extra_flags": "-DSTM32WL -DSTM32WLxx -DSTM32WL55xx",
|
||||
"f_cpu": "48000000L",
|
||||
"framework_extra_flags": {
|
||||
"arduino": "-DUSE_CM4_STARTUP_FILE -DARDUINO_GENERIC_WL55CCUX"
|
||||
},
|
||||
"mcu": "stm32wl55ccu6",
|
||||
"product_line": "STM32WL55xx",
|
||||
"variant": "STM32WLxx/WL54CCU_WL55CCU_WLE4C(8-B-C)U_WLE5C(8-B-C)U"
|
||||
},
|
||||
"debug": {
|
||||
"jlink_device": "STM32WL55CC",
|
||||
"openocd_target": "stm32wlx",
|
||||
"svd_path": "STM32WL5x_CM4.svd"
|
||||
},
|
||||
"frameworks": ["arduino"],
|
||||
"name": "LilyGO T3 STM32 V1.0 (STM32WL55CCU6)",
|
||||
"upload": {
|
||||
"maximum_ram_size": 65536,
|
||||
"maximum_size": 262144,
|
||||
"protocol": "serial",
|
||||
"protocols": ["serial", "stlink", "jlink"]
|
||||
},
|
||||
"url": "https://github.com/Xinyuan-LilyGO/T3-STM32",
|
||||
"vendor": "LilyGO"
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
{
|
||||
"build": {
|
||||
"arduino": {
|
||||
"ldscript": "nrf52840_s140_v6.ld"
|
||||
},
|
||||
"core": "nRF5",
|
||||
"cpu": "cortex-m4",
|
||||
"extra_flags": "-DARDUINO_NRF52840_MUZI_BASE -DNRF52840_XXAA",
|
||||
"f_cpu": "64000000L",
|
||||
"hwids": [
|
||||
[
|
||||
"0x239A",
|
||||
"0x4405"
|
||||
],
|
||||
[
|
||||
"0x239A",
|
||||
"0x0029"
|
||||
],
|
||||
[
|
||||
"0x239A",
|
||||
"0x002A"
|
||||
]
|
||||
],
|
||||
"usb_product": "muzi_base",
|
||||
"mcu": "nrf52840",
|
||||
"variant": "MUZI_BASE",
|
||||
"bsp": {
|
||||
"name": "adafruit"
|
||||
},
|
||||
"softdevice": {
|
||||
"sd_flags": "-DS140",
|
||||
"sd_name": "s140",
|
||||
"sd_version": "6.1.1",
|
||||
"sd_fwid": "0x00B6"
|
||||
},
|
||||
"bootloader": {
|
||||
"settings_addr": "0xFF000"
|
||||
}
|
||||
},
|
||||
"connectivity": [
|
||||
"bluetooth"
|
||||
],
|
||||
"debug": {
|
||||
"jlink_device": "nRF52840_xxAA",
|
||||
"onboard_tools": [
|
||||
"jlink"
|
||||
],
|
||||
"svd_path": "nrf52840.svd",
|
||||
"openocd_target": "nrf52.cfg"
|
||||
},
|
||||
"frameworks": [
|
||||
"arduino"
|
||||
],
|
||||
"name": "Muzi Base",
|
||||
"upload": {
|
||||
"maximum_ram_size": 248832,
|
||||
"maximum_size": 815104,
|
||||
"speed": 115200,
|
||||
"use_1200bps_touch": true,
|
||||
"require_upload_port": true,
|
||||
"wait_for_upload_port": true,
|
||||
"protocol": "nrfutil",
|
||||
"protocols": [
|
||||
"jlink",
|
||||
"nrfjprog",
|
||||
"nrfutil",
|
||||
"stlink"
|
||||
]
|
||||
},
|
||||
"url": "https://github.com/muzi-works",
|
||||
"vendor": "MuziWorks"
|
||||
}
|
||||
@@ -14,7 +14,34 @@ MEMORY
|
||||
* - Concurrent connection peripheral + central + secure links
|
||||
* - Event Len, HVN queue, Write CMD queue
|
||||
*/
|
||||
RAM (rwx) : ORIGIN = 0x20006000, LENGTH = 0x20040000 - 0x20006000
|
||||
/* CUSTOM (TeTeHacko): reserve 16 B at the end of RAM for a hardfault record
|
||||
* (PC/LR survive soft reset, printed on next boot) — see HardFault_Handler
|
||||
* in the framework and the boot-time printout in main.cpp.
|
||||
*
|
||||
* MEASURED 7. 8. 2026, AND IT UNDERMINES THE PREMISE: keeping an address out of
|
||||
* the linker's region is NOT enough to survive a soft reset on this hardware.
|
||||
* A clock record was tried at 0x2003FFE0 (32 B reserved) and came back as
|
||||
* `00000000 10001000 00000000` after a `reboot` — not zeroed, OVERWRITTEN, and
|
||||
* 0x10001000 is the nRF52 UICR base, i.e. a UICR pointer left on somebody's
|
||||
* stack. The Adafruit bootloader runs before the app on every reset and links
|
||||
* against the full RAM, so its stack starts at 0x20040000 and grows down
|
||||
* through this area; it reached at least 24 B down.
|
||||
*
|
||||
* The hardfault record at 0x2003FFF0 is HIGHER, i.e. the first thing that stack
|
||||
* touches, so it is unlikely to be any safer. Nothing here has ever
|
||||
* demonstrated it surviving. Do not build anything new on this mechanism
|
||||
* without proving retention first, and treat a missing hardfault report as
|
||||
* "unknown" rather than "no fault happened".
|
||||
*
|
||||
* 18. 10. 2026: what DOES survive is the middle of RAM. The clock record now
|
||||
* lives in .noinit (src/helpers/NRF52Board.cpp), which the linker places right
|
||||
* after .bss -- measured on x1 (XIAO, companion): set +30 days, soft `reboot`,
|
||||
* the clock came back +30 days. The hardfault record moved there too
|
||||
* (g_hardfault_record, handler in NRF52Board.cpp) and was proven on x2: a
|
||||
* deliberate fault printed its PC on the next boot. These 16 B are no longer
|
||||
* used by anything; kept only so the RAM layout of existing envs is unchanged.
|
||||
*/
|
||||
RAM (rwx) : ORIGIN = 0x20006000, LENGTH = 0x2003FFF0 - 0x20006000
|
||||
}
|
||||
|
||||
SECTIONS
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
{
|
||||
"build": {
|
||||
"arduino": {
|
||||
"ldscript": "nrf52840_s140_v6.ld"
|
||||
},
|
||||
"core": "nRF5",
|
||||
"cpu": "cortex-m4",
|
||||
"extra_flags": "-DNRF52840_XXAA",
|
||||
"f_cpu": "64000000L",
|
||||
"hwids": [
|
||||
[
|
||||
"0x239A",
|
||||
"0x4405"
|
||||
],
|
||||
[
|
||||
"0x239A",
|
||||
"0x0029"
|
||||
],
|
||||
[
|
||||
"0x239A",
|
||||
"0x002A"
|
||||
]
|
||||
],
|
||||
"usb_product": "elecrow_thinknode_m4",
|
||||
"mcu": "nrf52840",
|
||||
"variant": "ELECROW-ThinkNode-M4",
|
||||
"bsp": {
|
||||
"name": "adafruit"
|
||||
},
|
||||
"softdevice": {
|
||||
"sd_flags": "-DS140",
|
||||
"sd_name": "s140",
|
||||
"sd_version": "6.1.1",
|
||||
"sd_fwid": "0x00B6"
|
||||
},
|
||||
"bootloader": {
|
||||
"settings_addr": "0xFF000"
|
||||
}
|
||||
},
|
||||
"connectivity": [
|
||||
"bluetooth"
|
||||
],
|
||||
"debug": {
|
||||
"jlink_device": "nRF52840_xxAA",
|
||||
"onboard_tools": [
|
||||
"jlink"
|
||||
],
|
||||
"svd_path": "nrf52840.svd",
|
||||
"openocd_target": "nrf52.cfg"
|
||||
},
|
||||
"frameworks": [
|
||||
"arduino"
|
||||
],
|
||||
"name": "elecrow nrf",
|
||||
"upload": {
|
||||
"maximum_ram_size": 235520,
|
||||
"maximum_size": 815104,
|
||||
"speed": 115200,
|
||||
"use_1200bps_touch": true,
|
||||
"require_upload_port": true,
|
||||
"wait_for_upload_port": true,
|
||||
"protocol": "nrfutil",
|
||||
"protocols": [
|
||||
"jlink",
|
||||
"nrfjprog",
|
||||
"nrfutil",
|
||||
"stlink"
|
||||
]
|
||||
},
|
||||
"url": "https://github.com/Elecrow-RD",
|
||||
"vendor": "ELECROW"
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"build": {
|
||||
"arduino": {
|
||||
"ldscript": "nrf52840_s140_v6.ld"
|
||||
},
|
||||
"core": "nRF5",
|
||||
"cpu": "cortex-m4",
|
||||
"extra_flags": "-DARDUINO_NRF52840_ThinkNode_M8 -DNRF52840_XXAA",
|
||||
"f_cpu": "64000000L",
|
||||
"hwids": [
|
||||
["0x239A", "0x4405"],
|
||||
["0x239A", "0x0029"],
|
||||
["0x239A", "0x002A"]
|
||||
],
|
||||
"usb_product": "elecrow_thinknode_m8",
|
||||
"mcu": "nrf52840",
|
||||
"variant": "ELECROW-ThinkNode-M8",
|
||||
"variants_dir": "variants",
|
||||
"bsp": {
|
||||
"name": "adafruit"
|
||||
},
|
||||
"softdevice": {
|
||||
"sd_flags": "-DS140",
|
||||
"sd_name": "s140",
|
||||
"sd_version": "6.1.1",
|
||||
"sd_fwid": "0x00B6"
|
||||
},
|
||||
"bootloader": {
|
||||
"settings_addr": "0xFF000"
|
||||
}
|
||||
},
|
||||
"connectivity": ["bluetooth"],
|
||||
"debug": {
|
||||
"jlink_device": "nRF52840_xxAA",
|
||||
"onboard_tools": ["jlink"],
|
||||
"svd_path": "nrf52840.svd",
|
||||
"openocd_target": "nrf52840-mdk-rs"
|
||||
},
|
||||
"frameworks": ["arduino"],
|
||||
"name": "elecrow thinknode m8",
|
||||
"upload": {
|
||||
"maximum_ram_size": 248832,
|
||||
"maximum_size": 815104,
|
||||
"speed": 115200,
|
||||
"protocol": "nrfutil",
|
||||
"protocols": ["jlink", "nrfjprog", "nrfutil", "stlink"],
|
||||
"use_1200bps_touch": true,
|
||||
"require_upload_port": true,
|
||||
"wait_for_upload_port": true
|
||||
},
|
||||
"url": "",
|
||||
"vendor": "ELECROW"
|
||||
}
|
||||
@@ -20,10 +20,12 @@ for item in menv.get("CPPDEFINES", []):
|
||||
src_filter.append("+<helpers/stm32/*>")
|
||||
elif item == "ESP32":
|
||||
src_filter.append("+<helpers/esp32/*>")
|
||||
src_filter.append("+<helpers/wifi/*>")
|
||||
elif item == "NRF52_PLATFORM":
|
||||
src_filter.append("+<helpers/nrf52/*>")
|
||||
elif item == "RP2040_PLATFORM":
|
||||
src_filter.append("+<helpers/rp2040/*>")
|
||||
src_filter.append("+<helpers/wifi/*>")
|
||||
|
||||
# DISPLAY HANDLING
|
||||
elif isinstance(item, tuple) and item[0] == "DISPLAY_CLASS":
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
# BLE/LoRa coexistence — bench reproduction attempt
|
||||
|
||||
Working notes for the DIRECT-forward loss seen on `mast-three` (SenseCap Solar,
|
||||
`SenseCap_Solar_repeater_ble`). Written down because the result is mostly
|
||||
**negative**, and a negative result is only worth anything if the method and its
|
||||
limits are recorded with it.
|
||||
|
||||
## The claim under test
|
||||
|
||||
Commit `f6e9aeca` widened the BLE connection interval from 15–30 ms to 60–80 ms
|
||||
after an A/B on the mast showed ~40 % of DIRECT-route forwards silently lost
|
||||
with an **idle** BLE connection at 15–30 ms. The stated mechanism is that the
|
||||
SoftDevice's per-connection-event preemption disturbs the SX126x TX path
|
||||
(`startTransmit` fail / send-complete timeout).
|
||||
|
||||
The fix is deployed. What was never established is whether a bench rig can
|
||||
**detect** the effect at all — a measurement that reads zero in both the
|
||||
treatment and the control has shown nothing.
|
||||
|
||||
## Rig
|
||||
|
||||
Isolated test mesh on **866.5 MHz** (BW 62.5, SF 8, CR 5). Isolation is by
|
||||
frequency, not by tx power: a hilltop repeater with `RX_BOOSTED_GAIN` hears a
|
||||
few mW just fine. The override is compile-time (`platformio.local.ini`) because
|
||||
`MyMesh.cpp` seeds `_prefs.freq` from `LORA_FREQ`, so the firmware cannot come
|
||||
up on the production frequency even after `erase`.
|
||||
|
||||
| node | board | role |
|
||||
|---|---|---|
|
||||
| `bench-board` | XIAO nRF52840 + Wio-SX1262 | forwarder under test |
|
||||
| `bench-board` | same | paired control / radiating witness |
|
||||
| `bench-board`, `bench-board` | same | probe sources |
|
||||
| `bench-rpt` | SenseCap Solar Node | forwarder, mast-identical hardware |
|
||||
| `tth-s2-rpt` | same | paired control |
|
||||
|
||||
Paired controls differ **only** in `ADVERT_NAME`, verified by diffing strings in
|
||||
the ELF. Any other difference invalidates them.
|
||||
|
||||
### Oracle
|
||||
|
||||
The measured quantity is the node's own `direct_rx − direct_tx` from
|
||||
`stats-packets`: how many DIRECT packets it accepted for forwarding versus how
|
||||
many it actually sent. This is self-normalising — it does not depend on channel
|
||||
conditions or on a receiver hearing anything. `tx_start_fail` and `tx_timeout`
|
||||
are the mechanism-level counters. A second repeater with `repeat off` acts as a
|
||||
radiating witness, so "counted a TX" can be distinguished from "actually
|
||||
radiated".
|
||||
|
||||
Route forcing: a contact is injected into the sender's companion with an
|
||||
explicit `out_path`, so the DM must traverse the node under test.
|
||||
**`out_path_len` is not a hop count** — it is a packed byte, top two bits =
|
||||
hash size − 1, low six = hop count (`Packet.h:85`). One hop with a 2-byte hash
|
||||
is `0x41`, not `1`. The receiver reads the size out of the packet
|
||||
(`Mesh.cpp:93`), so a forced path works regardless of the node's
|
||||
`path.hash.mode`.
|
||||
|
||||
## What was measured
|
||||
|
||||
All cells at a **verified** 22.50 ms connection interval — `bleconn` reports the
|
||||
parameters actually negotiated, because `bleOnSecured()` only requests them and
|
||||
the central may refuse. Without that read-back none of the null results below
|
||||
would mean anything.
|
||||
|
||||
| `blepwr` | ≈RSSI at central | link up | direct_rx | direct_tx | lost | tx_timeout |
|
||||
|---:|---:|---:|---:|---:|---:|---:|
|
||||
| BLE off | — | — | 8 | 8 | 0 | 0 |
|
||||
| 0 dBm | −67 | 100 % | 8 | 8 | 0 | 0 |
|
||||
| −8 | −75 | 100 % | 8 | 8 | 0 | 0 |
|
||||
| −12 | −79 | 100 % | 8 | 8 | 0 | 0 |
|
||||
| −16 | −83 | 87 % | 8 | 8 | 0 | 0 |
|
||||
| −20 | −87 | 27 % | 8 | 8 | 0 | 0 |
|
||||
|
||||
The −20 dBm row is a bonus condition: the link held only a quarter of the
|
||||
window, so the node spent the rest advertising and re-connecting — close to the
|
||||
reconnect churn the mast reports as HCI 0x3E.
|
||||
|
||||
**Ruled out as the missing factor: BLE link margin.** The whole −75..−90 window
|
||||
the mast sits in is covered, at the known-bad interval, with zero loss.
|
||||
|
||||
### Why idle + weak link does nothing
|
||||
|
||||
In idle the connection events carry empty PDUs, whose retransmission costs
|
||||
almost no radio time. The cost of a retransmission scales with payload size, and
|
||||
the mast has a bridge actively draining the console. Hence the `poll` mode in
|
||||
the harness.
|
||||
|
||||
Direction matters too, and it is the reason to weaken **our** side rather than
|
||||
the central's: a connection event ends as soon as either side misses a packet,
|
||||
so if the central misses our PDU we must re-send it at the next anchor — an
|
||||
extra slave TX. If we miss the central's PDU we never transmit in that event at
|
||||
all, and the SoftDevice uses *less* radio.
|
||||
|
||||
## On mast hardware, with the file log on
|
||||
|
||||
Two SenseCap Solar nodes (`bench-rpt` forwarder, `tth-s2-rpt` paired control) —
|
||||
the same board as the mast, so InternalFS logging, INA226/solar telemetry and
|
||||
the SenseCap SPI layout are all in play. Again at a verified 22.50 ms interval
|
||||
(`bleconn`).
|
||||
|
||||
| file log | BLE | direct_rx | direct_tx | lost | tx_timeout | witness |
|
||||
|---|---|---:|---:|---:|---:|---:|
|
||||
| off | off | 8 | 8 | 0 | 0 | +39 |
|
||||
| off | idle, 88 % of window | 8 | 8 | 0 | 0 | +37 |
|
||||
| **on** | off | 8 | 8 | 0 | 0 | +39 |
|
||||
| **on** | idle, 90 % of window | 8 | 8 | 0 | 0 | +40 |
|
||||
|
||||
The logging condition was real, not nominal: `log` afterwards held 69 entries
|
||||
with RX/TX lines timestamped inside the measurement window, i.e. an InternalFS
|
||||
write per packet — the mechanism behind the known deaf windows.
|
||||
|
||||
**Ten cells, 80 forced forwards, zero lost, `tx_timeout` and `tx_start_fail` at
|
||||
zero throughout.** Against the mast's reported ~40 % loss rate this is not a
|
||||
weak null: a single 8-probe cell would miss a true 40 % effect with probability
|
||||
0.6⁸ ≈ 1.7 %, and ten cells make it vanishing. Whatever the mast is doing, it is
|
||||
not reproduced by the connection interval, the BLE link margin, the board, or
|
||||
InternalFS logging — alone or together.
|
||||
|
||||
## Still open
|
||||
|
||||
**Loaded LoRa channel** is the one uncontrolled difference left. Ours is idle;
|
||||
the mast relays flood traffic, so its forwards contend for a busy channel and
|
||||
the TX window lands on a BLE connection event far more often. This cannot be
|
||||
tested legally here: 866.5 is capped at 1 % duty and the 10 % sub-band
|
||||
(869.4–869.65) is where production lives.
|
||||
|
||||
Practical consequence: **f6e9aeca can be neither confirmed nor refuted on the
|
||||
bench.** Deciding whether the 60–80 ms interval is still needed requires
|
||||
measuring on `mast-three` itself — the counters (`stats-packets`, and now
|
||||
`bleconn` to prove which interval is actually in force) are all reachable over
|
||||
its BLE console.
|
||||
|
||||
## Airtime is a hard limit, and the firmware will not enforce it
|
||||
|
||||
866.5 MHz sits in 865–868 (CZ VO-R/10): 25 mW ERP, **1 % duty cycle = 36 s of
|
||||
transmission per hour**. The firmware does not police this — `airtime_factor`
|
||||
defaults to 0 (= 100 %) and is clamped to 9, so the lowest duty MeshCore can
|
||||
enforce is 10 %. The first sweep consumed `tx_air_secs` 27 s in 18 minutes of
|
||||
uptime, a rate of ~2.5 %. Budget the probes: `stats-radio.tx_air_secs` is the
|
||||
ground truth, and the harness aborts before crossing a configured cap.
|
||||
|
||||
`stats-core.queue_len` and `errors` are a required control, not decoration: when
|
||||
the airtime budget runs out the Dispatcher **defers** a forward
|
||||
(`next_tx_time`, `Dispatcher.cpp:101`), which looks identical to loss in the
|
||||
counters. Both were zero throughout.
|
||||
|
||||
## Traps worth remembering
|
||||
|
||||
- **USB and BLE consoles share one `command[160]`.** Two concurrent consoles
|
||||
interleave into one line and crash the node. The harness keeps a strict
|
||||
sequence: counters over USB → close USB → BLE client → probes → stop BLE →
|
||||
counters over USB.
|
||||
- **`Bluefruit.setTxPower()` is advertising-only** (see the commit message for
|
||||
`blepwr`); the connection runs at the SoftDevice default 0 dBm.
|
||||
- **Weakening the link can lock you out of BLE.** Below about −16 dBm the
|
||||
node's replies stop arriving and the value is re-applied on every reconnect
|
||||
(and, since 6. 10. 2026, saved). The way back is `blepwr` over the mesh admin
|
||||
CLI.
|
||||
- **~~Runtime `set tx` does not change radiated LoRa power~~ — retracted.** The
|
||||
original reading (+2 dBm → RSSI −44.1, −9 dBm → −44.0) was made with an
|
||||
instrument that could not report failure: `RadioLibWrapper::setTxPower()`
|
||||
discarded RadioLib's status, so a refused request looked exactly like an
|
||||
accepted one. Re-measured 2026-08-04 on the repeater build with `txpwr`
|
||||
confirming each step, x1 transmitting and x4 as witness:
|
||||
|
||||
| `txpwr` | witness `last_rssi` |
|
||||
|---:|---:|
|
||||
| +22 | 0 dBm *(saturated)* |
|
||||
| +14 | −1 dBm *(saturated)* |
|
||||
| +6 | −7 dBm |
|
||||
| 0 | −18 dBm |
|
||||
| −9 | −28 dBm |
|
||||
|
||||
31 dB of command produced 28 dB of RSSI, and the witness `recv` counter rose
|
||||
by one at every step, so no point was missed. Radiated power does follow the
|
||||
setting. The top two points are saturated — the boards were ~10 cm apart — so
|
||||
the usable range of that particular rig starts around +6 dBm; characterising
|
||||
the top end needs attenuation or distance, not a bigger number.
|
||||
|
||||
The lesson is not about tx power. It is that a null result from an instrument
|
||||
which cannot distinguish "refused" from "no effect" is not a result at all.
|
||||
|
||||
## The two commands this bench added
|
||||
|
||||
Both live in `examples/simple_repeater/main.cpp` and are repeater-only.
|
||||
|
||||
### `bleconn` — what the link is actually doing
|
||||
|
||||
```
|
||||
bleconn
|
||||
-> BLE conn: interval 75.00 ms (req 60-80), latency 0, sup timeout 4000 ms [live]
|
||||
```
|
||||
|
||||
Reports the **negotiated** connection parameters, not the requested ones. The
|
||||
central is free to ignore a peripheral's request, so this is the only way to
|
||||
know whether a change like `f6e9aeca` (widening the requested interval to
|
||||
60–80 ms) is in force on a node you cannot see. The trailing `[live]` /
|
||||
`[last]` says whether a client is connected right now or these are the values
|
||||
from the last one; before any client has ever connected it answers
|
||||
`nothing seen yet`.
|
||||
|
||||
### `blepwr [dBm]` — connection TX power, saved
|
||||
|
||||
```
|
||||
blepwr # report: BLE conn tx: 0 dBm, adv tx: 8 dBm
|
||||
blepwr 8 # set, apply to live connections and save
|
||||
blepwr default # forget the saved value, back to RPT_BLE_CONN_TX_POWER
|
||||
```
|
||||
|
||||
The reply carries how many live connections accepted the value
|
||||
(`OK - BLE conn tx 8 dBm (1/1 conn), saved`) because the nRF52840 only takes
|
||||
−40, −20, −16, −12, −8, −4, 0 and 2..8 dBm; anything else is rejected and is
|
||||
*not* latched or saved, so a typo cannot arm itself for the next reconnect.
|
||||
The value lives in `/ble_pwr` in InternalFS, so it survives a reboot and also a
|
||||
reflash with a different build default: an explicit value is pinned even when
|
||||
it equals the default (no file = follow `RPT_BLE_CONN_TX_POWER`, which
|
||||
mast-three's env sets to 8).
|
||||
|
||||
Sets `BLE_GAP_TX_POWER_ROLE_CONN`, which is **independent of**
|
||||
`Bluefruit.setTxPower()` — that one only affects advertising, despite reading
|
||||
like a global. The connection otherwise runs at the SoftDevice default of
|
||||
0 dBm; the compile-time starting value is `RPT_BLE_CONN_TX_POWER`.
|
||||
|
||||
The value is re-applied on every 'secured' event and saved, so a setting weak
|
||||
enough to break the link persists across reconnects and reboots — at −40 dBm
|
||||
during this bench it locked the BLE console out. Fix it over the mesh admin
|
||||
CLI (`blepwr 0`), which does not depend on BLE. Until 6. 10. 2026 a weakening
|
||||
auto-reverted after 5 minutes and nothing was saved; that went away once the
|
||||
value started to be saved, because a revert that the next reboot undoes again
|
||||
only made the state harder to read.
|
||||
@@ -0,0 +1,64 @@
|
||||
# Budka link — a Chytra Budka as a sensor source
|
||||
|
||||
A Chytra Budka (ESP32-S3 bird box) sends its readings over a one-way UART line
|
||||
to a XIAO nRF52840 running `simple_sensor`; the sensor serves them as
|
||||
CayenneLPP telemetry to anyone on the mesh. The line format and the budka side
|
||||
are documented in the chytra-budka repo, `firmware/MESHCORE.md`.
|
||||
|
||||
## Build
|
||||
|
||||
`BudkaLinkSensorManager` (`src/helpers/sensors/`) replaces the variant's
|
||||
`EnvironmentSensorManager` when the env defines `BUDKA_LINK_RX_PIN`; every
|
||||
other env is unchanged.
|
||||
|
||||
```ini
|
||||
[env:Xiao_x1_budka] ; platformio.local.ini
|
||||
extends = env:Xiao_nrf52_sensor
|
||||
build_flags =
|
||||
${env:Xiao_nrf52_sensor.build_flags}
|
||||
${test_radio.build_flags} ; bench: test band only
|
||||
-D BUDKA_LINK_RX_PIN=0 ; D0 = the only pad LoRa + I²C leave free
|
||||
```
|
||||
|
||||
Optional: `BUDKA_LINK_TX_PIN` (default `LED_GREEN` — nothing is ever sent, the
|
||||
idle-high line keeps that LED dark), `BUDKA_LINK_BAUD` (115200),
|
||||
`BUDKA_LINK_METERS` (3), `BUDKA_LINK_STALE_MS` (120 s).
|
||||
|
||||
## Wiring
|
||||
|
||||
Budka `mc_tx` pad → XIAO **D0**, GND ↔ GND, each board on its own USB. A
|
||||
1 kΩ series resistor protects against back-powering when one side is off.
|
||||
|
||||
## Telemetry layout
|
||||
|
||||
| channel | content |
|
||||
|---|---|
|
||||
| 1 | the node itself |
|
||||
| next | budka: temperature, humidity, pressure, motion count (generic sensor) |
|
||||
| next + k | UC96 meter *k*: voltage, current, power (analog input), energy (kWh) |
|
||||
|
||||
A line with a bad checksum is dropped whole; a value not refreshed for 2 min is
|
||||
left out. Meter channels stay reserved while a meter is missing.
|
||||
|
||||
Read it with `.tth/tools/budka_telem.py <companion-port> <sensor-name>`. The sensor
|
||||
answers only clients in its ACL — a request from anyone else is dropped
|
||||
(`recv matches no peers` in a `MESH_DEBUG` build). Add the companion from the
|
||||
sensor's USB console with `setperm <companion-pubkey> 1`, or log in as admin.
|
||||
The port may be a pyserial URL (`socket://…` for an openHop companion), and the
|
||||
name may be the sensor's public key when the companion does not have it yet.
|
||||
|
||||
## Bench result (13. 10. 2026)
|
||||
|
||||
x1 (sensor, test band) fed by the bench budka; x4 as USB companion:
|
||||
|
||||
```
|
||||
ch2 temp_C 25.3 humidity_% 59.0 generic 29
|
||||
ch3 voltage_V 4.94 current_A 0.10 analog_in 0.49 energy_kWh 0.111
|
||||
ch4 voltage_V 4.94 current_A 0.18 analog_in 0.89 energy_kWh 0.311
|
||||
```
|
||||
|
||||
## Not done
|
||||
|
||||
Alerts (reed opened, budka WiFi down) and the return direction (mesh → budka).
|
||||
The sensor build has no `dfu` console command — reflash with
|
||||
`pio run -t upload`, one touch per power session.
|
||||
+320
-12
@@ -48,18 +48,36 @@ This document provides an overview of CLI commands that can be sent to MeshCore
|
||||
|
||||
**Note:** No reply is sent.
|
||||
|
||||
Resets the clock to the firmware's build epoch (or, on an unstamped build, the
|
||||
upstream 15 May 2024 literal) and reboots. This is the **only** way to move a
|
||||
clock backwards: `time` and `clock sync` both refuse to.
|
||||
|
||||
---
|
||||
|
||||
### Sync the clock with the remote device
|
||||
**Usage:**
|
||||
- `clock sync`
|
||||
|
||||
Takes the time from the *packet's* `sender_timestamp`, so it works **only over
|
||||
the remote admin CLI**, never from the USB or BLE console — those pass
|
||||
`sender_timestamp = 0` (they share one command buffer, see
|
||||
`examples/simple_repeater/main.cpp`), and `0 > curr` is never true, so a local
|
||||
`clock sync` always answers `ERR: clock cannot go backwards`. Use `time <epoch>`
|
||||
locally.
|
||||
|
||||
---
|
||||
|
||||
### Display current time in UTC
|
||||
**Usage:**
|
||||
- `clock`
|
||||
|
||||
**Reply:** `HH:MM - D/M/YYYY UTC (epoch <seconds>)`
|
||||
|
||||
The epoch is a TeTeHacko addition. The human part is minutes only, so a host
|
||||
comparing clocks cannot see a difference smaller than a minute and has to leave
|
||||
a deadband of over 59 s; the epoch makes the comparison exact. It is appended,
|
||||
so anything that only prints the reply is unaffected.
|
||||
|
||||
---
|
||||
|
||||
### Set the time to a specific timestamp
|
||||
@@ -69,6 +87,23 @@ This document provides an overview of CLI commands that can be sent to MeshCore
|
||||
**Parameters:**
|
||||
- `epoch_seconds`: Unix epoch time
|
||||
|
||||
Refuses to go backwards (`secs > curr`), answering
|
||||
`(ERR: clock cannot go backwards)`. That reply usually means the clock was
|
||||
already right, so treat it as success and judge by reading `clock` back.
|
||||
|
||||
**Where the clock comes from if nobody sets it.** Without GPS and without an
|
||||
I2C RTC the clock is volatile: it starts at the build epoch and only ticks from
|
||||
`millis()`. It is worth setting, because the RTC stamps every advert the node
|
||||
transmits and a receiver drops a stale timestamp as a replay. Automatic sources,
|
||||
in order of preference:
|
||||
|
||||
- **GPS** (`gps duty` is enough — see `docs/power.md`);
|
||||
- **an attached host** — `tools/ble_cli.py <MAC> "time {epoch}"`, the
|
||||
`meshcore-ble-bridge`/`meshcore-serial-bridge` scrape, or
|
||||
`tools/xiao_uf2_flash.sh`, which sets it right after every flash;
|
||||
- **the build epoch**, which is where a freshly flashed board starts, and
|
||||
which needs nothing at all.
|
||||
|
||||
---
|
||||
|
||||
### Send a flood advert
|
||||
@@ -142,6 +177,18 @@ This document provides an overview of CLI commands that can be sent to MeshCore
|
||||
|
||||
**Serial Only:** Yes
|
||||
|
||||
**Note:** Output format: `{"battery_mv":<mV>,"uptime_secs":<secs>,"errors":<flags>,"queue_len":<count>}`
|
||||
|
||||
**Note:** `errors` is a bitmask shown as "Debug flags" in the app's repeater status.
|
||||
|
||||
| Value | Flag | Meaning |
|
||||
|-------|------|---------|
|
||||
| 1 | `ERR_EVENT_FULL` | A packet failed to send because the memory pool was full. |
|
||||
| 2 | `ERR_EVENT_CAD_TIMEOUT` | After waiting 4 seconds for a gap, a packet was transmitted into a busy network. |
|
||||
| 4 | `ERR_EVENT_STARTRX_TIMEOUT` | The radio was out of receive mode for more than 8 seconds. |
|
||||
|
||||
Flags stay set until the node reboots or `clear stats` is run.
|
||||
|
||||
---
|
||||
|
||||
### Radio Stats - Noise floor, Last RSSI/SNR, Airtime, Receive errors
|
||||
@@ -211,7 +258,7 @@ This document provides an overview of CLI commands that can be sent to MeshCore
|
||||
|
||||
**Set by build flag:** `LORA_FREQ`, `LORA_BW`, `LORA_SF`, `LORA_CR`
|
||||
|
||||
**Default:** `869.525,250,11,5`
|
||||
**Default:** `869.618,62.5,8,5`
|
||||
|
||||
**Note:** Requires reboot to apply
|
||||
|
||||
@@ -256,7 +303,7 @@ This document provides an overview of CLI commands that can be sent to MeshCore
|
||||
**Parameters:**
|
||||
- `frequency`: Frequency in MHz
|
||||
|
||||
**Default:** `869.525`
|
||||
**Default:** `869.618`
|
||||
|
||||
**Note:** Requires reboot to apply
|
||||
**Serial Only:** `set freq <frequency>`
|
||||
@@ -325,6 +372,55 @@ This document provides an overview of CLI commands that can be sent to MeshCore
|
||||
|
||||
---
|
||||
|
||||
#### Show battery state as an icon on the advertised name
|
||||
|
||||
*(TeTeHacko fork)* Appends a solar marker and a charge level to the name
|
||||
carried in adverts, so anyone who hears the node can see its state without
|
||||
logging in for telemetry. Off by default.
|
||||
|
||||
**Usage:**
|
||||
- `get batt.icon`
|
||||
- `set batt.icon on|off`
|
||||
|
||||
**Default:** `off`
|
||||
|
||||
**Glyphs:** `☀` permanently (solar node), then one of `▁▂▃▄▅▆▇█`
|
||||
for the charge level -- or `⚡` instead of the level while the node runs on
|
||||
external power (USB), where VBAT reads the charger rather than the cell.
|
||||
|
||||
**Note:** The indicator costs 6 bytes of the name (3 + 3), which with a
|
||||
position in the advert leaves 17. Unicode has only two battery emoji and no
|
||||
"half full" one, and at 4 bytes each they do not fit -- hence block elements,
|
||||
which are 3 bytes and come in eight steps. If the name is too long the whole
|
||||
indicator is dropped rather than truncated, and both `set` and `get` say so.
|
||||
|
||||
**Note:** Every level is the same byte width on purpose. A name that changed
|
||||
length with the charge would be re-truncated at some steps and not others, and
|
||||
every client that heard it would rewrite the contact.
|
||||
|
||||
**Note:** Switching is hysteretic (`BATT_ICON_HYST_MV`, default 50 mV) and
|
||||
asymmetric -- the level drops as soon as the voltage crosses a boundary but
|
||||
climbs only once clear of it. The measured daily swing of a solar node under
|
||||
weak sun is 38-46 mV and the drift 13 mV/day, so at eight levels the name
|
||||
changes roughly once a week.
|
||||
|
||||
---
|
||||
|
||||
#### Battery scale for the name icon
|
||||
**Usage:**
|
||||
- `get batt.icon.lo` / `set batt.icon.lo <millivolts>`
|
||||
- `get batt.icon.hi` / `set batt.icon.hi <millivolts>`
|
||||
|
||||
**Set by build flag:** `BATT_ICON_LO_MV`, `BATT_ICON_HI_MV`
|
||||
|
||||
**Default:** `3300` and `4200` -- the same 1S Li-Ion scale the dashboards use,
|
||||
so the icon and the Grafana percentage tell one story.
|
||||
|
||||
**Parameters:**
|
||||
- `millivolts`: `2500`..`4500`, or `0` to use the build default
|
||||
|
||||
---
|
||||
|
||||
#### View or change this node's latitude
|
||||
**Usage:**
|
||||
- `get lat`
|
||||
@@ -461,6 +557,45 @@ This document provides an overview of CLI commands that can be sent to MeshCore
|
||||
|
||||
---
|
||||
|
||||
#### View or change the RX duty cycle (rxps) -- CUSTOM (TeTeHacko)
|
||||
**Usage:**
|
||||
- `get radio.rxps`
|
||||
- `set radio.rxps off|on|balanced|max`
|
||||
- `set radio.rxps level <1-10> [preamble <16|32>]`
|
||||
- `set radio.rxps max preamble <16|32>`
|
||||
|
||||
The SX1262 sleeps between short listening windows (`SetRxDutyCycle`) instead
|
||||
of listening all the time, and stays awake through a packet once it hears a
|
||||
preamble. Ported from EasySkyMesh PowerSaving v18 (IoTThinks). Repeater, room
|
||||
server and sensor; SX1262 only (an LR11x0 reports `supported=no`). Present
|
||||
only in builds with `-D WITH_RX_POWERSAVING` (the public releases have it) and
|
||||
off until you set it; the setting is saved.
|
||||
|
||||
**Parameters:**
|
||||
- `on` (= `conservative`, level 3), `balanced` (level 6), `max` (level 8): the
|
||||
higher the level, the longer the sleep. The named presets assume senders
|
||||
with a 16-symbol preamble (the MeshCore default), so they are safe on a
|
||||
mixed mesh.
|
||||
- `level <n>`: the same scale by number; without `preamble` it follows the SF.
|
||||
9 (`overdrive`) and 10 (`riskyWorkingMax`) are past the datasheet's timing
|
||||
condition -- 10 is known to lose packets.
|
||||
- `<rx_us> <sleep_us>`: raw window lengths.
|
||||
|
||||
`get radio.rxps` shows the requested and the effective state
|
||||
(`desired=on,effective=armed`), the window lengths and two error counters. If
|
||||
arming fails three times in a row, the radio falls back to continuous RX by
|
||||
itself (`effective=continuous`, `fail` counts up). The noise-floor calibration
|
||||
also runs in continuous RX.
|
||||
|
||||
**Default:** `off`
|
||||
|
||||
**Note:** Measured 12. 11. 2026 on a XIAO nRF52840 + Wio-SX1262 at 5 V
|
||||
(866.5 MHz / SF8 / BW62.5, A/B/A/B, 15 min cells): `max` saves **~2.3 mA**
|
||||
(cell repeatability 0.3 mA). A 3-board zero-hop test lost nothing on `max`
|
||||
(0/240 over two runs, the second on the public release). See `docs/power.md`.
|
||||
|
||||
---
|
||||
|
||||
### Routing
|
||||
|
||||
#### View or change this node's repeat flag
|
||||
@@ -537,7 +672,7 @@ This document provides an overview of CLI commands that can be sent to MeshCore
|
||||
**Parameters:**
|
||||
- `value`: Direct transmit delay factor (0-2)
|
||||
|
||||
**Default:** `0.2`
|
||||
**Default:** `0.3` (Repeater) - `0.2` (Room Server, Sensor)
|
||||
|
||||
**Note:** Same collision-avoidance random window as `txdelay`, but applied to direct (non-flood, routed) traffic. The default is lower because direct packets are addressed to a specific next hop, so far fewer nodes compete to retransmit them.
|
||||
|
||||
@@ -628,12 +763,59 @@ This document provides an overview of CLI commands that can be sent to MeshCore
|
||||
- `set agc.reset.interval <value>`
|
||||
|
||||
**Parameters:**
|
||||
- `value`: Interval in seconds rounded down to a multiple of 4 (17 becomes 16). 0 to disable.
|
||||
- `value`: Interval in seconds, 0-1020, rounded down to a multiple of 4 (17 becomes 16). 0 to disable.
|
||||
|
||||
**Default:** `0.0`
|
||||
|
||||
---
|
||||
|
||||
#### Radio silence watchdog (repeater, sensor, room server)
|
||||
**Usage:**
|
||||
- `get radio.silence`
|
||||
- `set radio.silence <minutes>`
|
||||
- `get radio.reboots`
|
||||
|
||||
**Parameters:**
|
||||
- `minutes`: 1-1440, or `0`/`off` to disable.
|
||||
|
||||
**Description:** Recovers a receiver that has gone deaf while the node keeps running (the hardware watchdog only catches a frozen loop). After `minutes` without a single received frame — a receive error counts as heard, too — the receiver is re-armed (IRQs cleared, RX restarted). If nothing arrives within a further quarter of the threshold (at least 5 minutes), the node reboots.
|
||||
|
||||
To keep a quiet site out of a reboot loop, each such reboot doubles the threshold for the next boot (up to 16×); the first frame received afterwards resets it. `get radio.silence` shows the threshold, the current multiplier, how long the receiver has been quiet and the stage (0 healthy, 1 re-armed). `get radio.reboots` counts the reboots done by this watchdog; it survives power loss. Pick a threshold well above the longest quiet spell the site normally has.
|
||||
|
||||
**Default:** `0` (off)
|
||||
|
||||
---
|
||||
|
||||
#### TX stall watchdog (repeater)
|
||||
**Usage:**
|
||||
- `get radio.txstall`
|
||||
- `set radio.txstall <minutes>`
|
||||
|
||||
**Parameters:**
|
||||
- `minutes`: 1-1440, or `0`/`off` to disable. Not saved: the build default (`RADIO_TXSTALL_MIN`) is back after a reboot.
|
||||
|
||||
**Description:** Recovers a node that still receives but no longer transmits. If packets wait in the outbound queue and the sent counter does not move for `minutes`, the radio is re-armed (IRQs cleared, back to standby); if still nothing goes out within a further quarter of the threshold (at least 5 minutes), the node reboots. An empty queue never counts, so a quiet site cannot trigger it. `get radio.txstall` shows the threshold, the queue (in total and due now), how long nothing has been sent and the stage (0 healthy, 1 re-armed). Its reboots are counted in `get radio.reboots` and are logged with the queue numbers.
|
||||
|
||||
**Default:** `15`
|
||||
|
||||
---
|
||||
|
||||
#### Reboot into the bootloader (repeater, sensor, room server; nRF52, local console only)
|
||||
**Usage:**
|
||||
- `dfu [uf2|serial|ota]`
|
||||
|
||||
**Description:** Reboots straight into the Adafruit bootloader: `uf2` (default) brings up the UF2 drive, `serial` only the CDC port for `adafruit-nrfutil`, `ota` BLE DFU. Refused over the mesh, where it would leave the node waiting in the bootloader with no way back.
|
||||
|
||||
---
|
||||
|
||||
#### Why the board last reset (repeater, sensor, room server)
|
||||
**Usage:**
|
||||
- `get boot`
|
||||
|
||||
**Description:** The reset reason latched at boot (`RESETREAS` on nRF52: `0x1` reset pin, `0x2` watchdog, `0x4` software reset, `0x8` lockup, `0` power-on) and, if the board crashed, the hardfault record (PC, LR, PSR). The same is printed once at boot, but on a build without a settle delay the console is not open yet at that moment.
|
||||
|
||||
---
|
||||
|
||||
#### Enable or disable Multi-Acks support
|
||||
**Usage:**
|
||||
- `get multi.acks`
|
||||
@@ -654,7 +836,7 @@ This document provides an overview of CLI commands that can be sent to MeshCore
|
||||
**Parameters:**
|
||||
- `hours`: Interval in hours (3-168)
|
||||
|
||||
**Default:** `12` (Repeater) - `0` (Sensor)
|
||||
**Default:** `47` (Repeater, Room Server) - `0`, disabled (Sensor)
|
||||
|
||||
---
|
||||
|
||||
@@ -666,7 +848,12 @@ This document provides an overview of CLI commands that can be sent to MeshCore
|
||||
**Parameters:**
|
||||
- `minutes`: Interval in minutes rounded down to the nearest multiple of 2 (61 becomes 60) (60-240)
|
||||
|
||||
**Default:** `0`
|
||||
**Default:** `2` on a factory-fresh node, then `0` (disabled) once configured.
|
||||
|
||||
**Note:** A new install ships with a 2 minute zero-hop advert interval. Saving
|
||||
any setting resets an interval below the 60 minute minimum to `0`, on the
|
||||
assumption that the node has now been deliberately configured. To keep zero-hop
|
||||
adverts running, set an explicit value in the 60-240 range.
|
||||
|
||||
---
|
||||
|
||||
@@ -994,19 +1181,74 @@ region save
|
||||
---
|
||||
### GPS (When GPS support is compiled in)
|
||||
|
||||
#### View or change GPS state
|
||||
#### View GPS state
|
||||
**Usage:**
|
||||
- `gps`
|
||||
|
||||
**Note:** Reports the requested state, receiver activity, last-fix status (last fix gives number of sats and how long ago was the fix), and mode. In periodic mode, `waiting` means the receiver is off between acquisitions; the last fix remains available. `off(hw)` means a hardware GPS switch is off.
|
||||
|
||||
---
|
||||
|
||||
#### Change GPS state
|
||||
**Usage:**
|
||||
- `gps <state>`
|
||||
|
||||
**Parameters:**
|
||||
- `state`: `on`|`off`
|
||||
- `state`: `on`|`off`|`duty`
|
||||
|
||||
**Default:** `off`
|
||||
|
||||
**Note:** Output format:
|
||||
- `off` when the GPS hardware is disabled
|
||||
- `on, {active|deactivated}, {fix|no fix}, {sat count} sats` when the GPS hardware is enabled
|
||||
**Note:** In duty-cycle mode `gps` answers `duty, {awake|asleep}, {fix|no fix}, {sat count} sats`.
|
||||
|
||||
`gps duty` powers the receiver only around a clock sync and cuts it in between.
|
||||
It is meant for a node that runs GPS purely to keep its (volatile) RTC set — a
|
||||
mast or solar repeater — where a receiver drawing tens of mA continuously
|
||||
dwarfs the rest of the power budget. Unlike `gps period`, every attempt is
|
||||
capped even before the first fix ever, so a node that never sees the sky does
|
||||
not keep the receiver powered. It sets `gps period` to 0. The position still
|
||||
comes from prefs (see `set advert.loc`), so duty mode does not affect what a repeater
|
||||
advertises. `gps on` / `gps off` leave duty mode. Build-time knobs:
|
||||
`GPS_DUTY_SYNC_INTERVAL_SECS` (86400), `GPS_DUTY_MAX_AWAKE_SECS` (300, the cap on
|
||||
one attempt) and `GPS_DUTY_RETRY_SECS` (21600, backoff after a window with no fix).
|
||||
|
||||
---
|
||||
|
||||
#### View or change the GPS acquisition period
|
||||
**Usage:**
|
||||
- `gps period`
|
||||
- `gps period <value>`
|
||||
|
||||
**Parameters:**
|
||||
- `value`: `0` for continuous tracking, or a period. The value can be postfixed with `s`, `m`, `h` or `d` to specify the unit (seconds by default).
|
||||
|
||||
**Note:** A periodic acquisition stops after receiving a valid fix, then resumes after the configured period. Without a fix it stops after 5 minutes (`GPS_PERIODIC_ACQUISITION_TIMEOUT_MS`), or, until the first fix since boot, after the first fix timeout (see `gps firstfix`).
|
||||
|
||||
---
|
||||
|
||||
#### View or change the first fix timeout
|
||||
**Usage:**
|
||||
- `gps firstfix`
|
||||
- `gps firstfix <value>`
|
||||
|
||||
**Parameters:**
|
||||
- `value`: `0` for no limit, or a duration up to `1d`. The value can be postfixed with `s`, `m`, `h` or `d` to specify the unit (seconds by default).
|
||||
|
||||
**Default:** `1h` (`GPS_FIRST_FIX_TIMEOUT_MS`)
|
||||
|
||||
**Note:** In periodic mode, limits an acquisition until the first valid fix since boot. A cold start can take much longer than the usual 5 minutes with a weak sky view; after the limit the GPS sleeps for the period and tries again. Saved with the other GPS settings.
|
||||
|
||||
---
|
||||
|
||||
#### View the last GPS fix
|
||||
**Usage:**
|
||||
- `gps fix`
|
||||
|
||||
**Output:**
|
||||
- `> Fix (n sat): <lat>, <lon>`: the GPS currently has a fix.
|
||||
- `> Last fix <age> ago (n sat)[, acq <time>]: <lat>, <lon>`: position of the last valid fix; `acq` is shown only while the receiver is running and shows how for how long the gps has been trying to get a fix.
|
||||
- `> No fix[, acq <time>]`: no valid fix since the node started.
|
||||
|
||||
**Note:** Ages and durations are given in `s`, `m` or `h`.
|
||||
|
||||
---
|
||||
|
||||
@@ -1016,6 +1258,50 @@ region save
|
||||
|
||||
---
|
||||
|
||||
#### On demand GPS fix
|
||||
**Usage:**
|
||||
- `gps once`
|
||||
- `gps once -s`
|
||||
|
||||
**Parameters:**
|
||||
- `-s`: also sync this node's clock with GPS time (as `gps sync`)
|
||||
|
||||
**Note:** Starts an acquisition now. If the GPS is off, it is switched and kept on until a valid fix and then turned off.
|
||||
|
||||
**Reply:** `OK - turning on and acquiring` (GPS was off), `OK - waking gps` (periodic mode, receiver off between acquisitions) or `OK - gps already on`. `Error, gps hw switch off` if a hardware GPS switch is off, `Error, gps once not supported`.
|
||||
|
||||
---
|
||||
|
||||
#### View GPS time to first fix statistics
|
||||
**Usage:**
|
||||
- `gps fix_stats`
|
||||
|
||||
**Output:** `> ttf:<last>/<max> ok:<n> miss:<n>`: last and maximum time between a start of the GPS and its first valid fix, then the last count of consecutive starts with a fix (`ok`) or without one (`miss`).
|
||||
|
||||
---
|
||||
|
||||
#### View GPS diagnostics
|
||||
**Usage:**
|
||||
- `gps diag`
|
||||
|
||||
---
|
||||
|
||||
#### GPS anti-spoofing guard (When built with `GPS_GUARD`)
|
||||
With `GPS_GUARD`, a fix becomes the node's last fix (position, telemetry, adverts) only after it passes plausibility checks: at least `GPS_GUARD_MIN_SATS` satellites, HDOP ≤ `GPS_GUARD_MAX_HDOP10`/10, inside the optional build-time region (`GPS_GUARD_LAT_MIN/MAX`, `GPS_GUARD_LON_MIN/MAX`), within the fence around the node's configured `lat`/`lon` (if set), no jump faster than `GPS_GUARD_MAX_SPEED_KMH`, and `GPS_GUARD_STABLE_FIXES` consistent fixes in a row. An unverified position is never reported.
|
||||
|
||||
GPS time is written to the clock only while such a fix is current, never earlier than the firmware build date, and, once the clock holds a plausible time (from the build date to 10 years after it), only within `GPS_GUARD_TIME_MAX_STEP` seconds for the first sync and within clock drift (`GPS_GUARD_TIME_DRIFT_BASE` s + `GPS_GUARD_TIME_DRIFT_PPM`) afterwards. Setting the clock manually (`time`, `clock sync`) resets that anchor. A clock outside that window (e.g. a bogus date in 2080) is corrected by the first trusted fix.
|
||||
|
||||
Covers serial NMEA receivers (`MicroNMEALocationProvider`).
|
||||
|
||||
**Usage:**
|
||||
- `gps guard`: status, e.g. `> ok 7sat time ok +1s`, `> rej region time rej nofix`, `> ok 7sat time wait` (last check passed, no current trusted fix to check again, e.g. GPS asleep between periodic fixes), or `... ALERT gps-clk +3600s 75m` when a trusted fix has disagreed with the clock by the same offset for `GPS_GUARD_ALERT_MIN` minutes.
|
||||
- `gps guard on`, `gps guard off`: turn the guard on or off (saved, default on). While off, every fix and GPS time is accepted and `gps guard` shows `off`.
|
||||
- `gps guard accept`: while an alert is active, confirm that the GPS time is right and apply it to the clock.
|
||||
- `gps fence`, `gps fence <metres>`: fence radius around the configured `lat`/`lon` (`0` = off). Default `GPS_GUARD_FENCE_M` (1000); a value set here is saved.
|
||||
- `gps ref`: the reference position; follows `set lat`, `set lon` and `gps setloc`.
|
||||
|
||||
---
|
||||
|
||||
#### Set this node's location based on the GPS coordinates
|
||||
**Usage:**
|
||||
- `gps setloc`
|
||||
@@ -1024,6 +1310,8 @@ region save
|
||||
|
||||
#### View or change the GPS advert policy
|
||||
**Usage:**
|
||||
- `get advert.loc`
|
||||
- `set advert.loc <policy>`
|
||||
- `gps advert`
|
||||
- `gps advert <policy>`
|
||||
|
||||
@@ -1031,10 +1319,12 @@ region save
|
||||
- `policy`: `none`|`share`|`prefs`
|
||||
- `none`: don't include location in adverts
|
||||
- `share`: share gps location (from SensorManager)
|
||||
- `prefs`: location stored in node's lat and lon settings
|
||||
- `prefs`: location stored in node's lat and lon settings (can be different from gps value)
|
||||
|
||||
**Default:** `prefs`
|
||||
|
||||
**Note:** `gps advert` command is the old format but is only accessible when a gps is attached to the unit. It has been kept for compatibility but one should prefer using `get/set` commands instead.
|
||||
|
||||
---
|
||||
|
||||
### Sensors (When sensor support is compiled in)
|
||||
@@ -1060,6 +1350,24 @@ region save
|
||||
|
||||
---
|
||||
|
||||
#### Set the INA current sensor's shunt resistor
|
||||
**Usage:**
|
||||
- `sensor get ina.shunt`
|
||||
- `sensor set ina.shunt <mOhm>`
|
||||
|
||||
**Parameters:**
|
||||
- `mOhm`: the shunt on the module, in milliohms (`10` for a shunt marked `R010`,
|
||||
`100` for `R100`); `0` = the build's value (100 mOhm unless the build sets
|
||||
`TELEM_INA219_SHUNT_VALUE` / `TELEM_INA226_SHUNT_VALUE` / `TELEM_INA3221_SHUNT_VALUE`)
|
||||
|
||||
**Note:** Listed only when an INA219, INA226 or INA3221 was detected at boot.
|
||||
Saved, applies at once and survives a reboot; it also works over the mesh as
|
||||
admin, and on a companion as the custom variable `ina.shunt`. With the wrong value
|
||||
the current is off by the ratio -- LaskaKit's INA226 modules carry 10 mOhm, the
|
||||
default assumes 100. Current is reported in steps of 1 mA (CayenneLPP).
|
||||
|
||||
---
|
||||
|
||||
### Bridge (When bridge support is compiled in)
|
||||
|
||||
#### View the compiled bridge type
|
||||
|
||||
@@ -0,0 +1,591 @@
|
||||
# Companion CLI
|
||||
|
||||
Since version 1.18 meshcore companion radio firmware has a CLI interface, which can be accessed locally (through companion radio protocol) or remotely via the network.
|
||||
|
||||
## Navigation
|
||||
- [Operational](#operational)
|
||||
- [Configuration](#configuration)
|
||||
- [System](#system)
|
||||
- [Radio](#radio)
|
||||
- [GPS](#gps)
|
||||
- [BLE](#ble)
|
||||
- [Wifi](#wifi)
|
||||
- [UI](#ui)
|
||||
|
||||
## Operational
|
||||
|
||||
### Reboot the node
|
||||
**Usage:**
|
||||
- `reboot`
|
||||
|
||||
**Note:** No reply is sent.
|
||||
|
||||
---
|
||||
|
||||
### Power-off the node
|
||||
**Usage:**
|
||||
- `poweroff`, or
|
||||
- `shutdown`
|
||||
|
||||
**Note:** No reply is sent.
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
### System
|
||||
|
||||
#### View or change this node's name
|
||||
**Usage:**
|
||||
- `get name`
|
||||
- `set name <name>`
|
||||
|
||||
**Parameters:**
|
||||
- `name`: Node name
|
||||
|
||||
**Set by build flag:** `ADVERT_NAME`
|
||||
|
||||
**Default:** Varies by board
|
||||
|
||||
**Note:** Advertised names can use up to 23 bytes when location is included and 31 bytes otherwise. Emoji and Unicode characters may take more than one byte. Names that exceed the available advert space are truncated at a valid UTF-8 code point boundary.
|
||||
|
||||
---
|
||||
|
||||
#### View this node's firmware version
|
||||
**Usage:** `ver`
|
||||
|
||||
---
|
||||
|
||||
#### Configure this node's timezone
|
||||
**Usage:**
|
||||
- `set tz.offset <offset>`
|
||||
- `get tz.offset`
|
||||
|
||||
**Parameters:**
|
||||
- `offset`: float value of the offset in hours
|
||||
|
||||
---
|
||||
|
||||
#### Fine-tune the battery reading
|
||||
**Usage:**
|
||||
- `get adc.multiplier`
|
||||
- `set adc.multiplier <value>`
|
||||
|
||||
**Parameters:**
|
||||
- `value`: ADC multiplier (0.0-10.0)
|
||||
|
||||
**Default:** `0.0` (value defined by board)
|
||||
|
||||
**Note:** Returns "Error: unsupported" if the board doesn't support it. Same command as on repeaters, for boards whose battery divider resistors vary (e.g. DIY ProMicro / Faketec).
|
||||
|
||||
---
|
||||
|
||||
### Radio
|
||||
|
||||
Radio parameters are common to all roles and handled by `CommonRadioPrefs`.
|
||||
|
||||
#### View or change this node's radio parameters
|
||||
**Usage:**
|
||||
- `get radio`
|
||||
- `set radio <freq>,<bw>,<sf>,<cr>`
|
||||
|
||||
**Parameters:**
|
||||
- `freq`: Frequency in MHz
|
||||
- `bw`: Bandwidth in kHz
|
||||
- `sf`: Spreading factor (5-12)
|
||||
- `cr`: Coding rate (5-8)
|
||||
|
||||
**Set by build flag:** `LORA_FREQ`, `LORA_BW`, `LORA_SF`, `LORA_CR`
|
||||
|
||||
**Default:** `869.618,62.5,8,5`
|
||||
|
||||
**Note:** Requires reboot to apply
|
||||
|
||||
---
|
||||
|
||||
#### View or change this node's transmit power
|
||||
**Usage:**
|
||||
- `get tx`
|
||||
- `set tx <dbm>`
|
||||
|
||||
**Parameters:**
|
||||
- `dbm`: Power level in dBm (1-22)
|
||||
|
||||
**Set by build flag:** `LORA_TX_POWER`
|
||||
|
||||
**Default:** Varies by board
|
||||
|
||||
**Notes:** This setting only controls the power level of the LoRa chip. Some nodes have an additional power amplifier stage which increases the total output. Refer to the node's manual for the correct setting to use. **Setting a value too high may violate the laws in your country.**
|
||||
|
||||
---
|
||||
|
||||
#### View or change this node's frequency
|
||||
**Usage:**
|
||||
- `get freq`
|
||||
- `set freq <frequency>`
|
||||
|
||||
**Parameters:**
|
||||
- `frequency`: Frequency in MHz
|
||||
|
||||
**Default:** `869.618`
|
||||
|
||||
**Note:** Requires reboot to apply
|
||||
**Serial Only:** `set freq <frequency>`
|
||||
|
||||
---
|
||||
|
||||
### GPS
|
||||
|
||||
#### View GPS state
|
||||
**Usage:**
|
||||
- `gps`
|
||||
|
||||
**Note:** Reports the requested state, receiver activity, last-fix status (last fix gives number of sats and how long ago was the fix), and mode. In periodic mode, `waiting` means the receiver is off between acquisitions; the last fix remains available. `off(hw)` means a hardware GPS switch is off.
|
||||
|
||||
---
|
||||
|
||||
#### Change GPS state
|
||||
**Usage:**
|
||||
- `gps <state>`
|
||||
|
||||
**Parameters:**
|
||||
- `state`: `on`|`off`
|
||||
|
||||
---
|
||||
|
||||
#### View or change the GPS acquisition period
|
||||
**Usage:**
|
||||
- `gps period`
|
||||
- `gps period <value>`
|
||||
|
||||
**Parameters:**
|
||||
- `value`: `0` for continuous tracking, or a period. The value can be postfixed with `s`, `m`, `h` or `d` to specify the unit (seconds by default).
|
||||
|
||||
**Note:** A periodic acquisition stops after receiving a valid fix, then resumes after the configured period.
|
||||
|
||||
---
|
||||
|
||||
#### View the last GPS fix
|
||||
**Usage:**
|
||||
- `gps fix`
|
||||
|
||||
**Output:**
|
||||
- `> Fix (n sat): <lat>, <lon>`: the GPS currently has a fix.
|
||||
- `> Last fix <age> ago (n sat)[, acq <time>]: <lat>, <lon>`: position of the last valid fix; `acq` is shown only while the receiver is running and shows how for how long the gps has been trying to get a fix.
|
||||
- `> No fix[, acq <time>]`: no valid fix since the node started.
|
||||
|
||||
**Note:** Ages and durations are given in `s`, `m` or `h`.
|
||||
|
||||
---
|
||||
|
||||
#### Sync this node's clock with GPS time
|
||||
**Usage:**
|
||||
- `gps sync`
|
||||
|
||||
---
|
||||
|
||||
#### On demand GPS fix
|
||||
**Usage:**
|
||||
- `gps once`
|
||||
- `gps once -s`
|
||||
|
||||
**Parameters:**
|
||||
- `-s`: also sync this node's clock with GPS time (as `gps sync`)
|
||||
|
||||
**Note:** Starts an acquisition now. If the GPS is off, it is switched and kept on until a valid fix and then turned off.
|
||||
|
||||
**Reply:** `OK - turning on and acquiring` (GPS was off), `OK - waking gps` (periodic mode, receiver off between acquisitions) or `OK - gps already on`. `Error, gps hw switch off` if a hardware GPS switch is off, `Error, gps once not supported`.
|
||||
|
||||
---
|
||||
|
||||
#### View GPS time to first fix statistics
|
||||
**Usage:**
|
||||
- `gps fix_stats`
|
||||
|
||||
**Output:** `> ttf:<last>/<max> ok:<n> miss:<n>`: last and maximum time between a start of the GPS and its first valid fix, then the last count of consecutive starts with a fix (`ok`) or without one (`miss`).
|
||||
|
||||
---
|
||||
|
||||
#### View GPS diagnostics
|
||||
**Usage:**
|
||||
- `gps diag`
|
||||
|
||||
---
|
||||
|
||||
#### View or change this node's rx boosted gain mode (SX12xx and LR1110)
|
||||
**Usage:**
|
||||
- `get radio.rxgain`
|
||||
- `set radio.rxgain <state>`
|
||||
|
||||
**Parameters:**
|
||||
- `state`: `on`|`off`
|
||||
|
||||
**Default:** `on`
|
||||
|
||||
---
|
||||
|
||||
#### View or change the LoRa FEM receive-path gain state on supported boards
|
||||
**Usage:**
|
||||
- `get radio.fem.rxgain`
|
||||
- `set radio.fem.rxgain <state>`
|
||||
|
||||
**Parameters:**
|
||||
- `state`: `on`|`off`
|
||||
|
||||
**Notes:**
|
||||
- This controls the external LoRa FEM receive-path LNA where the board supports it.
|
||||
- This is separate from `radio.rxgain`, which controls the radio chip receive gain mode.
|
||||
|
||||
---
|
||||
|
||||
#### View or change the LoRa FEM transmit-path gain state on supported boards
|
||||
**Usage:**
|
||||
- `get radio.fem.txgain`
|
||||
- `set radio.fem.txgain <state>`
|
||||
|
||||
**Parameters:**
|
||||
- `state`: `on`|`off`
|
||||
|
||||
**Notes:**
|
||||
- This controls a software-selectable external LoRa FEM transmit gain where the board supports it.
|
||||
- On Station G3, remove the PA PL1 jumper to allow software control. `on` selects PA PL1 high/short and `off` selects PA PL1 low/open. The PA PL2 hardware jumper determines whether this switches between power levels 1/3 or 2/4.
|
||||
- Select an operating level and SX1262 transmit power that comply with local RF limits and the Station G3 power-supply requirements.
|
||||
- The setting is saved immediately, but on Station G3 the level is applied to the hardware at the start of the next transmit, so that the PA supply rail is never re-targeted while the PA is being driven. `get` reports the configured state, which may lead the hardware until the node next transmits.
|
||||
|
||||
---
|
||||
|
||||
#### View or change the duty cycle limit
|
||||
**Usage:**
|
||||
- `get dutycycle`
|
||||
- `set dutycycle <value>`
|
||||
|
||||
**Parameters:**
|
||||
- `value`: Duty cycle percentage (1-100)
|
||||
|
||||
**Default:** `50%` (equivalent to airtime factor 1.0)
|
||||
|
||||
**Examples:**
|
||||
- `set dutycycle 100` — no duty cycle limit
|
||||
- `set dutycycle 50` — 50% duty cycle (default)
|
||||
- `set dutycycle 10` — 10% duty cycle
|
||||
- `set dutycycle 1` — 1% duty cycle (strictest EU requirement)
|
||||
|
||||
> **Note:** Added in firmware v1.15.0
|
||||
|
||||
---
|
||||
|
||||
#### View or change the airtime factor (duty cycle limit)
|
||||
> **Deprecated** as of firmware v1.15.0. Use [`get/set dutycycle`](#view-or-change-the-duty-cycle-limit) instead.
|
||||
|
||||
**Usage:**
|
||||
- `get af`
|
||||
- `set af <value>`
|
||||
|
||||
**Parameters:**
|
||||
- `value`: Airtime factor (0-9). After each transmission, the repeater enforces a silent period of approximately the on-air transmission time multiplied by the value. This results in a long-term duty cycle of roughly 1 divided by (1 plus the value). For example:
|
||||
- `af = 1` → ~50% duty
|
||||
- `af = 2` → ~33% duty
|
||||
- `af = 3` → ~25% duty
|
||||
- `af = 9` → ~10% duty
|
||||
You are responsible for choosing a value that is appropriate for your jurisdiction and channel plan (for example EU 868 Mhz 10% duty cycle regulation).
|
||||
|
||||
**Default:** `1.0`
|
||||
|
||||
---
|
||||
|
||||
#### View or change the local interference threshold
|
||||
**Usage:**
|
||||
- `get int.thresh`
|
||||
- `set int.thresh <value>`
|
||||
|
||||
**Parameters:**
|
||||
- `value`: Interference threshold value
|
||||
|
||||
**Default:** `0.0`
|
||||
|
||||
---
|
||||
|
||||
#### Enable or disable hardware Channel Activity Detection (CAD)
|
||||
**Usage:**
|
||||
- `get cad`
|
||||
- `set cad <on|off>`
|
||||
|
||||
**Description:** When enabled, the radio performs a hardware Channel Activity Detection scan before transmitting and defers if the channel is busy. Runs independently of `int.thresh` — either, both, or none may be active.
|
||||
|
||||
**Parameters:**
|
||||
- `on|off`: Enable or disable hardware CAD
|
||||
|
||||
**Default:** `off`
|
||||
|
||||
---
|
||||
|
||||
#### View or change the AGC Reset Interval
|
||||
**Usage:**
|
||||
- `get agc.reset.interval`
|
||||
- `set agc.reset.interval <value>`
|
||||
|
||||
**Parameters:**
|
||||
- `value`: Interval in seconds, 0-1020, rounded down to a multiple of 4 (17 becomes 16). 0 to disable.
|
||||
|
||||
**Default:** `0.0`
|
||||
|
||||
---
|
||||
|
||||
#### Enable or disable Multi-Acks support
|
||||
**Usage:**
|
||||
- `get multi.acks`
|
||||
- `set multi.acks <state>`
|
||||
|
||||
**Parameters:**
|
||||
- `state`: `0` (disable) or `1` (enable)
|
||||
|
||||
**Default:** `0`
|
||||
|
||||
---
|
||||
|
||||
#### View or change this node's advert path hash size
|
||||
**Usage:**
|
||||
- `get path.hash.mode`
|
||||
- `set path.hash.mode <value>`
|
||||
|
||||
**Parameters:**
|
||||
- `value`: Path hash size (0-2)
|
||||
- `0`: 1 Byte hash size (256 unique ids)[64 max flood]
|
||||
- `1`: 2 Byte hash size (65,536 unique ids)[32 max flood]
|
||||
- `2`: 3 Byte hash size (16,777,216 unique ids)[21 max flood]
|
||||
- `3`: DO NOT USE (Reserved)
|
||||
|
||||
**Default:** `0`
|
||||
|
||||
**Note:** the 'path.hash.mode' sets the low-level ID/hash encoding size used when the repeater adverts. This setting has no impact on what packet ID/hash size this repeater forwards, all sizes should be forwarded on firmware >= 1.14. This feature was added in firmware 1.14
|
||||
#### View or change the retransmit delay factor for flood traffic
|
||||
**Usage:**
|
||||
- `get txdelay`
|
||||
- `set txdelay <value>`
|
||||
|
||||
**Parameters:**
|
||||
- `value`: Transmit delay factor (0-2)
|
||||
|
||||
**Default:** `0.5`
|
||||
|
||||
**Note:** When multiple nearby repeaters all hear the same flood packet, each waits a random amount of time before retransmitting to avoid simultaneous collisions. This factor scales the size of that random window. Higher values reduce collision risk at the cost of added latency. `0` disables the window entirely.
|
||||
|
||||
---
|
||||
|
||||
#### View or change the retransmit delay factor for direct traffic
|
||||
**Usage:**
|
||||
- `get direct.txdelay`
|
||||
- `set direct.txdelay <value>`
|
||||
|
||||
**Parameters:**
|
||||
- `value`: Direct transmit delay factor (0-2)
|
||||
|
||||
**Default:** `0.3` (Repeater) - `0.2` (Room Server, Sensor)
|
||||
|
||||
**Note:** Same collision-avoidance random window as `txdelay`, but applied to direct (non-flood, routed) traffic. The default is lower because direct packets are addressed to a specific next hop, so far fewer nodes compete to retransmit them.
|
||||
|
||||
---
|
||||
|
||||
#### [Experimental] View or change the processing delay for received traffic
|
||||
**Usage:**
|
||||
- `get rxdelay`
|
||||
- `set rxdelay <value>`
|
||||
|
||||
**Parameters:**
|
||||
- `value`: Receive delay base (0-20)
|
||||
|
||||
**Default:** `0.0`
|
||||
|
||||
**Note:** When enabled, repeaters that received a flood packet with a weak signal are held in a delay queue before processing, while those that received it with a strong signal process it immediately. This gives strong-signal paths forwarding priority. By the time weak-signal nodes process their copy, the packet may have already propagated and will be suppressed as a duplicate, reducing redundant retransmissions.
|
||||
|
||||
---
|
||||
|
||||
### BLE
|
||||
|
||||
#### Change BLE PIN
|
||||
**Usage:**
|
||||
- `set pin <pin>`
|
||||
|
||||
**Parameters:**
|
||||
- `pin`: New BLE PIN
|
||||
|
||||
**Set by build flag:** `BLE_PIN_CODE`
|
||||
|
||||
---
|
||||
|
||||
#### Change BLE name
|
||||
**Usage:**
|
||||
- `get ble.name`
|
||||
- `set ble.name <name>`
|
||||
|
||||
**Parameters:**
|
||||
- `name`: New BLE name
|
||||
|
||||
**Note:** By default the BLE name is `Meshcore-` followed by the node name. If `<name>` is empty the BLE name will be reset to the aforementioned default. These commands require a reboot to take effect.
|
||||
|
||||
---
|
||||
|
||||
### Wifi
|
||||
|
||||
#### Get status
|
||||
**Usage:**
|
||||
- `get wifi.status`
|
||||
- `get wifi.ip`
|
||||
|
||||
---
|
||||
|
||||
#### Toggle
|
||||
**Usage:**
|
||||
- `set wifi.enabled <value>`
|
||||
- `get wifi.enabled`
|
||||
|
||||
**Parameters:**
|
||||
- `value`: `0` (disable) or `1` (enable)
|
||||
|
||||
---
|
||||
|
||||
#### Set SSID
|
||||
**Usage:**
|
||||
- `set wifi.ssid <value>`
|
||||
- `get wifi.ssid`
|
||||
|
||||
**Parameters:**
|
||||
- `value`: ssid as a string
|
||||
|
||||
---
|
||||
|
||||
#### Set password
|
||||
**Usage:**
|
||||
- `set wifi.pwd <value>`
|
||||
- `get wifi.pwd`
|
||||
|
||||
**Parameters:**
|
||||
- `value`: password string
|
||||
|
||||
---
|
||||
|
||||
### UI
|
||||
|
||||
#### Show clock
|
||||
**Usage:**
|
||||
- `set ui.show_clock <state>`
|
||||
- `get ui.show_clock`
|
||||
|
||||
**Parameters:**
|
||||
- `state`: `0` (disable) or `1` (enable)
|
||||
|
||||
**Default:** `0` (or `UI_SHOW_CLOCK` build flag)
|
||||
|
||||
---
|
||||
|
||||
#### GPS key action
|
||||
**Usage:**
|
||||
- `set ui.gps_action <action>`
|
||||
- `get ui.gps_action`
|
||||
|
||||
**Parameters:**
|
||||
- `action`: `toggle` (or `0`) to switch the GPS on and off, `once` (or `trigger`, `1`) to acquire a fix on demand, as `gps once`
|
||||
|
||||
**Default:** `toggle`, or `once` on boards with a GPS switch
|
||||
|
||||
**Note:** Only used by the `ui-new` screens for now.
|
||||
|
||||
---
|
||||
|
||||
#### Node discovery screen shows nodes names
|
||||
**Usage:**
|
||||
- `set ui.nd_name <state>`
|
||||
- `get ui.nd_name`
|
||||
|
||||
**Parameters:**
|
||||
- `state`: `1` (show name) or `0` (show pubkey_prefix)
|
||||
|
||||
**Default:** `1`
|
||||
|
||||
**Note:** When showing name, there is not always enough space to draw both incoming and outgoing snr values.
|
||||
|
||||
---
|
||||
|
||||
#### Auto-off screen
|
||||
**Usage:**
|
||||
- `set ui.auto_off_delay <delay>`
|
||||
- `get ui.auto_off_delay`
|
||||
|
||||
**Parameters:**
|
||||
- `delay`: in seconds (`0` means always on)
|
||||
|
||||
**Default:** `15` (or set by `AUTO_OFF_MILLIS` build flag (in ms))
|
||||
|
||||
**Note:**
|
||||
On e-ink displays, when turned off, the screen is not necessarily blanked, see `ui.auto_off_blank` and `ui.backlight_delay`.
|
||||
|
||||
When screen is not blanked, it is not refreshed any more. To let the user aware of that, a sleep icon is shown.
|
||||
|
||||
---
|
||||
|
||||
#### Display backlight timeout
|
||||
**Usage:**
|
||||
- `set ui.backlight_delay <delay>`
|
||||
- `get ui.backlight_delay`
|
||||
|
||||
**Parameters:**
|
||||
- `delay`: in seconds
|
||||
- `0` means no timeout
|
||||
- `-2` means always off
|
||||
- `-1` means always on
|
||||
|
||||
**Note:**
|
||||
When set to `0`, backlight can only be triggered using backlight btn.
|
||||
|
||||
---
|
||||
|
||||
#### When to turn backlight on
|
||||
**Usage:**
|
||||
- `set ui.backlight_on_keys <state>`
|
||||
- `get ui.backlight_on_keys`
|
||||
- `set ui.backlight_on_msgs <state>`
|
||||
- `get ui.backlight_on_msgs`
|
||||
|
||||
**Parameters:**
|
||||
- `state`: `0` (disable) or `1` (enable)
|
||||
|
||||
**Default:**
|
||||
- `ui.backlight_on_msgs = 0`
|
||||
- `ui.backlight_on_keys = 0` if there is a backlight button on the board, else `1`
|
||||
|
||||
**Note:**
|
||||
By default backlight is triggered by backlight button if present (as long as the button is pressed backlight is on, and is turned off after a delay).
|
||||
These toggles permits to toggle backlight when keys are pressed or when a message arrives (it acts as a notification signal).
|
||||
If `backlight_delay` is set to `0` then this setting has no effect, backlight won't be turned on.
|
||||
|
||||
---
|
||||
|
||||
#### Control if eink screen should be blanked
|
||||
**Usage:**
|
||||
- `set ui.auto_off_blank <state>`
|
||||
- `get ui.auto_off_blank`
|
||||
|
||||
**Parameters:**
|
||||
- `state`: `0` (disable) or `1` (enable)
|
||||
|
||||
**Default:** `0` (or set by `UI_SCREENOFF_BLANK` build flag)
|
||||
|
||||
**Note:**
|
||||
If disabled, when screen is shut the displays stays on screen and is not updated (an sleep icons covers battery to show the screen is sleeping).
|
||||
|
||||
When screen is blanked, the controller is also put into hibernation, which should preserve the screen a little and some battery ...
|
||||
|
||||
---
|
||||
|
||||
#### Maximum number of partial refreshes
|
||||
**Usage:**
|
||||
- `set ui.max_partial <value>`
|
||||
- `get ui.max_partial`
|
||||
|
||||
**Parmeters:**
|
||||
- `value`: max partial refreshes before doing a full refresh
|
||||
|
||||
**Default:** 0 (no partial refresh or set by `EINK_MAX_PARTIAL_REFRESH` build flag)
|
||||
|
||||
**Note:**
|
||||
Forcing full refresh helps revives the screen when some tearing appears (under certain environmental conditions). If you see some tearing appearing, you can force full refresh on your screen manually by double clicking the backlight button. If tearing reappears often, use this setting to force full refresh every `value` partial refreshes.
|
||||
+39
-15
@@ -206,7 +206,7 @@ Byte 1: 0x03
|
||||
**Command Format**:
|
||||
```
|
||||
Byte 0: 0x1F
|
||||
Byte 1: Channel Index (0-7)
|
||||
Byte 1: Channel Index (0 .. max_channels-1)
|
||||
```
|
||||
|
||||
**Example** (get channel 1):
|
||||
@@ -225,7 +225,7 @@ Byte 1: Channel Index (0-7)
|
||||
**Command Format**:
|
||||
```
|
||||
Byte 0: 0x20
|
||||
Byte 1: Channel Index (0-7)
|
||||
Byte 1: Channel Index (0 .. max_channels-1)
|
||||
Bytes 2-33: Channel Name (32 bytes, UTF-8, null-padded)
|
||||
Bytes 34-49: Secret (16 bytes)
|
||||
```
|
||||
@@ -233,8 +233,12 @@ Bytes 34-49: Secret (16 bytes)
|
||||
**Total Length**: 50 bytes
|
||||
|
||||
**Channel Index**:
|
||||
- Index 0: Reserved for public channels (no secret)
|
||||
- Indices 1-7: Available for private channels
|
||||
- Valid range is `0` to `max_channels - 1`. Read `max_channels` from byte 3 of
|
||||
the `PACKET_DEVICE_INFO` response; do not assume 8. Builds ship with
|
||||
`MAX_GROUP_CHANNELS` set to 1, 8 or 40 depending on the board.
|
||||
- Index 0: pre-populated by the firmware with the built-in "Public" channel.
|
||||
It can be overwritten like any other slot.
|
||||
- An out-of-range index is rejected with `PACKET_ERROR` / `ERR_CODE_NOT_FOUND`.
|
||||
|
||||
**Channel Name**:
|
||||
- UTF-8 encoded
|
||||
@@ -242,8 +246,18 @@ Bytes 34-49: Secret (16 bytes)
|
||||
- Padded with null bytes (0x00) if shorter
|
||||
|
||||
**Secret Field** (16 bytes):
|
||||
- For **private channels**: 16-byte secret
|
||||
- For **public channels**: All zeros (0x00)
|
||||
- Always a real 16-byte key; the firmware derives the channel hash from
|
||||
`SHA256(secret)` (`BaseChatMesh.cpp:936-942`). There is no "no secret" form.
|
||||
- Do **not** write an all-zero secret. `SHA256` over 16 zero bytes is a fixed,
|
||||
globally identical value, so a zero-secret channel is a well-known channel
|
||||
with an all-zero AES key that any node can read — not a private one. The
|
||||
firmware skips *unnamed* slots when matching inbound group traffic for
|
||||
exactly this reason (`BaseChatMesh.cpp:392-401`), but a slot that has been
|
||||
given a name and a zero secret is not skipped, and will absorb null-key
|
||||
group traffic from any node on the mesh.
|
||||
- The built-in public channel uses the well-known key
|
||||
`izOH6cXN6mrJ5e26oRXNcg==` (base64), i.e.
|
||||
`8b3387e9c5cdea6ac9e5edbaa115cd72` in hex.
|
||||
|
||||
**Example** (create channel "YourChannelName" at index 1 with secret):
|
||||
```
|
||||
@@ -265,7 +279,7 @@ Bytes 34-49: Secret (16 bytes)
|
||||
```
|
||||
Byte 0: 0x03
|
||||
Byte 1: 0x00
|
||||
Byte 2: Channel Index (0-7)
|
||||
Byte 2: Channel Index (0 .. max_channels-1)
|
||||
Bytes 3-6: Timestamp (32-bit little-endian Unix timestamp, seconds)
|
||||
Bytes 7+: Message Text (UTF-8, variable length)
|
||||
```
|
||||
@@ -288,7 +302,7 @@ Bytes 7+: Message Text (UTF-8, variable length)
|
||||
**Command Format**:
|
||||
```
|
||||
Byte 0: 0x3E
|
||||
Byte 1: Channel Index (0-7)
|
||||
Byte 1: Channel Index (0 .. max_channels-1)
|
||||
Byte 2: Path Length (0xFF = flood, otherwise actual path length)
|
||||
Bytes 3 .. 2+path_len: Path (omitted when path_len == 0xFF)
|
||||
Next 2 bytes (little-endian): Data Type (`data_type`, uint16)
|
||||
@@ -306,13 +320,23 @@ Remaining bytes: Binary payload (variable length)
|
||||
- Values `0x0001`–`0xFFFE` are available for registered application/community namespaces. See the [Registered data_type values](#registered-data_type-values) table below.
|
||||
|
||||
**Limits**:
|
||||
- Maximum payload length is `MAX_CHANNEL_DATA_LENGTH = MAX_FRAME_SIZE - 9 = 163` bytes.
|
||||
- Larger payloads are rejected with `PACKET_ERROR` (`ERR_CODE_ILLEGAL_ARG`).
|
||||
- Maximum payload length is **165** bytes — `MAX_GROUP_DATA_LENGTH =
|
||||
MAX_PACKET_PAYLOAD - CIPHER_BLOCK_SIZE - 3` (`src/MeshCore.h:21`). This is the
|
||||
radio-side limit and the one clients should enforce.
|
||||
- Two different bounds are checked, and they do not agree. The host-frame check
|
||||
uses the larger `MAX_CHANNEL_DATA_LENGTH = MAX_FRAME_SIZE - 9 = 167`
|
||||
(`companion_radio/MyMesh.cpp:1265`); the radio-side check uses 165
|
||||
(`BaseChatMesh.cpp:544`).
|
||||
- Payloads **above 167** are rejected with `ERR_CODE_ILLEGAL_ARG` (6).
|
||||
- Payloads of **166 or 167** pass the frame check, then fail the radio-side
|
||||
check and return `ERR_CODE_TABLE_FULL` (3). Despite that code's usual
|
||||
meaning, such a send can never succeed — do not retry it. Keep payloads at
|
||||
165 bytes or fewer and this case cannot arise.
|
||||
|
||||
**Response**: `PACKET_OK` (0x00) on success, or `PACKET_ERROR` (0x01) with one of:
|
||||
- `ERR_CODE_NOT_FOUND` (2) — unknown `channel_idx`
|
||||
- `ERR_CODE_ILLEGAL_ARG` (6) — invalid `path_len`, reserved `data_type` (`0x0000`), or payload larger than `MAX_CHANNEL_DATA_LENGTH`
|
||||
- `ERR_CODE_TABLE_FULL` (3) — outbound send queue is full; retry later
|
||||
- `ERR_CODE_ILLEGAL_ARG` (6) — invalid `path_len`, reserved `data_type` (`0x0000`), or payload larger than `MAX_CHANNEL_DATA_LENGTH` (167)
|
||||
- `ERR_CODE_TABLE_FULL` (3) — outbound send queue is full (retry later), **or** a payload of 166-167 bytes that exceeds the radio-side limit (permanent; see Limits above)
|
||||
|
||||
**Inbound datagrams** are delivered to the host via `RESP_CODE_CHANNEL_DATA_RECV` (0x1B); see [Receive Channel Data Datagram](#receive-channel-data-datagram).
|
||||
|
||||
@@ -341,7 +365,7 @@ Inbound group datagrams (radio-level `PAYLOAD_TYPE_GRP_DATA`, 0x06) are forwarde
|
||||
Byte 0: 0x1B (packet type)
|
||||
Byte 1: SNR (signed int8, scaled ×4 — divide by 4.0 to recover dB)
|
||||
Bytes 2-3: Reserved (clients MUST ignore)
|
||||
Byte 4: Channel Index (0-7)
|
||||
Byte 4: Channel Index (0 .. max_channels-1)
|
||||
Byte 5: Path Length (actual path length when flooded, otherwise 0xFF for direct)
|
||||
Bytes 6-7: Data Type (uint16 little-endian)
|
||||
Byte 8: Data Length
|
||||
@@ -550,7 +574,7 @@ def parse_contact_message(data):
|
||||
**Standard Format** (`PACKET_CHANNEL_MSG_RECV`, 0x08):
|
||||
```
|
||||
Byte 0: 0x08 (packet type)
|
||||
Byte 1: Channel Index (0-7)
|
||||
Byte 1: Channel Index (0 .. max_channels-1)
|
||||
Byte 2: Path Length
|
||||
Byte 3: Text Type
|
||||
Bytes 4-7: Timestamp (32-bit little-endian)
|
||||
@@ -562,7 +586,7 @@ Bytes 8+: Message Text (UTF-8)
|
||||
Byte 0: 0x11 (packet type)
|
||||
Byte 1: SNR (signed byte, multiplied by 4)
|
||||
Bytes 2-3: Reserved
|
||||
Byte 4: Channel Index (0-7)
|
||||
Byte 4: Channel Index (0 .. max_channels-1)
|
||||
Byte 5: Path Length
|
||||
Byte 6: Text Type
|
||||
Bytes 7-10: Timestamp (32-bit little-endian)
|
||||
|
||||
+32
-27
@@ -537,18 +537,18 @@ Mac: python3 should be already installed.
|
||||
|
||||
Then it should be the same for all platforms:
|
||||
```
|
||||
python3 -m venv meshcore
|
||||
cd meshcore && source bin/activate
|
||||
python3 -m venv meshcore-venv
|
||||
cd meshcore-venv && source bin/activate
|
||||
pip install -U platformio
|
||||
git clone https://github.com/ripplebiz/MeshCore.git
|
||||
cd MeshCore
|
||||
git clone https://github.com/meshcore-dev/meshcore.git
|
||||
cd meshcore
|
||||
```
|
||||
open platformio.ini and in `[arduino_base]` edit the `LORA_FREQ=867.5`
|
||||
save, then run:
|
||||
open platformio.ini and in `[arduino_base]` edit `LORA_FREQ` (it defaults to
|
||||
`869.618`) to the frequency for your region, save, then run:
|
||||
```
|
||||
pio run -e RAK_4631_Repeater
|
||||
pio run -e RAK_4631_repeater
|
||||
```
|
||||
then you'll find `firmware.zip` in `.pio/build/RAK_4631_Repeater`
|
||||
then you'll find `firmware.zip` in `.pio/build/RAK_4631_repeater`
|
||||
|
||||
### 5.10. Q: Are there other MeshCore related open source projects?
|
||||
|
||||
@@ -592,7 +592,7 @@ For ESP-based devices (e.g. Heltec V3) you need:
|
||||
1. Download the firmware file from <https://flasher.meshcore.io>.
|
||||
- Go to the website in a browser and find the section that has the firmware you need.
|
||||
- Click the Download button, right-click on the file you need, for example:
|
||||
- `Heltec_V3_companion_radio_ble-v1.7.1-165fb33.bin`
|
||||
- `Heltec_v3_companion_radio_ble-v1.7.1-165fb33.bin`
|
||||
- Non-merged bin keeps the existing Bluetooth pairing database.
|
||||
- `Heltec_v3_companion_radio_usb-v1.7.1-165fb33-merged.bin`
|
||||
- Merged bin overwrites everything including the bootloader and existing Bluetooth pairing database, but keeps configurations.
|
||||
@@ -691,23 +691,28 @@ You can get the epoch time on <https://www.epochconverter.com> and use it to set
|
||||
### 6.6. Q: My Heltec V3 keeps disconnecting from my smartphone. It can't hold a solid Bluetooth connection.
|
||||
**A:** Heltec V3 has a very small coil antenna on its PCB for Wi-Fi and Bluetooth connectivity. It has a very short range, only a few feet. It is possible to remove the coil antenna and replace it with a 31mm wire. The BT range is much improved with the modification.
|
||||
|
||||
### 6.7. Q: My RAK/T1000-E/xiao_nRF52 device seems to be corrupted, how do I wipe it clean to start fresh?
|
||||
**A:**
|
||||
### 6.7. Q: My RAK/T1000-E/xiao_nRF52/... device seems to be corrupted, how do I wipe it clean to start fresh?
|
||||
**A: If you're able to connect to the device from your MeshCore app**
|
||||
1. Navigate to Gear icon(Settings) on the upper right corner
|
||||
2. Click on `Export Settings` button, choose `Select All` and Confirm. This will save your Node configuration
|
||||
3. Now choose `Factory Reset` option
|
||||
4. Confirm that you want to reset your device
|
||||
5. Go to Bluetooth System settings and remove pairing of the device, so you can connect again
|
||||
6. Connect your device in the app and enter the PIN
|
||||
7. Navigate to Gear icon(Settings) on the upper right corner
|
||||
8. Click on `Import Settings` and choose the file from 2., click on `Select All` and Confirm
|
||||
9. Find `Reboot` button on of the Settings list
|
||||
|
||||
1. Connect USB-C cable to your device, per your device's instruction, get it to flash mode:
|
||||
- For RAK, click the reset button **TWICE**
|
||||
- For T1000-e, quickly disconnect and reconnect the magnetic side of the cable from the device **TWICE**
|
||||
- For Heltec T114, click the reset button **TWICE** (the bottom button)
|
||||
- For Xiao nRF52, click the reset button once. If that doesn't work, quickly double-click the reset button twice. If that doesn't work, disconnect the board from your PC and reconnect again ([seeed studio wiki](https://wiki.seeedstudio.com/XIAO_BLE/#access-the-swd-pins-for-debugging-and-reflashing-bootloader))
|
||||
2. A new folder will appear on your computer's desktop
|
||||
3. Download the `flash_erase*.uf2` file for your device on <https://flasher.meshcore.io>
|
||||
- RAK WisBlock and Heltec T114: `Flash_erase-nRF32_softdevice_v6.uf2`
|
||||
- Seeed Studio Xiao nRF52 WIO: `Flash_erase-nRF52_softdevice_v7.uf2`
|
||||
4. drag and drop the uf2 file for your device to the root of the new folder
|
||||
5. Wait for the copy to complete. You might get an error dialog, you can ignore it
|
||||
6. Go to <https://flasher.meshcore.io>, click `Console` and select the serial port for your connected device
|
||||
7. In the console, press enter. Your flash should now be erased
|
||||
8. You may now flash the latest MeshCore firmware onto your device
|
||||
**B: You're not able to connect to the App**
|
||||
1. Connect USB cable to your device
|
||||
2. Go to https://flasher.meshcore.io
|
||||
3. Search for your device in the list
|
||||
4. Choose `Companion Bluetooth`
|
||||
5. Press `Enter DFU mode` button, choose your USB device
|
||||
6. Press `Erase Flash` button, choose the device again and wait until it completes
|
||||
7. Press `Flash!` button and choose the USB device last time
|
||||
8. The device is erased and newest firmware is installed
|
||||
9. You might need to remove the pairing in Bluetooth System Settings in order to re-pair the app again.
|
||||
|
||||
Separately, starting in firmware version 1.7.0, there is a CLI Rescue mode. If your device has a user button (e.g. some RAK, T114), you can activate the rescue mode by holding down the user button of the device within 8 seconds of boot. Then you can use the 'Console' on <https://flasher.meshcore.io>
|
||||
|
||||
@@ -716,9 +721,9 @@ Separately, starting in firmware version 1.7.0, there is a CLI Rescue mode. If y
|
||||
|
||||
`NetworkError: Failed to execute 'open' on 'SerialPort': Failed to open serial port.`
|
||||
|
||||
Allow the browser user on it:
|
||||
Allow user access on your USB port:
|
||||
|
||||
`# setfacl -m u:YOUR_USER_HERE:rw /dev/ttyUSB0`
|
||||
`sudo setfacl -m u:$USER:rw /dev/ttyUSB0`
|
||||
|
||||
---
|
||||
|
||||
|
||||
+90
-10
@@ -18,10 +18,10 @@ Standard KISS framing per the KA9Q/K3MC specification.
|
||||
| `0xDD` | TFESC | Escaped FESC (FESC + TFESC = 0xDB) |
|
||||
|
||||
```
|
||||
┌──────┬───────────┬──────────────┬──────┐
|
||||
│ FEND │ Type Byte │ Data (escaped)│ FEND │
|
||||
│ 0xC0 │ 1 byte │ 0-510 bytes │ 0xC0 │
|
||||
└──────┴───────────┴──────────────┴──────┘
|
||||
┌──────┬───────────┬────────────────┬──────┐
|
||||
│ FEND │ Type Byte │ Data (escaped) │ FEND │
|
||||
│ 0xC0 │ 1 byte │ 0-510 bytes │ 0xC0 │
|
||||
└──────┴───────────┴────────────────┴──────┘
|
||||
```
|
||||
|
||||
### Type Byte
|
||||
@@ -82,10 +82,10 @@ MeshCore-specific functionality uses the standard KISS SetHardware command. The
|
||||
### Frame Format
|
||||
|
||||
```
|
||||
┌──────┬──────┬─────────────┬──────────────┬──────┐
|
||||
│ FEND │ 0x06 │ Sub-command │ Data (escaped)│ FEND │
|
||||
│ 0xC0 │ │ 1 byte │ variable │ 0xC0 │
|
||||
└──────┴──────┴─────────────┴──────────────┴──────┘
|
||||
┌──────┬──────┬─────────────┬────────────────┬──────┐
|
||||
│ FEND │ 0x06 │ Sub-command │ Data (escaped) │ FEND │
|
||||
│ 0xC0 │ │ 1 byte │ variable │ 0xC0 │
|
||||
└──────┴──────┴─────────────┴────────────────┴──────┘
|
||||
```
|
||||
|
||||
### Request Sub-commands (Host to TNC)
|
||||
@@ -118,10 +118,17 @@ MeshCore-specific functionality uses the standard KISS SetHardware command. The
|
||||
| Reboot | `0x18` | - |
|
||||
| SetSignalReport | `0x19` | Enable (1): 0x00=disable, nonzero=enable |
|
||||
| GetSignalReport | `0x1A` | - |
|
||||
| GetCapabilities | `0x1B` | - |
|
||||
| SetAgcResetInterval | `0x1C` | Seconds (2): 0=disable, 0-1020 |
|
||||
| GetAgcResetInterval | `0x1D` | - |
|
||||
| SetFemState | `0x1E` | Apply mask (1) + Value mask (1) |
|
||||
| GetFemState | `0x1F` | - |
|
||||
| SetRxBoostedGain | `0x20` | Enable (1): 0x00=disable, nonzero=enable |
|
||||
| GetRxBoostedGain | `0x21` | - |
|
||||
|
||||
### Response Sub-commands (TNC to Host)
|
||||
|
||||
Response codes use the high-bit convention: `response = command | 0x80`. Generic and unsolicited responses use the `0xF0`+ range.
|
||||
Response codes use the high-bit convention: `response = command | 0x80`. Generic and unsolicited responses use the `0xF0`+ range. Set commands that report state (SetSignalReport, SetAgcResetInterval, SetFemState, SetRxBoostedGain) reply with the matching Get response, so `0x9C`, `0x9E` and `0xA0` are never sent.
|
||||
|
||||
| Sub-command | Value | Data |
|
||||
|--------------|--------|-----------------------------------------|
|
||||
@@ -147,6 +154,10 @@ Response codes use the high-bit convention: `response = command | 0x80`. Generic
|
||||
| DeviceName | `0x96` | Name (variable, UTF-8) |
|
||||
| Pong | `0x97` | - |
|
||||
| SignalReport | `0x9A` | Status (1): 0x00=disabled, 0x01=enabled |
|
||||
| Capabilities | `0x9B` | Feature bits (4) |
|
||||
| AgcResetInterval | `0x9D` | Effective seconds (2) |
|
||||
| FemState | `0x9F` | Capability mask (1) + Value mask (1) |
|
||||
| RxBoostedGain | `0xA1` | Status (1): 0x00=disabled, 0x01=enabled |
|
||||
| OK | `0xF0` | - |
|
||||
| Error | `0xF1` | Error code (1) |
|
||||
| TxDone | `0xF8` | Result (1): 0x00=failed, 0x01=success |
|
||||
@@ -163,6 +174,7 @@ Response codes use the high-bit convention: `response = command | 0x80`. Generic
|
||||
| UnknownCmd | `0x05` | Unknown sub-command |
|
||||
| EncryptFailed | `0x06` | Encryption failed |
|
||||
| TxBusy | `0x07` | Radio TX busy, or host output queue full |
|
||||
| Unsupported | `0x08` | Command known, but not supported by this board |
|
||||
|
||||
### Unsolicited Events
|
||||
|
||||
@@ -215,7 +227,75 @@ All values little-endian.
|
||||
|-------------|---------|-----------------------|
|
||||
| Noise floor | 2 bytes | int16_t, dBm (signed) |
|
||||
|
||||
The modem recalibrates the noise floor every 2 seconds with an AGC reset every 30 seconds.
|
||||
The modem recalibrates the noise floor every 2 seconds. AGC resets follow the configured AGC reset interval (default 32 seconds).
|
||||
|
||||
### Capabilities (Capabilities response)
|
||||
|
||||
All values little-endian. Hosts should probe capabilities rather than infer them from the firmware version: boards running the same version expose different hardware controls. Firmware older than version 2 answers GetCapabilities with `UnknownCmd`; treat that as no capabilities.
|
||||
|
||||
| Field | Size | Description |
|
||||
|--------------|---------|--------------------|
|
||||
| Feature bits | 4 bytes | uint32_t, see below |
|
||||
|
||||
| Bit | Value | Description |
|
||||
|-----|--------|-------------------------------------------|
|
||||
| 0 | `0x01` | AGC reset interval control (always set) |
|
||||
| 1 | `0x02` | External FEM RX (LNA) gain control |
|
||||
| 2 | `0x04` | External FEM TX (PA) gain control |
|
||||
| 3 | `0x08` | Radio chip boosted RX gain control |
|
||||
|
||||
Remaining bits are reserved and sent as 0.
|
||||
|
||||
### AGC Reset Interval (SetAgcResetInterval / AgcResetInterval response)
|
||||
|
||||
All values little-endian.
|
||||
|
||||
| Field | Size | Description |
|
||||
|---------|---------|-------------------------------------------|
|
||||
| Seconds | 2 bytes | uint16_t, 0 = disabled, maximum 1020 |
|
||||
|
||||
The modem periodically resets the radio's AGC while idle (no transmission in progress and host output not backed up). The interval has 4-second resolution, matching the MeshCore `agc.reset.interval` setting: requested values are rounded down to a multiple of 4, so 1-3 disable the reset. Values above 1020 return `InvalidParam`. SetAgcResetInterval replies with the AgcResetInterval response carrying the effective value, and restarts the countdown from the time of the request.
|
||||
|
||||
The default is 32 seconds (previously a fixed 30; changed so the default is a settable 4-second multiple). The setting is not persisted; hosts should re-send it after reconnecting or rebooting the modem.
|
||||
|
||||
### FEM State (SetFemState / FemState response)
|
||||
|
||||
Controls the board's external LoRa front-end module gain. This is separate from the radio chip's own RX boosted gain. TX/RX switching of the FEM is handled by the board and is not affected by these settings.
|
||||
|
||||
| Bit | Value | Description |
|
||||
|-----|--------|---------------------------------|
|
||||
| 0 | `0x01` | RX gain (LNA enabled) |
|
||||
| 1 | `0x02` | TX gain (PA high gain enabled) |
|
||||
|
||||
SetFemState data:
|
||||
|
||||
| Field | Size | Description |
|
||||
|------------|--------|------------------------------------------------|
|
||||
| Apply mask | 1 byte | Bits to change; bits not set are left as-is |
|
||||
| Value mask | 1 byte | New value for each bit in the apply mask |
|
||||
|
||||
FemState response data:
|
||||
|
||||
| Field | Size | Description |
|
||||
|-----------------|--------|---------------------------------------------------|
|
||||
| Capability mask | 1 byte | Bits this board can control |
|
||||
| Value mask | 1 byte | Current state; always 0 for uncontrollable bits |
|
||||
|
||||
Example: enable RX gain without changing TX gain: apply `0x01`, value `0x01`.
|
||||
|
||||
If any bit in the apply mask is not in the board's capability mask (including reserved bits), the modem replies `Unsupported` and changes nothing. Otherwise SetFemState replies with the FemState response carrying the state read back from the board; if a bit differs from the request, that change did not take effect. SetFemState and GetFemState requests, including their error replies, are answered strictly in the order received. A SetFemState received while a packet is on air (before its TxDone is queued) is held and applied after TxDone, so its reply follows TxDone, and FEM requests that arrive after it wait behind it. Up to 4 FEM requests can wait; beyond that the modem replies `TxBusy` immediately. Capabilities come from the board's own `get/set radio.fem.rxgain` and `radio.fem.txgain` CLI commands (see [cli_commands.md](./cli_commands.md)): a gain is controllable when the board answers `get` with `> on` or `> off`. Any board that implements those commands is supported without KISS changes, and a board with a fixed, board-managed FEM (for example RAK3401) reports none. Changes made over KISS are not saved to the board's preferences.
|
||||
|
||||
The setting is not persisted; the board's power-on default applies after reboot.
|
||||
|
||||
### RX Boosted Gain (SetRxBoostedGain / RxBoostedGain response)
|
||||
|
||||
Controls the radio chip's own boosted RX gain mode (SX1262, SX1268, LLCC68, LR11x0, LR2021), the equivalent of the MeshCore `radio.rxgain` setting. This is independent of the external FEM RX gain controlled by SetFemState; a board can support either, both or neither.
|
||||
|
||||
| Field | Size | Description |
|
||||
|--------|--------|------------------------------------|
|
||||
| Status | 1 byte | 0x00 = power-saving, 0x01 = boosted |
|
||||
|
||||
SetRxBoostedGain always replies with the RxBoostedGain response carrying the effective state read back from the radio; if it differs from the requested value, the change did not take effect. Some radios must drop to standby to apply it, so the modem replies `TxBusy` and changes nothing while a packet is on air or host output is backed up; retry later. Before applying, any completed received packet is delivered to the host first. A packet still being received at that moment can be lost. Radios whose driver has no boosted RX gain control (for example SX127x and STM32WLx) do not set capability bit 3 and reply `Unsupported` to both commands. The power-on default is the build's `SX126X_RX_BOOSTED_GAIN` setting; the value is not persisted, and periodic AGC resets preserve it.
|
||||
|
||||
### Stats (Stats response)
|
||||
|
||||
|
||||
@@ -186,11 +186,19 @@ Power management status can be queried via the CLI:
|
||||
| `get pwrmgt.bootreason` | Returns reset and shutdown reason strings |
|
||||
| `get pwrmgt.bootmv` | Returns boot voltage in millivolts |
|
||||
|
||||
On boards without power management enabled, all commands except `get pwrmgt.support` return:
|
||||
On boards without power management enabled, `get pwrmgt.source` and
|
||||
`get pwrmgt.bootmv` return:
|
||||
```
|
||||
ERROR: Power management not supported
|
||||
```
|
||||
|
||||
`get pwrmgt.support` returns `unsupported`. `get pwrmgt.bootreason` is not
|
||||
compiled out at all and answers on every board: `getResetReason()` and
|
||||
`getShutdownReason()` are virtuals on the base board class, so a board that
|
||||
does not override them reports `Not available` rather than an error. ESP32
|
||||
boards override the reset half with `esp_reset_reason()`, so they return a real
|
||||
reset reason and `Not available` for the shutdown reason.
|
||||
|
||||
## Debug Output
|
||||
|
||||
When `MESH_DEBUG=1` is enabled, the power management module outputs:
|
||||
|
||||
@@ -19,6 +19,8 @@ Once you have a working app/project, you need to be able to demonstrate it exist
|
||||
| 0110 - 011F | Ripple | ripple_biz@protonmail.com — https://buymeacoffee.com/ripplebiz |
|
||||
| 0120 | MCO Advanced | most.original.address@gmail.com — https://hdden.ru/MCOa/ |
|
||||
| 0130 - 013F | StreamSensor | william@housedillon.com - https://housedillon.com/blog/lora-e5-with-seeed-fusion |
|
||||
| 0140 | Nelos | support@nelos.app — https://nelos.app |
|
||||
| 0150 | Road Events | juraj@bednar.io — https://github.com/jooray/roadbeacon/blob/main/nips/road-events.md |
|
||||
| FF00 - FFFF | -reserved for testing/dev- | |
|
||||
|
||||
(add rows, inside the range 0100 - FEFF for custom apps)
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
# Admin-pushed firmware update (experimental `-ota` images)
|
||||
|
||||
> [!WARNING]
|
||||
> Part of an experimental fork, not meant for regular users: its releases
|
||||
> are a rolling release on MeshCore `dev` (see the [README](../README.md)).
|
||||
|
||||
The `*-ota` and `*-observer-ota` images of this fork's releases can take a new
|
||||
firmware from their admin -- over the USB or BLE console, or **over the mesh,
|
||||
as remote admin CLI**. Nothing changes in the bootloader and there is no second
|
||||
bank: the node stores the package in free flash, checks all of it, and only on
|
||||
an explicit `fw apply` rewrites itself from a routine running in RAM.
|
||||
|
||||
The point is the **delta**: a package against the image the node runs is
|
||||
usually a few kB, so it goes through LoRa in minutes. A full image (~300 kB)
|
||||
goes only over USB or BLE.
|
||||
|
||||
**Rolling release on `dev`, for experienced users.** These `-ota` images track
|
||||
MeshCore `dev`, merged continuously, so a new release lands roughly twice a day
|
||||
and each delta stays small. There is no stable channel, no second bank, and no
|
||||
automatic rollback: a bad image that still boots keeps running until you push the
|
||||
next one, and one that will not boot needs USB/BLE DFU in hand. Run it only on
|
||||
nodes you can reach, and try every release on one within reach first.
|
||||
|
||||
## What a release carries
|
||||
|
||||
For every `<board>_<role>-ota` / `-observer-ota` image:
|
||||
|
||||
| file | what |
|
||||
|---|---|
|
||||
| `<image>-<release>.zip` / `.uf2` | the image, flashed the usual way (first time) |
|
||||
| `<image>-<release>.mcfw` | full package: USB/BLE console only |
|
||||
| `<image>-<release>.from-<earlier>.mcfw` | delta from an earlier release's same image |
|
||||
| `manifest.json` | image sha256, target, build epoch, packages, deltas by base |
|
||||
| `SHA256SUMS`, `SHA256SUMS.sig` | checksums, signed by `meshcore-ota@tth-pub` |
|
||||
|
||||
Check a download:
|
||||
|
||||
ssh-keygen -Y verify -f tools/ota_allowed_signers -I meshcore-ota@tth-pub \
|
||||
-n meshcore-ota -s SHA256SUMS.sig < SHA256SUMS
|
||||
sha256sum -c --ignore-missing SHA256SUMS
|
||||
|
||||
`tools/ota_pack.py fetch <image> --base <sha8>` does both and picks the delta
|
||||
for the node's image (`--full` for the full package, `--release <tag>` for
|
||||
another than the latest).
|
||||
|
||||
## On the node
|
||||
|
||||
```
|
||||
fw status state, battery, the running image's size and sha256 prefix
|
||||
fw ver target and build epoch a package for this image needs
|
||||
fw begin <bytes> [sid] start a transfer
|
||||
fw w <offset> <base64> one 96 B chunk (text)
|
||||
fw missing what is still missing
|
||||
fw verify queue the full check, poll fw status
|
||||
fw apply battery gate, then rewrite and reboot
|
||||
fw apply downgrade local console only: an older (or the same) image
|
||||
fw abort
|
||||
```
|
||||
|
||||
What the node checks before it touches its own image:
|
||||
|
||||
1. The **manifest**, as soon as it is in: an Ed25519 signature by the key the
|
||||
image was built with (`[ota] pubkey`), the target (board + variant: an
|
||||
`-observer-ota` node takes no `-ota` package), the size, for a delta the
|
||||
base (the sha256 of the image it runs), and the build epoch.
|
||||
2. Over the mesh: **only a delta, and only a newer build.** An older or equal
|
||||
one is refused right after the manifest; a full image is refused when the
|
||||
transfer begins. Locally a full image is fine, and an older one takes
|
||||
`fw apply downgrade`.
|
||||
3. `fw verify`: the payload hash, and a delta applied **dry** -- the same code
|
||||
the real run uses, with the flash untouched -- must produce the signed
|
||||
image hash.
|
||||
4. `fw apply`: battery at 3.8 V or more unless the node runs on USB. The
|
||||
bootloader settings get the new image's CRC **first**, so a power cut during
|
||||
the rewrite leaves the node in the bootloader (back with USB/BLE DFU), not
|
||||
in half an image.
|
||||
|
||||
## When an update goes wrong
|
||||
|
||||
No second bank, no automatic rollback. The checks above stop a *corrupt* package,
|
||||
but firmware that passes them and still boots into a broken state keeps running.
|
||||
Two watchdogs catch that. The deaf-receiver one is **off by default** -- turn it
|
||||
on for nodes you push to; the TX stall one is on in repeaters:
|
||||
|
||||
set radio.silence <min> re-arm the receiver, then reboot, if it hears nothing
|
||||
for <min> (persisted, off by default); catches an OTA
|
||||
that boots with a dead radio
|
||||
set radio.txstall <min> the same when the TX queue stalls (repeater only, on
|
||||
at 15 min by default, a change holds until reboot)
|
||||
get radio.reboots watchdog reboots so far (survives power loss)
|
||||
get boot why the board last reset, plus the hardfault record
|
||||
|
||||
Details: `docs/cli_commands.md`, "Radio silence watchdog" and "TX stall watchdog".
|
||||
|
||||
A node that will not boot at all has to be reflashed over USB/BLE DFU. After an
|
||||
`fw apply` over **BLE** the bond can drop (a supervision timeout while the node
|
||||
reboots) -- re-pair from the same host; it is not a brick.
|
||||
|
||||
## Tools
|
||||
|
||||
```bash
|
||||
# a delta for the node's image, from the latest release
|
||||
tools/ota_pack.py fetch Xiao_nrf52_repeater-ota --base <sha8 from fw status>
|
||||
|
||||
# over the mesh, through a companion (USB port or tcp://host:port), as admin
|
||||
tools/ota_mesh_push.py /dev/serial/by-id/<companion> <node pubkey prefix> pkg.mcfw --apply
|
||||
|
||||
# over the node's own USB console
|
||||
tools/ota_push.py /dev/serial/by-id/<node> pkg.mcfw --apply
|
||||
```
|
||||
|
||||
### From a phone
|
||||
|
||||
The [tth fork of meshcore-open](https://git.rfa.cz/tth-pub/meshcore-open)
|
||||
(Android, Obtainium) has it in the repeater management of an admin: Firmware
|
||||
update (OTA). With no file chosen it reads the node's target and image and
|
||||
takes the delta from the latest release (checked against `SHA256SUMS`); the
|
||||
side channel below is a switch there.
|
||||
|
||||
### Off the shared channel: `--side`
|
||||
|
||||
tools/ota_mesh_push.py <companion> <node> pkg.mcfw --apply \
|
||||
--side 869.525,62.5,7,5 --duty 10 --gap 1
|
||||
|
||||
Login, `fw status` and `get radio` still go over the mesh; then the node gets
|
||||
`tempradio <side>,3`, the companion retunes to the same preset, logs in again
|
||||
zero-hop, and the chunks go there. The window grows to `--window` (15 min) once
|
||||
the link is proven and is renewed while the transfer runs. The node comes back
|
||||
by itself when the window runs out, on `fw apply` (the reboot), or when the
|
||||
tool sends it back with `tempradio <its preset>,1`. Nothing new in the firmware:
|
||||
any node with `tempradio` takes it.
|
||||
|
||||
- The companion must be in **direct** range of the node, and it must be a
|
||||
companion **firmware** that retunes its own radio. An openHop virtual
|
||||
companion answers `set_radio` with OK and stays put; the tool checks that
|
||||
and stops, and the node returns within 3 minutes.
|
||||
- The companion's preset is put back at the end -- unless the tool is killed
|
||||
hard; then `set_radio` it back yourself.
|
||||
- The example preset sits inside 869.4-869.65 MHz (10 % duty) between the CZ
|
||||
mesh (869.432/62.5) and EU Narrow (869.618/62.5). The node keeps its TX
|
||||
power on the side channel: pick a band where that power is allowed.
|
||||
|
||||
The transfer in both tools is the OTA engine of the
|
||||
[tth.meshcore Ansible collection](https://git.rfa.cz/tth-pub/meshcore-ansible)
|
||||
(`plugins/module_utils/meshcore_ota_engine.py`) -- its `meshcore_fw_ota` module
|
||||
runs the same code, so a fix lands everywhere at once. The tools need only its
|
||||
files, not Ansible: an installed collection
|
||||
(`ansible-galaxy collection install git+https://git.rfa.cz/tth-pub/meshcore-ansible.git`),
|
||||
a checkout named by `MESHCORE_ANSIBLE`, or one next to this repository
|
||||
(`tools/ota_collection.py` prints which one it uses).
|
||||
|
||||
`ota_mesh_push.py` needs the `meshcore` Python library. It logs in as admin
|
||||
(password from `[secrets] admin_pw` of `platformio.local.ini`, or asked for),
|
||||
sends binary chunks with a pause between them, asks which are missing and
|
||||
resends only those, and keeps an airtime budget (`--duty`, default 1 % per
|
||||
hour: the 865-868 MHz band). A refused package costs the two manifest chunks,
|
||||
not the whole transfer. Check `get radio` on both ends first: this transmits.
|
||||
|
||||
## Your own builds
|
||||
|
||||
A build with `-D FW_OTA=1` trusts `[ota] pubkey` of `platformio.ini` -- the
|
||||
release key. To sign your own packages, set your key in the gitignored
|
||||
`platformio.local.ini`:
|
||||
|
||||
```ini
|
||||
[ota]
|
||||
pubkey = <tools/ota_pack.py pubkey --key your.key>
|
||||
```
|
||||
|
||||
and pack with `tools/ota_pack.py pack|diff <env> --key your.key`. Target and
|
||||
build epoch come from the ELF, never from the command line. Keep every image
|
||||
you flash: a delta needs the exact bytes the node runs as its base.
|
||||
|
||||
Cost: about 10 kB of RAM on a repeater, the applier code in RAM, a 32 kB
|
||||
buffer while a full package is verified or applied. Classic images (without
|
||||
`-ota`) have none of it.
|
||||
+46
-9
@@ -93,6 +93,7 @@ Returned path messages provide a description of the route a packet took from the
|
||||
| Field | Size (bytes) | Description |
|
||||
|--------------|-----------------|------------------------------------------|
|
||||
| timestamp | 4 | sender time (unix timestamp) |
|
||||
| req type | 1 | request sub type |
|
||||
| request data | rest of payload | application-defined request payload body |
|
||||
|
||||
For the common chat/server helpers in `BaseChatMesh`, the current request type values are:
|
||||
@@ -100,7 +101,13 @@ For the common chat/server helpers in `BaseChatMesh`, the current request type v
|
||||
| Value | Name | Description |
|
||||
|--------|-----------|----------------------------------------------------|
|
||||
| `0x01` | get stats | get stats of repeater or room server |
|
||||
| `0x02` | keepalive | keep-alive request used for maintained connections |
|
||||
| `0x02` | keepalive | (deprecated) |
|
||||
| `0x03` | get telemetry | request node telemetry |
|
||||
| `0x04` | get min/max/avg | get sensor node stats on time series data |
|
||||
| `0x05` | get acl | node ACL query |
|
||||
| `0x06` | get neighbors | node neighbors query |
|
||||
| `0x08` | subscribe | subscribe to telemetry push |
|
||||
| `0x09` | ubsubscribe | unsubscribe from telemetry push |
|
||||
|
||||
#### Get stats
|
||||
|
||||
@@ -125,21 +132,50 @@ Gets information about the node, possibly including the following:
|
||||
* Number posted (?)
|
||||
* Number of post pushes (?)
|
||||
|
||||
#### Get telemetry data
|
||||
|
||||
Not defined in `BaseChatMesh`. Sensor- and application-specific request payloads may be implemented by higher-level firmware.
|
||||
|
||||
#### Get Telemetry
|
||||
|
||||
Not defined in `BaseChatMesh`.
|
||||
| Field | Size (bytes) | Description |
|
||||
|----------------|--------------|------------------------------|
|
||||
| timestamp | 4 | sender time (unix timestamp) |
|
||||
| req type | 1 | 0x03 (request sub type) |
|
||||
| permission mask | 1 | bitwise inverse mask to AND to permissions (0 = get ALL telem values) |
|
||||
|
||||
#### Get Min/Max/Ave (Sensor nodes)
|
||||
|
||||
Not defined in `BaseChatMesh`.
|
||||
| Field | Size (bytes) | Description |
|
||||
|----------------|--------------|------------------------------|
|
||||
| timestamp | 4 | sender time (unix timestamp) |
|
||||
| req type | 1 | 0x04 (request sub type) |
|
||||
| start | 4 | starting time, seconds ago |
|
||||
| end | 4 | ending time, seconds ago |
|
||||
| reserved | 2 | should be zeroes |
|
||||
|
||||
#### Subscribe to Telemetry push - (Sensor nodes)
|
||||
|
||||
| Field | Size (bytes) | Description |
|
||||
|----------------|--------------|------------------------------|
|
||||
| timestamp | 4 | sender time (unix timestamp) |
|
||||
| req type | 1 | 0x08 (request sub type) |
|
||||
| push tag | 4 | 32-bit tag to be used in telemetry push _REPLY payloads |
|
||||
| timeout secs | 2 | subscription timeout (seconds) |
|
||||
| reserved | 1 | should be zero |
|
||||
| min deltas len | 1 | byte length of LPP encoded min_deltas |
|
||||
| min deltas | (variable) | LPP encoded min_deltas |
|
||||
|
||||
#### Unsubscribe from Telemetry push - (Sensor nodes)
|
||||
|
||||
| Field | Size (bytes) | Description |
|
||||
|----------------|--------------|------------------------------|
|
||||
| timestamp | 4 | sender time (unix timestamp) |
|
||||
| req type | 1 | 0x09 (request sub type) |
|
||||
|
||||
#### Get Access List
|
||||
|
||||
Not defined in `BaseChatMesh`.
|
||||
| Field | Size (bytes) | Description |
|
||||
|----------------|--------------|------------------------------|
|
||||
| timestamp | 4 | sender time (unix timestamp) |
|
||||
| req type | 1 | 0x05 (request sub type) |
|
||||
| reserved | 2 | should be zeroes |
|
||||
|
||||
#### Get Neighbors
|
||||
|
||||
@@ -171,8 +207,9 @@ txt_type
|
||||
| Value | Description | Message content |
|
||||
|--------|---------------------------|--------------------------------------------------------------------------|
|
||||
| `0x00` | plain text message | the plain text of the message |
|
||||
| `0x01` | CLI command | the command text of the message |
|
||||
| `0x01` | CLI data | CLI command OR reply text |
|
||||
| `0x02` | signed plain text message | first four bytes is sender pubkey prefix, followed by plain text message |
|
||||
| `0x03` | CLI command | (since v1.18+) CLI command text (explicit) |
|
||||
|
||||
## Anonymous request
|
||||
|
||||
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
# Power saving on a solar repeater — what it costs, measured
|
||||
|
||||
Everything here was measured on the deployment hardware (SenseCAP Solar Node
|
||||
P1-Pro, nRF52840 + SX1262 + L76K) on 2026-08-05/06 with `tools/power_ab.py`, not
|
||||
taken from a datasheet. Numbers are input current on the 5 V USB side; the delta
|
||||
between two states is what the paired design measures, and that is what these
|
||||
figures are.
|
||||
|
||||
## The order that matters
|
||||
|
||||
| lever | measured | verdict |
|
||||
|---|---|---|
|
||||
| **GPS running continuously** | **46.0 mA** (spread 43.7-47.5) | `gps duty` recovers 42-45 of it |
|
||||
| BLE advertising + Bluefruit's blinking LED | see below | defaults changed, LED off, 1 s interval |
|
||||
| `powersaving on` (MCU light sleep) | **~1 mA, not separable from zero** | keep it on (free), but it is not a lever |
|
||||
| RX duty cycle (`set radio.rxps`, from EasySkyMesh) | **~2.3 mA** at `max` (XIAO, 12. 11. 2026) | **no** on a live node: -16 % received and a TX stall on mast-three, see below |
|
||||
| `radio.rxgain off` | ~0.7 mA | **no** — 1-3 dB of sensitivity is what a mast node is for |
|
||||
| FEM LNA control | n/a | SenseCap has no FEM, only an RXEN switch |
|
||||
|
||||
A whole node in the shipping configuration, with the battery charged and GPS
|
||||
duty-cycled, sits at **~24 mA**. Continuous GPS alone would nearly triple that.
|
||||
|
||||
## GPS is the whole game
|
||||
|
||||
The receiver on this board draws 46 mA, and a mast repeater runs GPS for one
|
||||
reason only: the RTC is volatile, and a node whose clock is wrong has its
|
||||
replies dropped by clients. It does not need a continuous fix — it needs the
|
||||
clock set.
|
||||
|
||||
GPS is no longer the *only* way to get that (since 7. 8. 2026 a node starts at
|
||||
its build epoch and any attached host sets it — see `docs/cli_commands.md` under
|
||||
`time`). A reboot still throws the clock back to the build epoch: carrying it
|
||||
across one in retained RAM was tried and measured not to work, because the
|
||||
bootloader's stack owns the top of RAM. GPS is still
|
||||
what makes a mast node's clock **absolutely** right months after the flash, with
|
||||
nobody there to set it, so this reasoning stands for anything on a mast. What
|
||||
changed is that a node without GPS is no longer stuck in 2024.
|
||||
|
||||
`gps duty` (`gps_enabled == 2`, so no prefs-layout change) powers the receiver
|
||||
only around a sync, once a day (until 11/2026 every 30 minutes, the cadence
|
||||
`gps on` re-syncs at). The LF crystal is ±20 ppm plus ~40 ppm at −10 °C, so a
|
||||
day costs ~5 s of clock — far below what the mesh notices — and a reboot syncs
|
||||
at once anyway. Verified on hardware in both paths (with the old 30 min / 1 h
|
||||
timers):
|
||||
|
||||
- with sky (`mast-three`): `duty, asleep, fix, 7 sats` — got a fix, set the clock,
|
||||
cut power to the receiver;
|
||||
- without (indoors, `bench-rpt`): `awake` for exactly 300 s
|
||||
(`GPS_DUTY_MAX_AWAKE_SECS`), then `asleep` with an hourly retry, so a blocked
|
||||
sky cannot turn duty mode back into "always on".
|
||||
|
||||
Worst case (fix never obtained) still saves 42 mA; a normal 30 s fix saves 45.
|
||||
Going from 30 min to 24 h saves another 0.25–0.75 mA (hot vs. warm start, not
|
||||
measured per window), and the retry from 1 h to 6 h takes a node whose dome is
|
||||
under snow from 3.8 mA (300 s at 46 mA hourly) to 0.64 mA.
|
||||
Knobs: `GPS_DUTY_SYNC_INTERVAL_SECS` (86400), `GPS_DUTY_MAX_AWAKE_SECS` (300),
|
||||
`GPS_DUTY_RETRY_SECS` (21600).
|
||||
|
||||
Upstream later (v1.18 dev, 11/2026) added its own `gps period <s>`. It is not a
|
||||
replacement: a periodic acquisition has no timeout until the first fix ever, so
|
||||
the indoor case above would stay at 46 mA for good. `gps duty` sets the period
|
||||
to 0, and `gps on` / `gps off` leave duty mode.
|
||||
|
||||
**One visible side effect:** `querySensors()` only adds the GPS channel to
|
||||
telemetry while the receiver is powered, so a duty-cycled node reports position
|
||||
in telemetry only during its sync windows (well under 1 % of the time). What a repeater
|
||||
*advertises* is unaffected — that comes from prefs via `set advert.loc prefs` (formerly `gps advert prefs`) — and
|
||||
`node_lat/lon` keep the last fix. Confirmed in the field: `mast-three`'s scrape now
|
||||
carries `voltage/temperature/humidity` and no `gps` field.
|
||||
|
||||
## BLE: two defaults that were quietly expensive
|
||||
|
||||
- **The blinking LED.** Bluefruit drives `LED_BLUE` while advertising and holds
|
||||
it on while connected. On SenseCap Solar that pin is **12 — the same pin as
|
||||
`P_LORA_TX_LED`**, so a sealed mast node spent solar charge blinking an LED
|
||||
nobody can see, and the LoRa TX indicator lied as a bonus.
|
||||
`RPT_BLE_CONN_LED` now defaults to 0.
|
||||
- **The advertising rate.** Upstream leaves the slow interval at 244 units =
|
||||
152.5 ms, i.e. three channels ~6.5 times a second, forever.
|
||||
`RPT_BLE_ADV_SLOW` now defaults to 1600 = 1 s; the first
|
||||
`RPT_BLE_ADV_FAST_SECS` (30) after boot or disconnect stay fast so discovery
|
||||
is still immediate when someone is looking.
|
||||
|
||||
Bench boards keep both upstream behaviours (`-D RPT_BLE_CONN_LED=1`,
|
||||
`-D RPT_BLE_ADV_SLOW=244` in `xiao_analyzer`): on a desk the blinking LED is the
|
||||
"this thing is alive" indicator.
|
||||
|
||||
`ble off` remains the big BLE lever for a deployed node, but the deployment rule
|
||||
stands: ship with BLE **on**, verify the node on site, and only then turn it off
|
||||
over the mesh — otherwise a node that does not come up has no way in.
|
||||
|
||||
## RX duty cycle (rxps)
|
||||
|
||||
Ported from EasySkyMesh PowerSaving v18 behind `-D WITH_RX_POWERSAVING` (the
|
||||
public releases have it), SX1262 only, **off until set**. The radio listens in
|
||||
short windows and sleeps between them, staying awake through a packet once it
|
||||
hears a preamble; after three failed arms it falls back to continuous RX by
|
||||
itself. Commands: `docs/cli_commands.md`, `radio.rxps`.
|
||||
|
||||
Measured 12. 11. 2026 on a XIAO nRF52840 + Wio-SX1262 (not the SenseCAP of
|
||||
the rest of this page), bench preset 866.5 MHz / SF8 / BW62.5, fed at 5 V
|
||||
through an INA226 (10 mOhm) read every 5 s; the only other load was a UC96 on
|
||||
the XIAO's USB port. A/B/A/B, 15 min cells, the first 2 min of each dropped:
|
||||
|
||||
| cell | rxps | mean | median |
|
||||
|---|---|---|---|
|
||||
| 1 | off | 33.84 mA | 32.2 mA |
|
||||
| 2 | max | 31.31 mA | 30.5 mA |
|
||||
| 3 | off | 33.53 mA | 32.5 mA |
|
||||
| 4 | max | 31.36 mA | 30.3 mA |
|
||||
|
||||
`max` (level 8) against the mean of its neighbours: **-2.4 / -2.2 mA**, pooled
|
||||
-2.35 mA (medians -1.95 mA); off vs off differs by 0.3 mA, max vs max by
|
||||
0.05 mA. That is the radio's share, so it carries over to other SX1262 boards
|
||||
in absolute terms; the 33 mA base is this bench (meter, BLE advertising), not
|
||||
a node. Behind the XIAO's linear regulator the battery sees the same current:
|
||||
~7-8 mW at 3.3 V.
|
||||
|
||||
Reception: a 3-board zero-hop matrix (x1, x3, x4; rxps switched on x1 and x4,
|
||||
x3 the reference with rxps off; 20 rounds per phase, each link witnessed by
|
||||
another board), run twice -- on the development build, then repeated on the
|
||||
public release `v1.18.0+tth.20261112` (`ver` v1.18.0-tthd4afea1):
|
||||
|
||||
| phase | development build | public release | together |
|
||||
|---|---|---|---|
|
||||
| rxps off | 0/120 | 1/120 | 1/240 |
|
||||
| `on` (level 3) | 1/120 | 2/120 | 3/240 |
|
||||
| `max` (level 8) | 0/120 | 0/120 | **0/240** |
|
||||
|
||||
rxps stayed armed throughout, no error counts. Single losses happen with rxps
|
||||
off as well, and of the three at level 3 one was on x3, which had rxps off: the
|
||||
bench shows no degradation at any level. Not measured: mixed SF/preamble senders, a busy
|
||||
live mesh. On a mast, where 2 mA of ~24 is not the problem, leave it off.
|
||||
|
||||
**On the live mesh it failed (mast-three, 14. 11. 2026, `max`).** Against ob1 as
|
||||
the reference for the hour-to-hour traffic, the node received ~16 % fewer
|
||||
packets (2.08 vs 2.47 per ob1 packet) with ~30 % more `recv_errors`, and within
|
||||
two hours of switching it on it stopped transmitting altogether: `sent` frozen,
|
||||
queue full (32), no `tx_start_fail`/`tx_timeout`, RX still counting -- so no
|
||||
adverts and no replies to an admin login, for 6+ hours. `radiostat` showed
|
||||
`irq=0x0014` (preamble + header valid, no RX done). `set radio.rxps off` did
|
||||
NOT bring TX back; a reboot did. The mechanism is not proven, and the radio
|
||||
silence watchdog cannot see it (it watches RX only). Do not enable rxps on a
|
||||
node that has to answer.
|
||||
|
||||
## MCU sleep
|
||||
|
||||
`powersaving on` makes the nRF52 wait in WFE between events (it wakes on any
|
||||
interrupt, including LoRa DIO1). Upstream ships it **off**, and it was missing
|
||||
from our provisioning, so every node built from that file ran the core at 64 MHz
|
||||
around the clock. It is now in our provisioning file.
|
||||
|
||||
**But it buys about 1 mA, not the 3-4 that seemed obvious.** Measured with GPS
|
||||
held off so its sync windows could not pollute the cells: paired estimate
|
||||
-0.96 mA over three pairs, spread -1.97 to +0.07, against a measured
|
||||
cell-to-cell repeatability of 1.16 mA — i.e. the effect is the same size as this
|
||||
rig's noise and cannot be told from zero. That fits the mechanism: the loop
|
||||
still polls the SX1262 over SPI on every pass and the SoftDevice wakes the core
|
||||
for each advertising event, so there is not much idle left to sleep through.
|
||||
Keep it on (it is free and cannot hurt), but do not budget for it.
|
||||
|
||||
Blocking the loop task instead of waiting for an event (so that FreeRTOS can
|
||||
sleep tickless) changes nothing either: `delay(10)` against `sd_app_evt_wait()`,
|
||||
XIAO x4, A/B/A/B 30 min cells (14. 11. 2026): paired difference **0.04 mA**,
|
||||
cell repeatability 0.1-0.4 mA. The tick wakeups are not where the current goes.
|
||||
|
||||
One fork-specific fix goes with it: the sleep is also held off while the BLE
|
||||
console still has queued output (`bleTxPending()`), because on the observer node
|
||||
a half-drained `rxlog`/`pktlog` page would otherwise wait for the next
|
||||
connection event — the bridge drains those on a 2-minute duty cycle, so a slower
|
||||
drain directly costs collected frames.
|
||||
|
||||
## Measuring this yourself — two traps
|
||||
|
||||
1. **A solar node measured on its USB side measures the CHARGER.** With a
|
||||
charging cell the meter reads 500-700 mA, pulsing, and the node's own tens of
|
||||
mA ride on top of a drifting number. Wait for the charge to finish (it fell
|
||||
0.71 → 0.53 → 0.22 → 0.05 A over about an hour here) or the numbers are
|
||||
fiction. There is **no INA226 on this board** to cross-check with — the `i2c`
|
||||
command reports nothing at all on the only bus the variant has — on three
|
||||
separate P1-Pro units (`bench-rpt`, `mast-rpt-two`, `tth-mast-repeater-one`),
|
||||
against a sensor table that expects `38 76 70 44 5C 42 40 41 5A 29 77`. So it
|
||||
is the board, not one dead part, and the cross-check for a power measurement
|
||||
has to be a second *board*.
|
||||
2. **With `gps duty` enabled you cannot measure anything under ~5 mA.** A sync
|
||||
window lands in a random cell and adds ~17 mA to a 10-minute average (seen:
|
||||
40.9 mA against 24.1-24.5 in its neighbours). Put `gps off` in every cell of
|
||||
such a run and restore `gps duty` afterwards.
|
||||
|
||||
See `tools/power_ab.py --help` for the alternating-cell design that makes
|
||||
these deltas trustworthy in the first place.
|
||||
@@ -0,0 +1,66 @@
|
||||
# Radio Presets
|
||||
|
||||
The radio presets are currently stored on the MeshCore App API server.
|
||||
|
||||
This allows us to update the presets without releasing new application updates.
|
||||
|
||||
The presets can be fetched from [https://api.meshcore.nz/api/v1/config](https://api.meshcore.nz/api/v1/config)
|
||||
|
||||
If you'd like a new radio preset to be added, this will need to be brought up for discussion in the [MeshCore Discord](https://meshcore.gg) server, or via the [issues section](https://github.com/meshcore-dev/MeshCore/issues) in our GitHub repo.
|
||||
|
||||
Before a new preset will be considered for being added, local radio regulations must be researched by the person suggesting the preset, and investigation of the frequencies with an SDR is advised to ensure the least interference to provide a decent user experience.
|
||||
|
||||
Once a preset is added, it's unlikely to be changed. Adding too many presets can lead to user frustration, as new users won't know which preset to select during setup.
|
||||
|
||||
At this time, presets provided by the MeshCore App API are just suggestions, but you are free to configure any radio settings through the companion applications, provided they comply with local laws/regulations.
|
||||
|
||||
> Note: We are planning to implement deep linking such as meshcore:// URLs, and QR codes so local mesh networks can easily distribute their own settings, without relying on the internet, or all the companion applications to provide all the settings.
|
||||
|
||||
## JSON Response
|
||||
|
||||
See the example JSON response below, which shows the expected format provided by the API server.
|
||||
|
||||
Your application should be programmed to expect any of the JSON keys to be missing from the response, as the format could change at any time without any notification.
|
||||
|
||||
Please configure an appropriate User Agent header string when sending your request to the server. We should be able to reach out to you if needed.
|
||||
|
||||
> Note: Some presets contain an optional `network_settings` section which defines the `path_hash_size` to use for this mesh network.
|
||||
|
||||
```json
|
||||
{
|
||||
"config": {
|
||||
"suggested_radio_settings": {
|
||||
"info_message": "These presets are suggested by the community.",
|
||||
"entries": [
|
||||
{
|
||||
"title": "Australia (Narrow)",
|
||||
"description": "916.575MHz / SF7 / BW62.5 / CR7",
|
||||
"frequency": "916.575",
|
||||
"spreading_factor": "7",
|
||||
"bandwidth": "62.5",
|
||||
"coding_rate": "7"
|
||||
},
|
||||
{
|
||||
"title": "New Zealand (Narrow)",
|
||||
"description": "917.375MHz / SF7 / BW62.5 / CR5 / 2B",
|
||||
"frequency": "917.375",
|
||||
"spreading_factor": "7",
|
||||
"bandwidth": "62.5",
|
||||
"coding_rate": "5",
|
||||
"network_settings": {
|
||||
"path_hash_size": 2
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Portugal 868",
|
||||
"description": "869.618MHz / SF7 / BW62.5 / CR6",
|
||||
"frequency": "869.618",
|
||||
"spreading_factor": "7",
|
||||
"bandwidth": "62.5",
|
||||
"coding_rate": "6"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -27,15 +27,17 @@ set lon {longitude}
|
||||
```
|
||||
Sets your advertisement map longitude. (decimal degrees)
|
||||
|
||||
```
|
||||
set dutycycle {percent}
|
||||
```
|
||||
Sets the transmit duty cycle limit (1-100%). Example: `set dutycycle 10` for 10%.
|
||||
|
||||
```
|
||||
set af {air-time-factor}
|
||||
```
|
||||
Sets the transmit air-time-factor. Deprecated — use `set dutycycle` instead.
|
||||
Sets the transmit air-time-factor.
|
||||
|
||||
> **Note:** `set dutycycle` is *not* available in Terminal Chat. Every other
|
||||
> firmware — Repeater, Room Server, Sensor and Companion Radio — routes its
|
||||
> `set`/`get` commands through the shared radio prefs handler and does support
|
||||
> it (see [CLI Commands](./cli_commands.md)). Terminal Chat is the sole
|
||||
> exception: it has its own inline `set` handler covering only the six options
|
||||
> listed above.
|
||||
|
||||
|
||||
```
|
||||
@@ -99,3 +101,8 @@ Resets the path to current recipient, for new path discovery.
|
||||
public {text}
|
||||
```
|
||||
Sends the text message to the built-in 'public' group channel
|
||||
|
||||
```
|
||||
help
|
||||
```
|
||||
Lists the available commands.
|
||||
@@ -0,0 +1,197 @@
|
||||
# Console commands of this fork (meshcore-tth)
|
||||
|
||||
> [!WARNING]
|
||||
> Part of an experimental fork, not meant for regular users: its releases are
|
||||
> a rolling release on MeshCore `dev` (see the [README](../README.md)).
|
||||
|
||||
Everything this fork adds to the text console of a node, on top of upstream's
|
||||
[cli_commands.md](cli_commands.md). Where a command is described there too
|
||||
(the watchdogs, `rxps`, `batt.icon`, `gps duty`, `dfu`, `get boot`), this page
|
||||
gives the short form and points to it.
|
||||
|
||||
**Where a command exists** depends on the role and on build flags:
|
||||
|
||||
| mark | builds |
|
||||
|---|---|
|
||||
| all | repeater, room server and sensor -- every build with a text console |
|
||||
| repeater | `simple_repeater` builds |
|
||||
| observer | the `*-observer` variants of the nRF52 repeaters in the releases (`MAX_HEARD_NODES`, `RXLOG_SIZE`, `PKTFEED_SIZE`, `BLE_PIN_CODE`) |
|
||||
| own build | only with the named flag -- not in the releases |
|
||||
|
||||
**Where it can be sent from:** the USB console, the BLE console (observer
|
||||
variants) and the mesh, as admin in the remote CLI of an app -- unless the
|
||||
entry says *local only*. Replies over the mesh are cut to one packet (~150 B).
|
||||
|
||||
## Antispam (repeater)
|
||||
|
||||
Forwarding only: what this node hears, logs and feeds to an observer is never
|
||||
affected. Everything is persisted in prefs, so a reboot keeps it.
|
||||
|
||||
### FairnessLimiter -- `fairness`
|
||||
|
||||
Token buckets on forwarded floods, keyed on the 1-byte ids already in the
|
||||
clear: channel hash, sender hash, advert origin. Buckets collide (the hash is
|
||||
masked), and every key is chosen by the sender: it contains runaway floods,
|
||||
it is not security. Direct-routed traffic is never limited.
|
||||
**On after flashing** (`FAIRNESS_ENABLED_DEFAULT`).
|
||||
|
||||
| command | |
|
||||
|---|---|
|
||||
| `fairness` | state, denials per category, caps and refill intervals |
|
||||
| `fairness on\|off` | the buckets on/off |
|
||||
| `fairness cap <group> <sender> <advert>` | burst caps 0..255, `0` = build default (100 / 150 / 30) |
|
||||
| `fairness refill <group_s> <sender_s> <advert_s>` | one token per interval, seconds, `0` = default (30 / 10 / 600) |
|
||||
| `fairness grid` | the busiest denied buckets per category -- what is being shed |
|
||||
| `fairness air` | estimated airtime shed per reason |
|
||||
| `fairness advert [<hours>\|clear]` | per-origin advert window: one flood advert per origin per `<hours>` (0..720, `0` = off, default off); `clear` forgets the origins seen |
|
||||
| `fairness dryrun [on\|off]` | count every verdict but forward anyway (default off) |
|
||||
|
||||
The defaults keep about twice the headroom over 30 days of CZ mesh traffic
|
||||
(the zero-loss frontier was 60 s / cap 60 per channel, 10 s / 60 per sender,
|
||||
600 s / 12 per advert origin).
|
||||
|
||||
### Channel filter -- `filter`
|
||||
|
||||
On channels whose key the node knows (`FILTER_CHANNEL_PSKS`; the releases
|
||||
know Public, `#meshcore` and `#test`) the node decrypts each group text and
|
||||
refuses to forward listed senders. The sender name is plain text in the
|
||||
message: anyone can rename around it.
|
||||
|
||||
| command | |
|
||||
|---|---|
|
||||
| `filter` / `filter list` | channels known, drops, the deny list |
|
||||
| `filter add <name>` / `filter del <name>` | exact, case-insensitive; spaces allowed, commas not |
|
||||
| `filter clear` | empty the list |
|
||||
|
||||
### Channel-hash deny-forward -- `filter hash` (every repeater)
|
||||
|
||||
Keyless: the first byte of a group packet is the channel hash, in the clear,
|
||||
so this works on private channels too. One byte is coarse -- every other
|
||||
channel whose key hashes to the same byte is hit as well; check what else
|
||||
lives on it before adding one.
|
||||
|
||||
| command | |
|
||||
|---|---|
|
||||
| `filter hash` | drops, passes by a throttle, the list (`43` blocked, `43/60` throttled) |
|
||||
| `filter hash add <hex> [secs]` | block the byte, or let one packet through per `secs` (1..65535); re-adding changes the interval |
|
||||
| `filter hash del <hex>` / `filter hash clear` | |
|
||||
|
||||
A throttle's window lives in RAM: the first match after a boot passes.
|
||||
|
||||
### Message age -- `filter age` (repeater with channel keys)
|
||||
|
||||
`filter age <min>|off` (1..10080, default off): do not forward a group text
|
||||
on a decrypted channel whose sender timestamp is older than `<min>` by this
|
||||
node's clock. It judges the sender's clock, so a companion that never got a
|
||||
time sync (it stamps 2024) is dropped too -- keep it in days. Inactive while
|
||||
the node's own clock reads before 2026; a clock running ahead makes
|
||||
everything look old.
|
||||
|
||||
### `filter dryrun [on|off]`
|
||||
|
||||
Count every `filter` verdict (sender, hash, age) but forward anyway -- try a
|
||||
rule on a live node before it bites. Default off.
|
||||
|
||||
## Radio watchdogs and board upkeep (all)
|
||||
|
||||
Details: [cli_commands.md](cli_commands.md), "Radio silence watchdog", "TX
|
||||
stall watchdog", "Reboot into the bootloader" and "Why the board last reset".
|
||||
|
||||
| command | |
|
||||
|---|---|
|
||||
| `set radio.silence <min>\|off` / `get radio.silence` | deaf receiver: re-arm RX, then reboot after `<min>` without a received frame (CRC errors count as heard); each such reboot doubles the threshold for the next boot (up to 16x), the first frame clears it. 1..1440, persisted, **default off** |
|
||||
| `set radio.txstall <min>\|off` / `get radio.txstall` | repeater only: packets queued and nothing sent for `<min>` -> re-arm, then reboot. An empty queue never counts. **On, 15 min** (`RADIO_TXSTALL_MIN`); a change holds until reboot |
|
||||
| `get radio.reboots` | reboots done by the watchdogs, survives power loss |
|
||||
| `get boot` | reset reason and the hardfault record (also printed at boot) |
|
||||
| `dfu [uf2\|serial\|ota]` | *local only*: reboot into the bootloader -- UF2 drive (default), CDC port for `adafruit-nrfutil`, or BLE DFU |
|
||||
| `fw ...` | `-ota` images only: admin-pushed firmware update, see [ota.md](ota.md) |
|
||||
|
||||
## Diagnostics
|
||||
|
||||
| command | where | |
|
||||
|---|---|---|
|
||||
| `blink [n]` / `blink on\|off` | repeater | flash a spare LED (not the BLE or TX one) `n` times (default 6, max 999), or until `blink off` (gives up after 10 min); finds a board on a bench or a node on a mast |
|
||||
| `txpwr [dBm]` | repeater | LoRa output power until reboot, with RadioLib's status (`set tx` saves and says OK even when the radio refused) |
|
||||
| `i2c` | all | scan the I2C bus |
|
||||
| `get chip` | nRF52 (repeater, room server, sensor) | the silicon (`nRF52840 AAD0`; variant `xxF0` and later = rev3) and `UICR.APPROTECT`: `open` means SWD can read the whole flash, keys included ([locked-bootloader.md](locked-bootloader.md)) |
|
||||
| `dio1` | own build: `PIN_DIAG` | has the SX1262 raise TX_DONE and compares its IRQ register with the level on the DIO1 pin -- which end of a dead IRQ line is broken |
|
||||
| `radiostat` | own build: `RADIO_DIAG` | receiver state, interrupt and RX counters, without touching the radio |
|
||||
| `radiokick rx\|clrirq\|standby\|agc` | own build: `RADIO_DIAG` | one recovery step, gentlest first: re-arm RX, clear latched IRQs, standby + RX, AGC reset; the first that brings `recv` back names the broken layer |
|
||||
|
||||
A board with a dead DIO1 line still runs with `LORA_POLL_IRQ` (own build):
|
||||
the IRQ status is polled over SPI.
|
||||
|
||||
## BLE console (observer)
|
||||
|
||||
The text console over BLE (Nordic UART), next to USB. No login of its own:
|
||||
the BLE PIN is the only lock, and the release PIN is the public placeholder
|
||||
`123456`. These commands also work as admin over the mesh.
|
||||
|
||||
| command | |
|
||||
|---|---|
|
||||
| `ble` | on/off, PIN `own` or `build default` -- never the PIN itself |
|
||||
| `ble pin <6 digits>` | set your own PIN (saved, survives a reflash; drops every bond, so paired devices pair again) |
|
||||
| `ble on\|off` | persisted; **off after flashing** (`RPT_BLE_DEFAULT_OFF`), and `ble on` is refused while the PIN is the placeholder |
|
||||
| `blepwr [dBm\|default]` | TX power of the connection (-40, -20, -16, -12, -8, -4, 0, 2..8), applied to live connections and saved; `default` returns to the build value (0 dBm) |
|
||||
| `bleconn` | what the central actually agreed to: interval (and what was requested), latency, supervision timeout |
|
||||
|
||||
A connected central stops the node advertising: if the BLE console cannot be
|
||||
found, look for who is connected (`ble` shows it).
|
||||
|
||||
## Passive analyzer (observer)
|
||||
|
||||
| command | |
|
||||
|---|---|
|
||||
| `nodes [offset]` | heard repeaters and room servers with a key to join several paths, paged |
|
||||
| `rxlog [cursor]` | every frame heard: type, path, SNR, RSSI; `cursor` from the previous page (`0` = all) |
|
||||
| `pktlog [cursor]` | raw frames heard, for an observer feed ([meshcore-repeater-observer](https://git.rfa.cz/tth-pub/meshcore-repeater-observer)) |
|
||||
|
||||
A page is as big as the caller's reply buffer: ~1000 B on the local console,
|
||||
one packet over the mesh.
|
||||
|
||||
## Channel bot (own build: `BOT_CHANNEL_PSK`)
|
||||
|
||||
A repeater that answers on one channel without forwarding anything:
|
||||
`!link`, `!path`, `!snr`, `!heard`, `!noise`, `!ping`, `!help` (narrowed by
|
||||
`BOT_COMMANDS`), with a per-sender cooldown and an ignore list. `bot` on the
|
||||
console shows its state.
|
||||
|
||||
## Power and clock
|
||||
|
||||
| command | where | |
|
||||
|---|---|---|
|
||||
| `set radio.rxps off\|on\|balanced\|max`, `level <1-10> [preamble 16\|32]` / `get radio.rxps` | all, SX1262 only (`WITH_RX_POWERSAVING`, in the releases) | RX duty cycle: the radio sleeps between short listening windows. **Off by default.** `max` saved ~2.3 mA on the bench, but a mast on the live mesh lost 16 % of its reception -- see cli_commands.md and [power.md](power.md) |
|
||||
| `set batt.icon on\|off`, `set batt.icon.lo\|hi <mV>` | all | battery level as an icon at the end of the advertised name (off by default; with a name too long for it the icon is left out, and the reply says so) |
|
||||
| `gps duty ...` | GPS boards | the receiver runs only around a clock sync; see cli_commands.md |
|
||||
| `clkreboot` | all | reset the clock to the build epoch and reboot -- the only way to move a clock backwards (`time` and `clock sync` refuse to) |
|
||||
|
||||
## Sensors
|
||||
|
||||
| command | |
|
||||
|---|---|
|
||||
| `sensor read` | the live telemetry decoded into one line (`sensor list` shows only settings) |
|
||||
| `sensor set ina.shunt <mOhm>` | shunt resistance of an INA219/226/260/3221, saved across reboots |
|
||||
|
||||
## Build flags
|
||||
|
||||
The ones that change what a node does; set in `platformio.ini` /
|
||||
`platformio.local.ini` (`-D NAME=value`, the last `-D` wins).
|
||||
|
||||
| flag | default | |
|
||||
|---|---|---|
|
||||
| `FAIRNESS_ENABLED_DEFAULT` | `1` | FairnessLimiter on for a node without prefs |
|
||||
| `RADIO_SILENCE_MIN_DEFAULT` | `0` | deaf-receiver watchdog for a node without prefs |
|
||||
| `RADIO_TXSTALL_MIN` | `15` | TX stall watchdog at boot (repeater), `0` = off |
|
||||
| `FILTER_CHANNEL_PSKS` | releases: Public, `#meshcore`, `#test` | channel keys the filter can decrypt |
|
||||
| `MAX_HEARD_NODES`, `RXLOG_SIZE`, `PKTFEED_SIZE` | `0` (observer variants: 128 / 512 / 64) | the analyzer rings |
|
||||
| `BLE_PIN_CODE`, `RPT_BLE_DEFAULT_OFF` | observer variants | BLE console, starting off |
|
||||
| `BOT_CHANNEL_PSK`, `BOT_COMMANDS` | unset | channel bot |
|
||||
| `RADIO_DIAG`, `PIN_DIAG`, `LORA_POLL_IRQ` | unset | radio diagnostics, DIO1-less operation |
|
||||
| `FW_OTA` | `-ota` images | admin-pushed firmware update |
|
||||
| `PATH_HASH_MODE_DEFAULT` | `1` (2 B per hop) | path hash width for a node without prefs |
|
||||
| `ACL_TS_MAX_AHEAD` | `86400` (s) | a client timestamp further ahead of the node's clock is not stored as the replay floor |
|
||||
| `LOCKED_NODE` | unset | a node that keeps its secrets from whoever holds it: `get prv.key`, `get guest.password` and `get bridge.secret` answer `Error: locked build` to everyone (USB and BLE console, an admin over the mesh); a companion serves only paired BLE (USB, UART and WiFi get the device info and nothing else) and its rescue CLI refuses `set pin`. Only half of it: [locked-bootloader.md](locked-bootloader.md) |
|
||||
| `LOGIN_FAIL_MAX`, `LOGIN_FAIL_SECS` | `4`, `180` (s) | after that many wrong passwords in the window no password is checked until it ends (an admin already in the ACL always gets in) |
|
||||
|
||||
Prefs saved on the node override the build defaults: a reflash keeps what a
|
||||
node already has; only a new node or one after `erase` takes them.
|
||||
@@ -265,6 +265,12 @@ File file = openRead(_getContactsChannelsFS(), "/contacts3");
|
||||
uint8_t pub_key[32];
|
||||
uint8_t unused;
|
||||
|
||||
// The on-disk record has no shared_secret/shared_secret_valid, so those
|
||||
// two members are never written by the reads below. Left indeterminate,
|
||||
// a non-zero shared_secret_valid makes getSharedSecret() return an
|
||||
// uninitialised secret for a contact loaded at boot.
|
||||
memset(&c, 0, sizeof(c));
|
||||
|
||||
bool success = (file.read(pub_key, 32) == 32);
|
||||
success = success && (file.read((uint8_t *)&c.name, 32) == 32);
|
||||
success = success && (file.read(&c.type, 1) == 1);
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
#include <helpers/IdentityStore.h>
|
||||
#include <helpers/ContactInfo.h>
|
||||
#include <helpers/ChannelDetails.h>
|
||||
#include "NodePrefs.h"
|
||||
#include <helpers/CompanionNodePrefs.h>
|
||||
|
||||
class DataStoreHost {
|
||||
public:
|
||||
|
||||
+568
-139
File diff suppressed because it is too large.
Load diff
@@ -2,17 +2,16 @@
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <Mesh.h>
|
||||
#include "AbstractUITask.h"
|
||||
|
||||
/*------------ Frame Protocol --------------*/
|
||||
#define FIRMWARE_VER_CODE 13
|
||||
#define FIRMWARE_VER_CODE 14
|
||||
|
||||
#ifndef FIRMWARE_BUILD_DATE
|
||||
#define FIRMWARE_BUILD_DATE "14 Aug 2026"
|
||||
#define FIRMWARE_BUILD_DATE "15 Oct 2026"
|
||||
#endif
|
||||
|
||||
#ifndef FIRMWARE_VERSION
|
||||
#define FIRMWARE_VERSION "v1.17.1"
|
||||
#define FIRMWARE_VERSION "v1.18.0"
|
||||
#endif
|
||||
|
||||
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
|
||||
@@ -24,7 +23,7 @@
|
||||
#endif
|
||||
|
||||
#include "DataStore.h"
|
||||
#include "NodePrefs.h"
|
||||
#include <helpers/CompanionNodePrefs.h>
|
||||
|
||||
#include <RTClib.h>
|
||||
#include <helpers/ArduinoHelpers.h>
|
||||
@@ -69,6 +68,7 @@
|
||||
|
||||
#include <helpers/BaseChatMesh.h>
|
||||
#include <helpers/TransportKeyStore.h>
|
||||
#include <helpers/MeshEventListener.h>
|
||||
|
||||
/* -------------------------------------------------------------------------------------- */
|
||||
|
||||
@@ -86,26 +86,35 @@ struct AdvertPath {
|
||||
|
||||
class MyMesh : public BaseChatMesh, public DataStoreHost {
|
||||
public:
|
||||
MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMeshTables &tables, DataStore& store, AbstractUITask* ui=NULL);
|
||||
MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMeshTables &tables, DataStore& store);
|
||||
|
||||
void begin(bool has_display);
|
||||
void begin();
|
||||
void startInterface(BaseSerialInterface &serial);
|
||||
void setListener(MeshEventListener* listener) { _listener = listener; }
|
||||
|
||||
const char *getNodeName();
|
||||
NodePrefs *getNodePrefs();
|
||||
uint32_t getBLEPin();
|
||||
void setBLEPin(uint32_t active_pin);
|
||||
|
||||
void loop();
|
||||
void handleCmdFrame(size_t len);
|
||||
bool advert();
|
||||
void enterCLIRescue();
|
||||
|
||||
int getRecentlyHeard(AdvertPath dest[], int max_num);
|
||||
void enterCLIRescue() override;
|
||||
void savePrefs() override {
|
||||
_prefs.node_lat = sensors.node_lat;
|
||||
_prefs.node_lon = sensors.node_lon;
|
||||
_store->savePrefs(_prefs);
|
||||
_prefs.clearDirty();
|
||||
}
|
||||
|
||||
protected:
|
||||
float getAirtimeBudgetFactor() const override;
|
||||
int getInterferenceThreshold() const override;
|
||||
bool getCADEnabled() const override;
|
||||
int getAGCResetInterval() const override {
|
||||
return ((int)_prefs.agc_reset_interval) * 4000; // milliseconds
|
||||
}
|
||||
int calcRxDelay(float score, uint32_t air_time) const override;
|
||||
uint32_t getRetransmitDelay(const mesh::Packet *packet) override;
|
||||
uint32_t getDirectRetransmitDelay(const mesh::Packet *packet) override;
|
||||
@@ -113,6 +122,11 @@ protected:
|
||||
bool filterRecvFloodPacket(mesh::Packet* packet) override;
|
||||
bool allowPacketForward(const mesh::Packet* packet) override;
|
||||
|
||||
// Šířku path hashe volí ODESÍLATEL, takže musí přijít z prefs tohohle uzlu.
|
||||
// Díky tomuhle overridu ji dostanou i volání send*(), která ji nepředávají
|
||||
// explicitně (ACKy, PATH-return, zerohop odpovědi sousedovi).
|
||||
uint8_t getSelfPathHashSize() const override { return _prefs.path_hash_mode + 1; }
|
||||
|
||||
void sendFloodScoped(const TransportKey& scope, mesh::Packet* pkt, uint32_t delay_millis);
|
||||
void sendFloodScoped(const ContactInfo& recipient, mesh::Packet* pkt, uint32_t delay_millis=0) override;
|
||||
void sendFloodScoped(const mesh::GroupChannel& channel, mesh::Packet* pkt, uint32_t delay_millis=0) override;
|
||||
@@ -135,6 +149,8 @@ protected:
|
||||
const char *text) override;
|
||||
void onCommandDataRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp,
|
||||
const char *text) override;
|
||||
void onCLICommandRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp,
|
||||
const char *text, char* reply) override;
|
||||
void onSignedMessageRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp,
|
||||
const uint8_t *sender_prefix, const char *text) override;
|
||||
void onChannelMessageRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint32_t timestamp,
|
||||
@@ -165,20 +181,18 @@ protected:
|
||||
}
|
||||
|
||||
public:
|
||||
void savePrefs() {
|
||||
_prefs.node_lat = sensors.node_lat;
|
||||
_prefs.node_lon = sensors.node_lon;
|
||||
_store->savePrefs(_prefs);
|
||||
}
|
||||
|
||||
#if ENV_INCLUDE_GPS == 1
|
||||
void applyGpsPrefs() {
|
||||
sensors.setSettingValue("gps", _prefs.gps_enabled ? "1" : "0");
|
||||
if (_prefs.gps_interval > 0) {
|
||||
char interval_str[12]; // Max: 24 hours = 86400 seconds (5 digits + null)
|
||||
sprintf(interval_str, "%u", _prefs.gps_interval);
|
||||
sensors.setSettingValue("gps_interval", interval_str);
|
||||
if (_prefs.gps_interval > 0 &&
|
||||
sensors.getSettingByKey("gps_interval") != nullptr) {
|
||||
char interval[11];
|
||||
snprintf(interval, sizeof(interval), "%lu", (unsigned long)_prefs.gps_interval);
|
||||
sensors.setSettingValue("gps_interval", interval);
|
||||
}
|
||||
_prefs.getGpsPrefs()->apply(sensors);
|
||||
// 2 = duty cycle (see EnvironmentSensorManager::gpsDutyLoop); apply() only
|
||||
// knows on/off, so switch the sensor manager into duty after it
|
||||
if (_prefs.gps_enabled == 2) sensors.setSettingValue("gps", "2");
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -201,6 +215,7 @@ private:
|
||||
}
|
||||
|
||||
void checkCLIRescueCmd();
|
||||
bool handleCommand(const char* text, uint32_t sender_timestamp, char* reply);
|
||||
void checkSerialInterface();
|
||||
bool isValidClientRepeatFreq(uint32_t f) const;
|
||||
|
||||
@@ -215,7 +230,7 @@ private:
|
||||
uint32_t pending_telemetry, pending_discovery; // pending _TELEMETRY_REQ
|
||||
uint32_t pending_req; // pending _BINARY_REQ
|
||||
BaseSerialInterface *_serial;
|
||||
AbstractUITask* _ui;
|
||||
MeshEventListener* _listener;
|
||||
|
||||
ContactsIterator _iter;
|
||||
uint32_t _iter_filter_since;
|
||||
@@ -225,6 +240,7 @@ private:
|
||||
bool _cli_rescue;
|
||||
bool send_unscoped; // force un-scoped flood (instead of using send_scope)
|
||||
char cli_command[80];
|
||||
char reply_buf[166];
|
||||
uint8_t app_target_ver;
|
||||
uint8_t *sign_data;
|
||||
uint32_t sign_data_len;
|
||||
|
||||
@@ -1,145 +0,0 @@
|
||||
#pragma once
|
||||
#include <cstdint> // For uint8_t, uint32_t
|
||||
#include <helpers/ConfigSerializer.h>
|
||||
|
||||
#define TELEM_MODE_DENY 0
|
||||
#define TELEM_MODE_ALLOW_FLAGS 1 // use contact.flags
|
||||
#define TELEM_MODE_ALLOW_ALL 2
|
||||
|
||||
#define ADVERT_LOC_NONE 0
|
||||
#define ADVERT_LOC_SHARE 1
|
||||
|
||||
class NodePrefs : public ConfigSerializer { // persisted to file
|
||||
public:
|
||||
float airtime_factor = 0;
|
||||
char node_name[32];
|
||||
double node_lat = 0, node_lon = 0;
|
||||
float freq = 0;
|
||||
uint8_t sf = 0;
|
||||
uint8_t cr = 0;
|
||||
uint8_t multi_acks = 0;
|
||||
uint8_t manual_add_contacts = 0;
|
||||
float bw = 0;
|
||||
int8_t tx_power_dbm = 0;
|
||||
uint8_t telemetry_mode_base = 0;
|
||||
uint8_t telemetry_mode_loc = 0;
|
||||
uint8_t telemetry_mode_env = 0;
|
||||
float rx_delay_base = 0;
|
||||
uint32_t ble_pin = 0;
|
||||
uint8_t advert_loc_policy = 0;
|
||||
uint8_t buzzer_quiet = 0;
|
||||
uint8_t vibe_quiet = 0;
|
||||
uint8_t gps_enabled = 0; // GPS enabled flag (0=disabled, 1=enabled)
|
||||
uint32_t gps_interval = 0; // GPS read interval in seconds
|
||||
uint8_t autoadd_config = 0; // bitmask for auto-add contacts config
|
||||
uint8_t rx_boosted_gain = 0; // SX126x RX boosted gain mode (0=power saving, 1=boosted)
|
||||
uint8_t radio_fem_rxgain = 0; // external LoRa FEM RX gain (LNA)
|
||||
uint8_t radio_fem_txgain = 0; // external LoRa FEM TX gain (low by default)
|
||||
uint8_t _client_repeat = 0; // DEPRECATED -> use repeat.disable_fwd
|
||||
uint8_t path_hash_mode = 0; // which path mode to use when sending
|
||||
uint8_t autoadd_max_hops = 0; // 0 = no limit, 1 = direct (0 hops), N = up to N-1 hops (max 64)
|
||||
char default_scope_name[31];
|
||||
uint8_t default_scope_key[16];
|
||||
|
||||
private:
|
||||
class RadioPrefs : public ConfigSerializer { // COPIED from CommonCLI (for now)
|
||||
NodePrefs* _parent;
|
||||
protected:
|
||||
void structure() override {
|
||||
def("freq", _parent->freq);
|
||||
def("bw", _parent->bw);
|
||||
def("sf", _parent->sf);
|
||||
def("cr", _parent->cr);
|
||||
//def("cad", _parent->cad_enabled);
|
||||
//def("int_thr", _parent->interference_threshold);
|
||||
def("rxgain", _parent->rx_boosted_gain);
|
||||
#if 0
|
||||
// NOTE: these cannot be set (yet) so don't load/save until we can.
|
||||
// also, fem_rxgain WAS mapped to wrong JSON property previously
|
||||
def("fem_rxgain", _parent->radio_fem_rxgain);
|
||||
def("fem_txgain", _parent->radio_fem_txgain);
|
||||
#endif
|
||||
def("tx", _parent->tx_power_dbm);
|
||||
def("af", _parent->airtime_factor);
|
||||
def("rxdelay", _parent->rx_delay_base);
|
||||
//def("f_txdelay", _parent->tx_delay_factor); currently hard-coded
|
||||
//def("d_txdelay", _parent->direct_tx_delay_factor); currently hard-coded
|
||||
//def("agc_int", _parent->agc_reset_interval);
|
||||
def("hash_mode", _parent->path_hash_mode);
|
||||
def("multi_ack", _parent->multi_acks);
|
||||
}
|
||||
public:
|
||||
RadioPrefs(NodePrefs* parent) : _parent(parent) { }
|
||||
};
|
||||
RadioPrefs radio;
|
||||
|
||||
class GPSPrefs : public ConfigSerializer { // COPIED from CommonCLI (for now)
|
||||
NodePrefs* _parent;
|
||||
protected:
|
||||
void structure() override {
|
||||
def("en", _parent->gps_enabled); // boolean
|
||||
def("int", _parent->gps_interval); // interval in seconds
|
||||
def("adv_loc", _parent->advert_loc_policy);
|
||||
}
|
||||
public:
|
||||
GPSPrefs(NodePrefs* parent) : _parent(parent) { }
|
||||
};
|
||||
GPSPrefs gps;
|
||||
|
||||
class RepeatPrefs : public ConfigSerializer { // COPIED from CommonCLI (for now)
|
||||
public:
|
||||
uint8_t disable_fwd = 1;
|
||||
protected:
|
||||
void structure() override {
|
||||
def("disable", disable_fwd);
|
||||
//def("f_max", flood_max);
|
||||
//def("f_max_uns", flood_max_unscoped);
|
||||
//def("f_max_adv", flood_max_advert);
|
||||
//def("loop", loop_detect);
|
||||
}
|
||||
};
|
||||
RepeatPrefs repeat;
|
||||
|
||||
class CompanionPrefs : public ConfigSerializer {
|
||||
NodePrefs* _parent;
|
||||
protected:
|
||||
void structure() override {
|
||||
def("auto_max", _parent->autoadd_max_hops); // 0 = no limit, 1 = direct (0 hops), N = up to N-1 hops (max 64)
|
||||
def("defs_nm", _parent->default_scope_name, sizeof(_parent->default_scope_name));
|
||||
def("defs_key", (void *) _parent->default_scope_key, sizeof(_parent->default_scope_key));
|
||||
def("pin", _parent->ble_pin);
|
||||
def("buzz_q", _parent->buzzer_quiet);
|
||||
def("vibe_q", _parent->vibe_quiet);
|
||||
def("auto_add", _parent->autoadd_config); // bitmask for auto-add contacts config
|
||||
def("man_add", _parent->manual_add_contacts);
|
||||
def("tel_base", _parent->telemetry_mode_base);
|
||||
def("tel_loc", _parent->telemetry_mode_loc);
|
||||
def("tel_env", _parent->telemetry_mode_env);
|
||||
}
|
||||
public:
|
||||
CompanionPrefs(NodePrefs* parent) : _parent(parent) { }
|
||||
};
|
||||
CompanionPrefs companion;
|
||||
|
||||
protected:
|
||||
void structure() override {
|
||||
def("name", node_name, sizeof(node_name));
|
||||
//def("adv_int", advert_interval);
|
||||
//def("f_adv_int", flood_advert_interval);
|
||||
def("lat", node_lat);
|
||||
def("lon", node_lon);
|
||||
def("radio", radio);
|
||||
def("gps", gps);
|
||||
def("repeat", repeat);
|
||||
def("comp", companion);
|
||||
}
|
||||
public:
|
||||
NodePrefs() : radio(this), gps(this), companion(this) {
|
||||
node_name[0] = 0;
|
||||
default_scope_name[0] = 0;
|
||||
memset(default_scope_key, 0, sizeof(default_scope_key));
|
||||
}
|
||||
// new accessor methods
|
||||
bool isRepeatEn() const { return repeat.disable_fwd == 0; }
|
||||
void setRepeatEn(bool en) { repeat.disable_fwd = en ? 0 : 1; }
|
||||
};
|
||||
@@ -2,6 +2,11 @@
|
||||
#include <Mesh.h>
|
||||
#include "MyMesh.h"
|
||||
|
||||
#if defined(ENABLE_WIFI_INTERFACE) && defined(ENABLE_ESP_MDNS)
|
||||
#define HAS_ESP_MDNS
|
||||
#include <ESPmDNS.h>
|
||||
#endif
|
||||
|
||||
// Believe it or not, this std C function is busted on some platforms!
|
||||
static uint32_t _atoi(const char* sp) {
|
||||
uint32_t n = 0;
|
||||
@@ -26,19 +31,38 @@ MultiSerialInterface interface_manager;
|
||||
// include nrf52 bluetooth interface
|
||||
#include <helpers/nrf52/SerialBLEInterface.h>
|
||||
SerialBLEInterface bluetooth_interface;
|
||||
#elif defined(RP2040_PLATFORM)
|
||||
// include rp2040 (Pico W / CYW43) bluetooth interface
|
||||
#include <helpers/rp2040/SerialBLEInterface.h>
|
||||
SerialBLEInterface bluetooth_interface;
|
||||
#else
|
||||
#error "SerialBLEInterface is not defined for this platform"
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// include wifi interface
|
||||
#ifdef WIFI_SSID
|
||||
#ifdef ENABLE_WIFI_INTERFACE
|
||||
#ifndef WIFI_SSID
|
||||
#define WIFI_SSID ""
|
||||
#endif
|
||||
#ifndef WIFI_PWD
|
||||
#define WIFI_PWD ""
|
||||
#endif
|
||||
#ifndef TCP_PORT
|
||||
#define TCP_PORT 5000
|
||||
#endif
|
||||
#ifdef ESP32
|
||||
// include esp32 wifi interface
|
||||
#include <helpers/esp32/SerialWifiInterface.h>
|
||||
#ifndef WIFI_RETRY_INTERVAL
|
||||
#if defined(RP2040_PLATFORM)
|
||||
#define WIFI_RETRY_INTERVAL 30000 // each attempt blocks loop(), so retry less often
|
||||
#else
|
||||
#define WIFI_RETRY_INTERVAL 10000 // millis between reconnect attempts
|
||||
#endif
|
||||
#endif
|
||||
#ifndef WIFI_RETRY_TIMEOUT
|
||||
#define WIFI_RETRY_TIMEOUT 5000 // RP2040: cap on how long one join may block loop()
|
||||
#endif
|
||||
#if defined(ESP32) || defined(RP2040_PLATFORM)
|
||||
#include <helpers/wifi/SerialWifiInterface.h>
|
||||
SerialWifiInterface wifi_interface;
|
||||
#else
|
||||
#error "SerialWifiInterface is not defined for this platform"
|
||||
@@ -88,18 +112,9 @@ MultiSerialInterface interface_manager;
|
||||
#endif
|
||||
|
||||
/* GLOBAL OBJECTS */
|
||||
#ifdef DISPLAY_CLASS
|
||||
#include "UITask.h"
|
||||
UITask ui_task(&board, &interface_manager);
|
||||
#endif
|
||||
|
||||
StdRNG fast_rng;
|
||||
SimpleMeshTables tables;
|
||||
MyMesh the_mesh(radio_driver, fast_rng, rtc_clock, tables, store
|
||||
#ifdef DISPLAY_CLASS
|
||||
, &ui_task
|
||||
#endif
|
||||
);
|
||||
MyMesh the_mesh(radio_driver, fast_rng, rtc_clock, tables, store);
|
||||
|
||||
/* END GLOBAL OBJECTS */
|
||||
|
||||
@@ -108,9 +123,17 @@ void halt() {
|
||||
}
|
||||
|
||||
/* WIFI RECONNECT TRACKERS */
|
||||
#if defined(ESP32) && defined(WIFI_SSID)
|
||||
#ifdef ENABLE_WIFI_INTERFACE
|
||||
bool wifi_needs_reconnect = false;
|
||||
unsigned long last_wifi_reconnect_attempt = 0;
|
||||
char wifi_ssid[33] = WIFI_SSID; // replaced by stored prefs at boot, if set
|
||||
char wifi_pwd[64] = WIFI_PWD;
|
||||
bool wifi_was_connected = false;
|
||||
bool wifi_enabled = false; // set at boot from prefs; false also when the effective SSID is blank
|
||||
#endif
|
||||
|
||||
#if defined(DISPLAY_CLASS) && defined(EINK_REFRESH_LOOP)
|
||||
static void loopDuringDisplayRefresh();
|
||||
#endif
|
||||
|
||||
void setup() {
|
||||
@@ -153,61 +176,92 @@ void setup() {
|
||||
#endif
|
||||
#endif
|
||||
store.begin();
|
||||
the_mesh.begin(
|
||||
#ifdef DISPLAY_CLASS
|
||||
disp != NULL
|
||||
#else
|
||||
false
|
||||
#endif
|
||||
);
|
||||
the_mesh.begin();
|
||||
#elif defined(RP2040_PLATFORM)
|
||||
LittleFS.begin();
|
||||
store.begin();
|
||||
the_mesh.begin(
|
||||
#ifdef DISPLAY_CLASS
|
||||
disp != NULL
|
||||
#else
|
||||
false
|
||||
#endif
|
||||
);
|
||||
the_mesh.begin();
|
||||
#elif defined(ESP32)
|
||||
SPIFFS.begin(true);
|
||||
store.begin();
|
||||
the_mesh.begin(
|
||||
#ifdef DISPLAY_CLASS
|
||||
disp != NULL
|
||||
#else
|
||||
false
|
||||
#endif
|
||||
);
|
||||
the_mesh.begin();
|
||||
#else
|
||||
#error "need to define filesystem"
|
||||
#endif
|
||||
|
||||
#ifdef BLE_PIN_CODE // 123456 by default
|
||||
if (the_mesh.getNodePrefs()->ble_pin == 0) {
|
||||
#ifdef DISPLAY_CLASS
|
||||
if (disp != NULL && BLE_PIN_CODE == 123456) {
|
||||
StdRNG rng;
|
||||
the_mesh.setBLEPin(rng.nextInt(100000, 999999)); // random pin each session
|
||||
} else {
|
||||
the_mesh.setBLEPin(BLE_PIN_CODE); // otherwise static pin
|
||||
}
|
||||
#else
|
||||
the_mesh.setBLEPin(BLE_PIN_CODE); // otherwise static pin
|
||||
#endif
|
||||
} else {
|
||||
the_mesh.setBLEPin(the_mesh.getNodePrefs()->ble_pin);
|
||||
}
|
||||
#else
|
||||
the_mesh.setBLEPin(0);
|
||||
#endif
|
||||
|
||||
// add bluetooth interface
|
||||
#if defined(BLE_PIN_CODE)
|
||||
bluetooth_interface.begin(BLE_NAME_PREFIX, the_mesh.getNodePrefs()->node_name, the_mesh.getBLEPin());
|
||||
char *prefix = BLE_NAME_PREFIX;
|
||||
char *ble_name = the_mesh.getNodePrefs()->node_name;
|
||||
if (the_mesh.getNodePrefs()->ble_name[0]) {
|
||||
prefix = "";
|
||||
ble_name = the_mesh.getNodePrefs()->ble_name;
|
||||
}
|
||||
bluetooth_interface.begin((const char *) prefix, ble_name, the_mesh.getBLEPin());
|
||||
interface_manager.addInterface(InterfaceType::Bluetooth, &bluetooth_interface);
|
||||
#endif
|
||||
|
||||
// add wifi interface
|
||||
#ifdef WIFI_SSID
|
||||
board.setInhibitSleep(true); // prevent sleep when WiFi is active
|
||||
WiFi.setAutoReconnect(true);
|
||||
#ifdef ENABLE_WIFI_INTERFACE
|
||||
// use wifi ssid and password from prefs if ssid is not empty, otherwise use the build flag defaults
|
||||
if (the_mesh.getNodePrefs()->wifi_ssid[0]) {
|
||||
strcpy(wifi_ssid, the_mesh.getNodePrefs()->wifi_ssid);
|
||||
strcpy(wifi_pwd, the_mesh.getNodePrefs()->wifi_pwd);
|
||||
}
|
||||
// only start wifi if enabled and ssid is not empty
|
||||
wifi_enabled = the_mesh.getNodePrefs()->wifi_enabled;
|
||||
if (wifi_enabled && wifi_ssid[0]) {
|
||||
#if defined(ESP32)
|
||||
board.setInhibitSleep(true); // prevent sleep when WiFi is active
|
||||
WiFi.setAutoReconnect(true);
|
||||
|
||||
WiFi.onEvent([](WiFiEvent_t event, WiFiEventInfo_t info){
|
||||
if (event == ARDUINO_EVENT_WIFI_STA_DISCONNECTED) {
|
||||
WIFI_DEBUG_PRINTLN("WiFi disconnected. Flagging for reconnect...");
|
||||
wifi_needs_reconnect = true;
|
||||
} else if (event == ARDUINO_EVENT_WIFI_STA_GOT_IP) {
|
||||
WIFI_DEBUG_PRINTLN("WiFi connected successfully!");
|
||||
wifi_needs_reconnect = false;
|
||||
}
|
||||
});
|
||||
WiFi.onEvent([](WiFiEvent_t event, WiFiEventInfo_t info){
|
||||
if (event == ARDUINO_EVENT_WIFI_STA_DISCONNECTED) {
|
||||
WIFI_DEBUG_PRINTLN("WiFi disconnected (reason=%s). Flagging for reconnect...",
|
||||
WiFi.disconnectReasonName((wifi_err_reason_t)info.wifi_sta_disconnected.reason));
|
||||
wifi_needs_reconnect = true;
|
||||
} else if (event == ARDUINO_EVENT_WIFI_STA_GOT_IP) {
|
||||
WIFI_DEBUG_PRINTLN("WiFi connected successfully!");
|
||||
wifi_needs_reconnect = false;
|
||||
}
|
||||
});
|
||||
#endif
|
||||
|
||||
WiFi.begin(WIFI_SSID, WIFI_PWD);
|
||||
wifi_interface.begin(TCP_PORT);
|
||||
interface_manager.addInterface(InterfaceType::WiFi, &wifi_interface);
|
||||
WIFI_DEBUG_PRINTLN("connecting to %s", wifi_ssid);
|
||||
|
||||
#if defined(RP2040_PLATFORM)
|
||||
// the join itself blocks inside the core (CYW43::begin busy-waits for the
|
||||
// association), so every attempt stalls the mesh loop. beginNoBlock() only skips the
|
||||
// extra DHCP wait. Give the first connect a full window, then bound the retries below.
|
||||
WiFi.beginNoBlock(wifi_ssid, wifi_pwd);
|
||||
last_wifi_reconnect_attempt = millis(); // let DHCP finish before the poll can retry
|
||||
#else
|
||||
WiFi.begin(wifi_ssid, wifi_pwd);
|
||||
#endif
|
||||
wifi_interface.begin(TCP_PORT);
|
||||
interface_manager.addInterface(InterfaceType::WiFi, &wifi_interface);
|
||||
} else {
|
||||
WIFI_DEBUG_PRINTLN("wifi disabled");
|
||||
}
|
||||
#endif
|
||||
|
||||
// add usb interface
|
||||
@@ -222,6 +276,36 @@ void setup() {
|
||||
interface_manager.addInterface(InterfaceType::Ethernet, ðernet_interface);
|
||||
#endif
|
||||
|
||||
#ifdef HAS_ESP_MDNS
|
||||
const char* nodeName = the_mesh.getNodeName();
|
||||
|
||||
// "meshcore_" prefix + sanitized node name, capped at 63 chars (max DNS label length)
|
||||
char mdnsName[64];
|
||||
const size_t prefixLen = snprintf(mdnsName, sizeof(mdnsName), "meshcore_");
|
||||
size_t pos = prefixLen;
|
||||
for (size_t i = 0; nodeName[i] != '\0' && pos < sizeof(mdnsName) - 1; ++i) {
|
||||
const char c = nodeName[i];
|
||||
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
|
||||
(c >= '0' && c <= '9') || c == '-' || c == '_') {
|
||||
mdnsName[pos++] = c;
|
||||
}
|
||||
}
|
||||
mdnsName[pos] = '\0';
|
||||
|
||||
if (!MDNS.begin(mdnsName)) {
|
||||
WIFI_DEBUG_PRINTLN("mDNS failed to start!");
|
||||
} else {
|
||||
MDNS.addService("meshcore", "tcp", TCP_PORT);
|
||||
MDNS.addServiceTxt("meshcore", "tcp", "node-name", nodeName);
|
||||
MDNS.addServiceTxt("meshcore", "tcp", "firmware-version", FIRMWARE_VERSION);
|
||||
char protocol[12];
|
||||
snprintf(protocol, sizeof(protocol), "%d", (int)FIRMWARE_VER_CODE);
|
||||
MDNS.addServiceTxt("meshcore", "tcp", "protocol-version", (const char*)protocol);
|
||||
MDNS.addServiceTxt("meshcore", "tcp", "build-date", __DATE__);
|
||||
MDNS.addServiceTxt("meshcore", "tcp", "build-time", __TIME__);
|
||||
}
|
||||
#endif
|
||||
|
||||
// add hardware serial interface
|
||||
#if defined(SERIAL_RX)
|
||||
companion_serial.setPins(SERIAL_RX, SERIAL_TX);
|
||||
@@ -236,22 +320,46 @@ void setup() {
|
||||
#if ENV_INCLUDE_GPS == 1
|
||||
the_mesh.applyGpsPrefs();
|
||||
#endif
|
||||
sensors.applyInaShunt(the_mesh.getNodePrefs()->ina_shunt_mohm); // CUSTOM (TeTeHacko)
|
||||
|
||||
#ifdef DISPLAY_CLASS
|
||||
ui_task.begin(disp, &sensors, the_mesh.getNodePrefs()); // still want to pass this in as dependency, as prefs might be moved
|
||||
ui_task.begin(disp, &sensors, the_mesh.getNodePrefs(), &interface_manager, &the_mesh, the_mesh.getBLEPin(), FIRMWARE_VERSION, FIRMWARE_BUILD_DATE);
|
||||
the_mesh.setListener(&ui_task);
|
||||
#ifdef EINK_REFRESH_LOOP
|
||||
if (disp != NULL) disp->setBusyHook(loopDuringDisplayRefresh);
|
||||
#endif
|
||||
#endif
|
||||
|
||||
board.onBootComplete();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// Work that must keep running even while the UI is blocked (e.g. by an e-ink refresh).
|
||||
// Called from loop() and from the display busy hook, so both always run the same set.
|
||||
static void loopCore() {
|
||||
the_mesh.loop();
|
||||
interface_manager.loop();
|
||||
sensors.loop();
|
||||
}
|
||||
|
||||
#if defined(DISPLAY_CLASS) && defined(EINK_REFRESH_LOOP)
|
||||
// Runs from inside the e-ink busy wait, so radio/BLE/sensors keep going during a panel refresh.
|
||||
// Must not touch the display: UI listener callbacks only update state and schedule the next frame.
|
||||
static void loopDuringDisplayRefresh() {
|
||||
static bool active = false;
|
||||
if (active) return;
|
||||
active = true;
|
||||
loopCore();
|
||||
active = false;
|
||||
}
|
||||
#endif
|
||||
|
||||
void loop() {
|
||||
loopCore();
|
||||
#ifdef DISPLAY_CLASS
|
||||
ui_task.loop();
|
||||
#endif
|
||||
rtc_clock.tick();
|
||||
board.loop();
|
||||
#ifdef HAS_EXTERNAL_WATCHDOG
|
||||
external_watchdog.loop();
|
||||
#endif
|
||||
@@ -262,13 +370,34 @@ void loop() {
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(ESP32) && defined(WIFI_SSID)
|
||||
// Safely attempt to reconnect every 10 seconds if flagged
|
||||
if (wifi_needs_reconnect && (millis() - last_wifi_reconnect_attempt > 10000)) {
|
||||
WIFI_DEBUG_PRINTLN("Attempting manual WiFi reconnect...");
|
||||
WiFi.disconnect();
|
||||
WiFi.reconnect();
|
||||
last_wifi_reconnect_attempt = millis();
|
||||
#ifdef ENABLE_WIFI_INTERFACE
|
||||
if (wifi_enabled) {
|
||||
// RP2040 has no WiFi event callbacks, so poll the link state instead
|
||||
#if defined(RP2040_PLATFORM)
|
||||
wifi_needs_reconnect = (WiFi.status() != WL_CONNECTED);
|
||||
if (wifi_was_connected == wifi_needs_reconnect) { // link state changed
|
||||
wifi_was_connected = !wifi_needs_reconnect;
|
||||
if (wifi_was_connected) {
|
||||
WIFI_DEBUG_PRINTLN("connected, listening on %s:%d", WiFi.localIP().toString().c_str(), TCP_PORT);
|
||||
} else {
|
||||
WIFI_DEBUG_PRINTLN("link lost");
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// Safely attempt to reconnect if flagged. On RP2040 each attempt blocks the mesh loop
|
||||
// for up to WIFI_RETRY_TIMEOUT, so retry less often and cap how long a join may stall.
|
||||
if (wifi_needs_reconnect && (millis() - last_wifi_reconnect_attempt > WIFI_RETRY_INTERVAL)) {
|
||||
WIFI_DEBUG_PRINTLN("Attempting manual WiFi reconnect to %s (status %d)...", wifi_ssid, WiFi.status());
|
||||
#if defined(RP2040_PLATFORM)
|
||||
WiFi.setTimeout(WIFI_RETRY_TIMEOUT);
|
||||
WiFi.beginNoBlock(wifi_ssid, wifi_pwd); // no reconnect() on this platform
|
||||
#else
|
||||
WiFi.disconnect();
|
||||
WiFi.reconnect();
|
||||
#endif
|
||||
last_wifi_reconnect_attempt = millis();
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "KissModem.h"
|
||||
#include <CayenneLPP.h>
|
||||
#include <stdio.h>
|
||||
|
||||
KissModem::KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& rng,
|
||||
mesh::Radio& radio, mesh::MainBoard& board, SensorManager& sensors)
|
||||
@@ -20,8 +21,15 @@ KissModem::KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& r
|
||||
_setTxPowerCallback = nullptr;
|
||||
_getCurrentRssiCallback = nullptr;
|
||||
_getStatsCallback = nullptr;
|
||||
_setRxBoostedGainCallback = nullptr;
|
||||
_getRxBoostedGainCallback = nullptr;
|
||||
_pollRxCallback = nullptr;
|
||||
_config = {0, 0, 0, 0, 0};
|
||||
_signal_report_enabled = true;
|
||||
_agc_reset_interval_sec = KISS_AGC_RESET_DEFAULT_SEC;
|
||||
_next_agc_reset_ms = 0;
|
||||
_fem_op_head = 0;
|
||||
_fem_op_count = 0;
|
||||
resetOutputQueue();
|
||||
}
|
||||
|
||||
@@ -31,6 +39,9 @@ void KissModem::begin() {
|
||||
_rx_active = false;
|
||||
_has_pending_tx = false;
|
||||
_tx_state = TX_IDLE;
|
||||
_fem_op_head = 0;
|
||||
_fem_op_count = 0;
|
||||
_next_agc_reset_ms = millis() + (uint32_t)_agc_reset_interval_sec * 1000;
|
||||
resetOutputQueue();
|
||||
}
|
||||
|
||||
@@ -240,10 +251,24 @@ void KissModem::loop() {
|
||||
}
|
||||
|
||||
processTx();
|
||||
processFemOps();
|
||||
maybeResetAgc();
|
||||
tryFlushFrames();
|
||||
queuePendingBusyError();
|
||||
}
|
||||
|
||||
void KissModem::maybeResetAgc() {
|
||||
if (_agc_reset_interval_sec == 0) return;
|
||||
// same guard as the RX path in main.cpp, so receive is restarted right after the reset
|
||||
if (_tx_state != TX_IDLE || isHostOutputBackedUp()) return;
|
||||
|
||||
uint32_t now = millis();
|
||||
if ((int32_t)(now - _next_agc_reset_ms) >= 0) {
|
||||
_radio.resetAGC();
|
||||
_next_agc_reset_ms = now + (uint32_t)_agc_reset_interval_sec * 1000;
|
||||
}
|
||||
}
|
||||
|
||||
void KissModem::processFrame() {
|
||||
if (_rx_len < 1) return;
|
||||
|
||||
@@ -381,6 +406,27 @@ void KissModem::handleHardwareCommand(uint8_t sub_cmd, const uint8_t* data, uint
|
||||
case HW_CMD_GET_SIGNAL_REPORT:
|
||||
handleGetSignalReport();
|
||||
break;
|
||||
case HW_CMD_GET_CAPABILITIES:
|
||||
handleGetCapabilities();
|
||||
break;
|
||||
case HW_CMD_SET_AGC_RESET_INTERVAL:
|
||||
handleSetAgcResetInterval(data, len);
|
||||
break;
|
||||
case HW_CMD_GET_AGC_RESET_INTERVAL:
|
||||
handleGetAgcResetInterval();
|
||||
break;
|
||||
case HW_CMD_SET_FEM_STATE:
|
||||
handleSetFemState(data, len);
|
||||
break;
|
||||
case HW_CMD_GET_FEM_STATE:
|
||||
handleGetFemState();
|
||||
break;
|
||||
case HW_CMD_SET_RX_BOOSTED_GAIN:
|
||||
handleSetRxBoostedGain(data, len);
|
||||
break;
|
||||
case HW_CMD_GET_RX_BOOSTED_GAIN:
|
||||
handleGetRxBoostedGain();
|
||||
break;
|
||||
default:
|
||||
writeHardwareError(HW_ERR_UNKNOWN_CMD);
|
||||
break;
|
||||
@@ -714,8 +760,26 @@ void KissModem::handleReboot() {
|
||||
}
|
||||
|
||||
void KissModem::handleGetDeviceName() {
|
||||
const char* name = _board.getManufacturerName();
|
||||
writeHardwareFrame(HW_RESP(HW_CMD_GET_DEVICE_NAME), (const uint8_t*)name, strlen(name));
|
||||
// CUSTOM (TeTeHacko): k výrobci se připojuje STAMPOVANÁ verze firmwaru.
|
||||
//
|
||||
// Bez ní je deska s tímhle buildem z hlediska verzí neidentifikovatelná:
|
||||
// GetVersion (0x11) vrací verzi KISS PROTOKOLU (konstanta KISS_FIRMWARE_VERSION),
|
||||
// textovou konzoli ani companion protokol tenhle build nemá, a protože se
|
||||
// FIRMWARE_VERSION nikde jinde nepoužívá, linker ten řetězec z obrazu vyhodí --
|
||||
// takže ho nenajde ani `tools/xiao_uf2_flash.sh`, který kvůli tomu flash rovnou
|
||||
// odmítne ("obraz nema verzi od tools/build_version.py").
|
||||
//
|
||||
// 1. 9. 2026 to stálo hodinu: KISS modem skončil omylem na x2, deska pak
|
||||
// neodpovídala konzoli ani companionu a vypadala jako zaseklá, a nešlo z ní
|
||||
// zjistit, co na ní vlastně je. `tools/board_probe.py` se ptá právě sem.
|
||||
char buf[96];
|
||||
int n = snprintf(buf, sizeof(buf), "%s %s", _board.getManufacturerName(), FIRMWARE_VERSION);
|
||||
if (n < 0) n = 0;
|
||||
// snprintf vraci delku BEZ koncove nuly, takze n == sizeof(buf) znamena
|
||||
// "presne se to nevleslo". `n > sizeof(buf)` to propustilo a clampovalo na
|
||||
// sizeof(buf), cimz na drat sla i ta koncova nula na buf[95].
|
||||
if (n >= (int)sizeof(buf)) n = (int)sizeof(buf) - 1;
|
||||
writeHardwareFrame(HW_RESP(HW_CMD_GET_DEVICE_NAME), (const uint8_t*)buf, n);
|
||||
}
|
||||
|
||||
void KissModem::handleSetSignalReport(const uint8_t* data, uint16_t len) {
|
||||
@@ -732,3 +796,183 @@ void KissModem::handleGetSignalReport() {
|
||||
uint8_t val = _signal_report_enabled ? 0x01 : 0x00;
|
||||
writeHardwareFrame(HW_RESP(HW_CMD_GET_SIGNAL_REPORT), &val, 1);
|
||||
}
|
||||
|
||||
void KissModem::handleGetCapabilities() {
|
||||
uint32_t caps = HW_CAP_AGC_RESET;
|
||||
uint8_t fem_caps, fem_values;
|
||||
readFemState(&fem_caps, &fem_values);
|
||||
if (fem_caps & HW_FEM_RX_GAIN) caps |= HW_CAP_FEM_RX_GAIN;
|
||||
if (fem_caps & HW_FEM_TX_GAIN) caps |= HW_CAP_FEM_TX_GAIN;
|
||||
if (_setRxBoostedGainCallback && _getRxBoostedGainCallback) caps |= HW_CAP_RX_BOOSTED_GAIN;
|
||||
uint8_t buf[4] = { (uint8_t)caps, (uint8_t)(caps >> 8), (uint8_t)(caps >> 16), (uint8_t)(caps >> 24) };
|
||||
writeHardwareFrame(HW_RESP(HW_CMD_GET_CAPABILITIES), buf, 4);
|
||||
}
|
||||
|
||||
void KissModem::handleSetAgcResetInterval(const uint8_t* data, uint16_t len) {
|
||||
if (len < 2) {
|
||||
writeHardwareError(HW_ERR_INVALID_LENGTH);
|
||||
return;
|
||||
}
|
||||
uint16_t secs = (uint16_t)(data[0] | (data[1] << 8));
|
||||
if (secs > KISS_AGC_RESET_MAX_SEC) {
|
||||
writeHardwareError(HW_ERR_INVALID_PARAM);
|
||||
return;
|
||||
}
|
||||
_agc_reset_interval_sec = secs - (secs % KISS_AGC_RESET_STEP_SEC);
|
||||
_next_agc_reset_ms = millis() + (uint32_t)_agc_reset_interval_sec * 1000;
|
||||
handleGetAgcResetInterval();
|
||||
}
|
||||
|
||||
void KissModem::handleGetAgcResetInterval() {
|
||||
uint8_t buf[2] = { (uint8_t)_agc_reset_interval_sec, (uint8_t)(_agc_reset_interval_sec >> 8) };
|
||||
writeHardwareFrame(HW_RESP(HW_CMD_GET_AGC_RESET_INTERVAL), buf, 2);
|
||||
}
|
||||
|
||||
// FEM gain is reached through the board's own "radio.fem.*" CLI commands, the same ones users run.
|
||||
static const char* femGainName(uint8_t bit) {
|
||||
return bit == HW_FEM_RX_GAIN ? "rxgain" : "txgain";
|
||||
}
|
||||
|
||||
// Anything but an exact "> on" / "> off" (not handled, "Error: ...", unexpected text) means unsupported.
|
||||
bool KissModem::queryFemGain(uint8_t bit, bool* enabled) {
|
||||
char cmd[32];
|
||||
char reply[KISS_BOARD_REPLY_SIZE] = { 0 };
|
||||
snprintf(cmd, sizeof(cmd), "get radio.fem.%s", femGainName(bit));
|
||||
if (!_board.handleCommand(cmd, 0, reply)) return false;
|
||||
if (strcmp(reply, "> on") == 0) {
|
||||
*enabled = true;
|
||||
} else if (strcmp(reply, "> off") == 0) {
|
||||
*enabled = false;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Success is judged by reading the state back, not by the wording of the set reply.
|
||||
bool KissModem::setFemGain(uint8_t bit, bool enable) {
|
||||
char cmd[32];
|
||||
char reply[KISS_BOARD_REPLY_SIZE] = { 0 };
|
||||
snprintf(cmd, sizeof(cmd), "set radio.fem.%s %s", femGainName(bit), enable ? "on" : "off");
|
||||
_board.handleCommand(cmd, 0, reply);
|
||||
bool now;
|
||||
return queryFemGain(bit, &now) && now == enable;
|
||||
}
|
||||
|
||||
void KissModem::readFemState(uint8_t* caps, uint8_t* values) {
|
||||
*caps = 0;
|
||||
*values = 0;
|
||||
const uint8_t bits[] = { HW_FEM_RX_GAIN, HW_FEM_TX_GAIN };
|
||||
for (uint8_t bit : bits) {
|
||||
bool enabled;
|
||||
if (queryFemGain(bit, &enabled)) {
|
||||
*caps |= bit;
|
||||
if (enabled) *values |= bit;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool KissModem::queueFemReply() {
|
||||
uint8_t buf[2];
|
||||
readFemState(&buf[0], &buf[1]);
|
||||
return queueHardwareFrame(HW_RESP(HW_CMD_GET_FEM_STATE), buf, 2, false);
|
||||
}
|
||||
|
||||
// The reply always carries the read-back state, so a bit that failed to apply shows its real value.
|
||||
void KissModem::applyFemState(uint8_t apply_mask, uint8_t value_mask) {
|
||||
if (apply_mask & HW_FEM_RX_GAIN) {
|
||||
setFemGain(HW_FEM_RX_GAIN, (value_mask & HW_FEM_RX_GAIN) != 0);
|
||||
}
|
||||
if (apply_mask & HW_FEM_TX_GAIN) {
|
||||
setFemGain(HW_FEM_TX_GAIN, (value_mask & HW_FEM_TX_GAIN) != 0);
|
||||
}
|
||||
}
|
||||
|
||||
void KissModem::enqueueFemOp(FemOpKind kind, uint8_t apply_mask, uint8_t value_mask) {
|
||||
if (_fem_op_count >= KISS_FEM_OP_QUEUE_DEPTH) {
|
||||
writeHardwareError(HW_ERR_TX_BUSY); // too many FEM requests waiting
|
||||
return;
|
||||
}
|
||||
FemOp& op = _fem_ops[(_fem_op_head + _fem_op_count) % KISS_FEM_OP_QUEUE_DEPTH];
|
||||
op.kind = kind;
|
||||
op.apply_mask = apply_mask;
|
||||
op.value_mask = value_mask;
|
||||
op.applied = false;
|
||||
_fem_op_count++;
|
||||
processFemOps();
|
||||
}
|
||||
|
||||
// Every FEM reply goes out in request order. A Set waits until TxDone is queued, since board
|
||||
// setters drive FEM pins directly; each reply is retained until there is room to queue it.
|
||||
void KissModem::processFemOps() {
|
||||
while (_fem_op_count > 0) {
|
||||
FemOp& op = _fem_ops[_fem_op_head];
|
||||
if (op.kind == FEM_OP_ERROR) {
|
||||
if (!queueHardwareFrame(HW_RESP_ERROR, &op.value_mask, 1, false)) return;
|
||||
} else {
|
||||
if (op.kind == FEM_OP_SET && !op.applied) {
|
||||
if (_tx_state == TX_SENDING || _tx_state == TX_DONE_PENDING) return;
|
||||
uint8_t caps, values;
|
||||
readFemState(&caps, &values);
|
||||
if (op.apply_mask & ~caps) {
|
||||
// all-or-nothing: any bit the board cannot control rejects the whole request
|
||||
op.kind = FEM_OP_ERROR;
|
||||
op.value_mask = HW_ERR_UNSUPPORTED;
|
||||
continue;
|
||||
}
|
||||
applyFemState(op.apply_mask, op.value_mask);
|
||||
op.applied = true;
|
||||
}
|
||||
if (!queueFemReply()) return;
|
||||
}
|
||||
_fem_op_head = (uint8_t)((_fem_op_head + 1) % KISS_FEM_OP_QUEUE_DEPTH);
|
||||
_fem_op_count--;
|
||||
}
|
||||
}
|
||||
|
||||
void KissModem::handleSetFemState(const uint8_t* data, uint16_t len) {
|
||||
if (len < 2) {
|
||||
enqueueFemOp(FEM_OP_ERROR, 0, HW_ERR_INVALID_LENGTH);
|
||||
return;
|
||||
}
|
||||
enqueueFemOp(FEM_OP_SET, data[0], data[1]);
|
||||
}
|
||||
|
||||
void KissModem::handleGetFemState() {
|
||||
enqueueFemOp(FEM_OP_GET, 0, 0);
|
||||
}
|
||||
|
||||
void KissModem::handleSetRxBoostedGain(const uint8_t* data, uint16_t len) {
|
||||
if (len < 1) {
|
||||
writeHardwareError(HW_ERR_INVALID_LENGTH);
|
||||
return;
|
||||
}
|
||||
if (!_setRxBoostedGainCallback || !_getRxBoostedGainCallback) {
|
||||
writeHardwareError(HW_ERR_UNSUPPORTED);
|
||||
return;
|
||||
}
|
||||
// some drivers (LR2021) drop to standby to apply the gain, which would abort a TX and
|
||||
// discard a completed RX packet; so never during TX, and only after draining RX
|
||||
if (_tx_state == TX_SENDING || isHostOutputBackedUp()) {
|
||||
writeHardwareError(HW_ERR_TX_BUSY);
|
||||
return;
|
||||
}
|
||||
if (_pollRxCallback) _pollRxCallback();
|
||||
tryFlushFrames();
|
||||
if (_tx_frame_count >= KISS_TX_FRAME_QUEUE_DEPTH) {
|
||||
writeHardwareError(HW_ERR_TX_BUSY); // no room left for the reply; change nothing
|
||||
return;
|
||||
}
|
||||
// always reply with the state read back, so a failed or partial write is never misreported
|
||||
_setRxBoostedGainCallback(data[0] != 0x00);
|
||||
handleGetRxBoostedGain();
|
||||
}
|
||||
|
||||
void KissModem::handleGetRxBoostedGain() {
|
||||
if (!_getRxBoostedGainCallback) {
|
||||
writeHardwareError(HW_ERR_UNSUPPORTED);
|
||||
return;
|
||||
}
|
||||
uint8_t val = _getRxBoostedGainCallback() ? 0x01 : 0x00;
|
||||
writeHardwareFrame(HW_RESP(HW_CMD_GET_RX_BOOSTED_GAIN), &val, 1);
|
||||
}
|
||||
@@ -62,6 +62,13 @@
|
||||
#define HW_CMD_REBOOT 0x18
|
||||
#define HW_CMD_SET_SIGNAL_REPORT 0x19
|
||||
#define HW_CMD_GET_SIGNAL_REPORT 0x1A
|
||||
#define HW_CMD_GET_CAPABILITIES 0x1B
|
||||
#define HW_CMD_SET_AGC_RESET_INTERVAL 0x1C
|
||||
#define HW_CMD_GET_AGC_RESET_INTERVAL 0x1D
|
||||
#define HW_CMD_SET_FEM_STATE 0x1E
|
||||
#define HW_CMD_GET_FEM_STATE 0x1F
|
||||
#define HW_CMD_SET_RX_BOOSTED_GAIN 0x20
|
||||
#define HW_CMD_GET_RX_BOOSTED_GAIN 0x21
|
||||
|
||||
/* Response code = command code | 0x80. Generic / unsolicited use 0xF0+. */
|
||||
#define HW_RESP(cmd) ((cmd) | 0x80)
|
||||
@@ -81,13 +88,37 @@
|
||||
#define HW_ERR_UNKNOWN_CMD 0x05
|
||||
#define HW_ERR_ENCRYPT_FAILED 0x06
|
||||
#define HW_ERR_TX_BUSY 0x07
|
||||
#define HW_ERR_UNSUPPORTED 0x08
|
||||
|
||||
#define KISS_FIRMWARE_VERSION 1
|
||||
/* GetCapabilities feature bits */
|
||||
#define HW_CAP_AGC_RESET (1UL << 0)
|
||||
#define HW_CAP_FEM_RX_GAIN (1UL << 1)
|
||||
#define HW_CAP_FEM_TX_GAIN (1UL << 2)
|
||||
#define HW_CAP_RX_BOOSTED_GAIN (1UL << 3)
|
||||
|
||||
/* SetFemState / GetFemState mask bits */
|
||||
#define HW_FEM_RX_GAIN (1 << 0)
|
||||
#define HW_FEM_TX_GAIN (1 << 1)
|
||||
|
||||
/* Matches the CLI reply buffer boards write into from handleCommand() */
|
||||
#define KISS_BOARD_REPLY_SIZE 160
|
||||
|
||||
/* FEM requests are answered strictly in arrival order; this many may wait (e.g. during a TX) */
|
||||
#define KISS_FEM_OP_QUEUE_DEPTH 4
|
||||
|
||||
#define KISS_AGC_RESET_DEFAULT_SEC 32 // a multiple of the 4 s step, so hosts can set it back
|
||||
#define KISS_AGC_RESET_MAX_SEC 1020
|
||||
#define KISS_AGC_RESET_STEP_SEC 4
|
||||
|
||||
#define KISS_FIRMWARE_VERSION 2
|
||||
|
||||
typedef void (*SetRadioCallback)(float freq, float bw, uint8_t sf, uint8_t cr);
|
||||
typedef void (*SetTxPowerCallback)(uint8_t power);
|
||||
typedef float (*GetCurrentRssiCallback)();
|
||||
typedef void (*GetStatsCallback)(uint32_t* rx, uint32_t* tx, uint32_t* errors);
|
||||
typedef bool (*SetRxBoostedGainCallback)(bool enable);
|
||||
typedef bool (*GetRxBoostedGainCallback)();
|
||||
typedef void (*PollRxCallback)();
|
||||
|
||||
struct RadioConfig {
|
||||
uint32_t freq_hz;
|
||||
@@ -97,6 +128,19 @@ struct RadioConfig {
|
||||
uint8_t tx_power;
|
||||
};
|
||||
|
||||
enum FemOpKind : uint8_t {
|
||||
FEM_OP_SET,
|
||||
FEM_OP_GET,
|
||||
FEM_OP_ERROR
|
||||
};
|
||||
|
||||
struct FemOp {
|
||||
FemOpKind kind;
|
||||
uint8_t apply_mask; // FEM_OP_SET
|
||||
uint8_t value_mask; // FEM_OP_SET; error code for FEM_OP_ERROR
|
||||
bool applied; // FEM_OP_SET: hardware changed, reply still to be queued
|
||||
};
|
||||
|
||||
enum TxState {
|
||||
TX_IDLE,
|
||||
TX_WAIT_CLEAR,
|
||||
@@ -136,9 +180,17 @@ class KissModem {
|
||||
SetTxPowerCallback _setTxPowerCallback;
|
||||
GetCurrentRssiCallback _getCurrentRssiCallback;
|
||||
GetStatsCallback _getStatsCallback;
|
||||
SetRxBoostedGainCallback _setRxBoostedGainCallback;
|
||||
GetRxBoostedGainCallback _getRxBoostedGainCallback;
|
||||
PollRxCallback _pollRxCallback;
|
||||
|
||||
RadioConfig _config;
|
||||
bool _signal_report_enabled;
|
||||
uint16_t _agc_reset_interval_sec;
|
||||
uint32_t _next_agc_reset_ms;
|
||||
FemOp _fem_ops[KISS_FEM_OP_QUEUE_DEPTH];
|
||||
uint8_t _fem_op_head;
|
||||
uint8_t _fem_op_count;
|
||||
uint8_t _tx_frame_buf[KISS_TX_FRAME_QUEUE_DEPTH][KISS_MAX_ENCODED_FRAME_SIZE];
|
||||
uint16_t _tx_frame_len[KISS_TX_FRAME_QUEUE_DEPTH];
|
||||
uint16_t _tx_frame_written[KISS_TX_FRAME_QUEUE_DEPTH];
|
||||
@@ -165,6 +217,14 @@ class KissModem {
|
||||
void processFrame();
|
||||
void handleHardwareCommand(uint8_t sub_cmd, const uint8_t* data, uint16_t len);
|
||||
void processTx();
|
||||
void maybeResetAgc();
|
||||
bool queryFemGain(uint8_t bit, bool* enabled);
|
||||
bool setFemGain(uint8_t bit, bool enable);
|
||||
void readFemState(uint8_t* caps, uint8_t* values);
|
||||
bool queueFemReply();
|
||||
void applyFemState(uint8_t apply_mask, uint8_t value_mask);
|
||||
void enqueueFemOp(FemOpKind kind, uint8_t apply_mask, uint8_t value_mask);
|
||||
void processFemOps();
|
||||
|
||||
void handleGetIdentity();
|
||||
void handleGetRandom(const uint8_t* data, uint16_t len);
|
||||
@@ -192,6 +252,13 @@ class KissModem {
|
||||
void handleGetDeviceName();
|
||||
void handleSetSignalReport(const uint8_t* data, uint16_t len);
|
||||
void handleGetSignalReport();
|
||||
void handleGetCapabilities();
|
||||
void handleSetAgcResetInterval(const uint8_t* data, uint16_t len);
|
||||
void handleGetAgcResetInterval();
|
||||
void handleSetFemState(const uint8_t* data, uint16_t len);
|
||||
void handleGetFemState();
|
||||
void handleSetRxBoostedGain(const uint8_t* data, uint16_t len);
|
||||
void handleGetRxBoostedGain();
|
||||
|
||||
public:
|
||||
KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& rng,
|
||||
@@ -204,6 +271,13 @@ public:
|
||||
void setTxPowerCallback(SetTxPowerCallback cb) { _setTxPowerCallback = cb; }
|
||||
void setGetCurrentRssiCallback(GetCurrentRssiCallback cb) { _getCurrentRssiCallback = cb; }
|
||||
void setGetStatsCallback(GetStatsCallback cb) { _getStatsCallback = cb; }
|
||||
// Only register these when the radio supports boosted RX gain; they define the capability.
|
||||
// Delivers any completed RX packet to the host; called before settings that restart the receiver.
|
||||
void setPollRxCallback(PollRxCallback cb) { _pollRxCallback = cb; }
|
||||
void setRxBoostedGainCallbacks(SetRxBoostedGainCallback set_cb, GetRxBoostedGainCallback get_cb) {
|
||||
_setRxBoostedGainCallback = set_cb;
|
||||
_getRxBoostedGainCallback = get_cb;
|
||||
}
|
||||
|
||||
void onPacketReceived(int8_t snr, int8_t rssi, const uint8_t* packet, uint16_t len);
|
||||
bool isTxBusy() const { return _tx_state != TX_IDLE; }
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
#endif
|
||||
|
||||
#define NOISE_FLOOR_CALIB_INTERVAL_MS 2000
|
||||
#define AGC_RESET_INTERVAL_MS 30000
|
||||
#define USB_TX_TIMEOUT_MS 50
|
||||
#define USB_TX_BUFFER_SIZE 1024
|
||||
|
||||
@@ -27,7 +26,6 @@ StdRNG rng;
|
||||
mesh::LocalIdentity identity;
|
||||
KissModem* modem;
|
||||
static uint32_t next_noise_floor_calib_ms = 0;
|
||||
static uint32_t next_agc_reset_ms = 0;
|
||||
|
||||
void halt() {
|
||||
while (1) ;
|
||||
@@ -75,6 +73,24 @@ void onGetStats(uint32_t* rx, uint32_t* tx, uint32_t* errors) {
|
||||
*errors = radio_driver.getPacketsRecvErrors();
|
||||
}
|
||||
|
||||
void pollRadioRx() {
|
||||
uint8_t rx_buf[256];
|
||||
int rx_len = radio_driver.recvRaw(rx_buf, sizeof(rx_buf));
|
||||
if (rx_len > 0) {
|
||||
int8_t snr = (int8_t)(radio_driver.getLastSNR() * 4);
|
||||
int8_t rssi = (int8_t)radio_driver.getLastRSSI();
|
||||
modem->onPacketReceived(snr, rssi, rx_buf, rx_len);
|
||||
}
|
||||
}
|
||||
|
||||
bool onSetRxBoostedGain(bool enable) {
|
||||
return radio_driver.setRxBoostedGainMode(enable);
|
||||
}
|
||||
|
||||
bool onGetRxBoostedGain() {
|
||||
return radio_driver.getRxBoostedGainMode();
|
||||
}
|
||||
|
||||
void setup() {
|
||||
board.begin();
|
||||
|
||||
@@ -113,9 +129,12 @@ void setup() {
|
||||
uint32_t start = millis();
|
||||
while (!Serial && millis() - start < 3000) delay(10);
|
||||
delay(100);
|
||||
#if defined(ESP32) && ARDUINO_USB_MODE
|
||||
#if defined(ESP32) && defined(ARDUINO_USB_CDC_ON_BOOT) && ARDUINO_USB_CDC_ON_BOOT
|
||||
Serial.setTxTimeoutMs(USB_TX_TIMEOUT_MS);
|
||||
#if defined(ARDUINO_USB_MODE) && ARDUINO_USB_MODE
|
||||
// HWCDC only; TinyUSB's USBCDC TX buffer is fixed at build time
|
||||
Serial.setTxBufferSize(USB_TX_BUFFER_SIZE);
|
||||
#endif
|
||||
#endif
|
||||
modem = new KissModem(Serial, identity, rng, radio_driver, board, sensors);
|
||||
#endif
|
||||
@@ -124,6 +143,10 @@ void setup() {
|
||||
modem->setTxPowerCallback(onSetTxPower);
|
||||
modem->setGetCurrentRssiCallback(onGetCurrentRssi);
|
||||
modem->setGetStatsCallback(onGetStats);
|
||||
modem->setPollRxCallback(pollRadioRx);
|
||||
if (radio_driver.supportsRxBoostedGain()) {
|
||||
modem->setRxBoostedGainCallbacks(onSetRxBoostedGain, onGetRxBoostedGain);
|
||||
}
|
||||
modem->begin();
|
||||
|
||||
board.onBootComplete();
|
||||
@@ -133,22 +156,11 @@ void loop() {
|
||||
modem->loop();
|
||||
|
||||
if (!modem->isActuallyTransmitting() && !modem->isHostOutputBackedUp()) {
|
||||
if (!modem->isTxBusy()) {
|
||||
if ((uint32_t)(millis() - next_agc_reset_ms) >= AGC_RESET_INTERVAL_MS) {
|
||||
radio_driver.resetAGC();
|
||||
next_agc_reset_ms = millis();
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t rx_buf[256];
|
||||
int rx_len = radio_driver.recvRaw(rx_buf, sizeof(rx_buf));
|
||||
if (rx_len > 0) {
|
||||
int8_t snr = (int8_t)(radio_driver.getLastSNR() * 4);
|
||||
int8_t rssi = (int8_t)radio_driver.getLastRSSI();
|
||||
modem->onPacketReceived(snr, rssi, rx_buf, rx_len);
|
||||
}
|
||||
pollRadioRx();
|
||||
}
|
||||
|
||||
board.loop();
|
||||
|
||||
if ((uint32_t)(millis() - next_noise_floor_calib_ms) >= NOISE_FLOOR_CALIB_INTERVAL_MS) {
|
||||
radio_driver.triggerNoiseFloorCalibrate(0);
|
||||
next_noise_floor_calib_ms = millis();
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
#pragma once
|
||||
|
||||
// CUSTOM (TeTeHacko): pure string helpers for the channel modules
|
||||
// (ChannelCommon.h, ChannelFilter.h, ChannelBot.h). No MyMesh, no Arduino --
|
||||
// deliberately, so test/test_chan_list can compile them on the native env.
|
||||
|
||||
#include <ctype.h>
|
||||
#include <string.h>
|
||||
|
||||
// Longest node name an entry may hold. MeshCore node names are 32 bytes
|
||||
// (NodePrefs.node_name), the margin is for UTF-8 names people paste with
|
||||
// trailing decoration.
|
||||
#define CHAN_NAME_MAX 40
|
||||
|
||||
#define CHAN_LIST_OK 0
|
||||
#define CHAN_LIST_BAD_NAME -1 // empty, too long, or contains the ',' separator
|
||||
#define CHAN_LIST_DUP -2
|
||||
#define CHAN_LIST_FULL -3
|
||||
|
||||
static int chan_hex_nibble(char c) {
|
||||
if (c >= '0' && c <= '9') return c - '0';
|
||||
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
|
||||
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Exact, case-insensitive membership in a comma-separated list. Deliberately
|
||||
// NOT a substring search: an ignore/deny list matching on substrings would be
|
||||
// a trap (a node called "TTH" silencing "tracker"). Entries are trimmed of
|
||||
// surrounding spaces; case folding is ASCII-only, so UTF-8 names match
|
||||
// byte-exactly (good enough -- nobody case-shifts emoji).
|
||||
static bool chan_list_has(const char* list, const char* word) {
|
||||
const char* seg = list;
|
||||
while (*seg) {
|
||||
const char* comma = strchr(seg, ',');
|
||||
int len = comma ? (int)(comma - seg) : (int)strlen(seg);
|
||||
while (len > 0 && *seg == ' ') { seg++; len--; }
|
||||
while (len > 0 && seg[len - 1] == ' ') len--;
|
||||
if (len > 0 && (int)strlen(word) == len) {
|
||||
int i = 0;
|
||||
while (i < len && tolower((unsigned char)word[i]) == tolower((unsigned char)seg[i])) i++;
|
||||
if (i == len) return true;
|
||||
}
|
||||
if (!comma) break;
|
||||
seg = comma + 1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Append name[0..name_len) to the comma-separated `list` (buffer of `cap`
|
||||
// bytes, NUL-terminated). Leading/trailing spaces are trimmed off the name
|
||||
// first (RF-padded commands happen).
|
||||
static int chan_list_add(char* list, int cap, const char* name, int name_len) {
|
||||
while (name_len > 0 && *name == ' ') { name++; name_len--; }
|
||||
while (name_len > 0 && name[name_len - 1] == ' ') name_len--;
|
||||
if (name_len <= 0 || name_len >= CHAN_NAME_MAX) return CHAN_LIST_BAD_NAME;
|
||||
if (memchr(name, ',', name_len) != NULL) return CHAN_LIST_BAD_NAME; // ',' is the separator
|
||||
|
||||
char tmp[CHAN_NAME_MAX];
|
||||
memcpy(tmp, name, name_len);
|
||||
tmp[name_len] = 0;
|
||||
if (chan_list_has(list, tmp)) return CHAN_LIST_DUP;
|
||||
|
||||
int cur = strlen(list);
|
||||
if (cur + (cur > 0 ? 1 : 0) + name_len + 1 > cap) return CHAN_LIST_FULL;
|
||||
if (cur > 0) list[cur++] = ',';
|
||||
memcpy(&list[cur], tmp, name_len + 1);
|
||||
return CHAN_LIST_OK;
|
||||
}
|
||||
|
||||
// Remove the (case-insensitively) matching entry. Returns false when absent.
|
||||
static bool chan_list_del(char* list, const char* name) {
|
||||
while (*name == ' ') name++;
|
||||
int name_len = strlen(name);
|
||||
while (name_len > 0 && name[name_len - 1] == ' ') name_len--; // trim trailing too (RF pads)
|
||||
char out[512]; // callers' lists are far smaller (filter_deny is 128 B)
|
||||
int out_len = 0;
|
||||
bool removed = false;
|
||||
const char* seg = list;
|
||||
int list_len = strlen(list);
|
||||
if (list_len >= (int)sizeof(out)) return false; // defensive, never expected
|
||||
|
||||
while (*seg) {
|
||||
const char* comma = strchr(seg, ',');
|
||||
int len = comma ? (int)(comma - seg) : (int)strlen(seg);
|
||||
const char* e = seg;
|
||||
int elen = len;
|
||||
while (elen > 0 && *e == ' ') { e++; elen--; }
|
||||
while (elen > 0 && e[elen - 1] == ' ') elen--;
|
||||
bool match = false;
|
||||
if (name_len == elen) {
|
||||
int i = 0;
|
||||
while (i < elen && tolower((unsigned char)name[i]) == tolower((unsigned char)e[i])) i++;
|
||||
match = (i == elen);
|
||||
}
|
||||
if (match) {
|
||||
removed = true;
|
||||
} else if (len > 0) {
|
||||
if (out_len > 0) out[out_len++] = ',';
|
||||
memcpy(&out[out_len], seg, len);
|
||||
out_len += len;
|
||||
}
|
||||
if (!comma) break;
|
||||
seg = comma + 1;
|
||||
}
|
||||
if (removed) {
|
||||
out[out_len] = 0;
|
||||
memcpy(list, out, out_len + 1);
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
#pragma once
|
||||
|
||||
// CUSTOM (TeTeHacko): channel bot -- not part of upstream simple_repeater.
|
||||
// Included at the bottom of MyMesh.cpp, after ChannelCommon.h (which owns the
|
||||
// channel registry, the PSK parsing, searchChannelsByHash() and the
|
||||
// onGroupDataRecv() dispatcher that calls botOnChannelText() here), so these
|
||||
// are plain MyMesh methods with full access to the analyzer state.
|
||||
//
|
||||
// WHY THIS LIVES IN THE REPEATER/ANALYZER BUILD
|
||||
//
|
||||
// The obvious place for a bot is companion_radio (it already has channels and
|
||||
// contacts), but a companion build has no text CLI and no analyzer rings, so the
|
||||
// observer node would stop feeding CoreScope. The reverse -- teaching this build
|
||||
// to read one channel -- turned out to be small, because everything needed is
|
||||
// already virtual in mesh::Mesh:
|
||||
//
|
||||
// * Mesh::onRecvPacket() calls searchChannelsByHash() + onGroupDataRecv() and
|
||||
// THEN routeRecvPacket(), so decrypting a channel is independent of
|
||||
// forwarding it. Both defaults are no-ops (Mesh.cpp:37, Mesh.h:160), which
|
||||
// is the only reason a repeater is normally deaf to channel traffic.
|
||||
// * allowPacketForward() is consulted only for RECEIVED packets, so a node
|
||||
// with `repeat off` can still originate its own reply. That matters here:
|
||||
// x3 sits a few metres from mast-three and must never be a second repeater,
|
||||
// but it does have to be able to answer.
|
||||
// * createGroupDatagram() is in mesh::Mesh, not BaseChatMesh, and
|
||||
// sendFloodScoped() is a plain alias for sendFlood(), so no part of the
|
||||
// chat/contact machinery is needed to send.
|
||||
//
|
||||
// Written against the mesh::Mesh API only (no BaseChatMesh, no ClientACL, no
|
||||
// DataStore) so it can be dropped into simple_room_server unchanged -- that
|
||||
// example derives from the same base.
|
||||
|
||||
#ifdef BOT_CHANNEL_PSK
|
||||
|
||||
// Comma-separated, case-insensitive substrings; "*" answers anything, "" never.
|
||||
#ifndef BOT_TRIGGER
|
||||
#define BOT_TRIGGER "ping,test"
|
||||
#endif
|
||||
// Senders whose messages are skipped outright, comma-separated node names.
|
||||
// This is what keeps two bots on one channel from feeding each other: with
|
||||
// tracker (Solo firmware) periodically putting "Ping" on #tth-test, an
|
||||
// unfiltered trigger list made this node answer every one of them and burn the
|
||||
// cooldown, so a human asking a question got silence.
|
||||
#ifndef BOT_IGNORE_SENDERS
|
||||
#define BOT_IGNORE_SENDERS ""
|
||||
#endif
|
||||
// Whitelist of `!commands` this node answers, comma-separated, "" = all.
|
||||
// The point is complementarity: two bots answering !path means two packets and
|
||||
// one duplicate. Give each node the commands only it can answer well.
|
||||
#ifndef BOT_COMMANDS
|
||||
#define BOT_COMMANDS ""
|
||||
#endif
|
||||
// Throttle, PER SENDER. Measured reason it is not global: with one global
|
||||
// window, two people asking within it meant the second got silence -- observed
|
||||
// twice, and it reads as "the bot is broken" rather than "wait 10 s".
|
||||
#ifndef BOT_REPLY_COOLDOWN_MS
|
||||
#define BOT_REPLY_COOLDOWN_MS 10000
|
||||
#endif
|
||||
// Floor between ANY two replies, whoever asked. This is what still bounds the
|
||||
// node's airtime on a shared community mesh once the main window went
|
||||
// per-sender: N senders can no longer produce N simultaneous replies.
|
||||
#ifndef BOT_MIN_GAP_MS
|
||||
#define BOT_MIN_GAP_MS 2500
|
||||
#endif
|
||||
// Cap on the whole bot over a longer window: at most BOT_BURST_MAX replies per
|
||||
// BOT_BURST_WINDOW_MS (0 = off). The per-sender window is keyed by NAME, which
|
||||
// is plain text in a channel message, so ten names walk around it; the floor
|
||||
// alone still lets through 24 replies/min (~18 % of channel airtime). Normal
|
||||
// use is ~15 replies a DAY, so 10 per 5 min cuts nothing legitimate.
|
||||
// BOT_BURST_MAX itself defaults in MyMesh.h (it sizes an array there).
|
||||
#ifndef BOT_BURST_WINDOW_MS
|
||||
#define BOT_BURST_WINDOW_MS 300000
|
||||
#endif
|
||||
// Senders tracked for the per-sender window. Wraps LRU; overflowing just means
|
||||
// the oldest sender's window is forgotten early, i.e. one extra reply.
|
||||
#ifndef BOT_PEER_SLOTS
|
||||
#define BOT_PEER_SLOTS 8
|
||||
#endif
|
||||
|
||||
#define BOT_REPLY_LEN 120 // well under the 184 B packet payload
|
||||
#define BOT_PATH_STR_LEN 64 // "3f:a1:c8..." -- caps how many hops we print
|
||||
// One !command's answer. Sized for the WORST CASE of !link, which is the longest:
|
||||
// botFormatPath() caps the path string at 62 chars (21 hops x 1 B, or 9 x 3 B, or
|
||||
// 12 x 2 B -- all land just under BOT_PATH_STR_LEN), and the numbers in front of it
|
||||
// add 36 ("SNR -20.5 dB, RSSI -128 dBm, 63 hop "). 98 + NUL.
|
||||
//
|
||||
// It was 72, sized against the longest COMMAND rather than the longest PATH, and
|
||||
// that held only because !link had never been asked from further than 2 hops away.
|
||||
// Measured 7. 8. 2026: an 11-hop request wanted 88 chars, so the reply truncated at
|
||||
// 71 -- and with the old field order the part that got cut was exactly the SNR/RSSI
|
||||
// the command exists to report ("... 209f:34fa:ed9c, SNR 4.0 ").
|
||||
#define BOT_FRAG_LEN 100
|
||||
|
||||
// Registers the bot channel in the shared registry (ChannelCommon.h does the
|
||||
// hex parse and hash derivation) and resets bot state. Called by channelsInit().
|
||||
void MyMesh::botInit() {
|
||||
bot_next_reply_at = 0;
|
||||
bot_replies_sent = 0;
|
||||
bot_ignored = 0;
|
||||
bot_throttled = 0;
|
||||
memset(bot_peers, 0, sizeof(bot_peers));
|
||||
memset(bot_burst_until, 0, sizeof(bot_burst_until));
|
||||
bot_burst_head = 0;
|
||||
bot_last_reply_secs = 0;
|
||||
|
||||
const char* psk = BOT_CHANNEL_PSK;
|
||||
bot_channel_idx = (int8_t)channelAddFromPsk(psk, strlen(psk), CHAN_FLAG_BOT);
|
||||
}
|
||||
|
||||
// Colon-separated per-hop hashes, the same self-describing convention the
|
||||
// analyzer's pktlog uses (analyzer_path_hex): the hash width is uniform per
|
||||
// packet but invisible in the hex, so ':' marks where one hop ends. Width comes
|
||||
// from the packet, NOT a constant -- one node on this mesh runs 3-byte hashes
|
||||
// deliberately. `out` must hold BOT_PATH_STR_LEN bytes.
|
||||
void MyMesh::botFormatPath(char* out, const mesh::Packet* pkt) const {
|
||||
static const char hexd[] = "0123456789abcdef";
|
||||
uint8_t cnt = pkt->getPathHashCount();
|
||||
uint8_t sz = pkt->getPathHashSize();
|
||||
if (cnt == 0 || sz == 0) { strcpy(out, "direct"); return; }
|
||||
|
||||
uint8_t max_hops = (BOT_PATH_STR_LEN - 1) / (sz * 2 + 1);
|
||||
char* p = out;
|
||||
uint8_t off = 0;
|
||||
for (uint8_t h = 0; h < cnt && h < max_hops && off + sz <= MAX_PATH_SIZE; h++) {
|
||||
if (h) *p++ = ':';
|
||||
for (uint8_t b = 0; b < sz; b++, off++) {
|
||||
*p++ = hexd[pkt->path[off] >> 4];
|
||||
*p++ = hexd[pkt->path[off] & 0x0F];
|
||||
}
|
||||
}
|
||||
*p = 0;
|
||||
}
|
||||
|
||||
// NOTE: exact-membership matching lives in chan_list_has() (ChannelCommon.h);
|
||||
// it is distinct from botTriggerMatches(), which is a SUBSTRING search -- an
|
||||
// ignore list or a command whitelist matching on substrings would be a trap
|
||||
// ("path" enabling "!pathx", a node called "TTH" silencing "tracker").
|
||||
|
||||
// One `!command` -> one text fragment. Returns chars written, 0 for unknown.
|
||||
// The interesting ones are the analyzer's: a companion bot cannot answer these
|
||||
// at all, because it has no rxlog and no heard registry.
|
||||
int MyMesh::botCommandReply(char* out, int max_len, const char* cmd, const mesh::Packet* pkt) {
|
||||
// An empty BOT_COMMANDS means "all"; otherwise only what is listed.
|
||||
if (BOT_COMMANDS[0] != 0 && !chan_list_has(BOT_COMMANDS, cmd)) return 0;
|
||||
|
||||
if (strcmp(cmd, "noise") == 0) {
|
||||
// Noise floor is the analyzer's own measurement -- a companion bot has no
|
||||
// way to answer this, which makes it worth owning on a shared channel.
|
||||
return snprintf(out, max_len, "noise floor %d dBm",
|
||||
(int)(int16_t)_radio->getNoiseFloor());
|
||||
}
|
||||
if (strcmp(cmd, "ping") == 0) {
|
||||
return snprintf(out, max_len, "pong");
|
||||
}
|
||||
if (strcmp(cmd, "path") == 0) {
|
||||
char path[BOT_PATH_STR_LEN];
|
||||
botFormatPath(path, pkt);
|
||||
return snprintf(out, max_len, "path %s (%d hop)", path, (int)pkt->getPathHashCount());
|
||||
}
|
||||
if (strcmp(cmd, "link") == 0) {
|
||||
// "Jaky mam link domu?" v jednom prikazu. Zamerne slouceny path+snr: tohle
|
||||
// se pta clovek v aute, ktery nema chut psat dva prikazy -- a jde o cestu
|
||||
// JEHO paketu k NAM, cili presne ten smer, ktery si na svem uzlu overit
|
||||
// neumi (tam vidi jen to, co prijima).
|
||||
// The path goes LAST on purpose. It is the only unbounded part of this reply
|
||||
// (0 to 62 chars, and the sender picks the hash width), so it is also the only
|
||||
// part that can push the answer over BOT_FRAG_LEN. Putting it after the numbers
|
||||
// means a truncation eats hops off the tail instead of eating the SNR/RSSI --
|
||||
// and a partial path is still useful, a missing link budget is not.
|
||||
char path[BOT_PATH_STR_LEN];
|
||||
botFormatPath(path, pkt);
|
||||
return snprintf(out, max_len, "SNR %.1f dB, RSSI %d dBm, %d hop %s",
|
||||
pkt->getSNR(), pkt->getRSSI(), (int)pkt->getPathHashCount(), path);
|
||||
}
|
||||
if (strcmp(cmd, "snr") == 0) {
|
||||
// Straight off the frame that carried the request -- the same numbers
|
||||
// captureRx() files into the rxlog ring.
|
||||
return snprintf(out, max_len, "SNR %.1f dB / RSSI %d dBm", pkt->getSNR(), pkt->getRSSI());
|
||||
}
|
||||
#if MAX_HEARD_NODES
|
||||
if (strcmp(cmd, "heard") == 0) {
|
||||
int n = 0;
|
||||
for (int i = 0; i < MAX_HEARD_NODES; i++) {
|
||||
if (heard_nodes[i].heard_timestamp > 0) n++;
|
||||
}
|
||||
return snprintf(out, max_len, "heard %d nodes", n);
|
||||
}
|
||||
#endif
|
||||
if (strcmp(cmd, "help") == 0) {
|
||||
return snprintf(out, max_len, "!ping !path !snr"
|
||||
#if MAX_HEARD_NODES
|
||||
" !heard"
|
||||
#endif
|
||||
);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Scan the message for `!word` tokens and join their answers with " | ", so
|
||||
// "!path !snr" costs one packet instead of two. Returns total chars, 0 if the
|
||||
// message held no recognised command.
|
||||
int MyMesh::botScanCommands(char* out, int max_len, const char* text, const mesh::Packet* pkt) {
|
||||
int written = 0;
|
||||
int found = 0;
|
||||
out[0] = 0;
|
||||
|
||||
for (const char* p = text; *p; ) {
|
||||
if (*p != '!') { p++; continue; }
|
||||
p++;
|
||||
char word[12];
|
||||
int wl = 0;
|
||||
while (*p && wl < (int)sizeof(word) - 1 && isalpha((unsigned char)*p)) {
|
||||
word[wl++] = tolower((unsigned char)*p);
|
||||
p++;
|
||||
}
|
||||
word[wl] = 0;
|
||||
if (wl == 0) continue;
|
||||
|
||||
char frag[BOT_FRAG_LEN];
|
||||
if (botCommandReply(frag, sizeof(frag), word, pkt) <= 0) continue;
|
||||
|
||||
int room = max_len - written;
|
||||
if (room <= 1) break;
|
||||
int adv = snprintf(out + written, room, "%s%s", found ? " | " : "", frag);
|
||||
if (adv < 0) break;
|
||||
if (adv >= room) { written = max_len - 1; found++; break; } // truncated, stop
|
||||
written += adv;
|
||||
found++;
|
||||
}
|
||||
return found ? written : 0;
|
||||
}
|
||||
|
||||
// Comma-separated list, case-insensitive substring match. "*" answers anything.
|
||||
bool MyMesh::botTriggerMatches(const char* text) const {
|
||||
const char* seg = BOT_TRIGGER;
|
||||
if (*seg == 0) return false;
|
||||
if (seg[0] == '*' && seg[1] == 0) return true;
|
||||
|
||||
while (*seg) {
|
||||
const char* comma = strchr(seg, ',');
|
||||
int len = comma ? (int)(comma - seg) : (int)strlen(seg);
|
||||
while (len > 0 && *seg == ' ') { seg++; len--; }
|
||||
while (len > 0 && seg[len - 1] == ' ') len--;
|
||||
|
||||
if (len > 0) {
|
||||
for (const char* t = text; *t; t++) {
|
||||
int i = 0;
|
||||
while (i < len && t[i] && tolower((unsigned char)t[i]) == tolower((unsigned char)seg[i])) i++;
|
||||
if (i == len) return true;
|
||||
}
|
||||
}
|
||||
if (!comma) break;
|
||||
seg = comma + 1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void MyMesh::botSendReply(const mesh::Packet* pkt, const char* text) {
|
||||
// Payload layout copied from BaseChatMesh::sendGroupMessage(): 4 B timestamp
|
||||
// (which is also what keeps the packet hash unique), 1 B text type, then
|
||||
// "<name>: <msg>" -- the prefix is how every client shows the sender, since a
|
||||
// channel packet carries no identity.
|
||||
uint8_t temp[5 + BOT_REPLY_LEN];
|
||||
uint32_t timestamp = getRTCClock()->getCurrentTimeUnique();
|
||||
memcpy(temp, ×tamp, 4);
|
||||
temp[4] = TXT_TYPE_PLAIN;
|
||||
|
||||
int n = snprintf((char*)&temp[5], BOT_REPLY_LEN, "%s: %s", _prefs.node_name, text);
|
||||
if (n < 0) return;
|
||||
if (n > BOT_REPLY_LEN - 1) n = BOT_REPLY_LEN - 1; // snprintf reports untruncated length
|
||||
|
||||
auto reply = createGroupDatagram(PAYLOAD_TYPE_GRP_TXT, known_channels[bot_channel_idx], temp, 5 + n);
|
||||
if (reply == NULL) {
|
||||
MESH_DEBUG_PRINTLN("botSendReply: packet pool empty");
|
||||
return;
|
||||
}
|
||||
// Mirror the request's path-hash width and transport scope, exactly like every
|
||||
// other reply this firmware sends (see the sendFloodReply call sites).
|
||||
sendFloodReply(reply, SERVER_RESPONSE_DELAY, pkt->getPathHashSize());
|
||||
bot_replies_sent++;
|
||||
bot_last_reply_secs = getRTCClock()->getCurrentTime();
|
||||
}
|
||||
|
||||
// Per-sender cooldown over a tiny LRU. Returns true and CLAIMS the window when
|
||||
// this sender may be answered now.
|
||||
bool MyMesh::botPeerAllowed(const char* name) {
|
||||
uint32_t h = 2166136261u; // FNV-1a over the lowercased name
|
||||
for (const char* p = name; *p; p++) h = (h ^ (uint8_t)tolower((unsigned char)*p)) * 16777619u;
|
||||
if (h == 0) h = 1; // 0 marks a free slot
|
||||
|
||||
int free_slot = -1, oldest = 0;
|
||||
for (int i = 0; i < BOT_PEER_SLOTS; i++) {
|
||||
if (bot_peers[i].name_hash == h) {
|
||||
if (!millisHasNowPassed(bot_peers[i].next_at)) return false; // still cooling
|
||||
bot_peers[i].next_at = futureMillis(BOT_REPLY_COOLDOWN_MS);
|
||||
return true;
|
||||
}
|
||||
if (bot_peers[i].name_hash == 0 && free_slot < 0) free_slot = i;
|
||||
// signed compare = wraparound-safe "which window expires soonest"
|
||||
if ((long)(bot_peers[i].next_at - bot_peers[oldest].next_at) < 0) oldest = i;
|
||||
}
|
||||
int slot = (free_slot >= 0) ? free_slot : oldest;
|
||||
bot_peers[slot].name_hash = h;
|
||||
bot_peers[slot].next_at = futureMillis(BOT_REPLY_COOLDOWN_MS);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Called from onChannelText() (ChannelCommon.h) for messages on the bot
|
||||
// channel only -- the "<sender>: <msg>" split already happened there, and a
|
||||
// sender on the ChannelFilter deny list never reaches this point.
|
||||
void MyMesh::botOnChannelText(mesh::Packet* packet, const char* sender, const char* msg) {
|
||||
// Bail out if the sender is us: our own reply comes back through the mesh and
|
||||
// would otherwise ping-pong forever. The cooldown alone would not stop that,
|
||||
// it would only slow it down.
|
||||
if (sender[0] != 0) {
|
||||
if (strcmp(sender, _prefs.node_name) == 0) return;
|
||||
// Peer bots: skip before any trigger or command matching. Measured need --
|
||||
// tracker puts "Ping" on this channel by itself, and answering those ate the
|
||||
// cooldown, so a human question landed in a closed window.
|
||||
if (BOT_IGNORE_SENDERS[0] != 0 && chan_list_has(BOT_IGNORE_SENDERS, sender)) {
|
||||
bot_ignored++;
|
||||
MESH_DEBUG_PRINTLN("bot: ignoruji odesilatele z BOT_IGNORE_SENDERS");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
char reply[BOT_REPLY_LEN];
|
||||
if (botScanCommands(reply, sizeof(reply), msg, packet) <= 0) {
|
||||
if (!botTriggerMatches(msg)) return;
|
||||
char path[BOT_PATH_STR_LEN];
|
||||
botFormatPath(path, packet);
|
||||
snprintf(reply, sizeof(reply), "pong (%s)", path);
|
||||
}
|
||||
|
||||
// Global floor first: it is the airtime guarantee and must hold regardless of
|
||||
// how many distinct senders are asking.
|
||||
if (bot_next_reply_at != 0 && !millisHasNowPassed(bot_next_reply_at)) {
|
||||
MESH_DEBUG_PRINTLN("bot: reply suppressed, global gap");
|
||||
bot_throttled++;
|
||||
return;
|
||||
}
|
||||
// Then the cap over the longer window: the slot at head holds the oldest of
|
||||
// the last BOT_BURST_MAX replies, and while its window runs we are at the cap.
|
||||
// Checked before botPeerAllowed(), which claims the sender's window.
|
||||
if (BOT_BURST_MAX > 0 && bot_burst_until[bot_burst_head] != 0
|
||||
&& !millisHasNowPassed(bot_burst_until[bot_burst_head])) {
|
||||
MESH_DEBUG_PRINTLN("bot: reply suppressed, burst cap");
|
||||
bot_throttled++;
|
||||
return;
|
||||
}
|
||||
// Then this sender's own window. Name-based, so spoofable -- fine, this is a
|
||||
// politeness throttle and channel messages carry no identity anyway.
|
||||
if (!botPeerAllowed(sender)) {
|
||||
MESH_DEBUG_PRINTLN("bot: reply suppressed, sender cooldown");
|
||||
bot_throttled++;
|
||||
return;
|
||||
}
|
||||
bot_next_reply_at = futureMillis(BOT_MIN_GAP_MS);
|
||||
if (bot_next_reply_at == 0) bot_next_reply_at = 1; // 0 means "not armed"
|
||||
if (BOT_BURST_MAX > 0) {
|
||||
unsigned long until = futureMillis(BOT_BURST_WINDOW_MS);
|
||||
bot_burst_until[bot_burst_head] = until ? until : 1; // 0 means "free slot"
|
||||
bot_burst_head = (bot_burst_head + 1) % (BOT_BURST_MAX > 0 ? BOT_BURST_MAX : 1);
|
||||
}
|
||||
|
||||
botSendReply(packet, reply);
|
||||
}
|
||||
|
||||
// `bot` -- read-only diagnostics. Trigger and reply text stay build-time, so
|
||||
// there is nothing here to set: this is for answering "is it actually armed,
|
||||
// and has it ever spoken?" without a client on the channel.
|
||||
bool MyMesh::botHandleCommand(const char* command, char* reply) {
|
||||
if (memcmp(command, "bot", 3) != 0 || (command[3] != 0 && command[3] != ' ')) return false;
|
||||
|
||||
if (bot_channel_idx < 0) {
|
||||
strcpy(reply, "bot: DISABLED (bad BOT_CHANNEL_PSK)");
|
||||
return true;
|
||||
}
|
||||
// Short keys and snprintf: a remote CLI reply has 161 B (MyMesh.cpp temp[166]
|
||||
// minus header), and the old long form already overran it with a real cmds list.
|
||||
snprintf(reply, 161, "bot: ch %02X trig '%s' cmds '%s' ign '%s' cd %dms/odes + %dms, max %d/%ds, odp %u thr %u ign %u last %u",
|
||||
(uint32_t)known_channels[bot_channel_idx].hash[0], BOT_TRIGGER,
|
||||
BOT_COMMANDS[0] ? BOT_COMMANDS : "(vse)",
|
||||
BOT_IGNORE_SENDERS[0] ? BOT_IGNORE_SENDERS : "(nikdo)",
|
||||
(int)BOT_REPLY_COOLDOWN_MS, (int)BOT_MIN_GAP_MS,
|
||||
(int)BOT_BURST_MAX, (int)(BOT_BURST_WINDOW_MS / 1000),
|
||||
(uint32_t)bot_replies_sent, (uint32_t)bot_throttled,
|
||||
(uint32_t)bot_ignored, (uint32_t)bot_last_reply_secs);
|
||||
return true;
|
||||
}
|
||||
|
||||
#endif // BOT_CHANNEL_PSK
|
||||
@@ -0,0 +1,189 @@
|
||||
#pragma once
|
||||
|
||||
// CUSTOM (TeTeHacko): shared channel plumbing for ChannelBot.h and
|
||||
// ChannelFilter.h -- not part of upstream simple_repeater. Included at the
|
||||
// bottom of MyMesh.cpp (before the other two), so these are plain MyMesh
|
||||
// methods with full access to state.
|
||||
//
|
||||
// A repeater is normally deaf to channel traffic only because the two virtuals
|
||||
// below are no-ops in mesh::Mesh (Mesh.h:160, Mesh.cpp:37). Overriding them
|
||||
// decrypts matching GRP_TXT packets on the side; forwarding is untouched --
|
||||
// Mesh::onRecvPacket() calls routeRecvPacket() either way (Mesh.cpp:237-259).
|
||||
// The ONE deliberate exception is the ChannelFilter veto in onChannelText(),
|
||||
// which uses packet->markDoNotRetransmit() -- the exact mechanism the ANON
|
||||
// branch uses at Mesh.cpp:229 -- to stop THIS node re-airing a matched packet.
|
||||
//
|
||||
// Registry slots are MAX_KNOWN_CHANNELS(4) because searchChannelsByHash()
|
||||
// callers cap matches at 4 (Mesh.cpp:247). A channel named by both the bot and
|
||||
// the filter shares one slot (flags are OR-ed).
|
||||
|
||||
#if defined(BOT_CHANNEL_PSK) || defined(FILTER_CHANNEL_PSKS)
|
||||
|
||||
#include "ChanListUtil.h"
|
||||
|
||||
// Inbound text, after decrypt: 4 B timestamp + 1 B type + "sender: msg".
|
||||
#define CHAN_TEXT_LEN 160
|
||||
|
||||
// The PSK is given as HEX, which is exactly the form `meshcore-cli get_channel
|
||||
// <n>` prints -- no base64 round trip by hand, and no base64.hpp dependency in
|
||||
// this build (only companion_radio pulls that in). 32 hex chars = 128-bit key
|
||||
// (what the phone app generates), 64 = 256-bit. Shorter keys are zero-padded in
|
||||
// the 32-byte secret, same as BaseChatMesh::addChannel().
|
||||
// Returns the registry index, or -1 (bad hex/length, or registry full).
|
||||
int MyMesh::channelAddFromPsk(const char* psk_hex, int psk_len, uint8_t flag) {
|
||||
if (psk_len != 32 && psk_len != 64) {
|
||||
MESH_DEBUG_PRINTLN("channelAddFromPsk: PSK must be 32 or 64 hex chars, got %d", psk_len);
|
||||
return -1;
|
||||
}
|
||||
int key_len = psk_len / 2;
|
||||
uint8_t secret[PUB_KEY_SIZE];
|
||||
memset(secret, 0, sizeof(secret));
|
||||
for (int i = 0; i < key_len; i++) {
|
||||
int hi = chan_hex_nibble(psk_hex[i * 2]);
|
||||
int lo = chan_hex_nibble(psk_hex[i * 2 + 1]);
|
||||
if (hi < 0 || lo < 0) {
|
||||
MESH_DEBUG_PRINTLN("channelAddFromPsk: PSK is not hex");
|
||||
return -1;
|
||||
}
|
||||
secret[i] = (uint8_t)((hi << 4) | lo);
|
||||
}
|
||||
|
||||
// one slot per channel: a PSK named twice (bot + filter) just ORs its flags
|
||||
for (int i = 0; i < num_known_channels; i++) {
|
||||
if (memcmp(known_channels[i].secret, secret, sizeof(secret)) == 0) {
|
||||
known_channel_flags[i] |= flag;
|
||||
return i;
|
||||
}
|
||||
}
|
||||
if (num_known_channels >= MAX_KNOWN_CHANNELS) {
|
||||
MESH_DEBUG_PRINTLN("channelAddFromPsk: registry full (%d)", MAX_KNOWN_CHANNELS);
|
||||
return -1;
|
||||
}
|
||||
int idx = num_known_channels++;
|
||||
memcpy(known_channels[idx].secret, secret, sizeof(secret));
|
||||
// Same derivation as BaseChatMesh::addChannel() (hash over the REAL key
|
||||
// length, not the padded 32), so the hash matches what every other node
|
||||
// computes. Cross-checked live: the 128-bit #tth-test key hashes to 0x75.
|
||||
mesh::Utils::sha256(known_channels[idx].hash, sizeof(known_channels[idx].hash),
|
||||
known_channels[idx].secret, key_len);
|
||||
known_channel_flags[idx] = flag;
|
||||
return idx;
|
||||
}
|
||||
|
||||
void MyMesh::channelsInit() {
|
||||
num_known_channels = 0;
|
||||
memset(known_channels, 0, sizeof(known_channels));
|
||||
memset(known_channel_flags, 0, sizeof(known_channel_flags));
|
||||
#ifdef FILTER_CHANNEL_PSKS
|
||||
filter_dropped = 0;
|
||||
filter_age_dropped = 0;
|
||||
{
|
||||
// comma-separated hex PSKs
|
||||
const char* seg = FILTER_CHANNEL_PSKS;
|
||||
while (*seg) {
|
||||
const char* comma = strchr(seg, ',');
|
||||
int len = comma ? (int)(comma - seg) : (int)strlen(seg);
|
||||
channelAddFromPsk(seg, len, CHAN_FLAG_FILTER);
|
||||
if (!comma) break;
|
||||
seg = comma + 1;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#ifdef BOT_CHANNEL_PSK
|
||||
botInit();
|
||||
#endif
|
||||
}
|
||||
|
||||
// Mirrors BaseChatMesh::searchChannelsByHash() over the registry. Matching on
|
||||
// hash[0] alone is upstream's design: PATH_HASH_SIZE is 1, so collisions are
|
||||
// expected and resolved by MACThenDecrypt() failing in the caller.
|
||||
int MyMesh::searchChannelsByHash(const uint8_t* hash, mesh::GroupChannel channels[], int max_matches) {
|
||||
int n = 0;
|
||||
for (int i = 0; i < num_known_channels && n < max_matches; i++) {
|
||||
if (known_channels[i].hash[0] == hash[0]) {
|
||||
channels[n++] = known_channels[i];
|
||||
}
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
void MyMesh::onGroupDataRecv(mesh::Packet* packet, uint8_t type, const mesh::GroupChannel& channel,
|
||||
uint8_t* data, size_t len) {
|
||||
if (type != PAYLOAD_TYPE_GRP_TXT) return; // GRP_DATA (telemetry etc.) is not ours
|
||||
if (len < 5) return;
|
||||
|
||||
// which registry entry decrypted this? (the caller passes a COPY, not our slot)
|
||||
int chan_idx = -1;
|
||||
for (int i = 0; i < num_known_channels; i++) {
|
||||
if (memcmp(known_channels[i].secret, channel.secret, sizeof(channel.secret)) == 0) {
|
||||
chan_idx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (chan_idx < 0) return;
|
||||
|
||||
#ifdef FILTER_CHANNEL_PSKS
|
||||
// `filter age` (ChannelFilter.h): any group text, not only plain ones -- the
|
||||
// timestamp leads every GRP_TXT. Same veto as the deny list below.
|
||||
if (known_channel_flags[chan_idx] & CHAN_FLAG_FILTER) {
|
||||
uint32_t sender_ts;
|
||||
memcpy(&sender_ts, data, 4);
|
||||
if (msgAgeCheck(sender_ts, getRTCClock()->getCurrentTime(), _prefs.filter_age_min) == MSG_AGE_OLD) {
|
||||
filter_age_dropped++;
|
||||
if (!_prefs.filter_dry_run) {
|
||||
packet->markDoNotRetransmit();
|
||||
MESH_DEBUG_PRINTLN("filter: drop fwd, zprava starsi nez %u min", _prefs.filter_age_min);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
if ((data[4] >> 2) != 0) return; // only plain text, per BaseChatMesh.cpp:374
|
||||
|
||||
// Work on a bounded copy. Upstream NUL-terminates the caller's buffer in place
|
||||
// (data[len] = 0), which is fine there but relies on headroom this function
|
||||
// cannot verify -- and every other parse in this fork is bounds-checked.
|
||||
char text[CHAN_TEXT_LEN];
|
||||
size_t body = len - 5;
|
||||
if (body >= sizeof(text)) body = sizeof(text) - 1;
|
||||
memcpy(text, &data[5], body);
|
||||
text[body] = 0;
|
||||
|
||||
// "<sender>: <msg>". A channel packet carries no identity; this prefix is the
|
||||
// only sender there is (and therefore spoofable -- see ChannelFilter.h).
|
||||
const char* sender = "";
|
||||
const char* msg = text;
|
||||
char* sep = strstr(text, ": ");
|
||||
if (sep) {
|
||||
*sep = 0;
|
||||
sender = text;
|
||||
msg = sep + 2;
|
||||
}
|
||||
onChannelText(packet, chan_idx, sender, msg);
|
||||
}
|
||||
|
||||
void MyMesh::onChannelText(mesh::Packet* packet, int chan_idx, const char* sender, const char* msg) {
|
||||
#ifdef FILTER_CHANNEL_PSKS
|
||||
if ((known_channel_flags[chan_idx] & CHAN_FLAG_FILTER)
|
||||
&& sender[0] != 0 && filterDenied(sender)) {
|
||||
// Veto the forward of THIS packet -- routeRecvPacket() checks the mark
|
||||
// (Mesh.cpp:357). Local processing already happened (rxlog/pktfeed capture
|
||||
// on receive), so the observer evidence trail is intact; the node just
|
||||
// refuses to re-air it. And the bot must not answer a denied sender either.
|
||||
filter_dropped++;
|
||||
if (!_prefs.filter_dry_run) { // dry-run: counted, but forwarded
|
||||
packet->markDoNotRetransmit();
|
||||
MESH_DEBUG_PRINTLN("filter: drop fwd, sender na deny listu");
|
||||
}
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
#ifdef BOT_CHANNEL_PSK
|
||||
if (chan_idx == bot_channel_idx) {
|
||||
botOnChannelText(packet, sender, msg);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#endif // BOT_CHANNEL_PSK || FILTER_CHANNEL_PSKS
|
||||
@@ -0,0 +1,290 @@
|
||||
#pragma once
|
||||
|
||||
// CUSTOM (TeTeHacko): channel-message deny list -- not part of upstream
|
||||
// simple_repeater. Included at the bottom of MyMesh.cpp, after ChannelCommon.h.
|
||||
//
|
||||
// WHAT THIS IS (and is not)
|
||||
//
|
||||
// A repeater that knows a channel's PSK (FILTER_CHANNEL_PSKS, see
|
||||
// ChannelCommon.h) decrypts each GRP_TXT on it and refuses to FORWARD messages
|
||||
// whose "<sender>: " prefix is on a runtime deny list. Born 5. 9. 2026, when a
|
||||
// runaway AI bot looped an 11-part Gemini quota dump onto #meshcore for hours
|
||||
// and every repeater dutifully re-aired it.
|
||||
//
|
||||
// * The sender name is just text inside the encrypted payload -- GRP_TXT
|
||||
// carries NO identity (only adverts do). Anyone can rename around this.
|
||||
// It is containment of a runaway/rude node, not security. (For the
|
||||
// content-neutral automatic layer, see FairnessLimiter.h.)
|
||||
// * Only forwarding by THIS node is affected. Reception, rxlog/pktfeed
|
||||
// capture (CoreScope feed) and the rest of the mesh are untouched.
|
||||
// * DIRECT-routed packets are not seen here (their forward is decided before
|
||||
// any decrypt, Mesh.cpp:94) -- channel messages flood, so in practice this
|
||||
// covers them.
|
||||
// * Upstream would not take this (privacy/no-censorship principles, see
|
||||
// issue #169 discussion) -- fork-only, do not upstream.
|
||||
//
|
||||
// The deny list lives in _prefs.filter_deny (comma-separated exact names,
|
||||
// case-insensitive) so the stock savePrefs()/loadPrefs() machinery persists
|
||||
// it, and it is editable at runtime over RF admin: an incident response is
|
||||
// `filter add <name>`, not a mast reflash.
|
||||
|
||||
#ifdef FILTER_CHANNEL_PSKS
|
||||
|
||||
bool MyMesh::filterDenied(const char* sender) const {
|
||||
if (_prefs.filter_deny[0] == 0) return false;
|
||||
return chan_list_has(_prefs.filter_deny, sender);
|
||||
}
|
||||
|
||||
// `filter` / `filter list` -- show state; `filter add|del <name>` -- edit;
|
||||
// `filter clear` -- empty the list. Names may contain spaces (everything after
|
||||
// the subcommand is the name); commas are the storage separator so they are
|
||||
// rejected. Matching is exact and case-insensitive (chan_list_has).
|
||||
bool MyMesh::filterHandleCommand(const char* command, char* reply, int reply_max) {
|
||||
if (memcmp(command, "filter", 6) != 0 || (command[6] != 0 && command[6] != ' ')) return false;
|
||||
|
||||
if (memcmp(&command[6], " add ", 5) == 0) {
|
||||
const char* name = &command[11];
|
||||
int rc = chan_list_add(_prefs.filter_deny, sizeof(_prefs.filter_deny), name, strlen(name));
|
||||
if (rc == CHAN_LIST_OK) {
|
||||
savePrefs();
|
||||
snprintf(reply, reply_max, "OK - deny: %s", _prefs.filter_deny);
|
||||
} else if (rc == CHAN_LIST_DUP) {
|
||||
strcpy(reply, "Err - already listed");
|
||||
} else if (rc == CHAN_LIST_FULL) {
|
||||
strcpy(reply, "Err - list full");
|
||||
} else {
|
||||
strcpy(reply, "Err - bad name (empty, too long, or contains ',')");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (memcmp(&command[6], " del ", 5) == 0) {
|
||||
if (chan_list_del(_prefs.filter_deny, &command[11])) {
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Err - not listed");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (strcmp(&command[6], " clear") == 0) {
|
||||
_prefs.filter_deny[0] = 0;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK - deny list cleared");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (command[6] == 0 || strcmp(&command[6], " list") == 0) {
|
||||
snprintf(reply, reply_max, "filter: %d chan, dropped %u, deny: %s",
|
||||
(int)num_known_channels, filter_dropped,
|
||||
_prefs.filter_deny[0] ? _prefs.filter_deny : "(nikdo)");
|
||||
return true;
|
||||
}
|
||||
|
||||
strcpy(reply, "Err - filter [add|del <name>|list|clear|hash|age|dryrun]");
|
||||
return true;
|
||||
}
|
||||
|
||||
#endif // FILTER_CHANNEL_PSKS
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Keyless deny-forward by CHANNEL HASH -- independent of FILTER_CHANNEL_PSKS.
|
||||
//
|
||||
// The deny list above needs the PSK, so it can never touch a private channel.
|
||||
// This one needs nothing: payload[0] of GRP_TXT/GRP_DATA is the channel hash,
|
||||
// in the clear, and a repeater can refuse to re-air every packet carrying it.
|
||||
// Born 14. 10. 2026 for 0x43 (one private chat+bot = 43 % of the airtime on
|
||||
// the CZ mesh, reflooded all the way to remote-mast); FairnessLimiter only
|
||||
// throttled it blindly, and its group bucket (hash & 0x1F) collides with
|
||||
// 0x23/0x63/... anyway.
|
||||
//
|
||||
// * Content-neutral and coarse: the hash is 1 byte, so a deny entry also
|
||||
// hits every OTHER channel whose key happens to hash to the same byte.
|
||||
// Check the analyzer for what else lives on a byte before denying it.
|
||||
// * Only forwarding by THIS node: reception and rxlog/pktfeed capture
|
||||
// (CoreScope feed) happen before routeRecvPacket(), so the evidence trail
|
||||
// stays intact.
|
||||
// * Runtime-editable over RF admin and persisted in prefs (f_dhash/f_dhash_n),
|
||||
// so an incident response is `filter hash add 43`, not a mast reflash.
|
||||
//
|
||||
// THROTTLE (tth #3, 2. 11. 2026): an entry may carry an interval --
|
||||
// `filter hash add 43 60` lets one packet of that byte through per 60 s and
|
||||
// drops the rest, so a chatty channel is tamed instead of cut off. The window
|
||||
// state is RAM only (first match after boot passes) and only a pass moves it;
|
||||
// see HashThrottle in src/helpers/ChannelGate.h. Interval 0 = block, as before.
|
||||
//
|
||||
// `filter dryrun on` counts every verdict of `filter` (hash, age, sender deny)
|
||||
// but forwards anyway -- the way to try a new rule on a live mast.
|
||||
|
||||
bool MyMesh::filterHashDenied(const mesh::Packet* packet) {
|
||||
uint8_t n = _prefs.deny_hash_n;
|
||||
if (n == 0) return false;
|
||||
uint8_t type = packet->getPayloadType();
|
||||
if (type != PAYLOAD_TYPE_GRP_TXT && type != PAYLOAD_TYPE_GRP_DATA) return false;
|
||||
if (packet->payload_len < 1) return false;
|
||||
if (n > sizeof(_prefs.deny_hash)) n = sizeof(_prefs.deny_hash);
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (_prefs.deny_hash[i] != packet->payload[0]) continue;
|
||||
uint16_t secs = _prefs.deny_hash_secs[i];
|
||||
if (secs != 0 && hash_throttle.pass(i, secs, millis())) {
|
||||
filter_hash_passed++;
|
||||
return false;
|
||||
}
|
||||
filter_hash_dropped++;
|
||||
return !_prefs.filter_dry_run;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// `filter hash` -- show list + counters (passed = let through by a throttle);
|
||||
// `filter hash add <hex> [secs]` -- block (no secs / 0) or throttle to one
|
||||
// packet per secs; re-adding a listed byte changes its interval;
|
||||
// `filter hash del <hex>`; `filter hash clear`.
|
||||
// Listing: `43` = blocked, `43/60` = throttled to one per 60 s. The Ansible
|
||||
// module (tth.meshcore.meshcore_filter_hash) parses this line -- keep the
|
||||
// "filter hash: dropped N, passed M, deny:" shape stable.
|
||||
bool MyMesh::filterHashHandleCommand(const char* command, char* reply, int reply_max) {
|
||||
if (memcmp(command, "filter hash", 11) != 0 || (command[11] != 0 && command[11] != ' ')) return false;
|
||||
|
||||
const char* arg = (command[11] == ' ') ? &command[12] : "";
|
||||
uint8_t n = _prefs.deny_hash_n;
|
||||
if (n > sizeof(_prefs.deny_hash)) n = sizeof(_prefs.deny_hash);
|
||||
|
||||
if (strcmp(arg, "clear") == 0) {
|
||||
_prefs.deny_hash_n = 0;
|
||||
memset(_prefs.deny_hash, 0, sizeof(_prefs.deny_hash));
|
||||
memset(_prefs.deny_hash_secs, 0, sizeof(_prefs.deny_hash_secs));
|
||||
hash_throttle.reset();
|
||||
savePrefs();
|
||||
strcpy(reply, "OK - hash deny list cleared");
|
||||
return true;
|
||||
}
|
||||
|
||||
bool is_add = strncmp(arg, "add ", 4) == 0;
|
||||
bool is_del = strncmp(arg, "del ", 4) == 0;
|
||||
if (is_add || is_del) {
|
||||
const char* hex = arg + 4;
|
||||
if (hex[0] == '0' && (hex[1] == 'x' || hex[1] == 'X')) hex += 2;
|
||||
char* end;
|
||||
long v = strtol(hex, &end, 16);
|
||||
if (end == hex || (*end != 0 && *end != ' ') || end - hex > 2 || v < 0 || v > 0xFF) {
|
||||
strcpy(reply, "Err - 1 byte hex, e.g. 43");
|
||||
return true;
|
||||
}
|
||||
long secs = 0;
|
||||
if (*end == ' ') {
|
||||
if (is_del) { strcpy(reply, "Err - filter hash del <hex>"); return true; }
|
||||
const char* s = end + 1;
|
||||
secs = strtol(s, &end, 10);
|
||||
if (end == s || *end != 0 || secs < 0 || secs > 65535) {
|
||||
strcpy(reply, "Err - secs 0..65535 (0 = block)");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
int at = -1;
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (_prefs.deny_hash[i] == (uint8_t)v) { at = i; break; }
|
||||
}
|
||||
if (is_add) {
|
||||
if (at >= 0) {
|
||||
if (_prefs.deny_hash_secs[at] == (uint16_t)secs) { strcpy(reply, "Err - already listed"); return true; }
|
||||
_prefs.deny_hash_secs[at] = (uint16_t)secs; // change of interval
|
||||
hash_throttle.reset(at);
|
||||
} else {
|
||||
if (n >= sizeof(_prefs.deny_hash)) { strcpy(reply, "Err - list full"); return true; }
|
||||
_prefs.deny_hash[n] = (uint8_t)v;
|
||||
_prefs.deny_hash_secs[n] = (uint16_t)secs;
|
||||
hash_throttle.reset(n);
|
||||
n++;
|
||||
}
|
||||
} else {
|
||||
if (at < 0) { strcpy(reply, "Err - not listed"); return true; }
|
||||
for (int i = at; i + 1 < n; i++) {
|
||||
_prefs.deny_hash[i] = _prefs.deny_hash[i + 1];
|
||||
_prefs.deny_hash_secs[i] = _prefs.deny_hash_secs[i + 1];
|
||||
}
|
||||
hash_throttle.remove(at);
|
||||
--n;
|
||||
_prefs.deny_hash[n] = 0;
|
||||
_prefs.deny_hash_secs[n] = 0;
|
||||
}
|
||||
_prefs.deny_hash_n = n;
|
||||
savePrefs();
|
||||
// fall through to the listing as the reply
|
||||
} else if (arg[0] != 0 && strcmp(arg, "list") != 0) {
|
||||
strcpy(reply, "Err - filter hash [add <hex> [secs]|del <hex>|list|clear]");
|
||||
return true;
|
||||
}
|
||||
|
||||
int len = snprintf(reply, reply_max, "filter hash: dropped %u, passed %u, deny:",
|
||||
filter_hash_dropped, filter_hash_passed);
|
||||
if (n == 0 && len < reply_max) len += snprintf(&reply[len], reply_max - len, " (nic)");
|
||||
for (int i = 0; i < n && len < reply_max; i++) {
|
||||
if (_prefs.deny_hash_secs[i]) {
|
||||
len += snprintf(&reply[len], reply_max - len, " %02X/%u", _prefs.deny_hash[i], _prefs.deny_hash_secs[i]);
|
||||
} else {
|
||||
len += snprintf(&reply[len], reply_max - len, " %02X", _prefs.deny_hash[i]);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// `filter dryrun [on|off]` -- verdicts of `filter` (hash, age, sender deny)
|
||||
// are counted but the packet is forwarded anyway. Persisted (f_dry).
|
||||
// `filter age [<min>|off]` -- refuse to forward a group text the node can
|
||||
// DECRYPT (channels of FILTER_CHANNEL_PSKS) whose sender timestamp is older
|
||||
// than <min> minutes by THIS node's clock (1..10080). Off by default.
|
||||
// * It judges the sender's clock: a companion that never got a time sync
|
||||
// stamps 2024 and is dropped. On the CZ mesh 2. 11. 2026 every one of the
|
||||
// 5/2026 messages older than 10 min was such a clock, none a reflood --
|
||||
// hence opt-in, and days rather than minutes.
|
||||
// * Inactive while our own clock reads before 2026 (RTC-less boot). A clock
|
||||
// running AHEAD is not detected and makes everything look old -- check the
|
||||
// drift (tools/fw_status.py) before turning it on.
|
||||
bool MyMesh::filterMiscHandleCommand(const char* command, char* reply, int reply_max) {
|
||||
if (strcmp(command, "filter dryrun") == 0 || strcmp(command, "filter dryrun on") == 0
|
||||
|| strcmp(command, "filter dryrun off") == 0) {
|
||||
if (command[13] == ' ') {
|
||||
_prefs.filter_dry_run = (command[15] == 'n') ? 1 : 0;
|
||||
savePrefs();
|
||||
snprintf(reply, reply_max, "OK - filter dry-run %s", _prefs.filter_dry_run ? "on" : "off");
|
||||
} else {
|
||||
snprintf(reply, reply_max, "filter dry-run %s", _prefs.filter_dry_run ? "on" : "off");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (memcmp(command, "filter age", 10) != 0 || (command[10] != 0 && command[10] != ' ')) return false;
|
||||
#ifndef FILTER_CHANNEL_PSKS
|
||||
strcpy(reply, "Err - no channel keys in this build (FILTER_CHANNEL_PSKS)");
|
||||
return true;
|
||||
#else
|
||||
const char* arg = (command[10] == ' ') ? &command[11] : "";
|
||||
bool changed = false;
|
||||
if (strcmp(arg, "off") == 0) {
|
||||
_prefs.filter_age_min = 0;
|
||||
changed = true;
|
||||
} else if (arg[0] != 0) {
|
||||
char* end;
|
||||
long v = strtol(arg, &end, 10);
|
||||
if (end == arg || *end != 0 || v < 0 || v > MSG_AGE_MAX_MINUTES) {
|
||||
snprintf(reply, reply_max, "Err - filter age <1..%d min>|off", MSG_AGE_MAX_MINUTES);
|
||||
return true;
|
||||
}
|
||||
_prefs.filter_age_min = (uint16_t)v;
|
||||
changed = true;
|
||||
}
|
||||
if (changed) savePrefs();
|
||||
|
||||
if (_prefs.filter_age_min == 0) {
|
||||
snprintf(reply, reply_max, "%sfilter age off, dropped %u", changed ? "OK - " : "", filter_age_dropped);
|
||||
} else {
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
snprintf(reply, reply_max, "%sfilter age %um%s%s, dropped %u", changed ? "OK - " : "",
|
||||
_prefs.filter_age_min, _prefs.filter_dry_run ? " DRY-RUN" : "",
|
||||
now < MSG_AGE_CLOCK_VALID_FROM ? " (clock not set, inactive)" : "", filter_age_dropped);
|
||||
}
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -27,12 +27,15 @@
|
||||
#include <helpers/AdvertDataHelpers.h>
|
||||
#include <helpers/ArduinoHelpers.h>
|
||||
#include <helpers/ClientACL.h>
|
||||
#include <helpers/LoginGuard.h> // CUSTOM (TeTeHacko)
|
||||
#include <helpers/CommonCLI.h>
|
||||
#include <helpers/IdentityStore.h>
|
||||
#include <helpers/SimpleMeshTables.h>
|
||||
#include <helpers/StaticPoolPacketManager.h>
|
||||
#include <helpers/StatsFormatHelper.h>
|
||||
#include <helpers/TxtDataHelpers.h>
|
||||
#include <helpers/FairnessLimiter.h>
|
||||
#include <helpers/ChannelGate.h>
|
||||
#include <helpers/RegionMap.h>
|
||||
#include <helpers/RoutingPolicy.h>
|
||||
#include "RateLimiter.h"
|
||||
@@ -57,11 +60,30 @@ struct RepeaterStats {
|
||||
uint16_t n_direct_dups, n_flood_dups;
|
||||
uint32_t total_rx_air_time_secs;
|
||||
uint32_t n_recv_errors;
|
||||
// CUSTOM (TeTeHacko): appended at the END on purpose. Clients parse this
|
||||
// struct by fixed offsets, so fields added here are simply invisible to older
|
||||
// ones instead of shifting everything after them -- the same way upstream
|
||||
// grew its companion stats frame (docs/stats_binary_frames.md documents a
|
||||
// 26-byte "legacy" and a 30-byte frame that appends recv_errors).
|
||||
//
|
||||
// These two come from the Dispatcher requeue counters. Without them a
|
||||
// repeater that keeps failing to get its transmits out looks perfectly
|
||||
// healthy in every other field: sent/airtime just stop growing, and there is
|
||||
// nothing in the status that says why.
|
||||
uint32_t n_tx_start_fail, n_tx_timeout;
|
||||
};
|
||||
|
||||
#ifndef MAX_CLIENTS
|
||||
#define MAX_CLIENTS 32
|
||||
#endif
|
||||
// This struct goes on the air byte-for-byte, so its size is part of the
|
||||
// protocol: 56 bytes up to n_recv_errors (what upstream clients expect and
|
||||
// gate on -- meshcore-py's parse_status() reads recv_errors only
|
||||
// `if len(data) >= offset + 56`), plus the 8 appended here. Reordering a field
|
||||
// or letting the compiler insert padding would silently shift every offset
|
||||
// after it, so pin the number instead of trusting review.
|
||||
static_assert(sizeof(RepeaterStats) == 64,
|
||||
"RepeaterStats is a wire format: append only, keep it padding-free");
|
||||
|
||||
// MAX_CLIENTS zrusen tady mergem origin/dev (e0031870, "centralise max clients"):
|
||||
// od te doby ho definuje src/helpers/ClientACL.h, ktery se sem stejne dostane.
|
||||
|
||||
struct NeighbourInfo {
|
||||
mesh::Identity id;
|
||||
@@ -70,16 +92,100 @@ struct NeighbourInfo {
|
||||
int8_t snr; // multiplied by 4, user should divide to get float value
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CUSTOM (TeTeHacko): passive "mesh analyzer" data. Two independent, RAM-only
|
||||
// tables (both compiled out unless the build sets a non-zero size), fed from
|
||||
// the normal RX path and pulled out over the text console (serial / BLE) for a
|
||||
// map/bridge to consume:
|
||||
// * heard_nodes[] -- one row per DISTINCT REPEATER / ROOM SERVER whose
|
||||
// (verified) advert we heard (chat clients are intentionally skipped for
|
||||
// privacy): pubkey prefix, name, type, position, last SNR/RSSI and the path
|
||||
// the advert arrived by. -> map dots + topology edges + link quality.
|
||||
// Exposed by the `nodes [offset]` CLI command.
|
||||
// * rxlog_ring[] -- a circular firehose of EVERY parsed frame we hear:
|
||||
// capture seq, time, packet hash, header (route|type), SNR/RSSI and the hop
|
||||
// path. -> live traffic / analyzer view.
|
||||
// Exposed by the `rxlog [cursor]` CLI command.
|
||||
// * pktfeed_ring[] -- like rxlog but with the FULL RAW FRAME BYTES, for the
|
||||
// community observer feed (meshcoretomqtt-compatible: the bridge derives
|
||||
// type/route/payload and the SHA256 packet hash from the raw bytes).
|
||||
// Smaller ring -- raw frames are fat (~268 B/record).
|
||||
// Exposed by the `pktlog [cursor]` CLI command.
|
||||
// Enable per-variant, e.g.: -D MAX_HEARD_NODES=48 -D RXLOG_SIZE=96 -D PKTFEED_SIZE=32
|
||||
// ---------------------------------------------------------------------------
|
||||
#ifndef MAX_HEARD_NODES
|
||||
#define MAX_HEARD_NODES 0
|
||||
#endif
|
||||
#ifndef RXLOG_SIZE
|
||||
#define RXLOG_SIZE 0
|
||||
#endif
|
||||
#ifndef PKTFEED_SIZE
|
||||
#define PKTFEED_SIZE 0
|
||||
#endif
|
||||
#ifndef HEARD_NODE_NAME_LEN
|
||||
#define HEARD_NODE_NAME_LEN 24
|
||||
#endif
|
||||
#ifndef HEARD_NODE_PREFIX
|
||||
#define HEARD_NODE_PREFIX 6 // bytes of pub_key kept (resolve path hashes + registry cross-ref)
|
||||
#endif
|
||||
#ifndef ANALYZER_PATH_LEN
|
||||
#define ANALYZER_PATH_LEN 16 // max hop-hash bytes kept per record
|
||||
#endif
|
||||
#ifndef HEARD_DIRECT_TTL_SECS
|
||||
#define HEARD_DIRECT_TTL_SECS 3600 // keep showing a node as direct (0-hop) this long after last hearing it direct
|
||||
#endif
|
||||
|
||||
#if MAX_HEARD_NODES
|
||||
struct HeardNode {
|
||||
uint8_t pub_prefix[HEARD_NODE_PREFIX];
|
||||
char name[HEARD_NODE_NAME_LEN];
|
||||
int32_t lat, lon; // degrees x 1e6, 0 = unknown
|
||||
uint32_t heard_timestamp; // epoch when last heard (0 = empty slot)
|
||||
uint32_t advert_timestamp; // advert's own timestamp (newest wins)
|
||||
uint32_t pkt_hash; // FNV of the latest advert (type||payload) -- JOIN KEY:
|
||||
// group rxlog records by this to get every path the
|
||||
// advert arrived by (rxlog logs all copies pre-dedup)
|
||||
uint32_t direct_heard; // epoch we last heard this node 0-hop (0 = never)
|
||||
int8_t snr; // x4
|
||||
int8_t rssi; // dBm
|
||||
uint8_t type; // ADV_TYPE_*
|
||||
uint8_t path_len; // bit-packed (hash size|count); representative/best path
|
||||
uint8_t path[ANALYZER_PATH_LEN];
|
||||
};
|
||||
#endif
|
||||
|
||||
#if RXLOG_SIZE
|
||||
struct RxLogRec {
|
||||
uint32_t seq; // monotonic capture sequence (0 = empty slot; also the paging cursor)
|
||||
uint32_t when; // epoch
|
||||
uint32_t pkt_hash; // FNV-1a of (type||payload) -- cheap dedup / cross-observer id (NOT the SHA packet-hash)
|
||||
int8_t snr; // x4
|
||||
int8_t rssi; // dBm
|
||||
uint8_t header; // raw header byte (route|type|ver)
|
||||
uint8_t path_len; // bit-packed (hash size|count)
|
||||
uint8_t path[ANALYZER_PATH_LEN];
|
||||
};
|
||||
#endif
|
||||
|
||||
#if PKTFEED_SIZE
|
||||
struct PktFeedRec {
|
||||
uint32_t seq; // monotonic capture sequence (0 = empty slot; also the paging cursor)
|
||||
uint32_t when; // epoch
|
||||
int8_t snr; // x4
|
||||
int8_t rssi; // dBm
|
||||
uint8_t len; // raw frame length in bytes
|
||||
uint8_t raw[MAX_TRANS_UNIT]; // full wire frame (header|[transport]|path_len|path|payload)
|
||||
};
|
||||
#endif
|
||||
|
||||
#ifndef FIRMWARE_BUILD_DATE
|
||||
#define FIRMWARE_BUILD_DATE "14 Aug 2026"
|
||||
#define FIRMWARE_BUILD_DATE "15 Oct 2026"
|
||||
#endif
|
||||
|
||||
#ifndef FIRMWARE_VERSION
|
||||
#define FIRMWARE_VERSION "v1.17.1"
|
||||
#define FIRMWARE_VERSION "v1.18.0"
|
||||
#endif
|
||||
|
||||
#define FIRMWARE_ROLE "repeater"
|
||||
|
||||
#define PACKET_LOG_FILE "/packet_log"
|
||||
|
||||
class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
|
||||
@@ -90,6 +196,7 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
|
||||
bool _logging;
|
||||
NodePrefs _prefs;
|
||||
ClientACL acl;
|
||||
LoginGuard login_guard; // CUSTOM (TeTeHacko)
|
||||
CommonCLI _cli;
|
||||
uint8_t reply_data[MAX_PACKET_PAYLOAD];
|
||||
uint8_t reply_path[MAX_PATH_SIZE];
|
||||
@@ -99,13 +206,74 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
|
||||
RegionEntry* load_stack[8];
|
||||
RegionEntry* recv_pkt_region;
|
||||
TransportKey default_scope;
|
||||
uint32_t last_read_time;
|
||||
RateLimiter discover_limiter, anon_limiter;
|
||||
// CUSTOM (TeTeHacko): token-bucket limiter over FORWARDED traffic (port of
|
||||
// upstream proposal #1502). Kill switch: _prefs.fairness_enabled.
|
||||
FairnessLimiter fairness_limiter;
|
||||
uint32_t filter_hash_dropped; // forwards vetoed by the channel-hash deny list
|
||||
uint32_t filter_hash_passed; // throttled entries: forwards let through within budget
|
||||
HashThrottle hash_throttle; // per-entry windows of `filter hash add <hex> <secs>`
|
||||
unsigned long next_fair_sender_normal_refill, next_fair_sender_low_refill, next_fair_group_refill;
|
||||
uint32_t pending_discover_tag;
|
||||
unsigned long pending_discover_until;
|
||||
bool region_load_active;
|
||||
unsigned long dirty_contacts_expiry;
|
||||
#if MAX_NEIGHBOURS
|
||||
NeighbourInfo neighbours[MAX_NEIGHBOURS];
|
||||
#endif
|
||||
#if MAX_HEARD_NODES
|
||||
HeardNode heard_nodes[MAX_HEARD_NODES];
|
||||
#endif
|
||||
#if RXLOG_SIZE
|
||||
RxLogRec rxlog_ring[RXLOG_SIZE];
|
||||
uint16_t rxlog_head; // next slot to write
|
||||
uint32_t rxlog_next_seq; // next capture sequence to assign (starts at 1)
|
||||
#endif
|
||||
#if PKTFEED_SIZE
|
||||
PktFeedRec pktfeed_ring[PKTFEED_SIZE];
|
||||
uint16_t pktfeed_head; // next slot to write
|
||||
uint32_t pktfeed_next_seq; // next capture sequence to assign (starts at 1)
|
||||
// raw bytes staged in logRxRaw (pre-parse, the only place they exist) and
|
||||
// committed to the ring in logRx (fires only for frames that parsed OK, so
|
||||
// radio garbage never enters the feed)
|
||||
uint8_t pktfeed_stage[MAX_TRANS_UNIT];
|
||||
uint8_t pktfeed_stage_len; // 0 = nothing staged
|
||||
#endif
|
||||
#if defined(BOT_CHANNEL_PSK) || defined(FILTER_CHANNEL_PSKS)
|
||||
// CUSTOM (TeTeHacko): registry of channels this node can DECRYPT (the bot
|
||||
// channel and/or the filter channels). Shared by ChannelBot.h and
|
||||
// ChannelFilter.h; fed to searchChannelsByHash(), whose API caps matches at 4.
|
||||
#define MAX_KNOWN_CHANNELS 4
|
||||
#define CHAN_FLAG_BOT 0x01 // ChannelBot answers on this channel
|
||||
#define CHAN_FLAG_FILTER 0x02 // deny list applies to this channel
|
||||
mesh::GroupChannel known_channels[MAX_KNOWN_CHANNELS];
|
||||
uint8_t known_channel_flags[MAX_KNOWN_CHANNELS];
|
||||
uint8_t num_known_channels;
|
||||
#endif
|
||||
#ifdef FILTER_CHANNEL_PSKS
|
||||
uint32_t filter_dropped; // forwards vetoed by the deny list
|
||||
uint32_t filter_age_dropped; // forwards vetoed by `filter age`
|
||||
#endif
|
||||
#ifdef BOT_CHANNEL_PSK
|
||||
// Default zde, ne az v ChannelBot.h -- ten se includuje na konci MyMesh.cpp,
|
||||
// tedy dlouho po teto deklaraci pole.
|
||||
#ifndef BOT_PEER_SLOTS
|
||||
#define BOT_PEER_SLOTS 8
|
||||
#endif
|
||||
#ifndef BOT_BURST_MAX
|
||||
#define BOT_BURST_MAX 10
|
||||
#endif
|
||||
int8_t bot_channel_idx; // index into known_channels, -1 = PSK malformed, bot silently off
|
||||
unsigned long bot_next_reply_at; // cooldown gate, 0 = not armed
|
||||
uint32_t bot_replies_sent;
|
||||
uint32_t bot_ignored; // zprav zahozenych podle BOT_IGNORE_SENDERS
|
||||
uint32_t bot_throttled; // odpovedi potlacenych cooldownem
|
||||
struct BotPeer { uint32_t name_hash; unsigned long next_at; };
|
||||
BotPeer bot_peers[BOT_PEER_SLOTS]; // per-odesilatel okno, LRU
|
||||
uint32_t bot_last_reply_secs; // RTC time of the last reply, 0 = never
|
||||
unsigned long bot_burst_until[BOT_BURST_MAX > 0 ? BOT_BURST_MAX : 1]; // konce oken poslednich odpovedi, kruh
|
||||
uint8_t bot_burst_head; // nejstarsi z poslednich BOT_BURST_MAX odpovedi
|
||||
#endif
|
||||
CayenneLPP telemetry;
|
||||
unsigned long set_radio_at, revert_radio_at;
|
||||
@@ -121,15 +289,75 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
|
||||
#endif
|
||||
|
||||
void putNeighbour(const mesh::Identity& id, uint32_t timestamp, float snr);
|
||||
#if MAX_HEARD_NODES
|
||||
void putHeardNode(const mesh::Identity& id, uint32_t advert_timestamp, uint8_t type,
|
||||
int32_t lat, int32_t lon, const char* name,
|
||||
int8_t snr, int8_t rssi, const mesh::Packet* pkt);
|
||||
void formatNodesReply(char* reply, int max_len, uint16_t offset);
|
||||
#endif
|
||||
#if RXLOG_SIZE
|
||||
void captureRx(const mesh::Packet* pkt);
|
||||
void formatRxLogReply(char* reply, int max_len, uint32_t cursor);
|
||||
#endif
|
||||
#if PKTFEED_SIZE
|
||||
void stagePktFeed(const uint8_t raw[], int len);
|
||||
void commitPktFeed(const mesh::Packet* pkt);
|
||||
void formatPktFeedReply(char* reply, int max_len, uint32_t cursor);
|
||||
#endif
|
||||
#if defined(BOT_CHANNEL_PSK) || defined(FILTER_CHANNEL_PSKS)
|
||||
// CUSTOM (TeTeHacko): shared channel plumbing. Definitions in ChannelCommon.h,
|
||||
// included at the bottom of MyMesh.cpp.
|
||||
void channelsInit();
|
||||
int channelAddFromPsk(const char* psk_hex, int psk_len, uint8_t flag);
|
||||
void onChannelText(mesh::Packet* packet, int chan_idx, const char* sender, const char* msg);
|
||||
#endif
|
||||
#ifdef FILTER_CHANNEL_PSKS
|
||||
// CUSTOM (TeTeHacko): deny-list forwarding filter. Definitions in ChannelFilter.h.
|
||||
bool filterDenied(const char* sender) const;
|
||||
bool filterHandleCommand(const char* command, char* reply, int reply_max);
|
||||
#endif
|
||||
#ifdef BOT_CHANNEL_PSK
|
||||
// CUSTOM (TeTeHacko): channel bot. Definitions in ChannelBot.h, included at
|
||||
// the bottom of MyMesh.cpp. See that file for why this lives in the analyzer
|
||||
// build rather than in companion_radio.
|
||||
void botInit();
|
||||
void botOnChannelText(mesh::Packet* packet, const char* sender, const char* msg);
|
||||
bool botTriggerMatches(const char* text) const;
|
||||
void botFormatPath(char* out, const mesh::Packet* pkt) const;
|
||||
int botCommandReply(char* out, int max_len, const char* cmd, const mesh::Packet* pkt);
|
||||
int botScanCommands(char* out, int max_len, const char* text, const mesh::Packet* pkt);
|
||||
void botSendReply(const mesh::Packet* pkt, const char* text);
|
||||
bool botPeerAllowed(const char* name);
|
||||
bool botHandleCommand(const char* command, char* reply);
|
||||
#endif
|
||||
// CUSTOM (TeTeHacko): `fairness [on|off|grid|cap ...|refill ...]` CLI. Defined in MyMesh.cpp.
|
||||
bool fairnessHandleCommand(const char* command, char* reply, int reply_max);
|
||||
// CUSTOM (TeTeHacko): keyless deny-forward by channel hash. Definitions in ChannelFilter.h.
|
||||
bool filterHashDenied(const mesh::Packet* packet);
|
||||
bool filterHashHandleCommand(const char* command, char* reply, int reply_max);
|
||||
// `filter dryrun [on|off]` and `filter age [<min>|off]`. Definitions in ChannelFilter.h.
|
||||
bool filterMiscHandleCommand(const char* command, char* reply, int reply_max);
|
||||
// Refill interval in ms: persisted pref (seconds) if set, else the build default.
|
||||
uint32_t fairGroupRefillMs() const {
|
||||
return _prefs.fair_group_refill_s ? (uint32_t)_prefs.fair_group_refill_s * 1000 : FAIRNESS_GROUP_REFILL_MS;
|
||||
}
|
||||
uint32_t fairSenderRefillMs() const {
|
||||
return _prefs.fair_sender_refill_s ? (uint32_t)_prefs.fair_sender_refill_s * 1000 : FAIRNESS_SENDER_NORMAL_REFILL_MS;
|
||||
}
|
||||
uint32_t fairAdvertRefillMs() const {
|
||||
return _prefs.fair_advert_refill_s ? (uint32_t)_prefs.fair_advert_refill_s * 1000 : FAIRNESS_SENDER_LOW_REFILL_MS;
|
||||
}
|
||||
uint8_t handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data, bool is_flood);
|
||||
uint8_t handleAnonRegionsReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data);
|
||||
uint8_t handleAnonOwnerReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data);
|
||||
uint8_t handleAnonClockReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data);
|
||||
int handleRequest(ClientInfo* sender, uint32_t sender_timestamp, uint8_t* payload, size_t payload_len);
|
||||
int handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t req_type, uint8_t *payload, size_t payload_len);
|
||||
mesh::Packet* createSelfAdvert();
|
||||
|
||||
File openAppend(const char* fname);
|
||||
bool isLooped(const mesh::Packet* packet, const uint8_t max_counters[]);
|
||||
bool telemHasChanged(ClientInfo* c);
|
||||
|
||||
protected:
|
||||
float getAirtimeBudgetFactor() const override {
|
||||
@@ -137,6 +365,33 @@ protected:
|
||||
}
|
||||
|
||||
bool allowPacketForward(const mesh::Packet* packet) override;
|
||||
|
||||
// Šířku path hashe volí ODESÍLATEL, takže musí přijít z prefs tohohle uzlu.
|
||||
// Díky tomuhle overridu ji dostanou i volání send*(), která ji nepředávají
|
||||
// explicitně (ACKy, PATH-return, zerohop odpovědi sousedovi).
|
||||
uint8_t getSelfPathHashSize() const override { return _prefs.path_hash_mode + 1; }
|
||||
#if defined(BOT_CHANNEL_PSK) || defined(FILTER_CHANNEL_PSKS)
|
||||
// CUSTOM (TeTeHacko): both are no-op virtuals in mesh::Mesh, which is the only
|
||||
// reason a repeater is normally deaf to channel traffic. Overriding them does
|
||||
// NOT affect forwarding by itself -- Mesh::onRecvPacket() calls routeRecvPacket()
|
||||
// either way (Mesh.cpp:237-259). The ChannelFilter DOES veto forwarding of
|
||||
// matched packets, via packet->markDoNotRetransmit() (same mechanism the ANON
|
||||
// branch uses at Mesh.cpp:229).
|
||||
int searchChannelsByHash(const uint8_t* hash, mesh::GroupChannel channels[], int max_matches) override;
|
||||
void onGroupDataRecv(mesh::Packet* packet, uint8_t type, const mesh::GroupChannel& channel,
|
||||
uint8_t* data, size_t len) override;
|
||||
#endif
|
||||
// CUSTOM (TeTeHacko): FairnessLimiter veto. mesh::Mesh consults this as the
|
||||
// LAST condition of every forward decision, so a token is only taken for a
|
||||
// packet that would otherwise transmit. Buckets have a runtime kill switch
|
||||
// (`fairness on|off`), the advert window its own (`fairness advert 0`).
|
||||
// What gets shed is also summed as airtime -- in dry-run, what WOULD be.
|
||||
bool takeForwardingRateLimit(const mesh::Packet* packet) override {
|
||||
bool ok = fairness_limiter.allowPacket(packet, _ms->getMillis());
|
||||
FairShed why = fairness_limiter.lastShed();
|
||||
if (why != FAIR_SHED_NONE) fairness_limiter.addShedAirtime(why, _radio->getEstAirtimeFor(packet->getRawLength()));
|
||||
return ok;
|
||||
}
|
||||
const char* getLogDateTime() override;
|
||||
void logRxRaw(float snr, float rssi, const uint8_t raw[], int len) override;
|
||||
|
||||
@@ -163,7 +418,17 @@ protected:
|
||||
|
||||
#if ENV_INCLUDE_GPS == 1
|
||||
void applyGpsPrefs() {
|
||||
sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0");
|
||||
if (sensors.getSettingByKey("gps_interval") != nullptr) {
|
||||
// gps_interval was introduced only for EnvironmentSensorManager
|
||||
// and has little interest ... kept only as a legacy
|
||||
char interval[11];
|
||||
snprintf(interval, sizeof(interval), "%lu", (unsigned long)_prefs.gps_interval);
|
||||
sensors.setSettingValue("gps_interval", interval);
|
||||
}
|
||||
_prefs.getGpsPrefs()->apply(sensors);
|
||||
// 2 = duty cycle -- apply() only knows on/off, and a duty-cycled node must
|
||||
// not come back from a reboot with GPS powered forever
|
||||
if (_prefs.gps_enabled == 2) sensors.setSettingValue("gps", "2");
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -186,11 +451,14 @@ public:
|
||||
void sendNodeDiscoverReq();
|
||||
const char* getFirmwareVer() override { return FIRMWARE_VERSION; }
|
||||
const char* getBuildDate() override { return FIRMWARE_BUILD_DATE; }
|
||||
const char* getRole() override { return FIRMWARE_ROLE; }
|
||||
const char* getRole() override { return "repeater"; }
|
||||
const char* getNodeName() { return _prefs.node_name; }
|
||||
NodePrefs* getNodePrefs() {
|
||||
return &_prefs;
|
||||
}
|
||||
bool isHiddenNode() const {
|
||||
return _prefs.advert_interval == 0 && _prefs.flood_advert_interval == 0;
|
||||
}
|
||||
|
||||
void savePrefs() override {
|
||||
_cli.savePrefs(_fs);
|
||||
@@ -227,7 +495,11 @@ public:
|
||||
void saveIdentity(const mesh::LocalIdentity& new_id) override;
|
||||
void clearStats() override;
|
||||
|
||||
void handleCommand(uint32_t sender_timestamp, char* command, char* reply);
|
||||
// reply_max = usable reply capacity. Default 150 keeps the mesh admin CLI reply
|
||||
// inside one LoRa packet; the local console (USB/BLE, big buffer) passes more so
|
||||
// the paged analyzer replies (nodes/rxlog) can use big pages. Explicit parameter
|
||||
// on purpose — a forged sender_timestamp must never be able to grow the reply.
|
||||
void handleCommand(uint32_t sender_timestamp, char* command, char* reply, int reply_max = 150);
|
||||
void loop();
|
||||
|
||||
#if defined(WITH_BRIDGE)
|
||||
@@ -252,6 +524,9 @@ public:
|
||||
|
||||
// To check if there is pending work
|
||||
bool hasPendingWork() const;
|
||||
// CUSTOM (TeTeHacko): for the TX stall watchdog (helpers/NodeMaintenance.h).
|
||||
int txQueued() const { return _mgr->getOutboundTotal(); }
|
||||
int txDue() const { return _mgr->getOutboundCount(_ms->getMillis()); }
|
||||
|
||||
bool setRxBoostedGain(bool enable) override;
|
||||
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <helpers/ui/DisplayDriver.h>
|
||||
#include <helpers/CommonCLI.h>
|
||||
|
||||
class UITask {
|
||||
mesh::MainBoard* _board;
|
||||
DisplayDriver* _display;
|
||||
unsigned long _next_read, _next_refresh, _auto_off;
|
||||
int _prevBtnState;
|
||||
NodePrefs* _node_prefs;
|
||||
char _version_info[32];
|
||||
unsigned long _powering_off_at = 0;
|
||||
unsigned long _started_at = 0;
|
||||
|
||||
void renderCurrScreen();
|
||||
public:
|
||||
UITask(mesh::MainBoard& board, DisplayDriver& display) : _board(&board), _display(&display) { _next_read = _next_refresh = 0; }
|
||||
void begin(NodePrefs* node_prefs, const char* build_date, const char* firmware_version);
|
||||
|
||||
void loop();
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,5 @@
|
||||
#include "MyMesh.h"
|
||||
#include <algorithm>
|
||||
|
||||
#define REPLY_DELAY_MILLIS 1500
|
||||
#define PUSH_NOTIFY_DELAY_MILLIS 2000
|
||||
@@ -139,7 +140,7 @@ mesh::Packet *MyMesh::createSelfAdvert() {
|
||||
}
|
||||
|
||||
File MyMesh::openAppend(const char *fname) {
|
||||
#if defined(NRF52_PLATFORM)
|
||||
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
|
||||
return _fs->open(fname, FILE_O_WRITE);
|
||||
#elif defined(RP2040_PLATFORM)
|
||||
return _fs->open(fname, "a");
|
||||
@@ -154,6 +155,17 @@ int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t
|
||||
// memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
|
||||
memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag')
|
||||
|
||||
// CUSTOM (TeTeHacko): firmware chunks for FwUpdate (REQ_TYPE_FW_OTA = 0xF0, admin
|
||||
// only, helpers/FwUpdate.h). 0 = no reply: chunks are fire and forget.
|
||||
if (payload_len >= 1 && payload[0] == 0xF0) {
|
||||
extern int maintHandleRequest(bool admin, const uint8_t* req, int len, uint8_t* reply, int reply_max);
|
||||
// 150: tag + reply pads to 160 B, and the companion's push frame (6 + padded
|
||||
// length - 4) must stay within MAX_FRAME_SIZE 176 -- a 163 B reply padded to
|
||||
// 176 made a 178 B frame that the companion silently dropped
|
||||
int n = maintHandleRequest(sender->isAdmin(), payload, (int)payload_len, &reply_data[4], 150);
|
||||
return n > 0 ? 4 + n : 0;
|
||||
}
|
||||
|
||||
if (payload[0] == REQ_TYPE_GET_STATUS) {
|
||||
ServerStats stats;
|
||||
stats.batt_milli_volts = board.getBattMilliVolts();
|
||||
@@ -170,8 +182,8 @@ int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t
|
||||
stats.n_recv_direct = getNumRecvDirect();
|
||||
stats.err_events = _err_flags;
|
||||
stats.last_snr = (int16_t)(radio_driver.getLastSNR() * 4);
|
||||
stats.n_direct_dups = ((SimpleMeshTables *)getTables())->getNumDirectDups();
|
||||
stats.n_flood_dups = ((SimpleMeshTables *)getTables())->getNumFloodDups();
|
||||
stats.n_direct_dups = std::min<uint32_t>(((SimpleMeshTables *)getTables())->getNumDirectDups(), 0xFFFF);
|
||||
stats.n_flood_dups = std::min<uint32_t>(((SimpleMeshTables *)getTables())->getNumFloodDups(), 0xFFFF);
|
||||
stats.n_posted = _num_posted;
|
||||
stats.n_post_push = _num_post_pushes;
|
||||
|
||||
@@ -338,10 +350,19 @@ void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const m
|
||||
#if MESH_DEBUG
|
||||
MESH_DEBUG_PRINTLN("Login, sender not in ACL");
|
||||
#endif
|
||||
} else {
|
||||
// CUSTOM (TeTeHacko): a blank login has a replay floor too -- replayed, it
|
||||
// gained nothing, but each copy made us flood a reply over the mesh.
|
||||
if (sender_timestamp <= client->last_timestamp) return;
|
||||
acl.persistTimestamp(client, sender_timestamp, getRTCClock()->getCurrentTime());
|
||||
client->last_timestamp = sender_timestamp;
|
||||
}
|
||||
}
|
||||
if (client == NULL) {
|
||||
uint8_t perm;
|
||||
// CUSTOM (TeTeHacko): capped wrong passwords (LoginGuard.h); a known admin is never locked out
|
||||
ClientInfo* known = acl.getClient(sender.pub_key, PUB_KEY_SIZE);
|
||||
if (login_guard.locked(millis()) && !(known && known->isAdmin())) return;
|
||||
if (strcmp((char *)&data[8], _prefs.password) == 0) { // check for valid admin password
|
||||
perm = PERM_ACL_ADMIN;
|
||||
} else {
|
||||
@@ -351,6 +372,7 @@ void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const m
|
||||
perm = PERM_ACL_GUEST;
|
||||
} else {
|
||||
MESH_DEBUG_PRINTLN("Incorrect room password");
|
||||
login_guard.failed(millis()); // CUSTOM (TeTeHacko)
|
||||
return; // no response. Client will timeout
|
||||
}
|
||||
}
|
||||
@@ -360,7 +382,6 @@ void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const m
|
||||
MESH_DEBUG_PRINTLN("possible replay attack!");
|
||||
return;
|
||||
}
|
||||
|
||||
MESH_DEBUG_PRINTLN("Login success!");
|
||||
client->last_timestamp = sender_timestamp;
|
||||
client->extra.room.sync_since = sender_sync_since;
|
||||
@@ -370,6 +391,7 @@ void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const m
|
||||
client->last_activity = getRTCClock()->getCurrentTime();
|
||||
client->permissions &= ~0x03;
|
||||
client->permissions |= perm;
|
||||
acl.persistTimestamp(client, sender_timestamp, getRTCClock()->getCurrentTime()); // CUSTOM (TeTeHacko): admin only, so after the role
|
||||
memcpy(client->shared_secret, secret, PUB_KEY_SIZE);
|
||||
|
||||
dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY);
|
||||
@@ -443,10 +465,11 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx,
|
||||
memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
|
||||
uint8_t flags = (data[4] >> 2); // message attempt number, and other flags
|
||||
|
||||
if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA)) {
|
||||
if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA || flags == TXT_TYPE_CLI_COMMAND)) {
|
||||
MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported command flags received: flags=%02x", (uint32_t)flags);
|
||||
} else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks, but send Acks for retries
|
||||
bool is_retry = (sender_timestamp == client->last_timestamp);
|
||||
acl.persistTimestamp(client, sender_timestamp, getRTCClock()->getCurrentTime()); // CUSTOM (TeTeHacko): before acting
|
||||
client->last_timestamp = sender_timestamp;
|
||||
|
||||
uint32_t now = getRTCClock()->getCurrentTimeUnique();
|
||||
@@ -461,9 +484,10 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx,
|
||||
mesh::Utils::sha256((uint8_t *)&ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key,
|
||||
PUB_KEY_SIZE);
|
||||
|
||||
uint8_t temp[166];
|
||||
// 5-byte datagram header + 3-byte reflected CLI prefix + 160-byte reply text + NUL
|
||||
uint8_t temp[169];
|
||||
bool send_ack;
|
||||
if (flags == TXT_TYPE_CLI_DATA) {
|
||||
if (flags == TXT_TYPE_CLI_DATA || flags == TXT_TYPE_CLI_COMMAND) {
|
||||
if (client->isAdmin()) {
|
||||
if (is_retry) {
|
||||
temp[5] = 0; // no reply
|
||||
@@ -541,6 +565,7 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx,
|
||||
if (sender_timestamp < client->last_timestamp) { // prevent replay attacks
|
||||
MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
|
||||
} else {
|
||||
acl.persistTimestamp(client, sender_timestamp, getRTCClock()->getCurrentTime()); // CUSTOM (TeTeHacko): before acting
|
||||
client->last_timestamp = sender_timestamp;
|
||||
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
@@ -645,6 +670,9 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc
|
||||
|
||||
// defaults
|
||||
_prefs.airtime_factor = 1.0;
|
||||
#ifdef AIRTIME_FACTOR_DEFAULT // CUSTOM (TeTeHacko): e.g. 9 = 10 % duty cycle (meshcore.cz)
|
||||
_prefs.airtime_factor = AIRTIME_FACTOR_DEFAULT;
|
||||
#endif
|
||||
_prefs.rx_delay_base = 0.0f; // off by default, was 10.0
|
||||
_prefs.tx_delay_factor = 0.5f; // was 0.25f;
|
||||
_prefs.direct_tx_delay_factor = 0.2f; // was zero
|
||||
@@ -660,6 +688,12 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc
|
||||
_prefs.disable_fwd = 1;
|
||||
_prefs.advert_interval = 1; // default to 2 minutes for NEW installs
|
||||
_prefs.flood_advert_interval = 47; // 47 hours
|
||||
#ifdef ADVERT_INTERVAL_DEFAULT // CUSTOM (TeTeHacko): same knobs as simple_repeater
|
||||
_prefs.advert_interval = ADVERT_INTERVAL_DEFAULT;
|
||||
#endif
|
||||
#ifdef FLOOD_ADVERT_INTERVAL_DEFAULT
|
||||
_prefs.flood_advert_interval = FLOOD_ADVERT_INTERVAL_DEFAULT;
|
||||
#endif
|
||||
_prefs.flood_max = 64;
|
||||
_prefs.flood_max_unscoped = 64;
|
||||
_prefs.flood_max_advert = 8;
|
||||
@@ -724,9 +758,12 @@ void MyMesh::begin(FILESYSTEM *fs) {
|
||||
|
||||
radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
|
||||
radio_driver.setTxPower(_prefs.tx_power_dbm);
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
_prefs.getRadioPrefs()->applyRxPowerSaving(_prefs.sf, _prefs.bw); // CUSTOM (TeTeHacko)
|
||||
#endif
|
||||
radio_driver.setRxBoostedGainMode(_prefs.rx_boosted_gain);
|
||||
board.setLoRaFemLnaEnabled(_prefs.radio_fem_rxgain);
|
||||
board.setLoRaFemPaGainEnabled(_prefs.radio_fem_txgain);
|
||||
|
||||
board.attachDynamicPrefs(_prefs.getCustom());
|
||||
|
||||
updateAdvertTimer();
|
||||
updateFloodAdvertTimer();
|
||||
@@ -736,6 +773,7 @@ void MyMesh::begin(FILESYSTEM *fs) {
|
||||
#if ENV_INCLUDE_GPS == 1
|
||||
applyGpsPrefs();
|
||||
#endif
|
||||
sensors.applyInaShunt(_prefs.ina_shunt_mohm); // CUSTOM (TeTeHacko)
|
||||
}
|
||||
|
||||
void MyMesh::sendFloodScoped(const TransportKey& scope, mesh::Packet* pkt, uint32_t delay_millis, uint8_t path_hash_size) {
|
||||
@@ -781,7 +819,7 @@ void MyMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr,
|
||||
}
|
||||
|
||||
bool MyMesh::formatFileSystem() {
|
||||
#if defined(NRF52_PLATFORM)
|
||||
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
|
||||
return InternalFS.format();
|
||||
#elif defined(RP2040_PLATFORM)
|
||||
return LittleFS.format();
|
||||
@@ -940,6 +978,10 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply
|
||||
command += 3;
|
||||
}
|
||||
|
||||
// CUSTOM (TeTeHacko): dfu (local only), radio silence watchdog, `get boot`.
|
||||
extern bool maintHandleCommand(uint32_t sender_timestamp, const char* command, char* reply);
|
||||
if (maintHandleCommand(sender_timestamp, command, reply)) return;
|
||||
|
||||
// handle ACL related commands
|
||||
if (memcmp(command, "setperm ", 8) == 0) { // format: setperm {pubkey-hex} {permissions-int8}
|
||||
char* hex = &command[8];
|
||||
@@ -983,6 +1025,8 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply
|
||||
addSystemPost(msg);
|
||||
snprintf(reply, MAX_POST_TEXT_LEN, "OK");
|
||||
}
|
||||
} else if (memcmp(command, "set repeat on", 13) == 0) {
|
||||
strcpy(reply, "ERR - repeat now deprecated");
|
||||
} else{
|
||||
_cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
|
||||
}
|
||||
@@ -1055,12 +1099,18 @@ void MyMesh::loop() {
|
||||
if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
|
||||
set_radio_at = 0; // clear timer
|
||||
radio_driver.setParams(pending_freq, pending_bw, pending_sf, pending_cr);
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
_prefs.getRadioPrefs()->applyRxPowerSaving(pending_sf, pending_bw);
|
||||
#endif
|
||||
MESH_DEBUG_PRINTLN("Temp radio params");
|
||||
}
|
||||
|
||||
if (revert_radio_at && millisHasNowPassed(revert_radio_at)) { // revert radio params to orig
|
||||
revert_radio_at = 0; // clear timer
|
||||
radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
_prefs.getRadioPrefs()->applyRxPowerSaving(_prefs.sf, _prefs.bw);
|
||||
#endif
|
||||
MESH_DEBUG_PRINTLN("Radio params restored");
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
#include <Arduino.h> // needed for PlatformIO
|
||||
#include <Mesh.h>
|
||||
|
||||
#if defined(NRF52_PLATFORM)
|
||||
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
|
||||
#include <InternalFileSystem.h>
|
||||
#elif defined(RP2040_PLATFORM)
|
||||
#include <LittleFS.h>
|
||||
@@ -20,6 +20,7 @@
|
||||
#include <helpers/CommonCLI.h>
|
||||
#include <helpers/StatsFormatHelper.h>
|
||||
#include <helpers/ClientACL.h>
|
||||
#include <helpers/LoginGuard.h> // CUSTOM (TeTeHacko)
|
||||
#include <helpers/RegionMap.h>
|
||||
#include <helpers/RoutingPolicy.h>
|
||||
#include <RTClib.h>
|
||||
@@ -28,11 +29,11 @@
|
||||
/* ------------------------------ Config -------------------------------- */
|
||||
|
||||
#ifndef FIRMWARE_BUILD_DATE
|
||||
#define FIRMWARE_BUILD_DATE "14 Aug 2026"
|
||||
#define FIRMWARE_BUILD_DATE "15 Oct 2026"
|
||||
#endif
|
||||
|
||||
#ifndef FIRMWARE_VERSION
|
||||
#define FIRMWARE_VERSION "v1.17.1"
|
||||
#define FIRMWARE_VERSION "v1.18.0"
|
||||
#endif
|
||||
|
||||
#ifndef LORA_FREQ
|
||||
@@ -77,8 +78,6 @@
|
||||
#define TXT_ACK_DELAY 200
|
||||
#endif
|
||||
|
||||
#define FIRMWARE_ROLE "room_server"
|
||||
|
||||
#define PACKET_LOG_FILE "/packet_log"
|
||||
|
||||
#define MAX_POST_TEXT_LEN (160-9)
|
||||
@@ -100,6 +99,7 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
|
||||
TransportKeyStore key_store;
|
||||
RegionMap region_map, temp_map;
|
||||
ClientACL acl;
|
||||
LoginGuard login_guard; // CUSTOM (TeTeHacko)
|
||||
CommonCLI _cli;
|
||||
unsigned long dirty_contacts_expiry;
|
||||
uint8_t reply_data[MAX_PACKET_PAYLOAD];
|
||||
@@ -159,6 +159,11 @@ protected:
|
||||
mesh::DispatcherAction onRecvPacket(mesh::Packet* pkt) override;
|
||||
|
||||
bool allowPacketForward(const mesh::Packet* packet) override;
|
||||
|
||||
// Šířku path hashe volí ODESÍLATEL, takže musí přijít z prefs tohohle uzlu.
|
||||
// Díky tomuhle overridu ji dostanou i volání send*(), která ji nepředávají
|
||||
// explicitně (ACKy, PATH-return, zerohop odpovědi sousedovi).
|
||||
uint8_t getSelfPathHashSize() const override { return _prefs.path_hash_mode + 1; }
|
||||
void onAnonDataRecv(mesh::Packet* packet, const uint8_t* secret, const mesh::Identity& sender, uint8_t* data, size_t len) override;
|
||||
int searchPeersByHash(const uint8_t* hash) override ;
|
||||
void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override;
|
||||
@@ -168,7 +173,14 @@ protected:
|
||||
|
||||
#if ENV_INCLUDE_GPS == 1
|
||||
void applyGpsPrefs() {
|
||||
sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0");
|
||||
if (sensors.getSettingByKey("gps_interval") != nullptr) {
|
||||
// gps_interval was introduced only for EnvironmentSensorManager
|
||||
// and has little interest ... kept only as a legacy
|
||||
char interval[11];
|
||||
snprintf(interval, sizeof(interval), "%lu", (unsigned long)_prefs.gps_interval);
|
||||
sensors.setSettingValue("gps_interval", interval);
|
||||
}
|
||||
_prefs.getGpsPrefs()->apply(sensors);
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -182,7 +194,7 @@ public:
|
||||
|
||||
const char* getFirmwareVer() override { return FIRMWARE_VERSION; }
|
||||
const char* getBuildDate() override { return FIRMWARE_BUILD_DATE; }
|
||||
const char* getRole() override { return FIRMWARE_ROLE; }
|
||||
const char* getRole() override { return "room_server"; }
|
||||
const char* getNodeName() { return _prefs.node_name; }
|
||||
NodePrefs* getNodePrefs() {
|
||||
return &_prefs;
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
#include "UITask.h"
|
||||
#include <Arduino.h>
|
||||
#include <helpers/CommonCLI.h>
|
||||
|
||||
#ifndef USER_BTN_PRESSED
|
||||
#define USER_BTN_PRESSED LOW
|
||||
#endif
|
||||
|
||||
#define AUTO_OFF_MILLIS 20000 // 20 seconds
|
||||
#define BOOT_SCREEN_MILLIS 4000 // 4 seconds
|
||||
|
||||
// 'meshcore', 128x13px
|
||||
static const uint8_t meshcore_logo [] PROGMEM = {
|
||||
0x3c, 0x01, 0xe3, 0xff, 0xc7, 0xff, 0x8f, 0x03, 0x87, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe,
|
||||
0x3c, 0x03, 0xe3, 0xff, 0xc7, 0xff, 0x8e, 0x03, 0x8f, 0xfe, 0x3f, 0xfe, 0x1f, 0xff, 0x1f, 0xfe,
|
||||
0x3e, 0x03, 0xc3, 0xff, 0x8f, 0xff, 0x0e, 0x07, 0x8f, 0xfe, 0x7f, 0xfe, 0x1f, 0xff, 0x1f, 0xfc,
|
||||
0x3e, 0x07, 0xc7, 0x80, 0x0e, 0x00, 0x0e, 0x07, 0x9e, 0x00, 0x78, 0x0e, 0x3c, 0x0f, 0x1c, 0x00,
|
||||
0x3e, 0x0f, 0xc7, 0x80, 0x1e, 0x00, 0x0e, 0x07, 0x1e, 0x00, 0x70, 0x0e, 0x38, 0x0f, 0x3c, 0x00,
|
||||
0x7f, 0x0f, 0xc7, 0xfe, 0x1f, 0xfc, 0x1f, 0xff, 0x1c, 0x00, 0x70, 0x0e, 0x38, 0x0e, 0x3f, 0xf8,
|
||||
0x7f, 0x1f, 0xc7, 0xfe, 0x0f, 0xff, 0x1f, 0xff, 0x1c, 0x00, 0xf0, 0x0e, 0x38, 0x0e, 0x3f, 0xf8,
|
||||
0x7f, 0x3f, 0xc7, 0xfe, 0x0f, 0xff, 0x1f, 0xff, 0x1c, 0x00, 0xf0, 0x1e, 0x3f, 0xfe, 0x3f, 0xf0,
|
||||
0x77, 0x3b, 0x87, 0x00, 0x00, 0x07, 0x1c, 0x0f, 0x3c, 0x00, 0xe0, 0x1c, 0x7f, 0xfc, 0x38, 0x00,
|
||||
0x77, 0xfb, 0x8f, 0x00, 0x00, 0x07, 0x1c, 0x0f, 0x3c, 0x00, 0xe0, 0x1c, 0x7f, 0xf8, 0x38, 0x00,
|
||||
0x73, 0xf3, 0x8f, 0xff, 0x0f, 0xff, 0x1c, 0x0e, 0x3f, 0xf8, 0xff, 0xfc, 0x70, 0x78, 0x7f, 0xf8,
|
||||
0xe3, 0xe3, 0x8f, 0xff, 0x1f, 0xfe, 0x3c, 0x0e, 0x3f, 0xf8, 0xff, 0xfc, 0x70, 0x3c, 0x7f, 0xf8,
|
||||
0xe3, 0xe3, 0x8f, 0xff, 0x1f, 0xfc, 0x3c, 0x0e, 0x1f, 0xf8, 0xff, 0xf8, 0x70, 0x3c, 0x7f, 0xf8,
|
||||
};
|
||||
|
||||
void UITask::begin(NodePrefs* node_prefs, const char* build_date, const char* firmware_version) {
|
||||
_prevBtnState = HIGH;
|
||||
_auto_off = millis() + AUTO_OFF_MILLIS;
|
||||
_node_prefs = node_prefs;
|
||||
_display->turnOn();
|
||||
|
||||
// strip off dash and commit hash by changing dash to null terminator
|
||||
// e.g: v1.2.3-abcdef -> v1.2.3
|
||||
char *version = strdup(firmware_version);
|
||||
char *dash = strchr(version, '-');
|
||||
if(dash){
|
||||
*dash = 0;
|
||||
}
|
||||
|
||||
// v1.2.3 (1 Jan 2025)
|
||||
snprintf(_version_info, sizeof(_version_info), "%s (%s)", version, build_date);
|
||||
free(version);
|
||||
}
|
||||
|
||||
void UITask::renderCurrScreen() {
|
||||
char tmp[80];
|
||||
if (millis() < BOOT_SCREEN_MILLIS) { // boot screen
|
||||
// meshcore logo
|
||||
_display->setColor(UIColor::corp_blue);
|
||||
int logoWidth = 128;
|
||||
_display->drawXbm((_display->width() - logoWidth) / 2, 3, meshcore_logo, logoWidth, 13);
|
||||
|
||||
// meshcore website
|
||||
const char* website = "https://meshcore.io";
|
||||
_display->setColor(UIColor::primary_txt);
|
||||
_display->setTextSize(1);
|
||||
uint16_t websiteWidth = _display->getTextWidth(website);
|
||||
_display->setCursor((_display->width() - websiteWidth) / 2, 22);
|
||||
_display->print(website);
|
||||
|
||||
// version info
|
||||
_display->setTextSize(1);
|
||||
uint16_t versionWidth = _display->getTextWidth(_version_info);
|
||||
_display->setCursor((_display->width() - versionWidth) / 2, 35);
|
||||
_display->print(_version_info);
|
||||
|
||||
// node type
|
||||
const char* node_type = "< Room Server >";
|
||||
uint16_t typeWidth = _display->getTextWidth(node_type);
|
||||
_display->setCursor((_display->width() - typeWidth) / 2, 48);
|
||||
_display->print(node_type);
|
||||
} else { // home screen
|
||||
// node name
|
||||
_display->setCursor(0, 0);
|
||||
_display->setTextSize(1);
|
||||
_display->setColor(UIColor::primary_txt);
|
||||
_display->print(_node_prefs->node_name);
|
||||
|
||||
// freq / sf
|
||||
_display->setCursor(0, 20);
|
||||
sprintf(tmp, "FREQ: %06.3f SF%d", _node_prefs->freq, _node_prefs->sf);
|
||||
_display->print(tmp);
|
||||
|
||||
// bw / cr
|
||||
_display->setCursor(0, 30);
|
||||
sprintf(tmp, "BW: %03.2f CR: %d", _node_prefs->bw, _node_prefs->cr);
|
||||
_display->print(tmp);
|
||||
}
|
||||
}
|
||||
|
||||
void UITask::loop() {
|
||||
#ifdef PIN_USER_BTN
|
||||
if (millis() >= _next_read) {
|
||||
int btnState = digitalRead(PIN_USER_BTN);
|
||||
if (btnState != _prevBtnState) {
|
||||
if (btnState == USER_BTN_PRESSED) { // pressed?
|
||||
if (_display->isOn()) {
|
||||
// TODO: any action ?
|
||||
} else {
|
||||
_display->turnOn();
|
||||
}
|
||||
_auto_off = millis() + AUTO_OFF_MILLIS; // extend auto-off timer
|
||||
}
|
||||
_prevBtnState = btnState;
|
||||
}
|
||||
_next_read = millis() + 200; // 5 reads per second
|
||||
}
|
||||
#endif
|
||||
|
||||
if (_display->isOn()) {
|
||||
if (millis() >= _next_refresh) {
|
||||
_display->startFrame();
|
||||
renderCurrScreen();
|
||||
_display->endFrame();
|
||||
|
||||
_next_refresh = millis() + 1000; // refresh every second
|
||||
}
|
||||
if (millis() > _auto_off) {
|
||||
_display->turnOff();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <helpers/ui/DisplayDriver.h>
|
||||
#include <helpers/CommonCLI.h>
|
||||
|
||||
class UITask {
|
||||
DisplayDriver* _display;
|
||||
unsigned long _next_read, _next_refresh, _auto_off;
|
||||
int _prevBtnState;
|
||||
NodePrefs* _node_prefs;
|
||||
char _version_info[32];
|
||||
|
||||
void renderCurrScreen();
|
||||
public:
|
||||
UITask(DisplayDriver& display) : _display(&display) { _next_read = _next_refresh = 0; }
|
||||
void begin(NodePrefs* node_prefs, const char* build_date, const char* firmware_version);
|
||||
|
||||
void loop();
|
||||
};
|
||||
@@ -2,21 +2,28 @@
|
||||
#include <Mesh.h>
|
||||
|
||||
#include "MyMesh.h"
|
||||
#include <helpers/NodeMaintenance.h>
|
||||
|
||||
#ifdef ETHERNET_ENABLED
|
||||
#define ETHERNET_CLI_BANNER "MeshCore Room Server CLI"
|
||||
#include <helpers/nrf52/EthernetCLI.h>
|
||||
#endif
|
||||
|
||||
#ifdef DISPLAY_CLASS
|
||||
#include "UITask.h"
|
||||
static UITask ui_task(display);
|
||||
#endif
|
||||
|
||||
StdRNG fast_rng;
|
||||
SimpleMeshTables tables;
|
||||
MyMesh the_mesh(board, radio_driver, *new ArduinoMillis(), fast_rng, rtc_clock, tables);
|
||||
|
||||
// CUSTOM (TeTeHacko): dfu, radio silence watchdog, `get boot` -- see NodeMaintenance.h.
|
||||
static NodeMaintenance maint(board, radio_driver);
|
||||
bool maintHandleCommand(uint32_t sender_timestamp, const char* command, char* reply) {
|
||||
return maint.handleCommand(sender_timestamp, command, reply);
|
||||
}
|
||||
|
||||
// CUSTOM (TeTeHacko): binary firmware chunks (REQ_TYPE_FW_OTA), see helpers/FwUpdate.h.
|
||||
int maintHandleRequest(bool admin, const uint8_t* req, int len, uint8_t* reply, int reply_max) {
|
||||
return maint.handleRequest(admin, req, len, reply, reply_max);
|
||||
}
|
||||
|
||||
void halt() {
|
||||
while (1) ;
|
||||
}
|
||||
@@ -31,6 +38,7 @@ void setup() {
|
||||
delay(1000);
|
||||
|
||||
board.begin();
|
||||
maint.printBootDiag();
|
||||
|
||||
#ifdef HAS_EXTERNAL_WATCHDOG
|
||||
external_watchdog.begin();
|
||||
@@ -50,7 +58,7 @@ void setup() {
|
||||
fast_rng.begin(radio_driver.getRngSeed());
|
||||
|
||||
FILESYSTEM* fs;
|
||||
#if defined(NRF52_PLATFORM)
|
||||
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
|
||||
InternalFS.begin();
|
||||
fs = &InternalFS;
|
||||
IdentityStore store(InternalFS, "");
|
||||
@@ -86,9 +94,10 @@ void setup() {
|
||||
sensors.begin();
|
||||
|
||||
the_mesh.begin(fs);
|
||||
maint.begin(fs, the_mesh.getNodePrefs(), &the_mesh);
|
||||
|
||||
#ifdef DISPLAY_CLASS
|
||||
ui_task.begin(the_mesh.getNodePrefs(), FIRMWARE_BUILD_DATE, FIRMWARE_VERSION);
|
||||
ui_task.begin(the_mesh.getNodePrefs(), FIRMWARE_BUILD_DATE, FIRMWARE_VERSION, "< Room Server >");
|
||||
#endif
|
||||
|
||||
#ifdef ETHERNET_ENABLED
|
||||
@@ -105,6 +114,13 @@ void setup() {
|
||||
|
||||
void loop() {
|
||||
int len = strlen(command);
|
||||
// `command` must stay NUL-terminated within its bounds. If it ever isn't,
|
||||
// strlen() above can return >= sizeof(command) and the loop below would then
|
||||
// index past the buffer, so clamp defensively.
|
||||
if (len >= (int)sizeof(command)) {
|
||||
command[0] = 0;
|
||||
len = 0;
|
||||
}
|
||||
while (Serial.available() && len < sizeof(command)-1) {
|
||||
char c = Serial.read();
|
||||
if (c != '\n') {
|
||||
@@ -113,8 +129,9 @@ void loop() {
|
||||
}
|
||||
Serial.print(c);
|
||||
}
|
||||
if (len == sizeof(command)-1) { // command buffer full
|
||||
command[sizeof(command)-1] = '\r';
|
||||
if (len == sizeof(command)-1) { // buffer full: treat as a completed line
|
||||
command[sizeof(command)-2] = '\r'; // place end-of-line marker inside the buffer
|
||||
command[sizeof(command)-1] = 0; // keep the buffer NUL-terminated
|
||||
}
|
||||
|
||||
if (len > 0 && command[len - 1] == '\r') { // received complete line
|
||||
@@ -149,11 +166,13 @@ void loop() {
|
||||
#endif
|
||||
|
||||
the_mesh.loop();
|
||||
maint.loop();
|
||||
sensors.loop();
|
||||
#ifdef DISPLAY_CLASS
|
||||
ui_task.loop();
|
||||
#endif
|
||||
rtc_clock.tick();
|
||||
board.loop();
|
||||
#ifdef HAS_EXTERNAL_WATCHDOG
|
||||
external_watchdog.loop();
|
||||
#endif
|
||||
|
||||
@@ -103,6 +103,10 @@ class MyMesh : public BaseChatMesh, ContactVisitor {
|
||||
uint8_t unused;
|
||||
uint32_t reserved;
|
||||
|
||||
// No shared_secret/shared_secret_valid in the on-disk record; without
|
||||
// this the flag is indeterminate for every contact loaded at boot.
|
||||
memset(&c, 0, sizeof(c));
|
||||
|
||||
bool success = (file.read(pub_key, 32) == 32);
|
||||
success = success && (file.read((uint8_t *) &c.name, 32) == 32);
|
||||
success = success && (file.read(&c.type, 1) == 1);
|
||||
@@ -242,6 +246,10 @@ protected:
|
||||
|
||||
void onCommandDataRecv(const ContactInfo& from, mesh::Packet* pkt, uint32_t sender_timestamp, const char *text) override {
|
||||
}
|
||||
|
||||
void onCLICommandRecv(const ContactInfo& contact, mesh::Packet* pkt, uint32_t sender_timestamp, const char *text, char* reply) override {
|
||||
}
|
||||
|
||||
void onSignedMessageRecv(const ContactInfo& from, mesh::Packet* pkt, uint32_t sender_timestamp, const uint8_t *sender_prefix, const char *text) override {
|
||||
}
|
||||
|
||||
@@ -526,6 +534,13 @@ public:
|
||||
BaseChatMesh::loop();
|
||||
|
||||
int len = strlen(command);
|
||||
// `command` must stay NUL-terminated within its bounds. If it ever isn't,
|
||||
// strlen() above can return >= sizeof(command) and the loop below would then
|
||||
// index past the buffer, so clamp defensively.
|
||||
if (len >= (int)sizeof(command)) {
|
||||
command[0] = 0;
|
||||
len = 0;
|
||||
}
|
||||
while (Serial.available() && len < sizeof(command)-1) {
|
||||
char c = Serial.read();
|
||||
if (c != '\n') {
|
||||
@@ -534,8 +549,9 @@ public:
|
||||
}
|
||||
Serial.print(c);
|
||||
}
|
||||
if (len == sizeof(command)-1) { // command buffer full
|
||||
command[sizeof(command)-1] = '\r';
|
||||
if (len == sizeof(command)-1) { // buffer full: treat as a completed line
|
||||
command[sizeof(command)-2] = '\r'; // place end-of-line marker inside the buffer
|
||||
command[sizeof(command)-1] = 0; // keep the buffer NUL-terminated
|
||||
}
|
||||
|
||||
if (len > 0 && command[len - 1] == '\r') { // received complete line
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
#include "SensorMesh.h"
|
||||
#include <helpers/RoutingPolicy.h>
|
||||
#include <helpers/sensors/LPPDataHelpers.h>
|
||||
|
||||
/* ------------------------------ Config -------------------------------- */
|
||||
|
||||
@@ -54,6 +56,10 @@
|
||||
#define REQ_TYPE_GET_TELEMETRY_DATA 0x03
|
||||
#define REQ_TYPE_GET_AVG_MIN_MAX 0x04
|
||||
#define REQ_TYPE_GET_ACCESS_LIST 0x05
|
||||
#define REQ_TYPE_GET_NEIGHBOURS 0x06 // repeater only (at present)
|
||||
|
||||
#define REQ_TYPE_SUBSCRIBE 0x08
|
||||
#define REQ_TYPE_UNSUBSCRIBE 0x09
|
||||
|
||||
#define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ
|
||||
|
||||
@@ -73,104 +79,70 @@ static File openAppend(FILESYSTEM* _fs, const char* fname) {
|
||||
#endif
|
||||
}
|
||||
|
||||
static uint8_t getDataSize(uint8_t type) {
|
||||
switch (type) {
|
||||
case LPP_GPS:
|
||||
return 9;
|
||||
case LPP_POLYLINE:
|
||||
return 8; // TODO: this is MINIMIUM
|
||||
case LPP_GYROMETER:
|
||||
case LPP_ACCELEROMETER:
|
||||
return 6;
|
||||
case LPP_GENERIC_SENSOR:
|
||||
case LPP_FREQUENCY:
|
||||
case LPP_DISTANCE:
|
||||
case LPP_ENERGY:
|
||||
case LPP_UNIXTIME:
|
||||
return 4;
|
||||
case LPP_COLOUR:
|
||||
return 3;
|
||||
case LPP_ANALOG_INPUT:
|
||||
case LPP_ANALOG_OUTPUT:
|
||||
case LPP_LUMINOSITY:
|
||||
case LPP_TEMPERATURE:
|
||||
case LPP_CONCENTRATION:
|
||||
case LPP_BAROMETRIC_PRESSURE:
|
||||
case LPP_RELATIVE_HUMIDITY:
|
||||
case LPP_ALTITUDE:
|
||||
case LPP_VOLTAGE:
|
||||
case LPP_CURRENT:
|
||||
case LPP_DIRECTION:
|
||||
case LPP_POWER:
|
||||
return 2;
|
||||
/* --------------------- Cayenne LPP helpers ----------------------------*/
|
||||
|
||||
static float findTelemValue(const uint8_t* buf, uint8_t size, uint8_t channel, uint8_t type, float def_value) {
|
||||
uint8_t i = 0;
|
||||
|
||||
while (i + 2 < size) {
|
||||
// Get channel #
|
||||
uint8_t ch = buf[i++];
|
||||
// Get data type
|
||||
uint8_t t = buf[i++];
|
||||
uint8_t sz = LPPData::getDataSize(t);
|
||||
|
||||
if (ch == channel && t == type) {
|
||||
return LPPData::getFloat(&buf[i], sz, LPPData::getMultiplier(t), LPPData::isSigned(t));
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static uint32_t getMultiplier(uint8_t type) {
|
||||
switch (type) {
|
||||
case LPP_CURRENT:
|
||||
case LPP_DISTANCE:
|
||||
case LPP_ENERGY:
|
||||
return 1000;
|
||||
case LPP_VOLTAGE:
|
||||
case LPP_ANALOG_INPUT:
|
||||
case LPP_ANALOG_OUTPUT:
|
||||
return 100;
|
||||
case LPP_TEMPERATURE:
|
||||
case LPP_BAROMETRIC_PRESSURE:
|
||||
case LPP_RELATIVE_HUMIDITY:
|
||||
return 10;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static bool isSigned(uint8_t type) {
|
||||
return type == LPP_ALTITUDE || type == LPP_TEMPERATURE || type == LPP_GYROMETER ||
|
||||
type == LPP_ANALOG_INPUT || type == LPP_ANALOG_OUTPUT || type == LPP_GPS || type == LPP_ACCELEROMETER;
|
||||
}
|
||||
|
||||
static float getFloat(const uint8_t * buffer, uint8_t size, uint32_t multiplier, bool is_signed) {
|
||||
uint32_t value = 0;
|
||||
for (uint8_t i = 0; i < size; i++) {
|
||||
value = (value << 8) + buffer[i];
|
||||
i += sz; // skip
|
||||
}
|
||||
return def_value; // not found
|
||||
}
|
||||
|
||||
int sign = 1;
|
||||
if (is_signed) {
|
||||
uint32_t bit = 1ul << ((size * 8) - 1);
|
||||
if ((value & bit) == bit) {
|
||||
value = (bit << 1) - value;
|
||||
sign = -1;
|
||||
/* ------------------ end Cayenne LPP helpers ----------------------*/
|
||||
|
||||
bool SensorMesh::telemHasChanged(ClientInfo* c) {
|
||||
auto buf = telemetry.getBuffer();
|
||||
uint8_t size = telemetry.getSize();
|
||||
uint8_t i = 0;
|
||||
bool changed = false;
|
||||
|
||||
while (i + 2 < c->extra.sensor.min_deltas_len) {
|
||||
uint8_t ch = c->extra.sensor.min_deltas[i]; // Get channel #
|
||||
uint8_t t = c->extra.sensor.min_deltas[i + 1]; // Get data type
|
||||
uint8_t sz = LPPData::getDataSize(t);
|
||||
|
||||
float min_delta = LPPData::getFloat(&c->extra.sensor.min_deltas[i + 2], sz, LPPData::getMultiplier(t), LPPData::isSigned(t));
|
||||
float pv = LPPData::getFloat(&c->extra.sensor.prev_telem[i + 2], sz, LPPData::getMultiplier(t), LPPData::isSigned(t));
|
||||
|
||||
float v = findTelemValue(buf, size, ch, t, 0.0f);
|
||||
if (abs(v - pv) > min_delta) changed = true; // Yes, has changed
|
||||
|
||||
i += 2 + sz; // skip
|
||||
}
|
||||
if (changed) {
|
||||
// take snapshot of all _monitored_ telem values, for next cycle
|
||||
i = 0;
|
||||
while (i + 2 < c->extra.sensor.min_deltas_len) {
|
||||
uint8_t ch = c->extra.sensor.min_deltas[i]; // Get channel #
|
||||
uint8_t t = c->extra.sensor.min_deltas[i + 1]; // Get data type
|
||||
uint8_t sz = LPPData::getDataSize(t);
|
||||
|
||||
c->extra.sensor.prev_telem[i] = ch;
|
||||
c->extra.sensor.prev_telem[i + 1] = t;
|
||||
|
||||
float v = findTelemValue(buf, size, ch, t, 0.0f);
|
||||
LPPData::putFloat(&c->extra.sensor.prev_telem[i + 2], v, sz, LPPData::getMultiplier(t), LPPData::isSigned(t));
|
||||
|
||||
i += 2 + sz; // skip
|
||||
}
|
||||
}
|
||||
return sign * ((float) value / multiplier);
|
||||
return changed;
|
||||
}
|
||||
|
||||
static uint8_t putFloat(uint8_t * dest, float value, uint8_t size, uint32_t multiplier, bool is_signed) {
|
||||
// check sign
|
||||
bool sign = value < 0;
|
||||
if (sign) value = -value;
|
||||
uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len) {
|
||||
uint8_t perms = from->isAdmin() ? 0xFF : from->permissions;
|
||||
|
||||
// get value to store
|
||||
uint32_t v = value * multiplier;
|
||||
|
||||
// format an uint32_t as if it was an int32_t
|
||||
if (is_signed & sign) {
|
||||
uint32_t mask = (1 << (size * 8)) - 1;
|
||||
v = v & mask;
|
||||
if (sign) v = mask - v + 1;
|
||||
}
|
||||
|
||||
// add bytes (MSB first)
|
||||
for (uint8_t i=1; i<=size; i++) {
|
||||
dest[size - i] = (v & 0xFF);
|
||||
v >>= 8;
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
uint8_t SensorMesh::handleRequest(uint8_t perms, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len) {
|
||||
memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag')
|
||||
|
||||
if (req_type == REQ_TYPE_GET_TELEMETRY_DATA) { // allow all
|
||||
@@ -181,6 +153,10 @@ uint8_t SensorMesh::handleRequest(uint8_t perms, uint32_t sender_timestamp, uint
|
||||
// query other sensors -- target specific
|
||||
sensors.querySensors(0xFF & perm_mask, telemetry); // allow all telemetry permissions for admin or guest
|
||||
// TODO: let requester know permissions they have: telemetry.addPresence(TELEM_CHANNEL_SELF, perms);
|
||||
float temperature = board.getMCUTemperature();
|
||||
if (!isnan(temperature)) { // Supported boards with built-in temperature sensor. ESP32-C3 may return NAN
|
||||
telemetry.addTemperature(TELEM_CHANNEL_SELF, temperature); // Built-in MCU Temperature
|
||||
}
|
||||
|
||||
uint8_t tlen = telemetry.getSize();
|
||||
memcpy(&reply_data[4], telemetry.getBuffer(), tlen);
|
||||
@@ -211,12 +187,12 @@ uint8_t SensorMesh::handleRequest(uint8_t perms, uint32_t sender_timestamp, uint
|
||||
auto d = &data[i];
|
||||
reply_data[ofs++] = d->_channel;
|
||||
reply_data[ofs++] = d->_lpp_type;
|
||||
uint8_t sz = getDataSize(d->_lpp_type);
|
||||
uint32_t mult = getMultiplier(d->_lpp_type);
|
||||
bool is_signed = isSigned(d->_lpp_type);
|
||||
ofs += putFloat(&reply_data[ofs], d->_min, sz, mult, is_signed);
|
||||
ofs += putFloat(&reply_data[ofs], d->_max, sz, mult, is_signed);
|
||||
ofs += putFloat(&reply_data[ofs], d->_avg, sz, mult, is_signed);
|
||||
uint8_t sz = LPPData::getDataSize(d->_lpp_type);
|
||||
uint32_t mult = LPPData::getMultiplier(d->_lpp_type);
|
||||
bool is_signed = LPPData::isSigned(d->_lpp_type);
|
||||
ofs += LPPData::putFloat(&reply_data[ofs], d->_min, sz, mult, is_signed);
|
||||
ofs += LPPData::putFloat(&reply_data[ofs], d->_max, sz, mult, is_signed);
|
||||
ofs += LPPData::putFloat(&reply_data[ofs], d->_avg, sz, mult, is_signed);
|
||||
}
|
||||
return ofs;
|
||||
}
|
||||
@@ -234,6 +210,45 @@ uint8_t SensorMesh::handleRequest(uint8_t perms, uint32_t sender_timestamp, uint
|
||||
return ofs;
|
||||
}
|
||||
}
|
||||
if (req_type == REQ_TYPE_SUBSCRIBE && payload_len >= 8 && (perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) {
|
||||
memcpy(&from->extra.sensor.push_tag, &payload[0], 4);
|
||||
uint16_t timeout_secs;
|
||||
memcpy(&timeout_secs, &payload[4], 2);
|
||||
uint8_t reserved = payload[6];
|
||||
uint8_t min_deltas_len = payload[7];
|
||||
RegionEntry* r;
|
||||
if (recv_pkt_region && !recv_pkt_region->isWildcard()) { // use request scope
|
||||
r = recv_pkt_region;
|
||||
} else { // use default scope
|
||||
r = region_map.getDefaultRegion();
|
||||
}
|
||||
uint8_t reply_len;
|
||||
if (r && min_deltas_len >= 3 && min_deltas_len <= sizeof(from->extra.sensor.min_deltas)) {
|
||||
from->extra.sensor.scope_region_id = r->id;
|
||||
from->extra.sensor.expiry_timestamp = getRTCClock()->getCurrentTime() + timeout_secs;
|
||||
from->extra.sensor.min_deltas_len = min_deltas_len;
|
||||
memcpy(from->extra.sensor.min_deltas, &payload[8], min_deltas_len);
|
||||
// reply with actual expiry seconds (we could modify/impose restriction)
|
||||
memcpy(&reply_data[4], &timeout_secs, 2);
|
||||
memset(&reply_data[6], 0, 2); // reserved
|
||||
strcpy((char *)&reply_data[8], r ? r->name : ""); // reply with name of scope that will be used
|
||||
reply_len = 8 + strlen((char *)&reply_data[8]);
|
||||
} else {
|
||||
memset(&reply_data[4], 0, 4); // expiry secs (0 for error)
|
||||
reply_len = 8;
|
||||
}
|
||||
return reply_len;
|
||||
}
|
||||
if (req_type == REQ_TYPE_UNSUBSCRIBE && (perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) {
|
||||
from->extra.sensor.scope_region_id = 0;
|
||||
from->extra.sensor.push_tag = 0;
|
||||
from->extra.sensor.expiry_timestamp = 0;
|
||||
from->extra.sensor.min_deltas_len = 0;
|
||||
// REVISIT: maybe return some stats, eg total number of telemetry pushes since SUBSCRIBE?
|
||||
memset(&reply_data[4], 0, 8); // success
|
||||
getRNG()->random(&reply_data[12], 2); // just some entropy for better packet-hash uniqueness
|
||||
return 12 + 2;
|
||||
}
|
||||
return 0; // unknown command
|
||||
}
|
||||
|
||||
@@ -262,7 +277,7 @@ void SensorMesh::sendAlert(const ClientInfo* c, Trigger* t) {
|
||||
sendDirect(pkt, c->out_path, c->out_path_len);
|
||||
} else {
|
||||
unsigned long delay_millis = 0;
|
||||
sendFlood(pkt, delay_millis, _prefs.path_hash_mode + 1);
|
||||
sendFloodScoped(default_scope, pkt, delay_millis, _prefs.path_hash_mode + 1);
|
||||
}
|
||||
}
|
||||
t->send_expiry = futureMillis(ALERT_ACK_EXPIRY_MILLIS);
|
||||
@@ -330,6 +345,25 @@ int SensorMesh::getAGCResetInterval() const {
|
||||
return ((int)_prefs.agc_reset_interval) * 4000; // milliseconds
|
||||
}
|
||||
|
||||
void SensorMesh::startRegionsLoad() {
|
||||
temp_map.resetFrom(region_map); // rebuild regions in a temp instance
|
||||
memset(load_stack, 0, sizeof(load_stack));
|
||||
load_stack[0] = &temp_map.getWildcard();
|
||||
region_load_active = true;
|
||||
}
|
||||
|
||||
bool SensorMesh::saveRegions() {
|
||||
return region_map.save(_fs);
|
||||
}
|
||||
|
||||
void SensorMesh::onDefaultRegionChanged(const RegionEntry* r) {
|
||||
if (r) {
|
||||
region_map.getTransportKeysFor(*r, &default_scope, 1);
|
||||
} else {
|
||||
memset(default_scope.key, 0, sizeof(default_scope.key));
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t SensorMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data, bool is_flood) {
|
||||
ClientInfo* client;
|
||||
if (data[0] == 0) { // blank password, just check if sender is in ACL
|
||||
@@ -340,11 +374,20 @@ uint8_t SensorMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t*
|
||||
#endif
|
||||
return 0;
|
||||
}
|
||||
// CUSTOM (TeTeHacko): a blank login has a replay floor too -- replayed, it
|
||||
// gained nothing, but each copy made us send a reply.
|
||||
if (sender_timestamp <= client->last_timestamp) return 0;
|
||||
acl.persistTimestamp(client, sender_timestamp, getRTCClock()->getCurrentTime());
|
||||
client->last_timestamp = sender_timestamp;
|
||||
} else {
|
||||
// CUSTOM (TeTeHacko): capped wrong passwords (LoginGuard.h); a known admin is never locked out
|
||||
ClientInfo* known = acl.getClient(sender.pub_key, PUB_KEY_SIZE);
|
||||
if (login_guard.locked(millis()) && !(known && known->isAdmin())) return 0;
|
||||
if (strcmp((char *) data, _prefs.password) != 0) { // check for valid admin password
|
||||
#if MESH_DEBUG
|
||||
MESH_DEBUG_PRINTLN("Invalid password: %s", &data[4]);
|
||||
MESH_DEBUG_PRINTLN("Invalid password: %s", &data[0]);
|
||||
#endif
|
||||
login_guard.failed(millis()); // CUSTOM (TeTeHacko)
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -353,11 +396,11 @@ uint8_t SensorMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t*
|
||||
MESH_DEBUG_PRINTLN("Possible login replay attack!");
|
||||
return 0; // FATAL: client table is full -OR- replay attack
|
||||
}
|
||||
|
||||
MESH_DEBUG_PRINTLN("Login success!");
|
||||
client->last_timestamp = sender_timestamp;
|
||||
client->last_activity = getRTCClock()->getCurrentTime();
|
||||
client->permissions |= PERM_ACL_ADMIN;
|
||||
acl.persistTimestamp(client, sender_timestamp, getRTCClock()->getCurrentTime()); // CUSTOM (TeTeHacko): admin only, so after the role
|
||||
memcpy(client->shared_secret, secret, PUB_KEY_SIZE);
|
||||
|
||||
dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY);
|
||||
@@ -379,7 +422,41 @@ uint8_t SensorMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t*
|
||||
return 13; // reply length
|
||||
}
|
||||
|
||||
void SensorMesh::handleCommand(uint32_t sender_timestamp, char* command, char* reply) {
|
||||
void SensorMesh::handleCommand(ClientInfo* from, uint32_t sender_timestamp, char* command, char* reply) {
|
||||
if (region_load_active) {
|
||||
if (StrHelper::isBlank(command)) { // empty/blank line, signal to terminate 'load' operation
|
||||
region_map = temp_map; // copy over the temp instance as new current map
|
||||
region_load_active = false;
|
||||
|
||||
sprintf(reply, "OK - loaded %d regions", region_map.getCount());
|
||||
} else {
|
||||
char *np = command;
|
||||
while (*np == ' ') np++; // skip indent
|
||||
int indent = np - command;
|
||||
|
||||
char *ep = np;
|
||||
while (RegionMap::is_name_char(*ep)) ep++;
|
||||
if (*ep) { *ep++ = 0; } // set null terminator for end of name
|
||||
|
||||
while (*ep && *ep != 'F') ep++; // look for (optional) flags
|
||||
|
||||
if (indent > 0 && indent < 8 && strlen(np) > 0) {
|
||||
auto parent = load_stack[indent - 1];
|
||||
if (parent) {
|
||||
auto old = region_map.findByName(np);
|
||||
auto nw = temp_map.putRegion(np, parent->id, old ? old->id : 0); // carry-over the current ID (if name already exists)
|
||||
if (nw) {
|
||||
nw->flags = old ? old->flags : (*ep == 'F' ? 0 : REGION_DENY_FLOOD); // carry-over flags from curr
|
||||
|
||||
load_stack[indent] = nw; // keep pointers to parent regions, to resolve parent_id's
|
||||
}
|
||||
}
|
||||
}
|
||||
reply[0] = 0;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
while (*command == ' ') command++; // skip leading spaces
|
||||
|
||||
if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI)
|
||||
@@ -400,10 +477,11 @@ void SensorMesh::handleCommand(uint32_t sender_timestamp, char* command, char* r
|
||||
if (sp == NULL) {
|
||||
strcpy(reply, "Err - bad params");
|
||||
} else {
|
||||
int hex_len = min(sp - hex, PUB_KEY_SIZE*2);
|
||||
uint8_t pubkey[PUB_KEY_SIZE];
|
||||
|
||||
*sp++ = 0; // replace space with null terminator
|
||||
|
||||
uint8_t pubkey[PUB_KEY_SIZE];
|
||||
int hex_len = min(sp - hex, PUB_KEY_SIZE*2);
|
||||
if (mesh::Utils::fromHex(pubkey, hex_len / 2, hex)) {
|
||||
uint8_t perms = atoi(sp);
|
||||
if (acl.applyPermissions(self_id, pubkey, hex_len / 2, perms)) {
|
||||
@@ -446,11 +524,30 @@ void SensorMesh::handleCommand(uint32_t sender_timestamp, char* command, char* r
|
||||
board.setGpio(val);
|
||||
}
|
||||
sprintf(reply, "%x", board.getGpio());
|
||||
#ifdef RADIO_DIAG
|
||||
// CUSTOM (TeTeHacko): `radiostat` / `radiokick` -- see RadioLibWrappers.cpp.
|
||||
} else if (radio_driver.diagHandleCommand(command, reply)) {
|
||||
#endif
|
||||
} else{
|
||||
_cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
|
||||
}
|
||||
}
|
||||
|
||||
mesh::DispatcherAction SensorMesh::onRecvPacket(mesh::Packet* pkt) {
|
||||
if (pkt->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD) {
|
||||
recv_pkt_region = region_map.findMatch(pkt, REGION_DENY_FLOOD);
|
||||
} else if (pkt->getRouteType() == ROUTE_TYPE_FLOOD) {
|
||||
if (region_map.getWildcard().flags & REGION_DENY_FLOOD) {
|
||||
recv_pkt_region = NULL;
|
||||
} else {
|
||||
recv_pkt_region = ®ion_map.getWildcard();
|
||||
}
|
||||
} else {
|
||||
recv_pkt_region = NULL;
|
||||
}
|
||||
return Mesh::onRecvPacket(pkt);
|
||||
}
|
||||
|
||||
void SensorMesh::onAnonDataRecv(mesh::Packet* packet, const uint8_t* secret, const mesh::Identity& sender, uint8_t* data, size_t len) {
|
||||
if (packet->getPayloadType() == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin client (unknown at this stage)
|
||||
uint32_t timestamp;
|
||||
@@ -472,10 +569,10 @@ void SensorMesh::onAnonDataRecv(mesh::Packet* packet, const uint8_t* secret, con
|
||||
// let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
|
||||
mesh::Packet* path = createPathReturn(sender, secret, packet->path, packet->path_len,
|
||||
PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
|
||||
if (path) sendFlood(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
|
||||
if (path) sendFloodReply(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
|
||||
} else {
|
||||
mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len);
|
||||
if (reply) sendFlood(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
|
||||
if (reply) sendFloodReply(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -503,7 +600,7 @@ void SensorMesh::getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) {
|
||||
void SensorMesh::sendAckTo(const ClientInfo& dest, uint32_t ack_hash, uint8_t path_hash_size) {
|
||||
if (dest.out_path_len == OUT_PATH_UNKNOWN) {
|
||||
mesh::Packet* ack = createAck(ack_hash);
|
||||
if (ack) sendFlood(ack, TXT_ACK_DELAY, path_hash_size);
|
||||
if (ack) sendFloodScoped(default_scope, ack, TXT_ACK_DELAY, path_hash_size);
|
||||
} else {
|
||||
uint32_t d = TXT_ACK_DELAY;
|
||||
if (getExtraAckTransmitCount() > 0) {
|
||||
@@ -531,7 +628,8 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i
|
||||
memcpy(×tamp, data, 4);
|
||||
|
||||
if (timestamp > from->last_timestamp) { // prevent replay attacks
|
||||
uint8_t reply_len = handleRequest(from->isAdmin() ? 0xFF : from->permissions, timestamp, data[4], &data[5], len - 5);
|
||||
acl.persistTimestamp(from, timestamp, getRTCClock()->getCurrentTime()); // CUSTOM (TeTeHacko): before acting
|
||||
uint8_t reply_len = handleRequest(from, timestamp, data[4], &data[5], len - 5);
|
||||
if (reply_len == 0) return; // invalid command
|
||||
|
||||
from->last_timestamp = timestamp;
|
||||
@@ -541,14 +639,14 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i
|
||||
// let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
|
||||
mesh::Packet* path = createPathReturn(from->id, secret, packet->path, packet->path_len,
|
||||
PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
|
||||
if (path) sendFlood(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
|
||||
if (path) sendFloodReply(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
|
||||
} else {
|
||||
mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, from->id, secret, reply_data, reply_len);
|
||||
if (reply) {
|
||||
if (from->out_path_len != OUT_PATH_UNKNOWN) { // we have an out_path, so send DIRECT
|
||||
sendDirect(reply, from->out_path, from->out_path_len, SERVER_RESPONSE_DELAY);
|
||||
} else {
|
||||
sendFlood(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
|
||||
sendFloodReply(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -561,6 +659,7 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i
|
||||
uint8_t flags = (data[4] >> 2); // message attempt number, and other flags
|
||||
|
||||
if (sender_timestamp > from->last_timestamp) { // prevent replay attacks
|
||||
acl.persistTimestamp(from, sender_timestamp, getRTCClock()->getCurrentTime()); // CUSTOM (TeTeHacko): before acting
|
||||
if (flags == TXT_TYPE_PLAIN) {
|
||||
bool handled = handleIncomingMsg(*from, sender_timestamp, &data[5], flags, len - 5);
|
||||
if (handled) { // if msg was handled then send an ack
|
||||
@@ -571,22 +670,23 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i
|
||||
// let this sender know path TO here, so they can use sendDirect(), and ALSO encode the ACK
|
||||
mesh::Packet* path = createPathReturn(from->id, secret, packet->path, packet->path_len,
|
||||
PAYLOAD_TYPE_ACK, (uint8_t *) &ack_hash, 4);
|
||||
if (path) sendFlood(path, TXT_ACK_DELAY, packet->getPathHashSize());
|
||||
if (path) sendFloodReply(path, TXT_ACK_DELAY, packet->getPathHashSize());
|
||||
} else {
|
||||
sendAckTo(*from, ack_hash, packet->getPathHashSize());
|
||||
}
|
||||
}
|
||||
} else if (flags == TXT_TYPE_CLI_DATA) {
|
||||
} else if (flags == TXT_TYPE_CLI_DATA || flags == TXT_TYPE_CLI_COMMAND) {
|
||||
from->last_timestamp = sender_timestamp;
|
||||
from->last_activity = getRTCClock()->getCurrentTime();
|
||||
|
||||
// len can be > original length, but 'text' will be padded with zeroes
|
||||
data[len] = 0; // need to make a C string again, with null terminator
|
||||
|
||||
uint8_t temp[166];
|
||||
// 5-byte datagram header + 3-byte reflected CLI prefix + 160-byte reply text + NUL
|
||||
uint8_t temp[169];
|
||||
char *command = (char *) &data[5];
|
||||
char *reply = (char *) &temp[5];
|
||||
handleCommand(sender_timestamp, command, reply);
|
||||
handleCommand(from, sender_timestamp, command, reply);
|
||||
|
||||
int text_len = strlen(reply);
|
||||
if (text_len > 0) {
|
||||
@@ -601,7 +701,7 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i
|
||||
auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, from->id, secret, temp, 5 + text_len);
|
||||
if (reply) {
|
||||
if (from->out_path_len == OUT_PATH_UNKNOWN) {
|
||||
sendFlood(reply, CLI_REPLY_DELAY_MILLIS, packet->getPathHashSize());
|
||||
sendFloodReply(reply, CLI_REPLY_DELAY_MILLIS, packet->getPathHashSize());
|
||||
} else {
|
||||
sendDirect(reply, from->out_path, from->out_path_len, CLI_REPLY_DELAY_MILLIS);
|
||||
}
|
||||
@@ -699,7 +799,7 @@ void SensorMesh::onAckRecv(mesh::Packet* packet, uint32_t ack_crc) {
|
||||
|
||||
SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables)
|
||||
: mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
|
||||
region_map(key_store),
|
||||
region_map(key_store), temp_map(key_store),
|
||||
_cli(board, rtc, sensors, region_map, acl, &_prefs, this),
|
||||
telemetry(MAX_PACKET_PAYLOAD - 4)
|
||||
{
|
||||
@@ -708,6 +808,8 @@ SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::Millise
|
||||
last_read_time = 0;
|
||||
num_alert_tasks = 0;
|
||||
set_radio_at = revert_radio_at = 0;
|
||||
recv_pkt_region = NULL;
|
||||
region_load_active = false;
|
||||
|
||||
// defaults
|
||||
_prefs.airtime_factor = 1.0;
|
||||
@@ -771,8 +873,11 @@ void SensorMesh::begin(FILESYSTEM* fs) {
|
||||
|
||||
radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
|
||||
radio_driver.setTxPower(_prefs.tx_power_dbm);
|
||||
board.setLoRaFemLnaEnabled(_prefs.radio_fem_rxgain);
|
||||
board.setLoRaFemPaGainEnabled(_prefs.radio_fem_txgain);
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
_prefs.getRadioPrefs()->applyRxPowerSaving(_prefs.sf, _prefs.bw); // CUSTOM (TeTeHacko)
|
||||
#endif
|
||||
|
||||
board.attachDynamicPrefs(_prefs.getCustom());
|
||||
|
||||
updateAdvertTimer();
|
||||
updateFloodAdvertTimer();
|
||||
@@ -782,6 +887,7 @@ void SensorMesh::begin(FILESYSTEM* fs) {
|
||||
#if ENV_INCLUDE_GPS == 1
|
||||
applyGpsPrefs();
|
||||
#endif
|
||||
sensors.applyInaShunt(_prefs.ina_shunt_mohm); // CUSTOM (TeTeHacko)
|
||||
}
|
||||
|
||||
bool SensorMesh::formatFileSystem() {
|
||||
@@ -820,11 +926,43 @@ void SensorMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t
|
||||
revert_radio_at = futureMillis(2000 + timeout_mins*60*1000); // schedule when to revert radio params
|
||||
}
|
||||
|
||||
void SensorMesh::sendFloodScoped(const TransportKey& scope, mesh::Packet* pkt, uint32_t delay_millis, uint8_t path_hash_size) {
|
||||
if (scope.isNull()) {
|
||||
sendFlood(pkt, delay_millis, path_hash_size);
|
||||
} else {
|
||||
uint16_t codes[2];
|
||||
codes[0] = scope.calcTransportCode(pkt);
|
||||
codes[1] = 0; // REVISIT: set to 'home' Region, for sender/return region?
|
||||
sendFlood(pkt, codes, delay_millis, path_hash_size);
|
||||
}
|
||||
}
|
||||
|
||||
void SensorMesh::sendFloodReply(mesh::Packet* packet, unsigned long delay_millis, uint8_t path_hash_size) {
|
||||
TransportKey req_scope;
|
||||
bool is_wildcard = recv_pkt_region != NULL && recv_pkt_region->isWildcard();
|
||||
bool req_scope_known = recv_pkt_region != NULL && !is_wildcard
|
||||
&& region_map.getTransportKeysFor(*recv_pkt_region, &req_scope, 1) > 0;
|
||||
|
||||
switch (mesh::chooseReplyScope(req_scope_known, is_wildcard, !default_scope.isNull())) {
|
||||
case mesh::REPLY_SCOPE_REQUEST:
|
||||
sendFloodScoped(req_scope, packet, delay_millis, path_hash_size); // reply with same scope as request
|
||||
break;
|
||||
case mesh::REPLY_SCOPE_DEFAULT:
|
||||
// requester's scope is unknown: DIRECT request (no transport codes), or code matched no Region.
|
||||
// un-scoped would be dropped at hop 0 by repeaters running flood.max.unscoped=0
|
||||
sendFloodScoped(default_scope, packet, delay_millis, path_hash_size);
|
||||
break;
|
||||
case mesh::REPLY_SCOPE_NONE:
|
||||
sendFlood(packet, delay_millis, path_hash_size); // send un-scoped
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void SensorMesh::sendSelfAdvertisement(int delay_millis, bool flood) {
|
||||
mesh::Packet* pkt = createSelfAdvert();
|
||||
if (pkt) {
|
||||
if (flood) {
|
||||
sendFlood(pkt, delay_millis, _prefs.path_hash_mode + 1);
|
||||
sendFloodScoped(default_scope, pkt, delay_millis, _prefs.path_hash_mode + 1);
|
||||
} else {
|
||||
sendZeroHop(pkt, delay_millis);
|
||||
}
|
||||
@@ -866,23 +1004,7 @@ void SensorMesh::formatPacketStatsReply(char *reply) {
|
||||
}
|
||||
|
||||
float SensorMesh::getTelemValue(uint8_t channel, uint8_t type) {
|
||||
auto buf = telemetry.getBuffer();
|
||||
uint8_t size = telemetry.getSize();
|
||||
uint8_t i = 0;
|
||||
|
||||
while (i + 2 < size) {
|
||||
// Get channel #
|
||||
uint8_t ch = buf[i++];
|
||||
// Get data type
|
||||
uint8_t t = buf[i++];
|
||||
uint8_t sz = getDataSize(t);
|
||||
|
||||
if (ch == channel && t == type) {
|
||||
return getFloat(&buf[i], sz, getMultiplier(t), isSigned(t));
|
||||
}
|
||||
i += sz; // skip
|
||||
}
|
||||
return 0.0f; // not found
|
||||
return findTelemValue(telemetry.getBuffer(), telemetry.getSize(), channel, type, 0.0f);
|
||||
}
|
||||
|
||||
bool SensorMesh::getGPS(uint8_t channel, float& lat, float& lon, float& alt) {
|
||||
@@ -902,7 +1024,7 @@ void SensorMesh::loop() {
|
||||
if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
|
||||
mesh::Packet* pkt = createSelfAdvert();
|
||||
unsigned long delay_millis = 0;
|
||||
if (pkt) sendFlood(pkt, delay_millis, _prefs.path_hash_mode + 1);
|
||||
if (pkt) sendFloodScoped(default_scope, pkt, delay_millis, _prefs.path_hash_mode + 1);
|
||||
|
||||
updateFloodAdvertTimer(); // schedule next flood advert
|
||||
updateAdvertTimer(); // also schedule local advert (so they don't overlap)
|
||||
@@ -916,12 +1038,18 @@ void SensorMesh::loop() {
|
||||
if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
|
||||
set_radio_at = 0; // clear timer
|
||||
radio_driver.setParams(pending_freq, pending_bw, pending_sf, pending_cr);
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
_prefs.getRadioPrefs()->applyRxPowerSaving(pending_sf, pending_bw);
|
||||
#endif
|
||||
MESH_DEBUG_PRINTLN("Temp radio params");
|
||||
}
|
||||
|
||||
if (revert_radio_at && millisHasNowPassed(revert_radio_at)) { // revert radio params to orig
|
||||
revert_radio_at = 0; // clear timer
|
||||
radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
_prefs.getRadioPrefs()->applyRxPowerSaving(_prefs.sf, _prefs.bw);
|
||||
#endif
|
||||
MESH_DEBUG_PRINTLN("Radio params restored");
|
||||
}
|
||||
|
||||
@@ -931,6 +1059,39 @@ void SensorMesh::loop() {
|
||||
telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f);
|
||||
// query other sensors -- target specific
|
||||
sensors.querySensors(0xFF, telemetry); // allow all telemetry permissions
|
||||
// This MCU temperature will be overridden by external sensors (if any)
|
||||
float temperature = board.getMCUTemperature();
|
||||
if (!isnan(temperature)) { // Supported boards with built-in temperature sensor. ESP32-C3 may return NAN
|
||||
telemetry.addTemperature(TELEM_CHANNEL_SELF, temperature); // Built-in MCU Temperature
|
||||
}
|
||||
|
||||
// compare with previous telemetry, check if any deltas are greater than subscriber minimums
|
||||
for (int i = 0; i < acl.getNumClients(); i++) {
|
||||
auto c = acl.getClientByIdx(i);
|
||||
if (c->permissions == 0 || c->extra.sensor.scope_region_id == 0 || c->extra.sensor.min_deltas_len == 0) continue; // skip deleted entries, or Not subscribed to deltas
|
||||
RegionEntry* r = region_map.findById(c->extra.sensor.scope_region_id);
|
||||
if (r == NULL) continue; // unknown region scope
|
||||
if (curr > c->extra.sensor.expiry_timestamp) continue; // subscription now expired
|
||||
if (telemHasChanged(c)) {
|
||||
TransportKey scope;
|
||||
if (region_map.getTransportKeysFor(*r, &scope, 1) > 0) {
|
||||
uint8_t tlen = telemetry.getSize();
|
||||
memcpy(reply_data, &c->extra.sensor.push_tag, 4);
|
||||
uint32_t timestamp = getRTCClock()->getCurrentTimeUnique();
|
||||
memcpy(&reply_data[4], ×tamp, 4);
|
||||
memcpy(&reply_data[8], telemetry.getBuffer(), tlen);
|
||||
|
||||
mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, c->id, c->shared_secret, reply_data, 8 + tlen);
|
||||
if (reply) {
|
||||
if (c->out_path_len != OUT_PATH_UNKNOWN) { // we have an out_path, so send DIRECT
|
||||
sendDirect(reply, c->out_path, c->out_path_len, 0);
|
||||
} else {
|
||||
sendFloodScoped(scope, reply, 0, _prefs.path_hash_mode + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onSensorDataRead();
|
||||
|
||||
@@ -973,7 +1134,7 @@ void SensorMesh::loop() {
|
||||
}
|
||||
}
|
||||
|
||||
// is there are pending dirty contacts write needed?
|
||||
// pending dirty contacts write needed?
|
||||
if (dirty_contacts_expiry && millisHasNowPassed(dirty_contacts_expiry)) {
|
||||
acl.save(_fs);
|
||||
dirty_contacts_expiry = 0;
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
#include <helpers/CommonCLI.h>
|
||||
#include <helpers/StatsFormatHelper.h>
|
||||
#include <helpers/ClientACL.h>
|
||||
#include <helpers/LoginGuard.h> // CUSTOM (TeTeHacko)
|
||||
#include <helpers/RegionMap.h>
|
||||
#include <RTClib.h>
|
||||
#include <target.h>
|
||||
@@ -34,16 +35,14 @@
|
||||
#define PERM_RECV_ALERTS_HI (1 << 7) // high priority alerts
|
||||
|
||||
#ifndef FIRMWARE_BUILD_DATE
|
||||
#define FIRMWARE_BUILD_DATE "14 Aug 2026"
|
||||
#define FIRMWARE_BUILD_DATE "15 Oct 2026"
|
||||
#endif
|
||||
|
||||
#ifndef FIRMWARE_VERSION
|
||||
#define FIRMWARE_VERSION "v1.17.1"
|
||||
#define FIRMWARE_VERSION "v1.18.0"
|
||||
#endif
|
||||
|
||||
#define FIRMWARE_ROLE "sensor"
|
||||
|
||||
#define MAX_SEARCH_RESULTS 8
|
||||
#define MAX_SEARCH_RESULTS 24
|
||||
#define MAX_CONCURRENT_ALERTS 4
|
||||
|
||||
class SensorMesh : public mesh::Mesh, public CommonCLICallbacks {
|
||||
@@ -51,12 +50,12 @@ public:
|
||||
SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables);
|
||||
void begin(FILESYSTEM* fs);
|
||||
void loop();
|
||||
void handleCommand(uint32_t sender_timestamp, char* command, char* reply);
|
||||
void handleCommand(ClientInfo* from, uint32_t sender_timestamp, char* command, char* reply);
|
||||
|
||||
// CommonCLI callbacks
|
||||
const char* getFirmwareVer() override { return FIRMWARE_VERSION; }
|
||||
const char* getBuildDate() override { return FIRMWARE_BUILD_DATE; }
|
||||
const char* getRole() override { return FIRMWARE_ROLE; }
|
||||
const char* getRole() override { return "sensor"; }
|
||||
const char* getNodeName() { return _prefs.node_name; }
|
||||
NodePrefs* getNodePrefs() { return &_prefs; }
|
||||
void savePrefs() override { _cli.savePrefs(_fs); }
|
||||
@@ -78,9 +77,15 @@ public:
|
||||
void saveIdentity(const mesh::LocalIdentity& new_id) override;
|
||||
void clearStats() override { }
|
||||
void applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, int timeout_mins) override;
|
||||
void startRegionsLoad() override;
|
||||
bool saveRegions() override;
|
||||
void onDefaultRegionChanged(const RegionEntry* r) override;
|
||||
|
||||
float getTelemValue(uint8_t channel, uint8_t type);
|
||||
|
||||
void sendFloodScoped(const TransportKey& scope, mesh::Packet* pkt, uint32_t delay_millis, uint8_t path_hash_size);
|
||||
void sendFloodReply(mesh::Packet* packet, unsigned long delay_millis, uint8_t path_hash_size);
|
||||
|
||||
protected:
|
||||
// current telemetry data queries
|
||||
float getVoltage(uint8_t channel) { return getTelemValue(channel, LPP_VOLTAGE); }
|
||||
@@ -93,12 +98,12 @@ protected:
|
||||
bool getGPS(uint8_t channel, float& lat, float& lon, float& alt);
|
||||
|
||||
// alerts
|
||||
enum AlertPriority { LOW_PRI_ALERT, HIGH_PRI_ALERT };
|
||||
enum AlertPriority : uint8_t { LOW_PRI_ALERT, HIGH_PRI_ALERT };
|
||||
|
||||
struct Trigger {
|
||||
uint32_t timestamp;
|
||||
AlertPriority pri;
|
||||
uint32_t expected_acks[4];
|
||||
AlertPriority pri;
|
||||
int8_t curr_contact_idx;
|
||||
uint8_t attempt;
|
||||
unsigned long send_expiry;
|
||||
@@ -116,12 +121,18 @@ protected:
|
||||
// Mesh overrides
|
||||
float getAirtimeBudgetFactor() const override;
|
||||
bool allowPacketForward(const mesh::Packet* packet) override;
|
||||
|
||||
// Šířku path hashe volí ODESÍLATEL, takže musí přijít z prefs tohohle uzlu.
|
||||
// Díky tomuhle overridu ji dostanou i volání send*(), která ji nepředávají
|
||||
// explicitně (ACKy, PATH-return, zerohop odpovědi sousedovi).
|
||||
uint8_t getSelfPathHashSize() const override { return _prefs.path_hash_mode + 1; }
|
||||
int calcRxDelay(float score, uint32_t air_time) const override;
|
||||
uint32_t getRetransmitDelay(const mesh::Packet* packet) override;
|
||||
uint32_t getDirectRetransmitDelay(const mesh::Packet* packet) override;
|
||||
int getInterferenceThreshold() const override;
|
||||
bool getCADEnabled() const override;
|
||||
int getAGCResetInterval() const override;
|
||||
mesh::DispatcherAction onRecvPacket(mesh::Packet* pkt) override;
|
||||
void onAnonDataRecv(mesh::Packet* packet, const uint8_t* secret, const mesh::Identity& sender, uint8_t* data, size_t len) override;
|
||||
int searchPeersByHash(const uint8_t* hash) override;
|
||||
void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override;
|
||||
@@ -129,6 +140,7 @@ protected:
|
||||
bool onPeerPathRecv(mesh::Packet* packet, int sender_idx, const uint8_t* secret, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) override;
|
||||
void onControlDataRecv(mesh::Packet* packet) override;
|
||||
void onAckRecv(mesh::Packet* packet, uint32_t ack_crc) override;
|
||||
|
||||
virtual bool handleIncomingMsg(ClientInfo& from, uint32_t timestamp, uint8_t* data, uint8_t flags, size_t len);
|
||||
void sendAckTo(const ClientInfo& dest, uint32_t ack_hash, uint8_t path_hash_size=1);
|
||||
private:
|
||||
@@ -136,12 +148,15 @@ private:
|
||||
unsigned long next_local_advert, next_flood_advert;
|
||||
NodePrefs _prefs;
|
||||
ClientACL acl;
|
||||
LoginGuard login_guard; // CUSTOM (TeTeHacko)
|
||||
CommonCLI _cli;
|
||||
uint8_t reply_data[MAX_PACKET_PAYLOAD];
|
||||
unsigned long dirty_contacts_expiry;
|
||||
CayenneLPP telemetry;
|
||||
TransportKeyStore key_store;
|
||||
RegionMap region_map;
|
||||
RegionMap region_map, temp_map;
|
||||
RegionEntry* recv_pkt_region;
|
||||
RegionEntry* load_stack[8];
|
||||
TransportKey default_scope;
|
||||
uint32_t last_read_time;
|
||||
int matching_peer_indexes[MAX_SEARCH_RESULTS];
|
||||
@@ -152,16 +167,23 @@ private:
|
||||
float pending_bw;
|
||||
uint8_t pending_sf;
|
||||
uint8_t pending_cr;
|
||||
bool region_load_active;
|
||||
|
||||
bool telemHasChanged(ClientInfo* c);
|
||||
uint8_t handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data, bool is_flood);
|
||||
uint8_t handleRequest(uint8_t perms, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len);
|
||||
uint8_t handleRequest(ClientInfo* from, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len);
|
||||
mesh::Packet* createSelfAdvert();
|
||||
|
||||
void sendAlert(const ClientInfo* c, Trigger* t);
|
||||
|
||||
#if ENV_INCLUDE_GPS == 1
|
||||
void applyGpsPrefs() {
|
||||
sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0");
|
||||
if (sensors.getSettingByKey("gps_interval") != nullptr) {
|
||||
char interval[11];
|
||||
snprintf(interval, sizeof(interval), "%lu", (unsigned long)_prefs.gps_interval);
|
||||
sensors.setSettingValue("gps_interval", interval);
|
||||
}
|
||||
_prefs.getGpsPrefs()->apply(sensors);
|
||||
}
|
||||
#endif
|
||||
};
|
||||
@@ -1,125 +0,0 @@
|
||||
#include "UITask.h"
|
||||
#include <Arduino.h>
|
||||
#include <helpers/CommonCLI.h>
|
||||
|
||||
#ifndef USER_BTN_PRESSED
|
||||
#define USER_BTN_PRESSED LOW
|
||||
#endif
|
||||
|
||||
#define AUTO_OFF_MILLIS 20000 // 20 seconds
|
||||
#define BOOT_SCREEN_MILLIS 4000 // 4 seconds
|
||||
|
||||
// 'meshcore', 128x13px
|
||||
static const uint8_t meshcore_logo [] PROGMEM = {
|
||||
0x3c, 0x01, 0xe3, 0xff, 0xc7, 0xff, 0x8f, 0x03, 0x87, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe,
|
||||
0x3c, 0x03, 0xe3, 0xff, 0xc7, 0xff, 0x8e, 0x03, 0x8f, 0xfe, 0x3f, 0xfe, 0x1f, 0xff, 0x1f, 0xfe,
|
||||
0x3e, 0x03, 0xc3, 0xff, 0x8f, 0xff, 0x0e, 0x07, 0x8f, 0xfe, 0x7f, 0xfe, 0x1f, 0xff, 0x1f, 0xfc,
|
||||
0x3e, 0x07, 0xc7, 0x80, 0x0e, 0x00, 0x0e, 0x07, 0x9e, 0x00, 0x78, 0x0e, 0x3c, 0x0f, 0x1c, 0x00,
|
||||
0x3e, 0x0f, 0xc7, 0x80, 0x1e, 0x00, 0x0e, 0x07, 0x1e, 0x00, 0x70, 0x0e, 0x38, 0x0f, 0x3c, 0x00,
|
||||
0x7f, 0x0f, 0xc7, 0xfe, 0x1f, 0xfc, 0x1f, 0xff, 0x1c, 0x00, 0x70, 0x0e, 0x38, 0x0e, 0x3f, 0xf8,
|
||||
0x7f, 0x1f, 0xc7, 0xfe, 0x0f, 0xff, 0x1f, 0xff, 0x1c, 0x00, 0xf0, 0x0e, 0x38, 0x0e, 0x3f, 0xf8,
|
||||
0x7f, 0x3f, 0xc7, 0xfe, 0x0f, 0xff, 0x1f, 0xff, 0x1c, 0x00, 0xf0, 0x1e, 0x3f, 0xfe, 0x3f, 0xf0,
|
||||
0x77, 0x3b, 0x87, 0x00, 0x00, 0x07, 0x1c, 0x0f, 0x3c, 0x00, 0xe0, 0x1c, 0x7f, 0xfc, 0x38, 0x00,
|
||||
0x77, 0xfb, 0x8f, 0x00, 0x00, 0x07, 0x1c, 0x0f, 0x3c, 0x00, 0xe0, 0x1c, 0x7f, 0xf8, 0x38, 0x00,
|
||||
0x73, 0xf3, 0x8f, 0xff, 0x0f, 0xff, 0x1c, 0x0e, 0x3f, 0xf8, 0xff, 0xfc, 0x70, 0x78, 0x7f, 0xf8,
|
||||
0xe3, 0xe3, 0x8f, 0xff, 0x1f, 0xfe, 0x3c, 0x0e, 0x3f, 0xf8, 0xff, 0xfc, 0x70, 0x3c, 0x7f, 0xf8,
|
||||
0xe3, 0xe3, 0x8f, 0xff, 0x1f, 0xfc, 0x3c, 0x0e, 0x1f, 0xf8, 0xff, 0xf8, 0x70, 0x3c, 0x7f, 0xf8,
|
||||
};
|
||||
|
||||
void UITask::begin(NodePrefs* node_prefs, const char* build_date, const char* firmware_version) {
|
||||
_prevBtnState = HIGH;
|
||||
_auto_off = millis() + AUTO_OFF_MILLIS;
|
||||
_node_prefs = node_prefs;
|
||||
_display->turnOn();
|
||||
|
||||
// strip off dash and commit hash by changing dash to null terminator
|
||||
// e.g: v1.2.3-abcdef -> v1.2.3
|
||||
char *version = strdup(firmware_version);
|
||||
char *dash = strchr(version, '-');
|
||||
if(dash){
|
||||
*dash = 0;
|
||||
}
|
||||
|
||||
// v1.2.3 (1 Jan 2025)
|
||||
snprintf(_version_info, sizeof(_version_info), "%s (%s)", version, build_date);
|
||||
free(version);
|
||||
}
|
||||
|
||||
void UITask::renderCurrScreen() {
|
||||
char tmp[80];
|
||||
if (millis() < BOOT_SCREEN_MILLIS) { // boot screen
|
||||
// meshcore logo
|
||||
_display->setColor(UIColor::corp_blue);
|
||||
int logoWidth = 128;
|
||||
_display->drawXbm((_display->width() - logoWidth) / 2, 3, meshcore_logo, logoWidth, 13);
|
||||
|
||||
// meshcore website
|
||||
const char* website = "https://meshcore.io";
|
||||
_display->setColor(UIColor::primary_txt);
|
||||
_display->setTextSize(1);
|
||||
uint16_t websiteWidth = _display->getTextWidth(website);
|
||||
_display->setCursor((_display->width() - websiteWidth) / 2, 22);
|
||||
_display->print(website);
|
||||
|
||||
// version info
|
||||
_display->setTextSize(1);
|
||||
uint16_t versionWidth = _display->getTextWidth(_version_info);
|
||||
_display->setCursor((_display->width() - versionWidth) / 2, 35);
|
||||
_display->print(_version_info);
|
||||
|
||||
// node type
|
||||
const char* node_type = "< Sensor >";
|
||||
uint16_t typeWidth = _display->getTextWidth(node_type);
|
||||
_display->setCursor((_display->width() - typeWidth) / 2, 48);
|
||||
_display->print(node_type);
|
||||
} else { // home screen
|
||||
// node name
|
||||
_display->setCursor(0, 0);
|
||||
_display->setTextSize(1);
|
||||
_display->setColor(UIColor::primary_txt);
|
||||
_display->print(_node_prefs->node_name);
|
||||
|
||||
// freq / sf
|
||||
_display->setCursor(0, 20);
|
||||
sprintf(tmp, "FREQ: %06.3f SF%d", _node_prefs->freq, _node_prefs->sf);
|
||||
_display->print(tmp);
|
||||
|
||||
// bw / cr
|
||||
_display->setCursor(0, 30);
|
||||
sprintf(tmp, "BW: %03.2f CR: %d", _node_prefs->bw, _node_prefs->cr);
|
||||
_display->print(tmp);
|
||||
}
|
||||
}
|
||||
|
||||
void UITask::loop() {
|
||||
#ifdef PIN_USER_BTN
|
||||
if (millis() >= _next_read) {
|
||||
int btnState = digitalRead(PIN_USER_BTN);
|
||||
if (btnState != _prevBtnState) {
|
||||
if (btnState == USER_BTN_PRESSED) { // pressed?
|
||||
if (_display->isOn()) {
|
||||
// TODO: any action ?
|
||||
} else {
|
||||
_display->turnOn();
|
||||
}
|
||||
_auto_off = millis() + AUTO_OFF_MILLIS; // extend auto-off timer
|
||||
}
|
||||
_prevBtnState = btnState;
|
||||
}
|
||||
_next_read = millis() + 200; // 5 reads per second
|
||||
}
|
||||
#endif
|
||||
|
||||
if (_display->isOn()) {
|
||||
if (millis() >= _next_refresh) {
|
||||
_display->startFrame();
|
||||
renderCurrScreen();
|
||||
_display->endFrame();
|
||||
|
||||
_next_refresh = millis() + 1000; // refresh every second
|
||||
}
|
||||
if (millis() > _auto_off) {
|
||||
_display->turnOff();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <helpers/ui/DisplayDriver.h>
|
||||
#include <helpers/CommonCLI.h>
|
||||
|
||||
class UITask {
|
||||
DisplayDriver* _display;
|
||||
unsigned long _next_read, _next_refresh, _auto_off;
|
||||
int _prevBtnState;
|
||||
NodePrefs* _node_prefs;
|
||||
char _version_info[32];
|
||||
|
||||
void renderCurrScreen();
|
||||
public:
|
||||
UITask(DisplayDriver& display) : _display(&display) { _next_read = _next_refresh = 0; }
|
||||
void begin(NodePrefs* node_prefs, const char* build_date, const char* firmware_version);
|
||||
|
||||
void loop();
|
||||
};
|
||||
@@ -1,9 +1,8 @@
|
||||
#include "SensorMesh.h"
|
||||
#include <helpers/NodeMaintenance.h>
|
||||
|
||||
#ifdef DISPLAY_CLASS
|
||||
#include "UITask.h"
|
||||
static UITask ui_task(display);
|
||||
#endif
|
||||
// CUSTOM (TeTeHacko): dfu, radio silence watchdog, reset reason -- see NodeMaintenance.h.
|
||||
static NodeMaintenance maint(board, radio_driver);
|
||||
|
||||
class MyMesh : public SensorMesh {
|
||||
public:
|
||||
@@ -32,6 +31,7 @@ protected:
|
||||
}
|
||||
|
||||
bool handleCustomCommand(uint32_t sender_timestamp, char* command, char* reply) override {
|
||||
if (maint.handleCommand(sender_timestamp, command, reply)) return true;
|
||||
if (strcmp(command, "magic") == 0) { // example 'custom' command handling
|
||||
strcpy(reply, "**Magic now done**");
|
||||
return true; // handled
|
||||
@@ -57,6 +57,7 @@ void setup() {
|
||||
delay(1000);
|
||||
|
||||
board.begin();
|
||||
maint.printBootDiag();
|
||||
|
||||
#ifdef HAS_EXTERNAL_WATCHDOG
|
||||
external_watchdog.begin();
|
||||
@@ -109,9 +110,10 @@ void setup() {
|
||||
sensors.begin();
|
||||
|
||||
the_mesh.begin(fs);
|
||||
maint.begin(fs, the_mesh.getNodePrefs(), &the_mesh);
|
||||
|
||||
#ifdef DISPLAY_CLASS
|
||||
ui_task.begin(the_mesh.getNodePrefs(), FIRMWARE_BUILD_DATE, FIRMWARE_VERSION);
|
||||
ui_task.begin(the_mesh.getNodePrefs(), FIRMWARE_BUILD_DATE, FIRMWARE_VERSION, "< Sensor >");
|
||||
#endif
|
||||
|
||||
// send out initial zero hop Advertisement to the mesh
|
||||
@@ -122,6 +124,13 @@ void setup() {
|
||||
|
||||
void loop() {
|
||||
int len = strlen(command);
|
||||
// `command` must stay NUL-terminated within its bounds. If it ever isn't,
|
||||
// strlen() above can return >= sizeof(command) and the loop below would then
|
||||
// index past the buffer, so clamp defensively.
|
||||
if (len >= (int)sizeof(command)) {
|
||||
command[0] = 0;
|
||||
len = 0;
|
||||
}
|
||||
while (Serial.available() && len < sizeof(command)-1) {
|
||||
char c = Serial.read();
|
||||
if (c != '\n') {
|
||||
@@ -130,14 +139,15 @@ void loop() {
|
||||
}
|
||||
Serial.print(c);
|
||||
}
|
||||
if (len == sizeof(command)-1) { // command buffer full
|
||||
command[sizeof(command)-1] = '\r';
|
||||
if (len == sizeof(command)-1) { // buffer full: treat as a completed line
|
||||
command[sizeof(command)-2] = '\r'; // place end-of-line marker inside the buffer
|
||||
command[sizeof(command)-1] = 0; // keep the buffer NUL-terminated
|
||||
}
|
||||
|
||||
if (len > 0 && command[len - 1] == '\r') { // received complete line
|
||||
command[len - 1] = 0; // replace newline with C string null terminator
|
||||
char reply[160];
|
||||
the_mesh.handleCommand(0, command, reply); // NOTE: there is no sender_timestamp via serial!
|
||||
the_mesh.handleCommand(NULL, 0, command, reply); // NOTE: there is no sender_timestamp via serial!
|
||||
if (reply[0]) {
|
||||
Serial.print(" -> "); Serial.println(reply);
|
||||
}
|
||||
@@ -145,7 +155,10 @@ void loop() {
|
||||
command[0] = 0; // reset command buffer
|
||||
}
|
||||
|
||||
board.loop(); // let the board feed its watchdog, run periodic housekeeping
|
||||
|
||||
the_mesh.loop();
|
||||
maint.loop();
|
||||
sensors.loop();
|
||||
#ifdef DISPLAY_CLASS
|
||||
ui_task.loop();
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
stl/
|
||||
@@ -0,0 +1,256 @@
|
||||
// Krabička na dutinový filtr 868 MHz (hamparts; 130 x 58 x 40 mm i s konektory, 380 g, SMA female)
|
||||
// na stožár. Při pohledu zepředu je profil lichoběžník (dno užší než strop),
|
||||
// takže boční stěny jsou zkosené a dívají se dolů. Vývody vedou kolmo na ně,
|
||||
// tedy šikmo dolů, a kabel pod krabičkou udělá odkapovou smyčku sám.
|
||||
// Víko je vpředu na svislé ploše, s těsněním v drážce a šrouby vně těsnění.
|
||||
// Kabel ven průchodkou PG11 (projde jí SMA konektor, viz gland_hole). Tisk: MK4S, PETG.
|
||||
// Těsnění víka: silikon vytvrzený v drážce (TPU díl `gasket` je jen volitelný).
|
||||
//
|
||||
// Montáž třemi stahovacími pásky (UV černé nebo nerez, do 9 mm) na svislou tyč
|
||||
// libovolného průřezu. Tunely jsou zapuštěné v zádech, záda zůstávají rovná a celá.
|
||||
// Dno je trychtýř do odtokové dírky, takže kondenzát vyteče.
|
||||
//
|
||||
// Tisk bez supportu ZÁDY DOLŮ: sloupky rostou z podložky, pod přírubou je náběh 45°,
|
||||
// vstupy tunelů šikmo 45°. Díry pro vývodky jsou kulaté (12,6 mm vodorovně
|
||||
// většinou projde i bez supportu, jinak tree support jen tam); `gland_teardrop` = slza.
|
||||
// Šrouby: víko 14x M3x8 DIN 912 A2 do zatavených vložek M3x5x5, filtr 4x M3x10
|
||||
// s podložkou (uši filtru 4,1 mm) do stejných vložek ve sloupcích.
|
||||
//
|
||||
// Osy: X = šířka, Z = nahoru, Y = hloubka (čelo/víko v y=0, záda na stožár v y=-depth).
|
||||
// Díly: part = "body" | "lid" | "gasket" | "assembly" | "open"
|
||||
//
|
||||
// Rozměry filtru jsou z fotek s metrem a z obkreslení podstavy (17. 10. 2026), ne
|
||||
// posuvkou: tělo ~104 x 58 (výška 45 i se šrouby a rezervou), SMA na obou čelech, mimo střed (~37 mm od jedné dlouhé
|
||||
// hrany), 4 díry 4 mm v rozích 95 x 51 (změřeno), osa SMA 18 mm nad podstavou. Filtr je symetrický, IN/OUT je jedno;
|
||||
// montuje se konektory k horní hraně.
|
||||
|
||||
part = "assembly";
|
||||
|
||||
/* [Filtr] */
|
||||
filter_len = 104; // tělo vodorovně, bez konektorů
|
||||
filter_h = 58; // svisle
|
||||
filter_d = 45; // do hloubky vč. šroubů a rezervy
|
||||
sma_len = 11; // jak daleko SMA trčí z čela
|
||||
sma_z = 37; // osa SMA nad spodní hranou filtru (konektory nahoru)
|
||||
sma_y = 18; // osa SMA od podstavy filtru
|
||||
plug_clear = 22; // za koncem SMA: úhlový konektor kabelu
|
||||
floor_clear = 10; // pod filtrem a nad ním
|
||||
front_clear = 8; // mezi filtrem a víkem
|
||||
standoff = 6; // sloupky pod filtrem
|
||||
mount_dx = 95; // rozteč děr v rozích filtru, podélně
|
||||
mount_dz = 51; // a napříč
|
||||
post_d = 10; // sloupek kolem vložky
|
||||
|
||||
/* [Tvar] */
|
||||
slant = 15; // sklon bočnic od svislice [°]
|
||||
wall = 3;
|
||||
flange = 12; // šířka příruby kolem otvoru (nese drážku i šrouby); 12 = ~238 mm, na MK4 ještě s brimem
|
||||
flange_t = 5; // tloušťka příruby; slepá díra pro vložku pokračuje do náběhu pod ní
|
||||
corner_r = 5; // poloměr vnitřních rohů; ven roste s offsetem (stěna 8, příruba 20),
|
||||
// kulaté rohy se méně odlupují od podložky a náběh má i v rohu 45°
|
||||
|
||||
/* [Těsnění] */
|
||||
groove_off = 1.5; // od vnitřní hrany příruby
|
||||
groove_w = 2.5;
|
||||
groove_d = 2.0;
|
||||
gasket_h = 2.6; // ~30 % komprese
|
||||
gasket_clr = 0.25; // vůle na každé straně drážky
|
||||
|
||||
/* [Šrouby M3 a zatavené vložky M3x5x5] */
|
||||
insert_hole = 4.3; // pro vložku o vnějším průměru 5 mm
|
||||
insert_depth = 5.6; // vložka 5 mm + místo na vytlačený plast
|
||||
screw_hole = 3.4; // průchozí díra ve víku
|
||||
screw_off = 7.5; // osa šroubů od vnitřní hrany příruby; vložka musí minout drážku
|
||||
|
||||
/* [Vývody] */
|
||||
gland_hole = 18.6; // PG11 (závit 18,4 mm): SMA ~9,2 mm přes rohy
|
||||
// projde s vyjmutou a podélně naříznutou vložkou; PG7 = 12.5, ale konektor neprojde
|
||||
gland_dz = 0; // posun díry proti ose SMA (0 = v ose konektoru)
|
||||
gland_teardrop = false; // true = slza bez supportu; kulatá díra líp sedí na závit vývodky
|
||||
drain_hole = 4; // odtok kondenzátu v nejnižším bodě dna; 0 = bez
|
||||
floor_slope = 4; // dno se ze všech stran svažuje k odtoku [°]
|
||||
|
||||
/* [Uchycení: stahovací pásky v zapuštěných tunelech] */
|
||||
tie_w = 10; // šířka tunelu (pásek do 9 mm)
|
||||
tie_gap = 2.5; // výška tunelu
|
||||
tie_zs = [0.15, 0.5, 0.85]; // výšky tunelů jako podíl výšky krabice
|
||||
tie_l = 60; // délka tunelu mezi vstupy (tyč do ~60 mm)
|
||||
tie_skin = 3; // pod tunelem (strana k tyči)
|
||||
tie_root = 2.5; // nad tunelem (strana do krabice) – nese tah pásku
|
||||
|
||||
lid_t = 3;
|
||||
$fn = 48;
|
||||
|
||||
// ---- odvozené rozměry (vnitřek) ----
|
||||
tn = tan(slant);
|
||||
in_h = filter_h + 2 * floor_clear;
|
||||
need_w = filter_len + 2 * (sma_len + plug_clear); // potřeba v úrovni spodní hrany filtru
|
||||
in_wb = need_w - 2 * floor_clear * tn; // vnitřní šířka u dna
|
||||
in_wt = in_wb + 2 * in_h * tn; // vnitřní šířka u stropu
|
||||
in_d = standoff + filter_d + front_clear;
|
||||
back_t = tie_skin + tie_gap + tie_root; // záda s tunely
|
||||
depth = in_d + back_t;
|
||||
in_y0 = -depth + back_t; // vnitřní plocha zad
|
||||
filter_zc = floor_clear + filter_h / 2; // střed filtru (vnitřní z, dno = 0)
|
||||
|
||||
echo(str("vnitřek: dno ", in_wb, " / strop ", in_wt, " x výška ", in_h, " x hloubka ", in_d));
|
||||
echo(str("obrys příruby: ", 2 * (corner_pt(2, -corner_r)[0] + corner_r + wall + flange), " x ", in_h + 2 * (wall + flange)));
|
||||
echo(str("šrouby: vložka od drážky ", screw_off - groove_off - groove_w - insert_hole / 2,
|
||||
", od okraje ", flange - screw_off - insert_hole / 2));
|
||||
|
||||
// Lichoběžník vnitřku posunutý o d ven (rovnoběžně se stěnami), dno vnitřku v z = 0.
|
||||
function trap_pts(d) = let(
|
||||
xb = in_wb / 2 - d * tn + d / cos(slant),
|
||||
xt = in_wb / 2 + (in_h + d) * tn + d / cos(slant))
|
||||
[[-xb, -d], [xb, -d], [xt, in_h + d], [-xt, in_h + d]];
|
||||
|
||||
module trap(d) { polygon(trap_pts(d)); }
|
||||
// Vnitřek se zaoblenými rohy a jeho rovnoběžné offsety: stěna, drážka i příruba mají
|
||||
// všude stejnou šířku a rohy se zaoblují s offsetem (ostrý offset dával v rohu převis ~56°).
|
||||
module outline(d) { offset(r = corner_r + d) offset(delta = -corner_r) trap(0); }
|
||||
|
||||
// vrchol zaobleného rohu `outline(d)` u rohu i lichoběžníku
|
||||
function unit(v) = v / norm(v);
|
||||
function corner_pt(i, d) = let(
|
||||
P = trap_pts(0), p = P[i],
|
||||
u = unit(P[(i + 3) % 4] - p), v = unit(P[(i + 1) % 4] - p),
|
||||
half = acos(u * v) / 2)
|
||||
p + unit(u + v) * (corner_r / sin(half) - corner_r - d);
|
||||
|
||||
// 2D v rovině XZ vytažené v hloubce od y0 do y1
|
||||
module xz(y0, y1) {
|
||||
translate([0, y1, 0]) rotate([90, 0, 0]) linear_extrude(y1 - y0) children();
|
||||
}
|
||||
|
||||
// šrouby v ose příruby: rohy + středy delších hran
|
||||
function screw_pts() = let(
|
||||
d = wall + screw_off,
|
||||
p = trap_pts(d),
|
||||
mid = function(a, b) (a + b) / 2)
|
||||
concat([for (i = [0:3]) corner_pt(i, d)], [mid(p[0], p[1]), mid(p[2], p[3]),
|
||||
mid(p[0], mid(p[0], p[1])), mid(p[1], mid(p[0], p[1])),
|
||||
mid(p[2], mid(p[2], p[3])), mid(p[3], mid(p[2], p[3])),
|
||||
mid(p[1], p[2]), mid(p[3], p[0])]);
|
||||
|
||||
module groove2d(clr = 0) {
|
||||
difference() {
|
||||
outline(wall + groove_off + groove_w - clr);
|
||||
outline(wall + groove_off + clr);
|
||||
}
|
||||
}
|
||||
|
||||
sma_abs_z = floor_clear + sma_z; // osa SMA ve vnitřních z
|
||||
|
||||
module mount_post() {
|
||||
// sloupek na zadní stěně; díra jen do sloupku, ne skrz stěnu
|
||||
difference() {
|
||||
rotate([-90, 0, 0]) cylinder(d = post_d, h = standoff);
|
||||
translate([0, standoff - insert_depth, 0]) rotate([-90, 0, 0])
|
||||
cylinder(d = insert_hole, h = insert_depth + 0.01);
|
||||
}
|
||||
}
|
||||
|
||||
module gland_cut(side) {
|
||||
// kolmo na zkosenou bočnici => osa míří ven a dolů
|
||||
z = sma_abs_z + gland_dz;
|
||||
x = side * (in_wb / 2 + z * tn);
|
||||
translate([x, in_y0 + standoff + sma_y, z])
|
||||
rotate([0, side * (90 + slant), 0])
|
||||
if (gland_teardrop) teardrop(gland_hole, 4 * wall);
|
||||
else cylinder(d = gland_hole, h = 4 * wall, center = true);
|
||||
}
|
||||
|
||||
// válec s převisem 45° ve špičce: osa podle z, špička míří k +y (při tisku nahoru)
|
||||
module teardrop(d, h) {
|
||||
linear_extrude(h, center = true)
|
||||
hull() { circle(d = d); rotate(45) square(d / 2); }
|
||||
}
|
||||
|
||||
// ---- dno jako trychtýř k odtoku ----
|
||||
drain_y = in_y0 + in_d / 2;
|
||||
funnel_h = 8;
|
||||
|
||||
module floor_funnel() {
|
||||
difference() {
|
||||
intersection() {
|
||||
xz(in_y0, 0) outline(0);
|
||||
translate([-in_wt, -depth, 0]) cube([2 * in_wt, depth, funnel_h]);
|
||||
}
|
||||
translate([0, drain_y, 0])
|
||||
linear_extrude(height = funnel_h + 0.01, scale = 2 * funnel_h / tan(floor_slope) / 0.2)
|
||||
square(0.2, center = true);
|
||||
if (drain_hole > 0)
|
||||
translate([0, drain_y, -1]) cylinder(d = drain_hole, h = funnel_h + 2);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- tunely pro stahovací pásky ----
|
||||
// Vedou vodorovně uvnitř zad, na zadní plochu vyúsťují šikmo pod 45°, takže
|
||||
// pásek do tunelu sám zajede a vyjede druhým vstupem. Interiér neprotínají.
|
||||
module tie_cut() {
|
||||
y0 = -depth + tie_skin;
|
||||
translate([-tie_l / 2, y0, -tie_w / 2]) cube([tie_l, tie_gap, tie_w]);
|
||||
for (s = [-1, 1]) hull() {
|
||||
translate([s * tie_l / 2 - 0.01, y0, -tie_w / 2]) cube([0.02, tie_gap, tie_w]);
|
||||
translate([s * (tie_l / 2 + tie_skin) + (s > 0 ? 0 : -tie_gap), -depth - 1, -tie_w / 2])
|
||||
cube([tie_gap, 1.01, tie_w]);
|
||||
}
|
||||
}
|
||||
|
||||
module body() {
|
||||
difference() {
|
||||
union() {
|
||||
xz(-depth, 0) outline(wall);
|
||||
xz(-flange_t, 0) outline(wall + flange);
|
||||
// náběh 45° pod přírubou, aby se dala tisknout zády dolů bez supportu
|
||||
hull() {
|
||||
xz(-flange_t - flange, -flange_t - flange + 0.01) outline(wall);
|
||||
xz(-flange_t - 0.01, -flange_t) outline(wall + flange);
|
||||
}
|
||||
}
|
||||
xz(in_y0, 1) outline(0);
|
||||
// drážka pro těsnění
|
||||
translate([0, 0.01, 0]) xz(-groove_d, 0) groove2d();
|
||||
// šrouby
|
||||
for (p = screw_pts())
|
||||
translate([p[0], 0.01, p[1]]) rotate([90, 0, 0]) cylinder(d = insert_hole, h = insert_depth);
|
||||
for (s = [-1, 1]) gland_cut(s);
|
||||
if (drain_hole > 0)
|
||||
translate([0, drain_y, -wall - 1]) cylinder(d = drain_hole, h = wall + 2);
|
||||
for (f = tie_zs) translate([0, 0, f * in_h]) tie_cut();
|
||||
}
|
||||
floor_funnel();
|
||||
for (x = [-1, 1], z = [-1, 1])
|
||||
translate([x * mount_dx / 2, in_y0, filter_zc + z * mount_dz / 2]) mount_post();
|
||||
}
|
||||
|
||||
module lid() {
|
||||
difference() {
|
||||
xz(0, lid_t) outline(wall + flange);
|
||||
for (p = screw_pts())
|
||||
translate([p[0], lid_t + 1, p[1]]) rotate([90, 0, 0]) cylinder(d = screw_hole, h = lid_t + 2);
|
||||
}
|
||||
}
|
||||
|
||||
module gasket() { xz(-groove_d, -groove_d + gasket_h) groove2d(gasket_clr); }
|
||||
|
||||
module filter_dummy() {
|
||||
color("silver")
|
||||
translate([-filter_len / 2, in_y0 + standoff, floor_clear])
|
||||
cube([filter_len, filter_d, filter_h]);
|
||||
color("gold")
|
||||
for (s = [-1, 1])
|
||||
translate([s * filter_len / 2, in_y0 + standoff + sma_y, sma_abs_z])
|
||||
rotate([0, s * 90, 0]) cylinder(d = 6.4, h = sma_len);
|
||||
}
|
||||
|
||||
// tisk: tělo zády dolů, víko těsnicí plochou dolů, těsnění z TPU naplocho
|
||||
if (part == "body") translate([0, 0, depth]) rotate([90, 0, 0]) body();
|
||||
else if (part == "lid") rotate([90, 0, 0]) lid();
|
||||
else if (part == "gasket") rotate([-90, 0, 0]) translate([0, groove_d, 0]) gasket();
|
||||
else {
|
||||
color("orange", 0.85) body();
|
||||
color("black") gasket();
|
||||
filter_dummy();
|
||||
if (part == "assembly") color("lightblue", 0.35) translate([0, 25, 0]) lid();
|
||||
}
|
||||
+115
-8
@@ -13,14 +13,46 @@ extra_configs =
|
||||
variants/*/platformio.ini
|
||||
platformio.local.ini
|
||||
|
||||
; Default BLE pairing PIN. This is a non-secret placeholder; override it with
|
||||
; your real PIN in the git-ignored platformio.local.ini ([secrets] ble_pin=...)
|
||||
; so the real value never lands in the committed tree.
|
||||
; admin_pw: same idea for the mast envs in variants/tth_fleet (ADMIN_PASSWORD).
|
||||
; PlatformIO resolves ${secrets.*} of EVERY env when it loads the config, so a
|
||||
; checkout without platformio.local.ini (tth-upstream-sync CI) fails on the
|
||||
; missing key even when it never builds a mast env. tth-fw-release writes the
|
||||
; real values over it.
|
||||
[secrets]
|
||||
ble_pin = 123456
|
||||
admin_pw = password
|
||||
|
||||
; Admin-pushed OTA (src/helpers/FwUpdate, docs/ota.md): the PUBLIC key
|
||||
; every OTA package signature is checked against, raw Ed25519 hex. Default: the
|
||||
; public OTA key meshcore-ota@tth-pub, the one the -ota release images are
|
||||
; signed with (tools/ota_allowed_signers has it as an ssh key, for the release
|
||||
; checksums). Only images built with -D FW_OTA=1 use it. A self-built image
|
||||
; signed with your own key: [ota] pubkey = <tools/ota_pack.py pubkey --key ...>
|
||||
; in platformio.local.ini.
|
||||
[ota]
|
||||
pubkey = 8777b6e1a8494113b70f41f5ed75bf3f2a8eba9635bab1dc3d20efd1a8398090
|
||||
|
||||
; CUSTOM (TeTeHacko): channels the ChannelFilter deny list applies to
|
||||
; (examples/simple_repeater/ChannelFilter.h). These keys are PUBLIC by
|
||||
; construction, not secrets: hashtag channels derive key = SHA256(name)[:16]
|
||||
; (anyone joins #meshcore by typing the name), and the Public channel key is
|
||||
; the globally published izOH6cXN6mrJ5e26oRXNcg==. Derivation verified live
|
||||
; 5. 9. 2026: SHA256("#meshcore")[:16] hashes to channel byte 0xEF, matching
|
||||
; the on-air packets. Order: #meshcore, Public, #test.
|
||||
[channel_filter]
|
||||
build_flags =
|
||||
-D FILTER_CHANNEL_PSKS='"2fa78a5aef618e7c2a78f0ab5c8869b3,8b3387e9c5cdea6ac9e5edbaa115cd72,9cd8fcf22a47333b591d96a2b848b73f"'
|
||||
|
||||
[arduino_base]
|
||||
framework = arduino
|
||||
monitor_speed = 115200
|
||||
lib_deps =
|
||||
SPI
|
||||
Wire
|
||||
;jgromes/RadioLib @ ^7.7.1
|
||||
https://github.com/jgromes/RadioLib.git#6d8934836678d8894e3d556550475b37dce3e2b6
|
||||
jgromes/RadioLib @ 7.8.1
|
||||
rweather/Crypto @ ^0.4.0
|
||||
adafruit/RTClib @ ^2.1.3
|
||||
melopero/Melopero RV3028 @ ^1.1.0
|
||||
@@ -78,19 +110,37 @@ platform = https://github.com/pioarduino/platform-espressif32/releases/download/
|
||||
|
||||
; ----------------- NRF52 ---------------------
|
||||
|
||||
; nRF52 Adafruit framework package. Committed DEFAULT is a fetchable git pin
|
||||
; (works on CI and on any clone). d541301 is the tip of meshcore-dev's fork
|
||||
; master and carries the BLE-stack patch against rapid connect/disconnect
|
||||
; lockup (MeshCore PRs #1177, #1295). The full 40-char SHA is used on purpose:
|
||||
; PlatformIO's shallow fetch choked on the SHORT SHA, which is the whole reason
|
||||
; the local build used a full clone + symlink. That symlink hack now lives ONLY
|
||||
; in the gitignored platformio.local.ini (it redefines [nrf52_fw].pkg), so it
|
||||
; never leaks into the tracked tree and breaks CI again -- it did: a committed
|
||||
; `symlink:///home/user/...` gave PackageException on every nRF52 runner build.
|
||||
[nrf52_fw]
|
||||
pkg = https://github.com/meshcore-dev/Adafruit_nRF52_Arduino#d541301665b40959682252911e57b11df3ee651a
|
||||
|
||||
[nrf52_base]
|
||||
extends = arduino_base
|
||||
platform = nordicnrf52
|
||||
platform_packages =
|
||||
; use internal fork that includes patch to ble stack to prevent firmware lockup during rapid connect/disconnect
|
||||
; https://github.com/meshcore-dev/MeshCore/pull/1177
|
||||
; https://github.com/meshcore-dev/MeshCore/pull/1295
|
||||
framework-arduinoadafruitnrf52 @ https://github.com/meshcore-dev/Adafruit_nRF52_Arduino#d541301
|
||||
framework-arduinoadafruitnrf52 @ ${nrf52_fw.pkg}
|
||||
platformio/toolchain-gccarmnoneeabi@^1.140201.0
|
||||
; Stamping verze pro KAŽDÝ nRF52 env, ne po jednom: 19. 8. 2026 se ukázalo, že
|
||||
; z 585 envů v repu stampovaly DVA, takže `ver` na lavičních deskách hlásil
|
||||
; literál z upstream headeru a z uzlu nešlo poznat, který build na něm je.
|
||||
; U flashované desky je to podmínka, ne komfort (AGENTS.md).
|
||||
extra_scripts = create-uf2.py
|
||||
pre:tools/build_version.py
|
||||
; FwPatch.cpp (delta OTA applier) runs from RAM, see the script's header.
|
||||
pre:tools/ota_ramlib.py
|
||||
build_flags = ${arduino_base.build_flags}
|
||||
-D NRF52_PLATFORM
|
||||
-D LFS_NO_ASSERT=1
|
||||
-D EXTRAFS=1
|
||||
-D FW_OTA_PUBKEY='"${ota.pubkey}"'
|
||||
-D USE_CC310_HW_CRYPTO=1
|
||||
lib_deps =
|
||||
${arduino_base.lib_deps}
|
||||
@@ -101,7 +151,8 @@ lib_deps =
|
||||
extends = arduino_base
|
||||
upload_protocol = picotool
|
||||
board_build.core = earlephilhower
|
||||
platform = https://github.com/maxgerhardt/platform-raspberrypi.git ; framework-arduinopico @ 1.50600.0+sha.6a1d13e9
|
||||
; commit points to framework-arduinopico 5.6.0
|
||||
platform = https://github.com/maxgerhardt/platform-raspberrypi.git#4e22a0dcdd94eead72fdf56ea59a3d7c8aa2f379
|
||||
build_flags = ${arduino_base.build_flags}
|
||||
-D RP2040_PLATFORM
|
||||
|
||||
@@ -109,7 +160,9 @@ build_flags = ${arduino_base.build_flags}
|
||||
|
||||
[stm32_base]
|
||||
extends = arduino_base
|
||||
platform = ststm32
|
||||
; Pinned pending upstream fix for upstream conversions.
|
||||
; https://github.com/jgromes/RadioLib/issues/1873
|
||||
platform = ststm32@19.7.1
|
||||
extra_scripts = post:arch/stm32/build_hex.py
|
||||
build_flags = ${arduino_base.build_flags}
|
||||
-D STM32_PLATFORM
|
||||
@@ -167,15 +220,69 @@ test_build_src = yes
|
||||
test_ignore = test_kiss_modem
|
||||
build_src_filter =
|
||||
-<*>
|
||||
+<../src/helpers/FwPatch.cpp>
|
||||
+<../src/Utils.cpp>
|
||||
+<../src/Packet.cpp>
|
||||
+<../src/helpers/ConfigSerializer.cpp>
|
||||
+<../src/helpers/DynamicConfigSerializer.cpp>
|
||||
+<../src/helpers/FairnessLimiter.cpp>
|
||||
lib_deps =
|
||||
google/googletest @ 1.17.0
|
||||
|
||||
; Stejné jako [env:native], ale pod AddressSanitizerem. Bounds fixy v parsování
|
||||
; paketů nemění návratovou hodnotu -- odmítnou přesně to, co upstream odmítne až
|
||||
; po přečtení -- takže rozdíl je vidět jenom tady. Testy krmí parser bufferem
|
||||
; alokovaným na přesnou délku rámce, aby bylo čtení za jeho konec skutečná chyba.
|
||||
[env:native_asan]
|
||||
platform = native
|
||||
test_framework = googletest
|
||||
build_flags = -std=c++17
|
||||
-I src
|
||||
-I test/mocks
|
||||
-fsanitize=address,undefined
|
||||
# Bez -fno-sanitize-recover UBSan nalez jen VYPISE a test dobehne uspesne --
|
||||
# takze z te poloviny sanitizeru byla jen ozdoba. ASAN abortuje sam.
|
||||
-fno-sanitize-recover=all
|
||||
# POZOR na diagnostiku: `pio test` u padu sanitizeru vypise jen
|
||||
# "Program received signal SIGHUP" a ASAN report SPOLKNE. Necti z toho, ze
|
||||
# sanitizer nic nenasel -- spust binarku primo:
|
||||
# pio run -e native_asan -t buildprog && .pio/build/native_asan/program
|
||||
# Overeno 2. 9. 2026: pres `pio test` jen SIGHUP, primo pak
|
||||
# "heap-buffer-overflow ... src/Packet.cpp:93 in mesh::Packet::readFrom".
|
||||
-fno-omit-frame-pointer
|
||||
-g -O1
|
||||
build_unflags = -O2
|
||||
test_build_src = yes
|
||||
; test_empty_contact_slots (upstream 20. 10. 2026) jako prvni test vola ed25519
|
||||
; na hostu a UBSan zastavi na `lib/ed25519/fe.c:714: left shift of negative
|
||||
; value` -- idiom referencni implementace ref10, ne nalez v nasem kodu. GCC
|
||||
; nema per-file ignorelist, takze ten test bezi jen v [env:native].
|
||||
test_ignore =
|
||||
test_kiss_modem
|
||||
test_empty_contact_slots
|
||||
; POZOR: musi zustat v zakrytu s [env:native]. Merge upstreamu 2. 9. 2026 pridal
|
||||
; DynamicConfigSerializer.cpp jen tam a tenhle env pak padal na undefined
|
||||
; reference -- coz vypada jako nalez ASANu, a je to jen chybejici prekladova
|
||||
; jednotka.
|
||||
build_src_filter =
|
||||
-<*>
|
||||
+<../src/helpers/FwPatch.cpp>
|
||||
+<../src/Utils.cpp>
|
||||
+<../src/Packet.cpp>
|
||||
+<../src/helpers/ConfigSerializer.cpp>
|
||||
+<../src/helpers/DynamicConfigSerializer.cpp>
|
||||
+<../src/helpers/FairnessLimiter.cpp>
|
||||
lib_deps =
|
||||
google/googletest @ 1.17.0
|
||||
|
||||
[env:native_kiss_modem]
|
||||
platform = native
|
||||
test_framework = googletest
|
||||
; Stampovani i tady: `KissModem::handleGetDeviceName()` pripojuje k vyrobci
|
||||
; FIRMWARE_VERSION, jinak je deska s KISS buildem verzne neidentifikovatelna.
|
||||
; Bez tohohle skriptu se ten symbol na hostu nedefinuje a test env se od
|
||||
; 1. 9. 2026 ani neprelozil ("FIRMWARE_VERSION was not declared").
|
||||
extra_scripts = pre:tools/build_version.py
|
||||
build_flags = -std=c++17
|
||||
-I test/mocks
|
||||
-I src
|
||||
|
||||
+29
-5
@@ -19,6 +19,7 @@ namespace mesh {
|
||||
void Dispatcher::begin() {
|
||||
n_sent_flood = n_sent_direct = 0;
|
||||
n_recv_flood = n_recv_direct = 0;
|
||||
n_tx_start_fail = n_tx_timeout = 0;
|
||||
_err_flags = 0;
|
||||
radio_nonrx_start = _ms->getMillis();
|
||||
|
||||
@@ -118,9 +119,20 @@ void Dispatcher::loop() {
|
||||
MESH_DEBUG_PRINTLN("%s Dispatcher::loop(): WARNING: outbound packed send timed out!", getLogDateTime());
|
||||
|
||||
_radio->onSendFinished();
|
||||
logTxFail(outbound, 2 + outbound->getPathByteLen() + outbound->payload_len);
|
||||
|
||||
releasePacket(outbound); // return to pool
|
||||
// CUSTOM (TeTeHacko): the send-complete IRQ never arrived (SoftDevice/BLE
|
||||
// preemption can wedge the LoRa driver mid-TX). Requeue with a short
|
||||
// backoff instead of dropping -- a duplicate on air is harmless (hasSeen
|
||||
// dedup), a dropped direct forward is a black hole.
|
||||
n_tx_timeout++;
|
||||
_err_flags |= ERR_EVENT_TX_TIMEOUT;
|
||||
if (outbound->_tx_attempts < MESH_TX_RETRIES) {
|
||||
outbound->_tx_attempts++;
|
||||
_mgr->queueOutbound(outbound, 0, futureMillis(40 + 80 * outbound->_tx_attempts));
|
||||
} else {
|
||||
logTxFail(outbound, 2 + outbound->getPathByteLen() + outbound->payload_len);
|
||||
releasePacket(outbound); // return to pool
|
||||
}
|
||||
outbound = NULL;
|
||||
} else {
|
||||
return; // can't do any more radio activity until send is complete or timed out
|
||||
@@ -204,6 +216,8 @@ void Dispatcher::checkRecv() {
|
||||
} else {
|
||||
if (tryParsePacket(pkt, raw, len)) {
|
||||
pkt->_snr = _radio->getLastSNR() * 4.0f;
|
||||
pkt->_rssi = (int8_t)_radio->getLastRSSI();
|
||||
pkt->_tx_attempts = 0;
|
||||
score = _radio->packetScore(_radio->getLastSNR(), len);
|
||||
air_time = _radio->getEstAirtimeFor(len);
|
||||
rx_air_time += air_time;
|
||||
@@ -330,9 +344,18 @@ void Dispatcher::checkSend() {
|
||||
if (!success) {
|
||||
MESH_DEBUG_PRINTLN("%s Dispatcher::loop(): ERROR: send start failed!", getLogDateTime());
|
||||
|
||||
logTxFail(outbound, outbound->getRawLength());
|
||||
|
||||
releasePacket(outbound); // return to pool
|
||||
// CUSTOM (TeTeHacko): startTransmit() failing is usually transient
|
||||
// (SPI/BUSY hiccup while the SoftDevice services a BLE connection
|
||||
// event). Requeue with a short backoff instead of dropping.
|
||||
n_tx_start_fail++;
|
||||
_err_flags |= ERR_EVENT_TX_START_FAIL;
|
||||
if (outbound->_tx_attempts < MESH_TX_RETRIES) {
|
||||
outbound->_tx_attempts++;
|
||||
_mgr->queueOutbound(outbound, 0, futureMillis(40 + 80 * outbound->_tx_attempts));
|
||||
} else {
|
||||
logTxFail(outbound, outbound->getRawLength());
|
||||
releasePacket(outbound); // return to pool
|
||||
}
|
||||
outbound = NULL;
|
||||
return;
|
||||
}
|
||||
@@ -360,6 +383,7 @@ Packet* Dispatcher::obtainNewPacket() {
|
||||
} else {
|
||||
pkt->payload_len = pkt->path_len = 0;
|
||||
pkt->_snr = 0;
|
||||
pkt->_tx_attempts = 0;
|
||||
}
|
||||
return pkt;
|
||||
}
|
||||
|
||||
@@ -110,6 +110,17 @@ typedef uint32_t DispatcherAction;
|
||||
#define ERR_EVENT_FULL (1 << 0)
|
||||
#define ERR_EVENT_CAD_TIMEOUT (1 << 1)
|
||||
#define ERR_EVENT_STARTRX_TIMEOUT (1 << 2)
|
||||
#define ERR_EVENT_TX_START_FAIL (1 << 3) // CUSTOM (TeTeHacko): startSendRaw() returned error (radio busy/SPI hiccup)
|
||||
#define ERR_EVENT_TX_TIMEOUT (1 << 4) // CUSTOM (TeTeHacko): send-complete IRQ never came before outbound_expiry
|
||||
|
||||
// CUSTOM (TeTeHacko): how many times a failed TX (start fail or send timeout) is
|
||||
// requeued before the packet is finally dropped. Transient failures are common
|
||||
// when the nRF52 SoftDevice (BLE connection events) preempts the LoRa driver —
|
||||
// measured ~40 % direct-forward loss with an idle BLE connection. A short retry
|
||||
// converts those losses into ~100-300 ms of extra latency.
|
||||
#ifndef MESH_TX_RETRIES
|
||||
#define MESH_TX_RETRIES 3
|
||||
#endif
|
||||
|
||||
/**
|
||||
* \brief The low-level task that manages detecting incoming Packets, and the queueing
|
||||
@@ -125,6 +136,7 @@ class Dispatcher {
|
||||
bool prev_isrecv_mode;
|
||||
uint32_t n_sent_flood, n_sent_direct;
|
||||
uint32_t n_recv_flood, n_recv_direct;
|
||||
uint32_t n_tx_start_fail, n_tx_timeout; // CUSTOM (TeTeHacko): TX failure tallies (see MESH_TX_RETRIES)
|
||||
unsigned long tx_budget_ms;
|
||||
unsigned long last_budget_update;
|
||||
unsigned long duty_cycle_window_ms;
|
||||
@@ -187,6 +199,8 @@ public:
|
||||
uint32_t getNumSentDirect() const { return n_sent_direct; }
|
||||
uint32_t getNumRecvFlood() const { return n_recv_flood; }
|
||||
uint32_t getNumRecvDirect() const { return n_recv_direct; }
|
||||
uint32_t getNumTxStartFail() const { return n_tx_start_fail; } // CUSTOM (TeTeHacko)
|
||||
uint32_t getNumTxTimeout() const { return n_tx_timeout; } // CUSTOM (TeTeHacko)
|
||||
void resetStats() {
|
||||
n_sent_flood = n_sent_direct = n_recv_flood = n_recv_direct = 0;
|
||||
_err_flags = 0;
|
||||
|
||||
@@ -7,6 +7,10 @@
|
||||
#ifdef USE_CC310_HW_CRYPTO
|
||||
#include <Adafruit_nRFCrypto.h>
|
||||
#include "nrf_cc310/include/crys_ec_edw_api.h"
|
||||
#include "nrf_cc310/include/ssi_pal_mutex.h"
|
||||
extern "C" {
|
||||
extern SaSi_PalMutex sasiAsymCryptoMutex;
|
||||
}
|
||||
#endif
|
||||
|
||||
namespace mesh {
|
||||
@@ -30,6 +34,13 @@ bool Identity::verify(const uint8_t* sig, const uint8_t* message, int msg_len) c
|
||||
CRYSError_t rc = CRYS_ECEDW_Verify((uint8_t*)sig, CRYS_ECEDW_SIGNATURE_BYTES,
|
||||
(uint8_t*)pub_key, CRYS_ECEDW_MOD_SIZE_IN_BYTES,
|
||||
(uint8_t*)message, (size_t)msg_len, &cc310_tmp);
|
||||
|
||||
// workaround for CC310 v0.9.13 where mutex can still be locked after a failed verification
|
||||
if (rc != CRYS_OK && sasiAsymCryptoMutex != 0) {
|
||||
MESH_DEBUG_PRINTLN("CRYS_ECEDW_Verify mutex still locked after error result, unlocking");
|
||||
SaSi_PalMutexUnlock(&sasiAsymCryptoMutex);
|
||||
}
|
||||
|
||||
return rc == CRYS_OK;
|
||||
#elif 0
|
||||
// NOTE: memory corruption bug was found in this function!!
|
||||
|
||||
+80
-25
@@ -11,9 +11,12 @@ void Mesh::loop() {
|
||||
Dispatcher::loop();
|
||||
}
|
||||
|
||||
bool Mesh::allowPacketForward(const mesh::Packet* packet) {
|
||||
bool Mesh::allowPacketForward(const mesh::Packet* packet) {
|
||||
return false; // by default, Transport NOT enabled
|
||||
}
|
||||
bool Mesh::takeForwardingRateLimit(const mesh::Packet* packet) {
|
||||
return true; // by default, rate limiting is not implemented
|
||||
}
|
||||
uint32_t Mesh::getRetransmitDelay(const mesh::Packet* packet) {
|
||||
uint32_t t = (_radio->getEstAirtimeFor(packet->getRawLength()) * 52 / 50) / 2;
|
||||
|
||||
@@ -41,6 +44,10 @@ int Mesh::searchChannelsByHash(const uint8_t* hash, GroupChannel channels[], int
|
||||
DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
|
||||
if (pkt->isRouteDirect() && pkt->getPayloadType() == PAYLOAD_TYPE_TRACE) {
|
||||
if (pkt->path_len < MAX_PATH_SIZE) {
|
||||
// TRACE header is trace_tag(4)+auth_code(4)+flags(1) = 9 bytes. Without this
|
||||
// guard a crafted short TRACE (payload_len < 9) underflows `len` below to a
|
||||
// large value and steers the isHashMatch() read past the payload buffer.
|
||||
if (pkt->payload_len < 9) return ACTION_RELEASE;
|
||||
uint8_t i = 0;
|
||||
uint32_t trace_tag;
|
||||
memcpy(&trace_tag, &pkt->payload[i], 4); i += 4;
|
||||
@@ -55,7 +62,9 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
|
||||
uint16_t offset = (uint16_t)pkt->path_len << path_sz;
|
||||
if (offset >= len) { // TRACE has reached end of given path
|
||||
onTraceRecv(pkt, trace_tag, auth_code, flags, pkt->path, &pkt->payload[i], len);
|
||||
} else if (self_id.isHashMatch(&pkt->payload[i + offset], 1 << path_sz) && allowPacketForward(pkt) && !_tables->wasSeen(pkt)) {
|
||||
} else if ((size_t)i + offset + (1u << path_sz) <= pkt->payload_len
|
||||
&& self_id.isHashMatch(&pkt->payload[i + offset], 1 << path_sz) && allowPacketForward(pkt) && !_tables->wasSeen(pkt)
|
||||
&& takeForwardingRateLimit(pkt)) {
|
||||
_tables->markSeen(pkt);
|
||||
// append SNR (Not hash!)
|
||||
pkt->path[pkt->path_len++] = (int8_t) (pkt->getSNR()*4);
|
||||
@@ -87,23 +96,23 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
|
||||
}
|
||||
|
||||
if (self_id.isHashMatch(pkt->path, pkt->getPathHashSize()) && allowPacketForward(pkt)) {
|
||||
uint32_t d = getDirectRetransmitDelay(pkt);
|
||||
if (pkt->getPayloadType() == PAYLOAD_TYPE_MULTIPART) {
|
||||
return forwardMultipartDirect(pkt);
|
||||
return forwardMultipartDirect(pkt, d);
|
||||
} else if (pkt->getPayloadType() == PAYLOAD_TYPE_ACK) {
|
||||
if (!_tables->wasSeen(pkt)) { // don't retransmit!
|
||||
_tables->markSeen(pkt);
|
||||
removeSelfFromPath(pkt);
|
||||
routeDirectRecvAcks(pkt, 0);
|
||||
routeDirectRecvAcks(pkt, d);
|
||||
}
|
||||
return ACTION_RELEASE;
|
||||
}
|
||||
|
||||
if (!_tables->wasSeen(pkt)) {
|
||||
if (!_tables->wasSeen(pkt) && takeForwardingRateLimit(pkt)) {
|
||||
_tables->markSeen(pkt);
|
||||
removeSelfFromPath(pkt);
|
||||
|
||||
uint32_t d = getDirectRetransmitDelay(pkt);
|
||||
return ACTION_RETRANSMIT_DELAYED(0, d); // Routed traffic is HIGHEST priority
|
||||
return ACTION_RETRANSMIT_DELAYED(0, d); // Routed traffic is HIGHEST priority
|
||||
}
|
||||
}
|
||||
return ACTION_RELEASE; // this node is NOT the next hop (OR this packet has already been forwarded), so discard.
|
||||
@@ -167,14 +176,20 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
|
||||
uint8_t hash_size = (path_len >> 6) + 1;
|
||||
uint8_t hash_count = path_len & 63;
|
||||
uint8_t* path = &data[k]; k += hash_size*hash_count;
|
||||
uint8_t extra_type = data[k++] & 0x0F; // upper 4 bits reserved for future use
|
||||
uint8_t* extra = &data[k];
|
||||
uint8_t extra_len = len - k; // remainder of packet (may be padded with zeroes!)
|
||||
if (onPeerPathRecv(pkt, j, secret, path, path_len, extra_type, extra, extra_len)) {
|
||||
if (pkt->isRouteFlood()) {
|
||||
// send a reciprocal return path to sender, but send DIRECTLY!
|
||||
mesh::Packet* rpath = createPathReturn(&src_hash, secret, pkt->path, pkt->path_len, 0, NULL, 0);
|
||||
if (rpath) sendDirect(rpath, path, path_len, 500);
|
||||
// path_len comes from the (decrypted) payload and is otherwise unchecked:
|
||||
// without this guard `k` can jump past the `data` buffer (data[k] OOB read)
|
||||
// and `extra_len = len - k` underflows. Require a valid path length and that
|
||||
// the path + trailing extra_type byte fit within the decrypted length.
|
||||
if (Packet::isValidPathLen(path_len) && k < len) {
|
||||
uint8_t extra_type = data[k++] & 0x0F; // upper 4 bits reserved for future use
|
||||
uint8_t* extra = &data[k];
|
||||
uint8_t extra_len = len - k; // remainder of packet (may be padded with zeroes!)
|
||||
if (onPeerPathRecv(pkt, j, secret, path, path_len, extra_type, extra, extra_len)) {
|
||||
if (pkt->isRouteFlood()) {
|
||||
// send a reciprocal return path to sender, but send DIRECTLY!
|
||||
mesh::Packet* rpath = createPathReturn(&src_hash, secret, pkt->path, pkt->path_len, 0, NULL, 0);
|
||||
if (rpath) sendDirect(rpath, path, path_len, 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -344,7 +359,8 @@ void Mesh::removeSelfFromPath(Packet* pkt) {
|
||||
DispatcherAction Mesh::routeRecvPacket(Packet* packet) {
|
||||
uint8_t n = packet->getPathHashCount();
|
||||
if (packet->isRouteFlood() && !packet->isMarkedDoNotRetransmit()
|
||||
&& (n + 1)*packet->getPathHashSize() <= MAX_PATH_SIZE && allowPacketForward(packet)) {
|
||||
&& (n + 1)*packet->getPathHashSize() <= MAX_PATH_SIZE && allowPacketForward(packet)
|
||||
&& takeForwardingRateLimit(packet)) {
|
||||
// append this node's hash to 'path'
|
||||
self_id.copyHashTo(&packet->path[n * packet->getPathHashSize()], packet->getPathHashSize());
|
||||
packet->setPathHashCount(n + 1);
|
||||
@@ -356,7 +372,7 @@ DispatcherAction Mesh::routeRecvPacket(Packet* packet) {
|
||||
return ACTION_RELEASE;
|
||||
}
|
||||
|
||||
DispatcherAction Mesh::forwardMultipartDirect(Packet* pkt) {
|
||||
DispatcherAction Mesh::forwardMultipartDirect(Packet* pkt, uint32_t delay_millis) {
|
||||
uint8_t remaining = pkt->payload[0] >> 4; // num of packets in this multipart sequence still to be sent
|
||||
uint8_t type = pkt->payload[0] & 0x0F;
|
||||
|
||||
@@ -370,23 +386,23 @@ DispatcherAction Mesh::forwardMultipartDirect(Packet* pkt) {
|
||||
if (!_tables->wasSeen(&tmp)) { // don't retransmit!
|
||||
_tables->markSeen(&tmp);
|
||||
removeSelfFromPath(&tmp);
|
||||
routeDirectRecvAcks(&tmp, ((uint32_t)remaining + 1) * 300); // expect multipart ACKs 300ms apart (x2)
|
||||
routeDirectRecvAcks(&tmp, delay_millis + ((uint32_t)remaining + 1) * 300); // expect multipart ACKs 300ms apart (x2)
|
||||
}
|
||||
}
|
||||
return ACTION_RELEASE;
|
||||
}
|
||||
|
||||
void Mesh::routeDirectRecvAcks(Packet* packet, uint32_t delay_millis) {
|
||||
if (!packet->isMarkedDoNotRetransmit()) {
|
||||
if (!packet->isMarkedDoNotRetransmit() && takeForwardingRateLimit(packet)) {
|
||||
uint8_t extra = getExtraAckTransmitCount();
|
||||
while (extra > 0) {
|
||||
delay_millis += getDirectRetransmitDelay(packet) + 300;
|
||||
auto a1 = createMultiAck(packet->payload, packet->payload_len, extra);
|
||||
if (a1) {
|
||||
a1->path_len = Packet::copyPath(a1->path, packet->path, packet->path_len);
|
||||
a1->header &= ~PH_ROUTE_MASK;
|
||||
a1->header |= ROUTE_TYPE_DIRECT;
|
||||
sendPacket(a1, 0, delay_millis);
|
||||
delay_millis += 300;
|
||||
}
|
||||
extra--;
|
||||
}
|
||||
@@ -639,6 +655,7 @@ void Mesh::sendFlood(Packet* packet, uint32_t delay_millis, uint8_t path_hash_si
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::sendFlood(): TRACE type not suspported", getLogDateTime());
|
||||
return;
|
||||
}
|
||||
if (path_hash_size == 0) path_hash_size = getSelfPathHashSize();
|
||||
if (path_hash_size == 0 || path_hash_size > 3) {
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::sendFlood(): invalid path_hash_size", getLogDateTime());
|
||||
return;
|
||||
@@ -666,6 +683,7 @@ void Mesh::sendFlood(Packet* packet, uint16_t* transport_codes, uint32_t delay_m
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::sendFlood(): TRACE type not suspported", getLogDateTime());
|
||||
return;
|
||||
}
|
||||
if (path_hash_size == 0) path_hash_size = getSelfPathHashSize();
|
||||
if (path_hash_size == 0 || path_hash_size > 3) {
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::sendFlood(): invalid path_hash_size", getLogDateTime());
|
||||
return;
|
||||
@@ -690,13 +708,36 @@ void Mesh::sendFlood(Packet* packet, uint16_t* transport_codes, uint32_t delay_m
|
||||
sendPacket(packet, pri, delay_millis);
|
||||
}
|
||||
|
||||
void Mesh::sendDirect(Packet* packet, const uint8_t* path, uint8_t path_len, uint32_t delay_millis) {
|
||||
void Mesh::sendDirect(Packet* packet, const uint8_t* path, uint8_t path_len, uint32_t delay_millis, uint8_t path_hash_size) {
|
||||
packet->header &= ~PH_ROUTE_MASK;
|
||||
packet->header |= ROUTE_TYPE_DIRECT;
|
||||
|
||||
if (path_hash_size == 0) path_hash_size = getSelfPathHashSize();
|
||||
|
||||
uint8_t pri;
|
||||
if (packet->getPayloadType() == PAYLOAD_TYPE_TRACE) { // TRACE packets are different
|
||||
// for TRACE packets, path is appended to end of PAYLOAD. (path is used for SNR's)
|
||||
//
|
||||
// CUSTOM (TeTeHacko): a TRACE path is NOT capped at MAX_PATH_SIZE (see the note
|
||||
// below), so this append has to be checked against the payload buffer itself.
|
||||
// The companion guard on CMD_SEND_TRACE_PATH lets path_len reach 178, and a
|
||||
// TRACE header is 9 bytes: 9+176 lands one byte past payload[184]. Measured on
|
||||
// the host over all 194 path_len/path_sz combinations the guard admits -- two
|
||||
// of them write past the end and demonstrably clobber `_snr`, the member that
|
||||
// happens to sit right after the array. Those packets are then dropped by
|
||||
// sendPacket() for exceeding the MTU, which is why nothing ever looked wrong
|
||||
// from the outside. It is still a write out of bounds.
|
||||
//
|
||||
// Same fix as upstream PR #1662 (weebl2000), open and unmerged since Feb 2026.
|
||||
// Its second half -- guarding the non-TRACE branch on path_len > MAX_PATH_SIZE
|
||||
// -- is redundant here: that path goes through Packet::copyPath/writePath,
|
||||
// which already refuses to write more than MAX_PATH_SIZE.
|
||||
if ((size_t)packet->payload_len + path_len > sizeof(packet->payload)) {
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::sendDirect(): TRACE path too long, payload_len=%d path_len=%d",
|
||||
getLogDateTime(), (int)packet->payload_len, (int)path_len);
|
||||
_mgr->free(packet);
|
||||
return;
|
||||
}
|
||||
memcpy(&packet->payload[packet->payload_len], path, path_len); // NOTE: path_len here can be > 64, and NOT in the new scheme
|
||||
packet->payload_len += path_len;
|
||||
|
||||
@@ -704,6 +745,12 @@ void Mesh::sendDirect(Packet* packet, const uint8_t* path, uint8_t path_len, uin
|
||||
pri = 5; // maybe make this configurable
|
||||
} else {
|
||||
packet->path_len = Packet::copyPath(packet->path, path, path_len);
|
||||
// An empty path has no hash-size bits of its own to preserve, and a bare 0 decodes as
|
||||
// 1 byte. Zero-hop DIRECT is the common case for a neighbour reply, so without this a
|
||||
// 2-byte node declares 1 byte on every such reply.
|
||||
if (packet->getPathHashCount() == 0) {
|
||||
packet->setPathHashSizeAndCount(path_hash_size, 0);
|
||||
}
|
||||
if (packet->getPayloadType() == PAYLOAD_TYPE_PATH) {
|
||||
pri = 1; // slightly less priority
|
||||
} else {
|
||||
@@ -714,24 +761,32 @@ void Mesh::sendDirect(Packet* packet, const uint8_t* path, uint8_t path_len, uin
|
||||
sendPacket(packet, pri, delay_millis);
|
||||
}
|
||||
|
||||
void Mesh::sendZeroHop(Packet* packet, uint32_t delay_millis) {
|
||||
void Mesh::sendZeroHop(Packet* packet, uint32_t delay_millis, uint8_t path_hash_size) {
|
||||
packet->header &= ~PH_ROUTE_MASK;
|
||||
packet->header |= ROUTE_TYPE_DIRECT;
|
||||
|
||||
packet->path_len = 0; // path_len of zero means Zero Hop
|
||||
if (path_hash_size == 0) path_hash_size = getSelfPathHashSize();
|
||||
|
||||
// Zero Hop = nulový počet hopů. POZOR, dřív tu bylo `packet->path_len = 0`,
|
||||
// což vynulovalo CELÝ bajt — a v jeho horních dvou bitech bydlí šířka hashe
|
||||
// (Packet.h:85). Každý zerohop paket proto hlásil 1 B bez ohledu na
|
||||
// nastavení uzlu a v analyzerech kreslil dvoubajtový uzel jako jednobajtový.
|
||||
packet->setPathHashSizeAndCount(path_hash_size, 0);
|
||||
|
||||
_tables->markSeen(packet); // mark this packet as already sent in case it is rebroadcast back to us
|
||||
|
||||
sendPacket(packet, 0, delay_millis);
|
||||
}
|
||||
|
||||
void Mesh::sendZeroHop(Packet* packet, uint16_t* transport_codes, uint32_t delay_millis) {
|
||||
void Mesh::sendZeroHop(Packet* packet, uint16_t* transport_codes, uint32_t delay_millis, uint8_t path_hash_size) {
|
||||
packet->header &= ~PH_ROUTE_MASK;
|
||||
packet->header |= ROUTE_TYPE_TRANSPORT_DIRECT;
|
||||
|
||||
if (path_hash_size == 0) path_hash_size = getSelfPathHashSize();
|
||||
packet->transport_codes[0] = transport_codes[0];
|
||||
packet->transport_codes[1] = transport_codes[1];
|
||||
|
||||
packet->path_len = 0; // path_len of zero means Zero Hop
|
||||
packet->setPathHashSizeAndCount(path_hash_size, 0); // viz komentář výš
|
||||
|
||||
_tables->markSeen(packet); // mark this packet as already sent in case it is rebroadcast back to us
|
||||
|
||||
|
||||
+33
-6
@@ -32,7 +32,7 @@ class Mesh : public Dispatcher {
|
||||
void removeSelfFromPath(Packet* packet);
|
||||
void routeDirectRecvAcks(Packet* packet, uint32_t delay_millis);
|
||||
//void routeRecvAcks(Packet* packet, uint32_t delay_millis);
|
||||
DispatcherAction forwardMultipartDirect(Packet* pkt);
|
||||
DispatcherAction forwardMultipartDirect(Packet* pkt, uint32_t delay_millis);
|
||||
|
||||
protected:
|
||||
DispatcherAction onRecvPacket(Packet* pkt) override;
|
||||
@@ -56,6 +56,14 @@ protected:
|
||||
*/
|
||||
virtual bool allowPacketForward(const Packet* packet);
|
||||
|
||||
/**
|
||||
* \brief Takes a token from the rate-limiter, deciding whether this packet should be forwarded.
|
||||
* May CONSUME limiter state, so callers keep it as the LAST condition of a forward decision
|
||||
* and call it at most once per packet. (CUSTOM TeTeHacko: port of upstream proposal #1502.)
|
||||
* \returns true, if the packet should be forwarded
|
||||
*/
|
||||
virtual bool takeForwardingRateLimit(const Packet* packet);
|
||||
|
||||
/**
|
||||
* \returns number of milliseconds delay to apply to retransmitting the given packet.
|
||||
*/
|
||||
@@ -71,6 +79,17 @@ protected:
|
||||
*/
|
||||
virtual uint8_t getExtraAckTransmitCount() const;
|
||||
|
||||
/**
|
||||
* \brief Width (in bytes) of the path hashes this node writes into packets it originates.
|
||||
*
|
||||
* Sender-chosen, so it must come from this node's own prefs. The base class has no prefs
|
||||
* and returns the protocol minimum; firmwares with a NodePrefs override it. Used whenever
|
||||
* a send*() caller does not pass an explicit width.
|
||||
*
|
||||
* \returns 1, 2 or 3
|
||||
*/
|
||||
virtual uint8_t getSelfPathHashSize() const { return 1; }
|
||||
|
||||
/**
|
||||
* \brief Perform search of local DB of peers/contacts.
|
||||
* \returns Number of peers with matching hash
|
||||
@@ -199,29 +218,37 @@ public:
|
||||
/**
|
||||
* \brief send a locally-generated Packet with flood routing
|
||||
*/
|
||||
void sendFlood(Packet* packet, uint32_t delay_millis=0, uint8_t path_hash_size=1);
|
||||
void sendFlood(Packet* packet, uint32_t delay_millis=0, uint8_t path_hash_size=0);
|
||||
|
||||
/**
|
||||
* \brief send a locally-generated Packet with flood routing
|
||||
* \param transport_codes array of 2 codes to attach to packet
|
||||
*/
|
||||
void sendFlood(Packet* packet, uint16_t* transport_codes, uint32_t delay_millis=0, uint8_t path_hash_size=1);
|
||||
void sendFlood(Packet* packet, uint16_t* transport_codes, uint32_t delay_millis=0, uint8_t path_hash_size=0);
|
||||
|
||||
/**
|
||||
* \brief send a locally-generated Packet with Direct routing
|
||||
*
|
||||
* `path_len` is the ENCODED path byte (hash-size bits + hop count), so a non-empty path
|
||||
* carries its own width across unchanged. An EMPTY path has no width to carry, and a bare
|
||||
* 0 decodes as 1 byte -- which is why zero-hop replies used to declare 1 B on a 2 B node.
|
||||
* `path_hash_size` (0 = this node's prefs) fills that gap.
|
||||
*/
|
||||
void sendDirect(Packet* packet, const uint8_t* path, uint8_t path_len, uint32_t delay_millis=0);
|
||||
void sendDirect(Packet* packet, const uint8_t* path, uint8_t path_len, uint32_t delay_millis=0, uint8_t path_hash_size=0);
|
||||
|
||||
/**
|
||||
* \brief send a locally-generated Packet to just neighbor nodes (zero hops)
|
||||
*/
|
||||
void sendZeroHop(Packet* packet, uint32_t delay_millis=0);
|
||||
// `path_hash_size` tu je ze stejného důvodu jako u sendFlood: zerohop paket
|
||||
// sice cestu nenese, ale ta šířka je v hlavičce a analyzery z ní odvozují,
|
||||
// na kolika bajtech uzel jede. Bez toho parametru hlásí každý zerohop 1 B.
|
||||
void sendZeroHop(Packet* packet, uint32_t delay_millis=0, uint8_t path_hash_size=0);
|
||||
|
||||
/**
|
||||
* \brief send a locally-generated Packet to just neighbor nodes (zero hops), with specific transport codes
|
||||
* \param transport_codes array of 2 codes to attach to packet
|
||||
*/
|
||||
void sendZeroHop(Packet* packet, uint16_t* transport_codes, uint32_t delay_millis=0);
|
||||
void sendZeroHop(Packet* packet, uint16_t* transport_codes, uint32_t delay_millis=0, uint8_t path_hash_size=0);
|
||||
|
||||
};
|
||||
|
||||
|
||||
+38
-7
@@ -64,23 +64,54 @@ public:
|
||||
virtual uint8_t getStartupReason() const = 0;
|
||||
virtual bool getBootloaderVersion(char* version, size_t max_len) { return false; }
|
||||
virtual bool startOTAUpdate(const char* id, char reply[]) { return false; } // not supported
|
||||
virtual bool setLoRaFemLnaEnabled(bool enable) { return false; }
|
||||
virtual bool canControlLoRaFemLna() const { return false; }
|
||||
virtual bool isLoRaFemLnaEnabled() const { return false; }
|
||||
// Software-selectable external FEM transmit gain. This is not a PA power switch.
|
||||
virtual bool setLoRaFemPaGainEnabled(bool enable) { return false; }
|
||||
virtual bool canControlLoRaFemPaGain() const { return false; }
|
||||
virtual bool isLoRaFemPaGainEnabled() const { return false; }
|
||||
|
||||
// Power management interface (boards with power management override these)
|
||||
virtual bool isPwrMgtInitialised() const { return false; }
|
||||
virtual bool isExternalPowered() { return false; }
|
||||
// True while a board can identify an active battery-charging source.
|
||||
virtual bool isChargerActive() { return false; }
|
||||
|
||||
// Optional, source-specific power detection. Boards that can distinguish a USB
|
||||
// supply from a solar charger override these; defaults keep every other board
|
||||
// unaffected (the generic CLI prints "n/a" when a capability is absent).
|
||||
virtual bool hasUsbPowerDetect() const { return false; }
|
||||
virtual bool isUsbPowered() { return false; }
|
||||
virtual bool hasSolarChargerDetect() const { return false; }
|
||||
virtual bool isSolarChargerActive() { return false; }
|
||||
virtual uint16_t getBootVoltage() { return 0; }
|
||||
virtual bool getWakeLpcompSupported() const { return false; }
|
||||
virtual uint32_t getResetReason() const { return 0; }
|
||||
virtual const char* getResetReasonString(uint32_t reason) { return "Not available"; }
|
||||
virtual uint8_t getShutdownReason() const { return 0; }
|
||||
virtual const char* getShutdownReasonString(uint8_t reason) { return "Not available"; }
|
||||
|
||||
virtual bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { return false; }
|
||||
|
||||
// Called from the example main loops. Lets a board feed its watchdog and
|
||||
// run periodic housekeeping. Default no-op.
|
||||
virtual void loop() { /* no op */ }
|
||||
};
|
||||
|
||||
// CUSTOM (TeTeHacko): the time a clock with no other source comes up at.
|
||||
//
|
||||
// tools/build_version.py injects FIRMWARE_BUILD_EPOCH = the moment of compile, so
|
||||
// a freshly flashed board is right to within "time since build" -- seconds on the
|
||||
// bench -- with no GPS, no I2C RTC, nothing carrying a correct time on air and no
|
||||
// host attached. Without it the value is upstream's hardcoded 15 May 2024, which
|
||||
// is where bench-board sat for 811 days and every bench board for 812: the clock had
|
||||
// simply never been set, because setting it was a manual step.
|
||||
//
|
||||
// That is not cosmetic. Mesh.cpp stamps every advert this node transmits from the
|
||||
// RTC, and a receiver drops a stale timestamp as a replay (BaseChatMesh.cpp), so
|
||||
// a wrong clock turns into replies that vanish.
|
||||
//
|
||||
// The fallback is NOT optional: build_version.py is wired in through
|
||||
// ${stamped.extra_scripts}, which is nRF52-only and reaches 7 of the 16 envs in
|
||||
// platformio.local.ini. Upstream envs never define it and must keep compiling.
|
||||
#ifndef FIRMWARE_BUILD_EPOCH
|
||||
#define FIRMWARE_BUILD_EPOCH 1715770351 // 15 May 2024, 8:50pm
|
||||
#endif
|
||||
|
||||
/**
|
||||
* An abstraction of the device's Realtime Clock.
|
||||
*/
|
||||
|
||||
+22
-1
@@ -63,9 +63,30 @@ uint8_t Packet::writeTo(uint8_t dest[]) const {
|
||||
}
|
||||
|
||||
bool Packet::readFrom(const uint8_t src[], uint8_t len) {
|
||||
// CUSTOM (TeTeHacko): every field is bounds-checked against `len` BEFORE it is
|
||||
// read. Upstream reads the header, the transport codes, path_len and the whole
|
||||
// path first and only then asks whether any of it was actually there
|
||||
// (`if (i >= len)`), so a short frame is read past its end and the result is
|
||||
// thrown away afterwards.
|
||||
//
|
||||
// Measured with an ASAN harness that hands readFrom a heap buffer allocated to
|
||||
// exactly `len` bytes: 5 242 880 generated frames hit FOUR distinct
|
||||
// out-of-bounds reads (header, both transport codes, path_len, the path
|
||||
// memcpy). With these guards the same sweep is clean and accepts exactly the
|
||||
// same 1 351 424 frames -- the checks reject nothing that used to parse, they
|
||||
// only stop reading memory that was never received.
|
||||
//
|
||||
// On the device the source is Dispatcher's `raw[MAX_TRANS_UNIT+1]`, a 256-byte
|
||||
// stack buffer, and this reads at most ~70 bytes into it, so what it read was
|
||||
// leftovers from an earlier packet rather than memory outside the array. That
|
||||
// is why it never showed up as a crash -- and why this is hygiene, not a hole.
|
||||
//
|
||||
// Same fix as upstream PR #1666 (weebl2000), open and unmerged since Feb 2026.
|
||||
if (len < 2) return false; // at minimum: header + path_len
|
||||
uint8_t i = 0;
|
||||
header = src[i++];
|
||||
if (hasTransportCodes()) {
|
||||
if (i + 4 >= len) return false; // 4 transport bytes plus the path_len byte
|
||||
memcpy(&transport_codes[0], &src[i], 2); i += 2;
|
||||
memcpy(&transport_codes[1], &src[i], 2); i += 2;
|
||||
} else {
|
||||
@@ -75,9 +96,9 @@ bool Packet::readFrom(const uint8_t src[], uint8_t len) {
|
||||
if (!isValidPathLen(path_len)) return false; // bad encoding
|
||||
|
||||
uint8_t bl = getPathByteLen();
|
||||
if (i + bl >= len) return false; // path plus at least one payload byte must fit
|
||||
memcpy(path, &src[i], bl); i += bl;
|
||||
|
||||
if (i >= len) return false; // bad encoding
|
||||
payload_len = len - i;
|
||||
if (payload_len > sizeof(payload)) return false; // bad encoding
|
||||
memcpy(payload, &src[i], payload_len); //i += payload_len;
|
||||
|
||||
@@ -49,6 +49,8 @@ public:
|
||||
uint8_t path[MAX_PATH_SIZE];
|
||||
uint8_t payload[MAX_PACKET_PAYLOAD];
|
||||
int8_t _snr;
|
||||
int8_t _rssi; // CUSTOM (TeTeHacko): last-hop RSSI (dBm) captured at RX, for the passive mesh analyzer
|
||||
uint8_t _tx_attempts; // CUSTOM (TeTeHacko): failed TX tries so far (RAM only; Dispatcher requeues instead of dropping)
|
||||
|
||||
/**
|
||||
* \brief calculate the hash of payload + type
|
||||
@@ -90,6 +92,7 @@ public:
|
||||
bool isMarkedDoNotRetransmit() const { return header == 0xFF; }
|
||||
|
||||
float getSNR() const { return ((float)_snr) / 4.0f; }
|
||||
int getRSSI() const { return _rssi; }
|
||||
|
||||
/**
|
||||
* \returns the encoded/wire format length of this packet
|
||||
|
||||
+14
-2
@@ -147,6 +147,9 @@ int Utils::encryptThenMAC(const uint8_t* shared_secret, uint8_t* dest, const uin
|
||||
int Utils::MACThenDecrypt(const uint8_t* shared_secret, uint8_t* dest, const uint8_t* src, int src_len) {
|
||||
if (src_len <= CIPHER_MAC_SIZE) return 0; // invalid src bytes
|
||||
|
||||
int enc_len = src_len - CIPHER_MAC_SIZE;
|
||||
if (enc_len % CIPHER_BLOCK_SIZE != 0) return 0; // reject non-block-aligned ciphertext
|
||||
|
||||
uint8_t hmac[CIPHER_MAC_SIZE];
|
||||
#ifdef USE_CC310_HW_CRYPTO
|
||||
{
|
||||
@@ -161,12 +164,12 @@ int Utils::MACThenDecrypt(const uint8_t* shared_secret, uint8_t* dest, const uin
|
||||
{
|
||||
SHA256 sha;
|
||||
sha.resetHMAC(shared_secret, PUB_KEY_SIZE);
|
||||
sha.update(src + CIPHER_MAC_SIZE, src_len - CIPHER_MAC_SIZE);
|
||||
sha.update(src + CIPHER_MAC_SIZE, enc_len);
|
||||
sha.finalizeHMAC(shared_secret, PUB_KEY_SIZE, hmac, CIPHER_MAC_SIZE);
|
||||
}
|
||||
#endif
|
||||
if (memcmp(hmac, src, CIPHER_MAC_SIZE) == 0) {
|
||||
return decrypt(shared_secret, dest, src + CIPHER_MAC_SIZE, src_len - CIPHER_MAC_SIZE);
|
||||
return decrypt(shared_secret, dest, src + CIPHER_MAC_SIZE, enc_len);
|
||||
}
|
||||
return 0; // invalid HMAC
|
||||
}
|
||||
@@ -203,6 +206,15 @@ bool Utils::isHexChar(char c) {
|
||||
return c == '0' || hexVal(c) > 0;
|
||||
}
|
||||
|
||||
bool Utils::isZeroes(const uint8_t* buf, size_t len) {
|
||||
while (len > 0) {
|
||||
if (*buf != 0) return false;
|
||||
buf++;
|
||||
len--;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Utils::fromHex(uint8_t* dest, int dest_size, const char *src_hex) {
|
||||
int len = strlen(src_hex);
|
||||
if (len != dest_size*2) return false; // incorrect length
|
||||
|
||||
+3
-1
@@ -50,7 +50,7 @@ public:
|
||||
|
||||
/**
|
||||
* \brief checks the MAC (in leading bytes of 'src'), then if valid, decrypts remaining bytes in src.
|
||||
* \returns zero if MAC is invalid, otherwise the length of decrypted bytes in 'dest'
|
||||
* \returns zero if MAC is invalid or ciphertext is not block-aligned, otherwise the length of decrypted bytes in 'dest'
|
||||
*/
|
||||
static int MACThenDecrypt(const uint8_t* shared_secret, uint8_t* dest, const uint8_t* src, int src_len);
|
||||
|
||||
@@ -82,6 +82,8 @@ public:
|
||||
static int parseTextParts(char* text, const char* parts[], int max_num, char separator=',');
|
||||
|
||||
static bool isHexChar(char c);
|
||||
|
||||
static bool isZeroes(const uint8_t* buf, size_t len);
|
||||
};
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// https://github.com/meshcore-dev/MeshCore/issues/2469
|
||||
// armstubs.cpp exists to silence warnings introduced after upgrading platformio/toolchain-gccarmnoneeabi
|
||||
extern "C" __attribute__((weak)) int _close(int fd) { return -1; }
|
||||
extern "C" __attribute__((weak)) int _lseek(int fd, int offset, int whence) { return 0; }
|
||||
extern "C" __attribute__((weak)) int _read(int fd, char *buf, int len) { return 0; }
|
||||
extern "C" __attribute__((weak)) int _fstat(int fd, struct stat *st) { return 0; }
|
||||
extern "C" __attribute__((weak)) int _isatty(int fd) { return 1; }
|
||||
extern "C" __attribute__((weak)) int _getpid(void) { return 1; }
|
||||
extern "C" __attribute__((weak)) int _kill(int pid, int sig) { return -1; }
|
||||
@@ -28,6 +28,14 @@
|
||||
return i;
|
||||
}
|
||||
|
||||
bool AdvertDataParser::isValidName(const char *n) {
|
||||
while (*n) {
|
||||
if (*n == '[' || *n == ']' || *n == '\\' || *n == ':' || *n == ',' || *n == '?' || *n == '*') return false;
|
||||
n++;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
AdvertDataParser::AdvertDataParser(const uint8_t app_data[], uint8_t app_data_len) {
|
||||
_name[0] = 0;
|
||||
_lat = _lon = 0;
|
||||
|
||||
@@ -31,6 +31,25 @@ public:
|
||||
|
||||
void setFeat1(uint16_t extra) { _extra1 = extra; }
|
||||
void setFeat2(uint16_t extra) { _extra2 = extra; }
|
||||
void setName(const char* name) { _name = name; }
|
||||
|
||||
/**
|
||||
* \brief bytes left for the name with the fields set so far.
|
||||
*
|
||||
* CUSTOM (TeTeHacko): the name is encoded last and clamped to whatever is
|
||||
* left, so anyone who wants to append to it (battery icon, see
|
||||
* helpers/BatteryIcon.h) has to know the remainder. Deriving it a second
|
||||
* time elsewhere goes stale the moment a field is added -- a copy in
|
||||
* BatteryIcon.h already missed FEAT1/FEAT2 and would have let the UTF-8
|
||||
* clamp cut a glyph in half.
|
||||
*/
|
||||
size_t nameBudget() const {
|
||||
size_t used = 1; // flags
|
||||
if (_has_loc) used += 8; // lat + lon
|
||||
if (_extra1) used += 2;
|
||||
if (_extra2) used += 2;
|
||||
return MAX_ADVERT_DATA_SIZE - used;
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief encode the given advertisement data.
|
||||
@@ -50,6 +69,8 @@ class AdvertDataParser {
|
||||
public:
|
||||
AdvertDataParser(const uint8_t app_data[], uint8_t app_data_len);
|
||||
|
||||
static bool isValidName(const char* name);
|
||||
|
||||
bool isValid() const { return _valid; }
|
||||
uint8_t getType() const { return _flags & 0x0F; }
|
||||
uint16_t getFeat1() const { return _extra1; }
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
#pragma once
|
||||
|
||||
// CUSTOM (TeTeHacko): per-origin advert window, ported from DutchMeshCore's
|
||||
// AdvertLimiter (Dutch-MeshCore/MeshCore d26421b0, examples/simple_repeater/
|
||||
// AdvertLimiter.h; same MIT licence as this tree). Behaviour is theirs, names
|
||||
// and the eviction counter are ours.
|
||||
//
|
||||
// Each origin's flood advert is forwarded at most once per window, so a node
|
||||
// that re-advertises every minute (CP1 on the CZ mesh, since 30. 10. 2026:
|
||||
// a flood advert every 60 s, seen by 40-90 observers each) stops being
|
||||
// re-flooded by this repeater while it still stays reachable through it once
|
||||
// per window. FairnessLimiter's advert bucket cannot do that:
|
||||
// it is keyed on 7 bits of the key, so the chatty node and ~8 innocent ones
|
||||
// share a bucket, and loosening it for them lets the chatty one through.
|
||||
//
|
||||
// Origins are keyed on the first 4 bytes of the advert's public key (payload
|
||||
// starts with it). Fixed ring of ADVERT_WINDOW_SIZE entries: once full, the
|
||||
// oldest entry is overwritten -- that origin gets a free pass next time. RAM
|
||||
// only, so after a reboot every origin gets one free pass. Time is millis and
|
||||
// compared with unsigned subtraction, so it survives the 49-day wrap.
|
||||
// Header-only and dependency-free so it runs in the native tests.
|
||||
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
#ifndef ADVERT_WINDOW_SIZE
|
||||
#define ADVERT_WINDOW_SIZE 256 // 8 B each => 2 KB RAM
|
||||
#endif
|
||||
#define ADVERT_WINDOW_KEY_LEN 4
|
||||
#define ADVERT_WINDOW_MAX_HOURS 720 // 30 days; keeps hours*3600*1000 inside uint32
|
||||
|
||||
class AdvertWindow {
|
||||
struct Entry {
|
||||
uint8_t key[ADVERT_WINDOW_KEY_LEN];
|
||||
uint32_t seen_ms;
|
||||
};
|
||||
|
||||
Entry _cache[ADVERT_WINDOW_SIZE];
|
||||
uint16_t _count = 0; // entries in use
|
||||
uint16_t _head = 0; // next entry to overwrite once the cache is full
|
||||
uint16_t _hours = 0; // 0 = off
|
||||
uint32_t _evicted = 0; // origins forgotten because the ring was full
|
||||
|
||||
public:
|
||||
AdvertWindow() { memset(_cache, 0, sizeof(_cache)); }
|
||||
|
||||
void setHours(uint16_t hours) { _hours = hours > ADVERT_WINDOW_MAX_HOURS ? ADVERT_WINDOW_MAX_HOURS : hours; }
|
||||
uint16_t hours() const { return _hours; }
|
||||
int count() const { return _count; }
|
||||
int capacity() const { return ADVERT_WINDOW_SIZE; }
|
||||
// Non-zero = the ring is too small for the mesh: origins fall out before
|
||||
// their window ends and get a pass they should not have had.
|
||||
uint32_t evicted() const { return _evicted; }
|
||||
|
||||
void clear() { _count = 0; _head = 0; }
|
||||
|
||||
// True when the advert from `key` may be forwarded now (and records it),
|
||||
// false when the same origin already passed inside the current window.
|
||||
bool allow(const uint8_t* key, uint32_t now_ms) {
|
||||
if (_hours == 0 || key == nullptr) return true;
|
||||
|
||||
uint32_t window_ms = (uint32_t)_hours * 3600UL * 1000UL;
|
||||
|
||||
for (int i = 0; i < _count; i++) {
|
||||
Entry& e = _cache[i];
|
||||
if (memcmp(e.key, key, ADVERT_WINDOW_KEY_LEN) != 0) continue;
|
||||
if (now_ms - e.seen_ms < window_ms) return false; // unsigned: wrap-safe
|
||||
e.seen_ms = now_ms; // window elapsed: pass, and start a new window
|
||||
return true;
|
||||
}
|
||||
|
||||
Entry* e;
|
||||
if (_count < ADVERT_WINDOW_SIZE) {
|
||||
e = &_cache[_count++];
|
||||
} else {
|
||||
e = &_cache[_head]; // overwrite the oldest entry
|
||||
_head = (uint16_t)((_head + 1) % ADVERT_WINDOW_SIZE);
|
||||
_evicted++;
|
||||
}
|
||||
memcpy(e->key, key, ADVERT_WINDOW_KEY_LEN);
|
||||
e->seen_ms = now_ms;
|
||||
return true;
|
||||
}
|
||||
};
|
||||
@@ -3,19 +3,79 @@
|
||||
#include <Mesh.h>
|
||||
#include <Arduino.h>
|
||||
|
||||
#if defined(NRF52_PLATFORM) && !defined(NO_RETAINED_CLOCK)
|
||||
// CUSTOM (TeTeHacko): the wall clock survives a warm reset (`reboot`, `dfu`,
|
||||
// watchdog, reset pin) in RAM the startup code does not touch. NRF52Board.cpp
|
||||
// holds the record in .noinit -- placed by the linker after .bss, NOT at the top
|
||||
// of RAM: the Adafruit bootloader runs before every boot with its stack starting
|
||||
// at 0x20040000, and an earlier fixed record at 0x2003FFE0 came back overwritten
|
||||
// (7. 8. 2026). Approach from weebl2000/meshcore 9a561fd7.
|
||||
#define RETAINED_CLOCK_NOINIT 1
|
||||
extern "C" {
|
||||
extern uint32_t g_retained_clock[3]; // magic, time, ~time
|
||||
extern uint8_t g_retained_clock_status; // RetainedClockStatus, for the boot printout
|
||||
uint32_t readResetReason(void); // latched by the core's init()
|
||||
}
|
||||
#define RETAINED_CLOCK_MAGIC 0xC10CB0DE
|
||||
enum RetainedClockStatus { RC_NOT_YET, RC_EMPTY, RC_POWER_ON, RC_NOT_NEWER, RC_RESTORED };
|
||||
#endif
|
||||
|
||||
class VolatileRTCClock : public mesh::RTCClock {
|
||||
uint32_t base_time;
|
||||
uint64_t accumulator;
|
||||
unsigned long prev_millis;
|
||||
#ifdef RETAINED_CLOCK_NOINIT
|
||||
bool restore_pending = true;
|
||||
uint32_t last_saved = 0;
|
||||
|
||||
static void save(uint32_t t) {
|
||||
g_retained_clock[1] = t;
|
||||
g_retained_clock[2] = ~t;
|
||||
g_retained_clock[0] = RETAINED_CLOCK_MAGIC; // magic last: a reset mid-write leaves it invalid
|
||||
}
|
||||
// Not in the constructor: static constructors run before the core's init()
|
||||
// latches RESETREAS, so the reset reason would still read 0 there.
|
||||
void restoreOnce() {
|
||||
if (!restore_pending) return;
|
||||
restore_pending = false;
|
||||
uint32_t t = g_retained_clock[1];
|
||||
bool valid = g_retained_clock[0] == RETAINED_CLOCK_MAGIC && g_retained_clock[2] == ~t;
|
||||
if (!valid) { g_retained_clock_status = RC_EMPTY; return; }
|
||||
// No reset bit = power-on/brownout: RAM may still hold the record through a
|
||||
// short outage, but it is stale by however long the power was gone.
|
||||
if (readResetReason() == 0) { g_retained_clock_status = RC_POWER_ON; return; }
|
||||
if (t <= base_time + accumulator / 1000) { g_retained_clock_status = RC_NOT_NEWER; return; }
|
||||
base_time = t; accumulator = 0; prev_millis = millis();
|
||||
g_retained_clock_status = RC_RESTORED;
|
||||
}
|
||||
#endif
|
||||
public:
|
||||
VolatileRTCClock() { base_time = 1715770351; accumulator = 0; prev_millis = millis(); } // 15 May 2024, 8:50pm
|
||||
uint32_t getCurrentTime() override { return base_time + accumulator/1000; }
|
||||
void setCurrentTime(uint32_t time) override { base_time = time; accumulator = 0; prev_millis = millis(); }
|
||||
// FIRMWARE_BUILD_EPOCH = compile time when the build is stamped, else upstream's
|
||||
// 15 May 2024 literal. See the define in MeshCore.h for why this matters.
|
||||
VolatileRTCClock() { base_time = FIRMWARE_BUILD_EPOCH; accumulator = 0; prev_millis = millis(); }
|
||||
uint32_t getCurrentTime() override {
|
||||
#ifdef RETAINED_CLOCK_NOINIT
|
||||
restoreOnce();
|
||||
#endif
|
||||
return base_time + accumulator/1000;
|
||||
}
|
||||
void setCurrentTime(uint32_t time) override {
|
||||
base_time = time; accumulator = 0; prev_millis = millis();
|
||||
#ifdef RETAINED_CLOCK_NOINIT
|
||||
restore_pending = false; // an explicit set wins over whatever was retained
|
||||
save(time); last_saved = time;
|
||||
#endif
|
||||
}
|
||||
|
||||
void tick() override {
|
||||
unsigned long now = millis();
|
||||
accumulator += (now - prev_millis);
|
||||
prev_millis = now;
|
||||
#ifdef RETAINED_CLOCK_NOINIT
|
||||
restoreOnce();
|
||||
uint32_t t = base_time + accumulator / 1000;
|
||||
if (t != last_saved) { save(t); last_saved = t; }
|
||||
#endif
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -13,8 +13,12 @@ void ArduinoSerialInterface::disable() {
|
||||
_isEnabled = false;
|
||||
}
|
||||
|
||||
bool ArduinoSerialInterface::isConnected() const {
|
||||
return true; // no way of knowing, so assume yes
|
||||
bool ArduinoSerialInterface::isConnected() const {
|
||||
#if defined(NRF52_PLATFORM) || defined(ESP32_PLATFORM)
|
||||
return Serial; // operator bool() checks connection (USB CDC DTR, UART init)
|
||||
#else
|
||||
return true; // platforms without operator bool() on Serial have no way of knowing, so assume yes
|
||||
#endif
|
||||
}
|
||||
|
||||
bool ArduinoSerialInterface::isWriteBusy() const {
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
#define TXT_ACK_DELAY 200
|
||||
#endif
|
||||
|
||||
#define CLI_REPLY_DELAY_MILLIS 600
|
||||
|
||||
void BaseChatMesh::sendFloodScoped(const ContactInfo& recipient, mesh::Packet* pkt, uint32_t delay_millis) {
|
||||
sendFlood(pkt, delay_millis);
|
||||
}
|
||||
@@ -62,7 +64,12 @@ void BaseChatMesh::bootstrapRTCfromContacts() {
|
||||
latest = contacts[i].lastmod;
|
||||
}
|
||||
}
|
||||
if (latest != 0) {
|
||||
// CUSTOM (TeTeHacko): only ever forward. Upstream sets this unconditionally,
|
||||
// which was harmless while the clock started in 2024; ours starts at the build
|
||||
// epoch (or a time retained across a warm reset, read by getCurrentTime()
|
||||
// here), and an old contact would otherwise pull the clock back -- and, on
|
||||
// nRF52, cancel the retained-clock restore it ran ahead of.
|
||||
if (latest != 0 && latest + 1 > getRTCClock()->getCurrentTime()) {
|
||||
getRTCClock()->setCurrentTime(latest + 1);
|
||||
}
|
||||
}
|
||||
@@ -126,6 +133,7 @@ void BaseChatMesh::onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id,
|
||||
|
||||
ContactInfo* from = NULL;
|
||||
for (int i = 0; i < num_contacts; i++) {
|
||||
if (contacts[i].isEmptySlot()) continue;
|
||||
if (id.matches(contacts[i].id)) { // is from one of our contacts
|
||||
from = &contacts[i];
|
||||
if (timestamp <= from->last_advert_timestamp) { // check for replay attacks!!
|
||||
@@ -201,6 +209,11 @@ void BaseChatMesh::onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id,
|
||||
int BaseChatMesh::searchPeersByHash(const uint8_t* hash) {
|
||||
int n = 0;
|
||||
for (int i = 0; i < num_contacts && n < MAX_SEARCH_RESULTS; i++) {
|
||||
// Skip empty/unconfigured anon slots. An empty slot has an all-zero pub_key
|
||||
// (an order-4 Edwards25519 point whose clamped X25519 key exchange yields an
|
||||
// all-zero shared secret for any private key) and would otherwise match
|
||||
// src_hash == 0x00 as a null-key peer sink while consuming search slots.
|
||||
if (contacts[i].isEmptySlot()) continue;
|
||||
if (contacts[i].id.isHashMatch(hash)) {
|
||||
matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
|
||||
}
|
||||
@@ -227,8 +240,8 @@ void BaseChatMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender
|
||||
ContactInfo& from = contacts[i];
|
||||
|
||||
if (type == PAYLOAD_TYPE_TXT_MSG && len > 5) {
|
||||
uint32_t timestamp;
|
||||
memcpy(×tamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
|
||||
uint32_t sender_timestamp;
|
||||
memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
|
||||
uint8_t flags = data[4] >> 2; // message attempt number, and other flags
|
||||
|
||||
// len can be > original length, but 'text' will be padded with zeroes
|
||||
@@ -236,7 +249,7 @@ void BaseChatMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender
|
||||
|
||||
if (flags == TXT_TYPE_PLAIN) {
|
||||
from.lastmod = getRTCClock()->getCurrentTime(); // update last heard time
|
||||
onMessageRecv(from, packet, timestamp, (const char *) &data[5]); // let UI know
|
||||
onMessageRecv(from, packet, sender_timestamp, (const char *) &data[5]); // let UI know
|
||||
|
||||
int text_len = strlen((char *)&data[5]);
|
||||
uint8_t ack_hash[6]; // calc truncated hash of the message timestamp + text + sender pub_key, to prove to sender that we got it
|
||||
@@ -254,20 +267,44 @@ void BaseChatMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender
|
||||
sendAckTo(from, ack_hash, 6);
|
||||
}
|
||||
} else if (flags == TXT_TYPE_CLI_DATA) {
|
||||
onCommandDataRecv(from, packet, timestamp, (const char *) &data[5]); // let UI know
|
||||
char *text = (char *)&data[5];
|
||||
onCommandDataRecv(from, packet, sender_timestamp, text); // let UI know
|
||||
// NOTE: no ack expected for CLI_DATA replies
|
||||
} else if (flags == TXT_TYPE_CLI_COMMAND) {
|
||||
// 5-byte datagram header + 3-byte reflected CLI prefix + 160-byte reply text + NUL
|
||||
uint8_t temp[169];
|
||||
char *command = (char *)&data[5];
|
||||
char *reply = (char *)&temp[5];
|
||||
*reply = 0;
|
||||
|
||||
if (packet->isRouteFlood()) {
|
||||
// let this sender know path TO here, so they can use sendDirect() (NOTE: no ACK as extra)
|
||||
mesh::Packet* path = createPathReturn(from.id, secret, packet->path, packet->path_len, 0, NULL, 0);
|
||||
if (path) sendFloodScoped(from, path);
|
||||
onCLICommandRecv(from, packet, sender_timestamp, command, reply); // let UI know
|
||||
// NOTE: no ack expected for CLI_COMMAND replies
|
||||
|
||||
int text_len = strlen(reply);
|
||||
if (text_len > 0) {
|
||||
uint32_t timestamp = getRTCClock()->getCurrentTimeUnique();
|
||||
if (timestamp == sender_timestamp) {
|
||||
// WORKAROUND: the two timestamps need to be different, in the CLI view
|
||||
timestamp++;
|
||||
}
|
||||
memcpy(temp, ×tamp, 4);
|
||||
temp[4] = (TXT_TYPE_CLI_DATA << 2);
|
||||
|
||||
auto reply_pkt = createDatagram(PAYLOAD_TYPE_TXT_MSG, from.id, secret, temp, 5 + text_len);
|
||||
if (reply_pkt) {
|
||||
if (from.out_path_len == OUT_PATH_UNKNOWN) {
|
||||
sendFloodScoped(from, reply_pkt, CLI_REPLY_DELAY_MILLIS);
|
||||
} else {
|
||||
sendDirect(reply_pkt, from.out_path, from.out_path_len, CLI_REPLY_DELAY_MILLIS);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (flags == TXT_TYPE_SIGNED_PLAIN) {
|
||||
if (timestamp > from.sync_since) { // make sure 'sync_since' is up-to-date
|
||||
from.sync_since = timestamp;
|
||||
if (sender_timestamp > from.sync_since) { // make sure 'sync_since' is up-to-date
|
||||
from.sync_since = sender_timestamp;
|
||||
}
|
||||
from.lastmod = getRTCClock()->getCurrentTime(); // update last heard time
|
||||
onSignedMessageRecv(from, packet, timestamp, &data[5], (const char *) &data[9]); // let UI know
|
||||
onSignedMessageRecv(from, packet, sender_timestamp, &data[5], (const char *) &data[9]); // let UI know
|
||||
|
||||
uint32_t ack_hash; // calc truncated hash of the message timestamp + text + OUR pub_key, to prove to sender that we got it
|
||||
mesh::Utils::sha256((uint8_t *) &ack_hash, 4, data, 9 + strlen((char *)&data[9]), self_id.pub_key, PUB_KEY_SIZE);
|
||||
@@ -368,6 +405,12 @@ void BaseChatMesh::handleReturnPathRetry(const ContactInfo& contact, const uint8
|
||||
int BaseChatMesh::searchChannelsByHash(const uint8_t* hash, mesh::GroupChannel dest[], int max_matches) {
|
||||
int n = 0;
|
||||
for (int i = 0; i < MAX_GROUP_CHANNELS && n < max_matches; i++) {
|
||||
// Skip empty/unconfigured slots. An empty slot has an all-zero secret and
|
||||
// therefore matches null-key group traffic (a node transmitting with an
|
||||
// unset PSK): the zero-key MAC validates against the empty slot and the
|
||||
// foreign message is delivered as if it belonged to that channel. Any node
|
||||
// with a free channel slot would otherwise act as a null-key sink.
|
||||
if (channels[i].name[0] == 0) continue;
|
||||
if (channels[i].channel.hash[0] == hash[0]) {
|
||||
dest[n++] = channels[i].channel;
|
||||
}
|
||||
@@ -458,13 +501,13 @@ int BaseChatMesh::sendMessage(const ContactInfo& recipient, uint32_t timestamp,
|
||||
return rc;
|
||||
}
|
||||
|
||||
int BaseChatMesh::sendCommandData(const ContactInfo& recipient, uint32_t timestamp, uint8_t attempt, const char* text, uint32_t& est_timeout) {
|
||||
int BaseChatMesh::sendCommandData(const ContactInfo& recipient, uint32_t timestamp, uint8_t attempt, uint8_t txt_type, const char* text, uint32_t& est_timeout) {
|
||||
int text_len = strlen(text);
|
||||
if (text_len > MAX_TEXT_LEN) return MSG_SEND_FAILED;
|
||||
|
||||
uint8_t temp[5+MAX_TEXT_LEN+1];
|
||||
memcpy(temp, ×tamp, 4); // mostly an extra blob to help make packet_hash unique
|
||||
temp[4] = (attempt & 3) | (TXT_TYPE_CLI_DATA << 2);
|
||||
temp[4] = (attempt & 3) | (txt_type << 2);
|
||||
memcpy(&temp[5], text, text_len + 1);
|
||||
|
||||
auto pkt = createDatagram(PAYLOAD_TYPE_TXT_MSG, recipient.id, recipient.getSharedSecret(self_id), temp, 5 + text_len);
|
||||
@@ -485,6 +528,11 @@ int BaseChatMesh::sendCommandData(const ContactInfo& recipient, uint32_t timest
|
||||
}
|
||||
|
||||
bool BaseChatMesh::sendGroupMessage(uint32_t timestamp, mesh::GroupChannel& channel, const char* sender_name, const char* text, int text_len) {
|
||||
if (text_len < 0) { // memcpy() below would read this as a size_t, so clamping cannot catch it
|
||||
MESH_DEBUG_PRINTLN("sendGroupMessage: invalid negative text_len=%d", text_len);
|
||||
return false;
|
||||
}
|
||||
|
||||
uint8_t temp[5+MAX_TEXT_LEN+32];
|
||||
memcpy(temp, ×tamp, 4); // mostly an extra blob to help make packet_hash unique
|
||||
temp[4] = 0; // TXT_TYPE_PLAIN
|
||||
@@ -835,6 +883,7 @@ ContactInfo* BaseChatMesh::searchContactsByPrefix(const char* name_prefix) {
|
||||
int len = strlen(name_prefix);
|
||||
for (int i = 0; i < num_contacts; i++) {
|
||||
auto c = &contacts[i];
|
||||
if (c->isEmptySlot() || c->name[0] == 0) continue;
|
||||
if (memcmp(c->name, name_prefix, len) == 0) return c;
|
||||
}
|
||||
return NULL; // not found
|
||||
@@ -843,6 +892,7 @@ ContactInfo* BaseChatMesh::searchContactsByPrefix(const char* name_prefix) {
|
||||
ContactInfo* BaseChatMesh::lookupContactByPubKey(const uint8_t* pub_key, int prefix_len) {
|
||||
for (int i = 0; i < num_contacts; i++) {
|
||||
auto c = &contacts[i];
|
||||
if (c->isEmptySlot()) continue;
|
||||
if (memcmp(c->id.pub_key, pub_key, prefix_len) == 0) return c;
|
||||
}
|
||||
return NULL; // not found
|
||||
@@ -860,7 +910,7 @@ bool BaseChatMesh::addContact(const ContactInfo& contact) {
|
||||
|
||||
bool BaseChatMesh::removeContact(ContactInfo& contact) {
|
||||
int idx = 0;
|
||||
while (idx < num_contacts && !contacts[idx].id.matches(contact.id)) {
|
||||
while (idx < num_contacts && (contacts[idx].isEmptySlot() || !contacts[idx].id.matches(contact.id))) {
|
||||
idx++;
|
||||
}
|
||||
if (idx >= num_contacts) return false; // not found
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
#include "ContactInfo.h"
|
||||
|
||||
#define MAX_SEARCH_RESULTS 8
|
||||
#define MAX_SEARCH_RESULTS 24
|
||||
|
||||
#define MSG_SEND_FAILED 0
|
||||
#define MSG_SEND_SENT_FLOOD 1
|
||||
@@ -114,6 +114,7 @@ protected:
|
||||
virtual bool onContactPathRecv(ContactInfo& from, uint8_t* in_path, uint8_t in_path_len, uint8_t* out_path, uint8_t out_path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len);
|
||||
virtual void onMessageRecv(const ContactInfo& contact, mesh::Packet* pkt, uint32_t sender_timestamp, const char *text) = 0;
|
||||
virtual void onCommandDataRecv(const ContactInfo& contact, mesh::Packet* pkt, uint32_t sender_timestamp, const char *text) = 0;
|
||||
virtual void onCLICommandRecv(const ContactInfo& contact, mesh::Packet* pkt, uint32_t sender_timestamp, const char *text, char* reply) = 0;
|
||||
virtual void onSignedMessageRecv(const ContactInfo& contact, mesh::Packet* pkt, uint32_t sender_timestamp, const uint8_t *sender_prefix, const char *text) = 0;
|
||||
virtual uint32_t calcFloodTimeoutMillisFor(uint32_t pkt_airtime_millis) const = 0;
|
||||
virtual uint32_t calcDirectTimeoutMillisFor(uint32_t pkt_airtime_millis, uint8_t path_len) const = 0;
|
||||
@@ -156,7 +157,7 @@ public:
|
||||
mesh::Packet* createSelfAdvert(const char* name);
|
||||
mesh::Packet* createSelfAdvert(const char* name, double lat, double lon);
|
||||
int sendMessage(const ContactInfo& recipient, uint32_t timestamp, uint8_t attempt, const char* text, uint32_t& expected_ack, uint32_t& est_timeout);
|
||||
int sendCommandData(const ContactInfo& recipient, uint32_t timestamp, uint8_t attempt, const char* text, uint32_t& est_timeout);
|
||||
int sendCommandData(const ContactInfo& recipient, uint32_t timestamp, uint8_t attempt, uint8_t txt_type, const char* text, uint32_t& est_timeout);
|
||||
bool sendGroupMessage(uint32_t timestamp, mesh::GroupChannel& channel, const char* sender_name, const char* text, int text_len);
|
||||
bool sendGroupData(mesh::GroupChannel& channel, uint8_t* path, uint8_t path_len, uint16_t data_type, const uint8_t* data, int data_len);
|
||||
int sendLogin(const ContactInfo& recipient, const char* password, uint32_t& est_timeout);
|
||||
@@ -181,5 +182,8 @@ public:
|
||||
bool setChannel(int idx, const ChannelDetails& src);
|
||||
int findChannelIdx(const mesh::GroupChannel& ch);
|
||||
|
||||
virtual void savePrefs() { }
|
||||
virtual void enterCLIRescue() { }
|
||||
|
||||
void loop();
|
||||
};
|
||||
@@ -19,4 +19,18 @@ public:
|
||||
virtual bool isWriteBusy() const = 0;
|
||||
virtual size_t writeFrame(const uint8_t src[], size_t len) = 0;
|
||||
virtual size_t checkRecvFrame(uint8_t dest[]) = 0;
|
||||
|
||||
// Whether the transport carrying the current / most-recent frame is
|
||||
// authenticated. A single-transport interface is trusted by definition
|
||||
// (physically-connected USB, or a MITM-paired BLE link), so the default is
|
||||
// true. Multi-transport wrappers (e.g. SerialDualInterface) override this to
|
||||
// distinguish an unauthenticated local channel (USB) from a paired one, so
|
||||
// callers can gate sensitive commands (key export, PIN read/set).
|
||||
virtual bool isConnectionSecure() const { return true; }
|
||||
|
||||
// CUSTOM (TeTeHacko): a reply that must go back only over the transport the
|
||||
// request came on -- the private key, the BLE PIN. writeFrame() of a
|
||||
// multi-transport wrapper sends to every enabled transport, so a key exported
|
||||
// over paired BLE also went out on USB. Single transports: the same thing.
|
||||
virtual size_t writeReplyFrame(const uint8_t src[], size_t len) { return writeFrame(src, len); }
|
||||
};
|
||||
@@ -0,0 +1,161 @@
|
||||
#pragma once
|
||||
|
||||
// CUSTOM (TeTeHacko): battery state as an icon appended to the advertised
|
||||
// node name.
|
||||
//
|
||||
// Why at all: the node already reports its battery in telemetry, but only
|
||||
// someone who can log into it gets to read that. An icon in the advert reaches
|
||||
// everyone who hears the node, and costs a handful of bytes of app_data.
|
||||
//
|
||||
// The budget is tight. app_data is MAX_ADVERT_DATA_SIZE (32) bytes, of which
|
||||
// the flags take 1 and lat/lon another 8, leaving 23 bytes for the name on a
|
||||
// node that advertises its position. The whole indicator has to fit in what
|
||||
// the name leaves over -- for the deployed names that is 6 bytes.
|
||||
//
|
||||
// Which rules out emoji for the level. Unicode has exactly TWO battery emoji,
|
||||
// U+1F50B and U+1FAAB; there is no "half full" one, and at 4 bytes each a
|
||||
// sun-plus-battery pair costs 7 bytes, one too many. Block elements live in
|
||||
// the BMP, so they are 3 bytes rather than 4, and come in eight steps -- the
|
||||
// most states for the fewest bytes:
|
||||
//
|
||||
// marker U+2600 3 B sun, permanent -- "this is a solar node".
|
||||
// Deliberately WITHOUT the U+FE0F variation
|
||||
// selector, which costs 3 more bytes and buys
|
||||
// only a colour glyph.
|
||||
// level U+2581..88 3 B eight steps of charge
|
||||
//
|
||||
// Sampling rate is a non-issue: a solar node drifts by about 13 mV/day
|
||||
// (measured on mast-repeater-one over 30 days), so even at eight steps the
|
||||
// name changes roughly once a week. The flood advert interval of 25 h is far
|
||||
// finer than the thing being measured.
|
||||
|
||||
#include <MeshCore.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
// Permanent marker, prepended to the level. Empty string disables it.
|
||||
#ifndef BATT_ICON_MARKER
|
||||
#define BATT_ICON_MARKER "☀" // sun, 3 bytes
|
||||
#endif
|
||||
// Level glyphs, low to high. All must be the same byte length.
|
||||
#ifndef BATT_ICON_LEVELS
|
||||
#define BATT_ICON_LEVELS "▁▂▃▄▅▆▇█"
|
||||
#endif
|
||||
#ifndef BATT_ICON_LEVEL_BYTES
|
||||
#define BATT_ICON_LEVEL_BYTES 3
|
||||
#endif
|
||||
// Shown INSTEAD of the level while the node runs on external power, which
|
||||
// nRF52 reports straight from VBUS detect (MainBoard::isExternalPowered()).
|
||||
// That covers the bench, where a board with no cell reads a meaningless
|
||||
// floating VBAT -- better to say "on USB" than to draw a charge level out of
|
||||
// noise. It is 3 bytes like a level glyph, so the budget does not move.
|
||||
#ifndef BATT_ICON_EXTERNAL
|
||||
#define BATT_ICON_EXTERNAL "\u26A1" // high voltage, 3 bytes
|
||||
#endif
|
||||
|
||||
// Scale ends in millivolts for a 1S Li-Ion/LiPo cell -- the same 3300..4200
|
||||
// the dashboards use, so the icon and the Grafana percentage tell one story.
|
||||
#ifndef BATT_ICON_LO_MV
|
||||
#define BATT_ICON_LO_MV 3300
|
||||
#endif
|
||||
#ifndef BATT_ICON_HI_MV
|
||||
#define BATT_ICON_HI_MV 4200
|
||||
#endif
|
||||
// Hysteresis per boundary. Has to clear the measured daily swing of a solar
|
||||
// node under weak sun (38-46 mV) or the level would follow sunrise and
|
||||
// sunset, and stay well under one step (112 mV at eight levels) or the level
|
||||
// could never climb at all.
|
||||
#ifndef BATT_ICON_HYST_MV
|
||||
#define BATT_ICON_HYST_MV 50
|
||||
#endif
|
||||
|
||||
namespace mesh {
|
||||
|
||||
// Number of level glyphs.
|
||||
inline uint8_t battIconLevels() {
|
||||
return (uint8_t)((sizeof(BATT_ICON_LEVELS) - 1) / BATT_ICON_LEVEL_BYTES);
|
||||
}
|
||||
|
||||
// Bytes the indicator adds to the name: marker plus one level glyph.
|
||||
//
|
||||
// Every level is the same width, and that is the point rather than a detail:
|
||||
// a name whose length changed with the charge would be re-truncated by the
|
||||
// UTF-8 clamp at some steps and not others, and every client that hears it
|
||||
// would rewrite the contact.
|
||||
inline size_t battIconWidth() {
|
||||
const size_t lvl = BATT_ICON_LEVEL_BYTES;
|
||||
const size_t ext = sizeof(BATT_ICON_EXTERNAL) - 1;
|
||||
return (sizeof(BATT_ICON_MARKER) - 1) + (lvl > ext ? lvl : ext);
|
||||
}
|
||||
|
||||
// Does the name still fit with the indicator appended?
|
||||
//
|
||||
// `budget` musí přijít z AdvertDataBuilder::nameBudget(), ne z druhého výpočtu
|
||||
// tady: rozpočet závisí i na FEAT1/FEAT2, a kopie, která o nich nevěděla, by
|
||||
// tvrdila o 2-4 bajty víc, než je pravda. Pak by UTF-8 clamp uřízl glyf
|
||||
// vpůli -- přesně to tiché selhání, které tenhle soubor jinde odmítá.
|
||||
inline bool battIconFits(size_t name_len, size_t budget) {
|
||||
return name_len + battIconWidth() <= budget;
|
||||
}
|
||||
|
||||
// Copy the glyph for `level` into dest, which must hold
|
||||
// BATT_ICON_LEVEL_BYTES + 1 bytes.
|
||||
inline void battIconGlyph(char dest[], uint8_t level) {
|
||||
uint8_t n = battIconLevels();
|
||||
if (n == 0) { dest[0] = 0; return; }
|
||||
if (level >= n) level = n - 1;
|
||||
const char* tbl = BATT_ICON_LEVELS;
|
||||
memcpy(dest, tbl + (size_t)level * BATT_ICON_LEVEL_BYTES, BATT_ICON_LEVEL_BYTES);
|
||||
dest[BATT_ICON_LEVEL_BYTES] = 0;
|
||||
}
|
||||
|
||||
// Charge level 0..n-1 for `mv`, with hysteresis against the previous level.
|
||||
//
|
||||
// Asymmetric on purpose: the level drops as soon as the voltage falls below a
|
||||
// boundary, but climbs only once it is hyst_mv clear of one. Falling is the
|
||||
// direction that matters -- an optimistic icon on a node that is browning out
|
||||
// is worse than a pessimistic one on a node that is charging.
|
||||
//
|
||||
// Starting from 0 the climb loop walks up to wherever the voltage actually
|
||||
// is, so a fresh boot settles on the right level (one hysteresis band low,
|
||||
// the safe side) without needing a separate "unknown" state.
|
||||
inline uint8_t battIconLevel(uint8_t prev, uint16_t mv, uint16_t lo_mv, uint16_t hi_mv,
|
||||
uint8_t n, uint16_t hyst_mv) {
|
||||
if (n <= 1 || hi_mv <= lo_mv) return 0;
|
||||
if (prev >= n) prev = n - 1;
|
||||
|
||||
const uint32_t span = (uint32_t)hi_mv - lo_mv;
|
||||
uint8_t lvl = prev;
|
||||
|
||||
// The boundary into level k sits at lo + k*span/n, for k = 1..n-1.
|
||||
while (lvl + 1 < n) {
|
||||
uint32_t edge = lo_mv + (uint32_t)(lvl + 1) * span / n;
|
||||
if ((uint32_t)mv >= edge + hyst_mv) lvl++; else break;
|
||||
}
|
||||
while (lvl > 0) {
|
||||
uint32_t edge = lo_mv + (uint32_t)lvl * span / n;
|
||||
if ((uint32_t)mv < edge) lvl--; else break;
|
||||
}
|
||||
return lvl;
|
||||
}
|
||||
|
||||
// On sampling: one analogRead per decision is deliberate, and it is the same
|
||||
// call that feeds the battery metric (simple_repeater/MyMesh.cpp:482 for
|
||||
// stats, :510 for telemetry). There is no smoothed copy of the voltage
|
||||
// anywhere in the firmware to prefer instead -- what looks steady in Grafana
|
||||
// is steady because the cell is.
|
||||
//
|
||||
// A cell-less XIAO on USB reads bimodally -- measured over 20 reads on x4:
|
||||
// 4160 3760 4160 3760 4140 4150 3750 ... two levels ~390 mV apart, alternating
|
||||
// roughly 50/50. A median over five samples was tried and does NOT help
|
||||
// (spread 420 mV raw vs 380 mV median): it is not an outlier to reject, it is
|
||||
// VBAT floating against the charger with nothing to clamp it.
|
||||
//
|
||||
// It is also not what a deployed node sees. mast-repeater-one, with a real
|
||||
// cell, holds a max-min spread of 0-22 mV over 10-minute windows (queried
|
||||
// from Prometheus). Against a 112 mV step and 50 mV of hysteresis that is
|
||||
// quiet, so the noise is a property of the bench, not of the firmware.
|
||||
// A bench board without a cell WILL step around; that is expected.
|
||||
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
#pragma once
|
||||
|
||||
// CUSTOM (TeTeHacko): the two decisions behind `filter hash add <hex> [secs]`
|
||||
// (throttle a channel byte instead of muting it) and `filter age <min>|off`
|
||||
// (refuse to re-air group texts stamped long ago). Header-only and free of
|
||||
// mesh/Arduino types so both run in the native tests; the glue that feeds them
|
||||
// packets lives in examples/simple_repeater/ChannelFilter.h. Issue tth #3.
|
||||
//
|
||||
// Both ideas come from DutchMeshCore (`filter sender add <name> [secs]`,
|
||||
// 18341f13; `filter age`, 89dbb2bd). Behaviour follows theirs where it matters:
|
||||
// an over-rate message does not extend the throttle window, the first match
|
||||
// after a reboot is a free pass (state is RAM only), the age limit is inactive
|
||||
// while the repeater clock is unset, and a message stamped in the future is
|
||||
// never old.
|
||||
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
#define HASH_THROTTLE_SLOTS 8 // = sizeof(NodePrefs::deny_hash)
|
||||
|
||||
// One throttle per deny-list slot. Slots follow the prefs list order, so the
|
||||
// caller must remove() when it deletes an entry, or later entries would
|
||||
// inherit the wrong window.
|
||||
class HashThrottle {
|
||||
uint32_t _last_ms[HASH_THROTTLE_SLOTS];
|
||||
uint8_t _armed[HASH_THROTTLE_SLOTS]; // 0 = nothing passed since boot/reset
|
||||
|
||||
public:
|
||||
HashThrottle() { reset(); }
|
||||
|
||||
void reset() {
|
||||
memset(_last_ms, 0, sizeof(_last_ms));
|
||||
memset(_armed, 0, sizeof(_armed));
|
||||
}
|
||||
|
||||
void reset(int slot) {
|
||||
if (slot < 0 || slot >= HASH_THROTTLE_SLOTS) return;
|
||||
_last_ms[slot] = 0;
|
||||
_armed[slot] = 0;
|
||||
}
|
||||
|
||||
// Close the gap after the prefs list dropped `slot` (entries above shift down).
|
||||
void remove(int slot) {
|
||||
if (slot < 0 || slot >= HASH_THROTTLE_SLOTS) return;
|
||||
for (int i = slot; i + 1 < HASH_THROTTLE_SLOTS; i++) {
|
||||
_last_ms[i] = _last_ms[i + 1];
|
||||
_armed[i] = _armed[i + 1];
|
||||
}
|
||||
reset(HASH_THROTTLE_SLOTS - 1);
|
||||
}
|
||||
|
||||
// true = this packet may be forwarded. secs 0 = blocked outright. Only a
|
||||
// pass moves the window, so a sender pushing hard still gets exactly one
|
||||
// message per `secs`. Unsigned subtraction survives the millis() wrap.
|
||||
bool pass(int slot, uint16_t secs, uint32_t now_ms) {
|
||||
if (secs == 0 || slot < 0 || slot >= HASH_THROTTLE_SLOTS) return false;
|
||||
if (_armed[slot] && (uint32_t)(now_ms - _last_ms[slot]) < (uint32_t)secs * 1000u) return false;
|
||||
_armed[slot] = 1;
|
||||
_last_ms[slot] = now_ms;
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
// A repeater without RTC or GPS boots at 15 May 2024 (VolatileRTCClock) and
|
||||
// would call every live message old. Anything before 2026-01-01 = clock unset.
|
||||
#define MSG_AGE_CLOCK_VALID_FROM 1767225600UL
|
||||
#define MSG_AGE_MAX_MINUTES 10080 // one week, as in DMC
|
||||
|
||||
enum MsgAgeVerdict {
|
||||
MSG_AGE_OFF, // limit not set
|
||||
MSG_AGE_CLOCK_UNSET, // limit set, but our clock cannot be trusted -> pass
|
||||
MSG_AGE_FRESH,
|
||||
MSG_AGE_OLD,
|
||||
};
|
||||
|
||||
// sender_ts is the 4-byte timestamp at the start of a decrypted group text.
|
||||
// It is the SENDER's clock: a companion running behind looks "old" here, which
|
||||
// is why the limit is opt-in and meant to be generous (days, not minutes).
|
||||
inline MsgAgeVerdict msgAgeCheck(uint32_t sender_ts, uint32_t now, uint16_t max_minutes) {
|
||||
if (max_minutes == 0) return MSG_AGE_OFF;
|
||||
if (now < MSG_AGE_CLOCK_VALID_FROM) return MSG_AGE_CLOCK_UNSET;
|
||||
if (sender_ts >= now) return MSG_AGE_FRESH;
|
||||
return (now - sender_ts > (uint32_t)max_minutes * 60u) ? MSG_AGE_OLD : MSG_AGE_FRESH;
|
||||
}
|
||||
@@ -50,6 +50,125 @@ void ClientACL::load(FILESYSTEM* fs, const mesh::LocalIdentity& self_id) {
|
||||
file.close();
|
||||
}
|
||||
}
|
||||
loadTimestamps();
|
||||
}
|
||||
|
||||
// CUSTOM (TeTeHacko): /s_acl_ts0 and /s_acl_ts1 are written alternately, each
|
||||
// {pubkey prefix 8, timestamp 4} * n + seq 4 + sha256 tag 4. A write torn by a
|
||||
// power cut leaves the other slot intact, and the floor is the max over both
|
||||
// valid slots, so it can only ever move forward. The next write always goes over
|
||||
// the OLDER slot (lower seq) -- and a torn write means the command it guarded
|
||||
// never ran, so nothing executed is lost.
|
||||
#define ACL_TS_PREFIX 8
|
||||
#define ACL_TS_RECORD (ACL_TS_PREFIX + 4)
|
||||
|
||||
static const char* tsFilename(uint8_t slot) { return slot ? "/s_acl_ts1" : "/s_acl_ts0"; }
|
||||
|
||||
void ClientACL::loadTimestamps() {
|
||||
static uint8_t buf[2 * MAX_CLIENTS * ACL_TS_RECORD + 8];
|
||||
_num_ts_orphans = 0;
|
||||
_ts_seq = 0;
|
||||
_ts_slot = 0;
|
||||
bool have_newest = false;
|
||||
for (uint8_t slot = 0; slot < 2; slot++) {
|
||||
if (!_fs->exists(tsFilename(slot))) continue;
|
||||
#if defined(RP2040_PLATFORM)
|
||||
File file = _fs->open(tsFilename(slot), "r");
|
||||
#else
|
||||
File file = _fs->open(tsFilename(slot));
|
||||
#endif
|
||||
if (!file) continue;
|
||||
int len = file.read(buf, sizeof(buf));
|
||||
file.close();
|
||||
if (len < 8 || (len - 8) % ACL_TS_RECORD != 0) continue;
|
||||
|
||||
uint8_t tag[4];
|
||||
mesh::Utils::sha256(tag, 4, buf, len - 4);
|
||||
if (memcmp(tag, &buf[len - 4], 4) != 0) continue; // torn write: ignore this slot
|
||||
uint32_t seq;
|
||||
memcpy(&seq, &buf[len - 8], 4);
|
||||
if (!have_newest || seq > _ts_seq) {
|
||||
_ts_seq = seq;
|
||||
_ts_slot = slot ^ 1; // next write goes over the other, older slot
|
||||
have_newest = true;
|
||||
}
|
||||
|
||||
for (int ofs = 0; ofs < len - 8; ofs += ACL_TS_RECORD) {
|
||||
uint32_t ts;
|
||||
memcpy(&ts, &buf[ofs + ACL_TS_PREFIX], 4);
|
||||
ClientInfo* c = getClient(&buf[ofs], ACL_TS_PREFIX);
|
||||
if (c) {
|
||||
if (ts > c->saved_timestamp) c->saved_timestamp = ts;
|
||||
continue;
|
||||
}
|
||||
// Not in /s_contacts: a fresh login whose lazy ACL write a reboot beat, or an
|
||||
// evicted guest. Keep the floor, or replaying their login would re-admit them.
|
||||
int j = 0;
|
||||
while (j < _num_ts_orphans && memcmp(_ts_orphans[j].prefix, &buf[ofs], ACL_TS_PREFIX) != 0) j++;
|
||||
if (j == _num_ts_orphans) {
|
||||
if (j == MAX_CLIENTS) continue;
|
||||
memcpy(_ts_orphans[j].prefix, &buf[ofs], ACL_TS_PREFIX);
|
||||
_ts_orphans[j].ts = 0;
|
||||
_num_ts_orphans++;
|
||||
}
|
||||
if (ts > _ts_orphans[j].ts) _ts_orphans[j].ts = ts;
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < num_clients; i++) {
|
||||
clients[i].last_timestamp = clients[i].saved_timestamp;
|
||||
}
|
||||
}
|
||||
|
||||
void ClientACL::saveTimestamps() {
|
||||
if (!_fs) return;
|
||||
static uint8_t buf[2 * MAX_CLIENTS * ACL_TS_RECORD + 8];
|
||||
int len = 0;
|
||||
for (int i = 0; i < num_clients; i++) {
|
||||
if (clients[i].saved_timestamp == 0) continue;
|
||||
memcpy(&buf[len], clients[i].id.pub_key, ACL_TS_PREFIX);
|
||||
memcpy(&buf[len + ACL_TS_PREFIX], &clients[i].saved_timestamp, 4);
|
||||
len += ACL_TS_RECORD;
|
||||
}
|
||||
for (int i = 0; i < _num_ts_orphans; i++) {
|
||||
memcpy(&buf[len], _ts_orphans[i].prefix, ACL_TS_PREFIX);
|
||||
memcpy(&buf[len + ACL_TS_PREFIX], &_ts_orphans[i].ts, 4);
|
||||
len += ACL_TS_RECORD;
|
||||
}
|
||||
_ts_seq++;
|
||||
memcpy(&buf[len], &_ts_seq, 4);
|
||||
len += 4;
|
||||
mesh::Utils::sha256(&buf[len], 4, buf, len);
|
||||
len += 4;
|
||||
|
||||
File file = openWrite(_fs, tsFilename(_ts_slot));
|
||||
if (file) {
|
||||
file.write(buf, len);
|
||||
file.close();
|
||||
}
|
||||
_ts_slot ^= 1;
|
||||
}
|
||||
|
||||
void ClientACL::orphanTimestamp(const ClientInfo* c) {
|
||||
if (c->saved_timestamp == 0) return;
|
||||
if (_num_ts_orphans == MAX_CLIENTS) { // full: drop the oldest
|
||||
memmove(&_ts_orphans[0], &_ts_orphans[1], (MAX_CLIENTS - 1) * sizeof(TsOrphan));
|
||||
_num_ts_orphans--;
|
||||
}
|
||||
memcpy(_ts_orphans[_num_ts_orphans].prefix, c->id.pub_key, ACL_TS_PREFIX);
|
||||
_ts_orphans[_num_ts_orphans].ts = c->saved_timestamp;
|
||||
_num_ts_orphans++;
|
||||
}
|
||||
|
||||
void ClientACL::persistTimestamp(ClientInfo* c, uint32_t sender_timestamp, uint32_t now) {
|
||||
// Admins only. A guest can only read, and anybody gets in as one when the
|
||||
// guest password is empty (the default): its every request would be a flash
|
||||
// write, and its floors would push the admins' out of the orphan list. Its
|
||||
// floor stays in RAM, as upstream.
|
||||
if (!c->isAdmin()) return;
|
||||
if (sender_timestamp <= c->saved_timestamp) return; // retry, or nothing new
|
||||
if (sender_timestamp > now + ACL_TS_MAX_AHEAD) return; // runaway sender clock
|
||||
c->saved_timestamp = sender_timestamp;
|
||||
saveTimestamps();
|
||||
}
|
||||
|
||||
void ClientACL::save(FILESYSTEM* fs, bool (*filter)(ClientInfo*)) {
|
||||
@@ -82,8 +201,12 @@ bool ClientACL::clear() {
|
||||
if (_fs->exists("/s_contacts")) {
|
||||
_fs->remove("/s_contacts");
|
||||
}
|
||||
// The replay floors outlive the ACL: with them gone, a captured password login
|
||||
// would be accepted again.
|
||||
for (int i = 0; i < num_clients; i++) orphanTimestamp(&clients[i]);
|
||||
memset(clients, 0, sizeof(clients));
|
||||
num_clients = 0;
|
||||
saveTimestamps();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -110,11 +233,20 @@ ClientInfo* ClientACL::putClient(const mesh::Identity& id, uint8_t init_perms) {
|
||||
c = &clients[num_clients++];
|
||||
} else {
|
||||
c = oldest; // evict least active contact
|
||||
orphanTimestamp(c);
|
||||
}
|
||||
memset(c, 0, sizeof(*c));
|
||||
c->permissions = init_perms;
|
||||
c->id = id;
|
||||
c->out_path_len = OUT_PATH_UNKNOWN;
|
||||
for (int i = 0; i < _num_ts_orphans; i++) { // known before: its replay floor comes back
|
||||
if (memcmp(_ts_orphans[i].prefix, id.pub_key, ACL_TS_PREFIX) == 0) {
|
||||
c->saved_timestamp = c->last_timestamp = _ts_orphans[i].ts;
|
||||
_num_ts_orphans--;
|
||||
memmove(&_ts_orphans[i], &_ts_orphans[i + 1], (_num_ts_orphans - i) * sizeof(TsOrphan));
|
||||
break;
|
||||
}
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
@@ -124,6 +256,7 @@ bool ClientACL::applyPermissions(const mesh::LocalIdentity& self_id, const uint8
|
||||
c = getClient(pubkey, key_len);
|
||||
if (c == NULL) return false; // partial pubkey not found
|
||||
|
||||
orphanTimestamp(c);
|
||||
num_clients--; // delete from contacts[]
|
||||
int i = c - clients;
|
||||
while (i < num_clients) {
|
||||
|
||||
+36
-2
@@ -18,7 +18,8 @@ struct ClientInfo {
|
||||
uint8_t out_path_len;
|
||||
uint8_t out_path[MAX_PATH_SIZE];
|
||||
uint8_t shared_secret[PUB_KEY_SIZE];
|
||||
uint32_t last_timestamp; // by THEIR clock (transient)
|
||||
uint32_t last_timestamp; // by THEIR clock (restored from /s_acl_ts* on boot)
|
||||
uint32_t saved_timestamp; // last_timestamp as last written to /s_acl_ts*
|
||||
uint32_t last_activity; // by OUR clock (transient)
|
||||
union {
|
||||
struct {
|
||||
@@ -28,29 +29,62 @@ struct ClientInfo {
|
||||
unsigned long ack_timeout;
|
||||
uint8_t push_failures;
|
||||
} room;
|
||||
struct {
|
||||
uint32_t expiry_timestamp; // epoch seconds
|
||||
uint32_t push_tag;
|
||||
uint16_t scope_region_id; // scope to use when sending telemetry to this client/subscriber
|
||||
uint8_t min_deltas_len;
|
||||
uint8_t min_deltas[14]; // LPP encoded
|
||||
uint8_t prev_telem[14]; // LPP encoded
|
||||
} sensor;
|
||||
} extra;
|
||||
|
||||
bool isAdmin() const { return (permissions & PERM_ACL_ROLE_MASK) == PERM_ACL_ADMIN; }
|
||||
};
|
||||
|
||||
#ifndef MAX_CLIENTS
|
||||
#define MAX_CLIENTS 20
|
||||
#define MAX_CLIENTS 32
|
||||
#endif
|
||||
|
||||
// CUSTOM (TeTeHacko): a timestamp further ahead of our clock than this is accepted
|
||||
// but not persisted, so a companion with a runaway RTC cannot lock its admin out
|
||||
// across reboots.
|
||||
#ifndef ACL_TS_MAX_AHEAD
|
||||
#define ACL_TS_MAX_AHEAD (24 * 3600)
|
||||
#endif
|
||||
|
||||
class ClientACL {
|
||||
FILESYSTEM* _fs;
|
||||
ClientInfo clients[MAX_CLIENTS];
|
||||
int num_clients;
|
||||
uint8_t _ts_slot;
|
||||
uint32_t _ts_seq;
|
||||
struct TsOrphan { uint8_t prefix[8]; uint32_t ts; };
|
||||
TsOrphan _ts_orphans[MAX_CLIENTS]; // floors of clients not (or no longer) in clients[]
|
||||
int _num_ts_orphans;
|
||||
|
||||
void loadTimestamps();
|
||||
void saveTimestamps();
|
||||
void orphanTimestamp(const ClientInfo* c);
|
||||
|
||||
public:
|
||||
ClientACL() {
|
||||
memset(clients, 0, sizeof(clients));
|
||||
num_clients = 0;
|
||||
_ts_slot = 0;
|
||||
_ts_seq = 0;
|
||||
_num_ts_orphans = 0;
|
||||
}
|
||||
void load(FILESYSTEM* _fs, const mesh::LocalIdentity& self_id);
|
||||
void save(FILESYSTEM* _fs, bool (*filter)(ClientInfo*)=NULL);
|
||||
bool clear();
|
||||
|
||||
// CUSTOM (TeTeHacko): replay protection that survives a reboot. last_timestamp
|
||||
// used to live only in RAM, so after any reboot a captured command (a `reboot`
|
||||
// among them) was accepted again -- forever. Call this BEFORE acting on an
|
||||
// authenticated packet; it writes the new high-water mark synchronously.
|
||||
void persistTimestamp(ClientInfo* c, uint32_t sender_timestamp, uint32_t now);
|
||||
|
||||
ClientInfo* getClient(const uint8_t* pubkey, int key_len);
|
||||
ClientInfo* putClient(const mesh::Identity& id, uint8_t init_perms);
|
||||
bool applyPermissions(const mesh::LocalIdentity& self_id, const uint8_t* pubkey, int key_len, uint8_t perms);
|
||||
|
||||
+406
-258
@@ -2,13 +2,21 @@
|
||||
#include "CommonCLI.h"
|
||||
#include "TxtDataHelpers.h"
|
||||
#include "AdvertDataHelpers.h"
|
||||
#include "BatteryIcon.h"
|
||||
#include "TxtDataHelpers.h"
|
||||
#include <RTClib.h>
|
||||
#include <CayenneLPP.h>
|
||||
|
||||
#ifndef BRIDGE_MAX_BAUD
|
||||
#define BRIDGE_MAX_BAUD 115200
|
||||
#endif
|
||||
|
||||
// CUSTOM (TeTeHacko): defined by apps that keep the wall clock in retained RAM
|
||||
// across a soft reset (examples/simple_repeater/main.cpp). Weak, so every build
|
||||
// that does not links fine and the pointer is simply NULL. `clkreboot` has to
|
||||
// clear that record or it would undo itself -- see the call site below.
|
||||
extern "C" void retainedClockInvalidate() __attribute__((weak));
|
||||
|
||||
// Believe it or not, this std C function is busted on some platforms!
|
||||
static uint32_t _atoi(const char* sp) {
|
||||
uint32_t n = 0;
|
||||
@@ -127,7 +135,7 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) { // Legacy
|
||||
|
||||
_prefs->powersaving_enabled = constrain(_prefs->powersaving_enabled, 0, 1);
|
||||
|
||||
_prefs->gps_enabled = constrain(_prefs->gps_enabled, 0, 1);
|
||||
_prefs->gps_enabled = constrain(_prefs->gps_enabled, 0, 2); // 0 off, 1 on, 2 duty cycle
|
||||
_prefs->advert_loc_policy = constrain(_prefs->advert_loc_policy, 0, 2);
|
||||
|
||||
// sanitise settings
|
||||
@@ -164,29 +172,124 @@ void CommonCLI::savePrefs() {
|
||||
_prefs->advert_interval = 0; // turn it off, now that device has been manually configured
|
||||
}
|
||||
_callbacks->savePrefs();
|
||||
_prefs->clearDirty();
|
||||
}
|
||||
|
||||
// Rozpočet na jméno pro současné nastavení advertu. Staví prázdný builder
|
||||
// a ptá se JEHO, ať `set`, `get` i samotný advert počítají z jednoho místa --
|
||||
// druhá kopie toho výpočtu už jednou zapomněla na FEAT1/FEAT2.
|
||||
size_t CommonCLI::nameBudget() const {
|
||||
if (_prefs->advert_loc_policy == ADVERT_LOC_NONE) {
|
||||
return AdvertDataBuilder(ADV_TYPE_NONE).nameBudget();
|
||||
}
|
||||
return AdvertDataBuilder(ADV_TYPE_NONE, NULL, 0.0, 0.0).nameBudget();
|
||||
}
|
||||
|
||||
// Name as it goes on the air: the configured name, plus the solar marker and
|
||||
// either a charge level or the external-power glyph. Returns the bare name in
|
||||
// every other case -- an indicator that does not fit is dropped whole rather
|
||||
// than letting the UTF-8 clamp eat half of it silently.
|
||||
const char* CommonCLI::advertName(size_t budget) {
|
||||
if (!_prefs->batt_icon) return _prefs->node_name;
|
||||
|
||||
size_t nlen = strlen(_prefs->node_name);
|
||||
if (!mesh::battIconFits(nlen, budget)) return _prefs->node_name;
|
||||
|
||||
char glyph[8];
|
||||
if (_board->isExternalPowered()) {
|
||||
// On USB the cell (if any) is being charged and VBAT reads the charger,
|
||||
// not the battery -- a level drawn from it would be fiction.
|
||||
StrHelper::strncpy(glyph, BATT_ICON_EXTERNAL, sizeof(glyph));
|
||||
} else {
|
||||
uint16_t mv = _board->getBattMilliVolts();
|
||||
if (mv == 0) return _prefs->node_name; // board has no battery sense
|
||||
uint16_t lo = _prefs->batt_icon_lo ? _prefs->batt_icon_lo : BATT_ICON_LO_MV;
|
||||
uint16_t hi = _prefs->batt_icon_hi ? _prefs->batt_icon_hi : BATT_ICON_HI_MV;
|
||||
_batt_level = mesh::battIconLevel(_batt_level, mv, lo, hi,
|
||||
mesh::battIconLevels(), BATT_ICON_HYST_MV);
|
||||
mesh::battIconGlyph(glyph, _batt_level);
|
||||
}
|
||||
|
||||
StrHelper::strncpy(_adv_name, _prefs->node_name, sizeof(_adv_name));
|
||||
strncat(_adv_name, BATT_ICON_MARKER, sizeof(_adv_name) - strlen(_adv_name) - 1);
|
||||
strncat(_adv_name, glyph, sizeof(_adv_name) - strlen(_adv_name) - 1);
|
||||
return _adv_name;
|
||||
}
|
||||
|
||||
uint8_t CommonCLI::buildAdvertData(uint8_t node_type, uint8_t* app_data) {
|
||||
// Builder se postaví bez jména, protože rozpočet na jméno závisí na tom, co
|
||||
// v něm už je (poloha, případné FEAT). Teprve pak se jméno doplní -- jinak
|
||||
// by se remainder musel počítat podruhé jinde a rozejít se s encodeTo().
|
||||
if (_prefs->advert_loc_policy == ADVERT_LOC_NONE) {
|
||||
AdvertDataBuilder builder(node_type, _prefs->node_name);
|
||||
AdvertDataBuilder builder(node_type);
|
||||
builder.setName(advertName(builder.nameBudget()));
|
||||
return builder.encodeTo(app_data);
|
||||
} else if (_prefs->advert_loc_policy == ADVERT_LOC_SHARE) {
|
||||
AdvertDataBuilder builder(node_type, _prefs->node_name, _sensors->node_lat, _sensors->node_lon);
|
||||
AdvertDataBuilder builder(node_type, NULL, _sensors->node_lat, _sensors->node_lon);
|
||||
builder.setName(advertName(builder.nameBudget()));
|
||||
return builder.encodeTo(app_data);
|
||||
} else {
|
||||
AdvertDataBuilder builder(node_type, _prefs->node_name, _prefs->node_lat, _prefs->node_lon);
|
||||
AdvertDataBuilder builder(node_type, NULL, _prefs->node_lat, _prefs->node_lon);
|
||||
builder.setName(advertName(builder.nameBudget()));
|
||||
return builder.encodeTo(app_data);
|
||||
}
|
||||
}
|
||||
|
||||
// CayenneLPP data-payload size (bytes) for a given type; -1 if unknown.
|
||||
// Lets `sensor read` skip a field it doesn't surface without losing sync
|
||||
// (silently dropping the rest of the buffer).
|
||||
static int cayenne_lpp_size(uint8_t type) {
|
||||
switch (type) {
|
||||
case LPP_DIGITAL_INPUT: case LPP_DIGITAL_OUTPUT: case LPP_PRESENCE:
|
||||
case LPP_RELATIVE_HUMIDITY: case LPP_PERCENTAGE: case LPP_SWITCH:
|
||||
return 1;
|
||||
case LPP_ANALOG_INPUT: case LPP_ANALOG_OUTPUT: case LPP_LUMINOSITY:
|
||||
case LPP_TEMPERATURE: case LPP_BAROMETRIC_PRESSURE: case LPP_VOLTAGE:
|
||||
case LPP_CURRENT: case LPP_ALTITUDE: case LPP_CONCENTRATION:
|
||||
case LPP_POWER: case LPP_DIRECTION:
|
||||
return 2;
|
||||
case LPP_COLOUR:
|
||||
return 3;
|
||||
case LPP_GENERIC_SENSOR: case LPP_FREQUENCY: case LPP_DISTANCE:
|
||||
case LPP_ENERGY: case LPP_UNIXTIME:
|
||||
return 4;
|
||||
case LPP_ACCELEROMETER: case LPP_GYROMETER:
|
||||
return 6;
|
||||
case LPP_GPS:
|
||||
return LPP_GPS_SIZE;
|
||||
default:
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* reply) {
|
||||
if (_prefs->getRadioPrefs()->handleCommand(command, sender_timestamp, reply)) { // is a radio CLI command?
|
||||
if (_prefs->getRadioPrefs()->isDirty()) { savePrefs(); }
|
||||
return;
|
||||
}
|
||||
// hook for variant-specific CLI processing
|
||||
if (_board->handleCommand(command, sender_timestamp, reply)) {
|
||||
if (_prefs->isDirty()) { savePrefs(); }
|
||||
return;
|
||||
}
|
||||
|
||||
if (memcmp(command, "poweroff", 8) == 0 || memcmp(command, "shutdown", 8) == 0) {
|
||||
_board->powerOff(); // doesn't return
|
||||
} else if (memcmp(command, "reboot", 6) == 0) {
|
||||
_board->reboot(); // doesn't return
|
||||
} else if (memcmp(command, "clkreboot", 9) == 0) {
|
||||
// Reset clock
|
||||
getRTCClock()->setCurrentTime(1715770351); // 15 May 2024, 8:50pm
|
||||
// Reset clock. On a volatile clock this write is redundant -- the reboot
|
||||
// re-runs the constructor, which seeds the same value -- but on a battery
|
||||
// backed I2C RTC it really does rewrite the chip, so it must not put the
|
||||
// year 2024 there. This is also the ONLY way to move a clock BACKWARDS:
|
||||
// `time` and `clock sync` both refuse to, so an over-set clock can only be
|
||||
// fixed by resetting it here and setting it again.
|
||||
//
|
||||
// The retained-RAM copy has to die with it. Otherwise the reboot restores
|
||||
// the very value being thrown away here, and the command silently does
|
||||
// nothing on exactly the nodes that keep their clock across a reset.
|
||||
if (retainedClockInvalidate) retainedClockInvalidate();
|
||||
getRTCClock()->setCurrentTime(FIRMWARE_BUILD_EPOCH);
|
||||
_board->reboot(); // doesn't return
|
||||
} else if (memcmp(command, "advert.zerohop", 14) == 0 && (command[14] == 0 || command[14] == ' ')) {
|
||||
// send zerohop advert
|
||||
@@ -200,6 +303,7 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
|
||||
uint32_t curr = getRTCClock()->getCurrentTime();
|
||||
if (sender_timestamp > curr) {
|
||||
getRTCClock()->setCurrentTime(sender_timestamp + 1);
|
||||
CommonGpsPrefs::onClockSetManually(*_sensors);
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
DateTime dt = DateTime(now);
|
||||
sprintf(reply, "OK - clock set: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
|
||||
@@ -213,12 +317,20 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
|
||||
} else if (memcmp(command, "clock", 5) == 0) {
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
DateTime dt = DateTime(now);
|
||||
sprintf(reply, "%02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
|
||||
// CUSTOM (TeTeHacko): the epoch goes on the end. The human part is minutes
|
||||
// only, so a host comparing its own clock against this one cannot see a
|
||||
// difference smaller than a minute -- meaning it cannot tell a node that is
|
||||
// 40 s out from one that is exact, and has to leave a >59 s deadband. The
|
||||
// epoch makes the comparison exact. Appended, so anything that only reads
|
||||
// or prints the reply is unaffected.
|
||||
sprintf(reply, "%02d:%02d - %d/%d/%d UTC (epoch %u)", dt.hour(), dt.minute(),
|
||||
dt.day(), dt.month(), dt.year(), (unsigned) now);
|
||||
} else if (memcmp(command, "time ", 5) == 0) { // set time (to epoch seconds)
|
||||
uint32_t secs = _atoi(&command[5]);
|
||||
uint32_t curr = getRTCClock()->getCurrentTime();
|
||||
if (secs > curr) {
|
||||
getRTCClock()->setCurrentTime(secs);
|
||||
CommonGpsPrefs::onClockSetManually(*_sensors);
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
DateTime dt = DateTime(now);
|
||||
sprintf(reply, "OK - clock set: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
|
||||
@@ -239,7 +351,7 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
|
||||
strcpy(reply, "ERR: bad pubkey");
|
||||
}
|
||||
} else if (memcmp(command, "tempradio ", 10) == 0) {
|
||||
strcpy(tmp, &command[10]);
|
||||
StrHelper::strncpy(tmp, &command[10], sizeof(tmp));
|
||||
const char *parts[5];
|
||||
int num = mesh::Utils::parseTextParts(tmp, parts, 5);
|
||||
float freq = num > 0 ? strtof(parts[0], nullptr) : 0.0f;
|
||||
@@ -273,6 +385,19 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
|
||||
sprintf(reply, "%s (Build: %s)", _callbacks->getFirmwareVer(), _callbacks->getBuildDate());
|
||||
} else if (memcmp(command, "board", 5) == 0) {
|
||||
sprintf(reply, "%s", _board->getManufacturerName());
|
||||
} else if (strcmp(command, "power") == 0) {
|
||||
const char* usb_state = _board->hasUsbPowerDetect()
|
||||
? (_board->isUsbPowered() ? "yes" : "no")
|
||||
: "n/a";
|
||||
const char* solar_state = _board->hasSolarChargerDetect()
|
||||
? (_board->isSolarChargerActive() ? "yes" : "no")
|
||||
: "n/a";
|
||||
snprintf(reply, 160, "batt:%u mV usb:%s solar_chg:%s ext:%s charger:%s",
|
||||
(unsigned)_board->getBattMilliVolts(),
|
||||
usb_state,
|
||||
solar_state,
|
||||
_board->isExternalPowered() ? "yes" : "no",
|
||||
_board->isChargerActive() ? "yes" : "no");
|
||||
} else if (memcmp(command, "sensor get ", 11) == 0) {
|
||||
const char* key = command + 11;
|
||||
const char* val = _sensors->getSettingByKey(key);
|
||||
@@ -282,12 +407,16 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
|
||||
strcpy(reply, "null");
|
||||
}
|
||||
} else if (memcmp(command, "sensor set ", 11) == 0) {
|
||||
strcpy(tmp, &command[11]);
|
||||
StrHelper::strncpy(tmp, &command[11], sizeof(tmp));
|
||||
const char *parts[2];
|
||||
int num = mesh::Utils::parseTextParts(tmp, parts, 2, ' ');
|
||||
const char *key = (num > 0) ? parts[0] : "";
|
||||
const char *value = (num > 1) ? parts[1] : "null";
|
||||
if (_sensors->setSettingValue(key, value)) {
|
||||
if (strcmp(key, "ina.shunt") == 0) { // CUSTOM (TeTeHacko): survives a reboot
|
||||
_prefs->ina_shunt_mohm = atof(value);
|
||||
savePrefs();
|
||||
}
|
||||
strcpy(reply, "ok");
|
||||
} else {
|
||||
strcpy(reply, "can't find custom var");
|
||||
@@ -302,53 +431,148 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
|
||||
if (start >= end) {
|
||||
strcpy(reply, "no custom var");
|
||||
} else {
|
||||
const int reply_max = 160; // callers pass a 160-byte reply buffer
|
||||
const int next_reserve = 16; // room for "... next:NNN"
|
||||
sprintf(dp, "%d vars\n", end);
|
||||
dp = strchr(dp, 0);
|
||||
int i;
|
||||
for (i = start; i < end && (dp-reply < 134); i++) {
|
||||
sprintf(dp, "%s=%s\n",
|
||||
_sensors->getSettingName(i),
|
||||
_sensors->getSettingValue(i));
|
||||
for (i = start; i < end; i++) {
|
||||
const char* name = _sensors->getSettingName(i);
|
||||
const char* value = _sensors->getSettingValue(i);
|
||||
if (name == NULL) name = "?";
|
||||
if (value == NULL) value = "";
|
||||
int room = reply_max - next_reserve - (int)(dp - reply);
|
||||
int need = snprintf(NULL, 0, "%s=%s\n", name, value);
|
||||
if (need >= room && i > start) break; // continue on the next page
|
||||
snprintf(dp, room, "%s=%s\n", name, value); // a single oversized entry is truncated
|
||||
dp = strchr(dp, 0);
|
||||
if (need >= room) { i++; break; }
|
||||
}
|
||||
if (i < end) {
|
||||
sprintf(dp, "... next:%d", i);
|
||||
} else {
|
||||
snprintf(dp, reply_max - (int)(dp - reply), "... next:%d", i);
|
||||
} else if (dp > reply && *(dp-1) == '\n') {
|
||||
*(dp-1) = 0; // remove last CR
|
||||
}
|
||||
}
|
||||
} else if (memcmp(command, "i2c", 3) == 0) {
|
||||
// Live bus scan. `sensor read` only shows what got initialised, so a
|
||||
// sensor that is absent and one whose address is wrong look identical
|
||||
// there; this separates the two.
|
||||
// 150 = what one LoRa packet carries, i.e. the smallest reply buffer any
|
||||
// caller of CommonCLI passes (the local console's is far bigger, but
|
||||
// CommonCLI is not told which one it got).
|
||||
int n = _sensors->scanI2C(reply, 150);
|
||||
if (n < 0) strcpy(reply, "no I2C bus on this build");
|
||||
} else if (memcmp(command, "sensor read", 11) == 0) {
|
||||
// Decode the live telemetry (the same CayenneLPP payload sent over the
|
||||
// mesh) into a human-readable line. `sensor list` only exposes settings
|
||||
// (e.g. gps on/off), never the measured values; this lets a console or
|
||||
// bridge pull temperature, humidity, voltage, etc. as plain text.
|
||||
CayenneLPP lpp(128);
|
||||
lpp.reset();
|
||||
// Mirror the node's own mesh telemetry so `sensor read` reflects reality:
|
||||
// battery voltage + attached I2C sensors + built-in MCU temperature. Note
|
||||
// the two temperatures (ambient sensor vs MCU) sit on different LPP
|
||||
// channels, so each field below is keyed by channel to keep them distinct.
|
||||
lpp.addVoltage(TELEM_CHANNEL_SELF, _board->getBattMilliVolts() / 1000.0f);
|
||||
_sensors->querySensors(0xFF, lpp);
|
||||
float mcu_temp = _board->getMCUTemperature();
|
||||
if (!isnan(mcu_temp)) lpp.addTemperature(TELEM_CHANNEL_SELF, mcu_temp);
|
||||
|
||||
const uint8_t* b = lpp.getBuffer();
|
||||
int sz = lpp.getSize();
|
||||
const int CAP = 158; // reply buffer is ~160 bytes on all callers
|
||||
char* dp = reply;
|
||||
*dp = 0;
|
||||
int k = 0;
|
||||
while (k + 2 <= sz && (CAP - (int)(dp - reply)) > 44) {
|
||||
uint8_t ch = b[k];
|
||||
uint8_t type = b[k + 1];
|
||||
int dsz = cayenne_lpp_size(type);
|
||||
if (dsz < 0 || k + 2 + dsz > sz) break; // unknown type / truncated -> stop cleanly
|
||||
const uint8_t* d = &b[k + 2];
|
||||
int rem = CAP - (int)(dp - reply);
|
||||
switch (type) {
|
||||
case LPP_TEMPERATURE:
|
||||
snprintf(dp, rem, "temperature.%d=%s ", ch, StrHelper::ftoa((int16_t)((d[0]<<8)|d[1]) / 10.0f)); break;
|
||||
case LPP_RELATIVE_HUMIDITY:
|
||||
snprintf(dp, rem, "humidity.%d=%s ", ch, StrHelper::ftoa(d[0] / 2.0f)); break;
|
||||
case LPP_BAROMETRIC_PRESSURE:
|
||||
snprintf(dp, rem, "pressure.%d=%s ", ch, StrHelper::ftoa((uint16_t)((d[0]<<8)|d[1]) / 10.0f)); break;
|
||||
case LPP_VOLTAGE:
|
||||
snprintf(dp, rem, "voltage.%d=%s ", ch, StrHelper::ftoa((uint16_t)((d[0]<<8)|d[1]) / 100.0f)); break;
|
||||
case LPP_CURRENT:
|
||||
snprintf(dp, rem, "current.%d=%s ", ch, StrHelper::ftoa((uint16_t)((d[0]<<8)|d[1]) / 1000.0f)); break;
|
||||
case LPP_POWER:
|
||||
snprintf(dp, rem, "power.%d=%d ", ch, (int)(uint16_t)((d[0]<<8)|d[1])); break;
|
||||
case LPP_PERCENTAGE:
|
||||
snprintf(dp, rem, "percent.%d=%d ", ch, (int)d[0]); break;
|
||||
case LPP_ALTITUDE:
|
||||
snprintf(dp, rem, "altitude.%d=%d ", ch, (int)(int16_t)((d[0]<<8)|d[1])); break;
|
||||
case LPP_ANALOG_INPUT:
|
||||
snprintf(dp, rem, "analog.%d=%s ", ch, StrHelper::ftoa((int16_t)((d[0]<<8)|d[1]) / 100.0f)); break;
|
||||
case LPP_LUMINOSITY:
|
||||
snprintf(dp, rem, "lux.%d=%d ", ch, (int)(uint16_t)((d[0]<<8)|d[1])); break;
|
||||
case LPP_GPS: {
|
||||
int32_t lat = ((int32_t)d[0]<<16)|(d[1]<<8)|d[2];
|
||||
int32_t lon = ((int32_t)d[3]<<16)|(d[4]<<8)|d[5];
|
||||
int32_t alt = ((int32_t)d[6]<<16)|(d[7]<<8)|d[8];
|
||||
if (lat & 0x800000) lat |= 0xFF000000; // sign-extend 24-bit
|
||||
if (lon & 0x800000) lon |= 0xFF000000;
|
||||
if (alt & 0x800000) alt |= 0xFF000000;
|
||||
snprintf(dp, rem, "gps.%d=", ch); dp = strchr(dp, 0);
|
||||
snprintf(dp, CAP-(int)(dp-reply), "%s,", StrHelper::ftoa(lat / 10000.0f)); dp = strchr(dp, 0);
|
||||
snprintf(dp, CAP-(int)(dp-reply), "%s,", StrHelper::ftoa(lon / 10000.0f)); dp = strchr(dp, 0);
|
||||
snprintf(dp, CAP-(int)(dp-reply), "%s ", StrHelper::ftoa(alt / 100.0f)); break;
|
||||
}
|
||||
default: break; // known size but not surfaced -> skip (already advanced)
|
||||
}
|
||||
dp = strchr(dp, 0);
|
||||
k += 2 + dsz;
|
||||
}
|
||||
if (dp == reply) {
|
||||
strcpy(reply, "no telemetry");
|
||||
} else if (*(dp-1) == ' ') {
|
||||
*(dp-1) = 0; // trim trailing space
|
||||
}
|
||||
#if ENV_INCLUDE_GPS == 1
|
||||
} else if (memcmp(command, "gps duty", 8) == 0) {
|
||||
// Power GPS only around a clock sync. For a node that runs GPS purely for
|
||||
// the (volatile) RTC this is the same service at a fraction of the power;
|
||||
// position keeps coming from prefs, see `set advert.loc`. Duty owns the cadence,
|
||||
// so a `gps period` left over would fight it.
|
||||
if (_sensors->setSettingValue("gps", "2")) {
|
||||
_prefs->getGpsPrefs()->setGpsPeriod(*_sensors, 0);
|
||||
_prefs->gps_enabled = 2;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error, gps toggle not found");
|
||||
}
|
||||
} else if (strcmp(command, "gps") == 0 && _prefs->gps_enabled == 2) {
|
||||
// Duty cycle: the receiver is off most of the time BY DESIGN, so the
|
||||
// generic "on, inactive" would read as a dead GPS. Say which.
|
||||
LocationProvider * l = _sensors->getLocationProvider();
|
||||
if (l != NULL) {
|
||||
sprintf(reply, "> duty, %s, %s, %ld sats",
|
||||
l->isActive() ? "awake" : "asleep",
|
||||
l->hasValidFix() ? "fix" : "no fix",
|
||||
l->satellitesCount());
|
||||
} else {
|
||||
strcpy(reply, "Error, gps provider not found");
|
||||
}
|
||||
#endif
|
||||
} else if (_prefs->getGpsPrefs()->handleCommand(command, *_sensors, reply)) {
|
||||
if (_prefs->getGpsPrefs()->isDirty()) savePrefs();
|
||||
} else if (memcmp(command, "region", 6) == 0) {
|
||||
handleRegionCmd(command, reply);
|
||||
#if ENV_INCLUDE_GPS == 1
|
||||
} else if (memcmp(command, "gps on", 6) == 0) {
|
||||
if (_sensors->setSettingValue("gps", "1")) {
|
||||
_prefs->gps_enabled = 1;
|
||||
savePrefs();
|
||||
strcpy(reply, "ok");
|
||||
} else {
|
||||
strcpy(reply, "gps toggle not found");
|
||||
}
|
||||
} else if (memcmp(command, "gps off", 7) == 0) {
|
||||
if (_sensors->setSettingValue("gps", "0")) {
|
||||
_prefs->gps_enabled = 0;
|
||||
savePrefs();
|
||||
strcpy(reply, "ok");
|
||||
} else {
|
||||
strcpy(reply, "gps toggle not found");
|
||||
}
|
||||
} else if (memcmp(command, "gps sync", 8) == 0) {
|
||||
LocationProvider * l = _sensors->getLocationProvider();
|
||||
if (l != NULL) {
|
||||
l->syncTime();
|
||||
strcpy(reply, "ok");
|
||||
} else {
|
||||
strcpy(reply, "gps provider not found");
|
||||
}
|
||||
} else if (memcmp(command, "gps setloc", 10) == 0) {
|
||||
_prefs->node_lat = _sensors->node_lat;
|
||||
_prefs->node_lon = _sensors->node_lon;
|
||||
_prefs->getGpsPrefs()->applyGuardReference(*_sensors);
|
||||
savePrefs();
|
||||
strcpy(reply, "ok");
|
||||
strcpy(reply, "OK");
|
||||
} else if (memcmp(command, "gps advert", 10) == 0) {
|
||||
if (strlen(command) == 10) {
|
||||
switch (_prefs->advert_loc_policy) {
|
||||
@@ -362,40 +586,22 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
|
||||
strcpy(reply, "> share");
|
||||
break;
|
||||
default:
|
||||
strcpy(reply, "error");
|
||||
strcpy(reply, "Error, invalid policy");
|
||||
}
|
||||
} else if (memcmp(command+11, "none", 4) == 0) {
|
||||
_prefs->advert_loc_policy = ADVERT_LOC_NONE;
|
||||
savePrefs();
|
||||
strcpy(reply, "ok");
|
||||
strcpy(reply, "OK");
|
||||
} else if (memcmp(command+11, "share", 5) == 0) {
|
||||
_prefs->advert_loc_policy = ADVERT_LOC_SHARE;
|
||||
savePrefs();
|
||||
strcpy(reply, "ok");
|
||||
strcpy(reply, "OK");
|
||||
} else if (memcmp(command+11, "prefs", 5) == 0) {
|
||||
_prefs->advert_loc_policy = ADVERT_LOC_PREFS;
|
||||
savePrefs();
|
||||
strcpy(reply, "ok");
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "error");
|
||||
}
|
||||
} else if (memcmp(command, "gps", 3) == 0) {
|
||||
LocationProvider * l = _sensors->getLocationProvider();
|
||||
if (l != NULL) {
|
||||
bool enabled = l->isEnabled(); // is EN pin on ?
|
||||
bool fix = l->isValid(); // has fix ?
|
||||
int sats = l->satellitesCount();
|
||||
bool active = !strcmp(_sensors->getSettingByKey("gps"), "1");
|
||||
if (enabled) {
|
||||
sprintf(reply, "on, %s, %s, %d sats",
|
||||
active?"active":"deactivated",
|
||||
fix?"fix":"no fix",
|
||||
sats);
|
||||
} else {
|
||||
strcpy(reply, "off");
|
||||
}
|
||||
} else {
|
||||
strcpy(reply, "Can't find GPS");
|
||||
strcpy(reply, "Error, invalid policy");
|
||||
}
|
||||
#endif
|
||||
} else if (memcmp(command, "powersaving on", 14) == 0) {
|
||||
@@ -447,39 +653,8 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
|
||||
|
||||
void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* reply) {
|
||||
const char* config = &command[4];
|
||||
if (memcmp(config, "dutycycle ", 10) == 0) {
|
||||
float dc = atof(&config[10]);
|
||||
if (dc < 1 || dc > 100) {
|
||||
strcpy(reply, "ERROR: dutycycle must be 1-100");
|
||||
} else {
|
||||
_prefs->airtime_factor = (100.0f / dc) - 1.0f;
|
||||
savePrefs();
|
||||
float actual = 100.0f / (_prefs->airtime_factor + 1.0f);
|
||||
int a_int = (int)actual;
|
||||
int a_frac = (int)((actual - a_int) * 10.0f + 0.5f);
|
||||
sprintf(reply, "OK - %d.%d%%", a_int, a_frac);
|
||||
}
|
||||
} else if (memcmp(config, "af ", 3) == 0) {
|
||||
_prefs->airtime_factor = atof(&config[3]);
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else if (memcmp(config, "int.thresh ", 11) == 0) {
|
||||
_prefs->interference_threshold = atoi(&config[11]);
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else if (memcmp(config, "cad ", 4) == 0) {
|
||||
_prefs->cad_enabled = memcmp(&config[4], "on", 2) == 0;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else if (memcmp(config, "agc.reset.interval ", 19) == 0) {
|
||||
_prefs->agc_reset_interval = atoi(&config[19]) / 4;
|
||||
savePrefs();
|
||||
sprintf(reply, "OK - interval rounded to %d", ((uint32_t) _prefs->agc_reset_interval) * 4);
|
||||
} else if (memcmp(config, "multi.acks ", 11) == 0) {
|
||||
_prefs->multi_acks = atoi(&config[11]);
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else if (memcmp(config, "allow.read.only ", 16) == 0) {
|
||||
|
||||
if (memcmp(config, "allow.read.only ", 16) == 0) {
|
||||
_prefs->allow_read_only = memcmp(&config[16], "on", 2) == 0;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
@@ -503,6 +678,22 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
}
|
||||
} else if (memcmp(config, "advert.loc ", 11) == 0) {
|
||||
if (memcmp(config+11, "none", 4) == 0) {
|
||||
_prefs->advert_loc_policy = ADVERT_LOC_NONE;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else if (memcmp(config+11, "share", 5) == 0) {
|
||||
_prefs->advert_loc_policy = ADVERT_LOC_SHARE;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else if (memcmp(config+11, "prefs", 5) == 0) {
|
||||
_prefs->advert_loc_policy = ADVERT_LOC_PREFS;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error, invalid policy");
|
||||
}
|
||||
} else if (memcmp(config, "guest.password ", 15) == 0) {
|
||||
StrHelper::strncpy(_prefs->guest_password, &config[15], sizeof(_prefs->guest_password));
|
||||
savePrefs();
|
||||
@@ -524,7 +715,16 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
if (isValidName(&config[5])) {
|
||||
StrHelper::strncpy(_prefs->node_name, &config[5], sizeof(_prefs->node_name));
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
// Přejmenování může vytlačit zapnutou ikonku z advertu, a to je změna,
|
||||
// kterou by nikdo neviděl: `set batt.icon` i `get batt.icon` na to
|
||||
// upozorňují, ale rename je ta cesta, kterou operátor jde později --
|
||||
// a bez tohohle by mu indikátor zmizel ze vzduchu bez jediné hlášky.
|
||||
if (_prefs->batt_icon && !mesh::battIconFits(strlen(_prefs->node_name), nameBudget())) {
|
||||
sprintf(reply, "OK - ALE jméno má %d B, s ikonkou se vejde jen %d B - batt.icon se zahodí",
|
||||
(int)strlen(_prefs->node_name), (int)(nameBudget() - mesh::battIconWidth()));
|
||||
} else {
|
||||
strcpy(reply, "OK");
|
||||
}
|
||||
} else {
|
||||
strcpy(reply, "Error, bad chars");
|
||||
}
|
||||
@@ -532,103 +732,16 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
_prefs->disable_fwd = memcmp(&config[7], "off", 3) == 0;
|
||||
savePrefs();
|
||||
strcpy(reply, _prefs->disable_fwd ? "OK - repeat is now OFF" : "OK - repeat is now ON");
|
||||
} else if (memcmp(config, "radio.rxgain ", 13) == 0) {
|
||||
bool enabled = memcmp(&config[13], "on", 2) == 0;
|
||||
_prefs->rx_boosted_gain = enabled;
|
||||
savePrefs();
|
||||
if (_callbacks->setRxBoostedGain(enabled)) {
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error: unsupported");
|
||||
}
|
||||
} else if (memcmp(config, "radio.fem.rxgain ", 17) == 0) {
|
||||
if (!_board->canControlLoRaFemLna()) {
|
||||
strcpy(reply, "Error: unsupported");
|
||||
} else if (memcmp(&config[17], "on", 2) == 0) {
|
||||
if (_board->setLoRaFemLnaEnabled(true)) {
|
||||
_prefs->radio_fem_rxgain = 1;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK - LoRa FEM RX gain on");
|
||||
} else {
|
||||
strcpy(reply, "Error: failed to apply LoRa FEM RX gain");
|
||||
}
|
||||
} else if (memcmp(&config[17], "off", 3) == 0) {
|
||||
if (_board->setLoRaFemLnaEnabled(false)) {
|
||||
_prefs->radio_fem_rxgain = 0;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK - LoRa FEM RX gain off");
|
||||
} else {
|
||||
strcpy(reply, "Error: failed to apply LoRa FEM RX gain");
|
||||
}
|
||||
} else {
|
||||
strcpy(reply, "Error: state must be on or off");
|
||||
}
|
||||
} else if (memcmp(config, "radio.fem.txgain ", 17) == 0) {
|
||||
if (!_board->canControlLoRaFemPaGain()) {
|
||||
strcpy(reply, "Error: unsupported");
|
||||
} else if (memcmp(&config[17], "on", 2) == 0) {
|
||||
if (_board->setLoRaFemPaGainEnabled(true)) {
|
||||
_prefs->radio_fem_txgain = 1;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK - LoRa FEM TX gain on");
|
||||
} else {
|
||||
strcpy(reply, "Error: failed to apply LoRa FEM TX gain");
|
||||
}
|
||||
} else if (memcmp(&config[17], "off", 3) == 0) {
|
||||
if (_board->setLoRaFemPaGainEnabled(false)) {
|
||||
_prefs->radio_fem_txgain = 0;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK - LoRa FEM TX gain off");
|
||||
} else {
|
||||
strcpy(reply, "Error: failed to apply LoRa FEM TX gain");
|
||||
}
|
||||
} else {
|
||||
strcpy(reply, "Error: state must be on or off");
|
||||
}
|
||||
} else if (memcmp(config, "radio ", 6) == 0) {
|
||||
strcpy(tmp, &config[6]);
|
||||
const char *parts[4];
|
||||
int num = mesh::Utils::parseTextParts(tmp, parts, 4);
|
||||
float freq = num > 0 ? strtof(parts[0], nullptr) : 0.0f;
|
||||
float bw = num > 1 ? strtof(parts[1], nullptr) : 0.0f;
|
||||
uint8_t sf = num > 2 ? atoi(parts[2]) : 0;
|
||||
uint8_t cr = num > 3 ? atoi(parts[3]) : 0;
|
||||
if (freq >= 150.0f && freq <= 2500.0f && sf >= 5 && sf <= 12 && cr >= 5 && cr <= 8 && bw >= 7.0f && bw <= 500.0f) {
|
||||
_prefs->sf = sf;
|
||||
_prefs->cr = cr;
|
||||
_prefs->freq = freq;
|
||||
_prefs->bw = bw;
|
||||
_callbacks->savePrefs();
|
||||
strcpy(reply, "OK - reboot to apply");
|
||||
} else {
|
||||
strcpy(reply, "Error, invalid radio params");
|
||||
}
|
||||
} else if (memcmp(config, "lat ", 4) == 0) {
|
||||
_prefs->node_lat = atof(&config[4]);
|
||||
_prefs->getGpsPrefs()->applyGuardReference(*_sensors);
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else if (memcmp(config, "lon ", 4) == 0) {
|
||||
_prefs->node_lon = atof(&config[4]);
|
||||
_prefs->getGpsPrefs()->applyGuardReference(*_sensors);
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else if (memcmp(config, "rxdelay ", 8) == 0) {
|
||||
float db = atof(&config[8]);
|
||||
if (db >= 0 && db <= 20.0f) {
|
||||
_prefs->rx_delay_base = db;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error, must be 0-20");
|
||||
}
|
||||
} else if (memcmp(config, "txdelay ", 8) == 0) {
|
||||
float f = atof(&config[8]);
|
||||
if (f >= 0 && f <= 2.0f) {
|
||||
_prefs->tx_delay_factor = f;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error, must be 0-2");
|
||||
}
|
||||
} else if (memcmp(config, "flood.max.unscoped ", 19) == 0) {
|
||||
uint8_t m = atoi(&config[19]);
|
||||
if (m <= 64) {
|
||||
@@ -656,15 +769,6 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
} else {
|
||||
strcpy(reply, "Error, max 64");
|
||||
}
|
||||
} else if (memcmp(config, "direct.txdelay ", 15) == 0) {
|
||||
float f = atof(&config[15]);
|
||||
if (f >= 0 && f <= 2.0f) {
|
||||
_prefs->direct_tx_delay_factor = f;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error, must be 0-2");
|
||||
}
|
||||
} else if (memcmp(config, "owner.info ", 11) == 0) {
|
||||
config += 11;
|
||||
char *dp = _prefs->owner_info;
|
||||
@@ -675,16 +779,6 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
*dp = 0;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else if (memcmp(config, "path.hash.mode ", 15) == 0) {
|
||||
config += 15;
|
||||
uint8_t mode = atoi(config);
|
||||
if (mode < 3) {
|
||||
_prefs->path_hash_mode = mode;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error, must be 0,1, or 2");
|
||||
}
|
||||
} else if (memcmp(config, "loop.detect ", 12) == 0) {
|
||||
config += 12;
|
||||
uint8_t mode;
|
||||
@@ -705,11 +799,6 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
}
|
||||
} else if (memcmp(config, "tx ", 3) == 0) {
|
||||
_prefs->tx_power_dbm = atoi(&config[3]);
|
||||
savePrefs();
|
||||
_callbacks->setTxPower(_prefs->tx_power_dbm);
|
||||
strcpy(reply, "OK");
|
||||
} else if (sender_timestamp == 0 && memcmp(config, "freq ", 5) == 0) {
|
||||
_prefs->freq = atof(&config[5]);
|
||||
savePrefs();
|
||||
@@ -763,6 +852,38 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
#endif
|
||||
} else if (memcmp(config, "batt.icon.lo ", 13) == 0 || memcmp(config, "batt.icon.hi ", 13) == 0) {
|
||||
bool is_lo = config[10] == 'l';
|
||||
int mv = atoi(&config[13]);
|
||||
if (mv != 0 && (mv < 2500 || mv > 4500)) {
|
||||
strcpy(reply, "Error: expected 2500..4500, or 0 for default");
|
||||
} else {
|
||||
if (is_lo) _prefs->batt_icon_lo = mv; else _prefs->batt_icon_hi = mv;
|
||||
savePrefs();
|
||||
uint16_t lo = _prefs->batt_icon_lo ? _prefs->batt_icon_lo : BATT_ICON_LO_MV;
|
||||
uint16_t hi = _prefs->batt_icon_hi ? _prefs->batt_icon_hi : BATT_ICON_HI_MV;
|
||||
if (hi <= lo) {
|
||||
strcpy(reply, "OK - WARNING: hi <= lo, level will stay at 0");
|
||||
} else {
|
||||
sprintf(reply, "OK - scale %d..%d mV, %d levels, step %d mV",
|
||||
(uint32_t)lo, (uint32_t)hi, (uint32_t)mesh::battIconLevels(),
|
||||
(uint32_t)((hi - lo) / mesh::battIconLevels()));
|
||||
}
|
||||
}
|
||||
} else if (memcmp(config, "batt.icon ", 10) == 0) {
|
||||
_prefs->batt_icon = memcmp(&config[10], "on", 2) == 0 ? 1 : 0;
|
||||
savePrefs();
|
||||
if (!_prefs->batt_icon) {
|
||||
strcpy(reply, "off");
|
||||
} else if (!mesh::battIconFits(strlen(_prefs->node_name), nameBudget())) {
|
||||
// Say so now rather than let the operator wonder why nothing shows up:
|
||||
// the icon is dropped whole when it doesn't fit.
|
||||
sprintf(reply, "on - BUT name is %d B, max %d B with icon - icon omitted",
|
||||
(int)strlen(_prefs->node_name),
|
||||
(int)(nameBudget() - mesh::battIconWidth()));
|
||||
} else {
|
||||
strcpy(reply, "on - shows on next advert");
|
||||
}
|
||||
} else if (memcmp(config, "adc.multiplier ", 15) == 0) {
|
||||
_prefs->adc_multiplier = atof(&config[15]);
|
||||
if (_board->setAdcMultiplier(_prefs->adc_multiplier)) {
|
||||
@@ -806,27 +927,50 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
|
||||
void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* reply) {
|
||||
const char* config = &command[4];
|
||||
if (memcmp(config, "dutycycle", 9) == 0) {
|
||||
float dc = 100.0f / (_prefs->airtime_factor + 1.0f);
|
||||
int dc_int = (int)dc;
|
||||
int dc_frac = (int)((dc - dc_int) * 10.0f + 0.5f);
|
||||
sprintf(reply, "> %d.%d%%", dc_int, dc_frac);
|
||||
} else if (memcmp(config, "af", 2) == 0) {
|
||||
sprintf(reply, "> %s", StrHelper::ftoa(_prefs->airtime_factor));
|
||||
} else if (memcmp(config, "int.thresh", 10) == 0) {
|
||||
sprintf(reply, "> %d", (uint32_t) _prefs->interference_threshold);
|
||||
} else if (memcmp(config, "cad", 3) == 0) {
|
||||
sprintf(reply, "> %s", _prefs->cad_enabled ? "on" : "off");
|
||||
} else if (memcmp(config, "agc.reset.interval", 18) == 0) {
|
||||
sprintf(reply, "> %d", ((uint32_t) _prefs->agc_reset_interval) * 4);
|
||||
} else if (memcmp(config, "multi.acks", 10) == 0) {
|
||||
sprintf(reply, "> %d", (uint32_t) _prefs->multi_acks);
|
||||
} else if (memcmp(config, "allow.read.only", 15) == 0) {
|
||||
#ifdef LOCKED_NODE
|
||||
// CUSTOM (TeTeHacko): a locked node gives its secrets to nobody -- not to the
|
||||
// USB console (no login: whoever holds the board), not to the BLE console, not
|
||||
// to an admin over the mesh. docs/locked-bootloader.md, point 4.
|
||||
if (memcmp(config, "prv.key", 7) == 0 || memcmp(config, "guest.password", 14) == 0 ||
|
||||
memcmp(config, "bridge.secret", 13) == 0) {
|
||||
strcpy(reply, "Error: locked build");
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
#if defined(NRF52_PLATFORM)
|
||||
// CUSTOM (TeTeHacko): which silicon, and whether SWD can read the flash
|
||||
// (docs/locked-bootloader.md, point 5). Variant xxF0 and later = rev3, where
|
||||
// the hardware closes the debug port unless the firmware opens it on every
|
||||
// boot -- ours never does; rev1/rev2 obey UICR.APPROTECT alone (0xFF = open).
|
||||
if (memcmp(config, "chip", 4) == 0 && config[4] == 0) {
|
||||
uint32_t v = NRF_FICR->INFO.VARIANT;
|
||||
uint32_t ap = NRF_UICR->APPROTECT;
|
||||
sprintf(reply, "> nRF%lx %c%c%c%c, uicr.approtect %08lx (%s)", (unsigned long)NRF_FICR->INFO.PART,
|
||||
(char)(v >> 24), (char)(v >> 16), (char)(v >> 8), (char)v, (unsigned long)ap,
|
||||
(ap & 0xFF) == 0xFF ? "open" : "protected");
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
if (memcmp(config, "allow.read.only", 15) == 0) {
|
||||
sprintf(reply, "> %s", _prefs->allow_read_only ? "on" : "off");
|
||||
} else if (memcmp(config, "flood.advert.interval", 21) == 0) {
|
||||
sprintf(reply, "> %d", ((uint32_t) _prefs->flood_advert_interval));
|
||||
} else if (memcmp(config, "advert.interval", 15) == 0) {
|
||||
sprintf(reply, "> %d", ((uint32_t) _prefs->advert_interval) * 2);
|
||||
} else if (memcmp(config, "advert.loc", 10) == 0) {
|
||||
switch (_prefs->advert_loc_policy) {
|
||||
case ADVERT_LOC_NONE:
|
||||
strcpy(reply, "> none");
|
||||
break;
|
||||
case ADVERT_LOC_PREFS:
|
||||
strcpy(reply, "> prefs");
|
||||
break;
|
||||
case ADVERT_LOC_SHARE:
|
||||
strcpy(reply, "> share");
|
||||
break;
|
||||
default:
|
||||
strcpy(reply, "Error, invalid policy");
|
||||
}
|
||||
} else if (memcmp(config, "guest.password", 14) == 0) {
|
||||
sprintf(reply, "> %s", _prefs->guest_password);
|
||||
} else if (sender_timestamp == 0 && memcmp(config, "prv.key", 7) == 0) { // from serial command line only
|
||||
@@ -834,6 +978,37 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
int len = _callbacks->getSelfId().writeTo(prv_key, PRV_KEY_SIZE);
|
||||
mesh::Utils::toHex(tmp, prv_key, len);
|
||||
sprintf(reply, "> %s", tmp);
|
||||
} else if (memcmp(config, "batt.icon.lo", 12) == 0) {
|
||||
sprintf(reply, "> %d", (uint32_t)(_prefs->batt_icon_lo ? _prefs->batt_icon_lo : BATT_ICON_LO_MV));
|
||||
} else if (memcmp(config, "batt.icon.hi", 12) == 0) {
|
||||
sprintf(reply, "> %d", (uint32_t)(_prefs->batt_icon_hi ? _prefs->batt_icon_hi : BATT_ICON_HI_MV));
|
||||
} else if (memcmp(config, "batt.icon", 9) == 0) {
|
||||
// Report what actually goes on the air, not just the flag: the indicator
|
||||
// is dropped when the name leaves no room, and the voltage is the only way
|
||||
// to tell "not there yet" from "board reads nothing".
|
||||
if (!_prefs->batt_icon) {
|
||||
strcpy(reply, "> off");
|
||||
} else if (!mesh::battIconFits(strlen(_prefs->node_name), nameBudget())) {
|
||||
strcpy(reply, "> on (omitted, name too long)");
|
||||
} else if (_board->isExternalPowered()) {
|
||||
strcpy(reply, "> on (external power)");
|
||||
} else {
|
||||
uint16_t mv = _board->getBattMilliVolts();
|
||||
if (mv == 0) {
|
||||
strcpy(reply, "> on (omitted, no battery reading)");
|
||||
} else {
|
||||
// What the NEXT advert would carry, not what the last one did: the
|
||||
// state only advances in advertName(), so reporting the stored level
|
||||
// had `get` disagreeing with the advert that went out moments later.
|
||||
// Predicting is read-only -- _batt_level is deliberately not updated.
|
||||
uint16_t lo = _prefs->batt_icon_lo ? _prefs->batt_icon_lo : BATT_ICON_LO_MV;
|
||||
uint16_t hi = _prefs->batt_icon_hi ? _prefs->batt_icon_hi : BATT_ICON_HI_MV;
|
||||
uint8_t n = mesh::battIconLevels();
|
||||
uint8_t next = mesh::battIconLevel(_batt_level, mv, lo, hi, n, BATT_ICON_HYST_MV);
|
||||
sprintf(reply, "> on (level %d/%d, %d mV, scale %d..%d)",
|
||||
(uint32_t)(next + 1), (uint32_t)n, (uint32_t)mv, (uint32_t)lo, (uint32_t)hi);
|
||||
}
|
||||
}
|
||||
} else if (memcmp(config, "name", 4) == 0) {
|
||||
sprintf(reply, "> %s", _prefs->node_name);
|
||||
} else if (memcmp(config, "repeat", 6) == 0) {
|
||||
@@ -842,37 +1017,12 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
sprintf(reply, "> %s", StrHelper::ftoa(_prefs->node_lat));
|
||||
} else if (memcmp(config, "lon", 3) == 0) {
|
||||
sprintf(reply, "> %s", StrHelper::ftoa(_prefs->node_lon));
|
||||
} else if (memcmp(config, "radio.rxgain", 12) == 0) {
|
||||
sprintf(reply, "> %s", _prefs->rx_boosted_gain ? "on" : "off");
|
||||
} else if (memcmp(config, "radio.fem.rxgain", 16) == 0) {
|
||||
if (!_board->canControlLoRaFemLna()) {
|
||||
strcpy(reply, "Error: unsupported");
|
||||
} else {
|
||||
sprintf(reply, "> %s", _board->isLoRaFemLnaEnabled() ? "on" : "off");
|
||||
}
|
||||
} else if (memcmp(config, "radio.fem.txgain", 16) == 0) {
|
||||
if (!_board->canControlLoRaFemPaGain()) {
|
||||
strcpy(reply, "Error: unsupported");
|
||||
} else {
|
||||
sprintf(reply, "> %s", _board->isLoRaFemPaGainEnabled() ? "on" : "off");
|
||||
}
|
||||
} else if (memcmp(config, "radio", 5) == 0) {
|
||||
char freq[16], bw[16];
|
||||
strcpy(freq, StrHelper::ftoa(_prefs->freq));
|
||||
strcpy(bw, StrHelper::ftoa3(_prefs->bw));
|
||||
sprintf(reply, "> %s,%s,%d,%d", freq, bw, (uint32_t)_prefs->sf, (uint32_t)_prefs->cr);
|
||||
} else if (memcmp(config, "rxdelay", 7) == 0) {
|
||||
sprintf(reply, "> %s", StrHelper::ftoa(_prefs->rx_delay_base));
|
||||
} else if (memcmp(config, "txdelay", 7) == 0) {
|
||||
sprintf(reply, "> %s", StrHelper::ftoa(_prefs->tx_delay_factor));
|
||||
} else if (memcmp(config, "flood.max.advert", 16) == 0) {
|
||||
sprintf(reply, "> %d", (uint32_t)_prefs->flood_max_advert);
|
||||
} else if (memcmp(config, "flood.max.unscoped", 18) == 0) {
|
||||
sprintf(reply, "> %d", (uint32_t)_prefs->flood_max_unscoped);
|
||||
} else if (memcmp(config, "flood.max", 9) == 0) {
|
||||
sprintf(reply, "> %d", (uint32_t)_prefs->flood_max);
|
||||
} else if (memcmp(config, "direct.txdelay", 14) == 0) {
|
||||
sprintf(reply, "> %s", StrHelper::ftoa(_prefs->direct_tx_delay_factor));
|
||||
} else if (memcmp(config, "owner.info", 10) == 0) {
|
||||
auto start = reply;
|
||||
*reply++ = '>';
|
||||
@@ -883,8 +1033,6 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
sp++;
|
||||
}
|
||||
*reply = 0; // set null terminator
|
||||
} else if (memcmp(config, "path.hash.mode", 14) == 0) {
|
||||
sprintf(reply, "> %d", (uint32_t)_prefs->path_hash_mode);
|
||||
} else if (memcmp(config, "loop.detect", 11) == 0) {
|
||||
if (_prefs->loop_detect == LOOP_DETECT_OFF) {
|
||||
strcpy(reply, "> off");
|
||||
@@ -895,10 +1043,6 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
} else {
|
||||
strcpy(reply, "> strict");
|
||||
}
|
||||
} else if (memcmp(config, "tx", 2) == 0 && (config[2] == 0 || config[2] == ' ')) {
|
||||
sprintf(reply, "> %d", (int32_t) _prefs->tx_power_dbm);
|
||||
} else if (memcmp(config, "freq", 4) == 0) {
|
||||
sprintf(reply, "> %s", StrHelper::ftoa(_prefs->freq));
|
||||
} else if (memcmp(config, "public.key", 10) == 0) {
|
||||
strcpy(reply, "> ");
|
||||
mesh::Utils::toHex(&reply[2], _callbacks->getSelfId().pub_key, PUB_KEY_SIZE);
|
||||
@@ -982,7 +1126,11 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
sprintf(reply, "No extra SF configured");
|
||||
}
|
||||
} else {
|
||||
sprintf(reply, "??: %s", config);
|
||||
// CUSTOM (TeTeHacko): bounded echo, as the `set` branch does. An unbounded
|
||||
// sprintf put a remote `get <167 chars>` (172 B reply) into the 164 B the
|
||||
// repeater and room server leave for it (temp[169] minus the 5 B header).
|
||||
strcpy(reply, "??: ");
|
||||
StrHelper::strncpy(&reply[4], config, 160-5);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+155
-3
@@ -6,6 +6,9 @@
|
||||
#include <helpers/ClientACL.h>
|
||||
#include <helpers/RegionMap.h>
|
||||
#include <helpers/ConfigSerializer.h>
|
||||
#include <helpers/CommonRadioPrefs.h>
|
||||
#include <helpers/CommonGpsPrefs.h>
|
||||
#include <helpers/DynamicConfigSerializer.h>
|
||||
|
||||
#if defined(WITH_RS232_BRIDGE) || defined(WITH_ESPNOW_BRIDGE)
|
||||
#define WITH_BRIDGE
|
||||
@@ -59,20 +62,53 @@ public:
|
||||
// Gps settings
|
||||
uint8_t gps_enabled = 0;
|
||||
uint32_t gps_interval = 0; // in seconds
|
||||
uint32_t gps_period = 0; // periodic acquisition interval in seconds
|
||||
int32_t gps_fence = -1; // GPS_GUARD fence in metres, 0 = off, -1 = build default
|
||||
int32_t gps_first_fix = -1; // first-fix timeout in seconds, 0 = no limit, -1 = build default
|
||||
uint8_t gps_guard = 1; // GPS_GUARD on/off
|
||||
uint8_t advert_loc_policy = 0;
|
||||
uint32_t discovery_mod_timestamp = 0;
|
||||
float adc_multiplier = 0;
|
||||
float ina_shunt_mohm = 0; // CUSTOM (TeTeHacko): INA shunt in mOhm, 0 = build default
|
||||
char owner_info[120];
|
||||
uint8_t rx_boosted_gain = 0; // power settings
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
RxPowerSavingConfig rxps; // CUSTOM (TeTeHacko): RX duty cycle, off by default
|
||||
#endif
|
||||
uint8_t radio_fem_rxgain = 0; // LoRa FEM RX gain setting
|
||||
uint8_t radio_fem_txgain = 0; // LoRa FEM TX gain setting
|
||||
uint8_t path_hash_mode = 0; // which path mode to use when sending
|
||||
uint8_t loop_detect = 0;
|
||||
uint8_t cad_enabled = 0; // hardware Channel Activity Detection before TX (boolean)
|
||||
uint8_t extra_sf[4];
|
||||
// CUSTOM (TeTeHacko): antispam knobs of simple_repeater. Live here so that the
|
||||
// existing savePrefs()/loadPrefs() machinery persists them; other examples
|
||||
// just leave them at defaults.
|
||||
uint8_t fairness_enabled = 0; // FairnessLimiter runtime kill switch
|
||||
char filter_deny[128]; // channel-filter deny list, comma-separated node names
|
||||
// channel hashes (payload[0] of GRP_TXT/GRP_DATA) this node refuses to forward,
|
||||
// keyless -- works on private channels too. See ChannelFilter.h (`filter hash`).
|
||||
uint8_t deny_hash[8];
|
||||
uint8_t deny_hash_n = 0;
|
||||
uint16_t deny_hash_secs[8]; // per entry: 0 = block, else pass one per N s (throttle)
|
||||
uint16_t filter_age_min = 0; // drop decrypted group texts older than this; 0 = off
|
||||
uint8_t filter_dry_run = 0; // count `filter` verdicts, forward anyway
|
||||
// Battery state as an icon on the advertised name (see BatteryIcon.h).
|
||||
// Off by default: it costs bytes of the name, so it has to be asked for.
|
||||
uint8_t batt_icon = 0; // boolean
|
||||
uint16_t batt_icon_lo = 0; // scale bottom in mV; 0 = BATT_ICON_LO_MV
|
||||
uint16_t batt_icon_hi = 0; // scale top in mV; 0 = BATT_ICON_HI_MV
|
||||
// FairnessLimiter runtime tuning; 0 = use the firmware build default.
|
||||
uint8_t fair_group_cap = 0, fair_sender_cap = 0, fair_advert_cap = 0;
|
||||
uint16_t fair_group_refill_s = 0, fair_sender_refill_s = 0, fair_advert_refill_s = 0;
|
||||
uint16_t fair_advert_hours = 0; // per-origin advert window, hours; 0 = off
|
||||
uint8_t fair_dry_run = 0; // count FairnessLimiter verdicts, forward anyway
|
||||
// Radio silence watchdog (RadioSilenceWatchdog.h, simple_repeater): minutes
|
||||
// without a received frame before the receiver is re-armed, then rebooted; 0 = off.
|
||||
uint16_t radio_silence_min = 0;
|
||||
|
||||
private:
|
||||
class RadioPrefs : public ConfigSerializer {
|
||||
class RadioPrefs : public CommonRadioPrefs {
|
||||
NodePrefs* _parent;
|
||||
protected:
|
||||
void structure() override {
|
||||
@@ -93,9 +129,55 @@ private:
|
||||
def("agc_int", _parent->agc_reset_interval);
|
||||
def("hash_mode", _parent->path_hash_mode);
|
||||
def("multi_ack", _parent->multi_acks);
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
def("rxps_en", _parent->rxps.enabled);
|
||||
def("rxps_rx_us", _parent->rxps.rx_us);
|
||||
def("rxps_sleep_us", _parent->rxps.sleep_us);
|
||||
def("rxps_level", _parent->rxps.level);
|
||||
def("rxps_preamble", _parent->rxps.preamble);
|
||||
#endif
|
||||
def("rsilence", _parent->radio_silence_min);
|
||||
}
|
||||
public:
|
||||
RadioPrefs(NodePrefs* parent) : _parent(parent) { }
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
RxPowerSavingConfig* getRxPowerSavingConfig() override { return &_parent->rxps; }
|
||||
#endif
|
||||
// CommonRadioPrefs interface
|
||||
float getFreq() const override { return _parent->freq; }
|
||||
void setFreq(float f) override { _parent->freq = f; markDirty(); }
|
||||
float getBandwidth() const override { return _parent->bw; }
|
||||
void setBandwidth(float bw) override { _parent->bw = bw; markDirty(); }
|
||||
uint8_t getSpreadFactor() const override { return _parent->sf; }
|
||||
void setSpreadFactor(uint8_t sf) override { _parent->sf = sf; markDirty(); }
|
||||
uint8_t getCodingRate() const override { return _parent->cr; }
|
||||
void setCodingRate(uint8_t cr) override { _parent->cr = cr; markDirty(); }
|
||||
float getAirtimeFactor() const override { return _parent->airtime_factor; }
|
||||
void setAirtimeFactor(float af) override { _parent->airtime_factor = af; markDirty(); }
|
||||
bool isCadEnabled() const override { return _parent->cad_enabled; }
|
||||
void setCadEnabled(bool en) override { _parent->cad_enabled = en; markDirty(); }
|
||||
uint8_t getIntThresh() const override { return _parent->interference_threshold; }
|
||||
void setIntThresh(uint8_t t) override { _parent->interference_threshold = t; markDirty(); }
|
||||
uint8_t getRxGain() const override { return _parent->rx_boosted_gain; }
|
||||
void setRxGain(uint8_t g) override { _parent->rx_boosted_gain = g; markDirty(); }
|
||||
int8_t getTxPower() const override { return _parent->tx_power_dbm; }
|
||||
void setTxPower(int8_t dbm) override { _parent->tx_power_dbm = dbm; markDirty(); }
|
||||
float getRxDelay() const override { return _parent->rx_delay_base; }
|
||||
void setRxDelay(float d) override { _parent->rx_delay_base = d; markDirty(); }
|
||||
uint16_t getAgcResetInt() const override { return _parent->agc_reset_interval * 4; }
|
||||
void setAgcResetInt(uint16_t secs) override { _parent->agc_reset_interval = secs / 4; markDirty(); }
|
||||
uint8_t getHashMode() const override { return _parent->path_hash_mode; }
|
||||
void setHashMode(uint8_t m) override { _parent->path_hash_mode = m; markDirty(); }
|
||||
uint8_t getMultiAcks() const override { return _parent->multi_acks; }
|
||||
void setMultiAcks(uint8_t m) override { _parent->multi_acks = m; markDirty(); }
|
||||
float getFloodTxDelay() const override { return _parent->tx_delay_factor; }
|
||||
void setFloodTxDelay(float d) override { _parent->tx_delay_factor = d; markDirty(); }
|
||||
float getDirectTxDelay() const override { return _parent->direct_tx_delay_factor; }
|
||||
void setDirectTxDelay(float d) override { _parent->direct_tx_delay_factor = d; markDirty(); }
|
||||
uint8_t getFEMRxGain() const override { return _parent->radio_fem_rxgain; }
|
||||
void setFEMRxGain(uint8_t g) override { _parent->radio_fem_rxgain = g; markDirty(); }
|
||||
uint8_t getFEMTxGain() const override { return _parent->radio_fem_txgain; }
|
||||
void setFEMTxGain(uint8_t g) override { _parent->radio_fem_txgain = g; markDirty(); }
|
||||
};
|
||||
RadioPrefs radio;
|
||||
|
||||
@@ -115,16 +197,48 @@ private:
|
||||
};
|
||||
BridgePrefs bridge;
|
||||
|
||||
class GPSPrefs : public ConfigSerializer {
|
||||
class GPSPrefs : public CommonGpsPrefs {
|
||||
NodePrefs* _parent;
|
||||
protected:
|
||||
void structure() override {
|
||||
def("en", _parent->gps_enabled); // boolean
|
||||
def("int", _parent->gps_interval); // interval in seconds
|
||||
def("period", _parent->gps_period); // periodic acquisition interval in seconds
|
||||
def("adv_loc", _parent->advert_loc_policy);
|
||||
def("ffix", _parent->gps_first_fix);
|
||||
#ifdef GPS_GUARD
|
||||
def("fence", _parent->gps_fence);
|
||||
def("guard", _parent->gps_guard);
|
||||
#endif
|
||||
}
|
||||
public:
|
||||
GPSPrefs(NodePrefs* parent) : _parent(parent) { }
|
||||
bool isGpsEnabled() const override { return _parent->gps_enabled; }
|
||||
void setGpsEnabled(bool enabled) override { _parent->gps_enabled = enabled; markDirty(); }
|
||||
uint32_t getGpsPeriod() const override { return _parent->gps_period; }
|
||||
void setGpsPeriod(uint32_t seconds) override { _parent->gps_period = seconds; markDirty(); }
|
||||
bool getFirstFixTimeout(uint32_t& seconds) const override {
|
||||
if (_parent->gps_first_fix < 0) return false;
|
||||
seconds = (uint32_t)_parent->gps_first_fix;
|
||||
return true;
|
||||
}
|
||||
void setFirstFixTimeout(uint32_t seconds) override { _parent->gps_first_fix = (int32_t)seconds; markDirty(); }
|
||||
bool getGuardFence(uint32_t& metres) const override {
|
||||
if (_parent->gps_fence < 0) return false;
|
||||
metres = (uint32_t)_parent->gps_fence;
|
||||
return true;
|
||||
}
|
||||
void setGuardFence(uint32_t metres) override { _parent->gps_fence = (int32_t)metres; markDirty(); }
|
||||
bool getGuardEnabled(bool& enabled) const override {
|
||||
enabled = _parent->gps_guard != 0;
|
||||
return true;
|
||||
}
|
||||
void setGuardEnabled(bool enabled) override { _parent->gps_guard = enabled ? 1 : 0; markDirty(); }
|
||||
bool getGuardReference(double& lat, double& lon) const override {
|
||||
lat = _parent->node_lat;
|
||||
lon = _parent->node_lon;
|
||||
return true;
|
||||
}
|
||||
};
|
||||
GPSPrefs gps;
|
||||
|
||||
@@ -133,7 +247,11 @@ private:
|
||||
protected:
|
||||
void structure() override {
|
||||
def("adc_mult", _parent->adc_multiplier);
|
||||
def("ina_shunt", _parent->ina_shunt_mohm);
|
||||
def("pwr_sav_en", _parent->powersaving_enabled);
|
||||
def("bicon", _parent->batt_icon);
|
||||
def("bicon_lo", _parent->batt_icon_lo);
|
||||
def("bicon_hi", _parent->batt_icon_hi);
|
||||
}
|
||||
public:
|
||||
PowerPrefs(NodePrefs* parent) : _parent(parent) { }
|
||||
@@ -149,6 +267,21 @@ private:
|
||||
def("f_max_uns", _parent->flood_max_unscoped);
|
||||
def("f_max_adv", _parent->flood_max_advert);
|
||||
def("loop", _parent->loop_detect);
|
||||
def("fair_en", _parent->fairness_enabled);
|
||||
def("f_deny", _parent->filter_deny, sizeof(_parent->filter_deny));
|
||||
def("f_dhash", (void*)_parent->deny_hash, sizeof(_parent->deny_hash));
|
||||
def("f_dhash_n", _parent->deny_hash_n);
|
||||
def("f_dhash_s", (void*)_parent->deny_hash_secs, sizeof(_parent->deny_hash_secs));
|
||||
def("f_age", _parent->filter_age_min);
|
||||
def("f_dry", _parent->filter_dry_run);
|
||||
def("fair_gcap", _parent->fair_group_cap);
|
||||
def("fair_scap", _parent->fair_sender_cap);
|
||||
def("fair_acap", _parent->fair_advert_cap);
|
||||
def("fair_grf", _parent->fair_group_refill_s);
|
||||
def("fair_srf", _parent->fair_sender_refill_s);
|
||||
def("fair_arf", _parent->fair_advert_refill_s);
|
||||
def("fair_advh", _parent->fair_advert_hours);
|
||||
def("fair_dry", _parent->fair_dry_run);
|
||||
}
|
||||
public:
|
||||
RepeatPrefs(NodePrefs* parent) : _parent(parent) { }
|
||||
@@ -166,6 +299,8 @@ private:
|
||||
};
|
||||
RoomPrefs room;
|
||||
|
||||
DynamicConfigSerializer custom;
|
||||
|
||||
protected:
|
||||
void structure() override {
|
||||
def("name", node_name, sizeof(node_name));
|
||||
@@ -182,16 +317,27 @@ protected:
|
||||
def("repeat", repeat);
|
||||
def("room", room);
|
||||
def("power", power);
|
||||
def("custom", custom);
|
||||
}
|
||||
|
||||
public:
|
||||
NodePrefs() : ConfigSerializer(), bridge(this), gps(this), radio(this), power(this), repeat(this), room(this) {
|
||||
NodePrefs() : ConfigSerializer(), bridge(this), gps(this), radio(this), power(this), repeat(this), room(this), custom(&radio) {
|
||||
node_name[0] = 0;
|
||||
password[0] = 0;
|
||||
guest_password[0] = 0;
|
||||
bridge_secret[0] = 0;
|
||||
owner_info[0] = 0;
|
||||
filter_deny[0] = 0;
|
||||
memset(deny_hash, 0, sizeof(deny_hash));
|
||||
memset(deny_hash_secs, 0, sizeof(deny_hash_secs));
|
||||
}
|
||||
|
||||
CommonRadioPrefs* getRadioPrefs() { return &radio; }
|
||||
CommonGpsPrefs* getGpsPrefs() { return &gps; }
|
||||
KeyValueStore* getCustom() { return &custom; }
|
||||
|
||||
bool isDirty() const override { return ConfigSerializer::isDirty() || radio.isDirty() || gps.isDirty() || custom.isDirty(); }
|
||||
void clearDirty() override { ConfigSerializer::clearDirty(); radio.clearDirty(); gps.clearDirty(); custom.clearDirty(); }
|
||||
};
|
||||
|
||||
class CommonCLICallbacks {
|
||||
@@ -258,8 +404,14 @@ class CommonCLI {
|
||||
RegionMap* _region_map;
|
||||
ClientACL* _acl;
|
||||
char tmp[PRV_KEY_SIZE*2 + 4];
|
||||
// Name handed to AdvertDataBuilder, which keeps the pointer until encodeTo();
|
||||
// it has to outlive buildAdvertData(), hence a member and not a local.
|
||||
char _adv_name[sizeof(NodePrefs::node_name) + 8];
|
||||
uint8_t _batt_level = 0; // hysteresis state, see BatteryIcon.h
|
||||
|
||||
mesh::RTCClock* getRTCClock() { return _rtc; }
|
||||
const char* advertName(size_t budget);
|
||||
size_t nameBudget() const;
|
||||
void savePrefs();
|
||||
void loadPrefsInt(FILESYSTEM* _fs, const char* filename);
|
||||
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
#include "CommonGpsPrefs.h"
|
||||
#include <helpers/sensors/LocationProvider.h>
|
||||
#ifdef GPS_GUARD
|
||||
#include <helpers/sensors/GpsGuard.h>
|
||||
#endif
|
||||
|
||||
bool CommonGpsPrefs::setGpsEnabled(SensorManager& sensors, bool enabled) {
|
||||
LocationProvider* location = sensors.getLocationProvider();
|
||||
if (location == nullptr) return false;
|
||||
// `gps duty` (setting "2") runs in the sensor manager, above the provider:
|
||||
// on/off has to leave it there too, or its loop keeps cycling the receiver
|
||||
const char* mode = sensors.getSettingByKey("gps");
|
||||
if (mode != nullptr && strcmp(mode, "2") == 0) sensors.setSettingValue("gps", enabled ? "1" : "0");
|
||||
location->setGpsOn(enabled);
|
||||
setGpsEnabled(enabled);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CommonGpsPrefs::setGpsPeriod(SensorManager& sensors, uint32_t seconds) {
|
||||
LocationProvider* location = sensors.getLocationProvider();
|
||||
if (location == nullptr) return false;
|
||||
location->setGpsPeriod(seconds);
|
||||
setGpsPeriod(seconds);
|
||||
return true;
|
||||
}
|
||||
|
||||
void CommonGpsPrefs::applyGuardReference(SensorManager& sensors) const {
|
||||
#ifdef GPS_GUARD
|
||||
LocationProvider* location = sensors.getLocationProvider();
|
||||
GpsGuard* guard = location != nullptr ? location->getGuard() : nullptr;
|
||||
double lat, lon;
|
||||
if (guard != nullptr && getGuardReference(lat, lon)) guard->setReference(lat, lon);
|
||||
uint32_t fence;
|
||||
if (guard != nullptr && getGuardFence(fence)) guard->setFence(fence);
|
||||
bool enabled;
|
||||
if (guard != nullptr && getGuardEnabled(enabled)) guard->setEnabled(enabled);
|
||||
#endif
|
||||
}
|
||||
|
||||
// The clock was set by hand: the guard drops its GPS time anchor and any alert.
|
||||
void CommonGpsPrefs::onClockSetManually(SensorManager& sensors) {
|
||||
#ifdef GPS_GUARD
|
||||
LocationProvider* location = sensors.getLocationProvider();
|
||||
GpsGuard* guard = location != nullptr ? location->getGuard() : nullptr;
|
||||
if (guard != nullptr) guard->clockSetManually();
|
||||
#endif
|
||||
}
|
||||
|
||||
bool CommonGpsPrefs::apply(SensorManager& sensors) const {
|
||||
LocationProvider* location = sensors.getLocationProvider();
|
||||
if (location == nullptr) return false;
|
||||
applyGuardReference(sensors);
|
||||
uint32_t first_fix;
|
||||
if (getFirstFixTimeout(first_fix)) location->setFirstFixTimeout(first_fix);
|
||||
location->setGpsPeriod(getGpsPeriod());
|
||||
location->setGpsOn(isGpsEnabled());
|
||||
return true;
|
||||
}
|
||||
|
||||
// single unit, rounded down: "45s", "12m", "3h"
|
||||
static void formatDuration(char* buf, size_t size, uint32_t seconds) {
|
||||
if (seconds < 60) {
|
||||
snprintf(buf, size, "%lus", (unsigned long)seconds);
|
||||
} else if (seconds < 3600) {
|
||||
snprintf(buf, size, "%lum", (unsigned long)(seconds / 60));
|
||||
} else {
|
||||
snprintf(buf, size, "%luh", (unsigned long)(seconds / 3600));
|
||||
}
|
||||
}
|
||||
|
||||
// "<n>[s|m|h|d]", seconds by default
|
||||
static bool parseDuration(const char* text, uint32_t& seconds) {
|
||||
char* end;
|
||||
unsigned long value = strtoul(text, &end, 10);
|
||||
unsigned long mult = 1;
|
||||
if (*end == 'm') mult = 60;
|
||||
else if (*end == 'h') mult = 3600;
|
||||
else if (*end == 'd') mult = 86400;
|
||||
if (mult > 1 || *end == 's') end++; // skip the suffix char
|
||||
if (text[0] == '\0' || *end != '\0') return false;
|
||||
seconds = (uint32_t)(value * mult);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, char* reply) {
|
||||
if (strcmp(command, "gps") == 0) {
|
||||
LocationProvider* location = sensors.getLocationProvider();
|
||||
char mode[32];
|
||||
if (getGpsPeriod() == 0) {
|
||||
strcpy(mode, "continuous");
|
||||
} else {
|
||||
snprintf(mode, sizeof(mode), "periodic (%lus)",
|
||||
(unsigned long)getGpsPeriod());
|
||||
}
|
||||
if (location == nullptr) {
|
||||
strcpy(reply, "Error, gps provider not found");
|
||||
} else if (location->isGpsOn()) {
|
||||
const char* activity = "active";
|
||||
if (!location->isActive()) {
|
||||
if (location->hasHardwareEnableState() && !location->isHardwareEnabled()) {
|
||||
activity = "off(hw)";
|
||||
} else if (getGpsPeriod() > 0) {
|
||||
activity = "waiting";
|
||||
} else {
|
||||
activity = "inactive";
|
||||
}
|
||||
}
|
||||
char fix[32];
|
||||
if (location->hasValidFix()) {
|
||||
char age[12];
|
||||
formatDuration(age, sizeof(age), location->getLastFixAge());
|
||||
snprintf(fix, sizeof(fix), "%ld sats %s ago", location->satellitesCount(), age);
|
||||
} else {
|
||||
strcpy(fix, "no fix");
|
||||
}
|
||||
snprintf(reply, 160, "> on, %s, %s, %s", activity, fix, mode);
|
||||
} else {
|
||||
snprintf(reply, 160, "> off, %s", mode);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (strcmp(command, "gps fix") == 0) {
|
||||
LocationProvider* location = sensors.getLocationProvider();
|
||||
char acq[16] = "";
|
||||
if (location == nullptr) {
|
||||
strcpy(reply, "Error, gps provider not found");
|
||||
return true;
|
||||
}
|
||||
if (location->isActive()) {
|
||||
char t[12];
|
||||
formatDuration(t, sizeof(t), location->getAcquisitionAge());
|
||||
snprintf(acq, sizeof(acq), "acq %s", t);
|
||||
}
|
||||
if (!location->hasValidFix()) {
|
||||
snprintf(reply, 160, "> No fix%s%s", acq[0] ? ", " : "", acq);
|
||||
} else {
|
||||
const long latitude = location->getLatitude();
|
||||
const long longitude = location->getLongitude();
|
||||
char pos[40];
|
||||
snprintf(pos, sizeof(pos), "%.6f, %.6f", latitude / 1e6, longitude / 1e6);
|
||||
if (location->isValid()) {
|
||||
snprintf(reply, 160, "> Fix (%d sat): %s", location->satellitesCount(), pos);
|
||||
} else {
|
||||
char age[12];
|
||||
formatDuration(age, sizeof(age), location->getLastFixAge());
|
||||
snprintf(reply, 160, "> Fix %s ago (%d sat)%s%s: %s", age, location->satellitesCount(),acq[0] ? ", " : "", acq, pos);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "gps once", 8) == 0) { // before "gps on"
|
||||
LocationProvider* location = sensors.getLocationProvider();
|
||||
|
||||
if (location == nullptr) {
|
||||
strcpy(reply, "Error, gps provider not found");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (location->hasHardwareEnableState() && !location->isHardwareEnabled()) {
|
||||
strcpy(reply, "Error, gps hw switch off");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (strstr(command, " -s") != nullptr) location->syncTime();
|
||||
|
||||
const char* state = !location->isGpsOn() ? "turning on and acquiring"
|
||||
: (location->getGpsPeriod() > 0 && !location->isActive()) ? "waking gps"
|
||||
: "gps already on";
|
||||
|
||||
if (location->startOnce()) {
|
||||
snprintf(reply, 160, "OK - %s", state);
|
||||
} else {
|
||||
strcpy(reply, "Error, gps once not supported");
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "gps on", 6) == 0) {
|
||||
if (!setGpsEnabled(sensors, true)) {
|
||||
strcpy(reply, "Error, gps toggle not found");
|
||||
} else {
|
||||
strcpy(reply, "OK");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "gps off", 7) == 0) {
|
||||
if (!setGpsEnabled(sensors, false)) {
|
||||
strcpy(reply, "Error, gps toggle not found");
|
||||
} else {
|
||||
strcpy(reply, "OK");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (strcmp(command, "gps period") == 0) {
|
||||
if (getGpsPeriod() == 0) {
|
||||
strcpy(reply, "> 0 (continuous)");
|
||||
} else {
|
||||
sprintf(reply, "> %lu", (unsigned long)getGpsPeriod());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "gps period ", 11) == 0) {
|
||||
uint32_t period;
|
||||
if (!parseDuration(command + 11, period)) {
|
||||
strcpy(reply, "Error, invalid gps period");
|
||||
} else if (!setGpsPeriod(sensors, period) ||
|
||||
!setGpsEnabled(sensors, true)) {
|
||||
strcpy(reply, "Error, gps provider not found");
|
||||
} else {
|
||||
strcpy(reply, "OK");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (strcmp(command, "gps firstfix") == 0) {
|
||||
LocationProvider* location = sensors.getLocationProvider();
|
||||
if (location == nullptr) {
|
||||
strcpy(reply, "Error, gps provider not found");
|
||||
} else if (location->getFirstFixTimeout() == 0) {
|
||||
strcpy(reply, "> 0 (no limit)");
|
||||
} else {
|
||||
sprintf(reply, "> %lu", (unsigned long)location->getFirstFixTimeout());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "gps firstfix ", 13) == 0) {
|
||||
LocationProvider* location = sensors.getLocationProvider();
|
||||
uint32_t seconds;
|
||||
if (location == nullptr) {
|
||||
strcpy(reply, "Error, gps provider not found");
|
||||
} else if (!parseDuration(command + 13, seconds) || seconds > 86400UL) { // at most a day
|
||||
strcpy(reply, "Error, invalid first fix timeout");
|
||||
} else {
|
||||
location->setFirstFixTimeout(seconds);
|
||||
setFirstFixTimeout(seconds); // saved by the caller (isDirty)
|
||||
strcpy(reply, "OK");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "gps sync", 8) == 0) {
|
||||
LocationProvider* location = sensors.getLocationProvider();
|
||||
if (location == nullptr) {
|
||||
strcpy(reply, "Error, gps provider not found");
|
||||
} else {
|
||||
location->syncTime();
|
||||
strcpy(reply, "OK");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (strcmp(command, "gps fix_stats") == 0) {
|
||||
LocationProvider* location = sensors.getLocationProvider();
|
||||
if (location == nullptr) {
|
||||
strcpy(reply, "Error, gps provider not found");
|
||||
} else {
|
||||
const LocationProvider::FixStats s = location->getFixStats();
|
||||
char last[12] = "-", max[12] = "-";
|
||||
if (s.maxTtffMs > 0) {
|
||||
formatDuration(last, sizeof(last), (s.lastTtffMs + 500) / 1000);
|
||||
formatDuration(max, sizeof(max), (s.maxTtffMs + 500) / 1000);
|
||||
}
|
||||
snprintf(reply, 160, "> ttf:%s/%s ok:%lu miss:%lu", last, max,
|
||||
(unsigned long)s.consecutiveFixes, (unsigned long)s.consecutiveMisses);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
#ifdef GPS_GUARD
|
||||
if (memcmp(command, "gps guard", 9) == 0 || memcmp(command, "gps fence", 9) == 0 ||
|
||||
strcmp(command, "gps ref") == 0) {
|
||||
LocationProvider* location = sensors.getLocationProvider();
|
||||
GpsGuard* guard = location != nullptr ? location->getGuard() : nullptr;
|
||||
if (guard == nullptr) {
|
||||
strcpy(reply, "Error, gps guard not supported");
|
||||
} else if (strcmp(command, "gps guard") == 0) {
|
||||
reply[0] = '>'; reply[1] = ' ';
|
||||
guard->formatStatus(reply + 2, 158);
|
||||
} else if (strcmp(command, "gps guard on") == 0 || strcmp(command, "gps guard off") == 0) {
|
||||
const bool enabled = command[11] == 'n';
|
||||
guard->setEnabled(enabled);
|
||||
setGuardEnabled(enabled); // saved by the caller (isDirty)
|
||||
strcpy(reply, "OK");
|
||||
} else if (strcmp(command, "gps guard accept") == 0) {
|
||||
// operator confirms that the alerted GPS time is right: apply it to the clock
|
||||
long offset;
|
||||
if (!guard->isTimeAlert()) {
|
||||
strcpy(reply, "Error, no time alert");
|
||||
} else if (!location->getClockOffset(offset) ||
|
||||
!guard->acceptAlertedTime(offset, (uint32_t)location->getTimestamp()) ||
|
||||
!location->applyTimeNow()) {
|
||||
strcpy(reply, "Error, no current trusted fix with the alerted time");
|
||||
} else {
|
||||
strcpy(reply, "OK - clock set from GPS");
|
||||
}
|
||||
} else if (strcmp(command, "gps fence") == 0) {
|
||||
sprintf(reply, "> %lu", (unsigned long)guard->getFence());
|
||||
} else if (memcmp(command, "gps fence ", 10) == 0) {
|
||||
char* end;
|
||||
unsigned long metres = strtoul(command + 10, &end, 10);
|
||||
if (command[10] == '\0' || *end != '\0' || metres > 20000000UL) { // at most half the Earth
|
||||
strcpy(reply, "Error, invalid fence");
|
||||
} else {
|
||||
guard->setFence((uint32_t)metres);
|
||||
setGuardFence((uint32_t)metres); // saved by the caller (isDirty)
|
||||
strcpy(reply, "OK");
|
||||
}
|
||||
} else if (strcmp(command, "gps ref") == 0) {
|
||||
snprintf(reply, 160, "> %.6f, %.6f", guard->getRefLat(), guard->getRefLon());
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
if (strcmp(command, "gps diag") == 0) {
|
||||
LocationProvider* location = sensors.getLocationProvider();
|
||||
if (location == nullptr) {
|
||||
strcpy(reply, "Error, gps provider not found");
|
||||
} else {
|
||||
int prefix = snprintf(reply, 160, "> req:%u ", isGpsEnabled() ? 1U : 0U);
|
||||
if (prefix >= 0 && prefix < 160) location->formatDiagnostics(reply + prefix, 160 - prefix);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
|
||||
#include "ConfigSerializer.h"
|
||||
#include "SensorManager.h"
|
||||
|
||||
class CommonGpsPrefs : public ConfigSerializer {
|
||||
protected:
|
||||
CommonGpsPrefs() = default;
|
||||
|
||||
public:
|
||||
virtual bool isGpsEnabled() const = 0;
|
||||
virtual void setGpsEnabled(bool enabled) = 0;
|
||||
virtual uint32_t getGpsPeriod() const = 0;
|
||||
virtual void setGpsPeriod(uint32_t seconds) = 0;
|
||||
// Saved first-fix timeout in seconds; false = not set, use the build default.
|
||||
virtual bool getFirstFixTimeout(uint32_t& seconds) const { return false; }
|
||||
virtual void setFirstFixTimeout(uint32_t seconds) { }
|
||||
|
||||
// Reference position for the anti-spoofing guard (GPS_GUARD), e.g. the configured node position.
|
||||
virtual bool getGuardReference(double& lat, double& lon) const { return false; }
|
||||
// Saved fence radius for the guard; false = not set, use the build default.
|
||||
virtual bool getGuardFence(uint32_t& metres) const { return false; }
|
||||
virtual void setGuardFence(uint32_t metres) { }
|
||||
// Saved on/off state of the guard; false = not set, guard on.
|
||||
virtual bool getGuardEnabled(bool& enabled) const { return false; }
|
||||
virtual void setGuardEnabled(bool enabled) { }
|
||||
|
||||
bool setGpsEnabled(SensorManager& sensors, bool enabled);
|
||||
void applyGuardReference(SensorManager& sensors) const;
|
||||
static void onClockSetManually(SensorManager& sensors);
|
||||
bool setGpsPeriod(SensorManager& sensors, uint32_t seconds);
|
||||
bool apply(SensorManager& sensors) const;
|
||||
bool handleCommand(const char* command, SensorManager& sensors, char* reply);
|
||||
};
|
||||
@@ -0,0 +1,314 @@
|
||||
#include "CommonRadioPrefs.h"
|
||||
#include "TxtDataHelpers.h"
|
||||
#include "Utils.h"
|
||||
#include "target.h"
|
||||
#include <ctype.h>
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
#include "radiolib/RXPowerSavingCLI.h"
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
|
||||
// strtof() and atof() also read "nan" and "inf". A NaN cannot be refused by a
|
||||
// range check: no ordered comparison is true for it, and under -ffast-math,
|
||||
// which nRF52 builds use, the compiler may assume it never occurs and fold any
|
||||
// test on the parsed value away. So the text is checked before it is parsed:
|
||||
// after optional white space and sign, a number starts with a digit or a '.'.
|
||||
bool looksLikeANumber(const char* s) {
|
||||
while (isspace((unsigned char)*s)) s++;
|
||||
if (*s == '+' || *s == '-') s++;
|
||||
return isdigit((unsigned char)*s) || *s == '.';
|
||||
}
|
||||
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
RxPowerSavingControl* rxpsControl() {
|
||||
#ifdef WRAPPER_CLASS
|
||||
return &radio_driver;
|
||||
#else
|
||||
return nullptr;
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
} // namespace
|
||||
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
bool CommonRadioPrefs::applyRxPowerSaving(uint8_t sf, float bw) {
|
||||
_active_sf = sf;
|
||||
_active_bw = bw;
|
||||
RxPowerSavingConfig* config = getRxPowerSavingConfig();
|
||||
if (!config) return false;
|
||||
// temporary radio parameters must not overwrite the saved automatic periods
|
||||
RxPowerSavingConfig active = *config;
|
||||
return applyRxPowerSavingConfig(&active, sf, bw, rxpsControl());
|
||||
}
|
||||
|
||||
bool CommonRadioPrefs::isRxPowerSavingCalibrationActive() const {
|
||||
const auto* control = rxpsControl();
|
||||
return control && control->isRxPowerSavingCalibrationActive();
|
||||
}
|
||||
#endif
|
||||
|
||||
bool CommonRadioPrefs::getByKey(const char* key, char* value, size_t max_len) {
|
||||
if (strcmp(key, "fem_rxgain") == 0) {
|
||||
snprintf(value, max_len, "%d", (uint32_t)getFEMRxGain());
|
||||
return true;
|
||||
}
|
||||
if (strcmp(key, "fem_txgain") == 0) {
|
||||
snprintf(value, max_len, "%d", (uint32_t)getFEMTxGain());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
bool CommonRadioPrefs::setByKey(const char* key, const char* value) {
|
||||
if (strcmp(key, "fem_rxgain") == 0) {
|
||||
setFEMRxGain(atoi(value));
|
||||
markDirty();
|
||||
return true;
|
||||
}
|
||||
if (strcmp(key, "fem_txgain") == 0) {
|
||||
setFEMTxGain(atoi(value));
|
||||
markDirty();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) {
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
if (strncmp(command, "get radio.rxps", 14) == 0 && (command[14] == 0 || command[14] == ' ')) {
|
||||
const char* suffix = command + 14;
|
||||
while (*suffix == ' ') ++suffix;
|
||||
if (*suffix) return false;
|
||||
auto* config = getRxPowerSavingConfig();
|
||||
if (!config) { strcpy(reply, "Error: unsupported"); return true; }
|
||||
const uint8_t sf = _active_sf ? _active_sf : getSpreadFactor();
|
||||
const float bw = _active_sf ? _active_bw : getBandwidth();
|
||||
RxPowerSavingConfig active = *config;
|
||||
normalizeRxPowerSavingConfig(&active, sf, bw,
|
||||
rxPowerSavingCaptureCost(rxpsControl()), rxPowerSavingTransition(rxpsControl()));
|
||||
RXPowerSavingCLI::get(&active, rxpsControl(), sf, bw, reply, 160);
|
||||
return true;
|
||||
}
|
||||
if (strncmp(command, "set radio.rxps ", 15) == 0) {
|
||||
auto* config = getRxPowerSavingConfig();
|
||||
if (!config) { strcpy(reply, "Error: unsupported"); return true; }
|
||||
if (RXPowerSavingCLI::set(command + 15,
|
||||
_active_sf ? _active_sf : getSpreadFactor(), _active_sf ? _active_bw : getBandwidth(),
|
||||
config, rxpsControl(), reply, 160)) markDirty();
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
if (strcmp(command, "get radio") == 0) {
|
||||
char freq[16], bw[16];
|
||||
strcpy(freq, StrHelper::ftoa(getFreq()));
|
||||
strcpy(bw, StrHelper::ftoa3(getBandwidth()));
|
||||
sprintf(reply, "> %s,%s,%d,%d", freq, bw, (uint32_t)getSpreadFactor(), (uint32_t)getCodingRate());
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set radio ", 10) == 0) {
|
||||
char tmp[132];
|
||||
strcpy(tmp, &command[10]);
|
||||
const char *parts[4];
|
||||
int num = mesh::Utils::parseTextParts(tmp, parts, 4);
|
||||
float freq = num > 0 ? strtof(parts[0], nullptr) : 0.0f;
|
||||
float bw = num > 1 ? strtof(parts[1], nullptr) : 0.0f;
|
||||
uint8_t sf = num > 2 ? atoi(parts[2]) : 0;
|
||||
uint8_t cr = num > 3 ? atoi(parts[3]) : 0;
|
||||
if (freq >= 150.0f && freq <= 2500.0f && sf >= 5 && sf <= 12 && cr >= 5 && cr <= 8 && bw >= 7.0f && bw <= 500.0f) {
|
||||
setSpreadFactor(sf);
|
||||
setCodingRate(cr);
|
||||
setFreq(freq);
|
||||
setBandwidth(bw);
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
// the RXPS timing is in symbols: a new SF/BW can make it invalid
|
||||
auto* rxps = getRxPowerSavingConfig();
|
||||
const bool timing_ok = !rxps || !rxps->enabled || normalizeRxPowerSavingConfig(
|
||||
rxps, sf, bw, rxPowerSavingCaptureCost(rxpsControl()), rxPowerSavingTransition(rxpsControl()));
|
||||
if (!timing_ok && rxpsControl()) {
|
||||
rxpsControl()->setRxPowerSaving(false, rxps->rx_us, rxps->sleep_us);
|
||||
rxpsControl()->setRxPowerSavingConfigError(true);
|
||||
}
|
||||
strcpy(reply, timing_ok ? "OK - reboot to apply" : "OK - reboot to apply; RXPS continuous: invalid timing");
|
||||
#else
|
||||
strcpy(reply, "OK - reboot to apply");
|
||||
#endif
|
||||
} else {
|
||||
strcpy(reply, "Error, invalid radio params");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (strcmp(command, "get freq") == 0) {
|
||||
sprintf(reply, "> %s", StrHelper::ftoa(getFreq()));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (strcmp(command, "get af") == 0) {
|
||||
sprintf(reply, "> %s", StrHelper::ftoa(getAirtimeFactor()));
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set af ", 7) == 0) {
|
||||
char* end;
|
||||
float af = strtof(&command[7], &end);
|
||||
if (end == &command[7] || !looksLikeANumber(&command[7]) || af < 0 || af > 9) {
|
||||
strcpy(reply, "ERROR: af must be 0-9");
|
||||
} else {
|
||||
setAirtimeFactor(af);
|
||||
strcpy(reply, "OK");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (strcmp(command, "get dutycycle") == 0) {
|
||||
float dc = 100.0f / (getAirtimeFactor() + 1.0f);
|
||||
int dc_int = (int)dc;
|
||||
int dc_frac = (int)((dc - dc_int) * 10.0f + 0.5f);
|
||||
sprintf(reply, "> %d.%d%%", dc_int, dc_frac);
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set dutycycle ", 14) == 0) {
|
||||
float dc = atof(&command[14]);
|
||||
if (!looksLikeANumber(&command[14]) || dc < 1 || dc > 100) {
|
||||
strcpy(reply, "ERROR: dutycycle must be 1-100");
|
||||
} else {
|
||||
setAirtimeFactor((100.0f / dc) - 1.0f);
|
||||
float actual = 100.0f / (getAirtimeFactor() + 1.0f);
|
||||
int a_int = (int)actual;
|
||||
int a_frac = (int)((actual - a_int) * 10.0f + 0.5f);
|
||||
sprintf(reply, "OK - %d.%d%%", a_int, a_frac);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (strcmp(command, "get int.thresh") == 0) {
|
||||
sprintf(reply, "> %d", (uint32_t) getIntThresh());
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set int.thresh ", 15) == 0) {
|
||||
setIntThresh(atoi(&command[15]));
|
||||
strcpy(reply, "OK");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (strcmp(command, "get cad") == 0) {
|
||||
sprintf(reply, "> %s", isCadEnabled() ? "on" : "off");
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set cad ", 8) == 0) {
|
||||
setCadEnabled(memcmp(&command[8], "on", 2) == 0);
|
||||
strcpy(reply, "OK");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (strcmp(command, "get radio.rxgain") == 0) {
|
||||
sprintf(reply, "> %s", getRxGain() != 0 ? "on" : "off");
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set radio.rxgain ", 17) == 0) {
|
||||
bool enabled = memcmp(&command[17], "on", 2) == 0;
|
||||
setRxGain(enabled);
|
||||
if (radio_driver.setRxBoostedGainMode(enabled)) {
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error: unsupported");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (memcmp(command, "get tx", 6) == 0 && (command[6] == 0 || command[6] == ' ')) {
|
||||
sprintf(reply, "> %d", (int32_t) getTxPower());
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set tx ", 7) == 0) {
|
||||
setTxPower(atoi(&command[7]));
|
||||
radio_driver.setTxPower(getTxPower());
|
||||
strcpy(reply, "OK");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (strcmp(command, "get rxdelay") == 0) {
|
||||
sprintf(reply, "> %s", StrHelper::ftoa(getRxDelay()));
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set rxdelay ", 12) == 0) {
|
||||
float db = atof(&command[12]);
|
||||
if (db >= 0 && db <= 20.0f) {
|
||||
setRxDelay(db);
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error, must be 0-20");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (strcmp(command, "get agc.reset.interval") == 0) {
|
||||
sprintf(reply, "> %d", (uint32_t) getAgcResetInt());
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set agc.reset.interval ", 23) == 0) {
|
||||
int secs = atoi(&command[23]);
|
||||
secs = constrain(secs, 0, 255 * 4);
|
||||
setAgcResetInt((uint16_t) secs);
|
||||
sprintf(reply, "OK - interval rounded to %d", (uint32_t) getAgcResetInt());
|
||||
return true;
|
||||
}
|
||||
|
||||
if (strcmp(command, "get path.hash.mode") == 0) {
|
||||
sprintf(reply, "> %d", (uint32_t)getHashMode());
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set path.hash.mode ", 19) == 0) {
|
||||
const char* config = command + 19;
|
||||
uint8_t mode = atoi(config);
|
||||
if (mode < 3) {
|
||||
setHashMode(mode);
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error, must be 0,1, or 2");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (strcmp(command, "get multi.acks") == 0) {
|
||||
sprintf(reply, "> %d", (uint32_t) getMultiAcks());
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set multi.acks ", 15) == 0) {
|
||||
setMultiAcks(atoi(&command[15]));
|
||||
strcpy(reply, "OK");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (strcmp(command, "get txdelay") == 0) {
|
||||
sprintf(reply, "> %s", StrHelper::ftoa(getFloodTxDelay()));
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set txdelay ", 12) == 0) {
|
||||
float f = atof(&command[12]);
|
||||
if (f >= 0 && f <= 2.0f) {
|
||||
setFloodTxDelay(f);
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error, must be 0-2");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (strcmp(command, "get direct.txdelay") == 0) {
|
||||
sprintf(reply, "> %s", StrHelper::ftoa(getDirectTxDelay()));
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set direct.txdelay ", 19) == 0) {
|
||||
float f = atof(&command[19]);
|
||||
if (f >= 0 && f <= 2.0f) {
|
||||
setDirectTxDelay(f);
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error, must be 0-2");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
return false; // not handled
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
#pragma once
|
||||
#include "ConfigSerializer.h"
|
||||
#include "KeyValueStore.h"
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
#include "radiolib/RXPowerSaving.h"
|
||||
#endif
|
||||
|
||||
class CommonRadioPrefs : public ConfigSerializer, public KeyValueStore {
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
uint8_t _active_sf = 0; // what the radio runs now (tempradio differs from prefs)
|
||||
float _active_bw = 0;
|
||||
#endif
|
||||
protected:
|
||||
CommonRadioPrefs() { }
|
||||
public:
|
||||
virtual float getFreq() const = 0;
|
||||
virtual void setFreq(float f) = 0;
|
||||
|
||||
virtual float getBandwidth() const = 0;
|
||||
virtual void setBandwidth(float bw) = 0;
|
||||
|
||||
virtual uint8_t getSpreadFactor() const = 0;
|
||||
virtual void setSpreadFactor(uint8_t sf) = 0;
|
||||
|
||||
virtual uint8_t getCodingRate() const = 0;
|
||||
virtual void setCodingRate(uint8_t cr) = 0;
|
||||
|
||||
virtual float getAirtimeFactor() const = 0;
|
||||
virtual void setAirtimeFactor(float af) = 0;
|
||||
|
||||
virtual bool isCadEnabled() const = 0;
|
||||
virtual void setCadEnabled(bool en) = 0;
|
||||
|
||||
virtual uint8_t getIntThresh() const = 0;
|
||||
virtual void setIntThresh(uint8_t t) = 0;
|
||||
|
||||
virtual uint8_t getRxGain() const = 0;
|
||||
virtual void setRxGain(uint8_t g) = 0;
|
||||
|
||||
virtual int8_t getTxPower() const = 0;
|
||||
virtual void setTxPower(int8_t dbm) = 0;
|
||||
|
||||
virtual float getRxDelay() const = 0;
|
||||
virtual void setRxDelay(float d) = 0;
|
||||
|
||||
virtual uint16_t getAgcResetInt() const = 0;
|
||||
virtual void setAgcResetInt(uint16_t secs) = 0;
|
||||
|
||||
virtual uint8_t getHashMode() const = 0;
|
||||
virtual void setHashMode(uint8_t m) = 0;
|
||||
|
||||
virtual uint8_t getMultiAcks() const = 0;
|
||||
virtual void setMultiAcks(uint8_t m) = 0;
|
||||
|
||||
virtual float getFloodTxDelay() const = 0;
|
||||
virtual void setFloodTxDelay(float d) = 0;
|
||||
|
||||
virtual float getDirectTxDelay() const = 0;
|
||||
virtual void setDirectTxDelay(float d) = 0;
|
||||
|
||||
virtual uint8_t getFEMRxGain() const = 0;
|
||||
virtual void setFEMRxGain(uint8_t g) = 0;
|
||||
|
||||
virtual uint8_t getFEMTxGain() const = 0;
|
||||
virtual void setFEMTxGain(uint8_t g) = 0;
|
||||
|
||||
bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply);
|
||||
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
// CUSTOM (TeTeHacko): RXPS, see radiolib/RXPowerSaving.h. Prefs that carry an
|
||||
// RXPS config override getRxPowerSavingConfig(); apply after every change of
|
||||
// the radio's SF/BW (the timing is in symbols).
|
||||
virtual RxPowerSavingConfig* getRxPowerSavingConfig() { return nullptr; }
|
||||
bool applyRxPowerSaving(uint8_t sf, float bw);
|
||||
bool isRxPowerSavingCalibrationActive() const;
|
||||
#endif
|
||||
|
||||
bool setByKey(const char* key, const char* value) override; // for dynamic key/value access
|
||||
bool getByKey(const char* key, char* value, size_t max_len) override;
|
||||
};
|
||||
@@ -0,0 +1,327 @@
|
||||
#pragma once
|
||||
#include <cstdint> // For uint8_t, uint32_t
|
||||
#include <helpers/ConfigSerializer.h>
|
||||
#include <helpers/CommonRadioPrefs.h>
|
||||
#include <helpers/CommonGpsPrefs.h>
|
||||
#include <helpers/DynamicConfigSerializer.h>
|
||||
|
||||
#define TELEM_MODE_DENY 0
|
||||
#define TELEM_MODE_ALLOW_FLAGS 1 // use contact.flags
|
||||
#define TELEM_MODE_ALLOW_ALL 2
|
||||
|
||||
#define ADVERT_LOC_NONE 0
|
||||
#define ADVERT_LOC_SHARE 1
|
||||
|
||||
class NodePrefs : public ConfigSerializer { // persisted to file
|
||||
public:
|
||||
float airtime_factor = 0;
|
||||
char node_name[32];
|
||||
double node_lat = 0, node_lon = 0;
|
||||
float freq = 0;
|
||||
uint8_t sf = 0;
|
||||
uint8_t cr = 0;
|
||||
uint8_t multi_acks = 0;
|
||||
uint8_t manual_add_contacts = 0;
|
||||
float bw = 0;
|
||||
int8_t tx_power_dbm = 0;
|
||||
uint8_t telemetry_mode_base = 0;
|
||||
uint8_t telemetry_mode_loc = 0;
|
||||
uint8_t telemetry_mode_env = 0;
|
||||
float rx_delay_base = 0;
|
||||
float tx_delay_factor = 0;
|
||||
float direct_tx_delay_factor = 0;
|
||||
uint32_t ble_pin = 0;
|
||||
char ble_name[32] = {0};
|
||||
uint8_t advert_loc_policy = 0;
|
||||
uint8_t buzzer_quiet = 0;
|
||||
uint8_t vibe_quiet = 0;
|
||||
uint8_t gps_enabled = 0; // GPS enabled flag (0=disabled, 1=enabled)
|
||||
uint32_t gps_interval = 0; // GPS read interval in seconds
|
||||
uint32_t gps_period = 0; // periodic acquisition interval in seconds
|
||||
int32_t gps_fence = -1; // GPS_GUARD fence in metres, 0 = off, -1 = build default
|
||||
int32_t gps_first_fix = -1; // first-fix timeout in seconds, 0 = no limit, -1 = build default
|
||||
uint8_t gps_guard = 1; // GPS_GUARD on/off
|
||||
uint8_t autoadd_config = 0; // bitmask for auto-add contacts config
|
||||
uint8_t rx_boosted_gain = 0; // SX126x RX boosted gain mode (0=power saving, 1=boosted)
|
||||
uint8_t radio_fem_rxgain = 0; // external LoRa FEM RX gain (LNA)
|
||||
uint8_t radio_fem_txgain = 0; // external LoRa FEM TX gain (low by default)
|
||||
uint8_t _client_repeat = 0; // DEPRECATED -> use repeat.disable_fwd
|
||||
uint8_t path_hash_mode = 0; // which path mode to use when sending
|
||||
uint8_t autoadd_max_hops = 0; // 0 = no limit, 1 = direct (0 hops), N = up to N-1 hops (max 64)
|
||||
uint8_t cad_enabled = 0;
|
||||
uint8_t interference_threshold = 0;
|
||||
uint8_t agc_reset_interval = 0; // secs / 4
|
||||
char default_scope_name[31];
|
||||
uint8_t default_scope_key[16];
|
||||
float tz_offset = 0;
|
||||
float adc_multiplier = 0; // battery ADC multiplier, 0 = board default
|
||||
float ina_shunt_mohm = 0; // CUSTOM (TeTeHacko): INA shunt in mOhm, 0 = build default
|
||||
#ifdef ENABLE_WIFI_INTERFACE
|
||||
#ifndef WIFI_SSID
|
||||
#define WIFI_SSID ""
|
||||
#endif
|
||||
char wifi_ssid[33] = {0}; // if empty, the compile-time WIFI_SSID is used
|
||||
char wifi_pwd[64] = {0};
|
||||
uint8_t wifi_enabled = 1; // enabled by default to allow wifi only builds to work. wifi won't be started if ssid is empty
|
||||
// use ssid from prefs, or fallback to ssid from build flags
|
||||
const char* getWifiSSID() const { return wifi_ssid[0] ? wifi_ssid : WIFI_SSID; }
|
||||
#endif
|
||||
#ifdef DISPLAY_CLASS
|
||||
#ifndef UI_SHOW_CLOCK
|
||||
#define UI_SHOW_CLOCK 0
|
||||
#endif
|
||||
#ifndef AUTO_OFF_MILLIS
|
||||
#define AUTO_OFF_MILLIS 15000
|
||||
#endif
|
||||
#ifndef EINK_MAX_PARTIAL_REFRESH
|
||||
#define EINK_MAX_PARTIAL_REFRESH 0
|
||||
#endif
|
||||
uint8_t ui_show_clock = UI_SHOW_CLOCK;
|
||||
uint32_t ui_auto_off_delay = AUTO_OFF_MILLIS / 1000;
|
||||
int32_t ui_backlight_delay = 5;
|
||||
#if defined(BACKLIGHT_BTN)
|
||||
uint8_t ui_backlight_on_keys = 0;
|
||||
#else
|
||||
uint8_t ui_backlight_on_keys = 1;
|
||||
#endif
|
||||
uint8_t ui_backlight_on_msgs = 0;
|
||||
#ifdef UI_SCREENOFF_BLANK
|
||||
uint8_t ui_auto_off_blank = 1;
|
||||
#else
|
||||
uint8_t ui_auto_off_blank = 0;
|
||||
#endif
|
||||
uint8_t ui_auto_off_keep_msgs = 1;
|
||||
uint8_t ui_max_partial = EINK_MAX_PARTIAL_REFRESH;
|
||||
uint8_t ui_nd_name = 1;
|
||||
#ifdef PIN_GPS_SWITCH
|
||||
uint8_t ui_gps_action = 1;
|
||||
#else
|
||||
uint8_t ui_gps_action = 0;
|
||||
#endif
|
||||
#endif
|
||||
|
||||
private:
|
||||
class RadioPrefs : public CommonRadioPrefs {
|
||||
NodePrefs* _parent;
|
||||
protected:
|
||||
void structure() override {
|
||||
def("freq", _parent->freq);
|
||||
def("bw", _parent->bw);
|
||||
def("sf", _parent->sf);
|
||||
def("cr", _parent->cr);
|
||||
def("cad", _parent->cad_enabled);
|
||||
def("int_thr", _parent->interference_threshold);
|
||||
def("rxgain", _parent->rx_boosted_gain);
|
||||
def("fem_rxgain", _parent->radio_fem_rxgain); // fem_rxgain WAS mapped to wrong JSON property previously
|
||||
def("fem_txgain", _parent->radio_fem_txgain);
|
||||
def("tx", _parent->tx_power_dbm);
|
||||
def("af", _parent->airtime_factor);
|
||||
def("rxdelay", _parent->rx_delay_base);
|
||||
def("f_txdelay", _parent->tx_delay_factor);
|
||||
def("d_txdelay", _parent->direct_tx_delay_factor);
|
||||
def("agc_int", _parent->agc_reset_interval);
|
||||
def("hash_mode", _parent->path_hash_mode);
|
||||
def("multi_ack", _parent->multi_acks);
|
||||
}
|
||||
public:
|
||||
RadioPrefs(NodePrefs* parent) : _parent(parent) { }
|
||||
|
||||
// CommonRadioPrefs interface
|
||||
float getFreq() const override { return _parent->freq; }
|
||||
void setFreq(float f) override { _parent->freq = f; markDirty(); }
|
||||
float getBandwidth() const override { return _parent->bw; }
|
||||
void setBandwidth(float bw) override { _parent->bw = bw; markDirty(); }
|
||||
uint8_t getSpreadFactor() const override { return _parent->sf; }
|
||||
void setSpreadFactor(uint8_t sf) override { _parent->sf = sf; markDirty(); }
|
||||
uint8_t getCodingRate() const override { return _parent->cr; }
|
||||
void setCodingRate(uint8_t cr) override { _parent->cr = cr; markDirty(); }
|
||||
float getAirtimeFactor() const override { return _parent->airtime_factor; }
|
||||
void setAirtimeFactor(float af) override { _parent->airtime_factor = af; markDirty(); }
|
||||
bool isCadEnabled() const override { return _parent->cad_enabled; }
|
||||
void setCadEnabled(bool en) override { _parent->cad_enabled = en; markDirty(); }
|
||||
uint8_t getIntThresh() const override { return _parent->interference_threshold; }
|
||||
void setIntThresh(uint8_t t) override { _parent->interference_threshold = t; markDirty(); }
|
||||
uint8_t getRxGain() const override { return _parent->rx_boosted_gain; }
|
||||
void setRxGain(uint8_t g) override { _parent->rx_boosted_gain = g; markDirty(); }
|
||||
int8_t getTxPower() const override { return _parent->tx_power_dbm; }
|
||||
void setTxPower(int8_t dbm) override { _parent->tx_power_dbm = dbm; markDirty(); }
|
||||
float getRxDelay() const override { return _parent->rx_delay_base; }
|
||||
void setRxDelay(float d) override { _parent->rx_delay_base = d; markDirty(); }
|
||||
uint16_t getAgcResetInt() const override { return _parent->agc_reset_interval * 4; }
|
||||
void setAgcResetInt(uint16_t secs) override { _parent->agc_reset_interval = secs / 4; markDirty(); }
|
||||
uint8_t getHashMode() const override { return _parent->path_hash_mode; }
|
||||
void setHashMode(uint8_t m) override { _parent->path_hash_mode = m; markDirty(); }
|
||||
uint8_t getMultiAcks() const override { return _parent->multi_acks; }
|
||||
void setMultiAcks(uint8_t m) override { _parent->multi_acks = m; markDirty(); }
|
||||
float getFloodTxDelay() const override { return _parent->tx_delay_factor; }
|
||||
void setFloodTxDelay(float d) override { _parent->tx_delay_factor = d; markDirty(); }
|
||||
float getDirectTxDelay() const override { return _parent->direct_tx_delay_factor; }
|
||||
void setDirectTxDelay(float d) override { _parent->direct_tx_delay_factor = d; markDirty(); }
|
||||
uint8_t getFEMRxGain() const override { return _parent->radio_fem_rxgain; }
|
||||
void setFEMRxGain(uint8_t g) override { _parent->radio_fem_rxgain = g; markDirty(); }
|
||||
uint8_t getFEMTxGain() const override { return _parent->radio_fem_txgain; }
|
||||
void setFEMTxGain(uint8_t g) override { _parent->radio_fem_txgain = g; markDirty(); }
|
||||
};
|
||||
RadioPrefs radio;
|
||||
|
||||
class GPSPrefs : public CommonGpsPrefs {
|
||||
NodePrefs* _parent;
|
||||
protected:
|
||||
void structure() override {
|
||||
def("en", _parent->gps_enabled); // boolean
|
||||
def("int", _parent->gps_interval); // interval in seconds
|
||||
def("period", _parent->gps_period); // periodic acquisition interval in seconds
|
||||
def("adv_loc", _parent->advert_loc_policy);
|
||||
def("ffix", _parent->gps_first_fix);
|
||||
#ifdef GPS_GUARD
|
||||
def("fence", _parent->gps_fence);
|
||||
def("guard", _parent->gps_guard);
|
||||
#endif
|
||||
}
|
||||
public:
|
||||
GPSPrefs(NodePrefs* parent) : _parent(parent) { }
|
||||
bool isGpsEnabled() const override { return _parent->gps_enabled; }
|
||||
void setGpsEnabled(bool enabled) override { _parent->gps_enabled = enabled; markDirty(); }
|
||||
uint32_t getGpsPeriod() const override { return _parent->gps_period; }
|
||||
void setGpsPeriod(uint32_t seconds) override { _parent->gps_period = seconds; markDirty(); }
|
||||
bool getFirstFixTimeout(uint32_t& seconds) const override {
|
||||
if (_parent->gps_first_fix < 0) return false;
|
||||
seconds = (uint32_t)_parent->gps_first_fix;
|
||||
return true;
|
||||
}
|
||||
void setFirstFixTimeout(uint32_t seconds) override { _parent->gps_first_fix = (int32_t)seconds; markDirty(); }
|
||||
bool getGuardFence(uint32_t& metres) const override {
|
||||
if (_parent->gps_fence < 0) return false;
|
||||
metres = (uint32_t)_parent->gps_fence;
|
||||
return true;
|
||||
}
|
||||
void setGuardFence(uint32_t metres) override { _parent->gps_fence = (int32_t)metres; markDirty(); }
|
||||
bool getGuardEnabled(bool& enabled) const override {
|
||||
enabled = _parent->gps_guard != 0;
|
||||
return true;
|
||||
}
|
||||
void setGuardEnabled(bool enabled) override { _parent->gps_guard = enabled ? 1 : 0; markDirty(); }
|
||||
};
|
||||
GPSPrefs gps;
|
||||
|
||||
class RepeatPrefs : public ConfigSerializer { // COPIED from CommonCLI (for now)
|
||||
public:
|
||||
uint8_t disable_fwd = 1;
|
||||
protected:
|
||||
void structure() override {
|
||||
def("disable", disable_fwd);
|
||||
//def("f_max", flood_max);
|
||||
//def("f_max_uns", flood_max_unscoped);
|
||||
//def("f_max_adv", flood_max_advert);
|
||||
//def("loop", loop_detect);
|
||||
}
|
||||
};
|
||||
RepeatPrefs repeat;
|
||||
|
||||
class CompanionPrefs : public ConfigSerializer {
|
||||
NodePrefs* _parent;
|
||||
protected:
|
||||
void structure() override {
|
||||
def("auto_max", _parent->autoadd_max_hops); // 0 = no limit, 1 = direct (0 hops), N = up to N-1 hops (max 64)
|
||||
def("defs_nm", _parent->default_scope_name, sizeof(_parent->default_scope_name));
|
||||
def("defs_key", (void *) _parent->default_scope_key, sizeof(_parent->default_scope_key));
|
||||
def("pin", _parent->ble_pin);
|
||||
def("ble_name", _parent->ble_name, sizeof(_parent->ble_name));
|
||||
def("buzz_q", _parent->buzzer_quiet);
|
||||
def("vibe_q", _parent->vibe_quiet);
|
||||
def("auto_add", _parent->autoadd_config); // bitmask for auto-add contacts config
|
||||
def("man_add", _parent->manual_add_contacts);
|
||||
def("tel_base", _parent->telemetry_mode_base);
|
||||
def("tel_loc", _parent->telemetry_mode_loc);
|
||||
def("tel_env", _parent->telemetry_mode_env);
|
||||
def("tz_offset", _parent->tz_offset);
|
||||
def("adc_mult", _parent->adc_multiplier);
|
||||
def("ina_shunt", _parent->ina_shunt_mohm);
|
||||
}
|
||||
public:
|
||||
CompanionPrefs(NodePrefs* parent) : _parent(parent) { }
|
||||
};
|
||||
CompanionPrefs companion;
|
||||
|
||||
DynamicConfigSerializer custom;
|
||||
|
||||
#ifdef ENABLE_WIFI_INTERFACE
|
||||
class WiFiPrefs : public ConfigSerializer {
|
||||
NodePrefs* _parent;
|
||||
protected:
|
||||
void structure() override {
|
||||
def("ssid", _parent->wifi_ssid, sizeof(_parent->wifi_ssid));
|
||||
def("pwd", _parent->wifi_pwd, sizeof(_parent->wifi_pwd));
|
||||
def("enabled", _parent->wifi_enabled);
|
||||
}
|
||||
public:
|
||||
WiFiPrefs(NodePrefs* parent) : _parent(parent) { }
|
||||
};
|
||||
WiFiPrefs wifi;
|
||||
#endif
|
||||
|
||||
#ifdef DISPLAY_CLASS
|
||||
class UI_Prefs : public ConfigSerializer {
|
||||
NodePrefs* _parent;
|
||||
protected:
|
||||
void structure() override {
|
||||
def("show_clock", _parent->ui_show_clock);
|
||||
def("auto_off", _parent->ui_auto_off_delay);
|
||||
def("bl_dly", _parent->ui_backlight_delay);
|
||||
def("bl_keys", _parent->ui_backlight_on_keys);
|
||||
def("bl_msgs", _parent->ui_backlight_on_msgs);
|
||||
def("max_partial", _parent->ui_max_partial);
|
||||
def("off_blank", _parent->ui_auto_off_blank);
|
||||
def("off_keep_msgs", _parent->ui_auto_off_keep_msgs);
|
||||
def("nd_name", _parent->ui_nd_name);
|
||||
def("gps_act", _parent->ui_gps_action);
|
||||
}
|
||||
public:
|
||||
UI_Prefs(NodePrefs* parent) : _parent(parent) {}
|
||||
};
|
||||
UI_Prefs ui;
|
||||
#endif
|
||||
|
||||
protected:
|
||||
void structure() override {
|
||||
def("name", node_name, sizeof(node_name));
|
||||
//def("adv_int", advert_interval);
|
||||
//def("f_adv_int", flood_advert_interval);
|
||||
def("lat", node_lat);
|
||||
def("lon", node_lon);
|
||||
def("radio", radio);
|
||||
def("gps", gps);
|
||||
def("repeat", repeat);
|
||||
def("comp", companion);
|
||||
def("custom", custom);
|
||||
#ifdef ENABLE_WIFI_INTERFACE
|
||||
def("wifi", wifi);
|
||||
#endif
|
||||
#ifdef DISPLAY_CLASS
|
||||
def("ui", ui);
|
||||
#endif
|
||||
}
|
||||
public:
|
||||
NodePrefs() : radio(this), gps(this), companion(this), custom(&radio)
|
||||
#ifdef ENABLE_WIFI_INTERFACE
|
||||
, wifi(this)
|
||||
#endif
|
||||
#ifdef DISPLAY_CLASS
|
||||
, ui(this)
|
||||
#endif
|
||||
{
|
||||
node_name[0] = 0;
|
||||
default_scope_name[0] = 0;
|
||||
memset(default_scope_key, 0, sizeof(default_scope_key));
|
||||
}
|
||||
// new accessor methods
|
||||
bool isRepeatEn() const { return repeat.disable_fwd == 0; }
|
||||
void setRepeatEn(bool en) { repeat.disable_fwd = en ? 0 : 1; }
|
||||
|
||||
CommonRadioPrefs* getRadioPrefs() { return &radio; }
|
||||
CommonGpsPrefs* getGpsPrefs() { return &gps; }
|
||||
KeyValueStore* getCustom() { return &custom; }
|
||||
|
||||
bool isDirty() const override { return ConfigSerializer::isDirty() || radio.isDirty() || gps.isDirty() || custom.isDirty(); }
|
||||
void clearDirty() override { ConfigSerializer::clearDirty(); radio.clearDirty(); gps.clearDirty(); custom.clearDirty(); }
|
||||
};
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "ConfigSerializer.h"
|
||||
#include <stdlib.h> // atoi/atol/atof (Arduino.h pulls this in on-device, native builds do not)
|
||||
|
||||
bool ConfigSerializer::saveSerial(Stream& s) {
|
||||
Context context(&s, OP::WRITE);
|
||||
@@ -23,7 +24,9 @@ static bool is_whitespace(char c) {
|
||||
return c == ' ' || c == '\t' || c == '\r' || c == '\n';
|
||||
}
|
||||
static bool is_key_char(char c) {
|
||||
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_';
|
||||
// digits are allowed: keys like gr_1hop contain one, otherwise loadSerial
|
||||
// fails at that key and prefs stop reloading after a reboot
|
||||
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_';
|
||||
}
|
||||
static bool is_value_char(char c) {
|
||||
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || c == '-' || c == '.';
|
||||
@@ -62,6 +65,7 @@ int ConfigSerializer::Context::readNext() {
|
||||
case EXPECT_COMMA_OR_KEY:
|
||||
if (c == ',') { rd_mode = EXPECT_KEY; return TOK_WHITESPACE; }
|
||||
case EXPECT_KEY:
|
||||
if (rd_len == 0 && c == '}') { rd_mode = EXPECT_COMMA_OR_KEY_OR_CLOSE; return TOK_END_OBJ; } // empty object, eg. 'custom:{}'
|
||||
if (rd_len > 0 && c == ':') { rd_buf[rd_len] = 0; rd_len = 0; rd_mode = EXPECT_VAL_OR_OBJ; return TOK_KEY; }
|
||||
if (rd_len == 0 && is_whitespace(c)) return TOK_WHITESPACE;
|
||||
if (rd_len < CONFIG_MAX_KEYLEN-1 && is_key_char(c)) { rd_buf[rd_len++] = c; return TOK_WHITESPACE; }
|
||||
|
||||
@@ -17,7 +17,9 @@
|
||||
class ConfigSerializer {
|
||||
bool _first;
|
||||
int8_t _depth;
|
||||
bool _dirty = false;
|
||||
|
||||
protected:
|
||||
enum OP { READ, WRITE };
|
||||
|
||||
class Context {
|
||||
@@ -38,13 +40,14 @@ class ConfigSerializer {
|
||||
const char* getToken() const { return rd_buf; }
|
||||
bool keyMatch(int8_t depth, const char* key) { return strcmp(key, _keys[depth]) == 0; }
|
||||
void setKey(uint8_t depth, const char* key) { strcpy(_keys[depth], key); }
|
||||
const char* getKey(uint8_t depth) { return _keys[depth]; }
|
||||
};
|
||||
|
||||
Context* _context = NULL;
|
||||
int8_t getDepth() const { return _depth; }
|
||||
|
||||
void writeComma();
|
||||
|
||||
protected:
|
||||
ConfigSerializer() { }
|
||||
|
||||
void def(const char* key, char* value, size_t max_len); // max_len inclusive of null
|
||||
@@ -62,7 +65,12 @@ protected:
|
||||
|
||||
virtual void structure() = 0;
|
||||
|
||||
void markDirty() { _dirty = true; }
|
||||
|
||||
public:
|
||||
bool loadSerial(Stream& s);
|
||||
bool saveSerial(Stream& s);
|
||||
|
||||
virtual bool isDirty() const { return _dirty; }
|
||||
virtual void clearDirty() { _dirty = false; }
|
||||
};
|
||||
@@ -26,6 +26,18 @@ struct ContactInfo {
|
||||
return shared_secret;
|
||||
}
|
||||
|
||||
bool isFav() const { return flags & 0x01; }
|
||||
bool isTelemBaseAllowed() const { return flags & 0x02; }
|
||||
bool isTelemLocAllowed() const { return flags & 0x04; }
|
||||
bool isTelemEnvAllowed() const { return flags & 0x08; }
|
||||
bool isRemoteCLIAllowed() const { return flags & 0x10; }
|
||||
bool isEmptySlot() const {
|
||||
for (int i = 0; i < PUB_KEY_SIZE; i++) {
|
||||
if (id.pub_key[i] != 0) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
mutable uint8_t shared_secret[PUB_KEY_SIZE];
|
||||
};
|
||||
@@ -0,0 +1,97 @@
|
||||
#include "DynamicConfigSerializer.h"
|
||||
#include <Utils.h>
|
||||
|
||||
#define PROP_SEP_CHAR '|'
|
||||
#define PROP_SEP_STR "|"
|
||||
#define KEY_SEP_CHAR ':'
|
||||
#define KEY_SEP_STR ":"
|
||||
|
||||
bool DynamicConfigSerializer::setByKeyPrv(const char* key, const char* value) {
|
||||
if (_fallback && _fallback->setByKey(key, value)) return true;
|
||||
|
||||
// TODO: guard for bad chars (':' or '|')
|
||||
char tmp[MAX_DYNAMIC_CONFG];
|
||||
strcpy(tmp, _config); // make a (modifiable) copy
|
||||
|
||||
const char* parts[8];
|
||||
int n = mesh::Utils::parseTextParts(tmp, parts, 8, PROP_SEP_CHAR);
|
||||
|
||||
// add/replace in _config[]
|
||||
char new_config[MAX_DYNAMIC_CONFG];
|
||||
new_config[0] = 0;
|
||||
|
||||
int keylen = strlen(key);
|
||||
for (int i = 0; i < n; i++) {
|
||||
const char* item = parts[i];
|
||||
if (item[keylen] == KEY_SEP_CHAR && memcmp(item, key, keylen) == 0) {
|
||||
// key exists, so omit old value from this pass (will append new value at end)
|
||||
} else {
|
||||
if (new_config[0]) {
|
||||
strcat(new_config, PROP_SEP_STR);
|
||||
}
|
||||
strcat(new_config, item);
|
||||
}
|
||||
}
|
||||
// now append new key/value (if it fits)
|
||||
if (strlen(new_config) + strlen(key) + strlen(value) + 2 < sizeof(_config)-1) {
|
||||
if (new_config[0]) {
|
||||
strcat(new_config, PROP_SEP_STR);
|
||||
}
|
||||
strcat(new_config, key);
|
||||
strcat(new_config, KEY_SEP_STR);
|
||||
strcat(new_config, value);
|
||||
strcpy(_config, new_config); // commit new serialized string
|
||||
return true;
|
||||
}
|
||||
return false; // didn't fit in _config[]
|
||||
}
|
||||
|
||||
bool DynamicConfigSerializer::setByKey(const char* key, const char* value) {
|
||||
if (setByKeyPrv(key, value)) {
|
||||
markDirty();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool DynamicConfigSerializer::getByKey(const char* key, char* value, size_t max_len) {
|
||||
if (_fallback && _fallback->getByKey(key, value, max_len)) return true;
|
||||
|
||||
char tmp[MAX_DYNAMIC_CONFG];
|
||||
strcpy(tmp, _config); // make a (modifiable) copy
|
||||
|
||||
const char* parts[8];
|
||||
int n = mesh::Utils::parseTextParts(tmp, parts, 8, PROP_SEP_CHAR);
|
||||
|
||||
int keylen = strlen(key);
|
||||
for (int i = 0; i < n; i++) {
|
||||
const char* item = parts[i];
|
||||
if (item[keylen] == KEY_SEP_CHAR && memcmp(item, key, keylen) == 0) {
|
||||
strncpy(value, &item[keylen+1], max_len);
|
||||
value[max_len] = 0;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void DynamicConfigSerializer::structure() {
|
||||
if (_context->op() == OP::WRITE) {
|
||||
char tmp[MAX_DYNAMIC_CONFG];
|
||||
strcpy(tmp, _config); // make a (modifiable) copy
|
||||
|
||||
const char* parts[8];
|
||||
int n = mesh::Utils::parseTextParts(tmp, parts, 8, PROP_SEP_CHAR);
|
||||
|
||||
for (int i = 0; i < n; i++) {
|
||||
char* item = (char *) parts[i];
|
||||
char* eq = strchr(item, KEY_SEP_CHAR);
|
||||
if (eq) {
|
||||
*eq = 0; // replace separator with null terminator
|
||||
def(item, eq + 1, MAX_DYNAMIC_CONFG/2);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
setByKeyPrv(_context->getKey(getDepth()), _context->getToken());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
#include "ConfigSerializer.h"
|
||||
#include "KeyValueStore.h"
|
||||
|
||||
#ifndef MAX_DYNAMIC_CONFG
|
||||
#define MAX_DYNAMIC_CONFG 128
|
||||
#endif
|
||||
|
||||
class DynamicConfigSerializer : public ConfigSerializer, public KeyValueStore {
|
||||
char _config[MAX_DYNAMIC_CONFG];
|
||||
KeyValueStore* _fallback;
|
||||
|
||||
bool setByKeyPrv(const char* key, const char* value);
|
||||
|
||||
protected:
|
||||
void structure() override;
|
||||
|
||||
public:
|
||||
DynamicConfigSerializer(KeyValueStore* fallback = NULL) : _fallback(fallback) { _config[0] = 0; }
|
||||
|
||||
bool setByKey(const char* key, const char* value) override;
|
||||
bool getByKey(const char* key, char* value, size_t max_len) override;
|
||||
};
|
||||
@@ -3,6 +3,10 @@
|
||||
#include "ESP32Board.h"
|
||||
#include <target.h>
|
||||
|
||||
// The RTC backup of ESP32RTCClock, declared in ESP32Board.h.
|
||||
RTC_NOINIT_ATTR uint32_t _rtc_backup_time;
|
||||
RTC_NOINIT_ATTR uint32_t _rtc_backup_magic;
|
||||
|
||||
#if defined(ADMIN_PASSWORD) && !defined(DISABLE_WIFI_OTA) // Repeater or Room Server only
|
||||
#include <WiFi.h>
|
||||
#include <AsyncTCP.h>
|
||||
@@ -59,11 +63,13 @@ void ESP32Board::enterDeepSleep(uint32_t secs) {
|
||||
radio_driver.powerOff();
|
||||
|
||||
// Keep LoRa inactive during deepsleep
|
||||
#ifdef P_LORA_NSS
|
||||
digitalWrite(P_LORA_NSS, HIGH);
|
||||
#if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6)
|
||||
gpio_hold_en((gpio_num_t)P_LORA_NSS);
|
||||
#else
|
||||
rtc_gpio_hold_en((gpio_num_t)P_LORA_NSS);
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// Power off GPS if any
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
#include "soc/rtc.h"
|
||||
#include "esp_system.h"
|
||||
#include <driver/rtc_io.h>
|
||||
#include <helpers/KeyValueStore.h>
|
||||
|
||||
class ESP32Board : public mesh::MainBoard {
|
||||
protected:
|
||||
@@ -51,6 +52,8 @@ public:
|
||||
#endif
|
||||
}
|
||||
|
||||
void attachDynamicPrefs(KeyValueStore* prefs) { } // no-op
|
||||
|
||||
// Temperature from ESP32 MCU
|
||||
float getMCUTemperature() override {
|
||||
uint32_t raw = 0;
|
||||
@@ -66,9 +69,11 @@ public:
|
||||
virtual void powerOff() override;
|
||||
void enterDeepSleep(uint32_t secs);
|
||||
|
||||
#ifdef P_LORA_DIO_1
|
||||
uint32_t getIRQGpio() override {
|
||||
return P_LORA_DIO_1; // default for SX1262
|
||||
}
|
||||
#endif
|
||||
|
||||
void sleep(uint32_t secs) override {
|
||||
// Skip if not allow to sleep
|
||||
@@ -79,6 +84,10 @@ public:
|
||||
|
||||
// Set GPIO wakeup
|
||||
gpio_num_t wakeupPin = (gpio_num_t)getIRQGpio();
|
||||
if (wakeupPin == GPIO_NUM_NC) { // no radio IRQ pin to wake on
|
||||
delay(1);
|
||||
return;
|
||||
}
|
||||
|
||||
// Configure timer wakeup
|
||||
if (secs > 0) {
|
||||
@@ -197,19 +206,35 @@ public:
|
||||
}
|
||||
};
|
||||
|
||||
// The time ESP32RTCClock restores after a reset, in RTC memory that a reset does
|
||||
// not clear. Defined once, in ESP32Board.cpp: the inline members below run in
|
||||
// every translation unit that uses them and must all see the same backup.
|
||||
extern uint32_t _rtc_backup_time;
|
||||
extern uint32_t _rtc_backup_magic;
|
||||
#define RTC_BACKUP_MAGIC 0xAA55CC33
|
||||
#define RTC_TIME_MIN 1772323200 // 1 Mar 2026
|
||||
|
||||
class ESP32RTCClock : public mesh::RTCClock {
|
||||
public:
|
||||
ESP32RTCClock() { }
|
||||
void begin() {
|
||||
esp_reset_reason_t reason = esp_reset_reason();
|
||||
if (reason == ESP_RST_POWERON) {
|
||||
// start with some date/time in the recent past
|
||||
struct timeval tv;
|
||||
tv.tv_sec = 1715770351; // 15 May 2024, 8:50pm
|
||||
if (reason == ESP_RST_DEEPSLEEP) {
|
||||
return; // ESP-IDF preserves system time across deep sleep
|
||||
}
|
||||
// All other resets (power-on, crash, WDT, brownout) lose system time.
|
||||
// Restore from RTC backup if valid, otherwise seed with the build time
|
||||
// (stamped builds) or RTC_TIME_MIN, whichever is newer.
|
||||
uint32_t seed = FIRMWARE_BUILD_EPOCH > RTC_TIME_MIN ? FIRMWARE_BUILD_EPOCH : RTC_TIME_MIN;
|
||||
struct timeval tv;
|
||||
if (_rtc_backup_magic == RTC_BACKUP_MAGIC && _rtc_backup_time > seed) {
|
||||
tv.tv_sec = _rtc_backup_time;
|
||||
} else {
|
||||
tv.tv_sec = seed;
|
||||
}
|
||||
tv.tv_usec = 0;
|
||||
settimeofday(&tv, NULL);
|
||||
}
|
||||
}
|
||||
uint32_t getCurrentTime() override {
|
||||
time_t _now;
|
||||
time(&_now);
|
||||
@@ -220,6 +245,16 @@ public:
|
||||
tv.tv_sec = time;
|
||||
tv.tv_usec = 0;
|
||||
settimeofday(&tv, NULL);
|
||||
_rtc_backup_time = time;
|
||||
_rtc_backup_magic = RTC_BACKUP_MAGIC;
|
||||
}
|
||||
void tick() override {
|
||||
time_t now;
|
||||
time(&now);
|
||||
if (now > RTC_TIME_MIN && (uint32_t)now != _rtc_backup_time) {
|
||||
_rtc_backup_time = (uint32_t)now;
|
||||
_rtc_backup_magic = RTC_BACKUP_MAGIC;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
#include "FairnessLimiter.h"
|
||||
|
||||
#include <MeshCore.h>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
uint8_t FairnessLimiter::peekGroup(const uint8_t* hash) {
|
||||
auto i = group_idx(hash);
|
||||
if (i >= GROUP_MAP_SIZE) {
|
||||
return 0;
|
||||
}
|
||||
return group_map[i];
|
||||
}
|
||||
|
||||
bool FairnessLimiter::takeGroup(const uint8_t* hash) {
|
||||
auto i = group_idx(hash);
|
||||
bool allow = false;
|
||||
if (i < GROUP_MAP_SIZE && group_map[i] > 0) {
|
||||
group_map[i]--;
|
||||
allow = true;
|
||||
} else {
|
||||
denied_group++;
|
||||
if (i < GROUP_MAP_SIZE && group_deny[i] != 0xFFFF) group_deny[i]++;
|
||||
}
|
||||
MESH_DEBUG_PRINTLN("FAIR, group=%02X allow=%u", (uint32_t)hash[0], (uint32_t)allow);
|
||||
return allow;
|
||||
}
|
||||
|
||||
void FairnessLimiter::refillGroup() {
|
||||
for (int i = 0; i < GROUP_MAP_SIZE; i++) {
|
||||
if (group_map[i] < group_cap) {
|
||||
group_map[i]++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t FairnessLimiter::peekSenderNormal(const uint8_t* hash) {
|
||||
auto i = sender_normal_idx(hash);
|
||||
if (i >= SENDER_NORMAL_MAP_SIZE) {
|
||||
return 0;
|
||||
}
|
||||
return sender_normal_map[i];
|
||||
}
|
||||
|
||||
bool FairnessLimiter::takeSenderNormal(const uint8_t* hash) {
|
||||
auto i = sender_normal_idx(hash);
|
||||
bool allow = false;
|
||||
if (i < SENDER_NORMAL_MAP_SIZE && sender_normal_map[i] > 0) {
|
||||
sender_normal_map[i]--;
|
||||
allow = true;
|
||||
} else {
|
||||
denied_sender_normal++;
|
||||
if (i < SENDER_NORMAL_MAP_SIZE && sender_normal_deny[i] != 0xFFFF) sender_normal_deny[i]++;
|
||||
}
|
||||
MESH_DEBUG_PRINTLN("FAIR, sender=%02X prio=normal allow=%u", (uint32_t)hash[0], (uint32_t)allow);
|
||||
return allow;
|
||||
}
|
||||
|
||||
void FairnessLimiter::refillSenderNormal() {
|
||||
for (int i = 0; i < SENDER_NORMAL_MAP_SIZE; i++) {
|
||||
if (sender_normal_map[i] < sender_normal_cap) {
|
||||
sender_normal_map[i]++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t FairnessLimiter::peekSenderLow(const uint8_t* hash) {
|
||||
auto i = sender_low_idx(hash);
|
||||
if (i >= SENDER_LOW_MAP_SIZE) {
|
||||
return 0;
|
||||
}
|
||||
return sender_low_map[i];
|
||||
}
|
||||
|
||||
bool FairnessLimiter::takeSenderLow(const uint8_t* hash) {
|
||||
auto i = sender_low_idx(hash);
|
||||
bool allow = false;
|
||||
if (i < SENDER_LOW_MAP_SIZE && sender_low_map[i] > 0) {
|
||||
sender_low_map[i]--;
|
||||
allow = true;
|
||||
} else {
|
||||
denied_sender_low++;
|
||||
if (i < SENDER_LOW_MAP_SIZE && sender_low_deny[i] != 0xFFFF) sender_low_deny[i]++;
|
||||
}
|
||||
MESH_DEBUG_PRINTLN("FAIR, sender=%02X prio=low allow=%u", (uint32_t)hash[0], (uint32_t)allow);
|
||||
return allow;
|
||||
}
|
||||
|
||||
void FairnessLimiter::refillSenderLow() {
|
||||
for (int i = 0; i < SENDER_LOW_MAP_SIZE; i++) {
|
||||
if (sender_low_map[i] < sender_low_cap) {
|
||||
sender_low_map[i]++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool FairnessLimiter::allowPacket(const mesh::Packet* pkt, uint32_t now_ms) {
|
||||
last_shed = FAIR_SHED_NONE;
|
||||
// Don't limit versions we don't understand.
|
||||
if (pkt->getPayloadVer() != PAYLOAD_VER_1) {
|
||||
return true;
|
||||
}
|
||||
|
||||
#if FAIRNESS_ALLOW_DIRECT
|
||||
// Don't limit direct
|
||||
if (!pkt->isRouteFlood()) {
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
|
||||
uint8_t hash[1] = { 0x00 };
|
||||
auto type = pkt->getPayloadType();
|
||||
|
||||
// Per-origin advert window -- flood adverts only, ahead of the buckets. The
|
||||
// payload starts with the origin's public key.
|
||||
if (type == PAYLOAD_TYPE_ADVERT && pkt->isRouteFlood() && pkt->payload_len >= ADVERT_WINDOW_KEY_LEN
|
||||
&& !advert_window.allow(pkt->payload, now_ms)) {
|
||||
denied_window++;
|
||||
MESH_DEBUG_PRINTLN("FAIR, advert window origin=%02X%02X%02X%02X dry=%u", (uint32_t)pkt->payload[0],
|
||||
(uint32_t)pkt->payload[1], (uint32_t)pkt->payload[2], (uint32_t)pkt->payload[3],
|
||||
(uint32_t)dry_run);
|
||||
return shed(FAIR_SHED_WINDOW);
|
||||
}
|
||||
|
||||
if (!buckets_enabled) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Packets by group channel hash
|
||||
if (type == PAYLOAD_TYPE_GRP_TXT || type == PAYLOAD_TYPE_GRP_DATA) {
|
||||
if (pkt->payload_len < 1) return true; // malformed, not ours to judge
|
||||
hash[0] = pkt->payload[0];
|
||||
return takeGroup(hash) || shed(FAIR_SHED_GROUP);
|
||||
}
|
||||
|
||||
// Packets with a plaintext 1-byte src hash at payload[1] (see Mesh.cpp,
|
||||
// PAYLOAD_TYPE_PATH/REQ/RESPONSE/TXT_MSG parse: dest_hash, then src_hash)
|
||||
if (type == PAYLOAD_TYPE_PATH || type == PAYLOAD_TYPE_REQ || type == PAYLOAD_TYPE_RESPONSE ||
|
||||
type == PAYLOAD_TYPE_TXT_MSG || type == PAYLOAD_TYPE_ANON_REQ) {
|
||||
if (pkt->payload_len < 2) return true; // malformed, not ours to judge
|
||||
hash[0] = pkt->payload[1];
|
||||
return takeSenderNormal(hash) || shed(FAIR_SHED_SENDER);
|
||||
}
|
||||
|
||||
if (type == PAYLOAD_TYPE_ADVERT) {
|
||||
if (pkt->payload_len < 1) return true; // malformed, not ours to judge
|
||||
hash[0] = pkt->payload[0]; // first byte of sender pub key
|
||||
return takeSenderLow(hash) || shed(FAIR_SHED_ADVERT);
|
||||
}
|
||||
|
||||
// Not classified (allowed through):
|
||||
// PAYLOAD_TYPE_ACK, PAYLOAD_TYPE_TRACE, PAYLOAD_TYPE_MULTIPART,
|
||||
// PAYLOAD_TYPE_CONTROL, PAYLOAD_TYPE_RAW_CUSTOM
|
||||
return true;
|
||||
}
|
||||
|
||||
// Append the busiest deny buckets of one category to `out`. Repeated max-scan
|
||||
// over a small array (<=128) -- picks up to `top` entries, busiest first, and
|
||||
// skips a bucket once emitted by nulling a scratch copy. Returns chars written.
|
||||
static int fmt_deny_cat(char* out, int max_len, const char* label,
|
||||
uint16_t* deny, int size, uint8_t cap, int top) {
|
||||
int w = snprintf(out, max_len, "%s(cap %u):", label, (unsigned)cap);
|
||||
if (w < 0 || w >= max_len) return (w < 0) ? 0 : max_len - 1;
|
||||
bool any = false;
|
||||
for (int n = 0; n < top; n++) {
|
||||
int best = -1;
|
||||
uint16_t best_v = 0;
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (deny[i] > best_v) { best_v = deny[i]; best = i; }
|
||||
}
|
||||
if (best < 0) break; // no non-zero left
|
||||
int adv = snprintf(out + w, max_len - w, " %02x=%u", (unsigned)best, (unsigned)best_v);
|
||||
if (adv < 0 || adv >= max_len - w) { out[w] = 0; break; } // no room, stop clean
|
||||
w += adv;
|
||||
any = true;
|
||||
deny[best] = 0; // consumed for the next pass; `deny` is formatGrid's scratch copy
|
||||
}
|
||||
if (!any) {
|
||||
int adv = snprintf(out + w, max_len - w, " -");
|
||||
if (adv > 0 && adv < max_len - w) w += adv;
|
||||
}
|
||||
return w;
|
||||
}
|
||||
|
||||
int FairnessLimiter::formatGrid(char* out, int max_len) const {
|
||||
if (max_len <= 0) return 0;
|
||||
// Work on scratch copies so the busiest-first selection can null entries as
|
||||
// it consumes them without disturbing the live counters. Plain locals (~448 B
|
||||
// on the stack) -- called only from the main-loop CLI path, never an ISR.
|
||||
uint16_t g[GROUP_MAP_SIZE], sn[SENDER_NORMAL_MAP_SIZE], sl[SENDER_LOW_MAP_SIZE];
|
||||
memcpy(g, group_deny, sizeof(g));
|
||||
memcpy(sn, sender_normal_deny, sizeof(sn));
|
||||
memcpy(sl, sender_low_deny, sizeof(sl));
|
||||
|
||||
int w = 0;
|
||||
w += fmt_deny_cat(out + w, max_len - w, "group", g, GROUP_MAP_SIZE, group_cap, 6);
|
||||
if (w < max_len - 2) { int a = snprintf(out + w, max_len - w, " | "); if (a > 0) w += a; }
|
||||
w += fmt_deny_cat(out + w, max_len - w, "sender", sn, SENDER_NORMAL_MAP_SIZE, sender_normal_cap, 6);
|
||||
if (w < max_len - 2) { int a = snprintf(out + w, max_len - w, " | "); if (a > 0) w += a; }
|
||||
w += fmt_deny_cat(out + w, max_len - w, "advert", sl, SENDER_LOW_MAP_SIZE, sender_low_cap, 4);
|
||||
return w;
|
||||
}
|
||||
Loaded 100 of 580 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user