Compare commits

...

125 Commits
0.0.3 ... 0.1.5

Author SHA1 Message Date
geeksville
e93187b630 0.1.5 add support for EU 433MHz radios thanks to @astro-arphid 2020-03-12 09:34:10 -07:00
geeksville
eca3cda8b9 fix typos 2020-03-12 09:31:31 -07:00
Kevin Hester
2874adfd69 Merge pull request #21 from astro-arphid/master
#13 - add support for 433MHz Heltec boards (thanks to @astro-arphid)
2020-03-12 09:29:54 -07:00
astro-arphid
91227b25df #13 - add support for 433MHz Heltec boards 2020-03-12 06:05:11 +00:00
geeksville
4dfac03402 add note about 3d printed cases 2020-03-11 10:59:02 -07:00
geeksville
9bc895eb57 fix formatting 2020-03-11 10:55:58 -07:00
geeksville
474026d7fe add a faq 2020-03-11 10:51:38 -07:00
geeksville
9995d2a7ab oops copypasta error fix #19. Thanks @iveskins! 2020-03-10 19:33:16 -07:00
geeksville
3028ac3f24 add note about dash7 2020-03-10 19:32:45 -07:00
geeksville
8605950eef add credits list 2020-03-10 11:43:45 -07:00
Kevin Hester
0f856dea7b Merge pull request #18 from claesg/master
Updated README for 3D cases for T-Beam.
2020-03-10 11:39:17 -07:00
claes
2a2bc5b1d6 Updated README for 3D cases for T-Beam.
T-Beam V1 has moved the antenna connector a bit to the right compared
to the V0. This makes the case not fit.
Added 2 more links for T-Beam cases.
2020-03-10 09:31:32 +01:00
geeksville
f87cb00940 show reason for last reset 2020-03-08 14:05:12 -07:00
geeksville
a4ebf83b69 minor doc update 2020-03-08 14:03:36 -07:00
geeksville
5dbacbddba version 0.1.13 Fix #15 found by @claesg. Thanks for the detailed report! 2020-03-08 11:07:27 -07:00
geeksville
011864a2d3 Fix #15 Force all devices to update preferences 2020-03-08 11:02:58 -07:00
geeksville
8646d8aeba mesh alg replacement update 2020-03-08 11:02:15 -07:00
geeksville
87782cdf8f progress on re readdition of the mesh router 2020-03-06 19:52:34 -08:00
geeksville
10289ed11a todo updates 2020-03-06 19:47:57 -08:00
geeksville
5def6a66e6 cleanup dev docs a bit more 2020-03-05 19:00:00 -08:00
geeksville
2d3bb4bb75 fix table formatting 2020-03-05 18:45:48 -08:00
geeksville
ffe8bf2be6 Refactor to make some real design docs 2020-03-05 18:39:24 -08:00
geeksville
ab73033e51 Fix #10. Add note about board types. 2020-03-05 13:18:36 -08:00
geeksville
c66e24aa4d most users are not using the phone app now, don't enter SDS state because of no phone comms 2020-03-04 18:59:10 -08:00
geeksville
651b13b3e5 version 0.1.0 2020-03-04 16:49:59 -08:00
geeksville
951f5d11d5 fix text message display when new text arrives
The problem was we were pulsing the display power briefly down while
reentering the ON state (because the ON states exit rule turned it off).
Instead we now just turn off the screen on entry to DARK or LS states
2020-03-04 16:46:57 -08:00
geeksville
2ce95ed2ce fix typo in SDS sleep time 2020-03-04 16:10:48 -08:00
geeksville
d1b7b6c5c5 oops - I was previously stopping bluetooth before stopping the mesh bluetooth service
which was bad bad
2020-03-04 16:10:36 -08:00
geeksville
425c570757 don't show fake GPS level on devices without one #4 2020-03-04 10:51:29 -08:00
Kevin Hester
46dab2d496 Make devicestate.version something that only the device code cares about 2020-03-03 13:46:11 -08:00
Kevin Hester
f5271f5c79 website updates 2020-03-03 13:37:01 -08:00
Kevin Hester
375804c9e4 (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).

Signed-off-by: Kevin Hester <kevinh@geeksville.com>
2020-03-03 13:31:44 -08:00
Kevin Hester
fe5703c684 fix the "blank screen when a text message arrives" bug 2020-03-03 10:15:23 -08:00
Kevin Hester
f1c90a232f fix release test script paths 2020-03-03 09:52:10 -08:00
Kevin Hester
a91fba763a release 0.0.9 2020-03-03 08:29:37 -08:00
Kevin Hester
28588f6730 send hw version info via protobufs 2020-03-03 08:23:58 -08:00
Kevin Hester
d074218049 no need to stop mesh service during sw update, bug was on the android side 2020-03-03 07:38:56 -08:00
Kevin Hester
1f07d6735b fix a nasty sleep bug: we weren't stopping our old mesh service
so it would kinda keep living (along with the recreated one) when we
come back from sleep.
2020-03-03 07:36:35 -08:00
Kevin Hester
bb0b2e72c8 stop using ino files, visual studio doesn't like them 2020-03-03 07:34:05 -08:00
Kevin Hester
30c717ac2f minor doc updates 2020-03-02 15:31:04 -08:00
Kevin Hester
e01680cd4b Change all repo URLs to be meshtastic... instead of geeksville... 2020-03-02 15:13:33 -08:00
Kevin Hester
4bb308c80c Pull protobufs from submodule instead of a symbolic link Fix #2 2020-03-02 09:57:05 -08:00
Kevin Hester
12a68026e7 clarify release of meshpacket back to pool 2020-03-02 09:02:21 -08:00
Kevin Hester
06449e39c1 Prove to google that we own this domain 2020-03-02 09:02:21 -08:00
Kevin Hester
cc6a8c8430 Merge pull request #12 from claesg/master
Updated the README.md with a new radio: TTGO LORA32
2020-03-01 16:25:51 -08:00
claes
9aedec2c5c Updated the README.md with a new radio: TTGO LORA32 2020-03-01 13:00:15 +01:00
Kevin Hester
2221ddfca2 Add note about a mystery bug following light sleep 2020-02-29 19:06:14 -08:00
Kevin Hester
7dc6264fa7 It helps to spell things correctly... 2020-02-29 19:05:59 -08:00
Kevin Hester
f091a9505a Add a pretty CI badge based on @girtsf work 2020-02-29 19:00:46 -08:00
Kevin Hester
57d5a54099 Merge pull request #6 from girtsf/fix-some-warnings
some minor cleanups
2020-02-29 07:10:50 -08:00
Kevin Hester
045a2031a3 todo updates 2020-02-29 07:08:18 -08:00
Girts Folkmanis
0b8d7768fd some minor cleanups
* Suppress warnings about conflicting library names in platformio.ini by
  explicitly picking the libraries by id that we want.
* fix unused static function warning by making it not static ;)
* declare arduino-fsm as dependency for BluetoothOTA. Hopefully this
  fixes the CI builds?

Tested: `pio run` builds.
2020-02-28 19:26:11 -08:00
Kevin Hester
c41f572cf5 update todo list while sitting in airplane ;-) 2020-02-28 12:36:52 -08:00
geeksville
bf26994d4e add misc hw docs/datasheets 2020-02-27 11:25:27 -08:00
geeksville
30ff67d46a fix CI? 2020-02-26 17:37:08 -08:00
geeksville
65e6d029e0 move CI script 2020-02-26 17:22:37 -08:00
geeksville
31e9d34d1e try github actions for CI builds 2020-02-26 17:20:19 -08:00
geeksville
0a796c4937 get ready for 0.0.6 2020-02-26 14:27:00 -08:00
geeksville
877e312833 allow TBEAMs to provide approx GPS time to Heltec devices 2020-02-26 09:00:53 -08:00
geeksville
cace2f4290 update readme for android release 2020-02-25 11:22:42 -08:00
geeksville
7b348f30ac text messages screen not coming up if screen was already on 2020-02-25 10:29:37 -08:00
geeksville
8893be57df kinda ugly but BLE sw update seems reliable again 2020-02-24 18:09:58 -08:00
geeksville
6b696bfdc5 hw vendor strings must match file names for auto update 2020-02-24 11:21:34 -08:00
geeksville
a3df099f60 until my TBEAM is fixed, leave GPS power on in sleep sometimes 2020-02-24 11:21:08 -08:00
geeksville
0ce1bbb758 expose standard ble sw/hw version characteristics from the updater
We also implement the following standard GATT entries because SW update probably needs them:
+
+ESP_GATT_UUID_SW_VERSION_STR/0x2a28
+ESP_GATT_UUID_MANU_NAME/0x2a29
+ESP_GATT_UUID_HW_VERSION_STR/0x2a27
2020-02-24 10:24:21 -08:00
geeksville
bb808c6c52 fix bluetooth pairing UX. enter full ON state when requested 2020-02-24 10:23:07 -08:00
geeksville
15ea13c286 start machine generating curfirmwareversion 2020-02-24 09:55:02 -08:00
geeksville
b0e0ee6934 begin to track firmware versions in a machine readable way 2020-02-24 09:46:32 -08:00
geeksville
f4791137fd keep latest builds in their own directory - so android build can find them 2020-02-24 09:33:41 -08:00
geeksville
51b53f406e include region code in the BLE HW version string. ie 1.0-US 2020-02-24 09:22:34 -08:00
geeksville
bd0f35ad83 fix encoding of sw version numbers in the BLE device info 2020-02-24 09:12:13 -08:00
geeksville
af5e3a0e02 TODO updates - back to Android app for now 2020-02-24 08:47:02 -08:00
geeksville
0110e1d2e0 release 0.0.4 2020-02-23 20:08:20 -08:00
geeksville
82afd234a1 don't stomp on RX packets when we have something ready to send 2020-02-23 19:51:43 -08:00
geeksville
419dd44ff6 BT sleep leak now down to about 200 bytes 2020-02-23 18:09:40 -08:00
geeksville
621beadb5c btle leak per sleep now down to about 500 bytes. 2020-02-23 16:42:09 -08:00
geeksville
8dfd7a4a71 the ble goo is still leaking on destroy, but better 2020-02-23 14:09:52 -08:00
geeksville
a45d7be922 still leaking in the BT stack but better 2020-02-23 13:54:40 -08:00
geeksville
f9ce6a53e1 ble works again after sleep - but we are still leaking 2020-02-23 13:20:46 -08:00
geeksville
5f88174dbf wip - finally done switching to dynamic allocs 2020-02-23 12:25:59 -08:00
geeksville
bf640bec3c WIP - more progress switching to dynamic alloc 2020-02-23 11:46:58 -08:00
geeksville
76100e23eb WIP make swupdate keep power on 2020-02-23 11:37:38 -08:00
geeksville
a678dd3ee8 WIP - all BT characteristics must be dynamically alloced 2020-02-23 11:05:55 -08:00
geeksville
356902d552 wip - make ble come back after sleep 2020-02-23 10:49:37 -08:00
geeksville
4906b12489 prevent ble powerdown while phone is connected 2020-02-23 08:53:52 -08:00
geeksville
316347226b don't use a symlink to find my modified RadioHead, use a pio depdency
To make it more easily buildable by others.
2020-02-23 08:24:10 -08:00
geeksville
4e06d9409a about to work on new gps code 2020-02-22 18:21:55 -08:00
geeksville
372a3e000e button presses are fixed 2020-02-22 18:02:44 -08:00
geeksville
5e2044dd63 blink the led very briefly every 5 secs while in light sleep 2020-02-22 17:40:31 -08:00
geeksville
a1a1ceb94d while not perfect, good enough to move power statemachine to master 2020-02-22 14:56:19 -08:00
geeksville
ca37e50362 WIP light sleep kinda works 2020-02-22 14:45:58 -08:00
geeksville
fe2ca65a11 WIP kinda works but light sleep still busted 2020-02-22 13:50:08 -08:00
geeksville
c7894f3bc5 fsm WIP might work 2020-02-22 13:14:10 -08:00
geeksville
509f9b6e2b WIP state machine builds 2020-02-22 12:01:59 -08:00
geeksville
045529d91f begin cleanup of sleep code for new state machine 2020-02-21 17:01:26 -08:00
geeksville
4fa6b64c3d beginnings of sw design doc 2020-02-21 14:55:28 -08:00
geeksville
fa4c63edc8 document the sleep management state machine 2020-02-21 14:31:15 -08:00
geeksville
aebcbf767f GPS works better now with light-sleep but not quite done. 2020-02-21 12:24:35 -08:00
geeksville
598023f5db PMU IRQ polarity was backwards 2020-02-21 11:39:10 -08:00
geeksville
3df81682b3 now that light-sleep kinda works, use deep-sleep far more rarely 2020-02-21 11:32:33 -08:00
geeksville
20461807f3 change screen into a periodictask, so it can be used with the scheduler 2020-02-21 10:51:36 -08:00
geeksville
a6b98bec1f cleanup period stuff for new scheduler 2020-02-21 10:20:47 -08:00
geeksville
d4efb2c44c burn _lots_ less cpu updating the display when idle 2020-02-21 10:13:51 -08:00
geeksville
5f3e8b5309 unify periodic timers 2020-02-21 08:41:36 -08:00
geeksville
132e54ecc5 don't turn bluetooth back on every time we exit light sleep 2020-02-21 08:09:07 -08:00
geeksville
7a745c9e65 light sleep seems to work well 2020-02-21 04:57:08 -08:00
geeksville
beccc34ef1 lower cpu freq to 80MHz 2020-02-21 03:48:13 -08:00
geeksville
7e2d765516 omg so many typos. 2020-02-20 22:15:19 -08:00
geeksville
e00d2db741 misc typos 2020-02-20 22:11:13 -08:00
geeksville
96ca063f63 more webpage typos - back to code soon... 2020-02-20 21:09:22 -08:00
geeksville
045ac16e7f add a price ;-) 2020-02-20 21:08:25 -08:00
geeksville
e40bf8e2d3 add link to LoRa wiki page 2020-02-20 21:06:23 -08:00
geeksville
ab1ace63a5 minor readme updates 2020-02-20 21:01:31 -08:00
geeksville
57c483d136 todo updates 2020-02-20 20:48:16 -08:00
geeksville
655814c816 add Girts' HAM idea (@girtsf) 2020-02-20 15:21:07 -08:00
geeksville
84a86ec35d typo 2020-02-20 15:10:19 -08:00
geeksville
8972814270 remove disclaimer 2020-02-20 14:38:50 -08:00
geeksville
a4c6ad6e8f kid joke 2020-02-20 14:26:33 -08:00
geeksville
5233c6d629 add range note 2020-02-20 14:23:36 -08:00
geeksville
31cc277553 ping github 2020-02-20 14:16:15 -08:00
geeksville
8c80861b69 layout tweak 2020-02-20 14:15:27 -08:00
geeksville
0ab5b69c11 docs update 2020-02-20 14:14:27 -08:00
geeksville
e9279c6daa add high level end-user todos 2020-02-20 14:05:18 -08:00
geeksville
b060c518a2 highlight chat link 2020-02-20 13:33:08 -08:00
geeksville
6ade723caa release 0.0.3 alpha posted 2020-02-20 13:23:42 -08:00
72 changed files with 2237 additions and 976 deletions

19
.github/workflows/main.yml vendored Normal file
View File

@@ -0,0 +1,19 @@
name: Continuous Integration
on: push
jobs:
main:
name: Main
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- name: Setup Python
uses: actions/setup-python@master
with:
python-version: 3.x
- name: Install Platform IO
run: |
python -m pip install --upgrade pip
pip install -U platformio
- name: Build
run: platformio run

3
.gitmodules vendored Normal file
View File

@@ -0,0 +1,3 @@
[submodule "proto"]
path = proto
url = https://github.com/meshtastic/Meshtastic-protobufs.git

View File

@@ -41,9 +41,12 @@
"utility": "cpp",
"typeinfo": "cpp",
"string": "cpp",
"*.xbm": "cpp"
"*.xbm": "cpp",
"list": "cpp"
},
"cSpell.words": [
"Meshtastic"
"Meshtastic",
"descs",
"protobufs"
]
}

View File

