Compare commits
109
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
189ed79d46 | ||
|
|
be2af61dfe | ||
|
|
54af8ad2a9 | ||
|
|
c01c2ed3ac | ||
|
|
abb2dea321 | ||
|
|
64ccc4e289 | ||
|
|
85e867e923 | ||
|
|
c4c5d43bc4 | ||
|
|
dbc9659e9a | ||
|
|
83c827ce85 | ||
|
|
7290bf0c7d | ||
|
|
cc1a944988 | ||
|
|
a6a6bef371 | ||
|
|
c4cc3dd1ec | ||
|
|
d81bbe56a0 | ||
|
|
d880a48b85 | ||
|
|
274bd6ddbf | ||
|
|
fc4e5ed54c | ||
|
|
37f4ceff85 | ||
|
|
4d8478de98 | ||
|
|
f434123e99 | ||
|
|
0bb202327a | ||
|
|
9faba8f184 | ||
|
|
6af9774976 | ||
|
|
f8d03804e1 | ||
|
|
e65c3e3240 | ||
|
|
fc02d8fbcb | ||
|
|
cf63ec9493 | ||
|
|
72d44a17d4 | ||
|
|
ba181da94a | ||
|
|
a115626afd | ||
|
|
3b5b7a1642 | ||
|
|
5811cf9f02 | ||
|
|
9d9145a1c2 | ||
|
|
ef95462345 | ||
|
|
769711ff81 | ||
|
|
b934a1286e | ||
|
|
a96ecd8b5b | ||
|
|
d6c218c928 | ||
|
|
e8390ebc7b | ||
|
|
a2fa4caa3f | ||
|
|
65580c76d0 | ||
|
|
e16dad778c | ||
|
|
b4ee9ecfb9 | ||
|
|
67c7fc070e | ||
|
|
a922d0711d | ||
|
|
b8d467fbab | ||
|
|
cd9b60495d | ||
|
|
7af8f4dfa3 | ||
|
|
0eaa11c56f | ||
|
|
51a6cb8982 | ||
|
|
824f8c1349 | ||
|
|
55531993bd | ||
|
|
9013d99265 | ||
|
|
1bab9c861c | ||
|
|
eb7fec6f1d | ||
|
|
5d4a5dce36 | ||
|
|
42f2c1ece5 | ||
|
|
b85e43e0ae | ||
|
|
8ab1d495e2 | ||
|
|
0ab6aadf7c | ||
|
|
082be00ade | ||
|
|
5e599f143c | ||
|
|
53a55f3a13 | ||
|
|
cd7a8d0411 | ||
|
|
4f3bd4b57c | ||
|
|
5fb83c9bf7 | ||
|
|
50421ad405 | ||
|
|
5395214ef2 | ||
|
|
5824c9a6c0 | ||
|
|
55f14d968f | ||
|
|
cc0ba10cf1 | ||
|
|
8b69f09ddf | ||
|
|
b428ecf31f | ||
|
|
ab11421c92 | ||
|
|
4e8d6de7d7 | ||
|
|
f4229bb185 | ||
|
|
8c9144f785 | ||
|
|
61b09e9445 | ||
|
|
6cef056488 | ||
|
|
aaeccd121c | ||
|
|
4b8d704455 | ||
|
|
51ab76ecc4 | ||
|
|
cc3cf18573 | ||
|
|
a93412216a | ||
|
|
0f66210478 | ||
|
|
7da0a5f7ec | ||
|
|
29e62b9ce2 | ||
|
|
a0bb332ce5 | ||
|
|
7f15205e29 | ||
|
|
466caebd9a | ||
|
|
7b31fc8ef9 | ||
|
|
79f2d65a64 | ||
|
|
78fe83f065 | ||
|
|
c7f9fa95e1 | ||
|
|
01fc05f496 | ||
|
|
33bee48d38 | ||
|
|
e877b135e8 | ||
|
|
5523daad9d | ||
|
|
ef45cb3ae0 | ||
|
|
f9fa913d9e | ||
|
|
7ed2b17b35 | ||
|
|
6e708dc0ec | ||
|
|
16b81d2a6c | ||
|
|
cef23fa7d9 | ||
|
|
ac8b7b31fe | ||
|
|
8d0a17bc39 | ||
|
|
78e307c495 | ||
|
|
bc655c8797 |
No files matched your search
@@ -1,33 +1,69 @@
|
||||
## About MeshCore
|
||||
|
||||
MeshCore is a portable C++ library which provides classes for adding multi-hop packet routing to embedded projects typically employing packet radios like LoRa.
|
||||
MeshCore is a lightweight, portable C++ library that enables multi-hop packet routing for embedded projects using LoRa and other packet radios. It is designed for developers who want to create resilient, decentralized communication networks that work without the internet.
|
||||
|
||||
At present it is mostly aimed at Arduino projects, using the [PlatformIO](https://docs.platformio.org) tools, but could potentially be integrated into other environments.
|
||||
## 🔍 What is MeshCore?
|
||||
|
||||
## Getting Started
|
||||
MeshCore now supports a range of LoRa devices, allowing for easy flashing without the need to compile firmware manually. Users can flash a pre-built binary using tools like Adafruit ESPTool and interact with the network through a serial console.
|
||||
MeshCore provides the ability to create wireless mesh networks, similar to Meshtastic and Reticulum but with a focus on lightweight multi-hop packet routing for embedded projects. Unlike Meshtastic, which is tailored for casual LoRa communication, or Reticulum, which offers advanced networking, MeshCore balances simplicity with scalability, making it ideal for custom embedded solutions., where devices (nodes) can communicate over long distances by relaying messages through intermediate nodes. This is especially useful in off-grid, emergency, or tactical situations where traditional communication infrastructure is unavailable.
|
||||
|
||||
You'll need to install PlatformIO, and an IDE in which it runs, like VSCode. Once installed, you should just be able to open this folder as a project, and it will read the platformio.ini file, and bring in all the required dependencies.
|
||||
## ⚡ Key Features
|
||||
|
||||
There are a number of build environments defined in the platformio.ini file, all targeting the Heltec V3 LoRa boards. For example, **[env:Heltec_v3_chat_alice]** is the target for building/running the 'secure chat' sample app as the user 'Alice'. There is a similar env, configured to run the secure chat as the user 'Bob'.
|
||||
* Multi-Hop Packet Routing – Devices can forward messages across multiple nodes, extending range beyond a single radio's reach. MeshCore supports up to a configurable number of hops to balance network efficiency and prevent excessive traffic.
|
||||
* Supports LoRa Radios – Works with Heltec, RAK Wireless, and other LoRa-based hardware.
|
||||
* Decentralized & Resilient – No central server or internet required; the network is self-healing.
|
||||
* Low Power Consumption – Ideal for battery-powered or solar-powered devices.
|
||||
* Simple to Deploy – Pre-built example applications make it easy to get started.
|
||||
|
||||
Try running these two examples first, flashing to two separate Heltec V3's, and use the Serial Monitor to interact with the *very basic* command-line interface.
|
||||
## 🎯 What Can You Use MeshCore For?
|
||||
|
||||
## Other Example Apps
|
||||
* Off-Grid Communication: Stay connected even in remote areas.
|
||||
* Emergency Response & Disaster Recovery: Set up instant networks where infrastructure is down.
|
||||
* Outdoor Activities: Hiking, camping, and adventure racing communication.
|
||||
* Tactical & Security Applications: Military, law enforcement, and private security use cases.
|
||||
* IoT & Sensor Networks: Collect data from remote sensors and relay it back to a central location.
|
||||
|
||||
There is also a pair of examples, **'ping_client'** and **'ping_server'** which has some very basic constructs for setting up a node in a 'server'-like role, and another as client.
|
||||
## 🚀 How to Get Started
|
||||
|
||||
There is also a **'simple_repeater'** example, which should function as a basic repeater to ALL of the various samples, like the chat ones. It also defines a few examples of some 'remote admin', like setting the clock. The **'test_admin'** example is an example of an app that remotely monitors and sends commands to the 'simple_repeater' nodes.
|
||||
Flash the Firmware: Download the pre-built firmware binary for Heltec V3 and flash it using Adafruit ESPTool.
|
||||
Install [PlatformIO](https://docs.platformio.org) in Visual Studio Code (optional for developers who want to modify the firmware).
|
||||
Download & Open the MeshCore repository.
|
||||
Select a Sample Application: Choose from chat, ping, repeater, or admin test tools.
|
||||
Monitor & Communicate using the Serial Monitor (e.g., Serial USB Terminal on Android).
|
||||
|
||||
📁 Included Example Applications
|
||||
* 📡 Terminal Chat: Secure text communication between devices.
|
||||
* 📡 Simple Repeater: Extends network coverage by relaying messages.
|
||||
* 📡 Companion Radio: For use with an external chat app, over BLE or USB.
|
||||
* 📡 Room Server: A simple BBS server for shared Posts.
|
||||
* 📡 Ping Client, Ping Server & Client: Basic client/server example.
|
||||
* 📡 Test Admin: Monitors and manages repeaters remotely.
|
||||
|
||||
## 🛠 Hardware Compatibility
|
||||
|
||||
MeshCore is designed for use with:
|
||||
* Heltec V3 LoRa Boards
|
||||
* RAK4631
|
||||
* XiaoS3 WIO (sx1262 combo)
|
||||
* XiaoC3 (plus external sx126x module)
|
||||
* LilyGo T3S3
|
||||
* Heltec T114
|
||||
* Station G2
|
||||
|
||||
## 📜 License
|
||||
MeshCore is open-source software released under the MIT License. You are free to use, modify, and distribute it for personal and commercial projects.
|
||||
|
||||
## 📞 Get Support
|
||||
|
||||
Check out the GitHub Issues page to report bugs or request features.
|
||||
|
||||
You will be able to find additional guides and components at [my site](https://buymeacoffee.com/ripplebiz), or [join Andy Kirby's Discord](https://discord.gg/GBxVx2JMAy) for discussions.
|
||||
|
||||
## RAK Wireless Board Support in PlatformIO
|
||||
|
||||
Before building/flashing the RAK4631 targets in this project, there is, unfortunately, some patching you have to do to your platformIO packages to make it work. There is a guide here on the process:
|
||||
https://learn.rakwireless.com/hc/en-us/articles/26687276346775-How-To-Perform-Installation-of-Board-Support-Package-in-PlatformIO
|
||||
|
||||
## To-Do's
|
||||
[RAK Wireless: How to Perform Installation of Board Support Package in PlatformIO](https://learn.rakwireless.com/hc/en-us/articles/26687276346775-How-To-Perform-Installation-of-Board-Support-Package-in-PlatformIO)
|
||||
|
||||
Will hopefully figure out how to make this a registered PlatformIO library, so it can just be added in **lib_deps** in your own project.
|
||||
|
||||
## More Resources
|
||||
|
||||
You will be able to find additional guides and components at [my site](https://buymeacoffee.com/ripplebiz), or [join Andy Kirby's Discord](https://discord.gg/GBxVx2JMAy) for discussions.
|
||||
After building, you will need to convert the output firmware.hex file into a .uf2 file you can copy over to your RAK4631 device (after doing a full erase) by using the command `uf2conv.py -f 0xADA52840 -c firmware.hex` with the python script available from:
|
||||
[GitHub: Microsoft - uf2](https://github.com/Microsoft/uf2/blob/master/utils/uf2conv.py)
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
/* Linker script to configure memory regions. */
|
||||
|
||||
SEARCH_DIR(.)
|
||||
GROUP(-lgcc -lc -lnosys)
|
||||
|
||||
MEMORY
|
||||
{
|
||||
FLASH (rx) : ORIGIN = 0x27000, LENGTH = 0xED000 - 0x27000
|
||||
|
||||
/* SRAM required by Softdevice depend on
|
||||
* - Attribute Table Size (Number of Services and Characteristics)
|
||||
* - Vendor UUID count
|
||||
* - Max ATT MTU
|
||||
* - Concurrent connection peripheral + central + secure links
|
||||
* - Event Len, HVN queue, Write CMD queue
|
||||
*/
|
||||
RAM (rwx) : ORIGIN = 0x20006000, LENGTH = 0x20040000 - 0x20006000
|
||||
}
|
||||
|
||||
SECTIONS
|
||||
{
|
||||
. = ALIGN(4);
|
||||
.svc_data :
|
||||
{
|
||||
PROVIDE(__start_svc_data = .);
|
||||
KEEP(*(.svc_data))
|
||||
PROVIDE(__stop_svc_data = .);
|
||||
} > RAM
|
||||
|
||||
.fs_data :
|
||||
{
|
||||
PROVIDE(__start_fs_data = .);
|
||||
KEEP(*(.fs_data))
|
||||
PROVIDE(__stop_fs_data = .);
|
||||
} > RAM
|
||||
} INSERT AFTER .data;
|
||||
|
||||
INCLUDE "nrf52_common.ld"
|
||||
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"build": {
|
||||
"arduino": {
|
||||
"ldscript": "esp32s3_out.ld",
|
||||
"partitions": "default.csv",
|
||||
"memory_type": "qio_qspi"
|
||||
},
|
||||
"core": "esp32",
|
||||
"extra_flags": [
|
||||
"-DARDUINO_LILYGO_T3_S3_V1_X",
|
||||
"-DBOARD_HAS_PSRAM",
|
||||
"-DARDUINO_USB_CDC_ON_BOOT=1",
|
||||
"-DARDUINO_RUNNING_CORE=1",
|
||||
"-DARDUINO_EVENT_RUNNING_CORE=1",
|
||||
"-DARDUINO_USB_MODE=1"
|
||||
],
|
||||
"f_cpu": "240000000L",
|
||||
"f_flash": "80000000L",
|
||||
"flash_mode": "qio",
|
||||
"mcu": "esp32s3",
|
||||
"variant": "esp32s3"
|
||||
},
|
||||
"connectivity": [
|
||||
"wifi"
|
||||
],
|
||||
"debug": {
|
||||
"openocd_target": "esp32s3.cfg"
|
||||
},
|
||||
"frameworks": [
|
||||
"arduino",
|
||||
"espidf"
|
||||
],
|
||||
"name": "LilyGo T3-S3 Radio",
|
||||
"upload": {
|
||||
"flash_size": "4MB",
|
||||
"maximum_ram_size": 327680,
|
||||
"maximum_size": 4194304,
|
||||
"use_1200bps_touch": true,
|
||||
"wait_for_upload_port": true,
|
||||
"require_upload_port": true,
|
||||
"speed": 460800
|
||||
},
|
||||
"url": "https://www.lilygo.cc",
|
||||
"vendor": "LilyGo"
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"build": {
|
||||
"arduino": {
|
||||
"ldscript": "nrf52840_s140_v7.ld"
|
||||
},
|
||||
"core": "nRF5",
|
||||
"cpu": "cortex-m4",
|
||||
"extra_flags": "-DARDUINO_WIO_WM1110 -DNRF52840_XXAA",
|
||||
"f_cpu": "64000000L",
|
||||
"hwids": [
|
||||
["0x239A", "0x8029"],
|
||||
["0x239A", "0x0029"],
|
||||
["0x239A", "0x002A"],
|
||||
["0x239A", "0x802A"]
|
||||
],
|
||||
"usb_product": "T1000-E-BOOT",
|
||||
"mcu": "nrf52840",
|
||||
"variant": "Seeed_T1000-E",
|
||||
"bsp": {
|
||||
"name": "adafruit"
|
||||
},
|
||||
"softdevice": {
|
||||
"sd_flags": "-DS140",
|
||||
"sd_name": "s140",
|
||||
"sd_version": "7.3.0",
|
||||
"sd_fwid": "0x0123"
|
||||
},
|
||||
"bootloader": {
|
||||
"settings_addr": "0xFF000"
|
||||
}
|
||||
},
|
||||
"connectivity": ["bluetooth"],
|
||||
"debug": {
|
||||
"jlink_device": "nRF52840_xxAA",
|
||||
"svd_path": "nrf52840.svd"
|
||||
},
|
||||
"frameworks": ["arduino"],
|
||||
"name": "Seeed T1000-E",
|
||||
"upload": {
|
||||
"maximum_ram_size": 248832,
|
||||
"maximum_size": 815104,
|
||||
"speed": 115200,
|
||||
"protocol": "nrfutil",
|
||||
"protocols": [
|
||||
"jlink",
|
||||
"nrfjprog",
|
||||
"nrfutil",
|
||||
"stlink",
|
||||
"cmsis-dap",
|
||||
"blackmagic"
|
||||
],
|
||||
"use_1200bps_touch": true,
|
||||
"require_upload_port": true,
|
||||
"wait_for_upload_port": true
|
||||
},
|
||||
"url": "https://www.seeedstudio.com/SenseCAP-Card-Tracker-T1000-E-for-Meshtastic-p-5913.html",
|
||||
"vendor": "Seeed Studio"
|
||||
}
|
||||
@@ -34,17 +34,24 @@
|
||||
#ifndef LORA_TX_POWER
|
||||
#define LORA_TX_POWER 20
|
||||
#endif
|
||||
#ifndef MAX_LORA_TX_POWER
|
||||
#define MAX_LORA_TX_POWER LORA_TX_POWER
|
||||
#endif
|
||||
|
||||
#ifndef MAX_CONTACTS
|
||||
#define MAX_CONTACTS 100
|
||||
#endif
|
||||
|
||||
#ifndef OFFLINE_QUEUE_SIZE
|
||||
#define OFFLINE_QUEUE_SIZE 16
|
||||
#endif
|
||||
|
||||
#include <helpers/BaseChatMesh.h>
|
||||
|
||||
#define SEND_TIMEOUT_BASE_MILLIS 300
|
||||
#define SEND_TIMEOUT_BASE_MILLIS 500
|
||||
#define FLOOD_SEND_TIMEOUT_FACTOR 16.0f
|
||||
#define DIRECT_SEND_PERHOP_FACTOR 4.0f
|
||||
#define DIRECT_SEND_PERHOP_EXTRA_MILLIS 200
|
||||
#define DIRECT_SEND_PERHOP_FACTOR 6.0f
|
||||
#define DIRECT_SEND_PERHOP_EXTRA_MILLIS 250
|
||||
|
||||
#define PUBLIC_GROUP_PSK "izOH6cXN6mrJ5e26oRXNcg=="
|
||||
|
||||
@@ -52,19 +59,27 @@
|
||||
#include <helpers/HeltecV3Board.h>
|
||||
#include <helpers/CustomSX1262Wrapper.h>
|
||||
static HeltecV3Board board;
|
||||
#elif defined(HELTEC_LORA_V2)
|
||||
#include <helpers/HeltecV2Board.h>
|
||||
#include <helpers/CustomSX1276Wrapper.h>
|
||||
static HeltecV2Board board;
|
||||
#elif defined(ARDUINO_XIAO_ESP32C3)
|
||||
#include <helpers/XiaoC3Board.h>
|
||||
#include <helpers/CustomSX1262Wrapper.h>
|
||||
#include <helpers/CustomSX1268Wrapper.h>
|
||||
static XiaoC3Board board;
|
||||
#elif defined(SEEED_XIAO_S3)
|
||||
#elif defined(SEEED_XIAO_S3) || defined(LILYGO_T3S3)
|
||||
#include <helpers/ESP32Board.h>
|
||||
#include <helpers/CustomSX1262Wrapper.h>
|
||||
static ESP32Board board;
|
||||
#elif defined(RAK_4631)
|
||||
#include <helpers/RAK4631Board.h>
|
||||
#include <helpers/nrf52/RAK4631Board.h>
|
||||
#include <helpers/CustomSX1262Wrapper.h>
|
||||
static RAK4631Board board;
|
||||
#elif defined(T1000_E)
|
||||
#include <helpers/nrf52/T1000eBoard.h>
|
||||
#include <helpers/CustomLR1110Wrapper.h>
|
||||
static T1000eBoard board;
|
||||
#else
|
||||
#error "need to provide a 'board' object"
|
||||
#endif
|
||||
@@ -81,6 +96,9 @@ static uint32_t _atoi(const char* sp) {
|
||||
|
||||
/*------------ Frame Protocol --------------*/
|
||||
|
||||
#define FIRMWARE_VER_CODE 1
|
||||
#define FIRMWARE_BUILD_DATE "19 Feb 2025"
|
||||
|
||||
#define CMD_APP_START 1
|
||||
#define CMD_SEND_TXT_MSG 2
|
||||
#define CMD_SEND_CHANNEL_TXT_MSG 3
|
||||
@@ -91,6 +109,23 @@ static uint32_t _atoi(const char* sp) {
|
||||
#define CMD_SET_ADVERT_NAME 8
|
||||
#define CMD_ADD_UPDATE_CONTACT 9
|
||||
#define CMD_SYNC_NEXT_MESSAGE 10
|
||||
#define CMD_SET_RADIO_PARAMS 11
|
||||
#define CMD_SET_RADIO_TX_POWER 12
|
||||
#define CMD_RESET_PATH 13
|
||||
#define CMD_SET_ADVERT_LATLON 14
|
||||
#define CMD_REMOVE_CONTACT 15
|
||||
#define CMD_SHARE_CONTACT 16
|
||||
#define CMD_EXPORT_CONTACT 17
|
||||
#define CMD_IMPORT_CONTACT 18
|
||||
#define CMD_REBOOT 19
|
||||
#define CMD_GET_BATTERY_VOLTAGE 20
|
||||
#define CMD_SET_TUNING_PARAMS 21
|
||||
#define CMD_DEVICE_QEURY 22
|
||||
#define CMD_EXPORT_PRIVATE_KEY 23
|
||||
#define CMD_IMPORT_PRIVATE_KEY 24
|
||||
#define CMD_SEND_RAW_DATA 25
|
||||
#define CMD_SEND_LOGIN 26
|
||||
#define CMD_SEND_STATUS_REQ 27
|
||||
|
||||
#define RESP_CODE_OK 0
|
||||
#define RESP_CODE_ERR 1
|
||||
@@ -101,27 +136,78 @@ static uint32_t _atoi(const char* sp) {
|
||||
#define RESP_CODE_SENT 6 // reply to CMD_SEND_TXT_MSG
|
||||
#define RESP_CODE_CONTACT_MSG_RECV 7 // a reply to CMD_SYNC_NEXT_MESSAGE
|
||||
#define RESP_CODE_CHANNEL_MSG_RECV 8 // a reply to CMD_SYNC_NEXT_MESSAGE
|
||||
#define RESP_CODE_CURR_TIME 9 // a reply to CMD_GET_DEVICE_TIME
|
||||
#define RESP_CODE_NO_MORE_MESSAGES 10 // a reply to CMD_SYNC_NEXT_MESSAGE
|
||||
#define RESP_CODE_EXPORT_CONTACT 11
|
||||
#define RESP_CODE_BATTERY_VOLTAGE 12 // a reply to a CMD_GET_BATTERY_VOLTAGE
|
||||
#define RESP_CODE_DEVICE_INFO 13 // a reply to CMD_DEVICE_QEURY
|
||||
#define RESP_CODE_PRIVATE_KEY 14 // a reply to CMD_EXPORT_PRIVATE_KEY
|
||||
#define RESP_CODE_DISABLED 15
|
||||
|
||||
// these are _pushed_ to client app at any time
|
||||
#define PUSH_CODE_ADVERT 0x80
|
||||
#define PUSH_CODE_PATH_UPDATED 0x81
|
||||
#define PUSH_CODE_SEND_CONFIRMED 0x82
|
||||
#define PUSH_CODE_MSG_WAITING 0x83
|
||||
#define PUSH_CODE_RAW_DATA 0x84
|
||||
#define PUSH_CODE_LOGIN_SUCCESS 0x85
|
||||
#define PUSH_CODE_LOGIN_FAIL 0x86
|
||||
#define PUSH_CODE_STATUS_RESPONSE 0x87
|
||||
|
||||
/* -------------------------------------------------------------------------------------- */
|
||||
|
||||
struct NodePrefs { // persisted to file
|
||||
float airtime_factor;
|
||||
char node_name[32];
|
||||
double node_lat, node_lon;
|
||||
float freq;
|
||||
uint8_t sf;
|
||||
uint8_t cr;
|
||||
uint8_t reserved1;
|
||||
uint8_t reserved2;
|
||||
float bw;
|
||||
uint8_t tx_power_dbm;
|
||||
uint8_t unused[3];
|
||||
float rx_delay_base;
|
||||
};
|
||||
|
||||
class MyMesh : public BaseChatMesh {
|
||||
FILESYSTEM* _fs;
|
||||
RADIO_CLASS* _phy;
|
||||
IdentityStore* _identity_store;
|
||||
NodePrefs _prefs;
|
||||
uint32_t expected_ack_crc; // TODO: keep table of expected ACKs
|
||||
uint32_t pending_login;
|
||||
uint32_t pending_status;
|
||||
mesh::GroupChannel* _public;
|
||||
BaseSerialInterface* _serial;
|
||||
unsigned long last_msg_sent;
|
||||
ContactsIterator _iter;
|
||||
uint32_t _iter_filter_since;
|
||||
uint32_t _most_recent_lastmod;
|
||||
bool _iter_started;
|
||||
uint8_t app_target_ver;
|
||||
uint8_t cmd_frame[MAX_FRAME_SIZE+1];
|
||||
uint8_t out_frame[MAX_FRAME_SIZE+1];
|
||||
|
||||
struct Frame {
|
||||
uint8_t len;
|
||||
uint8_t buf[MAX_FRAME_SIZE];
|
||||
};
|
||||
int offline_queue_len;
|
||||
Frame offline_queue[OFFLINE_QUEUE_SIZE];
|
||||
|
||||
void loadMainIdentity(mesh::RNG& trng) {
|
||||
if (!_identity_store->load("_main", self_id)) {
|
||||
self_id = mesh::LocalIdentity(&trng); // create new random identity
|
||||
saveMainIdentity(self_id);
|
||||
}
|
||||
}
|
||||
|
||||
bool saveMainIdentity(const mesh::LocalIdentity& identity) {
|
||||
return _identity_store->save("_main", identity);
|
||||
}
|
||||
|
||||
void loadContacts() {
|
||||
if (_fs->exists("/contacts3")) {
|
||||
File file = _fs->open("/contacts3");
|
||||
@@ -131,20 +217,19 @@ class MyMesh : public BaseChatMesh {
|
||||
ContactInfo c;
|
||||
uint8_t pub_key[32];
|
||||
uint8_t unused;
|
||||
uint32_t reserved;
|
||||
|
||||
bool success = (file.read(pub_key, 32) == 32);
|
||||
success = success && (file.read((uint8_t *) &c.name, 32) == 32);
|
||||
success = success && (file.read(&c.type, 1) == 1);
|
||||
success = success && (file.read(&c.flags, 1) == 1);
|
||||
success = success && (file.read(&unused, 1) == 1);
|
||||
success = success && (file.read((uint8_t *) &reserved, 4) == 4);
|
||||
success = success && (file.read((uint8_t *) &c.sync_since, 4) == 4); // was 'reserved'
|
||||
success = success && (file.read((uint8_t *) &c.out_path_len, 1) == 1);
|
||||
success = success && (file.read((uint8_t *) &c.last_advert_timestamp, 4) == 4);
|
||||
success = success && (file.read(c.out_path, 64) == 64);
|
||||
success = success && (file.read((uint8_t *) c.lastmod, 4) == 4);
|
||||
success = success && (file.read((uint8_t *) c.gps_lat, 4) == 4);
|
||||
success = success && (file.read((uint8_t *) c.gps_lon, 4) == 4);
|
||||
success = success && (file.read((uint8_t *) &c.lastmod, 4) == 4);
|
||||
success = success && (file.read((uint8_t *) &c.gps_lat, 4) == 4);
|
||||
success = success && (file.read((uint8_t *) &c.gps_lon, 4) == 4);
|
||||
|
||||
if (!success) break; // EOF
|
||||
|
||||
@@ -167,7 +252,6 @@ class MyMesh : public BaseChatMesh {
|
||||
ContactsIterator iter;
|
||||
ContactInfo c;
|
||||
uint8_t unused = 0;
|
||||
uint32_t reserved = 0;
|
||||
|
||||
while (iter.hasNext(this, c)) {
|
||||
bool success = (file.write(c.id.pub_key, 32) == 32);
|
||||
@@ -175,7 +259,7 @@ class MyMesh : public BaseChatMesh {
|
||||
success = success && (file.write(&c.type, 1) == 1);
|
||||
success = success && (file.write(&c.flags, 1) == 1);
|
||||
success = success && (file.write(&unused, 1) == 1);
|
||||
success = success && (file.write((uint8_t *) &reserved, 4) == 4);
|
||||
success = success && (file.write((uint8_t *) &c.sync_since, 4) == 4);
|
||||
success = success && (file.write((uint8_t *) &c.out_path_len, 1) == 1);
|
||||
success = success && (file.write((uint8_t *) &c.last_advert_timestamp, 4) == 4);
|
||||
success = success && (file.write(c.out_path, 64) == 64);
|
||||
@@ -189,6 +273,49 @@ class MyMesh : public BaseChatMesh {
|
||||
}
|
||||
}
|
||||
|
||||
int getBlobByKey(const uint8_t key[], int key_len, uint8_t dest_buf[]) override {
|
||||
char path[64];
|
||||
char fname[18];
|
||||
|
||||
if (key_len > 8) key_len = 8; // just use first 8 bytes (prefix)
|
||||
mesh::Utils::toHex(fname, key, key_len);
|
||||
sprintf(path, "/bl/%s", fname);
|
||||
|
||||
if (_fs->exists(path)) {
|
||||
File f = _fs->open(path);
|
||||
if (f) {
|
||||
int len = f.read(dest_buf, 255); // currently MAX 255 byte blob len supported!!
|
||||
f.close();
|
||||
return len;
|
||||
}
|
||||
}
|
||||
return 0; // not found
|
||||
}
|
||||
|
||||
bool putBlobByKey(const uint8_t key[], int key_len, const uint8_t src_buf[], int len) override {
|
||||
char path[64];
|
||||
char fname[18];
|
||||
|
||||
if (key_len > 8) key_len = 8; // just use first 8 bytes (prefix)
|
||||
mesh::Utils::toHex(fname, key, key_len);
|
||||
sprintf(path, "/bl/%s", fname);
|
||||
|
||||
#if defined(NRF52_PLATFORM)
|
||||
File f = _fs->open(path, FILE_O_WRITE);
|
||||
if (f) { f.seek(0); f.truncate(); }
|
||||
#else
|
||||
File f = _fs->open(path, "w", true);
|
||||
#endif
|
||||
if (f) {
|
||||
int n = f.write(src_buf, len);
|
||||
f.close();
|
||||
if (n == len) return true; // success!
|
||||
|
||||
_fs->remove(path); // blob was only partially written!
|
||||
}
|
||||
return false; // error
|
||||
}
|
||||
|
||||
void writeOKFrame() {
|
||||
uint8_t buf[1];
|
||||
buf[0] = RESP_CODE_OK;
|
||||
@@ -200,6 +327,12 @@ class MyMesh : public BaseChatMesh {
|
||||
_serial->writeFrame(buf, 1);
|
||||
}
|
||||
|
||||
void writeDisabledFrame() {
|
||||
uint8_t buf[1];
|
||||
buf[0] = RESP_CODE_DISABLED;
|
||||
_serial->writeFrame(buf, 1);
|
||||
}
|
||||
|
||||
void writeContactRespFrame(uint8_t code, const ContactInfo& contact) {
|
||||
int i = 0;
|
||||
out_frame[i++] = code;
|
||||
@@ -208,7 +341,7 @@ class MyMesh : public BaseChatMesh {
|
||||
out_frame[i++] = contact.flags;
|
||||
out_frame[i++] = contact.out_path_len;
|
||||
memcpy(&out_frame[i], contact.out_path, MAX_PATH_SIZE); i += MAX_PATH_SIZE;
|
||||
memcpy(&out_frame[i], contact.name, 32); i += 32;
|
||||
StrHelper::strzcpy((char *) &out_frame[i], contact.name, 32); i += 32;
|
||||
memcpy(&out_frame[i], &contact.last_advert_timestamp, 4); i += 4;
|
||||
memcpy(&out_frame[i], &contact.gps_lat, 4); i += 4;
|
||||
memcpy(&out_frame[i], &contact.gps_lon, 4); i += 4;
|
||||
@@ -233,9 +366,25 @@ class MyMesh : public BaseChatMesh {
|
||||
}
|
||||
|
||||
void addToOfflineQueue(const uint8_t frame[], int len) {
|
||||
// TODO
|
||||
if (offline_queue_len >= OFFLINE_QUEUE_SIZE) {
|
||||
MESH_DEBUG_PRINTLN("ERROR: offline_queue is full!");
|
||||
} else {
|
||||
offline_queue[offline_queue_len].len = len;
|
||||
memcpy(offline_queue[offline_queue_len].buf, frame, len);
|
||||
offline_queue_len++;
|
||||
}
|
||||
}
|
||||
int getFromOfflineQueue(uint8_t frame[]) {
|
||||
if (offline_queue_len > 0) { // check offline queue
|
||||
size_t len = offline_queue[0].len; // take from top of queue
|
||||
memcpy(frame, offline_queue[0].buf, len);
|
||||
|
||||
offline_queue_len--;
|
||||
for (int i = 0; i < offline_queue_len; i++) { // delete top item from queue
|
||||
offline_queue[i] = offline_queue[i + 1];
|
||||
}
|
||||
return len;
|
||||
}
|
||||
return 0; // queue is empty
|
||||
}
|
||||
|
||||
@@ -244,6 +393,15 @@ class MyMesh : public BaseChatMesh {
|
||||
}
|
||||
|
||||
protected:
|
||||
float getAirtimeBudgetFactor() const override {
|
||||
return _prefs.airtime_factor;
|
||||
}
|
||||
|
||||
int calcRxDelay(float score, uint32_t air_time) const override {
|
||||
if (_prefs.rx_delay_base <= 0.0f) return 0;
|
||||
return (int) ((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time);
|
||||
}
|
||||
|
||||
void onDiscoveredContact(ContactInfo& contact, bool is_new) override {
|
||||
if (_serial->isConnected()) {
|
||||
out_frame[0] = PUSH_CODE_ADVERT;
|
||||
@@ -306,6 +464,7 @@ protected:
|
||||
void onChannelMessageRecv(const mesh::GroupChannel& channel, int in_path_len, uint32_t timestamp, const char *text) override {
|
||||
int i = 0;
|
||||
out_frame[i++] = RESP_CODE_CHANNEL_MSG_RECV;
|
||||
out_frame[i++] = 0; // FUTURE: channel_idx (will just be 'public' for now)
|
||||
out_frame[i++] = in_path_len < 0 ? 0xFF : in_path_len;
|
||||
out_frame[i++] = TXT_TYPE_PLAIN;
|
||||
memcpy(&out_frame[i], ×tamp, 4); i += 4;
|
||||
@@ -325,6 +484,56 @@ protected:
|
||||
}
|
||||
}
|
||||
|
||||
void onContactResponse(const ContactInfo& contact, const uint8_t* data, uint8_t len) override {
|
||||
uint32_t sender_timestamp;
|
||||
memcpy(&sender_timestamp, data, 4);
|
||||
|
||||
if (pending_login && memcmp(&pending_login, contact.id.pub_key, 4) == 0) { // check for login response
|
||||
// yes, is response to pending sendLogin()
|
||||
pending_login = 0;
|
||||
|
||||
int i = 0;
|
||||
if (memcmp(&data[4], "OK", 2) == 0) { // legacy Repeater login OK response
|
||||
out_frame[i++] = PUSH_CODE_LOGIN_SUCCESS;
|
||||
out_frame[i++] = 0; // legacy: is_admin = false
|
||||
} else if (data[4] == RESP_SERVER_LOGIN_OK) { // new login response
|
||||
// keep_alive_interval = data[5] * 16
|
||||
out_frame[i++] = PUSH_CODE_LOGIN_SUCCESS;
|
||||
out_frame[i++] = data[6]; // permissions (eg. is_admin)
|
||||
} else {
|
||||
out_frame[i++] = PUSH_CODE_LOGIN_FAIL;
|
||||
out_frame[i++] = 0; // reserved
|
||||
}
|
||||
memcpy(&out_frame[i], contact.id.pub_key, 6); i += 6; // pub_key_prefix
|
||||
_serial->writeFrame(out_frame, i);
|
||||
} else if (len > 4 && pending_status && memcmp(&pending_status, contact.id.pub_key, 4) == 0) { // check for status response
|
||||
// yes, is response to pending sendStatusRequest()
|
||||
pending_status = 0;
|
||||
|
||||
int i = 0;
|
||||
out_frame[i++] = PUSH_CODE_STATUS_RESPONSE;
|
||||
out_frame[i++] = 0; // reserved
|
||||
memcpy(&out_frame[i], contact.id.pub_key, 6); i += 6; // pub_key_prefix
|
||||
memcpy(&out_frame[i], &data[4], len - 4); i += (len - 4);
|
||||
_serial->writeFrame(out_frame, i);
|
||||
}
|
||||
}
|
||||
|
||||
void onRawDataRecv(mesh::Packet* packet) override {
|
||||
int i = 0;
|
||||
out_frame[i++] = PUSH_CODE_RAW_DATA;
|
||||
out_frame[i++] = (int8_t)(_radio->getLastSNR() * 4);
|
||||
out_frame[i++] = (int8_t)(_radio->getLastRSSI());
|
||||
out_frame[i++] = 0xFF; // reserved (possibly path_len in future)
|
||||
memcpy(&out_frame[i], packet->payload, packet->payload_len); i += packet->payload_len;
|
||||
|
||||
if (_serial->isConnected()) {
|
||||
_serial->writeFrame(out_frame, i);
|
||||
} else {
|
||||
MESH_DEBUG_PRINTLN("onRawDataRecv(), data received while app offline");
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t calcFloodTimeoutMillisFor(uint32_t pkt_airtime_millis) const override {
|
||||
return SEND_TIMEOUT_BASE_MILLIS + (FLOOD_SEND_TIMEOUT_FACTOR * pkt_airtime_millis);
|
||||
}
|
||||
@@ -334,56 +543,131 @@ protected:
|
||||
}
|
||||
|
||||
void onSendTimeout() override {
|
||||
Serial.println(" ERROR: timed out, no ACK.");
|
||||
}
|
||||
|
||||
public:
|
||||
char self_name[sizeof(ContactInfo::name)];
|
||||
|
||||
MyMesh(RadioLibWrapper& radio, mesh::RNG& rng, mesh::RTCClock& rtc, SimpleMeshTables& tables)
|
||||
: BaseChatMesh(radio, *new ArduinoMillis(), rng, rtc, *new StaticPoolPacketManager(16), tables), _serial(NULL)
|
||||
MyMesh(RADIO_CLASS& phy, RadioLibWrapper& rw, mesh::RNG& rng, mesh::RTCClock& rtc, SimpleMeshTables& tables)
|
||||
: BaseChatMesh(rw, *new ArduinoMillis(), rng, rtc, *new StaticPoolPacketManager(16), tables), _serial(NULL), _phy(&phy)
|
||||
{
|
||||
_iter_started = false;
|
||||
offline_queue_len = 0;
|
||||
app_target_ver = 0;
|
||||
_identity_store = NULL;
|
||||
pending_login = pending_status = 0;
|
||||
|
||||
// defaults
|
||||
memset(&_prefs, 0, sizeof(_prefs));
|
||||
_prefs.airtime_factor = 1.0; // one half
|
||||
strcpy(_prefs.node_name, "NONAME");
|
||||
_prefs.freq = LORA_FREQ;
|
||||
_prefs.sf = LORA_SF;
|
||||
_prefs.bw = LORA_BW;
|
||||
_prefs.cr = LORA_CR;
|
||||
_prefs.tx_power_dbm = LORA_TX_POWER;
|
||||
//_prefs.rx_delay_base = 10.0f; enable once new algo fixed
|
||||
}
|
||||
|
||||
void begin(FILESYSTEM& fs, BaseSerialInterface& serial) {
|
||||
void begin(FILESYSTEM& fs, mesh::RNG& trng) {
|
||||
_fs = &fs;
|
||||
_serial = &serial;
|
||||
|
||||
BaseChatMesh::begin();
|
||||
|
||||
strcpy(self_name, "UNSET");
|
||||
IdentityStore store(fs, "/identity");
|
||||
if (!store.load("_main", self_id, self_name, sizeof(self_name))) {
|
||||
self_id = mesh::LocalIdentity(getRNG()); // create new random identity
|
||||
store.save("_main", self_id);
|
||||
#if defined(NRF52_PLATFORM)
|
||||
_identity_store = new IdentityStore(fs, "");
|
||||
#else
|
||||
_identity_store = new IdentityStore(fs, "/identity");
|
||||
#endif
|
||||
|
||||
loadMainIdentity(trng);
|
||||
|
||||
// load persisted prefs
|
||||
if (_fs->exists("/node_prefs")) {
|
||||
File file = _fs->open("/node_prefs");
|
||||
if (file) {
|
||||
file.read((uint8_t *) &_prefs, sizeof(_prefs));
|
||||
file.close();
|
||||
}
|
||||
}
|
||||
|
||||
// init 'blob store' support
|
||||
_fs->mkdir("/bl");
|
||||
|
||||
loadContacts();
|
||||
_public = addChannel(PUBLIC_GROUP_PSK); // pre-configure Andy's public channel
|
||||
|
||||
_phy->setFrequency(_prefs.freq);
|
||||
_phy->setSpreadingFactor(_prefs.sf);
|
||||
_phy->setBandwidth(_prefs.bw);
|
||||
_phy->setCodingRate(_prefs.cr);
|
||||
_phy->setOutputPower(_prefs.tx_power_dbm);
|
||||
}
|
||||
|
||||
const char* getNodeName() { return _prefs.node_name; }
|
||||
|
||||
void startInterface(BaseSerialInterface& serial) {
|
||||
_serial = &serial;
|
||||
serial.enable();
|
||||
}
|
||||
|
||||
void savePrefs() {
|
||||
#if defined(NRF52_PLATFORM)
|
||||
File file = _fs->open("/node_prefs", FILE_O_WRITE);
|
||||
if (file) { file.seek(0); file.truncate(); }
|
||||
#else
|
||||
File file = _fs->open("/node_prefs", "w", true);
|
||||
#endif
|
||||
if (file) {
|
||||
file.write((const uint8_t *)&_prefs, sizeof(_prefs));
|
||||
file.close();
|
||||
}
|
||||
}
|
||||
|
||||
void handleCmdFrame(size_t len) {
|
||||
if (cmd_frame[0] == CMD_APP_START && len >= 8) { // sent when app establishes connection, respond with node ID
|
||||
uint8_t app_ver = cmd_frame[1];
|
||||
// cmd_frame[2..7] reserved future
|
||||
if (cmd_frame[0] == CMD_DEVICE_QEURY && len >= 2) { // sent when app establishes connection
|
||||
app_target_ver = cmd_frame[1]; // which version of protocol does app understand
|
||||
|
||||
int i = 0;
|
||||
out_frame[i++] = RESP_CODE_DEVICE_INFO;
|
||||
out_frame[i++] = FIRMWARE_VER_CODE;
|
||||
memset(&out_frame[i], 0, 6); i += 6; // reserved
|
||||
memset(&out_frame[i], 0, 12);
|
||||
strcpy((char *) &out_frame[i], FIRMWARE_BUILD_DATE);
|
||||
i += 12;
|
||||
const char* name = board.getManufacturerName();
|
||||
int tlen = strlen(name);
|
||||
memcpy(&out_frame[i], name, tlen); i += tlen;
|
||||
_serial->writeFrame(out_frame, i);
|
||||
} else if (cmd_frame[0] == CMD_APP_START && len >= 8) { // sent when app establishes connection, respond with node ID
|
||||
// cmd_frame[1..7] reserved future
|
||||
char* app_name = (char *) &cmd_frame[8];
|
||||
cmd_frame[len] = 0; // make app_name null terminated
|
||||
MESH_DEBUG_PRINTLN("App %s connected, ver: %d", app_name, (uint32_t)app_ver);
|
||||
MESH_DEBUG_PRINTLN("App %s connected", app_name);
|
||||
|
||||
_iter_started = false; // stop any left-over ContactsIterator
|
||||
int i = 0;
|
||||
out_frame[i++] = RESP_CODE_SELF_INFO;
|
||||
out_frame[i++] = ADV_TYPE_CHAT; // what this node Advert identifies as (maybe node's pronouns too?? :-)
|
||||
out_frame[i++] = 0; // reserved
|
||||
out_frame[i++] = 0; // reserved
|
||||
out_frame[i++] = _prefs.tx_power_dbm;
|
||||
out_frame[i++] = MAX_LORA_TX_POWER;
|
||||
memcpy(&out_frame[i], self_id.pub_key, PUB_KEY_SIZE); i += PUB_KEY_SIZE;
|
||||
int32_t latlonsats = 0;
|
||||
memcpy(&out_frame[i], &latlonsats, 4); i += 4; // reserved future, for companion radios with GPS (like T-Beam, T1000)
|
||||
memcpy(&out_frame[i], &latlonsats, 4); i += 4;
|
||||
memcpy(&out_frame[i], &latlonsats, 4); i += 4;
|
||||
int tlen = strlen(self_name); // revisit: UTF_8 ??
|
||||
memcpy(&out_frame[i], self_name, tlen); i += tlen;
|
||||
|
||||
int32_t lat, lon, alt = 0;
|
||||
lat = (_prefs.node_lat * 1000000.0);
|
||||
lon = (_prefs.node_lon * 1000000.0);
|
||||
memcpy(&out_frame[i], &lat, 4); i += 4;
|
||||
memcpy(&out_frame[i], &lon, 4); i += 4;
|
||||
memcpy(&out_frame[i], &alt, 4); i += 4;
|
||||
|
||||
uint32_t freq = _prefs.freq * 1000;
|
||||
memcpy(&out_frame[i], &freq, 4); i += 4;
|
||||
uint32_t bw = _prefs.bw*1000;
|
||||
memcpy(&out_frame[i], &bw, 4); i += 4;
|
||||
out_frame[i++] = _prefs.sf;
|
||||
out_frame[i++] = _prefs.cr;
|
||||
|
||||
int tlen = strlen(_prefs.node_name); // revisit: UTF_8 ??
|
||||
memcpy(&out_frame[i], _prefs.node_name, tlen); i += tlen;
|
||||
_serial->writeFrame(out_frame, i);
|
||||
} else if (cmd_frame[0] == CMD_SEND_TXT_MSG && len >= 14) {
|
||||
int i = 1;
|
||||
@@ -415,26 +699,18 @@ public:
|
||||
writeErrFrame(); // unknown recipient, or unsuported TXT_TYPE_*
|
||||
}
|
||||
} else if (cmd_frame[0] == CMD_SEND_CHANNEL_TXT_MSG) { // send GroupChannel msg
|
||||
#if 0 //TODO
|
||||
uint8_t temp[5+MAX_TEXT_LEN+32];
|
||||
uint32_t timestamp = getRTCClock()->getCurrentTime();
|
||||
memcpy(temp, ×tamp, 4); // mostly an extra blob to help make packet_hash unique
|
||||
temp[4] = 0; // attempt and flags
|
||||
int i = 1;
|
||||
uint8_t txt_type = cmd_frame[i++]; // should be TXT_TYPE_PLAIN
|
||||
uint8_t channel_idx = cmd_frame[i++]; // reserved future
|
||||
uint32_t msg_timestamp;
|
||||
memcpy(&msg_timestamp, &cmd_frame[i], 4); i += 4;
|
||||
const char *text = (char *) &cmd_frame[i];
|
||||
|
||||
sprintf((char *) &temp[5], "%s: %s", self_name, &command[7]); // <sender>: <msg>
|
||||
temp[5 + MAX_TEXT_LEN] = 0; // truncate if too long
|
||||
|
||||
int len = strlen((char *) &temp[5]);
|
||||
auto pkt = createGroupDatagram(PAYLOAD_TYPE_GRP_TXT, *_public, temp, 5 + len);
|
||||
if (pkt) {
|
||||
sendFlood(pkt);
|
||||
Serial.println(" Sent.");
|
||||
if (txt_type == TXT_TYPE_PLAIN && sendGroupMessage(msg_timestamp, *_public, _prefs.node_name, text, len - i)) { // hard-coded to 'public' channel for now
|
||||
writeOKFrame();
|
||||
} else {
|
||||
Serial.println(" ERROR: unable to send");
|
||||
writeErrFrame();
|
||||
}
|
||||
#else
|
||||
writeErrFrame();
|
||||
#endif
|
||||
} else if (cmd_frame[0] == CMD_GET_CONTACTS) { // get Contact list
|
||||
if (_iter_started) {
|
||||
writeErrFrame(); // iterator is currently busy
|
||||
@@ -454,18 +730,33 @@ public:
|
||||
// start iterator
|
||||
_iter = startContactsIterator();
|
||||
_iter_started = true;
|
||||
_most_recent_lastmod = 0;
|
||||
}
|
||||
} else if (cmd_frame[0] == CMD_SET_ADVERT_NAME && len >= 2) {
|
||||
int nlen = len - 1;
|
||||
if (nlen > sizeof(self_name)-1) nlen = sizeof(self_name)-1; // max len
|
||||
memcpy(self_name, &cmd_frame[1], nlen);
|
||||
self_name[nlen] = 0;
|
||||
IdentityStore store(*_fs, "/identity"); // update IdentityStore
|
||||
store.save("_main", self_id, self_name);
|
||||
if (nlen > sizeof(_prefs.node_name)-1) nlen = sizeof(_prefs.node_name)-1; // max len
|
||||
memcpy(_prefs.node_name, &cmd_frame[1], nlen);
|
||||
_prefs.node_name[nlen] = 0; // null terminator
|
||||
savePrefs();
|
||||
writeOKFrame();
|
||||
} else if (cmd_frame[0] == CMD_SET_ADVERT_LATLON && len >= 9) {
|
||||
int32_t lat, lon, alt = 0;
|
||||
memcpy(&lat, &cmd_frame[1], 4);
|
||||
memcpy(&lon, &cmd_frame[5], 4);
|
||||
if (len >= 13) {
|
||||
memcpy(&alt, &cmd_frame[9], 4); // for FUTURE support
|
||||
}
|
||||
if (lat <= 90*1E6 && lat >= -90*1E6 && lon <= 180*1E6 && lon >= -180*1E6) {
|
||||
_prefs.node_lat = ((double)lat) / 1000000.0;
|
||||
_prefs.node_lon = ((double)lon) / 1000000.0;
|
||||
savePrefs();
|
||||
writeOKFrame();
|
||||
} else {
|
||||
writeErrFrame(); // invalid geo coordinate
|
||||
}
|
||||
} else if (cmd_frame[0] == CMD_GET_DEVICE_TIME) {
|
||||
uint8_t reply[5];
|
||||
reply[0] = RESP_CODE_OK;
|
||||
reply[0] = RESP_CODE_CURR_TIME;
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
memcpy(&reply[1], &now, 4);
|
||||
_serial->writeFrame(reply, 5);
|
||||
@@ -473,14 +764,14 @@ public:
|
||||
uint32_t secs;
|
||||
memcpy(&secs, &cmd_frame[1], 4);
|
||||
uint32_t curr = getRTCClock()->getCurrentTime();
|
||||
if (secs > curr) {
|
||||
if (secs >= curr) {
|
||||
getRTCClock()->setCurrentTime(secs);
|
||||
writeOKFrame();
|
||||
} else {
|
||||
writeErrFrame();
|
||||
}
|
||||
} else if (cmd_frame[0] == CMD_SEND_SELF_ADVERT) {
|
||||
auto pkt = createSelfAdvert(self_name);
|
||||
auto pkt = createSelfAdvert(_prefs.node_name, _prefs.node_lat, _prefs.node_lon);
|
||||
if (pkt) {
|
||||
if (len >= 2 && cmd_frame[1] == 1) { // optional param (1 = flood, 0 = zero hop)
|
||||
sendFlood(pkt);
|
||||
@@ -491,6 +782,17 @@ public:
|
||||
} else {
|
||||
writeErrFrame();
|
||||
}
|
||||
} else if (cmd_frame[0] == CMD_RESET_PATH && len >= 1+32) {
|
||||
uint8_t* pub_key = &cmd_frame[1];
|
||||
ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
|
||||
if (recipient) {
|
||||
recipient->out_path_len = -1;
|
||||
//recipient->lastmod = ?? shouldn't be needed, app already has this version of contact
|
||||
saveContacts();
|
||||
writeOKFrame();
|
||||
} else {
|
||||
writeErrFrame(); // unknown contact
|
||||
}
|
||||
} else if (cmd_frame[0] == CMD_ADD_UPDATE_CONTACT && len >= 1+32+2+1) {
|
||||
uint8_t* pub_key = &cmd_frame[1];
|
||||
ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
|
||||
@@ -503,6 +805,7 @@ public:
|
||||
ContactInfo contact;
|
||||
updateContactFromFrame(contact, cmd_frame, len);
|
||||
contact.lastmod = getRTCClock()->getCurrentTime();
|
||||
contact.sync_since = 0;
|
||||
if (addContact(contact)) {
|
||||
saveContacts();
|
||||
writeOKFrame();
|
||||
@@ -510,10 +813,191 @@ public:
|
||||
writeErrFrame(); // table is full!
|
||||
}
|
||||
}
|
||||
} else if (cmd_frame[0] == CMD_REMOVE_CONTACT) {
|
||||
uint8_t* pub_key = &cmd_frame[1];
|
||||
ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
|
||||
if (recipient && removeContact(*recipient)) {
|
||||
saveContacts();
|
||||
writeOKFrame();
|
||||
} else {
|
||||
writeErrFrame(); // not found, or unable to remove
|
||||
}
|
||||
} else if (cmd_frame[0] == CMD_SHARE_CONTACT) {
|
||||
uint8_t* pub_key = &cmd_frame[1];
|
||||
ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
|
||||
if (recipient && shareContactZeroHop(*recipient)) {
|
||||
writeOKFrame();
|
||||
} else {
|
||||
writeErrFrame(); // not found, or unable to send
|
||||
}
|
||||
} else if (cmd_frame[0] == CMD_EXPORT_CONTACT) {
|
||||
if (len < 1 + PUB_KEY_SIZE) {
|
||||
// export SELF
|
||||
auto pkt = createSelfAdvert(_prefs.node_name, _prefs.node_lat, _prefs.node_lon);
|
||||
if (pkt) {
|
||||
out_frame[0] = RESP_CODE_EXPORT_CONTACT;
|
||||
uint8_t out_len = pkt->writeTo(&out_frame[1]);
|
||||
releasePacket(pkt); // undo the obtainNewPacket()
|
||||
_serial->writeFrame(out_frame, out_len + 1);
|
||||
} else {
|
||||
writeErrFrame(); // Error
|
||||
}
|
||||
} else {
|
||||
uint8_t* pub_key = &cmd_frame[1];
|
||||
ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
|
||||
uint8_t out_len;
|
||||
if (recipient && (out_len = exportContact(*recipient, &out_frame[1])) > 0) {
|
||||
out_frame[0] = RESP_CODE_EXPORT_CONTACT;
|
||||
_serial->writeFrame(out_frame, out_len + 1);
|
||||
} else {
|
||||
writeErrFrame(); // not found
|
||||
}
|
||||
}
|
||||
} else if (cmd_frame[0] == CMD_IMPORT_CONTACT && len > 2+32+64) {
|
||||
if (importContact(&cmd_frame[1], len - 1)) {
|
||||
writeOKFrame();
|
||||
} else {
|
||||
writeErrFrame();
|
||||
}
|
||||
} else if (cmd_frame[0] == CMD_SYNC_NEXT_MESSAGE) {
|
||||
int out_len;
|
||||
if ((out_len = getFromOfflineQueue(out_frame)) > 0) {
|
||||
_serial->writeFrame(out_frame, out_len);
|
||||
} else {
|
||||
out_frame[0] = RESP_CODE_NO_MORE_MESSAGES;
|
||||
_serial->writeFrame(out_frame, 1);
|
||||
}
|
||||
} else if (cmd_frame[0] == CMD_SET_RADIO_PARAMS) {
|
||||
int i = 1;
|
||||
uint32_t freq;
|
||||
memcpy(&freq, &cmd_frame[i], 4); i += 4;
|
||||
uint32_t bw;
|
||||
memcpy(&bw, &cmd_frame[i], 4); i += 4;
|
||||
uint8_t sf = cmd_frame[i++];
|
||||
uint8_t cr = cmd_frame[i++];
|
||||
|
||||
if (freq >= 300000 && freq <= 2500000 && sf >= 7 && sf <= 12 && cr >= 5 && cr <= 8 && bw >= 7000 && bw <= 500000) {
|
||||
_prefs.sf = sf;
|
||||
_prefs.cr = cr;
|
||||
_prefs.freq = (float)freq / 1000.0;
|
||||
_prefs.bw = (float)bw / 1000.0;
|
||||
savePrefs();
|
||||
|
||||
_phy->setFrequency(_prefs.freq);
|
||||
_phy->setSpreadingFactor(_prefs.sf);
|
||||
_phy->setBandwidth(_prefs.bw);
|
||||
_phy->setCodingRate(_prefs.cr);
|
||||
MESH_DEBUG_PRINTLN("OK: CMD_SET_RADIO_PARAMS: f=%d, bw=%d, sf=%d, cr=%d", freq, bw, (uint32_t)sf, (uint32_t)cr);
|
||||
|
||||
writeOKFrame();
|
||||
} else {
|
||||
MESH_DEBUG_PRINTLN("Error: CMD_SET_RADIO_PARAMS: f=%d, bw=%d, sf=%d, cr=%d", freq, bw, (uint32_t)sf, (uint32_t)cr);
|
||||
writeErrFrame();
|
||||
}
|
||||
} else if (cmd_frame[0] == CMD_SET_RADIO_TX_POWER) {
|
||||
if (cmd_frame[1] > MAX_LORA_TX_POWER) {
|
||||
writeErrFrame();
|
||||
} else {
|
||||
_prefs.tx_power_dbm = cmd_frame[1];
|
||||
savePrefs();
|
||||
_phy->setOutputPower(_prefs.tx_power_dbm);
|
||||
writeOKFrame();
|
||||
}
|
||||
} else if (cmd_frame[0] == CMD_SET_TUNING_PARAMS) {
|
||||
int i = 1;
|
||||
uint32_t rx, af;
|
||||
memcpy(&rx, &cmd_frame[i], 4); i += 4;
|
||||
memcpy(&af, &cmd_frame[i], 4); i += 4;
|
||||
_prefs.rx_delay_base = ((float)rx) / 1000.0f;
|
||||
_prefs.airtime_factor = ((float)af) / 1000.0f;
|
||||
savePrefs();
|
||||
writeOKFrame();
|
||||
} else if (cmd_frame[0] == CMD_REBOOT && memcmp(&cmd_frame[1], "reboot", 6) == 0) {
|
||||
board.reboot();
|
||||
} else if (cmd_frame[0] == CMD_GET_BATTERY_VOLTAGE) {
|
||||
uint8_t reply[3];
|
||||
reply[0] = RESP_CODE_BATTERY_VOLTAGE;
|
||||
uint16_t battery_millivolts = board.getBattMilliVolts();
|
||||
memcpy(&reply[1], &battery_millivolts, 2);
|
||||
_serial->writeFrame(reply, 3);
|
||||
} else if (cmd_frame[0] == CMD_EXPORT_PRIVATE_KEY) {
|
||||
#if ENABLE_PRIVATE_KEY_EXPORT
|
||||
uint8_t reply[65];
|
||||
reply[0] = RESP_CODE_PRIVATE_KEY;
|
||||
self_id.writeTo(&reply[1], 64);
|
||||
_serial->writeFrame(reply, 65);
|
||||
#else
|
||||
writeDisabledFrame();
|
||||
#endif
|
||||
} else if (cmd_frame[0] == CMD_IMPORT_PRIVATE_KEY && len >= 65) {
|
||||
#if ENABLE_PRIVATE_KEY_IMPORT
|
||||
mesh::LocalIdentity identity;
|
||||
identity.readFrom(&cmd_frame[1], 64);
|
||||
if (saveMainIdentity(identity)) {
|
||||
self_id = identity;
|
||||
writeOKFrame();
|
||||
} else {
|
||||
writeErrFrame();
|
||||
}
|
||||
#else
|
||||
writeDisabledFrame();
|
||||
#endif
|
||||
} else if (cmd_frame[0] == CMD_SEND_RAW_DATA && len >= 6) {
|
||||
int i = 1;
|
||||
int8_t path_len = cmd_frame[i++];
|
||||
if (path_len >= 0 && i + path_len + 4 <= len) { // minimum 4 byte payload
|
||||
uint8_t* path = &cmd_frame[i]; i += path_len;
|
||||
auto pkt = createRawData(&cmd_frame[i], len - i);
|
||||
if (pkt) {
|
||||
sendDirect(pkt, path, path_len);
|
||||
writeOKFrame();
|
||||
} else {
|
||||
writeErrFrame();
|
||||
}
|
||||
} else {
|
||||
writeErrFrame(); // flood, not supported (yet)
|
||||
}
|
||||
} else if (cmd_frame[0] == CMD_SEND_LOGIN && len >= 1+PUB_KEY_SIZE) {
|
||||
uint8_t* pub_key = &cmd_frame[1];
|
||||
ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
|
||||
char *password = (char *) &cmd_frame[1+PUB_KEY_SIZE];
|
||||
cmd_frame[len] = 0; // ensure null terminator in password
|
||||
if (recipient) {
|
||||
uint32_t est_timeout;
|
||||
int result = sendLogin(*recipient, password, est_timeout);
|
||||
if (result == MSG_SEND_FAILED) {
|
||||
writeErrFrame();
|
||||
} else {
|
||||
pending_status = 0;
|
||||
memcpy(&pending_login, recipient->id.pub_key, 4); // match this to onContactResponse()
|
||||
out_frame[0] = RESP_CODE_SENT;
|
||||
out_frame[1] = (result == MSG_SEND_SENT_FLOOD) ? 1 : 0;
|
||||
memcpy(&out_frame[2], &pending_login, 4);
|
||||
memcpy(&out_frame[6], &est_timeout, 4);
|
||||
_serial->writeFrame(out_frame, 10);
|
||||
}
|
||||
} else {
|
||||
writeErrFrame(); // contact not found
|
||||
}
|
||||
} else if (cmd_frame[0] == CMD_SEND_STATUS_REQ && len >= 1+PUB_KEY_SIZE) {
|
||||
uint8_t* pub_key = &cmd_frame[1];
|
||||
ContactInfo* recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
|
||||
if (recipient) {
|
||||
uint32_t est_timeout;
|
||||
int result = sendStatusRequest(*recipient, est_timeout);
|
||||
if (result == MSG_SEND_FAILED) {
|
||||
writeErrFrame();
|
||||
} else {
|
||||
pending_login = 0;
|
||||
memcpy(&pending_status, recipient->id.pub_key, 4); // match this to onContactResponse()
|
||||
out_frame[0] = RESP_CODE_SENT;
|
||||
out_frame[1] = (result == MSG_SEND_SENT_FLOOD) ? 1 : 0;
|
||||
memcpy(&out_frame[2], &pending_status, 4);
|
||||
memcpy(&out_frame[6], &est_timeout, 4);
|
||||
_serial->writeFrame(out_frame, 10);
|
||||
}
|
||||
} else {
|
||||
writeErrFrame(); // contact not found
|
||||
}
|
||||
} else {
|
||||
writeErrFrame();
|
||||
@@ -523,6 +1007,7 @@ public:
|
||||
|
||||
void loop() {
|
||||
BaseChatMesh::loop();
|
||||
|
||||
size_t len = _serial->checkRecvFrame(cmd_frame);
|
||||
if (len > 0) {
|
||||
handleCmdFrame(len);
|
||||
@@ -533,10 +1018,14 @@ public:
|
||||
if (_iter.hasNext(this, contact)) {
|
||||
if (contact.lastmod > _iter_filter_since) { // apply the 'since' filter
|
||||
writeContactRespFrame(RESP_CODE_CONTACT, contact);
|
||||
if (contact.lastmod > _most_recent_lastmod) {
|
||||
_most_recent_lastmod = contact.lastmod; // save for the RESP_CODE_END_OF_CONTACTS frame
|
||||
}
|
||||
}
|
||||
} else { // EOF
|
||||
out_frame[0] = RESP_CODE_END_OF_CONTACTS;
|
||||
_serial->writeFrame(out_frame, 1);
|
||||
memcpy(&out_frame[1], &_most_recent_lastmod, 4); // include the most recent lastmod, so app can update their 'since'
|
||||
_serial->writeFrame(out_frame, 5);
|
||||
_iter_started = false;
|
||||
}
|
||||
}
|
||||
@@ -553,7 +1042,8 @@ public:
|
||||
#endif
|
||||
#elif defined(NRF52_PLATFORM)
|
||||
#ifdef BLE_PIN_CODE
|
||||
#error "BLE not defined yet"
|
||||
#include <helpers/nrf52/SerialBLEInterface.h>
|
||||
SerialBLEInterface serial_interface;
|
||||
#else
|
||||
#include <helpers/ArduinoSerialInterface.h>
|
||||
ArduinoSerialInterface serial_interface;
|
||||
@@ -572,7 +1062,7 @@ RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BU
|
||||
#endif
|
||||
StdRNG fast_rng;
|
||||
SimpleMeshTables tables;
|
||||
MyMesh the_mesh(*new WRAPPER_CLASS(radio, board), fast_rng, *new VolatileRTCClock(), tables);
|
||||
MyMesh the_mesh(radio, *new WRAPPER_CLASS(radio, board), fast_rng, *new VolatileRTCClock(), tables);
|
||||
|
||||
void halt() {
|
||||
while (1) ;
|
||||
@@ -613,21 +1103,33 @@ void setup() {
|
||||
|
||||
fast_rng.begin(radio.random(0x7FFFFFFF));
|
||||
|
||||
RadioNoiseListener trng(radio);
|
||||
|
||||
#if defined(NRF52_PLATFORM)
|
||||
InternalFS.begin();
|
||||
|
||||
the_mesh.begin(InternalFS, serial_interface);
|
||||
#elif defined(ESP32)
|
||||
SPIFFS.begin(true);
|
||||
the_mesh.begin(InternalFS, trng);
|
||||
|
||||
#ifdef BLE_PIN_CODE
|
||||
serial_interface.begin("MeshCore", BLE_PIN_CODE);
|
||||
char dev_name[32+10];
|
||||
sprintf(dev_name, "MeshCore-%s", the_mesh.getNodeName());
|
||||
serial_interface.begin(dev_name, BLE_PIN_CODE);
|
||||
#else
|
||||
pinMode(WB_IO2, OUTPUT);
|
||||
serial_interface.begin(Serial);
|
||||
#endif
|
||||
the_mesh.startInterface(serial_interface);
|
||||
#elif defined(ESP32)
|
||||
SPIFFS.begin(true);
|
||||
the_mesh.begin(SPIFFS, trng);
|
||||
|
||||
#ifdef BLE_PIN_CODE
|
||||
char dev_name[32+10];
|
||||
sprintf(dev_name, "MeshCore-%s", the_mesh.getNodeName());
|
||||
serial_interface.begin(dev_name, BLE_PIN_CODE);
|
||||
#else
|
||||
serial_interface.begin(Serial);
|
||||
#endif
|
||||
serial_interface.enable();
|
||||
|
||||
the_mesh.begin(SPIFFS, serial_interface);
|
||||
the_mesh.startInterface(serial_interface);
|
||||
#else
|
||||
#error "need to define filesystem"
|
||||
#endif
|
||||
|
||||
@@ -1,161 +0,0 @@
|
||||
#include <Arduino.h> // needed for PlatformIO
|
||||
#include <Mesh.h>
|
||||
#include <SPIFFS.h>
|
||||
|
||||
#define RADIOLIB_STATIC_ONLY 1
|
||||
#include <RadioLib.h>
|
||||
#include <helpers/RadioLibWrappers.h>
|
||||
#include <helpers/ArduinoHelpers.h>
|
||||
#include <helpers/StaticPoolPacketManager.h>
|
||||
#include <helpers/SimpleMeshTables.h>
|
||||
|
||||
/* ------------------------------ Config -------------------------------- */
|
||||
|
||||
#ifndef LORA_FREQ
|
||||
#define LORA_FREQ 915.0
|
||||
#endif
|
||||
#ifndef LORA_BW
|
||||
#define LORA_BW 125
|
||||
#endif
|
||||
#ifndef LORA_SF
|
||||
#define LORA_SF 9
|
||||
#endif
|
||||
#ifndef LORA_CR
|
||||
#define LORA_CR 5
|
||||
#endif
|
||||
|
||||
#ifdef HELTEC_LORA_V3
|
||||
#include <helpers/HeltecV3Board.h>
|
||||
static HeltecV3Board board;
|
||||
#else
|
||||
#error "need to provide a 'board' object"
|
||||
#endif
|
||||
|
||||
/* ------------------------------ Code -------------------------------- */
|
||||
|
||||
class MyMesh : public mesh::Mesh {
|
||||
uint32_t last_advert_timestamp = 0;
|
||||
mesh::Identity server_id;
|
||||
uint8_t server_secret[PUB_KEY_SIZE];
|
||||
int server_path_len = -1;
|
||||
uint8_t server_path[MAX_PATH_SIZE];
|
||||
bool got_adv = false;
|
||||
|
||||
protected:
|
||||
void onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, uint32_t timestamp, const uint8_t* app_data, size_t app_data_len) override {
|
||||
if (memcmp(app_data, "PING", 4) == 0) {
|
||||
Serial.println("Received advertisement from a PING server");
|
||||
|
||||
// check for replay attacks
|
||||
if (timestamp > last_advert_timestamp) {
|
||||
last_advert_timestamp = timestamp;
|
||||
|
||||
server_id = id;
|
||||
self_id.calcSharedSecret(server_secret, id); // calc ECDH shared secret
|
||||
got_adv = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int searchPeersByHash(const uint8_t* hash) override {
|
||||
if (got_adv && server_id.isHashMatch(hash)) {
|
||||
return 1;
|
||||
}
|
||||
return 0; // not found
|
||||
}
|
||||
|
||||
void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override {
|
||||
// lookup pre-calculated shared_secret
|
||||
memcpy(dest_secret, server_secret, PUB_KEY_SIZE);
|
||||
}
|
||||
|
||||
void onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, const uint8_t* secret, uint8_t* data, size_t len) override {
|
||||
if (type == PAYLOAD_TYPE_RESPONSE) {
|
||||
Serial.println("Received PING Reply!");
|
||||
|
||||
if (packet->isRouteFlood()) {
|
||||
// let server know path TO here, so they can use sendDirect() for future ping responses
|
||||
mesh::Packet* path = createPathReturn(server_id, secret, packet->path, packet->path_len, 0, NULL, 0);
|
||||
if (path) sendFlood(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool onPeerPathRecv(mesh::Packet* packet, int sender_idx, const uint8_t* secret, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) override {
|
||||
// must be from server_id
|
||||
Serial.printf("PATH to server, path_len=%d\n", (uint32_t) path_len);
|
||||
|
||||
memcpy(server_path, path, server_path_len = path_len); // store a copy of path, for sendDirect()
|
||||
|
||||
if (extra_type == PAYLOAD_TYPE_RESPONSE && extra_len > 0) {
|
||||
Serial.println("Received PING Reply!");
|
||||
}
|
||||
return true; // send reciprocal path if necessary
|
||||
}
|
||||
|
||||
public:
|
||||
MyMesh(mesh::Radio& radio, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables)
|
||||
: mesh::Mesh(radio, *new ArduinoMillis(), rng, rtc, *new StaticPoolPacketManager(16), tables)
|
||||
{
|
||||
}
|
||||
|
||||
void sendPingPacket() {
|
||||
if (!got_adv) return; // have not received Advert yet
|
||||
|
||||
uint32_t now = getRTCClock()->getCurrentTime(); // important, need timestamp in packet, so that packet_hash will be unique
|
||||
mesh::Packet* ping = createAnonDatagram(PAYLOAD_TYPE_ANON_REQ, self_id, server_id, server_secret, (uint8_t *) &now, sizeof(now));
|
||||
|
||||
if (ping) {
|
||||
if (server_path_len < 0) {
|
||||
sendFlood(ping);
|
||||
} else {
|
||||
sendDirect(ping, server_path, server_path_len);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
SPIClass spi;
|
||||
StdRNG fast_rng;
|
||||
SimpleMeshTables tables;
|
||||
SX1262 radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi);
|
||||
MyMesh the_mesh(*new RadioLibWrapper(radio, board), fast_rng, *new VolatileRTCClock(), tables);
|
||||
unsigned long nextPing;
|
||||
|
||||
void halt() {
|
||||
while (1) ;
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
|
||||
board.begin();
|
||||
#if defined(P_LORA_SCLK)
|
||||
spi.begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI);
|
||||
int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 22, 8);
|
||||
#else
|
||||
int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 22, 8);
|
||||
#endif
|
||||
if (status != RADIOLIB_ERR_NONE) {
|
||||
Serial.print("ERROR: radio init failed: ");
|
||||
Serial.println(status);
|
||||
halt();
|
||||
}
|
||||
fast_rng.begin(radio.random(0x7FFFFFFF));
|
||||
the_mesh.begin();
|
||||
|
||||
RadioNoiseListener true_rng(radio);
|
||||
the_mesh.self_id = mesh::LocalIdentity(&true_rng); // create new random identity
|
||||
|
||||
nextPing = 0;
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if (the_mesh.millisHasNowPassed(nextPing)) {
|
||||
the_mesh.sendPingPacket();
|
||||
|
||||
nextPing = the_mesh.futureMillis(10000); // attempt ping every 10 seconds
|
||||
}
|
||||
the_mesh.loop();
|
||||
}
|
||||
@@ -1,194 +0,0 @@
|
||||
#include <Arduino.h> // needed for PlatformIO
|
||||
#include <Mesh.h>
|
||||
#include <SPIFFS.h>
|
||||
|
||||
#define RADIOLIB_STATIC_ONLY 1
|
||||
#include <RadioLib.h>
|
||||
#include <helpers/RadioLibWrappers.h>
|
||||
#include <helpers/ArduinoHelpers.h>
|
||||
#include <helpers/StaticPoolPacketManager.h>
|
||||
#include <helpers/SimpleMeshTables.h>
|
||||
|
||||
/* ------------------------------ Config -------------------------------- */
|
||||
|
||||
#ifndef LORA_FREQ
|
||||
#define LORA_FREQ 915.0
|
||||
#endif
|
||||
#ifndef LORA_BW
|
||||
#define LORA_BW 125
|
||||
#endif
|
||||
#ifndef LORA_SF
|
||||
#define LORA_SF 9
|
||||
#endif
|
||||
#ifndef LORA_CR
|
||||
#define LORA_CR 5
|
||||
#endif
|
||||
|
||||
#ifdef HELTEC_LORA_V3
|
||||
#include <helpers/HeltecV3Board.h>
|
||||
static HeltecV3Board board;
|
||||
#else
|
||||
#error "need to provide a 'board' object"
|
||||
#endif
|
||||
|
||||
/* ------------------------------ Code -------------------------------- */
|
||||
|
||||
struct ClientInfo {
|
||||
mesh::Identity id;
|
||||
uint32_t last_timestamp;
|
||||
uint8_t secret[PUB_KEY_SIZE];
|
||||
int out_path_len;
|
||||
uint8_t out_path[MAX_PATH_SIZE];
|
||||
};
|
||||
|
||||
#define MAX_CLIENTS 4
|
||||
|
||||
class MyMesh : public mesh::Mesh {
|
||||
int num_clients;
|
||||
ClientInfo known_clients[MAX_CLIENTS];
|
||||
|
||||
ClientInfo* putClient(const mesh::Identity& id) {
|
||||
for (int i = 0; i < num_clients; i++) {
|
||||
if (id.matches(known_clients[i].id)) return &known_clients[i]; // already known
|
||||
}
|
||||
if (num_clients < MAX_CLIENTS) {
|
||||
auto newClient = &known_clients[num_clients++];
|
||||
newClient->id = id;
|
||||
newClient->out_path_len = -1; // initially out_path is unknown
|
||||
newClient->last_timestamp = 0;
|
||||
self_id.calcSharedSecret(newClient->secret, id); // calc ECDH shared secret
|
||||
return newClient;
|
||||
}
|
||||
return NULL; // table is full
|
||||
}
|
||||
|
||||
protected:
|
||||
void onAnonDataRecv(mesh::Packet* packet, uint8_t type, const mesh::Identity& sender, uint8_t* data, size_t len) override {
|
||||
if (type == PAYLOAD_TYPE_ANON_REQ) { // received a PING!
|
||||
uint32_t timestamp;
|
||||
memcpy(×tamp, data, 4);
|
||||
|
||||
auto client = putClient(sender); // add to known clients (if not already known)
|
||||
if (client == NULL || timestamp <= client->last_timestamp) {
|
||||
return; // FATAL: client table is full -OR- replay attack
|
||||
}
|
||||
|
||||
client->last_timestamp = timestamp;
|
||||
|
||||
uint32_t now = getRTCClock()->getCurrentTime(); // response packets always prefixed with timestamp
|
||||
|
||||
if (packet->isRouteFlood()) {
|
||||
// let this sender know path TO here, so they can use sendDirect(), and ALSO encode the Ping response
|
||||
mesh::Packet* path = createPathReturn(sender, client->secret, packet->path, packet->path_len,
|
||||
PAYLOAD_TYPE_RESPONSE, (uint8_t *) &now, sizeof(now));
|
||||
if (path) sendFlood(path);
|
||||
} else {
|
||||
mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, client->secret, (uint8_t *) &now, sizeof(now));
|
||||
if (reply) {
|
||||
if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
|
||||
sendDirect(reply, client->out_path, client->out_path_len);
|
||||
} else {
|
||||
sendFlood(reply);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int matching_peer_indexes[MAX_CLIENTS];
|
||||
|
||||
int searchPeersByHash(const uint8_t* hash) override {
|
||||
int n = 0;
|
||||
for (int i = 0; i < num_clients; i++) {
|
||||
if (known_clients[i].id.isHashMatch(hash)) {
|
||||
matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
|
||||
}
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
// not needed for this example, but for sake of 'completeness' of Mesh impl
|
||||
void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override {
|
||||
if (peer_idx >= 0 && peer_idx < MAX_CLIENTS) {
|
||||
// lookup pre-calculated shared_secret
|
||||
int i = matching_peer_indexes[peer_idx];
|
||||
memcpy(dest_secret, known_clients[i].secret, PUB_KEY_SIZE);
|
||||
} else {
|
||||
MESH_DEBUG_PRINTLN("Invalid peer_idx: %d", peer_idx);
|
||||
}
|
||||
}
|
||||
|
||||
bool onPeerPathRecv(mesh::Packet* packet, int sender_idx, const uint8_t* secret, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) override {
|
||||
if (sender_idx >= 0 && sender_idx < MAX_CLIENTS) {
|
||||
Serial.printf("PATH to client, path_len=%d\n", (uint32_t) path_len);
|
||||
|
||||
// TODO: prevent replay attacks
|
||||
|
||||
int i = matching_peer_indexes[sender_idx];
|
||||
if (i >= 0 && i < num_clients) {
|
||||
auto client = &known_clients[i]; // get from our known_clients table (sender SHOULD already be known in this context)
|
||||
memcpy(client->out_path, path, client->out_path_len = path_len); // store a copy of path, for sendDirect()
|
||||
}
|
||||
} else {
|
||||
MESH_DEBUG_PRINTLN("Invalid sender_idx: %d", sender_idx);
|
||||
}
|
||||
|
||||
// NOTE: no reciprocal path send!!
|
||||
return false;
|
||||
}
|
||||
|
||||
public:
|
||||
MyMesh(mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables)
|
||||
: mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(16), tables)
|
||||
{
|
||||
num_clients = 0;
|
||||
}
|
||||
};
|
||||
|
||||
SPIClass spi;
|
||||
StdRNG fast_rng;
|
||||
SimpleMeshTables tables;
|
||||
SX1262 radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi);
|
||||
MyMesh the_mesh(*new RadioLibWrapper(radio, board), *new ArduinoMillis(), fast_rng, *new VolatileRTCClock(), tables);
|
||||
|
||||
unsigned long nextAnnounce;
|
||||
|
||||
void halt() {
|
||||
while (1) ;
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
|
||||
board.begin();
|
||||
#if defined(P_LORA_SCLK)
|
||||
spi.begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI);
|
||||
int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 22, 8);
|
||||
#else
|
||||
int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 22, 8);
|
||||
#endif
|
||||
if (status != RADIOLIB_ERR_NONE) {
|
||||
Serial.print("ERROR: radio init failed: ");
|
||||
Serial.println(status);
|
||||
halt();
|
||||
}
|
||||
fast_rng.begin(radio.random(0x7FFFFFFF));
|
||||
the_mesh.begin();
|
||||
|
||||
RadioNoiseListener true_rng(radio);
|
||||
the_mesh.self_id = mesh::LocalIdentity(&true_rng); // create new random identity
|
||||
|
||||
nextAnnounce = 0;
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if (the_mesh.millisHasNowPassed(nextAnnounce)) {
|
||||
mesh::Packet* pkt = the_mesh.createAdvert(the_mesh.self_id, (const uint8_t *)"PING", 4);
|
||||
if (pkt) the_mesh.sendFlood(pkt);
|
||||
|
||||
nextAnnounce = the_mesh.futureMillis(30000); // announce every 30 seconds (test only, don't do in production!)
|
||||
}
|
||||
the_mesh.loop();
|
||||
|
||||
// TODO: periodically check for OLD entries in known_clients[], and evict
|
||||
}
|
||||
@@ -13,13 +13,14 @@
|
||||
#include <helpers/StaticPoolPacketManager.h>
|
||||
#include <helpers/SimpleMeshTables.h>
|
||||
#include <helpers/IdentityStore.h>
|
||||
#include <helpers/AutoDiscoverRTCClock.h>
|
||||
#include <helpers/AdvertDataHelpers.h>
|
||||
#include <helpers/TxtDataHelpers.h>
|
||||
#include <RTClib.h>
|
||||
|
||||
/* ------------------------------ Config -------------------------------- */
|
||||
|
||||
#define FIRMWARE_VER_TEXT "v2 (build: 30 Jan 2025)"
|
||||
#define FIRMWARE_VER_TEXT "v6 (build: 27 Feb 2025)"
|
||||
|
||||
#ifndef LORA_FREQ
|
||||
#define LORA_FREQ 915.0
|
||||
@@ -51,27 +52,35 @@
|
||||
#define ADMIN_PASSWORD "password"
|
||||
#endif
|
||||
|
||||
#define MIN_LOCAL_ADVERT_INTERVAL 60
|
||||
|
||||
#if defined(HELTEC_LORA_V3)
|
||||
#include <helpers/HeltecV3Board.h>
|
||||
#include <helpers/CustomSX1262Wrapper.h>
|
||||
static HeltecV3Board board;
|
||||
#elif defined(HELTEC_LORA_V2)
|
||||
#include <helpers/HeltecV2Board.h>
|
||||
#include <helpers/CustomSX1276Wrapper.h>
|
||||
static HeltecV2Board board;
|
||||
#elif defined(ARDUINO_XIAO_ESP32C3)
|
||||
#include <helpers/XiaoC3Board.h>
|
||||
#include <helpers/CustomSX1262Wrapper.h>
|
||||
#include <helpers/CustomSX1268Wrapper.h>
|
||||
static XiaoC3Board board;
|
||||
#elif defined(SEEED_XIAO_S3)
|
||||
#elif defined(SEEED_XIAO_S3) || defined(LILYGO_T3S3)
|
||||
#include <helpers/ESP32Board.h>
|
||||
#include <helpers/CustomSX1262Wrapper.h>
|
||||
static ESP32Board board;
|
||||
#elif defined(RAK_4631)
|
||||
#include <helpers/RAK4631Board.h>
|
||||
#include <helpers/nrf52/RAK4631Board.h>
|
||||
#include <helpers/CustomSX1262Wrapper.h>
|
||||
static RAK4631Board board;
|
||||
#else
|
||||
#error "need to provide a 'board' object"
|
||||
#endif
|
||||
|
||||
#define PACKET_LOG_FILE "/packet_log"
|
||||
|
||||
/* ------------------------------ Code -------------------------------- */
|
||||
|
||||
// Believe it or not, this std C function is busted on some platforms!
|
||||
@@ -84,7 +93,9 @@ static uint32_t _atoi(const char* sp) {
|
||||
return n;
|
||||
}
|
||||
|
||||
#define CMD_GET_STATS 0x01
|
||||
#define CMD_GET_STATUS 0x01
|
||||
|
||||
#define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ
|
||||
|
||||
struct RepeaterStats {
|
||||
uint16_t batt_milli_volts;
|
||||
@@ -97,14 +108,16 @@ struct RepeaterStats {
|
||||
uint32_t total_up_time_secs;
|
||||
uint32_t n_sent_flood, n_sent_direct;
|
||||
uint32_t n_recv_flood, n_recv_direct;
|
||||
uint32_t n_full_events;
|
||||
uint16_t n_full_events, reserved1;
|
||||
uint16_t n_direct_dups, n_flood_dups;
|
||||
};
|
||||
|
||||
struct ClientInfo {
|
||||
mesh::Identity id;
|
||||
uint32_t last_timestamp;
|
||||
uint32_t last_timestamp, last_activity;
|
||||
uint8_t secret[PUB_KEY_SIZE];
|
||||
int out_path_len;
|
||||
bool is_admin;
|
||||
int8_t out_path_len;
|
||||
uint8_t out_path[MAX_PATH_SIZE];
|
||||
};
|
||||
|
||||
@@ -119,44 +132,50 @@ struct NodePrefs { // persisted to file
|
||||
double node_lat, node_lon;
|
||||
char password[16];
|
||||
float freq;
|
||||
uint8_t tx_power_dbm;
|
||||
uint8_t disable_fwd;
|
||||
uint8_t advert_interval; // minutes / 2
|
||||
uint8_t unused;
|
||||
float rx_delay_base;
|
||||
float tx_delay_factor;
|
||||
char guest_password[16];
|
||||
float direct_tx_delay_factor;
|
||||
};
|
||||
|
||||
class MyMesh : public mesh::Mesh {
|
||||
RadioLibWrapper* my_radio;
|
||||
FILESYSTEM* _fs;
|
||||
mesh::MainBoard* _board;
|
||||
unsigned long next_local_advert;
|
||||
bool _logging;
|
||||
NodePrefs _prefs;
|
||||
uint8_t reply_data[MAX_PACKET_PAYLOAD];
|
||||
int num_clients;
|
||||
ClientInfo known_clients[MAX_CLIENTS];
|
||||
|
||||
ClientInfo* putClient(const mesh::Identity& id) {
|
||||
for (int i = 0; i < num_clients; i++) {
|
||||
uint32_t min_time = 0xFFFFFFFF;
|
||||
ClientInfo* oldest = &known_clients[0];
|
||||
for (int i = 0; i < MAX_CLIENTS; i++) {
|
||||
if (known_clients[i].last_activity < min_time) {
|
||||
oldest = &known_clients[i];
|
||||
min_time = oldest->last_activity;
|
||||
}
|
||||
if (id.matches(known_clients[i].id)) return &known_clients[i]; // already known
|
||||
}
|
||||
if (num_clients < MAX_CLIENTS) {
|
||||
auto newClient = &known_clients[num_clients++];
|
||||
newClient->id = id;
|
||||
newClient->out_path_len = -1; // initially out_path is unknown
|
||||
newClient->last_timestamp = 0;
|
||||
self_id.calcSharedSecret(newClient->secret, id); // calc ECDH shared secret
|
||||
return newClient;
|
||||
}
|
||||
return NULL; // table is full
|
||||
|
||||
oldest->id = id;
|
||||
oldest->out_path_len = -1; // initially out_path is unknown
|
||||
oldest->last_timestamp = 0;
|
||||
self_id.calcSharedSecret(oldest->secret, id); // calc ECDH shared secret
|
||||
return oldest;
|
||||
}
|
||||
|
||||
int handleRequest(ClientInfo* sender, uint8_t* payload, size_t payload_len) {
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
uint32_t now = getRTCClock()->getCurrentTimeUnique();
|
||||
memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
|
||||
|
||||
switch (payload[0]) {
|
||||
case CMD_GET_STATS: {
|
||||
uint32_t max_age_secs;
|
||||
if (payload_len >= 5) {
|
||||
memcpy(&max_age_secs, &payload[1], 4); // first param in request pkt
|
||||
} else {
|
||||
max_age_secs = 12*60*60; // default, 12 hours
|
||||
}
|
||||
|
||||
case CMD_GET_STATUS: { // guests can also access this now
|
||||
RepeaterStats stats;
|
||||
stats.batt_milli_volts = board.getBattMilliVolts();
|
||||
stats.curr_tx_queue_len = _mgr->getOutboundCount();
|
||||
@@ -171,6 +190,9 @@ class MyMesh : public mesh::Mesh {
|
||||
stats.n_recv_flood = getNumRecvFlood();
|
||||
stats.n_recv_direct = getNumRecvDirect();
|
||||
stats.n_full_events = getNumFullEvents();
|
||||
stats.reserved1 = 0;
|
||||
stats.n_direct_dups = ((SimpleMeshTables *)getTables())->getNumDirectDups();
|
||||
stats.n_flood_dups = ((SimpleMeshTables *)getTables())->getNumFloodDups();
|
||||
|
||||
memcpy(&reply_data[4], &stats, sizeof(stats));
|
||||
|
||||
@@ -181,13 +203,117 @@ class MyMesh : public mesh::Mesh {
|
||||
return 0; // reply_len
|
||||
}
|
||||
|
||||
void checkAdvertInterval() {
|
||||
if (_prefs.advert_interval * 2 < MIN_LOCAL_ADVERT_INTERVAL) {
|
||||
_prefs.advert_interval = 0; // turn it off, now that device has been manually configured
|
||||
}
|
||||
}
|
||||
|
||||
void updateAdvertTimer() {
|
||||
if (_prefs.advert_interval > 0) { // schedule local advert timer
|
||||
next_local_advert = futureMillis((uint32_t)_prefs.advert_interval * 2 * 60 * 1000);
|
||||
} else {
|
||||
next_local_advert = 0; // stop the timer
|
||||
}
|
||||
}
|
||||
|
||||
mesh::Packet* createSelfAdvert() {
|
||||
uint8_t app_data[MAX_ADVERT_DATA_SIZE];
|
||||
uint8_t app_data_len;
|
||||
{
|
||||
AdvertDataBuilder builder(ADV_TYPE_REPEATER, _prefs.node_name, _prefs.node_lat, _prefs.node_lon);
|
||||
app_data_len = builder.encodeTo(app_data);
|
||||
}
|
||||
|
||||
return createAdvert(self_id, app_data, app_data_len);
|
||||
}
|
||||
|
||||
File openAppend(const char* fname) {
|
||||
#if defined(NRF52_PLATFORM)
|
||||
return _fs->open(fname, FILE_O_WRITE);
|
||||
#else
|
||||
return _fs->open(fname, "a", true);
|
||||
#endif
|
||||
}
|
||||
|
||||
protected:
|
||||
float getAirtimeBudgetFactor() const override {
|
||||
return _prefs.airtime_factor;
|
||||
}
|
||||
|
||||
bool allowPacketForward(const mesh::Packet* packet) override {
|
||||
return true; // Yes, allow packet to be forwarded
|
||||
return !_prefs.disable_fwd;
|
||||
}
|
||||
|
||||
const char* getLogDateTime() override {
|
||||
static char tmp[32];
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
DateTime dt = DateTime(now);
|
||||
sprintf(tmp, "%02d:%02d:%02d - %d/%d/%d U", dt.hour(), dt.minute(), dt.second(), dt.day(), dt.month(), dt.year());
|
||||
return tmp;
|
||||
}
|
||||
|
||||
void logRx(mesh::Packet* pkt, int len, float score) override {
|
||||
if (_logging) {
|
||||
File f = openAppend(PACKET_LOG_FILE);
|
||||
if (f) {
|
||||
f.print(getLogDateTime());
|
||||
f.printf(": RX, len=%d (type=%d, route=%s, payload_len=%d) SNR=%d RSSI=%d score=%d",
|
||||
len, pkt->getPayloadType(), pkt->isRouteDirect() ? "D" : "F", pkt->payload_len,
|
||||
(int)_radio->getLastSNR(), (int)_radio->getLastRSSI(), (int)(score*1000));
|
||||
|
||||
if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ
|
||||
|| pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
|
||||
f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
|
||||
} else {
|
||||
f.printf("\n");
|
||||
}
|
||||
f.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
void logTx(mesh::Packet* pkt, int len) override {
|
||||
if (_logging) {
|
||||
File f = openAppend(PACKET_LOG_FILE);
|
||||
if (f) {
|
||||
f.print(getLogDateTime());
|
||||
f.printf(": TX, len=%d (type=%d, route=%s, payload_len=%d)",
|
||||
len, pkt->getPayloadType(), pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
|
||||
|
||||
if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ
|
||||
|| pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
|
||||
f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
|
||||
} else {
|
||||
f.printf("\n");
|
||||
}
|
||||
f.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
void logTxFail(mesh::Packet* pkt, int len) override {
|
||||
if (_logging) {
|
||||
File f = openAppend(PACKET_LOG_FILE);
|
||||
if (f) {
|
||||
f.print(getLogDateTime());
|
||||
f.printf(": TX FAIL!, len=%d (type=%d, route=%s, payload_len=%d)\n",
|
||||
len, pkt->getPayloadType(), pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
|
||||
f.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int calcRxDelay(float score, uint32_t air_time) const override {
|
||||
if (_prefs.rx_delay_base <= 0.0f) return 0;
|
||||
return (int) ((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time);
|
||||
}
|
||||
|
||||
uint32_t getRetransmitDelay(const mesh::Packet* packet) override {
|
||||
uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.tx_delay_factor);
|
||||
return getRNG()->nextInt(0, 6)*t;
|
||||
}
|
||||
uint32_t getDirectRetransmitDelay(const mesh::Packet* packet) override {
|
||||
uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.direct_tx_delay_factor);
|
||||
return getRNG()->nextInt(0, 6)*t;
|
||||
}
|
||||
|
||||
void onAnonDataRecv(mesh::Packet* packet, uint8_t type, const mesh::Identity& sender, uint8_t* data, size_t len) override {
|
||||
@@ -195,38 +321,56 @@ protected:
|
||||
uint32_t timestamp;
|
||||
memcpy(×tamp, data, 4);
|
||||
|
||||
if (memcmp(&data[4], _prefs.password, strlen(_prefs.password)) == 0) { // check for valid password
|
||||
auto client = putClient(sender); // add to known clients (if not already known)
|
||||
if (client == NULL || timestamp <= client->last_timestamp) {
|
||||
MESH_DEBUG_PRINTLN("Client table full, or replay attack!");
|
||||
return; // FATAL: client table is full -OR- replay attack
|
||||
}
|
||||
bool is_admin;
|
||||
data[len] = 0; // ensure null terminator
|
||||
if (strcmp((char *) &data[4], _prefs.password) == 0) { // check for valid password
|
||||
is_admin = true;
|
||||
} else if (strcmp((char *) &data[4], _prefs.guest_password) == 0) { // check guest password
|
||||
is_admin = false;
|
||||
} else {
|
||||
#if MESH_DEBUG
|
||||
MESH_DEBUG_PRINTLN("Invalid password: %s", &data[4]);
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
|
||||
MESH_DEBUG_PRINTLN("Login success!");
|
||||
client->last_timestamp = timestamp;
|
||||
auto client = putClient(sender); // add to known clients (if not already known)
|
||||
if (timestamp <= client->last_timestamp) {
|
||||
MESH_DEBUG_PRINTLN("Possible login replay attack!");
|
||||
return; // FATAL: client table is full -OR- replay attack
|
||||
}
|
||||
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
|
||||
memcpy(&reply_data[4], "OK", 2);
|
||||
MESH_DEBUG_PRINTLN("Login success!");
|
||||
client->last_timestamp = timestamp;
|
||||
client->last_activity = getRTCClock()->getCurrentTime();
|
||||
client->is_admin = is_admin;
|
||||
|
||||
if (packet->isRouteFlood()) {
|
||||
// let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
|
||||
mesh::Packet* path = createPathReturn(sender, client->secret, packet->path, packet->path_len,
|
||||
PAYLOAD_TYPE_RESPONSE, reply_data, 4 + 2);
|
||||
if (path) sendFlood(path);
|
||||
} else {
|
||||
mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, client->secret, reply_data, 4 + 2);
|
||||
if (reply) {
|
||||
if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
|
||||
sendDirect(reply, client->out_path, client->out_path_len);
|
||||
} else {
|
||||
sendFlood(reply);
|
||||
}
|
||||
uint32_t now = getRTCClock()->getCurrentTimeUnique();
|
||||
memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
|
||||
#if 0
|
||||
memcpy(&reply_data[4], "OK", 2); // legacy response
|
||||
#else
|
||||
reply_data[4] = RESP_SERVER_LOGIN_OK;
|
||||
reply_data[5] = 0; // NEW: recommended keep-alive interval (secs / 16)
|
||||
reply_data[6] = is_admin ? 1 : 0;
|
||||
reply_data[7] = 0; // FUTURE: reserved
|
||||
getRNG()->random(&reply_data[8], 4); // random blob to help packet-hash uniqueness
|
||||
#endif
|
||||
|
||||
if (packet->isRouteFlood()) {
|
||||
// let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
|
||||
mesh::Packet* path = createPathReturn(sender, client->secret, packet->path, packet->path_len,
|
||||
PAYLOAD_TYPE_RESPONSE, reply_data, 12);
|
||||
if (path) sendFlood(path);
|
||||
} else {
|
||||
mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, client->secret, reply_data, 12);
|
||||
if (reply) {
|
||||
if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
|
||||
sendDirect(reply, client->out_path, client->out_path_len);
|
||||
} else {
|
||||
sendFlood(reply);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
data[4+8] = 0; // ensure null terminator
|
||||
MESH_DEBUG_PRINTLN("Incorrect password: %s", &data[4]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -235,7 +379,7 @@ protected:
|
||||
|
||||
int searchPeersByHash(const uint8_t* hash) override {
|
||||
int n = 0;
|
||||
for (int i = 0; i < num_clients; i++) {
|
||||
for (int i = 0; i < MAX_CLIENTS; i++) {
|
||||
if (known_clients[i].id.isHashMatch(hash)) {
|
||||
matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
|
||||
}
|
||||
@@ -245,7 +389,7 @@ protected:
|
||||
|
||||
void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override {
|
||||
int i = matching_peer_indexes[peer_idx];
|
||||
if (i >= 0 && i < num_clients) {
|
||||
if (i >= 0 && i < MAX_CLIENTS) {
|
||||
// lookup pre-calculated shared_secret
|
||||
memcpy(dest_secret, known_clients[i].secret, PUB_KEY_SIZE);
|
||||
} else {
|
||||
@@ -255,7 +399,7 @@ protected:
|
||||
|
||||
void onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, const uint8_t* secret, uint8_t* data, size_t len) override {
|
||||
int i = matching_peer_indexes[sender_idx];
|
||||
if (i < 0 || i >= num_clients) { // get from our known_clients table (sender SHOULD already be known in this context)
|
||||
if (i < 0 || i >= MAX_CLIENTS) { // get from our known_clients table (sender SHOULD already be known in this context)
|
||||
MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
|
||||
return;
|
||||
}
|
||||
@@ -269,6 +413,7 @@ protected:
|
||||
if (reply_len == 0) return; // invalid command
|
||||
|
||||
client->last_timestamp = timestamp;
|
||||
client->last_activity = getRTCClock()->getCurrentTime();
|
||||
|
||||
if (packet->isRouteFlood()) {
|
||||
// let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
|
||||
@@ -288,7 +433,7 @@ protected:
|
||||
} else {
|
||||
MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
|
||||
}
|
||||
} else if (type == PAYLOAD_TYPE_TXT_MSG && len > 5) { // a CLI command
|
||||
} else if (type == PAYLOAD_TYPE_TXT_MSG && len > 5 && client->is_admin) { // a CLI command
|
||||
uint32_t sender_timestamp;
|
||||
memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
|
||||
uint flags = (data[4] >> 2); // message attempt number, and other flags
|
||||
@@ -297,6 +442,7 @@ protected:
|
||||
MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported text type received: flags=%02x", (uint32_t)flags);
|
||||
} else if (sender_timestamp > client->last_timestamp) { // prevent replay attacks
|
||||
client->last_timestamp = sender_timestamp;
|
||||
client->last_activity = getRTCClock()->getCurrentTime();
|
||||
|
||||
// len can be > original length, but 'text' will be padded with zeroes
|
||||
data[len] = 0; // need to make a C string again, with null terminator
|
||||
@@ -317,7 +463,7 @@ protected:
|
||||
handleCommand(sender_timestamp, (const char *) &data[5], (char *) &temp[5]);
|
||||
int text_len = strlen((char *) &temp[5]);
|
||||
if (text_len > 0) {
|
||||
uint32_t timestamp = getRTCClock()->getCurrentTime();
|
||||
uint32_t timestamp = getRTCClock()->getCurrentTimeUnique();
|
||||
if (timestamp == sender_timestamp) {
|
||||
// WORKAROUND: the two timestamps need to be different, in the CLI view
|
||||
timestamp++;
|
||||
@@ -347,7 +493,7 @@ protected:
|
||||
// TODO: prevent replay attacks
|
||||
int i = matching_peer_indexes[sender_idx];
|
||||
|
||||
if (i >= 0 && i < num_clients) { // get from our known_clients table (sender SHOULD already be known in this context)
|
||||
if (i >= 0 && i < MAX_CLIENTS) { // get from our known_clients table (sender SHOULD already be known in this context)
|
||||
MESH_DEBUG_PRINTLN("PATH to client, path_len=%d", (uint32_t) path_len);
|
||||
auto client = &known_clients[i];
|
||||
memcpy(client->out_path, path, client->out_path_len = path_len); // store a copy of path, for sendDirect()
|
||||
@@ -360,24 +506,30 @@ protected:
|
||||
}
|
||||
|
||||
public:
|
||||
MyMesh(RadioLibWrapper& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables)
|
||||
: mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables)
|
||||
MyMesh(mesh::MainBoard& board, RadioLibWrapper& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, SimpleMeshTables& tables)
|
||||
: mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables), _board(&board)
|
||||
{
|
||||
my_radio = &radio;
|
||||
num_clients = 0;
|
||||
memset(known_clients, 0, sizeof(known_clients));
|
||||
next_local_advert = 0;
|
||||
_logging = false;
|
||||
|
||||
// defaults
|
||||
memset(&_prefs, 0, sizeof(_prefs));
|
||||
_prefs.airtime_factor = 1.0; // one half
|
||||
strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name)-1);
|
||||
_prefs.node_name[sizeof(_prefs.node_name)-1] = 0; // truncate if necessary
|
||||
_prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0;
|
||||
_prefs.tx_delay_factor = 0.5f; // was 0.25f
|
||||
StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
|
||||
_prefs.node_lat = ADVERT_LAT;
|
||||
_prefs.node_lon = ADVERT_LON;
|
||||
strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password)-1);
|
||||
_prefs.password[sizeof(_prefs.password)-1] = 0; // truncate if necessary
|
||||
StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
|
||||
_prefs.freq = LORA_FREQ;
|
||||
_prefs.tx_power_dbm = LORA_TX_POWER;
|
||||
_prefs.advert_interval = 1; // default to 2 minutes for NEW installs
|
||||
}
|
||||
|
||||
float getFreqPref() const { return _prefs.freq; }
|
||||
uint8_t getTxPowerPref() const { return _prefs.tx_power_dbm; }
|
||||
|
||||
void begin(FILESYSTEM* fs) {
|
||||
mesh::Mesh::begin();
|
||||
@@ -390,6 +542,8 @@ public:
|
||||
file.close();
|
||||
}
|
||||
}
|
||||
|
||||
updateAdvertTimer();
|
||||
}
|
||||
|
||||
void savePrefs() {
|
||||
@@ -405,29 +559,35 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
void sendSelfAdvertisement() {
|
||||
uint8_t app_data[MAX_ADVERT_DATA_SIZE];
|
||||
uint8_t app_data_len;
|
||||
{
|
||||
AdvertDataBuilder builder(ADV_TYPE_REPEATER, _prefs.node_name, _prefs.node_lat, _prefs.node_lon);
|
||||
app_data_len = builder.encodeTo(app_data);
|
||||
}
|
||||
|
||||
mesh::Packet* pkt = createAdvert(self_id, app_data, app_data_len);
|
||||
void sendSelfAdvertisement(int delay_millis) {
|
||||
mesh::Packet* pkt = createSelfAdvert();
|
||||
if (pkt) {
|
||||
sendFlood(pkt, 800); // add slight delay
|
||||
sendFlood(pkt, delay_millis);
|
||||
} else {
|
||||
MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
|
||||
}
|
||||
}
|
||||
|
||||
void loop() {
|
||||
mesh::Mesh::loop();
|
||||
|
||||
if (next_local_advert && millisHasNowPassed(next_local_advert)) {
|
||||
mesh::Packet* pkt = createSelfAdvert();
|
||||
if (pkt) {
|
||||
sendZeroHop(pkt);
|
||||
}
|
||||
|
||||
updateAdvertTimer(); // schedule next local advert
|
||||
}
|
||||
}
|
||||
|
||||
void handleCommand(uint32_t sender_timestamp, const char* command, char reply[]) {
|
||||
while (*command == ' ') command++; // skip leading spaces
|
||||
|
||||
if (memcmp(command, "reboot", 6) == 0) {
|
||||
board.reboot(); // doesn't return
|
||||
} else if (memcmp(command, "advert", 6) == 0) {
|
||||
sendSelfAdvertisement();
|
||||
sendSelfAdvertisement(400);
|
||||
strcpy(reply, "OK - Advert sent");
|
||||
} else if (memcmp(command, "clock sync", 10) == 0) {
|
||||
uint32_t curr = getRTCClock()->getCurrentTime();
|
||||
@@ -437,6 +597,12 @@ public:
|
||||
} else {
|
||||
strcpy(reply, "ERR: clock cannot go backwards");
|
||||
}
|
||||
} else if (memcmp(command, "start ota", 9) == 0) {
|
||||
if (_board->startOTAUpdate()) {
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error");
|
||||
}
|
||||
} else if (memcmp(command, "clock", 5) == 0) {
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
DateTime dt = DateTime(now);
|
||||
@@ -452,8 +618,8 @@ public:
|
||||
}
|
||||
} else if (memcmp(command, "password ", 9) == 0) {
|
||||
// change admin password
|
||||
strncpy(_prefs.password, &command[9], sizeof(_prefs.password)-1);
|
||||
_prefs.password[sizeof(_prefs.password)-1] = 0; // truncate if necesary
|
||||
StrHelper::strncpy(_prefs.password, &command[9], sizeof(_prefs.password));
|
||||
checkAdvertInterval();
|
||||
savePrefs();
|
||||
sprintf(reply, "password now: %s", _prefs.password); // echo back just to let admin know for sure!!
|
||||
} else if (memcmp(command, "set ", 4) == 0) {
|
||||
@@ -462,19 +628,72 @@ public:
|
||||
_prefs.airtime_factor = atof(&config[3]);
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else if (memcmp(config, "name ", 5) == 0) {
|
||||
strncpy(_prefs.node_name, &config[5], sizeof(_prefs.node_name)-1);
|
||||
_prefs.node_name[sizeof(_prefs.node_name)-1] = 0; // truncate if nec
|
||||
} else if (memcmp(config, "advert.interval ", 16) == 0) {
|
||||
int mins = _atoi(&config[16]);
|
||||
if (mins > 0 && mins < MIN_LOCAL_ADVERT_INTERVAL) {
|
||||
sprintf(reply, "Error: min is %d mins", MIN_LOCAL_ADVERT_INTERVAL);
|
||||
} else if (mins > 240) {
|
||||
strcpy(reply, "Error: max is 240 mins");
|
||||
} else {
|
||||
_prefs.advert_interval = (uint8_t)(mins / 2);
|
||||
updateAdvertTimer();
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
}
|
||||
} else if (memcmp(config, "guest.password ", 15) == 0) {
|
||||
StrHelper::strncpy(_prefs.guest_password, &config[15], sizeof(_prefs.guest_password));
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else if (memcmp(config, "name ", 5) == 0) {
|
||||
StrHelper::strncpy(_prefs.node_name, &config[5], sizeof(_prefs.node_name));
|
||||
checkAdvertInterval();
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else if (memcmp(config, "repeat ", 7) == 0) {
|
||||
_prefs.disable_fwd = memcmp(&config[7], "off", 3) == 0;
|
||||
savePrefs();
|
||||
strcpy(reply, _prefs.disable_fwd ? "OK - repeat is now OFF" : "OK - repeat is now ON");
|
||||
} else if (memcmp(config, "lat ", 4) == 0) {
|
||||
_prefs.node_lat = atof(&config[4]);
|
||||
checkAdvertInterval();
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else if (memcmp(config, "lon ", 4) == 0) {
|
||||
_prefs.node_lon = atof(&config[4]);
|
||||
checkAdvertInterval();
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else if (memcmp(config, "rxdelay ", 8) == 0) {
|
||||
float db = atof(&config[8]);
|
||||
if (db >= 0) {
|
||||
_prefs.rx_delay_base = db;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error, cannot be negative");
|
||||
}
|
||||
} else if (memcmp(config, "txdelay ", 8) == 0) {
|
||||
float f = atof(&config[8]);
|
||||
if (f >= 0) {
|
||||
_prefs.tx_delay_factor = f;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error, cannot be negative");
|
||||
}
|
||||
} else if (memcmp(config, "direct.txdelay ", 15) == 0) {
|
||||
float f = atof(&config[15]);
|
||||
if (f >= 0) {
|
||||
_prefs.direct_tx_delay_factor = f;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error, cannot be negative");
|
||||
}
|
||||
} else if (memcmp(config, "tx ", 3) == 0) {
|
||||
_prefs.tx_power_dbm = atoi(&config[3]);
|
||||
savePrefs();
|
||||
strcpy(reply, "OK - reboot to apply");
|
||||
} else if (sender_timestamp == 0 && memcmp(config, "freq ", 5) == 0) {
|
||||
_prefs.freq = atof(&config[5]);
|
||||
savePrefs();
|
||||
@@ -482,10 +701,39 @@ public:
|
||||
} else {
|
||||
sprintf(reply, "unknown config: %s", config);
|
||||
}
|
||||
} else if (sender_timestamp == 0 && strcmp(command, "erase") == 0) {
|
||||
#if defined(NRF52_PLATFORM)
|
||||
bool s = InternalFS.format();
|
||||
#elif defined(ESP32)
|
||||
bool s = SPIFFS.format();
|
||||
#else
|
||||
#error "need to implement file system erase"
|
||||
#endif
|
||||
sprintf(reply, "File system erase: %s", s ? "OK" : "Err");
|
||||
} else if (memcmp(command, "ver", 3) == 0) {
|
||||
strcpy(reply, FIRMWARE_VER_TEXT);
|
||||
} else if (memcmp(command, "log start", 9) == 0) {
|
||||
_logging = true;
|
||||
strcpy(reply, " logging on");
|
||||
} else if (memcmp(command, "log stop", 8) == 0) {
|
||||
_logging = false;
|
||||
strcpy(reply, " logging off");
|
||||
} else if (memcmp(command, "log erase", 9) == 0) {
|
||||
_fs->remove(PACKET_LOG_FILE);
|
||||
strcpy(reply, " log erased");
|
||||
} else if (sender_timestamp == 0 && memcmp(command, "log", 3) == 0) {
|
||||
File f = _fs->open(PACKET_LOG_FILE);
|
||||
if (f) {
|
||||
while (f.available()) {
|
||||
int c = f.read();
|
||||
if (c < 0) break;
|
||||
Serial.print((char)c);
|
||||
}
|
||||
f.close();
|
||||
}
|
||||
strcpy(reply, " EOF");
|
||||
} else {
|
||||
sprintf(reply, "Unknown: %s (commands: reboot, advert, clock, set, ver)", command);
|
||||
sprintf(reply, "Unknown: %s (commands: reboot, advert, clock, set, ver, password, start ota)", command);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -502,12 +750,13 @@ StdRNG fast_rng;
|
||||
SimpleMeshTables tables;
|
||||
|
||||
#ifdef ESP32
|
||||
ESP32RTCClock rtc_clock;
|
||||
ESP32RTCClock fallback_clock;
|
||||
#else
|
||||
VolatileRTCClock rtc_clock;
|
||||
VolatileRTCClock fallback_clock;
|
||||
#endif
|
||||
AutoDiscoverRTCClock rtc_clock(fallback_clock);
|
||||
|
||||
MyMesh the_mesh(*new WRAPPER_CLASS(radio, board), *new ArduinoMillis(), fast_rng, rtc_clock, tables);
|
||||
MyMesh the_mesh(board, *new WRAPPER_CLASS(radio, board), *new ArduinoMillis(), fast_rng, rtc_clock, tables);
|
||||
|
||||
void halt() {
|
||||
while (1) ;
|
||||
@@ -521,15 +770,16 @@ void setup() {
|
||||
|
||||
board.begin();
|
||||
#ifdef ESP32
|
||||
rtc_clock.begin();
|
||||
fallback_clock.begin();
|
||||
#endif
|
||||
rtc_clock.begin(Wire);
|
||||
|
||||
#ifdef SX126X_DIO3_TCXO_VOLTAGE
|
||||
float tcxo = SX126X_DIO3_TCXO_VOLTAGE;
|
||||
#else
|
||||
float tcxo = 1.6f;
|
||||
#endif
|
||||
|
||||
|
||||
#if defined(NRF52_PLATFORM)
|
||||
SPI.setPins(P_LORA_MISO, P_LORA_SCLK, P_LORA_MOSI);
|
||||
SPI.begin();
|
||||
@@ -554,11 +804,13 @@ void setup() {
|
||||
radio.setDio2AsRfSwitch(SX126X_DIO2_AS_RF_SWITCH);
|
||||
#endif
|
||||
|
||||
fast_rng.begin(radio.random(0x7FFFFFFF));
|
||||
|
||||
FILESYSTEM* fs;
|
||||
#if defined(NRF52_PLATFORM)
|
||||
InternalFS.begin();
|
||||
fs = &InternalFS;
|
||||
IdentityStore store(InternalFS, "/identity");
|
||||
IdentityStore store(InternalFS, "");
|
||||
#elif defined(ESP32)
|
||||
SPIFFS.begin(true);
|
||||
fs = &SPIFFS;
|
||||
@@ -567,7 +819,9 @@ void setup() {
|
||||
#error "need to define filesystem"
|
||||
#endif
|
||||
if (!store.load("_main", the_mesh.self_id)) {
|
||||
the_mesh.self_id = mesh::LocalIdentity(the_mesh.getRNG()); // create new random identity
|
||||
MESH_DEBUG_PRINTLN("Generating new keypair");
|
||||
RadioNoiseListener rng(radio);
|
||||
the_mesh.self_id = mesh::LocalIdentity(&rng); // create new random identity
|
||||
store.save("_main", the_mesh.self_id);
|
||||
}
|
||||
|
||||
@@ -581,9 +835,12 @@ void setup() {
|
||||
if (LORA_FREQ != the_mesh.getFreqPref()) {
|
||||
radio.setFrequency(the_mesh.getFreqPref());
|
||||
}
|
||||
if (LORA_TX_POWER != the_mesh.getTxPowerPref()) {
|
||||
radio.setOutputPower(the_mesh.getTxPowerPref());
|
||||
}
|
||||
|
||||
// send out initial Advertisement to the mesh
|
||||
the_mesh.sendSelfAdvertisement();
|
||||
the_mesh.sendSelfAdvertisement(2000);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
@@ -612,6 +869,4 @@ void loop() {
|
||||
}
|
||||
|
||||
the_mesh.loop();
|
||||
|
||||
// TODO: periodically check for OLD/inactive entries in known_clients[], and evict
|
||||
}
|
||||
@@ -13,13 +13,14 @@
|
||||
#include <helpers/StaticPoolPacketManager.h>
|
||||
#include <helpers/SimpleMeshTables.h>
|
||||
#include <helpers/IdentityStore.h>
|
||||
#include <helpers/AutoDiscoverRTCClock.h>
|
||||
#include <helpers/AdvertDataHelpers.h>
|
||||
#include <helpers/TxtDataHelpers.h>
|
||||
#include <RTClib.h>
|
||||
|
||||
/* ------------------------------ Config -------------------------------- */
|
||||
|
||||
#define FIRMWARE_VER_TEXT "v3 (build: 30 Jan 2025)"
|
||||
#define FIRMWARE_VER_TEXT "v6 (build: 27 Feb 2025)"
|
||||
|
||||
#ifndef LORA_FREQ
|
||||
#define LORA_FREQ 915.0
|
||||
@@ -59,6 +60,8 @@
|
||||
#define MAX_UNSYNCED_POSTS 16
|
||||
#endif
|
||||
|
||||
#define MIN_LOCAL_ADVERT_INTERVAL 8
|
||||
|
||||
|
||||
#if defined(HELTEC_LORA_V3)
|
||||
#include <helpers/HeltecV3Board.h>
|
||||
@@ -74,7 +77,7 @@
|
||||
#include <helpers/CustomSX1262Wrapper.h>
|
||||
static ESP32Board board;
|
||||
#elif defined(RAK_4631)
|
||||
#include <helpers/RAK4631Board.h>
|
||||
#include <helpers/nrf52/RAK4631Board.h>
|
||||
#include <helpers/CustomSX1262Wrapper.h>
|
||||
static RAK4631Board board;
|
||||
#else
|
||||
@@ -117,8 +120,8 @@ struct PostInfo {
|
||||
};
|
||||
|
||||
#define REPLY_DELAY_MILLIS 1500
|
||||
#define PUSH_NOTIFY_DELAY_MILLIS 1000
|
||||
#define SYNC_PUSH_INTERVAL 1000
|
||||
#define PUSH_NOTIFY_DELAY_MILLIS 2000
|
||||
#define SYNC_PUSH_INTERVAL 2000
|
||||
|
||||
#define PUSH_ACK_TIMEOUT_FLOOD 12000
|
||||
#define PUSH_TIMEOUT_BASE 4000
|
||||
@@ -129,7 +132,6 @@ struct PostInfo {
|
||||
#define REQ_TYPE_KEEP_ALIVE 1
|
||||
|
||||
#define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ
|
||||
#define RESP_SERVER_KEEP_ALIVE 1 // response to REQ_TYPE_KEEP_ALIVE
|
||||
|
||||
struct NodePrefs { // persisted to file
|
||||
float airtime_factor;
|
||||
@@ -137,11 +139,21 @@ struct NodePrefs { // persisted to file
|
||||
double node_lat, node_lon;
|
||||
char password[16];
|
||||
float freq;
|
||||
uint8_t tx_power_dbm;
|
||||
uint8_t disable_fwd;
|
||||
uint8_t advert_interval; // minutes
|
||||
uint8_t unused;
|
||||
float rx_delay_base;
|
||||
float tx_delay_factor;
|
||||
char guest_password[16];
|
||||
float direct_tx_delay_factor;
|
||||
};
|
||||
|
||||
class MyMesh : public mesh::Mesh {
|
||||
RadioLibWrapper* my_radio;
|
||||
FILESYSTEM* _fs;
|
||||
mesh::MainBoard* _board;
|
||||
unsigned long next_local_advert;
|
||||
NodePrefs _prefs;
|
||||
uint8_t reply_data[MAX_PACKET_PAYLOAD];
|
||||
int num_clients;
|
||||
@@ -184,17 +196,14 @@ class MyMesh : public mesh::Mesh {
|
||||
client->pending_ack = 0;
|
||||
}
|
||||
|
||||
void addPost(ClientInfo* client, const char* postData, char reply[]) {
|
||||
void addPost(ClientInfo* client, const char* postData) {
|
||||
// TODO: suggested postData format: <title>/<descrption>
|
||||
posts[next_post_idx].author = client->id; // add to cyclic queue
|
||||
strncpy(posts[next_post_idx].text, postData, MAX_POST_TEXT_LEN);
|
||||
posts[next_post_idx].text[MAX_POST_TEXT_LEN] = 0;
|
||||
StrHelper::strncpy(posts[next_post_idx].text, postData, MAX_POST_TEXT_LEN);
|
||||
|
||||
posts[next_post_idx].post_timestamp = getRTCClock()->getCurrentTime();
|
||||
// TODO: only post at maximum of ONE PER SECOND, so that post_timestamps are UNIQUE!!
|
||||
posts[next_post_idx].post_timestamp = getRTCClock()->getCurrentTimeUnique();
|
||||
next_post_idx = (next_post_idx + 1) % MAX_UNSYNCED_POSTS;
|
||||
|
||||
strcpy(reply, "[Posted]");
|
||||
next_push = futureMillis(PUSH_NOTIFY_DELAY_MILLIS);
|
||||
}
|
||||
|
||||
@@ -241,16 +250,61 @@ class MyMesh : public mesh::Mesh {
|
||||
return false;
|
||||
}
|
||||
|
||||
void checkAdvertInterval() {
|
||||
if (_prefs.advert_interval < MIN_LOCAL_ADVERT_INTERVAL) {
|
||||
_prefs.advert_interval = 0; // turn it off, now that device has been manually configured
|
||||
}
|
||||
}
|
||||
|
||||
void updateAdvertTimer() {
|
||||
if (_prefs.advert_interval > 0) { // schedule local advert timer
|
||||
next_local_advert = futureMillis(_prefs.advert_interval * 60 * 1000);
|
||||
} else {
|
||||
next_local_advert = 0; // stop the timer
|
||||
}
|
||||
}
|
||||
|
||||
mesh::Packet* createSelfAdvert() {
|
||||
uint8_t app_data[MAX_ADVERT_DATA_SIZE];
|
||||
uint8_t app_data_len;
|
||||
{
|
||||
AdvertDataBuilder builder(ADV_TYPE_ROOM, _prefs.node_name, _prefs.node_lat, _prefs.node_lon);
|
||||
app_data_len = builder.encodeTo(app_data);
|
||||
}
|
||||
|
||||
return createAdvert(self_id, app_data, app_data_len);
|
||||
}
|
||||
|
||||
protected:
|
||||
float getAirtimeBudgetFactor() const override {
|
||||
return _prefs.airtime_factor;
|
||||
}
|
||||
|
||||
#if ROOM_IS_ALSO_REPEATER
|
||||
bool allowPacketForward(const mesh::Packet* packet) override {
|
||||
return true; // Yes, allow packet to be forwarded
|
||||
int calcRxDelay(float score, uint32_t air_time) const override {
|
||||
if (_prefs.rx_delay_base <= 0.0f) return 0;
|
||||
return (int) ((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time);
|
||||
}
|
||||
|
||||
const char* getLogDateTime() override {
|
||||
static char tmp[32];
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
DateTime dt = DateTime(now);
|
||||
sprintf(tmp, "%02d:%02d:%02d - %d/%d/%d U", dt.hour(), dt.minute(), dt.second(), dt.day(), dt.month(), dt.year());
|
||||
return tmp;
|
||||
}
|
||||
|
||||
uint32_t getRetransmitDelay(const mesh::Packet* packet) override {
|
||||
uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.tx_delay_factor);
|
||||
return getRNG()->nextInt(0, 6)*t;
|
||||
}
|
||||
uint32_t getDirectRetransmitDelay(const mesh::Packet* packet) override {
|
||||
uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.direct_tx_delay_factor);
|
||||
return getRNG()->nextInt(0, 6)*t;
|
||||
}
|
||||
|
||||
bool allowPacketForward(const mesh::Packet* packet) override {
|
||||
return !_prefs.disable_fwd;
|
||||
}
|
||||
#endif
|
||||
|
||||
void onAnonDataRecv(mesh::Packet* packet, uint8_t type, const mesh::Identity& sender, uint8_t* data, size_t len) override {
|
||||
if (type == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin client (unknown at this stage)
|
||||
@@ -259,16 +313,15 @@ protected:
|
||||
memcpy(&sender_sync_since, &data[4], 4); // sender's "sync messags SINCE x" timestamp
|
||||
|
||||
bool is_admin;
|
||||
if (memcmp(&data[8], _prefs.password, strlen(_prefs.password)) == 0) { // check for valid admin password
|
||||
data[len] = 0; // ensure null terminator
|
||||
if (strcmp((char *) &data[8], _prefs.password) == 0) { // check for valid admin password
|
||||
is_admin = true;
|
||||
} else {
|
||||
is_admin = false;
|
||||
#ifdef ROOM_PASSWORD
|
||||
if (memcmp(&data[8], ROOM_PASSWORD, strlen(ROOM_PASSWORD)) != 0) { // check the room/public password
|
||||
if (strcmp((char *) &data[8], _prefs.guest_password) != 0) { // check the room/public password
|
||||
MESH_DEBUG_PRINTLN("Incorrect room password");
|
||||
return; // no response. Client will timeout
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
auto client = putClient(sender); // add to known clients (if not already known)
|
||||
@@ -287,6 +340,7 @@ protected:
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
client->last_activity = now;
|
||||
|
||||
now = getRTCClock()->getCurrentTimeUnique();
|
||||
memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
|
||||
// TODO: maybe reply with count of messages waiting to be synced for THIS client?
|
||||
reply_data[4] = RESP_SERVER_LOGIN_OK;
|
||||
@@ -295,6 +349,8 @@ protected:
|
||||
reply_data[7] = 0; // FUTURE: reserved
|
||||
memcpy(&reply_data[8], "OK", 2); // REVISIT: not really needed
|
||||
|
||||
next_push = futureMillis(PUSH_NOTIFY_DELAY_MILLIS); // delay next push, give RESPONSE packet time to arrive first
|
||||
|
||||
if (packet->isRouteFlood()) {
|
||||
// let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
|
||||
mesh::Packet* path = createPathReturn(sender, client->secret, packet->path, packet->path_len,
|
||||
@@ -352,7 +408,7 @@ protected:
|
||||
} else if (sender_timestamp > client->last_timestamp) { // prevent replay attacks
|
||||
client->last_timestamp = sender_timestamp;
|
||||
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
uint32_t now = getRTCClock()->getCurrentTimeUnique();
|
||||
client->last_activity = now;
|
||||
client->push_failures = 0; // reset so push can resume (if prev failed)
|
||||
|
||||
@@ -362,24 +418,31 @@ protected:
|
||||
uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove to sender that we got it
|
||||
mesh::Utils::sha256((uint8_t *) &ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key, PUB_KEY_SIZE);
|
||||
|
||||
mesh::Packet* ack = createAck(ack_hash);
|
||||
if (ack) {
|
||||
if (client->out_path_len < 0) {
|
||||
sendFlood(ack);
|
||||
} else {
|
||||
sendDirect(ack, client->out_path, client->out_path_len);
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t temp[166];
|
||||
bool send_ack;
|
||||
if (flags == TXT_TYPE_CLI_DATA) {
|
||||
if (client->is_admin) {
|
||||
handleAdminCommand(sender_timestamp, (const char *) &data[5], (char *) &temp[5]);
|
||||
send_ack = true;
|
||||
} else {
|
||||
strcpy((char *) &temp[5], "auth-err");
|
||||
temp[5] = 0; // no reply
|
||||
send_ack = false; // and no ACK... user shoudn't be sending these
|
||||
}
|
||||
} else { // TXT_TYPE_PLAIN
|
||||
addPost(client, (const char *) &data[5], (char *) &temp[5]);
|
||||
addPost(client, (const char *) &data[5]);
|
||||
temp[5] = 0; // no reply (ACK is enough)
|
||||
send_ack = true;
|
||||
}
|
||||
|
||||
if (send_ack) {
|
||||
mesh::Packet* ack = createAck(ack_hash);
|
||||
if (ack) {
|
||||
if (client->out_path_len < 0) {
|
||||
sendFlood(ack);
|
||||
} else {
|
||||
sendDirect(ack, client->out_path, client->out_path_len);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int text_len = strlen((char *) &temp[5]);
|
||||
@@ -410,25 +473,31 @@ protected:
|
||||
uint32_t sender_timestamp;
|
||||
memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
|
||||
if (data[4] == REQ_TYPE_KEEP_ALIVE && packet->isRouteDirect()) { // request type
|
||||
uint32_t forceSince = 0;
|
||||
if (len >= 9) { // optional - last post_timestamp client received
|
||||
memcpy(&client->sync_since, &data[5], 4); // force-update the 'sync since'
|
||||
memcpy(&forceSince, &data[5], 4); // NOTE: this may be 0, if part of decrypted PADDING!
|
||||
}
|
||||
if (forceSince > 0) {
|
||||
client->sync_since = forceSince; // force-update the 'sync since'
|
||||
len = 9; // for ACK hash calc below
|
||||
} else {
|
||||
len = 5; // for ACK hash calc below
|
||||
}
|
||||
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
client->last_activity = now; // <-- THIS will keep client connection alive
|
||||
client->push_failures = 0; // reset so push can resume (if prev failed)
|
||||
client->pending_ack = 0;
|
||||
|
||||
// TODO: Throttle KEEP_ALIVE requests!
|
||||
// if client sends too quickly, evict()
|
||||
|
||||
// RULE: only send keep_alive response DIRECT!
|
||||
if (client->out_path_len >= 0) {
|
||||
uint8_t temp[8];
|
||||
memcpy(temp, &now, 4); // all responses start with sender timestamp
|
||||
temp[4] = RESP_SERVER_KEEP_ALIVE;
|
||||
memcpy(&temp[5], &client->sync_since, 4); // let client know what server thinks is their 'since'
|
||||
uint32_t ack_hash; // calc ACK to prove to sender that we got request
|
||||
mesh::Utils::sha256((uint8_t *) &ack_hash, 4, data, len, client->id.pub_key, PUB_KEY_SIZE);
|
||||
|
||||
auto reply = createDatagram(PAYLOAD_TYPE_RESPONSE, client->id, secret, temp, 9);
|
||||
auto reply = createAck(ack_hash);
|
||||
if (reply) {
|
||||
sendDirect(reply, client->out_path, client->out_path_len);
|
||||
}
|
||||
@@ -465,20 +534,28 @@ protected:
|
||||
}
|
||||
|
||||
public:
|
||||
MyMesh(RadioLibWrapper& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables)
|
||||
: mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables)
|
||||
MyMesh(mesh::MainBoard& board, RadioLibWrapper& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables)
|
||||
: mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables), _board(&board)
|
||||
{
|
||||
my_radio = &radio;
|
||||
next_local_advert = 0;
|
||||
|
||||
// defaults
|
||||
memset(&_prefs, 0, sizeof(_prefs));
|
||||
_prefs.airtime_factor = 1.0; // one half
|
||||
strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name)-1);
|
||||
_prefs.node_name[sizeof(_prefs.node_name)-1] = 0; // truncate if necessary
|
||||
_prefs.rx_delay_base = 0.0f; // off by default, was 10.0
|
||||
_prefs.tx_delay_factor = 0.5f; // was 0.25f;
|
||||
StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
|
||||
_prefs.node_lat = ADVERT_LAT;
|
||||
_prefs.node_lon = ADVERT_LON;
|
||||
strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password)-1);
|
||||
_prefs.password[sizeof(_prefs.password)-1] = 0; // truncate if necessary
|
||||
StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
|
||||
_prefs.freq = LORA_FREQ;
|
||||
_prefs.tx_power_dbm = LORA_TX_POWER;
|
||||
_prefs.disable_fwd = 1;
|
||||
_prefs.advert_interval = 2; // default to 2 minutes for NEW installs
|
||||
#ifdef ROOM_PASSWORD
|
||||
StrHelper::strncpy(_prefs.guest_password, ROOM_PASSWORD, sizeof(_prefs.guest_password));
|
||||
#endif
|
||||
|
||||
num_clients = 0;
|
||||
next_post_idx = 0;
|
||||
@@ -488,6 +565,7 @@ public:
|
||||
}
|
||||
|
||||
float getFreqPref() const { return _prefs.freq; }
|
||||
uint8_t getTxPowerPref() const { return _prefs.tx_power_dbm; }
|
||||
|
||||
void begin(FILESYSTEM* fs) {
|
||||
mesh::Mesh::begin();
|
||||
@@ -500,6 +578,8 @@ public:
|
||||
file.close();
|
||||
}
|
||||
}
|
||||
|
||||
updateAdvertTimer();
|
||||
}
|
||||
|
||||
void savePrefs() {
|
||||
@@ -515,17 +595,10 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
void sendSelfAdvertisement() {
|
||||
uint8_t app_data[MAX_ADVERT_DATA_SIZE];
|
||||
uint8_t app_data_len;
|
||||
{
|
||||
AdvertDataBuilder builder(ADV_TYPE_ROOM, _prefs.node_name, _prefs.node_lat, _prefs.node_lon);
|
||||
app_data_len = builder.encodeTo(app_data);
|
||||
}
|
||||
|
||||
mesh::Packet* pkt = createAdvert(self_id, app_data, app_data_len);
|
||||
void sendSelfAdvertisement(int delay_millis) {
|
||||
mesh::Packet* pkt = createSelfAdvert();
|
||||
if (pkt) {
|
||||
sendFlood(pkt, 1200); // add slight delay
|
||||
sendFlood(pkt, delay_millis);
|
||||
} else {
|
||||
MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
|
||||
}
|
||||
@@ -537,7 +610,7 @@ public:
|
||||
if (memcmp(command, "reboot", 6) == 0) {
|
||||
board.reboot(); // doesn't return
|
||||
} else if (memcmp(command, "advert", 6) == 0) {
|
||||
sendSelfAdvertisement();
|
||||
sendSelfAdvertisement(400);
|
||||
strcpy(reply, "OK - Advert sent");
|
||||
} else if (memcmp(command, "clock sync", 10) == 0) {
|
||||
uint32_t curr = getRTCClock()->getCurrentTime();
|
||||
@@ -547,6 +620,12 @@ public:
|
||||
} else {
|
||||
strcpy(reply, "ERR: clock cannot go backwards");
|
||||
}
|
||||
} else if (memcmp(command, "start ota", 9) == 0) {
|
||||
if (_board->startOTAUpdate()) {
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error");
|
||||
}
|
||||
} else if (memcmp(command, "clock", 5) == 0) {
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
DateTime dt = DateTime(now);
|
||||
@@ -562,8 +641,7 @@ public:
|
||||
}
|
||||
} else if (memcmp(command, "password ", 9) == 0) {
|
||||
// change admin password
|
||||
strncpy(_prefs.password, &command[9], sizeof(_prefs.password)-1);
|
||||
_prefs.password[sizeof(_prefs.password)-1] = 0; // truncate if necesary
|
||||
StrHelper::strncpy(_prefs.password, &command[9], sizeof(_prefs.password));
|
||||
savePrefs();
|
||||
sprintf(reply, "password now: %s", _prefs.password); // echo back just to let admin know for sure!!
|
||||
} else if (memcmp(command, "set ", 4) == 0) {
|
||||
@@ -572,11 +650,30 @@ public:
|
||||
_prefs.airtime_factor = atof(&config[3]);
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else if (memcmp(config, "name ", 5) == 0) {
|
||||
strncpy(_prefs.node_name, &config[5], sizeof(_prefs.node_name)-1);
|
||||
_prefs.node_name[sizeof(_prefs.node_name)-1] = 0; // truncate if nec
|
||||
} else if (memcmp(config, "advert.interval ", 16) == 0) {
|
||||
int mins = _atoi(&config[16]);
|
||||
if (mins > 0 && mins < MIN_LOCAL_ADVERT_INTERVAL) {
|
||||
sprintf(reply, "Error: min is %d mins", MIN_LOCAL_ADVERT_INTERVAL);
|
||||
} else if (mins > 120) {
|
||||
strcpy(reply, "Error: max is 120 mins");
|
||||
} else {
|
||||
_prefs.advert_interval = (uint8_t)mins;
|
||||
updateAdvertTimer();
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
}
|
||||
} else if (memcmp(config, "guest.password ", 15) == 0) {
|
||||
StrHelper::strncpy(_prefs.guest_password, &config[15], sizeof(_prefs.guest_password));
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else if (memcmp(config, "name ", 5) == 0) {
|
||||
StrHelper::strncpy(_prefs.node_name, &config[5], sizeof(_prefs.node_name));
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else if (memcmp(config, "repeat ", 7) == 0) {
|
||||
_prefs.disable_fwd = memcmp(&config[7], "off", 3) == 0;
|
||||
savePrefs();
|
||||
strcpy(reply, _prefs.disable_fwd ? "OK - repeat is now OFF" : "OK - repeat is now ON");
|
||||
} else if (memcmp(config, "lat ", 4) == 0) {
|
||||
_prefs.node_lat = atof(&config[4]);
|
||||
savePrefs();
|
||||
@@ -585,6 +682,37 @@ public:
|
||||
_prefs.node_lon = atof(&config[4]);
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else if (memcmp(config, "rxdelay ", 8) == 0) {
|
||||
float db = atof(&config[8]);
|
||||
if (db >= 0) {
|
||||
_prefs.rx_delay_base = db;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error, cannot be negative");
|
||||
}
|
||||
} else if (memcmp(config, "txdelay ", 8) == 0) {
|
||||
float f = atof(&config[8]);
|
||||
if (f >= 0) {
|
||||
_prefs.tx_delay_factor = f;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error, cannot be negative");
|
||||
}
|
||||
} else if (memcmp(config, "direct.txdelay ", 15) == 0) {
|
||||
float f = atof(&config[15]);
|
||||
if (f >= 0) {
|
||||
_prefs.direct_tx_delay_factor = f;
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else {
|
||||
strcpy(reply, "Error, cannot be negative");
|
||||
}
|
||||
} else if (memcmp(config, "tx ", 3) == 0) {
|
||||
_prefs.tx_power_dbm = atoi(&config[3]);
|
||||
savePrefs();
|
||||
strcpy(reply, "OK - reboot to apply");
|
||||
} else if (sender_timestamp == 0 && memcmp(config, "freq ", 5) == 0) {
|
||||
_prefs.freq = atof(&config[5]);
|
||||
savePrefs();
|
||||
@@ -634,6 +762,15 @@ public:
|
||||
next_push = futureMillis(SYNC_PUSH_INTERVAL);
|
||||
}
|
||||
|
||||
if (next_local_advert && millisHasNowPassed(next_local_advert)) {
|
||||
mesh::Packet* pkt = createSelfAdvert();
|
||||
if (pkt) {
|
||||
sendZeroHop(pkt);
|
||||
}
|
||||
|
||||
updateAdvertTimer(); // schedule next local advert
|
||||
}
|
||||
|
||||
// TODO: periodically check for OLD/inactive entries in known_clients[], and evict
|
||||
}
|
||||
};
|
||||
@@ -650,12 +787,13 @@ StdRNG fast_rng;
|
||||
SimpleMeshTables tables;
|
||||
|
||||
#ifdef ESP32
|
||||
ESP32RTCClock rtc_clock;
|
||||
ESP32RTCClock fallback_clock;
|
||||
#else
|
||||
VolatileRTCClock rtc_clock;
|
||||
VolatileRTCClock fallback_clock;
|
||||
#endif
|
||||
AutoDiscoverRTCClock rtc_clock(fallback_clock);
|
||||
|
||||
MyMesh the_mesh(*new WRAPPER_CLASS(radio, board), *new ArduinoMillis(), fast_rng, rtc_clock, tables);
|
||||
MyMesh the_mesh(board, *new WRAPPER_CLASS(radio, board), *new ArduinoMillis(), fast_rng, rtc_clock, tables);
|
||||
|
||||
void halt() {
|
||||
while (1) ;
|
||||
@@ -669,8 +807,9 @@ void setup() {
|
||||
|
||||
board.begin();
|
||||
#ifdef ESP32
|
||||
rtc_clock.begin();
|
||||
fallback_clock.begin();
|
||||
#endif
|
||||
rtc_clock.begin(Wire);
|
||||
|
||||
#ifdef SX126X_DIO3_TCXO_VOLTAGE
|
||||
float tcxo = SX126X_DIO3_TCXO_VOLTAGE;
|
||||
@@ -702,11 +841,13 @@ void setup() {
|
||||
radio.setDio2AsRfSwitch(SX126X_DIO2_AS_RF_SWITCH);
|
||||
#endif
|
||||
|
||||
fast_rng.begin(radio.random(0x7FFFFFFF));
|
||||
|
||||
FILESYSTEM* fs;
|
||||
#if defined(NRF52_PLATFORM)
|
||||
InternalFS.begin();
|
||||
fs = &InternalFS;
|
||||
IdentityStore store(InternalFS, "/identity");
|
||||
IdentityStore store(InternalFS, "");
|
||||
#elif defined(ESP32)
|
||||
SPIFFS.begin(true);
|
||||
fs = &SPIFFS;
|
||||
@@ -715,7 +856,8 @@ void setup() {
|
||||
#error "need to define filesystem"
|
||||
#endif
|
||||
if (!store.load("_main", the_mesh.self_id)) {
|
||||
the_mesh.self_id = mesh::LocalIdentity(the_mesh.getRNG()); // create new random identity
|
||||
RadioNoiseListener rng(radio);
|
||||
the_mesh.self_id = mesh::LocalIdentity(&rng); // create new random identity
|
||||
store.save("_main", the_mesh.self_id);
|
||||
}
|
||||
|
||||
@@ -729,9 +871,12 @@ void setup() {
|
||||
if (LORA_FREQ != the_mesh.getFreqPref()) {
|
||||
radio.setFrequency(the_mesh.getFreqPref());
|
||||
}
|
||||
if (LORA_TX_POWER != the_mesh.getTxPowerPref()) {
|
||||
radio.setOutputPower(the_mesh.getTxPowerPref());
|
||||
}
|
||||
|
||||
// send out initial Advertisement to the mesh
|
||||
the_mesh.sendSelfAdvertisement();
|
||||
the_mesh.sendSelfAdvertisement(2000);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
|
||||
/* ---------------------------------- CONFIGURATION ------------------------------------- */
|
||||
|
||||
#define FIRMWARE_VER_TEXT "v2 (build: 4 Feb 2025)"
|
||||
|
||||
#ifndef LORA_FREQ
|
||||
#define LORA_FREQ 915.0
|
||||
#endif
|
||||
@@ -40,10 +42,10 @@
|
||||
|
||||
#include <helpers/BaseChatMesh.h>
|
||||
|
||||
#define SEND_TIMEOUT_BASE_MILLIS 300
|
||||
#define SEND_TIMEOUT_BASE_MILLIS 500
|
||||
#define FLOOD_SEND_TIMEOUT_FACTOR 16.0f
|
||||
#define DIRECT_SEND_PERHOP_FACTOR 4.0f
|
||||
#define DIRECT_SEND_PERHOP_EXTRA_MILLIS 200
|
||||
#define DIRECT_SEND_PERHOP_FACTOR 6.0f
|
||||
#define DIRECT_SEND_PERHOP_EXTRA_MILLIS 250
|
||||
|
||||
#define PUBLIC_GROUP_PSK "izOH6cXN6mrJ5e26oRXNcg=="
|
||||
|
||||
@@ -51,19 +53,27 @@
|
||||
#include <helpers/HeltecV3Board.h>
|
||||
#include <helpers/CustomSX1262Wrapper.h>
|
||||
static HeltecV3Board board;
|
||||
#elif defined(HELTEC_LORA_V2)
|
||||
#include <helpers/HeltecV2Board.h>
|
||||
#include <helpers/CustomSX1276Wrapper.h>
|
||||
static HeltecV2Board board;
|
||||
#elif defined(ARDUINO_XIAO_ESP32C3)
|
||||
#include <helpers/XiaoC3Board.h>
|
||||
#include <helpers/CustomSX1262Wrapper.h>
|
||||
#include <helpers/CustomSX1268Wrapper.h>
|
||||
static XiaoC3Board board;
|
||||
#elif defined(SEEED_XIAO_S3)
|
||||
#elif defined(SEEED_XIAO_S3) || defined(LILYGO_T3S3)
|
||||
#include <helpers/ESP32Board.h>
|
||||
#include <helpers/CustomSX1262Wrapper.h>
|
||||
static ESP32Board board;
|
||||
#elif defined(RAK_4631)
|
||||
#include <helpers/RAK4631Board.h>
|
||||
#include <helpers/nrf52/RAK4631Board.h>
|
||||
#include <helpers/CustomSX1262Wrapper.h>
|
||||
static RAK4631Board board;
|
||||
#elif defined(T1000_E)
|
||||
#include <helpers/nrf52/T1000eBoard.h>
|
||||
#include <helpers/CustomLR1110Wrapper.h>
|
||||
static T1000eBoard board;
|
||||
#else
|
||||
#error "need to provide a 'board' object"
|
||||
#endif
|
||||
@@ -80,13 +90,25 @@ static uint32_t _atoi(const char* sp) {
|
||||
|
||||
/* -------------------------------------------------------------------------------------- */
|
||||
|
||||
struct NodePrefs { // persisted to file
|
||||
float airtime_factor;
|
||||
char node_name[32];
|
||||
double node_lat, node_lon;
|
||||
float freq;
|
||||
uint8_t tx_power_dbm;
|
||||
uint8_t unused[3];
|
||||
};
|
||||
|
||||
class MyMesh : public BaseChatMesh, ContactVisitor {
|
||||
FILESYSTEM* _fs;
|
||||
NodePrefs _prefs;
|
||||
uint32_t expected_ack_crc;
|
||||
mesh::GroupChannel* _public;
|
||||
unsigned long last_msg_sent;
|
||||
ContactInfo* curr_recipient;
|
||||
char command[MAX_TEXT_LEN+1];
|
||||
char command[512+10];
|
||||
uint8_t tmp_buf[256];
|
||||
char hex_buf[512];
|
||||
|
||||
const char* getTypeName(uint8_t type) const {
|
||||
if (type == ADV_TYPE_CHAT) return "Chat";
|
||||
@@ -168,7 +190,37 @@ class MyMesh : public BaseChatMesh, ContactVisitor {
|
||||
}
|
||||
}
|
||||
|
||||
void importCard(const char* command) {
|
||||
while (*command == ' ') command++; // skip leading spaces
|
||||
if (memcmp(command, "meshcore://", 11) == 0) {
|
||||
command += 11; // skip the prefix
|
||||
char *ep = strchr(command, 0); // find end of string
|
||||
while (ep > command) {
|
||||
ep--;
|
||||
if (mesh::Utils::isHexChar(*ep)) break; // found tail end of card
|
||||
*ep = 0; // remove trailing spaces and other junk
|
||||
}
|
||||
int len = strlen(command);
|
||||
if (len % 2 == 0) {
|
||||
len >>= 1; // halve, for num bytes
|
||||
if (mesh::Utils::fromHex(tmp_buf, len, command)) {
|
||||
importContact(tmp_buf, len);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
Serial.println(" error: invalid format");
|
||||
}
|
||||
|
||||
protected:
|
||||
float getAirtimeBudgetFactor() const override {
|
||||
return _prefs.airtime_factor;
|
||||
}
|
||||
|
||||
int calcRxDelay(float score, uint32_t air_time) const override {
|
||||
return 0; // disable rxdelay
|
||||
}
|
||||
|
||||
void onDiscoveredContact(ContactInfo& contact, bool is_new) override {
|
||||
// TODO: if not in favs, prompt to add as fav(?)
|
||||
|
||||
@@ -216,6 +268,10 @@ protected:
|
||||
Serial.printf(" %s\n", text);
|
||||
}
|
||||
|
||||
void onContactResponse(const ContactInfo& contact, const uint8_t* data, uint8_t len) override {
|
||||
// not supported
|
||||
}
|
||||
|
||||
uint32_t calcFloodTimeoutMillisFor(uint32_t pkt_airtime_millis) const override {
|
||||
return SEND_TIMEOUT_BASE_MILLIS + (FLOOD_SEND_TIMEOUT_FACTOR * pkt_airtime_millis);
|
||||
}
|
||||
@@ -229,39 +285,80 @@ protected:
|
||||
}
|
||||
|
||||
public:
|
||||
char self_name[sizeof(ContactInfo::name)];
|
||||
|
||||
MyMesh(RadioLibWrapper& radio, mesh::RNG& rng, mesh::RTCClock& rtc, SimpleMeshTables& tables)
|
||||
: BaseChatMesh(radio, *new ArduinoMillis(), rng, rtc, *new StaticPoolPacketManager(16), tables)
|
||||
{
|
||||
// defaults
|
||||
memset(&_prefs, 0, sizeof(_prefs));
|
||||
_prefs.airtime_factor = 2.0; // one third
|
||||
strcpy(_prefs.node_name, "NONAME");
|
||||
_prefs.freq = LORA_FREQ;
|
||||
_prefs.tx_power_dbm = LORA_TX_POWER;
|
||||
|
||||
command[0] = 0;
|
||||
curr_recipient = NULL;
|
||||
}
|
||||
|
||||
float getFreqPref() const { return _prefs.freq; }
|
||||
uint8_t getTxPowerPref() const { return _prefs.tx_power_dbm; }
|
||||
|
||||
void begin(FILESYSTEM& fs) {
|
||||
_fs = &fs;
|
||||
|
||||
BaseChatMesh::begin();
|
||||
|
||||
strcpy(self_name, "UNSET");
|
||||
#if defined(NRF52_PLATFORM)
|
||||
IdentityStore store(fs, "");
|
||||
#else
|
||||
IdentityStore store(fs, "/identity");
|
||||
if (!store.load("_main", self_id, self_name, sizeof(self_name))) {
|
||||
#endif
|
||||
if (!store.load("_main", self_id, _prefs.node_name, sizeof(_prefs.node_name))) { // legacy: node_name was from identity file
|
||||
self_id = mesh::LocalIdentity(getRNG()); // create new random identity
|
||||
store.save("_main", self_id);
|
||||
}
|
||||
|
||||
// load persisted prefs
|
||||
if (_fs->exists("/node_prefs")) {
|
||||
File file = _fs->open("/node_prefs");
|
||||
if (file) {
|
||||
file.read((uint8_t *) &_prefs, sizeof(_prefs));
|
||||
file.close();
|
||||
}
|
||||
}
|
||||
|
||||
loadContacts();
|
||||
_public = addChannel(PUBLIC_GROUP_PSK); // pre-configure Andy's public channel
|
||||
}
|
||||
|
||||
void savePrefs() {
|
||||
#if defined(NRF52_PLATFORM)
|
||||
File file = _fs->open("/node_prefs", FILE_O_WRITE);
|
||||
if (file) { file.seek(0); file.truncate(); }
|
||||
#else
|
||||
File file = _fs->open("/node_prefs", "w", true);
|
||||
#endif
|
||||
if (file) {
|
||||
file.write((const uint8_t *)&_prefs, sizeof(_prefs));
|
||||
file.close();
|
||||
}
|
||||
}
|
||||
|
||||
void showWelcome() {
|
||||
Serial.println("===== MeshCore Chat Terminal =====");
|
||||
Serial.println();
|
||||
Serial.printf("WELCOME %s\n", self_name);
|
||||
Serial.printf("WELCOME %s\n", _prefs.node_name);
|
||||
Serial.println(" (enter 'help' for basic commands)");
|
||||
Serial.println();
|
||||
}
|
||||
|
||||
void sendSelfAdvert(int delay_millis) {
|
||||
auto pkt = createSelfAdvert(_prefs.node_name, _prefs.node_lat, _prefs.node_lon);
|
||||
if (pkt) {
|
||||
sendFlood(pkt, delay_millis);
|
||||
}
|
||||
}
|
||||
|
||||
// ContactVisitor
|
||||
void onContactVisit(const ContactInfo& contact) override {
|
||||
Serial.printf(" %s - ", contact.name);
|
||||
@@ -295,7 +392,7 @@ public:
|
||||
memcpy(temp, ×tamp, 4); // mostly an extra blob to help make packet_hash unique
|
||||
temp[4] = 0; // attempt and flags
|
||||
|
||||
sprintf((char *) &temp[5], "%s: %s", self_name, &command[7]); // <sender>: <msg>
|
||||
sprintf((char *) &temp[5], "%s: %s", _prefs.node_name, &command[7]); // <sender>: <msg>
|
||||
temp[5 + MAX_TEXT_LEN] = 0; // truncate if too long
|
||||
|
||||
int len = strlen((char *) &temp[5]);
|
||||
@@ -316,11 +413,6 @@ public:
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
DateTime dt = DateTime(now);
|
||||
Serial.printf( "%02d:%02d - %d/%d/%d UTC\n", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
|
||||
} else if (memcmp(command, "name ", 5) == 0) { // set name
|
||||
strncpy(self_name, &command[5], sizeof(self_name)-1);
|
||||
self_name[sizeof(self_name)-1] = 0;
|
||||
IdentityStore store(*_fs, "/identity"); // update IdentityStore
|
||||
store.save("_main", self_id, self_name);
|
||||
} else if (memcmp(command, "time ", 5) == 0) { // set time (to epoch seconds)
|
||||
uint32_t secs = _atoi(&command[5]);
|
||||
setClock(secs);
|
||||
@@ -338,7 +430,7 @@ public:
|
||||
Serial.println(" Err: no recipient selected");
|
||||
}
|
||||
} else if (strcmp(command, "advert") == 0) {
|
||||
auto pkt = createSelfAdvert(self_name);
|
||||
auto pkt = createSelfAdvert(_prefs.node_name, _prefs.node_lat, _prefs.node_lon);
|
||||
if (pkt) {
|
||||
sendZeroHop(pkt);
|
||||
Serial.println(" (advert sent, zero hop).");
|
||||
@@ -351,9 +443,58 @@ public:
|
||||
saveContacts();
|
||||
Serial.println(" Done.");
|
||||
}
|
||||
} else if (memcmp(command, "card", 4) == 0) {
|
||||
Serial.printf("Hello %s\n", _prefs.node_name);
|
||||
auto pkt = createSelfAdvert(_prefs.node_name, _prefs.node_lat, _prefs.node_lon);
|
||||
if (pkt) {
|
||||
uint8_t len = pkt->writeTo(tmp_buf);
|
||||
releasePacket(pkt); // undo the obtainNewPacket()
|
||||
|
||||
mesh::Utils::toHex(hex_buf, tmp_buf, len);
|
||||
Serial.println("Your MeshCore biz card:");
|
||||
Serial.print("meshcore://"); Serial.println(hex_buf);
|
||||
Serial.println();
|
||||
} else {
|
||||
Serial.println(" Error");
|
||||
}
|
||||
} else if (memcmp(command, "import ", 7) == 0) {
|
||||
importCard(&command[7]);
|
||||
} else if (memcmp(command, "set ", 4) == 0) {
|
||||
const char* config = &command[4];
|
||||
if (memcmp(config, "af ", 3) == 0) {
|
||||
_prefs.airtime_factor = atof(&config[3]);
|
||||
savePrefs();
|
||||
Serial.println(" OK");
|
||||
} else if (memcmp(config, "name ", 5) == 0) {
|
||||
StrHelper::strncpy(_prefs.node_name, &config[5], sizeof(_prefs.node_name));
|
||||
savePrefs();
|
||||
Serial.println(" OK");
|
||||
} else if (memcmp(config, "lat ", 4) == 0) {
|
||||
_prefs.node_lat = atof(&config[4]);
|
||||
savePrefs();
|
||||
Serial.println(" OK");
|
||||
} else if (memcmp(config, "lon ", 4) == 0) {
|
||||
_prefs.node_lon = atof(&config[4]);
|
||||
savePrefs();
|
||||
Serial.println(" OK");
|
||||
} else if (memcmp(config, "tx ", 3) == 0) {
|
||||
_prefs.tx_power_dbm = atoi(&config[3]);
|
||||
savePrefs();
|
||||
Serial.println(" OK - reboot to apply");
|
||||
} else if (memcmp(config, "freq ", 5) == 0) {
|
||||
_prefs.freq = atof(&config[5]);
|
||||
savePrefs();
|
||||
Serial.println(" OK - reboot to apply");
|
||||
} else {
|
||||
Serial.printf(" ERROR: unknown config: %s\n", config);
|
||||
}
|
||||
} else if (memcmp(command, "ver", 3) == 0) {
|
||||
Serial.println(FIRMWARE_VER_TEXT);
|
||||
} else if (memcmp(command, "help", 4) == 0) {
|
||||
Serial.printf("Hello %s, Commands:\n", self_name);
|
||||
Serial.println(" name <your name>");
|
||||
Serial.println("Commands:");
|
||||
Serial.println(" set {name|lat|lon|freq|tx|af} {value}");
|
||||
Serial.println(" card");
|
||||
Serial.println(" import {biz card}");
|
||||
Serial.println(" clock");
|
||||
Serial.println(" time <epoch-seconds>");
|
||||
Serial.println(" list {n}");
|
||||
@@ -454,13 +595,17 @@ void setup() {
|
||||
#error "need to define filesystem"
|
||||
#endif
|
||||
|
||||
if (LORA_FREQ != the_mesh.getFreqPref()) {
|
||||
radio.setFrequency(the_mesh.getFreqPref());
|
||||
}
|
||||
if (LORA_TX_POWER != the_mesh.getTxPowerPref()) {
|
||||
radio.setOutputPower(the_mesh.getTxPowerPref());
|
||||
}
|
||||
|
||||
the_mesh.showWelcome();
|
||||
|
||||
// send out initial Advertisement to the mesh
|
||||
auto pkt = the_mesh.createSelfAdvert(the_mesh.self_name);
|
||||
if (pkt) {
|
||||
the_mesh.sendFlood(pkt, 1200); // add slight delay
|
||||
}
|
||||
the_mesh.sendSelfAdvert(1200); // add slight delay
|
||||
}
|
||||
|
||||
void loop() {
|
||||
|
||||
@@ -1,315 +0,0 @@
|
||||
#include <Arduino.h> // needed for PlatformIO
|
||||
#include <Mesh.h>
|
||||
#include <SPIFFS.h>
|
||||
|
||||
#define RADIOLIB_STATIC_ONLY 1
|
||||
#include <RadioLib.h>
|
||||
#include <helpers/CustomSX1262Wrapper.h>
|
||||
#include <helpers/ArduinoHelpers.h>
|
||||
#include <helpers/SimpleMeshTables.h>
|
||||
#include <helpers/StaticPoolPacketManager.h>
|
||||
|
||||
/* ---------------------------------- CONFIGURATION ------------------------------------- */
|
||||
|
||||
#ifndef LORA_FREQ
|
||||
#define LORA_FREQ 915.0
|
||||
#endif
|
||||
#ifndef LORA_BW
|
||||
#define LORA_BW 125
|
||||
#endif
|
||||
#ifndef LORA_SF
|
||||
#define LORA_SF 9
|
||||
#endif
|
||||
#ifndef LORA_CR
|
||||
#define LORA_CR 5
|
||||
#endif
|
||||
|
||||
#define ADMIN_PASSWORD "h^(kl@#)"
|
||||
|
||||
#ifdef HELTEC_LORA_V3
|
||||
#include <helpers/HeltecV3Board.h>
|
||||
static HeltecV3Board board;
|
||||
#else
|
||||
#error "need to provide a 'board' object"
|
||||
#endif
|
||||
|
||||
/* -------------------------------------------------------------------------------------- */
|
||||
|
||||
#define MAX_TEXT_LEN (10*CIPHER_BLOCK_SIZE) // must be LESS than (MAX_PACKET_PAYLOAD - FROM_HASH_LEN - CIPHER_MAC_SIZE - 1)
|
||||
|
||||
#define CMD_GET_STATS 0x01
|
||||
#define CMD_SET_CLOCK 0x02
|
||||
#define CMD_SEND_ANNOUNCE 0x03
|
||||
#define CMD_SET_CONFIG 0x04
|
||||
|
||||
struct RepeaterStats {
|
||||
uint16_t batt_milli_volts;
|
||||
uint16_t curr_tx_queue_len;
|
||||
uint16_t curr_free_queue_len;
|
||||
int16_t last_rssi;
|
||||
uint32_t n_packets_recv;
|
||||
uint32_t n_packets_sent;
|
||||
uint32_t total_air_time_secs;
|
||||
uint32_t total_up_time_secs;
|
||||
uint32_t n_sent_flood, n_sent_direct;
|
||||
uint32_t n_recv_flood, n_recv_direct;
|
||||
uint32_t n_full_events;
|
||||
};
|
||||
|
||||
class MyMesh : public mesh::Mesh {
|
||||
uint32_t last_advert_timestamp = 0;
|
||||
mesh::Identity server_id;
|
||||
uint8_t server_secret[PUB_KEY_SIZE];
|
||||
int server_path_len = -1;
|
||||
uint8_t server_path[MAX_PATH_SIZE];
|
||||
bool got_adv = false;
|
||||
|
||||
protected:
|
||||
void onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, uint32_t timestamp, const uint8_t* app_data, size_t app_data_len) override {
|
||||
if (memcmp(app_data, "repeater:", 9) == 0) {
|
||||
Serial.println("Received advertisement from a repeater!");
|
||||
|
||||
// check for replay attacks
|
||||
if (timestamp > last_advert_timestamp) {
|
||||
last_advert_timestamp = timestamp;
|
||||
|
||||
server_id = id;
|
||||
self_id.calcSharedSecret(server_secret, id); // calc ECDH shared secret
|
||||
got_adv = true;
|
||||
|
||||
// 'login' to repeater. (mainly lets it know our public key)
|
||||
uint32_t now = getRTCClock()->getCurrentTime(); // important, need timestamp in packet, so that packet_hash will be unique
|
||||
uint8_t temp[4 + 8];
|
||||
memcpy(temp, &now, 4);
|
||||
memcpy(&temp[4], ADMIN_PASSWORD, 8);
|
||||
|
||||
mesh::Packet* login = createAnonDatagram(PAYLOAD_TYPE_ANON_REQ, self_id, server_id, server_secret, temp, sizeof(temp));
|
||||
if (login) sendFlood(login); // server_path won't be known yet
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void handleResponse(const uint8_t* reply, size_t reply_len) {
|
||||
if (reply_len >= 4 + sizeof(RepeaterStats)) { // got an GET_STATS reply from repeater
|
||||
RepeaterStats stats;
|
||||
memcpy(&stats, &reply[4], sizeof(stats));
|
||||
Serial.println("Repeater Stats:");
|
||||
Serial.printf(" battery: %d mV\n", (uint32_t) stats.batt_milli_volts);
|
||||
Serial.printf(" tx queue: %d\n", (uint32_t) stats.curr_tx_queue_len);
|
||||
Serial.printf(" free queue: %d\n", (uint32_t) stats.curr_free_queue_len);
|
||||
Serial.printf(" last RSSI: %d\n", (int) stats.last_rssi);
|
||||
Serial.printf(" num recv: %d\n", stats.n_packets_recv);
|
||||
Serial.printf(" num sent: %d\n", stats.n_packets_sent);
|
||||
Serial.printf(" air time (secs): %d\n", stats.total_air_time_secs);
|
||||
Serial.printf(" up time (secs): %d\n", stats.total_up_time_secs);
|
||||
} else if (reply_len > 4) { // got an SET_* reply from repeater
|
||||
char tmp[MAX_PACKET_PAYLOAD];
|
||||
memcpy(tmp, &reply[4], reply_len - 4);
|
||||
tmp[reply_len - 4] = 0; // make a C string of reply
|
||||
|
||||
Serial.print("Reply: "); Serial.println(tmp);
|
||||
}
|
||||
}
|
||||
|
||||
int searchPeersByHash(const uint8_t* hash) override {
|
||||
if (got_adv && server_id.isHashMatch(hash)) {
|
||||
return 1;
|
||||
}
|
||||
return 0; // not found
|
||||
}
|
||||
|
||||
void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override {
|
||||
// lookup pre-calculated shared_secret
|
||||
memcpy(dest_secret, server_secret, PUB_KEY_SIZE);
|
||||
}
|
||||
|
||||
void onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, const uint8_t* secret, uint8_t* data, size_t len) override {
|
||||
if (type == PAYLOAD_TYPE_RESPONSE) {
|
||||
handleResponse(data, len);
|
||||
|
||||
if (packet->isRouteFlood()) {
|
||||
// let server know path TO here, so they can use sendDirect() for future ping responses
|
||||
mesh::Packet* path = createPathReturn(server_id, secret, packet->path, packet->path_len, 0, NULL, 0);
|
||||
if (path) sendFlood(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool onPeerPathRecv(mesh::Packet* packet, int sender_idx, const uint8_t* secret, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) override {
|
||||
// must be from server_id
|
||||
Serial.printf("PATH to repeater, path_len=%d\n", (uint32_t) path_len);
|
||||
|
||||
memcpy(server_path, path, server_path_len = path_len); // store a copy of path, for sendDirect()
|
||||
|
||||
if (extra_type == PAYLOAD_TYPE_RESPONSE) {
|
||||
handleResponse(extra, extra_len);
|
||||
}
|
||||
return true; // send reciprocal path if necessary
|
||||
}
|
||||
|
||||
public:
|
||||
MyMesh(mesh::Radio& radio, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables)
|
||||
: mesh::Mesh(radio, *new ArduinoMillis(), rng, rtc, *new StaticPoolPacketManager(16), tables)
|
||||
{
|
||||
}
|
||||
|
||||
mesh::Packet* createStatsRequest(uint32_t max_age) {
|
||||
uint8_t payload[9];
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
memcpy(payload, &now, 4);
|
||||
payload[4] = CMD_GET_STATS;
|
||||
memcpy(&payload[5], &max_age, 4);
|
||||
|
||||
return createDatagram(PAYLOAD_TYPE_REQ, server_id, server_secret, payload, sizeof(payload));
|
||||
}
|
||||
|
||||
mesh::Packet* createSetClockRequest(uint32_t timestamp) {
|
||||
uint8_t payload[9];
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
memcpy(payload, &now, 4);
|
||||
payload[4] = CMD_SET_CLOCK;
|
||||
memcpy(&payload[5], &now, 4); // repeated :-(
|
||||
|
||||
return createDatagram(PAYLOAD_TYPE_REQ, server_id, server_secret, payload, sizeof(payload));
|
||||
}
|
||||
|
||||
mesh::Packet* createSetAirtimeFactorRequest(float airtime_factor) {
|
||||
uint8_t payload[16];
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
memcpy(payload, &now, 4);
|
||||
payload[4] = CMD_SET_CONFIG;
|
||||
sprintf((char *) &payload[5], "AF%f", airtime_factor);
|
||||
|
||||
return createDatagram(PAYLOAD_TYPE_REQ, server_id, server_secret, payload, sizeof(payload));
|
||||
}
|
||||
|
||||
mesh::Packet* createAnnounceRequest() {
|
||||
uint8_t payload[5];
|
||||
uint32_t now = getRTCClock()->getCurrentTime();
|
||||
memcpy(payload, &now, 4);
|
||||
payload[4] = CMD_SEND_ANNOUNCE;
|
||||
|
||||
return createDatagram(PAYLOAD_TYPE_REQ, server_id, server_secret, payload, sizeof(payload));
|
||||
}
|
||||
|
||||
mesh::Packet* parseCommand(char* command) {
|
||||
if (strcmp(command, "stats") == 0) {
|
||||
return createStatsRequest(60*60); // max_age = one hour
|
||||
} else if (memcmp(command, "setclock ", 9) == 0) {
|
||||
uint32_t timestamp = atol(&command[9]);
|
||||
return createSetClockRequest(timestamp);
|
||||
} else if (memcmp(command, "set AF=", 7) == 0) {
|
||||
float factor = atof(&command[7]);
|
||||
return createSetAirtimeFactorRequest(factor);
|
||||
} else if (strcmp(command, "ann") == 0) {
|
||||
return createAnnounceRequest();
|
||||
}
|
||||
return NULL; // unknown command
|
||||
}
|
||||
|
||||
void sendCommand(mesh::Packet* pkt) {
|
||||
if (server_path_len < 0) {
|
||||
sendFlood(pkt);
|
||||
} else {
|
||||
sendDirect(pkt, server_path, server_path_len);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
StdRNG fast_rng;
|
||||
SimpleMeshTables tables;
|
||||
#if defined(P_LORA_SCLK)
|
||||
SPIClass spi;
|
||||
CustomSX1262 radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi);
|
||||
#else
|
||||
CustomSX1262 radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY);
|
||||
#endif
|
||||
MyMesh the_mesh(*new CustomSX1262Wrapper(radio, board), fast_rng, *new VolatileRTCClock(), tables);
|
||||
|
||||
void halt() {
|
||||
while (1) ;
|
||||
}
|
||||
|
||||
static char command[MAX_TEXT_LEN+1];
|
||||
|
||||
#include <SHA256.h>
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
delay(5000);
|
||||
|
||||
board.begin();
|
||||
#if defined(P_LORA_SCLK)
|
||||
spi.begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI);
|
||||
int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 22, 8);
|
||||
#else
|
||||
int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 22, 8);
|
||||
#endif
|
||||
if (status != RADIOLIB_ERR_NONE) {
|
||||
Serial.print("ERROR: radio init failed: ");
|
||||
Serial.println(status);
|
||||
halt();
|
||||
}
|
||||
|
||||
fast_rng.begin(radio.random(0x7FFFFFFF));
|
||||
|
||||
/* add this to tests
|
||||
uint8_t mac_encrypted[CIPHER_MAC_SIZE+CIPHER_BLOCK_SIZE];
|
||||
const char *orig_msg = "original";
|
||||
int enc_len = mesh::Utils::encryptThenMAC(mesh.admin_secret, mac_encrypted, (const uint8_t *) orig_msg, strlen(orig_msg));
|
||||
char decrypted[CIPHER_BLOCK_SIZE*2];
|
||||
int len = mesh::Utils::MACThenDecrypt(mesh.admin_secret, (uint8_t *)decrypted, mac_encrypted, enc_len);
|
||||
if (len > 0) {
|
||||
decrypted[len] = 0;
|
||||
Serial.print("decrypted text: "); Serial.println(decrypted);
|
||||
} else {
|
||||
Serial.println("MACs DONT match!");
|
||||
}
|
||||
*/
|
||||
|
||||
Serial.println("Help:");
|
||||
Serial.println(" enter 'key' to generate new keypair");
|
||||
Serial.println(" enter 'stats' to request repeater stats");
|
||||
Serial.println(" enter 'setclock {unix-epoch-seconds}' to set repeater's clock");
|
||||
Serial.println(" enter 'set AF={factor}' to set airtime budget factor");
|
||||
Serial.println(" enter 'ann' to make repeater re-announce to mesh");
|
||||
|
||||
the_mesh.begin();
|
||||
|
||||
command[0] = 0;
|
||||
}
|
||||
|
||||
void loop() {
|
||||
int len = strlen(command);
|
||||
while (Serial.available() && len < sizeof(command)-1) {
|
||||
char c = Serial.read();
|
||||
if (c != '\n') {
|
||||
command[len++] = c;
|
||||
command[len] = 0;
|
||||
}
|
||||
Serial.print(c);
|
||||
}
|
||||
if (len == sizeof(command)-1) { // command buffer full
|
||||
command[sizeof(command)-1] = '\r';
|
||||
}
|
||||
|
||||
if (len > 0 && command[len - 1] == '\r') { // received complete line
|
||||
command[len - 1] = 0; // replace newline with C string null terminator
|
||||
|
||||
if (strcmp(command, "key") == 0) {
|
||||
mesh::LocalIdentity new_id(the_mesh.getRNG());
|
||||
new_id.printTo(Serial);
|
||||
} else {
|
||||
mesh::Packet* pkt = the_mesh.parseCommand(command);
|
||||
if (pkt) {
|
||||
the_mesh.sendCommand(pkt);
|
||||
Serial.println(" (request sent)");
|
||||
} else {
|
||||
Serial.print(" ERROR: unknown command: "); Serial.println(command);
|
||||
}
|
||||
}
|
||||
command[0] = 0; // reset command buffer
|
||||
}
|
||||
|
||||
the_mesh.loop();
|
||||
}
|
||||
+242
-52
@@ -16,7 +16,9 @@ lib_deps =
|
||||
Wire
|
||||
jgromes/RadioLib @ ^6.3.0
|
||||
rweather/Crypto @ ^0.4.0
|
||||
build_flags = -w -DNDEBUG -DRADIOLIB_STATIC_ONLY=1
|
||||
adafruit/RTClib @ ^2.1.3
|
||||
melopero/Melopero RV3028 @ ^1.1.0
|
||||
build_flags = -w -DNDEBUG -DRADIOLIB_STATIC_ONLY=1 -DRADIOLIB_GODMODE=1
|
||||
-D LORA_FREQ=867.5
|
||||
-D LORA_BW=250
|
||||
-D LORA_SF=10
|
||||
@@ -29,13 +31,74 @@ monitor_filters = esp32_exception_decoder
|
||||
extra_scripts = merge-bin.py
|
||||
build_src_filter = ${arduino_base.build_src_filter}
|
||||
|
||||
[Heltec_stick_lite]
|
||||
extends = esp32_base
|
||||
board = heltec_wireless_stick_lite
|
||||
|
||||
; ================
|
||||
[Heltec_lora32_v2]
|
||||
extends = esp32_base
|
||||
board = heltec_wifi_lora_32_V2
|
||||
board = heltec_wifi_lora_32_V2 ; heltec_wifi_lora_32_V2
|
||||
build_flags =
|
||||
${esp32_base.build_flags}
|
||||
-D HELTEC_LORA_V2
|
||||
-D RADIO_CLASS=CustomSX1276
|
||||
-D WRAPPER_CLASS=CustomSX1276Wrapper
|
||||
-D LORA_TX_POWER=20
|
||||
-D P_LORA_TX_LED=25
|
||||
build_src_filter = ${esp32_base.build_src_filter}
|
||||
|
||||
[env:Heltec_v2_repeater]
|
||||
extends = Heltec_lora32_v2
|
||||
build_flags =
|
||||
${Heltec_lora32_v2.build_flags}
|
||||
-D ADVERT_NAME="\"Heltec Repeater\""
|
||||
-D ADVERT_LAT=-37.0
|
||||
-D ADVERT_LON=145.0
|
||||
-D ADMIN_PASSWORD="\"password\""
|
||||
; -D MESH_PACKET_LOGGING=1
|
||||
; -D MESH_DEBUG=1
|
||||
build_src_filter = ${Heltec_lora32_v2.build_src_filter} +<../examples/simple_repeater/main.cpp>
|
||||
|
||||
[env:Heltec_v2_terminal_chat]
|
||||
extends = Heltec_lora32_v2
|
||||
build_flags =
|
||||
${Heltec_lora32_v2.build_flags}
|
||||
-D MAX_CONTACTS=100
|
||||
-D MAX_GROUP_CHANNELS=1
|
||||
; -D MESH_PACKET_LOGGING=1
|
||||
; -D MESH_DEBUG=1
|
||||
build_src_filter = ${Heltec_lora32_v2.build_src_filter} +<../examples/simple_secure_chat/main.cpp>
|
||||
lib_deps =
|
||||
${Heltec_lora32_v2.lib_deps}
|
||||
densaugeo/base64 @ ~1.4.0
|
||||
|
||||
[env:Heltec_v2_companion_radio_usb]
|
||||
extends = Heltec_lora32_v2
|
||||
build_flags =
|
||||
${Heltec_lora32_v2.build_flags}
|
||||
-D MAX_CONTACTS=100
|
||||
-D MAX_GROUP_CHANNELS=1
|
||||
; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1
|
||||
; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1
|
||||
build_src_filter = ${Heltec_lora32_v2.build_src_filter} +<helpers/esp32/*.cpp> +<../examples/companion_radio/main.cpp>
|
||||
lib_deps =
|
||||
${Heltec_lora32_v2.lib_deps}
|
||||
densaugeo/base64 @ ~1.4.0
|
||||
|
||||
[env:Heltec_v2_companion_radio_ble]
|
||||
extends = Heltec_lora32_v2
|
||||
build_flags =
|
||||
${Heltec_lora32_v2.build_flags}
|
||||
-D MAX_CONTACTS=100
|
||||
-D MAX_GROUP_CHANNELS=1
|
||||
-D BLE_PIN_CODE=123456
|
||||
-D BLE_DEBUG_LOGGING=1
|
||||
; -D ENABLE_PRIVATE_KEY_IMPORT=1
|
||||
; -D ENABLE_PRIVATE_KEY_EXPORT=1
|
||||
; -D MESH_PACKET_LOGGING=1
|
||||
; -D MESH_DEBUG=1
|
||||
build_src_filter = ${Heltec_lora32_v2.build_src_filter} +<helpers/esp32/*.cpp> +<../examples/companion_radio/main.cpp>
|
||||
lib_deps =
|
||||
${Heltec_lora32_v2.lib_deps}
|
||||
densaugeo/base64 @ ~1.4.0
|
||||
|
||||
|
||||
; ================
|
||||
[Heltec_lora32_v3]
|
||||
@@ -53,14 +116,6 @@ build_flags =
|
||||
-D SX126X_CURRENT_LIMIT=130.0f ; for best TX power!
|
||||
build_src_filter = ${esp32_base.build_src_filter}
|
||||
|
||||
[env:Heltec_v3_ping_server]
|
||||
extends = Heltec_lora32_v3
|
||||
build_src_filter = ${Heltec_lora32_v3.build_src_filter} +<../examples/ping_server/main.cpp>
|
||||
|
||||
[env:Heltec_v3_ping_client]
|
||||
extends = Heltec_lora32_v3
|
||||
build_src_filter = ${Heltec_lora32_v3.build_src_filter} +<../examples/ping_client/main.cpp>
|
||||
|
||||
[env:Heltec_v3_repeater]
|
||||
extends = Heltec_lora32_v3
|
||||
build_flags =
|
||||
@@ -69,12 +124,9 @@ build_flags =
|
||||
-D ADVERT_LAT=-37.0
|
||||
-D ADVERT_LON=145.0
|
||||
-D ADMIN_PASSWORD="\"password\""
|
||||
; -D MESH_PACKET_LOGGING=1
|
||||
-D MESH_PACKET_LOGGING=1
|
||||
; -D MESH_DEBUG=1
|
||||
build_src_filter = ${Heltec_lora32_v3.build_src_filter} +<../examples/simple_repeater/main.cpp>
|
||||
lib_deps =
|
||||
${Heltec_lora32_v3.lib_deps}
|
||||
adafruit/RTClib @ ^2.1.3
|
||||
|
||||
[env:Heltec_v3_room_server]
|
||||
extends = Heltec_lora32_v3
|
||||
@@ -88,9 +140,6 @@ build_flags =
|
||||
-D ROOM_PASSWORD="\"hello\""
|
||||
; -D MESH_PACKET_LOGGING=1
|
||||
; -D MESH_DEBUG=1
|
||||
lib_deps =
|
||||
${Heltec_lora32_v3.lib_deps}
|
||||
adafruit/RTClib @ ^2.1.3
|
||||
|
||||
[env:Heltec_v3_terminal_chat]
|
||||
extends = Heltec_lora32_v3
|
||||
@@ -103,7 +152,6 @@ build_flags =
|
||||
build_src_filter = ${Heltec_lora32_v3.build_src_filter} +<../examples/simple_secure_chat/main.cpp>
|
||||
lib_deps =
|
||||
${Heltec_lora32_v3.lib_deps}
|
||||
adafruit/RTClib @ ^2.1.3
|
||||
densaugeo/base64 @ ~1.4.0
|
||||
|
||||
[env:Heltec_v3_companion_radio_usb]
|
||||
@@ -112,12 +160,13 @@ build_flags =
|
||||
${Heltec_lora32_v3.build_flags}
|
||||
-D MAX_CONTACTS=100
|
||||
-D MAX_GROUP_CHANNELS=1
|
||||
; -D MESH_PACKET_LOGGING=1
|
||||
; -D MESH_DEBUG=1
|
||||
; -D ENABLE_PRIVATE_KEY_IMPORT=1
|
||||
; -D ENABLE_PRIVATE_KEY_EXPORT=1
|
||||
; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1
|
||||
; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1
|
||||
build_src_filter = ${Heltec_lora32_v3.build_src_filter} +<../examples/companion_radio/main.cpp>
|
||||
lib_deps =
|
||||
${Heltec_lora32_v3.lib_deps}
|
||||
adafruit/RTClib @ ^2.1.3
|
||||
densaugeo/base64 @ ~1.4.0
|
||||
|
||||
[env:Heltec_v3_companion_radio_ble]
|
||||
@@ -128,20 +177,15 @@ build_flags =
|
||||
-D MAX_GROUP_CHANNELS=1
|
||||
-D BLE_PIN_CODE=123456
|
||||
-D BLE_DEBUG_LOGGING=1
|
||||
; -D ENABLE_PRIVATE_KEY_IMPORT=1
|
||||
; -D ENABLE_PRIVATE_KEY_EXPORT=1
|
||||
; -D MESH_PACKET_LOGGING=1
|
||||
; -D MESH_DEBUG=1
|
||||
build_src_filter = ${Heltec_lora32_v3.build_src_filter} +<helpers/esp32/*.cpp> +<../examples/companion_radio/main.cpp>
|
||||
lib_deps =
|
||||
${Heltec_lora32_v3.lib_deps}
|
||||
adafruit/RTClib @ ^2.1.3
|
||||
densaugeo/base64 @ ~1.4.0
|
||||
|
||||
[env:Heltec_v3_test_admin]
|
||||
extends = Heltec_lora32_v3
|
||||
build_flags =
|
||||
${Heltec_lora32_v3.build_flags}
|
||||
build_src_filter = ${Heltec_lora32_v3.build_src_filter} +<../examples/test_admin/main.cpp>
|
||||
|
||||
; ================
|
||||
[Xiao_esp32_C3]
|
||||
extends = esp32_base
|
||||
@@ -155,6 +199,8 @@ build_flags =
|
||||
-D P_LORA_NSS=D4
|
||||
-D P_LORA_RESET=RADIOLIB_NC
|
||||
-D P_LORA_BUSY=D1
|
||||
-D PIN_BOARD_SDA=D6
|
||||
-D PIN_BOARD_SCL=D7
|
||||
-D SX126X_DIO2_AS_RF_SWITCH=true
|
||||
-D SX126X_DIO3_TCXO_VOLTAGE=1.8
|
||||
-D SX126X_CURRENT_LIMIT=130.0f ; for best TX power!
|
||||
@@ -173,9 +219,6 @@ build_flags =
|
||||
-D ADMIN_PASSWORD="\"password\""
|
||||
; -D MESH_PACKET_LOGGING=1
|
||||
; -D MESH_DEBUG=1
|
||||
lib_deps =
|
||||
${Xiao_esp32_C3.lib_deps}
|
||||
adafruit/RTClib @ ^2.1.3
|
||||
|
||||
[env:Xiao_C3_Repeater_sx1268]
|
||||
extends = Xiao_esp32_C3
|
||||
@@ -191,9 +234,6 @@ build_flags =
|
||||
-D ADMIN_PASSWORD="\"password\""
|
||||
; -D MESH_PACKET_LOGGING=1
|
||||
; -D MESH_DEBUG=1
|
||||
lib_deps =
|
||||
${Xiao_esp32_C3.lib_deps}
|
||||
adafruit/RTClib @ ^2.1.3
|
||||
|
||||
; =============
|
||||
[Xiao_S3_WIO]
|
||||
@@ -228,9 +268,6 @@ build_flags =
|
||||
-D ADMIN_PASSWORD="\"password\""
|
||||
; -D MESH_PACKET_LOGGING=1
|
||||
; -D MESH_DEBUG=1
|
||||
lib_deps =
|
||||
${Xiao_S3_WIO.lib_deps}
|
||||
adafruit/RTClib @ ^2.1.3
|
||||
|
||||
[env:Xiao_S3_WIO_terminal_chat]
|
||||
extends = Xiao_S3_WIO
|
||||
@@ -243,7 +280,102 @@ build_flags =
|
||||
build_src_filter = ${Xiao_S3_WIO.build_src_filter} +<../examples/simple_secure_chat/main.cpp>
|
||||
lib_deps =
|
||||
${Xiao_S3_WIO.lib_deps}
|
||||
adafruit/RTClib @ ^2.1.3
|
||||
densaugeo/base64 @ ~1.4.0
|
||||
|
||||
[env:Xiao_S3_WIO_companion_radio_ble]
|
||||
extends = Xiao_S3_WIO
|
||||
build_flags =
|
||||
${Xiao_S3_WIO.build_flags}
|
||||
-D MAX_CONTACTS=100
|
||||
-D MAX_GROUP_CHANNELS=1
|
||||
-D BLE_PIN_CODE=123456
|
||||
; -D BLE_DEBUG_LOGGING=1
|
||||
; -D ENABLE_PRIVATE_KEY_IMPORT=1
|
||||
; -D ENABLE_PRIVATE_KEY_EXPORT=1
|
||||
; -D MESH_PACKET_LOGGING=1
|
||||
; -D MESH_DEBUG=1
|
||||
build_src_filter = ${Xiao_S3_WIO.build_src_filter} +<helpers/esp32/*.cpp> +<../examples/companion_radio/main.cpp>
|
||||
lib_deps =
|
||||
${Xiao_S3_WIO.lib_deps}
|
||||
densaugeo/base64 @ ~1.4.0
|
||||
|
||||
; =============
|
||||
[LilyGo_T3S3_sx1262]
|
||||
extends = esp32_base
|
||||
board = t3_s3_v1_x
|
||||
build_flags = ${esp32_base.build_flags}
|
||||
-D LILYGO_T3S3
|
||||
-D P_LORA_DIO_1=33
|
||||
-D P_LORA_NSS=7
|
||||
-D P_LORA_RESET=8 ; RADIOLIB_NC
|
||||
-D P_LORA_BUSY=34
|
||||
-D P_LORA_SCLK=5
|
||||
-D P_LORA_MISO=3
|
||||
-D P_LORA_MOSI=6
|
||||
-D P_LORA_TX_LED=37
|
||||
-D PIN_VBAT_READ=1
|
||||
-D SX126X_DIO2_AS_RF_SWITCH=true
|
||||
-D SX126X_DIO3_TCXO_VOLTAGE=1.8
|
||||
-D SX126X_CURRENT_LIMIT=130
|
||||
-D RADIO_CLASS=CustomSX1262
|
||||
-D WRAPPER_CLASS=CustomSX1262Wrapper
|
||||
-D LORA_TX_POWER=22
|
||||
|
||||
[env:LilyGo_T3S3_sx1262_Repeater]
|
||||
extends = LilyGo_T3S3_sx1262
|
||||
build_src_filter = ${LilyGo_T3S3_sx1262.build_src_filter} +<../examples/simple_repeater/main.cpp>
|
||||
build_flags =
|
||||
${LilyGo_T3S3_sx1262.build_flags}
|
||||
-D ADVERT_NAME="\"T3S3 Repeater\""
|
||||
-D ADVERT_LAT=-37.0
|
||||
-D ADVERT_LON=145.0
|
||||
-D ADMIN_PASSWORD="\"password\""
|
||||
; -D MESH_PACKET_LOGGING=1
|
||||
; -D MESH_DEBUG=1
|
||||
|
||||
[env:LilyGo_T3S3_sx1262_terminal_chat]
|
||||
extends = LilyGo_T3S3_sx1262
|
||||
build_flags =
|
||||
${LilyGo_T3S3_sx1262.build_flags}
|
||||
-D MAX_CONTACTS=100
|
||||
-D MAX_GROUP_CHANNELS=1
|
||||
; -D MESH_PACKET_LOGGING=1
|
||||
; -D MESH_DEBUG=1
|
||||
build_src_filter = ${LilyGo_T3S3_sx1262.build_src_filter} +<../examples/simple_secure_chat/main.cpp>
|
||||
lib_deps =
|
||||
${LilyGo_T3S3_sx1262.lib_deps}
|
||||
densaugeo/base64 @ ~1.4.0
|
||||
|
||||
[env:LilyGo_T3S3_sx1262_companion_radio_usb]
|
||||
extends = LilyGo_T3S3_sx1262
|
||||
build_flags =
|
||||
${LilyGo_T3S3_sx1262.build_flags}
|
||||
-D MAX_CONTACTS=100
|
||||
-D MAX_GROUP_CHANNELS=1
|
||||
; -D ENABLE_PRIVATE_KEY_IMPORT=1
|
||||
; -D ENABLE_PRIVATE_KEY_EXPORT=1
|
||||
; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1
|
||||
; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1
|
||||
build_src_filter = ${LilyGo_T3S3_sx1262.build_src_filter} +<../examples/companion_radio/main.cpp>
|
||||
lib_deps =
|
||||
${LilyGo_T3S3_sx1262.lib_deps}
|
||||
densaugeo/base64 @ ~1.4.0
|
||||
|
||||
[env:LilyGo_T3S3_sx1262_companion_radio_ble]
|
||||
extends = LilyGo_T3S3_sx1262
|
||||
build_flags =
|
||||
${LilyGo_T3S3_sx1262.build_flags}
|
||||
-D MAX_CONTACTS=100
|
||||
-D MAX_GROUP_CHANNELS=1
|
||||
-D BLE_PIN_CODE=123456
|
||||
-D BLE_DEBUG_LOGGING=1
|
||||
; -D ENABLE_PRIVATE_KEY_IMPORT=1
|
||||
; -D ENABLE_PRIVATE_KEY_EXPORT=1
|
||||
; -D MESH_PACKET_LOGGING=1
|
||||
; -D MESH_DEBUG=1
|
||||
build_src_filter = ${LilyGo_T3S3_sx1262.build_src_filter} +<helpers/esp32/*.cpp> +<../examples/companion_radio/main.cpp>
|
||||
lib_deps =
|
||||
${LilyGo_T3S3_sx1262.lib_deps}
|
||||
densaugeo/base64 @ ~1.4.0
|
||||
|
||||
; ----------------- NRF52 ---------------------
|
||||
@@ -263,8 +395,10 @@ lib_deps =
|
||||
|
||||
[rak4631]
|
||||
extends = nrf52840_base
|
||||
platform = https://github.com/maxgerhardt/platform-nordicnrf52.git#rak
|
||||
board = wiscore_rak4631
|
||||
board_check = true
|
||||
build_src_filter = ${nrf52840_base.build_src_filter} +<helpers/nrf52/*.cpp>
|
||||
build_flags = ${nrf52840_base.build_flags}
|
||||
-D RAK_4631
|
||||
-D RADIO_CLASS=CustomSX1262
|
||||
@@ -283,9 +417,6 @@ build_flags =
|
||||
-D ADMIN_PASSWORD="\"password\""
|
||||
; -D MESH_PACKET_LOGGING=1
|
||||
; -D MESH_DEBUG=1
|
||||
lib_deps =
|
||||
${rak4631.lib_deps}
|
||||
adafruit/RTClib @ ^2.1.3
|
||||
|
||||
[env:RAK_4631_room_server]
|
||||
extends = rak4631
|
||||
@@ -299,9 +430,6 @@ build_flags =
|
||||
-D ROOM_PASSWORD="\"hello\""
|
||||
; -D MESH_PACKET_LOGGING=1
|
||||
; -D MESH_DEBUG=1
|
||||
lib_deps =
|
||||
${rak4631.lib_deps}
|
||||
adafruit/RTClib @ ^2.1.3
|
||||
|
||||
[env:RAK_4631_terminal_chat]
|
||||
extends = rak4631
|
||||
@@ -315,7 +443,6 @@ build_src_filter = ${rak4631.build_src_filter} +<../examples/simple_secure_chat/
|
||||
lib_deps =
|
||||
${rak4631.lib_deps}
|
||||
densaugeo/base64 @ ~1.4.0
|
||||
adafruit/RTClib @ ^2.1.3
|
||||
|
||||
[env:RAK_4631_companion_radio_usb]
|
||||
extends = rak4631
|
||||
@@ -323,10 +450,73 @@ build_flags =
|
||||
${rak4631.build_flags}
|
||||
-D MAX_CONTACTS=100
|
||||
-D MAX_GROUP_CHANNELS=1
|
||||
; -D MESH_PACKET_LOGGING=1
|
||||
; -D MESH_DEBUG=1
|
||||
; -D ENABLE_PRIVATE_KEY_IMPORT=1
|
||||
; -D ENABLE_PRIVATE_KEY_EXPORT=1
|
||||
; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1
|
||||
; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1
|
||||
build_src_filter = ${rak4631.build_src_filter} +<../examples/companion_radio/main.cpp>
|
||||
lib_deps =
|
||||
${rak4631.lib_deps}
|
||||
adafruit/RTClib @ ^2.1.3
|
||||
densaugeo/base64 @ ~1.4.0
|
||||
|
||||
[env:RAK_4631_companion_radio_ble]
|
||||
extends = rak4631
|
||||
build_flags =
|
||||
${rak4631.build_flags}
|
||||
-D MAX_CONTACTS=100
|
||||
-D MAX_GROUP_CHANNELS=1
|
||||
-D BLE_PIN_CODE=123456
|
||||
-D BLE_DEBUG_LOGGING=1
|
||||
; -D ENABLE_PRIVATE_KEY_IMPORT=1
|
||||
; -D ENABLE_PRIVATE_KEY_EXPORT=1
|
||||
; -D MESH_PACKET_LOGGING=1
|
||||
; -D MESH_DEBUG=1
|
||||
build_src_filter = ${rak4631.build_src_filter} +<helpers/nrf52/*.cpp> +<../examples/companion_radio/main.cpp>
|
||||
lib_deps =
|
||||
${rak4631.lib_deps}
|
||||
densaugeo/base64 @ ~1.4.0
|
||||
|
||||
; ----------------- NRF52 T1000e---------------------
|
||||
[nrf52840_t1000e]
|
||||
extends = nrf52_base
|
||||
platform_packages = framework-arduinoadafruitnrf52
|
||||
build_flags = ${nrf52_base.build_flags}
|
||||
-I src/helpers/nrf52
|
||||
lib_ignore =
|
||||
BluetoothOTA
|
||||
lvgl
|
||||
lib5b4
|
||||
lib_deps =
|
||||
${nrf52_base.lib_deps}
|
||||
rweather/Crypto @ ^0.4.0
|
||||
|
||||
[t1000-e]
|
||||
extends = nrf52840_t1000e
|
||||
board = tracker-t1000-e
|
||||
board_build.ldscript = boards/nrf52840_s140_v7.ld
|
||||
build_flags = ${nrf52840_t1000e.build_flags}
|
||||
-Ivariants/t1000-e
|
||||
-DT1000_E
|
||||
-D RADIO_CLASS=CustomLR1110
|
||||
-D WRAPPER_CLASS=CustomLR1110Wrapper
|
||||
build_src_filter = ${nrf52840_t1000e.build_src_filter}
|
||||
+<helpers/*.cpp>
|
||||
+<helpers/nrf52/T1000eBoard.cpp>
|
||||
+<../variants/t1000-e>
|
||||
debug_tool = jlink
|
||||
upload_protocol = nrfutil
|
||||
|
||||
[env:t1000e_companion_radio_ble]
|
||||
extends = t1000-e
|
||||
build_flags = ${t1000-e.build_flags}
|
||||
-D MAX_CONTACTS=100
|
||||
-D MAX_GROUP_CHANNELS=1
|
||||
-D BLE_PIN_CODE=123456
|
||||
-D BLE_DEBUG_LOGGING=1
|
||||
-D MESH_PACKET_LOGGING=1
|
||||
-D MESH_DEBUG=1
|
||||
build_src_filter = ${t1000-e.build_src_filter}
|
||||
+<helpers/nrf52/SerialBLEInterface.cpp>
|
||||
+<../examples/companion_radio/*.cpp>
|
||||
lib_deps = ${t1000-e.lib_deps}
|
||||
densaugeo/base64 @ ~1.4.0
|
||||
+90
-29
@@ -4,8 +4,12 @@
|
||||
#include <Arduino.h>
|
||||
#endif
|
||||
|
||||
#include <math.h>
|
||||
|
||||
namespace mesh {
|
||||
|
||||
#define MAX_RX_DELAY_MILLIS 32000 // 32 seconds
|
||||
|
||||
void Dispatcher::begin() {
|
||||
n_sent_flood = n_sent_direct = 0;
|
||||
n_recv_flood = n_recv_direct = 0;
|
||||
@@ -18,6 +22,14 @@ float Dispatcher::getAirtimeBudgetFactor() const {
|
||||
return 2.0; // default, 33.3% (1/3rd)
|
||||
}
|
||||
|
||||
int Dispatcher::calcRxDelay(float score, uint32_t air_time) const {
|
||||
return (int) ((pow(10, 0.85f - score) - 1.0) * air_time);
|
||||
}
|
||||
|
||||
uint32_t Dispatcher::getCADFailRetryDelay() const {
|
||||
return 200;
|
||||
}
|
||||
|
||||
void Dispatcher::loop() {
|
||||
if (outbound) { // waiting for outbound send to be completed
|
||||
if (_radio->isSendComplete()) {
|
||||
@@ -29,17 +41,20 @@ void Dispatcher::loop() {
|
||||
next_tx_time = futureMillis(t * getAirtimeBudgetFactor());
|
||||
|
||||
_radio->onSendFinished();
|
||||
onPacketSent(outbound);
|
||||
logTx(outbound, 2 + outbound->path_len + outbound->payload_len);
|
||||
if (outbound->isRouteFlood()) {
|
||||
n_sent_flood++;
|
||||
} else {
|
||||
n_sent_direct++;
|
||||
}
|
||||
releasePacket(outbound); // return to pool
|
||||
outbound = NULL;
|
||||
} else if (millisHasNowPassed(outbound_expiry)) {
|
||||
MESH_DEBUG_PRINTLN("Dispatcher::loop(): WARNING: outbound packed send timed out!");
|
||||
MESH_DEBUG_PRINTLN("%s Dispatcher::loop(): WARNING: outbound packed send timed out!", getLogDateTime());
|
||||
|
||||
_radio->onSendFinished();
|
||||
logTxFail(outbound, 2 + outbound->path_len + outbound->payload_len);
|
||||
|
||||
releasePacket(outbound); // return to pool
|
||||
outbound = NULL;
|
||||
} else {
|
||||
@@ -47,23 +62,28 @@ void Dispatcher::loop() {
|
||||
}
|
||||
}
|
||||
|
||||
// check inbound (delayed) queue
|
||||
{
|
||||
Packet* pkt = _mgr->getNextInbound(_ms->getMillis());
|
||||
if (pkt) {
|
||||
processRecvPacket(pkt);
|
||||
}
|
||||
}
|
||||
checkRecv();
|
||||
checkSend();
|
||||
}
|
||||
|
||||
void Dispatcher::onPacketSent(Packet* packet) {
|
||||
releasePacket(packet); // default behaviour, return packet to pool
|
||||
}
|
||||
|
||||
void Dispatcher::checkRecv() {
|
||||
Packet* pkt;
|
||||
float score;
|
||||
uint32_t air_time;
|
||||
{
|
||||
uint8_t raw[MAX_TRANS_UNIT];
|
||||
int len = _radio->recvRaw(raw, MAX_TRANS_UNIT);
|
||||
if (len > 0) {
|
||||
pkt = _mgr->allocNew();
|
||||
if (pkt == NULL) {
|
||||
MESH_DEBUG_PRINTLN("Dispatcher::checkRecv(): WARNING: received data, no unused packets available!");
|
||||
MESH_DEBUG_PRINTLN("%s Dispatcher::checkRecv(): WARNING: received data, no unused packets available!", getLogDateTime());
|
||||
} else {
|
||||
int i = 0;
|
||||
#ifdef NODE_ID
|
||||
@@ -79,7 +99,7 @@ void Dispatcher::checkRecv() {
|
||||
pkt->path_len = raw[i++];
|
||||
|
||||
if (pkt->path_len > MAX_PATH_SIZE || i + pkt->path_len > len) {
|
||||
MESH_DEBUG_PRINTLN("Dispatcher::checkRecv(): partial or corrupt packet received, len=%d", len);
|
||||
MESH_DEBUG_PRINTLN("%s Dispatcher::checkRecv(): partial or corrupt packet received, len=%d", getLogDateTime(), len);
|
||||
_mgr->free(pkt); // put back into pool
|
||||
pkt = NULL;
|
||||
} else {
|
||||
@@ -87,6 +107,9 @@ void Dispatcher::checkRecv() {
|
||||
|
||||
pkt->payload_len = len - i; // payload is remainder
|
||||
memcpy(pkt->payload, &raw[i], pkt->payload_len);
|
||||
|
||||
score = _radio->packetScore(_radio->getLastSNR(), len);
|
||||
air_time = _radio->getEstAirtimeFor(len);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -94,34 +117,62 @@ void Dispatcher::checkRecv() {
|
||||
}
|
||||
}
|
||||
if (pkt) {
|
||||
#if MESH_PACKET_LOGGING
|
||||
Serial.print(getLogDateTime());
|
||||
Serial.printf(": RX, len=%d (type=%d, route=%s, payload_len=%d) SNR=%d RSSI=%d score=%d",
|
||||
2 + pkt->path_len + pkt->payload_len, pkt->getPayloadType(), pkt->isRouteDirect() ? "D" : "F", pkt->payload_len,
|
||||
(int)_radio->getLastSNR(), (int)_radio->getLastRSSI(), (int)(score*1000));
|
||||
if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ
|
||||
|| pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
|
||||
Serial.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
|
||||
} else {
|
||||
Serial.printf("\n");
|
||||
}
|
||||
#endif
|
||||
logRx(pkt, 2 + pkt->path_len + pkt->payload_len, score); // hook for custom logging
|
||||
|
||||
if (pkt->isRouteFlood()) {
|
||||
n_recv_flood++;
|
||||
|
||||
int _delay = calcRxDelay(score, air_time);
|
||||
if (_delay < 50) {
|
||||
MESH_DEBUG_PRINTLN("%s Dispatcher::checkRecv(), score delay below threshold (%d)", getLogDateTime(), _delay);
|
||||
processRecvPacket(pkt); // is below the score delay threshold, so process immediately
|
||||
} else {
|
||||
MESH_DEBUG_PRINTLN("%s Dispatcher::checkRecv(), score delay is: %d millis", getLogDateTime(), _delay);
|
||||
if (_delay > MAX_RX_DELAY_MILLIS) {
|
||||
_delay = MAX_RX_DELAY_MILLIS;
|
||||
}
|
||||
_mgr->queueInbound(pkt, futureMillis(_delay)); // add to delayed inbound queue
|
||||
}
|
||||
} else {
|
||||
n_recv_direct++;
|
||||
processRecvPacket(pkt);
|
||||
}
|
||||
#if MESH_PACKET_LOGGING
|
||||
Serial.printf("PACKET: recv, len=%d (type=%d, route=%s, payload_len=%d) SNR=%d RSSI=%d\n",
|
||||
2 + pkt->path_len + pkt->payload_len, pkt->getPayloadType(), pkt->isRouteDirect() ? "D" : "F", pkt->payload_len,
|
||||
(int)_radio->getLastSNR(), (int)_radio->getLastRSSI());
|
||||
#endif
|
||||
DispatcherAction action = onRecvPacket(pkt);
|
||||
if (action == ACTION_RELEASE) {
|
||||
_mgr->free(pkt);
|
||||
} else if (action == ACTION_MANUAL_HOLD) {
|
||||
// sub-class is wanting to manually hold Packet instance, and call releasePacket() at appropriate time
|
||||
} else { // ACTION_RETRANSMIT*
|
||||
uint8_t priority = (action >> 24) - 1;
|
||||
uint32_t _delay = action & 0xFFFFFF;
|
||||
}
|
||||
}
|
||||
|
||||
_mgr->queueOutbound(pkt, priority, futureMillis(_delay));
|
||||
}
|
||||
void Dispatcher::processRecvPacket(Packet* pkt) {
|
||||
DispatcherAction action = onRecvPacket(pkt);
|
||||
if (action == ACTION_RELEASE) {
|
||||
_mgr->free(pkt);
|
||||
} else if (action == ACTION_MANUAL_HOLD) {
|
||||
// sub-class is wanting to manually hold Packet instance, and call releasePacket() at appropriate time
|
||||
} else { // ACTION_RETRANSMIT*
|
||||
uint8_t priority = (action >> 24) - 1;
|
||||
uint32_t _delay = action & 0xFFFFFF;
|
||||
|
||||
_mgr->queueOutbound(pkt, priority, futureMillis(_delay));
|
||||
}
|
||||
}
|
||||
|
||||
void Dispatcher::checkSend() {
|
||||
if (_mgr->getOutboundCount() == 0) return; // nothing waiting to send
|
||||
if (!millisHasNowPassed(next_tx_time)) return; // still in 'radio silence' phase (from airtime budget setting)
|
||||
if (_radio->isReceiving()) return; // LBT - check if radio is currently mid-receive, or if channel activity
|
||||
if (_radio->isReceiving()) { // LBT - check if radio is currently mid-receive, or if channel activity
|
||||
next_tx_time = futureMillis(getCADFailRetryDelay());
|
||||
return;
|
||||
}
|
||||
|
||||
outbound = _mgr->getNextOutbound(_ms->getMillis());
|
||||
if (outbound) {
|
||||
@@ -136,7 +187,7 @@ void Dispatcher::checkSend() {
|
||||
memcpy(&raw[len], outbound->path, outbound->path_len); len += outbound->path_len;
|
||||
|
||||
if (len + outbound->payload_len > MAX_TRANS_UNIT) {
|
||||
MESH_DEBUG_PRINTLN("Dispatcher::checkSend(): FATAL: Invalid packet queued... too long, len=%d", len + outbound->payload_len);
|
||||
MESH_DEBUG_PRINTLN("%s Dispatcher::checkSend(): FATAL: Invalid packet queued... too long, len=%d", getLogDateTime(), len + outbound->payload_len);
|
||||
_mgr->free(outbound);
|
||||
outbound = NULL;
|
||||
} else {
|
||||
@@ -148,8 +199,15 @@ void Dispatcher::checkSend() {
|
||||
outbound_expiry = futureMillis(max_airtime);
|
||||
|
||||
#if MESH_PACKET_LOGGING
|
||||
Serial.printf("PACKET: send, len=%d (type=%d, route=%s, payload_len=%d)\n",
|
||||
Serial.print(getLogDateTime());
|
||||
Serial.printf(": TX, len=%d (type=%d, route=%s, payload_len=%d)",
|
||||
len, outbound->getPayloadType(), outbound->isRouteDirect() ? "D" : "F", outbound->payload_len);
|
||||
if (outbound->getPayloadType() == PAYLOAD_TYPE_PATH || outbound->getPayloadType() == PAYLOAD_TYPE_REQ
|
||||
|| outbound->getPayloadType() == PAYLOAD_TYPE_RESPONSE || outbound->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
|
||||
Serial.printf(" [%02X -> %02X]\n", (uint32_t)outbound->payload[1], (uint32_t)outbound->payload[0]);
|
||||
} else {
|
||||
Serial.printf("\n");
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -157,8 +215,11 @@ void Dispatcher::checkSend() {
|
||||
|
||||
Packet* Dispatcher::obtainNewPacket() {
|
||||
auto pkt = _mgr->allocNew(); // TODO: zero out all fields
|
||||
if (pkt == NULL) n_full_events++;
|
||||
|
||||
if (pkt == NULL) {
|
||||
n_full_events++;
|
||||
} else {
|
||||
pkt->payload_len = pkt->path_len = 0;
|
||||
}
|
||||
return pkt;
|
||||
}
|
||||
|
||||
@@ -168,7 +229,7 @@ void Dispatcher::releasePacket(Packet* packet) {
|
||||
|
||||
void Dispatcher::sendPacket(Packet* packet, uint8_t priority, uint32_t delay_millis) {
|
||||
if (packet->path_len > MAX_PATH_SIZE || packet->payload_len > MAX_PACKET_PAYLOAD) {
|
||||
MESH_DEBUG_PRINTLN("Dispatcher::sendPacket(): ERROR: invalid packet... path_len=%d, payload_len=%d", (uint32_t) packet->path_len, (uint32_t) packet->payload_len);
|
||||
MESH_DEBUG_PRINTLN("%s Dispatcher::sendPacket(): ERROR: invalid packet... path_len=%d, payload_len=%d", getLogDateTime(), (uint32_t) packet->path_len, (uint32_t) packet->payload_len);
|
||||
_mgr->free(packet);
|
||||
} else {
|
||||
_mgr->queueOutbound(packet, priority, futureMillis(delay_millis));
|
||||
|
||||
+14
-1
@@ -36,6 +36,8 @@ public:
|
||||
*/
|
||||
virtual uint32_t getEstAirtimeFor(int len_bytes) = 0;
|
||||
|
||||
virtual float packetScore(float snr, int packet_len) = 0;
|
||||
|
||||
/**
|
||||
* \brief starts the raw packet send. (no wait)
|
||||
* \param bytes the raw packet data
|
||||
@@ -77,6 +79,8 @@ public:
|
||||
virtual int getFreeCount() const = 0;
|
||||
virtual Packet* getOutboundByIdx(int i) = 0;
|
||||
virtual Packet* removeOutboundByIdx(int i) = 0;
|
||||
virtual void queueInbound(Packet* packet, uint32_t scheduled_for) = 0;
|
||||
virtual Packet* getNextInbound(uint32_t now) = 0;
|
||||
};
|
||||
|
||||
typedef uint32_t DispatcherAction;
|
||||
@@ -98,6 +102,8 @@ class Dispatcher {
|
||||
uint32_t n_recv_flood, n_recv_direct;
|
||||
uint32_t n_full_events;
|
||||
|
||||
void processRecvPacket(Packet* pkt);
|
||||
|
||||
protected:
|
||||
PacketManager* _mgr;
|
||||
Radio* _radio;
|
||||
@@ -110,8 +116,15 @@ protected:
|
||||
}
|
||||
|
||||
virtual DispatcherAction onRecvPacket(Packet* pkt) = 0;
|
||||
virtual void onPacketSent(Packet* packet);
|
||||
|
||||
virtual void logRx(Packet* packet, int len, float score) { } // hooks for custom logging
|
||||
virtual void logTx(Packet* packet, int len) { }
|
||||
virtual void logTxFail(Packet* packet, int len) { }
|
||||
virtual const char* getLogDateTime() { return ""; }
|
||||
|
||||
virtual float getAirtimeBudgetFactor() const;
|
||||
virtual int calcRxDelay(float score, uint32_t air_time) const;
|
||||
virtual uint32_t getCADFailRetryDelay() const;
|
||||
|
||||
public:
|
||||
void begin();
|
||||
|
||||
+51
-17
@@ -19,6 +19,13 @@ uint32_t Mesh::getRetransmitDelay(const mesh::Packet* packet) {
|
||||
|
||||
return _rng->nextInt(0, 5)*t;
|
||||
}
|
||||
uint32_t Mesh::getDirectRetransmitDelay(const Packet* packet) {
|
||||
return 0; // by default, no delay
|
||||
}
|
||||
|
||||
uint32_t Mesh::getCADFailRetryDelay() const {
|
||||
return _rng->nextInt(1, 4)*120;
|
||||
}
|
||||
|
||||
int Mesh::searchPeersByHash(const uint8_t* hash) {
|
||||
return 0; // not found
|
||||
@@ -30,7 +37,7 @@ int Mesh::searchChannelsByHash(const uint8_t* hash, GroupChannel channels[], int
|
||||
|
||||
DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
|
||||
if (pkt->getPayloadVer() > PAYLOAD_VER_1) { // not supported in this firmware version
|
||||
MESH_DEBUG_PRINTLN("Mesh::onRecvPacket(): unsupported packet version");
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::onRecvPacket(): unsupported packet version", getLogDateTime());
|
||||
return ACTION_RELEASE;
|
||||
}
|
||||
|
||||
@@ -41,7 +48,9 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
|
||||
// remove our hash from 'path', then re-broadcast
|
||||
pkt->path_len -= PATH_HASH_SIZE;
|
||||
memcpy(pkt->path, &pkt->path[PATH_HASH_SIZE], pkt->path_len);
|
||||
return ACTION_RETRANSMIT(0); // Routed traffic is HIGHEST priority (and NO per-hop delay)
|
||||
|
||||
uint32_t d = getDirectRetransmitDelay(pkt);
|
||||
return ACTION_RETRANSMIT_DELAYED(0, d); // Routed traffic is HIGHEST priority
|
||||
}
|
||||
return ACTION_RELEASE; // this node is NOT the next hop (OR this packet has already been forwarded), so discard.
|
||||
}
|
||||
@@ -54,7 +63,7 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
|
||||
uint32_t ack_crc;
|
||||
memcpy(&ack_crc, &pkt->payload[i], 4); i += 4;
|
||||
if (i > pkt->payload_len) {
|
||||
MESH_DEBUG_PRINTLN("Mesh::onRecvPacket(): incomplete ACK packet");
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::onRecvPacket(): incomplete ACK packet", getLogDateTime());
|
||||
} else if (!_tables->hasSeen(pkt)) {
|
||||
onAckRecv(pkt, ack_crc);
|
||||
action = routeRecvPacket(pkt);
|
||||
@@ -71,7 +80,7 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
|
||||
|
||||
uint8_t* macAndData = &pkt->payload[i]; // MAC + encrypted data
|
||||
if (i + 2 >= pkt->payload_len) {
|
||||
MESH_DEBUG_PRINTLN("Mesh::onRecvPacket(): incomplete data packet");
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::onRecvPacket(): incomplete data packet", getLogDateTime());
|
||||
} else if (!_tables->hasSeen(pkt)) {
|
||||
// NOTE: this is a 'first packet wins' impl. When receiving from multiple paths, the first to arrive wins.
|
||||
// For flood mode, the path may not be the 'best' in terms of hops.
|
||||
@@ -114,7 +123,7 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
|
||||
if (found) {
|
||||
pkt->markDoNotRetransmit(); // packet was for this node, so don't retransmit
|
||||
} else {
|
||||
MESH_DEBUG_PRINTLN("recv matches no peers, src_hash=%02X", (uint32_t)src_hash);
|
||||
MESH_DEBUG_PRINTLN("%s recv matches no peers, src_hash=%02X", getLogDateTime(), (uint32_t)src_hash);
|
||||
}
|
||||
}
|
||||
action = routeRecvPacket(pkt);
|
||||
@@ -128,7 +137,7 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
|
||||
|
||||
uint8_t* macAndData = &pkt->payload[i]; // MAC + encrypted data
|
||||
if (i + 2 >= pkt->payload_len) {
|
||||
MESH_DEBUG_PRINTLN("Mesh::onRecvPacket(): incomplete data packet");
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::onRecvPacket(): incomplete data packet", getLogDateTime());
|
||||
} else if (!_tables->hasSeen(pkt)) {
|
||||
if (self_id.isHashMatch(&dest_hash)) {
|
||||
Identity sender(sender_pub_key);
|
||||
@@ -155,7 +164,7 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
|
||||
|
||||
uint8_t* macAndData = &pkt->payload[i]; // MAC + encrypted data
|
||||
if (i + 2 >= pkt->payload_len) {
|
||||
MESH_DEBUG_PRINTLN("Mesh::onRecvPacket(): incomplete data packet");
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::onRecvPacket(): incomplete data packet", getLogDateTime());
|
||||
} else if (!_tables->hasSeen(pkt)) {
|
||||
// scan channels DB, for all matching hashes of 'channel_hash' (max 2 matches supported ATM)
|
||||
GroupChannel channels[2];
|
||||
@@ -184,7 +193,9 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
|
||||
const uint8_t* signature = &pkt->payload[i]; i += SIGNATURE_SIZE;
|
||||
|
||||
if (i > pkt->payload_len) {
|
||||
MESH_DEBUG_PRINTLN("Mesh::onRecvPacket(): incomplete advertisement packet");
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::onRecvPacket(): incomplete advertisement packet", getLogDateTime());
|
||||
} else if (self_id.matches(id.pub_key)) {
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::onRecvPacket(): receiving SELF advert packet", getLogDateTime());
|
||||
} else if (!_tables->hasSeen(pkt)) {
|
||||
uint8_t* app_data = &pkt->payload[i];
|
||||
int app_data_len = pkt->payload_len - i;
|
||||
@@ -202,17 +213,24 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
|
||||
is_ok = id.verify(signature, message, msg_len);
|
||||
}
|
||||
if (is_ok) {
|
||||
MESH_DEBUG_PRINTLN("Mesh::onRecvPacket(): valid advertisement received!");
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::onRecvPacket(): valid advertisement received!", getLogDateTime());
|
||||
onAdvertRecv(pkt, id, timestamp, app_data, app_data_len);
|
||||
action = routeRecvPacket(pkt);
|
||||
} else {
|
||||
MESH_DEBUG_PRINTLN("Mesh::onRecvPacket(): received advertisement with forged signature! (app_data_len=%d)", app_data_len);
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::onRecvPacket(): received advertisement with forged signature! (app_data_len=%d)", getLogDateTime(), app_data_len);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case PAYLOAD_TYPE_RAW_CUSTOM: {
|
||||
if (pkt->isRouteDirect() && !_tables->hasSeen(pkt)) {
|
||||
onRawDataRecv(pkt);
|
||||
//action = routeRecvPacket(pkt); don't flood route these (yet)
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
MESH_DEBUG_PRINTLN("Mesh::onRecvPacket(): unknown payload type, header: %d", (int) pkt->header);
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::onRecvPacket(): unknown payload type, header: %d", getLogDateTime(), (int) pkt->header);
|
||||
// Don't flood route unknown packet types! action = routeRecvPacket(pkt);
|
||||
break;
|
||||
}
|
||||
@@ -237,7 +255,7 @@ Packet* Mesh::createAdvert(const LocalIdentity& id, const uint8_t* app_data, siz
|
||||
|
||||
Packet* packet = obtainNewPacket();
|
||||
if (packet == NULL) {
|
||||
MESH_DEBUG_PRINTLN("Mesh::createAdvert(): error, packet pool empty");
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::createAdvert(): error, packet pool empty", getLogDateTime());
|
||||
return NULL;
|
||||
}
|
||||
|
||||
@@ -281,7 +299,7 @@ Packet* Mesh::createPathReturn(const uint8_t* dest_hash, const uint8_t* secret,
|
||||
|
||||
Packet* packet = obtainNewPacket();
|
||||
if (packet == NULL) {
|
||||
MESH_DEBUG_PRINTLN("Mesh::createPathReturn(): error, packet pool empty");
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::createPathReturn(): error, packet pool empty", getLogDateTime());
|
||||
return NULL;
|
||||
}
|
||||
packet->header = (PAYLOAD_TYPE_PATH << PH_TYPE_SHIFT); // ROUTE_TYPE_* set later
|
||||
@@ -322,7 +340,7 @@ Packet* Mesh::createDatagram(uint8_t type, const Identity& dest, const uint8_t*
|
||||
|
||||
Packet* packet = obtainNewPacket();
|
||||
if (packet == NULL) {
|
||||
MESH_DEBUG_PRINTLN("Mesh::createDatagram(): error, packet pool empty");
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::createDatagram(): error, packet pool empty", getLogDateTime());
|
||||
return NULL;
|
||||
}
|
||||
packet->header = (type << PH_TYPE_SHIFT); // ROUTE_TYPE_* set later
|
||||
@@ -346,7 +364,7 @@ Packet* Mesh::createAnonDatagram(uint8_t type, const LocalIdentity& sender, cons
|
||||
|
||||
Packet* packet = obtainNewPacket();
|
||||
if (packet == NULL) {
|
||||
MESH_DEBUG_PRINTLN("Mesh::createAnonDatagram(): error, packet pool empty");
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::createAnonDatagram(): error, packet pool empty", getLogDateTime());
|
||||
return NULL;
|
||||
}
|
||||
packet->header = (type << PH_TYPE_SHIFT); // ROUTE_TYPE_* set later
|
||||
@@ -371,7 +389,7 @@ Packet* Mesh::createGroupDatagram(uint8_t type, const GroupChannel& channel, con
|
||||
|
||||
Packet* packet = obtainNewPacket();
|
||||
if (packet == NULL) {
|
||||
MESH_DEBUG_PRINTLN("Mesh::createGroupDatagram(): error, packet pool empty");
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::createGroupDatagram(): error, packet pool empty", getLogDateTime());
|
||||
return NULL;
|
||||
}
|
||||
packet->header = (type << PH_TYPE_SHIFT); // ROUTE_TYPE_* set later
|
||||
@@ -388,7 +406,7 @@ Packet* Mesh::createGroupDatagram(uint8_t type, const GroupChannel& channel, con
|
||||
Packet* Mesh::createAck(uint32_t ack_crc) {
|
||||
Packet* packet = obtainNewPacket();
|
||||
if (packet == NULL) {
|
||||
MESH_DEBUG_PRINTLN("Mesh::createAck(): error, packet pool empty");
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::createAck(): error, packet pool empty", getLogDateTime());
|
||||
return NULL;
|
||||
}
|
||||
packet->header = (PAYLOAD_TYPE_ACK << PH_TYPE_SHIFT); // ROUTE_TYPE_* set later
|
||||
@@ -399,6 +417,22 @@ Packet* Mesh::createAck(uint32_t ack_crc) {
|
||||
return packet;
|
||||
}
|
||||
|
||||
Packet* Mesh::createRawData(const uint8_t* data, size_t len) {
|
||||
if (len > sizeof(Packet::payload)) return NULL; // invalid arg
|
||||
|
||||
Packet* packet = obtainNewPacket();
|
||||
if (packet == NULL) {
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::createRawData(): error, packet pool empty", getLogDateTime());
|
||||
return NULL;
|
||||
}
|
||||
packet->header = (PAYLOAD_TYPE_RAW_CUSTOM << PH_TYPE_SHIFT); // ROUTE_TYPE_* set later
|
||||
|
||||
memcpy(packet->payload, data, len);
|
||||
packet->payload_len = len;
|
||||
|
||||
return packet;
|
||||
}
|
||||
|
||||
void Mesh::sendFlood(Packet* packet, uint32_t delay_millis) {
|
||||
packet->header &= ~PH_ROUTE_MASK;
|
||||
packet->header |= ROUTE_TYPE_FLOOD;
|
||||
|
||||
+27
@@ -8,6 +8,10 @@ namespace mesh {
|
||||
* An abstraction of the device's Realtime Clock.
|
||||
*/
|
||||
class RTCClock {
|
||||
uint32_t last_unique;
|
||||
protected:
|
||||
RTCClock() { last_unique = 0; }
|
||||
|
||||
public:
|
||||
/**
|
||||
* \returns the current time. in UNIX epoch seconds.
|
||||
@@ -18,6 +22,14 @@ public:
|
||||
* \param time current time in UNIX epoch seconds.
|
||||
*/
|
||||
virtual void setCurrentTime(uint32_t time) = 0;
|
||||
|
||||
uint32_t getCurrentTimeUnique() {
|
||||
uint32_t t = getCurrentTime();
|
||||
if (t <= last_unique) {
|
||||
return ++last_unique;
|
||||
}
|
||||
return last_unique = t;
|
||||
}
|
||||
};
|
||||
|
||||
class GroupChannel {
|
||||
@@ -46,6 +58,8 @@ class Mesh : public Dispatcher {
|
||||
protected:
|
||||
DispatcherAction onRecvPacket(Packet* pkt) override;
|
||||
|
||||
virtual uint32_t getCADFailRetryDelay() const override;
|
||||
|
||||
/**
|
||||
* \brief Decide what to do with received packet, ie. discard, forward, or hold
|
||||
*/
|
||||
@@ -62,6 +76,11 @@ protected:
|
||||
*/
|
||||
virtual uint32_t getRetransmitDelay(const Packet* packet);
|
||||
|
||||
/**
|
||||
* \returns number of milliseconds delay to apply to retransmitting the given packet, for DIRECT mode.
|
||||
*/
|
||||
virtual uint32_t getDirectRetransmitDelay(const Packet* packet);
|
||||
|
||||
/**
|
||||
* \brief Perform search of local DB of peers/contacts.
|
||||
* \returns Number of peers with matching hash
|
||||
@@ -113,6 +132,11 @@ protected:
|
||||
*/
|
||||
virtual void onPathRecv(Packet* packet, Identity& sender, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) { }
|
||||
|
||||
/**
|
||||
* \brief A packet with PAYLOAD_TYPE_RAW_CUSTOM has been received.
|
||||
*/
|
||||
virtual void onRawDataRecv(Packet* packet) { }
|
||||
|
||||
/**
|
||||
* \brief Perform search of local DB of matching GroupChannels.
|
||||
* \param channels OUT - store matching channels in this array, up to max_matches
|
||||
@@ -139,6 +163,8 @@ protected:
|
||||
{
|
||||
}
|
||||
|
||||
MeshTables* getTables() const { return _tables; }
|
||||
|
||||
public:
|
||||
void begin();
|
||||
void loop();
|
||||
@@ -155,6 +181,7 @@ public:
|
||||
Packet* createAck(uint32_t ack_crc);
|
||||
Packet* createPathReturn(const uint8_t* dest_hash, const uint8_t* secret, const uint8_t* path, uint8_t path_len, uint8_t extra_type, const uint8_t*extra, size_t extra_len);
|
||||
Packet* createPathReturn(const Identity& dest, const uint8_t* secret, const uint8_t* path, uint8_t path_len, uint8_t extra_type, const uint8_t*extra, size_t extra_len);
|
||||
Packet* createRawData(const uint8_t* data, size_t len);
|
||||
|
||||
/**
|
||||
* \brief send a locally-generated Packet with flood routing
|
||||
|
||||
@@ -41,6 +41,7 @@ public:
|
||||
virtual void onAfterTransmit() { }
|
||||
virtual void reboot() = 0;
|
||||
virtual uint8_t getStartupReason() const = 0;
|
||||
virtual bool startOTAUpdate() { return false; } // not supported
|
||||
};
|
||||
|
||||
}
|
||||
@@ -19,5 +19,25 @@ void Packet::calculatePacketHash(uint8_t* hash) const {
|
||||
sha.finalize(hash, MAX_HASH_SIZE);
|
||||
}
|
||||
|
||||
uint8_t Packet::writeTo(uint8_t dest[]) const {
|
||||
uint8_t i = 0;
|
||||
dest[i++] = header;
|
||||
dest[i++] = path_len;
|
||||
memcpy(&dest[i], path, path_len); i += path_len;
|
||||
memcpy(&dest[i], payload, payload_len); i += payload_len;
|
||||
return i;
|
||||
}
|
||||
|
||||
bool Packet::readFrom(const uint8_t src[], uint8_t len) {
|
||||
uint8_t i = 0;
|
||||
header = src[i++];
|
||||
path_len = src[i++];
|
||||
if (path_len > sizeof(path)) return false; // bad encoding
|
||||
memcpy(path, &src[i], path_len); i += path_len;
|
||||
if (i >= len) return false; // bad encoding
|
||||
payload_len = len - i;
|
||||
memcpy(payload, &src[i], payload_len); //i += payload_len;
|
||||
return true; // success
|
||||
}
|
||||
|
||||
}
|
||||
+15
-1
@@ -26,7 +26,7 @@ namespace mesh {
|
||||
#define PAYLOAD_TYPE_ANON_REQ 0x07 // generic request (prefixed with dest_hash, ephemeral pub_key, MAC) (enc data: ...)
|
||||
#define PAYLOAD_TYPE_PATH 0x08 // returned path (prefixed with dest/src hashes, MAC) (enc data: path, extra)
|
||||
//...
|
||||
#define PAYLOAD_TYPE_RESERVEDM 0x0F // FUTURE
|
||||
#define PAYLOAD_TYPE_RAW_CUSTOM 0x0F // custom packet as raw bytes, for applications with custom encryption, payloads, etc
|
||||
|
||||
#define PAYLOAD_VER_1 0x00 // 1-byte src/dest hashes, 2-byte MAC
|
||||
#define PAYLOAD_VER_2 0x01 // FUTURE (eg. 2-byte hashes, 4-byte MAC ??)
|
||||
@@ -71,6 +71,20 @@ public:
|
||||
|
||||
void markDoNotRetransmit() { header = 0xFF; }
|
||||
bool isMarkedDoNotRetransmit() const { return header == 0xFF; }
|
||||
|
||||
/**
|
||||
* \brief save entire packet as a blob
|
||||
* \param dest (OUT) destination buffer (assumed to be MAX_MTU_SIZE)
|
||||
* \returns the packet length
|
||||
*/
|
||||
uint8_t writeTo(uint8_t dest[]) const;
|
||||
|
||||
/**
|
||||
* \brief restore this packet from a blob (as created using writeTo())
|
||||
* \param src (IN) buffer containing blob
|
||||
* \param len the packet length (as returned by writeTo())
|
||||
*/
|
||||
bool readFrom(const uint8_t src[], uint8_t len);
|
||||
};
|
||||
|
||||
}
|
||||
@@ -115,6 +115,10 @@ static uint8_t hexVal(char c) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool Utils::isHexChar(char c) {
|
||||
return c == '0' || hexVal(c) > 0;
|
||||
}
|
||||
|
||||
bool Utils::fromHex(uint8_t* dest, int dest_size, const char *src_hex) {
|
||||
int len = strlen(src_hex);
|
||||
if (len != dest_size*2) return false; // incorrect length
|
||||
|
||||
@@ -80,6 +80,8 @@ public:
|
||||
* \returns the number of parts parsed (in 'parts')
|
||||
*/
|
||||
static int parseTextParts(char* text, const char* parts[], int max_num, char separator=',');
|
||||
|
||||
static bool isHexChar(char c);
|
||||
};
|
||||
|
||||
}
|
||||
@@ -8,13 +8,25 @@ class ArduinoSerialInterface : public BaseSerialInterface {
|
||||
uint8_t _state;
|
||||
uint16_t _frame_len;
|
||||
uint16_t rx_len;
|
||||
#ifdef LILYGO_T3S3
|
||||
HWCDC* _serial;
|
||||
#elif defined(NRF52_PLATFORM)
|
||||
Adafruit_USBD_CDC* _serial;
|
||||
#else
|
||||
HardwareSerial* _serial;
|
||||
#endif
|
||||
uint8_t rx_buf[MAX_FRAME_SIZE];
|
||||
|
||||
public:
|
||||
ArduinoSerialInterface() { _isEnabled = false; _state = 0; }
|
||||
|
||||
#ifdef LILYGO_T3S3
|
||||
void begin(HWCDC& serial) { _serial = &serial; }
|
||||
#elif defined(NRF52_PLATFORM)
|
||||
void begin(Adafruit_USBD_CDC& serial) { _serial = &serial; }
|
||||
#else
|
||||
void begin(HardwareSerial& serial) { _serial = &serial; }
|
||||
#endif
|
||||
|
||||
// BaseSerialInterface methods
|
||||
void enable() override;
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
#include "AutoDiscoverRTCClock.h"
|
||||
#include "RTClib.h"
|
||||
#include <Melopero_RV3028.h>
|
||||
|
||||
static RTC_DS3231 rtc_3231;
|
||||
static bool ds3231_success = false;
|
||||
|
||||
static Melopero_RV3028 rtc_rv3028;
|
||||
static bool rv3028_success = false;
|
||||
|
||||
#define DS3231_ADDRESS 0x68
|
||||
#define RV3028_ADDRESS 0x52
|
||||
|
||||
bool AutoDiscoverRTCClock::i2c_probe(TwoWire& wire, uint8_t addr) {
|
||||
wire.beginTransmission(addr);
|
||||
uint8_t error = wire.endTransmission();
|
||||
return (error == 0);
|
||||
}
|
||||
|
||||
void AutoDiscoverRTCClock::begin(TwoWire& wire) {
|
||||
if (i2c_probe(wire, DS3231_ADDRESS)) {
|
||||
ds3231_success = rtc_3231.begin(&wire);
|
||||
}
|
||||
if (i2c_probe(wire, RV3028_ADDRESS)) {
|
||||
rtc_rv3028.initI2C(wire);
|
||||
rtc_rv3028.writeToRegister(0x35, 0x00);
|
||||
rtc_rv3028.writeToRegister(0x37, 0xB4); // Direct Switching Mode (DSM): when VDD < VBACKUP, switchover occurs from VDD to VBACKUP
|
||||
rtc_rv3028.set24HourMode(); // Set the device to use the 24hour format (default) instead of the 12 hour format
|
||||
rv3028_success = true;
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t AutoDiscoverRTCClock::getCurrentTime() {
|
||||
if (ds3231_success) {
|
||||
return rtc_3231.now().unixtime();
|
||||
}
|
||||
if (rv3028_success) {
|
||||
return DateTime(
|
||||
rtc_rv3028.getYear(),
|
||||
rtc_rv3028.getMonth(),
|
||||
rtc_rv3028.getDate(),
|
||||
rtc_rv3028.getHour(),
|
||||
rtc_rv3028.getMinute(),
|
||||
rtc_rv3028.getSecond()
|
||||
).unixtime();
|
||||
}
|
||||
return _fallback->getCurrentTime();
|
||||
}
|
||||
|
||||
void AutoDiscoverRTCClock::setCurrentTime(uint32_t time) {
|
||||
if (ds3231_success) {
|
||||
rtc_3231.adjust(DateTime(time));
|
||||
} else if (rv3028_success) {
|
||||
auto dt = DateTime(time);
|
||||
uint8_t weekday = (dt.day() + (uint16_t)((2.6 * dt.month()) - 0.2) - (2 * (dt.year() / 100)) + dt.year() + (uint16_t)(dt.year() / 4) + (uint16_t)(dt.year() / 400)) % 7;
|
||||
|
||||
rtc_rv3028.setTime(dt.year(), dt.month(), weekday, dt.day(), dt.hour(), dt.minute(), dt.second());
|
||||
} else {
|
||||
_fallback->setCurrentTime(time);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <Mesh.h>
|
||||
#include <Arduino.h>
|
||||
#include <Wire.h>
|
||||
|
||||
class AutoDiscoverRTCClock : public mesh::RTCClock {
|
||||
mesh::RTCClock* _fallback;
|
||||
|
||||
bool i2c_probe(TwoWire& wire, uint8_t addr);
|
||||
public:
|
||||
AutoDiscoverRTCClock(mesh::RTCClock& fallback) : _fallback(&fallback) { }
|
||||
|
||||
void begin(TwoWire& wire);
|
||||
uint32_t getCurrentTime() override;
|
||||
void setCurrentTime(uint32_t time) override;
|
||||
};
|
||||
+151
-14
@@ -1,11 +1,11 @@
|
||||
#include <helpers/BaseChatMesh.h>
|
||||
#include <Utils.h>
|
||||
|
||||
mesh::Packet* BaseChatMesh::createSelfAdvert(const char* name) {
|
||||
mesh::Packet* BaseChatMesh::createSelfAdvert(const char* name, double lat, double lon) {
|
||||
uint8_t app_data[MAX_ADVERT_DATA_SIZE];
|
||||
uint8_t app_data_len;
|
||||
{
|
||||
AdvertDataBuilder builder(ADV_TYPE_CHAT, name);
|
||||
AdvertDataBuilder builder(ADV_TYPE_CHAT, name, lat, lon);
|
||||
app_data_len = builder.encodeTo(app_data);
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@ void BaseChatMesh::onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id,
|
||||
from->out_path_len = -1; // initially out_path is unknown
|
||||
from->gps_lat = 0; // initially unknown GPS loc
|
||||
from->gps_lon = 0;
|
||||
from->sync_since = 0;
|
||||
|
||||
// only need to calculate the shared_secret once, for better performance
|
||||
self_id.calcSharedSecret(from->shared_secret, id);
|
||||
@@ -49,9 +50,12 @@ void BaseChatMesh::onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id,
|
||||
}
|
||||
}
|
||||
|
||||
// save a copy of raw advert packet (to support "Share..." function)
|
||||
int plen = packet->writeTo(temp_buf);
|
||||
putBlobByKey(id.pub_key, PUB_KEY_SIZE, temp_buf, plen);
|
||||
|
||||
// update
|
||||
strncpy(from->name, parser.getName(), sizeof(from->name)-1);
|
||||
from->name[sizeof(from->name)-1] = 0;
|
||||
StrHelper::strncpy(from->name, parser.getName(), sizeof(from->name));
|
||||
from->type = parser.getType();
|
||||
if (parser.hasLatLon()) {
|
||||
from->gps_lat = parser.getIntLat();
|
||||
@@ -84,15 +88,15 @@ void BaseChatMesh::getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) {
|
||||
}
|
||||
|
||||
void BaseChatMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, const uint8_t* secret, uint8_t* data, size_t len) {
|
||||
int i = matching_peer_indexes[sender_idx];
|
||||
if (i < 0 || i >= num_contacts) {
|
||||
MESH_DEBUG_PRINTLN("onPeerDataRecv: Invalid sender idx: %d", i);
|
||||
return;
|
||||
}
|
||||
|
||||
ContactInfo& from = contacts[i];
|
||||
|
||||
if (type == PAYLOAD_TYPE_TXT_MSG && len > 5) {
|
||||
int i = matching_peer_indexes[sender_idx];
|
||||
if (i < 0 || i >= num_contacts) {
|
||||
MESH_DEBUG_PRINTLN("onPeerDataRecv: Invalid sender idx: %d", i);
|
||||
return;
|
||||
}
|
||||
|
||||
ContactInfo& from = contacts[i];
|
||||
|
||||
uint32_t timestamp;
|
||||
memcpy(×tamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
|
||||
uint flags = data[4]; // message attempt number, and other flags
|
||||
@@ -125,6 +129,8 @@ void BaseChatMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender
|
||||
} else {
|
||||
MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported message type: %u", (uint32_t) (flags >> 2));
|
||||
}
|
||||
} else if (type == PAYLOAD_TYPE_RESPONSE && len > 0) {
|
||||
onContactResponse(from, data, len);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,6 +155,8 @@ bool BaseChatMesh::onPeerPathRecv(mesh::Packet* packet, int sender_idx, const ui
|
||||
if (processAck(extra)) {
|
||||
txt_send_timeout = 0; // matched one we're waiting for, cancel timeout timer
|
||||
}
|
||||
} else if (extra_type == PAYLOAD_TYPE_RESPONSE && extra_len > 0) {
|
||||
onContactResponse(from, extra, extra_len);
|
||||
}
|
||||
return true; // send reciprocal path if necessary
|
||||
}
|
||||
@@ -220,6 +228,113 @@ int BaseChatMesh::sendMessage(const ContactInfo& recipient, uint32_t timestamp,
|
||||
return rc;
|
||||
}
|
||||
|
||||
bool BaseChatMesh::sendGroupMessage(uint32_t timestamp, mesh::GroupChannel& channel, const char* sender_name, const char* text, int text_len) {
|
||||
uint8_t temp[5+MAX_TEXT_LEN+32];
|
||||
memcpy(temp, ×tamp, 4); // mostly an extra blob to help make packet_hash unique
|
||||
temp[4] = 0; // TXT_TYPE_PLAIN
|
||||
|
||||
sprintf((char *) &temp[5], "%s: ", sender_name); // <sender>: <msg>
|
||||
char *ep = strchr((char *) &temp[5], 0);
|
||||
int prefix_len = ep - (char *) &temp[5];
|
||||
|
||||
if (text_len + prefix_len > MAX_TEXT_LEN) text_len = MAX_TEXT_LEN - prefix_len;
|
||||
memcpy(ep, text, text_len);
|
||||
ep[text_len] = 0; // null terminator
|
||||
|
||||
auto pkt = createGroupDatagram(PAYLOAD_TYPE_GRP_TXT, channel, temp, 5 + prefix_len + text_len);
|
||||
if (pkt) {
|
||||
sendFlood(pkt);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool BaseChatMesh::shareContactZeroHop(const ContactInfo& contact) {
|
||||
int plen = getBlobByKey(contact.id.pub_key, PUB_KEY_SIZE, temp_buf); // retrieve last raw advert packet
|
||||
if (plen == 0) return false; // not found
|
||||
|
||||
auto packet = obtainNewPacket();
|
||||
if (packet == NULL) return false; // no Packets available
|
||||
|
||||
packet->readFrom(temp_buf, plen); // restore Packet from 'blob'
|
||||
sendZeroHop(packet);
|
||||
return true; // success
|
||||
}
|
||||
|
||||
uint8_t BaseChatMesh::exportContact(const ContactInfo& contact, uint8_t dest_buf[]) {
|
||||
return getBlobByKey(contact.id.pub_key, PUB_KEY_SIZE, dest_buf); // retrieve last raw advert packet
|
||||
}
|
||||
|
||||
bool BaseChatMesh::importContact(const uint8_t src_buf[], uint8_t len) {
|
||||
auto pkt = obtainNewPacket();
|
||||
if (pkt) {
|
||||
if (pkt->readFrom(src_buf, len) && pkt->getPayloadType() == PAYLOAD_TYPE_ADVERT) {
|
||||
pkt->header |= ROUTE_TYPE_FLOOD; // simulate it being received flood-mode
|
||||
_pendingLoopback = pkt; // loop-back, as if received over radio
|
||||
return true; // success
|
||||
} else {
|
||||
releasePacket(pkt); // undo the obtainNewPacket()
|
||||
}
|
||||
}
|
||||
return false; // error
|
||||
}
|
||||
|
||||
int BaseChatMesh::sendLogin(const ContactInfo& recipient, const char* password, uint32_t& est_timeout) {
|
||||
int tlen;
|
||||
uint8_t temp[24];
|
||||
uint32_t now = getRTCClock()->getCurrentTimeUnique();
|
||||
memcpy(temp, &now, 4); // mostly an extra blob to help make packet_hash unique
|
||||
if (recipient.type == ADV_TYPE_ROOM) {
|
||||
memcpy(&temp[4], &recipient.sync_since, 4);
|
||||
int len = strlen(password); if (len > 15) len = 15; // max 15 chars currently
|
||||
memcpy(&temp[8], password, len);
|
||||
tlen = 8 + len;
|
||||
} else {
|
||||
int len = strlen(password); if (len > 15) len = 15; // max 15 chars currently
|
||||
memcpy(&temp[4], password, len);
|
||||
tlen = 4 + len;
|
||||
}
|
||||
|
||||
auto pkt = createAnonDatagram(PAYLOAD_TYPE_ANON_REQ, self_id, recipient.id, recipient.shared_secret, temp, tlen);
|
||||
if (pkt) {
|
||||
uint32_t t = _radio->getEstAirtimeFor(pkt->payload_len + pkt->path_len + 2);
|
||||
if (recipient.out_path_len < 0) {
|
||||
sendFlood(pkt);
|
||||
est_timeout = calcFloodTimeoutMillisFor(t);
|
||||
return MSG_SEND_SENT_FLOOD;
|
||||
} else {
|
||||
sendDirect(pkt, recipient.out_path, recipient.out_path_len);
|
||||
est_timeout = calcDirectTimeoutMillisFor(t, recipient.out_path_len);
|
||||
return MSG_SEND_SENT_DIRECT;
|
||||
}
|
||||
}
|
||||
return MSG_SEND_FAILED;
|
||||
}
|
||||
|
||||
int BaseChatMesh::sendStatusRequest(const ContactInfo& recipient, uint32_t& est_timeout) {
|
||||
uint8_t temp[13];
|
||||
uint32_t now = getRTCClock()->getCurrentTimeUnique();
|
||||
memcpy(temp, &now, 4); // mostly an extra blob to help make packet_hash unique
|
||||
temp[4] = CMD_GET_STATUS;
|
||||
memset(&temp[5], 0, 4); // reserved (possibly for 'since' param)
|
||||
getRNG()->random(&temp[9], 4); // random blob to help make packet-hash unique
|
||||
|
||||
auto pkt = createDatagram(PAYLOAD_TYPE_REQ, recipient.id, recipient.shared_secret, temp, sizeof(temp));
|
||||
if (pkt) {
|
||||
uint32_t t = _radio->getEstAirtimeFor(pkt->payload_len + pkt->path_len + 2);
|
||||
if (recipient.out_path_len < 0) {
|
||||
sendFlood(pkt);
|
||||
est_timeout = calcFloodTimeoutMillisFor(t);
|
||||
return MSG_SEND_SENT_FLOOD;
|
||||
} else {
|
||||
sendDirect(pkt, recipient.out_path, recipient.out_path_len);
|
||||
est_timeout = calcDirectTimeoutMillisFor(t, recipient.out_path_len);
|
||||
return MSG_SEND_SENT_DIRECT;
|
||||
}
|
||||
}
|
||||
return MSG_SEND_FAILED;
|
||||
}
|
||||
|
||||
void BaseChatMesh::resetPathTo(ContactInfo& recipient) {
|
||||
recipient.out_path_len = -1;
|
||||
}
|
||||
@@ -281,6 +396,22 @@ bool BaseChatMesh::addContact(const ContactInfo& contact) {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool BaseChatMesh::removeContact(ContactInfo& contact) {
|
||||
int idx = 0;
|
||||
while (idx < num_contacts && !contacts[idx].id.matches(contact.id)) {
|
||||
idx++;
|
||||
}
|
||||
if (idx >= num_contacts) return false; // not found
|
||||
|
||||
// remove from contacts array
|
||||
num_contacts--;
|
||||
while (idx < num_contacts) {
|
||||
contacts[idx] = contacts[idx + 1];
|
||||
idx++;
|
||||
}
|
||||
return true; // Success
|
||||
}
|
||||
|
||||
#ifdef MAX_GROUP_CHANNELS
|
||||
#include <base64.hpp>
|
||||
|
||||
@@ -309,7 +440,7 @@ ContactsIterator BaseChatMesh::startContactsIterator() {
|
||||
}
|
||||
|
||||
bool ContactsIterator::hasNext(const BaseChatMesh* mesh, ContactInfo& dest) {
|
||||
if (next_idx >= mesh->num_contacts) return false;
|
||||
if (next_idx >= mesh->getNumContacts()) return false;
|
||||
|
||||
dest = mesh->contacts[next_idx++];
|
||||
return true;
|
||||
@@ -323,4 +454,10 @@ void BaseChatMesh::loop() {
|
||||
onSendTimeout();
|
||||
txt_send_timeout = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (_pendingLoopback) {
|
||||
onRecvPacket(_pendingLoopback); // loop-back, as if received over radio
|
||||
releasePacket(_pendingLoopback); // undo the obtainNewPacket()
|
||||
_pendingLoopback = NULL;
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ struct ContactInfo {
|
||||
uint8_t shared_secret[PUB_KEY_SIZE];
|
||||
uint32_t lastmod; // by OUR clock
|
||||
int32_t gps_lat, gps_lon; // 6 dec places
|
||||
uint32_t sync_since;
|
||||
};
|
||||
|
||||
#define MAX_SEARCH_RESULTS 8
|
||||
@@ -26,6 +27,10 @@ struct ContactInfo {
|
||||
#define MSG_SEND_SENT_FLOOD 1
|
||||
#define MSG_SEND_SENT_DIRECT 2
|
||||
|
||||
#define CMD_GET_STATUS 0x01 // same as _GET_STATS
|
||||
|
||||
#define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ
|
||||
|
||||
class ContactVisitor {
|
||||
public:
|
||||
virtual void onContactVisit(const ContactInfo& contact) = 0;
|
||||
@@ -59,6 +64,8 @@ class BaseChatMesh : public mesh::Mesh {
|
||||
mesh::GroupChannel channels[MAX_GROUP_CHANNELS];
|
||||
int num_channels;
|
||||
#endif
|
||||
mesh::Packet* _pendingLoopback;
|
||||
uint8_t temp_buf[MAX_TRANS_UNIT];
|
||||
|
||||
mesh::Packet* composeMsgPacket(const ContactInfo& recipient, uint32_t timestamp, uint8_t attempt, const char *text, uint32_t& expected_ack);
|
||||
|
||||
@@ -71,6 +78,7 @@ protected:
|
||||
num_channels = 0;
|
||||
#endif
|
||||
txt_send_timeout = 0;
|
||||
_pendingLoopback = NULL;
|
||||
}
|
||||
|
||||
// 'UI' concepts, for sub-classes to implement
|
||||
@@ -82,6 +90,11 @@ protected:
|
||||
virtual uint32_t calcDirectTimeoutMillisFor(uint32_t pkt_airtime_millis, uint8_t path_len) const = 0;
|
||||
virtual void onSendTimeout() = 0;
|
||||
virtual void onChannelMessageRecv(const mesh::GroupChannel& channel, int in_path_len, uint32_t timestamp, const char *text) = 0;
|
||||
virtual void onContactResponse(const ContactInfo& contact, const uint8_t* data, uint8_t len) = 0;
|
||||
|
||||
// storage concepts, for sub-classes to override/implement
|
||||
virtual int getBlobByKey(const uint8_t key[], int key_len, uint8_t dest_buf[]) { return 0; } // not implemented
|
||||
virtual bool putBlobByKey(const uint8_t key[], int key_len, const uint8_t src_buf[], int len) { return false; }
|
||||
|
||||
// Mesh overrides
|
||||
void onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, uint32_t timestamp, const uint8_t* app_data, size_t app_data_len) override;
|
||||
@@ -96,12 +109,19 @@ protected:
|
||||
void onGroupDataRecv(mesh::Packet* packet, uint8_t type, const mesh::GroupChannel& channel, uint8_t* data, size_t len) override;
|
||||
|
||||
public:
|
||||
mesh::Packet* createSelfAdvert(const char* name);
|
||||
mesh::Packet* createSelfAdvert(const char* name, double lat=0.0, double lon=0.0);
|
||||
int sendMessage(const ContactInfo& recipient, uint32_t timestamp, uint8_t attempt, const char* text, uint32_t& expected_ack, uint32_t& est_timeout);
|
||||
bool sendGroupMessage(uint32_t timestamp, mesh::GroupChannel& channel, const char* sender_name, const char* text, int text_len);
|
||||
int sendLogin(const ContactInfo& recipient, const char* password, uint32_t& est_timeout);
|
||||
int sendStatusRequest(const ContactInfo& recipient, uint32_t& est_timeout);
|
||||
bool shareContactZeroHop(const ContactInfo& contact);
|
||||
uint8_t exportContact(const ContactInfo& contact, uint8_t dest_buf[]);
|
||||
bool importContact(const uint8_t src_buf[], uint8_t len);
|
||||
void resetPathTo(ContactInfo& recipient);
|
||||
void scanRecentContacts(int last_n, ContactVisitor* visitor);
|
||||
ContactInfo* searchContactsByPrefix(const char* name_prefix);
|
||||
ContactInfo* lookupContactByPubKey(const uint8_t* pub_key, int prefix_len);
|
||||
bool removeContact(ContactInfo& contact);
|
||||
bool addContact(const ContactInfo& contact);
|
||||
int getNumContacts() const { return num_contacts; }
|
||||
ContactsIterator startContactsIterator();
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
#pragma once
|
||||
|
||||
#include <RadioLib.h>
|
||||
|
||||
#define SX126X_IRQ_HEADER_VALID 0b0000010000 // 4 4 valid LoRa header received
|
||||
|
||||
class CustomLLCC68 : public LLCC68 {
|
||||
public:
|
||||
CustomLLCC68(Module *mod) : LLCC68(mod) { }
|
||||
|
||||
bool isReceiving() {
|
||||
uint16_t irq = getIrqStatus();
|
||||
bool hasPreamble = (irq & SX126X_IRQ_HEADER_VALID);
|
||||
return hasPreamble;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,29 @@
|
||||
#pragma once
|
||||
|
||||
#include "CustomLLCC68.h"
|
||||
#include "RadioLibWrappers.h"
|
||||
|
||||
class CustomLLCC68Wrapper : public RadioLibWrapper {
|
||||
public:
|
||||
CustomLLCC68Wrapper(CustomLLCC68& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { }
|
||||
bool isReceiving() override {
|
||||
if (((CustomLLCC68 *)_radio)->isReceiving()) return true;
|
||||
|
||||
idle(); // put sx126x into standby
|
||||
// do some basic CAD (blocks for ~12780 micros (on SF 10)!)
|
||||
bool activity = (((CustomLLCC68 *)_radio)->scanChannel() == RADIOLIB_LORA_DETECTED);
|
||||
if (activity) {
|
||||
startRecv();
|
||||
} else {
|
||||
idle();
|
||||
}
|
||||
return activity;
|
||||
}
|
||||
float getLastRSSI() const override { return ((CustomLLCC68 *)_radio)->getRSSI(); }
|
||||
float getLastSNR() const override { return ((CustomLLCC68 *)_radio)->getSNR(); }
|
||||
|
||||
float packetScore(float snr, int packet_len) override {
|
||||
int sf = ((CustomLLCC68 *)_radio)->spreadingFactor;
|
||||
return packetScoreInt(snr, sf, packet_len);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <RadioLib.h>
|
||||
|
||||
#define LR1110_IRQ_HAS_PREAMBLE 0b0000000100 // 4 4 valid LoRa header received
|
||||
#define LR1110_IRQ_HEADER_VALID 0b0000010000 // 4 4 valid LoRa header received
|
||||
|
||||
class CustomLR1110 : public LR1110 {
|
||||
public:
|
||||
CustomLR1110(Module *mod) : LR1110(mod) { }
|
||||
|
||||
bool isReceiving() {
|
||||
uint16_t irq = getIrqStatus();
|
||||
bool hasPreamble = ((irq & LR1110_IRQ_HEADER_VALID) && (irq & LR1110_IRQ_HAS_PREAMBLE));
|
||||
return hasPreamble;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
|
||||
#include "CustomLR1110.h"
|
||||
#include "RadioLibWrappers.h"
|
||||
|
||||
class CustomLR1110Wrapper : public RadioLibWrapper {
|
||||
public:
|
||||
CustomLR1110Wrapper(CustomLR1110& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { }
|
||||
bool isReceiving() override {
|
||||
if (((CustomLR1110 *)_radio)->isReceiving()) return true;
|
||||
|
||||
idle(); // put sx126x into standby
|
||||
// do some basic CAD (blocks for ~12780 micros (on SF 10)!)
|
||||
bool activity = (((CustomLR1110 *)_radio)->scanChannel() == RADIOLIB_LORA_DETECTED);
|
||||
if (activity) {
|
||||
startRecv();
|
||||
} else {
|
||||
idle();
|
||||
}
|
||||
return activity;
|
||||
}
|
||||
|
||||
void onSendFinished() override {
|
||||
RadioLibWrapper::onSendFinished();
|
||||
_radio->setPreambleLength(8); // overcomes weird issues with small and big pkts
|
||||
}
|
||||
|
||||
float getLastRSSI() const override { return ((CustomLR1110 *)_radio)->getRSSI(); }
|
||||
float getLastSNR() const override { return ((CustomLR1110 *)_radio)->getSNR(); }
|
||||
};
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include "CustomSX1262.h"
|
||||
#include "RadioLibWrappers.h"
|
||||
#include <math.h>
|
||||
|
||||
class CustomSX1262Wrapper : public RadioLibWrapper {
|
||||
public:
|
||||
@@ -12,10 +13,18 @@ public:
|
||||
idle(); // put sx126x into standby
|
||||
// do some basic CAD (blocks for ~12780 micros (on SF 10)!)
|
||||
bool activity = (((CustomSX1262 *)_radio)->scanChannel() == RADIOLIB_LORA_DETECTED);
|
||||
idle();
|
||||
|
||||
if (activity) {
|
||||
startRecv();
|
||||
} else {
|
||||
idle();
|
||||
}
|
||||
return activity;
|
||||
}
|
||||
float getLastRSSI() const override { return ((CustomSX1262 *)_radio)->getRSSI(); }
|
||||
float getLastSNR() const override { return ((CustomSX1262 *)_radio)->getSNR(); }
|
||||
|
||||
float packetScore(float snr, int packet_len) override {
|
||||
int sf = ((CustomSX1262 *)_radio)->spreadingFactor;
|
||||
return packetScoreInt(snr, sf, packet_len);
|
||||
}
|
||||
};
|
||||
@@ -12,10 +12,18 @@ public:
|
||||
idle(); // put sx126x into standby
|
||||
// do some basic CAD (blocks for ~12780 micros (on SF 10)!)
|
||||
bool activity = (((CustomSX1268 *)_radio)->scanChannel() == RADIOLIB_LORA_DETECTED);
|
||||
idle();
|
||||
|
||||
if (activity) {
|
||||
startRecv();
|
||||
} else {
|
||||
idle();
|
||||
}
|
||||
return activity;
|
||||
}
|
||||
float getLastRSSI() const override { return ((CustomSX1268 *)_radio)->getRSSI(); }
|
||||
float getLastSNR() const override { return ((CustomSX1268 *)_radio)->getSNR(); }
|
||||
|
||||
float packetScore(float snr, int packet_len) override {
|
||||
int sf = ((CustomSX1268 *)_radio)->spreadingFactor;
|
||||
return packetScoreInt(snr, sf, packet_len);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,37 @@
|
||||
#pragma once
|
||||
|
||||
#include <RadioLib.h>
|
||||
|
||||
#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
|
||||
|
||||
class CustomSX1276 : public SX1276 {
|
||||
public:
|
||||
CustomSX1276(Module *mod) : SX1276(mod) { }
|
||||
|
||||
bool isReceiving() {
|
||||
return (getModemStatus() &
|
||||
(RH_RF95_MODEM_STATUS_SIGNAL_DETECTED
|
||||
| RH_RF95_MODEM_STATUS_SIGNAL_SYNCHRONIZED
|
||||
| RH_RF95_MODEM_STATUS_HEADER_INFO_VALID)) != 0;
|
||||
}
|
||||
|
||||
int tryScanChannel() {
|
||||
// start CAD
|
||||
int16_t state = startChannelScan();
|
||||
RADIOLIB_ASSERT(state);
|
||||
|
||||
// wait for channel activity detected or timeout
|
||||
unsigned long timeout = millis() + 16;
|
||||
while(!this->mod->hal->digitalRead(this->mod->getIrq()) && millis() < timeout) {
|
||||
this->mod->hal->yield();
|
||||
if(this->mod->hal->digitalRead(this->mod->getGpio())) {
|
||||
return(RADIOLIB_PREAMBLE_DETECTED);
|
||||
}
|
||||
}
|
||||
return 0; // timed out
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,29 @@
|
||||
#pragma once
|
||||
|
||||
#include "CustomSX1276.h"
|
||||
#include "RadioLibWrappers.h"
|
||||
|
||||
class CustomSX1276Wrapper : public RadioLibWrapper {
|
||||
public:
|
||||
CustomSX1276Wrapper(CustomSX1276& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { }
|
||||
bool isReceiving() override {
|
||||
if (((CustomSX1276 *)_radio)->isReceiving()) return true;
|
||||
|
||||
idle(); // put into standby
|
||||
// do some basic CAD (blocks for ~12780 micros (on SF 10)!)
|
||||
bool activity = (((CustomSX1276 *)_radio)->tryScanChannel() == RADIOLIB_PREAMBLE_DETECTED);
|
||||
if (activity) {
|
||||
startRecv();
|
||||
} else {
|
||||
idle();
|
||||
}
|
||||
return activity;
|
||||
}
|
||||
float getLastRSSI() const override { return ((CustomSX1276 *)_radio)->getRSSI(); }
|
||||
float getLastSNR() const override { return ((CustomSX1276 *)_radio)->getSNR(); }
|
||||
|
||||
float packetScore(float snr, int packet_len) override {
|
||||
int sf = ((CustomSX1276 *)_radio)->spreadingFactor;
|
||||
return packetScoreInt(snr, sf, packet_len);
|
||||
}
|
||||
};
|
||||
@@ -16,12 +16,50 @@ public:
|
||||
void begin() {
|
||||
// for future use, sub-classes SHOULD call this from their begin()
|
||||
startup_reason = BD_STARTUP_NORMAL;
|
||||
|
||||
#ifdef PIN_VBAT_READ
|
||||
// battery read support
|
||||
pinMode(PIN_VBAT_READ, INPUT);
|
||||
adcAttachPin(PIN_VBAT_READ);
|
||||
#endif
|
||||
|
||||
#ifdef P_LORA_TX_LED
|
||||
pinMode(P_LORA_TX_LED, OUTPUT);
|
||||
digitalWrite(P_LORA_TX_LED, LOW);
|
||||
#endif
|
||||
|
||||
#if defined(PIN_BOARD_SDA) && defined(PIN_BOARD_SCL)
|
||||
Wire.begin(PIN_BOARD_SDA, PIN_BOARD_SCL);
|
||||
#else
|
||||
Wire.begin();
|
||||
#endif
|
||||
}
|
||||
|
||||
uint8_t getStartupReason() const override { return startup_reason; }
|
||||
|
||||
#if defined(P_LORA_TX_LED)
|
||||
void onBeforeTransmit() override {
|
||||
digitalWrite(P_LORA_TX_LED, HIGH); // turn TX LED on
|
||||
}
|
||||
void onAfterTransmit() override {
|
||||
digitalWrite(P_LORA_TX_LED, LOW); // turn TX LED off
|
||||
}
|
||||
#endif
|
||||
|
||||
uint16_t getBattMilliVolts() override {
|
||||
#ifdef PIN_VBAT_READ
|
||||
analogReadResolution(12);
|
||||
|
||||
uint32_t raw = 0;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
raw += analogReadMilliVolts(PIN_VBAT_READ);
|
||||
}
|
||||
raw = raw / 4;
|
||||
|
||||
return (2 * raw);
|
||||
#else
|
||||
return 0; // not supported
|
||||
#endif
|
||||
}
|
||||
|
||||
const char* getManufacturerName() const override {
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
// LoRa radio module pins for Heltec V2
|
||||
#define P_LORA_DIO_1 26 // DIO0
|
||||
#define P_LORA_NSS 18
|
||||
#define P_LORA_RESET RADIOLIB_NC // 14
|
||||
#define P_LORA_BUSY RADIOLIB_NC
|
||||
#define P_LORA_SCLK 5
|
||||
#define P_LORA_MISO 19
|
||||
#define P_LORA_MOSI 27
|
||||
|
||||
// built-ins
|
||||
#define PIN_VBAT_READ 37
|
||||
#define PIN_LED_BUILTIN 25
|
||||
|
||||
#include "ESP32Board.h"
|
||||
|
||||
#include <driver/rtc_io.h>
|
||||
|
||||
class HeltecV2Board : public ESP32Board {
|
||||
public:
|
||||
void begin() {
|
||||
ESP32Board::begin();
|
||||
|
||||
esp_reset_reason_t reason = esp_reset_reason();
|
||||
if (reason == ESP_RST_DEEPSLEEP) {
|
||||
long wakeup_source = esp_sleep_get_ext1_wakeup_status();
|
||||
if (wakeup_source & (1 << P_LORA_DIO_1)) { // received a LoRa packet (while in deep sleep)
|
||||
startup_reason = BD_STARTUP_RX_PACKET;
|
||||
}
|
||||
|
||||
rtc_gpio_hold_dis((gpio_num_t)P_LORA_NSS);
|
||||
rtc_gpio_deinit((gpio_num_t)P_LORA_DIO_1);
|
||||
}
|
||||
}
|
||||
|
||||
void enterDeepSleep(uint32_t secs, int pin_wake_btn = -1) {
|
||||
esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);
|
||||
|
||||
// Make sure the DIO1 and NSS GPIOs are hold on required levels during deep sleep
|
||||
rtc_gpio_set_direction((gpio_num_t)P_LORA_DIO_1, RTC_GPIO_MODE_INPUT_ONLY);
|
||||
rtc_gpio_pulldown_en((gpio_num_t)P_LORA_DIO_1);
|
||||
|
||||
rtc_gpio_hold_en((gpio_num_t)P_LORA_NSS);
|
||||
|
||||
if (pin_wake_btn < 0) {
|
||||
esp_sleep_enable_ext1_wakeup( (1L << P_LORA_DIO_1), ESP_EXT1_WAKEUP_ANY_HIGH); // wake up on: recv LoRa packet
|
||||
} else {
|
||||
esp_sleep_enable_ext1_wakeup( (1L << P_LORA_DIO_1) | (1L << pin_wake_btn), ESP_EXT1_WAKEUP_ANY_HIGH); // wake up on: recv LoRa packet OR wake btn
|
||||
}
|
||||
|
||||
if (secs > 0) {
|
||||
esp_sleep_enable_timer_wakeup(secs * 1000000);
|
||||
}
|
||||
|
||||
// Finally set ESP32 into sleep
|
||||
esp_deep_sleep_start(); // CPU halts here and never returns!
|
||||
}
|
||||
|
||||
uint16_t getBattMilliVolts() override {
|
||||
analogReadResolution(10);
|
||||
|
||||
uint32_t raw = 0;
|
||||
for (int i = 0; i < 8; i++) {
|
||||
raw += analogRead(PIN_VBAT_READ);
|
||||
}
|
||||
raw = raw / 8;
|
||||
|
||||
return (1.883 * (2 / 1024.0) * raw) * 1000;
|
||||
}
|
||||
|
||||
const char* getManufacturerName() const override {
|
||||
return "Heltec V2";
|
||||
}
|
||||
};
|
||||
@@ -1,6 +1,5 @@
|
||||
#pragma once
|
||||
|
||||
#include "ESP32Board.h"
|
||||
#include <Arduino.h>
|
||||
|
||||
// LoRa radio module pins for Heltec V3
|
||||
@@ -19,6 +18,8 @@
|
||||
#define PIN_ADC_CTRL_INACTIVE HIGH
|
||||
#define PIN_LED_BUILTIN 35
|
||||
|
||||
#include "ESP32Board.h"
|
||||
|
||||
#include <driver/rtc_io.h>
|
||||
|
||||
class HeltecV3Board : public ESP32Board {
|
||||
@@ -26,6 +27,8 @@ public:
|
||||
void begin() {
|
||||
ESP32Board::begin();
|
||||
|
||||
pinMode(PIN_ADC_CTRL, OUTPUT);
|
||||
|
||||
esp_reset_reason_t reason = esp_reset_reason();
|
||||
if (reason == ESP_RST_DEEPSLEEP) {
|
||||
long wakeup_source = esp_sleep_get_ext1_wakeup_status();
|
||||
@@ -36,17 +39,6 @@ public:
|
||||
rtc_gpio_hold_dis((gpio_num_t)P_LORA_NSS);
|
||||
rtc_gpio_deinit((gpio_num_t)P_LORA_DIO_1);
|
||||
}
|
||||
|
||||
// battery read support
|
||||
pinMode(PIN_VBAT_READ, INPUT);
|
||||
adcAttachPin(PIN_VBAT_READ);
|
||||
analogReadResolution(10);
|
||||
pinMode(PIN_ADC_CTRL, OUTPUT);
|
||||
|
||||
#ifdef P_LORA_TX_LED
|
||||
pinMode(P_LORA_TX_LED, OUTPUT);
|
||||
digitalWrite(P_LORA_TX_LED, LOW);
|
||||
#endif
|
||||
}
|
||||
|
||||
void enterDeepSleep(uint32_t secs, int pin_wake_btn = -1) {
|
||||
@@ -72,16 +64,8 @@ public:
|
||||
esp_deep_sleep_start(); // CPU halts here and never returns!
|
||||
}
|
||||
|
||||
#if defined(P_LORA_TX_LED)
|
||||
void onBeforeTransmit() override {
|
||||
digitalWrite(P_LORA_TX_LED, HIGH); // turn TX LED on
|
||||
}
|
||||
void onAfterTransmit() override {
|
||||
digitalWrite(P_LORA_TX_LED, LOW); // turn TX LED off
|
||||
}
|
||||
#endif
|
||||
|
||||
uint16_t getBattMilliVolts() override {
|
||||
analogReadResolution(10);
|
||||
digitalWrite(PIN_ADC_CTRL, PIN_ADC_CTRL_ACTIVE);
|
||||
|
||||
uint32_t raw = 0;
|
||||
|
||||
@@ -45,10 +45,12 @@ bool IdentityStore::save(const char *name, const mesh::LocalIdentity& id) {
|
||||
File file = _fs->open(filename, "w", true);
|
||||
#endif
|
||||
if (file) {
|
||||
id.writeTo(file);
|
||||
bool success = id.writeTo(file);
|
||||
file.close();
|
||||
MESH_DEBUG_PRINTLN("IdentityStore::save() write - %s", success ? "OK" : "Err");
|
||||
return true;
|
||||
}
|
||||
MESH_DEBUG_PRINTLN("IdentityStore::save() failed");
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -35,6 +35,15 @@ void RadioLibWrapper::idle() {
|
||||
state = STATE_IDLE; // need another startReceive()
|
||||
}
|
||||
|
||||
void RadioLibWrapper::startRecv() {
|
||||
int err = _radio->startReceive();
|
||||
if (err == RADIOLIB_ERR_NONE) {
|
||||
state = STATE_RX;
|
||||
} else {
|
||||
MESH_DEBUG_PRINTLN("RadioLibWrapper: error: startReceive(%d)", err);
|
||||
}
|
||||
}
|
||||
|
||||
int RadioLibWrapper::recvRaw(uint8_t* bytes, int sz) {
|
||||
if (state & STATE_INT_READY) {
|
||||
int len = _radio->getPacketLength();
|
||||
@@ -54,10 +63,11 @@ int RadioLibWrapper::recvRaw(uint8_t* bytes, int sz) {
|
||||
|
||||
if (state != STATE_RX) {
|
||||
int err = _radio->startReceive();
|
||||
if (err != RADIOLIB_ERR_NONE) {
|
||||
if (err == RADIOLIB_ERR_NONE) {
|
||||
state = STATE_RX;
|
||||
} else {
|
||||
MESH_DEBUG_PRINTLN("RadioLibWrapper: error: startReceive(%d)", err);
|
||||
}
|
||||
state = STATE_RX;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -96,3 +106,24 @@ float RadioLibWrapper::getLastRSSI() const {
|
||||
float RadioLibWrapper::getLastSNR() const {
|
||||
return _radio->getSNR();
|
||||
}
|
||||
|
||||
// Approximate SNR threshold per SF for successful reception (based on Semtech datasheets)
|
||||
static float snr_threshold[] = {
|
||||
-7.5, // SF7 needs at least -7.5 dB SNR
|
||||
-10, // SF8 needs at least -10 dB SNR
|
||||
-12.5, // SF9 needs at least -12.5 dB SNR
|
||||
-15, // SF10 needs at least -15 dB SNR
|
||||
-17.5,// SF11 needs at least -17.5 dB SNR
|
||||
-20 // SF12 needs at least -20 dB SNR
|
||||
};
|
||||
|
||||
float RadioLibWrapper::packetScoreInt(float snr, int sf, int packet_len) {
|
||||
if (sf < 7) return 0.0f;
|
||||
|
||||
if (snr < snr_threshold[sf - 7]) return 0.0f; // Below threshold, no chance of success
|
||||
|
||||
auto success_rate_based_on_snr = (snr - snr_threshold[sf - 7]) / 10.0;
|
||||
auto collision_penalty = 1 - (packet_len / 256.0); // Assuming max packet of 256 bytes
|
||||
|
||||
return max(0.0, min(1.0, success_rate_based_on_snr * collision_penalty));
|
||||
}
|
||||
@@ -10,6 +10,8 @@ protected:
|
||||
uint32_t n_recv, n_sent;
|
||||
|
||||
void idle();
|
||||
void startRecv();
|
||||
float packetScoreInt(float snr, int sf, int packet_len);
|
||||
|
||||
public:
|
||||
RadioLibWrapper(PhysicalLayer& radio, mesh::MainBoard& board) : _radio(&radio), _board(&board) { n_recv = n_sent = 0; }
|
||||
@@ -25,6 +27,8 @@ public:
|
||||
uint32_t getPacketsSent() const { return n_sent; }
|
||||
virtual float getLastRSSI() const override;
|
||||
virtual float getLastSNR() const override;
|
||||
|
||||
float packetScore(float snr, int packet_len) override { return packetScoreInt(snr, 10, packet_len); } // assume sf=10
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -7,42 +7,80 @@
|
||||
#endif
|
||||
|
||||
#define MAX_PACKET_HASHES 128
|
||||
#define MAX_PACKET_ACKS 64
|
||||
|
||||
class SimpleMeshTables : public mesh::MeshTables {
|
||||
uint8_t _hashes[MAX_PACKET_HASHES*MAX_HASH_SIZE];
|
||||
int _next_idx;
|
||||
uint32_t _acks[MAX_PACKET_ACKS];
|
||||
int _next_ack_idx;
|
||||
uint32_t _direct_dups, _flood_dups;
|
||||
|
||||
public:
|
||||
SimpleMeshTables() {
|
||||
memset(_hashes, 0, sizeof(_hashes));
|
||||
_next_idx = 0;
|
||||
memset(_acks, 0, sizeof(_acks));
|
||||
_next_ack_idx = 0;
|
||||
_direct_dups = _flood_dups = 0;
|
||||
}
|
||||
|
||||
#ifdef ESP32
|
||||
void restoreFrom(File f) {
|
||||
f.read(_hashes, sizeof(_hashes));
|
||||
f.read((uint8_t *) &_next_idx, sizeof(_next_idx));
|
||||
f.read((uint8_t *) &_acks[0], sizeof(_acks));
|
||||
f.read((uint8_t *) &_next_ack_idx, sizeof(_next_ack_idx));
|
||||
}
|
||||
void saveTo(File f) {
|
||||
f.write(_hashes, sizeof(_hashes));
|
||||
f.write((const uint8_t *) &_next_idx, sizeof(_next_idx));
|
||||
f.write((const uint8_t *) &_acks[0], sizeof(_acks));
|
||||
f.write((const uint8_t *) &_next_ack_idx, sizeof(_next_ack_idx));
|
||||
}
|
||||
#endif
|
||||
|
||||
bool hasSeen(const mesh::Packet* packet) override {
|
||||
if (packet->getPayloadType() == PAYLOAD_TYPE_ACK) {
|
||||
uint32_t ack;
|
||||
memcpy(&ack, packet->payload, 4);
|
||||
for (int i = 0; i < MAX_PACKET_ACKS; i++) {
|
||||
if (ack == _acks[i]) {
|
||||
if (packet->isRouteDirect()) {
|
||||
_direct_dups++; // keep some stats
|
||||
} else {
|
||||
_flood_dups++;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
_acks[_next_ack_idx] = ack;
|
||||
_next_ack_idx = (_next_ack_idx + 1) % MAX_PACKET_ACKS; // cyclic table
|
||||
return false;
|
||||
}
|
||||
|
||||
uint8_t hash[MAX_HASH_SIZE];
|
||||
packet->calculatePacketHash(hash);
|
||||
|
||||
const uint8_t* sp = _hashes;
|
||||
for (int i = 0; i < MAX_PACKET_HASHES; i++, sp += MAX_HASH_SIZE) {
|
||||
if (memcmp(hash, sp, MAX_HASH_SIZE) == 0) return true;
|
||||
if (memcmp(hash, sp, MAX_HASH_SIZE) == 0) {
|
||||
if (packet->isRouteDirect()) {
|
||||
_direct_dups++; // keep some stats
|
||||
} else {
|
||||
_flood_dups++;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
memcpy(&_hashes[_next_idx*MAX_HASH_SIZE], hash, MAX_HASH_SIZE);
|
||||
_next_idx = (_next_idx + 1) % MAX_PACKET_HASHES; // cyclic table
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
uint32_t getNumDirectDups() const { return _direct_dups; }
|
||||
uint32_t getNumFloodDups() const { return _flood_dups; }
|
||||
|
||||
};
|
||||
@@ -57,7 +57,7 @@ void PacketQueue::add(mesh::Packet* packet, uint8_t priority, uint32_t scheduled
|
||||
_num++;
|
||||
}
|
||||
|
||||
StaticPoolPacketManager::StaticPoolPacketManager(int pool_size): unused(pool_size), send_queue(pool_size) {
|
||||
StaticPoolPacketManager::StaticPoolPacketManager(int pool_size): unused(pool_size), send_queue(pool_size), rx_queue(pool_size) {
|
||||
// load up our unusued Packet pool
|
||||
for (int i = 0; i < pool_size; i++) {
|
||||
unused.add(new mesh::Packet(), 0, 0);
|
||||
@@ -95,3 +95,10 @@ mesh::Packet* StaticPoolPacketManager::getOutboundByIdx(int i) {
|
||||
mesh::Packet* StaticPoolPacketManager::removeOutboundByIdx(int i) {
|
||||
return send_queue.removeByIdx(i);
|
||||
}
|
||||
|
||||
void StaticPoolPacketManager::queueInbound(mesh::Packet* packet, uint32_t scheduled_for) {
|
||||
rx_queue.add(packet, 0, scheduled_for);
|
||||
}
|
||||
mesh::Packet* StaticPoolPacketManager::getNextInbound(uint32_t now) {
|
||||
return rx_queue.get(now);
|
||||
}
|
||||
@@ -18,7 +18,7 @@ public:
|
||||
};
|
||||
|
||||
class StaticPoolPacketManager : public mesh::PacketManager {
|
||||
PacketQueue unused, send_queue;
|
||||
PacketQueue unused, send_queue, rx_queue;
|
||||
|
||||
public:
|
||||
StaticPoolPacketManager(int pool_size);
|
||||
@@ -31,4 +31,6 @@ public:
|
||||
int getFreeCount() const override;
|
||||
mesh::Packet* getOutboundByIdx(int i) override;
|
||||
mesh::Packet* removeOutboundByIdx(int i) override;
|
||||
void queueInbound(mesh::Packet* packet, uint32_t scheduled_for) override;
|
||||
mesh::Packet* getNextInbound(uint32_t now) override;
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
#include "TxtDataHelpers.h"
|
||||
|
||||
void StrHelper::strncpy(char* dest, const char* src, size_t buf_sz) {
|
||||
while (buf_sz > 1 && *src) {
|
||||
*dest++ = *src++;
|
||||
buf_sz--;
|
||||
}
|
||||
*dest = 0; // truncates if needed
|
||||
}
|
||||
|
||||
void StrHelper::strzcpy(char* dest, const char* src, size_t buf_sz) {
|
||||
while (buf_sz > 1 && *src) {
|
||||
*dest++ = *src++;
|
||||
buf_sz--;
|
||||
}
|
||||
while (buf_sz > 0) { // pad remaining with nulls
|
||||
*dest++ = 0;
|
||||
buf_sz--;
|
||||
}
|
||||
}
|
||||
@@ -6,3 +6,9 @@
|
||||
#define TXT_TYPE_PLAIN 0 // a plain text message
|
||||
#define TXT_TYPE_CLI_DATA 1 // a CLI command
|
||||
#define TXT_TYPE_SIGNED_PLAIN 2 // plain text, signed by sender
|
||||
|
||||
class StrHelper {
|
||||
public:
|
||||
static void strncpy(char* dest, const char* src, size_t buf_sz);
|
||||
static void strzcpy(char* dest, const char* src, size_t buf_sz); // pads with trailing nulls
|
||||
};
|
||||
@@ -7,18 +7,19 @@
|
||||
#define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
|
||||
#define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
|
||||
|
||||
#define ADVERT_RESTART_DELAY 1000 // millis
|
||||
|
||||
void SerialBLEInterface::begin(const char* device_name, uint32_t pin_code) {
|
||||
_pin_code = pin_code;
|
||||
|
||||
// Create the BLE Device
|
||||
BLEDevice::init(device_name);
|
||||
BLEDevice::setEncryptionLevel(ESP_BLE_SEC_ENCRYPT);
|
||||
BLEDevice::setSecurityCallbacks(this);
|
||||
BLEDevice::setMTU(MAX_FRAME_SIZE);
|
||||
|
||||
BLESecurity sec;
|
||||
sec.setStaticPIN(pin_code);
|
||||
sec.setAuthenticationMode(ESP_LE_AUTH_REQ_SC_BOND);
|
||||
sec.setAuthenticationMode(ESP_LE_AUTH_REQ_SC_MITM_BOND);
|
||||
|
||||
//BLEDevice::setPower(ESP_PWR_LVL_N8);
|
||||
|
||||
@@ -31,11 +32,11 @@ void SerialBLEInterface::begin(const char* device_name, uint32_t pin_code) {
|
||||
|
||||
// Create a BLE Characteristic
|
||||
pTxCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID_TX, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
|
||||
pTxCharacteristic->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED);
|
||||
pTxCharacteristic->setAccessPermissions(ESP_GATT_PERM_READ_ENC_MITM);
|
||||
pTxCharacteristic->addDescriptor(new BLE2902());
|
||||
|
||||
BLECharacteristic * pRxCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID_RX, BLECharacteristic::PROPERTY_WRITE);
|
||||
pRxCharacteristic->setAccessPermissions(ESP_GATT_PERM_WRITE_ENCRYPTED);
|
||||
pRxCharacteristic->setAccessPermissions(ESP_GATT_PERM_WRITE_ENC_MITM);
|
||||
pRxCharacteristic->setCallbacks(this);
|
||||
|
||||
pServer->getAdvertising()->addServiceUUID(SERVICE_UUID);
|
||||
@@ -71,7 +72,7 @@ void SerialBLEInterface::onAuthenticationComplete(esp_ble_auth_cmpl_t cmpl) {
|
||||
|
||||
//pServer->removePeerDevice(pServer->getConnId(), true);
|
||||
pServer->disconnect(pServer->getConnId());
|
||||
checkAdvRestart = true;
|
||||
adv_restart_time = millis() + ADVERT_RESTART_DELAY;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,7 +94,8 @@ void SerialBLEInterface::onMtuChanged(BLEServer* pServer, esp_ble_gatts_cb_param
|
||||
void SerialBLEInterface::onDisconnect(BLEServer* pServer) {
|
||||
BLE_DEBUG_PRINTLN("onDisconnect()");
|
||||
if (_isEnabled) {
|
||||
checkAdvRestart = true;
|
||||
adv_restart_time = millis() + ADVERT_RESTART_DELAY;
|
||||
|
||||
// loop() will detect this on next loop, and set deviceConnected to false
|
||||
}
|
||||
}
|
||||
@@ -132,7 +134,7 @@ void SerialBLEInterface::enable() {
|
||||
//pServer->getAdvertising()->setMaxInterval(1000);
|
||||
|
||||
pServer->getAdvertising()->start();
|
||||
checkAdvRestart = false;
|
||||
adv_restart_time = 0;
|
||||
}
|
||||
|
||||
void SerialBLEInterface::disable() {
|
||||
@@ -143,7 +145,7 @@ void SerialBLEInterface::disable() {
|
||||
pServer->getAdvertising()->stop();
|
||||
pService->stop();
|
||||
oldDeviceConnected = deviceConnected = false;
|
||||
checkAdvRestart = false;
|
||||
adv_restart_time = 0;
|
||||
}
|
||||
|
||||
size_t SerialBLEInterface::writeFrame(const uint8_t src[], size_t len) {
|
||||
@@ -181,7 +183,7 @@ size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) {
|
||||
pTxCharacteristic->setValue(send_queue[0].buf, send_queue[0].len);
|
||||
pTxCharacteristic->notify();
|
||||
|
||||
BLE_DEBUG_PRINTLN("writeBytes: sz=%d", (uint32_t)send_queue[0].len);
|
||||
BLE_DEBUG_PRINTLN("writeBytes: sz=%d, hdr=%d", (uint32_t)send_queue[0].len, (uint32_t) send_queue[0].buf[0]);
|
||||
|
||||
send_queue_len--;
|
||||
for (int i = 0; i < send_queue_len; i++) { // delete top item from queue
|
||||
@@ -193,6 +195,8 @@ size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) {
|
||||
size_t len = recv_queue[0].len; // take from top of queue
|
||||
memcpy(dest, recv_queue[0].buf, len);
|
||||
|
||||
BLE_DEBUG_PRINTLN("readBytes: sz=%d, hdr=%d", len, (uint32_t) dest[0]);
|
||||
|
||||
recv_queue_len--;
|
||||
for (int i = 0; i < recv_queue_len; i++) { // delete top item from queue
|
||||
recv_queue[i] = recv_queue[i + 1];
|
||||
@@ -207,29 +211,28 @@ size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) {
|
||||
clearBuffers();
|
||||
|
||||
BLE_DEBUG_PRINTLN("SerialBLEInterface -> disconnecting...");
|
||||
delay(500); // give the bluetooth stack the chance to get things ready
|
||||
|
||||
//pServer->getAdvertising()->setMinInterval(500);
|
||||
//pServer->getAdvertising()->setMaxInterval(1000);
|
||||
|
||||
checkAdvRestart = true;
|
||||
adv_restart_time = millis() + ADVERT_RESTART_DELAY;
|
||||
} else {
|
||||
BLE_DEBUG_PRINTLN("SerialBLEInterface -> stopping advertising");
|
||||
BLE_DEBUG_PRINTLN("SerialBLEInterface -> connecting...");
|
||||
// connecting
|
||||
// do stuff here on connecting
|
||||
pServer->getAdvertising()->stop();
|
||||
checkAdvRestart = false;
|
||||
adv_restart_time = 0;
|
||||
}
|
||||
oldDeviceConnected = deviceConnected;
|
||||
}
|
||||
|
||||
if (checkAdvRestart) {
|
||||
if (adv_restart_time && millis() >= adv_restart_time) {
|
||||
if (pServer->getConnectedCount() == 0) {
|
||||
BLE_DEBUG_PRINTLN("SerialBLEInterface -> re-starting advertising");
|
||||
pServer->getAdvertising()->start(); // re-Start advertising
|
||||
}
|
||||
checkAdvRestart = false;
|
||||
adv_restart_time = 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -12,10 +12,10 @@ class SerialBLEInterface : public BaseSerialInterface, BLESecurityCallbacks, BLE
|
||||
BLECharacteristic * pTxCharacteristic;
|
||||
bool deviceConnected;
|
||||
bool oldDeviceConnected;
|
||||
bool checkAdvRestart;
|
||||
bool _isEnabled;
|
||||
uint32_t _pin_code;
|
||||
unsigned long _last_write;
|
||||
unsigned long adv_restart_time;
|
||||
|
||||
struct Frame {
|
||||
uint8_t len;
|
||||
@@ -53,7 +53,7 @@ public:
|
||||
pService = NULL;
|
||||
deviceConnected = false;
|
||||
oldDeviceConnected = false;
|
||||
checkAdvRestart = false;
|
||||
adv_restart_time = 0;
|
||||
_isEnabled = false;
|
||||
_last_write = 0;
|
||||
send_queue_len = recv_queue_len = 0;
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
#include <Arduino.h>
|
||||
#include "RAK4631Board.h"
|
||||
|
||||
#include <bluefruit.h>
|
||||
#include <Wire.h>
|
||||
|
||||
static BLEDfu bledfu;
|
||||
|
||||
static void connect_callback(uint16_t conn_handle)
|
||||
{
|
||||
(void)conn_handle;
|
||||
MESH_DEBUG_PRINTLN("BLE client connected");
|
||||
}
|
||||
|
||||
static void disconnect_callback(uint16_t conn_handle, uint8_t reason)
|
||||
{
|
||||
(void)conn_handle;
|
||||
(void)reason;
|
||||
|
||||
MESH_DEBUG_PRINTLN("BLE client disconnected");
|
||||
}
|
||||
|
||||
void RAK4631Board::begin() {
|
||||
// for future use, sub-classes SHOULD call this from their begin()
|
||||
startup_reason = BD_STARTUP_NORMAL;
|
||||
|
||||
pinMode(PIN_VBAT_READ, INPUT);
|
||||
|
||||
#if defined(PIN_BOARD_SDA) && defined(PIN_BOARD_SCL)
|
||||
Wire.begin(PIN_BOARD_SDA, PIN_BOARD_SCL);
|
||||
#else
|
||||
Wire.begin();
|
||||
#endif
|
||||
|
||||
pinMode(SX126X_POWER_EN, OUTPUT);
|
||||
digitalWrite(SX126X_POWER_EN, HIGH);
|
||||
delay(10); // give sx1262 some time to power up
|
||||
}
|
||||
|
||||
bool RAK4631Board::startOTAUpdate() {
|
||||
// Config the peripheral connection with maximum bandwidth
|
||||
// more SRAM required by SoftDevice
|
||||
// Note: All config***() function must be called before begin()
|
||||
Bluefruit.configPrphBandwidth(BANDWIDTH_MAX);
|
||||
Bluefruit.configPrphConn(92, BLE_GAP_EVENT_LENGTH_MIN, 16, 16);
|
||||
|
||||
Bluefruit.begin(1, 0);
|
||||
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
|
||||
Bluefruit.setTxPower(4);
|
||||
// Set the BLE device name
|
||||
Bluefruit.setName("RAK4631_OTA");
|
||||
|
||||
Bluefruit.Periph.setConnectCallback(connect_callback);
|
||||
Bluefruit.Periph.setDisconnectCallback(disconnect_callback);
|
||||
|
||||
// To be consistent OTA DFU should be added first if it exists
|
||||
bledfu.begin();
|
||||
|
||||
// Set up and start advertising
|
||||
// Advertising packet
|
||||
Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
|
||||
Bluefruit.Advertising.addTxPower();
|
||||
Bluefruit.Advertising.addName();
|
||||
|
||||
/* Start Advertising
|
||||
- Enable auto advertising if disconnected
|
||||
- Interval: fast mode = 20 ms, slow mode = 152.5 ms
|
||||
- Timeout for fast mode is 30 seconds
|
||||
- Start(timeout) with timeout = 0 will advertise forever (until connected)
|
||||
|
||||
For recommended advertising interval
|
||||
https://developer.apple.com/library/content/qa/qa1931/_index.html
|
||||
*/
|
||||
Bluefruit.Advertising.restartOnDisconnect(true);
|
||||
Bluefruit.Advertising.setInterval(32, 244); // in unit of 0.625 ms
|
||||
Bluefruit.Advertising.setFastTimeout(30); // number of seconds in fast mode
|
||||
Bluefruit.Advertising.start(0); // 0 = Don't stop advertising after n seconds
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -3,8 +3,6 @@
|
||||
#include <MeshCore.h>
|
||||
#include <Arduino.h>
|
||||
|
||||
#if defined(NRF52_PLATFORM)
|
||||
|
||||
// LoRa radio module pins for RAK4631
|
||||
#define P_LORA_DIO_1 47
|
||||
#define P_LORA_NSS 42
|
||||
@@ -19,26 +17,18 @@
|
||||
#define SX126X_DIO3_TCXO_VOLTAGE 1.8
|
||||
|
||||
// built-ins
|
||||
#define PIN_VBAT_READ 1
|
||||
#define ADC_MULTIPLIER 6.17
|
||||
#define PIN_VBAT_READ 5
|
||||
#define ADC_MULTIPLIER (3 * 1.73 * 1.187 * 1000)
|
||||
|
||||
class RAK4631Board : public mesh::MainBoard {
|
||||
protected:
|
||||
uint8_t startup_reason;
|
||||
|
||||
public:
|
||||
void begin() {
|
||||
// for future use, sub-classes SHOULD call this from their begin()
|
||||
startup_reason = BD_STARTUP_NORMAL;
|
||||
|
||||
pinMode(SX126X_POWER_EN, OUTPUT);
|
||||
digitalWrite(SX126X_POWER_EN, HIGH);
|
||||
delay(10); // give sx1262 some time to power up
|
||||
}
|
||||
|
||||
void begin();
|
||||
uint8_t getStartupReason() const override { return startup_reason; }
|
||||
|
||||
#define BATTERY_SAMPLES 10
|
||||
#define BATTERY_SAMPLES 8
|
||||
|
||||
uint16_t getBattMilliVolts() override {
|
||||
analogReadResolution(12);
|
||||
@@ -59,6 +49,6 @@ public:
|
||||
void reboot() override {
|
||||
NVIC_SystemReset();
|
||||
}
|
||||
};
|
||||
|
||||
#endif
|
||||
bool startOTAUpdate() override;
|
||||
};
|
||||
@@ -0,0 +1,158 @@
|
||||
#include "SerialBLEInterface.h"
|
||||
|
||||
void SerialBLEInterface::begin(const char* device_name, uint32_t pin_code) {
|
||||
char charpin[20];
|
||||
sprintf(charpin, "%d", pin_code);
|
||||
|
||||
Bluefruit.configPrphBandwidth(BANDWIDTH_MAX);
|
||||
Bluefruit.configPrphConn(250, BLE_GAP_EVENT_LENGTH_MIN, 16, 16); // increase MTU
|
||||
Bluefruit.begin();
|
||||
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
|
||||
Bluefruit.setName(device_name);
|
||||
|
||||
Bluefruit.Security.setMITM(true);
|
||||
Bluefruit.Security.setPIN(charpin);
|
||||
|
||||
// To be consistent OTA DFU should be added first if it exists
|
||||
//bledfu.begin();
|
||||
}
|
||||
|
||||
void SerialBLEInterface::startAdv() {
|
||||
// Advertising packet
|
||||
Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
|
||||
Bluefruit.Advertising.addTxPower();
|
||||
|
||||
// Include the BLE UART (AKA 'NUS') 128-bit UUID
|
||||
Bluefruit.Advertising.addService(bleuart);
|
||||
|
||||
// Secondary Scan Response packet (optional)
|
||||
// Since there is no room for 'Name' in Advertising packet
|
||||
Bluefruit.ScanResponse.addName();
|
||||
|
||||
/* Start Advertising
|
||||
* - Enable auto advertising if disconnected
|
||||
* - Interval: fast mode = 20 ms, slow mode = 152.5 ms
|
||||
* - Timeout for fast mode is 30 seconds
|
||||
* - Start(timeout) with timeout = 0 will advertise forever (until connected)
|
||||
*
|
||||
* For recommended advertising interval
|
||||
* https://developer.apple.com/library/content/qa/qa1931/_index.html
|
||||
*/
|
||||
Bluefruit.Advertising.restartOnDisconnect(true);
|
||||
Bluefruit.Advertising.setInterval(32, 244); // in unit of 0.625 ms
|
||||
Bluefruit.Advertising.setFastTimeout(30); // number of seconds in fast mode
|
||||
Bluefruit.Advertising.start(0); // 0 = Don't stop advertising after n seconds
|
||||
}
|
||||
|
||||
// ---------- public methods
|
||||
|
||||
void SerialBLEInterface::enable() {
|
||||
if (_isEnabled) return;
|
||||
|
||||
_isEnabled = true;
|
||||
clearBuffers();
|
||||
|
||||
// Configure and start the BLE Uart service
|
||||
bleuart.setPermission(SECMODE_ENC_WITH_MITM, SECMODE_ENC_WITH_MITM);
|
||||
bleuart.begin();
|
||||
|
||||
// Start advertising
|
||||
startAdv();
|
||||
|
||||
checkAdvRestart = false;
|
||||
}
|
||||
|
||||
void SerialBLEInterface::disable() {
|
||||
_isEnabled = false;
|
||||
|
||||
BLE_DEBUG_PRINTLN("SerialBLEInterface::disable");
|
||||
|
||||
Bluefruit.Advertising.stop();
|
||||
|
||||
oldDeviceConnected = deviceConnected = false;
|
||||
checkAdvRestart = false;
|
||||
}
|
||||
|
||||
size_t SerialBLEInterface::writeFrame(const uint8_t src[], size_t len) {
|
||||
if (len > MAX_FRAME_SIZE) {
|
||||
BLE_DEBUG_PRINTLN("writeFrame(), frame too big, len=%d", len);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (deviceConnected && len > 0) {
|
||||
if (send_queue_len >= FRAME_QUEUE_SIZE) {
|
||||
BLE_DEBUG_PRINTLN("writeFrame(), send_queue is full!");
|
||||
return 0;
|
||||
}
|
||||
|
||||
send_queue[send_queue_len].len = len; // add to send queue
|
||||
memcpy(send_queue[send_queue_len].buf, src, len);
|
||||
send_queue_len++;
|
||||
|
||||
return len;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#define BLE_WRITE_MIN_INTERVAL 20
|
||||
|
||||
bool SerialBLEInterface::isWriteBusy() const {
|
||||
return millis() < _last_write + BLE_WRITE_MIN_INTERVAL; // still too soon to start another write?
|
||||
}
|
||||
|
||||
size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) {
|
||||
if (send_queue_len > 0 // first, check send queue
|
||||
&& millis() >= _last_write + BLE_WRITE_MIN_INTERVAL // space the writes apart
|
||||
) {
|
||||
_last_write = millis();
|
||||
bleuart.write(send_queue[0].buf, send_queue[0].len);
|
||||
BLE_DEBUG_PRINTLN("writeBytes: sz=%d, hdr=%d", (uint32_t)send_queue[0].len, (uint32_t) send_queue[0].buf[0]);
|
||||
|
||||
send_queue_len--;
|
||||
for (int i = 0; i < send_queue_len; i++) { // delete top item from queue
|
||||
send_queue[i] = send_queue[i + 1];
|
||||
}
|
||||
} else {
|
||||
int len = bleuart.available();
|
||||
if (len > 0) {
|
||||
deviceConnected = true; // should probably use the callback to monitor cx
|
||||
bleuart.readBytes(dest, len);
|
||||
BLE_DEBUG_PRINTLN("readBytes: sz=%d, hdr=%d", len, (uint32_t) dest[0]);
|
||||
return len;
|
||||
}
|
||||
}
|
||||
|
||||
if (Bluefruit.connected() == 0) deviceConnected = false;
|
||||
|
||||
if (deviceConnected != oldDeviceConnected) {
|
||||
if (!deviceConnected) { // disconnecting
|
||||
clearBuffers();
|
||||
|
||||
BLE_DEBUG_PRINTLN("SerialBLEInterface -> disconnecting...");
|
||||
delay(500); // give the bluetooth stack the chance to get things ready
|
||||
|
||||
checkAdvRestart = true;
|
||||
} else {
|
||||
BLE_DEBUG_PRINTLN("SerialBLEInterface -> stopping advertising");
|
||||
BLE_DEBUG_PRINTLN("SerialBLEInterface -> connecting...");
|
||||
// connecting
|
||||
// do stuff here on connecting
|
||||
Bluefruit.Advertising.stop();
|
||||
checkAdvRestart = false;
|
||||
}
|
||||
oldDeviceConnected = deviceConnected;
|
||||
}
|
||||
|
||||
if (checkAdvRestart) {
|
||||
if (Bluefruit.connected() == 0) {
|
||||
BLE_DEBUG_PRINTLN("SerialBLEInterface -> re-starting advertising");
|
||||
startAdv();
|
||||
}
|
||||
checkAdvRestart = false;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool SerialBLEInterface::isConnected() const {
|
||||
return deviceConnected; //pServer != NULL && pServer->getConnectedCount() > 0;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
#pragma once
|
||||
|
||||
#include "../BaseSerialInterface.h"
|
||||
#include <bluefruit.h>
|
||||
|
||||
class SerialBLEInterface : public BaseSerialInterface {
|
||||
BLEUart bleuart;
|
||||
bool deviceConnected;
|
||||
bool oldDeviceConnected;
|
||||
bool checkAdvRestart;
|
||||
bool _isEnabled;
|
||||
unsigned long _last_write;
|
||||
|
||||
struct Frame {
|
||||
uint8_t len;
|
||||
uint8_t buf[MAX_FRAME_SIZE];
|
||||
};
|
||||
|
||||
#define FRAME_QUEUE_SIZE 4
|
||||
int send_queue_len;
|
||||
Frame send_queue[FRAME_QUEUE_SIZE];
|
||||
|
||||
void clearBuffers() { send_queue_len = 0; }
|
||||
void startAdv();
|
||||
|
||||
public:
|
||||
SerialBLEInterface() {
|
||||
deviceConnected = false;
|
||||
oldDeviceConnected = false;
|
||||
checkAdvRestart = false;
|
||||
_isEnabled = false;
|
||||
_last_write = 0;
|
||||
send_queue_len = 0;
|
||||
}
|
||||
|
||||
void begin(const char* device_name, uint32_t pin_code);
|
||||
|
||||
// BaseSerialInterface methods
|
||||
void enable() override;
|
||||
void disable() override;
|
||||
bool isEnabled() const override { return _isEnabled; }
|
||||
|
||||
bool isConnected() const override;
|
||||
|
||||
bool isWriteBusy() const override;
|
||||
size_t writeFrame(const uint8_t src[], size_t len) override;
|
||||
size_t checkRecvFrame(uint8_t dest[]) override;
|
||||
};
|
||||
|
||||
#if BLE_DEBUG_LOGGING && ARDUINO
|
||||
#include <Arduino.h>
|
||||
#define BLE_DEBUG_PRINT(F, ...) Serial.printf("BLE: " F, ##__VA_ARGS__)
|
||||
#define BLE_DEBUG_PRINTLN(F, ...) Serial.printf("BLE: " F "\n", ##__VA_ARGS__)
|
||||
#else
|
||||
#define BLE_DEBUG_PRINT(...) {}
|
||||
#define BLE_DEBUG_PRINTLN(...) {}
|
||||
#endif
|
||||
@@ -0,0 +1,87 @@
|
||||
#include <Arduino.h>
|
||||
#include "T1000eBoard.h"
|
||||
#include <Wire.h>
|
||||
|
||||
#include <bluefruit.h>
|
||||
|
||||
void T1000eBoard::begin()
|
||||
{
|
||||
// for future use, sub-classes SHOULD call this from their begin()
|
||||
startup_reason = BD_STARTUP_NORMAL;
|
||||
btn_prev_state = HIGH;
|
||||
|
||||
#ifdef BUTTON_PIN
|
||||
pinMode(BATTERY_PIN, INPUT);
|
||||
pinMode(BUTTON_PIN, INPUT);
|
||||
pinMode(LED_PIN, OUTPUT);
|
||||
#endif
|
||||
|
||||
#if defined(PIN_BOARD_SDA) && defined(PIN_BOARD_SCL)
|
||||
Wire.begin(PIN_BOARD_SDA, PIN_BOARD_SCL);
|
||||
#else
|
||||
Wire.begin();
|
||||
#endif
|
||||
|
||||
delay(10); // give sx1262 some time to power up
|
||||
}
|
||||
|
||||
#if 0
|
||||
static BLEDfu bledfu;
|
||||
|
||||
static void connect_callback(uint16_t conn_handle)
|
||||
{
|
||||
(void)conn_handle;
|
||||
MESH_DEBUG_PRINTLN("BLE client connected");
|
||||
}
|
||||
|
||||
static void disconnect_callback(uint16_t conn_handle, uint8_t reason)
|
||||
{
|
||||
(void)conn_handle;
|
||||
(void)reason;
|
||||
|
||||
MESH_DEBUG_PRINTLN("BLE client disconnected");
|
||||
}
|
||||
|
||||
|
||||
bool TrackerT1000eBoard::startOTAUpdate() {
|
||||
// Config the peripheral connection with maximum bandwidth
|
||||
// more SRAM required by SoftDevice
|
||||
// Note: All config***() function must be called before begin()
|
||||
Bluefruit.configPrphBandwidth(BANDWIDTH_MAX);
|
||||
Bluefruit.configPrphConn(92, BLE_GAP_EVENT_LENGTH_MIN, 16, 16);
|
||||
|
||||
Bluefruit.begin(1, 0);
|
||||
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
|
||||
Bluefruit.setTxPower(4);
|
||||
// Set the BLE device name
|
||||
Bluefruit.setName("T1000E_OTA");
|
||||
|
||||
Bluefruit.Periph.setConnectCallback(connect_callback);
|
||||
Bluefruit.Periph.setDisconnectCallback(disconnect_callback);
|
||||
|
||||
// To be consistent OTA DFU should be added first if it exists
|
||||
bledfu.begin();
|
||||
|
||||
// Set up and start advertising
|
||||
// Advertising packet
|
||||
Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
|
||||
Bluefruit.Advertising.addTxPower();
|
||||
Bluefruit.Advertising.addName();
|
||||
|
||||
/* Start Advertising
|
||||
- Enable auto advertising if disconnected
|
||||
- Interval: fast mode = 20 ms, slow mode = 152.5 ms
|
||||
- Timeout for fast mode is 30 seconds
|
||||
- Start(timeout) with timeout = 0 will advertise forever (until connected)
|
||||
|
||||
For recommended advertising interval
|
||||
https://developer.apple.com/library/content/qa/qa1931/_index.html
|
||||
*/
|
||||
Bluefruit.Advertising.restartOnDisconnect(true);
|
||||
Bluefruit.Advertising.setInterval(32, 244); // in unit of 0.625 ms
|
||||
Bluefruit.Advertising.setFastTimeout(30); // number of seconds in fast mode
|
||||
Bluefruit.Advertising.start(0); // 0 = Don't stop advertising after n seconds
|
||||
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,91 @@
|
||||
#pragma once
|
||||
|
||||
#include <MeshCore.h>
|
||||
#include <Arduino.h>
|
||||
|
||||
#define HAS_T1000e_POWEROFF
|
||||
|
||||
// LoRa and SPI pins
|
||||
#define P_LORA_DIO_1 (32 + 1) // P1.1
|
||||
#define P_LORA_NSS (0 + 12) // P0.12
|
||||
#define P_LORA_RESET (32 + 10) // P1.10
|
||||
#define P_LORA_BUSY (0 + 7) // P0.7
|
||||
#define P_LORA_SCLK (0 + 11) // P0.11
|
||||
#define P_LORA_MISO (32 + 8) // P1.8
|
||||
#define P_LORA_MOSI (32 + 9) // P0.9
|
||||
|
||||
#define LR11X0_DIO_AS_RF_SWITCH true
|
||||
#define LR11X0_DIO3_TCXO_VOLTAGE 1.6
|
||||
|
||||
// built-ins
|
||||
//#define PIN_VBAT_READ 5
|
||||
//#define ADC_MULTIPLIER (3 * 1.73 * 1000)
|
||||
|
||||
class T1000eBoard : public mesh::MainBoard {
|
||||
protected:
|
||||
uint8_t startup_reason;
|
||||
uint8_t btn_prev_state;
|
||||
|
||||
public:
|
||||
void begin();
|
||||
|
||||
uint16_t getBattMilliVolts() override {
|
||||
#ifdef BATTERY_PIN
|
||||
analogReadResolution(12);
|
||||
float volts = (analogRead(BATTERY_PIN) * ADC_MULTIPLIER * AREF_VOLTAGE) / 4096;
|
||||
return volts * 1000;
|
||||
#else
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
uint8_t getStartupReason() const override { return startup_reason; }
|
||||
|
||||
const char* getManufacturerName() const override {
|
||||
return "Seeed Tracker T1000-e";
|
||||
}
|
||||
|
||||
int buttonStateChanged() {
|
||||
#ifdef BUTTON_PIN
|
||||
uint8_t v = digitalRead(BUTTON_PIN);
|
||||
if (v != btn_prev_state) {
|
||||
btn_prev_state = v;
|
||||
return (v == LOW) ? 1 : -1;
|
||||
}
|
||||
#endif
|
||||
return 0;
|
||||
}
|
||||
|
||||
void powerOff() {
|
||||
#ifdef HAS_GPS
|
||||
digitalWrite(GPS_VRTC_EN, LOW);
|
||||
digitalWrite(GPS_RESET, LOW);
|
||||
digitalWrite(GPS_SLEEP_INT, LOW);
|
||||
digitalWrite(GPS_RTC_INT, LOW);
|
||||
pinMode(GPS_RESETB, OUTPUT);
|
||||
digitalWrite(GPS_RESETB, LOW);
|
||||
#endif
|
||||
|
||||
#ifdef BUZZER_EN
|
||||
digitalWrite(BUZZER_EN, LOW);
|
||||
#endif
|
||||
|
||||
#ifdef PIN_3V3_EN
|
||||
digitalWrite(PIN_3V3_EN, LOW);
|
||||
#endif
|
||||
|
||||
#ifdef LED_PIN
|
||||
digitalWrite(LED_PIN, LOW);
|
||||
#endif
|
||||
#ifdef BUTTON_PIN
|
||||
nrf_gpio_cfg_sense_input(digitalPinToInterrupt(BUTTON_PIN), NRF_GPIO_PIN_NOPULL, NRF_GPIO_PIN_SENSE_HIGH);
|
||||
#endif
|
||||
sd_power_system_off();
|
||||
}
|
||||
|
||||
void reboot() override {
|
||||
NVIC_SystemReset();
|
||||
}
|
||||
|
||||
// bool startOTAUpdate() override;
|
||||
};
|
||||
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* variant.cpp
|
||||
* Copyright (C) 2023 Seeed K.K.
|
||||
* MIT License
|
||||
*/
|
||||
|
||||
#include "variant.h"
|
||||
#include "wiring_constants.h"
|
||||
#include "wiring_digital.h"
|
||||
|
||||
const uint32_t g_ADigitalPinMap[PINS_COUNT + 1] =
|
||||
{
|
||||
0, // P0.00
|
||||
1, // P0.01
|
||||
2, // P0.02, AIN0 BATTERY_PIN
|
||||
3, // P0.03
|
||||
4, // P0.04, SENSOR_EN
|
||||
5, // P0.05, EXT_PWR_DETEC
|
||||
6, // P0.06, PIN_BUTTON1
|
||||
7, // P0.07, LORA_BUSY
|
||||
8, // P0.08, GPS_VRTC_EN
|
||||
9, // P0.09
|
||||
10, // P0.10
|
||||
11, // P0.11, PIN_SPI_SCK
|
||||
12, // P0.12, PIN_SPI_NSS
|
||||
13, // P0.13, PIN_SERIAL1_TX
|
||||
14, // P0.14, PIN_SERIAL1_RX
|
||||
15, // P0.15, GPS_RTC_INT
|
||||
16, // P0.16, PIN_SERIAL2_TX
|
||||
17, // P0.17, PIN_SERIAL2_RX
|
||||
18, // P0.18
|
||||
19, // P0.19
|
||||
20, // P0.20
|
||||
21, // P0.21
|
||||
22, // P0.22
|
||||
23, // P0.23
|
||||
24, // P0.24, LED_GREEN
|
||||
25, // P0.25, BUZZER_PIN
|
||||
26, // P0.26, PIN_WIRE_SDA
|
||||
27, // P0.27, PIN_WIRE_SCL
|
||||
28, // P0.28
|
||||
29, // P0.29, AIN5, LUX_SENSOR
|
||||
30, // P0.30
|
||||
31, // P0.31, AIN7, TEMP_SENSOR
|
||||
32, // P1.00
|
||||
33, // P1.01, LORA_DIO_1
|
||||
34, // P1.02
|
||||
35, // P1.03, EXT_CHRG_DETECT
|
||||
36, // P1.04
|
||||
37, // P1.05, LR1110_EN
|
||||
38, // P1.06, 3V3_EN PWR TO SENSORS
|
||||
39, // P1.07, PIN_3V3_ACC_EN
|
||||
40, // P1.08, PIN_SPI_MISO
|
||||
41, // P1.09, PIN_SPI_MOSI
|
||||
42, // P1.10, LORA_RESET
|
||||
43, // P1.11, GPS_EN
|
||||
44, // P1.12, GPS_SLEEP_INT
|
||||
45, // P1.13
|
||||
46, // P1.14, GPS_RESETB
|
||||
47, // P1.15, PIN_GPS_RESET
|
||||
255, // NRFX_SPIM_PIN_NOT_USED
|
||||
};
|
||||
|
||||
void initVariant()
|
||||
{
|
||||
// All pins output HIGH by default.
|
||||
// https://github.com/Seeed-Studio/Adafruit_nRF52_Arduino/blob/fab7d30a997a1dfeef9d1d59bfb549adda73815a/cores/nRF5/wiring.c#L65-L69
|
||||
|
||||
pinMode(BATTERY_PIN, INPUT);
|
||||
pinMode(EXT_CHRG_DETECT, INPUT);
|
||||
pinMode(EXT_PWR_DETECT, INPUT);
|
||||
pinMode(GPS_RESETB, INPUT);
|
||||
pinMode(PIN_BUTTON1, INPUT);
|
||||
|
||||
pinMode(PIN_3V3_EN, OUTPUT);
|
||||
pinMode(PIN_3V3_ACC_EN, OUTPUT);
|
||||
pinMode(BUZZER_EN, OUTPUT);
|
||||
pinMode(SENSOR_EN, OUTPUT);
|
||||
pinMode(GPS_EN, OUTPUT);
|
||||
pinMode(GPS_RESET, OUTPUT);
|
||||
pinMode(GPS_VRTC_EN, OUTPUT);
|
||||
pinMode(GPS_SLEEP_INT, OUTPUT);
|
||||
pinMode(GPS_RTC_INT, OUTPUT);
|
||||
pinMode(LED_PIN, OUTPUT);
|
||||
|
||||
digitalWrite(PIN_3V3_EN, HIGH);
|
||||
digitalWrite(PIN_3V3_ACC_EN, LOW);
|
||||
digitalWrite(BUZZER_EN, LOW);
|
||||
digitalWrite(SENSOR_EN, LOW);
|
||||
digitalWrite(GPS_EN, LOW);
|
||||
digitalWrite(GPS_RESET, LOW);
|
||||
digitalWrite(GPS_VRTC_EN, HIGH);
|
||||
digitalWrite(GPS_SLEEP_INT, HIGH);
|
||||
digitalWrite(GPS_RTC_INT, LOW);
|
||||
digitalWrite(LED_PIN, LOW);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
/*
|
||||
* variant.h
|
||||
* Copyright (C) 2023 Seeed K.K.
|
||||
* MIT License
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "WVariant.h"
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Low frequency clock source
|
||||
|
||||
#define USE_LFXO // 32.768 kHz crystal oscillator
|
||||
#define VARIANT_MCK (64000000ul)
|
||||
// #define USE_LFRC // 32.768 kHz RC oscillator
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Power
|
||||
|
||||
#define NRF_APM // detect usb power
|
||||
#define PIN_3V3_EN (38) // P1.6 Power to Sensors
|
||||
|
||||
#define BATTERY_PIN (2) // P0.2/AIN0
|
||||
#define BATTERY_IMMUTABLE
|
||||
#define ADC_MULTIPLIER (2.0F)
|
||||
|
||||
#define EXT_CHRG_DETECT (35) // P1.3
|
||||
#define EXT_PWR_DETECT (5) // P0.5
|
||||
|
||||
#define ADC_RESOLUTION (14)
|
||||
#define BATTERY_SENSE_RES (12)
|
||||
|
||||
#define AREF_VOLTAGE (3.0)
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Number of pins
|
||||
|
||||
#define PINS_COUNT (48)
|
||||
#define NUM_DIGITAL_PINS (48)
|
||||
#define NUM_ANALOG_INPUTS (6)
|
||||
#define NUM_ANALOG_OUTPUTS (0)
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// UART pin definition
|
||||
|
||||
#define PIN_SERIAL1_RX (14) // P0.14
|
||||
#define PIN_SERIAL1_TX (13) // P0.13
|
||||
|
||||
#define PIN_SERIAL2_RX (17) // P0.17
|
||||
#define PIN_SERIAL2_TX (16) // P0.16
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// I2C pin definition
|
||||
|
||||
#define HAS_WIRE (1)
|
||||
#define WIRE_INTERFACES_COUNT (1)
|
||||
|
||||
#define PIN_WIRE_SDA (26) // P0.26
|
||||
#define PIN_WIRE_SCL (27) // P0.27
|
||||
#define I2C_NO_RESCAN
|
||||
#define HAS_QMA6100P
|
||||
#define QMA_6100P_INT_PIN (34) // P1.2
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// SPI pin definition
|
||||
|
||||
#define SPI_INTERFACES_COUNT (1)
|
||||
|
||||
#define PIN_SPI_MISO (40) // P1.8
|
||||
#define PIN_SPI_MOSI (41) // P1.9
|
||||
#define PIN_SPI_SCK (11) // P0.11
|
||||
#define PIN_SPI_NSS (12) // P0.12
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Builtin LEDs
|
||||
|
||||
#define LED_BUILTIN (-1)
|
||||
#define LED_BLUE (-1) // No blue led
|
||||
#define LED_GREEN (24) // P0.24
|
||||
#define LED_PIN LED_GREEN
|
||||
|
||||
#define LED_STATE_ON HIGH
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Builtin buttons
|
||||
|
||||
#define PIN_BUTTON1 (6) // P0.6
|
||||
#define BUTTON_PIN PIN_BUTTON1
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// LR1110
|
||||
|
||||
#define LORA_DIO_1 (33) // P1.1
|
||||
#define LORA_NSS (PIN_SPI_NSS) // P0.12
|
||||
#define LORA_RESET (42) // P1.10
|
||||
#define LORA_BUSY (7) // P0.7
|
||||
#define LORA_SCLK (PIN_SPI_SCK) // P0.11
|
||||
#define LORA_MISO (PIN_SPI_MISO) // P1.8
|
||||
#define LORA_MOSI (PIN_SPI_MOSI) // P0.9
|
||||
|
||||
#define LR11X0_DIO_AS_RF_SWITCH true
|
||||
#define LR11X0_DIO3_TCXO_VOLTAGE 1.6
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// GPS
|
||||
|
||||
#define HAS_GPS 1
|
||||
#define GPS_RX_PIN PIN_SERIAL1_RX
|
||||
#define GPS_TX_PIN PIN_SERIAL1_TX
|
||||
|
||||
#define GPS_EN (43) // P1.11
|
||||
#define GPS_RESET (47) // P1.15
|
||||
|
||||
#define GPS_VRTC_EN (8) // P0.8
|
||||
#define GPS_SLEEP_INT (44) // P1.12
|
||||
#define GPS_RTC_INT (15) // P0.15
|
||||
#define GPS_RESETB (46) // P1.14
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Temp+Lux Sensor
|
||||
|
||||
#define SENSOR_EN (4) // P0.4
|
||||
#define TEMP_SENSOR (31) // P0.31/AIN7
|
||||
#define LUX_SENSOR (29) // P0.29/AIN5
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Accelerometer (I2C addr : ??? )
|
||||
|
||||
#define PIN_3V3_ACC_EN (39) // P1.7
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Buzzer
|
||||
|
||||
#define BUZZER_EN (37) // P1.5
|
||||
#define BUZZER_PIN (25) // P0.25
|
||||
Reference in new issue
Block a user