Compare commits

..

130 Commits
0.6.0 ... 0.6.4

Author SHA1 Message Date
Kevin Hester
1897d4703c Merge pull request #142 from geeksville/reliable
Reliable messages now also work for broadcasts
2020-05-21 17:55:31 -07:00
geeksville
a25cead7d7 Merge remote-tracking branch 'root/master' into reliable 2020-05-21 17:51:50 -07:00
geeksville
3d919b21f6 0.6.4 2020-05-21 17:51:35 -07:00
geeksville
d2de04d5b2 Fix #59 no need for broadcasts when showing new node pane 2020-05-21 17:21:44 -07:00
Kevin Hester
a753c942b9 Merge pull request #141 from geeksville/reliable
Reliable
2020-05-21 16:46:01 -07:00
geeksville
9dd88281af reliable broadcast now works 2020-05-21 16:34:16 -07:00
geeksville
e75561016b retransmissions work again 2020-05-21 15:55:57 -07:00
geeksville
e2cbccb133 add want_ack support for broadcast packets 2020-05-21 12:47:41 -07:00
geeksville
0271df0657 add beginnings of full DSR routing 2020-05-21 12:47:08 -07:00
Kevin Hester
e05e324a7c Merge pull request #136 from geeksville/reliable
WIP for reliable unicast and BLE software update
2020-05-19 16:09:06 -07:00
geeksville
71041e8674 reliable unicast 1 hop works! 2020-05-19 15:51:07 -07:00
geeksville
c65b518432 less logspam 2020-05-19 14:54:58 -07:00
geeksville
6ba960ce47 one hop reliable ready for testing 2020-05-19 14:54:47 -07:00
geeksville
8bf4919576 wip reliable unicast (1 hop) 2020-05-19 11:56:17 -07:00
geeksville
cca4867987 want_ack flag added 2020-05-19 10:27:28 -07:00
geeksville
7aa47cf93b Merge remote-tracking branch 'root/master' into reliable 2020-05-19 10:20:34 -07:00
Kevin Hester
3089de79ee thanks @dafeman for documentation updates!
README GUI update
2020-05-19 07:31:43 -07:00
Dafeman
6b020149f3 Update GUI Install 2020-05-19 13:50:07 +12:00
Dafeman
34fae52e98 Merge pull request #2 from meshtastic/master
Update
2020-05-19 13:30:21 +12:00
geeksville
976bdad067 sniffReceived now allows router to inspect packets not destined for this node 2020-05-18 17:57:58 -07:00
geeksville
26d3ef529e Use the hop_limit field of MeshPacket to limit max delivery depth in
the mesh.
2020-05-18 17:35:23 -07:00
geeksville
53c3d9baa2 doc updates 2020-05-18 17:02:51 -07:00
Kevin Hester
2a6858fa34 Update CNAME 2020-05-18 08:10:51 -07:00
Kevin Hester
5440cbec6a Update CNAME 2020-05-18 08:08:57 -07:00
geeksville
19f5a5ef79 oops - use correct battery shutoff voltage 2020-05-17 05:12:16 -07:00
geeksville
ef831a0b4d Fix leaving display on in deep sleep.
We shutoff screen immediately, rather than waiting for our loop call()
2020-05-17 05:11:32 -07:00
geeksville
efc239533c Fix #133 - force deep sleep if battery reaches 10% 2020-05-17 05:10:51 -07:00
geeksville
ef1463a6a9 have tbeam charge at max rate (450mA) 2020-05-17 04:44:48 -07:00
geeksville
95e952b896 todo update 2020-05-16 16:09:06 -07:00
geeksville
db72faca5e Merge remote-tracking branch 'root/master' 2020-05-15 11:25:47 -07:00
geeksville
6961853ed7 ble software update fixes 2020-05-15 10:16:10 -07:00
geeksville
5ec5248fe4 complete ble ota move 2020-05-14 14:22:11 -07:00
geeksville
14fdd33972 move bluetooth OTA back into main tree for now 2020-05-14 14:20:05 -07:00
geeksville
140e29840a fix rare gurumeditation if we are unlucky and some ISR code is in serial flash 2020-05-14 12:46:29 -07:00
Kevin Hester
d1d318fad5 Merge pull request #135 from mehuman/supported-hardware
Supported hardware README updates
2020-05-13 08:22:23 -07:00
Mark Huson
dfb6c0bb20 Merge branch 'master' into supported-hardware 2020-05-12 19:15:47 -07:00
Mark Huson
7339abbab5 Update README.md 2020-05-12 19:14:12 -07:00
Mark Huson
27db0e27e8 Update supported hardware 2020-05-12 19:11:16 -07:00
geeksville
a0b43b9a95 Send "unset" for hwver and swver if they were unset 2020-05-12 17:57:51 -07:00
geeksville
b6a202d68e runs again with new protobufs 2020-05-12 13:35:22 -07:00
Dafeman
125035d546 Merge pull request #1 from meshtastic/master
Update
2020-05-12 22:49:54 +12:00
geeksville
9f05ad2927 remove random delay hack from broadcast, since we now do that for all transmits 2020-05-11 16:19:44 -07:00
geeksville
86ae69d360 refactor so I can track and ignore recent packets of any type 2020-05-11 16:14:53 -07:00
geeksville
c12fb69ca2 update protos 2020-05-10 14:17:05 -07:00
geeksville
8b911aba7f Cleanup build for NRF52 targets 2020-05-10 12:33:17 -07:00
geeksville
2fa595523f minor fixups to get nrf52 building again 2020-05-09 21:02:56 -07:00
geeksville
190a3c2d6b filename typo 2020-05-09 20:27:08 -07:00
Kevin Hester
1bf9d052fc Merge pull request #132 from geeksville/crypto
Crypto
2020-05-09 19:14:01 -07:00
Kevin Hester
e7b99b0d78 Merge branch 'master' into crypto 2020-05-09 19:12:00 -07:00
geeksville
96313ee1c4 remove stale link 2020-05-09 19:11:06 -07:00
geeksville
3e356e5866 Crypto works! 2020-05-09 19:08:04 -07:00
geeksville
1cc24de787 stub encryptor seems nicely backwards compatible with old devices and apps 2020-05-09 17:51:20 -07:00
geeksville
e6875d559c Remove MeshRadio wrapper class - we don't need it anymore. 2020-05-09 16:32:26 -07:00
geeksville
b73dd5b23b misc todo 2020-05-09 16:15:16 -07:00
geeksville
28d21ecdcc begin work on crypto 2020-05-09 16:15:01 -07:00
Kevin Hester
42298abfad Merge pull request #131 from Dafeman/master
Pad Bluetooth passkey to 6 digits
2020-05-09 10:13:29 -07:00
Dafeman
c4a1fe0f36 Pad Bluetooth passkey to 6 digits 2020-05-09 23:09:36 +12:00
Mark Huson
0396f8f968 Merge pull request #1 from meshtastic/master
Merge upstream
2020-05-08 08:50:58 -07:00
Kevin Hester
f1b840dede Merge pull request #128 from mehuman/device-update
Device update
2020-05-07 14:42:42 -07:00
Mark Huson
4da5d79e88 add device-update to zip 2020-05-06 19:45:02 -07:00
Mark Huson
fc0c9bcfe3 add update script and README changes 2020-05-06 19:43:17 -07:00
Kevin Hester
32d0368f59 Merge pull request #127 from geeksville/nema-124
0.6.3 - fix the problem of BLE message receiption being busted in 0.6.2
2020-05-05 18:49:44 -07:00
geeksville
8bfe9fa8fc 0.6.3 - fix the problem of BLE message receiption being busted in 0.6.2 2020-05-05 18:40:17 -07:00
Kevin Hester
f10ad07f97 Merge pull request #125 from geeksville/nema-124
support ublox 8m gpses (I think)
2020-05-04 20:18:33 -07:00
geeksville
95df7dd8dc 0.6.2 2020-05-04 20:04:44 -07:00
geeksville
dcd1f7478a fix 124 - we now fallback to nema if we can't talk ublox protocol to
the GPS.  Though we are super power inefficient about it so TODO/FIXME
someday to decrease our power draw.
2020-05-04 20:02:43 -07:00
geeksville
c2be6c4068 WIP on #124 2020-05-04 17:39:57 -07:00
geeksville
101eef5495 oops lat/lon need to be signed ;-) 2020-05-04 11:21:24 -07:00
geeksville
933d5424da abstract out the UBlox GPS driver 2020-05-04 11:15:05 -07:00
geeksville
ecf528f9b6 move gps before refactoring 2020-05-04 10:23:47 -07:00
geeksville
9b309fe0a0 Use int based lat/long from now on in the device code
for https://github.com/meshtastic/Meshtastic-device/issues/124
2020-05-04 08:09:08 -07:00
Kevin Hester
29fd8dc7a5 Merge pull request #123 from geeksville/screen
fix missing carriage returns.  thanks to @gregwalters in #119
2020-05-02 20:24:03 -07:00
geeksville
624b95782d fix missing carriage returns. thanks to @gregwalters in #119 2020-05-02 20:21:42 -07:00
Kevin Hester
4fa25042c8 Merge pull request #122 from geeksville/dropped
changes to fix #121
2020-05-02 20:17:14 -07:00
Kevin Hester
9f9cb030ad Merge branch 'master' into dropped 2020-05-02 20:14:48 -07:00
geeksville
1d9290afc0 now that the rfinterfaces are smarter, no need to do backoff in
the flood router.  the interfaces will handle it.
2020-05-02 19:53:58 -07:00
geeksville
ad2f639195 don't leak messages if they are handled locally 2020-05-02 19:53:13 -07:00
geeksville
07b4eea037 fix log msg 2020-05-02 19:52:54 -07:00
geeksville
79c61cf0e0 limit max power on rf95 to 17 (rather than 20, because 20 can...
burn up parts if you exceed 1% duty cycle)
2020-05-02 19:52:37 -07:00
geeksville
80268ea56a send() is supposed to always free buffers, even if it returns an error 2020-05-02 19:51:55 -07:00
geeksville
bb9f595b8b Fix #11 2020-05-02 19:51:25 -07:00
geeksville
2ad314f150 we now always listen before transmit - even if we have just completed a packet 2020-05-02 08:29:51 -07:00
Kevin Hester
916e62398d Merge pull request #120 from geeksville/master
fix busted build on heltec style devices (0.6.1)
2020-05-01 17:01:52 -07:00
geeksville
4735b3ff5b 0.6.1 hotfix build for busted heltec style devices 2020-05-01 16:35:32 -07:00
geeksville
cfd6483ea5 oops - platform IO can have stale target specific builds without this 2020-05-01 16:34:16 -07:00
geeksville
4f7a25f562 remove unneeded include 2020-05-01 16:33:40 -07:00
geeksville
4176d79ee9 fix warnings 2020-05-01 16:33:26 -07:00
Kevin Hester
fad496378c Merge pull request #118 from geeksville/master
misc fri workqueue
2020-05-01 12:37:28 -07:00
geeksville
e084699704 SNR is now a float, fix the screen display 2020-05-01 12:31:36 -07:00
geeksville
50213d8323 move packet handling into its own thread 2020-05-01 12:11:04 -07:00
geeksville
763276a2c8 Merge branch 'radiolib' 2020-05-01 09:04:19 -07:00
geeksville
71fcdba017 cleanup directory structure 2020-05-01 09:04:00 -07:00
Kevin Hester
08227e79d0 Merge pull request #117 from geeksville/radiolib
Change to use Radiolib as the basis for our networking, and add RX1262 support
2020-05-01 08:55:17 -07:00
geeksville
5a4fab2506 start msg sequence numbers with a random number each boot 2020-05-01 08:51:53 -07:00
geeksville
31eb2f5337 very important: don't allow immediate sends if we have pending ISRs 2020-05-01 08:32:16 -07:00
geeksville
82c1752d85 less logspam 2020-05-01 08:31:52 -07:00
geeksville
49a13bbfd3 increase gps config timeout, could take up to 2.5 secs 2020-05-01 08:31:31 -07:00
geeksville
0096f54ae9 better debug output 2020-04-30 22:53:21 -07:00
geeksville
5af122b39d update todo list 2020-04-30 21:49:55 -07:00
geeksville
4e106f4098 remove radiohead 2020-04-30 21:42:11 -07:00
geeksville
1f1d683f4f add back the old code that checked if the radio was actvively receiving 2020-04-30 21:29:51 -07:00
geeksville
a8f64c3cc8 make a custom version fo rf95 class, so we can can deal with
chips that have bad version codes.
2020-04-30 21:11:03 -07:00
geeksville
968a2d7fbc store SNR in received packets 2020-04-30 19:58:10 -07:00
geeksville
1fab9c5aac temp hack to get new rf95 driver working 2020-04-30 19:31:17 -07:00
geeksville
22bca31ce3 properly set the RF95 iface 2020-04-30 18:05:06 -07:00
geeksville
48c045a253 move SPI init into main 2020-04-30 17:56:30 -07:00
geeksville
e9ca7792eb new RF95 driver is written 2020-04-30 17:43:29 -07:00
geeksville
b1a55b4576 old RF95 API works again 2020-04-30 16:47:56 -07:00
geeksville
dd7452ad96 old RF95 code builds again 2020-04-30 16:36:59 -07:00
geeksville
d7d8188093 implement most of sleep handling for the new radio stack 2020-04-30 15:50:07 -07:00
geeksville
62a893c760 SX1262 approximately works top-to-bottom, but need to add sleep modes 2020-04-30 15:43:41 -07:00
geeksville
a2ba9d3c44 new receive code works a little better 2020-04-30 13:50:40 -07:00
geeksville
22720e9f63 ex1262 receiving kinda works 2020-04-30 12:37:58 -07:00
geeksville
11b79a942d add todos 2020-04-30 10:54:53 -07:00
geeksville
3c3e722181 new sending kinda works 2020-04-30 10:00:40 -07:00
geeksville
fce31560c6 the mountain of changes needed to kinda make tx work compiles. 2020-04-30 09:44:16 -07:00
geeksville
074ac33b8a make a gdb "restart" command that allows restarting without rebuilding 2020-04-29 20:23:59 -07:00
geeksville
2982e197e0 radio settings now work on real sx1262 hw 2020-04-29 19:04:59 -07:00
geeksville
f69ddf168b we now hopefully apply the same radio settings as we did for the RF95 2020-04-29 18:46:32 -07:00
geeksville
8d985cfd37 cleanup so eventually rf95 can share common msg code with sx1262 2020-04-29 16:28:11 -07:00
geeksville
4693302d82 crummy sx1262 fake init kinda works 2020-04-29 16:06:23 -07:00
geeksville
814c126e67 ugly WIP on switching to RadioLib, still need to set freq etc... 2020-04-29 14:54:03 -07:00
geeksville
a7d153abcb CUSTOM GPIOs the SX1262MB2CAS shield when installed on the NRF52840-DK development board 2020-04-29 12:57:34 -07:00
geeksville
1b265eb48d switch from sx126x-arduino to radiolab 2020-04-29 10:50:50 -07:00
geeksville
94e80d3b44 mention python API 2020-04-28 20:51:02 -07:00
geeksville
f1ec95f49b update project name 2020-04-28 20:47:20 -07:00
Kevin Hester
7ee2643e9a Merge pull request #114 from geeksville/master
Add python API to webpage
2020-04-28 17:48:00 -07:00
geeksville
2ab34357d5 emit FromRadio.rebooted to serial test harness can detect reboots 2020-04-28 17:43:16 -07:00
geeksville
b53392ab73 Merge remote-tracking branch 'root/master' 2020-04-28 17:07:42 -07:00
geeksville
803d2dfefb add note about python API 2020-04-28 17:06:00 -07:00
114 changed files with 3769 additions and 6829 deletions

32
.vscode/launch.json vendored
View File

@@ -1,32 +0,0 @@
// AUTOMATICALLY GENERATED FILE. PLEASE DO NOT MODIFY IT MANUALLY
// PIO Unified Debugger
//
// Documentation: https://docs.platformio.org/page/plus/debugging.html
// Configuration: https://docs.platformio.org/page/projectconf/section_env_debug.html
{
"version": "0.2.0",
"configurations": [
{
"type": "platformio-debug",
"request": "launch",
"name": "PIO Debug",
"executable": "/home/kevinh/development/meshtastic/meshtastic-esp32/.pio/build/tbeam/firmware.elf",
"toolchainBinDir": "/home/kevinh/.platformio/packages/toolchain-xtensa32/bin",
"preLaunchTask": {
"type": "PlatformIO",
"task": "Pre-Debug"
},
"internalConsoleOptions": "openOnSessionStart"
},
{
"type": "platformio-debug",
"request": "launch",
"name": "PIO Debug (skip Pre-Debug)",
"executable": "/home/kevinh/development/meshtastic/meshtastic-esp32/.pio/build/tbeam/firmware.elf",
"toolchainBinDir": "/home/kevinh/.platformio/packages/toolchain-xtensa32/bin",
"internalConsoleOptions": "openOnSessionStart"
}
]
}

View File

@@ -50,7 +50,10 @@
"cassert": "cpp"
},
"cSpell.words": [
"Blox",
"Meshtastic",
"NEMAGPS",
"Ublox",
"descs",
"protobufs"
]

View File