@@ -1,6 +1,8 @@
# Meshtastic-esp32
This is the device side code for the [meshtastic.org](https://www.meshtastic.org) project.
![Continuous Integration](https://github.com/meshtastic/Meshtastic-esp32/workflows/Continuous%20Integration/badge.svg)
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
@@ -11,37 +13,90 @@ 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 pre-alpha, but if you have questions please join our chat [![Join the chat at https://gitter.im/Meshtastic/community](https://badges.gitter.im/Meshtastic/community.svg)](https://gitter.im/Meshtastic/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge).
This project is currently early-alpha, but if you have questions please join our chat [![Join the chat at https://gitter.im/Meshtastic/community](https://badges.gitter.im/Meshtastic/community.svg)](https://gitter.im/Meshtastic/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge).
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.
## Meshtastic Android app
The source code for the (optional) Meshtastic Android app is [here](https://github.com/geeksville/Meshtastic-Android).
Soon our first alpha release of will be released here:
[![Download at https://play.google.com/store/apps/details?id=com.geeksville.mesh](https://play.google.com/intl/en_us/badges/static/images/badges/en_badge_web_generic.png)](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)
## 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 users should buy the T-Beam and a 18650 battery (total cost less than $35). Make
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 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 don't yet distribute prebuilt binaries. But soon (by Feb 22) we will have a file that you can fairly easily install on your radio via USB. Once our software is installed, all future software updates happen over bluetooth from your phone.
See (meshtastic.org) for 3D printable cases.
For a nice 3D printable case see this [design](https://www.thingiverse.com/thing:3773717) by [bsiege](https://www.thingiverse.com/bsiege).
## Installing the firmware
Prebuilt binaries for the supported radios is 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.
The instructions currently require a few commmand lines, but it should be pretty straightforward. Please post comments on our group chat if you have problems or successes. Steps to install:
1. Purchase a radio (see above) with the correct frequencies for your country (915MHz for US or JP, 470MHz for CN, 433MHz and 870MHz for EU).
2. Install "pip". Pip is the python package manager we use to get the esptool installer app. Instructions [here](https://www.makeuseof.com/tag/install-pip-for-python/).
3. Run "pip install --upgrade esptool" to get esptool installed on your machine
4. Connect your radio to your USB port
5. Confirm that your device is talking to your PC by running "esptool.py chip_id". The Heltec build also works on the TTGO LORA32 radio. You should see something like:
```
mydir$ esptool.py chip_id
esptool.py v2.6
Found 2 serial ports
Serial port /dev/ttyUSB0
Connecting....
Detecting chip type... ESP32
Chip is ESP32D0WDQ6 (revision 1)
Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse, Coding Scheme None
MAC: 24:6f:28:b5:36:71
Uploading stub...
Running stub...
Stub running...
Warning: ESP32 has no Chip ID. Reading MAC instead.
MAC: 24:6f:28:b5:36:71
Hard resetting via RTS pin...
```
6. Install the correct firmware for your board with "esptool.py write_flash 0x10000 firmware-_board_-_country_.bin". For instance "esptool.py write_flash 0x10000 release/firmware-HELTEC-US-0.0.3.bin". You should see something like this:
```
~/development/meshtastic/meshtastic-esp32$ esptool.py write_flash 0x10000 release/firmware-HELTEC-US-0.0.3.bin
esptool.py v2.6
Found 2 serial ports
Serial port /dev/ttyUSB0
Connecting......
Detecting chip type... ESP32
Chip is ESP32D0WDQ6 (revision 1)
Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse, Coding Scheme None
MAC: 24:6f:28:b5:36:71
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Auto-detected Flash size: 8MB
Compressed 1184800 bytes to 652635...
Wrote 1184800 bytes (652635 compressed) at 0x00010000 in 57.6 seconds (effective 164.5 kbit/s)...
Hash of data verified.
Leaving...
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
The source code for the (optional) Meshtastic Android app is [here](https://github.com/meshtastic/Meshtastic-Android).
Alpha test builds are current available by opting into our alpha test group. See (www.meshtastic.org) for instructions.
After our rate of change slows a bit, we will make beta builds available here (without needing to join the alphatest group):
[![Download at https://play.google.com/store/apps/details?id=com.geeksville.mesh](https://play.google.com/intl/en_us/badges/static/images/badges/en_badge_web_generic.png)](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)
# Development
The following sections are probably only interesting if you want to join us in developing the software.
## Power measurements
Since one of the main goals of this project is long battery life, it is important to consider that in our software/protocol design. Based on initial measurements it seems that the current code should run about three days between charging, and with a bit more software work (see the [TODO list](TODO.md)) a battery life of eight days should be quite doable. Our current power measurements/model is in [this spreadsheet](https://docs.google.com/spreadsheets/d/1ft1bS3iXqFKU8SApU8ZLTq9r7QQEGESYnVgdtvdT67k/edit?usp=sharing).
We'd love to have you join us on this merry little project. Please see our [development documents](./docs/software/sw-design.md) and join us on the gitter chat above.
## Build instructions
This project uses the simple PlatformIO build system. You can use the IDE, but for brevity
in these instructions I describe use of their command line tool.
# Credits
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. Plug the radio into your USB port
4. Type "pio run -t upload" (This command will fetch dependencies, build the project and install it on the board via USB)
5. 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
This project is run by volunteers. Past contributors include:
* @astro-arphid: Added support for 433MHz radios in europe.
* @claesg: Various documentation fixes and 3D print enclosures
* @girtsf: So far our CI system, but soon lots of device improvements
# IMPORTANT DISCLAIMERS AND FAQ
For a listing of currently missing features and a FAQ click [here](docs/faq.md).

View File

@@ -1,15 +1,56 @@
#!/bin/bash
set -e
VERSION=0.0.3
source bin/version.sh
COUNTRY=US
COUNTRIES="US EU433 EU865 CN JP"
# COUNTRIES=US
rm .pio/build/esp32/firmware.bin
export PLATFORMIO_BUILD_FLAGS="-DT_BEAM_V10 -DAPP_VERSION=$VERSION"
pio run # -v
cp .pio/build/esp32/firmware.bin release/firmware-TBEAM-$COUNTRY.bin
SRCMAP=.pio/build/esp32/output.map
SRCBIN=.pio/build/esp32/firmware.bin
OUTDIR=release/latest
rm .pio/build/esp32/firmware.bin
export PLATFORMIO_BUILD_FLAGS="-DHELTEC_LORA32 -DAPP_VERSION=$VERSION"
pio run # -v
cp .pio/build/esp32/firmware.bin release/firmware-HELTEC-$COUNTRY.bin
# We keep all old builds (and their map files in the archive dir)
ARCHIVEDIR=release/archive
rm -f $OUTDIR/firmware*
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 -Wl,-Map,.pio/build/esp32/output.map -DAXP_DEBUG_PORT=Serial"
export PLATFORMIO_BUILD_FLAGS="-DT_BEAM_V10 $COMMONOPTS"
echo "Building with $PLATFORMIO_BUILD_FLAGS"
rm -f $SRCBIN $SRCMAP
pio run # -v
cp $SRCBIN $OUTDIR/firmware-TBEAM-$COUNTRY-$VERSION.bin
#cp $SRCMAP $ARCHIVEDIR/firmware-TBEAM-$COUNTRY-$VERSION.map
export PLATFORMIO_BUILD_FLAGS="-DHELTEC_LORA32 $COMMONOPTS"
rm -f $SRCBIN $SRCMAP
pio run # -v
cp $SRCBIN $OUTDIR/firmware-HELTEC-$COUNTRY-$VERSION.bin
#cp $SRCMAP $ARCHIVEDIR/firmware-HELTEC-$COUNTRY-$VERSION.map
done
# keep the bins in archive also
cp $OUTDIR/firmware* $ARCHIVEDIR
cat >$OUTDIR/curfirmwareversion.xml <<XML
<?xml version="1.0" encoding="utf-8"?>
<!-- This file is kept in source control because it reflects the last stable
release. It is used by the android app for forcing software updates. Do not edit.
Generated by bin/buildall.sh -->
<resources>
<string name="cur_firmware_version">$VERSION</string>
</resources>
XML
rm -f $ARCHIVEDIR/firmware-$VERSION.zip
zip $ARCHIVEDIR/firmware-$VERSION.zip $OUTDIR/firmware-*-$VERSION.bin
echo BUILT ALL

6
bin/program-release-heltec.sh Executable file
View File

@@ -0,0 +1,6 @@
set -e
source bin/version.sh
esptool.py --baud 921600 write_flash 0x10000 release/latest/firmware-HELTEC-US-$VERSION.bin

View File

@@ -1 +1,6 @@
/home/kevinh/packages/nanopb-0.4.1-linux-x86/generator-bin/protoc --nanopb_out=-v:src -I=../MeshUtil/app/src/main/proto mesh.proto
#!/bin/bash
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

3
bin/version.sh Normal file
View File

@@ -0,0 +1,3 @@
export VERSION=0.1.5

View File

@@ -0,0 +1,9 @@
[{
"relation": ["delegate_permission/common.handle_all_urls"],
"target": {
"namespace": "android_app",
"package_name": "com.geeksville.mesh",
"sha256_cert_fingerprints":
["D0:05:E7:8B:D2:1B:FA:94:56:1D:6B:90:EB:53:07:1A:74:4F:D9:C2:6F:13:87:6A:D9:17:4F:C2:59:48:02:9D"]
}
}]

View File

@@ -1,38 +1,73 @@
# What is Meshtastic?
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 -
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.
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.
Typical time between recharging the radios should be about eight days.
### Uses
This project is currently pre-alpha, but if you have questions please join our chat [![Join the chat at https://gitter.im/Meshtastic/community](https://badges.gitter.im/Meshtastic/community.svg)](https://gitter.im/Meshtastic/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge).
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.
* Outdoor sports where cellular coverage is limited. (Hiking, Skiing, Boating, Paragliding, Gliders etc..)
* 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 ;-)
[![Youtube video demo](desk-video-screenshot.png)](https://www.youtube.com/watch?v=WlNbMbVZlHI "Meshtastic early demo")
### Features
Not all of these features are fully implemented yet - see **important** disclaimers below. But they should be in by the time we decide to call this project beta (three months?)
* 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
* 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.
* 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 chat [![Join the chat at https://gitter.im/Meshtastic/community](https://badges.gitter.im/Meshtastic/community.svg)](https://gitter.im/Meshtastic/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge).
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](https://gitter.im/Meshtastic/community).
# 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.
* 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.
* 02/20/2020 - Our first alpha release (0.0.3) of the radio software is ready brave early people.
## Meshtastic Android app
The source code for the Meshtastic Android app is [here](https://github.com/geeksville/Meshtastic-Android).
Soon our first alpha release of will be released here:
Once out of alpha the companion Android application will be released here:
[![Download at https://play.google.com/store/apps/details?id=com.geeksville.mesh](https://play.google.com/intl/en_us/badges/static/images/badges/en_badge_web_generic.png)](https://play.google.com/store/apps/details?id=com.geeksville.mesh&referrer=utm_source%3Dhomepage%26anid%3Dadmob)
If you would like to join our bleeding-edge alpha test group for this app, we'd love to have you. Three steps:
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:
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.
3. If you encounter any problems or have questions, post in our gitter chat and we'll help.
If you'd like to help with development, the source code is [on github](https://github.com/meshtastic/Meshtastic-Android).
## 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 users 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/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 don't yet distribute prebuilt binaries. But soon (by Feb 22) we will have a file that you can easily install on your radio via USB. Once our software is installed, all future software updates happen over bluetooth from your phone.
Instructions for installing prebuilt firmware can be found [here](https://github.com/meshtastic/Meshtastic-esp32/blob/master/README.md).
For a nice TTGO 3D printable case see this [design](https://www.thingiverse.com/thing:3773717) by [bsiege](https://www.thingiverse.com/bsiege).
For a nice Heltec 3D printable case see this [design](https://www.thingiverse.com/thing:3125854) by [ornotermes](https://www.thingiverse.com/ornotermes).
For a nice printable cases:
1. TTGO T-Beam V0 see this [design](https://www.thingiverse.com/thing:3773717) by [bsiege](https://www.thingiverse.com/bsiege).
2. TTGO T_Beam V1 see this [design](https://www.thingiverse.com/thing:3830711) by [rwanrooy](https://www.thingiverse.com/rwanrooy) or this [remix](https://www.thingiverse.com/thing:3949330) by [8ung](https://www.thingiverse.com/8ung)
3. Heltec Lora32 see this [design](https://www.thingiverse.com/thing:3125854) by [ornotermes](https://www.thingiverse.com/ornotermes).
# IMPORTANT DISCLAIMERS AND FAQ
For a listing of currently missing features and a FAQ click [here](faq.md).

36
docs/faq.md Normal file
View File

@@ -0,0 +1,36 @@
# Disclaimers
This project is still pretty young but moving at a pretty good pace. Not all features are fully implemented in the current alpha builds.
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
* 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 current Android GUI is slightly ugly still
* The Android API needs to be documented better
* The mesh protocol is turned off for now, currently we only send packets one hop distant. The mesh feature will be turned on again [soonish](https://github.com/meshtastic/Meshtastic-esp32/issues/3).
* No one has written an iOS app yet. But some good souls [are talking about it](https://github.com/meshtastic/Meshtastic-esp32/issues/14) ;-)
For more details see the [device software TODO](https://github.com/meshtastic/Meshtastic-esp32/blob/master/docs/software/TODO.md) or the [Android app TODO](https://github.com/meshtastic/Meshtastic-Android/blob/master/TODO.md).
# FAQ
If you have a question missing from this faq, please ask on our gitter chat. And if you are feeling extra generous send in a pull-request for this faq.md with whatever we answered ;-).
## Q: Which of the various supported radios should I buy?
Basically you just need the radio + (optional but recommended) battery. The TBEAM is usually better because it has gps and huge battery socket. The Heltec is basically the same hardware but without the GPS (the phone provides position data to the radio in that case, so the behavior is similar - but it does burn some battery in the phone). Also the battery for the Heltec can be smaller.
In addition to Aliexpress, (banggood.com) usually has stock and faster shipping, or Amazon. If buying a TBEAM, make sure to buy a version that includes the OLED screen - this project doesn't absolutely require the screen, but we use it if is installed.
@claesg has added links to various 3D printable cases, you can see them at (www.meshtastic.org).
## Q: Do you have plans to commercialize this project
Nope. though if some other person/group wanted to use this software and a more customized device we think that would be awesome (as long as they obey the GPL license).
## Q: Does this project use patented algorithms?
(Kindly borrowed from the geeks at [ffmpeg](http://ffmpeg.org/legal.html))
We do not know, we are not lawyers so we are not qualified to answer this. Also we have never read patents to implement any part of this, so even if we were qualified we could not answer it as we do not know what is patented. Furthermore the sheer number of software patents makes it impossible to read them all so no one (lawyer or not) could answer such a question with a definite no. We are merely geeks experimenting on a fun and free project.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

20
docs/mesh-proto.md Normal file
View File

@@ -0,0 +1,20 @@
TODO:
* reread the radiohead mesh implementation
* read about general mesh flooding solutions
* reread the disaster radio protocol docs
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
It seems like DSR might be the algorithm used by RadioheadMesh. DSR is described in https://tools.ietf.org/html/rfc4728
https://en.wikipedia.org/wiki/Dynamic_Source_Routing
broadcast solution:
Use naive flooding at first (FIXME - do some math for a 20 node, 3 hop mesh. A single flood will require a max of 20 messages sent)
Then move to MPR later (http://www.olsr.org/docs/report_html/node28.html). Use altitude and location as heursitics in selecting the MPR set
compare to db sync algorithm?
what about never flooding gps broadcasts. instead only have them go one hop in the common case, but if any node X is looking at the position of Y on their gui, then send a unicast to Y asking for position update. Y replies.
If Y were to die, at least the neighbor nodes of Y would have their last known position of Y.

View File

@@ -5,7 +5,7 @@ We don't collect any personal identifying information.
If you have opted-in to analytics (thank you - that helps us know what things we need to improve), we'll receive anonymized information about user behavior. i.e. which screens you used in the app etc... We never
capture usernames, the contents of your texts or your location.
This is an open-source project run by hobbyists and we try to be completely transparent. If you have questions on this policy, please file [a github issue](https://github.com/geeksville/meshtastic-esp32/issues) and we'll reply/clarify/correct.
This is an open-source project run by hobbyists and we try to be completely transparent. If you have questions on this policy, please file [a github issue](https://github.com/meshtastic/meshtastic-esp32/issues) and we'll reply/clarify/correct.
Keep being awesome!

View File

@@ -10,6 +10,13 @@ See [this site](https://www.rfwireless-world.com/Tutorials/LoRa-channels-list.ht
The maximum power allowed is +14dBM.
### 433 MHz
There are eight channels defined with a 0.2 MHz gap between them.
Channel zero starts at 433.175 MHz
### 870 MHz
There are eight channels defined with a 0.3 MHz gap between them.
Channel zero starts at 865.20 MHz

View File

@@ -1,117 +1,94 @@
# High priority
Items to complete before the first alpha release.
* rx signal measurements -3 marginal, -9 bad, 10 great
* only send 10% of phone gps positions on the network
* post sample video to signal forum
* support non US frequencies
* make an install script to let novices install software on their boards
* retest BLE software update for both board types
* default to enter deep sleep if no LORA received for two hours (indicates user has probably left the meshS)
* first alpha release, article writeup for hackaday
* send note about Adafruit Clue
* send note to the guy who designed the cases
* send pr https://github.com/ThingPulse/esp8266-oled-ssd1306 to tell them about this project
* update the prebuilt bins for different regulatory regions
Items to complete soon (next couple of alpha releases).
* 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.
* 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
* remeasure wake time power draws now that we run CPU down at 80MHz
* add a SF12 transmit option for _super_ long range
# AXP192 tasks
* "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
# Medium priority
Items to complete before the first beta release.
* Make a FAQ
* good source of battery/signal/gps icons https://materialdesignicons.com/
* 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
* research and implement better mesh algorithm
* 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
* Use the Periodic class for both position and user periodic broadcasts
* make debug info screen show real data (including battery level & charging)
* don't forward redundant pings or ping responses to the phone, it just wastes phone battery
* don't treat north as up, instead adjust shown bearings for our guess at the users heading (i.e. subtract one from the other)
* answer to pings (because some other user is looking at our nodeinfo) with our latest 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.
* use https://platformio.org/lib/show/1260/OneButton if necessary
* make an about to sleep screen
* don't send location packets if we haven't moved
* scrub default radio config settings for bandwidth/range/speed
* add basic crypto - http://rweather.github.io/arduinolibs/crypto.html with speck https://www.airspayce.com/mikem/arduino/RadioHead/rf95_encrypted_client_8pde-example.html
* override peekAtMessage so we can see any messages that pass through our node (even if not broadcast)? would that be useful?
* sendToMesh can currently block for a long time, instead have it just queue a packet for a radio freertos thread
* How do avalanche beacons work? Could this do that as well? possibly by using beacon mode feature of the RF95?
* use std::map<NodeInfo*, std::string> in node db
# Low power consumption tasks
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.
* (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.
# Mesh broadcast algoritm
FIXME - instead look for standard solutions. this approach seems really suboptimal, because too many nodes will try to rebroast.
## approach 1
* send all broadcasts with a TTL
* periodically(?) do a survey to find the max TTL that is needed to fully cover the current network.
* to do a study first send a broadcast (maybe our current initial user announcement?) with TTL set to one (so therefore no one will rebroadcast our request)
* survey replies are sent unicast back to us (and intervening nodes will need to keep the route table that they have built up based on past packets)
* count the number of replies to this TTL 1 attempt. That is the number of nodes we can reach without any rebroadcasts
* repeat the study with a TTL of 2 and then 3. stop once the # of replies stops going up.
* it is important for any node to do listen before talk to prevent stomping on other rebroadcasters...
* For these little networks I bet a max TTL would never be higher than 3?
## approach 2
* send a TTL1 broadcast, the replies let us build a list of the nodes (stored as a bitvector?) that we can see (and their rssis)
* we then broadcast out that bitvector (also TTL1) asking "can any of ya'll (even indirectly) see anyone else?"
* if a node can see someone I missed (and they are the best person to see that node), they reply (unidirectionally) with the missing nodes and their rssis (other nodes might sniff (and update their db) based on this reply but they don't have to)
* given that the max number of nodes in this mesh will be like 20 (for normal cases), I bet globally updating this db of "nodenums and who has the best rssi for packets from that node" would be useful
* once the global DB is shared, when a node wants to broadcast, it just sends out its broadcast . the first level receivers then make a decision "am I the best to rebroadcast to someone who likely missed this packet?" if so, rebroadcast
* 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
* 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
# Pre-beta priority
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
* swap out speck for hw-accelerated full AES https://github.com/espressif/arduino-esp32/blob/master/tools/sdk/include/esp32/hwcrypto/aes.h
* use variable length arduino Strings in protobufs (instead of current fixed buffers)
* 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/
* make sure main cpu is not woken for packets with bad crc or not addressed to this node - do that in the radio hw
* enable fast init inside the gps chip
* triple check fcc compliance
* pick channel center frequency based on name? "dolphin" would hash to 900Mhz, "cat" to 905MHz etc? Or is that too opaque?
* scan to find channels with low background noise?
* share channel settings over Signal (or qr code) by embedding an an URL which is handled by the MeshUtil app.
* 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
# 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.
* make a no bluetooth configured yet screen - include this screen in the loop if the user hasn't yet paired
* 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.
* if radio params change fundamentally, discard the nodedb
* 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
* have android provide position data for nodes that don't have gps
* 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
* fix GPS.zeroOffset calculation it is wrong
* handle millis() rollover in GPS.getTime - otherwise we will break after 50 days
* reneable the bluetooth battery level service on the T-BEAM, because we can read battery level there
* report esp32 device code bugs back to the mothership via android
# Done
@@ -180,4 +157,41 @@ Items after the first final candidate release.
* 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
* 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

View File

@@ -0,0 +1,110 @@
# Bluetooth API
The Bluetooth API is design to have only a few characteristics and most polymorphism comes from the flexible set of Google Protocol Buffers which are sent over the wire. We use protocol buffers extensively both for the bluetooth API and for packets inside the mesh or when providing packets to other applications on the phone.
## A note on MTU sizes
This device will work with any MTU size, but it is highly recommended that you call your phone's "setMTU function to increase MTU to 512 bytes" as soon as you connect to a service. This will dramatically improve performance when reading/writing packets.
## MeshBluetoothService
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:
* 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"
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)
UUID for the service: 6ba1b218-15a8-461f-9fa8-5dcae273eafd
Each characteristic is listed as follows:
UUID
Properties
Description (including human readable name)
8ba2bcc2-ee02-4a55-a531-c525c5e454d5
read
fromradio - contains a newly received FromRadio packet destined towards the phone (up to MAXPACKET bytes per packet).
After reading the esp32 will put the next packet in this mailbox. If the FIFO is empty it will put an empty packet in this
mailbox.
f75c76d2-129e-4dad-a1dd-7866124401e7
write
toradio - write ToRadio protobufs to this characteristic to send them (up to MAXPACKET len)
ed9da18c-a800-4f66-a670-aa7547e34453
read,notify,write
fromnum - the current packet # in the message waiting inside fromradio, if the phone sees this notify it should read messages
until it catches up with this number.
The phone can write to this register to go backwards up to FIXME packets, to handle the rare case of a fromradio packet was dropped after the esp32 callback was called, but before it arrives at the phone. If the phone writes to this register the esp32 will discard older packets and put the next packet >= fromnum in fromradio.
When the esp32 advances fromnum, it will delay doing the notify by 100ms, in the hopes that the notify will never actally need to be sent if the phone is already pulling from fromradio.
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
A variable keepAllPackets, if set to true will suppress this behavior and instead keep everything for forwarding to the phone (for debugging)
## Other bluetooth services
This document focuses on the core mesh service, but it is worth noting that the following other Bluetooth services are also
provided by the device.
### BluetoothSoftwareUpdate
The software update service. For a sample function that performs a software update using this API see [startUpdate](https://github.com/meshtastic/Meshtastic-Android/blob/master/app/src/main/java/com/geeksville/mesh/service/SoftwareUpdateService.kt).
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 |
| 5e134862-7411-4424-ac4a-210937432c77 | read,notify | result code, readable but will notify when the OTA operation completes |
| GATT_UUID_SW_VERSION_STR/0x2a28 | read | We also implement these standard GATT entries because SW update probably needs them: |
| GATT_UUID_MANU_NAME/0x2a29 | read | |
| GATT_UUID_HW_VERSION_STR/0x2a27 | read | |
### DeviceInformationService
Implements the standard BLE contract for this service (has software version, hardware model, serial number, etc...)
### BatteryLevelService
Implements the standard BLE contract service, provides battery level in a way that most client devices should automatically understand (i.e. it should show in the bluetooth devices screen automatically)

View File

@@ -0,0 +1,16 @@
# Build instructions
This project uses the simple PlatformIO build system. You can use the IDE, but for brevity
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. Edit configuration.h and comment out *one* of the following two lines (depending on which board you are using):
```
// #define T_BEAM_V10
#define HELTEC_LORA32
```
5. Plug the radio into your USB port
6. Type "pio run -t upload" (This command will fetch dependencies, build the project and install it on the board via USB)
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

72
docs/software/mesh-alg.md Normal file
View File

@@ -0,0 +1,72 @@
# 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/
TODO:
* DONE reread the radiohead mesh implementation - hop to hop acknoledgement 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
* 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)
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
It seems like DSR might be the algorithm used by RadioheadMesh. DSR is described in https://tools.ietf.org/html/rfc4728
https://en.wikipedia.org/wiki/Dynamic_Source_Routing
broadcast solution:
Use naive flooding at first (FIXME - do some math for a 20 node, 3 hop mesh. A single flood will require a max of 20 messages sent)
Then move to MPR later (http://www.olsr.org/docs/report_html/node28.html). Use altitude and location as heursitics in selecting the MPR set
compare to db sync algorithm?
what about never flooding gps broadcasts. instead only have them go one hop in the common case, but if any node X is looking at the position of Y on their gui, then send a unicast to Y asking for position update. Y replies.
If Y were to die, at least the neighbor nodes of Y would have their last known position of Y.
## approach 1
* send all broadcasts with a TTL
* periodically(?) do a survey to find the max TTL that is needed to fully cover the current network.
* to do a study first send a broadcast (maybe our current initial user announcement?) with TTL set to one (so therefore no one will rebroadcast our request)
* survey replies are sent unicast back to us (and intervening nodes will need to keep the route table that they have built up based on past packets)
* count the number of replies to this TTL 1 attempt. That is the number of nodes we can reach without any rebroadcasts
* repeat the study with a TTL of 2 and then 3. stop once the # of replies stops going up.
* it is important for any node to do listen before talk to prevent stomping on other rebroadcasters...
* For these little networks I bet a max TTL would never be higher than 3?
## approach 2
* send a TTL1 broadcast, the replies let us build a list of the nodes (stored as a bitvector?) that we can see (and their rssis)
* we then broadcast out that bitvector (also TTL1) asking "can any of ya'll (even indirectly) see anyone else?"
* if a node can see someone I missed (and they are the best person to see that node), they reply (unidirectionally) with the missing nodes and their rssis (other nodes might sniff (and update their db) based on this reply but they don't have to)
* given that the max number of nodes in this mesh will be like 20 (for normal cases), I bet globally updating this db of "nodenums and who has the best rssi for packets from that node" would be useful
* once the global DB is shared, when a node wants to broadcast, it just sends out its broadcast . the first level receivers then make a decision "am I the best to rebroadcast to someone who likely missed this packet?" if so, rebroadcast
## approach 3
* when a node X wants to know other nodes positions, it broadcasts its position with want_replies=true. Then each of the nodes that received that request broadcast their replies (possibly by using special timeslots?)
* all nodes constantly update their local db based on replies they witnessed.
* after 10s (or whatever) if node Y notices that it didn't hear a reply from node Z (that Y has heard from recently ) to that initial request, that means Z never heard the request from X. Node Y will reply to X on Z's behalf.
* could this work for more than one hop? Is more than one hop needed? Could it work for sending messages (i.e. for a msg sent to Z with want-reply set).
## approach 4
look into the literature for this idea specifically.
* don't view it as a mesh protocol as much as a "distributed db unification problem". When nodes talk to nearby nodes they work together
to update their nodedbs. Each nodedb would have a last change date and any new changes that only one node has would get passed to the
other node. This would nicely allow distant nodes to propogate their position to all other nodes (eventually).
* handle group messages the same way, there would be a table of messages and time of creation.
* when a node has a new position or message to send out, it does a broadcast. All the adjacent nodes update their db instantly (this handles 90% of messages I'll bet).
* Occasionally a node might broadcast saying "anyone have anything newer than time X?" If someone does, they send the diffs since that date.
* essentially everything in this variant becomes broadcasts of "request db updates for >time X - for _all_ or for a particular nodenum" and nodes sending (either due to request or because they changed state) "here's a set of db updates". Every node is constantly trying to
build the most recent version of reality, and if some nodes are too far, then nodes closer in will eventually forward their changes to the distributed db.
* construct non ambigious rules for who broadcasts to request db updates. ideally the algorithm should nicely realize node X can see most other nodes, so they should just listen to all those nodes and minimize the # of broadcasts. the distributed picture of nodes rssi could be useful here?
* possibly view the BLE protocol to the radio the same way - just a process of reconverging the node/msgdb database.

85
docs/software/power.md Normal file
View File

@@ -0,0 +1,85 @@
# Power Management State Machine
i.e. sleep behavior
## Power measurements
Since one of the main goals of this project is long battery life, it is important to consider that in our software/protocol design. Based on initial measurements it seems that the current code should run about three days between charging, and with a bit more software work (see the [TODO list](TODO.md)) a battery life of eight days should be quite doable. Our current power measurements/model is in [this spreadsheet](https://docs.google.com/spreadsheets/d/1ft1bS3iXqFKU8SApU8ZLTq9r7QQEGESYnVgdtvdT67k/edit?usp=sharing).
## States
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.
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
(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
off during light sleep, but there is a TODO item to fix this.
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.
onEntry: setBluetoothOn(false)
onExit:
* running dark (DARK) - Everything is on except screen
onEntry: setBluetoothOn(true)
onExit:
* full on (ON) - Everything is on
onEntry: setBluetoothOn(true), screen.setOn(true)
onExit: screen.setOn(false)
## 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)
### 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
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.
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...
# Low power consumption tasks
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.

View File

@@ -0,0 +1,9 @@
This is a mini design doc for developing the meshtastic software.
* [Build instructions](build-instructions.md)
* [TODO](TODO.md) - read this if you are looking for things to do (or curious about currently missing features)
* Our [project board](https://github.com/orgs/meshtastic/projects/1) - shows what things we are currently working on and remaining work items for the current release.
* [Power Management](power.md)
* [Mesh algorithm](mesh-alg.md)
* [Bluetooth API](bluetooth-api.md) and porting guide for new clients (iOS, python, etc...)
* TODO: how to port the device code to a new device.

View File

@@ -2,13 +2,11 @@
"name": "BluetoothOTA",
"keywords": "esp32, bluetooth",
"description": "A BTLE based software OTA update tool",
"repository":
{
"repository": {
"type": "git",
"url": "https://github.com/geeksville/fixme.git"
},
"authors":
[
"authors": [
{
"name": "Kevin Hester",
"email": "kevinh@geeksville.com",
@@ -20,7 +18,15 @@
"frameworks": "arduino",
"platforms": "*",
"dependencies": [
{ "name": "Update" },
{ "name": "ESP32 BLE Arduino" }
{
"name": "Update"
},
{
"name": "ESP32 BLE Arduino"
},
{
"name": "arduino-fsm",
"version": "https://github.com/meshtastic/arduino-fsm.git"
}
]
}
}

View File

@@ -6,111 +6,153 @@
#include <Arduino.h>
#include <Update.h>
#include <CRC32.h>
static BLECharacteristic swUpdateTotalSizeCharacteristic("e74dd9c0-a301-4a6f-95a1-f0e1dbea8e1e", BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_READ);
static BLECharacteristic swUpdateDataCharacteristic("e272ebac-d463-4b98-bc84-5cc1a39ee517", BLECharacteristic::PROPERTY_WRITE);
static BLECharacteristic swUpdateCRC32Characteristic("4826129c-c22a-43a3-b066-ce8f0d5bacc6", BLECharacteristic::PROPERTY_WRITE);
static BLECharacteristic swUpdateResultCharacteristic("5e134862-7411-4424-ac4a-210937432c77", BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
#include "CallbackCharacteristic.h"
CRC32 crc;
uint32_t rebootAtMsec = 0; // If not zero we will reboot at this time (used to reboot shortly after the update completes)
class UpdateCallbacks : public BLECharacteristicCallbacks
class TotalSizeCharacteristic : public CallbackCharacteristic
{
void onRead(BLECharacteristic *pCharacteristic) {
DEBUG_MSG("Got on read\n");
public:
TotalSizeCharacteristic()
: CallbackCharacteristic("e74dd9c0-a301-4a6f-95a1-f0e1dbea8e1e", BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_READ)
{
}
void onWrite(BLECharacteristic *pCharacteristic)
void onWrite(BLECharacteristic *c)
{
// dumpCharacteristic(pCharacteristic);
BLEKeepAliveCallbacks::onWrite(c);
if (pCharacteristic == &swUpdateTotalSizeCharacteristic)
{
// Check if there is enough to OTA Update
uint32_t len = getValue32(pCharacteristic, 0);
crc.reset();
bool canBegin = Update.begin(len);
DEBUG_MSG("Setting update size %u, result %d\n", len, canBegin);
if(!canBegin)
// Indicate failure by forcing the size to 0
pCharacteristic->setValue(0UL);
}
else if (pCharacteristic == &swUpdateDataCharacteristic)
{
std::string value = pCharacteristic->getValue();
uint32_t len = value.length();
uint8_t *data = pCharacteristic->getData();
// DEBUG_MSG("Writing %u\n", len);
crc.update(data, len);
Update.write(data, len);
}
else if (pCharacteristic == &swUpdateCRC32Characteristic)
{
uint32_t expectedCRC = getValue32(pCharacteristic, 0);
DEBUG_MSG("expected CRC %u\n", expectedCRC);
uint8_t result = 0xff;
// Check the CRC before asking the update to happen.
if(crc.finalize() != expectedCRC) {
DEBUG_MSG("Invalid CRC!\n");
result = 0xe0; // FIXME, use real error codes
}
else {
if (Update.end())
{
DEBUG_MSG("OTA done, rebooting in 5 seconds!\n");
rebootAtMsec = millis() + 5000;
}
else
{
DEBUG_MSG("Error Occurred. Error #: %d\n", Update.getError());
}
result = Update.getError();
}
swUpdateResultCharacteristic.setValue(&result, 1);
swUpdateResultCharacteristic.notify();
}
// Check if there is enough to OTA Update
uint32_t len = getValue32(c, 0);
crc.reset();
bool canBegin = Update.begin(len);
DEBUG_MSG("Setting update size %u, result %d\n", len, canBegin);
if (!canBegin)
// Indicate failure by forcing the size to 0
c->setValue(0UL);
else {
DEBUG_MSG("unexpected write\n");
// 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();
}
}
};
void bluetoothRebootCheck() {
if(rebootAtMsec && millis() > rebootAtMsec)
class DataCharacteristic : public CallbackCharacteristic
{
public:
DataCharacteristic()
: CallbackCharacteristic(
"e272ebac-d463-4b98-bc84-5cc1a39ee517", BLECharacteristic::PROPERTY_WRITE)
{
}
void onWrite(BLECharacteristic *c)
{
BLEKeepAliveCallbacks::onWrite(c);
std::string value = c->getValue();
uint32_t len = value.length();
uint8_t *data = c->getData();
// DEBUG_MSG("Writing %u\n", len);
crc.update(data, len);
Update.write(data, len);
}
};
static BLECharacteristic *resultC;
class CRC32Characteristic : public CallbackCharacteristic
{
public:
CRC32Characteristic()
: CallbackCharacteristic(
"4826129c-c22a-43a3-b066-ce8f0d5bacc6", BLECharacteristic::PROPERTY_WRITE)
{
}
void onWrite(BLECharacteristic *c)
{
BLEKeepAliveCallbacks::onWrite(c);
uint32_t expectedCRC = getValue32(c, 0);
DEBUG_MSG("expected CRC %u\n", expectedCRC);
uint8_t result = 0xff;
// Check the CRC before asking the update to happen.
if (crc.finalize() != expectedCRC)
{
DEBUG_MSG("Invalid CRC!\n");
result = 0xe0; // FIXME, use real error codes
}
else
{
if (Update.end())
{
DEBUG_MSG("OTA done, rebooting in 5 seconds!\n");
rebootAtMsec = millis() + 5000;
}
else
{
DEBUG_MSG("Error Occurred. Error #: %d\n", Update.getError());
}
result = Update.getError();
}
assert(resultC);
resultC->setValue(&result, 1);
resultC->notify();
}
};
void bluetoothRebootCheck()
{
if (rebootAtMsec && millis() > rebootAtMsec)
ESP.restart();
}
static UpdateCallbacks updateCb;
/*
SoftwareUpdateService UUID cb0b9a0b-a84c-4c0d-bdbb-442e3144ee30
See bluetooth-api.md
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
5e134862-7411-4424-ac4a-210937432c77 read|notify result code, readable but will notify when the OTA operation completes
*/
BLEService *createUpdateService(BLEServer* server) {
BLEService *createUpdateService(BLEServer *server, std::string hwVendor, std::string swVersion, std::string hwVersion)
{
// Create the BLE Service
BLEService *service = server->createService("cb0b9a0b-a84c-4c0d-bdbb-442e3144ee30");
BLEService *service = server->createService(BLEUUID("cb0b9a0b-a84c-4c0d-bdbb-442e3144ee30"), 25, 0);
addWithDesc(service, &swUpdateTotalSizeCharacteristic, "total image size");
addWithDesc(service, &swUpdateDataCharacteristic, "data");
addWithDesc(service, &swUpdateCRC32Characteristic, "crc32");
addWithDesc(service, &swUpdateResultCharacteristic, "result code");
assert(!resultC);
resultC = new BLECharacteristic("5e134862-7411-4424-ac4a-210937432c77", BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
swUpdateTotalSizeCharacteristic.setCallbacks(&updateCb);
swUpdateDataCharacteristic.setCallbacks(&updateCb);
swUpdateCRC32Characteristic.setCallbacks(&updateCb);
swUpdateResultCharacteristic.addDescriptor(new BLE2902()); // Needed so clients can request notification
addWithDesc(service, new TotalSizeCharacteristic, "total image size");
addWithDesc(service, new DataCharacteristic, "data");
addWithDesc(service, new CRC32Characteristic, "crc32");
addWithDesc(service, resultC, "result code");
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);
swC->setValue(swVersion);
service->addCharacteristic(addBLECharacteristic(swC));
BLECharacteristic *mfC = new BLECharacteristic(BLEUUID((uint16_t)ESP_GATT_UUID_MANU_NAME), BLECharacteristic::PROPERTY_READ);
mfC->setValue(hwVendor);
service->addCharacteristic(addBLECharacteristic(mfC));
BLECharacteristic *hwvC = new BLECharacteristic(BLEUUID((uint16_t)ESP_GATT_UUID_HW_VERSION_STR), BLECharacteristic::PROPERTY_READ);
hwvC->setValue(hwVersion);
service->addCharacteristic(addBLECharacteristic(hwvC));
return service;
}
void destroyUpdateService()
{
assert(resultC);
resultC = NULL;
}

View File

@@ -2,6 +2,7 @@
#include <Arduino.h>
BLEService *createUpdateService(BLEServer* server);
BLEService *createUpdateService(BLEServer* server, std::string hwVendor, std::string swVersion, std::string hwVersion);
void destroyUpdateService();
void bluetoothRebootCheck();

View File

@@ -7,10 +7,7 @@
#include "configuration.h"
#include "screen.h"
static BLECharacteristic SWVersionCharacteristic(BLEUUID((uint16_t)ESP_GATT_UUID_SW_VERSION_STR), BLECharacteristic::PROPERTY_READ);
static BLECharacteristic ManufacturerCharacteristic(BLEUUID((uint16_t)ESP_GATT_UUID_MANU_NAME), BLECharacteristic::PROPERTY_READ);
static BLECharacteristic HardwareVersionCharacteristic(BLEUUID((uint16_t)ESP_GATT_UUID_HW_VERSION_STR), BLECharacteristic::PROPERTY_READ);
//static BLECharacteristic SerialNumberCharacteristic(BLEUUID((uint16_t) ESP_GATT_UUID_SERIAL_NUMBER_STR), BLECharacteristic::PROPERTY_READ);
SimpleAllocator btPool;
/**
* Create standard device info service
@@ -19,6 +16,10 @@ BLEService *createDeviceInfomationService(BLEServer *server, std::string hwVendo
{
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?
@@ -28,14 +29,15 @@ BLEService *createDeviceInfomationService(BLEServer *server, std::string hwVendo
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));
*/
SWVersionCharacteristic.setValue(swVersion);
deviceInfoService->addCharacteristic(&SWVersionCharacteristic);
ManufacturerCharacteristic.setValue(hwVendor);
deviceInfoService->addCharacteristic(&ManufacturerCharacteristic);
swC->setValue(swVersion);
deviceInfoService->addCharacteristic(addBLECharacteristic(swC));
mfC->setValue(hwVendor);
deviceInfoService->addCharacteristic(addBLECharacteristic(mfC));
if (!hwVersion.empty())
{
HardwareVersionCharacteristic.setValue(hwVersion);
deviceInfoService->addCharacteristic(&HardwareVersionCharacteristic);
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);
@@ -66,6 +68,31 @@ class MyServerCallbacks : public BLEServerCallbacks
}
};
#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)
@@ -78,9 +105,11 @@ void addWithDesc(BLEService *service, BLECharacteristic *c, const char *descript
desc->setValue(description);
c->addDescriptor(desc);
service->addCharacteristic(c);
addBLECharacteristic(c);
addBLEDescriptor(desc);
}
static BLECharacteristic BatteryLevelCharacteristic(BLEUUID((uint16_t)ESP_GATT_UUID_BATTERY_LEVEL), BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
static BLECharacteristic *batteryLevelC;
/**
* Create a battery level service
@@ -90,8 +119,10 @@ BLEService *createBatteryService(BLEServer *server)
// Create the BLE Service
BLEService *pBattery = server->createService(BLEUUID((uint16_t)0x180F));
addWithDesc(pBattery, &BatteryLevelCharacteristic, "Percentage 0 - 100");
BatteryLevelCharacteristic.addDescriptor(new BLE2902()); // Needed so clients can request notification
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());
@@ -107,8 +138,11 @@ BLEService *createBatteryService(BLEServer *server)
void updateBatteryLevel(uint8_t level)
{
// Pretend to update battery levels - fixme do elsewhere
BatteryLevelCharacteristic.setValue(&level, 1);
BatteryLevelCharacteristic.notify();
if (batteryLevelC)
{
batteryLevelC->setValue(&level, 1);
batteryLevelC->notify();
}
}
void dumpCharacteristic(BLECharacteristic *c)
@@ -178,10 +212,49 @@ class MySecurity : public BLESecurityCallbacks
}
// Remove our custom screen
screen_set_frames();
screen.setFrames();
}
};
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(std::string deviceName, std::string hwVendor, std::string swVersion, std::string hwVersion)
{
BLEDevice::init(deviceName);
@@ -190,18 +263,20 @@ BLEServer *initBLE(std::string deviceName, std::string hwVendor, std::string swV
/*
* Required in authentication process to provide displaying and/or input passkey or yes/no butttons confirmation
*/
BLEDevice::setSecurityCallbacks(new MySecurity());
static MySecurity mySecurity;
BLEDevice::setSecurityCallbacks(&mySecurity);
// Create the BLE Server
BLEServer *pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
pServer = BLEDevice::createServer();
static MyServerCallbacks myCallbacks;
pServer->setCallbacks(&myCallbacks);
BLEService *pDevInfo = createDeviceInfomationService(pServer, hwVendor, swVersion, hwVersion);
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);
BLEService *pUpdate = createUpdateService(pServer); // We need to advertise this so our android ble scan operation can see it
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());
@@ -213,7 +288,8 @@ BLEServer *initBLE(std::string deviceName, std::string hwVendor, std::string swV
// 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
BLESecurity *pSecurity = new BLESecurity();
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);

View File

@@ -4,7 +4,7 @@
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include "SimpleAllocator.h"
// Now handled by BluetoothUtil.cpp
// BLEService *createDeviceInfomationService(BLEServer* server, uint8_t sig, uint16_t vid, uint16_t pid, uint16_t version);
@@ -18,4 +18,14 @@ void dumpCharacteristic(BLECharacteristic *c);
uint32_t getValue32(BLECharacteristic *c, uint32_t defaultValue);
void loopBLE();
BLEServer *initBLE(std::string devName, std::string hwVendor, std::string swVersion, std::string hwVersion = "");
BLEServer *initBLE(std::string devName, std::string hwVendor, std::string swVersion, std::string hwVersion = "");
void deinitBLE();
/// Add a characteristic that we will delete when we restart
BLECharacteristic *addBLECharacteristic(BLECharacteristic *c);
/// Add a characteristic that we will delete when we restart
BLEDescriptor *addBLEDescriptor(BLEDescriptor *c);
/// Any bluetooth objects you allocate _must_ come from this pool if you want to be able to call deinitBLE()
extern SimpleAllocator btPool;

View File

@@ -0,0 +1,33 @@
#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);
}
};

View File

@@ -0,0 +1,60 @@
#include "SimpleAllocator.h"
#include "assert.h"
SimpleAllocator::SimpleAllocator() { reset(); }
void *SimpleAllocator::alloc(size_t size)
{
assert(nextFree + size <= sizeof(bytes));
void *res = &bytes[nextFree];
nextFree += size;
Serial.printf("Total simple allocs %u\n", nextFree);
return res;
}
void SimpleAllocator::reset() { nextFree = 0; }
void *operator new(size_t size, SimpleAllocator &p)
{
return p.alloc(size);
}
#if 0
// This was a dumb idea, turn off for now
SimpleAllocator *activeAllocator;
AllocatorScope::AllocatorScope(SimpleAllocator &a)
{
assert(!activeAllocator);
activeAllocator = &a;
}
AllocatorScope::~AllocatorScope()
{
assert(activeAllocator);
activeAllocator = NULL;
}
/// Global new/delete, uses a simple allocator if it is in scope
void *operator new(size_t sz) throw(std::bad_alloc)
{
void *mem = activeAllocator ? activeAllocator->alloc(sz) : malloc(sz);
if (mem)
return mem;
else
throw std::bad_alloc();
}
void operator delete(void *ptr) throw()
{
if (activeAllocator)
Serial.println("Warning: leaking an active allocator object"); // We don't properly handle this yet
else
free(ptr);
}
#endif

View File

@@ -0,0 +1,42 @@
#pragma once
#include <Arduino.h>
#define POOL_SIZE 16384
/**
* An allocator (and placement new operator) that allocates storage from a fixed sized buffer.
* It will panic if that buffer fills up.
* If you are _sure_ no outstanding references to blocks in this buffer still exist, you can call
* reset() to start from scratch.
*
* Currently the only usecase for this class is the ESP32 bluetooth stack, where once we've called deinit(false)
* we are sure all those bluetooth objects no longer exist, and we'll need to recreate them when we restart bluetooth
*/
class SimpleAllocator
{
uint8_t bytes[POOL_SIZE];
uint32_t nextFree;
public:
SimpleAllocator();
void *alloc(size_t size);
/** If you are _sure_ no outstanding references to blocks in this buffer still exist, you can call
* reset() to start from scratch.
* */
void reset();
};
void *operator new(size_t size, SimpleAllocator &p);
/**
* Temporarily makes the specified Allocator be used for _all_ allocations. Useful when calling library routines
* that don't know about pools
*/
class AllocatorScope {
public:
AllocatorScope(SimpleAllocator &a);
~AllocatorScope();
};

View File

@@ -1 +0,0 @@
../../RadioHead

View File

@@ -1 +0,0 @@
../MeshUtil/app/src/main/proto/mesh.options

View File

@@ -1 +0,0 @@
../MeshUtil/app/src/main/proto/mesh.proto

View File

@@ -21,7 +21,8 @@ framework = arduino
board_build.partitions = partition-table.csv
; note: we add src to our include search path so that lmic_project_config can override
build_flags = -Wall -Wextra -Wno-missing-field-initializers -Isrc -Os -Wl,-Map,.pio/build/esp32/output.map -DAXP_DEBUG_PORT=Serial
; FIXME: fix lib/BluetoothOTA dependency back on src/ so we can remove -Isrc
build_flags = -Wall -Wextra -Wno-missing-field-initializers -Isrc -Os -Wl,-Map,.pio/build/esp32/output.map -DAXP_DEBUG_PORT=Serial
; 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
@@ -54,20 +55,22 @@ debug_tool = jlink
debug_init_break = tbreak setup
; Note: some libraries are specified by #ID where there are conflicting library
; names.
lib_deps =
; RadioHead - I now use a custom build of this library
; file:///home/kevinh/development/meshtastic/RadioHead
TinyGPSPlus
https://github.com/geeksville/esp8266-oled-ssd1306.git ; ESP8266_SSD1306
https://github.com/meshtastic/RadioHead.git
1655 ; TinyGPSPlus
https://github.com/meshtastic/esp8266-oled-ssd1306.git ; ESP8266_SSD1306
AXP202X_Library
SPI
OneButton
CRC32 ; explicitly needed because dependency is missing in the ble ota update lib
1260 ; OneButton
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
;[env:tbeam]
;board = ttgo-t-beam
;[env:heltec]
;build_type = debug ; to make it possible to step through our jtag debugger
;board = heltec_wifi_lora_32_V2
;board = heltec_wifi_lora_32_V2

1
proto Submodule

Submodule proto added at 66e926740a

4
release/.gitignore vendored
View File

@@ -1 +1,3 @@
*.bin
*.bin
*.map
*.zip

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- This file is kept in source control because it reflects the last stable
release. It is used by the android app for forcing software updates. Do not edit.
Generated by bin/buildall.sh -->
<resources>
<string name="cur_firmware_version">0.1.3</string>
</resources>

View File

@@ -18,6 +18,21 @@ CustomRF95::CustomRF95(MemoryPool<MeshPacket> &_pool, PointerQueue<MeshPacket> &
{
}
bool CustomRF95::canSleep()
{
// We allow initializing mode, because sometimes while testing we don't ever call init() to turn on the hardware
return (_mode == RHModeInitialising || _mode == RHModeIdle || _mode == RHModeRx) && !_isReceiving && txQueue.isEmpty();
}
bool CustomRF95::sleep()
{
// we no longer care about interrupts from this device
prepareDeepSleep();
// FIXME - leave the device state in rx mode instead
return RH_RF95::sleep();
}
bool CustomRF95::init()
{
bool ok = RH_RF95::init();
@@ -30,12 +45,10 @@ bool CustomRF95::init()
/// bluetooth comms code. If the txmit queue is empty it might return an error
ErrorCode CustomRF95::send(MeshPacket *p)
{
// FIXME - we currently just slam over into send mode if the RF95 is in RX mode. This is _probably_ safe given
// how quiet our network is, bu it would be better to wait _if_ we are partially though receiving a packet (rather than
// just merely waiting for one).
// This is doubly bad because not only do we drop the packet that was on the way in, we almost certainly guarantee no one
// outside will like the packet we are sending.
if (_mode == RHModeIdle || _mode == RHModeRx)
// We wait _if_ we are partially though receiving a packet (rather than just merely waiting for one).
// To do otherwise would be doubly bad because not only would we drop the packet that was on the way in,
// we almost certainly guarantee no one outside will like the packet we are sending.
if (_mode == RHModeIdle || (_mode == RHModeRx && !_isReceiving))
{
// if the radio is idle, we can send right away
DEBUG_MSG("immedate send on mesh (txGood=%d,rxGood=%d,rxBad=%d)\n", txGood(), rxGood(), rxBad());
@@ -127,7 +140,10 @@ void CustomRF95::handleInterrupt()
portYIELD_FROM_ISR();
}
/// Return true if a higher pri task has woken
/** The ISR doesn't have any good work to do, give a new assignment.
*
* Return true if a higher pri task has woken
*/
bool CustomRF95::handleIdleISR()
{
BaseType_t higherPriWoken = false;

View File

@@ -15,6 +15,8 @@
*/
class CustomRF95 : public RH_RF95
{
friend class MeshRadio; // for debugging we let that class touch pool
MemoryPool<MeshPacket> &pool;
PointerQueue<MeshPacket> &rxDest;
PointerQueue<MeshPacket> txQueue;
@@ -26,6 +28,16 @@ public:
*/
CustomRF95(MemoryPool<MeshPacket> &pool, PointerQueue<MeshPacket> &rxDest);
/**
* Return true if we think the board can go to sleep (i.e. our tx queue is empty, we are not sending or receiving)
*
* This method must be used before putting the CPU into deep or light sleep.
*/
bool canSleep();
/// Prepare hardware for sleep. Call this _only_ for deep sleep, not needed for light sleep.
virtual bool sleep();
/// Send a packet (possibly by enquing in a private fifo). This routine will
/// later free() the packet to pool. This routine is not allowed to stall because it is called from
/// bluetooth comms code. If the txmit queue is empty it might return an error

View File

@@ -2,17 +2,20 @@
#include "GPS.h"
#include "time.h"
#include <sys/time.h>
#include "configuration.h"
// stuff that really should be in in the instance instead...
HardwareSerial _serial_gps(GPS_SERIAL_NUM);
uint32_t timeStartMsec; // Once we have a GPS lock, this is where we hold the initial msec clock that corresponds to that time
uint64_t zeroOffsetSecs; // GPS based time in secs since 1970 - only updated once on initial lock
RTC_DATA_ATTR bool timeSetFromGPS; // We only reset our time once per _boot_ after that point just run from the internal clock (even across sleeps)
RTC_DATA_ATTR bool timeSetFromGPS; // We only reset our time once per _boot_ after that point just run from the internal clock (even across sleeps)
GPS gps;
bool hasValidLocation; // default to false, until we complete our first read
bool wantNewLocation = true;
GPS::GPS() : PeriodicTask(30 * 1000)
GPS::GPS() : PeriodicTask()
{
}
@@ -57,17 +60,54 @@ void GPS::perhapsSetRTC(const struct timeval *tv)
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 !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()
{
// discard all rx serial bytes so we don't try to parse them when we come back
while (_serial_gps.available())
{
_serial_gps.read();
}
// make the parser bail on whatever it was parsing
encode('\n');
}
void GPS::doTask()
{
#ifdef GPS_RX_PIN
// Consume all characters that have arrived
while (_serial_gps.available())
{
encode(_serial_gps.read());
// DEBUG_MSG("Got GPS response\n");
}
if (!timeSetFromGPS && time.isValid() && date.isValid())
{
struct timeval tv;
DEBUG_MSG("Got time from GPS\n");
/* 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).
*/
@@ -86,25 +126,26 @@ void GPS::loop()
perhapsSetRTC(&tv);
}
#endif
}
uint32_t GPS::getTime()
{
return ((millis() - timeStartMsec) / 1000) + zeroOffsetSecs;
}
uint32_t GPS::getValidTime()
{
return timeSetFromGPS ? getTime() : 0;
}
void GPS::doTask()
{
if (location.isValid() && location.isUpdated())
{ // we only notify if position has changed
// DEBUG_MSG("new gps pos\n");
hasValidLocation = true;
wantNewLocation = false;
notifyObservers();
}
else // we didn't get a location update, go back to sleep and hope the characters show up
wantNewLocation = true;
// Once we have sent a location once we only poll the GPS rarely, otherwise check back every 100ms until we have something over the serial
setPeriod(hasValidLocation && !wantNewLocation ? 30 * 1000 : 100);
}
void GPS::startLock()
{
DEBUG_MSG("Looking for GPS lock\n");
wantNewLocation = true;
setPeriod(1);
}
String GPS::getTimeStr()

View File

@@ -32,6 +32,15 @@ public:
/// 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();
private:
void readFromRTC();
};

View File

@@ -10,18 +10,20 @@
#include "mesh-pb-constants.h"
#include "NodeDB.h"
#include "configuration.h"
#include "PowerFSM.h"
#include "CallbackCharacteristic.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 BLECharacteristic, public BLECharacteristicCallbacks
class ProtobufCharacteristic : public CallbackCharacteristic
{
const pb_msgdesc_t *fields;
void *my_struct;
public:
ProtobufCharacteristic(const char *uuid, uint32_t btprops, const pb_msgdesc_t *_fields, void *_my_struct)
: BLECharacteristic(uuid, btprops),
: CallbackCharacteristic(uuid, btprops),
fields(_fields),
my_struct(_my_struct)
{
@@ -30,13 +32,15 @@ public:
void onRead(BLECharacteristic *c)
{
DEBUG_MSG("Got proto read\n");
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);
}
@@ -47,13 +51,13 @@ protected:
bool writeToDest(BLECharacteristic *c, void *dest)
{
// dumpCharacteristic(pCharacteristic);
DEBUG_MSG("Got on proto write\n");
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 BLECharacteristicCallbacks
class NodeInfoCharacteristic : public BLECharacteristic, public BLEKeepAliveCallbacks
{
public:
NodeInfoCharacteristic()
@@ -64,6 +68,8 @@ public:
void onRead(BLECharacteristic *c)
{
BLEKeepAliveCallbacks::onRead(c);
const NodeInfo *info = nodeDB.readNextInfo();
if (info)
@@ -81,8 +87,8 @@ public:
void onWrite(BLECharacteristic *c)
{
// dumpCharacteristic(pCharacteristic);
DEBUG_MSG("Got on nodeinfo write\n");
BLEKeepAliveCallbacks::onWrite(c);
DEBUG_MSG("Reset nodeinfo read pointer\n");
nodeDB.resetReadPointer();
}
};
@@ -114,6 +120,8 @@ public:
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))
{
@@ -141,167 +149,145 @@ public:
}
};
static BLECharacteristic
meshFromRadioCharacteristic("8ba2bcc2-ee02-4a55-a531-c525c5e454d5", BLECharacteristic::PROPERTY_READ),
meshToRadioCharacteristic("f75c76d2-129e-4dad-a1dd-7866124401e7", BLECharacteristic::PROPERTY_WRITE),
meshFromNumCharacteristic("ed9da18c-a800-4f66-a670-aa7547e34453", BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
class ToRadioCharacteristic : public CallbackCharacteristic
{
public:
ToRadioCharacteristic()
: CallbackCharacteristic("f75c76d2-129e-4dad-a1dd-7866124401e7", BLECharacteristic::PROPERTY_WRITE)
{
}
static NodeInfoCharacteristic meshNodeInfoCharacteristic;
void onWrite(BLECharacteristic *c)
{
BLEKeepAliveCallbacks::onWrite(c);
DEBUG_MSG("Got on write\n");
static ProtobufCharacteristic
meshMyNodeCharacteristic("ea9f3f82-8dc4-4733-9452-1f6da28892a2", BLECharacteristic::PROPERTY_READ, MyNodeInfo_fields, &myNodeInfo);
service.handleToRadio(c->getValue());
}
};
static OwnerCharacteristic meshOwnerCharacteristic;
static RadioCharacteristic meshRadioCharacteristic;
class FromRadioCharacteristic : public CallbackCharacteristic
{
public:
FromRadioCharacteristic()
: CallbackCharacteristic("8ba2bcc2-ee02-4a55-a531-c525c5e454d5", BLECharacteristic::PROPERTY_READ)
{
}
void onRead(BLECharacteristic *c)
{
BLEKeepAliveCallbacks::onRead(c);
MeshPacket *mp = service.getForPhone();
// 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);
}
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
}
}
};
class FromNumCharacteristic : public CallbackCharacteristic
{
public:
FromNumCharacteristic()
: CallbackCharacteristic("ed9da18c-a800-4f66-a670-aa7547e34453",
BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY)
{
}
void onRead(BLECharacteristic *c)
{
BLEKeepAliveCallbacks::onRead(c);
DEBUG_MSG("FIXME implement fromnum read\n");
}
};
FromNumCharacteristic *meshFromNumCharacteristic;
/**
* Tell any bluetooth clients that the number of rx packets has changed
*/
void bluetoothNotifyFromNum(uint32_t newValue)
{
meshFromNumCharacteristic.setValue(newValue);
meshFromNumCharacteristic.notify();
if (meshFromNumCharacteristic)
{
// if bt not running ignore
meshFromNumCharacteristic->setValue(newValue);
meshFromNumCharacteristic->notify();
}
}
class BluetoothMeshCallbacks : public BLECharacteristicCallbacks
{
void onRead(BLECharacteristic *c)
{
DEBUG_MSG("Got on read\n");
if (c == &meshFromRadioCharacteristic)
{
MeshPacket *mp = service.getForPhone();
// 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);
}
else
{
DEBUG_MSG("delivering toPhone packet to phone\n");
static FromRadio fradio;
// Encapsulate as a ToRadio packet
memset(&fradio, 0, sizeof(fradio));
fradio.which_variant = FromRadio_packet_tag;
fradio.variant.packet = *mp;
service.releaseToPool(mp); // we just copied the bytes, so don't need this buffer anymore
size_t numbytes = pb_encode_to_bytes(trBytes, sizeof(trBytes), FromRadio_fields, &fradio);
c->setValue(trBytes, numbytes);
}
}
else
{
// we are uninterested in the other reads
}
}
void onWrite(BLECharacteristic *c)
{
// dumpCharacteristic(pCharacteristic);
DEBUG_MSG("Got on write\n");
if (c == &meshToRadioCharacteristic)
{
service.handleToRadio(c->getValue());
}
else
{
// we are uninterested in the other writes
}
}
};
static BluetoothMeshCallbacks btMeshCb;
BLEService *meshService;
/*
MeshBluetoothService UUID 6ba1b218-15a8-461f-9fa8-5dcae273eafd
FIXME - notify vs indication for fromradio output. Using notify for now, not sure if that is best
FIXME - in the esp32 mesh managment code, occasionally mirror the current net db to flash, so that if we reboot we still have a good guess of users who are out there.
FIXME - make sure this protocol is guaranteed robust and won't drop packets
"According to the BLE specification the notification length can be max ATT_MTU - 3. The 3 bytes subtracted is the 3-byte header(OP-code (operation, 1 byte) and the attribute handle (2 bytes)).
In BLE 4.1 the ATT_MTU is 23 bytes (20 bytes for payload), but in BLE 4.2 the ATT_MTU can be negotiated up to 247 bytes."
MAXPACKET is 256? look into what the lora lib uses. FIXME
Characteristics:
UUID
properties
description
8ba2bcc2-ee02-4a55-a531-c525c5e454d5
read
fromradio - contains a newly received packet destined towards the phone (up to MAXPACKET bytes? per packet).
After reading the esp32 will put the next packet in this mailbox. If the FIFO is empty it will put an empty packet in this
mailbox.
f75c76d2-129e-4dad-a1dd-7866124401e7
write
toradio - write ToRadio protobufs to this charstic to send them (up to MAXPACKET len)
ed9da18c-a800-4f66-a670-aa7547e34453
read|notify|write
fromnum - the current packet # in the message waiting inside fromradio, if the phone sees this notify it should read messages
until it catches up with this number.
The phone can write to this register to go backwards up to FIXME packets, to handle the rare case of a fromradio packet was dropped after the esp32
callback was called, but before it arrives at the phone. If the phone writes to this register the esp32 will discard older packets and put the next packet >= fromnum in fromradio.
When the esp32 advances fromnum, it will delay doing the notify by 100ms, in the hopes that the notify will never actally need to be sent if the phone is already pulling from fromradio.
Note: that if the phone ever sees this number decrease, it means the esp32 has rebooted.
meshMyNodeCharacteristic("ea9f3f82-8dc4-4733-9452-1f6da28892a2", BLECharacteristic::PROPERTY_READ)
mynode - read this to access a MyNodeInfo protobuf
meshNodeInfoCharacteristic("d31e02e0-c8ab-4d3f-9cc9-0b8466bdabe8", BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_READ),
nodeinfo - read this to get a series of node infos (ending with a null empty record), write to this to restart the read statemachine that returns all the node infos
meshRadioCharacteristic("b56786c8-839a-44a1-b98e-a1724c4a0262", BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_READ),
radio - read/write this to access a RadioConfig protobuf
meshOwnerCharacteristic("6ff1d8b6-e2de-41e3-8c0b-8fa384f64eb6", BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_READ)
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
A variable keepAllPackets, if set to true will suppress this behavior and instead keep everything for forwarding to the phone (for debugging)
See bluetooth-api.md for documentation.
*/
BLEService *createMeshBluetoothService(BLEServer *server)
{
// Create the BLE Service, we need more than the default of 15 handles
BLEService *service = server->createService(BLEUUID("6ba1b218-15a8-461f-9fa8-5dcae273eafd"), 25, 0);
addWithDesc(service, &meshFromRadioCharacteristic, "fromRadio");
addWithDesc(service, &meshToRadioCharacteristic, "toRadio");
addWithDesc(service, &meshFromNumCharacteristic, "fromNum");
assert(!meshFromNumCharacteristic);
meshFromNumCharacteristic = new FromNumCharacteristic;
meshFromRadioCharacteristic.setCallbacks(&btMeshCb);
meshToRadioCharacteristic.setCallbacks(&btMeshCb);
meshFromNumCharacteristic.setCallbacks(&btMeshCb);
addWithDesc(service, meshFromNumCharacteristic, "fromRadio");
addWithDesc(service, new ToRadioCharacteristic, "toRadio");
addWithDesc(service, new FromRadioCharacteristic, "fromNum");
addWithDesc(service, &meshMyNodeCharacteristic, "myNode");
addWithDesc(service, &meshRadioCharacteristic, "radio");
addWithDesc(service, &meshOwnerCharacteristic, "owner");
addWithDesc(service, &meshNodeInfoCharacteristic, "nodeinfo");
addWithDesc(service, new ProtobufCharacteristic("ea9f3f82-8dc4-4733-9452-1f6da28892a2", BLECharacteristic::PROPERTY_READ, MyNodeInfo_fields, &myNodeInfo), "myNode");
addWithDesc(service, new RadioCharacteristic, "radio");
addWithDesc(service, new OwnerCharacteristic, "owner");
addWithDesc(service, new NodeInfoCharacteristic, "nodeinfo");
meshFromNumCharacteristic.addDescriptor(new BLE2902()); // Needed so clients can request notification
meshFromNumCharacteristic->addDescriptor(addBLEDescriptor(new BLE2902())); // Needed so clients can request notification
service->start();
server->getAdvertising()->addServiceUUID(service->getUUID());
// We only add to advertisting once, because the ESP32 arduino code is dumb and that object never dies
static bool firstTime = true;
if (firstTime)
{
firstTime = false;
server->getAdvertising()->addServiceUUID(service->getUUID());
}
DEBUG_MSG("*** Mesh service:\n");
service->dump();
meshService = service;
return service;
}
void stopMeshBluetoothService()
{
assert(meshService);
meshService->stop();
}
void destroyMeshBluetoothService()
{
assert(meshService);
delete meshService;
meshFromNumCharacteristic = NULL;
}

View File

@@ -5,8 +5,11 @@
#include <Arduino.h>
BLEService *createMeshBluetoothService(BLEServer* server);
void destroyMeshBluetoothService();
/**
* Tell any bluetooth clients that the number of rx packets has changed
*/
void bluetoothNotifyFromNum(uint32_t newValue);
void stopMeshBluetoothService();

View File

@@ -25,6 +25,9 @@ The band is from 902 to 928 MHz. It mentions channel number and its respective c
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(MemoryPool<MeshPacket> &_pool, PointerQueue<MeshPacket> &_rxDest)
: rf95(_pool, _rxDest),
manager(rf95)
@@ -45,6 +48,9 @@ MeshRadio::MeshRadio(MemoryPool<MeshPacket> &_pool, PointerQueue<MeshPacket> &_r
bool MeshRadio::init()
{
if (!useHardware)
return true;
DEBUG_MSG("Starting meshradio init...\n");
#ifdef RESET_GPIO
@@ -109,138 +115,18 @@ void MeshRadio::reloadConfig()
rf95.setModeRx();
}
void MeshRadio::sleep()
{
// we no longer care about interrupts from this device
rf95.prepareDeepSleep();
// FIXME - leave the device state in rx mode instead
rf95.sleep();
}
ErrorCode MeshRadio::send(MeshPacket *p)
{
#if 1
return rf95.send(p);
#else
DEBUG_MSG("enquing packet for send from=0x%x, to=0x%x\n", p->from, p->to);
return txQueue.enqueue(p, 0); // nowait
#endif
if (useHardware)
return rf95.send(p);
else
{
rf95.pool.release(p);
return ERRNO_OK;
}
}
#if 0
ErrorCode MeshRadio::sendTo(NodeNum dest, const uint8_t *buf, size_t len)
{
// We must do this before each send, because we might have just changed our nodenum
manager.setThisAddress(nodeDB.getNodeNum()); // Note: we must do this here, because the nodenum isn't inited at constructor time.
assert(len <= 251); // Make sure we don't overflow the tiny max packet size
uint32_t start = millis();
// Note: we don't use sendToWait here because we don't want to wait and for the time being don't require
// reliable delivery
// return manager.sendtoWait((uint8_t *) buf, len, dest);
ErrorCode res = manager.sendto((uint8_t *)buf, len, dest) ? ERRNO_OK : ERRNO_UNKNOWN;
// FIXME, we have to wait for sending to complete before freeing the buffer, otherwise it might get wiped
// instead just have the radiohead layer understand queues.
if (res == ERRNO_OK)
manager.waitPacketSent();
DEBUG_MSG("mesh sendTo %d bytes to 0x%x (%lu msecs)\n", len, dest, millis() - start);
return res;
}
/// enqueue a received packet in rxDest
void MeshRadio::handleReceive(MeshPacket *mp)
{
int res = rxDest.enqueue(mp, 0); // NOWAIT - fixme, if queue is full, delete older messages
assert(res == pdTRUE);
}
#endif
void MeshRadio::loop()
{
// FIXME read from radio with recvfromAckTimeout
#if 0
static int16_t packetnum = 0; // packet counter, we increment per xmission
char radiopacket[20] = "Hello World # ";
sprintf(radiopacket, "hello %d", packetnum++);
assert(sendTo(NODENUM_BROADCAST, (uint8_t *)radiopacket, sizeof(radiopacket)) == ERRNO_OK);
#endif
#if 0
/// A temporary buffer used for sending/receving packets, sized to hold the biggest buffer we might need
#define MAX_RHPACKETLEN 251
static uint8_t radiobuf[MAX_RHPACKETLEN];
uint8_t rxlen;
uint8_t srcaddr, destaddr, id, flags;
// Poll to see if we've received a packet
// if (manager.recvfromAckTimeout(radiobuf, &rxlen, 0, &srcaddr, &destaddr, &id, &flags))
// prefill rxlen with the max length we can accept - very important
rxlen = (uint8_t) MAX_RHPACKETLEN;
if (manager.recvfrom(radiobuf, &rxlen, &srcaddr, &destaddr, &id, &flags))
{
// We received a packet
int32_t freqerr = rf95.frequencyError(), snr = rf95.lastSNR();
DEBUG_MSG("Received packet from mesh src=0x%x,dest=0x%x,id=%d,len=%d rxGood=%d,rxBad=%d,freqErr=%d,snr=%d\n",
srcaddr, destaddr, id, rxlen, rf95.rxGood(), rf95.rxBad(), freqerr, snr);
MeshPacket *mp = pool.allocZeroed();
SubPacket *p = &mp->payload;
mp->from = srcaddr;
mp->to = destaddr;
// If we already have an entry in the DB for this nodenum, goahead and hide the snr/freqerr info there.
// Note: we can't create it at this point, because it might be a bogus User node allocation. But odds are we will
// already have a record we can hide this debugging info in.
NodeInfo *info = nodeDB.getNode(mp->from);
if (info)
{
info->snr = snr;
info->frequency_error = freqerr;
}
if (!pb_decode_from_bytes(radiobuf, rxlen, SubPacket_fields, p))
{
pool.release(mp);
}
else
{
// parsing was successful, queue for our recipient
mp->has_payload = true;
handleReceive(mp);
}
}
#endif
#if 0
// Poll to see if we need to send any packets
MeshPacket *txp = txQueue.dequeuePtr(0); // nowait
if (txp)
{
DEBUG_MSG("sending queued packet on mesh (txGood=%d,rxGood=%d,rxBad=%d)\n", rf95.txGood(), rf95.rxGood(), rf95.rxBad());
assert(txp->has_payload);
size_t numbytes = pb_encode_to_bytes(radiobuf, sizeof(radiobuf), SubPacket_fields, &txp->payload);
int res = sendTo(txp->to, radiobuf, numbytes);
assert(res == ERRNO_OK);
bool loopbackTest = false; // if true we will pretend to receive any packets we just sent
if (loopbackTest)
handleReceive(txp);
else
pool.release(txp);
DEBUG_MSG("Done with send\n");
}
#endif
// Currently does nothing, since we do it all in ISRs now
}

View File

@@ -13,18 +13,23 @@
#define CH_SPACING_US 2.16f // MHz
#define NUM_CHANNELS_US 13
// EU channel settings
#define CH0_EU 865.2f // MHz
#define CH_SPACING_EU 0.3f // MHz
#define NUM_CHANNELS_EU 10
// 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 470f // MHz
#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
// CN channel settings
#define CH0_JP 920f // MHz
// 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
@@ -33,10 +38,14 @@
#define CH0 CH0_US
#define CH_SPACING CH_SPACING_US
#define NUM_CHANNELS NUM_CHANNELS_US
#elif defined(HW_VERSION_EU)
#define CH0 CH0_EU
#define CH_SPACING CH_SPACING_EU
#define NUM_CHANNELS NUM_CHANNELS_EU
#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
@@ -55,6 +64,8 @@
*/
class MeshRadio {
public:
CustomRF95 rf95; // the raw radio interface - for now I'm leaving public - because this class is shrinking to be almost nothing
/** 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
*/
@@ -62,9 +73,6 @@ public:
bool init();
/// Prepare the radio to enter sleep mode, where it should draw only 0.2 uA
void sleep();
/// Send a packet (possibly by enquing in a private fifo). This routine will
/// later free() the packet to pool. This routine is not allowed to stall because it is called from
/// bluetooth comms code. If the txmit queue is empty it might return an error
@@ -78,7 +86,6 @@ public:
void reloadConfig();
private:
CustomRF95 rf95; // the raw radio interface
// RHDatagram manager;
// RHReliableDatagram manager; // don't use mesh yet

View File

@@ -8,6 +8,8 @@
#include "NodeDB.h"
#include "GPS.h"
#include "screen.h"
#include "Periodic.h"
#include "PowerFSM.h"
/*
receivedPacketQueue - this is a queue of messages we've received from the mesh, which we are keeping to deliver to the phone.
@@ -60,7 +62,9 @@ void MeshService::init()
DEBUG_MSG("radio init failed\n");
gps.addObserver(this);
sendOurOwner();
// No need to call this here, our periodic task will fire quite soon
// sendOwnerPeriod();
}
void MeshService::sendOurOwner(NodeNum dest)
@@ -120,10 +124,35 @@ MeshPacket *MeshService::handleFromRadioUser(MeshPacket *mp)
return mp;
}
void MeshService::handleIncomingPosition(MeshPacket *mp)
{
if (mp->has_payload && mp->payload.which_variant == SubPacket_position_tag)
{
DEBUG_MSG("handled incoming position time=%u\n", mp->payload.variant.position.time);
if (mp->payload.variant.position.time)
{
struct timeval tv;
uint32_t secs = mp->payload.variant.position.time;
tv.tv_sec = secs;
tv.tv_usec = 0;
gps.perhapsSetRTC(&tv);
}
}
}
void MeshService::handleFromRadio(MeshPacket *mp)
{
powerFSM.trigger(EVENT_RECEIVED_PACKET); // Possibly keep the node from sleeping
mp->rx_time = gps.getValidTime(); // store the arrival timestamp for the phone
// If it is a position packet, perhaps set our clock (if we don't have a GPS of our own, otherwise wait for that to work)
if (!myNodeInfo.has_gps)
handleIncomingPosition(mp);
if (mp->has_payload && mp->payload.which_variant == SubPacket_user_tag)
{
mp = handleFromRadioUser(mp);
@@ -146,7 +175,7 @@ void MeshService::handleFromRadio(MeshPacket *mp)
}
assert(toPhoneQueue.enqueue(mp, 0) == pdTRUE); // FIXME, instead of failing for full queue, delete the oldest mssages
if(mp->payload.want_response)
if (mp->payload.want_response)
sendNetworkPing(mp->from);
}
else
@@ -165,6 +194,15 @@ void MeshService::handleFromRadio()
bluetoothNotifyFromNum(fromNum);
}
uint32_t sendOwnerCb()
{
service.sendOurOwner();
return radioConfig.preferences.send_owner_interval * radioConfig.preferences.position_broadcast_secs * 1000;
}
Periodic sendOwnerPeriod(sendOwnerCb);
/// Do idle processing (mostly processing messages which have been queued from the radio)
void MeshService::loop()
{
@@ -173,13 +211,7 @@ void MeshService::loop()
handleFromRadio();
// occasionally send our owner info
static uint32_t lastsend;
uint32_t now = millis();
if (now - lastsend > radioConfig.preferences.send_owner_secs * 1000)
{
lastsend = now;
sendOurOwner();
}
sendOwnerPeriod.loop();
}
/// The radioConfig object just changed, call this to force the hw to change to the new settings
@@ -202,17 +234,7 @@ void MeshService::handleToRadio(std::string s)
case ToRadio_packet_tag:
{
// If our phone is sending a position, see if we can use it to set our RTC
if (r.variant.packet.has_payload && r.variant.packet.payload.which_variant == SubPacket_position_tag && r.variant.packet.payload.variant.position.time)
{
struct timeval tv;
uint32_t secs = r.variant.packet.payload.variant.position.time;
// FIXME, this is a shit not right version of the standard def of unix time!!!
tv.tv_sec = secs;
tv.tv_usec = 0;
gps.perhapsSetRTC(&tv);
}
handleIncomingPosition(&r.variant.packet); // If it is a position packet, perhaps set our clock
r.variant.packet.rx_time = gps.getValidTime(); // Record the time the packet arrived from the phone (so we update our nodedb for the local node)
@@ -240,8 +262,14 @@ void MeshService::sendToMesh(MeshPacket *p)
nodeDB.updateFrom(*p); // update our local DB for this packet (because phone might have sent position packets etc...)
// Strip out any time information before sending packets to other nodes - to keep the wire size small (and because other nodes shouldn't trust it anyways)
// Note: for now, we allow a device with a local GPS to include the time, so that gpsless devices can get time.
if (p->has_payload && p->payload.which_variant == SubPacket_position_tag)
p->payload.variant.position.time = 0;
{
if (!myNodeInfo.has_gps)
p->payload.variant.position.time = 0;
else
DEBUG_MSG("Providing time to mesh %u\n", p->payload.variant.position.time);
}
// If the phone sent a packet just to us, don't send it out into the network
if (p->to == nodeDB.getNodeNum())
@@ -288,8 +316,7 @@ void MeshService::sendOurPosition(NodeNum dest)
p->to = dest;
p->payload.which_variant = SubPacket_position_tag;
p->payload.variant.position = node->position;
// FIXME - for now we are leaving this in the sent packets (for debugging)
//p->payload.variant.position.time = 0; // No need to send time, other node won't trust it anyways
p->payload.variant.position.time = gps.getValidTime(); // This nodedb timestamp might be stale, so update it if our clock is valid.
sendToMesh(p);
}

View File

@@ -86,6 +86,9 @@ private:
/// handle a user packet that just arrived on the radio, return NULL if we should not process this packet at all
MeshPacket *handleFromRadioUser(MeshPacket *mp);
/// look at inbound packets and if they contain a position with time, possibly set our clock
void handleIncomingPosition(MeshPacket *mp);
};
extern MeshService service;

View File

@@ -11,6 +11,7 @@
#include "mesh-pb-constants.h"
#include "NodeDB.h"
#include "GPS.h"
#include "PowerFSM.h"
NodeDB nodeDB;
@@ -20,6 +21,14 @@ MyNodeInfo &myNodeInfo = devicestate.my_node;
RadioConfig &radioConfig = devicestate.radio;
ChannelSettings &channelSettings = radioConfig.channel_settings;
/*
DeviceState versions used to be defined in the .proto file but really only this function cares. So changed to a
#define here.
*/
#define DEVICESTATE_CUR_VER 2
#define DEVICESTATE_MIN_VER DEVICESTATE_CUR_VER
#define FS SPIFFS
/**
@@ -49,13 +58,23 @@ void NodeDB::init()
devicestate.node_db_count = 0;
devicestate.receive_queue_count = 0;
radioConfig.preferences.send_owner_secs = 60 * 60; // default to once an hour
radioConfig.preferences.position_broadcast_secs = 15 * 60; // default to once every 15 mins
radioConfig.preferences.send_owner_interval = 4; // per sw-design.md
radioConfig.preferences.position_broadcast_secs = 15 * 60;
radioConfig.preferences.wait_bluetooth_secs = 120;
radioConfig.preferences.screen_on_secs = 30;
radioConfig.preferences.mesh_sds_timeout_secs = 2 * 60 * 60;
radioConfig.preferences.phone_sds_timeout_sec = 2 * 60 * 60;
radioConfig.preferences.sds_secs = 365 * 24 * 60 * 60; // one year
radioConfig.preferences.ls_secs = 60 * 60;
radioConfig.preferences.phone_timeout_secs = 15 * 60;
#ifdef GPS_RX_PIN
// some hardware defaults to have a built in GPS
myNodeInfo.has_gps = true;
#endif
strncpy(myNodeInfo.region, xstr(HW_VERSION), sizeof(myNodeInfo.region));
strncpy(myNodeInfo.firmware_version, xstr(APP_VERSION), sizeof(myNodeInfo.firmware_version));
strncpy(myNodeInfo.hw_model, HW_VENDOR, sizeof(myNodeInfo.hw_model));
// Init our blank owner info to reasonable defaults
esp_efuse_mac_get_default(ourMacAddr);
@@ -136,7 +155,7 @@ void NodeDB::loadFromDisk()
}
else
{
if (scratch.version < DeviceState_Version_Minimum)
if (scratch.version < DEVICESTATE_MIN_VER)
DEBUG_MSG("Warn: devicestate is old, discarding\n");
else
{
@@ -165,7 +184,7 @@ void NodeDB::saveToDisk()
//DEBUG_MSG("Presave channel name=%s\n", channelSettings.name);
devicestate.version = DeviceState_Version_Current;
devicestate.version = DEVICESTATE_CUR_VER;
if (!pb_encode(&stream, DeviceState_fields, &devicestate))
{
DEBUG_MSG("Error: can't write protobuf %s\n", PB_GET_ERROR(&stream));
@@ -244,7 +263,8 @@ void NodeDB::updateFrom(const MeshPacket &mp)
switch (p.which_variant)
{
case SubPacket_position_tag: {
case SubPacket_position_tag:
{
// we carefully preserve the old time, because we always trust our local timestamps more
uint32_t oldtime = info->position.time;
info->position = p.variant.position;
@@ -266,6 +286,7 @@ void NodeDB::updateFrom(const MeshPacket &mp)
devicestate.rx_text_message = mp;
devicestate.has_rx_text_message = true;
updateTextMessage = true;
powerFSM.trigger(EVENT_RECEIVED_TEXT_MSG);
}
}
break;
@@ -284,6 +305,7 @@ void NodeDB::updateFrom(const MeshPacket &mp)
if (changed)
{
updateGUIforNode = info;
powerFSM.trigger(EVENT_NODEDB_UPDATED);
// Not really needed - we will save anyways when we go to sleep
// We just changed something important about the user, store our DB

View File

@@ -1,32 +1,22 @@
#pragma once
#include <Arduino.h>
#include "PeriodicTask.h"
/**
* Periodically invoke a callback.
*
* FIXME: currently just syntatic sugar for polling in loop (you must call .loop), but eventually
* generalize with the freertos scheduler so we can save lots of power by having everything either in
* something like this or triggered off of an irq.
* This just provides C style callback conventions rather than a virtual function - FIXME, remove?
*/
class Periodic
class Periodic : public PeriodicTask
{
uint32_t lastMsec = 0;
uint32_t period = 1; // call soon after creation
uint32_t (*callback)();
public:
// callback returns the period for the next callback invocation (or 0 if we should no longer be called)
Periodic(uint32_t (*_callback)()) : callback(_callback) {}
// for the time being this must be called from loop
void loop()
{
uint32_t now = millis();
if (period && (now - lastMsec) >= period)
{
lastMsec = now;
period = (*callback)();
}
}
protected:
void doTask();
};

23
src/PeriodicTask.cpp Normal file
View File

@@ -0,0 +1,23 @@
#include "PeriodicTask.h"
#include "Periodic.h"
PeriodicTask::PeriodicTask(uint32_t initialPeriod) : period(initialPeriod)
{
}
/// call this from loop
void PeriodicTask::loop()
{
uint32_t now = millis();
if (period && (now - lastMsec) >= period)
{
lastMsec = now;
doTask();
}
}
void Periodic::doTask()
{
uint32_t p = callback();
setPeriod(p);
}

View File

@@ -3,34 +3,31 @@
#include <Arduino.h>
#include "configuration.h"
/**
* A base class for tasks that want their doTask() method invoked periodically
*
* FIXME: currently just syntatic sugar for polling in loop (you must call .loop), but eventually
* generalize with the freertos scheduler so we can save lots of power by having everything either in
* something like this or triggered off of an irq.
*/
class PeriodicTask
{
/// we use prevMsec rather than nextMsec because it is easier to handle the uint32 rollover in that case, also changes in periodMsec take effect immediately
uint32_t prevMsec;
uint32_t lastMsec = 0;
uint32_t period = 1; // call soon after creation
public:
uint32_t periodMsec;
virtual ~PeriodicTask() {}
PeriodicTask(uint32_t period) : periodMsec(period)
{
prevMsec = millis();
}
PeriodicTask(uint32_t initialPeriod = 1);
/// call this from loop
virtual void loop()
{
uint32_t now = millis();
if (now > (prevMsec + periodMsec))
{
// FIXME, this lets period slightly drift based on scheduling - not sure if that is always good
prevMsec = now;
virtual void loop();
// DEBUG_MSG("Calling periodic task\n");
doTask();
}
}
/// Set a new period in msecs (can be called from doTask or elsewhere and the scheduler will cope)
void setPeriod(uint32_t p) { period = p; }
protected:
virtual void doTask() = 0;
};

165
src/PowerFSM.cpp Normal file
View File

@@ -0,0 +1,165 @@
#include "sleep.h"
#include "MeshService.h"
#include "NodeDB.h"
#include "configuration.h"
#include "screen.h"
#include "PowerFSM.h"
#include "GPS.h"
#include "main.h"
static void sdsEnter()
{
/*
// Don't deepsleep if we have USB power or if the user as pressed a button recently
// !isUSBPowered <- doesn't work yet because the axp192 isn't letting the battery fully charge when we are awake - FIXME
if (millis() - lastPressMs > radioConfig.preferences.mesh_sds_timeout_secs)
{
doDeepSleep(radioConfig.preferences.sds_secs);
}
*/
doDeepSleep(radioConfig.preferences.sds_secs * 1000LL);
}
static void lsEnter()
{
screen.setOn(false);
while (!service.radio.rf95.canSleep())
delay(10); // Kinda yucky - wait until radio says say we can shutdown (finished in process sends/receives)
gps.prepareSleep(); // abandon in-process parsing
if (!isUSBPowered) // FIXME - temp hack until we can put gps in sleep mode, if we have AC when we go to sleep then leave GPS on
setGPSPower(false); // kill GPS power
}
static void lsIdle()
{
uint32_t secsSlept = 0;
esp_sleep_source_t wakeCause = ESP_SLEEP_WAKEUP_UNDEFINED;
bool reached_ls_secs = false;
while (!reached_ls_secs)
{
// Briefly come out of sleep long enough to blink the led once every few seconds
uint32_t sleepTime = 5;
setLed(false); // Never leave led on while in light sleep
wakeCause = doLightSleep(sleepTime * 1000LL);
if (wakeCause != ESP_SLEEP_WAKEUP_TIMER)
break;
setLed(true); // briefly turn on led
doLightSleep(1);
if (wakeCause != ESP_SLEEP_WAKEUP_TIMER)
break;
secsSlept += sleepTime;
reached_ls_secs = secsSlept >= radioConfig.preferences.ls_secs;
}
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");
}
else
{
// Regardless of why we woke just transition to NB (and that state will handle stuff like IRQs etc)
powerFSM.trigger(EVENT_WAKE_TIMER);
}
}
static void lsExit()
{
setGPSPower(true); // restore GPS power
gps.startLock();
}
static void nbEnter()
{
screen.setOn(false);
setBluetoothEnable(false);
// FIXME - check if we already have packets for phone and immediately trigger EVENT_PACKETS_FOR_PHONE
}
static void darkEnter()
{
screen.setOn(false);
}
static void onEnter()
{
screen.setOn(true);
setBluetoothEnable(true);
}
static void wakeForPing()
{
}
static void screenPress()
{
screen.onPress();
}
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 stateON(onEnter, NULL, NULL, "ON");
Fsm powerFSM(&stateDARK);
void PowerFSM_setup()
{
powerFSM.add_transition(&stateDARK, &stateON, EVENT_BOOT, NULL, "Boot");
powerFSM.add_transition(&stateLS, &stateDARK, EVENT_WAKE_TIMER, wakeForPing, "Wake timer");
// Note we don't really use this transition, because when we wake from light sleep we _always_ transition to NB and then it handles things
// powerFSM.add_transition(&stateLS, &stateNB, EVENT_RECEIVED_PACKET, NULL, "Received packet");
powerFSM.add_transition(&stateNB, &stateNB, EVENT_RECEIVED_PACKET, NULL, "Received packet, resetting win wake");
// Note we don't really use this transition, because when we wake from light sleep we _always_ transition to NB and then it handles things
// 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
powerFSM.add_transition(&stateDARK, &stateON, EVENT_BLUETOOTH_PAIR, NULL, "Bluetooth pairing");
powerFSM.add_transition(&stateON, &stateON, EVENT_BLUETOOTH_PAIR, NULL, "Bluetooth pairing");
powerFSM.add_transition(&stateNB, &stateON, EVENT_NODEDB_UPDATED, NULL, "NodeDB update");
powerFSM.add_transition(&stateDARK, &stateON, EVENT_NODEDB_UPDATED, NULL, "NodeDB update");
powerFSM.add_transition(&stateON, &stateON, EVENT_NODEDB_UPDATED, NULL, "NodeDB update");
powerFSM.add_transition(&stateLS, &stateON, EVENT_RECEIVED_TEXT_MSG, NULL, "Received text");
powerFSM.add_transition(&stateNB, &stateON, EVENT_RECEIVED_TEXT_MSG, NULL, "Received text");
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(&stateDARK, &stateDARK, EVENT_CONTACT_FROM_PHONE, NULL, "Contact from phone");
powerFSM.add_transition(&stateNB, &stateDARK, EVENT_PACKET_FOR_PHONE, NULL, "Packet for phone");
powerFSM.add_timed_transition(&stateON, &stateDARK, radioConfig.preferences.screen_on_secs * 1000, NULL, "Screen-on timeout");
powerFSM.add_timed_transition(&stateDARK, &stateNB, radioConfig.preferences.phone_timeout_secs * 1000, NULL, "Phone timeout");
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");
powerFSM.add_timed_transition(&stateLS, &stateSDS, radioConfig.preferences.mesh_sds_timeout_secs * 1000, NULL, "mesh timeout");
// removing for now, because some users don't even have phones
// powerFSM.add_timed_transition(&stateLS, &stateSDS, radioConfig.preferences.phone_sds_timeout_sec * 1000, NULL, "phone timeout");
powerFSM.run_machine(); // run one interation of the state machine, so we run our on enter tasks for the initial DARK state
}

19
src/PowerFSM.h Normal file
View File

@@ -0,0 +1,19 @@
#pragma once
#include <Fsm.h>
// See sw-design.md for documentation
#define EVENT_PRESS 1
#define EVENT_WAKE_TIMER 2
#define EVENT_RECEIVED_PACKET 3
#define EVENT_PACKET_FOR_PHONE 4
#define EVENT_RECEIVED_TEXT_MSG 5
#define EVENT_BOOT 6
#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
extern Fsm powerFSM;
void PowerFSM_setup();

View File

@@ -29,6 +29,11 @@ public:
return uxQueueSpacesAvailable(h);
}
bool isEmpty()
{
return uxQueueMessagesWaiting(h) == 0;
}
// pdTRUE for success else failure
BaseType_t enqueue(T x, TickType_t maxWait = portMAX_DELAY)
{

View File

@@ -29,21 +29,19 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
// Version
// -----------------------------------------------------------------------------
#define APP_NAME "Meshtastic"
// 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 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
// -----------------------------------------------------------------------------
// Configuration
// -----------------------------------------------------------------------------
// Select which board is being used. If the outside build environment has sent a choice, just use that
#if !defined(T_BEAM_V10) && !defined(HELTEC_LORA32)
//#define T_BEAM_V10 // AKA Rev1 (second board released)
// #define T_BEAM_V10 // AKA Rev1 (second board released)
#define HELTEC_LORA32
#define HW_VERSION_US // We encode the hardware freq range in the hw version string, so sw update can eventually install the correct build
@@ -55,26 +53,20 @@ 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 SLEEP_MSECS (30 * 24 * 60 * 60 * 1000LL) // Sleep for these many millis (or a button press or a lora msg?)
#define DEBUG_PORT Serial // Serial debug port
#define SERIAL_BAUD 115200 // Serial debug baud rate
#define MESSAGE_TO_SLEEP_DELAY 5000 // Time after message before going to sleep
#define REQUIRE_RADIO true // If true, we will fail to start if the radio is not found
#define LOGO_DELAY 2000 // Time to show logo on first boot
#define REQUIRE_RADIO true // If true, we will fail to start if the radio is not found
// If not defined, we will wait for lock forever
#define MINWAKE_MSECS (10 * 60 * 1000) // stay awake a long time (30 mins) for debugging
// #define MINWAKE_MSECS (30 * 1000) // Wait after every boot for GPS lock (may need longer than 5s because we turned the gps off during deep sleep)
#define xstr(s) str(s)
#define str(s) #s
// -----------------------------------------------------------------------------
// DEBUG
// -----------------------------------------------------------------------------
#ifdef DEBUG_PORT
#define DEBUG_MSG(...) DEBUG_PORT.printf( __VA_ARGS__ )
#define DEBUG_MSG(...) DEBUG_PORT.printf(__VA_ARGS__)
#else
#define DEBUG_MSG(...)
#endif
@@ -89,15 +81,15 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
// GPS
// -----------------------------------------------------------------------------
#define GPS_SERIAL_NUM 1
#define GPS_BAUDRATE 9600
#define GPS_SERIAL_NUM 1
#define GPS_BAUDRATE 9600
#if defined(T_BEAM_V10)
#define GPS_RX_PIN 34
#define GPS_RX_PIN 34
#ifdef USE_JTAG
#define GPS_TX_PIN -1
#define GPS_TX_PIN -1
#else
#define GPS_TX_PIN 12
#define GPS_TX_PIN 12
#endif
#endif
@@ -105,59 +97,59 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
// LoRa SPI
// -----------------------------------------------------------------------------
#define SCK_GPIO 5
#define MISO_GPIO 19
#define MOSI_GPIO 27
#define NSS_GPIO 18
#define SCK_GPIO 5
#define MISO_GPIO 19
#define MOSI_GPIO 27
#define NSS_GPIO 18
#if defined(T_BEAM_V10)
#define HW_VENDOR "TTGO"
// This string must exactly match the case used in release file names or the android updater won't work
#define HW_VENDOR "TBEAM"
#define BICOLOR_DISPLAY // we have yellow at the top 16 lines
#define I2C_SDA 21
#define I2C_SCL 22
#define I2C_SDA 21
#define I2C_SCL 22
#define BUTTON_PIN 38
#define BUTTON_PIN 38
#ifndef USE_JTAG
#define RESET_GPIO 14
#define RESET_GPIO 14
#endif
#define DIO0_GPIO 26
#define DIO1_GPIO 33 // Note: not really used on this board
#define DIO2_GPIO 32 // Note: not really used on this board
#define DIO0_GPIO 26
#define DIO1_GPIO 33 // Note: not really used on this board
#define DIO2_GPIO 32 // Note: not really used on this board
// Leave undefined to disable our PMU IRQ handler
#define PMU_IRQ 35
// Leave undefined to disable our PMU IRQ handler
#define PMU_IRQ 35
#elif defined(HELTEC_LORA32)
#define HW_VENDOR "Heltec"
// This string must exactly match the case used in release file names or the android updater won't work
#define HW_VENDOR "HELTEC"
#ifndef USE_JTAG // gpio15 is TDO for JTAG, so no I2C on this board while doing jtag
#define I2C_SDA 4
#define I2C_SCL 15
#define I2C_SDA 4
#define I2C_SCL 15
#endif
#define RESET_OLED 16
#define RESET_OLED 16
#define VEXT_ENABLE 21 // active low, powers the oled display and the lora antenna boost
#define LED_PIN 25
#define BUTTON_PIN 0
#define VEXT_ENABLE 21 // active low, powers the oled display and the lora antenna boost
#define LED_PIN 25
#define BUTTON_PIN 0
#ifndef USE_JTAG
#define RESET_GPIO 14
#define RESET_GPIO 14
#endif
#define DIO0_GPIO 26
#define DIO1_GPIO 35
#define DIO2_GPIO 34
#define DIO0_GPIO 26
#define DIO1_GPIO 35
#define DIO2_GPIO 34
#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
#define GPS_POWER_CTRL_CH 3
#define LORA_POWER_CTRL_CH 2

View File

@@ -35,159 +35,29 @@
#include "Periodic.h"
#include "esp32/pm.h"
#include "esp_pm.h"
#include "MeshRadio.h"
#include "sleep.h"
#include "PowerFSM.h"
#ifdef T_BEAM_V10
#include "axp20x.h"
AXP20X_Class axp;
bool pmu_irq = false;
#endif
bool isCharging = false;
bool isUSBPowered = false;
bool ssd1306_found = false;
bool axp192_found = false;
// these flags are all in bss so they default false
bool isCharging;
bool isUSBPowered;
bool packetSent, packetQueued;
bool ssd1306_found;
bool axp192_found;
// deep sleep support
RTC_DATA_ATTR int bootCount = 0;
esp_sleep_source_t wakeCause; // the reason we booted this time
bool bluetoothOn;
// -----------------------------------------------------------------------------
// Application
// -----------------------------------------------------------------------------
void doDeepSleep(uint64_t msecToWake)
{
DEBUG_MSG("Entering deep sleep for %llu seconds\n", msecToWake / 1000);
// not using wifi yet, but once we are this is needed to shutoff the radio hw
// esp_wifi_stop();
BLEDevice::deinit(false); // We are required to shutdown bluetooth before deep or light sleep
screen_off(); // datasheet says this will draw only 10ua
// Put radio in sleep mode (will still draw power but only 0.2uA)
service.radio.sleep();
nodeDB.saveToDisk();
#ifdef RESET_OLED
digitalWrite(RESET_OLED, 1); // put the display in reset before killing its power
#endif
#ifdef VEXT_ENABLE
digitalWrite(VEXT_ENABLE, 1); // turn off the display power
#endif
#ifdef LED_PIN
digitalWrite(LED_PIN, 0); // turn off the led
#endif
#ifdef T_BEAM_V10
if (axp192_found)
{
axp.setChgLEDMode(AXP20X_LED_OFF); // turn off the AXP LED
// No need to turn this off if the power draw in sleep mode really is just 0.2uA and turning it off would
// leave floating input for the IRQ line
// If we want to leave the radio receving in would be 11.5mA current draw, but most of the time it is just waiting
// in its sequencer (true?) so the average power draw should be much lower even if we were listinging for packets
// all the time.
// axp.setPowerOutPut(AXP192_LDO2, AXP202_OFF); // LORA radio
axp.setPowerOutPut(AXP192_LDO3, AXP202_OFF); // GPS main power
}
#endif
/*
Some ESP32 IOs have internal pullups or pulldowns, which are enabled by default.
If an external circuit drives this pin in deep sleep mode, current consumption may
increase due to current flowing through these pullups and pulldowns.
To isolate a pin, preventing extra current draw, call rtc_gpio_isolate() function.
For example, on ESP32-WROVER module, GPIO12 is pulled up externally.
GPIO12 also has an internal pulldown in the ESP32 chip. This means that in deep sleep,
some current will flow through these external and internal resistors, increasing deep
sleep current above the minimal possible value.
Note: we don't isolate pins that are used for the LORA, LED, i2c, spi or the wake button
*/
static const uint8_t rtcGpios[] = {/* 0, */ 2,
/* 4, */
#ifndef USE_JTAG
12, 13, /* 14, */ /* 15, */
#endif
/* 25, */ 26, /* 27, */
32, 33, 34, 35, 36, 37, /* 38, */ 39};
for (int i = 0; i < sizeof(rtcGpios); i++)
rtc_gpio_isolate((gpio_num_t)rtcGpios[i]);
// FIXME, disable internal rtc pullups/pulldowns on the non isolated pins. for inputs that we aren't using
// to detect wake and in normal operation the external part drives them hard.
// FIXME - use an external 10k pulldown so we can leave the RTC peripherals powered off
// until then we need the following lines
esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);
#ifdef BUTTON_PIN
// Only GPIOs which are have RTC functionality can be used in this bit map: 0,2,4,12-15,25-27,32-39.
uint64_t gpioMask = (1ULL << BUTTON_PIN);
// Not needed because both of the current boards have external pullups
// FIXME change polarity in hw so we can wake on ANY_HIGH instead - that would allow us to use all three buttons (instead of just the first)
// gpio_pullup_en((gpio_num_t)BUTTON_PIN);
esp_sleep_enable_ext1_wakeup(gpioMask, ESP_EXT1_WAKEUP_ALL_LOW);
#endif
esp_sleep_enable_timer_wakeup(msecToWake * 1000ULL); // call expects usecs
esp_deep_sleep_start(); // TBD mA sleep current (battery)
}
/**
* enable modem sleep mode as needed and available. Should lower our CPU current draw to an average of about 20mA.
*
* per https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/system/power_management.html
*/
void enableModemSleep()
{
static esp_pm_config_esp32_t config; // filled with zeros because bss
config.max_freq_mhz = CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ;
config.min_freq_mhz = 10; // 10Mhz is minimum recommended
config.light_sleep_enable = false;
DEBUG_MSG("Sleep request result %x\n", esp_pm_configure(&config));
}
void sleep()
{
#ifdef SLEEP_MSECS
// If the user has a screen, tell them we are about to sleep
if (ssd1306_found)
{
// Show the going to sleep message on the screen
char buffer[20];
snprintf(buffer, sizeof(buffer), "Sleeping in %3.1fs\n", (MESSAGE_TO_SLEEP_DELAY / 1000.0));
screen_print(buffer);
// Wait for MESSAGE_TO_SLEEP_DELAY millis to sleep
delay(MESSAGE_TO_SLEEP_DELAY);
}
// We sleep for the interval between messages minus the current millis
// this way we distribute the messages evenly every SEND_INTERVAL millis
doDeepSleep(SLEEP_MSECS);
#endif
}
void scanI2Cdevice(void)
{
byte err, addr;
@@ -295,15 +165,15 @@ void axp192Init()
attachInterrupt(PMU_IRQ, [] {
pmu_irq = true;
},
FALLING);
RISING);
axp.adc1Enable(AXP202_BATT_CUR_ADC1, 1);
axp.enableIRQ(AXP202_VBUS_REMOVED_IRQ | AXP202_VBUS_CONNECT_IRQ | AXP202_BATT_REMOVED_IRQ | AXP202_BATT_CONNECT_IRQ, 1);
axp.clearIRQ();
#endif
isCharging = axp.isChargeing();
isUSBPowered = axp.isVBUSPlug();
isCharging = axp.isChargeing() ? 1 : 0;
isUSBPowered = axp.isVBUSPlug() ? 1 : 0;
}
else
{
@@ -317,22 +187,6 @@ void axp192Init()
#endif
}
// Perform power on init that we do on each wake from deep sleep
void initDeepSleep()
{
bootCount++;
wakeCause = esp_sleep_get_wakeup_cause();
/*
Not using yet because we are using wake on all buttons being low
wakeButtons = esp_sleep_get_ext1_wakeup_status(); // If one of these buttons is set it was the reason we woke
if (wakeCause == ESP_SLEEP_WAKEUP_EXT1 && !wakeButtons) // we must have been using the 'all buttons rule for waking' to support busted boards, assume button one was pressed
wakeButtons = ((uint64_t)1) << buttons.gpios[0];
*/
DEBUG_MSG("booted, wake cause %d (boot count %d)\n", wakeCause, bootCount);
}
const char *getDeviceName()
{
uint8_t dmac[6];
@@ -352,7 +206,6 @@ void setup()
#endif
initDeepSleep();
// delay(1000); FIXME - remove
#ifdef VEXT_ENABLE
pinMode(VEXT_ENABLE, OUTPUT);
@@ -382,14 +235,14 @@ void setup()
#endif
// Hello
DEBUG_MSG(APP_NAME " " APP_VERSION "\n");
DEBUG_MSG("Meshtastic swver=%s, hwver=%s\n", xstr(APP_VERSION), xstr(HW_VERSION));
// 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
if (ssd1306_found)
screen_setup();
screen.setup();
// Init GPS
gps.setup();
@@ -398,18 +251,51 @@ void setup()
service.init();
bool useBluetooth = true;
if (useBluetooth)
// setBluetoothEnable(false); we now don't start bluetooth until we enter the proper state
setCPUFast(false); // 80MHz is fine for our slow peripherals
PowerFSM_setup();
powerFSM.trigger(EVENT_BOOT); // transition to ON, FIXME, only do this for cold boots, not waking from SDS
}
void initBluetooth()
{
DEBUG_MSG("Starting bluetooth\n");
// FIXME - we are leaking like crazy
// AllocatorScope scope(btPool);
BLEServer *serve = initBLE(getDeviceName(), HW_VENDOR, xstr(APP_VERSION), xstr(HW_VERSION)); // FIXME, use a real name based on the macaddr
createMeshBluetoothService(serve);
// Start advertising - this must be done _after_ creating all services
serve->getAdvertising()->start();
}
void setBluetoothEnable(bool on)
{
if (on != bluetoothOn)
{
DEBUG_MSG("Starting bluetooth\n");
BLEServer *serve = initBLE(getDeviceName(), HW_VENDOR, APP_VERSION); // FIXME, use a real name based on the macaddr
createMeshBluetoothService(serve);
DEBUG_MSG("Setting bluetooth enable=%d\n", on);
// Start advertising - this must be done _after_ creating all services
serve->getAdvertising()->start();
bluetoothOn = on;
if (on)
{
Serial.printf("Pre BT: %u heap size\n", ESP.getFreeHeap());
//ESP_ERROR_CHECK( heap_trace_start(HEAP_TRACE_LEAKS) );
initBluetooth();
}
else
{
// We have to totally teardown our bluetooth objects to prevent leaks
stopMeshBluetoothService(); // Must do before shutting down bluetooth
deinitBLE();
destroyMeshBluetoothService(); // must do after deinit, because it frees our service
Serial.printf("Shutdown BT: %u heap size\n", ESP.getFreeHeap());
//ESP_ERROR_CHECK( heap_trace_stop() );
//heap_trace_dump();
}
}
enableModemSleep();
}
uint32_t ledBlinker()
@@ -417,18 +303,7 @@ uint32_t ledBlinker()
static bool ledOn;
ledOn ^= 1;
#ifdef LED_PIN
// toggle the led so we can get some rough sense of how often loop is pausing
digitalWrite(LED_PIN, ledOn);
#endif
#ifdef T_BEAM_V10
if (axp192_found)
{
// blink the axp led
axp.setChgLEDMode(ledOn ? AXP20X_LED_LOW_LEVEL : AXP20X_LED_OFF);
}
#endif
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 isCharging ? 1000 : (ledOn ? 2 : 1000);
@@ -451,15 +326,17 @@ uint32_t axpReads()
}
Periodic axpDebugOutput(axpReads);
#endif
#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();
msecstosleep = min(screen_loop(), msecstosleep);
screen.loop();
service.loop();
ledPeriodic.loop();
// axpDebugOutput.loop();
loopBLE();
@@ -473,11 +350,17 @@ void loop()
pmu_irq = false;
axp.readIRQ();
isCharging = axp.isChargeing();
isUSBPowered = axp.isVBUSPlug();
DEBUG_MSG("pmu irq!\n");
isCharging = axp.isChargeing() ? 1 : 0;
isUSBPowered = axp.isVBUSPlug() ? 1 : 0;
axp.clearIRQ();
}
// FIXME AXP192 interrupt is not firing, remove this temporary polling of battery state
isCharging = axp.isChargeing() ? 1 : 0;
isUSBPowered = axp.isVBUSPlug() ? 1 : 0;
#endif
}
#endif
@@ -486,17 +369,19 @@ void loop()
// 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;
static uint32_t minPressMs; // what tick should we call this press long enough
static uint32_t lastPingMs, lastPressMs;
static uint32_t lastPingMs;
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;
uint32_t now = millis();
lastPressMs = now;
minPressMs = now + 3000;
if (now - lastPingMs > 60 * 1000)
@@ -505,7 +390,7 @@ void loop()
lastPingMs = now;
}
screen_press();
powerFSM.trigger(EVENT_PRESS);
}
}
else if (wasPressed)
@@ -522,20 +407,12 @@ void loop()
}
#endif
#ifdef MINWAKE_MSECS
// Don't deepsleep if we have USB power or if the user as pressed a button recently
// !isUSBPowered <- doesn't work yet because the axp192 isn't letting the battery fully charge when we are awake - FIXME
if (millis() - lastPressMs > MINWAKE_MSECS)
{
sleep();
}
#endif
// 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.
//DEBUG_MSG("msecs %d\n", msecstosleep);
// FIXME - until button press handling is done by interrupt (see polling above) we can't sleep very long at all or buttons feel slow
msecstosleep = 10;
delay(msecstosleep);
}

6
src/main.h Normal file
View File

@@ -0,0 +1,6 @@
#pragma once
extern bool axp192_found;
extern bool ssd1306_found;
extern bool isCharging;
extern bool isUSBPowered;

View File

@@ -49,7 +49,6 @@ PB_BIND(ToRadio, ToRadio, 2)
#ifndef PB_CONVERT_DOUBLE_FLOAT
/* On some platforms (such as AVR), double is really float.
* To be able to encode/decode double on these platforms, you need.

View File

@@ -31,12 +31,6 @@ typedef enum _ChannelSettings_ModemConfig {
ChannelSettings_ModemConfig_Bw125Cr48Sf4096 = 3
} ChannelSettings_ModemConfig;
typedef enum _DeviceState_Version {
DeviceState_Version_Unset = 0,
DeviceState_Version_Minimum = 15,
DeviceState_Version_Current = 15
} DeviceState_Version;
/* Struct definitions */
typedef struct _ChannelSettings {
int32_t tx_power;
@@ -56,6 +50,9 @@ typedef struct _MyNodeInfo {
int32_t my_node_num;
bool has_gps;
int32_t num_channels;
char region[12];
char hw_model[12];
char firmware_version[12];
} MyNodeInfo;
typedef struct _Position {
@@ -63,14 +60,21 @@ typedef struct _Position {
double longitude;
int32_t altitude;
int32_t battery_level;
bool from_hardware;
uint32_t time;
} Position;
typedef struct _RadioConfig_UserPreferences {
uint32_t position_broadcast_secs;
uint32_t send_owner_secs;
uint32_t send_owner_interval;
uint32_t num_missed_to_fail;
uint32_t wait_bluetooth_secs;
uint32_t screen_on_secs;
uint32_t phone_timeout_secs;
uint32_t phone_sds_timeout_sec;
uint32_t mesh_sds_timeout_secs;
uint32_t sds_secs;
uint32_t ls_secs;
uint32_t min_wake_secs;
bool keep_all_packets;
bool promiscuous_mode;
} RadioConfig_UserPreferences;
@@ -128,9 +132,9 @@ typedef struct _DeviceState {
NodeInfo node_db[32];
pb_size_t receive_queue_count;
MeshPacket receive_queue[32];
DeviceState_Version version;
bool has_rx_text_message;
MeshPacket rx_text_message;
uint32_t version;
} DeviceState;
typedef struct _FromRadio {
@@ -162,36 +166,32 @@ typedef struct _ToRadio {
#define _ChannelSettings_ModemConfig_MAX ChannelSettings_ModemConfig_Bw125Cr48Sf4096
#define _ChannelSettings_ModemConfig_ARRAYSIZE ((ChannelSettings_ModemConfig)(ChannelSettings_ModemConfig_Bw125Cr48Sf4096+1))
#define _DeviceState_Version_MIN DeviceState_Version_Unset
#define _DeviceState_Version_MAX DeviceState_Version_Current
#define _DeviceState_Version_ARRAYSIZE ((DeviceState_Version)(DeviceState_Version_Current+1))
/* Initializer values for message structs */
#define Position_init_default {0, 0, 0, 0, 0, 0}
#define Position_init_default {0, 0, 0, 0, 0}
#define Data_init_default {_Data_Type_MIN, {0, {0}}}
#define User_init_default {"", "", "", {0}}
#define SubPacket_init_default {0, {Position_init_default}, 0}
#define MeshPacket_init_default {0, 0, false, SubPacket_init_default, 0}
#define ChannelSettings_init_default {0, 0, _ChannelSettings_ModemConfig_MIN, {0}, ""}
#define RadioConfig_init_default {false, RadioConfig_UserPreferences_init_default, false, ChannelSettings_init_default}
#define RadioConfig_UserPreferences_init_default {0, 0, 0, 0, 0}
#define RadioConfig_UserPreferences_init_default {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
#define NodeInfo_init_default {0, false, User_init_default, false, Position_init_default, 0, 0}
#define MyNodeInfo_init_default {0, 0, 0}
#define DeviceState_init_default {false, RadioConfig_init_default, false, MyNodeInfo_init_default, false, User_init_default, 0, {NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default}, 0, {MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default}, _DeviceState_Version_MIN, false, MeshPacket_init_default}
#define MyNodeInfo_init_default {0, 0, 0, "", "", ""}
#define DeviceState_init_default {false, RadioConfig_init_default, false, MyNodeInfo_init_default, false, User_init_default, 0, {NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default}, 0, {MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default, MeshPacket_init_default}, false, MeshPacket_init_default, 0}
#define FromRadio_init_default {0, 0, {MeshPacket_init_default}}
#define ToRadio_init_default {0, {MeshPacket_init_default}}
#define Position_init_zero {0, 0, 0, 0, 0, 0}
#define Position_init_zero {0, 0, 0, 0, 0}
#define Data_init_zero {_Data_Type_MIN, {0, {0}}}
#define User_init_zero {"", "", "", {0}}
#define SubPacket_init_zero {0, {Position_init_zero}, 0}
#define MeshPacket_init_zero {0, 0, false, SubPacket_init_zero, 0}
#define ChannelSettings_init_zero {0, 0, _ChannelSettings_ModemConfig_MIN, {0}, ""}
#define RadioConfig_init_zero {false, RadioConfig_UserPreferences_init_zero, false, ChannelSettings_init_zero}
#define RadioConfig_UserPreferences_init_zero {0, 0, 0, 0, 0}
#define RadioConfig_UserPreferences_init_zero {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
#define NodeInfo_init_zero {0, false, User_init_zero, false, Position_init_zero, 0, 0}
#define MyNodeInfo_init_zero {0, 0, 0}
#define DeviceState_init_zero {false, RadioConfig_init_zero, false, MyNodeInfo_init_zero, false, User_init_zero, 0, {NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero}, 0, {MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero}, _DeviceState_Version_MIN, false, MeshPacket_init_zero}
#define MyNodeInfo_init_zero {0, 0, 0, "", "", ""}
#define DeviceState_init_zero {false, RadioConfig_init_zero, false, MyNodeInfo_init_zero, false, User_init_zero, 0, {NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero}, 0, {MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero, MeshPacket_init_zero}, false, MeshPacket_init_zero, 0}
#define FromRadio_init_zero {0, 0, {MeshPacket_init_zero}}
#define ToRadio_init_zero {0, {MeshPacket_init_zero}}
@@ -206,15 +206,25 @@ typedef struct _ToRadio {
#define MyNodeInfo_my_node_num_tag 1
#define MyNodeInfo_has_gps_tag 2
#define MyNodeInfo_num_channels_tag 3
#define MyNodeInfo_region_tag 4
#define MyNodeInfo_hw_model_tag 5
#define MyNodeInfo_firmware_version_tag 6
#define Position_latitude_tag 1
#define Position_longitude_tag 2
#define Position_altitude_tag 3
#define Position_battery_level_tag 4
#define Position_from_hardware_tag 5
#define Position_time_tag 6
#define RadioConfig_UserPreferences_position_broadcast_secs_tag 1
#define RadioConfig_UserPreferences_send_owner_secs_tag 2
#define RadioConfig_UserPreferences_send_owner_interval_tag 2
#define RadioConfig_UserPreferences_num_missed_to_fail_tag 3
#define RadioConfig_UserPreferences_wait_bluetooth_secs_tag 4
#define RadioConfig_UserPreferences_screen_on_secs_tag 5
#define RadioConfig_UserPreferences_phone_timeout_secs_tag 6
#define RadioConfig_UserPreferences_phone_sds_timeout_sec_tag 7
#define RadioConfig_UserPreferences_mesh_sds_timeout_secs_tag 8
#define RadioConfig_UserPreferences_sds_secs_tag 9
#define RadioConfig_UserPreferences_ls_secs_tag 10
#define RadioConfig_UserPreferences_min_wake_secs_tag 11
#define RadioConfig_UserPreferences_keep_all_packets_tag 100
#define RadioConfig_UserPreferences_promiscuous_mode_tag 101
#define User_id_tag 1
@@ -241,7 +251,7 @@ typedef struct _ToRadio {
#define DeviceState_owner_tag 3
#define DeviceState_node_db_tag 4
#define DeviceState_receive_queue_tag 5
#define DeviceState_version_tag 6
#define DeviceState_version_tag 8
#define DeviceState_rx_text_message_tag 7
#define FromRadio_packet_tag 2
#define FromRadio_num_tag 1
@@ -253,7 +263,6 @@ X(a, STATIC, SINGULAR, DOUBLE, latitude, 1) \
X(a, STATIC, SINGULAR, DOUBLE, longitude, 2) \
X(a, STATIC, SINGULAR, INT32, altitude, 3) \
X(a, STATIC, SINGULAR, INT32, battery_level, 4) \
X(a, STATIC, SINGULAR, BOOL, from_hardware, 5) \
X(a, STATIC, SINGULAR, UINT32, time, 6)
#define Position_CALLBACK NULL
#define Position_DEFAULT NULL
@@ -311,8 +320,16 @@ X(a, STATIC, OPTIONAL, MESSAGE, channel_settings, 2)
#define RadioConfig_UserPreferences_FIELDLIST(X, a) \
X(a, STATIC, SINGULAR, UINT32, position_broadcast_secs, 1) \
X(a, STATIC, SINGULAR, UINT32, send_owner_secs, 2) \
X(a, STATIC, SINGULAR, UINT32, send_owner_interval, 2) \
X(a, STATIC, SINGULAR, UINT32, num_missed_to_fail, 3) \
X(a, STATIC, SINGULAR, UINT32, wait_bluetooth_secs, 4) \
X(a, STATIC, SINGULAR, UINT32, screen_on_secs, 5) \
X(a, STATIC, SINGULAR, UINT32, phone_timeout_secs, 6) \
X(a, STATIC, SINGULAR, UINT32, phone_sds_timeout_sec, 7) \
X(a, STATIC, SINGULAR, UINT32, mesh_sds_timeout_secs, 8) \
X(a, STATIC, SINGULAR, UINT32, sds_secs, 9) \
X(a, STATIC, SINGULAR, UINT32, ls_secs, 10) \
X(a, STATIC, SINGULAR, UINT32, min_wake_secs, 11) \
X(a, STATIC, SINGULAR, BOOL, keep_all_packets, 100) \
X(a, STATIC, SINGULAR, BOOL, promiscuous_mode, 101)
#define RadioConfig_UserPreferences_CALLBACK NULL
@@ -332,7 +349,10 @@ X(a, STATIC, SINGULAR, INT32, frequency_error, 6)
#define MyNodeInfo_FIELDLIST(X, a) \
X(a, STATIC, SINGULAR, INT32, my_node_num, 1) \
X(a, STATIC, SINGULAR, BOOL, has_gps, 2) \
X(a, STATIC, SINGULAR, INT32, num_channels, 3)
X(a, STATIC, SINGULAR, INT32, num_channels, 3) \
X(a, STATIC, SINGULAR, STRING, region, 4) \
X(a, STATIC, SINGULAR, STRING, hw_model, 5) \
X(a, STATIC, SINGULAR, STRING, firmware_version, 6)
#define MyNodeInfo_CALLBACK NULL
#define MyNodeInfo_DEFAULT NULL
@@ -342,8 +362,8 @@ X(a, STATIC, OPTIONAL, MESSAGE, my_node, 2) \
X(a, STATIC, OPTIONAL, MESSAGE, owner, 3) \
X(a, STATIC, REPEATED, MESSAGE, node_db, 4) \
X(a, STATIC, REPEATED, MESSAGE, receive_queue, 5) \
X(a, STATIC, SINGULAR, UENUM, version, 6) \
X(a, STATIC, OPTIONAL, MESSAGE, rx_text_message, 7)
X(a, STATIC, OPTIONAL, MESSAGE, rx_text_message, 7) \
X(a, STATIC, SINGULAR, UINT32, version, 8)
#define DeviceState_CALLBACK NULL
#define DeviceState_DEFAULT NULL
#define DeviceState_radio_MSGTYPE RadioConfig
@@ -396,17 +416,17 @@ extern const pb_msgdesc_t ToRadio_msg;
#define ToRadio_fields &ToRadio_msg
/* Maximum encoded size of messages (where known) */
#define Position_size 48
#define Position_size 46
#define Data_size 256
#define User_size 72
#define SubPacket_size 261
#define MeshPacket_size 292
#define ChannelSettings_size 50
#define RadioConfig_size 78
#define RadioConfig_UserPreferences_size 24
#define NodeInfo_size 157
#define MyNodeInfo_size 24
#define DeviceState_size 15037
#define RadioConfig_size 126
#define RadioConfig_UserPreferences_size 72
#define NodeInfo_size 155
#define MyNodeInfo_size 63
#define DeviceState_size 15064
#define FromRadio_size 301
#define ToRadio_size 295

View File

@@ -30,6 +30,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "screen.h"
#include "mesh-pb-constants.h"
#include "NodeDB.h"
#include "main.h"
#define FONT_HEIGHT 14 // actually 13 for "ariel 10" but want a little extra space
#define FONT_HEIGHT_16 (ArialMT_Plain_16[1] + 1)
@@ -51,6 +52,14 @@ OLEDDisplayUi ui(&dispdev);
// A text message frame + debug frame + all the node infos
FrameCallback nonBootFrames[MAX_NUM_NODES + NUM_EXTRA_FRAMES];
Screen screen;
static bool showingBluetooth;
/// If set to true (possibly from an ISR), we should turn on the screen the next time our idle loop runs.
static bool showingBootScreen = true; // start by showing the bootscreen
bool Screen::isOn() { return screenOn; }
void msOverlay(OLEDDisplay *display, OLEDDisplayUiState *state)
{
display->setTextAlignment(TEXT_ALIGN_RIGHT);
@@ -131,6 +140,7 @@ void drawTextMessageFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16
{
MeshPacket &mp = devicestate.rx_text_message;
NodeInfo *node = nodeDB.getNode(mp.from);
// DEBUG_MSG("drawing text message from 0x%x: %s\n", mp.from, mp.payload.variant.data.payload.bytes);
// Demo for drawStringMaxWidth:
// with the third parameter you can define the width after which words will be wrapped.
@@ -321,7 +331,8 @@ float estimatedHeading(double lat, double lon)
}
/// Sometimes we will have Position objects that only have a time, so check for valid lat/lon
bool hasPosition(NodeInfo *n) {
bool hasPosition(NodeInfo *n)
{
return n->has_position && (n->position.latitude != 0 || n->position.longitude != 0);
}
#define COMPASS_DIAM 44
@@ -433,9 +444,19 @@ void drawDebugInfo(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, i
static char channelStr[20];
snprintf(channelStr, sizeof(channelStr), "%s", channelSettings.name);
// We don't show battery levels yet - for now just lie and show debug info
static char batStr[20];
snprintf(batStr, sizeof(batStr), "Batt %x%%", (isCharging << 1) + isUSBPowered);
static char gpsStr[20];
if (myNodeInfo.has_gps)
snprintf(gpsStr, sizeof(gpsStr), "GPS %d%%", 75); // FIXME, use something based on hdop
else
gpsStr[0] = '\0'; // Just show emptystring
const char *fields[] = {
"Batt 89%",
"GPS 75%",
batStr,
gpsStr,
usersStr,
channelStr,
NULL};
@@ -479,25 +500,28 @@ void _screen_header()
}
#endif
void screen_off()
void Screen::setOn(bool on)
{
if (!disp)
return;
dispdev.displayOff();
screenOn = false;
if (on != screenOn)
{
if (on)
{
DEBUG_MSG("Turning on screen\n");
dispdev.displayOn();
setPeriod(1); // redraw ASAP
}
else {
DEBUG_MSG("Turning off screen\n");
dispdev.displayOff();
}
screenOn = on;
}
}
void screen_on()
{
if (!disp)
return;
dispdev.displayOn();
screenOn = true;
}
static void screen_print(const char *text, uint8_t x, uint8_t y, uint8_t alignment)
void screen_print(const char *text, uint8_t x, uint8_t y, uint8_t alignment)
{
DEBUG_MSG(text);
@@ -518,7 +542,7 @@ void screen_print(const char *text)
// ui.update();
}
void screen_setup()
void Screen::setup()
{
#ifdef I2C_SDA
// Display instance
@@ -527,12 +551,15 @@ void screen_setup()
// The ESP is capable of rendering 60fps in 80Mhz mode
// but that won't give you much time for anything else
// run it in 160Mhz mode or just set it to 30 fps
ui.setTargetFPS(30);
// We do this now in loop()
// ui.setTargetFPS(30);
// Customize the active and inactive symbol
//ui.setActiveSymbol(activeSymbol);
//ui.setInactiveSymbol(inactiveSymbol);
ui.setTimePerTransition(300); // msecs
// You can change this to
// TOP, LEFT, BOTTOM, RIGHT
ui.setIndicatorPosition(BOTTOM);
@@ -556,7 +583,7 @@ void screen_setup()
// Scroll buffer
dispdev.setLogBuffer(3, 32);
screen_on(); // update our screenOn bool
setOn(true); // update our screenOn bool
#ifdef BICOLOR_DISPLAY
dispdev.flipScreenVertically(); // looks better without this on lora32
@@ -568,34 +595,35 @@ void screen_setup()
#endif
}
static bool showingBluetooth;
#define TRANSITION_FRAMERATE 30 // fps
#define IDLE_FRAMERATE 10 // in fps
/// If set to true (possibly from an ISR), we should turn on the screen the next time our idle loop runs.
static bool wakeScreen;
static uint32_t targetFramerate = IDLE_FRAMERATE;
uint32_t lastPressMs;
/// Turn off the screen this many ms after last press or wake
#define SCREEN_SLEEP_MS (60 * 1000)
uint32_t screen_loop()
void Screen::doTask()
{
if (!disp) // If we don't have a screen, don't ever spend any CPU for us
return UINT32_MAX;
if (wakeScreen || nodeDB.updateTextMessage) // If a new text message arrived, turn the screen on immedately
{
lastPressMs = millis(); // if we were told to wake the screen, reset the press timeout
screen_on(); // make sure the screen is not asleep
wakeScreen = false;
if (!disp)
{ // If we don't have a screen, don't ever spend any CPU for us
setPeriod(0);
return;
}
if (!screenOn) // If we didn't just wake and the screen is still off, then bail
return UINT32_MAX;
if (!screenOn)
{ // If we didn't just wake and the screen is still off, then stop updating until it is on again
setPeriod(0);
return;
}
static bool showingBootScreen = true; // start by showing the bootscreen
ui.update();
// Switch to a low framerate (to save CPU) when we are not in transition
// but we should only call setTargetFPS when framestate changes, because otherwise that breaks
// animations.
if (targetFramerate != IDLE_FRAMERATE && ui.getUiState()->frameState == FIXED)
{
// oldFrameState = ui.getUiState()->frameState;
DEBUG_MSG("Setting idle framerate\n");
targetFramerate = IDLE_FRAMERATE;
ui.setTargetFPS(targetFramerate);
}
// While showing the bluetooth pair screen all of our standard screen switching is stopped
if (!showingBluetooth)
@@ -603,10 +631,10 @@ uint32_t screen_loop()
// Once we finish showing the bootscreen, remove it from the loop
if (showingBootScreen)
{
if (millis() > 5 * 1000) // we show the boot screen for a few seconds only
if (millis() > 3 * 1000) // we show the boot screen for a few seconds only
{
showingBootScreen = false;
screen_set_frames();
setFrames();
}
}
else // standard screen loop handling ehre
@@ -614,23 +642,25 @@ uint32_t screen_loop()
// If the # nodes changes, we need to regen our list of screens
if (nodeDB.updateGUI || nodeDB.updateTextMessage)
{
screen_set_frames();
setFrames();
nodeDB.updateGUI = false;
nodeDB.updateTextMessage = false;
}
if (millis() - lastPressMs > SCREEN_SLEEP_MS)
{
DEBUG_MSG("screen timeout, turn it off for now...\n");
screen_off();
}
}
}
// If we are scrolling do 30fps, otherwise just 1 fps (to save CPU)
return (ui.getUiState()->frameState == IN_TRANSITION ? 10 : 500);
// This must be after we possibly do screen_set_frames() to ensure we draw the new data
ui.update();
// DEBUG_MSG("want fps %d, fixed=%d\n", targetFramerate, ui.getUiState()->frameState);
// If we are scrolling we need to be called soon, otherwise just 1 fps (to save CPU)
// We also ask to be called twice as fast as we really need so that any rounding errors still result
// with the correct framerate
setPeriod(1000 / targetFramerate);
}
#include "PowerFSM.h"
// Show the bluetooth PIN screen
void screen_start_bluetooth(uint32_t pin)
{
@@ -640,7 +670,7 @@ void screen_start_bluetooth(uint32_t pin)
DEBUG_MSG("showing bluetooth screen\n");
showingBluetooth = true;
wakeScreen = true;
powerFSM.trigger(EVENT_BLUETOOTH_PAIR);
ui.setFrames(btFrames, 1); // Just show the bluetooth frame
// we rely on our main loop to show this screen (because we are invoked deep inside of bluetooth callbacks)
@@ -648,7 +678,7 @@ void screen_start_bluetooth(uint32_t pin)
}
// restore our regular frame list
void screen_set_frames()
void Screen::setFrames()
{
DEBUG_MSG("showing standard frames\n");
@@ -677,14 +707,19 @@ void screen_set_frames()
}
/// handle press of the button
void screen_press()
void Screen::onPress()
{
// screen_start_bluetooth(123456);
lastPressMs = millis();
wakeScreen = true;
// If screen was off, just wake it, otherwise advance to next frame
if (screenOn)
// If we are in a transition, the press must have bounced, drop it.
if (ui.getUiState()->frameState == FIXED)
{
setPeriod(1); // redraw ASAP
ui.nextFrame();
}
DEBUG_MSG("Setting fast framerate\n");
// We are about to start a transition so speed up fps
targetFramerate = TRANSITION_FRAMERATE;
ui.setTargetFPS(targetFramerate);
}
}

View File

@@ -1,14 +1,44 @@
#pragma once
#include "PeriodicTask.h"
void screen_print(const char * text);
void screen_print(const char * text, uint8_t x, uint8_t y, uint8_t alignment);
/// @return how many msecs can we sleep before we want service again
uint32_t screen_loop();
void screen_setup(), screen_on(), screen_off(), screen_press();
// Show the bluetooth PIN screen
void screen_start_bluetooth(uint32_t pin);
// restore our regular frame list
void screen_set_frames();
void screen_set_frames();
/**
* Slowly I'm moving screen crap into this class
*/
class Screen : public PeriodicTask
{
public:
void setup();
virtual void doTask();
/// Turn on the screen asap
void doWakeScreen();
/// Is the screen currently on
bool isOn();
/// Turn the screen on/off
void setOn(bool on);
/// Handle a button press
void onPress();
/// Rebuilt our list of screens
void setFrames();
private:
};
extern Screen screen;

240
src/sleep.cpp Normal file
View File

@@ -0,0 +1,240 @@
#include "configuration.h"
#include "rom/rtc.h"
#include <driver/rtc_io.h>
#include <TinyGPS++.h>
#include <Wire.h>
#include "BluetoothUtil.h"
#include "MeshBluetoothService.h"
#include "MeshService.h"
#include "GPS.h"
#include "screen.h"
#include "NodeDB.h"
#include "Periodic.h"
#include "esp32/pm.h"
#include "esp_pm.h"
#include "MeshRadio.h"
#include "main.h"
#include "sleep.h"
#ifdef T_BEAM_V10
#include "axp20x.h"
extern AXP20X_Class axp;
#endif
// deep sleep support
RTC_DATA_ATTR int bootCount = 0;
esp_sleep_source_t wakeCause; // the reason we booted this time
#define xstr(s) str(s)
#define str(s) #s
// -----------------------------------------------------------------------------
// Application
// -----------------------------------------------------------------------------
/**
* Control CPU core speed (80MHz vs 240MHz)
*
* We leave CPU at full speed during init, but once loop is called switch to low speed (for a 50% power savings)
*
*/
void setCPUFast(bool on)
{
setCpuFrequencyMhz(on ? 240 : 80);
}
void setLed(bool ledOn)
{
#ifdef LED_PIN
// toggle the led so we can get some rough sense of how often loop is pausing
digitalWrite(LED_PIN, ledOn);
#endif
#ifdef T_BEAM_V10
if (axp192_found)
{
// blink the axp led
axp.setChgLEDMode(ledOn ? AXP20X_LED_LOW_LEVEL : AXP20X_LED_OFF);
}
#endif
}
void setGPSPower(bool on)
{
DEBUG_MSG("Setting GPS power=%d\n", on);
#ifdef T_BEAM_V10
if (axp192_found)
axp.setPowerOutPut(AXP192_LDO3, on ? AXP202_ON : AXP202_OFF); // GPS main power
#endif
}
// Perform power on init that we do on each wake from deep sleep
void initDeepSleep()
{
bootCount++;
wakeCause = esp_sleep_get_wakeup_cause();
/*
Not using yet because we are using wake on all buttons being low
wakeButtons = esp_sleep_get_ext1_wakeup_status(); // If one of these buttons is set it was the reason we woke
if (wakeCause == ESP_SLEEP_WAKEUP_EXT1 && !wakeButtons) // we must have been using the 'all buttons rule for waking' to support busted boards, assume button one was pressed
wakeButtons = ((uint64_t)1) << buttons.gpios[0];
*/
// If we booted because our timer ran out or the user pressed reset, send those as fake events
const char *reason = "reset"; // our best guess
RESET_REASON hwReason = rtc_get_reset_reason(0);
if (hwReason == RTCWDT_BROWN_OUT_RESET)
reason = "brownout";
if (hwReason == TG0WDT_SYS_RESET)
reason = "taskWatchdog";
if (hwReason == TG1WDT_SYS_RESET)
reason = "intWatchdog";
if (wakeCause == ESP_SLEEP_WAKEUP_TIMER)
reason = "timeout";
DEBUG_MSG("booted, wake cause %d (boot count %d), reset_reason=%s\n", wakeCause, bootCount, reason);
}
void doDeepSleep(uint64_t msecToWake)
{
DEBUG_MSG("Entering deep sleep for %llu seconds\n", msecToWake / 1000);
// not using wifi yet, but once we are this is needed to shutoff the radio hw
// esp_wifi_stop();
BLEDevice::deinit(false); // We are required to shutdown bluetooth before deep or light sleep
screen.setOn(false); // datasheet says this will draw only 10ua
// Put radio in sleep mode (will still draw power but only 0.2uA)
service.radio.rf95.sleep();
nodeDB.saveToDisk();
#ifdef RESET_OLED
digitalWrite(RESET_OLED, 1); // put the display in reset before killing its power
#endif
#ifdef VEXT_ENABLE
digitalWrite(VEXT_ENABLE, 1); // turn off the display power
#endif
setLed(false);
#ifdef T_BEAM_V10
if (axp192_found)
{
// No need to turn this off if the power draw in sleep mode really is just 0.2uA and turning it off would
// leave floating input for the IRQ line
// If we want to leave the radio receving in would be 11.5mA current draw, but most of the time it is just waiting
// in its sequencer (true?) so the average power draw should be much lower even if we were listinging for packets
// all the time.
// axp.setPowerOutPut(AXP192_LDO2, AXP202_OFF); // LORA radio
setGPSPower(false);
}
#endif
/*
Some ESP32 IOs have internal pullups or pulldowns, which are enabled by default.
If an external circuit drives this pin in deep sleep mode, current consumption may
increase due to current flowing through these pullups and pulldowns.
To isolate a pin, preventing extra current draw, call rtc_gpio_isolate() function.
For example, on ESP32-WROVER module, GPIO12 is pulled up externally.
GPIO12 also has an internal pulldown in the ESP32 chip. This means that in deep sleep,
some current will flow through these external and internal resistors, increasing deep
sleep current above the minimal possible value.
Note: we don't isolate pins that are used for the LORA, LED, i2c, spi or the wake button
*/
static const uint8_t rtcGpios[] = {/* 0, */ 2,
/* 4, */
#ifndef USE_JTAG
12, 13, /* 14, */ /* 15, */
#endif
/* 25, */ 26, /* 27, */
32, 33, 34, 35, 36, 37, /* 38, */ 39};
for (int i = 0; i < sizeof(rtcGpios); i++)
rtc_gpio_isolate((gpio_num_t)rtcGpios[i]);
// FIXME, disable internal rtc pullups/pulldowns on the non isolated pins. for inputs that we aren't using
// to detect wake and in normal operation the external part drives them hard.
// We want RTC peripherals to stay on
esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);
#ifdef BUTTON_PIN
// Only GPIOs which are have RTC functionality can be used in this bit map: 0,2,4,12-15,25-27,32-39.
uint64_t gpioMask = (1ULL << BUTTON_PIN);
// Not needed because both of the current boards have external pullups
// FIXME change polarity in hw so we can wake on ANY_HIGH instead - that would allow us to use all three buttons (instead of just the first)
// gpio_pullup_en((gpio_num_t)BUTTON_PIN);
esp_sleep_enable_ext1_wakeup(gpioMask, ESP_EXT1_WAKEUP_ALL_LOW);
#endif
esp_sleep_enable_timer_wakeup(msecToWake * 1000ULL); // call expects usecs
esp_deep_sleep_start(); // TBD mA sleep current (battery)
}
/**
* enter light sleep (preserves ram but stops everything about CPU).
*
* Returns (after restoring hw state) when the user presses a button or we get a LoRa interrupt
*/
esp_sleep_wakeup_cause_t doLightSleep(uint64_t sleepMsec) // FIXME, use a more reasonable default
{
//DEBUG_MSG("Enter light sleep\n");
uint64_t sleepUsec = sleepMsec * 1000LL;
Serial.flush(); // send all our characters before we stop cpu clock
setBluetoothEnable(false); // has to be off before calling light sleep
// NOTE! ESP docs say we must disable bluetooth and wifi before light sleep
// We want RTC peripherals to stay on
esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);
gpio_wakeup_enable((gpio_num_t)BUTTON_PIN, GPIO_INTR_LOW_LEVEL); // when user presses, this button goes low
gpio_wakeup_enable((gpio_num_t)DIO0_GPIO, GPIO_INTR_HIGH_LEVEL); // RF95 interrupt, active high
#ifdef PMU_IRQ
gpio_wakeup_enable((gpio_num_t)PMU_IRQ, GPIO_INTR_HIGH_LEVEL); // pmu irq
#endif
assert(esp_sleep_enable_gpio_wakeup() == ESP_OK);
assert(esp_sleep_enable_timer_wakeup(sleepUsec) == ESP_OK);
assert(esp_light_sleep_start() == ESP_OK);
//DEBUG_MSG("Exit light sleep\n");
return esp_sleep_get_wakeup_cause();
}
#if 0
// not legal on the stock android ESP build
/**
* enable modem sleep mode as needed and available. Should lower our CPU current draw to an average of about 20mA.
*
* per https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/system/power_management.html
*
* supposedly according to https://github.com/espressif/arduino-esp32/issues/475 this is already done in arduino
*/
void enableModemSleep()
{
static esp_pm_config_esp32_t config; // filled with zeros because bss
config.max_freq_mhz = CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ;
config.min_freq_mhz = 10; // 10Mhz is minimum recommended
config.light_sleep_enable = false;
DEBUG_MSG("Sleep request result %x\n", esp_pm_configure(&config));
}
#endif

21
src/sleep.h Normal file
View File

@@ -0,0 +1,21 @@
#pragma once
#include "Arduino.h"
#include "esp_sleep.h"
void doDeepSleep(uint64_t msecToWake);
esp_sleep_wakeup_cause_t doLightSleep(uint64_t msecToWake);
void setBluetoothEnable(bool on);
void setGPSPower(bool on);
// Perform power on init that we do on each wake from deep sleep
void initDeepSleep();
void setCPUFast(bool on);
void setLed(bool ledOn);
extern int bootCount;
extern esp_sleep_source_t wakeCause;
// is bluetooth sw currently running?
extern bool bluetoothOn;