mirror of
https://github.com/meshtastic/firmware.git
synced 2025-12-14 06:42:34 +00:00
Compare commits
491 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6dec6af5dc | ||
|
|
11444621ae | ||
|
|
98f1b3296c | ||
|
|
26c43e7091 | ||
|
|
9b9447858a | ||
|
|
3151cfb064 | ||
|
|
c327fee986 | ||
|
|
a4f53270e8 | ||
|
|
a7456a1126 | ||
|
|
8381512ce4 | ||
|
|
20a669029b | ||
|
|
f2e6c6de58 | ||
|
|
8fa44c3590 | ||
|
|
f5b7c33d4e | ||
|
|
be8e663d39 | ||
|
|
0d4a9748e3 | ||
|
|
bd477f0fb2 | ||
|
|
5317895a5e | ||
|
|
542b8b26ce | ||
|
|
64da384fc1 | ||
|
|
a595fc4642 | ||
|
|
ac135be8cd | ||
|
|
5ea59a1c4d | ||
|
|
8bafd87b76 | ||
|
|
6b40e9a5e0 | ||
|
|
a2f6fd9298 | ||
|
|
bc604fc9ba | ||
|
|
9baaa13897 | ||
|
|
65e53be8b0 | ||
|
|
7f5283e95d | ||
|
|
ae4ab48ddc | ||
|
|
afccf1da02 | ||
|
|
fc07c7c01f | ||
|
|
aeb906414f | ||
|
|
a6c6b45576 | ||
|
|
13806cce93 | ||
|
|
e7eee0995a | ||
|
|
5687bd09c6 | ||
|
|
f3db895832 | ||
|
|
dd2ffe5d14 | ||
|
|
ec10e784e1 | ||
|
|
649faa1d93 | ||
|
|
669f96b367 | ||
|
|
996821d18e | ||
|
|
2e172b019e | ||
|
|
3df05cd5c1 | ||
|
|
8bb85cdc69 | ||
|
|
9f6e23754c | ||
|
|
5a7cfdffb3 | ||
|
|
caafddfdfa | ||
|
|
ee0e31be97 | ||
|
|
f1da6469a3 | ||
|
|
68e57dd3a7 | ||
|
|
2504311671 | ||
|
|
aa29315624 | ||
|
|
e3bcb87cf0 | ||
|
|
2530dc44c7 | ||
|
|
70a8fe30b7 | ||
|
|
30e538e5ed | ||
|
|
58dbc3c702 | ||
|
|
210c904604 | ||
|
|
27fdab7c8d | ||
|
|
ba3e1abb5e | ||
|
|
ce194e2162 | ||
|
|
595166db8e | ||
|
|
38d9e34a66 | ||
|
|
c1e0977db3 | ||
|
|
b4f32e7645 | ||
|
|
6bb0c95c95 | ||
|
|
4e958c9230 | ||
|
|
64cf1890f2 | ||
|
|
6a857b00db | ||
|
|
6d60a061bc | ||
|
|
6a09ddef18 | ||
|
|
d48e803b7b | ||
|
|
9061b3d8c3 | ||
|
|
2839539c6c | ||
|
|
f77a1798f3 | ||
|
|
664b558a36 | ||
|
|
c1865f127c | ||
|
|
3a69539192 | ||
|
|
cfcaf28ace | ||
|
|
d9e93f3944 | ||
|
|
60470211e5 | ||
|
|
c5851a4a0c | ||
|
|
0c0b2446b7 | ||
|
|
ce9352fd23 | ||
|
|
375ae5fe77 | ||
|
|
665d35196d | ||
|
|
9757f9ae53 | ||
|
|
e45d0c4dcf | ||
|
|
5c9f22bc18 | ||
|
|
d8287e9cdb | ||
|
|
c66e064f42 | ||
|
|
364fc84aaa | ||
|
|
fe4f86bc84 | ||
|
|
982b2e33ff | ||
|
|
8190098bb8 | ||
|
|
c99411311b | ||
|
|
da8a048dce | ||
|
|
b4de495154 | ||
|
|
aaa6af3f38 | ||
|
|
b11b322581 | ||
|
|
60b38215ce | ||
|
|
53e68515dd | ||
|
|
7676ae9184 | ||
|
|
b385feefa5 | ||
|
|
fc50b4abc0 | ||
|
|
0104a2eb3a | ||
|
|
23fdc9d1a9 | ||
|
|
ea4a678308 | ||
|
|
6566c4f15e | ||
|
|
6f39f1740f | ||
|
|
7b61bdbfd2 | ||
|
|
8e65db19b0 | ||
|
|
698fcdad36 | ||
|
|
c25d6e974f | ||
|
|
35aae48932 | ||
|
|
f8afa2703f | ||
|
|
cd903dceb9 | ||
|
|
5843c6f25e | ||
|
|
3005373760 | ||
|
|
7678540a93 | ||
|
|
463666aec5 | ||
|
|
5847f94ece | ||
|
|
09855b76ef | ||
|
|
f4d476d160 | ||
|
|
d88d4be63e | ||
|
|
154114e900 | ||
|
|
03f019dea2 | ||
|
|
a47524b762 | ||
|
|
fd2f5a5ba4 | ||
|
|
e66b2234f6 | ||
|
|
f35b15b09c | ||
|
|
99dac51b9d | ||
|
|
656faf4ce9 | ||
|
|
d9ab6986ad | ||
|
|
514d45c219 | ||
|
|
94b7fc76c1 | ||
|
|
e9923ac257 | ||
|
|
60ad1793e4 | ||
|
|
96a15bec3b | ||
|
|
fba676fc07 | ||
|
|
9ad14ad98b | ||
|
|
477c62082d | ||
|
|
82169d4115 | ||
|
|
362d5452d5 | ||
|
|
92e5a15399 | ||
|
|
114e0c4ada | ||
|
|
075ff26499 | ||
|
|
d65f2ede81 | ||
|
|
4a9248a451 | ||
|
|
1c6092c430 | ||
|
|
0e9ed1e82f | ||
|
|
02ce0558b9 | ||
|
|
63110f0134 | ||
|
|
d8db4449be | ||
|
|
fda98bbf58 | ||
|
|
aadba1f694 | ||
|
|
2c8d152885 | ||
|
|
37c598833c | ||
|
|
e80de4eba0 | ||
|
|
e382a181f7 | ||
|
|
85f69cb908 | ||
|
|
112a94e572 | ||
|
|
13307c502f | ||
|
|
8a1754efe8 | ||
|
|
8caa075bc6 | ||
|
|
d5deb49d20 | ||
|
|
575a15e135 | ||
|
|
dc7469c64b | ||
|
|
f54b18f733 | ||
|
|
db66e4dc00 | ||
|
|
47e614c7d6 | ||
|
|
03cb3c2145 | ||
|
|
a8d4b5479d | ||
|
|
de37e1bbab | ||
|
|
f0b8f10665 | ||
|
|
88b91de197 | ||
|
|
f22bb34c07 | ||
|
|
2d1cb7a43a | ||
|
|
dc169675e2 | ||
|
|
99f8253637 | ||
|
|
f3244caac1 | ||
|
|
6edaadf5d8 | ||
|
|
1f668046a0 | ||
|
|
cb2aa3b29f | ||
|
|
8ccd59a7d8 | ||
|
|
ddfdae64bf | ||
|
|
21a90a42e5 | ||
|
|
712d6e5c1e | ||
|
|
f02a2c0853 | ||
|
|
00d55c9daa | ||
|
|
a05e45f84b | ||
|
|
e650033f2c | ||
|
|
846fc14b4a | ||
|
|
a8a5e036f5 | ||
|
|
009f05b61d | ||
|
|
d8a6f82459 | ||
|
|
185fe8520a | ||
|
|
ce9bac34d6 | ||
|
|
e80673ed15 | ||
|
|
bdbaf9c655 | ||
|
|
7473a6c27a | ||
|
|
71a4cfefd5 | ||
|
|
4919129bbc | ||
|
|
a02175cec0 | ||
|
|
63affdd2e7 | ||
|
|
351687e5cd | ||
|
|
739f497bbd | ||
|
|
2d2ed591e9 | ||
|
|
871a85d688 | ||
|
|
a5f05019db | ||
|
|
e124d2094f | ||
|
|
5d874cd43b | ||
|
|
9f6cdadd3e | ||
|
|
6a3853ef35 | ||
|
|
9ea65c6793 | ||
|
|
8d14e97dfa | ||
|
|
1c63a70673 | ||
|
|
8022f3b920 | ||
|
|
420b7d48d9 | ||
|
|
5915669f6f | ||
|
|
52b01db306 | ||
|
|
a0d6ecb331 | ||
|
|
0271b02d50 | ||
|
|
9f61c78c0e | ||
|
|
4db176867b | ||
|
|
4b5cfaf9ba | ||
|
|
c014c1bafe | ||
|
|
96594516af | ||
|
|
bed20bf1fa | ||
|
|
4e5a445d8b | ||
|
|
99437d931e | ||
|
|
5166717298 | ||
|
|
49b5738f4f | ||
|
|
c753ea7cd1 | ||
|
|
5b1488ddf0 | ||
|
|
a34cfb0ee0 | ||
|
|
d8ff605d32 | ||
|
|
8031c47602 | ||
|
|
e522e47544 | ||
|
|
ed0f79b683 | ||
|
|
de1337d351 | ||
|
|
1b34a0c6d8 | ||
|
|
313380381b | ||
|
|
f56ff2ca20 | ||
|
|
da2ef0ac61 | ||
|
|
6a3033fa85 | ||
|
|
f3a1c5e679 | ||
|
|
a96c8fd4db | ||
|
|
da3ed9926b | ||
|
|
fd386d9d7f | ||
|
|
5d1614989e | ||
|
|
bae73a9526 | ||
|
|
f4b1678535 | ||
|
|
943517a1e4 | ||
|
|
03999e9d56 | ||
|
|
d5f177b1ee | ||
|
|
fdaed7e323 | ||
|
|
d39e775c95 | ||
|
|
829e0b6e26 | ||
|
|
1656c8d0cb | ||
|
|
2770cc7de3 | ||
|
|
48de631e04 | ||
|
|
66b11bcbd7 | ||
|
|
cda7487cbe | ||
|
|
e8f6504ec4 | ||
|
|
8f1b26bdda | ||
|
|
5bd3e4bcd0 | ||
|
|
fb3b62f8f0 | ||
|
|
e89fe2f7d9 | ||
|
|
16812c3ee4 | ||
|
|
c9cb293bf2 | ||
|
|
8e2e154cdd | ||
|
|
b7505ab575 | ||
|
|
cc47e29fac | ||
|
|
608f8349d9 | ||
|
|
3ecd93dcf6 | ||
|
|
dd0209b192 | ||
|
|
ae92567383 | ||
|
|
9f2646ba03 | ||
|
|
925e46da8c | ||
|
|
a6475ce848 | ||
|
|
9149912a2d | ||
|
|
2dadb4d7a2 | ||
|
|
1897d4703c | ||
|
|
a25cead7d7 | ||
|
|
3d919b21f6 | ||
|
|
d2de04d5b2 | ||
|
|
a753c942b9 | ||
|
|
9dd88281af | ||
|
|
e75561016b | ||
|
|
e2cbccb133 | ||
|
|
0271df0657 | ||
|
|
e05e324a7c | ||
|
|
71041e8674 | ||
|
|
c65b518432 | ||
|
|
6ba960ce47 | ||
|
|
8bf4919576 | ||
|
|
cca4867987 | ||
|
|
7aa47cf93b | ||
|
|
3089de79ee | ||
|
|
6b020149f3 | ||
|
|
34fae52e98 | ||
|
|
976bdad067 | ||
|
|
26d3ef529e | ||
|
|
53c3d9baa2 | ||
|
|
2a6858fa34 | ||
|
|
5440cbec6a | ||
|
|
19f5a5ef79 | ||
|
|
ef831a0b4d | ||
|
|
efc239533c | ||
|
|
ef1463a6a9 | ||
|
|
95e952b896 | ||
|
|
db72faca5e | ||
|
|
6961853ed7 | ||
|
|
5ec5248fe4 | ||
|
|
14fdd33972 | ||
|
|
140e29840a | ||
|
|
d1d318fad5 | ||
|
|
dfb6c0bb20 | ||
|
|
7339abbab5 | ||
|
|
27db0e27e8 | ||
|
|
a0b43b9a95 | ||
|
|
b6a202d68e | ||
|
|
125035d546 | ||
|
|
9f05ad2927 | ||
|
|
86ae69d360 | ||
|
|
c12fb69ca2 | ||
|
|
8b911aba7f | ||
|
|
2fa595523f | ||
|
|
190a3c2d6b | ||
|
|
1bf9d052fc | ||
|
|
e7b99b0d78 | ||
|
|
96313ee1c4 | ||
|
|
3e356e5866 | ||
|
|
1cc24de787 | ||
|
|
e6875d559c | ||
|
|
b73dd5b23b | ||
|
|
28d21ecdcc | ||
|
|
42298abfad | ||
|
|
c4a1fe0f36 | ||
|
|
0396f8f968 | ||
|
|
f1b840dede | ||
|
|
4da5d79e88 | ||
|
|
fc0c9bcfe3 | ||
|
|
32d0368f59 | ||
|
|
8bfe9fa8fc | ||
|
|
f10ad07f97 | ||
|
|
95df7dd8dc | ||
|
|
dcd1f7478a | ||
|
|
c2be6c4068 | ||
|
|
101eef5495 | ||
|
|
933d5424da | ||
|
|
ecf528f9b6 | ||
|
|
9b309fe0a0 | ||
|
|
29fd8dc7a5 | ||
|
|
624b95782d | ||
|
|
4fa25042c8 | ||
|
|
9f9cb030ad | ||
|
|
1d9290afc0 | ||
|
|
ad2f639195 | ||
|
|
07b4eea037 | ||
|
|
79c61cf0e0 | ||
|
|
80268ea56a | ||
|
|
bb9f595b8b | ||
|
|
2ad314f150 | ||
|
|
916e62398d | ||
|
|
4735b3ff5b | ||
|
|
cfd6483ea5 | ||
|
|
4f7a25f562 | ||
|
|
4176d79ee9 | ||
|
|
fad496378c | ||
|
|
e084699704 | ||
|
|
50213d8323 | ||
|
|
763276a2c8 | ||
|
|
71fcdba017 | ||
|
|
08227e79d0 | ||
|
|
5a4fab2506 | ||
|
|
31eb2f5337 | ||
|
|
82c1752d85 | ||
|
|
49a13bbfd3 | ||
|
|
0096f54ae9 | ||
|
|
5af122b39d | ||
|
|
4e106f4098 | ||
|
|
1f1d683f4f | ||
|
|
a8f64c3cc8 | ||
|
|
968a2d7fbc | ||
|
|
1fab9c5aac | ||
|
|
22bca31ce3 | ||
|
|
48c045a253 | ||
|
|
e9ca7792eb | ||
|
|
b1a55b4576 | ||
|
|
dd7452ad96 | ||
|
|
d7d8188093 | ||
|
|
62a893c760 | ||
|
|
a2ba9d3c44 | ||
|
|
22720e9f63 | ||
|
|
11b79a942d | ||
|
|
3c3e722181 | ||
|
|
fce31560c6 | ||
|
|
074ac33b8a | ||
|
|
2982e197e0 | ||
|
|
f69ddf168b | ||
|
|
8d985cfd37 | ||
|
|
4693302d82 | ||
|
|
814c126e67 | ||
|
|
a7d153abcb | ||
|
|
1b265eb48d | ||
|
|
94e80d3b44 | ||
|
|
f1ec95f49b | ||
|
|
7ee2643e9a | ||
|
|
2ab34357d5 | ||
|
|
b53392ab73 | ||
|
|
803d2dfefb | ||
|
|
6a54bbcf2a | ||
|
|
02dfe7564f | ||
|
|
b704911603 | ||
|
|
0193c281ef | ||
|
|
59086fd477 | ||
|
|
88a704c4d3 | ||
|
|
9f49f90acd | ||
|
|
93f69d5a94 | ||
|
|
cceecf5f8e | ||
|
|
e5d2d24e2c | ||
|
|
eb40013ddc | ||
|
|
dda946d933 | ||
|
|
178e800969 | ||
|
|
dec4870649 | ||
|
|
97f5a7c5fe | ||
|
|
7ff42b89a6 | ||
|
|
44de3bd179 | ||
|
|
15cb599cd1 | ||
|
|
038b7c9c91 | ||
|
|
724e39bc92 | ||
|
|
def86131f0 | ||
|
|
8f1c1a9049 | ||
|
|
3f3a1a11df | ||
|
|
64f6c0f5c0 | ||
|
|
7cd60d859e | ||
|
|
db11d9280c | ||
|
|
ca03110932 | ||
|
|
b8b503cb0a | ||
|
|
bb885a5110 | ||
|
|
bebaa838c4 | ||
|
|
7fa9d09d9f | ||
|
|
7bc299573f | ||
|
|
e0a1855429 | ||
|
|
5e75beff3f | ||
|
|
4f7e85c1a4 | ||
|
|
5ad30caf67 | ||
|
|
8f26ae240a | ||
|
|
d445cbe083 | ||
|
|
12599849db | ||
|
|
3c9c01189d | ||
|
|
4f3a9d8646 | ||
|
|
0c7c3f17e5 | ||
|
|
5b0451f25c | ||
|
|
8f3b33c84c | ||
|
|
2fdb75efdf | ||
|
|
fbd12e1929 | ||
|
|
ffe95f62ab | ||
|
|
3e4ccef992 | ||
|
|
309e7be00c | ||
|
|
f0f6c4950b | ||
|
|
16998ebd8d | ||
|
|
b77c068881 | ||
|
|
e94227cddd | ||
|
|
fe3cbeed3a | ||
|
|
2061706c11 | ||
|
|
a0b6d57591 | ||
|
|
3673f95fe5 | ||
|
|
c67b53b969 | ||
|
|
562b227c73 | ||
|
|
169d85d0fa | ||
|
|
bd77d47215 | ||
|
|
e40524baf0 | ||
|
|
31f735ae1f | ||
|
|
9232dfcccf | ||
|
|
fab616a15e | ||
|
|
2419ebb04e | ||
|
|
88c576798b | ||
|
|
db766f18ed | ||
|
|
f9a805e3d4 | ||
|
|
e5f9a752d8 | ||
|
|
20b41836e2 | ||
|
|
c55df4d1cc | ||
|
|
908b1020c0 | ||
|
|
78470ed3f5 | ||
|
|
4ce7df295e |
38
.github/ISSUE_TEMPLATE/bug-report-or-feature-proposal.md
vendored
Normal file
38
.github/ISSUE_TEMPLATE/bug-report-or-feature-proposal.md
vendored
Normal file
@@ -0,0 +1,38 @@
|
||||
---
|
||||
name: Bug report or feature proposal
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
Please - if you just have a question (i.e. not a bug report or a feature proposal), post in our [forum](https://meshtastic.discourse.group/) instead.
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Device info:**
|
||||
- Device model: [e.g. TBEAM]
|
||||
- Software Version [e.g. 0.7.8]
|
||||
|
||||
**Smartphone information (if relevant):**
|
||||
- Device: [e.g. iPhone6]
|
||||
- OS: [e.g. iOS8.1]
|
||||
- App Version [e.g. 0.7.2]
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
13
.github/pull_request_template.md
vendored
Normal file
13
.github/pull_request_template.md
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
## Thank you for sending in a pull request, here's some tips to get started!
|
||||
|
||||
(Please delete all these tips and replace with your text)
|
||||
|
||||
- Before starting on some new big chunk of code, it it is optional but highly recommended to open an issue first
|
||||
to say "hey, I think this idea X should be implemented and I'm starting work on it. My general plan is Y, any feedback
|
||||
is appreciated." This will allow other devs to potentially save you time by not accidentially duplicating work etc...
|
||||
- Please do not check in files that don't have real changes
|
||||
- Please do not reformat lines that you didn't have to change the code on
|
||||
- We recommend using the [Visual Studio Code](https://platformio.org/install/ide?install=vscode) editor,
|
||||
because automatically follows our indentation rules and it's auto reformatting will not cause spurious changes to lines.
|
||||
- If your PR fixes a bug, mention "fixes #bugnum" somewhere in your pull request description.
|
||||
- If your other co-developers have comments on your PR please tweak as needed.
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -6,6 +6,5 @@ main/credentials.h
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
*.code-workspace
|
||||
3
.gitmodules
vendored
3
.gitmodules
vendored
@@ -1,3 +1,6 @@
|
||||
[submodule "proto"]
|
||||
path = proto
|
||||
url = https://github.com/meshtastic/Meshtastic-protobufs.git
|
||||
[submodule "sdk-nrfxlib"]
|
||||
path = sdk-nrfxlib
|
||||
url = https://github.com/nrfconnect/sdk-nrfxlib.git
|
||||
|
||||
32
.vscode/launch.json
vendored
32
.vscode/launch.json
vendored
@@ -1,32 +0,0 @@
|
||||
// AUTOMATICALLY GENERATED FILE. PLEASE DO NOT MODIFY IT MANUALLY
|
||||
|
||||
// PIO Unified Debugger
|
||||
//
|
||||
// Documentation: https://docs.platformio.org/page/plus/debugging.html
|
||||
// Configuration: https://docs.platformio.org/page/projectconf/section_env_debug.html
|
||||
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"type": "platformio-debug",
|
||||
"request": "launch",
|
||||
"name": "PIO Debug",
|
||||
"executable": "/home/kevinh/development/meshtastic/meshtastic-esp32/.pio/build/tbeam/firmware.elf",
|
||||
"toolchainBinDir": "/home/kevinh/.platformio/packages/toolchain-xtensa32/bin",
|
||||
"preLaunchTask": {
|
||||
"type": "PlatformIO",
|
||||
"task": "Pre-Debug"
|
||||
},
|
||||
"internalConsoleOptions": "openOnSessionStart"
|
||||
},
|
||||
{
|
||||
"type": "platformio-debug",
|
||||
"request": "launch",
|
||||
"name": "PIO Debug (skip Pre-Debug)",
|
||||
"executable": "/home/kevinh/development/meshtastic/meshtastic-esp32/.pio/build/tbeam/firmware.elf",
|
||||
"toolchainBinDir": "/home/kevinh/.platformio/packages/toolchain-xtensa32/bin",
|
||||
"internalConsoleOptions": "openOnSessionStart"
|
||||
}
|
||||
]
|
||||
}
|
||||
10
.vscode/settings.json
vendored
10
.vscode/settings.json
vendored
@@ -50,8 +50,16 @@
|
||||
"cassert": "cpp"
|
||||
},
|
||||
"cSpell.words": [
|
||||
"Blox",
|
||||
"HFSR",
|
||||
"Meshtastic",
|
||||
"NEMAGPS",
|
||||
"Ublox",
|
||||
"bkpt",
|
||||
"cfsr",
|
||||
"descs",
|
||||
"protobufs"
|
||||
"ocrypto",
|
||||
"protobufs",
|
||||
"wifi"
|
||||
]
|
||||
}
|
||||
53
README.md
53
README.md
@@ -1,10 +1,10 @@
|
||||
# Meshtastic-esp32
|
||||
# Meshtastic-device
|
||||
|
||||
This is the device side code for the [meshtastic.org](https://www.meshtastic.org) project.
|
||||
|
||||

|
||||
|
||||
Meshtastic is a project that lets you use
|
||||
Meshtastic™ is a project that lets you use
|
||||
inexpensive GPS mesh radios as an extensible, super long battery life mesh GPS communicator. These radios are great for hiking, skiing, paragliding -
|
||||
essentially any hobby where you don't have reliable internet access. Each member of your private mesh can always see the location and distance of all other
|
||||
members and any text messages sent to your group chat.
|
||||
@@ -14,20 +14,44 @@ will optionally work with your phone, but no phone is required.
|
||||
|
||||
Typical time between recharging the radios should be about eight days.
|
||||
|
||||
This project is currently early-alpha, but if you have questions please [join our discussion forum](https://meshtastic.discourse.group/).
|
||||
This project is is currently in beta-testing - if you have questions please [join our discussion forum](https://meshtastic.discourse.group/).
|
||||
|
||||
This software is 100% open source and developed by a group of hobbyist experimenters. No warranty is provided, if you'd like to improve it - we'd love your help. Please post in the chat.
|
||||
|
||||
## Supported hardware
|
||||
|
||||
We currently support three models of radios. The [TTGO T-Beam](https://www.aliexpress.com/item/4000119152086.html), [TTGO LORA32](https://www.banggood.com/LILYGO-TTGO-LORA32-868Mhz-SX1276-ESP32-Oled-Display-bluetooth-WIFI-Lora-Development-Module-Board-p-1248652.html?cur_warehouse=UK) and the [Heltec LoRa 32](https://heltec.org/project/wifi-lora-32/). Most users should buy the T-Beam and an 18650 battery (total cost less than \$35). Make sure to buy the frequency range which is legal for your country (915MHz for US/JP/AU/NZ, 470MHz for CN, 433MHz and 870MHz for EU). Getting a version that includes a screen is optional, but highly recommended.
|
||||
We currently support three models of radios.
|
||||
|
||||
See (meshtastic.org) for 3D printable cases.
|
||||
- TTGO T-Beam
|
||||
|
||||
- [T-Beam V1.0 w/ NEO-6M - special Meshtastic version](https://www.aliexpress.com/item/4001178678568.html) (Includes built-in OLED display and they have **preinstalled** the meshtastic software)
|
||||
- [T-Beam V1.0 w/ NEO-M8N](https://www.aliexpress.com/item/33047631119.html) (slightly better GPS)
|
||||
- 3D printable cases
|
||||
- [T-Beam V0](https://www.thingiverse.com/thing:3773717)
|
||||
- [T-Beam V1](https://www.thingiverse.com/thing:3830711)
|
||||
|
||||
- [TTGO LORA32](https://www.aliexpress.com/item/4000211331316.html) - No GPS
|
||||
|
||||
- 3D printable case
|
||||
- [TTGO LORA32 v1](https://www.thingiverse.com/thing:3385109)
|
||||
|
||||
- [Heltec LoRa 32](https://heltec.org/project/wifi-lora-32/) - No GPS
|
||||
- [3D Printable case](https://www.thingiverse.com/thing:3125854)
|
||||
|
||||
**Make sure to get the frequency for your country**
|
||||
|
||||
- US/JP/AU/NZ/CA - 915MHz
|
||||
- CN - 470MHz
|
||||
- EU - 868MHz, 433MHz
|
||||
|
||||
Getting a version that includes a screen is optional, but highly recommended.
|
||||
|
||||
## Firmware Installation
|
||||
|
||||
Prebuilt binaries for the supported radios are available in our [releases](https://github.com/meshtastic/Meshtastic-esp32/releases). Your initial installation has to happen over USB from your Mac, Windows or Linux PC. Once our software is installed, all future software updates happen over bluetooth from your phone.
|
||||
|
||||
Be **very careful** to install the correct load for your board. In particular the popular 'T-BEAM' radio from TTGO is not called 'TTGO-Lora' (that is a different board). So don't install the 'TTGO-Lora' build on a TBEAM, it won't work correctly.
|
||||
|
||||
Please post comments on our [group chat](https://meshtastic.discourse.group/) if you have problems or successes.
|
||||
|
||||
### Installing from a GUI - Windows and Mac
|
||||
@@ -40,7 +64,8 @@ Please post comments on our [group chat](https://meshtastic.discourse.group/) if
|
||||
6. In ESPHome Flasher, refresh the serial ports and select your board.
|
||||
7. Browse to the previously downloaded firmware and select the correct firmware based on the board type, country and frequency.
|
||||
8. Select Flash ESP.
|
||||
9. Once finished, the terminal should start displaying debug messages including the Bluetooth passphrase when you try connect from your phone (handy if you don’t have a screen).
|
||||
9. Once complete, “Done! Flashing is complete!” will be shown.
|
||||
10. Debug messages sent from the Meshtastic device can be viewed with a terminal program such as [PuTTY](https://www.putty.org/) (Windows only). Within PuTTY, click “Serial”, enter the “Serial line” com port (can be found at step 4), enter “Speed” as 921600, then click “Open”.
|
||||
|
||||
### Installing from a commandline
|
||||
|
||||
@@ -70,9 +95,12 @@ Hard resetting via RTS pin...
|
||||
```
|
||||
|
||||
5. cd into the directory where the release zip file was expanded.
|
||||
6. Install the correct firmware for your board with "device-install.sh firmware-_board_-_country_.bin". For instance "./device-install.sh firmware-HELTEC-US-0.0.3.bin".
|
||||
6. Install the correct firmware for your board with `device-install.sh firmware-_board_-_country_.bin`.
|
||||
- Example: `./device-install.sh firmware-HELTEC-US-0.0.3.bin`.
|
||||
7. To update run `device-update.sh firmware-_board_-_country_.bin`
|
||||
- Example: `./device-update.sh firmware-HELTEC-US-0.0.3.bin`.
|
||||
|
||||
Note: If you have previously installed meshtastic, you don't need to run this full script instead just run "esptool.py --baud 921600 write*flash 0x10000 firmware-\_board*-_country_.bin". This will be faster, also all of your current preferences will be preserved.
|
||||
Note: If you have previously installed meshtastic, you don't need to run this full script instead just run `esptool.py --baud 921600 write_flash 0x10000 firmware-_board_-_country_-_version_.bin`. This will be faster, also all of your current preferences will be preserved.
|
||||
|
||||
You should see something like this:
|
||||
|
||||
@@ -143,14 +171,13 @@ Hard resetting via RTS pin...
|
||||
7. The board will boot and show the Meshtastic logo.
|
||||
8. Please post a comment on our chat so we know if these instructions worked for you ;-). If you find bugs/have-questions post there also - we will be rapidly iterating over the next few weeks.
|
||||
|
||||
## Meshtastic Android app
|
||||
# Meshtastic Android app
|
||||
|
||||
The source code for the (optional) Meshtastic Android app is [here](https://github.com/meshtastic/Meshtastic-Android).
|
||||
The companion (optional) Meshtastic Android app is [here](https://play.google.com/store/apps/details?id=com.geeksville.mesh&referrer=utm_source%3Dgithub-dev-readme). You can also download it on Google Play.
|
||||
|
||||
Alpha test builds are current available by opting into our alpha test group. See (www.meshtastic.org) for instructions.
|
||||
# Python API
|
||||
|
||||
After our rate of change slows a bit, we will make beta builds available here (without needing to join the alphatest group):
|
||||
[](https://play.google.com/store/apps/details?id=com.geeksville.mesh&referrer=utm_source%3Dgithub%26utm_medium%3Desp32-readme%26utm_campaign%3Dmeshtastic-esp32%2520readme%26anid%3Dadmob&pcampaignid=pcampaignidMKT-Other-global-all-co-prtnr-py-PartBadge-Mar2515-1)
|
||||
We offer a [python API](https://github.com/meshtastic/Meshtastic-python) that makes it easy to use these devices to provide mesh networking for your custom projects.
|
||||
|
||||
# Development
|
||||
|
||||
|
||||
@@ -6,6 +6,10 @@ source bin/version.sh
|
||||
|
||||
COUNTRIES="US EU433 EU865 CN JP"
|
||||
#COUNTRIES=US
|
||||
#COUNTRIES=CN
|
||||
|
||||
BOARDS="ttgo-lora32-v2 ttgo-lora32-v1 tbeam heltec"
|
||||
#BOARDS=tbeam
|
||||
|
||||
OUTDIR=release/latest
|
||||
|
||||
@@ -24,23 +28,27 @@ function do_build {
|
||||
SRCBIN=.pio/build/$ENV_NAME/firmware.bin
|
||||
SRCELF=.pio/build/$ENV_NAME/firmware.elf
|
||||
rm -f $SRCBIN
|
||||
pio run --environment $ENV_NAME # -v
|
||||
|
||||
# The shell vars the build tool expects to find
|
||||
export HW_VERSION="1.0-$COUNTRY"
|
||||
export APP_VERSION=$VERSION
|
||||
export COUNTRY
|
||||
|
||||
pio run --jobs 4 --environment $ENV_NAME # -v
|
||||
cp $SRCBIN $OUTDIR/bins/firmware-$ENV_NAME-$COUNTRY-$VERSION.bin
|
||||
cp $SRCELF $OUTDIR/elfs/firmware-$ENV_NAME-$COUNTRY-$VERSION.elf
|
||||
}
|
||||
|
||||
# Make sure our submodules are current
|
||||
git submodule update
|
||||
|
||||
# Important to pull latest version of libs into all device flavors, otherwise some devices might be stale
|
||||
platformio lib update
|
||||
|
||||
for COUNTRY in $COUNTRIES; do
|
||||
|
||||
HWVERSTR="1.0-$COUNTRY"
|
||||
COMMONOPTS="-DAPP_VERSION=$VERSION -DHW_VERSION_$COUNTRY -DHW_VERSION=$HWVERSTR -Wall -Wextra -Wno-missing-field-initializers -Isrc -Os -DAXP_DEBUG_PORT=Serial"
|
||||
|
||||
export PLATFORMIO_BUILD_FLAGS="$COMMONOPTS"
|
||||
|
||||
#do_build "tbeam0.7"
|
||||
do_build "ttgo-lora32-v2"
|
||||
do_build "ttgo-lora32-v1"
|
||||
do_build "tbeam"
|
||||
do_build "heltec"
|
||||
for BOARD in $BOARDS; do
|
||||
do_build $BOARD
|
||||
done
|
||||
done
|
||||
|
||||
# keep the bins in archive also
|
||||
@@ -59,6 +67,6 @@ Generated by bin/buildall.sh -->
|
||||
XML
|
||||
|
||||
rm -f $ARCHIVEDIR/firmware-$VERSION.zip
|
||||
zip --junk-paths $ARCHIVEDIR/firmware-$VERSION.zip $OUTDIR/bins/firmware-*-$VERSION.* images/system-info.bin bin/device-install.sh
|
||||
zip --junk-paths $ARCHIVEDIR/firmware-$VERSION.zip $OUTDIR/bins/firmware-*-$VERSION.* images/system-info.bin bin/device-install.sh bin/device-update.sh
|
||||
|
||||
echo BUILT ALL
|
||||
8
bin/device-update.sh
Executable file
8
bin/device-update.sh
Executable file
@@ -0,0 +1,8 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
|
||||
FILENAME=$1
|
||||
|
||||
echo "Trying to update $FILENAME"
|
||||
esptool.py --baud 921600 write_flash 0x10000 $FILENAME
|
||||
3
bin/dump-ram-users.sh
Executable file
3
bin/dump-ram-users.sh
Executable file
@@ -0,0 +1,3 @@
|
||||
arm-none-eabi-readelf -s -e .pio/build/nrf52dk/firmware.elf | head -80
|
||||
|
||||
nm -CSr --size-sort .pio/build/nrf52dk/firmware.elf | grep '^200'
|
||||
4
bin/nrf52-console.sh
Executable file
4
bin/nrf52-console.sh
Executable file
@@ -0,0 +1,4 @@
|
||||
|
||||
|
||||
# JLinkRTTViewer
|
||||
JLinkRTTClient
|
||||
3
bin/nrf52-gdbserver.sh
Executable file
3
bin/nrf52-gdbserver.sh
Executable file
@@ -0,0 +1,3 @@
|
||||
|
||||
|
||||
JLinkGDBServerCLExe -if SWD -select USB -port 2331 -device NRF52840_XXAA
|
||||
@@ -3,4 +3,4 @@
|
||||
echo "This script requires https://jpa.kapsi.fi/nanopb/download/ version 0.4.1"
|
||||
# the nanopb tool seems to require that the .options file be in the current directory!
|
||||
cd proto
|
||||
../../nanopb-0.4.1-linux-x86/generator-bin/protoc --nanopb_out=-v:../src -I=../proto mesh.proto
|
||||
../../nanopb-0.4.1-linux-x86/generator-bin/protoc --nanopb_out=-v:../src/mesh -I=../proto mesh.proto
|
||||
|
||||
@@ -1 +1 @@
|
||||
pio device monitor -b 115200
|
||||
pio device monitor -b 921600
|
||||
|
||||
@@ -1 +1 @@
|
||||
pio device monitor -p /dev/ttyUSB1 -b 115200
|
||||
pio device monitor -p /dev/ttyUSB1 -b 921600
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
|
||||
|
||||
export VERSION=0.4.2
|
||||
export VERSION=0.7.10
|
||||
46
boards/nrf52840_dk_modified.json
Normal file
46
boards/nrf52840_dk_modified.json
Normal file
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"build": {
|
||||
"arduino": {
|
||||
"ldscript": "nrf52840_s140_v6.ld"
|
||||
},
|
||||
"core": "nRF5",
|
||||
"cpu": "cortex-m4",
|
||||
"extra_flags": "-DARDUINO_NRF52840_PCA10056 -DNRF52840_XXAA",
|
||||
"f_cpu": "64000000L",
|
||||
"hwids": [["0x239A", "0x4404"]],
|
||||
"usb_product": "SimPPR",
|
||||
"mcu": "nrf52840",
|
||||
"variant": "pca10056-rc-clock",
|
||||
"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"
|
||||
},
|
||||
"frameworks": ["arduino"],
|
||||
"name": "A modified NRF52840-DK devboard (Adafruit BSP)",
|
||||
"upload": {
|
||||
"maximum_ram_size": 248832,
|
||||
"maximum_size": 815104,
|
||||
"require_upload_port": true,
|
||||
"speed": 115200,
|
||||
"protocol": "jlink",
|
||||
"protocols": ["jlink", "nrfjprog", "stlink"]
|
||||
},
|
||||
"url": "https://meshtastic.org/",
|
||||
"vendor": "Nordic Semi"
|
||||
}
|
||||
46
boards/ppr.json
Normal file
46
boards/ppr.json
Normal file
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"build": {
|
||||
"arduino": {
|
||||
"ldscript": "nrf52840_s140_v6.ld"
|
||||
},
|
||||
"core": "nRF5",
|
||||
"cpu": "cortex-m4",
|
||||
"extra_flags": "-DARDUINO_NRF52840_PPR -DNRF52840_XXAA",
|
||||
"f_cpu": "64000000L",
|
||||
"hwids": [["0x239A", "0x4403"]],
|
||||
"usb_product": "PPR",
|
||||
"mcu": "nrf52840",
|
||||
"variant": "ppr",
|
||||
"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"
|
||||
},
|
||||
"frameworks": ["arduino"],
|
||||
"name": "Meshtastic PPR (Adafruit BSP)",
|
||||
"upload": {
|
||||
"maximum_ram_size": 248832,
|
||||
"maximum_size": 815104,
|
||||
"require_upload_port": true,
|
||||
"speed": 115200,
|
||||
"protocol": "jlink",
|
||||
"protocols": ["jlink", "nrfjprog", "stlink"]
|
||||
},
|
||||
"url": "https://meshtastic.org/",
|
||||
"vendor": "Othernet"
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
# What is Meshtastic?
|
||||
|
||||
Meshtastic is a project that lets you use
|
||||
inexpensive (\$30 ish) GPS radios as an extensible, super long battery life mesh GPS communicator. These radios are great for hiking, skiing, paragliding - essentially any hobby where you don't have reliable internet access. Each member of your private mesh can always see the location and distance of all other members and any text messages sent to your group chat.
|
||||
Meshtastic™ is a project that lets you use
|
||||
inexpensive (\$30 ish) GPS radios as an extensible, long battery life, secure, mesh GPS communicator. These radios are great for hiking, skiing, paragliding - essentially any hobby where you don't have reliable internet access. Each member of your private mesh can always see the location and distance of all other members and any text messages sent to your group chat.
|
||||
|
||||
The radios automatically create a mesh to forward packets as needed, so everyone in the group can receive messages from even the furthest member. The radios will optionally work with your phone, but no phone is required.
|
||||
|
||||
@@ -13,6 +13,7 @@ Note: Questions after reading this? See our new [forum](https://meshtastic.disco
|
||||
- Applications where closed source GPS communicators just won't cut it (it is easy to add features for glider pilots etc...)
|
||||
- Secure long-range communication within groups without depending on cellular providers
|
||||
- Finding your lost kids ;-)
|
||||
- Through our [python API](https://pypi.org/project/meshtastic/) use these inexpensive radios to easily add mesh networking to your own projects.
|
||||
|
||||
[](https://www.youtube.com/watch?v=WlNbMbVZlHI "Meshtastic early demo")
|
||||
|
||||
@@ -23,21 +24,25 @@ Not all of these features are fully implemented yet - see **important** disclaim
|
||||
- Very long battery life (should be about eight days with the beta software)
|
||||
- Built in GPS and [LoRa](https://en.wikipedia.org/wiki/LoRa) radio, but we manage the radio automatically for you
|
||||
- Long range - a few miles per node but each node will forward packets as needed
|
||||
- Secure - channels are encrypted by AES256 (But see important disclaimers below wrt this feature)
|
||||
- Shows direction and distance to all members of your channel
|
||||
- Directed or broadcast text messages for channel members
|
||||
- Open and extensible codebase supporting multiple hardware vendors - no lock in to one vendor
|
||||
- Communication API for bluetooth devices (such as our Android app) to use the mesh. So if you have some application that needs long range low power networking, this might work for you.
|
||||
- Eventually (within a couple of months) we should have a modified version of Signal that works with this project.
|
||||
- Communication API for bluetooth devices (such as our Android app) to use the mesh. An iOS application is in the works. And [Meshtastic-python](https://pypi.org/project/meshtastic/) provides access from desktop computers.
|
||||
- Very easy sharing of private secured channels. Just share a special link or QR code with friends and they can join your encrypted mesh
|
||||
|
||||
This project is currently in early alpha - if you have questions please [join our discussion forum](https://meshtastic.discourse.group/).
|
||||
This project is currently in beta testing but it is fairly stable and feature complete - if you have questions please [join our discussion forum](https://meshtastic.discourse.group/).
|
||||
|
||||
This software is 100% open source and developed by a group of hobbyist experimenters. No warranty is provided, if you'd like to improve it - we'd love your help. Please post in the [forum](https://meshtastic.discourse.group/).
|
||||
|
||||
# Updates
|
||||
|
||||
Note: Updates are happening almost daily, only major updates are listed below. For more details see our chat, github releases or the Android alpha tester emails.
|
||||
Note: Updates are happening almost daily, only major updates are listed below. For more details see our forum.
|
||||
|
||||
- 06/24/2020 - 0.7.x Now with over 1000 android users, over 600 people using the radios and translated into 13 languages. Fairly stable and we are working through bugs to get to 1.0.
|
||||
- 06/04/2020 - 0.6.7 Beta releases of both the application and the device code are released. Features are fairly solid now with a sizable number of users.
|
||||
- 04/28/2020 - 0.6.0 [Python API](https://pypi.org/project/meshtastic/) released. Makes it easy to use meshtastic devices as "zero config / just works" mesh transport adapters for other projects.
|
||||
- 04/20/2020 - 0.4.3 Pretty solid now both for the android app and the device code. Many people have donated translations and code. Probably going to call it a beta soon.
|
||||
- 03/03/2020 - 0.0.9 of the Android app and device code is released. Still an alpha but fairly functional.
|
||||
- 02/25/2020 - 0.0.4 of the Android app is released. This is a very early alpha, see below to join the alpha-testers group.
|
||||
- 02/23/2020 - 0.0.4 release. Still very bleeding edge but much closer to the final power management, a charged T-BEAM should run for many days with this load. If you'd like to try it, we'd love your feedback. Click [here](https://github.com/meshtastic/Meshtastic-esp32/blob/master/README.md) for instructions.
|
||||
@@ -45,11 +50,11 @@ Note: Updates are happening almost daily, only major updates are listed below. F
|
||||
|
||||
## Meshtastic Android app
|
||||
|
||||
Once out of alpha the companion Android application will be released here:
|
||||
Our Android application is available here:
|
||||
|
||||
[](https://play.google.com/store/apps/details?id=com.geeksville.mesh&referrer=utm_source%3Dhomepage%26anid%3Dadmob)
|
||||
[](https://play.google.com/store/apps/details?id=com.geeksville.mesh&referrer=utm_source%3Dgithub-homepage)
|
||||
|
||||
But if you want the bleeding edge app now, we'd love to have your help testing. Three steps to opt-in to the alpha- test:
|
||||
The link above will return older more stable releases. We would prefer if you join our alpha-test group, because the application is rapidly improving. Three steps to opt-in to the alpha- test:
|
||||
|
||||
1. Join [this Google group](https://groups.google.com/forum/#!forum/meshtastic-alpha-testers) with the account you use in Google Play.
|
||||
2. Go to this [URL](https://play.google.com/apps/testing/com.geeksville.mesh) to opt-in to the alpha test.
|
||||
@@ -59,8 +64,9 @@ If you'd like to help with development, the source code is [on github](https://g
|
||||
|
||||
## Supported hardware
|
||||
|
||||
We currently support two brands of radios. The [TTGO T-Beam](https://www.aliexpress.com/item/4000119152086.html) and the [Heltec LoRa 32](https://heltec.org/project/wifi-lora-32/). Most people should buy the T-Beam and a 18650 battery (total cost less than \$35). Make
|
||||
sure to buy the frequency range which is legal for your country. For the USA, you should buy the 915MHz version. Getting a version that include a screen is optional, but highly recommended.
|
||||
We currently support two brands of radios. The [TTGO T-Beam](https://www.aliexpress.com/item/4001178678568.html) and the [Heltec LoRa 32](https://heltec.org/project/wifi-lora-32/). Most people should buy the T-Beam and a 18650 battery (total cost less than \$35). Also, the version of the T-Beam we link to is shipped with Meshtastic **preinstalled** by TTGO, so you don't have to install it yourself.
|
||||
|
||||
Make sure to buy the frequency range which is legal for your country. For the USA, you should buy the 915MHz version. Getting a version that include a screen is optional, but highly recommended.
|
||||
|
||||
Instructions for installing prebuilt firmware can be found [here](https://github.com/meshtastic/Meshtastic-esp32/blob/master/README.md).
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ This project is still pretty young but moving at a pretty good pace. Not all fea
|
||||
Most of these problems should be solved by the beta release (within three months):
|
||||
|
||||
- We don't make these devices and they haven't been tested by UL or the FCC. If you use them you are experimenting and we can't promise they won't burn your house down ;-)
|
||||
- Encryption is turned off for now
|
||||
- The encryption implementation is good but see this list of [caveats](software/crypto.md#summary-of-strengthsweaknesses-of-our-current-implementation) to determine risks you might face.
|
||||
- A number of (straightforward) software work items have to be completed before battery life matches our measurements, currently battery life is about three days. Join us on chat if you want the spreadsheet of power measurements/calculations.
|
||||
- The Android API needs to be documented better
|
||||
- No one has written an iOS app yet. But some good souls [are talking about it](https://github.com/meshtastic/Meshtastic-esp32/issues/14) ;-)
|
||||
|
||||
6
docs/hardware/cubecell-TODO.md
Normal file
6
docs/hardware/cubecell-TODO.md
Normal file
@@ -0,0 +1,6 @@
|
||||
|
||||
https://heltec-automation-docs.readthedocs.io/en/latest/cubecell/index.html
|
||||
|
||||
https://github.com/HelTecAutomation/ASR650x-Arduino?utm_source=platformio.org&utm_medium=docs
|
||||
|
||||
* Either portfreertos or make not theaded versions of Lock, WorkerThread, Queue (probably the latter).
|
||||
BIN
docs/hardware/nrf52/nrf52-programming.png
Normal file
BIN
docs/hardware/nrf52/nrf52-programming.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 142 KiB |
@@ -1,207 +1,66 @@
|
||||
# High priority
|
||||
# Geeksville's current work queue
|
||||
|
||||
Items to complete soon (next couple of alpha releases).
|
||||
You probably don't care about this section - skip to the next one.
|
||||
|
||||
- lower wait_bluetooth_secs to 30 seconds once we have the GPS power on (but GPS in sleep mode) across light sleep. For the time
|
||||
being I have it set at 2 minutes to ensure enough time for a GPS lock from scratch.
|
||||
|
||||
- remeasure wake time power draws now that we run CPU down at 80MHz
|
||||
|
||||
# AXP192 tasks
|
||||
|
||||
- figure out why this fixme is needed: "FIXME, disable wake due to PMU because it seems to fire all the time?"
|
||||
- "AXP192 interrupt is not firing, remove this temporary polling of battery state"
|
||||
- make debug info screen show real data (including battery level & charging) - close corresponding github issue
|
||||
- implement first cut of router mode: preferentially handle flooding, and change sleep and GPS behaviors (plan for geofence mode and battery save mode)
|
||||
- NRF52 BLE support
|
||||
|
||||
# Medium priority
|
||||
|
||||
Items to complete before the first beta release.
|
||||
Items to complete before 1.0.
|
||||
|
||||
# Post 1.0 ideas
|
||||
|
||||
- finish DSR for unicast
|
||||
- check fcc rules on duty cycle. we might not need to freq hop. https://www.sunfiretesting.com/LoRa-FCC-Certification-Guide/ . Might need to add enforcement for europe though.
|
||||
- make a no bluetooth configured yet screen - include this screen in the loop if the user hasn't yet paired
|
||||
- if radio params change fundamentally, discard the nodedb
|
||||
- re-enable the bluetooth battery level service on the T-BEAM
|
||||
- provide generalized (but slow) internet message forwarding service if one of our nodes has internet connectivity (MQTT) [ Not a requirement but a personal interest ]
|
||||
|
||||
# Low priority ideas
|
||||
|
||||
Items after the first final candidate release.
|
||||
|
||||
- dynamic frequency scaling could save a lot of power on ESP32, but it seems to corrupt uart (even with ref_tick set correctly)
|
||||
- Change back to using a fixed sized MemoryPool rather than MemoryDynamic (see bug #149)
|
||||
- scan to find channels with low background noise? (Use CAD mode of the RF95 to automatically find low noise channels)
|
||||
- If the phone doesn't read fromradio mailbox within X seconds, assume the phone is gone and we can stop queing location msgs
|
||||
for it (because it will redownload the nodedb when it comes back)
|
||||
- add frequency hopping, dependent on the gps time, make the switch moment far from the time anyone is going to be transmitting
|
||||
- assign every "channel" a random shared 8 bit sync word (per 4.2.13.6 of datasheet) - use that word to filter packets before even checking CRC. This will ensure our CPU will only wake for packets on our "channel"
|
||||
- the BLE stack is leaking about 200 bytes each time we go to light sleep
|
||||
- use fuse bits to store the board type and region. So one load can be used on all boards
|
||||
- Don't store position packets in the to phone fifo if we are disconnected. The phone will get that info for 'free' when it
|
||||
fetches the fresh nodedb.
|
||||
- Use the RFM95 sequencer to stay in idle mode most of the time, then automatically go to receive mode and automatically go from transmit to receive mode. See 4.2.8.2 of manual.
|
||||
- possibly switch to https://github.com/SlashDevin/NeoGPS for gps comms
|
||||
- good source of battery/signal/gps icons https://materialdesignicons.com/
|
||||
- research and implement better mesh algorithm - investigate changing routing to https://github.com/sudomesh/LoRaLayer2 ?
|
||||
- check fcc rules on duty cycle. we might not need to freq hop. https://www.sunfiretesting.com/LoRa-FCC-Certification-Guide/
|
||||
- use fuse bits to store the board type and region. So one load can be used on all boards
|
||||
- the BLE stack is leaking about 200 bytes each time we go to light sleep
|
||||
- rx signal measurements -3 marginal, -9 bad, 10 great, -10 means almost unusable. So scale this into % signal strength. preferably as a graph, with an X indicating loss of comms.
|
||||
- assign every "channel" a random shared 8 bit sync word (per 4.2.13.6 of datasheet) - use that word to filter packets before even checking CRC. This will ensure our CPU will only wake for packets on our "channel"
|
||||
- Note: we do not do address filtering at the chip level, because we might need to route for the mesh
|
||||
- add basic crypto - https://github.com/chegewara/esp32-mbedtls-aes-test/blob/master/main/main.c https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation - use ECB at first (though it is shit) because it doesn't require us to send 16 bytes of IV with each packet. Then OFB per example. Possibly do this crypto at the data payload level only, so that all of the packet routing metadata
|
||||
is in cleartext (so that nodes will route for other radios that are cryptoed with a key we don't know)
|
||||
- add frequency hopping, dependent on the gps time, make the switch moment far from the time anyone is going to be transmitting
|
||||
- share channel settings over Signal (or qr code) by embedding an an URL which is handled by the MeshUtil app.
|
||||
- publish update articles on the web
|
||||
- Use fixed32 for node IDs, packetIDs, successid, failid, and lat/lon - will require all nodes to be updated, but make messages slightly smaller.
|
||||
- add "store and forward" support for messages, or move to the DB sync model. This would allow messages to be eventually delivered even if nodes are out of contact at the moment.
|
||||
- use variable length Strings in protobufs (instead of current fixed buffers). This would save lots of RAM
|
||||
- use BLEDevice::setPower to lower our BLE transmit power - extra range doesn't help us, it costs amps and it increases snoopability
|
||||
- make a HAM build: just a new frequency list, a bool to say 'never do encryption' and use hte callsign as that node's unique id. -from Girts
|
||||
- don't forward redundant pings or ping responses to the phone, it just wastes phone battery
|
||||
- don't send location packets if we haven't moved significantly
|
||||
- scrub default radio config settings for bandwidth/range/speed
|
||||
- show radio and gps signal strength as an image
|
||||
- only BLE advertise for a short time after the screen is on and button pressed - to save power and prevent people for sniffing for our BT app.
|
||||
- make mesh aware network timing state machine (sync wake windows to gps time) - this can save LOTS of battery
|
||||
- split out the software update utility so other projects can use it. Have the appload specify the URL for downloads.
|
||||
- read the PMU battery fault indicators and blink/led/warn user on screen
|
||||
- discard very old nodedb records (> 1wk)
|
||||
- handle millis() rollover in GPS.getTime - otherwise we will break after 50 days
|
||||
- report esp32 device code bugs back to the mothership via android
|
||||
- change BLE bonding to something more secure. see comment by pSecurity->setAuthenticationMode(ESP_LE_AUTH_BOND)
|
||||
|
||||
# Pre-beta priority
|
||||
Changes related to wifi support on ESP32:
|
||||
|
||||
During the beta timeframe the following improvements 'would be nice' (and yeah - I guess some of these items count as features, but it is a hobby project ;-) )
|
||||
|
||||
- If the phone doesn't read fromradio mailbox within X seconds, assume the phone is gone and we can stop queing location msgs
|
||||
for it (because it will redownload the nodedb when it comes back)
|
||||
- Figure out why the RF95 ISR is never seeing RH_RF95_VALID_HEADER, so it is not protecting our rx packets from getting stomped on by sends
|
||||
- fix the frequency error reading in the RF95 RX code (can't do floating point math in an ISR ;-)
|
||||
- See CustomRF95::send and fix the problem of dropping partially received packets if we want to start sending
|
||||
- make sure main cpu is not woken for packets with bad crc or not addressed to this node - do that in the radio hw
|
||||
- triple check fcc compliance
|
||||
- pick channel center frequency based on channel name? "dolphin" would hash to 900Mhz, "cat" to 905MHz etc? allows us to hide the concept of channel # from hte user.
|
||||
- scan to find channels with low background noise? (Use CAD mode of the RF95 to automatically find low noise channels)
|
||||
- make a no bluetooth configured yet screen - include this screen in the loop if the user hasn't yet paired
|
||||
- if radio params change fundamentally, discard the nodedb
|
||||
- reneable the bluetooth battery level service on the T-BEAM, because we can read battery level there
|
||||
- iram space: https://esp32.com/viewtopic.php?t=8460
|
||||
- set https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-guides/external-ram.html spi ram bss
|
||||
- figure out if iram or bluetooth classic caused ble problems
|
||||
- post bug on esp32-arduino with BLE bug findings
|
||||
|
||||
# Spinoff project ideas
|
||||
|
||||
- an open source version of https://www.burnair.ch/skynet/
|
||||
- a paragliding app like http://airwhere.co.uk/
|
||||
- a version with a solar cell for power, just mounted high to permanently provide routing for nodes in a valley. Someone just pointed me at disaster.radio
|
||||
- How do avalanche beacons work? Could this do that as well? possibly by using beacon mode feature of the RF95?
|
||||
- provide generalized (but slow) internet message forwarding servie if one of our nodes has internet connectivity
|
||||
|
||||
# Low priority
|
||||
|
||||
Items after the first final candidate release.
|
||||
|
||||
- use variable length arduino Strings in protobufs (instead of current fixed buffers)
|
||||
- use BLEDevice::setPower to lower our BLE transmit power - extra range doesn't help us, it costs amps and it increases snoopability
|
||||
- make an install script to let novices install software on their boards
|
||||
- use std::map<NodeInfo\*, std::string> in node db
|
||||
- make a HAM build: yep - that's a great idea. I'll add it to the TODO. should be pretty painless - just a new frequency list, a bool to say 'never do encryption' and use hte callsign as that node's unique id. -from Girts
|
||||
- don't forward redundant pings or ping responses to the phone, it just wastes phone battery
|
||||
- use https://platformio.org/lib/show/1260/OneButton if necessary
|
||||
- don't send location packets if we haven't moved
|
||||
- scrub default radio config settings for bandwidth/range/speed
|
||||
- answer to pings (because some other user is looking at our nodeinfo) with our latest location (not a stale location)
|
||||
- show radio and gps signal strength as an image
|
||||
- only BLE advertise for a short time after the screen is on and button pressed - to save power and prevent people for sniffing for our BT app.
|
||||
- make mesh aware network timing state machine (sync wake windows to gps time)
|
||||
- split out the software update utility so other projects can use it. Have the appload specify the URL for downloads.
|
||||
- read the PMU battery fault indicators and blink/led/warn user on screen
|
||||
- the AXP debug output says it is trying to charge at 700mA, but the max I've seen is 180mA, so AXP registers probably need to be set to tell them the circuit can only provide 300mAish max. So that the low charge rate kicks in faster and we don't wear out batteries.
|
||||
- increase the max charging rate a bit for 18650s, currently it limits to 180mA (at 4V). Work backwards from the 500mA USB limit (at 5V) and let the AXP charge at that rate.
|
||||
- discard very old nodedb records (> 1wk)
|
||||
- using the genpartitions based table doesn't work on TTGO so for now I stay with my old memory map
|
||||
- We let anyone BLE scan for us (FIXME, perhaps only allow that until we are paired with a phone and configured)
|
||||
- use two different buildenv flags for ttgo vs lora32. https://docs.platformio.org/en/latest/ide/vscode.html#key-bindings
|
||||
- sim gps data for testing nodes that don't have hardware
|
||||
- do debug serial logging to android over bluetooth
|
||||
- break out my bluetooth OTA software as a seperate library so others can use it
|
||||
- Heltec LoRa32 has 8MB flash, use a bigger partition table if needed - TTGO is 4MB but has PSRAM
|
||||
- add a watchdog timer
|
||||
- handle millis() rollover in GPS.getTime - otherwise we will break after 50 days
|
||||
- report esp32 device code bugs back to the mothership via android
|
||||
|
||||
# Done
|
||||
|
||||
- change the partition table to take advantage of the 4MB flash on the wroom: http://docs.platformio.org/en/latest/platforms/espressif32.html#partition-tables
|
||||
- wrap in nice MeshRadio class
|
||||
- add mesh send & rx
|
||||
- make message send from android go to service, then to mesh radio
|
||||
- make message receive from radio go through to android
|
||||
- test loopback tx/rx path code without using radio
|
||||
- notify phone when rx packets arrive, currently the phone polls at startup only
|
||||
- figure out if we can use PA_BOOST - yes, it seems to be on both boards
|
||||
- implement new ble characteristics
|
||||
- have MeshService keep a node DB by sniffing user messages
|
||||
- have a state machine return the correct FromRadio packet to the phone, it isn't always going to be a MeshPacket. Do a notify on fromnum to force the radio to read our state machine generated packets
|
||||
- send my_node_num when phone sends WantsNodes
|
||||
- have meshservice periodically send location data on mesh (if device has a GPS)
|
||||
- implement getCurrentTime() - set based off gps but then updated locally
|
||||
- make default owner record have valid usernames
|
||||
- message loop between node 0x28 and 0x7c
|
||||
- check in my radiolib fixes
|
||||
- figure out what is busted with rx
|
||||
- send our owner info at boot, reply if we see anyone send theirs
|
||||
- add manager layers
|
||||
- confirm second device receives that gps message and updates device db
|
||||
- send correct hw vendor in the bluetooth info - needed so the android app can update different radio models
|
||||
- correctly map nodeids to nodenums, currently we just do a proof of concept by always doing a broadcast
|
||||
- add interrupt detach/sleep mode config to lora radio so we can enable deepsleep without panicing
|
||||
- make jtag work on second board
|
||||
- implement regen owner and radio prefs
|
||||
- use a better font
|
||||
- make nice screens (boot, about to sleep, debug info (gps signal, #people), latest text, person info - one frame per person on network)
|
||||
- turn framerate from ui->state.frameState to 1 fps (or less) unless in transition
|
||||
- switch to my gui layout manager
|
||||
- make basic gui. different screens: debug, one page for each user in the user db, last received text message
|
||||
- make button press cycle between screens
|
||||
- save our node db on entry to sleep
|
||||
- fix the logo
|
||||
- sent/received packets (especially if a node was just reset) have variant of zero sometimes - I think there is a bug (race-condtion?) in the radio send/rx path.
|
||||
- DONE dynamic nodenum assignment tasks
|
||||
- make jtag debugger id stable: https://askubuntu.com/questions/49910/how-to-distinguish-between-identical-usb-to-serial-adapters
|
||||
- reported altitude is crap
|
||||
- good tips on which bands might be more free https://github.com/TheThingsNetwork/ttn/issues/119
|
||||
- finish power measurements (GPS on during sleep vs LCD on during sleep vs LORA on during sleep) and est battery life
|
||||
- make screen sleep behavior work
|
||||
- make screen advance only when a new node update arrives, a new text arrives or the user presses a button, turn off screen after a while
|
||||
- after reboot, channel number is getting reset to zero! fix!
|
||||
- send user and location events much less often
|
||||
- send location (or if not available user) when the user wakes the device from display sleep (both for testing and to improve user experience)
|
||||
- make real implementation of getNumOnlineNodes
|
||||
- very occasionally send our position and user packet based on the schedule in the radio info (if for nothing else so that other nodes update last_seen)
|
||||
- show real text info on the text screen
|
||||
- apply radio settings from android land
|
||||
- cope with nodes that have 0xff or 0x00 as the last byte of their mac
|
||||
- allow setting full radio params from android
|
||||
- add receive timestamps to messages, inserted by esp32 when message is received but then shown on the phone
|
||||
- update build to generate both board types
|
||||
- have node info screen show real info (including distance and heading)
|
||||
- blink the power led less often
|
||||
- have radiohead ISR send messages to RX queue directly, to allow that thread to block until we have something to send
|
||||
- move lora rx/tx to own thread and block on IO
|
||||
- keep our pseudo time moving forward even if we enter deep sleep (use esp32 rtc)
|
||||
- for non GPS equipped devices, set time from phone
|
||||
- GUI on oled hangs for a few seconds occasionally, but comes back
|
||||
- update local GPS position (but do not broadcast) at whatever rate the GPS is giving it
|
||||
- don't send our times to other nodes
|
||||
- don't trust times from other nodes
|
||||
- draw compass rose based off local walking track
|
||||
- add requestResponse optional bool - use for location broadcasts when sending tests
|
||||
- post sample video to signal forum
|
||||
- support non US frequencies
|
||||
- send pr https://github.com/ThingPulse/esp8266-oled-ssd1306 to tell them about this project
|
||||
- document rules for sleep wrt lora/bluetooth/screen/gps. also: if I have text messages (only) for the phone, then give a few seconds in the hopes BLE can get it across before we have to go back to sleep.
|
||||
- wake from light sleep as needed for our next scheduled periodic task (needed for gps position broadcasts etc)
|
||||
- turn bluetooth off based on our sleep policy
|
||||
- blink LED while in LS sleep mode
|
||||
- scrolling between screens based on press is busted
|
||||
- Use Neo-M8M API to put it in sleep mode (on hold until my new boards arrive)
|
||||
- update the prebuilt bins for different regulatory regions
|
||||
- don't enter NB state if we've recently talked to the phone (to prevent breaking syncing or bluetooth sw update)
|
||||
- have sw update prevent BLE sleep
|
||||
- manually delete characteristics/descs
|
||||
- leave lora receiver always on
|
||||
- protobufs are sometimes corrupted after sleep!
|
||||
- stay awake while charging
|
||||
- check gps battery voltage
|
||||
- if a position report includes ground truth time and we don't have time yet, set our clock from that. It is better than nothing.
|
||||
- retest BLE software update for both board types
|
||||
- report on wikifactory
|
||||
- send note to the guy who designed the cases
|
||||
- turn light sleep on aggressively (while lora is on but BLE off)
|
||||
- Use the Periodic class for both position and user periodic broadcasts
|
||||
- don't treat north as up, instead adjust shown bearings for our guess at the users heading (i.e. subtract one from the other)
|
||||
- sendToMesh can currently block for a long time, instead have it just queue a packet for a radio freertos thread
|
||||
- don't even power on bluetooth until we have some data to send to the android phone. Most of the time we should be sleeping in a lowpower "listening for lora" only mode. Once we have some packets for the phone, then power on bluetooth
|
||||
until the phone pulls those packets. Ever so often power on bluetooth just so we can see if the phone wants to send some packets. Possibly might need ULP processor to help with this wake process.
|
||||
- do hibernation mode to get power draw down to 2.5uA https://lastminuteengineers.com/esp32-sleep-modes-power-consumption/
|
||||
- fix GPS.zeroOffset calculation it is wrong
|
||||
- (needs testing) fixed the following during a plane flight:
|
||||
Have state machine properly enter deep sleep based on loss of mesh and phone comms.
|
||||
Default to enter deep sleep if no LORA received for two hours (indicates user has probably left the mesh).
|
||||
- (fixed I think) text messages are not showing on local screen if screen was on
|
||||
- add links to todos
|
||||
- link to the kanban page
|
||||
- add a getting started page
|
||||
- finish mesh alg reeval
|
||||
- ublox gps parsing seems a little buggy (we shouldn't be sending out read solution commands, the device is already broadcasting them)
|
||||
- turn on gps https://github.com/sparkfun/SparkFun_Ublox_Arduino_Library/blob/master/examples/Example18_PowerSaveMode/Example18_PowerSaveMode.ino
|
||||
- switch gps to 38400 baud https://github.com/sparkfun/SparkFun_Ublox_Arduino_Library/blob/master/examples/Example11_ResetModule/Example2_FactoryDefaultsviaSerial/Example2_FactoryDefaultsviaSerial.ino
|
||||
- Use Neo-M8M API to put it in sleep mode
|
||||
- use gps sleep mode instead of killing its power (to allow fast position when we wake)
|
||||
- enable fast lock and low power inside the gps chip
|
||||
- Make a FAQ
|
||||
- add a SF12 transmit option for _super_ long range
|
||||
|
||||
@@ -10,19 +10,28 @@ This device will work with any MTU size, but it is highly recommended that you c
|
||||
|
||||
This is the main bluetooth service for the device and provides the API your app should use to get information about the mesh, send packets or provision the radio.
|
||||
|
||||
For a reference implementation of a client that uses this service see [RadioInterfaceService](https://github.com/meshtastic/Meshtastic-Android/blob/master/app/src/main/java/com/geeksville/mesh/service/RadioInterfaceService.kt). Typical flow when
|
||||
a phone connects to the device should be the following:
|
||||
For a reference implementation of a client that uses this service see [RadioInterfaceService](https://github.com/meshtastic/Meshtastic-Android/blob/master/app/src/main/java/com/geeksville/mesh/service/RadioInterfaceService.kt).
|
||||
|
||||
* SetMTU size to 512
|
||||
* Read a RadioConfig from "radio" - used to get the channel and radio settings
|
||||
* Read (and write if incorrect) a User from "user" - to get the username for this node
|
||||
* Read a MyNodeInfo from "mynode" to get information about this local device
|
||||
* Write an empty record to "nodeinfo" to restart the nodeinfo reading state machine
|
||||
* Read from "nodeinfo" until it returns empty to build the phone's copy of the current NodeDB for the mesh
|
||||
* Read from "fromradio" until it returns empty to get any messages that arrived for this node while the phone was away
|
||||
* Subscribe to notify on "fromnum" to get notified whenever the device has a new received packet
|
||||
* Read that new packet from "fromradio"
|
||||
* Whenever the phone has a packet to send write to "toradio"
|
||||
Typical flow when a phone connects to the device should be the following (if you want to watch this flow from the python app just run "meshtastic --debug --info" - the flow over BLE is identical):
|
||||
|
||||
- There are only three relevant endpoints (and they have built in BLE documentation - so use a BLE tool of your choice to watch them): FromRadio, FromNum (sends notifies when new data is available in FromRadio) and ToRadio
|
||||
- SetMTU size to 512
|
||||
- Write a ToRadio.startConfig protobuf to the "ToRadio" endpoint" - this tells the radio you are a new connection and you need the entire NodeDB sent down.
|
||||
- Read repeatedly from the "FromRadio" endpoint. Each time you read you will get back a FromRadio protobuf (see Meshtatastic-protobuf). Keep reading from this endpoint until you get back and empty buffer.
|
||||
- See below for the expected sequence for your initial download.
|
||||
- After the initial download, you should subscribe for BLE "notify" on the "FromNum" endpoint. If a notification arrives, that means there are now one or more FromRadio packets waiting inside FromRadio. Read from FromRadio until you get back an empty packet.
|
||||
- Any time you want to send packets to the radio, you should write a ToRadio packet into ToRadio.
|
||||
|
||||
Expected sequence for initial download:
|
||||
|
||||
- After your send startConfig, you will receive a series of FromRadio packets. The sequence of these packets will be as follows (but you are best not counting on this, instead just update your model for whatever packet you receive - based on looking at the type)
|
||||
- Read a RadioConfig from "radio" - used to get the channel and radio settings
|
||||
- Read a User from "user" - to get the username for this node
|
||||
- Read a MyNodeInfo from "mynode" to get information about this local device
|
||||
- Write an empty record to "nodeinfo" to restart the nodeinfo reading state machine
|
||||
- Read a series of NodeInfo packets to build the phone's copy of the current NodeDB for the mesh
|
||||
- Read a endConfig packet that indicates that the entire state you need has been sent.
|
||||
- Read a series of MeshPackets until it returns empty to get any messages that arrived for this node while the phone was away
|
||||
|
||||
For definitions (and documentation) on FromRadio, ToRadio, MyNodeInfo, NodeInfo and User protocol buffers see [mesh.proto](https://github.com/meshtastic/Meshtastic-protobufs/blob/master/mesh.proto)
|
||||
|
||||
@@ -54,29 +63,17 @@ When the esp32 advances fromnum, it will delay doing the notify by 100ms, in the
|
||||
|
||||
Note: that if the phone ever sees this number decrease, it means the esp32 has rebooted.
|
||||
|
||||
ea9f3f82-8dc4-4733-9452-1f6da28892a2
|
||||
read
|
||||
mynode - read this to access a MyNodeInfo protobuf
|
||||
|
||||
d31e02e0-c8ab-4d3f-9cc9-0b8466bdabe8
|
||||
read, write
|
||||
nodeinfo - read this to get a series of NodeInfos (ending with a null empty record), write to this to restart the read statemachine that returns all the node infos
|
||||
|
||||
b56786c8-839a-44a1-b98e-a1724c4a0262
|
||||
read,write
|
||||
radio - read/write this to access a RadioConfig protobuf
|
||||
|
||||
6ff1d8b6-e2de-41e3-8c0b-8fa384f64eb6
|
||||
read,write
|
||||
owner - read/write this to access a User protobuf
|
||||
|
||||
Re: queue management
|
||||
Not all messages are kept in the fromradio queue (filtered based on SubPacket):
|
||||
* only the most recent Position and User messages for a particular node are kept
|
||||
* all Data SubPackets are kept
|
||||
* No WantNodeNum / DenyNodeNum messages are kept
|
||||
|
||||
- only the most recent Position and User messages for a particular node are kept
|
||||
- all Data SubPackets are kept
|
||||
- No WantNodeNum / DenyNodeNum messages are kept
|
||||
A variable keepAllPackets, if set to true will suppress this behavior and instead keep everything for forwarding to the phone (for debugging)
|
||||
|
||||
## Protobuf API
|
||||
|
||||
On connect, you should send a want_config_id protobuf to the device. This will cause the device to send its node DB and radio config via the fromradio endpoint. After sending the full DB, the radio will send a want_config_id to indicate it is done sending the configuration.
|
||||
|
||||
## Other bluetooth services
|
||||
|
||||
@@ -92,7 +89,7 @@ SoftwareUpdateService UUID cb0b9a0b-a84c-4c0d-bdbb-442e3144ee30
|
||||
Characteristics
|
||||
|
||||
| UUID | properties | description |
|
||||
|--------------------------------------|------------------|------------|
|
||||
| ------------------------------------ | ----------- | ----------------------------------------------------------------------------------------------------------------- |
|
||||
| e74dd9c0-a301-4a6f-95a1-f0e1dbea8e1e | write,read | total image size, 32 bit, write this first, then read read back to see if it was acceptable (0 mean not accepted) |
|
||||
| e272ebac-d463-4b98-bc84-5cc1a39ee517 | write | data, variable sized, recommended 512 bytes, write one for each block of file |
|
||||
| 4826129c-c22a-43a3-b066-ce8f0d5bacc6 | write | crc32, write last - writing this will complete the OTA operation, now you can read result |
|
||||
|
||||
@@ -6,10 +6,11 @@ in these instructions I describe use of their command line tool.
|
||||
1. Purchase a suitable radio (see above)
|
||||
2. Install [PlatformIO](https://platformio.org/platformio-ide)
|
||||
3. Download this git repo and cd into it
|
||||
4. If you are outside the USA, edit [platformio.ini](/platformio.ini) to set the correct frequency range for your country. The line you need to change starts with "hw_version" and instructions are provided above that line. Options are provided for EU433, EU835, CN, JP and US. Pull-requests eagerly accepted for other countries.
|
||||
5. Plug the radio into your USB port
|
||||
6. Type "pio run --environment XXX -t upload" (This command will fetch dependencies, build the project and install it on the board via USB). For XXX, use the board type you have (either tbeam, heltec, ttgo-lora32-v1, ttgo-lora32-v2).
|
||||
7. Platform IO also installs a very nice VisualStudio Code based IDE, see their [tutorial](https://docs.platformio.org/en/latest/tutorials/espressif32/arduino_debugging_unit_testing.html) if you'd like to use it.
|
||||
4. Run `git submodule update --init --recursive` to pull in dependencies this project needs.
|
||||
5. If you are outside the USA, run "export COUNTRY=EU865" (or whatever) to set the correct frequency range for your country. Options are provided for `EU433`, `EU865`, `CN`, `JP` and `US` (default). Pull-requests eagerly accepted for other countries.
|
||||
6. Plug the radio into your USB port
|
||||
7. Type `pio run --environment XXX -t upload` (This command will fetch dependencies, build the project and install it on the board via USB). For XXX, use the board type you have (either `tbeam`, `heltec`, `ttgo-lora32-v1`, `ttgo-lora32-v2`).
|
||||
8. Platform IO also installs a very nice VisualStudio Code based IDE, see their [tutorial](https://docs.platformio.org/en/latest/tutorials/espressif32/arduino_debugging_unit_testing.html) if you'd like to use it.
|
||||
|
||||
## Decoding stack traces
|
||||
|
||||
|
||||
51
docs/software/crypto.md
Normal file
51
docs/software/crypto.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# Encryption in Meshtastic
|
||||
|
||||
Cryptography is tricky, so we've tried to 'simply' apply standard crypto solutions to our implementation. However,
|
||||
the project developers are not cryptography experts. Therefore we ask two things:
|
||||
|
||||
- If you are a cryptography expert, please review these notes and our questions below. Can you help us by reviewing our
|
||||
notes below and offering advice? We will happily give as much or as little credit as you wish ;-).
|
||||
- Consider our existing solution 'alpha' and probably fairly secure against a not particularly aggressive adversary
|
||||
(but we can't yet make a more confident statement).
|
||||
|
||||
## Summary of strengths/weaknesses of our current implementation
|
||||
|
||||
Based on comments from reviewers (see below), here's some tips for usage of these radios. So you can know the level of protection offered:
|
||||
|
||||
* It is pretty likely that the AES256 security is implemented 'correctly' and an observer will not be able to decode your messages.
|
||||
* Warning: If an attacker is able to get one of the radios in their position, they could either a) extract the channel key from that device or b) use that radio to listen to new communications.
|
||||
* Warning: If an attacker is able to get the "Channel QR code/URL" that you share with others - that attacker could then be able to read any messages sent on the channel (either tomorrow or in the past - if they kept a raw copy of those broadcast packets)
|
||||
|
||||
Possible future areas of work (if there is enough interest - post in our [forum](https://meshtastic.discourse.group) if you want this):
|
||||
|
||||
1. Optionally requiring users to provide a PIN to regain access to the mesh. This could be based on: intentionally locking the device, time since last use, or any member could force all members to reauthenticate,
|
||||
2. Until a device reauthenticates, any other access via BLE or USB would be blocked (this would protect against attackers who are not prepared to write custom software to extract and reverse engineer meshtastic flash memory)
|
||||
3. Turning on read-back protection in the device fuse-bits (this would extend protection in #2 to block all but **extremely** advanced attacks involving chip disassembly)
|
||||
4. Time limiting keys used for message transmission and automatically cycling them on a schedule. This would protect past messages from being decoded even if an attacker learns the current key.
|
||||
|
||||
### Notes for reviewers
|
||||
|
||||
If you are reviewing our implementation, this is a brief statement of our method.
|
||||
|
||||
- We do all crypto at the SubPacket (payload) level only, so that all meshtastic nodes will route for others - even those channels which are encrypted with a different key.
|
||||
- Mostly based on reading [Wikipedia](<https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_(CTR)>) and using the modes the ESP32 provides support for in hardware.
|
||||
- We use AES256-CTR as a stream cypher (with zero padding on the last BLOCK) because it is well supported with hardware acceleration.
|
||||
- Our AES key is 128 or 256 bits, shared as part of the 'Channel' specification.
|
||||
- The node number concatenated with the packet number is used as the NONCE. This nonce will be stored in flash in the device and should essentially never repeat. If the user makes a new 'Channel' (i.e. picking a new random 256 bit key), the packet number will start at zero.
|
||||
- The packet number is sent in cleartext with each packet. The node number can be derived from the "from" field of each packet. (Cleartext is acceptable because it merely provides IV for each encryption run)
|
||||
- Each 16 byte BLOCK for a packet has an incrementing COUNTER. COUNTER starts at zero for the first block of each packet.
|
||||
- The IV for each block is constructed by concatenating the NONCE as the upper 96 bits of the IV and the COUNTER as the bottom 32 bits. Since our packets are small counter portion will really never be higher than 32 (five bits).
|
||||
|
||||
## Comments from reviewer #1
|
||||
|
||||
This reviewer is a cryptography professional, but would like to remain anonymous. We thank them for their comments ;-):
|
||||
|
||||
I'm assuming that meshtastic is being used to hike in places where someone capable is trying to break it - like you were going to walk around DefCon using these. I spent about an hour reviewing the encryption, and have the following notes:
|
||||
|
||||
* The write-up isn't quite as clear as the code.
|
||||
* The code is using AES-CTR mode correctly to ensure confidentiality.
|
||||
* The comment for initNonce really covers the necessary information.
|
||||
* I think the bigger encryption question is "what does the encryption need to do"? As it stands, an attacker who has yet to capture any of the devices cannot reasonably capture text or location data. An attacker who captures any device in the channel/mesh can read everything going to that device, everything stored on that device, and any other communication within the channel that they captured in encrypted form. If that capability basically matches your expectations, it is suitable for whatever adventures this was intended for, then, based on information publicly available or widely disclosed, the encryption is good. If those properties are distressing (like, device history is deliberately limited and you don't want a device captured today to endanger the information sent over the channel yesterday) we could talk about ways to achieve that (most likely synchronizing time and replacing the key with its own SHA256 every X hours, and ensuring the old key is not retained unnecessarily).
|
||||
* Two other things to keep in mind are that AES-CTR does not itself provide authenticity (e.g. an attacker can flip bits in replaying data and scramble the resulting plaintext), and that the current scheme gives some hints about transmission in the size. So, if you worry about an adversary deliberately messing-up messages or knowing the length of a text message, it looks like those might be possible.
|
||||
|
||||
I'm guessing that the network behaves somewhat like a store-and-forward network - or, at least, that the goal is to avoid establishing a two-way connection to transmit data. I'm afraid I haven't worked with mesh networks much, but remember studying them briefly in school about ten years ago.
|
||||
16
docs/software/esp32-arduino-build-notes.md
Normal file
16
docs/software/esp32-arduino-build-notes.md
Normal file
@@ -0,0 +1,16 @@
|
||||
# esp32-arduino build instructions
|
||||
|
||||
We build our own custom version of esp32-arduino, in order to get some fixes we've made but haven't yet been merged in master.
|
||||
|
||||
These are a set of currently unformatted notes on how to build and install them. Most developers should not care about this, because
|
||||
you'll automatically get our fixed libraries.
|
||||
|
||||
```
|
||||
last EDF release in arduino is: https://github.com/espressif/arduino-esp32/commit/1977370e6fc069e93ffd8818798fbfda27ae7d99
|
||||
IDF release/v3.3 46b12a560
|
||||
IDF release/v3.3 367c3c09c
|
||||
https://docs.espressif.com/projects/esp-idf/en/release-v3.3/get-started/linux-setup.html
|
||||
kevinh@kevin-server:~/development/meshtastic/esp32-arduino-lib-builder\$ python /home/kevinh/development/meshtastic/esp32-arduino-lib-builder/esp-idf/components/esptool*py/esptool/esptool.py --chip esp32 --port /dev/ttyUSB0 --baud 921600 --before default_reset --after hard_reset write_flash -z --flash_mode dout --flash_freq 40m --flash_size detect 0x1000 /home/kevinh/development/meshtastic/esp32-arduino-lib-builder/build/bootloader/bootloader.bin
|
||||
cp -a out/tools/sdk/* components/arduino/tools/sdk
|
||||
cp -ar components/arduino/* ~/.platformio/packages/framework-arduinoespressif32@src-fba9d33740f719f712e9f8b07da6ea13/
|
||||
```
|
||||
@@ -1,19 +1,93 @@
|
||||
# Mesh broadcast algorithm
|
||||
|
||||
FIXME - instead look for standard solutions. this approach seems really suboptimal, because too many nodes will try to rebroast. If
|
||||
all else fails could always use the stock Radiohead solution - though super inefficient.
|
||||
|
||||
great source of papers and class notes: http://www.cs.jhu.edu/~cs647/
|
||||
|
||||
flood routing improvements
|
||||
|
||||
- DONE if we don't see anyone rebroadcast our want_ack=true broadcasts, retry as needed.
|
||||
|
||||
reliable messaging tasks (stage one for DSR):
|
||||
|
||||
- DONE generalize naive flooding
|
||||
- DONE add a max hops parameter, use it for broadcast as well (0 means adjacent only, 1 is one forward etc...). Store as three bits in the header.
|
||||
- DONE add a 'snoopReceived' hook for all messages that pass through our node.
|
||||
- DONE use the same 'recentmessages' array used for broadcast msgs to detect duplicate retransmitted messages.
|
||||
- DONE in the router receive path?, send an ack packet if want_ack was set and we are the final destination. FIXME, for now don't handle multihop or merging of data replies with these acks.
|
||||
- DONE keep a list of packets waiting for acks
|
||||
- DONE for each message keep a count of # retries (max of three). Local to the node, only for the most immediate hop, ignorant of multihop routing.
|
||||
- DONE delay some random time for each retry (large enough to allow for acks to come in)
|
||||
- DONE once an ack comes in, remove the packet from the retry list and deliver the ack to the original sender
|
||||
- DONE after three retries, deliver a no-ack packet to the original sender (i.e. the phone app or mesh router service)
|
||||
- DONE test one hop ack/nak with the python framework
|
||||
- DONE Do stress test with acks
|
||||
|
||||
dsr tasks
|
||||
|
||||
- DONE oops I might have broken message reception
|
||||
- DONE Don't use broadcasts for the network pings (close open github issue)
|
||||
- DONE add ignoreSenders to radioconfig to allow testing different mesh topologies by refusing to see certain senders
|
||||
- DONE test multihop delivery with the python framework
|
||||
|
||||
optimizations / low priority:
|
||||
|
||||
- read this [this](http://pages.cs.wisc.edu/~suman/pubs/nadv-mobihoc05.pdf) paper and others and make our naive flood routing less naive
|
||||
- read @cyclomies long email with good ideas on optimizations and reply
|
||||
- DONE Remove NodeNum assignment algorithm (now that we use 4 byte node nums)
|
||||
- DONE make android app warn if firmware is too old or too new to talk to
|
||||
- change nodenums and packetids in protobuf to be fixed32
|
||||
- low priority: think more careful about reliable retransmit intervals
|
||||
- make ReliableRouter.pending threadsafe
|
||||
- bump up PacketPool size for all the new ack/nak/routing packets
|
||||
- handle 51 day rollover in doRetransmissions
|
||||
- use a priority queue for the messages waiting to send. Send acks first, then routing messages, then data messages, then broadcasts?
|
||||
|
||||
when we send a packet
|
||||
|
||||
- do "hop by hop" routing
|
||||
- when sending, if destnodeinfo.next_hop is zero (and no message is already waiting for an arp for that node), startRouteDiscovery() for that node. Queue the message in the 'waiting for arp queue' so we can send it later when then the arp completes.
|
||||
- otherwise, use next_hop and start sending a message (with ack request) towards that node (starting with next_hop).
|
||||
|
||||
when we receive any packet
|
||||
|
||||
- sniff and update tables (especially useful to find adjacent nodes). Update user, network and position info.
|
||||
- if we need to route() that packet, resend it to the next_hop based on our nodedb.
|
||||
- if it is broadcast or destined for our node, deliver locally
|
||||
- handle routereply/routeerror/routediscovery messages as described below
|
||||
- then free it
|
||||
|
||||
routeDiscovery
|
||||
|
||||
- if we've already passed through us (or is from us), then it ignore it
|
||||
- use the nodes already mentioned in the request to update our routing table
|
||||
- if they were looking for us, send back a routereply
|
||||
- NOT DOING FOR NOW -if max_hops is zero and they weren't looking for us, drop (FIXME, send back error - I think not though?)
|
||||
- if we receive a discovery packet, and we don't have next_hop set in our nodedb, we use it to populate next_hop (if needed) towards the requester (after decrementing max_hops)
|
||||
- if we receive a discovery packet, and we have a next_hop in our nodedb for that destination we send a (reliable) we send a route reply towards the requester
|
||||
|
||||
when sending any reliable packet
|
||||
|
||||
- if timeout doing retries, send a routeError (nak) message back towards the original requester. all nodes eavesdrop on that packet and update their route caches.
|
||||
|
||||
when we receive a routereply packet
|
||||
|
||||
- update next_hop on the node, if the new reply needs fewer hops than the existing one (we prefer shorter paths). fixme, someday use a better heuristic
|
||||
|
||||
when we receive a routeError packet
|
||||
|
||||
- delete the route for that failed recipient, restartRouteDiscovery()
|
||||
- if we receive routeerror in response to a discovery,
|
||||
- fixme, eventually keep caches of possible other routes.
|
||||
|
||||
TODO:
|
||||
|
||||
- DONE reread the radiohead mesh implementation - hop to hop acknoledgement seems VERY expensive but otherwise it seems like DSR
|
||||
- optimize our generalized flooding with heuristics, possibly have particular nodes self mark as 'router' nodes.
|
||||
|
||||
- DONE reread the radiohead mesh implementation - hop to hop acknowledgement seems VERY expensive but otherwise it seems like DSR
|
||||
- DONE read about mesh routing solutions (DSR and AODV)
|
||||
- DONE read about general mesh flooding solutions (naive, MPR, geo assisted)
|
||||
- DONE reread the disaster radio protocol docs - seems based on Babel (which is AODVish)
|
||||
- possibly dash7? https://www.slideshare.net/MaartenWeyn1/dash7-alliance-protocol-technical-presentation https://github.com/MOSAIC-LoPoW/dash7-ap-open-source-stack - does the opensource stack implement multihop routing? flooding? their discussion mailing list looks dead-dead
|
||||
- REJECTED - seems dying - possibly dash7? https://www.slideshare.net/MaartenWeyn1/dash7-alliance-protocol-technical-presentation https://github.com/MOSAIC-LoPoW/dash7-ap-open-source-stack - does the opensource stack implement multihop routing? flooding? their discussion mailing list looks dead-dead
|
||||
- update duty cycle spreadsheet for our typical usecase
|
||||
- generalize naive flooding on top of radiohead or disaster.radio? (and fix radiohead to use my new driver)
|
||||
|
||||
a description of DSR: https://tools.ietf.org/html/rfc4728 good slides here: https://www.slideshare.net/ashrafmath/dynamic-source-routing
|
||||
good description of batman protocol: https://www.open-mesh.org/projects/open-mesh/wiki/BATMANConcept
|
||||
@@ -77,7 +151,6 @@ look into the literature for this idea specifically.
|
||||
|
||||
FIXME, merge into the above:
|
||||
|
||||
|
||||
good description of batman protocol: https://www.open-mesh.org/projects/open-mesh/wiki/BATMANConcept
|
||||
|
||||
interesting paper on lora mesh: https://portal.research.lu.se/portal/files/45735775/paper.pdf
|
||||
|
||||
195
docs/software/nrf52-TODO.md
Normal file
195
docs/software/nrf52-TODO.md
Normal file
@@ -0,0 +1,195 @@
|
||||
# NRF52 TODO
|
||||
|
||||
## Misc work items
|
||||
|
||||
RAM investigation.
|
||||
nRF52832-QFAA 64KB ram, 512KB flash vs
|
||||
nrf52832-QFAB 32KB ram, 512kb flash
|
||||
nrf52840 256KB RAM, 1MB flash
|
||||
|
||||
platform.json
|
||||
|
||||
"framework-arduinoadafruitnrf52": {
|
||||
"type": "framework",
|
||||
"optional": true,
|
||||
"version": "https://github.com/meshtastic/Adafruit_nRF52_Arduino.git"
|
||||
},
|
||||
|
||||
## Initial work items
|
||||
|
||||
Minimum items needed to make sure hardware is good.
|
||||
|
||||
- DONE set power UICR per https://devzone.nordicsemi.com/f/nordic-q-a/28562/nrf52840-regulator-configuration
|
||||
- switch charge controller into / out of performance mode (see 8.3.1 in datasheet)
|
||||
- write UC1701 wrapper
|
||||
- Test hardfault handler for null ptrs (if one isn't already installed)
|
||||
- test my hackedup bootloader on the real hardware
|
||||
- Use the PMU driver on real hardware
|
||||
- Use new radio driver on real hardware
|
||||
- Use UC1701 LCD driver on real hardware. Still need to create at startup and probe on SPI. Make sure SPI is atomic.
|
||||
- set vbus voltage per https://infocenter.nordicsemi.com/topic/ps_nrf52840/power.html?cp=4_0_0_4_2
|
||||
- test the LEDs
|
||||
- test the buttons
|
||||
|
||||
## Secondary work items
|
||||
|
||||
Needed to be fully functional at least at the same level of the ESP32 boards. At this point users would probably want them.
|
||||
|
||||
- DONE get serial API working
|
||||
- get full BLE api working
|
||||
- make power management/sleep work properly
|
||||
- make a settimeofday implementation
|
||||
- DONE increase preamble length? - will break other clients? so all devices must update
|
||||
- DONE enable BLE DFU somehow
|
||||
- report appversion/hwversion in BLE
|
||||
- use new LCD driver from screen.cpp. Still need to hook it to a subclass of (poorly named) OLEDDisplay, and override display() to stream bytes out to the screen.
|
||||
- we need to enable the external tcxo for the sx1262 (on dio3)?
|
||||
- figure out which regulator mode the sx1262 is operating in
|
||||
- turn on security for BLE, make pairing work
|
||||
- make ble endpoints not require "start config", just have them start in config mode
|
||||
- use new PMU to provide battery voltage/% full to app (both bluetooth and screen)
|
||||
- do initial power measurements, measure effects of more preamble bits, measure power management and confirm battery life
|
||||
- set UICR.CUSTOMER to indicate board model & version
|
||||
|
||||
## Items to be 'feature complete'
|
||||
|
||||
- check datasheet about sx1262 temperature compensation
|
||||
- enable brownout detection and watchdog
|
||||
- stop polling for GPS characters, instead stay blocked on read in a thread
|
||||
- figure out what the correct current limit should be for the sx1262, currently we just use the default 100
|
||||
- put sx1262 in sleepmode when processor gets shutdown (or rebooted), ideally even for critical faults (to keep power draw low). repurpose deepsleep state for this.
|
||||
- good power management tips: https://devzone.nordicsemi.com/nordic/nordic-blog/b/blog/posts/optimizing-power-on-nrf52-designs
|
||||
- call PMU set_ADC_CONV(0) during sleep, to stop reading PMU adcs and decrease current draw
|
||||
- do final power measurements
|
||||
- backport the common PMU API between AXP192 and PmuBQ25703A
|
||||
- use the new buttons in the UX
|
||||
- currently using soft device SD140, is that ideal?
|
||||
- turn on the watchdog timer, require servicing from key application threads
|
||||
- nrf52setup should call randomSeed(tbd)
|
||||
- implement SYSTEMOFF behavior per https://infocenter.nordicsemi.com/topic/ps_nrf52840/power.html?cp=4_0_0_4_2
|
||||
|
||||
## Things to do 'someday'
|
||||
|
||||
Nice ideas worth considering someday...
|
||||
|
||||
- enable monitor mode debugging (need to use real jlink): https://devzone.nordicsemi.com/nordic/nordic-blog/b/blog/posts/monitor-mode-debugging-with-j-link-and-gdbeclipse
|
||||
- Improve efficiency of PeriodicTimer by only checking the next queued timer event, and carefully sorting based on schedule
|
||||
- make a Mfg Controller and device under test classes as examples of custom app code for third party devs. Make a post about this. Use a custom payload type code. Have device under test send a broadcast with max hopcount of 0 for the 'mfgcontroller' payload type. mfg controller will read SNR and reply. DOT will declare failure/success and switch to the regular app screen.
|
||||
- Hook Segger RTT to the nordic logging framework. https://devzone.nordicsemi.com/nordic/nordic-blog/b/blog/posts/debugging-with-real-time-terminal
|
||||
- Use nordic logging for DEBUG_MSG
|
||||
- use the Jumper simulator to run meshes of simulated hardware: https://docs.jumper.io/docs/install.html
|
||||
- make/find a multithread safe debug logging class (include remote logging and timestamps and levels). make each log event atomic.
|
||||
- turn on freertos stack size checking
|
||||
- Currently we use Nordic's vendor ID, which is apparently okay: https://devzone.nordicsemi.com/f/nordic-q-a/44014/using-nordic-vid-and-pid-for-nrf52840 and I just picked a PID of 0x4403
|
||||
- Use NRF logger module (includes flash logging etc...) instead of DEBUG_MSG
|
||||
- Use "LED softblink" library on NRF52 to do nice pretty "breathing" LEDs. Don't whack LED from main thread anymore.
|
||||
- decrease BLE xmit power "At 0dBm with the DC/DC on, the nRF52832 transmitter draws 5.3mA. Increasing the TX power to +4dBm adds only 2.2mA. Decreasing it to -40 dBm saves only 2.6mA."
|
||||
- in addition to the main CPU watchdog, use the PMU watchdog as a really big emergency hammer
|
||||
- turn on 'shipping mode' in the PMU when device is 'off' - to cut battery draw to essentially zero
|
||||
- make Lorro_BQ25703A read/write operations atomic, current version could let other threads sneak in (once we start using threads)
|
||||
- make the segger logbuffer larger, move it to RAM that is preserved across reboots and support reading it out at runtime (to allow full log messages to be included in crash reports). Share this code with ESP32 (use gcc noinit attribute)
|
||||
- convert hardfaults/panics/asserts/wd exceptions into fault codes sent to phone
|
||||
- stop enumerating all i2c devices at boot, it wastes power & time
|
||||
- consider using "SYSTEMOFF" deep sleep mode, without RAM retension. Only useful for 'truly off - wake only by button press' only saves 1.5uA vs SYSTEMON. (SYSTEMON only costs 1.5uA). Possibly put PMU into shipping mode?
|
||||
- change the BLE protocol to be more symmetric. Have the phone _also_ host a GATT service which receives writes to
|
||||
'fromradio'. This would allow removing the 'fromnum' mailbox/notify scheme of the current approach and decrease the number of packet handoffs when a packet is received.
|
||||
- Using the preceeding, make a generalized 'nrf52/esp32 ble to internet' bridge service. To let nrf52 apps do MQTT/UDP/HTTP POST/HTTP GET operations to web services.
|
||||
- lower advertise interval to save power, lower ble transmit power to save power
|
||||
- the SX126x class does SPI transfers on a byte by byte basis, which is very ineffecient. Much better to do block writes/reads.
|
||||
|
||||
## Old unorganized notes
|
||||
|
||||
## Notes on PCA10059 Dongle
|
||||
|
||||
- docs: https://infocenter.nordicsemi.com/pdf/nRF52840_Dongle_User_Guide_v1.0.pdf
|
||||
|
||||
- Currently using Nordic PCA10059 Dongle hardware
|
||||
- https://community.platformio.org/t/same-bootloader-same-softdevice-different-board-different-pins/11411/9
|
||||
|
||||
- To make Segger JLink more reliable, turn off its fake filesystem. "JLinkExe MSDDisable" per https://learn.adafruit.com/circuitpython-on-the-nrf52/nrf52840-bootloader
|
||||
|
||||
## Done
|
||||
|
||||
- DONE add "DFU trigger library" to application load
|
||||
- DONE: using this: Possibly use this bootloader? https://github.com/adafruit/Adafruit_nRF52_Bootloader
|
||||
- DONE select and install a bootloader (adafruit)
|
||||
- DONE get old radio driver working on NRF52
|
||||
- DONE basic test of BLE
|
||||
- DONE get a debug 'serial' console working via the ICE passthrough feature
|
||||
- DONE switch to RadioLab? test it with current radio. https://github.com/jgromes/RadioLib
|
||||
- DONE change rx95 to radiolib
|
||||
- DONE track rxbad, rxgood, txgood
|
||||
- DONE neg 7 error code from receive
|
||||
- DONE remove unused sx1262 lib from github
|
||||
- at boot we are starting our message IDs at 1, rather we should start them at a random number. also, seed random based on timer. this could be the cause of our first message not seen bug.
|
||||
- add a NEMA based GPS driver to test GPS
|
||||
- DONE use "variants" to get all gpio bindings
|
||||
- DONE plug in correct variants for the real board
|
||||
- turn on DFU assistance in the appload using the nordic DFU helper lib call
|
||||
- make a new boarddef with a variant.h file. Fix pins in that file. In particular (at least):
|
||||
#define PIN_SPI_MISO (46)
|
||||
#define PIN_SPI_MOSI (45)
|
||||
#define PIN_SPI_SCK (47)
|
||||
#define PIN_WIRE_SDA (26)
|
||||
#define PIN_WIRE_SCL (27)
|
||||
- customize the bootloader to use proper button bindings
|
||||
- remove the MeshRadio wrapper - we don't need it anymore, just do everything in RadioInterface subclasses.
|
||||
- DONE use SX126x::startReceiveDutyCycleAuto to save power by sleeping and briefly waking to check for preamble bits. Change xmit rules to have more preamble bits.
|
||||
- scheduleOSCallback doesn't work yet - it is way too fast (causes rapid polling of busyTx, high power draw etc...)
|
||||
- find out why we reboot while debugging - it was bluetooth/softdevice
|
||||
- make a file system implementation (preferably one that can see the files the bootloader also sees) - preferably https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/master/libraries/InternalFileSytem/examples/Internal_ReadWrite/Internal_ReadWrite.ino else use https://infocenter.nordicsemi.com/topic/com.nordic.infocenter.sdk5.v15.3.0/lib_fds_usage.html?cp=7_5_0_3_55_3
|
||||
- change packet numbers to be 32 bits
|
||||
|
||||
```
|
||||
|
||||
/*
|
||||
per
|
||||
https://docs.platformio.org/en/latest/tutorials/nordicnrf52/arduino_debugging_unit_testing.html
|
||||
|
||||
ardunino github is here https://github.com/sandeepmistry/arduino-nRF5
|
||||
devboard hw docs here:
|
||||
https://infocenter.nordicsemi.com/topic/ug_nrf52840_dk/UG/nrf52840_DK/hw_buttons_leds.html?cp=4_0_4_7_6
|
||||
|
||||
https://docs.platformio.org/en/latest/boards/nordicnrf52/nrf52840_dk_adafruit.html
|
||||
|
||||
must install adafruit bootloader first!
|
||||
https://learn.adafruit.com/circuitpython-on-the-nrf52/nrf52840-bootloader
|
||||
see link above and turn off jlink filesystem if we see unreliable serial comms
|
||||
over USBCDC
|
||||
|
||||
adafruit bootloader install commands (from their readme)
|
||||
kevinh@kevin-server:~/.platformio/packages/framework-arduinoadafruitnrf52/bootloader$
|
||||
nrfjprog -e -f nrf52 Erasing user available code and UICR flash areas. Applying
|
||||
system reset.
|
||||
kevinh@kevin-server:~/.platformio/packages/framework-arduinoadafruitnrf52/bootloader$
|
||||
nrfjprog --program pca10056/pca10056_bootloader-0.3.2_s140_6.1.1.hex -f nrf52
|
||||
Parsing hex file.
|
||||
Reading flash area to program to guarantee it is erased.
|
||||
Checking that the area to write is not protected.
|
||||
Programming device.
|
||||
kevinh@kevin-server:~/.platformio/packages/framework-arduinoadafruitnrf52/bootloader$
|
||||
nrfjprog --reset -f nrf52 Applying system reset. Run.
|
||||
|
||||
install jlink tools from here:
|
||||
https://www.segger.com/downloads/jlink#J-LinkSoftwareAndDocumentationPack
|
||||
|
||||
install nrf tools from here:
|
||||
https://www.nordicsemi.com/Software-and-tools/Development-Tools/nRF-Command-Line-Tools/Download#infotabs
|
||||
|
||||
examples of turning off the loop call to save power:
|
||||
https://learn.adafruit.com/bluefruit-nrf52-feather-learning-guide/advertising-beacon
|
||||
|
||||
example of a more complex BLE service:
|
||||
https://learn.adafruit.com/bluefruit-nrf52-feather-learning-guide/custom-hrm
|
||||
*/
|
||||
|
||||
// See g_ADigitalPinMap to see how arduino maps to the real gpio#s - and all in
|
||||
// P0
|
||||
#define LED1 14
|
||||
#define LED2 13
|
||||
|
||||
/*
|
||||
good led ble demo:
|
||||
https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/master/libraries/Bluefruit52Lib/examples/Peripheral/nrf_blinky/nrf_blinky.ino
|
||||
*/
|
||||
```
|
||||
27
docs/software/pinetab.md
Normal file
27
docs/software/pinetab.md
Normal file
@@ -0,0 +1,27 @@
|
||||
# Pinetab
|
||||
|
||||
These are **preliminary** notes on support for Meshtastic in the Pinetab.
|
||||
|
||||
A RF95 is connected via a CS341 USB-SPI chip.
|
||||
|
||||
Pin assignments:
|
||||
CS0 from RF95 goes to CS0 on CS341
|
||||
DIO0 from RF95 goes to INT on CS341
|
||||
RST from RF95 goes to RST on CS341
|
||||
|
||||
This linux driver claims to provide USB-SPI support: https://github.com/gschorcht/spi-ch341-usb
|
||||
Notes here on using that driver: https://www.linuxquestions.org/questions/linux-hardware-18/ch341-usb-to-spi-adaptor-driver-doesn%27t-work-4175622736/
|
||||
|
||||
Or if **absolutely** necessary could bitbang: https://www.cnx-software.com/2018/02/16/wch-ch341-usb-to-serial-chip-gets-linux-driver-to-control-gpios-over-usb/
|
||||
|
||||
## Task list
|
||||
|
||||
* Port meshtastic to build (under platformio) for a poxix target. spec: no screen, no gpios, sim network interface, posix threads, posix semaphores & queues, IO to the console only
|
||||
Use ARM linux: https://platformio.org/platforms/linux_arm
|
||||
And linux native: https://platformio.org/platforms/native
|
||||
|
||||
* Test cs341 driver - just test reading/writing a register and detecting interrupts, confirm can see rf95
|
||||
* Make a radiolib spi module that targets the cs341 (and builds on linux)
|
||||
* use new radiolib module to hook pinebook lora to meshtastic, confirm mesh discovery works
|
||||
* Make a subclass of StreamAPI that works as a posix TCP server
|
||||
* Use new TCP endpoint from meshtastic-python
|
||||
@@ -10,56 +10,63 @@ Since one of the main goals of this project is long battery life, it is importan
|
||||
|
||||
From lower to higher power consumption.
|
||||
|
||||
* Super-deep-sleep (SDS) - everything is off, CPU, radio, bluetooth, GPS. Only wakes due to timer or button press. We enter this mode only after no radio comms for a few hours, used to put the device into what is effectively "off" mode.
|
||||
- Super-deep-sleep (SDS) - everything is off, CPU, radio, bluetooth, GPS. Only wakes due to timer or button press. We enter this mode only after no radio comms for a few hours, used to put the device into what is effectively "off" mode.
|
||||
onEntry: setBluetoothOn(false), call doDeepSleep
|
||||
onExit: (standard bootup code, starts in DARK)
|
||||
|
||||
* deep-sleep (DS) - CPU is off, radio is on, bluetooth and GPS is off. Note: This mode is never used currently, because it only saves 1.5mA vs light-sleep
|
||||
- deep-sleep (DS) - CPU is off, radio is on, bluetooth and GPS is off. Note: This mode is never used currently, because it only saves 1.5mA vs light-sleep
|
||||
(Not currently used)
|
||||
|
||||
* light-sleep (LS) - CPU is suspended (RAM stays alive), radio is on, bluetooth is off, GPS is off. Note: currently GPS is not turned
|
||||
- light-sleep (LS) - CPU is suspended (RAM stays alive), radio is on, bluetooth is off, GPS is off. Note: currently GPS is not turned
|
||||
off during light sleep, but there is a TODO item to fix this.
|
||||
NOTE: On NRF52 platforms (because CPU current draw is so low), light-sleep state is never used.
|
||||
onEntry: setBluetoothOn(false), setGPSPower(false), doLightSleep()
|
||||
onIdle: (if we wake because our led blink timer has expired) blink the led then go back to sleep until we sleep for ls_secs
|
||||
onExit: setGPSPower(true), start trying to get gps lock: gps.startLock(), once lock arrives service.sendPosition(BROADCAST)
|
||||
|
||||
* No bluetooth (NB) - CPU is running, radio is on, GPS is on but bluetooth is off, screen is off.
|
||||
- No bluetooth (NB) - CPU is running, radio is on, GPS is on but bluetooth is off, screen is off.
|
||||
onEntry: setBluetoothOn(false)
|
||||
onExit:
|
||||
|
||||
* running dark (DARK) - Everything is on except screen
|
||||
- running dark (DARK) - Everything is on except screen
|
||||
onEntry: setBluetoothOn(true)
|
||||
onExit:
|
||||
|
||||
* full on (ON) - Everything is on
|
||||
- full on (ON) - Everything is on
|
||||
onEntry: setBluetoothOn(true), screen.setOn(true)
|
||||
onExit: screen.setOn(false)
|
||||
|
||||
- serial API usage (SERIAL) - Screen is on, device doesn't sleep, bluetooth off
|
||||
onEntry: setBluetooth off, screen on
|
||||
onExit:
|
||||
|
||||
## Behavior
|
||||
|
||||
### events that increase CPU activity
|
||||
|
||||
* At cold boot: The initial state (after setup() has run) is DARK
|
||||
* While in DARK: if we receive EVENT_BOOT, transition to ON (and show the bootscreen). This event will be sent if we detect we woke due to reset (as opposed to deep sleep)
|
||||
* While in LS: Once every position_broadcast_secs (default 15 mins) - the unit will wake into DARK mode and broadcast a "networkPing" (our position) and stay alive for wait_bluetooth_secs (default 30 seconds). This allows other nodes to have a record of our last known position if we go away and allows a paired phone to hear from us and download messages.
|
||||
* While in LS: Every send_owner_interval (defaults to 4, i.e. one hour), when we wake to send our position we _also_ broadcast our owner. This lets new nodes on the network find out about us or correct duplicate node number assignments.
|
||||
* While in LS/NB/DARK: If the user presses a button (EVENT_PRESS) we go to full ON mode for screen_on_secs (default 30 seconds). Multiple presses keeps resetting this timeout
|
||||
* While in LS/NB/DARK: If we receive new text messages (EVENT_RECEIVED_TEXT_MSG), we go to full ON mode for screen_on_secs (same as if user pressed a button)
|
||||
* While in LS: while we receive packets on the radio (EVENT_RECEIVED_PACKET) we will wake and handle them and stay awake in NB mode for min_wake_secs (default 10 seconds)
|
||||
* While in NB: If we do have packets the phone (EVENT_PACKETS_FOR_PHONE) would want we transition to DARK mode for wait_bluetooth secs.
|
||||
* While in DARK/ON: If we receive EVENT_BLUETOOTH_PAIR we transition to ON and start our screen_on_secs timeout
|
||||
* While in NB/DARK/ON: If we receive EVENT_NODEDB_UPDATED we transition to ON (so the new screen can be shown)
|
||||
* While in DARK: While the phone talks to us over BLE (EVENT_CONTACT_FROM_PHONE) reset any sleep timers and stay in DARK (needed for bluetooth sw update and nice user experience if the user is reading/replying to texts)
|
||||
- At cold boot: The initial state (after setup() has run) is DARK
|
||||
- While in DARK: if we receive EVENT_BOOT, transition to ON (and show the bootscreen). This event will be sent if we detect we woke due to reset (as opposed to deep sleep)
|
||||
- While in LS: Once every position_broadcast_secs (default 15 mins) - the unit will wake into DARK mode and broadcast a "networkPing" (our position) and stay alive for wait_bluetooth_secs (default 30 seconds). This allows other nodes to have a record of our last known position if we go away and allows a paired phone to hear from us and download messages.
|
||||
- While in LS: Every send*owner_interval (defaults to 4, i.e. one hour), when we wake to send our position we \_also* broadcast our owner. This lets new nodes on the network find out about us or correct duplicate node number assignments.
|
||||
- While in LS/NB/DARK: If the user presses a button (EVENT_PRESS) we go to full ON mode for screen_on_secs (default 30 seconds). Multiple presses keeps resetting this timeout
|
||||
- While in LS/NB/DARK: If we receive new text messages (EVENT_RECEIVED_TEXT_MSG), we go to full ON mode for screen_on_secs (same as if user pressed a button)
|
||||
- While in LS: while we receive packets on the radio (EVENT_RECEIVED_PACKET) we will wake and handle them and stay awake in NB mode for min_wake_secs (default 10 seconds)
|
||||
- While in NB: If we do have packets the phone (EVENT_PACKETS_FOR_PHONE) would want we transition to DARK mode for wait_bluetooth secs.
|
||||
- While in DARK/ON: If we receive EVENT_BLUETOOTH_PAIR we transition to ON and start our screen_on_secs timeout
|
||||
- While in NB/DARK/ON: If we receive EVENT_NODEDB_UPDATED we transition to ON (so the new screen can be shown)
|
||||
- While in DARK: While the phone talks to us over BLE (EVENT_CONTACT_FROM_PHONE) reset any sleep timers and stay in DARK (needed for bluetooth sw update and nice user experience if the user is reading/replying to texts)
|
||||
- while in LS/NB/DARK: if SERIAL_CONNECTED, go to serial
|
||||
|
||||
### events that decrease cpu activity
|
||||
|
||||
* While in ON: If PRESS event occurs, reset screen_on_secs timer and tell the screen to handle the pess
|
||||
* While in ON: If it has been more than screen_on_secs since a press, lower to DARK
|
||||
* While in DARK: If time since last contact by our phone exceeds phone_timeout_secs (15 minutes), we transition down into NB mode
|
||||
* While in DARK or NB: If nothing above is forcing us to stay in a higher mode (wait_bluetooth_secs, min_wake_secs) we will lower down to LS state
|
||||
* While in LS: If either phone_sds_timeout_secs (default 2 hr) or mesh_sds_timeout_secs (default 2 hr) are exceeded we will lower into SDS mode for sds_secs (default 1 yr) (or a button press). (Note: phone_sds_timeout_secs is currently disabled for now, because most users
|
||||
- While in SERIAL: if SERIAL_DISCONNECTED, go to NB
|
||||
- While in ON: If PRESS event occurs, reset screen_on_secs timer and tell the screen to handle the pess
|
||||
- While in ON: If it has been more than screen_on_secs since a press, lower to DARK
|
||||
- While in DARK: If time since last contact by our phone exceeds phone_timeout_secs (15 minutes), we transition down into NB mode
|
||||
- While in DARK or NB: If nothing above is forcing us to stay in a higher mode (wait_bluetooth_secs, min_wake_secs) we will lower down to LS state
|
||||
- While in LS: If either phone_sds_timeout_secs (default 2 hr) or mesh_sds_timeout_secs (default 2 hr) are exceeded we will lower into SDS mode for sds_secs (default 1 yr) (or a button press). (Note: phone_sds_timeout_secs is currently disabled for now, because most users
|
||||
are using without a phone)
|
||||
* Any time we enter LS mode: We stay in that until an interrupt, button press or other state transition. Every ls_secs (default 1 hr) and let the arduino loop() run one iteration (FIXME, not sure if we need this at all), and then immediately reenter lightsleep mode on the CPU.
|
||||
- Any time we enter LS mode: We stay in that until an interrupt, button press or other state transition. Every ls_secs (default 1 hr) and let the arduino loop() run one iteration (FIXME, not sure if we need this at all), and then immediately reenter lightsleep mode on the CPU.
|
||||
|
||||
TODO: Eventually these scheduled intervals should be synchronized to the GPS clock, so that we can consider leaving the lora receiver off to save even more power.
|
||||
TODO: In NB mode we should put cpu into light sleep any time we really aren't that busy (without declaring LS state) - i.e. we should leave GPS on etc...
|
||||
@@ -68,18 +75,18 @@ TODO: In NB mode we should put cpu into light sleep any time we really aren't th
|
||||
|
||||
General ideas to hit the power draws our spreadsheet predicts. Do the easy ones before beta, the last 15% can be done after 1.0.
|
||||
|
||||
* don't even power on the gps until someone else wants our position, just stay in lora deep sleep until press or rxpacket (except for once an hour updates)
|
||||
* (possibly bad idea - better to have lora radio always listen - check spreadsheet) have every node wake at the same tick and do their position syncs then go back to deep sleep
|
||||
* lower BT announce interval to save battery
|
||||
* change to use RXcontinuous mode and config to drop packets with bad CRC (see section 6.4 of datasheet) - I think this is already the case
|
||||
* have mesh service run in a thread that stays blocked until a packet arrives from the RF95
|
||||
* platformio sdkconfig CONFIG_PM and turn on modem sleep mode
|
||||
* keep cpu 100% in deepsleep until irq from radio wakes it. Then stay awake for 30 secs to attempt delivery to phone.
|
||||
* use https://lastminuteengineers.com/esp32-sleep-modes-power-consumption/ association sleep pattern to save power - but see https://github.com/espressif/esp-idf/issues/2070 and https://esp32.com/viewtopic.php?f=13&t=12182 it seems with BLE on the 'easy' draw people are getting is 80mA
|
||||
* stop using loop() instead use a job queue and let cpu sleep
|
||||
* measure power consumption and calculate battery life assuming no deep sleep
|
||||
* do lowest sleep level possible where BT still works during normal sleeping, make sure cpu stays in that mode unless lora rx packet happens, bt rx packet happens or button press happens
|
||||
* optionally do lora messaging only during special scheduled intervals (unless nodes are told to go to low latency mode), then deep sleep except during those intervals - before implementing calculate what battery life would be with this feature
|
||||
* see section 7.3 of https://cdn.sparkfun.com/assets/learn_tutorials/8/0/4/RFM95_96_97_98W.pdf and have hope radio wake only when a valid packet is received. Possibly even wake the ESP32 from deep sleep via GPIO.
|
||||
* never enter deep sleep while connected to USB power (but still go to other low power modes)
|
||||
* when main cpu is idle (in loop), turn cpu clock rate down and/or activate special sleep modes. We want almost everything shutdown until it gets an interrupt.
|
||||
- don't even power on the gps until someone else wants our position, just stay in lora deep sleep until press or rxpacket (except for once an hour updates)
|
||||
- (possibly bad idea - better to have lora radio always listen - check spreadsheet) have every node wake at the same tick and do their position syncs then go back to deep sleep
|
||||
- lower BT announce interval to save battery
|
||||
- change to use RXcontinuous mode and config to drop packets with bad CRC (see section 6.4 of datasheet) - I think this is already the case
|
||||
- have mesh service run in a thread that stays blocked until a packet arrives from the RF95
|
||||
- platformio sdkconfig CONFIG_PM and turn on modem sleep mode
|
||||
- keep cpu 100% in deepsleep until irq from radio wakes it. Then stay awake for 30 secs to attempt delivery to phone.
|
||||
- use https://lastminuteengineers.com/esp32-sleep-modes-power-consumption/ association sleep pattern to save power - but see https://github.com/espressif/esp-idf/issues/2070 and https://esp32.com/viewtopic.php?f=13&t=12182 it seems with BLE on the 'easy' draw people are getting is 80mA
|
||||
- stop using loop() instead use a job queue and let cpu sleep
|
||||
- measure power consumption and calculate battery life assuming no deep sleep
|
||||
- do lowest sleep level possible where BT still works during normal sleeping, make sure cpu stays in that mode unless lora rx packet happens, bt rx packet happens or button press happens
|
||||
- optionally do lora messaging only during special scheduled intervals (unless nodes are told to go to low latency mode), then deep sleep except during those intervals - before implementing calculate what battery life would be with this feature
|
||||
- see section 7.3 of https://cdn.sparkfun.com/assets/learn_tutorials/8/0/4/RFM95_96_97_98W.pdf and have hope radio wake only when a valid packet is received. Possibly even wake the ESP32 from deep sleep via GPIO.
|
||||
- never enter deep sleep while connected to USB power (but still go to other low power modes)
|
||||
- when main cpu is idle (in loop), turn cpu clock rate down and/or activate special sleep modes. We want almost everything shutdown until it gets an interrupt.
|
||||
|
||||
202
docs/software/ramusage-nrf52.txt
Normal file
202
docs/software/ramusage-nrf52.txt
Normal file
@@ -0,0 +1,202 @@
|
||||
23K + messages
|
||||
+ heap of 70ish packets, 300ish bytes per packet: 20KB
|
||||
+ 14KB soft device RAM
|
||||
|
||||
With max length Data inside the packet
|
||||
Size of NodeInfo 104
|
||||
Size of SubPacket 272
|
||||
Size of MeshPacket 304
|
||||
|
||||
If Data was smaller: for 70 data packets we would save 7KB. We would need to make SubPacket.data and MeshPacket.encrypted into "type:FT_POINTER" - variably sized mallocs
|
||||
Size of NodeInfo 104
|
||||
Size of SubPacket 96
|
||||
Size of MeshPacket 292 (could have been much smaller but I forgot to shrink MeshPacket.encrypted)
|
||||
|
||||
therefore:
|
||||
a) we should store all ToPhone message queued messages compressed as protobufs (since they will become that anyways)
|
||||
b) shrink packet pool size because none of that storage will be used for ToPhone packets
|
||||
c) don't allocate any storage in RAM for the tophone messages we save inside device state, instead just use nanopb callbacks to save/load those
|
||||
d) a smarter MeshPacket in memory representation would save about 7KB of RAM. call pb_release before freeing each freshly malloced MeshPacket
|
||||
|
||||
- nrf52 free memory https://learn.adafruit.com/bluefruit-nrf52-feather-learning-guide/hathach-memory-map
|
||||
|
||||
2000790c 00003558 B devicestate // 16KB
|
||||
2000b53c 00001000 b _cache_buffer // 4KB flash filesystem support
|
||||
20003b1c 000006b0 B console
|
||||
2000d5f4 00000400 b vApplicationGetTimerTaskMemory::uxTimerTaskStack
|
||||
2000da04 00000400 b _acUpBuffer
|
||||
2000c558 0000036c B Bluefruit
|
||||
2000c8d8 00000358 b _cdcd_itf
|
||||
2000e54c 00000258 B _midid_itf
|
||||
2000d0dc 00000200 b ucStaticTimerQueueStorage.9390
|
||||
2000e044 00000200 b _mscd_buf
|
||||
2000e284 000001cc b _vendord_itf
|
||||
2000d410 00000190 b vApplicationGetIdleTaskMemory::uxIdleTaskStack
|
||||
2000374c 0000016c D __global_locale
|
||||
2000de48 0000012c B USBDevice
|
||||
2000afa4 00000100 b Router::send(_MeshPacket*)::bytes
|
||||
2000aea4 00000100 b Router::perhapsDecode(_MeshPacket*)::bytes
|
||||
200039b0 000000f4 B powerFSM
|
||||
20004258 000000f0 B screen
|
||||
2000cd7c 000000c4 b _dcd
|
||||
2000cc68 000000c0 b _usbd_qdef_buf
|
||||
2000b3c4 000000bc B Wire
|
||||
2000cef4 000000a8 B Serial2
|
||||
2000ce4c 000000a8 B Serial1
|
||||
2000e498 000000a8 B _SEGGER_RTT
|
||||
2000b498 000000a4 B InternalFS
|
||||
2000dfb8 0000008c b _hidd_itf
|
||||
2000b260 00000088 b meshtastic::normalFrames
|
||||
2000cfdc 00000064 b pxReadyTasksLists
|
||||
2000b340 00000060 b meshtastic::drawTextMessageFrame(OLEDDisplay*, OLEDDisplayUiState*, short, short)::tempBuf
|
||||
200036ec 00000060 d impure_data
|
||||
2000b104 00000060 B bledfu
|
||||
2000b0a4 00000060 B blebas
|
||||
20003684 00000058 D _usbd_qdef
|
||||
200038c0 00000058 d tzinfo
|
||||
2000d5a0 00000054 b vApplicationGetTimerTaskMemory::xTimerTaskTCB
|
||||
2000d3bc 00000054 b vApplicationGetIdleTaskMemory::xIdleTaskTCB
|
||||
2000d308 00000050 b xStaticTimerQueue.9389
|
||||
2000b1f4 00000050 B hrmc
|
||||
2000b1a4 00000050 B bslc
|
||||
20004360 0000004c B service
|
||||
2000d374 00000048 b m_cb
|
||||
2000df74 00000042 b _desc_str
|
||||
2000cd3c 00000040 b _usbd_ctrl_buf
|
||||
20004214 00000040 B realRouter
|
||||
2000e244 00000040 b _mscd_itf
|
||||
2000b164 00000040 B bledis
|
||||
20003634 00000038 d _InternalFSConfig
|
||||
2000cc30 00000031 b _usbd_dev
|
||||
2000398c 00000020 B periodicScheduler
|
||||
2000cfa4 00000020 b callbacksInt
|
||||
2000de10 0000001f b fw_str.13525
|
||||
20003974 00000018 b object.9934
|
||||
2000ae68 00000018 B nodeDB
|
||||
2000366c 00000018 d _cache
|
||||
2000b314 00000014 b meshtastic::drawNodeInfo(OLEDDisplay*, OLEDDisplayUiState*, short, short)::signalStr
|
||||
2000b300 00000014 b meshtastic::drawNodeInfo(OLEDDisplay*, OLEDDisplayUiState*, short, short)::lastStr
|
||||
2000b2ec 00000014 b meshtastic::drawNodeInfo(OLEDDisplay*, OLEDDisplayUiState*, short, short)::distStr
|
||||
200041e0 00000014 b getDeviceName()::name
|
||||
2000d0b8 00000014 b xTasksWaitingTermination
|
||||
2000d0a4 00000014 b xSuspendedTaskList
|
||||
2000d08c 00000014 b xPendingReadyList
|
||||
2000d06c 00000014 b xDelayedTaskList2
|
||||
2000d058 00000014 b xDelayedTaskList1
|
||||
2000d2f0 00000014 b xActiveTimerList2
|
||||
2000d2dc 00000014 b xActiveTimerList1
|
||||
2000b480 00000014 B SPI
|
||||
2000c8c4 00000014 B Serial
|
||||
2000cd28 00000014 b _ctrl_xfer
|
||||
2000de30 00000011 b serial_str.13534
|
||||
2000c544 00000010 b BLEAdvertising::_start(unsigned short, unsigned short)::gap_adv
|
||||
20003614 00000010 d meshtastic::btPIN
|
||||
2000434c 00000010 b sendOwnerPeriod
|
||||
2000ae8c 00000010 b staticPool
|
||||
2000e484 00000010 B xQueueRegistry
|
||||
20003b04 00000010 B stateSERIAL
|
||||
20003af4 00000010 B stateSDS
|
||||
20003ae4 00000010 B stateON
|
||||
20003ad4 00000010 B stateNB
|
||||
20003ac4 00000010 B stateLS
|
||||
20003ab4 00000010 B stateDARK
|
||||
20003aa4 00000010 B stateBOOT
|
||||
200041f8 00000010 B ledPeriodic
|
||||
2000b244 00000010 B hrms
|
||||
2000d9f4 00000010 b _acDownBuffer
|
||||
2000b3b8 0000000c B preflightSleep
|
||||
20004208 0000000c B powerStatus
|
||||
2000e540 0000000c B nrf_nvic_state
|
||||
2000b3ac 0000000c B notifySleep
|
||||
2000b3a0 0000000c B notifyDeepSleep
|
||||
2000e463 0000000b b __tzname_std
|
||||
2000e458 0000000b b __tzname_dst
|
||||
2000b338 00000008 b meshtastic::estimatedHeading(double, double)::oldLon
|
||||
2000b330 00000008 b meshtastic::estimatedHeading(double, double)::oldLat
|
||||
200041d0 00000008 b zeroOffsetSecs
|
||||
2000ae80 00000008 b spiSettings
|
||||
200038b8 00000008 D _tzname
|
||||
20003b14 00000008 B noopPrint
|
||||
2000cfc4 00000008 b channelMap
|
||||
2000cf9c 00000008 b callbackDeferred
|
||||
200043ac 00000006 b ourMacAddr
|
||||
2000435c 00000004 b MeshService::onGPSChanged(void*)::lastGpsSend
|
||||
2000b32c 00000004 b meshtastic::estimatedHeading(double, double)::b
|
||||
2000b328 00000004 b meshtastic::drawNodeInfo(OLEDDisplay*, OLEDDisplayUiState*, short, short)::simRadian
|
||||
2000362c 00000004 d meshtastic::Screen::setup()::bootFrames
|
||||
20003628 00000004 d meshtastic::Screen::handleStartBluetoothPinScreen(unsigned long)::btFrames
|
||||
200039ac 00000004 b onEnter()::lastPingMs
|
||||
2000ae9c 00000004 b generatePacketId()::i
|
||||
2000ae88 00000004 B RadioLibInterface::instance
|
||||
2000b2e8 00000004 b meshtastic::nodeIndex
|
||||
20003610 00000004 d meshtastic::targetFramerate
|
||||
2000c554 00000004 B BLEService::lastService
|
||||
200041cc 00000004 b timeStartMsec
|
||||
200036dc 00000004 d sbrk_heap_top
|
||||
2000d364 00000004 b _loopHandle
|
||||
2000c540 00000004 b guard variable for BLEAdvertising::_start(unsigned short, unsigned short)::gap_adv
|
||||
2000d0d0 00000004 b xYieldPending
|
||||
2000d35c 00000004 b xTimerTaskHandle
|
||||
2000d358 00000004 b xTimerQueue
|
||||
2000d0cc 00000004 b xTickCount
|
||||
2000d0a0 00000004 b xSchedulerRunning
|
||||
2000d088 00000004 b xNumOfOverflows
|
||||
2000d084 00000004 b xNextTaskUnblockTime
|
||||
2000d304 00000004 b xLastTime.9343
|
||||
2000d080 00000004 b xIdleTaskHandle
|
||||
2000d054 00000004 b uxTopReadyPriority
|
||||
2000d050 00000004 b uxTaskNumber
|
||||
2000d04c 00000004 b uxSchedulerSuspended
|
||||
2000d048 00000004 b uxPendedTicks
|
||||
2000d044 00000004 b uxDeletedTasksWaitingCleanUp
|
||||
2000d040 00000004 b uxCurrentNumberOfTasks
|
||||
2000d360 00000004 b uxCriticalNesting
|
||||
2000cc64 00000004 b _usbd_q
|
||||
2000e478 00000004 B _timezone
|
||||
200036e0 00000004 D SystemCoreClock
|
||||
2000c53c 00000004 b _sem
|
||||
2000d0d8 00000004 b pxOverflowTimerList
|
||||
2000cfd8 00000004 b pxOverflowDelayedTaskList
|
||||
2000cfd4 00000004 b pxDelayedTaskList
|
||||
2000d0d4 00000004 b pxCurrentTimerList
|
||||
2000cfd0 00000004 B pxCurrentTCB
|
||||
2000e470 00000004 b prev_tzenv
|
||||
2000360c 00000004 D preftmp
|
||||
20003608 00000004 D preffile
|
||||
2000b25c 00000004 B nrf52Bluetooth
|
||||
2000d370 00000004 b m_usbevt_handler
|
||||
2000d36c 00000004 b m_sleepevt_handler
|
||||
2000d368 00000004 b m_pofwarn_handler
|
||||
2000e454 00000004 B __malloc_sbrk_start
|
||||
2000e450 00000004 B __malloc_free_list
|
||||
2000e480 00000004 B MAIN_MonCnt
|
||||
2000e47c 00000004 b initial_env
|
||||
200036e8 00000004 D _impure_ptr
|
||||
200041d8 00000004 B gps
|
||||
2000e7a4 00000004 B errno
|
||||
20003918 00000004 D environ
|
||||
2000cfcc 00000004 b enabled
|
||||
2000ae64 00000004 B displayedNodeNum
|
||||
2000e474 00000004 B _daylight
|
||||
2000b254 00000004 B crypto
|
||||
2000ce44 00000004 B count_duration
|
||||
2000de0c 00000004 b _cb_task
|
||||
2000de08 00000004 b _cb_queue
|
||||
2000de04 00000004 b _cb_qdepth
|
||||
2000de44 00000004 B bootloaderVersion
|
||||
200041f5 00000001 b ledBlinker()::ledOn
|
||||
20003604 00000001 d loop::showingBootScreen
|
||||
200041f4 00000001 b loop::wasPressed
|
||||
2000b494 00000001 b DefaultFontTableLookup(unsigned char)::LASTCHAR
|
||||
2000aea0 00000001 b generatePacketId()::didInit
|
||||
20003624 00000001 d meshtastic::prevFrame
|
||||
2000b258 00000001 b bleOn
|
||||
200041dc 00000001 B timeSetFromGPS
|
||||
20004348 00000001 B ssd1306_found
|
||||
2000ce49 00000001 B pin_sound
|
||||
2000e494 00000001 B nrfx_power_irq_enabled
|
||||
2000ce48 00000001 B no_stop
|
||||
20003630 00000001 D neo6M
|
||||
2000ce40 00000001 b _initialized
|
||||
200036e4 00000001 D __fdlib_version
|
||||
20003970 00000001 b completed.9929
|
||||
19
gdbinit
Normal file
19
gdbinit
Normal file
@@ -0,0 +1,19 @@
|
||||
|
||||
# Setup Monitor Mode Debugging
|
||||
# Per .platformio/packages/framework-arduinoadafruitnrf52-old/cores/nRF5/linker/nrf52840_s140_v6.ld
|
||||
# our appload starts at 0x26000
|
||||
# Disable for now because our version on board doesn't support monitor mode debugging
|
||||
# mon exec SetMonModeDebug=1
|
||||
# mon exec SetMonModeVTableAddr=0x26000
|
||||
|
||||
# echo setting RTTAddr
|
||||
# eval "monitor exec SetRTTAddr %p", &_SEGGER_RTT
|
||||
|
||||
# the jlink debugger seems to want a pause after reset before we tell it to start running
|
||||
define restart
|
||||
echo Restarting
|
||||
monitor reset
|
||||
shell sleep 1
|
||||
cont
|
||||
end
|
||||
|
||||
@@ -1,312 +0,0 @@
|
||||
#include "BluetoothUtil.h"
|
||||
#include "BluetoothSoftwareUpdate.h"
|
||||
#include <esp_gatt_defs.h>
|
||||
#include <BLE2902.h>
|
||||
#include <Arduino.h>
|
||||
#include <Update.h>
|
||||
#include "configuration.h"
|
||||
|
||||
SimpleAllocator btPool;
|
||||
|
||||
/**
|
||||
* Create standard device info service
|
||||
**/
|
||||
BLEService *createDeviceInfomationService(BLEServer *server, std::string hwVendor, std::string swVersion, std::string hwVersion = "")
|
||||
{
|
||||
BLEService *deviceInfoService = server->createService(BLEUUID((uint16_t)ESP_GATT_UUID_DEVICE_INFO_SVC));
|
||||
|
||||
BLECharacteristic *swC = new BLECharacteristic(BLEUUID((uint16_t)ESP_GATT_UUID_SW_VERSION_STR), BLECharacteristic::PROPERTY_READ);
|
||||
BLECharacteristic *mfC = new BLECharacteristic(BLEUUID((uint16_t)ESP_GATT_UUID_MANU_NAME), BLECharacteristic::PROPERTY_READ);
|
||||
// BLECharacteristic SerialNumberCharacteristic(BLEUUID((uint16_t) ESP_GATT_UUID_SERIAL_NUMBER_STR), BLECharacteristic::PROPERTY_READ);
|
||||
|
||||
/*
|
||||
* Mandatory characteristic for device info service?
|
||||
|
||||
BLECharacteristic *m_pnpCharacteristic = m_deviceInfoService->createCharacteristic(ESP_GATT_UUID_PNP_ID, BLECharacteristic::PROPERTY_READ);
|
||||
|
||||
uint8_t sig, uint16_t vid, uint16_t pid, uint16_t version;
|
||||
uint8_t pnp[] = { sig, (uint8_t) (vid >> 8), (uint8_t) vid, (uint8_t) (pid >> 8), (uint8_t) pid, (uint8_t) (version >> 8), (uint8_t) version };
|
||||
m_pnpCharacteristic->setValue(pnp, sizeof(pnp));
|
||||
*/
|
||||
swC->setValue(swVersion);
|
||||
deviceInfoService->addCharacteristic(addBLECharacteristic(swC));
|
||||
mfC->setValue(hwVendor);
|
||||
deviceInfoService->addCharacteristic(addBLECharacteristic(mfC));
|
||||
if (!hwVersion.empty())
|
||||
{
|
||||
BLECharacteristic *hwvC = new BLECharacteristic(BLEUUID((uint16_t)ESP_GATT_UUID_HW_VERSION_STR), BLECharacteristic::PROPERTY_READ);
|
||||
hwvC->setValue(hwVersion);
|
||||
deviceInfoService->addCharacteristic(addBLECharacteristic(hwvC));
|
||||
}
|
||||
//SerialNumberCharacteristic.setValue("FIXME");
|
||||
//deviceInfoService->addCharacteristic(&SerialNumberCharacteristic);
|
||||
|
||||
// m_manufacturerCharacteristic = m_deviceInfoService->createCharacteristic((uint16_t) 0x2a29, BLECharacteristic::PROPERTY_READ);
|
||||
// m_manufacturerCharacteristic->setValue(name);
|
||||
|
||||
/* add these later?
|
||||
ESP_GATT_UUID_SYSTEM_ID
|
||||
*/
|
||||
|
||||
// caller must call service->start();
|
||||
return deviceInfoService;
|
||||
}
|
||||
|
||||
bool _BLEClientConnected = false;
|
||||
|
||||
class MyServerCallbacks : public BLEServerCallbacks
|
||||
{
|
||||
void onConnect(BLEServer *pServer)
|
||||
{
|
||||
_BLEClientConnected = true;
|
||||
};
|
||||
|
||||
void onDisconnect(BLEServer *pServer)
|
||||
{
|
||||
_BLEClientConnected = false;
|
||||
}
|
||||
};
|
||||
|
||||
#define MAX_DESCRIPTORS 32
|
||||
#define MAX_CHARACTERISTICS 32
|
||||
|
||||
static BLECharacteristic *chars[MAX_CHARACTERISTICS];
|
||||
static size_t numChars;
|
||||
static BLEDescriptor *descs[MAX_DESCRIPTORS];
|
||||
static size_t numDescs;
|
||||
|
||||
/// Add a characteristic that we will delete when we restart
|
||||
BLECharacteristic *addBLECharacteristic(BLECharacteristic *c)
|
||||
{
|
||||
assert(numChars < MAX_CHARACTERISTICS);
|
||||
chars[numChars++] = c;
|
||||
return c;
|
||||
}
|
||||
|
||||
/// Add a characteristic that we will delete when we restart
|
||||
BLEDescriptor *addBLEDescriptor(BLEDescriptor *c)
|
||||
{
|
||||
assert(numDescs < MAX_DESCRIPTORS);
|
||||
descs[numDescs++] = c;
|
||||
|
||||
return c;
|
||||
}
|
||||
|
||||
// Help routine to add a description to any BLECharacteristic and add it to the service
|
||||
// We default to require an encrypted BOND for all these these characterstics
|
||||
void addWithDesc(BLEService *service, BLECharacteristic *c, const char *description)
|
||||
{
|
||||
c->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED);
|
||||
|
||||
BLEDescriptor *desc = new BLEDescriptor(BLEUUID((uint16_t)ESP_GATT_UUID_CHAR_DESCRIPTION), strlen(description) + 1);
|
||||
assert(desc);
|
||||
desc->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED);
|
||||
desc->setValue(description);
|
||||
c->addDescriptor(desc);
|
||||
service->addCharacteristic(c);
|
||||
addBLECharacteristic(c);
|
||||
addBLEDescriptor(desc);
|
||||
}
|
||||
|
||||
static BLECharacteristic *batteryLevelC;
|
||||
|
||||
/**
|
||||
* Create a battery level service
|
||||
*/
|
||||
BLEService *createBatteryService(BLEServer *server)
|
||||
{
|
||||
// Create the BLE Service
|
||||
BLEService *pBattery = server->createService(BLEUUID((uint16_t)0x180F));
|
||||
|
||||
batteryLevelC = new BLECharacteristic(BLEUUID((uint16_t)ESP_GATT_UUID_BATTERY_LEVEL), BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
|
||||
|
||||
addWithDesc(pBattery, batteryLevelC, "Percentage 0 - 100");
|
||||
batteryLevelC->addDescriptor(addBLEDescriptor(new BLE2902())); // Needed so clients can request notification
|
||||
|
||||
// I don't think we need to advertise this
|
||||
// server->getAdvertising()->addServiceUUID(pBattery->getUUID());
|
||||
pBattery->start();
|
||||
|
||||
return pBattery;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the battery level we are currently telling clients.
|
||||
* level should be a pct between 0 and 100
|
||||
*/
|
||||
void updateBatteryLevel(uint8_t level)
|
||||
{
|
||||
// Pretend to update battery levels - fixme do elsewhere
|
||||
if (batteryLevelC)
|
||||
{
|
||||
batteryLevelC->setValue(&level, 1);
|
||||
batteryLevelC->notify();
|
||||
}
|
||||
}
|
||||
|
||||
void dumpCharacteristic(BLECharacteristic *c)
|
||||
{
|
||||
std::string value = c->getValue();
|
||||
|
||||
if (value.length() > 0)
|
||||
{
|
||||
DEBUG_MSG("New value: ");
|
||||
for (int i = 0; i < value.length(); i++)
|
||||
DEBUG_MSG("%c", value[i]);
|
||||
|
||||
DEBUG_MSG("\n");
|
||||
}
|
||||
}
|
||||
|
||||
/** converting endianness pull out a 32 bit value */
|
||||
uint32_t getValue32(BLECharacteristic *c, uint32_t defaultValue)
|
||||
{
|
||||
std::string value = c->getValue();
|
||||
uint32_t r = defaultValue;
|
||||
|
||||
if (value.length() == 4)
|
||||
r = value[0] | (value[1] << 8UL) | (value[2] << 16UL) | (value[3] << 24UL);
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
class MySecurity : public BLESecurityCallbacks
|
||||
{
|
||||
protected:
|
||||
bool onConfirmPIN(uint32_t pin)
|
||||
{
|
||||
Serial.printf("onConfirmPIN %u\n", pin);
|
||||
return false;
|
||||
}
|
||||
|
||||
uint32_t onPassKeyRequest()
|
||||
{
|
||||
Serial.println("onPassKeyRequest");
|
||||
return 123511; // not used
|
||||
}
|
||||
|
||||
void onPassKeyNotify(uint32_t pass_key)
|
||||
{
|
||||
Serial.printf("onPassKeyNotify %u\n", pass_key);
|
||||
startCb(pass_key);
|
||||
}
|
||||
|
||||
bool onSecurityRequest()
|
||||
{
|
||||
Serial.println("onSecurityRequest");
|
||||
return true;
|
||||
}
|
||||
|
||||
void onAuthenticationComplete(esp_ble_auth_cmpl_t cmpl)
|
||||
{
|
||||
if (cmpl.success)
|
||||
{
|
||||
uint16_t length;
|
||||
esp_ble_gap_get_whitelist_size(&length);
|
||||
Serial.printf(" onAuthenticationComplete -> success size: %d\n", length);
|
||||
}
|
||||
else
|
||||
{
|
||||
Serial.printf("onAuthenticationComplete -> fail %d\n", cmpl.fail_reason);
|
||||
}
|
||||
|
||||
// Remove our custom PIN request screen.
|
||||
stopCb();
|
||||
}
|
||||
|
||||
public:
|
||||
StartBluetoothPinScreenCallback startCb;
|
||||
StopBluetoothPinScreenCallback stopCb;
|
||||
};
|
||||
|
||||
BLEServer *pServer;
|
||||
|
||||
BLEService *pDevInfo, *pUpdate;
|
||||
|
||||
void deinitBLE()
|
||||
{
|
||||
assert(pServer);
|
||||
|
||||
pServer->getAdvertising()->stop();
|
||||
|
||||
destroyUpdateService();
|
||||
|
||||
pUpdate->stop();
|
||||
pDevInfo->stop();
|
||||
pUpdate->stop(); // we delete them below
|
||||
|
||||
// First shutdown bluetooth
|
||||
BLEDevice::deinit(false);
|
||||
|
||||
// do not delete this - it is dynamically allocated, but only once - statically in BLEDevice
|
||||
// delete pServer->getAdvertising();
|
||||
|
||||
delete pUpdate;
|
||||
delete pDevInfo;
|
||||
delete pServer;
|
||||
|
||||
batteryLevelC = NULL; // Don't let anyone generate bogus notifies
|
||||
|
||||
for (int i = 0; i < numChars; i++)
|
||||
delete chars[i];
|
||||
numChars = 0;
|
||||
|
||||
for (int i = 0; i < numDescs; i++)
|
||||
delete descs[i];
|
||||
numDescs = 0;
|
||||
|
||||
btPool.reset();
|
||||
}
|
||||
|
||||
BLEServer *initBLE(
|
||||
StartBluetoothPinScreenCallback startBtPinScreen,
|
||||
StopBluetoothPinScreenCallback stopBtPinScreen,
|
||||
std::string deviceName, std::string hwVendor, std::string swVersion, std::string hwVersion)
|
||||
{
|
||||
BLEDevice::init(deviceName);
|
||||
BLEDevice::setEncryptionLevel(ESP_BLE_SEC_ENCRYPT);
|
||||
|
||||
/*
|
||||
* Required in authentication process to provide displaying and/or input passkey or yes/no butttons confirmation
|
||||
*/
|
||||
static MySecurity mySecurity;
|
||||
mySecurity.startCb = startBtPinScreen;
|
||||
mySecurity.stopCb = stopBtPinScreen;
|
||||
BLEDevice::setSecurityCallbacks(&mySecurity);
|
||||
|
||||
// Create the BLE Server
|
||||
pServer = BLEDevice::createServer();
|
||||
static MyServerCallbacks myCallbacks;
|
||||
pServer->setCallbacks(&myCallbacks);
|
||||
|
||||
pDevInfo = createDeviceInfomationService(pServer, hwVendor, swVersion, hwVersion);
|
||||
|
||||
// We now let users create the battery service only if they really want (not all devices have a battery)
|
||||
// BLEService *pBattery = createBatteryService(pServer);
|
||||
|
||||
pUpdate = createUpdateService(pServer, hwVendor, swVersion, hwVersion); // We need to advertise this so our android ble scan operation can see it
|
||||
|
||||
// It seems only one service can be advertised - so for now don't advertise our updater
|
||||
// pServer->getAdvertising()->addServiceUUID(pUpdate->getUUID());
|
||||
|
||||
// start all our services (do this after creating all of them)
|
||||
pDevInfo->start();
|
||||
pUpdate->start();
|
||||
|
||||
// FIXME turn on this restriction only after the device is paired with a phone
|
||||
// advert->setScanFilter(false, true); // We let anyone scan for us (FIXME, perhaps only allow that until we are paired with a phone and configured) but only let whitelist phones connect
|
||||
|
||||
static BLESecurity security; // static to avoid allocs
|
||||
BLESecurity *pSecurity = &security;
|
||||
pSecurity->setCapability(ESP_IO_CAP_OUT);
|
||||
pSecurity->setAuthenticationMode(ESP_LE_AUTH_REQ_SC_BOND);
|
||||
pSecurity->setInitEncryptionKey(ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK);
|
||||
|
||||
return pServer;
|
||||
}
|
||||
|
||||
// Called from loop
|
||||
void loopBLE()
|
||||
{
|
||||
bluetoothRebootCheck();
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
#pragma once
|
||||
#include "PowerFSM.h" // FIXME - someday I want to make this OTA thing a separate lb at at that point it can't touch this
|
||||
#include "BLECharacteristic.h"
|
||||
|
||||
/**
|
||||
* This mixin just lets the power management state machine know the phone is still talking to us
|
||||
*/
|
||||
class BLEKeepAliveCallbacks : public BLECharacteristicCallbacks
|
||||
{
|
||||
public:
|
||||
void onRead(BLECharacteristic *c)
|
||||
{
|
||||
powerFSM.trigger(EVENT_CONTACT_FROM_PHONE);
|
||||
}
|
||||
|
||||
void onWrite(BLECharacteristic *c)
|
||||
{
|
||||
powerFSM.trigger(EVENT_CONTACT_FROM_PHONE);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* A characterstic with a set of overridable callbacks
|
||||
*/
|
||||
class CallbackCharacteristic : public BLECharacteristic, public BLEKeepAliveCallbacks
|
||||
{
|
||||
public:
|
||||
CallbackCharacteristic(const char *uuid, uint32_t btprops)
|
||||
: BLECharacteristic(uuid, btprops)
|
||||
{
|
||||
setCallbacks(this);
|
||||
}
|
||||
};
|
||||
@@ -11,7 +11,7 @@
|
||||
*****************************************************************/
|
||||
|
||||
/* Enable support for dynamically allocated fields */
|
||||
/* #define PB_ENABLE_MALLOC 1 */
|
||||
#define PB_ENABLE_MALLOC 1
|
||||
|
||||
/* Define this if your CPU / compiler combination does not support
|
||||
* unaligned memory access to packed structures. */
|
||||
18
linker/esp32.extram.bss.ld
Normal file
18
linker/esp32.extram.bss.ld
Normal file
@@ -0,0 +1,18 @@
|
||||
/* This section is only included if CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY
|
||||
is set, to link some sections to BSS in PSRAM */
|
||||
|
||||
SECTIONS
|
||||
{
|
||||
/* external memory bss, from any global variable with EXT_RAM_ATTR attribute*/
|
||||
.ext_ram.bss (NOLOAD) :
|
||||
{
|
||||
_ext_ram_bss_start = ABSOLUTE(.);
|
||||
*(.ext_ram.bss*)
|
||||
*libnet80211.a:(.dynsbss .sbss .sbss.* .gnu.linkonce.sb.* .scommon .sbss2.* .gnu.linkonce.sb2.* .dynbss .bss .bss.* .share.mem .gnu.linkonce.b.* COMMON)
|
||||
*libpp.a:(.dynsbss .sbss .sbss.* .gnu.linkonce.sb.* .scommon .sbss2.* .gnu.linkonce.sb2.* .dynbss .bss .bss.* .share.mem .gnu.linkonce.b.* COMMON)
|
||||
*liblwip.a:(.dynsbss .sbss .sbss.* .gnu.linkonce.sb.* .scommon .sbss2.* .gnu.linkonce.sb2.* .dynbss .bss .bss.* .share.mem .gnu.linkonce.b.* COMMON)
|
||||
*libbt.a:(EXCLUDE_FILE (libbtdm_app.a) .dynsbss .sbss .sbss.* .gnu.linkonce.sb.* .scommon .sbss2.* .gnu.linkonce.sb2.* .dynbss .bss .bss.* .share.mem .gnu.linkonce.b.* COMMON)
|
||||
. = ALIGN(4);
|
||||
_ext_ram_bss_end = ABSOLUTE(.);
|
||||
} > extern_ram_seg
|
||||
}
|
||||
46
linker/nrf52840_s140_sim832.ld
Normal file
46
linker/nrf52840_s140_sim832.ld
Normal file
@@ -0,0 +1,46 @@
|
||||
/* Linker script to configure memory regions.
|
||||
|
||||
geeksville: modified this to simulate a nrf52832 but with a sd140 soft device. So I can
|
||||
see how the memory footprint works on this lower end CPU. Note: to work with sd140 in my bootloader
|
||||
I need to start ram at 0x6000 (instead of the correct 0x3600 for sd132) - so I have less
|
||||
RAM available than on a real 832.
|
||||
*/
|
||||
|
||||
SEARCH_DIR(.)
|
||||
GROUP(-lgcc -lc -lnosys)
|
||||
|
||||
MEMORY
|
||||
{
|
||||
FLASH (rx) : ORIGIN = 0x26000, LENGTH = 0x6D000 - 0x26000
|
||||
/* FLASH (rx) : ORIGIN = 0x26000, LENGTH = 0xED000 - 0x26000 */
|
||||
|
||||
/* SRAM required by S132 depend on
|
||||
* - Attribute Table Size
|
||||
* - Vendor UUID count
|
||||
* - Max ATT MTU
|
||||
* - Concurrent connection peripheral + central + secure links
|
||||
* - Event Len, HVN queue, Write CMD queue
|
||||
*/
|
||||
/* RAM (rwx) : ORIGIN = 0x20003600, LENGTH = 0x20010000 - 0x20003600 */
|
||||
RAM (rwx) : ORIGIN = 0x20006000, LENGTH = 0x20010000 - 0x20006000
|
||||
}
|
||||
|
||||
SECTIONS
|
||||
{
|
||||
. = ALIGN(4);
|
||||
.svc_data :
|
||||
{
|
||||
PROVIDE(__start_svc_data = .);
|
||||
KEEP(*(.svc_data))
|
||||
PROVIDE(__stop_svc_data = .);
|
||||
} > RAM
|
||||
|
||||
.fs_data :
|
||||
{
|
||||
PROVIDE(__start_fs_data = .);
|
||||
KEEP(*(.fs_data))
|
||||
PROVIDE(__stop_fs_data = .);
|
||||
} > RAM
|
||||
} INSERT AFTER .data;
|
||||
|
||||
INCLUDE "nrf52_common.ld"
|
||||
@@ -9,15 +9,20 @@
|
||||
; https://docs.platformio.org/page/projectconf.html
|
||||
|
||||
[platformio]
|
||||
default_envs = tbeam
|
||||
default_envs = tbeam ; Note: the github actions CI test build can't yet build NRF52 targets
|
||||
|
||||
[common]
|
||||
; default to a US frequency range, change it as needed for your region and hardware (CN, JP, EU433, EU865)
|
||||
hw_version = US
|
||||
; common is not currently used
|
||||
|
||||
; REQUIRED environment variables - if not set the specified default will be sued
|
||||
; The following environment variables must be set in the shell if you'd like to override them.
|
||||
; They are used in this ini file as systenv.VARNAME, so in your shell do export "VARNAME=fish"
|
||||
; COUNTRY (default US), i.e. "export COUNTRY=EU865"
|
||||
; APP_VERSION (default emptystring)
|
||||
; HW_VERSION (default emptystring)
|
||||
|
||||
[env]
|
||||
platform = espressif32
|
||||
|
||||
framework = arduino
|
||||
|
||||
; customize the partition table
|
||||
@@ -26,7 +31,11 @@ board_build.partitions = partition-table.csv
|
||||
|
||||
; note: we add src to our include search path so that lmic_project_config can override
|
||||
; FIXME: fix lib/BluetoothOTA dependency back on src/ so we can remove -Isrc
|
||||
build_flags = -Wno-missing-field-initializers -Isrc -Isrc/rf95 -Os -Wl,-Map,.pio/build/output.map -DAXP_DEBUG_PORT=Serial -DHW_VERSION_${common.hw_version}
|
||||
build_flags = -Wno-missing-field-initializers -Isrc -Isrc/mesh -Isrc/gps -Ilib/nanopb/include -Os -Wl,-Map,.pio/build/output.map
|
||||
-DAXP_DEBUG_PORT=Serial
|
||||
-DHW_VERSION_${sysenv.COUNTRY}
|
||||
-DAPP_VERSION=${sysenv.APP_VERSION}
|
||||
-DHW_VERSION=${sysenv.HW_VERSION}
|
||||
|
||||
; not needed included in ttgo-t-beam board file
|
||||
; also to use PSRAM https://docs.platformio.org/en/latest/platforms/espressif32.html#external-ram-psram
|
||||
@@ -42,7 +51,8 @@ build_flags = -Wno-missing-field-initializers -Isrc -Isrc/rf95 -Os -Wl,-Map,.pio
|
||||
; the default is esptool
|
||||
; upload_protocol = esp-prog
|
||||
|
||||
monitor_speed = 115200
|
||||
; monitor_speed = 115200
|
||||
monitor_speed = 921600
|
||||
|
||||
# debug_tool = esp-prog
|
||||
# debug_port = /dev/ttyACM0
|
||||
@@ -59,20 +69,28 @@ debug_tool = jlink
|
||||
lib_deps =
|
||||
https://github.com/meshtastic/esp8266-oled-ssd1306.git ; ESP8266_SSD1306
|
||||
SPI
|
||||
; 1260 ; OneButton - not used yet
|
||||
1260 ; OneButton library for non-blocking button debounce
|
||||
1202 ; CRC32, explicitly needed because dependency is missing in the ble ota update lib
|
||||
Wire ; explicitly needed here because the AXP202 library forgets to add it
|
||||
https://github.com/meshtastic/arduino-fsm.git
|
||||
https://github.com/meshtastic/SparkFun_Ublox_Arduino_Library.git
|
||||
https://github.com/meshtastic/RadioLib.git
|
||||
https://github.com/meshtastic/TinyGPSPlus.git
|
||||
|
||||
; Common settings for ESP targes, mixin with extends = esp32_base
|
||||
[esp32_base]
|
||||
platform = espressif32
|
||||
src_filter =
|
||||
${env.src_filter} -<bare/>
|
||||
${env.src_filter} -<nrf52/>
|
||||
upload_speed = 921600
|
||||
debug_init_break = tbreak setup
|
||||
build_flags =
|
||||
${env.build_flags} -Wall -Wextra
|
||||
${env.build_flags} -Wall -Wextra -Isrc/esp32 -mfix-esp32-psram-cache-issue
|
||||
# Hmm - this doesn't work yet
|
||||
# board_build.ldscript = linker/esp32.extram.bss.ld
|
||||
lib_ignore = segger_rtt
|
||||
platform_packages =
|
||||
framework-arduinoespressif32 @ https://github.com/meshtastic/arduino-esp32.git#f26c4f96fefd13ed0ed042e27954f8aba6328f6b
|
||||
|
||||
; The 1.0 release of the TBEAM board
|
||||
[env:tbeam]
|
||||
@@ -80,7 +98,8 @@ extends = esp32_base
|
||||
board = ttgo-t-beam
|
||||
lib_deps =
|
||||
${env.lib_deps}
|
||||
AXP202X_Library
|
||||
https://github.com/meshtastic/AXP202X_Library.git
|
||||
|
||||
build_flags =
|
||||
${esp32_base.build_flags} -D TBEAM_V10
|
||||
|
||||
@@ -110,19 +129,59 @@ board = ttgo-lora32-v1
|
||||
build_flags =
|
||||
${esp32_base.build_flags} -D TTGO_LORA_V2
|
||||
|
||||
; The Heltec Cubecell plus
|
||||
; IMPORTANT NOTE: This target doesn't yet work and probably won't ever work. I'm keeping it around for now.
|
||||
; For more details see my post in the forum.
|
||||
[env:cubecellplus]
|
||||
platform = https://github.com/HelTecAutomation/platform-asrmicro650x.git ; we use top-of-tree because stable version has too many bugs - asrmicro650x
|
||||
board = cubecell_board_plus
|
||||
; FIXME, bug in cubecell arduino - they are supposed to set ARDUINO
|
||||
build_flags = ${env.build_flags} -DARDUINO=100 -Isrc/cubecell
|
||||
src_filter =
|
||||
${env.src_filter} -<esp32/> -<nrf52/>
|
||||
|
||||
; This is a temporary build target to test turning off particular hardare bits in the build (to improve modularity)
|
||||
[env:bare]
|
||||
; Common settings for NRF52 based targets
|
||||
[nrf52_base]
|
||||
platform = nordicnrf52
|
||||
board = nrf52840_dk_adafruit ; nicer than nrf52840_dk - more full gpio mappings
|
||||
framework = arduino
|
||||
debug_tool = jlink
|
||||
build_type = debug ; I'm debugging with ICE a lot now
|
||||
; note: liboberon provides the AES256 implementation for NRF52 (though not using the hardware acceleration of the NRF52840 - FIXME)
|
||||
build_flags =
|
||||
${env.build_flags} -D BARE_BOARD -Wno-unused-variable -Isrc/bare
|
||||
${env.build_flags} -Wno-unused-variable -Isrc/nrf52 -Isdk-nrfxlib/crypto/nrf_oberon/include -Lsdk-nrfxlib/crypto/nrf_oberon/lib/cortex-m4/hard-float/ -lliboberon_3.0.3
|
||||
;-DCFG_DEBUG=3
|
||||
src_filter =
|
||||
${env.src_filter} -<esp32/>
|
||||
lib_ignore =
|
||||
BluetoothOTA
|
||||
monitor_port = /dev/ttyACM1
|
||||
|
||||
debug_extra_cmds =
|
||||
source gdbinit
|
||||
|
||||
; after programming the flash, reset the initial PC
|
||||
; debug_load_cmds = load
|
||||
|
||||
; Set initial breakpoint (defaults to main)
|
||||
debug_init_break =
|
||||
;debug_init_break = tbreak loop
|
||||
;debug_init_break = tbreak Reset_Handler
|
||||
|
||||
; The NRF52840-dk development board
|
||||
[env:nrf52dk]
|
||||
extends = nrf52_base
|
||||
board = nrf52840_dk_modified
|
||||
|
||||
# For experimenting with RAM sizes
|
||||
# board_build.ldscript = linker/nrf52840_s140_sim832.ld
|
||||
|
||||
; The PPR board
|
||||
[env:ppr]
|
||||
extends = nrf52_base
|
||||
board = ppr
|
||||
lib_deps =
|
||||
${env.lib_deps}
|
||||
monitor_port = /dev/ttyACM1
|
||||
UC1701
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
2
proto
2
proto
Submodule proto updated: e06645d8db...ab281311c4
1
sdk-nrfxlib
Submodule
1
sdk-nrfxlib
Submodule
Submodule sdk-nrfxlib added at 17e8453553
222
src/GPS.cpp
222
src/GPS.cpp
@@ -1,222 +0,0 @@
|
||||
|
||||
#include "GPS.h"
|
||||
#include "configuration.h"
|
||||
#include "time.h"
|
||||
#include <assert.h>
|
||||
#include <sys/time.h>
|
||||
|
||||
#ifdef GPS_RX_PIN
|
||||
HardwareSerial _serial_gps(GPS_SERIAL_NUM);
|
||||
#else
|
||||
// Assume NRF52
|
||||
// Uart _serial_gps(GPS_SERIAL_NUM);
|
||||
#endif
|
||||
|
||||
bool timeSetFromGPS; // We try to set our time from GPS each time we wake from sleep
|
||||
|
||||
GPS gps;
|
||||
|
||||
// stuff that really should be in in the instance instead...
|
||||
static uint32_t
|
||||
timeStartMsec; // Once we have a GPS lock, this is where we hold the initial msec clock that corresponds to that time
|
||||
static uint64_t zeroOffsetSecs; // GPS based time in secs since 1970 - only updated once on initial lock
|
||||
|
||||
static bool wantNewLocation = true;
|
||||
|
||||
GPS::GPS() : PeriodicTask() {}
|
||||
|
||||
void GPS::setup()
|
||||
{
|
||||
readFromRTC(); // read the main CPU RTC at first
|
||||
|
||||
#ifdef GPS_RX_PIN
|
||||
_serial_gps.begin(GPS_BAUDRATE, SERIAL_8N1, GPS_RX_PIN, GPS_TX_PIN);
|
||||
// _serial_gps.setRxBufferSize(1024); // the default is 256
|
||||
// ublox.enableDebugging(Serial);
|
||||
|
||||
// note: the lib's implementation has the wrong docs for what the return val is
|
||||
// it is not a bool, it returns zero for success
|
||||
isConnected = ublox.begin(_serial_gps);
|
||||
|
||||
// try a second time, the ublox lib serial parsing is buggy?
|
||||
if (!isConnected)
|
||||
isConnected = ublox.begin(_serial_gps);
|
||||
|
||||
if (isConnected) {
|
||||
DEBUG_MSG("Connected to GPS successfully, TXpin=%d\n", GPS_TX_PIN);
|
||||
|
||||
bool factoryReset = false;
|
||||
bool ok;
|
||||
if (factoryReset) {
|
||||
// It is useful to force back into factory defaults (9600baud, NEMA to test the behavior of boards that don't have
|
||||
// GPS_TX connected)
|
||||
ublox.factoryReset();
|
||||
delay(2000);
|
||||
isConnected = ublox.begin(_serial_gps);
|
||||
DEBUG_MSG("Factory reset success=%d\n", isConnected);
|
||||
if (isConnected) {
|
||||
ublox.assumeAutoPVT(true, true); // Just parse NEMA for now
|
||||
}
|
||||
} else {
|
||||
ok = ublox.setUART1Output(COM_TYPE_UBX, 500); // Use native API
|
||||
assert(ok);
|
||||
ok = ublox.setNavigationFrequency(1, 500); // Produce 4x/sec to keep the amount of time we stall in getPVT low
|
||||
assert(ok);
|
||||
// ok = ublox.setAutoPVT(false); // Not implemented on NEO-6M
|
||||
// assert(ok);
|
||||
// ok = ublox.setDynamicModel(DYN_MODEL_BIKE); // probably PEDESTRIAN but just in case assume bike speeds
|
||||
// assert(ok);
|
||||
ok = ublox.powerSaveMode(); // use power save mode
|
||||
assert(ok);
|
||||
}
|
||||
ok = ublox.saveConfiguration(2000);
|
||||
assert(ok);
|
||||
} else {
|
||||
// Some boards might have only the TX line from the GPS connected, in that case, we can't configure it at all. Just
|
||||
// assume NEMA at 9600 baud.
|
||||
DEBUG_MSG("ERROR: No bidirectional GPS found, hoping that it still might work\n");
|
||||
|
||||
// tell lib, we are expecting the module to send PVT messages by itself to our Rx pin
|
||||
// you can set second parameter to "false" if you want to control the parsing and eviction of the data (need to call
|
||||
// checkUblox cyclically)
|
||||
ublox.assumeAutoPVT(true, true);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void GPS::readFromRTC()
|
||||
{
|
||||
struct timeval tv; /* btw settimeofday() is helpfull here too*/
|
||||
|
||||
if (!gettimeofday(&tv, NULL)) {
|
||||
uint32_t now = millis();
|
||||
|
||||
DEBUG_MSG("Read RTC time as %ld (cur millis %u) valid=%d\n", tv.tv_sec, now, timeSetFromGPS);
|
||||
timeStartMsec = now;
|
||||
zeroOffsetSecs = tv.tv_sec;
|
||||
}
|
||||
}
|
||||
|
||||
/// If we haven't yet set our RTC this boot, set it from a GPS derived time
|
||||
void GPS::perhapsSetRTC(const struct timeval *tv)
|
||||
{
|
||||
if (!timeSetFromGPS) {
|
||||
timeSetFromGPS = true;
|
||||
DEBUG_MSG("Setting RTC %ld secs\n", tv->tv_sec);
|
||||
#ifndef NO_ESP32
|
||||
settimeofday(tv, NULL);
|
||||
#else
|
||||
assert(0);
|
||||
#endif
|
||||
readFromRTC();
|
||||
}
|
||||
}
|
||||
|
||||
#include <time.h>
|
||||
|
||||
// for the time being we need to rapidly read from the serial port to prevent overruns
|
||||
void GPS::loop()
|
||||
{
|
||||
PeriodicTask::loop();
|
||||
}
|
||||
|
||||
uint32_t GPS::getTime()
|
||||
{
|
||||
return ((millis() - timeStartMsec) / 1000) + zeroOffsetSecs;
|
||||
}
|
||||
|
||||
uint32_t GPS::getValidTime()
|
||||
{
|
||||
return timeSetFromGPS ? getTime() : 0;
|
||||
}
|
||||
|
||||
/// Returns true if we think the board can enter deep or light sleep now (we might be trying to get a GPS lock)
|
||||
bool GPS::canSleep()
|
||||
{
|
||||
return true; // we leave GPS on during sleep now, so sleep is okay !wantNewLocation;
|
||||
}
|
||||
|
||||
/// Prepare the GPS for the cpu entering deep or light sleep, expect to be gone for at least 100s of msecs
|
||||
void GPS::prepareSleep()
|
||||
{
|
||||
if (isConnected)
|
||||
ublox.powerOff();
|
||||
}
|
||||
|
||||
void GPS::doTask()
|
||||
{
|
||||
#ifdef GPS_RX_PIN
|
||||
uint8_t fixtype = 3; // If we are only using the RX pin, assume we have a 3d fix
|
||||
|
||||
if (isConnected) {
|
||||
// Consume all characters that have arrived
|
||||
|
||||
// getPVT automatically calls checkUblox
|
||||
ublox.checkUblox(); // See if new data is available. Process bytes as they come in.
|
||||
|
||||
// If we don't have a fix (a quick check), don't try waiting for a solution)
|
||||
// Hmmm my fix type reading returns zeros for fix, which doesn't seem correct, because it is still sptting out positions
|
||||
// turn off for now
|
||||
// fixtype = ublox.getFixType();
|
||||
DEBUG_MSG("fix type %d\n", fixtype);
|
||||
}
|
||||
|
||||
// DEBUG_MSG("sec %d\n", ublox.getSecond());
|
||||
// DEBUG_MSG("lat %d\n", ublox.getLatitude());
|
||||
|
||||
// any fix that has time
|
||||
if (!timeSetFromGPS && ublox.getT()) {
|
||||
struct timeval tv;
|
||||
|
||||
/* Convert to unix time
|
||||
The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970
|
||||
(midnight UTC/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z).
|
||||
*/
|
||||
struct tm t;
|
||||
t.tm_sec = ublox.getSecond();
|
||||
t.tm_min = ublox.getMinute();
|
||||
t.tm_hour = ublox.getHour();
|
||||
t.tm_mday = ublox.getDay();
|
||||
t.tm_mon = ublox.getMonth() - 1;
|
||||
t.tm_year = ublox.getYear() - 1900;
|
||||
t.tm_isdst = false;
|
||||
time_t res = mktime(&t);
|
||||
tv.tv_sec = res;
|
||||
tv.tv_usec = 0; // time.centisecond() * (10 / 1000);
|
||||
|
||||
DEBUG_MSG("Got time from GPS month=%d, year=%d, unixtime=%ld\n", t.tm_mon, t.tm_year, tv.tv_sec);
|
||||
if (t.tm_year < 0 || t.tm_year >= 300)
|
||||
DEBUG_MSG("Ignoring invalid GPS time\n");
|
||||
else
|
||||
perhapsSetRTC(&tv);
|
||||
}
|
||||
|
||||
if ((fixtype >= 3 && fixtype <= 4) && ublox.getP()) // rd fixes only
|
||||
{
|
||||
// we only notify if position has changed
|
||||
latitude = ublox.getLatitude() * 1e-7;
|
||||
longitude = ublox.getLongitude() * 1e-7;
|
||||
altitude = ublox.getAltitude() / 1000; // in mm convert to meters
|
||||
DEBUG_MSG("new gps pos lat=%f, lon=%f, alt=%d\n", latitude, longitude, altitude);
|
||||
|
||||
hasValidLocation = (latitude != 0) || (longitude != 0); // bogus lat lon is reported as 0,0
|
||||
if (hasValidLocation) {
|
||||
wantNewLocation = false;
|
||||
notifyObservers(NULL);
|
||||
// ublox.powerOff();
|
||||
}
|
||||
} else // we didn't get a location update, go back to sleep and hope the characters show up
|
||||
wantNewLocation = true;
|
||||
#endif
|
||||
|
||||
// Once we have sent a location once we only poll the GPS rarely, otherwise check back every 1s until we have something over
|
||||
// the serial
|
||||
setPeriod(hasValidLocation && !wantNewLocation ? 30 * 1000 : 10 * 1000);
|
||||
}
|
||||
|
||||
void GPS::startLock()
|
||||
{
|
||||
DEBUG_MSG("Looking for GPS lock\n");
|
||||
wantNewLocation = true;
|
||||
setPeriod(1);
|
||||
}
|
||||
57
src/GPS.h
57
src/GPS.h
@@ -1,57 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "Observer.h"
|
||||
#include "PeriodicTask.h"
|
||||
#include "SparkFun_Ublox_Arduino_Library.h"
|
||||
#include "sys/time.h"
|
||||
|
||||
/**
|
||||
* A gps class that only reads from the GPS periodically (and FIXME - eventually keeps the gps powered down except when reading)
|
||||
*
|
||||
* When new data is available it will notify observers.
|
||||
*/
|
||||
class GPS : public PeriodicTask, public Observable<void *>
|
||||
{
|
||||
SFE_UBLOX_GPS ublox;
|
||||
|
||||
public:
|
||||
double latitude, longitude;
|
||||
uint32_t altitude;
|
||||
bool isConnected; // Do we have a GPS we are talking to
|
||||
|
||||
GPS();
|
||||
|
||||
/// Return time since 1970 in secs. Until we have a GPS lock we will be returning time based at zero
|
||||
uint32_t getTime();
|
||||
|
||||
/// Return time since 1970 in secs. If we don't have a GPS lock return zero
|
||||
uint32_t getValidTime();
|
||||
|
||||
void setup();
|
||||
|
||||
virtual void loop();
|
||||
|
||||
virtual void doTask();
|
||||
|
||||
/// If we haven't yet set our RTC this boot, set it from a GPS derived time
|
||||
void perhapsSetRTC(const struct timeval *tv);
|
||||
|
||||
/// Returns true if we think the board can enter deep or light sleep now (we might be trying to get a GPS lock)
|
||||
bool canSleep();
|
||||
|
||||
/// Prepare the GPS for the cpu entering deep or light sleep, expect to be gone for at least 100s of msecs
|
||||
void prepareSleep();
|
||||
|
||||
/// Restart our lock attempt - try to get and broadcast a GPS reading ASAP
|
||||
void startLock();
|
||||
|
||||
/// Returns ture if we have acquired GPS lock.
|
||||
bool hasLock() const { return hasValidLocation; }
|
||||
|
||||
private:
|
||||
void readFromRTC();
|
||||
|
||||
bool hasValidLocation = false; // default to false, until we complete our first read
|
||||
};
|
||||
|
||||
extern GPS gps;
|
||||
108
src/GPSStatus.h
Normal file
108
src/GPSStatus.h
Normal file
@@ -0,0 +1,108 @@
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
#include "Status.h"
|
||||
#include "configuration.h"
|
||||
|
||||
namespace meshtastic {
|
||||
|
||||
/// Describes the state of the GPS system.
|
||||
class GPSStatus : public Status
|
||||
{
|
||||
|
||||
private:
|
||||
CallbackObserver<GPSStatus, const GPSStatus *> statusObserver = CallbackObserver<GPSStatus, const GPSStatus *>(this, &GPSStatus::updateStatus);
|
||||
|
||||
bool hasLock = false; // default to false, until we complete our first read
|
||||
bool isConnected = false; // Do we have a GPS we are talking to
|
||||
int32_t latitude = 0, longitude = 0; // as an int mult by 1e-7 to get value as double
|
||||
int32_t altitude = 0;
|
||||
uint32_t dop = 0; // Diminution of position; PDOP where possible (UBlox), HDOP otherwise (TinyGPS) in 10^2 units (needs scaling before use)
|
||||
|
||||
public:
|
||||
|
||||
GPSStatus() {
|
||||
statusType = STATUS_TYPE_GPS;
|
||||
}
|
||||
GPSStatus( bool hasLock, bool isConnected, int32_t latitude, int32_t longitude, int32_t altitude, uint32_t dop ) : Status()
|
||||
{
|
||||
this->hasLock = hasLock;
|
||||
this->isConnected = isConnected;
|
||||
this->latitude = latitude;
|
||||
this->longitude = longitude;
|
||||
this->altitude = altitude;
|
||||
this->dop = dop;
|
||||
}
|
||||
GPSStatus(const GPSStatus &);
|
||||
GPSStatus &operator=(const GPSStatus &);
|
||||
|
||||
void observe(Observable<const GPSStatus *> *source)
|
||||
{
|
||||
statusObserver.observe(source);
|
||||
}
|
||||
|
||||
bool getHasLock() const
|
||||
{
|
||||
return hasLock;
|
||||
}
|
||||
|
||||
bool getIsConnected() const
|
||||
{
|
||||
return isConnected;
|
||||
}
|
||||
|
||||
int32_t getLatitude() const
|
||||
{
|
||||
return latitude;
|
||||
}
|
||||
|
||||
int32_t getLongitude() const
|
||||
{
|
||||
return longitude;
|
||||
}
|
||||
|
||||
int32_t getAltitude() const
|
||||
{
|
||||
return altitude;
|
||||
}
|
||||
|
||||
uint32_t getDOP() const
|
||||
{
|
||||
return dop;
|
||||
}
|
||||
|
||||
bool matches(const GPSStatus *newStatus) const
|
||||
{
|
||||
return (
|
||||
newStatus->hasLock != hasLock ||
|
||||
newStatus->isConnected != isConnected ||
|
||||
newStatus->latitude != latitude ||
|
||||
newStatus->longitude != longitude ||
|
||||
newStatus->altitude != altitude ||
|
||||
newStatus->dop != dop
|
||||
);
|
||||
}
|
||||
int updateStatus(const GPSStatus *newStatus) {
|
||||
// Only update the status if values have actually changed
|
||||
bool isDirty;
|
||||
{
|
||||
isDirty = matches(newStatus);
|
||||
initialized = true;
|
||||
hasLock = newStatus->hasLock;
|
||||
isConnected = newStatus->isConnected;
|
||||
latitude = newStatus->latitude;
|
||||
longitude = newStatus->longitude;
|
||||
altitude = newStatus->altitude;
|
||||
dop = newStatus->dop;
|
||||
}
|
||||
if(isDirty) {
|
||||
DEBUG_MSG("New GPS pos lat=%f, lon=%f, alt=%d, pdop=%f\n", latitude * 1e-7, longitude * 1e-7, altitude, dop * 1e-2);
|
||||
onNewStatus.notifyObservers(this);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
extern meshtastic::GPSStatus *gpsStatus;
|
||||
@@ -1,125 +0,0 @@
|
||||
#include "error.h"
|
||||
#include <SPI.h>
|
||||
#include <assert.h>
|
||||
|
||||
#include "MeshRadio.h"
|
||||
#include "MeshService.h"
|
||||
#include "NodeDB.h"
|
||||
#include "configuration.h"
|
||||
#include "sleep.h"
|
||||
#include <pb_decode.h>
|
||||
#include <pb_encode.h>
|
||||
|
||||
/**
|
||||
* ## LoRaWAN for North America
|
||||
|
||||
LoRaWAN defines 64, 125 kHz channels from 902.3 to 914.9 MHz increments.
|
||||
|
||||
The maximum output power for North America is +30 dBM.
|
||||
|
||||
The band is from 902 to 928 MHz. It mentions channel number and its respective channel frequency. All the 13 channels are
|
||||
separated by 2.16 MHz with respect to the adjacent channels. Channel zero starts at 903.08 MHz center frequency.
|
||||
*/
|
||||
|
||||
/// Sometimes while debugging it is useful to set this false, to disable rf95 accesses
|
||||
bool useHardware = true;
|
||||
|
||||
MeshRadio::MeshRadio() // , manager(radioIf)
|
||||
{
|
||||
myNodeInfo.num_channels = NUM_CHANNELS;
|
||||
|
||||
// Can't print strings this early - serial not setup yet
|
||||
// DEBUG_MSG("Set meshradio defaults name=%s\n", channelSettings.name);
|
||||
}
|
||||
|
||||
bool MeshRadio::init()
|
||||
{
|
||||
if (!useHardware)
|
||||
return true;
|
||||
|
||||
DEBUG_MSG("Starting meshradio init...\n");
|
||||
|
||||
configChangedObserver.observe(&service.configChanged);
|
||||
preflightSleepObserver.observe(&preflightSleep);
|
||||
notifyDeepSleepObserver.observe(¬ifyDeepSleep);
|
||||
|
||||
#ifdef RESET_GPIO
|
||||
pinMode(RESET_GPIO, OUTPUT); // Deassert reset
|
||||
digitalWrite(RESET_GPIO, HIGH);
|
||||
|
||||
// pulse reset
|
||||
digitalWrite(RESET_GPIO, LOW);
|
||||
delay(10);
|
||||
digitalWrite(RESET_GPIO, HIGH);
|
||||
delay(10);
|
||||
#endif
|
||||
|
||||
radioIf.setThisAddress(
|
||||
nodeDB.getNodeNum()); // Note: we must do this here, because the nodenum isn't inited at constructor time.
|
||||
|
||||
if (!radioIf.init()) {
|
||||
DEBUG_MSG("LoRa radio init failed\n");
|
||||
DEBUG_MSG("Uncomment '#define SERIAL_DEBUG' in RH_RF95.cpp for detailed debug info\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
// not needed - defaults on
|
||||
// rf95.setPayloadCRC(true);
|
||||
|
||||
reloadConfig();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** hash a string into an integer
|
||||
*
|
||||
* djb2 by Dan Bernstein.
|
||||
* http://www.cse.yorku.ca/~oz/hash.html
|
||||
*/
|
||||
unsigned long hash(char *str)
|
||||
{
|
||||
unsigned long hash = 5381;
|
||||
int c;
|
||||
|
||||
while ((c = *str++) != 0)
|
||||
hash = ((hash << 5) + hash) + (unsigned char)c; /* hash * 33 + c */
|
||||
|
||||
return hash;
|
||||
}
|
||||
|
||||
int MeshRadio::reloadConfig(void *unused)
|
||||
{
|
||||
radioIf.setModeIdle(); // Need to be idle before doing init
|
||||
|
||||
// Set up default configuration
|
||||
// No Sync Words in LORA mode.
|
||||
radioIf.setModemConfig(
|
||||
(RH_RF95::ModemConfigChoice)channelSettings.modem_config); // Radio default
|
||||
// setModemConfig(Bw125Cr48Sf4096); // slow and reliable?
|
||||
// rf95.setPreambleLength(8); // Default is 8
|
||||
|
||||
// Defaults after init are 434.0MHz, modulation GFSK_Rb250Fd250, +13dbM
|
||||
int channel_num = hash(channelSettings.name) % NUM_CHANNELS;
|
||||
float center_freq = CH0 + CH_SPACING * channel_num;
|
||||
if (!radioIf.setFrequency(center_freq)) {
|
||||
DEBUG_MSG("setFrequency failed\n");
|
||||
assert(0); // fixme panic
|
||||
}
|
||||
|
||||
// Defaults after init are 434.0MHz, 13dBm, Bw = 125 kHz, Cr = 4/5, Sf = 128chips/symbol, CRC on
|
||||
|
||||
// The default transmitter power is 13dBm, using PA_BOOST.
|
||||
// If you are using RFM95/96/97/98 modules which uses the PA_BOOST transmitter pin, then
|
||||
// you can set transmitter powers from 5 to 23 dBm:
|
||||
// FIXME - can we do this? It seems to be in the Heltec board.
|
||||
radioIf.setTxPower(channelSettings.tx_power, false);
|
||||
|
||||
DEBUG_MSG("Set radio: name=%s, config=%u, ch=%d, txpower=%d\n", channelSettings.name, channelSettings.modem_config,
|
||||
channel_num, channelSettings.tx_power);
|
||||
|
||||
// Done with init tell radio to start receiving
|
||||
radioIf.setModeRx();
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
104
src/MeshRadio.h
104
src/MeshRadio.h
@@ -1,104 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "CustomRF95.h"
|
||||
#include "MemoryPool.h"
|
||||
#include "MeshTypes.h"
|
||||
#include "Observer.h"
|
||||
#include "PointerQueue.h"
|
||||
#include "configuration.h"
|
||||
#include "mesh.pb.h"
|
||||
|
||||
// US channel settings
|
||||
#define CH0_US 903.08f // MHz
|
||||
#define CH_SPACING_US 2.16f // MHz
|
||||
#define NUM_CHANNELS_US 13
|
||||
|
||||
// EU433 channel settings
|
||||
#define CH0_EU433 433.175f // MHz
|
||||
#define CH_SPACING_EU433 0.2f // MHz
|
||||
#define NUM_CHANNELS_EU433 8
|
||||
|
||||
// EU865 channel settings
|
||||
#define CH0_EU865 865.2f // MHz
|
||||
#define CH_SPACING_EU865 0.3f // MHz
|
||||
#define NUM_CHANNELS_EU865 10
|
||||
|
||||
// CN channel settings
|
||||
#define CH0_CN 470.0f // MHz
|
||||
#define CH_SPACING_CN 2.0f // MHz FIXME, this is just a guess for 470-510
|
||||
#define NUM_CHANNELS_CN 20
|
||||
|
||||
// JP channel settings
|
||||
#define CH0_JP 920.0f // MHz
|
||||
#define CH_SPACING_JP 0.5f // MHz FIXME, this is just a guess for 920-925
|
||||
#define NUM_CHANNELS_JP 10
|
||||
|
||||
// FIXME add defs for other regions and use them here
|
||||
#ifdef HW_VERSION_US
|
||||
#define CH0 CH0_US
|
||||
#define CH_SPACING CH_SPACING_US
|
||||
#define NUM_CHANNELS NUM_CHANNELS_US
|
||||
#elif defined(HW_VERSION_EU433)
|
||||
#define CH0 CH0_EU433
|
||||
#define CH_SPACING CH_SPACING_EU433
|
||||
#define NUM_CHANNELS NUM_CHANNELS_EU433
|
||||
#elif defined(HW_VERSION_EU865)
|
||||
#define CH0 CH0_EU865
|
||||
#define CH_SPACING CH_SPACING_EU865
|
||||
#define NUM_CHANNELS NUM_CHANNELS_EU865
|
||||
#elif defined(HW_VERSION_CN)
|
||||
#define CH0 CH0_CN
|
||||
#define CH_SPACING CH_SPACING_CN
|
||||
#define NUM_CHANNELS NUM_CHANNELS_CN
|
||||
#elif defined(HW_VERSION_JP)
|
||||
#define CH0 CH0_JP
|
||||
#define CH_SPACING CH_SPACING_JP
|
||||
#define NUM_CHANNELS NUM_CHANNELS_JP
|
||||
#else
|
||||
#error "HW_VERSION not set"
|
||||
#endif
|
||||
|
||||
/**
|
||||
* A raw low level interface to our mesh. Only understands nodenums and bytes (not protobufs or node ids)
|
||||
*/
|
||||
class MeshRadio
|
||||
{
|
||||
public:
|
||||
// Kinda ugly way of selecting different radio implementations, but soon this MeshRadio class will be going away
|
||||
// entirely. At that point we can make things pretty.
|
||||
#ifdef RF95_IRQ_GPIO
|
||||
CustomRF95
|
||||
radioIf; // the raw radio interface - for now I'm leaving public - because this class is shrinking to be almost nothing
|
||||
#else
|
||||
SimRadio radioIf;
|
||||
#endif
|
||||
|
||||
/** pool is the pool we will alloc our rx packets from
|
||||
* rxDest is where we will send any rx packets, it becomes receivers responsibility to return packet to the pool
|
||||
*/
|
||||
MeshRadio();
|
||||
|
||||
bool init();
|
||||
|
||||
private:
|
||||
CallbackObserver<MeshRadio, void *> configChangedObserver =
|
||||
CallbackObserver<MeshRadio, void *>(this, &MeshRadio::reloadConfig);
|
||||
|
||||
CallbackObserver<MeshRadio, void *> preflightSleepObserver =
|
||||
CallbackObserver<MeshRadio, void *>(this, &MeshRadio::preflightSleepCb);
|
||||
|
||||
CallbackObserver<MeshRadio, void *> notifyDeepSleepObserver =
|
||||
CallbackObserver<MeshRadio, void *>(this, &MeshRadio::notifyDeepSleepDb);
|
||||
|
||||
/// The radioConfig object just changed, call this to force the hw to change to the new settings
|
||||
int reloadConfig(void *unused = NULL);
|
||||
|
||||
/// Return 0 if sleep is okay
|
||||
int preflightSleepCb(void *unused = NULL) { return radioIf.canSleep() ? 0 : 1; }
|
||||
|
||||
int notifyDeepSleepDb(void *unused = NULL)
|
||||
{
|
||||
radioIf.sleep();
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
@@ -1,19 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
// low level types
|
||||
|
||||
#include "MemoryPool.h"
|
||||
#include "mesh.pb.h"
|
||||
#include <Arduino.h>
|
||||
|
||||
typedef uint8_t NodeNum;
|
||||
typedef uint8_t PacketId; // A packet sequence number
|
||||
|
||||
#define NODENUM_BROADCAST 255
|
||||
#define ERRNO_OK 0
|
||||
#define ERRNO_UNKNOWN 32 // pick something that doesn't conflict with RH_ROUTER_ERROR_UNABLE_TO_DELIVER
|
||||
|
||||
typedef int ErrorCode;
|
||||
|
||||
/// Alloc and free packets to our global, ISR safe pool
|
||||
extern MemoryPool<MeshPacket> packetPool;
|
||||
73
src/NodeStatus.h
Normal file
73
src/NodeStatus.h
Normal file
@@ -0,0 +1,73 @@
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
#include "Status.h"
|
||||
#include "configuration.h"
|
||||
|
||||
namespace meshtastic {
|
||||
|
||||
/// Describes the state of the NodeDB system.
|
||||
class NodeStatus : public Status
|
||||
{
|
||||
|
||||
private:
|
||||
CallbackObserver<NodeStatus, const NodeStatus *> statusObserver = CallbackObserver<NodeStatus, const NodeStatus *>(this, &NodeStatus::updateStatus);
|
||||
|
||||
uint8_t numOnline = 0;
|
||||
uint8_t numTotal = 0;
|
||||
|
||||
public:
|
||||
|
||||
NodeStatus() {
|
||||
statusType = STATUS_TYPE_NODE;
|
||||
}
|
||||
NodeStatus( uint8_t numOnline, uint8_t numTotal ) : Status()
|
||||
{
|
||||
this->numOnline = numOnline;
|
||||
this->numTotal = numTotal;
|
||||
}
|
||||
NodeStatus(const NodeStatus &);
|
||||
NodeStatus &operator=(const NodeStatus &);
|
||||
|
||||
void observe(Observable<const NodeStatus *> *source)
|
||||
{
|
||||
statusObserver.observe(source);
|
||||
}
|
||||
|
||||
uint8_t getNumOnline() const
|
||||
{
|
||||
return numOnline;
|
||||
}
|
||||
|
||||
uint8_t getNumTotal() const
|
||||
{
|
||||
return numTotal;
|
||||
}
|
||||
|
||||
bool matches(const NodeStatus *newStatus) const
|
||||
{
|
||||
return (
|
||||
newStatus->getNumOnline() != numOnline ||
|
||||
newStatus->getNumTotal() != numTotal
|
||||
);
|
||||
}
|
||||
int updateStatus(const NodeStatus *newStatus) {
|
||||
// Only update the status if values have actually changed
|
||||
bool isDirty;
|
||||
{
|
||||
isDirty = matches(newStatus);
|
||||
initialized = true;
|
||||
numOnline = newStatus->getNumOnline();
|
||||
numTotal = newStatus->getNumTotal();
|
||||
}
|
||||
if(isDirty) {
|
||||
DEBUG_MSG("Node status update: %d online, %d total\n", numOnline, numTotal);
|
||||
onNewStatus.notifyObservers(this);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
extern meshtastic::NodeStatus *nodeStatus;
|
||||
49
src/OSTimer.cpp
Normal file
49
src/OSTimer.cpp
Normal file
@@ -0,0 +1,49 @@
|
||||
#include "OSTimer.h"
|
||||
#include "configuration.h"
|
||||
|
||||
/**
|
||||
* Schedule a callback to run. The callback must _not_ block, though it is called from regular thread level (not ISR)
|
||||
*
|
||||
* NOTE! xTimerPend... seems to ignore the time passed in on ESP32 and on NRF52
|
||||
* The reason this didn't work is bcause xTimerPednFunctCall really isn't a timer function at all - it just means run the callback
|
||||
* from the timer thread the next time you have spare cycles.
|
||||
*
|
||||
* @return true if successful, false if the timer fifo is too full.
|
||||
|
||||
bool scheduleOSCallback(PendableFunction callback, void *param1, uint32_t param2, uint32_t delayMsec)
|
||||
{
|
||||
return xTimerPendFunctionCall(callback, param1, param2, pdMS_TO_TICKS(delayMsec));
|
||||
} */
|
||||
|
||||
#ifndef NO_ESP32
|
||||
|
||||
// Super skanky quick hack to use hardware timers of the ESP32
|
||||
static hw_timer_t *timer;
|
||||
static PendableFunction tCallback;
|
||||
static void *tParam1;
|
||||
static uint32_t tParam2;
|
||||
|
||||
static void IRAM_ATTR onTimer()
|
||||
{
|
||||
(*tCallback)(tParam1, tParam2);
|
||||
}
|
||||
|
||||
bool scheduleHWCallback(PendableFunction callback, void *param1, uint32_t param2, uint32_t delayMsec)
|
||||
{
|
||||
if (!timer) {
|
||||
timer = timerBegin(0, 80, true); // one usec per tick (main clock is 80MhZ on ESP32)
|
||||
assert(timer);
|
||||
timerAttachInterrupt(timer, &onTimer, true);
|
||||
}
|
||||
|
||||
tCallback = callback;
|
||||
tParam1 = param1;
|
||||
tParam2 = param2;
|
||||
|
||||
timerAlarmWrite(timer, delayMsec * 1000L, false); // Do not reload, we want it to be a single shot timer
|
||||
timerRestart(timer);
|
||||
timerAlarmEnable(timer);
|
||||
return true;
|
||||
}
|
||||
|
||||
#endif
|
||||
8
src/OSTimer.h
Normal file
8
src/OSTimer.h
Normal file
@@ -0,0 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
typedef void (*PendableFunction)(void *pvParameter1, uint32_t ulParameter2);
|
||||
|
||||
/// Uses a hardware timer, but calls the handler in _interrupt_ context
|
||||
bool scheduleHWCallback(PendableFunction callback, void *param1, uint32_t param2, uint32_t delayMsec);
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
#include <assert.h>
|
||||
#include <list>
|
||||
|
||||
template <class T> class Observable;
|
||||
@@ -14,7 +14,6 @@ template <class T> class Observer
|
||||
Observable<T> *observed = NULL;
|
||||
|
||||
public:
|
||||
|
||||
virtual ~Observer();
|
||||
|
||||
void observe(Observable<T> *o);
|
||||
|
||||
@@ -1,21 +1,39 @@
|
||||
#include "PeriodicTask.h"
|
||||
#include "Periodic.h"
|
||||
PeriodicScheduler periodicScheduler;
|
||||
|
||||
PeriodicTask::PeriodicTask(uint32_t initialPeriod) : period(initialPeriod) {}
|
||||
|
||||
/// call this from loop
|
||||
void PeriodicTask::loop()
|
||||
void PeriodicTask::setup()
|
||||
{
|
||||
periodicScheduler.schedule(this);
|
||||
}
|
||||
|
||||
/// call this from loop
|
||||
void PeriodicScheduler::loop()
|
||||
{
|
||||
meshtastic::LockGuard lg(&lock);
|
||||
|
||||
uint32_t now = millis();
|
||||
if (!period || (now - lastMsec) < period) {
|
||||
return;
|
||||
for (auto t : tasks) {
|
||||
if (t->period && (now - t->lastMsec) >= t->period) {
|
||||
|
||||
t->doTask();
|
||||
t->lastMsec = now;
|
||||
}
|
||||
lastMsec = now;
|
||||
}
|
||||
// Release the lock in case the task wants to change the period.
|
||||
doTask();
|
||||
}
|
||||
|
||||
void PeriodicScheduler::schedule(PeriodicTask *t)
|
||||
{
|
||||
meshtastic::LockGuard lg(&lock);
|
||||
tasks.insert(t);
|
||||
}
|
||||
|
||||
void PeriodicScheduler::unschedule(PeriodicTask *t)
|
||||
{
|
||||
meshtastic::LockGuard lg(&lock);
|
||||
tasks.erase(t);
|
||||
}
|
||||
|
||||
void Periodic::doTask()
|
||||
|
||||
@@ -1,8 +1,41 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "lock.h"
|
||||
#include <Arduino.h>
|
||||
#include <cstdint>
|
||||
#include <unordered_set>
|
||||
|
||||
class PeriodicTask;
|
||||
|
||||
/**
|
||||
* Runs all PeriodicTasks in the system.
|
||||
*
|
||||
* Currently called from main loop() but eventually should be its own thread blocked on a freertos timer.
|
||||
*/
|
||||
class PeriodicScheduler
|
||||
{
|
||||
friend class PeriodicTask;
|
||||
|
||||
/**
|
||||
* This really should be some form of heap, and when the period gets changed on a task it should get
|
||||
* rescheduled in that heap. Currently it is just a dumb array and everytime we run loop() we check
|
||||
* _every_ tasks. If it was a heap we'd only have to check the first task.
|
||||
*/
|
||||
std::unordered_set<PeriodicTask *> tasks;
|
||||
|
||||
// Protects the above variables.
|
||||
meshtastic::Lock lock;
|
||||
|
||||
public:
|
||||
/// Run any next tasks which are due for execution
|
||||
void loop();
|
||||
|
||||
private:
|
||||
void schedule(PeriodicTask *t);
|
||||
void unschedule(PeriodicTask *t);
|
||||
};
|
||||
|
||||
extern PeriodicScheduler periodicScheduler;
|
||||
|
||||
/**
|
||||
* A base class for tasks that want their doTask() method invoked periodically
|
||||
@@ -13,27 +46,40 @@
|
||||
*/
|
||||
class PeriodicTask
|
||||
{
|
||||
friend class PeriodicScheduler;
|
||||
|
||||
uint32_t lastMsec = 0;
|
||||
uint32_t period = 1; // call soon after creation
|
||||
|
||||
// Protects the above variables.
|
||||
meshtastic::Lock lock;
|
||||
|
||||
public:
|
||||
virtual ~PeriodicTask() {}
|
||||
virtual ~PeriodicTask() { periodicScheduler.unschedule(this); }
|
||||
|
||||
/**
|
||||
* Constructor (will schedule with the global PeriodicScheduler)
|
||||
*/
|
||||
PeriodicTask(uint32_t initialPeriod = 1);
|
||||
|
||||
/// call this from loop
|
||||
virtual void loop();
|
||||
/** MUST be be called once at startup (but after threading is running - i.e. not from a constructor)
|
||||
*/
|
||||
void setup();
|
||||
|
||||
/// Set a new period in msecs (can be called from doTask or elsewhere and the scheduler will cope)
|
||||
/**
|
||||
* Set a new period in msecs (can be called from doTask or elsewhere and the scheduler will cope)
|
||||
* While zero this task is disabled and will not run
|
||||
*/
|
||||
void setPeriod(uint32_t p)
|
||||
{
|
||||
meshtastic::LockGuard lg(&lock);
|
||||
lastMsec = millis(); // reset starting from now
|
||||
period = p;
|
||||
}
|
||||
|
||||
uint32_t getPeriod() const { return period; }
|
||||
|
||||
/**
|
||||
* Syntatic sugar for suspending tasks
|
||||
*/
|
||||
void disable() { setPeriod(0); }
|
||||
|
||||
protected:
|
||||
virtual void doTask() = 0;
|
||||
};
|
||||
|
||||
180
src/Power.cpp
Normal file
180
src/Power.cpp
Normal file
@@ -0,0 +1,180 @@
|
||||
#include "power.h"
|
||||
#include "PowerFSM.h"
|
||||
#include "main.h"
|
||||
#include "utils.h"
|
||||
#include "sleep.h"
|
||||
|
||||
|
||||
#ifdef TBEAM_V10
|
||||
|
||||
// FIXME. nasty hack cleanup how we load axp192
|
||||
#undef AXP192_SLAVE_ADDRESS
|
||||
#include "axp20x.h"
|
||||
AXP20X_Class axp;
|
||||
bool pmu_irq = false;
|
||||
|
||||
Power *power;
|
||||
|
||||
bool Power::setup()
|
||||
{
|
||||
|
||||
axp192Init();
|
||||
PeriodicTask::setup(); // We don't start our periodic task unless we actually found the device
|
||||
setPeriod(1);
|
||||
|
||||
return axp192_found;
|
||||
}
|
||||
|
||||
/// Reads power status to powerStatus singleton.
|
||||
//
|
||||
// TODO(girts): move this and other axp stuff to power.h/power.cpp.
|
||||
void Power::readPowerStatus()
|
||||
{
|
||||
bool hasBattery = axp.isBatteryConnect();
|
||||
int batteryVoltageMv = 0;
|
||||
uint8_t batteryChargePercent = 0;
|
||||
if (hasBattery) {
|
||||
batteryVoltageMv = axp.getBattVoltage();
|
||||
// If the AXP192 returns a valid battery percentage, use it
|
||||
if (axp.getBattPercentage() >= 0) {
|
||||
batteryChargePercent = axp.getBattPercentage();
|
||||
} else {
|
||||
// If the AXP192 returns a percentage less than 0, the feature is either not supported or there is an error
|
||||
// In that case, we compute an estimate of the charge percent based on maximum and minimum voltages defined in power.h
|
||||
batteryChargePercent = clamp((int)(((batteryVoltageMv - BAT_MILLIVOLTS_EMPTY) * 1e2) / (BAT_MILLIVOLTS_FULL - BAT_MILLIVOLTS_EMPTY)), 0, 100);
|
||||
}
|
||||
}
|
||||
|
||||
// Notify any status instances that are observing us
|
||||
const meshtastic::PowerStatus powerStatus = meshtastic::PowerStatus(hasBattery, axp.isVBUSPlug(), axp.isChargeing(), batteryVoltageMv, batteryChargePercent);
|
||||
newStatus.notifyObservers(&powerStatus);
|
||||
|
||||
// If we have a battery at all and it is less than 10% full, force deep sleep
|
||||
if (powerStatus.getHasBattery() && !powerStatus.getHasUSB() &&
|
||||
axp.getBattVoltage() < MIN_BAT_MILLIVOLTS)
|
||||
powerFSM.trigger(EVENT_LOW_BATTERY);
|
||||
}
|
||||
|
||||
void Power::doTask()
|
||||
{
|
||||
readPowerStatus();
|
||||
|
||||
// Only read once every 20 seconds once the power status for the app has been initialized
|
||||
if(statusHandler && statusHandler->isInitialized())
|
||||
setPeriod(1000 * 20);
|
||||
}
|
||||
#endif // TBEAM_V10
|
||||
|
||||
#ifdef AXP192_SLAVE_ADDRESS
|
||||
/**
|
||||
* Init the power manager chip
|
||||
*
|
||||
* axp192 power
|
||||
DCDC1 0.7-3.5V @ 1200mA max -> OLED // If you turn this off you'll lose comms to the axp192 because the OLED and the axp192
|
||||
share the same i2c bus, instead use ssd1306 sleep mode DCDC2 -> unused DCDC3 0.7-3.5V @ 700mA max -> ESP32 (keep this on!) LDO1
|
||||
30mA -> charges GPS backup battery // charges the tiny J13 battery by the GPS to power the GPS ram (for a couple of days), can
|
||||
not be turned off LDO2 200mA -> LORA LDO3 200mA -> GPS
|
||||
*/
|
||||
void Power::axp192Init()
|
||||
{
|
||||
if (axp192_found) {
|
||||
if (!axp.begin(Wire, AXP192_SLAVE_ADDRESS)) {
|
||||
DEBUG_MSG("AXP192 Begin PASS\n");
|
||||
|
||||
// axp.setChgLEDMode(LED_BLINK_4HZ);
|
||||
DEBUG_MSG("DCDC1: %s\n", axp.isDCDC1Enable() ? "ENABLE" : "DISABLE");
|
||||
DEBUG_MSG("DCDC2: %s\n", axp.isDCDC2Enable() ? "ENABLE" : "DISABLE");
|
||||
DEBUG_MSG("LDO2: %s\n", axp.isLDO2Enable() ? "ENABLE" : "DISABLE");
|
||||
DEBUG_MSG("LDO3: %s\n", axp.isLDO3Enable() ? "ENABLE" : "DISABLE");
|
||||
DEBUG_MSG("DCDC3: %s\n", axp.isDCDC3Enable() ? "ENABLE" : "DISABLE");
|
||||
DEBUG_MSG("Exten: %s\n", axp.isExtenEnable() ? "ENABLE" : "DISABLE");
|
||||
DEBUG_MSG("----------------------------------------\n");
|
||||
|
||||
axp.setPowerOutPut(AXP192_LDO2, AXP202_ON); // LORA radio
|
||||
axp.setPowerOutPut(AXP192_LDO3, AXP202_ON); // GPS main power
|
||||
axp.setPowerOutPut(AXP192_DCDC2, AXP202_ON);
|
||||
axp.setPowerOutPut(AXP192_EXTEN, AXP202_ON);
|
||||
axp.setPowerOutPut(AXP192_DCDC1, AXP202_ON);
|
||||
axp.setDCDC1Voltage(3300); // for the OLED power
|
||||
|
||||
DEBUG_MSG("DCDC1: %s\n", axp.isDCDC1Enable() ? "ENABLE" : "DISABLE");
|
||||
DEBUG_MSG("DCDC2: %s\n", axp.isDCDC2Enable() ? "ENABLE" : "DISABLE");
|
||||
DEBUG_MSG("LDO2: %s\n", axp.isLDO2Enable() ? "ENABLE" : "DISABLE");
|
||||
DEBUG_MSG("LDO3: %s\n", axp.isLDO3Enable() ? "ENABLE" : "DISABLE");
|
||||
DEBUG_MSG("DCDC3: %s\n", axp.isDCDC3Enable() ? "ENABLE" : "DISABLE");
|
||||
DEBUG_MSG("Exten: %s\n", axp.isExtenEnable() ? "ENABLE" : "DISABLE");
|
||||
|
||||
axp.setChargeControlCur(AXP1XX_CHARGE_CUR_1320MA); // actual limit (in HW) on the tbeam is 450mA
|
||||
#if 0
|
||||
|
||||
// Not connected
|
||||
//val = 0xfc;
|
||||
//axp._writeByte(AXP202_VHTF_CHGSET, 1, &val); // Set temperature protection
|
||||
|
||||
//not used
|
||||
//val = 0x46;
|
||||
//axp._writeByte(AXP202_OFF_CTL, 1, &val); // enable bat detection
|
||||
#endif
|
||||
axp.debugCharging();
|
||||
|
||||
#ifdef PMU_IRQ
|
||||
pinMode(PMU_IRQ, INPUT);
|
||||
attachInterrupt(
|
||||
PMU_IRQ, [] { pmu_irq = true; }, FALLING);
|
||||
|
||||
axp.adc1Enable(AXP202_BATT_CUR_ADC1, 1);
|
||||
axp.enableIRQ(AXP202_BATT_REMOVED_IRQ | AXP202_BATT_CONNECT_IRQ | AXP202_CHARGING_FINISHED_IRQ | AXP202_CHARGING_IRQ |
|
||||
AXP202_VBUS_REMOVED_IRQ | AXP202_VBUS_CONNECT_IRQ | AXP202_PEK_SHORTPRESS_IRQ,
|
||||
1);
|
||||
|
||||
axp.clearIRQ();
|
||||
#endif
|
||||
readPowerStatus();
|
||||
} else {
|
||||
DEBUG_MSG("AXP192 Begin FAIL\n");
|
||||
}
|
||||
} else {
|
||||
DEBUG_MSG("AXP192 not found\n");
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
void Power::loop()
|
||||
{
|
||||
|
||||
#ifdef PMU_IRQ
|
||||
if (pmu_irq) {
|
||||
pmu_irq = false;
|
||||
axp.readIRQ();
|
||||
|
||||
DEBUG_MSG("pmu irq!\n");
|
||||
|
||||
if (axp.isChargingIRQ()) {
|
||||
DEBUG_MSG("Battery start charging\n");
|
||||
}
|
||||
if (axp.isChargingDoneIRQ()) {
|
||||
DEBUG_MSG("Battery fully charged\n");
|
||||
}
|
||||
if (axp.isVbusRemoveIRQ()) {
|
||||
DEBUG_MSG("USB unplugged\n");
|
||||
}
|
||||
if (axp.isVbusPlugInIRQ()) {
|
||||
DEBUG_MSG("USB plugged In\n");
|
||||
}
|
||||
if (axp.isBattPlugInIRQ()) {
|
||||
DEBUG_MSG("Battery inserted\n");
|
||||
}
|
||||
if (axp.isBattRemoveIRQ()) {
|
||||
DEBUG_MSG("Battery removed\n");
|
||||
}
|
||||
if (axp.isPEKShortPressIRQ()) {
|
||||
DEBUG_MSG("PEK short button press\n");
|
||||
}
|
||||
|
||||
readPowerStatus();
|
||||
axp.clearIRQ();
|
||||
}
|
||||
|
||||
#endif // T_BEAM_V10
|
||||
|
||||
}
|
||||
@@ -26,46 +26,49 @@ static void sdsEnter()
|
||||
|
||||
#include "error.h"
|
||||
|
||||
static uint32_t secsSlept;
|
||||
|
||||
static void lsEnter()
|
||||
{
|
||||
DEBUG_MSG("lsEnter begin, ls_secs=%u\n", radioConfig.preferences.ls_secs);
|
||||
screen.setOn(false);
|
||||
secsSlept = 0; // How long have we been sleeping this time
|
||||
|
||||
DEBUG_MSG("lsEnter end\n");
|
||||
}
|
||||
|
||||
static void lsIdle()
|
||||
{
|
||||
DEBUG_MSG("lsIdle begin ls_secs=%u\n", radioConfig.preferences.ls_secs);
|
||||
// DEBUG_MSG("lsIdle begin ls_secs=%u\n", radioConfig.preferences.ls_secs);
|
||||
|
||||
#ifndef NO_ESP32
|
||||
uint32_t secsSlept = 0;
|
||||
esp_sleep_source_t wakeCause = ESP_SLEEP_WAKEUP_UNDEFINED;
|
||||
bool reached_ls_secs = false;
|
||||
|
||||
while (!reached_ls_secs) {
|
||||
// Do we have more sleeping to do?
|
||||
if (secsSlept < radioConfig.preferences.ls_secs) {
|
||||
// Briefly come out of sleep long enough to blink the led once every few seconds
|
||||
uint32_t sleepTime = 5;
|
||||
uint32_t sleepTime = 30;
|
||||
|
||||
// If some other service would stall sleep, don't let sleep happen yet
|
||||
if (doPreflightSleep()) {
|
||||
setLed(false); // Never leave led on while in light sleep
|
||||
wakeCause = doLightSleep(sleepTime * 1000LL);
|
||||
if (wakeCause != ESP_SLEEP_WAKEUP_TIMER)
|
||||
break;
|
||||
|
||||
if (wakeCause == ESP_SLEEP_WAKEUP_TIMER) {
|
||||
// Normal case: timer expired, we should just go back to sleep ASAP
|
||||
|
||||
setLed(true); // briefly turn on led
|
||||
doLightSleep(1);
|
||||
if (wakeCause != ESP_SLEEP_WAKEUP_TIMER)
|
||||
break;
|
||||
wakeCause = doLightSleep(1); // leave led on for 1ms
|
||||
|
||||
secsSlept += sleepTime;
|
||||
reached_ls_secs = secsSlept >= radioConfig.preferences.ls_secs;
|
||||
// DEBUG_MSG("sleeping, flash led!\n");
|
||||
}
|
||||
setLed(false);
|
||||
|
||||
if (reached_ls_secs) {
|
||||
// stay in LS mode but let loop check whatever it wants
|
||||
DEBUG_MSG("reached ls_secs, servicing loop()\n");
|
||||
if (wakeCause == ESP_SLEEP_WAKEUP_UART) {
|
||||
// Not currently used (because uart triggers in hw have problems)
|
||||
powerFSM.trigger(EVENT_SERIAL_CONNECTED);
|
||||
} else {
|
||||
// We woke for some other reason (button press, uart, device interrupt)
|
||||
// uint64_t status = esp_sleep_get_ext1_wakeup_status();
|
||||
DEBUG_MSG("wakeCause %d\n", wakeCause);
|
||||
|
||||
#ifdef BUTTON_PIN
|
||||
@@ -81,13 +84,23 @@ static void lsIdle()
|
||||
powerFSM.trigger(EVENT_WAKE_TIMER);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Someone says we can't sleep now, so just save some power by sleeping the CPU for 100ms or so
|
||||
delay(100);
|
||||
}
|
||||
} else {
|
||||
// Time to stop sleeping!
|
||||
setLed(false);
|
||||
DEBUG_MSG("reached ls_secs, servicing loop()\n");
|
||||
powerFSM.trigger(EVENT_WAKE_TIMER);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
static void lsExit()
|
||||
{
|
||||
// setGPSPower(true); // restore GPS power
|
||||
gps.startLock();
|
||||
gps->startLock();
|
||||
}
|
||||
|
||||
static void nbEnter()
|
||||
@@ -104,6 +117,12 @@ static void darkEnter()
|
||||
screen.setOn(false);
|
||||
}
|
||||
|
||||
static void serialEnter()
|
||||
{
|
||||
setBluetoothEnable(false);
|
||||
screen.setOn(true);
|
||||
}
|
||||
|
||||
static void onEnter()
|
||||
{
|
||||
screen.setOn(true);
|
||||
@@ -113,8 +132,9 @@ static void onEnter()
|
||||
|
||||
uint32_t now = millis();
|
||||
|
||||
if (now - lastPingMs > 60 * 1000) { // if more than a minute since our last press, ask other nodes to update their state
|
||||
service.sendNetworkPing(NODENUM_BROADCAST, true);
|
||||
if (now - lastPingMs > 30 * 1000) { // if more than a minute since our last press, ask other nodes to update their state
|
||||
if (displayedNodeNum)
|
||||
service.sendNetworkPing(displayedNodeNum, true); // Refresh the currently displayed node
|
||||
lastPingMs = now;
|
||||
}
|
||||
}
|
||||
@@ -132,6 +152,7 @@ State stateSDS(sdsEnter, NULL, NULL, "SDS");
|
||||
State stateLS(lsEnter, lsIdle, lsExit, "LS");
|
||||
State stateNB(nbEnter, NULL, NULL, "NB");
|
||||
State stateDARK(darkEnter, NULL, NULL, "DARK");
|
||||
State stateSERIAL(serialEnter, NULL, NULL, "SERIAL");
|
||||
State stateBOOT(bootEnter, NULL, NULL, "BOOT");
|
||||
State stateON(onEnter, NULL, NULL, "ON");
|
||||
Fsm powerFSM(&stateBOOT);
|
||||
@@ -147,12 +168,20 @@ void PowerFSM_setup()
|
||||
|
||||
powerFSM.add_transition(&stateNB, &stateNB, EVENT_RECEIVED_PACKET, NULL, "Received packet, resetting win wake");
|
||||
|
||||
// Handle press events
|
||||
// Handle press events - note: we ignore button presses when in API mode
|
||||
powerFSM.add_transition(&stateLS, &stateON, EVENT_PRESS, NULL, "Press");
|
||||
powerFSM.add_transition(&stateNB, &stateON, EVENT_PRESS, NULL, "Press");
|
||||
powerFSM.add_transition(&stateDARK, &stateON, EVENT_PRESS, NULL, "Press");
|
||||
powerFSM.add_transition(&stateON, &stateON, EVENT_PRESS, screenPress, "Press"); // reenter On to restart our timers
|
||||
|
||||
// Handle critically low power battery by forcing deep sleep
|
||||
powerFSM.add_transition(&stateBOOT, &stateSDS, EVENT_LOW_BATTERY, NULL, "LowBat");
|
||||
powerFSM.add_transition(&stateLS, &stateSDS, EVENT_LOW_BATTERY, NULL, "LowBat");
|
||||
powerFSM.add_transition(&stateNB, &stateSDS, EVENT_LOW_BATTERY, NULL, "LowBat");
|
||||
powerFSM.add_transition(&stateDARK, &stateSDS, EVENT_LOW_BATTERY, NULL, "LowBat");
|
||||
powerFSM.add_transition(&stateON, &stateSDS, EVENT_LOW_BATTERY, NULL, "LowBat");
|
||||
powerFSM.add_transition(&stateSERIAL, &stateSDS, EVENT_LOW_BATTERY, NULL, "LowBat");
|
||||
|
||||
powerFSM.add_transition(&stateDARK, &stateON, EVENT_BLUETOOTH_PAIR, NULL, "Bluetooth pairing");
|
||||
powerFSM.add_transition(&stateON, &stateON, EVENT_BLUETOOTH_PAIR, NULL, "Bluetooth pairing");
|
||||
|
||||
@@ -165,6 +194,13 @@ void PowerFSM_setup()
|
||||
powerFSM.add_transition(&stateDARK, &stateON, EVENT_RECEIVED_TEXT_MSG, NULL, "Received text");
|
||||
powerFSM.add_transition(&stateON, &stateON, EVENT_RECEIVED_TEXT_MSG, NULL, "Received text"); // restarts the sleep timer
|
||||
|
||||
powerFSM.add_transition(&stateLS, &stateSERIAL, EVENT_SERIAL_CONNECTED, NULL, "serial API");
|
||||
powerFSM.add_transition(&stateNB, &stateSERIAL, EVENT_SERIAL_CONNECTED, NULL, "serial API");
|
||||
powerFSM.add_transition(&stateDARK, &stateSERIAL, EVENT_SERIAL_CONNECTED, NULL, "serial API");
|
||||
powerFSM.add_transition(&stateON, &stateSERIAL, EVENT_SERIAL_CONNECTED, NULL, "serial API");
|
||||
|
||||
powerFSM.add_transition(&stateSERIAL, &stateNB, EVENT_SERIAL_DISCONNECTED, NULL, "serial disconnect");
|
||||
|
||||
powerFSM.add_transition(&stateDARK, &stateDARK, EVENT_CONTACT_FROM_PHONE, NULL, "Contact from phone");
|
||||
|
||||
powerFSM.add_transition(&stateNB, &stateDARK, EVENT_PACKET_FOR_PHONE, NULL, "Packet for phone");
|
||||
@@ -173,10 +209,13 @@ void PowerFSM_setup()
|
||||
|
||||
powerFSM.add_timed_transition(&stateDARK, &stateNB, radioConfig.preferences.phone_timeout_secs * 1000, NULL, "Phone timeout");
|
||||
|
||||
#ifndef NRF52_SERIES
|
||||
// We never enter light-sleep state on NRF52 (because the CPU uses so little power normally)
|
||||
powerFSM.add_timed_transition(&stateNB, &stateLS, radioConfig.preferences.min_wake_secs * 1000, NULL, "Min wake timeout");
|
||||
|
||||
powerFSM.add_timed_transition(&stateDARK, &stateLS, radioConfig.preferences.wait_bluetooth_secs * 1000, NULL,
|
||||
"Bluetooth timeout");
|
||||
#endif
|
||||
|
||||
powerFSM.add_timed_transition(&stateLS, &stateSDS, radioConfig.preferences.mesh_sds_timeout_secs * 1000, NULL,
|
||||
"mesh timeout");
|
||||
|
||||
@@ -13,6 +13,9 @@
|
||||
#define EVENT_BLUETOOTH_PAIR 7
|
||||
#define EVENT_NODEDB_UPDATED 8 // NodeDB has a big enough change that we think you should turn on the screen
|
||||
#define EVENT_CONTACT_FROM_PHONE 9 // the phone just talked to us over bluetooth
|
||||
#define EVENT_LOW_BATTERY 10 // Battery is critically low, go to sleep
|
||||
#define EVENT_SERIAL_CONNECTED 11
|
||||
#define EVENT_SERIAL_DISCONNECTED 12
|
||||
|
||||
extern Fsm powerFSM;
|
||||
|
||||
|
||||
103
src/PowerStatus.h
Normal file
103
src/PowerStatus.h
Normal file
@@ -0,0 +1,103 @@
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
#include "Status.h"
|
||||
#include "configuration.h"
|
||||
|
||||
namespace meshtastic {
|
||||
|
||||
/// Describes the state of the GPS system.
|
||||
class PowerStatus : public Status
|
||||
{
|
||||
|
||||
private:
|
||||
CallbackObserver<PowerStatus, const PowerStatus *> statusObserver = CallbackObserver<PowerStatus, const PowerStatus *>(this, &PowerStatus::updateStatus);
|
||||
|
||||
/// Whether we have a battery connected
|
||||
bool hasBattery;
|
||||
/// Battery voltage in mV, valid if haveBattery is true
|
||||
int batteryVoltageMv;
|
||||
/// Battery charge percentage, either read directly or estimated
|
||||
uint8_t batteryChargePercent;
|
||||
/// Whether USB is connected
|
||||
bool hasUSB;
|
||||
/// Whether we are charging the battery
|
||||
bool isCharging;
|
||||
|
||||
public:
|
||||
|
||||
PowerStatus() {
|
||||
statusType = STATUS_TYPE_POWER;
|
||||
}
|
||||
PowerStatus( bool hasBattery, bool hasUSB, bool isCharging, int batteryVoltageMv, uint8_t batteryChargePercent ) : Status()
|
||||
{
|
||||
this->hasBattery = hasBattery;
|
||||
this->hasUSB = hasUSB;
|
||||
this->isCharging = isCharging;
|
||||
this->batteryVoltageMv = batteryVoltageMv;
|
||||
this->batteryChargePercent = batteryChargePercent;
|
||||
}
|
||||
PowerStatus(const PowerStatus &);
|
||||
PowerStatus &operator=(const PowerStatus &);
|
||||
|
||||
void observe(Observable<const PowerStatus *> *source)
|
||||
{
|
||||
statusObserver.observe(source);
|
||||
}
|
||||
|
||||
bool getHasBattery() const
|
||||
{
|
||||
return hasBattery;
|
||||
}
|
||||
|
||||
bool getHasUSB() const
|
||||
{
|
||||
return hasUSB;
|
||||
}
|
||||
|
||||
bool getIsCharging() const
|
||||
{
|
||||
return isCharging;
|
||||
}
|
||||
|
||||
int getBatteryVoltageMv() const
|
||||
{
|
||||
return batteryVoltageMv;
|
||||
}
|
||||
|
||||
uint8_t getBatteryChargePercent() const
|
||||
{
|
||||
return batteryChargePercent;
|
||||
}
|
||||
|
||||
bool matches(const PowerStatus *newStatus) const
|
||||
{
|
||||
return (
|
||||
newStatus->getHasBattery() != hasBattery ||
|
||||
newStatus->getHasUSB() != hasUSB ||
|
||||
newStatus->getBatteryVoltageMv() != batteryVoltageMv
|
||||
);
|
||||
}
|
||||
int updateStatus(const PowerStatus *newStatus) {
|
||||
// Only update the status if values have actually changed
|
||||
bool isDirty;
|
||||
{
|
||||
isDirty = matches(newStatus);
|
||||
initialized = true;
|
||||
hasBattery = newStatus->getHasBattery();
|
||||
batteryVoltageMv = newStatus->getBatteryVoltageMv();
|
||||
batteryChargePercent = newStatus->getBatteryChargePercent();
|
||||
hasUSB = newStatus->getHasUSB();
|
||||
isCharging = newStatus->getIsCharging();
|
||||
}
|
||||
if(isDirty) {
|
||||
DEBUG_MSG("Battery %dmV %d%%\n", batteryVoltageMv, batteryChargePercent);
|
||||
onNewStatus.notifyObservers(this);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
extern meshtastic::PowerStatus *powerStatus;
|
||||
13
src/RedirectablePrint.cpp
Normal file
13
src/RedirectablePrint.cpp
Normal file
@@ -0,0 +1,13 @@
|
||||
#include "RedirectablePrint.h"
|
||||
#include <assert.h>
|
||||
|
||||
/**
|
||||
* A printer that doesn't go anywhere
|
||||
*/
|
||||
NoopPrint noopPrint;
|
||||
|
||||
void RedirectablePrint::setDestination(Print *_dest)
|
||||
{
|
||||
assert(_dest);
|
||||
dest = _dest;
|
||||
}
|
||||
34
src/RedirectablePrint.h
Normal file
34
src/RedirectablePrint.h
Normal file
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
|
||||
#include <Print.h>
|
||||
|
||||
/**
|
||||
* A Printable that can be switched to squirt its bytes to a different sink.
|
||||
* This class is mostly useful to allow debug printing to be redirected away from Serial
|
||||
* to some other transport if we switch Serial usage (on the fly) to some other purpose.
|
||||
*/
|
||||
class RedirectablePrint : public Print
|
||||
{
|
||||
Print *dest;
|
||||
|
||||
public:
|
||||
RedirectablePrint(Print *_dest) : dest(_dest) {}
|
||||
|
||||
/**
|
||||
* Set a new destination
|
||||
*/
|
||||
void setDestination(Print *dest);
|
||||
|
||||
virtual size_t write(uint8_t c) { return dest->write(c); }
|
||||
};
|
||||
|
||||
class NoopPrint : public Print
|
||||
{
|
||||
public:
|
||||
virtual size_t write(uint8_t c) { return 1; }
|
||||
};
|
||||
|
||||
/**
|
||||
* A printer that doesn't go anywhere
|
||||
*/
|
||||
extern NoopPrint noopPrint;
|
||||
45
src/SerialConsole.cpp
Normal file
45
src/SerialConsole.cpp
Normal file
@@ -0,0 +1,45 @@
|
||||
#include "SerialConsole.h"
|
||||
#include "PowerFSM.h"
|
||||
#include "configuration.h"
|
||||
#include <Arduino.h>
|
||||
|
||||
#define Port Serial
|
||||
|
||||
SerialConsole console;
|
||||
|
||||
SerialConsole::SerialConsole() : StreamAPI(&Port), RedirectablePrint(&Port)
|
||||
{
|
||||
canWrite = false; // We don't send packets to our port until it has talked to us first
|
||||
// setDestination(&noopPrint); for testing, try turning off 'all' debug output and see what leaks
|
||||
}
|
||||
|
||||
/// Do late init that can't happen at constructor time
|
||||
void SerialConsole::init()
|
||||
{
|
||||
Port.begin(SERIAL_BAUD);
|
||||
StreamAPI::init();
|
||||
emitRebooted();
|
||||
}
|
||||
|
||||
/**
|
||||
* we override this to notice when we've received a protobuf over the serial
|
||||
* stream. Then we shunt off debug serial output.
|
||||
*/
|
||||
void SerialConsole::handleToRadio(const uint8_t *buf, size_t len)
|
||||
{
|
||||
// Turn off debug serial printing once the API is activated, because other threads could print and corrupt packets
|
||||
setDestination(&noopPrint);
|
||||
canWrite = true;
|
||||
|
||||
StreamAPI::handleToRadio(buf, len);
|
||||
}
|
||||
|
||||
/// Hookable to find out when connection changes
|
||||
void SerialConsole::onConnectionChanged(bool connected)
|
||||
{
|
||||
if (connected) { // To prevent user confusion, turn off bluetooth while using the serial port api
|
||||
powerFSM.trigger(EVENT_SERIAL_CONNECTED);
|
||||
} else {
|
||||
powerFSM.trigger(EVENT_SERIAL_DISCONNECTED);
|
||||
}
|
||||
}
|
||||
35
src/SerialConsole.h
Normal file
35
src/SerialConsole.h
Normal file
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include "RedirectablePrint.h"
|
||||
#include "StreamAPI.h"
|
||||
/**
|
||||
* Provides both debug printing and, if the client starts sending protobufs to us, switches to send/receive protobufs
|
||||
* (and starts dropping debug printing - FIXME, eventually those prints should be encapsulated in protobufs).
|
||||
*/
|
||||
class SerialConsole : public StreamAPI, public RedirectablePrint
|
||||
{
|
||||
public:
|
||||
SerialConsole();
|
||||
|
||||
/// Do late init that can't happen at constructor time
|
||||
virtual void init();
|
||||
|
||||
/**
|
||||
* we override this to notice when we've received a protobuf over the serial stream. Then we shunt off
|
||||
* debug serial output.
|
||||
*/
|
||||
virtual void handleToRadio(const uint8_t *buf, size_t len);
|
||||
|
||||
virtual size_t write(uint8_t c)
|
||||
{
|
||||
if (c == '\n') // prefix any newlines with carriage return
|
||||
RedirectablePrint::write('\r');
|
||||
return RedirectablePrint::write(c);
|
||||
}
|
||||
|
||||
protected:
|
||||
/// Hookable to find out when connection changes
|
||||
virtual void onConnectionChanged(bool connected);
|
||||
};
|
||||
|
||||
extern SerialConsole console;
|
||||
72
src/Status.h
Normal file
72
src/Status.h
Normal file
@@ -0,0 +1,72 @@
|
||||
#pragma once
|
||||
|
||||
#include "Observer.h"
|
||||
|
||||
// Constants for the various status types, so we can tell subclass instances apart
|
||||
#define STATUS_TYPE_BASE 0
|
||||
#define STATUS_TYPE_POWER 1
|
||||
#define STATUS_TYPE_GPS 2
|
||||
#define STATUS_TYPE_NODE 3
|
||||
|
||||
|
||||
namespace meshtastic
|
||||
{
|
||||
|
||||
// A base class for observable status
|
||||
class Status
|
||||
{
|
||||
protected:
|
||||
// Allows us to observe an Observable
|
||||
CallbackObserver<Status, const Status *> statusObserver = CallbackObserver<Status, const Status *>(this, &Status::updateStatus);
|
||||
bool initialized = false;
|
||||
// Workaround for no typeid support
|
||||
int statusType;
|
||||
|
||||
public:
|
||||
// Allows us to generate observable events
|
||||
Observable<const Status *> onNewStatus;
|
||||
|
||||
// Enable polymorphism ?
|
||||
virtual ~Status() = default;
|
||||
|
||||
Status() {
|
||||
if (!statusType)
|
||||
{
|
||||
statusType = STATUS_TYPE_BASE;
|
||||
}
|
||||
}
|
||||
|
||||
// Prevent object copy/move
|
||||
Status(const Status &) = delete;
|
||||
Status &operator=(const Status &) = delete;
|
||||
|
||||
// Start observing a source of data
|
||||
void observe(Observable<const Status *> *source)
|
||||
{
|
||||
statusObserver.observe(source);
|
||||
}
|
||||
|
||||
// Determines whether or not existing data matches the data in another Status instance
|
||||
bool matches(const Status *otherStatus) const
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
bool isInitialized() const
|
||||
{
|
||||
return initialized;
|
||||
}
|
||||
|
||||
int getStatusType() const
|
||||
{
|
||||
return statusType;
|
||||
}
|
||||
|
||||
// Called when the Observable we're observing generates a new notification
|
||||
int updateStatus(const Status *newStatus)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
};
|
||||
};
|
||||
0
src/StatusHandler.h
Normal file
0
src/StatusHandler.h
Normal file
58
src/WorkerThread.cpp
Normal file
58
src/WorkerThread.cpp
Normal file
@@ -0,0 +1,58 @@
|
||||
#include "WorkerThread.h"
|
||||
#include "debug.h"
|
||||
#include <assert.h>
|
||||
|
||||
#ifdef configUSE_PREEMPTION
|
||||
|
||||
void Thread::start(const char *name, size_t stackSize, uint32_t priority)
|
||||
{
|
||||
auto r = xTaskCreate(callRun, name, stackSize, this, priority, &taskHandle);
|
||||
assert(r == pdPASS);
|
||||
}
|
||||
|
||||
void Thread::callRun(void *_this)
|
||||
{
|
||||
((Thread *)_this)->doRun();
|
||||
}
|
||||
|
||||
void WorkerThread::doRun()
|
||||
{
|
||||
startWatchdog();
|
||||
|
||||
while (!wantExit) {
|
||||
stopWatchdog();
|
||||
block();
|
||||
startWatchdog();
|
||||
|
||||
// no need - startWatchdog is guaranteed to give us one full watchdog interval
|
||||
// serviceWatchdog(); // Let our loop worker have one full watchdog interval (at least) to run
|
||||
|
||||
#ifdef DEBUG_STACK
|
||||
static uint32_t lastPrint = 0;
|
||||
if (millis() - lastPrint > 10 * 1000L) {
|
||||
lastPrint = millis();
|
||||
meshtastic::printThreadInfo("net");
|
||||
}
|
||||
#endif
|
||||
|
||||
loop();
|
||||
}
|
||||
|
||||
stopWatchdog();
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify this thread so it can run
|
||||
*/
|
||||
void NotifiedWorkerThread::notify(uint32_t v, eNotifyAction action)
|
||||
{
|
||||
xTaskNotify(taskHandle, v, action);
|
||||
}
|
||||
|
||||
void NotifiedWorkerThread::block()
|
||||
{
|
||||
xTaskNotifyWait(0, // don't clear notification on entry
|
||||
clearOnRead, ¬ification, portMAX_DELAY); // Wait forever
|
||||
}
|
||||
|
||||
#endif
|
||||
114
src/WorkerThread.h
Normal file
114
src/WorkerThread.h
Normal file
@@ -0,0 +1,114 @@
|
||||
#include "esp_task_wdt.h"
|
||||
#include "freertosinc.h"
|
||||
#include <Arduino.h>
|
||||
|
||||
#ifdef HAS_FREE_RTOS
|
||||
|
||||
class Thread
|
||||
{
|
||||
protected:
|
||||
TaskHandle_t taskHandle = NULL;
|
||||
|
||||
/**
|
||||
* set this to true to ask thread to cleanly exit asap
|
||||
*/
|
||||
volatile bool wantExit = false;
|
||||
|
||||
public:
|
||||
void start(const char *name, size_t stackSize = 1024, uint32_t priority = tskIDLE_PRIORITY);
|
||||
|
||||
virtual ~Thread() { vTaskDelete(taskHandle); }
|
||||
|
||||
uint32_t getStackHighwaterMark() { return uxTaskGetStackHighWaterMark(taskHandle); }
|
||||
|
||||
protected:
|
||||
/**
|
||||
* The method that will be called when start is called.
|
||||
*/
|
||||
virtual void doRun() = 0;
|
||||
|
||||
/**
|
||||
* All thread run methods must periodically call serviceWatchdog, or the system will declare them hung and panic.
|
||||
*
|
||||
* this only applies after startWatchdog() has been called. If you need to sleep for a long time call stopWatchdog()
|
||||
*/
|
||||
void serviceWatchdog() { esp_task_wdt_reset(); }
|
||||
void startWatchdog()
|
||||
{
|
||||
auto r = esp_task_wdt_add(taskHandle);
|
||||
assert(r == ESP_OK);
|
||||
}
|
||||
void stopWatchdog()
|
||||
{
|
||||
auto r = esp_task_wdt_delete(taskHandle);
|
||||
assert(r == ESP_OK);
|
||||
}
|
||||
|
||||
private:
|
||||
static void callRun(void *_this);
|
||||
};
|
||||
|
||||
/**
|
||||
* This wraps threading (FreeRTOS for now) with a blocking API intended for efficiently converting onlyschool arduino loop() code.
|
||||
*
|
||||
* Use as a mixin base class for the classes you want to convert.
|
||||
*
|
||||
* https://www.freertos.org/RTOS_Task_Notification_As_Mailbox.html
|
||||
*/
|
||||
class WorkerThread : public Thread
|
||||
{
|
||||
protected:
|
||||
/**
|
||||
* A method that should block execution - either waiting ona queue/mutex or a "task notification"
|
||||
*/
|
||||
virtual void block() = 0;
|
||||
|
||||
virtual void loop() = 0;
|
||||
|
||||
/**
|
||||
* The method that will be called when start is called.
|
||||
*/
|
||||
virtual void doRun();
|
||||
};
|
||||
|
||||
/**
|
||||
* A worker thread that waits on a freertos notification
|
||||
*/
|
||||
class NotifiedWorkerThread : public WorkerThread
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* Notify this thread so it can run
|
||||
*/
|
||||
void notify(uint32_t v = 0, eNotifyAction action = eNoAction);
|
||||
|
||||
/**
|
||||
* Notify from an ISR
|
||||
*
|
||||
* This must be inline or IRAM_ATTR on ESP32
|
||||
*/
|
||||
inline void notifyFromISR(BaseType_t *highPriWoken, uint32_t v = 0, eNotifyAction action = eNoAction)
|
||||
{
|
||||
xTaskNotifyFromISR(taskHandle, v, action, highPriWoken);
|
||||
}
|
||||
|
||||
protected:
|
||||
/**
|
||||
* The notification that was most recently used to wake the thread. Read from loop()
|
||||
*/
|
||||
uint32_t notification = 0;
|
||||
|
||||
/**
|
||||
* What notification bits should be cleared just after we read and return them in notification?
|
||||
*
|
||||
* Defaults to clear all of them.
|
||||
*/
|
||||
uint32_t clearOnRead = UINT32_MAX;
|
||||
|
||||
/**
|
||||
* A method that should block execution - either waiting ona queue/mutex or a "task notification"
|
||||
*/
|
||||
virtual void block();
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -1,3 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
// FIXME - make a FS abstraction for NRF52
|
||||
@@ -1,6 +0,0 @@
|
||||
#include "target_specific.h"
|
||||
|
||||
void setBluetoothEnable(bool on)
|
||||
{
|
||||
// Do nothing
|
||||
}
|
||||
@@ -31,8 +31,9 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
// If app version is not specified we assume we are not being invoked by the build script
|
||||
#ifndef APP_VERSION
|
||||
#define APP_VERSION 0.0.0 // this def normally comes from build-all.sh
|
||||
#define HW_VERSION 1.0 - US // normally comes from build-all.sh and contains the region code
|
||||
#error APP_VERSION, HW_VERSION, and HW_VERSION_countryname must be set by the build environment
|
||||
//#define APP_VERSION 0.0.0 // this def normally comes from build-all.sh
|
||||
//#define HW_VERSION 1.0 - US // normally comes from build-all.sh and contains the region code
|
||||
#endif
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
@@ -45,45 +46,54 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
//#define USE_JTAG
|
||||
#endif
|
||||
|
||||
#define DEBUG_PORT Serial // Serial debug port
|
||||
#define SERIAL_BAUD 115200 // Serial debug baud rate
|
||||
|
||||
#define REQUIRE_RADIO true // If true, we will fail to start if the radio is not found
|
||||
|
||||
/// Convert a preprocessor name into a quoted string
|
||||
#define xstr(s) str(s)
|
||||
#define str(s) #s
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// DEBUG
|
||||
// -----------------------------------------------------------------------------
|
||||
/// Convert a preprocessor name into a quoted string and if that string is empty use "unset"
|
||||
#define optstr(s) (xstr(s)[0] ? xstr(s) : "unset")
|
||||
|
||||
#ifdef NRF52840_XXAA // All of the NRF52 targets are configured using variant.h, so this section shouldn't need to be
|
||||
// board specific
|
||||
|
||||
//
|
||||
// Standard definitions for NRF52 targets
|
||||
//
|
||||
|
||||
#define NO_ESP32 // Don't use ESP32 libs (mainly bluetooth)
|
||||
|
||||
// We bind to the GPS using variant.h instead for this platform (Serial1)
|
||||
|
||||
// FIXME, not yet ready for NRF52
|
||||
#define RTC_DATA_ATTR
|
||||
|
||||
#define LED_PIN PIN_LED1 // LED1 on nrf52840-DK
|
||||
#define BUTTON_PIN PIN_BUTTON1
|
||||
|
||||
// FIXME, use variant.h defs for all of this!!! (even on the ESP32 targets)
|
||||
#elif defined(CubeCell_BoardPlus)
|
||||
|
||||
//
|
||||
// Standard definitions for CubeCell targets
|
||||
//
|
||||
|
||||
#define NO_ESP32 // Don't use ESP32 libs (mainly bluetooth)
|
||||
|
||||
// FIXME, not yet ready for NRF52
|
||||
#define RTC_DATA_ATTR
|
||||
|
||||
#define LED_PIN -1 // FIXME totally bogus
|
||||
#define BUTTON_PIN -1
|
||||
|
||||
#ifdef DEBUG_PORT
|
||||
#define DEBUG_MSG(...) DEBUG_PORT.printf(__VA_ARGS__)
|
||||
#else
|
||||
#define DEBUG_MSG(...)
|
||||
#endif
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// OLED
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
#define SSD1306_ADDRESS 0x3C
|
||||
|
||||
// Flip the screen upside down by default as it makes more sense on T-BEAM
|
||||
// devices. Comment this out to not rotate screen 180 degrees.
|
||||
#define FLIP_SCREEN_VERTICALLY
|
||||
|
||||
// DEBUG LED
|
||||
|
||||
#define LED_INVERTED 0 // define as 1 if LED is active low (on)
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// GPS
|
||||
// -----------------------------------------------------------------------------
|
||||
//
|
||||
// Standard definitions for ESP32 targets
|
||||
//
|
||||
|
||||
#define GPS_SERIAL_NUM 1
|
||||
#define GPS_BAUDRATE 9600
|
||||
|
||||
#define GPS_RX_PIN 34
|
||||
#ifdef USE_JTAG
|
||||
#define GPS_TX_PIN -1
|
||||
@@ -100,6 +110,31 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#define MOSI_GPIO 27
|
||||
#define NSS_GPIO 18
|
||||
|
||||
#endif
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// OLED
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
#define SSD1306_ADDRESS 0x3C
|
||||
|
||||
// The SH1106 controller is almost, but not quite, the same as SSD1306
|
||||
// Define this if you know you have that controller or your "SSD1306" misbehaves.
|
||||
//#define USE_SH1106
|
||||
|
||||
// Flip the screen upside down by default as it makes more sense on T-BEAM
|
||||
// devices. Comment this out to not rotate screen 180 degrees.
|
||||
#define FLIP_SCREEN_VERTICALLY
|
||||
|
||||
// DEBUG LED
|
||||
#define LED_INVERTED 0 // define as 1 if LED is active low (on)
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// GPS
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
#define GPS_BAUDRATE 9600
|
||||
|
||||
#if defined(TBEAM_V10)
|
||||
// This string must exactly match the case used in release file names or the android updater won't work
|
||||
#define HW_VENDOR "tbeam"
|
||||
@@ -109,7 +144,8 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#define I2C_SDA 21
|
||||
#define I2C_SCL 22
|
||||
|
||||
#define BUTTON_PIN 38
|
||||
#define BUTTON_PIN 38 // The middle button GPIO on the T-Beam
|
||||
#define BUTTON_PIN_ALT 13 // Alternate GPIO for an external button if needed
|
||||
|
||||
#ifndef USE_JTAG
|
||||
#define RESET_GPIO 14
|
||||
@@ -121,6 +157,8 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
// Leave undefined to disable our PMU IRQ handler
|
||||
#define PMU_IRQ 35
|
||||
|
||||
#define AXP192_SLAVE_ADDRESS 0x34
|
||||
|
||||
#elif defined(TBEAM_V07)
|
||||
// This string must exactly match the case used in release file names or the android updater won't work
|
||||
#define HW_VENDOR "tbeam0.7"
|
||||
@@ -149,6 +187,13 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
// This string must exactly match the case used in release file names or the android updater won't work
|
||||
#define HW_VENDOR "heltec"
|
||||
|
||||
// the default ESP32 Pin of 15 is the Oled SCL, set to 36 and 37 and works fine.
|
||||
// Tested on Neo6m module.
|
||||
#undef GPS_RX_PIN
|
||||
#undef GPS_TX_PIN
|
||||
#define GPS_RX_PIN 36
|
||||
#define GPS_TX_PIN 37
|
||||
|
||||
#ifndef USE_JTAG // gpio15 is TDO for JTAG, so no I2C on this board while doing jtag
|
||||
#define I2C_SDA 4 // I2C pins for this board
|
||||
#define I2C_SCL 15
|
||||
@@ -169,6 +214,10 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#elif defined(TTGO_LORA_V1)
|
||||
// This string must exactly match the case used in release file names or the android updater won't work
|
||||
#define HW_VENDOR "ttgo-lora32-v1"
|
||||
#undef GPS_RX_PIN
|
||||
#undef GPS_TX_PIN
|
||||
#define GPS_RX_PIN 36
|
||||
#define GPS_TX_PIN 37
|
||||
|
||||
#define I2C_SDA 4 // I2C pins for this board
|
||||
#define I2C_SCL 15
|
||||
@@ -187,6 +236,11 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
// This string must exactly match the case used in release file names or the android updater won't work
|
||||
#define HW_VENDOR "ttgo-lora32-v2"
|
||||
|
||||
#undef GPS_RX_PIN
|
||||
#undef GPS_TX_PIN
|
||||
#define GPS_RX_PIN 36
|
||||
#define GPS_TX_PIN 13 // per @eugene
|
||||
|
||||
#define I2C_SDA 21 // I2C pins for this board
|
||||
#define I2C_SCL 22
|
||||
|
||||
@@ -202,32 +256,62 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#define RF95_IRQ_GPIO 26 // IRQ line for the LORA radio
|
||||
#define DIO1_GPIO 35 // DIO1 & DIO2 are not currently used, but they must be assigned to a pin number
|
||||
#define DIO2_GPIO 34 // DIO1 & DIO2 are not currently used, but they must be assigned to a pin number
|
||||
#elif defined(BARE_BOARD)
|
||||
#endif
|
||||
|
||||
#ifdef ARDUINO_NRF52840_PCA10056
|
||||
|
||||
// This string must exactly match the case used in release file names or the android updater won't work
|
||||
#define HW_VENDOR "bare"
|
||||
|
||||
#define NO_ESP32 // Don't use ESP32 libs (mainly bluetooth)
|
||||
|
||||
// Turn off GPS code for now
|
||||
#undef GPS_RX_PIN
|
||||
#undef GPS_TX_PIN
|
||||
|
||||
// FIXME, not yet ready for NRF52
|
||||
#define RTC_DATA_ATTR
|
||||
|
||||
#define LED_PIN PIN_LED1 // LED1 on nrf52840-DK
|
||||
#define BUTTON_PIN PIN_BUTTON1
|
||||
#define HW_VENDOR "nrf52dk"
|
||||
|
||||
// This board uses 0 to be mean LED on
|
||||
#undef LED_INVERTED
|
||||
#define LED_INVERTED 1
|
||||
|
||||
// Uncomment to confirm if we can build the RF95 driver for NRF52
|
||||
#if 0
|
||||
#define RESET_GPIO 14 // If defined, this pin will be used to reset the LORA radio
|
||||
#define RF95_IRQ_GPIO 26 // IRQ line for the LORA radio
|
||||
#define DIO1_GPIO 35 // DIO1 & DIO2 are not currently used, but they must be assigned to a pin number
|
||||
#define DIO2_GPIO 34 // DIO1 & DIO2 are not currently used, but they must be assigned to a pin number
|
||||
#endif
|
||||
|
||||
#elif defined(ARDUINO_NRF52840_PPR)
|
||||
|
||||
#define HW_VENDOR "ppr"
|
||||
|
||||
#endif
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// DEBUG
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
#define SERIAL_BAUD 921600 // Serial debug baud rate
|
||||
|
||||
#include "SerialConsole.h"
|
||||
|
||||
#define DEBUG_PORT console // Serial debug port
|
||||
|
||||
// What platforms should use SEGGER?
|
||||
#ifdef NRF52_SERIES
|
||||
#define USE_SEGGER
|
||||
#else
|
||||
#define SERIAL0_RX_GPIO 3 // Always GPIO3 on ESP32
|
||||
#endif
|
||||
|
||||
#ifdef USE_SEGGER
|
||||
#include "SEGGER_RTT.h"
|
||||
#define DEBUG_MSG(...) SEGGER_RTT_printf(0, __VA_ARGS__)
|
||||
#else
|
||||
#ifdef DEBUG_PORT
|
||||
#define DEBUG_MSG(...) DEBUG_PORT.printf(__VA_ARGS__)
|
||||
#else
|
||||
#define DEBUG_MSG(...)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// AXP192 (Rev1-specific options)
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
// #define AXP192_SLAVE_ADDRESS 0x34 // Now defined in axp20x.h
|
||||
#define GPS_POWER_CTRL_CH 3
|
||||
#define LORA_POWER_CTRL_CH 2
|
||||
|
||||
1
src/cubecell/FS.h
Normal file
1
src/cubecell/FS.h
Normal file
@@ -0,0 +1 @@
|
||||
// Placeholder FIXME
|
||||
@@ -3,7 +3,7 @@
|
||||
#include <Arduino.h>
|
||||
|
||||
/// Error codes for critical error
|
||||
enum CriticalErrorCode { NoError, ErrTxWatchdog, ErrSleepEnterWait, ErrNoRadio };
|
||||
enum CriticalErrorCode { NoError, ErrTxWatchdog, ErrSleepEnterWait, ErrNoRadio, ErrUnspecified };
|
||||
|
||||
/// Record an error that should be reported via analytics
|
||||
void recordCriticalError(CriticalErrorCode code, uint32_t address = 0);
|
||||
|
||||
@@ -1,65 +1,82 @@
|
||||
#include "BluetoothUtil.h"
|
||||
#include "BluetoothSoftwareUpdate.h"
|
||||
#include "configuration.h"
|
||||
#include <esp_gatt_defs.h>
|
||||
#include <BLE2902.h>
|
||||
#include <Arduino.h>
|
||||
#include <Update.h>
|
||||
#include <CRC32.h>
|
||||
#include "BluetoothUtil.h"
|
||||
#include "CallbackCharacteristic.h"
|
||||
#include "RadioLibInterface.h"
|
||||
#include "configuration.h"
|
||||
#include "lock.h"
|
||||
#include <Arduino.h>
|
||||
#include <BLE2902.h>
|
||||
#include <CRC32.h>
|
||||
#include <Update.h>
|
||||
#include <esp_gatt_defs.h>
|
||||
|
||||
using namespace meshtastic;
|
||||
|
||||
CRC32 crc;
|
||||
uint32_t rebootAtMsec = 0; // If not zero we will reboot at this time (used to reboot shortly after the update completes)
|
||||
|
||||
uint32_t updateExpectedSize, updateActualSize;
|
||||
|
||||
Lock *updateLock;
|
||||
|
||||
class TotalSizeCharacteristic : public CallbackCharacteristic
|
||||
{
|
||||
public:
|
||||
TotalSizeCharacteristic()
|
||||
: CallbackCharacteristic("e74dd9c0-a301-4a6f-95a1-f0e1dbea8e1e", BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_READ)
|
||||
: CallbackCharacteristic("e74dd9c0-a301-4a6f-95a1-f0e1dbea8e1e",
|
||||
BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_READ)
|
||||
{
|
||||
}
|
||||
|
||||
void onWrite(BLECharacteristic *c)
|
||||
{
|
||||
BLEKeepAliveCallbacks::onWrite(c);
|
||||
|
||||
LockGuard g(updateLock);
|
||||
// Check if there is enough to OTA Update
|
||||
uint32_t len = getValue32(c, 0);
|
||||
updateExpectedSize = len;
|
||||
updateActualSize = 0;
|
||||
crc.reset();
|
||||
bool canBegin = Update.begin(len);
|
||||
DEBUG_MSG("Setting update size %u, result %d\n", len, canBegin);
|
||||
if (!canBegin)
|
||||
if (!canBegin) {
|
||||
// Indicate failure by forcing the size to 0
|
||||
c->setValue(0UL);
|
||||
else {
|
||||
uint32_t zero = 0;
|
||||
c->setValue(zero);
|
||||
} else {
|
||||
// This totally breaks abstraction to up up into the app layer for this, but quick hack to make sure we only
|
||||
// talk to one service during the sw update.
|
||||
// DEBUG_MSG("FIXME, crufty shutdown of mesh bluetooth for sw update.");
|
||||
// void stopMeshBluetoothService();
|
||||
// stopMeshBluetoothService();
|
||||
|
||||
if (RadioLibInterface::instance)
|
||||
RadioLibInterface::instance->sleep(); // FIXME, nasty hack - the RF95 ISR/SPI code on ESP32 can fail while we are
|
||||
// writing flash - shut the radio off during updates
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
#define MAX_BLOCKSIZE 512
|
||||
|
||||
class DataCharacteristic : public CallbackCharacteristic
|
||||
{
|
||||
public:
|
||||
DataCharacteristic()
|
||||
: CallbackCharacteristic(
|
||||
"e272ebac-d463-4b98-bc84-5cc1a39ee517", BLECharacteristic::PROPERTY_WRITE)
|
||||
{
|
||||
}
|
||||
DataCharacteristic() : CallbackCharacteristic("e272ebac-d463-4b98-bc84-5cc1a39ee517", BLECharacteristic::PROPERTY_WRITE) {}
|
||||
|
||||
void onWrite(BLECharacteristic *c)
|
||||
{
|
||||
BLEKeepAliveCallbacks::onWrite(c);
|
||||
|
||||
LockGuard g(updateLock);
|
||||
std::string value = c->getValue();
|
||||
uint32_t len = value.length();
|
||||
uint8_t *data = c->getData();
|
||||
assert(len <= MAX_BLOCKSIZE);
|
||||
static uint8_t
|
||||
data[MAX_BLOCKSIZE]; // we temporarily copy here because I'm worried that a fast sender might be able overwrite srcbuf
|
||||
memcpy(data, c->getData(), len);
|
||||
// DEBUG_MSG("Writing %u\n", len);
|
||||
crc.update(data, len);
|
||||
Update.write(data, len);
|
||||
updateActualSize += len;
|
||||
powerFSM.trigger(EVENT_RECEIVED_TEXT_MSG); // Not exactly correct, but we want to force the device to not sleep now
|
||||
}
|
||||
};
|
||||
|
||||
@@ -68,53 +85,50 @@ static BLECharacteristic *resultC;
|
||||
class CRC32Characteristic : public CallbackCharacteristic
|
||||
{
|
||||
public:
|
||||
CRC32Characteristic()
|
||||
: CallbackCharacteristic(
|
||||
"4826129c-c22a-43a3-b066-ce8f0d5bacc6", BLECharacteristic::PROPERTY_WRITE)
|
||||
{
|
||||
}
|
||||
CRC32Characteristic() : CallbackCharacteristic("4826129c-c22a-43a3-b066-ce8f0d5bacc6", BLECharacteristic::PROPERTY_WRITE) {}
|
||||
|
||||
void onWrite(BLECharacteristic *c)
|
||||
{
|
||||
BLEKeepAliveCallbacks::onWrite(c);
|
||||
|
||||
LockGuard g(updateLock);
|
||||
uint32_t expectedCRC = getValue32(c, 0);
|
||||
uint32_t actualCRC = crc.finalize();
|
||||
DEBUG_MSG("expected CRC %u\n", expectedCRC);
|
||||
|
||||
uint8_t result = 0xff;
|
||||
|
||||
// Check the CRC before asking the update to happen.
|
||||
if (crc.finalize() != expectedCRC)
|
||||
if (updateActualSize != updateExpectedSize) {
|
||||
DEBUG_MSG("Expected %u bytes, but received %u bytes!\n", updateExpectedSize, updateActualSize);
|
||||
result = 0xe1; // FIXME, use real error codes
|
||||
} else if (actualCRC != expectedCRC) // Check the CRC before asking the update to happen.
|
||||
{
|
||||
DEBUG_MSG("Invalid CRC!\n");
|
||||
DEBUG_MSG("Invalid CRC! expected=%u, actual=%u\n", expectedCRC, actualCRC);
|
||||
result = 0xe0; // FIXME, use real error codes
|
||||
}
|
||||
else
|
||||
{
|
||||
if (Update.end())
|
||||
{
|
||||
} else {
|
||||
if (Update.end()) {
|
||||
DEBUG_MSG("OTA done, rebooting in 5 seconds!\n");
|
||||
rebootAtMsec = millis() + 5000;
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
DEBUG_MSG("Error Occurred. Error #: %d\n", Update.getError());
|
||||
}
|
||||
result = Update.getError();
|
||||
}
|
||||
|
||||
if (RadioLibInterface::instance)
|
||||
RadioLibInterface::instance->startReceive(); // Resume radio
|
||||
|
||||
assert(resultC);
|
||||
resultC->setValue(&result, 1);
|
||||
resultC->notify();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
void bluetoothRebootCheck()
|
||||
{
|
||||
if (rebootAtMsec && millis() > rebootAtMsec)
|
||||
if (rebootAtMsec && millis() > rebootAtMsec) {
|
||||
DEBUG_MSG("Rebooting for update\n");
|
||||
ESP.restart();
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
See bluetooth-api.md
|
||||
@@ -122,11 +136,15 @@ See bluetooth-api.md
|
||||
*/
|
||||
BLEService *createUpdateService(BLEServer *server, std::string hwVendor, std::string swVersion, std::string hwVersion)
|
||||
{
|
||||
if (!updateLock)
|
||||
updateLock = new Lock();
|
||||
|
||||
// Create the BLE Service
|
||||
BLEService *service = server->createService(BLEUUID("cb0b9a0b-a84c-4c0d-bdbb-442e3144ee30"), 25, 0);
|
||||
|
||||
assert(!resultC);
|
||||
resultC = new BLECharacteristic("5e134862-7411-4424-ac4a-210937432c77", BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
|
||||
resultC = new BLECharacteristic("5e134862-7411-4424-ac4a-210937432c77",
|
||||
BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
|
||||
|
||||
addWithDesc(service, new TotalSizeCharacteristic, "total image size");
|
||||
addWithDesc(service, new DataCharacteristic, "data");
|
||||
@@ -135,7 +153,8 @@ BLEService *createUpdateService(BLEServer *server, std::string hwVendor, std::st
|
||||
|
||||
resultC->addDescriptor(addBLEDescriptor(new BLE2902())); // Needed so clients can request notification
|
||||
|
||||
BLECharacteristic *swC = new BLECharacteristic(BLEUUID((uint16_t)ESP_GATT_UUID_SW_VERSION_STR), BLECharacteristic::PROPERTY_READ);
|
||||
BLECharacteristic *swC =
|
||||
new BLECharacteristic(BLEUUID((uint16_t)ESP_GATT_UUID_SW_VERSION_STR), BLECharacteristic::PROPERTY_READ);
|
||||
swC->setValue(swVersion);
|
||||
service->addCharacteristic(addBLECharacteristic(swC));
|
||||
|
||||
@@ -143,7 +162,8 @@ BLEService *createUpdateService(BLEServer *server, std::string hwVendor, std::st
|
||||
mfC->setValue(hwVendor);
|
||||
service->addCharacteristic(addBLECharacteristic(mfC));
|
||||
|
||||
BLECharacteristic *hwvC = new BLECharacteristic(BLEUUID((uint16_t)ESP_GATT_UUID_HW_VERSION_STR), BLECharacteristic::PROPERTY_READ);
|
||||
BLECharacteristic *hwvC =
|
||||
new BLECharacteristic(BLEUUID((uint16_t)ESP_GATT_UUID_HW_VERSION_STR), BLECharacteristic::PROPERTY_READ);
|
||||
hwvC->setValue(hwVersion);
|
||||
service->addCharacteristic(addBLECharacteristic(hwvC));
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <BLEDevice.h>
|
||||
#include <BLEServer.h>
|
||||
#include <BLEUtils.h>
|
||||
|
||||
BLEService *createUpdateService(BLEServer *server, std::string hwVendor, std::string swVersion, std::string hwVersion);
|
||||
|
||||
323
src/esp32/BluetoothUtil.cpp
Normal file
323
src/esp32/BluetoothUtil.cpp
Normal file
@@ -0,0 +1,323 @@
|
||||
#include "BluetoothUtil.h"
|
||||
#include "BluetoothSoftwareUpdate.h"
|
||||
#include "configuration.h"
|
||||
#include <Arduino.h>
|
||||
#include <BLE2902.h>
|
||||
#include <Update.h>
|
||||
#include <esp_gatt_defs.h>
|
||||
|
||||
SimpleAllocator btPool;
|
||||
|
||||
bool _BLEClientConnected = false;
|
||||
|
||||
class MyServerCallbacks : public BLEServerCallbacks
|
||||
{
|
||||
void onConnect(BLEServer *pServer) { _BLEClientConnected = true; };
|
||||
|
||||
void onDisconnect(BLEServer *pServer) { _BLEClientConnected = false; }
|
||||
};
|
||||
|
||||
#define MAX_DESCRIPTORS 32
|
||||
#define MAX_CHARACTERISTICS 32
|
||||
|
||||
static BLECharacteristic *chars[MAX_CHARACTERISTICS];
|
||||
static size_t numChars;
|
||||
static BLEDescriptor *descs[MAX_DESCRIPTORS];
|
||||
static size_t numDescs;
|
||||
|
||||
/// Add a characteristic that we will delete when we restart
|
||||
BLECharacteristic *addBLECharacteristic(BLECharacteristic *c)
|
||||
{
|
||||
assert(numChars < MAX_CHARACTERISTICS);
|
||||
chars[numChars++] = c;
|
||||
return c;
|
||||
}
|
||||
|
||||
/// Add a characteristic that we will delete when we restart
|
||||
BLEDescriptor *addBLEDescriptor(BLEDescriptor *c)
|
||||
{
|
||||
assert(numDescs < MAX_DESCRIPTORS);
|
||||
descs[numDescs++] = c;
|
||||
|
||||
return c;
|
||||
}
|
||||
|
||||
// Help routine to add a description to any BLECharacteristic and add it to the service
|
||||
// We default to require an encrypted BOND for all these these characterstics
|
||||
void addWithDesc(BLEService *service, BLECharacteristic *c, const char *description)
|
||||
{
|
||||
c->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED);
|
||||
|
||||
BLEDescriptor *desc = new BLEDescriptor(BLEUUID((uint16_t)ESP_GATT_UUID_CHAR_DESCRIPTION), strlen(description) + 1);
|
||||
assert(desc);
|
||||
desc->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED);
|
||||
desc->setValue(description);
|
||||
c->addDescriptor(desc);
|
||||
service->addCharacteristic(c);
|
||||
addBLECharacteristic(c);
|
||||
addBLEDescriptor(desc);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create standard device info service
|
||||
**/
|
||||
BLEService *createDeviceInfomationService(BLEServer *server, std::string hwVendor, std::string swVersion,
|
||||
std::string hwVersion = "")
|
||||
{
|
||||
BLEService *deviceInfoService = server->createService(BLEUUID((uint16_t)ESP_GATT_UUID_DEVICE_INFO_SVC));
|
||||
|
||||
BLECharacteristic *swC =
|
||||
new BLECharacteristic(BLEUUID((uint16_t)ESP_GATT_UUID_SW_VERSION_STR), BLECharacteristic::PROPERTY_READ);
|
||||
BLECharacteristic *mfC = new BLECharacteristic(BLEUUID((uint16_t)ESP_GATT_UUID_MANU_NAME), BLECharacteristic::PROPERTY_READ);
|
||||
// BLECharacteristic SerialNumberCharacteristic(BLEUUID((uint16_t) ESP_GATT_UUID_SERIAL_NUMBER_STR),
|
||||
// BLECharacteristic::PROPERTY_READ);
|
||||
|
||||
/*
|
||||
* Mandatory characteristic for device info service?
|
||||
|
||||
BLECharacteristic *m_pnpCharacteristic = m_deviceInfoService->createCharacteristic(ESP_GATT_UUID_PNP_ID,
|
||||
BLECharacteristic::PROPERTY_READ);
|
||||
|
||||
uint8_t sig, uint16_t vid, uint16_t pid, uint16_t version;
|
||||
uint8_t pnp[] = { sig, (uint8_t) (vid >> 8), (uint8_t) vid, (uint8_t) (pid >> 8), (uint8_t) pid, (uint8_t) (version >>
|
||||
8), (uint8_t) version }; m_pnpCharacteristic->setValue(pnp, sizeof(pnp));
|
||||
*/
|
||||
swC->setValue(swVersion);
|
||||
deviceInfoService->addCharacteristic(addBLECharacteristic(swC));
|
||||
mfC->setValue(hwVendor);
|
||||
deviceInfoService->addCharacteristic(addBLECharacteristic(mfC));
|
||||
if (!hwVersion.empty()) {
|
||||
BLECharacteristic *hwvC =
|
||||
new BLECharacteristic(BLEUUID((uint16_t)ESP_GATT_UUID_HW_VERSION_STR), BLECharacteristic::PROPERTY_READ);
|
||||
hwvC->setValue(hwVersion);
|
||||
deviceInfoService->addCharacteristic(addBLECharacteristic(hwvC));
|
||||
}
|
||||
// SerialNumberCharacteristic.setValue("FIXME");
|
||||
// deviceInfoService->addCharacteristic(&SerialNumberCharacteristic);
|
||||
|
||||
// m_manufacturerCharacteristic = m_deviceInfoService->createCharacteristic((uint16_t) 0x2a29,
|
||||
// BLECharacteristic::PROPERTY_READ); m_manufacturerCharacteristic->setValue(name);
|
||||
|
||||
/* add these later?
|
||||
ESP_GATT_UUID_SYSTEM_ID
|
||||
*/
|
||||
|
||||
// caller must call service->start();
|
||||
return deviceInfoService;
|
||||
}
|
||||
|
||||
static BLECharacteristic *batteryLevelC;
|
||||
|
||||
/**
|
||||
* Create a battery level service
|
||||
*/
|
||||
BLEService *createBatteryService(BLEServer *server)
|
||||
{
|
||||
// Create the BLE Service
|
||||
BLEService *pBattery = server->createService(BLEUUID((uint16_t)0x180F));
|
||||
|
||||
batteryLevelC = new BLECharacteristic(BLEUUID((uint16_t)ESP_GATT_UUID_BATTERY_LEVEL),
|
||||
BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
|
||||
|
||||
addWithDesc(pBattery, batteryLevelC, "Percentage 0 - 100");
|
||||
batteryLevelC->addDescriptor(addBLEDescriptor(new BLE2902())); // Needed so clients can request notification
|
||||
|
||||
// I don't think we need to advertise this? and some phones only see the first thing advertised anyways...
|
||||
// server->getAdvertising()->addServiceUUID(pBattery->getUUID());
|
||||
pBattery->start();
|
||||
|
||||
return pBattery;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the battery level we are currently telling clients.
|
||||
* level should be a pct between 0 and 100
|
||||
*/
|
||||
void updateBatteryLevel(uint8_t level)
|
||||
{
|
||||
if (batteryLevelC) {
|
||||
DEBUG_MSG("set BLE battery level %u\n", level);
|
||||
batteryLevelC->setValue(&level, 1);
|
||||
batteryLevelC->notify();
|
||||
}
|
||||
}
|
||||
|
||||
void dumpCharacteristic(BLECharacteristic *c)
|
||||
{
|
||||
std::string value = c->getValue();
|
||||
|
||||
if (value.length() > 0) {
|
||||
DEBUG_MSG("New value: ");
|
||||
for (int i = 0; i < value.length(); i++)
|
||||
DEBUG_MSG("%c", value[i]);
|
||||
|
||||
DEBUG_MSG("\n");
|
||||
}
|
||||
}
|
||||
|
||||
/** converting endianness pull out a 32 bit value */
|
||||
uint32_t getValue32(BLECharacteristic *c, uint32_t defaultValue)
|
||||
{
|
||||
std::string value = c->getValue();
|
||||
uint32_t r = defaultValue;
|
||||
|
||||
if (value.length() == 4)
|
||||
r = value[0] | (value[1] << 8UL) | (value[2] << 16UL) | (value[3] << 24UL);
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
class MySecurity : public BLESecurityCallbacks
|
||||
{
|
||||
protected:
|
||||
bool onConfirmPIN(uint32_t pin)
|
||||
{
|
||||
Serial.printf("onConfirmPIN %u\n", pin);
|
||||
return false;
|
||||
}
|
||||
|
||||
uint32_t onPassKeyRequest()
|
||||
{
|
||||
Serial.println("onPassKeyRequest");
|
||||
return 123511; // not used
|
||||
}
|
||||
|
||||
void onPassKeyNotify(uint32_t pass_key)
|
||||
{
|
||||
Serial.printf("onPassKeyNotify %06u\n", pass_key);
|
||||
startCb(pass_key);
|
||||
}
|
||||
|
||||
bool onSecurityRequest()
|
||||
{
|
||||
Serial.println("onSecurityRequest");
|
||||
return true;
|
||||
}
|
||||
|
||||
void onAuthenticationComplete(esp_ble_auth_cmpl_t cmpl)
|
||||
{
|
||||
if (cmpl.success) {
|
||||
uint16_t length;
|
||||
esp_ble_gap_get_whitelist_size(&length);
|
||||
Serial.printf(" authenticated and connected to phone\n");
|
||||
} else {
|
||||
Serial.printf("phone authenticate failed %d\n", cmpl.fail_reason);
|
||||
}
|
||||
|
||||
// Remove our custom PIN request screen.
|
||||
stopCb();
|
||||
}
|
||||
|
||||
public:
|
||||
StartBluetoothPinScreenCallback startCb;
|
||||
StopBluetoothPinScreenCallback stopCb;
|
||||
};
|
||||
|
||||
BLEServer *pServer;
|
||||
|
||||
BLEService *pDevInfo, *pUpdate, *pBattery;
|
||||
|
||||
void deinitBLE()
|
||||
{
|
||||
assert(pServer);
|
||||
|
||||
pServer->getAdvertising()->stop();
|
||||
|
||||
if (pUpdate != NULL) {
|
||||
destroyUpdateService();
|
||||
|
||||
pUpdate->stop(); // we delete them below
|
||||
pUpdate->executeDelete();
|
||||
}
|
||||
|
||||
pBattery->stop();
|
||||
pBattery->executeDelete();
|
||||
|
||||
pDevInfo->stop();
|
||||
pDevInfo->executeDelete();
|
||||
|
||||
// First shutdown bluetooth
|
||||
BLEDevice::deinit(false);
|
||||
|
||||
// do not delete this - it is dynamically allocated, but only once - statically in BLEDevice
|
||||
// delete pServer->getAdvertising();
|
||||
|
||||
if (pUpdate != NULL)
|
||||
delete pUpdate;
|
||||
delete pDevInfo;
|
||||
delete pBattery;
|
||||
delete pServer;
|
||||
|
||||
batteryLevelC = NULL; // Don't let anyone generate bogus notifies
|
||||
|
||||
for (int i = 0; i < numChars; i++) {
|
||||
delete chars[i];
|
||||
}
|
||||
numChars = 0;
|
||||
|
||||
for (int i = 0; i < numDescs; i++)
|
||||
delete descs[i];
|
||||
numDescs = 0;
|
||||
|
||||
btPool.reset();
|
||||
}
|
||||
|
||||
BLEServer *initBLE(StartBluetoothPinScreenCallback startBtPinScreen, StopBluetoothPinScreenCallback stopBtPinScreen,
|
||||
std::string deviceName, std::string hwVendor, std::string swVersion, std::string hwVersion)
|
||||
{
|
||||
BLEDevice::init(deviceName);
|
||||
BLEDevice::setEncryptionLevel(ESP_BLE_SEC_ENCRYPT);
|
||||
|
||||
/*
|
||||
* Required in authentication process to provide displaying and/or input passkey or yes/no butttons confirmation
|
||||
*/
|
||||
static MySecurity mySecurity;
|
||||
mySecurity.startCb = startBtPinScreen;
|
||||
mySecurity.stopCb = stopBtPinScreen;
|
||||
BLEDevice::setSecurityCallbacks(&mySecurity);
|
||||
|
||||
// Create the BLE Server
|
||||
pServer = BLEDevice::createServer();
|
||||
static MyServerCallbacks myCallbacks;
|
||||
pServer->setCallbacks(&myCallbacks);
|
||||
|
||||
pDevInfo = createDeviceInfomationService(pServer, hwVendor, swVersion, hwVersion);
|
||||
|
||||
pBattery = createBatteryService(pServer);
|
||||
|
||||
#define BLE_SOFTWARE_UPDATE
|
||||
#ifdef BLE_SOFTWARE_UPDATE
|
||||
pUpdate = createUpdateService(pServer, hwVendor, swVersion,
|
||||
hwVersion); // We need to advertise this so our android ble scan operation can see it
|
||||
|
||||
pUpdate->start();
|
||||
#endif
|
||||
|
||||
// It seems only one service can be advertised - so for now don't advertise our updater
|
||||
// pServer->getAdvertising()->addServiceUUID(pUpdate->getUUID());
|
||||
|
||||
// start all our services (do this after creating all of them)
|
||||
pDevInfo->start();
|
||||
|
||||
// FIXME turn on this restriction only after the device is paired with a phone
|
||||
// advert->setScanFilter(false, true); // We let anyone scan for us (FIXME, perhaps only allow that until we are paired with a
|
||||
// phone and configured) but only let whitelist phones connect
|
||||
|
||||
static BLESecurity security; // static to avoid allocs
|
||||
BLESecurity *pSecurity = &security;
|
||||
pSecurity->setCapability(ESP_IO_CAP_OUT);
|
||||
|
||||
// FIXME - really should be ESP_LE_AUTH_REQ_SC_BOND but it seems there is a bug right now causing that bonding info to be lost
|
||||
// occasionally?
|
||||
pSecurity->setAuthenticationMode(ESP_LE_AUTH_REQ_SC_BOND);
|
||||
|
||||
pSecurity->setInitEncryptionKey(ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK);
|
||||
|
||||
return pServer;
|
||||
}
|
||||
|
||||
// Called from loop
|
||||
void loopBLE()
|
||||
{
|
||||
bluetoothRebootCheck();
|
||||
}
|
||||
@@ -35,5 +35,8 @@ BLECharacteristic *addBLECharacteristic(BLECharacteristic *c);
|
||||
/// Add a characteristic that we will delete when we restart
|
||||
BLEDescriptor *addBLEDescriptor(BLEDescriptor *c);
|
||||
|
||||
/// Given a level between 0-100, update the BLE attribute
|
||||
void updateBatteryLevel(uint8_t level);
|
||||
|
||||
/// Any bluetooth objects you allocate _must_ come from this pool if you want to be able to call deinitBLE()
|
||||
extern SimpleAllocator btPool;
|
||||
12
src/esp32/CallbackCharacteristic.h
Normal file
12
src/esp32/CallbackCharacteristic.h
Normal file
@@ -0,0 +1,12 @@
|
||||
#pragma once
|
||||
#include "BLECharacteristic.h"
|
||||
#include "PowerFSM.h" // FIXME - someday I want to make this OTA thing a separate lb at at that point it can't touch this
|
||||
|
||||
/**
|
||||
* A characterstic with a set of overridable callbacks
|
||||
*/
|
||||
class CallbackCharacteristic : public BLECharacteristic, public BLECharacteristicCallbacks
|
||||
{
|
||||
public:
|
||||
CallbackCharacteristic(const char *uuid, uint32_t btprops) : BLECharacteristic(uuid, btprops) { setCallbacks(this); }
|
||||
};
|
||||
83
src/esp32/ESP32CryptoEngine.cpp
Normal file
83
src/esp32/ESP32CryptoEngine.cpp
Normal file
@@ -0,0 +1,83 @@
|
||||
#include "CryptoEngine.h"
|
||||
#include "configuration.h"
|
||||
|
||||
#include "crypto/includes.h"
|
||||
|
||||
#include "crypto/common.h"
|
||||
|
||||
// #include "esp_system.h"
|
||||
|
||||
#include "crypto/aes.h"
|
||||
#include "crypto/aes_wrap.h"
|
||||
#include "mbedtls/aes.h"
|
||||
|
||||
|
||||
|
||||
class ESP32CryptoEngine : public CryptoEngine
|
||||
{
|
||||
|
||||
mbedtls_aes_context aes;
|
||||
|
||||
/// How many bytes in our key
|
||||
uint8_t keySize = 0;
|
||||
|
||||
public:
|
||||
ESP32CryptoEngine() { mbedtls_aes_init(&aes); }
|
||||
|
||||
~ESP32CryptoEngine() { mbedtls_aes_free(&aes); }
|
||||
|
||||
/**
|
||||
* Set the key used for encrypt, decrypt.
|
||||
*
|
||||
* As a special case: If all bytes are zero, we assume _no encryption_ and send all data in cleartext.
|
||||
*
|
||||
* @param numBytes must be 16 (AES128), 32 (AES256) or 0 (no crypt)
|
||||
* @param bytes a _static_ buffer that will remain valid for the life of this crypto instance (i.e. this class will cache the
|
||||
* provided pointer)
|
||||
*/
|
||||
virtual void setKey(size_t numBytes, uint8_t *bytes)
|
||||
{
|
||||
keySize = numBytes;
|
||||
DEBUG_MSG("Installing AES%d key!\n", numBytes * 8);
|
||||
if (numBytes != 0) {
|
||||
auto res = mbedtls_aes_setkey_enc(&aes, bytes, numBytes * 8);
|
||||
assert(!res);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Encrypt a packet
|
||||
*
|
||||
* @param bytes is updated in place
|
||||
*/
|
||||
virtual void encrypt(uint32_t fromNode, uint64_t packetNum, size_t numBytes, uint8_t *bytes)
|
||||
{
|
||||
if (keySize != 0) {
|
||||
uint8_t stream_block[16];
|
||||
static uint8_t scratch[MAX_BLOCKSIZE];
|
||||
size_t nc_off = 0;
|
||||
|
||||
// DEBUG_MSG("ESP32 encrypt!\n");
|
||||
initNonce(fromNode, packetNum);
|
||||
assert(numBytes <= MAX_BLOCKSIZE);
|
||||
memcpy(scratch, bytes, numBytes);
|
||||
memset(scratch + numBytes, 0,
|
||||
sizeof(scratch) - numBytes); // Fill rest of buffer with zero (in case cypher looks at it)
|
||||
|
||||
auto res = mbedtls_aes_crypt_ctr(&aes, numBytes, &nc_off, nonce, stream_block, scratch, bytes);
|
||||
assert(!res);
|
||||
}
|
||||
}
|
||||
|
||||
virtual void decrypt(uint32_t fromNode, uint64_t packetNum, size_t numBytes, uint8_t *bytes)
|
||||
{
|
||||
// DEBUG_MSG("ESP32 decrypt!\n");
|
||||
|
||||
// For CTR, the implementation is the same
|
||||
encrypt(fromNode, packetNum, numBytes, bytes);
|
||||
}
|
||||
|
||||
private:
|
||||
};
|
||||
|
||||
CryptoEngine *crypto = new ESP32CryptoEngine();
|
||||
@@ -6,155 +6,41 @@
|
||||
#include <esp_gatt_defs.h>
|
||||
|
||||
#include "CallbackCharacteristic.h"
|
||||
#include "GPS.h"
|
||||
#include "MeshService.h"
|
||||
#include "NodeDB.h"
|
||||
#include "PhoneAPI.h"
|
||||
#include "PowerFSM.h"
|
||||
#include "configuration.h"
|
||||
#include "mesh-pb-constants.h"
|
||||
#include "mesh.pb.h"
|
||||
|
||||
#include "GPS.h"
|
||||
|
||||
// This scratch buffer is used for various bluetooth reads/writes - but it is safe because only one bt operation can be in
|
||||
// proccess at once
|
||||
static uint8_t trBytes[_max(_max(_max(_max(ToRadio_size, RadioConfig_size), User_size), MyNodeInfo_size), FromRadio_size)];
|
||||
|
||||
class ProtobufCharacteristic : public CallbackCharacteristic
|
||||
{
|
||||
const pb_msgdesc_t *fields;
|
||||
void *my_struct;
|
||||
static CallbackCharacteristic *meshFromNumCharacteristic;
|
||||
|
||||
public:
|
||||
ProtobufCharacteristic(const char *uuid, uint32_t btprops, const pb_msgdesc_t *_fields, void *_my_struct)
|
||||
: CallbackCharacteristic(uuid, btprops), fields(_fields), my_struct(_my_struct)
|
||||
BLEService *meshService;
|
||||
|
||||
class BluetoothPhoneAPI : public PhoneAPI
|
||||
{
|
||||
setCallbacks(this);
|
||||
/**
|
||||
* Subclasses can use this as a hook to provide custom notifications for their transport (i.e. bluetooth notifies)
|
||||
*/
|
||||
virtual void onNowHasData(uint32_t fromRadioNum)
|
||||
{
|
||||
PhoneAPI::onNowHasData(fromRadioNum);
|
||||
|
||||
if (meshFromNumCharacteristic) { // this ptr might change from sleep to sleep, or even be null
|
||||
meshFromNumCharacteristic->setValue(fromRadioNum);
|
||||
meshFromNumCharacteristic->notify();
|
||||
}
|
||||
|
||||
void onRead(BLECharacteristic *c)
|
||||
{
|
||||
BLEKeepAliveCallbacks::onRead(c);
|
||||
size_t numbytes = pb_encode_to_bytes(trBytes, sizeof(trBytes), fields, my_struct);
|
||||
DEBUG_MSG("pbread from %s returns %d bytes\n", c->getUUID().toString().c_str(), numbytes);
|
||||
c->setValue(trBytes, numbytes);
|
||||
}
|
||||
|
||||
void onWrite(BLECharacteristic *c)
|
||||
{
|
||||
BLEKeepAliveCallbacks::onWrite(c);
|
||||
writeToDest(c, my_struct);
|
||||
}
|
||||
|
||||
protected:
|
||||
/// like onWrite, but we provide an different destination to write to, for use by subclasses that
|
||||
/// want to optionally ignore parts of writes.
|
||||
/// returns true for success
|
||||
bool writeToDest(BLECharacteristic *c, void *dest)
|
||||
{
|
||||
// dumpCharacteristic(pCharacteristic);
|
||||
std::string src = c->getValue();
|
||||
DEBUG_MSG("pbwrite to %s of %d bytes\n", c->getUUID().toString().c_str(), src.length());
|
||||
return pb_decode_from_bytes((const uint8_t *)src.c_str(), src.length(), fields, dest);
|
||||
}
|
||||
};
|
||||
|
||||
class NodeInfoCharacteristic : public BLECharacteristic, public BLEKeepAliveCallbacks
|
||||
{
|
||||
public:
|
||||
NodeInfoCharacteristic()
|
||||
: BLECharacteristic("d31e02e0-c8ab-4d3f-9cc9-0b8466bdabe8",
|
||||
BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_READ)
|
||||
{
|
||||
setCallbacks(this);
|
||||
}
|
||||
BluetoothPhoneAPI *bluetoothPhoneAPI;
|
||||
|
||||
void onRead(BLECharacteristic *c)
|
||||
{
|
||||
BLEKeepAliveCallbacks::onRead(c);
|
||||
|
||||
const NodeInfo *info = nodeDB.readNextInfo();
|
||||
|
||||
if (info) {
|
||||
DEBUG_MSG("Sending nodeinfo: num=0x%x, lastseen=%u, id=%s, name=%s\n", info->num, info->position.time, info->user.id,
|
||||
info->user.long_name);
|
||||
size_t numbytes = pb_encode_to_bytes(trBytes, sizeof(trBytes), NodeInfo_fields, info);
|
||||
c->setValue(trBytes, numbytes);
|
||||
} else {
|
||||
c->setValue(trBytes, 0); // Send an empty response
|
||||
DEBUG_MSG("Done sending nodeinfos\n");
|
||||
}
|
||||
}
|
||||
|
||||
void onWrite(BLECharacteristic *c)
|
||||
{
|
||||
BLEKeepAliveCallbacks::onWrite(c);
|
||||
DEBUG_MSG("Reset nodeinfo read pointer\n");
|
||||
nodeDB.resetReadPointer();
|
||||
}
|
||||
};
|
||||
|
||||
// wrap our protobuf version with something that forces the service to reload the config
|
||||
class RadioCharacteristic : public ProtobufCharacteristic
|
||||
{
|
||||
public:
|
||||
RadioCharacteristic()
|
||||
: ProtobufCharacteristic("b56786c8-839a-44a1-b98e-a1724c4a0262",
|
||||
BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_READ, RadioConfig_fields,
|
||||
&radioConfig)
|
||||
{
|
||||
}
|
||||
|
||||
void onRead(BLECharacteristic *c)
|
||||
{
|
||||
DEBUG_MSG("Reading radio config, sdsecs %u\n", radioConfig.preferences.sds_secs);
|
||||
ProtobufCharacteristic::onRead(c);
|
||||
}
|
||||
|
||||
void onWrite(BLECharacteristic *c)
|
||||
{
|
||||
DEBUG_MSG("Writing radio config\n");
|
||||
ProtobufCharacteristic::onWrite(c);
|
||||
service.reloadConfig();
|
||||
}
|
||||
};
|
||||
|
||||
// wrap our protobuf version with something that forces the service to reload the owner
|
||||
class OwnerCharacteristic : public ProtobufCharacteristic
|
||||
{
|
||||
public:
|
||||
OwnerCharacteristic()
|
||||
: ProtobufCharacteristic("6ff1d8b6-e2de-41e3-8c0b-8fa384f64eb6",
|
||||
BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_READ, User_fields, &owner)
|
||||
{
|
||||
}
|
||||
|
||||
void onWrite(BLECharacteristic *c)
|
||||
{
|
||||
BLEKeepAliveCallbacks::onWrite(
|
||||
c); // NOTE: We do not call the standard ProtobufCharacteristic superclass, because we want custom write behavior
|
||||
|
||||
static User o; // if the phone doesn't set ID we are careful to keep ours, we also always keep our macaddr
|
||||
if (writeToDest(c, &o)) {
|
||||
int changed = 0;
|
||||
|
||||
if (*o.long_name) {
|
||||
changed |= strcmp(owner.long_name, o.long_name);
|
||||
strcpy(owner.long_name, o.long_name);
|
||||
}
|
||||
if (*o.short_name) {
|
||||
changed |= strcmp(owner.short_name, o.short_name);
|
||||
strcpy(owner.short_name, o.short_name);
|
||||
}
|
||||
if (*o.id) {
|
||||
changed |= strcmp(owner.id, o.id);
|
||||
strcpy(owner.id, o.id);
|
||||
}
|
||||
|
||||
if (changed) // If nothing really changed, don't broadcast on the network or write to flash
|
||||
service.reloadOwner();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
class ToRadioCharacteristic : public CallbackCharacteristic
|
||||
{
|
||||
@@ -163,10 +49,7 @@ class ToRadioCharacteristic : public CallbackCharacteristic
|
||||
|
||||
void onWrite(BLECharacteristic *c)
|
||||
{
|
||||
BLEKeepAliveCallbacks::onWrite(c);
|
||||
DEBUG_MSG("Got on write\n");
|
||||
|
||||
service.handleToRadio(c->getValue());
|
||||
bluetoothPhoneAPI->handleToRadio(c->getData(), c->getValue().length());
|
||||
}
|
||||
};
|
||||
|
||||
@@ -179,32 +62,19 @@ class FromRadioCharacteristic : public CallbackCharacteristic
|
||||
|
||||
void onRead(BLECharacteristic *c)
|
||||
{
|
||||
BLEKeepAliveCallbacks::onRead(c);
|
||||
MeshPacket *mp = service.getForPhone();
|
||||
size_t numBytes = bluetoothPhoneAPI->getFromRadio(trBytes);
|
||||
|
||||
// Someone is going to read our value as soon as this callback returns. So fill it with the next message in the queue
|
||||
// or make empty if the queue is empty
|
||||
if (!mp) {
|
||||
DEBUG_MSG("toPhone queue is empty\n");
|
||||
c->setValue((uint8_t *)"", 0);
|
||||
if (numBytes) {
|
||||
c->setValue(trBytes, numBytes);
|
||||
} else {
|
||||
static FromRadio fRadio;
|
||||
|
||||
// Encapsulate as a FromRadio packet
|
||||
memset(&fRadio, 0, sizeof(fRadio));
|
||||
fRadio.which_variant = FromRadio_packet_tag;
|
||||
fRadio.variant.packet = *mp;
|
||||
|
||||
size_t numbytes = pb_encode_to_bytes(trBytes, sizeof(trBytes), FromRadio_fields, &fRadio);
|
||||
DEBUG_MSG("delivering toPhone packet to phone %d bytes\n", numbytes);
|
||||
c->setValue(trBytes, numbytes);
|
||||
|
||||
service.releaseToPool(mp); // we just copied the bytes, so don't need this buffer anymore
|
||||
c->setValue((uint8_t *)"", 0);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
class FromNumCharacteristic : public CallbackCharacteristic, public Observer<uint32_t>
|
||||
class FromNumCharacteristic : public CallbackCharacteristic
|
||||
{
|
||||
public:
|
||||
FromNumCharacteristic()
|
||||
@@ -212,54 +82,23 @@ class FromNumCharacteristic : public CallbackCharacteristic, public Observer<uin
|
||||
BLECharacteristic::PROPERTY_READ |
|
||||
BLECharacteristic::PROPERTY_NOTIFY)
|
||||
{
|
||||
observe(&service.fromNumChanged);
|
||||
// observe(&service.fromNumChanged);
|
||||
}
|
||||
|
||||
void onRead(BLECharacteristic *c)
|
||||
{
|
||||
BLEKeepAliveCallbacks::onRead(c);
|
||||
DEBUG_MSG("FIXME implement fromnum read\n");
|
||||
}
|
||||
|
||||
/// If the mesh service tells us fromNum has changed, tell the phone
|
||||
virtual int onNotify(uint32_t newValue)
|
||||
{
|
||||
setValue(newValue);
|
||||
notify();
|
||||
return 0;
|
||||
}
|
||||
void onRead(BLECharacteristic *c) { DEBUG_MSG("FIXME implement fromnum read\n"); }
|
||||
};
|
||||
|
||||
class MyNodeInfoCharacteristic : public ProtobufCharacteristic
|
||||
{
|
||||
public:
|
||||
MyNodeInfoCharacteristic()
|
||||
: ProtobufCharacteristic("ea9f3f82-8dc4-4733-9452-1f6da28892a2", BLECharacteristic::PROPERTY_READ, MyNodeInfo_fields,
|
||||
&myNodeInfo)
|
||||
{
|
||||
}
|
||||
|
||||
void onRead(BLECharacteristic *c)
|
||||
{
|
||||
// update gps connection state
|
||||
myNodeInfo.has_gps = gps.isConnected;
|
||||
|
||||
ProtobufCharacteristic::onRead(c);
|
||||
|
||||
myNodeInfo.error_code = 0; // The phone just read us, so throw it away
|
||||
myNodeInfo.error_address = 0;
|
||||
}
|
||||
};
|
||||
|
||||
FromNumCharacteristic *meshFromNumCharacteristic;
|
||||
|
||||
BLEService *meshService;
|
||||
|
||||
/*
|
||||
See bluetooth-api.md for documentation.
|
||||
*/
|
||||
BLEService *createMeshBluetoothService(BLEServer *server)
|
||||
{
|
||||
// Only create our phone API object once
|
||||
if (!bluetoothPhoneAPI) {
|
||||
bluetoothPhoneAPI = new BluetoothPhoneAPI();
|
||||
bluetoothPhoneAPI->init();
|
||||
}
|
||||
|
||||
// Create the BLE Service, we need more than the default of 15 handles
|
||||
BLEService *service = server->createService(BLEUUID("6ba1b218-15a8-461f-9fa8-5dcae273eafd"), 30, 0);
|
||||
|
||||
@@ -269,10 +108,6 @@ BLEService *createMeshBluetoothService(BLEServer *server)
|
||||
addWithDesc(service, meshFromNumCharacteristic, "fromRadio");
|
||||
addWithDesc(service, new ToRadioCharacteristic, "toRadio");
|
||||
addWithDesc(service, new FromRadioCharacteristic, "fromNum");
|
||||
addWithDesc(service, new MyNodeInfoCharacteristic, "myNode");
|
||||
addWithDesc(service, new RadioCharacteristic, "radio");
|
||||
addWithDesc(service, new OwnerCharacteristic, "owner");
|
||||
addWithDesc(service, new NodeInfoCharacteristic, "nodeinfo");
|
||||
|
||||
meshFromNumCharacteristic->addDescriptor(addBLEDescriptor(new BLE2902())); // Needed so clients can request notification
|
||||
|
||||
@@ -296,6 +131,7 @@ void stopMeshBluetoothService()
|
||||
{
|
||||
assert(meshService);
|
||||
meshService->stop();
|
||||
meshService->executeDelete();
|
||||
}
|
||||
|
||||
void destroyMeshBluetoothService()
|
||||
|
||||
@@ -2,8 +2,11 @@
|
||||
#include "MeshBluetoothService.h"
|
||||
#include "PowerFSM.h"
|
||||
#include "configuration.h"
|
||||
#include "esp_task_wdt.h"
|
||||
#include "main.h"
|
||||
#include "sleep.h"
|
||||
#include "target_specific.h"
|
||||
#include "utils.h"
|
||||
|
||||
bool bluetoothOn;
|
||||
|
||||
@@ -21,8 +24,8 @@ void reinitBluetooth()
|
||||
powerFSM.trigger(EVENT_BLUETOOTH_PAIR);
|
||||
screen.startBluetoothPinScreen(pin);
|
||||
},
|
||||
[]() { screen.stopBluetoothPinScreen(); }, getDeviceName(), HW_VENDOR, xstr(APP_VERSION),
|
||||
xstr(HW_VERSION)); // FIXME, use a real name based on the macaddr
|
||||
[]() { screen.stopBluetoothPinScreen(); }, getDeviceName(), HW_VENDOR, optstr(APP_VERSION),
|
||||
optstr(HW_VERSION)); // FIXME, use a real name based on the macaddr
|
||||
createMeshBluetoothService(serve);
|
||||
|
||||
// Start advertising - this must be done _after_ creating all services
|
||||
@@ -51,3 +54,74 @@ void setBluetoothEnable(bool on)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void getMacAddr(uint8_t *dmac)
|
||||
{
|
||||
assert(esp_efuse_mac_get_default(dmac) == ESP_OK);
|
||||
}
|
||||
|
||||
/*
|
||||
static void printBLEinfo() {
|
||||
int dev_num = esp_ble_get_bond_device_num();
|
||||
|
||||
esp_ble_bond_dev_t *dev_list = (esp_ble_bond_dev_t *)malloc(sizeof(esp_ble_bond_dev_t) * dev_num);
|
||||
esp_ble_get_bond_device_list(&dev_num, dev_list);
|
||||
for (int i = 0; i < dev_num; i++) {
|
||||
// esp_ble_remove_bond_device(dev_list[i].bd_addr);
|
||||
}
|
||||
|
||||
} */
|
||||
|
||||
void esp32Setup()
|
||||
{
|
||||
uint32_t seed = esp_random();
|
||||
DEBUG_MSG("Setting random seed %u\n", seed);
|
||||
randomSeed(seed); // ESP docs say this is fairly random
|
||||
|
||||
DEBUG_MSG("Total heap: %d\n", ESP.getHeapSize());
|
||||
DEBUG_MSG("Free heap: %d\n", ESP.getFreeHeap());
|
||||
DEBUG_MSG("Total PSRAM: %d\n", ESP.getPsramSize());
|
||||
DEBUG_MSG("Free PSRAM: %d\n", ESP.getFreePsram());
|
||||
|
||||
// enableModemSleep();
|
||||
|
||||
// Since we are turning on watchdogs rather late in the release schedule, we really don't want to catch any
|
||||
// false positives. The wait-to-sleep timeout for shutting down radios is 30 secs, so pick 45 for now.
|
||||
#define APP_WATCHDOG_SECS 45
|
||||
|
||||
auto res = esp_task_wdt_init(APP_WATCHDOG_SECS, true);
|
||||
assert(res == ESP_OK);
|
||||
|
||||
res = esp_task_wdt_add(NULL);
|
||||
assert(res == ESP_OK);
|
||||
}
|
||||
|
||||
#if 0
|
||||
// Turn off for now
|
||||
|
||||
uint32_t axpDebugRead()
|
||||
{
|
||||
axp.debugCharging();
|
||||
DEBUG_MSG("vbus current %f\n", axp.getVbusCurrent());
|
||||
DEBUG_MSG("charge current %f\n", axp.getBattChargeCurrent());
|
||||
DEBUG_MSG("bat voltage %f\n", axp.getBattVoltage());
|
||||
DEBUG_MSG("batt pct %d\n", axp.getBattPercentage());
|
||||
DEBUG_MSG("is battery connected %d\n", axp.isBatteryConnect());
|
||||
DEBUG_MSG("is USB connected %d\n", axp.isVBUSPlug());
|
||||
DEBUG_MSG("is charging %d\n", axp.isChargeing());
|
||||
|
||||
return 30 * 1000;
|
||||
}
|
||||
|
||||
Periodic axpDebugOutput(axpDebugRead);
|
||||
#endif
|
||||
|
||||
/// loop code specific to ESP32 targets
|
||||
void esp32Loop()
|
||||
{
|
||||
esp_task_wdt_reset(); // service our app level watchdog
|
||||
loopBLE();
|
||||
|
||||
// for debug printing
|
||||
// radio.radioIf.canSleep();
|
||||
}
|
||||
@@ -1,16 +1,30 @@
|
||||
#pragma once
|
||||
|
||||
// The FreeRTOS includes are in a different directory on ESP32 and I can't figure out how to make that work with platformio gcc options
|
||||
// so this is my quick hack to make things work
|
||||
// The FreeRTOS includes are in a different directory on ESP32 and I can't figure out how to make that work with platformio gcc
|
||||
// options so this is my quick hack to make things work
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
#define HAS_FREE_RTOS
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/task.h>
|
||||
#include <freertos/semphr.h>
|
||||
#include <freertos/queue.h>
|
||||
#include <freertos/semphr.h>
|
||||
#include <freertos/task.h>
|
||||
#else
|
||||
// not yet supported on cubecell
|
||||
#ifndef CubeCell_BoardPlus
|
||||
#define HAS_FREE_RTOS
|
||||
#include <FreeRTOS.h>
|
||||
#include <task.h>
|
||||
#include <semphr.h>
|
||||
#include <queue.h>
|
||||
#include <semphr.h>
|
||||
#include <task.h>
|
||||
#else
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
typedef uint32_t TickType_t;
|
||||
typedef uint32_t BaseType_t;
|
||||
|
||||
#define portMAX_DELAY UINT32_MAX
|
||||
|
||||
#endif
|
||||
#endif
|
||||
81
src/gps/GPS.cpp
Normal file
81
src/gps/GPS.cpp
Normal file
@@ -0,0 +1,81 @@
|
||||
|
||||
#include "GPS.h"
|
||||
#include "configuration.h"
|
||||
#include "time.h"
|
||||
#include <assert.h>
|
||||
#include <sys/time.h>
|
||||
|
||||
#ifdef GPS_RX_PIN
|
||||
HardwareSerial _serial_gps_real(GPS_SERIAL_NUM);
|
||||
HardwareSerial &GPS::_serial_gps = _serial_gps_real;
|
||||
#else
|
||||
// Assume NRF52
|
||||
HardwareSerial &GPS::_serial_gps = Serial1;
|
||||
#endif
|
||||
|
||||
bool timeSetFromGPS; // We try to set our time from GPS each time we wake from sleep
|
||||
|
||||
GPS *gps;
|
||||
|
||||
// stuff that really should be in in the instance instead...
|
||||
static uint32_t
|
||||
timeStartMsec; // Once we have a GPS lock, this is where we hold the initial msec clock that corresponds to that time
|
||||
static uint64_t zeroOffsetSecs; // GPS based time in secs since 1970 - only updated once on initial lock
|
||||
|
||||
void readFromRTC()
|
||||
{
|
||||
struct timeval tv; /* btw settimeofday() is helpfull here too*/
|
||||
|
||||
if (!gettimeofday(&tv, NULL)) {
|
||||
uint32_t now = millis();
|
||||
|
||||
DEBUG_MSG("Read RTC time as %ld (cur millis %u) valid=%d\n", tv.tv_sec, now, timeSetFromGPS);
|
||||
timeStartMsec = now;
|
||||
zeroOffsetSecs = tv.tv_sec;
|
||||
}
|
||||
}
|
||||
|
||||
/// If we haven't yet set our RTC this boot, set it from a GPS derived time
|
||||
void perhapsSetRTC(const struct timeval *tv)
|
||||
{
|
||||
if (!timeSetFromGPS) {
|
||||
timeSetFromGPS = true;
|
||||
DEBUG_MSG("Setting RTC %ld secs\n", tv->tv_sec);
|
||||
#ifndef NO_ESP32
|
||||
settimeofday(tv, NULL);
|
||||
#else
|
||||
DEBUG_MSG("ERROR TIME SETTING NOT IMPLEMENTED!\n");
|
||||
#endif
|
||||
readFromRTC();
|
||||
}
|
||||
}
|
||||
|
||||
void perhapsSetRTC(struct tm &t)
|
||||
{
|
||||
/* Convert to unix time
|
||||
The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970
|
||||
(midnight UTC/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z).
|
||||
*/
|
||||
time_t res = mktime(&t);
|
||||
struct timeval tv;
|
||||
tv.tv_sec = res;
|
||||
tv.tv_usec = 0; // time.centisecond() * (10 / 1000);
|
||||
|
||||
// DEBUG_MSG("Got time from GPS month=%d, year=%d, unixtime=%ld\n", t.tm_mon, t.tm_year, tv.tv_sec);
|
||||
if (t.tm_year < 0 || t.tm_year >= 300)
|
||||
DEBUG_MSG("Ignoring invalid GPS time\n");
|
||||
else
|
||||
perhapsSetRTC(&tv);
|
||||
}
|
||||
|
||||
#include <time.h>
|
||||
|
||||
uint32_t getTime()
|
||||
{
|
||||
return ((millis() - timeStartMsec) / 1000) + zeroOffsetSecs;
|
||||
}
|
||||
|
||||
uint32_t getValidTime()
|
||||
{
|
||||
return timeSetFromGPS ? getTime() : 0;
|
||||
}
|
||||
63
src/gps/GPS.h
Normal file
63
src/gps/GPS.h
Normal file
@@ -0,0 +1,63 @@
|
||||
#pragma once
|
||||
|
||||
#include "Observer.h"
|
||||
#include "GPSStatus.h"
|
||||
#include "PeriodicTask.h"
|
||||
#include "sys/time.h"
|
||||
|
||||
/// If we haven't yet set our RTC this boot, set it from a GPS derived time
|
||||
void perhapsSetRTC(const struct timeval *tv);
|
||||
void perhapsSetRTC(struct tm &t);
|
||||
|
||||
// Generate a string representation of DOP
|
||||
const char *getDOPString(uint32_t dop);
|
||||
|
||||
/// Return time since 1970 in secs. Until we have a GPS lock we will be returning time based at zero
|
||||
uint32_t getTime();
|
||||
|
||||
/// Return time since 1970 in secs. If we don't have a GPS lock return zero
|
||||
uint32_t getValidTime();
|
||||
|
||||
void readFromRTC();
|
||||
|
||||
/**
|
||||
* A gps class that only reads from the GPS periodically (and FIXME - eventually keeps the gps powered down except when reading)
|
||||
*
|
||||
* When new data is available it will notify observers.
|
||||
*/
|
||||
class GPS : public Observable<void *>
|
||||
{
|
||||
protected:
|
||||
bool hasValidLocation = false; // default to false, until we complete our first read
|
||||
|
||||
static HardwareSerial &_serial_gps;
|
||||
|
||||
public:
|
||||
int32_t latitude = 0, longitude = 0; // as an int mult by 1e-7 to get value as double
|
||||
int32_t altitude = 0;
|
||||
uint32_t dop = 0; // Diminution of position; PDOP where possible (UBlox), HDOP otherwise (TinyGPS) in 10^2 units (needs scaling before use)
|
||||
|
||||
bool isConnected = false; // Do we have a GPS we are talking to
|
||||
|
||||
virtual ~GPS() {}
|
||||
|
||||
Observable<const meshtastic::GPSStatus *> newStatus;
|
||||
|
||||
/**
|
||||
* Returns true if we succeeded
|
||||
*/
|
||||
virtual bool setup() { return true; }
|
||||
|
||||
/// A loop callback for subclasses that need it. FIXME, instead just block on serial reads
|
||||
virtual void loop() {}
|
||||
|
||||
/// Returns ture if we have acquired GPS lock.
|
||||
bool hasLock() const { return hasValidLocation; }
|
||||
|
||||
/**
|
||||
* Restart our lock attempt - try to get and broadcast a GPS reading ASAP
|
||||
* called after the CPU wakes from light-sleep state */
|
||||
virtual void startLock() {}
|
||||
};
|
||||
|
||||
extern GPS *gps;
|
||||
73
src/gps/NEMAGPS.cpp
Normal file
73
src/gps/NEMAGPS.cpp
Normal file
@@ -0,0 +1,73 @@
|
||||
#include "NEMAGPS.h"
|
||||
#include "configuration.h"
|
||||
|
||||
static int32_t toDegInt(RawDegrees d)
|
||||
{
|
||||
int32_t degMult = 10000000; // 1e7
|
||||
int32_t r = d.deg * degMult + d.billionths / 100;
|
||||
if (d.negative)
|
||||
r *= -1;
|
||||
return r;
|
||||
}
|
||||
|
||||
void NEMAGPS::loop()
|
||||
{
|
||||
|
||||
while (_serial_gps.available() > 0) {
|
||||
int c = _serial_gps.read();
|
||||
// Serial.write(c);
|
||||
reader.encode(c);
|
||||
}
|
||||
|
||||
uint32_t now = millis();
|
||||
if ((now - lastUpdateMsec) > 20 * 1000) { // Ugly hack for now - limit update checks to once every 20 secs (but still consume
|
||||
// serial chars at whatever rate)
|
||||
lastUpdateMsec = now;
|
||||
|
||||
auto ti = reader.time;
|
||||
auto d = reader.date;
|
||||
if (ti.isUpdated() && ti.isValid() && d.isValid()) {
|
||||
/* Convert to unix time
|
||||
The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970
|
||||
(midnight UTC/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z).
|
||||
*/
|
||||
struct tm t;
|
||||
t.tm_sec = ti.second();
|
||||
t.tm_min = ti.minute();
|
||||
t.tm_hour = ti.hour();
|
||||
t.tm_mday = d.day();
|
||||
t.tm_mon = d.month() - 1;
|
||||
t.tm_year = d.year() - 1900;
|
||||
t.tm_isdst = false;
|
||||
perhapsSetRTC(t);
|
||||
|
||||
isConnected = true; // we seem to have a real GPS (but not necessarily a lock)
|
||||
}
|
||||
|
||||
if (reader.location.isUpdated()) {
|
||||
if (reader.altitude.isValid())
|
||||
altitude = reader.altitude.meters();
|
||||
|
||||
if (reader.location.isValid()) {
|
||||
auto loc = reader.location.value();
|
||||
latitude = toDegInt(loc.lat);
|
||||
longitude = toDegInt(loc.lng);
|
||||
}
|
||||
// Diminution of precision (an accuracy metric) is reported in 10^2 units, so we need to scale down when we use it
|
||||
if(reader.hdop.isValid()) {
|
||||
dop = reader.hdop.value();
|
||||
}
|
||||
|
||||
// expect gps pos lat=37.520825, lon=-122.309162, alt=158
|
||||
DEBUG_MSG("new NEMA GPS pos lat=%f, lon=%f, alt=%d, hdop=%f\n", latitude * 1e-7, longitude * 1e-7, altitude, dop * 1e-2);
|
||||
|
||||
hasValidLocation = (latitude != 0) || (longitude != 0); // bogus lat lon is reported as 0,0
|
||||
if (hasValidLocation)
|
||||
notifyObservers(NULL);
|
||||
}
|
||||
|
||||
// Notify any status instances that are observing us
|
||||
const meshtastic::GPSStatus status = meshtastic::GPSStatus(hasLock(), isConnected, latitude, longitude, altitude, dop);
|
||||
newStatus.notifyObservers(&status);
|
||||
}
|
||||
}
|
||||
21
src/gps/NEMAGPS.h
Normal file
21
src/gps/NEMAGPS.h
Normal file
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
|
||||
#include "GPS.h"
|
||||
#include "Observer.h"
|
||||
#include "PeriodicTask.h"
|
||||
#include "TinyGPS++.h"
|
||||
|
||||
/**
|
||||
* A gps class thatreads from a NEMA GPS stream (and FIXME - eventually keeps the gps powered down except when reading)
|
||||
*
|
||||
* When new data is available it will notify observers.
|
||||
*/
|
||||
class NEMAGPS : public GPS
|
||||
{
|
||||
TinyGPSPlus reader;
|
||||
|
||||
uint32_t lastUpdateMsec = 0;
|
||||
|
||||
public:
|
||||
virtual void loop();
|
||||
};
|
||||
145
src/gps/UBloxGPS.cpp
Normal file
145
src/gps/UBloxGPS.cpp
Normal file
@@ -0,0 +1,145 @@
|
||||
#include "UBloxGPS.h"
|
||||
#include "sleep.h"
|
||||
#include <assert.h>
|
||||
|
||||
UBloxGPS::UBloxGPS() : PeriodicTask()
|
||||
{
|
||||
notifySleepObserver.observe(¬ifySleep);
|
||||
}
|
||||
|
||||
bool UBloxGPS::setup()
|
||||
{
|
||||
#ifdef GPS_RX_PIN
|
||||
_serial_gps.begin(GPS_BAUDRATE, SERIAL_8N1, GPS_RX_PIN, GPS_TX_PIN);
|
||||
#else
|
||||
_serial_gps.begin(GPS_BAUDRATE);
|
||||
#endif
|
||||
// _serial_gps.setRxBufferSize(1024); // the default is 256
|
||||
// ublox.enableDebugging(Serial);
|
||||
|
||||
// note: the lib's implementation has the wrong docs for what the return val is
|
||||
// it is not a bool, it returns zero for success
|
||||
isConnected = ublox.begin(_serial_gps);
|
||||
|
||||
// try a second time, the ublox lib serial parsing is buggy?
|
||||
if (!isConnected)
|
||||
isConnected = ublox.begin(_serial_gps);
|
||||
|
||||
if (isConnected) {
|
||||
DEBUG_MSG("Connected to UBLOX GPS successfully\n");
|
||||
|
||||
bool factoryReset = false;
|
||||
bool ok;
|
||||
if (factoryReset) {
|
||||
// It is useful to force back into factory defaults (9600baud, NEMA to test the behavior of boards that don't have
|
||||
// GPS_TX connected)
|
||||
ublox.factoryReset();
|
||||
delay(3000);
|
||||
isConnected = ublox.begin(_serial_gps);
|
||||
DEBUG_MSG("Factory reset success=%d\n", isConnected);
|
||||
ok = ublox.saveConfiguration(3000);
|
||||
assert(ok);
|
||||
return false;
|
||||
} else {
|
||||
ok = ublox.setUART1Output(COM_TYPE_UBX, 500); // Use native API
|
||||
assert(ok);
|
||||
ok = ublox.setNavigationFrequency(1, 500); // Produce 4x/sec to keep the amount of time we stall in getPVT low
|
||||
assert(ok);
|
||||
// ok = ublox.setAutoPVT(false); // Not implemented on NEO-6M
|
||||
// assert(ok);
|
||||
// ok = ublox.setDynamicModel(DYN_MODEL_BIKE); // probably PEDESTRIAN but just in case assume bike speeds
|
||||
// assert(ok);
|
||||
ok = ublox.powerSaveMode(true, 2000); // use power save mode, the default timeout (1100ms seems a bit too tight)
|
||||
assert(ok);
|
||||
}
|
||||
ok = ublox.saveConfiguration(3000);
|
||||
assert(ok);
|
||||
|
||||
PeriodicTask::setup(); // We don't start our periodic task unless we actually found the device
|
||||
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Prepare the GPS for the cpu entering deep or light sleep, expect to be gone for at least 100s of msecs
|
||||
int UBloxGPS::prepareSleep(void *unused)
|
||||
{
|
||||
if (isConnected)
|
||||
ublox.powerOff();
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void UBloxGPS::doTask()
|
||||
{
|
||||
uint8_t fixtype = 3; // If we are only using the RX pin, assume we have a 3d fix
|
||||
|
||||
assert(isConnected);
|
||||
|
||||
// Consume all characters that have arrived
|
||||
|
||||
// getPVT automatically calls checkUblox
|
||||
ublox.checkUblox(); // See if new data is available. Process bytes as they come in.
|
||||
|
||||
// If we don't have a fix (a quick check), don't try waiting for a solution)
|
||||
// Hmmm my fix type reading returns zeros for fix, which doesn't seem correct, because it is still sptting out positions
|
||||
// turn off for now
|
||||
fixtype = ublox.getFixType(0);
|
||||
DEBUG_MSG("GPS fix type %d\n", fixtype);
|
||||
|
||||
// DEBUG_MSG("sec %d\n", ublox.getSecond());
|
||||
// DEBUG_MSG("lat %d\n", ublox.getLatitude());
|
||||
|
||||
// any fix that has time
|
||||
if (ublox.getT(0)) {
|
||||
/* Convert to unix time
|
||||
The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970
|
||||
(midnight UTC/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z).
|
||||
*/
|
||||
struct tm t;
|
||||
t.tm_sec = ublox.getSecond(0);
|
||||
t.tm_min = ublox.getMinute(0);
|
||||
t.tm_hour = ublox.getHour(0);
|
||||
t.tm_mday = ublox.getDay(0);
|
||||
t.tm_mon = ublox.getMonth(0) - 1;
|
||||
t.tm_year = ublox.getYear(0) - 1900;
|
||||
t.tm_isdst = false;
|
||||
perhapsSetRTC(t);
|
||||
}
|
||||
|
||||
if ((fixtype >= 3 && fixtype <= 4) && ublox.getP(0)) // rd fixes only
|
||||
{
|
||||
// we only notify if position has changed
|
||||
latitude = ublox.getLatitude(0);
|
||||
longitude = ublox.getLongitude(0);
|
||||
altitude = ublox.getAltitude(0) / 1000; // in mm convert to meters
|
||||
dop = ublox.getPDOP(0); // PDOP (an accuracy metric) is reported in 10^2 units so we have to scale down when we use it
|
||||
|
||||
// bogus lat lon is reported as 0 or 0 (can be bogus just for one)
|
||||
// Also: apparently when the GPS is initially reporting lock it can output a bogus latitude > 90 deg!
|
||||
hasValidLocation = (latitude != 0) && (longitude != 0) && (latitude <= 900000000 && latitude >= -900000000);
|
||||
if (hasValidLocation) {
|
||||
wantNewLocation = false;
|
||||
notifyObservers(NULL);
|
||||
// ublox.powerOff();
|
||||
}
|
||||
} else // we didn't get a location update, go back to sleep and hope the characters show up
|
||||
wantNewLocation = true;
|
||||
|
||||
// Notify any status instances that are observing us
|
||||
const meshtastic::GPSStatus status = meshtastic::GPSStatus(hasLock(), isConnected, latitude, longitude, altitude, dop);
|
||||
newStatus.notifyObservers(&status);
|
||||
|
||||
// Once we have sent a location once we only poll the GPS rarely, otherwise check back every 1s until we have something over
|
||||
// the serial
|
||||
setPeriod(hasValidLocation && !wantNewLocation ? 30 * 1000 : 10 * 1000);
|
||||
}
|
||||
|
||||
void UBloxGPS::startLock()
|
||||
{
|
||||
DEBUG_MSG("Looking for GPS lock\n");
|
||||
wantNewLocation = true;
|
||||
setPeriod(1);
|
||||
}
|
||||
41
src/gps/UBloxGPS.h
Normal file
41
src/gps/UBloxGPS.h
Normal file
@@ -0,0 +1,41 @@
|
||||
#pragma once
|
||||
|
||||
#include "GPS.h"
|
||||
#include "Observer.h"
|
||||
#include "PeriodicTask.h"
|
||||
#include "SparkFun_Ublox_Arduino_Library.h"
|
||||
|
||||
/**
|
||||
* A gps class that only reads from the GPS periodically (and FIXME - eventually keeps the gps powered down except when reading)
|
||||
*
|
||||
* When new data is available it will notify observers.
|
||||
*/
|
||||
class UBloxGPS : public GPS, public PeriodicTask
|
||||
{
|
||||
SFE_UBLOX_GPS ublox;
|
||||
|
||||
bool wantNewLocation = true;
|
||||
|
||||
CallbackObserver<UBloxGPS, void *> notifySleepObserver = CallbackObserver<UBloxGPS, void *>(this, &UBloxGPS::prepareSleep);
|
||||
|
||||
public:
|
||||
UBloxGPS();
|
||||
|
||||
/**
|
||||
* Returns true if we succeeded
|
||||
*/
|
||||
virtual bool setup();
|
||||
|
||||
virtual void doTask();
|
||||
|
||||
/**
|
||||
* Restart our lock attempt - try to get and broadcast a GPS reading ASAP
|
||||
* called after the CPU wakes from light-sleep state */
|
||||
virtual void startLock();
|
||||
|
||||
private:
|
||||
|
||||
/// Prepare the GPS for the cpu entering deep or light sleep, expect to be gone for at least 100s of msecs
|
||||
/// always returns 0 to indicate okay to sleep
|
||||
int prepareSleep(void *unused);
|
||||
};
|
||||
@@ -4,7 +4,12 @@ const uint8_t SATELLITE_IMAGE[] PROGMEM = {0x00, 0x08, 0x00, 0x1C, 0x00, 0x0E, 0
|
||||
0xF8, 0x00, 0xF0, 0x01, 0xE0, 0x03, 0xC8, 0x01, 0x9C, 0x54,
|
||||
0x0E, 0x52, 0x07, 0x48, 0x02, 0x26, 0x00, 0x10, 0x00, 0x0E};
|
||||
|
||||
const
|
||||
const uint8_t imgUSB[] PROGMEM = { 0x60, 0x60, 0x30, 0x18, 0x18, 0x18, 0x24, 0x42, 0x42, 0x42, 0x42, 0x7E, 0x24, 0x24, 0x24, 0x3C };
|
||||
const uint8_t imgPower[] PROGMEM = { 0x40, 0x40, 0x40, 0x58, 0x48, 0x08, 0x08, 0x08, 0x1C, 0x22, 0x22, 0x41, 0x7F, 0x22, 0x22, 0x22 };
|
||||
const uint8_t imgUser[] PROGMEM = { 0x3C, 0x42, 0x99, 0xA5, 0xA5, 0x99, 0x42, 0x3C };
|
||||
const uint8_t imgPositionEmpty[] PROGMEM = { 0x20, 0x30, 0x28, 0x24, 0x42, 0xFF };
|
||||
const uint8_t imgPositionSolid[] PROGMEM = { 0x20, 0x30, 0x38, 0x3C, 0x7E, 0xFF };
|
||||
|
||||
#include "icon.xbm"
|
||||
|
||||
// We now programmatically draw our compass
|
||||
|
||||
15
src/lock.cpp
15
src/lock.cpp
@@ -5,6 +5,7 @@
|
||||
namespace meshtastic
|
||||
{
|
||||
|
||||
#ifdef configUSE_PREEMPTION
|
||||
Lock::Lock()
|
||||
{
|
||||
handle = xSemaphoreCreateBinary();
|
||||
@@ -21,6 +22,20 @@ void Lock::unlock()
|
||||
{
|
||||
assert(xSemaphoreGive(handle));
|
||||
}
|
||||
#else
|
||||
Lock::Lock()
|
||||
{
|
||||
}
|
||||
|
||||
void Lock::lock()
|
||||
{
|
||||
}
|
||||
|
||||
void Lock::unlock()
|
||||
{
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
LockGuard::LockGuard(Lock *lock) : lock(lock)
|
||||
{
|
||||
|
||||
@@ -25,7 +25,9 @@ class Lock
|
||||
void unlock();
|
||||
|
||||
private:
|
||||
#ifdef configUSE_PREEMPTION
|
||||
SemaphoreHandle_t handle;
|
||||
#endif
|
||||
};
|
||||
|
||||
// RAII lock guard.
|
||||
|
||||
405
src/main.cpp
405
src/main.cpp
@@ -21,47 +21,54 @@
|
||||
|
||||
*/
|
||||
|
||||
#include "GPS.h"
|
||||
#include "MeshRadio.h"
|
||||
#include "MeshService.h"
|
||||
#include "NEMAGPS.h"
|
||||
#include "NodeDB.h"
|
||||
#include "Periodic.h"
|
||||
#include "PowerFSM.h"
|
||||
#include "UBloxGPS.h"
|
||||
#include "configuration.h"
|
||||
#include "error.h"
|
||||
#include "power.h"
|
||||
// #include "rom/rtc.h"
|
||||
#include "FloodingRouter.h"
|
||||
#include "DSRRouter.h"
|
||||
#include "debug.h"
|
||||
#include "main.h"
|
||||
#include "screen.h"
|
||||
#include "sleep.h"
|
||||
#include <OneButton.h>
|
||||
#include <Wire.h>
|
||||
// #include <driver/rtc_io.h>
|
||||
|
||||
#ifndef NO_ESP32
|
||||
#include "BluetoothUtil.h"
|
||||
#include "WiFi.h"
|
||||
#endif
|
||||
|
||||
#ifdef TBEAM_V10
|
||||
#include "axp20x.h"
|
||||
AXP20X_Class axp;
|
||||
bool pmu_irq = false;
|
||||
#include "RF95Interface.h"
|
||||
#include "SX1262Interface.h"
|
||||
|
||||
#ifdef NRF52_SERIES
|
||||
#include "variant.h"
|
||||
#endif
|
||||
|
||||
// Global Screen singleton
|
||||
#ifdef I2C_SDA
|
||||
meshtastic::Screen screen(SSD1306_ADDRESS, I2C_SDA, I2C_SCL);
|
||||
#else
|
||||
// Fake values for pins to keep build happy, we won't ever initialize it.
|
||||
meshtastic::Screen screen(SSD1306_ADDRESS, 0, 0);
|
||||
#endif
|
||||
// We always create a screen object, but we only init it if we find the hardware
|
||||
meshtastic::Screen screen(SSD1306_ADDRESS);
|
||||
|
||||
// Global power status singleton
|
||||
static meshtastic::PowerStatus powerStatus;
|
||||
// Global power status
|
||||
meshtastic::PowerStatus *powerStatus = new meshtastic::PowerStatus();
|
||||
|
||||
// Global GPS status
|
||||
meshtastic::GPSStatus *gpsStatus = new meshtastic::GPSStatus();
|
||||
|
||||
// Global Node status
|
||||
meshtastic::NodeStatus *nodeStatus = new meshtastic::NodeStatus();
|
||||
|
||||
bool ssd1306_found;
|
||||
bool axp192_found;
|
||||
|
||||
FloodingRouter realRouter;
|
||||
DSRRouter realRouter;
|
||||
Router &router = realRouter; // Users of router don't care what sort of subclass implements that API
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
@@ -84,7 +91,7 @@ void scanI2Cdevice(void)
|
||||
ssd1306_found = true;
|
||||
DEBUG_MSG("ssd1306 display found\n");
|
||||
}
|
||||
#ifdef TBEAM_V10
|
||||
#ifdef AXP192_SLAVE_ADDRESS
|
||||
if (addr == AXP192_SLAVE_ADDRESS) {
|
||||
axp192_found = true;
|
||||
DEBUG_MSG("axp192 PMU found\n");
|
||||
@@ -100,117 +107,6 @@ void scanI2Cdevice(void)
|
||||
DEBUG_MSG("done\n");
|
||||
}
|
||||
|
||||
#ifdef TBEAM_V10
|
||||
/// Reads power status to powerStatus singleton.
|
||||
//
|
||||
// TODO(girts): move this and other axp stuff to power.h/power.cpp.
|
||||
void readPowerStatus()
|
||||
{
|
||||
powerStatus.haveBattery = axp.isBatteryConnect();
|
||||
if (powerStatus.haveBattery) {
|
||||
powerStatus.batteryVoltageMv = axp.getBattVoltage();
|
||||
}
|
||||
powerStatus.usb = axp.isVBUSPlug();
|
||||
powerStatus.charging = axp.isChargeing();
|
||||
}
|
||||
#endif // TBEAM_V10
|
||||
|
||||
/**
|
||||
* Init the power manager chip
|
||||
*
|
||||
* axp192 power
|
||||
DCDC1 0.7-3.5V @ 1200mA max -> OLED // If you turn this off you'll lose comms to the axp192 because the OLED and the axp192
|
||||
share the same i2c bus, instead use ssd1306 sleep mode DCDC2 -> unused DCDC3 0.7-3.5V @ 700mA max -> ESP32 (keep this on!) LDO1
|
||||
30mA -> charges GPS backup battery // charges the tiny J13 battery by the GPS to power the GPS ram (for a couple of days), can
|
||||
not be turned off LDO2 200mA -> LORA LDO3 200mA -> GPS
|
||||
*/
|
||||
void axp192Init()
|
||||
{
|
||||
#ifdef TBEAM_V10
|
||||
if (axp192_found) {
|
||||
if (!axp.begin(Wire, AXP192_SLAVE_ADDRESS)) {
|
||||
DEBUG_MSG("AXP192 Begin PASS\n");
|
||||
|
||||
// axp.setChgLEDMode(LED_BLINK_4HZ);
|
||||
DEBUG_MSG("DCDC1: %s\n", axp.isDCDC1Enable() ? "ENABLE" : "DISABLE");
|
||||
DEBUG_MSG("DCDC2: %s\n", axp.isDCDC2Enable() ? "ENABLE" : "DISABLE");
|
||||
DEBUG_MSG("LDO2: %s\n", axp.isLDO2Enable() ? "ENABLE" : "DISABLE");
|
||||
DEBUG_MSG("LDO3: %s\n", axp.isLDO3Enable() ? "ENABLE" : "DISABLE");
|
||||
DEBUG_MSG("DCDC3: %s\n", axp.isDCDC3Enable() ? "ENABLE" : "DISABLE");
|
||||
DEBUG_MSG("Exten: %s\n", axp.isExtenEnable() ? "ENABLE" : "DISABLE");
|
||||
DEBUG_MSG("----------------------------------------\n");
|
||||
|
||||
axp.setPowerOutPut(AXP192_LDO2, AXP202_ON); // LORA radio
|
||||
axp.setPowerOutPut(AXP192_LDO3, AXP202_ON); // GPS main power
|
||||
axp.setPowerOutPut(AXP192_DCDC2, AXP202_ON);
|
||||
axp.setPowerOutPut(AXP192_EXTEN, AXP202_ON);
|
||||
axp.setPowerOutPut(AXP192_DCDC1, AXP202_ON);
|
||||
axp.setDCDC1Voltage(3300); // for the OLED power
|
||||
|
||||
DEBUG_MSG("DCDC1: %s\n", axp.isDCDC1Enable() ? "ENABLE" : "DISABLE");
|
||||
DEBUG_MSG("DCDC2: %s\n", axp.isDCDC2Enable() ? "ENABLE" : "DISABLE");
|
||||
DEBUG_MSG("LDO2: %s\n", axp.isLDO2Enable() ? "ENABLE" : "DISABLE");
|
||||
DEBUG_MSG("LDO3: %s\n", axp.isLDO3Enable() ? "ENABLE" : "DISABLE");
|
||||
DEBUG_MSG("DCDC3: %s\n", axp.isDCDC3Enable() ? "ENABLE" : "DISABLE");
|
||||
DEBUG_MSG("Exten: %s\n", axp.isExtenEnable() ? "ENABLE" : "DISABLE");
|
||||
|
||||
#if 0
|
||||
// cribbing from https://github.com/m5stack/M5StickC/blob/master/src/AXP192.cpp to fix charger to be more like 300ms.
|
||||
// I finally found an english datasheet. Will look at this later - but suffice it to say the default code from TTGO has 'issues'
|
||||
|
||||
axp.adc1Enable(0xff, 1); // turn on all adcs
|
||||
uint8_t val = 0xc2;
|
||||
axp._writeByte(0x33, 1, &val); // Bat charge voltage to 4.2, Current 280mA
|
||||
val = 0b11110010;
|
||||
// Set ADC sample rate to 200hz
|
||||
// axp._writeByte(0x84, 1, &val);
|
||||
|
||||
// Not connected
|
||||
//val = 0xfc;
|
||||
//axp._writeByte(AXP202_VHTF_CHGSET, 1, &val); // Set temperature protection
|
||||
|
||||
//not used
|
||||
//val = 0x46;
|
||||
//axp._writeByte(AXP202_OFF_CTL, 1, &val); // enable bat detection
|
||||
#endif
|
||||
axp.debugCharging();
|
||||
|
||||
#ifdef PMU_IRQ
|
||||
pinMode(PMU_IRQ, INPUT);
|
||||
attachInterrupt(
|
||||
PMU_IRQ, [] { pmu_irq = true; }, FALLING);
|
||||
|
||||
axp.adc1Enable(AXP202_BATT_CUR_ADC1, 1);
|
||||
axp.enableIRQ(AXP202_BATT_REMOVED_IRQ | AXP202_BATT_CONNECT_IRQ | AXP202_CHARGING_FINISHED_IRQ | AXP202_CHARGING_IRQ |
|
||||
AXP202_VBUS_REMOVED_IRQ | AXP202_VBUS_CONNECT_IRQ | AXP202_PEK_SHORTPRESS_IRQ,
|
||||
1);
|
||||
|
||||
axp.clearIRQ();
|
||||
#endif
|
||||
readPowerStatus();
|
||||
} else {
|
||||
DEBUG_MSG("AXP192 Begin FAIL\n");
|
||||
}
|
||||
} else {
|
||||
DEBUG_MSG("AXP192 not found\n");
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void getMacAddr(uint8_t *dmac)
|
||||
{
|
||||
#ifndef NO_ESP32
|
||||
assert(esp_efuse_mac_get_default(dmac) == ESP_OK);
|
||||
#else
|
||||
dmac[0] = 0xde;
|
||||
dmac[1] = 0xad;
|
||||
dmac[2] = 0xbe;
|
||||
dmac[3] = 0xef;
|
||||
dmac[4] = 0x01;
|
||||
dmac[5] = 0x02; // FIXME, macaddr stuff needed for NRF52
|
||||
#endif
|
||||
}
|
||||
|
||||
const char *getDeviceName()
|
||||
{
|
||||
uint8_t dmac[6];
|
||||
@@ -223,15 +119,67 @@ const char *getDeviceName()
|
||||
return name;
|
||||
}
|
||||
|
||||
static MeshRadio *radio = NULL;
|
||||
static uint32_t ledBlinker()
|
||||
{
|
||||
static bool ledOn;
|
||||
ledOn ^= 1;
|
||||
|
||||
#include "Router.h"
|
||||
setLed(ledOn);
|
||||
|
||||
// have a very sparse duty cycle of LED being on, unless charging, then blink 0.5Hz square wave rate to indicate that
|
||||
return powerStatus->getIsCharging() ? 1000 : (ledOn ? 2 : 1000);
|
||||
}
|
||||
|
||||
Periodic ledPeriodic(ledBlinker);
|
||||
|
||||
// Prepare for button presses
|
||||
#ifdef BUTTON_PIN
|
||||
OneButton userButton;
|
||||
#endif
|
||||
#ifdef BUTTON_PIN_ALT
|
||||
OneButton userButtonAlt;
|
||||
#endif
|
||||
void userButtonPressed()
|
||||
{
|
||||
powerFSM.trigger(EVENT_PRESS);
|
||||
}
|
||||
void userButtonPressedLong()
|
||||
{
|
||||
screen.adjustBrightness();
|
||||
}
|
||||
|
||||
#ifndef NO_ESP32
|
||||
void initWifi()
|
||||
{
|
||||
strcpy(radioConfig.preferences.wifi_ssid, "geeksville");
|
||||
strcpy(radioConfig.preferences.wifi_password, "xxx");
|
||||
if (radioConfig.has_preferences) {
|
||||
const char *wifiName = radioConfig.preferences.wifi_ssid;
|
||||
|
||||
if (*wifiName) {
|
||||
const char *wifiPsw = radioConfig.preferences.wifi_password;
|
||||
if (radioConfig.preferences.wifi_ap_mode) {
|
||||
// DEBUG_MSG("STARTING WIFI AP: ssid=%s, ok=%d\n", wifiName, WiFi.softAP(wifiName, wifiPsw));
|
||||
} else {
|
||||
// WiFi.mode(WIFI_MODE_STA);
|
||||
DEBUG_MSG("JOINING WIFI: ssid=%s\n", wifiName);
|
||||
// WiFi.begin(wifiName, wifiPsw);
|
||||
}
|
||||
}
|
||||
} else
|
||||
DEBUG_MSG("Not using WIFI\n");
|
||||
}
|
||||
#endif
|
||||
|
||||
void setup()
|
||||
{
|
||||
#ifdef USE_SEGGER
|
||||
SEGGER_RTT_ConfigUpBuffer(0, NULL, NULL, 0, SEGGER_RTT_MODE_NO_BLOCK_TRIM);
|
||||
#endif
|
||||
|
||||
// Debug
|
||||
#ifdef DEBUG_PORT
|
||||
DEBUG_PORT.begin(SERIAL_BAUD);
|
||||
DEBUG_PORT.init(); // Set serial baud rate and init our mesh console
|
||||
#endif
|
||||
|
||||
initDeepSleep();
|
||||
@@ -248,49 +196,118 @@ void setup()
|
||||
|
||||
#ifdef I2C_SDA
|
||||
Wire.begin(I2C_SDA, I2C_SCL);
|
||||
#else
|
||||
Wire.begin();
|
||||
#endif
|
||||
// i2c still busted on new board
|
||||
#ifndef ARDUINO_NRF52840_PPR
|
||||
scanI2Cdevice();
|
||||
#endif
|
||||
|
||||
// Buttons & LED
|
||||
#ifdef BUTTON_PIN
|
||||
pinMode(BUTTON_PIN, INPUT_PULLUP);
|
||||
digitalWrite(BUTTON_PIN, 1);
|
||||
userButton = OneButton(BUTTON_PIN, true, true);
|
||||
userButton.attachClick(userButtonPressed);
|
||||
userButton.attachDuringLongPress(userButtonPressedLong);
|
||||
#endif
|
||||
#ifdef BUTTON_PIN_ALT
|
||||
userButtonAlt = OneButton(BUTTON_PIN_ALT, true, true);
|
||||
userButtonAlt.attachClick(userButtonPressed);
|
||||
userButton.attachDuringLongPress(userButtonPressedLong);
|
||||
#endif
|
||||
#ifdef LED_PIN
|
||||
pinMode(LED_PIN, OUTPUT);
|
||||
digitalWrite(LED_PIN, 1 ^ LED_INVERTED); // turn on for now
|
||||
#endif
|
||||
|
||||
ledPeriodic.setup();
|
||||
|
||||
// Hello
|
||||
DEBUG_MSG("Meshtastic swver=%s, hwver=%s\n", xstr(APP_VERSION), xstr(HW_VERSION));
|
||||
DEBUG_MSG("Meshtastic swver=%s, hwver=%s\n", optstr(APP_VERSION), optstr(HW_VERSION));
|
||||
|
||||
#ifndef NO_ESP32
|
||||
// Don't init display if we don't have one or we are waking headless due to a timer event
|
||||
if (wakeCause == ESP_SLEEP_WAKEUP_TIMER)
|
||||
ssd1306_found = false; // forget we even have the hardware
|
||||
|
||||
esp32Setup();
|
||||
#endif
|
||||
|
||||
#ifdef TBEAM_V10
|
||||
// Currently only the tbeam has a PMU
|
||||
power = new Power();
|
||||
power->setup();
|
||||
power->setStatusHandler(powerStatus);
|
||||
powerStatus->observe(&power->newStatus);
|
||||
#endif
|
||||
|
||||
#ifdef NRF52_SERIES
|
||||
nrf52Setup();
|
||||
#endif
|
||||
|
||||
// Initialize the screen first so we can show the logo while we start up everything else.
|
||||
if (ssd1306_found)
|
||||
screen.setup();
|
||||
|
||||
axp192Init();
|
||||
|
||||
screen.print("Started...\n");
|
||||
|
||||
// Init GPS
|
||||
gps.setup();
|
||||
readFromRTC(); // read the main CPU RTC at first (in case we can't get GPS time)
|
||||
|
||||
// If we know we have a L80 GPS, don't try UBLOX
|
||||
#ifndef L80_RESET
|
||||
// Init GPS - first try ublox
|
||||
gps = new UBloxGPS();
|
||||
if (!gps->setup()) {
|
||||
// Some boards might have only the TX line from the GPS connected, in that case, we can't configure it at all. Just
|
||||
// assume NEMA at 9600 baud.
|
||||
DEBUG_MSG("ERROR: No UBLOX GPS found, hoping that NEMA might work\n");
|
||||
delete gps;
|
||||
gps = new NEMAGPS();
|
||||
gps->setup();
|
||||
}
|
||||
#else
|
||||
gps = new NEMAGPS();
|
||||
gps->setup();
|
||||
#endif
|
||||
gpsStatus->observe(&gps->newStatus);
|
||||
nodeStatus->observe(&nodeDB.newStatus);
|
||||
|
||||
service.init();
|
||||
|
||||
#ifndef NO_ESP32
|
||||
// MUST BE AFTER service.init, so we have our radio config settings (from nodedb init)
|
||||
radio = new MeshRadio();
|
||||
router.addInterface(&radio->radioIf);
|
||||
// Must be after we init the service, because the wifi settings are loaded by NodeDB (oops)
|
||||
initWifi();
|
||||
#endif
|
||||
|
||||
if (radio && !radio->init())
|
||||
#ifdef SX1262_ANT_SW
|
||||
// make analog PA vs not PA switch on SX1262 eval board work properly
|
||||
pinMode(SX1262_ANT_SW, OUTPUT);
|
||||
digitalWrite(SX1262_ANT_SW, 1);
|
||||
#endif
|
||||
|
||||
// Init our SPI controller
|
||||
#ifdef NRF52_SERIES
|
||||
SPI.begin();
|
||||
#else
|
||||
// ESP32
|
||||
SPI.begin(SCK_GPIO, MISO_GPIO, MOSI_GPIO, NSS_GPIO);
|
||||
SPI.setFrequency(4000000);
|
||||
#endif
|
||||
|
||||
// MUST BE AFTER service.init, so we have our radio config settings (from nodedb init)
|
||||
RadioInterface *rIf =
|
||||
#if defined(RF95_IRQ_GPIO)
|
||||
// new CustomRF95(); old Radiohead based driver
|
||||
new RF95Interface(NSS_GPIO, RF95_IRQ_GPIO, RESET_GPIO, SPI);
|
||||
#elif defined(SX1262_CS)
|
||||
new SX1262Interface(SX1262_CS, SX1262_DIO1, SX1262_RESET, SX1262_BUSY, SPI);
|
||||
#else
|
||||
new SimRadio();
|
||||
#endif
|
||||
|
||||
if (!rIf || !rIf->init())
|
||||
recordCriticalError(ErrNoRadio);
|
||||
else
|
||||
router.addInterface(rIf);
|
||||
|
||||
// This must be _after_ service.init because we need our preferences loaded from flash to have proper timeout values
|
||||
PowerFSM_setup(); // we will transition to ON in a couple of seconds, FIXME, only do this for cold boots, not waking from SDS
|
||||
@@ -299,19 +316,6 @@ void setup()
|
||||
setCPUFast(false); // 80MHz is fine for our slow peripherals
|
||||
}
|
||||
|
||||
uint32_t ledBlinker()
|
||||
{
|
||||
static bool ledOn;
|
||||
ledOn ^= 1;
|
||||
|
||||
setLed(ledOn);
|
||||
|
||||
// have a very sparse duty cycle of LED being on, unless charging, then blink 0.5Hz square wave rate to indicate that
|
||||
return powerStatus.charging ? 1000 : (ledOn ? 2 : 1000);
|
||||
}
|
||||
|
||||
Periodic ledPeriodic(ledBlinker);
|
||||
|
||||
#if 0
|
||||
// Turn off for now
|
||||
|
||||
@@ -330,80 +334,39 @@ uint32_t axpDebugRead()
|
||||
}
|
||||
|
||||
Periodic axpDebugOutput(axpDebugRead);
|
||||
axpDebugOutput.setup();
|
||||
#endif
|
||||
|
||||
void loop()
|
||||
{
|
||||
uint32_t msecstosleep = 1000 * 30; // How long can we sleep before we again need to service the main loop?
|
||||
|
||||
powerFSM.run_machine();
|
||||
gps.loop();
|
||||
gps->loop(); // FIXME, remove from main, instead block on read
|
||||
router.loop();
|
||||
powerFSM.run_machine();
|
||||
service.loop();
|
||||
|
||||
ledPeriodic.loop();
|
||||
periodicScheduler.loop();
|
||||
// axpDebugOutput.loop();
|
||||
|
||||
#ifndef NO_ESP32
|
||||
loopBLE();
|
||||
#ifdef DEBUG_PORT
|
||||
DEBUG_PORT.loop(); // Send/receive protobufs over the serial port
|
||||
#endif
|
||||
|
||||
// for debug printing
|
||||
// radio.radioIf.canSleep();
|
||||
// heap_caps_check_integrity_all(true); // FIXME - disable this expensive check
|
||||
|
||||
#ifdef PMU_IRQ
|
||||
if (pmu_irq) {
|
||||
pmu_irq = false;
|
||||
axp.readIRQ();
|
||||
|
||||
DEBUG_MSG("pmu irq!\n");
|
||||
|
||||
if (axp.isChargingIRQ()) {
|
||||
DEBUG_MSG("Battery start charging\n");
|
||||
}
|
||||
if (axp.isChargingDoneIRQ()) {
|
||||
DEBUG_MSG("Battery fully charged\n");
|
||||
}
|
||||
if (axp.isVbusRemoveIRQ()) {
|
||||
DEBUG_MSG("USB unplugged\n");
|
||||
}
|
||||
if (axp.isVbusPlugInIRQ()) {
|
||||
DEBUG_MSG("USB plugged In\n");
|
||||
}
|
||||
if (axp.isBattPlugInIRQ()) {
|
||||
DEBUG_MSG("Battery inserted\n");
|
||||
}
|
||||
if (axp.isBattRemoveIRQ()) {
|
||||
DEBUG_MSG("Battery removed\n");
|
||||
}
|
||||
if (axp.isPEKShortPressIRQ()) {
|
||||
DEBUG_MSG("PEK short button press\n");
|
||||
}
|
||||
|
||||
readPowerStatus();
|
||||
axp.clearIRQ();
|
||||
}
|
||||
#endif // T_BEAM_V10
|
||||
#ifndef NO_ESP32
|
||||
esp32Loop();
|
||||
#endif
|
||||
#ifdef TBEAM_V10
|
||||
power->loop();
|
||||
#endif
|
||||
|
||||
#ifdef BUTTON_PIN
|
||||
// if user presses button for more than 3 secs, discard our network prefs and reboot (FIXME, use a debounce lib instead of
|
||||
// this boilerplate)
|
||||
static bool wasPressed = false;
|
||||
|
||||
if (!digitalRead(BUTTON_PIN)) {
|
||||
if (!wasPressed) { // just started a new press
|
||||
DEBUG_MSG("pressing\n");
|
||||
|
||||
// doLightSleep();
|
||||
// esp_pm_dump_locks(stdout); // FIXME, do this someplace better
|
||||
wasPressed = true;
|
||||
|
||||
powerFSM.trigger(EVENT_PRESS);
|
||||
}
|
||||
} else if (wasPressed) {
|
||||
// we just did a release
|
||||
wasPressed = false;
|
||||
}
|
||||
userButton.tick();
|
||||
#endif
|
||||
#ifdef BUTTON_PIN_ALT
|
||||
userButtonAlt.tick();
|
||||
#endif
|
||||
|
||||
// Show boot screen for first 3 seconds, then switch to normal operation.
|
||||
@@ -413,13 +376,17 @@ void loop()
|
||||
showingBootScreen = false;
|
||||
}
|
||||
|
||||
#ifdef DEBUG_STACK
|
||||
static uint32_t lastPrint = 0;
|
||||
if (millis() - lastPrint > 10 * 1000L) {
|
||||
lastPrint = millis();
|
||||
meshtastic::printThreadInfo("main");
|
||||
}
|
||||
#endif
|
||||
|
||||
// Update the screen last, after we've figured out what to show.
|
||||
screen.debug()->setNodeNumbersStatus(nodeDB.getNumOnlineNodes(), nodeDB.getNumNodes());
|
||||
screen.debug()->setChannelNameStatus(channelSettings.name);
|
||||
screen.debug()->setPowerStatus(powerStatus);
|
||||
// TODO(#4): use something based on hdop to show GPS "signal" strength.
|
||||
screen.debug()->setGPSStatus(gps.hasLock() ? "ok" : ":(");
|
||||
screen.loop();
|
||||
// screen.debug()->setPowerStatus(powerStatus);
|
||||
|
||||
// No GPS lock yet, let the OS put the main CPU in low power mode for 100ms (or until another interrupt comes in)
|
||||
// i.e. don't just keep spinning in loop as fast as we can.
|
||||
|
||||
12
src/main.h
12
src/main.h
@@ -1,6 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#include "screen.h"
|
||||
#include "PowerStatus.h"
|
||||
#include "GPSStatus.h"
|
||||
#include "NodeStatus.h"
|
||||
|
||||
extern bool axp192_found;
|
||||
extern bool ssd1306_found;
|
||||
@@ -9,6 +12,15 @@ extern bool isUSBPowered;
|
||||
|
||||
// Global Screen singleton.
|
||||
extern meshtastic::Screen screen;
|
||||
//extern Observable<meshtastic::PowerStatus> newPowerStatus; //TODO: move this to main-esp32.cpp somehow or a helper class
|
||||
|
||||
//extern meshtastic::PowerStatus *powerStatus;
|
||||
//extern meshtastic::GPSStatus *gpsStatus;
|
||||
//extern meshtastic::NodeStatusHandler *nodeStatusHandler;
|
||||
|
||||
// Return a human readable string of the form "Meshtastic_ab13"
|
||||
const char *getDeviceName();
|
||||
|
||||
void getMacAddr(uint8_t *dmac);
|
||||
|
||||
void nrf52Setup(), esp32Setup(), nrf52Loop(), esp32Loop();
|
||||
32
src/mesh/CryptoEngine.cpp
Normal file
32
src/mesh/CryptoEngine.cpp
Normal file
@@ -0,0 +1,32 @@
|
||||
#include "CryptoEngine.h"
|
||||
#include "configuration.h"
|
||||
|
||||
void CryptoEngine::setKey(size_t numBytes, uint8_t *bytes)
|
||||
{
|
||||
DEBUG_MSG("WARNING: Using stub crypto - all crypto is sent in plaintext!\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Encrypt a packet
|
||||
*
|
||||
* @param bytes is updated in place
|
||||
*/
|
||||
void CryptoEngine::encrypt(uint32_t fromNode, uint64_t packetNum, size_t numBytes, uint8_t *bytes)
|
||||
{
|
||||
DEBUG_MSG("WARNING: noop encryption!\n");
|
||||
}
|
||||
|
||||
void CryptoEngine::decrypt(uint32_t fromNode, uint64_t packetNum, size_t numBytes, uint8_t *bytes)
|
||||
{
|
||||
DEBUG_MSG("WARNING: noop decryption!\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Init our 128 bit nonce for a new packet
|
||||
*/
|
||||
void CryptoEngine::initNonce(uint32_t fromNode, uint64_t packetNum)
|
||||
{
|
||||
memset(nonce, 0, sizeof(nonce));
|
||||
*((uint64_t *)&nonce[0]) = packetNum;
|
||||
*((uint32_t *)&nonce[8]) = fromNode;
|
||||
}
|
||||
52
src/mesh/CryptoEngine.h
Normal file
52
src/mesh/CryptoEngine.h
Normal file
@@ -0,0 +1,52 @@
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
/**
|
||||
* see docs/software/crypto.md for details.
|
||||
*
|
||||
*/
|
||||
|
||||
#define MAX_BLOCKSIZE 256
|
||||
|
||||
class CryptoEngine
|
||||
{
|
||||
protected:
|
||||
/** Our per packet nonce */
|
||||
uint8_t nonce[16];
|
||||
|
||||
public:
|
||||
virtual ~CryptoEngine() {}
|
||||
|
||||
/**
|
||||
* Set the key used for encrypt, decrypt.
|
||||
*
|
||||
* As a special case: If all bytes are zero, we assume _no encryption_ and send all data in cleartext.
|
||||
*
|
||||
* @param numBytes must be 16 (AES128), 32 (AES256) or 0 (no crypt)
|
||||
* @param bytes a _static_ buffer that will remain valid for the life of this crypto instance (i.e. this class will cache the
|
||||
* provided pointer)
|
||||
*/
|
||||
virtual void setKey(size_t numBytes, uint8_t *bytes);
|
||||
|
||||
/**
|
||||
* Encrypt a packet
|
||||
*
|
||||
* @param bytes is updated in place
|
||||
*/
|
||||
virtual void encrypt(uint32_t fromNode, uint64_t packetNum, size_t numBytes, uint8_t *bytes);
|
||||
virtual void decrypt(uint32_t fromNode, uint64_t packetNum, size_t numBytes, uint8_t *bytes);
|
||||
|
||||
protected:
|
||||
/**
|
||||
* Init our 128 bit nonce for a new packet
|
||||
*
|
||||
* The NONCE is constructed by concatenating (from MSB to LSB):
|
||||
* a 64 bit packet number (stored in little endian order)
|
||||
* a 32 bit sending node number (stored in little endian order)
|
||||
* a 32 bit block counter (starts at zero)
|
||||
*/
|
||||
void initNonce(uint32_t fromNode, uint64_t packetNum);
|
||||
};
|
||||
|
||||
extern CryptoEngine *crypto;
|
||||
245
src/mesh/DSRRouter.cpp
Normal file
245
src/mesh/DSRRouter.cpp
Normal file
@@ -0,0 +1,245 @@
|
||||
#include "DSRRouter.h"
|
||||
#include "configuration.h"
|
||||
|
||||
/* when we receive any packet
|
||||
|
||||
- sniff and update tables (especially useful to find adjacent nodes). Update user, network and position info.
|
||||
- if we need to route() that packet, resend it to the next_hop based on our nodedb.
|
||||
- if it is broadcast or destined for our node, deliver locally
|
||||
- handle routereply/routeerror/routediscovery messages as described below
|
||||
- then free it
|
||||
|
||||
routeDiscovery
|
||||
|
||||
- if we've already passed through us (or is from us), then it ignore it
|
||||
- use the nodes already mentioned in the request to update our routing table
|
||||
- if they were looking for us, send back a routereply
|
||||
- if max_hops is zero and they weren't looking for us, drop (FIXME, send back error - I think not though?)
|
||||
- if we receive a discovery packet, we use it to populate next_hop (if needed) towards the requester (after decrementing max_hops)
|
||||
- if we receive a discovery packet, and we have a next_hop in our nodedb for that destination we send a (reliable) we send a route
|
||||
reply towards the requester
|
||||
|
||||
when sending any reliable packet
|
||||
|
||||
- if timeout doing retries, send a routeError (nak) message back towards the original requester. all nodes eavesdrop on that
|
||||
packet and update their route caches.
|
||||
|
||||
when we receive a routereply packet
|
||||
|
||||
- update next_hop on the node, if the new reply needs fewer hops than the existing one (we prefer shorter paths). fixme, someday
|
||||
use a better heuristic
|
||||
|
||||
when we receive a routeError packet
|
||||
|
||||
- delete the route for that failed recipient, restartRouteDiscovery()
|
||||
- if we receive routeerror in response to a discovery,
|
||||
- fixme, eventually keep caches of possible other routes.
|
||||
*/
|
||||
|
||||
ErrorCode DSRRouter::send(MeshPacket *p)
|
||||
{
|
||||
// We only consider multihop routing packets (i.e. those with dest set)
|
||||
if (p->decoded.dest) {
|
||||
// add an entry for this pending message
|
||||
auto pending = startRetransmission(p);
|
||||
// FIXME - when acks come in for this packet, we should _not_ delete the record unless the ack was from
|
||||
// the final dest. We need to keep that record around until FIXME
|
||||
// Also we should not retransmit multihop entries in that table at all
|
||||
|
||||
// If we have an entry in our routing tables, just send it, otherwise start a route discovery
|
||||
NodeNum nextHop = getNextHop(p->decoded.dest);
|
||||
if (nextHop) {
|
||||
sendNextHop(nextHop, p); // start a reliable single hop send
|
||||
} else {
|
||||
pending->wantRoute = true;
|
||||
|
||||
// start discovery, but only if we don't already a discovery in progress for that node number
|
||||
startDiscovery(p->decoded.dest);
|
||||
}
|
||||
|
||||
return ERRNO_OK;
|
||||
} else
|
||||
return ReliableRouter::send(p);
|
||||
}
|
||||
|
||||
void DSRRouter::sniffReceived(const MeshPacket *p)
|
||||
{
|
||||
// Learn 0 hop routes by just hearing any adjacent nodes
|
||||
// But treat broadcasts carefully, because when flood broadcasts go out they keep the same original "from". So we want to
|
||||
// ignore rebroadcasts.
|
||||
// this will also add records for any ACKs we receive for our messages
|
||||
if (p->to != NODENUM_BROADCAST || p->hop_limit != HOP_RELIABLE) {
|
||||
addRoute(p->from, p->from, 0); // We are adjacent with zero hops
|
||||
}
|
||||
|
||||
switch (p->decoded.which_payload) {
|
||||
case SubPacket_route_request_tag:
|
||||
// Handle route discovery packets (will be a broadcast message)
|
||||
// FIXME - always start request with the senders nodenum
|
||||
if (weAreInRoute(p->decoded.route_request)) {
|
||||
DEBUG_MSG("Ignoring a route request that contains us\n");
|
||||
} else {
|
||||
updateRoutes(p->decoded.route_request,
|
||||
true); // Update our routing tables based on the route that came in so far on this request
|
||||
|
||||
if (p->decoded.dest == getNodeNum()) {
|
||||
// They were looking for us, send back a route reply (the sender address will be first in the list)
|
||||
sendRouteReply(p->decoded.route_request);
|
||||
} else {
|
||||
// They were looking for someone else, forward it along (as a zero hop broadcast)
|
||||
NodeNum nextHop = getNextHop(p->decoded.dest);
|
||||
if (nextHop) {
|
||||
// in our route cache, reply to the requester (the sender address will be first in the list)
|
||||
sendRouteReply(p->decoded.route_request, nextHop);
|
||||
} else {
|
||||
// Not in our route cache, rebroadcast on their behalf (after adding ourselves to the request route)
|
||||
resendRouteRequest(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
case SubPacket_route_reply_tag:
|
||||
updateRoutes(p->decoded.route_reply, false);
|
||||
|
||||
// FIXME, if any of our current pending packets were waiting for this route, send them (and leave them as regular pending
|
||||
// packets until ack arrives)
|
||||
// FIXME, if we don't get a route reply at all (or a route error), timeout and generate a routeerror TIMEOUT on our own...
|
||||
break;
|
||||
case SubPacket_route_error_tag:
|
||||
removeRoute(p->decoded.dest);
|
||||
|
||||
// FIXME: if any pending packets were waiting on this route, delete them
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
// We simply ignore ACKs - because ReliableRouter will delete the pending packet for us
|
||||
|
||||
// Handle regular packets
|
||||
if (p->to == getNodeNum()) { // Destined for us (at least for this hop)
|
||||
|
||||
// We need to route this packet to some other node
|
||||
if (p->decoded.dest && p->decoded.dest != p->to) {
|
||||
// if we have a route out, resend the packet to the next hop, otherwise return RouteError no-route available
|
||||
|
||||
NodeNum nextHop = getNextHop(p->decoded.dest);
|
||||
if (nextHop) {
|
||||
sendNextHop(nextHop, p); // start a reliable single hop send
|
||||
} else {
|
||||
// We don't have a route out
|
||||
assert(p->decoded.source); // I think this is guaranteed by now
|
||||
|
||||
// FIXME - what if the current packet _is_ a route error packet?
|
||||
sendRouteError(p, RouteError_NO_ROUTE);
|
||||
}
|
||||
|
||||
// FIXME, stop local processing of this packet
|
||||
}
|
||||
|
||||
// handle naks - convert them to route error packets
|
||||
// All naks are generated locally, because we failed resending the packet too many times
|
||||
PacketId nakId = p->decoded.which_ack == SubPacket_fail_id_tag ? p->decoded.ack.fail_id : 0;
|
||||
if (nakId) {
|
||||
auto pending = findPendingPacket(p->to, nakId);
|
||||
if (pending && pending->packet->decoded.source) { // if source not set, this was not a multihop packet, just ignore
|
||||
removeRoute(pending->packet->decoded.dest); // We no longer have a route to the specified node
|
||||
|
||||
sendRouteError(p, RouteError_GOT_NAK);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ReliableRouter::sniffReceived(p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Does our node appear in the specified route
|
||||
*/
|
||||
bool DSRRouter::weAreInRoute(const RouteDiscovery &route)
|
||||
{
|
||||
return true; // FIXME
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a DSR route, use that route to update our DB of possible routes
|
||||
*
|
||||
* Note: routes are always listed in the same order - from sender to receipient (i.e. route_replies also use this some order)
|
||||
*
|
||||
* @param isRequest is true if we are looking at a route request, else we are looking at a reply
|
||||
**/
|
||||
void DSRRouter::updateRoutes(const RouteDiscovery &route, bool isRequest)
|
||||
{
|
||||
DEBUG_MSG("FIXME not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* send back a route reply (the sender address will be first in the list)
|
||||
*/
|
||||
void DSRRouter::sendRouteReply(const RouteDiscovery &route, NodeNum toAppend)
|
||||
{
|
||||
DEBUG_MSG("FIXME not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a nodenum return the next node we should forward to if we want to reach that node.
|
||||
*
|
||||
* @return 0 if no route found
|
||||
*/
|
||||
NodeNum DSRRouter::getNextHop(NodeNum dest)
|
||||
{
|
||||
DEBUG_MSG("FIXME not implemented");
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Not in our route cache, rebroadcast on their behalf (after adding ourselves to the request route)
|
||||
*
|
||||
* We will bump down hop_limit in this call.
|
||||
*/
|
||||
void DSRRouter::resendRouteRequest(const MeshPacket *p)
|
||||
{
|
||||
DEBUG_MSG("FIXME not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* Record that forwarder can reach dest for us, but they will need numHops to get there.
|
||||
* If our routing tables already have something that can reach that node in fewer hops we will keep the existing route
|
||||
* instead.
|
||||
*/
|
||||
void DSRRouter::addRoute(NodeNum dest, NodeNum forwarder, uint8_t numHops)
|
||||
{
|
||||
DEBUG_MSG("FIXME not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* Record that we no longer have a route to the dest
|
||||
*/
|
||||
void DSRRouter::removeRoute(NodeNum dest)
|
||||
{
|
||||
DEBUG_MSG("FIXME not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* Forward the specified packet to the specified node
|
||||
*/
|
||||
void DSRRouter::sendNextHop(NodeNum n, const MeshPacket *p)
|
||||
{
|
||||
DEBUG_MSG("FIXME not implemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a route error packet towards whoever originally sent this message
|
||||
*/
|
||||
void DSRRouter::sendRouteError(const MeshPacket *p, RouteError err)
|
||||
{
|
||||
DEBUG_MSG("FIXME not implemented");
|
||||
}
|
||||
|
||||
/** make a copy of p, start discovery, but only if we don't
|
||||
* already a discovery in progress for that node number. Caller has already scheduled this message for retransmission
|
||||
* when the discovery is complete.
|
||||
*/
|
||||
void DSRRouter::startDiscovery(NodeNum dest)
|
||||
{
|
||||
DEBUG_MSG("FIXME not implemented");
|
||||
}
|
||||
80
src/mesh/DSRRouter.h
Normal file
80
src/mesh/DSRRouter.h
Normal file
@@ -0,0 +1,80 @@
|
||||
#include "ReliableRouter.h"
|
||||
|
||||
class DSRRouter : public ReliableRouter
|
||||
{
|
||||
|
||||
protected:
|
||||
/**
|
||||
* Every (non duplicate) packet this node receives will be passed through this method. This allows subclasses to
|
||||
* update routing tables etc... based on what we overhear (even for messages not destined to our node)
|
||||
*/
|
||||
virtual void sniffReceived(const MeshPacket *p);
|
||||
|
||||
/**
|
||||
* Send a packet on a suitable interface. This routine will
|
||||
* later free() the packet to pool. This routine is not allowed to stall.
|
||||
* If the txmit queue is full it might return an error
|
||||
*/
|
||||
virtual ErrorCode send(MeshPacket *p);
|
||||
|
||||
private:
|
||||
/**
|
||||
* Does our node appear in the specified route
|
||||
*/
|
||||
bool weAreInRoute(const RouteDiscovery &route);
|
||||
|
||||
/**
|
||||
* Given a DSR route, use that route to update our DB of possible routes
|
||||
*
|
||||
* Note: routes are always listed in the same order - from sender to receipient (i.e. route_replies also use this some order)
|
||||
*
|
||||
* @param isRequest is true if we are looking at a route request, else we are looking at a reply
|
||||
**/
|
||||
void updateRoutes(const RouteDiscovery &route, bool isRequest);
|
||||
|
||||
/**
|
||||
* send back a route reply (the sender address will be first in the list)
|
||||
*/
|
||||
void sendRouteReply(const RouteDiscovery &route, NodeNum toAppend = 0);
|
||||
|
||||
/**
|
||||
* Given a nodenum return the next node we should forward to if we want to reach that node.
|
||||
*
|
||||
* @return 0 if no route found
|
||||
*/
|
||||
NodeNum getNextHop(NodeNum dest);
|
||||
|
||||
/** Not in our route cache, rebroadcast on their behalf (after adding ourselves to the request route)
|
||||
*
|
||||
* We will bump down hop_limit in this call.
|
||||
*/
|
||||
void resendRouteRequest(const MeshPacket *p);
|
||||
|
||||
/**
|
||||
* Record that forwarder can reach dest for us, but they will need numHops to get there.
|
||||
* If our routing tables already have something that can reach that node in fewer hops we will keep the existing route
|
||||
* instead.
|
||||
*/
|
||||
void addRoute(NodeNum dest, NodeNum forwarder, uint8_t numHops);
|
||||
|
||||
/**
|
||||
* Record that we no longer have a route to the dest
|
||||
*/
|
||||
void removeRoute(NodeNum dest);
|
||||
|
||||
/**
|
||||
* Forward the specified packet to the specified node
|
||||
*/
|
||||
void sendNextHop(NodeNum n, const MeshPacket *p);
|
||||
|
||||
/**
|
||||
* Send a route error packet towards whoever originally sent this message
|
||||
*/
|
||||
void sendRouteError(const MeshPacket *p, RouteError err);
|
||||
|
||||
/** make a copy of p, start discovery, but only if we don't
|
||||
* already a discovery in progress for that node number. Caller has already scheduled this message for retransmission
|
||||
* when the discovery is complete.
|
||||
*/
|
||||
void startDiscovery(NodeNum dest);
|
||||
};
|
||||
54
src/mesh/FloodingRouter.cpp
Normal file
54
src/mesh/FloodingRouter.cpp
Normal file
@@ -0,0 +1,54 @@
|
||||
#include "FloodingRouter.h"
|
||||
#include "configuration.h"
|
||||
#include "mesh-pb-constants.h"
|
||||
|
||||
FloodingRouter::FloodingRouter() {}
|
||||
|
||||
/**
|
||||
* Send a packet on a suitable interface. This routine will
|
||||
* later free() the packet to pool. This routine is not allowed to stall.
|
||||
* If the txmit queue is full it might return an error
|
||||
*/
|
||||
ErrorCode FloodingRouter::send(MeshPacket *p)
|
||||
{
|
||||
// Add any messages _we_ send to the seen message list (so we will ignore all retransmissions we see)
|
||||
wasSeenRecently(p); // FIXME, move this to a sniffSent method
|
||||
|
||||
return Router::send(p);
|
||||
}
|
||||
|
||||
bool FloodingRouter::shouldFilterReceived(const MeshPacket *p)
|
||||
{
|
||||
if (wasSeenRecently(p)) { // Note: this will also add a recent packet record
|
||||
DEBUG_MSG("Ignoring incoming msg, because we've already seen it: fr=0x%x,to=0x%x,id=%d,hop_limit=%d\n", p->from, p->to,
|
||||
p->id, p->hop_limit);
|
||||
return true;
|
||||
}
|
||||
|
||||
return Router::shouldFilterReceived(p);
|
||||
}
|
||||
|
||||
void FloodingRouter::sniffReceived(const MeshPacket *p)
|
||||
{
|
||||
// If a broadcast, possibly _also_ send copies out into the mesh.
|
||||
// (FIXME, do something smarter than naive flooding here)
|
||||
if (p->to == NODENUM_BROADCAST && p->hop_limit > 0) {
|
||||
if (p->id != 0) {
|
||||
MeshPacket *tosend = packetPool.allocCopy(*p); // keep a copy because we will be sending it
|
||||
|
||||
tosend->hop_limit--; // bump down the hop count
|
||||
|
||||
DEBUG_MSG("Rebroadcasting received floodmsg to neighbors, fr=0x%x,to=0x%x,id=%d,hop_limit=%d\n", p->from, p->to,
|
||||
p->id, tosend->hop_limit);
|
||||
// Note: we are careful to resend using the original senders node id
|
||||
// We are careful not to call our hooked version of send() - because we don't want to check this again
|
||||
Router::send(tosend);
|
||||
|
||||
} else {
|
||||
DEBUG_MSG("Ignoring a simple (0 id) broadcast\n");
|
||||
}
|
||||
}
|
||||
|
||||
// handle the packet as normal
|
||||
Router::sniffReceived(p);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user