@@ -1,4 +1,4 @@
# Meshtastic-esp32
# Meshtastic-device
This is the device side code for the [meshtastic.org](https://www.meshtastic.org) project.
@@ -20,9 +20,25 @@ This software is 100% open source and developed by a group of hobbyist experimen
## Supported hardware
We currently support three models of radios. The [TTGO T-Beam](https://www.aliexpress.com/item/4000119152086.html), [TTGO LORA32](https://www.banggood.com/LILYGO-TTGO-LORA32-868Mhz-SX1276-ESP32-Oled-Display-bluetooth-WIFI-Lora-Development-Module-Board-p-1248652.html?cur_warehouse=UK) and the [Heltec LoRa 32](https://heltec.org/project/wifi-lora-32/). Most users should buy the T-Beam and an 18650 battery (total cost less than \$35). Make sure to buy the frequency range which is legal for your country (915MHz for US/JP/AU/NZ, 470MHz for CN, 433MHz and 870MHz for EU). Getting a version that includes a screen is optional, but highly recommended.
We currently support three models of radios.
- TTGO T-Beam
- [T-Beam V1.0 w/ NEO-M8N](https://www.aliexpress.com/item/33047631119.html) (Recommended)
- [T-Beam V1.0 w/ NEO-6M](https://www.aliexpress.com/item/33050391850.html)
- 3D printable cases
- [T-Beam V0](https://www.thingiverse.com/thing:3773717)
- [T-Beam V1](https://www.thingiverse.com/thing:3830711)
See (meshtastic.org) for 3D printable cases.
- [TTGO LORA32](https://www.aliexpress.com/item/4000211331316.html) - No GPS
- [Heltec LoRa 32](https://heltec.org/project/wifi-lora-32/) - No GPS
- [3D Printable case](https://www.thingiverse.com/thing:3125854)
**Make sure to get the frequency for your country**
- US/JP/AU/NZ - 915MHz
- CN - 470MHz
- EU - 870MHz
Getting a version that includes a screen is optional, but highly recommended.
## Firmware Installation
@@ -35,12 +51,13 @@ Please post comments on our [group chat](https://meshtastic.discourse.group/) if
1. Download and unzip the latest Meshtastic firmware [release](https://github.com/meshtastic/Meshtastic-esp32/releases).
2. Download [ESPHome Flasher](https://github.com/esphome/esphome-flasher/releases) (either x86-32bit Windows or x64-64 bit Windows).
3. Connect your radio to your USB port and open ESPHome Flasher.
4. If your board is not showing under Serial Port then you likely need to install the drivers for the CP210X serial chip. In Windows you can check by searching “Device Manager” and ensuring the device is shown under “Ports”.
5. If there is an error, download the drivers [here](https://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp-drivers), then unzip and run the Installer application.
4. If your board is not showing under Serial Port then you likely need to install the drivers for the CP210X serial chip. In Windows you can check by searching “Device Manager” and ensuring the device is shown under “Ports”.
5. If there is an error, download the drivers [here](https://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp-drivers), then unzip and run the Installer application.
6. In ESPHome Flasher, refresh the serial ports and select your board.
7. Browse to the previously downloaded firmware and select the correct firmware based on the board type, country and frequency.
8. Select Flash ESP.
9. Once finished, the terminal should start displaying debug messages including the Bluetooth passphrase when you try connect from your phone (handy if you dont have a screen).
9. Once complete, “Done! Flashing is complete!” will be shown.
10. Debug messages sent from the Meshtastic device can be viewed with a terminal program such as [PuTTY](https://www.putty.org/) (Windows only). Within PuTTY, click “Serial”, enter the “Serial line” com port (can be found at step 4), enter “Speed” as 921600, then click “Open”.
### Installing from a commandline
@@ -70,7 +87,10 @@ Hard resetting via RTS pin...
```
5. cd into the directory where the release zip file was expanded.
6. Install the correct firmware for your board with "device-install.sh firmware-_board_-_country_.bin". For instance "./device-install.sh firmware-HELTEC-US-0.0.3.bin".
6. Install the correct firmware for your board with `device-install.sh firmware-_board_-_country_.bin`.
- Example: `./device-install.sh firmware-HELTEC-US-0.0.3.bin`.
7. To update run `device-update.sh firmware-_board_-_country_.bin`
- Example: `./device-update.sh firmware-HELTEC-US-0.0.3.bin`.
Note: If you have previously installed meshtastic, you don't need to run this full script instead just run "esptool.py --baud 921600 write*flash 0x10000 firmware-\_board*-_country_.bin". This will be faster, also all of your current preferences will be preserved.
@@ -143,15 +163,19 @@ Hard resetting via RTS pin...
7. The board will boot and show the Meshtastic logo.
8. Please post a comment on our chat so we know if these instructions worked for you ;-). If you find bugs/have-questions post there also - we will be rapidly iterating over the next few weeks.
## Meshtastic Android app
# Meshtastic Android app
The source code for the (optional) Meshtastic Android app is [here](https://github.com/meshtastic/Meshtastic-Android).
Alpha test builds are current available by opting into our alpha test group. See (www.meshtastic.org) for instructions.
Alpha test builds 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):
If you don't want to live on the 'bleeding edge' you can opt-in to the beta-test or use the released version:
[![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)
# Python API
We offer a [python API](https://github.com/meshtastic/Meshtastic-python) that makes it easy to use these devices to provide mesh networking for your custom projects.
# Development
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 in our discussion forum](https://meshtastic.discourse.group/).

View File

@@ -39,6 +39,12 @@ function do_build {
cp $SRCELF $OUTDIR/elfs/firmware-$ENV_NAME-$COUNTRY-$VERSION.elf
}
# Make sure our submodules are current
git submodule update
# Important to pull latest version of libs into all device flavors, otherwise some devices might be stale
platformio lib update
for COUNTRY in $COUNTRIES; do
for BOARD in $BOARDS; do
do_build $BOARD
@@ -61,6 +67,6 @@ Generated by bin/buildall.sh -->
XML
rm -f $ARCHIVEDIR/firmware-$VERSION.zip
zip --junk-paths $ARCHIVEDIR/firmware-$VERSION.zip $OUTDIR/bins/firmware-*-$VERSION.* images/system-info.bin bin/device-install.sh
zip --junk-paths $ARCHIVEDIR/firmware-$VERSION.zip $OUTDIR/bins/firmware-*-$VERSION.* images/system-info.bin bin/device-install.sh bin/device-update.sh
echo BUILT ALL
echo BUILT ALL

8
bin/device-update.sh Executable file
View File

@@ -0,0 +1,8 @@
#!/bin/bash
set -e
FILENAME=$1
echo "Trying to update $FILENAME"
esptool.py --baud 921600 writeflash 0x10000 $FILENAME

View File

@@ -1,3 +1,3 @@
export VERSION=0.6.0
export VERSION=0.6.4

View File

@@ -0,0 +1,46 @@
{
"build": {
"arduino": {
"ldscript": "nrf52840_s140_v6.ld"
},
"core": "nRF5",
"cpu": "cortex-m4",
"extra_flags": "-DARDUINO_NRF52840_PCA10056 -DNRF52840_XXAA",
"f_cpu": "64000000L",
"hwids": [["0x239A", "0x4404"]],
"usb_product": "SimPPR",
"mcu": "nrf52840",
"variant": "pca10056-rc-clock",
"variants_dir": "variants",
"bsp": {
"name": "adafruit"
},
"softdevice": {
"sd_flags": "-DS140",
"sd_name": "s140",
"sd_version": "6.1.1",
"sd_fwid": "0x00B6"
},
"bootloader": {
"settings_addr": "0xFF000"
}
},
"connectivity": ["bluetooth"],
"debug": {
"jlink_device": "nRF52840_xxAA",
"onboard_tools": ["jlink"],
"svd_path": "nrf52840.svd"
},
"frameworks": ["arduino"],
"name": "A modified NRF52840-DK devboard (Adafruit BSP)",
"upload": {
"maximum_ram_size": 248832,
"maximum_size": 815104,
"require_upload_port": true,
"speed": 115200,
"protocol": "jlink",
"protocols": ["jlink", "nrfjprog", "stlink"]
},
"url": "https://meshtastic.org/",
"vendor": "Nordic Semi"
}

View File

@@ -1,7 +1,7 @@
# What is Meshtastic?
Meshtastic is a project that lets you use
inexpensive (\$30 ish) GPS radios as an extensible, super long battery life mesh GPS communicator. These radios are great for hiking, skiing, paragliding - essentially any hobby where you don't have reliable internet access. Each member of your private mesh can always see the location and distance of all other members and any text messages sent to your group chat.
inexpensive (\$30 ish) GPS radios as an extensible, long battery life, secure, mesh GPS communicator. These radios are great for hiking, skiing, paragliding - essentially any hobby where you don't have reliable internet access. Each member of your private mesh can always see the location and distance of all other members and any text messages sent to your group chat.
The radios automatically create a mesh to forward packets as needed, so everyone in the group can receive messages from even the furthest member. The radios will optionally work with your phone, but no phone is required.
@@ -13,6 +13,7 @@ Note: Questions after reading this? See our new [forum](https://meshtastic.disco
- Applications where closed source GPS communicators just won't cut it (it is easy to add features for glider pilots etc...)
- Secure long-range communication within groups without depending on cellular providers
- Finding your lost kids ;-)
- Through our [python API](https://pypi.org/project/meshtastic/) use these inexpensive radios to easily add mesh networking to your own projects.
[![Youtube video demo](desk-video-screenshot.png)](https://www.youtube.com/watch?v=WlNbMbVZlHI "Meshtastic early demo")
@@ -38,6 +39,7 @@ This software is 100% open source and developed by a group of hobbyist experimen
Note: Updates are happening almost daily, only major updates are listed below. For more details see our forum.
- 04/28/2020 - 0.6.0 [Python API](https://pypi.org/project/meshtastic/) released. Makes it easy to use meshtastic devices as "zero config / just works" mesh transport adapters for other projects.
- 04/20/2020 - 0.4.3 Pretty solid now both for the android app and the device code. Many people have donated translations and code. Probably going to call it a beta soon.
- 03/03/2020 - 0.0.9 of the Android app and device code is released. Still an alpha but fairly functional.
- 02/25/2020 - 0.0.4 of the Android app is released. This is a very early alpha, see below to join the alpha-testers group.

View File

@@ -4,7 +4,7 @@ This project is still pretty young but moving at a pretty good pace. Not all fea
Most of these problems should be solved by the beta release (within three months):
- We don't make these devices and they haven't been tested by UL or the FCC. If you use them you are experimenting and we can't promise they won't burn your house down ;-)
- Encryption is turned off for now
- The encryption [implementation](software/crypto.md) has not been reviewed by an expert. (Are you an expert? Please help us)
- A number of (straightforward) software work items have to be completed before battery life matches our measurements, currently battery life is about three days. Join us on chat if you want the spreadsheet of power measurements/calculations.
- The Android API needs to be documented better
- No one has written an iOS app yet. But some good souls [are talking about it](https://github.com/meshtastic/Meshtastic-esp32/issues/14) ;-)

View File

@@ -5,21 +5,16 @@ 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.
- remeasure wake time power draws now that we run CPU down at 80MHz
# AXP192 tasks
- figure out why this fixme is needed: "FIXME, disable wake due to PMU because it seems to fire all the time?"
- "AXP192 interrupt is not firing, remove this temporary polling of battery state"
- make debug info screen show real data (including battery level & charging) - close corresponding github issue
# Medium priority
Items to complete before the first beta release.
- Don't store position packets in the to phone fifo if we are disconnected. The phone will get that info for 'free' when it
fetches the fresh nodedb.
- Use the RFM95 sequencer to stay in idle mode most of the time, then automatically go to receive mode and automatically go from transmit to receive mode. See 4.2.8.2 of manual.
- Use 32 bits for message IDs
- Use fixed32 for node IDs
- Remove the "want node" node number arbitration process
- Don't store position packets in the to phone fifo if we are disconnected. The phone will get that info for 'free' when it
fetches the fresh nodedb.
- Use the RFM95 sequencer to stay in idle mode most of the time, then automatically go to receive mode and automatically go from transmit to receive mode. See 4.2.8.2 of manual.
- possibly switch to https://github.com/SlashDevin/NeoGPS for gps comms
- good source of battery/signal/gps icons https://materialdesignicons.com/
- research and implement better mesh algorithm - investigate changing routing to https://github.com/sudomesh/LoRaLayer2 ?
@@ -29,7 +24,6 @@ fetches the fresh nodedb.
- rx signal measurements -3 marginal, -9 bad, 10 great, -10 means almost unusable. So scale this into % signal strength. preferably as a graph, with an X indicating loss of comms.
- assign every "channel" a random shared 8 bit sync word (per 4.2.13.6 of datasheet) - use that word to filter packets before even checking CRC. This will ensure our CPU will only wake for packets on our "channel"
- Note: we do not do address filtering at the chip level, because we might need to route for the mesh
- add basic crypto - https://github.com/chegewara/esp32-mbedtls-aes-test/blob/master/main/main.c https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation - use ECB at first (though it is shit) because it doesn't require us to send 16 bytes of IV with each packet. Then OFB per example. Possibly do this crypto at the data payload level only, so that all of the packet routing metadata
is in cleartext (so that nodes will route for other radios that are cryptoed with a key we don't know)
- add frequency hopping, dependent on the gps time, make the switch moment far from the time anyone is going to be transmitting
- share channel settings over Signal (or qr code) by embedding an an URL which is handled by the MeshUtil app.
@@ -205,3 +199,7 @@ Items after the first final candidate release.
- enable fast lock and low power inside the gps chip
- Make a FAQ
- add a SF12 transmit option for _super_ long range
- figure out why this fixme is needed: "FIXME, disable wake due to PMU because it seems to fire all the time?"
- "AXP192 interrupt is not firing, remove this temporary polling of battery state"
- make debug info screen show real data (including battery level & charging) - close corresponding github issue
- remeasure wake time power draws now that we run CPU down at 80MHz

40
docs/software/crypto.md Normal file
View File

@@ -0,0 +1,40 @@
# Encryption in Meshtastic
Cryptography is tricky, so we've tried to 'simply' apply standard crypto solutions to our implementation. However,
the project developers are not cryptography experts. Therefore we ask two things:
- If you are a cryptography expert, please review these notes and our questions below. Can you help us by reviewing our
notes below and offering advice? We will happily give as much or as little credit as you wish ;-).
- Consider our existing solution 'alpha' and probably fairly secure against a not particularly aggressive adversary. But until
it is reviewed by someone smarter than us, assume it might have flaws.
## Notes on implementation
- We do all crypto at the SubPacket (payload) level only, so that all meshtastic nodes will route for others - even those channels which are encrypted with a different key.
- Mostly based on reading [Wikipedia](<https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_(CTR)>) and using the modes the ESP32 provides support for in hardware.
- We use AES256-CTR as a stream cypher (with zero padding on the last BLOCK) because it is well supported with hardware acceleration.
Parameters for our CTR implementation:
- Our AES key is 128 or 256 bits, shared as part of the 'Channel' specification.
- Each SubPacket will be sent as a series of 16 byte BLOCKS.
- The node number concatenated with the packet number is used as the NONCE. This counter will be stored in flash in the device and should essentially never repeat. If the user makes a new 'Channel' (i.e. picking a new random 256 bit key), the packet number will start at zero. The packet number is sent
in cleartext with each packet. The node number can be derived from the "from" field of each packet.
- Each BLOCK for a packet has an incrementing COUNTER. COUNTER starts at zero for the first block of each packet.
- The IV for each block is constructed by concatenating the NONCE as the upper 96 bits of the IV and the COUNTER as the bottom 32 bits. Note: since our packets are small counter will really never be higher than 32 (five bits).
```
You can encrypt separate messages by dividing the nonce_counter buffer in two areas: the first one used for a per-message nonce, handled by yourself, and the second one updated by this function internally.
For example, you might reserve the first 12 bytes for the per-message nonce, and the last 4 bytes for internal use. In that case, before calling this function on a new message you need to set the first 12 bytes of nonce_counter to your chosen nonce value, the last 4 to 0, and nc_off to 0 (which will cause stream_block to be ignored). That way, you can encrypt at most 2**96 messages of up to 2**32 blocks each with the same key.
The per-message nonce (or information sufficient to reconstruct it) needs to be communicated with the ciphertext and must be unique. The recommended way to ensure uniqueness is to use a message counter. An alternative is to generate random nonces, but this limits the number of messages that can be securely encrypted: for example, with 96-bit random nonces, you should not encrypt more than 2**32 messages with the same key.
Note that for both stategies, sizes are measured in blocks and that an AES block is 16 bytes.
```
## Remaining todo
- Make the packet numbers 32 bit
- Confirm the packet #s are stored in flash across deep sleep (and otherwise in in RAM)
- Have the app change the crypto key when the user generates a new channel
- Implement for NRF52 [NRF52](https://infocenter.nordicsemi.com/topic/com.nordic.infocenter.sdk5.v15.0.0/lib_crypto_aes.html#sub_aes_ctr)

View File

@@ -1,19 +1,87 @@
# Mesh broadcast algorithm
FIXME - instead look for standard solutions. this approach seems really suboptimal, because too many nodes will try to rebroast. If
all else fails could always use the stock Radiohead solution - though super inefficient.
great source of papers and class notes: http://www.cs.jhu.edu/~cs647/
flood routing improvements
- DONE if we don't see anyone rebroadcast our want_ack=true broadcasts, retry as needed.
reliable messaging tasks (stage one for DSR):
- DONE generalize naive flooding
- DONE add a max hops parameter, use it for broadcast as well (0 means adjacent only, 1 is one forward etc...). Store as three bits in the header.
- DONE add a 'snoopReceived' hook for all messages that pass through our node.
- DONE use the same 'recentmessages' array used for broadcast msgs to detect duplicate retransmitted messages.
- DONE in the router receive path?, send an ack packet if want_ack was set and we are the final destination. FIXME, for now don't handle multihop or merging of data replies with these acks.
- DONE keep a list of packets waiting for acks
- DONE for each message keep a count of # retries (max of three). Local to the node, only for the most immediate hop, ignorant of multihop routing.
- DONE delay some random time for each retry (large enough to allow for acks to come in)
- DONE once an ack comes in, remove the packet from the retry list and deliver the ack to the original sender
- DONE after three retries, deliver a no-ack packet to the original sender (i.e. the phone app or mesh router service)
- DONE test one hop ack/nak with the python framework
- Do stress test with acks
dsr tasks
- Don't use broadcasts for the network pings (close open github issue)
- add ignoreSenders to radioconfig to allow testing different mesh topologies by refusing to see certain senders
- test multihop delivery with the python framework
optimizations / low priority:
- low priority: think more careful about reliable retransmit intervals
- make ReliableRouter.pending threadsafe
- bump up PacketPool size for all the new ack/nak/routing packets
- handle 51 day rollover in doRetransmissions
- use a priority queue for the messages waiting to send. Send acks first, then routing messages, then data messages, then broadcasts?
when we send a packet
- do "hop by hop" routing
- when sending, if destnodeinfo.next_hop is zero (and no message is already waiting for an arp for that node), startRouteDiscovery() for that node. Queue the message in the 'waiting for arp queue' so we can send it later when then the arp completes.
- otherwise, use next_hop and start sending a message (with ack request) towards that node (starting with next_hop).
when we receive any packet
- sniff and update tables (especially useful to find adjacent nodes). Update user, network and position info.
- if we need to route() that packet, resend it to the next_hop based on our nodedb.
- if it is broadcast or destined for our node, deliver locally
- handle routereply/routeerror/routediscovery messages as described below
- then free it
routeDiscovery
- if we've already passed through us (or is from us), then it ignore it
- use the nodes already mentioned in the request to update our routing table
- if they were looking for us, send back a routereply
- NOT DOING FOR NOW -if max_hops is zero and they weren't looking for us, drop (FIXME, send back error - I think not though?)
- if we receive a discovery packet, and we don't have next_hop set in our nodedb, we use it to populate next_hop (if needed) towards the requester (after decrementing max_hops)
- if we receive a discovery packet, and we have a next_hop in our nodedb for that destination we send a (reliable) we send a route reply towards the requester
when sending any reliable packet
- if timeout doing retries, send a routeError (nak) message back towards the original requester. all nodes eavesdrop on that packet and update their route caches.
when we receive a routereply packet
- update next_hop on the node, if the new reply needs fewer hops than the existing one (we prefer shorter paths). fixme, someday use a better heuristic
when we receive a routeError packet
- delete the route for that failed recipient, restartRouteDiscovery()
- if we receive routeerror in response to a discovery,
- fixme, eventually keep caches of possible other routes.
TODO:
- DONE reread the radiohead mesh implementation - hop to hop acknoledgement seems VERY expensive but otherwise it seems like DSR
- optimize our generalized flooding with heuristics, possibly have particular nodes self mark as 'router' nodes.
- DONE reread the radiohead mesh implementation - hop to hop acknowledgement seems VERY expensive but otherwise it seems like DSR
- DONE read about mesh routing solutions (DSR and AODV)
- DONE read about general mesh flooding solutions (naive, MPR, geo assisted)
- DONE reread the disaster radio protocol docs - seems based on Babel (which is AODVish)
- possibly dash7? https://www.slideshare.net/MaartenWeyn1/dash7-alliance-protocol-technical-presentation https://github.com/MOSAIC-LoPoW/dash7-ap-open-source-stack - does the opensource stack implement multihop routing? flooding? their discussion mailing list looks dead-dead
- REJECTED - seems dying - possibly dash7? https://www.slideshare.net/MaartenWeyn1/dash7-alliance-protocol-technical-presentation https://github.com/MOSAIC-LoPoW/dash7-ap-open-source-stack - does the opensource stack implement multihop routing? flooding? their discussion mailing list looks dead-dead
- update duty cycle spreadsheet for our typical usecase
- generalize naive flooding on top of radiohead or disaster.radio? (and fix radiohead to use my new driver)
a description of DSR: https://tools.ietf.org/html/rfc4728 good slides here: https://www.slideshare.net/ashrafmath/dynamic-source-routing
good description of batman protocol: https://www.open-mesh.org/projects/open-mesh/wiki/BATMANConcept
@@ -77,7 +145,6 @@ look into the literature for this idea specifically.
FIXME, merge into the above:
good description of batman protocol: https://www.open-mesh.org/projects/open-mesh/wiki/BATMANConcept
interesting paper on lora mesh: https://portal.research.lu.se/portal/files/45735775/paper.pdf

View File

@@ -1,33 +1,25 @@
# NRF52 TODO
## Misc work items
## Initial work items
Minimum items needed to make sure hardware is good.
- DONE select and install a bootloader (adafruit)
- DONE get old radio driver working on NRF52
- DONE basic test of BLE
- DONE get a debug 'serial' console working via the ICE passthrough feature
- switch to RadioLab? test it with current radio. https://github.com/jgromes/RadioLib
- use "variants" to get all gpio bindings
- plug in correct variants for the real board
- test my hackedup bootloader on the real hardware
- add a hard fault handler
- Use the PMU driver on real hardware
- add a NEMA based GPS driver to test GPS
- Use new radio driver on real hardware - possibly start with https://os.mbed.com/teams/Semtech/code/SX126xLib/
- Use new radio driver on real hardware
- Use UC1701 LCD driver on real hardware. Still need to create at startup and probe on SPI
- test the LEDs
- test the buttons
- make a new boarddef with a variant.h file. Fix pins in that file. In particular (at least):
#define PIN_SPI_MISO (46)
#define PIN_SPI_MOSI (45)
#define PIN_SPI_SCK (47)
#define PIN_WIRE_SDA (26)
#define PIN_WIRE_SCL (27)
## Secondary work items
Needed to be fully functional at least at the same level of the ESP32 boards. At this point users would probably want them.
- stop polling for GPS characters, instead stay blocked on read in a thread
- increase preamble length? - will break other clients? so all devices must update
- enable BLE DFU somehow
- set appversion/hwversion
- report appversion/hwversion in BLE
@@ -46,6 +38,10 @@ Needed to be fully functional at least at the same level of the ESP32 boards. At
## Items to be 'feature complete'
- use SX126x::startReceiveDutyCycleAuto to save power by sleeping and briefly waking to check for preamble bits. Change xmit rules to have more preamble bits.
- turn back on in-radio destaddr checking for RF95
- figure out what the correct current limit should be for the sx1262, currently we just use the default 100
- put sx1262 in sleepmode when processor gets shutdown (or rebooted), ideally even for critical faults (to keep power draw low). repurpose deepsleep state for this.
- good power management tips: https://devzone.nordicsemi.com/nordic/nordic-blog/b/blog/posts/optimizing-power-on-nrf52-designs
- call PMU set_ADC_CONV(0) during sleep, to stop reading PMU adcs and decrease current draw
- do final power measurements
@@ -54,11 +50,20 @@ Needed to be fully functional at least at the same level of the ESP32 boards. At
- currently using soft device SD140, is that ideal?
- turn on the watchdog timer, require servicing from key application threads
- install a hardfault handler for null ptrs (if one isn't already installed)
- nrf52setup should call randomSeed(tbd)
## Things to do 'someday'
Nice ideas worth considering someday...
- Use flego to me an iOS/linux app? https://felgo.com/doc/qt/qtbluetooth-index/ or
- Use flutter to make an iOS/linux app? https://github.com/Polidea/FlutterBleLib
- make a Mfg Controller and device under test classes as examples of custom app code for third party devs. Make a post about this. Use a custom payload type code. Have device under test send a broadcast with max hopcount of 0 for the 'mfgcontroller' payload type. mfg controller will read SNR and reply. DOT will declare failure/success and switch to the regular app screen.
- Hook Segger RTT to the nordic logging framework. https://devzone.nordicsemi.com/nordic/nordic-blog/b/blog/posts/debugging-with-real-time-terminal
- Use nordic logging for DEBUG_MSG
- use the Jumper simulator to run meshes of simulated hardware: https://docs.jumper.io/docs/install.html
- make/find a multithread safe debug logging class (include remote logging and timestamps and levels). make each log event atomic.
- turn on freertos stack size checking
- Currently we use Nordic's vendor ID, which is apparently okay: https://devzone.nordicsemi.com/f/nordic-q-a/44014/using-nordic-vid-and-pid-for-nrf52840 and I just picked a PID of 0x4403
- Use NRF logger module (includes flash logging etc...) instead of DEBUG_MSG
- Use "LED softblink" library on NRF52 to do nice pretty "breathing" LEDs. Don't whack LED from main thread anymore.
@@ -66,11 +71,14 @@ Nice ideas worth considering someday...
- in addition to the main CPU watchdog, use the PMU watchdog as a really big emergency hammer
- turn on 'shipping mode' in the PMU when device is 'off' - to cut battery draw to essentially zero
- make Lorro_BQ25703A read/write operations atomic, current version could let other threads sneak in (once we start using threads)
- turn on DFU assistance in the appload using the nordic DFU helper lib call
- make the segger logbuffer larger, move it to RAM that is preserved across reboots and support reading it out at runtime (to allow full log messages to be included in crash reports). Share this code with ESP32 (use gcc noinit attribute)
- convert hardfaults/panics/asserts/wd exceptions into fault codes sent to phone
- stop enumerating all i2c devices at boot, it wastes power & time
- consider using "SYSTEMOFF" deep sleep mode, without RAM retension. Only useful for 'truly off - wake only by button press' only saves 1.5uA vs SYSTEMON. (SYSTEMON only costs 1.5uA). Possibly put PMU into shipping mode?
- change the BLE protocol to be more symmetric. Have the phone _also_ host a GATT service which receives writes to
'fromradio'. This would allow removing the 'fromnum' mailbox/notify scheme of the current approach and decrease the number of packet handoffs when a packet is received.
- Using the preceeding, make a generalized 'nrf52/esp32 ble to internet' bridge service. To let nrf52 apps do MQTT/UDP/HTTP POST/HTTP GET operations to web services.
- lower advertise interval to save power, lower ble transmit power to save power
## Old unorganized notes
@@ -85,6 +93,28 @@ Nice ideas worth considering someday...
- DONE add "DFU trigger library" to application load
- DONE: using this: Possibly use this bootloader? https://github.com/adafruit/Adafruit_nRF52_Bootloader
- DONE select and install a bootloader (adafruit)
- DONE get old radio driver working on NRF52
- DONE basic test of BLE
- DONE get a debug 'serial' console working via the ICE passthrough feature
- DONE switch to RadioLab? test it with current radio. https://github.com/jgromes/RadioLib
- DONE change rx95 to radiolib
- DONE track rxbad, rxgood, txgood
- DONE neg 7 error code from receive
- DONE remove unused sx1262 lib from github
- at boot we are starting our message IDs at 1, rather we should start them at a random number. also, seed random based on timer. this could be the cause of our first message not seen bug.
- add a NEMA based GPS driver to test GPS
- DONE use "variants" to get all gpio bindings
- DONE plug in correct variants for the real board
- turn on DFU assistance in the appload using the nordic DFU helper lib call
- make a new boarddef with a variant.h file. Fix pins in that file. In particular (at least):
#define PIN_SPI_MISO (46)
#define PIN_SPI_MOSI (45)
#define PIN_SPI_SCK (47)
#define PIN_WIRE_SDA (26)
#define PIN_WIRE_SCL (27)
- customize the bootloader to use proper button bindings
- remove the MeshRadio wrapper - we don't need it anymore, just do everything in RadioInterface subclasses.
```

6
gdbinit Normal file
View File

@@ -0,0 +1,6 @@
# the jlink debugger seems to want a pause after reset before we tell it to start running
define restart
monitor reset
shell sleep 1
cont
end

View File

@@ -31,7 +31,7 @@ board_build.partitions = partition-table.csv
; note: we add src to our include search path so that lmic_project_config can override
; FIXME: fix lib/BluetoothOTA dependency back on src/ so we can remove -Isrc
build_flags = -Wno-missing-field-initializers -Isrc -Isrc/rf95 -Isrc/mesh -Ilib/nanopb/include -Os -Wl,-Map,.pio/build/output.map
build_flags = -Wno-missing-field-initializers -Isrc -Isrc/mesh -Isrc/gps -Ilib/nanopb/include -Os -Wl,-Map,.pio/build/output.map
-DAXP_DEBUG_PORT=Serial
-DHW_VERSION_${sysenv.COUNTRY}
-DAPP_VERSION=${sysenv.APP_VERSION}
@@ -51,6 +51,7 @@ build_flags = -Wno-missing-field-initializers -Isrc -Isrc/rf95 -Isrc/mesh -Ilib/
; the default is esptool
; upload_protocol = esp-prog
; monitor_speed = 115200
monitor_speed = 921600
# debug_tool = esp-prog
@@ -73,9 +74,9 @@ lib_deps =
Wire ; explicitly needed here because the AXP202 library forgets to add it
https://github.com/meshtastic/arduino-fsm.git
https://github.com/meshtastic/SparkFun_Ublox_Arduino_Library.git
https://github.com/meshtastic/SX126x-Arduino.git
Ticker ; Needed for SX126x-Arduino on ESP32
https://github.com/meshtastic/RadioLib.git
https://github.com/meshtastic/TinyGPSPlus.git
; Common settings for ESP targes, mixin with extends = esp32_base
[esp32_base]
src_filter =
@@ -83,7 +84,7 @@ src_filter =
upload_speed = 921600
debug_init_break = tbreak setup
build_flags =
${env.build_flags} -Wall -Wextra
${env.build_flags} -Wall -Wextra -Isrc/esp32
lib_ignore = segger_rtt
; The 1.0 release of the TBEAM board
@@ -92,7 +93,7 @@ extends = esp32_base
board = ttgo-t-beam
lib_deps =
${env.lib_deps}
AXP202X_Library
https://github.com/meshtastic/AXP202X_Library.git
build_flags =
${esp32_base.build_flags} -D TBEAM_V10
@@ -122,26 +123,41 @@ board = ttgo-lora32-v1
build_flags =
${esp32_base.build_flags} -D TTGO_LORA_V2
; The NRF52840-dk development board
[env:nrf52dk]
; Common settings for NRF52 based targets
[nrf52_base]
platform = nordicnrf52
board = ppr
framework = arduino
debug_tool = jlink
build_type = debug ; I'm debugging with ICE a lot now
build_flags =
${env.build_flags} -Wno-unused-variable -Isrc/nrf52
src_filter =
${env.src_filter} -<esp32/>
lib_ignore =
BluetoothOTA
lib_deps =
${env.lib_deps}
UC1701
https://github.com/meshtastic/BQ25703A.git
monitor_port = /dev/ttyACM1
debug_extra_cmds =
source gdbinit
; Set initial breakpoint (defaults to main)
debug_init_break =
;debug_init_break = tbreak loop
;debug_init_break = tbreak Reset_Handler
;debug_init_break = tbreak Reset_Handler
; The NRF52840-dk development board
[env:nrf52dk]
extends = nrf52_base
board = nrf52840_dk_modified
; The PPR board
[env:ppr]
extends = nrf52_base
board = ppr
lib_deps =
${env.lib_deps}
UC1701
https://github.com/meshtastic/BQ25703A.git

2
proto

Submodule proto updated: 8427b23016...bfae47bdc0

View File

@@ -1,218 +0,0 @@
#include "GPS.h"
#include "configuration.h"
#include "time.h"
#include <assert.h>
#include <sys/time.h>
#ifdef GPS_RX_PIN
HardwareSerial _serial_gps(GPS_SERIAL_NUM);
#else
// Assume NRF52
HardwareSerial &_serial_gps = Serial1;
#endif
bool timeSetFromGPS; // We try to set our time from GPS each time we wake from sleep
GPS gps;
// stuff that really should be in in the instance instead...
static uint32_t
timeStartMsec; // Once we have a GPS lock, this is where we hold the initial msec clock that corresponds to that time
static uint64_t zeroOffsetSecs; // GPS based time in secs since 1970 - only updated once on initial lock
static bool wantNewLocation = true;
GPS::GPS() : PeriodicTask() {}
void GPS::setup()
{
PeriodicTask::setup();
readFromRTC(); // read the main CPU RTC at first
#ifdef GPS_RX_PIN
_serial_gps.begin(GPS_BAUDRATE, SERIAL_8N1, GPS_RX_PIN, GPS_TX_PIN);
#else
_serial_gps.begin(GPS_BAUDRATE);
#endif
// _serial_gps.setRxBufferSize(1024); // the default is 256
// ublox.enableDebugging(Serial);
// note: the lib's implementation has the wrong docs for what the return val is
// it is not a bool, it returns zero for success
isConnected = ublox.begin(_serial_gps);
// try a second time, the ublox lib serial parsing is buggy?
if (!isConnected)
isConnected = ublox.begin(_serial_gps);
if (isConnected) {
DEBUG_MSG("Connected to GPS successfully\n");
bool factoryReset = false;
bool ok;
if (factoryReset) {
// It is useful to force back into factory defaults (9600baud, NEMA to test the behavior of boards that don't have
// GPS_TX connected)
ublox.factoryReset();
delay(2000);
isConnected = ublox.begin(_serial_gps);
DEBUG_MSG("Factory reset success=%d\n", isConnected);
if (isConnected) {
ublox.assumeAutoPVT(true, true); // Just parse NEMA for now
}
} else {
ok = ublox.setUART1Output(COM_TYPE_UBX, 500); // Use native API
assert(ok);
ok = ublox.setNavigationFrequency(1, 500); // Produce 4x/sec to keep the amount of time we stall in getPVT low
assert(ok);
// ok = ublox.setAutoPVT(false); // Not implemented on NEO-6M
// assert(ok);
// ok = ublox.setDynamicModel(DYN_MODEL_BIKE); // probably PEDESTRIAN but just in case assume bike speeds
// assert(ok);
ok = ublox.powerSaveMode(); // use power save mode
assert(ok);
}
ok = ublox.saveConfiguration(2000);
assert(ok);
} else {
// Some boards might have only the TX line from the GPS connected, in that case, we can't configure it at all. Just
// assume NEMA at 9600 baud.
DEBUG_MSG("ERROR: No bidirectional GPS found, hoping that it still might work\n");
// tell lib, we are expecting the module to send PVT messages by itself to our Rx pin
// you can set second parameter to "false" if you want to control the parsing and eviction of the data (need to call
// checkUblox cyclically)
ublox.assumeAutoPVT(true, true);
}
}
void GPS::readFromRTC()
{
struct timeval tv; /* btw settimeofday() is helpfull here too*/
if (!gettimeofday(&tv, NULL)) {
uint32_t now = millis();
DEBUG_MSG("Read RTC time as %ld (cur millis %u) valid=%d\n", tv.tv_sec, now, timeSetFromGPS);
timeStartMsec = now;
zeroOffsetSecs = tv.tv_sec;
}
}
/// If we haven't yet set our RTC this boot, set it from a GPS derived time
void GPS::perhapsSetRTC(const struct timeval *tv)
{
if (!timeSetFromGPS) {
timeSetFromGPS = true;
DEBUG_MSG("Setting RTC %ld secs\n", tv->tv_sec);
#ifndef NO_ESP32
settimeofday(tv, NULL);
#else
assert(0);
#endif
readFromRTC();
}
}
#include <time.h>
uint32_t GPS::getTime()
{
return ((millis() - timeStartMsec) / 1000) + zeroOffsetSecs;
}
uint32_t GPS::getValidTime()
{
return timeSetFromGPS ? getTime() : 0;
}
/// Returns true if we think the board can enter deep or light sleep now (we might be trying to get a GPS lock)
bool GPS::canSleep()
{
return true; // we leave GPS on during sleep now, so sleep is okay !wantNewLocation;
}
/// Prepare the GPS for the cpu entering deep or light sleep, expect to be gone for at least 100s of msecs
void GPS::prepareSleep()
{
if (isConnected)
ublox.powerOff();
}
void GPS::doTask()
{
uint8_t fixtype = 3; // If we are only using the RX pin, assume we have a 3d fix
if (isConnected) {
// Consume all characters that have arrived
// getPVT automatically calls checkUblox
ublox.checkUblox(); // See if new data is available. Process bytes as they come in.
// If we don't have a fix (a quick check), don't try waiting for a solution)
// Hmmm my fix type reading returns zeros for fix, which doesn't seem correct, because it is still sptting out positions
// turn off for now
// fixtype = ublox.getFixType();
DEBUG_MSG("fix type %d\n", fixtype);
}
// DEBUG_MSG("sec %d\n", ublox.getSecond());
// DEBUG_MSG("lat %d\n", ublox.getLatitude());
// any fix that has time
if (!timeSetFromGPS && ublox.getT()) {
struct timeval tv;
/* Convert to unix time
The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970
(midnight UTC/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z).
*/
struct tm t;
t.tm_sec = ublox.getSecond();
t.tm_min = ublox.getMinute();
t.tm_hour = ublox.getHour();
t.tm_mday = ublox.getDay();
t.tm_mon = ublox.getMonth() - 1;
t.tm_year = ublox.getYear() - 1900;
t.tm_isdst = false;
time_t res = mktime(&t);
tv.tv_sec = res;
tv.tv_usec = 0; // time.centisecond() * (10 / 1000);
DEBUG_MSG("Got time from GPS month=%d, year=%d, unixtime=%ld\n", t.tm_mon, t.tm_year, tv.tv_sec);
if (t.tm_year < 0 || t.tm_year >= 300)
DEBUG_MSG("Ignoring invalid GPS time\n");
else
perhapsSetRTC(&tv);
}
if ((fixtype >= 3 && fixtype <= 4) && ublox.getP()) // rd fixes only
{
// we only notify if position has changed
latitude = ublox.getLatitude() * 1e-7;
longitude = ublox.getLongitude() * 1e-7;
altitude = ublox.getAltitude() / 1000; // in mm convert to meters
DEBUG_MSG("new gps pos lat=%f, lon=%f, alt=%d\n", latitude, longitude, altitude);
hasValidLocation = (latitude != 0) || (longitude != 0); // bogus lat lon is reported as 0,0
if (hasValidLocation) {
wantNewLocation = false;
notifyObservers(NULL);
// ublox.powerOff();
}
} else // we didn't get a location update, go back to sleep and hope the characters show up
wantNewLocation = true;
// Once we have sent a location once we only poll the GPS rarely, otherwise check back every 1s until we have something over
// the serial
setPeriod(hasValidLocation && !wantNewLocation ? 30 * 1000 : 10 * 1000);
}
void GPS::startLock()
{
DEBUG_MSG("Looking for GPS lock\n");
wantNewLocation = true;
setPeriod(1);
}

View File

@@ -1,56 +0,0 @@
#pragma once
#include "Observer.h"
#include "PeriodicTask.h"
#include "SparkFun_Ublox_Arduino_Library.h"
#include "sys/time.h"
/**
* A gps class that only reads from the GPS periodically (and FIXME - eventually keeps the gps powered down except when reading)
*
* When new data is available it will notify observers.
*/
class GPS : public PeriodicTask, public Observable<void *>
{
SFE_UBLOX_GPS ublox;
public:
double latitude, longitude;
uint32_t altitude;
bool isConnected; // Do we have a GPS we are talking to
GPS();
/// Return time since 1970 in secs. Until we have a GPS lock we will be returning time based at zero
uint32_t getTime();
/// Return time since 1970 in secs. If we don't have a GPS lock return zero
uint32_t getValidTime();
void setup();
virtual void doTask();
/// If we haven't yet set our RTC this boot, set it from a GPS derived time
void perhapsSetRTC(const struct timeval *tv);
/// Returns true if we think the board can enter deep or light sleep now (we might be trying to get a GPS lock)
bool canSleep();
/// Prepare the GPS for the cpu entering deep or light sleep, expect to be gone for at least 100s of msecs
void prepareSleep();
/// Restart our lock attempt - try to get and broadcast a GPS reading ASAP
void startLock();
/// Returns ture if we have acquired GPS lock.
bool hasLock() const { return hasValidLocation; }
private:
void readFromRTC();
bool hasValidLocation = false; // default to false, until we complete our first read
};
extern GPS gps;

49
src/OSTimer.cpp Normal file
View File

@@ -0,0 +1,49 @@
#include "OSTimer.h"
#include "configuration.h"
#ifdef NO_ESP32
/**
* Schedule a callback to run. The callback must _not_ block, though it is called from regular thread level (not ISR)
*
* NOTE! xTimerPend... seems to ignore the time passed in on ESP32 - I haven't checked on NRF52
*
* @return true if successful, false if the timer fifo is too full.
*/
bool scheduleOSCallback(PendableFunction callback, void *param1, uint32_t param2, uint32_t delayMsec)
{
return xTimerPendFunctionCall(callback, param1, param2, pdMS_TO_TICKS(delayMsec));
}
#else
// Super skanky quick hack to use hardware timers of the ESP32
static hw_timer_t *timer;
static PendableFunction tCallback;
static void *tParam1;
static uint32_t tParam2;
static void IRAM_ATTR onTimer()
{
(*tCallback)(tParam1, tParam2);
}
bool scheduleHWCallback(PendableFunction callback, void *param1, uint32_t param2, uint32_t delayMsec)
{
if (!timer) {
timer = timerBegin(0, 80, true); // one usec per tick (main clock is 80MhZ on ESP32)
assert(timer);
timerAttachInterrupt(timer, &onTimer, true);
}
tCallback = callback;
tParam1 = param1;
tParam2 = param2;
timerAlarmWrite(timer, delayMsec * 1000L, false); // Do not reload, we want it to be a single shot timer
timerRestart(timer);
timerAlarmEnable(timer);
return true;
}
#endif

18
src/OSTimer.h Normal file
View File

@@ -0,0 +1,18 @@
#pragma once
#include <Arduino.h>
typedef void (*PendableFunction)(void *pvParameter1, uint32_t ulParameter2);
/**
* Schedule a callback to run. The callback must _not_ block, though it is called from regular thread level (not ISR)
*
* NOTE! ESP32 implementation is busted - always waits 0 ticks
*
* @return true if successful, false if the timer fifo is too full.
*/
bool scheduleOSCallback(PendableFunction callback, void *param1, uint32_t param2, uint32_t delayMsec);
/// Uses a hardware timer, but calls the handler in _interrupt_ context
bool scheduleHWCallback(PendableFunction callback, void *param1, uint32_t param2, uint32_t delayMsec);

View File

@@ -87,7 +87,7 @@ static void lsIdle()
static void lsExit()
{
// setGPSPower(true); // restore GPS power
gps.startLock();
gps->startLock();
}
static void nbEnter()
@@ -113,8 +113,9 @@ static void onEnter()
uint32_t now = millis();
if (now - lastPingMs > 60 * 1000) { // if more than a minute since our last press, ask other nodes to update their state
service.sendNetworkPing(NODENUM_BROADCAST, true);
if (now - lastPingMs > 30 * 1000) { // if more than a minute since our last press, ask other nodes to update their state
if (displayedNodeNum)
service.sendNetworkPing(displayedNodeNum, true); // Refresh the currently displayed node
lastPingMs = now;
}
}
@@ -153,6 +154,13 @@ void PowerFSM_setup()
powerFSM.add_transition(&stateDARK, &stateON, EVENT_PRESS, NULL, "Press");
powerFSM.add_transition(&stateON, &stateON, EVENT_PRESS, screenPress, "Press"); // reenter On to restart our timers
// Handle critically low power battery by forcing deep sleep
powerFSM.add_transition(&stateBOOT, &stateSDS, EVENT_LOW_BATTERY, NULL, "LowBat");
powerFSM.add_transition(&stateLS, &stateSDS, EVENT_LOW_BATTERY, NULL, "LowBat");
powerFSM.add_transition(&stateNB, &stateSDS, EVENT_LOW_BATTERY, NULL, "LowBat");
powerFSM.add_transition(&stateDARK, &stateSDS, EVENT_LOW_BATTERY, NULL, "LowBat");
powerFSM.add_transition(&stateON, &stateSDS, EVENT_LOW_BATTERY, NULL, "LowBat");
powerFSM.add_transition(&stateDARK, &stateON, EVENT_BLUETOOTH_PAIR, NULL, "Bluetooth pairing");
powerFSM.add_transition(&stateON, &stateON, EVENT_BLUETOOTH_PAIR, NULL, "Bluetooth pairing");

View File

@@ -13,6 +13,7 @@
#define EVENT_BLUETOOTH_PAIR 7
#define EVENT_NODEDB_UPDATED 8 // NodeDB has a big enough change that we think you should turn on the screen
#define EVENT_CONTACT_FROM_PHONE 9 // the phone just talked to us over bluetooth
#define EVENT_LOW_BATTERY 10 // Battery is critically low, go to sleep
extern Fsm powerFSM;

View File

@@ -17,11 +17,12 @@ void SerialConsole::init()
{
Port.begin(SERIAL_BAUD);
StreamAPI::init();
emitRebooted();
}
/**
* we override this to notice when we've received a protobuf over the serial stream. Then we shunt off
* debug serial output.
* we override this to notice when we've received a protobuf over the serial
* stream. Then we shunt off debug serial output.
*/
void SerialConsole::handleToRadio(const uint8_t *buf, size_t len)
{

View File

@@ -19,6 +19,13 @@ class SerialConsole : public StreamAPI, public RedirectablePrint
* debug serial output.
*/
virtual void handleToRadio(const uint8_t *buf, size_t len);
virtual size_t write(uint8_t c)
{
if (c == '\n') // prefix any newlines with carriage return
RedirectablePrint::write('\r');
return RedirectablePrint::write(c);
}
};
extern SerialConsole console;

37
src/WorkerThread.cpp Normal file
View File

@@ -0,0 +1,37 @@
#include "WorkerThread.h"
#include <assert.h>
void Thread::start(const char *name, size_t stackSize, uint32_t priority)
{
auto r = xTaskCreate(callRun, name, stackSize, this, priority, &taskHandle);
assert(r == pdPASS);
}
void Thread::callRun(void *_this)
{
((Thread *)_this)->doRun();
}
void WorkerThread::doRun()
{
while (!wantExit) {
block();
loop();
}
}
/**
* Notify this thread so it can run
*/
void NotifiedWorkerThread::notify(uint32_t v, eNotifyAction action)
{
xTaskNotify(taskHandle, v, action);
}
void NotifiedWorkerThread::block()
{
xTaskNotifyWait(0, // don't clear notification on entry
clearOnRead, &notification, portMAX_DELAY); // Wait forever
}

89
src/WorkerThread.h Normal file
View File

@@ -0,0 +1,89 @@
#include <Arduino.h>
class Thread
{
protected:
TaskHandle_t taskHandle = NULL;
/**
* set this to true to ask thread to cleanly exit asap
*/
volatile bool wantExit = false;
public:
void start(const char *name, size_t stackSize = 1024, uint32_t priority = tskIDLE_PRIORITY);
virtual ~Thread() { vTaskDelete(taskHandle); }
protected:
/**
* The method that will be called when start is called.
*/
virtual void doRun() = 0;
private:
static void callRun(void *_this);
};
/**
* This wraps threading (FreeRTOS for now) with a blocking API intended for efficiently converting onlyschool arduino loop() code.
*
* Use as a mixin base class for the classes you want to convert.
*
* https://www.freertos.org/RTOS_Task_Notification_As_Mailbox.html
*/
class WorkerThread : public Thread
{
protected:
/**
* A method that should block execution - either waiting ona queue/mutex or a "task notification"
*/
virtual void block() = 0;
virtual void loop() = 0;
/**
* The method that will be called when start is called.
*/
virtual void doRun();
};
/**
* A worker thread that waits on a freertos notification
*/
class NotifiedWorkerThread : public WorkerThread
{
public:
/**
* Notify this thread so it can run
*/
void notify(uint32_t v = 0, eNotifyAction action = eNoAction);
/**
* Notify from an ISR
*
* This must be inline or IRAM_ATTR on ESP32
*/
inline void notifyFromISR(BaseType_t *highPriWoken, uint32_t v = 0, eNotifyAction action = eNoAction)
{
xTaskNotifyFromISR(taskHandle, v, action, highPriWoken);
}
protected:
/**
* The notification that was most recently used to wake the thread. Read from loop()
*/
uint32_t notification = 0;
/**
* What notification bits should be cleared just after we read and return them in notification?
*
* Defaults to clear all of them.
*/
uint32_t clearOnRead = UINT32_MAX;
/**
* A method that should block execution - either waiting ona queue/mutex or a "task notification"
*/
virtual void block();
};

View File

@@ -48,30 +48,38 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
#define REQUIRE_RADIO true // If true, we will fail to start if the radio is not found
/// Convert a preprocessor name into a quoted string
#define xstr(s) str(s)
#define str(s) #s
// -----------------------------------------------------------------------------
// OLED
// -----------------------------------------------------------------------------
/// Convert a preprocessor name into a quoted string and if that string is empty use "unset"
#define optstr(s) (xstr(s)[0] ? xstr(s) : "unset")
#define SSD1306_ADDRESS 0x3C
#ifdef NRF52840_XXAA // All of the NRF52 targets are configured using variant.h, so this section shouldn't need to be
// board specific
// Flip the screen upside down by default as it makes more sense on T-BEAM
// devices. Comment this out to not rotate screen 180 degrees.
#define FLIP_SCREEN_VERTICALLY
//
// Standard definitions for NRF52 targets
//
// DEBUG LED
#define NO_ESP32 // Don't use ESP32 libs (mainly bluetooth)
#define LED_INVERTED 0 // define as 1 if LED is active low (on)
// We bind to the GPS using variant.h instead for this platform (Serial1)
// -----------------------------------------------------------------------------
// GPS
// -----------------------------------------------------------------------------
// FIXME, not yet ready for NRF52
#define RTC_DATA_ATTR
#define LED_PIN PIN_LED1 // LED1 on nrf52840-DK
#define BUTTON_PIN PIN_BUTTON1
// FIXME, use variant.h defs for all of this!!! (even on the ESP32 targets)
#else
//
// Standard definitions for ESP32 targets
//
#define GPS_SERIAL_NUM 1
#define GPS_BAUDRATE 9600
#define GPS_RX_PIN 34
#ifdef USE_JTAG
#define GPS_TX_PIN -1
@@ -88,6 +96,27 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
#define MOSI_GPIO 27
#define NSS_GPIO 18
#endif
// -----------------------------------------------------------------------------
// OLED
// -----------------------------------------------------------------------------
#define SSD1306_ADDRESS 0x3C
// Flip the screen upside down by default as it makes more sense on T-BEAM
// devices. Comment this out to not rotate screen 180 degrees.
#define FLIP_SCREEN_VERTICALLY
// DEBUG LED
#define LED_INVERTED 0 // define as 1 if LED is active low (on)
// -----------------------------------------------------------------------------
// GPS
// -----------------------------------------------------------------------------
#define GPS_BAUDRATE 9600
#if defined(TBEAM_V10)
// This string must exactly match the case used in release file names or the android updater won't work
#define HW_VENDOR "tbeam"
@@ -188,39 +217,32 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
0 // If defined, this will be used for user button presses, if your board doesn't have a physical switch, you can wire one
// between this pin and ground
#define RESET_GPIO 14 // If defined, this pin will be used to reset the LORA radio
#define RF95_IRQ_GPIO 26 // IRQ line for the LORA radio
#define DIO1_GPIO 35 // DIO1 & DIO2 are not currently used, but they must be assigned to a pin number
#define DIO2_GPIO 34 // DIO1 & DIO2 are not currently used, but they must be assigned to a pin number
#elif defined(NRF52840_XXAA) // All of the NRF52 targets are configured using variant.h, so this section shouldn't need to be
// board specific
#define RESET_GPIO 14 // If defined, this pin will be used to reset the LORA radio
#define RF95_IRQ_GPIO 26 // IRQ line for the LORA radio
#define DIO1_GPIO 35 // DIO1 & DIO2 are not currently used, but they must be assigned to a pin number
#define DIO2_GPIO 34 // DIO1 & DIO2 are not currently used, but they must be assigned to a pin number
#endif
// FIXME, use variant.h defs for all of this!!!
#ifdef ARDUINO_NRF52840_PCA10056
// This string must exactly match the case used in release file names or the android updater won't work
#define HW_VENDOR "nrf52"
#define NO_ESP32 // Don't use ESP32 libs (mainly bluetooth)
// We bind to the GPS using variant.h instead for this platform (Serial1)
#undef GPS_RX_PIN
#undef GPS_TX_PIN
// FIXME, not yet ready for NRF52
#define RTC_DATA_ATTR
#define LED_PIN PIN_LED1 // LED1 on nrf52840-DK
#define BUTTON_PIN PIN_BUTTON1
#define HW_VENDOR "nrf52dk"
// This board uses 0 to be mean LED on
#undef LED_INVERTED
#define LED_INVERTED 1
// Temporarily testing if we can build the RF95 driver for NRF52
// Uncomment to confirm if we can build the RF95 driver for NRF52
#if 0
#define RESET_GPIO 14 // If defined, this pin will be used to reset the LORA radio
#define RF95_IRQ_GPIO 26 // IRQ line for the LORA radio
#define DIO1_GPIO 35 // DIO1 & DIO2 are not currently used, but they must be assigned to a pin number
#define DIO2_GPIO 34 // DIO1 & DIO2 are not currently used, but they must be assigned to a pin number
#endif
#elif defined(ARDUINO_NRF52840_PPR)
#define HW_VENDOR "ppr"
#endif

View File

@@ -1,21 +1,30 @@
#include "BluetoothUtil.h"
#include "BluetoothSoftwareUpdate.h"
#include "configuration.h"
#include <esp_gatt_defs.h>
#include <BLE2902.h>
#include <Arduino.h>
#include <Update.h>
#include <CRC32.h>
#include "BluetoothUtil.h"
#include "CallbackCharacteristic.h"
#include "RadioLibInterface.h"
#include "configuration.h"
#include "lock.h"
#include <Arduino.h>
#include <BLE2902.h>
#include <CRC32.h>
#include <Update.h>
#include <esp_gatt_defs.h>
using namespace meshtastic;
CRC32 crc;
uint32_t rebootAtMsec = 0; // If not zero we will reboot at this time (used to reboot shortly after the update completes)
uint32_t updateExpectedSize, updateActualSize;
Lock *updateLock;
class TotalSizeCharacteristic : public CallbackCharacteristic
{
public:
public:
TotalSizeCharacteristic()
: CallbackCharacteristic("e74dd9c0-a301-4a6f-95a1-f0e1dbea8e1e", BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_READ)
: CallbackCharacteristic("e74dd9c0-a301-4a6f-95a1-f0e1dbea8e1e",
BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_READ)
{
}
@@ -23,43 +32,54 @@ public:
{
BLEKeepAliveCallbacks::onWrite(c);
LockGuard g(updateLock);
// Check if there is enough to OTA Update
uint32_t len = getValue32(c, 0);
updateExpectedSize = len;
updateActualSize = 0;
crc.reset();
bool canBegin = Update.begin(len);
DEBUG_MSG("Setting update size %u, result %d\n", len, canBegin);
if (!canBegin)
if (!canBegin) {
// Indicate failure by forcing the size to 0
c->setValue(0UL);
else {
uint32_t zero = 0;
c->setValue(zero);
} else {
// This totally breaks abstraction to up up into the app layer for this, but quick hack to make sure we only
// talk to one service during the sw update.
//DEBUG_MSG("FIXME, crufty shutdown of mesh bluetooth for sw update.");
//void stopMeshBluetoothService();
//stopMeshBluetoothService();
// DEBUG_MSG("FIXME, crufty shutdown of mesh bluetooth for sw update.");
// void stopMeshBluetoothService();
// stopMeshBluetoothService();
if (RadioLibInterface::instance)
RadioLibInterface::instance->sleep(); // FIXME, nasty hack - the RF95 ISR/SPI code on ESP32 can fail while we are
// writing flash - shut the radio off during updates
}
}
};
#define MAX_BLOCKSIZE 512
class DataCharacteristic : public CallbackCharacteristic
{
public:
DataCharacteristic()
: CallbackCharacteristic(
"e272ebac-d463-4b98-bc84-5cc1a39ee517", BLECharacteristic::PROPERTY_WRITE)
{
}
public:
DataCharacteristic() : CallbackCharacteristic("e272ebac-d463-4b98-bc84-5cc1a39ee517", BLECharacteristic::PROPERTY_WRITE) {}
void onWrite(BLECharacteristic *c)
{
BLEKeepAliveCallbacks::onWrite(c);
LockGuard g(updateLock);
std::string value = c->getValue();
uint32_t len = value.length();
uint8_t *data = c->getData();
assert(len <= MAX_BLOCKSIZE);
static uint8_t
data[MAX_BLOCKSIZE]; // we temporarily copy here because I'm worried that a fast sender might be able overwrite srcbuf
memcpy(data, c->getData(), len);
// DEBUG_MSG("Writing %u\n", len);
crc.update(data, len);
Update.write(data, len);
updateActualSize += len;
}
};
@@ -67,49 +87,46 @@ static BLECharacteristic *resultC;
class CRC32Characteristic : public CallbackCharacteristic
{
public:
CRC32Characteristic()
: CallbackCharacteristic(
"4826129c-c22a-43a3-b066-ce8f0d5bacc6", BLECharacteristic::PROPERTY_WRITE)
{
}
public:
CRC32Characteristic() : CallbackCharacteristic("4826129c-c22a-43a3-b066-ce8f0d5bacc6", BLECharacteristic::PROPERTY_WRITE) {}
void onWrite(BLECharacteristic *c)
{
BLEKeepAliveCallbacks::onWrite(c);
LockGuard g(updateLock);
uint32_t expectedCRC = getValue32(c, 0);
uint32_t actualCRC = crc.finalize();
DEBUG_MSG("expected CRC %u\n", expectedCRC);
uint8_t result = 0xff;
// Check the CRC before asking the update to happen.
if (crc.finalize() != expectedCRC)
if (updateActualSize != updateExpectedSize) {
DEBUG_MSG("Expected %u bytes, but received %u bytes!\n", updateExpectedSize, updateActualSize);
result = 0xe1; // FIXME, use real error codes
} else if (actualCRC != expectedCRC) // Check the CRC before asking the update to happen.
{
DEBUG_MSG("Invalid CRC!\n");
DEBUG_MSG("Invalid CRC! expected=%u, actual=%u\n", expectedCRC, actualCRC);
result = 0xe0; // FIXME, use real error codes
}
else
{
if (Update.end())
{
} else {
if (Update.end()) {
DEBUG_MSG("OTA done, rebooting in 5 seconds!\n");
rebootAtMsec = millis() + 5000;
}
else
{
} else {
DEBUG_MSG("Error Occurred. Error #: %d\n", Update.getError());
}
result = Update.getError();
}
if (RadioLibInterface::instance)
RadioLibInterface::instance->startReceive(); // Resume radio
assert(resultC);
resultC->setValue(&result, 1);
resultC->notify();
}
};
void bluetoothRebootCheck()
{
if (rebootAtMsec && millis() > rebootAtMsec)
@@ -122,11 +139,15 @@ See bluetooth-api.md
*/
BLEService *createUpdateService(BLEServer *server, std::string hwVendor, std::string swVersion, std::string hwVersion)
{
if (!updateLock)
updateLock = new Lock();
// Create the BLE Service
BLEService *service = server->createService(BLEUUID("cb0b9a0b-a84c-4c0d-bdbb-442e3144ee30"), 25, 0);
assert(!resultC);
resultC = new BLECharacteristic("5e134862-7411-4424-ac4a-210937432c77", BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
resultC = new BLECharacteristic("5e134862-7411-4424-ac4a-210937432c77",
BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
addWithDesc(service, new TotalSizeCharacteristic, "total image size");
addWithDesc(service, new DataCharacteristic, "data");
@@ -135,7 +156,8 @@ BLEService *createUpdateService(BLEServer *server, std::string hwVendor, std::st
resultC->addDescriptor(addBLEDescriptor(new BLE2902())); // Needed so clients can request notification
BLECharacteristic *swC = new BLECharacteristic(BLEUUID((uint16_t)ESP_GATT_UUID_SW_VERSION_STR), BLECharacteristic::PROPERTY_READ);
BLECharacteristic *swC =
new BLECharacteristic(BLEUUID((uint16_t)ESP_GATT_UUID_SW_VERSION_STR), BLECharacteristic::PROPERTY_READ);
swC->setValue(swVersion);
service->addCharacteristic(addBLECharacteristic(swC));
@@ -143,7 +165,8 @@ BLEService *createUpdateService(BLEServer *server, std::string hwVendor, std::st
mfC->setValue(hwVendor);
service->addCharacteristic(addBLECharacteristic(mfC));
BLECharacteristic *hwvC = new BLECharacteristic(BLEUUID((uint16_t)ESP_GATT_UUID_HW_VERSION_STR), BLECharacteristic::PROPERTY_READ);
BLECharacteristic *hwvC =
new BLECharacteristic(BLEUUID((uint16_t)ESP_GATT_UUID_HW_VERSION_STR), BLECharacteristic::PROPERTY_READ);
hwvC->setValue(hwVersion);
service->addCharacteristic(addBLECharacteristic(hwvC));

View File

@@ -1,8 +1,11 @@
#pragma once
#include <Arduino.h>
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
BLEService *createUpdateService(BLEServer* server, std::string hwVendor, std::string swVersion, std::string hwVersion);
BLEService *createUpdateService(BLEServer *server, std::string hwVendor, std::string swVersion, std::string hwVersion);
void destroyUpdateService();
void bluetoothRebootCheck();

View File

@@ -184,7 +184,7 @@ class MySecurity : public BLESecurityCallbacks
void onPassKeyNotify(uint32_t pass_key)
{
Serial.printf("onPassKeyNotify %u\n", pass_key);
Serial.printf("onPassKeyNotify %06u\n", pass_key);
startCb(pass_key);
}

View File

@@ -0,0 +1,83 @@
#include "CryptoEngine.h"
#include "configuration.h"
#include "crypto/includes.h"
#include "crypto/common.h"
// #include "esp_system.h"
#include "crypto/aes.h"
#include "crypto/aes_wrap.h"
#include "mbedtls/aes.h"
#define MAX_BLOCKSIZE 256
class ESP32CryptoEngine : public CryptoEngine
{
mbedtls_aes_context aes;
/// How many bytes in our key
uint8_t keySize = 0;
public:
ESP32CryptoEngine() { mbedtls_aes_init(&aes); }
~ESP32CryptoEngine() { mbedtls_aes_free(&aes); }
/**
* Set the key used for encrypt, decrypt.
*
* As a special case: If all bytes are zero, we assume _no encryption_ and send all data in cleartext.
*
* @param numBytes must be 16 (AES128), 32 (AES256) or 0 (no crypt)
* @param bytes a _static_ buffer that will remain valid for the life of this crypto instance (i.e. this class will cache the
* provided pointer)
*/
virtual void setKey(size_t numBytes, uint8_t *bytes)
{
keySize = numBytes;
DEBUG_MSG("Installing AES%d key!\n", numBytes * 8);
if (numBytes != 0) {
auto res = mbedtls_aes_setkey_enc(&aes, bytes, numBytes * 8);
assert(!res);
}
}
/**
* Encrypt a packet
*
* @param bytes is updated in place
*/
virtual void encrypt(uint32_t fromNode, uint64_t packetNum, size_t numBytes, uint8_t *bytes)
{
if (keySize != 0) {
uint8_t stream_block[16];
static uint8_t scratch[MAX_BLOCKSIZE];
size_t nc_off = 0;
// DEBUG_MSG("ESP32 encrypt!\n");
initNonce(fromNode, packetNum);
assert(numBytes <= MAX_BLOCKSIZE);
memcpy(scratch, bytes, numBytes);
memset(scratch + numBytes, 0,
sizeof(scratch) - numBytes); // Fill rest of buffer with zero (in case cypher looks at it)
auto res = mbedtls_aes_crypt_ctr(&aes, numBytes, &nc_off, nonce, stream_block, scratch, bytes);
assert(!res);
}
}
virtual void decrypt(uint32_t fromNode, uint64_t packetNum, size_t numBytes, uint8_t *bytes)
{
// DEBUG_MSG("ESP32 decrypt!\n");
// For CTR, the implementation is the same
encrypt(fromNode, packetNum, numBytes, bytes);
}
private:
};
CryptoEngine *crypto = new ESP32CryptoEngine();

View File

@@ -178,7 +178,7 @@ class MyNodeInfoCharacteristic : public ProtobufCharacteristic
void onRead(BLECharacteristic *c)
{
// update gps connection state
myNodeInfo.has_gps = gps.isConnected;
myNodeInfo.has_gps = gps->isConnected;
ProtobufCharacteristic::onRead(c);

View File

@@ -22,8 +22,8 @@ void reinitBluetooth()
powerFSM.trigger(EVENT_BLUETOOTH_PAIR);
screen.startBluetoothPinScreen(pin);
},
[]() { screen.stopBluetoothPinScreen(); }, getDeviceName(), HW_VENDOR, xstr(APP_VERSION),
xstr(HW_VERSION)); // FIXME, use a real name based on the macaddr
[]() { screen.stopBluetoothPinScreen(); }, getDeviceName(), HW_VENDOR, optstr(APP_VERSION),
optstr(HW_VERSION)); // FIXME, use a real name based on the macaddr
createMeshBluetoothService(serve);
// Start advertising - this must be done _after_ creating all services
@@ -119,16 +119,8 @@ void axp192Init()
DEBUG_MSG("DCDC3: %s\n", axp.isDCDC3Enable() ? "ENABLE" : "DISABLE");
DEBUG_MSG("Exten: %s\n", axp.isExtenEnable() ? "ENABLE" : "DISABLE");
axp.setChargeControlCur(AXP1XX_CHARGE_CUR_1320MA); // actual limit (in HW) on the tbeam is 450mA
#if 0
// cribbing from https://github.com/m5stack/M5StickC/blob/master/src/AXP192.cpp to fix charger to be more like 300ms.
// I finally found an english datasheet. Will look at this later - but suffice it to say the default code from TTGO has 'issues'
axp.adc1Enable(0xff, 1); // turn on all adcs
uint8_t val = 0xc2;
axp._writeByte(0x33, 1, &val); // Bat charge voltage to 4.2, Current 280mA
val = 0b11110010;
// Set ADC sample rate to 200hz
// axp._writeByte(0x84, 1, &val);
// Not connected
//val = 0xfc;
@@ -164,6 +156,8 @@ void axp192Init()
void esp32Setup()
{
randomSeed(esp_random()); // ESP docs say this is fairly random
#ifdef AXP192_SLAVE_ADDRESS
axp192Init();
#endif
@@ -189,6 +183,8 @@ uint32_t axpDebugRead()
Periodic axpDebugOutput(axpDebugRead);
#endif
#define MIN_BAT_MILLIVOLTS 3690 // millivolts. 10% per https://blog.ampow.com/lipo-voltage-chart/
/// loop code specific to ESP32 targets
void esp32Loop()
{
@@ -229,5 +225,10 @@ void esp32Loop()
readPowerStatus();
axp.clearIRQ();
}
if (powerStatus.haveBattery && !powerStatus.usb &&
axp.getBattVoltage() < MIN_BAT_MILLIVOLTS) // If we have a battery at all and it is less than 10% full, force deep sleep
powerFSM.trigger(EVENT_LOW_BATTERY);
#endif // T_BEAM_V10
}

81
src/gps/GPS.cpp Normal file
View File

@@ -0,0 +1,81 @@
#include "GPS.h"
#include "configuration.h"
#include "time.h"
#include <assert.h>
#include <sys/time.h>
#ifdef GPS_RX_PIN
HardwareSerial _serial_gps_real(GPS_SERIAL_NUM);
HardwareSerial &GPS::_serial_gps = _serial_gps_real;
#else
// Assume NRF52
HardwareSerial &GPS::_serial_gps = Serial1;
#endif
bool timeSetFromGPS; // We try to set our time from GPS each time we wake from sleep
GPS *gps;
// stuff that really should be in in the instance instead...
static uint32_t
timeStartMsec; // Once we have a GPS lock, this is where we hold the initial msec clock that corresponds to that time
static uint64_t zeroOffsetSecs; // GPS based time in secs since 1970 - only updated once on initial lock
void readFromRTC()
{
struct timeval tv; /* btw settimeofday() is helpfull here too*/
if (!gettimeofday(&tv, NULL)) {
uint32_t now = millis();
DEBUG_MSG("Read RTC time as %ld (cur millis %u) valid=%d\n", tv.tv_sec, now, timeSetFromGPS);
timeStartMsec = now;
zeroOffsetSecs = tv.tv_sec;
}
}
/// If we haven't yet set our RTC this boot, set it from a GPS derived time
void perhapsSetRTC(const struct timeval *tv)
{
if (!timeSetFromGPS) {
timeSetFromGPS = true;
DEBUG_MSG("Setting RTC %ld secs\n", tv->tv_sec);
#ifndef NO_ESP32
settimeofday(tv, NULL);
#else
DEBUG_MSG("ERROR TIME SETTING NOT IMPLEMENTED!\n");
#endif
readFromRTC();
}
}
void perhapsSetRTC(struct tm &t)
{
/* Convert to unix time
The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970
(midnight UTC/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z).
*/
time_t res = mktime(&t);
struct timeval tv;
tv.tv_sec = res;
tv.tv_usec = 0; // time.centisecond() * (10 / 1000);
// DEBUG_MSG("Got time from GPS month=%d, year=%d, unixtime=%ld\n", t.tm_mon, t.tm_year, tv.tv_sec);
if (t.tm_year < 0 || t.tm_year >= 300)
DEBUG_MSG("Ignoring invalid GPS time\n");
else
perhapsSetRTC(&tv);
}
#include <time.h>
uint32_t getTime()
{
return ((millis() - timeStartMsec) / 1000) + zeroOffsetSecs;
}
uint32_t getValidTime()
{
return timeSetFromGPS ? getTime() : 0;
}

55
src/gps/GPS.h Normal file
View File

@@ -0,0 +1,55 @@
#pragma once
#include "Observer.h"
#include "PeriodicTask.h"
#include "sys/time.h"
/// If we haven't yet set our RTC this boot, set it from a GPS derived time
void perhapsSetRTC(const struct timeval *tv);
void perhapsSetRTC(struct tm &t);
/// Return time since 1970 in secs. Until we have a GPS lock we will be returning time based at zero
uint32_t getTime();
/// Return time since 1970 in secs. If we don't have a GPS lock return zero
uint32_t getValidTime();
void readFromRTC();
/**
* A gps class that only reads from the GPS periodically (and FIXME - eventually keeps the gps powered down except when reading)
*
* When new data is available it will notify observers.
*/
class GPS : public Observable<void *>
{
protected:
bool hasValidLocation = false; // default to false, until we complete our first read
static HardwareSerial &_serial_gps;
public:
int32_t latitude = 0, longitude = 0; // as an int mult by 1e-7 to get value as double
int32_t altitude = 0;
bool isConnected = false; // Do we have a GPS we are talking to
virtual ~GPS() {}
/**
* Returns true if we succeeded
*/
virtual bool setup() { return true; }
/// A loop callback for subclasses that need it. FIXME, instead just block on serial reads
virtual void loop() {}
/// Returns ture if we have acquired GPS lock.
bool hasLock() const { return hasValidLocation; }
/**
* Restart our lock attempt - try to get and broadcast a GPS reading ASAP
* called after the CPU wakes from light-sleep state */
virtual void startLock() {}
};
extern GPS *gps;

65
src/gps/NEMAGPS.cpp Normal file
View File

@@ -0,0 +1,65 @@
#include "NEMAGPS.h"
#include "configuration.h"
static int32_t toDegInt(RawDegrees d)
{
int32_t degMult = 10000000; // 1e7
int32_t r = d.deg * degMult + d.billionths / 100;
if (d.negative)
r *= -1;
return r;
}
void NEMAGPS::loop()
{
while (_serial_gps.available() > 0) {
int c = _serial_gps.read();
// Serial.write(c);
reader.encode(c);
}
uint32_t now = millis();
if ((now - lastUpdateMsec) > 20 * 1000) { // Ugly hack for now - limit update checks to once every 20 secs (but still consume
// serial chars at whatever rate)
lastUpdateMsec = now;
auto ti = reader.time;
auto d = reader.date;
if (ti.isUpdated() && ti.isValid() && d.isValid()) {
/* Convert to unix time
The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970
(midnight UTC/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z).
*/
struct tm t;
t.tm_sec = ti.second();
t.tm_min = ti.minute();
t.tm_hour = ti.hour();
t.tm_mday = d.day();
t.tm_mon = d.month() - 1;
t.tm_year = d.year() - 1900;
t.tm_isdst = false;
perhapsSetRTC(t);
isConnected = true; // we seem to have a real GPS (but not necessarily a lock)
}
if (reader.location.isUpdated()) {
if (reader.altitude.isValid())
altitude = reader.altitude.meters();
if (reader.location.isValid()) {
auto loc = reader.location.value();
latitude = toDegInt(loc.lat);
longitude = toDegInt(loc.lng);
}
// expect gps pos lat=37.520825, lon=-122.309162, alt=158
DEBUG_MSG("new NEMA GPS pos lat=%f, lon=%f, alt=%d\n", latitude * 1e-7, longitude * 1e-7, altitude);
hasValidLocation = (latitude != 0) || (longitude != 0); // bogus lat lon is reported as 0,0
if (hasValidLocation)
notifyObservers(NULL);
}
}
}

21
src/gps/NEMAGPS.h Normal file
View File

@@ -0,0 +1,21 @@
#pragma once
#include "GPS.h"
#include "Observer.h"
#include "PeriodicTask.h"
#include "TinyGPS++.h"
/**
* A gps class thatreads from a NEMA GPS stream (and FIXME - eventually keeps the gps powered down except when reading)
*
* When new data is available it will notify observers.
*/
class NEMAGPS : public GPS
{
TinyGPSPlus reader;
uint32_t lastUpdateMsec = 0;
public:
virtual void loop();
};

139
src/gps/UBloxGPS.cpp Normal file
View File

@@ -0,0 +1,139 @@
#include "UBloxGPS.h"
#include "sleep.h"
#include <assert.h>
UBloxGPS::UBloxGPS() : PeriodicTask()
{
notifySleepObserver.observe(&notifySleep);
}
bool UBloxGPS::setup()
{
#ifdef GPS_RX_PIN
_serial_gps.begin(GPS_BAUDRATE, SERIAL_8N1, GPS_RX_PIN, GPS_TX_PIN);
#else
_serial_gps.begin(GPS_BAUDRATE);
#endif
// _serial_gps.setRxBufferSize(1024); // the default is 256
// ublox.enableDebugging(Serial);
// note: the lib's implementation has the wrong docs for what the return val is
// it is not a bool, it returns zero for success
isConnected = ublox.begin(_serial_gps);
// try a second time, the ublox lib serial parsing is buggy?
if (!isConnected)
isConnected = ublox.begin(_serial_gps);
if (isConnected) {
DEBUG_MSG("Connected to UBLOX GPS successfully\n");
bool factoryReset = false;
bool ok;
if (factoryReset) {
// It is useful to force back into factory defaults (9600baud, NEMA to test the behavior of boards that don't have
// GPS_TX connected)
ublox.factoryReset();
delay(3000);
isConnected = ublox.begin(_serial_gps);
DEBUG_MSG("Factory reset success=%d\n", isConnected);
ok = ublox.saveConfiguration(3000);
assert(ok);
return false;
} else {
ok = ublox.setUART1Output(COM_TYPE_UBX, 500); // Use native API
assert(ok);
ok = ublox.setNavigationFrequency(1, 500); // Produce 4x/sec to keep the amount of time we stall in getPVT low
assert(ok);
// ok = ublox.setAutoPVT(false); // Not implemented on NEO-6M
// assert(ok);
// ok = ublox.setDynamicModel(DYN_MODEL_BIKE); // probably PEDESTRIAN but just in case assume bike speeds
// assert(ok);
ok = ublox.powerSaveMode(); // use power save mode
assert(ok);
}
ok = ublox.saveConfiguration(3000);
assert(ok);
PeriodicTask::setup(); // We don't start our periodic task unless we actually found the device
return true;
} else {
return false;
}
}
/// Prepare the GPS for the cpu entering deep or light sleep, expect to be gone for at least 100s of msecs
int UBloxGPS::prepareSleep(void *unused)
{
if (isConnected)
ublox.powerOff();
return 0;
}
void UBloxGPS::doTask()
{
uint8_t fixtype = 3; // If we are only using the RX pin, assume we have a 3d fix
assert(isConnected);
// Consume all characters that have arrived
// getPVT automatically calls checkUblox
ublox.checkUblox(); // See if new data is available. Process bytes as they come in.
// If we don't have a fix (a quick check), don't try waiting for a solution)
// Hmmm my fix type reading returns zeros for fix, which doesn't seem correct, because it is still sptting out positions
// turn off for now
// fixtype = ublox.getFixType();
// DEBUG_MSG("fix type %d\n", fixtype);
// DEBUG_MSG("sec %d\n", ublox.getSecond());
// DEBUG_MSG("lat %d\n", ublox.getLatitude());
// any fix that has time
if (ublox.getT()) {
/* Convert to unix time
The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970
(midnight UTC/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z).
*/
struct tm t;
t.tm_sec = ublox.getSecond();
t.tm_min = ublox.getMinute();
t.tm_hour = ublox.getHour();
t.tm_mday = ublox.getDay();
t.tm_mon = ublox.getMonth() - 1;
t.tm_year = ublox.getYear() - 1900;
t.tm_isdst = false;
perhapsSetRTC(t);
}
if ((fixtype >= 3 && fixtype <= 4) && ublox.getP()) // rd fixes only
{
// we only notify if position has changed
latitude = ublox.getLatitude();
longitude = ublox.getLongitude();
altitude = ublox.getAltitude() / 1000; // in mm convert to meters
DEBUG_MSG("new gps pos lat=%f, lon=%f, alt=%d\n", latitude * 1e-7, longitude * 1e-7, altitude);
hasValidLocation = (latitude != 0) || (longitude != 0); // bogus lat lon is reported as 0,0
if (hasValidLocation) {
wantNewLocation = false;
notifyObservers(NULL);
// ublox.powerOff();
}
} else // we didn't get a location update, go back to sleep and hope the characters show up
wantNewLocation = true;
// Once we have sent a location once we only poll the GPS rarely, otherwise check back every 1s until we have something over
// the serial
setPeriod(hasValidLocation && !wantNewLocation ? 30 * 1000 : 10 * 1000);
}
void UBloxGPS::startLock()
{
DEBUG_MSG("Looking for GPS lock\n");
wantNewLocation = true;
setPeriod(1);
}

41
src/gps/UBloxGPS.h Normal file
View File

@@ -0,0 +1,41 @@
#pragma once
#include "GPS.h"
#include "Observer.h"
#include "PeriodicTask.h"
#include "SparkFun_Ublox_Arduino_Library.h"
/**
* A gps class that only reads from the GPS periodically (and FIXME - eventually keeps the gps powered down except when reading)
*
* When new data is available it will notify observers.
*/
class UBloxGPS : public GPS, public PeriodicTask
{
SFE_UBLOX_GPS ublox;
bool wantNewLocation = true;
CallbackObserver<UBloxGPS, void *> notifySleepObserver = CallbackObserver<UBloxGPS, void *>(this, &UBloxGPS::prepareSleep);
public:
UBloxGPS();
/**
* Returns true if we succeeded
*/
virtual bool setup();
virtual void doTask();
/**
* Restart our lock attempt - try to get and broadcast a GPS reading ASAP
* called after the CPU wakes from light-sleep state */
virtual void startLock();
private:
/// Prepare the GPS for the cpu entering deep or light sleep, expect to be gone for at least 100s of msecs
/// always returns 0 to indicate okay to sleep
int prepareSleep(void *unused);
};

View File

@@ -21,18 +21,19 @@
*/
#include "GPS.h"
#include "MeshRadio.h"
#include "MeshService.h"
#include "NEMAGPS.h"
#include "NodeDB.h"
#include "Periodic.h"
#include "PowerFSM.h"
#include "Router.h"
#include "UBloxGPS.h"
#include "configuration.h"
#include "error.h"
#include "power.h"
// #include "rom/rtc.h"
#include "FloodingRouter.h"
#include "ReliableRouter.h"
#include "main.h"
#include "screen.h"
#include "sleep.h"
@@ -52,7 +53,7 @@ meshtastic::PowerStatus powerStatus;
bool ssd1306_found;
bool axp192_found;
FloodingRouter realRouter;
ReliableRouter realRouter;
Router &router = realRouter; // Users of router don't care what sort of subclass implements that API
// -----------------------------------------------------------------------------
@@ -103,8 +104,6 @@ const char *getDeviceName()
return name;
}
static MeshRadio *radio = NULL;
static uint32_t ledBlinker()
{
static bool ledOn;
@@ -118,6 +117,13 @@ static uint32_t ledBlinker()
Periodic ledPeriodic(ledBlinker);
#include "RF95Interface.h"
#include "SX1262Interface.h"
#ifdef NO_ESP32
#include "variant.h"
#endif
void setup()
{
#ifdef USE_SEGGER
@@ -161,7 +167,7 @@ void setup()
ledPeriodic.setup();
// Hello
DEBUG_MSG("Meshtastic swver=%s, hwver=%s\n", xstr(APP_VERSION), xstr(HW_VERSION));
DEBUG_MSG("Meshtastic swver=%s, hwver=%s\n", optstr(APP_VERSION), optstr(HW_VERSION));
#ifndef NO_ESP32
// Don't init display if we don't have one or we are waking headless due to a timer event
@@ -181,18 +187,56 @@ void setup()
screen.print("Started...\n");
// Init GPS
gps.setup();
readFromRTC(); // read the main CPU RTC at first (in case we can't get GPS time)
// If we know we have a L80 GPS, don't try UBLOX
#ifndef L80_RESET
// Init GPS - first try ublox
gps = new UBloxGPS();
if (!gps->setup()) {
// Some boards might have only the TX line from the GPS connected, in that case, we can't configure it at all. Just
// assume NEMA at 9600 baud.
DEBUG_MSG("ERROR: No UBLOX GPS found, hoping that NEMA might work\n");
delete gps;
gps = new NEMAGPS();
gps->setup();
}
#else
gps = new NEMAGPS();
gps->setup();
#endif
service.init();
realRouter.setup(); // required for our periodic task (kinda skanky FIXME)
#ifdef SX1262_ANT_SW
// make analog PA vs not PA switch on SX1262 eval board work properly
pinMode(SX1262_ANT_SW, OUTPUT);
digitalWrite(SX1262_ANT_SW, 1);
#endif
// Init our SPI controller
#ifdef NRF52_SERIES
SPI.begin();
#else
// ESP32
SPI.begin(SCK_GPIO, MISO_GPIO, MOSI_GPIO, NSS_GPIO);
SPI.setFrequency(4000000);
#endif
// MUST BE AFTER service.init, so we have our radio config settings (from nodedb init)
radio = new MeshRadio();
router.addInterface(&radio->radioIf);
RadioInterface *rIf =
#if defined(RF95_IRQ_GPIO)
// new CustomRF95(); old Radiohead based driver
new RF95Interface(NSS_GPIO, RF95_IRQ_GPIO, RESET_GPIO, SPI);
#elif defined(SX1262_CS)
new SX1262Interface(SX1262_CS, SX1262_DIO1, SX1262_RESET, SX1262_BUSY, SPI);
#else
new SimRadio();
#endif
if (radio && !radio->init())
router.addInterface(rIf);
if (!rIf->init())
recordCriticalError(ErrNoRadio);
// This must be _after_ service.init because we need our preferences loaded from flash to have proper timeout values
@@ -227,6 +271,7 @@ void loop()
{
uint32_t msecstosleep = 1000 * 30; // How long can we sleep before we again need to service the main loop?
gps->loop(); // FIXME, remove from main, instead block on read
router.loop();
powerFSM.run_machine();
service.loop();
@@ -275,7 +320,7 @@ void loop()
screen.debug()->setChannelNameStatus(channelSettings.name);
screen.debug()->setPowerStatus(powerStatus);
// TODO(#4): use something based on hdop to show GPS "signal" strength.
screen.debug()->setGPSStatus(gps.hasLock() ? "ok" : ":(");
screen.debug()->setGPSStatus(gps->hasLock() ? "good" : "bad");
// 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.

32
src/mesh/CryptoEngine.cpp Normal file
View File

@@ -0,0 +1,32 @@
#include "CryptoEngine.h"
#include "configuration.h"
void CryptoEngine::setKey(size_t numBytes, uint8_t *bytes)
{
DEBUG_MSG("WARNING: Using stub crypto - all crypto is sent in plaintext!\n");
}
/**
* Encrypt a packet
*
* @param bytes is updated in place
*/
void CryptoEngine::encrypt(uint32_t fromNode, uint64_t packetNum, size_t numBytes, uint8_t *bytes)
{
DEBUG_MSG("WARNING: noop encryption!\n");
}
void CryptoEngine::decrypt(uint32_t fromNode, uint64_t packetNum, size_t numBytes, uint8_t *bytes)
{
DEBUG_MSG("WARNING: noop decryption!\n");
}
/**
* Init our 128 bit nonce for a new packet
*/
void CryptoEngine::initNonce(uint32_t fromNode, uint64_t packetNum)
{
memset(nonce, 0, sizeof(nonce));
*((uint64_t *)&nonce[0]) = packetNum;
*((uint32_t *)&nonce[8]) = fromNode;
}

50
src/mesh/CryptoEngine.h Normal file
View File

@@ -0,0 +1,50 @@
#pragma once
#include <Arduino.h>
/**
* see docs/software/crypto.md for details.
*
*/
class CryptoEngine
{
protected:
/** Our per packet nonce */
uint8_t nonce[16];
public:
virtual ~CryptoEngine() {}
/**
* Set the key used for encrypt, decrypt.
*
* As a special case: If all bytes are zero, we assume _no encryption_ and send all data in cleartext.
*
* @param numBytes must be 16 (AES128), 32 (AES256) or 0 (no crypt)
* @param bytes a _static_ buffer that will remain valid for the life of this crypto instance (i.e. this class will cache the
* provided pointer)
*/
virtual void setKey(size_t numBytes, uint8_t *bytes);
/**
* Encrypt a packet
*
* @param bytes is updated in place
*/
virtual void encrypt(uint32_t fromNode, uint64_t packetNum, size_t numBytes, uint8_t *bytes);
virtual void decrypt(uint32_t fromNode, uint64_t packetNum, size_t numBytes, uint8_t *bytes);
protected:
/**
* Init our 128 bit nonce for a new packet
*
* The NONCE is constructed by concatenating (from MSB to LSB):
* a 64 bit packet number (stored in little endian order)
* a 32 bit sending node number (stored in little endian order)
* a 32 bit block counter (starts at zero)
*/
void initNonce(uint32_t fromNode, uint64_t packetNum);
};
extern CryptoEngine *crypto;

80
src/mesh/DSRRouter.cpp Normal file
View File

@@ -0,0 +1,80 @@
#include "DSRRouter.h"
#include "configuration.h"
/* when we receive any packet
- sniff and update tables (especially useful to find adjacent nodes). Update user, network and position info.
- if we need to route() that packet, resend it to the next_hop based on our nodedb.
- if it is broadcast or destined for our node, deliver locally
- handle routereply/routeerror/routediscovery messages as described below
- then free it
routeDiscovery
- if we've already passed through us (or is from us), then it ignore it
- use the nodes already mentioned in the request to update our routing table
- if they were looking for us, send back a routereply
- if max_hops is zero and they weren't looking for us, drop (FIXME, send back error - I think not though?)
- if we receive a discovery packet, we use it to populate next_hop (if needed) towards the requester (after decrementing max_hops)
- if we receive a discovery packet, and we have a next_hop in our nodedb for that destination we send a (reliable) we send a route
reply towards the requester
when sending any reliable packet
- if timeout doing retries, send a routeError (nak) message back towards the original requester. all nodes eavesdrop on that
packet and update their route caches.
when we receive a routereply packet
- update next_hop on the node, if the new reply needs fewer hops than the existing one (we prefer shorter paths). fixme, someday
use a better heuristic
when we receive a routeError packet
- delete the route for that failed recipient, restartRouteDiscovery()
- if we receive routeerror in response to a discovery,
- fixme, eventually keep caches of possible other routes.
*/
void DSRRouter::sniffReceived(const MeshPacket *p)
{
// FIXME, update nodedb
// Handle route discovery packets (will be a broadcast message)
if (p->decoded.which_payload == SubPacket_request_tag) {
// FIXME - always start request with the senders nodenum
if (weAreInRoute(p->decoded.request)) {
DEBUG_MSG("Ignoring a route request that contains us\n");
} else {
updateRoutes(p->decoded.request, false); // Update our routing tables based on the route that came in so far on this request
if (p->decoded.dest == getNodeNum()) {
// They were looking for us, send back a route reply (the sender address will be first in the list)
sendRouteReply(p->decoded.request);
} else {
// They were looking for someone else, forward it along (as a zero hop broadcast)
NodeNum nextHop = getNextHop(p->decoded.dest);
if (nextHop) {
// in our route cache, reply to the requester (the sender address will be first in the list)
sendRouteReply(p->decoded.request, nextHop);
} else {
// Not in our route cache, rebroadcast on their behalf (after adding ourselves to the request route)
resendRouteRequest(p);
}
}
}
}
// Handle regular packets
if (p->to == getNodeNum()) { // Destined for us (at least for this hop)
// We need to route this packet
if (p->decoded.dest != p->to) {
// FIXME
}
}
return ReliableRouter::sniffReceived(p);
}

39
src/mesh/DSRRouter.h Normal file
View File

@@ -0,0 +1,39 @@
#include "ReliableRouter.h"
class DSRRouter : public ReliableRouter
{
protected:
/**
* Every (non duplicate) packet this node receives will be passed through this method. This allows subclasses to
* update routing tables etc... based on what we overhear (even for messages not destined to our node)
*/
virtual void sniffReceived(const MeshPacket *p);
private:
/**
* Does our node appear in the specified route
*/
bool weAreInRoute(const RouteDiscovery &route);
/**
* Given a DSR route, use that route to update our DB of possible routes
**/
void updateRoutes(const RouteDiscovery &route, bool reverse);
/**
* send back a route reply (the sender address will be first in the list)
*/
void sendRouteReply(const RouteDiscovery &route, NodeNum toAppend = 0);
/**
* Given a nodenum return the next node we should forward to if we want to reach that node.
*
* @return 0 if no route found
*/
NodeNum getNextHop(NodeNum dest);
/** Not in our route cache, rebroadcast on their behalf (after adding ourselves to the request route)
*/
void resendRouteRequest(const MeshPacket *p);
};

View File

@@ -0,0 +1,55 @@
#include "FloodingRouter.h"
#include "configuration.h"
#include "mesh-pb-constants.h"
FloodingRouter::FloodingRouter() {}
/**
* Send a packet on a suitable interface. This routine will
* later free() the packet to pool. This routine is not allowed to stall.
* If the txmit queue is full it might return an error
*/
ErrorCode FloodingRouter::send(MeshPacket *p)
{
// Add any messages _we_ send to the seen message list (so we will ignore all retransmissions we see)
wasSeenRecently(p); // FIXME, move this to a sniffSent method
return Router::send(p);
}
/**
* Called from loop()
* Handle any packet that is received by an interface on this node.
* Note: some packets may merely being passed through this node and will be forwarded elsewhere.
*
* Note: this method will free the provided packet
*/
void FloodingRouter::handleReceived(MeshPacket *p)
{
if (wasSeenRecently(p)) {
DEBUG_MSG("Ignoring incoming msg, because we've already seen it\n");
packetPool.release(p);
} else {
// If a broadcast, possibly _also_ send copies out into the mesh.
// (FIXME, do something smarter than naive flooding here)
if (p->to == NODENUM_BROADCAST && p->hop_limit > 0) {
if (p->id != 0) {
MeshPacket *tosend = packetPool.allocCopy(*p); // keep a copy because we will be sending it
tosend->hop_limit--; // bump down the hop count
DEBUG_MSG("Rebroadcasting received floodmsg to neighbors, fr=0x%x,to=0x%x,id=%d,hop_limit=%d\n", p->from, p->to,
p->id, tosend->hop_limit);
// Note: we are careful to resend using the original senders node id
// We are careful not to call our hooked version of send() - because we don't want to check this again
Router::send(tosend);
} else {
DEBUG_MSG("Ignoring a simple (0 id) broadcast\n");
}
}
// handle the packet as normal
Router::handleReceived(p);
}
}

View File

@@ -1,17 +1,8 @@
#pragma once
#include "PacketHistory.h"
#include "PeriodicTask.h"
#include "Router.h"
#include <vector>
/**
* A record of a recent message broadcast
*/
struct BroadcastRecord {
NodeNum sender;
PacketId id;
uint32_t rxTimeMsec; // Unix time in msecs - the time we received it
};
/**
* This is a mixin that extends Router with the ability to do Naive Flooding (in the standard mesh protocol sense)
@@ -36,19 +27,9 @@ struct BroadcastRecord {
Any entries in recentBroadcasts that are older than X seconds (longer than the
max time a flood can take) will be discarded.
*/
class FloodingRouter : public Router, public PeriodicTask
class FloodingRouter : public Router, protected PacketHistory
{
private:
/** FIXME: really should be a std::unordered_set with the key being sender,id.
* This would make checking packets in wasSeenRecently faster.
*/
std::vector<BroadcastRecord> recentBroadcasts;
/**
* Packets we've received that we need to resend after a short delay
*/
PointerQueue<MeshPacket> toResend;
public:
/**
* Constructor
@@ -72,12 +53,4 @@ class FloodingRouter : public Router, public PeriodicTask
* Note: this method will free the provided packet
*/
virtual void handleReceived(MeshPacket *p);
virtual void doTask();
private:
/**
* Update recentBroadcasts and return true if we have already seen this packet
*/
bool wasSeenRecently(const MeshPacket *p);
};

View File

@@ -1,125 +0,0 @@
#include "error.h"
#include <SPI.h>
#include <assert.h>
#include "MeshRadio.h"
#include "MeshService.h"
#include "NodeDB.h"
#include "configuration.h"
#include "sleep.h"
#include <pb_decode.h>
#include <pb_encode.h>
/**
* ## LoRaWAN for North America
LoRaWAN defines 64, 125 kHz channels from 902.3 to 914.9 MHz increments.
The maximum output power for North America is +30 dBM.
The band is from 902 to 928 MHz. It mentions channel number and its respective channel frequency. All the 13 channels are
separated by 2.16 MHz with respect to the adjacent channels. Channel zero starts at 903.08 MHz center frequency.
*/
/// Sometimes while debugging it is useful to set this false, to disable rf95 accesses
bool useHardware = true;
MeshRadio::MeshRadio() // , manager(radioIf)
{
myNodeInfo.num_channels = NUM_CHANNELS;
// Can't print strings this early - serial not setup yet
// DEBUG_MSG("Set meshradio defaults name=%s\n", channelSettings.name);
}
bool MeshRadio::init()
{
if (!useHardware)
return true;
DEBUG_MSG("Starting meshradio init...\n");
configChangedObserver.observe(&service.configChanged);
preflightSleepObserver.observe(&preflightSleep);
notifyDeepSleepObserver.observe(&notifyDeepSleep);
#ifdef RESET_GPIO
pinMode(RESET_GPIO, OUTPUT); // Deassert reset
digitalWrite(RESET_GPIO, HIGH);
// pulse reset
digitalWrite(RESET_GPIO, LOW);
delay(10);
digitalWrite(RESET_GPIO, HIGH);
delay(10);
#endif
radioIf.setThisAddress(
nodeDB.getNodeNum()); // Note: we must do this here, because the nodenum isn't inited at constructor time.
if (!radioIf.init()) {
DEBUG_MSG("LoRa radio init failed\n");
DEBUG_MSG("Uncomment '#define SERIAL_DEBUG' in RH_RF95.cpp for detailed debug info\n");
return false;
}
// not needed - defaults on
// rf95.setPayloadCRC(true);
reloadConfig();
return true;
}
/** hash a string into an integer
*
* djb2 by Dan Bernstein.
* http://www.cse.yorku.ca/~oz/hash.html
*/
unsigned long hash(char *str)
{
unsigned long hash = 5381;
int c;
while ((c = *str++) != 0)
hash = ((hash << 5) + hash) + (unsigned char)c; /* hash * 33 + c */
return hash;
}
int MeshRadio::reloadConfig(void *unused)
{
radioIf.setModeIdle(); // Need to be idle before doing init
// Set up default configuration
// No Sync Words in LORA mode.
radioIf.setModemConfig(
(RH_RF95::ModemConfigChoice)channelSettings.modem_config); // Radio default
// setModemConfig(Bw125Cr48Sf4096); // slow and reliable?
// rf95.setPreambleLength(8); // Default is 8
// Defaults after init are 434.0MHz, modulation GFSK_Rb250Fd250, +13dbM
int channel_num = hash(channelSettings.name) % NUM_CHANNELS;
float center_freq = CH0 + CH_SPACING * channel_num;
if (!radioIf.setFrequency(center_freq)) {
DEBUG_MSG("setFrequency failed\n");
assert(0); // fixme panic
}
// Defaults after init are 434.0MHz, 13dBm, Bw = 125 kHz, Cr = 4/5, Sf = 128chips/symbol, CRC on
// The default transmitter power is 13dBm, using PA_BOOST.
// If you are using RFM95/96/97/98 modules which uses the PA_BOOST transmitter pin, then
// you can set transmitter powers from 5 to 23 dBm:
// FIXME - can we do this? It seems to be in the Heltec board.
radioIf.setTxPower(channelSettings.tx_power, false);
DEBUG_MSG("Set radio: name=%s, config=%u, ch=%d, txpower=%d\n", channelSettings.name, channelSettings.modem_config,
channel_num, channelSettings.tx_power);
// Done with init tell radio to start receiving
radioIf.setModeRx();
return 0;
}

View File

@@ -1,9 +1,7 @@
#pragma once
#include "CustomRF95.h"
#include "MemoryPool.h"
#include "MeshTypes.h"
#include "Observer.h"
#include "PointerQueue.h"
#include "configuration.h"
#include "mesh.pb.h"
@@ -61,47 +59,3 @@
#define NUM_CHANNELS NUM_CHANNELS_US
#endif
/**
* A raw low level interface to our mesh. Only understands nodenums and bytes (not protobufs or node ids)
*/
class MeshRadio
{
public:
// Kinda ugly way of selecting different radio implementations, but soon this MeshRadio class will be going away
// entirely. At that point we can make things pretty.
#ifdef RF95_IRQ_GPIO
CustomRF95
radioIf; // the raw radio interface - for now I'm leaving public - because this class is shrinking to be almost nothing
#else
SimRadio radioIf;
#endif
/** pool is the pool we will alloc our rx packets from
* rxDest is where we will send any rx packets, it becomes receivers responsibility to return packet to the pool
*/
MeshRadio();
bool init();
private:
CallbackObserver<MeshRadio, void *> configChangedObserver =
CallbackObserver<MeshRadio, void *>(this, &MeshRadio::reloadConfig);
CallbackObserver<MeshRadio, void *> preflightSleepObserver =
CallbackObserver<MeshRadio, void *>(this, &MeshRadio::preflightSleepCb);
CallbackObserver<MeshRadio, void *> notifyDeepSleepObserver =
CallbackObserver<MeshRadio, void *>(this, &MeshRadio::notifyDeepSleepDb);
/// The radioConfig object just changed, call this to force the hw to change to the new settings
int reloadConfig(void *unused = NULL);
/// Return 0 if sleep is okay
int preflightSleepCb(void *unused = NULL) { return radioIf.canSleep() ? 0 : 1; }
int notifyDeepSleepDb(void *unused = NULL)
{
radioIf.sleep();
return 0;
}
};

View File

@@ -46,8 +46,6 @@ MeshService service;
#include "Router.h"
#define NUM_PACKET_ID 255 // 0 is consider invalid
static uint32_t sendOwnerCb()
{
service.sendOurOwner();
@@ -57,16 +55,6 @@ static uint32_t sendOwnerCb()
static Periodic sendOwnerPeriod(sendOwnerCb);
/// Generate a unique packet id
// FIXME, move this someplace better
PacketId generatePacketId()
{
static uint32_t i;
i++;
return (i % NUM_PACKET_ID) + 1; // return number between 1 and 255
}
MeshService::MeshService() : toPhoneQueue(MAX_RX_TOPHONE)
{
// assert(MAX_RX_TOPHONE == 32); // FIXME, delete this, just checking my clever macro
@@ -77,17 +65,17 @@ void MeshService::init()
sendOwnerPeriod.setup();
nodeDB.init();
gpsObserver.observe(&gps);
gpsObserver.observe(gps);
packetReceivedObserver.observe(&router.notifyPacketReceived);
}
void MeshService::sendOurOwner(NodeNum dest, bool wantReplies)
{
MeshPacket *p = allocForSending();
MeshPacket *p = router.allocForSending();
p->to = dest;
p->payload.want_response = wantReplies;
p->payload.has_user = true;
User &u = p->payload.user;
p->decoded.want_response = wantReplies;
p->decoded.which_payload = SubPacket_user_tag;
User &u = p->decoded.user;
u = owner;
DEBUG_MSG("sending owner %s/%s/%s\n", u.id, u.long_name, u.short_name);
@@ -101,7 +89,7 @@ const MeshPacket *MeshService::handleFromRadioUser(const MeshPacket *mp)
bool isCollision = mp->from == myNodeInfo.my_node_num;
// we win if we have a lower macaddr
bool weWin = memcmp(&owner.macaddr, &mp->payload.user.macaddr, sizeof(owner.macaddr)) < 0;
bool weWin = memcmp(&owner.macaddr, &mp->decoded.user.macaddr, sizeof(owner.macaddr)) < 0;
if (isCollision) {
if (weWin) {
@@ -127,7 +115,7 @@ const MeshPacket *MeshService::handleFromRadioUser(const MeshPacket *mp)
sendOurOwner(mp->from);
String lcd = String("Joined: ") + mp->payload.user.long_name + "\n";
String lcd = String("Joined: ") + mp->decoded.user.long_name + "\n";
screen.print(lcd.c_str());
}
@@ -136,17 +124,17 @@ const MeshPacket *MeshService::handleFromRadioUser(const MeshPacket *mp)
void MeshService::handleIncomingPosition(const MeshPacket *mp)
{
if (mp->has_payload && mp->payload.has_position) {
DEBUG_MSG("handled incoming position time=%u\n", mp->payload.position.time);
if (mp->which_payload == MeshPacket_decoded_tag && mp->decoded.which_payload == SubPacket_position_tag) {
DEBUG_MSG("handled incoming position time=%u\n", mp->decoded.position.time);
if (mp->payload.position.time) {
if (mp->decoded.position.time) {
struct timeval tv;
uint32_t secs = mp->payload.position.time;
uint32_t secs = mp->decoded.position.time;
tv.tv_sec = secs;
tv.tv_usec = 0;
gps.perhapsSetRTC(&tv);
perhapsSetRTC(&tv);
}
} else {
DEBUG_MSG("Ignoring incoming packet - not a position\n");
@@ -158,13 +146,13 @@ int MeshService::handleFromRadio(const MeshPacket *mp)
powerFSM.trigger(EVENT_RECEIVED_PACKET); // Possibly keep the node from sleeping
// 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 (!gps.isConnected)
if (!gps->isConnected)
handleIncomingPosition(mp);
else {
DEBUG_MSG("Ignoring incoming time, because we have a GPS\n");
}
if (mp->has_payload && mp->payload.has_user) {
if (mp->which_payload == MeshPacket_decoded_tag && mp->decoded.which_payload == SubPacket_user_tag) {
mp = handleFromRadioUser(mp);
}
@@ -185,7 +173,7 @@ int MeshService::handleFromRadio(const MeshPacket *mp)
MeshPacket *copied = packetPool.allocCopy(*mp);
assert(toPhoneQueue.enqueue(copied, 0)); // FIXME, instead of failing for full queue, delete the oldest mssages
if (mp->payload.want_response)
if (mp->decoded.want_response)
sendNetworkPing(mp->from);
} else {
DEBUG_MSG("Not delivering vetoed User message\n");
@@ -227,8 +215,8 @@ void MeshService::handleToRadio(MeshPacket &p)
if (p.id == 0)
p.id = generatePacketId(); // If the phone didn't supply one, then pick one
p.rx_time = gps.getValidTime(); // Record the time the packet arrived from the phone
// (so we update our nodedb for the local node)
p.rx_time = getValidTime(); // Record the time the packet arrived from the phone
// (so we update our nodedb for the local node)
// Send the packet into the mesh
@@ -250,39 +238,21 @@ void MeshService::sendToMesh(MeshPacket *p)
// 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.has_position) {
if (!gps.isConnected) {
DEBUG_MSG("Stripping time %u from position send\n", p->payload.position.time);
p->payload.position.time = 0;
if (p->which_payload == MeshPacket_decoded_tag && p->decoded.which_payload == SubPacket_position_tag) {
if (!gps->isConnected) {
DEBUG_MSG("Stripping time %u from position send\n", p->decoded.position.time);
p->decoded.position.time = 0;
} else
DEBUG_MSG("Providing time to mesh %u\n", p->payload.position.time);
DEBUG_MSG("Providing time to mesh %u\n", p->decoded.position.time);
}
// If the phone sent a packet just to us, don't send it out into the network
if (p->to == nodeDB.getNodeNum())
DEBUG_MSG("Dropping locally processed message\n");
else {
// Note: We might return !OK if our fifo was full, at that point the only option we have is to drop it
if (router.send(p) != ERRNO_OK) {
DEBUG_MSG("No radio was able to send packet, discarding...\n");
releaseToPool(p);
}
// Note: We might return !OK if our fifo was full, at that point the only option we have is to drop it
if (router.sendLocal(p) != ERRNO_OK) {
DEBUG_MSG("No radio was able to send packet, discarding...\n");
releaseToPool(p);
}
}
MeshPacket *MeshService::allocForSending()
{
MeshPacket *p = packetPool.allocZeroed();
p->has_payload = true;
p->from = nodeDB.getNodeNum();
p->to = NODENUM_BROADCAST;
p->id = generatePacketId();
p->rx_time = gps.getValidTime(); // Just in case we process the packet locally - make sure it has a valid timestamp
return p;
}
void MeshService::sendNetworkPing(NodeNum dest, bool wantReplies)
{
NodeInfo *node = nodeDB.getNode(nodeDB.getNodeNum());
@@ -302,31 +272,31 @@ void MeshService::sendOurPosition(NodeNum dest, bool wantReplies)
assert(node->has_position);
// Update our local node info with our position (even if we don't decide to update anyone else)
MeshPacket *p = allocForSending();
MeshPacket *p = router.allocForSending();
p->to = dest;
p->payload.has_position = true;
p->payload.position = node->position;
p->payload.want_response = wantReplies;
p->payload.position.time = gps.getValidTime(); // This nodedb timestamp might be stale, so update it if our clock is valid.
p->decoded.which_payload = SubPacket_position_tag;
p->decoded.position = node->position;
p->decoded.want_response = wantReplies;
p->decoded.position.time = getValidTime(); // This nodedb timestamp might be stale, so update it if our clock is valid.
sendToMesh(p);
}
int MeshService::onGPSChanged(void *unused)
{
DEBUG_MSG("got gps notify\n");
// DEBUG_MSG("got gps notify\n");
// Update our local node info with our position (even if we don't decide to update anyone else)
MeshPacket *p = allocForSending();
p->payload.has_position = true;
MeshPacket *p = router.allocForSending();
p->decoded.which_payload = SubPacket_position_tag;
Position &pos = p->payload.position;
Position &pos = p->decoded.position;
// !zero or !zero lat/long means valid
if (gps.latitude != 0 || gps.longitude != 0) {
if (gps.altitude != 0)
pos.altitude = gps.altitude;
pos.latitude = gps.latitude;
pos.longitude = gps.longitude;
pos.time = gps.getValidTime();
if (gps->latitude != 0 || gps->longitude != 0) {
if (gps->altitude != 0)
pos.altitude = gps->altitude;
pos.latitude_i = gps->latitude;
pos.longitude_i = gps->longitude;
pos.time = getValidTime();
}
// We limit our GPS broadcasts to a max rate

View File

@@ -67,9 +67,6 @@ class MeshService
/// The owner User record just got updated, update our node DB and broadcast the info into the mesh
void reloadOwner() { sendOurOwner(); }
/// Allocate and return a meshpacket which defaults as send to broadcast from the current node.
MeshPacket *allocForSending();
/// Called when the user wakes up our GUI, normally sends our latest location to the mesh (if we have it), otherwise at least
/// sends our owner
void sendNetworkPing(NodeNum dest, bool wantReplies = false);

View File

@@ -14,6 +14,18 @@ typedef uint8_t PacketId; // A packet sequence number
#define ERRNO_NO_INTERFACES 33
#define ERRNO_UNKNOWN 32 // pick something that doesn't conflict with RH_ROUTER_ERROR_UNABLE_TO_DELIVER
/**
* the max number of hops a message can pass through, used as the default max for hop_limit in MeshPacket.
*
* We reserve 3 bits in the header so this could be up to 7, but given the high range of lora and typical usecases, keeping
* maxhops to 3 should be fine for a while. This also serves to prevent routing/flooding attempts to be attempted for
* too long.
**/
#define HOP_MAX 7
/// We normally just use max 3 hops for sending reliable messages
#define HOP_RELIABLE 3
typedef int ErrorCode;
/// Alloc and free packets to our global, ISR safe pool

View File

@@ -5,6 +5,7 @@
#include "FS.h"
#include "SPIFFS.h"
#include "CryptoEngine.h"
#include "GPS.h"
#include "NodeDB.h"
#include "PowerFSM.h"
@@ -47,11 +48,17 @@ User &owner = devicestate.owner;
static uint8_t ourMacAddr[6];
/**
* The node number the user is currently looking at
* 0 if none
*/
NodeNum displayedNodeNum;
NodeDB::NodeDB() : nodes(devicestate.node_db), numNodes(&devicestate.node_db_count) {}
void NodeDB::resetRadioConfig()
{
/// 16 bytes of random PSK for our _public_ default channel that all devices power up on
/// 16 bytes of random PSK for our _public_ default channel that all devices power up on (AES128)
static const uint8_t defaultpsk[] = {0xd4, 0xf1, 0xbb, 0x3a, 0x20, 0x29, 0x07, 0x59,
0xf0, 0xbc, 0xff, 0xab, 0xcf, 0x4e, 0x69, 0xbf};
@@ -75,10 +82,14 @@ void NodeDB::resetRadioConfig()
channelSettings.modem_config = ChannelSettings_ModemConfig_Bw125Cr48Sf4096; // slow and long range
channelSettings.tx_power = 23;
memcpy(&channelSettings.psk, &defaultpsk, sizeof(channelSettings.psk));
memcpy(&channelSettings.psk.bytes, &defaultpsk, sizeof(channelSettings.psk));
channelSettings.psk.size = sizeof(defaultpsk);
strcpy(channelSettings.name, "Default");
}
// Tell our crypto engine about the psk
crypto->setKey(channelSettings.psk.size, channelSettings.psk.bytes);
// temp hack for quicker testing
/*
radioConfig.preferences.screen_on_secs = 30;
@@ -104,10 +115,6 @@ void NodeDB::init()
// default to no GPS, until one has been found by probing
myNodeInfo.has_gps = false;
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
getMacAddr(ourMacAddr);
sprintf(owner.id, "!%02x%02x%02x%02x%02x%02x", ourMacAddr[0], ourMacAddr[1], ourMacAddr[2], ourMacAddr[3], ourMacAddr[4],
@@ -130,6 +137,13 @@ void NodeDB::init()
// saveToDisk();
loadFromDisk();
// We set these _after_ loading from disk - because they come from the build and are more trusted than
// what is stored in flash
strncpy(myNodeInfo.region, optstr(HW_VERSION), sizeof(myNodeInfo.region));
strncpy(myNodeInfo.firmware_version, optstr(APP_VERSION), sizeof(myNodeInfo.firmware_version));
strncpy(myNodeInfo.hw_model, HW_VENDOR, sizeof(myNodeInfo.hw_model));
resetRadioConfig(); // If bogus settings got saved, then fix them
DEBUG_MSG("NODENUM=0x%x, dbsize=%d\n", myNodeInfo.my_node_num, *numNodes);
@@ -246,7 +260,7 @@ const NodeInfo *NodeDB::readNextInfo()
/// Given a node, return how many seconds in the past (vs now) that we last heard from it
uint32_t sinceLastSeen(const NodeInfo *n)
{
uint32_t now = gps.getTime();
uint32_t now = getTime();
uint32_t last_seen = n->position.time;
int delta = (int)(now - last_seen);
@@ -274,8 +288,8 @@ size_t NodeDB::getNumOnlineNodes()
/// we updateGUI and updateGUIforNode if we think our this change is big enough for a redraw
void NodeDB::updateFrom(const MeshPacket &mp)
{
if (mp.has_payload) {
const SubPacket &p = mp.payload;
if (mp.which_payload == MeshPacket_decoded_tag) {
const SubPacket &p = mp.decoded;
DEBUG_MSG("Update DB node 0x%x, rx_time=%u\n", mp.from, mp.rx_time);
int oldNumNodes = *numNodes;
@@ -289,19 +303,24 @@ void NodeDB::updateFrom(const MeshPacket &mp)
info->position.time = mp.rx_time;
}
if (p.has_position) {
info->snr = mp.rx_snr; // keep the most recent SNR we received for this node.
switch (p.which_payload) {
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.position;
info->position.time = oldtime;
info->has_position = true;
updateGUIforNode = info;
break;
}
if (p.has_data) {
case SubPacket_data_tag: {
// Keep a copy of the most recent text message.
if (p.data.typ == Data_Type_CLEAR_TEXT) {
DEBUG_MSG("Received text msg from=0%0x, msg=%.*s\n", mp.from, p.data.payload.size, p.data.payload.bytes);
DEBUG_MSG("Received text msg from=0x%0x, id=%d, msg=%.*s\n", mp.from, mp.id, p.data.payload.size,
p.data.payload.bytes);
if (mp.to == NODENUM_BROADCAST || mp.to == nodeDB.getNodeNum()) {
// We only store/display messages destined for us.
devicestate.rx_text_message = mp;
@@ -310,9 +329,10 @@ void NodeDB::updateFrom(const MeshPacket &mp)
powerFSM.trigger(EVENT_RECEIVED_TEXT_MSG);
}
}
break;
}
if (p.has_user) {
case SubPacket_user_tag: {
DEBUG_MSG("old user %s/%s/%s\n", info->user.id, info->user.long_name, info->user.short_name);
bool changed = memcmp(&info->user, &p.user,
@@ -330,6 +350,8 @@ void NodeDB::updateFrom(const MeshPacket &mp)
// We just changed something important about the user, store our DB
// saveToDisk();
}
break;
}
}
}
}

View File

@@ -95,4 +95,10 @@ class NodeDB
void loadFromDisk();
};
/**
* The node number the user is currently looking at
* 0 if none
*/
extern NodeNum displayedNodeNum;
extern NodeDB nodeDB;

View File

@@ -0,0 +1,55 @@
#include "PacketHistory.h"
#include "configuration.h"
/// We clear our old flood record five minute after we see the last of it
#define FLOOD_EXPIRE_TIME (5 * 60 * 1000L)
PacketHistory::PacketHistory()
{
recentPackets.reserve(MAX_NUM_NODES); // Prealloc the worst case # of records - to prevent heap fragmentation
// setup our periodic task
}
/**
* Update recentBroadcasts and return true if we have already seen this packet
*/
bool PacketHistory::wasSeenRecently(const MeshPacket *p, bool withUpdate)
{
if (p->id == 0) {
DEBUG_MSG("Ignoring message with zero id\n");
return false; // Not a floodable message ID, so we don't care
}
uint32_t now = millis();
for (size_t i = 0; i < recentPackets.size();) {
PacketRecord &r = recentPackets[i];
if ((now - r.rxTimeMsec) >= FLOOD_EXPIRE_TIME) {
// DEBUG_MSG("Deleting old broadcast record %d\n", i);
recentPackets.erase(recentPackets.begin() + i); // delete old record
} else {
if (r.id == p->id && r.sender == p->from) {
DEBUG_MSG("Found existing packet record for fr=0x%x,to=0x%x,id=%d\n", p->from, p->to, p->id);
// Update the time on this record to now
if (withUpdate)
r.rxTimeMsec = now;
return true;
}
i++;
}
}
// Didn't find an existing record, make one
if (withUpdate) {
PacketRecord r;
r.id = p->id;
r.sender = p->from;
r.rxTimeMsec = now;
recentPackets.push_back(r);
DEBUG_MSG("Adding packet record for fr=0x%x,to=0x%x,id=%d\n", p->from, p->to, p->id);
}
return false;
}

68
src/mesh/PacketHistory.h Normal file
View File

@@ -0,0 +1,68 @@
#pragma once
#include "Router.h"
#include <queue>
#include <unordered_set>
using namespace std;
/**
* A record of a recent message broadcast
*/
struct PacketRecord {
NodeNum sender;
PacketId id;
uint32_t rxTimeMsec; // Unix time in msecs - the time we received it
bool operator==(const PacketRecord &p) const { return sender == p.sender && id == p.id; }
};
class PacketRecordHashFunction
{
public:
size_t operator()(const PacketRecord &p) const { return (hash<NodeNum>()(p.sender)) ^ (hash<PacketId>()(p.id)); }
};
/// Order packet records by arrival time, we want the oldest packets to be in the front of our heap
class PacketRecordOrderFunction
{
public:
size_t operator()(const PacketRecord &p1, const PacketRecord &p2) const
{
// If the timer ticks have rolled over the difference between times will be _enormous_. Handle that case specially
uint32_t t1 = p1.rxTimeMsec, t2 = p2.rxTimeMsec;
if (abs(t1 - t2) >
UINT32_MAX /
2) { // time must have rolled over, swap them because the new little number is 'bigger' than the old big number
t1 = t2;
t2 = p1.rxTimeMsec;
}
return t1 > t2;
}
};
/**
* This is a mixin that adds a record of past packets we have seen
*/
class PacketHistory
{
private:
/** FIXME: really should be a std::unordered_set with the key being sender,id.
* This would make checking packets in wasSeenRecently faster.
*/
vector<PacketRecord> recentPackets;
// priority_queue<PacketRecord, vector<PacketRecord>, PacketRecordOrderFunction> arrivalTimes;
// unordered_set<PacketRecord, PacketRecordHashFunction> recentPackets;
public:
PacketHistory();
/**
* Update recentBroadcasts and return true if we have already seen this packet
*
* @param withUpdate if true and not found we add an entry to recentPackets
*/
bool wasSeenRecently(const MeshPacket *p, bool withUpdate = true);
};

View File

@@ -45,9 +45,6 @@ class PhoneAPI
/// We temporarily keep the nodeInfo here between the call to available and getFromRadio
const NodeInfo *nodeInfoForPhone = NULL;
/// Our fromradio packet while it is being assembled
FromRadio fromRadioScratch;
ToRadio toRadioScratch; // this is a static scratch object, any data must be copied elsewhere before returning
/// Use to ensure that clients don't get confused about old messages from the radio
@@ -85,10 +82,13 @@ class PhoneAPI
void handleSetRadio(const RadioConfig &r);
protected:
/// Our fromradio packet while it is being assembled
FromRadio fromRadioScratch;
/**
* Subclasses can use this as a hook to provide custom notifications for their transport (i.e. bluetooth notifies)
*/
void onNowHasData(uint32_t fromRadioNum) {}
virtual void onNowHasData(uint32_t fromRadioNum) {}
private:
/**

126
src/mesh/RF95Interface.cpp Normal file
View File

@@ -0,0 +1,126 @@
#include "RF95Interface.h"
#include "MeshRadio.h" // kinda yucky, but we need to know which region we are in
#include "RadioLibRF95.h"
#include <configuration.h>
#define MAX_POWER 17
// if we use 20 we are limited to 1% duty cycle or hw might overheat. For continuous operation set a limit of 17
RF95Interface::RF95Interface(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, SPIClass &spi)
: RadioLibInterface(cs, irq, rst, 0, spi)
{
// FIXME - we assume devices never get destroyed
}
/// Initialise the Driver transport hardware and software.
/// Make sure the Driver is properly configured before calling init().
/// \return true if initialisation succeeded.
bool RF95Interface::init()
{
RadioLibInterface::init();
applyModemConfig();
if (power > MAX_POWER) // This chip has lower power limits than some
power = MAX_POWER;
iface = lora = new RadioLibRF95(&module);
int res = lora->begin(freq, bw, sf, cr, syncWord, power, currentLimit, preambleLength);
DEBUG_MSG("LORA init result %d\n", res);
if (res == ERR_NONE)
res = lora->setCRC(SX126X_LORA_CRC_ON);
if (res == ERR_NONE)
startReceive(); // start receiving
return res == ERR_NONE;
}
void INTERRUPT_ATTR RF95Interface::disableInterrupt()
{
lora->clearDio0Action();
}
bool RF95Interface::reconfigure()
{
applyModemConfig();
// set mode to standby
setStandby();
// configure publicly accessible settings
int err = lora->setSpreadingFactor(sf);
assert(err == ERR_NONE);
err = lora->setBandwidth(bw);
assert(err == ERR_NONE);
err = lora->setCodingRate(cr);
assert(err == ERR_NONE);
err = lora->setSyncWord(syncWord);
assert(err == ERR_NONE);
err = lora->setCurrentLimit(currentLimit);
assert(err == ERR_NONE);
err = lora->setPreambleLength(preambleLength);
assert(err == ERR_NONE);
err = lora->setFrequency(freq);
assert(err == ERR_NONE);
if (power > MAX_POWER) // This chip has lower power limits than some
power = MAX_POWER;
err = lora->setOutputPower(power);
assert(err == ERR_NONE);
startReceive(); // restart receiving
return ERR_NONE;
}
/**
* Add SNR data to received messages
*/
void RF95Interface::addReceiveMetadata(MeshPacket *mp)
{
mp->rx_snr = lora->getSNR();
}
void RF95Interface::setStandby()
{
int err = lora->standby();
assert(err == ERR_NONE);
isReceiving = false; // If we were receiving, not any more
disableInterrupt();
completeSending(); // If we were sending, not anymore
}
void RF95Interface::startReceive()
{
setStandby();
int err = lora->startReceive();
assert(err == ERR_NONE);
isReceiving = true;
// Must be done AFTER, starting transmit, because startTransmit clears (possibly stale) interrupt pending register bits
enableInterrupt(isrRxLevel0);
}
/** Could we send right now (i.e. either not actively receving or transmitting)? */
bool RF95Interface::isActivelyReceiving()
{
return lora->isReceiving();
}
bool RF95Interface::sleep()
{
// put chipset into sleep mode
disableInterrupt();
lora->sleep();
return true;
}

55
src/mesh/RF95Interface.h Normal file
View File

@@ -0,0 +1,55 @@
#pragma once
#include "MeshRadio.h" // kinda yucky, but we need to know which region we are in
#include "RadioLibInterface.h"
#include "RadioLibRF95.h"
/**
* Our new not radiohead adapter for RF95 style radios
*/
class RF95Interface : public RadioLibInterface
{
RadioLibRF95 *lora; // Either a RFM95 or RFM96 depending on what was stuffed on this board
public:
RF95Interface(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, SPIClass &spi);
/// Initialise the Driver transport hardware and software.
/// Make sure the Driver is properly configured before calling init().
/// \return true if initialisation succeeded.
virtual bool init();
/// Apply any radio provisioning changes
/// Make sure the Driver is properly configured before calling init().
/// \return true if initialisation succeeded.
virtual bool reconfigure();
/// Prepare hardware for sleep. Call this _only_ for deep sleep, not needed for light sleep.
virtual bool sleep();
protected:
/**
* Glue functions called from ISR land
*/
virtual void disableInterrupt();
/**
* Enable a particular ISR callback glue function
*/
virtual void enableInterrupt(void (*callback)()) { lora->setDio0Action(callback); }
/** are we actively receiving a packet (only called during receiving state) */
virtual bool isActivelyReceiving();
/**
* Start waiting to receive a message
*/
virtual void startReceive();
/**
* Add SNR data to received messages
*/
virtual void addReceiveMetadata(MeshPacket *mp);
virtual void setStandby();
};

129
src/mesh/RadioInterface.cpp Normal file
View File

@@ -0,0 +1,129 @@
#include "RadioInterface.h"
#include "MeshRadio.h"
#include "MeshService.h"
#include "NodeDB.h"
#include "assert.h"
#include "configuration.h"
#include "sleep.h"
#include <assert.h>
#include <pb_decode.h>
#include <pb_encode.h>
/**
* ## LoRaWAN for North America
LoRaWAN defines 64, 125 kHz channels from 902.3 to 914.9 MHz increments.
The maximum output power for North America is +30 dBM.
The band is from 902 to 928 MHz. It mentions channel number and its respective channel frequency. All the 13 channels are
separated by 2.16 MHz with respect to the adjacent channels. Channel zero starts at 903.08 MHz center frequency.
*/
// 1kb was too small
#define RADIO_STACK_SIZE 4096
RadioInterface::RadioInterface() : txQueue(MAX_TX_QUEUE)
{
assert(sizeof(PacketHeader) == 4); // make sure the compiler did what we expected
myNodeInfo.num_channels = NUM_CHANNELS;
// Can't print strings this early - serial not setup yet
// DEBUG_MSG("Set meshradio defaults name=%s\n", channelSettings.name);
}
bool RadioInterface::init()
{
DEBUG_MSG("Starting meshradio init...\n");
configChangedObserver.observe(&service.configChanged);
preflightSleepObserver.observe(&preflightSleep);
notifyDeepSleepObserver.observe(&notifyDeepSleep);
// we now expect interfaces to operate in promiscous mode
// radioIf.setThisAddress(nodeDB.getNodeNum()); // Note: we must do this here, because the nodenum isn't inited at constructor
// time.
// we want this thread to run at very high priority, because it is effectively running as a user space ISR
start("radio", RADIO_STACK_SIZE, configMAX_PRIORITIES - 1); // Start our worker thread
return true;
}
/** hash a string into an integer
*
* djb2 by Dan Bernstein.
* http://www.cse.yorku.ca/~oz/hash.html
*/
unsigned long hash(char *str)
{
unsigned long hash = 5381;
int c;
while ((c = *str++) != 0)
hash = ((hash << 5) + hash) + (unsigned char)c; /* hash * 33 + c */
return hash;
}
/**
* Pull our channel settings etc... from protobufs to the dumb interface settings
*/
void RadioInterface::applyModemConfig()
{
// Set up default configuration
// No Sync Words in LORA mode.
modemConfig = (ModemConfigChoice)channelSettings.modem_config;
// Defaults after init are 434.0MHz, modulation GFSK_Rb250Fd250, +13dbM
int channel_num = hash(channelSettings.name) % NUM_CHANNELS;
freq = CH0 + CH_SPACING * channel_num;
power = channelSettings.tx_power;
DEBUG_MSG("Set radio: name=%s, config=%u, ch=%d, power=%d\n", channelSettings.name, channelSettings.modem_config, channel_num,
channelSettings.tx_power);
}
ErrorCode SimRadio::send(MeshPacket *p)
{
DEBUG_MSG("SimRadio.send\n");
packetPool.release(p);
return ERRNO_OK;
}
void RadioInterface::deliverToReceiver(MeshPacket *p)
{
assert(rxDest);
assert(rxDest->enqueue(p, 0)); // NOWAIT - fixme, if queue is full, delete older messages
}
/***
* given a packet set sendingPacket and decode the protobufs into radiobuf. Returns # of payload bytes to send
*/
size_t RadioInterface::beginSending(MeshPacket *p)
{
assert(!sendingPacket);
// DEBUG_MSG("sending queued packet on mesh (txGood=%d,rxGood=%d,rxBad=%d)\n", rf95.txGood(), rf95.rxGood(), rf95.rxBad());
assert(p->which_payload == MeshPacket_encrypted_tag); // It should have already been encoded by now
lastTxStart = millis();
PacketHeader *h = (PacketHeader *)radiobuf;
h->from = p->from;
h->to = p->to;
h->id = p->id;
assert(p->hop_limit <= HOP_MAX);
h->flags = p->hop_limit | (p->want_ack ? PACKET_FLAGS_WANT_ACK_MASK : 0);
// if the sender nodenum is zero, that means uninitialized
assert(h->from);
memcpy(radiobuf + sizeof(PacketHeader), p->encrypted.bytes, p->encrypted.size);
sendingPacket = p;
return p->encrypted.size + sizeof(PacketHeader);
}

163
src/mesh/RadioInterface.h Normal file
View File

@@ -0,0 +1,163 @@
#pragma once
#include "MemoryPool.h"
#include "MeshTypes.h"
#include "Observer.h"
#include "PointerQueue.h"
#include "WorkerThread.h"
#include "mesh.pb.h"
#define MAX_TX_QUEUE 16 // max number of packets which can be waiting for transmission
#define MAX_RHPACKETLEN 256
#define PACKET_FLAGS_HOP_MASK 0x07
#define PACKET_FLAGS_WANT_ACK_MASK 0x08
/**
* This structure has to exactly match the wire layout when sent over the radio link. Used to keep compatibility
* wtih the old radiohead implementation.
*/
typedef struct {
uint8_t to, from, id;
/**
* Usage of flags:
*
* The bottom three bits of flags are use to store hop_limit when sent over the wire.
**/
uint8_t flags;
} PacketHeader;
typedef enum {
Bw125Cr45Sf128 = 0, ///< Bw = 125 kHz, Cr = 4/5, Sf = 128chips/symbol, CRC on. Default medium range
Bw500Cr45Sf128, ///< Bw = 500 kHz, Cr = 4/5, Sf = 128chips/symbol, CRC on. Fast+short range
Bw31_25Cr48Sf512, ///< Bw = 31.25 kHz, Cr = 4/8, Sf = 512chips/symbol, CRC on. Slow+long range
Bw125Cr48Sf4096, ///< Bw = 125 kHz, Cr = 4/8, Sf = 4096chips/symbol, CRC on. Slow+long range
} ModemConfigChoice;
/**
* Basic operations all radio chipsets must implement.
*
* This defines the SOLE API for talking to radios (because soon we will have alternate radio implementations)
*/
class RadioInterface : protected NotifiedWorkerThread
{
friend class MeshRadio; // for debugging we let that class touch pool
PointerQueue<MeshPacket> *rxDest = NULL;
CallbackObserver<RadioInterface, void *> configChangedObserver =
CallbackObserver<RadioInterface, void *>(this, &RadioInterface::reloadConfig);
CallbackObserver<RadioInterface, void *> preflightSleepObserver =
CallbackObserver<RadioInterface, void *>(this, &RadioInterface::preflightSleepCb);
CallbackObserver<RadioInterface, void *> notifyDeepSleepObserver =
CallbackObserver<RadioInterface, void *>(this, &RadioInterface::notifyDeepSleepDb);
protected:
MeshPacket *sendingPacket = NULL; // The packet we are currently sending
PointerQueue<MeshPacket> txQueue;
uint32_t lastTxStart = 0L;
/**
* A temporary buffer used for sending/receving packets, sized to hold the biggest buffer we might need
* */
uint8_t radiobuf[MAX_RHPACKETLEN];
/**
* Enqueue a received packet for the registered receiver
*/
void deliverToReceiver(MeshPacket *p);
public:
float freq = 915.0; // FIXME, init all these params from user setings
int8_t power = 17;
ModemConfigChoice modemConfig;
/** 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
*/
RadioInterface();
/**
* Set where to deliver received packets. This method should only be used by the Router class
*/
void setReceiver(PointerQueue<MeshPacket> *_rxDest) { rxDest = _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.
*/
virtual bool canSleep() { return true; }
/// Prepare hardware for sleep. Call this _only_ for deep sleep, not needed for light sleep.
virtual bool sleep() { return true; }
/**
* 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.
* If the txmit queue is full it might return an error
*/
virtual ErrorCode send(MeshPacket *p) = 0;
// methods from radiohead
/// Initialise the Driver transport hardware and software.
/// Make sure the Driver is properly configured before calling init().
/// \return true if initialisation succeeded.
virtual bool init();
/// Apply any radio provisioning changes
/// Make sure the Driver is properly configured before calling init().
/// \return true if initialisation succeeded.
virtual bool reconfigure() = 0;
protected:
/***
* given a packet set sendingPacket and decode the protobufs into radiobuf. Returns # of bytes to send (including the
* PacketHeader & payload).
*
* Used as the first step of
*/
size_t beginSending(MeshPacket *p);
virtual void loop() {} // Idle processing
/**
* Convert our modemConfig enum into wf, sf, etc...
*
* These paramaters will be pull from the channelSettings global
*/
virtual void applyModemConfig();
private:
/// Return 0 if sleep is okay
int preflightSleepCb(void *unused = NULL) { return canSleep() ? 0 : 1; }
int notifyDeepSleepDb(void *unused = NULL)
{
sleep();
return 0;
}
int reloadConfig(void *unused)
{
reconfigure();
return 0;
}
};
class SimRadio : public RadioInterface
{
public:
virtual ErrorCode send(MeshPacket *p);
// methods from radiohead
/// Initialise the Driver transport hardware and software.
/// Make sure the Driver is properly configured before calling init().
/// \return true if initialisation succeeded.
virtual bool init() { return true; }
};

View File

@@ -0,0 +1,328 @@
#include "RadioLibInterface.h"
#include "MeshTypes.h"
#include "OSTimer.h"
#include "mesh-pb-constants.h"
#include <configuration.h>
#include <pb_decode.h>
#include <pb_encode.h>
// FIXME, we default to 4MHz SPI, SPI mode 0, check if the datasheet says it can really do that
static SPISettings spiSettings(4000000, MSBFIRST, SPI_MODE0);
RadioLibInterface::RadioLibInterface(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, RADIOLIB_PIN_TYPE busy,
SPIClass &spi, PhysicalLayer *_iface)
: module(cs, irq, rst, busy, spi, spiSettings), iface(_iface)
{
assert(!instance); // We assume only one for now
instance = this;
}
#ifndef NO_ESP32
// ESP32 doesn't use that flag
#define YIELD_FROM_ISR(x) portYIELD_FROM_ISR()
#else
#define YIELD_FROM_ISR(x) portYIELD_FROM_ISR(x)
#endif
void INTERRUPT_ATTR RadioLibInterface::isrLevel0Common(PendingISR cause)
{
instance->disableInterrupt();
instance->pending = cause;
BaseType_t xHigherPriorityTaskWoken;
instance->notifyFromISR(&xHigherPriorityTaskWoken, cause, eSetValueWithOverwrite);
/* Force a context switch if xHigherPriorityTaskWoken is now set to pdTRUE.
The macro used to do this is dependent on the port and may be called
portEND_SWITCHING_ISR. */
YIELD_FROM_ISR(xHigherPriorityTaskWoken);
}
void INTERRUPT_ATTR RadioLibInterface::isrRxLevel0()
{
isrLevel0Common(ISR_RX);
}
void INTERRUPT_ATTR RadioLibInterface::isrTxLevel0()
{
isrLevel0Common(ISR_TX);
}
/** Our ISR code currently needs this to find our active instance
*/
RadioLibInterface *RadioLibInterface::instance;
/**
* Convert our modemConfig enum into wf, sf, etc...
*/
void RadioLibInterface::applyModemConfig()
{
RadioInterface::applyModemConfig();
switch (modemConfig) {
case Bw125Cr45Sf128: ///< Bw = 125 kHz, Cr = 4/5, Sf = 128chips/symbol, CRC on. Default medium range
bw = 125;
cr = 5;
sf = 7;
break;
case Bw500Cr45Sf128: ///< Bw = 500 kHz, Cr = 4/5, Sf = 128chips/symbol, CRC on. Fast+short range
bw = 500;
cr = 5;
sf = 7;
break;
case Bw31_25Cr48Sf512: ///< Bw = 31.25 kHz, Cr = 4/8, Sf = 512chips/symbol, CRC on. Slow+long range
bw = 31.25;
cr = 8;
sf = 9;
break;
case Bw125Cr48Sf4096:
bw = 125;
cr = 8;
sf = 12;
break;
default:
assert(0); // Unknown enum
}
}
/** Could we send right now (i.e. either not actively receving or transmitting)? */
bool RadioLibInterface::canSendImmediately()
{
// 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.
bool busyTx = sendingPacket != NULL;
bool busyRx = isReceiving && isActivelyReceiving();
if (busyTx || busyRx) {
if (busyTx)
DEBUG_MSG("Can not send yet, busyTx\n");
if (busyRx)
DEBUG_MSG("Can not send yet, busyRx\n");
return false;
} else
return true;
}
/// 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
ErrorCode RadioLibInterface::send(MeshPacket *p)
{
DEBUG_MSG("enqueuing for send on mesh fr=0x%x,to=0x%x,id=%d (txGood=%d,rxGood=%d,rxBad=%d)\n", p->from, p->to, p->id, txGood,
rxGood, rxBad);
ErrorCode res = txQueue.enqueue(p, 0) ? ERRNO_OK : ERRNO_UNKNOWN;
if (res != ERRNO_OK) { // we weren't able to queue it, so we must drop it to prevent leaks
packetPool.release(p);
return res;
}
// We want all sending/receiving to be done by our daemon thread, We use a delay here because this packet might have been sent
// in response to a packet we just received. So we want to make sure the other side has had a chance to reconfigure its radio
startTransmitTimer(true);
return res;
}
bool RadioLibInterface::canSleep()
{
bool res = txQueue.isEmpty();
if (!res) // only print debug messages if we are vetoing sleep
DEBUG_MSG("radio wait to sleep, txEmpty=%d\n", txQueue.isEmpty());
return res;
}
/** At the low end we want to pick a delay large enough that anyone who just completed sending (some other node)
* has had enough time to switch their radio back into receive mode.
*/
#define MIN_TX_WAIT_MSEC 100
/**
* At the high end, this value is used to spread node attempts across time so when they are replying to a packet
* they don't both check that the airwaves are clear at the same moment. As long as they are off by some amount
* one of the two will be first to start transmitting and the other will see that. I bet 500ms is more than enough
* to guarantee this.
*/
#define MAX_TX_WAIT_MSEC 2000 // stress test would still fail occasionally with 1000
/** radio helper thread callback.
We never immediately transmit after any operation (either rx or tx). Instead we should start receiving and
wait a random delay of 50 to 200 ms to make sure we are not stomping on someone else. The 50ms delay at the beginning ensures all
possible listeners have had time to finish processing the previous packet and now have their radio in RX state. The up to 200ms
random delay gives a chance for all possible senders to have high odds of detecting that someone else started transmitting first
and then they will wait until that packet finishes.
NOTE: the large flood rebroadcast delay might still be needed even with this approach. Because we might not be able to hear other
transmitters that we are potentially stomping on. Requires further thought.
FIXME, the MIN_TX_WAIT_MSEC and MAX_TX_WAIT_MSEC values should be tuned via logic analyzer later.
*/
void RadioLibInterface::loop()
{
pending = ISR_NONE;
switch (notification) {
case ISR_TX:
handleTransmitInterrupt();
startReceive();
startTransmitTimer();
break;
case ISR_RX:
handleReceiveInterrupt();
startReceive();
startTransmitTimer();
break;
case TRANSMIT_DELAY_COMPLETED:
// If we are not currently in receive mode, then restart the timer and try again later (this can happen if the main thread
// has placed the unit into standby) FIXME, how will this work if the chipset is in sleep mode?
if (!txQueue.isEmpty()) {
if (!canSendImmediately()) {
startTransmitTimer(); // try again in a little while
} else {
// Send any outgoing packets we have ready
MeshPacket *txp = txQueue.dequeuePtr(0);
assert(txp);
startSend(txp);
}
}
break;
default:
assert(0); // We expected to receive a valid notification from the ISR
}
}
#ifndef NO_ESP32
#define USE_HW_TIMER
#else
// Not needed on NRF52
#define IRAM_ATTR
#endif
void IRAM_ATTR RadioLibInterface::timerCallback(void *p1, uint32_t p2)
{
RadioLibInterface *t = (RadioLibInterface *)p1;
t->timerRunning = false;
// We use without overwrite, so that if there is already an interrupt pending to be handled, that gets handle properly (the
// ISR handler will restart our timer)
#ifndef USE_HW_TIMER
t->notify(TRANSMIT_DELAY_COMPLETED, eSetValueWithoutOverwrite);
#else
BaseType_t xHigherPriorityTaskWoken;
instance->notifyFromISR(&xHigherPriorityTaskWoken, TRANSMIT_DELAY_COMPLETED, eSetValueWithoutOverwrite);
/* Force a context switch if xHigherPriorityTaskWoken is now set to pdTRUE.
The macro used to do this is dependent on the port and may be called
portEND_SWITCHING_ISR. */
YIELD_FROM_ISR(xHigherPriorityTaskWoken);
#endif
}
void RadioLibInterface::startTransmitTimer(bool withDelay)
{
// If we have work to do and the timer wasn't already scheduled, schedule it now
if (!timerRunning && !txQueue.isEmpty()) {
timerRunning = true;
uint32_t delay =
!withDelay ? 0 : random(MIN_TX_WAIT_MSEC, MAX_TX_WAIT_MSEC); // See documentation for loop() wrt these values
// DEBUG_MSG("xmit timer %d\n", delay);
#ifdef USE_HW_TIMER
bool okay = scheduleHWCallback(timerCallback, this, 0, delay);
#else
bool okay = scheduleOSCallback(timerCallback, this, 0, delay);
#endif
assert(okay);
}
}
void RadioLibInterface::handleTransmitInterrupt()
{
// DEBUG_MSG("handling lora TX interrupt\n");
assert(sendingPacket); // Were we sending? - FIXME, this was null coming out of light sleep due to RF95 ISR!
completeSending();
}
void RadioLibInterface::completeSending()
{
if (sendingPacket) {
txGood++;
DEBUG_MSG("Completed sending to=0x%x, id=%u\n", sendingPacket->to, sendingPacket->id);
// We are done sending that packet, release it
packetPool.release(sendingPacket);
sendingPacket = NULL;
// DEBUG_MSG("Done with send\n");
}
}
void RadioLibInterface::handleReceiveInterrupt()
{
assert(isReceiving);
isReceiving = false;
// read the number of actually received bytes
size_t length = iface->getPacketLength();
int state = iface->readData(radiobuf, length);
if (state != ERR_NONE) {
DEBUG_MSG("ignoring received packet due to error=%d\n", state);
rxBad++;
} else {
// Skip the 4 headers that are at the beginning of the rxBuf
int32_t payloadLen = length - sizeof(PacketHeader);
const uint8_t *payload = radiobuf + sizeof(PacketHeader);
// check for short packets
if (payloadLen < 0) {
DEBUG_MSG("ignoring received packet too short\n");
rxBad++;
} else {
const PacketHeader *h = (PacketHeader *)radiobuf;
rxGood++;
// Note: we deliver _all_ packets to our router (i.e. our interface is intentionally promiscuous).
// This allows the router and other apps on our node to sniff packets (usually routing) between other
// nodes.
MeshPacket *mp = packetPool.allocZeroed();
mp->from = h->from;
mp->to = h->to;
mp->id = h->id;
assert(HOP_MAX <= PACKET_FLAGS_HOP_MASK); // If hopmax changes, carefully check this code
mp->hop_limit = h->flags & PACKET_FLAGS_HOP_MASK;
mp->want_ack = !!(h->flags & PACKET_FLAGS_WANT_ACK_MASK);
addReceiveMetadata(mp);
mp->which_payload = MeshPacket_encrypted_tag; // Mark that the payload is still encrypted at this point
assert(payloadLen <= sizeof(mp->encrypted.bytes));
memcpy(mp->encrypted.bytes, payload, payloadLen);
mp->encrypted.size = payloadLen;
DEBUG_MSG("Lora RX interrupt from=0x%x, id=%u\n", mp->from, mp->id);
deliverToReceiver(mp);
}
}
}
/** start an immediate transmit */
void RadioLibInterface::startSend(MeshPacket *txp)
{
DEBUG_MSG("Starting low level send from=0x%x, to=0x%x, id=%u, want_ack=%d\n", txp->from, txp->to, txp->id, txp->want_ack);
setStandby(); // Cancel any already in process receives
size_t numbytes = beginSending(txp);
int res = iface->startTransmit(radiobuf, numbytes);
assert(res == ERR_NONE);
// Must be done AFTER, starting transmit, because startTransmit clears (possibly stale) interrupt pending register bits
enableInterrupt(isrTxLevel0);
}

View File

@@ -0,0 +1,138 @@
#pragma once
#include "RadioInterface.h"
#include <RadioLib.h>
// ESP32 has special rules about ISR code
#ifdef ARDUINO_ARCH_ESP32
#define INTERRUPT_ATTR IRAM_ATTR
#else
#define INTERRUPT_ATTR
#endif
class RadioLibInterface : public RadioInterface
{
/// Used as our notification from the ISR
enum PendingISR { ISR_NONE = 0, ISR_RX, ISR_TX, TRANSMIT_DELAY_COMPLETED };
volatile PendingISR pending = ISR_NONE;
volatile bool timerRunning = false;
/**
* Raw ISR handler that just calls our polymorphic method
*/
static void isrTxLevel0(), isrLevel0Common(PendingISR code);
/**
* Debugging counts
*/
uint32_t rxBad = 0, rxGood = 0, txGood = 0;
protected:
float bw = 125;
uint8_t sf = 9;
uint8_t cr = 7;
/**
* FIXME, use a meshtastic sync word, but hashed with the Channel name. Currently picking the same default
* the RF95 used (0x14). Note: do not use 0x34 - that is reserved for lorawan
*/
uint8_t syncWord = SX126X_SYNC_WORD_PRIVATE;
float currentLimit = 100; // FIXME
uint16_t preambleLength = 32; // 8 is default, but FIXME use longer to increase the amount of sleep time when receiving
Module module; // The HW interface to the radio
/**
* provides lowest common denominator RadioLib API
*/
PhysicalLayer *iface;
/// are _trying_ to receive a packet currently (note - we might just be waiting for one)
bool isReceiving;
public:
/** Our ISR code currently needs this to find our active instance
*/
static RadioLibInterface *instance;
/**
* Glue functions called from ISR land
*/
virtual void disableInterrupt() = 0;
/**
* Enable a particular ISR callback glue function
*/
virtual void enableInterrupt(void (*)()) = 0;
public:
RadioLibInterface(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, RADIOLIB_PIN_TYPE busy, SPIClass &spi,
PhysicalLayer *iface = NULL);
virtual ErrorCode send(MeshPacket *p);
/**
* 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.
*/
virtual bool canSleep();
/**
* Start waiting to receive a message
*
* External functions can call this method to wake the device from sleep.
*/
virtual void startReceive() = 0;
private:
/** start an immediate transmit */
void startSend(MeshPacket *txp);
/** if we have something waiting to send, start a short random timer so we can come check for collision before actually doing
* the transmit
*
* If the timer was already running, we just wait for that one to occur.
* */
void startTransmitTimer(bool withDelay = true);
void handleTransmitInterrupt();
void handleReceiveInterrupt();
static void timerCallback(void *p1, uint32_t p2);
protected:
/**
* Convert our modemConfig enum into wf, sf, etc...
*
* These paramaters will be pull from the channelSettings global
*/
virtual void applyModemConfig();
/** Could we send right now (i.e. either not actively receiving or transmitting)? */
virtual bool canSendImmediately();
/** are we actively receiving a packet (only called during receiving state) */
virtual bool isActivelyReceiving() = 0;
/**
* Raw ISR handler that just calls our polymorphic method
*/
static void isrRxLevel0();
/**
* If a send was in progress finish it and return the buffer to the pool */
void completeSending();
/**
* Add SNR data to received messages
*/
virtual void addReceiveMetadata(MeshPacket *mp) = 0;
virtual void loop(); // Idle processing
virtual void setStandby() = 0;
};

68
src/mesh/RadioLibRF95.cpp Normal file
View File

@@ -0,0 +1,68 @@
#include "RadioLibRF95.h"
#define RF95_CHIP_VERSION 0x12
#define RF95_ALT_VERSION 0x11 // Supposedly some versions of the chip have id 0x11
RadioLibRF95::RadioLibRF95(Module *mod) : SX1278(mod) {}
int16_t RadioLibRF95::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint8_t currentLimit,
uint16_t preambleLength, uint8_t gain)
{
// execute common part
int16_t state = SX127x::begin(RF95_CHIP_VERSION, syncWord, currentLimit, preambleLength);
if (state != ERR_NONE)
state = SX127x::begin(RF95_ALT_VERSION, syncWord, currentLimit, preambleLength);
RADIOLIB_ASSERT(state);
// configure settings not accessible by API
state = config();
RADIOLIB_ASSERT(state);
// configure publicly accessible settings
state = setFrequency(freq);
RADIOLIB_ASSERT(state);
state = setBandwidth(bw);
RADIOLIB_ASSERT(state);
state = setSpreadingFactor(sf);
RADIOLIB_ASSERT(state);
state = setCodingRate(cr);
RADIOLIB_ASSERT(state);
state = setOutputPower(power);
RADIOLIB_ASSERT(state);
state = setGain(gain);
return (state);
}
int16_t RadioLibRF95::setFrequency(float freq)
{
// RADIOLIB_CHECK_RANGE(freq, 862.0, 1020.0, ERR_INVALID_FREQUENCY);
// set frequency
return (SX127x::setFrequencyRaw(freq));
}
#define RH_RF95_MODEM_STATUS_CLEAR 0x10
#define RH_RF95_MODEM_STATUS_HEADER_INFO_VALID 0x08
#define RH_RF95_MODEM_STATUS_RX_ONGOING 0x04
#define RH_RF95_MODEM_STATUS_SIGNAL_SYNCHRONIZED 0x02
#define RH_RF95_MODEM_STATUS_SIGNAL_DETECTED 0x01
bool RadioLibRF95::isReceiving()
{
// 0x0b == Look for header info valid, signal synchronized or signal detected
uint8_t reg = readReg(SX127X_REG_MODEM_STAT);
// Serial.printf("reg %x\n", reg);
return (reg & (RH_RF95_MODEM_STATUS_SIGNAL_DETECTED | RH_RF95_MODEM_STATUS_SIGNAL_SYNCHRONIZED |
RH_RF95_MODEM_STATUS_HEADER_INFO_VALID)) != 0;
}
uint8_t RadioLibRF95::readReg(uint8_t addr)
{
return _mod->SPIreadRegister(addr);
}

73
src/mesh/RadioLibRF95.h Normal file
View File

@@ -0,0 +1,73 @@
#pragma once
#include <RadioLib.h>
/*!
\class RFM95
\brief Derived class for %RFM95 modules. Overrides some methods from SX1278 due to different parameter ranges.
*/
class RadioLibRF95: public SX1278 {
public:
// constructor
/*!
\brief Default constructor. Called from Arduino sketch when creating new LoRa instance.
\param mod Instance of Module that will be used to communicate with the %LoRa chip.
*/
RadioLibRF95(Module* mod);
// basic methods
/*!
\brief %LoRa modem initialization method. Must be called at least once from Arduino sketch to initialize the module.
\param freq Carrier frequency in MHz. Allowed values range from 868.0 MHz to 915.0 MHz.
\param bw %LoRa link bandwidth in kHz. Allowed values are 10.4, 15.6, 20.8, 31.25, 41.7, 62.5, 125, 250 and 500 kHz.
\param sf %LoRa link spreading factor. Allowed values range from 6 to 12.
\param cr %LoRa link coding rate denominator. Allowed values range from 5 to 8.
\param syncWord %LoRa sync word. Can be used to distinguish different networks. Note that value 0x34 is reserved for LoRaWAN networks.
\param power Transmission output power in dBm. Allowed values range from 2 to 17 dBm.
\param currentLimit Trim value for OCP (over current protection) in mA. Can be set to multiplies of 5 in range 45 to 120 mA and to multiples of 10 in range 120 to 240 mA.
Set to 0 to disable OCP (not recommended).
\param preambleLength Length of %LoRa transmission preamble in symbols. The actual preamble length is 4.25 symbols longer than the set number.
Allowed values range from 6 to 65535.
\param gain Gain of receiver LNA (low-noise amplifier). Can be set to any integer in range 1 to 6 where 1 is the highest gain.
Set to 0 to enable automatic gain control (recommended).
\returns \ref status_codes
*/
int16_t begin(float freq = 915.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, uint8_t syncWord = SX127X_SYNC_WORD, int8_t power = 17, uint8_t currentLimit = 100, uint16_t preambleLength = 8, uint8_t gain = 0);
// configuration methods
/*!
\brief Sets carrier frequency. Allowed values range from 868.0 MHz to 915.0 MHz.
\param freq Carrier frequency to be set in MHz.
\returns \ref status_codes
*/
int16_t setFrequency(float freq);
// Return true if we are actively receiving a message currently
bool isReceiving();
/// For debugging
uint8_t readReg(uint8_t addr);
#ifndef RADIOLIB_GODMODE
private:
#endif
};

178
src/mesh/ReliableRouter.cpp Normal file
View File

@@ -0,0 +1,178 @@
#include "ReliableRouter.h"
#include "MeshTypes.h"
#include "configuration.h"
#include "mesh-pb-constants.h"
// ReliableRouter::ReliableRouter() {}
/**
* If the message is want_ack, then add it to a list of packets to retransmit.
* If we run out of retransmissions, send a nak packet towards the original client to indicate failure.
*/
ErrorCode ReliableRouter::send(MeshPacket *p)
{
if (p->want_ack) {
// If someone asks for acks on broadcast, we need the hop limit to be at least one, so that first node that receives our
// message will rebroadcast
if (p->to == NODENUM_BROADCAST && p->hop_limit == 0)
p->hop_limit = 1;
auto copy = packetPool.allocCopy(*p);
startRetransmission(copy);
}
return FloodingRouter::send(p);
}
/**
* If we receive a want_ack packet (do not check for wasSeenRecently), send back an ack (this might generate multiple ack sends in
* case the our first ack gets lost)
*
* If we receive an ack packet (do check wasSeenRecently), clear out any retransmissions and
* forward the ack to the application layer.
*
* If we receive a nak packet (do check wasSeenRecently), clear out any retransmissions
* and forward the nak to the application layer.
*
* Otherwise, let superclass handle it.
*/
void ReliableRouter::handleReceived(MeshPacket *p)
{
NodeNum ourNode = getNodeNum();
if (p->from == ourNode && p->to == NODENUM_BROADCAST) {
DEBUG_MSG("Received someone rebroadcasting for us fr=0x%x,to=0x%x,id=%d\n", p->from, p->to, p->id);
// We are seeing someone rebroadcast one of our broadcast attempts.
// If this is the first time we saw this, cancel any retransmissions we have queued up and generate an internal ack for
// the original sending process.
if (stopRetransmission(p->from, p->id)) {
DEBUG_MSG("Someone is retransmitting for us, generate implicit ack\n");
sendAckNak(true, p->from, p->id);
}
} else if (p->to == ourNode) { // ignore ack/nak/want_ack packets that are not address to us (for now)
if (p->want_ack) {
sendAckNak(true, p->from, p->id);
}
if (perhapsDecode(p)) {
// If the payload is valid, look for ack/nak
PacketId ackId = p->decoded.which_ack == SubPacket_success_id_tag ? p->decoded.ack.success_id : 0;
PacketId nakId = p->decoded.which_ack == SubPacket_fail_id_tag ? p->decoded.ack.fail_id : 0;
// we are careful to only read/update wasSeenRecently _after_ confirming this is an ack (to not mess
// up broadcasts)
if ((ackId || nakId) && !wasSeenRecently(p, false)) {
if (ackId) {
DEBUG_MSG("Received a ack=%d, stopping retransmissions\n", ackId);
stopRetransmission(p->to, ackId);
} else {
DEBUG_MSG("Received a nak=%d, stopping retransmissions\n", nakId);
stopRetransmission(p->to, nakId);
}
}
}
}
// handle the packet as normal
FloodingRouter::handleReceived(p);
}
/**
* Send an ack or a nak packet back towards whoever sent idFrom
*/
void ReliableRouter::sendAckNak(bool isAck, NodeNum to, PacketId idFrom)
{
auto p = allocForSending();
p->hop_limit = 0; // Assume just immediate neighbors for now
p->to = to;
DEBUG_MSG("Sending an ack=0x%x,to=0x%x,idFrom=%d,id=%d\n", isAck, to, idFrom, p->id);
if (isAck) {
p->decoded.ack.success_id = idFrom;
p->decoded.which_ack = SubPacket_success_id_tag;
} else {
p->decoded.ack.fail_id = idFrom;
p->decoded.which_ack = SubPacket_fail_id_tag;
}
sendLocal(p); // we sometimes send directly to the local node
}
#define NUM_RETRANSMISSIONS 3
PendingPacket::PendingPacket(MeshPacket *p)
{
packet = p;
numRetransmissions = NUM_RETRANSMISSIONS - 1; // We subtract one, because we assume the user just did the first send
setNextTx();
}
/**
* Stop any retransmissions we are doing of the specified node/packet ID pair
*/
bool ReliableRouter::stopRetransmission(NodeNum from, PacketId id)
{
auto key = GlobalPacketId(from, id);
return stopRetransmission(key);
}
bool ReliableRouter::stopRetransmission(GlobalPacketId key)
{
auto old = pending.find(key); // If we have an old record, someone messed up because id got reused
if (old != pending.end()) {
auto numErased = pending.erase(key);
assert(numErased == 1);
packetPool.release(old->second.packet);
return true;
} else
return false;
}
/**
* Add p to the list of packets to retransmit occasionally. We will free it once we stop retransmitting.
*/
void ReliableRouter::startRetransmission(MeshPacket *p)
{
auto id = GlobalPacketId(p);
auto rec = PendingPacket(p);
stopRetransmission(p->from, p->id);
pending[id] = rec;
}
/**
* Do any retransmissions that are scheduled (FIXME - for the time being called from loop)
*/
void ReliableRouter::doRetransmissions()
{
uint32_t now = millis();
// FIXME, we should use a better datastructure rather than walking through this map.
// for(auto el: pending) {
for (auto it = pending.begin(), nextIt = it; it != pending.end(); it = nextIt) {
++nextIt; // we use this odd pattern because we might be deleting it...
auto &p = it->second;
// FIXME, handle 51 day rolloever here!!!
if (p.nextTxMsec <= now) {
if (p.numRetransmissions == 0) {
DEBUG_MSG("Reliable send failed, returning a nak fr=0x%x,to=0x%x,id=%d\n", p.packet->from, p.packet->to,
p.packet->id);
sendAckNak(false, p.packet->from, p.packet->id);
stopRetransmission(it->first);
} else {
DEBUG_MSG("Sending reliable retransmission fr=0x%x,to=0x%x,id=%d, tries left=%d\n", p.packet->from, p.packet->to,
p.packet->id, p.numRetransmissions);
// Note: we call the superclass version because we don't want to have our version of send() add a new
// retransmission record
FloodingRouter::send(packetPool.allocCopy(*p.packet));
// Queue again
--p.numRetransmissions;
p.setNextTx();
}
}
}
}

122
src/mesh/ReliableRouter.h Normal file
View File

@@ -0,0 +1,122 @@
#pragma once
#include "FloodingRouter.h"
#include "PeriodicTask.h"
#include <unordered_map>
/**
* An identifier for a globalally unique message - a pair of the sending nodenum and the packet id assigned
* to that message
*/
struct GlobalPacketId {
NodeNum node;
PacketId id;
bool operator==(const GlobalPacketId &p) const { return node == p.node && id == p.id; }
GlobalPacketId(const MeshPacket *p)
{
node = p->from;
id = p->id;
}
GlobalPacketId(NodeNum _from, PacketId _id)
{
node = _from;
id = _id;
}
};
/**
* A packet queued for retransmission
*/
struct PendingPacket {
MeshPacket *packet;
/** The next time we should try to retransmit this packet */
uint32_t nextTxMsec;
/** Starts at NUM_RETRANSMISSIONS -1(normally 3) and counts down. Once zero it will be removed from the list */
uint8_t numRetransmissions;
/** True if we have started trying to find a route - for DSR usage
* While trying to find a route we don't actually send the data packet. We just leave it here pending until
* we have a route or we've failed to find one.
*/
bool wantRoute = false;
PendingPacket() {}
PendingPacket(MeshPacket *p);
void setNextTx() { nextTxMsec = millis() + random(20 * 1000, 22 * 1000); }
};
class GlobalPacketIdHashFunction
{
public:
size_t operator()(const GlobalPacketId &p) const { return (hash<NodeNum>()(p.node)) ^ (hash<PacketId>()(p.id)); }
};
/**
* This is a mixin that extends Router with the ability to do (one hop only) reliable message sends.
*/
class ReliableRouter : public FloodingRouter
{
private:
unordered_map<GlobalPacketId, PendingPacket, GlobalPacketIdHashFunction> pending;
public:
/**
* Constructor
*
*/
// ReliableRouter();
/**
* Send a packet on a suitable interface. This routine will
* later free() the packet to pool. This routine is not allowed to stall.
* If the txmit queue is full it might return an error
*/
virtual ErrorCode send(MeshPacket *p);
/** Do our retransmission handling */
virtual void loop()
{
doRetransmissions();
FloodingRouter::loop();
}
protected:
/**
* Called from loop()
* Handle any packet that is received by an interface on this node.
* Note: some packets may merely being passed through this node and will be forwarded elsewhere.
*
* Note: this method will free the provided packet
*/
virtual void handleReceived(MeshPacket *p);
private:
/**
* Send an ack or a nak packet back towards whoever sent idFrom
*/
void sendAckNak(bool isAck, NodeNum to, PacketId idFrom);
/**
* Stop any retransmissions we are doing of the specified node/packet ID pair
*
* @return true if we found and removed a transmission with this ID
*/
bool stopRetransmission(NodeNum from, PacketId id);
bool stopRetransmission(GlobalPacketId p);
/**
* Add p to the list of packets to retransmit occasionally. We will free it once we stop retransmitting.
*/
void startRetransmission(MeshPacket *p);
/**
* Do any retransmissions that are scheduled (FIXME - for the time being called from loop)
*/
void doRetransmissions();
};

196
src/mesh/Router.cpp Normal file
View File

@@ -0,0 +1,196 @@
#include "Router.h"
#include "CryptoEngine.h"
#include "GPS.h"
#include "configuration.h"
#include "mesh-pb-constants.h"
#include <NodeDB.h>
/**
* Router todo
*
* DONE: Implement basic interface and use it elsewhere in app
* Add naive flooding mixin (& drop duplicate rx broadcasts), add tools for sending broadcasts with incrementing sequence #s
* Add an optional adjacent node only 'send with ack' mixin. If we timeout waiting for the ack, call handleAckTimeout(packet)
* Add DSR mixin
*
**/
#define MAX_RX_FROMRADIO \
4 // max number of packets destined to our queue, we dispatch packets quickly so it doesn't need to be big
// I think this is right, one packet for each of the three fifos + one packet being currently assembled for TX or RX
#define MAX_PACKETS \
(MAX_RX_TOPHONE + MAX_RX_FROMRADIO + MAX_TX_QUEUE + \
2) // max number of packets which can be in flight (either queued from reception or queued for sending)
MemoryPool<MeshPacket> packetPool(MAX_PACKETS);
/**
* Constructor
*
* Currently we only allow one interface, that may change in the future
*/
Router::Router() : fromRadioQueue(MAX_RX_FROMRADIO) {}
/**
* do idle processing
* Mostly looking in our incoming rxPacket queue and calling handleReceived.
*/
void Router::loop()
{
MeshPacket *mp;
while ((mp = fromRadioQueue.dequeuePtr(0)) != NULL) {
handleReceived(mp);
}
}
#define NUM_PACKET_ID 255 // 0 is consider invalid
/// Generate a unique packet id
// FIXME, move this someplace better
PacketId generatePacketId()
{
static uint32_t i; // Note: trying to keep this in noinit didn't help for working across reboots
static bool didInit = false;
if (!didInit) {
didInit = true;
i = random(0, NUM_PACKET_ID +
1); // pick a random initial sequence number at boot (to prevent repeated reboots always starting at 0)
}
i++;
return (i % NUM_PACKET_ID) + 1; // return number between 1 and 255
}
MeshPacket *Router::allocForSending()
{
MeshPacket *p = packetPool.allocZeroed();
p->which_payload = MeshPacket_decoded_tag; // Assume payload is decoded at start.
p->from = nodeDB.getNodeNum();
p->to = NODENUM_BROADCAST;
p->hop_limit = HOP_RELIABLE;
p->id = generatePacketId();
p->rx_time = getValidTime(); // Just in case we process the packet locally - make sure it has a valid timestamp
return p;
}
ErrorCode Router::sendLocal(MeshPacket *p)
{
if (p->to == nodeDB.getNodeNum()) {
DEBUG_MSG("Enqueuing internal message for the receive queue\n");
fromRadioQueue.enqueue(p);
return ERRNO_OK;
} else
return send(p);
}
/**
* Send a packet on a suitable interface. This routine will
* later free() the packet to pool. This routine is not allowed to stall.
* If the txmit queue is full it might return an error.
*/
ErrorCode Router::send(MeshPacket *p)
{
assert(p->to != nodeDB.getNodeNum()); // should have already been handled by sendLocal
// Never set the want_ack flag on broadcast packets sent over the air.
if (p->to == NODENUM_BROADCAST)
p->want_ack = false;
// If the packet hasn't yet been encrypted, do so now (it might already be encrypted if we are just forwarding it)
assert(p->which_payload == MeshPacket_encrypted_tag ||
p->which_payload == MeshPacket_decoded_tag); // I _think_ all packets should have a payload by now
// First convert from protobufs to raw bytes
if (p->which_payload == MeshPacket_decoded_tag) {
static uint8_t bytes[MAX_RHPACKETLEN]; // we have to use a scratch buffer because a union
size_t numbytes = pb_encode_to_bytes(bytes, sizeof(bytes), SubPacket_fields, &p->decoded);
assert(numbytes <= MAX_RHPACKETLEN);
crypto->encrypt(p->from, p->id, numbytes, bytes);
// Copy back into the packet and set the variant type
memcpy(p->encrypted.bytes, bytes, numbytes);
p->encrypted.size = numbytes;
p->which_payload = MeshPacket_encrypted_tag;
}
if (iface) {
// DEBUG_MSG("Sending packet via interface fr=0x%x,to=0x%x,id=%d\n", p->from, p->to, p->id);
return iface->send(p);
} else {
DEBUG_MSG("Dropping packet - no interfaces - fr=0x%x,to=0x%x,id=%d\n", p->from, p->to, p->id);
packetPool.release(p);
return ERRNO_NO_INTERFACES;
}
}
/**
* Every (non duplicate) packet this node receives will be passed through this method. This allows subclasses to
* update routing tables etc... based on what we overhear (even for messages not destined to our node)
*/
void Router::sniffReceived(const MeshPacket *p)
{
DEBUG_MSG("FIXME-update-db Sniffing packet fr=0x%x,to=0x%x,id=%d\n", p->from, p->to, p->id);
}
bool Router::perhapsDecode(MeshPacket *p)
{
if (p->which_payload == MeshPacket_decoded_tag)
return true; // If packet was already decoded just return
assert(p->which_payload == MeshPacket_encrypted_tag);
// FIXME - someday don't send routing packets encrypted. That would allow us to route for other channels without
// being able to decrypt their data.
// Try to decrypt the packet if we can
static uint8_t bytes[MAX_RHPACKETLEN];
memcpy(bytes, p->encrypted.bytes,
p->encrypted.size); // we have to copy into a scratch buffer, because these bytes are a union with the decoded protobuf
crypto->decrypt(p->from, p->id, p->encrypted.size, bytes);
// Take those raw bytes and convert them back into a well structured protobuf we can understand
if (!pb_decode_from_bytes(bytes, p->encrypted.size, SubPacket_fields, &p->decoded)) {
DEBUG_MSG("Invalid protobufs in received mesh packet!\n");
return false;
} else {
// parsing was successful
p->which_payload = MeshPacket_decoded_tag;
return true;
}
}
NodeNum Router::getNodeNum()
{
return nodeDB.getNodeNum();
}
/**
* Handle any packet that is received by an interface on this node.
* Note: some packets may merely being passed through this node and will be forwarded elsewhere.
*/
void Router::handleReceived(MeshPacket *p)
{
// FIXME, this class shouldn't EVER need to know about the GPS, move getValidTime() into a non gps dependent function
// Also, we should set the time from the ISR and it should have msec level resolution
p->rx_time = getValidTime(); // store the arrival timestamp for the phone
// Take those raw bytes and convert them back into a well structured protobuf we can understand
if (perhapsDecode(p)) {
// parsing was successful, queue for our recipient
sniffReceived(p);
if (p->to == NODENUM_BROADCAST || p->to == getNodeNum()) {
DEBUG_MSG("Notifying observers of received packet fr=0x%x,to=0x%x,id=%d\n", p->from, p->to, p->id);
notifyPacketReceived.notifyObservers(p);
}
}
packetPool.release(p);
}

View File

@@ -6,7 +6,6 @@
#include "PointerQueue.h"
#include "RadioInterface.h"
#include "mesh.pb.h"
#include <RH_RF95.h>
/**
* A mesh aware router that supports multiple interfaces.
@@ -45,8 +44,21 @@ class Router
* do idle processing
* Mostly looking in our incoming rxPacket queue and calling handleReceived.
*/
void loop();
virtual void loop();
/**
* Works like send, but if we are sending to the local node, we directly put the message in the receive queue
*/
ErrorCode sendLocal(MeshPacket *p);
/// Allocate and return a meshpacket which defaults as send to broadcast from the current node.
MeshPacket *allocForSending();
/**
* @return our local nodenum */
NodeNum getNodeNum();
protected:
/**
* Send a packet on a suitable interface. This routine will
* later free() the packet to pool. This routine is not allowed to stall.
@@ -54,15 +66,32 @@ class Router
*/
virtual ErrorCode send(MeshPacket *p);
protected:
/**
* Called from loop()
* Handle any packet that is received by an interface on this node.
* Note: some packets may merely being passed through this node and will be forwarded elsewhere.
*
* Note: this method will free the provided packet
* Note: this packet will never be called for messages sent/generated by this node.
* Note: this method will free the provided packet.
*/
virtual void handleReceived(MeshPacket *p);
/**
* Every (non duplicate) packet this node receives will be passed through this method. This allows subclasses to
* update routing tables etc... based on what we overhear (even for messages not destined to our node)
*/
virtual void sniffReceived(const MeshPacket *p);
/**
* Remove any encryption and decode the protobufs inside this packet (if necessary).
*
* @return true for success, false for corrupt packet.
*/
bool perhapsDecode(MeshPacket *p);
};
extern Router &router;
extern Router &router;
/// Generate a unique packet id
// FIXME, move this someplace better
PacketId generatePacketId();

View File

@@ -0,0 +1,117 @@
#include "SX1262Interface.h"
#include <configuration.h>
SX1262Interface::SX1262Interface(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, RADIOLIB_PIN_TYPE busy,
SPIClass &spi)
: RadioLibInterface(cs, irq, rst, busy, spi, &lora), lora(&module)
{
}
/// Initialise the Driver transport hardware and software.
/// Make sure the Driver is properly configured before calling init().
/// \return true if initialisation succeeded.
bool SX1262Interface::init()
{
RadioLibInterface::init();
float tcxoVoltage = 0; // None - we use an XTAL
bool useRegulatorLDO = false; // Seems to depend on the connection to pin 9/DCC_SW - if an inductor DCDC?
applyModemConfig();
if (power > 22) // This chip has lower power limits than some
power = 22;
int res = lora.begin(freq, bw, sf, cr, syncWord, power, currentLimit, preambleLength, tcxoVoltage, useRegulatorLDO);
DEBUG_MSG("LORA init result %d\n", res);
if (res == ERR_NONE)
res = lora.setCRC(SX126X_LORA_CRC_ON);
if (res == ERR_NONE)
startReceive(); // start receiving
return res == ERR_NONE;
}
bool SX1262Interface::reconfigure()
{
applyModemConfig();
// set mode to standby
setStandby();
// configure publicly accessible settings
int err = lora.setSpreadingFactor(sf);
assert(err == ERR_NONE);
err = lora.setBandwidth(bw);
assert(err == ERR_NONE);
err = lora.setCodingRate(cr);
assert(err == ERR_NONE);
err = lora.setSyncWord(syncWord);
assert(err == ERR_NONE);
err = lora.setCurrentLimit(currentLimit);
assert(err == ERR_NONE);
err = lora.setPreambleLength(preambleLength);
assert(err == ERR_NONE);
err = lora.setFrequency(freq);
assert(err == ERR_NONE);
if (power > 22) // This chip has lower power limits than some
power = 22;
err = lora.setOutputPower(power);
assert(err == ERR_NONE);
startReceive(); // restart receiving
return ERR_NONE;
}
void SX1262Interface::setStandby()
{
int err = lora.standby();
assert(err == ERR_NONE);
isReceiving = false; // If we were receiving, not any more
disableInterrupt();
completeSending(); // If we were sending, not anymore
}
/**
* Add SNR data to received messages
*/
void SX1262Interface::addReceiveMetadata(MeshPacket *mp)
{
mp->rx_snr = lora.getSNR();
}
void SX1262Interface::startReceive()
{
setStandby();
int err = lora.startReceive();
assert(err == ERR_NONE);
isReceiving = true;
// Must be done AFTER, starting transmit, because startTransmit clears (possibly stale) interrupt pending register bits
enableInterrupt(isrRxLevel0);
}
/** Could we send right now (i.e. either not actively receving or transmitting)? */
bool SX1262Interface::isActivelyReceiving()
{
return lora.getPacketLength() > 0;
}
bool SX1262Interface::sleep()
{
// put chipset into sleep mode
disableInterrupt();
lora.sleep();
return true;
}

View File

@@ -0,0 +1,55 @@
#pragma once
#include "RadioLibInterface.h"
/**
* Our adapter for SX1262 radios
*/
class SX1262Interface : public RadioLibInterface
{
SX1262 lora;
public:
SX1262Interface(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, RADIOLIB_PIN_TYPE busy, SPIClass &spi);
/// Initialise the Driver transport hardware and software.
/// Make sure the Driver is properly configured before calling init().
/// \return true if initialisation succeeded.
virtual bool init();
/// Apply any radio provisioning changes
/// Make sure the Driver is properly configured before calling init().
/// \return true if initialisation succeeded.
virtual bool reconfigure();
/// Prepare hardware for sleep. Call this _only_ for deep sleep, not needed for light sleep.
virtual bool sleep();
protected:
/**
* Glue functions called from ISR land
*/
virtual void INTERRUPT_ATTR disableInterrupt() { lora.clearDio1Action(); }
/**
* Enable a particular ISR callback glue function
*/
virtual void enableInterrupt(void (*callback)()) { lora.setDio1Action(callback); }
/** are we actively receiving a packet (only called during receiving state) */
virtual bool isActivelyReceiving();
/**
* Start waiting to receive a message
*/
virtual void startReceive();
/**
* Add SNR data to received messages
*/
virtual void addReceiveMetadata(MeshPacket *mp);
virtual void setStandby();
private:
};

View File

@@ -1,4 +1,5 @@
#include "StreamAPI.h"
#include "configuration.h"
#define START1 0x94
#define START2 0xc3
@@ -30,7 +31,7 @@ void StreamAPI::readStream()
if (c != START2)
rxPtr = 0; // failed to find framing
} else if (ptr >= HEADER_LEN) { // we have at least read our 4 byte framing
uint16_t len = (rxBuf[2] << 8) + rxBuf[3]; // big endian 16 bit length follows framing
uint32_t len = (rxBuf[2] << 8) + rxBuf[3]; // big endian 16 bit length follows framing
if (ptr == HEADER_LEN) {
// we _just_ finished our 4 byte header, validate length now (note: a length of zero is a valid
@@ -58,14 +59,33 @@ void StreamAPI::writeStream()
do {
// Send every packet we can
len = getFromRadio(txBuf + HEADER_LEN);
if (len != 0) {
txBuf[0] = START1;
txBuf[1] = START2;
txBuf[2] = (len >> 8) & 0xff;
txBuf[3] = len & 0xff;
stream->write(txBuf, len + HEADER_LEN);
}
emitTxBuffer(len);
} while (len);
}
}
/**
* Send the current txBuffer over our stream
*/
void StreamAPI::emitTxBuffer(size_t len)
{
if (len != 0) {
txBuf[0] = START1;
txBuf[1] = START2;
txBuf[2] = (len >> 8) & 0xff;
txBuf[3] = len & 0xff;
stream->write(txBuf, len + HEADER_LEN);
}
}
void StreamAPI::emitRebooted()
{
// In case we send a FromRadio packet
memset(&fromRadioScratch, 0, sizeof(fromRadioScratch));
fromRadioScratch.which_variant = FromRadio_rebooted_tag;
fromRadioScratch.variant.rebooted = true;
DEBUG_MSG("Emitting reboot packet for serial shell\n");
emitTxBuffer(pb_encode_to_bytes(txBuf + HEADER_LEN, FromRadio_size, FromRadio_fields, &fromRadioScratch));
}

View File

@@ -37,8 +37,6 @@ class StreamAPI : public PhoneAPI
uint8_t rxBuf[MAX_STREAM_BUF_SIZE];
size_t rxPtr = 0;
uint8_t txBuf[MAX_STREAM_BUF_SIZE];
public:
StreamAPI(Stream *_stream) : stream(_stream) {}
@@ -61,6 +59,19 @@ class StreamAPI : public PhoneAPI
void writeStream();
protected:
/**
* Send a FromRadio.rebooted = true packet to the phone
*/
void emitRebooted();
/**
* Send the current txBuffer over our stream
*/
void emitTxBuffer(size_t len);
/// Are we allowed to write packets to our output stream (subclasses can turn this off - i.e. SerialConsole)
bool canWrite = true;
/// Subclasses can use this scratch buffer if they wish
uint8_t txBuf[MAX_STREAM_BUF_SIZE];
};

View File

@@ -51,15 +51,10 @@ PB_BIND(FromRadio, FromRadio, 2)
PB_BIND(ToRadio, ToRadio, 2)
PB_BIND(ManufacturingData, ManufacturingData, AUTO)
#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.
* to define PB_CONVERT_DOUBLE_FLOAT in pb.h or compiler command line.
*/
PB_STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)
#endif

View File

@@ -32,14 +32,11 @@ typedef enum _ChannelSettings_ModemConfig {
} ChannelSettings_ModemConfig;
/* Struct definitions */
typedef struct _RouteDiscovery {
pb_callback_t route;
} RouteDiscovery;
typedef PB_BYTES_ARRAY_T(32) ChannelSettings_psk_t;
typedef struct _ChannelSettings {
int32_t tx_power;
ChannelSettings_ModemConfig modem_config;
pb_byte_t psk[16];
ChannelSettings_psk_t psk;
char name[12];
} ChannelSettings;
@@ -53,6 +50,13 @@ typedef struct _DebugString {
char message[256];
} DebugString;
typedef struct _ManufacturingData {
uint32_t fradioFreq;
pb_callback_t hw_model;
pb_callback_t hw_version;
int32_t selftest_result;
} ManufacturingData;
typedef struct _MyNodeInfo {
int32_t my_node_num;
bool has_gps;
@@ -66,10 +70,10 @@ typedef struct _MyNodeInfo {
} MyNodeInfo;
typedef struct _Position {
double latitude;
double longitude;
int32_t altitude;
int32_t battery_level;
int32_t latitude_i;
int32_t longitude_i;
uint32_t time;
} Position;
@@ -89,6 +93,11 @@ typedef struct _RadioConfig_UserPreferences {
bool promiscuous_mode;
} RadioConfig_UserPreferences;
typedef struct _RouteDiscovery {
pb_size_t route_count;
int32_t route[8];
} RouteDiscovery;
typedef struct _User {
char id[16];
char long_name[40];
@@ -97,13 +106,13 @@ typedef struct _User {
} User;
typedef struct _NodeInfo {
int32_t num;
uint32_t num;
bool has_user;
User user;
bool has_position;
Position position;
int32_t snr;
int32_t frequency_error;
uint32_t next_hop;
float snr;
} NodeInfo;
typedef struct _RadioConfig {
@@ -114,23 +123,37 @@ typedef struct _RadioConfig {
} RadioConfig;
typedef struct _SubPacket {
bool has_position;
Position position;
bool has_data;
Data data;
bool has_user;
User user;
pb_size_t which_payload;
union {
Position position;
Data data;
User user;
RouteDiscovery request;
RouteDiscovery reply;
};
bool want_response;
uint32_t dest;
pb_size_t which_ack;
union {
uint32_t success_id;
uint32_t fail_id;
} ack;
} SubPacket;
typedef PB_BYTES_ARRAY_T(256) MeshPacket_encrypted_t;
typedef struct _MeshPacket {
int32_t from;
int32_t to;
bool has_payload;
SubPacket payload;
uint32_t rx_time;
int32_t rx_snr;
uint32_t from;
uint32_t to;
pb_size_t which_payload;
union {
SubPacket decoded;
MeshPacket_encrypted_t encrypted;
};
uint32_t id;
float rx_snr;
uint32_t rx_time;
uint32_t hop_limit;
bool want_ack;
} MeshPacket;
typedef struct _DeviceState {
@@ -159,6 +182,7 @@ typedef struct _FromRadio {
RadioConfig radio;
DebugString debug_string;
uint32_t config_complete_id;
bool rebooted;
} variant;
} FromRadio;
@@ -191,10 +215,10 @@ typedef struct _ToRadio {
#define Position_init_default {0, 0, 0, 0, 0}
#define Data_init_default {_Data_Type_MIN, {0, {0}}}
#define User_init_default {"", "", "", {0}}
#define RouteDiscovery_init_default {{{NULL}, NULL}}
#define SubPacket_init_default {false, Position_init_default, false, Data_init_default, false, User_init_default, 0}
#define MeshPacket_init_default {0, 0, false, SubPacket_init_default, 0, 0, 0}
#define ChannelSettings_init_default {0, _ChannelSettings_ModemConfig_MIN, {0}, ""}
#define RouteDiscovery_init_default {0, {0, 0, 0, 0, 0, 0, 0, 0}}
#define SubPacket_init_default {0, {Position_init_default}, 0, 0, 0, {0}}
#define MeshPacket_init_default {0, 0, 0, {SubPacket_init_default}, 0, 0, 0, 0, 0}
#define ChannelSettings_init_default {0, _ChannelSettings_ModemConfig_MIN, {0, {0}}, ""}
#define RadioConfig_init_default {false, RadioConfig_UserPreferences_init_default, false, ChannelSettings_init_default}
#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}
@@ -203,13 +227,14 @@ typedef struct _ToRadio {
#define DebugString_init_default {""}
#define FromRadio_init_default {0, 0, {MeshPacket_init_default}}
#define ToRadio_init_default {0, {MeshPacket_init_default}}
#define ManufacturingData_init_default {0, {{NULL}, NULL}, {{NULL}, NULL}, 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 RouteDiscovery_init_zero {{{NULL}, NULL}}
#define SubPacket_init_zero {false, Position_init_zero, false, Data_init_zero, false, User_init_zero, 0}
#define MeshPacket_init_zero {0, 0, false, SubPacket_init_zero, 0, 0, 0}
#define ChannelSettings_init_zero {0, _ChannelSettings_ModemConfig_MIN, {0}, ""}
#define RouteDiscovery_init_zero {0, {0, 0, 0, 0, 0, 0, 0, 0}}
#define SubPacket_init_zero {0, {Position_init_zero}, 0, 0, 0, {0}}
#define MeshPacket_init_zero {0, 0, 0, {SubPacket_init_zero}, 0, 0, 0, 0, 0}
#define ChannelSettings_init_zero {0, _ChannelSettings_ModemConfig_MIN, {0, {0}}, ""}
#define RadioConfig_init_zero {false, RadioConfig_UserPreferences_init_zero, false, ChannelSettings_init_zero}
#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}
@@ -218,9 +243,9 @@ typedef struct _ToRadio {
#define DebugString_init_zero {""}
#define FromRadio_init_zero {0, 0, {MeshPacket_init_zero}}
#define ToRadio_init_zero {0, {MeshPacket_init_zero}}
#define ManufacturingData_init_zero {0, {{NULL}, NULL}, {{NULL}, NULL}, 0}
/* Field tags (for use in manual encoding/decoding) */
#define RouteDiscovery_route_tag 2
#define ChannelSettings_tx_power_tag 1
#define ChannelSettings_modem_config_tag 3
#define ChannelSettings_psk_tag 4
@@ -228,6 +253,10 @@ typedef struct _ToRadio {
#define Data_typ_tag 1
#define Data_payload_tag 2
#define DebugString_message_tag 1
#define ManufacturingData_fradioFreq_tag 1
#define ManufacturingData_hw_model_tag 2
#define ManufacturingData_hw_version_tag 3
#define ManufacturingData_selftest_result_tag 4
#define MyNodeInfo_my_node_num_tag 1
#define MyNodeInfo_has_gps_tag 2
#define MyNodeInfo_num_channels_tag 3
@@ -237,11 +266,11 @@ typedef struct _ToRadio {
#define MyNodeInfo_error_code_tag 7
#define MyNodeInfo_error_address_tag 8
#define MyNodeInfo_error_count_tag 9
#define Position_latitude_tag 1
#define Position_longitude_tag 2
#define Position_latitude_i_tag 7
#define Position_longitude_i_tag 8
#define Position_altitude_tag 3
#define Position_battery_level_tag 4
#define Position_time_tag 6
#define Position_time_tag 9
#define RadioConfig_UserPreferences_position_broadcast_secs_tag 1
#define RadioConfig_UserPreferences_send_owner_interval_tag 2
#define RadioConfig_UserPreferences_num_missed_to_fail_tag 3
@@ -255,6 +284,7 @@ typedef struct _ToRadio {
#define RadioConfig_UserPreferences_min_wake_secs_tag 11
#define RadioConfig_UserPreferences_keep_all_packets_tag 100
#define RadioConfig_UserPreferences_promiscuous_mode_tag 101
#define RouteDiscovery_route_tag 2
#define User_id_tag 1
#define User_long_name_tag 2
#define User_short_name_tag 3
@@ -262,20 +292,28 @@ typedef struct _ToRadio {
#define NodeInfo_num_tag 1
#define NodeInfo_user_tag 2
#define NodeInfo_position_tag 3
#define NodeInfo_snr_tag 5
#define NodeInfo_frequency_error_tag 6
#define NodeInfo_snr_tag 7
#define NodeInfo_next_hop_tag 5
#define RadioConfig_preferences_tag 1
#define RadioConfig_channel_settings_tag 2
#define SubPacket_position_tag 1
#define SubPacket_data_tag 3
#define SubPacket_user_tag 4
#define SubPacket_request_tag 6
#define SubPacket_reply_tag 7
#define SubPacket_success_id_tag 10
#define SubPacket_fail_id_tag 11
#define SubPacket_want_response_tag 5
#define SubPacket_dest_tag 9
#define MeshPacket_decoded_tag 3
#define MeshPacket_encrypted_tag 8
#define MeshPacket_from_tag 1
#define MeshPacket_to_tag 2
#define MeshPacket_payload_tag 3
#define MeshPacket_rx_time_tag 4
#define MeshPacket_rx_snr_tag 5
#define MeshPacket_id_tag 6
#define MeshPacket_rx_time_tag 9
#define MeshPacket_rx_snr_tag 7
#define MeshPacket_hop_limit_tag 10
#define MeshPacket_want_ack_tag 11
#define DeviceState_radio_tag 1
#define DeviceState_my_node_tag 2
#define DeviceState_owner_tag 3
@@ -289,6 +327,7 @@ typedef struct _ToRadio {
#define FromRadio_radio_tag 6
#define FromRadio_debug_string_tag 7
#define FromRadio_config_complete_id_tag 8
#define FromRadio_rebooted_tag 9
#define FromRadio_num_tag 1
#define ToRadio_packet_tag 1
#define ToRadio_want_config_id_tag 100
@@ -297,11 +336,11 @@ typedef struct _ToRadio {
/* Struct field encoding specification for nanopb */
#define Position_FIELDLIST(X, a) \
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, UINT32, time, 6)
X(a, STATIC, SINGULAR, SINT32, latitude_i, 7) \
X(a, STATIC, SINGULAR, SINT32, longitude_i, 8) \
X(a, STATIC, SINGULAR, FIXED32, time, 9)
#define Position_CALLBACK NULL
#define Position_DEFAULT NULL
@@ -320,36 +359,46 @@ X(a, STATIC, SINGULAR, FIXED_LENGTH_BYTES, macaddr, 4)
#define User_DEFAULT NULL
#define RouteDiscovery_FIELDLIST(X, a) \
X(a, CALLBACK, REPEATED, INT32, route, 2)
#define RouteDiscovery_CALLBACK pb_default_field_callback
X(a, STATIC, REPEATED, INT32, route, 2)
#define RouteDiscovery_CALLBACK NULL
#define RouteDiscovery_DEFAULT NULL
#define SubPacket_FIELDLIST(X, a) \
X(a, STATIC, OPTIONAL, MESSAGE, position, 1) \
X(a, STATIC, OPTIONAL, MESSAGE, data, 3) \
X(a, STATIC, OPTIONAL, MESSAGE, user, 4) \
X(a, STATIC, SINGULAR, BOOL, want_response, 5)
X(a, STATIC, ONEOF, MESSAGE, (payload,position,position), 1) \
X(a, STATIC, ONEOF, MESSAGE, (payload,data,data), 3) \
X(a, STATIC, ONEOF, MESSAGE, (payload,user,user), 4) \
X(a, STATIC, ONEOF, MESSAGE, (payload,request,request), 6) \
X(a, STATIC, ONEOF, MESSAGE, (payload,reply,reply), 7) \
X(a, STATIC, SINGULAR, BOOL, want_response, 5) \
X(a, STATIC, SINGULAR, UINT32, dest, 9) \
X(a, STATIC, ONEOF, UINT32, (ack,success_id,ack.success_id), 10) \
X(a, STATIC, ONEOF, UINT32, (ack,fail_id,ack.fail_id), 11)
#define SubPacket_CALLBACK NULL
#define SubPacket_DEFAULT NULL
#define SubPacket_position_MSGTYPE Position
#define SubPacket_data_MSGTYPE Data
#define SubPacket_user_MSGTYPE User
#define SubPacket_payload_position_MSGTYPE Position
#define SubPacket_payload_data_MSGTYPE Data
#define SubPacket_payload_user_MSGTYPE User
#define SubPacket_payload_request_MSGTYPE RouteDiscovery
#define SubPacket_payload_reply_MSGTYPE RouteDiscovery
#define MeshPacket_FIELDLIST(X, a) \
X(a, STATIC, SINGULAR, INT32, from, 1) \
X(a, STATIC, SINGULAR, INT32, to, 2) \
X(a, STATIC, OPTIONAL, MESSAGE, payload, 3) \
X(a, STATIC, SINGULAR, UINT32, rx_time, 4) \
X(a, STATIC, SINGULAR, SINT32, rx_snr, 5) \
X(a, STATIC, SINGULAR, UINT32, id, 6)
X(a, STATIC, SINGULAR, UINT32, from, 1) \
X(a, STATIC, SINGULAR, UINT32, to, 2) \
X(a, STATIC, ONEOF, MESSAGE, (payload,decoded,decoded), 3) \
X(a, STATIC, ONEOF, BYTES, (payload,encrypted,encrypted), 8) \
X(a, STATIC, SINGULAR, UINT32, id, 6) \
X(a, STATIC, SINGULAR, FLOAT, rx_snr, 7) \
X(a, STATIC, SINGULAR, FIXED32, rx_time, 9) \
X(a, STATIC, SINGULAR, UINT32, hop_limit, 10) \
X(a, STATIC, SINGULAR, BOOL, want_ack, 11)
#define MeshPacket_CALLBACK NULL
#define MeshPacket_DEFAULT NULL
#define MeshPacket_payload_MSGTYPE SubPacket
#define MeshPacket_payload_decoded_MSGTYPE SubPacket
#define ChannelSettings_FIELDLIST(X, a) \
X(a, STATIC, SINGULAR, INT32, tx_power, 1) \
X(a, STATIC, SINGULAR, UENUM, modem_config, 3) \
X(a, STATIC, SINGULAR, FIXED_LENGTH_BYTES, psk, 4) \
X(a, STATIC, SINGULAR, BYTES, psk, 4) \
X(a, STATIC, SINGULAR, STRING, name, 5)
#define ChannelSettings_CALLBACK NULL
#define ChannelSettings_DEFAULT NULL
@@ -380,11 +429,11 @@ X(a, STATIC, SINGULAR, BOOL, promiscuous_mode, 101)
#define RadioConfig_UserPreferences_DEFAULT NULL
#define NodeInfo_FIELDLIST(X, a) \
X(a, STATIC, SINGULAR, INT32, num, 1) \
X(a, STATIC, SINGULAR, UINT32, num, 1) \
X(a, STATIC, OPTIONAL, MESSAGE, user, 2) \
X(a, STATIC, OPTIONAL, MESSAGE, position, 3) \
X(a, STATIC, SINGULAR, INT32, snr, 5) \
X(a, STATIC, SINGULAR, INT32, frequency_error, 6)
X(a, STATIC, SINGULAR, UINT32, next_hop, 5) \
X(a, STATIC, SINGULAR, FLOAT, snr, 7)
#define NodeInfo_CALLBACK NULL
#define NodeInfo_DEFAULT NULL
#define NodeInfo_user_MSGTYPE User
@@ -432,7 +481,8 @@ X(a, STATIC, ONEOF, MESSAGE, (variant,my_info,variant.my_info), 3) \
X(a, STATIC, ONEOF, MESSAGE, (variant,node_info,variant.node_info), 4) \
X(a, STATIC, ONEOF, MESSAGE, (variant,radio,variant.radio), 6) \
X(a, STATIC, ONEOF, MESSAGE, (variant,debug_string,variant.debug_string), 7) \
X(a, STATIC, ONEOF, UINT32, (variant,config_complete_id,variant.config_complete_id), 8)
X(a, STATIC, ONEOF, UINT32, (variant,config_complete_id,variant.config_complete_id), 8) \
X(a, STATIC, ONEOF, BOOL, (variant,rebooted,variant.rebooted), 9)
#define FromRadio_CALLBACK NULL
#define FromRadio_DEFAULT NULL
#define FromRadio_variant_packet_MSGTYPE MeshPacket
@@ -452,6 +502,14 @@ X(a, STATIC, ONEOF, MESSAGE, (variant,set_owner,variant.set_owner), 102)
#define ToRadio_variant_set_radio_MSGTYPE RadioConfig
#define ToRadio_variant_set_owner_MSGTYPE User
#define ManufacturingData_FIELDLIST(X, a) \
X(a, STATIC, SINGULAR, UINT32, fradioFreq, 1) \
X(a, CALLBACK, SINGULAR, STRING, hw_model, 2) \
X(a, CALLBACK, SINGULAR, STRING, hw_version, 3) \
X(a, STATIC, SINGULAR, SINT32, selftest_result, 4)
#define ManufacturingData_CALLBACK pb_default_field_callback
#define ManufacturingData_DEFAULT NULL
extern const pb_msgdesc_t Position_msg;
extern const pb_msgdesc_t Data_msg;
extern const pb_msgdesc_t User_msg;
@@ -467,6 +525,7 @@ extern const pb_msgdesc_t DeviceState_msg;
extern const pb_msgdesc_t DebugString_msg;
extern const pb_msgdesc_t FromRadio_msg;
extern const pb_msgdesc_t ToRadio_msg;
extern const pb_msgdesc_t ManufacturingData_msg;
/* Defines for backwards compatibility with code written before nanopb-0.4.0 */
#define Position_fields &Position_msg
@@ -484,23 +543,25 @@ extern const pb_msgdesc_t ToRadio_msg;
#define DebugString_fields &DebugString_msg
#define FromRadio_fields &FromRadio_msg
#define ToRadio_fields &ToRadio_msg
#define ManufacturingData_fields &ManufacturingData_msg
/* Maximum encoded size of messages (where known) */
#define Position_size 46
#define Position_size 39
#define Data_size 256
#define User_size 72
/* RouteDiscovery_size depends on runtime parameters */
#define SubPacket_size 383
#define MeshPacket_size 426
#define ChannelSettings_size 44
#define RadioConfig_size 120
#define RouteDiscovery_size 88
#define SubPacket_size 273
#define MeshPacket_size 312
#define ChannelSettings_size 60
#define RadioConfig_size 136
#define RadioConfig_UserPreferences_size 72
#define NodeInfo_size 155
#define NodeInfo_size 132
#define MyNodeInfo_size 85
#define DeviceState_size 19502
#define DeviceState_size 15021
#define DebugString_size 258
#define FromRadio_size 435
#define ToRadio_size 429
#define FromRadio_size 321
#define ToRadio_size 315
/* ManufacturingData_size depends on runtime parameters */
#ifdef __cplusplus
} /* extern "C" */

View File

@@ -0,0 +1,5 @@
#include "CryptoEngine.h"
// FIXME, do a NRF52 version
CryptoEngine *crypto = new CryptoEngine();

View File

@@ -17,7 +17,7 @@ static inline void debugger_break(void)
void __attribute__((noreturn)) __assert_func(const char *file, int line, const char *func, const char *failedexpr)
{
DEBUG_MSG("assert failed %s: %d, %s, test=%s\n", file, line, func, failedexpr);
debugger_break();
// debugger_break(); FIXME doesn't work, possibly not for segger
while (1)
; // FIXME, reboot!
}
@@ -67,4 +67,5 @@ void nrf52Setup()
{
// Not yet on board
// pmu.init();
DEBUG_MSG("FIXME, need to call randomSeed on nrf52!\n");
}

View File

@@ -1,208 +0,0 @@
#include "CustomRF95.h"
#include "NodeDB.h" // FIXME, this class should not need to touch nodedb
#include "assert.h"
#include "configuration.h"
#include <pb_decode.h>
#include <pb_encode.h>
#ifdef RF95_IRQ_GPIO
/// 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];
CustomRF95::CustomRF95() : RH_RF95(NSS_GPIO, RF95_IRQ_GPIO), txQueue(MAX_TX_QUEUE) {}
bool CustomRF95::canSleep()
{
// We allow initializing mode, because sometimes while testing we don't ever call init() to turn on the hardware
bool isRx = isReceiving();
bool res = (_mode == RHModeInitialising || _mode == RHModeIdle || _mode == RHModeRx) && !isRx && txQueue.isEmpty();
if (!res) // only print debug messages if we are vetoing sleep
DEBUG_MSG("radio wait to sleep, mode=%d, isRx=%d, txEmpty=%d, txGood=%d\n", _mode, isRx, txQueue.isEmpty(), _txGood);
return res;
}
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();
return ok;
}
/// 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
ErrorCode CustomRF95::send(MeshPacket *p)
{
// 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("immediate send on mesh fr=0x%x,to=0x%x,id=%d\n (txGood=%d,rxGood=%d,rxBad=%d)\n", p->from, p->to, p->id,
txGood(), rxGood(), rxBad());
waitPacketSent(); // Make sure we dont interrupt an outgoing message
if (!waitCAD())
return false; // Check channel activity
startSend(p);
return ERRNO_OK;
} else {
DEBUG_MSG("enquing packet for send from=0x%x, to=0x%x\n", p->from, p->to);
ErrorCode res = txQueue.enqueue(p, 0) ? ERRNO_OK : ERRNO_UNKNOWN;
if (res != ERRNO_OK) // we weren't able to queue it, so we must drop it to prevent leaks
packetPool.release(p);
return res;
}
}
// After doing standard behavior, check to see if a new packet arrived or one was sent and start a new send or receive as
// necessary
void CustomRF95::handleInterrupt()
{
RH_RF95::handleInterrupt();
if (_mode == RHModeIdle) // We are now done sending or receiving
{
if (sendingPacket) // Were we sending?
{
// We are done sending that packet, release it
packetPool.release(sendingPacket);
sendingPacket = NULL;
// DEBUG_MSG("Done with send\n");
}
// If we just finished receiving a packet, forward it into a queue
if (_rxBufValid) {
// We received a packet
// Skip the 4 headers that are at the beginning of the rxBuf
size_t payloadLen = _bufLen - RH_RF95_HEADER_LEN;
uint8_t *payload = _buf + RH_RF95_HEADER_LEN;
// FIXME - throws exception if called in ISR context: frequencyError() - probably the floating point math
int32_t freqerr = -1, snr = 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 = packetPool.allocZeroed();
SubPacket *p = &mp->payload;
mp->from = _rxHeaderFrom;
mp->to = _rxHeaderTo;
mp->id = _rxHeaderId;
//_rxHeaderId = _buf[2];
//_rxHeaderFlags = _buf[3];
// 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(payload, payloadLen, SubPacket_fields, p)) {
packetPool.release(mp);
} else {
// parsing was successful, queue for our recipient
mp->has_payload = true;
deliverToReceiver(mp);
}
clearRxBuf(); // This message accepted and cleared
}
handleIdleISR();
}
}
/** The ISR doesn't have any good work to do, give a new assignment.
*
* Return true if a higher pri task has woken
*/
void CustomRF95::handleIdleISR()
{
// First send any outgoing packets we have ready
MeshPacket *txp = txQueue.dequeuePtr(0);
if (txp)
startSend(txp);
else {
// Nothing to send, let's switch back to receive mode
setModeRx();
}
}
/// This routine might be called either from user space or ISR
void CustomRF95::startSend(MeshPacket *txp)
{
assert(!sendingPacket);
// DEBUG_MSG("sending queued packet on mesh (txGood=%d,rxGood=%d,rxBad=%d)\n", rf95.txGood(), rf95.rxGood(), rf95.rxBad());
assert(txp->has_payload);
lastTxStart = millis();
size_t numbytes = pb_encode_to_bytes(radiobuf, sizeof(radiobuf), SubPacket_fields, &txp->payload);
sendingPacket = txp;
setHeaderTo(txp->to);
setHeaderId(txp->id);
// if the sender nodenum is zero, that means uninitialized
assert(txp->from);
setHeaderFrom(txp->from); // We must do this before each send, because we might have just changed our nodenum
assert(numbytes <= 251); // Make sure we don't overflow the tiny max packet size
// uint32_t start = millis(); // FIXME, store this in the class
int res = RH_RF95::send(radiobuf, numbytes);
assert(res);
}
#define TX_WATCHDOG_TIMEOUT 30 * 1000
#include "error.h"
void CustomRF95::loop()
{
RH_RF95::loop();
// It should never take us more than 30 secs to send a packet, if it does, we have a bug, FIXME, move most of this
// into CustomRF95
uint32_t now = millis();
if (lastTxStart != 0 && (now - lastTxStart) > TX_WATCHDOG_TIMEOUT && mode() == RHGenericDriver::RHModeTx) {
DEBUG_MSG("ERROR! Bug! Tx packet took too long to send, forcing radio into rx mode\n");
setModeRx();
if (sendingPacket) { // There was probably a packet we were trying to send, free it
packetPool.release(sendingPacket);
sendingPacket = NULL;
}
recordCriticalError(ErrTxWatchdog);
lastTxStart = 0; // Stop checking for now, because we just warned the developer
}
}
#endif

View File

@@ -1,56 +0,0 @@
#pragma once
#include "RadioInterface.h"
#include "mesh.pb.h"
#include <RH_RF95.h>
#define MAX_TX_QUEUE 16 // max number of packets which can be waiting for transmission
/**
* A version of the RF95 driver which is smart enough to manage packets via queues (no polling or blocking in user threads!)
*/
class CustomRF95 : public RH_RF95, public RadioInterface
{
friend class MeshRadio; // for debugging we let that class touch pool
PointerQueue<MeshPacket> txQueue;
uint32_t lastTxStart = 0L;
public:
/** 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
*/
CustomRF95();
/**
* 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
ErrorCode send(MeshPacket *p);
bool init();
void loop(); // Idle processing
protected:
// After doing standard behavior, check to see if a new packet arrived or one was sent and start a new send or receive as
// necessary
virtual void handleInterrupt();
private:
/// Send a new packet - this low level call can be called from either ISR or userspace
void startSend(MeshPacket *txp);
/// Return true if a higher pri task has woken
void handleIdleISR();
};

View File

@@ -1,126 +0,0 @@
#include "FloodingRouter.h"
#include "configuration.h"
#include "mesh-pb-constants.h"
/// We clear our old flood record five minute after we see the last of it
#define FLOOD_EXPIRE_TIME (5 * 60 * 1000L)
FloodingRouter::FloodingRouter() : toResend(MAX_NUM_NODES)
{
recentBroadcasts.reserve(MAX_NUM_NODES); // Prealloc the worst case # of records - to prevent heap fragmentation
// setup our periodic task
}
/**
* Send a packet on a suitable interface. This routine will
* later free() the packet to pool. This routine is not allowed to stall.
* If the txmit queue is full it might return an error
*/
ErrorCode FloodingRouter::send(MeshPacket *p)
{
// We update our table of recent broadcasts, even for messages we send
wasSeenRecently(p);
return Router::send(p);
}
// Return a delay in msec before sending the next packet
uint32_t getRandomDelay()
{
return random(200, 10 * 1000L); // between 200ms and 10s
}
/**
* Called from loop()
* Handle any packet that is received by an interface on this node.
* Note: some packets may merely being passed through this node and will be forwarded elsewhere.
*
* Note: this method will free the provided packet
*/
void FloodingRouter::handleReceived(MeshPacket *p)
{
if (wasSeenRecently(p)) {
DEBUG_MSG("Ignoring incoming floodmsg, because we've already seen it\n");
packetPool.release(p);
} else {
if (p->to == NODENUM_BROADCAST) {
if (p->id != 0) {
uint32_t delay = getRandomDelay();
DEBUG_MSG("Rebroadcasting received floodmsg to neighbors in %u msec, fr=0x%x,to=0x%x,id=%d\n", delay, p->from,
p->to, p->id);
MeshPacket *tosend = packetPool.allocCopy(*p);
toResend.enqueue(tosend);
setPeriod(delay); // This will work even if we were already waiting a random delay
} else {
DEBUG_MSG("Ignoring a simple (0 hop) broadcast\n");
}
}
// handle the packet as normal
Router::handleReceived(p);
}
}
void FloodingRouter::doTask()
{
MeshPacket *p = toResend.dequeuePtr(0);
if (p) {
DEBUG_MSG("Sending delayed message!\n");
// Note: we are careful to resend using the original senders node id
// We are careful not to call our hooked version of send() - because we don't want to check this again
Router::send(p);
}
if (toResend.isEmpty())
disable(); // no more work right now
else {
setPeriod(getRandomDelay());
}
}
/**
* Update recentBroadcasts and return true if we have already seen this packet
*/
bool FloodingRouter::wasSeenRecently(const MeshPacket *p)
{
if (p->to != NODENUM_BROADCAST)
return false; // Not a broadcast, so we don't care
if (p->id == 0) {
DEBUG_MSG("Ignoring message with zero id\n");
return false; // Not a floodable message ID, so we don't care
}
uint32_t now = millis();
for (int i = 0; i < recentBroadcasts.size();) {
BroadcastRecord &r = recentBroadcasts[i];
if ((now - r.rxTimeMsec) >= FLOOD_EXPIRE_TIME) {
DEBUG_MSG("Deleting old broadcast record %d\n", i);
recentBroadcasts.erase(recentBroadcasts.begin() + i); // delete old record
} else {
if (r.id == p->id && r.sender == p->from) {
DEBUG_MSG("Found existing broadcast record for fr=0x%x,to=0x%x,id=%d\n", p->from, p->to, p->id);
// Update the time on this record to now
r.rxTimeMsec = now;
return true;
}
i++;
}
}
// Didn't find an existing record, make one
BroadcastRecord r;
r.id = p->id;
r.sender = p->from;
r.rxTimeMsec = now;
recentBroadcasts.push_back(r);
DEBUG_MSG("Adding broadcast record for fr=0x%x,to=0x%x,id=%d\n", p->from, p->to, p->id);
return false;
}

View File

@@ -1,17 +0,0 @@
This software is Copyright (C) 2008 Mike McCauley. Use is subject to license
conditions. The main licensing options available are GPL V2 or Commercial:
Open Source Licensing GPL V2
This is the appropriate option if you want to share the source code of your
application with everyone you distribute it to, and you also want to give them
the right to share who uses it. If you wish to use this software under Open
Source Licensing, you must contribute all your source code to the open source
community in accordance with the GPL Version 2 when your application is
distributed. See http://www.gnu.org/copyleft/gpl.html
Commercial Licensing
This is the appropriate option if you are creating proprietary applications
and you are not prepared to distribute and share the source code of your
application. Contact info@open.com.au for details.

View File

@@ -1,4 +0,0 @@
# RF95
This is a heavily modified version of the Mike McCauley's RadioHead RF95 driver. We are using it under the GPL V3 License. See the
file LICENSE for Mike's license terms (which listed GPL as acceptible).

View File

@@ -1,207 +0,0 @@
// RHGenericDriver.cpp
//
// Copyright (C) 2014 Mike McCauley
// $Id: RHGenericDriver.cpp,v 1.23 2018/02/11 23:57:18 mikem Exp $
#include <RHGenericDriver.h>
RHGenericDriver::RHGenericDriver()
: _mode(RHModeInitialising), _thisAddress(RH_BROADCAST_ADDRESS), _txHeaderTo(RH_BROADCAST_ADDRESS),
_txHeaderFrom(RH_BROADCAST_ADDRESS), _txHeaderId(0), _txHeaderFlags(0), _rxBad(0), _rxGood(0), _txGood(0), _cad_timeout(0)
{
}
bool RHGenericDriver::init()
{
return true;
}
// Blocks until a valid message is received
void RHGenericDriver::waitAvailable()
{
while (!available())
YIELD;
}
// Blocks until a valid message is received or timeout expires
// Return true if there is a message available
// Works correctly even on millis() rollover
bool RHGenericDriver::waitAvailableTimeout(uint16_t timeout)
{
unsigned long starttime = millis();
while ((millis() - starttime) < timeout) {
if (available()) {
return true;
}
YIELD;
}
return false;
}
bool RHGenericDriver::waitPacketSent()
{
while (_mode == RHModeTx)
YIELD; // Wait for any previous transmit to finish
return true;
}
bool RHGenericDriver::waitPacketSent(uint16_t timeout)
{
unsigned long starttime = millis();
while ((millis() - starttime) < timeout) {
if (_mode != RHModeTx) // Any previous transmit finished?
return true;
YIELD;
}
return false;
}
// Wait until no channel activity detected or timeout
bool RHGenericDriver::waitCAD()
{
if (!_cad_timeout)
return true;
// Wait for any channel activity to finish or timeout
// Sophisticated DCF function...
// DCF : BackoffTime = random() x aSlotTime
// 100 - 1000 ms
// 10 sec timeout
unsigned long t = millis();
while (isChannelActive()) {
if (millis() - t > _cad_timeout)
return false;
#if (RH_PLATFORM == RH_PLATFORM_STM32) // stdlib on STMF103 gets confused if random is redefined
delay(_random(1, 10) * 100);
#else
delay(random(1, 10) * 100); // Should these values be configurable? Macros?
#endif
}
return true;
}
// subclasses are expected to override if CAD is available for that radio
bool RHGenericDriver::isChannelActive()
{
return false;
}
void RHGenericDriver::setPromiscuous(bool promiscuous)
{
_promiscuous = promiscuous;
}
void RHGenericDriver::setThisAddress(uint8_t address)
{
_thisAddress = address;
}
void RHGenericDriver::setHeaderTo(uint8_t to)
{
_txHeaderTo = to;
}
void RHGenericDriver::setHeaderFrom(uint8_t from)
{
_txHeaderFrom = from;
}
void RHGenericDriver::setHeaderId(uint8_t id)
{
_txHeaderId = id;
}
void RHGenericDriver::setHeaderFlags(uint8_t set, uint8_t clear)
{
_txHeaderFlags &= ~clear;
_txHeaderFlags |= set;
}
uint8_t RHGenericDriver::headerTo()
{
return _rxHeaderTo;
}
uint8_t RHGenericDriver::headerFrom()
{
return _rxHeaderFrom;
}
uint8_t RHGenericDriver::headerId()
{
return _rxHeaderId;
}
uint8_t RHGenericDriver::headerFlags()
{
return _rxHeaderFlags;
}
int16_t RHGenericDriver::lastRssi()
{
return _lastRssi;
}
RHGenericDriver::RHMode RHGenericDriver::mode()
{
return _mode;
}
void RHGenericDriver::setMode(RHMode mode)
{
_mode = mode;
}
bool RHGenericDriver::sleep()
{
return false;
}
// Diagnostic help
void RHGenericDriver::printBuffer(const char *prompt, const uint8_t *buf, uint8_t len)
{
#ifdef RH_HAVE_SERIAL
Serial.println(prompt);
uint8_t i;
for (i = 0; i < len; i++) {
if (i % 16 == 15)
Serial.println(buf[i], HEX);
else {
Serial.print(buf[i], HEX);
Serial.print(' ');
}
}
Serial.println("");
#endif
}
uint16_t RHGenericDriver::rxBad()
{
return _rxBad;
}
uint16_t RHGenericDriver::rxGood()
{
return _rxGood;
}
uint16_t RHGenericDriver::txGood()
{
return _txGood;
}
void RHGenericDriver::setCADTimeout(unsigned long cad_timeout)
{
_cad_timeout = cad_timeout;
}
#if (RH_PLATFORM == RH_PLATFORM_ATTINY)
// Tinycore does not have __cxa_pure_virtual, so without this we
// get linking complaints from the default code generated for pure virtual functions
extern "C" void __cxa_pure_virtual()
{
while (1)
;
}
#endif

View File

@@ -1,280 +0,0 @@
// RHGenericDriver.h
// Author: Mike McCauley (mikem@airspayce.com)
// Copyright (C) 2014 Mike McCauley
// $Id: RHGenericDriver.h,v 1.23 2018/09/23 23:54:01 mikem Exp $
#ifndef RHGenericDriver_h
#define RHGenericDriver_h
#include <RadioHead.h>
// Defines bits of the FLAGS header reserved for use by the RadioHead library and
// the flags available for use by applications
#define RH_FLAGS_RESERVED 0xf0
#define RH_FLAGS_APPLICATION_SPECIFIC 0x0f
#define RH_FLAGS_NONE 0
// Default timeout for waitCAD() in ms
#define RH_CAD_DEFAULT_TIMEOUT 10000
/////////////////////////////////////////////////////////////////////
/// \class RHGenericDriver RHGenericDriver.h <RHGenericDriver.h>
/// \brief Abstract base class for a RadioHead driver.
///
/// This class defines the functions that must be provided by any RadioHead driver.
/// Different types of driver will implement all the abstract functions, and will perhaps override
/// other functions in this subclass, or perhaps add new functions specifically required by that driver.
/// Do not directly instantiate this class: it is only to be subclassed by driver classes.
///
/// Subclasses are expected to implement a half-duplex, unreliable, error checked, unaddressed packet transport.
/// They are expected to carry a message payload with an appropriate maximum length for the transport hardware
/// and to also carry unaltered 4 message headers: TO, FROM, ID, FLAGS
///
/// \par Headers
///
/// Each message sent and received by a RadioHead driver includes 4 headers:
/// -TO The node address that the message is being sent to (broadcast RH_BROADCAST_ADDRESS (255) is permitted)
/// -FROM The node address of the sending node
/// -ID A message ID, distinct (over short time scales) for each message sent by a particilar node
/// -FLAGS A bitmask of flags. The most significant 4 bits are reserved for use by RadioHead. The least
/// significant 4 bits are reserved for applications.
class RHGenericDriver
{
public:
/// \brief Defines different operating modes for the transport hardware
///
/// These are the different values that can be adopted by the _mode variable and
/// returned by the mode() member function,
typedef enum {
RHModeInitialising = 0, ///< Transport is initialising. Initial default value until init() is called..
RHModeSleep, ///< Transport hardware is in low power sleep mode (if supported)
RHModeIdle, ///< Transport is idle.
RHModeTx, ///< Transport is in the process of transmitting a message.
RHModeRx, ///< Transport is in the process of receiving a message.
RHModeCad ///< Transport is in the process of detecting channel activity (if supported)
} RHMode;
/// Constructor
RHGenericDriver();
/// Initialise the Driver transport hardware and software.
/// Make sure the Driver is properly configured before calling init().
/// \return true if initialisation succeeded.
virtual bool init();
/// Tests whether a new message is available
/// from the Driver.
/// On most drivers, if there is an uncollected received message, and there is no message
/// currently bing transmitted, this will also put the Driver into RHModeRx mode until
/// a message is actually received by the transport, when it will be returned to RHModeIdle.
/// This can be called multiple times in a timeout loop.
/// \return true if a new, complete, error-free uncollected message is available to be retreived by recv().
virtual bool available() = 0;
/// Returns the maximum message length
/// available in this Driver.
/// \return The maximum legal message length
virtual uint8_t maxMessageLength() = 0;
/// Starts the receiver and blocks until a valid received
/// message is available.
virtual void waitAvailable();
/// Blocks until the transmitter
/// is no longer transmitting.
virtual bool waitPacketSent();
/// Blocks until the transmitter is no longer transmitting.
/// or until the timeout occuers, whichever happens first
/// \param[in] timeout Maximum time to wait in milliseconds.
/// \return true if the radio completed transmission within the timeout period. False if it timed out.
virtual bool waitPacketSent(uint16_t timeout);
/// Starts the receiver and blocks until a received message is available or a timeout
/// \param[in] timeout Maximum time to wait in milliseconds.
/// \return true if a message is available
virtual bool waitAvailableTimeout(uint16_t timeout);
// Bent G Christensen (bentor@gmail.com), 08/15/2016
/// Channel Activity Detection (CAD).
/// Blocks until channel activity is finished or CAD timeout occurs.
/// Uses the radio's CAD function (if supported) to detect channel activity.
/// Implements random delays of 100 to 1000ms while activity is detected and until timeout.
/// Caution: the random() function is not seeded. If you want non-deterministic behaviour, consider
/// using something like randomSeed(analogRead(A0)); in your sketch.
/// Permits the implementation of listen-before-talk mechanism (Collision Avoidance).
/// Calls the isChannelActive() member function for the radio (if supported)
/// to determine if the channel is active. If the radio does not support isChannelActive(),
/// always returns true immediately
/// \return true if the radio-specific CAD (as returned by isChannelActive())
/// shows the channel is clear within the timeout period (or the timeout period is 0), else returns false.
virtual bool waitCAD();
/// Sets the Channel Activity Detection timeout in milliseconds to be used by waitCAD().
/// The default is 0, which means do not wait for CAD detection.
/// CAD detection depends on support for isChannelActive() by your particular radio.
void setCADTimeout(unsigned long cad_timeout);
/// Determine if the currently selected radio channel is active.
/// This is expected to be subclassed by specific radios to implement their Channel Activity Detection
/// if supported. If the radio does not support CAD, returns true immediately. If a RadioHead radio
/// supports isChannelActive() it will be documented in the radio specific documentation.
/// This is called automatically by waitCAD().
/// \return true if the radio-specific CAD (as returned by override of isChannelActive()) shows the
/// current radio channel as active, else false. If there is no radio-specific CAD, returns false.
virtual bool isChannelActive();
/// Sets the address of this node. Defaults to 0xFF. Subclasses or the user may want to change this.
/// This will be used to test the adddress in incoming messages. In non-promiscuous mode,
/// only messages with a TO header the same as thisAddress or the broadcast addess (0xFF) will be accepted.
/// In promiscuous mode, all messages will be accepted regardless of the TO header.
/// In a conventional multinode system, all nodes will have a unique address
/// (which you could store in EEPROM).
/// You would normally set the header FROM address to be the same as thisAddress (though you dont have to,
/// allowing the possibilty of address spoofing).
/// \param[in] thisAddress The address of this node.
virtual void setThisAddress(uint8_t thisAddress);
/// Sets the TO header to be sent in all subsequent messages
/// \param[in] to The new TO header value
virtual void setHeaderTo(uint8_t to);
/// Sets the FROM header to be sent in all subsequent messages
/// \param[in] from The new FROM header value
virtual void setHeaderFrom(uint8_t from);
/// Sets the ID header to be sent in all subsequent messages
/// \param[in] id The new ID header value
virtual void setHeaderId(uint8_t id);
/// Sets and clears bits in the FLAGS header to be sent in all subsequent messages
/// First it clears he FLAGS according to the clear argument, then sets the flags according to the
/// set argument. The default for clear always clears the application specific flags.
/// \param[in] set bitmask of bits to be set. Flags are cleared with the clear mask before being set.
/// \param[in] clear bitmask of flags to clear. Defaults to RH_FLAGS_APPLICATION_SPECIFIC
/// which clears the application specific flags, resulting in new application specific flags
/// identical to the set.
virtual void setHeaderFlags(uint8_t set, uint8_t clear = RH_FLAGS_APPLICATION_SPECIFIC);
/// Tells the receiver to accept messages with any TO address, not just messages
/// addressed to thisAddress or the broadcast address
/// \param[in] promiscuous true if you wish to receive messages with any TO address
virtual void setPromiscuous(bool promiscuous);
/// Returns the TO header of the last received message
/// \return The TO header
virtual uint8_t headerTo();
/// Returns the FROM header of the last received message
/// \return The FROM header
virtual uint8_t headerFrom();
/// Returns the ID header of the last received message
/// \return The ID header
virtual uint8_t headerId();
/// Returns the FLAGS header of the last received message
/// \return The FLAGS header
virtual uint8_t headerFlags();
/// Returns the most recent RSSI (Receiver Signal Strength Indicator).
/// Usually it is the RSSI of the last received message, which is measured when the preamble is received.
/// If you called readRssi() more recently, it will return that more recent value.
/// \return The most recent RSSI measurement in dBm.
virtual int16_t lastRssi();
/// Returns the operating mode of the library.
/// \return the current mode, one of RF69_MODE_*
virtual RHMode mode();
/// Sets the operating mode of the transport.
virtual void setMode(RHMode mode);
/// Sets the transport hardware into low-power sleep mode
/// (if supported). May be overridden by specific drivers to initialte sleep mode.
/// If successful, the transport will stay in sleep mode until woken by
/// changing mode it idle, transmit or receive (eg by calling send(), recv(), available() etc)
/// \return true if sleep mode is supported by transport hardware and the RadioHead driver, and if sleep mode
/// was successfully entered. If sleep mode is not suported, return false.
virtual bool sleep();
/// Prints a data buffer in HEX.
/// For diagnostic use
/// \param[in] prompt string to preface the print
/// \param[in] buf Location of the buffer to print
/// \param[in] len Length of the buffer in octets.
static void printBuffer(const char *prompt, const uint8_t *buf, uint8_t len);
/// Returns the count of the number of bad received packets (ie packets with bad lengths, checksum etc)
/// which were rejected and not delivered to the application.
/// Caution: not all drivers can correctly report this count. Some underlying hardware only report
/// good packets.
/// \return The number of bad packets received.
virtual uint16_t rxBad();
/// Returns the count of the number of
/// good received packets
/// \return The number of good packets received.
virtual uint16_t rxGood();
/// Returns the count of the number of
/// packets successfully transmitted (though not necessarily received by the destination)
/// \return The number of packets successfully transmitted
virtual uint16_t txGood();
protected:
/// The current transport operating mode
volatile RHMode _mode;
/// This node id
uint8_t _thisAddress;
/// Whether the transport is in promiscuous mode
bool _promiscuous;
/// TO header in the last received mesasge
volatile uint8_t _rxHeaderTo;
/// FROM header in the last received mesasge
volatile uint8_t _rxHeaderFrom;
/// ID header in the last received mesasge
volatile uint8_t _rxHeaderId;
/// FLAGS header in the last received mesasge
volatile uint8_t _rxHeaderFlags;
/// TO header to send in all messages
uint8_t _txHeaderTo;
/// FROM header to send in all messages
uint8_t _txHeaderFrom;
/// ID header to send in all messages
uint8_t _txHeaderId;
/// FLAGS header to send in all messages
uint8_t _txHeaderFlags;
/// The value of the last received RSSI value, in some transport specific units
volatile int16_t _lastRssi;
/// Count of the number of bad messages (eg bad checksum etc) received
volatile uint16_t _rxBad;
/// Count of the number of successfully transmitted messaged
volatile uint16_t _rxGood;
/// Count of the number of bad messages (correct checksum etc) received
volatile uint16_t _txGood;
/// Channel activity detected
volatile bool _cad;
/// Channel activity timeout in ms
unsigned int _cad_timeout;
private:
};
#endif

View File

@@ -1,31 +0,0 @@
// RHGenericSPI.cpp
// Author: Mike McCauley (mikem@airspayce.com)
// Copyright (C) 2011 Mike McCauley
// Contributed by Joanna Rutkowska
// $Id: RHGenericSPI.cpp,v 1.2 2014/04/12 05:26:05 mikem Exp $
#include <RHGenericSPI.h>
RHGenericSPI::RHGenericSPI(Frequency frequency, BitOrder bitOrder, DataMode dataMode)
:
_frequency(frequency),
_bitOrder(bitOrder),
_dataMode(dataMode)
{
}
void RHGenericSPI::setBitOrder(BitOrder bitOrder)
{
_bitOrder = bitOrder;
}
void RHGenericSPI::setDataMode(DataMode dataMode)
{
_dataMode = dataMode;
}
void RHGenericSPI::setFrequency(Frequency frequency)
{
_frequency = frequency;
}

View File

@@ -1,183 +0,0 @@
// RHGenericSPI.h
// Author: Mike McCauley (mikem@airspayce.com)
// Copyright (C) 2011 Mike McCauley
// Contributed by Joanna Rutkowska
// $Id: RHGenericSPI.h,v 1.9 2020/01/05 07:02:23 mikem Exp mikem $
#ifndef RHGenericSPI_h
#define RHGenericSPI_h
#include <RadioHead.h>
/////////////////////////////////////////////////////////////////////
/// \class RHGenericSPI RHGenericSPI.h <RHGenericSPI.h>
/// \brief Base class for SPI interfaces
///
/// This generic abstract class is used to encapsulate hardware or software SPI interfaces for
/// a variety of platforms.
/// The intention is so that driver classes can be configured to use hardware or software SPI
/// without changing the main code.
///
/// You must provide a subclass of this class to driver constructors that require SPI.
/// A concrete subclass that encapsualates the standard Arduino hardware SPI and a bit-banged
/// software implementation is included.
///
/// Do not directly use this class: it must be subclassed and the following abstract functions at least
/// must be implmented:
/// - begin()
/// - end()
/// - transfer()
class RHGenericSPI
{
public:
/// \brief Defines constants for different SPI modes
///
/// Defines constants for different SPI modes
/// that can be passed to the constructor or setMode()
/// We need to define these in a device and platform independent way, because the
/// SPI implementation is different on each platform.
typedef enum
{
DataMode0 = 0, ///< SPI Mode 0: CPOL = 0, CPHA = 0
DataMode1, ///< SPI Mode 1: CPOL = 0, CPHA = 1
DataMode2, ///< SPI Mode 2: CPOL = 1, CPHA = 0
DataMode3, ///< SPI Mode 3: CPOL = 1, CPHA = 1
} DataMode;
/// \brief Defines constants for different SPI bus frequencies
///
/// Defines constants for different SPI bus frequencies
/// that can be passed to setFrequency().
/// The frequency you get may not be exactly the one according to the name.
/// We need to define these in a device and platform independent way, because the
/// SPI implementation is different on each platform.
typedef enum
{
Frequency1MHz = 0, ///< SPI bus frequency close to 1MHz
Frequency2MHz, ///< SPI bus frequency close to 2MHz
Frequency4MHz, ///< SPI bus frequency close to 4MHz
Frequency8MHz, ///< SPI bus frequency close to 8MHz
Frequency16MHz ///< SPI bus frequency close to 16MHz
} Frequency;
/// \brief Defines constants for different SPI endianness
///
/// Defines constants for different SPI endianness
/// that can be passed to setBitOrder()
/// We need to define these in a device and platform independent way, because the
/// SPI implementation is different on each platform.
typedef enum
{
BitOrderMSBFirst = 0, ///< SPI MSB first
BitOrderLSBFirst, ///< SPI LSB first
} BitOrder;
/// Constructor
/// Creates an instance of an abstract SPI interface.
/// Do not use this contructor directly: you must instead use on of the concrete subclasses provided
/// such as RHHardwareSPI or RHSoftwareSPI
/// \param[in] frequency One of RHGenericSPI::Frequency to select the SPI bus frequency. The frequency
/// is mapped to the closest available bus frequency on the platform.
/// \param[in] bitOrder Select the SPI bus bit order, one of RHGenericSPI::BitOrderMSBFirst or
/// RHGenericSPI::BitOrderLSBFirst.
/// \param[in] dataMode Selects the SPI bus data mode. One of RHGenericSPI::DataMode
RHGenericSPI(Frequency frequency = Frequency1MHz, BitOrder bitOrder = BitOrderMSBFirst, DataMode dataMode = DataMode0);
/// Transfer a single octet to and from the SPI interface
/// \param[in] data The octet to send
/// \return The octet read from SPI while the data octet was sent
virtual uint8_t transfer(uint8_t data) = 0;
#if (RH_PLATFORM == RH_PLATFORM_MONGOOSE_OS)
/// Transfer up to 2 bytes on the SPI interface
/// \param[in] byte0 The first byte to be sent on the SPI interface
/// \param[in] byte1 The second byte to be sent on the SPI interface
/// \return The second byte clocked in as the second byte is sent.
virtual uint8_t transfer2B(uint8_t byte0, uint8_t byte1) = 0;
/// Read a number of bytes on the SPI interface from an NRF device
/// \param[in] reg The NRF device register to read
/// \param[out] dest The buffer to hold the bytes read
/// \param[in] len The number of bytes to read
/// \return The NRF status byte
virtual uint8_t spiBurstRead(uint8_t reg, uint8_t* dest, uint8_t len) = 0;
/// Wrte a number of bytes on the SPI interface to an NRF device
/// \param[in] reg The NRF device register to read
/// \param[out] src The buffer to hold the bytes write
/// \param[in] len The number of bytes to write
/// \return The NRF status byte
virtual uint8_t spiBurstWrite(uint8_t reg, const uint8_t* src, uint8_t len) = 0;
#endif
/// SPI Configuration methods
/// Enable SPI interrupts (if supported)
/// This can be used in an SPI slave to indicate when an SPI message has been received
virtual void attachInterrupt() {};
/// Disable SPI interrupts (if supported)
/// This can be used to diable the SPI interrupt in slaves where that is supported.
virtual void detachInterrupt() {};
/// Initialise the SPI library.
/// Call this after configuring and before using the SPI library
virtual void begin() = 0;
/// Disables the SPI bus (leaving pin modes unchanged).
/// Call this after you have finished using the SPI interface
virtual void end() = 0;
/// Sets the bit order the SPI interface will use
/// Sets the order of the bits shifted out of and into the SPI bus, either
/// LSBFIRST (least-significant bit first) or MSBFIRST (most-significant bit first).
/// \param[in] bitOrder Bit order to be used: one of RHGenericSPI::BitOrder
virtual void setBitOrder(BitOrder bitOrder);
/// Sets the SPI data mode: that is, clock polarity and phase.
/// See the Wikipedia article on SPI for details.
/// \param[in] dataMode The mode to use: one of RHGenericSPI::DataMode
virtual void setDataMode(DataMode dataMode);
/// Sets the SPI clock divider relative to the system clock.
/// On AVR based boards, the dividers available are 2, 4, 8, 16, 32, 64 or 128.
/// The default setting is SPI_CLOCK_DIV4, which sets the SPI clock to one-quarter
/// the frequency of the system clock (4 Mhz for the boards at 16 MHz).
/// \param[in] frequency The data rate to use: one of RHGenericSPI::Frequency
virtual void setFrequency(Frequency frequency);
/// Signal the start of an SPI transaction that must not be interrupted by other SPI actions
/// In subclasses that support transactions this will ensure that other SPI transactions
/// are blocked until this one is completed by endTransaction().
/// Base does nothing
/// Might be overridden in subclass
virtual void beginTransaction(){}
/// Signal the end of an SPI transaction
/// Base does nothing
/// Might be overridden in subclass
virtual void endTransaction(){}
/// Specify the interrupt number of the interrupt that will use SPI transactions
/// Tells the SPI support software that SPI transactions will occur with the interrupt
/// handler assocated with interruptNumber
/// Base does nothing
/// Might be overridden in subclass
/// \param[in] interruptNumber The number of the interrupt
virtual void usingInterrupt(uint8_t interruptNumber){
(void)interruptNumber;
}
protected:
/// The configure SPI Bus frequency, one of RHGenericSPI::Frequency
Frequency _frequency; // Bus frequency, one of RHGenericSPI::Frequency
/// Bit order, one of RHGenericSPI::BitOrder
BitOrder _bitOrder;
/// SPI bus mode, one of RHGenericSPI::DataMode
DataMode _dataMode;
};
#endif

View File

@@ -1,499 +0,0 @@
// RHHardwareSPI.cpp
// Author: Mike McCauley (mikem@airspayce.com)
// Copyright (C) 2011 Mike McCauley
// Contributed by Joanna Rutkowska
// $Id: RHHardwareSPI.cpp,v 1.25 2020/01/05 07:02:23 mikem Exp mikem $
#include <RHHardwareSPI.h>
#ifdef RH_HAVE_HARDWARE_SPI
// Declare a single default instance of the hardware SPI interface class
RHHardwareSPI hardware_spi;
#if (RH_PLATFORM == RH_PLATFORM_STM32) // Maple etc
// Declare an SPI interface to use
HardwareSPI SPI(1);
#elif (RH_PLATFORM == RH_PLATFORM_STM32STD) // STM32F4 Discovery
// Declare an SPI interface to use
HardwareSPI SPI(1);
#elif (RH_PLATFORM == RH_PLATFORM_MONGOOSE_OS) // Mongoose OS platform
HardwareSPI SPI(1);
#endif
// Arduino Due has default SPI pins on central SPI headers, and not on 10, 11, 12, 13
// as per other Arduinos
// http://21stdigitalhome.blogspot.com.au/2013/02/arduino-due-hardware-spi.html
#if defined (__arm__) && !defined(CORE_TEENSY) && !defined(SPI_CLOCK_DIV16) && !defined(RH_PLATFORM_NRF52)
// Arduino Due in 1.5.5 has no definitions for SPI dividers
// SPI clock divider is based on MCK of 84MHz
#define SPI_CLOCK_DIV16 (VARIANT_MCK/84000000) // 1MHz
#define SPI_CLOCK_DIV8 (VARIANT_MCK/42000000) // 2MHz
#define SPI_CLOCK_DIV4 (VARIANT_MCK/21000000) // 4MHz
#define SPI_CLOCK_DIV2 (VARIANT_MCK/10500000) // 8MHz
#define SPI_CLOCK_DIV1 (VARIANT_MCK/5250000) // 16MHz
#endif
RHHardwareSPI::RHHardwareSPI(Frequency frequency, BitOrder bitOrder, DataMode dataMode)
:
RHGenericSPI(frequency, bitOrder, dataMode)
{
}
uint8_t RHHardwareSPI::transfer(uint8_t data)
{
return SPI.transfer(data);
}
#if (RH_PLATFORM == RH_PLATFORM_MONGOOSE_OS)
uint8_t RHHardwareSPI::transfer2B(uint8_t byte0, uint8_t byte1)
{
return SPI.transfer2B(byte0, byte1);
}
uint8_t RHHardwareSPI::spiBurstRead(uint8_t reg, uint8_t* dest, uint8_t len)
{
return SPI.spiBurstRead(reg, dest, len);
}
uint8_t RHHardwareSPI::spiBurstWrite(uint8_t reg, const uint8_t* src, uint8_t len)
{
uint8_t status = SPI.spiBurstWrite(reg, src, len);
return status;
}
#endif
void RHHardwareSPI::attachInterrupt()
{
#if (RH_PLATFORM == RH_PLATFORM_ARDUINO || RH_PLATFORM == RH_PLATFORM_NRF52)
SPI.attachInterrupt();
#endif
}
void RHHardwareSPI::detachInterrupt()
{
#if (RH_PLATFORM == RH_PLATFORM_ARDUINO || RH_PLATFORM == RH_PLATFORM_NRF52)
SPI.detachInterrupt();
#endif
}
void RHHardwareSPI::begin()
{
#if defined(SPI_HAS_TRANSACTION)
// Perhaps this is a uniform interface for SPI?
// Currently Teensy and ESP32 only
uint32_t frequency;
if (_frequency == Frequency16MHz)
frequency = 16000000;
else if (_frequency == Frequency8MHz)
frequency = 8000000;
else if (_frequency == Frequency4MHz)
frequency = 4000000;
else if (_frequency == Frequency2MHz)
frequency = 2000000;
else
frequency = 1000000;
#if ((RH_PLATFORM == RH_PLATFORM_ARDUINO) && defined (__arm__) && (defined(ARDUINO_SAM_DUE) || defined(ARDUINO_ARCH_SAMD))) || defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_ARCH_STM32) || defined(ARDUINO_ARCH_STM32) || defined(NRF52)
// Arduino Due in 1.5.5 has its own BitOrder :-(
// So too does Arduino Zero
// So too does rogerclarkmelbourne/Arduino_STM32
::BitOrder bitOrder;
#elif (RH_PLATFORM == RH_PLATFORM_ATTINY_MEGA)
::BitOrder bitOrder;
#else
uint8_t bitOrder;
#endif
if (_bitOrder == BitOrderLSBFirst)
bitOrder = LSBFIRST;
else
bitOrder = MSBFIRST;
uint8_t dataMode;
if (_dataMode == DataMode0)
dataMode = SPI_MODE0;
else if (_dataMode == DataMode1)
dataMode = SPI_MODE1;
else if (_dataMode == DataMode2)
dataMode = SPI_MODE2;
else if (_dataMode == DataMode3)
dataMode = SPI_MODE3;
else
dataMode = SPI_MODE0;
// Save the settings for use in transactions
_settings = SPISettings(frequency, bitOrder, dataMode);
SPI.begin();
#else // SPI_HAS_TRANSACTION
// Sigh: there are no common symbols for some of these SPI options across all platforms
#if (RH_PLATFORM == RH_PLATFORM_ARDUINO) || (RH_PLATFORM == RH_PLATFORM_UNO32) || (RH_PLATFORM == RH_PLATFORM_CHIPKIT_CORE || RH_PLATFORM == RH_PLATFORM_NRF52)
uint8_t dataMode;
if (_dataMode == DataMode0)
dataMode = SPI_MODE0;
else if (_dataMode == DataMode1)
dataMode = SPI_MODE1;
else if (_dataMode == DataMode2)
dataMode = SPI_MODE2;
else if (_dataMode == DataMode3)
dataMode = SPI_MODE3;
else
dataMode = SPI_MODE0;
#if (RH_PLATFORM == RH_PLATFORM_ARDUINO) && defined(__arm__) && defined(CORE_TEENSY)
// Temporary work-around due to problem where avr_emulation.h does not work properly for the setDataMode() cal
SPCR &= ~SPI_MODE_MASK;
#else
#if ((RH_PLATFORM == RH_PLATFORM_ARDUINO) && defined (__arm__) && defined(ARDUINO_ARCH_SAMD)) || defined(ARDUINO_ARCH_NRF52)
// Zero requires begin() before anything else :-)
SPI.begin();
#endif
SPI.setDataMode(dataMode);
#endif
#if ((RH_PLATFORM == RH_PLATFORM_ARDUINO) && defined (__arm__) && (defined(ARDUINO_SAM_DUE) || defined(ARDUINO_ARCH_SAMD))) || defined(ARDUINO_ARCH_NRF52) || defined (ARDUINO_ARCH_STM32) || defined(ARDUINO_ARCH_STM32)
// Arduino Due in 1.5.5 has its own BitOrder :-(
// So too does Arduino Zero
// So too does rogerclarkmelbourne/Arduino_STM32
::BitOrder bitOrder;
#else
uint8_t bitOrder;
#endif
if (_bitOrder == BitOrderLSBFirst)
bitOrder = LSBFIRST;
else
bitOrder = MSBFIRST;
SPI.setBitOrder(bitOrder);
uint8_t divider;
switch (_frequency)
{
case Frequency1MHz:
default:
#if F_CPU == 8000000
divider = SPI_CLOCK_DIV8;
#else
divider = SPI_CLOCK_DIV16;
#endif
break;
case Frequency2MHz:
#if F_CPU == 8000000
divider = SPI_CLOCK_DIV4;
#else
divider = SPI_CLOCK_DIV8;
#endif
break;
case Frequency4MHz:
#if F_CPU == 8000000
divider = SPI_CLOCK_DIV2;
#else
divider = SPI_CLOCK_DIV4;
#endif
break;
case Frequency8MHz:
divider = SPI_CLOCK_DIV2; // 4MHz on an 8MHz Arduino
break;
case Frequency16MHz:
divider = SPI_CLOCK_DIV2; // Not really 16MHz, only 8MHz. 4MHz on an 8MHz Arduino
break;
}
SPI.setClockDivider(divider);
SPI.begin();
// Teensy requires it to be set _after_ begin()
SPI.setClockDivider(divider);
#elif (RH_PLATFORM == RH_PLATFORM_STM32) // Maple etc
spi_mode dataMode;
// Hmmm, if we do this as a switch, GCC on maple gets v confused!
if (_dataMode == DataMode0)
dataMode = SPI_MODE_0;
else if (_dataMode == DataMode1)
dataMode = SPI_MODE_1;
else if (_dataMode == DataMode2)
dataMode = SPI_MODE_2;
else if (_dataMode == DataMode3)
dataMode = SPI_MODE_3;
else
dataMode = SPI_MODE_0;
uint32 bitOrder;
if (_bitOrder == BitOrderLSBFirst)
bitOrder = LSBFIRST;
else
bitOrder = MSBFIRST;
SPIFrequency frequency; // Yes, I know these are not exact equivalents.
switch (_frequency)
{
case Frequency1MHz:
default:
frequency = SPI_1_125MHZ;
break;
case Frequency2MHz:
frequency = SPI_2_25MHZ;
break;
case Frequency4MHz:
frequency = SPI_4_5MHZ;
break;
case Frequency8MHz:
frequency = SPI_9MHZ;
break;
case Frequency16MHz:
frequency = SPI_18MHZ;
break;
}
SPI.begin(frequency, bitOrder, dataMode);
#elif (RH_PLATFORM == RH_PLATFORM_STM32STD) // STM32F4 discovery
uint8_t dataMode;
if (_dataMode == DataMode0)
dataMode = SPI_MODE0;
else if (_dataMode == DataMode1)
dataMode = SPI_MODE1;
else if (_dataMode == DataMode2)
dataMode = SPI_MODE2;
else if (_dataMode == DataMode3)
dataMode = SPI_MODE3;
else
dataMode = SPI_MODE0;
uint32_t bitOrder;
if (_bitOrder == BitOrderLSBFirst)
bitOrder = LSBFIRST;
else
bitOrder = MSBFIRST;
SPIFrequency frequency; // Yes, I know these are not exact equivalents.
switch (_frequency)
{
case Frequency1MHz:
default:
frequency = SPI_1_3125MHZ;
break;
case Frequency2MHz:
frequency = SPI_2_625MHZ;
break;
case Frequency4MHz:
frequency = SPI_5_25MHZ;
break;
case Frequency8MHz:
frequency = SPI_10_5MHZ;
break;
case Frequency16MHz:
frequency = SPI_21_0MHZ;
break;
}
SPI.begin(frequency, bitOrder, dataMode);
#elif (RH_PLATFORM == RH_PLATFORM_STM32F2) // Photon
uint8_t dataMode;
if (_dataMode == DataMode0)
dataMode = SPI_MODE0;
else if (_dataMode == DataMode1)
dataMode = SPI_MODE1;
else if (_dataMode == DataMode2)
dataMode = SPI_MODE2;
else if (_dataMode == DataMode3)
dataMode = SPI_MODE3;
else
dataMode = SPI_MODE0;
SPI.setDataMode(dataMode);
if (_bitOrder == BitOrderLSBFirst)
SPI.setBitOrder(LSBFIRST);
else
SPI.setBitOrder(MSBFIRST);
switch (_frequency)
{
case Frequency1MHz:
default:
SPI.setClockSpeed(1, MHZ);
break;
case Frequency2MHz:
SPI.setClockSpeed(2, MHZ);
break;
case Frequency4MHz:
SPI.setClockSpeed(4, MHZ);
break;
case Frequency8MHz:
SPI.setClockSpeed(8, MHZ);
break;
case Frequency16MHz:
SPI.setClockSpeed(16, MHZ);
break;
}
// SPI.setClockDivider(SPI_CLOCK_DIV4); // 72MHz / 4MHz = 18MHz
// SPI.setClockSpeed(1, MHZ);
SPI.begin();
#elif (RH_PLATFORM == RH_PLATFORM_ESP8266)
// Requires SPI driver for ESP8266 from https://github.com/esp8266/Arduino/tree/master/libraries/SPI
// Which ppears to be in Arduino Board Manager ESP8266 Community version 2.1.0
// Contributed by David Skinner
// begin comes first
SPI.begin();
// datamode
switch ( _dataMode )
{
case DataMode1:
SPI.setDataMode ( SPI_MODE1 );
break;
case DataMode2:
SPI.setDataMode ( SPI_MODE2 );
break;
case DataMode3:
SPI.setDataMode ( SPI_MODE3 );
break;
case DataMode0:
default:
SPI.setDataMode ( SPI_MODE0 );
break;
}
// bitorder
SPI.setBitOrder(_bitOrder == BitOrderLSBFirst ? LSBFIRST : MSBFIRST);
// frequency (this sets the divider)
switch (_frequency)
{
case Frequency1MHz:
default:
SPI.setFrequency(1000000);
break;
case Frequency2MHz:
SPI.setFrequency(2000000);
break;
case Frequency4MHz:
SPI.setFrequency(4000000);
break;
case Frequency8MHz:
SPI.setFrequency(8000000);
break;
case Frequency16MHz:
SPI.setFrequency(16000000);
break;
}
#elif (RH_PLATFORM == RH_PLATFORM_RASPI) // Raspberry PI
uint8_t dataMode;
if (_dataMode == DataMode0)
dataMode = BCM2835_SPI_MODE0;
else if (_dataMode == DataMode1)
dataMode = BCM2835_SPI_MODE1;
else if (_dataMode == DataMode2)
dataMode = BCM2835_SPI_MODE2;
else if (_dataMode == DataMode3)
dataMode = BCM2835_SPI_MODE3;
uint8_t bitOrder;
if (_bitOrder == BitOrderLSBFirst)
bitOrder = BCM2835_SPI_BIT_ORDER_LSBFIRST;
else
bitOrder = BCM2835_SPI_BIT_ORDER_MSBFIRST;
uint32_t divider;
switch (_frequency)
{
case Frequency1MHz:
default:
divider = BCM2835_SPI_CLOCK_DIVIDER_256;
break;
case Frequency2MHz:
divider = BCM2835_SPI_CLOCK_DIVIDER_128;
break;
case Frequency4MHz:
divider = BCM2835_SPI_CLOCK_DIVIDER_64;
break;
case Frequency8MHz:
divider = BCM2835_SPI_CLOCK_DIVIDER_32;
break;
case Frequency16MHz:
divider = BCM2835_SPI_CLOCK_DIVIDER_16;
break;
}
SPI.begin(divider, bitOrder, dataMode);
#elif (RH_PLATFORM == RH_PLATFORM_MONGOOSE_OS)
uint8_t dataMode = SPI_MODE0;
uint32_t frequency = 4000000; //!!! ESP32/NRF902 works ok at 4MHz but not at 8MHz SPI clock.
uint32_t bitOrder = MSBFIRST;
if (_dataMode == DataMode0) {
dataMode = SPI_MODE0;
} else if (_dataMode == DataMode1) {
dataMode = SPI_MODE1;
} else if (_dataMode == DataMode2) {
dataMode = SPI_MODE2;
} else if (_dataMode == DataMode3) {
dataMode = SPI_MODE3;
}
if (_bitOrder == BitOrderLSBFirst) {
bitOrder = LSBFIRST;
}
if (_frequency == Frequency4MHz)
frequency = 4000000;
else if (_frequency == Frequency2MHz)
frequency = 2000000;
else
frequency = 1000000;
SPI.begin(frequency, bitOrder, dataMode);
#else
#warning RHHardwareSPI does not support this platform yet. Consider adding it and contributing a patch.
#endif
#endif // SPI_HAS_TRANSACTION
}
void RHHardwareSPI::end()
{
return SPI.end();
}
void RHHardwareSPI::beginTransaction()
{
#if defined(SPI_HAS_TRANSACTION)
SPI.beginTransaction(_settings);
#endif
}
void RHHardwareSPI::endTransaction()
{
#if defined(SPI_HAS_TRANSACTION)
SPI.endTransaction();
#endif
}
void RHHardwareSPI::usingInterrupt(uint8_t interrupt)
{
#if defined(SPI_HAS_TRANSACTION) && !defined(RH_MISSING_SPIUSINGINTERRUPT)
SPI.usingInterrupt(interrupt);
#endif
(void)interrupt;
}
#endif

View File

@@ -1,116 +0,0 @@
// RHHardwareSPI.h
// Author: Mike McCauley (mikem@airspayce.com)
// Copyright (C) 2011 Mike McCauley
// Contributed by Joanna Rutkowska
// $Id: RHHardwareSPI.h,v 1.12 2020/01/05 07:02:23 mikem Exp mikem $
#ifndef RHHardwareSPI_h
#define RHHardwareSPI_h
#include <RHGenericSPI.h>
/////////////////////////////////////////////////////////////////////
/// \class RHHardwareSPI RHHardwareSPI.h <RHHardwareSPI.h>
/// \brief Encapsulate a hardware SPI bus interface
///
/// This concrete subclass of GenericSPIClass encapsulates the standard Arduino hardware and other
/// hardware SPI interfaces.
///
/// SPI transactions are supported in development environments that support it with SPI_HAS_TRANSACTION.
class RHHardwareSPI : public RHGenericSPI
{
#ifdef RH_HAVE_HARDWARE_SPI
public:
/// Constructor
/// Creates an instance of a hardware SPI interface, using whatever SPI hardware is available on
/// your processor platform. On Arduino and Uno32, uses SPI. On Maple, uses HardwareSPI.
/// \param[in] frequency One of RHGenericSPI::Frequency to select the SPI bus frequency. The frequency
/// is mapped to the closest available bus frequency on the platform.
/// \param[in] bitOrder Select the SPI bus bit order, one of RHGenericSPI::BitOrderMSBFirst or
/// RHGenericSPI::BitOrderLSBFirst.
/// \param[in] dataMode Selects the SPI bus data mode. One of RHGenericSPI::DataMode
RHHardwareSPI(Frequency frequency = Frequency1MHz, BitOrder bitOrder = BitOrderMSBFirst, DataMode dataMode = DataMode0);
/// Transfer a single octet to and from the SPI interface
/// \param[in] data The octet to send
/// \return The octet read from SPI while the data octet was sent
uint8_t transfer(uint8_t data);
#if (RH_PLATFORM == RH_PLATFORM_MONGOOSE_OS)
/// Transfer (write) 2 bytes on the SPI interface to an NRF device
/// \param[in] byte0 The first byte to be sent on the SPI interface
/// \param[in] byte1 The second byte to be sent on the SPI interface
/// \return The second byte clocked in as the second byte is sent.
uint8_t transfer2B(uint8_t byte0, uint8_t byte1);
/// Read a number of bytes on the SPI interface from an NRF device
/// \param[in] reg The NRF device register to read
/// \param[out] dest The buffer to hold the bytes read
/// \param[in] len The number of bytes to read
/// \return The NRF status byte
uint8_t spiBurstRead(uint8_t reg, uint8_t* dest, uint8_t len);
/// Wrte a number of bytes on the SPI interface to an NRF device
/// \param[in] reg The NRF device register to read
/// \param[out] src The buffer to hold the bytes write
/// \param[in] len The number of bytes to write
/// \return The NRF status byte
uint8_t spiBurstWrite(uint8_t reg, const uint8_t* src, uint8_t len);
#endif
// SPI Configuration methods
/// Enable SPI interrupts
/// This can be used in an SPI slave to indicate when an SPI message has been received
/// It will cause the SPI_STC_vect interrupt vectr to be executed
void attachInterrupt();
/// Disable SPI interrupts
/// This can be used to diable the SPI interrupt in slaves where that is supported.
void detachInterrupt();
/// Initialise the SPI library
/// Call this after configuring the SPI interface and before using it to transfer data.
/// Initializes the SPI bus by setting SCK, MOSI, and SS to outputs, pulling SCK and MOSI low, and SS high.
void begin();
/// Disables the SPI bus (leaving pin modes unchanged).
/// Call this after you have finished using the SPI interface.
void end();
#else
// not supported on ATTiny etc
uint8_t transfer(uint8_t /*data*/) {return 0;}
void begin(){}
void end(){}
#endif
/// Signal the start of an SPI transaction that must not be interrupted by other SPI actions
/// In subclasses that support transactions this will ensure that other SPI transactions
/// are blocked until this one is completed by endTransaction().
/// Uses the underlying SPI transaction support if available as specified by SPI_HAS_TRANSACTION.
virtual void beginTransaction();
/// Signal the end of an SPI transaction
/// Uses the underlying SPI transaction support if available as specified by SPI_HAS_TRANSACTION.
virtual void endTransaction();
/// Specify the interrupt number of the interrupt that will use SPI transactions
/// Tells the SPI support software that SPI transactions will occur with the interrupt
/// handler assocated with interruptNumber
/// Uses the underlying SPI transaction support if available as specified by SPI_HAS_TRANSACTION.
/// \param[in] interruptNumber The number of the interrupt
virtual void usingInterrupt(uint8_t interruptNumber);
protected:
#if defined(SPI_HAS_TRANSACTION)
// Storage for SPI settings used in SPI transactions
SPISettings _settings;
#endif
};
// Built in default instance
extern RHHardwareSPI hardware_spi;
#endif

View File

@@ -1,137 +0,0 @@
// RHNRFSPIDriver.cpp
//
// Copyright (C) 2014 Mike McCauley
// $Id: RHNRFSPIDriver.cpp,v 1.5 2020/01/05 07:02:23 mikem Exp mikem $
#include <RHNRFSPIDriver.h>
RHNRFSPIDriver::RHNRFSPIDriver(uint8_t slaveSelectPin, RHGenericSPI& spi)
:
_spi(spi),
_slaveSelectPin(slaveSelectPin)
{
}
bool RHNRFSPIDriver::init()
{
// start the SPI library with the default speeds etc:
// On Arduino Due this defaults to SPI1 on the central group of 6 SPI pins
_spi.begin();
// Initialise the slave select pin
// On Maple, this must be _after_ spi.begin
pinMode(_slaveSelectPin, OUTPUT);
digitalWrite(_slaveSelectPin, HIGH);
delay(100);
return true;
}
// Low level commands for interfacing with the device
uint8_t RHNRFSPIDriver::spiCommand(uint8_t command)
{
uint8_t status;
ATOMIC_BLOCK_START;
#if (RH_PLATFORM == RH_PLATFORM_MONGOOSE_OS)
status = _spi.transfer(command);
#else
_spi.beginTransaction();
digitalWrite(_slaveSelectPin, LOW);
status = _spi.transfer(command);
digitalWrite(_slaveSelectPin, HIGH);
_spi.endTransaction();
#endif
ATOMIC_BLOCK_END;
return status;
}
uint8_t RHNRFSPIDriver::spiRead(uint8_t reg)
{
uint8_t val;
ATOMIC_BLOCK_START;
#if (RH_PLATFORM == RH_PLATFORM_MONGOOSE_OS)
val = _spi.transfer2B(reg, 0); // Send the address, discard the status, The written value is ignored, reg value is read
#else
_spi.beginTransaction();
digitalWrite(_slaveSelectPin, LOW);
_spi.transfer(reg); // Send the address, discard the status
val = _spi.transfer(0); // The written value is ignored, reg value is read
digitalWrite(_slaveSelectPin, HIGH);
_spi.endTransaction();
#endif
ATOMIC_BLOCK_END;
return val;
}
uint8_t RHNRFSPIDriver::spiWrite(uint8_t reg, uint8_t val)
{
uint8_t status = 0;
ATOMIC_BLOCK_START;
#if (RH_PLATFORM == RH_PLATFORM_MONGOOSE_OS)
status = _spi.transfer2B(reg, val);
#else
_spi.beginTransaction();
digitalWrite(_slaveSelectPin, LOW);
status = _spi.transfer(reg); // Send the address
_spi.transfer(val); // New value follows
#if (RH_PLATFORM == RH_PLATFORM_ARDUINO) && defined(__arm__) && defined(CORE_TEENSY)
// Sigh: some devices, such as MRF89XA dont work properly on Teensy 3.1:
// At 1MHz, the clock returns low _after_ slave select goes high, which prevents SPI
// write working. This delay gixes time for the clock to return low.
delayMicroseconds(5);
#endif
digitalWrite(_slaveSelectPin, HIGH);
_spi.endTransaction();
#endif
ATOMIC_BLOCK_END;
return status;
}
uint8_t RHNRFSPIDriver::spiBurstRead(uint8_t reg, uint8_t* dest, uint8_t len)
{
uint8_t status = 0;
ATOMIC_BLOCK_START;
#if (RH_PLATFORM == RH_PLATFORM_MONGOOSE_OS)
status = _spi.spiBurstRead(reg, dest, len);
#else
_spi.beginTransaction();
digitalWrite(_slaveSelectPin, LOW);
status = _spi.transfer(reg); // Send the start address
while (len--)
*dest++ = _spi.transfer(0);
digitalWrite(_slaveSelectPin, HIGH);
_spi.endTransaction();
#endif
ATOMIC_BLOCK_END;
return status;
}
uint8_t RHNRFSPIDriver::spiBurstWrite(uint8_t reg, const uint8_t* src, uint8_t len)
{
uint8_t status = 0;
ATOMIC_BLOCK_START;
#if (RH_PLATFORM == RH_PLATFORM_MONGOOSE_OS)
status = _spi.spiBurstWrite(reg, src, len);
#else
_spi.beginTransaction();
digitalWrite(_slaveSelectPin, LOW);
status = _spi.transfer(reg); // Send the start address
while (len--)
_spi.transfer(*src++);
digitalWrite(_slaveSelectPin, HIGH);
_spi.endTransaction();
#endif
ATOMIC_BLOCK_END;
return status;
}
void RHNRFSPIDriver::setSlaveSelectPin(uint8_t slaveSelectPin)
{
_slaveSelectPin = slaveSelectPin;
}
void RHNRFSPIDriver::spiUsingInterrupt(uint8_t interruptNumber)
{
_spi.usingInterrupt(interruptNumber);
}

View File

@@ -1,101 +0,0 @@
// RHNRFSPIDriver.h
// Author: Mike McCauley (mikem@airspayce.com)
// Copyright (C) 2014 Mike McCauley
// $Id: RHNRFSPIDriver.h,v 1.5 2017/11/06 00:04:08 mikem Exp $
#ifndef RHNRFSPIDriver_h
#define RHNRFSPIDriver_h
#include <RHGenericDriver.h>
#include <RHHardwareSPI.h>
class RHGenericSPI;
/////////////////////////////////////////////////////////////////////
/// \class RHNRFSPIDriver RHNRFSPIDriver.h <RHNRFSPIDriver.h>
/// \brief Base class for RadioHead drivers that use the SPI bus
/// to communicate with its NRF family transport hardware.
///
/// This class can be subclassed by Drivers that require to use the SPI bus.
/// It can be configured to use either the RHHardwareSPI class (if there is one available on the platform)
/// of the bitbanged RHSoftwareSPI class. The dfault behaviour is to use a pre-instantiated built-in RHHardwareSPI
/// interface.
///
/// SPI bus access is protected by ATOMIC_BLOCK_START and ATOMIC_BLOCK_END, which will ensure interrupts
/// are disabled during access.
///
/// The read and write routines use SPI conventions as used by Nordic NRF radios and otehr devices,
/// but these can be overriden
/// in subclasses if necessary.
///
/// Application developers are not expected to instantiate this class directly:
/// it is for the use of Driver developers.
class RHNRFSPIDriver : public RHGenericDriver
{
public:
/// Constructor
/// \param[in] slaveSelectPin The controller pin to use to select the desired SPI device. This pin will be driven LOW
/// during SPI communications with the SPI device that uis iused by this Driver.
/// \param[in] spi Reference to the SPI interface to use. The default is to use a default built-in Hardware interface.
RHNRFSPIDriver(uint8_t slaveSelectPin = SS, RHGenericSPI& spi = hardware_spi);
/// Initialise the Driver transport hardware and software.
/// Make sure the Driver is properly configured before calling init().
/// \return true if initialisation succeeded.
bool init();
/// Sends a single command to the device
/// \param[in] command The command code to send to the device.
/// \return Some devices return a status byte during the first data transfer. This byte is returned.
/// it may or may not be meaningfule depending on the the type of device being accessed.
uint8_t spiCommand(uint8_t command);
/// Reads a single register from the SPI device
/// \param[in] reg Register number
/// \return The value of the register
uint8_t spiRead(uint8_t reg);
/// Writes a single byte to the SPI device
/// \param[in] reg Register number
/// \param[in] val The value to write
/// \return Some devices return a status byte during the first data transfer. This byte is returned.
/// it may or may not be meaningfule depending on the the type of device being accessed.
uint8_t spiWrite(uint8_t reg, uint8_t val);
/// Reads a number of consecutive registers from the SPI device using burst read mode
/// \param[in] reg Register number of the first register
/// \param[in] dest Array to write the register values to. Must be at least len bytes
/// \param[in] len Number of bytes to read
/// \return Some devices return a status byte during the first data transfer. This byte is returned.
/// it may or may not be meaningfule depending on the the type of device being accessed.
uint8_t spiBurstRead(uint8_t reg, uint8_t* dest, uint8_t len);
/// Write a number of consecutive registers using burst write mode
/// \param[in] reg Register number of the first register
/// \param[in] src Array of new register values to write. Must be at least len bytes
/// \param[in] len Number of bytes to write
/// \return Some devices return a status byte during the first data transfer. This byte is returned.
/// it may or may not be meaningfule depending on the the type of device being accessed.
uint8_t spiBurstWrite(uint8_t reg, const uint8_t* src, uint8_t len);
/// Set or change the pin to be used for SPI slave select.
/// This can be called at any time to change the
/// pin that will be used for slave select in subsquent SPI operations.
/// \param[in] slaveSelectPin The pin to use
void setSlaveSelectPin(uint8_t slaveSelectPin);
/// Set the SPI interrupt number
/// If SPI transactions can occur within an interrupt, tell the low level SPI
/// interface which interrupt is used
/// \param[in] interruptNumber the interrupt number
void spiUsingInterrupt(uint8_t interruptNumber);
protected:
/// Reference to the RHGenericSPI instance to use to trasnfer data with teh SPI device
RHGenericSPI& _spi;
/// The pin number of the Slave Select pin that is used to select the desired device.
uint8_t _slaveSelectPin;
};
#endif

View File

@@ -1,95 +0,0 @@
// RHSPIDriver.cpp
//
// Copyright (C) 2014 Mike McCauley
// $Id: RHSPIDriver.cpp,v 1.11 2017/11/06 00:04:08 mikem Exp $
#include <RHSPIDriver.h>
RHSPIDriver::RHSPIDriver(uint8_t slaveSelectPin, RHGenericSPI& spi)
:
_spi(spi),
_slaveSelectPin(slaveSelectPin)
{
}
bool RHSPIDriver::init()
{
// start the SPI library with the default speeds etc:
// On Arduino Due this defaults to SPI1 on the central group of 6 SPI pins
_spi.begin();
// Initialise the slave select pin
// On Maple, this must be _after_ spi.begin
pinMode(_slaveSelectPin, OUTPUT);
digitalWrite(_slaveSelectPin, HIGH);
delay(100);
return true;
}
uint8_t RHSPIDriver::spiRead(uint8_t reg)
{
uint8_t val;
ATOMIC_BLOCK_START;
digitalWrite(_slaveSelectPin, LOW);
_spi.transfer(reg & ~RH_SPI_WRITE_MASK); // Send the address with the write mask off
val = _spi.transfer(0); // The written value is ignored, reg value is read
digitalWrite(_slaveSelectPin, HIGH);
ATOMIC_BLOCK_END;
return val;
}
uint8_t RHSPIDriver::spiWrite(uint8_t reg, uint8_t val)
{
uint8_t status = 0;
ATOMIC_BLOCK_START;
_spi.beginTransaction();
digitalWrite(_slaveSelectPin, LOW);
status = _spi.transfer(reg | RH_SPI_WRITE_MASK); // Send the address with the write mask on
_spi.transfer(val); // New value follows
digitalWrite(_slaveSelectPin, HIGH);
_spi.endTransaction();
ATOMIC_BLOCK_END;
return status;
}
uint8_t RHSPIDriver::spiBurstRead(uint8_t reg, uint8_t* dest, uint8_t len)
{
uint8_t status = 0;
ATOMIC_BLOCK_START;
_spi.beginTransaction();
digitalWrite(_slaveSelectPin, LOW);
status = _spi.transfer(reg & ~RH_SPI_WRITE_MASK); // Send the start address with the write mask off
while (len--)
*dest++ = _spi.transfer(0);
digitalWrite(_slaveSelectPin, HIGH);
_spi.endTransaction();
ATOMIC_BLOCK_END;
return status;
}
uint8_t RHSPIDriver::spiBurstWrite(uint8_t reg, const uint8_t* src, uint8_t len)
{
uint8_t status = 0;
ATOMIC_BLOCK_START;
_spi.beginTransaction();
digitalWrite(_slaveSelectPin, LOW);
status = _spi.transfer(reg | RH_SPI_WRITE_MASK); // Send the start address with the write mask on
while (len--)
_spi.transfer(*src++);
digitalWrite(_slaveSelectPin, HIGH);
_spi.endTransaction();
ATOMIC_BLOCK_END;
return status;
}
void RHSPIDriver::setSlaveSelectPin(uint8_t slaveSelectPin)
{
_slaveSelectPin = slaveSelectPin;
}
void RHSPIDriver::spiUsingInterrupt(uint8_t interruptNumber)
{
_spi.usingInterrupt(interruptNumber);
}

View File

@@ -1,100 +0,0 @@
// RHSPIDriver.h
// Author: Mike McCauley (mikem@airspayce.com)
// Copyright (C) 2014 Mike McCauley
// $Id: RHSPIDriver.h,v 1.14 2019/09/06 04:40:40 mikem Exp $
#ifndef RHSPIDriver_h
#define RHSPIDriver_h
#include <RHGenericDriver.h>
#include <RHHardwareSPI.h>
// This is the bit in the SPI address that marks it as a write
#define RH_SPI_WRITE_MASK 0x80
class RHGenericSPI;
/////////////////////////////////////////////////////////////////////
/// \class RHSPIDriver RHSPIDriver.h <RHSPIDriver.h>
/// \brief Base class for RadioHead drivers that use the SPI bus
/// to communicate with its transport hardware.
///
/// This class can be subclassed by Drivers that require to use the SPI bus.
/// It can be configured to use either the RHHardwareSPI class (if there is one available on the platform)
/// of the bitbanged RHSoftwareSPI class. The default behaviour is to use a pre-instantiated built-in RHHardwareSPI
/// interface.
///
/// SPI bus access is protected by ATOMIC_BLOCK_START and ATOMIC_BLOCK_END, which will ensure interrupts
/// are disabled during access.
///
/// The read and write routines implement commonly used SPI conventions: specifically that the MSB
/// of the first byte transmitted indicates that it is a write and the remaining bits indicate the rehgister to access)
/// This can be overriden
/// in subclasses if necessaryor an alternative class, RHNRFSPIDriver can be used to access devices like
/// Nordic NRF series radios, which have different requirements.
///
/// Application developers are not expected to instantiate this class directly:
/// it is for the use of Driver developers.
class RHSPIDriver : public RHGenericDriver
{
public:
/// Constructor
/// \param[in] slaveSelectPin The controler pin to use to select the desired SPI device. This pin will be driven LOW
/// during SPI communications with the SPI device that uis iused by this Driver.
/// \param[in] spi Reference to the SPI interface to use. The default is to use a default built-in Hardware interface.
RHSPIDriver(uint8_t slaveSelectPin = SS, RHGenericSPI& spi = hardware_spi);
/// Initialise the Driver transport hardware and software.
/// Make sure the Driver is properly configured before calling init().
/// \return true if initialisation succeeded.
bool init();
/// Reads a single register from the SPI device
/// \param[in] reg Register number
/// \return The value of the register
uint8_t spiRead(uint8_t reg);
/// Writes a single byte to the SPI device
/// \param[in] reg Register number
/// \param[in] val The value to write
/// \return Some devices return a status byte during the first data transfer. This byte is returned.
/// it may or may not be meaningfule depending on the the type of device being accessed.
uint8_t spiWrite(uint8_t reg, uint8_t val);
/// Reads a number of consecutive registers from the SPI device using burst read mode
/// \param[in] reg Register number of the first register
/// \param[in] dest Array to write the register values to. Must be at least len bytes
/// \param[in] len Number of bytes to read
/// \return Some devices return a status byte during the first data transfer. This byte is returned.
/// it may or may not be meaningfule depending on the the type of device being accessed.
uint8_t spiBurstRead(uint8_t reg, uint8_t* dest, uint8_t len);
/// Write a number of consecutive registers using burst write mode
/// \param[in] reg Register number of the first register
/// \param[in] src Array of new register values to write. Must be at least len bytes
/// \param[in] len Number of bytes to write
/// \return Some devices return a status byte during the first data transfer. This byte is returned.
/// it may or may not be meaningfule depending on the the type of device being accessed.
uint8_t spiBurstWrite(uint8_t reg, const uint8_t* src, uint8_t len);
/// Set or change the pin to be used for SPI slave select.
/// This can be called at any time to change the
/// pin that will be used for slave select in subsquent SPI operations.
/// \param[in] slaveSelectPin The pin to use
void setSlaveSelectPin(uint8_t slaveSelectPin);
/// Set the SPI interrupt number
/// If SPI transactions can occur within an interrupt, tell the low level SPI
/// interface which interrupt is used
/// \param[in] interruptNumber the interrupt number
void spiUsingInterrupt(uint8_t interruptNumber);
protected:
/// Reference to the RHGenericSPI instance to use to transfer data with the SPI device
RHGenericSPI& _spi;
/// The pin number of the Slave Select pin that is used to select the desired device.
uint8_t _slaveSelectPin;
};
#endif

View File

@@ -1,166 +0,0 @@
// SoftwareSPI.cpp
// Author: Chris Lapa (chris@lapa.com.au)
// Copyright (C) 2014 Chris Lapa
// Contributed by Chris Lapa
#include <RHSoftwareSPI.h>
RHSoftwareSPI::RHSoftwareSPI(Frequency frequency, BitOrder bitOrder, DataMode dataMode)
:
RHGenericSPI(frequency, bitOrder, dataMode)
{
setPins(12, 11, 13);
}
// Caution: on Arduino Uno and many other CPUs, digitalWrite is quite slow, taking about 4us
// digitalWrite is also slow, taking about 3.5us
// resulting in very slow SPI bus speeds using this technique, up to about 120us per octet of transfer
uint8_t RHSoftwareSPI::transfer(uint8_t data)
{
uint8_t readData;
uint8_t writeData;
uint8_t builtReturn;
uint8_t mask;
if (_bitOrder == BitOrderMSBFirst)
{
mask = 0x80;
}
else
{
mask = 0x01;
}
builtReturn = 0;
readData = 0;
for (uint8_t count=0; count<8; count++)
{
if (data & mask)
{
writeData = HIGH;
}
else
{
writeData = LOW;
}
if (_clockPhase == 1)
{
// CPHA=1, miso/mosi changing state now
digitalWrite(_mosi, writeData);
digitalWrite(_sck, ~_clockPolarity);
delayPeriod();
// CPHA=1, miso/mosi stable now
readData = digitalRead(_miso);
digitalWrite(_sck, _clockPolarity);
delayPeriod();
}
else
{
// CPHA=0, miso/mosi changing state now
digitalWrite(_mosi, writeData);
digitalWrite(_sck, _clockPolarity);
delayPeriod();
// CPHA=0, miso/mosi stable now
readData = digitalRead(_miso);
digitalWrite(_sck, ~_clockPolarity);
delayPeriod();
}
if (_bitOrder == BitOrderMSBFirst)
{
mask >>= 1;
builtReturn |= (readData << (7 - count));
}
else
{
mask <<= 1;
builtReturn |= (readData << count);
}
}
digitalWrite(_sck, _clockPolarity);
return builtReturn;
}
/// Initialise the SPI library
void RHSoftwareSPI::begin()
{
if (_dataMode == DataMode0 ||
_dataMode == DataMode1)
{
_clockPolarity = LOW;
}
else
{
_clockPolarity = HIGH;
}
if (_dataMode == DataMode0 ||
_dataMode == DataMode2)
{
_clockPhase = 0;
}
else
{
_clockPhase = 1;
}
digitalWrite(_sck, _clockPolarity);
// Caution: these counts assume that digitalWrite is very fast, which is usually not true
switch (_frequency)
{
case Frequency1MHz:
_delayCounts = 8;
break;
case Frequency2MHz:
_delayCounts = 4;
break;
case Frequency4MHz:
_delayCounts = 2;
break;
case Frequency8MHz:
_delayCounts = 1;
break;
case Frequency16MHz:
_delayCounts = 0;
break;
}
}
/// Disables the SPI bus usually, in this case
/// there is no hardware controller to disable.
void RHSoftwareSPI::end() { }
/// Sets the pins used by this SoftwareSPIClass instance.
/// \param[in] miso master in slave out pin used
/// \param[in] mosi master out slave in pin used
/// \param[in] sck clock pin used
void RHSoftwareSPI::setPins(uint8_t miso, uint8_t mosi, uint8_t sck)
{
_miso = miso;
_mosi = mosi;
_sck = sck;
pinMode(_miso, INPUT);
pinMode(_mosi, OUTPUT);
pinMode(_sck, OUTPUT);
digitalWrite(_sck, _clockPolarity);
}
void RHSoftwareSPI::delayPeriod()
{
for (uint8_t count = 0; count < _delayCounts; count++)
{
__asm__ __volatile__ ("nop");
}
}

View File

@@ -1,90 +0,0 @@
// SoftwareSPI.h
// Author: Chris Lapa (chris@lapa.com.au)
// Copyright (C) 2014 Chris Lapa
// Contributed by Chris Lapa
#ifndef RHSoftwareSPI_h
#define RHSoftwareSPI_h
#include <RHGenericSPI.h>
/////////////////////////////////////////////////////////////////////
/// \class RHSoftwareSPI RHSoftwareSPI.h <RHSoftwareSPI.h>
/// \brief Encapsulate a software SPI interface
///
/// This concrete subclass of RHGenericSPI enapsulates a bit-banged software SPI interface.
/// Caution: this software SPI interface will be much slower than hardware SPI on most
/// platforms.
///
/// SPI transactions are not supported, and associated functions do nothing.
///
/// \par Usage
///
/// Usage varies slightly depending on what driver you are using.
///
/// For RF22, for example:
/// \code
/// #include <RHSoftwareSPI.h>
/// RHSoftwareSPI spi;
/// RH_RF22 driver(SS, 2, spi);
/// RHReliableDatagram(driver, CLIENT_ADDRESS);
/// void setup()
/// {
/// spi.setPins(6, 5, 7); // Or whatever SPI pins you need
/// ....
/// }
/// \endcode
class RHSoftwareSPI : public RHGenericSPI
{
public:
/// Constructor
/// Creates an instance of a bit-banged software SPI interface.
/// Sets the SPI pins to the defaults of
/// MISO = 12, MOSI = 11, SCK = 13. If you need other assigments, call setPins() before
/// calling manager.init() or driver.init().
/// \param[in] frequency One of RHGenericSPI::Frequency to select the SPI bus frequency. The frequency
/// is mapped to the closest available bus frequency on the platform. CAUTION: the achieved
/// frequency will almost certainly be very much slower on most platforms. eg on Arduino Uno, the
/// the clock rate is likely to be at best around 46kHz.
/// \param[in] bitOrder Select the SPI bus bit order, one of RHGenericSPI::BitOrderMSBFirst or
/// RHGenericSPI::BitOrderLSBFirst.
/// \param[in] dataMode Selects the SPI bus data mode. One of RHGenericSPI::DataMode
RHSoftwareSPI(Frequency frequency = Frequency1MHz, BitOrder bitOrder = BitOrderMSBFirst, DataMode dataMode = DataMode0);
/// Transfer a single octet to and from the SPI interface
/// \param[in] data The octet to send
/// \return The octet read from SPI while the data octet was sent.
uint8_t transfer(uint8_t data);
/// Initialise the software SPI library
/// Call this after configuring the SPI interface and before using it to transfer data.
/// Initializes the SPI bus by setting SCK, MOSI, and SS to outputs, pulling SCK and MOSI low, and SS high.
void begin();
/// Disables the SPI bus usually, in this case
/// there is no hardware controller to disable.
void end();
/// Sets the pins used by this SoftwareSPIClass instance.
/// The defaults are: MISO = 12, MOSI = 11, SCK = 13.
/// \param[in] miso master in slave out pin used
/// \param[in] mosi master out slave in pin used
/// \param[in] sck clock pin used
void setPins(uint8_t miso = 12, uint8_t mosi = 11, uint8_t sck = 13);
private:
/// Delay routine for bus timing.
void delayPeriod();
private:
uint8_t _miso;
uint8_t _mosi;
uint8_t _sck;
uint8_t _delayCounts;
uint8_t _clockPolarity;
uint8_t _clockPhase;
};
#endif

Some files were not shown because too many files have changed in this diff Show More