From 26885ded29794cbe15f03e9055c03aabe4764094 Mon Sep 17 00:00:00 2001 From: Daniel Novak Date: Mon, 23 Feb 2026 21:40:17 +0100 Subject: [PATCH 001/381] Fix stack buffer overflow in MACThenDecrypt via block-alignment check Add validation that ciphertext length is a multiple of CIPHER_BLOCK_SIZE before calling decrypt(). The decrypt() function processes data in 16-byte AES blocks, rounding up non-aligned input, which can write up to 8 bytes past the caller's stack buffer. This can be triggered by crafted packets that pass the 2-byte HMAC check (1-in-65536 chance per attempt), enabling a persistent denial-of-service attack against repeaters and other nodes. --- src/Utils.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Utils.cpp b/src/Utils.cpp index 186c8720..573c4398 100644 --- a/src/Utils.cpp +++ b/src/Utils.cpp @@ -82,7 +82,9 @@ int Utils::MACThenDecrypt(const uint8_t* shared_secret, uint8_t* dest, const uin sha.finalizeHMAC(shared_secret, PUB_KEY_SIZE, hmac, CIPHER_MAC_SIZE); } if (memcmp(hmac, src, CIPHER_MAC_SIZE) == 0) { - return decrypt(shared_secret, dest, src + CIPHER_MAC_SIZE, src_len - CIPHER_MAC_SIZE); + int enc_len = src_len - CIPHER_MAC_SIZE; + if (enc_len % CIPHER_BLOCK_SIZE != 0) return 0; // reject non-block-aligned ciphertext + return decrypt(shared_secret, dest, src + CIPHER_MAC_SIZE, enc_len); } return 0; // invalid HMAC } From 5461450bfaab1a8e39288c84d6cf126d33052782 Mon Sep 17 00:00:00 2001 From: Daniel Novak Date: Thu, 26 Feb 2026 09:08:06 +0100 Subject: [PATCH 002/381] Move block-alignment check before HMAC computation Address review feedback: - Move the alignment check before the HMAC-SHA256 computation to skip expensive crypto on obviously malformed packets - Update MACThenDecrypt header comment to document block-alignment as a reason for returning zero --- src/Utils.cpp | 7 ++++--- src/Utils.h | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/Utils.cpp b/src/Utils.cpp index 573c4398..a70d4a70 100644 --- a/src/Utils.cpp +++ b/src/Utils.cpp @@ -74,16 +74,17 @@ int Utils::encryptThenMAC(const uint8_t* shared_secret, uint8_t* dest, const uin int Utils::MACThenDecrypt(const uint8_t* shared_secret, uint8_t* dest, const uint8_t* src, int src_len) { if (src_len <= CIPHER_MAC_SIZE) return 0; // invalid src bytes + int enc_len = src_len - CIPHER_MAC_SIZE; + if (enc_len % CIPHER_BLOCK_SIZE != 0) return 0; // reject non-block-aligned ciphertext + uint8_t hmac[CIPHER_MAC_SIZE]; { SHA256 sha; sha.resetHMAC(shared_secret, PUB_KEY_SIZE); - sha.update(src + CIPHER_MAC_SIZE, src_len - CIPHER_MAC_SIZE); + sha.update(src + CIPHER_MAC_SIZE, enc_len); sha.finalizeHMAC(shared_secret, PUB_KEY_SIZE, hmac, CIPHER_MAC_SIZE); } if (memcmp(hmac, src, CIPHER_MAC_SIZE) == 0) { - int enc_len = src_len - CIPHER_MAC_SIZE; - if (enc_len % CIPHER_BLOCK_SIZE != 0) return 0; // reject non-block-aligned ciphertext return decrypt(shared_secret, dest, src + CIPHER_MAC_SIZE, enc_len); } return 0; // invalid HMAC diff --git a/src/Utils.h b/src/Utils.h index 5736b874..9997fe3c 100644 --- a/src/Utils.h +++ b/src/Utils.h @@ -50,7 +50,7 @@ public: /** * \brief checks the MAC (in leading bytes of 'src'), then if valid, decrypts remaining bytes in src. - * \returns zero if MAC is invalid, otherwise the length of decrypted bytes in 'dest' + * \returns zero if MAC is invalid or ciphertext is not block-aligned, otherwise the length of decrypted bytes in 'dest' */ static int MACThenDecrypt(const uint8_t* shared_secret, uint8_t* dest, const uint8_t* src, int src_len); From 7c9a74cb069114ae3e9724f6277593be285f56c0 Mon Sep 17 00:00:00 2001 From: Robert Ekl Date: Tue, 17 Mar 2026 00:50:19 -0500 Subject: [PATCH 003/381] Fix T1000-E sensor power pin mapping --- variants/t1000-e/T1000eBoard.h | 4 ---- variants/t1000-e/t1000e_sensors.cpp | 4 ---- variants/t1000-e/variant.cpp | 4 +--- variants/t1000-e/variant.h | 3 +-- 4 files changed, 2 insertions(+), 13 deletions(-) diff --git a/variants/t1000-e/T1000eBoard.h b/variants/t1000-e/T1000eBoard.h index 49223607..546bd774 100644 --- a/variants/t1000-e/T1000eBoard.h +++ b/variants/t1000-e/T1000eBoard.h @@ -69,10 +69,6 @@ public: #ifdef PIN_3V3_ACC_EN digitalWrite(PIN_3V3_ACC_EN, LOW); #endif - #ifdef SENSOR_EN - digitalWrite(SENSOR_EN, LOW); - #endif - // set led on and wait for button release before poweroff #ifdef LED_PIN digitalWrite(LED_PIN, HIGH); diff --git a/variants/t1000-e/t1000e_sensors.cpp b/variants/t1000-e/t1000e_sensors.cpp index 85298d3a..cb4977fd 100644 --- a/variants/t1000-e/t1000e_sensors.cpp +++ b/variants/t1000-e/t1000e_sensors.cpp @@ -72,7 +72,6 @@ float t1000e_get_temperature(void) { unsigned int ntc_v, vcc_v; digitalWrite(PIN_3V3_EN, HIGH); - digitalWrite(SENSOR_EN, HIGH); analogReference(AR_INTERNAL_3_0); analogReadResolution(12); delay(10); @@ -80,7 +79,6 @@ float t1000e_get_temperature(void) { vcc_v = (rail_v > NTC_REF_VCC) ? NTC_REF_VCC : rail_v; ntc_v = (1000.0 * AREF_VOLTAGE * analogRead(TEMP_SENSOR)) / 4096; digitalWrite(PIN_3V3_EN, LOW); - digitalWrite(SENSOR_EN, LOW); return get_heater_temperature(vcc_v, ntc_v); } @@ -90,13 +88,11 @@ uint32_t t1000e_get_light(void) { unsigned int lux_v = 0; digitalWrite(PIN_3V3_EN, HIGH); - digitalWrite(SENSOR_EN, HIGH); analogReference(AR_INTERNAL_3_0); analogReadResolution(12); delay(10); lux_v = 1000 * analogRead(LUX_SENSOR) * AREF_VOLTAGE / 4096; lux = get_light_lv(lux_v); - digitalWrite(SENSOR_EN, LOW); digitalWrite(PIN_3V3_EN, LOW); return lux; diff --git a/variants/t1000-e/variant.cpp b/variants/t1000-e/variant.cpp index a598e3ca..5627e659 100644 --- a/variants/t1000-e/variant.cpp +++ b/variants/t1000-e/variant.cpp @@ -14,7 +14,7 @@ const uint32_t g_ADigitalPinMap[PINS_COUNT + 1] = 1, // P0.01 2, // P0.02, AIN0 BATTERY_PIN 3, // P0.03 - 4, // P0.04, SENSOR_EN + 4, // P0.04 5, // P0.05, EXT_PWR_DETEC 6, // P0.06, PIN_BUTTON1 7, // P0.07, LORA_BUSY @@ -77,7 +77,6 @@ void initVariant() 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); @@ -88,7 +87,6 @@ void initVariant() digitalWrite(PIN_3V3_EN, LOW); 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, LOW); diff --git a/variants/t1000-e/variant.h b/variants/t1000-e/variant.h index 458f12bc..81e028d6 100644 --- a/variants/t1000-e/variant.h +++ b/variants/t1000-e/variant.h @@ -120,7 +120,6 @@ //////////////////////////////////////////////////////////////////////////////// // Temp+Lux Sensor -#define SENSOR_EN (4) // P0.4 #define TEMP_SENSOR (31) // P0.31/AIN7 #define LUX_SENSOR (29) // P0.29/AIN5 @@ -133,4 +132,4 @@ // Buzzer #define BUZZER_EN (37) // P1.5 -#define BUZZER_PIN (25) // P0.25 \ No newline at end of file +#define BUZZER_PIN (25) // P0.25 From 0d3d5ed619e5b737fd05b8bc8150a381e72fedd4 Mon Sep 17 00:00:00 2001 From: Frieder Schrempf Date: Wed, 22 Apr 2026 19:56:21 +0200 Subject: [PATCH 004/381] Disable NRF52 undervoltage bootlock feature The NRF52 undervoltage bootlock feature implemented behind NRF52_POWER_MANAGEMENT was introduced in v1.12. It configures a fixed voltage level of 3.3V and prevents the software from booting if the battery voltage is below that level. This is problematic for various reasons. The most important one being that it breaks devices that use cell chemistries other than Li-Ion, such as LFP, LTO or SIB which have much lower minimum voltages. As a quick fix to prevent devices from failing, disable the feature until it has been decided how to handle this in the future and a proper implementation has been provided. Signed-off-by: Frieder Schrempf --- variants/gat562_30s_mesh_kit/platformio.ini | 1 - variants/gat562_mesh_evb_pro/platformio.ini | 1 - variants/gat562_mesh_tracker_pro/platformio.ini | 1 - variants/gat562_mesh_watch13/platformio.ini | 1 - variants/heltec_t096/platformio.ini | 1 - variants/heltec_t114/platformio.ini | 1 - variants/muziworks_r1_neo/platformio.ini | 1 - variants/rak3401/platformio.ini | 1 - variants/rak4631/platformio.ini | 1 - variants/sensecap_solar/platformio.ini | 1 - variants/xiao_nrf52/platformio.ini | 1 - 11 files changed, 11 deletions(-) diff --git a/variants/gat562_30s_mesh_kit/platformio.ini b/variants/gat562_30s_mesh_kit/platformio.ini index 1467f0fa..efc87e37 100644 --- a/variants/gat562_30s_mesh_kit/platformio.ini +++ b/variants/gat562_30s_mesh_kit/platformio.ini @@ -7,7 +7,6 @@ build_flags = ${nrf52_base.build_flags} -I variants/gat562_30s_mesh_kit -D RAK_4631 -D RAK_BOARD - -D NRF52_POWER_MANAGEMENT -D PIN_BOARD_SCL=14 -D PIN_BOARD_SDA=13 -D PIN_OLED_RESET=-1 diff --git a/variants/gat562_mesh_evb_pro/platformio.ini b/variants/gat562_mesh_evb_pro/platformio.ini index cede9c97..b14e89af 100644 --- a/variants/gat562_mesh_evb_pro/platformio.ini +++ b/variants/gat562_mesh_evb_pro/platformio.ini @@ -5,7 +5,6 @@ board_check = true build_flags = ${nrf52_base.build_flags} ${sensor_base.build_flags} -I variants/gat562_mesh_evb_pro - -D NRF52_POWER_MANAGEMENT -D PIN_BOARD_SCL=14 -D PIN_BOARD_SDA=13 -D RADIO_CLASS=CustomSX1262 diff --git a/variants/gat562_mesh_tracker_pro/platformio.ini b/variants/gat562_mesh_tracker_pro/platformio.ini index 8a947bce..1f7502d6 100644 --- a/variants/gat562_mesh_tracker_pro/platformio.ini +++ b/variants/gat562_mesh_tracker_pro/platformio.ini @@ -5,7 +5,6 @@ board_check = true build_flags = ${nrf52_base.build_flags} ${sensor_base.build_flags} -I variants/gat562_mesh_tracker_pro - -D NRF52_POWER_MANAGEMENT -D PIN_BOARD_SCL=14 -D PIN_BOARD_SDA=13 -D PIN_OLED_RESET=-1 diff --git a/variants/gat562_mesh_watch13/platformio.ini b/variants/gat562_mesh_watch13/platformio.ini index ef30829d..92bfe54c 100644 --- a/variants/gat562_mesh_watch13/platformio.ini +++ b/variants/gat562_mesh_watch13/platformio.ini @@ -8,7 +8,6 @@ build_flags = ${nrf52_base.build_flags} -I variants/gat562_mesh_watch13 -D RAK_4631 -D RAK_BOARD - -D NRF52_POWER_MANAGEMENT -D PIN_BOARD_SCL=14 -D PIN_BOARD_SDA=13 -D PIN_OLED_RESET=-1 diff --git a/variants/heltec_t096/platformio.ini b/variants/heltec_t096/platformio.ini index 19b05f3c..3d72c96b 100644 --- a/variants/heltec_t096/platformio.ini +++ b/variants/heltec_t096/platformio.ini @@ -9,7 +9,6 @@ build_flags = ${nrf52_base.build_flags} -I variants/heltec_t096 -I src/helpers/ui -D HELTEC_T096 - -D NRF52_POWER_MANAGEMENT -D P_LORA_DIO_1=21 -D P_LORA_NSS=5 -D P_LORA_RESET=16 diff --git a/variants/heltec_t114/platformio.ini b/variants/heltec_t114/platformio.ini index b985030f..a6ad2a38 100644 --- a/variants/heltec_t114/platformio.ini +++ b/variants/heltec_t114/platformio.ini @@ -12,7 +12,6 @@ build_flags = ${nrf52_base.build_flags} -I variants/heltec_t114 -I src/helpers/ui -D HELTEC_T114 - -D NRF52_POWER_MANAGEMENT -D P_LORA_DIO_1=20 -D P_LORA_NSS=24 -D P_LORA_RESET=25 diff --git a/variants/muziworks_r1_neo/platformio.ini b/variants/muziworks_r1_neo/platformio.ini index 39ef8728..645961ce 100644 --- a/variants/muziworks_r1_neo/platformio.ini +++ b/variants/muziworks_r1_neo/platformio.ini @@ -7,7 +7,6 @@ build_flags = ${nrf52_base.build_flags} -I variants/muziworks_r1_neo -I src/helpers/ui -D R1Neo - -D NRF52_POWER_MANAGEMENT -D RADIO_CLASS=CustomSX1262 -D WRAPPER_CLASS=CustomSX1262Wrapper -D LORA_TX_POWER=22 diff --git a/variants/rak3401/platformio.ini b/variants/rak3401/platformio.ini index 3d2d4a3e..949bf2c4 100644 --- a/variants/rak3401/platformio.ini +++ b/variants/rak3401/platformio.ini @@ -6,7 +6,6 @@ build_flags = ${nrf52_base.build_flags} ${sensor_base.build_flags} -I variants/rak3401 -D RAK_3401 - -D NRF52_POWER_MANAGEMENT -D RADIO_CLASS=CustomSX1262 -D WRAPPER_CLASS=CustomSX1262Wrapper -D LORA_TX_POWER=22 diff --git a/variants/rak4631/platformio.ini b/variants/rak4631/platformio.ini index ea7e49c3..37365354 100644 --- a/variants/rak4631/platformio.ini +++ b/variants/rak4631/platformio.ini @@ -7,7 +7,6 @@ build_flags = ${nrf52_base.build_flags} -I variants/rak4631 -D RAK_4631 -D RAK_BOARD - -D NRF52_POWER_MANAGEMENT -D PIN_BOARD_SCL=14 -D PIN_BOARD_SDA=13 -D PIN_GPS_TX=PIN_SERIAL1_RX diff --git a/variants/sensecap_solar/platformio.ini b/variants/sensecap_solar/platformio.ini index aabbcf00..24407180 100644 --- a/variants/sensecap_solar/platformio.ini +++ b/variants/sensecap_solar/platformio.ini @@ -10,7 +10,6 @@ build_flags = ${nrf52_base.build_flags} -I src/helpers/nrf52 -D NRF52_PLATFORM=1 -D USE_SX1262 - -D NRF52_POWER_MANAGEMENT -D RADIO_CLASS=CustomSX1262 -D WRAPPER_CLASS=CustomSX1262Wrapper -D P_LORA_TX_LED=11 diff --git a/variants/xiao_nrf52/platformio.ini b/variants/xiao_nrf52/platformio.ini index a0854336..931629c7 100644 --- a/variants/xiao_nrf52/platformio.ini +++ b/variants/xiao_nrf52/platformio.ini @@ -9,7 +9,6 @@ build_flags = ${nrf52_base.build_flags} -I variants/xiao_nrf52 -UENV_INCLUDE_GPS -D NRF52_PLATFORM - -D NRF52_POWER_MANAGEMENT -D XIAO_NRF52 -D USE_SX1262 -D RADIO_CLASS=CustomSX1262 From faed93543f26520a129a1e97e330ac984d07f947 Mon Sep 17 00:00:00 2001 From: Emily Kerst Date: Sun, 3 May 2026 22:40:01 +0200 Subject: [PATCH 005/381] Added USB Companion variant for LilyGo T-Echo Lite Co-authored-by: Natalie Kagelmacher Mentored-by: Natalie Kagelmacher Tested-by: Emily Kerst --- variants/lilygo_techo_lite/platformio.ini | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/variants/lilygo_techo_lite/platformio.ini b/variants/lilygo_techo_lite/platformio.ini index 4b5edf69..db629b36 100644 --- a/variants/lilygo_techo_lite/platformio.ini +++ b/variants/lilygo_techo_lite/platformio.ini @@ -190,3 +190,24 @@ lib_deps = extends = LilyGo_T-Echo-Lite build_src_filter = ${LilyGo_T-Echo-Lite.build_src_filter} +<../examples/kiss_modem/> +[env:LilyGo_T-Echo-Lite_companion_radio_usb] +extends = LilyGo_T-Echo-Lite +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 712704 +build_flags = + ${LilyGo_T-Echo-Lite.build_flags} + -I src/helpers/ui + -I examples/companion_radio/ui-new + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D OFFLINE_QUEUE_SIZE=256 + -D UI_RECENT_LIST_SIZE=9 + -D UI_SENSORS_PAGE=1 + -D AUTO_SHUTDOWN_MILLIVOLTS=3300 +; -D QSPIFLASH=1 +build_src_filter = ${LilyGo_T-Echo-Lite.build_src_filter} + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = + ${LilyGo_T-Echo-Lite.lib_deps} + densaugeo/base64 @ ~1.4.0 From 9c60a4a217183d9aec2acb5784d61b86a1f8a8f7 Mon Sep 17 00:00:00 2001 From: Emily Kerst Date: Fri, 15 May 2026 20:20:27 +0200 Subject: [PATCH 006/381] chore: reformat T-Echo Lite platformio.ini to keep normal and non-shell variants together --- variants/lilygo_techo_lite/platformio.ini | 52 +++++++++++------------ 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/variants/lilygo_techo_lite/platformio.ini b/variants/lilygo_techo_lite/platformio.ini index db629b36..ed46adcd 100644 --- a/variants/lilygo_techo_lite/platformio.ini +++ b/variants/lilygo_techo_lite/platformio.ini @@ -98,6 +98,32 @@ lib_deps = ${LilyGo_T-Echo-Lite.lib_deps} densaugeo/base64 @ ~1.4.0 +[env:LilyGo_T-Echo-Lite_kiss_modem] +extends = LilyGo_T-Echo-Lite +build_src_filter = ${LilyGo_T-Echo-Lite.build_src_filter} + +<../examples/kiss_modem/> +[env:LilyGo_T-Echo-Lite_companion_radio_usb] +extends = LilyGo_T-Echo-Lite +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 712704 +build_flags = + ${LilyGo_T-Echo-Lite.build_flags} + -I src/helpers/ui + -I examples/companion_radio/ui-new + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D OFFLINE_QUEUE_SIZE=256 + -D UI_RECENT_LIST_SIZE=9 + -D UI_SENSORS_PAGE=1 + -D AUTO_SHUTDOWN_MILLIVOLTS=3300 +; -D QSPIFLASH=1 +build_src_filter = ${LilyGo_T-Echo-Lite.build_src_filter} + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = + ${LilyGo_T-Echo-Lite.lib_deps} + densaugeo/base64 @ ~1.4.0 + [env:LilyGo_T-Echo-Lite_non_shell_companion_radio_ble] extends = LilyGo_T-Echo-Lite upload_protocol = nrfutil @@ -185,29 +211,3 @@ build_src_filter = ${nrf52_base.build_src_filter} lib_deps = ${LilyGo_T-Echo-Lite.lib_deps} densaugeo/base64 @ ~1.4.0 - -[env:LilyGo_T-Echo-Lite_kiss_modem] -extends = LilyGo_T-Echo-Lite -build_src_filter = ${LilyGo_T-Echo-Lite.build_src_filter} - +<../examples/kiss_modem/> -[env:LilyGo_T-Echo-Lite_companion_radio_usb] -extends = LilyGo_T-Echo-Lite -board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld -board_upload.maximum_size = 712704 -build_flags = - ${LilyGo_T-Echo-Lite.build_flags} - -I src/helpers/ui - -I examples/companion_radio/ui-new - -D MAX_CONTACTS=350 - -D MAX_GROUP_CHANNELS=40 - -D OFFLINE_QUEUE_SIZE=256 - -D UI_RECENT_LIST_SIZE=9 - -D UI_SENSORS_PAGE=1 - -D AUTO_SHUTDOWN_MILLIVOLTS=3300 -; -D QSPIFLASH=1 -build_src_filter = ${LilyGo_T-Echo-Lite.build_src_filter} - +<../examples/companion_radio/*.cpp> - +<../examples/companion_radio/ui-new/*.cpp> -lib_deps = - ${LilyGo_T-Echo-Lite.lib_deps} - densaugeo/base64 @ ~1.4.0 From a3a48badc8a93dcab7b764aec773e78c8e94b905 Mon Sep 17 00:00:00 2001 From: UltimateCodeWarrior Date: Mon, 22 Jun 2026 23:30:35 -0700 Subject: [PATCH 007/381] Fix blank OLED on T-Beam Supreme V3 (I2C bus + 0x3D address) The SH1106 OLED on the LilyGo T-Beam Supreme V3 never lights up because: 1. The primary I2C bus (Wire) that the OLED, BME280 and magnetometer share is never initialized. The PMU/RTC use Wire1 (via XPowersLib); nothing brings up Wire on PIN_BOARD_SDA/PIN_BOARD_SCL, so the display driver talks on the wrong default pins. 2. The OLED is at I2C address 0x3D on this board (0x3C is taken by the QMC6310 magnetometer), but SH1106Display::begin() only tried 0x3C. Initialize Wire for TBEAM_SUPREME_SX1262, and have SH1106Display::begin() prefer 0x3D (only ever used by the OLED) before falling back to 0x3C. Backwards-compatible for boards with the OLED at 0x3C. Closes #2609 --- src/helpers/esp32/TBeamBoard.cpp | 10 ++++++++++ src/helpers/ui/SH1106Display.cpp | 12 +++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/helpers/esp32/TBeamBoard.cpp b/src/helpers/esp32/TBeamBoard.cpp index 5f708d71..d9f6e022 100644 --- a/src/helpers/esp32/TBeamBoard.cpp +++ b/src/helpers/esp32/TBeamBoard.cpp @@ -16,6 +16,16 @@ void TBeamBoard::begin() { ESP32Board::begin(); +#ifdef TBEAM_SUPREME_SX1262 + // On the T-Beam S3 Supreme the PMU + RTC sit on Wire1 (GPIO 42/41, brought + // up by XPowersLib), while the SH1106 OLED and the BME280/QMC6310 sensors + // sit on the primary bus, Wire (GPIO PIN_BOARD_SDA/PIN_BOARD_SCL). Nothing + // else initialises Wire on this board, so the display driver would + // otherwise talk on the wrong (default) pins and display.begin() fails, + // leaving the screen blank. Bring the OLED bus up here. + Wire.begin(PIN_BOARD_SDA, PIN_BOARD_SCL); +#endif + power_init(); //Configure user button diff --git a/src/helpers/ui/SH1106Display.cpp b/src/helpers/ui/SH1106Display.cpp index f383bb00..86c6089b 100644 --- a/src/helpers/ui/SH1106Display.cpp +++ b/src/helpers/ui/SH1106Display.cpp @@ -11,7 +11,17 @@ bool SH1106Display::i2c_probe(TwoWire &wire, uint8_t addr) bool SH1106Display::begin() { - return display.begin(DISPLAY_ADDRESS, true) && i2c_probe(Wire, DISPLAY_ADDRESS); + // Address selection: on some board revisions (notably the LilyGo T-Beam + // Supreme V3) the OLED lives at 0x3D because 0x3C is occupied by a + // magnetometer (QMC6310N). 0x3D is only ever used by the OLED, so prefer it + // when present, otherwise fall back to the standard 0x3C (DISPLAY_ADDRESS). + uint8_t addr = 0; + if (i2c_probe(Wire, 0x3D)) { + addr = 0x3D; + } else if (i2c_probe(Wire, DISPLAY_ADDRESS)) { + addr = DISPLAY_ADDRESS; + } + return addr && display.begin(addr, true); } void SH1106Display::turnOn() From 37bd27afa9395fe031dfdab20c1f8f356264ebee Mon Sep 17 00:00:00 2001 From: Nick Dunklee Date: Tue, 23 Jun 2026 11:28:55 -0600 Subject: [PATCH 008/381] feat: use RAK hardware crypto on advert processing While working on some sensor code implementations, I ran into some hard crashes that root-caused to the 4KB loop task stack being exhausted. Looking for various optimization schemes resulted in this relatively low-lift fix. RAK3401 and RAK4631 both support hardware crypto. Rather than loading in one of the two software crypto libs, we can just use the onboard hardware. This is faster, should consume less power, and in testing used a scant up to 700 bytes in the run loop vs 2.5-3KB per advert. This change **only** affects advert verification processing, which currently consumes a significant chunk of the 4KB run loop. I figured such a change should likely be implemented in phases. After soaking, this hardware crypto verification process could be implemented across the entire MeshCore cryptographic function on RAK nodes. Also possible other nodes have available hardware crypto, however, I have not checked, so future improvements may also exist there. Tested on: - RAK3401 RAK 1W - RAK4631 19001 --- src/Identity.cpp | 20 +++++++++++++++++++- variants/rak3401/platformio.ini | 1 + variants/rak4631/platformio.ini | 1 + 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/Identity.cpp b/src/Identity.cpp index ea546274..2ab1cefa 100644 --- a/src/Identity.cpp +++ b/src/Identity.cpp @@ -4,6 +4,11 @@ #include #include +#ifdef USE_CC310_ED25519 +#include +#include "nrf_cc310/include/crys_ec_edw_api.h" +#endif + namespace mesh { Identity::Identity() { @@ -15,7 +20,20 @@ Identity::Identity(const char* pub_hex) { } bool Identity::verify(const uint8_t* sig, const uint8_t* message, int msg_len) const { -#if 0 +#ifdef USE_CC310_ED25519 + // nRF52840 CryptoCell CC310 hardware Ed25519 verification. The software + // implementations need ~3KB of stack (which can overflow the Adafruit core's + // 4KB loop task stack from the advert receive path); the hardware path + // needs much less, around 600-700bytes. The CC310 workspace is static, faster, + // should save power at scale as well. + static CRYS_ECEDW_TempBuff_t cc310_tmp; + nRFCrypto.begin(); + CRYSError_t rc = CRYS_ECEDW_Verify((uint8_t*)sig, CRYS_ECEDW_SIGNATURE_BYTES, + (uint8_t*)pub_key, CRYS_ECEDW_MOD_SIZE_IN_BYTES, + (uint8_t*)message, (size_t)msg_len, &cc310_tmp); + nRFCrypto.end(); + return rc == CRYS_OK; +#elif 0 // NOTE: memory corruption bug was found in this function!! return ed25519_verify(sig, message, msg_len, pub_key); #else diff --git a/variants/rak3401/platformio.ini b/variants/rak3401/platformio.ini index 20a8a548..9537fc7f 100644 --- a/variants/rak3401/platformio.ini +++ b/variants/rak3401/platformio.ini @@ -13,6 +13,7 @@ build_flags = ${nrf52_base.build_flags} -D SX126X_CURRENT_LIMIT=140 -D SX126X_RX_BOOSTED_GAIN=1 -D SX126X_REGISTER_PATCH=1 ; Patch register 0x8B5 for improved RX with SKY66122 FEM + -D USE_CC310_ED25519=1 build_src_filter = ${nrf52_base.build_src_filter} +<../variants/rak3401> + diff --git a/variants/rak4631/platformio.ini b/variants/rak4631/platformio.ini index 2bbba314..f6b634ad 100644 --- a/variants/rak4631/platformio.ini +++ b/variants/rak4631/platformio.ini @@ -22,6 +22,7 @@ build_flags = ${nrf52_base.build_flags} -D LORA_TX_POWER=22 -D SX126X_CURRENT_LIMIT=140 -D SX126X_RX_BOOSTED_GAIN=1 + -D USE_CC310_ED25519=1 -D ENV_INCLUDE_RAK12035=1 -UENV_INCLUDE_BME680 -D ENV_INCLUDE_BME680_BSEC=1 From ca586ced69ed9ff2ded3a8ee7842c461efa53057 Mon Sep 17 00:00:00 2001 From: Nick Dunklee Date: Wed, 24 Jun 2026 15:58:09 -0600 Subject: [PATCH 009/381] Added Heltec t096 and seeed t1000-e Tested Heltec t096 and Seeed t1000-e, both support this hardware feature. --- variants/heltec_t096/platformio.ini | 1 + variants/t1000-e/platformio.ini | 1 + 2 files changed, 2 insertions(+) diff --git a/variants/heltec_t096/platformio.ini b/variants/heltec_t096/platformio.ini index e820bf58..4da11c0c 100644 --- a/variants/heltec_t096/platformio.ini +++ b/variants/heltec_t096/platformio.ini @@ -29,6 +29,7 @@ build_flags = ${nrf52_base.build_flags} -D SX126X_DIO3_TCXO_VOLTAGE=1.8 -D SX126X_CURRENT_LIMIT=140 -D SX126X_RX_BOOSTED_GAIN=1 + -D USE_CC310_ED25519=1 -D PIN_VEXT_EN=26 ; Vext is connected to VDD which is also connected to TFT & GPS -D PIN_VEXT_EN_ACTIVE=HIGH -D PIN_GPS_RX=25 diff --git a/variants/t1000-e/platformio.ini b/variants/t1000-e/platformio.ini index 43a3d93f..9218c578 100644 --- a/variants/t1000-e/platformio.ini +++ b/variants/t1000-e/platformio.ini @@ -18,6 +18,7 @@ build_flags = ${nrf52_base.build_flags} -D LORA_TX_POWER=22 -D RF_SWITCH_TABLE -D RX_BOOSTED_GAIN=true + -D USE_CC310_ED25519=1 -D P_LORA_BUSY=7 ; P0.7 -D P_LORA_SCLK=11 ; P0.11 -D P_LORA_NSS=12 ; P0.12 From cff3b4c6e757eb5c05e115c9e1fefccc6503f156 Mon Sep 17 00:00:00 2001 From: Jody Bentley Date: Wed, 24 Jun 2026 19:43:55 -0400 Subject: [PATCH 010/381] GPS: poll up to 5s for cold-start detection instead of a single 1s check initBasicGPS() waited a fixed 1 second and then decided the GPS was present only if NMEA data had already arrived. Cold-start GPS modules often need 2-5 seconds before they emit their first sentence, so on a cold boot detection frequently failed. A failed detection sets gps_detected = false, which hides all GPS CLI settings and disables GPS time sync until the next reboot - so the GPS appears permanently dead even though the hardware is fine. Poll for up to ~5 seconds (in 250ms steps) and return as soon as any data appears. Fast modules are detected almost immediately and add no boot delay; slow cold-start modules now get enough time. The ENV_SKIP_GPS_DETECT bypass is unchanged. Fixes #2258. --- src/helpers/sensors/EnvironmentSensorManager.cpp | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/helpers/sensors/EnvironmentSensorManager.cpp b/src/helpers/sensors/EnvironmentSensorManager.cpp index 73842d9e..b26fc038 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.cpp +++ b/src/helpers/sensors/EnvironmentSensorManager.cpp @@ -748,14 +748,18 @@ void EnvironmentSensorManager::initBasicGPS() { MESH_DEBUG_PRINTLN("No GPS wake/reset pin found for this board. Continuing on..."); #endif - // Give GPS a moment to power up and send data - delay(1000); - - // We'll consider GPS detected if we see any data on Serial1 + // Give the GPS time to power up and emit its first NMEA sentence. Cold-start + // modules can take several seconds, so poll for up to ~5s instead of checking + // once after a fixed 1s delay -- returning as soon as any data appears, so + // fast modules add no boot delay (issue #2258). #ifdef ENV_SKIP_GPS_DETECT gps_detected = true; #else - gps_detected = (Serial1.available() > 0); + gps_detected = false; + for (int i = 0; i < 20 && !gps_detected; i++) { + delay(250); + gps_detected = (Serial1.available() > 0); + } #endif if (gps_detected) { From d273d8181b6995e447aa1de39a593942fd83fc83 Mon Sep 17 00:00:00 2001 From: Jody Bentley Date: Mon, 29 Jun 2026 14:49:11 -0400 Subject: [PATCH 011/381] thinknode_m6: don't drive GPS REINIT pin (fixes GPS never detected) The M6's L76K GPS streams NMEA at 9600 baud on its own, but the firmware reported no GPS. Root cause: pin 29 (PIN_GPS_RESET / the module's REINIT line) was driven HIGH, which holds the L76K silent so it never emits any sentences and detection fails. variant.cpp drove pin 29 HIGH at boot, and because PIN_GPS_RESET was defined, MicroNMEALocationProvider also drove it HIGH in begin(). Bench testing on a sealed M6 (passive NMEA capture, no logic analyzer) confirmed: pin 29 driven HIGH = 0 bytes; pin 29 floating = full NMEA stream. Define GPS_RESET (-1) so the location provider never touches pin 29, and stop driving it in initVariant. This matches the Meshtastic M6 variant, which leaves the same pin as a floating input. --- variants/thinknode_m6/variant.cpp | 6 ++++-- variants/thinknode_m6/variant.h | 7 ++++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/variants/thinknode_m6/variant.cpp b/variants/thinknode_m6/variant.cpp index c88f387d..79930e2d 100644 --- a/variants/thinknode_m6/variant.cpp +++ b/variants/thinknode_m6/variant.cpp @@ -30,6 +30,8 @@ void initVariant() { digitalWrite(PIN_GPS_STANDBY, HIGH); pinMode(PIN_GPS_EN, OUTPUT); digitalWrite(PIN_GPS_EN, HIGH); - pinMode(PIN_GPS_RESET, OUTPUT); - digitalWrite(PIN_GPS_RESET, HIGH); + // PIN_GPS_RESET (pin 29 / REINIT) is intentionally left floating (input). + // Driving it HIGH holds the L76K silent, so it never streams NMEA and the + // firmware reports "no GPS". Letting it float lets the module run, matching + // the Meshtastic M6 variant. See GPS_RESET (-1) in variant.h. } diff --git a/variants/thinknode_m6/variant.h b/variants/thinknode_m6/variant.h index 70fd6506..0a4025f3 100644 --- a/variants/thinknode_m6/variant.h +++ b/variants/thinknode_m6/variant.h @@ -102,7 +102,12 @@ #define PIN_GPS_RX (2) #define PIN_GPS_TX (3) #define PIN_GPS_EN (6) // EN -#define PIN_GPS_RESET (29) +#define PIN_GPS_RESET (29) // REINIT - must FLOAT; driving it (esp. HIGH) silences the L76K +// The M6's L76K streams NMEA on its own and must not have its REINIT pin driven. +// Tell the location provider there is no reset pin so it never touches pin 29 +// (driving it HIGH holds the module silent). Matches Meshtastic, which leaves +// this pin as an input. See variant.cpp (pin 29 is intentionally not configured). +#define GPS_RESET (-1) #define PIN_GPS_STANDBY (30) // STANDBY #define PIN_GPS_PPS (31) #define GPS_BAUD_RATE 9600 From 86d33ec100a384a4f2b4a22264f74cd3b5966e7e Mon Sep 17 00:00:00 2001 From: me Date: Sun, 7 Jun 2026 18:11:23 -0700 Subject: [PATCH 012/381] fix(techo-lite): remove duplicate EXTERNAL_FLASH_DEVICES definition variant.h defines EXTERNAL_FLASH_DEVICES twice: - First (correct): ZD25WQ32CEIGR (32Mbit = 4MB, matches actual hardware) - Second (incorrect): MX25R1635F (16Mbit = 2MB, T-Echo non-Lite chip) Due to C preprocessor behavior, the second definition silently overrides the first, causing firmware to initialize the wrong flash chip. This can result in LittleFS operating incorrectly on T-Echo Lite hardware. Remove the erroneous second definition. Also fix missing newline at end of file. --- variants/lilygo_techo_lite/variant.h | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/variants/lilygo_techo_lite/variant.h b/variants/lilygo_techo_lite/variant.h index 702ab334..628ffe19 100644 --- a/variants/lilygo_techo_lite/variant.h +++ b/variants/lilygo_techo_lite/variant.h @@ -95,9 +95,6 @@ #define PIN_BUTTON2 _PINNUM(0, 18) #define BUTTON_PIN2 PIN_BUTTON2 -#define EXTERNAL_FLASH_DEVICES MX25R1635F -#define EXTERNAL_FLASH_USE_QSPI - //////////////////////////////////////////////////////////////////////////////// // Lora @@ -156,4 +153,4 @@ extern const int SCK; #define PIN_GPS_RX _PINNUM(1, 10) // GPS UART RX ← MCU TX #define GPS_EN _PINNUM(1, 11) // GPS RT9080 power enable #define PIN_GPS_STANDBY _PINNUM(1, 13) // GPS wake-up -#define PIN_GPS_PPS _PINNUM(1, 15) // GPS 1PPS \ No newline at end of file +#define PIN_GPS_PPS _PINNUM(1, 15) // GPS 1PPS From b6c768aa98721e95bcfa9a684c70960b9ebaca83 Mon Sep 17 00:00:00 2001 From: me Date: Thu, 2 Jul 2026 08:43:06 -0700 Subject: [PATCH 013/381] fix(techo-lite): remove unused EXTERNAL_FLASH_DEVICES definition entirely MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Per review feedback from @liamcottle and @entr0p1, EXTERNAL_FLASH_DEVICES is not used by MeshCore firmware — CustomLFS determines the flash chip via JEDEC ID at runtime instead. Removing the definition entirely rather than keeping the (now-confirmed-unnecessary) correct value. Also removes EXTERNAL_FLASH_USE_QSPI, which was paired with the same define. --- variants/lilygo_techo_lite/variant.h | 3 --- 1 file changed, 3 deletions(-) diff --git a/variants/lilygo_techo_lite/variant.h b/variants/lilygo_techo_lite/variant.h index 628ffe19..673e8fc7 100644 --- a/variants/lilygo_techo_lite/variant.h +++ b/variants/lilygo_techo_lite/variant.h @@ -70,9 +70,6 @@ #define PIN_QSPI_IO2 _PINNUM(1, 9) #define PIN_QSPI_IO3 _PINNUM(0, 26) -#define EXTERNAL_FLASH_DEVICES ZD25WQ32CEIGR -#define EXTERNAL_FLASH_USE_QSPI - //////////////////////////////////////////////////////////////////////////////// // Builtin LEDs From 5efbc3d29c403d3ccef3d5516db128f1f8eac13f Mon Sep 17 00:00:00 2001 From: Nick Dunklee Date: Tue, 14 Jul 2026 08:35:27 -0600 Subject: [PATCH 014/381] feat: add more crypto After soaking for a bit on the adverts without issue on multiple nodes, I added more hardware crypto. Supported nodes is unchanged in this PR addition, but if others can verify, they can easily be added. Some info on the CC310: https://docs.nordicsemi.com/r/bundle/ps_nrf9151/page/cryptocell.html **Added:** - AES-128 packet encryption/decryption now use hardware crypto - HMAC-SHA-256 authentication now uses hardware crypto - ACK hash computation and channel ID derivation now use hardware crypto - RNG (random number generator) now uses hardware crypto rather than radio noise + weak software RNG (which can have issues if there's no surrounding radio noise.) NIST SP 800-90B certified. - Runs hardware self-tests on startup - Runs continuous health tests during operation - Uses thermal noise/shot noise for randomness **Unchanged:** - calcSharedSecret remains software - it would be a split hw/sw solution and added complexity for likely not a lot of gains. This only happens when establishing a new contact, so not too frequent to be worth it. - ed25519_create_keypair remains software. This is only called when a node is first initialized. It does use the hardware RNG change, however, so better randomization. Tested on (so far): - Heltec t096 Build test on: - Heltec t096 companion ble - t1000e companion ble - RAK 4631 repeater - RAK 3401 companion BLE - Heltec v3 companion wifi --- src/Utils.cpp | 98 ++++++++++++++++++++++++- src/helpers/radiolib/RadioLibWrappers.h | 11 +++ 2 files changed, 108 insertions(+), 1 deletion(-) diff --git a/src/Utils.cpp b/src/Utils.cpp index 186c8720..9cd44ce2 100644 --- a/src/Utils.cpp +++ b/src/Utils.cpp @@ -2,6 +2,13 @@ #include #include +#ifdef USE_CC310_ED25519 +#include +#include "nrf_cc310/include/crys_hash.h" +#include "nrf_cc310/include/crys_hmac.h" +#include "nrf_cc310/include/ssi_aes.h" +#endif + #ifdef ARDUINO #include #endif @@ -15,19 +22,58 @@ uint32_t RNG::nextInt(uint32_t _min, uint32_t _max) { } void Utils::sha256(uint8_t *hash, size_t hash_len, const uint8_t* msg, int msg_len) { +#ifdef USE_CC310_ED25519 + static CRYS_HASH_Result_t result; + nRFCrypto.begin(); + CRYS_HASH(CRYS_HASH_SHA256_mode, (uint8_t*)msg, (size_t)msg_len, result); + nRFCrypto.end(); + memcpy(hash, result, hash_len); +#else SHA256 sha; sha.update(msg, msg_len); sha.finalize(hash, hash_len); +#endif } void Utils::sha256(uint8_t *hash, size_t hash_len, const uint8_t* frag1, int frag1_len, const uint8_t* frag2, int frag2_len) { +#ifdef USE_CC310_ED25519 + static CRYS_HASHUserContext_t ctx; + static CRYS_HASH_Result_t result; + nRFCrypto.begin(); + CRYS_HASH_Init(&ctx, CRYS_HASH_SHA256_mode); + CRYS_HASH_Update(&ctx, (uint8_t*)frag1, (size_t)frag1_len); + CRYS_HASH_Update(&ctx, (uint8_t*)frag2, (size_t)frag2_len); + CRYS_HASH_Finish(&ctx, result); + nRFCrypto.end(); + memcpy(hash, result, hash_len); +#else SHA256 sha; sha.update(frag1, frag1_len); sha.update(frag2, frag2_len); sha.finalize(hash, hash_len); +#endif } int Utils::decrypt(const uint8_t* shared_secret, uint8_t* dest, const uint8_t* src, int src_len) { +#ifdef USE_CC310_ED25519 + static SaSiAesUserContext_t ctx; + SaSiAesUserKeyData_t keyData = { (uint8_t*)shared_secret, CIPHER_KEY_SIZE }; + uint8_t* dp = dest; + const uint8_t* sp = src; + size_t dummy_out = 0; + + nRFCrypto.begin(); + SaSi_AesInit(&ctx, SASI_AES_DECRYPT, SASI_AES_MODE_ECB, SASI_AES_PADDING_NONE); + SaSi_AesSetKey(&ctx, SASI_AES_USER_KEY, &keyData, sizeof(keyData)); + while (sp - src < src_len) { + SaSi_AesBlock(&ctx, (uint8_t*)sp, 16, dp); + dp += 16; sp += 16; + } + SaSi_AesFinish(&ctx, 0, NULL, 0, NULL, &dummy_out); + SaSi_AesFree(&ctx); + nRFCrypto.end(); + return sp - src; +#else AES128 aes; uint8_t* dp = dest; const uint8_t* sp = src; @@ -39,9 +85,34 @@ int Utils::decrypt(const uint8_t* shared_secret, uint8_t* dest, const uint8_t* s } return sp - src; // will always be multiple of 16 +#endif } int Utils::encrypt(const uint8_t* shared_secret, uint8_t* dest, const uint8_t* src, int src_len) { +#ifdef USE_CC310_ED25519 + static SaSiAesUserContext_t ctx; + SaSiAesUserKeyData_t keyData = { (uint8_t*)shared_secret, CIPHER_KEY_SIZE }; + uint8_t* dp = dest; + size_t dummy_out = 0; + + nRFCrypto.begin(); + SaSi_AesInit(&ctx, SASI_AES_ENCRYPT, SASI_AES_MODE_ECB, SASI_AES_PADDING_NONE); + SaSi_AesSetKey(&ctx, SASI_AES_USER_KEY, &keyData, sizeof(keyData)); + while (src_len >= 16) { + SaSi_AesBlock(&ctx, (uint8_t*)src, 16, dp); + dp += 16; src += 16; src_len -= 16; + } + if (src_len > 0) { // remaining partial block — zero-pad to 16 bytes + uint8_t tmp[16] = {}; + memcpy(tmp, src, src_len); + SaSi_AesBlock(&ctx, tmp, 16, dp); + dp += 16; + } + SaSi_AesFinish(&ctx, 0, NULL, 0, NULL, &dummy_out); + SaSi_AesFree(&ctx); + nRFCrypto.end(); + return dp - dest; +#else AES128 aes; uint8_t* dp = dest; @@ -58,15 +129,27 @@ int Utils::encrypt(const uint8_t* shared_secret, uint8_t* dest, const uint8_t* s dp += 16; } return dp - dest; // will always be multiple of 16 +#endif } int Utils::encryptThenMAC(const uint8_t* shared_secret, uint8_t* dest, const uint8_t* src, int src_len) { int enc_len = encrypt(shared_secret, dest + CIPHER_MAC_SIZE, src, src_len); +#ifdef USE_CC310_ED25519 + static CRYS_HMACUserContext_t hmac_ctx; + static CRYS_HASH_Result_t hmac_result; + nRFCrypto.begin(); + CRYS_HMAC_Init(&hmac_ctx, CRYS_HASH_SHA256_mode, (uint8_t*)shared_secret, PUB_KEY_SIZE); + CRYS_HMAC_Update(&hmac_ctx, dest + CIPHER_MAC_SIZE, enc_len); + CRYS_HMAC_Finish(&hmac_ctx, hmac_result); + nRFCrypto.end(); + memcpy(dest, hmac_result, CIPHER_MAC_SIZE); +#else SHA256 sha; sha.resetHMAC(shared_secret, PUB_KEY_SIZE); sha.update(dest + CIPHER_MAC_SIZE, enc_len); sha.finalizeHMAC(shared_secret, PUB_KEY_SIZE, dest, CIPHER_MAC_SIZE); +#endif return CIPHER_MAC_SIZE + enc_len; } @@ -75,12 +158,25 @@ int Utils::MACThenDecrypt(const uint8_t* shared_secret, uint8_t* dest, const uin if (src_len <= CIPHER_MAC_SIZE) return 0; // invalid src bytes uint8_t hmac[CIPHER_MAC_SIZE]; +#ifdef USE_CC310_ED25519 + { + static CRYS_HMACUserContext_t hmac_ctx; + static CRYS_HASH_Result_t hmac_result; + nRFCrypto.begin(); + CRYS_HMAC_Init(&hmac_ctx, CRYS_HASH_SHA256_mode, (uint8_t*)shared_secret, PUB_KEY_SIZE); + CRYS_HMAC_Update(&hmac_ctx, (uint8_t*)(src + CIPHER_MAC_SIZE), src_len - CIPHER_MAC_SIZE); + CRYS_HMAC_Finish(&hmac_ctx, hmac_result); + nRFCrypto.end(); + memcpy(hmac, hmac_result, CIPHER_MAC_SIZE); + } +#else { SHA256 sha; sha.resetHMAC(shared_secret, PUB_KEY_SIZE); sha.update(src + CIPHER_MAC_SIZE, src_len - CIPHER_MAC_SIZE); sha.finalizeHMAC(shared_secret, PUB_KEY_SIZE, hmac, CIPHER_MAC_SIZE); } +#endif if (memcmp(hmac, src, CIPHER_MAC_SIZE) == 0) { return decrypt(shared_secret, dest, src + CIPHER_MAC_SIZE, src_len - CIPHER_MAC_SIZE); } @@ -150,4 +246,4 @@ int Utils::parseTextParts(char* text, const char* parts[], int max_num, char sep return num; } -} \ No newline at end of file +} diff --git a/src/helpers/radiolib/RadioLibWrappers.h b/src/helpers/radiolib/RadioLibWrappers.h index 3091832f..f390199f 100644 --- a/src/helpers/radiolib/RadioLibWrappers.h +++ b/src/helpers/radiolib/RadioLibWrappers.h @@ -3,6 +3,10 @@ #include #include +#ifdef USE_CC310_ED25519 +#include +#endif + class RadioLibWrapper : public mesh::Radio { protected: PhysicalLayer* _radio; @@ -80,8 +84,15 @@ public: RadioNoiseListener(PhysicalLayer& radio): _radio(&radio) { } void random(uint8_t* dest, size_t sz) override { +#ifdef USE_CC310_ED25519 + // CC310 TRNG is higher quality and environment-independent vs radio RSSI noise. + nRFCrypto.begin(); + nRFCrypto.Random.generate(dest, (uint16_t)sz); + nRFCrypto.end(); +#else for (int i = 0; i < sz; i++) { dest[i] = _radio->randomByte() ^ (::random(0, 256) & 0xFF); } +#endif } }; From a4e7cdf4f3036dbfbdfcdd282a7711c4e940e111 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Wed, 15 Jul 2026 01:23:57 +1000 Subject: [PATCH 015/381] * first draft of new ConfigSerializer. (simple embedded JSON prefs) --- examples/simple_repeater/MyMesh.cpp | 1 - examples/simple_room_server/MyMesh.cpp | 1 - examples/simple_sensor/SensorMesh.cpp | 1 - src/helpers/CommonCLI.cpp | 84 ++------ src/helpers/CommonCLI.h | 122 ++++++++++- src/helpers/ConfigSerializer.cpp | 278 +++++++++++++++++++++++++ src/helpers/ConfigSerializer.h | 67 ++++++ 7 files changed, 485 insertions(+), 69 deletions(-) create mode 100644 src/helpers/ConfigSerializer.cpp create mode 100644 src/helpers/ConfigSerializer.h diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index b66e1952..09f74cbe 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -872,7 +872,6 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc #endif // defaults - memset(&_prefs, 0, sizeof(_prefs)); _prefs.airtime_factor = 1.0; _prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0; _prefs.tx_delay_factor = 0.5f; // was 0.25f diff --git a/examples/simple_room_server/MyMesh.cpp b/examples/simple_room_server/MyMesh.cpp index 36978e80..1a778d4a 100644 --- a/examples/simple_room_server/MyMesh.cpp +++ b/examples/simple_room_server/MyMesh.cpp @@ -628,7 +628,6 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc recv_pkt_region = NULL; // defaults - memset(&_prefs, 0, sizeof(_prefs)); _prefs.airtime_factor = 1.0; _prefs.rx_delay_base = 0.0f; // off by default, was 10.0 _prefs.tx_delay_factor = 0.5f; // was 0.25f; diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 59c9aa09..17f8e323 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -710,7 +710,6 @@ SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::Millise set_radio_at = revert_radio_at = 0; // defaults - memset(&_prefs, 0, sizeof(_prefs)); _prefs.airtime_factor = 1.0; _prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0; _prefs.tx_delay_factor = 0.5f; // was 0.25f diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index c95e3e34..56a46d46 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -28,16 +28,21 @@ static bool isValidName(const char *n) { } void CommonCLI::loadPrefs(FILESYSTEM* fs) { - if (fs->exists("/com_prefs")) { - loadPrefsInt(fs, "/com_prefs"); // new filename - } else if (fs->exists("/node_prefs")) { - loadPrefsInt(fs, "/node_prefs"); - savePrefs(fs); // save to new filename - fs->remove("/node_prefs"); // remove old + if (fs->exists("/ser_prefs")) { + File file = fs->open("/ser_prefs"); + if (file) { + _prefs->loadSerial(file); // new Serial prefs + file.close(); + } + } else if (fs->exists("/com_prefs")) { + loadPrefsInt(fs, "/com_prefs"); + if (savePrefs(fs)) { // save to new Serial prefs + // fs->remove("/com_prefs"); // remove old + } } } -void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) { +void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) { // Legacy prefs loader #if defined(RP2040_PLATFORM) File file = fs->open(filename, "r"); #else @@ -130,70 +135,21 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) { } } -void CommonCLI::savePrefs(FILESYSTEM* fs) { +bool CommonCLI::savePrefs(FILESYSTEM* fs) { #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) - fs->remove("/com_prefs"); - File file = fs->open("/com_prefs", FILE_O_WRITE); + fs->remove("/ser_prefs"); + File file = fs->open("/ser_prefs", FILE_O_WRITE); #elif defined(RP2040_PLATFORM) - File file = fs->open("/com_prefs", "w"); + File file = fs->open("/ser_prefs", "w"); #else - File file = fs->open("/com_prefs", "w", true); + File file = fs->open("/ser_prefs", "w", true); #endif if (file) { - uint8_t pad[8]; - memset(pad, 0, sizeof(pad)); - - file.write((uint8_t *)&_prefs->airtime_factor, sizeof(_prefs->airtime_factor)); // 0 - file.write((uint8_t *)&_prefs->node_name, sizeof(_prefs->node_name)); // 4 - file.write(pad, 4); // 36 - file.write((uint8_t *)&_prefs->node_lat, sizeof(_prefs->node_lat)); // 40 - file.write((uint8_t *)&_prefs->node_lon, sizeof(_prefs->node_lon)); // 48 - file.write((uint8_t *)&_prefs->password[0], sizeof(_prefs->password)); // 56 - file.write((uint8_t *)&_prefs->freq, sizeof(_prefs->freq)); // 72 - file.write((uint8_t *)&_prefs->tx_power_dbm, sizeof(_prefs->tx_power_dbm)); // 76 - file.write((uint8_t *)&_prefs->disable_fwd, sizeof(_prefs->disable_fwd)); // 77 - file.write((uint8_t *)&_prefs->advert_interval, sizeof(_prefs->advert_interval)); // 78 - file.write(pad, 1); // 79 : 1 byte unused (rx_boosted_gain moved to end) - file.write((uint8_t *)&_prefs->rx_delay_base, sizeof(_prefs->rx_delay_base)); // 80 - file.write((uint8_t *)&_prefs->tx_delay_factor, sizeof(_prefs->tx_delay_factor)); // 84 - file.write((uint8_t *)&_prefs->guest_password[0], sizeof(_prefs->guest_password)); // 88 - file.write((uint8_t *)&_prefs->direct_tx_delay_factor, sizeof(_prefs->direct_tx_delay_factor)); // 104 - file.write(pad, 4); // 108 : 4 byte unused - file.write((uint8_t *)&_prefs->sf, sizeof(_prefs->sf)); // 112 - file.write((uint8_t *)&_prefs->cr, sizeof(_prefs->cr)); // 113 - file.write((uint8_t *)&_prefs->allow_read_only, sizeof(_prefs->allow_read_only)); // 114 - file.write((uint8_t *)&_prefs->multi_acks, sizeof(_prefs->multi_acks)); // 115 - file.write((uint8_t *)&_prefs->bw, sizeof(_prefs->bw)); // 116 - file.write((uint8_t *)&_prefs->agc_reset_interval, sizeof(_prefs->agc_reset_interval)); // 120 - file.write((uint8_t *)&_prefs->path_hash_mode, sizeof(_prefs->path_hash_mode)); // 121 - file.write((uint8_t *)&_prefs->loop_detect, sizeof(_prefs->loop_detect)); // 122 - file.write(pad, 1); // 123 - file.write((uint8_t *)&_prefs->flood_max, sizeof(_prefs->flood_max)); // 124 - file.write((uint8_t *)&_prefs->flood_advert_interval, sizeof(_prefs->flood_advert_interval)); // 125 - file.write((uint8_t *)&_prefs->interference_threshold, sizeof(_prefs->interference_threshold)); // 126 - file.write((uint8_t *)&_prefs->bridge_enabled, sizeof(_prefs->bridge_enabled)); // 127 - file.write((uint8_t *)&_prefs->bridge_delay, sizeof(_prefs->bridge_delay)); // 128 - file.write((uint8_t *)&_prefs->bridge_pkt_src, sizeof(_prefs->bridge_pkt_src)); // 130 - file.write((uint8_t *)&_prefs->bridge_baud, sizeof(_prefs->bridge_baud)); // 131 - file.write((uint8_t *)&_prefs->bridge_channel, sizeof(_prefs->bridge_channel)); // 135 - file.write((uint8_t *)&_prefs->bridge_secret, sizeof(_prefs->bridge_secret)); // 136 - file.write((uint8_t *)&_prefs->powersaving_enabled, sizeof(_prefs->powersaving_enabled)); // 152 - file.write(pad, 3); // 153 - file.write((uint8_t *)&_prefs->gps_enabled, sizeof(_prefs->gps_enabled)); // 156 - file.write((uint8_t *)&_prefs->gps_interval, sizeof(_prefs->gps_interval)); // 157 - file.write((uint8_t *)&_prefs->advert_loc_policy, sizeof(_prefs->advert_loc_policy)); // 161 - file.write((uint8_t *)&_prefs->discovery_mod_timestamp, sizeof(_prefs->discovery_mod_timestamp)); // 162 - file.write((uint8_t *)&_prefs->adc_multiplier, sizeof(_prefs->adc_multiplier)); // 166 - file.write((uint8_t *)_prefs->owner_info, sizeof(_prefs->owner_info)); // 170 - file.write((uint8_t *)&_prefs->rx_boosted_gain, sizeof(_prefs->rx_boosted_gain)); // 290 - file.write((uint8_t *)&_prefs->flood_max_unscoped, sizeof(_prefs->flood_max_unscoped)); // 291 - file.write((uint8_t *)&_prefs->flood_max_advert, sizeof(_prefs->flood_max_advert)); // 292 - file.write((uint8_t *)&_prefs->radio_fem_rxgain, sizeof(_prefs->radio_fem_rxgain)); // 293 - file.write((uint8_t *)&_prefs->cad_enabled, sizeof(_prefs->cad_enabled)); // 294 - // next: 295 - + bool success = _prefs->saveSerial(file); file.close(); + return success; } + return false; } #define MIN_LOCAL_ADVERT_INTERVAL 60 diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index f3abcf47..aab33d11 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -5,6 +5,7 @@ #include #include #include +#include #if defined(WITH_RS232_BRIDGE) || defined(WITH_ESPNOW_BRIDGE) #define WITH_BRIDGE @@ -19,7 +20,9 @@ #define LOOP_DETECT_MODERATE 2 #define LOOP_DETECT_STRICT 3 -struct NodePrefs { // persisted to file +class NodePrefs : public ConfigSerializer { +public: + // in-memory backing data float airtime_factor; char node_name[32]; double node_lat, node_lon; @@ -65,6 +68,121 @@ struct NodePrefs { // persisted to file uint8_t path_hash_mode; // which path mode to use when sending uint8_t loop_detect; uint8_t cad_enabled; // hardware Channel Activity Detection before TX (boolean) + +private: + class RadioPrefs : public ConfigSerializer { + NodePrefs* _parent; + protected: + void structure() override { + def("freq", _parent->freq); + def("bw", _parent->bw); + def("sf", _parent->sf); + def("cr", _parent->cr); + def("cad", _parent->cad_enabled); + def("int_thr", _parent->interference_threshold); + def("rxgain", _parent->rx_boosted_gain); + def("fem_rxgain", _parent->rx_boosted_gain); + def("tx", _parent->tx_power_dbm); + def("af", _parent->airtime_factor); + def("rxdelay", _parent->rx_delay_base); + def("f_txdelay", _parent->tx_delay_factor); + def("d_txdelay", _parent->direct_tx_delay_factor); + def("agc_int", _parent->agc_reset_interval); + def("hash_mode", _parent->path_hash_mode); + def("multi_ack", _parent->multi_acks); + } + public: + RadioPrefs(NodePrefs* parent) : _parent(parent) { } + }; + RadioPrefs radio; + + class BridgePrefs : public ConfigSerializer { + NodePrefs* _parent; + protected: + void structure() override { + def("en", _parent->bridge_enabled); // boolean + def("delay", _parent->bridge_delay); // milliseconds (default 500 ms) + def("src", _parent->bridge_pkt_src); // 0 = logTx, 1 = logRx (default logTx) + def("baud", _parent->bridge_baud); // 9600, 19200, 38400, 57600, 115200 (default 115200) + def("ch", _parent->bridge_channel); // 1-14 (ESP-NOW only) + def("secret", _parent->bridge_secret, sizeof(_parent->bridge_secret)); // for XOR encryption of bridge packets (ESP-NOW only) + } + public: + BridgePrefs(NodePrefs* parent) : _parent(parent) { } + }; + BridgePrefs bridge; + + class GPSPrefs : public ConfigSerializer { + NodePrefs* _parent; + protected: + void structure() override { + def("en", _parent->gps_enabled); // boolean + def("int", _parent->gps_interval); // interval in seconds + def("adv_loc", _parent->advert_loc_policy); + } + public: + GPSPrefs(NodePrefs* parent) : _parent(parent) { } + }; + GPSPrefs gps; + + class PowerPrefs : public ConfigSerializer { + NodePrefs* _parent; + protected: + void structure() override { + def("adc_mult", _parent->adc_multiplier); + def("pwr_sav_en", _parent->powersaving_enabled); + } + public: + PowerPrefs(NodePrefs* parent) : _parent(parent) { } + }; + PowerPrefs power; + + class RepeatPrefs : public ConfigSerializer { + NodePrefs* _parent; + protected: + void structure() override { + def("disable", _parent->disable_fwd); + def("f_max", _parent->flood_max); + def("f_max_uns", _parent->flood_max_unscoped); + def("f_max_adv", _parent->flood_max_advert); + def("loop", _parent->loop_detect); + } + public: + RepeatPrefs(NodePrefs* parent) : _parent(parent) { } + }; + RepeatPrefs repeat; + + class RoomPrefs : public ConfigSerializer { + NodePrefs* _parent; + protected: + void structure() override { + def("rd_only", _parent->allow_read_only); + } + public: + RoomPrefs(NodePrefs* parent) : _parent(parent) { } + }; + RoomPrefs room; + +protected: + void structure() override { + def("name", node_name, sizeof(node_name)); + def("pass", password, sizeof(password)); + def("guest", guest_password, sizeof(guest_password)); + def("owner", owner_info, sizeof(owner_info)); + def("adv_int", advert_interval); + def("f_adv_int", flood_advert_interval); + def("lat", node_lat); + def("lon", node_lon); + def("radio", radio); + def("bridge", bridge); + def("gps", gps); + def("repeat", repeat); + def("room", room); + def("power", power); + } + +public: + NodePrefs() : ConfigSerializer(), bridge(this), gps(this), radio(this), power(this), repeat(this), room(this) { } }; class CommonCLICallbacks { @@ -139,7 +257,7 @@ public: : _board(&board), _rtc(&rtc), _sensors(&sensors), _region_map(®ion_map), _acl(&acl), _prefs(prefs), _callbacks(callbacks) { } void loadPrefs(FILESYSTEM* _fs); - void savePrefs(FILESYSTEM* _fs); + bool savePrefs(FILESYSTEM* _fs); void handleCommand(uint32_t sender_timestamp, char* command, char* reply); uint8_t buildAdvertData(uint8_t node_type, uint8_t* app_data); }; diff --git a/src/helpers/ConfigSerializer.cpp b/src/helpers/ConfigSerializer.cpp new file mode 100644 index 00000000..221fd197 --- /dev/null +++ b/src/helpers/ConfigSerializer.cpp @@ -0,0 +1,278 @@ +#include "ConfigSerializer.h" + +bool ConfigSerializer::saveSerial(Stream& s) { + Context context(&s, OP::WRITE); + _context = &context; // set the context for structure() call + s.print("{"); // root object + _first = true; + structure(); + if (s.print("}") != 1) context.success = false; // failure detect + _context = NULL; + return context.success; +} + +#define TOK_ERROR -1 +#define TOK_EOF 0 +#define TOK_KEY 1 +#define TOK_VALUE 2 +#define TOK_START_OBJ 3 +#define TOK_END_OBJ 4 +#define TOK_WHITESPACE 5 + +static bool is_whitespace(char c) { + return c == ' ' || c == '\t' || c == '\r' || c == '\n'; +} +static bool is_key_char(char c) { + return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_'; +} +static bool is_value_char(char c) { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || c == '-' || c == '.'; +} + +#define EXPECT_OPEN_BRACE 0 +#define EXPECT_KEY 1 +#define EXPECT_VAL_OR_OBJ 2 +#define EXPECT_STRING_VAL 3 +#define EXPECT_STRING_ESCAPE 4 +#define EXPECT_COMMA_OR_CLOSE 5 +#define EXPECT_COMMA_OR_KEY 6 +#define EXPECT_COMMA_OR_KEY_OR_CLOSE 7 + +int ConfigSerializer::Context::readNext() { + char c; + if (pending) { + c = pending; + pending = 0; + } else { + if (_f->available() == 0) return TOK_EOF; + + int n = _f->read(); + if (n < 0) return TOK_EOF; + c = (char)n; + } + + switch (rd_mode) { + case EXPECT_OPEN_BRACE: + if (c == '{') { rd_mode = EXPECT_KEY; return TOK_START_OBJ; } + if (is_whitespace(c)) return TOK_WHITESPACE; + return TOK_ERROR; + + case EXPECT_COMMA_OR_KEY_OR_CLOSE: + if (c == '}') { rd_mode = EXPECT_COMMA_OR_KEY_OR_CLOSE; return TOK_END_OBJ; } + case EXPECT_COMMA_OR_KEY: + if (c == ',') { rd_mode = EXPECT_KEY; return TOK_WHITESPACE; } + case EXPECT_KEY: + if (rd_len > 0 && c == ':') { rd_buf[rd_len] = 0; rd_len = 0; rd_mode = EXPECT_VAL_OR_OBJ; return TOK_KEY; } + if (rd_len == 0 && is_whitespace(c)) return TOK_WHITESPACE; + if (rd_len < CONFIG_MAX_KEYLEN-1 && is_key_char(c)) { rd_buf[rd_len++] = c; return TOK_WHITESPACE; } + return TOK_ERROR; + + case EXPECT_VAL_OR_OBJ: + if (rd_len == 0 && is_whitespace(c)) return TOK_WHITESPACE; + if (rd_len == 0 && c == '"') { rd_mode = EXPECT_STRING_VAL; return TOK_WHITESPACE; } + if (rd_len == 0 && c == '{') { rd_mode = EXPECT_KEY; return TOK_START_OBJ; } + if (is_value_char(c) && rd_len < CONFIG_MAX_TOKEN_LEN-1) { rd_buf[rd_len++] = c; return TOK_WHITESPACE; } + if (rd_len > 0 && (c == ',' || c == '}' || is_whitespace(c))) { pending = c; rd_buf[rd_len] = 0; rd_len = 0; rd_mode = EXPECT_COMMA_OR_CLOSE; return TOK_VALUE; } + return TOK_ERROR; + + case EXPECT_STRING_ESCAPE: + if ((c == '"' || c == '\\' || c == '/') && rd_len < CONFIG_MAX_TOKEN_LEN-1) { rd_buf[rd_len++] = c; rd_mode = EXPECT_STRING_VAL; return TOK_WHITESPACE; } + return TOK_ERROR; // unsupport escape + + case EXPECT_STRING_VAL: + if (c == '"') { rd_buf[rd_len] = 0; rd_len = 0; rd_mode = EXPECT_COMMA_OR_CLOSE; return TOK_VALUE; } + if (c == '\\') { rd_mode = EXPECT_STRING_ESCAPE; return TOK_WHITESPACE; } + if (rd_len < CONFIG_MAX_TOKEN_LEN-1) { rd_buf[rd_len++] = c; return TOK_WHITESPACE; } + return TOK_ERROR; + + case EXPECT_COMMA_OR_CLOSE: + if (c == ',') { rd_mode = EXPECT_KEY; return TOK_WHITESPACE; } + if (c == '}') { rd_mode = EXPECT_COMMA_OR_KEY_OR_CLOSE; return TOK_END_OBJ; } + if (is_whitespace(c)) return TOK_WHITESPACE; + return TOK_ERROR; + } + return TOK_ERROR; // unknown mode +} + +bool ConfigSerializer::loadSerial(Stream& s) { + Context context(&s, OP::READ); + _context = &context; // set the context for structure() call + // parse the Json file + uint8_t sp = 0; + int next_tok; + + while ((next_tok = context.readNext()) > TOK_EOF) { + if (next_tok == TOK_KEY) { + context.setKey(sp, context.getToken()); + } else if (next_tok == TOK_VALUE) { + _depth = 1; // re-run the structure() hierarchy again (looking for specific key, at specific depth) + structure(); + } else if (next_tok == TOK_START_OBJ) { + if (sp < CONFIF_MAX_DEPTH - 1) { + sp++; + } else { + Serial.printf("Error: max nesting reached"); // TODO: debug logging + context.success = false; + break; + } + } else if (next_tok == TOK_END_OBJ) { + if (sp > 0) { + sp--; + } else { + Serial.printf("Error: too many closing '}'"); // TODO: debug logging + context.success = false; + break; + } + } + } + if (sp != 0 || next_tok == TOK_ERROR) { + context.success = false; // unmatched { }, or other parse error + } + _context = NULL; + return context.success; +} + +void ConfigSerializer::writeComma() { + if (_first) { + _first = false; + } else { + _context->file()->print(","); // comma separated properties + } +} + +void ConfigSerializer::def(const char* key, char* value, size_t max_len) { + if (_context->op() == OP::WRITE) { + writeComma(); + _context->file()->print(key); + _context->file()->print(":\""); + _context->file()->print(value); // TODO: escape quotes + _context->file()->print("\""); + } else { + if (_context->keyMatch(_depth, key)) { + strncpy(value, _context->getToken(), max_len - 1); + value[max_len - 1] = 0; + } + } +} + +void ConfigSerializer::def(const char* key, int32_t& value) { + if (_context->op() == OP::WRITE) { + writeComma(); + _context->file()->print(key); + _context->file()->print(":"); + _context->file()->print(value); + } else { + if (_context->keyMatch(_depth, key)) { + value = atol(_context->getToken()); + } + } +} + +void ConfigSerializer::def(const char* key, uint32_t& value) { + if (_context->op() == OP::WRITE) { + writeComma(); + _context->file()->print(key); + _context->file()->print(":"); + _context->file()->print(value); + } else { + if (_context->keyMatch(_depth, key)) { + value = atol(_context->getToken()); + } + } +} + +void ConfigSerializer::def(const char* key, int16_t& value) { + if (_context->op() == OP::WRITE) { + writeComma(); + _context->file()->print(key); + _context->file()->print(":"); + _context->file()->print((int32_t) value, 10); + } else { + if (_context->keyMatch(_depth, key)) { + value = atol(_context->getToken()); + } + } +} + +void ConfigSerializer::def(const char* key, uint16_t& value) { + if (_context->op() == OP::WRITE) { + writeComma(); + _context->file()->print(key); + _context->file()->print(":"); + _context->file()->print((uint32_t) value, 10); + } else { + if (_context->keyMatch(_depth, key)) { + value = atoi(_context->getToken()); + } + } +} + +void ConfigSerializer::def(const char* key, uint8_t& value) { + if (_context->op() == OP::WRITE) { + writeComma(); + _context->file()->print(key); + _context->file()->print(":"); + _context->file()->print((uint32_t) value, 10); + } else { + if (_context->keyMatch(_depth, key)) { + value = atoi(_context->getToken()); + } + } +} + +void ConfigSerializer::def(const char* key, int8_t& value) { + if (_context->op() == OP::WRITE) { + writeComma(); + _context->file()->print(key); + _context->file()->print(":"); + _context->file()->print((int32_t) value, 10); + } else { + if (_context->keyMatch(_depth, key)) { + value = atoi(_context->getToken()); + } + } +} + +void ConfigSerializer::def(const char* key, double& value) { + if (_context->op() == OP::WRITE) { + writeComma(); + _context->file()->print(key); + _context->file()->print(":"); + _context->file()->print(value, 6); // REVISIT: how many dec places? + } else { + if (_context->keyMatch(_depth, key)) { + value = atof(_context->getToken()); + } + } +} + +void ConfigSerializer::def(const char* key, float& value) { + if (_context->op() == OP::WRITE) { + writeComma(); + _context->file()->print(key); + _context->file()->print(":"); + _context->file()->print(value, 4); // REVISIT: how many dec places? + } else { + if (_context->keyMatch(_depth, key)) { + value = (float) atof(_context->getToken()); + } + } +} + +void ConfigSerializer::def(const char* key, ConfigSerializer& sub_obj) { + if (_context->op() == OP::WRITE) { + writeComma(); + _context->file()->print(key); + _context->file()->print(":{"); + sub_obj._context = _context; // inherit the Context + sub_obj._first = true; + sub_obj.structure(); // recurse into sub object + if (_context->file()->print("}") != 1) _context->success = false; // failure detect + } else { + if (_context->keyMatch(_depth, key)) { + sub_obj._context = _context; // inherit the Context + sub_obj._depth = _depth + 1; + sub_obj.structure(); // recurse into sub object + } + } +} diff --git a/src/helpers/ConfigSerializer.h b/src/helpers/ConfigSerializer.h new file mode 100644 index 00000000..2f1d2ae1 --- /dev/null +++ b/src/helpers/ConfigSerializer.h @@ -0,0 +1,67 @@ +#pragma once + +#include + +#ifndef CONFIF_MAX_DEPTH + #define CONFIF_MAX_DEPTH 8 +#endif + +#ifndef CONFIG_MAX_KEYLEN + #define CONFIG_MAX_KEYLEN 16 +#endif + +#ifndef CONFIG_MAX_TOKEN_LEN + #define CONFIG_MAX_TOKEN_LEN 128 +#endif + +class ConfigSerializer { + bool _first; + int8_t _depth; + + enum OP { READ, WRITE }; + + class Context { + Stream* _f; + OP _op; + uint8_t rd_len; + uint8_t rd_mode; + char pending; + char rd_buf[CONFIG_MAX_TOKEN_LEN]; + char _keys[CONFIF_MAX_DEPTH][CONFIG_MAX_KEYLEN]; + + public: + bool success = true; + Context(Stream* f, OP op) : _f(f), _op(op) { rd_buf[rd_len = 0] = 0; rd_mode = 0; pending = 0; } + OP op() const { return _op; } + Stream* file() const { return _f; } + int readNext(); + const char* getToken() const { return rd_buf; } + bool keyMatch(int8_t depth, const char* key) { return strcmp(key, _keys[depth]) == 0; } + void setKey(uint8_t depth, const char* key) { strcpy(_keys[depth], key); } + }; + + Context* _context = NULL; + + void writeComma(); + +protected: + ConfigSerializer() { } + + void def(const char* key, char* value, size_t max_len); // max_len inclusive of null + void def(const char* key, int32_t& value); + void def(const char* key, int16_t& value); + void def(const char* key, int8_t& value); + void def(const char* key, uint32_t& value); + void def(const char* key, uint16_t& value); + void def(const char* key, uint8_t& value); + void def(const char* key, float& value); + void def(const char* key, double& value); + void def(const char* key, bool& value); + void def(const char* key, ConfigSerializer& sub_obj); + + virtual void structure() = 0; + +public: + bool loadSerial(Stream& s); + bool saveSerial(Stream& s); +}; From 06eec9e512aac8d3de643a2b1506c19937e7ce3a Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Wed, 15 Jul 2026 13:21:44 +1000 Subject: [PATCH 016/381] * misc fixes --- src/helpers/ConfigSerializer.cpp | 46 +++++++++++++++++++++++++++----- src/helpers/ConfigSerializer.h | 6 ++--- 2 files changed, 43 insertions(+), 9 deletions(-) diff --git a/src/helpers/ConfigSerializer.cpp b/src/helpers/ConfigSerializer.cpp index 221fd197..76673309 100644 --- a/src/helpers/ConfigSerializer.cpp +++ b/src/helpers/ConfigSerializer.cpp @@ -97,10 +97,10 @@ int ConfigSerializer::Context::readNext() { bool ConfigSerializer::loadSerial(Stream& s) { Context context(&s, OP::READ); _context = &context; // set the context for structure() call - // parse the Json file - uint8_t sp = 0; + uint8_t sp = 0; // object nesting stack pointer int next_tok; + // parse the Json file while ((next_tok = context.readNext()) > TOK_EOF) { if (next_tok == TOK_KEY) { context.setKey(sp, context.getToken()); @@ -108,7 +108,7 @@ bool ConfigSerializer::loadSerial(Stream& s) { _depth = 1; // re-run the structure() hierarchy again (looking for specific key, at specific depth) structure(); } else if (next_tok == TOK_START_OBJ) { - if (sp < CONFIF_MAX_DEPTH - 1) { + if (sp < CONFIG_MAX_DEPTH - 1) { sp++; } else { Serial.printf("Error: max nesting reached"); // TODO: debug logging @@ -145,7 +145,20 @@ void ConfigSerializer::def(const char* key, char* value, size_t max_len) { writeComma(); _context->file()->print(key); _context->file()->print(":\""); - _context->file()->print(value); // TODO: escape quotes + char c; + while ((c = *value++) != 0) { // TODO: handle UTF-8 encoding + if (c == '"') { + _context->file()->print("\\\""); + } else if (c == '\\') { + _context->file()->print("\\\\"); + } else if (c == '\n') { + _context->file()->print("\\n"); + } else if (c == '\r') { + _context->file()->print("\\r"); + } else { + _context->file()->print(c); + } + } _context->file()->print("\""); } else { if (_context->keyMatch(_depth, key)) { @@ -233,12 +246,29 @@ void ConfigSerializer::def(const char* key, int8_t& value) { } } +void ConfigSerializer::def(const char* key, bool& value) { + if (_context->op() == OP::WRITE) { + writeComma(); + _context->file()->print(key); + _context->file()->print(":"); + _context->file()->print(value ? "true" : "false"); + } else { + if (_context->keyMatch(_depth, key)) { + value = strcmp(_context->getToken(), "true") == 0 || atoi(_context->getToken()) != 0; // 'true' or a non-zero number + } + } +} + void ConfigSerializer::def(const char* key, double& value) { if (_context->op() == OP::WRITE) { writeComma(); _context->file()->print(key); _context->file()->print(":"); - _context->file()->print(value, 6); // REVISIT: how many dec places? + if (value == 0.0) { + _context->file()->print("0"); // shorter encoding + } else { + _context->file()->print(value, 6); // REVISIT: how many dec places? + } } else { if (_context->keyMatch(_depth, key)) { value = atof(_context->getToken()); @@ -251,7 +281,11 @@ void ConfigSerializer::def(const char* key, float& value) { writeComma(); _context->file()->print(key); _context->file()->print(":"); - _context->file()->print(value, 4); // REVISIT: how many dec places? + if (value == 0.0f) { + _context->file()->print("0"); // shorter encoding + } else { + _context->file()->print(value, 4); // REVISIT: how many dec places? + } } else { if (_context->keyMatch(_depth, key)) { value = (float) atof(_context->getToken()); diff --git a/src/helpers/ConfigSerializer.h b/src/helpers/ConfigSerializer.h index 2f1d2ae1..5f0dc488 100644 --- a/src/helpers/ConfigSerializer.h +++ b/src/helpers/ConfigSerializer.h @@ -2,8 +2,8 @@ #include -#ifndef CONFIF_MAX_DEPTH - #define CONFIF_MAX_DEPTH 8 +#ifndef CONFIG_MAX_DEPTH + #define CONFIG_MAX_DEPTH 8 #endif #ifndef CONFIG_MAX_KEYLEN @@ -27,7 +27,7 @@ class ConfigSerializer { uint8_t rd_mode; char pending; char rd_buf[CONFIG_MAX_TOKEN_LEN]; - char _keys[CONFIF_MAX_DEPTH][CONFIG_MAX_KEYLEN]; + char _keys[CONFIG_MAX_DEPTH][CONFIG_MAX_KEYLEN]; public: bool success = true; From 06ec571ec123ab7e890bb922a6d0bbac9ef66c87 Mon Sep 17 00:00:00 2001 From: Nick Dunklee Date: Thu, 16 Jul 2026 21:44:35 -0600 Subject: [PATCH 017/381] Minor ifdef rename as it now covers more than just Ed25519 for hardware encryption. Now `USE_CC310_HW_CRYPTO` --- src/Identity.cpp | 4 ++-- src/Utils.cpp | 14 +++++++------- src/helpers/radiolib/RadioLibWrappers.h | 4 ++-- variants/heltec_t096/platformio.ini | 2 +- variants/rak3401/platformio.ini | 2 +- variants/rak4631/platformio.ini | 2 +- variants/t1000-e/platformio.ini | 2 +- 7 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/Identity.cpp b/src/Identity.cpp index 2ab1cefa..25419fd4 100644 --- a/src/Identity.cpp +++ b/src/Identity.cpp @@ -4,7 +4,7 @@ #include #include -#ifdef USE_CC310_ED25519 +#ifdef USE_CC310_HW_CRYPTO #include #include "nrf_cc310/include/crys_ec_edw_api.h" #endif @@ -20,7 +20,7 @@ Identity::Identity(const char* pub_hex) { } bool Identity::verify(const uint8_t* sig, const uint8_t* message, int msg_len) const { -#ifdef USE_CC310_ED25519 +#ifdef USE_CC310_HW_CRYPTO // nRF52840 CryptoCell CC310 hardware Ed25519 verification. The software // implementations need ~3KB of stack (which can overflow the Adafruit core's // 4KB loop task stack from the advert receive path); the hardware path diff --git a/src/Utils.cpp b/src/Utils.cpp index 9cd44ce2..d4bc8c45 100644 --- a/src/Utils.cpp +++ b/src/Utils.cpp @@ -2,7 +2,7 @@ #include #include -#ifdef USE_CC310_ED25519 +#ifdef USE_CC310_HW_CRYPTO #include #include "nrf_cc310/include/crys_hash.h" #include "nrf_cc310/include/crys_hmac.h" @@ -22,7 +22,7 @@ uint32_t RNG::nextInt(uint32_t _min, uint32_t _max) { } void Utils::sha256(uint8_t *hash, size_t hash_len, const uint8_t* msg, int msg_len) { -#ifdef USE_CC310_ED25519 +#ifdef USE_CC310_HW_CRYPTO static CRYS_HASH_Result_t result; nRFCrypto.begin(); CRYS_HASH(CRYS_HASH_SHA256_mode, (uint8_t*)msg, (size_t)msg_len, result); @@ -36,7 +36,7 @@ void Utils::sha256(uint8_t *hash, size_t hash_len, const uint8_t* msg, int msg_l } void Utils::sha256(uint8_t *hash, size_t hash_len, const uint8_t* frag1, int frag1_len, const uint8_t* frag2, int frag2_len) { -#ifdef USE_CC310_ED25519 +#ifdef USE_CC310_HW_CRYPTO static CRYS_HASHUserContext_t ctx; static CRYS_HASH_Result_t result; nRFCrypto.begin(); @@ -55,7 +55,7 @@ void Utils::sha256(uint8_t *hash, size_t hash_len, const uint8_t* frag1, int fra } int Utils::decrypt(const uint8_t* shared_secret, uint8_t* dest, const uint8_t* src, int src_len) { -#ifdef USE_CC310_ED25519 +#ifdef USE_CC310_HW_CRYPTO static SaSiAesUserContext_t ctx; SaSiAesUserKeyData_t keyData = { (uint8_t*)shared_secret, CIPHER_KEY_SIZE }; uint8_t* dp = dest; @@ -89,7 +89,7 @@ int Utils::decrypt(const uint8_t* shared_secret, uint8_t* dest, const uint8_t* s } int Utils::encrypt(const uint8_t* shared_secret, uint8_t* dest, const uint8_t* src, int src_len) { -#ifdef USE_CC310_ED25519 +#ifdef USE_CC310_HW_CRYPTO static SaSiAesUserContext_t ctx; SaSiAesUserKeyData_t keyData = { (uint8_t*)shared_secret, CIPHER_KEY_SIZE }; uint8_t* dp = dest; @@ -135,7 +135,7 @@ int Utils::encrypt(const uint8_t* shared_secret, uint8_t* dest, const uint8_t* s int Utils::encryptThenMAC(const uint8_t* shared_secret, uint8_t* dest, const uint8_t* src, int src_len) { int enc_len = encrypt(shared_secret, dest + CIPHER_MAC_SIZE, src, src_len); -#ifdef USE_CC310_ED25519 +#ifdef USE_CC310_HW_CRYPTO static CRYS_HMACUserContext_t hmac_ctx; static CRYS_HASH_Result_t hmac_result; nRFCrypto.begin(); @@ -158,7 +158,7 @@ int Utils::MACThenDecrypt(const uint8_t* shared_secret, uint8_t* dest, const uin if (src_len <= CIPHER_MAC_SIZE) return 0; // invalid src bytes uint8_t hmac[CIPHER_MAC_SIZE]; -#ifdef USE_CC310_ED25519 +#ifdef USE_CC310_HW_CRYPTO { static CRYS_HMACUserContext_t hmac_ctx; static CRYS_HASH_Result_t hmac_result; diff --git a/src/helpers/radiolib/RadioLibWrappers.h b/src/helpers/radiolib/RadioLibWrappers.h index f390199f..4cbbb055 100644 --- a/src/helpers/radiolib/RadioLibWrappers.h +++ b/src/helpers/radiolib/RadioLibWrappers.h @@ -3,7 +3,7 @@ #include #include -#ifdef USE_CC310_ED25519 +#ifdef USE_CC310_HW_CRYPTO #include #endif @@ -84,7 +84,7 @@ public: RadioNoiseListener(PhysicalLayer& radio): _radio(&radio) { } void random(uint8_t* dest, size_t sz) override { -#ifdef USE_CC310_ED25519 +#ifdef USE_CC310_HW_CRYPTO // CC310 TRNG is higher quality and environment-independent vs radio RSSI noise. nRFCrypto.begin(); nRFCrypto.Random.generate(dest, (uint16_t)sz); diff --git a/variants/heltec_t096/platformio.ini b/variants/heltec_t096/platformio.ini index fae7d642..2f440e83 100644 --- a/variants/heltec_t096/platformio.ini +++ b/variants/heltec_t096/platformio.ini @@ -29,7 +29,7 @@ build_flags = ${nrf52_base.build_flags} -D SX126X_DIO3_TCXO_VOLTAGE=1.8 -D SX126X_CURRENT_LIMIT=140 -D SX126X_RX_BOOSTED_GAIN=1 - -D USE_CC310_ED25519=1 + -D USE_CC310_HW_CRYPTO=1 -D PIN_VEXT_EN=26 ; Vext is connected to VDD which is also connected to TFT & GPS -D PIN_VEXT_EN_ACTIVE=HIGH -D PIN_GPS_RX=25 diff --git a/variants/rak3401/platformio.ini b/variants/rak3401/platformio.ini index 9537fc7f..ea53b2dc 100644 --- a/variants/rak3401/platformio.ini +++ b/variants/rak3401/platformio.ini @@ -13,7 +13,7 @@ build_flags = ${nrf52_base.build_flags} -D SX126X_CURRENT_LIMIT=140 -D SX126X_RX_BOOSTED_GAIN=1 -D SX126X_REGISTER_PATCH=1 ; Patch register 0x8B5 for improved RX with SKY66122 FEM - -D USE_CC310_ED25519=1 + -D USE_CC310_HW_CRYPTO=1 build_src_filter = ${nrf52_base.build_src_filter} +<../variants/rak3401> + diff --git a/variants/rak4631/platformio.ini b/variants/rak4631/platformio.ini index f6b634ad..f94f7e30 100644 --- a/variants/rak4631/platformio.ini +++ b/variants/rak4631/platformio.ini @@ -22,7 +22,7 @@ build_flags = ${nrf52_base.build_flags} -D LORA_TX_POWER=22 -D SX126X_CURRENT_LIMIT=140 -D SX126X_RX_BOOSTED_GAIN=1 - -D USE_CC310_ED25519=1 + -D USE_CC310_HW_CRYPTO=1 -D ENV_INCLUDE_RAK12035=1 -UENV_INCLUDE_BME680 -D ENV_INCLUDE_BME680_BSEC=1 diff --git a/variants/t1000-e/platformio.ini b/variants/t1000-e/platformio.ini index 9218c578..d5e3bb53 100644 --- a/variants/t1000-e/platformio.ini +++ b/variants/t1000-e/platformio.ini @@ -18,7 +18,7 @@ build_flags = ${nrf52_base.build_flags} -D LORA_TX_POWER=22 -D RF_SWITCH_TABLE -D RX_BOOSTED_GAIN=true - -D USE_CC310_ED25519=1 + -D USE_CC310_HW_CRYPTO=1 -D P_LORA_BUSY=7 ; P0.7 -D P_LORA_SCLK=11 ; P0.11 -D P_LORA_NSS=12 ; P0.12 From f6651882666a32843dbb1ea94a1f2c6f382fba05 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Fri, 17 Jul 2026 16:05:10 +1000 Subject: [PATCH 018/381] * new NodePrefs for companion --- examples/companion_radio/DataStore.cpp | 70 +++++++----------- examples/companion_radio/DataStore.h | 6 +- examples/companion_radio/MyMesh.cpp | 13 ++-- examples/companion_radio/MyMesh.h | 6 +- examples/companion_radio/NodePrefs.h | 99 +++++++++++++++++++++++++- src/helpers/ConfigSerializer.cpp | 17 +++++ src/helpers/ConfigSerializer.h | 1 + 7 files changed, 155 insertions(+), 57 deletions(-) diff --git a/examples/companion_radio/DataStore.cpp b/examples/companion_radio/DataStore.cpp index 0f3a0f9c..06c56a7a 100644 --- a/examples/companion_radio/DataStore.cpp +++ b/examples/companion_radio/DataStore.cpp @@ -189,17 +189,22 @@ bool DataStore::saveMainIdentity(const mesh::LocalIdentity &identity) { return identity_store.save("_main", identity); } -void DataStore::loadPrefs(NodePrefs& prefs, double& node_lat, double& node_lon) { - if (_fs->exists("/new_prefs")) { - loadPrefsInt("/new_prefs", prefs, node_lat, node_lon); // new filename - } else if (_fs->exists("/node_prefs")) { - loadPrefsInt("/node_prefs", prefs, node_lat, node_lon); - savePrefs(prefs, node_lat, node_lon); // save to new filename - _fs->remove("/node_prefs"); // remove old +void DataStore::loadPrefs(NodePrefs& prefs) { + if (_fs->exists("/prefs.json")) { + File file = openRead(_fs, "/prefs.json"); + if (file) { + prefs.loadSerial(file); // new Serial prefs + file.close(); + } + } else if (_fs->exists("/new_prefs")) { + loadPrefsInt("/new_prefs", prefs); + if (savePrefs(prefs) ) { // save to new format + //_fs->remove("/new_prefs"); // remove old + } } } -void DataStore::loadPrefsInt(const char *filename, NodePrefs& _prefs, double& node_lat, double& node_lon) { +void DataStore::loadPrefsInt(const char *filename, NodePrefs& _prefs) { File file = openRead(_fs, filename); if (file) { uint8_t pad[8]; @@ -207,12 +212,12 @@ void DataStore::loadPrefsInt(const char *filename, NodePrefs& _prefs, double& no file.read((uint8_t *)&_prefs.airtime_factor, sizeof(float)); // 0 file.read((uint8_t *)_prefs.node_name, sizeof(_prefs.node_name)); // 4 file.read(pad, 4); // 36 - file.read((uint8_t *)&node_lat, sizeof(node_lat)); // 40 - file.read((uint8_t *)&node_lon, sizeof(node_lon)); // 48 + file.read((uint8_t *)&_prefs.node_lat, sizeof(_prefs.node_lat)); // 40 + file.read((uint8_t *)&_prefs.node_lon, sizeof(_prefs.node_lon)); // 48 file.read((uint8_t *)&_prefs.freq, sizeof(_prefs.freq)); // 56 file.read((uint8_t *)&_prefs.sf, sizeof(_prefs.sf)); // 60 file.read((uint8_t *)&_prefs.cr, sizeof(_prefs.cr)); // 61 - file.read((uint8_t *)&_prefs.client_repeat, sizeof(_prefs.client_repeat)); // 62 + file.read((uint8_t *)&_prefs._client_repeat, sizeof(_prefs._client_repeat)); // 62 file.read((uint8_t *)&_prefs.manual_add_contacts, sizeof(_prefs.manual_add_contacts)); // 63 file.read((uint8_t *)&_prefs.bw, sizeof(_prefs.bw)); // 64 file.read((uint8_t *)&_prefs.tx_power_dbm, sizeof(_prefs.tx_power_dbm)); // 68 @@ -234,48 +239,21 @@ void DataStore::loadPrefsInt(const char *filename, NodePrefs& _prefs, double& no file.read((uint8_t *)_prefs.default_scope_name, sizeof(_prefs.default_scope_name)); // 90 file.read((uint8_t *)_prefs.default_scope_key, sizeof(_prefs.default_scope_key)); // 121 + // migrate old fields + _prefs.setRepeatEn(_prefs._client_repeat != 0); + file.close(); } } -void DataStore::savePrefs(const NodePrefs& _prefs, double node_lat, double node_lon) { - File file = openWrite(_fs, "/new_prefs"); +bool DataStore::savePrefs(NodePrefs& _prefs) { + File file = openWrite(_fs, "/prefs.json"); if (file) { - uint8_t pad[8]; - memset(pad, 0, sizeof(pad)); - - file.write((uint8_t *)&_prefs.airtime_factor, sizeof(float)); // 0 - file.write((uint8_t *)_prefs.node_name, sizeof(_prefs.node_name)); // 4 - file.write(pad, 4); // 36 - file.write((uint8_t *)&node_lat, sizeof(node_lat)); // 40 - file.write((uint8_t *)&node_lon, sizeof(node_lon)); // 48 - file.write((uint8_t *)&_prefs.freq, sizeof(_prefs.freq)); // 56 - file.write((uint8_t *)&_prefs.sf, sizeof(_prefs.sf)); // 60 - file.write((uint8_t *)&_prefs.cr, sizeof(_prefs.cr)); // 61 - file.write((uint8_t *)&_prefs.client_repeat, sizeof(_prefs.client_repeat)); // 62 - file.write((uint8_t *)&_prefs.manual_add_contacts, sizeof(_prefs.manual_add_contacts)); // 63 - file.write((uint8_t *)&_prefs.bw, sizeof(_prefs.bw)); // 64 - file.write((uint8_t *)&_prefs.tx_power_dbm, sizeof(_prefs.tx_power_dbm)); // 68 - file.write((uint8_t *)&_prefs.telemetry_mode_base, sizeof(_prefs.telemetry_mode_base)); // 69 - file.write((uint8_t *)&_prefs.telemetry_mode_loc, sizeof(_prefs.telemetry_mode_loc)); // 70 - file.write((uint8_t *)&_prefs.telemetry_mode_env, sizeof(_prefs.telemetry_mode_env)); // 71 - file.write((uint8_t *)&_prefs.rx_delay_base, sizeof(_prefs.rx_delay_base)); // 72 - file.write((uint8_t *)&_prefs.advert_loc_policy, sizeof(_prefs.advert_loc_policy)); // 76 - file.write((uint8_t *)&_prefs.multi_acks, sizeof(_prefs.multi_acks)); // 77 - file.write((uint8_t *)&_prefs.path_hash_mode, sizeof(_prefs.path_hash_mode)); // 78 - file.write(pad, 1); // 79 - file.write((uint8_t *)&_prefs.ble_pin, sizeof(_prefs.ble_pin)); // 80 - file.write((uint8_t *)&_prefs.buzzer_quiet, sizeof(_prefs.buzzer_quiet)); // 84 - file.write((uint8_t *)&_prefs.gps_enabled, sizeof(_prefs.gps_enabled)); // 85 - file.write((uint8_t *)&_prefs.gps_interval, sizeof(_prefs.gps_interval)); // 86 - file.write((uint8_t *)&_prefs.autoadd_config, sizeof(_prefs.autoadd_config)); // 87 - file.write((uint8_t *)&_prefs.autoadd_max_hops, sizeof(_prefs.autoadd_max_hops)); // 88 - file.write((uint8_t *)&_prefs.rx_boosted_gain, sizeof(_prefs.rx_boosted_gain)); // 89 - file.write((uint8_t *)_prefs.default_scope_name, sizeof(_prefs.default_scope_name)); // 90 - file.write((uint8_t *)_prefs.default_scope_key, sizeof(_prefs.default_scope_key)); // 121 - + bool success = _prefs.saveSerial(file); file.close(); + return success; } + return false; } void DataStore::loadContacts(DataStoreHost* host) { diff --git a/examples/companion_radio/DataStore.h b/examples/companion_radio/DataStore.h index af5ee7af..e0a145ca 100644 --- a/examples/companion_radio/DataStore.h +++ b/examples/companion_radio/DataStore.h @@ -19,7 +19,7 @@ class DataStore { mesh::RTCClock* _clock; IdentityStore identity_store; - void loadPrefsInt(const char *filename, NodePrefs& prefs, double& node_lat, double& node_lon); + void loadPrefsInt(const char *filename, NodePrefs& prefs); #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) void checkAdvBlobFile(); #endif @@ -33,8 +33,8 @@ public: FILESYSTEM* getSecondaryFS() const { return _fsExtra; } bool loadMainIdentity(mesh::LocalIdentity &identity); bool saveMainIdentity(const mesh::LocalIdentity &identity); - void loadPrefs(NodePrefs& prefs, double& node_lat, double& node_lon); - void savePrefs(const NodePrefs& prefs, double node_lat, double node_lon); + void loadPrefs(NodePrefs& prefs); + bool savePrefs(NodePrefs& prefs); void loadContacts(DataStoreHost* host); void saveContacts(DataStoreHost* host, bool (*filter)(const ContactInfo& c) = NULL); void loadChannels(DataStoreHost* host); diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index a78fd29a..1423d1ff 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -483,7 +483,7 @@ bool MyMesh::filterRecvFloodPacket(mesh::Packet* packet) { } bool MyMesh::allowPacketForward(const mesh::Packet* packet) { - return _prefs.client_repeat != 0; + return _prefs.isRepeatEn(); } void MyMesh::sendFloodScoped(const TransportKey& scope, mesh::Packet* pkt, uint32_t delay_millis) { @@ -876,7 +876,7 @@ MyMesh::MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMe send_unscoped = false; // defaults - memset(&_prefs, 0, sizeof(_prefs)); + //memset(&_prefs, 0, sizeof(_prefs)); _prefs.airtime_factor = 1.0; strcpy(_prefs.node_name, "NONAME"); _prefs.freq = LORA_FREQ; @@ -887,6 +887,7 @@ MyMesh::MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMe _prefs.gps_enabled = 0; // GPS disabled by default _prefs.gps_interval = 0; // No automatic GPS updates by default //_prefs.rx_delay_base = 10.0f; enable once new algo fixed + _prefs.setRepeatEn(false); #if defined(USE_SX1262) || defined(USE_SX1268) #ifdef SX126X_RX_BOOSTED_GAIN _prefs.rx_boosted_gain = SX126X_RX_BOOSTED_GAIN; @@ -931,7 +932,9 @@ void MyMesh::begin(bool has_display) { #endif // load persisted prefs - _store->loadPrefs(_prefs, sensors.node_lat, sensors.node_lon); + _store->loadPrefs(_prefs); + sensors.node_lat = _prefs.node_lat; + sensors.node_lon = _prefs.node_lon; // sanitise bad pref values _prefs.rx_delay_base = constrain(_prefs.rx_delay_base, 0, 20.0f); @@ -1031,7 +1034,7 @@ void MyMesh::handleCmdFrame(size_t len) { i += 40; StrHelper::strzcpy((char *)&out_frame[i], FIRMWARE_VERSION, 20); i += 20; - out_frame[i++] = _prefs.client_repeat; // v9+ + out_frame[i++] = _prefs.isRepeatEn() ? 1 : 0; // v9+ out_frame[i++] = _prefs.path_hash_mode; // v10+ _serial->writeFrame(out_frame, i); } else if (cmd_frame[0] == CMD_APP_START && @@ -1393,7 +1396,7 @@ void MyMesh::handleCmdFrame(size_t len) { _prefs.cr = cr; _prefs.freq = (float)freq / 1000.0; _prefs.bw = (float)bw / 1000.0; - _prefs.client_repeat = repeat; + _prefs.setRepeatEn(repeat != 0); savePrefs(); radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr); diff --git a/examples/companion_radio/MyMesh.h b/examples/companion_radio/MyMesh.h index f4190f30..d95b073f 100644 --- a/examples/companion_radio/MyMesh.h +++ b/examples/companion_radio/MyMesh.h @@ -165,7 +165,11 @@ protected: } public: - void savePrefs() { _store->savePrefs(_prefs, sensors.node_lat, sensors.node_lon); } + void savePrefs() { + _prefs.node_lat = sensors.node_lat; + _prefs.node_lon = sensors.node_lon; + _store->savePrefs(_prefs); + } #if ENV_INCLUDE_GPS == 1 void applyGpsPrefs() { diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index 48c381ce..521693f3 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -1,5 +1,6 @@ #pragma once #include // For uint8_t, uint32_t +#include #define TELEM_MODE_DENY 0 #define TELEM_MODE_ALLOW_FLAGS 1 // use contact.flags @@ -8,9 +9,11 @@ #define ADVERT_LOC_NONE 0 #define ADVERT_LOC_SHARE 1 -struct NodePrefs { // persisted to file +class NodePrefs : public ConfigSerializer { // persisted to file +public: float airtime_factor; char node_name[32]; + double node_lat, node_lon; float freq; uint8_t sf; uint8_t cr; @@ -29,9 +32,101 @@ struct NodePrefs { // persisted to file uint32_t gps_interval; // GPS read interval in seconds uint8_t autoadd_config; // bitmask for auto-add contacts config uint8_t rx_boosted_gain; // SX126x RX boosted gain mode (0=power saving, 1=boosted) - uint8_t client_repeat; + uint8_t _client_repeat; // DEPRECATED -> use repeat.disable_fwd uint8_t path_hash_mode; // which path mode to use when sending uint8_t autoadd_max_hops; // 0 = no limit, 1 = direct (0 hops), N = up to N-1 hops (max 64) char default_scope_name[31]; uint8_t default_scope_key[16]; + +private: + class RadioPrefs : public ConfigSerializer { // COPIED from CommonCLI (for now) + NodePrefs* _parent; + protected: + void structure() override { + def("freq", _parent->freq); + def("bw", _parent->bw); + def("sf", _parent->sf); + def("cr", _parent->cr); + //def("cad", _parent->cad_enabled); + //def("int_thr", _parent->interference_threshold); + def("rxgain", _parent->rx_boosted_gain); + def("fem_rxgain", _parent->rx_boosted_gain); + def("tx", _parent->tx_power_dbm); + def("af", _parent->airtime_factor); + def("rxdelay", _parent->rx_delay_base); + //def("f_txdelay", _parent->tx_delay_factor); currently hard-coded + //def("d_txdelay", _parent->direct_tx_delay_factor); currently hard-coded + //def("agc_int", _parent->agc_reset_interval); + def("hash_mode", _parent->path_hash_mode); + def("multi_ack", _parent->multi_acks); + } + public: + RadioPrefs(NodePrefs* parent) : _parent(parent) { } + }; + RadioPrefs radio; + + class GPSPrefs : public ConfigSerializer { // COPIED from CommionCLI (for now) + NodePrefs* _parent; + protected: + void structure() override { + def("en", _parent->gps_enabled); // boolean + def("int", _parent->gps_interval); // interval in seconds + def("adv_loc", _parent->advert_loc_policy); + } + public: + GPSPrefs(NodePrefs* parent) : _parent(parent) { } + }; + GPSPrefs gps; + + class RepeatPrefs : public ConfigSerializer { // COPIED from CommionCLI (for now) + public: + uint8_t disable_fwd = 1; + protected: + void structure() override { + def("disable", disable_fwd); + //def("f_max", flood_max); + //def("f_max_uns", flood_max_unscoped); + //def("f_max_adv", flood_max_advert); + //def("loop", loop_detect); + } + }; + RepeatPrefs repeat; + + class CompanionPrefs : public ConfigSerializer { + NodePrefs* _parent; + protected: + void structure() override { + def("auto_max", _parent->autoadd_max_hops); // 0 = no limit, 1 = direct (0 hops), N = up to N-1 hops (max 64) + def("defs_nm", _parent->default_scope_name, sizeof(_parent->default_scope_name)); + def("defs_key", (void *) _parent->default_scope_key, sizeof(_parent->default_scope_key)); + def("pin", _parent->ble_pin); + def("buzz_q", _parent->buzzer_quiet); + def("auto_add", _parent->autoadd_config); // bitmask for auto-add contacts config + def("man_add", _parent->manual_add_contacts); + def("tel_base", _parent->telemetry_mode_base); + def("tel_loc", _parent->telemetry_mode_loc); + def("tel_env", _parent->telemetry_mode_env); + } + public: + CompanionPrefs(NodePrefs* parent) : _parent(parent) { } + }; + CompanionPrefs companion; + +protected: + void structure() override { + def("name", node_name, sizeof(node_name)); + //def("adv_int", advert_interval); + //def("f_adv_int", flood_advert_interval); + def("lat", node_lat); + def("lon", node_lon); + def("radio", radio); + def("gps", gps); + def("repeat", repeat); + def("comp", companion); + } +public: + NodePrefs() : radio(this), gps(this), companion(this) { } + // new accessor methods + bool isRepeatEn() const { return repeat.disable_fwd == 0; } + void setRepeatEn(bool en) { repeat.disable_fwd = en ? 0 : 1; } }; \ No newline at end of file diff --git a/src/helpers/ConfigSerializer.cpp b/src/helpers/ConfigSerializer.cpp index 76673309..775ef220 100644 --- a/src/helpers/ConfigSerializer.cpp +++ b/src/helpers/ConfigSerializer.cpp @@ -140,6 +140,23 @@ void ConfigSerializer::writeComma() { } } +#include + +void ConfigSerializer::def(const char* key, void* value, size_t len) { + if (_context->op() == OP::WRITE) { + writeComma(); + _context->file()->print(key); + _context->file()->print(":\""); + mesh::Utils::printHex(*_context->file(), (uint8_t*) value, len); + _context->file()->print("\""); + } else { + if (_context->keyMatch(_depth, key)) { + memset(value, 0, len); + mesh::Utils::fromHex((uint8_t *)value, len, _context->getToken()); + } + } +} + void ConfigSerializer::def(const char* key, char* value, size_t max_len) { if (_context->op() == OP::WRITE) { writeComma(); diff --git a/src/helpers/ConfigSerializer.h b/src/helpers/ConfigSerializer.h index 5f0dc488..7e6d6f2a 100644 --- a/src/helpers/ConfigSerializer.h +++ b/src/helpers/ConfigSerializer.h @@ -48,6 +48,7 @@ protected: ConfigSerializer() { } void def(const char* key, char* value, size_t max_len); // max_len inclusive of null + void def(const char* key, void* value, size_t len); // binary blob (encoded in hex) void def(const char* key, int32_t& value); void def(const char* key, int16_t& value); void def(const char* key, int8_t& value); From bfb5310c6b299997e3859914d637e128279fdf6d Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Fri, 17 Jul 2026 20:55:30 +1000 Subject: [PATCH 019/381] * added unit tests for ConfigSerializer --- platformio.ini | 1 + src/helpers/ConfigSerializer.cpp | 4 +- test/mocks/Arduino.h | 3 + test/mocks/Stream.h | 67 ++++++++- .../test_config_serializer.cpp | 136 ++++++++++++++++++ 5 files changed, 206 insertions(+), 5 deletions(-) create mode 100644 test/mocks/Arduino.h create mode 100644 test/test_config_serializer/test_config_serializer.cpp diff --git a/platformio.ini b/platformio.ini index f3ada133..17f6c773 100644 --- a/platformio.ini +++ b/platformio.ini @@ -167,5 +167,6 @@ build_src_filter = -<*> +<../src/Utils.cpp> +<../src/Packet.cpp> + +<../src/helpers/ConfigSerializer.cpp> lib_deps = google/googletest @ 1.17.0 diff --git a/src/helpers/ConfigSerializer.cpp b/src/helpers/ConfigSerializer.cpp index 775ef220..9d1323e4 100644 --- a/src/helpers/ConfigSerializer.cpp +++ b/src/helpers/ConfigSerializer.cpp @@ -111,7 +111,7 @@ bool ConfigSerializer::loadSerial(Stream& s) { if (sp < CONFIG_MAX_DEPTH - 1) { sp++; } else { - Serial.printf("Error: max nesting reached"); // TODO: debug logging + //Serial.printf("Error: max nesting reached"); // TODO: debug logging context.success = false; break; } @@ -119,7 +119,7 @@ bool ConfigSerializer::loadSerial(Stream& s) { if (sp > 0) { sp--; } else { - Serial.printf("Error: too many closing '}'"); // TODO: debug logging + //Serial.printf("Error: too many closing '}'"); // TODO: debug logging context.success = false; break; } diff --git a/test/mocks/Arduino.h b/test/mocks/Arduino.h new file mode 100644 index 00000000..f0821bf4 --- /dev/null +++ b/test/mocks/Arduino.h @@ -0,0 +1,3 @@ +#pragma once + +#include diff --git a/test/mocks/Stream.h b/test/mocks/Stream.h index 195a3029..9b41c54d 100644 --- a/test/mocks/Stream.h +++ b/test/mocks/Stream.h @@ -1,10 +1,71 @@ #pragma once +#include +#include +#include + // Mock Stream class for native testing // Provides minimal interface needed by Utils.h -class Stream { +#define DEC 10 +#define HEX 16 +#define OCT 8 +#define BIN 2 + +class Print +{ public: - virtual void print(char c) {} - virtual void print(const char* str) {} + virtual size_t write(uint8_t b) { return 1; } + size_t write(const char *str) + { + if(str == NULL) { + return 0; + } + return write((const uint8_t *) str, strlen(str)); + } + virtual size_t write(const uint8_t *buffer, size_t size) { + size_t t = 0; + for (int i = 0; i < size; i++) { t += write(buffer[i]); } + return t; + } + size_t write(const char *buffer, size_t size) + { + return write((const uint8_t *) buffer, size); + } + + virtual size_t print(unsigned char b, int r = DEC) { return 0; } + virtual size_t print(int v, int r = DEC) { return 0; } + virtual size_t print(unsigned int v, int r = DEC) { return 0; } + virtual size_t print(long v, int r = DEC) { return 0; } + virtual size_t print(unsigned long v, int r = DEC) { return 0; } + virtual size_t print(long long v, int r = DEC) { return 0; } + virtual size_t print(unsigned long long v, int r = DEC) { return 0; } + virtual size_t print(double v, int p = 2) { return 0; } + + size_t print(char c) { return write(c); } + size_t print(const char* str) { return write(str); } + + //size_t println(void) { return 0; } + + virtual void flush() { /* Empty implementation for backward compatibility */ } }; + +class Stream: public Print +{ +public: + virtual int available() { return 0; } + virtual int read() { return -1; } + virtual int peek() { return 0; } + + virtual size_t readBytes(char *buffer, size_t length) { + size_t i = 0; + while (i < length && available()) { + buffer[i++] = read(); + } + return i; + } + virtual size_t readBytes(uint8_t *buffer, size_t length) + { + return readBytes((char *) buffer, length); + } +}; \ No newline at end of file diff --git a/test/test_config_serializer/test_config_serializer.cpp b/test/test_config_serializer/test_config_serializer.cpp new file mode 100644 index 00000000..d6ce6813 --- /dev/null +++ b/test/test_config_serializer/test_config_serializer.cpp @@ -0,0 +1,136 @@ +#include +#include "helpers/ConfigSerializer.h" + +#define TEST_INT_S "56" +#define TEST_INT 56 +#define TEST_FLOAT_S "-6.123" +#define TEST_FLOAT -6.1230f +#define TEST_DOUBLE_S "12.123456" +#define TEST_DOUBLE 12.123456 + +class MockInputStream : public Stream { + const char* _text; + int pos, len; +public: + MockInputStream(const char* text) : _text(text) { pos = 0; len = strlen(text); } + int available() override { return len - pos; } + int read() override { if (pos < len) { return _text[pos++]; } return -1; } + int peek() override { if (pos < len) { return _text[pos]; } return -1; } +}; + +class MockPrintStream : public Stream { + int len = 0; + uint8_t _buf[1024]; +public: + size_t write(uint8_t b) override { + if (len < sizeof(_buf)) { + _buf[len++] = b; + return 1; + } + return 0; + } + + size_t print(unsigned char b, int r) override { if (b == TEST_INT) return Print::print(TEST_INT_S); return 0; } + size_t print(int v, int r) override { if (v == TEST_INT) return Print::print(TEST_INT_S); return 0; } + size_t print(unsigned int v, int r) override { if (v == TEST_INT) return Print::print(TEST_INT_S); return 0; } + size_t print(long v, int r) override { if (v == TEST_INT) return Print::print(TEST_INT_S); return 0; } + size_t print(unsigned long v, int r) override { if (v == TEST_INT) return Print::print(TEST_INT_S); return 0; } + size_t print(long long v, int r) override { if (v == TEST_INT) return Print::print(TEST_INT_S); return 0; } + size_t print(unsigned long long v, int r) override { if (v == TEST_INT) return Print::print(TEST_INT_S); return 0; } + size_t print(double v, int p = 2) override { + if (p == 6) return Print::print(TEST_DOUBLE_S); + if (p == 4) return Print::print(TEST_FLOAT_S); + return 0; + } + + int getLength() const { return len; } + const uint8_t* getBytes() const { return _buf; } +}; + +class TestStruct : public ConfigSerializer { + protected: + void structure() override { + def("age", age); + def("flags", flags); + def("name", name, sizeof(name)); + } + public: + int32_t age; + char name[16]; + uint8_t flags; +}; + +// ── saveSerial: basic ─────────────────────────────────────────────────────── + +TEST(ConfigSerializer, SaveSerial_Basic) { + MockPrintStream s; + TestStruct data; + + data.age = TEST_INT; + data.flags = TEST_INT; + strcpy(data.name, "Scott"); + + bool success = data.saveSerial(s); + EXPECT_TRUE(success); + + auto l = s.getLength(); + const char* expect = "{age:" TEST_INT_S ",flags:" TEST_INT_S ",name:\"Scott\"}"; + EXPECT_EQ(strlen(expect), l); + + bool match = memcmp(s.getBytes(), expect, l) == 0; + EXPECT_TRUE(match); +} + +// ── loadSerial: basic ─────────────────────────────────────────────────────── + +TEST(ConfigSerializer, LoadSerial_Basic) { + MockInputStream s("{age:" TEST_INT_S ",flags:" TEST_INT_S ",name:\"Scott\"}"); + TestStruct data; + + bool success = data.loadSerial(s); + EXPECT_TRUE(success); + + EXPECT_EQ(TEST_INT, data.age); + EXPECT_EQ(TEST_INT, data.flags); + bool match = strcmp("Scott", data.name) == 0; + EXPECT_TRUE(match); +} + +TEST(ConfigSerializer, LoadSerial_UnmatchedBraces) { + MockInputStream s("{age:" TEST_INT_S ",flags:" TEST_INT_S ",name:\"Scott\""); + TestStruct data; + + bool success = data.loadSerial(s); + EXPECT_FALSE(success); +} + +TEST(ConfigSerializer, LoadSerial_MissingCommas) { + MockInputStream s("{age:" TEST_INT_S " flags:" TEST_INT_S " name:\"Scott\"}"); + TestStruct data; + + bool success = data.loadSerial(s); + EXPECT_FALSE(success); +} + +TEST(ConfigSerializer, LoadSerial_IgnoreUnknowns) { + MockInputStream s("{age:" TEST_INT_S ",xxx:" TEST_INT_S ",name:\"Scott\"}"); + TestStruct data; + data.flags = 1; + + // should ignore the 'xxx' property + bool success = data.loadSerial(s); + EXPECT_TRUE(success); + + EXPECT_EQ(TEST_INT, data.age); + EXPECT_EQ(1, data.flags); // flags should be unmodified + bool match = strcmp("Scott", data.name) == 0; + EXPECT_TRUE(match); +} + + +// ── main ─────────────────────────────────────────────────────── + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} From dae73ac97138b734e4f5c047cd8a885d51b17d85 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Fri, 17 Jul 2026 21:23:40 +1000 Subject: [PATCH 020/381] * loadSerial(), support for \n and \r --- src/helpers/ConfigSerializer.cpp | 2 + .../test_config_serializer.cpp | 43 +++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/src/helpers/ConfigSerializer.cpp b/src/helpers/ConfigSerializer.cpp index 9d1323e4..adff147f 100644 --- a/src/helpers/ConfigSerializer.cpp +++ b/src/helpers/ConfigSerializer.cpp @@ -76,6 +76,8 @@ int ConfigSerializer::Context::readNext() { return TOK_ERROR; case EXPECT_STRING_ESCAPE: + if ((c == 'n') && rd_len < CONFIG_MAX_TOKEN_LEN-1) { rd_buf[rd_len++] = '\n'; rd_mode = EXPECT_STRING_VAL; return TOK_WHITESPACE; } + if ((c == 'r') && rd_len < CONFIG_MAX_TOKEN_LEN-1) { rd_buf[rd_len++] = '\r'; rd_mode = EXPECT_STRING_VAL; return TOK_WHITESPACE; } if ((c == '"' || c == '\\' || c == '/') && rd_len < CONFIG_MAX_TOKEN_LEN-1) { rd_buf[rd_len++] = c; rd_mode = EXPECT_STRING_VAL; return TOK_WHITESPACE; } return TOK_ERROR; // unsupport escape diff --git a/test/test_config_serializer/test_config_serializer.cpp b/test/test_config_serializer/test_config_serializer.cpp index d6ce6813..c63ea8e8 100644 --- a/test/test_config_serializer/test_config_serializer.cpp +++ b/test/test_config_serializer/test_config_serializer.cpp @@ -81,6 +81,25 @@ TEST(ConfigSerializer, SaveSerial_Basic) { EXPECT_TRUE(match); } +TEST(ConfigSerializer, SaveSerial_EscChars) { + MockPrintStream s; + TestStruct data; + + data.age = TEST_INT; + data.flags = TEST_INT; + strcpy(data.name, "\"Scott\"\n"); + + bool success = data.saveSerial(s); + EXPECT_TRUE(success); + + auto l = s.getLength(); + const char* expect = "{age:" TEST_INT_S ",flags:" TEST_INT_S ",name:\"\\\"Scott\\\"\\n\"}"; + EXPECT_EQ(strlen(expect), l); + + bool match = memcmp(s.getBytes(), expect, l) == 0; + EXPECT_TRUE(match); +} + // ── loadSerial: basic ─────────────────────────────────────────────────────── TEST(ConfigSerializer, LoadSerial_Basic) { @@ -96,6 +115,30 @@ TEST(ConfigSerializer, LoadSerial_Basic) { EXPECT_TRUE(match); } +TEST(ConfigSerializer, LoadSerial_HandleWhitespace) { + MockInputStream s(" { age: " TEST_INT_S " , flags: " TEST_INT_S " , name: \"Scott\" } "); + TestStruct data; + + bool success = data.loadSerial(s); + EXPECT_TRUE(success); + + EXPECT_EQ(TEST_INT, data.age); + EXPECT_EQ(TEST_INT, data.flags); + bool match = strcmp("Scott", data.name) == 0; + EXPECT_TRUE(match); +} + +TEST(ConfigSerializer, LoadSerial_EscChars) { + MockInputStream s("{age:" TEST_INT_S ",flags:" TEST_INT_S ",name:\"\\\"Scott\\\"\\n\"}"); + TestStruct data; + + bool success = data.loadSerial(s); + EXPECT_TRUE(success); + + bool match = strcmp("\"Scott\"\n", data.name) == 0; + EXPECT_TRUE(match); +} + TEST(ConfigSerializer, LoadSerial_UnmatchedBraces) { MockInputStream s("{age:" TEST_INT_S ",flags:" TEST_INT_S ",name:\"Scott\""); TestStruct data; From 10434a1cfd686dd24157cb7492e96f593babd24d Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Sat, 18 Jul 2026 19:22:53 +1000 Subject: [PATCH 021/381] * added prefs initialisers to match original zeroed state --- examples/companion_radio/MyMesh.cpp | 1 - examples/companion_radio/NodePrefs.h | 52 +++++++++--------- src/helpers/CommonCLI.h | 80 +++++++++++++++------------- 3 files changed, 71 insertions(+), 62 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 1423d1ff..b8661caf 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -876,7 +876,6 @@ MyMesh::MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMe send_unscoped = false; // defaults - //memset(&_prefs, 0, sizeof(_prefs)); _prefs.airtime_factor = 1.0; strcpy(_prefs.node_name, "NONAME"); _prefs.freq = LORA_FREQ; diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index 521693f3..0c03bd78 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -11,30 +11,30 @@ class NodePrefs : public ConfigSerializer { // persisted to file public: - float airtime_factor; + float airtime_factor = 0; char node_name[32]; - double node_lat, node_lon; - float freq; - uint8_t sf; - uint8_t cr; - uint8_t multi_acks; - uint8_t manual_add_contacts; - float bw; - int8_t tx_power_dbm; - uint8_t telemetry_mode_base; - uint8_t telemetry_mode_loc; - uint8_t telemetry_mode_env; - float rx_delay_base; - uint32_t ble_pin; - uint8_t advert_loc_policy; - uint8_t buzzer_quiet; - uint8_t gps_enabled; // GPS enabled flag (0=disabled, 1=enabled) - uint32_t gps_interval; // GPS read interval in seconds - uint8_t autoadd_config; // bitmask for auto-add contacts config - uint8_t rx_boosted_gain; // SX126x RX boosted gain mode (0=power saving, 1=boosted) - uint8_t _client_repeat; // DEPRECATED -> use repeat.disable_fwd - uint8_t path_hash_mode; // which path mode to use when sending - uint8_t autoadd_max_hops; // 0 = no limit, 1 = direct (0 hops), N = up to N-1 hops (max 64) + double node_lat = 0, node_lon = 0; + float freq = 0; + uint8_t sf = 0; + uint8_t cr = 0; + uint8_t multi_acks = 0; + uint8_t manual_add_contacts = 0; + float bw = 0; + int8_t tx_power_dbm = 0; + uint8_t telemetry_mode_base = 0; + uint8_t telemetry_mode_loc = 0; + uint8_t telemetry_mode_env = 0; + float rx_delay_base = 0; + uint32_t ble_pin = 0; + uint8_t advert_loc_policy = 0; + uint8_t buzzer_quiet = 0; + uint8_t gps_enabled = 0; // GPS enabled flag (0=disabled, 1=enabled) + uint32_t gps_interval = 0; // GPS read interval in seconds + uint8_t autoadd_config = 0; // bitmask for auto-add contacts config + uint8_t rx_boosted_gain = 0; // SX126x RX boosted gain mode (0=power saving, 1=boosted) + uint8_t _client_repeat = 0; // DEPRECATED -> use repeat.disable_fwd + uint8_t path_hash_mode = 0; // which path mode to use when sending + uint8_t autoadd_max_hops = 0; // 0 = no limit, 1 = direct (0 hops), N = up to N-1 hops (max 64) char default_scope_name[31]; uint8_t default_scope_key[16]; @@ -125,7 +125,11 @@ protected: def("comp", companion); } public: - NodePrefs() : radio(this), gps(this), companion(this) { } + NodePrefs() : radio(this), gps(this), companion(this) { + node_name[0] = 0; + default_scope_name[0] = 0; + memset(default_scope_key, 0, sizeof(default_scope_key)); + } // new accessor methods bool isRepeatEn() const { return repeat.disable_fwd == 0; } void setRepeatEn(bool en) { repeat.disable_fwd = en ? 0 : 1; } diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index aab33d11..69fe0315 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -23,51 +23,51 @@ class NodePrefs : public ConfigSerializer { public: // in-memory backing data - float airtime_factor; + float airtime_factor = 0; char node_name[32]; - double node_lat, node_lon; + double node_lat = 0, node_lon = 0; char password[16]; - float freq; - int8_t tx_power_dbm; - uint8_t disable_fwd; - uint8_t advert_interval; // minutes / 2 - uint8_t flood_advert_interval; // hours - float rx_delay_base; - float tx_delay_factor; + float freq = 0; + int8_t tx_power_dbm = 0; + uint8_t disable_fwd = 0; + uint8_t advert_interval = 0; // minutes / 2 + uint8_t flood_advert_interval = 0; // hours + float rx_delay_base = 0; + float tx_delay_factor = 0; char guest_password[16]; - float direct_tx_delay_factor; + float direct_tx_delay_factor = 0; uint32_t guard; - uint8_t sf; - uint8_t cr; - uint8_t allow_read_only; - uint8_t multi_acks; - float bw; - uint8_t flood_max; - uint8_t flood_max_unscoped; - uint8_t flood_max_advert; - uint8_t interference_threshold; - uint8_t agc_reset_interval; // secs / 4 + uint8_t sf = 0; + uint8_t cr = 0; + uint8_t allow_read_only = 0; + uint8_t multi_acks = 0; + float bw = 0; + uint8_t flood_max = 0; + uint8_t flood_max_unscoped = 0; + uint8_t flood_max_advert = 0; + uint8_t interference_threshold = 0; + uint8_t agc_reset_interval = 0; // secs / 4 // Bridge settings - uint8_t bridge_enabled; // boolean - uint16_t bridge_delay; // milliseconds (default 500 ms) - uint8_t bridge_pkt_src; // 0 = logTx, 1 = logRx (default logTx) - uint32_t bridge_baud; // 9600, 19200, 38400, 57600, 115200 (default 115200) - uint8_t bridge_channel; // 1-14 (ESP-NOW only) + uint8_t bridge_enabled = 0; // boolean + uint16_t bridge_delay = 0; // milliseconds (default 500 ms) + uint8_t bridge_pkt_src = 0; // 0 = logTx, 1 = logRx (default logTx) + uint32_t bridge_baud = 0; // 9600, 19200, 38400, 57600, 115200 (default 115200) + uint8_t bridge_channel = 0; // 1-14 (ESP-NOW only) char bridge_secret[16]; // for XOR encryption of bridge packets (ESP-NOW only) // Power setting - uint8_t powersaving_enabled; // boolean + uint8_t powersaving_enabled = 0; // boolean // Gps settings - uint8_t gps_enabled; - uint32_t gps_interval; // in seconds - uint8_t advert_loc_policy; - uint32_t discovery_mod_timestamp; - float adc_multiplier; + uint8_t gps_enabled = 0; + uint32_t gps_interval = 0; // in seconds + uint8_t advert_loc_policy = 0; + uint32_t discovery_mod_timestamp = 0; + float adc_multiplier = 0; char owner_info[120]; - uint8_t rx_boosted_gain; // power settings - uint8_t radio_fem_rxgain; // LoRa FEM RX gain setting - uint8_t path_hash_mode; // which path mode to use when sending - uint8_t loop_detect; - uint8_t cad_enabled; // hardware Channel Activity Detection before TX (boolean) + uint8_t rx_boosted_gain = 0; // power settings + uint8_t radio_fem_rxgain = 0; // LoRa FEM RX gain setting + uint8_t path_hash_mode = 0; // which path mode to use when sending + uint8_t loop_detect = 0; + uint8_t cad_enabled = 0; // hardware Channel Activity Detection before TX (boolean) private: class RadioPrefs : public ConfigSerializer { @@ -182,7 +182,13 @@ protected: } public: - NodePrefs() : ConfigSerializer(), bridge(this), gps(this), radio(this), power(this), repeat(this), room(this) { } + NodePrefs() : ConfigSerializer(), bridge(this), gps(this), radio(this), power(this), repeat(this), room(this) { + node_name[0] = 0; + password[0] = 0; + guest_password[0] = 0; + bridge_secret[0] = 0; + owner_info[0] = 0; + } }; class CommonCLICallbacks { From c34c368e3f4555ebfe69c776c8bc1077daf8fc83 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Sat, 18 Jul 2026 20:12:21 +1000 Subject: [PATCH 022/381] * RP2040 build fixes * new prefs file now "/prefs.json" --- examples/companion_radio/NodePrefs.h | 4 ++-- platformio.ini | 2 +- src/helpers/CommonCLI.cpp | 16 ++++++++++------ 3 files changed, 13 insertions(+), 9 deletions(-) diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index 0c03bd78..39a5386a 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -65,7 +65,7 @@ private: }; RadioPrefs radio; - class GPSPrefs : public ConfigSerializer { // COPIED from CommionCLI (for now) + class GPSPrefs : public ConfigSerializer { // COPIED from CommonCLI (for now) NodePrefs* _parent; protected: void structure() override { @@ -78,7 +78,7 @@ private: }; GPSPrefs gps; - class RepeatPrefs : public ConfigSerializer { // COPIED from CommionCLI (for now) + class RepeatPrefs : public ConfigSerializer { // COPIED from CommonCLI (for now) public: uint8_t disable_fwd = 1; protected: diff --git a/platformio.ini b/platformio.ini index 17f6c773..fd0afcdf 100644 --- a/platformio.ini +++ b/platformio.ini @@ -100,7 +100,7 @@ lib_deps = extends = arduino_base upload_protocol = picotool board_build.core = earlephilhower -platform = https://github.com/maxgerhardt/platform-raspberrypi.git#4e22a0d ; framework-arduinopico @ 1.50600.0+sha.6a1d13e9 +platform = https://github.com/maxgerhardt/platform-raspberrypi.git ; framework-arduinopico @ 1.50600.0+sha.6a1d13e9 build_flags = ${arduino_base.build_flags} -D RP2040_PLATFORM diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index 56a46d46..9d0571d9 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -28,8 +28,12 @@ static bool isValidName(const char *n) { } void CommonCLI::loadPrefs(FILESYSTEM* fs) { - if (fs->exists("/ser_prefs")) { - File file = fs->open("/ser_prefs"); + if (fs->exists("/prefs.json")) { +#if defined(RP2040_PLATFORM) + File file = fs->open("/prefs.json", "r"); +#else + File file = fs->open("/prefs.json"); +#endif if (file) { _prefs->loadSerial(file); // new Serial prefs file.close(); @@ -137,12 +141,12 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) { // Legacy bool CommonCLI::savePrefs(FILESYSTEM* fs) { #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) - fs->remove("/ser_prefs"); - File file = fs->open("/ser_prefs", FILE_O_WRITE); + fs->remove("/prefs.json"); + File file = fs->open("/prefs.json", FILE_O_WRITE); #elif defined(RP2040_PLATFORM) - File file = fs->open("/ser_prefs", "w"); + File file = fs->open("/prefs.json", "w"); #else - File file = fs->open("/ser_prefs", "w", true); + File file = fs->open("/prefs.json", "w", true); #endif if (file) { bool success = _prefs->saveSerial(file); From 2679fa8ebc182bbe34875975170f3a135a50b1ed Mon Sep 17 00:00:00 2001 From: ViezeVingertjes Date: Mon, 22 Jun 2026 16:12:00 +0200 Subject: [PATCH 023/381] fix: prevent ESP32 KISS modem stalls under USB backpressure Switch ESP32-S3 KISS modem environments to HWCDC and move outbound KISS writes to a non-blocking queued frame path so loop() and TX completion keep progressing when the host reads slowly. Add native backpressure regression tests and correct the native_kiss_modem test filter so this suite runs directly with pio test. --- docs/kiss_modem_protocol.md | 14 +- examples/kiss_modem/KissModem.cpp | 199 ++++++++++-- examples/kiss_modem/KissModem.h | 36 ++- examples/kiss_modem/main.cpp | 10 +- platformio.ini | 15 + test/mocks/Arduino.h | 17 + test/mocks/CayenneLPP.h | 11 + test/mocks/Identity.h | 39 +++ test/mocks/Mesh.h | 27 ++ test/mocks/Stream.h | 21 +- test/mocks/Utils.h | 44 +++ test/mocks/helpers/SensorManager.h | 10 + test/test_kiss_modem/test_tx_backpressure.cpp | 294 ++++++++++++++++++ variants/heltec_v4/platformio.ini | 5 + variants/station_g2/platformio.ini | 5 + 15 files changed, 701 insertions(+), 46 deletions(-) create mode 100644 test/mocks/Arduino.h create mode 100644 test/mocks/CayenneLPP.h create mode 100644 test/mocks/Identity.h create mode 100644 test/mocks/Mesh.h create mode 100644 test/mocks/Utils.h create mode 100644 test/mocks/helpers/SensorManager.h create mode 100644 test/test_kiss_modem/test_tx_backpressure.cpp diff --git a/docs/kiss_modem_protocol.md b/docs/kiss_modem_protocol.md index 9a996224..3f4dbf9c 100644 --- a/docs/kiss_modem_protocol.md +++ b/docs/kiss_modem_protocol.md @@ -41,7 +41,7 @@ Maximum unescaped frame size: 512 bytes. | Command | Value | Data | Description | |-------------|--------|--------------------|-------------------------------------------------------------| -| Data | `0x00` | Raw packet | Queue packet for transmission | +| Data | `0x00` | Raw packet | Queue packet for transmission (one pending at a time) | | TXDELAY | `0x01` | Delay (1 byte) | Transmitter keyup delay in 10ms units (default: 50 = 500ms) | | Persistence | `0x02` | P (1 byte) | CSMA persistence parameter 0-255 (default: 63) | | SlotTime | `0x03` | Interval (1 byte) | CSMA slot interval in 10ms units (default: 10 = 100ms) | @@ -58,6 +58,12 @@ Maximum unescaped frame size: 512 bytes. Data frames carry raw packet data only, with no metadata prepended. The Data command payload is limited to 255 bytes to match the MeshCore maximum transmission unit (MAX_TRANS_UNIT); frames larger than 255 bytes are silently dropped. The KISS specification recommends at least 1024 bytes for general-purpose TNCs; this modem is intended for MeshCore packets only, whose protocol MTU is 255 bytes. +Only one packet may be pending for radio transmission at a time. If the host sends a second Data frame before the first has completed, the modem responds with Error (0xF1) and TxBusy (0x07). + +### Host Output Backpressure + +Outbound frames are encoded into a 2-slot queue and flushed when serial output space is available; `loop()` never blocks on writes. Radio TX state advances independently of host read speed. TxDone is retained until it can be queued. If the outbound queue is full, the modem responds with Error (0xF1) and TxBusy (0x07). Hosts should read serial promptly to avoid delayed responses. + ### CSMA Behavior The TNC implements p-persistent CSMA for half-duplex operation: @@ -156,15 +162,15 @@ Response codes use the high-bit convention: `response = command | 0x80`. Generic | MacFailed | `0x04` | MAC verification failed | | UnknownCmd | `0x05` | Unknown sub-command | | EncryptFailed | `0x06` | Encryption failed | -| TxBusy | `0x07` | Transmit busy | +| TxBusy | `0x07` | Radio TX busy, or host output queue full | ### Unsolicited Events The TNC sends these SetHardware frames without a preceding request: -**TxDone (0xF8)**: Sent after a packet has been transmitted. Contains a single byte: 0x01 for success, 0x00 for failure. +**TxDone (0xF8)**: Sent after radio transmission completes. Contains a single byte: 0x01 for success, 0x00 for failure. Delivery to the host may be delayed under serial backpressure but is not dropped. -**RxMeta (0xF9)**: Sent immediately after each standard data frame (type 0x00) with metadata for the received packet. Contains SNR (1 byte, signed, value x4 for 0.25 dB precision) followed by RSSI (1 byte, signed, dBm). Enabled by default; can be toggled with SetSignalReport. Standard KISS clients ignore this frame. +**RxMeta (0xF9)**: Sent after each standard data frame (type 0x00) with SNR (1 byte, signed, value x4) and RSSI (1 byte, signed, dBm). Queued with the data frame; omitted if the data frame cannot be queued. Enabled by default; toggle with SetSignalReport. Standard KISS clients ignore this frame. ## Data Formats diff --git a/examples/kiss_modem/KissModem.cpp b/examples/kiss_modem/KissModem.cpp index eeab1501..7dcfc8d7 100644 --- a/examples/kiss_modem/KissModem.cpp +++ b/examples/kiss_modem/KissModem.cpp @@ -22,6 +22,7 @@ KissModem::KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& r _getStatsCallback = nullptr; _config = {0, 0, 0, 0, 0}; _signal_report_enabled = true; + resetOutputQueue(); } void KissModem::begin() { @@ -30,37 +31,168 @@ void KissModem::begin() { _rx_active = false; _has_pending_tx = false; _tx_state = TX_IDLE; + resetOutputQueue(); } -void KissModem::writeByte(uint8_t b) { - if (b == KISS_FEND) { - _serial.write(KISS_FESC); - _serial.write(KISS_TFEND); - } else if (b == KISS_FESC) { - _serial.write(KISS_FESC); - _serial.write(KISS_TFESC); - } else { - _serial.write(b); +void KissModem::resetOutputQueue() { + _tx_frame_head = 0; + _tx_frame_tail = 0; + _tx_frame_count = 0; + _tx_busy_error_pending = false; + _tx_done_pending = false; + _tx_done_result = 0; +} + +void KissModem::popTxFrame() { + _tx_frame_head = (uint8_t)((_tx_frame_head + 1) % KISS_TX_FRAME_QUEUE_DEPTH); + _tx_frame_count--; +} + +uint16_t KissModem::appendEscapedByte(uint8_t* dest, uint16_t idx, uint16_t max_len, uint8_t b) { + if (b == KISS_FEND || b == KISS_FESC) { + if (idx + 2 > max_len) { + return 0; + } + dest[idx++] = KISS_FESC; + dest[idx++] = (b == KISS_FEND) ? KISS_TFEND : KISS_TFESC; + return idx; } + if (idx + 1 > max_len) { + return 0; + } + dest[idx++] = b; + return idx; } -void KissModem::writeFrame(uint8_t type, const uint8_t* data, uint16_t len) { - _serial.write(KISS_FEND); - writeByte(type); +uint16_t KissModem::encodeFrame(uint8_t type, const uint8_t* data, uint16_t len, uint8_t* dest, uint16_t max_len) { + if (max_len < KISS_FRAME_BOUNDARY_BYTES) { + return 0; + } + + uint16_t idx = 0; + dest[idx++] = KISS_FEND; + + idx = appendEscapedByte(dest, idx, max_len, type); + if (idx == 0) { + return 0; + } + for (uint16_t i = 0; i < len; i++) { - writeByte(data[i]); + idx = appendEscapedByte(dest, idx, max_len, data[i]); + if (idx == 0) { + return 0; + } } - _serial.write(KISS_FEND); + + if (idx + 1 > max_len) { + return 0; + } + dest[idx++] = KISS_FEND; + return idx; } -void KissModem::writeHardwareFrame(uint8_t sub_cmd, const uint8_t* data, uint16_t len) { - _serial.write(KISS_FEND); - writeByte(KISS_CMD_SETHARDWARE); - writeByte(sub_cmd); - for (uint16_t i = 0; i < len; i++) { - writeByte(data[i]); +bool KissModem::tryFlushFrames() { + while (_tx_frame_count > 0) { + const uint8_t idx = _tx_frame_head; + const uint16_t frame_len = _tx_frame_len[idx]; + uint16_t written_len = _tx_frame_written[idx]; + + if (written_len >= frame_len) { + popTxFrame(); + continue; + } + + const int available = _serial.availableForWrite(); + if (available <= 0) { + return false; + } + + const uint16_t remaining = frame_len - written_len; + const uint16_t chunk_len = (available < (int)remaining) ? (uint16_t)available : remaining; + if (chunk_len == 0) { + return false; + } + + size_t chunk_written = _serial.write(_tx_frame_buf[idx] + written_len, chunk_len); + if (chunk_written == 0) { + return false; + } + + written_len += (uint16_t)chunk_written; + _tx_frame_written[idx] = written_len; + + if (written_len < frame_len) { + return false; + } + + popTxFrame(); } - _serial.write(KISS_FEND); + return true; +} + +bool KissModem::queueFrame(uint8_t type, const uint8_t* data, uint16_t len, bool mark_busy_error) { + if (_tx_frame_count >= KISS_TX_FRAME_QUEUE_DEPTH && !tryFlushFrames()) { + if (mark_busy_error) { + _tx_busy_error_pending = true; + } + return false; + } + const uint8_t idx = _tx_frame_tail; + uint16_t frame_len = encodeFrame(type, data, len, _tx_frame_buf[idx], sizeof(_tx_frame_buf[idx])); + if (frame_len == 0) { + return false; + } + + _tx_frame_len[idx] = frame_len; + _tx_frame_written[idx] = 0; + _tx_frame_tail = (uint8_t)((_tx_frame_tail + 1) % KISS_TX_FRAME_QUEUE_DEPTH); + _tx_frame_count++; + tryFlushFrames(); + return true; +} + +bool KissModem::queuePendingBusyError() { + if (!_tx_busy_error_pending) { + return true; + } + const uint8_t err = HW_ERR_TX_BUSY; + if (!queueHardwareFrame(HW_RESP_ERROR, &err, 1, false)) { + return false; + } + _tx_busy_error_pending = false; + return true; +} + +bool KissModem::queueHardwareFrame(uint8_t sub_cmd, const uint8_t* data, uint16_t len, bool mark_busy_error) { + if (len > KISS_MAX_FRAME_SIZE) { + return false; + } + _tx_hw_payload[0] = sub_cmd; + if (len > 0) { + memcpy(_tx_hw_payload + 1, data, len); + } + return queueFrame(KISS_CMD_SETHARDWARE, _tx_hw_payload, len + 1, mark_busy_error); +} + +bool KissModem::queuePendingTxDone() { + if (!_tx_done_pending) { + return true; + } + if (!queueHardwareFrame(HW_RESP_TX_DONE, &_tx_done_result, 1, false)) { + return false; + } + _tx_done_pending = false; + return true; +} + +void KissModem::setTxDonePending(uint8_t result) { + _tx_done_result = result; + _tx_done_pending = true; + _tx_state = TX_DONE_PENDING; +} + +bool KissModem::writeHardwareFrame(uint8_t sub_cmd, const uint8_t* data, uint16_t len) { + return queueHardwareFrame(sub_cmd, data, len, true); } void KissModem::writeHardwareError(uint8_t error_code) { @@ -68,6 +200,8 @@ void KissModem::writeHardwareError(uint8_t error_code) { } void KissModem::loop() { + tryFlushFrames(); + while (_serial.available()) { uint8_t b = _serial.read(); @@ -106,6 +240,8 @@ void KissModem::loop() { } processTx(); + tryFlushFrames(); + queuePendingBusyError(); } void KissModem::processFrame() { @@ -295,10 +431,7 @@ void KissModem::processTx() { _tx_timer = millis(); _tx_state = TX_SENDING; } else { - uint8_t result = 0x00; - writeHardwareFrame(HW_RESP_TX_DONE, &result, 1); - _has_pending_tx = false; - _tx_state = TX_IDLE; + setTxDonePending(0x00); } } break; @@ -306,14 +439,15 @@ void KissModem::processTx() { case TX_SENDING: if (_radio.isSendComplete()) { _radio.onSendFinished(); - uint8_t result = 0x01; - writeHardwareFrame(HW_RESP_TX_DONE, &result, 1); - _has_pending_tx = false; - _tx_state = TX_IDLE; + setTxDonePending(0x01); } else if (millis() - _tx_timer >= _radio.getEstAirtimeFor(_pending_tx_len) * KISS_TX_TIMEOUT_FACTOR) { _radio.onSendFinished(); - uint8_t result = 0x00; - writeHardwareFrame(HW_RESP_TX_DONE, &result, 1); + setTxDonePending(0x00); + } + break; + + case TX_DONE_PENDING: + if (queuePendingTxDone()) { _has_pending_tx = false; _tx_state = TX_IDLE; } @@ -322,8 +456,7 @@ void KissModem::processTx() { } void KissModem::onPacketReceived(int8_t snr, int8_t rssi, const uint8_t* packet, uint16_t len) { - writeFrame(KISS_CMD_DATA, packet, len); - if (_signal_report_enabled) { + if (queueFrame(KISS_CMD_DATA, packet, len) && _signal_report_enabled) { uint8_t meta[2] = { (uint8_t)snr, (uint8_t)rssi }; writeHardwareFrame(HW_RESP_RX_META, meta, 2); } diff --git a/examples/kiss_modem/KissModem.h b/examples/kiss_modem/KissModem.h index bbe99d6d..a23e459b 100644 --- a/examples/kiss_modem/KissModem.h +++ b/examples/kiss_modem/KissModem.h @@ -13,6 +13,14 @@ #define KISS_MAX_FRAME_SIZE 512 #define KISS_MAX_PACKET_SIZE 255 +#define KISS_FRAME_BOUNDARY_BYTES 2 +#define KISS_TYPE_BYTES 1 +#define KISS_HW_SUBCMD_BYTES 1 +#define KISS_MAX_ESCAPABLE_BYTES (KISS_MAX_FRAME_SIZE + KISS_TYPE_BYTES + KISS_HW_SUBCMD_BYTES) +#define KISS_MAX_ESCAPED_PAYLOAD_SIZE (2 * KISS_MAX_ESCAPABLE_BYTES) +#define KISS_MAX_ENCODED_FRAME_SIZE (KISS_FRAME_BOUNDARY_BYTES + KISS_MAX_ESCAPED_PAYLOAD_SIZE) +#define KISS_TX_FRAME_QUEUE_DEPTH 2 +#define KISS_HW_MAX_PAYLOAD_SIZE (KISS_MAX_FRAME_SIZE + KISS_HW_SUBCMD_BYTES) #define KISS_CMD_DATA 0x00 #define KISS_CMD_TXDELAY 0x01 @@ -94,7 +102,8 @@ enum TxState { TX_WAIT_CLEAR, TX_SLOT_WAIT, TX_DELAY, - TX_SENDING + TX_SENDING, + TX_DONE_PENDING }; class KissModem { @@ -130,10 +139,28 @@ class KissModem { RadioConfig _config; bool _signal_report_enabled; + uint8_t _tx_frame_buf[KISS_TX_FRAME_QUEUE_DEPTH][KISS_MAX_ENCODED_FRAME_SIZE]; + uint16_t _tx_frame_len[KISS_TX_FRAME_QUEUE_DEPTH]; + uint16_t _tx_frame_written[KISS_TX_FRAME_QUEUE_DEPTH]; + uint8_t _tx_frame_head; + uint8_t _tx_frame_tail; + uint8_t _tx_frame_count; + bool _tx_busy_error_pending; + bool _tx_done_pending; + uint8_t _tx_done_result; + uint8_t _tx_hw_payload[KISS_HW_MAX_PAYLOAD_SIZE]; - void writeByte(uint8_t b); - void writeFrame(uint8_t type, const uint8_t* data, uint16_t len); - void writeHardwareFrame(uint8_t sub_cmd, const uint8_t* data, uint16_t len); + static uint16_t appendEscapedByte(uint8_t* dest, uint16_t idx, uint16_t max_len, uint8_t b); + static uint16_t encodeFrame(uint8_t type, const uint8_t* data, uint16_t len, uint8_t* dest, uint16_t max_len); + void resetOutputQueue(); + void popTxFrame(); + bool tryFlushFrames(); + bool queueFrame(uint8_t type, const uint8_t* data, uint16_t len, bool mark_busy_error = true); + bool queuePendingBusyError(); + bool queueHardwareFrame(uint8_t sub_cmd, const uint8_t* data, uint16_t len, bool mark_busy_error); + bool queuePendingTxDone(); + void setTxDonePending(uint8_t result); + bool writeHardwareFrame(uint8_t sub_cmd, const uint8_t* data, uint16_t len); void writeHardwareError(uint8_t error_code); void processFrame(); void handleHardwareCommand(uint8_t sub_cmd, const uint8_t* data, uint16_t len); @@ -182,4 +209,5 @@ public: bool isTxBusy() const { return _tx_state != TX_IDLE; } /** True only when radio is actually transmitting; use to skip recvRaw in main loop. */ bool isActuallyTransmitting() const { return _tx_state == TX_SENDING; } + bool isHostOutputBackedUp() const { return _tx_frame_count > 0 || _tx_busy_error_pending || _tx_done_pending; } }; diff --git a/examples/kiss_modem/main.cpp b/examples/kiss_modem/main.cpp index 7fbcaed1..95a06ee6 100644 --- a/examples/kiss_modem/main.cpp +++ b/examples/kiss_modem/main.cpp @@ -20,6 +20,8 @@ #define NOISE_FLOOR_CALIB_INTERVAL_MS 2000 #define AGC_RESET_INTERVAL_MS 30000 +#define USB_TX_TIMEOUT_MS 50 +#define USB_TX_BUFFER_SIZE 1024 StdRNG rng; mesh::LocalIdentity identity; @@ -111,6 +113,12 @@ void setup() { uint32_t start = millis(); while (!Serial && millis() - start < 3000) delay(10); delay(100); +#if defined(ESP32) + Serial.setTxTimeoutMs(USB_TX_TIMEOUT_MS); +#if ARDUINO_USB_MODE + Serial.setTxBufferSize(USB_TX_BUFFER_SIZE); +#endif +#endif modem = new KissModem(Serial, identity, rng, radio_driver, board, sensors); #endif @@ -126,7 +134,7 @@ void setup() { void loop() { modem->loop(); - if (!modem->isActuallyTransmitting()) { + if (!modem->isActuallyTransmitting() && !modem->isHostOutputBackedUp()) { if (!modem->isTxBusy()) { if ((uint32_t)(millis() - next_agc_reset_ms) >= AGC_RESET_INTERVAL_MS) { radio_driver.resetAGC(); diff --git a/platformio.ini b/platformio.ini index f3ada133..2de71a37 100644 --- a/platformio.ini +++ b/platformio.ini @@ -169,3 +169,18 @@ build_src_filter = +<../src/Packet.cpp> lib_deps = google/googletest @ 1.17.0 + +[env:native_kiss_modem] +platform = native +test_framework = googletest +build_flags = -std=c++17 + -I test/mocks + -I src + -I examples/kiss_modem +test_build_src = yes +test_filter = test_kiss_modem +build_src_filter = + -<*> + +<../examples/kiss_modem/KissModem.cpp> +lib_deps = + google/googletest @ 1.17.0 diff --git a/test/mocks/Arduino.h b/test/mocks/Arduino.h new file mode 100644 index 00000000..77499fe4 --- /dev/null +++ b/test/mocks/Arduino.h @@ -0,0 +1,17 @@ +#pragma once + +#include +#include +#include "Stream.h" + +inline uint32_t g_mock_millis = 0; + +using std::isnan; + +inline uint32_t millis() { + return g_mock_millis; +} + +inline void delay(uint32_t ms) { + g_mock_millis += ms; +} diff --git a/test/mocks/CayenneLPP.h b/test/mocks/CayenneLPP.h new file mode 100644 index 00000000..9d51c0fc --- /dev/null +++ b/test/mocks/CayenneLPP.h @@ -0,0 +1,11 @@ +#pragma once + +#include +#include + +class CayenneLPP { +public: + explicit CayenneLPP(size_t) {} + const uint8_t* getBuffer() const { return nullptr; } + uint16_t getSize() const { return 0; } +}; diff --git a/test/mocks/Identity.h b/test/mocks/Identity.h new file mode 100644 index 00000000..5c3d25e9 --- /dev/null +++ b/test/mocks/Identity.h @@ -0,0 +1,39 @@ +#pragma once + +#include +#include +#include "Utils.h" + +namespace mesh { + +class Identity { +public: + uint8_t pub_key[PUB_KEY_SIZE]; + + Identity() { + std::memset(pub_key, 0, sizeof(pub_key)); + } + + explicit Identity(const uint8_t* src) { + std::memcpy(pub_key, src, PUB_KEY_SIZE); + } + + bool verify(const uint8_t*, const uint8_t*, int) const { + return true; + } +}; + +class LocalIdentity : public Identity { +public: + LocalIdentity() : Identity() {} + + void sign(uint8_t* sig, const uint8_t*, int) const { + std::memset(sig, 0x5A, SIGNATURE_SIZE); + } + + void calcSharedSecret(uint8_t* secret, const uint8_t*) const { + std::memset(secret, 0x11, PUB_KEY_SIZE); + } +}; + +} diff --git a/test/mocks/Mesh.h b/test/mocks/Mesh.h new file mode 100644 index 00000000..b6c263c1 --- /dev/null +++ b/test/mocks/Mesh.h @@ -0,0 +1,27 @@ +#pragma once + +#include + +namespace mesh { + +class Radio { +public: + virtual ~Radio() = default; + virtual bool isReceiving() { return false; } + virtual uint32_t getEstAirtimeFor(uint16_t) { return 10; } + virtual bool startSendRaw(const uint8_t*, uint16_t) { return true; } + virtual bool isSendComplete() { return true; } + virtual void onSendFinished() {} + virtual int16_t getNoiseFloor() { return -120; } +}; + +class MainBoard { +public: + virtual ~MainBoard() = default; + virtual uint16_t getBattMilliVolts() { return 4200; } + virtual float getMCUTemperature() { return 25.0f; } + virtual const char* getManufacturerName() { return "mock-board"; } + virtual void reboot() {} +}; + +} diff --git a/test/mocks/Stream.h b/test/mocks/Stream.h index 195a3029..cf33785d 100644 --- a/test/mocks/Stream.h +++ b/test/mocks/Stream.h @@ -1,10 +1,23 @@ #pragma once -// Mock Stream class for native testing -// Provides minimal interface needed by Utils.h +#include +#include class Stream { public: - virtual void print(char c) {} - virtual void print(const char* str) {} + virtual ~Stream() = default; + virtual size_t write(uint8_t) { return 1; } + virtual size_t write(const uint8_t* buffer, size_t size) { + size_t total = 0; + for (size_t i = 0; i < size; i++) { + total += write(buffer[i]); + } + return total; + } + virtual int available() { return 0; } + virtual int availableForWrite() { return 0; } + virtual int read() { return -1; } + virtual void flush() {} + virtual void print(char) {} + virtual void print(const char*) {} }; diff --git a/test/mocks/Utils.h b/test/mocks/Utils.h new file mode 100644 index 00000000..9bb6b060 --- /dev/null +++ b/test/mocks/Utils.h @@ -0,0 +1,44 @@ +#pragma once + +#include +#include +#include +#include + +#define PUB_KEY_SIZE 32 +#define PRV_KEY_SIZE 64 +#define SIGNATURE_SIZE 64 +#define CIPHER_MAC_SIZE 16 + +namespace mesh { + +class RNG { +public: + virtual ~RNG() = default; + virtual void random(uint8_t* dest, size_t sz) = 0; +}; + +class Utils { +public: + static void sha256(uint8_t* hash, size_t hash_len, const uint8_t*, int) { + std::memset(hash, 0, hash_len); + } + + static int encryptThenMAC(const uint8_t*, uint8_t* dest, const uint8_t* src, int src_len) { + int out_len = src_len + CIPHER_MAC_SIZE; + std::memset(dest, 0xAA, CIPHER_MAC_SIZE); + std::memcpy(dest + CIPHER_MAC_SIZE, src, src_len); + return out_len; + } + + static int MACThenDecrypt(const uint8_t*, uint8_t* dest, const uint8_t* src, int src_len) { + if (src_len < CIPHER_MAC_SIZE) { + return 0; + } + int out_len = src_len - CIPHER_MAC_SIZE; + std::memcpy(dest, src + CIPHER_MAC_SIZE, out_len); + return out_len; + } +}; + +} diff --git a/test/mocks/helpers/SensorManager.h b/test/mocks/helpers/SensorManager.h new file mode 100644 index 00000000..d1a41cb5 --- /dev/null +++ b/test/mocks/helpers/SensorManager.h @@ -0,0 +1,10 @@ +#pragma once + +#include +#include "CayenneLPP.h" + +class SensorManager { +public: + virtual ~SensorManager() = default; + virtual bool querySensors(uint8_t, CayenneLPP&) { return false; } +}; diff --git a/test/test_kiss_modem/test_tx_backpressure.cpp b/test/test_kiss_modem/test_tx_backpressure.cpp new file mode 100644 index 00000000..39a5e3b7 --- /dev/null +++ b/test/test_kiss_modem/test_tx_backpressure.cpp @@ -0,0 +1,294 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "KissModem.h" + +static constexpr int TEST_TX_AVAILABLE_BYTES = 4096; +static constexpr size_t TEST_DEFAULT_MAX_WRITE_CHUNK = SIZE_MAX; +static constexpr size_t TEST_PARTIAL_WRITE_CHUNK = 2; +static constexpr int TEST_PARTIAL_WRITE_FLUSH_LOOPS = 3; +static constexpr uint8_t TEST_SNR = 8; +static constexpr uint8_t TEST_RSSI = 200; + +class BlockingStream : public Stream { +public: + void pushRx(const std::vector& bytes) { + std::lock_guard lock(_mutex); + for (uint8_t b : bytes) { + _rx.push(b); + } + } + + void setBlockWrites(bool blocked) { + { + std::lock_guard lock(_mutex); + _block_writes = blocked; + } + _cv.notify_all(); + } + + bool isWriteBlocked() const { + return _entered_block.load(); + } + + size_t writesCount() const { + std::lock_guard lock(_mutex); + return _writes.size(); + } + + std::vector writesSnapshot() const { + std::lock_guard lock(_mutex); + return _writes; + } + + int availableForWrite() override { + std::lock_guard lock(_mutex); + return _block_writes ? 0 : TEST_TX_AVAILABLE_BYTES; + } + + void setMaxWriteChunk(size_t chunk) { + std::lock_guard lock(_mutex); + _max_write_chunk = chunk; + } + + size_t write(const uint8_t* buffer, size_t size) override { + std::unique_lock lock(_mutex); + while (_block_writes) { + _entered_block.store(true); + _cv.wait(lock); + } + const size_t chunk = (size < _max_write_chunk) ? size : _max_write_chunk; + for (size_t i = 0; i < chunk; i++) { + _writes.push_back(buffer[i]); + } + return chunk; + } + + size_t write(uint8_t b) override { + return write(&b, 1); + } + + int available() override { + std::lock_guard lock(_mutex); + return static_cast(_rx.size()); + } + + int read() override { + std::lock_guard lock(_mutex); + if (_rx.empty()) { + return -1; + } + int b = _rx.front(); + _rx.pop(); + return b; + } + +private: + mutable std::mutex _mutex; + std::condition_variable _cv; + std::queue _rx; + std::vector _writes; + bool _block_writes = false; + std::atomic _entered_block = false; + size_t _max_write_chunk = TEST_DEFAULT_MAX_WRITE_CHUNK; +}; + +class FakeRNG : public mesh::RNG { +public: + void random(uint8_t* dest, size_t sz) override { + for (size_t i = 0; i < sz; i++) { + dest[i] = 0; + } + } +}; + +class FakeRadio : public mesh::Radio { +public: + bool isReceiving() override { return false; } + uint32_t getEstAirtimeFor(uint16_t) override { return 10; } + bool startSendRaw(const uint8_t*, uint16_t) override { + _start_send_count++; + return _start_send_result; + } + bool isSendComplete() override { return _send_complete; } + void onSendFinished() override { _send_finished_count++; } + int16_t getNoiseFloor() override { return -120; } + + void setStartSendResult(bool result) { _start_send_result = result; } + void setSendComplete(bool complete) { _send_complete = complete; } + int startSendCount() const { return _start_send_count; } + int sendFinishedCount() const { return _send_finished_count; } + +private: + bool _start_send_result = true; + bool _send_complete = true; + int _start_send_count = 0; + int _send_finished_count = 0; +}; + +class FakeBoard : public mesh::MainBoard { +public: + uint16_t getBattMilliVolts() override { return 4200; } + float getMCUTemperature() override { return 24.0f; } + const char* getManufacturerName() override { return "test-board"; } + void reboot() override {} +}; + +class FakeSensors : public SensorManager { +public: + bool querySensors(uint8_t, CayenneLPP&) override { return false; } +}; + +class KissModemFixture : public ::testing::Test { +protected: + BlockingStream serial; + mesh::LocalIdentity identity; + FakeRNG rng; + FakeRadio radio; + FakeBoard board; + FakeSensors sensors; + KissModem modem; + + KissModemFixture() + : modem(serial, identity, rng, radio, board, sensors) { + modem.begin(); + } + + static std::vector dataFrame(const std::vector& packet) { + std::vector frame = {KISS_FEND, KISS_CMD_DATA}; + frame.insert(frame.end(), packet.begin(), packet.end()); + frame.push_back(KISS_FEND); + return frame; + } + + void advanceToTxSending() { + modem.loop(); + modem.loop(); + delay((uint32_t)KISS_DEFAULT_TXDELAY * 10); + modem.loop(); + } +}; + +TEST_F(KissModemFixture, PingResponseShouldNotStallLoopUnderTxBackpressure) { + serial.setBlockWrites(true); + serial.pushRx({KISS_FEND, KISS_CMD_SETHARDWARE, HW_CMD_PING, KISS_FEND}); + + auto future = std::async(std::launch::async, [this]() { + modem.loop(); + }); + + auto status = future.wait_for(std::chrono::milliseconds(100)); + EXPECT_EQ(status, std::future_status::ready) << "KissModem::loop blocked in serial write under TX backpressure"; + EXPECT_FALSE(serial.isWriteBlocked()) << "KissModem entered blocking write path"; + + serial.setBlockWrites(false); + future.wait(); + modem.loop(); + EXPECT_GT(serial.writesCount(), 0U) << "KissModem did not flush queued response after backpressure cleared"; +} + +TEST_F(KissModemFixture, PingResponseKeepsStandardKissFraming) { + serial.pushRx({KISS_FEND, KISS_CMD_SETHARDWARE, HW_CMD_PING, KISS_FEND}); + modem.loop(); + + const std::vector expected = {KISS_FEND, KISS_CMD_SETHARDWARE, HW_RESP(HW_CMD_PING), KISS_FEND}; + EXPECT_EQ(serial.writesSnapshot(), expected); +} + +TEST_F(KissModemFixture, PingResponseKeepsFramingWithPartialBulkWrites) { + serial.setMaxWriteChunk(TEST_PARTIAL_WRITE_CHUNK); + serial.pushRx({KISS_FEND, KISS_CMD_SETHARDWARE, HW_CMD_PING, KISS_FEND}); + for (int i = 0; i < TEST_PARTIAL_WRITE_FLUSH_LOOPS; i++) { + modem.loop(); + } + + const std::vector expected = {KISS_FEND, KISS_CMD_SETHARDWARE, HW_RESP(HW_CMD_PING), KISS_FEND}; + EXPECT_EQ(serial.writesSnapshot(), expected); +} + +TEST_F(KissModemFixture, PacketAndMetaAreQueuedTogetherUnderBackpressure) { + static constexpr uint8_t TEST_PACKET[] = {0x01, 0x02, 0x03}; + + serial.setBlockWrites(true); + modem.onPacketReceived((int8_t)TEST_SNR, (int8_t)TEST_RSSI, TEST_PACKET, sizeof(TEST_PACKET)); + serial.setBlockWrites(false); + modem.loop(); + modem.loop(); + + const std::vector expected = { + KISS_FEND, KISS_CMD_DATA, TEST_PACKET[0], TEST_PACKET[1], TEST_PACKET[2], KISS_FEND, + KISS_FEND, KISS_CMD_SETHARDWARE, HW_RESP_RX_META, TEST_SNR, TEST_RSSI, KISS_FEND}; + EXPECT_EQ(serial.writesSnapshot(), expected); +} + +TEST_F(KissModemFixture, RadioTxCompletionAdvancesWhileHostOutputIsBackedUp) { + serial.pushRx(dataFrame({0x42})); + advanceToTxSending(); + ASSERT_EQ(radio.startSendCount(), 1); + + serial.setBlockWrites(true); + modem.loop(); + EXPECT_EQ(radio.sendFinishedCount(), 1); + EXPECT_TRUE(modem.isTxBusy()); + + serial.setBlockWrites(false); + modem.loop(); + + const std::vector expected = {KISS_FEND, KISS_CMD_SETHARDWARE, HW_RESP_TX_DONE, 0x01, KISS_FEND}; + EXPECT_EQ(serial.writesSnapshot(), expected); + EXPECT_FALSE(modem.isTxBusy()); +} + +TEST_F(KissModemFixture, QueueFullReportsBusyWithoutDroppingQueuedFrames) { + static constexpr uint8_t TEST_PACKET_ONE[] = {0x11, 0x12}; + static constexpr uint8_t TEST_PACKET_TWO[] = {0x21, 0x22}; + + serial.setBlockWrites(true); + modem.onPacketReceived((int8_t)TEST_SNR, (int8_t)TEST_RSSI, TEST_PACKET_ONE, sizeof(TEST_PACKET_ONE)); + modem.onPacketReceived((int8_t)TEST_SNR, (int8_t)TEST_RSSI, TEST_PACKET_TWO, sizeof(TEST_PACKET_TWO)); + serial.setBlockWrites(false); + modem.loop(); + + const std::vector expected = { + KISS_FEND, KISS_CMD_DATA, TEST_PACKET_ONE[0], TEST_PACKET_ONE[1], KISS_FEND, + KISS_FEND, KISS_CMD_SETHARDWARE, HW_RESP_RX_META, TEST_SNR, TEST_RSSI, KISS_FEND, + KISS_FEND, KISS_CMD_SETHARDWARE, HW_RESP_ERROR, HW_ERR_TX_BUSY, KISS_FEND}; + EXPECT_EQ(serial.writesSnapshot(), expected); +} + +TEST_F(KissModemFixture, QueuedEncoderEscapesKissSpecialBytes) { + static constexpr uint8_t TEST_PACKET[] = {KISS_FEND, KISS_FESC, 0x01}; + + modem.onPacketReceived((int8_t)TEST_SNR, (int8_t)TEST_RSSI, TEST_PACKET, sizeof(TEST_PACKET)); + + const std::vector expected = { + KISS_FEND, KISS_CMD_DATA, KISS_FESC, KISS_TFEND, KISS_FESC, KISS_TFESC, 0x01, KISS_FEND, + KISS_FEND, KISS_CMD_SETHARDWARE, HW_RESP_RX_META, TEST_SNR, TEST_RSSI, KISS_FEND}; + EXPECT_EQ(serial.writesSnapshot(), expected); +} + +TEST_F(KissModemFixture, MaxPacketWorstCaseEscapingFitsQueuedFrame) { + std::vector packet(KISS_MAX_PACKET_SIZE, KISS_FEND); + std::vector expected = {KISS_FEND, KISS_CMD_DATA}; + for (size_t i = 0; i < packet.size(); i++) { + expected.push_back(KISS_FESC); + expected.push_back(KISS_TFEND); + } + expected.push_back(KISS_FEND); + expected.insert(expected.end(), {KISS_FEND, KISS_CMD_SETHARDWARE, HW_RESP_RX_META, TEST_SNR, TEST_RSSI, KISS_FEND}); + + modem.onPacketReceived((int8_t)TEST_SNR, (int8_t)TEST_RSSI, packet.data(), packet.size()); + EXPECT_EQ(serial.writesSnapshot(), expected); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/variants/heltec_v4/platformio.ini b/variants/heltec_v4/platformio.ini index fabf3827..cb76beb3 100644 --- a/variants/heltec_v4/platformio.ini +++ b/variants/heltec_v4/platformio.ini @@ -432,5 +432,10 @@ lib_deps = [env:heltec_v4_kiss_modem] extends = Heltec_lora32_v4 +build_unflags = + -DARDUINO_USB_MODE=0 +build_flags = + ${Heltec_lora32_v4.build_flags} + -DARDUINO_USB_MODE=1 build_src_filter = ${Heltec_lora32_v4.build_src_filter} +<../examples/kiss_modem/> diff --git a/variants/station_g2/platformio.ini b/variants/station_g2/platformio.ini index 6432b523..508ffe4b 100644 --- a/variants/station_g2/platformio.ini +++ b/variants/station_g2/platformio.ini @@ -241,5 +241,10 @@ lib_deps = [env:Station_G2_kiss_modem] extends = Station_G2 +build_unflags = + -DARDUINO_USB_MODE=0 +build_flags = + ${Station_G2.build_flags} + -DARDUINO_USB_MODE=1 build_src_filter = ${Station_G2.build_src_filter} +<../examples/kiss_modem/> From 779cd08e54abd44e7a00a960f59edd9a715b99c2 Mon Sep 17 00:00:00 2001 From: ViezeVingertjes Date: Tue, 23 Jun 2026 15:15:13 +0200 Subject: [PATCH 024/381] fix: run KISS modem unit tests in CI via native_kiss_modem env The new test_kiss_modem suite needs KissModem headers and sources that only native_kiss_modem provides. Scope native to test_utils and run both envs in the unit test workflow. --- .github/workflows/run-unit-tests.yml | 2 +- platformio.ini | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/run-unit-tests.yml b/.github/workflows/run-unit-tests.yml index e3af3aaf..5d48f4c6 100644 --- a/.github/workflows/run-unit-tests.yml +++ b/.github/workflows/run-unit-tests.yml @@ -20,7 +20,7 @@ jobs: uses: ./.github/actions/setup-build-environment - name: Run Unit Tests - run: pio test -e native -vv + run: pio test -e native -e native_kiss_modem -vv - name: Upload Test Results # Upload test results even if the test step failed. diff --git a/platformio.ini b/platformio.ini index 2de71a37..cdd67d27 100644 --- a/platformio.ini +++ b/platformio.ini @@ -163,6 +163,7 @@ build_flags = -std=c++17 -I src -I test/mocks test_build_src = yes +test_filter = test_utils build_src_filter = -<*> +<../src/Utils.cpp> From 5614deb63f5512db29f00828b6e7f8f43f0769cf Mon Sep 17 00:00:00 2001 From: ViezeVingertjes Date: Fri, 26 Jun 2026 00:11:33 +0200 Subject: [PATCH 025/381] fix: guard HWCDC serial config behind ARDUINO_USB_MODE setTxTimeoutMs() and setTxBufferSize() are HWCDC-only APIs; calling them on HardwareSerial (UART-bridge boards like T-Beam) fails to compile. Co-Authored-By: Adam Gessaman --- examples/kiss_modem/main.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/examples/kiss_modem/main.cpp b/examples/kiss_modem/main.cpp index 95a06ee6..5836a694 100644 --- a/examples/kiss_modem/main.cpp +++ b/examples/kiss_modem/main.cpp @@ -113,11 +113,9 @@ void setup() { uint32_t start = millis(); while (!Serial && millis() - start < 3000) delay(10); delay(100); -#if defined(ESP32) +#if defined(ESP32) && ARDUINO_USB_MODE Serial.setTxTimeoutMs(USB_TX_TIMEOUT_MS); -#if ARDUINO_USB_MODE Serial.setTxBufferSize(USB_TX_BUFFER_SIZE); -#endif #endif modem = new KissModem(Serial, identity, rng, radio_driver, board, sensors); #endif From 8afa7242c2a7cd3e310c19726842461d5edd352e Mon Sep 17 00:00:00 2001 From: Szetya Date: Mon, 20 Jul 2026 14:11:06 +0200 Subject: [PATCH 026/381] Update variant.h Correct of GPS RX/TX Pins. --- variants/lilygo_techo_lite/variant.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/variants/lilygo_techo_lite/variant.h b/variants/lilygo_techo_lite/variant.h index 702ab334..19b12b1b 100644 --- a/variants/lilygo_techo_lite/variant.h +++ b/variants/lilygo_techo_lite/variant.h @@ -152,8 +152,8 @@ extern const int SCK; // GPS — per LilyGo t_echo_lite_config.h // PIN_GPS_TX/RX named from GPS module's perspective -#define PIN_GPS_TX _PINNUM(0, 29) // GPS UART TX → MCU RX -#define PIN_GPS_RX _PINNUM(1, 10) // GPS UART RX ← MCU TX +#define PIN_GPS_RX _PINNUM(0, 29) // GPS UART TX → MCU RX +#define PIN_GPS_TX _PINNUM(1, 10) // GPS UART RX ← MCU TX #define GPS_EN _PINNUM(1, 11) // GPS RT9080 power enable #define PIN_GPS_STANDBY _PINNUM(1, 13) // GPS wake-up -#define PIN_GPS_PPS _PINNUM(1, 15) // GPS 1PPS \ No newline at end of file +#define PIN_GPS_PPS _PINNUM(1, 15) // GPS 1PPS From 9812e567e6937d1d9990c3a9e1d89a2355d551d0 Mon Sep 17 00:00:00 2001 From: entr0p1 <1475255+entr0p1@users.noreply.github.com> Date: Mon, 20 Jul 2026 23:44:48 +1000 Subject: [PATCH 027/381] nRF52840 Power Management Stage 1 (Boot Lock) - v2.3 preparation work This commit lays some of the ground work for the upcoming power management fix that allows users to configure the boot lock behaviour. It is *not* the full fix yet. The goal is to break up the larger commit into smaller chunks so it is easier to review and softer to merge. Improvements: - MainBoard: Add bool to check if power management has been initialised (later to be consumed by CommonCLI to validate we can safely configure the settings) - MainBoard: Add bool to validate LPCOMP is supported on the board (gates LPCOMP config so it doesnt wedge on an unsupported board) - NRF52Board: Rename initPowerMgr() -> pwrmgtInit() to align with the "pwrmgt" prefix being used by any power management related functions in the upcoming new version - NRF52Board: Add a shutdown reason for "None" so the `get pwrmgt.bootreason` command doesnt erroneously return "Unknown" - NRF52Board: Add gate in configureVoltageWake to not arm LPCOMP when power management isn't initialised or the board doesn't support LPCOMP (i.e. we havent defined the AIN pin) - NRF52Board: Reference the LPCOMP AIN pin directly instead of from the per-board definitions to align to the upcoming deprecation of the per-board static configs - NRF52Board: Drop LPCOMP hysteresis as it broadens the wake voltage too much and makes the board less likely to self-recover - NRF52Board: Separate LPCOMP and VBUS wake arm into their own functions --- src/MeshCore.h | 2 ++ src/helpers/NRF52Board.cpp | 47 ++++++++++++++++++++++---------------- src/helpers/NRF52Board.h | 11 ++++++--- 3 files changed, 37 insertions(+), 23 deletions(-) diff --git a/src/MeshCore.h b/src/MeshCore.h index 89e60b1f..70587833 100644 --- a/src/MeshCore.h +++ b/src/MeshCore.h @@ -69,8 +69,10 @@ public: virtual bool isLoRaFemLnaEnabled() const { return false; } // Power management interface (boards with power management override these) + virtual bool isPwrMgtInitialised() const { return false; } virtual bool isExternalPowered() { return false; } virtual uint16_t getBootVoltage() { return 0; } + virtual bool getWakeLpcompSupported() const { return false; } virtual uint32_t getResetReason() const { return 0; } virtual const char* getResetReasonString(uint32_t reason) { return "Not available"; } virtual uint8_t getShutdownReason() const { return 0; } diff --git a/src/helpers/NRF52Board.cpp b/src/helpers/NRF52Board.cpp index 5fb1e55e..84ab0448 100644 --- a/src/helpers/NRF52Board.cpp +++ b/src/helpers/NRF52Board.cpp @@ -38,7 +38,8 @@ static void __attribute__((constructor(101))) nrf52_early_reset_capture() { g_nrf52_shutdown_reason = NRF_POWER->GPREGRET2; } -void NRF52Board::initPowerMgr() { +void NRF52Board::pwrmgtInit() { + if (pwrmgt_initialised) return; // Copy early-captured register values reset_reason = g_nrf52_reset_reason; shutdown_reason = g_nrf52_shutdown_reason; @@ -65,6 +66,7 @@ void NRF52Board::initPowerMgr() { MESH_DEBUG_PRINTLN("PWRMGT: Reset = %s (0x%lX)", getResetReasonString(reset_reason), (unsigned long)reset_reason); } + pwrmgt_initialised = true; } const char* NRF52Board::getResetReasonString(uint32_t reason) { @@ -89,6 +91,7 @@ const char* NRF52Board::getResetReasonString(uint32_t reason) { const char* NRF52Board::getShutdownReasonString(uint8_t reason) { switch (reason) { + case SHUTDOWN_REASON_NONE: return "None"; case SHUTDOWN_REASON_LOW_VOLTAGE: return "Low Voltage"; case SHUTDOWN_REASON_USER: return "User Request"; case SHUTDOWN_REASON_BOOT_PROTECT: return "Boot Protection"; @@ -97,7 +100,7 @@ const char* NRF52Board::getShutdownReasonString(uint8_t reason) { } bool NRF52Board::checkBootVoltage(const PowerMgtConfig* config) { - initPowerMgr(); + pwrmgtInit(); // Read boot voltage boot_voltage_mv = getBattMilliVolts(); @@ -164,24 +167,30 @@ void NRF52Board::enterSystemOff(uint8_t reason) { NVIC_SystemReset(); } -void NRF52Board::configureVoltageWake(uint8_t ain_channel, uint8_t refsel) { +void NRF52Board::configureVoltageWake(uint8_t ain_channel, uint8_t lpcomp_refsel) { + pwrmgtWakeArmVbus(); + if (!isPwrMgtInitialised()) { + MESH_DEBUG_PRINTLN("PWRMGT: LPCOMP wake not armed. Reason: Power Management not initialised"); + return; + } + if (!getWakeLpcompSupported()) { + MESH_DEBUG_PRINTLN("PWRMGT: LPCOMP wake not armed. Reason: LPCOMP unsupported on variant"); + return; + } // LPCOMP is not managed by SoftDevice - direct register access required // Halt and disable before reconfiguration NRF_LPCOMP->TASKS_STOP = 1; NRF_LPCOMP->ENABLE = LPCOMP_ENABLE_ENABLE_Disabled; // Select analog input (AIN0-7 maps to PSEL 0-7) - NRF_LPCOMP->PSEL = ((uint32_t)ain_channel << LPCOMP_PSEL_PSEL_Pos) & LPCOMP_PSEL_PSEL_Msk; + NRF_LPCOMP->PSEL = ((uint32_t)PWRMGT_LPCOMP_AIN << LPCOMP_PSEL_PSEL_Pos) & LPCOMP_PSEL_PSEL_Msk; // Reference: REFSEL (0-6=1/8..7/8, 7=ARef, 8-15=1/16..15/16) - NRF_LPCOMP->REFSEL = ((uint32_t)refsel << LPCOMP_REFSEL_REFSEL_Pos) & LPCOMP_REFSEL_REFSEL_Msk; + NRF_LPCOMP->REFSEL = ((uint32_t)lpcomp_refsel << LPCOMP_REFSEL_REFSEL_Pos) & LPCOMP_REFSEL_REFSEL_Msk; // Detect UP events (voltage rises above threshold for battery recovery) NRF_LPCOMP->ANADETECT = LPCOMP_ANADETECT_ANADETECT_Up; - // Enable 50mV hysteresis for noise immunity - NRF_LPCOMP->HYST = LPCOMP_HYST_HYST_Hyst50mV; - // Clear stale events/interrupts before enabling wake NRF_LPCOMP->EVENTS_READY = 0; NRF_LPCOMP->EVENTS_DOWN = 0; @@ -195,23 +204,22 @@ void NRF52Board::configureVoltageWake(uint8_t ain_channel, uint8_t refsel) { NRF_LPCOMP->ENABLE = LPCOMP_ENABLE_ENABLE_Enabled; NRF_LPCOMP->TASKS_START = 1; - // Wait for comparator to settle before entering SYSTEMOFF + // Wait for comparator to settle for (uint8_t i = 0; i < 20 && !NRF_LPCOMP->EVENTS_READY; i++) { delayMicroseconds(50); } - if (refsel == 7) { - MESH_DEBUG_PRINTLN("PWRMGT: LPCOMP wake configured (AIN%d, ref=ARef)", ain_channel); - } else if (refsel <= 6) { - MESH_DEBUG_PRINTLN("PWRMGT: LPCOMP wake configured (AIN%d, ref=%d/8 VDD)", - ain_channel, refsel + 1); + if (lpcomp_refsel == 7) { + MESH_DEBUG_PRINTLN("PWRMGT: LPCOMP wake armed (AIN%d, ref=ARef)", PWRMGT_LPCOMP_AIN); + } else if (lpcomp_refsel <= 6) { + MESH_DEBUG_PRINTLN("PWRMGT: LPCOMP wake armed (AIN%d, ref=%d/8 VDD)", PWRMGT_LPCOMP_AIN, lpcomp_refsel + 1); } else { - uint8_t ref_num = (uint8_t)((refsel - 8) * 2 + 1); - MESH_DEBUG_PRINTLN("PWRMGT: LPCOMP wake configured (AIN%d, ref=%d/16 VDD)", - ain_channel, ref_num); + uint8_t ref_num = (uint8_t)((lpcomp_refsel - 8) * 2 + 1); + MESH_DEBUG_PRINTLN("PWRMGT: LPCOMP wake armed (AIN%d, ref=%d/16 VDD)", PWRMGT_LPCOMP_AIN, ref_num); } +} - // Configure VBUS (USB power) wake alongside LPCOMP +void NRF52Board::pwrmgtWakeArmVbus() { uint8_t sd_enabled = 0; sd_softdevice_is_enabled(&sd_enabled); if (sd_enabled) { @@ -220,8 +228,7 @@ void NRF52Board::configureVoltageWake(uint8_t ain_channel, uint8_t refsel) { NRF_POWER->EVENTS_USBDETECTED = 0; NRF_POWER->INTENSET = POWER_INTENSET_USBDETECTED_Msk; } - - MESH_DEBUG_PRINTLN("PWRMGT: VBUS wake configured"); + MESH_DEBUG_PRINTLN("PWRMGT: VBUS wake armed"); } #endif diff --git a/src/helpers/NRF52Board.h b/src/helpers/NRF52Board.h index dba15f97..0d31726b 100644 --- a/src/helpers/NRF52Board.h +++ b/src/helpers/NRF52Board.h @@ -25,15 +25,15 @@ struct PowerMgtConfig { #endif class NRF52Board : public mesh::MainBoard { -#ifdef NRF52_POWER_MANAGEMENT - void initPowerMgr(); -#endif +private: + bool pwrmgt_initialised = false; protected: uint8_t startup_reason; char *ota_name; #ifdef NRF52_POWER_MANAGEMENT + void pwrmgtInit(); uint32_t reset_reason; // RESETREAS register value uint8_t shutdown_reason; // GPREGRET value (why we entered last SYSTEMOFF) uint16_t boot_voltage_mv; // Battery voltage at boot (millivolts) @@ -41,6 +41,7 @@ protected: bool checkBootVoltage(const PowerMgtConfig* config); void enterSystemOff(uint8_t reason); void configureVoltageWake(uint8_t ain_channel, uint8_t refsel); + void pwrmgtWakeArmVbus(); virtual void initiateShutdown(uint8_t reason); #endif @@ -63,6 +64,10 @@ public: uint8_t getShutdownReason() const override { return shutdown_reason; } const char* getResetReasonString(uint32_t reason) override; const char* getShutdownReasonString(uint8_t reason) override; + bool isPwrMgtInitialised() const override { return pwrmgt_initialised; } + #ifdef PWRMGT_LPCOMP_AIN + bool getWakeLpcompSupported() const override { return true; } + #endif #endif }; From 65e14d5bd92817150974704e1c938f139eb97ddf Mon Sep 17 00:00:00 2001 From: Alexander Hoffer Date: Mon, 20 Jul 2026 15:47:03 +0100 Subject: [PATCH 028/381] fix: synchronize BLE receive queue --- src/helpers/BoundedQueue.h | 39 +++++++++++++ src/helpers/esp32/SerialBLEInterface.cpp | 41 ++++++++----- src/helpers/esp32/SerialBLEInterface.h | 10 ++-- .../test_bounded_queue/test_bounded_queue.cpp | 58 +++++++++++++++++++ 4 files changed, 129 insertions(+), 19 deletions(-) create mode 100644 src/helpers/BoundedQueue.h create mode 100644 test/test_bounded_queue/test_bounded_queue.cpp diff --git a/src/helpers/BoundedQueue.h b/src/helpers/BoundedQueue.h new file mode 100644 index 00000000..07ecb4ff --- /dev/null +++ b/src/helpers/BoundedQueue.h @@ -0,0 +1,39 @@ +#pragma once + +#include + +namespace mesh { + +template +class BoundedQueue { + static_assert(Capacity > 0, "BoundedQueue capacity must be greater than zero"); + + T _items[Capacity]; + size_t _head = 0; + size_t _size = 0; + +public: + bool push(const T& item) { + if (_size == Capacity) return false; + _items[(_head + _size) % Capacity] = item; + _size++; + return true; + } + + bool pop(T& item) { + if (_size == 0) return false; + item = _items[_head]; + _head = (_head + 1) % Capacity; + _size--; + return true; + } + + void clear() { + _head = 0; + _size = 0; + } + + size_t size() const { return _size; } +}; + +} // namespace mesh diff --git a/src/helpers/esp32/SerialBLEInterface.cpp b/src/helpers/esp32/SerialBLEInterface.cpp index dcfa0e1e..9c81dc7b 100644 --- a/src/helpers/esp32/SerialBLEInterface.cpp +++ b/src/helpers/esp32/SerialBLEInterface.cpp @@ -118,17 +118,30 @@ void SerialBLEInterface::onWrite(BLECharacteristic* pCharacteristic, esp_ble_gat if (len > MAX_FRAME_SIZE) { BLE_DEBUG_PRINTLN("ERROR: onWrite(), frame too big, len=%d", len); - } else if (recv_queue_len >= FRAME_QUEUE_SIZE) { - BLE_DEBUG_PRINTLN("ERROR: onWrite(), recv_queue is full!"); } else { - recv_queue[recv_queue_len].len = len; - memcpy(recv_queue[recv_queue_len].buf, rxValue, len); - recv_queue_len++; + Frame frame = {}; + frame.len = len; + memcpy(frame.buf, rxValue, len); + + portENTER_CRITICAL(&recv_queue_mux); + bool queued = recv_queue.push(frame); + portEXIT_CRITICAL(&recv_queue_mux); + + if (!queued) { + BLE_DEBUG_PRINTLN("ERROR: onWrite(), recv_queue is full!"); + } } } // ---------- public methods +void SerialBLEInterface::clearBuffers() { + portENTER_CRITICAL(&recv_queue_mux); + recv_queue.clear(); + portEXIT_CRITICAL(&recv_queue_mux); + send_queue_len = 0; +} + void SerialBLEInterface::enable() { if (_isEnabled) return; @@ -202,17 +215,15 @@ size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) { } } - if (recv_queue_len > 0) { // check recv queue - size_t len = recv_queue[0].len; // take from top of queue - memcpy(dest, recv_queue[0].buf, len); + Frame frame = {}; + portENTER_CRITICAL(&recv_queue_mux); + bool received = recv_queue.pop(frame); + portEXIT_CRITICAL(&recv_queue_mux); - 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]; - } - return len; + if (received) { + memcpy(dest, frame.buf, frame.len); + BLE_DEBUG_PRINTLN("readBytes: sz=%d, hdr=%d", (uint32_t) frame.len, (uint32_t) dest[0]); + return frame.len; } if (pServer->getConnectedCount() == 0) deviceConnected = false; diff --git a/src/helpers/esp32/SerialBLEInterface.h b/src/helpers/esp32/SerialBLEInterface.h index 965e90fd..e2d600a0 100644 --- a/src/helpers/esp32/SerialBLEInterface.h +++ b/src/helpers/esp32/SerialBLEInterface.h @@ -1,10 +1,12 @@ #pragma once #include "../BaseSerialInterface.h" +#include "../BoundedQueue.h" #include #include #include #include +#include class SerialBLEInterface : public BaseSerialInterface, BLESecurityCallbacks, BLEServerCallbacks, BLECharacteristicCallbacks { BLEServer *pServer; @@ -24,12 +26,12 @@ class SerialBLEInterface : public BaseSerialInterface, BLESecurityCallbacks, BLE }; #define FRAME_QUEUE_SIZE 4 - int recv_queue_len; - Frame recv_queue[FRAME_QUEUE_SIZE]; + portMUX_TYPE recv_queue_mux = portMUX_INITIALIZER_UNLOCKED; + mesh::BoundedQueue recv_queue; int send_queue_len; Frame send_queue[FRAME_QUEUE_SIZE]; - void clearBuffers() { recv_queue_len = 0; send_queue_len = 0; } + void clearBuffers(); protected: // BLESecurityCallbacks methods @@ -58,7 +60,7 @@ public: _isEnabled = false; _last_write = 0; last_conn_id = 0; - send_queue_len = recv_queue_len = 0; + send_queue_len = 0; } /** diff --git a/test/test_bounded_queue/test_bounded_queue.cpp b/test/test_bounded_queue/test_bounded_queue.cpp new file mode 100644 index 00000000..3e2e2de7 --- /dev/null +++ b/test/test_bounded_queue/test_bounded_queue.cpp @@ -0,0 +1,58 @@ +#include + +#include + +TEST(BoundedQueue, PreservesOrderAcrossWraparound) { + mesh::BoundedQueue queue; + int value = 0; + + for (int i = 0; i < 4; i++) EXPECT_TRUE(queue.push(i)); + EXPECT_FALSE(queue.push(4)); + + EXPECT_TRUE(queue.pop(value)); + EXPECT_EQ(0, value); + EXPECT_TRUE(queue.pop(value)); + EXPECT_EQ(1, value); + + EXPECT_TRUE(queue.push(4)); + EXPECT_TRUE(queue.push(5)); + + for (int expected = 2; expected < 6; expected++) { + EXPECT_TRUE(queue.pop(value)); + EXPECT_EQ(expected, value); + } + EXPECT_FALSE(queue.pop(value)); +} + +TEST(BoundedQueue, SurvivesRepeatedFillAndDrainCycles) { + mesh::BoundedQueue queue; + int value = 0; + + for (int cycle = 0; cycle < 1000; cycle++) { + for (int i = 0; i < 4; i++) EXPECT_TRUE(queue.push(cycle * 4 + i)); + for (int i = 0; i < 4; i++) { + EXPECT_TRUE(queue.pop(value)); + EXPECT_EQ(cycle * 4 + i, value); + } + } +} + +TEST(BoundedQueue, ClearDropsPendingItems) { + mesh::BoundedQueue queue; + int value = 0; + + EXPECT_TRUE(queue.push(1)); + EXPECT_TRUE(queue.push(2)); + queue.clear(); + + EXPECT_EQ(0u, queue.size()); + EXPECT_FALSE(queue.pop(value)); + EXPECT_TRUE(queue.push(3)); + EXPECT_TRUE(queue.pop(value)); + EXPECT_EQ(3, value); +} + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} From c7531c4502fb706c85971f8323cc367b9e8bcd6b Mon Sep 17 00:00:00 2001 From: Alexander Hoffer Date: Mon, 20 Jul 2026 15:47:03 +0100 Subject: [PATCH 029/381] fix: enable Heltec V4 USB serial --- boards/heltec_v4.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/boards/heltec_v4.json b/boards/heltec_v4.json index 36cdfc04..0d3a52cd 100644 --- a/boards/heltec_v4.json +++ b/boards/heltec_v4.json @@ -9,7 +9,7 @@ "extra_flags": [ "-DBOARD_HAS_PSRAM", "-DARDUINO_USB_CDC_ON_BOOT=1", - "-DARDUINO_USB_MODE=0", + "-DARDUINO_USB_MODE=1", "-DARDUINO_RUNNING_CORE=1", "-DARDUINO_EVENT_RUNNING_CORE=1" ], @@ -40,4 +40,4 @@ }, "url": "https://heltec.org/", "vendor": "heltec" -} \ No newline at end of file +} From ef45704c533072b2cd7da65392f1a525f67f55fc Mon Sep 17 00:00:00 2001 From: Alexander Hoffer Date: Mon, 20 Jul 2026 15:47:03 +0100 Subject: [PATCH 030/381] fix: preserve bonded BLE reconnects --- src/helpers/esp32/SerialBLEInterface.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/helpers/esp32/SerialBLEInterface.cpp b/src/helpers/esp32/SerialBLEInterface.cpp index dcfa0e1e..c1c04602 100644 --- a/src/helpers/esp32/SerialBLEInterface.cpp +++ b/src/helpers/esp32/SerialBLEInterface.cpp @@ -103,10 +103,9 @@ void SerialBLEInterface::onMtuChanged(BLEServer* pServer, esp_ble_gatts_cb_param void SerialBLEInterface::onDisconnect(BLEServer* pServer) { BLE_DEBUG_PRINTLN("onDisconnect()"); + deviceConnected = false; if (_isEnabled) { adv_restart_time = millis() + ADVERT_RESTART_DELAY; - - // loop() will detect this on next loop, and set deviceConnected to false } } @@ -215,8 +214,6 @@ size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) { return len; } - if (pServer->getConnectedCount() == 0) deviceConnected = false; - if (deviceConnected != oldDeviceConnected) { if (!deviceConnected) { // disconnecting clearBuffers(); From c5f09f2490b9212f99b7d725e7b96e3730d061d1 Mon Sep 17 00:00:00 2001 From: Alexander Hoffer Date: Mon, 20 Jul 2026 15:47:03 +0100 Subject: [PATCH 031/381] fix: preserve UTF-8 advert names --- docs/cli_commands.md | 2 +- src/helpers/AdvertDataHelpers.cpp | 14 ++--- src/helpers/UTF8Helpers.h | 56 ++++++++++++++++++++ test/test_utf8_helpers/test_utf8_helpers.cpp | 38 +++++++++++++ 4 files changed, 103 insertions(+), 7 deletions(-) create mode 100644 src/helpers/UTF8Helpers.h create mode 100644 test/test_utf8_helpers/test_utf8_helpers.cpp diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 5598dba5..b618ae2b 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -305,7 +305,7 @@ This document provides an overview of CLI commands that can be sent to MeshCore **Default:** Varies by board -**Note:** Max length varies. If a location is set, the max length is 24 bytes; 32 otherwise. Emoji and unicode characters may take more than one byte. +**Note:** Advertised names can use up to 23 bytes when location is included and 31 bytes otherwise. Emoji and Unicode characters may take more than one byte. Names that exceed the available advert space are truncated at a valid UTF-8 code point boundary. --- diff --git a/src/helpers/AdvertDataHelpers.cpp b/src/helpers/AdvertDataHelpers.cpp index 0e05620e..998733ae 100644 --- a/src/helpers/AdvertDataHelpers.cpp +++ b/src/helpers/AdvertDataHelpers.cpp @@ -1,4 +1,5 @@ #include +#include uint8_t AdvertDataBuilder::encodeTo(uint8_t app_data[]) { app_data[0] = _type; @@ -16,11 +17,12 @@ app_data[0] |= ADV_FEAT2_MASK; memcpy(&app_data[i], &_extra2, 2); i += 2; } - if (_name && *_name != 0) { - app_data[0] |= ADV_NAME_MASK; - const char* sp = _name; - while (*sp && i < MAX_ADVERT_DATA_SIZE) { - app_data[i++] = *sp++; + if (_name && *_name != 0) { + size_t name_len = mesh::validUtf8PrefixLength(_name, MAX_ADVERT_DATA_SIZE - i); + if (name_len > 0) { + app_data[0] |= ADV_NAME_MASK; + memcpy(&app_data[i], _name, name_len); + i += name_len; } } return i; @@ -84,4 +86,4 @@ void AdvertTimeHelper::formatRelativeTimeDiff(char dest[], int32_t seconds_from_ } } } -} \ No newline at end of file +} diff --git a/src/helpers/UTF8Helpers.h b/src/helpers/UTF8Helpers.h new file mode 100644 index 00000000..e06cf4a6 --- /dev/null +++ b/src/helpers/UTF8Helpers.h @@ -0,0 +1,56 @@ +#pragma once + +#include +#include + +namespace mesh { + +inline bool isUtf8Continuation(uint8_t byte) { + return (byte & 0xC0) == 0x80; +} + +inline size_t validUtf8PrefixLength(const char* text, size_t max_bytes) { + if (text == nullptr) return 0; + + size_t offset = 0; + while (text[offset] != '\0') { + const uint8_t first = static_cast(text[offset]); + size_t sequence_length = 0; + + if (first <= 0x7F) { + sequence_length = 1; + } else if (first >= 0xC2 && first <= 0xDF) { + sequence_length = 2; + } else if (first >= 0xE0 && first <= 0xEF) { + sequence_length = 3; + } else if (first >= 0xF0 && first <= 0xF4) { + sequence_length = 4; + } else { + break; + } + + if (offset + sequence_length > max_bytes) break; + + bool complete = true; + for (size_t i = 1; i < sequence_length; i++) { + if (text[offset + i] == '\0' || !isUtf8Continuation(static_cast(text[offset + i]))) { + complete = false; + break; + } + } + if (!complete) break; + + if (sequence_length == 3) { + const uint8_t second = static_cast(text[offset + 1]); + if ((first == 0xE0 && second < 0xA0) || (first == 0xED && second > 0x9F)) break; + } else if (sequence_length == 4) { + const uint8_t second = static_cast(text[offset + 1]); + if ((first == 0xF0 && second < 0x90) || (first == 0xF4 && second > 0x8F)) break; + } + + offset += sequence_length; + } + return offset; +} + +} // namespace mesh diff --git a/test/test_utf8_helpers/test_utf8_helpers.cpp b/test/test_utf8_helpers/test_utf8_helpers.cpp new file mode 100644 index 00000000..ee953522 --- /dev/null +++ b/test/test_utf8_helpers/test_utf8_helpers.cpp @@ -0,0 +1,38 @@ +#include + +#include + +TEST(UTF8Helpers, KeepsCompleteNameWithinLimit) { + const char* name = "Example RPT 🔋🇵🇱"; + + EXPECT_EQ(24u, mesh::validUtf8PrefixLength(name, 24)); +} + +TEST(UTF8Helpers, StopsBeforeCodePointCrossingLimit) { + const char* name = "Example RPT 🔋🇵🇱"; + + EXPECT_EQ(20u, mesh::validUtf8PrefixLength(name, 23)); +} + +TEST(UTF8Helpers, RejectsMalformedAndTruncatedSequences) { + const char overlong[] = {'A', static_cast(0xC0), static_cast(0xAF), 0}; + const char surrogate[] = {'A', static_cast(0xED), static_cast(0xA0), static_cast(0x80), 0}; + const char out_of_range[] = {'A', static_cast(0xF4), static_cast(0x90), static_cast(0x80), static_cast(0x80), 0}; + const char truncated[] = {'A', static_cast(0xF0), static_cast(0x9F), 0}; + + EXPECT_EQ(1u, mesh::validUtf8PrefixLength(overlong, sizeof(overlong))); + EXPECT_EQ(1u, mesh::validUtf8PrefixLength(surrogate, sizeof(surrogate))); + EXPECT_EQ(1u, mesh::validUtf8PrefixLength(out_of_range, sizeof(out_of_range))); + EXPECT_EQ(1u, mesh::validUtf8PrefixLength(truncated, sizeof(truncated))); +} + +TEST(UTF8Helpers, RejectsUnexpectedContinuationByte) { + const char invalid[] = {'A', static_cast(0x80), 'B', 0}; + + EXPECT_EQ(1u, mesh::validUtf8PrefixLength(invalid, sizeof(invalid))); +} + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} From 1dd58e3b49ea8efcd554468f66c55df7e3dc1aff Mon Sep 17 00:00:00 2001 From: =UltimateCodeWarrior Date: Mon, 20 Jul 2026 19:24:38 -0700 Subject: [PATCH 032/381] Move Supreme OLED address to variant config Keep SH1106Display generic by relying on DISPLAY_ADDRESS while the T-Beam Supreme variant declares its 0x3D OLED address. --- src/helpers/ui/SH1106Display.cpp | 15 ++++----------- .../lilygo_tbeam_supreme_SX1262/platformio.ini | 1 + 2 files changed, 5 insertions(+), 11 deletions(-) diff --git a/src/helpers/ui/SH1106Display.cpp b/src/helpers/ui/SH1106Display.cpp index 86c6089b..57ccfc2e 100644 --- a/src/helpers/ui/SH1106Display.cpp +++ b/src/helpers/ui/SH1106Display.cpp @@ -11,17 +11,10 @@ bool SH1106Display::i2c_probe(TwoWire &wire, uint8_t addr) bool SH1106Display::begin() { - // Address selection: on some board revisions (notably the LilyGo T-Beam - // Supreme V3) the OLED lives at 0x3D because 0x3C is occupied by a - // magnetometer (QMC6310N). 0x3D is only ever used by the OLED, so prefer it - // when present, otherwise fall back to the standard 0x3C (DISPLAY_ADDRESS). - uint8_t addr = 0; - if (i2c_probe(Wire, 0x3D)) { - addr = 0x3D; - } else if (i2c_probe(Wire, DISPLAY_ADDRESS)) { - addr = DISPLAY_ADDRESS; - } - return addr && display.begin(addr, true); + // Wire must already be initialised by board.begin() before this is called. + // Boards with non-standard SH1106 addresses should define DISPLAY_ADDRESS + // in their variant/platformio configuration. + return i2c_probe(Wire, DISPLAY_ADDRESS) && display.begin(DISPLAY_ADDRESS, true); } void SH1106Display::turnOn() diff --git a/variants/lilygo_tbeam_supreme_SX1262/platformio.ini b/variants/lilygo_tbeam_supreme_SX1262/platformio.ini index 02946156..8bfc4093 100644 --- a/variants/lilygo_tbeam_supreme_SX1262/platformio.ini +++ b/variants/lilygo_tbeam_supreme_SX1262/platformio.ini @@ -18,6 +18,7 @@ build_flags = -D RADIO_CLASS=CustomSX1262 -D WRAPPER_CLASS=CustomSX1262Wrapper -D DISPLAY_CLASS=SH1106Display + -D DISPLAY_ADDRESS=0x3D -D LORA_TX_POWER=22 -D P_LORA_TX_LED=6 -D PIN_BOARD_SDA=17 From 299e921549a655741b7aacf4162c48fcb4d67c14 Mon Sep 17 00:00:00 2001 From: Alexander Hoffer Date: Tue, 21 Jul 2026 07:17:01 +0100 Subject: [PATCH 033/381] refactor: use FreeRTOS BLE receive queue --- src/helpers/BoundedQueue.h | 39 ------------- src/helpers/esp32/SerialBLEInterface.cpp | 16 +---- src/helpers/esp32/SerialBLEInterface.h | 10 +++- .../test_bounded_queue/test_bounded_queue.cpp | 58 ------------------- 4 files changed, 10 insertions(+), 113 deletions(-) delete mode 100644 src/helpers/BoundedQueue.h delete mode 100644 test/test_bounded_queue/test_bounded_queue.cpp diff --git a/src/helpers/BoundedQueue.h b/src/helpers/BoundedQueue.h deleted file mode 100644 index 07ecb4ff..00000000 --- a/src/helpers/BoundedQueue.h +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once - -#include - -namespace mesh { - -template -class BoundedQueue { - static_assert(Capacity > 0, "BoundedQueue capacity must be greater than zero"); - - T _items[Capacity]; - size_t _head = 0; - size_t _size = 0; - -public: - bool push(const T& item) { - if (_size == Capacity) return false; - _items[(_head + _size) % Capacity] = item; - _size++; - return true; - } - - bool pop(T& item) { - if (_size == 0) return false; - item = _items[_head]; - _head = (_head + 1) % Capacity; - _size--; - return true; - } - - void clear() { - _head = 0; - _size = 0; - } - - size_t size() const { return _size; } -}; - -} // namespace mesh diff --git a/src/helpers/esp32/SerialBLEInterface.cpp b/src/helpers/esp32/SerialBLEInterface.cpp index 9c81dc7b..2dd20b2f 100644 --- a/src/helpers/esp32/SerialBLEInterface.cpp +++ b/src/helpers/esp32/SerialBLEInterface.cpp @@ -123,11 +123,7 @@ void SerialBLEInterface::onWrite(BLECharacteristic* pCharacteristic, esp_ble_gat frame.len = len; memcpy(frame.buf, rxValue, len); - portENTER_CRITICAL(&recv_queue_mux); - bool queued = recv_queue.push(frame); - portEXIT_CRITICAL(&recv_queue_mux); - - if (!queued) { + if (xQueueSend(recv_queue, &frame, 0) != pdTRUE) { BLE_DEBUG_PRINTLN("ERROR: onWrite(), recv_queue is full!"); } } @@ -136,9 +132,7 @@ void SerialBLEInterface::onWrite(BLECharacteristic* pCharacteristic, esp_ble_gat // ---------- public methods void SerialBLEInterface::clearBuffers() { - portENTER_CRITICAL(&recv_queue_mux); - recv_queue.clear(); - portEXIT_CRITICAL(&recv_queue_mux); + xQueueReset(recv_queue); send_queue_len = 0; } @@ -216,11 +210,7 @@ size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) { } Frame frame = {}; - portENTER_CRITICAL(&recv_queue_mux); - bool received = recv_queue.pop(frame); - portEXIT_CRITICAL(&recv_queue_mux); - - if (received) { + if (xQueueReceive(recv_queue, &frame, 0) == pdTRUE) { memcpy(dest, frame.buf, frame.len); BLE_DEBUG_PRINTLN("readBytes: sz=%d, hdr=%d", (uint32_t) frame.len, (uint32_t) dest[0]); return frame.len; diff --git a/src/helpers/esp32/SerialBLEInterface.h b/src/helpers/esp32/SerialBLEInterface.h index e2d600a0..9fb6adba 100644 --- a/src/helpers/esp32/SerialBLEInterface.h +++ b/src/helpers/esp32/SerialBLEInterface.h @@ -1,12 +1,12 @@ #pragma once #include "../BaseSerialInterface.h" -#include "../BoundedQueue.h" #include #include #include #include #include +#include class SerialBLEInterface : public BaseSerialInterface, BLESecurityCallbacks, BLEServerCallbacks, BLECharacteristicCallbacks { BLEServer *pServer; @@ -26,8 +26,9 @@ class SerialBLEInterface : public BaseSerialInterface, BLESecurityCallbacks, BLE }; #define FRAME_QUEUE_SIZE 4 - portMUX_TYPE recv_queue_mux = portMUX_INITIALIZER_UNLOCKED; - mesh::BoundedQueue recv_queue; + StaticQueue_t recv_queue_state; + uint8_t recv_queue_storage[FRAME_QUEUE_SIZE * sizeof(Frame)]; + QueueHandle_t recv_queue; int send_queue_len; Frame send_queue[FRAME_QUEUE_SIZE]; @@ -60,6 +61,9 @@ public: _isEnabled = false; _last_write = 0; last_conn_id = 0; + recv_queue = xQueueCreateStatic( + FRAME_QUEUE_SIZE, sizeof(Frame), recv_queue_storage, &recv_queue_state + ); send_queue_len = 0; } diff --git a/test/test_bounded_queue/test_bounded_queue.cpp b/test/test_bounded_queue/test_bounded_queue.cpp deleted file mode 100644 index 3e2e2de7..00000000 --- a/test/test_bounded_queue/test_bounded_queue.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include - -#include - -TEST(BoundedQueue, PreservesOrderAcrossWraparound) { - mesh::BoundedQueue queue; - int value = 0; - - for (int i = 0; i < 4; i++) EXPECT_TRUE(queue.push(i)); - EXPECT_FALSE(queue.push(4)); - - EXPECT_TRUE(queue.pop(value)); - EXPECT_EQ(0, value); - EXPECT_TRUE(queue.pop(value)); - EXPECT_EQ(1, value); - - EXPECT_TRUE(queue.push(4)); - EXPECT_TRUE(queue.push(5)); - - for (int expected = 2; expected < 6; expected++) { - EXPECT_TRUE(queue.pop(value)); - EXPECT_EQ(expected, value); - } - EXPECT_FALSE(queue.pop(value)); -} - -TEST(BoundedQueue, SurvivesRepeatedFillAndDrainCycles) { - mesh::BoundedQueue queue; - int value = 0; - - for (int cycle = 0; cycle < 1000; cycle++) { - for (int i = 0; i < 4; i++) EXPECT_TRUE(queue.push(cycle * 4 + i)); - for (int i = 0; i < 4; i++) { - EXPECT_TRUE(queue.pop(value)); - EXPECT_EQ(cycle * 4 + i, value); - } - } -} - -TEST(BoundedQueue, ClearDropsPendingItems) { - mesh::BoundedQueue queue; - int value = 0; - - EXPECT_TRUE(queue.push(1)); - EXPECT_TRUE(queue.push(2)); - queue.clear(); - - EXPECT_EQ(0u, queue.size()); - EXPECT_FALSE(queue.pop(value)); - EXPECT_TRUE(queue.push(3)); - EXPECT_TRUE(queue.pop(value)); - EXPECT_EQ(3, value); -} - -int main(int argc, char **argv) { - ::testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} From 372281ee8f8bc72d335a775c282d1d279e8c5480 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Tue, 21 Jul 2026 19:22:09 +1000 Subject: [PATCH 034/381] * optimised: value-init not needed --- src/helpers/esp32/SerialBLEInterface.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/helpers/esp32/SerialBLEInterface.cpp b/src/helpers/esp32/SerialBLEInterface.cpp index 7084b7d9..6371cf33 100644 --- a/src/helpers/esp32/SerialBLEInterface.cpp +++ b/src/helpers/esp32/SerialBLEInterface.cpp @@ -208,7 +208,7 @@ size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) { } } - Frame frame = {}; + Frame frame; if (xQueueReceive(recv_queue, &frame, 0) == pdTRUE) { memcpy(dest, frame.buf, frame.len); BLE_DEBUG_PRINTLN("readBytes: sz=%d, hdr=%d", (uint32_t) frame.len, (uint32_t) dest[0]); From 20f7421f72907dcb8582d569610ec1e9d2fc6a0f Mon Sep 17 00:00:00 2001 From: agessaman Date: Tue, 21 Jul 2026 12:23:20 -0700 Subject: [PATCH 035/381] fix(room_server): support RX boosted gain The room server never supported RX boosted gain, while the repeater does. Three consequences on SX1262/SX1268 boards: - boosted gain was never applied to the radio at boot, so a room server ran in power-saving RX mode while an identical repeater ran boosted - a real receive-sensitivity difference with nothing pointing at it - _prefs.rx_boosted_gain was never initialised (the prefs are memset to 0 before defaults are set), so it defaulted to off - 'set radio.rxgain on' replied "Error: unsupported" but CommonCLI had already written the value to prefs and saved them, so a stale setting survived reboot and was never applied Mirror the repeater's implementation: initialise the pref default under the same USE_SX1262/USE_SX1268 and SX126X_RX_BOOSTED_GAIN guards, apply it during radio init, and override setRxBoostedGain() so the CLI reports success and takes effect. Built Heltec_v3_room_server (SX1262) and LilyGo_T3S3_sx1276_room_server (guards compile out cleanly). --- examples/simple_room_server/MyMesh.cpp | 13 +++++++++++++ examples/simple_room_server/MyMesh.h | 1 + 2 files changed, 14 insertions(+) diff --git a/examples/simple_room_server/MyMesh.cpp b/examples/simple_room_server/MyMesh.cpp index 36978e80..b6485128 100644 --- a/examples/simple_room_server/MyMesh.cpp +++ b/examples/simple_room_server/MyMesh.cpp @@ -658,6 +658,14 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc _prefs.gps_enabled = 0; _prefs.gps_interval = 0; _prefs.advert_loc_policy = ADVERT_LOC_PREFS; + +#if defined(USE_SX1262) || defined(USE_SX1268) +#ifdef SX126X_RX_BOOSTED_GAIN + _prefs.rx_boosted_gain = SX126X_RX_BOOSTED_GAIN; +#else + _prefs.rx_boosted_gain = 1; // enabled by default; +#endif +#endif _prefs.radio_fem_rxgain = 1; next_post_idx = 0; @@ -700,6 +708,7 @@ void MyMesh::begin(FILESYSTEM *fs) { radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr); radio_driver.setTxPower(_prefs.tx_power_dbm); + radio_driver.setRxBoostedGainMode(_prefs.rx_boosted_gain); board.setLoRaFemLnaEnabled(_prefs.radio_fem_rxgain); updateAdvertTimer(); @@ -807,6 +816,10 @@ void MyMesh::setTxPower(int8_t power_dbm) { radio_driver.setTxPower(power_dbm); } +bool MyMesh::setRxBoostedGain(bool enable) { + return radio_driver.setRxBoostedGainMode(enable); +} + void MyMesh::saveIdentity(const mesh::LocalIdentity &new_id) { #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) IdentityStore store(*_fs, ""); diff --git a/examples/simple_room_server/MyMesh.h b/examples/simple_room_server/MyMesh.h index 6bab9dc2..caef6920 100644 --- a/examples/simple_room_server/MyMesh.h +++ b/examples/simple_room_server/MyMesh.h @@ -206,6 +206,7 @@ public: void dumpLogFile() override; void setTxPower(int8_t power_dbm) override; + bool setRxBoostedGain(bool enable) override; void formatNeighborsReply(char *reply) override { strcpy(reply, "not supported"); From 365332205e1a3dff4d1c535b193706d32b44610e Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Wed, 22 Jul 2026 16:03:33 +1000 Subject: [PATCH 036/381] * refactor of Color mapping in UITasks / DisplayDrivers * color displays now with a new light theme --- examples/companion_radio/ui-new/UITask.cpp | 67 ++++++++++++------- examples/companion_radio/ui-orig/UITask.cpp | 27 ++++---- .../ui-tiny/ScrollingStatusBar.h | 2 +- examples/companion_radio/ui-tiny/UITask.cpp | 31 +++++---- examples/simple_repeater/UITask.cpp | 12 ++-- examples/simple_room_server/UITask.cpp | 8 +-- examples/simple_sensor/UITask.cpp | 8 +-- src/helpers/ui/DisplayDriver.h | 14 +++- src/helpers/ui/E213Display.cpp | 30 ++++++--- src/helpers/ui/E213Display.h | 5 +- src/helpers/ui/E290Display.cpp | 30 ++++++--- src/helpers/ui/E290Display.h | 5 +- src/helpers/ui/GxEPDDisplay.cpp | 29 +++++--- src/helpers/ui/GxEPDDisplay.h | 4 +- src/helpers/ui/LGFXDisplay.cpp | 48 +++++-------- src/helpers/ui/LGFXDisplay.h | 4 +- src/helpers/ui/NV3001BDisplay.cpp | 34 +++++----- src/helpers/ui/NV3001BDisplay.h | 4 +- src/helpers/ui/NullDisplayDriver.h | 4 +- src/helpers/ui/SH1106Display.cpp | 19 ++++-- src/helpers/ui/SH1106Display.h | 4 +- src/helpers/ui/SSD1306Display.cpp | 19 ++++-- src/helpers/ui/SSD1306Display.h | 4 +- src/helpers/ui/ST7735Display.cpp | 46 +++++-------- src/helpers/ui/ST7735Display.h | 4 +- src/helpers/ui/ST7789Display.cpp | 51 +++++--------- src/helpers/ui/ST7789Display.h | 4 +- src/helpers/ui/ST7789LCDDisplay.cpp | 47 +++++-------- src/helpers/ui/ST7789LCDDisplay.h | 4 +- src/helpers/ui/U8g2Display.cpp | 12 ++++ src/helpers/ui/U8g2Display.h | 16 ++--- variants/lilygo_techo_card/platformio.ini | 2 +- 32 files changed, 313 insertions(+), 285 deletions(-) create mode 100644 src/helpers/ui/U8g2Display.cpp diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index a26dc19a..09903db0 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -53,23 +53,24 @@ public: int render(DisplayDriver& display) override { // meshcore logo - display.setColor(DisplayDriver::BLUE); + display.setColor(UIColor::corp_blue); int logoWidth = 128; display.drawXbm((display.width() - logoWidth) / 2, 3, meshcore_logo, logoWidth, 13); // meshcore website const char* website = "https://meshcore.io"; - display.setColor(DisplayDriver::LIGHT); + display.setColor(UIColor::primary_txt); display.setTextSize(1); uint16_t websiteWidth = display.getTextWidth(website); display.setCursor((display.width() - websiteWidth) / 2, 22); display.print(website); // version info - display.setColor(DisplayDriver::LIGHT); + display.setColor(UIColor::primary_txt); display.setTextSize(1); display.drawTextCentered(display.width()/2, 35, _version_info); + display.setColor(UIColor::secondary_txt); display.setTextSize(1); display.drawTextCentered(display.width()/2, 48, FIRMWARE_BUILD_DATE); @@ -128,7 +129,7 @@ class HomeScreen : public UIScreen { int iconHeight = 10; int iconX = display.width() - iconWidth - 5; // Position the icon near the top-right corner int iconY = 0; - display.setColor(DisplayDriver::GREEN); + display.setColor(UIColor::title_txt); // battery outline display.drawRect(iconX, iconY, iconWidth, iconHeight); @@ -143,7 +144,7 @@ class HomeScreen : public UIScreen { // show muted icon if buzzer is muted #ifdef PIN_BUZZER if (_task->isBuzzerQuiet()) { - display.setColor(DisplayDriver::RED); + display.setColor(UIColor::warning_txt); display.drawXbm(iconX - 9, iconY + 1, muted_icon, 8, 8); } #endif @@ -188,34 +189,37 @@ public: } int render(DisplayDriver& display) override { + display.setColor(UIColor::title_bkg); + display.fillRect(0, 0, display.width(), 12); char tmp[80]; // node name display.setTextSize(1); - display.setColor(DisplayDriver::GREEN); + display.setColor(UIColor::title_txt); char filtered_name[sizeof(_node_prefs->node_name)]; display.translateUTF8ToBlocks(filtered_name, _node_prefs->node_name, sizeof(filtered_name)); - display.setCursor(0, 0); + display.setCursor(0, 2); display.print(filtered_name); // battery voltage renderBatteryIndicator(display, _task->getBattMilliVolts()); // curr page indicator + display.setColor(UIColor::title_bkg); int y = 14; int x = display.width() / 2 - 5 * (HomePage::Count-1); for (uint8_t i = 0; i < HomePage::Count; i++, x += 10) { if (i == _page) { - display.fillRect(x-1, y-1, 3, 3); + display.fillRect(x-1, y-1, 4, 4); } else { - display.fillRect(x, y, 1, 1); + display.fillRect(x, y, 2, 2); } } if (_page == HomePage::FIRST) { - display.setColor(DisplayDriver::YELLOW); + display.setColor(UIColor::primary_txt); display.setTextSize(2); sprintf(tmp, "MSG: %d", _task->getMsgCount()); - display.drawTextCentered(display.width() / 2, 20, tmp); + display.drawTextCentered(display.width() / 2, 22, tmp); #ifdef WIFI_SSID IPAddress ip = WiFi.localIP(); @@ -224,19 +228,19 @@ public: display.drawTextCentered(display.width() / 2, 54, tmp); #endif if (_task->hasConnection()) { - display.setColor(DisplayDriver::GREEN); + display.setColor(UIColor::warning_txt); display.setTextSize(1); display.drawTextCentered(display.width() / 2, 43, "< Connected >"); } else if (the_mesh.getBLEPin() != 0) { // BT pin - display.setColor(DisplayDriver::RED); + display.setColor(UIColor::warning_txt); display.setTextSize(2); sprintf(tmp, "Pin:%d", the_mesh.getBLEPin()); display.drawTextCentered(display.width() / 2, 43, tmp); } } else if (_page == HomePage::RECENT) { the_mesh.getRecentlyHeard(recent, UI_RECENT_LIST_SIZE); - display.setColor(DisplayDriver::GREEN); + display.setColor(UIColor::primary_txt); int y = 20; for (int i = 0; i < UI_RECENT_LIST_SIZE; i++, y += 11) { auto a = &recent[i]; @@ -260,7 +264,7 @@ public: display.print(tmp); } } else if (_page == HomePage::RADIO) { - display.setColor(DisplayDriver::YELLOW); + display.setColor(UIColor::primary_txt); display.setTextSize(1); // freq / sf display.setCursor(0, 20); @@ -279,15 +283,17 @@ public: sprintf(tmp, "Noise floor: %d", radio_driver.getNoiseFloor()); display.print(tmp); } else if (_page == HomePage::BLUETOOTH) { - display.setColor(DisplayDriver::GREEN); + display.setColor(UIColor::corp_blue); display.drawXbm((display.width() - 32) / 2, 18, _task->isSerialEnabled() ? bluetooth_on : bluetooth_off, 32, 32); + display.setColor(UIColor::secondary_txt); display.setTextSize(1); display.drawTextCentered(display.width() / 2, 64 - 11, "toggle: " PRESS_LABEL); } else if (_page == HomePage::ADVERT) { - display.setColor(DisplayDriver::GREEN); + display.setColor(UIColor::corp_blue); display.drawXbm((display.width() - 32) / 2, 18, advert_icon, 32, 32); + display.setColor(UIColor::secondary_txt); display.drawTextCentered(display.width() / 2, 64 - 11, "advert: " PRESS_LABEL); #if ENV_INCLUDE_GPS == 1 } else if (_page == HomePage::GPS) { @@ -305,24 +311,33 @@ public: #else strcpy(buf, gps_state ? "gps on" : "gps off"); #endif + display.setColor(UIColor::primary_txt); display.drawTextLeftAlign(0, y, buf); if (nmea == NULL) { y = y + 12; + display.setColor(UIColor::secondary_txt); display.drawTextLeftAlign(0, y, "Can't access GPS"); } else { + display.setColor(UIColor::primary_txt); strcpy(buf, nmea->isValid()?"fix":"no fix"); display.drawTextRightAlign(display.width()-1, y, buf); y = y + 12; + display.setColor(UIColor::secondary_txt); display.drawTextLeftAlign(0, y, "sat"); + display.setColor(UIColor::primary_txt); sprintf(buf, "%d", nmea->satellitesCount()); display.drawTextRightAlign(display.width()-1, y, buf); y = y + 12; + display.setColor(UIColor::secondary_txt); display.drawTextLeftAlign(0, y, "pos"); + display.setColor(UIColor::primary_txt); sprintf(buf, "%.4f %.4f", nmea->getLatitude()/1000000., nmea->getLongitude()/1000000.); display.drawTextRightAlign(display.width()-1, y, buf); y = y + 12; + display.setColor(UIColor::secondary_txt); display.drawTextLeftAlign(0, y, "alt"); + display.setColor(UIColor::primary_txt); sprintf(buf, "%.2f", nmea->getAltitude()/1000.); display.drawTextRightAlign(display.width()-1, y, buf); y = y + 12; @@ -390,7 +405,9 @@ public: strcpy(name, "unk"); sprintf(buf, ""); } display.setCursor(0, y); + display.setColor(UIColor::secondary_txt); display.print(name); + display.setColor(UIColor::primary_txt); display.setCursor( display.width()-display.getTextWidth(buf)-1, y ); @@ -401,11 +418,13 @@ public: else sensors_scroll_offset = 0; #endif } else if (_page == HomePage::SHUTDOWN) { - display.setColor(DisplayDriver::GREEN); + display.setColor(UIColor::corp_blue); display.setTextSize(1); if (_shutdown_init) { + display.setColor(UIColor::warning_txt); display.drawTextCentered(display.width() / 2, 34, "hibernating..."); } else { + display.setColor(UIColor::secondary_txt); display.drawXbm((display.width() - 32) / 2, 18, power_icon, 32, 32); display.drawTextCentered(display.width() / 2, 64 - 11, "hibernate:" PRESS_LABEL); } @@ -498,7 +517,7 @@ public: char tmp[16]; display.setCursor(0, 0); display.setTextSize(1); - display.setColor(DisplayDriver::GREEN); + display.setColor(UIColor::corp_blue); sprintf(tmp, "Unread: %d", num_unread); display.print(tmp); @@ -518,13 +537,13 @@ public: display.drawRect(0, 11, display.width(), 1); // horiz line display.setCursor(0, 14); - display.setColor(DisplayDriver::YELLOW); + display.setColor(UIColor::secondary_txt); char filtered_origin[sizeof(p->origin)]; display.translateUTF8ToBlocks(filtered_origin, p->origin, sizeof(filtered_origin)); display.print(filtered_origin); display.setCursor(0, 25); - display.setColor(DisplayDriver::LIGHT); + display.setColor(UIColor::primary_txt); char filtered_msg[sizeof(p->msg)]; display.translateUTF8ToBlocks(filtered_msg, p->msg, sizeof(filtered_msg)); display.printWordWrap(filtered_msg, display.width()); @@ -806,9 +825,9 @@ void UITask::loop() { _display->setTextSize(1); int y = _display->height() / 3; int p = _display->height() / 32; - _display->setColor(DisplayDriver::DARK); + _display->setColor(UIColor::popup_bkg); _display->fillRect(p, y, _display->width() - p*2, y); - _display->setColor(DisplayDriver::LIGHT); // draw box border + _display->setColor(UIColor::popup_txt); // draw box border _display->drawRect(p, y, _display->width() - p*2, y); _display->drawTextCentered(_display->width() / 2, y + p*3, _alert); _next_refresh = _alert_expiry; // will need refresh when alert is dismissed @@ -845,7 +864,7 @@ void UITask::loop() { if (_display != NULL) { _display->startFrame(); _display->setTextSize(2); - _display->setColor(DisplayDriver::RED); + _display->setColor(UIColor::warning_txt); _display->drawTextCentered(_display->width() / 2, 20, "Low Battery."); _display->drawTextCentered(_display->width() / 2, 40, "Shutting Down!"); _display->endFrame(); diff --git a/examples/companion_radio/ui-orig/UITask.cpp b/examples/companion_radio/ui-orig/UITask.cpp index b48f6412..09fc8e77 100644 --- a/examples/companion_radio/ui-orig/UITask.cpp +++ b/examples/companion_radio/ui-orig/UITask.cpp @@ -167,7 +167,7 @@ void UITask::renderBatteryIndicator(uint16_t batteryMilliVolts) { int iconHeight = 12; int iconX = _display->width() - iconWidth - 5; // Position the icon near the top-right corner int iconY = 0; - _display->setColor(DisplayDriver::GREEN); + _display->setColor(UIColor::primary_txt); // battery outline _display->drawRect(iconX, iconY, iconWidth, iconHeight); @@ -188,7 +188,7 @@ void UITask::renderCurrScreen() { _display->setTextSize(1.4); uint16_t textWidth = _display->getTextWidth(_alert); _display->setCursor((_display->width() - textWidth) / 2, 22); - _display->setColor(DisplayDriver::GREEN); + _display->setColor(UIColor::warning_txt); _display->print(_alert); _alert[0] = 0; _need_refresh = true; @@ -197,30 +197,29 @@ void UITask::renderCurrScreen() { // render message preview _display->setCursor(0, 0); _display->setTextSize(1); - _display->setColor(DisplayDriver::GREEN); + _display->setColor(UIColor::primary_txt); _display->print(_node_prefs->node_name); _display->setCursor(0, 12); - _display->setColor(DisplayDriver::YELLOW); + _display->setColor(UIColor::secondary_txt); _display->print(_origin); _display->setCursor(0, 24); - _display->setColor(DisplayDriver::LIGHT); _display->print(_msg); _display->setCursor(_display->width() - 28, 9); _display->setTextSize(2); - _display->setColor(DisplayDriver::ORANGE); + _display->setColor(UIColor::primary_txt); sprintf(tmp, "%d", _msgcount); _display->print(tmp); - _display->setColor(DisplayDriver::YELLOW); // last color will be kept on T114 + _display->setColor(UIColor::secondary_txt); // last color will be kept on T114 } else if ((millis() - ui_started_at) < BOOT_SCREEN_MILLIS) { // boot screen // meshcore logo - _display->setColor(DisplayDriver::BLUE); + _display->setColor(UIColor::corp_blue); int logoWidth = 128; _display->drawXbm((_display->width() - logoWidth) / 2, 3, meshcore_logo, logoWidth, 13); // version info - _display->setColor(DisplayDriver::LIGHT); + _display->setColor(UIColor::primary_txt); _display->setTextSize(1); uint16_t textWidth = _display->getTextWidth(_version_info); _display->setCursor((_display->width() - textWidth) / 2, 22); @@ -229,7 +228,7 @@ void UITask::renderCurrScreen() { // node name _display->setCursor(0, 0); _display->setTextSize(1); - _display->setColor(DisplayDriver::GREEN); + _display->setColor(UIColor::primary_txt); _display->print(_node_prefs->node_name); // battery voltage @@ -237,7 +236,7 @@ void UITask::renderCurrScreen() { // freq / sf _display->setCursor(0, 20); - _display->setColor(DisplayDriver::YELLOW); + _display->setColor(UIColor::secondary_txt); sprintf(tmp, "FREQ: %06.3f SF%d", _node_prefs->freq, _node_prefs->sf); _display->print(tmp); @@ -248,14 +247,14 @@ void UITask::renderCurrScreen() { // BT pin if (!_connected && the_mesh.getBLEPin() != 0) { - _display->setColor(DisplayDriver::RED); + _display->setColor(UIColor::warning_txt); _display->setTextSize(2); _display->setCursor(0, 43); sprintf(tmp, "Pin:%d", the_mesh.getBLEPin()); _display->print(tmp); - _display->setColor(DisplayDriver::GREEN); + _display->setColor(UIColor::primary_txt); } else { - _display->setColor(DisplayDriver::LIGHT); + _display->setColor(UIColor::primary_txt); } } _need_refresh = false; diff --git a/examples/companion_radio/ui-tiny/ScrollingStatusBar.h b/examples/companion_radio/ui-tiny/ScrollingStatusBar.h index f5943c9b..9967489f 100644 --- a/examples/companion_radio/ui-tiny/ScrollingStatusBar.h +++ b/examples/companion_radio/ui-tiny/ScrollingStatusBar.h @@ -104,7 +104,7 @@ public: if (_status[0] == 0) return; display.setTextSize(1); - display.setColor(DisplayDriver::GREEN); + display.setColor(UIColor::primary_txt); // if (_needs_redraw) { // _text_width = display.getTextWidth(_status); diff --git a/examples/companion_radio/ui-tiny/UITask.cpp b/examples/companion_radio/ui-tiny/UITask.cpp index 452c02d4..5b9ebfd3 100644 --- a/examples/companion_radio/ui-tiny/UITask.cpp +++ b/examples/companion_radio/ui-tiny/UITask.cpp @@ -56,24 +56,24 @@ public: int render(DisplayDriver& display) override { if (millis() < version_after) { // meshcore logo - display.setColor(DisplayDriver::BLUE); + display.setColor(UIColor::corp_blue); int logoWidth = 72; display.drawXbm(0, 0, meshcore_logo, 72, 36); } else { // meshcore website const char* website = "meshcore.io"; - display.setColor(DisplayDriver::LIGHT); + display.setColor(UIColor::primary_txt); display.setTextSize(1); uint16_t websiteWidth = display.getTextWidth(website); display.setCursor((display.width() - websiteWidth) / 2, 9); display.print(website); // version info - display.setColor(DisplayDriver::LIGHT); display.setTextSize(1); display.drawTextCentered(display.width()/2, 18, _version_info); + display.setColor(UIColor::secondary_txt); display.setTextSize(1); display.drawTextCentered(display.width()/2, 27, FIRMWARE_BUILD_DATE); } @@ -163,7 +163,7 @@ public: // display.print(filtered_name); - display.setColor(DisplayDriver::YELLOW); + display.setColor(UIColor::primary_txt); display.setTextSize(2); sprintf(tmp, "MSG: %d", _task->getMsgCount()); display.setCursor(0, 10); @@ -180,19 +180,19 @@ public: display.drawTextCentered(display.width() / 2, 54, tmp); #endif if (_task->hasConnection()) { - display.setColor(DisplayDriver::GREEN); + display.setColor(UIColor::warning_txt); display.setTextSize(1); display.drawTextCentered(display.width() / 2, display.height()-8, "< Connected >"); } else if (the_mesh.getBLEPin() != 0) { // BT pin - display.setColor(DisplayDriver::RED); + display.setColor(UIColor::warning_txt); display.setTextSize(2); sprintf(tmp, "Pin:%d", the_mesh.getBLEPin()); display.drawTextCentered(display.width() / 2, display.height()-8, tmp); } } else if (_page == HomePage::RECENT) { the_mesh.getRecentlyHeard(recent, UI_RECENT_LIST_SIZE); - display.setColor(DisplayDriver::GREEN); + display.setColor(UIColor::primary_txt); int y = 8; for (int i = 0; i < UI_RECENT_LIST_SIZE; i++, y += 11) { auto a = &recent[i]; @@ -216,7 +216,7 @@ public: display.print(tmp); } } else if (_page == HomePage::RADIO) { - display.setColor(DisplayDriver::YELLOW); + display.setColor(UIColor::primary_txt); display.setTextSize(1); // frequency and spreading factor display.setCursor(0, 8); @@ -238,14 +238,14 @@ public: display.drawTextRightAlign(display.width(), 26, tmp); } else if (_page == HomePage::BLUETOOTH) { - display.setColor(DisplayDriver::GREEN); + display.setColor(UIColor::corp_blue); display.drawXbm((display.width() - 32) / 2, 8, _task->isSerialEnabled() ? bluetooth_on : bluetooth_off, 32, 32); display.setTextSize(1); // display.drawTextCentered(display.width() / 2, 40 - 11, "toggle: " PRESS_LABEL); } else if (_page == HomePage::ADVERT) { - display.setColor(DisplayDriver::GREEN); + display.setColor(UIColor::corp_blue); display.drawXbm((display.width() - 32) / 2, 8, advert_icon, 32, 32); // display.drawTextCentered(display.width() / 2, 40 - 11, "advert: " PRESS_LABEL); #if ENV_INCLUDE_GPS == 1 @@ -264,9 +264,11 @@ public: #else strcpy(buf, gps_state ? "gps on" : "gps off"); #endif + display.setColor(UIColor::primary_txt); display.drawTextLeftAlign(0, y, buf); if (nmea == NULL) { // y = y + 8; + display.setColor(UIColor::warning_txt); display.drawTextLeftAlign(0, y, "Can't access GPS"); } else { if (!gps_state || !nmea->isValid()) { @@ -274,6 +276,7 @@ public: } else { sprintf(buf, "%d sat", nmea->satellitesCount()); } + display.setColor(UIColor::primary_txt); display.drawTextRightAlign(display.width()-1, y, buf); y = y + 8; sprintf(buf, "lat %.4f", @@ -349,8 +352,10 @@ public: r.skipData(type); strcpy(name, "unk"); sprintf(buf, ""); } + display.setColor(UIColor::secondary_txt); display.setCursor(0, y); display.print(name); + display.setColor(UIColor::primary_txt); display.setCursor( display.width()-display.getTextWidth(buf)-1, y ); @@ -361,7 +366,7 @@ public: else sensors_scroll_offset = 0; #endif } else if (_page == HomePage::SHUTDOWN) { - display.setColor(DisplayDriver::GREEN); + display.setColor(UIColor::secondary_txt); display.setTextSize(1); if (_shutdown_init) { display.drawTextCentered(display.width() / 2, 20, "hibernating..."); @@ -692,9 +697,9 @@ void UITask::loop() { _display->setTextSize(1); int y = _display->height() / 3; int p = _display->height() / 32; - _display->setColor(DisplayDriver::DARK); + _display->setColor(UIColor::popup_bkg); _display->fillRect(p, y, _display->width() - p*2, y); - _display->setColor(DisplayDriver::LIGHT); // draw box border + _display->setColor(UIColor::popup_txt); // draw box border _display->drawRect(p, y, _display->width() - p*2, y); _display->drawTextCentered(_display->width() / 2, y + p*3, _alert); _next_refresh = _alert_expiry; // will need refresh when alert is dismissed diff --git a/examples/simple_repeater/UITask.cpp b/examples/simple_repeater/UITask.cpp index 6751aad6..e7225557 100644 --- a/examples/simple_repeater/UITask.cpp +++ b/examples/simple_repeater/UITask.cpp @@ -57,18 +57,17 @@ void UITask::renderCurrScreen() { char tmp[80]; if (millis() < _started_at + BOOT_SCREEN_MILLIS) { // boot screen // meshcore logo - _display->setColor(DisplayDriver::BLUE); + _display->setColor(UIColor::corp_blue); int logoWidth = 128; _display->drawXbm((_display->width() - logoWidth) / 2, 3, meshcore_logo, logoWidth, 13); // meshcore website const char* website = "https://meshcore.io"; - _display->setColor(DisplayDriver::LIGHT); + _display->setColor(UIColor::primary_txt); _display->setTextSize(1); _display->drawTextCentered(_display->width() / 2, 22, website); // version info - _display->setColor(DisplayDriver::LIGHT); _display->setTextSize(1); _display->drawTextCentered(_display->width() / 2, 35, _version_info); @@ -77,13 +76,13 @@ void UITask::renderCurrScreen() { _display->drawTextCentered(_display->width() / 2, 48, node_type); } else if (_powering_off_at > 0) { // meshcore logo - _display->setColor(DisplayDriver::BLUE); + _display->setColor(UIColor::corp_blue); int logoWidth = 128; _display->drawXbm((_display->width() - logoWidth) / 2, 3, meshcore_logo, logoWidth, 13); // meshcore website const char* website = "https://meshcore.io"; - _display->setColor(DisplayDriver::LIGHT); + _display->setColor(UIColor::primary_txt); _display->setTextSize(1); _display->drawTextCentered(_display->width()/ 2, 22, website); @@ -95,12 +94,11 @@ void UITask::renderCurrScreen() { } else { _display->setCursor(0, 0); _display->setTextSize(1); - _display->setColor(DisplayDriver::GREEN); + _display->setColor(UIColor::primary_txt); _display->print(_node_prefs->node_name); // freq / sf _display->setCursor(0, 20); - _display->setColor(DisplayDriver::YELLOW); sprintf(tmp, "FREQ: %06.3f SF%d", _node_prefs->freq, _node_prefs->sf); _display->print(tmp); diff --git a/examples/simple_room_server/UITask.cpp b/examples/simple_room_server/UITask.cpp index fb66b819..8e4c2fcf 100644 --- a/examples/simple_room_server/UITask.cpp +++ b/examples/simple_room_server/UITask.cpp @@ -49,20 +49,19 @@ void UITask::renderCurrScreen() { char tmp[80]; if (millis() < BOOT_SCREEN_MILLIS) { // boot screen // meshcore logo - _display->setColor(DisplayDriver::BLUE); + _display->setColor(UIColor::corp_blue); int logoWidth = 128; _display->drawXbm((_display->width() - logoWidth) / 2, 3, meshcore_logo, logoWidth, 13); // meshcore website const char* website = "https://meshcore.io"; - _display->setColor(DisplayDriver::LIGHT); + _display->setColor(UIColor::primary_txt); _display->setTextSize(1); uint16_t websiteWidth = _display->getTextWidth(website); _display->setCursor((_display->width() - websiteWidth) / 2, 22); _display->print(website); // version info - _display->setColor(DisplayDriver::LIGHT); _display->setTextSize(1); uint16_t versionWidth = _display->getTextWidth(_version_info); _display->setCursor((_display->width() - versionWidth) / 2, 35); @@ -77,12 +76,11 @@ void UITask::renderCurrScreen() { // node name _display->setCursor(0, 0); _display->setTextSize(1); - _display->setColor(DisplayDriver::GREEN); + _display->setColor(UIColor::primary_txt); _display->print(_node_prefs->node_name); // freq / sf _display->setCursor(0, 20); - _display->setColor(DisplayDriver::YELLOW); sprintf(tmp, "FREQ: %06.3f SF%d", _node_prefs->freq, _node_prefs->sf); _display->print(tmp); diff --git a/examples/simple_sensor/UITask.cpp b/examples/simple_sensor/UITask.cpp index 68a80607..75a0b465 100644 --- a/examples/simple_sensor/UITask.cpp +++ b/examples/simple_sensor/UITask.cpp @@ -49,20 +49,19 @@ void UITask::renderCurrScreen() { char tmp[80]; if (millis() < BOOT_SCREEN_MILLIS) { // boot screen // meshcore logo - _display->setColor(DisplayDriver::BLUE); + _display->setColor(UIColor::corp_blue); int logoWidth = 128; _display->drawXbm((_display->width() - logoWidth) / 2, 3, meshcore_logo, logoWidth, 13); // meshcore website const char* website = "https://meshcore.io"; - _display->setColor(DisplayDriver::LIGHT); + _display->setColor(UIColor::primary_txt); _display->setTextSize(1); uint16_t websiteWidth = _display->getTextWidth(website); _display->setCursor((_display->width() - websiteWidth) / 2, 22); _display->print(website); // version info - _display->setColor(DisplayDriver::LIGHT); _display->setTextSize(1); uint16_t versionWidth = _display->getTextWidth(_version_info); _display->setCursor((_display->width() - versionWidth) / 2, 35); @@ -77,12 +76,11 @@ void UITask::renderCurrScreen() { // node name _display->setCursor(0, 0); _display->setTextSize(1); - _display->setColor(DisplayDriver::GREEN); + _display->setColor(UIColor::primary_txt); _display->print(_node_prefs->node_name); // freq / sf _display->setCursor(0, 20); - _display->setColor(DisplayDriver::YELLOW); sprintf(tmp, "FREQ: %06.3f SF%d", _node_prefs->freq, _node_prefs->sf); _display->print(tmp); diff --git a/src/helpers/ui/DisplayDriver.h b/src/helpers/ui/DisplayDriver.h index dcc5fe03..b76a1b6c 100644 --- a/src/helpers/ui/DisplayDriver.h +++ b/src/helpers/ui/DisplayDriver.h @@ -3,12 +3,20 @@ #include #include +using ColorVal = uint16_t; + +class UIColor { +public: + // color definitions (by element _type_) + static ColorVal window_bkg, title_bkg, title_txt, primary_txt, secondary_txt, warning_txt, popup_bkg, popup_txt, corp_blue; +}; + class DisplayDriver { int _w, _h; protected: DisplayDriver(int w, int h) { _w = w; _h = h; } public: - enum Color { DARK=0, LIGHT, RED, GREEN, BLUE, YELLOW, ORANGE }; // on b/w screen, colors will be !=0 synonym of light + //enum Color { DARK=0, LIGHT, RED, GREEN, BLUE, YELLOW, ORANGE }; // on b/w screen, colors will be !=0 synonym of light int width() const { return _w; } int height() const { return _h; } @@ -18,9 +26,9 @@ public: virtual void turnOn() = 0; virtual void turnOff() = 0; virtual void clear() = 0; - virtual void startFrame(Color bkg = DARK) = 0; + virtual void startFrame(ColorVal bkg = UIColor::window_bkg) = 0; virtual void setTextSize(int sz) = 0; - virtual void setColor(Color c) = 0; + virtual void setColor(ColorVal c) = 0; virtual void setCursor(int x, int y) = 0; virtual void print(const char* str) = 0; virtual void printWordWrap(const char* str, int max_width) { print(str); } // fallback to basic print() if no override diff --git a/src/helpers/ui/E213Display.cpp b/src/helpers/ui/E213Display.cpp index 814693a0..ab742976 100644 --- a/src/helpers/ui/E213Display.cpp +++ b/src/helpers/ui/E213Display.cpp @@ -2,6 +2,17 @@ #include "../../MeshCore.h" +// Color scheme +ColorVal UIColor::window_bkg = WHITE; +ColorVal UIColor::title_bkg = BLACK; +ColorVal UIColor::title_txt = WHITE; +ColorVal UIColor::primary_txt = BLACK; +ColorVal UIColor::secondary_txt = BLACK; +ColorVal UIColor::warning_txt = BLACK; +ColorVal UIColor::popup_bkg = BLACK; +ColorVal UIColor::popup_txt = WHITE; +ColorVal UIColor::corp_blue = BLACK; + BaseDisplay* E213Display::detectEInk() { // Test 1: Logic of BUSY pin @@ -108,16 +119,18 @@ void E213Display::clear() { display->clear(); } -void E213Display::startFrame(Color bkg) { +void E213Display::startFrame(ColorVal bkg) { display_crc.reset(); // Fill screen with white first to ensure clean background display->fillRect(0, 0, width(), height(), WHITE); - if (bkg == LIGHT) { + if (bkg == 0) { // Fill with black if light background requested (inverted for e-ink) display->fillRect(0, 0, width(), height(), BLACK); } + _color = UIColor::primary_txt; + display->setTextColor(_color); } void E213Display::setTextSize(int sz) { @@ -126,9 +139,10 @@ void E213Display::setTextSize(int sz) { display->setTextSize(sz); } -void E213Display::setColor(Color c) { - display_crc.update(c); - // implemented in individual display methods +void E213Display::setColor(ColorVal c) { + _color = c; + display_crc.update(c); + display->setTextColor(_color); } void E213Display::setCursor(int x, int y) { @@ -147,7 +161,7 @@ void E213Display::fillRect(int x, int y, int w, int h) { display_crc.update(y); display_crc.update(w); display_crc.update(h); - display->fillRect(x, y, w, h, BLACK); + display->fillRect(x, y, w, h, _color); } void E213Display::drawRect(int x, int y, int w, int h) { @@ -155,7 +169,7 @@ void E213Display::drawRect(int x, int y, int w, int h) { display_crc.update(y); display_crc.update(w); display_crc.update(h); - display->drawRect(x, y, w, h, BLACK); + display->drawRect(x, y, w, h, _color); } void E213Display::drawXbm(int x, int y, const uint8_t *bits, int w, int h) { @@ -179,7 +193,7 @@ void E213Display::drawXbm(int x, int y, const uint8_t *bits, int w, int h) { // If the bit is set, draw the pixel if (bitSet) { - display->drawPixel(x + bx, y + by, BLACK); + display->drawPixel(x + bx, y + by, _color); } } } diff --git a/src/helpers/ui/E213Display.h b/src/helpers/ui/E213Display.h index add8f11b..32567a79 100644 --- a/src/helpers/ui/E213Display.h +++ b/src/helpers/ui/E213Display.h @@ -16,6 +16,7 @@ class E213Display : public DisplayDriver { RefCountedDigitalPin* _periph_power; CRC32 display_crc; uint32_t last_display_crc_value = 0; + uint16_t _color; public: E213Display(RefCountedDigitalPin* periph_power = NULL) : DisplayDriver(250, 122), _periph_power(periph_power) {} @@ -30,9 +31,9 @@ public: void turnOn() override; void turnOff() override; void clear() override; - void startFrame(Color bkg = DARK) override; + void startFrame(ColorVal bkg = UIColor::window_bkg) override; void setTextSize(int sz) override; - void setColor(Color c) override; + void setColor(ColorVal c) override; void setCursor(int x, int y) override; void print(const char *str) override; void fillRect(int x, int y, int w, int h) override; diff --git a/src/helpers/ui/E290Display.cpp b/src/helpers/ui/E290Display.cpp index ef4df05e..ddb449f4 100644 --- a/src/helpers/ui/E290Display.cpp +++ b/src/helpers/ui/E290Display.cpp @@ -2,6 +2,17 @@ #include "../../MeshCore.h" +// Color scheme +ColorVal UIColor::window_bkg = WHITE; +ColorVal UIColor::title_bkg = BLACK; +ColorVal UIColor::title_txt = WHITE; +ColorVal UIColor::primary_txt = BLACK; +ColorVal UIColor::secondary_txt = BLACK; +ColorVal UIColor::warning_txt = BLACK; +ColorVal UIColor::popup_bkg = BLACK; +ColorVal UIColor::popup_txt = WHITE; +ColorVal UIColor::corp_blue = BLACK; + bool E290Display::begin() { if (_init) return true; @@ -62,15 +73,17 @@ void E290Display::clear() { display.clear(); } -void E290Display::startFrame(Color bkg) { +void E290Display::startFrame(ColorVal bkg) { display_crc.reset(); // Fill screen with white first to ensure clean background display.fillRect(0, 0, width(), height(), WHITE); - if (bkg == LIGHT) { + if (bkg == 0) { // Fill with black if light background requested (inverted for e-ink) display.fillRect(0, 0, width(), height(), BLACK); } + _color = UIColor::primary_txt; + display.setTextColor(_color); } void E290Display::setTextSize(int sz) { @@ -79,9 +92,10 @@ void E290Display::setTextSize(int sz) { display.setTextSize(sz); } -void E290Display::setColor(Color c) { - display_crc.update(c); - // implemented in individual display methods +void E290Display::setColor(ColorVal c) { + _color = c; + display_crc.update(c); + display.setTextColor(_color); } void E290Display::setCursor(int x, int y) { @@ -100,7 +114,7 @@ void E290Display::fillRect(int x, int y, int w, int h) { display_crc.update(y); display_crc.update(w); display_crc.update(h); - display.fillRect(x, y, w, h, BLACK); + display.fillRect(x, y, w, h, _color); } void E290Display::drawRect(int x, int y, int w, int h) { @@ -108,7 +122,7 @@ void E290Display::drawRect(int x, int y, int w, int h) { display_crc.update(y); display_crc.update(w); display_crc.update(h); - display.drawRect(x, y, w, h, BLACK); + display.drawRect(x, y, w, h, _color); } void E290Display::drawXbm(int x, int y, const uint8_t *bits, int w, int h) { @@ -132,7 +146,7 @@ void E290Display::drawXbm(int x, int y, const uint8_t *bits, int w, int h) { // If the bit is set, draw the pixel if (bitSet) { - display.drawPixel(x + bx, y + by, BLACK); + display.drawPixel(x + bx, y + by, _color); } } } diff --git a/src/helpers/ui/E290Display.h b/src/helpers/ui/E290Display.h index 88bf34ff..bf6296bb 100644 --- a/src/helpers/ui/E290Display.h +++ b/src/helpers/ui/E290Display.h @@ -16,6 +16,7 @@ class E290Display : public DisplayDriver { RefCountedDigitalPin* _periph_power; CRC32 display_crc; uint32_t last_display_crc_value = 0; + uint16_t _color; public: E290Display(RefCountedDigitalPin* periph_power = NULL) : DisplayDriver(296, 128), _periph_power(periph_power) {} @@ -26,9 +27,9 @@ public: void turnOn() override; void turnOff() override; void clear() override; - void startFrame(Color bkg = DARK) override; + void startFrame(ColorVal bkg = UIColor::window_bkg) override; void setTextSize(int sz) override; - void setColor(Color c) override; + void setColor(ColorVal c) override; void setCursor(int x, int y) override; void print(const char *str) override; void fillRect(int x, int y, int w, int h) override; diff --git a/src/helpers/ui/GxEPDDisplay.cpp b/src/helpers/ui/GxEPDDisplay.cpp index ad47754b..0a5f6a55 100644 --- a/src/helpers/ui/GxEPDDisplay.cpp +++ b/src/helpers/ui/GxEPDDisplay.cpp @@ -14,6 +14,18 @@ SPIClass SPI1 = SPIClass(FSPI); #endif +// Color scheme +ColorVal UIColor::window_bkg = GxEPD_WHITE; +ColorVal UIColor::title_bkg = GxEPD_BLACK; +ColorVal UIColor::title_txt = GxEPD_WHITE; +ColorVal UIColor::primary_txt = GxEPD_BLACK; +ColorVal UIColor::secondary_txt = GxEPD_BLACK; +ColorVal UIColor::warning_txt = GxEPD_BLACK; +ColorVal UIColor::popup_bkg = GxEPD_BLACK; +ColorVal UIColor::popup_txt = GxEPD_WHITE; +ColorVal UIColor::corp_blue = GxEPD_BLACK; + + bool GxEPDDisplay::begin() { display.epd2.selectSPI(SPI1, SPISettings(4000000, MSBFIRST, SPI_MODE0)); #ifdef ESP32 @@ -61,9 +73,9 @@ void GxEPDDisplay::clear() { display_crc.reset(); } -void GxEPDDisplay::startFrame(Color bkg) { - display.fillScreen(GxEPD_WHITE); - display.setTextColor(_curr_color = GxEPD_BLACK); +void GxEPDDisplay::startFrame(ColorVal bkg) { + display.fillScreen(bkg); + display.setTextColor(_curr_color = UIColor::primary_txt); display_crc.reset(); } @@ -85,14 +97,9 @@ void GxEPDDisplay::setTextSize(int sz) { } } -void GxEPDDisplay::setColor(Color c) { - display_crc.update (c); - // colours need to be inverted for epaper displays - if (c == DARK) { - display.setTextColor(_curr_color = GxEPD_WHITE); - } else { - display.setTextColor(_curr_color = GxEPD_BLACK); - } +void GxEPDDisplay::setColor(ColorVal c) { + display_crc.update (c); + display.setTextColor(_curr_color = c); } void GxEPDDisplay::setCursor(int x, int y) { diff --git a/src/helpers/ui/GxEPDDisplay.h b/src/helpers/ui/GxEPDDisplay.h index 219b6076..c653eac4 100644 --- a/src/helpers/ui/GxEPDDisplay.h +++ b/src/helpers/ui/GxEPDDisplay.h @@ -51,9 +51,9 @@ public: void turnOn() override; void turnOff() override; void clear() override; - void startFrame(Color bkg = DARK) override; + void startFrame(ColorVal bkg = UIColor::window_bkg) override; void setTextSize(int sz) override; - void setColor(Color c) override; + void setColor(ColorVal c) override; void setCursor(int x, int y) override; void print(const char* str) override; void fillRect(int x, int y, int w, int h) override; diff --git a/src/helpers/ui/LGFXDisplay.cpp b/src/helpers/ui/LGFXDisplay.cpp index a53cbc62..7bdd52a2 100644 --- a/src/helpers/ui/LGFXDisplay.cpp +++ b/src/helpers/ui/LGFXDisplay.cpp @@ -1,5 +1,16 @@ #include "LGFXDisplay.h" +// Color scheme +ColorVal UIColor::window_bkg = 0xFFFF; +ColorVal UIColor::title_bkg = 0x001F; +ColorVal UIColor::title_txt = 0xFFFF; +ColorVal UIColor::primary_txt = 0x0000; +ColorVal UIColor::secondary_txt = (18 << 11) | (36 << 5) | 18; // mid-gray +ColorVal UIColor::warning_txt = 0xFD20; +ColorVal UIColor::popup_bkg = 0x07FF; // CYAN +ColorVal UIColor::popup_txt = 0x0000; +ColorVal UIColor::corp_blue = 0x001A; + bool LGFXDisplay::begin() { turnOn(); display->init(); @@ -35,45 +46,20 @@ void LGFXDisplay::clear() { buffer.clearDisplay(); } -void LGFXDisplay::startFrame(Color bkg) { +void LGFXDisplay::startFrame(ColorVal bkg) { // display->startWrite(); // display->getScanLine(); - buffer.clearDisplay(); - buffer.setTextColor(TFT_WHITE); + _color = bkg; + buffer.fillScreen(_color); + buffer.setTextColor(_color = UIColor::primary_txt); } void LGFXDisplay::setTextSize(int sz) { buffer.setTextSize(sz); } -void LGFXDisplay::setColor(Color c) { - // _color = (c != 0) ? ILI9342_WHITE : ILI9342_BLACK; - switch (c) { - case DARK: - _color = TFT_BLACK; - break; - case LIGHT: - _color = TFT_WHITE; - break; - case RED: - _color = TFT_RED; - break; - case GREEN: - _color = TFT_GREEN; - break; - case BLUE: - _color = TFT_BLUE; - break; - case YELLOW: - _color = TFT_YELLOW; - break; - case ORANGE: - _color = TFT_ORANGE; - break; - default: - _color = TFT_WHITE; - } - buffer.setTextColor(_color); +void LGFXDisplay::setColor(ColorVal c) { + buffer.setTextColor(_color = c); } void LGFXDisplay::setCursor(int x, int y) { diff --git a/src/helpers/ui/LGFXDisplay.h b/src/helpers/ui/LGFXDisplay.h index ad7212ec..a2d660b2 100644 --- a/src/helpers/ui/LGFXDisplay.h +++ b/src/helpers/ui/LGFXDisplay.h @@ -25,9 +25,9 @@ public: void turnOn() override; void turnOff() override; void clear() override; - void startFrame(Color bkg = DARK) override; + void startFrame(ColorVal bkg = UIColor::window_bkg) override; void setTextSize(int sz) override; - void setColor(Color c) override; + void setColor(ColorVal c) override; void setCursor(int x, int y) override; void print(const char* str) override; void fillRect(int x, int y, int w, int h) override; diff --git a/src/helpers/ui/NV3001BDisplay.cpp b/src/helpers/ui/NV3001BDisplay.cpp index 03825cc0..1ff7765c 100644 --- a/src/helpers/ui/NV3001BDisplay.cpp +++ b/src/helpers/ui/NV3001BDisplay.cpp @@ -96,18 +96,16 @@ #define NV3001B_TEXT_SIZE2_SCALE_Y 3 #endif -static uint16_t mapColor(DisplayDriver::Color c) { - switch (c) { - case DisplayDriver::DARK: return 0x0000; - case DisplayDriver::LIGHT: return 0xffff; - case DisplayDriver::RED: return 0xf800; - case DisplayDriver::GREEN: return 0x07e0; - case DisplayDriver::BLUE: return 0x001f; - case DisplayDriver::YELLOW: return 0xffe0; - case DisplayDriver::ORANGE: return 0xfd20; - default: return 0xffff; - } -} +// Color scheme +ColorVal UIColor::window_bkg = 0xFFFF; +ColorVal UIColor::title_bkg = 0x001F; +ColorVal UIColor::title_txt = 0xFFFF; +ColorVal UIColor::primary_txt = 0x0000; +ColorVal UIColor::secondary_txt = (18 << 11) | (36 << 5) | 18; // mid-gray +ColorVal UIColor::warning_txt = 0xFD20; +ColorVal UIColor::popup_bkg = 0x07FF; // CYAN +ColorVal UIColor::popup_txt = 0x0000; +ColorVal UIColor::corp_blue = 0x001A; static int scaleX(int x) { return (int)(x * DISPLAY_SCALE_X); @@ -465,15 +463,15 @@ void NV3001BDisplay::turnOff() { void NV3001BDisplay::clear() { uint16_t saved = color; - color = 0x0000; + color = UIColor::window_bkg; fillPhysicalRect(0, 0, NV3001B_SCREEN_WIDTH, NV3001B_SCREEN_HEIGHT); color = saved; } -void NV3001BDisplay::startFrame(Color bkg) { - color = mapColor(bkg); +void NV3001BDisplay::startFrame(ColorVal bkg) { + color = bkg; fillPhysicalRect(0, 0, NV3001B_SCREEN_WIDTH, NV3001B_SCREEN_HEIGHT); - color = 0xffff; + color = UIColor::primary_txt; text_size = 1; cursor_x = 0; cursor_y = 0; @@ -483,8 +481,8 @@ void NV3001BDisplay::setTextSize(int sz) { text_size = sz < 1 ? 1 : sz; } -void NV3001BDisplay::setColor(Color c) { - color = mapColor(c); +void NV3001BDisplay::setColor(ColorVal c) { + color = c; } void NV3001BDisplay::setCursor(int x, int y) { diff --git a/src/helpers/ui/NV3001BDisplay.h b/src/helpers/ui/NV3001BDisplay.h index 98cdaae8..76505b5d 100644 --- a/src/helpers/ui/NV3001BDisplay.h +++ b/src/helpers/ui/NV3001BDisplay.h @@ -55,9 +55,9 @@ public: void turnOn() override; void turnOff() override; void clear() override; - void startFrame(Color bkg = DARK) override; + void startFrame(ColorVal bkg = UIColor::window_bkg) override; void setTextSize(int sz) override; - void setColor(Color c) override; + void setColor(ColorVal c) override; void setCursor(int x, int y) override; void print(const char* str) override; void fillRect(int x, int y, int w, int h) override; diff --git a/src/helpers/ui/NullDisplayDriver.h b/src/helpers/ui/NullDisplayDriver.h index 2a9670bd..ff214c88 100644 --- a/src/helpers/ui/NullDisplayDriver.h +++ b/src/helpers/ui/NullDisplayDriver.h @@ -11,9 +11,9 @@ public: void turnOn() override { } void turnOff() override { } void clear() override { } - void startFrame(Color bkg = DARK) override { } + void startFrame(ColorVal bkg = UIColor::window_bkg) override { } void setTextSize(int sz) override { } - void setColor(Color c) override { } + void setColor(ColorVal c) override { } void setCursor(int x, int y) override { } void print(const char* str) override { } void fillRect(int x, int y, int w, int h) override { } diff --git a/src/helpers/ui/SH1106Display.cpp b/src/helpers/ui/SH1106Display.cpp index 57ccfc2e..aeb4f300 100644 --- a/src/helpers/ui/SH1106Display.cpp +++ b/src/helpers/ui/SH1106Display.cpp @@ -9,6 +9,17 @@ bool SH1106Display::i2c_probe(TwoWire &wire, uint8_t addr) return (error == 0); } +// Color scheme +ColorVal UIColor::window_bkg = SH110X_BLACK; +ColorVal UIColor::title_bkg = SH110X_WHITE; +ColorVal UIColor::title_txt = SH110X_BLACK; +ColorVal UIColor::primary_txt = SH110X_WHITE; +ColorVal UIColor::secondary_txt = SH110X_WHITE; +ColorVal UIColor::warning_txt = SH110X_WHITE; +ColorVal UIColor::popup_bkg = SH110X_WHITE; +ColorVal UIColor::popup_txt = SH110X_BLACK; +ColorVal UIColor::corp_blue = SH110X_WHITE; + bool SH1106Display::begin() { // Wire must already be initialised by board.begin() before this is called. @@ -35,7 +46,7 @@ void SH1106Display::clear() display.display(); } -void SH1106Display::startFrame(Color bkg) +void SH1106Display::startFrame(ColorVal bkg) { display.clearDisplay(); // TODO: apply 'bkg' _color = SH110X_WHITE; @@ -49,9 +60,9 @@ void SH1106Display::setTextSize(int sz) display.setTextSize(sz); } -void SH1106Display::setColor(Color c) +void SH1106Display::setColor(ColorVal c) { - _color = (c != 0) ? SH110X_WHITE : SH110X_BLACK; + _color = c; display.setTextColor(_color); } @@ -77,7 +88,7 @@ void SH1106Display::drawRect(int x, int y, int w, int h) void SH1106Display::drawXbm(int x, int y, const uint8_t *bits, int w, int h) { - display.drawBitmap(x, y, bits, w, h, SH110X_WHITE); + display.drawBitmap(x, y, bits, w, h, _color); } uint16_t SH1106Display::getTextWidth(const char *str) diff --git a/src/helpers/ui/SH1106Display.h b/src/helpers/ui/SH1106Display.h index b52a6adf..4e269d5e 100644 --- a/src/helpers/ui/SH1106Display.h +++ b/src/helpers/ui/SH1106Display.h @@ -30,9 +30,9 @@ public: void turnOn() override; void turnOff() override; void clear() override; - void startFrame(Color bkg = DARK) override; + void startFrame(ColorVal bkg = UIColor::window_bkg) override; void setTextSize(int sz) override; - void setColor(Color c) override; + void setColor(ColorVal c) override; void setCursor(int x, int y) override; void print(const char *str) override; void fillRect(int x, int y, int w, int h) override; diff --git a/src/helpers/ui/SSD1306Display.cpp b/src/helpers/ui/SSD1306Display.cpp index 464b2642..9b858071 100644 --- a/src/helpers/ui/SSD1306Display.cpp +++ b/src/helpers/ui/SSD1306Display.cpp @@ -6,6 +6,17 @@ bool SSD1306Display::i2c_probe(TwoWire& wire, uint8_t addr) { return (error == 0); } +// Color scheme +ColorVal UIColor::window_bkg = SSD1306_BLACK; +ColorVal UIColor::title_bkg = SSD1306_WHITE; +ColorVal UIColor::title_txt = SSD1306_BLACK; +ColorVal UIColor::primary_txt = SSD1306_WHITE; +ColorVal UIColor::secondary_txt = SSD1306_WHITE; +ColorVal UIColor::warning_txt = SSD1306_WHITE; +ColorVal UIColor::popup_bkg = SSD1306_WHITE; +ColorVal UIColor::popup_txt = SSD1306_BLACK; +ColorVal UIColor::corp_blue = SSD1306_WHITE; + bool SSD1306Display::begin() { if (!_isOn) { if (_peripher_power) _peripher_power->claim(); @@ -44,7 +55,7 @@ void SSD1306Display::clear() { display.display(); } -void SSD1306Display::startFrame(Color bkg) { +void SSD1306Display::startFrame(ColorVal bkg) { display.clearDisplay(); // TODO: apply 'bkg' _color = SSD1306_WHITE; display.setTextColor(_color); @@ -56,8 +67,8 @@ void SSD1306Display::setTextSize(int sz) { display.setTextSize(sz); } -void SSD1306Display::setColor(Color c) { - _color = (c != 0) ? SSD1306_WHITE : SSD1306_BLACK; +void SSD1306Display::setColor(ColorVal c) { + _color = c; display.setTextColor(_color); } @@ -78,7 +89,7 @@ void SSD1306Display::drawRect(int x, int y, int w, int h) { } void SSD1306Display::drawXbm(int x, int y, const uint8_t* bits, int w, int h) { - display.drawBitmap(x, y, bits, w, h, SSD1306_WHITE); + display.drawBitmap(x, y, bits, w, h, _color); } uint16_t SSD1306Display::getTextWidth(const char* str) { diff --git a/src/helpers/ui/SSD1306Display.h b/src/helpers/ui/SSD1306Display.h index d843da85..5dabbc58 100644 --- a/src/helpers/ui/SSD1306Display.h +++ b/src/helpers/ui/SSD1306Display.h @@ -35,9 +35,9 @@ public: void turnOn() override; void turnOff() override; void clear() override; - void startFrame(Color bkg = DARK) override; + void startFrame(ColorVal bkg = UIColor::window_bkg) override; void setTextSize(int sz) override; - void setColor(Color c) override; + void setColor(ColorVal c) override; void setCursor(int x, int y) override; void print(const char* str) override; void fillRect(int x, int y, int w, int h) override; diff --git a/src/helpers/ui/ST7735Display.cpp b/src/helpers/ui/ST7735Display.cpp index 905ff503..344f5b1d 100644 --- a/src/helpers/ui/ST7735Display.cpp +++ b/src/helpers/ui/ST7735Display.cpp @@ -417,6 +417,17 @@ bool ST7735Display::i2c_probe(TwoWire& wire, uint8_t addr) { #define PIN_TFT_LEDA_CTL_ACTIVE HIGH #endif +// Color scheme +ColorVal UIColor::window_bkg = ST77XX_WHITE; +ColorVal UIColor::title_bkg = ST77XX_BLUE; +ColorVal UIColor::title_txt = ST77XX_WHITE; +ColorVal UIColor::primary_txt = ST77XX_BLACK; +ColorVal UIColor::secondary_txt = (18 << 11) | (36 << 5) | 18; // mid-gray +ColorVal UIColor::warning_txt = ST77XX_ORANGE; +ColorVal UIColor::popup_bkg = ST77XX_CYAN; +ColorVal UIColor::popup_txt = ST77XX_BLACK; +ColorVal UIColor::corp_blue = 0x001A; + bool ST7735Display::begin() { if (!sprite) { // alloc offscreen canvas @@ -527,9 +538,9 @@ void ST7735Display::clear() { sprite->fillScreen(ST77XX_BLACK); } -void ST7735Display::startFrame(Color bkg) { - sprite->fillScreen(ST77XX_BLACK); - sprite->setTextColor(curr_color = ST77XX_WHITE); +void ST7735Display::startFrame(ColorVal bkg) { + sprite->fillScreen(bkg); + sprite->setTextColor(curr_color = UIColor::primary_txt); sprite->setFreeFont(); sprite->setTextSize(1); // This one affects size of Please wait... message //sprite->cp437(true); // Use full 256 char 'Code Page 437' font @@ -539,33 +550,8 @@ void ST7735Display::setTextSize(int sz) { sprite->setTextSize(sz); } -void ST7735Display::setColor(Color c) { - switch (c) { - case DisplayDriver::DARK : - curr_color = ST77XX_BLACK; - break; - case DisplayDriver::LIGHT : - curr_color = ST77XX_WHITE; - break; - case DisplayDriver::RED : - curr_color = ST77XX_RED; - break; - case DisplayDriver::GREEN : - curr_color = ST77XX_GREEN; - break; - case DisplayDriver::BLUE : - curr_color = ST77XX_BLUE; - break; - case DisplayDriver::YELLOW : - curr_color = ST77XX_YELLOW; - break; - case DisplayDriver::ORANGE : - curr_color = ST77XX_ORANGE; - break; - default: - curr_color = ST77XX_WHITE; - break; - } +void ST7735Display::setColor(ColorVal c) { + curr_color = c; sprite->setTextColor(curr_color); } diff --git a/src/helpers/ui/ST7735Display.h b/src/helpers/ui/ST7735Display.h index 68c83db2..6e289b21 100644 --- a/src/helpers/ui/ST7735Display.h +++ b/src/helpers/ui/ST7735Display.h @@ -33,9 +33,9 @@ public: void turnOn() override; void turnOff() override; void clear() override; - void startFrame(Color bkg = DARK) override; + void startFrame(ColorVal bkg = UIColor::window_bkg) override; void setTextSize(int sz) override; - void setColor(Color c) override; + void setColor(ColorVal c) override; void setCursor(int x, int y) override; void print(const char* str) override; void fillRect(int x, int y, int w, int h) override; diff --git a/src/helpers/ui/ST7789Display.cpp b/src/helpers/ui/ST7789Display.cpp index 98d69395..fad75194 100644 --- a/src/helpers/ui/ST7789Display.cpp +++ b/src/helpers/ui/ST7789Display.cpp @@ -26,6 +26,17 @@ #define SCALE_Y DISPLAY_SCALE_Y #endif +// Color scheme +ColorVal UIColor::window_bkg = ST77XX_WHITE; +ColorVal UIColor::title_bkg = ST77XX_BLUE; +ColorVal UIColor::title_txt = ST77XX_WHITE; +ColorVal UIColor::primary_txt = ST77XX_BLACK; +ColorVal UIColor::secondary_txt = (18 << 11) | (36 << 5) | 18; // mid-gray +ColorVal UIColor::warning_txt = ST77XX_ORANGE; +ColorVal UIColor::popup_bkg = ST77XX_CYAN; +ColorVal UIColor::popup_txt = ST77XX_BLACK; +ColorVal UIColor::corp_blue = 0x001A; + bool ST7789Display::begin() { if(!_isOn) { pinMode(PIN_TFT_VDD_CTL, OUTPUT); @@ -90,9 +101,9 @@ void ST7789Display::clear() { display.clear(); } -void ST7789Display::startFrame(Color bkg) { - display.clear(); - _color = ST77XX_WHITE; +void ST7789Display::startFrame(ColorVal bkg) { + display.fillRect(0, 0, display.width(), display.height()); + _color = UIColor::primary_txt; display.setRGB(_color); display.setFont(ArialMT_Plain_16); } @@ -110,38 +121,8 @@ void ST7789Display::setTextSize(int sz) { } } -void ST7789Display::setColor(Color c) { - switch (c) { - case DisplayDriver::DARK : - _color = ST77XX_BLACK; - display.setColor(OLEDDISPLAY_COLOR::BLACK); - break; -#if 0 - case DisplayDriver::LIGHT : - _color = ST77XX_WHITE; - break; - case DisplayDriver::RED : - _color = ST77XX_RED; - break; - case DisplayDriver::GREEN : - _color = ST77XX_GREEN; - break; - case DisplayDriver::BLUE : - _color = ST77XX_BLUE; - break; - case DisplayDriver::YELLOW : - _color = ST77XX_YELLOW; - break; - case DisplayDriver::ORANGE : - _color = ST77XX_ORANGE; - break; -#endif - default: - _color = ST77XX_WHITE; - display.setColor(OLEDDISPLAY_COLOR::WHITE); - break; - } - display.setRGB(_color); +void ST7789Display::setColor(ColorVal c) { + display.setRGB(_color = c); } void ST7789Display::setCursor(int x, int y) { diff --git a/src/helpers/ui/ST7789Display.h b/src/helpers/ui/ST7789Display.h index 9822a67d..580ad463 100644 --- a/src/helpers/ui/ST7789Display.h +++ b/src/helpers/ui/ST7789Display.h @@ -27,9 +27,9 @@ public: void turnOn() override; void turnOff() override; void clear() override; - void startFrame(Color bkg = DARK) override; + void startFrame(ColorVal bkg = UIColor::window_bkg) override; void setTextSize(int sz) override; - void setColor(Color c) override; + void setColor(ColorVal c) override; void setCursor(int x, int y) override; void print(const char* str) override; void printWordWrap(const char* str, int max_width) override; diff --git a/src/helpers/ui/ST7789LCDDisplay.cpp b/src/helpers/ui/ST7789LCDDisplay.cpp index 7a02668b..a9f30dd5 100644 --- a/src/helpers/ui/ST7789LCDDisplay.cpp +++ b/src/helpers/ui/ST7789LCDDisplay.cpp @@ -23,6 +23,17 @@ bool ST7789LCDDisplay::i2c_probe(TwoWire& wire, uint8_t addr) { return true; } +// Color scheme +ColorVal UIColor::window_bkg = ST77XX_WHITE; +ColorVal UIColor::title_bkg = ST77XX_BLUE; +ColorVal UIColor::title_txt = ST77XX_WHITE; +ColorVal UIColor::primary_txt = ST77XX_BLACK; +ColorVal UIColor::secondary_txt = (18 << 11) | (36 << 5) | 18; // mid-gray +ColorVal UIColor::warning_txt = ST77XX_ORANGE; +ColorVal UIColor::popup_bkg = ST77XX_CYAN; +ColorVal UIColor::popup_txt = ST77XX_BLACK; +ColorVal UIColor::corp_blue = 0x001A; + bool ST7789LCDDisplay::begin() { if (!_isOn) { if (_peripher_power) _peripher_power->claim(); @@ -78,9 +89,9 @@ void ST7789LCDDisplay::clear() { display.fillScreen(ST77XX_BLACK); } -void ST7789LCDDisplay::startFrame(Color bkg) { - display.fillScreen(ST77XX_BLACK); - display.setTextColor(ST77XX_WHITE); +void ST7789LCDDisplay::startFrame(ColorVal bkg) { + display.fillScreen(bkg); + display.setTextColor(_color = UIColor::primary_txt); display.setTextSize(1 * DISPLAY_SCALE_X); // This one affects size of Please wait... message display.cp437(true); // Use full 256 char 'Code Page 437' font } @@ -89,34 +100,8 @@ void ST7789LCDDisplay::setTextSize(int sz) { display.setTextSize(sz * DISPLAY_SCALE_X); } -void ST7789LCDDisplay::setColor(Color c) { - switch (c) { - case DisplayDriver::DARK : - _color = ST77XX_BLACK; - break; - case DisplayDriver::LIGHT : - _color = ST77XX_WHITE; - break; - case DisplayDriver::RED : - _color = ST77XX_RED; - break; - case DisplayDriver::GREEN : - _color = ST77XX_GREEN; - break; - case DisplayDriver::BLUE : - _color = ST77XX_BLUE; - break; - case DisplayDriver::YELLOW : - _color = ST77XX_YELLOW; - break; - case DisplayDriver::ORANGE : - _color = ST77XX_ORANGE; - break; - default: - _color = ST77XX_WHITE; - break; - } - display.setTextColor(_color); +void ST7789LCDDisplay::setColor(ColorVal c) { + display.setTextColor(_color = c); } void ST7789LCDDisplay::setCursor(int x, int y) { diff --git a/src/helpers/ui/ST7789LCDDisplay.h b/src/helpers/ui/ST7789LCDDisplay.h index 03a6d3f1..b5127d35 100644 --- a/src/helpers/ui/ST7789LCDDisplay.h +++ b/src/helpers/ui/ST7789LCDDisplay.h @@ -47,9 +47,9 @@ public: void turnOn() override; void turnOff() override; void clear() override; - void startFrame(Color bkg = DARK) override; + void startFrame(ColorVal bkg = UIColor::window_bkg) override; void setTextSize(int sz) override; - void setColor(Color c) override; + void setColor(ColorVal c) override; void setCursor(int x, int y) override; void print(const char* str) override; void fillRect(int x, int y, int w, int h) override; diff --git a/src/helpers/ui/U8g2Display.cpp b/src/helpers/ui/U8g2Display.cpp new file mode 100644 index 00000000..72118a0e --- /dev/null +++ b/src/helpers/ui/U8g2Display.cpp @@ -0,0 +1,12 @@ +#include "U8g2Display.h" + +// Color scheme +ColorVal UIColor::window_bkg = 0; +ColorVal UIColor::title_bkg = 1; +ColorVal UIColor::title_txt = 0; +ColorVal UIColor::primary_txt = 1; +ColorVal UIColor::secondary_txt = 1; +ColorVal UIColor::warning_txt = 1; +ColorVal UIColor::popup_bkg = 1; +ColorVal UIColor::popup_txt = 0; +ColorVal UIColor::corp_blue = 1; diff --git a/src/helpers/ui/U8g2Display.h b/src/helpers/ui/U8g2Display.h index 73c58936..a87ee19b 100644 --- a/src/helpers/ui/U8g2Display.h +++ b/src/helpers/ui/U8g2Display.h @@ -72,10 +72,10 @@ public: _u8g2.sendBuffer(); } - void startFrame(Color bkg = DARK) override { - _u8g2.clearBuffer(); - _drawColor = 1; - _u8g2.setDrawColor(1); + void startFrame(ColorVal bkg = UIColor::window_bkg) override { + _u8g2.clearBuffer(); // TODO: apply 'bkg' color + _drawColor = UIColor::primary_txt; + _u8g2.setDrawColor(_drawColor); applyFont(1); } @@ -83,8 +83,8 @@ public: applyFont(sz); } - void setColor(Color c) override { - _drawColor = (c != DARK) ? 1 : 0; + void setColor(ColorVal c) override { + _drawColor = c; _u8g2.setDrawColor(_drawColor); } @@ -94,22 +94,18 @@ public: } void print(const char* str) override { - _u8g2.setDrawColor(_drawColor); _u8g2.drawStr(_cursorX, _cursorY, str); } void fillRect(int x, int y, int w, int h) override { - _u8g2.setDrawColor(_drawColor); _u8g2.drawBox(x, y, w, h); } void drawRect(int x, int y, int w, int h) override { - _u8g2.setDrawColor(_drawColor); _u8g2.drawFrame(x, y, w, h); } void drawXbm(int x, int y, const uint8_t* bits, int w, int h) override { - _u8g2.setDrawColor(1); _u8g2.drawXBM(x, y, w, h, bits); } diff --git a/variants/lilygo_techo_card/platformio.ini b/variants/lilygo_techo_card/platformio.ini index 07bcebfe..c7bb7378 100644 --- a/variants/lilygo_techo_card/platformio.ini +++ b/variants/lilygo_techo_card/platformio.ini @@ -23,7 +23,7 @@ build_src_filter = ${nrf52_base.build_src_filter} + + + - + + + + +<../variants/lilygo_techo_card> lib_deps = From 37ff90ab957c02857f28a4301f4918eafb4b401a Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Wed, 22 Jul 2026 18:55:59 +1000 Subject: [PATCH 037/381] * build fixes for NullDisplayDriver --- src/helpers/ui/NullDisplayDriver.cpp | 11 +++++++++ variants/heltec_rc32/platformio.ini | 3 +++ variants/heltec_t114/platformio.ini | 2 ++ variants/heltec_tower_v2/platformio.ini | 2 ++ variants/ikoka_nano_nrf/platformio.ini | 5 ++-- .../minewsemi_me25ls01/NullDisplayDriver.h | 24 ------------------- variants/minewsemi_me25ls01/platformio.ini | 5 ++++ variants/minewsemi_me25ls01/target.h | 2 +- variants/t1000-e/platformio.ini | 2 ++ variants/thinknode_m3/platformio.ini | 2 ++ variants/thinknode_m7/platformio.ini | 2 ++ variants/wio-e5-mini/NullDisplayDriver.h | 24 ------------------- variants/wio-e5-mini/platformio.ini | 1 + variants/wio-e5-mini/target.h | 2 +- 14 files changed, 34 insertions(+), 53 deletions(-) create mode 100644 src/helpers/ui/NullDisplayDriver.cpp delete mode 100644 variants/minewsemi_me25ls01/NullDisplayDriver.h delete mode 100644 variants/wio-e5-mini/NullDisplayDriver.h diff --git a/src/helpers/ui/NullDisplayDriver.cpp b/src/helpers/ui/NullDisplayDriver.cpp new file mode 100644 index 00000000..1500f5c1 --- /dev/null +++ b/src/helpers/ui/NullDisplayDriver.cpp @@ -0,0 +1,11 @@ +#include "NullDisplayDriver.h" + +ColorVal UIColor::window_bkg = 0; +ColorVal UIColor::title_bkg = 0; +ColorVal UIColor::title_txt = 0; +ColorVal UIColor::primary_txt = 0; +ColorVal UIColor::secondary_txt = 0; +ColorVal UIColor::warning_txt = 0; +ColorVal UIColor::popup_bkg = 0; +ColorVal UIColor::popup_txt = 0; +ColorVal UIColor::corp_blue = 0; diff --git a/variants/heltec_rc32/platformio.ini b/variants/heltec_rc32/platformio.ini index d535fb77..6361f61d 100644 --- a/variants/heltec_rc32/platformio.ini +++ b/variants/heltec_rc32/platformio.ini @@ -134,6 +134,7 @@ build_flags = build_src_filter = ${Heltec_RC32.build_src_filter} + + + + + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> @@ -157,6 +158,7 @@ build_flags = build_src_filter = ${Heltec_RC32.build_src_filter} + + + + + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> @@ -180,6 +182,7 @@ build_flags = build_src_filter = ${Heltec_RC32.build_src_filter} + + + + + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> diff --git a/variants/heltec_t114/platformio.ini b/variants/heltec_t114/platformio.ini index 135babb1..48dfe078 100644 --- a/variants/heltec_t114/platformio.ini +++ b/variants/heltec_t114/platformio.ini @@ -109,6 +109,7 @@ build_flags = ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${Heltec_t114.build_src_filter} + + + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> @@ -128,6 +129,7 @@ build_flags = -D MAX_GROUP_CHANNELS=40 build_src_filter = ${Heltec_t114.build_src_filter} + + + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = diff --git a/variants/heltec_tower_v2/platformio.ini b/variants/heltec_tower_v2/platformio.ini index f029b7d4..9c703ae1 100644 --- a/variants/heltec_tower_v2/platformio.ini +++ b/variants/heltec_tower_v2/platformio.ini @@ -69,6 +69,7 @@ build_flags = ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${Heltec_tower_v2.build_src_filter} + + + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> @@ -91,6 +92,7 @@ build_flags = ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${Heltec_tower_v2.build_src_filter} + + + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> diff --git a/variants/ikoka_nano_nrf/platformio.ini b/variants/ikoka_nano_nrf/platformio.ini index e72f83ce..7880ea4a 100644 --- a/variants/ikoka_nano_nrf/platformio.ini +++ b/variants/ikoka_nano_nrf/platformio.ini @@ -31,6 +31,8 @@ debug_tool = jlink upload_protocol = nrfutil lib_deps = ${nrf52_base.lib_deps} ${sensor_base.lib_deps} +build_src_filter = ${nrf52_base.build_src_filter} + + [ikoka_nano_nrf_e22_22dbm] extends = ikoka_nano_nrf @@ -42,7 +44,6 @@ build_flags = build_src_filter = ${ikoka_nano_nrf.build_src_filter} + + - + +<../variants/ikoka_nano_nrf> [ikoka_nano_nrf_e22_30dbm] @@ -56,7 +57,6 @@ build_flags = build_src_filter = ${ikoka_nano_nrf.build_src_filter} + + - + +<../variants/ikoka_nano_nrf> [ikoka_nano_nrf_e22_33dbm] @@ -70,7 +70,6 @@ build_flags = build_src_filter = ${ikoka_nano_nrf.build_src_filter} + + - + +<../variants/ikoka_nano_nrf> [ikoka_nano_nrf_companion_radio_ble] diff --git a/variants/minewsemi_me25ls01/NullDisplayDriver.h b/variants/minewsemi_me25ls01/NullDisplayDriver.h deleted file mode 100644 index 38bf93f1..00000000 --- a/variants/minewsemi_me25ls01/NullDisplayDriver.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include - -class NullDisplayDriver : public DisplayDriver { -public: - NullDisplayDriver() : DisplayDriver(128, 64) { } - bool begin() { return false; } // not present - - bool isOn() override { return false; } - void turnOn() override { } - void turnOff() override { } - void clear() override { } - void startFrame(Color bkg = DARK) override { } - void setTextSize(int sz) override { } - void setColor(Color c) override { } - void setCursor(int x, int y) override { } - void print(const char* str) override { } - void fillRect(int x, int y, int w, int h) override { } - void drawRect(int x, int y, int w, int h) override { } - void drawXbm(int x, int y, const uint8_t* bits, int w, int h) override { } - uint16_t getTextWidth(const char* str) override { return 0; } - void endFrame() { } -}; diff --git a/variants/minewsemi_me25ls01/platformio.ini b/variants/minewsemi_me25ls01/platformio.ini index 39d4252d..ac81fa16 100644 --- a/variants/minewsemi_me25ls01/platformio.ini +++ b/variants/minewsemi_me25ls01/platformio.ini @@ -55,6 +55,7 @@ build_flags = ${me25ls01.build_flags} ;-D PIN_BUZZER=25 ;-D PIN_BUZZER_EN=37 build_src_filter = ${me25ls01.build_src_filter} + + + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-orig/*.cpp> @@ -79,6 +80,7 @@ build_flags = ${me25ls01.build_flags} -D DISPLAY_CLASS=NullDisplayDriver build_src_filter = ${me25ls01.build_src_filter} +<../examples/simple_repeater> + + [env:Minewsemi_me25ls01_room_server] extends = me25ls01 @@ -101,6 +103,7 @@ build_flags = ${me25ls01.build_flags} -D DISPLAY_CLASS=NullDisplayDriver build_src_filter = ${me25ls01.build_src_filter} +<../examples/simple_room_server> + + [env:Minewsemi_me25ls01_terminal_chat] extends = me25ls01 @@ -123,6 +126,7 @@ build_flags = ${me25ls01.build_flags} -D DISPLAY_CLASS=NullDisplayDriver build_src_filter = ${me25ls01.build_src_filter} +<../examples/simple_secure_chat/main.cpp> + + [env:Minewsemi_me25ls01_companion_radio_usb] extends = me25ls01 @@ -142,6 +146,7 @@ build_flags = ${me25ls01.build_flags} -D DISPLAY_CLASS=NullDisplayDriver build_src_filter = ${me25ls01.build_src_filter} + + + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-orig/*.cpp> diff --git a/variants/minewsemi_me25ls01/target.h b/variants/minewsemi_me25ls01/target.h index f8d42863..978e616b 100644 --- a/variants/minewsemi_me25ls01/target.h +++ b/variants/minewsemi_me25ls01/target.h @@ -10,7 +10,7 @@ #include #include #ifdef DISPLAY_CLASS - #include "NullDisplayDriver.h" + #include #endif #ifdef DISPLAY_CLASS diff --git a/variants/t1000-e/platformio.ini b/variants/t1000-e/platformio.ini index 43a3d93f..6f32e54d 100644 --- a/variants/t1000-e/platformio.ini +++ b/variants/t1000-e/platformio.ini @@ -84,6 +84,7 @@ build_flags = ${t1000-e.build_flags} -D PIN_BUZZER_EN=37 ; P1/5 - required for T1000-E build_src_filter = ${t1000-e.build_src_filter} + + + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-orig/*.cpp> lib_deps = ${t1000-e.lib_deps} @@ -112,6 +113,7 @@ build_flags = ${t1000-e.build_flags} build_src_filter = ${t1000-e.build_src_filter} + + + + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-orig/*.cpp> lib_deps = ${t1000-e.lib_deps} diff --git a/variants/thinknode_m3/platformio.ini b/variants/thinknode_m3/platformio.ini index 0004f4c7..f80a6161 100644 --- a/variants/thinknode_m3/platformio.ini +++ b/variants/thinknode_m3/platformio.ini @@ -85,6 +85,7 @@ build_flags = ${ThinkNode_M3.build_flags} -D PIN_BUZZER_EN=36 build_src_filter = ${ThinkNode_M3.build_src_filter} + + + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-orig/*.cpp> lib_deps = ${ThinkNode_M3.lib_deps} @@ -111,6 +112,7 @@ build_flags = ${ThinkNode_M3.build_flags} build_src_filter = ${ThinkNode_M3.build_src_filter} + + + + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-orig/*.cpp> lib_deps = ${ThinkNode_M3.lib_deps} diff --git a/variants/thinknode_m7/platformio.ini b/variants/thinknode_m7/platformio.ini index af5d8ea0..acd98c8c 100644 --- a/variants/thinknode_m7/platformio.ini +++ b/variants/thinknode_m7/platformio.ini @@ -83,6 +83,7 @@ build_flags = build_src_filter = ${ThinkNode_M7.build_src_filter} + + + + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-orig/*.cpp> lib_deps = @@ -122,6 +123,7 @@ build_flags = build_src_filter = ${ThinkNode_M7.build_src_filter} + + + + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-orig/*.cpp> lib_deps = diff --git a/variants/wio-e5-mini/NullDisplayDriver.h b/variants/wio-e5-mini/NullDisplayDriver.h deleted file mode 100644 index 2a9670bd..00000000 --- a/variants/wio-e5-mini/NullDisplayDriver.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include - -class NullDisplayDriver : public DisplayDriver { -public: - NullDisplayDriver() : DisplayDriver(128, 64) { } - bool begin() { return false; } // not present - - bool isOn() override { return false; } - void turnOn() override { } - void turnOff() override { } - void clear() override { } - void startFrame(Color bkg = DARK) override { } - void setTextSize(int sz) override { } - void setColor(Color c) override { } - void setCursor(int x, int y) override { } - void print(const char* str) override { } - void fillRect(int x, int y, int w, int h) override { } - void drawRect(int x, int y, int w, int h) override { } - void drawXbm(int x, int y, const uint8_t* bits, int w, int h) override { } - uint16_t getTextWidth(const char* str) override { return 0; } - void endFrame() { } -}; diff --git a/variants/wio-e5-mini/platformio.ini b/variants/wio-e5-mini/platformio.ini index 82f01331..7cf26198 100644 --- a/variants/wio-e5-mini/platformio.ini +++ b/variants/wio-e5-mini/platformio.ini @@ -45,6 +45,7 @@ build_flags = ${lora_e5_mini.build_flags} -D MAX_GROUP_CHANNELS=8 -D DISPLAY_CLASS=NullDisplayDriver build_src_filter = ${lora_e5_mini.build_src_filter} + + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-orig/*.cpp> lib_deps = ${lora_e5_mini.lib_deps} diff --git a/variants/wio-e5-mini/target.h b/variants/wio-e5-mini/target.h index 4807e0f7..f4d6a088 100644 --- a/variants/wio-e5-mini/target.h +++ b/variants/wio-e5-mini/target.h @@ -8,7 +8,7 @@ #include #include #ifdef DISPLAY_CLASS - #include "NullDisplayDriver.h" + #include #endif #include From 9f6ab20bbba216f9fa0e49b341f6751df2f41ec7 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Wed, 22 Jul 2026 19:52:23 +1000 Subject: [PATCH 038/381] * build fixes for old ESP32 boards --- examples/simple_repeater/MyMesh.h | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index 0b2e7491..aa7d30b0 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -11,6 +11,7 @@ #include #elif defined(ESP32) #include + using File = fs::File; #endif #ifdef WITH_RS232_BRIDGE From 0b7f83894f982b864aa555ce92bb7f4217117c77 Mon Sep 17 00:00:00 2001 From: Nick Dunklee Date: Thu, 23 Jul 2026 14:02:34 -0600 Subject: [PATCH 039/381] Global nrf52 hardware crypto, removed from individual configs Select nodes had this flag enabled, testing by the community and hardware specs indicate this can be enabled global for all node types using this chipset. Any nodes down the line that may be quirky can be individually disabled with `-U USE_CC310_HW_CRYPTO`. --- platformio.ini | 1 + variants/heltec_t096/platformio.ini | 1 - variants/rak3401/platformio.ini | 1 - variants/rak4631/platformio.ini | 1 - variants/t1000-e/platformio.ini | 1 - 5 files changed, 1 insertion(+), 4 deletions(-) diff --git a/platformio.ini b/platformio.ini index f3ada133..c3254940 100644 --- a/platformio.ini +++ b/platformio.ini @@ -91,6 +91,7 @@ build_flags = ${arduino_base.build_flags} -D NRF52_PLATFORM -D LFS_NO_ASSERT=1 -D EXTRAFS=1 + -D USE_CC310_HW_CRYPTO=1 lib_deps = ${arduino_base.lib_deps} https://github.com/oltaco/CustomLFS#0.2.2 diff --git a/variants/heltec_t096/platformio.ini b/variants/heltec_t096/platformio.ini index 2f440e83..0a062f00 100644 --- a/variants/heltec_t096/platformio.ini +++ b/variants/heltec_t096/platformio.ini @@ -29,7 +29,6 @@ build_flags = ${nrf52_base.build_flags} -D SX126X_DIO3_TCXO_VOLTAGE=1.8 -D SX126X_CURRENT_LIMIT=140 -D SX126X_RX_BOOSTED_GAIN=1 - -D USE_CC310_HW_CRYPTO=1 -D PIN_VEXT_EN=26 ; Vext is connected to VDD which is also connected to TFT & GPS -D PIN_VEXT_EN_ACTIVE=HIGH -D PIN_GPS_RX=25 diff --git a/variants/rak3401/platformio.ini b/variants/rak3401/platformio.ini index ea53b2dc..20a8a548 100644 --- a/variants/rak3401/platformio.ini +++ b/variants/rak3401/platformio.ini @@ -13,7 +13,6 @@ build_flags = ${nrf52_base.build_flags} -D SX126X_CURRENT_LIMIT=140 -D SX126X_RX_BOOSTED_GAIN=1 -D SX126X_REGISTER_PATCH=1 ; Patch register 0x8B5 for improved RX with SKY66122 FEM - -D USE_CC310_HW_CRYPTO=1 build_src_filter = ${nrf52_base.build_src_filter} +<../variants/rak3401> + diff --git a/variants/rak4631/platformio.ini b/variants/rak4631/platformio.ini index 58055ab4..31b507b4 100644 --- a/variants/rak4631/platformio.ini +++ b/variants/rak4631/platformio.ini @@ -22,7 +22,6 @@ build_flags = ${nrf52_base.build_flags} -D LORA_TX_POWER=22 -D SX126X_CURRENT_LIMIT=140 -D SX126X_RX_BOOSTED_GAIN=1 - -D USE_CC310_HW_CRYPTO=1 -D ENV_INCLUDE_RAK12035=1 -UENV_INCLUDE_BME680 -D ENV_INCLUDE_BME680_BSEC=1 diff --git a/variants/t1000-e/platformio.ini b/variants/t1000-e/platformio.ini index d5e3bb53..43a3d93f 100644 --- a/variants/t1000-e/platformio.ini +++ b/variants/t1000-e/platformio.ini @@ -18,7 +18,6 @@ build_flags = ${nrf52_base.build_flags} -D LORA_TX_POWER=22 -D RF_SWITCH_TABLE -D RX_BOOSTED_GAIN=true - -D USE_CC310_HW_CRYPTO=1 -D P_LORA_BUSY=7 ; P0.7 -D P_LORA_SCLK=11 ; P0.11 -D P_LORA_NSS=12 ; P0.12 From 77244ce4a6c7762029a2bc7688b07472dadc417d Mon Sep 17 00:00:00 2001 From: liamcottle Date: Fri, 24 Jul 2026 15:31:01 +1200 Subject: [PATCH 040/381] increase tbeam sx1276 max group channels from 8 to 40 --- variants/lilygo_tbeam_SX1276/platformio.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/variants/lilygo_tbeam_SX1276/platformio.ini b/variants/lilygo_tbeam_SX1276/platformio.ini index cb25903c..f5f49047 100644 --- a/variants/lilygo_tbeam_SX1276/platformio.ini +++ b/variants/lilygo_tbeam_SX1276/platformio.ini @@ -45,7 +45,7 @@ build_flags = ${LilyGo_TBeam_SX1276.build_flags} -I examples/companion_radio/ui-new -D MAX_CONTACTS=160 - -D MAX_GROUP_CHANNELS=8 + -D MAX_GROUP_CHANNELS=40 -D BLE_PIN_CODE=123456 ; -D BLE_DEBUG_LOGGING=1 -D OFFLINE_QUEUE_SIZE=128 From c194f52916832646c5137f149a71cf23dc417169 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Fri, 24 Jul 2026 15:14:56 +1000 Subject: [PATCH 041/381] * monochrome displays now do _not_ invert titlebar --- src/helpers/ui/E213Display.cpp | 8 ++++---- src/helpers/ui/E290Display.cpp | 8 ++++---- src/helpers/ui/GxEPDDisplay.cpp | 8 ++++---- src/helpers/ui/SH1106Display.cpp | 8 ++++---- src/helpers/ui/SSD1306Display.cpp | 8 ++++---- src/helpers/ui/U8g2Display.cpp | 8 ++++---- 6 files changed, 24 insertions(+), 24 deletions(-) diff --git a/src/helpers/ui/E213Display.cpp b/src/helpers/ui/E213Display.cpp index ab742976..daf26989 100644 --- a/src/helpers/ui/E213Display.cpp +++ b/src/helpers/ui/E213Display.cpp @@ -4,13 +4,13 @@ // Color scheme ColorVal UIColor::window_bkg = WHITE; -ColorVal UIColor::title_bkg = BLACK; -ColorVal UIColor::title_txt = WHITE; +ColorVal UIColor::title_bkg = WHITE; +ColorVal UIColor::title_txt = BLACK; ColorVal UIColor::primary_txt = BLACK; ColorVal UIColor::secondary_txt = BLACK; ColorVal UIColor::warning_txt = BLACK; -ColorVal UIColor::popup_bkg = BLACK; -ColorVal UIColor::popup_txt = WHITE; +ColorVal UIColor::popup_bkg = WHITE; +ColorVal UIColor::popup_txt = BLACK; ColorVal UIColor::corp_blue = BLACK; BaseDisplay* E213Display::detectEInk() diff --git a/src/helpers/ui/E290Display.cpp b/src/helpers/ui/E290Display.cpp index ddb449f4..34bbcdbc 100644 --- a/src/helpers/ui/E290Display.cpp +++ b/src/helpers/ui/E290Display.cpp @@ -4,13 +4,13 @@ // Color scheme ColorVal UIColor::window_bkg = WHITE; -ColorVal UIColor::title_bkg = BLACK; -ColorVal UIColor::title_txt = WHITE; +ColorVal UIColor::title_bkg = WHITE; +ColorVal UIColor::title_txt = BLACK; ColorVal UIColor::primary_txt = BLACK; ColorVal UIColor::secondary_txt = BLACK; ColorVal UIColor::warning_txt = BLACK; -ColorVal UIColor::popup_bkg = BLACK; -ColorVal UIColor::popup_txt = WHITE; +ColorVal UIColor::popup_bkg = WHITE; +ColorVal UIColor::popup_txt = BLACK; ColorVal UIColor::corp_blue = BLACK; bool E290Display::begin() { diff --git a/src/helpers/ui/GxEPDDisplay.cpp b/src/helpers/ui/GxEPDDisplay.cpp index 0a5f6a55..13dafa34 100644 --- a/src/helpers/ui/GxEPDDisplay.cpp +++ b/src/helpers/ui/GxEPDDisplay.cpp @@ -16,13 +16,13 @@ // Color scheme ColorVal UIColor::window_bkg = GxEPD_WHITE; -ColorVal UIColor::title_bkg = GxEPD_BLACK; -ColorVal UIColor::title_txt = GxEPD_WHITE; +ColorVal UIColor::title_bkg = GxEPD_WHITE; +ColorVal UIColor::title_txt = GxEPD_BLACK; ColorVal UIColor::primary_txt = GxEPD_BLACK; ColorVal UIColor::secondary_txt = GxEPD_BLACK; ColorVal UIColor::warning_txt = GxEPD_BLACK; -ColorVal UIColor::popup_bkg = GxEPD_BLACK; -ColorVal UIColor::popup_txt = GxEPD_WHITE; +ColorVal UIColor::popup_bkg = GxEPD_WHITE; +ColorVal UIColor::popup_txt = GxEPD_BLACK; ColorVal UIColor::corp_blue = GxEPD_BLACK; diff --git a/src/helpers/ui/SH1106Display.cpp b/src/helpers/ui/SH1106Display.cpp index aeb4f300..c3840c02 100644 --- a/src/helpers/ui/SH1106Display.cpp +++ b/src/helpers/ui/SH1106Display.cpp @@ -11,13 +11,13 @@ bool SH1106Display::i2c_probe(TwoWire &wire, uint8_t addr) // Color scheme ColorVal UIColor::window_bkg = SH110X_BLACK; -ColorVal UIColor::title_bkg = SH110X_WHITE; -ColorVal UIColor::title_txt = SH110X_BLACK; +ColorVal UIColor::title_bkg = SH110X_BLACK; +ColorVal UIColor::title_txt = SH110X_WHITE; ColorVal UIColor::primary_txt = SH110X_WHITE; ColorVal UIColor::secondary_txt = SH110X_WHITE; ColorVal UIColor::warning_txt = SH110X_WHITE; -ColorVal UIColor::popup_bkg = SH110X_WHITE; -ColorVal UIColor::popup_txt = SH110X_BLACK; +ColorVal UIColor::popup_bkg = SH110X_BLACK; +ColorVal UIColor::popup_txt = SH110X_WHITE; ColorVal UIColor::corp_blue = SH110X_WHITE; bool SH1106Display::begin() diff --git a/src/helpers/ui/SSD1306Display.cpp b/src/helpers/ui/SSD1306Display.cpp index 9b858071..ab2d77fb 100644 --- a/src/helpers/ui/SSD1306Display.cpp +++ b/src/helpers/ui/SSD1306Display.cpp @@ -8,13 +8,13 @@ bool SSD1306Display::i2c_probe(TwoWire& wire, uint8_t addr) { // Color scheme ColorVal UIColor::window_bkg = SSD1306_BLACK; -ColorVal UIColor::title_bkg = SSD1306_WHITE; -ColorVal UIColor::title_txt = SSD1306_BLACK; +ColorVal UIColor::title_bkg = SSD1306_BLACK; +ColorVal UIColor::title_txt = SSD1306_WHITE; ColorVal UIColor::primary_txt = SSD1306_WHITE; ColorVal UIColor::secondary_txt = SSD1306_WHITE; ColorVal UIColor::warning_txt = SSD1306_WHITE; -ColorVal UIColor::popup_bkg = SSD1306_WHITE; -ColorVal UIColor::popup_txt = SSD1306_BLACK; +ColorVal UIColor::popup_bkg = SSD1306_BLACK; +ColorVal UIColor::popup_txt = SSD1306_WHITE; ColorVal UIColor::corp_blue = SSD1306_WHITE; bool SSD1306Display::begin() { diff --git a/src/helpers/ui/U8g2Display.cpp b/src/helpers/ui/U8g2Display.cpp index 72118a0e..e8d7fe2f 100644 --- a/src/helpers/ui/U8g2Display.cpp +++ b/src/helpers/ui/U8g2Display.cpp @@ -2,11 +2,11 @@ // Color scheme ColorVal UIColor::window_bkg = 0; -ColorVal UIColor::title_bkg = 1; -ColorVal UIColor::title_txt = 0; +ColorVal UIColor::title_bkg = 0; +ColorVal UIColor::title_txt = 1; ColorVal UIColor::primary_txt = 1; ColorVal UIColor::secondary_txt = 1; ColorVal UIColor::warning_txt = 1; -ColorVal UIColor::popup_bkg = 1; -ColorVal UIColor::popup_txt = 0; +ColorVal UIColor::popup_bkg = 0; +ColorVal UIColor::popup_txt = 1; ColorVal UIColor::corp_blue = 1; From b6ff4ad43f0a489d5024ea038ed7f1058e7ebfb5 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Fri, 24 Jul 2026 15:31:22 +1000 Subject: [PATCH 042/381] * fixed for mono ST7789 display driver --- src/helpers/ui/ST7789Display.cpp | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/src/helpers/ui/ST7789Display.cpp b/src/helpers/ui/ST7789Display.cpp index fad75194..7aff92a1 100644 --- a/src/helpers/ui/ST7789Display.cpp +++ b/src/helpers/ui/ST7789Display.cpp @@ -27,15 +27,15 @@ #endif // Color scheme -ColorVal UIColor::window_bkg = ST77XX_WHITE; -ColorVal UIColor::title_bkg = ST77XX_BLUE; -ColorVal UIColor::title_txt = ST77XX_WHITE; -ColorVal UIColor::primary_txt = ST77XX_BLACK; -ColorVal UIColor::secondary_txt = (18 << 11) | (36 << 5) | 18; // mid-gray -ColorVal UIColor::warning_txt = ST77XX_ORANGE; -ColorVal UIColor::popup_bkg = ST77XX_CYAN; -ColorVal UIColor::popup_txt = ST77XX_BLACK; -ColorVal UIColor::corp_blue = 0x001A; +ColorVal UIColor::window_bkg = OLEDDISPLAY_COLOR::WHITE; +ColorVal UIColor::title_bkg = OLEDDISPLAY_COLOR::WHITE; +ColorVal UIColor::title_txt = OLEDDISPLAY_COLOR::BLACK; +ColorVal UIColor::primary_txt = OLEDDISPLAY_COLOR::BLACK; +ColorVal UIColor::secondary_txt = OLEDDISPLAY_COLOR::BLACK; +ColorVal UIColor::warning_txt = OLEDDISPLAY_COLOR::BLACK; +ColorVal UIColor::popup_bkg = OLEDDISPLAY_COLOR::WHITE; +ColorVal UIColor::popup_txt = OLEDDISPLAY_COLOR::BLACK; +ColorVal UIColor::corp_blue = OLEDDISPLAY_COLOR::BLACK; bool ST7789Display::begin() { if(!_isOn) { @@ -102,9 +102,8 @@ void ST7789Display::clear() { } void ST7789Display::startFrame(ColorVal bkg) { - display.fillRect(0, 0, display.width(), display.height()); - _color = UIColor::primary_txt; - display.setRGB(_color); + display.clear(); // TODO: use bkg + setColor(UIColor::primary_txt); display.setFont(ArialMT_Plain_16); } @@ -122,7 +121,9 @@ void ST7789Display::setTextSize(int sz) { } void ST7789Display::setColor(ColorVal c) { - display.setRGB(_color = c); + _color = c; + display.setColor((OLEDDISPLAY_COLOR)_color); + display.setRGB(_color == OLEDDISPLAY_COLOR::WHITE ? ST77XX_WHITE : ST77XX_BLACK); } void ST7789Display::setCursor(int x, int y) { From 1d4e21c89f9ca7c77e3d5290371b44450961d8d6 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Fri, 24 Jul 2026 18:35:56 +1000 Subject: [PATCH 043/381] * T114 display fix --- examples/companion_radio/ui-new/UITask.cpp | 6 +++++- src/helpers/ui/ST7789Display.cpp | 18 +++++++++--------- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index 09903db0..50dc91d2 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -204,7 +204,11 @@ public: renderBatteryIndicator(display, _task->getBattMilliVolts()); // curr page indicator - display.setColor(UIColor::title_bkg); + if (UIColor::title_bkg == UIColor::window_bkg) { + display.setColor(UIColor::title_txt); + } else { + display.setColor(UIColor::title_bkg); + } int y = 14; int x = display.width() / 2 - 5 * (HomePage::Count-1); for (uint8_t i = 0; i < HomePage::Count; i++, x += 10) { diff --git a/src/helpers/ui/ST7789Display.cpp b/src/helpers/ui/ST7789Display.cpp index 7aff92a1..7d039a13 100644 --- a/src/helpers/ui/ST7789Display.cpp +++ b/src/helpers/ui/ST7789Display.cpp @@ -27,15 +27,15 @@ #endif // Color scheme -ColorVal UIColor::window_bkg = OLEDDISPLAY_COLOR::WHITE; -ColorVal UIColor::title_bkg = OLEDDISPLAY_COLOR::WHITE; -ColorVal UIColor::title_txt = OLEDDISPLAY_COLOR::BLACK; -ColorVal UIColor::primary_txt = OLEDDISPLAY_COLOR::BLACK; -ColorVal UIColor::secondary_txt = OLEDDISPLAY_COLOR::BLACK; -ColorVal UIColor::warning_txt = OLEDDISPLAY_COLOR::BLACK; -ColorVal UIColor::popup_bkg = OLEDDISPLAY_COLOR::WHITE; -ColorVal UIColor::popup_txt = OLEDDISPLAY_COLOR::BLACK; -ColorVal UIColor::corp_blue = OLEDDISPLAY_COLOR::BLACK; +ColorVal UIColor::window_bkg = OLEDDISPLAY_COLOR::BLACK; +ColorVal UIColor::title_bkg = OLEDDISPLAY_COLOR::BLACK; +ColorVal UIColor::title_txt = OLEDDISPLAY_COLOR::WHITE; +ColorVal UIColor::primary_txt = OLEDDISPLAY_COLOR::WHITE; +ColorVal UIColor::secondary_txt = OLEDDISPLAY_COLOR::WHITE; +ColorVal UIColor::warning_txt = OLEDDISPLAY_COLOR::WHITE; +ColorVal UIColor::popup_bkg = OLEDDISPLAY_COLOR::BLACK; +ColorVal UIColor::popup_txt = OLEDDISPLAY_COLOR::WHITE; +ColorVal UIColor::corp_blue = OLEDDISPLAY_COLOR::WHITE; bool ST7789Display::begin() { if(!_isOn) { From 11a0236c2cb020cda7ed14b746cced0d82ff68f9 Mon Sep 17 00:00:00 2001 From: taco Date: Mon, 20 Jul 2026 20:50:38 +1000 Subject: [PATCH 044/381] SX1262: add PREAMBLE_DETECTED to reported irq flags --- src/helpers/radiolib/CustomSX1262.h | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/helpers/radiolib/CustomSX1262.h b/src/helpers/radiolib/CustomSX1262.h index 15efed5c..6a7c2144 100644 --- a/src/helpers/radiolib/CustomSX1262.h +++ b/src/helpers/radiolib/CustomSX1262.h @@ -100,6 +100,11 @@ class CustomSX1262 : public SX1262 { return true; // success } + int16_t startReceive() override { + // include the PREAMBLE_DETECTED irq bit in reported flags + return SX1262::startReceive(RADIOLIB_SX126X_RX_TIMEOUT_INF, RADIOLIB_IRQ_RX_DEFAULT_FLAGS | (1UL << RADIOLIB_IRQ_PREAMBLE_DETECTED), RADIOLIB_IRQ_RX_DEFAULT_MASK, 0); + } + bool isReceiving() { uint32_t irq = getIrqFlags(); bool preamble = irq & RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED; // bit 2 From 04b643b21a2ddb959a593c1b572ea760a3bbf5d4 Mon Sep 17 00:00:00 2001 From: taco Date: Sat, 25 Jul 2026 00:46:36 +1000 Subject: [PATCH 045/381] LR1110: add PREAMBLE_DETECTED to reported irq flags --- src/helpers/radiolib/CustomLR1110.h | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/helpers/radiolib/CustomLR1110.h b/src/helpers/radiolib/CustomLR1110.h index 0470e48f..20aea9ff 100644 --- a/src/helpers/radiolib/CustomLR1110.h +++ b/src/helpers/radiolib/CustomLR1110.h @@ -35,6 +35,11 @@ class CustomLR1110 : public LR1110 { bool getRxBoostedGainMode() const { return _rx_boosted; } + int16_t startReceive() override { + // include the PREAMBLE_DETECTED irq bit in reported flags + return LR1110::startReceive(RADIOLIB_LR11X0_IRQ_PREAMBLE_DETECTED, RADIOLIB_IRQ_RX_DEFAULT_FLAGS | (1UL << RADIOLIB_IRQ_PREAMBLE_DETECTED), RADIOLIB_IRQ_RX_DEFAULT_MASK, 0); + } + bool isReceiving() { uint32_t irq = getIrqStatus(); bool preamble = irq & RADIOLIB_LR11X0_IRQ_PREAMBLE_DETECTED; // bit 4 From 15edc9e9e9ec2744dc0db651f3e4a6fce83303b6 Mon Sep 17 00:00:00 2001 From: taco Date: Sat, 25 Jul 2026 00:18:59 +1000 Subject: [PATCH 046/381] LLCC68: add PREAMBLE_DETECTED to reported irq flags --- src/helpers/radiolib/CustomLLCC68.h | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/helpers/radiolib/CustomLLCC68.h b/src/helpers/radiolib/CustomLLCC68.h index 686b09ec..bde44b6c 100644 --- a/src/helpers/radiolib/CustomLLCC68.h +++ b/src/helpers/radiolib/CustomLLCC68.h @@ -2,9 +2,6 @@ #include -#define SX126X_IRQ_HEADER_VALID 0b0000010000 // 4 4 valid LoRa header received -#define SX126X_IRQ_PREAMBLE_DETECTED 0x04 - class CustomLLCC68 : public LLCC68 { public: CustomLLCC68(Module *mod) : LLCC68(mod) { } @@ -78,9 +75,14 @@ class CustomLLCC68 : public LLCC68 { return true; // success } + int16_t startReceive() override { + // include the PREAMBLE_DETECTED irq bit in reported flags + return LLCC68::startReceive(RADIOLIB_SX126X_RX_TIMEOUT_INF, RADIOLIB_IRQ_RX_DEFAULT_FLAGS | (1UL << RADIOLIB_IRQ_PREAMBLE_DETECTED), RADIOLIB_IRQ_RX_DEFAULT_MASK, 0); + } + bool isReceiving() { uint16_t irq = getIrqFlags(); - bool detected = (irq & SX126X_IRQ_HEADER_VALID) || (irq & SX126X_IRQ_PREAMBLE_DETECTED); + bool detected = (irq & RADIOLIB_SX126X_IRQ_HEADER_VALID) || (irq & RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED); return detected; } From a04833f0294c548916ba8de0ec0ab5467a3fea9b Mon Sep 17 00:00:00 2001 From: taco Date: Sat, 25 Jul 2026 00:20:02 +1000 Subject: [PATCH 047/381] STM32WLx: add PREAMBLE_DETECTED to reported irq flags --- src/helpers/radiolib/CustomSTM32WLx.h | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/helpers/radiolib/CustomSTM32WLx.h b/src/helpers/radiolib/CustomSTM32WLx.h index cbdd5c8c..01190d06 100644 --- a/src/helpers/radiolib/CustomSTM32WLx.h +++ b/src/helpers/radiolib/CustomSTM32WLx.h @@ -2,16 +2,18 @@ #include -#define SX126X_IRQ_HEADER_VALID 0b0000010000 // 4 4 valid LoRa header received -#define SX126X_IRQ_PREAMBLE_DETECTED 0x04 - class CustomSTM32WLx : public STM32WLx { public: CustomSTM32WLx(STM32WLx_Module *mod) : STM32WLx(mod) { } + int16_t startReceive() override { + // include the PREAMBLE_DETECTED irq bit in reported flags + return STM32WLx::startReceive(RADIOLIB_SX126X_RX_TIMEOUT_INF, RADIOLIB_IRQ_RX_DEFAULT_FLAGS | (1UL << RADIOLIB_IRQ_PREAMBLE_DETECTED), RADIOLIB_IRQ_RX_DEFAULT_MASK, 0); + } + bool isReceiving() { uint16_t irq = getIrqFlags(); - bool detected = (irq & SX126X_IRQ_HEADER_VALID) || (irq & SX126X_IRQ_PREAMBLE_DETECTED); + bool detected = (irq & RADIOLIB_SX126X_IRQ_HEADER_VALID) || (irq & RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED); return detected; } }; \ No newline at end of file From fd3639dd4ee29fa894e7eaafe75bca57741dbbf0 Mon Sep 17 00:00:00 2001 From: taco Date: Sat, 25 Jul 2026 00:20:57 +1000 Subject: [PATCH 048/381] SX1268: add PREAMBLE_DETECTED to reported irq flags --- src/helpers/radiolib/CustomSX1268.h | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/helpers/radiolib/CustomSX1268.h b/src/helpers/radiolib/CustomSX1268.h index 0c6f828b..1e71a3fa 100644 --- a/src/helpers/radiolib/CustomSX1268.h +++ b/src/helpers/radiolib/CustomSX1268.h @@ -2,9 +2,6 @@ #include -#define SX126X_IRQ_HEADER_VALID 0b0000010000 // 4 4 valid LoRa header received -#define SX126X_IRQ_PREAMBLE_DETECTED 0x04 - class CustomSX1268 : public SX1268 { public: CustomSX1268(Module *mod) : SX1268(mod) { } @@ -78,9 +75,14 @@ class CustomSX1268 : public SX1268 { return true; // success } + int16_t startReceive() override { + // include the PREAMBLE_DETECTED irq bit in reported flags + return SX1268::startReceive(RADIOLIB_SX126X_RX_TIMEOUT_INF, RADIOLIB_IRQ_RX_DEFAULT_FLAGS | (1UL << RADIOLIB_IRQ_PREAMBLE_DETECTED), RADIOLIB_IRQ_RX_DEFAULT_MASK, 0); + } + bool isReceiving() { uint16_t irq = getIrqFlags(); - bool detected = (irq & SX126X_IRQ_HEADER_VALID) || (irq & SX126X_IRQ_PREAMBLE_DETECTED); + bool detected = (irq & RADIOLIB_SX126X_IRQ_HEADER_VALID) || (irq & RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED); return detected; } From 9d2343e06fa51a7edee7f614dfcf479922ae09f0 Mon Sep 17 00:00:00 2001 From: Talia Date: Sat, 25 Jul 2026 20:55:58 -0700 Subject: [PATCH 049/381] docs: increase header levels on payloads page to fix table of contents mkdocs will only consider the first H1 (if any) and subheaders under it for the table of contents this increases the header levels of everything below "important concepts" by 1 so that the table of contents correctly resolves them --- docs/payloads.md | 52 ++++++++++++++++++++++++------------------------ 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/docs/payloads.md b/docs/payloads.md index 21cb9469..b4a98b38 100644 --- a/docs/payloads.md +++ b/docs/payloads.md @@ -23,7 +23,7 @@ NOTE: all 16 and 32-bit integer fields are Little Endian. * Node hash: the first byte of the node's public key -# Node advertisement +## Node advertisement This kind of payload notifies receivers that a node exists, and gives information about the node | Field | Size (bytes) | Description | @@ -57,7 +57,7 @@ Appdata Flags | `0x40` | has feature 2 | Reserved for future use. | | `0x80` | has name | appdata contains a node name | -# Acknowledgement +## Acknowledgement An acknowledgement that a message was received. Note that for returned path messages, an acknowledgement can be sent in the "extra" payload (see [Returned Path](#returned-path)) instead of as a separate acknowledgement packet. CLI commands do not cause acknowledgement responses, neither discrete nor extra. @@ -66,7 +66,7 @@ An acknowledgement that a message was received. Note that for returned path mess | checksum | 4 | CRC checksum of message timestamp, text, and sender pubkey | -# Returned path, request, response, and plain text message +## Returned path, request, response, and plain text message Returned path, request, response, and plain text messages are all formatted in the same way. See the subsection for more details about the ciphertext's associated plaintext representation. @@ -77,7 +77,7 @@ Returned path, request, response, and plain text messages are all formatted in t | cipher MAC | 2 | MAC for encrypted data in next field | | ciphertext | rest of payload | encrypted message, see subsections below for details | -## Returned path +### Returned path Returned path messages provide a description of the route a packet took from the original author. Receivers will send returned path messages to the author of the original message. @@ -88,7 +88,7 @@ Returned path messages provide a description of the route a packet took from the | extra type | 1 | extra, bundled payload type, eg., acknowledgement or response. Same values as in [Packet Format](./packet_format.md) | | extra | rest of data | extra, bundled payload content, follows same format as main content defined by this document | -## Request +### Request | Field | Size (bytes) | Description | |--------------|-----------------|------------------------------------------| @@ -102,7 +102,7 @@ For the common chat/server helpers in `BaseChatMesh`, the current request type v | `0x01` | get stats | get stats of repeater or room server | | `0x02` | keepalive | keep-alive request used for maintained connections | -### Get stats +#### Get stats Gets information about the node, possibly including the following: @@ -125,32 +125,32 @@ Gets information about the node, possibly including the following: * Number posted (?) * Number of post pushes (?) -### Get telemetry data +#### Get telemetry data Not defined in `BaseChatMesh`. Sensor- and application-specific request payloads may be implemented by higher-level firmware. -### Get Telemetry +#### Get Telemetry Not defined in `BaseChatMesh`. -### Get Min/Max/Ave (Sensor nodes) +#### Get Min/Max/Ave (Sensor nodes) Not defined in `BaseChatMesh`. -### Get Access List +#### Get Access List Not defined in `BaseChatMesh`. -### Get Neighbors +#### Get Neighbors Not defined in `BaseChatMesh`. -### Get Owner Info +#### Get Owner Info Not defined in `BaseChatMesh`. -## Response +### Response | Field | Size (bytes) | Description | |---------|-----------------|-----------------------------------| @@ -158,7 +158,7 @@ Not defined in `BaseChatMesh`. Response contents are opaque application data. There is no single generic response envelope beyond the encrypted payload wrapper shown above. -## Plain text message +### Plain text message | Field | Size (bytes) | Description | |--------------------|-----------------|-----------------------------------------------------------------------------------| @@ -174,7 +174,7 @@ txt_type | `0x01` | CLI command | the command text of the message | | `0x02` | signed plain text message | first four bytes is sender pubkey prefix, followed by plain text message | -# Anonymous request +## Anonymous request | Field | Size (bytes) | Description | |------------------|-----------------|-------------------------------------------| @@ -183,7 +183,7 @@ txt_type | cipher MAC | 2 | MAC for encrypted data in next field | | ciphertext | rest of payload | encrypted message, see below for details | -## Room server login +### Room server login | Field | Size (bytes) | Description | |----------------|-----------------|-------------------------------------------------------------------------------| @@ -191,14 +191,14 @@ txt_type | sync timestamp | 4 | sender's "sync messages SINCE x" timestamp | | password | rest of message | password for room | -## Repeater/Sensor login +### Repeater/Sensor login | Field | Size (bytes) | Description | |----------------|-----------------|-------------------------------------------------------------------------------| | timestamp | 4 | sender time (unix timestamp) | | password | rest of message | password for repeater/sensor | -## Repeater - Regions request +### Repeater - Regions request | Field | Size (bytes) | Description | |----------------|--------------|------------------------------| @@ -207,7 +207,7 @@ txt_type | reply path len | 1 | path len for reply | | reply path | (variable) | reply path | -## Repeater - Owner info request +### Repeater - Owner info request | Field | Size (bytes) | Description | |----------------|--------------|------------------------------| @@ -216,7 +216,7 @@ txt_type | reply path len | 1 | path len for reply | | reply path | (variable) | reply path | -## Repeater - Clock and status request +### Repeater - Clock and status request | Field | Size (bytes) | Description | |----------------|--------------|------------------------------| @@ -226,7 +226,7 @@ txt_type | reply path | (variable) | reply path | -# Group text message +## Group text message | Field | Size (bytes) | Description | |--------------|-----------------|----------------------------------------------| @@ -236,7 +236,7 @@ txt_type The plaintext contained in the ciphertext matches the format described in [plain text message](#plain-text-message). Specifically, it consists of a four byte timestamp, a flags byte, and the message. The flags byte will generally be `0x00` because it is a "plain text message". The message will be of the form `: ` (eg., `user123: I'm on my way`). -# Group datagram +## Group datagram | Field | Size (bytes) | Description | |--------------|-----------------|----------------------------------------------| @@ -253,14 +253,14 @@ The data contained in the ciphertext uses the format below: | data | rest of payload | (depends on data type) | -# Control data +## Control data | Field | Size (bytes) | Description | |--------------|-----------------|--------------------------------------------| | flags | 1 | upper 4 bits is sub_type | | data | rest of payload | typically unencrypted data | -## DISCOVER_REQ (sub_type) +### DISCOVER_REQ (sub_type) | Field | Size (bytes) | Description | |--------------|-----------------|----------------------------------------------| @@ -269,7 +269,7 @@ The data contained in the ciphertext uses the format below: | tag | 4 | randomly generate by sender | | since | 4 | (optional) epoch timestamp (0 by default) | -## DISCOVER_RESP (sub_type) +### DISCOVER_RESP (sub_type) | Field | Size (bytes) | Description | |--------------|-----------------|--------------------------------------------| @@ -279,6 +279,6 @@ The data contained in the ciphertext uses the format below: | pubkey | 8 or 32 | node's ID (or prefix) | -# Custom packet +## Custom packet Custom packets have no defined format. From 1c7a4b307fd219cedcaa2b01b7d46b63a8bde84b Mon Sep 17 00:00:00 2001 From: liamcottle Date: Fri, 17 Jul 2026 23:59:27 +1200 Subject: [PATCH 050/381] initial ch390 ethernet support for thinknode m7 companion --- examples/companion_radio/main.cpp | 5 + src/helpers/ethernet/Ethernet.h | 9 + .../ethernet/ch390/CH390EthernetInterface.cpp | 207 ++++++++++++++++++ .../ethernet/ch390/CH390EthernetInterface.h | 80 +++++++ variants/thinknode_m7/platformio.ini | 36 +++ 5 files changed, 337 insertions(+) create mode 100644 src/helpers/ethernet/Ethernet.h create mode 100644 src/helpers/ethernet/ch390/CH390EthernetInterface.cpp create mode 100644 src/helpers/ethernet/ch390/CH390EthernetInterface.h diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index d39aeef9..2fc00dbd 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -48,6 +48,9 @@ static uint32_t _atoi(const char* sp) { #include ArduinoSerialInterface serial_interface; HardwareSerial companion_serial(1); + #elif defined(ETHERNET_ENABLED) + #include + ETHERNET_CLASS serial_interface; #else #include ArduinoSerialInterface serial_interface; @@ -240,6 +243,8 @@ void setup() { companion_serial.setPins(SERIAL_RX, SERIAL_TX); companion_serial.begin(115200); serial_interface.begin(companion_serial); +#elif defined(ETHERNET_ENABLED) + serial_interface.begin(); #else serial_interface.begin(Serial); #endif diff --git a/src/helpers/ethernet/Ethernet.h b/src/helpers/ethernet/Ethernet.h new file mode 100644 index 00000000..4d889df4 --- /dev/null +++ b/src/helpers/ethernet/Ethernet.h @@ -0,0 +1,9 @@ +#pragma once + +#if defined(ETHERNET_ENABLED) + #if defined(ETHERNET_USE_CH390) + #include "helpers/ethernet/ch390/CH390EthernetInterface.h" + #else + #error "ETHERNET_ENABLED is defined, but no specific driver flag (e.g. ETHERNET_USE_CH390) was provided!" + #endif +#endif diff --git a/src/helpers/ethernet/ch390/CH390EthernetInterface.cpp b/src/helpers/ethernet/ch390/CH390EthernetInterface.cpp new file mode 100644 index 00000000..f7ee5503 --- /dev/null +++ b/src/helpers/ethernet/ch390/CH390EthernetInterface.cpp @@ -0,0 +1,207 @@ +#include "CH390EthernetInterface.h" + +#define RECV_STATE_IDLE 0 +#define RECV_STATE_HDR_FOUND 1 +#define RECV_STATE_LEN1_FOUND 2 +#define RECV_STATE_LEN2_FOUND 3 + +bool CH390EthernetInterface::begin() { + ETHERNET_DEBUG_PRINTLN("Ethernet initializing"); + + // Init CH390 + ch390_config_t config = CH390_DEFAULT_CONFIG(); + config.spi_miso_gpio = ETH_MISO_PIN; + config.spi_mosi_gpio = ETH_MOSI_PIN; + config.spi_sck_gpio = ETH_SCLK_PIN; + config.spi_cs_gpio = ETH_CS_PIN; + config.int_gpio = ETH_INT_PIN; + if (!CH390.begin(config)) { + ETHERNET_DEBUG_PRINTLN("Failed to initialize CH390 hardware."); + return false; + } + + // Setup Static IP if build flags are present + #if defined(ETHERNET_STATIC_IP) && defined(ETHERNET_STATIC_GATEWAY) && defined(ETHERNET_STATIC_SUBNET) + IPAddress ip(ETHERNET_STATIC_IP); + IPAddress gw(ETHERNET_STATIC_GATEWAY); + IPAddress sn(ETHERNET_STATIC_SUBNET); + CH390.config(ip, gw, sn); + #endif + + // Start Server + server.begin(); + ETHERNET_DEBUG_PRINTLN("listening on TCP port: %d", ETHERNET_TCP_PORT); + + return true; +} + +void CH390EthernetInterface::enable() { + if (_isEnabled) return; + _isEnabled = true; + clearBuffers(); +} + +void CH390EthernetInterface::disable() { + _isEnabled = false; +} + +size_t CH390EthernetInterface::writeFrame(const uint8_t src[], size_t len) { + if (len > MAX_FRAME_SIZE) { + ETHERNET_DEBUG_PRINTLN("writeFrame(), frame too big, len=%d\n", len); + return 0; + } + + if (deviceConnected && len > 0) { + if (send_queue_len >= FRAME_QUEUE_SIZE) { + ETHERNET_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; +} + +bool CH390EthernetInterface::isWriteBusy() const { + return false; +} + +size_t CH390EthernetInterface::checkRecvFrame(uint8_t dest[]) { + if (server.hasClient()) { + auto newClient = server.available(); + if (newClient) { + IPAddress new_ip = newClient.remoteIP(); + uint16_t new_port = newClient.remotePort(); + ETHERNET_DEBUG_PRINTLN( + "New client accepted %u.%u.%u.%u:%u", + new_ip[0], new_ip[1], new_ip[2], new_ip[3], new_port); + + deviceConnected = false; + if (client) { + ETHERNET_DEBUG_PRINTLN("Closing previous client"); + client.stop(); + } + _state = RECV_STATE_IDLE; + _frame_len = 0; + _rx_len = 0; + client = newClient; + ETHERNET_DEBUG_PRINTLN("Switched to new client"); + } + } + + if (client.connected()) { + if (!deviceConnected) { + ETHERNET_DEBUG_PRINTLN( + "Got connection %u.%u.%u.%u:%u", + client.remoteIP()[0], + client.remoteIP()[1], + client.remoteIP()[2], + client.remoteIP()[3], + client.remotePort()); + deviceConnected = true; + } + } else { + if (deviceConnected) { + deviceConnected = false; + ETHERNET_DEBUG_PRINTLN("Disconnected"); + } + } + + if (deviceConnected) { + if (send_queue_len > 0) { // first, check send queue + + _last_write = millis(); + int len = send_queue[0].len; + +#if ETHERNET_RAW_LINE + ETHERNET_DEBUG_PRINTLN("TX line len=%d", len); + client.write(send_queue[0].buf, len); + client.write("\r\n", 2); +#else + uint8_t pkt[3+len]; // use same header as serial interface so client can delimit frames + pkt[0] = '>'; + pkt[1] = (len & 0xFF); // LSB + pkt[2] = (len >> 8); // MSB + memcpy(&pkt[3], send_queue[0].buf, send_queue[0].len); + ETHERNET_DEBUG_PRINTLN("Sending frame len=%d", len); + #if ETHERNET_DEBUG_LOGGING && ARDUINO + ETHERNET_DEBUG_PRINTLN("TX frame len=%d", len); + #endif + client.write(pkt, 3 + len); +#endif + 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 { + while (client.available()) { + int c = client.read(); + if (c < 0) break; + +#if ETHERNET_RAW_LINE + if (c == '\r' || c == '\n') { + if (_rx_len == 0) { + continue; + } + uint16_t out_len = _rx_len; + if (out_len > MAX_FRAME_SIZE) out_len = MAX_FRAME_SIZE; + memcpy(dest, _rx_buf, out_len); + _rx_len = 0; + return out_len; + } + if (_rx_len < MAX_FRAME_SIZE) { + _rx_buf[_rx_len] = (uint8_t)c; + _rx_len++; + } +#else + switch (_state) { + case RECV_STATE_IDLE: + if (c == '<') { + _state = RECV_STATE_HDR_FOUND; + } + break; + case RECV_STATE_HDR_FOUND: + _frame_len = (uint8_t)c; + _state = RECV_STATE_LEN1_FOUND; + break; + case RECV_STATE_LEN1_FOUND: + _frame_len |= ((uint16_t)c) << 8; + _rx_len = 0; + _state = _frame_len > 0 ? RECV_STATE_LEN2_FOUND : RECV_STATE_IDLE; + break; + default: + if (_rx_len < MAX_FRAME_SIZE) { + _rx_buf[_rx_len] = (uint8_t)c; + } + _rx_len++; + if (_rx_len >= _frame_len) { + if (_frame_len > MAX_FRAME_SIZE) { + _frame_len = MAX_FRAME_SIZE; + } + #if ETHERNET_DEBUG_LOGGING && ARDUINO + ETHERNET_DEBUG_PRINTLN("RX frame len=%d", _frame_len); + #endif + memcpy(dest, _rx_buf, _frame_len); + _state = RECV_STATE_IDLE; + return _frame_len; + } + } +#endif + } + } + } + + return 0; +} + +bool CH390EthernetInterface::isConnected() const { + return deviceConnected; +} + +void CH390EthernetInterface::loop() { + +} diff --git a/src/helpers/ethernet/ch390/CH390EthernetInterface.h b/src/helpers/ethernet/ch390/CH390EthernetInterface.h new file mode 100644 index 00000000..d638319b --- /dev/null +++ b/src/helpers/ethernet/ch390/CH390EthernetInterface.h @@ -0,0 +1,80 @@ +#pragma once + +#include "../../BaseSerialInterface.h" +#include +#include +#include +#include +#include + +#ifndef ETHERNET_TCP_PORT + #define ETHERNET_TCP_PORT 5000 +#endif +// define ETHERNET_RAW_LINE=1 to use raw line-based CLI instead of framed packets + +class CH390EthernetInterface : public BaseSerialInterface { + bool deviceConnected; + bool _isEnabled; + unsigned long _last_write; + uint8_t _state; + uint16_t _frame_len; + uint16_t _rx_len; + uint8_t _rx_buf[MAX_FRAME_SIZE]; + + WiFiServer server; + WiFiClient client; + + 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; + _state = 0; + _frame_len = 0; + _rx_len = 0; + } + + protected: + + public: + CH390EthernetInterface() : server(ETHERNET_TCP_PORT) { + deviceConnected = false; + _isEnabled = false; + _last_write = 0; + send_queue_len = 0; + _state = 0; + _frame_len = 0; + _rx_len = 0; + } + bool begin(); + void loop(); + + // 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 ETHERNET_DEBUG_LOGGING && ARDUINO + #include + #define ETHERNET_DEBUG_PRINT(F, ...) Serial.printf("ETH: " F, ##__VA_ARGS__) + #define ETHERNET_DEBUG_PRINTLN(F, ...) Serial.printf("ETH: " F "\n", ##__VA_ARGS__) + #define ETHERNET_DEBUG_PRINT_IP(name, ip) Serial.printf(name ": %u.%u.%u.%u" "\n", ip[0], ip[1], ip[2], ip[3]) +#else + #define ETHERNET_DEBUG_PRINT(...) {} + #define ETHERNET_DEBUG_PRINTLN(...) {} + #define ETHERNET_DEBUG_PRINT_IP(...) {} +#endif diff --git a/variants/thinknode_m7/platformio.ini b/variants/thinknode_m7/platformio.ini index acd98c8c..43ff61c3 100644 --- a/variants/thinknode_m7/platformio.ini +++ b/variants/thinknode_m7/platformio.ini @@ -34,6 +34,22 @@ build_src_filter = ${esp32_base.build_src_filter} lib_deps = ${esp32_base.lib_deps} stevemarple/MicroNMEA @ ^2.0.6 +[ThinkNode_M7_ethernet] +build_flags = + -D ETHERNET_ENABLED + -D ETHERNET_USE_CH390 + -D ETHERNET_CLASS=CH390EthernetInterface + -D ETH_MISO_PIN=14 + -D ETH_MOSI_PIN=48 + -D ETH_SCLK_PIN=47 + -D ETH_CS_PIN=21 + -D ETH_INT_PIN=45 + -D ETHERNET_DEBUG_LOGGING=1 +build_src_filter = + + +lib_deps = + https://github.com/liamcottle/ESP32-CH390.git#47b401f1de546118b03c18b5689dedec45871f2d + [env:ThinkNode_M7_repeater] extends = ThinkNode_M7 build_src_filter = ${ThinkNode_M7.build_src_filter} @@ -130,6 +146,26 @@ lib_deps = ${ThinkNode_M7.lib_deps} densaugeo/base64 @ ~1.4.0 +[env:ThinkNode_M7_companion_radio_ethernet] +extends = ThinkNode_M7 +build_flags = + ${ThinkNode_M7.build_flags} + ${ThinkNode_M7_ethernet.build_flags} + -I examples/companion_radio/ui-orig + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D DISPLAY_CLASS=NullDisplayDriver + -D OFFLINE_QUEUE_SIZE=256 +build_src_filter = ${ThinkNode_M7.build_src_filter} + ${ThinkNode_M7_ethernet.build_src_filter} + + + + + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-orig/*.cpp> +lib_deps = ${ThinkNode_M7.lib_deps} + ${ThinkNode_M7_ethernet.lib_deps} + densaugeo/base64 @ ~1.4.0 + [env:ThinkNode_M7_kiss_modem] extends = ThinkNode_M7 build_src_filter = ${ThinkNode_M7.build_src_filter} From a20eb5112457d2b742955b4699cd091b19dd8a92 Mon Sep 17 00:00:00 2001 From: liamcottle Date: Sat, 18 Jul 2026 00:33:35 +1200 Subject: [PATCH 051/381] rename class --- examples/companion_radio/main.cpp | 2 +- src/helpers/ethernet/{Ethernet.h => EthernetInterface.h} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename src/helpers/ethernet/{Ethernet.h => EthernetInterface.h} (100%) diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index 2fc00dbd..b6b6d93c 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -49,7 +49,7 @@ static uint32_t _atoi(const char* sp) { ArduinoSerialInterface serial_interface; HardwareSerial companion_serial(1); #elif defined(ETHERNET_ENABLED) - #include + #include ETHERNET_CLASS serial_interface; #else #include diff --git a/src/helpers/ethernet/Ethernet.h b/src/helpers/ethernet/EthernetInterface.h similarity index 100% rename from src/helpers/ethernet/Ethernet.h rename to src/helpers/ethernet/EthernetInterface.h From 6a785759d3b75ae8ee2bfc50f3f2019def46c1cf Mon Sep 17 00:00:00 2001 From: liamcottle Date: Sun, 19 Jul 2026 23:28:01 +1200 Subject: [PATCH 052/381] refactored companion interfaces to allow for multiple active connection modes --- examples/companion_radio/AbstractUITask.h | 12 +- examples/companion_radio/main.cpp | 209 ++++++++--------- examples/companion_radio/ui-new/UITask.cpp | 8 +- examples/companion_radio/ui-new/UITask.h | 4 +- examples/companion_radio/ui-orig/UITask.h | 2 +- examples/companion_radio/ui-tiny/UITask.h | 4 +- src/helpers/BaseSerialInterface.h | 1 + src/helpers/MultiSerialInterface.h | 200 ++++++++++++++++ .../ethernet/SerialEthernetInterface.cpp | 140 ++++++++++++ .../ethernet/SerialEthernetInterface.h | 75 ++++++ .../ethernet/ch390/CH390EthernetInterface.cpp | 215 +++++------------- .../ethernet/ch390/CH390EthernetInterface.h | 72 +----- variants/thinknode_m7/platformio.ini | 6 + 13 files changed, 595 insertions(+), 353 deletions(-) create mode 100644 src/helpers/MultiSerialInterface.h create mode 100644 src/helpers/ethernet/SerialEthernetInterface.cpp create mode 100644 src/helpers/ethernet/SerialEthernetInterface.h diff --git a/examples/companion_radio/AbstractUITask.h b/examples/companion_radio/AbstractUITask.h index 0eee45ae..b25b1442 100644 --- a/examples/companion_radio/AbstractUITask.h +++ b/examples/companion_radio/AbstractUITask.h @@ -4,7 +4,7 @@ #include #include #include -#include +#include #include #ifdef PIN_BUZZER @@ -25,10 +25,10 @@ enum class UIEventType { class AbstractUITask { protected: mesh::MainBoard* _board; - BaseSerialInterface* _serial; + MultiSerialInterface* _interfaceManager; bool _connected; - AbstractUITask(mesh::MainBoard* board, BaseSerialInterface* serial) : _board(board), _serial(serial) { + AbstractUITask(mesh::MainBoard* board, MultiSerialInterface* interfaceManager) : _board(board), _interfaceManager(interfaceManager) { _connected = false; } @@ -36,9 +36,9 @@ public: void setHasConnection(bool connected) { _connected = connected; } bool hasConnection() const { return _connected; } uint16_t getBattMilliVolts() const { return _board->getBattMilliVolts(); } - bool isSerialEnabled() const { return _serial->isEnabled(); } - void enableSerial() { _serial->enable(); } - void disableSerial() { _serial->disable(); } + bool isBluetoothEnabled() const { return _interfaceManager->isBluetoothEnabled(); } + void enableBluetooth() { _interfaceManager->enableBluetooth(); } + void disableBluetooth() { _interfaceManager->disableBluetooth(); } virtual void msgRead(int msgcount) = 0; virtual void newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount) = 0; virtual void notify(UIEventType t = UIEventType::none) = 0; diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index b6b6d93c..7c67d90d 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -12,6 +12,67 @@ static uint32_t _atoi(const char* sp) { return n; } +// interface manager +#include +MultiSerialInterface interface_manager; + +// include bluetooth interface +#if defined(BLE_PIN_CODE) + #ifdef ESP32 + // include esp32 bluetooth interface + #include + SerialBLEInterface bluetooth_interface; + #elif defined(NRF52_PLATFORM) + // include nrf52 bluetooth interface + #include + SerialBLEInterface bluetooth_interface; + #else + #error "SerialBLEInterface is not defined for this platform" + #endif +#endif + +// include wifi interface +#ifdef WIFI_SSID + #ifndef TCP_PORT + #define TCP_PORT 5000 + #endif + #ifdef ESP32 + // include esp32 wifi interface + #include + SerialWifiInterface wifi_interface; + #else + #error "SerialWifiInterface is not defined for this platform" + #endif +#endif + +// include usb interface +#if defined(ENABLE_USB_INTERFACE) + #include + ArduinoSerialInterface usb_serial_interface; +#endif + +// include ethernet interface +#if defined(ETHERNET_ENABLED) + // todo refactor rak/nrf52 SerialEthernetInterface to new EthernetInterface + #if defined(NRF52_PLATFORM) + // include nrf52 ethernet interface + #include + SerialEthernetInterface ethernet_interface; + #else + // include ethernet interface + #include + ETHERNET_CLASS ethernet_interface; + #endif +#endif + +// include hardware serial interface +#if defined(SERIAL_RX) + #include + ArduinoSerialInterface hardware_serial_interface; + HardwareSerial companion_serial(1); +#endif + +// platform file system #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) #include #if defined(QSPIFLASH) @@ -34,67 +95,10 @@ static uint32_t _atoi(const char* sp) { DataStore store(SPIFFS, rtc_clock); #endif -#ifdef ESP32 - #ifdef WIFI_SSID - #include - SerialWifiInterface serial_interface; - #ifndef TCP_PORT - #define TCP_PORT 5000 - #endif - #elif defined(BLE_PIN_CODE) - #include - SerialBLEInterface serial_interface; - #elif defined(SERIAL_RX) - #include - ArduinoSerialInterface serial_interface; - HardwareSerial companion_serial(1); - #elif defined(ETHERNET_ENABLED) - #include - ETHERNET_CLASS serial_interface; - #else - #include - ArduinoSerialInterface serial_interface; - #endif -#elif defined(RP2040_PLATFORM) - //#ifdef WIFI_SSID - // #include - // SerialWifiInterface serial_interface; - // #ifndef TCP_PORT - // #define TCP_PORT 5000 - // #endif - // #elif defined(BLE_PIN_CODE) - // #include - // SerialBLEInterface serial_interface; - #if defined(SERIAL_RX) - #include - ArduinoSerialInterface serial_interface; - HardwareSerial companion_serial(1); - #else - #include - ArduinoSerialInterface serial_interface; - #endif -#elif defined(NRF52_PLATFORM) - #ifdef BLE_PIN_CODE - #include - SerialBLEInterface serial_interface; - #elif defined(ETHERNET_ENABLED) - #include - SerialEthernetInterface serial_interface; - #else - #include - ArduinoSerialInterface serial_interface; - #endif -#elif defined(STM32_PLATFORM) - #include - ArduinoSerialInterface serial_interface; -#else - #error "need to define a serial interface" -#endif - /* GLOBAL OBJECTS */ #ifdef DISPLAY_CLASS #include "UITask.h" - UITask ui_task(&board, &serial_interface); + UITask ui_task(&board, &interface_manager); #endif StdRNG fast_rng; @@ -164,26 +168,6 @@ void setup() { false #endif ); - -#ifdef BLE_PIN_CODE - serial_interface.begin(BLE_NAME_PREFIX, the_mesh.getNodePrefs()->node_name, the_mesh.getBLEPin()); - the_mesh.startInterface(serial_interface); -#elif defined(ETHERNET_ENABLED) - Serial.print("Waiting for serial to connect...\n"); - unsigned long timeout = millis(); - while (!Serial) { - if ((millis() - timeout) < 5000) { delay(100); } else { break; } - } - Serial.println("Initializing Ethernet adapter..."); - if (serial_interface.begin()) { - the_mesh.startInterface(serial_interface); - } else { - Serial.println("ETH: Init failed, continuing without Ethernet (mesh only)"); - } -#else - serial_interface.begin(Serial); - the_mesh.startInterface(serial_interface); -#endif #elif defined(RP2040_PLATFORM) LittleFS.begin(); store.begin(); @@ -194,22 +178,6 @@ void setup() { false #endif ); - - //#ifdef WIFI_SSID - // WiFi.begin(WIFI_SSID, WIFI_PWD); - // serial_interface.begin(TCP_PORT); - // #elif defined(BLE_PIN_CODE) - // char dev_name[32+16]; - // sprintf(dev_name, "%s%s", BLE_NAME_PREFIX, the_mesh.getNodeName()); - // serial_interface.begin(dev_name, the_mesh.getBLEPin()); - #if defined(SERIAL_RX) - companion_serial.setPins(SERIAL_RX, SERIAL_TX); - companion_serial.begin(115200); - serial_interface.begin(companion_serial); - #else - serial_interface.begin(Serial); - #endif - the_mesh.startInterface(serial_interface); #elif defined(ESP32) SPIFFS.begin(true); store.begin(); @@ -220,7 +188,17 @@ void setup() { false #endif ); +#else + #error "need to define filesystem" +#endif +// add bluetooth interface +#if defined(BLE_PIN_CODE) + bluetooth_interface.begin(BLE_NAME_PREFIX, the_mesh.getNodePrefs()->node_name, the_mesh.getBLEPin()); + interface_manager.addInterface(InterfaceType::Bluetooth, &bluetooth_interface); +#endif + +// add wifi interface #ifdef WIFI_SSID board.setInhibitSleep(true); // prevent sleep when WiFi is active WiFi.setAutoReconnect(true); @@ -236,23 +214,31 @@ void setup() { }); WiFi.begin(WIFI_SSID, WIFI_PWD); - serial_interface.begin(TCP_PORT); -#elif defined(BLE_PIN_CODE) - serial_interface.begin(BLE_NAME_PREFIX, the_mesh.getNodePrefs()->node_name, the_mesh.getBLEPin()); -#elif defined(SERIAL_RX) - companion_serial.setPins(SERIAL_RX, SERIAL_TX); - companion_serial.begin(115200); - serial_interface.begin(companion_serial); -#elif defined(ETHERNET_ENABLED) - serial_interface.begin(); -#else - serial_interface.begin(Serial); -#endif - the_mesh.startInterface(serial_interface); -#else - #error "need to define filesystem" + wifi_interface.begin(TCP_PORT); + interface_manager.addInterface(InterfaceType::WiFi, &wifi_interface); #endif +// add usb interface +#if defined(ENABLE_USB_INTERFACE) + usb_serial_interface.begin(Serial); + interface_manager.addInterface(InterfaceType::USB, &usb_serial_interface); +#endif + +// add ethernet interface +#if defined(ETHERNET_ENABLED) + ethernet_interface.begin(); + interface_manager.addInterface(InterfaceType::Ethernet, ðernet_interface); +#endif + +// add hardware serial interface +#if defined(SERIAL_RX) + companion_serial.setPins(SERIAL_RX, SERIAL_TX); + companion_serial.begin(115200); + hardware_serial_interface.begin(companion_serial); + interface_manager.addInterface(InterfaceType::HardwareSerial, &hardware_serial_interface); +#endif + + the_mesh.startInterface(interface_manager); sensors.begin(); #if ENV_INCLUDE_GPS == 1 @@ -268,6 +254,7 @@ void setup() { void loop() { the_mesh.loop(); + interface_manager.loop(); sensors.loop(); #ifdef DISPLAY_CLASS ui_task.loop(); @@ -277,10 +264,6 @@ void loop() { external_watchdog.loop(); #endif -#ifdef ETHERNET_ENABLED - serial_interface.loop(); -#endif - if (!the_mesh.hasPendingWork()) { #if defined(NRF52_PLATFORM) board.sleep(0); // nrf ignores seconds param, sleeps whenever possible diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index 50dc91d2..051f3b31 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -289,7 +289,7 @@ public: } else if (_page == HomePage::BLUETOOTH) { display.setColor(UIColor::corp_blue); display.drawXbm((display.width() - 32) / 2, 18, - _task->isSerialEnabled() ? bluetooth_on : bluetooth_off, + _task->isBluetoothEnabled() ? bluetooth_on : bluetooth_off, 32, 32); display.setColor(UIColor::secondary_txt); display.setTextSize(1); @@ -449,10 +449,10 @@ public: return true; } if (c == KEY_ENTER && _page == HomePage::BLUETOOTH) { - if (_task->isSerialEnabled()) { // toggle Bluetooth on/off - _task->disableSerial(); + if (_task->isBluetoothEnabled()) { // toggle Bluetooth on/off + _task->disableBluetooth(); } else { - _task->enableSerial(); + _task->enableBluetooth(); } return true; } diff --git a/examples/companion_radio/ui-new/UITask.h b/examples/companion_radio/ui-new/UITask.h index a77ad6e7..52d3ffa1 100644 --- a/examples/companion_radio/ui-new/UITask.h +++ b/examples/companion_radio/ui-new/UITask.h @@ -4,7 +4,7 @@ #include #include #include -#include +#include #include #include @@ -65,7 +65,7 @@ class UITask : public AbstractUITask { public: - UITask(mesh::MainBoard* board, BaseSerialInterface* serial) : AbstractUITask(board, serial), _display(NULL), _sensors(NULL) { + UITask(mesh::MainBoard* board, MultiSerialInterface* serial) : AbstractUITask(board, serial), _display(NULL), _sensors(NULL) { next_batt_chck = _next_refresh = 0; ui_started_at = 0; curr = NULL; diff --git a/examples/companion_radio/ui-orig/UITask.h b/examples/companion_radio/ui-orig/UITask.h index 60cd0d04..961c07a0 100644 --- a/examples/companion_radio/ui-orig/UITask.h +++ b/examples/companion_radio/ui-orig/UITask.h @@ -54,7 +54,7 @@ class UITask : public AbstractUITask { public: - UITask(mesh::MainBoard* board, BaseSerialInterface* serial) : AbstractUITask(board, serial), _display(NULL), _sensors(NULL) { + UITask(mesh::MainBoard* board, MultiSerialInterface* serial) : AbstractUITask(board, serial), _display(NULL), _sensors(NULL) { _next_refresh = 0; ui_started_at = 0; } diff --git a/examples/companion_radio/ui-tiny/UITask.h b/examples/companion_radio/ui-tiny/UITask.h index 344e48b9..dc689478 100644 --- a/examples/companion_radio/ui-tiny/UITask.h +++ b/examples/companion_radio/ui-tiny/UITask.h @@ -4,7 +4,7 @@ #include #include #include -#include +#include #include #include @@ -71,7 +71,7 @@ class UITask : public AbstractUITask { public: - UITask(mesh::MainBoard* board, BaseSerialInterface* serial) : AbstractUITask(board, serial), _display(NULL), _sensors(NULL) { + UITask(mesh::MainBoard* board, MultiSerialInterface* serial) : AbstractUITask(board, serial), _display(NULL), _sensors(NULL) { next_batt_chck = _next_refresh = 0; _cached_batt_mv = 0; ui_started_at = 0; diff --git a/src/helpers/BaseSerialInterface.h b/src/helpers/BaseSerialInterface.h index e9a3f2ab..23933fcb 100644 --- a/src/helpers/BaseSerialInterface.h +++ b/src/helpers/BaseSerialInterface.h @@ -14,6 +14,7 @@ public: virtual bool isEnabled() const = 0; virtual bool isConnected() const = 0; + virtual void loop() {}; virtual bool isWriteBusy() const = 0; virtual size_t writeFrame(const uint8_t src[], size_t len) = 0; diff --git a/src/helpers/MultiSerialInterface.h b/src/helpers/MultiSerialInterface.h new file mode 100644 index 00000000..f7742b24 --- /dev/null +++ b/src/helpers/MultiSerialInterface.h @@ -0,0 +1,200 @@ +#pragma once + +#include "BaseSerialInterface.h" + +#ifndef MAX_INTERFACES + // ble, usb, wifi, ethernet + #define MAX_INTERFACES 4 +#endif + +enum class InterfaceType : uint8_t { + NONE, + Bluetooth, + USB, + WiFi, + Ethernet, + HardwareSerial +}; + +class MultiSerialInterface : public BaseSerialInterface { +private: + + struct RegisteredInterface { + InterfaceType type = InterfaceType::NONE; + BaseSerialInterface* instance = nullptr; + }; + + bool _enabled = false; + RegisteredInterface _interfaces[MAX_INTERFACES] = {}; + +public: + bool addInterface(InterfaceType type, BaseSerialInterface* iface) { + // make sure an interface was provided + if(iface == nullptr){ + return false; + } + + // put it in the first free slot + for(int i = 0; i < MAX_INTERFACES; i++){ + if(_interfaces[i].instance == nullptr){ + _interfaces[i].instance = iface; + _interfaces[i].type = type; + return true; + } + } + + // no free slots available + return false; + } + + bool removeInterface(BaseSerialInterface* iface) { + // make sure an interface was provided + if(iface == nullptr){ + return false; + } + + // find and remove interface + for(int i = 0; i < MAX_INTERFACES; i++){ + if(_interfaces[i].instance == iface){ + _interfaces[i] = {}; + return true; + } + } + + // interface not found + return false; + } + + void enableBluetooth() { + for(auto iface : _interfaces){ + if(iface.instance && iface.type == InterfaceType::Bluetooth){ + iface.instance->enable(); + } + } + } + + void disableBluetooth() { + for(auto iface : _interfaces){ + if(iface.instance && iface.type == InterfaceType::Bluetooth){ + iface.instance->disable(); + } + } + } + + bool isBluetoothEnabled() { + for(auto iface : _interfaces){ + if(iface.instance && iface.type == InterfaceType::Bluetooth){ + return iface.instance->isEnabled(); + } + } + return false; + } + + // enable all interfaces + void enable() override { + _enabled = true; + for(auto iface : _interfaces){ + if(iface.instance){ + iface.instance->enable(); + } + } + } + + // disable all interfaces + void disable() override { + _enabled = false; + for(auto iface : _interfaces){ + if(iface.instance){ + iface.instance->disable(); + } + } + } + + bool isEnabled() const override { + return _enabled; + } + + bool isConnected() const override { + // not connected when disabled + if(!_enabled){ + return false; + } + + // check if any interface is connected + for(auto iface : _interfaces){ + if(iface.instance && iface.instance->isConnected()) { + return true; + } + } + + // nothing connected + return false; + } + + // loop all interfaces + void loop() override { + for(auto iface : _interfaces){ + if(iface.instance){ + iface.instance->loop(); + } + } + } + + bool isWriteBusy() const override { + // not busy when disabled + if(!_enabled){ + return false; + } + + // check if any interface is busy + for(auto iface : _interfaces){ + if(iface.instance && iface.instance->isEnabled() && iface.instance->isWriteBusy()){ + return true; + } + } + + // nothing busy + return false; + } + + size_t writeFrame(const uint8_t src[], size_t len) override { + // don't write when disabled or nothing provided + if(!_enabled || len == 0){ + return 0; + } + + // write frame to all enabled interfaces + bool allSuccessful = true; + for(auto iface : _interfaces){ + if(iface.instance && iface.instance->isEnabled()){ + if(iface.instance->writeFrame(src, len) != len){ + allSuccessful = false; + } + } + } + + // report success if all writes completed successfully + return allSuccessful ? len : 0; + } + + size_t checkRecvFrame(uint8_t dest[]) override { + // don't read when disabled + if(!_enabled){ + return 0; + } + + // try to read a frame from any enabled interface + for(auto iface : _interfaces){ + if(iface.instance && iface.instance->isEnabled()){ + size_t frameSize = iface.instance->checkRecvFrame(dest); + if(frameSize > 0){ + return frameSize; + } + } + } + + // no frame received + return 0; + } + +}; diff --git a/src/helpers/ethernet/SerialEthernetInterface.cpp b/src/helpers/ethernet/SerialEthernetInterface.cpp new file mode 100644 index 00000000..22bcabc1 --- /dev/null +++ b/src/helpers/ethernet/SerialEthernetInterface.cpp @@ -0,0 +1,140 @@ +#include "SerialEthernetInterface.h" + +#define RECV_STATE_IDLE 0 +#define RECV_STATE_HDR_FOUND 1 +#define RECV_STATE_LEN1_FOUND 2 +#define RECV_STATE_LEN2_FOUND 3 + +bool SerialEthernetInterface::begin() { + return true; +} + +void SerialEthernetInterface::enable() { + if (_isEnabled) return; + _isEnabled = true; + clearBuffers(); +} + +void SerialEthernetInterface::disable() { + _isEnabled = false; +} + +size_t SerialEthernetInterface::writeFrame(const uint8_t src[], size_t len) { + if (len > MAX_FRAME_SIZE) { + ETHERNET_DEBUG_PRINTLN("writeFrame(), frame too big, len=%d\n", len); + return 0; + } + + if (isConnected() && len > 0) { + if (send_queue_len >= FRAME_QUEUE_SIZE) { + ETHERNET_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; +} + +bool SerialEthernetInterface::isWriteBusy() const { + return false; +} + +void SerialEthernetInterface::onClientConnected() { + _state = RECV_STATE_IDLE; + _frame_len = 0; + _rx_len = 0; +} + +size_t SerialEthernetInterface::checkRecvFrame(uint8_t dest[]) { + + if (isConnected()) { + if (send_queue_len > 0) { // first, check send queue + + _last_write = millis(); + int len = send_queue[0].len; + +#if ETHERNET_RAW_LINE + ETHERNET_DEBUG_PRINTLN("TX line len=%d", len); + client.write(send_queue[0].buf, len); + client.write("\r\n", 2); +#else + uint8_t pkt[3+len]; // use same header as serial interface so client can delimit frames + pkt[0] = '>'; + pkt[1] = (len & 0xFF); // LSB + pkt[2] = (len >> 8); // MSB + memcpy(&pkt[3], send_queue[0].buf, send_queue[0].len); + ETHERNET_DEBUG_PRINTLN("Sending frame len=%d", len); + #if ETHERNET_DEBUG_LOGGING && ARDUINO + ETHERNET_DEBUG_PRINTLN("TX frame len=%d", len); + #endif + write(pkt, 3 + len); +#endif + 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 { + while (available()) { + int c = read(); + if (c < 0) break; + +#if ETHERNET_RAW_LINE + if (c == '\r' || c == '\n') { + if (_rx_len == 0) { + continue; + } + uint16_t out_len = _rx_len; + if (out_len > MAX_FRAME_SIZE) out_len = MAX_FRAME_SIZE; + memcpy(dest, _rx_buf, out_len); + _rx_len = 0; + return out_len; + } + if (_rx_len < MAX_FRAME_SIZE) { + _rx_buf[_rx_len] = (uint8_t)c; + _rx_len++; + } +#else + switch (_state) { + case RECV_STATE_IDLE: + if (c == '<') { + _state = RECV_STATE_HDR_FOUND; + } + break; + case RECV_STATE_HDR_FOUND: + _frame_len = (uint8_t)c; + _state = RECV_STATE_LEN1_FOUND; + break; + case RECV_STATE_LEN1_FOUND: + _frame_len |= ((uint16_t)c) << 8; + _rx_len = 0; + _state = _frame_len > 0 ? RECV_STATE_LEN2_FOUND : RECV_STATE_IDLE; + break; + default: + if (_rx_len < MAX_FRAME_SIZE) { + _rx_buf[_rx_len] = (uint8_t)c; + } + _rx_len++; + if (_rx_len >= _frame_len) { + if (_frame_len > MAX_FRAME_SIZE) { + _frame_len = MAX_FRAME_SIZE; + } + #if ETHERNET_DEBUG_LOGGING && ARDUINO + ETHERNET_DEBUG_PRINTLN("RX frame len=%d", _frame_len); + #endif + memcpy(dest, _rx_buf, _frame_len); + _state = RECV_STATE_IDLE; + return _frame_len; + } + } +#endif + } + } + } + + return 0; +} diff --git a/src/helpers/ethernet/SerialEthernetInterface.h b/src/helpers/ethernet/SerialEthernetInterface.h new file mode 100644 index 00000000..46789f71 --- /dev/null +++ b/src/helpers/ethernet/SerialEthernetInterface.h @@ -0,0 +1,75 @@ +#pragma once + +#include "../BaseSerialInterface.h" + +#ifndef ETHERNET_TCP_PORT + #define ETHERNET_TCP_PORT 5000 +#endif +// define ETHERNET_RAW_LINE=1 to use raw line-based CLI instead of framed packets + +class SerialEthernetInterface : public BaseSerialInterface { + bool _isEnabled; + unsigned long _last_write; + uint8_t _state; + uint16_t _frame_len; + uint16_t _rx_len; + uint8_t _rx_buf[MAX_FRAME_SIZE]; + + 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; + _state = 0; + _frame_len = 0; + _rx_len = 0; + } + + protected: + + public: + SerialEthernetInterface() { + _isEnabled = false; + _last_write = 0; + send_queue_len = 0; + _state = 0; + _frame_len = 0; + _rx_len = 0; + } + bool begin(); + + void onClientConnected(); + + // 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; + + virtual int available() = 0; + virtual int read() = 0; + virtual size_t write(const uint8_t *buf, size_t size) = 0; +}; + + +#if ETHERNET_DEBUG_LOGGING && ARDUINO + #include + #define ETHERNET_DEBUG_PRINT(F, ...) Serial.printf("ETH: " F, ##__VA_ARGS__) + #define ETHERNET_DEBUG_PRINTLN(F, ...) Serial.printf("ETH: " F "\n", ##__VA_ARGS__) + #define ETHERNET_DEBUG_PRINT_IP(name, ip) Serial.printf("ETH: " name ": %u.%u.%u.%u" "\n", ip[0], ip[1], ip[2], ip[3]) +#else + #define ETHERNET_DEBUG_PRINT(...) {} + #define ETHERNET_DEBUG_PRINTLN(...) {} + #define ETHERNET_DEBUG_PRINT_IP(...) {} +#endif diff --git a/src/helpers/ethernet/ch390/CH390EthernetInterface.cpp b/src/helpers/ethernet/ch390/CH390EthernetInterface.cpp index f7ee5503..7f696245 100644 --- a/src/helpers/ethernet/ch390/CH390EthernetInterface.cpp +++ b/src/helpers/ethernet/ch390/CH390EthernetInterface.cpp @@ -1,12 +1,33 @@ #include "CH390EthernetInterface.h" -#define RECV_STATE_IDLE 0 -#define RECV_STATE_HDR_FOUND 1 -#define RECV_STATE_LEN1_FOUND 2 -#define RECV_STATE_LEN2_FOUND 3 +void onWiFiEvent(WiFiEvent_t event) { + switch(event){ + case ARDUINO_EVENT_ETH_START: + ETHERNET_DEBUG_PRINTLN("Ethernet Started"); + break; + case ARDUINO_EVENT_ETH_CONNECTED: + ETHERNET_DEBUG_PRINTLN("Ethernet Connected"); + break; + case ARDUINO_EVENT_ETH_DISCONNECTED: + ETHERNET_DEBUG_PRINTLN("Ethernet Disconnected"); + break; + case ARDUINO_EVENT_ETH_GOT_IP: + ETHERNET_DEBUG_PRINTLN("Ethernet Got IP"); + ETHERNET_DEBUG_PRINT_IP("IP Address", CH390.localIP()); + ETHERNET_DEBUG_PRINT_IP("Subnet Mask", CH390.subnetMask()); + ETHERNET_DEBUG_PRINT_IP("Gateway", CH390.gatewayIP()); + ETHERNET_DEBUG_PRINT_IP("DNS", CH390.dnsIP()); + ETHERNET_DEBUG_PRINTLN("MAC Address: %s", CH390.macAddress().c_str()); + break; + default: + break; + } +} bool CH390EthernetInterface::begin() { - ETHERNET_DEBUG_PRINTLN("Ethernet initializing"); + + // listen to ethernet events + WiFi.onEvent(onWiFiEvent); // Init CH390 ch390_config_t config = CH390_DEFAULT_CONFIG(); @@ -29,179 +50,45 @@ bool CH390EthernetInterface::begin() { #endif // Start Server - server.begin(); + server.begin(ETHERNET_TCP_PORT); ETHERNET_DEBUG_PRINTLN("listening on TCP port: %d", ETHERNET_TCP_PORT); return true; } -void CH390EthernetInterface::enable() { - if (_isEnabled) return; - _isEnabled = true; - clearBuffers(); +int CH390EthernetInterface::available() { + return client.available(); } -void CH390EthernetInterface::disable() { - _isEnabled = false; +int CH390EthernetInterface::read() { + return client.read(); } -size_t CH390EthernetInterface::writeFrame(const uint8_t src[], size_t len) { - if (len > MAX_FRAME_SIZE) { - ETHERNET_DEBUG_PRINTLN("writeFrame(), frame too big, len=%d\n", len); - return 0; - } - - if (deviceConnected && len > 0) { - if (send_queue_len >= FRAME_QUEUE_SIZE) { - ETHERNET_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; -} - -bool CH390EthernetInterface::isWriteBusy() const { - return false; -} - -size_t CH390EthernetInterface::checkRecvFrame(uint8_t dest[]) { - if (server.hasClient()) { - auto newClient = server.available(); - if (newClient) { - IPAddress new_ip = newClient.remoteIP(); - uint16_t new_port = newClient.remotePort(); - ETHERNET_DEBUG_PRINTLN( - "New client accepted %u.%u.%u.%u:%u", - new_ip[0], new_ip[1], new_ip[2], new_ip[3], new_port); - - deviceConnected = false; - if (client) { - ETHERNET_DEBUG_PRINTLN("Closing previous client"); - client.stop(); - } - _state = RECV_STATE_IDLE; - _frame_len = 0; - _rx_len = 0; - client = newClient; - ETHERNET_DEBUG_PRINTLN("Switched to new client"); - } - } - - if (client.connected()) { - if (!deviceConnected) { - ETHERNET_DEBUG_PRINTLN( - "Got connection %u.%u.%u.%u:%u", - client.remoteIP()[0], - client.remoteIP()[1], - client.remoteIP()[2], - client.remoteIP()[3], - client.remotePort()); - deviceConnected = true; - } - } else { - if (deviceConnected) { - deviceConnected = false; - ETHERNET_DEBUG_PRINTLN("Disconnected"); - } - } - - if (deviceConnected) { - if (send_queue_len > 0) { // first, check send queue - - _last_write = millis(); - int len = send_queue[0].len; - -#if ETHERNET_RAW_LINE - ETHERNET_DEBUG_PRINTLN("TX line len=%d", len); - client.write(send_queue[0].buf, len); - client.write("\r\n", 2); -#else - uint8_t pkt[3+len]; // use same header as serial interface so client can delimit frames - pkt[0] = '>'; - pkt[1] = (len & 0xFF); // LSB - pkt[2] = (len >> 8); // MSB - memcpy(&pkt[3], send_queue[0].buf, send_queue[0].len); - ETHERNET_DEBUG_PRINTLN("Sending frame len=%d", len); - #if ETHERNET_DEBUG_LOGGING && ARDUINO - ETHERNET_DEBUG_PRINTLN("TX frame len=%d", len); - #endif - client.write(pkt, 3 + len); -#endif - 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 { - while (client.available()) { - int c = client.read(); - if (c < 0) break; - -#if ETHERNET_RAW_LINE - if (c == '\r' || c == '\n') { - if (_rx_len == 0) { - continue; - } - uint16_t out_len = _rx_len; - if (out_len > MAX_FRAME_SIZE) out_len = MAX_FRAME_SIZE; - memcpy(dest, _rx_buf, out_len); - _rx_len = 0; - return out_len; - } - if (_rx_len < MAX_FRAME_SIZE) { - _rx_buf[_rx_len] = (uint8_t)c; - _rx_len++; - } -#else - switch (_state) { - case RECV_STATE_IDLE: - if (c == '<') { - _state = RECV_STATE_HDR_FOUND; - } - break; - case RECV_STATE_HDR_FOUND: - _frame_len = (uint8_t)c; - _state = RECV_STATE_LEN1_FOUND; - break; - case RECV_STATE_LEN1_FOUND: - _frame_len |= ((uint16_t)c) << 8; - _rx_len = 0; - _state = _frame_len > 0 ? RECV_STATE_LEN2_FOUND : RECV_STATE_IDLE; - break; - default: - if (_rx_len < MAX_FRAME_SIZE) { - _rx_buf[_rx_len] = (uint8_t)c; - } - _rx_len++; - if (_rx_len >= _frame_len) { - if (_frame_len > MAX_FRAME_SIZE) { - _frame_len = MAX_FRAME_SIZE; - } - #if ETHERNET_DEBUG_LOGGING && ARDUINO - ETHERNET_DEBUG_PRINTLN("RX frame len=%d", _frame_len); - #endif - memcpy(dest, _rx_buf, _frame_len); - _state = RECV_STATE_IDLE; - return _frame_len; - } - } -#endif - } - } - } - - return 0; +size_t CH390EthernetInterface::write(const uint8_t *buf, size_t size) { + return client.write(buf, size); } bool CH390EthernetInterface::isConnected() const { - return deviceConnected; + return _isConnected; } void CH390EthernetInterface::loop() { + if (server.hasClient()) { + auto newClient = server.available(); + if (newClient) { + IPAddress remoteIp = newClient.remoteIP(); + uint16_t remotePort = newClient.remotePort(); + ETHERNET_DEBUG_PRINTLN("New client accepted %u.%u.%u.%u:%u", remoteIp[0], remoteIp[1], remoteIp[2], remoteIp[3], remotePort); + if (client) { + ETHERNET_DEBUG_PRINTLN("Closing previous client"); + client.stop(); + } + client = newClient; + onClientConnected(); + } + } + + _isConnected = client.connected(); + } diff --git a/src/helpers/ethernet/ch390/CH390EthernetInterface.h b/src/helpers/ethernet/ch390/CH390EthernetInterface.h index d638319b..09c3fc23 100644 --- a/src/helpers/ethernet/ch390/CH390EthernetInterface.h +++ b/src/helpers/ethernet/ch390/CH390EthernetInterface.h @@ -1,80 +1,30 @@ #pragma once -#include "../../BaseSerialInterface.h" +#include "../SerialEthernetInterface.h" #include #include #include #include #include -#ifndef ETHERNET_TCP_PORT - #define ETHERNET_TCP_PORT 5000 -#endif -// define ETHERNET_RAW_LINE=1 to use raw line-based CLI instead of framed packets - -class CH390EthernetInterface : public BaseSerialInterface { - bool deviceConnected; - bool _isEnabled; - unsigned long _last_write; - uint8_t _state; - uint16_t _frame_len; - uint16_t _rx_len; - uint8_t _rx_buf[MAX_FRAME_SIZE]; - +class CH390EthernetInterface : public SerialEthernetInterface { + + bool _isConnected; WiFiServer server; WiFiClient client; - 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; - _state = 0; - _frame_len = 0; - _rx_len = 0; - } - - protected: - public: - CH390EthernetInterface() : server(ETHERNET_TCP_PORT) { - deviceConnected = false; - _isEnabled = false; - _last_write = 0; - send_queue_len = 0; - _state = 0; - _frame_len = 0; - _rx_len = 0; + CH390EthernetInterface(){ + _isConnected = false; } + bool begin(); - void loop(); + void loop() override; // 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; + int available() override; + int read() override; + size_t write(const uint8_t *buf, size_t size) override; }; - - -#if ETHERNET_DEBUG_LOGGING && ARDUINO - #include - #define ETHERNET_DEBUG_PRINT(F, ...) Serial.printf("ETH: " F, ##__VA_ARGS__) - #define ETHERNET_DEBUG_PRINTLN(F, ...) Serial.printf("ETH: " F "\n", ##__VA_ARGS__) - #define ETHERNET_DEBUG_PRINT_IP(name, ip) Serial.printf(name ": %u.%u.%u.%u" "\n", ip[0], ip[1], ip[2], ip[3]) -#else - #define ETHERNET_DEBUG_PRINT(...) {} - #define ETHERNET_DEBUG_PRINTLN(...) {} - #define ETHERNET_DEBUG_PRINT_IP(...) {} -#endif diff --git a/variants/thinknode_m7/platformio.ini b/variants/thinknode_m7/platformio.ini index 43ff61c3..2ff6fc0a 100644 --- a/variants/thinknode_m7/platformio.ini +++ b/variants/thinknode_m7/platformio.ini @@ -1,6 +1,8 @@ [ThinkNode_M7] extends = esp32_base board = thinknode_m7 +board_upload.flash_size = 8MB +board_build.partitions = default_8MB.csv build_flags = ${esp32_base.build_flags} -I src/helpers/esp32 -I variants/thinknode_m7 @@ -46,6 +48,7 @@ build_flags = -D ETH_INT_PIN=45 -D ETHERNET_DEBUG_LOGGING=1 build_src_filter = + + + lib_deps = https://github.com/liamcottle/ESP32-CH390.git#47b401f1de546118b03c18b5689dedec45871f2d @@ -88,6 +91,7 @@ lib_deps = extends = ThinkNode_M7 build_flags = ${ThinkNode_M7.build_flags} + ${ThinkNode_M7_ethernet.build_flags} -I examples/companion_radio/ui-orig -D DISPLAY_CLASS=NullDisplayDriver -D MAX_CONTACTS=350 @@ -97,6 +101,7 @@ build_flags = ; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 build_src_filter = ${ThinkNode_M7.build_src_filter} + ${ThinkNode_M7_ethernet.build_src_filter} + + + @@ -104,6 +109,7 @@ build_src_filter = ${ThinkNode_M7.build_src_filter} +<../examples/companion_radio/ui-orig/*.cpp> lib_deps = ${ThinkNode_M7.lib_deps} + ${ThinkNode_M7_ethernet.lib_deps} densaugeo/base64 @ ~1.4.0 [env:ThinkNode_M7_companion_radio_usb] From bd83d290da0463feea2922186ea5a773917d0110 Mon Sep 17 00:00:00 2001 From: liamcottle Date: Tue, 28 Jul 2026 03:05:49 +1200 Subject: [PATCH 053/381] refactor rak13800 to new ethernet interface class --- examples/companion_radio/main.cpp | 12 +- src/helpers/ethernet/EthernetInterface.h | 2 + .../RAK13800/RAK13800EthernetInterface.cpp | 109 ++++++++++++++++++ .../RAK13800/RAK13800EthernetInterface.h | 27 +++++ variants/rak4631/platformio.ini | 5 +- 5 files changed, 144 insertions(+), 11 deletions(-) create mode 100644 src/helpers/ethernet/RAK13800/RAK13800EthernetInterface.cpp create mode 100644 src/helpers/ethernet/RAK13800/RAK13800EthernetInterface.h diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index 7c67d90d..89f0e6cb 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -53,16 +53,8 @@ MultiSerialInterface interface_manager; // include ethernet interface #if defined(ETHERNET_ENABLED) - // todo refactor rak/nrf52 SerialEthernetInterface to new EthernetInterface - #if defined(NRF52_PLATFORM) - // include nrf52 ethernet interface - #include - SerialEthernetInterface ethernet_interface; - #else - // include ethernet interface - #include - ETHERNET_CLASS ethernet_interface; - #endif + #include + ETHERNET_CLASS ethernet_interface; #endif // include hardware serial interface diff --git a/src/helpers/ethernet/EthernetInterface.h b/src/helpers/ethernet/EthernetInterface.h index 4d889df4..4e1f9176 100644 --- a/src/helpers/ethernet/EthernetInterface.h +++ b/src/helpers/ethernet/EthernetInterface.h @@ -3,6 +3,8 @@ #if defined(ETHERNET_ENABLED) #if defined(ETHERNET_USE_CH390) #include "helpers/ethernet/ch390/CH390EthernetInterface.h" + #elif defined(ETHERNET_USE_RAK13800) + #include "helpers/ethernet/RAK13800/RAK13800EthernetInterface.h" #else #error "ETHERNET_ENABLED is defined, but no specific driver flag (e.g. ETHERNET_USE_CH390) was provided!" #endif diff --git a/src/helpers/ethernet/RAK13800/RAK13800EthernetInterface.cpp b/src/helpers/ethernet/RAK13800/RAK13800EthernetInterface.cpp new file mode 100644 index 00000000..027581e3 --- /dev/null +++ b/src/helpers/ethernet/RAK13800/RAK13800EthernetInterface.cpp @@ -0,0 +1,109 @@ +#include "RAK13800EthernetInterface.h" +#include "../../nrf52/EthernetMac.h" +#include +#include + +#define PIN_SPI1_MISO (29) // (0 + 29) +#define PIN_SPI1_MOSI (30) // (0 + 30) +#define PIN_SPI1_SCK (3) // (0 + 3) + +SPIClass ETHERNET_SPI_PORT(NRF_SPIM1, PIN_SPI1_MISO, PIN_SPI1_SCK, PIN_SPI1_MOSI); + +#define PIN_ETHERNET_POWER_EN WB_IO2 // output, high to enable +#define PIN_ETHERNET_RESET 21 +#define PIN_ETHERNET_SS 26 + +bool RAK13800EthernetInterface::begin() { + + // WB_IO2 (power enable) is already driven HIGH by early constructor + // in RAK4631Board.cpp to support POE boot. + // Skip hardware reset — the W5100S comes out of power-on reset cleanly, + // and toggling reset kills the PHY link which breaks POE power. +#ifdef PIN_ETHERNET_RESET + pinMode(PIN_ETHERNET_RESET, OUTPUT); + digitalWrite(PIN_ETHERNET_RESET, HIGH); +#endif + + // generate mac address + uint8_t mac[6]; + generateEthernetMac(mac); + ETHERNET_DEBUG_PRINTLN( + "Ethernet MAC: %02X:%02X:%02X:%02X:%02X:%02X", + mac[0], + mac[1], + mac[2], + mac[3], + mac[4], + mac[5]); + ETHERNET_SPI_PORT.begin(); + Ethernet.init(ETHERNET_SPI_PORT, PIN_ETHERNET_SS); + + // Use static IP if build flags are defined, otherwise DHCP + #if defined(ETHERNET_STATIC_IP) && defined(ETHERNET_STATIC_GATEWAY) && defined(ETHERNET_STATIC_SUBNET) && defined(ETHERNET_STATIC_DNS) + IPAddress ip(ETHERNET_STATIC_IP); + IPAddress gateway(ETHERNET_STATIC_GATEWAY); + IPAddress subnet(ETHERNET_STATIC_SUBNET); + IPAddress dns(ETHERNET_STATIC_DNS); + Ethernet.begin(mac, ip, dns, gateway, subnet); + #else + if (Ethernet.begin(mac) == 0) { + ETHERNET_DEBUG_PRINTLN("Failed to initialize RAK13800 hardware."); + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + ETHERNET_DEBUG_PRINTLN("Ethernet hardware not found."); + } else if (Ethernet.linkStatus() == LinkOFF) { + ETHERNET_DEBUG_PRINTLN("Ethernet cable not connected."); + } else { + ETHERNET_DEBUG_PRINTLN("DHCP failed for unknown reason."); + } + return false; + } + #endif + + ETHERNET_DEBUG_PRINTLN("Ethernet begin complete"); + ETHERNET_DEBUG_PRINT_IP("IP Address", Ethernet.localIP()); + ETHERNET_DEBUG_PRINT_IP("Subnet Mask", Ethernet.subnetMask()); + ETHERNET_DEBUG_PRINT_IP("Gateway", Ethernet.gatewayIP()); + ETHERNET_DEBUG_PRINT_IP("DNS", Ethernet.dnsServerIP()); + + server.begin(); + ETHERNET_DEBUG_PRINTLN("listening on TCP port: %d", ETHERNET_TCP_PORT); + + return true; +} + +int RAK13800EthernetInterface::available() { + return client.available(); +} + +int RAK13800EthernetInterface::read() { + return client.read(); +} + +size_t RAK13800EthernetInterface::write(const uint8_t *buf, size_t size) { + return client.write(buf, size); +} + +bool RAK13800EthernetInterface::isConnected() const { + return _isConnected; +} + +void RAK13800EthernetInterface::loop() { + + Ethernet.maintain(); + + auto newClient = server.accept(); + if (newClient) { + IPAddress remoteIp = newClient.remoteIP(); + uint16_t remotePort = newClient.remotePort(); + ETHERNET_DEBUG_PRINTLN("New client accepted %u.%u.%u.%u:%u", remoteIp[0], remoteIp[1], remoteIp[2], remoteIp[3], remotePort); + if (client) { + ETHERNET_DEBUG_PRINTLN("Closing previous client"); + client.stop(); + } + client = newClient; + onClientConnected(); + } + + _isConnected = client.connected(); + +} diff --git a/src/helpers/ethernet/RAK13800/RAK13800EthernetInterface.h b/src/helpers/ethernet/RAK13800/RAK13800EthernetInterface.h new file mode 100644 index 00000000..34bb7587 --- /dev/null +++ b/src/helpers/ethernet/RAK13800/RAK13800EthernetInterface.h @@ -0,0 +1,27 @@ +#pragma once + +#include "../SerialEthernetInterface.h" +#include +#include + +class RAK13800EthernetInterface : public SerialEthernetInterface { + + bool _isConnected; + EthernetServer server; + EthernetClient client; + + public: + RAK13800EthernetInterface() : server(EthernetServer(ETHERNET_TCP_PORT)) { + _isConnected = false; + } + + bool begin(); + void loop() override; + + // BaseSerialInterface methods + bool isConnected() const override; + + int available() override; + int read() override; + size_t write(const uint8_t *buf, size_t size) override; +}; diff --git a/variants/rak4631/platformio.ini b/variants/rak4631/platformio.ini index 31b507b4..65c7ce54 100644 --- a/variants/rak4631/platformio.ini +++ b/variants/rak4631/platformio.ini @@ -190,13 +190,16 @@ build_flags = -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D ETHERNET_ENABLED=1 + -D ETHERNET_USE_RAK13800 + -D ETHERNET_CLASS=RAK13800EthernetInterface ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 ; -D ETHERNET_DEBUG_LOGGING=1 build_src_filter = ${rak4631.build_src_filter} +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> - + + + + + lib_deps = ${rak4631.lib_deps} densaugeo/base64 @ ~1.4.0 From 4ba459402cebdb4bc6836379e64d96b2a4c87f11 Mon Sep 17 00:00:00 2001 From: liamcottle Date: Tue, 28 Jul 2026 03:16:59 +1200 Subject: [PATCH 054/381] remove old rak ethernet interface --- src/helpers/nrf52/SerialEthernetInterface.cpp | 268 ------------------ src/helpers/nrf52/SerialEthernetInterface.h | 82 ------ 2 files changed, 350 deletions(-) delete mode 100644 src/helpers/nrf52/SerialEthernetInterface.cpp delete mode 100644 src/helpers/nrf52/SerialEthernetInterface.h diff --git a/src/helpers/nrf52/SerialEthernetInterface.cpp b/src/helpers/nrf52/SerialEthernetInterface.cpp deleted file mode 100644 index 36a998a4..00000000 --- a/src/helpers/nrf52/SerialEthernetInterface.cpp +++ /dev/null @@ -1,268 +0,0 @@ -#ifdef ETHERNET_ENABLED - -#include "SerialEthernetInterface.h" -#include "EthernetMac.h" -#include -#include - -#define PIN_SPI1_MISO (29) // (0 + 29) -#define PIN_SPI1_MOSI (30) // (0 + 30) -#define PIN_SPI1_SCK (3) // (0 + 3) - -SPIClass ETHERNET_SPI_PORT(NRF_SPIM1, PIN_SPI1_MISO, PIN_SPI1_SCK, PIN_SPI1_MOSI); - -#define PIN_ETHERNET_POWER_EN WB_IO2 // output, high to enable -#define PIN_ETHERNET_RESET 21 -#define PIN_ETHERNET_SS 26 - -#define RECV_STATE_IDLE 0 -#define RECV_STATE_HDR_FOUND 1 -#define RECV_STATE_LEN1_FOUND 2 -#define RECV_STATE_LEN2_FOUND 3 - -bool SerialEthernetInterface::begin() { - - ETHERNET_DEBUG_PRINTLN("Ethernet initializing"); - - // WB_IO2 (power enable) is already driven HIGH by early constructor - // in RAK4631Board.cpp to support POE boot. - // Skip hardware reset — the W5100S comes out of power-on reset cleanly, - // and toggling reset kills the PHY link which breaks POE power. -#ifdef PIN_ETHERNET_RESET - pinMode(PIN_ETHERNET_RESET, OUTPUT); - digitalWrite(PIN_ETHERNET_RESET, HIGH); -#endif - - uint8_t mac[6]; - generateEthernetMac(mac); - ETHERNET_DEBUG_PRINTLN( - "Ethernet MAC: %02X:%02X:%02X:%02X:%02X:%02X", - mac[0], - mac[1], - mac[2], - mac[3], - mac[4], - mac[5]); - ETHERNET_DEBUG_PRINTLN("Init"); - ETHERNET_SPI_PORT.begin(); - Ethernet.init(ETHERNET_SPI_PORT, PIN_ETHERNET_SS); - - // Use static IP if build flags are defined, otherwise DHCP - #if defined(ETHERNET_STATIC_IP) && defined(ETHERNET_STATIC_GATEWAY) && defined(ETHERNET_STATIC_SUBNET) && defined(ETHERNET_STATIC_DNS) - IPAddress ip(ETHERNET_STATIC_IP); - IPAddress gateway(ETHERNET_STATIC_GATEWAY); - IPAddress subnet(ETHERNET_STATIC_SUBNET); - IPAddress dns(ETHERNET_STATIC_DNS); - Ethernet.begin(mac, ip, dns, gateway, subnet); - #else - ETHERNET_DEBUG_PRINTLN("Begin"); - if (Ethernet.begin(mac) == 0) { - ETHERNET_DEBUG_PRINTLN("Begin failed."); - - // DHCP failed -- let's figure out why - if (Ethernet.hardwareStatus() == EthernetNoHardware) // Check for Ethernet hardware present. - { - ETHERNET_DEBUG_PRINTLN("Ethernet hardware not found."); - return false; - } - if (Ethernet.linkStatus() == LinkOFF) // No physical connection - { - ETHERNET_DEBUG_PRINTLN("Ethernet cable not connected."); - return false; - } - ETHERNET_DEBUG_PRINTLN("Ethernet: DHCP failed for unknown reason."); - return false; - } - #endif - ETHERNET_DEBUG_PRINTLN("Ethernet begin complete"); - ETHERNET_DEBUG_PRINT_IP("IP", Ethernet.localIP()); - ETHERNET_DEBUG_PRINT_IP("Subnet", Ethernet.subnetMask()); - ETHERNET_DEBUG_PRINT_IP("Gateway", Ethernet.gatewayIP()); - - server.begin(); // start listening for clients - ETHERNET_DEBUG_PRINTLN("Ethernet: listening on TCP port: %d", ETHERNET_TCP_PORT); - - return true; -} - -void SerialEthernetInterface::enable() { - if (_isEnabled) return; - - _isEnabled = true; - clearBuffers(); -} - -void SerialEthernetInterface::disable() { - _isEnabled = false; -} - -size_t SerialEthernetInterface::writeFrame(const uint8_t src[], size_t len) { - if (len > MAX_FRAME_SIZE) { - ETHERNET_DEBUG_PRINTLN("writeFrame(), frame too big, len=%d\n", len); - return 0; - } - - if (deviceConnected && len > 0) { - if (send_queue_len >= FRAME_QUEUE_SIZE) { - ETHERNET_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; -} - -bool SerialEthernetInterface::isWriteBusy() const { - return false; -} - -size_t SerialEthernetInterface::checkRecvFrame(uint8_t dest[]) { - // Use accept() (not available()) so we only see newly-accepted sockets. - // available() also returns existing connected sockets that have data, - // which would cause us to treat each inbound packet as a "new client" - // and stop() the underlying socket — disconnecting the companion. - auto newClient = server.accept(); - if (newClient) { - IPAddress new_ip = newClient.remoteIP(); - uint16_t new_port = newClient.remotePort(); - ETHERNET_DEBUG_PRINTLN( - "New client accepted %u.%u.%u.%u:%u", - new_ip[0], - new_ip[1], - new_ip[2], - new_ip[3], - new_port); - - deviceConnected = false; - if (client) { - ETHERNET_DEBUG_PRINTLN("Closing previous client"); - client.stop(); - } - _state = RECV_STATE_IDLE; - _frame_len = 0; - _rx_len = 0; - client = newClient; - ETHERNET_DEBUG_PRINTLN("Switched to new client"); - } - - if (client.connected()) { - if (!deviceConnected) { - ETHERNET_DEBUG_PRINTLN( - "Got connection %u.%u.%u.%u:%u", - client.remoteIP()[0], - client.remoteIP()[1], - client.remoteIP()[2], - client.remoteIP()[3], - client.remotePort()); - deviceConnected = true; - } - } else { - if (deviceConnected) { - deviceConnected = false; - ETHERNET_DEBUG_PRINTLN("Disconnected"); - } - } - - if (deviceConnected) { - if (send_queue_len > 0) { // first, check send queue - - _last_write = millis(); - int len = send_queue[0].len; - -#if ETHERNET_RAW_LINE - ETHERNET_DEBUG_PRINTLN("TX line len=%d", len); - client.write(send_queue[0].buf, len); - client.write("\r\n", 2); -#else - uint8_t pkt[3+len]; // use same header as serial interface so client can delimit frames - pkt[0] = '>'; - pkt[1] = (len & 0xFF); // LSB - pkt[2] = (len >> 8); // MSB - memcpy(&pkt[3], send_queue[0].buf, send_queue[0].len); - ETHERNET_DEBUG_PRINTLN("Sending frame len=%d", len); - #if ETHERNET_DEBUG_LOGGING && ARDUINO - ETHERNET_DEBUG_PRINTLN("TX frame len=%d", len); - #endif - client.write(pkt, 3 + len); -#endif - 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 { - while (client.available()) { - int c = client.read(); - if (c < 0) break; - -#if ETHERNET_RAW_LINE - if (c == '\r' || c == '\n') { - if (_rx_len == 0) { - continue; - } - uint16_t out_len = _rx_len; - if (out_len > MAX_FRAME_SIZE) { - out_len = MAX_FRAME_SIZE; - } - memcpy(dest, _rx_buf, out_len); - _rx_len = 0; - return out_len; - } - if (_rx_len < MAX_FRAME_SIZE) { - _rx_buf[_rx_len] = (uint8_t)c; - _rx_len++; - } -#else - switch (_state) { - case RECV_STATE_IDLE: - if (c == '<') { - _state = RECV_STATE_HDR_FOUND; - } - break; - case RECV_STATE_HDR_FOUND: - _frame_len = (uint8_t)c; - _state = RECV_STATE_LEN1_FOUND; - break; - case RECV_STATE_LEN1_FOUND: - _frame_len |= ((uint16_t)c) << 8; - _rx_len = 0; - _state = _frame_len > 0 ? RECV_STATE_LEN2_FOUND : RECV_STATE_IDLE; - break; - default: - if (_rx_len < MAX_FRAME_SIZE) { - _rx_buf[_rx_len] = (uint8_t)c; - } - _rx_len++; - if (_rx_len >= _frame_len) { - if (_frame_len > MAX_FRAME_SIZE) { - _frame_len = MAX_FRAME_SIZE; - } - #if ETHERNET_DEBUG_LOGGING && ARDUINO - ETHERNET_DEBUG_PRINTLN("RX frame len=%d", _frame_len); - #endif - memcpy(dest, _rx_buf, _frame_len); - _state = RECV_STATE_IDLE; - return _frame_len; - } - } -#endif - } - } - } - - return 0; -} - -bool SerialEthernetInterface::isConnected() const { - return deviceConnected; -} - -void SerialEthernetInterface::loop() { - Ethernet.maintain(); -} - -#endif // ETHERNET_ENABLED diff --git a/src/helpers/nrf52/SerialEthernetInterface.h b/src/helpers/nrf52/SerialEthernetInterface.h deleted file mode 100644 index b8b4e94b..00000000 --- a/src/helpers/nrf52/SerialEthernetInterface.h +++ /dev/null @@ -1,82 +0,0 @@ -#pragma once - -#ifdef ETHERNET_ENABLED - -#include "helpers/BaseSerialInterface.h" -#include -#include - -#ifndef ETHERNET_TCP_PORT - #define ETHERNET_TCP_PORT 5000 -#endif -// define ETHERNET_RAW_LINE=1 to use raw line-based CLI instead of framed packets - -class SerialEthernetInterface : public BaseSerialInterface { - bool deviceConnected; - bool _isEnabled; - unsigned long _last_write; - uint8_t _state; - uint16_t _frame_len; - uint16_t _rx_len; - uint8_t _rx_buf[MAX_FRAME_SIZE]; - - EthernetServer server; - EthernetClient client; - - 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; - _state = 0; - _frame_len = 0; - _rx_len = 0; - } - - protected: - - public: - SerialEthernetInterface() : server(EthernetServer(ETHERNET_TCP_PORT)) { - deviceConnected = false; - _isEnabled = false; - _last_write = 0; - send_queue_len = 0; - _state = 0; - _frame_len = 0; - _rx_len = 0; - } - bool begin(); - - // 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; - - void loop(); -}; - - -#if ETHERNET_DEBUG_LOGGING && ARDUINO - #include - #define ETHERNET_DEBUG_PRINT(F, ...) Serial.printf("ETH: " F, ##__VA_ARGS__) - #define ETHERNET_DEBUG_PRINTLN(F, ...) Serial.printf("ETH: " F "\n", ##__VA_ARGS__) - #define ETHERNET_DEBUG_PRINT_IP(name, ip) Serial.printf(name ": %u.%u.%u.%u" "\n", ip[0], ip[1], ip[2], ip[3]) -#else - #define ETHERNET_DEBUG_PRINT(...) {} - #define ETHERNET_DEBUG_PRINTLN(...) {} - #define ETHERNET_DEBUG_PRINT_IP(...) {} -#endif - -#endif // ETHERNET_ENABLED From 6e815d755fd6c81db218631eef3a9a046d1e4298 Mon Sep 17 00:00:00 2001 From: liamcottle Date: Tue, 28 Jul 2026 03:45:02 +1200 Subject: [PATCH 055/381] usb companion firmwares now require build flag to include usb interface --- variants/ebyte_eora_s3/platformio.ini | 1 + variants/gat562_30s_mesh_kit/platformio.ini | 1 + variants/gat562_mesh_tracker_pro/platformio.ini | 1 + variants/heltec_ct62/platformio.ini | 1 + variants/heltec_e213/platformio.ini | 1 + variants/heltec_mesh_solar/platformio.ini | 1 + variants/heltec_rc32/platformio.ini | 2 ++ variants/heltec_t096/platformio.ini | 1 + variants/heltec_t1/platformio.ini | 1 + variants/heltec_t114/platformio.ini | 2 ++ variants/heltec_t190/platformio.ini | 1 + variants/heltec_tower_v2/platformio.ini | 1 + variants/heltec_tracker/platformio.ini | 1 + variants/heltec_tracker_v2/platformio.ini | 1 + variants/heltec_v2/platformio.ini | 1 + variants/heltec_v3/platformio.ini | 2 ++ variants/heltec_v4/platformio.ini | 2 ++ variants/heltec_v4_r8/platformio.ini | 2 ++ variants/heltec_wireless_paper/platformio.ini | 1 + variants/ikoka_handheld_nrf/platformio.ini | 2 ++ variants/ikoka_nano_nrf/platformio.ini | 1 + variants/ikoka_stick_nrf/platformio.ini | 1 + variants/keepteen_lt1/platformio.ini | 1 + variants/lilygo_t3s3/platformio.ini | 1 + variants/lilygo_t3s3_sx1276/platformio.ini | 1 + variants/lilygo_tbeam_1w/platformio.ini | 1 + variants/lilygo_tdeck/platformio.ini | 1 + variants/lilygo_techo/platformio.ini | 1 + variants/lilygo_techo_card/platformio.ini | 1 + variants/lilygo_techo_lite/platformio.ini | 1 + variants/lilygo_teth_elite/platformio.ini | 1 + variants/lilygo_tlora_v2_1/platformio.ini | 1 + variants/m5stack_unit_c6l/platformio.ini | 1 + variants/mesh_pocket/platformio.ini | 1 + variants/meshadventurer/platformio.ini | 2 ++ variants/meshtiny/platformio.ini | 1 + variants/minewsemi_me25ls01/platformio.ini | 1 + variants/muziworks_r1_neo/platformio.ini | 1 + variants/nano_g2_ultra/platformio.ini | 1 + variants/nibble_screen_connect/platformio.ini | 1 + variants/nibble_zero_connect/platformio.ini | 1 + variants/promicro/platformio.ini | 1 + variants/rak11310/platformio.ini | 1 + variants/rak3112/platformio.ini | 1 + variants/rak3401/platformio.ini | 1 + variants/rak3x72/platformio.ini | 1 + variants/rak4631/platformio.ini | 1 + variants/rak_wismesh_tag/platformio.ini | 1 + variants/rpi_picow/platformio.ini | 1 + variants/sensecap_solar/platformio.ini | 1 + variants/station_g2/platformio.ini | 1 + variants/station_g3_esp32/platformio.ini | 1 + variants/t1000-e/platformio.ini | 1 + variants/thinknode_m1/platformio.ini | 1 + variants/thinknode_m2/platformio.ini | 1 + variants/thinknode_m3/platformio.ini | 1 + variants/thinknode_m5/platformio.ini | 1 + variants/thinknode_m6/platformio.ini | 1 + variants/thinknode_m7/platformio.ini | 1 + variants/thinknode_m9/platformio.ini | 1 + variants/tiny_relay/platformio.ini | 1 + variants/waveshare_rp2040_lora/platformio.ini | 1 + variants/wio-e5-dev/platformio.ini | 1 + variants/wio-e5-mini/platformio.ini | 1 + variants/wio-tracker-l1/platformio.ini | 1 + variants/xiao_c3/platformio.ini | 1 + variants/xiao_nrf52/platformio.ini | 1 + variants/xiao_rp2040/platformio.ini | 1 + variants/xiao_s3/platformio.ini | 1 + variants/xiao_s3_wio/platformio.ini | 1 + 70 files changed, 77 insertions(+) diff --git a/variants/ebyte_eora_s3/platformio.ini b/variants/ebyte_eora_s3/platformio.ini index 15fe761b..1ab3d3fb 100644 --- a/variants/ebyte_eora_s3/platformio.ini +++ b/variants/ebyte_eora_s3/platformio.ini @@ -102,6 +102,7 @@ build_flags = -D DISPLAY_CLASS=SSD1306Display -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 build_src_filter = ${Ebyte_EoRa-S3.build_src_filter} diff --git a/variants/gat562_30s_mesh_kit/platformio.ini b/variants/gat562_30s_mesh_kit/platformio.ini index 2baac256..89276a49 100644 --- a/variants/gat562_30s_mesh_kit/platformio.ini +++ b/variants/gat562_30s_mesh_kit/platformio.ini @@ -75,6 +75,7 @@ build_flags = -D DISPLAY_CLASS=SSD1306Display -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 build_src_filter = ${GAT562_30S_Mesh_Kit.build_src_filter} diff --git a/variants/gat562_mesh_tracker_pro/platformio.ini b/variants/gat562_mesh_tracker_pro/platformio.ini index af153b8f..142cfe4b 100644 --- a/variants/gat562_mesh_tracker_pro/platformio.ini +++ b/variants/gat562_mesh_tracker_pro/platformio.ini @@ -71,6 +71,7 @@ build_flags = -D DISPLAY_CLASS=SSD1306Display -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 build_src_filter = ${GAT562_Mesh_Tracker_Pro.build_src_filter} diff --git a/variants/heltec_ct62/platformio.ini b/variants/heltec_ct62/platformio.ini index 0179d965..401a30d2 100644 --- a/variants/heltec_ct62/platformio.ini +++ b/variants/heltec_ct62/platformio.ini @@ -101,6 +101,7 @@ build_flags = -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_USB_INTERFACE ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${Heltec_ct62.build_src_filter} diff --git a/variants/heltec_e213/platformio.ini b/variants/heltec_e213/platformio.ini index 123edd91..02193819 100644 --- a/variants/heltec_e213/platformio.ini +++ b/variants/heltec_e213/platformio.ini @@ -73,6 +73,7 @@ build_flags = -D DISPLAY_CLASS=E213Display -D AUTO_OFF_MILLIS=0 -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_USB_INTERFACE build_src_filter = ${Heltec_E213_base.build_src_filter} + + diff --git a/variants/heltec_mesh_solar/platformio.ini b/variants/heltec_mesh_solar/platformio.ini index fb5cd515..17f8ba21 100644 --- a/variants/heltec_mesh_solar/platformio.ini +++ b/variants/heltec_mesh_solar/platformio.ini @@ -87,6 +87,7 @@ build_flags = ${Heltec_mesh_solar.build_flags} -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE ; -D BLE_PIN_CODE=123456 ; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 diff --git a/variants/heltec_rc32/platformio.ini b/variants/heltec_rc32/platformio.ini index 6361f61d..354004f0 100644 --- a/variants/heltec_rc32/platformio.ini +++ b/variants/heltec_rc32/platformio.ini @@ -131,6 +131,7 @@ build_flags = -D DISPLAY_CLASS=NullDisplayDriver -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE build_src_filter = ${Heltec_RC32.build_src_filter} + + @@ -275,6 +276,7 @@ build_flags = -D UI_HAS_ROTARY_INPUT -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE build_src_filter = ${Heltec_RC32_with_display.build_src_filter} + + diff --git a/variants/heltec_t096/platformio.ini b/variants/heltec_t096/platformio.ini index 0a062f00..02e88328 100644 --- a/variants/heltec_t096/platformio.ini +++ b/variants/heltec_t096/platformio.ini @@ -152,6 +152,7 @@ build_flags = -I examples/companion_radio/ui-new -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE ; -D BLE_PIN_CODE=123456 ; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 diff --git a/variants/heltec_t1/platformio.ini b/variants/heltec_t1/platformio.ini index eaa8af37..28ed67ed 100644 --- a/variants/heltec_t1/platformio.ini +++ b/variants/heltec_t1/platformio.ini @@ -90,6 +90,7 @@ build_flags = -I examples/companion_radio/ui-new -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${Heltec_t1.build_src_filter} diff --git a/variants/heltec_t114/platformio.ini b/variants/heltec_t114/platformio.ini index 48dfe078..48fb4b0f 100644 --- a/variants/heltec_t114/platformio.ini +++ b/variants/heltec_t114/platformio.ini @@ -127,6 +127,7 @@ build_flags = -D DISPLAY_CLASS=NullDisplayDriver -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE build_src_filter = ${Heltec_t114.build_src_filter} + + @@ -238,6 +239,7 @@ build_flags = -I examples/companion_radio/ui-new -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE ; -D BLE_PIN_CODE=123456 ; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 diff --git a/variants/heltec_t190/platformio.ini b/variants/heltec_t190/platformio.ini index 411fee85..28355393 100644 --- a/variants/heltec_t190/platformio.ini +++ b/variants/heltec_t190/platformio.ini @@ -74,6 +74,7 @@ build_flags = -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_USB_INTERFACE build_src_filter = ${Heltec_T190_base.build_src_filter} + +<../examples/companion_radio/*.cpp> diff --git a/variants/heltec_tower_v2/platformio.ini b/variants/heltec_tower_v2/platformio.ini index 9c703ae1..207e0a50 100644 --- a/variants/heltec_tower_v2/platformio.ini +++ b/variants/heltec_tower_v2/platformio.ini @@ -87,6 +87,7 @@ build_flags = -D DISPLAY_CLASS=NullDisplayDriver -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE ; -D BLE_PIN_CODE=123456 ; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 diff --git a/variants/heltec_tracker/platformio.ini b/variants/heltec_tracker/platformio.ini index 07d2e987..75d1cadf 100644 --- a/variants/heltec_tracker/platformio.ini +++ b/variants/heltec_tracker/platformio.ini @@ -59,6 +59,7 @@ build_flags = -D DISPLAY_CLASS=ST7735Display -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE ; -D BLE_PIN_CODE=123456 ; HWT will use display for pin ; -D OFFLINE_QUEUE_SIZE=256 ; -D BLE_DEBUG_LOGGING=1 diff --git a/variants/heltec_tracker_v2/platformio.ini b/variants/heltec_tracker_v2/platformio.ini index f1fe9dd0..d040b72f 100644 --- a/variants/heltec_tracker_v2/platformio.ini +++ b/variants/heltec_tracker_v2/platformio.ini @@ -140,6 +140,7 @@ build_flags = -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D DISPLAY_CLASS=ST7735Display + -D ENABLE_USB_INTERFACE ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 build_src_filter = ${Heltec_tracker_v2.build_src_filter} diff --git a/variants/heltec_v2/platformio.ini b/variants/heltec_v2/platformio.ini index ba4f8694..78561a14 100644 --- a/variants/heltec_v2/platformio.ini +++ b/variants/heltec_v2/platformio.ini @@ -137,6 +137,7 @@ build_flags = -D DISPLAY_CLASS=SSD1306Display -D MAX_CONTACTS=160 -D MAX_GROUP_CHANNELS=8 + -D ENABLE_USB_INTERFACE ; 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} diff --git a/variants/heltec_v3/platformio.ini b/variants/heltec_v3/platformio.ini index a70a93a5..65e636eb 100644 --- a/variants/heltec_v3/platformio.ini +++ b/variants/heltec_v3/platformio.ini @@ -144,6 +144,7 @@ build_flags = -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D DISPLAY_CLASS=SSD1306Display + -D ENABLE_USB_INTERFACE ; 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} @@ -326,6 +327,7 @@ build_flags = ${Heltec_lora32_v3.build_flags} -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE ; 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} diff --git a/variants/heltec_v4/platformio.ini b/variants/heltec_v4/platformio.ini index cb76beb3..d718c006 100644 --- a/variants/heltec_v4/platformio.ini +++ b/variants/heltec_v4/platformio.ini @@ -187,6 +187,7 @@ build_flags = -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D DISPLAY_CLASS=SSD1306Display + -D ENABLE_USB_INTERFACE ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 build_src_filter = ${heltec_v4_oled.build_src_filter} @@ -351,6 +352,7 @@ build_flags = -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D DISPLAY_CLASS=ST7789LCDDisplay + -D ENABLE_USB_INTERFACE ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 build_src_filter = ${heltec_v4_tft.build_src_filter} diff --git a/variants/heltec_v4_r8/platformio.ini b/variants/heltec_v4_r8/platformio.ini index 4057d6f1..f523ebf9 100644 --- a/variants/heltec_v4_r8/platformio.ini +++ b/variants/heltec_v4_r8/platformio.ini @@ -138,6 +138,7 @@ build_flags = -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D DISPLAY_CLASS=SSD1306Display + -D ENABLE_USB_INTERFACE build_src_filter = ${heltec_v4_r8_oled.build_src_filter} + + @@ -262,6 +263,7 @@ build_flags = -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D DISPLAY_CLASS=ST7789LCDDisplay + -D ENABLE_USB_INTERFACE build_src_filter = ${heltec_v4_r8_tft.build_src_filter} + + diff --git a/variants/heltec_wireless_paper/platformio.ini b/variants/heltec_wireless_paper/platformio.ini index 48723d16..55ed62b3 100644 --- a/variants/heltec_wireless_paper/platformio.ini +++ b/variants/heltec_wireless_paper/platformio.ini @@ -73,6 +73,7 @@ build_flags = -D MAX_GROUP_CHANNELS=40 -D DISPLAY_CLASS=E213Display -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_USB_INTERFACE build_src_filter = ${Heltec_Wireless_Paper_base.build_src_filter} + + diff --git a/variants/ikoka_handheld_nrf/platformio.ini b/variants/ikoka_handheld_nrf/platformio.ini index 51b602e4..1c6f17c2 100644 --- a/variants/ikoka_handheld_nrf/platformio.ini +++ b/variants/ikoka_handheld_nrf/platformio.ini @@ -74,6 +74,7 @@ extends = ikoka_handheld_nrf board_build.ldscript = boards/nrf52840_s140_v7_extrafs.ld build_flags = ${ikoka_handheld_nrf_ssd1306_companion.build_flags} -D LORA_TX_POWER=20 + -D ENABLE_USB_INTERFACE build_src_filter = ${ikoka_handheld_nrf_ssd1306_companion.build_src_filter} [env:ikoka_handheld_nrf_e22_30dbm_096_rotated_companion_radio_usb] @@ -82,6 +83,7 @@ board_build.ldscript = boards/nrf52840_s140_v7_extrafs.ld build_flags = ${ikoka_handheld_nrf_ssd1306_companion.build_flags} -D LORA_TX_POWER=20 -D DISPLAY_ROTATION=2 + -D ENABLE_USB_INTERFACE build_src_filter = ${ikoka_handheld_nrf_ssd1306_companion.build_src_filter} [env:ikoka_handheld_nrf_e22_30dbm_repeater] diff --git a/variants/ikoka_nano_nrf/platformio.ini b/variants/ikoka_nano_nrf/platformio.ini index 7880ea4a..87c6240e 100644 --- a/variants/ikoka_nano_nrf/platformio.ini +++ b/variants/ikoka_nano_nrf/platformio.ini @@ -105,6 +105,7 @@ build_flags = -D MAX_GROUP_CHANNELS=40 -I examples/companion_radio/ui-new -D QSPIFLASH=1 + -D ENABLE_USB_INTERFACE ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${ikoka_nano_nrf.build_src_filter} diff --git a/variants/ikoka_stick_nrf/platformio.ini b/variants/ikoka_stick_nrf/platformio.ini index 06e39e84..c8184fc4 100644 --- a/variants/ikoka_stick_nrf/platformio.ini +++ b/variants/ikoka_stick_nrf/platformio.ini @@ -111,6 +111,7 @@ build_flags = -D MAX_GROUP_CHANNELS=40 -I examples/companion_radio/ui-new -D QSPIFLASH=1 + -D ENABLE_USB_INTERFACE ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${ikoka_stick_nrf.build_src_filter} diff --git a/variants/keepteen_lt1/platformio.ini b/variants/keepteen_lt1/platformio.ini index 27cf809e..11dc214b 100644 --- a/variants/keepteen_lt1/platformio.ini +++ b/variants/keepteen_lt1/platformio.ini @@ -66,6 +66,7 @@ build_flags = ${KeepteenLT1.build_flags} -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D DISPLAY_CLASS=SSD1306Display + -D ENABLE_USB_INTERFACE ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 build_src_filter = ${KeepteenLT1.build_src_filter} diff --git a/variants/lilygo_t3s3/platformio.ini b/variants/lilygo_t3s3/platformio.ini index 54990117..966235c6 100644 --- a/variants/lilygo_t3s3/platformio.ini +++ b/variants/lilygo_t3s3/platformio.ini @@ -140,6 +140,7 @@ build_flags = -D DISPLAY_CLASS=SSD1306Display -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE ; 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} diff --git a/variants/lilygo_t3s3_sx1276/platformio.ini b/variants/lilygo_t3s3_sx1276/platformio.ini index e579e91c..c6497dcb 100644 --- a/variants/lilygo_t3s3_sx1276/platformio.ini +++ b/variants/lilygo_t3s3_sx1276/platformio.ini @@ -138,6 +138,7 @@ build_flags = -D DISPLAY_CLASS=SSD1306Display -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE build_src_filter = ${LilyGo_T3S3_sx1276.build_src_filter} + + diff --git a/variants/lilygo_tbeam_1w/platformio.ini b/variants/lilygo_tbeam_1w/platformio.ini index c7a59552..0f604fac 100644 --- a/variants/lilygo_tbeam_1w/platformio.ini +++ b/variants/lilygo_tbeam_1w/platformio.ini @@ -114,6 +114,7 @@ build_flags = -D MAX_GROUP_CHANNELS=40 -D PERSISTANT_GPS=1 -D ENV_SKIP_GPS_DETECT=1 + -D ENABLE_USB_INTERFACE ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${LilyGo_TBeam_1W.build_src_filter} diff --git a/variants/lilygo_tdeck/platformio.ini b/variants/lilygo_tdeck/platformio.ini index 745d8ff5..00571db9 100644 --- a/variants/lilygo_tdeck/platformio.ini +++ b/variants/lilygo_tdeck/platformio.ini @@ -71,6 +71,7 @@ build_flags = -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_USB_INTERFACE build_src_filter = ${LilyGo_TDeck.build_src_filter} + + diff --git a/variants/lilygo_techo/platformio.ini b/variants/lilygo_techo/platformio.ini index 5df77f95..81da2e48 100644 --- a/variants/lilygo_techo/platformio.ini +++ b/variants/lilygo_techo/platformio.ini @@ -120,6 +120,7 @@ build_flags = -D UI_SENSORS_PAGE=1 -D AUTO_SHUTDOWN_MILLIVOLTS=3300 -D QSPIFLASH=1 + -D ENABLE_USB_INTERFACE build_src_filter = ${LilyGo_T-Echo.build_src_filter} +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> diff --git a/variants/lilygo_techo_card/platformio.ini b/variants/lilygo_techo_card/platformio.ini index c7bb7378..4ebf43da 100644 --- a/variants/lilygo_techo_card/platformio.ini +++ b/variants/lilygo_techo_card/platformio.ini @@ -110,6 +110,7 @@ build_flags = ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 -D AUTO_SHUTDOWN_MILLIVOLTS=3300 + -D ENABLE_USB_INTERFACE build_src_filter = ${LilyGo_T-Echo_Card.build_src_filter} +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-tiny/*.cpp> diff --git a/variants/lilygo_techo_lite/platformio.ini b/variants/lilygo_techo_lite/platformio.ini index a9b3d124..9ec73d59 100644 --- a/variants/lilygo_techo_lite/platformio.ini +++ b/variants/lilygo_techo_lite/platformio.ini @@ -174,6 +174,7 @@ build_flags = -D MAX_GROUP_CHANNELS=40 -D UI_RECENT_LIST_SIZE=9 -D AUTO_SHUTDOWN_MILLIVOLTS=3300 + -D ENABLE_USB_INTERFACE ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${nrf52_base.build_src_filter} diff --git a/variants/lilygo_teth_elite/platformio.ini b/variants/lilygo_teth_elite/platformio.ini index 97728f8b..ee1b9879 100644 --- a/variants/lilygo_teth_elite/platformio.ini +++ b/variants/lilygo_teth_elite/platformio.ini @@ -72,6 +72,7 @@ build_flags = -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_USB_INTERFACE ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${LilyGo_TETH_Elite_sx1262.build_src_filter} diff --git a/variants/lilygo_tlora_v2_1/platformio.ini b/variants/lilygo_tlora_v2_1/platformio.ini index 36731668..1aea74d2 100644 --- a/variants/lilygo_tlora_v2_1/platformio.ini +++ b/variants/lilygo_tlora_v2_1/platformio.ini @@ -77,6 +77,7 @@ build_flags = -I examples/companion_radio/ui-new -D MAX_CONTACTS=160 -D MAX_GROUP_CHANNELS=8 + -D ENABLE_USB_INTERFACE ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 build_src_filter = ${LilyGo_TLora_V2_1_1_6.build_src_filter} diff --git a/variants/m5stack_unit_c6l/platformio.ini b/variants/m5stack_unit_c6l/platformio.ini index 94083eb4..190add04 100644 --- a/variants/m5stack_unit_c6l/platformio.ini +++ b/variants/m5stack_unit_c6l/platformio.ini @@ -97,6 +97,7 @@ build_flags = ${M5Stack_Unit_C6L.build_flags} -D OFFLINE_QUEUE_SIZE=256 -D ARDUINO_USB_CDC_ON_BOOT=1 -D ARDUINO_USB_MODE=1 + -D ENABLE_USB_INTERFACE build_src_filter = ${M5Stack_Unit_C6L.build_src_filter} + - diff --git a/variants/mesh_pocket/platformio.ini b/variants/mesh_pocket/platformio.ini index 0d2a74ad..a6f823db 100644 --- a/variants/mesh_pocket/platformio.ini +++ b/variants/mesh_pocket/platformio.ini @@ -96,6 +96,7 @@ build_flags = -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D AUTO_OFF_MILLIS=0 + -D ENABLE_USB_INTERFACE ; -D BLE_PIN_CODE=123456 ; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 diff --git a/variants/meshadventurer/platformio.ini b/variants/meshadventurer/platformio.ini index f85be238..149d324f 100644 --- a/variants/meshadventurer/platformio.ini +++ b/variants/meshadventurer/platformio.ini @@ -186,6 +186,7 @@ build_flags = -D MAX_CONTACTS=160 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=128 + -D ENABLE_USB_INTERFACE ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 lib_deps = @@ -266,6 +267,7 @@ build_flags = -D MAX_CONTACTS=160 -D OFFLINE_QUEUE_SIZE=128 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 lib_deps = diff --git a/variants/meshtiny/platformio.ini b/variants/meshtiny/platformio.ini index c5439c88..c0a3c5f9 100644 --- a/variants/meshtiny/platformio.ini +++ b/variants/meshtiny/platformio.ini @@ -36,6 +36,7 @@ build_flags = -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_USB_INTERFACE ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${Meshtiny.build_src_filter} diff --git a/variants/minewsemi_me25ls01/platformio.ini b/variants/minewsemi_me25ls01/platformio.ini index ac81fa16..b1d3a161 100644 --- a/variants/minewsemi_me25ls01/platformio.ini +++ b/variants/minewsemi_me25ls01/platformio.ini @@ -144,6 +144,7 @@ build_flags = ${me25ls01.build_flags} -D RX_BOOSTED_GAIN=true -D RF_SWITCH_TABLE -D DISPLAY_CLASS=NullDisplayDriver + -D ENABLE_USB_INTERFACE build_src_filter = ${me25ls01.build_src_filter} + + diff --git a/variants/muziworks_r1_neo/platformio.ini b/variants/muziworks_r1_neo/platformio.ini index 3dbecf1e..cf02b9e2 100644 --- a/variants/muziworks_r1_neo/platformio.ini +++ b/variants/muziworks_r1_neo/platformio.ini @@ -66,6 +66,7 @@ build_flags = -I examples/companion_radio/ui-orig -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 build_src_filter = ${R1Neo.build_src_filter} diff --git a/variants/nano_g2_ultra/platformio.ini b/variants/nano_g2_ultra/platformio.ini index 3cdc29ff..b817b3e9 100644 --- a/variants/nano_g2_ultra/platformio.ini +++ b/variants/nano_g2_ultra/platformio.ini @@ -99,6 +99,7 @@ build_flags = -D OFFLINE_QUEUE_SIZE=256 -D DISPLAY_CLASS=SH1106Display -D PIN_BUZZER=4 + -D ENABLE_USB_INTERFACE ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${Nano_G2_Ultra.build_src_filter} diff --git a/variants/nibble_screen_connect/platformio.ini b/variants/nibble_screen_connect/platformio.ini index 6a2f3dec..112181df 100644 --- a/variants/nibble_screen_connect/platformio.ini +++ b/variants/nibble_screen_connect/platformio.ini @@ -107,6 +107,7 @@ build_flags = -D DISPLAY_CLASS=SSD1306Display -D MAX_CONTACTS=300 -D MAX_GROUP_CHANNELS=8 + -D ENABLE_USB_INTERFACE build_src_filter = ${nibble_screen_connect_base.build_src_filter} + + diff --git a/variants/nibble_zero_connect/platformio.ini b/variants/nibble_zero_connect/platformio.ini index 83495cd8..1161743e 100644 --- a/variants/nibble_zero_connect/platformio.ini +++ b/variants/nibble_zero_connect/platformio.ini @@ -104,6 +104,7 @@ build_flags = -D DISPLAY_CLASS=SSD1306Display -D MAX_CONTACTS=300 -D MAX_GROUP_CHANNELS=8 + -D ENABLE_USB_INTERFACE build_src_filter = ${nibble_zero_connect_base.build_src_filter} + + diff --git a/variants/promicro/platformio.ini b/variants/promicro/platformio.ini index 5415e158..dea4ccfa 100644 --- a/variants/promicro/platformio.ini +++ b/variants/promicro/platformio.ini @@ -119,6 +119,7 @@ build_flags = ${Promicro.build_flags} -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D DISPLAY_CLASS=SSD1306Display + -D ENABLE_USB_INTERFACE ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 build_src_filter = ${Promicro.build_src_filter} diff --git a/variants/rak11310/platformio.ini b/variants/rak11310/platformio.ini index ab820cf6..c8526317 100644 --- a/variants/rak11310/platformio.ini +++ b/variants/rak11310/platformio.ini @@ -85,6 +85,7 @@ extends = rak11310 build_flags = ${rak11310.build_flags} -D MAX_CONTACTS=100 -D MAX_GROUP_CHANNELS=8 + -D ENABLE_USB_INTERFACE ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 build_src_filter = ${rak11310.build_src_filter} diff --git a/variants/rak3112/platformio.ini b/variants/rak3112/platformio.ini index 9cd32c4b..8bd3c597 100644 --- a/variants/rak3112/platformio.ini +++ b/variants/rak3112/platformio.ini @@ -136,6 +136,7 @@ build_flags = -I examples/companion_radio/ui-orig -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 build_src_filter = ${rak3112.build_src_filter} diff --git a/variants/rak3401/platformio.ini b/variants/rak3401/platformio.ini index 20a8a548..48e71922 100644 --- a/variants/rak3401/platformio.ini +++ b/variants/rak3401/platformio.ini @@ -67,6 +67,7 @@ build_flags = -D DISPLAY_CLASS=SSD1306Display -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 build_src_filter = ${rak3401.build_src_filter} diff --git a/variants/rak3x72/platformio.ini b/variants/rak3x72/platformio.ini index f9667860..c23019c8 100644 --- a/variants/rak3x72/platformio.ini +++ b/variants/rak3x72/platformio.ini @@ -37,6 +37,7 @@ build_flags = ${rak3x72.build_flags} ; -D FORMAT_FS=true -D MAX_CONTACTS=100 -D MAX_GROUP_CHANNELS=8 + -D ENABLE_USB_INTERFACE build_src_filter = ${rak3x72.build_src_filter} +<../examples/companion_radio/*.cpp> lib_deps = ${rak3x72.lib_deps} diff --git a/variants/rak4631/platformio.ini b/variants/rak4631/platformio.ini index 65c7ce54..1a610956 100644 --- a/variants/rak4631/platformio.ini +++ b/variants/rak4631/platformio.ini @@ -165,6 +165,7 @@ build_flags = -D DISPLAY_CLASS=SSD1306Display -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 build_src_filter = ${rak4631.build_src_filter} diff --git a/variants/rak_wismesh_tag/platformio.ini b/variants/rak_wismesh_tag/platformio.ini index e9cddb74..d6140187 100644 --- a/variants/rak_wismesh_tag/platformio.ini +++ b/variants/rak_wismesh_tag/platformio.ini @@ -71,6 +71,7 @@ build_flags = -I examples/companion_radio/ui-orig -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 build_src_filter = ${rak_wismesh_tag.build_src_filter} diff --git a/variants/rpi_picow/platformio.ini b/variants/rpi_picow/platformio.ini index 66c7b9f8..0fe8c436 100644 --- a/variants/rpi_picow/platformio.ini +++ b/variants/rpi_picow/platformio.ini @@ -58,6 +58,7 @@ extends = rpi_picow build_flags = ${rpi_picow.build_flags} -D MAX_CONTACTS=100 -D MAX_GROUP_CHANNELS=8 + -D ENABLE_USB_INTERFACE ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 build_src_filter = ${rpi_picow.build_src_filter} diff --git a/variants/sensecap_solar/platformio.ini b/variants/sensecap_solar/platformio.ini index effef38c..6e0eadbc 100644 --- a/variants/sensecap_solar/platformio.ini +++ b/variants/sensecap_solar/platformio.ini @@ -92,6 +92,7 @@ build_flags = ${SenseCap_Solar.build_flags} -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${SenseCap_Solar.build_src_filter} diff --git a/variants/station_g2/platformio.ini b/variants/station_g2/platformio.ini index 508ffe4b..e463aee0 100644 --- a/variants/station_g2/platformio.ini +++ b/variants/station_g2/platformio.ini @@ -188,6 +188,7 @@ build_flags = -I examples/companion_radio/ui-new -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 build_src_filter = ${Station_G2.build_src_filter} diff --git a/variants/station_g3_esp32/platformio.ini b/variants/station_g3_esp32/platformio.ini index b29388ef..96eca1fc 100644 --- a/variants/station_g3_esp32/platformio.ini +++ b/variants/station_g3_esp32/platformio.ini @@ -103,6 +103,7 @@ build_flags = -I examples/companion_radio/ui-new -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 build_src_filter = ${Station_G3_ESP32.build_src_filter} diff --git a/variants/t1000-e/platformio.ini b/variants/t1000-e/platformio.ini index 6f32e54d..8456dc91 100644 --- a/variants/t1000-e/platformio.ini +++ b/variants/t1000-e/platformio.ini @@ -82,6 +82,7 @@ build_flags = ${t1000-e.build_flags} -D DISPLAY_CLASS=NullDisplayDriver -D PIN_BUZZER=25 -D PIN_BUZZER_EN=37 ; P1/5 - required for T1000-E + -D ENABLE_USB_INTERFACE build_src_filter = ${t1000-e.build_src_filter} + + diff --git a/variants/thinknode_m1/platformio.ini b/variants/thinknode_m1/platformio.ini index 617f9240..89c48403 100644 --- a/variants/thinknode_m1/platformio.ini +++ b/variants/thinknode_m1/platformio.ini @@ -117,6 +117,7 @@ build_flags = -D OFFLINE_QUEUE_SIZE=256 -D PIN_BUZZER=6 -D AUTO_SHUTDOWN_MILLIVOLTS=3300 + -D ENABLE_USB_INTERFACE build_src_filter = ${ThinkNode_M1.build_src_filter} + + diff --git a/variants/thinknode_m2/platformio.ini b/variants/thinknode_m2/platformio.ini index aae83324..79dac6ab 100644 --- a/variants/thinknode_m2/platformio.ini +++ b/variants/thinknode_m2/platformio.ini @@ -159,6 +159,7 @@ build_flags = -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_USB_INTERFACE build_src_filter = ${ThinkNode_M2.build_src_filter} + + diff --git a/variants/thinknode_m3/platformio.ini b/variants/thinknode_m3/platformio.ini index f80a6161..74382b36 100644 --- a/variants/thinknode_m3/platformio.ini +++ b/variants/thinknode_m3/platformio.ini @@ -83,6 +83,7 @@ build_flags = ${ThinkNode_M3.build_flags} -D DISPLAY_CLASS=NullDisplayDriver -D PIN_BUZZER=23 -D PIN_BUZZER_EN=36 + -D ENABLE_USB_INTERFACE build_src_filter = ${ThinkNode_M3.build_src_filter} + + diff --git a/variants/thinknode_m5/platformio.ini b/variants/thinknode_m5/platformio.ini index 8572d1eb..eda21bf0 100644 --- a/variants/thinknode_m5/platformio.ini +++ b/variants/thinknode_m5/platformio.ini @@ -173,6 +173,7 @@ build_flags = -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_USB_INTERFACE build_src_filter = ${ThinkNode_M5.build_src_filter} + + diff --git a/variants/thinknode_m6/platformio.ini b/variants/thinknode_m6/platformio.ini index 187a8819..3606d6a8 100644 --- a/variants/thinknode_m6/platformio.ini +++ b/variants/thinknode_m6/platformio.ini @@ -110,6 +110,7 @@ build_flags = -D QSPIFLASH=1 -D OFFLINE_QUEUE_SIZE=256 -D AUTO_SHUTDOWN_MILLIVOLTS=3300 + -D ENABLE_USB_INTERFACE build_src_filter = ${ThinkNode_M6.build_src_filter} + + diff --git a/variants/thinknode_m7/platformio.ini b/variants/thinknode_m7/platformio.ini index 2ff6fc0a..eb745b6d 100644 --- a/variants/thinknode_m7/platformio.ini +++ b/variants/thinknode_m7/platformio.ini @@ -120,6 +120,7 @@ build_flags = -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_USB_INTERFACE build_src_filter = ${ThinkNode_M7.build_src_filter} + + diff --git a/variants/thinknode_m9/platformio.ini b/variants/thinknode_m9/platformio.ini index a7171726..09b1391d 100755 --- a/variants/thinknode_m9/platformio.ini +++ b/variants/thinknode_m9/platformio.ini @@ -120,6 +120,7 @@ build_flags = -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_USB_INTERFACE build_src_filter = ${ThinkNode_M9.build_src_filter} + + diff --git a/variants/tiny_relay/platformio.ini b/variants/tiny_relay/platformio.ini index 82cb251f..13c2ec1c 100644 --- a/variants/tiny_relay/platformio.ini +++ b/variants/tiny_relay/platformio.ini @@ -44,6 +44,7 @@ build_flags = ${Tiny_Relay.build_flags} -D MAX_CONTACTS=100 -D MAX_GROUP_CHANNELS=8 -D MAX_LORA_TX_POWER=22 + -D ENABLE_USB_INTERFACE build_src_filter = ${Tiny_Relay.build_src_filter} +<../examples/companion_radio/*.cpp> lib_deps = ${Tiny_Relay.lib_deps} diff --git a/variants/waveshare_rp2040_lora/platformio.ini b/variants/waveshare_rp2040_lora/platformio.ini index 7dfe1401..db1ec603 100644 --- a/variants/waveshare_rp2040_lora/platformio.ini +++ b/variants/waveshare_rp2040_lora/platformio.ini @@ -84,6 +84,7 @@ extends = waveshare_rp2040_lora build_flags = ${waveshare_rp2040_lora.build_flags} -D MAX_CONTACTS=100 -D MAX_GROUP_CHANNELS=8 + -D ENABLE_USB_INTERFACE ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 build_src_filter = ${waveshare_rp2040_lora.build_src_filter} diff --git a/variants/wio-e5-dev/platformio.ini b/variants/wio-e5-dev/platformio.ini index 22bdc3c8..82b3781e 100644 --- a/variants/wio-e5-dev/platformio.ini +++ b/variants/wio-e5-dev/platformio.ini @@ -46,6 +46,7 @@ build_flags = ${lora_e5.build_flags} -D LORA_TX_POWER=22 -D MAX_CONTACTS=100 -D MAX_GROUP_CHANNELS=8 + -D ENABLE_USB_INTERFACE build_src_filter = ${lora_e5.build_src_filter} +<../examples/companion_radio/*.cpp> lib_deps = ${lora_e5.lib_deps} diff --git a/variants/wio-e5-mini/platformio.ini b/variants/wio-e5-mini/platformio.ini index 7cf26198..021c7db2 100644 --- a/variants/wio-e5-mini/platformio.ini +++ b/variants/wio-e5-mini/platformio.ini @@ -44,6 +44,7 @@ build_flags = ${lora_e5_mini.build_flags} -D MAX_CONTACTS=100 -D MAX_GROUP_CHANNELS=8 -D DISPLAY_CLASS=NullDisplayDriver + -D ENABLE_USB_INTERFACE build_src_filter = ${lora_e5_mini.build_src_filter} + +<../examples/companion_radio/*.cpp> diff --git a/variants/wio-tracker-l1/platformio.ini b/variants/wio-tracker-l1/platformio.ini index 7bb175bb..fc958ea2 100644 --- a/variants/wio-tracker-l1/platformio.ini +++ b/variants/wio-tracker-l1/platformio.ini @@ -68,6 +68,7 @@ build_flags = ${WioTrackerL1.build_flags} -D OFFLINE_QUEUE_SIZE=256 -D PIN_BUZZER=12 -D QSPIFLASH=1 + -D ENABLE_USB_INTERFACE ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 build_src_filter = ${WioTrackerL1.build_src_filter} diff --git a/variants/xiao_c3/platformio.ini b/variants/xiao_c3/platformio.ini index c0e8458d..587c5c27 100644 --- a/variants/xiao_c3/platformio.ini +++ b/variants/xiao_c3/platformio.ini @@ -100,6 +100,7 @@ build_flags = -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_USB_INTERFACE ; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 diff --git a/variants/xiao_nrf52/platformio.ini b/variants/xiao_nrf52/platformio.ini index a0854336..4551a233 100644 --- a/variants/xiao_nrf52/platformio.ini +++ b/variants/xiao_nrf52/platformio.ini @@ -74,6 +74,7 @@ build_flags = -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 -D QSPIFLASH=1 + -D ENABLE_USB_INTERFACE ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${Xiao_nrf52.build_src_filter} diff --git a/variants/xiao_rp2040/platformio.ini b/variants/xiao_rp2040/platformio.ini index ca00e38b..63c6798d 100644 --- a/variants/xiao_rp2040/platformio.ini +++ b/variants/xiao_rp2040/platformio.ini @@ -61,6 +61,7 @@ extends = Xiao_rp2040 build_flags = ${Xiao_rp2040.build_flags} -D MAX_CONTACTS=100 -D MAX_GROUP_CHANNELS=8 + -D ENABLE_USB_INTERFACE ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 build_src_filter = ${Xiao_rp2040.build_src_filter} diff --git a/variants/xiao_s3/platformio.ini b/variants/xiao_s3/platformio.ini index 22464e7d..1632d112 100644 --- a/variants/xiao_s3/platformio.ini +++ b/variants/xiao_s3/platformio.ini @@ -123,6 +123,7 @@ build_flags = -D MAX_GROUP_CHANNELS=40 -D DISPLAY_CLASS=SSD1306Display -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_USB_INTERFACE ; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 diff --git a/variants/xiao_s3_wio/platformio.ini b/variants/xiao_s3_wio/platformio.ini index db8c5a94..293a13c1 100644 --- a/variants/xiao_s3_wio/platformio.ini +++ b/variants/xiao_s3_wio/platformio.ini @@ -136,6 +136,7 @@ build_flags = -D MAX_GROUP_CHANNELS=40 -D DISPLAY_CLASS=SSD1306Display -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_USB_INTERFACE ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${Xiao_S3_WIO.build_src_filter} From b1218c1dbec1dbbf412985442feb087f0829f24e Mon Sep 17 00:00:00 2001 From: liamcottle Date: Tue, 28 Jul 2026 03:50:08 +1200 Subject: [PATCH 056/381] fix bluetooth toggle on ui tiny --- examples/companion_radio/ui-tiny/UITask.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/companion_radio/ui-tiny/UITask.cpp b/examples/companion_radio/ui-tiny/UITask.cpp index 5b9ebfd3..b6bdbcf4 100644 --- a/examples/companion_radio/ui-tiny/UITask.cpp +++ b/examples/companion_radio/ui-tiny/UITask.cpp @@ -240,7 +240,7 @@ public: } else if (_page == HomePage::BLUETOOTH) { display.setColor(UIColor::corp_blue); display.drawXbm((display.width() - 32) / 2, 8, - _task->isSerialEnabled() ? bluetooth_on : bluetooth_off, + _task->isBluetoothEnabled() ? bluetooth_on : bluetooth_off, 32, 32); display.setTextSize(1); // display.drawTextCentered(display.width() / 2, 40 - 11, "toggle: " PRESS_LABEL); @@ -391,10 +391,10 @@ public: return true; } if (c == KEY_ENTER && _page == HomePage::BLUETOOTH) { - if (_task->isSerialEnabled()) { // toggle Bluetooth on/off - _task->disableSerial(); + if (_task->isBluetoothEnabled()) { // toggle Bluetooth on/off + _task->disableBluetooth(); } else { - _task->enableSerial(); + _task->enableBluetooth(); } return true; } @@ -677,7 +677,7 @@ void UITask::loop() { _cached_batt_mv, isBuzzerQuiet(), getGPSState(), - isSerialEnabled()); + isBluetoothEnabled()); bool status_dirty = _statusBar.needsRedraw(); bool content_dirty = (millis() >= _next_refresh && curr); From ae3517f480e44e6609d5ef245233d8f24efcc8c2 Mon Sep 17 00:00:00 2001 From: DG1TAL Date: Mon, 27 Jul 2026 20:07:08 +0200 Subject: [PATCH 057/381] Clarify hashtag privacy and group sender identity --- docs/companion_protocol.md | 2 ++ docs/payloads.md | 3 +++ 2 files changed, 5 insertions(+) diff --git a/docs/companion_protocol.md b/docs/companion_protocol.md index 7cca7bc9..8c6b84b9 100644 --- a/docs/companion_protocol.md +++ b/docs/companion_protocol.md @@ -440,6 +440,8 @@ Byte 0: 0x14 - Uses a secret key derived from the channel name - It is the first 16 bytes of `sha256("#test")` - For example hashtag channel `#test` has the key: `9cd8fcf22a47333b591d96a2b848b73f` + - Traffic is encrypted on air, but anyone who knows or guesses the channel + name can derive the key. Hashtag channels should not be treated as private. - Used as a topic based public group chat, separate from the default public channel 3. **Private Channels** - Uses a randomly generated 16-byte secret key diff --git a/docs/payloads.md b/docs/payloads.md index 21cb9469..9d2a8a11 100644 --- a/docs/payloads.md +++ b/docs/payloads.md @@ -236,6 +236,9 @@ txt_type The plaintext contained in the ciphertext matches the format described in [plain text message](#plain-text-message). Specifically, it consists of a four byte timestamp, a flags byte, and the message. The flags byte will generally be `0x00` because it is a "plain text message". The message will be of the form `: ` (eg., `user123: I'm on my way`). +The sender name is unverified message text. Group messages contain no sender +signature, so any channel-key holder can choose any sender name. + # Group datagram | Field | Size (bytes) | Description | From d4ee0fc4eb08c9e405c8049f60fe6159510d4e81 Mon Sep 17 00:00:00 2001 From: entr0p1 <1475255+entr0p1@users.noreply.github.com> Date: Tue, 28 Jul 2026 10:14:59 +1000 Subject: [PATCH 058/381] nRF52840 "start ota" Failure Recovery If Bluefruit.begin fails, BLE OTA mode won't actually start and the board might require a reboot to reattempt. Fixes: - Bluefruit.begin returns false in NRF52Board.startOTAUpdate if OTA mode fails to start. User is notified of the fault through existing error message in CommonCLI and can reattempt "start ota" command. --- src/helpers/NRF52Board.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/helpers/NRF52Board.cpp b/src/helpers/NRF52Board.cpp index 23f7cafc..b6c8fec5 100644 --- a/src/helpers/NRF52Board.cpp +++ b/src/helpers/NRF52Board.cpp @@ -396,7 +396,8 @@ bool NRF52Board::startOTAUpdate(const char *id, char reply[]) { Bluefruit.configPrphBandwidth(BANDWIDTH_MAX); Bluefruit.configPrphConn(92, BLE_GAP_EVENT_LENGTH_MIN, 16, 16); - Bluefruit.begin(1, 0); + if (!Bluefruit.begin(1, 0)) return false; + // Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4 Bluefruit.setTxPower(4); // Set the BLE device name From b9918e6037ab8b20d6ca556696b1ce38822fa81b Mon Sep 17 00:00:00 2001 From: Che177 Date: Mon, 27 Jul 2026 19:32:47 -0700 Subject: [PATCH 059/381] room_server: add room.post system posts --- examples/simple_room_server/MyMesh.cpp | 42 +++++++++++++++++++++++--- examples/simple_room_server/MyMesh.h | 2 ++ 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/examples/simple_room_server/MyMesh.cpp b/examples/simple_room_server/MyMesh.cpp index 7bf941a9..e7cd2d75 100644 --- a/examples/simple_room_server/MyMesh.cpp +++ b/examples/simple_room_server/MyMesh.cpp @@ -39,18 +39,43 @@ struct ServerStats { }; void MyMesh::addPost(ClientInfo *client, const char *postData) { - // TODO: suggested postData format: /<descrption> - posts[next_post_idx].author = client->id; // add to cyclic queue - StrHelper::strncpy(posts[next_post_idx].text, postData, MAX_POST_TEXT_LEN); + storePost(client->id, postData); +} - posts[next_post_idx].post_timestamp = getRTCClock()->getCurrentTimeUnique(); +void MyMesh::addSystemPost(const char *postData) { + if (!postData || postData[0] == 0) return; + +#if defined(ENABLE_ROOM_POST_DEBUG) && ENABLE_ROOM_POST_DEBUG == 1 + Serial.print("room.post: addSystemPost: "); Serial.println(postData); +#endif + + storePost(self_id, postData); +} + +void MyMesh::storePost(const mesh::Identity &author, const char *postData) { + int idx = next_post_idx; + // TODO: suggested postData format: <title>/<descrption> + posts[idx].author = author; // add to cyclic queue + StrHelper::strncpy(posts[idx].text, postData, MAX_POST_TEXT_LEN); + + posts[idx].post_timestamp = getRTCClock()->getCurrentTimeUnique(); +#if defined(ENABLE_ROOM_POST_DEBUG) && ENABLE_ROOM_POST_DEBUG == 1 + Serial.printf("room.post: storePost idx=%d text=%s\n", idx, posts[idx].text); + Serial.printf("room.post: timestamp=%u\n", posts[idx].post_timestamp); +#endif next_post_idx = (next_post_idx + 1) % MAX_UNSYNCED_POSTS; next_push = futureMillis(PUSH_NOTIFY_DELAY_MILLIS); _num_posted++; // stats +#if defined(ENABLE_ROOM_POST_DEBUG) && ENABLE_ROOM_POST_DEBUG == 1 + Serial.printf("room.post: next_post_idx=%d num_posted=%d push scheduled\n", next_post_idx, _num_posted); +#endif } void MyMesh::pushPostToClient(ClientInfo *client, PostInfo &post) { +#if defined(ENABLE_ROOM_POST_DEBUG) && ENABLE_ROOM_POST_DEBUG == 1 + Serial.print("room.post: pushPostToClient text="); Serial.println(post.text); +#endif int len = 0; memcpy(&reply_data[len], &post.post_timestamp, 4); len += 4; // this is a PAST timestamp... but should be accepted by client @@ -948,6 +973,15 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply Serial.printf("\n"); } reply[0] = 0; + } else if (strncmp(command, "room.post", 9) == 0) { + char* msg = command + 9; + while (*msg == ' ') msg++; + if (*msg == 0) { + snprintf(reply, MAX_POST_TEXT_LEN, "ERR empty message"); + } else { + addSystemPost(msg); + snprintf(reply, MAX_POST_TEXT_LEN, "OK"); + } } else{ _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands } diff --git a/examples/simple_room_server/MyMesh.h b/examples/simple_room_server/MyMesh.h index caef6920..5f78bee8 100644 --- a/examples/simple_room_server/MyMesh.h +++ b/examples/simple_room_server/MyMesh.h @@ -119,6 +119,7 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { int matching_peer_indexes[MAX_CLIENTS]; void addPost(ClientInfo* client, const char* postData); + void storePost(const mesh::Identity& author, const char* postData); void pushPostToClient(ClientInfo* client, PostInfo& post); uint8_t getUnsyncedCount(ClientInfo* client); bool processAck(const uint8_t *data); @@ -176,6 +177,7 @@ public: MyMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables); void begin(FILESYSTEM* fs); + void addSystemPost(const char* postData); const char* getFirmwareVer() override { return FIRMWARE_VERSION; } const char* getBuildDate() override { return FIRMWARE_BUILD_DATE; } From 8762862522fba822635dd7756092b55904105882 Mon Sep 17 00:00:00 2001 From: Che177 <github@kitagor.com> Date: Tue, 28 Jul 2026 21:57:42 -0700 Subject: [PATCH 060/381] room_server: use standard mesh debug logging --- examples/simple_room_server/MyMesh.cpp | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/examples/simple_room_server/MyMesh.cpp b/examples/simple_room_server/MyMesh.cpp index e7cd2d75..0aff39cc 100644 --- a/examples/simple_room_server/MyMesh.cpp +++ b/examples/simple_room_server/MyMesh.cpp @@ -45,9 +45,7 @@ void MyMesh::addPost(ClientInfo *client, const char *postData) { void MyMesh::addSystemPost(const char *postData) { if (!postData || postData[0] == 0) return; -#if defined(ENABLE_ROOM_POST_DEBUG) && ENABLE_ROOM_POST_DEBUG == 1 - Serial.print("room.post: addSystemPost: "); Serial.println(postData); -#endif + MESH_DEBUG_PRINTLN("room.post: addSystemPost: %s", postData); storePost(self_id, postData); } @@ -59,23 +57,17 @@ void MyMesh::storePost(const mesh::Identity &author, const char *postData) { StrHelper::strncpy(posts[idx].text, postData, MAX_POST_TEXT_LEN); posts[idx].post_timestamp = getRTCClock()->getCurrentTimeUnique(); -#if defined(ENABLE_ROOM_POST_DEBUG) && ENABLE_ROOM_POST_DEBUG == 1 - Serial.printf("room.post: storePost idx=%d text=%s\n", idx, posts[idx].text); - Serial.printf("room.post: timestamp=%u\n", posts[idx].post_timestamp); -#endif + MESH_DEBUG_PRINTLN("room.post: storePost idx=%d text=%s", idx, posts[idx].text); + MESH_DEBUG_PRINTLN("room.post: timestamp=%u", posts[idx].post_timestamp); next_post_idx = (next_post_idx + 1) % MAX_UNSYNCED_POSTS; next_push = futureMillis(PUSH_NOTIFY_DELAY_MILLIS); _num_posted++; // stats -#if defined(ENABLE_ROOM_POST_DEBUG) && ENABLE_ROOM_POST_DEBUG == 1 - Serial.printf("room.post: next_post_idx=%d num_posted=%d push scheduled\n", next_post_idx, _num_posted); -#endif + MESH_DEBUG_PRINTLN("room.post: next_post_idx=%d num_posted=%d push scheduled", next_post_idx, _num_posted); } void MyMesh::pushPostToClient(ClientInfo *client, PostInfo &post) { -#if defined(ENABLE_ROOM_POST_DEBUG) && ENABLE_ROOM_POST_DEBUG == 1 - Serial.print("room.post: pushPostToClient text="); Serial.println(post.text); -#endif + MESH_DEBUG_PRINTLN("room.post: pushPostToClient text=%s", post.text); int len = 0; memcpy(&reply_data[len], &post.post_timestamp, 4); len += 4; // this is a PAST timestamp... but should be accepted by client From 52fb56395d74b12dac5fd0b8638a5d88f0e1420b Mon Sep 17 00:00:00 2001 From: entr0p1 <1475255+entr0p1@users.noreply.github.com> Date: Wed, 29 Jul 2026 18:27:15 +1000 Subject: [PATCH 061/381] Clean up debugs left on in platform.ini files --- variants/meshadventurer/platformio.ini | 8 ++++---- variants/minewsemi_me25ls01/platformio.ini | 16 ++++++++-------- variants/muziworks_r1_neo/platformio.ini | 2 +- variants/promicro/platformio.ini | 2 +- variants/rak4631/platformio.ini | 2 +- variants/station_g2/platformio.ini | 4 ++-- variants/station_g3_esp32/platformio.ini | 2 +- variants/thinknode_m2/platformio.ini | 2 +- variants/thinknode_m3/platformio.ini | 2 +- variants/thinknode_m5/platformio.ini | 2 +- variants/thinknode_m7/platformio.ini | 2 +- variants/xiao_nrf52/platformio.ini | 2 +- variants/xiao_rp2040/platformio.ini | 4 ++-- 13 files changed, 25 insertions(+), 25 deletions(-) diff --git a/variants/meshadventurer/platformio.ini b/variants/meshadventurer/platformio.ini index f85be238..5def659c 100644 --- a/variants/meshadventurer/platformio.ini +++ b/variants/meshadventurer/platformio.ini @@ -209,8 +209,8 @@ build_flags = -D BLE_PIN_CODE=123456 -D BLE_DEBUG_LOGGING=1 -D OFFLINE_QUEUE_SIZE=128 - -D MESH_PACKET_LOGGING=1 - -D MESH_DEBUG=1 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 lib_deps = ${Meshadventurer.lib_deps} densaugeo/base64 @ ~1.4.0 @@ -289,8 +289,8 @@ build_flags = -D BLE_PIN_CODE=123456 -D BLE_DEBUG_LOGGING=1 -D OFFLINE_QUEUE_SIZE=128 - -D MESH_PACKET_LOGGING=1 - -D MESH_DEBUG=1 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 lib_deps = ${Meshadventurer.lib_deps} densaugeo/base64 @ ~1.4.0 diff --git a/variants/minewsemi_me25ls01/platformio.ini b/variants/minewsemi_me25ls01/platformio.ini index ac81fa16..97c6c11e 100644 --- a/variants/minewsemi_me25ls01/platformio.ini +++ b/variants/minewsemi_me25ls01/platformio.ini @@ -46,8 +46,8 @@ build_flags = ${me25ls01.build_flags} -D MAX_GROUP_CHANNELS=40 -D BLE_PIN_CODE=123456 ; -D BLE_DEBUG_LOGGING=1 - -D MESH_PACKET_LOGGING=1 - -D MESH_DEBUG=1 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 -D OFFLINE_QUEUE_SIZE=256 -D RX_BOOSTED_GAIN=true -D RF_SWITCH_TABLE @@ -67,8 +67,8 @@ build_flags = ${me25ls01.build_flags} -D MAX_GROUP_CHANNELS=8 -D BLE_PIN_CODE=123456 ; -D BLE_DEBUG_LOGGING=1 - -D MESH_PACKET_LOGGING=1 - -D MESH_DEBUG=1 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 -D OFFLINE_QUEUE_SIZE=256 -D RX_BOOSTED_GAIN=true -D RF_SWITCH_TABLE @@ -112,8 +112,8 @@ build_flags = ${me25ls01.build_flags} -D MAX_GROUP_CHANNELS=8 -D BLE_PIN_CODE=123456 ; -D BLE_DEBUG_LOGGING=1 - -D MESH_PACKET_LOGGING=1 - -D MESH_DEBUG=1 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 -D OFFLINE_QUEUE_SIZE=256 -D RX_BOOSTED_GAIN=true -D RF_SWITCH_TABLE @@ -138,8 +138,8 @@ build_flags = ${me25ls01.build_flags} -D MAX_GROUP_CHANNELS=40 ;-D BLE_PIN_CODE=123456 ; -D BLE_DEBUG_LOGGING=1 - -D MESH_PACKET_LOGGING=1 - -D MESH_DEBUG=1 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 -D OFFLINE_QUEUE_SIZE=256 -D RX_BOOSTED_GAIN=true -D RF_SWITCH_TABLE diff --git a/variants/muziworks_r1_neo/platformio.ini b/variants/muziworks_r1_neo/platformio.ini index 3dbecf1e..13795879 100644 --- a/variants/muziworks_r1_neo/platformio.ini +++ b/variants/muziworks_r1_neo/platformio.ini @@ -127,7 +127,7 @@ build_flags = -D ADVERT_LON=0.0 -D ADMIN_PASSWORD='"password"' ; -D MESH_PACKET_LOGGING=1 - -D MESH_DEBUG=1 +; -D MESH_DEBUG=1 build_src_filter = ${R1Neo.build_src_filter} +<../examples/simple_sensor> diff --git a/variants/promicro/platformio.ini b/variants/promicro/platformio.ini index 5415e158..01fd8932 100644 --- a/variants/promicro/platformio.ini +++ b/variants/promicro/platformio.ini @@ -143,7 +143,7 @@ build_flags = ${Promicro.build_flags} -D OFFLINE_QUEUE_SIZE=256 -D DISPLAY_CLASS=SSD1306Display ; -D MESH_PACKET_LOGGING=1 - -D MESH_DEBUG=1 +; -D MESH_DEBUG=1 build_src_filter = ${Promicro.build_src_filter} +<helpers/nrf52/SerialBLEInterface.cpp> +<helpers/ui/SSD1306Display.cpp> diff --git a/variants/rak4631/platformio.ini b/variants/rak4631/platformio.ini index 31b507b4..ea900c6c 100644 --- a/variants/rak4631/platformio.ini +++ b/variants/rak4631/platformio.ini @@ -254,7 +254,7 @@ build_flags = -D ADVERT_LON=0.0 -D ADMIN_PASSWORD='"password"' ; -D MESH_PACKET_LOGGING=1 - -D MESH_DEBUG=1 +; -D MESH_DEBUG=1 build_src_filter = ${rak4631.build_src_filter} +<helpers/ui/SSD1306Display.cpp> +<../examples/simple_sensor> diff --git a/variants/station_g2/platformio.ini b/variants/station_g2/platformio.ini index 508ffe4b..ffbf387a 100644 --- a/variants/station_g2/platformio.ini +++ b/variants/station_g2/platformio.ini @@ -110,7 +110,7 @@ build_flags = -D ADVERT_LON=0.0 -D ADMIN_PASSWORD='"password"' -D MAX_NEIGHBOURS=50 - -D MESH_PACKET_LOGGING=1 +; -D MESH_PACKET_LOGGING=1 -D SX126X_RX_BOOSTED_GAIN=1 ; https://wiki.uniteng.com/en/meshtastic/station-g2#impact-of-lora-node-dense-areashigh-noise-environments-on-rf-performance ; -D MESH_DEBUG=1 @@ -152,7 +152,7 @@ build_flags = -D ADVERT_LON=0.0 -D ADMIN_PASSWORD='"password"' -D MAX_NEIGHBOURS=50 - -D MESH_PACKET_LOGGING=1 +; -D MESH_PACKET_LOGGING=1 -D SX126X_RX_BOOSTED_GAIN=1 -D WITH_ESPNOW_BRIDGE=1 ; -D BRIDGE_DEBUG=1 diff --git a/variants/station_g3_esp32/platformio.ini b/variants/station_g3_esp32/platformio.ini index b29388ef..71bad18b 100644 --- a/variants/station_g3_esp32/platformio.ini +++ b/variants/station_g3_esp32/platformio.ini @@ -71,7 +71,7 @@ build_flags = -D ADVERT_LON=0.0 -D ADMIN_PASSWORD='"password"' -D MAX_NEIGHBOURS=50 - -D MESH_PACKET_LOGGING=1 +; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${Station_G3_ESP32.build_src_filter} +<../examples/simple_repeater> diff --git a/variants/thinknode_m2/platformio.ini b/variants/thinknode_m2/platformio.ini index aae83324..cc9f7688 100644 --- a/variants/thinknode_m2/platformio.ini +++ b/variants/thinknode_m2/platformio.ini @@ -30,7 +30,7 @@ build_flags = ${esp32_base.build_flags} -D WRAPPER_CLASS=CustomSX1262Wrapper -D LORA_TX_POWER=22 -D SX126X_RX_BOOSTED_GAIN=1 - -D MESH_DEBUG=1 +; -D MESH_DEBUG=1 build_src_filter = ${esp32_base.build_src_filter} +<helpers/ui/SH1106Display.cpp> +<helpers/ui/MomentaryButton.cpp> diff --git a/variants/thinknode_m3/platformio.ini b/variants/thinknode_m3/platformio.ini index f80a6161..39eaed84 100644 --- a/variants/thinknode_m3/platformio.ini +++ b/variants/thinknode_m3/platformio.ini @@ -26,7 +26,7 @@ build_flags = ${nrf52_base.build_flags} -D P_LORA_TX_LED=PIN_LED_BLUE -D LR11X0_DIO_AS_RF_SWITCH=true -D LR11X0_DIO3_TCXO_VOLTAGE=3.3 - -D MESH_DEBUG=1 +; -D MESH_DEBUG=1 -D ENV_INCLUDE_GPS=1 build_src_filter = ${nrf52_base.build_src_filter} +<helpers/*.cpp> diff --git a/variants/thinknode_m5/platformio.ini b/variants/thinknode_m5/platformio.ini index 8572d1eb..cdbcceef 100644 --- a/variants/thinknode_m5/platformio.ini +++ b/variants/thinknode_m5/platformio.ini @@ -37,7 +37,7 @@ build_flags = ${esp32_base.build_flags} -D WRAPPER_CLASS=CustomSX1262Wrapper -D LORA_TX_POWER=22 -D SX126X_RX_BOOSTED_GAIN=1 - -D MESH_DEBUG=1 +; -D MESH_DEBUG=1 -D ENV_INCLUDE_GPS=1 -D PERSISTANT_GPS=1 -D ENV_SKIP_GPS_DETECT=1 diff --git a/variants/thinknode_m7/platformio.ini b/variants/thinknode_m7/platformio.ini index acd98c8c..c4bed017 100644 --- a/variants/thinknode_m7/platformio.ini +++ b/variants/thinknode_m7/platformio.ini @@ -119,7 +119,7 @@ build_flags = -D WIFI_SSID='"myssid"' -D WIFI_PWD='"mypwd"' -D OFFLINE_QUEUE_SIZE=256 - -D MESH_PACKET_LOGGING=1 +; -D MESH_PACKET_LOGGING=1 build_src_filter = ${ThinkNode_M7.build_src_filter} +<helpers/esp32/*.cpp> +<helpers/ui/MomentaryButton.cpp> diff --git a/variants/xiao_nrf52/platformio.ini b/variants/xiao_nrf52/platformio.ini index a0854336..56e27cbb 100644 --- a/variants/xiao_nrf52/platformio.ini +++ b/variants/xiao_nrf52/platformio.ini @@ -53,7 +53,7 @@ build_flags = -D OFFLINE_QUEUE_SIZE=256 ; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 - -D MESH_DEBUG=1 +; -D MESH_DEBUG=1 -D QSPIFLASH=1 build_src_filter = ${Xiao_nrf52.build_src_filter} +<helpers/nrf52/SerialBLEInterface.cpp> diff --git a/variants/xiao_rp2040/platformio.ini b/variants/xiao_rp2040/platformio.ini index ca00e38b..62d36005 100644 --- a/variants/xiao_rp2040/platformio.ini +++ b/variants/xiao_rp2040/platformio.ini @@ -38,8 +38,8 @@ build_flags = ${Xiao_rp2040.build_flags} -D ADVERT_LON=0.0 -D ADMIN_PASSWORD='"password"' -D MAX_NEIGHBOURS=50 - -D MESH_PACKET_LOGGING=1 - -D MESH_DEBUG=1 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 build_src_filter = ${Xiao_rp2040.build_src_filter} +<../examples/simple_repeater> From 0f543ccc34a6d3abe53f75b0dbe4c1c8f4080649 Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Wed, 29 Jul 2026 16:10:15 +1000 Subject: [PATCH 062/381] fix unnecessary IRQ clear --- src/helpers/radiolib/CustomSX1262.h | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/helpers/radiolib/CustomSX1262.h b/src/helpers/radiolib/CustomSX1262.h index 6a7c2144..b4ee6c97 100644 --- a/src/helpers/radiolib/CustomSX1262.h +++ b/src/helpers/radiolib/CustomSX1262.h @@ -117,6 +117,12 @@ class CustomSX1262 : public SX1262 { _headerSeen = false; return false; } + if (!header && _headerSeen) { + // something cleared the header flag, reset our state. + _activityAt = 0; _headerSeen = false; + return false; + } + if (header) { if (!_headerSeen) { _headerSeen = true; _activityAt = now; }; if (now - _activityAt > _maxPayloadMillis) { From 7fbac66a339776b2d4e5e2abb3044b19f3c1efea Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Wed, 29 Jul 2026 23:18:15 +1000 Subject: [PATCH 063/381] LR1110: fix unnecessary IRQ clear --- src/helpers/radiolib/CustomLR1110.h | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/helpers/radiolib/CustomLR1110.h b/src/helpers/radiolib/CustomLR1110.h index 20aea9ff..c481cf5e 100644 --- a/src/helpers/radiolib/CustomLR1110.h +++ b/src/helpers/radiolib/CustomLR1110.h @@ -52,6 +52,11 @@ class CustomLR1110 : public LR1110 { _headerSeen = false; return false; } + if (!header && _headerSeen) { + // something cleared the header flag, reset our state. + _activityAt = 0; _headerSeen = false; + return false; + } if (header) { if (!_headerSeen) { _headerSeen = true; _activityAt = now; }; if (now - _activityAt > _maxPayloadMillis) { From c490abf452498c9bddbe32c1d246b3ef8518f754 Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Wed, 29 Jul 2026 23:19:40 +1000 Subject: [PATCH 064/381] STM32WLx: add IRQ timeout logic --- src/helpers/radiolib/CustomSTM32WLx.h | 58 +++++++++++++++++++- src/helpers/radiolib/CustomSTM32WLxWrapper.h | 3 + 2 files changed, 58 insertions(+), 3 deletions(-) diff --git a/src/helpers/radiolib/CustomSTM32WLx.h b/src/helpers/radiolib/CustomSTM32WLx.h index 01190d06..e312a5ee 100644 --- a/src/helpers/radiolib/CustomSTM32WLx.h +++ b/src/helpers/radiolib/CustomSTM32WLx.h @@ -3,6 +3,11 @@ #include <RadioLib.h> class CustomSTM32WLx : public STM32WLx { + uint32_t _preambleMillis = 66; + uint32_t _maxPayloadMillis = 3934; + uint32_t _activityAt = 0; + bool _headerSeen = false; + public: CustomSTM32WLx(STM32WLx_Module *mod) : STM32WLx(mod) { } @@ -12,8 +17,55 @@ class CustomSTM32WLx : public STM32WLx { } bool isReceiving() { - uint16_t irq = getIrqFlags(); - bool detected = (irq & RADIOLIB_SX126X_IRQ_HEADER_VALID) || (irq & RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED); - return detected; + uint32_t irq = getIrqFlags(); + bool preamble = irq & RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED; // bit 2 + bool header = irq & RADIOLIB_SX126X_IRQ_HEADER_VALID; // bit 4 + bool hdrErr = irq & RADIOLIB_SX126X_IRQ_HEADER_ERR; // bit 5 + uint32_t now = millis(); + if (hdrErr) { + clearIrqFlags(RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED | RADIOLIB_SX126X_IRQ_HEADER_VALID | RADIOLIB_SX126X_IRQ_HEADER_ERR | RADIOLIB_SX126X_IRQ_SYNC_WORD_VALID); + _activityAt = 0; + _headerSeen = false; + return false; + } + if (!header && _headerSeen) { + // something cleared the header flag, reset our state. + _activityAt = 0; _headerSeen = false; + return false; + } + + if (header) { + if (!_headerSeen) { _headerSeen = true; _activityAt = now; }; + if (now - _activityAt > _maxPayloadMillis) { + MESH_DEBUG_PRINTLN("Clearing header IRQ after %ums", _maxPayloadMillis); + clearIrqFlags(RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED | RADIOLIB_SX126X_IRQ_HEADER_VALID | RADIOLIB_SX126X_IRQ_HEADER_ERR | RADIOLIB_SX126X_IRQ_SYNC_WORD_VALID); + _activityAt = 0; _headerSeen = false; + return false; + } + return true; + } + if (preamble) { + if (_activityAt == 0) _activityAt = now; + if (now - _activityAt > _preambleMillis) { + clearIrqFlags(RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED); + _activityAt = 0; + MESH_DEBUG_PRINTLN("Clearing preamble IRQ after %ums", _preambleMillis); + + return false; + } + return true; + } + _activityAt = 0; _headerSeen = false; + return false; } + + void setPreambleMillis(uint32_t preambleMillis) { + _preambleMillis = preambleMillis; + MESH_DEBUG_PRINTLN("Set _preambleMillis=%u", _preambleMillis); + } + void setMaxPayloadMillis(uint32_t payloadMillis) { + _maxPayloadMillis = payloadMillis; + MESH_DEBUG_PRINTLN("Set _maxPayloadMillis=%u", _maxPayloadMillis); + } + }; \ No newline at end of file diff --git a/src/helpers/radiolib/CustomSTM32WLxWrapper.h b/src/helpers/radiolib/CustomSTM32WLxWrapper.h index 97bf6820..a792a877 100644 --- a/src/helpers/radiolib/CustomSTM32WLxWrapper.h +++ b/src/helpers/radiolib/CustomSTM32WLxWrapper.h @@ -15,6 +15,9 @@ public: ((CustomSTM32WLx *)_radio)->setBandwidth(bw); ((CustomSTM32WLx *)_radio)->setCodingRate(cr); updatePreamble(sf); + PacketMillis pm = calcMaxPacketMillis(sf, bw, cr, preambleLengthForSF(sf)); + ((CustomSTM32WLx *)_radio)->setPreambleMillis(pm.preambleMillis); + ((CustomSTM32WLx *)_radio)->setMaxPayloadMillis(pm.payloadMillis); } bool isReceivingPacket() override { From 2f19204283d8fcdb37e9d7fd6fdea787e0de0a24 Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Wed, 29 Jul 2026 23:29:37 +1000 Subject: [PATCH 065/381] SX1268: add IRQ timeout logic --- src/helpers/radiolib/CustomSX1268.h | 58 ++++++++++++++++++++-- src/helpers/radiolib/CustomSX1268Wrapper.h | 3 ++ 2 files changed, 58 insertions(+), 3 deletions(-) diff --git a/src/helpers/radiolib/CustomSX1268.h b/src/helpers/radiolib/CustomSX1268.h index 1e71a3fa..f915332d 100644 --- a/src/helpers/radiolib/CustomSX1268.h +++ b/src/helpers/radiolib/CustomSX1268.h @@ -3,6 +3,11 @@ #include <RadioLib.h> class CustomSX1268 : public SX1268 { + uint32_t _preambleMillis = 66; + uint32_t _maxPayloadMillis = 3934; + uint32_t _activityAt = 0; + bool _headerSeen = false; + public: CustomSX1268(Module *mod) : SX1268(mod) { } @@ -81,10 +86,57 @@ class CustomSX1268 : public SX1268 { } bool isReceiving() { - uint16_t irq = getIrqFlags(); - bool detected = (irq & RADIOLIB_SX126X_IRQ_HEADER_VALID) || (irq & RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED); - return detected; + uint32_t irq = getIrqFlags(); + bool preamble = irq & RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED; // bit 2 + bool header = irq & RADIOLIB_SX126X_IRQ_HEADER_VALID; // bit 4 + bool hdrErr = irq & RADIOLIB_SX126X_IRQ_HEADER_ERR; // bit 5 + uint32_t now = millis(); + if (hdrErr) { + clearIrqFlags(RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED | RADIOLIB_SX126X_IRQ_HEADER_VALID | RADIOLIB_SX126X_IRQ_HEADER_ERR | RADIOLIB_SX126X_IRQ_SYNC_WORD_VALID); + _activityAt = 0; + _headerSeen = false; + return false; + } + if (!header && _headerSeen) { + // something cleared the header flag, reset our state. + _activityAt = 0; _headerSeen = false; + return false; + } + + if (header) { + if (!_headerSeen) { _headerSeen = true; _activityAt = now; }; + if (now - _activityAt > _maxPayloadMillis) { + MESH_DEBUG_PRINTLN("Clearing header IRQ after %ums", _maxPayloadMillis); + clearIrqFlags(RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED | RADIOLIB_SX126X_IRQ_HEADER_VALID | RADIOLIB_SX126X_IRQ_HEADER_ERR | RADIOLIB_SX126X_IRQ_SYNC_WORD_VALID); + _activityAt = 0; _headerSeen = false; + return false; + } + return true; + } + if (preamble) { + if (_activityAt == 0) _activityAt = now; + if (now - _activityAt > _preambleMillis) { + clearIrqFlags(RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED); + _activityAt = 0; + MESH_DEBUG_PRINTLN("Clearing preamble IRQ after %ums", _preambleMillis); + + return false; + } + return true; + } + _activityAt = 0; _headerSeen = false; + return false; } + + void setPreambleMillis(uint32_t preambleMillis) { + _preambleMillis = preambleMillis; + MESH_DEBUG_PRINTLN("Set _preambleMillis=%u", _preambleMillis); + } + void setMaxPayloadMillis(uint32_t payloadMillis) { + _maxPayloadMillis = payloadMillis; + MESH_DEBUG_PRINTLN("Set _maxPayloadMillis=%u", _maxPayloadMillis); + } + bool getRxBoostedGainMode() { uint8_t rxGain = 0; diff --git a/src/helpers/radiolib/CustomSX1268Wrapper.h b/src/helpers/radiolib/CustomSX1268Wrapper.h index bce56b99..104ba08b 100644 --- a/src/helpers/radiolib/CustomSX1268Wrapper.h +++ b/src/helpers/radiolib/CustomSX1268Wrapper.h @@ -18,6 +18,9 @@ public: ((CustomSX1268 *)_radio)->setBandwidth(bw); ((CustomSX1268 *)_radio)->setCodingRate(cr); updatePreamble(sf); + PacketMillis pm = calcMaxPacketMillis(sf, bw, cr, preambleLengthForSF(sf)); + ((CustomSX1268 *)_radio)->setPreambleMillis(pm.preambleMillis); + ((CustomSX1268 *)_radio)->setMaxPayloadMillis(pm.payloadMillis); } bool isReceivingPacket() override { From dc6264b870f72771f1d517df442f063e96c02542 Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Wed, 29 Jul 2026 23:33:24 +1000 Subject: [PATCH 066/381] LLCC68: add IRQ timeout logic --- src/helpers/radiolib/CustomLLCC68.h | 57 ++++++++++++++++++++-- src/helpers/radiolib/CustomLLCC68Wrapper.h | 4 ++ 2 files changed, 58 insertions(+), 3 deletions(-) diff --git a/src/helpers/radiolib/CustomLLCC68.h b/src/helpers/radiolib/CustomLLCC68.h index bde44b6c..1dcd916f 100644 --- a/src/helpers/radiolib/CustomLLCC68.h +++ b/src/helpers/radiolib/CustomLLCC68.h @@ -3,6 +3,11 @@ #include <RadioLib.h> class CustomLLCC68 : public LLCC68 { + uint32_t _preambleMillis = 66; + uint32_t _maxPayloadMillis = 3934; + uint32_t _activityAt = 0; + bool _headerSeen = false; + public: CustomLLCC68(Module *mod) : LLCC68(mod) { } @@ -81,9 +86,55 @@ class CustomLLCC68 : public LLCC68 { } bool isReceiving() { - uint16_t irq = getIrqFlags(); - bool detected = (irq & RADIOLIB_SX126X_IRQ_HEADER_VALID) || (irq & RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED); - return detected; + uint32_t irq = getIrqFlags(); + bool preamble = irq & RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED; // bit 2 + bool header = irq & RADIOLIB_SX126X_IRQ_HEADER_VALID; // bit 4 + bool hdrErr = irq & RADIOLIB_SX126X_IRQ_HEADER_ERR; // bit 5 + uint32_t now = millis(); + if (hdrErr) { + clearIrqFlags(RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED | RADIOLIB_SX126X_IRQ_HEADER_VALID | RADIOLIB_SX126X_IRQ_HEADER_ERR | RADIOLIB_SX126X_IRQ_SYNC_WORD_VALID); + _activityAt = 0; + _headerSeen = false; + return false; + } + if (!header && _headerSeen) { + // something cleared the header flag, reset our state. + _activityAt = 0; _headerSeen = false; + return false; + } + + if (header) { + if (!_headerSeen) { _headerSeen = true; _activityAt = now; }; + if (now - _activityAt > _maxPayloadMillis) { + MESH_DEBUG_PRINTLN("Clearing header IRQ after %ums", _maxPayloadMillis); + clearIrqFlags(RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED | RADIOLIB_SX126X_IRQ_HEADER_VALID | RADIOLIB_SX126X_IRQ_HEADER_ERR | RADIOLIB_SX126X_IRQ_SYNC_WORD_VALID); + _activityAt = 0; _headerSeen = false; + return false; + } + return true; + } + if (preamble) { + if (_activityAt == 0) _activityAt = now; + if (now - _activityAt > _preambleMillis) { + clearIrqFlags(RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED); + _activityAt = 0; + MESH_DEBUG_PRINTLN("Clearing preamble IRQ after %ums", _preambleMillis); + + return false; + } + return true; + } + _activityAt = 0; _headerSeen = false; + return false; + } + + void setPreambleMillis(uint32_t preambleMillis) { + _preambleMillis = preambleMillis; + MESH_DEBUG_PRINTLN("Set _preambleMillis=%u", _preambleMillis); + } + void setMaxPayloadMillis(uint32_t payloadMillis) { + _maxPayloadMillis = payloadMillis; + MESH_DEBUG_PRINTLN("Set _maxPayloadMillis=%u", _maxPayloadMillis); } bool getRxBoostedGainMode() { diff --git a/src/helpers/radiolib/CustomLLCC68Wrapper.h b/src/helpers/radiolib/CustomLLCC68Wrapper.h index 851fd644..ae0fe0a2 100644 --- a/src/helpers/radiolib/CustomLLCC68Wrapper.h +++ b/src/helpers/radiolib/CustomLLCC68Wrapper.h @@ -14,6 +14,10 @@ public: ((CustomLLCC68 *)_radio)->setBandwidth(bw); ((CustomLLCC68 *)_radio)->setCodingRate(cr); updatePreamble(sf); + PacketMillis pm = calcMaxPacketMillis(sf, bw, cr, preambleLengthForSF(sf)); + ((CustomLLCC68 *)_radio)->setPreambleMillis(pm.preambleMillis); + ((CustomLLCC68 *)_radio)->setMaxPayloadMillis(pm.payloadMillis); + } bool isReceivingPacket() override { From d53513472454c61a6c49b4111cc4672e1b14dd27 Mon Sep 17 00:00:00 2001 From: Mike Damon <mike.damon@lioinsurance.com> Date: Thu, 30 Jul 2026 10:58:40 -0400 Subject: [PATCH 067/381] LR1110: fix startReceive() passing an IRQ bit as the RX timeout CustomLR1110::startReceive() passed RADIOLIB_LR11X0_IRQ_PREAMBLE_DETECTED (1<<4 = 16) as RadioLib's first argument, which is the RX *timeout*, not an IRQ mask. At the LR11x0's 30.52us tick that armed the receiver for ~488us, so it dropped out of RX before any packet could arrive and the node received nothing at all -- while transmitting normally. Symptoms on a SenseCAP T1000-E: tx_air_secs rising, rx_air_secs stuck at 0, recv_errors 0, and the noise floor pinned at the -120 clamp because getCurrentRSSI() never sampled a live receiver. Pass RADIOLIB_LR11X0_RX_TIMEOUT_INF (continuous RX), which is what LR11x0::startReceive() itself uses, keeping the PREAMBLE_DETECTED flag in the reported IRQ flags as intended. Introduced in 04b643b2 ("LR1110: add PREAMBLE_DETECTED to reported irq flags"). Verified on two T1000-E units: with only the repeater fixed it began receiving (last_rssi -29, SNR 17.0) while the unfixed companion stayed deaf; fixing both brought up the link in each direction. --- src/helpers/radiolib/CustomLR1110.h | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/helpers/radiolib/CustomLR1110.h b/src/helpers/radiolib/CustomLR1110.h index c481cf5e..56a9aa6e 100644 --- a/src/helpers/radiolib/CustomLR1110.h +++ b/src/helpers/radiolib/CustomLR1110.h @@ -36,8 +36,15 @@ class CustomLR1110 : public LR1110 { bool getRxBoostedGainMode() const { return _rx_boosted; } int16_t startReceive() override { - // include the PREAMBLE_DETECTED irq bit in reported flags - return LR1110::startReceive(RADIOLIB_LR11X0_IRQ_PREAMBLE_DETECTED, RADIOLIB_IRQ_RX_DEFAULT_FLAGS | (1UL << RADIOLIB_IRQ_PREAMBLE_DETECTED), RADIOLIB_IRQ_RX_DEFAULT_MASK, 0); + // include the PREAMBLE_DETECTED irq bit in reported flags. + // + // NOTE: the first argument is the RX *timeout*, not an IRQ mask. Passing + // RADIOLIB_LR11X0_IRQ_PREAMBLE_DETECTED (1<<4 = 16) here armed the receiver + // with a 16-tick timeout -- at the LR11x0's 30.52us tick that is a ~488us + // receive window, so the radio dropped out of RX before any packet could + // arrive and the node never received anything. It must stay RX_TIMEOUT_INF + // (continuous RX), which is what LR11x0::startReceive() itself passes. + return LR1110::startReceive(RADIOLIB_LR11X0_RX_TIMEOUT_INF, RADIOLIB_IRQ_RX_DEFAULT_FLAGS | (1UL << RADIOLIB_IRQ_PREAMBLE_DETECTED), RADIOLIB_IRQ_RX_DEFAULT_MASK, 0); } bool isReceiving() { From 77b1356b36dc0f1a52907683e690927217d83563 Mon Sep 17 00:00:00 2001 From: me <jiroiset@gmail.com> Date: Sat, 1 Aug 2026 22:20:20 -0700 Subject: [PATCH 068/381] fix: M5Stack Unit C6L merged.bin fails to boot (flash_mode qio->dio) Board manifest for esp32-c6-devkitm-1 defaults build.flash_mode to qio, which this module's flash chip does not support -- causes a boot crash-loop (repeated USB-Serial-JTAG reconnects) on real hardware. Override with board_build.flash_mode = dio in the common M5Stack_Unit_C6L section so it applies to all envs (ble/usb/repeater/room_server). --- variants/m5stack_unit_c6l/platformio.ini | 1 + 1 file changed, 1 insertion(+) diff --git a/variants/m5stack_unit_c6l/platformio.ini b/variants/m5stack_unit_c6l/platformio.ini index 190add04..ea4d852d 100644 --- a/variants/m5stack_unit_c6l/platformio.ini +++ b/variants/m5stack_unit_c6l/platformio.ini @@ -2,6 +2,7 @@ extends = esp32c6_base board = esp32-c6-devkitm-1 board_build.partitions = min_spiffs.csv ; get around 4mb flash limit +board_build.flash_mode = dio ; board manifest defaults to qio, which causes a boot crash-loop on this module build_flags = ${esp32c6_base.build_flags} ${sensor_base.build_flags} From 8c0d5aee925e456b627ca1c9991c5103d67c8ea7 Mon Sep 17 00:00:00 2001 From: me <jiroiset@gmail.com> Date: Sat, 1 Aug 2026 23:48:20 -0700 Subject: [PATCH 069/381] Add USB CDC flags to M5Stack Unit C6L kiss_modem env M5Stack_Unit_C6L_kiss_modem env was missing ARDUINO_USB_CDC_ON_BOOT, ARDUINO_USB_MODE, and ENABLE_USB_INTERFACE build flags, present in the companion_radio_usb env for the same board. Without these, ESP32-C6 native USB serial output goes to UART0 (unconnected on this board), making the KISS modem unresponsive over USB. Hardware-verified: M5Stack Unit C6L, KISS modem confirmed operational via /dev/ttyACM0 with openhop_repeater. --- variants/m5stack_unit_c6l/platformio.ini | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/variants/m5stack_unit_c6l/platformio.ini b/variants/m5stack_unit_c6l/platformio.ini index 190add04..388532e0 100644 --- a/variants/m5stack_unit_c6l/platformio.ini +++ b/variants/m5stack_unit_c6l/platformio.ini @@ -109,5 +109,9 @@ lib_deps = [env:M5Stack_Unit_C6L_kiss_modem] extends = M5Stack_Unit_C6L +build_flags = ${M5Stack_Unit_C6L.build_flags} + -D ARDUINO_USB_CDC_ON_BOOT=1 + -D ARDUINO_USB_MODE=1 + -D ENABLE_USB_INTERFACE build_src_filter = ${M5Stack_Unit_C6L.build_src_filter} +<../examples/kiss_modem/> From 02bb3bbad84dc44f1adf69367de3e752801b3577 Mon Sep 17 00:00:00 2001 From: Huw Duddy <37787853+oltaco@users.noreply.github.com> Date: Mon, 3 Aug 2026 22:57:34 +1000 Subject: [PATCH 070/381] Clean up comments in startReceive method Removed unnecessary comments regarding RX timeout and IRQ mask. --- src/helpers/radiolib/CustomLR1110.h | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/helpers/radiolib/CustomLR1110.h b/src/helpers/radiolib/CustomLR1110.h index 56a9aa6e..75674a1d 100644 --- a/src/helpers/radiolib/CustomLR1110.h +++ b/src/helpers/radiolib/CustomLR1110.h @@ -37,13 +37,6 @@ class CustomLR1110 : public LR1110 { int16_t startReceive() override { // include the PREAMBLE_DETECTED irq bit in reported flags. - // - // NOTE: the first argument is the RX *timeout*, not an IRQ mask. Passing - // RADIOLIB_LR11X0_IRQ_PREAMBLE_DETECTED (1<<4 = 16) here armed the receiver - // with a 16-tick timeout -- at the LR11x0's 30.52us tick that is a ~488us - // receive window, so the radio dropped out of RX before any packet could - // arrive and the node never received anything. It must stay RX_TIMEOUT_INF - // (continuous RX), which is what LR11x0::startReceive() itself passes. return LR1110::startReceive(RADIOLIB_LR11X0_RX_TIMEOUT_INF, RADIOLIB_IRQ_RX_DEFAULT_FLAGS | (1UL << RADIOLIB_IRQ_PREAMBLE_DETECTED), RADIOLIB_IRQ_RX_DEFAULT_MASK, 0); } @@ -99,4 +92,4 @@ class CustomLR1110 : public LR1110 { } uint8_t getSpreadingFactor() const { return spreadingFactor; } -}; \ No newline at end of file +}; From c63f7d77f70cca5596822d12cd2e711478841a82 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Tue, 4 Aug 2026 01:00:31 +1000 Subject: [PATCH 071/381] * bounds check added for anon_req reply_path_len --- examples/simple_repeater/MyMesh.cpp | 28 ++++++++++++---------------- examples/simple_repeater/MyMesh.h | 3 +-- 2 files changed, 13 insertions(+), 18 deletions(-) diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index 09f74cbe..c7e651a1 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -147,11 +147,10 @@ uint8_t MyMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* secr uint8_t MyMesh::handleAnonRegionsReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data) { if (anon_limiter.allow(rtc_clock.getCurrentTime())) { // request data has: {reply-path-len}{reply-path} - reply_path_len = *data & 63; - reply_path_hash_size = (*data >> 6) + 1; - data++; + reply_path_len = *data++; + if (!mesh::Packet::isValidPathLen(reply_path_len)) return 0; // reject - bad encoding - memcpy(reply_path, data, ((uint8_t)reply_path_len) * reply_path_hash_size); + mesh::Packet::writePath(reply_path, data, reply_path_len); // data += (uint8_t)reply_path_len * reply_path_hash_size; memcpy(reply_data, &sender_timestamp, 4); // prefix with sender_timestamp, like a tag @@ -166,11 +165,10 @@ uint8_t MyMesh::handleAnonRegionsReq(const mesh::Identity& sender, uint32_t send uint8_t MyMesh::handleAnonOwnerReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data) { if (anon_limiter.allow(rtc_clock.getCurrentTime())) { // request data has: {reply-path-len}{reply-path} - reply_path_len = *data & 63; - reply_path_hash_size = (*data >> 6) + 1; - data++; + reply_path_len = *data++; + if (!mesh::Packet::isValidPathLen(reply_path_len)) return 0; // reject - bad encoding - memcpy(reply_path, data, ((uint8_t)reply_path_len) * reply_path_hash_size); + mesh::Packet::writePath(reply_path, data, reply_path_len); // data += (uint8_t)reply_path_len * reply_path_hash_size; memcpy(reply_data, &sender_timestamp, 4); // prefix with sender_timestamp, like a tag @@ -186,11 +184,10 @@ uint8_t MyMesh::handleAnonOwnerReq(const mesh::Identity& sender, uint32_t sender uint8_t MyMesh::handleAnonClockReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data) { if (anon_limiter.allow(rtc_clock.getCurrentTime())) { // request data has: {reply-path-len}{reply-path} - reply_path_len = *data & 63; - reply_path_hash_size = (*data >> 6) + 1; - data++; + reply_path_len = *data++; + if (!mesh::Packet::isValidPathLen(reply_path_len)) return 0; // reject - bad encoding - memcpy(reply_path, data, ((uint8_t)reply_path_len) * reply_path_hash_size); + mesh::Packet::writePath(reply_path, data, reply_path_len); // data += (uint8_t)reply_path_len * reply_path_hash_size; memcpy(reply_data, &sender_timestamp, 4); // prefix with sender_timestamp, like a tag @@ -574,7 +571,7 @@ void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const m data[len] = 0; // ensure null terminator uint8_t reply_len; - reply_path_len = -1; + reply_path_len = 0xFF; if (data[4] == 0 || data[4] >= ' ') { // is password, ie. a login request reply_len = handleLoginReq(sender, secret, timestamp, &data[4], packet->isRouteFlood()); } else if (data[4] == ANON_REQ_TYPE_REGIONS && packet->isRouteDirect()) { @@ -594,13 +591,12 @@ void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const m mesh::Packet* path = createPathReturn(sender, secret, packet->path, packet->path_len, PAYLOAD_TYPE_RESPONSE, reply_data, reply_len); if (path) sendFloodReply(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize()); - } else if (reply_path_len < 0) { + } else if (reply_path_len == 0xFF) { mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len); if (reply) sendFloodReply(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize()); } else { mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len); - uint8_t path_len = ((reply_path_hash_size - 1) << 6) | (reply_path_len & 63); - if (reply) sendDirect(reply, reply_path, path_len, SERVER_RESPONSE_DELAY); + if (reply) sendDirect(reply, reply_path, reply_path_len, SERVER_RESPONSE_DELAY); } } } diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index aa7d30b0..19022b77 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -92,8 +92,7 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { CommonCLI _cli; uint8_t reply_data[MAX_PACKET_PAYLOAD]; uint8_t reply_path[MAX_PATH_SIZE]; - int8_t reply_path_len; - uint8_t reply_path_hash_size; + uint8_t reply_path_len; TransportKeyStore key_store; RegionMap region_map, temp_map; RegionEntry* load_stack[8]; From 34156ddb1198f084400e6674cb4861894d096e54 Mon Sep 17 00:00:00 2001 From: ViezeVingertjes <michael.overhorst@gmail.com> Date: Mon, 3 Aug 2026 22:55:13 +0200 Subject: [PATCH 072/381] Fix replies dropped when flood.max.unscoped is low --- examples/simple_repeater/MyMesh.cpp | 57 ++++++--- examples/simple_repeater/MyMesh.h | 1 + examples/simple_room_server/MyMesh.cpp | 31 +++-- examples/simple_room_server/MyMesh.h | 1 + src/helpers/RoutingPolicy.h | 68 +++++++++++ .../test_routing_policy.cpp | 110 ++++++++++++++++++ 6 files changed, 237 insertions(+), 31 deletions(-) create mode 100644 src/helpers/RoutingPolicy.h create mode 100644 test/test_routing_policy/test_routing_policy.cpp diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index 09f74cbe..0d2f5c86 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -414,24 +414,31 @@ bool MyMesh::isLooped(const mesh::Packet* packet, const uint8_t max_counters[]) } void MyMesh::sendFloodReply(mesh::Packet* packet, unsigned long delay_millis, uint8_t path_hash_size) { - if (recv_pkt_region && !recv_pkt_region->isWildcard()) { // if _request_ packet scope is known, send reply with same scope - TransportKey scope; - if (region_map.getTransportKeysFor(*recv_pkt_region, &scope, 1) > 0) { - sendFloodScoped(scope, packet, delay_millis, path_hash_size); - } else { + TransportKey req_scope; + bool is_wildcard = recv_pkt_region != NULL && recv_pkt_region->isWildcard(); + bool req_scope_known = recv_pkt_region != NULL && !is_wildcard + && region_map.getTransportKeysFor(*recv_pkt_region, &req_scope, 1) > 0; + + switch (mesh::chooseReplyScope(req_scope_known, is_wildcard, !default_scope.isNull())) { + case mesh::REPLY_SCOPE_REQUEST: + sendFloodScoped(req_scope, packet, delay_millis, path_hash_size); // reply with same scope as request + break; + case mesh::REPLY_SCOPE_DEFAULT: + // requester's scope is unknown: DIRECT request (no transport codes), or code matched no Region. + // un-scoped would be dropped at hop 0 by repeaters running flood.max.unscoped=0 + sendFloodScoped(default_scope, packet, delay_millis, path_hash_size); + break; + case mesh::REPLY_SCOPE_NONE: sendFlood(packet, delay_millis, path_hash_size); // send un-scoped - } - } else { - sendFlood(packet, delay_millis, path_hash_size); // send un-scoped + break; } } bool MyMesh::allowPacketForward(const mesh::Packet *packet) { if (_prefs.disable_fwd) return false; - if (packet->isRouteFlood()) { - if (packet->getPathHashCount() >= _prefs.flood_max) return false; - if (packet->getRouteType() == ROUTE_TYPE_FLOOD && packet->getPathHashCount() >= _prefs.flood_max_unscoped) return false; - if (packet->getPayloadType() == PAYLOAD_TYPE_ADVERT && packet->getPathHashCount() >= _prefs.flood_max_advert) return false; + if (packet->isRouteFlood() + && mesh::isFloodHopLimitExceeded(packet, _prefs.flood_max, _prefs.flood_max_unscoped, _prefs.flood_max_advert)) { + return false; } if (packet->isRouteFlood() && recv_pkt_region == NULL) { MESH_DEBUG_PRINTLN("allowPacketForward: unknown transport code, or wildcard not allowed for FLOOD packet"); @@ -589,18 +596,30 @@ void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const m if (reply_len == 0) return; // invalid request - if (packet->isRouteFlood()) { + // a DIRECT login can reply via the stored out_path, as onPeerDataRecv() does for REQ + ClientInfo* client = acl.getClient(sender.pub_key, PUB_KEY_SIZE); + bool have_out_path = client != NULL && client->out_path_len != OUT_PATH_UNKNOWN; + + auto route = mesh::chooseReplyRoute(packet->isRouteFlood(), reply_path_len >= 0, have_out_path); + + if (route == mesh::REPLY_ROUTE_PATH_RETURN) { // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response mesh::Packet* path = createPathReturn(sender, secret, packet->path, packet->path_len, PAYLOAD_TYPE_RESPONSE, reply_data, reply_len); if (path) sendFloodReply(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize()); - } else if (reply_path_len < 0) { - mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len); - if (reply) sendFloodReply(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize()); - } else { - mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len); + return; + } + + mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len); + if (reply == NULL) return; + + if (route == mesh::REPLY_ROUTE_DIRECT_SUPPLIED) { uint8_t path_len = ((reply_path_hash_size - 1) << 6) | (reply_path_len & 63); - if (reply) sendDirect(reply, reply_path, path_len, SERVER_RESPONSE_DELAY); + sendDirect(reply, reply_path, path_len, SERVER_RESPONSE_DELAY); + } else if (route == mesh::REPLY_ROUTE_DIRECT_OUT_PATH) { + sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY); + } else { + sendFloodReply(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize()); } } } diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index aa7d30b0..f1a1bcff 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -34,6 +34,7 @@ #include <helpers/StatsFormatHelper.h> #include <helpers/TxtDataHelpers.h> #include <helpers/RegionMap.h> +#include <helpers/RoutingPolicy.h> #include "RateLimiter.h" #ifdef WITH_BRIDGE diff --git a/examples/simple_room_server/MyMesh.cpp b/examples/simple_room_server/MyMesh.cpp index 0aff39cc..b951f427 100644 --- a/examples/simple_room_server/MyMesh.cpp +++ b/examples/simple_room_server/MyMesh.cpp @@ -299,10 +299,9 @@ uint32_t MyMesh::getDirectRetransmitDelay(const mesh::Packet *packet) { bool MyMesh::allowPacketForward(const mesh::Packet *packet) { if (_prefs.disable_fwd) return false; - if (packet->isRouteFlood()) { - if (packet->getPathHashCount() >= _prefs.flood_max) return false; - if (packet->getRouteType() == ROUTE_TYPE_FLOOD && packet->getPathHashCount() >= _prefs.flood_max_unscoped) return false; - if (packet->getPayloadType() == PAYLOAD_TYPE_ADVERT && packet->getPathHashCount() >= _prefs.flood_max_advert) return false; + if (packet->isRouteFlood() + && mesh::isFloodHopLimitExceeded(packet, _prefs.flood_max, _prefs.flood_max_unscoped, _prefs.flood_max_advert)) { + return false; } return true; } @@ -749,15 +748,23 @@ void MyMesh::sendFloodScoped(const TransportKey& scope, mesh::Packet* pkt, uint3 } void MyMesh::sendFloodReply(mesh::Packet* packet, unsigned long delay_millis, uint8_t path_hash_size) { - if (recv_pkt_region && !recv_pkt_region->isWildcard()) { // if _request_ packet scope is known, send reply with same scope - TransportKey scope; - if (region_map.getTransportKeysFor(*recv_pkt_region, &scope, 1) > 0) { - sendFloodScoped(scope, packet, delay_millis, path_hash_size); - } else { + TransportKey req_scope; + bool is_wildcard = recv_pkt_region != NULL && recv_pkt_region->isWildcard(); + bool req_scope_known = recv_pkt_region != NULL && !is_wildcard + && region_map.getTransportKeysFor(*recv_pkt_region, &req_scope, 1) > 0; + + switch (mesh::chooseReplyScope(req_scope_known, is_wildcard, !default_scope.isNull())) { + case mesh::REPLY_SCOPE_REQUEST: + sendFloodScoped(req_scope, packet, delay_millis, path_hash_size); // reply with same scope as request + break; + case mesh::REPLY_SCOPE_DEFAULT: + // requester's scope is unknown: DIRECT request (no transport codes), or code matched no Region. + // un-scoped would be dropped at hop 0 by repeaters running flood.max.unscoped=0 + sendFloodScoped(default_scope, packet, delay_millis, path_hash_size); + break; + case mesh::REPLY_SCOPE_NONE: sendFlood(packet, delay_millis, path_hash_size); // send un-scoped - } - } else { - sendFlood(packet, delay_millis, path_hash_size); // send un-scoped + break; } } diff --git a/examples/simple_room_server/MyMesh.h b/examples/simple_room_server/MyMesh.h index 5f78bee8..a45ed9cd 100644 --- a/examples/simple_room_server/MyMesh.h +++ b/examples/simple_room_server/MyMesh.h @@ -21,6 +21,7 @@ #include <helpers/StatsFormatHelper.h> #include <helpers/ClientACL.h> #include <helpers/RegionMap.h> +#include <helpers/RoutingPolicy.h> #include <RTClib.h> #include <target.h> diff --git a/src/helpers/RoutingPolicy.h b/src/helpers/RoutingPolicy.h new file mode 100644 index 00000000..5251a590 --- /dev/null +++ b/src/helpers/RoutingPolicy.h @@ -0,0 +1,68 @@ +#pragma once + +#include <Packet.h> + +namespace mesh { + +/** + * \brief Test a flood packet against the configured hop limits. + * \param packet inbound flood packet (caller has already checked isRouteFlood()) + * \param flood_max max hops for any flood packet + * \param flood_max_unscoped max hops for ROUTE_TYPE_FLOOD (ie. un-scoped) packets + * \param flood_max_advert max hops for ADVERT packets + * \returns true if the packet has exceeded a limit, and must not be forwarded + */ +inline bool isFloodHopLimitExceeded(const Packet* packet, uint8_t flood_max, + uint8_t flood_max_unscoped, uint8_t flood_max_advert) { + uint8_t hops = packet->getPathHashCount(); + if (hops >= flood_max) return true; + if (packet->getRouteType() == ROUTE_TYPE_FLOOD && hops >= flood_max_unscoped) return true; + if (packet->getPayloadType() == PAYLOAD_TYPE_ADVERT && hops >= flood_max_advert) return true; + return false; +} + +/** + * \brief How a server routes a reply back to the requesting client. + */ +enum ReplyRoute : uint8_t { + REPLY_ROUTE_PATH_RETURN, // request arrived by flood: reply with a PATH return, flooded back + REPLY_ROUTE_DIRECT_SUPPLIED, // reply DIRECT, along the return path supplied in the request + REPLY_ROUTE_DIRECT_OUT_PATH, // reply DIRECT, along the out_path already stored for this client + REPLY_ROUTE_FLOOD, // no return path known: flood the reply +}; + +/** + * \param inbound_is_flood the request arrived as a flood packet + * \param have_supplied_path the request payload carried an explicit reply path + * \param have_out_path this server already has a stored out_path for the client + */ +inline ReplyRoute chooseReplyRoute(bool inbound_is_flood, bool have_supplied_path, bool have_out_path) { + if (inbound_is_flood) return REPLY_ROUTE_PATH_RETURN; + if (have_supplied_path) return REPLY_ROUTE_DIRECT_SUPPLIED; + if (have_out_path) return REPLY_ROUTE_DIRECT_OUT_PATH; + return REPLY_ROUTE_FLOOD; +} + +/** + * \brief Which transport scope a flooded reply should be sent with. + */ +enum ReplyScope : uint8_t { + REPLY_SCOPE_REQUEST, // re-use the scope the request arrived on + REPLY_SCOPE_DEFAULT, // fall back to this node's default region scope + REPLY_SCOPE_NONE, // send un-scoped (ROUTE_TYPE_FLOOD) +}; + +/** + * \param request_scope_known request arrived scoped, and we resolved its Region's key + * \param request_was_unscoped_flood request arrived as an un-scoped flood + * \param default_scope_known this node has a default Region with a usable transport key + */ +inline ReplyScope chooseReplyScope(bool request_scope_known, bool request_was_unscoped_flood, + bool default_scope_known) { + if (request_scope_known) return REPLY_SCOPE_REQUEST; + if (request_was_unscoped_flood) return REPLY_SCOPE_NONE; // requester chose un-scoped, so mirror it + if (default_scope_known) return REPLY_SCOPE_DEFAULT; // scope unknowable: DIRECT, or unresolved Region + return REPLY_SCOPE_NONE; +} + +} diff --git a/test/test_routing_policy/test_routing_policy.cpp b/test/test_routing_policy/test_routing_policy.cpp new file mode 100644 index 00000000..bba9ec79 --- /dev/null +++ b/test/test_routing_policy/test_routing_policy.cpp @@ -0,0 +1,110 @@ +#include <gtest/gtest.h> +#include "helpers/RoutingPolicy.h" + +using namespace mesh; + +static Packet makeFlood(uint8_t route_type, uint8_t payload_type, uint8_t hops) { + Packet p; + p.header = route_type | (payload_type << PH_TYPE_SHIFT); + p.setPathHashSizeAndCount(1, hops); + p.payload_len = 1; + return p; +} + +TEST(FloodHopLimit, UnscopedFloodIsDroppedAtFirstHopWhenMaxUnscopedIsZero) { + auto pkt = makeFlood(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_RESPONSE, 0); + EXPECT_TRUE(isFloodHopLimitExceeded(&pkt, 64, 0, 8)); +} + +TEST(FloodHopLimit, ScopedFloodIsForwardedWhenMaxUnscopedIsZero) { + for (uint8_t hops = 0; hops < 4; hops++) { + auto pkt = makeFlood(ROUTE_TYPE_TRANSPORT_FLOOD, PAYLOAD_TYPE_RESPONSE, hops); + EXPECT_FALSE(isFloodHopLimitExceeded(&pkt, 64, 0, 8)) << "hops=" << (int)hops; + } +} + +TEST(FloodHopLimit, UnscopedFloodSurvivesUpToMaxUnscopedHops) { + // matches the reported workaround: raising flood.max.unscoped to the expected hop count + auto ok = makeFlood(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_RESPONSE, 2); + EXPECT_FALSE(isFloodHopLimitExceeded(&ok, 64, 3, 8)); + + auto too_far = makeFlood(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_RESPONSE, 3); + EXPECT_TRUE(isFloodHopLimitExceeded(&too_far, 64, 3, 8)); +} + +TEST(FloodHopLimit, ScopedFloodStillHonoursFloodMaxAndAdvertMax) { + auto beyond_max = makeFlood(ROUTE_TYPE_TRANSPORT_FLOOD, PAYLOAD_TYPE_RESPONSE, 5); + EXPECT_TRUE(isFloodHopLimitExceeded(&beyond_max, 5, 64, 8)); + + auto advert = makeFlood(ROUTE_TYPE_TRANSPORT_FLOOD, PAYLOAD_TYPE_ADVERT, 8); + EXPECT_TRUE(isFloodHopLimitExceeded(&advert, 64, 64, 8)); +} + +// flood.max.unscoped=0 hits adverts too, well before flood_max_advert applies: a node +// still advertising un-scoped is invisible past its immediate neighbours +TEST(FloodHopLimit, UnscopedAdvertIsAlsoDroppedAtHopZero) { + auto advert = makeFlood(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_ADVERT, 0); + EXPECT_TRUE(isFloodHopLimitExceeded(&advert, 64, 0, 8)); + + auto scoped = makeFlood(ROUTE_TYPE_TRANSPORT_FLOOD, PAYLOAD_TYPE_ADVERT, 0); + EXPECT_FALSE(isFloodHopLimitExceeded(&scoped, 64, 0, 8)); +} + +TEST(ReplyRoute, FloodRequestGetsAPathReturn) { + EXPECT_EQ(REPLY_ROUTE_PATH_RETURN, + chooseReplyRoute(true, false, false)); + EXPECT_EQ(REPLY_ROUTE_PATH_RETURN, + chooseReplyRoute(true, false, true)); +} + +TEST(ReplyRoute, DirectRequestWithSuppliedPathRepliesDirect) { + EXPECT_EQ(REPLY_ROUTE_DIRECT_SUPPLIED, chooseReplyRoute(false, true, false)); +} + +// the reported bug: a DIRECT login (app already has a path) was answered by flooding, even +// with an out_path stored. Under flood.max.unscoped=0 that reply never arrives. +TEST(ReplyRoute, DirectRequestWithKnownOutPathRepliesDirect) { + EXPECT_EQ(REPLY_ROUTE_DIRECT_OUT_PATH, + chooseReplyRoute(false, false, true)); +} + +TEST(ReplyRoute, SuppliedPathWinsOverStoredOutPath) { + EXPECT_EQ(REPLY_ROUTE_DIRECT_SUPPLIED, chooseReplyRoute(false, true, true)); +} + +TEST(ReplyRoute, DirectRequestWithNoReturnPathFallsBackToFlood) { + EXPECT_EQ(REPLY_ROUTE_FLOOD, chooseReplyRoute(false, false, false)); +} + +TEST(ReplyScope, MirrorsTheRequestScopeWhenKnown) { + EXPECT_EQ(REPLY_SCOPE_REQUEST, chooseReplyScope(true, + false, + false)); + EXPECT_EQ(REPLY_SCOPE_REQUEST, chooseReplyScope(true, false, true)); +} + +// un-scoped is itself a known scope, so mirror it. Replying scoped would change a path that +// works today, and repeaters not holding our default Region would drop it anyway. +TEST(ReplyScope, RepliesUnscopedToAnUnscopedFloodEvenWhenADefaultScopeExists) { + EXPECT_EQ(REPLY_SCOPE_NONE, chooseReplyScope(false, + true, + true)); +} + +// second half of the bug: a DIRECT request carries no transport codes, so recv_pkt_region is +// always NULL. Un-scoped is dropped under flood.max.unscoped=0, and floods the mesh otherwise. +TEST(ReplyScope, FallsBackToDefaultScopeWhenRequestScopeUnknown) { + EXPECT_EQ(REPLY_SCOPE_DEFAULT, chooseReplyScope(false, + false, + true)); +} + +TEST(ReplyScope, SendsUnscopedOnlyWhenNoScopeIsAvailableAtAll) { + EXPECT_EQ(REPLY_SCOPE_NONE, chooseReplyScope(false, false, false)); + EXPECT_EQ(REPLY_SCOPE_NONE, chooseReplyScope(false, true, false)); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} From e2d050df9f5137fcd025104351cece0b12edaffe Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Wed, 5 Aug 2026 14:23:29 +1000 Subject: [PATCH 073/381] add Meshnology W12 support and LR2021 wrapper --- boards/meshnology_w12.json | 43 ++++ src/helpers/radiolib/CustomLR2021.h | 76 ++++++ src/helpers/radiolib/CustomLR2021Wrapper.h | 57 +++++ src/helpers/radiolib/RadioLibWrappers.cpp | 4 + .../meshnology_w12/MeshnologyW12Board.cpp | 83 +++++++ variants/meshnology_w12/MeshnologyW12Board.h | 37 +++ variants/meshnology_w12/pins_arduino.h | 69 ++++++ variants/meshnology_w12/platformio.ini | 216 ++++++++++++++++++ variants/meshnology_w12/target.cpp | 73 ++++++ variants/meshnology_w12/target.h | 28 +++ 10 files changed, 686 insertions(+) create mode 100644 boards/meshnology_w12.json create mode 100644 src/helpers/radiolib/CustomLR2021.h create mode 100644 src/helpers/radiolib/CustomLR2021Wrapper.h create mode 100644 variants/meshnology_w12/MeshnologyW12Board.cpp create mode 100644 variants/meshnology_w12/MeshnologyW12Board.h create mode 100644 variants/meshnology_w12/pins_arduino.h create mode 100644 variants/meshnology_w12/platformio.ini create mode 100644 variants/meshnology_w12/target.cpp create mode 100644 variants/meshnology_w12/target.h diff --git a/boards/meshnology_w12.json b/boards/meshnology_w12.json new file mode 100644 index 00000000..2e74af9b --- /dev/null +++ b/boards/meshnology_w12.json @@ -0,0 +1,43 @@ +{ + "build": { + "arduino": { + "ldscript": "esp32s3_out.ld", + "partitions": "default_16MB.csv", + "memory_type": "qio_opi" + }, + "core": "esp32", + "extra_flags": [ + "-DBOARD_HAS_PSRAM", + "-DARDUINO_USB_CDC_ON_BOOT=1", + "-DARDUINO_USB_MODE=1", + "-DARDUINO_RUNNING_CORE=1", + "-DARDUINO_EVENT_RUNNING_CORE=1" + ], + "f_cpu": "240000000L", + "f_flash": "80000000L", + "flash_mode": "qio", + "psram_type": "opi", + "hwids": [["0x303A", "0x0002"], ["0x303A", "0x1001"]], + "mcu": "esp32s3", + "variant": "meshnology_w12" + }, + "connectivity": ["wifi", "bluetooth", "lora"], + "debug": { + "default_tool": "esp-builtin", + "onboard_tools": ["esp-builtin"], + "openocd_target": "esp32s3.cfg" + }, + "frameworks": ["arduino", "espidf"], + "name": "heltec_wifi_lora_32 v5 (16 MB FLASH, 8 MB PSRAM)", + "upload": { + "flash_size": "16MB", + "maximum_ram_size": 327680, + "maximum_size": 16777216, + "use_1200bps_touch": true, + "wait_for_upload_port": true, + "require_upload_port": true, + "speed": 921600 + }, + "url": "https://heltec.org/", + "vendor": "heltec" +} \ No newline at end of file diff --git a/src/helpers/radiolib/CustomLR2021.h b/src/helpers/radiolib/CustomLR2021.h new file mode 100644 index 00000000..17944ef0 --- /dev/null +++ b/src/helpers/radiolib/CustomLR2021.h @@ -0,0 +1,76 @@ +#pragma once + +#include <RadioLib.h> +#include "MeshCore.h" + +class CustomLR2021 : public LR2021 { + bool _rx_boosted = false; + + public: + CustomLR2021(Module *mod) : LR2021(mod) { irqDioNum = LR2021_IRQ_DIO; } + + bool std_init(SPIClass* spi = NULL) + { + + #ifdef LR2021_TCXO_VOLTAGE + float tcxo = LR2021_TCXO_VOLTAGE; + #else + float tcxo = 1.6f; + #endif + + #ifdef LORA_CR + uint8_t cr = LORA_CR; + #else + uint8_t cr = 5; + #endif + + #if defined(P_LORA_SCLK) + #ifdef NRF52_PLATFORM + if (spi) { spi->setPins(P_LORA_MISO, P_LORA_SCLK, P_LORA_MOSI); spi->begin(); } + #elif defined(RP2040_PLATFORM) + if (spi) { + spi->setMISO(P_LORA_MISO); + //spi->setCS(P_LORA_NSS); // Setting CS results in freeze + spi->setSCK(P_LORA_SCLK); + spi->setMOSI(P_LORA_MOSI); + spi->begin(); + } + #else + if (spi) spi->begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI); + #endif + #endif + int status = begin(LORA_FREQ, LORA_BW, LORA_SF, cr, RADIOLIB_LR2021_LORA_SYNC_WORD_PRIVATE, LORA_TX_POWER, 16, tcxo); + // if radio init fails with -707/-706, try again with tcxo voltage set to 0.0f + if (status == RADIOLIB_ERR_SPI_CMD_FAILED || status == RADIOLIB_ERR_SPI_CMD_INVALID) { + tcxo = 0.0f; + status = begin(LORA_FREQ, LORA_BW, LORA_SF, cr, RADIOLIB_LR2021_LORA_SYNC_WORD_PRIVATE, LORA_TX_POWER, 16, tcxo); + } + if (status != RADIOLIB_ERR_NONE) { + Serial.print("ERROR: radio init failed: "); + Serial.println(status); + return false; // fail + } + + setCRC(2); + explicitHeader(); + + + #ifdef LR2021_RX_BOOSTED_GAIN + setRxBoostedGainMode(LR2021_RX_BOOSTED_GAIN); + #endif + + return true; // success + } + + float getFreqMHz() const { return freqMHz; } + + bool getRxBoostedGainMode() const { return _rx_boosted; } + + bool isReceiving() { + uint32_t irq = getIrqStatus(); + bool detected = ((irq & RADIOLIB_LR2021_IRQ_SYNCWORD_VALID) || (irq & RADIOLIB_LR2021_IRQ_PREAMBLE_DETECTED)); + return detected; + } + + uint8_t getSpreadingFactor() const { return spreadingFactor; } +}; \ No newline at end of file diff --git a/src/helpers/radiolib/CustomLR2021Wrapper.h b/src/helpers/radiolib/CustomLR2021Wrapper.h new file mode 100644 index 00000000..0f1b1f9e --- /dev/null +++ b/src/helpers/radiolib/CustomLR2021Wrapper.h @@ -0,0 +1,57 @@ +#pragma once + +#include "CustomLR2021.h" +#include "RadioLibWrappers.h" + +#ifndef USE_LR2021 +#define USE_LR2021 +#endif + +#ifndef LR2021_RX_BOOST_LEVEL +#define LR2021_RX_BOOST_LEVEL 7 +#endif + +class CustomLR2021Wrapper : public RadioLibWrapper { +public: + CustomLR2021Wrapper(CustomLR2021& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { } + + void setParams(float freq, float bw, uint8_t sf, uint8_t cr) override { + ((CustomLR2021 *)_radio)->setFrequency(freq); + ((CustomLR2021 *)_radio)->setSpreadingFactor(sf); + ((CustomLR2021 *)_radio)->setBandwidth(bw); + ((CustomLR2021 *)_radio)->setCodingRate(cr); + updatePreamble(sf); + } + + bool isReceivingPacket() override { + return ((CustomLR2021 *)_radio)->isReceiving(); + } + + float getCurrentRSSI() override { + float rssi = -110; + ((CustomLR2021 *)_radio)->getRssiInst(&rssi); + return rssi; + } + + void onSendFinished() override { + RadioLibWrapper::onSendFinished(); + _radio->setPreambleLength(preambleLengthForSF(getSpreadingFactor())); // overcomes weird issues with small and big pkts + } + + float getLastRSSI() const override { return ((CustomLR2021 *)_radio)->getRSSI(); } + float getLastSNR() const override { return ((CustomLR2021 *)_radio)->getSNR(); } + + uint8_t getSpreadingFactor() const override { return ((CustomLR2021 *)_radio)->getSpreadingFactor(); } + + bool setRxBoostedGainMode(bool en) override { + ((CustomLR2021 *)_radio)->standby(); // radio must be in standby to accept the setRxBoostedGainMode command, otherwise it returns -707 error. + int16_t status = ((CustomLR2021 *)_radio)->setRxBoostedGainMode(en ? LR2021_RX_BOOST_LEVEL: 0); + RadioLibWrapper::idle(); // trigger startReceive() + return status == RADIOLIB_ERR_NONE; + } + + bool getRxBoostedGainMode() const override { + return ((CustomLR2021 *)_radio)->getRxBoostedGainMode(); + } + +}; diff --git a/src/helpers/radiolib/RadioLibWrappers.cpp b/src/helpers/radiolib/RadioLibWrappers.cpp index 7146e47b..c2bd6b26 100644 --- a/src/helpers/radiolib/RadioLibWrappers.cpp +++ b/src/helpers/radiolib/RadioLibWrappers.cpp @@ -133,7 +133,11 @@ int RadioLibWrapper::recvRaw(uint8_t* bytes, int sz) { n_recv++; } } + #if defined(USE_LR2021) + state = STATE_RX; // LR2021 stays in Rx after readData, if we issue another startReceive while still in Rx we get -706 errors. + #else state = STATE_IDLE; // need another startReceive() + #endif } if (state != STATE_RX) { diff --git a/variants/meshnology_w12/MeshnologyW12Board.cpp b/variants/meshnology_w12/MeshnologyW12Board.cpp new file mode 100644 index 00000000..25c0d4f1 --- /dev/null +++ b/variants/meshnology_w12/MeshnologyW12Board.cpp @@ -0,0 +1,83 @@ +#include "MeshnologyW12Board.h" + +void MeshnologyW12Board::begin() { + ESP32Board::begin(); + + pinMode(PIN_ADC_CTRL, OUTPUT); + digitalWrite(PIN_ADC_CTRL, LOW); // Disable battery sense until required + + pinMode(P_LORA_LF_PA_POWER, OUTPUT); + digitalWrite(P_LORA_LF_PA_POWER, HIGH); // PA_EN_M — power the GC1109 FEM + + pinMode(P_LORA_HF_PA_POWER, OUTPUT); + digitalWrite(P_LORA_HF_PA_POWER, LOW); // PA_EN_G — disable the 2.4GHz FEM + + delay(100); // give the GC1109 some time to start + + periph_power.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 MeshnologyW12Board::onBeforeTransmit(void) { + neopixelWrite(NEOPIXEL_LED, NEOPIXEL_BRIGHTNESS, NEOPIXEL_BRIGHTNESS, NEOPIXEL_BRIGHTNESS); // turn TX neopixel on (White) + } + + void MeshnologyW12Board::onAfterTransmit(void) { + neopixelWrite(NEOPIXEL_LED, 0, 0, 0); // turn TX neopixel off + } + + void MeshnologyW12Board::enterDeepSleep(uint32_t secs, int pin_wake_btn) { + 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! + } + + void MeshnologyW12Board::powerOff() { + enterDeepSleep(0); + } + + uint16_t MeshnologyW12Board::getBattMilliVolts() { + analogReadResolution(12); + analogSetAttenuation(ADC_11db); + digitalWrite(PIN_ADC_CTRL, HIGH); + delay(10); + uint32_t raw = 0; + for (int i = 0; i < 8; i++) { + raw += analogRead(PIN_VBAT_READ); + } + raw = raw / 8; + + digitalWrite(PIN_ADC_CTRL, LOW); + + return (adc_mult * (3.3 / 4096.0) * raw) * 1000; + } + + const char* MeshnologyW12Board::getManufacturerName() const { + return "Meshnology W12"; + } \ No newline at end of file diff --git a/variants/meshnology_w12/MeshnologyW12Board.h b/variants/meshnology_w12/MeshnologyW12Board.h new file mode 100644 index 00000000..85bec990 --- /dev/null +++ b/variants/meshnology_w12/MeshnologyW12Board.h @@ -0,0 +1,37 @@ +#pragma once + +#include <Arduino.h> +#include <helpers/RefCountedDigitalPin.h> +#include <helpers/ESP32Board.h> +#include <driver/rtc_io.h> + +#ifndef ADC_MULTIPLIER + #define ADC_MULTIPLIER 5.42 +#endif + +class MeshnologyW12Board : public ESP32Board { + +protected: + float adc_mult = ADC_MULTIPLIER; + +public: + RefCountedDigitalPin periph_power; + MeshnologyW12Board() : periph_power(PIN_VEXT_EN, PIN_VEXT_EN_ACTIVE) { } + + void begin(); + void onBeforeTransmit(void) override; + void onAfterTransmit(void) override; + void enterDeepSleep(uint32_t secs, int pin_wake_btn = -1); + void powerOff() override; + uint16_t getBattMilliVolts() override; + bool setAdcMultiplier(float multiplier) override { + if (multiplier == 0.0f) { + adc_mult = ADC_MULTIPLIER; + } else { + adc_mult = multiplier; + } + return true; + } + float getAdcMultiplier() const override { return adc_mult; } + const char* getManufacturerName() const override; +}; diff --git a/variants/meshnology_w12/pins_arduino.h b/variants/meshnology_w12/pins_arduino.h new file mode 100644 index 00000000..5cfb3697 --- /dev/null +++ b/variants/meshnology_w12/pins_arduino.h @@ -0,0 +1,69 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include <stdint.h> + +static const uint8_t LED_BUILTIN = -1; +#define BUILTIN_LED LED_BUILTIN // backward compatibility +#define LED_BUILTIN LED_BUILTIN // allow testing #ifdef LED_BUILTIN + +static const uint8_t TX = 43; +static const uint8_t RX = 44; + +static const uint8_t SDA = 3; +static const uint8_t SCL = 4; + +static const uint8_t SS = 8; +static const uint8_t MOSI = 10; +static const uint8_t MISO = 11; +static const uint8_t SCK = 9; + +static const uint8_t A0 = 1; +static const uint8_t A1 = 2; +static const uint8_t A2 = 3; +static const uint8_t A3 = 4; +static const uint8_t A4 = 5; +static const uint8_t A5 = 6; +static const uint8_t A6 = 7; +static const uint8_t A7 = 8; +static const uint8_t A8 = 9; +static const uint8_t A9 = 10; +static const uint8_t A10 = 11; +static const uint8_t A11 = 12; +static const uint8_t A12 = 13; +static const uint8_t A13 = 14; +static const uint8_t A14 = 15; +static const uint8_t A15 = 16; +static const uint8_t A16 = 17; +static const uint8_t A17 = 18; +static const uint8_t A18 = 19; +static const uint8_t A19 = 20; + +static const uint8_t T1 = 1; +static const uint8_t T2 = 2; +static const uint8_t T3 = 3; +static const uint8_t T4 = 4; +static const uint8_t T5 = 5; +static const uint8_t T6 = 6; +static const uint8_t T7 = 7; +static const uint8_t T8 = 8; +static const uint8_t T9 = 9; +static const uint8_t T10 = 10; +static const uint8_t T11 = 11; +static const uint8_t T12 = 12; +static const uint8_t T13 = 13; +static const uint8_t T14 = 14; + +static const uint8_t Vext = 45; +static const uint8_t LED = -1; +static const uint8_t RST_OLED = 21; +static const uint8_t SCL_OLED = 18; +static const uint8_t SDA_OLED = 17; + +static const uint8_t RST_LoRa = 12; +static const uint8_t BUSY_LoRa = 13; +static const uint8_t DIO0 = 14; + + + +#endif /* Pins_Arduino_h */ \ No newline at end of file diff --git a/variants/meshnology_w12/platformio.ini b/variants/meshnology_w12/platformio.ini new file mode 100644 index 00000000..1168f10a --- /dev/null +++ b/variants/meshnology_w12/platformio.ini @@ -0,0 +1,216 @@ +[meshnology_w12] +extends = esp32_base +board = meshnology_w12 +build_flags = + ${esp32_base.build_flags} + ${sensor_base.build_flags} + -I variants/meshnology_w12 + -D MESHNOLOGY_W12 + -D ESP32_CPU_FREQ=80 + -D RADIO_CLASS=CustomLR2021 + -D WRAPPER_CLASS=CustomLR2021Wrapper + -D USE_LR2021 + -D NEOPIXEL_LED=46 + -D NEOPIXEL_BRIGHTNESS=64 + -D P_LORA_DIO_1=14 + -D LR2021_IRQ_DIO=8 ; GPIO14 is connected to LR2021 DIO8 + -D P_LORA_NSS=8 + -D P_LORA_SCLK=9 + -D P_LORA_MOSI=10 + -D P_LORA_MISO=11 + -D P_LORA_RESET=12 + -D P_LORA_BUSY=13 + -D LR2021_TCXO_VOLTAGE=0.0f ; this board has no tcxo + -D RF_SWITCH_TABLE ; used below in commented code for the RF switch table. + -D P_LORA_LF_PA_POWER=4 ; PA_EN_M - power enable for the GC1109 868/915 PA + -D P_LORA_HF_PA_POWER=3 ; PA_EN_G - power enable for RFX2402E 2.4G PA + -D PIN_USER_BTN=0 + -D PIN_VEXT_EN=45 + -D PIN_VEXT_EN_ACTIVE=HIGH + -D LORA_TX_POWER=4 + -D MAX_LORA_TX_POWER=4 ; GC1109 datasheet says max input at TX port is +5dbm, confirmed full saturation seems to occur at around 3-4dbm + -D PIN_GPS_RX=38 + -D PIN_GPS_TX=39 + -D PIN_GPS_RESET=42 + -D PIN_GPS_RESET_ACTIVE=LOW + -D PIN_GPS_EN=48 + -D PIN_GPS_EN_ACTIVE=LOW + ; -D ENV_INCLUDE_GPS=1 + -D PIN_VBAT_READ=1 + -D PIN_ADC_CTRL=2 + -D PIN_BOARD_SDA=17 + -D PIN_BOARD_SCL=18 + -D PIN_RESET=47 +build_src_filter = ${esp32_base.build_src_filter} + +<../variants/meshnology_w12> + +<helpers/sensors> +lib_deps = + ${esp32_base.lib_deps} + ${sensor_base.lib_deps} + +[env:meshnology_w12_repeater] +extends = meshnology_w12 +build_flags = + ${meshnology_w12.build_flags} + -D DISPLAY_CLASS=SSD1306Display + -D ADVERT_NAME='"Meshnology W12 Repeater"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=50 + ; -D MESH_PACKET_LOGGING=1 + ; -D MESH_DEBUG=1 +build_src_filter = ${meshnology_w12.build_src_filter} + +<helpers/ui/SSD1306Display.cpp> + +<../examples/simple_repeater> +lib_deps = + ${meshnology_w12.lib_deps} + ${esp32_ota.lib_deps} + bakercp/CRC32 @ ^2.0.0 + +[env:meshnology_w12_repeater_bridge_espnow] +extends = meshnology_w12 +build_flags = + ${meshnology_w12.build_flags} + -D DISPLAY_CLASS=SSD1306Display + -D ADVERT_NAME='"ESPNow Bridge"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=50 + -D WITH_ESPNOW_BRIDGE=1 + ; -D BRIDGE_DEBUG=1 + ; -D MESH_PACKET_LOGGING=1 + ; -D MESH_DEBUG=1 +build_src_filter = ${meshnology_w12.build_src_filter} + +<helpers/bridges/ESPNowBridge.cpp> + +<helpers/ui/SSD1306Display.cpp> + +<../examples/simple_repeater> +lib_deps = + ${meshnology_w12.lib_deps} + ${esp32_ota.lib_deps} + +[env:meshnology_w12_room_server] +extends = meshnology_w12 +build_flags = + ${meshnology_w12.build_flags} + -D DISPLAY_CLASS=SSD1306Display + -D ADVERT_NAME='"Meshnology W12 Room"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D ROOM_PASSWORD='"hello"' + ; -D MESH_PACKET_LOGGING=1 + ; -D MESH_DEBUG=1 +build_src_filter = ${meshnology_w12.build_src_filter} + +<helpers/ui/SSD1306Display.cpp> + +<../examples/simple_room_server> +lib_deps = + ${meshnology_w12.lib_deps} + ${esp32_ota.lib_deps} + +[env:meshnology_w12_terminal_chat] +extends = meshnology_w12 +build_flags = + ${meshnology_w12.build_flags} + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=1 + ; -D MESH_PACKET_LOGGING=1 + ; -D MESH_DEBUG=1 +build_src_filter = ${meshnology_w12.build_src_filter} + +<../examples/simple_secure_chat/main.cpp> +lib_deps = + ${meshnology_w12.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[env:meshnology_w12_companion_radio_usb] +extends = meshnology_w12 +build_flags = + ${meshnology_w12.build_flags} + -I examples/companion_radio/ui-new + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D DISPLAY_CLASS=SSD1306Display +; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 +; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 +build_src_filter = ${meshnology_w12.build_src_filter} + +<helpers/ui/SSD1306Display.cpp> + +<helpers/ui/MomentaryButton.cpp> + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = + ${meshnology_w12.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[env:meshnology_w12_companion_radio_ble] +extends = meshnology_w12 +build_flags = + ${meshnology_w12.build_flags} + -I examples/companion_radio/ui-new + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D DISPLAY_CLASS=SSD1306Display + -D BLE_PIN_CODE=123456 ; dynamic, random PIN + ; -D AUTO_SHUTDOWN_MILLIVOLTS=3400 ; disabled by default, otherwise reading bounce causes shutdown when there's no battery connected. + ; -D BLE_DEBUG_LOGGING=1 + -D OFFLINE_QUEUE_SIZE=256 + ; -D MESH_PACKET_LOGGING=1 + ; -D MESH_DEBUG=1 +build_src_filter = ${meshnology_w12.build_src_filter} + +<helpers/ui/SSD1306Display.cpp> + +<helpers/ui/MomentaryButton.cpp> + +<helpers/esp32/*.cpp> + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = + ${meshnology_w12.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[env:meshnology_w12_companion_radio_wifi] +extends = meshnology_w12 +build_flags = + ${meshnology_w12.build_flags} + -I examples/companion_radio/ui-new + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D OFFLINE_QUEUE_SIZE=256 + -D DISPLAY_CLASS=SSD1306Display + ; -D WIFI_DEBUG_LOGGING=1 + -D WIFI_SSID='"myssid"' + -D WIFI_PWD='"mypwd"' + ; -D MESH_PACKET_LOGGING=1 + ; -D MESH_DEBUG=1 +build_src_filter = ${meshnology_w12.build_src_filter} + +<helpers/ui/SSD1306Display.cpp> + +<helpers/ui/MomentaryButton.cpp> + +<helpers/esp32/*.cpp> + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = + ${meshnology_w12.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[env:meshnology_w12_sensor] +extends = meshnology_w12 +build_flags = + ${meshnology_w12.build_flags} + -D ADVERT_NAME='"Meshnology W12 Sensor"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D ENV_PIN_SDA=3 + -D ENV_PIN_SCL=4 + -D DISPLAY_CLASS=SSD1306Display + ; -D MESH_PACKET_LOGGING=1 + ; -D MESH_DEBUG=1 +build_src_filter = ${meshnology_w12.build_src_filter} + +<helpers/ui/SSD1306Display.cpp> + +<../examples/simple_sensor> +lib_deps = + ${meshnology_w12.lib_deps} + ${esp32_ota.lib_deps} + +[env:meshnology_w12_kiss_modem] +extends = meshnology_w12 +build_src_filter = ${meshnology_w12.build_src_filter} + +<../examples/kiss_modem/> diff --git a/variants/meshnology_w12/target.cpp b/variants/meshnology_w12/target.cpp new file mode 100644 index 00000000..bf04ba36 --- /dev/null +++ b/variants/meshnology_w12/target.cpp @@ -0,0 +1,73 @@ +#include <Arduino.h> +#include "target.h" + +MeshnologyW12Board board; + +#if defined(P_LORA_SCLK) + static SPIClass spi; + RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi); +#else + RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY); +#endif + +WRAPPER_CLASS radio_driver(radio, board); + +ESP32RTCClock fallback_clock; +AutoDiscoverRTCClock rtc_clock(fallback_clock); + +#if ENV_INCLUDE_GPS + #include <helpers/sensors/MicroNMEALocationProvider.h> + MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); +#else + EnvironmentSensorManager sensors; +#endif + +#ifdef DISPLAY_CLASS + DISPLAY_CLASS display(NULL); + MomentaryButton user_btn(PIN_USER_BTN, 1000, true); +#endif + +const uint32_t rfswitch_dios[] = { + RADIOLIB_LR2021_DIO5, // RFX2402E 2.4G_TX_EN + RADIOLIB_LR2021_DIO6, // RFX2402E 2.4G_RX_EN + RADIOLIB_LR2021_DIO9, // GC1109 CTX (Transmit mode) + RADIOLIB_LR2021_DIO10, // GC1109 CPS (Bypass mode) + RADIOLIB_LR2021_DIO11, // GC1109 CSD (Shutdown) +}; + +static const Module::RfSwitchMode_t rfswitch_table[] = { + // DIO5 DIO6 DIO9 DIO10 DIO11 + { LR2021::MODE_STBY, { LOW, LOW, LOW, LOW, LOW } }, // everything off + { LR2021::MODE_RX, { LOW, LOW, LOW, LOW, HIGH } }, // rx_lf: GC1109 LNA + { LR2021::MODE_TX, { LOW, LOW, HIGH, HIGH, HIGH } }, // tx_lf: GC1109 full PA + { LR2021::MODE_RX_HF, { LOW, HIGH, LOW, LOW, LOW } }, // rx_hf: 2G4 LNA, GC1109 off + { LR2021::MODE_TX_HF, { HIGH, LOW, LOW, LOW, LOW } }, // tx_hf: 2G4 PA, GC1109 off + END_OF_MODE_TABLE, +}; + + +bool radio_init() { + fallback_clock.begin(); + rtc_clock.begin(Wire); + +#if defined(P_LORA_SCLK) + int err = radio.std_init(&spi); + if (err != 1) return err; +#else + int err = radio.std_init(); + if (err != 1) return err; +#endif + +#ifdef RF_SWITCH_TABLE + radio.setRfSwitchTable(rfswitch_dios, rfswitch_table); +#endif + + return true; +} + +mesh::LocalIdentity radio_new_identity() { + RadioNoiseListener rng(radio); + return mesh::LocalIdentity(&rng); // create new random identity +} + diff --git a/variants/meshnology_w12/target.h b/variants/meshnology_w12/target.h new file mode 100644 index 00000000..1bf8876b --- /dev/null +++ b/variants/meshnology_w12/target.h @@ -0,0 +1,28 @@ +#pragma once + +#define RADIOLIB_STATIC_ONLY 1 +#include <RadioLib.h> +#include <helpers/radiolib/RadioLibWrappers.h> +#include <MeshnologyW12Board.h> +#include <helpers/radiolib/CustomLR2021Wrapper.h> +#include <helpers/AutoDiscoverRTCClock.h> +#include <helpers/SensorManager.h> +#include <helpers/sensors/EnvironmentSensorManager.h> +#ifdef DISPLAY_CLASS + #include <helpers/ui/SSD1306Display.h> + #include <helpers/ui/MomentaryButton.h> +#endif + +extern MeshnologyW12Board board; +extern WRAPPER_CLASS radio_driver; +extern AutoDiscoverRTCClock rtc_clock; +extern EnvironmentSensorManager sensors; + +#ifdef DISPLAY_CLASS + extern DISPLAY_CLASS display; + extern MomentaryButton user_btn; +#endif + +bool radio_init(); +mesh::LocalIdentity radio_new_identity(); + From 5687ba3f87b10b5e1056f1771bafe1138c9b0f2f Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Wed, 1 Jul 2026 18:17:48 +1000 Subject: [PATCH 074/381] LR2021 multi-SF support (side detectors) --- examples/simple_repeater/MyMesh.cpp | 6 +++ examples/simple_repeater/MyMesh.h | 4 ++ src/helpers/CommonCLI.cpp | 30 ++++++++++++++ src/helpers/CommonCLI.h | 7 ++++ src/helpers/radiolib/CustomLR2021Wrapper.h | 47 +++++++++++++++++++++- src/helpers/radiolib/RadioLibWrappers.h | 2 + 6 files changed, 95 insertions(+), 1 deletion(-) diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index 09f74cbe..cc0cc1f1 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -1064,6 +1064,12 @@ bool MyMesh::setRxBoostedGain(bool enable) { return radio_driver.setRxBoostedGainMode(enable); } +#if defined(USE_LR2021) +bool MyMesh::configSideDetectors(const uint8_t sideDetSFs[], uint8_t num) { + return radio_driver.configSideDetectors(sideDetSFs, num); +} +#endif + void MyMesh::formatNeighborsReply(char *reply) { char *dp = reply; diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index aa7d30b0..6a260e33 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -255,4 +255,8 @@ public: bool setRxBoostedGain(bool enable) override; + #if defined(USE_LR2021) + virtual bool configSideDetectors(const uint8_t sideDetSFs[], uint8_t num) override; + #endif + }; diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index 9d0571d9..bb54197f 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -753,6 +753,28 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep _prefs->adc_multiplier = 0.0f; strcpy(reply, "Error: unsupported"); }; + #if defined(USE_LR2021) + } else if (memcmp(config, "extra.sf ", 9) == 0) { + strcpy(tmp, &config[9]); + const char *parts[4]; + uint8_t sideDetSFs[4]; + int num = mesh::Utils::parseTextParts(tmp, parts, 4); + if (num > 3) { + sprintf(reply, "Invalid extra SF config"); + } else { + for (int i = 0; i < num; i++) { + sideDetSFs[i] = atoi(parts[i]); + } + sideDetSFs[num] = 0; + if (_callbacks->configSideDetectors(sideDetSFs, num)) { + for (int i = 0; i <= num; i++) _prefs->extra_sf[i] = sideDetSFs[i]; + savePrefs(); + sprintf(reply, "OK - extra SFs set"); + } else { + sprintf(reply, "Invalid extra SF config"); + } + } + #endif } else { strcpy(reply, "unknown config: "); StrHelper::strncpy(&reply[16], config, 160-17); @@ -922,6 +944,14 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep #else strcpy(reply, "ERROR: Power management not supported"); #endif + } else if (memcmp(config, "extra.sf", 8) == 0) { + char* tmp = reply; + for (int i = 0; i < 3 && _prefs->extra_sf[i] != 0; i++) { + tmp += sprintf(tmp, "%s%d", (i == 0) ? "" : ",", _prefs->extra_sf[i]); + } + if (tmp == reply) { + sprintf(reply, "No extra SF configured"); + } } else { sprintf(reply, "??: %s", config); } diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 69fe0315..fafabcb1 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -68,6 +68,7 @@ public: uint8_t path_hash_mode = 0; // which path mode to use when sending uint8_t loop_detect = 0; uint8_t cad_enabled = 0; // hardware Channel Activity Detection before TX (boolean) + uint8_t extra_sf[4]; private: class RadioPrefs : public ConfigSerializer { @@ -238,6 +239,12 @@ public: virtual bool setRxBoostedGain(bool enable) { return false; // CommonCLI reports unsupported if not overridden by wrapper }; + + #if defined(USE_LR2021) + virtual bool configSideDetectors(const uint8_t sideDetSFs[], uint8_t num) { + return false; // Override in wrapper + } + #endif }; class CommonCLI { diff --git a/src/helpers/radiolib/CustomLR2021Wrapper.h b/src/helpers/radiolib/CustomLR2021Wrapper.h index 0f1b1f9e..6d0204ac 100644 --- a/src/helpers/radiolib/CustomLR2021Wrapper.h +++ b/src/helpers/radiolib/CustomLR2021Wrapper.h @@ -21,6 +21,46 @@ public: ((CustomLR2021 *)_radio)->setBandwidth(bw); ((CustomLR2021 *)_radio)->setCodingRate(cr); updatePreamble(sf); + applySideDetectorConfig(); + } + + bool configSideDetectors(const uint8_t* sideDetSFs, uint8_t num) override { + LR2021LoRaSideDetector_t tmp[3]; + uint8_t sf = getSpreadingFactor(); + + if (sf >= 10 && num > 1) { return false; } // only 1 side detector allowed when primary SF >= 10 + for (int i = 0; i < num; i++) { + if (sideDetSFs[i] > 12 || sideDetSFs[i] < 5) { return false; } // must be valid SF + if (sideDetSFs[i] <= sf) { return false; } // must be < primary SF + if (sideDetSFs[i] > sf + 4) { return false; } // span must not be > 4 + + tmp[i].sf = sideDetSFs[i]; + if (sideDetSFs[i] == 10) { // TODO: set ldro=true when tSym >=16 + tmp[i].ldro = true; + } else { + tmp[i].ldro = false; + } + tmp[i].invertIQ = false; + tmp[i].syncWord = 0x12; + } + int16_t status = ((CustomLR2021 *)_radio)->setSideDetector(tmp, num); + RadioLibWrapper::idle(); // trigger startReceive() + MESH_DEBUG_PRINTLN("setSideDetector() returned %d", status); + + if (status == RADIOLIB_ERR_NONE) { + for (int i = 0; i < num; i++) { _sideDet[i] = tmp[i]; } + _numSideDet = num; + } else { + return false; + } + + return true; + } + + int16_t applySideDetectorConfig() { + int16_t status = ((CustomLR2021 *)_radio)->setSideDetector(_sideDet, _numSideDet); + RadioLibWrapper::idle(); // trigger startReceive() + return status; } bool isReceivingPacket() override { @@ -44,7 +84,7 @@ public: uint8_t getSpreadingFactor() const override { return ((CustomLR2021 *)_radio)->getSpreadingFactor(); } bool setRxBoostedGainMode(bool en) override { - ((CustomLR2021 *)_radio)->standby(); // radio must be in standby to accept the setRxBoostedGainMode command, otherwise it returns -707 error. + ((CustomLR2021 *)_radio)->standby(); // LR2021 must be in standby to accept setRxBoostedGainMode int16_t status = ((CustomLR2021 *)_radio)->setRxBoostedGainMode(en ? LR2021_RX_BOOST_LEVEL: 0); RadioLibWrapper::idle(); // trigger startReceive() return status == RADIOLIB_ERR_NONE; @@ -54,4 +94,9 @@ public: return ((CustomLR2021 *)_radio)->getRxBoostedGainMode(); } + protected: + LR2021LoRaSideDetector_t _sideDet[3]; + size_t _numSideDet = 0; + + }; diff --git a/src/helpers/radiolib/RadioLibWrappers.h b/src/helpers/radiolib/RadioLibWrappers.h index e886c81b..4ca958e4 100644 --- a/src/helpers/radiolib/RadioLibWrappers.h +++ b/src/helpers/radiolib/RadioLibWrappers.h @@ -77,6 +77,8 @@ public: virtual bool setRxBoostedGainMode(bool) { return false; } virtual bool getRxBoostedGainMode() const { return false; } + + virtual bool configSideDetectors(const uint8_t sideDetSFs[], uint8_t num) { return false; } }; /** From c2b7e56cbc80c3c44f93104fb6b46e812927bbbf Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Thu, 2 Jul 2026 17:18:03 +1000 Subject: [PATCH 075/381] LR2021: fix for hardware cad and side detectors --- src/helpers/radiolib/RadioLibWrappers.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/helpers/radiolib/RadioLibWrappers.cpp b/src/helpers/radiolib/RadioLibWrappers.cpp index c2bd6b26..dc851e5c 100644 --- a/src/helpers/radiolib/RadioLibWrappers.cpp +++ b/src/helpers/radiolib/RadioLibWrappers.cpp @@ -105,6 +105,9 @@ void RadioLibWrapper::loop() { } void RadioLibWrapper::startRecv() { + #if defined(USE_LR2021) + _radio->standby(); // without this LR2021 can throw -706 when calling startReceive after hardware CAD when side detectors are enabled + #endif int err = _radio->startReceive(); if (err == RADIOLIB_ERR_NONE) { state = STATE_RX; @@ -134,7 +137,7 @@ int RadioLibWrapper::recvRaw(uint8_t* bytes, int sz) { } } #if defined(USE_LR2021) - state = STATE_RX; // LR2021 stays in Rx after readData, if we issue another startReceive while still in Rx we get -706 errors. + state = STATE_RX; // LR2021 stays in Rx after readData, calling startReceive while still in Rx throws -706 errors #else state = STATE_IDLE; // need another startReceive() #endif From cb7b158931500adca40b9d1c0150dc0ce8d9aa37 Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Sun, 12 Jul 2026 18:03:25 +1000 Subject: [PATCH 076/381] LR2021: auto-LDRO for side detectors --- examples/simple_repeater/MyMesh.cpp | 4 ++-- examples/simple_repeater/MyMesh.h | 2 +- src/helpers/CommonCLI.cpp | 2 +- src/helpers/CommonCLI.h | 2 +- src/helpers/radiolib/CustomLR2021Wrapper.h | 11 ++++++++--- src/helpers/radiolib/RadioLibWrappers.h | 2 +- 6 files changed, 14 insertions(+), 9 deletions(-) diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index cc0cc1f1..6da8cca2 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -1065,8 +1065,8 @@ bool MyMesh::setRxBoostedGain(bool enable) { } #if defined(USE_LR2021) -bool MyMesh::configSideDetectors(const uint8_t sideDetSFs[], uint8_t num) { - return radio_driver.configSideDetectors(sideDetSFs, num); +bool MyMesh::configSideDetectors(const uint8_t sideDetSFs[], uint8_t num, float bw) { + return radio_driver.configSideDetectors(sideDetSFs, num, bw); } #endif diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index 6a260e33..ff35cfab 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -256,7 +256,7 @@ public: bool setRxBoostedGain(bool enable) override; #if defined(USE_LR2021) - virtual bool configSideDetectors(const uint8_t sideDetSFs[], uint8_t num) override; + virtual bool configSideDetectors(const uint8_t sideDetSFs[], uint8_t num, float bw) override; #endif }; diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index bb54197f..07181e16 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -766,7 +766,7 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep sideDetSFs[i] = atoi(parts[i]); } sideDetSFs[num] = 0; - if (_callbacks->configSideDetectors(sideDetSFs, num)) { + if (_callbacks->configSideDetectors(sideDetSFs, num, _prefs->bw)) { for (int i = 0; i <= num; i++) _prefs->extra_sf[i] = sideDetSFs[i]; savePrefs(); sprintf(reply, "OK - extra SFs set"); diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index fafabcb1..2a9ec43b 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -241,7 +241,7 @@ public: }; #if defined(USE_LR2021) - virtual bool configSideDetectors(const uint8_t sideDetSFs[], uint8_t num) { + virtual bool configSideDetectors(const uint8_t sideDetSFs[], uint8_t num, float bw) { return false; // Override in wrapper } #endif diff --git a/src/helpers/radiolib/CustomLR2021Wrapper.h b/src/helpers/radiolib/CustomLR2021Wrapper.h index 6d0204ac..87989831 100644 --- a/src/helpers/radiolib/CustomLR2021Wrapper.h +++ b/src/helpers/radiolib/CustomLR2021Wrapper.h @@ -24,7 +24,7 @@ public: applySideDetectorConfig(); } - bool configSideDetectors(const uint8_t* sideDetSFs, uint8_t num) override { + bool configSideDetectors(const uint8_t* sideDetSFs, uint8_t num, float bw) override { LR2021LoRaSideDetector_t tmp[3]; uint8_t sf = getSpreadingFactor(); @@ -35,7 +35,8 @@ public: if (sideDetSFs[i] > sf + 4) { return false; } // span must not be > 4 tmp[i].sf = sideDetSFs[i]; - if (sideDetSFs[i] == 10) { // TODO: set ldro=true when tSym >=16 + float tSym = calcTsym(tmp[i].sf, bw); + if (tSym >= 16.0f) { tmp[i].ldro = true; } else { tmp[i].ldro = false; @@ -63,6 +64,11 @@ public: return status; } + float calcTsym(uint8_t sf, float bw) { + float tSym = (float)(uint32_t(1) << sf) / (float)bw; + return tSym; + } + bool isReceivingPacket() override { return ((CustomLR2021 *)_radio)->isReceiving(); } @@ -98,5 +104,4 @@ public: LR2021LoRaSideDetector_t _sideDet[3]; size_t _numSideDet = 0; - }; diff --git a/src/helpers/radiolib/RadioLibWrappers.h b/src/helpers/radiolib/RadioLibWrappers.h index 4ca958e4..99f5ebbd 100644 --- a/src/helpers/radiolib/RadioLibWrappers.h +++ b/src/helpers/radiolib/RadioLibWrappers.h @@ -78,7 +78,7 @@ public: virtual bool setRxBoostedGainMode(bool) { return false; } virtual bool getRxBoostedGainMode() const { return false; } - virtual bool configSideDetectors(const uint8_t sideDetSFs[], uint8_t num) { return false; } + virtual bool configSideDetectors(const uint8_t sideDetSFs[], uint8_t num, float bw) { return false; } }; /** From 5b2613fc0af2f7d79568c34544fc9cb060014b1f Mon Sep 17 00:00:00 2001 From: Hacuchino-hash <246103064+Hacuchino-hash@users.noreply.github.com> Date: Tue, 4 Aug 2026 12:59:16 -0500 Subject: [PATCH 077/381] Add support for Seeed SenseCAP MeshTracker X1 (LR2021) --- boards/seeed-mesh-tracker-x1.json | 60 +++++++++ .../meshtracker_x1/MeshTrackerX1Board.cpp | 23 ++++ variants/meshtracker_x1/MeshTrackerX1Board.h | 87 +++++++++++++ variants/meshtracker_x1/platformio.ini | 117 +++++++++++++++++ variants/meshtracker_x1/target.cpp | 116 +++++++++++++++++ variants/meshtracker_x1/target.h | 44 +++++++ variants/meshtracker_x1/variant.cpp | 106 +++++++++++++++ variants/meshtracker_x1/variant.h | 123 ++++++++++++++++++ 8 files changed, 676 insertions(+) create mode 100644 boards/seeed-mesh-tracker-x1.json create mode 100644 variants/meshtracker_x1/MeshTrackerX1Board.cpp create mode 100644 variants/meshtracker_x1/MeshTrackerX1Board.h create mode 100644 variants/meshtracker_x1/platformio.ini create mode 100644 variants/meshtracker_x1/target.cpp create mode 100644 variants/meshtracker_x1/target.h create mode 100644 variants/meshtracker_x1/variant.cpp create mode 100644 variants/meshtracker_x1/variant.h diff --git a/boards/seeed-mesh-tracker-x1.json b/boards/seeed-mesh-tracker-x1.json new file mode 100644 index 00000000..347aca53 --- /dev/null +++ b/boards/seeed-mesh-tracker-x1.json @@ -0,0 +1,60 @@ +{ + "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"], + ["0x2886", "0x0057"] + ], + "usb_product": "X1-BOOT", + "mcu": "nrf52840", + "variant": "Seeed_Mesh-Tracker-X1", + "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", + "openocd_target": "nrf52.cfg" + }, + "frameworks": ["arduino"], + "name": "Seeed SenseCAP MeshTracker X1", + "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-MeshTracker-X1-for-Meshtastic-p-6793.html", + "vendor": "Seeed Studio" +} diff --git a/variants/meshtracker_x1/MeshTrackerX1Board.cpp b/variants/meshtracker_x1/MeshTrackerX1Board.cpp new file mode 100644 index 00000000..56e537a2 --- /dev/null +++ b/variants/meshtracker_x1/MeshTrackerX1Board.cpp @@ -0,0 +1,23 @@ +#include <Arduino.h> +#include <Wire.h> + +#include "MeshTrackerX1Board.h" + +void MeshTrackerX1Board::begin() { + NRF52BoardDCDC::begin(); + btn_prev_state = LOW; // button is active HIGH + +#ifdef BUTTON_PIN + pinMode(BATTERY_PIN, INPUT); + pinMode(BUTTON_PIN, INPUT_PULLDOWN); + pinMode(LED_PIN, OUTPUT); +#endif + +#if defined(PIN_BOARD_SDA) && defined(PIN_BOARD_SCL) + Wire.setPins(PIN_BOARD_SDA, PIN_BOARD_SCL); +#endif + + Wire.begin(); + + delay(10); // give lr2021 some time to power up +} diff --git a/variants/meshtracker_x1/MeshTrackerX1Board.h b/variants/meshtracker_x1/MeshTrackerX1Board.h new file mode 100644 index 00000000..51f022e0 --- /dev/null +++ b/variants/meshtracker_x1/MeshTrackerX1Board.h @@ -0,0 +1,87 @@ +#pragma once + +#include <MeshCore.h> +#include <Arduino.h> +#include <helpers/NRF52Board.h> + +class MeshTrackerX1Board : public NRF52BoardDCDC { +protected: + uint8_t btn_prev_state; + +public: + MeshTrackerX1Board() : NRF52Board("X1_OTA") {} + void begin(); + + uint16_t getBattMilliVolts() override { + #ifdef BATTERY_PIN + #ifdef PIN_BAT_ADC_EN + digitalWrite(PIN_BAT_ADC_EN, HIGH); + #endif + analogReference(AR_INTERNAL_3_0); + analogReadResolution(12); + delay(10); + float volts = (analogRead(BATTERY_PIN) * ADC_MULTIPLIER * AREF_VOLTAGE) / 4096; + + analogReference(AR_DEFAULT); // put back to default + analogReadResolution(10); + + return volts * 1000; + #else + return 0; + #endif + } + + const char* getManufacturerName() const override { + return "Seeed SenseCAP MeshTracker X1"; + } + + int buttonStateChanged() { + #ifdef BUTTON_PIN + uint8_t v = digitalRead(BUTTON_PIN); + if (v != btn_prev_state) { + btn_prev_state = v; + return (v == USER_BTN_PRESSED) ? 1 : -1; + } + #endif + return 0; + } + + void powerOff() override { + #ifdef HAS_GPS + digitalWrite(GPS_VRTC_EN, LOW); + digitalWrite(GPS_RESET, LOW); + digitalWrite(GPS_SLEEP_INT, LOW); + digitalWrite(GPS_RTC_INT, LOW); + digitalWrite(GPS_EN, LOW); + #endif + + #ifdef PIN_DRV_EN + digitalWrite(PIN_DRV_EN, LOW); + #endif + + #ifdef PIN_BAT_ADC_EN + digitalWrite(PIN_BAT_ADC_EN, LOW); + #endif + + #ifdef PIN_3V3_EN + digitalWrite(PIN_3V3_EN, LOW); + #endif + + // set led on and wait for button release before poweroff + #ifdef LED_PIN + digitalWrite(LED_PIN, HIGH); + #endif + #ifdef BUTTON_PIN + while(digitalRead(BUTTON_PIN)); + #endif + #ifdef LED_PIN + digitalWrite(LED_PIN, LOW); + #endif + + #ifdef BUTTON_PIN + nrf_gpio_cfg_sense_input(BUTTON_PIN, NRF_GPIO_PIN_PULLDOWN, NRF_GPIO_PIN_SENSE_HIGH); + #endif + + sd_power_system_off(); + } +}; diff --git a/variants/meshtracker_x1/platformio.ini b/variants/meshtracker_x1/platformio.ini new file mode 100644 index 00000000..dbab5ca6 --- /dev/null +++ b/variants/meshtracker_x1/platformio.ini @@ -0,0 +1,117 @@ +[MeshTracker_X1] +extends = nrf52_base +board = seeed-mesh-tracker-x1 +board_build.ldscript = boards/nrf52840_s140_v7.ld +build_flags = ${nrf52_base.build_flags} + -I src/helpers/nrf52 + -I lib/nrf52/s140_nrf52_7.3.0_API/include + -I lib/nrf52/s140_nrf52_7.3.0_API/include/nrf52 + -I variants/meshtracker_x1 + -I src/helpers/ui + -D MESH_TRACKER_X1 + -D PIN_USER_BTN=6 + -D USER_BTN_PRESSED=HIGH + -D PIN_STATUS_LED=24 + -D RADIO_CLASS=CustomLR2021 + -D USE_LR2021 + -D WRAPPER_CLASS=CustomLR2021Wrapper + -D LORA_TX_POWER=22 + -D P_LORA_BUSY=7 ; P0.7 + -D P_LORA_SCLK=11 ; P0.11 + -D P_LORA_NSS=12 ; P0.12 + -D P_LORA_DIO_1=33 ; P1.1 + -D P_LORA_MISO=40 ; P1.8 + -D P_LORA_MOSI=41 ; P1.9 + -D P_LORA_RESET=42 ; P1.10 + -D LR2021_IRQ_DIO=8 ; P1.1 is connected to LR2021 DIO8 + -D LR2021_TCXO_VOLTAGE=1.6f + -D ENV_INCLUDE_GPS=1 +build_src_filter = ${nrf52_base.build_src_filter} + +<helpers/*.cpp> + +<../variants/meshtracker_x1> +debug_tool = jlink +upload_protocol = nrfutil + +[env:MeshTracker_X1_repeater] +extends = MeshTracker_X1 +build_flags = ${MeshTracker_X1.build_flags} + -I examples/companion_radio/ui-orig + -D ADVERT_NAME='"MeshTracker X1 Repeater"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=50 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${MeshTracker_X1.build_src_filter} + +<../examples/simple_repeater> +lib_deps = ${MeshTracker_X1.lib_deps} + stevemarple/MicroNMEA @ ^2.0.6 + +[env:MeshTracker_X1_room_server] +extends = MeshTracker_X1 +build_flags = ${MeshTracker_X1.build_flags} + -I examples/companion_radio/ui-orig + -D ADVERT_NAME='"MeshTracker X1 Room"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D ROOM_PASSWORD='"hello"' +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${MeshTracker_X1.build_src_filter} + +<../examples/simple_room_server> +lib_deps = ${MeshTracker_X1.lib_deps} + stevemarple/MicroNMEA @ ^2.0.6 + +[env:MeshTracker_X1_companion_radio_usb] +extends = MeshTracker_X1 +board_build.ldscript = boards/nrf52840_s140_v7_extrafs.ld +board_upload.maximum_size = 708608 +build_flags = ${MeshTracker_X1.build_flags} + -I examples/companion_radio/ui-orig + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 + -D OFFLINE_QUEUE_SIZE=256 + -D DISPLAY_CLASS=NullDisplayDriver + -D PIN_BUZZER=25 + -D ENABLE_USB_INTERFACE +build_src_filter = ${MeshTracker_X1.build_src_filter} + +<helpers/ui/buzzer.cpp> + +<helpers/ui/NullDisplayDriver.cpp> + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-orig/*.cpp> +lib_deps = ${MeshTracker_X1.lib_deps} + densaugeo/base64 @ ~1.4.0 + stevemarple/MicroNMEA @ ^2.0.6 + end2endzone/NonBlockingRTTTL@^1.3.0 + +[env:MeshTracker_X1_companion_radio_ble] +extends = MeshTracker_X1 +board_build.ldscript = boards/nrf52840_s140_v7_extrafs.ld +board_upload.maximum_size = 708608 +build_flags = ${MeshTracker_X1.build_flags} + -I examples/companion_radio/ui-orig + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D BLE_PIN_CODE=123456 + -D BLE_TX_POWER=0 +; -D BLE_DEBUG_LOGGING=1 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 + -D OFFLINE_QUEUE_SIZE=256 + -D DISPLAY_CLASS=NullDisplayDriver + -D PIN_BUZZER=25 + -D ADVERT_NAME='"@@MAC"' +build_src_filter = ${MeshTracker_X1.build_src_filter} + +<helpers/nrf52/SerialBLEInterface.cpp> + +<helpers/ui/buzzer.cpp> + +<helpers/ui/NullDisplayDriver.cpp> + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-orig/*.cpp> +lib_deps = ${MeshTracker_X1.lib_deps} + densaugeo/base64 @ ~1.4.0 + stevemarple/MicroNMEA @ ^2.0.6 + end2endzone/NonBlockingRTTTL@^1.3.0 diff --git a/variants/meshtracker_x1/target.cpp b/variants/meshtracker_x1/target.cpp new file mode 100644 index 00000000..1139b8b7 --- /dev/null +++ b/variants/meshtracker_x1/target.cpp @@ -0,0 +1,116 @@ +#include <Arduino.h> +#include "target.h" +#include <helpers/sensors/MicroNMEALocationProvider.h> + +MeshTrackerX1Board board; + +RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, SPI); + +WRAPPER_CLASS radio_driver(radio, board); + +VolatileRTCClock rtc_clock; +MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +MeshTrackerX1SensorManager sensors = MeshTrackerX1SensorManager(nmea); + +#ifdef DISPLAY_CLASS + NullDisplayDriver display; +#endif + +bool radio_init() { + return radio.std_init(&SPI); +} + +mesh::LocalIdentity radio_new_identity() { + RadioNoiseListener rng(radio); + return mesh::LocalIdentity(&rng); // create new random identity +} + +void MeshTrackerX1SensorManager::start_gps() { + gps_active = true; + // this init sequence comes from seeed examples and deals with all gps pins + pinMode(GPS_EN, OUTPUT); + digitalWrite(GPS_EN, HIGH); + delay(10); + pinMode(GPS_VRTC_EN, OUTPUT); + digitalWrite(GPS_VRTC_EN, HIGH); + delay(10); + + pinMode(GPS_RESET, OUTPUT); + digitalWrite(GPS_RESET, HIGH); + delay(10); + digitalWrite(GPS_RESET, LOW); + + pinMode(GPS_SLEEP_INT, OUTPUT); + digitalWrite(GPS_SLEEP_INT, HIGH); + pinMode(GPS_RTC_INT, OUTPUT); + digitalWrite(GPS_RTC_INT, LOW); +} + +void MeshTrackerX1SensorManager::sleep_gps() { + gps_active = false; + digitalWrite(GPS_VRTC_EN, HIGH); // keep RTC alive for faster fix on wake + digitalWrite(GPS_EN, LOW); + digitalWrite(GPS_RESET, LOW); + digitalWrite(GPS_SLEEP_INT, HIGH); + digitalWrite(GPS_RTC_INT, LOW); +} + +void MeshTrackerX1SensorManager::stop_gps() { + gps_active = false; + digitalWrite(GPS_VRTC_EN, LOW); + digitalWrite(GPS_EN, LOW); + digitalWrite(GPS_RESET, LOW); + digitalWrite(GPS_SLEEP_INT, HIGH); + digitalWrite(GPS_RTC_INT, LOW); +} + +bool MeshTrackerX1SensorManager::begin() { + // init GPS + Serial1.begin(GPS_BAUD_RATE); + return true; +} + +bool MeshTrackerX1SensorManager::querySensors(uint8_t requester_permissions, CayenneLPP& telemetry) { + if (requester_permissions & TELEM_PERM_LOCATION) { // does requester have permission? + telemetry.addGPS(TELEM_CHANNEL_SELF, node_lat, node_lon, node_altitude); + } + return true; +} + +void MeshTrackerX1SensorManager::loop() { + static long next_gps_update = 0; + + _nmea->loop(); + + if (millis() > next_gps_update) { + if (gps_active && _nmea->isValid()) { + node_lat = ((double)_nmea->getLatitude())/1000000.; + node_lon = ((double)_nmea->getLongitude())/1000000.; + node_altitude = ((double)_nmea->getAltitude()) / 1000.0; + } + next_gps_update = millis() + 1000; + } +} + +int MeshTrackerX1SensorManager::getNumSettings() const { return 1; } // just one supported: "gps" (power switch) + +const char* MeshTrackerX1SensorManager::getSettingName(int i) const { + return i == 0 ? "gps" : NULL; +} +const char* MeshTrackerX1SensorManager::getSettingValue(int i) const { + if (i == 0) { + return gps_active ? "1" : "0"; + } + return NULL; +} +bool MeshTrackerX1SensorManager::setSettingValue(const char* name, const char* value) { + if (strcmp(name, "gps") == 0) { + if (strcmp(value, "0") == 0) { + sleep_gps(); // sleep for faster fix ! + } else { + start_gps(); + } + return true; + } + return false; // not supported +} diff --git a/variants/meshtracker_x1/target.h b/variants/meshtracker_x1/target.h new file mode 100644 index 00000000..665f4328 --- /dev/null +++ b/variants/meshtracker_x1/target.h @@ -0,0 +1,44 @@ +#pragma once + +#define RADIOLIB_STATIC_ONLY 1 +#include <RadioLib.h> +#include <helpers/radiolib/RadioLibWrappers.h> +#include "MeshTrackerX1Board.h" +#include <helpers/radiolib/CustomLR2021Wrapper.h> +#include <helpers/ArduinoHelpers.h> +#include <helpers/SensorManager.h> +#include <helpers/sensors/LocationProvider.h> +#ifdef DISPLAY_CLASS + #include "NullDisplayDriver.h" +#endif + +class MeshTrackerX1SensorManager: public SensorManager { + bool gps_active = false; + LocationProvider * _nmea; + + void start_gps(); + void sleep_gps(); + void stop_gps(); +public: + MeshTrackerX1SensorManager(LocationProvider &nmea): _nmea(&nmea) { } + bool begin() override; + bool querySensors(uint8_t requester_permissions, CayenneLPP& telemetry) override; + void loop() override; + int getNumSettings() const override; + const char* getSettingName(int i) const override; + const char* getSettingValue(int i) const override; + bool setSettingValue(const char* name, const char* value) override; + LocationProvider* getLocationProvider() { return _nmea; } +}; + +#ifdef DISPLAY_CLASS + extern NullDisplayDriver display; +#endif + +extern MeshTrackerX1Board board; +extern WRAPPER_CLASS radio_driver; +extern VolatileRTCClock rtc_clock; +extern MeshTrackerX1SensorManager sensors; + +bool radio_init(); +mesh::LocalIdentity radio_new_identity(); diff --git a/variants/meshtracker_x1/variant.cpp b/variants/meshtracker_x1/variant.cpp new file mode 100644 index 00000000..a0e64380 --- /dev/null +++ b/variants/meshtracker_x1/variant.cpp @@ -0,0 +1,106 @@ +/* + * variant.cpp - Seeed SenseCAP MeshTracker X1 (nRF52840 + Semtech LR2021) + */ + +#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, LED_RED + 4, // P0.04, AIN2 VCC_ADC + 5, // P0.05, AIN3 EXT_PWR_DETECT + 6, // P0.06, PIN_BUTTON1 + 7, // P0.07, LORA_BUSY + 8, // P0.08, GPS_RESET + 9, // P0.09, PIN_RTC_EN + 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 + 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 + 27, // P0.27 + 28, // P0.28, LED_BLUE + 29, // P0.29, GPS_RTC_INT + 30, // P0.30, GPS_SLEEP_INT + 31, // P0.31 + 32, // P1.00 + 33, // P1.01, LORA_DIO_1 (LR2021 DIO8 IRQ) + 34, // P1.02 + 35, // P1.03, EXT_CHRG_DETECT + 36, // P1.04, CHARGE_DONE + 37, // P1.05, PIN_DRV_EN + 38, // P1.06, PIN_BAT_ADC_EN + 39, // P1.07, PIN_3V3_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 + 45, // P1.13, GPS_VRTC_EN + 46, // P1.14, PIN_WIRE_SCL + 47, // P1.15, PIN_WIRE_SDA + 255, // NRFX_SPIM_PIN_NOT_USED +}; + +void initVariant() +{ + pinMode(BATTERY_PIN, INPUT); + pinMode(EXT_CHRG_DETECT, INPUT); + pinMode(EXT_PWR_DETECT, INPUT); + pinMode(PIN_BUTTON1, INPUT_PULLDOWN); + + pinMode(PIN_3V3_EN, OUTPUT); + digitalWrite(PIN_3V3_EN, HIGH); + + pinMode(PIN_BAT_ADC_EN, OUTPUT); + digitalWrite(PIN_BAT_ADC_EN, HIGH); + + pinMode(PIN_RTC_EN, OUTPUT); + digitalWrite(PIN_RTC_EN, LOW); + + pinMode(PIN_DRV_EN, OUTPUT); + digitalWrite(PIN_DRV_EN, LOW); + + pinMode(LED_RED, OUTPUT); + digitalWrite(LED_RED, LOW); + + pinMode(LED_GREEN, OUTPUT); + digitalWrite(LED_GREEN, LOW); + + pinMode(LED_BLUE, OUTPUT); + digitalWrite(LED_BLUE, LOW); + + pinMode(GPS_EN, OUTPUT); + digitalWrite(GPS_EN, LOW); + + pinMode(GPS_VRTC_EN, OUTPUT); + digitalWrite(GPS_VRTC_EN, HIGH); + + pinMode(GPS_RESET, OUTPUT); + digitalWrite(GPS_RESET, LOW); + + pinMode(GPS_SLEEP_INT, OUTPUT); + digitalWrite(GPS_SLEEP_INT, HIGH); + + pinMode(GPS_RTC_INT, OUTPUT); + digitalWrite(GPS_RTC_INT, LOW); + + pinMode(BUZZER_PIN, INPUT_PULLDOWN); +} diff --git a/variants/meshtracker_x1/variant.h b/variants/meshtracker_x1/variant.h new file mode 100644 index 00000000..8e9bae8f --- /dev/null +++ b/variants/meshtracker_x1/variant.h @@ -0,0 +1,123 @@ +/* + * variant.h - Seeed SenseCAP MeshTracker X1 (nRF52840 + Semtech LR2021) + */ + +#pragma once + +#include "WVariant.h" + +//////////////////////////////////////////////////////////////////////////////// +// Low frequency clock source + +#define USE_LFXO // 32.768 kHz crystal oscillator +#define VARIANT_MCK (64000000ul) + +//////////////////////////////////////////////////////////////////////////////// +// Power + +#define NRF_APM // detect usb power +#define PIN_3V3_EN (39) // P1.7 Power to sensors +#define PIN_BAT_ADC_EN (38) // P1.6 Power to battery ADC divider +#define PIN_RTC_EN (9) // P0.9 Power to RTC + +#define BATTERY_PIN (2) // P0.2/AIN0 +#define BATTERY_IMMUTABLE +#define ADC_MULTIPLIER (2.0F) + +#define EXT_CHRG_DETECT (35) // P1.3, LOW while charging +#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 (GPS) +#define PIN_SERIAL1_TX (13) // P0.13 (GPS) + +#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 (47) // P1.15 +#define PIN_WIRE_SCL (46) // P1.14 +#define I2C_NO_RESCAN + +//////////////////////////////////////////////////////////////////////////////// +// 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 (RGB) + +#define LED_BUILTIN (-1) +#define LED_RED (3) // P0.3 +#define LED_GREEN (24) // P0.24 +#define LED_BLUE (28) // P0.28 +#define LED_PIN LED_GREEN + +#define LED_STATE_ON HIGH + +//////////////////////////////////////////////////////////////////////////////// +// Builtin buttons + +#define PIN_BUTTON1 (6) // P0.6, active HIGH (internal pull-down) +#define BUTTON_PIN PIN_BUTTON1 + +//////////////////////////////////////////////////////////////////////////////// +// LR2021 + +#define LORA_DIO_1 (33) // P1.1, IRQ line (LR2021 DIO8) +#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) // P1.9 + +//////////////////////////////////////////////////////////////////////////////// +// GPS (Airoha, dual-band L1+L5) + +#define HAS_GPS 1 +#define GPS_RX_PIN PIN_SERIAL1_RX +#define GPS_TX_PIN PIN_SERIAL1_TX +#define GPS_BAUD_RATE (115200) + +#define GPS_EN (43) // P1.11, active HIGH +#define GPS_RESET (8) // P0.8, active HIGH + +#define GPS_VRTC_EN (45) // P1.13 +#define GPS_SLEEP_INT (30) // P0.30 +#define GPS_RTC_INT (29) // P0.29 + +//////////////////////////////////////////////////////////////////////////////// +// Haptic driver (DRV2605 on I2C) + +#define PIN_DRV_EN (37) // P1.5, power to haptic driver + +//////////////////////////////////////////////////////////////////////////////// +// Buzzer + +#define BUZZER_PIN (25) // P0.25, pwm output From 63108c2c902770232d6d923550c0bdd631585dcd Mon Sep 17 00:00:00 2001 From: Rastislav Vysoky <recrof@gmail.com> Date: Thu, 6 Aug 2026 12:37:21 +0200 Subject: [PATCH 078/381] ThinkNode M6: Remove QSPIFLASH=1 build flag to fix companion roles M6 doesn't have flash chip available, so companion roles fail to start. --- variants/thinknode_m6/platformio.ini | 2 -- 1 file changed, 2 deletions(-) diff --git a/variants/thinknode_m6/platformio.ini b/variants/thinknode_m6/platformio.ini index 3606d6a8..ad7e6902 100644 --- a/variants/thinknode_m6/platformio.ini +++ b/variants/thinknode_m6/platformio.ini @@ -85,7 +85,6 @@ build_flags = -D BLE_DEBUG_LOGGING=1 -D OFFLINE_QUEUE_SIZE=256 -D AUTO_SHUTDOWN_MILLIVOLTS=3300 - -D QSPIFLASH=1 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${ThinkNode_M6.build_src_filter} @@ -107,7 +106,6 @@ build_flags = -I examples/companion_radio/ui-new -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 - -D QSPIFLASH=1 -D OFFLINE_QUEUE_SIZE=256 -D AUTO_SHUTDOWN_MILLIVOLTS=3300 -D ENABLE_USB_INTERFACE From 3da5f1d4c570d8276b49f38010bb62aeef9a59e7 Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Fri, 7 Aug 2026 00:19:18 +1200 Subject: [PATCH 079/381] disable cad on companion until it's configurable --- examples/companion_radio/MyMesh.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index b8661caf..b03334c1 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -262,7 +262,7 @@ int MyMesh::getInterferenceThreshold() const { return 0; // disabled for now, until currentRSSI() problem is resolved } bool MyMesh::getCADEnabled() const { - return true; // hardware CAD before TX (no CLI toggle on companion; enabled by default) + return false; // hardware CAD before TX (disabled by default, until configurable) } int MyMesh::calcRxDelay(float score, uint32_t air_time) const { From f8ea866b1ff34ba97e48ec62f3e2a6349b3827fb Mon Sep 17 00:00:00 2001 From: Hacuchino-hash <246103064+Hacuchino-hash@users.noreply.github.com> Date: Wed, 5 Aug 2026 09:03:44 -0500 Subject: [PATCH 080/381] Add RGB LED and haptic notifications for SenseCAP MeshTracker X1 --- examples/companion_radio/NodePrefs.h | 2 + examples/companion_radio/ui-orig/UITask.cpp | 124 +++++++++++++++++++- examples/companion_radio/ui-orig/UITask.h | 7 ++ src/helpers/ui/DRV2605Vibration.cpp | 47 ++++++++ src/helpers/ui/DRV2605Vibration.h | 39 ++++++ variants/meshtracker_x1/platformio.ini | 11 ++ 6 files changed, 225 insertions(+), 5 deletions(-) create mode 100644 src/helpers/ui/DRV2605Vibration.cpp create mode 100644 src/helpers/ui/DRV2605Vibration.h diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index 39a5386a..4ec1803e 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -28,6 +28,7 @@ public: uint32_t ble_pin = 0; uint8_t advert_loc_policy = 0; uint8_t buzzer_quiet = 0; + uint8_t vibe_quiet = 0; uint8_t gps_enabled = 0; // GPS enabled flag (0=disabled, 1=enabled) uint32_t gps_interval = 0; // GPS read interval in seconds uint8_t autoadd_config = 0; // bitmask for auto-add contacts config @@ -101,6 +102,7 @@ private: def("defs_key", (void *) _parent->default_scope_key, sizeof(_parent->default_scope_key)); def("pin", _parent->ble_pin); def("buzz_q", _parent->buzzer_quiet); + def("vibe_q", _parent->vibe_quiet); def("auto_add", _parent->autoadd_config); // bitmask for auto-add contacts config def("man_add", _parent->manual_add_contacts); def("tel_base", _parent->telemetry_mode_base); diff --git a/examples/companion_radio/ui-orig/UITask.cpp b/examples/companion_radio/ui-orig/UITask.cpp index 09fc8e77..08fc9b7a 100644 --- a/examples/companion_radio/ui-orig/UITask.cpp +++ b/examples/companion_radio/ui-orig/UITask.cpp @@ -6,12 +6,19 @@ #define AUTO_OFF_MILLIS 15000 // 15 seconds #define BOOT_SCREEN_MILLIS 3000 // 3 seconds -#ifdef PIN_STATUS_LED +#if defined(PIN_STATUS_LED) || defined(PIN_STATUS_LED_R) #define LED_ON_MILLIS 20 #define LED_ON_MSG_MILLIS 200 #define LED_CYCLE_MILLIS 4000 #endif +#if defined(PIN_STATUS_LED_R) && defined(PIN_STATUS_LED_G) && defined(PIN_STATUS_LED_B) +#define STATUS_LED_RGB 1 +#ifndef LOW_BATT_MILLIVOLTS +#define LOW_BATT_MILLIVOLTS 3500 +#endif +#endif + #ifndef USER_BTN_PRESSED #define USER_BTN_PRESSED LOW #endif @@ -60,6 +67,11 @@ void UITask::begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* no buzzer.startup(); #endif +#ifdef HAS_DRV2605 + vibration.begin(); + vibration.quiet(_node_prefs->vibe_quiet); +#endif + // Initialize digital button if available #ifdef PIN_USER_BTN _userButton = new Button(PIN_USER_BTN, USER_BTN_PRESSED); @@ -130,6 +142,10 @@ void UITask::clearMsgPreview() { void UITask::newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount) { _msgcount = msgcount; +#ifdef HAS_DRV2605 + vibration.trigger(); // vibrate even while the app is connected (honors quiet + cooldown) +#endif + if (path_len == 0xFF) { sprintf(_origin, "(F) %s", from_name); } else { @@ -260,8 +276,88 @@ void UITask::renderCurrScreen() { _need_refresh = false; } +#ifdef STATUS_LED_RGB +static void statusLedWrite(uint8_t r, uint8_t g, uint8_t b) { + analogWrite(PIN_STATUS_LED_R, r); + analogWrite(PIN_STATUS_LED_G, g); + analogWrite(PIN_STATUS_LED_B, b); +} + +static void statusLedWheel(uint8_t pos) { // smooth hue sweep, 0..255 + if (pos < 85) { + statusLedWrite(255 - pos * 3, pos * 3, 0); + } else if (pos < 170) { + pos -= 85; + statusLedWrite(0, 255 - pos * 3, pos * 3); + } else { + pos -= 170; + statusLedWrite(pos * 3, 0, 255 - pos * 3); + } +} +#endif + void UITask::userLedHandler() { -#ifdef PIN_STATUS_LED +#ifdef STATUS_LED_RGB + static bool booted = false; + static bool flourish_active = false; + static unsigned long flourish_until = 0; + static int prev_msgcount = 0; + static int state = 0; + static unsigned long next_change = 0; + static int last_increment = 0; + static unsigned long next_batt_check = 0; + static bool low_batt = false; + + unsigned long cur_time = millis(); + + if (!booted) { // color sweep on boot + booted = true; + flourish_until = cur_time + 1200; + flourish_active = true; + } + if (_msgcount > prev_msgcount) { // color sweep when a new message arrives + flourish_until = cur_time + 800; + flourish_active = true; + } + prev_msgcount = _msgcount; + + if (flourish_active) { + if (cur_time < flourish_until) { + statusLedWheel((cur_time % 1200) * 255 / 1200); + return; + } + statusLedWrite(0, 0, 0); + flourish_active = false; + state = 0; + next_change = cur_time; + } + + if (cur_time > next_batt_check) { // battery reads are not free, keep them rare + low_batt = _board->getBattMilliVolts() < LOW_BATT_MILLIVOLTS; + next_batt_check = cur_time + 60000; + } + + if (cur_time > next_change) { + if (state == 0) { + state = 1; + last_increment = (_msgcount > 0) ? LED_ON_MSG_MILLIS : LED_ON_MILLIS; + next_change = cur_time + last_increment; + if (low_batt) { + statusLedWrite(255, 0, 0); // red: battery low + } else if (_msgcount > 0) { + statusLedWrite(255, 90, 0); // amber: unread messages + } else if (_connected) { + statusLedWrite(0, 0, 255); // blue: app connected + } else { + statusLedWrite(0, 255, 0); // green: heartbeat + } + } else { + state = 0; + next_change = cur_time + LED_CYCLE_MILLIS - last_increment; + statusLedWrite(0, 0, 0); + } + } +#elif defined(PIN_STATUS_LED) static int state = 0; static int next_change = 0; static int last_increment = 0; @@ -406,8 +502,26 @@ void UITask::handleButtonDoublePress() { void UITask::handleButtonTriplePress() { MESH_DEBUG_PRINTLN("UITask: triple press triggered"); - // Toggle buzzer quiet mode - #ifdef PIN_BUZZER +#if defined(PIN_BUZZER) && defined(HAS_DRV2605) + // cycle alert modes: Buzz+Vibe -> Buzz only -> Vibe only -> Silent + int mode = (_node_prefs->buzzer_quiet ? 2 : 0) | (_node_prefs->vibe_quiet ? 1 : 0); + mode = (mode + 1) & 3; + _node_prefs->buzzer_quiet = (mode & 2) ? 1 : 0; + _node_prefs->vibe_quiet = (mode & 1) ? 1 : 0; + buzzer.quiet(_node_prefs->buzzer_quiet); + vibration.quiet(_node_prefs->vibe_quiet); + // audible/tactile confirmation of the new mode (no screen on some boards) + if (!_node_prefs->buzzer_quiet) notify(UIEventType::ack); + if (!_node_prefs->vibe_quiet) vibration.trigger(true); + switch (mode) { + case 0: sprintf(_alert, "Alerts: Buzz+Vibe"); break; + case 1: sprintf(_alert, "Alerts: Buzz only"); break; + case 2: sprintf(_alert, "Alerts: Vibe only"); break; + default: sprintf(_alert, "Alerts: Silent"); break; + } + the_mesh.savePrefs(); + _need_refresh = true; +#elif defined(PIN_BUZZER) if (buzzer.isQuiet()) { buzzer.quiet(false); notify(UIEventType::ack); @@ -419,7 +533,7 @@ void UITask::handleButtonTriplePress() { _node_prefs->buzzer_quiet = buzzer.isQuiet(); the_mesh.savePrefs(); _need_refresh = true; - #endif +#endif } void UITask::handleButtonQuadruplePress() { diff --git a/examples/companion_radio/ui-orig/UITask.h b/examples/companion_radio/ui-orig/UITask.h index 961c07a0..02d126e8 100644 --- a/examples/companion_radio/ui-orig/UITask.h +++ b/examples/companion_radio/ui-orig/UITask.h @@ -14,11 +14,18 @@ #include "Button.h" +#ifdef HAS_DRV2605 + #include <helpers/ui/DRV2605Vibration.h> +#endif + class UITask : public AbstractUITask { DisplayDriver* _display; SensorManager* _sensors; #ifdef PIN_BUZZER genericBuzzer buzzer; +#endif +#ifdef HAS_DRV2605 + DRV2605Vibration vibration; #endif unsigned long _next_refresh, _auto_off; NodePrefs* _node_prefs; diff --git a/src/helpers/ui/DRV2605Vibration.cpp b/src/helpers/ui/DRV2605Vibration.cpp new file mode 100644 index 00000000..3a42bb88 --- /dev/null +++ b/src/helpers/ui/DRV2605Vibration.cpp @@ -0,0 +1,47 @@ +#ifdef HAS_DRV2605 + +#include "DRV2605Vibration.h" +#include <Wire.h> + +void DRV2605Vibration::begin() { +#ifdef PIN_DRV_EN + pinMode(PIN_DRV_EN, OUTPUT); + digitalWrite(PIN_DRV_EN, HIGH); // power up the haptic driver + delay(10); +#endif + if (!drv.begin(&Wire)) { + return; // no haptic driver found, stay silent + } +#ifdef DRV2605_USE_LRA + // LRA mode: 4x brake factor, medium loop gain, back-EMF gain 2 + drv.writeRegister8(DRV2605_REG_FEEDBACK, 0xB6); +#endif + drv.selectLibrary(1); + drv.setMode(DRV2605_MODE_INTTRIG); + _ready = true; +} + +void DRV2605Vibration::trigger(bool force) { + if (!_ready || _quiet) return; + unsigned long now = millis(); + if (!force && _last_trigger != 0 && now - _last_trigger < VIBRATION_TIMEOUT) return; + _last_trigger = now; + drv.setWaveform(0, DRV2605_EFFECT); + drv.setWaveform(1, 0); // pause + drv.setWaveform(2, DRV2605_EFFECT); + drv.setWaveform(3, 0); // end of sequence + drv.go(); +} + +void DRV2605Vibration::loop() { +} + +bool DRV2605Vibration::isVibrating() { + return false; // effects are short, treat as instantaneous +} + +void DRV2605Vibration::stop() { + if (_ready) drv.stop(); +} + +#endif // ifdef HAS_DRV2605 diff --git a/src/helpers/ui/DRV2605Vibration.h b/src/helpers/ui/DRV2605Vibration.h new file mode 100644 index 00000000..a40894be --- /dev/null +++ b/src/helpers/ui/DRV2605Vibration.h @@ -0,0 +1,39 @@ +#pragma once + +#ifdef HAS_DRV2605 + +#include <Arduino.h> +#include <Adafruit_DRV2605.h> + +/* + * Vibration control class for boards where the motor is behind a + * DRV2605 haptic driver on I2C (e.g. Seeed SenseCAP MeshTracker X1). + * Same interface as GenericVibration. + */ + +#ifndef VIBRATION_TIMEOUT +#define VIBRATION_TIMEOUT 5000 // cooldown between vibrations +#endif + +#ifndef DRV2605_EFFECT +#define DRV2605_EFFECT 16 // "1000 ms alert" from the DRV2605 effect library +#endif + +class DRV2605Vibration { +public: + void begin(); // power up and init the DRV2605 + void trigger(bool force = false); // trigger vibration; force skips the cooldown + void loop(); // no-op, the DRV2605 plays effects autonomously + bool isVibrating(); + void stop(); // stop vibration immediately + void quiet(bool q) { _quiet = q; } + bool isQuiet() const { return _quiet; } + +private: + Adafruit_DRV2605 drv; + bool _ready = false; + bool _quiet = false; + unsigned long _last_trigger = 0; +}; + +#endif // ifdef HAS_DRV2605 diff --git a/variants/meshtracker_x1/platformio.ini b/variants/meshtracker_x1/platformio.ini index dbab5ca6..18506916 100644 --- a/variants/meshtracker_x1/platformio.ini +++ b/variants/meshtracker_x1/platformio.ini @@ -12,6 +12,9 @@ build_flags = ${nrf52_base.build_flags} -D PIN_USER_BTN=6 -D USER_BTN_PRESSED=HIGH -D PIN_STATUS_LED=24 + -D PIN_STATUS_LED_R=3 ; P0.3 red + -D PIN_STATUS_LED_G=24 ; P0.24 green + -D PIN_STATUS_LED_B=28 ; P0.28 blue -D RADIO_CLASS=CustomLR2021 -D USE_LR2021 -D WRAPPER_CLASS=CustomLR2021Wrapper @@ -77,16 +80,20 @@ build_flags = ${MeshTracker_X1.build_flags} -D OFFLINE_QUEUE_SIZE=256 -D DISPLAY_CLASS=NullDisplayDriver -D PIN_BUZZER=25 + -D HAS_DRV2605=1 + -D DRV2605_USE_LRA=1 -D ENABLE_USB_INTERFACE build_src_filter = ${MeshTracker_X1.build_src_filter} +<helpers/ui/buzzer.cpp> +<helpers/ui/NullDisplayDriver.cpp> + +<helpers/ui/DRV2605Vibration.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-orig/*.cpp> lib_deps = ${MeshTracker_X1.lib_deps} densaugeo/base64 @ ~1.4.0 stevemarple/MicroNMEA @ ^2.0.6 end2endzone/NonBlockingRTTTL@^1.3.0 + adafruit/Adafruit DRV2605 Library @ ^1.2.4 [env:MeshTracker_X1_companion_radio_ble] extends = MeshTracker_X1 @@ -104,14 +111,18 @@ build_flags = ${MeshTracker_X1.build_flags} -D OFFLINE_QUEUE_SIZE=256 -D DISPLAY_CLASS=NullDisplayDriver -D PIN_BUZZER=25 + -D HAS_DRV2605=1 + -D DRV2605_USE_LRA=1 -D ADVERT_NAME='"@@MAC"' build_src_filter = ${MeshTracker_X1.build_src_filter} +<helpers/nrf52/SerialBLEInterface.cpp> +<helpers/ui/buzzer.cpp> +<helpers/ui/NullDisplayDriver.cpp> + +<helpers/ui/DRV2605Vibration.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-orig/*.cpp> lib_deps = ${MeshTracker_X1.lib_deps} densaugeo/base64 @ ~1.4.0 stevemarple/MicroNMEA @ ^2.0.6 end2endzone/NonBlockingRTTTL@^1.3.0 + adafruit/Adafruit DRV2605 Library @ ^1.2.4 From dc8e2d67456ff74f75cbfd887dfc2dd0af932546 Mon Sep 17 00:00:00 2001 From: Hacuchino-hash <246103064+Hacuchino-hash@users.noreply.github.com> Date: Wed, 5 Aug 2026 09:34:02 -0500 Subject: [PATCH 081/381] Add SPA06 barometer telemetry and charge status LED for MeshTracker X1 --- examples/companion_radio/ui-orig/UITask.cpp | 30 +++++++++++++++++++++ variants/meshtracker_x1/platformio.ini | 2 ++ variants/meshtracker_x1/target.cpp | 16 +++++++++++ variants/meshtracker_x1/target.h | 3 +++ variants/meshtracker_x1/variant.cpp | 3 ++- variants/meshtracker_x1/variant.h | 1 + 6 files changed, 54 insertions(+), 1 deletion(-) diff --git a/examples/companion_radio/ui-orig/UITask.cpp b/examples/companion_radio/ui-orig/UITask.cpp index 08fc9b7a..1e961316 100644 --- a/examples/companion_radio/ui-orig/UITask.cpp +++ b/examples/companion_radio/ui-orig/UITask.cpp @@ -337,6 +337,36 @@ void UITask::userLedHandler() { next_batt_check = cur_time + 60000; } +#ifdef EXT_CHRG_DETECT + // charge status display while docked (skipped when messages are waiting, + // so the unread indication is never masked) + static unsigned long next_pwr_check = 0; + static bool ext_powered = false, ext_charging = false; + if (cur_time > next_pwr_check) { + ext_powered = _board->isExternalPowered(); + bool chrg = digitalRead(EXT_CHRG_DETECT) == LOW; + #ifdef EXT_CHRG_DONE + if (digitalRead(EXT_CHRG_DONE) == LOW) chrg = false; // charge-done wins + #endif + ext_charging = ext_powered && chrg; + next_pwr_check = cur_time + 1000; + } + if (ext_powered && _msgcount == 0) { + if (ext_charging) { + // amber breathing while charging + int ph = cur_time % 2000; + int v = ph < 1000 ? ph : 2000 - ph; + uint8_t lvl = (uint8_t)(v * 255 / 1000); + statusLedWrite(lvl, (uint8_t)(lvl * 35 / 100), 0); + } else { + statusLedWrite(0, 40, 0); // dim solid green: charge complete + } + state = 0; + next_change = cur_time; + return; + } +#endif + if (cur_time > next_change) { if (state == 0) { state = 1; diff --git a/variants/meshtracker_x1/platformio.ini b/variants/meshtracker_x1/platformio.ini index 18506916..6a46a79f 100644 --- a/variants/meshtracker_x1/platformio.ini +++ b/variants/meshtracker_x1/platformio.ini @@ -32,6 +32,8 @@ build_flags = ${nrf52_base.build_flags} build_src_filter = ${nrf52_base.build_src_filter} +<helpers/*.cpp> +<../variants/meshtracker_x1> +lib_deps = ${nrf52_base.lib_deps} + https://github.com/adafruit/Adafruit_SPA06_003/archive/refs/tags/1.0.2.zip debug_tool = jlink upload_protocol = nrfutil diff --git a/variants/meshtracker_x1/target.cpp b/variants/meshtracker_x1/target.cpp index 1139b8b7..d6d548b5 100644 --- a/variants/meshtracker_x1/target.cpp +++ b/variants/meshtracker_x1/target.cpp @@ -67,6 +67,17 @@ void MeshTrackerX1SensorManager::stop_gps() { bool MeshTrackerX1SensorManager::begin() { // init GPS Serial1.begin(GPS_BAUD_RATE); + + // init SPA06-003 barometer + baro_ok = spa06.begin(SPA06_003_DEFAULT_ADDR, &Wire) || spa06.begin(0x76, &Wire); + if (baro_ok) { + spa06.setPressureOversampling(SPA06_003_OVERSAMPLE_8); + spa06.setTemperatureOversampling(SPA06_003_OVERSAMPLE_8); + // 1 Hz continuous keeps reads non-blocking at minimal power cost + spa06.setPressureMeasureRate(SPA06_003_RATE_1); + spa06.setTemperatureMeasureRate(SPA06_003_RATE_1); + spa06.setMeasurementMode(SPA06_003_MEAS_CONTINUOUS_BOTH); + } return true; } @@ -74,12 +85,17 @@ bool MeshTrackerX1SensorManager::querySensors(uint8_t requester_permissions, Cay if (requester_permissions & TELEM_PERM_LOCATION) { // does requester have permission? telemetry.addGPS(TELEM_CHANNEL_SELF, node_lat, node_lon, node_altitude); } + if (requester_permissions & TELEM_PERM_ENVIRONMENT && baro_ok) { + telemetry.addTemperature(TELEM_CHANNEL_SELF, spa06.readTemperature()); + telemetry.addBarometricPressure(TELEM_CHANNEL_SELF, spa06.readPressure()); + } return true; } void MeshTrackerX1SensorManager::loop() { static long next_gps_update = 0; + _nmea->loop(); if (millis() > next_gps_update) { diff --git a/variants/meshtracker_x1/target.h b/variants/meshtracker_x1/target.h index 665f4328..9741efb6 100644 --- a/variants/meshtracker_x1/target.h +++ b/variants/meshtracker_x1/target.h @@ -8,12 +8,15 @@ #include <helpers/ArduinoHelpers.h> #include <helpers/SensorManager.h> #include <helpers/sensors/LocationProvider.h> +#include <Adafruit_SPA06_003.h> #ifdef DISPLAY_CLASS #include "NullDisplayDriver.h" #endif class MeshTrackerX1SensorManager: public SensorManager { bool gps_active = false; + bool baro_ok = false; + Adafruit_SPA06_003 spa06; LocationProvider * _nmea; void start_gps(); diff --git a/variants/meshtracker_x1/variant.cpp b/variants/meshtracker_x1/variant.cpp index a0e64380..5a685a8e 100644 --- a/variants/meshtracker_x1/variant.cpp +++ b/variants/meshtracker_x1/variant.cpp @@ -62,7 +62,8 @@ const uint32_t g_ADigitalPinMap[PINS_COUNT + 1] = void initVariant() { pinMode(BATTERY_PIN, INPUT); - pinMode(EXT_CHRG_DETECT, INPUT); + pinMode(EXT_CHRG_DETECT, INPUT_PULLUP); + pinMode(EXT_CHRG_DONE, INPUT_PULLUP); pinMode(EXT_PWR_DETECT, INPUT); pinMode(PIN_BUTTON1, INPUT_PULLDOWN); diff --git a/variants/meshtracker_x1/variant.h b/variants/meshtracker_x1/variant.h index 8e9bae8f..c3dbd274 100644 --- a/variants/meshtracker_x1/variant.h +++ b/variants/meshtracker_x1/variant.h @@ -25,6 +25,7 @@ #define ADC_MULTIPLIER (2.0F) #define EXT_CHRG_DETECT (35) // P1.3, LOW while charging +#define EXT_CHRG_DONE (36) // P1.4, LOW when charge complete #define EXT_PWR_DETECT (5) // P0.5 #define ADC_RESOLUTION (14) From 2eb7feffe010f1c39acb3b382dbe9be9c1b7101b Mon Sep 17 00:00:00 2001 From: agessaman <adam@gessaman.com> Date: Thu, 6 Aug 2026 15:29:14 -0700 Subject: [PATCH 082/381] fix(station-g3): expose FEM gain preferences --- docs/cli_commands.md | 15 +++++ examples/simple_repeater/MyMesh.cpp | 2 + examples/simple_room_server/MyMesh.cpp | 2 + examples/simple_sensor/SensorMesh.cpp | 2 + src/MeshCore.h | 4 ++ src/helpers/CommonCLI.cpp | 32 ++++++++- src/helpers/CommonCLI.h | 4 +- variants/station_g3_esp32/LoRaFEMControl.cpp | 69 ++++++++++++++++++++ variants/station_g3_esp32/LoRaFEMControl.h | 20 ++++++ variants/station_g3_esp32/StationG3Board.cpp | 35 +++++++++- variants/station_g3_esp32/StationG3Board.h | 53 +++++---------- variants/station_g3_esp32/platformio.ini | 4 +- 12 files changed, 198 insertions(+), 44 deletions(-) create mode 100644 variants/station_g3_esp32/LoRaFEMControl.cpp create mode 100644 variants/station_g3_esp32/LoRaFEMControl.h diff --git a/docs/cli_commands.md b/docs/cli_commands.md index b618ae2b..390c8e04 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -291,6 +291,21 @@ This document provides an overview of CLI commands that can be sent to MeshCore --- +#### View or change the LoRa FEM transmit-path gain state on supported boards +**Usage:** +- `get radio.fem.txgain` +- `set radio.fem.txgain <state>` + +**Parameters:** +- `state`: `on`|`off` + +**Notes:** +- This controls a software-selectable external LoRa FEM transmit gain where the board supports it. +- On Station G3, remove the PA PL1 jumper to allow software control. `on` selects PA PL1 high/short and `off` selects PA PL1 low/open. The PA PL2 hardware jumper determines whether this switches between power levels 1/3 or 2/4. +- Select an operating level and SX1262 transmit power that comply with local RF limits and the Station G3 power-supply requirements. + +--- + ### System #### View or change this node's name diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index c93ba1a4..d3c2e160 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -913,6 +913,7 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc #endif #endif _prefs.radio_fem_rxgain = 1; + _prefs.radio_fem_txgain = 0; pending_discover_tag = 0; pending_discover_until = 0; @@ -962,6 +963,7 @@ void MyMesh::begin(FILESYSTEM *fs) { MESH_DEBUG_PRINTLN("RX Boosted Gain Mode: %s", radio_driver.getRxBoostedGainMode() ? "Enabled" : "Disabled"); board.setLoRaFemLnaEnabled(_prefs.radio_fem_rxgain); + board.setLoRaFemPaGainEnabled(_prefs.radio_fem_txgain); updateAdvertTimer(); updateFloodAdvertTimer(); diff --git a/examples/simple_room_server/MyMesh.cpp b/examples/simple_room_server/MyMesh.cpp index 0aff39cc..f7ec1480 100644 --- a/examples/simple_room_server/MyMesh.cpp +++ b/examples/simple_room_server/MyMesh.cpp @@ -683,6 +683,7 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc #endif #endif _prefs.radio_fem_rxgain = 1; + _prefs.radio_fem_txgain = 0; next_post_idx = 0; next_client_idx = 0; @@ -726,6 +727,7 @@ void MyMesh::begin(FILESYSTEM *fs) { radio_driver.setTxPower(_prefs.tx_power_dbm); radio_driver.setRxBoostedGainMode(_prefs.rx_boosted_gain); board.setLoRaFemLnaEnabled(_prefs.radio_fem_rxgain); + board.setLoRaFemPaGainEnabled(_prefs.radio_fem_txgain); updateAdvertTimer(); updateFloodAdvertTimer(); diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 17f8e323..9bfa5ec6 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -735,6 +735,7 @@ SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::Millise _prefs.gps_interval = 0; _prefs.advert_loc_policy = ADVERT_LOC_PREFS; _prefs.radio_fem_rxgain = 1; + _prefs.radio_fem_txgain = 0; memset(default_scope.key, 0, sizeof(default_scope.key)); } @@ -771,6 +772,7 @@ void SensorMesh::begin(FILESYSTEM* fs) { radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr); radio_driver.setTxPower(_prefs.tx_power_dbm); board.setLoRaFemLnaEnabled(_prefs.radio_fem_rxgain); + board.setLoRaFemPaGainEnabled(_prefs.radio_fem_txgain); updateAdvertTimer(); updateFloodAdvertTimer(); diff --git a/src/MeshCore.h b/src/MeshCore.h index 89e60b1f..e67371ef 100644 --- a/src/MeshCore.h +++ b/src/MeshCore.h @@ -67,6 +67,10 @@ public: virtual bool setLoRaFemLnaEnabled(bool enable) { return false; } virtual bool canControlLoRaFemLna() const { return false; } virtual bool isLoRaFemLnaEnabled() const { return false; } + // Software-selectable external FEM transmit gain. This is not a PA power switch. + virtual bool setLoRaFemPaGainEnabled(bool enable) { return false; } + virtual bool canControlLoRaFemPaGain() const { return false; } + virtual bool isLoRaFemPaGainEnabled() const { return false; } // Power management interface (boards with power management override these) virtual bool isExternalPowered() { return false; } diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index 07181e16..56a52a0b 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -102,7 +102,8 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) { // Legacy file.read((uint8_t *)&_prefs->flood_max_advert, sizeof(_prefs->flood_max_advert)); // 292 file.read((uint8_t *)&_prefs->radio_fem_rxgain, sizeof(_prefs->radio_fem_rxgain)); // 293 file.read((uint8_t *)&_prefs->cad_enabled, sizeof(_prefs->cad_enabled)); // 294 - // next: 295 + file.read((uint8_t *)&_prefs->radio_fem_txgain, sizeof(_prefs->radio_fem_txgain)); // 295 + // next: 296 // sanitise bad pref values _prefs->rx_delay_base = constrain(_prefs->rx_delay_base, 0, 20.0f); @@ -133,6 +134,7 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) { // Legacy // sanitise settings _prefs->rx_boosted_gain = constrain(_prefs->rx_boosted_gain, 0, 1); // boolean _prefs->radio_fem_rxgain = constrain(_prefs->radio_fem_rxgain, 0, 1); // boolean + _prefs->radio_fem_txgain = constrain(_prefs->radio_fem_txgain, 0, 1); // boolean _prefs->cad_enabled = constrain(_prefs->cad_enabled, 0, 1); // boolean file.close(); @@ -562,6 +564,28 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep } else { strcpy(reply, "Error: state must be on or off"); } + } else if (memcmp(config, "radio.fem.txgain ", 17) == 0) { + if (!_board->canControlLoRaFemPaGain()) { + strcpy(reply, "Error: unsupported"); + } else if (memcmp(&config[17], "on", 2) == 0) { + if (_board->setLoRaFemPaGainEnabled(true)) { + _prefs->radio_fem_txgain = 1; + savePrefs(); + strcpy(reply, "OK - LoRa FEM TX gain on"); + } else { + strcpy(reply, "Error: failed to apply LoRa FEM TX gain"); + } + } else if (memcmp(&config[17], "off", 3) == 0) { + if (_board->setLoRaFemPaGainEnabled(false)) { + _prefs->radio_fem_txgain = 0; + savePrefs(); + strcpy(reply, "OK - LoRa FEM TX gain off"); + } else { + strcpy(reply, "Error: failed to apply LoRa FEM TX gain"); + } + } else { + strcpy(reply, "Error: state must be on or off"); + } } else if (memcmp(config, "radio ", 6) == 0) { strcpy(tmp, &config[6]); const char *parts[4]; @@ -827,6 +851,12 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep } else { sprintf(reply, "> %s", _board->isLoRaFemLnaEnabled() ? "on" : "off"); } + } else if (memcmp(config, "radio.fem.txgain", 16) == 0) { + if (!_board->canControlLoRaFemPaGain()) { + strcpy(reply, "Error: unsupported"); + } else { + sprintf(reply, "> %s", _board->isLoRaFemPaGainEnabled() ? "on" : "off"); + } } else if (memcmp(config, "radio", 5) == 0) { char freq[16], bw[16]; strcpy(freq, StrHelper::ftoa(_prefs->freq)); diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 2a9ec43b..237c758e 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -65,6 +65,7 @@ public: char owner_info[120]; uint8_t rx_boosted_gain = 0; // power settings uint8_t radio_fem_rxgain = 0; // LoRa FEM RX gain setting + uint8_t radio_fem_txgain = 0; // LoRa FEM TX gain setting uint8_t path_hash_mode = 0; // which path mode to use when sending uint8_t loop_detect = 0; uint8_t cad_enabled = 0; // hardware Channel Activity Detection before TX (boolean) @@ -82,7 +83,8 @@ private: def("cad", _parent->cad_enabled); def("int_thr", _parent->interference_threshold); def("rxgain", _parent->rx_boosted_gain); - def("fem_rxgain", _parent->rx_boosted_gain); + def("fem_rxgain", _parent->radio_fem_rxgain); + def("fem_txgain", _parent->radio_fem_txgain); def("tx", _parent->tx_power_dbm); def("af", _parent->airtime_factor); def("rxdelay", _parent->rx_delay_base); diff --git a/variants/station_g3_esp32/LoRaFEMControl.cpp b/variants/station_g3_esp32/LoRaFEMControl.cpp new file mode 100644 index 00000000..04ac2ff8 --- /dev/null +++ b/variants/station_g3_esp32/LoRaFEMControl.cpp @@ -0,0 +1,69 @@ +#include "LoRaFEMControl.h" + +#include <Arduino.h> +#include <driver/rtc_io.h> + +void LoRaFEMControl::init() { +#ifdef P_PA1_EN + rtc_gpio_hold_dis((gpio_num_t)P_PA1_EN); + pinMode(P_PA1_EN, OUTPUT); + setPAGainEnable(pa_gain_enabled); +#endif + +#ifdef P_PRIMARY_LNA_EN + rtc_gpio_hold_dis((gpio_num_t)P_PRIMARY_LNA_EN); + pinMode(P_PRIMARY_LNA_EN, OUTPUT); + setRxModeEnable(); +#endif +} + +void LoRaFEMControl::setSleepModeEnable() { +#ifdef P_PA1_EN + // PA PL1 low/open selects the lower of the two hardware-jumper-selected levels. + digitalWrite(P_PA1_EN, !P_PA1_EN_ACTIVE); +#endif +#ifdef P_PRIMARY_LNA_EN + // Preserve the existing Station G3 power-off state. + digitalWrite(P_PRIMARY_LNA_EN, P_PRIMARY_LNA_EN_ACTIVE); +#endif +} + +void LoRaFEMControl::setTxModeEnable() { +#ifdef P_PRIMARY_LNA_EN + digitalWrite(P_PRIMARY_LNA_EN, !P_PRIMARY_LNA_EN_ACTIVE); +#endif +} + +void LoRaFEMControl::setRxModeEnable() { +#ifdef P_PRIMARY_LNA_EN + digitalWrite(P_PRIMARY_LNA_EN, lna_enabled ? P_PRIMARY_LNA_EN_ACTIVE : !P_PRIMARY_LNA_EN_ACTIVE); +#endif +} + +void LoRaFEMControl::setLNAEnable(bool enabled) { + lna_enabled = enabled; + setRxModeEnable(); +} + +void LoRaFEMControl::setPAGainEnable(bool enabled) { + pa_gain_enabled = enabled; +#ifdef P_PA1_EN + digitalWrite(P_PA1_EN, enabled ? P_PA1_EN_ACTIVE : !P_PA1_EN_ACTIVE); +#endif +} + +bool LoRaFEMControl::canControlLNA() const { +#ifdef P_PRIMARY_LNA_EN + return true; +#else + return false; +#endif +} + +bool LoRaFEMControl::canControlPAGain() const { +#ifdef P_PA1_EN + return true; +#else + return false; +#endif +} diff --git a/variants/station_g3_esp32/LoRaFEMControl.h b/variants/station_g3_esp32/LoRaFEMControl.h new file mode 100644 index 00000000..429d6127 --- /dev/null +++ b/variants/station_g3_esp32/LoRaFEMControl.h @@ -0,0 +1,20 @@ +#pragma once + +class LoRaFEMControl { +public: + void init(); + void setSleepModeEnable(); + void setTxModeEnable(); + void setRxModeEnable(); + void setLNAEnable(bool enabled); + void setPAGainEnable(bool enabled); + + bool canControlLNA() const; + bool canControlPAGain() const; + bool isLNAEnabled() const { return lna_enabled; } + bool isPAGainEnabled() const { return pa_gain_enabled; } + +private: + bool lna_enabled = true; + bool pa_gain_enabled = false; +}; diff --git a/variants/station_g3_esp32/StationG3Board.cpp b/variants/station_g3_esp32/StationG3Board.cpp index 4a498311..dd863aca 100644 --- a/variants/station_g3_esp32/StationG3Board.cpp +++ b/variants/station_g3_esp32/StationG3Board.cpp @@ -1,15 +1,46 @@ #include "StationG3Board.h" void StationG3Board::powerOff() { + loRaFEMControl.setSleepModeEnable(); #ifdef P_PA1_EN - setPAModeHigh(false); rtc_gpio_hold_en((gpio_num_t)P_PA1_EN); #endif #ifdef P_PRIMARY_LNA_EN - setPrimaryLNAControl(true); rtc_gpio_hold_en((gpio_num_t)P_PRIMARY_LNA_EN); #endif ESP32Board::powerOff(); } + +bool StationG3Board::setLoRaFemLnaEnabled(bool enable) { + if (!loRaFEMControl.canControlLNA()) { + return false; + } + loRaFEMControl.setLNAEnable(enable); + return true; +} + +bool StationG3Board::canControlLoRaFemLna() const { + return loRaFEMControl.canControlLNA(); +} + +bool StationG3Board::isLoRaFemLnaEnabled() const { + return loRaFEMControl.isLNAEnabled(); +} + +bool StationG3Board::setLoRaFemPaGainEnabled(bool enable) { + if (!loRaFEMControl.canControlPAGain()) { + return false; + } + loRaFEMControl.setPAGainEnable(enable); + return true; +} + +bool StationG3Board::canControlLoRaFemPaGain() const { + return loRaFEMControl.canControlPAGain(); +} + +bool StationG3Board::isLoRaFemPaGainEnabled() const { + return loRaFEMControl.isPAGainEnabled(); +} diff --git a/variants/station_g3_esp32/StationG3Board.h b/variants/station_g3_esp32/StationG3Board.h index 4b1fb81c..52628eb6 100644 --- a/variants/station_g3_esp32/StationG3Board.h +++ b/variants/station_g3_esp32/StationG3Board.h @@ -3,45 +3,15 @@ #include <Arduino.h> #include <helpers/ESP32Board.h> #include <driver/rtc_io.h> - -#ifndef P_PRIMARY_LNA_EN_ACTIVE -#define P_PRIMARY_LNA_EN_ACTIVE LOW -#endif - -#ifndef P_PA1_EN_ACTIVE -#define P_PA1_EN_ACTIVE HIGH -#endif +#include "LoRaFEMControl.h" class StationG3Board : public ESP32Board { - void setPAModeHigh(bool enabled) { -#ifdef P_PA1_EN - // Station G3 PA PL1 mode: LOW/open is PA low, HIGH/short is PA high. - digitalWrite(P_PA1_EN, enabled ? P_PA1_EN_ACTIVE : !P_PA1_EN_ACTIVE); -#endif - } - - void setPrimaryLNAControl(bool enabled) { -#ifdef P_PRIMARY_LNA_EN - // Station G3 primary LNA mode is active-low: LOW/open is LNA on, HIGH/short is LNA off. - digitalWrite(P_PRIMARY_LNA_EN, enabled ? P_PRIMARY_LNA_EN_ACTIVE : !P_PRIMARY_LNA_EN_ACTIVE); -#endif - } - public: + LoRaFEMControl loRaFEMControl; + void begin() { ESP32Board::begin(); - -#ifdef P_PA1_EN - rtc_gpio_hold_dis((gpio_num_t)P_PA1_EN); - pinMode(P_PA1_EN, OUTPUT); - setPAModeHigh(false); -#endif - -#ifdef P_PRIMARY_LNA_EN - rtc_gpio_hold_dis((gpio_num_t)P_PRIMARY_LNA_EN); - pinMode(P_PRIMARY_LNA_EN, OUTPUT); - setPrimaryLNAControl(true); -#endif + loRaFEMControl.init(); esp_reset_reason_t reason = esp_reset_reason(); if (reason == ESP_RST_DEEPSLEEP) { @@ -56,23 +26,30 @@ public: } void setPrimaryLNAEnable(bool enabled) { - setPrimaryLNAControl(enabled); + loRaFEMControl.setLNAEnable(enabled); } void setPrimaryPAHighPower(bool enabled) { - setPAModeHigh(enabled); + loRaFEMControl.setPAGainEnable(enabled); } void onBeforeTransmit() override { ESP32Board::onBeforeTransmit(); - setPrimaryLNAControl(false); + loRaFEMControl.setTxModeEnable(); } void onAfterTransmit() override { ESP32Board::onAfterTransmit(); - setPrimaryLNAControl(true); + loRaFEMControl.setRxModeEnable(); } + bool setLoRaFemLnaEnabled(bool enable) override; + bool canControlLoRaFemLna() const override; + bool isLoRaFemLnaEnabled() const override; + bool setLoRaFemPaGainEnabled(bool enable) override; + bool canControlLoRaFemPaGain() const override; + bool isLoRaFemPaGainEnabled() const override; + void powerOff() override; uint16_t getBattMilliVolts() override { diff --git a/variants/station_g3_esp32/platformio.ini b/variants/station_g3_esp32/platformio.ini index e4a66a18..074d6a2e 100644 --- a/variants/station_g3_esp32/platformio.ini +++ b/variants/station_g3_esp32/platformio.ini @@ -17,11 +17,11 @@ build_flags = -D P_LORA_SCLK=12 -D P_LORA_MISO=14 -D P_LORA_MOSI=13 - -D P_PA1_EN=9 ; PA PL1 Mode: LOW/open is PA low, HIGH/short is PA high. + -D P_PA1_EN=9 ; PA PL1 Mode: LOW/open selects low level, HIGH/short selects high level. -D P_PA1_EN_ACTIVE=HIGH -D P_PRIMARY_LNA_EN=10 ; Primary Slot LNA Mode: LOW/open is LNA on, HIGH/short is LNA off. -D P_PRIMARY_LNA_EN_ACTIVE=LOW - -D LORA_TX_POWER=7 ; configured as 7dbm, because the final output will be ~27dbm (~0.5w) if the PA is enabled. + -D LORA_TX_POWER=7 ; SX1262 input power to the Station G3 PA; final output depends on PA PL1/PL2 level. -D MAX_LORA_TX_POWER=22 ; -D P_LORA_TX_LED=35 -D PIN_BOARD_SDA=5 From 4160dfbb87cac0d54d527223d15a7270027f4e0c Mon Sep 17 00:00:00 2001 From: Hacuchino-hash <246103064+Hacuchino-hash@users.noreply.github.com> Date: Fri, 7 Aug 2026 08:08:08 -0500 Subject: [PATCH 083/381] Fix X1 charge status LED always showing charged --- examples/companion_radio/ui-orig/UITask.cpp | 6 +----- variants/meshtracker_x1/variant.cpp | 1 - variants/meshtracker_x1/variant.h | 3 ++- 3 files changed, 3 insertions(+), 7 deletions(-) diff --git a/examples/companion_radio/ui-orig/UITask.cpp b/examples/companion_radio/ui-orig/UITask.cpp index 1e961316..b49b05dd 100644 --- a/examples/companion_radio/ui-orig/UITask.cpp +++ b/examples/companion_radio/ui-orig/UITask.cpp @@ -344,11 +344,7 @@ void UITask::userLedHandler() { static bool ext_powered = false, ext_charging = false; if (cur_time > next_pwr_check) { ext_powered = _board->isExternalPowered(); - bool chrg = digitalRead(EXT_CHRG_DETECT) == LOW; - #ifdef EXT_CHRG_DONE - if (digitalRead(EXT_CHRG_DONE) == LOW) chrg = false; // charge-done wins - #endif - ext_charging = ext_powered && chrg; + ext_charging = ext_powered && digitalRead(EXT_CHRG_DETECT) == LOW; next_pwr_check = cur_time + 1000; } if (ext_powered && _msgcount == 0) { diff --git a/variants/meshtracker_x1/variant.cpp b/variants/meshtracker_x1/variant.cpp index 5a685a8e..49cbc8dc 100644 --- a/variants/meshtracker_x1/variant.cpp +++ b/variants/meshtracker_x1/variant.cpp @@ -63,7 +63,6 @@ void initVariant() { pinMode(BATTERY_PIN, INPUT); pinMode(EXT_CHRG_DETECT, INPUT_PULLUP); - pinMode(EXT_CHRG_DONE, INPUT_PULLUP); pinMode(EXT_PWR_DETECT, INPUT); pinMode(PIN_BUTTON1, INPUT_PULLDOWN); diff --git a/variants/meshtracker_x1/variant.h b/variants/meshtracker_x1/variant.h index c3dbd274..7672044c 100644 --- a/variants/meshtracker_x1/variant.h +++ b/variants/meshtracker_x1/variant.h @@ -25,7 +25,8 @@ #define ADC_MULTIPLIER (2.0F) #define EXT_CHRG_DETECT (35) // P1.3, LOW while charging -#define EXT_CHRG_DONE (36) // P1.4, LOW when charge complete +// P1.4 is the charger's second status line, but it reads LOW regardless of +// charge state on this board, so it is not used (Meshtastic leaves it out too) #define EXT_PWR_DETECT (5) // P0.5 #define ADC_RESOLUTION (14) From 5ee9758b75390ca0f3bd27888a9037de7ac4e06e Mon Sep 17 00:00:00 2001 From: Bill Plein <260078+bplein@users.noreply.github.com> Date: Fri, 7 Aug 2026 17:51:01 -0500 Subject: [PATCH 084/381] Allow for build-time macro to disable the bluetooth LED Several variants use one or another method to disable the bluetooth LED that is grabbed by the Adafruit Bluefruit library by default. This allows for single build_flags macro to control the behavior (default behavior if not defined, not auto-controlled by Bluefruit if defined). This would open up for future cases where this could be controlled via a CLI command or by an application. Does not change behavior if the flag is not defined. --- src/helpers/nrf52/SerialBLEInterface.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/helpers/nrf52/SerialBLEInterface.cpp b/src/helpers/nrf52/SerialBLEInterface.cpp index 75a4e3b0..2e5626a8 100644 --- a/src/helpers/nrf52/SerialBLEInterface.cpp +++ b/src/helpers/nrf52/SerialBLEInterface.cpp @@ -129,6 +129,12 @@ void SerialBLEInterface::begin(const char* prefix, char* name, uint32_t pin_code char charpin[20]; snprintf(charpin, sizeof(charpin), "%lu", (unsigned long)pin_code); + #ifdef DISABLE_BLE_LED \\ use variant platformio.ini build_flags macro: -D DISABLE_BLE_LED + Bluefruit.autoConnLed(false); \\ false removes the automatic control of the LED by the Bluefruit library + #else + Bluefruit.autoConnLed(true); \\ true leaves the default automatic control of the LED by the Bluefruit library + #endif + // If we want to control BLE LED ourselves, uncomment this: // Bluefruit.autoConnLed(false); Bluefruit.configPrphBandwidth(BANDWIDTH_MAX); From 5704db9f740abea9f2f7251c29979a12385c8ef1 Mon Sep 17 00:00:00 2001 From: Adam Gessaman <adam@gessaman.com> Date: Sat, 8 Aug 2026 14:53:57 -0700 Subject: [PATCH 085/381] fix(station-g3): apply FEM PA level at TX start PA PL1 re-targets the PA's DC-DC supply rail rather than selecting a logic-level gain, and the serial CLI is serviced on every main-loop pass regardless of whether a transmit is in flight. A `set radio.fem.txgain` write could therefore move the rail mid-transmit, while the SX1262 was still driving the PA at full input power. Record the requested level in setPAGainEnable() and drive the pin from setTxModeEnable(), which runs from onBeforeTransmit() ahead of startTransmit(). The level only matters while transmitting, so deferring costs nothing. Document that the pref is saved immediately but applied at the next transmit, so `get radio.fem.txgain` can lead the hardware until then. --- docs/cli_commands.md | 1 + variants/station_g3_esp32/LoRaFEMControl.cpp | 14 ++++++++++++-- variants/station_g3_esp32/LoRaFEMControl.h | 2 ++ 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 390c8e04..8772b929 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -303,6 +303,7 @@ This document provides an overview of CLI commands that can be sent to MeshCore - This controls a software-selectable external LoRa FEM transmit gain where the board supports it. - On Station G3, remove the PA PL1 jumper to allow software control. `on` selects PA PL1 high/short and `off` selects PA PL1 low/open. The PA PL2 hardware jumper determines whether this switches between power levels 1/3 or 2/4. - Select an operating level and SX1262 transmit power that comply with local RF limits and the Station G3 power-supply requirements. +- The setting is saved immediately, but on Station G3 the level is applied to the hardware at the start of the next transmit, so that the PA supply rail is never re-targeted while the PA is being driven. `get` reports the configured state, which may lead the hardware until the node next transmits. --- diff --git a/variants/station_g3_esp32/LoRaFEMControl.cpp b/variants/station_g3_esp32/LoRaFEMControl.cpp index 04ac2ff8..8d4f90f6 100644 --- a/variants/station_g3_esp32/LoRaFEMControl.cpp +++ b/variants/station_g3_esp32/LoRaFEMControl.cpp @@ -7,7 +7,7 @@ void LoRaFEMControl::init() { #ifdef P_PA1_EN rtc_gpio_hold_dis((gpio_num_t)P_PA1_EN); pinMode(P_PA1_EN, OUTPUT); - setPAGainEnable(pa_gain_enabled); + applyPAGain(); #endif #ifdef P_PRIMARY_LNA_EN @@ -29,6 +29,10 @@ void LoRaFEMControl::setSleepModeEnable() { } void LoRaFEMControl::setTxModeEnable() { + // Latch the requested PA level here, before the SX1262 starts driving the PA. PA PL1 + // retargets the PA's DC-DC rail, so moving it mid-transmit collapses the supply while + // the PA is still driven at full input power. + applyPAGain(); #ifdef P_PRIMARY_LNA_EN digitalWrite(P_PRIMARY_LNA_EN, !P_PRIMARY_LNA_EN_ACTIVE); #endif @@ -46,9 +50,15 @@ void LoRaFEMControl::setLNAEnable(bool enabled) { } void LoRaFEMControl::setPAGainEnable(bool enabled) { + // Recorded only -- the pin is driven from setTxModeEnable(). The PA level only matters + // while transmitting, so deferring costs nothing and keeps the rail change out of an + // in-flight transmit (the CLI runs on every main-loop pass, including mid-TX). pa_gain_enabled = enabled; +} + +void LoRaFEMControl::applyPAGain() { #ifdef P_PA1_EN - digitalWrite(P_PA1_EN, enabled ? P_PA1_EN_ACTIVE : !P_PA1_EN_ACTIVE); + digitalWrite(P_PA1_EN, pa_gain_enabled ? P_PA1_EN_ACTIVE : !P_PA1_EN_ACTIVE); #endif } diff --git a/variants/station_g3_esp32/LoRaFEMControl.h b/variants/station_g3_esp32/LoRaFEMControl.h index 429d6127..f622de91 100644 --- a/variants/station_g3_esp32/LoRaFEMControl.h +++ b/variants/station_g3_esp32/LoRaFEMControl.h @@ -15,6 +15,8 @@ public: bool isPAGainEnabled() const { return pa_gain_enabled; } private: + void applyPAGain(); + bool lna_enabled = true; bool pa_gain_enabled = false; }; From 964d87c8904ffa13004162c09cfd1b191d6e726e Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Sun, 9 Aug 2026 11:41:09 +1000 Subject: [PATCH 086/381] add QSPIFlash support for Seeed MeshTracker X1 --- variants/meshtracker_x1/platformio.ini | 2 ++ variants/meshtracker_x1/variant.cpp | 3 +++ variants/meshtracker_x1/variant.h | 14 ++++++++++++++ 3 files changed, 19 insertions(+) diff --git a/variants/meshtracker_x1/platformio.ini b/variants/meshtracker_x1/platformio.ini index 6a46a79f..1ce8bf17 100644 --- a/variants/meshtracker_x1/platformio.ini +++ b/variants/meshtracker_x1/platformio.ini @@ -75,6 +75,7 @@ board_build.ldscript = boards/nrf52840_s140_v7_extrafs.ld board_upload.maximum_size = 708608 build_flags = ${MeshTracker_X1.build_flags} -I examples/companion_radio/ui-orig + -D QSPIFLASH=1 -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 ; -D MESH_PACKET_LOGGING=1 @@ -103,6 +104,7 @@ board_build.ldscript = boards/nrf52840_s140_v7_extrafs.ld board_upload.maximum_size = 708608 build_flags = ${MeshTracker_X1.build_flags} -I examples/companion_radio/ui-orig + -D QSPIFLASH=1 -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D BLE_PIN_CODE=123456 diff --git a/variants/meshtracker_x1/variant.cpp b/variants/meshtracker_x1/variant.cpp index 5a685a8e..27c4c22e 100644 --- a/variants/meshtracker_x1/variant.cpp +++ b/variants/meshtracker_x1/variant.cpp @@ -70,6 +70,9 @@ void initVariant() pinMode(PIN_3V3_EN, OUTPUT); digitalWrite(PIN_3V3_EN, HIGH); + pinMode(PIN_FLASH_EN, OUTPUT); + digitalWrite(PIN_FLASH_EN, HIGH); + pinMode(PIN_BAT_ADC_EN, OUTPUT); digitalWrite(PIN_BAT_ADC_EN, HIGH); diff --git a/variants/meshtracker_x1/variant.h b/variants/meshtracker_x1/variant.h index c3dbd274..46414b48 100644 --- a/variants/meshtracker_x1/variant.h +++ b/variants/meshtracker_x1/variant.h @@ -122,3 +122,17 @@ // Buzzer #define BUZZER_PIN (25) // P0.25, pwm output + +//////////////////////////////////////////////////////////////////////////////// +// QSPI Flash + +#define PIN_FLASH_EN (15) // P0.15 (Flash power enable) + +#define PIN_QSPI_SCK (19) // P0.19 +#define PIN_QSPI_CS (20) // P0.20 +#define PIN_QSPI_IO0 (21) // P0.21 +#define PIN_QSPI_IO1 (22) // P0.22 +#define PIN_QSPI_IO2 (23) // P0.23 +#define PIN_QSPI_IO3 (32) // P1.00 + +#define EXTERNAL_FLASH_DEVICES GD25Q64C \ No newline at end of file From e1fa02a67713e38333ec26b26c70b53c323d021b Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Sun, 9 Aug 2026 11:45:35 +1000 Subject: [PATCH 087/381] bump CustomLFS version for GD25Q64C support --- platformio.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platformio.ini b/platformio.ini index aa336dec..e78124a4 100644 --- a/platformio.ini +++ b/platformio.ini @@ -94,7 +94,7 @@ build_flags = ${arduino_base.build_flags} -D USE_CC310_HW_CRYPTO=1 lib_deps = ${arduino_base.lib_deps} - https://github.com/oltaco/CustomLFS#0.2.2 + https://github.com/oltaco/CustomLFS#0.2.3 ; ----------------- RP2040 --------------------- [rp2040_base] From 430ef3b0864668f17f33917d11ea4011da638c44 Mon Sep 17 00:00:00 2001 From: entr0p1 <1475255+entr0p1@users.noreply.github.com> Date: Sun, 9 Aug 2026 14:09:35 +1000 Subject: [PATCH 088/381] Lilygo T-Echo Lite Pin Fixes - Aligned to Lilygo's updated schematic and pin map as per https://github.com/Xinyuan-LilyGO/T-Echo-Lite/issues/14 --- variants/lilygo_techo_lite/platformio.ini | 6 +++--- variants/lilygo_techo_lite/variant.h | 2 ++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/variants/lilygo_techo_lite/platformio.ini b/variants/lilygo_techo_lite/platformio.ini index 9ec73d59..1a8ad677 100644 --- a/variants/lilygo_techo_lite/platformio.ini +++ b/variants/lilygo_techo_lite/platformio.ini @@ -12,10 +12,9 @@ build_flags = ${nrf52_base.build_flags} -D WRAPPER_CLASS=CustomSX1262Wrapper -D LORA_TX_POWER=22 -D SX126X_POWER_EN=30 - -D SX126X_DIO3_TCXO_VOLTAGE=1.8 + -D SX126X_DIO3_TCXO_VOLTAGE=3.0 -D SX126X_CURRENT_LIMIT=140 -D SX126X_RX_BOOSTED_GAIN=1 - -D SX126X_USE_REGULATOR_LDO=1 -D P_LORA_TX_LED=LED_GREEN -D DISABLE_DIAGNOSTIC_OUTPUT -D ENV_INCLUDE_GPS=1 @@ -117,7 +116,7 @@ build_flags = -D WRAPPER_CLASS=CustomSX1262Wrapper -D LORA_TX_POWER=22 -D SX126X_POWER_EN=30 - -D SX126X_DIO3_TCXO_VOLTAGE=1.8 + -D SX126X_DIO3_TCXO_VOLTAGE=3.0 -D SX126X_CURRENT_LIMIT=140 -D SX126X_RX_BOOSTED_GAIN=1 -D P_LORA_TX_LED=LED_GREEN @@ -162,6 +161,7 @@ build_flags = -D WRAPPER_CLASS=CustomSX1262Wrapper -D LORA_TX_POWER=22 -D SX126X_POWER_EN=30 + -D SX126X_DIO3_TCXO_VOLTAGE=3.0 -D SX126X_CURRENT_LIMIT=140 -D SX126X_RX_BOOSTED_GAIN=1 -D P_LORA_TX_LED=LED_GREEN diff --git a/variants/lilygo_techo_lite/variant.h b/variants/lilygo_techo_lite/variant.h index 702ab334..38b79c66 100644 --- a/variants/lilygo_techo_lite/variant.h +++ b/variants/lilygo_techo_lite/variant.h @@ -105,12 +105,14 @@ #define LORA_CS _PINNUM(0, 11) #define SX126X_POWER_EN _PINNUM(0, 30) #define SX126X_DIO1 _PINNUM(1, 8) +#define SX126X_DIO2 _PINNUM(0, 5) #define SX126X_BUSY _PINNUM(0, 14) #define SX126X_RESET _PINNUM(0, 7) #define SX126X_RXEN _PINNUM(1, 1) #define SX126X_TXEN _PINNUM(0, 27) #define P_LORA_DIO_1 SX126X_DIO1 +#define P_LORA_DIO_2 SX126X_DIO2 #define P_LORA_NSS LORA_CS #define P_LORA_RESET SX126X_RESET #define P_LORA_BUSY SX126X_BUSY From 68dedd3e967e93a0ac89d9ae140ef5b3baeddf51 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Sun, 9 Aug 2026 15:14:46 +1000 Subject: [PATCH 089/381] * version 1.17.0 --- examples/companion_radio/MyMesh.h | 4 ++-- examples/simple_repeater/MyMesh.h | 4 ++-- examples/simple_room_server/MyMesh.h | 4 ++-- examples/simple_sensor/SensorMesh.h | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/examples/companion_radio/MyMesh.h b/examples/companion_radio/MyMesh.h index d95b073f..f73fe0e0 100644 --- a/examples/companion_radio/MyMesh.h +++ b/examples/companion_radio/MyMesh.h @@ -8,11 +8,11 @@ #define FIRMWARE_VER_CODE 13 #ifndef FIRMWARE_BUILD_DATE -#define FIRMWARE_BUILD_DATE "6 Jun 2026" +#define FIRMWARE_BUILD_DATE "9 Aug 2026" #endif #ifndef FIRMWARE_VERSION -#define FIRMWARE_VERSION "v1.16.0" +#define FIRMWARE_VERSION "v1.17.0" #endif #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index e959f01a..2f923c87 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -70,11 +70,11 @@ struct NeighbourInfo { }; #ifndef FIRMWARE_BUILD_DATE - #define FIRMWARE_BUILD_DATE "6 Jun 2026" + #define FIRMWARE_BUILD_DATE "9 Aug 2026" #endif #ifndef FIRMWARE_VERSION - #define FIRMWARE_VERSION "v1.16.0" + #define FIRMWARE_VERSION "v1.17.0" #endif #define FIRMWARE_ROLE "repeater" diff --git a/examples/simple_room_server/MyMesh.h b/examples/simple_room_server/MyMesh.h index 5f78bee8..878c2e95 100644 --- a/examples/simple_room_server/MyMesh.h +++ b/examples/simple_room_server/MyMesh.h @@ -27,11 +27,11 @@ /* ------------------------------ Config -------------------------------- */ #ifndef FIRMWARE_BUILD_DATE - #define FIRMWARE_BUILD_DATE "6 Jun 2026" + #define FIRMWARE_BUILD_DATE "9 Aug 2026" #endif #ifndef FIRMWARE_VERSION - #define FIRMWARE_VERSION "v1.16.0" + #define FIRMWARE_VERSION "v1.17.0" #endif #ifndef LORA_FREQ diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index 1d65b877..3a33b638 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -34,11 +34,11 @@ #define PERM_RECV_ALERTS_HI (1 << 7) // high priority alerts #ifndef FIRMWARE_BUILD_DATE - #define FIRMWARE_BUILD_DATE "6 Jun 2026" + #define FIRMWARE_BUILD_DATE "9 Aug 2026" #endif #ifndef FIRMWARE_VERSION - #define FIRMWARE_VERSION "v1.16.0" + #define FIRMWARE_VERSION "v1.17.0" #endif #define FIRMWARE_ROLE "sensor" From 7634c077e523a92ad971618cb1a28c8f12cc5faf Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Sun, 9 Aug 2026 16:50:44 +1000 Subject: [PATCH 090/381] build fix for R1 Neo repeater added missing declarations for user_btn and NullDisplayDriver --- variants/muziworks_r1_neo/platformio.ini | 1 + variants/muziworks_r1_neo/target.cpp | 11 ++++++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/variants/muziworks_r1_neo/platformio.ini b/variants/muziworks_r1_neo/platformio.ini index 52dc3e38..2fbb8ad6 100644 --- a/variants/muziworks_r1_neo/platformio.ini +++ b/variants/muziworks_r1_neo/platformio.ini @@ -10,6 +10,7 @@ build_flags = ${nrf52_base.build_flags} -D NRF52_POWER_MANAGEMENT -D RADIO_CLASS=CustomSX1262 -D WRAPPER_CLASS=CustomSX1262Wrapper + -D DISPLAY_CLASS=NullDisplayDriver -D LORA_TX_POWER=22 -D SX126X_CURRENT_LIMIT=140 -D SX126X_RX_BOOSTED_GAIN=1 diff --git a/variants/muziworks_r1_neo/target.cpp b/variants/muziworks_r1_neo/target.cpp index 68655c5d..f667a282 100644 --- a/variants/muziworks_r1_neo/target.cpp +++ b/variants/muziworks_r1_neo/target.cpp @@ -4,12 +4,17 @@ R1NeoBoard board; -DISPLAY_CLASS display; - RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, SPI); - WRAPPER_CLASS radio_driver(radio, board); +#ifdef DISPLAY_CLASS + NullDisplayDriver display; +#endif + +#ifdef PIN_USER_BTN +MomentaryButton user_btn(PIN_USER_BTN, 1000, true); +#endif + VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); From 05bdabe425a3174b084c7f7b5a91f3e32ffe0f24 Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Sun, 9 Aug 2026 16:51:45 +1000 Subject: [PATCH 091/381] R1 neo: remove stray lib_deps entry --- variants/muziworks_r1_neo/platformio.ini | 1 - 1 file changed, 1 deletion(-) diff --git a/variants/muziworks_r1_neo/platformio.ini b/variants/muziworks_r1_neo/platformio.ini index 2fbb8ad6..c139e34a 100644 --- a/variants/muziworks_r1_neo/platformio.ini +++ b/variants/muziworks_r1_neo/platformio.ini @@ -101,7 +101,6 @@ build_src_filter = ${R1Neo.build_src_filter} +<../examples/companion_radio/ui-orig/*.cpp> lib_deps = ${R1Neo.lib_deps} - ${rak4631.lib_deps} densaugeo/base64 @ ~1.4.0 end2endzone/NonBlockingRTTTL@^1.3.0 From 2d412be46526631fc49ac29d4e5bf401287cdb29 Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Sun, 9 Aug 2026 18:33:27 +1000 Subject: [PATCH 092/381] minewsemi: build fix and platformio.ini tidy up fixes minewsemi repeater failing build due to user_btn missing. --- variants/minewsemi_me25ls01/platformio.ini | 18 +----------------- variants/minewsemi_me25ls01/target.cpp | 4 ++-- variants/minewsemi_me25ls01/target.h | 9 +++++---- 3 files changed, 8 insertions(+), 23 deletions(-) diff --git a/variants/minewsemi_me25ls01/platformio.ini b/variants/minewsemi_me25ls01/platformio.ini index d115a1f1..1743e719 100644 --- a/variants/minewsemi_me25ls01/platformio.ini +++ b/variants/minewsemi_me25ls01/platformio.ini @@ -21,6 +21,7 @@ build_flags = ${nrf52_base.build_flags} -D ENV_INCLUDE_INA219=1 build_src_filter = ${nrf52_base.build_src_filter} +<helpers/*.cpp> + +<helpers/ui/NullDisplayDriver.cpp> +<../variants/minewsemi_me25ls01> +<helpers/sensors> debug_tool = jlink @@ -55,7 +56,6 @@ build_flags = ${me25ls01.build_flags} ;-D PIN_BUZZER=25 ;-D PIN_BUZZER_EN=37 build_src_filter = ${me25ls01.build_src_filter} - +<helpers/ui/NullDisplayDriver.cpp> +<helpers/nrf52/SerialBLEInterface.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-orig/*.cpp> @@ -63,10 +63,6 @@ build_src_filter = ${me25ls01.build_src_filter} [env:Minewsemi_me25ls01_repeater] extends = me25ls01 build_flags = ${me25ls01.build_flags} - -D MAX_CONTACTS=100 - -D MAX_GROUP_CHANNELS=8 - -D BLE_PIN_CODE=123456 -; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 -D OFFLINE_QUEUE_SIZE=256 @@ -85,10 +81,6 @@ build_src_filter = ${me25ls01.build_src_filter} [env:Minewsemi_me25ls01_room_server] extends = me25ls01 build_flags = ${me25ls01.build_flags} - -D MAX_CONTACTS=100 - -D MAX_GROUP_CHANNELS=8 -; -D BLE_PIN_CODE=123456 -; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 -D OFFLINE_QUEUE_SIZE=256 @@ -103,15 +95,10 @@ build_flags = ${me25ls01.build_flags} -D DISPLAY_CLASS=NullDisplayDriver build_src_filter = ${me25ls01.build_src_filter} +<../examples/simple_room_server> - +<helpers/ui/NullDisplayDriver.cpp> [env:Minewsemi_me25ls01_terminal_chat] extends = me25ls01 build_flags = ${me25ls01.build_flags} - -D MAX_CONTACTS=100 - -D MAX_GROUP_CHANNELS=8 - -D BLE_PIN_CODE=123456 -; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 -D OFFLINE_QUEUE_SIZE=256 @@ -126,7 +113,6 @@ build_flags = ${me25ls01.build_flags} -D DISPLAY_CLASS=NullDisplayDriver build_src_filter = ${me25ls01.build_src_filter} +<../examples/simple_secure_chat/main.cpp> - +<helpers/ui/NullDisplayDriver.cpp> [env:Minewsemi_me25ls01_companion_radio_usb] extends = me25ls01 @@ -137,7 +123,6 @@ build_flags = ${me25ls01.build_flags} -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 ;-D BLE_PIN_CODE=123456 -; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 -D OFFLINE_QUEUE_SIZE=256 @@ -147,7 +132,6 @@ build_flags = ${me25ls01.build_flags} -D ENABLE_USB_INTERFACE build_src_filter = ${me25ls01.build_src_filter} +<helpers/nrf52/*.cpp> - +<helpers/ui/NullDisplayDriver.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-orig/*.cpp> diff --git a/variants/minewsemi_me25ls01/target.cpp b/variants/minewsemi_me25ls01/target.cpp index 9944a38b..41fc71a7 100644 --- a/variants/minewsemi_me25ls01/target.cpp +++ b/variants/minewsemi_me25ls01/target.cpp @@ -4,7 +4,6 @@ MinewsemiME25LS01Board board; RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, SPI); - WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock rtc_clock; @@ -18,7 +17,8 @@ extern EnvironmentSensorManager sensors; #endif #ifdef DISPLAY_CLASS - NullDisplayDriver display; + DISPLAY_CLASS display; + MomentaryButton user_btn(PIN_USER_BTN, 1000, true); #endif #ifndef LORA_CR diff --git a/variants/minewsemi_me25ls01/target.h b/variants/minewsemi_me25ls01/target.h index 978e616b..db44058c 100644 --- a/variants/minewsemi_me25ls01/target.h +++ b/variants/minewsemi_me25ls01/target.h @@ -11,16 +11,17 @@ #include <helpers/sensors/EnvironmentSensorManager.h> #ifdef DISPLAY_CLASS #include <helpers/ui/NullDisplayDriver.h> -#endif - -#ifdef DISPLAY_CLASS - extern NullDisplayDriver display; + #include <helpers/ui/MomentaryButton.h> #endif extern MinewsemiME25LS01Board board; extern WRAPPER_CLASS radio_driver; extern VolatileRTCClock rtc_clock; extern EnvironmentSensorManager sensors; +#ifdef DISPLAY_CLASS + extern DISPLAY_CLASS display; + extern MomentaryButton user_btn; +#endif bool radio_init(); mesh::LocalIdentity radio_new_identity(); From 203c44c9f50d79d330b415a662165c57396abaff Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Sun, 9 Aug 2026 21:41:22 +1000 Subject: [PATCH 093/381] LR2021: add PREAMBLE_DETECTED bit and IRQ timeout logic --- src/helpers/radiolib/CustomLR2021.h | 59 +++++++++++++++++++++- src/helpers/radiolib/CustomLR2021Wrapper.h | 4 ++ 2 files changed, 61 insertions(+), 2 deletions(-) diff --git a/src/helpers/radiolib/CustomLR2021.h b/src/helpers/radiolib/CustomLR2021.h index 17944ef0..a89ae943 100644 --- a/src/helpers/radiolib/CustomLR2021.h +++ b/src/helpers/radiolib/CustomLR2021.h @@ -4,6 +4,10 @@ #include "MeshCore.h" class CustomLR2021 : public LR2021 { + uint32_t _preambleMillis = 66; + uint32_t _maxPayloadMillis = 3934; + uint32_t _activityAt = 0; + bool _headerSeen = false; bool _rx_boosted = false; public: @@ -66,11 +70,62 @@ class CustomLR2021 : public LR2021 { bool getRxBoostedGainMode() const { return _rx_boosted; } + int16_t startReceive() override { + // include the PREAMBLE_DETECTED irq bit in reported flags + return LR2021::startReceive(RADIOLIB_LR2021_RX_TIMEOUT_INF, RADIOLIB_IRQ_RX_DEFAULT_FLAGS | (1UL << RADIOLIB_LR2021_IRQ_PREAMBLE_DETECTED), RADIOLIB_IRQ_RX_DEFAULT_MASK, 0); + } + bool isReceiving() { uint32_t irq = getIrqStatus(); - bool detected = ((irq & RADIOLIB_LR2021_IRQ_SYNCWORD_VALID) || (irq & RADIOLIB_LR2021_IRQ_PREAMBLE_DETECTED)); - return detected; + bool preamble = irq & RADIOLIB_LR2021_IRQ_PREAMBLE_DETECTED; // bit 5 + bool header = irq & RADIOLIB_LR2021_IRQ_LORA_HEADER_VALID; // bit 6 + bool hdrErr = irq & RADIOLIB_LR2021_IRQ_LORA_HDR_CRC_ERROR; // bit 9 + uint32_t now = millis(); + if (hdrErr) { + clearIrqFlags(RADIOLIB_LR2021_IRQ_PREAMBLE_DETECTED | RADIOLIB_LR2021_IRQ_LORA_HEADER_VALID | RADIOLIB_LR2021_IRQ_LORA_HDR_CRC_ERROR); + _activityAt = 0; + _headerSeen = false; + return false; + } + if (!header && _headerSeen) { + // something cleared the header flag, reset our state. + _activityAt = 0; _headerSeen = false; + return false; + } + + if (header) { + if (!_headerSeen) { _headerSeen = true; _activityAt = now; }; + if (now - _activityAt > _maxPayloadMillis) { + MESH_DEBUG_PRINTLN("Clearing header IRQ after %ums", _maxPayloadMillis); + clearIrqFlags(RADIOLIB_LR2021_IRQ_PREAMBLE_DETECTED | RADIOLIB_LR2021_IRQ_LORA_HEADER_VALID | RADIOLIB_LR2021_IRQ_LORA_HDR_CRC_ERROR); + _activityAt = 0; _headerSeen = false; + return false; + } + return true; + } + if (preamble) { + if (_activityAt == 0) _activityAt = now; + if (now - _activityAt > _preambleMillis) { + clearIrqFlags(RADIOLIB_LR2021_IRQ_PREAMBLE_DETECTED); + _activityAt = 0; + MESH_DEBUG_PRINTLN("Clearing preamble IRQ after %ums", _preambleMillis); + return false; + } + return true; + } + _activityAt = 0; _headerSeen = false; + return false; } + + void setPreambleMillis(uint32_t preambleMillis) { + _preambleMillis = preambleMillis; + MESH_DEBUG_PRINTLN("Set _preambleMillis=%u", _preambleMillis); + } + void setMaxPayloadMillis(uint32_t payloadMillis) { + _maxPayloadMillis = payloadMillis; + MESH_DEBUG_PRINTLN("Set _maxPayloadMillis=%u", _maxPayloadMillis); + } + uint8_t getSpreadingFactor() const { return spreadingFactor; } }; \ No newline at end of file diff --git a/src/helpers/radiolib/CustomLR2021Wrapper.h b/src/helpers/radiolib/CustomLR2021Wrapper.h index 87989831..8299e2bf 100644 --- a/src/helpers/radiolib/CustomLR2021Wrapper.h +++ b/src/helpers/radiolib/CustomLR2021Wrapper.h @@ -22,6 +22,10 @@ public: ((CustomLR2021 *)_radio)->setCodingRate(cr); updatePreamble(sf); applySideDetectorConfig(); + PacketMillis pm = calcMaxPacketMillis(sf, bw, cr, preambleLengthForSF(sf)); + ((CustomLR2021 *)_radio)->setPreambleMillis(pm.preambleMillis); + ((CustomLR2021 *)_radio)->setMaxPayloadMillis(pm.payloadMillis); + } bool configSideDetectors(const uint8_t* sideDetSFs, uint8_t num, float bw) override { From d3f9cbb922f911ec225cec3b42a6f13920ba2587 Mon Sep 17 00:00:00 2001 From: Rastislav Vysoky <recrof@gmail.com> Date: Sun, 9 Aug 2026 14:17:18 +0200 Subject: [PATCH 094/381] add missing kiss radio roles, add kiss radio build to build.sh --- build.sh | 16 ++++++++++++++++ variants/lilygo_techo_card/platformio.ini | 5 +++++ variants/lilygo_teth_elite/platformio.ini | 5 +++++ variants/meshtracker_x1/platformio.ini | 5 +++++ .../sensecap_indicator-espnow/platformio.ini | 4 ++-- variants/sensecap_solar/platformio.ini | 5 +++++ variants/station_g2/platformio.ini | 6 ++---- 7 files changed, 40 insertions(+), 6 deletions(-) diff --git a/build.sh b/build.sh index 5d408345..80ff4cdf 100755 --- a/build.sh +++ b/build.sh @@ -34,6 +34,9 @@ $ sh build.sh build-repeater-firmwares Build all chat room server firmwares $ sh build.sh build-room-server-firmwares +Build all kiss radio firmwares +$ sh build.sh build-kiss-radio-firmwares + Environment Variables: DISABLE_DEBUG=1: Disables all debug logging flags (MESH_DEBUG, MESH_PACKET_LOGGING, etc.) If not set, debug flags from variant platformio.ini files are used. @@ -242,6 +245,17 @@ build_room_server_firmwares() { } +build_kiss_modem_firmwares() { + +# # build specific kiss radio firmwares +# build_firmware "Heltec_v3_kiss_modem" +# build_firmware "RAK_4631_kiss_modem" + + # build all room server firmwares + build_all_firmwares_by_suffix "_kiss_modem" + +} + build_firmwares() { build_companion_firmwares build_repeater_firmwares @@ -278,6 +292,8 @@ elif [[ $1 == "build-repeater-firmwares" ]]; then build_repeater_firmwares elif [[ $1 == "build-room-server-firmwares" ]]; then build_room_server_firmwares +elif [[ $1 == "build-kiss-radio-firmwares" ]]; then + build_kiss_modem_firmwares elif [[ $1 == "get-companion-firmwares-to-build" ]]; then get_pio_envs_ending_with_string "_companion_radio_usb" get_pio_envs_ending_with_string "_companion_radio_ble" diff --git a/variants/lilygo_techo_card/platformio.ini b/variants/lilygo_techo_card/platformio.ini index 4ebf43da..17ba8d1b 100644 --- a/variants/lilygo_techo_card/platformio.ini +++ b/variants/lilygo_techo_card/platformio.ini @@ -119,3 +119,8 @@ lib_deps = ${LilyGo_T-Echo_Card.lib_deps} end2endzone/NonBlockingRTTTL@^1.3.0 densaugeo/base64 @ ~1.4.0 + +[env:LilyGo_T-Echo_Card_kiss_modem] +extends = LilyGo_T-Echo_Card +build_src_filter = ${LilyGo_T-Echo_Card.build_src_filter} + +<../examples/kiss_modem/> diff --git a/variants/lilygo_teth_elite/platformio.ini b/variants/lilygo_teth_elite/platformio.ini index ee1b9879..2debb039 100644 --- a/variants/lilygo_teth_elite/platformio.ini +++ b/variants/lilygo_teth_elite/platformio.ini @@ -98,3 +98,8 @@ build_src_filter = ${LilyGo_TETH_Elite_sx1262.build_src_filter} lib_deps = ${LilyGo_TETH_Elite_sx1262.lib_deps} densaugeo/base64 @ ~1.4.0 + +[env:LilyGo_TETH_Elite_sx1262_kiss_modem] +extends = LilyGo_TETH_Elite_sx1262 +build_src_filter = ${LilyGo_TETH_Elite_sx1262.build_src_filter} + +<../examples/kiss_modem/> diff --git a/variants/meshtracker_x1/platformio.ini b/variants/meshtracker_x1/platformio.ini index 1ce8bf17..2194d48d 100644 --- a/variants/meshtracker_x1/platformio.ini +++ b/variants/meshtracker_x1/platformio.ini @@ -130,3 +130,8 @@ lib_deps = ${MeshTracker_X1.lib_deps} stevemarple/MicroNMEA @ ^2.0.6 end2endzone/NonBlockingRTTTL@^1.3.0 adafruit/Adafruit DRV2605 Library @ ^1.2.4 + +[env:MeshTracker_X1_kiss_modem] +extends = MeshTracker_X1 +build_src_filter = ${MeshTracker_X1.build_src_filter} + +<../examples/kiss_modem/> diff --git a/variants/sensecap_indicator-espnow/platformio.ini b/variants/sensecap_indicator-espnow/platformio.ini index e643d033..a5952d6e 100644 --- a/variants/sensecap_indicator-espnow/platformio.ini +++ b/variants/sensecap_indicator-espnow/platformio.ini @@ -33,7 +33,7 @@ lib_deps=${esp32_base.lib_deps} lovyan03/LovyanGFX @ ^1.2.7 [env:SenseCapIndicator-ESPNow_comp_radio_usb] -extends =SenseCapIndicator-ESPNow +extends = SenseCapIndicator-ESPNow build_flags = ${SenseCapIndicator-ESPNow.build_flags} -I examples/companion_radio/ui-new @@ -47,4 +47,4 @@ build_src_filter = ${SenseCapIndicator-ESPNow.build_src_filter} +<../examples/companion_radio/*.cpp> lib_deps = ${SenseCapIndicator-ESPNow.lib_deps} - densaugeo/base64 @ ~1.4.0 \ No newline at end of file + densaugeo/base64 @ ~1.4.0 diff --git a/variants/sensecap_solar/platformio.ini b/variants/sensecap_solar/platformio.ini index 6e0eadbc..70405218 100644 --- a/variants/sensecap_solar/platformio.ini +++ b/variants/sensecap_solar/platformio.ini @@ -101,3 +101,8 @@ build_src_filter = ${SenseCap_Solar.build_src_filter} lib_deps = ${SenseCap_Solar.lib_deps} densaugeo/base64 @ ~1.4.0 + +[env:SenseCap_Solar_kiss_modem] +extends = SenseCap_Solar +build_src_filter = ${SenseCap_Solar.build_src_filter} + +<../examples/kiss_modem/> diff --git a/variants/station_g2/platformio.ini b/variants/station_g2/platformio.ini index 753aee7a..bdb7ee0c 100644 --- a/variants/station_g2/platformio.ini +++ b/variants/station_g2/platformio.ini @@ -229,7 +229,7 @@ build_flags = -D WIFI_DEBUG_LOGGING=1 -D WIFI_SSID='"myssid"' -D WIFI_PWD='"mypwd"' - -D OFFLINE_QUEUE_SIZE=256 + -D OFFLINE_QUEUE_SIZE=256 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${Station_G2.build_src_filter} @@ -242,10 +242,8 @@ lib_deps = [env:Station_G2_kiss_modem] extends = Station_G2 -build_unflags = - -DARDUINO_USB_MODE=0 build_flags = ${Station_G2.build_flags} - -DARDUINO_USB_MODE=1 + -D ARDUINO_USB_MODE=1 build_src_filter = ${Station_G2.build_src_filter} +<../examples/kiss_modem/> From b8324f4fa86f66f87bb466e550aa3aad7137490e Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Sun, 9 Aug 2026 14:46:23 -0400 Subject: [PATCH 095/381] nrf52: call nRFCrypto.begin()/end() only once --- src/Identity.cpp | 2 -- src/Utils.cpp | 12 ------------ src/helpers/NRF52Board.cpp | 13 +++++++++++++ src/helpers/radiolib/RadioLibWrappers.h | 2 -- 4 files changed, 13 insertions(+), 16 deletions(-) diff --git a/src/Identity.cpp b/src/Identity.cpp index 25419fd4..51a01ae7 100644 --- a/src/Identity.cpp +++ b/src/Identity.cpp @@ -27,11 +27,9 @@ bool Identity::verify(const uint8_t* sig, const uint8_t* message, int msg_len) c // needs much less, around 600-700bytes. The CC310 workspace is static, faster, // should save power at scale as well. static CRYS_ECEDW_TempBuff_t cc310_tmp; - nRFCrypto.begin(); CRYSError_t rc = CRYS_ECEDW_Verify((uint8_t*)sig, CRYS_ECEDW_SIGNATURE_BYTES, (uint8_t*)pub_key, CRYS_ECEDW_MOD_SIZE_IN_BYTES, (uint8_t*)message, (size_t)msg_len, &cc310_tmp); - nRFCrypto.end(); return rc == CRYS_OK; #elif 0 // NOTE: memory corruption bug was found in this function!! diff --git a/src/Utils.cpp b/src/Utils.cpp index d4bc8c45..5ae7f0e2 100644 --- a/src/Utils.cpp +++ b/src/Utils.cpp @@ -24,9 +24,7 @@ uint32_t RNG::nextInt(uint32_t _min, uint32_t _max) { void Utils::sha256(uint8_t *hash, size_t hash_len, const uint8_t* msg, int msg_len) { #ifdef USE_CC310_HW_CRYPTO static CRYS_HASH_Result_t result; - nRFCrypto.begin(); CRYS_HASH(CRYS_HASH_SHA256_mode, (uint8_t*)msg, (size_t)msg_len, result); - nRFCrypto.end(); memcpy(hash, result, hash_len); #else SHA256 sha; @@ -39,12 +37,10 @@ void Utils::sha256(uint8_t *hash, size_t hash_len, const uint8_t* frag1, int fra #ifdef USE_CC310_HW_CRYPTO static CRYS_HASHUserContext_t ctx; static CRYS_HASH_Result_t result; - nRFCrypto.begin(); CRYS_HASH_Init(&ctx, CRYS_HASH_SHA256_mode); CRYS_HASH_Update(&ctx, (uint8_t*)frag1, (size_t)frag1_len); CRYS_HASH_Update(&ctx, (uint8_t*)frag2, (size_t)frag2_len); CRYS_HASH_Finish(&ctx, result); - nRFCrypto.end(); memcpy(hash, result, hash_len); #else SHA256 sha; @@ -62,7 +58,6 @@ int Utils::decrypt(const uint8_t* shared_secret, uint8_t* dest, const uint8_t* s const uint8_t* sp = src; size_t dummy_out = 0; - nRFCrypto.begin(); SaSi_AesInit(&ctx, SASI_AES_DECRYPT, SASI_AES_MODE_ECB, SASI_AES_PADDING_NONE); SaSi_AesSetKey(&ctx, SASI_AES_USER_KEY, &keyData, sizeof(keyData)); while (sp - src < src_len) { @@ -71,7 +66,6 @@ int Utils::decrypt(const uint8_t* shared_secret, uint8_t* dest, const uint8_t* s } SaSi_AesFinish(&ctx, 0, NULL, 0, NULL, &dummy_out); SaSi_AesFree(&ctx); - nRFCrypto.end(); return sp - src; #else AES128 aes; @@ -95,7 +89,6 @@ int Utils::encrypt(const uint8_t* shared_secret, uint8_t* dest, const uint8_t* s uint8_t* dp = dest; size_t dummy_out = 0; - nRFCrypto.begin(); SaSi_AesInit(&ctx, SASI_AES_ENCRYPT, SASI_AES_MODE_ECB, SASI_AES_PADDING_NONE); SaSi_AesSetKey(&ctx, SASI_AES_USER_KEY, &keyData, sizeof(keyData)); while (src_len >= 16) { @@ -110,7 +103,6 @@ int Utils::encrypt(const uint8_t* shared_secret, uint8_t* dest, const uint8_t* s } SaSi_AesFinish(&ctx, 0, NULL, 0, NULL, &dummy_out); SaSi_AesFree(&ctx); - nRFCrypto.end(); return dp - dest; #else AES128 aes; @@ -138,11 +130,9 @@ int Utils::encryptThenMAC(const uint8_t* shared_secret, uint8_t* dest, const uin #ifdef USE_CC310_HW_CRYPTO static CRYS_HMACUserContext_t hmac_ctx; static CRYS_HASH_Result_t hmac_result; - nRFCrypto.begin(); CRYS_HMAC_Init(&hmac_ctx, CRYS_HASH_SHA256_mode, (uint8_t*)shared_secret, PUB_KEY_SIZE); CRYS_HMAC_Update(&hmac_ctx, dest + CIPHER_MAC_SIZE, enc_len); CRYS_HMAC_Finish(&hmac_ctx, hmac_result); - nRFCrypto.end(); memcpy(dest, hmac_result, CIPHER_MAC_SIZE); #else SHA256 sha; @@ -162,11 +152,9 @@ int Utils::MACThenDecrypt(const uint8_t* shared_secret, uint8_t* dest, const uin { static CRYS_HMACUserContext_t hmac_ctx; static CRYS_HASH_Result_t hmac_result; - nRFCrypto.begin(); CRYS_HMAC_Init(&hmac_ctx, CRYS_HASH_SHA256_mode, (uint8_t*)shared_secret, PUB_KEY_SIZE); CRYS_HMAC_Update(&hmac_ctx, (uint8_t*)(src + CIPHER_MAC_SIZE), src_len - CIPHER_MAC_SIZE); CRYS_HMAC_Finish(&hmac_ctx, hmac_result); - nRFCrypto.end(); memcpy(hmac, hmac_result, CIPHER_MAC_SIZE); } #else diff --git a/src/helpers/NRF52Board.cpp b/src/helpers/NRF52Board.cpp index b6c8fec5..eb88c897 100644 --- a/src/helpers/NRF52Board.cpp +++ b/src/helpers/NRF52Board.cpp @@ -5,6 +5,10 @@ #include <bluefruit.h> #include <nrf_soc.h> +#ifdef USE_CC310_HW_CRYPTO +#include <Adafruit_nRFCrypto.h> +#endif + static BLEDfu bledfu; static void connect_callback(uint16_t conn_handle) { @@ -21,6 +25,11 @@ static void disconnect_callback(uint16_t conn_handle, uint8_t reason) { void NRF52Board::begin() { startup_reason = BD_STARTUP_NORMAL; + + #ifdef USE_CC310_HW_CRYPTO + // CC310 TRNG is higher quality and environment-independent vs radio RSSI noise. + nRFCrypto.begin(); + #endif } #ifdef NRF52_POWER_MANAGEMENT @@ -352,6 +361,10 @@ void NRF52Board::shutdownPeripherals() { sensors.getLocationProvider()->stop(); } +#ifdef USE_CC310_HW_CRYPTO + nRFCrypto.end(); +#endif + // Flush serial buffers Serial.flush(); delay(100); diff --git a/src/helpers/radiolib/RadioLibWrappers.h b/src/helpers/radiolib/RadioLibWrappers.h index 99f5ebbd..5db1e41f 100644 --- a/src/helpers/radiolib/RadioLibWrappers.h +++ b/src/helpers/radiolib/RadioLibWrappers.h @@ -93,9 +93,7 @@ public: void random(uint8_t* dest, size_t sz) override { #ifdef USE_CC310_HW_CRYPTO // CC310 TRNG is higher quality and environment-independent vs radio RSSI noise. - nRFCrypto.begin(); nRFCrypto.Random.generate(dest, (uint16_t)sz); - nRFCrypto.end(); #else for (int i = 0; i < sz; i++) { dest[i] = _radio->randomByte() ^ (::random(0, 256) & 0xFF); From 397ea610e6faff690f9de65e412a678895f105be Mon Sep 17 00:00:00 2001 From: Dan Theisen <djt@hxx.in> Date: Sun, 9 Aug 2026 18:04:24 -0700 Subject: [PATCH 096/381] RX Boosted Gain was set back to the compiled in value rather than the current/flash value set by the user when the ACG reset is triggered. This commit fixes this. --- src/helpers/radiolib/CustomLR1110Wrapper.h | 3 ++- src/helpers/radiolib/CustomSTM32WLxWrapper.h | 2 +- src/helpers/radiolib/CustomSX1262Wrapper.h | 4 ++-- src/helpers/radiolib/CustomSX1268Wrapper.h | 4 ++-- src/helpers/radiolib/LR11x0Reset.h | 4 ++-- src/helpers/radiolib/SX126xReset.h | 4 ++-- 6 files changed, 11 insertions(+), 10 deletions(-) diff --git a/src/helpers/radiolib/CustomLR1110Wrapper.h b/src/helpers/radiolib/CustomLR1110Wrapper.h index 44230c61..e7aaeb93 100644 --- a/src/helpers/radiolib/CustomLR1110Wrapper.h +++ b/src/helpers/radiolib/CustomLR1110Wrapper.h @@ -19,7 +19,6 @@ public: ((CustomLR1110 *)_radio)->setMaxPayloadMillis(pm.payloadMillis); } - void doResetAGC() override { lr11x0ResetAGC((LR11x0 *)_radio, ((CustomLR1110 *)_radio)->getFreqMHz()); } bool isReceivingPacket() override { return ((CustomLR1110 *)_radio)->isReceiving(); } @@ -50,4 +49,6 @@ public: bool getRxBoostedGainMode() const override { return ((CustomLR1110 *)_radio)->getRxBoostedGainMode(); } + + void doResetAGC() override { lr11x0ResetAGC((LR11x0 *)_radio, ((CustomLR1110 *)_radio)->getFreqMHz(), getRxBoostedGainMode()); } }; diff --git a/src/helpers/radiolib/CustomSTM32WLxWrapper.h b/src/helpers/radiolib/CustomSTM32WLxWrapper.h index a792a877..a4ba4971 100644 --- a/src/helpers/radiolib/CustomSTM32WLxWrapper.h +++ b/src/helpers/radiolib/CustomSTM32WLxWrapper.h @@ -35,5 +35,5 @@ public: } uint8_t getSpreadingFactor() const override { return ((CustomSTM32WLx *)_radio)->spreadingFactor; } - void doResetAGC() override { sx126xResetAGC((SX126x *)_radio); } + void doResetAGC() override { sx126xResetAGC((SX126x *)_radio, getRxBoostedGainMode()); } }; diff --git a/src/helpers/radiolib/CustomSX1262Wrapper.h b/src/helpers/radiolib/CustomSX1262Wrapper.h index bfea50ec..be314471 100644 --- a/src/helpers/radiolib/CustomSX1262Wrapper.h +++ b/src/helpers/radiolib/CustomSX1262Wrapper.h @@ -41,12 +41,12 @@ public: ((CustomSX1262 *)_radio)->sleep(false); } - void doResetAGC() override { sx126xResetAGC((SX126x *)_radio); } - bool setRxBoostedGainMode(bool en) override { return ((CustomSX1262 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE; } bool getRxBoostedGainMode() const override { return ((CustomSX1262 *)_radio)->getRxBoostedGainMode(); } + + void doResetAGC() override { sx126xResetAGC((SX126x *)_radio, getRxBoostedGainMode()); } }; diff --git a/src/helpers/radiolib/CustomSX1268Wrapper.h b/src/helpers/radiolib/CustomSX1268Wrapper.h index 104ba08b..70f5dabd 100644 --- a/src/helpers/radiolib/CustomSX1268Wrapper.h +++ b/src/helpers/radiolib/CustomSX1268Wrapper.h @@ -38,12 +38,12 @@ public: } uint8_t getSpreadingFactor() const override { return ((CustomSX1268 *)_radio)->spreadingFactor; } - void doResetAGC() override { sx126xResetAGC((SX126x *)_radio); } - bool setRxBoostedGainMode(bool en) override { return ((CustomSX1268 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE; } bool getRxBoostedGainMode() const override { return ((CustomSX1268 *)_radio)->getRxBoostedGainMode(); } + + void doResetAGC() override { sx126xResetAGC((SX126x *)_radio, getRxBoostedGainMode()); } }; diff --git a/src/helpers/radiolib/LR11x0Reset.h b/src/helpers/radiolib/LR11x0Reset.h index d06ffc53..cdfc1f9f 100644 --- a/src/helpers/radiolib/LR11x0Reset.h +++ b/src/helpers/radiolib/LR11x0Reset.h @@ -5,7 +5,7 @@ // Full receiver reset for LR11x0-family chips (LR1110, LR1120, LR1121). // Warm sleep powers down analog, calibrate(0x3F) refreshes all calibration blocks, // then re-applies RX settings that calibration may reset. -inline void lr11x0ResetAGC(LR11x0* radio, float freqMHz) { +inline void lr11x0ResetAGC(LR11x0* radio, float freqMHz, bool rx_boost_gain) { radio->sleep(true, 0); radio->standby(RADIOLIB_LR11X0_STANDBY_RC, true); @@ -16,6 +16,6 @@ inline void lr11x0ResetAGC(LR11x0* radio, float freqMHz) { radio->calibrateImageRejection(freqMHz - 4.0f, freqMHz + 4.0f); #ifdef RX_BOOSTED_GAIN - radio->setRxBoostedGainMode(RX_BOOSTED_GAIN); + radio->setRxBoostedGainMode(rx_boost_gain); #endif } diff --git a/src/helpers/radiolib/SX126xReset.h b/src/helpers/radiolib/SX126xReset.h index 39ddb73e..472eb33b 100644 --- a/src/helpers/radiolib/SX126xReset.h +++ b/src/helpers/radiolib/SX126xReset.h @@ -5,7 +5,7 @@ // Full receiver reset for all SX126x-family chips (SX1262, SX1268, LLCC68, STM32WLx). // Warm sleep powers down analog, Calibrate(0x7F) refreshes ADC/PLL/image calibration, // then re-applies RX settings that calibration may reset. -inline void sx126xResetAGC(SX126x* radio) { +inline void sx126xResetAGC(SX126x* radio, bool rx_boost_gain) { radio->sleep(true); radio->standby(RADIOLIB_SX126X_STANDBY_RC, true); @@ -26,7 +26,7 @@ inline void sx126xResetAGC(SX126x* radio) { radio->setDio2AsRfSwitch(SX126X_DIO2_AS_RF_SWITCH); #endif #ifdef SX126X_RX_BOOSTED_GAIN - radio->setRxBoostedGainMode(SX126X_RX_BOOSTED_GAIN); + radio->setRxBoostedGainMode(rx_boost_gain); #endif #ifdef SX126X_REGISTER_PATCH uint8_t r_data = 0; From 1d98c49b1bbf80abd6f948689a095727e78a406b Mon Sep 17 00:00:00 2001 From: Wessel Nieboer <wessel@weebl.me> Date: Mon, 10 Aug 2026 13:39:00 +0200 Subject: [PATCH 097/381] Fix T-beam Supreme S3 display --- src/helpers/ui/SH1106Display.cpp | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/helpers/ui/SH1106Display.cpp b/src/helpers/ui/SH1106Display.cpp index c3840c02..8b91d857 100644 --- a/src/helpers/ui/SH1106Display.cpp +++ b/src/helpers/ui/SH1106Display.cpp @@ -24,8 +24,21 @@ bool SH1106Display::begin() { // Wire must already be initialised by board.begin() before this is called. // Boards with non-standard SH1106 addresses should define DISPLAY_ADDRESS - // in their variant/platformio configuration. - return i2c_probe(Wire, DISPLAY_ADDRESS) && display.begin(DISPLAY_ADDRESS, true); + // in their variant/platformio configuration. The SA0 strap selects 0x3C or + // 0x3D and differs between revisions of the same board (e.g. T-Beam + // Supreme), so fall back to the other address of the pair. + uint8_t addr = 0; + if (i2c_probe(Wire, DISPLAY_ADDRESS)) { + addr = DISPLAY_ADDRESS; + } else if (i2c_probe(Wire, DISPLAY_ADDRESS ^ 1)) { + addr = DISPLAY_ADDRESS ^ 1; + } + // Run the Adafruit init even when no panel answered: it is what allocates + // the frame buffer and the I2C device. Skipping it leaves i2c_dev and + // spi_dev NULL, and UITask::begin() calls turnOn() regardless of our + // return value, which then dereferences the null spi_dev. + bool ok = display.begin(addr ? addr : DISPLAY_ADDRESS, true); + return addr != 0 && ok; } void SH1106Display::turnOn() From 09ef746f2903557a09f90a988bfde049191bdffa Mon Sep 17 00:00:00 2001 From: Rastislav Vysoky <recrof@gmail.com> Date: Mon, 10 Aug 2026 16:56:56 +0200 Subject: [PATCH 098/381] move RadioLibWrapper noise_floor level message under special debug flag --- src/helpers/radiolib/RadioLibWrappers.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/helpers/radiolib/RadioLibWrappers.cpp b/src/helpers/radiolib/RadioLibWrappers.cpp index dc851e5c..b9c095ac 100644 --- a/src/helpers/radiolib/RadioLibWrappers.cpp +++ b/src/helpers/radiolib/RadioLibWrappers.cpp @@ -15,7 +15,7 @@ static volatile uint8_t state = STATE_IDLE; // this function is called when a complete packet // is transmitted by the module -static +static #if defined(ESP8266) || defined(ESP32) ICACHE_RAM_ATTR #endif @@ -100,7 +100,9 @@ void RadioLibWrapper::loop() { } _floor_sample_sum = 0; + #ifdef MESH_DEBUG_NOISE_FLOOR MESH_DEBUG_PRINTLN("RadioLibWrapper: noise_floor = %d", (int)_noise_floor); + #endif } } @@ -224,10 +226,10 @@ static float snr_threshold[] = { -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; @@ -243,7 +245,7 @@ PacketMillis RadioLibWrapper::calcMaxPacketMillis(uint8_t sf, float bw, uint8_t // preamble + syncword + sfd + header uint32_t preamble_us = (((preambleSymbols + 8) * 4 + sfCoeff1_x4) * tsym_us) / 4; - + // airtime for max packet at current radio settings uint32_t total_us = _radio->getTimeOnAir(MAX_TRANS_UNIT); // airtime for payload only (no preamble, header or SOF) From a3825aa272f7e5f3b416ddea223d3f4532020f66 Mon Sep 17 00:00:00 2001 From: Rastislav Vysoky <recrof@gmail.com> Date: Mon, 10 Aug 2026 20:13:59 +0200 Subject: [PATCH 099/381] make promicro pinmap more tidy, move the LoRa pins to variant.h --- variants/promicro/PromicroBoard.h | 13 ------------- variants/promicro/variant.cpp | 32 +++++++++++++++++++++++-------- variants/promicro/variant.h | 18 +++++++++++++++-- 3 files changed, 40 insertions(+), 23 deletions(-) diff --git a/variants/promicro/PromicroBoard.h b/variants/promicro/PromicroBoard.h index b190c47c..ee16c965 100644 --- a/variants/promicro/PromicroBoard.h +++ b/variants/promicro/PromicroBoard.h @@ -4,19 +4,6 @@ #include <Arduino.h> #include <helpers/NRF52Board.h> -#define P_LORA_NSS 13 //P1.13 45 -#define P_LORA_DIO_1 11 //P0.10 10 -#define P_LORA_RESET 10 //P0.09 9 -#define P_LORA_BUSY 16 //P0.29 29 -#define P_LORA_MISO 15 //P0.02 2 -#define P_LORA_SCLK 12 //P1.11 43 -#define P_LORA_MOSI 14 //P1.15 47 -#define SX126X_POWER_EN 21 //P0.13 13 -#define SX126X_RXEN 2 //P0.17 -#define SX126X_TXEN RADIOLIB_NC -#define SX126X_DIO2_AS_RF_SWITCH true -#define SX126X_DIO3_TCXO_VOLTAGE (1.8f) - #define PIN_VBAT_READ 17 #define ADC_MULTIPLIER (1.815f) // dependent on voltage divider resistors. TODO: more accurate battery tracking diff --git a/variants/promicro/variant.cpp b/variants/promicro/variant.cpp index 0a4c3aac..b7d281ac 100644 --- a/variants/promicro/variant.cpp +++ b/variants/promicro/variant.cpp @@ -3,13 +3,29 @@ #include "wiring_digital.h" const uint32_t g_ADigitalPinMap[] = { - 8, 6, 17, 20, 22, 24, 32, 11, 36, 38, - 9, 10, 43, 45, 47, 2, 29, 31, - 33, 34, 37, - 13, 15 + 8, // P0.08 = GPIO 0 + 6, // P0.06 = GPIO 1 + 17, // P0.17 = GPIO 2 + 20, // P0.20 = GPIO 3 + 22, // P0.22 = GPIO 4 + 24, // P0.24 = GPIO 5 + 32, // P1.00 = GPIO 6 + 11, // P0.11 = GPIO 7 + 36, // P1.04 = GPIO 8 + 38, // P1.06 = GPIO 9 + 9, // P0.09 = GPIO 10 + 10, // P0.10 = GPIO 11 + 43, // P1.11 = GPIO 12 + 45, // P1.13 = GPIO 13 + 47, // P1.15 = GPIO 14 + 2, // P0.02 = GPIO 15 + 29, // P0.29 = GPIO 16 + 31, // P0.31 = GPIO 17 + 33, // P1.01 = GPIO 18 + 34, // P1.02 = GPIO 19 + 37, // P1.05 = GPIO 20 + 13, // P0.13 = GPIO 21 + 15 // P0.15 = GPIO 22 }; -void initVariant() -{ -} - +void initVariant() {} diff --git a/variants/promicro/variant.h b/variants/promicro/variant.h index 98489da1..e8a78331 100644 --- a/variants/promicro/variant.h +++ b/variants/promicro/variant.h @@ -7,9 +7,9 @@ #pragma once #include "WVariant.h" - + //////////////////////////////////////////////////////////////////////////////// - // Low frequency clock source + // Low frequency clock source #define VARIANT_MCK (64000000ul) @@ -79,4 +79,18 @@ #define PIN_BUTTON1 (6) #define BUTTON_PIN PIN_BUTTON1 +////////////////////////////////////////////////////////////////////////////// +// LoRa +#define P_LORA_NSS (13) +#define P_LORA_DIO_1 (11) +#define P_LORA_RESET (10) +#define P_LORA_BUSY (16) +#define P_LORA_MISO (15) +#define P_LORA_SCLK (12) +#define P_LORA_MOSI (14) +#define SX126X_POWER_EN (21) +#define SX126X_RXEN (2) +#define SX126X_TXEN (-1) +#define SX126X_DIO2_AS_RF_SWITCH true +#define SX126X_DIO3_TCXO_VOLTAGE (1.8f) From f82950f311bc6e0a59124f50281e648ec29696b0 Mon Sep 17 00:00:00 2001 From: agessaman <adam@gessaman.com> Date: Mon, 10 Aug 2026 11:59:26 -0700 Subject: [PATCH 100/381] feat(companion_radio): add external FEM gain preferences for RX and TX for companions Introduced consistent preferences for external LoRa FEM RX and TX gain settings in NodePrefs. Updated companion MyMesh to apply these settings during initialization and transmission. Added unit tests to verify the round-trip serialization of these new preferences. --- examples/companion_radio/MyMesh.cpp | 4 + examples/companion_radio/NodePrefs.h | 7 +- src/helpers/CommonCLI.cpp | 3 +- .../test_companion_node_prefs.cpp | 80 +++++++++++++++++++ .../test_config_serializer.cpp | 65 ++++++++++++--- 5 files changed, 144 insertions(+), 15 deletions(-) create mode 100644 test/test_companion_node_prefs/test_companion_node_prefs.cpp diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index b03334c1..2c334066 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -885,6 +885,8 @@ MyMesh::MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMe _prefs.tx_power_dbm = LORA_TX_POWER; _prefs.gps_enabled = 0; // GPS disabled by default _prefs.gps_interval = 0; // No automatic GPS updates by default + _prefs.radio_fem_rxgain = 1; + _prefs.radio_fem_txgain = 0; //_prefs.rx_delay_base = 10.0f; enable once new algo fixed _prefs.setRepeatEn(false); #if defined(USE_SX1262) || defined(USE_SX1268) @@ -974,6 +976,8 @@ void MyMesh::begin(bool has_display) { radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr); radio_driver.setTxPower(_prefs.tx_power_dbm); radio_driver.setRxBoostedGainMode(_prefs.rx_boosted_gain); + board.setLoRaFemLnaEnabled(_prefs.radio_fem_rxgain); + board.setLoRaFemPaGainEnabled(_prefs.radio_fem_txgain); MESH_DEBUG_PRINTLN("RX Boosted Gain Mode: %s", radio_driver.getRxBoostedGainMode() ? "Enabled" : "Disabled"); } diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index 39a5386a..5e67daaa 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -32,6 +32,8 @@ public: uint32_t gps_interval = 0; // GPS read interval in seconds uint8_t autoadd_config = 0; // bitmask for auto-add contacts config uint8_t rx_boosted_gain = 0; // SX126x RX boosted gain mode (0=power saving, 1=boosted) + uint8_t radio_fem_rxgain = 0; // external LoRa FEM RX gain (LNA) + uint8_t radio_fem_txgain = 0; // external LoRa FEM TX gain (low by default) uint8_t _client_repeat = 0; // DEPRECATED -> use repeat.disable_fwd uint8_t path_hash_mode = 0; // which path mode to use when sending uint8_t autoadd_max_hops = 0; // 0 = no limit, 1 = direct (0 hops), N = up to N-1 hops (max 64) @@ -50,7 +52,8 @@ private: //def("cad", _parent->cad_enabled); //def("int_thr", _parent->interference_threshold); def("rxgain", _parent->rx_boosted_gain); - def("fem_rxgain", _parent->rx_boosted_gain); + def("fem_rxgain", _parent->radio_fem_rxgain); + def("fem_txgain", _parent->radio_fem_txgain); def("tx", _parent->tx_power_dbm); def("af", _parent->airtime_factor); def("rxdelay", _parent->rx_delay_base); @@ -133,4 +136,4 @@ public: // new accessor methods bool isRepeatEn() const { return repeat.disable_fwd == 0; } void setRepeatEn(bool en) { repeat.disable_fwd = en ? 0 : 1; } -}; \ No newline at end of file +}; diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index 56a52a0b..b318bb58 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -102,8 +102,7 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) { // Legacy file.read((uint8_t *)&_prefs->flood_max_advert, sizeof(_prefs->flood_max_advert)); // 292 file.read((uint8_t *)&_prefs->radio_fem_rxgain, sizeof(_prefs->radio_fem_rxgain)); // 293 file.read((uint8_t *)&_prefs->cad_enabled, sizeof(_prefs->cad_enabled)); // 294 - file.read((uint8_t *)&_prefs->radio_fem_txgain, sizeof(_prefs->radio_fem_txgain)); // 295 - // next: 296 + // next: 295 // sanitise bad pref values _prefs->rx_delay_base = constrain(_prefs->rx_delay_base, 0, 20.0f); diff --git a/test/test_companion_node_prefs/test_companion_node_prefs.cpp b/test/test_companion_node_prefs/test_companion_node_prefs.cpp new file mode 100644 index 00000000..6d3cebdf --- /dev/null +++ b/test/test_companion_node_prefs/test_companion_node_prefs.cpp @@ -0,0 +1,80 @@ +#include <gtest/gtest.h> + +#include <cstdio> +#include <cstring> +#include <string> + +#include "../../examples/companion_radio/NodePrefs.h" + +class ReplayStream : public Stream { + const char* _text; + int _pos = 0; + int _len; + +public: + explicit ReplayStream(const char* text) : _text(text), _len(strlen(text)) { } + + int available() override { return _len - _pos; } + int read() override { return _pos < _len ? _text[_pos++] : -1; } + int peek() override { return _pos < _len ? _text[_pos] : -1; } +}; + +class CaptureStream : public Stream { + std::string _text; + + size_t emit(long long value) { + char text[24]; + int length = snprintf(text, sizeof(text), "%lld", value); + return write(reinterpret_cast<const uint8_t*>(text), length); + } + +public: + size_t write(uint8_t value) override { + _text.push_back(static_cast<char>(value)); + return 1; + } + + size_t write(const uint8_t* buffer, size_t size) override { + _text.append(reinterpret_cast<const char*>(buffer), size); + return size; + } + + size_t print(unsigned char value, int = DEC) override { return emit(value); } + size_t print(int value, int = DEC) override { return emit(value); } + size_t print(unsigned int value, int = DEC) override { return emit(value); } + size_t print(long value, int = DEC) override { return emit(value); } + size_t print(unsigned long value, int = DEC) override { return emit(value); } + size_t print(long long value, int = DEC) override { return emit(value); } + size_t print(unsigned long long value, int = DEC) override { return emit(value); } + + const std::string& text() const { return _text; } +}; + +TEST(CompanionNodePrefs, RxGainSettingsRoundTripIndependently) { + NodePrefs saved; + saved.rx_boosted_gain = 0; + saved.radio_fem_rxgain = 1; + saved.radio_fem_txgain = 0; + + CaptureStream output; + ASSERT_TRUE(saved.saveSerial(output)); + EXPECT_NE(std::string::npos, output.text().find("rxgain:0")); + EXPECT_NE(std::string::npos, output.text().find("fem_rxgain:1")); + EXPECT_NE(std::string::npos, output.text().find("fem_txgain:0")); + + ReplayStream input("{radio:{rxgain:1,fem_rxgain:0,fem_txgain:1}}"); + NodePrefs loaded; + loaded.rx_boosted_gain = 0; + loaded.radio_fem_rxgain = 1; + loaded.radio_fem_txgain = 0; + + ASSERT_TRUE(loaded.loadSerial(input)); + EXPECT_EQ(1, loaded.rx_boosted_gain); + EXPECT_EQ(0, loaded.radio_fem_rxgain); + EXPECT_EQ(1, loaded.radio_fem_txgain); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/test/test_config_serializer/test_config_serializer.cpp b/test/test_config_serializer/test_config_serializer.cpp index 7a13f487..27c3c811 100644 --- a/test/test_config_serializer/test_config_serializer.cpp +++ b/test/test_config_serializer/test_config_serializer.cpp @@ -1,6 +1,14 @@ #include <gtest/gtest.h> #include "helpers/ConfigSerializer.h" +class NativeFileSystem { +public: + void mkdir(const char*) { } +}; +#define FILESYSTEM NativeFileSystem +#include "helpers/CommonCLI.h" +#undef FILESYSTEM + #define TEST_INT_S "56" #define TEST_INT 56 #define TEST_FLOAT_S "-6.123" @@ -21,6 +29,19 @@ public: class MockPrintStream : public Stream { int len = 0; uint8_t _buf[1024]; + + size_t printSigned(long long value) { + char text[24]; + snprintf(text, sizeof(text), "%lld", value); + return Print::print(text); + } + + size_t printUnsigned(unsigned long long value) { + char text[24]; + snprintf(text, sizeof(text), "%llu", value); + return Print::print(text); + } + public: size_t write(uint8_t b) override { if (len < sizeof(_buf)) { @@ -30,17 +51,17 @@ public: return 0; } - size_t print(unsigned char b, int r) override { if (b == TEST_INT) return Print::print(TEST_INT_S); return 0; } - size_t print(int v, int r) override { if (v == TEST_INT) return Print::print(TEST_INT_S); return 0; } - size_t print(unsigned int v, int r) override { if (v == TEST_INT) return Print::print(TEST_INT_S); return 0; } - size_t print(long v, int r) override { if (v == TEST_INT) return Print::print(TEST_INT_S); return 0; } - size_t print(unsigned long v, int r) override { if (v == TEST_INT) return Print::print(TEST_INT_S); return 0; } - size_t print(long long v, int r) override { if (v == TEST_INT) return Print::print(TEST_INT_S); return 0; } - size_t print(unsigned long long v, int r) override { if (v == TEST_INT) return Print::print(TEST_INT_S); return 0; } - size_t print(double v, int p = 2) override { - if (p == 6) return Print::print(TEST_DOUBLE_S); - if (p == 4) return Print::print(TEST_FLOAT_S); - return 0; + size_t print(unsigned char v, int r) override { return printUnsigned(v); } + size_t print(int v, int r) override { return printSigned(v); } + size_t print(unsigned int v, int r) override { return printUnsigned(v); } + size_t print(long v, int r) override { return printSigned(v); } + size_t print(unsigned long v, int r) override { return printUnsigned(v); } + size_t print(long long v, int r) override { return printSigned(v); } + size_t print(unsigned long long v, int r) override { return printUnsigned(v); } + size_t print(double v, int p = 2) override { + char text[32]; + snprintf(text, sizeof(text), "%.*f", p, v); + return Print::print(text); } int getLength() const { return len; } @@ -171,6 +192,28 @@ TEST(ConfigSerializer, LoadSerial_IgnoreUnknowns) { EXPECT_TRUE(match); } +TEST(NodePrefs, FemGainSettingsRoundTrip) { + NodePrefs saved; + saved.radio_fem_rxgain = 0; + saved.radio_fem_txgain = 1; + + MockPrintStream output; + ASSERT_TRUE(saved.saveSerial(output)); + + std::string serialised(reinterpret_cast<const char*>(output.getBytes()), output.getLength()); + EXPECT_NE(std::string::npos, serialised.find("fem_rxgain:0")); + EXPECT_NE(std::string::npos, serialised.find("fem_txgain:1")); + + MockInputStream input(serialised.c_str()); + NodePrefs loaded; + loaded.radio_fem_rxgain = 1; + loaded.radio_fem_txgain = 0; + + ASSERT_TRUE(loaded.loadSerial(input)); + EXPECT_EQ(0, loaded.radio_fem_rxgain); + EXPECT_EQ(1, loaded.radio_fem_txgain); +} + // ── main ─────────────────────────────────────────────────────── From 3631de37de47cda74cfc11d3d3a03cddce00c8f7 Mon Sep 17 00:00:00 2001 From: Rastislav Vysoky <recrof@gmail.com> Date: Tue, 11 Aug 2026 10:37:20 +0200 Subject: [PATCH 101/381] removed misleading 'GPIO' from pin numbers --- variants/promicro/variant.cpp | 46 +++++++++++++++++------------------ 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/variants/promicro/variant.cpp b/variants/promicro/variant.cpp index b7d281ac..69b61745 100644 --- a/variants/promicro/variant.cpp +++ b/variants/promicro/variant.cpp @@ -3,29 +3,29 @@ #include "wiring_digital.h" const uint32_t g_ADigitalPinMap[] = { - 8, // P0.08 = GPIO 0 - 6, // P0.06 = GPIO 1 - 17, // P0.17 = GPIO 2 - 20, // P0.20 = GPIO 3 - 22, // P0.22 = GPIO 4 - 24, // P0.24 = GPIO 5 - 32, // P1.00 = GPIO 6 - 11, // P0.11 = GPIO 7 - 36, // P1.04 = GPIO 8 - 38, // P1.06 = GPIO 9 - 9, // P0.09 = GPIO 10 - 10, // P0.10 = GPIO 11 - 43, // P1.11 = GPIO 12 - 45, // P1.13 = GPIO 13 - 47, // P1.15 = GPIO 14 - 2, // P0.02 = GPIO 15 - 29, // P0.29 = GPIO 16 - 31, // P0.31 = GPIO 17 - 33, // P1.01 = GPIO 18 - 34, // P1.02 = GPIO 19 - 37, // P1.05 = GPIO 20 - 13, // P0.13 = GPIO 21 - 15 // P0.15 = GPIO 22 + 8, // P0.08 = 0 + 6, // P0.06 = 1 + 17, // P0.17 = 2 + 20, // P0.20 = 3 + 22, // P0.22 = 4 + 24, // P0.24 = 5 + 32, // P1.00 = 6 + 11, // P0.11 = 7 + 36, // P1.04 = 8 + 38, // P1.06 = 9 + 9, // P0.09 = 10 + 10, // P0.10 = 11 + 43, // P1.11 = 12 + 45, // P1.13 = 13 + 47, // P1.15 = 14 + 2, // P0.02 = 15 + 29, // P0.29 = 16 + 31, // P0.31 = 17 + 33, // P1.01 = 18 + 34, // P1.02 = 19 + 37, // P1.05 = 20 + 13, // P0.13 = 21 + 15 // P0.15 = 22 }; void initVariant() {} From 109ed685b2d19454af71a7a33898575019724026 Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Fri, 7 Aug 2026 21:47:02 -0400 Subject: [PATCH 102/381] thinknode_m8: initial support --- boards/thinknode_m8.json | 53 +++++++ examples/companion_radio/ui-new/UITask.cpp | 48 ++++++- src/helpers/ui/DisplayDriver.h | 1 + src/helpers/ui/GxEPDDisplay.cpp | 52 ++++++- src/helpers/ui/GxEPDDisplay.h | 10 ++ src/helpers/ui/MomentaryButton.h | 4 +- src/helpers/ui/RotaryInputGPIO.cpp | 34 +++++ src/helpers/ui/RotaryInputGPIO.h | 21 +++ variants/thinknode_m8/ThinkNodeM8Board.cpp | 38 +++++ variants/thinknode_m8/ThinkNodeM8Board.h | 50 +++++++ variants/thinknode_m8/platformio.ini | 160 +++++++++++++++++++++ variants/thinknode_m8/target.cpp | 36 +++++ variants/thinknode_m8/target.h | 30 ++++ variants/thinknode_m8/variant.cpp | 39 +++++ variants/thinknode_m8/variant.h | 141 ++++++++++++++++++ 15 files changed, 705 insertions(+), 12 deletions(-) create mode 100644 boards/thinknode_m8.json create mode 100644 src/helpers/ui/RotaryInputGPIO.cpp create mode 100644 src/helpers/ui/RotaryInputGPIO.h create mode 100644 variants/thinknode_m8/ThinkNodeM8Board.cpp create mode 100644 variants/thinknode_m8/ThinkNodeM8Board.h create mode 100644 variants/thinknode_m8/platformio.ini create mode 100644 variants/thinknode_m8/target.cpp create mode 100644 variants/thinknode_m8/target.h create mode 100644 variants/thinknode_m8/variant.cpp create mode 100644 variants/thinknode_m8/variant.h diff --git a/boards/thinknode_m8.json b/boards/thinknode_m8.json new file mode 100644 index 00000000..acd7f89c --- /dev/null +++ b/boards/thinknode_m8.json @@ -0,0 +1,53 @@ +{ + "build": { + "arduino": { + "ldscript": "nrf52840_s140_v6.ld" + }, + "core": "nRF5", + "cpu": "cortex-m4", + "extra_flags": "-DARDUINO_NRF52840_ThinkNode_M8 -DNRF52840_XXAA", + "f_cpu": "64000000L", + "hwids": [ + ["0x239A", "0x4405"], + ["0x239A", "0x0029"], + ["0x239A", "0x002A"] + ], + "usb_product": "elecrow_thinknode_m8", + "mcu": "nrf52840", + "variant": "ELECROW-ThinkNode-M8", + "variants_dir": "variants", + "bsp": { + "name": "adafruit" + }, + "softdevice": { + "sd_flags": "-DS140", + "sd_name": "s140", + "sd_version": "6.1.1", + "sd_fwid": "0x00B6" + }, + "bootloader": { + "settings_addr": "0xFF000" + } + }, + "connectivity": ["bluetooth"], + "debug": { + "jlink_device": "nRF52840_xxAA", + "onboard_tools": ["jlink"], + "svd_path": "nrf52840.svd", + "openocd_target": "nrf52840-mdk-rs" + }, + "frameworks": ["arduino"], + "name": "elecrow thinknode m8", + "upload": { + "maximum_ram_size": 248832, + "maximum_size": 815104, + "speed": 115200, + "protocol": "nrfutil", + "protocols": ["jlink", "nrfjprog", "nrfutil", "stlink"], + "use_1200bps_touch": true, + "require_upload_port": true, + "wait_for_upload_port": true + }, + "url": "", + "vendor": "ELECROW" +} diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index 051f3b31..d5e95d15 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -2,10 +2,15 @@ #include <helpers/TxtDataHelpers.h> #include "../MyMesh.h" #include "target.h" +#include <time.h> #ifdef WIFI_SSID #include <WiFi.h> #endif +#ifndef UI_TZ_OFFSET + #define UI_TZ_OFFSET 0 +#endif + #ifndef AUTO_OFF_MILLIS #define AUTO_OFF_MILLIS 15000 // 15 seconds #endif @@ -23,7 +28,7 @@ #define UI_RECENT_LIST_SIZE 4 #endif -#if UI_HAS_JOYSTICK +#if UI_HAS_JOYSTICK || UI_HAS_ROTARY_INPUT #define PRESS_LABEL "press Enter" #else #define PRESS_LABEL "long press" @@ -224,7 +229,19 @@ public: display.setTextSize(2); sprintf(tmp, "MSG: %d", _task->getMsgCount()); display.drawTextCentered(display.width() / 2, 22, tmp); - + + #ifdef UI_SHOW_CLOCK + display.setTextSize(3); + uint32_t now = _rtc->getCurrentTime(); + int8_t tz = UI_TZ_OFFSET; // for now draw time from Santo Domingo ... + now += (int32_t)tz * 3600; + DateTime dt (now); + sprintf(tmp, "%02d:%02d", dt.hour(), dt.minute()); + display.drawTextCentered(display.width() / 2, 60, tmp); + display.setTextSize(1); + sprintf(tmp, "%02d/%02d/%d", dt.day(), dt.month(), dt.year()); + display.drawTextCentered(display.width() / 2, 80, tmp); + #endif #ifdef WIFI_SSID IPAddress ip = WiFi.localIP(); snprintf(tmp, sizeof(tmp), "IP: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); @@ -234,13 +251,21 @@ public: if (_task->hasConnection()) { display.setColor(UIColor::warning_txt); display.setTextSize(1); + #ifdef UI_SHOW_CLOCK + display.drawTextCentered(display.width() / 2, 110, "< Connected >"); + #else display.drawTextCentered(display.width() / 2, 43, "< Connected >"); - + #endif } else if (the_mesh.getBLEPin() != 0) { // BT pin display.setColor(UIColor::warning_txt); - display.setTextSize(2); sprintf(tmp, "Pin:%d", the_mesh.getBLEPin()); + #ifdef UI_SHOW_CLOCK + display.setTextSize(1); + display.drawTextCentered(display.width() / 2, 110, tmp); + #else + display.setTextSize(2); display.drawTextCentered(display.width() / 2, 43, tmp); + #endif } } else if (_page == HomePage::RECENT) { the_mesh.getRecentlyHeard(recent, UI_RECENT_LIST_SIZE); @@ -720,6 +745,9 @@ void UITask::shutdown(bool restart){ if (restart) { _board->reboot(); } else { + display.forceFullRefresh(); + display.clear(); + display.endFrame(); // Power off board including radio, display, GPS and components _board->powerOff(); } @@ -760,6 +788,17 @@ void UITask::loop() { } #elif defined(PIN_USER_BTN) int ev = user_btn.check(); + #ifdef UI_HAS_NAV_INPUT + if (ev == BUTTON_EVENT_CLICK) { + c = checkDisplayOn(KEY_ENTER); + } else if (ev == BUTTON_EVENT_LONG_PRESS) { + display.turnOff(); + } else if (ev == BUTTON_EVENT_DOUBLE_CLICK) { + c = handleDoubleClick(KEY_SELECT); + } else if (ev == BUTTON_EVENT_TRIPLE_CLICK) { + c = handleTripleClick(KEY_SELECT); + } + #else if (ev == BUTTON_EVENT_CLICK) { c = checkDisplayOn(KEY_NEXT); } else if (ev == BUTTON_EVENT_LONG_PRESS) { @@ -769,6 +808,7 @@ void UITask::loop() { } else if (ev == BUTTON_EVENT_TRIPLE_CLICK) { c = handleTripleClick(KEY_SELECT); } + #endif #endif #if defined(UI_HAS_ROTARY_INPUT) RotaryInputEvent rotaryEv = rotary_input.poll(); diff --git a/src/helpers/ui/DisplayDriver.h b/src/helpers/ui/DisplayDriver.h index b76a1b6c..3e9e2dde 100644 --- a/src/helpers/ui/DisplayDriver.h +++ b/src/helpers/ui/DisplayDriver.h @@ -23,6 +23,7 @@ public: virtual bool isOn() = 0; virtual bool isEink() { return false; } // default to non-eink, override in eink drivers + virtual void forceFullRefresh() {} // next refresh will be full for eink virtual void turnOn() = 0; virtual void turnOff() = 0; virtual void clear() = 0; diff --git a/src/helpers/ui/GxEPDDisplay.cpp b/src/helpers/ui/GxEPDDisplay.cpp index 13dafa34..11f78b57 100644 --- a/src/helpers/ui/GxEPDDisplay.cpp +++ b/src/helpers/ui/GxEPDDisplay.cpp @@ -14,6 +14,10 @@ SPIClass SPI1 = SPIClass(FSPI); #endif +#ifndef EPD_WASHING_MACHINE_CYCLES + #define EPD_WASHING_MACHINE_CYCLES 0 +#endif + // Color scheme ColorVal UIColor::window_bkg = GxEPD_WHITE; ColorVal UIColor::title_bkg = GxEPD_WHITE; @@ -25,7 +29,6 @@ ColorVal UIColor::popup_bkg = GxEPD_WHITE; ColorVal UIColor::popup_txt = GxEPD_BLACK; ColorVal UIColor::corp_blue = GxEPD_BLACK; - bool GxEPDDisplay::begin() { display.epd2.selectSPI(SPI1, SPISettings(4000000, MSBFIRST, SPI_MODE0)); #ifdef ESP32 @@ -36,15 +39,27 @@ bool GxEPDDisplay::begin() { display.init(115200, true, 2, false); display.setRotation(DISPLAY_ROTATION); setTextSize(1); // Default to size 1 - display.setPartialWindow(0, 0, display.width(), display.height()); - display.fillScreen(GxEPD_WHITE); - display.display(true); + display.setFullWindow(); + + for (int i = 0; i < EPD_WASHING_MACHINE_CYCLES; i++) { + display.fillScreen(GxEPD_BLACK); + display.display(false); + delay(2000); + display.fillScreen(GxEPD_WHITE); + display.display(false); + delay(2000); + } + + display.setPartialWindow(0, 0, display.width(), display.height()); + resetPartialRefreshCounter(); + #if DISP_BACKLIGHT digitalWrite(DISP_BACKLIGHT, LOW); pinMode(DISP_BACKLIGHT, OUTPUT); #endif _init = true; + _isOn = true; return true; } @@ -55,7 +70,11 @@ void GxEPDDisplay::turnOn() { #elif defined(EXP_PIN_BACKLIGHT) && !defined(BACKLIGHT_BTN) expander.digitalWrite(EXP_PIN_BACKLIGHT, HIGH); #endif - _isOn = true; + if (!_isOn) { + forceFullRefresh(); + _isOn = true; + last_display_crc_value=0; + } } void GxEPDDisplay::turnOff() { @@ -65,6 +84,11 @@ void GxEPDDisplay::turnOff() { expander.digitalWrite(EXP_PIN_BACKLIGHT, LOW); #endif _isOn = false; + display.setFullWindow(); + display.fillScreen(GxEPD_WHITE); + display.display(true); + forceFullRefresh(); + display.powerOff(); } void GxEPDDisplay::clear() { @@ -77,6 +101,12 @@ void GxEPDDisplay::startFrame(ColorVal bkg) { display.fillScreen(bkg); display.setTextColor(_curr_color = UIColor::primary_txt); display_crc.reset(); + if (_cycles_before_full_refresh <= 0) { + display.setPartialWindow(0, 0, display.width(), display.height()); + } else { + display.setFullWindow(); + display.writeScreenBuffer(); + } } void GxEPDDisplay::setTextSize(int sz) { @@ -178,9 +208,19 @@ uint16_t GxEPDDisplay::getTextWidth(const char* str) { } void GxEPDDisplay::endFrame() { + if (_isOn == false) return; uint32_t crc = display_crc.finalize(); if (crc != last_display_crc_value) { - display.display(true); + if (_cycles_before_full_refresh == 0) { + display.display(false); + display.writeScreenBuffer(); + resetPartialRefreshCounter(); + } else { + display.display(true); + if (_cycles_before_full_refresh > 0) { + _cycles_before_full_refresh--; + } + } last_display_crc_value = crc; } } diff --git a/src/helpers/ui/GxEPDDisplay.h b/src/helpers/ui/GxEPDDisplay.h index c653eac4..8a37b72c 100644 --- a/src/helpers/ui/GxEPDDisplay.h +++ b/src/helpers/ui/GxEPDDisplay.h @@ -16,6 +16,12 @@ #include "DisplayDriver.h" +#ifndef EINK_MAX_PARTIAL_REFRESH + // 60 to prevent ghosting when refreshing every minute ... + // set to -1 to disable the counter + #define EINK_MAX_PARTIAL_REFRESH -1 +#endif + class GxEPDDisplay : public DisplayDriver { #if defined(EINK_DISPLAY_MODEL) @@ -36,6 +42,8 @@ class GxEPDDisplay : public DisplayDriver { uint16_t _curr_color; CRC32 display_crc; int last_display_crc_value = 0; + int _cycles_before_full_refresh; + int max_partial_refresh = EINK_MAX_PARTIAL_REFRESH; // so this can be changed by an option after public: #if defined(EINK_DISPLAY_MODEL) @@ -48,6 +56,8 @@ public: bool isOn() override { return _isOn; } bool isEink() override { return true; } + void forceFullRefresh() override { _cycles_before_full_refresh = 0; }; + void resetPartialRefreshCounter() { _cycles_before_full_refresh = max_partial_refresh; }; void turnOn() override; void turnOff() override; void clear() override; diff --git a/src/helpers/ui/MomentaryButton.h b/src/helpers/ui/MomentaryButton.h index 358a343b..351545ce 100644 --- a/src/helpers/ui/MomentaryButton.h +++ b/src/helpers/ui/MomentaryButton.h @@ -25,8 +25,8 @@ class MomentaryButton { public: MomentaryButton(int8_t pin, int long_press_mills=0, bool reverse=false, bool pulldownup=false, bool multiclick=true); MomentaryButton(int8_t pin, int long_press_mills, int analog_threshold); - void begin(); - int check(bool repeat_click=false); // returns one of BUTTON_EVENT_* + virtual void begin(); + virtual int check(bool repeat_click=false); // returns one of BUTTON_EVENT_* void cancelClick(); // suppress next BUTTON_EVENT_CLICK (if already in DOWN state) uint8_t getPin() { return _pin; } bool isPressed() const; diff --git a/src/helpers/ui/RotaryInputGPIO.cpp b/src/helpers/ui/RotaryInputGPIO.cpp new file mode 100644 index 00000000..b094fe49 --- /dev/null +++ b/src/helpers/ui/RotaryInputGPIO.cpp @@ -0,0 +1,34 @@ +#include "RotaryInputGPIO.h" + +bool RotaryInputGPIO::begin() { + + if (_pin_a >= 0) { + pinMode(_pin_a, _pull_a ? INPUT_PULLUP : INPUT); + } + if (_pin_b >= 0) { + pinMode(_pin_b, _pull_b ? INPUT_PULLUP : INPUT); + } + + b_prec = digitalRead(_pin_b); + + return true; +} + +RotaryInputEvent RotaryInputGPIO::poll() { + RotaryInputEvent ev = RotaryInputEvent::None; + bool a = digitalRead(_pin_a); + bool b = digitalRead(_pin_b); + + // this is the simplest scheme and it works well + // for thinknode M8, just read A when B rises ;) + if (!b_prec && b) { // rising edge of A + if (a) { + ev = RotaryInputEvent::Next; + } else { + ev = RotaryInputEvent::Prev; + } + } + b_prec = b; + + return ev; +} \ No newline at end of file diff --git a/src/helpers/ui/RotaryInputGPIO.h b/src/helpers/ui/RotaryInputGPIO.h new file mode 100644 index 00000000..16b7e46a --- /dev/null +++ b/src/helpers/ui/RotaryInputGPIO.h @@ -0,0 +1,21 @@ +#pragma once + +#include <Arduino.h> +#include "RotaryInput.h" + +#define BUTTON_EVENT_UP 5 +#define BUTTON_EVENT_DOWN 6 + +class RotaryInputGPIO: public RotaryInput { + int8_t _pin_a; + bool _pull_a; + int8_t _pin_b; + bool _pull_b; + bool b_prec; +public: + RotaryInputGPIO(int8_t pin_a, int8_t pin_b, bool pull_a=false, bool pull_b=false): _pin_a(pin_a), _pin_b(pin_b), _pull_a(pull_a), _pull_b(pull_b) {} + + bool begin() override; + RotaryInputEvent poll() override; + bool isReady() const override { return true;} +}; diff --git a/variants/thinknode_m8/ThinkNodeM8Board.cpp b/variants/thinknode_m8/ThinkNodeM8Board.cpp new file mode 100644 index 00000000..2ca393d9 --- /dev/null +++ b/variants/thinknode_m8/ThinkNodeM8Board.cpp @@ -0,0 +1,38 @@ +#include <Arduino.h> +#include <Wire.h> + +#include "ThinkNodeM8Board.h" + +#ifdef THINKNODE_M8 + +void ThinkNodeM8Board::begin() { + NRF52Board::begin(); + + Wire.begin(); + +#ifdef P_LORA_TX_LED + pinMode(P_LORA_TX_LED, OUTPUT); + digitalWrite(P_LORA_TX_LED, LOW); +#endif + + pinMode(SX126X_POWER_EN, OUTPUT); + digitalWrite(SX126X_POWER_EN, HIGH); + delay(10); // give sx1262 some time to power up +} + +uint16_t ThinkNodeM8Board::getBattMilliVolts() { + int adcvalue = 0; + + digitalWrite(ADC_EN, HIGH); + analogReference(AR_INTERNAL_2_4); + analogReadResolution(12); + delay(10); + + // ADC range is 0..3000mV and resolution is 12-bit (0..4095) + adcvalue = analogRead(PIN_VBAT_READ); + // Convert the raw value to compensated mv, taking the resistor- + // divider into account (providing the actual LIPO voltage) + digitalWrite(ADC_EN, LOW); + return (uint16_t)((float)adcvalue * REAL_VBAT_MV_PER_LSB); +} +#endif diff --git a/variants/thinknode_m8/ThinkNodeM8Board.h b/variants/thinknode_m8/ThinkNodeM8Board.h new file mode 100644 index 00000000..73aeb1f5 --- /dev/null +++ b/variants/thinknode_m8/ThinkNodeM8Board.h @@ -0,0 +1,50 @@ +#pragma once + +#include <MeshCore.h> +#include <Arduino.h> +#include <helpers/NRF52Board.h> + +// built-ins +#define VBAT_MV_PER_LSB (0.5859375F) // 2.4V ADC range and 12-bit ADC resolution = 2400mV/4096 + +#define VBAT_DIVIDER (0.57F) // 150K + 150K voltage divider on VBAT +#define VBAT_DIVIDER_COMP (1.75F) // Compensation factor for the VBAT divider + +#define PIN_VBAT_READ (4) +#define REAL_VBAT_MV_PER_LSB (VBAT_DIVIDER_COMP * VBAT_MV_PER_LSB) + +class ThinkNodeM8Board : public NRF52Board { +public: + ThinkNodeM8Board() : NRF52Board("THINKNODE_M8_OTA") {} + void begin(); + uint16_t getBattMilliVolts() override; + + #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 + + const char* getManufacturerName() const override { + return "Elecrow ThinkNode-M8"; + } + + void shutdownPeripherals() override { + // power off board + NRF52Board::shutdownPeripherals(); + + // make sure every gate is closed + digitalWrite(DISP_EN, LOW); + digitalWrite(PIN_PWR_EN, LOW); + digitalWrite(PIN_GPS_EN, LOW); + digitalWrite(SX126X_ANT_SW, LOW); + digitalWrite(ADC_EN, LOW); + + #ifdef PIN_BUTTON1 // Use BTN to go out of sleep + nrf_gpio_cfg_sense_input(PIN_BUTTON1, NRF_GPIO_PIN_PULLUP, NRF_GPIO_PIN_SENSE_LOW); + #endif + } +}; diff --git a/variants/thinknode_m8/platformio.ini b/variants/thinknode_m8/platformio.ini new file mode 100644 index 00000000..9f1595c5 --- /dev/null +++ b/variants/thinknode_m8/platformio.ini @@ -0,0 +1,160 @@ +[ThinkNode_M8] +extends = nrf52_base +board = thinknode_m8 +board_build.ldscript = boards/nrf52840_s140_v6.ld +build_flags = ${nrf52_base.build_flags} + -I src/helpers/nrf52 + -I lib/nrf52/s140_nrf52_6.1.1_API/include + -I lib/nrf52/s140_nrf52_6.1.1_API/include/nrf52 + -I variants/thinknode_m8 + -D THINKNODE_M8=1 + -D RADIO_CLASS=CustomSX1262 + -D WRAPPER_CLASS=CustomSX1262Wrapper + -D P_LORA_DIO_1=25 + -D P_LORA_DIO_2=32 + -D P_LORA_NSS=21 + -D P_LORA_RESET=24 + -D P_LORA_BUSY=32 # DIO2 + -D P_LORA_SCLK=19 + -D P_LORA_MISO=22 + -D P_LORA_MOSI=20 + -D UI_SHOW_CLOCK=1 + -D UI_HAS_ROTARY_INPUT=1 + -D UI_HAS_NAV_INPUT=1 + -D UI_RECENT_LIST_SIZE=9 + -D UI_TZ_OFFSET=-4 # GMT-4 + -D EINK_MAX_PARTIAL_REFRESH=60 + -D EINK_DISPLAY_MODEL=GxEPD2_154_D67 +; -D EINK_DISPLAY_MODEL=GxEPD2_154_GDEY0154D67 +; -D EINK_DISPLAY_MODEL=GxEPD2_150_BN + -D EINK_SCALE_X=1.5625f + -D EINK_SCALE_Y=1.5625f + -D EINK_X_OFFSET=0 + -D EINK_Y_OFFSET=10 + -D DISABLE_DIAGNOSTIC_OUTPUT + -D SX126X_POWER_EN=37 + -D SX126X_DIO2_AS_RF_SWITCH=true + -D SX126X_DIO3_TCXO_VOLTAGE=3.3 + -D SX126X_CURRENT_LIMIT=140 + -D SX126X_RX_BOOSTED_GAIN=1 + -D LORA_TX_POWER=22 +build_src_filter = ${nrf52_base.build_src_filter} + +<helpers/*.cpp> + +<ThinkNodeM8Board.cpp> + +<../variants/thinknode_m8> +lib_deps = + ${nrf52_base.lib_deps} + stevemarple/MicroNMEA @ ^2.0.6 +debug_tool = jlink +upload_protocol = nrfutil + +[env:ThinkNode_M8_repeater] +extends = ThinkNode_M8 +build_flags = + ${ThinkNode_M8.build_flags} + -D ADVERT_NAME='"ThinkNode Repeater"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=50 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${ThinkNode_M8.build_src_filter} + +<../examples/simple_repeater/*.cpp> +lib_deps = + ${ThinkNode_M8.lib_deps} + +[env:ThinkNode_M8_room_server] +extends = ThinkNode_M8 +build_flags = + ${ThinkNode_M8.build_flags} + -D ADVERT_NAME='"ThinkNode Room"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D ROOM_PASSWORD='"hello"' +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${ThinkNode_M8.build_src_filter} + +<../examples/simple_room_server/*.cpp> +lib_deps = + ${ThinkNode_M8.lib_deps} + +[env:ThinkNode_M8_companion_radio_ble] +extends = ThinkNode_M8 +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 712704 +build_flags = + ${ThinkNode_M8.build_flags} + -I src/helpers/ui + -I examples/companion_radio/ui-new + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D BLE_PIN_CODE=123456 +# -D BLE_DEBUG_LOGGING=1 + -D DISPLAY_ROTATION=4 + -D DISPLAY_CLASS=GxEPDDisplay + -D BACKLIGHT_BTN=PIN_BUTTON2 + -D AUTO_OFF_MILLIS=0 + -D OFFLINE_QUEUE_SIZE=256 + -D PIN_BUZZER=33 + -D AUTO_SHUTDOWN_MILLIVOLTS=3300 + -D QSPIFLASH=1 + -D ENV_INCLUDE_GPS=1 +; -D GPS_NMEA_DEBUG=1 +; -D MESH_PACKET_LOGGING=1 + -D MESH_DEBUG=1 +build_src_filter = ${ThinkNode_M8.build_src_filter} + +<helpers/nrf52/SerialBLEInterface.cpp> + +<helpers/ui/GxEPDDisplay.cpp> + +<helpers/ui/buzzer.cpp> + +<helpers/ui/MomentaryButton.cpp> + +<helpers/ui/RotaryInputGPIO.cpp> + +<helpers/sensors/EnvironmentSensorManager.cpp> + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = + ${ThinkNode_M8.lib_deps} + densaugeo/base64 @ ~1.4.0 + zinggjm/GxEPD2 @ 1.6.9 + bakercp/CRC32 @ ^2.0.0 + end2endzone/NonBlockingRTTTL@^1.3.0 + +[env:ThinkNode_M8_companion_radio_usb] +extends = ThinkNode_M8 +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 712704 +build_flags = + ${ThinkNode_M8.build_flags} + -I src/helpers/ui + -I examples/companion_radio/ui-new + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D DISPLAY_ROTATION=4 + -D QSPIFLASH=1 + -D DISPLAY_CLASS=GxEPDDisplay + -D BACKLIGHT_BTN=PIN_BUTTON2 + -D AUTO_OFF_MILLIS=0 + -D OFFLINE_QUEUE_SIZE=256 + -D PIN_BUZZER=6 + -D AUTO_SHUTDOWN_MILLIVOLTS=3300 + -D ENABLE_USB_INTERFACE +build_src_filter = ${ThinkNode_M8.build_src_filter} + +<helpers/ui/GxEPDDisplay.cpp> + +<helpers/ui/buzzer.cpp> + +<helpers/ui/MomentaryButton.cpp> + +<helpers/ui/RotaryInputGPIO.cpp> + +<helpers/sensors/EnvironmentSensorManager.cpp> + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = + ${ThinkNode_M8.lib_deps} + densaugeo/base64 @ ~1.4.0 + zinggjm/GxEPD2 @ 1.6.2 + bakercp/CRC32 @ ^2.0.0 + end2endzone/NonBlockingRTTTL@^1.3.0 + +[env:ThinkNode_M8_kiss_modem] +extends = ThinkNode_M8 +build_src_filter = ${ThinkNode_M8.build_src_filter} + +<../examples/kiss_modem/> diff --git a/variants/thinknode_m8/target.cpp b/variants/thinknode_m8/target.cpp new file mode 100644 index 00000000..ac4ac100 --- /dev/null +++ b/variants/thinknode_m8/target.cpp @@ -0,0 +1,36 @@ +#include <Arduino.h> +#include "target.h" +#include <helpers/ArduinoHelpers.h> +#include <helpers/sensors/MicroNMEALocationProvider.h> +#include <Wire.h> + +ThinkNodeM8Board board; + +RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, SPI); + +WRAPPER_CLASS radio_driver(radio, board); + +VolatileRTCClock fallback_clock; +AutoDiscoverRTCClock rtc_clock(fallback_clock); +#ifdef ENV_INCLUDE_GPS +MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); +#else +EnvironmentSensorManager sensors = EnvironmentSensorManager(); +#endif + +#ifdef DISPLAY_CLASS + DISPLAY_CLASS display; + MomentaryButton user_btn(PIN_USER_BTN, 1000, true); + RotaryInputGPIO rotary_input(PIN_BUTTON1_A, PIN_BUTTON1_B); +#endif + +bool radio_init() { + rtc_clock.begin(Wire); + return radio.std_init(&SPI); +} + +mesh::LocalIdentity radio_new_identity() { + RadioNoiseListener rng(radio); + return mesh::LocalIdentity(&rng); // create new random identity +} diff --git a/variants/thinknode_m8/target.h b/variants/thinknode_m8/target.h new file mode 100644 index 00000000..c3402a01 --- /dev/null +++ b/variants/thinknode_m8/target.h @@ -0,0 +1,30 @@ +#pragma once + +#define RADIOLIB_STATIC_ONLY 1 +#include <RadioLib.h> +#include <helpers/radiolib/RadioLibWrappers.h> +#include <ThinkNodeM8Board.h> +#include <helpers/radiolib/CustomSX1262Wrapper.h> +#include <helpers/AutoDiscoverRTCClock.h> +#include <helpers/SensorManager.h> +#include <helpers/sensors/LocationProvider.h> +#include <helpers/sensors/EnvironmentSensorManager.h> +#ifdef DISPLAY_CLASS + #include <helpers/ui/GxEPDDisplay.h> + #include <helpers/ui/RotaryInputGPIO.h> + #include <helpers/ui/MomentaryButton.h> +#endif + +extern ThinkNodeM8Board board; +extern WRAPPER_CLASS radio_driver; +extern AutoDiscoverRTCClock rtc_clock; +extern EnvironmentSensorManager sensors; + +#ifdef DISPLAY_CLASS + extern DISPLAY_CLASS display; + extern MomentaryButton user_btn; + extern RotaryInputGPIO rotary_input; +#endif + +bool radio_init(); +mesh::LocalIdentity radio_new_identity(); diff --git a/variants/thinknode_m8/variant.cpp b/variants/thinknode_m8/variant.cpp new file mode 100644 index 00000000..e15c0842 --- /dev/null +++ b/variants/thinknode_m8/variant.cpp @@ -0,0 +1,39 @@ +#include "variant.h" +#include "wiring_constants.h" +#include "wiring_digital.h" + +const int MISO = PIN_SPI1_MISO; +const int MOSI = PIN_SPI1_MOSI; +const int SCK = PIN_SPI1_SCK; + +const uint32_t g_ADigitalPinMap[] = { + 0xff, 0xff, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, + 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, + 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, + 40, 41, 42, 43, 44, 45, 46, 47 +}; + +void initVariant() { + pinMode(PIN_PWR_EN, OUTPUT); + digitalWrite(PIN_PWR_EN, HIGH); + pinMode(DISP_EN, OUTPUT); + digitalWrite(DISP_EN, HIGH); + + pinMode(PIN_BUTTON1, INPUT_PULLDOWN); + pinMode(PIN_BUTTON1_A, INPUT_PULLDOWN); + pinMode(PIN_BUTTON1_B, INPUT_PULLDOWN); + pinMode(PIN_BUTTON2, INPUT_PULLUP); + + // shutdown gps + pinMode(PIN_GPS_STANDBY, OUTPUT); + digitalWrite(PIN_GPS_STANDBY, HIGH); + pinMode(PIN_GPS_EN, OUTPUT); + digitalWrite(PIN_GPS_EN, LOW); // disable at startup + + pinMode(SX126X_ANT_SW, OUTPUT); // ANT_SW + digitalWrite(SX126X_ANT_SW, HIGH); + + pinMode(ADC_EN, OUTPUT); + digitalWrite(ADC_EN, LOW); + +} diff --git a/variants/thinknode_m8/variant.h b/variants/thinknode_m8/variant.h new file mode 100644 index 00000000..9c36c772 --- /dev/null +++ b/variants/thinknode_m8/variant.h @@ -0,0 +1,141 @@ +/* + * 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 WIRE_INTERFACES_COUNT (1) +#define PIN_TXCO (21) +//////////////////////////////////////////////////////////////////////////////// +// Power + +#define PIN_PWR_EN (13) // I2C + +#define BATTERY_PIN (4) +#define ADC_MULTIPLIER (1.75F) + +#define ADC_RESOLUTION (14) +#define BATTERY_SENSE_RES (12) + +#define AREF_VOLTAGE (2.4) + +#define ADC_EN (40) + +//////////////////////////////////////////////////////////////////////////////// +// Number of pins + +#define PINS_COUNT (48) +#define NUM_DIGITAL_PINS (48) +#define NUM_ANALOG_INPUTS (1) +#define NUM_ANALOG_OUTPUTS (0) + +//////////////////////////////////////////////////////////////////////////////// +// UART pin definition + +#define PIN_SERIAL1_RX PIN_GPS_TX +#define PIN_SERIAL1_TX PIN_GPS_RX +//////////////////////////////////////////////////////////////////////////////// +// I2C pin definition + +#define PIN_WIRE_SDA (26) // P0.26 +#define PIN_WIRE_SCL (27) // P0.27 + +//////////////////////////////////////////////////////////////////////////////// +// SPI pin definition + +#define SPI_INTERFACES_COUNT (2) + +#define PIN_SPI_MISO (22) +#define PIN_SPI_MOSI (20) +#define PIN_SPI_SCK (19) +#define PIN_SPI_NSS (21) + +//////////////////////////////////////////////////////////////////////////////// +// Builtin LEDs +#define LED_BLUE (-1) + +#define LED_BUILTIN LED_BLUE +#define LED_PIN LED_BUILTIN +#define LED_STATE_ON HIGH + +//////////////////////////////////////////////////////////////////////////////// +// Builtin buttons + +#define PIN_BUTTON1 (6) +#define PIN_BUTTON1_A (8) // Rotary button/Encoder +#define PIN_BUTTON1_B (41) +#define BUTTON_PIN PIN_BUTTON1 + +#define PIN_BUTTON2 (12) +#define BUTTON_PIN2 PIN_BUTTON2 + +#define PIN_USER_BTN PIN_BUTTON1 + +//////////////////////////////////////////////////////////////////////////////// +// Lora + +#define USE_SX1262 +#define LORA_CS (24) +#define SX126X_DIO1 (20) +#define SX126X_BUSY (17) +#define SX126X_RESET (25) +#define SX126X_ANT_SW (23) +#define SX126X_DIO2_AS_RF_SWITCH +#define SX126X_DIO3_TCXO_VOLTAGE 1.8 + +//////////////////////////////////////////////////////////////////////////////// +// SPI1 +#define PIN_SPI1_NSS (30) +#define PIN_SPI1_SCK (31) +#define PIN_SPI1_MOSI (29) +#define PIN_SPI1_MISO (-1) + +// GxEPD2 needs that for a panel that is not even used ! +extern const int MISO; +extern const int MOSI; +extern const int SCK; + +//////////////////////////////////////////////////////////////////////////////// +// QSPI +#define EXTERNAL_FLASH_DEVICES MX25R1635F +#define EXTERNAL_FLASH_USE_QSPI +#define PIN_QSPI_SCK (46) +#define PIN_QSPI_CS (47) +#define PIN_QSPI_IO0 (44) // MOSI if using two bit interface +#define PIN_QSPI_IO1 (45) // MISO if using two bit interface +#define PIN_QSPI_IO2 (7) // WP if using two bit interface (i.e. not used) +#define PIN_QSPI_IO3 (5) // HOLD if using two bit interface (i.e. not used) + +//////////////////////////////////////////////////////////////////////////////// +// Display + +#define DISP_MISO PIN_SPI1_MISO +#define DISP_MOSI PIN_SPI1_MOSI +#define DISP_SCLK PIN_SPI1_SCK +#define PIN_DISPLAY_CS PIN_SPI1_NSS +#define PIN_DISPLAY_DC (28) +#define PIN_DISPLAY_RST (2) +#define PIN_DISPLAY_BUSY (3) +#define DISP_BACKLIGHT (43) +#define DISP_EN (42) + +//////////////////////////////////////////////////////////////////////////////// +// GPS + +#define PIN_GPS_RX (36) +#define PIN_GPS_TX (34) +#define PIN_GPS_EN (16) +#define PIN_GPS_RESET (-1) +#define PIN_GPS_PPS (14) +#define PIN_GPS_STANDBY (15) // Low = sleep +#define GPS_BAUD_RATE 115200 From bdefc8d0854c28190cce08bf07d72c16a7a3a030 Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Wed, 12 Aug 2026 14:04:50 +1000 Subject: [PATCH 103/381] t096 compiler layout workaround see https://github.com/meshcore-dev/MeshCore/issues/3151 --- src/helpers/CommonCLI.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 2a9ec43b..3143acd2 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -79,7 +79,8 @@ private: def("bw", _parent->bw); def("sf", _parent->sf); def("cr", _parent->cr); - def("cad", _parent->cad_enabled); + static const char radio_cad_key[] = {'c', 'a', 'd', '\0'}; // workaround for T096, don't touch without testing T096 repeater still transmit + def(radio_cad_key, _parent->cad_enabled); def("int_thr", _parent->interference_threshold); def("rxgain", _parent->rx_boosted_gain); def("fem_rxgain", _parent->rx_boosted_gain); From b13962d7de356914d431c9a362bf15b77807114b Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Wed, 12 Aug 2026 14:07:31 +1000 Subject: [PATCH 104/381] T096 PA_CTX pin direction workaround --- variants/heltec_t096/LoRaFEMControl.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/variants/heltec_t096/LoRaFEMControl.cpp b/variants/heltec_t096/LoRaFEMControl.cpp index fb60a8f7..45bbfd64 100644 --- a/variants/heltec_t096/LoRaFEMControl.cpp +++ b/variants/heltec_t096/LoRaFEMControl.cpp @@ -21,6 +21,7 @@ void LoRaFEMControl::setSleepModeEnable(void) void LoRaFEMControl::setTxModeEnable(void) { + pinMode(P_LORA_KCT8103L_PA_CTX, OUTPUT); // force pinMode before transmit as temporary workaround for https://github.com/meshcore-dev/MeshCore/issues/3151 digitalWrite(P_LORA_KCT8103L_PA_CSD, HIGH); digitalWrite(P_LORA_KCT8103L_PA_CTX, HIGH); } From 309a04162e06a11115b78920751b71725594176b Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Wed, 12 Aug 2026 16:08:05 +1000 Subject: [PATCH 105/381] set T-Echo Card TCXO voltage to 3.0 as per https://github.com/meshcore-dev/MeshCore/pull/3140 and https://github.com/Xinyuan-LilyGO/T-Echo-Lite/issues/14 --- variants/lilygo_techo_card/variant.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/variants/lilygo_techo_card/variant.h b/variants/lilygo_techo_card/variant.h index 28c5f550..699453e0 100644 --- a/variants/lilygo_techo_card/variant.h +++ b/variants/lilygo_techo_card/variant.h @@ -107,7 +107,7 @@ #define P_LORA_NSS (11) // P0.11 #define SX126X_RXEN (33) // P1.01 #define SX126X_TXEN (27) // P0.27 -#define SX126X_DIO3_TCXO_VOLTAGE (1.8f) +#define SX126X_DIO3_TCXO_VOLTAGE (3.0f) //////////////////////////////////////////////////////////////////////////////// From 920ee315ec1d3c4c2280c8e6fdced1e0fb42efdf Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Wed, 12 Aug 2026 22:28:05 +1000 Subject: [PATCH 106/381] Revert "T096 PA_CTX pin direction workaround" This reverts commit b13962d7de356914d431c9a362bf15b77807114b. --- variants/heltec_t096/LoRaFEMControl.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/variants/heltec_t096/LoRaFEMControl.cpp b/variants/heltec_t096/LoRaFEMControl.cpp index 45bbfd64..fb60a8f7 100644 --- a/variants/heltec_t096/LoRaFEMControl.cpp +++ b/variants/heltec_t096/LoRaFEMControl.cpp @@ -21,7 +21,6 @@ void LoRaFEMControl::setSleepModeEnable(void) void LoRaFEMControl::setTxModeEnable(void) { - pinMode(P_LORA_KCT8103L_PA_CTX, OUTPUT); // force pinMode before transmit as temporary workaround for https://github.com/meshcore-dev/MeshCore/issues/3151 digitalWrite(P_LORA_KCT8103L_PA_CSD, HIGH); digitalWrite(P_LORA_KCT8103L_PA_CTX, HIGH); } From 0f686aa3f18c7b28bb817432097af58d7c8fe8cc Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Wed, 12 Aug 2026 22:28:36 +1000 Subject: [PATCH 107/381] Revert "t096 compiler layout workaround" This reverts commit bdefc8d0854c28190cce08bf07d72c16a7a3a030. --- src/helpers/CommonCLI.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 3143acd2..2a9ec43b 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -79,8 +79,7 @@ private: def("bw", _parent->bw); def("sf", _parent->sf); def("cr", _parent->cr); - static const char radio_cad_key[] = {'c', 'a', 'd', '\0'}; // workaround for T096, don't touch without testing T096 repeater still transmit - def(radio_cad_key, _parent->cad_enabled); + def("cad", _parent->cad_enabled); def("int_thr", _parent->interference_threshold); def("rxgain", _parent->rx_boosted_gain); def("fem_rxgain", _parent->rx_boosted_gain); From 248e6a9fab804846333a40ba7162cfb4e4f66b2b Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Wed, 12 Aug 2026 22:31:57 +1000 Subject: [PATCH 108/381] Heltec T096: fix PIN_SPI1_MISO Setting SPI pins to values that are OOB of the g_ADigitalPinMap[] array causes OOB reads. This variant.h has pin 0 as 0xFF which passes through as NRFX_SPIM_PIN_NOT_USED. --- variants/heltec_t096/variant.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/variants/heltec_t096/variant.h b/variants/heltec_t096/variant.h index c240c1f2..bfbf2e63 100644 --- a/variants/heltec_t096/variant.h +++ b/variants/heltec_t096/variant.h @@ -104,7 +104,7 @@ #define PIN_SPI_SCK (32 + 8) #define PIN_SPI_NSS LORA_CS -#define PIN_SPI1_MISO (-1) +#define PIN_SPI1_MISO (0) #define PIN_SPI1_MOSI (0+17) #define PIN_SPI1_SCK (0+20) From 0028bd9becfd33642313558ee6c8edbadb9e434f Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Thu, 13 Aug 2026 00:12:37 +1000 Subject: [PATCH 109/381] Fix Heltec T1 pin definitions SPI pins that are set to -1 cause OOB reads on NRF52. The unused Serial2 pin definitions were removed to avoid potential issues with the Uart framework. --- variants/heltec_t1/variant.h | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/variants/heltec_t1/variant.h b/variants/heltec_t1/variant.h index 7ee21816..b52aeba0 100644 --- a/variants/heltec_t1/variant.h +++ b/variants/heltec_t1/variant.h @@ -25,8 +25,8 @@ #define ST7735_SDA (0 + 24) #define ST7735_SCK (32 + 0) #define ST7735_RESET (0 + 20) -#define ST7735_MISO (-1) -#define ST7735_BUSY (-1) +#define ST7735_MISO (0) // 0 maps to 0xff on this device which is NRFX_SPIM_PIN_NOT_USED +#define ST7735_BUSY (0) // 0 maps to 0xff on this device which is NRFX_SPIM_PIN_NOT_USED #define ST7735_BL (0 + 15) #define VTFT_CTRL (0 + 13) @@ -66,8 +66,7 @@ // UART // No longer populated on PCB. -#define PIN_SERIAL2_RX (-1) -#define PIN_SERIAL2_TX (-1) +// Removed the pin definitions to avoid potential issues with Uart. //////////////////////////////////////////////////////////////////////////////// // I2C From d0ceba7976c28e47145097c5919a48c539c1da5a Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Thu, 13 Aug 2026 00:15:34 +1000 Subject: [PATCH 110/381] Fix Heltec MeshPocket SPI pins --- variants/mesh_pocket/variant.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/variants/mesh_pocket/variant.h b/variants/mesh_pocket/variant.h index 870d062a..9774276c 100644 --- a/variants/mesh_pocket/variant.h +++ b/variants/mesh_pocket/variant.h @@ -108,7 +108,7 @@ #define PIN_DISPLAY_DC (31) #define PIN_DISPLAY_RST (32 + 4) -#define PIN_SPI1_MISO (-1) +#define PIN_SPI1_MISO (0) // 0 maps to 0xff on this device which is NRFX_SPIM_PIN_NOT_USED #define PIN_SPI1_MOSI (20) #define PIN_SPI1_SCK (22) From a80ddbf4e2c867a82fd09e600412a6d6d482251f Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Thu, 13 Aug 2026 00:53:58 +1000 Subject: [PATCH 111/381] Fix LilyGo T-Echo Lite SPI pins --- variants/lilygo_techo_lite/variant.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/variants/lilygo_techo_lite/variant.h b/variants/lilygo_techo_lite/variant.h index 38b79c66..83bb6f07 100644 --- a/variants/lilygo_techo_lite/variant.h +++ b/variants/lilygo_techo_lite/variant.h @@ -58,7 +58,7 @@ #define PIN_SPI_MISO _PINNUM(0, 17) // (MISO) #define PIN_SPI_MOSI _PINNUM(0, 15) // (MOSI) #define PIN_SPI_SCK _PINNUM(0, 13) // (SCK) -#define PIN_SPI_NSS (-1) +#define PIN_SPI_NSS (0) //////////////////////////////////////////////////////////////////////////////// // QSPI FLASH @@ -123,7 +123,7 @@ //////////////////////////////////////////////////////////////////////////////// // SPI1 -#define PIN_SPI1_MISO (-1) // Not used for Display +#define PIN_SPI1_MISO (0) // Not used for Display, 0 maps to 0xff on this device which is NRFX_SPIM_PIN_NOT_USED #define PIN_SPI1_MOSI _PINNUM(0, 20) #define PIN_SPI1_SCK _PINNUM(0, 19) @@ -135,7 +135,7 @@ extern const int SCK; //////////////////////////////////////////////////////////////////////////////// // Display -// #define DISP_MISO (-1) // Not used for Display +// #define DISP_MISO (0) // Not used for Display, 0 maps to 0xff on this device which is NRFX_SPIM_PIN_NOT_USED #define DISP_MOSI _PINNUM(0, 20) #define DISP_SCLK _PINNUM(0, 19) #define DISP_CS _PINNUM(0, 22) @@ -143,7 +143,7 @@ extern const int SCK; #define DISP_RST _PINNUM(0, 28) #define DISP_BUSY _PINNUM(0, 3) #define DISP_POWER _PINNUM(1, 12) -// #define DISP_BACKLIGHT (-1) // Display has no backlight +// #define DISP_BACKLIGHT (0) // Display has no backlight, 0 maps to 0xff on this device which is NRFX_SPIM_PIN_NOT_USED #define PIN_DISPLAY_CS DISP_CS #define PIN_DISPLAY_DC DISP_DC From ad33137b71862d3e84bfa43b2d626fea69536015 Mon Sep 17 00:00:00 2001 From: F4FPR <Bensam148@hotmail.com> Date: Thu, 13 Aug 2026 23:52:02 +0200 Subject: [PATCH 112/381] Update LocationProvider.h --- src/helpers/sensors/LocationProvider.h | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/helpers/sensors/LocationProvider.h b/src/helpers/sensors/LocationProvider.h index 81d08652..a70ae8ca 100644 --- a/src/helpers/sensors/LocationProvider.h +++ b/src/helpers/sensors/LocationProvider.h @@ -1,6 +1,8 @@ #pragma once #include "Mesh.h" +#include <stddef.h> +#include <stdio.h> class LocationProvider { @@ -22,4 +24,14 @@ public: virtual void stop() = 0; virtual void loop() = 0; virtual bool isEnabled() = 0; + + // Format compact diagnostics in the caller-provided buffer. Providers that + // have more information (for example UART counters) can override this. + virtual void formatDiagnostics(char* out, size_t out_size) { + if (out_size == 0) return; + snprintf(out, out_size, "en:%u sat:%ld fix:%u", + isEnabled() ? 1U : 0U, + satellitesCount(), + isValid() ? 1U : 0U); + } }; From d86cb7355b0ac92e688f60fee34414566de97f0c Mon Sep 17 00:00:00 2001 From: F4FPR <Bensam148@hotmail.com> Date: Thu, 13 Aug 2026 23:52:31 +0200 Subject: [PATCH 113/381] Update MicroNMEALocationProvider.h --- .../sensors/MicroNMEALocationProvider.h | 84 ++++++++++++++++++- 1 file changed, 83 insertions(+), 1 deletion(-) diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index b66cb114..0a6ebc1d 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -4,6 +4,7 @@ #include <MicroNMEA.h> #include <RTClib.h> #include <helpers/RefCountedDigitalPin.h> +#include <string.h> #ifndef GPS_EN #ifdef PIN_GPS_EN @@ -51,6 +52,32 @@ class MicroNMEALocationProvider : public LocationProvider { unsigned long _last_time_sync = 0; static const unsigned long TIME_SYNC_INTERVAL = 1800000; // Re-sync every 30 minutes + // Observation-only diagnostics. These fields do not change GPS power, + // timing, reset behaviour, or parser input. + uint32_t _uart_bytes = 0; + uint32_t _nmea_checksum_ok = 0; + uint32_t _nmea_checksum_bad = 0; + uint32_t _begin_calls = 0; + uint32_t _stop_calls = 0; + unsigned long _last_uart_ms = 0; + unsigned long _last_nmea_ms = 0; + unsigned long _last_fix_ms = 0; + bool _uart_seen = false; + bool _nmea_seen = false; + bool _fix_seen = false; + + static uint32_t ageMs(unsigned long timestamp) { + return (uint32_t)(millis() - timestamp); + } + + static void formatAge(char* out, size_t out_size, bool seen, unsigned long timestamp) { + if (!seen) { + snprintf(out, out_size, "never"); + } else { + snprintf(out, out_size, "%lu", (unsigned long)ageMs(timestamp)); + } + } + public : MicroNMEALocationProvider(Stream& ser, mesh::RTCClock* clock = NULL, int pin_reset = GPS_RESET, int pin_en = GPS_EN,RefCountedDigitalPin* peripher_power=NULL) : nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), _gps_serial(&ser), _peripher_power(peripher_power), _pin_reset(pin_reset), _pin_en(pin_en) { @@ -76,6 +103,7 @@ public : } void begin() override { + _begin_calls++; claim(); if (_pin_en != -1) { digitalWrite(_pin_en, GPS_EN_ACTIVE); @@ -94,6 +122,7 @@ public : } void stop() override { + _stop_calls++; if (_pin_en != -1) { digitalWrite(_pin_en, !GPS_EN_ACTIVE); } @@ -137,10 +166,36 @@ public : while (_gps_serial->available()) { char c = _gps_serial->read(); + _uart_bytes++; + _last_uart_ms = millis(); + _uart_seen = true; #ifdef GPS_NMEA_DEBUG Serial.print(c); #endif - nmea.process(c); + bool parsed = nmea.process(c); + + // MicroNMEA leaves the completed sentence in its buffer after the + // first line terminator. CRLF therefore counts once: CR observes the + // sentence, then LF clears the now-empty buffer. + if ((c == '\0' || c == '\r' || c == '\n') && nmea.getSentence()[0] != '\0') { + if (MicroNMEA::testChecksum(nmea.getSentence())) { + _nmea_checksum_ok++; + _last_nmea_ms = millis(); + _nmea_seen = true; + + // Refresh fix age only when a newly parsed GGA/RMC sentence + // carries a valid fix. Other valid NMEA sentences must not + // make an old position look fresh. + const char* message_id = nmea.getMessageID(); + if (parsed && isValid() && + (strcmp(message_id, "GGA") == 0 || strcmp(message_id, "RMC") == 0)) { + _last_fix_ms = millis(); + _fix_seen = true; + } + } else { + _nmea_checksum_bad++; + } + } } if (!isValid()) time_valid = 0; @@ -163,4 +218,31 @@ public : } } } + + void formatDiagnostics(char* out, size_t out_size) override { + if (out_size == 0) return; + + char uart_age[11]; + char nmea_age[11]; + char fix_age[11]; + formatAge(uart_age, sizeof(uart_age), _uart_seen, _last_uart_ms); + formatAge(nmea_age, sizeof(nmea_age), _nmea_seen, _last_nmea_ms); + formatAge(fix_age, sizeof(fix_age), _fix_seen, _last_fix_ms); + + // Compact enough for CommonCLI's 160-byte reply buffer, including the + // "req:" prefix added by CommonCLI. + snprintf(out, out_size, + "en:%u ub:%lu ua:%s ok:%lu bad:%lu na:%s sat:%ld fix:%u fa:%s bc:%lu sc:%lu", + isEnabled() ? 1U : 0U, + (unsigned long)_uart_bytes, + uart_age, + (unsigned long)_nmea_checksum_ok, + (unsigned long)_nmea_checksum_bad, + nmea_age, + satellitesCount(), + isValid() ? 1U : 0U, + fix_age, + (unsigned long)_begin_calls, + (unsigned long)_stop_calls); + } }; From ae9c16efce53343d8d324daf4e88e678da1b5cb7 Mon Sep 17 00:00:00 2001 From: F4FPR <Bensam148@hotmail.com> Date: Thu, 13 Aug 2026 23:52:58 +0200 Subject: [PATCH 114/381] Update CommonCLI.cpp --- src/helpers/CommonCLI.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index b318bb58..b8fd6d56 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -344,6 +344,20 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re } else { strcpy(reply, "gps provider not found"); } + } else if (strcmp(command, "gps diag") == 0) { + LocationProvider * l = _sensors->getLocationProvider(); + if (l != NULL) { + const char* setting = _sensors->getSettingByKey("gps"); + bool requested = setting != NULL && strcmp(setting, "1") == 0; + int prefix_len = snprintf(reply, 160, "req:%u ", requested ? 1U : 0U); + if (prefix_len < 0 || prefix_len >= 160) { + reply[159] = 0; + } else { + l->formatDiagnostics(reply + prefix_len, 160 - prefix_len); + } + } else { + strcpy(reply, "gps provider not found"); + } } else if (memcmp(command, "gps setloc", 10) == 0) { _prefs->node_lat = _sensors->node_lat; _prefs->node_lon = _sensors->node_lon; From c1143fdf142f36aa3b6c107e04f618707194716e Mon Sep 17 00:00:00 2001 From: F4FPR <Bensam148@hotmail.com> Date: Fri, 14 Aug 2026 00:20:11 +0200 Subject: [PATCH 115/381] Update MicroNMEALocationProvider.h --- src/helpers/sensors/MicroNMEALocationProvider.h | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index b66cb114..a8bdbe0b 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -51,6 +51,17 @@ class MicroNMEALocationProvider : public LocationProvider { unsigned long _last_time_sync = 0; static const unsigned long TIME_SYNC_INTERVAL = 1800000; // Re-sync every 30 minutes +#ifdef GPS_L76K + void configureL76K() { + // Reapply the constellation mode at each provider start instead of + // assuming it survives a receiver power cycle. + // Mode 7 enables GPS + BeiDou + GLONASS. + delay(250); + MicroNMEA::sendSentence(*_gps_serial, "$PCAS04,7"); + delay(250); + } +#endif + public : MicroNMEALocationProvider(Stream& ser, mesh::RTCClock* clock = NULL, int pin_reset = GPS_RESET, int pin_en = GPS_EN,RefCountedDigitalPin* peripher_power=NULL) : nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), _gps_serial(&ser), _peripher_power(peripher_power), _pin_reset(pin_reset), _pin_en(pin_en) { @@ -91,6 +102,11 @@ public : delay(10); digitalWrite(_pin_reset, !GPS_RESET_ACTIVE); } +#ifdef GPS_L76K + // EnvironmentSensorManager calls reset() immediately after begin(). + // Configure only after that reset so the setting is not discarded. + configureL76K(); +#endif } void stop() override { From 3c155e4cce3207d00842b665a163d47123d187d4 Mon Sep 17 00:00:00 2001 From: F4FPR <Bensam148@hotmail.com> Date: Fri, 14 Aug 2026 00:42:57 +0200 Subject: [PATCH 116/381] Update MeshCore.h --- src/MeshCore.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/MeshCore.h b/src/MeshCore.h index e67371ef..22979476 100644 --- a/src/MeshCore.h +++ b/src/MeshCore.h @@ -74,6 +74,8 @@ public: // Power management interface (boards with power management override these) virtual bool isExternalPowered() { return false; } + // True while a board can identify an active battery-charging source. + virtual bool isChargerActive() { return false; } virtual uint16_t getBootVoltage() { return 0; } virtual uint32_t getResetReason() const { return 0; } virtual const char* getResetReasonString(uint32_t reason) { return "Not available"; } From f15e7fd8a91d23ed409d74cbf45e25535382412a Mon Sep 17 00:00:00 2001 From: F4FPR <Bensam148@hotmail.com> Date: Fri, 14 Aug 2026 00:43:33 +0200 Subject: [PATCH 117/381] Update CommonCLI.cpp --- src/helpers/CommonCLI.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index b318bb58..d2a8b707 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -273,6 +273,11 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re sprintf(reply, "%s (Build: %s)", _callbacks->getFirmwareVer(), _callbacks->getBuildDate()); } else if (memcmp(command, "board", 5) == 0) { sprintf(reply, "%s", _board->getManufacturerName()); + } else if (strcmp(command, "power") == 0) { + snprintf(reply, 160, "batt:%u mV ext:%s charger:%s", + (unsigned)_board->getBattMilliVolts(), + _board->isExternalPowered() ? "yes" : "no", + _board->isChargerActive() ? "yes" : "no"); } else if (memcmp(command, "sensor get ", 11) == 0) { const char* key = command + 11; const char* val = _sensors->getSettingByKey(key); From a6c4100711a6838bc85b1f33ebfe41fc00a935ee Mon Sep 17 00:00:00 2001 From: F4FPR <Bensam148@hotmail.com> Date: Fri, 14 Aug 2026 00:44:16 +0200 Subject: [PATCH 118/381] Update ThinkNodeM6Board.cpp --- variants/thinknode_m6/ThinkNodeM6Board.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/variants/thinknode_m6/ThinkNodeM6Board.cpp b/variants/thinknode_m6/ThinkNodeM6Board.cpp index 8ebae64c..f83f274f 100644 --- a/variants/thinknode_m6/ThinkNodeM6Board.cpp +++ b/variants/thinknode_m6/ThinkNodeM6Board.cpp @@ -15,6 +15,9 @@ void ThinkNodeM6Board::begin() { digitalWrite(P_LORA_TX_LED, LOW); #endif + pinMode(EXT_PWR_DETECT, INPUT); + pinMode(EXT_CHRG_DETECT, INPUT); + delay(10); // give sx1262 some time to power up } From c382f05c303cb7e2036a8194bb18f5c6eedf7059 Mon Sep 17 00:00:00 2001 From: F4FPR <Bensam148@hotmail.com> Date: Fri, 14 Aug 2026 00:44:43 +0200 Subject: [PATCH 119/381] Update ThinkNodeM6Board.h --- variants/thinknode_m6/ThinkNodeM6Board.h | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/variants/thinknode_m6/ThinkNodeM6Board.h b/variants/thinknode_m6/ThinkNodeM6Board.h index 78815e2c..1af952d2 100644 --- a/variants/thinknode_m6/ThinkNodeM6Board.h +++ b/variants/thinknode_m6/ThinkNodeM6Board.h @@ -36,6 +36,21 @@ public: return "Elecrow ThinkNode M6"; } + bool isExternalPowered() override { + if (digitalRead(EXT_PWR_DETECT) == EXT_PWR_DETECT_VALUE || + digitalRead(EXT_CHRG_DETECT) == EXT_CHRG_DETECT_VALUE) { + return true; + } + return NRF52Board::isExternalPowered(); + } + + bool isChargerActive() override { + // The charge-status line covers solar input; external USB input is also a + // charging source, although the board cannot report charge completion. + return digitalRead(EXT_CHRG_DETECT) == EXT_CHRG_DETECT_VALUE || + digitalRead(EXT_PWR_DETECT) == EXT_PWR_DETECT_VALUE; + } + void powerOff() override { // turn off all leds, sd_power_system_off will not do this for us From f34e1fcb9ba6aa2406a9363b3185ddbc9f1b1c13 Mon Sep 17 00:00:00 2001 From: F4FPR <Bensam148@hotmail.com> Date: Fri, 14 Aug 2026 00:45:22 +0200 Subject: [PATCH 120/381] Update variant.h --- variants/thinknode_m6/variant.h | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/variants/thinknode_m6/variant.h b/variants/thinknode_m6/variant.h index 0a4025f3..3428fcd6 100644 --- a/variants/thinknode_m6/variant.h +++ b/variants/thinknode_m6/variant.h @@ -29,6 +29,12 @@ #define AREF_VOLTAGE (3.0) +// External power and charger status lines. +#define EXT_PWR_DETECT (13) +#define EXT_PWR_DETECT_VALUE HIGH +#define EXT_CHRG_DETECT (15) +#define EXT_CHRG_DETECT_VALUE LOW + //////////////////////////////////////////////////////////////////////////////// // Number of pins From 5ff2d7109b642328078f7bf93ea31d31a4a50e6c Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Fri, 14 Aug 2026 16:30:12 +1000 Subject: [PATCH 121/381] * commenting out the load/save of the fem_ properties, until they can be set --- examples/companion_radio/NodePrefs.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index 453f28d5..21766de8 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -53,8 +53,12 @@ private: //def("cad", _parent->cad_enabled); //def("int_thr", _parent->interference_threshold); def("rxgain", _parent->rx_boosted_gain); + #if 0 + // NOTE: these cannot be set (yet) so don't load/save until we can. + // also, fem_rxgain WAS mapped to wrong JSON property previously def("fem_rxgain", _parent->radio_fem_rxgain); def("fem_txgain", _parent->radio_fem_txgain); + #endif def("tx", _parent->tx_power_dbm); def("af", _parent->airtime_factor); def("rxdelay", _parent->rx_delay_base); From c97e40d15d7a41dfaccef82dec11ca39417fca09 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Fri, 14 Aug 2026 16:42:54 +1000 Subject: [PATCH 122/381] * unit test no longer valid --- test/test_companion_node_prefs/test_companion_node_prefs.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/test_companion_node_prefs/test_companion_node_prefs.cpp b/test/test_companion_node_prefs/test_companion_node_prefs.cpp index 6d3cebdf..433c9710 100644 --- a/test/test_companion_node_prefs/test_companion_node_prefs.cpp +++ b/test/test_companion_node_prefs/test_companion_node_prefs.cpp @@ -50,6 +50,8 @@ public: const std::string& text() const { return _text; } }; +#if 0 +// Re-enable test once we can SET fem_ values in companion TEST(CompanionNodePrefs, RxGainSettingsRoundTripIndependently) { NodePrefs saved; saved.rx_boosted_gain = 0; @@ -73,6 +75,7 @@ TEST(CompanionNodePrefs, RxGainSettingsRoundTripIndependently) { EXPECT_EQ(0, loaded.radio_fem_rxgain); EXPECT_EQ(1, loaded.radio_fem_txgain); } +#endif int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); From 10b6552872b03a70215ddb7b61ba9d14ec5cde45 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Fri, 14 Aug 2026 17:46:43 +1000 Subject: [PATCH 123/381] * combine radio's entropy with CC310 RNG --- src/helpers/radiolib/RadioLibWrappers.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/helpers/radiolib/RadioLibWrappers.h b/src/helpers/radiolib/RadioLibWrappers.h index 5db1e41f..77dd9311 100644 --- a/src/helpers/radiolib/RadioLibWrappers.h +++ b/src/helpers/radiolib/RadioLibWrappers.h @@ -92,8 +92,10 @@ public: void random(uint8_t* dest, size_t sz) override { #ifdef USE_CC310_HW_CRYPTO - // CC310 TRNG is higher quality and environment-independent vs radio RSSI noise. nRFCrypto.Random.generate(dest, (uint16_t)sz); + for (int i = 0; i < sz; i++) { + dest[i] ^= _radio->randomByte() ^ (::random(0, 256) & 0xFF); // combine with Radio's entropy + } #else for (int i = 0; i < sz; i++) { dest[i] = _radio->randomByte() ^ (::random(0, 256) & 0xFF); From cad602e416e883a256623d8613374071192b48fd Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Fri, 14 Aug 2026 22:19:19 +1000 Subject: [PATCH 124/381] * version 1.17.1 --- examples/companion_radio/MyMesh.h | 4 ++-- examples/simple_repeater/MyMesh.h | 4 ++-- examples/simple_room_server/MyMesh.h | 4 ++-- examples/simple_sensor/SensorMesh.h | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/examples/companion_radio/MyMesh.h b/examples/companion_radio/MyMesh.h index f73fe0e0..238adada 100644 --- a/examples/companion_radio/MyMesh.h +++ b/examples/companion_radio/MyMesh.h @@ -8,11 +8,11 @@ #define FIRMWARE_VER_CODE 13 #ifndef FIRMWARE_BUILD_DATE -#define FIRMWARE_BUILD_DATE "9 Aug 2026" +#define FIRMWARE_BUILD_DATE "14 Aug 2026" #endif #ifndef FIRMWARE_VERSION -#define FIRMWARE_VERSION "v1.17.0" +#define FIRMWARE_VERSION "v1.17.1" #endif #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index 6d9cf459..04bd4fb9 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -71,11 +71,11 @@ struct NeighbourInfo { }; #ifndef FIRMWARE_BUILD_DATE - #define FIRMWARE_BUILD_DATE "9 Aug 2026" + #define FIRMWARE_BUILD_DATE "14 Aug 2026" #endif #ifndef FIRMWARE_VERSION - #define FIRMWARE_VERSION "v1.17.0" + #define FIRMWARE_VERSION "v1.17.1" #endif #define FIRMWARE_ROLE "repeater" diff --git a/examples/simple_room_server/MyMesh.h b/examples/simple_room_server/MyMesh.h index ba9f7eec..5cf949c6 100644 --- a/examples/simple_room_server/MyMesh.h +++ b/examples/simple_room_server/MyMesh.h @@ -28,11 +28,11 @@ /* ------------------------------ Config -------------------------------- */ #ifndef FIRMWARE_BUILD_DATE - #define FIRMWARE_BUILD_DATE "9 Aug 2026" + #define FIRMWARE_BUILD_DATE "14 Aug 2026" #endif #ifndef FIRMWARE_VERSION - #define FIRMWARE_VERSION "v1.17.0" + #define FIRMWARE_VERSION "v1.17.1" #endif #ifndef LORA_FREQ diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index 3a33b638..b5e96d5c 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -34,11 +34,11 @@ #define PERM_RECV_ALERTS_HI (1 << 7) // high priority alerts #ifndef FIRMWARE_BUILD_DATE - #define FIRMWARE_BUILD_DATE "9 Aug 2026" + #define FIRMWARE_BUILD_DATE "14 Aug 2026" #endif #ifndef FIRMWARE_VERSION - #define FIRMWARE_VERSION "v1.17.0" + #define FIRMWARE_VERSION "v1.17.1" #endif #define FIRMWARE_ROLE "sensor" From aa2292459f228261b7bd7b22faff40f3df3d9ba3 Mon Sep 17 00:00:00 2001 From: Fedor Kallay <fkallay1@gmail.com> Date: Sat, 15 Aug 2026 02:13:11 +0200 Subject: [PATCH 125/381] fix(lr2021): setTxPower() could leave the receiver down until reboot RadioLibWrapper::setTxPower() called setOutputPower() and nothing else. On LR2021 that writes the PA config and TxParams, which are standby-only commands, and it never re-arms the receiver. This only affects LR2021 boards. recvRaw() has: #if defined(USE_LR2021) state = STATE_RX; // LR2021 stays in Rx after readData #else state = STATE_IDLE; // need another startReceive() #endif so on SX126x the next recvRaw() re-arms Rx anyway and the write is harmless, while on LR2021 startReceive() is never called again on its own. A 'set tx' issued while the radio was listening could therefore stop reception until the next reboot. Observed a few times on an LR2021 repeater; recovery required a power cycle. Dispatcher's stuck-radio check does not catch it: isInRecvMode() reports the wrapper's own `state` flag rather than the chip's actual mode, so it still believes the radio is in Rx, and it only raises ERR_EVENT_STARTRX_TIMEOUT without attempting recovery. Fix: on LR2021, drop to standby via idle() before writing the PA config and let checkRecv() re-arm Rx - the same pattern resetAGC() and applySideDetectorConfig() already use. Other radios are left untouched. Affects meshtracker_x1 and meshnology_w12 (both USE_LR2021). Tested on hardware with an LR2021 repeater: six consecutive 'set tx' changes (15/18/21/14/19/14), after which the radio kept receiving and forwarding traffic (rawrx/rxpkts increasing, no missed IRQs). Noise-floor sampling also kept updating, which only happens while state == STATE_RX. --- src/helpers/radiolib/RadioLibWrappers.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/helpers/radiolib/RadioLibWrappers.cpp b/src/helpers/radiolib/RadioLibWrappers.cpp index b9c095ac..f404b625 100644 --- a/src/helpers/radiolib/RadioLibWrappers.cpp +++ b/src/helpers/radiolib/RadioLibWrappers.cpp @@ -48,6 +48,17 @@ uint32_t RadioLibWrapper::getRngSeed() { } void RadioLibWrapper::setTxPower(int8_t dbm) { +#if defined(USE_LR2021) + // On LR2021, setOutputPower() writes the PA config and TxParams, which are + // standby-only commands. recvRaw() keeps state == STATE_RX after readData on + // this platform ("LR2021 stays in Rx"), so - unlike the SX126x path, which + // falls back to STATE_IDLE and re-arms on the next recvRaw() - nothing calls + // startReceive() again by itself. Writing the PA config while listening could + // therefore leave the receiver down until the next reboot. Drop to standby + // first and let checkRecv() re-arm Rx, as resetAGC() and + // applySideDetectorConfig() already do. + idle(); +#endif _radio->setOutputPower(dbm); } From 3f4be260036e1d2d11e4ea21eadbaee0f013b8a2 Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Sun, 16 Aug 2026 11:40:13 -0400 Subject: [PATCH 126/381] gxepddisplay: better handling of full refresh (no faint partial afterwards !!!) --- src/helpers/ui/GxEPDDisplay.cpp | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/src/helpers/ui/GxEPDDisplay.cpp b/src/helpers/ui/GxEPDDisplay.cpp index 11f78b57..610b8541 100644 --- a/src/helpers/ui/GxEPDDisplay.cpp +++ b/src/helpers/ui/GxEPDDisplay.cpp @@ -88,7 +88,7 @@ void GxEPDDisplay::turnOff() { display.fillScreen(GxEPD_WHITE); display.display(true); forceFullRefresh(); - display.powerOff(); + display.hibernate(); } void GxEPDDisplay::clear() { @@ -101,11 +101,15 @@ void GxEPDDisplay::startFrame(ColorVal bkg) { display.fillScreen(bkg); display.setTextColor(_curr_color = UIColor::primary_txt); display_crc.reset(); - if (_cycles_before_full_refresh <= 0) { + if (_cycles_before_full_refresh != 0) { display.setPartialWindow(0, 0, display.width(), display.height()); } else { - display.setFullWindow(); - display.writeScreenBuffer(); + // forces a full wipe of the screen ... + display.clearScreen(0xFF); // Clears microcontroller side RAM + display.writeScreenBuffer(0xFF); // Forces 0xFF (White) into the display controller's history registers + // we'll need a partial refresh after that (whatever crc value is) + last_display_crc_value = 0; + resetPartialRefreshCounter(); } } @@ -211,16 +215,10 @@ void GxEPDDisplay::endFrame() { if (_isOn == false) return; uint32_t crc = display_crc.finalize(); if (crc != last_display_crc_value) { - if (_cycles_before_full_refresh == 0) { - display.display(false); - display.writeScreenBuffer(); - resetPartialRefreshCounter(); - } else { - display.display(true); - if (_cycles_before_full_refresh > 0) { - _cycles_before_full_refresh--; - } + display.display(true); + if (_cycles_before_full_refresh > 0) { + _cycles_before_full_refresh--; } - last_display_crc_value = crc; } + last_display_crc_value = crc; } From 11a02eeabaca39c6126e85cb013263c92ce8fb43 Mon Sep 17 00:00:00 2001 From: entr0p1 <1475255+entr0p1@users.noreply.github.com> Date: Mon, 17 Aug 2026 23:01:52 +1000 Subject: [PATCH 127/381] Duplicate MAX_CLIENTS definition MAX_CLIENTS is defined in both src/helpers/ClientACL.h and examples/simple_repeater/MyMesh.h. Appears it was centralised in the former header file some time ago. Both are included in some places and, depending on which order they're in, either value can win. This change drops the duplicate entry from the repeater firmware and bumps the central limit up to 32 (per the original repeater firmware value). Changes: - Remove MAX_CLIENTS from repeater MyMesh.h - Increase MAX_CLIENTS limit in ClientACL.h to 32 --- examples/simple_repeater/MyMesh.h | 4 ---- src/helpers/ClientACL.h | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index 04bd4fb9..cac6c4a2 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -59,10 +59,6 @@ struct RepeaterStats { uint32_t n_recv_errors; }; -#ifndef MAX_CLIENTS - #define MAX_CLIENTS 32 -#endif - struct NeighbourInfo { mesh::Identity id; uint32_t advert_timestamp; diff --git a/src/helpers/ClientACL.h b/src/helpers/ClientACL.h index b758f706..e0654464 100644 --- a/src/helpers/ClientACL.h +++ b/src/helpers/ClientACL.h @@ -34,7 +34,7 @@ struct ClientInfo { }; #ifndef MAX_CLIENTS - #define MAX_CLIENTS 20 + #define MAX_CLIENTS 32 #endif class ClientACL { From debbbb81c04ac66b6e790615b0aeef735bc5e063 Mon Sep 17 00:00:00 2001 From: Huw Duddy <37787853+oltaco@users.noreply.github.com> Date: Mon, 17 Aug 2026 23:16:01 +1000 Subject: [PATCH 128/381] trimmed comment --- src/helpers/radiolib/RadioLibWrappers.cpp | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/helpers/radiolib/RadioLibWrappers.cpp b/src/helpers/radiolib/RadioLibWrappers.cpp index f404b625..e4d2ba1c 100644 --- a/src/helpers/radiolib/RadioLibWrappers.cpp +++ b/src/helpers/radiolib/RadioLibWrappers.cpp @@ -49,14 +49,6 @@ uint32_t RadioLibWrapper::getRngSeed() { void RadioLibWrapper::setTxPower(int8_t dbm) { #if defined(USE_LR2021) - // On LR2021, setOutputPower() writes the PA config and TxParams, which are - // standby-only commands. recvRaw() keeps state == STATE_RX after readData on - // this platform ("LR2021 stays in Rx"), so - unlike the SX126x path, which - // falls back to STATE_IDLE and re-arms on the next recvRaw() - nothing calls - // startReceive() again by itself. Writing the PA config while listening could - // therefore leave the receiver down until the next reboot. Drop to standby - // first and let checkRecv() re-arm Rx, as resetAGC() and - // applySideDetectorConfig() already do. idle(); #endif _radio->setOutputPower(dbm); @@ -265,4 +257,4 @@ PacketMillis RadioLibWrapper::calcMaxPacketMillis(uint8_t sf, float bw, uint8_t if (cr >= 5 && cr < 8) { payload_us = (payload_us * 8) / cr; } return PacketMillis {(preamble_us + 999) / 1000, (payload_us + 999) / 1000}; -} \ No newline at end of file +} From c54139f7dbaf85337b9446aaf332bc33915164d0 Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Mon, 17 Aug 2026 09:24:17 -0400 Subject: [PATCH 129/381] M8: preview messages up to 164 cars --- examples/companion_radio/ui-new/UITask.cpp | 6 +++++- variants/thinknode_m8/platformio.ini | 1 + 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index d5e95d15..59b58461 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -511,6 +511,10 @@ public: } }; +#ifndef UI_MSG_PREVIEW_SIZE + #define UI_MSG_PREVIEW_SIZE 78 +#endif + class MsgPreviewScreen : public UIScreen { UITask* _task; mesh::RTCClock* _rtc; @@ -518,7 +522,7 @@ class MsgPreviewScreen : public UIScreen { struct MsgEntry { uint32_t timestamp; char origin[62]; - char msg[78]; + char msg[UI_MSG_PREVIEW_SIZE]; }; #define MAX_UNREAD_MSGS 32 int num_unread; diff --git a/variants/thinknode_m8/platformio.ini b/variants/thinknode_m8/platformio.ini index 9f1595c5..b8c70973 100644 --- a/variants/thinknode_m8/platformio.ini +++ b/variants/thinknode_m8/platformio.ini @@ -23,6 +23,7 @@ build_flags = ${nrf52_base.build_flags} -D UI_HAS_NAV_INPUT=1 -D UI_RECENT_LIST_SIZE=9 -D UI_TZ_OFFSET=-4 # GMT-4 + -D UI_MSG_PREVIEW_SIZE=165 -D EINK_MAX_PARTIAL_REFRESH=60 -D EINK_DISPLAY_MODEL=GxEPD2_154_D67 ; -D EINK_DISPLAY_MODEL=GxEPD2_154_GDEY0154D67 From cec44c05dd1c7e0748b4bdf11f9e5c5ded39d575 Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Mon, 17 Aug 2026 09:41:51 -0400 Subject: [PATCH 130/381] gxepd: do full refresh before screen off ... so wakes quicker ;) --- src/helpers/ui/GxEPDDisplay.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/helpers/ui/GxEPDDisplay.cpp b/src/helpers/ui/GxEPDDisplay.cpp index 610b8541..332157eb 100644 --- a/src/helpers/ui/GxEPDDisplay.cpp +++ b/src/helpers/ui/GxEPDDisplay.cpp @@ -71,9 +71,7 @@ void GxEPDDisplay::turnOn() { expander.digitalWrite(EXP_PIN_BACKLIGHT, HIGH); #endif if (!_isOn) { - forceFullRefresh(); _isOn = true; - last_display_crc_value=0; } } @@ -84,10 +82,12 @@ void GxEPDDisplay::turnOff() { expander.digitalWrite(EXP_PIN_BACKLIGHT, LOW); #endif _isOn = false; - display.setFullWindow(); - display.fillScreen(GxEPD_WHITE); - display.display(true); - forceFullRefresh(); + // do full refresh before powering off to clear screen + // no full refresh needed at wakeup + display.clearScreen(0xFF); // Clears microcontroller side RAM + display.writeScreenBuffer(0xFF); // Forces 0xFF (White) into the display controller's history registers + resetPartialRefreshCounter(); + last_display_crc_value=0; display.hibernate(); } From 1a82394d724410bfbd419db5e152ce04ba10ae57 Mon Sep 17 00:00:00 2001 From: agessaman <adam@gessaman.com> Date: Mon, 17 Aug 2026 14:34:19 -0700 Subject: [PATCH 131/381] fix(sensors): claim an I2C address after a successful init Several table entries share an address and not every driver verifies a chip ID: INA226::begin() only checks that the address ACKs, so an SHT4x at 0x44 was also registered as an INA226 and reported junk current on a second channel. Mark the address consumed once a driver initializes it so later entries cannot re-claim the same device. --- src/helpers/sensors/EnvironmentSensorManager.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/helpers/sensors/EnvironmentSensorManager.cpp b/src/helpers/sensors/EnvironmentSensorManager.cpp index e2f0d33e..c3dfd9f7 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.cpp +++ b/src/helpers/sensors/EnvironmentSensorManager.cpp @@ -650,6 +650,7 @@ bool EnvironmentSensorManager::begin() { continue; } MESH_DEBUG_PRINTLN("Found %s at address: %02X", def.name, def.address); + detected[def.address] = false; // consumed; later entries must not re-claim this device for (uint8_t sub = 0; sub < n && _active_sensor_count < MAX_ACTIVE_SENSORS; sub++) { _active_sensors[_active_sensor_count++] = { def.query, sub }; } From b4917d602792ddf9d1de31fc1310a93c8ddde587 Mon Sep 17 00:00:00 2001 From: agessaman <adam@gessaman.com> Date: Mon, 17 Aug 2026 14:59:59 -0700 Subject: [PATCH 132/381] fix(sensors): probe BMP/BME at both 0x76 and 0x77 Grove and other Bosch modules strap SDO high, so the 0x76-only table never initialized them. Add an alternate-address entry per Bosch sensor; the bus scan still gates every probe, and all four drivers verify a chip ID before claiming an address. Each sensor type has a single static driver instance, so skip an entry whose query is already active: the alternate address is a fallback, not a second device. --- .../sensors/EnvironmentSensorManager.cpp | 24 +++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/src/helpers/sensors/EnvironmentSensorManager.cpp b/src/helpers/sensors/EnvironmentSensorManager.cpp index c3dfd9f7..54305692 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.cpp +++ b/src/helpers/sensors/EnvironmentSensorManager.cpp @@ -539,6 +539,8 @@ static void query_bme680_bsec(uint8_t ch, uint8_t, CayenneLPP& lpp) { // are compiled in. The sentinel at the end keeps the array // non-empty regardless of which sensors are enabled. // +// Bosch BMP/BME SDO selects 0x76 or 0x77; probe both. +// // Ordering here determines channel assignment at runtime: // the first detected+initialized sensor gets channel 2, the // next gets channel 3, and so on. @@ -551,21 +553,27 @@ struct SensorDef { void (*query)(uint8_t channel, uint8_t sub_channel, CayenneLPP& telemetry); }; +#define TELEM_BOSCH_ALT_ADDR(addr) ((uint8_t)((addr) == 0x76 ? 0x77 : 0x76)) + static const SensorDef SENSOR_TABLE[] = { #if ENV_INCLUDE_AHTX0 { TELEM_AHTX_ADDRESS, "AHT10/AHT20", init_ahtx0, query_ahtx0 }, #endif #ifdef ENV_INCLUDE_BME680 - { TELEM_BME680_ADDRESS, "BME680", init_bme680, query_bme680 }, + { TELEM_BME680_ADDRESS, "BME680", init_bme680, query_bme680 }, + { TELEM_BOSCH_ALT_ADDR(TELEM_BME680_ADDRESS), "BME680", init_bme680, query_bme680 }, #endif #if ENV_INCLUDE_BME680_BSEC - { TELEM_BME680_ADDRESS, "BME680+BSEC", init_bme680_bsec, query_bme680_bsec }, + { TELEM_BME680_ADDRESS, "BME680+BSEC", init_bme680_bsec, query_bme680_bsec }, + { TELEM_BOSCH_ALT_ADDR(TELEM_BME680_ADDRESS), "BME680+BSEC", init_bme680_bsec, query_bme680_bsec }, #endif #if ENV_INCLUDE_BME280 - { TELEM_BME280_ADDRESS, "BME280", init_bme280, query_bme280 }, + { TELEM_BME280_ADDRESS, "BME280", init_bme280, query_bme280 }, + { TELEM_BOSCH_ALT_ADDR(TELEM_BME280_ADDRESS), "BME280", init_bme280, query_bme280 }, #endif #if ENV_INCLUDE_BMP280 - { TELEM_BMP280_ADDRESS, "BMP280", init_bmp280, query_bmp280 }, + { TELEM_BMP280_ADDRESS, "BMP280", init_bmp280, query_bmp280 }, + { TELEM_BOSCH_ALT_ADDR(TELEM_BMP280_ADDRESS), "BMP280", init_bmp280, query_bmp280 }, #endif #if ENV_INCLUDE_SHTC3 { 0x70, "SHTC3", init_shtc3, query_shtc3 }, @@ -603,6 +611,8 @@ static const SensorDef SENSOR_TABLE[] = { { 0, nullptr, nullptr, nullptr } // sentinel — keeps the array non-empty }; +#undef TELEM_BOSCH_ALT_ADDR + static const size_t SENSOR_TABLE_SIZE = (sizeof(SENSOR_TABLE) / sizeof(SENSOR_TABLE[0])) - 1; // ============================================================ @@ -640,6 +650,12 @@ bool EnvironmentSensorManager::begin() { _active_sensor_count = 0; for (size_t i = 0; i < SENSOR_TABLE_SIZE && _active_sensor_count < MAX_ACTIVE_SENSORS; i++) { const SensorDef& def = SENSOR_TABLE[i]; + // One static driver instance per type: an alternate address is a fallback, not a second device. + bool already_active = false; + for (int j = 0; j < _active_sensor_count; j++) { + if (_active_sensors[j].query == def.query) { already_active = true; break; } + } + if (already_active) continue; if (!detected[def.address]) { MESH_DEBUG_PRINTLN("%s not detected at I2C address %02X", def.name, def.address); continue; From 44bbf74fbfe11d1148612f2f45d9d1efb4274a20 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Tue, 18 Aug 2026 13:11:15 +1000 Subject: [PATCH 133/381] Fix for CMD_SEND_RAW_DATA and multi-byte paths --- examples/companion_radio/MyMesh.cpp | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 2c334066..16603bc4 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -1512,15 +1512,19 @@ void MyMesh::handleCmdFrame(size_t len) { } 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(); + if (path_len >= 0 && mesh::Packet::isValidPathLen(path_len)) { + uint8_t path[MAX_PATH_SIZE]; + i += mesh::Packet::writePath(path, &cmd_frame[i], path_len); + if (i + 4 > len) { // min payload 4 bytes + writeErrFrame(ERR_CODE_ILLEGAL_ARG); } else { - writeErrFrame(ERR_CODE_TABLE_FULL); + auto pkt = createRawData(&cmd_frame[i], len - i); + if (pkt) { + sendDirect(pkt, path, path_len); + writeOKFrame(); + } else { + writeErrFrame(ERR_CODE_TABLE_FULL); + } } } else { writeErrFrame(ERR_CODE_UNSUPPORTED_CMD); // flood, not supported (yet) From 974564b89ce959fcd4c8a24bab2e113ddf6bb39d Mon Sep 17 00:00:00 2001 From: agessaman <adam@gessaman.com> Date: Mon, 17 Aug 2026 21:04:06 -0700 Subject: [PATCH 134/381] feat(rak3401): cold-sleep RAK4631 onboard SX1262 on RAK13302 builds A RAK4631 core paired with a RAK13302 leaves the core's own SX1262 powered but never initialized, idling in STDBY_RC for the life of the board. Firmware cannot cut its supply -- P1.05 is the RF switch rail, not the radio's -- so bring it up on its own pins just long enough to issue a cold sleep, before std_init() repins SPI onto the RAK13302. Gated behind RAK4631_ONBOARD_SX1262_SLEEP and exposed through seven RAK_4631_13302_* envs, so RAK_3401_* artifacts are unchanged. The sleep is issued regardless of what begin() returns: Module::init() runs first, so SPI stays usable even if TCXO calibration fails. NSS is then held high, since the SX1262 wakes on an NSS falling edge. Verified on RAK19007 + RAK4631 + RAK13302: begin=0 sleep=0, RAK13302 init clean (device_errors=0x0000), TX and RX both confirmed. The current saving itself is derived from the datasheet (600 uA STDBY_RC -> 160 nA cold sleep) and is not measured. --- variants/rak3401/platformio.ini | 125 ++++++++++++++++++++++++++++++++ variants/rak3401/target.cpp | 33 +++++++++ variants/rak3401/variant.h | 15 ++++ 3 files changed, 173 insertions(+) diff --git a/variants/rak3401/platformio.ini b/variants/rak3401/platformio.ini index 48e71922..56883e75 100644 --- a/variants/rak3401/platformio.ini +++ b/variants/rak3401/platformio.ini @@ -134,3 +134,128 @@ build_src_filter = ${rak3401.build_src_filter} extends = rak3401 build_src_filter = ${rak3401.build_src_filter} +<../examples/kiss_modem/> + +; ------------------------- RAK4631 core + RAK13302 ------------------------- +; Same RF hardware as the RAK3401 1W kit, but the RAK4631 core carries a second, +; unused SX1262 that would otherwise idle in standby forever. These envs match +; the RAK_3401_* ones and additionally cold-sleep that radio at boot. +; Do not flash them to a genuine RAK3401 -- there is no onboard radio to sleep. + +[rak4631_13302] +extends = rak3401 +board = rak4631 +build_flags = ${rak3401.build_flags} + -D RAK4631_ONBOARD_SX1262_SLEEP +build_src_filter = ${rak3401.build_src_filter} +lib_deps = ${rak3401.lib_deps} + +[env:RAK_4631_13302_repeater] +extends = rak4631_13302 +build_flags = + ${rak4631_13302.build_flags} + -D DISPLAY_CLASS=SSD1306Display + -D ADVERT_NAME='"RAK4631 1W Repeater"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=50 + ;-D MESH_PACKET_LOGGING=1 + ;-D MESH_DEBUG=1 +build_src_filter = ${rak4631_13302.build_src_filter} + +<helpers/ui/SSD1306Display.cpp> + +<../examples/simple_repeater> + +[env:RAK_4631_13302_room_server] +extends = rak4631_13302 +build_flags = + ${rak4631_13302.build_flags} + -D DISPLAY_CLASS=SSD1306Display + -D ADVERT_NAME='"Test Room"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D ROOM_PASSWORD='"hello"' + ;-D MESH_PACKET_LOGGING=1 + ;-D MESH_DEBUG=1 +build_src_filter = ${rak4631_13302.build_src_filter} + +<helpers/ui/SSD1306Display.cpp> + +<../examples/simple_room_server> + +[env:RAK_4631_13302_companion_radio_usb] +extends = rak4631_13302 +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 712704 +build_flags = + ${rak4631_13302.build_flags} + -I examples/companion_radio/ui-new + -D PIN_USER_BTN_ANA=31 + -D DISPLAY_CLASS=SSD1306Display + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE +; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 +; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 +build_src_filter = ${rak4631_13302.build_src_filter} + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = + ${rak4631_13302.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[env:RAK_4631_13302_companion_radio_ble] +extends = rak4631_13302 +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 712704 +build_flags = + ${rak4631_13302.build_flags} + -I examples/companion_radio/ui-new + -D PIN_USER_BTN_ANA=31 + -D DISPLAY_CLASS=SSD1306Display + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D BLE_PIN_CODE=123456 + -D BLE_DEBUG_LOGGING=1 + -D OFFLINE_QUEUE_SIZE=256 + ;-D MESH_PACKET_LOGGING=1 + ;-D MESH_DEBUG=1 +build_src_filter = ${rak4631_13302.build_src_filter} + +<helpers/nrf52/SerialBLEInterface.cpp> + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = + ${rak4631_13302.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[env:RAK_4631_13302_terminal_chat] +extends = rak4631_13302 +build_flags = + ${rak4631_13302.build_flags} + -D MAX_CONTACTS=100 + -D MAX_GROUP_CHANNELS=1 + ;-D MESH_PACKET_LOGGING=1 + ;-D MESH_DEBUG=1 +build_src_filter = ${rak4631_13302.build_src_filter} + +<../examples/simple_secure_chat/main.cpp> +lib_deps = + ${rak4631_13302.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[env:RAK_4631_13302_sensor] +extends = rak4631_13302 +build_flags = + ${rak4631_13302.build_flags} + -D DISPLAY_CLASS=SSD1306Display + -D ADVERT_NAME='"RAK4631 Sensor"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + ;-D MESH_PACKET_LOGGING=1 + ;-D MESH_DEBUG=1 +build_src_filter = ${rak4631_13302.build_src_filter} + +<helpers/ui/SSD1306Display.cpp> + +<../examples/simple_sensor> + +[env:RAK_4631_13302_kiss_modem] +extends = rak4631_13302 +build_src_filter = ${rak4631_13302.build_src_filter} + +<../examples/kiss_modem/> diff --git a/variants/rak3401/target.cpp b/variants/rak3401/target.cpp index 5309e6b2..640b4d02 100644 --- a/variants/rak3401/target.cpp +++ b/variants/rak3401/target.cpp @@ -32,8 +32,41 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); EnvironmentSensorManager sensors; #endif +#ifdef RAK4631_ONBOARD_SX1262_SLEEP +// With a RAK13302 fitted the RAK4631's own SX1262 never gets initialized, so it +// sits in STDBY_RC drawing standby current for the life of the board. Firmware +// cannot cut its supply -- P1.05 is the RF switch rail, not the radio's -- so +// bring it up on its own pins just long enough to put it into cold sleep. +static void sleep_onboard_radio() { + pinMode(ONBOARD_LORA_ANT_SW, OUTPUT); + digitalWrite(ONBOARD_LORA_ANT_SW, LOW); // nothing downstream needs the RF switch + + SPI.setPins(ONBOARD_LORA_MISO, ONBOARD_LORA_SCLK, ONBOARD_LORA_MOSI); + SPI.begin(); + + Module mod(ONBOARD_LORA_NSS, ONBOARD_LORA_DIO_1, ONBOARD_LORA_RESET, ONBOARD_LORA_BUSY, SPI); + SX1262 onboard(&mod); + + // begin() resets the chip and leaves it in standby. A TCXO calibration failure + // still leaves SPI usable, so issue the sleep regardless of what it returns. + int status = onboard.begin(434.0f, 125.0f, 9, 7, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, + 0, 8, ONBOARD_LORA_TCXO_VOLTAGE, false); + int slept = onboard.sleep(false); // cold sleep: config discarded, RTC off + MESH_DEBUG_PRINTLN("onboard SX1262: begin=%d sleep=%d", status, slept); + + SPI.end(); // release SPIM3 so std_init() can repin it onto the RAK13302 + + // The SX1262 wakes on an NSS falling edge, so keep NSS driven high from here on. + digitalWrite(ONBOARD_LORA_NSS, HIGH); + pinMode(ONBOARD_LORA_NSS, OUTPUT); +} +#endif + bool radio_init() { rtc_clock.begin(Wire); +#ifdef RAK4631_ONBOARD_SX1262_SLEEP + sleep_onboard_radio(); +#endif return radio.std_init(&SPI); } diff --git a/variants/rak3401/variant.h b/variants/rak3401/variant.h index 98827886..0576dadb 100644 --- a/variants/rak3401/variant.h +++ b/variants/rak3401/variant.h @@ -175,6 +175,21 @@ static const uint8_t AREF = PIN_AREF; #define P_LORA_BUSY SX126X_BUSY #define P_LORA_RESET SX126X_RESET +// The RAK4631 core carries its own SX1262, which is unused when a RAK13302 +// supplies the RF path. RAK4631_ONBOARD_SX1262_SLEEP builds put it into cold +// sleep at boot; on a genuine RAK3401 these pins are unconnected. +#ifdef RAK4631_ONBOARD_SX1262_SLEEP +#define ONBOARD_LORA_NSS (42) // P1.10 +#define ONBOARD_LORA_SCLK (43) // P1.11 +#define ONBOARD_LORA_MOSI (44) // P1.12 +#define ONBOARD_LORA_MISO (45) // P1.13 +#define ONBOARD_LORA_BUSY (46) // P1.14 +#define ONBOARD_LORA_DIO_1 (47) // P1.15 +#define ONBOARD_LORA_RESET (38) // P1.06 +#define ONBOARD_LORA_ANT_SW (37) // P1.05, powers the onboard RF switch +#define ONBOARD_LORA_TCXO_VOLTAGE 1.8 +#endif + // enables 3.3V periphery like GPS or IO Module // Do not toggle this for GPS power savings #define PIN_3V3_EN (34) From 94a4c0b0ed1bc9a84308fab2ac4d2dfb4d1592c3 Mon Sep 17 00:00:00 2001 From: agessaman <adam@gessaman.com> Date: Mon, 17 Aug 2026 22:19:49 -0700 Subject: [PATCH 135/381] feat(rak3401): report onboard SX1262 sleep state via BUSY BUSY is driven low in STDBY_RC and high while asleep, so reading it either side of the sleep gives a non-invasive readback of the state the chip was found in and the state it was left in. Confirmed on hardware. This is what makes the sleep observable at all. The only other symptom of a failed sleep is ~600 uA, which is below what an inline USB meter can resolve, so without this a regression would be silent. It immediately earned itself: busy_before reads 0 on every boot, showing the cold sleep does not survive an MCU reset. GPIOs revert to input during reset, NSS stops being driven high, and the falling edge wakes the chip. The helper re-sleeps it, so this is self-healing, but it means the chip is never found already asleep. --- variants/rak3401/target.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/variants/rak3401/target.cpp b/variants/rak3401/target.cpp index 640b4d02..dac12ede 100644 --- a/variants/rak3401/target.cpp +++ b/variants/rak3401/target.cpp @@ -47,12 +47,20 @@ static void sleep_onboard_radio() { Module mod(ONBOARD_LORA_NSS, ONBOARD_LORA_DIO_1, ONBOARD_LORA_RESET, ONBOARD_LORA_BUSY, SPI); SX1262 onboard(&mod); + // BUSY is driven low in STDBY_RC and high while asleep, so it doubles as a + // non-invasive readback of what state we found the chip in and left it in. + pinMode(ONBOARD_LORA_BUSY, INPUT); + int busy_before = digitalRead(ONBOARD_LORA_BUSY); + // begin() resets the chip and leaves it in standby. A TCXO calibration failure // still leaves SPI usable, so issue the sleep regardless of what it returns. int status = onboard.begin(434.0f, 125.0f, 9, 7, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 0, 8, ONBOARD_LORA_TCXO_VOLTAGE, false); int slept = onboard.sleep(false); // cold sleep: config discarded, RTC off - MESH_DEBUG_PRINTLN("onboard SX1262: begin=%d sleep=%d", status, slept); + delay(2); + int busy_after = digitalRead(ONBOARD_LORA_BUSY); + MESH_DEBUG_PRINTLN("onboard SX1262: begin=%d sleep=%d busy %d->%d", + status, slept, busy_before, busy_after); SPI.end(); // release SPIM3 so std_init() can repin it onto the RAK13302 From 630fa3560405c7582f0a61052f0699a1d2969913 Mon Sep 17 00:00:00 2001 From: Dominik Tyrala <dominiktyrala.prog@gmail.com> Date: Mon, 17 Aug 2026 15:50:46 +0200 Subject: [PATCH 136/381] Fixes BLE exceeding flash size --- variants/xiao_c3/platformio.ini | 1 + 1 file changed, 1 insertion(+) diff --git a/variants/xiao_c3/platformio.ini b/variants/xiao_c3/platformio.ini index 587c5c27..c9c107c6 100644 --- a/variants/xiao_c3/platformio.ini +++ b/variants/xiao_c3/platformio.ini @@ -73,6 +73,7 @@ lib_deps = [env:Xiao_C3_companion_radio_ble] extends = Xiao_esp32_C3 +board_build.partitions = min_spiffs.csv ; get around 4mb flash limit build_src_filter = ${Xiao_esp32_C3.build_src_filter} +<../examples/companion_radio/*.cpp> +<helpers/esp32/*.cpp> From 053fa3eb836e848671a03df4847696762802a876 Mon Sep 17 00:00:00 2001 From: Rastislav Vysoky <recrof@gmail.com> Date: Tue, 18 Aug 2026 13:51:55 +0200 Subject: [PATCH 137/381] fix: move MeshadventurerBoard.h to correct location --- {src/helpers => variants/meshadventurer}/MeshadventurerBoard.h | 2 +- variants/meshadventurer/target.h | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) rename {src/helpers => variants/meshadventurer}/MeshadventurerBoard.h (97%) diff --git a/src/helpers/MeshadventurerBoard.h b/variants/meshadventurer/MeshadventurerBoard.h similarity index 97% rename from src/helpers/MeshadventurerBoard.h rename to variants/meshadventurer/MeshadventurerBoard.h index 0325161d..d9e88e1b 100644 --- a/src/helpers/MeshadventurerBoard.h +++ b/variants/meshadventurer/MeshadventurerBoard.h @@ -13,7 +13,7 @@ #define PIN_VBAT_READ 35 -#include "ESP32Board.h" +#include "helpers/ESP32Board.h" class MeshadventurerBoard : public ESP32Board { diff --git a/variants/meshadventurer/target.h b/variants/meshadventurer/target.h index d59b3aee..0749565d 100644 --- a/variants/meshadventurer/target.h +++ b/variants/meshadventurer/target.h @@ -3,7 +3,7 @@ #define RADIOLIB_STATIC_ONLY 1 #include <RadioLib.h> #include <helpers/radiolib/RadioLibWrappers.h> -#include <helpers/MeshadventurerBoard.h> +#include <MeshadventurerBoard.h> #include <helpers/radiolib/CustomSX1262Wrapper.h> #include <helpers/radiolib/CustomSX1268Wrapper.h> #include <helpers/AutoDiscoverRTCClock.h> @@ -44,4 +44,3 @@ extern MASensorManager sensors; bool radio_init(); mesh::LocalIdentity radio_new_identity(); - From d1a2a0c20bf04e2b63c1044f370340292a637416 Mon Sep 17 00:00:00 2001 From: Rastislav Vysoky <recrof@gmail.com> Date: Tue, 18 Aug 2026 14:56:27 +0200 Subject: [PATCH 138/381] repeater: set `loop.detect` to `minimal` as default for new installs --- examples/simple_repeater/MyMesh.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index 7d0179f3..a711ec0a 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -341,7 +341,7 @@ int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t int results_offset = 0; uint8_t results_buffer[130]; for(int index = 0; index < count && index + offset < neighbours_count; index++){ - + // stop if we can't fit another entry in results int entry_size = pubkey_prefix_length + 4 + 1; if(results_offset + entry_size > sizeof(results_buffer)){ @@ -907,6 +907,7 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc _prefs.flood_max_advert = 8; _prefs.interference_threshold = 0; // disabled _prefs.cad_enabled = 0; // hardware CAD before TX (off by default; 'set cad on') + _prefs.loop_detect = LOOP_DETECT_MINIMAL; // bridge defaults _prefs.bridge_enabled = 1; // enabled @@ -1170,7 +1171,7 @@ void MyMesh::formatRadioStatsReply(char *reply) { } void MyMesh::formatPacketStatsReply(char *reply) { - StatsFormatHelper::formatPacketStats(reply, radio_driver, getNumSentFlood(), getNumSentDirect(), + StatsFormatHelper::formatPacketStats(reply, radio_driver, getNumSentFlood(), getNumSentDirect(), getNumRecvFlood(), getNumRecvDirect()); } From 0c96a4fa98d1deb5707e31f67a8da945d1dd9c89 Mon Sep 17 00:00:00 2001 From: F4FPR <Bensam148@hotmail.com> Date: Tue, 18 Aug 2026 19:38:23 +0200 Subject: [PATCH 139/381] Update MeshCore.h --- src/MeshCore.h | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/MeshCore.h b/src/MeshCore.h index 22979476..ca12daee 100644 --- a/src/MeshCore.h +++ b/src/MeshCore.h @@ -76,6 +76,14 @@ public: virtual bool isExternalPowered() { return false; } // True while a board can identify an active battery-charging source. virtual bool isChargerActive() { return false; } + + // Optional, source-specific power detection. Boards that can distinguish a USB + // supply from a solar charger override these; defaults keep every other board + // unaffected (the generic CLI prints "n/a" when a capability is absent). + virtual bool hasUsbPowerDetect() const { return false; } + virtual bool isUsbPowered() { return false; } + virtual bool hasSolarChargerDetect() const { return false; } + virtual bool isSolarChargerActive() { return false; } virtual uint16_t getBootVoltage() { return 0; } virtual uint32_t getResetReason() const { return 0; } virtual const char* getResetReasonString(uint32_t reason) { return "Not available"; } From 5a6e12200cd662f73c7b4cb123e184d9e6ab321e Mon Sep 17 00:00:00 2001 From: F4FPR <Bensam148@hotmail.com> Date: Tue, 18 Aug 2026 19:39:21 +0200 Subject: [PATCH 140/381] Update CommonCLI.cpp --- src/helpers/CommonCLI.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index d2a8b707..f2daf3cd 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -274,8 +274,16 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re } else if (memcmp(command, "board", 5) == 0) { sprintf(reply, "%s", _board->getManufacturerName()); } else if (strcmp(command, "power") == 0) { - snprintf(reply, 160, "batt:%u mV ext:%s charger:%s", + const char* usb_state = _board->hasUsbPowerDetect() + ? (_board->isUsbPowered() ? "yes" : "no") + : "n/a"; + const char* solar_state = _board->hasSolarChargerDetect() + ? (_board->isSolarChargerActive() ? "yes" : "no") + : "n/a"; + snprintf(reply, 160, "batt:%u mV usb:%s solar_chg:%s ext:%s charger:%s", (unsigned)_board->getBattMilliVolts(), + usb_state, + solar_state, _board->isExternalPowered() ? "yes" : "no", _board->isChargerActive() ? "yes" : "no"); } else if (memcmp(command, "sensor get ", 11) == 0) { From 3f2751ac50a5e34189d4e3ea68e9f47b1bb23f0b Mon Sep 17 00:00:00 2001 From: F4FPR <Bensam148@hotmail.com> Date: Tue, 18 Aug 2026 19:40:42 +0200 Subject: [PATCH 141/381] Update ThinkNodeM6Board.h --- variants/thinknode_m6/ThinkNodeM6Board.h | 26 ++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/variants/thinknode_m6/ThinkNodeM6Board.h b/variants/thinknode_m6/ThinkNodeM6Board.h index 1af952d2..934794c9 100644 --- a/variants/thinknode_m6/ThinkNodeM6Board.h +++ b/variants/thinknode_m6/ThinkNodeM6Board.h @@ -36,19 +36,33 @@ public: return "Elecrow ThinkNode M6"; } + bool hasUsbPowerDetect() const override { return true; } + + bool isUsbPowered() override { + // P0.13 is the dedicated USB / external power-detect line on the M6 PCB + // (same pin the Meshtastic M6 variant uses for USB detection). + return digitalRead(EXT_PWR_DETECT) == EXT_PWR_DETECT_VALUE; + } + + bool hasSolarChargerDetect() const override { return true; } + + bool isSolarChargerActive() override { + // P0.15 is the active-low solar-charger status line. It reports the + // charger's state, not photovoltaic voltage or current. + return digitalRead(EXT_CHRG_DETECT) == EXT_CHRG_DETECT_VALUE; + } + bool isExternalPowered() override { - if (digitalRead(EXT_PWR_DETECT) == EXT_PWR_DETECT_VALUE || - digitalRead(EXT_CHRG_DETECT) == EXT_CHRG_DETECT_VALUE) { + if (isUsbPowered() || isSolarChargerActive()) { return true; } return NRF52Board::isExternalPowered(); } bool isChargerActive() override { - // The charge-status line covers solar input; external USB input is also a - // charging source, although the board cannot report charge completion. - return digitalRead(EXT_CHRG_DETECT) == EXT_CHRG_DETECT_VALUE || - digitalRead(EXT_PWR_DETECT) == EXT_PWR_DETECT_VALUE; + // Preserve a generic charging indication while also exposing both + // source-specific states (USB / solar) separately through the CLI. + return isSolarChargerActive() || isUsbPowered(); } void powerOff() override { From deb5e735b80a3c7d0f236b6b7b3a74eb182756c2 Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Wed, 19 Aug 2026 12:07:29 +1200 Subject: [PATCH 142/381] updated gcc toolchain for nrf52 boards --- platformio.ini | 1 + src/armstubs.cpp | 9 +++++++++ 2 files changed, 10 insertions(+) create mode 100644 src/armstubs.cpp diff --git a/platformio.ini b/platformio.ini index e78124a4..ee502473 100644 --- a/platformio.ini +++ b/platformio.ini @@ -86,6 +86,7 @@ platform_packages = ; https://github.com/meshcore-dev/MeshCore/pull/1177 ; https://github.com/meshcore-dev/MeshCore/pull/1295 framework-arduinoadafruitnrf52 @ https://github.com/meshcore-dev/Adafruit_nRF52_Arduino#d541301 + platformio/toolchain-gccarmnoneeabi@^1.140201.0 extra_scripts = create-uf2.py build_flags = ${arduino_base.build_flags} -D NRF52_PLATFORM diff --git a/src/armstubs.cpp b/src/armstubs.cpp new file mode 100644 index 00000000..30da40ec --- /dev/null +++ b/src/armstubs.cpp @@ -0,0 +1,9 @@ +// https://github.com/meshcore-dev/MeshCore/issues/2469 +// armstubs.cpp exists to silence warnings introduced after upgrading platformio/toolchain-gccarmnoneeabi +extern "C" __attribute__((weak)) int _close(int fd) { return -1; } +extern "C" __attribute__((weak)) int _lseek(int fd, int offset, int whence) { return 0; } +extern "C" __attribute__((weak)) int _read(int fd, char *buf, int len) { return 0; } +extern "C" __attribute__((weak)) int _fstat(int fd, struct stat *st) { return 0; } +extern "C" __attribute__((weak)) int _isatty(int fd) { return 1; } +extern "C" __attribute__((weak)) int _getpid(void) { return 1; } +extern "C" __attribute__((weak)) int _kill(int pid, int sig) { return -1; } From 0927801deb34ee957c9012c91b3ccbc35c507e68 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Wed, 19 Aug 2026 15:29:19 +1000 Subject: [PATCH 143/381] WIO Tracker L1 1W variant --- examples/companion_radio/MyMesh.cpp | 4 + .../wio-tracker-l1-1w/WioTrackerL1Board.cpp | 40 ++++++ .../wio-tracker-l1-1w/WioTrackerL1Board.h | 46 +++++++ variants/wio-tracker-l1-1w/platformio.ini | 121 ++++++++++++++++ variants/wio-tracker-l1-1w/target.cpp | 40 ++++++ variants/wio-tracker-l1-1w/target.h | 35 +++++ variants/wio-tracker-l1-1w/variant.cpp | 78 +++++++++++ variants/wio-tracker-l1-1w/variant.h | 130 ++++++++++++++++++ 8 files changed, 494 insertions(+) create mode 100644 variants/wio-tracker-l1-1w/WioTrackerL1Board.cpp create mode 100644 variants/wio-tracker-l1-1w/WioTrackerL1Board.h create mode 100644 variants/wio-tracker-l1-1w/platformio.ini create mode 100644 variants/wio-tracker-l1-1w/target.cpp create mode 100644 variants/wio-tracker-l1-1w/target.h create mode 100644 variants/wio-tracker-l1-1w/variant.cpp create mode 100644 variants/wio-tracker-l1-1w/variant.h diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 16603bc4..a6739ac0 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -886,7 +886,11 @@ MyMesh::MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMe _prefs.gps_enabled = 0; // GPS disabled by default _prefs.gps_interval = 0; // No automatic GPS updates by default _prefs.radio_fem_rxgain = 1; +#ifdef RADIO_FEM_TXGAIN + _prefs.radio_fem_txgain = RADIO_FEM_TXGAIN; // board-specific default for PA +#else _prefs.radio_fem_txgain = 0; +#endif //_prefs.rx_delay_base = 10.0f; enable once new algo fixed _prefs.setRepeatEn(false); #if defined(USE_SX1262) || defined(USE_SX1268) diff --git a/variants/wio-tracker-l1-1w/WioTrackerL1Board.cpp b/variants/wio-tracker-l1-1w/WioTrackerL1Board.cpp new file mode 100644 index 00000000..8210c24e --- /dev/null +++ b/variants/wio-tracker-l1-1w/WioTrackerL1Board.cpp @@ -0,0 +1,40 @@ +#include <Arduino.h> +#include <Wire.h> + +#include "WioTrackerL1Board.h" + +void WioTrackerL1Board::begin() { + NRF52BoardDCDC::begin(); + btn_prev_state = HIGH; + + pinMode(PIN_VBAT_READ, INPUT); // VBAT ADC input + // Set all button pins to INPUT_PULLUP + pinMode(PIN_BUTTON1, INPUT_PULLUP); + pinMode(PIN_BUTTON2, INPUT_PULLUP); + pinMode(PIN_BUTTON3, INPUT_PULLUP); + pinMode(PIN_BUTTON4, INPUT_PULLUP); + pinMode(PIN_BUTTON5, INPUT_PULLUP); + pinMode(PIN_BUTTON6, INPUT_PULLUP); + + + #if defined(PIN_WIRE_SDA) && defined(PIN_WIRE_SCL) + Wire.setPins(PIN_WIRE_SDA, PIN_WIRE_SCL); + #endif + + Wire.begin(); + + pinMode(SX126X_POWER_EN, OUTPUT); + + #ifdef P_LORA_TX_LED + pinMode(P_LORA_TX_LED, OUTPUT); + digitalWrite(P_LORA_TX_LED, LOW); + #endif + + delay(10); // give sx1262 some time to power up +} + +bool WioTrackerL1Board::setLoRaFemPaGainEnabled(bool enable) { + _is_pa_enabled = enable; + digitalWrite(SX126X_POWER_EN, enable ? HIGH : LOW); // enable/disable the 1W PA + return true; +} diff --git a/variants/wio-tracker-l1-1w/WioTrackerL1Board.h b/variants/wio-tracker-l1-1w/WioTrackerL1Board.h new file mode 100644 index 00000000..c5a60944 --- /dev/null +++ b/variants/wio-tracker-l1-1w/WioTrackerL1Board.h @@ -0,0 +1,46 @@ +#pragma once + +#include <MeshCore.h> +#include <Arduino.h> +#include <helpers/NRF52Board.h> + +class WioTrackerL1Board : public NRF52BoardDCDC { +protected: + uint8_t btn_prev_state; + bool _is_pa_enabled = false; + +public: + WioTrackerL1Board() : NRF52Board("WioTrackerL1 OTA") {} + void begin(); + +#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 { + int adcvalue = 0; + analogReadResolution(12); + analogReference(AR_INTERNAL); + delay(10); + adcvalue = analogRead(PIN_VBAT_READ); + return (adcvalue * ADC_MULTIPLIER * AREF_VOLTAGE) / 4.096; + } + + const char* getManufacturerName() const override { + return "Seeed Wio Tracker L1"; + } + + bool canControlLoRaFemPaGain() const override { return true; } + bool setLoRaFemPaGainEnabled(bool enable) override; + bool isLoRaFemPaGainEnabled() const override { return _is_pa_enabled; } + + void powerOff() override { + setLoRaFemPaGainEnabled(false); // turn Off PA + NRF52Board::powerOff(); + } +}; diff --git a/variants/wio-tracker-l1-1w/platformio.ini b/variants/wio-tracker-l1-1w/platformio.ini new file mode 100644 index 00000000..e5b4a3be --- /dev/null +++ b/variants/wio-tracker-l1-1w/platformio.ini @@ -0,0 +1,121 @@ +[WioTrackerL1-1W] +extends = nrf52_base +board = seeed-wio-tracker-l1 +board_build.ldscript = boards/nrf52840_s140_v7.ld +build_flags = ${nrf52_base.build_flags} + ${sensor_base.build_flags} + -I lib/nrf52/s140_nrf52_7.3.0_API/include + -I lib/nrf52/s140_nrf52_7.3.0_API/include/nrf52 + -I variants/wio-tracker-l1-1w + -D WIO_TRACKER_L1 + -D USE_SX1262 + -D RADIO_CLASS=CustomSX1262 + -D WRAPPER_CLASS=CustomSX1262Wrapper + -D LORA_TX_POWER=22 + -D SX126X_CURRENT_LIMIT=140 + -D SX126X_RX_BOOSTED_GAIN=1 + -D PIN_OLED_RESET=-1 + -D GPS_BAUD_RATE=9600 +build_src_filter = ${nrf52_base.build_src_filter} + +<WioTrackerL1Board.cpp> + +<../variants/wio-tracker-l1-1w> + +<helpers/ui/SH1106Display.cpp> + +<helpers/sensors> +lib_deps= ${nrf52_base.lib_deps} + ${sensor_base.lib_deps} + adafruit/Adafruit SH110X @ ^2.1.13 + adafruit/Adafruit GFX Library @ ^1.12.1 + +[env:WioTrackerL1-1W_repeater] +extends = WioTrackerL1-1W +build_src_filter = ${WioTrackerL1-1W.build_src_filter} + +<../examples/simple_repeater> +build_flags = + ${WioTrackerL1-1W.build_flags} + -D ADVERT_NAME='"WioTrackerL1 Repeater"' + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=50 + -D DISPLAY_CLASS=SH1106Display +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +lib_deps = ${WioTrackerL1-1W.lib_deps} + adafruit/RTClib @ ^2.1.3 + +[env:WioTrackerL1-1W_room_server] +extends = WioTrackerL1-1W +build_src_filter = ${WioTrackerL1-1W.build_src_filter} + +<../examples/simple_room_server> +build_flags = ${WioTrackerL1-1W.build_flags} + -D ADVERT_NAME='"WioTrackerL1 Room"' + -D ADMIN_PASSWORD='"password"' + -D ROOM_PASSWORD='"hello"' + -D DISPLAY_CLASS=SH1106Display +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +lib_deps = ${WioTrackerL1-1W.lib_deps} + adafruit/RTClib @ ^2.1.3 + +[env:WioTrackerL1-1W_companion_radio_usb] +extends = WioTrackerL1-1W +board_build.ldscript = boards/nrf52840_s140_v7_extrafs.ld +board_upload.maximum_size = 708608 +build_flags = ${WioTrackerL1-1W.build_flags} + -I examples/companion_radio/ui-new + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D DISPLAY_CLASS=SH1106Display + -D UI_HAS_JOYSTICK=1 + -D OFFLINE_QUEUE_SIZE=256 + -D PIN_BUZZER=12 + -D QSPIFLASH=1 + -D RADIO_FEM_TXGAIN=1 + -D ENABLE_USB_INTERFACE +; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 +; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 +build_src_filter = ${WioTrackerL1-1W.build_src_filter} + +<helpers/ui/MomentaryButton.cpp> + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> + +<helpers/ui/SH1106Display.cpp> + +<helpers/ui/buzzer.cpp> +lib_deps = ${WioTrackerL1-1W.lib_deps} + adafruit/RTClib @ ^2.1.3 + densaugeo/base64 @ ~1.4.0 + end2endzone/NonBlockingRTTTL@^1.3.0 + +[env:WioTrackerL1-1W_companion_radio_ble] +extends = WioTrackerL1-1W +board_build.ldscript = boards/nrf52840_s140_v7_extrafs.ld +board_upload.maximum_size = 708608 +build_flags = ${WioTrackerL1-1W.build_flags} + -I examples/companion_radio/ui-new + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D BLE_PIN_CODE=123456 + -D BLE_DEBUG_LOGGING=1 + -D OFFLINE_QUEUE_SIZE=256 + -D DISPLAY_CLASS=SH1106Display + -D UI_HAS_JOYSTICK=1 + -D PIN_BUZZER=12 + -D QSPIFLASH=1 + -D RADIO_FEM_TXGAIN=1 + -D ADVERT_NAME='"@@MAC"' + -D ENV_PIN_SDA=PIN_WIRE1_SDA + -D ENV_PIN_SCL=PIN_WIRE1_SCL + ; -D MESH_PACKET_LOGGING=1 + ; -D MESH_DEBUG=1 +build_src_filter = ${WioTrackerL1-1W.build_src_filter} + +<helpers/nrf52/SerialBLEInterface.cpp> + +<helpers/ui/MomentaryButton.cpp> + +<helpers/ui/buzzer.cpp> + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = ${WioTrackerL1-1W.lib_deps} + adafruit/RTClib @ ^2.1.3 + densaugeo/base64 @ ~1.4.0 + end2endzone/NonBlockingRTTTL@^1.3.0 + +[env:WioTrackerL1-1W_kiss_modem] +extends = WioTrackerL1-1W +build_src_filter = ${WioTrackerL1-1W.build_src_filter} + +<../examples/kiss_modem/> diff --git a/variants/wio-tracker-l1-1w/target.cpp b/variants/wio-tracker-l1-1w/target.cpp new file mode 100644 index 00000000..7a573258 --- /dev/null +++ b/variants/wio-tracker-l1-1w/target.cpp @@ -0,0 +1,40 @@ +#include <Arduino.h> +#include "target.h" +#include <helpers/ArduinoHelpers.h> +#include <helpers/sensors/MicroNMEALocationProvider.h> + +WioTrackerL1Board board; + +RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, SPI); + +WRAPPER_CLASS radio_driver(radio, board); + +VolatileRTCClock fallback_clock; +AutoDiscoverRTCClock rtc_clock(fallback_clock); + +#ifdef ENV_INCLUDE_GPS +MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); +#else +EnvironmentSensorManager sensors = EnvironmentSensorManager(); +#endif + +#ifdef DISPLAY_CLASS + DISPLAY_CLASS display; + MomentaryButton user_btn(PIN_USER_BTN, 1000, true, false, false); + MomentaryButton joystick_left(JOYSTICK_LEFT, 1000, true, false, false); + MomentaryButton joystick_right(JOYSTICK_RIGHT, 1000, true, false, false); + MomentaryButton back_btn(PIN_BACK_BTN, 1000, true, false, true); +#endif + +bool radio_init() { + rtc_clock.begin(Wire); + + return radio.std_init(&SPI); +} + +mesh::LocalIdentity radio_new_identity() { + RadioNoiseListener rng(radio); + return mesh::LocalIdentity(&rng); // create new random identity +} + diff --git a/variants/wio-tracker-l1-1w/target.h b/variants/wio-tracker-l1-1w/target.h new file mode 100644 index 00000000..05bc7ff1 --- /dev/null +++ b/variants/wio-tracker-l1-1w/target.h @@ -0,0 +1,35 @@ +#pragma once + +#define RADIOLIB_STATIC_ONLY 1 +#include <RadioLib.h> +#include <helpers/radiolib/RadioLibWrappers.h> +#include <WioTrackerL1Board.h> +#include <helpers/radiolib/CustomSX1262Wrapper.h> +#include <helpers/AutoDiscoverRTCClock.h> +#include <helpers/ArduinoHelpers.h> +#include <helpers/sensors/EnvironmentSensorManager.h> +#ifdef DISPLAY_CLASS + #if defined(WIO_TRACKER_L1_EINK) + #include <helpers/ui/GxEPDDisplay.h> + #else + #include <helpers/ui/SH1106Display.h> + #endif + #include <helpers/ui/MomentaryButton.h> +#endif +#include <helpers/sensors/EnvironmentSensorManager.h> + +extern WioTrackerL1Board board; +extern WRAPPER_CLASS radio_driver; +extern AutoDiscoverRTCClock rtc_clock; +extern EnvironmentSensorManager sensors; +#ifdef DISPLAY_CLASS + extern DISPLAY_CLASS display; + extern MomentaryButton user_btn; + extern MomentaryButton joystick_left; + extern MomentaryButton joystick_right; + extern MomentaryButton back_btn; +#endif + +bool radio_init(); +mesh::LocalIdentity radio_new_identity(); + diff --git a/variants/wio-tracker-l1-1w/variant.cpp b/variants/wio-tracker-l1-1w/variant.cpp new file mode 100644 index 00000000..18efe7ea --- /dev/null +++ b/variants/wio-tracker-l1-1w/variant.cpp @@ -0,0 +1,78 @@ +#include "variant.h" +#include "wiring_constants.h" +#include "wiring_digital.h" +#include "nrf.h" + +const uint32_t g_ADigitalPinMap[] = { + // D0 .. D10 - Peripheral control pins + 41, // D0 P1.09 GNSS_WAKEUP + 7, // D1 P0.07 LORA_DIO1 + 39, // D2 P1,07 LORA_RESET + 42, // D3 P1.10 LORA_BUSY + 46, // D4 P1.14 (A4/SDA) LORA_CS + 29, // D5 P0.29 (AIN5) LORA_VDET 鈥?Pro 1W: P0.29 (not P1.08) + 27, // D6 P0.27 (UART_TX) GNSS_TX + 26, // D7 P0.26 (UART_RX) GNSS_RX + 30, // D8 P0.30 (SPI_SCK) LORA_SCK + 3, // D9 P0.3 (SPI_MISO) LORA_MISO + 28, // D10 P0.28 (SPI_MOSI) LORA_MOSI + + // D11-D12 - LED outputs + 33, // D11 P1.01 Mesh_LED (orange) 鈥?Pro 1W: P1.01 (not P1.15) + // Buzzzer + 32, // D12 P1.0 Buzzer + + // D13 - User input + 8, // D13 P0.08 User Button + + // D14-D15 - OLED + 6, // D14 P0.06 OLED SDA + 5, // D15 P0.05 OLED SCL + + // D16 - Battery voltage ADC input + 31, // D16 P0.31 VBAT_ADC + // GROVE + 43, // D17 P0.00 GROVE SDA + 44, // D18 P0.01 GROVE SCL + + // FLASH + 21, // D19 P0.21 (QSPI_SCK) + 25, // D20 P0.25 (QSPI_CSN) + 20, // D21 P0.20 (QSPI_SIO_0 DI) + 24, // D22 P0.24 (QSPI_SIO_1 DO) + 22, // D23 P0.22 (QSPI_SIO_2 WP) + 23, // D24 P0.23 (QSPI_SIO_3 HOLD) + + // JOYSTICK + 36, // D25 TB_UP + 12, // D26 TB_DOWN + 11, // D27 TB_LEFT + 35, // D28 TB_RIGHT + 37, // D29 TB_PRESS + + // VBAT ENABLE + 4, // D30 BAT_CTL + + // D31-D33 - Pro 1W only + 13, // D31 P0.13 BOOST_EN (Grove 5V Boost) + 47, // D32 P1.15 nRF_Sig_Charge_State (BQ25616 STAT) + 14, // D33 P0.14 LORA_PWR_EN (SX1262 + 1 W PA LDO) +}; + +void initVariant() { + pinMode(PIN_QSPI_CS, OUTPUT); + digitalWrite(PIN_QSPI_CS, HIGH); + + // VBAT_ENABLE + pinMode(VBAT_ENABLE, OUTPUT); + digitalWrite(VBAT_ENABLE, HIGH); + + // set LED pin as output and set it low + pinMode(PIN_LED, OUTPUT); + digitalWrite(PIN_LED, LOW); + + // set buzzer pin as output and set it low + pinMode(12, OUTPUT); + digitalWrite(12, LOW); + pinMode(12, OUTPUT); +} diff --git a/variants/wio-tracker-l1-1w/variant.h b/variants/wio-tracker-l1-1w/variant.h new file mode 100644 index 00000000..7520460a --- /dev/null +++ b/variants/wio-tracker-l1-1w/variant.h @@ -0,0 +1,130 @@ +#ifndef _SEEED_WIO_TRACKER_L1_H_ +#define _SEEED_WIO_TRACKER_L1_H_ + +/** Master clock frequency */ +#define VARIANT_MCK (64000000ul) + +#define USE_LFXO // Board uses 32khz crystal for LF + +/*---------------------------------------------------------------------------- + * Headers + *----------------------------------------------------------------------------*/ + +#include "WVariant.h" + +#define PINS_COUNT (34) +#define NUM_DIGITAL_PINS (34) +#define NUM_ANALOG_INPUTS (8) +#define NUM_ANALOG_OUTPUTS (0) + +// LEDs +#define PIN_LED (11) +#define LED_BLUE (-1) // Disable annoying flashing caused by Bluefruit +#define LED_BUILTIN PIN_LED +#define P_LORA_TX_LED PIN_LED +#define LED_STATE_ON 1 + +// Buttons +#define PIN_BUTTON1 (13) // Menu / User Button +#define PIN_BUTTON2 (25) // Joystick Up +#define PIN_BUTTON3 (26) // Joystick Down +#define PIN_BUTTON4 (27) // Joystick Left +#define PIN_BUTTON5 (28) // Joystick Right +#define PIN_BUTTON6 (29) // Joystick Press +#define PIN_BACK_BTN PIN_BUTTON1 +#define JOYSTICK_UP PIN_BUTTON2 +#define JOYSTICK_DOWN PIN_BUTTON3 +#define JOYSTICK_LEFT PIN_BUTTON4 +#define JOYSTICK_RIGHT PIN_BUTTON5 +#define JOYSTICK_PRESS PIN_BUTTON6 +#define PIN_USER_BTN PIN_BUTTON6 + +// Buzzer +// #define PIN_BUZZER (12) // Buzzer pin (defined per firmware type) + +#define VBAT_ENABLE (30) + +// Analog pins +#define PIN_VBAT_READ (16) +#define AREF_VOLTAGE (3.6F) +#define ADC_MULTIPLIER (2.0F) +#define ADC_RESOLUTION (12) + +// Serial interfaces +#define PIN_SERIAL1_RX (7) +#define PIN_SERIAL1_TX (6) + +// SPI Interfaces +#define SPI_INTERFACES_COUNT (2) + +#define PIN_SPI_MISO (9) +#define PIN_SPI_MOSI (10) +#define PIN_SPI_SCK (8) + +// BQ25616 single-wire charge status (Pro 1W) +#define PIN_BOOST_EN (31) // D31 / P0.13 鈥?Grove 5V Boost enable +#define EXT_CHRG_DETECT (32) // D32 / P1.15 鈥?BQ25616 STAT +#define EXT_CHRG_DETECT_VALUE LOW // 0 = charging, 1 = full / charger sleep +#define BOOST_EN_ACTIVE HIGH // HIGH enables Grove 5V Boost + +// Lora Pins +#define P_LORA_SCLK PIN_SPI_SCK +#define P_LORA_MISO PIN_SPI_MISO +#define P_LORA_MOSI PIN_SPI_MOSI +#define P_LORA_DIO_1 (1) +#define P_LORA_RESET (2) +#define P_LORA_BUSY (3) +#define P_LORA_NSS (4) +#define SX126X_RXEN (5) +#define SX126X_TXEN RADIOLIB_NC +#define SX126X_DIO2_AS_RF_SWITCH true +#define SX126X_DIO3_TCXO_VOLTAGE (1.8f) + +// LORA_PWR_EN (P0.14): external LDO enable for the SX1262 + 1 W PA on the Pro 1W board. +#define LORA_PWR_EN (33) +#define SX126X_POWER_EN LORA_PWR_EN + +// Wire Interfaces +#define WIRE_INTERFACES_COUNT (2) + +#define PIN_WIRE_SDA (14) +#define PIN_WIRE_SCL (15) +#define PIN_WIRE1_SDA (18) +#define PIN_WIRE1_SCL (17) +#define I2C_NO_RESCAN +#define DISPLAY_ADDRESS 0x3D // SH1106 OLED I2C address + +// GPS L76KB +#define GPS_BAUDRATE 9600 +#define PIN_GPS_TX PIN_SERIAL1_RX +#define PIN_GPS_RX PIN_SERIAL1_TX +#define PIN_GPS_STANDBY (0) +#define PIN_GPS_EN (PIN_GPS_STANDBY) + +// QSPI Pins +#define PIN_QSPI_SCK (19) +#define PIN_QSPI_CS (20) +#define PIN_QSPI_IO0 (21) +#define PIN_QSPI_IO1 (22) +#define PIN_QSPI_IO2 (23) +#define PIN_QSPI_IO3 (24) + +#define EXTERNAL_FLASH_DEVICES P25Q16H +#define EXTERNAL_FLASH_USE_QSPI + +// // EInk on SPI1 +// #define PIN_DISPLAY_CS (36) +// #define PIN_DISPLAY_BUSY (35) +// #define PIN_DISPLAY_DC (34) +// #define PIN_DISPLAY_RST (32) + +#define PIN_SPI1_MISO (37) +#define PIN_SPI1_MOSI (33) +#define PIN_SPI1_SCK (31) + +// GxEPD2 needs that for a panel that is not even used ! +extern const int MISO; +extern const int MOSI; +extern const int SCK; + +#endif \ No newline at end of file From b123971e21a4c21df0f62942046b37a1ddd4f56b Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Wed, 19 Aug 2026 18:59:24 +1200 Subject: [PATCH 144/381] fix for 3-byte paths passed to CMD_SEND_RAW_DATA --- examples/companion_radio/MyMesh.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 16603bc4..fdece482 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -1511,7 +1511,7 @@ void MyMesh::handleCmdFrame(size_t len) { #endif } else if (cmd_frame[0] == CMD_SEND_RAW_DATA && len >= 6) { int i = 1; - int8_t path_len = cmd_frame[i++]; + uint8_t path_len = cmd_frame[i++]; if (path_len >= 0 && mesh::Packet::isValidPathLen(path_len)) { uint8_t path[MAX_PATH_SIZE]; i += mesh::Packet::writePath(path, &cmd_frame[i], path_len); From cedc9977c25547bbeeaf5b8c2ffe617618a2dbfb Mon Sep 17 00:00:00 2001 From: Thomas Osterried <thomas@osterried.de> Date: Wed, 19 Aug 2026 09:35:25 +0200 Subject: [PATCH 145/381] Skip empty channel slots in searchChannelsByHash MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An unconfigured slot has an all-zero secret, so it matches null-key group traffic (a sender with an unset PSK). The zero-key MAC validates against the empty slot and the foreign message is delivered as if it belonged to that channel — every node with a free slot is a null-key sink. Skip empty slots. --- src/helpers/BaseChatMesh.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/helpers/BaseChatMesh.cpp b/src/helpers/BaseChatMesh.cpp index 972a97e9..616ee39b 100644 --- a/src/helpers/BaseChatMesh.cpp +++ b/src/helpers/BaseChatMesh.cpp @@ -368,6 +368,12 @@ void BaseChatMesh::handleReturnPathRetry(const ContactInfo& contact, const uint8 int BaseChatMesh::searchChannelsByHash(const uint8_t* hash, mesh::GroupChannel dest[], int max_matches) { int n = 0; for (int i = 0; i < MAX_GROUP_CHANNELS && n < max_matches; i++) { + // Skip empty/unconfigured slots. An empty slot has an all-zero secret and + // therefore matches null-key group traffic (a node transmitting with an + // unset PSK): the zero-key MAC validates against the empty slot and the + // foreign message is delivered as if it belonged to that channel. Any node + // with a free channel slot would otherwise act as a null-key sink. + if (channels[i].name[0] == 0) continue; if (channels[i].channel.hash[0] == hash[0]) { dest[n++] = channels[i].channel; } From 0c72b517e862f164e6c48c78a1eeb264ba25830e Mon Sep 17 00:00:00 2001 From: hansimgamr <77758818+hansimgamr@users.noreply.github.com> Date: Tue, 28 Jul 2026 12:06:43 -0400 Subject: [PATCH 146/381] Add charging indicator to companion_radio battery icon Show a small lightning-bolt icon to the left of the battery indicator on the ui-new home screen while the device is externally powered, and a plug icon once the battery reads full. The bolt/plug sits beside the battery so the fill bar stays clean and uninterrupted. When a buzzer is present, the mute icon shifts one slot further left so the two never overlap. Charging state is derived from board.isExternalPowered(), so this works on any board that reports external power (e.g. the nRF52 VBUS-detect path). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --- examples/companion_radio/ui-new/UITask.cpp | 14 ++++++++++++-- examples/companion_radio/ui-new/icons.h | 10 ++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index 59b58461..617f5e87 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -146,11 +146,21 @@ class HomeScreen : public UIScreen { int fillWidth = (batteryPercentage * (iconWidth - 4)) / 100; display.fillRect(iconX + 2, iconY + 2, fillWidth, iconHeight - 4); - // show muted icon if buzzer is muted + // while charging, show a bolt (or a plug once full) just left of the battery, + // keeping the fill bar itself clean and uninterrupted + bool charging = board.isExternalPowered(); + if (charging) { + const uint8_t* symbol = (batteryPercentage < 100) ? charging_icon : plug_icon; + display.setColor(UIColor::title_txt); + display.drawXbm(iconX - 9, iconY + 1, symbol, 8, 8); + } + + // show muted icon if buzzer is muted (shifted further left when the charging + // icon already occupies the slot immediately left of the battery) #ifdef PIN_BUZZER if (_task->isBuzzerQuiet()) { display.setColor(UIColor::warning_txt); - display.drawXbm(iconX - 9, iconY + 1, muted_icon, 8, 8); + display.drawXbm(iconX - (charging ? 18 : 9), iconY + 1, muted_icon, 8, 8); } #endif } diff --git a/examples/companion_radio/ui-new/icons.h b/examples/companion_radio/ui-new/icons.h index cbe23790..8d9ab175 100644 --- a/examples/companion_radio/ui-new/icons.h +++ b/examples/companion_radio/ui-new/icons.h @@ -119,4 +119,14 @@ static const uint8_t advert_icon[] = { static const uint8_t muted_icon[] = { 0x20, 0x6a, 0xea, 0xe4, 0xe4, 0xea, 0x6a, 0x20 +}; + +// small lightning bolt, 8x8px, shown next to the battery icon while charging +static const uint8_t charging_icon[] = { + 0x18, 0x30, 0x60, 0xFC, 0x18, 0x30, 0x60, 0xC0 +}; + +// small power plug, 8x8px, shown next to the battery icon once fully charged +static const uint8_t plug_icon[] = { + 0x24, 0x24, 0x7E, 0x7E, 0x7E, 0x3C, 0x18, 0x18 }; \ No newline at end of file From cdff1a5f4f58486c4494b3e69abe5d387ffa2577 Mon Sep 17 00:00:00 2001 From: hansimgamr <77758818+hansimgamr@users.noreply.github.com> Date: Tue, 28 Jul 2026 12:14:12 -0400 Subject: [PATCH 147/381] Show plug at >=95% instead of exactly 100% Boards without a charge-complete signal only infer "full" from voltage, and a real pack rarely reads the full BATT_MAX_MILLIVOLTS (4.2V), so the plug icon was effectively never shown. Treat "full" as a high band (>= 95%) so the plug appears when the battery is charged rather than requiring an exact 100%. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --- examples/companion_radio/ui-new/UITask.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index 617f5e87..55755ef1 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -150,7 +150,10 @@ class HomeScreen : public UIScreen { // keeping the fill bar itself clean and uninterrupted bool charging = board.isExternalPowered(); if (charging) { - const uint8_t* symbol = (batteryPercentage < 100) ? charging_icon : plug_icon; + // There's no charge-complete signal on most boards, so "full" is a high + // voltage band rather than an exact 100% (a real pack rarely reads 4.2V). + const int BATT_FULL_PCT = 95; + const uint8_t* symbol = (batteryPercentage >= BATT_FULL_PCT) ? plug_icon : charging_icon; display.setColor(UIColor::title_txt); display.drawXbm(iconX - 9, iconY + 1, symbol, 8, 8); } From 5eaf5a86fb22dfd52808d011a91ef836abc822e4 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Fri, 21 Aug 2026 20:55:57 +1000 Subject: [PATCH 148/381] * initial wiring/routing of CLI commands to companion (either via app/serial interface, or remotely via txt message) --- examples/companion_radio/MyMesh.cpp | 57 ++++++++++++++++++++++------ examples/companion_radio/MyMesh.h | 6 ++- examples/simple_secure_chat/main.cpp | 2 +- src/Utils.cpp | 9 +++++ src/Utils.h | 2 + src/helpers/BaseChatMesh.cpp | 43 +++++++++++++++------ src/helpers/BaseChatMesh.h | 2 +- src/helpers/ContactInfo.h | 6 +++ 8 files changed, 101 insertions(+), 26 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index fdece482..49c9f91b 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -62,6 +62,7 @@ #define CMD_SET_DEFAULT_FLOOD_SCOPE 63 #define CMD_GET_DEFAULT_FLOOD_SCOPE 64 #define CMD_SEND_RAW_PACKET 65 +#define CMD_RUN_CLI_COMMAND 66 // v14+ // Stats sub-types for CMD_GET_STATS #define STATS_TYPE_CORE 0 @@ -97,6 +98,7 @@ #define RESP_ALLOWED_REPEAT_FREQ 26 #define RESP_CODE_CHANNEL_DATA_RECV 27 #define RESP_CODE_DEFAULT_FLOOD_SCOPE 28 +#define RESP_CODE_CLI_REPLY 29 // v14+, a reply to CMD_RUN_CLI_COMMAND #define MAX_CHANNEL_DATA_LENGTH (MAX_FRAME_SIZE - 9) @@ -529,9 +531,13 @@ void MyMesh::onMessageRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t } void MyMesh::onCommandDataRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp, - const char *text) { + const char *text, char* reply) { markConnectionActive(from); // in case this is from a server, and we have a connection - queueMessage(from, TXT_TYPE_CLI_DATA, pkt, sender_timestamp, NULL, 0, text); + if (from.isRemoteCLIAllowed() && handleCommand(text, sender_timestamp, reply)) { + // CLI command was handled. Let BaseChatMesh handle the sending of the reply + } else { + queueMessage(from, TXT_TYPE_CLI_DATA, pkt, sender_timestamp, NULL, 0, text); + } } void MyMesh::onSignedMessageRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp, @@ -1082,6 +1088,21 @@ void MyMesh::handleCmdFrame(size_t len) { memcpy(&out_frame[i], _prefs.node_name, tlen); i += tlen; _serial->writeFrame(out_frame, i); + } else if (cmd_frame[0] == CMD_RUN_CLI_COMMAND && len >= 3) { // V14+ + int i = 1; + char *text = (char *)&cmd_frame[i]; + int tlen = len - i; + text[tlen] = 0; // ensure null + + reply_buf[0] = 0; + if (handleCommand(text, 0, reply_buf)) { + out_frame[0] = RESP_CODE_CLI_REPLY; + int rlen = strlen(reply_buf); + memcpy(&out_frame[1], reply_buf, rlen); + _serial->writeFrame(out_frame, 1 + rlen); + } else { + writeErrFrame(ERR_CODE_ILLEGAL_ARG); // unsupported command + } } else if (cmd_frame[0] == CMD_SEND_TXT_MSG && len >= 14) { int i = 1; uint8_t txt_type = cmd_frame[i++]; @@ -2031,6 +2052,25 @@ void MyMesh::enterCLIRescue() { Serial.println("========= CLI Rescue ========="); } +bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { + while (*command == ' ') command++; // skip leading spaces + + if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI) + memcpy(reply, command, 3); // reflect the prefix back + reply += 3; + *reply = 0; + command += 3; + } + + if (memcmp(command, "set pin ", 8) == 0) { + _prefs.ble_pin = atoi(&command[8]); + savePrefs(); + sprintf(reply, "> pin is now %06d", _prefs.ble_pin); + return true; + } + return false; // not handled +} + void MyMesh::checkCLIRescueCmd() { int len = strlen(cli_command); while (Serial.available() && len < sizeof(cli_command)-1) { @@ -2048,15 +2088,10 @@ void MyMesh::checkCLIRescueCmd() { if (len > 0 && cli_command[len - 1] == '\r') { // received complete line cli_command[len - 1] = 0; // replace newline with C string null terminator - if (memcmp(cli_command, "set ", 4) == 0) { - const char* config = &cli_command[4]; - if (memcmp(config, "pin ", 4) == 0) { - _prefs.ble_pin = atoi(&config[4]); - savePrefs(); - Serial.printf(" > pin is now %06d\n", _prefs.ble_pin); - } else { - Serial.printf(" Error: unknown config: %s\n", config); - } + reply_buf[0] = 0; + if (handleCommand(cli_command, 0, reply_buf)) { + // command was handled, print reply output + Serial.print(" "); Serial.print(reply_buf); Serial.println(); } else if (strcmp(cli_command, "rebuild") == 0) { bool success = _store->formatFileSystem(); if (success) { diff --git a/examples/companion_radio/MyMesh.h b/examples/companion_radio/MyMesh.h index 238adada..9c479c15 100644 --- a/examples/companion_radio/MyMesh.h +++ b/examples/companion_radio/MyMesh.h @@ -5,7 +5,7 @@ #include "AbstractUITask.h" /*------------ Frame Protocol --------------*/ -#define FIRMWARE_VER_CODE 13 +#define FIRMWARE_VER_CODE 14 #ifndef FIRMWARE_BUILD_DATE #define FIRMWARE_BUILD_DATE "14 Aug 2026" @@ -134,7 +134,7 @@ protected: void onMessageRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp, const char *text) override; void onCommandDataRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp, - const char *text) override; + const char *text, char* reply) override; void onSignedMessageRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp, const uint8_t *sender_prefix, const char *text) override; void onChannelMessageRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint32_t timestamp, @@ -201,6 +201,7 @@ private: } void checkCLIRescueCmd(); + bool handleCommand(const char* text, uint32_t sender_timestamp, char* reply); void checkSerialInterface(); bool isValidClientRepeatFreq(uint32_t f) const; @@ -225,6 +226,7 @@ private: bool _cli_rescue; bool send_unscoped; // force un-scoped flood (instead of using send_scope) char cli_command[80]; + char reply_buf[166]; uint8_t app_target_ver; uint8_t *sign_data; uint32_t sign_data_len; diff --git a/examples/simple_secure_chat/main.cpp b/examples/simple_secure_chat/main.cpp index da42ddcb..241fe1c2 100644 --- a/examples/simple_secure_chat/main.cpp +++ b/examples/simple_secure_chat/main.cpp @@ -240,7 +240,7 @@ protected: } } - void onCommandDataRecv(const ContactInfo& from, mesh::Packet* pkt, uint32_t sender_timestamp, const char *text) override { + void onCommandDataRecv(const ContactInfo& from, mesh::Packet* pkt, uint32_t sender_timestamp, const char *text, char* reply) override { } void onSignedMessageRecv(const ContactInfo& from, mesh::Packet* pkt, uint32_t sender_timestamp, const uint8_t *sender_prefix, const char *text) override { } diff --git a/src/Utils.cpp b/src/Utils.cpp index 5ae7f0e2..7a3fb78b 100644 --- a/src/Utils.cpp +++ b/src/Utils.cpp @@ -203,6 +203,15 @@ bool Utils::isHexChar(char c) { return c == '0' || hexVal(c) > 0; } +bool Utils::isZeroes(const uint8_t* buf, size_t len) { + while (len > 0) { + if (*buf != 0) return false; + buf++; + len--; + } + return true; +} + bool Utils::fromHex(uint8_t* dest, int dest_size, const char *src_hex) { int len = strlen(src_hex); if (len != dest_size*2) return false; // incorrect length diff --git a/src/Utils.h b/src/Utils.h index 5736b874..7a0f7b6e 100644 --- a/src/Utils.h +++ b/src/Utils.h @@ -82,6 +82,8 @@ public: static int parseTextParts(char* text, const char* parts[], int max_num, char separator=','); static bool isHexChar(char c); + + static bool isZeroes(const uint8_t* buf, size_t len); }; } diff --git a/src/helpers/BaseChatMesh.cpp b/src/helpers/BaseChatMesh.cpp index 616ee39b..bf8a861c 100644 --- a/src/helpers/BaseChatMesh.cpp +++ b/src/helpers/BaseChatMesh.cpp @@ -9,6 +9,8 @@ #define TXT_ACK_DELAY 200 #endif +#define CLI_REPLY_DELAY_MILLIS 600 + void BaseChatMesh::sendFloodScoped(const ContactInfo& recipient, mesh::Packet* pkt, uint32_t delay_millis) { sendFlood(pkt, delay_millis); } @@ -227,8 +229,8 @@ void BaseChatMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender ContactInfo& from = contacts[i]; if (type == PAYLOAD_TYPE_TXT_MSG && len > 5) { - uint32_t timestamp; - memcpy(×tamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong) + uint32_t sender_timestamp; + memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong) uint8_t flags = data[4] >> 2; // message attempt number, and other flags // len can be > original length, but 'text' will be padded with zeroes @@ -236,7 +238,7 @@ void BaseChatMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender if (flags == TXT_TYPE_PLAIN) { from.lastmod = getRTCClock()->getCurrentTime(); // update last heard time - onMessageRecv(from, packet, timestamp, (const char *) &data[5]); // let UI know + onMessageRecv(from, packet, sender_timestamp, (const char *) &data[5]); // let UI know int text_len = strlen((char *)&data[5]); uint8_t ack_hash[6]; // calc truncated hash of the message timestamp + text + sender pub_key, to prove to sender that we got it @@ -254,20 +256,39 @@ void BaseChatMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender sendAckTo(from, ack_hash, 6); } } else if (flags == TXT_TYPE_CLI_DATA) { - onCommandDataRecv(from, packet, timestamp, (const char *) &data[5]); // let UI know + uint8_t temp[166]; + char *command = (char *)&data[5]; + char *reply = (char *)&temp[5]; + *reply = 0; + + onCommandDataRecv(from, packet, sender_timestamp, command, reply); // let UI know // NOTE: no ack expected for CLI_DATA replies - if (packet->isRouteFlood()) { - // let this sender know path TO here, so they can use sendDirect() (NOTE: no ACK as extra) - mesh::Packet* path = createPathReturn(from.id, secret, packet->path, packet->path_len, 0, NULL, 0); - if (path) sendFloodScoped(from, path); + int text_len = strlen(reply); + if (text_len > 0) { + uint32_t timestamp = getRTCClock()->getCurrentTimeUnique(); + if (timestamp == sender_timestamp) { + // WORKAROUND: the two timestamps need to be different, in the CLI view + timestamp++; + } + memcpy(temp, ×tamp, 4); + temp[4] = (TXT_TYPE_CLI_DATA << 2); + + auto reply_pkt = createDatagram(PAYLOAD_TYPE_TXT_MSG, from.id, secret, temp, 5 + text_len); + if (reply_pkt) { + if (from.out_path_len == OUT_PATH_UNKNOWN) { + sendFloodScoped(from, reply_pkt, CLI_REPLY_DELAY_MILLIS); + } else { + sendDirect(reply_pkt, from.out_path, from.out_path_len, CLI_REPLY_DELAY_MILLIS); + } + } } } else if (flags == TXT_TYPE_SIGNED_PLAIN) { - if (timestamp > from.sync_since) { // make sure 'sync_since' is up-to-date - from.sync_since = timestamp; + if (sender_timestamp > from.sync_since) { // make sure 'sync_since' is up-to-date + from.sync_since = sender_timestamp; } from.lastmod = getRTCClock()->getCurrentTime(); // update last heard time - onSignedMessageRecv(from, packet, timestamp, &data[5], (const char *) &data[9]); // let UI know + onSignedMessageRecv(from, packet, sender_timestamp, &data[5], (const char *) &data[9]); // let UI know uint32_t ack_hash; // calc truncated hash of the message timestamp + text + OUR pub_key, to prove to sender that we got it mesh::Utils::sha256((uint8_t *) &ack_hash, 4, data, 9 + strlen((char *)&data[9]), self_id.pub_key, PUB_KEY_SIZE); diff --git a/src/helpers/BaseChatMesh.h b/src/helpers/BaseChatMesh.h index d9878547..331d1041 100644 --- a/src/helpers/BaseChatMesh.h +++ b/src/helpers/BaseChatMesh.h @@ -113,7 +113,7 @@ protected: virtual void onContactPathUpdated(const ContactInfo& contact) = 0; virtual bool onContactPathRecv(ContactInfo& from, uint8_t* in_path, uint8_t in_path_len, uint8_t* out_path, uint8_t out_path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len); virtual void onMessageRecv(const ContactInfo& contact, mesh::Packet* pkt, uint32_t sender_timestamp, const char *text) = 0; - virtual void onCommandDataRecv(const ContactInfo& contact, mesh::Packet* pkt, uint32_t sender_timestamp, const char *text) = 0; + virtual void onCommandDataRecv(const ContactInfo& contact, mesh::Packet* pkt, uint32_t sender_timestamp, const char *text, char* reply) = 0; virtual void onSignedMessageRecv(const ContactInfo& contact, mesh::Packet* pkt, uint32_t sender_timestamp, const uint8_t *sender_prefix, const char *text) = 0; virtual uint32_t calcFloodTimeoutMillisFor(uint32_t pkt_airtime_millis) const = 0; virtual uint32_t calcDirectTimeoutMillisFor(uint32_t pkt_airtime_millis, uint8_t path_len) const = 0; diff --git a/src/helpers/ContactInfo.h b/src/helpers/ContactInfo.h index ede977ca..5a156c82 100644 --- a/src/helpers/ContactInfo.h +++ b/src/helpers/ContactInfo.h @@ -26,6 +26,12 @@ struct ContactInfo { return shared_secret; } + bool isFav() const { return flags & 0x01; } + bool isTelemBaseAllowed() const { return flags & 0x02; } + bool isTelemLocAllowed() const { return flags & 0x04; } + bool isTelemEnvAllowed() const { return flags & 0x08; } + bool isRemoteCLIAllowed() const { return flags & 0x10; } + private: mutable uint8_t shared_secret[PUB_KEY_SIZE]; }; From 93bd279d343aeff3828282c648fa87e965b84b30 Mon Sep 17 00:00:00 2001 From: entr0p1 <1475255+entr0p1@users.noreply.github.com> Date: Mon, 17 Aug 2026 23:01:52 +1000 Subject: [PATCH 149/381] Duplicate MAX_CLIENTS definition MAX_CLIENTS is defined in both src/helpers/ClientACL.h and examples/simple_repeater/MyMesh.h. Appears it was centralised in the former header file some time ago. Both are included in some places and, depending on which order they're in, either value can win. This change drops the duplicate entry from the repeater firmware and bumps the central limit up to 32 (per the original repeater firmware value). Changes: - Remove MAX_CLIENTS from repeater MyMesh.h - Increase MAX_CLIENTS limit in ClientACL.h to 32 --- examples/simple_repeater/MyMesh.h | 4 ---- src/helpers/ClientACL.h | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index 04bd4fb9..cac6c4a2 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -59,10 +59,6 @@ struct RepeaterStats { uint32_t n_recv_errors; }; -#ifndef MAX_CLIENTS - #define MAX_CLIENTS 32 -#endif - struct NeighbourInfo { mesh::Identity id; uint32_t advert_timestamp; diff --git a/src/helpers/ClientACL.h b/src/helpers/ClientACL.h index b758f706..e0654464 100644 --- a/src/helpers/ClientACL.h +++ b/src/helpers/ClientACL.h @@ -34,7 +34,7 @@ struct ClientInfo { }; #ifndef MAX_CLIENTS - #define MAX_CLIENTS 20 + #define MAX_CLIENTS 32 #endif class ClientACL { From 2678be75bd6824d31971ce7c3a4c1cf7896a81da Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Thu, 20 Aug 2026 21:17:17 -0400 Subject: [PATCH 150/381] ui: repeater discover screen --- examples/companion_radio/MyMesh.cpp | 50 ++++++++++++++++++++ examples/companion_radio/MyMesh.h | 18 ++++++++ examples/companion_radio/ui-new/UITask.cpp | 53 +++++++++++++++++++++- 3 files changed, 120 insertions(+), 1 deletion(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index fdece482..01512b16 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -134,6 +134,10 @@ #define ERR_CODE_FILE_IO_ERROR 5 #define ERR_CODE_ILLEGAL_ARG 6 +// Copied from simple_repeater (could probably be shared) +#define CTL_TYPE_NODE_DISCOVER_REQ 0x80 +#define CTL_TYPE_NODE_DISCOVER_RESP 0x90 + #define MAX_SIGN_DATA_LEN (8 * 1024) // 8K // Auto-add config bitmask @@ -403,6 +407,51 @@ int MyMesh::getRecentlyHeard(AdvertPath dest[], int max_num) { return max_num; } +int MyMesh::getDiscoveredNodes(DiscoveredNode nodes[], int max_num) { + if (max_num > DISCOVERED_NODES_TABLE_SIZE) max_num = DISCOVERED_NODES_TABLE_SIZE; + if (max_num > disc_nodes_count) max_num = disc_nodes_count; + + for (int i = 0; i < max_num; i++) { + nodes[i] = discovered_nodes[i]; + } + return max_num; +} + +bool MyMesh::requestRepeatersDiscovery() { + uint8_t cmd_bytes[6]; + cmd_bytes[0] = CTL_TYPE_NODE_DISCOVER_REQ | 1; // DISCOVER_REQ | prefix only + cmd_bytes[1] = 0xFF; // Repeaters + getRNG()->random(&cmd_bytes[2], 4); // tag + disc_nodes_count = 0; + disc_node_req_tag = *((uint32_t*)&cmd_bytes[2]); + mesh::Packet* req = createControlData(cmd_bytes, sizeof(cmd_bytes)); + if (req) { + sendZeroHop(req); + return true; + } + return false; +} + +void MyMesh::checkControlDataForPendingDiscovery(uint8_t payload[], size_t p_len) { + if ((p_len < 12) + || (payload[0] & 0xF0 != CTL_TYPE_NODE_DISCOVER_RESP) + || (disc_nodes_count >= DISCOVERED_NODES_TABLE_SIZE) + || (memcmp(&payload[2], &disc_node_req_tag, 4))) { + return; + } + memcpy(&discovered_nodes[disc_nodes_count].pubkey_prefix, &payload[6], 8); + discovered_nodes[disc_nodes_count].type = payload[0] & 0xF; + discovered_nodes[disc_nodes_count].snr_out = ((int8_t)payload[1]) / 4.0; + discovered_nodes[disc_nodes_count].snr_in = _radio->getLastSNR(); + ContactInfo* c = lookupContactByPubKey(&payload[6], 8); + if (c != NULL) { + strncpy(discovered_nodes[disc_nodes_count].name, c->name, 32); + } else { + discovered_nodes[disc_nodes_count].name[0] = 0; + } + disc_nodes_count ++; +} + void MyMesh::onContactPathUpdated(const ContactInfo &contact) { out_frame[0] = PUSH_CODE_PATH_UPDATED; memcpy(&out_frame[1], contact.id.pub_key, PUB_KEY_SIZE); @@ -783,6 +832,7 @@ void MyMesh::onControlDataRecv(mesh::Packet *packet) { MESH_DEBUG_PRINTLN("onControlDataRecv(), payload_len too long: %d", packet->payload_len); return; } + checkControlDataForPendingDiscovery(packet->payload, packet->payload_len); int i = 0; out_frame[i++] = PUSH_CODE_CONTROL_DATA; out_frame[i++] = (int8_t)(_radio->getLastSNR() * 4); diff --git a/examples/companion_radio/MyMesh.h b/examples/companion_radio/MyMesh.h index 238adada..848d21c0 100644 --- a/examples/companion_radio/MyMesh.h +++ b/examples/companion_radio/MyMesh.h @@ -84,6 +84,14 @@ struct AdvertPath { uint8_t path[MAX_PATH_SIZE]; }; +struct DiscoveredNode { + uint8_t pubkey_prefix[9]; + float snr_in; + float snr_out; + char name[32]; + uint8_t type; +}; + class MyMesh : public BaseChatMesh, public DataStoreHost { public: MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMeshTables &tables, DataStore& store, AbstractUITask* ui=NULL); @@ -102,6 +110,9 @@ public: int getRecentlyHeard(AdvertPath dest[], int max_num); + bool requestRepeatersDiscovery(); + int getDiscoveredNodes(DiscoveredNode nodes[], int max_num); + protected: float getAirtimeBudgetFactor() const override; int getInterferenceThreshold() const override; @@ -256,6 +267,13 @@ private: #define ADVERT_PATH_TABLE_SIZE 16 AdvertPath advert_paths[ADVERT_PATH_TABLE_SIZE]; // circular table + + #define DISCOVERED_NODES_TABLE_SIZE 10 + DiscoveredNode discovered_nodes[DISCOVERED_NODES_TABLE_SIZE]; // not circular, latest discovered nodes are not kept + uint32_t disc_node_req_tag = 0; + uint32_t disc_nodes_count = 0; + + void checkControlDataForPendingDiscovery(uint8_t payload[], size_t p_len); }; extern MyMesh the_mesh; diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index 55755ef1..35525028 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -24,6 +24,7 @@ #define LONG_PRESS_MILLIS 1200 +// Used both for recent adverts and discovered nodes #ifndef UI_RECENT_LIST_SIZE #define UI_RECENT_LIST_SIZE 4 #endif @@ -102,6 +103,7 @@ class HomeScreen : public UIScreen { #if UI_SENSORS_PAGE == 1 SENSORS, #endif + DISCOVERY, SHUTDOWN, Count // keep as last }; @@ -113,7 +115,9 @@ class HomeScreen : public UIScreen { uint8_t _page; bool _shutdown_init; AdvertPath recent[UI_RECENT_LIST_SIZE]; - + DiscoveredNode discovered[UI_RECENT_LIST_SIZE]; + uint32_t discovery_req_time = 0; + bool discovery_disp_names = true; // by default desplay names if available (removes SNR_O) void renderBatteryIndicator(DisplayDriver& display, uint16_t batteryMilliVolts) { // Convert millivolts to percentage @@ -459,6 +463,39 @@ public: if (sensors_scroll) sensors_scroll_offset = (sensors_scroll_offset+1)%sensors_nb; else sensors_scroll_offset = 0; #endif + } else if (_page == HomePage::DISCOVERY) { + int count = the_mesh.getDiscoveredNodes(discovered, UI_RECENT_LIST_SIZE); + display.setColor(UIColor::primary_txt); + int y = 20; + for (int i = 0; i < count; i++, y += 11) { + char name[32]; + auto a = &discovered[i]; + if ((a->name[0] == 0) || !discovery_disp_names) { + mesh::Utils::toHex(name, a->pubkey_prefix, 4); + } else { + strncpy(name, a->name, 32); + } + char filtered_name[sizeof(name)]; + char snr_s[12]; + if (strlen(name) <= 8) { // display snr_o + sprintf(snr_s, "%02.1f>%02.1f", a->snr_out, a->snr_in); + } else { + sprintf(snr_s, "%02.1f", a->snr_in); + } + int snr_width = display.getTextWidth(snr_s); + int max_name_width = display.width() - snr_width - 1; + display.translateUTF8ToBlocks(filtered_name, name, sizeof(filtered_name)); + display.drawTextEllipsized(0, y, max_name_width, filtered_name); + display.setCursor(display.width() - snr_width - 1, y); + display.print(snr_s); + } + if (millis() < discovery_req_time + 5000) { + return 1000; // more frequent updates just after req + } else if (count < UI_RECENT_LIST_SIZE -1) { // show only 5 sec after last disc + y = 10 + 11 * UI_RECENT_LIST_SIZE; + display.drawTextCentered(display.width() / 2, y, "discover: " PRESS_LABEL); + } + } else if (_page == HomePage::SHUTDOWN) { display.setColor(UIColor::corp_blue); display.setTextSize(1); @@ -484,6 +521,9 @@ public: if (_page == HomePage::RECENT) { _task->showAlert("Recent adverts", 800); } + if (_page == HomePage::DISCOVERY) { + _task->showAlert("Repeater disc", 800); + } return true; } if (c == KEY_ENTER && _page == HomePage::BLUETOOTH) { @@ -516,6 +556,17 @@ public: return true; } #endif + if (c == KEY_ENTER && _page == HomePage::DISCOVERY) { + if (millis() > discovery_req_time + 5000) { // rate limiter + the_mesh.requestRepeatersDiscovery(); + discovery_req_time = millis(); + } + return true; + } + if (c == KEY_SELECT && _page == HomePage::DISCOVERY) { + discovery_disp_names = !discovery_disp_names; + return true; + } if (c == KEY_ENTER && _page == HomePage::SHUTDOWN) { _shutdown_init = true; // need to wait for button to be released return true; From f58c7293e2db77144e7ad7ab64e3132a798ebafb Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Sat, 22 Aug 2026 16:16:32 +1200 Subject: [PATCH 151/381] add support for rak12500 and rak12501 gps on rak3401 --- variants/rak3401/platformio.ini | 1 + variants/rak3401/variant.h | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/variants/rak3401/platformio.ini b/variants/rak3401/platformio.ini index 48e71922..c285e3ec 100644 --- a/variants/rak3401/platformio.ini +++ b/variants/rak3401/platformio.ini @@ -6,6 +6,7 @@ build_flags = ${nrf52_base.build_flags} ${sensor_base.build_flags} -I variants/rak3401 -D RAK_3401 + -D RAK_BOARD -D NRF52_POWER_MANAGEMENT -D RADIO_CLASS=CustomSX1262 -D WRAPPER_CLASS=CustomSX1262Wrapper diff --git a/variants/rak3401/variant.h b/variants/rak3401/variant.h index 98827886..e0c24759 100644 --- a/variants/rak3401/variant.h +++ b/variants/rak3401/variant.h @@ -188,8 +188,8 @@ static const uint8_t AREF = PIN_AREF; // Power is on the controllable 3V3_S rail #define PIN_GPS_PPS (17) // Pulse per second input from the GPS -#define PIN_GPS_RX PIN_SERIAL1_RX -#define PIN_GPS_TX PIN_SERIAL1_TX +#define PIN_GPS_TX PIN_SERIAL1_RX +#define PIN_GPS_RX PIN_SERIAL1_TX #define PIN_GPS_1PPS PIN_GPS_PPS #define GPS_BAUD_RATE 9600 From 1266fc058f4e8baf36929e7fa4f87c3eb413cf41 Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Sun, 23 Aug 2026 14:14:45 +1200 Subject: [PATCH 152/381] don't toggle io pins on rak3401 when probing gps --- src/helpers/sensors/EnvironmentSensorManager.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/helpers/sensors/EnvironmentSensorManager.cpp b/src/helpers/sensors/EnvironmentSensorManager.cpp index 54305692..6f460775 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.cpp +++ b/src/helpers/sensors/EnvironmentSensorManager.cpp @@ -831,11 +831,15 @@ bool EnvironmentSensorManager::gpsIsAwake(uint8_t ioPin){ } #endif + #ifndef RAK_3401 //set initial waking state pinMode(ioPin,OUTPUT); digitalWrite(ioPin,LOW); delay(500); digitalWrite(ioPin,HIGH); + #endif + + // give gps time to power up delay(500); //Try to init RAK12500 on I2C @@ -871,7 +875,9 @@ bool EnvironmentSensorManager::gpsIsAwake(uint8_t ioPin){ return true; } + #ifndef RAK_3401 pinMode(ioPin, INPUT); + #endif MESH_DEBUG_PRINTLN("GPS did not init with this IO pin... try the next"); return false; } @@ -880,8 +886,10 @@ bool EnvironmentSensorManager::gpsIsAwake(uint8_t ioPin){ void EnvironmentSensorManager::start_gps() { gps_active = true; #ifdef RAK_WISBLOCK_GPS + #ifndef RAK_3401 pinMode(gpsResetPin, OUTPUT); digitalWrite(gpsResetPin, HIGH); + #endif return; #endif @@ -896,8 +904,10 @@ void EnvironmentSensorManager::start_gps() { void EnvironmentSensorManager::stop_gps() { gps_active = false; #ifdef RAK_WISBLOCK_GPS + #ifndef RAK_3401 // rak3401 shouldn't turn off WB_IO2 as it powers the PA pinMode(gpsResetPin, OUTPUT); digitalWrite(gpsResetPin, LOW); + #endif return; #endif From 414e91fd5d4a7e5acd9a2654a14348f2fa061b94 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Sun, 23 Aug 2026 14:45:15 +1000 Subject: [PATCH 153/381] * adding new CommonRadioPrefs * refactor: moving various radio CLI handling to CommonRadioPrefs --- examples/companion_radio/MyMesh.cpp | 26 +++++++++++++ examples/companion_radio/MyMesh.h | 1 + examples/companion_radio/NodePrefs.h | 18 ++++++++- src/helpers/AdvertDataHelpers.cpp | 8 ++++ src/helpers/AdvertDataHelpers.h | 2 + src/helpers/CommonCLI.cpp | 51 +++++-------------------- src/helpers/CommonCLI.h | 17 ++++++++- src/helpers/CommonRadioPrefs.cpp | 56 ++++++++++++++++++++++++++++ src/helpers/CommonRadioPrefs.h | 45 ++++++++++++++++++++++ 9 files changed, 180 insertions(+), 44 deletions(-) create mode 100644 src/helpers/CommonRadioPrefs.cpp create mode 100644 src/helpers/CommonRadioPrefs.h diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 49c9f91b..54be91c7 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2062,12 +2062,38 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* command += 3; } + if (_prefs.getRadioPrefs()->handleCommand(command, sender_timestamp, reply)) { // is radio CLI command? + if (_prefs.getRadioPrefs()->isDirty()) { savePrefs(); } + return true; + } + + if (memcmp(command, "set name ", 9) == 0) { + if (AdvertDataParser::isValidName(&command[9])) { + StrHelper::strncpy(_prefs.node_name, &command[9], sizeof(_prefs.node_name)); + savePrefs(); + strcpy(reply, "OK"); + } else { + strcpy(reply, "Error, bad chars"); + } + return true; + } + if (strcmp(command, "get name") == 0) { + sprintf(reply, "> %s", _prefs.node_name); + return true; + } + if (memcmp(command, "set pin ", 8) == 0) { _prefs.ble_pin = atoi(&command[8]); savePrefs(); sprintf(reply, "> pin is now %06d", _prefs.ble_pin); return true; } + + if (strcmp(command, "ver") == 0) { + sprintf(reply, "%s (Build: %s)", FIRMWARE_VERSION, FIRMWARE_BUILD_DATE); + return true; + } + return false; // not handled } diff --git a/examples/companion_radio/MyMesh.h b/examples/companion_radio/MyMesh.h index 9c479c15..b60030a6 100644 --- a/examples/companion_radio/MyMesh.h +++ b/examples/companion_radio/MyMesh.h @@ -169,6 +169,7 @@ public: _prefs.node_lat = sensors.node_lat; _prefs.node_lon = sensors.node_lon; _store->savePrefs(_prefs); + _prefs.clearDirty(); } #if ENV_INCLUDE_GPS == 1 diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index 21766de8..36788052 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -1,6 +1,7 @@ #pragma once #include <cstdint> // For uint8_t, uint32_t #include <helpers/ConfigSerializer.h> +#include <helpers/CommonRadioPrefs.h> #define TELEM_MODE_DENY 0 #define TELEM_MODE_ALLOW_FLAGS 1 // use contact.flags @@ -42,7 +43,7 @@ public: uint8_t default_scope_key[16]; private: - class RadioPrefs : public ConfigSerializer { // COPIED from CommonCLI (for now) + class RadioPrefs : public CommonRadioPrefs { NodePrefs* _parent; protected: void structure() override { @@ -70,6 +71,18 @@ private: } public: RadioPrefs(NodePrefs* parent) : _parent(parent) { } + + // CommonRadioPrefs interface + float getFreq() const override { return _parent->freq; } + void setFreq(float f) override { _parent->freq = f; markDirty(); } + float getBandwidth() const override { return _parent->bw; } + void setBandwidth(float bw) override { _parent->bw = bw; markDirty(); } + uint8_t getSpreadFactor() const override { return _parent->sf; } + void setSpreadFactor(uint8_t sf) { _parent->sf; markDirty(); } + uint8_t getCodingRate() const override { return _parent->cr; } + void setCodingRate(uint8_t cr) { _parent->cr = cr; markDirty(); } + float getAirtimeFactor() const override { return _parent->airtime_factor; } + void setAirtimeFactor(float af) override { _parent->airtime_factor = af; markDirty(); } }; RadioPrefs radio; @@ -142,4 +155,7 @@ public: // new accessor methods bool isRepeatEn() const { return repeat.disable_fwd == 0; } void setRepeatEn(bool en) { repeat.disable_fwd = en ? 0 : 1; } + + CommonRadioPrefs* getRadioPrefs() { return &radio; } + void clearDirty() { radio.clearDirty(); } }; diff --git a/src/helpers/AdvertDataHelpers.cpp b/src/helpers/AdvertDataHelpers.cpp index 998733ae..25e5cd3f 100644 --- a/src/helpers/AdvertDataHelpers.cpp +++ b/src/helpers/AdvertDataHelpers.cpp @@ -28,6 +28,14 @@ return i; } +bool AdvertDataParser::isValidName(const char *n) { + while (*n) { + if (*n == '[' || *n == ']' || *n == '\\' || *n == ':' || *n == ',' || *n == '?' || *n == '*') return false; + n++; + } + return true; +} + AdvertDataParser::AdvertDataParser(const uint8_t app_data[], uint8_t app_data_len) { _name[0] = 0; _lat = _lon = 0; diff --git a/src/helpers/AdvertDataHelpers.h b/src/helpers/AdvertDataHelpers.h index abe14cbd..f4e109e9 100644 --- a/src/helpers/AdvertDataHelpers.h +++ b/src/helpers/AdvertDataHelpers.h @@ -50,6 +50,8 @@ class AdvertDataParser { public: AdvertDataParser(const uint8_t app_data[], uint8_t app_data_len); + static bool isValidName(const char* name); + bool isValid() const { return _valid; } uint8_t getType() const { return _flags & 0x0F; } uint16_t getFeat1() const { return _extra1; } diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index b318bb58..4e7af30b 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -164,6 +164,7 @@ void CommonCLI::savePrefs() { _prefs->advert_interval = 0; // turn it off, now that device has been manually configured } _callbacks->savePrefs(); + _prefs->clearDirty(); } uint8_t CommonCLI::buildAdvertData(uint8_t node_type, uint8_t* app_data) { @@ -180,6 +181,11 @@ uint8_t CommonCLI::buildAdvertData(uint8_t node_type, uint8_t* app_data) { } void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* reply) { + if (_prefs->getRadioPrefs()->handleCommand(command, sender_timestamp, reply)) { // is a radio CLI command? + if (_prefs->getRadioPrefs()->isDirty()) { savePrefs(); } + return; + } + if (memcmp(command, "poweroff", 8) == 0 || memcmp(command, "shutdown", 8) == 0) { _board->powerOff(); // doesn't return } else if (memcmp(command, "reboot", 6) == 0) { @@ -447,19 +453,8 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* reply) { const char* config = &command[4]; - if (memcmp(config, "dutycycle ", 10) == 0) { - float dc = atof(&config[10]); - if (dc < 1 || dc > 100) { - strcpy(reply, "ERROR: dutycycle must be 1-100"); - } else { - _prefs->airtime_factor = (100.0f / dc) - 1.0f; - savePrefs(); - float actual = 100.0f / (_prefs->airtime_factor + 1.0f); - int a_int = (int)actual; - int a_frac = (int)((actual - a_int) * 10.0f + 0.5f); - sprintf(reply, "OK - %d.%d%%", a_int, a_frac); - } - } else if (memcmp(config, "af ", 3) == 0) { + + if (memcmp(config, "af ", 3) == 0) { _prefs->airtime_factor = atof(&config[3]); savePrefs(); strcpy(reply, "OK"); @@ -585,24 +580,6 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep } else { strcpy(reply, "Error: state must be on or off"); } - } else if (memcmp(config, "radio ", 6) == 0) { - strcpy(tmp, &config[6]); - const char *parts[4]; - int num = mesh::Utils::parseTextParts(tmp, parts, 4); - float freq = num > 0 ? strtof(parts[0], nullptr) : 0.0f; - float bw = num > 1 ? strtof(parts[1], nullptr) : 0.0f; - uint8_t sf = num > 2 ? atoi(parts[2]) : 0; - uint8_t cr = num > 3 ? atoi(parts[3]) : 0; - if (freq >= 150.0f && freq <= 2500.0f && sf >= 5 && sf <= 12 && cr >= 5 && cr <= 8 && bw >= 7.0f && bw <= 500.0f) { - _prefs->sf = sf; - _prefs->cr = cr; - _prefs->freq = freq; - _prefs->bw = bw; - _callbacks->savePrefs(); - strcpy(reply, "OK - reboot to apply"); - } else { - strcpy(reply, "Error, invalid radio params"); - } } else if (memcmp(config, "lat ", 4) == 0) { _prefs->node_lat = atof(&config[4]); savePrefs(); @@ -806,12 +783,7 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* reply) { const char* config = &command[4]; - if (memcmp(config, "dutycycle", 9) == 0) { - float dc = 100.0f / (_prefs->airtime_factor + 1.0f); - int dc_int = (int)dc; - int dc_frac = (int)((dc - dc_int) * 10.0f + 0.5f); - sprintf(reply, "> %d.%d%%", dc_int, dc_frac); - } else if (memcmp(config, "af", 2) == 0) { + if (memcmp(config, "af", 2) == 0) { sprintf(reply, "> %s", StrHelper::ftoa(_prefs->airtime_factor)); } else if (memcmp(config, "int.thresh", 10) == 0) { sprintf(reply, "> %d", (uint32_t) _prefs->interference_threshold); @@ -856,11 +828,6 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep } else { sprintf(reply, "> %s", _board->isLoRaFemPaGainEnabled() ? "on" : "off"); } - } else if (memcmp(config, "radio", 5) == 0) { - char freq[16], bw[16]; - strcpy(freq, StrHelper::ftoa(_prefs->freq)); - strcpy(bw, StrHelper::ftoa3(_prefs->bw)); - sprintf(reply, "> %s,%s,%d,%d", freq, bw, (uint32_t)_prefs->sf, (uint32_t)_prefs->cr); } else if (memcmp(config, "rxdelay", 7) == 0) { sprintf(reply, "> %s", StrHelper::ftoa(_prefs->rx_delay_base)); } else if (memcmp(config, "txdelay", 7) == 0) { diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 237c758e..9d3caf39 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -6,6 +6,7 @@ #include <helpers/ClientACL.h> #include <helpers/RegionMap.h> #include <helpers/ConfigSerializer.h> +#include <helpers/CommonRadioPrefs.h> #if defined(WITH_RS232_BRIDGE) || defined(WITH_ESPNOW_BRIDGE) #define WITH_BRIDGE @@ -72,7 +73,7 @@ public: uint8_t extra_sf[4]; private: - class RadioPrefs : public ConfigSerializer { + class RadioPrefs : public CommonRadioPrefs { NodePrefs* _parent; protected: void structure() override { @@ -96,6 +97,17 @@ private: } public: RadioPrefs(NodePrefs* parent) : _parent(parent) { } + // CommonRadioPrefs interface + float getFreq() const override { return _parent->freq; } + void setFreq(float f) override { _parent->freq = f; markDirty(); } + float getBandwidth() const override { return _parent->bw; } + void setBandwidth(float bw) override { _parent->bw = bw; markDirty(); } + uint8_t getSpreadFactor() const override { return _parent->sf; } + void setSpreadFactor(uint8_t sf) { _parent->sf; markDirty(); } + uint8_t getCodingRate() const override { return _parent->cr; } + void setCodingRate(uint8_t cr) { _parent->cr = cr; markDirty(); } + float getAirtimeFactor() const override { return _parent->airtime_factor; } + void setAirtimeFactor(float af) override { _parent->airtime_factor = af; markDirty(); } }; RadioPrefs radio; @@ -192,6 +204,9 @@ public: bridge_secret[0] = 0; owner_info[0] = 0; } + + CommonRadioPrefs* getRadioPrefs() { return &radio; } + void clearDirty() { radio.clearDirty(); } }; class CommonCLICallbacks { diff --git a/src/helpers/CommonRadioPrefs.cpp b/src/helpers/CommonRadioPrefs.cpp new file mode 100644 index 00000000..ed198c61 --- /dev/null +++ b/src/helpers/CommonRadioPrefs.cpp @@ -0,0 +1,56 @@ +#include "CommonRadioPrefs.h" +#include "TxtDataHelpers.h" +#include "Utils.h" + +bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { + if (strcmp(command, "get radio") == 0) { + char freq[16], bw[16]; + strcpy(freq, StrHelper::ftoa(getFreq())); + strcpy(bw, StrHelper::ftoa3(getBandwidth())); + sprintf(reply, "> %s,%s,%d,%d", freq, bw, (uint32_t)getSpreadFactor(), (uint32_t)getCodingRate()); + return true; + } + if (memcmp(command, "set radio ", 10) == 0) { + char tmp[132]; + strcpy(tmp, &command[10]); + const char *parts[4]; + int num = mesh::Utils::parseTextParts(tmp, parts, 4); + float freq = num > 0 ? strtof(parts[0], nullptr) : 0.0f; + float bw = num > 1 ? strtof(parts[1], nullptr) : 0.0f; + uint8_t sf = num > 2 ? atoi(parts[2]) : 0; + uint8_t cr = num > 3 ? atoi(parts[3]) : 0; + if (freq >= 150.0f && freq <= 2500.0f && sf >= 5 && sf <= 12 && cr >= 5 && cr <= 8 && bw >= 7.0f && bw <= 500.0f) { + setSpreadFactor(sf); + setCodingRate(cr); + setFreq(freq); + setBandwidth(bw); + // NOTE: savePrefs() should be handled by caller + strcpy(reply, "OK - reboot to apply"); + } else { + strcpy(reply, "Error, invalid radio params"); + } + return true; + } + if (strcmp(command, "get dutycycle") == 0) { + float dc = 100.0f / (getAirtimeFactor() + 1.0f); + int dc_int = (int)dc; + int dc_frac = (int)((dc - dc_int) * 10.0f + 0.5f); + sprintf(reply, "> %d.%d%%", dc_int, dc_frac); + return true; + } + if (memcmp(command, "set dutycycle ", 14) == 0) { + float dc = atof(&command[14]); + if (dc < 1 || dc > 100) { + strcpy(reply, "ERROR: dutycycle must be 1-100"); + } else { + setAirtimeFactor((100.0f / dc) - 1.0f); + // NOTE: savePrefs() should be handled by caller + float actual = 100.0f / (getAirtimeFactor() + 1.0f); + int a_int = (int)actual; + int a_frac = (int)((actual - a_int) * 10.0f + 0.5f); + sprintf(reply, "OK - %d.%d%%", a_int, a_frac); + } + return true; + } + return false; // not handled +} diff --git a/src/helpers/CommonRadioPrefs.h b/src/helpers/CommonRadioPrefs.h new file mode 100644 index 00000000..eaec2c0a --- /dev/null +++ b/src/helpers/CommonRadioPrefs.h @@ -0,0 +1,45 @@ +#include "ConfigSerializer.h" + +class CommonRadioPrefs : public ConfigSerializer { + bool _is_dirty = false; +protected: + CommonRadioPrefs() { } +public: + void markDirty() { _is_dirty = true; } + void clearDirty() { _is_dirty = false; } + bool isDirty() const { return _is_dirty; } + + virtual float getFreq() const = 0; + virtual void setFreq(float f) = 0; + + virtual float getBandwidth() const = 0; + virtual void setBandwidth(float bw) = 0; + + virtual uint8_t getSpreadFactor() const = 0; + virtual void setSpreadFactor(uint8_t sf) = 0; + + virtual uint8_t getCodingRate() const = 0; + virtual void setCodingRate(uint8_t cr) = 0; + + virtual float getAirtimeFactor() const = 0; + virtual void setAirtimeFactor(float af) = 0; + + // //def("cad", _parent->cad_enabled); + // //def("int_thr", _parent->interference_threshold); + // def("rxgain", _parent->rx_boosted_gain); + // #if 0 + // // NOTE: these cannot be set (yet) so don't load/save until we can. + // // also, fem_rxgain WAS mapped to wrong JSON property previously + // def("fem_rxgain", _parent->radio_fem_rxgain); + // def("fem_txgain", _parent->radio_fem_txgain); + // #endif + // def("tx", _parent->tx_power_dbm); + // def("rxdelay", _parent->rx_delay_base); + // //def("f_txdelay", _parent->tx_delay_factor); currently hard-coded + // //def("d_txdelay", _parent->direct_tx_delay_factor); currently hard-coded + // //def("agc_int", _parent->agc_reset_interval); + // def("hash_mode", _parent->path_hash_mode); + // def("multi_ack", _parent->multi_acks); + + bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply); +}; From f66ed7ca88d1f0f67a6e65037b0ac85e91fda5fc Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Sun, 23 Aug 2026 17:30:30 +1000 Subject: [PATCH 154/381] * CommonRadioPrefs refactors done --- examples/companion_radio/NodePrefs.h | 24 ++++- src/helpers/CommonCLI.cpp | 99 +----------------- src/helpers/CommonCLI.h | 24 ++++- src/helpers/CommonRadioPrefs.cpp | 147 ++++++++++++++++++++++++++- src/helpers/CommonRadioPrefs.h | 45 +++++--- 5 files changed, 220 insertions(+), 119 deletions(-) diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index 36788052..f1cb69cc 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -78,11 +78,31 @@ private: float getBandwidth() const override { return _parent->bw; } void setBandwidth(float bw) override { _parent->bw = bw; markDirty(); } uint8_t getSpreadFactor() const override { return _parent->sf; } - void setSpreadFactor(uint8_t sf) { _parent->sf; markDirty(); } + void setSpreadFactor(uint8_t sf) override { _parent->sf; markDirty(); } uint8_t getCodingRate() const override { return _parent->cr; } - void setCodingRate(uint8_t cr) { _parent->cr = cr; markDirty(); } + void setCodingRate(uint8_t cr) override { _parent->cr = cr; markDirty(); } float getAirtimeFactor() const override { return _parent->airtime_factor; } void setAirtimeFactor(float af) override { _parent->airtime_factor = af; markDirty(); } + bool isCadEnabled() const override { return false; } + void setCadEnabled(bool en) override { /* no-op */ } + uint8_t getIntThresh() const override { return 0; } + void setIntThresh(uint8_t t) override { /* no-op */ } + uint8_t getRxGain() const override { return _parent->rx_boosted_gain; } + void setRxGain(uint8_t g) override { _parent->rx_boosted_gain = g; markDirty(); } + uint8_t getTxPower() const override { return _parent->tx_power_dbm; } + void setTxPower(uint8_t dbm) override { _parent->tx_power_dbm = dbm; markDirty(); } + float getRxDelay() const override { return _parent->rx_delay_base; } + void setRxDelay(float d) override { _parent->rx_delay_base = d; markDirty(); } + uint8_t getAgcResetInt() const override { return 0; } + void setAgcResetInt(uint8_t secs) override { /* no-op */ } + uint8_t getHashMode() const override { return _parent->path_hash_mode; } + void setHashMode(uint8_t m) override { _parent->path_hash_mode = m; markDirty(); } + uint8_t getMultiAcks() const override { return _parent->multi_acks; } + void setMultiAcks(uint8_t m) override { _parent->multi_acks = m; markDirty(); } + float getFloodTxDelay() const override { return 0.5f; } // currently hard-coded + void setFloodTxDelay(float d) override { /* no-op */ } + float getDirectTxDelay() const override { return 0.2f; } // currently hard-coded + void setDirectTxDelay(float d) override { /* no-op */ } }; RadioPrefs radio; diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index 4e7af30b..2e9efa9c 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -454,27 +454,7 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* reply) { const char* config = &command[4]; - if (memcmp(config, "af ", 3) == 0) { - _prefs->airtime_factor = atof(&config[3]); - savePrefs(); - strcpy(reply, "OK"); - } else if (memcmp(config, "int.thresh ", 11) == 0) { - _prefs->interference_threshold = atoi(&config[11]); - savePrefs(); - strcpy(reply, "OK"); - } else if (memcmp(config, "cad ", 4) == 0) { - _prefs->cad_enabled = memcmp(&config[4], "on", 2) == 0; - savePrefs(); - strcpy(reply, "OK"); - } else if (memcmp(config, "agc.reset.interval ", 19) == 0) { - _prefs->agc_reset_interval = atoi(&config[19]) / 4; - savePrefs(); - sprintf(reply, "OK - interval rounded to %d", ((uint32_t) _prefs->agc_reset_interval) * 4); - } else if (memcmp(config, "multi.acks ", 11) == 0) { - _prefs->multi_acks = atoi(&config[11]); - savePrefs(); - strcpy(reply, "OK"); - } else if (memcmp(config, "allow.read.only ", 16) == 0) { + if (memcmp(config, "allow.read.only ", 16) == 0) { _prefs->allow_read_only = memcmp(&config[16], "on", 2) == 0; savePrefs(); strcpy(reply, "OK"); @@ -527,15 +507,6 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep _prefs->disable_fwd = memcmp(&config[7], "off", 3) == 0; savePrefs(); strcpy(reply, _prefs->disable_fwd ? "OK - repeat is now OFF" : "OK - repeat is now ON"); - } else if (memcmp(config, "radio.rxgain ", 13) == 0) { - bool enabled = memcmp(&config[13], "on", 2) == 0; - _prefs->rx_boosted_gain = enabled; - savePrefs(); - if (_callbacks->setRxBoostedGain(enabled)) { - strcpy(reply, "OK"); - } else { - strcpy(reply, "Error: unsupported"); - } } else if (memcmp(config, "radio.fem.rxgain ", 17) == 0) { if (!_board->canControlLoRaFemLna()) { strcpy(reply, "Error: unsupported"); @@ -588,24 +559,6 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep _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 && db <= 20.0f) { - _prefs->rx_delay_base = db; - savePrefs(); - strcpy(reply, "OK"); - } else { - strcpy(reply, "Error, must be 0-20"); - } - } else if (memcmp(config, "txdelay ", 8) == 0) { - float f = atof(&config[8]); - if (f >= 0 && f <= 2.0f) { - _prefs->tx_delay_factor = f; - savePrefs(); - strcpy(reply, "OK"); - } else { - strcpy(reply, "Error, must be 0-2"); - } } else if (memcmp(config, "flood.max.unscoped ", 19) == 0) { uint8_t m = atoi(&config[19]); if (m <= 64) { @@ -633,15 +586,6 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep } else { strcpy(reply, "Error, max 64"); } - } else if (memcmp(config, "direct.txdelay ", 15) == 0) { - float f = atof(&config[15]); - if (f >= 0 && f <= 2.0f) { - _prefs->direct_tx_delay_factor = f; - savePrefs(); - strcpy(reply, "OK"); - } else { - strcpy(reply, "Error, must be 0-2"); - } } else if (memcmp(config, "owner.info ", 11) == 0) { config += 11; char *dp = _prefs->owner_info; @@ -652,16 +596,6 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep *dp = 0; savePrefs(); strcpy(reply, "OK"); - } else if (memcmp(config, "path.hash.mode ", 15) == 0) { - config += 15; - uint8_t mode = atoi(config); - if (mode < 3) { - _prefs->path_hash_mode = mode; - savePrefs(); - strcpy(reply, "OK"); - } else { - strcpy(reply, "Error, must be 0,1, or 2"); - } } else if (memcmp(config, "loop.detect ", 12) == 0) { config += 12; uint8_t mode; @@ -682,11 +616,6 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep savePrefs(); strcpy(reply, "OK"); } - } else if (memcmp(config, "tx ", 3) == 0) { - _prefs->tx_power_dbm = atoi(&config[3]); - savePrefs(); - _callbacks->setTxPower(_prefs->tx_power_dbm); - strcpy(reply, "OK"); } else if (sender_timestamp == 0 && memcmp(config, "freq ", 5) == 0) { _prefs->freq = atof(&config[5]); savePrefs(); @@ -783,17 +712,7 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* reply) { const char* config = &command[4]; - if (memcmp(config, "af", 2) == 0) { - sprintf(reply, "> %s", StrHelper::ftoa(_prefs->airtime_factor)); - } else if (memcmp(config, "int.thresh", 10) == 0) { - sprintf(reply, "> %d", (uint32_t) _prefs->interference_threshold); - } else if (memcmp(config, "cad", 3) == 0) { - sprintf(reply, "> %s", _prefs->cad_enabled ? "on" : "off"); - } else if (memcmp(config, "agc.reset.interval", 18) == 0) { - sprintf(reply, "> %d", ((uint32_t) _prefs->agc_reset_interval) * 4); - } else if (memcmp(config, "multi.acks", 10) == 0) { - sprintf(reply, "> %d", (uint32_t) _prefs->multi_acks); - } else if (memcmp(config, "allow.read.only", 15) == 0) { + if (memcmp(config, "allow.read.only", 15) == 0) { sprintf(reply, "> %s", _prefs->allow_read_only ? "on" : "off"); } else if (memcmp(config, "flood.advert.interval", 21) == 0) { sprintf(reply, "> %d", ((uint32_t) _prefs->flood_advert_interval)); @@ -814,8 +733,6 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep sprintf(reply, "> %s", StrHelper::ftoa(_prefs->node_lat)); } else if (memcmp(config, "lon", 3) == 0) { sprintf(reply, "> %s", StrHelper::ftoa(_prefs->node_lon)); - } else if (memcmp(config, "radio.rxgain", 12) == 0) { - sprintf(reply, "> %s", _prefs->rx_boosted_gain ? "on" : "off"); } else if (memcmp(config, "radio.fem.rxgain", 16) == 0) { if (!_board->canControlLoRaFemLna()) { strcpy(reply, "Error: unsupported"); @@ -828,18 +745,12 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep } else { sprintf(reply, "> %s", _board->isLoRaFemPaGainEnabled() ? "on" : "off"); } - } else if (memcmp(config, "rxdelay", 7) == 0) { - sprintf(reply, "> %s", StrHelper::ftoa(_prefs->rx_delay_base)); - } else if (memcmp(config, "txdelay", 7) == 0) { - sprintf(reply, "> %s", StrHelper::ftoa(_prefs->tx_delay_factor)); } else if (memcmp(config, "flood.max.advert", 16) == 0) { sprintf(reply, "> %d", (uint32_t)_prefs->flood_max_advert); } else if (memcmp(config, "flood.max.unscoped", 18) == 0) { sprintf(reply, "> %d", (uint32_t)_prefs->flood_max_unscoped); } else if (memcmp(config, "flood.max", 9) == 0) { sprintf(reply, "> %d", (uint32_t)_prefs->flood_max); - } else if (memcmp(config, "direct.txdelay", 14) == 0) { - sprintf(reply, "> %s", StrHelper::ftoa(_prefs->direct_tx_delay_factor)); } else if (memcmp(config, "owner.info", 10) == 0) { auto start = reply; *reply++ = '>'; @@ -850,8 +761,6 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep sp++; } *reply = 0; // set null terminator - } else if (memcmp(config, "path.hash.mode", 14) == 0) { - sprintf(reply, "> %d", (uint32_t)_prefs->path_hash_mode); } else if (memcmp(config, "loop.detect", 11) == 0) { if (_prefs->loop_detect == LOOP_DETECT_OFF) { strcpy(reply, "> off"); @@ -862,10 +771,6 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep } else { strcpy(reply, "> strict"); } - } else if (memcmp(config, "tx", 2) == 0 && (config[2] == 0 || config[2] == ' ')) { - sprintf(reply, "> %d", (int32_t) _prefs->tx_power_dbm); - } else if (memcmp(config, "freq", 4) == 0) { - sprintf(reply, "> %s", StrHelper::ftoa(_prefs->freq)); } else if (memcmp(config, "public.key", 10) == 0) { strcpy(reply, "> "); mesh::Utils::toHex(&reply[2], _callbacks->getSelfId().pub_key, PUB_KEY_SIZE); diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 9d3caf39..69243f52 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -103,11 +103,31 @@ private: float getBandwidth() const override { return _parent->bw; } void setBandwidth(float bw) override { _parent->bw = bw; markDirty(); } uint8_t getSpreadFactor() const override { return _parent->sf; } - void setSpreadFactor(uint8_t sf) { _parent->sf; markDirty(); } + void setSpreadFactor(uint8_t sf) override { _parent->sf; markDirty(); } uint8_t getCodingRate() const override { return _parent->cr; } - void setCodingRate(uint8_t cr) { _parent->cr = cr; markDirty(); } + void setCodingRate(uint8_t cr) override { _parent->cr = cr; markDirty(); } float getAirtimeFactor() const override { return _parent->airtime_factor; } void setAirtimeFactor(float af) override { _parent->airtime_factor = af; markDirty(); } + bool isCadEnabled() const override { return _parent->cad_enabled; } + void setCadEnabled(bool en) override { _parent->cad_enabled; markDirty(); } + uint8_t getIntThresh() const override { return _parent->interference_threshold; } + void setIntThresh(uint8_t t) override { _parent->interference_threshold = t; markDirty(); } + uint8_t getRxGain() const override { return _parent->rx_boosted_gain; } + void setRxGain(uint8_t g) override { _parent->rx_boosted_gain = g; markDirty(); } + uint8_t getTxPower() const override { return _parent->tx_power_dbm; } + void setTxPower(uint8_t dbm) override { _parent->tx_power_dbm = dbm; markDirty(); } + float getRxDelay() const override { return _parent->rx_delay_base; } + void setRxDelay(float d) override { _parent->rx_delay_base = d; markDirty(); } + uint8_t getAgcResetInt() const override { return _parent->agc_reset_interval * 4; } + void setAgcResetInt(uint8_t secs) override { _parent->agc_reset_interval = secs / 4; markDirty(); } + uint8_t getHashMode() const override { return _parent->path_hash_mode; } + void setHashMode(uint8_t m) override { _parent->path_hash_mode = m; markDirty(); } + uint8_t getMultiAcks() const override { return _parent->multi_acks; } + void setMultiAcks(uint8_t m) override { _parent->multi_acks = m; markDirty(); } + float getFloodTxDelay() const override { return _parent->tx_delay_factor; } + void setFloodTxDelay(float d) override { _parent->tx_delay_factor = d; markDirty(); } + float getDirectTxDelay() const override { return _parent->direct_tx_delay_factor; } + void setDirectTxDelay(float d) override { _parent->direct_tx_delay_factor = d; markDirty(); } }; RadioPrefs radio; diff --git a/src/helpers/CommonRadioPrefs.cpp b/src/helpers/CommonRadioPrefs.cpp index ed198c61..275449e6 100644 --- a/src/helpers/CommonRadioPrefs.cpp +++ b/src/helpers/CommonRadioPrefs.cpp @@ -1,6 +1,7 @@ #include "CommonRadioPrefs.h" #include "TxtDataHelpers.h" #include "Utils.h" +#include "target.h" bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { if (strcmp(command, "get radio") == 0) { @@ -24,13 +25,28 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest setCodingRate(cr); setFreq(freq); setBandwidth(bw); - // NOTE: savePrefs() should be handled by caller strcpy(reply, "OK - reboot to apply"); } else { strcpy(reply, "Error, invalid radio params"); } return true; } + + if (strcmp(command, "get freq") == 0) { + sprintf(reply, "> %s", StrHelper::ftoa(getFreq())); + return true; + } + + if (strcmp(command, "get af") == 0) { + sprintf(reply, "> %s", StrHelper::ftoa(getAirtimeFactor())); + return true; + } + if (memcmp(command, "set af ", 7) == 0) { + setAirtimeFactor(atof(&command[7])); + strcpy(reply, "OK"); + return true; + } + if (strcmp(command, "get dutycycle") == 0) { float dc = 100.0f / (getAirtimeFactor() + 1.0f); int dc_int = (int)dc; @@ -44,7 +60,6 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest strcpy(reply, "ERROR: dutycycle must be 1-100"); } else { setAirtimeFactor((100.0f / dc) - 1.0f); - // NOTE: savePrefs() should be handled by caller float actual = 100.0f / (getAirtimeFactor() + 1.0f); int a_int = (int)actual; int a_frac = (int)((actual - a_int) * 10.0f + 0.5f); @@ -52,5 +67,133 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest } return true; } + + if (strcmp(command, "get int.thresh") == 0) { + sprintf(reply, "> %d", (uint32_t) getIntThresh()); + return true; + } + if (memcmp(command, "set int.thresh ", 15) == 0) { + setIntThresh(atoi(&command[15])); + strcpy(reply, "OK"); + return true; + } + + if (strcmp(command, "get cad") == 0) { + sprintf(reply, "> %s", isCadEnabled() ? "on" : "off"); + return true; + } + if (memcmp(command, "set cad ", 8) == 0) { + setCadEnabled(memcmp(&command[8], "on", 2) == 0); + strcpy(reply, "OK"); + return true; + } + + if (strcmp(command, "get radio.rxgain") == 0) { + sprintf(reply, "> %s", getRxGain() != 0 ? "on" : "off"); + return true; + } + if (memcmp(command, "set radio.rxgain ", 17) == 0) { + bool enabled = memcmp(&command[17], "on", 2) == 0; + setRxGain(enabled); + if (radio_driver.setRxBoostedGainMode(enabled)) { + strcpy(reply, "OK"); + } else { + strcpy(reply, "Error: unsupported"); + } + return true; + } + + if (memcmp(command, "get tx", 6) == 0 && (command[6] == 0 || command[6] == ' ')) { + sprintf(reply, "> %d", (int32_t) getTxPower()); + return true; + } + if (memcmp(command, "set tx ", 7) == 0) { + setTxPower(atoi(&command[7])); + radio_driver.setTxPower(getTxPower()); + strcpy(reply, "OK"); + return true; + } + + if (strcmp(command, "get rxdelay") == 0) { + sprintf(reply, "> %s", StrHelper::ftoa(getRxDelay())); + return true; + } + if (memcmp(command, "set rxdelay ", 12) == 0) { + float db = atof(&command[12]); + if (db >= 0 && db <= 20.0f) { + setRxDelay(db); + strcpy(reply, "OK"); + } else { + strcpy(reply, "Error, must be 0-20"); + } + return true; + } + + if (strcmp(command, "get agc.reset.interval") == 0) { + sprintf(reply, "> %d", (uint32_t) getAgcResetInt()); + return true; + } + if (memcmp(command, "set agc.reset.interval ", 23) == 0) { + setAgcResetInt(atoi(&command[23])); + sprintf(reply, "OK - interval rounded to %d", (uint32_t) getAgcResetInt()); + return true; + } + + if (strcmp(command, "get path.hash.mode") == 0) { + sprintf(reply, "> %d", (uint32_t)getHashMode()); + return true; + } + if (memcmp(command, "set path.hash.mode ", 19) == 0) { + const char* config = command + 19; + uint8_t mode = atoi(config); + if (mode < 3) { + setHashMode(mode); + strcpy(reply, "OK"); + } else { + strcpy(reply, "Error, must be 0,1, or 2"); + } + return true; + } + + if (strcmp(command, "get multi.acks") == 0) { + sprintf(reply, "> %d", (uint32_t) getMultiAcks()); + return true; + } + if (memcmp(command, "set multi.acks ", 15) == 0) { + setMultiAcks(atoi(&command[15])); + strcpy(reply, "OK"); + return true; + } + + if (strcmp(command, "get txdelay") == 0) { + sprintf(reply, "> %s", StrHelper::ftoa(getFloodTxDelay())); + return true; + } + if (memcmp(command, "set txdelay ", 12) == 0) { + float f = atof(&command[12]); + if (f >= 0 && f <= 2.0f) { + setFloodTxDelay(f); + strcpy(reply, "OK"); + } else { + strcpy(reply, "Error, must be 0-2"); + } + return true; + } + + if (strcmp(command, "get direct.txdelay") == 0) { + sprintf(reply, "> %s", StrHelper::ftoa(getDirectTxDelay())); + return true; + } + if (memcmp(command, "set direct.txdelay ", 19) == 0) { + float f = atof(&command[19]); + if (f >= 0 && f <= 2.0f) { + setDirectTxDelay(f); + strcpy(reply, "OK"); + } else { + strcpy(reply, "Error, must be 0-2"); + } + return true; + } + return false; // not handled } diff --git a/src/helpers/CommonRadioPrefs.h b/src/helpers/CommonRadioPrefs.h index eaec2c0a..c2aefd98 100644 --- a/src/helpers/CommonRadioPrefs.h +++ b/src/helpers/CommonRadioPrefs.h @@ -24,22 +24,35 @@ public: virtual float getAirtimeFactor() const = 0; virtual void setAirtimeFactor(float af) = 0; - // //def("cad", _parent->cad_enabled); - // //def("int_thr", _parent->interference_threshold); - // def("rxgain", _parent->rx_boosted_gain); - // #if 0 - // // NOTE: these cannot be set (yet) so don't load/save until we can. - // // also, fem_rxgain WAS mapped to wrong JSON property previously - // def("fem_rxgain", _parent->radio_fem_rxgain); - // def("fem_txgain", _parent->radio_fem_txgain); - // #endif - // def("tx", _parent->tx_power_dbm); - // def("rxdelay", _parent->rx_delay_base); - // //def("f_txdelay", _parent->tx_delay_factor); currently hard-coded - // //def("d_txdelay", _parent->direct_tx_delay_factor); currently hard-coded - // //def("agc_int", _parent->agc_reset_interval); - // def("hash_mode", _parent->path_hash_mode); - // def("multi_ack", _parent->multi_acks); + virtual bool isCadEnabled() const = 0; + virtual void setCadEnabled(bool en) = 0; + + virtual uint8_t getIntThresh() const = 0; + virtual void setIntThresh(uint8_t t) = 0; + + virtual uint8_t getRxGain() const = 0; + virtual void setRxGain(uint8_t g) = 0; + + virtual uint8_t getTxPower() const = 0; + virtual void setTxPower(uint8_t dbm) = 0; + + virtual float getRxDelay() const = 0; + virtual void setRxDelay(float d) = 0; + + virtual uint8_t getAgcResetInt() const = 0; + virtual void setAgcResetInt(uint8_t secs) = 0; + + virtual uint8_t getHashMode() const = 0; + virtual void setHashMode(uint8_t m) = 0; + + virtual uint8_t getMultiAcks() const = 0; + virtual void setMultiAcks(uint8_t m) = 0; + + virtual float getFloodTxDelay() const = 0; + virtual void setFloodTxDelay(float d) = 0; + + virtual float getDirectTxDelay() const = 0; + virtual void setDirectTxDelay(float d) = 0; bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply); }; From df507deac9954bf9e541569292448b1cb9c71624 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Sun, 23 Aug 2026 19:35:43 +1000 Subject: [PATCH 155/381] "Unknown command" replies --- examples/companion_radio/MyMesh.cpp | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 54be91c7..5f093f2b 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -533,10 +533,10 @@ void MyMesh::onMessageRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t void MyMesh::onCommandDataRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp, const char *text, char* reply) { markConnectionActive(from); // in case this is from a server, and we have a connection - if (from.isRemoteCLIAllowed() && handleCommand(text, sender_timestamp, reply)) { - // CLI command was handled. Let BaseChatMesh handle the sending of the reply - } else { - queueMessage(from, TXT_TYPE_CLI_DATA, pkt, sender_timestamp, NULL, 0, text); + if (from.isRemoteCLIAllowed()) { + if (!handleCommand(text, sender_timestamp, reply)) { + strcat(reply, "Unknown command"); // reply may have cmd prefix from 'text' + } } } @@ -1095,14 +1095,13 @@ void MyMesh::handleCmdFrame(size_t len) { text[tlen] = 0; // ensure null reply_buf[0] = 0; - if (handleCommand(text, 0, reply_buf)) { - out_frame[0] = RESP_CODE_CLI_REPLY; - int rlen = strlen(reply_buf); - memcpy(&out_frame[1], reply_buf, rlen); - _serial->writeFrame(out_frame, 1 + rlen); - } else { - writeErrFrame(ERR_CODE_ILLEGAL_ARG); // unsupported command + if (!handleCommand(text, 0, reply_buf)) { + strcat(reply_buf, "Unknown command"); // reply_buf may have cmd prefix from 'text' } + out_frame[0] = RESP_CODE_CLI_REPLY; + int rlen = strlen(reply_buf); + memcpy(&out_frame[1], reply_buf, rlen); + _serial->writeFrame(out_frame, 1 + rlen); } else if (cmd_frame[0] == CMD_SEND_TXT_MSG && len >= 14) { int i = 1; uint8_t txt_type = cmd_frame[i++]; From a29ccab17896b5c0b4bbbb52c890139c0ef1f19b Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Sun, 23 Aug 2026 20:03:49 +1000 Subject: [PATCH 156/381] onCommandDataRecv() use '>' prefix for CLI replies. --- examples/companion_radio/MyMesh.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 5f093f2b..b86af093 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -534,8 +534,13 @@ void MyMesh::onCommandDataRecv(const ContactInfo &from, mesh::Packet *pkt, uint3 const char *text, char* reply) { markConnectionActive(from); // in case this is from a server, and we have a connection if (from.isRemoteCLIAllowed()) { - if (!handleCommand(text, sender_timestamp, reply)) { - strcat(reply, "Unknown command"); // reply may have cmd prefix from 'text' + if (text[0] == '>') { // is this a CLI reply? + queueMessage(from, TXT_TYPE_CLI_DATA, pkt, sender_timestamp, NULL, 0, &text[1]); + } else { + *reply++ = '>'; // ensure the special 'is reply' prefix + if (!handleCommand(text, sender_timestamp, reply)) { + strcat(reply, "Unknown command"); // reply may have cmd prefix from 'text' + } } } } From 2c43bf1ba155939695adb0cece3bc95aa7e17840 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Sun, 23 Aug 2026 20:07:28 +1000 Subject: [PATCH 157/381] legacy queueMessage() case, eg. repeater replies --- examples/companion_radio/MyMesh.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index b86af093..489fd69c 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -542,6 +542,8 @@ void MyMesh::onCommandDataRecv(const ContactInfo &from, mesh::Packet *pkt, uint3 strcat(reply, "Unknown command"); // reply may have cmd prefix from 'text' } } + } else { + queueMessage(from, TXT_TYPE_CLI_DATA, pkt, sender_timestamp, NULL, 0, text); } } From 644e68d0ffef1f524b3bbc90dbfa7b6082cea887 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Sun, 23 Aug 2026 22:04:05 +1000 Subject: [PATCH 158/381] * new TXT_TYPE_CLI_COMMAND (3) --- examples/companion_radio/MyMesh.cpp | 18 +++++++++--------- examples/companion_radio/MyMesh.h | 2 ++ examples/simple_repeater/MyMesh.cpp | 2 +- examples/simple_room_server/MyMesh.cpp | 4 ++-- examples/simple_secure_chat/main.cpp | 6 +++++- examples/simple_sensor/SensorMesh.cpp | 2 +- src/helpers/BaseChatMesh.cpp | 8 ++++++-- src/helpers/BaseChatMesh.h | 3 ++- src/helpers/TxtDataHelpers.h | 4 +++- 9 files changed, 31 insertions(+), 18 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 489fd69c..99b3196d 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -530,20 +530,20 @@ void MyMesh::onMessageRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t queueMessage(from, TXT_TYPE_PLAIN, pkt, sender_timestamp, NULL, 0, text); } -void MyMesh::onCommandDataRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp, +void MyMesh::onCommandDataRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp, const char *text) { + markConnectionActive(from); // in case this is from a server, and we have a connection + queueMessage(from, TXT_TYPE_CLI_DATA, pkt, sender_timestamp, NULL, 0, text); +} + +void MyMesh::onCLICommandRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp, const char *text, char* reply) { markConnectionActive(from); // in case this is from a server, and we have a connection if (from.isRemoteCLIAllowed()) { - if (text[0] == '>') { // is this a CLI reply? - queueMessage(from, TXT_TYPE_CLI_DATA, pkt, sender_timestamp, NULL, 0, &text[1]); - } else { - *reply++ = '>'; // ensure the special 'is reply' prefix - if (!handleCommand(text, sender_timestamp, reply)) { - strcat(reply, "Unknown command"); // reply may have cmd prefix from 'text' - } + if (!handleCommand(text, sender_timestamp, reply)) { + strcat(reply, "Unknown command"); // reply may have cmd prefix from 'text' } } else { - queueMessage(from, TXT_TYPE_CLI_DATA, pkt, sender_timestamp, NULL, 0, text); + queueMessage(from, TXT_TYPE_CLI_COMMAND, pkt, sender_timestamp, NULL, 0, text); } } diff --git a/examples/companion_radio/MyMesh.h b/examples/companion_radio/MyMesh.h index b60030a6..780de35d 100644 --- a/examples/companion_radio/MyMesh.h +++ b/examples/companion_radio/MyMesh.h @@ -134,6 +134,8 @@ protected: void onMessageRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp, const char *text) override; void onCommandDataRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp, + const char *text) override; + void onCLICommandRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp, const char *text, char* reply) override; void onSignedMessageRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp, const uint8_t *sender_prefix, const char *text) override; diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index a711ec0a..9f3c90e9 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -704,7 +704,7 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong) uint8_t flags = (data[4] >> 2); // message attempt number, and other flags - if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA)) { + if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA || flags == TXT_TYPE_CLI_COMMAND)) { MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported text type received: flags=%02x", (uint32_t)flags); } else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks bool is_retry = (sender_timestamp == client->last_timestamp); diff --git a/examples/simple_room_server/MyMesh.cpp b/examples/simple_room_server/MyMesh.cpp index 546d094f..b786241a 100644 --- a/examples/simple_room_server/MyMesh.cpp +++ b/examples/simple_room_server/MyMesh.cpp @@ -443,7 +443,7 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong) uint8_t flags = (data[4] >> 2); // message attempt number, and other flags - if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA)) { + if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA || flags == TXT_TYPE_CLI_COMMAND)) { MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported command flags received: flags=%02x", (uint32_t)flags); } else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks, but send Acks for retries bool is_retry = (sender_timestamp == client->last_timestamp); @@ -463,7 +463,7 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, uint8_t temp[166]; bool send_ack; - if (flags == TXT_TYPE_CLI_DATA) { + if (flags == TXT_TYPE_CLI_DATA || flags == TXT_TYPE_CLI_COMMAND) { if (client->isAdmin()) { if (is_retry) { temp[5] = 0; // no reply diff --git a/examples/simple_secure_chat/main.cpp b/examples/simple_secure_chat/main.cpp index 241fe1c2..159249df 100644 --- a/examples/simple_secure_chat/main.cpp +++ b/examples/simple_secure_chat/main.cpp @@ -240,8 +240,12 @@ protected: } } - void onCommandDataRecv(const ContactInfo& from, mesh::Packet* pkt, uint32_t sender_timestamp, const char *text, char* reply) override { + void onCommandDataRecv(const ContactInfo& from, mesh::Packet* pkt, uint32_t sender_timestamp, const char *text) override { } + + void onCLICommandRecv(const ContactInfo& contact, mesh::Packet* pkt, uint32_t sender_timestamp, const char *text, char* reply) override { + } + void onSignedMessageRecv(const ContactInfo& from, mesh::Packet* pkt, uint32_t sender_timestamp, const uint8_t *sender_prefix, const char *text) override { } diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 9bfa5ec6..b4b42f64 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -576,7 +576,7 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i sendAckTo(*from, ack_hash, packet->getPathHashSize()); } } - } else if (flags == TXT_TYPE_CLI_DATA) { + } else if (flags == TXT_TYPE_CLI_DATA || flags == TXT_TYPE_CLI_COMMAND) { from->last_timestamp = sender_timestamp; from->last_activity = getRTCClock()->getCurrentTime(); diff --git a/src/helpers/BaseChatMesh.cpp b/src/helpers/BaseChatMesh.cpp index bf8a861c..d66aabca 100644 --- a/src/helpers/BaseChatMesh.cpp +++ b/src/helpers/BaseChatMesh.cpp @@ -256,13 +256,17 @@ void BaseChatMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender sendAckTo(from, ack_hash, 6); } } else if (flags == TXT_TYPE_CLI_DATA) { + char *text = (char *)&data[5]; + onCommandDataRecv(from, packet, sender_timestamp, text); // let UI know + // NOTE: no ack expected for CLI_DATA replies + } else if (flags == TXT_TYPE_CLI_COMMAND) { uint8_t temp[166]; char *command = (char *)&data[5]; char *reply = (char *)&temp[5]; *reply = 0; - onCommandDataRecv(from, packet, sender_timestamp, command, reply); // let UI know - // NOTE: no ack expected for CLI_DATA replies + onCLICommandRecv(from, packet, sender_timestamp, command, reply); // let UI know + // NOTE: no ack expected for CLI_COMMAND replies int text_len = strlen(reply); if (text_len > 0) { diff --git a/src/helpers/BaseChatMesh.h b/src/helpers/BaseChatMesh.h index 331d1041..a5fe54d5 100644 --- a/src/helpers/BaseChatMesh.h +++ b/src/helpers/BaseChatMesh.h @@ -113,7 +113,8 @@ protected: virtual void onContactPathUpdated(const ContactInfo& contact) = 0; virtual bool onContactPathRecv(ContactInfo& from, uint8_t* in_path, uint8_t in_path_len, uint8_t* out_path, uint8_t out_path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len); virtual void onMessageRecv(const ContactInfo& contact, mesh::Packet* pkt, uint32_t sender_timestamp, const char *text) = 0; - virtual void onCommandDataRecv(const ContactInfo& contact, mesh::Packet* pkt, uint32_t sender_timestamp, const char *text, char* reply) = 0; + virtual void onCommandDataRecv(const ContactInfo& contact, mesh::Packet* pkt, uint32_t sender_timestamp, const char *text) = 0; + virtual void onCLICommandRecv(const ContactInfo& contact, mesh::Packet* pkt, uint32_t sender_timestamp, const char *text, char* reply) = 0; virtual void onSignedMessageRecv(const ContactInfo& contact, mesh::Packet* pkt, uint32_t sender_timestamp, const uint8_t *sender_prefix, const char *text) = 0; virtual uint32_t calcFloodTimeoutMillisFor(uint32_t pkt_airtime_millis) const = 0; virtual uint32_t calcDirectTimeoutMillisFor(uint32_t pkt_airtime_millis, uint8_t path_len) const = 0; diff --git a/src/helpers/TxtDataHelpers.h b/src/helpers/TxtDataHelpers.h index ece494f2..693a47ca 100644 --- a/src/helpers/TxtDataHelpers.h +++ b/src/helpers/TxtDataHelpers.h @@ -4,8 +4,10 @@ #include <stdint.h> #define TXT_TYPE_PLAIN 0 // a plain text message -#define TXT_TYPE_CLI_DATA 1 // a CLI command +#define TXT_TYPE_CLI_DATA 1 // a CLI command -or- reply #define TXT_TYPE_SIGNED_PLAIN 2 // plain text, signed by sender +#define TXT_TYPE_CLI_COMMAND 3 // a CLI command (explictly) + #define DATA_TYPE_RESERVED 0x0000 // reserved for future use #define DATA_TYPE_DEV 0xFFFF // developer namespace for experimenting with group/channel datagrams and building apps From ae61e1a61cc27b69049ea0be34623d1f70a7edde Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Sun, 23 Aug 2026 22:49:45 +1000 Subject: [PATCH 159/381] support for CMD_SEND_TXT_MSG and new TXT_TYPE_CLI_COMMAND --- examples/companion_radio/MyMesh.cpp | 6 +++--- src/helpers/BaseChatMesh.cpp | 4 ++-- src/helpers/BaseChatMesh.h | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 99b3196d..b19c8d7f 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -1119,16 +1119,16 @@ void MyMesh::handleCmdFrame(size_t len) { uint8_t *pub_key_prefix = &cmd_frame[i]; i += 6; ContactInfo *recipient = lookupContactByPubKey(pub_key_prefix, 6); - if (recipient && (txt_type == TXT_TYPE_PLAIN || txt_type == TXT_TYPE_CLI_DATA)) { + if (recipient && (txt_type == TXT_TYPE_PLAIN || txt_type == TXT_TYPE_CLI_DATA || txt_type == TXT_TYPE_CLI_COMMAND)) { char *text = (char *)&cmd_frame[i]; int tlen = len - i; uint32_t est_timeout; text[tlen] = 0; // ensure null int result; uint32_t expected_ack; - if (txt_type == TXT_TYPE_CLI_DATA) { + if (txt_type == TXT_TYPE_CLI_DATA || txt_type == TXT_TYPE_CLI_COMMAND) { msg_timestamp = getRTCClock()->getCurrentTimeUnique(); // Use node's RTC instead of app timestamp to avoid tripping replay protection - result = sendCommandData(*recipient, msg_timestamp, attempt, text, est_timeout); + result = sendCommandData(*recipient, msg_timestamp, attempt, txt_type, text, est_timeout); expected_ack = 0; // no Ack expected } else { result = sendMessage(*recipient, msg_timestamp, attempt, text, expected_ack, est_timeout); diff --git a/src/helpers/BaseChatMesh.cpp b/src/helpers/BaseChatMesh.cpp index d66aabca..28592415 100644 --- a/src/helpers/BaseChatMesh.cpp +++ b/src/helpers/BaseChatMesh.cpp @@ -489,13 +489,13 @@ int BaseChatMesh::sendMessage(const ContactInfo& recipient, uint32_t timestamp, return rc; } -int BaseChatMesh::sendCommandData(const ContactInfo& recipient, uint32_t timestamp, uint8_t attempt, const char* text, uint32_t& est_timeout) { +int BaseChatMesh::sendCommandData(const ContactInfo& recipient, uint32_t timestamp, uint8_t attempt, uint8_t txt_type, const char* text, uint32_t& est_timeout) { int text_len = strlen(text); if (text_len > MAX_TEXT_LEN) return MSG_SEND_FAILED; uint8_t temp[5+MAX_TEXT_LEN+1]; memcpy(temp, ×tamp, 4); // mostly an extra blob to help make packet_hash unique - temp[4] = (attempt & 3) | (TXT_TYPE_CLI_DATA << 2); + temp[4] = (attempt & 3) | (txt_type << 2); memcpy(&temp[5], text, text_len + 1); auto pkt = createDatagram(PAYLOAD_TYPE_TXT_MSG, recipient.id, recipient.getSharedSecret(self_id), temp, 5 + text_len); diff --git a/src/helpers/BaseChatMesh.h b/src/helpers/BaseChatMesh.h index a5fe54d5..0a8fdef4 100644 --- a/src/helpers/BaseChatMesh.h +++ b/src/helpers/BaseChatMesh.h @@ -157,7 +157,7 @@ public: mesh::Packet* createSelfAdvert(const char* name); mesh::Packet* createSelfAdvert(const char* name, double lat, double lon); int sendMessage(const ContactInfo& recipient, uint32_t timestamp, uint8_t attempt, const char* text, uint32_t& expected_ack, uint32_t& est_timeout); - int sendCommandData(const ContactInfo& recipient, uint32_t timestamp, uint8_t attempt, const char* text, uint32_t& est_timeout); + int sendCommandData(const ContactInfo& recipient, uint32_t timestamp, uint8_t attempt, uint8_t txt_type, const char* text, uint32_t& est_timeout); bool sendGroupMessage(uint32_t timestamp, mesh::GroupChannel& channel, const char* sender_name, const char* text, int text_len); bool sendGroupData(mesh::GroupChannel& channel, uint8_t* path, uint8_t path_len, uint16_t data_type, const uint8_t* data, int data_len); int sendLogin(const ContactInfo& recipient, const char* password, uint32_t& est_timeout); From a9c977db5199fa5fcf65a25b6bb67bb0eae16cc5 Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Sun, 23 Aug 2026 10:42:00 -0400 Subject: [PATCH 160/381] ui: opt-out for discover screen --- examples/companion_radio/MyMesh.cpp | 4 ++++ examples/companion_radio/MyMesh.h | 12 +++++++++++- examples/companion_radio/ui-new/UITask.cpp | 11 ++++++++++- 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 01512b16..75566448 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -407,6 +407,7 @@ int MyMesh::getRecentlyHeard(AdvertPath dest[], int max_num) { return max_num; } +#if defined(DISPLAY_CLASS) && !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) int MyMesh::getDiscoveredNodes(DiscoveredNode nodes[], int max_num) { if (max_num > DISCOVERED_NODES_TABLE_SIZE) max_num = DISCOVERED_NODES_TABLE_SIZE; if (max_num > disc_nodes_count) max_num = disc_nodes_count; @@ -451,6 +452,7 @@ void MyMesh::checkControlDataForPendingDiscovery(uint8_t payload[], size_t p_len } disc_nodes_count ++; } +#endif void MyMesh::onContactPathUpdated(const ContactInfo &contact) { out_frame[0] = PUSH_CODE_PATH_UPDATED; @@ -832,7 +834,9 @@ void MyMesh::onControlDataRecv(mesh::Packet *packet) { MESH_DEBUG_PRINTLN("onControlDataRecv(), payload_len too long: %d", packet->payload_len); return; } +#if defined(DISPLAY_CLASS) && !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) checkControlDataForPendingDiscovery(packet->payload, packet->payload_len); +#endif int i = 0; out_frame[i++] = PUSH_CODE_CONTROL_DATA; out_frame[i++] = (int8_t)(_radio->getLastSNR() * 4); diff --git a/examples/companion_radio/MyMesh.h b/examples/companion_radio/MyMesh.h index 848d21c0..25b56930 100644 --- a/examples/companion_radio/MyMesh.h +++ b/examples/companion_radio/MyMesh.h @@ -84,6 +84,7 @@ struct AdvertPath { uint8_t path[MAX_PATH_SIZE]; }; +#if defined(DISPLAY_CLASS) && !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) struct DiscoveredNode { uint8_t pubkey_prefix[9]; float snr_in; @@ -91,6 +92,7 @@ struct DiscoveredNode { char name[32]; uint8_t type; }; +#endif class MyMesh : public BaseChatMesh, public DataStoreHost { public: @@ -110,8 +112,10 @@ public: int getRecentlyHeard(AdvertPath dest[], int max_num); +#if defined(DISPLAY_CLASS) && !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) bool requestRepeatersDiscovery(); int getDiscoveredNodes(DiscoveredNode nodes[], int max_num); +#endif protected: float getAirtimeBudgetFactor() const override; @@ -268,12 +272,18 @@ private: #define ADVERT_PATH_TABLE_SIZE 16 AdvertPath advert_paths[ADVERT_PATH_TABLE_SIZE]; // circular table - #define DISCOVERED_NODES_TABLE_SIZE 10 +#if defined(DISPLAY_CLASS) && !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) + #ifdef UI_RECENT_LIST_SIZE + #define DISCOVERED_NODES_TABLE_SIZE UI_RECENT_LIST_SIZE + #else + #define DISCOVERED_NODES_TABLE_SIZE 4 + #endif DiscoveredNode discovered_nodes[DISCOVERED_NODES_TABLE_SIZE]; // not circular, latest discovered nodes are not kept uint32_t disc_node_req_tag = 0; uint32_t disc_nodes_count = 0; void checkControlDataForPendingDiscovery(uint8_t payload[], size_t p_len); +#endif }; extern MyMesh the_mesh; diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index 35525028..0193ebbc 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -103,7 +103,9 @@ class HomeScreen : public UIScreen { #if UI_SENSORS_PAGE == 1 SENSORS, #endif +#if !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) DISCOVERY, +#endif SHUTDOWN, Count // keep as last }; @@ -115,9 +117,11 @@ class HomeScreen : public UIScreen { uint8_t _page; bool _shutdown_init; AdvertPath recent[UI_RECENT_LIST_SIZE]; +#if !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) DiscoveredNode discovered[UI_RECENT_LIST_SIZE]; uint32_t discovery_req_time = 0; bool discovery_disp_names = true; // by default desplay names if available (removes SNR_O) +#endif void renderBatteryIndicator(DisplayDriver& display, uint16_t batteryMilliVolts) { // Convert millivolts to percentage @@ -463,6 +467,7 @@ public: if (sensors_scroll) sensors_scroll_offset = (sensors_scroll_offset+1)%sensors_nb; else sensors_scroll_offset = 0; #endif +#if !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) } else if (_page == HomePage::DISCOVERY) { int count = the_mesh.getDiscoveredNodes(discovered, UI_RECENT_LIST_SIZE); display.setColor(UIColor::primary_txt); @@ -495,7 +500,7 @@ public: y = 10 + 11 * UI_RECENT_LIST_SIZE; display.drawTextCentered(display.width() / 2, y, "discover: " PRESS_LABEL); } - +#endif } else if (_page == HomePage::SHUTDOWN) { display.setColor(UIColor::corp_blue); display.setTextSize(1); @@ -521,9 +526,11 @@ public: if (_page == HomePage::RECENT) { _task->showAlert("Recent adverts", 800); } +#if !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) if (_page == HomePage::DISCOVERY) { _task->showAlert("Repeater disc", 800); } +#endif return true; } if (c == KEY_ENTER && _page == HomePage::BLUETOOTH) { @@ -556,6 +563,7 @@ public: return true; } #endif +#if !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) if (c == KEY_ENTER && _page == HomePage::DISCOVERY) { if (millis() > discovery_req_time + 5000) { // rate limiter the_mesh.requestRepeatersDiscovery(); @@ -567,6 +575,7 @@ public: discovery_disp_names = !discovery_disp_names; return true; } +#endif if (c == KEY_ENTER && _page == HomePage::SHUTDOWN) { _shutdown_init = true; // need to wait for button to be released return true; From 8c73c948b49b9e2f2108be95a28da5f3149fc3ee Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Mon, 24 Aug 2026 01:50:22 +1000 Subject: [PATCH 161/381] * T096, and Station G3: refactoring the 'FEM' prefs to variant-specific code * CommonCLI: 'FEM' commands removed * introduced static no-op attachDynamicPrefs() for all boards --- examples/companion_radio/MyMesh.cpp | 11 ++- examples/companion_radio/NodePrefs.h | 13 +-- examples/simple_repeater/MyMesh.cpp | 4 +- examples/simple_room_server/MyMesh.cpp | 4 +- examples/simple_sensor/SensorMesh.cpp | 4 +- src/MeshCore.h | 9 +- src/helpers/CommonCLI.cpp | 61 ++----------- src/helpers/CommonCLI.h | 7 +- src/helpers/CommonRadioPrefs.cpp | 21 +++++ src/helpers/CommonRadioPrefs.h | 13 ++- src/helpers/ConfigSerializer.h | 6 ++ src/helpers/ESP32Board.h | 3 + src/helpers/KeyValueStore.h | 11 +++ src/helpers/NRF52Board.h | 3 + src/helpers/stm32/STM32Board.h | 3 + variants/heltec_t096/T096Board.cpp | 48 +++++++++- variants/heltec_t096/T096Board.h | 12 ++- variants/station_g3_esp32/StationG3Board.cpp | 88 +++++++++++++++++-- variants/station_g3_esp32/StationG3Board.h | 17 ++-- .../waveshare_rp2040_lora/WaveshareBoard.h | 3 + variants/xiao_rp2040/XiaoRP2040Board.h | 3 + 21 files changed, 243 insertions(+), 101 deletions(-) create mode 100644 src/helpers/KeyValueStore.h diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index b19c8d7f..b8068dd9 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -989,8 +989,9 @@ void MyMesh::begin(bool has_display) { radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr); radio_driver.setTxPower(_prefs.tx_power_dbm); radio_driver.setRxBoostedGainMode(_prefs.rx_boosted_gain); - board.setLoRaFemLnaEnabled(_prefs.radio_fem_rxgain); - board.setLoRaFemPaGainEnabled(_prefs.radio_fem_txgain); + + board.attachDynamicPrefs(_prefs.getRadioPrefs()); + MESH_DEBUG_PRINTLN("RX Boosted Gain Mode: %s", radio_driver.getRxBoostedGainMode() ? "Enabled" : "Disabled"); } @@ -2073,6 +2074,12 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* return true; } + // hook for variant-specific CLI processing + if (board.handleCommand(command, sender_timestamp, reply)) { + if (_prefs.isDirty()) { savePrefs(); } + return true; + } + if (memcmp(command, "set name ", 9) == 0) { if (AdvertDataParser::isValidName(&command[9])) { StrHelper::strncpy(_prefs.node_name, &command[9], sizeof(_prefs.node_name)); diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index f1cb69cc..68af0911 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -54,12 +54,8 @@ private: //def("cad", _parent->cad_enabled); //def("int_thr", _parent->interference_threshold); def("rxgain", _parent->rx_boosted_gain); - #if 0 - // NOTE: these cannot be set (yet) so don't load/save until we can. - // also, fem_rxgain WAS mapped to wrong JSON property previously - def("fem_rxgain", _parent->radio_fem_rxgain); + def("fem_rxgain", _parent->radio_fem_rxgain); // fem_rxgain WAS mapped to wrong JSON property previously def("fem_txgain", _parent->radio_fem_txgain); - #endif def("tx", _parent->tx_power_dbm); def("af", _parent->airtime_factor); def("rxdelay", _parent->rx_delay_base); @@ -103,6 +99,10 @@ private: void setFloodTxDelay(float d) override { /* no-op */ } float getDirectTxDelay() const override { return 0.2f; } // currently hard-coded void setDirectTxDelay(float d) override { /* no-op */ } + uint8_t getFEMRxGain() const override { return _parent->radio_fem_rxgain; } + void setFEMRxGain(uint8_t g) override { _parent->radio_fem_rxgain = g; markDirty(); } + uint8_t getFEMTxGain() const override { return _parent->radio_fem_txgain; } + void setFEMTxGain(uint8_t g) override { _parent->radio_fem_txgain = g; markDirty(); } }; RadioPrefs radio; @@ -177,5 +177,6 @@ public: void setRepeatEn(bool en) { repeat.disable_fwd = en ? 0 : 1; } CommonRadioPrefs* getRadioPrefs() { return &radio; } - void clearDirty() { radio.clearDirty(); } + bool isDirty() const override { return ConfigSerializer::isDirty() || radio.isDirty(); } + void clearDirty() override { ConfigSerializer::clearDirty(); radio.clearDirty(); } }; diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index 9f3c90e9..d7371317 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -982,8 +982,8 @@ void MyMesh::begin(FILESYSTEM *fs) { radio_driver.setRxBoostedGainMode(_prefs.rx_boosted_gain); MESH_DEBUG_PRINTLN("RX Boosted Gain Mode: %s", radio_driver.getRxBoostedGainMode() ? "Enabled" : "Disabled"); - board.setLoRaFemLnaEnabled(_prefs.radio_fem_rxgain); - board.setLoRaFemPaGainEnabled(_prefs.radio_fem_txgain); + + board.attachDynamicPrefs(_prefs.getRadioPrefs()); updateAdvertTimer(); updateFloodAdvertTimer(); diff --git a/examples/simple_room_server/MyMesh.cpp b/examples/simple_room_server/MyMesh.cpp index b786241a..33a67bde 100644 --- a/examples/simple_room_server/MyMesh.cpp +++ b/examples/simple_room_server/MyMesh.cpp @@ -725,8 +725,8 @@ void MyMesh::begin(FILESYSTEM *fs) { radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr); radio_driver.setTxPower(_prefs.tx_power_dbm); radio_driver.setRxBoostedGainMode(_prefs.rx_boosted_gain); - board.setLoRaFemLnaEnabled(_prefs.radio_fem_rxgain); - board.setLoRaFemPaGainEnabled(_prefs.radio_fem_txgain); + + board.attachDynamicPrefs(_prefs.getRadioPrefs()); updateAdvertTimer(); updateFloodAdvertTimer(); diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index b4b42f64..97b39dac 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -771,8 +771,8 @@ void SensorMesh::begin(FILESYSTEM* fs) { radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr); radio_driver.setTxPower(_prefs.tx_power_dbm); - board.setLoRaFemLnaEnabled(_prefs.radio_fem_rxgain); - board.setLoRaFemPaGainEnabled(_prefs.radio_fem_txgain); + + board.attachDynamicPrefs(_prefs.getRadioPrefs()); updateAdvertTimer(); updateFloodAdvertTimer(); diff --git a/src/MeshCore.h b/src/MeshCore.h index e67371ef..43495232 100644 --- a/src/MeshCore.h +++ b/src/MeshCore.h @@ -64,13 +64,6 @@ public: virtual uint8_t getStartupReason() const = 0; virtual bool getBootloaderVersion(char* version, size_t max_len) { return false; } virtual bool startOTAUpdate(const char* id, char reply[]) { return false; } // not supported - virtual bool setLoRaFemLnaEnabled(bool enable) { return false; } - virtual bool canControlLoRaFemLna() const { return false; } - virtual bool isLoRaFemLnaEnabled() const { return false; } - // Software-selectable external FEM transmit gain. This is not a PA power switch. - virtual bool setLoRaFemPaGainEnabled(bool enable) { return false; } - virtual bool canControlLoRaFemPaGain() const { return false; } - virtual bool isLoRaFemPaGainEnabled() const { return false; } // Power management interface (boards with power management override these) virtual bool isExternalPowered() { return false; } @@ -79,6 +72,8 @@ public: virtual const char* getResetReasonString(uint32_t reason) { return "Not available"; } virtual uint8_t getShutdownReason() const { return 0; } virtual const char* getShutdownReasonString(uint8_t reason) { return "Not available"; } + + virtual bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { return false; } }; /** diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index 2e9efa9c..4930e81e 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -185,6 +185,11 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re if (_prefs->getRadioPrefs()->isDirty()) { savePrefs(); } return; } + // hook for variant-specific CLI processing + if (_board->handleCommand(command, sender_timestamp, reply)) { + if (_prefs->isDirty()) { savePrefs(); } + return; + } if (memcmp(command, "poweroff", 8) == 0 || memcmp(command, "shutdown", 8) == 0) { _board->powerOff(); // doesn't return @@ -507,50 +512,6 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep _prefs->disable_fwd = memcmp(&config[7], "off", 3) == 0; savePrefs(); strcpy(reply, _prefs->disable_fwd ? "OK - repeat is now OFF" : "OK - repeat is now ON"); - } else if (memcmp(config, "radio.fem.rxgain ", 17) == 0) { - if (!_board->canControlLoRaFemLna()) { - strcpy(reply, "Error: unsupported"); - } else if (memcmp(&config[17], "on", 2) == 0) { - if (_board->setLoRaFemLnaEnabled(true)) { - _prefs->radio_fem_rxgain = 1; - savePrefs(); - strcpy(reply, "OK - LoRa FEM RX gain on"); - } else { - strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); - } - } else if (memcmp(&config[17], "off", 3) == 0) { - if (_board->setLoRaFemLnaEnabled(false)) { - _prefs->radio_fem_rxgain = 0; - savePrefs(); - strcpy(reply, "OK - LoRa FEM RX gain off"); - } else { - strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); - } - } else { - strcpy(reply, "Error: state must be on or off"); - } - } else if (memcmp(config, "radio.fem.txgain ", 17) == 0) { - if (!_board->canControlLoRaFemPaGain()) { - strcpy(reply, "Error: unsupported"); - } else if (memcmp(&config[17], "on", 2) == 0) { - if (_board->setLoRaFemPaGainEnabled(true)) { - _prefs->radio_fem_txgain = 1; - savePrefs(); - strcpy(reply, "OK - LoRa FEM TX gain on"); - } else { - strcpy(reply, "Error: failed to apply LoRa FEM TX gain"); - } - } else if (memcmp(&config[17], "off", 3) == 0) { - if (_board->setLoRaFemPaGainEnabled(false)) { - _prefs->radio_fem_txgain = 0; - savePrefs(); - strcpy(reply, "OK - LoRa FEM TX gain off"); - } else { - strcpy(reply, "Error: failed to apply LoRa FEM TX gain"); - } - } else { - strcpy(reply, "Error: state must be on or off"); - } } else if (memcmp(config, "lat ", 4) == 0) { _prefs->node_lat = atof(&config[4]); savePrefs(); @@ -733,18 +694,6 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep sprintf(reply, "> %s", StrHelper::ftoa(_prefs->node_lat)); } else if (memcmp(config, "lon", 3) == 0) { sprintf(reply, "> %s", StrHelper::ftoa(_prefs->node_lon)); - } else if (memcmp(config, "radio.fem.rxgain", 16) == 0) { - if (!_board->canControlLoRaFemLna()) { - strcpy(reply, "Error: unsupported"); - } else { - sprintf(reply, "> %s", _board->isLoRaFemLnaEnabled() ? "on" : "off"); - } - } else if (memcmp(config, "radio.fem.txgain", 16) == 0) { - if (!_board->canControlLoRaFemPaGain()) { - strcpy(reply, "Error: unsupported"); - } else { - sprintf(reply, "> %s", _board->isLoRaFemPaGainEnabled() ? "on" : "off"); - } } else if (memcmp(config, "flood.max.advert", 16) == 0) { sprintf(reply, "> %d", (uint32_t)_prefs->flood_max_advert); } else if (memcmp(config, "flood.max.unscoped", 18) == 0) { diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 69243f52..5735abce 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -128,6 +128,10 @@ private: void setFloodTxDelay(float d) override { _parent->tx_delay_factor = d; markDirty(); } float getDirectTxDelay() const override { return _parent->direct_tx_delay_factor; } void setDirectTxDelay(float d) override { _parent->direct_tx_delay_factor = d; markDirty(); } + uint8_t getFEMRxGain() const override { return _parent->radio_fem_rxgain; } + void setFEMRxGain(uint8_t g) override { _parent->radio_fem_rxgain = g; markDirty(); } + uint8_t getFEMTxGain() const override { return _parent->radio_fem_txgain; } + void setFEMTxGain(uint8_t g) override { _parent->radio_fem_txgain = g; markDirty(); } }; RadioPrefs radio; @@ -226,7 +230,8 @@ public: } CommonRadioPrefs* getRadioPrefs() { return &radio; } - void clearDirty() { radio.clearDirty(); } + bool isDirty() const override { return ConfigSerializer::isDirty() || radio.isDirty(); } + void clearDirty() override { ConfigSerializer::clearDirty(); radio.clearDirty(); } }; class CommonCLICallbacks { diff --git a/src/helpers/CommonRadioPrefs.cpp b/src/helpers/CommonRadioPrefs.cpp index 275449e6..60d52e15 100644 --- a/src/helpers/CommonRadioPrefs.cpp +++ b/src/helpers/CommonRadioPrefs.cpp @@ -3,6 +3,27 @@ #include "Utils.h" #include "target.h" +void CommonRadioPrefs::getByKey(const char* key, char* value, size_t max_len) { + if (strcmp(key, "fem_rxgain") == 0) { + snprintf(value, max_len, "%d", (uint32_t)getFEMRxGain()); + } else if (strcmp(key, "fem_txgain") == 0) { + snprintf(value, max_len, "%d", (uint32_t)getFEMTxGain()); + } else { + MESH_DEBUG_PRINTLN("Error: getBykey() unknown key: %s", key); + } +} +void CommonRadioPrefs::setByKey(const char* key, const char* value) { + if (strcmp(key, "fem_rxgain") == 0) { + setFEMRxGain(atoi(value)); + markDirty(); + } else if (strcmp(key, "fem_txgain") == 0) { + setFEMTxGain(atoi(value)); + markDirty(); + } else { + MESH_DEBUG_PRINTLN("Error: setBykey() unknown key: %s", key); + } +} + bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { if (strcmp(command, "get radio") == 0) { char freq[16], bw[16]; diff --git a/src/helpers/CommonRadioPrefs.h b/src/helpers/CommonRadioPrefs.h index c2aefd98..de3e515f 100644 --- a/src/helpers/CommonRadioPrefs.h +++ b/src/helpers/CommonRadioPrefs.h @@ -1,6 +1,8 @@ +#pragma once #include "ConfigSerializer.h" +#include "KeyValueStore.h" -class CommonRadioPrefs : public ConfigSerializer { +class CommonRadioPrefs : public ConfigSerializer, public KeyValueStore{ bool _is_dirty = false; protected: CommonRadioPrefs() { } @@ -54,5 +56,14 @@ public: virtual float getDirectTxDelay() const = 0; virtual void setDirectTxDelay(float d) = 0; + virtual uint8_t getFEMRxGain() const = 0; + virtual void setFEMRxGain(uint8_t g) = 0; + + virtual uint8_t getFEMTxGain() const = 0; + virtual void setFEMTxGain(uint8_t g) = 0; + bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply); + + void setByKey(const char* key, const char* value) override; // for dynamic key/value access + void getByKey(const char* key, char* value, size_t max_len) override; }; diff --git a/src/helpers/ConfigSerializer.h b/src/helpers/ConfigSerializer.h index 7e6d6f2a..47ab5e81 100644 --- a/src/helpers/ConfigSerializer.h +++ b/src/helpers/ConfigSerializer.h @@ -17,6 +17,7 @@ class ConfigSerializer { bool _first; int8_t _depth; + bool _dirty = false; enum OP { READ, WRITE }; @@ -62,7 +63,12 @@ protected: virtual void structure() = 0; + void markDirty() { _dirty = true; } + public: bool loadSerial(Stream& s); bool saveSerial(Stream& s); + + virtual bool isDirty() const { return _dirty; } + virtual void clearDirty() { _dirty = false; } }; diff --git a/src/helpers/ESP32Board.h b/src/helpers/ESP32Board.h index d7eb5fee..75428bc6 100644 --- a/src/helpers/ESP32Board.h +++ b/src/helpers/ESP32Board.h @@ -15,6 +15,7 @@ #include "soc/rtc.h" #include "esp_system.h" #include <driver/rtc_io.h> +#include <helpers/KeyValueStore.h> class ESP32Board : public mesh::MainBoard { protected: @@ -51,6 +52,8 @@ public: #endif } + void attachDynamicPrefs(KeyValueStore* prefs) { } // no-op + // Temperature from ESP32 MCU float getMCUTemperature() override { uint32_t raw = 0; diff --git a/src/helpers/KeyValueStore.h b/src/helpers/KeyValueStore.h new file mode 100644 index 00000000..4bebb4d2 --- /dev/null +++ b/src/helpers/KeyValueStore.h @@ -0,0 +1,11 @@ +#pragma once +#include <stdint.h> +#include <string.h> + +class KeyValueStore { +protected: + KeyValueStore() { } +public: + virtual void setByKey(const char* key, const char* value) { } + virtual void getByKey(const char* key, char* value, size_t max_len) { } +}; diff --git a/src/helpers/NRF52Board.h b/src/helpers/NRF52Board.h index dba15f97..4dbfe1ca 100644 --- a/src/helpers/NRF52Board.h +++ b/src/helpers/NRF52Board.h @@ -2,6 +2,7 @@ #include <Arduino.h> #include <MeshCore.h> +#include <helpers/KeyValueStore.h> #if defined(NRF52_PLATFORM) @@ -57,6 +58,8 @@ public: virtual void sleep(uint32_t secs) override; bool isExternalPowered() override; + void attachDynamicPrefs(KeyValueStore* prefs) { } // no-op + #ifdef NRF52_POWER_MANAGEMENT uint16_t getBootVoltage() override { return boot_voltage_mv; } virtual uint32_t getResetReason() const override { return reset_reason; } diff --git a/src/helpers/stm32/STM32Board.h b/src/helpers/stm32/STM32Board.h index 06bc768f..016d1fb1 100644 --- a/src/helpers/stm32/STM32Board.h +++ b/src/helpers/stm32/STM32Board.h @@ -2,6 +2,7 @@ #include <MeshCore.h> #include <Arduino.h> +#include <helpers/KeyValueStore.h> class STM32Board : public mesh::MainBoard { protected: @@ -12,6 +13,8 @@ public: startup_reason = BD_STARTUP_NORMAL; } + void attachDynamicPrefs(KeyValueStore* prefs) { } // no-op + uint8_t getStartupReason() const override { return startup_reason; } uint16_t getBattMilliVolts() override { diff --git a/variants/heltec_t096/T096Board.cpp b/variants/heltec_t096/T096Board.cpp index 78af529d..255a703d 100644 --- a/variants/heltec_t096/T096Board.cpp +++ b/variants/heltec_t096/T096Board.cpp @@ -131,10 +131,50 @@ bool T096Board::setLoRaFemLnaEnabled(bool enable) { return true; } -bool T096Board::canControlLoRaFemLna() const { - return loRaFEMControl.isLnaCanControl(); -} - bool T096Board::isLoRaFemLnaEnabled() const { return loRaFEMControl.isLNAEnabled(); } + +void T096Board::attachDynamicPrefs(KeyValueStore* prefs) { + _prefs = prefs; + + char radio_fem_rxgain[8] = { 0 }; + _prefs->getByKey("radio.fem_rxgain", radio_fem_rxgain, 7); // get initial values + + setLoRaFemLnaEnabled(strcmp(radio_fem_rxgain, "1") == 0); +} + +bool T096Board::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { + if (strcmp(command, "get radio.fem.rxgain") == 0) { + if (!loRaFEMControl.isLnaCanControl()) { + strcpy(reply, "Error: unsupported"); + } else { + sprintf(reply, "> %s", isLoRaFemLnaEnabled() ? "on" : "off"); + } + return true; + } + if (memcmp(command, "set radio.fem.rxgain ", 21) == 0) { + if (!loRaFEMControl.isLnaCanControl()) { + strcpy(reply, "Error: unsupported"); + } else if (memcmp(&command[21], "on", 2) == 0) { + if (setLoRaFemLnaEnabled(true)) { + _prefs->setByKey("radio.fem_rxgain", "1"); + strcpy(reply, "OK - LoRa FEM RX gain on"); + } else { + strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); + } + } else if (memcmp(&command[21], "off", 3) == 0) { + if (setLoRaFemLnaEnabled(false)) { + _prefs->setByKey("radio.fem_rxgain", "0"); + strcpy(reply, "OK - LoRa FEM RX gain off"); + } else { + strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); + } + } else { + strcpy(reply, "Error: state must be on or off"); + } + return true; + } + + return false; // not handled +} diff --git a/variants/heltec_t096/T096Board.h b/variants/heltec_t096/T096Board.h index 15c7e68b..1fa7ee28 100644 --- a/variants/heltec_t096/T096Board.h +++ b/variants/heltec_t096/T096Board.h @@ -4,28 +4,34 @@ #include <Arduino.h> #include <helpers/NRF52Board.h> #include <helpers/RefCountedDigitalPin.h> +#include <helpers/KeyValueStore.h> #include "LoRaFEMControl.h" class T096Board : public NRF52BoardDCDC { + KeyValueStore* _prefs = NULL; + protected: #ifdef NRF52_POWER_MANAGEMENT void initiateShutdown(uint8_t reason) override; #endif void variant_shutdown(); + bool setLoRaFemLnaEnabled(bool enable); + bool isLoRaFemLnaEnabled() const; + public: RefCountedDigitalPin periph_power; LoRaFEMControl loRaFEMControl; T096Board() :periph_power(PIN_VEXT_EN,PIN_VEXT_EN_ACTIVE), NRF52Board("T096_OTA") {} void begin(); + void attachDynamicPrefs(KeyValueStore* prefs); void onBeforeTransmit(void) override; void onAfterTransmit(void) override; uint16_t getBattMilliVolts() override; const char* getManufacturerName() const override ; void powerOff() override; - bool setLoRaFemLnaEnabled(bool enable) override; - bool canControlLoRaFemLna() const override; - bool isLoRaFemLnaEnabled() const override; + + bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; }; diff --git a/variants/station_g3_esp32/StationG3Board.cpp b/variants/station_g3_esp32/StationG3Board.cpp index dd863aca..277c2b8b 100644 --- a/variants/station_g3_esp32/StationG3Board.cpp +++ b/variants/station_g3_esp32/StationG3Board.cpp @@ -21,10 +21,6 @@ bool StationG3Board::setLoRaFemLnaEnabled(bool enable) { return true; } -bool StationG3Board::canControlLoRaFemLna() const { - return loRaFEMControl.canControlLNA(); -} - bool StationG3Board::isLoRaFemLnaEnabled() const { return loRaFEMControl.isLNAEnabled(); } @@ -37,10 +33,86 @@ bool StationG3Board::setLoRaFemPaGainEnabled(bool enable) { return true; } -bool StationG3Board::canControlLoRaFemPaGain() const { - return loRaFEMControl.canControlPAGain(); -} - bool StationG3Board::isLoRaFemPaGainEnabled() const { return loRaFEMControl.isPAGainEnabled(); } + +void StationG3Board::attachDynamicPrefs(KeyValueStore* prefs) { + _prefs = prefs; + + char gain[8]; + + gain[0] = 0; + _prefs->getByKey("fem_rxgain", gain, 7); // get initial values + setLoRaFemLnaEnabled(strcmp(gain, "1") == 0); + + gain[0] = 0; + _prefs->getByKey("fem_txgain", gain, 7); // get initial values + setLoRaFemPaGainEnabled(strcmp(gain, "1") == 0); +} + +bool StationG3Board::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { + if (strcmp(command, "get radio.fem.rxgain") == 0) { + if (!loRaFEMControl.canControlLNA()) { + strcpy(reply, "Error: unsupported"); + } else { + sprintf(reply, "> %s", isLoRaFemLnaEnabled() ? "on" : "off"); + } + return true; + } + if (memcmp(command, "set radio.fem.rxgain ", 21) == 0) { + if (!loRaFEMControl.canControlLNA()) { + strcpy(reply, "Error: unsupported"); + } else if (memcmp(&command[21], "on", 2) == 0) { + if (setLoRaFemLnaEnabled(true)) { + _prefs->setByKey("fem_rxgain", "1"); + strcpy(reply, "OK - LoRa FEM RX gain on"); + } else { + strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); + } + } else if (memcmp(&command[21], "off", 3) == 0) { + if (setLoRaFemLnaEnabled(false)) { + _prefs->setByKey("fem_rxgain", "0"); + strcpy(reply, "OK - LoRa FEM RX gain off"); + } else { + strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); + } + } else { + strcpy(reply, "Error: state must be on or off"); + } + return true; + } + + if (strcmp(command, "get radio.fem.txgain") == 0) { + if (!loRaFEMControl.canControlPAGain()) { + strcpy(reply, "Error: unsupported"); + } else { + sprintf(reply, "> %s", isLoRaFemPaGainEnabled() ? "on" : "off"); + } + return true; + } + if (memcmp(command, "set radio.fem.txgain ", 21) == 0) { + if (!loRaFEMControl.canControlPAGain()) { + strcpy(reply, "Error: unsupported"); + } else if (memcmp(&command[21], "on", 2) == 0) { + if (setLoRaFemPaGainEnabled(true)) { + _prefs->setByKey("fem_txgain", "1"); + strcpy(reply, "OK - LoRa FEM TX gain on"); + } else { + strcpy(reply, "Error: failed to apply LoRa FEM TX gain"); + } + } else if (memcmp(&command[21], "off", 3) == 0) { + if (setLoRaFemPaGainEnabled(false)) { + _prefs->setByKey("fem_txgain", "0"); + strcpy(reply, "OK - LoRa FEM TX gain off"); + } else { + strcpy(reply, "Error: failed to apply LoRa FEM TX gain"); + } + } else { + strcpy(reply, "Error: state must be on or off"); + } + return true; + } + + return false; // not handled +} diff --git a/variants/station_g3_esp32/StationG3Board.h b/variants/station_g3_esp32/StationG3Board.h index 52628eb6..b4c5838c 100644 --- a/variants/station_g3_esp32/StationG3Board.h +++ b/variants/station_g3_esp32/StationG3Board.h @@ -6,6 +6,12 @@ #include "LoRaFEMControl.h" class StationG3Board : public ESP32Board { + KeyValueStore* _prefs = NULL; + + bool setLoRaFemLnaEnabled(bool enable); + bool isLoRaFemLnaEnabled() const; + bool setLoRaFemPaGainEnabled(bool enable); + bool isLoRaFemPaGainEnabled() const; public: LoRaFEMControl loRaFEMControl; @@ -25,6 +31,10 @@ public: } } + void attachDynamicPrefs(KeyValueStore* prefs); + + bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; + void setPrimaryLNAEnable(bool enabled) { loRaFEMControl.setLNAEnable(enabled); } @@ -43,13 +53,6 @@ public: loRaFEMControl.setRxModeEnable(); } - bool setLoRaFemLnaEnabled(bool enable) override; - bool canControlLoRaFemLna() const override; - bool isLoRaFemLnaEnabled() const override; - bool setLoRaFemPaGainEnabled(bool enable) override; - bool canControlLoRaFemPaGain() const override; - bool isLoRaFemPaGainEnabled() const override; - void powerOff() override; uint16_t getBattMilliVolts() override { diff --git a/variants/waveshare_rp2040_lora/WaveshareBoard.h b/variants/waveshare_rp2040_lora/WaveshareBoard.h index 694b8bd1..e7c70a5d 100644 --- a/variants/waveshare_rp2040_lora/WaveshareBoard.h +++ b/variants/waveshare_rp2040_lora/WaveshareBoard.h @@ -2,6 +2,7 @@ #include <Arduino.h> #include <MeshCore.h> +#include <helpers/KeyValueStore.h> // LoRa radio module pins for Waveshare RP2040-LoRa-HF/LF // https://files.waveshare.com/wiki/RP2040-LoRa/Rp2040-lora-sch.pdf @@ -32,6 +33,8 @@ public: void begin(); uint8_t getStartupReason() const override { return startup_reason; } + void attachDynamicPrefs(KeyValueStore* prefs) { } // no-op + #ifdef P_LORA_TX_LED void onBeforeTransmit() override { digitalWrite(P_LORA_TX_LED, HIGH); } void onAfterTransmit() override { digitalWrite(P_LORA_TX_LED, LOW); } diff --git a/variants/xiao_rp2040/XiaoRP2040Board.h b/variants/xiao_rp2040/XiaoRP2040Board.h index d2951c75..cad399de 100644 --- a/variants/xiao_rp2040/XiaoRP2040Board.h +++ b/variants/xiao_rp2040/XiaoRP2040Board.h @@ -2,6 +2,7 @@ #include <Arduino.h> #include <MeshCore.h> +#include <helpers/KeyValueStore.h> /* * This board has no built-in way to read battery voltage. @@ -30,6 +31,8 @@ public: void begin(); uint8_t getStartupReason() const override { return startup_reason; } + void attachDynamicPrefs(KeyValueStore* prefs) { } // no-op + #ifdef P_LORA_TX_LED void onBeforeTransmit() override { digitalWrite(P_LORA_TX_LED, HIGH); } void onAfterTransmit() override { digitalWrite(P_LORA_TX_LED, LOW); } From b5b20a77383d735ed9a7100eae1e3861bbec3715 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Mon, 24 Aug 2026 02:16:18 +1000 Subject: [PATCH 162/381] * refactored 'FEM' commands for HeltecTrackerV2 & HeltecV4 --- variants/heltec_t096/T096Board.cpp | 6 +-- variants/heltec_t096/T096Board.h | 3 +- .../HeltecTrackerV2Board.cpp | 48 +++++++++++++++++-- .../heltec_tracker_v2/HeltecTrackerV2Board.h | 10 ++-- variants/heltec_v4/HeltecV4Board.cpp | 48 +++++++++++++++++-- variants/heltec_v4/HeltecV4Board.h | 10 ++-- 6 files changed, 106 insertions(+), 19 deletions(-) diff --git a/variants/heltec_t096/T096Board.cpp b/variants/heltec_t096/T096Board.cpp index 255a703d..ea26d2cc 100644 --- a/variants/heltec_t096/T096Board.cpp +++ b/variants/heltec_t096/T096Board.cpp @@ -139,7 +139,7 @@ void T096Board::attachDynamicPrefs(KeyValueStore* prefs) { _prefs = prefs; char radio_fem_rxgain[8] = { 0 }; - _prefs->getByKey("radio.fem_rxgain", radio_fem_rxgain, 7); // get initial values + _prefs->getByKey("fem_rxgain", radio_fem_rxgain, 7); // get initial values setLoRaFemLnaEnabled(strcmp(radio_fem_rxgain, "1") == 0); } @@ -158,14 +158,14 @@ bool T096Board::handleCommand(const char* command, uint32_t sender_timestamp, ch strcpy(reply, "Error: unsupported"); } else if (memcmp(&command[21], "on", 2) == 0) { if (setLoRaFemLnaEnabled(true)) { - _prefs->setByKey("radio.fem_rxgain", "1"); + _prefs->setByKey("fem_rxgain", "1"); strcpy(reply, "OK - LoRa FEM RX gain on"); } else { strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); } } else if (memcmp(&command[21], "off", 3) == 0) { if (setLoRaFemLnaEnabled(false)) { - _prefs->setByKey("radio.fem_rxgain", "0"); + _prefs->setByKey("fem_rxgain", "0"); strcpy(reply, "OK - LoRa FEM RX gain off"); } else { strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); diff --git a/variants/heltec_t096/T096Board.h b/variants/heltec_t096/T096Board.h index 1fa7ee28..e926c8a6 100644 --- a/variants/heltec_t096/T096Board.h +++ b/variants/heltec_t096/T096Board.h @@ -26,12 +26,11 @@ public: T096Board() :periph_power(PIN_VEXT_EN,PIN_VEXT_EN_ACTIVE), NRF52Board("T096_OTA") {} void begin(); void attachDynamicPrefs(KeyValueStore* prefs); + bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; void onBeforeTransmit(void) override; void onAfterTransmit(void) override; uint16_t getBattMilliVolts() override; const char* getManufacturerName() const override ; void powerOff() override; - - bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; }; diff --git a/variants/heltec_tracker_v2/HeltecTrackerV2Board.cpp b/variants/heltec_tracker_v2/HeltecTrackerV2Board.cpp index 99b1cdfe..753824a0 100644 --- a/variants/heltec_tracker_v2/HeltecTrackerV2Board.cpp +++ b/variants/heltec_tracker_v2/HeltecTrackerV2Board.cpp @@ -72,10 +72,50 @@ void HeltecTrackerV2Board::begin() { return true; } - bool HeltecTrackerV2Board::canControlLoRaFemLna() const { - return loRaFEMControl.isLnaCanControl(); - } - bool HeltecTrackerV2Board::isLoRaFemLnaEnabled() const { return loRaFEMControl.isLNAEnabled(); } + +void HeltecTrackerV2Board::attachDynamicPrefs(KeyValueStore* prefs) { + _prefs = prefs; + + char radio_fem_rxgain[8] = { 0 }; + _prefs->getByKey("fem_rxgain", radio_fem_rxgain, 7); // get initial values + + setLoRaFemLnaEnabled(strcmp(radio_fem_rxgain, "1") == 0); +} + +bool HeltecTrackerV2Board::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { + if (strcmp(command, "get radio.fem.rxgain") == 0) { + if (!loRaFEMControl.isLnaCanControl()) { + strcpy(reply, "Error: unsupported"); + } else { + sprintf(reply, "> %s", isLoRaFemLnaEnabled() ? "on" : "off"); + } + return true; + } + if (memcmp(command, "set radio.fem.rxgain ", 21) == 0) { + if (!loRaFEMControl.isLnaCanControl()) { + strcpy(reply, "Error: unsupported"); + } else if (memcmp(&command[21], "on", 2) == 0) { + if (setLoRaFemLnaEnabled(true)) { + _prefs->setByKey("fem_rxgain", "1"); + strcpy(reply, "OK - LoRa FEM RX gain on"); + } else { + strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); + } + } else if (memcmp(&command[21], "off", 3) == 0) { + if (setLoRaFemLnaEnabled(false)) { + _prefs->setByKey("fem_rxgain", "0"); + strcpy(reply, "OK - LoRa FEM RX gain off"); + } else { + strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); + } + } else { + strcpy(reply, "Error: state must be on or off"); + } + return true; + } + + return false; // not handled +} diff --git a/variants/heltec_tracker_v2/HeltecTrackerV2Board.h b/variants/heltec_tracker_v2/HeltecTrackerV2Board.h index 2bd6a025..5fed2b65 100644 --- a/variants/heltec_tracker_v2/HeltecTrackerV2Board.h +++ b/variants/heltec_tracker_v2/HeltecTrackerV2Board.h @@ -6,6 +6,10 @@ #include "LoRaFEMControl.h" class HeltecTrackerV2Board : public ESP32Board { + KeyValueStore* _prefs = NULL; + + bool setLoRaFemLnaEnabled(bool enable); + bool isLoRaFemLnaEnabled() const; public: RefCountedDigitalPin periph_power; @@ -14,13 +18,13 @@ public: HeltecTrackerV2Board() : periph_power(PIN_VEXT_EN,PIN_VEXT_EN_ACTIVE) { } void begin(); + void attachDynamicPrefs(KeyValueStore* prefs); + bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; + void onBeforeTransmit(void) override; void onAfterTransmit(void) override; void powerOff() override; uint16_t getBattMilliVolts() override; const char* getManufacturerName() const override ; - bool setLoRaFemLnaEnabled(bool enable) override; - bool canControlLoRaFemLna() const override; - bool isLoRaFemLnaEnabled() const override; }; diff --git a/variants/heltec_v4/HeltecV4Board.cpp b/variants/heltec_v4/HeltecV4Board.cpp index 3f13f41f..794257d7 100644 --- a/variants/heltec_v4/HeltecV4Board.cpp +++ b/variants/heltec_v4/HeltecV4Board.cpp @@ -73,10 +73,50 @@ void HeltecV4Board::begin() { return true; } - bool HeltecV4Board::canControlLoRaFemLna() const { - return loRaFEMControl.isLnaCanControl(); - } - bool HeltecV4Board::isLoRaFemLnaEnabled() const { return loRaFEMControl.isLNAEnabled(); } + +void HeltecV4Board::attachDynamicPrefs(KeyValueStore* prefs) { + _prefs = prefs; + + char radio_fem_rxgain[8] = { 0 }; + _prefs->getByKey("fem_rxgain", radio_fem_rxgain, 7); // get initial values + + setLoRaFemLnaEnabled(strcmp(radio_fem_rxgain, "1") == 0); +} + +bool HeltecV4Board::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { + if (strcmp(command, "get radio.fem.rxgain") == 0) { + if (!loRaFEMControl.isLnaCanControl()) { + strcpy(reply, "Error: unsupported"); + } else { + sprintf(reply, "> %s", isLoRaFemLnaEnabled() ? "on" : "off"); + } + return true; + } + if (memcmp(command, "set radio.fem.rxgain ", 21) == 0) { + if (!loRaFEMControl.isLnaCanControl()) { + strcpy(reply, "Error: unsupported"); + } else if (memcmp(&command[21], "on", 2) == 0) { + if (setLoRaFemLnaEnabled(true)) { + _prefs->setByKey("fem_rxgain", "1"); + strcpy(reply, "OK - LoRa FEM RX gain on"); + } else { + strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); + } + } else if (memcmp(&command[21], "off", 3) == 0) { + if (setLoRaFemLnaEnabled(false)) { + _prefs->setByKey("fem_rxgain", "0"); + strcpy(reply, "OK - LoRa FEM RX gain off"); + } else { + strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); + } + } else { + strcpy(reply, "Error: state must be on or off"); + } + return true; + } + + return false; // not handled +} diff --git a/variants/heltec_v4/HeltecV4Board.h b/variants/heltec_v4/HeltecV4Board.h index 55166bb3..79a690e8 100644 --- a/variants/heltec_v4/HeltecV4Board.h +++ b/variants/heltec_v4/HeltecV4Board.h @@ -10,6 +10,10 @@ #endif class HeltecV4Board : public ESP32Board { + KeyValueStore* _prefs = NULL; + + bool setLoRaFemLnaEnabled(bool enable); + bool isLoRaFemLnaEnabled() const; protected: float adc_mult = ADC_MULTIPLIER; @@ -20,12 +24,12 @@ public: HeltecV4Board() : periph_power(PIN_VEXT_EN,PIN_VEXT_EN_ACTIVE) { } void begin(); + void attachDynamicPrefs(KeyValueStore* prefs); + bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; + void onBeforeTransmit(void) override; void onAfterTransmit(void) override; void powerOff() override; - bool setLoRaFemLnaEnabled(bool enable) override; - bool canControlLoRaFemLna() const override; - bool isLoRaFemLnaEnabled() const override; uint16_t getBattMilliVolts() override; bool setAdcMultiplier(float multiplier) override { if (multiplier == 0.0f) { From 213697837829ddb096e8739f17cb1dedec403623 Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Mon, 24 Aug 2026 13:45:19 +1200 Subject: [PATCH 163/381] add UI_NO_HIBERNATE build flag to disable hibernate screen on wio tracker l1 --- examples/companion_radio/ui-new/UITask.cpp | 6 ++++++ variants/wio-tracker-l1/platformio.ini | 2 ++ 2 files changed, 8 insertions(+) diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index 55755ef1..969ac3dd 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -102,7 +102,9 @@ class HomeScreen : public UIScreen { #if UI_SENSORS_PAGE == 1 SENSORS, #endif +#ifndef UI_NO_HIBERNATE SHUTDOWN, +#endif Count // keep as last }; @@ -459,6 +461,7 @@ public: if (sensors_scroll) sensors_scroll_offset = (sensors_scroll_offset+1)%sensors_nb; else sensors_scroll_offset = 0; #endif +#ifndef UI_NO_HIBERNATE } else if (_page == HomePage::SHUTDOWN) { display.setColor(UIColor::corp_blue); display.setTextSize(1); @@ -470,6 +473,7 @@ public: display.drawXbm((display.width() - 32) / 2, 18, power_icon, 32, 32); display.drawTextCentered(display.width() / 2, 64 - 11, "hibernate:" PRESS_LABEL); } +#endif } return 5000; // next render after 5000 ms } @@ -516,10 +520,12 @@ public: return true; } #endif +#ifndef UI_NO_HIBERNATE if (c == KEY_ENTER && _page == HomePage::SHUTDOWN) { _shutdown_init = true; // need to wait for button to be released return true; } +#endif return false; } }; diff --git a/variants/wio-tracker-l1/platformio.ini b/variants/wio-tracker-l1/platformio.ini index fc958ea2..19139c28 100644 --- a/variants/wio-tracker-l1/platformio.ini +++ b/variants/wio-tracker-l1/platformio.ini @@ -65,6 +65,7 @@ build_flags = ${WioTrackerL1.build_flags} -D MAX_GROUP_CHANNELS=40 -D DISPLAY_CLASS=SH1106Display -D UI_HAS_JOYSTICK=1 + -D UI_NO_HIBERNATE -D OFFLINE_QUEUE_SIZE=256 -D PIN_BUZZER=12 -D QSPIFLASH=1 @@ -95,6 +96,7 @@ build_flags = ${WioTrackerL1.build_flags} -D OFFLINE_QUEUE_SIZE=256 -D DISPLAY_CLASS=SH1106Display -D UI_HAS_JOYSTICK=1 + -D UI_NO_HIBERNATE -D PIN_BUZZER=12 -D QSPIFLASH=1 -D ADVERT_NAME='"@@MAC"' From 5a7bc507d11564baab6a51aff0eff7bae08524b4 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Mon, 24 Aug 2026 17:12:56 +1000 Subject: [PATCH 164/381] * new DynamicConfigSerializer * board/variant KeyValueStore now can write to 'custom' object in Json prefs --- examples/companion_radio/MyMesh.cpp | 2 +- examples/companion_radio/NodePrefs.h | 8 ++- examples/simple_repeater/MyMesh.cpp | 2 +- examples/simple_room_server/MyMesh.cpp | 2 +- examples/simple_sensor/SensorMesh.cpp | 2 +- src/helpers/CommonCLI.h | 8 ++- src/helpers/CommonRadioPrefs.cpp | 22 ++++--- src/helpers/CommonRadioPrefs.h | 6 +- src/helpers/DynamicConfigSerializer.cpp | 83 +++++++++++++++++++++++++ src/helpers/DynamicConfigSerializer.h | 20 ++++++ src/helpers/KeyValueStore.h | 4 +- 11 files changed, 139 insertions(+), 20 deletions(-) create mode 100644 src/helpers/DynamicConfigSerializer.cpp create mode 100644 src/helpers/DynamicConfigSerializer.h diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index b8068dd9..011df278 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -990,7 +990,7 @@ void MyMesh::begin(bool has_display) { radio_driver.setTxPower(_prefs.tx_power_dbm); radio_driver.setRxBoostedGainMode(_prefs.rx_boosted_gain); - board.attachDynamicPrefs(_prefs.getRadioPrefs()); + board.attachDynamicPrefs(_prefs.getCustom()); MESH_DEBUG_PRINTLN("RX Boosted Gain Mode: %s", radio_driver.getRxBoostedGainMode() ? "Enabled" : "Disabled"); diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index 68af0911..d2a011bf 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -2,6 +2,7 @@ #include <cstdint> // For uint8_t, uint32_t #include <helpers/ConfigSerializer.h> #include <helpers/CommonRadioPrefs.h> +#include <helpers/DynamicConfigSerializer.h> #define TELEM_MODE_DENY 0 #define TELEM_MODE_ALLOW_FLAGS 1 // use contact.flags @@ -154,6 +155,8 @@ private: }; CompanionPrefs companion; + DynamicConfigSerializer custom; + protected: void structure() override { def("name", node_name, sizeof(node_name)); @@ -165,9 +168,10 @@ protected: def("gps", gps); def("repeat", repeat); def("comp", companion); + def("custom", custom); } public: - NodePrefs() : radio(this), gps(this), companion(this) { + NodePrefs() : radio(this), gps(this), companion(this), custom(&radio) { node_name[0] = 0; default_scope_name[0] = 0; memset(default_scope_key, 0, sizeof(default_scope_key)); @@ -177,6 +181,8 @@ public: void setRepeatEn(bool en) { repeat.disable_fwd = en ? 0 : 1; } CommonRadioPrefs* getRadioPrefs() { return &radio; } + KeyValueStore* getCustom() { return &custom; } + bool isDirty() const override { return ConfigSerializer::isDirty() || radio.isDirty(); } void clearDirty() override { ConfigSerializer::clearDirty(); radio.clearDirty(); } }; diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index d7371317..ca6a3e60 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -983,7 +983,7 @@ void MyMesh::begin(FILESYSTEM *fs) { MESH_DEBUG_PRINTLN("RX Boosted Gain Mode: %s", radio_driver.getRxBoostedGainMode() ? "Enabled" : "Disabled"); - board.attachDynamicPrefs(_prefs.getRadioPrefs()); + board.attachDynamicPrefs(_prefs.getCustom()); updateAdvertTimer(); updateFloodAdvertTimer(); diff --git a/examples/simple_room_server/MyMesh.cpp b/examples/simple_room_server/MyMesh.cpp index 33a67bde..71b8d32a 100644 --- a/examples/simple_room_server/MyMesh.cpp +++ b/examples/simple_room_server/MyMesh.cpp @@ -726,7 +726,7 @@ void MyMesh::begin(FILESYSTEM *fs) { radio_driver.setTxPower(_prefs.tx_power_dbm); radio_driver.setRxBoostedGainMode(_prefs.rx_boosted_gain); - board.attachDynamicPrefs(_prefs.getRadioPrefs()); + board.attachDynamicPrefs(_prefs.getCustom()); updateAdvertTimer(); updateFloodAdvertTimer(); diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 97b39dac..23d0cdc3 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -772,7 +772,7 @@ void SensorMesh::begin(FILESYSTEM* fs) { radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr); radio_driver.setTxPower(_prefs.tx_power_dbm); - board.attachDynamicPrefs(_prefs.getRadioPrefs()); + board.attachDynamicPrefs(_prefs.getCustom()); updateAdvertTimer(); updateFloodAdvertTimer(); diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 5735abce..3fb03dc5 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -7,6 +7,7 @@ #include <helpers/RegionMap.h> #include <helpers/ConfigSerializer.h> #include <helpers/CommonRadioPrefs.h> +#include <helpers/DynamicConfigSerializer.h> #if defined(WITH_RS232_BRIDGE) || defined(WITH_ESPNOW_BRIDGE) #define WITH_BRIDGE @@ -202,6 +203,8 @@ private: }; RoomPrefs room; + DynamicConfigSerializer custom; + protected: void structure() override { def("name", node_name, sizeof(node_name)); @@ -218,10 +221,11 @@ protected: def("repeat", repeat); def("room", room); def("power", power); + def("custom", custom); } public: - NodePrefs() : ConfigSerializer(), bridge(this), gps(this), radio(this), power(this), repeat(this), room(this) { + NodePrefs() : ConfigSerializer(), bridge(this), gps(this), radio(this), power(this), repeat(this), room(this), custom(&radio) { node_name[0] = 0; password[0] = 0; guest_password[0] = 0; @@ -230,6 +234,8 @@ public: } CommonRadioPrefs* getRadioPrefs() { return &radio; } + KeyValueStore* getCustom() { return &custom; } + bool isDirty() const override { return ConfigSerializer::isDirty() || radio.isDirty(); } void clearDirty() override { ConfigSerializer::clearDirty(); radio.clearDirty(); } }; diff --git a/src/helpers/CommonRadioPrefs.cpp b/src/helpers/CommonRadioPrefs.cpp index 60d52e15..a25df880 100644 --- a/src/helpers/CommonRadioPrefs.cpp +++ b/src/helpers/CommonRadioPrefs.cpp @@ -3,25 +3,29 @@ #include "Utils.h" #include "target.h" -void CommonRadioPrefs::getByKey(const char* key, char* value, size_t max_len) { +bool CommonRadioPrefs::getByKey(const char* key, char* value, size_t max_len) { if (strcmp(key, "fem_rxgain") == 0) { snprintf(value, max_len, "%d", (uint32_t)getFEMRxGain()); - } else if (strcmp(key, "fem_txgain") == 0) { - snprintf(value, max_len, "%d", (uint32_t)getFEMTxGain()); - } else { - MESH_DEBUG_PRINTLN("Error: getBykey() unknown key: %s", key); + return true; } + if (strcmp(key, "fem_txgain") == 0) { + snprintf(value, max_len, "%d", (uint32_t)getFEMTxGain()); + return true; + } + return false; } -void CommonRadioPrefs::setByKey(const char* key, const char* value) { +bool CommonRadioPrefs::setByKey(const char* key, const char* value) { if (strcmp(key, "fem_rxgain") == 0) { setFEMRxGain(atoi(value)); markDirty(); - } else if (strcmp(key, "fem_txgain") == 0) { + return true; + } + if (strcmp(key, "fem_txgain") == 0) { setFEMTxGain(atoi(value)); markDirty(); - } else { - MESH_DEBUG_PRINTLN("Error: setBykey() unknown key: %s", key); + return true; } + return false; } bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { diff --git a/src/helpers/CommonRadioPrefs.h b/src/helpers/CommonRadioPrefs.h index de3e515f..96895bb2 100644 --- a/src/helpers/CommonRadioPrefs.h +++ b/src/helpers/CommonRadioPrefs.h @@ -2,7 +2,7 @@ #include "ConfigSerializer.h" #include "KeyValueStore.h" -class CommonRadioPrefs : public ConfigSerializer, public KeyValueStore{ +class CommonRadioPrefs : public ConfigSerializer, public KeyValueStore { bool _is_dirty = false; protected: CommonRadioPrefs() { } @@ -64,6 +64,6 @@ public: bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply); - void setByKey(const char* key, const char* value) override; // for dynamic key/value access - void getByKey(const char* key, char* value, size_t max_len) override; + bool setByKey(const char* key, const char* value) override; // for dynamic key/value access + bool getByKey(const char* key, char* value, size_t max_len) override; }; diff --git a/src/helpers/DynamicConfigSerializer.cpp b/src/helpers/DynamicConfigSerializer.cpp new file mode 100644 index 00000000..7ec6dc4e --- /dev/null +++ b/src/helpers/DynamicConfigSerializer.cpp @@ -0,0 +1,83 @@ +#include "DynamicConfigSerializer.h" +#include <Utils.h> + +#define PROP_SEP_CHAR '|' +#define PROP_SEP_STR "|" +#define KEY_SEP_CHAR ':' +#define KEY_SEP_STR ":" + +bool DynamicConfigSerializer::setByKey(const char* key, const char* value) { + if (_fallback && _fallback->setByKey(key, value)) return true; + + // TODO: guard for bad chars (':' or '|') + char tmp[MAX_DYNAMIC_CONFG]; + strcpy(tmp, _config); // make a (modifiable) copy + + const char* parts[8]; + int n = mesh::Utils::parseTextParts(tmp, parts, 8, PROP_SEP_CHAR); + + // add/replace in _config[] + char new_config[MAX_DYNAMIC_CONFG]; + new_config[0] = 0; + + int keylen = strlen(key); + for (int i = 0; i < n; i++) { + const char* item = parts[i]; + if (item[keylen] == KEY_SEP_CHAR && memcmp(item, key, keylen) == 0) { + // key exists, so omit old value from this pass (will append new value at end) + } else { + if (new_config[0]) { + strcat(new_config, PROP_SEP_STR); + } + strcat(new_config, item); + } + } + // now append new key/value (if it fits) + if (strlen(new_config) + strlen(key) + strlen(value) + 2 < sizeof(_config)-1) { + strcat(new_config, key); + strcat(new_config, KEY_SEP_STR); + strcat(new_config, value); + strcpy(_config, new_config); // commit new serialized string + return true; + } + return false; // didn't fit in _config[] +} + +bool DynamicConfigSerializer::getByKey(const char* key, char* value, size_t max_len) { + if (_fallback && _fallback->getByKey(key, value, max_len)) return true; + + char tmp[MAX_DYNAMIC_CONFG]; + strcpy(tmp, _config); // make a (modifiable) copy + + const char* parts[8]; + int n = mesh::Utils::parseTextParts(tmp, parts, 8, PROP_SEP_CHAR); + + int keylen = strlen(key); + for (int i = 0; i < n; i++) { + const char* item = parts[i]; + if (item[keylen] == KEY_SEP_CHAR && memcmp(item, key, keylen) == 0) { + strncpy(value, &item[keylen+1], max_len); + value[max_len] = 0; + return true; + } + } + return false; +} + +void DynamicConfigSerializer::structure() { + char tmp[MAX_DYNAMIC_CONFG]; + strcpy(tmp, _config); // make a (modifiable) copy + + const char* parts[8]; + int n = mesh::Utils::parseTextParts(tmp, parts, 8, PROP_SEP_CHAR); + + // dynamically call def()'s + for (int i = 0; i < n; i++) { + char* item = (char *) parts[i]; + char* eq = strchr(item, KEY_SEP_CHAR); + if (eq) { + *eq = 0; // replace separator with null terminator + def(item, eq + 1, MAX_DYNAMIC_CONFG/2); // maximum HALF of total for individual property value + } + } +} diff --git a/src/helpers/DynamicConfigSerializer.h b/src/helpers/DynamicConfigSerializer.h new file mode 100644 index 00000000..102f8e97 --- /dev/null +++ b/src/helpers/DynamicConfigSerializer.h @@ -0,0 +1,20 @@ +#include "ConfigSerializer.h" +#include "KeyValueStore.h" + +#ifndef MAX_DYNAMIC_CONFG + #define MAX_DYNAMIC_CONFG 128 +#endif + +class DynamicConfigSerializer : public ConfigSerializer, public KeyValueStore { + char _config[MAX_DYNAMIC_CONFG]; + KeyValueStore* _fallback; + +protected: + void structure() override; + +public: + DynamicConfigSerializer(KeyValueStore* fallback = NULL) : _fallback(fallback) { _config[0] = 0; } + + bool setByKey(const char* key, const char* value) override; + bool getByKey(const char* key, char* value, size_t max_len) override; +}; diff --git a/src/helpers/KeyValueStore.h b/src/helpers/KeyValueStore.h index 4bebb4d2..cc4ac455 100644 --- a/src/helpers/KeyValueStore.h +++ b/src/helpers/KeyValueStore.h @@ -6,6 +6,6 @@ class KeyValueStore { protected: KeyValueStore() { } public: - virtual void setByKey(const char* key, const char* value) { } - virtual void getByKey(const char* key, char* value, size_t max_len) { } + virtual bool setByKey(const char* key, const char* value) { return false; } + virtual bool getByKey(const char* key, char* value, size_t max_len) { return false; } }; From 71deb27b7e2cd0aa8c7e24f9d6a24c7ee7b8e553 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Mon, 24 Aug 2026 17:22:15 +1000 Subject: [PATCH 165/381] * prefs, custom dirty state --- examples/companion_radio/NodePrefs.h | 4 ++-- src/helpers/CommonCLI.h | 4 ++-- src/helpers/DynamicConfigSerializer.cpp | 1 + 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index d2a011bf..c79e2f0f 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -183,6 +183,6 @@ public: CommonRadioPrefs* getRadioPrefs() { return &radio; } KeyValueStore* getCustom() { return &custom; } - bool isDirty() const override { return ConfigSerializer::isDirty() || radio.isDirty(); } - void clearDirty() override { ConfigSerializer::clearDirty(); radio.clearDirty(); } + bool isDirty() const override { return ConfigSerializer::isDirty() || radio.isDirty() || custom.isDirty(); } + void clearDirty() override { ConfigSerializer::clearDirty(); radio.clearDirty(); custom.clearDirty(); } }; diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 3fb03dc5..17b3da87 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -236,8 +236,8 @@ public: CommonRadioPrefs* getRadioPrefs() { return &radio; } KeyValueStore* getCustom() { return &custom; } - bool isDirty() const override { return ConfigSerializer::isDirty() || radio.isDirty(); } - void clearDirty() override { ConfigSerializer::clearDirty(); radio.clearDirty(); } + bool isDirty() const override { return ConfigSerializer::isDirty() || radio.isDirty() || custom.isDirty(); } + void clearDirty() override { ConfigSerializer::clearDirty(); radio.clearDirty(); custom.clearDirty(); } }; class CommonCLICallbacks { diff --git a/src/helpers/DynamicConfigSerializer.cpp b/src/helpers/DynamicConfigSerializer.cpp index 7ec6dc4e..dc08d7d7 100644 --- a/src/helpers/DynamicConfigSerializer.cpp +++ b/src/helpers/DynamicConfigSerializer.cpp @@ -38,6 +38,7 @@ bool DynamicConfigSerializer::setByKey(const char* key, const char* value) { strcat(new_config, KEY_SEP_STR); strcat(new_config, value); strcpy(_config, new_config); // commit new serialized string + markDirty(); return true; } return false; // didn't fit in _config[] From 55855f4cae541406ea37f22d4bed06cd075e7c70 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Mon, 24 Aug 2026 19:42:55 +1000 Subject: [PATCH 166/381] * DynamicConfigSerializer fixes, and unit tests --- platformio.ini | 1 + src/helpers/CommonCLI.h | 4 +- src/helpers/ConfigSerializer.h | 4 +- src/helpers/DynamicConfigSerializer.cpp | 39 ++++--- src/helpers/DynamicConfigSerializer.h | 3 + .../test_config_serializer.cpp | 105 +++++++++++++----- 6 files changed, 115 insertions(+), 41 deletions(-) diff --git a/platformio.ini b/platformio.ini index ee502473..2219c978 100644 --- a/platformio.ini +++ b/platformio.ini @@ -171,6 +171,7 @@ build_src_filter = +<../src/Utils.cpp> +<../src/Packet.cpp> +<../src/helpers/ConfigSerializer.cpp> + +<../src/helpers/DynamicConfigSerializer.cpp> lib_deps = google/googletest @ 1.17.0 diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 17b3da87..8591cdc1 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -104,13 +104,13 @@ private: float getBandwidth() const override { return _parent->bw; } void setBandwidth(float bw) override { _parent->bw = bw; markDirty(); } uint8_t getSpreadFactor() const override { return _parent->sf; } - void setSpreadFactor(uint8_t sf) override { _parent->sf; markDirty(); } + void setSpreadFactor(uint8_t sf) override { _parent->sf = sf; markDirty(); } uint8_t getCodingRate() const override { return _parent->cr; } void setCodingRate(uint8_t cr) override { _parent->cr = cr; markDirty(); } float getAirtimeFactor() const override { return _parent->airtime_factor; } void setAirtimeFactor(float af) override { _parent->airtime_factor = af; markDirty(); } bool isCadEnabled() const override { return _parent->cad_enabled; } - void setCadEnabled(bool en) override { _parent->cad_enabled; markDirty(); } + void setCadEnabled(bool en) override { _parent->cad_enabled = en; markDirty(); } uint8_t getIntThresh() const override { return _parent->interference_threshold; } void setIntThresh(uint8_t t) override { _parent->interference_threshold = t; markDirty(); } uint8_t getRxGain() const override { return _parent->rx_boosted_gain; } diff --git a/src/helpers/ConfigSerializer.h b/src/helpers/ConfigSerializer.h index 47ab5e81..e55b1b12 100644 --- a/src/helpers/ConfigSerializer.h +++ b/src/helpers/ConfigSerializer.h @@ -19,6 +19,7 @@ class ConfigSerializer { int8_t _depth; bool _dirty = false; +protected: enum OP { READ, WRITE }; class Context { @@ -39,13 +40,14 @@ class ConfigSerializer { const char* getToken() const { return rd_buf; } bool keyMatch(int8_t depth, const char* key) { return strcmp(key, _keys[depth]) == 0; } void setKey(uint8_t depth, const char* key) { strcpy(_keys[depth], key); } + const char* getKey(uint8_t depth) { return _keys[depth]; } }; Context* _context = NULL; + int8_t getDepth() const { return _depth; } void writeComma(); -protected: ConfigSerializer() { } void def(const char* key, char* value, size_t max_len); // max_len inclusive of null diff --git a/src/helpers/DynamicConfigSerializer.cpp b/src/helpers/DynamicConfigSerializer.cpp index dc08d7d7..b9c6c267 100644 --- a/src/helpers/DynamicConfigSerializer.cpp +++ b/src/helpers/DynamicConfigSerializer.cpp @@ -6,7 +6,7 @@ #define KEY_SEP_CHAR ':' #define KEY_SEP_STR ":" -bool DynamicConfigSerializer::setByKey(const char* key, const char* value) { +bool DynamicConfigSerializer::setByKeyPrv(const char* key, const char* value) { if (_fallback && _fallback->setByKey(key, value)) return true; // TODO: guard for bad chars (':' or '|') @@ -34,16 +34,26 @@ bool DynamicConfigSerializer::setByKey(const char* key, const char* value) { } // now append new key/value (if it fits) if (strlen(new_config) + strlen(key) + strlen(value) + 2 < sizeof(_config)-1) { + if (new_config[0]) { + strcat(new_config, PROP_SEP_STR); + } strcat(new_config, key); strcat(new_config, KEY_SEP_STR); strcat(new_config, value); strcpy(_config, new_config); // commit new serialized string - markDirty(); return true; } return false; // didn't fit in _config[] } +bool DynamicConfigSerializer::setByKey(const char* key, const char* value) { + if (setByKeyPrv(key, value)) { + markDirty(); + return true; + } + return false; +} + bool DynamicConfigSerializer::getByKey(const char* key, char* value, size_t max_len) { if (_fallback && _fallback->getByKey(key, value, max_len)) return true; @@ -66,19 +76,22 @@ bool DynamicConfigSerializer::getByKey(const char* key, char* value, size_t max_ } void DynamicConfigSerializer::structure() { - char tmp[MAX_DYNAMIC_CONFG]; - strcpy(tmp, _config); // make a (modifiable) copy + if (_context->op() == OP::WRITE) { + char tmp[MAX_DYNAMIC_CONFG]; + strcpy(tmp, _config); // make a (modifiable) copy - const char* parts[8]; - int n = mesh::Utils::parseTextParts(tmp, parts, 8, PROP_SEP_CHAR); + const char* parts[8]; + int n = mesh::Utils::parseTextParts(tmp, parts, 8, PROP_SEP_CHAR); - // dynamically call def()'s - for (int i = 0; i < n; i++) { - char* item = (char *) parts[i]; - char* eq = strchr(item, KEY_SEP_CHAR); - if (eq) { - *eq = 0; // replace separator with null terminator - def(item, eq + 1, MAX_DYNAMIC_CONFG/2); // maximum HALF of total for individual property value + for (int i = 0; i < n; i++) { + char* item = (char *) parts[i]; + char* eq = strchr(item, KEY_SEP_CHAR); + if (eq) { + *eq = 0; // replace separator with null terminator + def(item, eq + 1, MAX_DYNAMIC_CONFG/2); + } } + } else { + setByKeyPrv(_context->getKey(getDepth()), _context->getToken()); } } diff --git a/src/helpers/DynamicConfigSerializer.h b/src/helpers/DynamicConfigSerializer.h index 102f8e97..e5dc4c7c 100644 --- a/src/helpers/DynamicConfigSerializer.h +++ b/src/helpers/DynamicConfigSerializer.h @@ -1,3 +1,4 @@ +#pragma once #include "ConfigSerializer.h" #include "KeyValueStore.h" @@ -9,6 +10,8 @@ class DynamicConfigSerializer : public ConfigSerializer, public KeyValueStore { char _config[MAX_DYNAMIC_CONFG]; KeyValueStore* _fallback; + bool setByKeyPrv(const char* key, const char* value); + protected: void structure() override; diff --git a/test/test_config_serializer/test_config_serializer.cpp b/test/test_config_serializer/test_config_serializer.cpp index 27c3c811..dec55483 100644 --- a/test/test_config_serializer/test_config_serializer.cpp +++ b/test/test_config_serializer/test_config_serializer.cpp @@ -1,13 +1,6 @@ #include <gtest/gtest.h> #include "helpers/ConfigSerializer.h" - -class NativeFileSystem { -public: - void mkdir(const char*) { } -}; -#define FILESYSTEM NativeFileSystem -#include "helpers/CommonCLI.h" -#undef FILESYSTEM +#include "helpers/DynamicConfigSerializer.h" #define TEST_INT_S "56" #define TEST_INT 56 @@ -192,28 +185,90 @@ TEST(ConfigSerializer, LoadSerial_IgnoreUnknowns) { EXPECT_TRUE(match); } -TEST(NodePrefs, FemGainSettingsRoundTrip) { - NodePrefs saved; - saved.radio_fem_rxgain = 0; - saved.radio_fem_txgain = 1; +TEST(DynamicConfigSerializer, GetSet_Basic) { + DynamicConfigSerializer data; - MockPrintStream output; - ASSERT_TRUE(saved.saveSerial(output)); + bool s1 = data.setByKey("age", "11"); + bool s2 = data.setByKey("name", "Scott"); + EXPECT_TRUE(s1 && s2); - std::string serialised(reinterpret_cast<const char*>(output.getBytes()), output.getLength()); - EXPECT_NE(std::string::npos, serialised.find("fem_rxgain:0")); - EXPECT_NE(std::string::npos, serialised.find("fem_txgain:1")); + char tmp[32]; + bool g1 = data.getByKey("age", tmp, 31); + EXPECT_TRUE(g1); + EXPECT_STREQ("11", tmp); - MockInputStream input(serialised.c_str()); - NodePrefs loaded; - loaded.radio_fem_rxgain = 1; - loaded.radio_fem_txgain = 0; - - ASSERT_TRUE(loaded.loadSerial(input)); - EXPECT_EQ(0, loaded.radio_fem_rxgain); - EXPECT_EQ(1, loaded.radio_fem_txgain); + bool g2 = data.getByKey("name", tmp, 31); + EXPECT_TRUE(g2); + EXPECT_STREQ("Scott", tmp); } +TEST(DynamicConfigSerializer, Set_Replaces) { + DynamicConfigSerializer data; + + bool s1 = data.setByKey("age", "11"); + bool s2 = data.setByKey("name", "Scott"); + EXPECT_TRUE(s1 && s2); + + bool s3 = data.setByKey("age", "333"); + EXPECT_TRUE(s3); + + char tmp[32]; + bool g1 = data.getByKey("age", tmp, 31); + EXPECT_TRUE(g1); + EXPECT_STREQ("333", tmp); + + bool g2 = data.getByKey("name", tmp, 31); + EXPECT_TRUE(g2); + EXPECT_STREQ("Scott", tmp); +} + +TEST(DynamicConfigSerializer, GetUnknown_Fail) { + DynamicConfigSerializer data; + + bool s1 = data.setByKey("age", "11"); + EXPECT_TRUE(s1); + + char tmp[32]; + bool g2 = data.getByKey("name", tmp, 31); + EXPECT_FALSE(g2); +} + +TEST(DynamicConfigSerializer, SaveCustom_Basic) { + MockPrintStream s; + DynamicConfigSerializer data; + + bool s1 = data.setByKey("age", "11"); + bool s2 = data.setByKey("name", "Scott"); + EXPECT_TRUE(s1 && s2); + + bool success = data.saveSerial(s); + EXPECT_TRUE(success); + + auto l = s.getLength(); + char tmp[128]; + memcpy(tmp, s.getBytes(), l); + tmp[l] = 0; + + const char* expect = "{age:\"11\",name:\"Scott\"}"; + EXPECT_STREQ(expect, tmp); +} + +TEST(DynamicConfigSerializer, LoadCustom_Basic) { + MockInputStream s("{age:\"" TEST_INT_S "\",name:\"Scott\"}"); + DynamicConfigSerializer data; + + bool success = data.loadSerial(s); + EXPECT_TRUE(success); + + char tmp[32]; + bool g1 = data.getByKey("age", tmp, 31); + EXPECT_TRUE(g1); + EXPECT_STREQ(TEST_INT_S, tmp); + + bool g2 = data.getByKey("name", tmp, 31); + EXPECT_TRUE(g2); + EXPECT_STREQ("Scott", tmp); +} // ── main ─────────────────────────────────────────────────────── From 6239b462f24de7a8c1ed833ec6c02b8ff1b57af0 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Mon, 24 Aug 2026 20:44:17 +1000 Subject: [PATCH 167/381] * companion: fix for setSpreadFactor(). "set cad ..." and "board" now implemented. --- examples/companion_radio/MyMesh.cpp | 7 ++++++- examples/companion_radio/NodePrefs.h | 5 +++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 011df278..f5a4a5a9 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -264,7 +264,7 @@ int MyMesh::getInterferenceThreshold() const { return 0; // disabled for now, until currentRSSI() problem is resolved } bool MyMesh::getCADEnabled() const { - return false; // hardware CAD before TX (disabled by default, until configurable) + return _prefs.cad_enabled; } int MyMesh::calcRxDelay(float score, uint32_t air_time) const { @@ -2102,6 +2102,11 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* return true; } + if (strcmp(command, "board") == 0) { + strcpy(reply, board.getManufacturerName()); + return true; + } + if (strcmp(command, "ver") == 0) { sprintf(reply, "%s (Build: %s)", FIRMWARE_VERSION, FIRMWARE_BUILD_DATE); return true; diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index c79e2f0f..e45915b7 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -40,6 +40,7 @@ public: uint8_t _client_repeat = 0; // DEPRECATED -> use repeat.disable_fwd uint8_t path_hash_mode = 0; // which path mode to use when sending uint8_t autoadd_max_hops = 0; // 0 = no limit, 1 = direct (0 hops), N = up to N-1 hops (max 64) + uint8_t cad_enabled = 0; char default_scope_name[31]; uint8_t default_scope_key[16]; @@ -52,7 +53,7 @@ private: def("bw", _parent->bw); def("sf", _parent->sf); def("cr", _parent->cr); - //def("cad", _parent->cad_enabled); + def("cad", _parent->cad_enabled); //def("int_thr", _parent->interference_threshold); def("rxgain", _parent->rx_boosted_gain); def("fem_rxgain", _parent->radio_fem_rxgain); // fem_rxgain WAS mapped to wrong JSON property previously @@ -75,7 +76,7 @@ private: float getBandwidth() const override { return _parent->bw; } void setBandwidth(float bw) override { _parent->bw = bw; markDirty(); } uint8_t getSpreadFactor() const override { return _parent->sf; } - void setSpreadFactor(uint8_t sf) override { _parent->sf; markDirty(); } + void setSpreadFactor(uint8_t sf) override { _parent->sf = sf; markDirty(); } uint8_t getCodingRate() const override { return _parent->cr; } void setCodingRate(uint8_t cr) override { _parent->cr = cr; markDirty(); } float getAirtimeFactor() const override { return _parent->airtime_factor; } From 3d4eadd2cd7a523ff9665ad6e3b93f459d67c43d Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Tue, 25 Aug 2026 19:04:32 +1000 Subject: [PATCH 168/381] * fix for RPI Picow --- variants/rpi_picow/PicoWBoard.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/variants/rpi_picow/PicoWBoard.h b/variants/rpi_picow/PicoWBoard.h index 708e9655..e64590f2 100644 --- a/variants/rpi_picow/PicoWBoard.h +++ b/variants/rpi_picow/PicoWBoard.h @@ -2,6 +2,7 @@ #include <MeshCore.h> #include <Arduino.h> +#include <helpers/KeyValueStore.h> // built-ins #define PIN_VBAT_READ 26 @@ -16,6 +17,8 @@ public: void begin(); uint8_t getStartupReason() const override { return startup_reason; } + void attachDynamicPrefs(KeyValueStore* prefs) { } // no-op + void onBeforeTransmit() override { digitalWrite(LED_BUILTIN, HIGH); // turn TX LED on } From 8536390800cd82cf1dbf2044815002955b0b08e2 Mon Sep 17 00:00:00 2001 From: Alex Beal <alexlbeal@gmail.com> Date: Tue, 25 Aug 2026 15:00:45 -0600 Subject: [PATCH 169/381] Fix: Do not misidentify IMU as an RTC on Heltec T1 The T1 has an ICM-42607-P IMU with the same address as a DS3231 RTC. This completely breaks the clock on the T1. Reading the time results in a garbage value, causing all sorts of strange issues. The time never advances, which breaks logging in to repeaters (due to their time-based replay protection). This simply disables the probe on the I2C line. The DS3231 doesn't have a WHO_AM_I register that could be used to prevent misidentifying it, so this simpler fix is used. --- variants/heltec_t1/variant.h | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/variants/heltec_t1/variant.h b/variants/heltec_t1/variant.h index b52aeba0..de40ea64 100644 --- a/variants/heltec_t1/variant.h +++ b/variants/heltec_t1/variant.h @@ -9,6 +9,12 @@ #define USE_LFXO #define VARIANT_MCK (64000000ul) +// This board has no external RTC chip -- the ICM-42607-P IMU sits at 0x68, +// the same I2C address DS3231 probing checks, so without this the IMU gets +// misidentified as a DS3231 and its unrelated registers get read/written +// as if they were time/status registers, producing a bogus, unfixable clock. +#define DISABLE_DS3231_PROBE + //////////////////////////////////////////////////////////////////////////////// // Number of pins From 599ecfcb6510b5d855ca2cb3958d1b4f73c9eeaf Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Thu, 27 Aug 2026 19:05:18 +1200 Subject: [PATCH 170/381] fix cad cli command on companion --- examples/companion_radio/NodePrefs.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index e45915b7..c8a9ab83 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -81,8 +81,8 @@ private: void setCodingRate(uint8_t cr) override { _parent->cr = cr; markDirty(); } float getAirtimeFactor() const override { return _parent->airtime_factor; } void setAirtimeFactor(float af) override { _parent->airtime_factor = af; markDirty(); } - bool isCadEnabled() const override { return false; } - void setCadEnabled(bool en) override { /* no-op */ } + bool isCadEnabled() const override { return _parent->cad_enabled; } + void setCadEnabled(bool en) override { _parent->cad_enabled = en; markDirty(); } uint8_t getIntThresh() const override { return 0; } void setIntThresh(uint8_t t) override { /* no-op */ } uint8_t getRxGain() const override { return _parent->rx_boosted_gain; } From 5c32c462190ea2154a1a365943a4306d6ac22856 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Fri, 28 Aug 2026 13:12:59 +1000 Subject: [PATCH 171/381] New TXT_TYPE_CLI_COMMAND (3) --- docs/payloads.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/payloads.md b/docs/payloads.md index a2945e27..fb9cbaf9 100644 --- a/docs/payloads.md +++ b/docs/payloads.md @@ -171,8 +171,9 @@ txt_type | Value | Description | Message content | |--------|---------------------------|--------------------------------------------------------------------------| | `0x00` | plain text message | the plain text of the message | -| `0x01` | CLI command | the command text of the message | +| `0x01` | CLI data | CLI command OR reply text | | `0x02` | signed plain text message | first four bytes is sender pubkey prefix, followed by plain text message | +| `0x03` | CLI command | (since v1.18+) CLI command text (explicit) | ## Anonymous request From 3739ce91cf23c2724bc564d0ad124cb439cba689 Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Sat, 29 Aug 2026 15:22:54 +1000 Subject: [PATCH 172/381] fix Meshnology W12 TX power --- variants/meshnology_w12/platformio.ini | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/variants/meshnology_w12/platformio.ini b/variants/meshnology_w12/platformio.ini index 1168f10a..8255e46c 100644 --- a/variants/meshnology_w12/platformio.ini +++ b/variants/meshnology_w12/platformio.ini @@ -27,8 +27,8 @@ build_flags = -D PIN_USER_BTN=0 -D PIN_VEXT_EN=45 -D PIN_VEXT_EN_ACTIVE=HIGH - -D LORA_TX_POWER=4 - -D MAX_LORA_TX_POWER=4 ; GC1109 datasheet says max input at TX port is +5dbm, confirmed full saturation seems to occur at around 3-4dbm + -D LORA_TX_POWER=5 ; default to 5, which gives ~22dbm + -D MAX_LORA_TX_POWER=13 ; tested with tinySA, 13 gives ~28dbm -D PIN_GPS_RX=38 -D PIN_GPS_TX=39 -D PIN_GPS_RESET=42 From c9e5cc15baa3ac4f6294ee1e2a0a2981cc0bf2df Mon Sep 17 00:00:00 2001 From: Aleksei Mamlin <mamlinav@gmail.com> Date: Mon, 31 Aug 2026 08:59:27 +0300 Subject: [PATCH 173/381] companion: get/set timezone offset for clock * Add tz_offset companion prefs and get/set commands for companion cli * Use tz_offset for clock on display Signed-off-by: Aleksei Mamlin <mamlinav@gmail.com> --- examples/companion_radio/MyMesh.cpp | 16 ++++++++++++++++ examples/companion_radio/NodePrefs.h | 2 ++ examples/companion_radio/ui-new/UITask.cpp | 7 +------ variants/thinknode_m8/platformio.ini | 1 - 4 files changed, 19 insertions(+), 7 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index b122b605..ee8114ca 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2166,6 +2166,22 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* return true; } + if (strcmp(command, "get tz.offset") == 0) { + sprintf(reply, "> %d", _prefs.tz_offset); + return true; + } + if (memcmp(command, "set tz.offset ", 14) == 0) { + int8_t tz = atof(&command[14]); + if (tz < -12 || tz > 14) { + strcpy(reply, "Error, must be from -12 to +14"); + } else { + _prefs.tz_offset = tz; + savePrefs(); + strcpy(reply, "OK"); + } + return true; + } + return false; // not handled } diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index c8a9ab83..f6f9b887 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -43,6 +43,7 @@ public: uint8_t cad_enabled = 0; char default_scope_name[31]; uint8_t default_scope_key[16]; + int8_t tz_offset = 0; private: class RadioPrefs : public CommonRadioPrefs { @@ -150,6 +151,7 @@ private: def("tel_base", _parent->telemetry_mode_base); def("tel_loc", _parent->telemetry_mode_loc); def("tel_env", _parent->telemetry_mode_env); + def("tz_offset", _parent->tz_offset); } public: CompanionPrefs(NodePrefs* parent) : _parent(parent) { } diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index a7227bd8..2c79ab91 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -7,10 +7,6 @@ #include <WiFi.h> #endif -#ifndef UI_TZ_OFFSET - #define UI_TZ_OFFSET 0 -#endif - #ifndef AUTO_OFF_MILLIS #define AUTO_OFF_MILLIS 15000 // 15 seconds #endif @@ -256,8 +252,7 @@ public: #ifdef UI_SHOW_CLOCK display.setTextSize(3); uint32_t now = _rtc->getCurrentTime(); - int8_t tz = UI_TZ_OFFSET; // for now draw time from Santo Domingo ... - now += (int32_t)tz * 3600; + now += (int32_t)_node_prefs->tz_offset * 3600; DateTime dt (now); sprintf(tmp, "%02d:%02d", dt.hour(), dt.minute()); display.drawTextCentered(display.width() / 2, 60, tmp); diff --git a/variants/thinknode_m8/platformio.ini b/variants/thinknode_m8/platformio.ini index b8c70973..db19e446 100644 --- a/variants/thinknode_m8/platformio.ini +++ b/variants/thinknode_m8/platformio.ini @@ -22,7 +22,6 @@ build_flags = ${nrf52_base.build_flags} -D UI_HAS_ROTARY_INPUT=1 -D UI_HAS_NAV_INPUT=1 -D UI_RECENT_LIST_SIZE=9 - -D UI_TZ_OFFSET=-4 # GMT-4 -D UI_MSG_PREVIEW_SIZE=165 -D EINK_MAX_PARTIAL_REFRESH=60 -D EINK_DISPLAY_MODEL=GxEPD2_154_D67 From f163c49339c886e83ebd2df7e67b65db603ef71f Mon Sep 17 00:00:00 2001 From: Robert Ekl <ekl.rob@gmail.com> Date: Wed, 2 Sep 2026 11:27:01 -0500 Subject: [PATCH 174/381] docs: correct stale CLI default values Five "Default:" values in cli_commands.md no longer matched the firmware: - radio / freq: the default preset moved to EU/UK (Narrow) in e80c91eb, changing LORA_FREQ/BW/SF from 869.525/250/11 to 869.618/62.5/8 (platformio.ini:29-31). No variant overrides these, and LORA_CR is 5 on every path, so the full preset is 869.618,62.5,8,5. - flood.advert.interval: raised to 47 hours in 3e0b9da4 for both repeater and room server; sensor leaves it disabled. - advert.interval: prefs store minutes/2 and the getter doubles on read, so a factory-fresh node reports 2, not 0. But savePrefs() zeroes any interval below the 60 minute minimum (CommonCLI.cpp:162-165), and it is called from every `set` handler -- so the value becomes 0 as soon as the node is configured. Documented both states, since neither alone is the whole story. - direct.txdelay: repeater defaults to 0.3, room server and sensor to 0.2. Sources: platformio.ini:29-31, simple_repeater/MyMesh.cpp:893,903-904, simple_room_server/MyMesh.cpp:650,661-662, simple_sensor/SensorMesh.cpp:716, 726-727, CommonCLI.cpp:162-165,680-681. --- docs/cli_commands.md | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 8772b929..f4a43fad 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -211,7 +211,7 @@ This document provides an overview of CLI commands that can be sent to MeshCore **Set by build flag:** `LORA_FREQ`, `LORA_BW`, `LORA_SF`, `LORA_CR` -**Default:** `869.525,250,11,5` +**Default:** `869.618,62.5,8,5` **Note:** Requires reboot to apply @@ -256,7 +256,7 @@ This document provides an overview of CLI commands that can be sent to MeshCore **Parameters:** - `frequency`: Frequency in MHz -**Default:** `869.525` +**Default:** `869.618` **Note:** Requires reboot to apply **Serial Only:** `set freq <frequency>` @@ -537,7 +537,7 @@ This document provides an overview of CLI commands that can be sent to MeshCore **Parameters:** - `value`: Direct transmit delay factor (0-2) -**Default:** `0.2` +**Default:** `0.3` (Repeater) - `0.2` (Room Server, Sensor) **Note:** Same collision-avoidance random window as `txdelay`, but applied to direct (non-flood, routed) traffic. The default is lower because direct packets are addressed to a specific next hop, so far fewer nodes compete to retransmit them. @@ -654,7 +654,7 @@ This document provides an overview of CLI commands that can be sent to MeshCore **Parameters:** - `hours`: Interval in hours (3-168) -**Default:** `12` (Repeater) - `0` (Sensor) +**Default:** `47` (Repeater, Room Server) - `0`, disabled (Sensor) --- @@ -666,7 +666,12 @@ This document provides an overview of CLI commands that can be sent to MeshCore **Parameters:** - `minutes`: Interval in minutes rounded down to the nearest multiple of 2 (61 becomes 60) (60-240) -**Default:** `0` +**Default:** `2` on a factory-fresh node, then `0` (disabled) once configured. + +**Note:** A new install ships with a 2 minute zero-hop advert interval. Saving +any setting resets an interval below the 60 minute minimum to `0`, on the +assumption that the node has now been deliberately configured. To keep zero-hop +adverts running, set an explicit value in the 60-240 range. --- From e00f1b54519f7ca3b6296db0430e7edae0ec1d9f Mon Sep 17 00:00:00 2001 From: Robert Ekl <ekl.rob@gmail.com> Date: Wed, 2 Sep 2026 11:27:42 -0500 Subject: [PATCH 175/381] docs: fix channel index range, secret semantics and payload limit Three factual errors in companion_protocol.md: - The channel-datagram payload cap was given as 163 (MAX_FRAME_SIZE - 9 when MAX_FRAME_SIZE was still 172). It went 172 -> 176 in 22510ab8, but simply updating the arithmetic to 167 would be worse than the stale value: 167 is only the host-frame bound (MyMesh.cpp:1265). The radio-side bound is MAX_GROUP_DATA_LENGTH = 184 - 16 - 3 = 165 (MeshCore.h:21, enforced at BaseChatMesh.cpp:544). A 166- or 167-byte payload passes the frame check, fails the radio check, and comes back as ERR_CODE_TABLE_FULL -- which this same doc describes as "retry later", so a conforming client would retry a permanently failing send forever. Documents 165 as the limit to enforce and calls out the 166-167 band explicitly. - Channel index was documented as 0-7 throughout. The bound is MAX_GROUP_CHANNELS (BaseChatMesh.cpp:927,936), which is 40 on most current variants, 8 on some and 1 on others. Clients should read max_channels from byte 3 of PACKET_DEVICE_INFO instead. Index 0 is pre-populated with the built-in Public channel but is not reserved. - The secret field was documented as "all zeros" for public channels. The firmware always hashes a real 16-byte key; the public channel ships with izOH6cXN6mrJ5e26oRXNcg== (companion_radio/MyMesh.cpp:111,1040). An all-zero secret is not a private channel and not an inert one: SHA256 over 16 zero bytes is a fixed global constant, giving a well-known channel with an all-zero AES key. searchChannelsByHash skips unnamed slots for exactly this reason (BaseChatMesh.cpp:392-401), but a named slot with a zero secret is not skipped and will absorb null-key group traffic from any node. Now documented as something not to do. --- docs/companion_protocol.md | 54 +++++++++++++++++++++++++++----------- 1 file changed, 39 insertions(+), 15 deletions(-) diff --git a/docs/companion_protocol.md b/docs/companion_protocol.md index 8c6b84b9..12d81bc4 100644 --- a/docs/companion_protocol.md +++ b/docs/companion_protocol.md @@ -206,7 +206,7 @@ Byte 1: 0x03 **Command Format**: ``` Byte 0: 0x1F -Byte 1: Channel Index (0-7) +Byte 1: Channel Index (0 .. max_channels-1) ``` **Example** (get channel 1): @@ -225,7 +225,7 @@ Byte 1: Channel Index (0-7) **Command Format**: ``` Byte 0: 0x20 -Byte 1: Channel Index (0-7) +Byte 1: Channel Index (0 .. max_channels-1) Bytes 2-33: Channel Name (32 bytes, UTF-8, null-padded) Bytes 34-49: Secret (16 bytes) ``` @@ -233,8 +233,12 @@ Bytes 34-49: Secret (16 bytes) **Total Length**: 50 bytes **Channel Index**: -- Index 0: Reserved for public channels (no secret) -- Indices 1-7: Available for private channels +- Valid range is `0` to `max_channels - 1`. Read `max_channels` from byte 3 of + the `PACKET_DEVICE_INFO` response; do not assume 8. Builds ship with + `MAX_GROUP_CHANNELS` set to 1, 8 or 40 depending on the board. +- Index 0: pre-populated by the firmware with the built-in "Public" channel. + It can be overwritten like any other slot. +- An out-of-range index is rejected with `PACKET_ERROR` / `ERR_CODE_NOT_FOUND`. **Channel Name**: - UTF-8 encoded @@ -242,8 +246,18 @@ Bytes 34-49: Secret (16 bytes) - Padded with null bytes (0x00) if shorter **Secret Field** (16 bytes): -- For **private channels**: 16-byte secret -- For **public channels**: All zeros (0x00) +- Always a real 16-byte key; the firmware derives the channel hash from + `SHA256(secret)` (`BaseChatMesh.cpp:936-942`). There is no "no secret" form. +- Do **not** write an all-zero secret. `SHA256` over 16 zero bytes is a fixed, + globally identical value, so a zero-secret channel is a well-known channel + with an all-zero AES key that any node can read — not a private one. The + firmware skips *unnamed* slots when matching inbound group traffic for + exactly this reason (`BaseChatMesh.cpp:392-401`), but a slot that has been + given a name and a zero secret is not skipped, and will absorb null-key + group traffic from any node on the mesh. +- The built-in public channel uses the well-known key + `izOH6cXN6mrJ5e26oRXNcg==` (base64), i.e. + `8b3387e9c5cdea6ac9e5edbaa115cd72` in hex. **Example** (create channel "YourChannelName" at index 1 with secret): ``` @@ -265,7 +279,7 @@ Bytes 34-49: Secret (16 bytes) ``` Byte 0: 0x03 Byte 1: 0x00 -Byte 2: Channel Index (0-7) +Byte 2: Channel Index (0 .. max_channels-1) Bytes 3-6: Timestamp (32-bit little-endian Unix timestamp, seconds) Bytes 7+: Message Text (UTF-8, variable length) ``` @@ -288,7 +302,7 @@ Bytes 7+: Message Text (UTF-8, variable length) **Command Format**: ``` Byte 0: 0x3E -Byte 1: Channel Index (0-7) +Byte 1: Channel Index (0 .. max_channels-1) Byte 2: Path Length (0xFF = flood, otherwise actual path length) Bytes 3 .. 2+path_len: Path (omitted when path_len == 0xFF) Next 2 bytes (little-endian): Data Type (`data_type`, uint16) @@ -306,13 +320,23 @@ Remaining bytes: Binary payload (variable length) - Values `0x0001`–`0xFFFE` are available for registered application/community namespaces. See the [Registered data_type values](#registered-data_type-values) table below. **Limits**: -- Maximum payload length is `MAX_CHANNEL_DATA_LENGTH = MAX_FRAME_SIZE - 9 = 163` bytes. -- Larger payloads are rejected with `PACKET_ERROR` (`ERR_CODE_ILLEGAL_ARG`). +- Maximum payload length is **165** bytes — `MAX_GROUP_DATA_LENGTH = + MAX_PACKET_PAYLOAD - CIPHER_BLOCK_SIZE - 3` (`src/MeshCore.h:21`). This is the + radio-side limit and the one clients should enforce. +- Two different bounds are checked, and they do not agree. The host-frame check + uses the larger `MAX_CHANNEL_DATA_LENGTH = MAX_FRAME_SIZE - 9 = 167` + (`companion_radio/MyMesh.cpp:1265`); the radio-side check uses 165 + (`BaseChatMesh.cpp:544`). +- Payloads **above 167** are rejected with `ERR_CODE_ILLEGAL_ARG` (6). +- Payloads of **166 or 167** pass the frame check, then fail the radio-side + check and return `ERR_CODE_TABLE_FULL` (3). Despite that code's usual + meaning, such a send can never succeed — do not retry it. Keep payloads at + 165 bytes or fewer and this case cannot arise. **Response**: `PACKET_OK` (0x00) on success, or `PACKET_ERROR` (0x01) with one of: - `ERR_CODE_NOT_FOUND` (2) — unknown `channel_idx` -- `ERR_CODE_ILLEGAL_ARG` (6) — invalid `path_len`, reserved `data_type` (`0x0000`), or payload larger than `MAX_CHANNEL_DATA_LENGTH` -- `ERR_CODE_TABLE_FULL` (3) — outbound send queue is full; retry later +- `ERR_CODE_ILLEGAL_ARG` (6) — invalid `path_len`, reserved `data_type` (`0x0000`), or payload larger than `MAX_CHANNEL_DATA_LENGTH` (167) +- `ERR_CODE_TABLE_FULL` (3) — outbound send queue is full (retry later), **or** a payload of 166-167 bytes that exceeds the radio-side limit (permanent; see Limits above) **Inbound datagrams** are delivered to the host via `RESP_CODE_CHANNEL_DATA_RECV` (0x1B); see [Receive Channel Data Datagram](#receive-channel-data-datagram). @@ -341,7 +365,7 @@ Inbound group datagrams (radio-level `PAYLOAD_TYPE_GRP_DATA`, 0x06) are forwarde Byte 0: 0x1B (packet type) Byte 1: SNR (signed int8, scaled ×4 — divide by 4.0 to recover dB) Bytes 2-3: Reserved (clients MUST ignore) -Byte 4: Channel Index (0-7) +Byte 4: Channel Index (0 .. max_channels-1) Byte 5: Path Length (actual path length when flooded, otherwise 0xFF for direct) Bytes 6-7: Data Type (uint16 little-endian) Byte 8: Data Length @@ -550,7 +574,7 @@ def parse_contact_message(data): **Standard Format** (`PACKET_CHANNEL_MSG_RECV`, 0x08): ``` Byte 0: 0x08 (packet type) -Byte 1: Channel Index (0-7) +Byte 1: Channel Index (0 .. max_channels-1) Byte 2: Path Length Byte 3: Text Type Bytes 4-7: Timestamp (32-bit little-endian) @@ -562,7 +586,7 @@ Bytes 8+: Message Text (UTF-8) Byte 0: 0x11 (packet type) Byte 1: SNR (signed byte, multiplied by 4) Bytes 2-3: Reserved -Byte 4: Channel Index (0-7) +Byte 4: Channel Index (0 .. max_channels-1) Byte 5: Path Length Byte 6: Text Type Bytes 7-10: Timestamp (32-bit little-endian) From e98254afdc82a3e8941ef9be139588a5789f1642 Mon Sep 17 00:00:00 2001 From: Robert Ekl <ekl.rob@gmail.com> Date: Wed, 2 Sep 2026 11:27:56 -0500 Subject: [PATCH 176/381] docs: correct pwrmgt CLI behaviour on unsupported boards The doc claimed every pwrmgt command except `get pwrmgt.support` returns "ERROR: Power management not supported" when NRF52_POWER_MANAGEMENT is not defined. `get pwrmgt.bootreason` is not inside the #ifdef (CommonCLI.cpp:787) and answers on all boards; only pwrmgt.source and pwrmgt.bootmv are gated. --- docs/nrf52_power_management.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/nrf52_power_management.md b/docs/nrf52_power_management.md index 6d97f2c3..417ee6dd 100644 --- a/docs/nrf52_power_management.md +++ b/docs/nrf52_power_management.md @@ -186,11 +186,19 @@ Power management status can be queried via the CLI: | `get pwrmgt.bootreason` | Returns reset and shutdown reason strings | | `get pwrmgt.bootmv` | Returns boot voltage in millivolts | -On boards without power management enabled, all commands except `get pwrmgt.support` return: +On boards without power management enabled, `get pwrmgt.source` and +`get pwrmgt.bootmv` return: ``` ERROR: Power management not supported ``` +`get pwrmgt.support` returns `unsupported`. `get pwrmgt.bootreason` is not +compiled out at all and answers on every board: `getResetReason()` and +`getShutdownReason()` are virtuals on the base board class, so a board that +does not override them reports `Not available` rather than an error. ESP32 +boards override the reset half with `esp_reset_reason()`, so they return a real +reset reason and `Not available` for the shutdown reason. + ## Debug Output When `MESH_DEBUG=1` is enabled, the power management module outputs: From c2860177dd8e0abc536f70d60c6dec51dc8905ce Mon Sep 17 00:00:00 2001 From: Robert Ekl <ekl.rob@gmail.com> Date: Wed, 2 Sep 2026 11:28:17 -0500 Subject: [PATCH 177/381] docs: remove non-existent set dutycycle from Terminal Chat CLI 3d792e7b added get/set dutycycle to CommonCLI and updated both CLI docs, but Terminal Chat does not use CommonCLI -- simple_secure_chat/main.cpp:479-507 has its own `set` handler supporting only af, name, lat, lon, tx and freq. Typing `set dutycycle` there returns "ERROR: unknown config". Restores `set af` as the documented command, points readers at cli_commands.md for the roles that do have dutycycle, and documents `help` (simple_secure_chat/main.cpp:510), which the client implements but the doc never listed. --- docs/terminal_chat_cli.md | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/docs/terminal_chat_cli.md b/docs/terminal_chat_cli.md index 31616144..d5bac7ed 100644 --- a/docs/terminal_chat_cli.md +++ b/docs/terminal_chat_cli.md @@ -27,15 +27,17 @@ set lon {longitude} ``` Sets your advertisement map longitude. (decimal degrees) -``` -set dutycycle {percent} -``` -Sets the transmit duty cycle limit (1-100%). Example: `set dutycycle 10` for 10%. - ``` set af {air-time-factor} ``` -Sets the transmit air-time-factor. Deprecated — use `set dutycycle` instead. +Sets the transmit air-time-factor. + +> **Note:** `set dutycycle` is *not* available in Terminal Chat. Every other +> firmware — Repeater, Room Server, Sensor and Companion Radio — routes its +> `set`/`get` commands through the shared radio prefs handler and does support +> it (see [CLI Commands](./cli_commands.md)). Terminal Chat is the sole +> exception: it has its own inline `set` handler covering only the six options +> listed above. ``` @@ -99,3 +101,8 @@ Resets the path to current recipient, for new path discovery. public {text} ``` Sends the text message to the built-in 'public' group channel + +``` +help +``` +Lists the available commands. From 1d87776c02766cd28ca9bc4142d9755a345707d0 Mon Sep 17 00:00:00 2001 From: Robert Ekl <ekl.rob@gmail.com> Date: Wed, 2 Sep 2026 11:28:51 -0500 Subject: [PATCH 178/381] docs: update stale repo URLs and build recipe The project moved to meshcore-dev/meshcore, but two links still pointed at ripplebiz/MeshCore: the GitHub Issues link in README and the git clone in the FAQ build instructions. Also fixes the FAQ build recipe: - `pio run -e RAK_4631_Repeater` does not exist; the env is spelled RAK_4631_repeater (variants/rak4631/platformio.ini:40). - LORA_FREQ was given as 867.5; the default in [arduino_base] is 869.618 (platformio.ini:29). Reworded to point at the flag rather than a value that drifts with the default preset. - Renamed the venv so it no longer collides with the cloned directory name. And one more env-name casing slip in the Raspberry Pi flashing instructions: `Heltec_V3_companion_radio_ble` should be `Heltec_v3_...`. Release artifacts are named directly from the env name (build.sh:147), and the two neighbouring examples in the same block already use the lowercase spelling. --- README.md | 2 +- docs/faq.md | 18 +++++++++--------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index af56aaf3..6cc45d7f 100644 --- a/README.md +++ b/README.md @@ -123,6 +123,6 @@ There are a number of fairly major features in the pipeline, with no particular ## 📞 Get Support -- Report bugs and request features on the [GitHub Issues](https://github.com/ripplebiz/MeshCore/issues) page. +- Report bugs and request features on the [GitHub Issues](https://github.com/meshcore-dev/meshcore/issues) page. - Find additional guides and components on [my site](https://buymeacoffee.com/ripplebiz). - Join [MeshCore Discord](https://meshcore.gg) to chat with the developers and get help from the community. diff --git a/docs/faq.md b/docs/faq.md index c7d7a118..ade59bf0 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -537,18 +537,18 @@ Mac: python3 should be already installed. Then it should be the same for all platforms: ``` -python3 -m venv meshcore -cd meshcore && source bin/activate +python3 -m venv meshcore-venv +cd meshcore-venv && source bin/activate pip install -U platformio -git clone https://github.com/ripplebiz/MeshCore.git -cd MeshCore +git clone https://github.com/meshcore-dev/meshcore.git +cd meshcore ``` -open platformio.ini and in `[arduino_base]` edit the `LORA_FREQ=867.5` -save, then run: +open platformio.ini and in `[arduino_base]` edit `LORA_FREQ` (it defaults to +`869.618`) to the frequency for your region, save, then run: ``` -pio run -e RAK_4631_Repeater +pio run -e RAK_4631_repeater ``` -then you'll find `firmware.zip` in `.pio/build/RAK_4631_Repeater` +then you'll find `firmware.zip` in `.pio/build/RAK_4631_repeater` ### 5.10. Q: Are there other MeshCore related open source projects? @@ -592,7 +592,7 @@ For ESP-based devices (e.g. Heltec V3) you need: 1. Download the firmware file from <https://flasher.meshcore.io>. - Go to the website in a browser and find the section that has the firmware you need. - Click the Download button, right-click on the file you need, for example: - - `Heltec_V3_companion_radio_ble-v1.7.1-165fb33.bin` + - `Heltec_v3_companion_radio_ble-v1.7.1-165fb33.bin` - Non-merged bin keeps the existing Bluetooth pairing database. - `Heltec_v3_companion_radio_usb-v1.7.1-165fb33-merged.bin` - Merged bin overwrites everything including the bootloader and existing Bluetooth pairing database, but keeps configurations. From 90c6be0cbff9e0c469ec6ad4fd6f88b296da8c53 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Thu, 3 Sep 2026 14:09:15 +1000 Subject: [PATCH 179/381] * default and reply scopes now applied --- examples/simple_sensor/SensorMesh.cpp | 76 ++++++++++++++++++++++----- examples/simple_sensor/SensorMesh.h | 6 +++ 2 files changed, 69 insertions(+), 13 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 23d0cdc3..287a3c1b 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -1,4 +1,5 @@ #include "SensorMesh.h" +#include <helpers/RoutingPolicy.h> /* ------------------------------ Config -------------------------------- */ @@ -262,7 +263,7 @@ void SensorMesh::sendAlert(const ClientInfo* c, Trigger* t) { sendDirect(pkt, c->out_path, c->out_path_len); } else { unsigned long delay_millis = 0; - sendFlood(pkt, delay_millis, _prefs.path_hash_mode + 1); + sendFloodScoped(default_scope, pkt, delay_millis, _prefs.path_hash_mode + 1); } } t->send_expiry = futureMillis(ALERT_ACK_EXPIRY_MILLIS); @@ -400,10 +401,11 @@ void SensorMesh::handleCommand(uint32_t sender_timestamp, char* command, char* r if (sp == NULL) { strcpy(reply, "Err - bad params"); } else { + int hex_len = min(sp - hex, PUB_KEY_SIZE*2); + uint8_t pubkey[PUB_KEY_SIZE]; + *sp++ = 0; // replace space with null terminator - uint8_t pubkey[PUB_KEY_SIZE]; - int hex_len = min(sp - hex, PUB_KEY_SIZE*2); if (mesh::Utils::fromHex(pubkey, hex_len / 2, hex)) { uint8_t perms = atoi(sp); if (acl.applyPermissions(self_id, pubkey, hex_len / 2, perms)) { @@ -451,6 +453,21 @@ void SensorMesh::handleCommand(uint32_t sender_timestamp, char* command, char* r } } +mesh::DispatcherAction SensorMesh::onRecvPacket(mesh::Packet* pkt) { + if (pkt->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD) { + recv_pkt_region = region_map.findMatch(pkt, REGION_DENY_FLOOD); + } else if (pkt->getRouteType() == ROUTE_TYPE_FLOOD) { + if (region_map.getWildcard().flags & REGION_DENY_FLOOD) { + recv_pkt_region = NULL; + } else { + recv_pkt_region = ®ion_map.getWildcard(); + } + } else { + recv_pkt_region = NULL; + } + return Mesh::onRecvPacket(pkt); +} + void SensorMesh::onAnonDataRecv(mesh::Packet* packet, const uint8_t* secret, const mesh::Identity& sender, uint8_t* data, size_t len) { if (packet->getPayloadType() == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin client (unknown at this stage) uint32_t timestamp; @@ -472,10 +489,10 @@ void SensorMesh::onAnonDataRecv(mesh::Packet* packet, const uint8_t* secret, con // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response mesh::Packet* path = createPathReturn(sender, secret, packet->path, packet->path_len, PAYLOAD_TYPE_RESPONSE, reply_data, reply_len); - if (path) sendFlood(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize()); + if (path) sendFloodReply(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize()); } else { mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len); - if (reply) sendFlood(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize()); + if (reply) sendFloodReply(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize()); } } } @@ -503,7 +520,7 @@ void SensorMesh::getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) { void SensorMesh::sendAckTo(const ClientInfo& dest, uint32_t ack_hash, uint8_t path_hash_size) { if (dest.out_path_len == OUT_PATH_UNKNOWN) { mesh::Packet* ack = createAck(ack_hash); - if (ack) sendFlood(ack, TXT_ACK_DELAY, path_hash_size); + if (ack) sendFloodScoped(default_scope, ack, TXT_ACK_DELAY, path_hash_size); } else { uint32_t d = TXT_ACK_DELAY; if (getExtraAckTransmitCount() > 0) { @@ -541,14 +558,14 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response mesh::Packet* path = createPathReturn(from->id, secret, packet->path, packet->path_len, PAYLOAD_TYPE_RESPONSE, reply_data, reply_len); - if (path) sendFlood(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize()); + if (path) sendFloodReply(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize()); } else { mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, from->id, secret, reply_data, reply_len); if (reply) { if (from->out_path_len != OUT_PATH_UNKNOWN) { // we have an out_path, so send DIRECT sendDirect(reply, from->out_path, from->out_path_len, SERVER_RESPONSE_DELAY); } else { - sendFlood(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize()); + sendFloodReply(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize()); } } } @@ -571,7 +588,7 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the ACK mesh::Packet* path = createPathReturn(from->id, secret, packet->path, packet->path_len, PAYLOAD_TYPE_ACK, (uint8_t *) &ack_hash, 4); - if (path) sendFlood(path, TXT_ACK_DELAY, packet->getPathHashSize()); + if (path) sendFloodReply(path, TXT_ACK_DELAY, packet->getPathHashSize()); } else { sendAckTo(*from, ack_hash, packet->getPathHashSize()); } @@ -601,7 +618,7 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, from->id, secret, temp, 5 + text_len); if (reply) { if (from->out_path_len == OUT_PATH_UNKNOWN) { - sendFlood(reply, CLI_REPLY_DELAY_MILLIS, packet->getPathHashSize()); + sendFloodReply(reply, CLI_REPLY_DELAY_MILLIS, packet->getPathHashSize()); } else { sendDirect(reply, from->out_path, from->out_path_len, CLI_REPLY_DELAY_MILLIS); } @@ -708,6 +725,7 @@ SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::Millise last_read_time = 0; num_alert_tasks = 0; set_radio_at = revert_radio_at = 0; + recv_pkt_region = NULL; // defaults _prefs.airtime_factor = 1.0; @@ -820,11 +838,43 @@ void SensorMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t revert_radio_at = futureMillis(2000 + timeout_mins*60*1000); // schedule when to revert radio params } +void SensorMesh::sendFloodScoped(const TransportKey& scope, mesh::Packet* pkt, uint32_t delay_millis, uint8_t path_hash_size) { + if (scope.isNull()) { + sendFlood(pkt, delay_millis, path_hash_size); + } else { + uint16_t codes[2]; + codes[0] = scope.calcTransportCode(pkt); + codes[1] = 0; // REVISIT: set to 'home' Region, for sender/return region? + sendFlood(pkt, codes, delay_millis, path_hash_size); + } +} + +void SensorMesh::sendFloodReply(mesh::Packet* packet, unsigned long delay_millis, uint8_t path_hash_size) { + TransportKey req_scope; + bool is_wildcard = recv_pkt_region != NULL && recv_pkt_region->isWildcard(); + bool req_scope_known = recv_pkt_region != NULL && !is_wildcard + && region_map.getTransportKeysFor(*recv_pkt_region, &req_scope, 1) > 0; + + switch (mesh::chooseReplyScope(req_scope_known, is_wildcard, !default_scope.isNull())) { + case mesh::REPLY_SCOPE_REQUEST: + sendFloodScoped(req_scope, packet, delay_millis, path_hash_size); // reply with same scope as request + break; + case mesh::REPLY_SCOPE_DEFAULT: + // requester's scope is unknown: DIRECT request (no transport codes), or code matched no Region. + // un-scoped would be dropped at hop 0 by repeaters running flood.max.unscoped=0 + sendFloodScoped(default_scope, packet, delay_millis, path_hash_size); + break; + case mesh::REPLY_SCOPE_NONE: + sendFlood(packet, delay_millis, path_hash_size); // send un-scoped + break; + } +} + void SensorMesh::sendSelfAdvertisement(int delay_millis, bool flood) { mesh::Packet* pkt = createSelfAdvert(); if (pkt) { if (flood) { - sendFlood(pkt, delay_millis, _prefs.path_hash_mode + 1); + sendFloodScoped(default_scope, pkt, delay_millis, _prefs.path_hash_mode + 1); } else { sendZeroHop(pkt, delay_millis); } @@ -902,7 +952,7 @@ void SensorMesh::loop() { if (next_flood_advert && millisHasNowPassed(next_flood_advert)) { mesh::Packet* pkt = createSelfAdvert(); unsigned long delay_millis = 0; - if (pkt) sendFlood(pkt, delay_millis, _prefs.path_hash_mode + 1); + if (pkt) sendFloodScoped(default_scope, pkt, delay_millis, _prefs.path_hash_mode + 1); updateFloodAdvertTimer(); // schedule next flood advert updateAdvertTimer(); // also schedule local advert (so they don't overlap) @@ -973,7 +1023,7 @@ void SensorMesh::loop() { } } - // is there are pending dirty contacts write needed? + // pending dirty contacts write needed? if (dirty_contacts_expiry && millisHasNowPassed(dirty_contacts_expiry)) { acl.save(_fs); dirty_contacts_expiry = 0; diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index b5e96d5c..845402ba 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -81,6 +81,9 @@ public: float getTelemValue(uint8_t channel, uint8_t type); + void sendFloodScoped(const TransportKey& scope, mesh::Packet* pkt, uint32_t delay_millis, uint8_t path_hash_size); + void sendFloodReply(mesh::Packet* packet, unsigned long delay_millis, uint8_t path_hash_size); + protected: // current telemetry data queries float getVoltage(uint8_t channel) { return getTelemValue(channel, LPP_VOLTAGE); } @@ -122,6 +125,7 @@ protected: int getInterferenceThreshold() const override; bool getCADEnabled() const override; int getAGCResetInterval() const override; + mesh::DispatcherAction onRecvPacket(mesh::Packet* pkt) override; void onAnonDataRecv(mesh::Packet* packet, const uint8_t* secret, const mesh::Identity& sender, uint8_t* data, size_t len) override; int searchPeersByHash(const uint8_t* hash) override; void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override; @@ -129,6 +133,7 @@ protected: bool onPeerPathRecv(mesh::Packet* packet, int sender_idx, const uint8_t* secret, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) override; void onControlDataRecv(mesh::Packet* packet) override; void onAckRecv(mesh::Packet* packet, uint32_t ack_crc) override; + virtual bool handleIncomingMsg(ClientInfo& from, uint32_t timestamp, uint8_t* data, uint8_t flags, size_t len); void sendAckTo(const ClientInfo& dest, uint32_t ack_hash, uint8_t path_hash_size=1); private: @@ -142,6 +147,7 @@ private: CayenneLPP telemetry; TransportKeyStore key_store; RegionMap region_map; + RegionEntry* recv_pkt_region; TransportKey default_scope; uint32_t last_read_time; int matching_peer_indexes[MAX_SEARCH_RESULTS]; From 7624acb28af13aa73b208496aec871647b8cb541 Mon Sep 17 00:00:00 2001 From: Quency-D <hj_zzns@163.com> Date: Thu, 3 Sep 2026 17:57:09 +0800 Subject: [PATCH 180/381] fix-heltec_v4r8-lna --- variants/heltec_v4_r8/HeltecV4R8Board.cpp | 58 +++++++++++++++++++++++ variants/heltec_v4_r8/HeltecV4R8Board.h | 7 +++ variants/heltec_v4_r8/LoRaFEMControl.h | 1 + 3 files changed, 66 insertions(+) diff --git a/variants/heltec_v4_r8/HeltecV4R8Board.cpp b/variants/heltec_v4_r8/HeltecV4R8Board.cpp index 1fb123b2..ea2cfbed 100644 --- a/variants/heltec_v4_r8/HeltecV4R8Board.cpp +++ b/variants/heltec_v4_r8/HeltecV4R8Board.cpp @@ -84,3 +84,61 @@ const char* HeltecV4R8Board::getManufacturerName() const { return "Heltec V4 R8 OLED"; #endif } + +bool HeltecV4R8Board::setLoRaFemLnaEnabled(bool enable) { + if (!loRaFEMControl.isLnaCanControl()) { + return false; + } + + loRaFEMControl.setLNAEnable(enable); + loRaFEMControl.setRxModeEnable(); + return true; +} + +bool HeltecV4R8Board::isLoRaFemLnaEnabled() const { + return loRaFEMControl.isLNAEnabled(); +} + +void HeltecV4R8Board::attachDynamicPrefs(KeyValueStore* prefs) { + _prefs = prefs; + + char radio_fem_rxgain[8] = { 0 }; + _prefs->getByKey("fem_rxgain", radio_fem_rxgain, 7); // get initial values + + setLoRaFemLnaEnabled(strcmp(radio_fem_rxgain, "1") == 0); +} + +bool HeltecV4R8Board::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { + if (strcmp(command, "get radio.fem.rxgain") == 0) { + if (!loRaFEMControl.isLnaCanControl()) { + strcpy(reply, "Error: unsupported"); + } else { + sprintf(reply, "> %s", isLoRaFemLnaEnabled() ? "on" : "off"); + } + return true; + } + if (memcmp(command, "set radio.fem.rxgain ", 21) == 0) { + if (!loRaFEMControl.isLnaCanControl()) { + strcpy(reply, "Error: unsupported"); + } else if (memcmp(&command[21], "on", 2) == 0) { + if (setLoRaFemLnaEnabled(true)) { + _prefs->setByKey("fem_rxgain", "1"); + strcpy(reply, "OK - LoRa FEM RX gain on"); + } else { + strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); + } + } else if (memcmp(&command[21], "off", 3) == 0) { + if (setLoRaFemLnaEnabled(false)) { + _prefs->setByKey("fem_rxgain", "0"); + strcpy(reply, "OK - LoRa FEM RX gain off"); + } else { + strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); + } + } else { + strcpy(reply, "Error: state must be on or off"); + } + return true; + } + + return false; // not handled +} diff --git a/variants/heltec_v4_r8/HeltecV4R8Board.h b/variants/heltec_v4_r8/HeltecV4R8Board.h index 20811abb..7ab29f96 100644 --- a/variants/heltec_v4_r8/HeltecV4R8Board.h +++ b/variants/heltec_v4_r8/HeltecV4R8Board.h @@ -11,6 +11,10 @@ #endif class HeltecV4R8Board : public ESP32Board { + KeyValueStore* _prefs = NULL; + + bool setLoRaFemLnaEnabled(bool enable); + bool isLoRaFemLnaEnabled() const; protected: float adc_mult = ADC_MULTIPLIER; @@ -21,6 +25,9 @@ public: HeltecV4R8Board() : periph_power(PIN_VEXT_EN, PIN_VEXT_EN_ACTIVE) { } void begin(); + void attachDynamicPrefs(KeyValueStore* prefs); + bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; + void onBeforeTransmit(void) override; void onAfterTransmit(void) override; void enterDeepSleep(uint32_t secs, int pin_wake_btn = -1); diff --git a/variants/heltec_v4_r8/LoRaFEMControl.h b/variants/heltec_v4_r8/LoRaFEMControl.h index 961cfd07..4b74c2e2 100644 --- a/variants/heltec_v4_r8/LoRaFEMControl.h +++ b/variants/heltec_v4_r8/LoRaFEMControl.h @@ -17,6 +17,7 @@ public: void setLNAEnable(bool enabled); bool isLnaCanControl(void) { return true; } void setLnaCanControl(bool can_control) { } + bool isLNAEnabled(void) const { return lna_enabled; } LoRaFEMType getFEMType(void) const { return KCT8103L_PA; } private: From fa0c7b8a5a090ae5dea076300a2d4274a9bd84ef Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Fri, 4 Sep 2026 15:13:17 +1000 Subject: [PATCH 181/381] * new: REQ_TYPE_SUBSCRIBE and REQ_TYPE_UNSUBSCRIBE --- examples/simple_sensor/SensorMesh.cpp | 124 ++++++++++++++++++++++---- examples/simple_sensor/SensorMesh.h | 9 +- src/helpers/ClientACL.h | 5 ++ 3 files changed, 116 insertions(+), 22 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 287a3c1b..0a78f5da 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -55,6 +55,8 @@ #define REQ_TYPE_GET_TELEMETRY_DATA 0x03 #define REQ_TYPE_GET_AVG_MIN_MAX 0x04 #define REQ_TYPE_GET_ACCESS_LIST 0x05 +#define REQ_TYPE_SUBSCRIBE 0x10 +#define REQ_TYPE_UNSUBSCRIBE 0x11 #define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ @@ -74,6 +76,8 @@ static File openAppend(FILESYSTEM* _fs, const char* fname) { #endif } +/* --------------------- Cayenne LPP helpers ----------------------------*/ + static uint8_t getDataSize(uint8_t type) { switch (type) { case LPP_GPS: @@ -171,7 +175,53 @@ static uint8_t putFloat(uint8_t * dest, float value, uint8_t size, uint32_t mult return size; } -uint8_t SensorMesh::handleRequest(uint8_t perms, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len) { +static float findTelemValue(const uint8_t* buf, uint8_t size, uint8_t channel, uint8_t type) { + uint8_t i = 0; + + while (i + 2 < size) { + // Get channel # + uint8_t ch = buf[i++]; + // Get data type + uint8_t t = buf[i++]; + uint8_t sz = getDataSize(t); + + if (ch == channel && t == type) { + return getFloat(&buf[i], sz, getMultiplier(t), isSigned(t)); + } + i += sz; // skip + } + return 0.0f; // not found +} + +/* ------------------ end Cayenne LPP helpers ----------------------*/ + +bool SensorMesh::telemHasChanged(const uint8_t* min_deltas, uint8_t min_deltas_len) { + if (telemetry.getSize() != prev_telem_size) return true; + + auto buf = telemetry.getBuffer(); + uint8_t size = telemetry.getSize(); + uint8_t i = 0; + + while (i + 2 < size) { + // Get channel # + uint8_t ch = buf[i++]; + // Get data type + uint8_t t = buf[i++]; + uint8_t sz = getDataSize(t); + + float v = getFloat(&buf[i], sz, getMultiplier(t), isSigned(t)); + float pv = getFloat(&prev_telem[i], sz, getMultiplier(t), isSigned(t)); + float min_delta = findTelemValue(min_deltas, min_deltas_len, ch, t); + if (abs(v - pv) > min_delta) return true; // Yes, has changed + + i += sz; // skip + } + return false; // no changes +} + +uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len) { + uint8_t perms = from->isAdmin() ? 0xFF : from->permissions; + memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag') if (req_type == REQ_TYPE_GET_TELEMETRY_DATA) { // allow all @@ -235,6 +285,29 @@ uint8_t SensorMesh::handleRequest(uint8_t perms, uint32_t sender_timestamp, uint return ofs; } } + if (req_type == REQ_TYPE_SUBSCRIBE && payload_len >= 2 && (perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { + uint8_t reserved = payload[0]; + RegionEntry* r; + if (recv_pkt_region && !recv_pkt_region->isWildcard()) { // use request scope + r = recv_pkt_region; + } else { // use default scope + r = region_map.getDefaultRegion(); + } + from->extra.sensor.scope_region_id = r ? r->id : 0; + from->extra.sensor.min_deltas_len = payload[1]; + // NOTE: curr impl truncates LPP min_diffs spec (re-do if better impl is needed) + memcpy(from->extra.sensor.min_deltas, &payload[2], min(sizeof(from->extra.sensor.min_deltas), (size_t)payload[1])); + + getRNG()->random(&reply_data[4], 2); // just some entropy for better packet-hash uniqueness + strcpy((char *)&reply_data[6], r ? r->name : ""); // reply with name of scope that will be used + return 6 + strlen((char *)&reply_data[6]); + } + if (req_type == REQ_TYPE_UNSUBSCRIBE && (perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { + from->extra.sensor.scope_region_id = 0; + reply_data[4] = 0; // success + getRNG()->random(&reply_data[5], 3); // just some entropy for better packet-hash uniqueness + return 8; + } return 0; // unknown command } @@ -548,7 +621,7 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i memcpy(×tamp, data, 4); if (timestamp > from->last_timestamp) { // prevent replay attacks - uint8_t reply_len = handleRequest(from->isAdmin() ? 0xFF : from->permissions, timestamp, data[4], &data[5], len - 5); + uint8_t reply_len = handleRequest(from, timestamp, data[4], &data[5], len - 5); if (reply_len == 0) return; // invalid command from->last_timestamp = timestamp; @@ -726,6 +799,7 @@ SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::Millise num_alert_tasks = 0; set_radio_at = revert_radio_at = 0; recv_pkt_region = NULL; + prev_telem_size = 0; // defaults _prefs.airtime_factor = 1.0; @@ -916,23 +990,7 @@ void SensorMesh::formatPacketStatsReply(char *reply) { } float SensorMesh::getTelemValue(uint8_t channel, uint8_t type) { - auto buf = telemetry.getBuffer(); - uint8_t size = telemetry.getSize(); - uint8_t i = 0; - - while (i + 2 < size) { - // Get channel # - uint8_t ch = buf[i++]; - // Get data type - uint8_t t = buf[i++]; - uint8_t sz = getDataSize(t); - - if (ch == channel && t == type) { - return getFloat(&buf[i], sz, getMultiplier(t), isSigned(t)); - } - i += sz; // skip - } - return 0.0f; // not found + return findTelemValue(telemetry.getBuffer(), telemetry.getSize(), channel, type); } bool SensorMesh::getGPS(uint8_t channel, float& lat, float& lon, float& alt) { @@ -982,6 +1040,34 @@ void SensorMesh::loop() { // query other sensors -- target specific sensors.querySensors(0xFF, telemetry); // allow all telemetry permissions + // compare with previous telemetry, check if any deltas are greater than subscriber minimums + for (int i = 0; i < acl.getNumClients(); i++) { + auto c = acl.getClientByIdx(i); + if (c->permissions == 0 || c->extra.sensor.scope_region_id == 0) continue; // skip deleted entries, or Not subscribed to deltas + RegionEntry* r = region_map.findById(c->extra.sensor.scope_region_id); + if (r == NULL) continue; // unknown region scope + if (telemHasChanged(c->extra.sensor.min_deltas, c->extra.sensor.min_deltas_len)) { + TransportKey scope; + if (region_map.getTransportKeysFor(*r, &scope, 1) > 0) { + uint8_t tlen = telemetry.getSize(); + uint32_t timestamp = getRTCClock()->getCurrentTimeUnique(); // this will be an unknown 'tag' to the client + memcpy(reply_data, ×tamp, 4); + memcpy(&reply_data[4], telemetry.getBuffer(), tlen); + + mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, c->id, c->shared_secret, reply_data, 4 + tlen); + if (reply) { + if (c->out_path_len != OUT_PATH_UNKNOWN) { // we have an out_path, so send DIRECT + sendDirect(reply, c->out_path, c->out_path_len, 0); + } else { + sendFloodScoped(scope, reply, 0, _prefs.path_hash_mode + 1); + } + } + } + } + } + memcpy(prev_telem, telemetry.getBuffer(), telemetry.getSize()); // save snapshot for next compare cycle + prev_telem_size = telemetry.getSize(); + onSensorDataRead(); last_read_time = curr; diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index 845402ba..7ea87f20 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -96,12 +96,12 @@ protected: bool getGPS(uint8_t channel, float& lat, float& lon, float& alt); // alerts - enum AlertPriority { LOW_PRI_ALERT, HIGH_PRI_ALERT }; + enum AlertPriority : uint8_t { LOW_PRI_ALERT, HIGH_PRI_ALERT }; struct Trigger { uint32_t timestamp; - AlertPriority pri; uint32_t expected_acks[4]; + AlertPriority pri; int8_t curr_contact_idx; uint8_t attempt; unsigned long send_expiry; @@ -145,6 +145,8 @@ private: uint8_t reply_data[MAX_PACKET_PAYLOAD]; unsigned long dirty_contacts_expiry; CayenneLPP telemetry; + uint8_t prev_telem_size; + uint8_t prev_telem[MAX_PACKET_PAYLOAD - 4]; TransportKeyStore key_store; RegionMap region_map; RegionEntry* recv_pkt_region; @@ -159,8 +161,9 @@ private: uint8_t pending_sf; uint8_t pending_cr; + bool telemHasChanged(const uint8_t* min_deltas, uint8_t min_deltas_len); uint8_t handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data, bool is_flood); - uint8_t handleRequest(uint8_t perms, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len); + uint8_t handleRequest(ClientInfo* from, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len); mesh::Packet* createSelfAdvert(); void sendAlert(const ClientInfo* c, Trigger* t); diff --git a/src/helpers/ClientACL.h b/src/helpers/ClientACL.h index e0654464..9fde35ec 100644 --- a/src/helpers/ClientACL.h +++ b/src/helpers/ClientACL.h @@ -28,6 +28,11 @@ struct ClientInfo { unsigned long ack_timeout; uint8_t push_failures; } room; + struct { + uint16_t scope_region_id; // scope to use when sending telemetry to this client/subscriber + uint8_t min_deltas_len; + uint8_t min_deltas[14]; // LPP encoded + } sensor; } extra; bool isAdmin() const { return (permissions & PERM_ACL_ROLE_MASK) == PERM_ACL_ADMIN; } From 595bf44beb89ae458772afac54ba31e922951ae3 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Fri, 4 Sep 2026 22:02:49 +1000 Subject: [PATCH 182/381] * sensor: CLI "sub" and "unsub" commands --- examples/simple_sensor/SensorMesh.cpp | 68 ++++++++++++++++++++++++++- examples/simple_sensor/SensorMesh.h | 2 +- examples/simple_sensor/main.cpp | 2 +- 3 files changed, 68 insertions(+), 4 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 0a78f5da..008cbcfc 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -193,6 +193,43 @@ static float findTelemValue(const uint8_t* buf, uint8_t size, uint8_t channel, u return 0.0f; // not found } +static uint8_t compileLPPSpec(char* txt, uint8_t* dest, size_t max_len) { + const char* parts[3]; + int n = mesh::Utils::parseTextParts(txt, parts, 3, ','); + uint8_t len = 0; + for (int i = 0; i < n && len + 6 <= max_len; i++) { + const char* cp = strchr(parts[i], ':'); + if (cp) { + uint8_t t; + float factor = 1.0f; + cp++; // skip the ':' + char* ep = strchr(cp, 0) - 1; // find LAST char + if (*ep == 'V') { // Volts + t = LPP_VOLTAGE; + } else if (*ep == 'W') { // Watts + t = LPP_POWER; + } else if (*ep == 'C') { // Celcius + t = LPP_TEMPERATURE; + } else if (*ep == 'P') { // Pascals + t = LPP_BAROMETRIC_PRESSURE; + } else if (*ep == 'A') { // Amps + t = LPP_CURRENT; + } else if (*ep == 'm') { + t = LPP_DISTANCE; factor = 0.001f; + } else { + t = 0; + } + + if (t) { + dest[len++] = atoi(parts[i]); // channel number + dest[len++] = t; // LPP type + len += putFloat(&dest[len], atof(cp) * factor, getDataSize(t), getMultiplier(t), isSigned(t)); + } + } + } + return len; +} + /* ------------------ end Cayenne LPP helpers ----------------------*/ bool SensorMesh::telemHasChanged(const uint8_t* min_deltas, uint8_t min_deltas_len) { @@ -453,7 +490,7 @@ uint8_t SensorMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* return 13; // reply length } -void SensorMesh::handleCommand(uint32_t sender_timestamp, char* command, char* reply) { +void SensorMesh::handleCommand(ClientInfo* from, uint32_t sender_timestamp, char* command, char* reply) { while (*command == ' ') command++; // skip leading spaces if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI) @@ -502,6 +539,33 @@ void SensorMesh::handleCommand(uint32_t sender_timestamp, char* command, char* r Serial.printf("\n"); } reply[0] = 0; + } else if (from != NULL && memcmp(command, "sub", 3) == 0 && (command[3] == ' ' || command[3] == 0)) { // subscribe + uint8_t perms = from->isAdmin() ? 0xFF : from->permissions; + if ((perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { + RegionEntry* r; + if (recv_pkt_region && !recv_pkt_region->isWildcard()) { // use request scope + r = recv_pkt_region; + } else { // use default scope + r = region_map.getDefaultRegion(); + } + if (command[3] == ' ') { + // compile params as LPP data, eg. "sub 1:0.2V" + from->extra.sensor.min_deltas_len = compileLPPSpec(&command[4], from->extra.sensor.min_deltas, sizeof(from->extra.sensor.min_deltas)); + } else { + from->extra.sensor.min_deltas_len = 0; // no minimums (telemetry just needs to CHANGE) + } + from->extra.sensor.scope_region_id = r ? r->id : 0; + if (from->extra.sensor.scope_region_id) { + strcpy(reply, "OK - subscribed"); + } else { + strcpy(reply, "Err - region scope needed"); + } + } else { + strcpy(reply, "Err - no permission"); + } + } else if (from != NULL && strcmp(command, "unsub") == 0) { // unsubscribe + from->extra.sensor.scope_region_id = 0; + strcpy(reply, "OK - unsubscribed"); } else if (memcmp(command, "io ", 2) == 0) { // io {value}: write, io: read if (command[2] == ' ') { // it's a write uint32_t val; @@ -676,7 +740,7 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i uint8_t temp[166]; char *command = (char *) &data[5]; char *reply = (char *) &temp[5]; - handleCommand(sender_timestamp, command, reply); + handleCommand(from, sender_timestamp, command, reply); int text_len = strlen(reply); if (text_len > 0) { diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index 7ea87f20..6d5857d0 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -51,7 +51,7 @@ public: SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables); void begin(FILESYSTEM* fs); void loop(); - void handleCommand(uint32_t sender_timestamp, char* command, char* reply); + void handleCommand(ClientInfo* from, uint32_t sender_timestamp, char* command, char* reply); // CommonCLI callbacks const char* getFirmwareVer() override { return FIRMWARE_VERSION; } diff --git a/examples/simple_sensor/main.cpp b/examples/simple_sensor/main.cpp index 69182f3a..9e3b230b 100644 --- a/examples/simple_sensor/main.cpp +++ b/examples/simple_sensor/main.cpp @@ -137,7 +137,7 @@ void loop() { if (len > 0 && command[len - 1] == '\r') { // received complete line command[len - 1] = 0; // replace newline with C string null terminator char reply[160]; - the_mesh.handleCommand(0, command, reply); // NOTE: there is no sender_timestamp via serial! + the_mesh.handleCommand(NULL, 0, command, reply); // NOTE: there is no sender_timestamp via serial! if (reply[0]) { Serial.print(" -> "); Serial.println(reply); } From dbb2aeee0062f41c5f694ad16d3e3ad6e857c144 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Br=C3=A1zio?= <jbrazio@gmail.com> Date: Thu, 16 Jul 2026 19:59:12 +0000 Subject: [PATCH 183/381] Ensure command buffers stay NUL-terminated to prevent overflow The serial command buffers must stay NUL-terminated within their bounds: if they ever aren't, strlen() can return >= sizeof(command) and the read loop would index past the buffer. Additionally, a full buffer now becomes a completed line (end-of-line marker placed inside the buffer, NUL terminator kept) instead of overwriting the terminator and silently corrupting the buffer for the next pass. Applies to the serial CLI readers of the repeater, room server, sensor and secure chat examples, and to the CLI rescue reader of the companion example. --- examples/companion_radio/MyMesh.cpp | 12 ++++++++++-- examples/simple_repeater/main.cpp | 12 ++++++++++-- examples/simple_room_server/main.cpp | 12 ++++++++++-- examples/simple_secure_chat/main.cpp | 12 ++++++++++-- examples/simple_sensor/main.cpp | 12 ++++++++++-- 5 files changed, 50 insertions(+), 10 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index ee8114ca..b4e51514 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2187,6 +2187,13 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* void MyMesh::checkCLIRescueCmd() { int len = strlen(cli_command); + // `cli_command` must stay NUL-terminated within its bounds. If it ever isn't, + // strlen() above can return >= sizeof(cli_command) and the loop below would + // then index past the buffer, so clamp defensively. + if (len >= (int)sizeof(cli_command)) { + cli_command[0] = 0; + len = 0; + } while (Serial.available() && len < sizeof(cli_command)-1) { char c = Serial.read(); if (c != '\n') { @@ -2195,8 +2202,9 @@ void MyMesh::checkCLIRescueCmd() { } Serial.print(c); // echo } - if (len == sizeof(cli_command)-1) { // command buffer full - cli_command[sizeof(cli_command)-1] = '\r'; + if (len == sizeof(cli_command)-1) { // buffer full: treat as a completed line + cli_command[sizeof(cli_command)-2] = '\r'; // place end-of-line marker inside the buffer + cli_command[sizeof(cli_command)-1] = 0; // keep the buffer NUL-terminated } if (len > 0 && cli_command[len - 1] == '\r') { // received complete line diff --git a/examples/simple_repeater/main.cpp b/examples/simple_repeater/main.cpp index a714db68..1f71da74 100644 --- a/examples/simple_repeater/main.cpp +++ b/examples/simple_repeater/main.cpp @@ -125,6 +125,13 @@ void setup() { void loop() { // Handle Serial CLI int len = strlen(command); + // `command` must stay NUL-terminated within its bounds. If it ever isn't, + // strlen() above can return >= sizeof(command) and the loop below would then + // index past the buffer, so clamp defensively. + if (len >= (int)sizeof(command)) { + command[0] = 0; + len = 0; + } while (Serial.available() && len < sizeof(command)-1) { char c = Serial.read(); if (c != '\n') { @@ -134,8 +141,9 @@ void loop() { } if (c == '\r') break; } - if (len == sizeof(command)-1) { // command buffer full - command[sizeof(command)-1] = '\r'; + if (len == sizeof(command)-1) { // buffer full: treat as a completed line + command[sizeof(command)-2] = '\r'; // place end-of-line marker inside the buffer + command[sizeof(command)-1] = 0; // keep the buffer NUL-terminated } if (len > 0 && command[len - 1] == '\r') { // received complete line diff --git a/examples/simple_room_server/main.cpp b/examples/simple_room_server/main.cpp index d833fff3..227ee2cb 100644 --- a/examples/simple_room_server/main.cpp +++ b/examples/simple_room_server/main.cpp @@ -105,6 +105,13 @@ void setup() { void loop() { int len = strlen(command); + // `command` must stay NUL-terminated within its bounds. If it ever isn't, + // strlen() above can return >= sizeof(command) and the loop below would then + // index past the buffer, so clamp defensively. + if (len >= (int)sizeof(command)) { + command[0] = 0; + len = 0; + } while (Serial.available() && len < sizeof(command)-1) { char c = Serial.read(); if (c != '\n') { @@ -113,8 +120,9 @@ void loop() { } Serial.print(c); } - if (len == sizeof(command)-1) { // command buffer full - command[sizeof(command)-1] = '\r'; + if (len == sizeof(command)-1) { // buffer full: treat as a completed line + command[sizeof(command)-2] = '\r'; // place end-of-line marker inside the buffer + command[sizeof(command)-1] = 0; // keep the buffer NUL-terminated } if (len > 0 && command[len - 1] == '\r') { // received complete line diff --git a/examples/simple_secure_chat/main.cpp b/examples/simple_secure_chat/main.cpp index 159249df..2e6ba712 100644 --- a/examples/simple_secure_chat/main.cpp +++ b/examples/simple_secure_chat/main.cpp @@ -530,6 +530,13 @@ public: BaseChatMesh::loop(); int len = strlen(command); + // `command` must stay NUL-terminated within its bounds. If it ever isn't, + // strlen() above can return >= sizeof(command) and the loop below would then + // index past the buffer, so clamp defensively. + if (len >= (int)sizeof(command)) { + command[0] = 0; + len = 0; + } while (Serial.available() && len < sizeof(command)-1) { char c = Serial.read(); if (c != '\n') { @@ -538,8 +545,9 @@ public: } Serial.print(c); } - if (len == sizeof(command)-1) { // command buffer full - command[sizeof(command)-1] = '\r'; + if (len == sizeof(command)-1) { // buffer full: treat as a completed line + command[sizeof(command)-2] = '\r'; // place end-of-line marker inside the buffer + command[sizeof(command)-1] = 0; // keep the buffer NUL-terminated } if (len > 0 && command[len - 1] == '\r') { // received complete line diff --git a/examples/simple_sensor/main.cpp b/examples/simple_sensor/main.cpp index 69182f3a..749ff6ef 100644 --- a/examples/simple_sensor/main.cpp +++ b/examples/simple_sensor/main.cpp @@ -122,6 +122,13 @@ void setup() { void loop() { int len = strlen(command); + // `command` must stay NUL-terminated within its bounds. If it ever isn't, + // strlen() above can return >= sizeof(command) and the loop below would then + // index past the buffer, so clamp defensively. + if (len >= (int)sizeof(command)) { + command[0] = 0; + len = 0; + } while (Serial.available() && len < sizeof(command)-1) { char c = Serial.read(); if (c != '\n') { @@ -130,8 +137,9 @@ void loop() { } Serial.print(c); } - if (len == sizeof(command)-1) { // command buffer full - command[sizeof(command)-1] = '\r'; + if (len == sizeof(command)-1) { // buffer full: treat as a completed line + command[sizeof(command)-2] = '\r'; // place end-of-line marker inside the buffer + command[sizeof(command)-1] = 0; // keep the buffer NUL-terminated } if (len > 0 && command[len - 1] == '\r') { // received complete line From a4d1854a779a42a468032641db771d3ef129c871 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Br=C3=A1zio?= <jbrazio@gmail.com> Date: Wed, 15 Jul 2026 08:18:59 +0000 Subject: [PATCH 184/381] Improve null checks and index validation in StaticPoolPacketManager --- src/helpers/StaticPoolPacketManager.cpp | 9 +++++++-- src/helpers/StaticPoolPacketManager.h | 5 ++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/helpers/StaticPoolPacketManager.cpp b/src/helpers/StaticPoolPacketManager.cpp index b8926df0..8a8eefe8 100644 --- a/src/helpers/StaticPoolPacketManager.cpp +++ b/src/helpers/StaticPoolPacketManager.cpp @@ -44,7 +44,7 @@ mesh::Packet* PacketQueue::get(uint32_t now) { } mesh::Packet* PacketQueue::removeByIdx(int i) { - if (i >= _num) return NULL; // invalid index + if (i < 0 || i >= _num) return NULL; // invalid index mesh::Packet* item = _table[i]; _num--; @@ -80,10 +80,14 @@ mesh::Packet* StaticPoolPacketManager::allocNew() { } void StaticPoolPacketManager::free(mesh::Packet* packet) { - unused.add(packet, 0, 0); + if (packet == NULL) return; + if (!unused.add(packet, 0, 0)) { + MESH_DEBUG_PRINTLN("free: unused queue full, possible double-free detected"); + } } void StaticPoolPacketManager::queueOutbound(mesh::Packet* packet, uint8_t priority, uint32_t scheduled_for) { + if (packet == NULL) return; if (!send_queue.add(packet, priority, scheduled_for)) { MESH_DEBUG_PRINTLN("queueOutbound: send queue full, dropping packet"); free(packet); @@ -115,6 +119,7 @@ mesh::Packet* StaticPoolPacketManager::removeOutboundByIdx(int i) { } void StaticPoolPacketManager::queueInbound(mesh::Packet* packet, uint32_t scheduled_for) { + if (packet == NULL) return; if (!rx_queue.add(packet, 0, scheduled_for)) { MESH_DEBUG_PRINTLN("queueInbound: rx queue full, dropping packet"); free(packet); diff --git a/src/helpers/StaticPoolPacketManager.h b/src/helpers/StaticPoolPacketManager.h index 59715b4e..f63700e5 100644 --- a/src/helpers/StaticPoolPacketManager.h +++ b/src/helpers/StaticPoolPacketManager.h @@ -14,7 +14,10 @@ public: bool add(mesh::Packet* packet, uint8_t priority, uint32_t scheduled_for); int count() const { return _num; } int countBefore(uint32_t now) const; - mesh::Packet* itemAt(int i) const { return _table[i]; } + mesh::Packet* itemAt(int i) const { + if (i < 0 || i >= _num) return NULL; + return _table[i]; + } mesh::Packet* removeByIdx(int i); }; From 9c592b7aceabc783671e31e852932c153499ae4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Br=C3=A1zio?= <jbrazio@gmail.com> Date: Fri, 4 Sep 2026 21:04:20 +0100 Subject: [PATCH 185/381] Add isGPSDetected() capability probe to SensorManager Lets applications know whether a GPS was actually detected (EnvironmentSensorManager reports its gps_detected state), e.g. to hide GPS-dependent UI when no receiver is attached. --- src/helpers/SensorManager.h | 1 + src/helpers/sensors/EnvironmentSensorManager.h | 1 + 2 files changed, 2 insertions(+) diff --git a/src/helpers/SensorManager.h b/src/helpers/SensorManager.h index 89a174c2..85b9a1ee 100644 --- a/src/helpers/SensorManager.h +++ b/src/helpers/SensorManager.h @@ -23,6 +23,7 @@ public: virtual const char* getSettingValue(int i) const { return NULL; } virtual bool setSettingValue(const char* name, const char* value) { return false; } virtual LocationProvider* getLocationProvider() { return NULL; } + virtual bool isGPSDetected() const { return false; } // Helper functions to manage setting by keys (useful in many places ...) const char* getSettingByKey(const char* key) { diff --git a/src/helpers/sensors/EnvironmentSensorManager.h b/src/helpers/sensors/EnvironmentSensorManager.h index 29147c89..17706cbc 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.h +++ b/src/helpers/sensors/EnvironmentSensorManager.h @@ -38,6 +38,7 @@ public: #if ENV_INCLUDE_GPS EnvironmentSensorManager(LocationProvider &location): _location(&location){}; LocationProvider* getLocationProvider() { return _location; } + bool isGPSDetected() const override { return gps_detected; } #else EnvironmentSensorManager(){}; #endif From 5933636214603330f5c294a9d465d196a76a1c6b Mon Sep 17 00:00:00 2001 From: agessaman <adam@gessaman.com> Date: Fri, 4 Sep 2026 16:03:41 -0700 Subject: [PATCH 186/381] feat: add T-Beam 1W thermal fan control --- variants/lilygo_tbeam_1w/TBeam1WBoard.cpp | 341 +++++++++++++++++++++- variants/lilygo_tbeam_1w/TBeam1WBoard.h | 39 ++- variants/lilygo_tbeam_1w/variant.h | 19 +- 3 files changed, 387 insertions(+), 12 deletions(-) diff --git a/variants/lilygo_tbeam_1w/TBeam1WBoard.cpp b/variants/lilygo_tbeam_1w/TBeam1WBoard.cpp index 1719d733..e82e4623 100644 --- a/variants/lilygo_tbeam_1w/TBeam1WBoard.cpp +++ b/variants/lilygo_tbeam_1w/TBeam1WBoard.cpp @@ -1,5 +1,12 @@ #include "TBeam1WBoard.h" +#include <errno.h> +#include <limits.h> +#include <math.h> +#include <stdlib.h> + +static const int FAN_PWM_MAX = (1 << FAN_PWM_RES_BITS) - 1; + void TBeam1WBoard::begin() { ESP32Board::begin(); @@ -15,31 +22,57 @@ void TBeam1WBoard::begin() { pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, LOW); - // Initialize fan control (on by default - 1W PA can overheat) + // NTC ADC (PA-adjacent thermistor) + pinMode(NTC_PIN, INPUT); + analogSetPinAttenuation(NTC_PIN, ADC_11db); + analogReadResolution(12); + + // Fan: auto/onoff. Thermal on at 36C / off below 30C; TX still forces a cooldown. pinMode(FAN_CTRL_PIN, OUTPUT); digitalWrite(FAN_CTRL_PIN, HIGH); + _temp_c = readNtcTempC(); + applyDuty(100); + startFanTask(); +} + +void TBeam1WBoard::startFanTask() { + if (_fan_task) return; + xTaskCreate(fanTaskThunk, "tbeam1w_fan", 4096, this, 1, &_fan_task); +} + +void TBeam1WBoard::fanTaskThunk(void* arg) { + auto* self = static_cast<TBeam1WBoard*>(arg); + for (;;) { + if (!self->_stopped) { + self->updateFan(); + } + vTaskDelay(pdMS_TO_TICKS(1000)); + } } void TBeam1WBoard::onBeforeTransmit() { - // RF switching handled by RadioLib via SX126X_DIO2_AS_RF_SWITCH and setRfSwitchPins() digitalWrite(LED_PIN, HIGH); // TX LED on + _tx_active = true; + if (_mode == FAN_AUTO && _manual_duty < 0 && !_stopped) { + applyDuty(FAN_TX_FLOOR_PCT); + } } void TBeam1WBoard::onAfterTransmit() { digitalWrite(LED_PIN, LOW); // TX LED off + _tx_until_ms = millis() + FAN_TX_COOLDOWN_MS; + _tx_cooldown_active = true; + _tx_active = false; } uint16_t TBeam1WBoard::getBattMilliVolts() { // T-Beam 1W uses 7.4V battery with voltage divider - // ADC reads through divider - adjust multiplier based on actual divider ratio analogReadResolution(12); uint32_t raw = 0; for (int i = 0; i < 8; i++) { raw += analogRead(BATTERY_PIN); } raw = raw / 8; - // Assuming voltage divider ratio from ADC_MULTIPLIER - // 3.3V reference, 12-bit ADC (4095 max) return static_cast<uint16_t>((raw * 3300 * ADC_MULTIPLIER) / 4095); } @@ -48,6 +81,9 @@ const char* TBeam1WBoard::getManufacturerName() const { } void TBeam1WBoard::powerOff() { + _stopped = true; + applyDuty(0); + // Turn off radio LNA (CTRL pin must be LOW when not receiving) digitalWrite(SX126X_RXEN, LOW); @@ -55,17 +91,304 @@ void TBeam1WBoard::powerOff() { digitalWrite(SX126X_POWER_EN, LOW); radio_powered = false; - // Turn off LED and fan digitalWrite(LED_PIN, LOW); - digitalWrite(FAN_CTRL_PIN, LOW); ESP32Board::powerOff(); } void TBeam1WBoard::setFanEnabled(bool enabled) { - digitalWrite(FAN_CTRL_PIN, enabled ? HIGH : LOW); + applyDuty(enabled ? 100 : 0); } bool TBeam1WBoard::isFanEnabled() const { - return digitalRead(FAN_CTRL_PIN) == HIGH; + return _duty_pct > 0; +} + +float TBeam1WBoard::readNtcTempC() { + analogReadMilliVolts(NTC_PIN); // settle + uint32_t sum = 0; + for (int i = 0; i < 8; i++) { + uint32_t sample_mv = analogReadMilliVolts(NTC_PIN); + // GPIO14 is ADC2 on ESP32-S3. Wi-Fi/ESP-NOW arbitration failures are + // reported by Arduino as 0 mV; never average a failed sample into a + // plausible-but-low temperature. + if (sample_mv == 0 || sample_mv >= NTC_VCC_MV) return NAN; + sum += sample_mv; + } + float mv = sum / 8.0f; + + // R_ntc = R_fixed * (Vcc - V) / V for 3.3V-NTC-ADC-10k-GND + float r_ntc = NTC_R_FIXED * (NTC_VCC_MV - mv) / mv; + if (r_ntc <= 0.0f) return NAN; + + float temp_k = 1.0f / (1.0f / 298.15f + (1.0f / NTC_B) * logf(r_ntc / NTC_R25)); + return temp_k - 273.15f; +} + +bool TBeam1WBoard::ntcImplausible(float temp_c) const { + return isnan(temp_c) || temp_c < -20.0f || temp_c > 120.0f; +} + +int TBeam1WBoard::rampDuty(float temp_c) const { + if (temp_c < (float)_lo_c) return 0; + if (temp_c >= (float)_hi_c) return 100; + float span = (float)(_hi_c - _lo_c); + if (span <= 0.0f) return 100; + float t = (temp_c - (float)_lo_c) / span; + return FAN_MIN_DUTY_PCT + (int)((100 - FAN_MIN_DUTY_PCT) * t + 0.5f); +} + +bool TBeam1WBoard::isTxCooling(uint32_t now) { + if (_tx_active) return true; + if (!_tx_cooldown_active) return false; + if ((int32_t)(now - _tx_until_ms) >= 0) { + _tx_cooldown_active = false; + return false; + } + return true; +} + +int TBeam1WBoard::cooldownSecs() { + if (_tx_active) return (FAN_TX_COOLDOWN_MS + 999) / 1000; + if (!_tx_cooldown_active) return 0; + int32_t remain_ms = (int32_t)(_tx_until_ms - millis()); + if (remain_ms <= 0) { + _tx_cooldown_active = false; + return 0; + } + return (remain_ms + 999) / 1000; +} + +void TBeam1WBoard::applyDuty(int pct) { + if (pct < 0) pct = 0; + if (pct > 100) pct = 100; + _duty_pct = pct; + + if (_drive == FAN_DRIVE_PWM) { + if (!_pwm_attached) { + ledcSetup(FAN_PWM_CHANNEL, FAN_PWM_FREQ_HZ, FAN_PWM_RES_BITS); + ledcAttachPin(FAN_CTRL_PIN, FAN_PWM_CHANNEL); + _pwm_attached = true; + } + uint32_t ticks = ((uint32_t)pct * FAN_PWM_MAX + 50) / 100; + ledcWrite(FAN_PWM_CHANNEL, ticks); + } else { + if (_pwm_attached) { + ledcDetachPin(FAN_CTRL_PIN); + _pwm_attached = false; + pinMode(FAN_CTRL_PIN, OUTPUT); + } + digitalWrite(FAN_CTRL_PIN, pct > 0 ? HIGH : LOW); + } +} + +void TBeam1WBoard::updateFan() { + float t = readNtcTempC(); + _temp_c = t; + bool tx_cooling = isTxCooling(millis()); + + int duty; + if (_manual_duty >= 0) { + duty = _manual_duty; + } else if (_mode == FAN_ON) { + duty = 100; + } else if (_mode == FAN_OFF) { + duty = 0; + } else if (ntcImplausible(t)) { + duty = 100; // fail-safe: treat bad NTC as hot + } else if (_drive == FAN_DRIVE_PWM) { + duty = rampDuty(t); + } else { + // Thermal hysteresis only: on at hi, off below lo. TX cooldown is applied + // after this and must not latch _thermal_on, or a TX at 30C keeps the fan + // running until temp dips under lo. + if (t >= (float)_hi_c) _thermal_on = true; + else if (t < (float)_lo_c) _thermal_on = false; + duty = _thermal_on ? 100 : 0; + } + + if (_mode == FAN_AUTO && _manual_duty < 0 && !ntcImplausible(t)) { + if (tx_cooling && duty < FAN_TX_FLOOR_PCT) duty = FAN_TX_FLOOR_PCT; + } + + applyDuty(duty); +} + +bool TBeam1WBoard::persistKey(const char* key, const char* value) { + return _prefs && _prefs->setByKey(key, value); +} + +bool TBeam1WBoard::parseIntArg(const char* text, int& value) { + if (!text || !*text) return false; + errno = 0; + char* end = nullptr; + long parsed = strtol(text, &end, 10); + if (errno == ERANGE || end == text || *end != '\0' || parsed < INT_MIN || parsed > INT_MAX) { + return false; + } + value = (int)parsed; + return true; +} + +void TBeam1WBoard::loadFanPrefs() { + if (!_prefs) return; + + char buf[12]; + buf[0] = 0; + if (_prefs->getByKey("fan", buf, 11)) { + if (strcmp(buf, "auto") == 0) _mode = FAN_AUTO; + else if (strcmp(buf, "off") == 0) _mode = FAN_OFF; + else if (strcmp(buf, "on") == 0) _mode = FAN_ON; + } + + buf[0] = 0; + if (_prefs->getByKey("fan_drv", buf, 11)) { + if (strcmp(buf, "onoff") == 0) _drive = FAN_DRIVE_ONOFF; + else if (strcmp(buf, "pwm") == 0) _drive = FAN_DRIVE_PWM; + } + + int lo = _lo_c; + int hi = _hi_c; + buf[0] = 0; + if (_prefs->getByKey("fan_lo", buf, 11)) lo = atoi(buf); + buf[0] = 0; + if (_prefs->getByKey("fan_hi", buf, 11)) hi = atoi(buf); + if (lo >= 0 && hi <= 120 && lo < hi) { + _lo_c = lo; + _hi_c = hi; + } + + _manual_duty = -1; +} + +void TBeam1WBoard::attachDynamicPrefs(KeyValueStore* prefs) { + _prefs = prefs; + loadFanPrefs(); + updateFan(); +} + +const char* TBeam1WBoard::modeName() const { + if (_manual_duty >= 0) return "manual"; + if (_mode == FAN_AUTO) return "auto"; + if (_mode == FAN_OFF) return "off"; + return "on"; +} + +const char* TBeam1WBoard::driveName() const { + return _drive == FAN_DRIVE_ONOFF ? "onoff" : "pwm"; +} + +bool TBeam1WBoard::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { + (void)sender_timestamp; + + if (strcmp(command, "get fan") == 0) { + int cd = cooldownSecs(); + if (ntcImplausible(_temp_c)) { + sprintf(reply, "> %s n/a duty=%d%% %s cd=%ds", + modeName(), (int)_duty_pct, driveName(), cd); + } else { + sprintf(reply, "> %s %.1fC duty=%d%% %s cd=%ds", + modeName(), (double)_temp_c, (int)_duty_pct, driveName(), cd); + } + return true; + } + + if (strncmp(command, "set fan.lo ", 11) == 0) { + int lo; + if (!parseIntArg(&command[11], lo) || lo < 0 || lo >= _hi_c || lo > 100) { + strcpy(reply, "Error: fan.lo must be 0..100 and < fan.hi"); + } else if (!persistKey("fan_lo", &command[11])) { + strcpy(reply, "Error: failed to save fan.lo"); + } else { + _lo_c = lo; + sprintf(reply, "OK - fan.lo %d", lo); + } + return true; + } + + if (strncmp(command, "set fan.hi ", 11) == 0) { + int hi; + if (!parseIntArg(&command[11], hi) || hi <= _lo_c || hi > 120) { + strcpy(reply, "Error: fan.hi must be > fan.lo and <= 120"); + } else if (!persistKey("fan_hi", &command[11])) { + strcpy(reply, "Error: failed to save fan.hi"); + } else { + _hi_c = hi; + sprintf(reply, "OK - fan.hi %d", hi); + } + return true; + } + + if (strncmp(command, "set fan.drive ", 14) == 0) { + const char* arg = &command[14]; + if (strcmp(arg, "pwm") == 0) { + if (!persistKey("fan_drv", "pwm")) { + strcpy(reply, "Error: failed to save fan.drive"); + } else { + _drive = FAN_DRIVE_PWM; + applyDuty(_duty_pct); + strcpy(reply, "OK - fan.drive pwm"); + } + } else if (strcmp(arg, "onoff") == 0) { + if (!persistKey("fan_drv", "onoff")) { + strcpy(reply, "Error: failed to save fan.drive"); + } else { + _drive = FAN_DRIVE_ONOFF; + applyDuty(_duty_pct); + strcpy(reply, "OK - fan.drive onoff"); + } + } else { + strcpy(reply, "Error: fan.drive must be pwm or onoff"); + } + return true; + } + + if (strncmp(command, "set fan.duty ", 13) == 0) { + int duty; + if (!parseIntArg(&command[13], duty) || duty < 0 || duty > 100) { + strcpy(reply, "Error: fan.duty must be 0-100"); + } else { + _manual_duty = duty; + applyDuty(duty); + sprintf(reply, "OK - fan.duty %d (not saved)", duty); + } + return true; + } + + if (strncmp(command, "set fan ", 8) == 0) { + const char* arg = &command[8]; + if (strcmp(arg, "on") == 0) { + if (!persistKey("fan", "on")) { + strcpy(reply, "Error: failed to save fan mode"); + } else { + _mode = FAN_ON; + _manual_duty = -1; + applyDuty(100); + strcpy(reply, "OK - fan on"); + } + } else if (strcmp(arg, "off") == 0) { + if (!persistKey("fan", "off")) { + strcpy(reply, "Error: failed to save fan mode"); + } else { + _mode = FAN_OFF; + _manual_duty = -1; + applyDuty(0); + strcpy(reply, "OK - fan off"); + } + } else if (strcmp(arg, "auto") == 0) { + if (!persistKey("fan", "auto")) { + strcpy(reply, "Error: failed to save fan mode"); + } else { + _mode = FAN_AUTO; + _manual_duty = -1; + updateFan(); + strcpy(reply, "OK - fan auto"); + } + } else { + strcpy(reply, "Error: fan must be on, off, or auto"); + } + return true; + } + + return false; } diff --git a/variants/lilygo_tbeam_1w/TBeam1WBoard.h b/variants/lilygo_tbeam_1w/TBeam1WBoard.h index d999dfd4..e96923c5 100644 --- a/variants/lilygo_tbeam_1w/TBeam1WBoard.h +++ b/variants/lilygo_tbeam_1w/TBeam1WBoard.h @@ -1,6 +1,8 @@ #pragma once #include <Arduino.h> +#include <freertos/FreeRTOS.h> +#include <freertos/task.h> #include <helpers/ESP32Board.h> #include "variant.h" @@ -28,18 +30,53 @@ // - Battery must support 2A+ discharge for high-power TX class TBeam1WBoard : public ESP32Board { +public: + enum FanMode { FAN_ON, FAN_OFF, FAN_AUTO }; + enum FanDrive { FAN_DRIVE_PWM, FAN_DRIVE_ONOFF }; + private: bool radio_powered = false; + bool _stopped = false; + bool _pwm_attached = false; + KeyValueStore* _prefs = nullptr; + FanMode _mode = FAN_AUTO; + FanDrive _drive = FAN_DRIVE_ONOFF; + int _lo_c = FAN_DEFAULT_LO_C; + int _hi_c = FAN_DEFAULT_HI_C; + int _manual_duty = -1; // -1 = follow mode; 0..100 = CLI override + bool _thermal_on = false; // onoff hysteresis; TX boost must not latch this + volatile float _temp_c = NAN; + volatile int _duty_pct = 100; + volatile bool _tx_active = false; + volatile bool _tx_cooldown_active = false; + volatile uint32_t _tx_until_ms = 0; + TaskHandle_t _fan_task = nullptr; + + void startFanTask(); + void updateFan(); + void applyDuty(int pct); + float readNtcTempC(); + int rampDuty(float temp_c) const; + int cooldownSecs(); + bool isTxCooling(uint32_t now); + bool ntcImplausible(float temp_c) const; + bool persistKey(const char* key, const char* value); + static bool parseIntArg(const char* text, int& value); + void loadFanPrefs(); + const char* modeName() const; + const char* driveName() const; + static void fanTaskThunk(void* arg); public: void begin(); + void attachDynamicPrefs(KeyValueStore* prefs); + bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; void onBeforeTransmit() override; void onAfterTransmit() override; uint16_t getBattMilliVolts() override; const char* getManufacturerName() const override; void powerOff() override; - // Fan control methods void setFanEnabled(bool enabled); bool isFanEnabled() const; }; diff --git a/variants/lilygo_tbeam_1w/variant.h b/variants/lilygo_tbeam_1w/variant.h index f6807e56..a67e2e84 100644 --- a/variants/lilygo_tbeam_1w/variant.h +++ b/variants/lilygo_tbeam_1w/variant.h @@ -77,11 +77,26 @@ #define BATTERY_SENSE_SAMPLES 30 #define ADC_MULTIPLIER 3.0 -// NTC temperature sensor +// NTC thermistor (Murata NCP18XH103F03RB, 10k, B25/50=3380K) +// Divider: 3.3V -> NTC -> GPIO14 -> 10k pull-down -> GND (Vadc rises with temp) #define NTC_PIN 14 +#define NTC_B 3380.0f +#define NTC_R25 10000.0f +#define NTC_R_FIXED 10000.0f +#define NTC_VCC_MV 3300.0f -// Fan control +// Fan control (GPIO41). Default auto + on/off: NTC is PA-adjacent PCB temp, +// not die temp, so trip well below the SX1262/ESP32 85C operating limit. +// This fan/MOSFET path does not respond to PWM below 100% duty. #define FAN_CTRL_PIN 41 +#define FAN_PWM_CHANNEL 4 +#define FAN_PWM_FREQ_HZ 25000 +#define FAN_PWM_RES_BITS 8 +#define FAN_MIN_DUTY_PCT 40 +#define FAN_TX_COOLDOWN_MS 15000 +#define FAN_TX_FLOOR_PCT 100 +#define FAN_DEFAULT_LO_C 30 // off below typical indoor idle (~86F) +#define FAN_DEFAULT_HI_C 36 // on at ~97F PCB; still far below 85C chip ratings // PA Ramp Time - T-Beam 1W requires >800us stabilization (default is 200us) // Value 0x05 = RADIOLIB_SX126X_PA_RAMP_800U From 0549a9f943decbe04b9b929beb617f16b987e87d Mon Sep 17 00:00:00 2001 From: agessaman <adam@gessaman.com> Date: Fri, 4 Sep 2026 16:51:53 -0700 Subject: [PATCH 187/381] Fix T-Beam 1W fan races and remove PWM controls --- variants/lilygo_tbeam_1w/TBeam1WBoard.cpp | 222 +++++++++------------- variants/lilygo_tbeam_1w/TBeam1WBoard.h | 25 +-- variants/lilygo_tbeam_1w/variant.h | 11 +- 3 files changed, 102 insertions(+), 156 deletions(-) diff --git a/variants/lilygo_tbeam_1w/TBeam1WBoard.cpp b/variants/lilygo_tbeam_1w/TBeam1WBoard.cpp index e82e4623..e0419955 100644 --- a/variants/lilygo_tbeam_1w/TBeam1WBoard.cpp +++ b/variants/lilygo_tbeam_1w/TBeam1WBoard.cpp @@ -5,8 +5,6 @@ #include <math.h> #include <stdlib.h> -static const int FAN_PWM_MAX = (1 << FAN_PWM_RES_BITS) - 1; - void TBeam1WBoard::begin() { ESP32Board::begin(); @@ -30,8 +28,8 @@ void TBeam1WBoard::begin() { // Fan: auto/onoff. Thermal on at 36C / off below 30C; TX still forces a cooldown. pinMode(FAN_CTRL_PIN, OUTPUT); digitalWrite(FAN_CTRL_PIN, HIGH); + _fan_on = true; _temp_c = readNtcTempC(); - applyDuty(100); startFanTask(); } @@ -43,26 +41,30 @@ void TBeam1WBoard::startFanTask() { void TBeam1WBoard::fanTaskThunk(void* arg) { auto* self = static_cast<TBeam1WBoard*>(arg); for (;;) { - if (!self->_stopped) { - self->updateFan(); - } + self->updateFan(); vTaskDelay(pdMS_TO_TICKS(1000)); } } void TBeam1WBoard::onBeforeTransmit() { digitalWrite(LED_PIN, HIGH); // TX LED on + portENTER_CRITICAL(&_fan_mux); _tx_active = true; - if (_mode == FAN_AUTO && _manual_duty < 0 && !_stopped) { - applyDuty(FAN_TX_FLOOR_PCT); + if (_mode == FAN_AUTO && !_stopped) { + setFanOutputLocked(true); } + portEXIT_CRITICAL(&_fan_mux); } void TBeam1WBoard::onAfterTransmit() { digitalWrite(LED_PIN, LOW); // TX LED off - _tx_until_ms = millis() + FAN_TX_COOLDOWN_MS; - _tx_cooldown_active = true; + portENTER_CRITICAL(&_fan_mux); + if (!_stopped) { + _tx_until_ms = millis() + FAN_TX_COOLDOWN_MS; + _tx_cooldown_active = true; + } _tx_active = false; + portEXIT_CRITICAL(&_fan_mux); } uint16_t TBeam1WBoard::getBattMilliVolts() { @@ -81,8 +83,12 @@ const char* TBeam1WBoard::getManufacturerName() const { } void TBeam1WBoard::powerOff() { + portENTER_CRITICAL(&_fan_mux); _stopped = true; - applyDuty(0); + _tx_active = false; + _tx_cooldown_active = false; + setFanOutputLocked(false); + portEXIT_CRITICAL(&_fan_mux); // Turn off radio LNA (CTRL pin must be LOW when not receiving) digitalWrite(SX126X_RXEN, LOW); @@ -97,11 +103,16 @@ void TBeam1WBoard::powerOff() { } void TBeam1WBoard::setFanEnabled(bool enabled) { - applyDuty(enabled ? 100 : 0); + portENTER_CRITICAL(&_fan_mux); + setFanOutputLocked(enabled && !_stopped); + portEXIT_CRITICAL(&_fan_mux); } bool TBeam1WBoard::isFanEnabled() const { - return _duty_pct > 0; + portENTER_CRITICAL(&_fan_mux); + bool enabled = _fan_on; + portEXIT_CRITICAL(&_fan_mux); + return enabled; } float TBeam1WBoard::readNtcTempC() { @@ -129,16 +140,7 @@ bool TBeam1WBoard::ntcImplausible(float temp_c) const { return isnan(temp_c) || temp_c < -20.0f || temp_c > 120.0f; } -int TBeam1WBoard::rampDuty(float temp_c) const { - if (temp_c < (float)_lo_c) return 0; - if (temp_c >= (float)_hi_c) return 100; - float span = (float)(_hi_c - _lo_c); - if (span <= 0.0f) return 100; - float t = (temp_c - (float)_lo_c) / span; - return FAN_MIN_DUTY_PCT + (int)((100 - FAN_MIN_DUTY_PCT) * t + 0.5f); -} - -bool TBeam1WBoard::isTxCooling(uint32_t now) { +bool TBeam1WBoard::isTxCoolingLocked(uint32_t now) { if (_tx_active) return true; if (!_tx_cooldown_active) return false; if ((int32_t)(now - _tx_until_ms) >= 0) { @@ -148,7 +150,7 @@ bool TBeam1WBoard::isTxCooling(uint32_t now) { return true; } -int TBeam1WBoard::cooldownSecs() { +int TBeam1WBoard::cooldownSecsLocked() { if (_tx_active) return (FAN_TX_COOLDOWN_MS + 999) / 1000; if (!_tx_cooldown_active) return 0; int32_t remain_ms = (int32_t)(_tx_until_ms - millis()); @@ -159,59 +161,41 @@ int TBeam1WBoard::cooldownSecs() { return (remain_ms + 999) / 1000; } -void TBeam1WBoard::applyDuty(int pct) { - if (pct < 0) pct = 0; - if (pct > 100) pct = 100; - _duty_pct = pct; - - if (_drive == FAN_DRIVE_PWM) { - if (!_pwm_attached) { - ledcSetup(FAN_PWM_CHANNEL, FAN_PWM_FREQ_HZ, FAN_PWM_RES_BITS); - ledcAttachPin(FAN_CTRL_PIN, FAN_PWM_CHANNEL); - _pwm_attached = true; - } - uint32_t ticks = ((uint32_t)pct * FAN_PWM_MAX + 50) / 100; - ledcWrite(FAN_PWM_CHANNEL, ticks); - } else { - if (_pwm_attached) { - ledcDetachPin(FAN_CTRL_PIN); - _pwm_attached = false; - pinMode(FAN_CTRL_PIN, OUTPUT); - } - digitalWrite(FAN_CTRL_PIN, pct > 0 ? HIGH : LOW); - } +void TBeam1WBoard::setFanOutputLocked(bool enabled) { + _fan_on = enabled; + digitalWrite(FAN_CTRL_PIN, enabled ? HIGH : LOW); } void TBeam1WBoard::updateFan() { float t = readNtcTempC(); - _temp_c = t; - bool tx_cooling = isTxCooling(millis()); + uint32_t now = millis(); - int duty; - if (_manual_duty >= 0) { - duty = _manual_duty; - } else if (_mode == FAN_ON) { - duty = 100; + portENTER_CRITICAL(&_fan_mux); + if (_stopped) { + portEXIT_CRITICAL(&_fan_mux); + return; + } + + _temp_c = t; + bool tx_cooling = isTxCoolingLocked(now); + + bool enabled; + if (_mode == FAN_ON) { + enabled = true; } else if (_mode == FAN_OFF) { - duty = 0; + enabled = false; } else if (ntcImplausible(t)) { - duty = 100; // fail-safe: treat bad NTC as hot - } else if (_drive == FAN_DRIVE_PWM) { - duty = rampDuty(t); + enabled = true; // fail-safe: treat bad NTC as hot } else { - // Thermal hysteresis only: on at hi, off below lo. TX cooldown is applied - // after this and must not latch _thermal_on, or a TX at 30C keeps the fan - // running until temp dips under lo. + // TX cooldown must not latch _thermal_on, or a TX at 30C keeps the fan + // running until the temperature dips under lo. if (t >= (float)_hi_c) _thermal_on = true; else if (t < (float)_lo_c) _thermal_on = false; - duty = _thermal_on ? 100 : 0; + enabled = _thermal_on || tx_cooling; } - if (_mode == FAN_AUTO && _manual_duty < 0 && !ntcImplausible(t)) { - if (tx_cooling && duty < FAN_TX_FLOOR_PCT) duty = FAN_TX_FLOOR_PCT; - } - - applyDuty(duty); + setFanOutputLocked(enabled); + portEXIT_CRITICAL(&_fan_mux); } bool TBeam1WBoard::persistKey(const char* key, const char* value) { @@ -233,32 +217,28 @@ bool TBeam1WBoard::parseIntArg(const char* text, int& value) { void TBeam1WBoard::loadFanPrefs() { if (!_prefs) return; + FanMode mode = FAN_AUTO; char buf[12]; buf[0] = 0; if (_prefs->getByKey("fan", buf, 11)) { - if (strcmp(buf, "auto") == 0) _mode = FAN_AUTO; - else if (strcmp(buf, "off") == 0) _mode = FAN_OFF; - else if (strcmp(buf, "on") == 0) _mode = FAN_ON; + if (strcmp(buf, "off") == 0) mode = FAN_OFF; + else if (strcmp(buf, "on") == 0) mode = FAN_ON; } - buf[0] = 0; - if (_prefs->getByKey("fan_drv", buf, 11)) { - if (strcmp(buf, "onoff") == 0) _drive = FAN_DRIVE_ONOFF; - else if (strcmp(buf, "pwm") == 0) _drive = FAN_DRIVE_PWM; - } - - int lo = _lo_c; - int hi = _hi_c; + int lo = FAN_DEFAULT_LO_C; + int hi = FAN_DEFAULT_HI_C; buf[0] = 0; if (_prefs->getByKey("fan_lo", buf, 11)) lo = atoi(buf); buf[0] = 0; if (_prefs->getByKey("fan_hi", buf, 11)) hi = atoi(buf); + + portENTER_CRITICAL(&_fan_mux); + _mode = mode; if (lo >= 0 && hi <= 120 && lo < hi) { _lo_c = lo; _hi_c = hi; } - - _manual_duty = -1; + portEXIT_CRITICAL(&_fan_mux); } void TBeam1WBoard::attachDynamicPrefs(KeyValueStore* prefs) { @@ -267,40 +247,44 @@ void TBeam1WBoard::attachDynamicPrefs(KeyValueStore* prefs) { updateFan(); } -const char* TBeam1WBoard::modeName() const { - if (_manual_duty >= 0) return "manual"; +const char* TBeam1WBoard::modeNameLocked() const { if (_mode == FAN_AUTO) return "auto"; if (_mode == FAN_OFF) return "off"; return "on"; } -const char* TBeam1WBoard::driveName() const { - return _drive == FAN_DRIVE_ONOFF ? "onoff" : "pwm"; -} - bool TBeam1WBoard::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { (void)sender_timestamp; if (strcmp(command, "get fan") == 0) { - int cd = cooldownSecs(); - if (ntcImplausible(_temp_c)) { - sprintf(reply, "> %s n/a duty=%d%% %s cd=%ds", - modeName(), (int)_duty_pct, driveName(), cd); + portENTER_CRITICAL(&_fan_mux); + int cd = cooldownSecsLocked(); + float temp_c = _temp_c; + bool enabled = _fan_on; + const char* mode = modeNameLocked(); + portEXIT_CRITICAL(&_fan_mux); + if (ntcImplausible(temp_c)) { + sprintf(reply, "> %s n/a fan=%s cd=%ds", mode, enabled ? "on" : "off", cd); } else { - sprintf(reply, "> %s %.1fC duty=%d%% %s cd=%ds", - modeName(), (double)_temp_c, (int)_duty_pct, driveName(), cd); + sprintf(reply, "> %s %.1fC fan=%s cd=%ds", + mode, (double)temp_c, enabled ? "on" : "off", cd); } return true; } if (strncmp(command, "set fan.lo ", 11) == 0) { int lo; - if (!parseIntArg(&command[11], lo) || lo < 0 || lo >= _hi_c || lo > 100) { + portENTER_CRITICAL(&_fan_mux); + int hi_limit = _hi_c; + portEXIT_CRITICAL(&_fan_mux); + if (!parseIntArg(&command[11], lo) || lo < 0 || lo >= hi_limit || lo > 100) { strcpy(reply, "Error: fan.lo must be 0..100 and < fan.hi"); } else if (!persistKey("fan_lo", &command[11])) { strcpy(reply, "Error: failed to save fan.lo"); } else { + portENTER_CRITICAL(&_fan_mux); _lo_c = lo; + portEXIT_CRITICAL(&_fan_mux); sprintf(reply, "OK - fan.lo %d", lo); } return true; @@ -308,79 +292,51 @@ bool TBeam1WBoard::handleCommand(const char* command, uint32_t sender_timestamp, if (strncmp(command, "set fan.hi ", 11) == 0) { int hi; - if (!parseIntArg(&command[11], hi) || hi <= _lo_c || hi > 120) { + portENTER_CRITICAL(&_fan_mux); + int lo_limit = _lo_c; + portEXIT_CRITICAL(&_fan_mux); + if (!parseIntArg(&command[11], hi) || hi <= lo_limit || hi > 120) { strcpy(reply, "Error: fan.hi must be > fan.lo and <= 120"); } else if (!persistKey("fan_hi", &command[11])) { strcpy(reply, "Error: failed to save fan.hi"); } else { + portENTER_CRITICAL(&_fan_mux); _hi_c = hi; + portEXIT_CRITICAL(&_fan_mux); sprintf(reply, "OK - fan.hi %d", hi); } return true; } - if (strncmp(command, "set fan.drive ", 14) == 0) { - const char* arg = &command[14]; - if (strcmp(arg, "pwm") == 0) { - if (!persistKey("fan_drv", "pwm")) { - strcpy(reply, "Error: failed to save fan.drive"); - } else { - _drive = FAN_DRIVE_PWM; - applyDuty(_duty_pct); - strcpy(reply, "OK - fan.drive pwm"); - } - } else if (strcmp(arg, "onoff") == 0) { - if (!persistKey("fan_drv", "onoff")) { - strcpy(reply, "Error: failed to save fan.drive"); - } else { - _drive = FAN_DRIVE_ONOFF; - applyDuty(_duty_pct); - strcpy(reply, "OK - fan.drive onoff"); - } - } else { - strcpy(reply, "Error: fan.drive must be pwm or onoff"); - } - return true; - } - - if (strncmp(command, "set fan.duty ", 13) == 0) { - int duty; - if (!parseIntArg(&command[13], duty) || duty < 0 || duty > 100) { - strcpy(reply, "Error: fan.duty must be 0-100"); - } else { - _manual_duty = duty; - applyDuty(duty); - sprintf(reply, "OK - fan.duty %d (not saved)", duty); - } - return true; - } - if (strncmp(command, "set fan ", 8) == 0) { const char* arg = &command[8]; if (strcmp(arg, "on") == 0) { if (!persistKey("fan", "on")) { strcpy(reply, "Error: failed to save fan mode"); } else { + portENTER_CRITICAL(&_fan_mux); _mode = FAN_ON; - _manual_duty = -1; - applyDuty(100); + if (!_stopped) setFanOutputLocked(true); + portEXIT_CRITICAL(&_fan_mux); strcpy(reply, "OK - fan on"); } } else if (strcmp(arg, "off") == 0) { if (!persistKey("fan", "off")) { strcpy(reply, "Error: failed to save fan mode"); } else { + portENTER_CRITICAL(&_fan_mux); _mode = FAN_OFF; - _manual_duty = -1; - applyDuty(0); + setFanOutputLocked(false); + portEXIT_CRITICAL(&_fan_mux); strcpy(reply, "OK - fan off"); } } else if (strcmp(arg, "auto") == 0) { if (!persistKey("fan", "auto")) { strcpy(reply, "Error: failed to save fan mode"); } else { + portENTER_CRITICAL(&_fan_mux); _mode = FAN_AUTO; - _manual_duty = -1; + portEXIT_CRITICAL(&_fan_mux); updateFan(); strcpy(reply, "OK - fan auto"); } diff --git a/variants/lilygo_tbeam_1w/TBeam1WBoard.h b/variants/lilygo_tbeam_1w/TBeam1WBoard.h index e96923c5..429b7bd1 100644 --- a/variants/lilygo_tbeam_1w/TBeam1WBoard.h +++ b/variants/lilygo_tbeam_1w/TBeam1WBoard.h @@ -32,39 +32,34 @@ class TBeam1WBoard : public ESP32Board { public: enum FanMode { FAN_ON, FAN_OFF, FAN_AUTO }; - enum FanDrive { FAN_DRIVE_PWM, FAN_DRIVE_ONOFF }; private: bool radio_powered = false; bool _stopped = false; - bool _pwm_attached = false; KeyValueStore* _prefs = nullptr; FanMode _mode = FAN_AUTO; - FanDrive _drive = FAN_DRIVE_ONOFF; int _lo_c = FAN_DEFAULT_LO_C; int _hi_c = FAN_DEFAULT_HI_C; - int _manual_duty = -1; // -1 = follow mode; 0..100 = CLI override bool _thermal_on = false; // onoff hysteresis; TX boost must not latch this - volatile float _temp_c = NAN; - volatile int _duty_pct = 100; - volatile bool _tx_active = false; - volatile bool _tx_cooldown_active = false; - volatile uint32_t _tx_until_ms = 0; + bool _fan_on = true; + float _temp_c = NAN; + bool _tx_active = false; + bool _tx_cooldown_active = false; + uint32_t _tx_until_ms = 0; TaskHandle_t _fan_task = nullptr; + mutable portMUX_TYPE _fan_mux = portMUX_INITIALIZER_UNLOCKED; void startFanTask(); void updateFan(); - void applyDuty(int pct); + void setFanOutputLocked(bool enabled); float readNtcTempC(); - int rampDuty(float temp_c) const; - int cooldownSecs(); - bool isTxCooling(uint32_t now); + int cooldownSecsLocked(); + bool isTxCoolingLocked(uint32_t now); bool ntcImplausible(float temp_c) const; bool persistKey(const char* key, const char* value); static bool parseIntArg(const char* text, int& value); void loadFanPrefs(); - const char* modeName() const; - const char* driveName() const; + const char* modeNameLocked() const; static void fanTaskThunk(void* arg); public: diff --git a/variants/lilygo_tbeam_1w/variant.h b/variants/lilygo_tbeam_1w/variant.h index a67e2e84..528459a4 100644 --- a/variants/lilygo_tbeam_1w/variant.h +++ b/variants/lilygo_tbeam_1w/variant.h @@ -85,16 +85,11 @@ #define NTC_R_FIXED 10000.0f #define NTC_VCC_MV 3300.0f -// Fan control (GPIO41). Default auto + on/off: NTC is PA-adjacent PCB temp, -// not die temp, so trip well below the SX1262/ESP32 85C operating limit. -// This fan/MOSFET path does not respond to PWM below 100% duty. +// Fan control (GPIO41). NTC is PA-adjacent PCB temp, not die temp, so trip +// well below the SX1262/ESP32 85C operating limit. Hardware testing confirmed +// that this fan/MOSFET path is on/off; PWM below 100% does not spin the fan. #define FAN_CTRL_PIN 41 -#define FAN_PWM_CHANNEL 4 -#define FAN_PWM_FREQ_HZ 25000 -#define FAN_PWM_RES_BITS 8 -#define FAN_MIN_DUTY_PCT 40 #define FAN_TX_COOLDOWN_MS 15000 -#define FAN_TX_FLOOR_PCT 100 #define FAN_DEFAULT_LO_C 30 // off below typical indoor idle (~86F) #define FAN_DEFAULT_HI_C 36 // on at ~97F PCB; still far below 85C chip ratings From 96866be3390ad9235d93165cf9f14a3862e1cd33 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Sat, 5 Sep 2026 15:59:29 +1000 Subject: [PATCH 188/381] * added region load/save support * SUBSCRIBE now with timeout param (default 30 mins, max ~18 hours) --- examples/simple_sensor/SensorMesh.cpp | 102 ++++++++++++++++++++++---- examples/simple_sensor/SensorMesh.h | 7 +- src/helpers/ClientACL.h | 1 + 3 files changed, 93 insertions(+), 17 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 008cbcfc..c3f2d9b0 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -322,8 +322,10 @@ uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, u return ofs; } } - if (req_type == REQ_TYPE_SUBSCRIBE && payload_len >= 2 && (perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { - uint8_t reserved = payload[0]; + if (req_type == REQ_TYPE_SUBSCRIBE && payload_len >= 4 && (perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { + uint16_t timeout_secs; + memcpy(&timeout_secs, &payload[0], 2); + uint8_t reserved = payload[2]; RegionEntry* r; if (recv_pkt_region && !recv_pkt_region->isWildcard()) { // use request scope r = recv_pkt_region; @@ -331,16 +333,19 @@ uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, u r = region_map.getDefaultRegion(); } from->extra.sensor.scope_region_id = r ? r->id : 0; - from->extra.sensor.min_deltas_len = payload[1]; + from->extra.sensor.expiry_timestamp = r ? getRTCClock()->getCurrentTime() + timeout_secs : 0; + from->extra.sensor.min_deltas_len = payload[3]; // NOTE: curr impl truncates LPP min_diffs spec (re-do if better impl is needed) - memcpy(from->extra.sensor.min_deltas, &payload[2], min(sizeof(from->extra.sensor.min_deltas), (size_t)payload[1])); + memcpy(from->extra.sensor.min_deltas, &payload[4], min(sizeof(from->extra.sensor.min_deltas), (size_t)payload[3])); - getRNG()->random(&reply_data[4], 2); // just some entropy for better packet-hash uniqueness - strcpy((char *)&reply_data[6], r ? r->name : ""); // reply with name of scope that will be used - return 6 + strlen((char *)&reply_data[6]); + memcpy(&reply_data[4], &from->extra.sensor.expiry_timestamp, 4); // reply with actual expiry timestamp (or 0 for error) + strcpy((char *)&reply_data[8], r ? r->name : ""); // reply with name of scope that will be used + return 6 + strlen((char *)&reply_data[8]); } if (req_type == REQ_TYPE_UNSUBSCRIBE && (perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { from->extra.sensor.scope_region_id = 0; + from->extra.sensor.expiry_timestamp = 0; + // REVISIT: maybe return some stats, eg total number of telemetry pushes since SUBSCRIBE? reply_data[4] = 0; // success getRNG()->random(&reply_data[5], 3); // just some entropy for better packet-hash uniqueness return 8; @@ -441,6 +446,25 @@ int SensorMesh::getAGCResetInterval() const { return ((int)_prefs.agc_reset_interval) * 4000; // milliseconds } +void SensorMesh::startRegionsLoad() { + temp_map.resetFrom(region_map); // rebuild regions in a temp instance + memset(load_stack, 0, sizeof(load_stack)); + load_stack[0] = &temp_map.getWildcard(); + region_load_active = true; +} + +bool SensorMesh::saveRegions() { + return region_map.save(_fs); +} + +void SensorMesh::onDefaultRegionChanged(const RegionEntry* r) { + if (r) { + region_map.getTransportKeysFor(*r, &default_scope, 1); + } else { + memset(default_scope.key, 0, sizeof(default_scope.key)); + } +} + uint8_t SensorMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data, bool is_flood) { ClientInfo* client; if (data[0] == 0) { // blank password, just check if sender is in ACL @@ -454,7 +478,7 @@ uint8_t SensorMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* } else { if (strcmp((char *) data, _prefs.password) != 0) { // check for valid admin password #if MESH_DEBUG - MESH_DEBUG_PRINTLN("Invalid password: %s", &data[4]); + MESH_DEBUG_PRINTLN("Invalid password: %s", &data[0]); #endif return 0; } @@ -491,6 +515,40 @@ uint8_t SensorMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* } void SensorMesh::handleCommand(ClientInfo* from, uint32_t sender_timestamp, char* command, char* reply) { + if (region_load_active) { + if (StrHelper::isBlank(command)) { // empty/blank line, signal to terminate 'load' operation + region_map = temp_map; // copy over the temp instance as new current map + region_load_active = false; + + sprintf(reply, "OK - loaded %d regions", region_map.getCount()); + } else { + char *np = command; + while (*np == ' ') np++; // skip indent + int indent = np - command; + + char *ep = np; + while (RegionMap::is_name_char(*ep)) ep++; + if (*ep) { *ep++ = 0; } // set null terminator for end of name + + while (*ep && *ep != 'F') ep++; // look for (optional) flags + + if (indent > 0 && indent < 8 && strlen(np) > 0) { + auto parent = load_stack[indent - 1]; + if (parent) { + auto old = region_map.findByName(np); + auto nw = temp_map.putRegion(np, parent->id, old ? old->id : 0); // carry-over the current ID (if name already exists) + if (nw) { + nw->flags = old ? old->flags : (*ep == 'F' ? 0 : REGION_DENY_FLOOD); // carry-over flags from curr + + load_stack[indent] = nw; // keep pointers to parent regions, to resolve parent_id's + } + } + } + reply[0] = 0; + } + return; + } + while (*command == ' ') command++; // skip leading spaces if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI) @@ -548,15 +606,25 @@ void SensorMesh::handleCommand(ClientInfo* from, uint32_t sender_timestamp, char } else { // use default scope r = region_map.getDefaultRegion(); } - if (command[3] == ' ') { - // compile params as LPP data, eg. "sub 1:0.2V" - from->extra.sensor.min_deltas_len = compileLPPSpec(&command[4], from->extra.sensor.min_deltas, sizeof(from->extra.sensor.min_deltas)); - } else { - from->extra.sensor.min_deltas_len = 0; // no minimums (telemetry just needs to CHANGE) + // defaults: + from->extra.sensor.min_deltas_len = 0; // no minimums (telemetry just needs to CHANGE) + uint16_t timeout_secs = 30*60; // expires after 30 mins + if (command[3] == ' ') { // eg. "sub 300 1:0.2V" + char* cp = &command[4]; + while (*cp >= '0' && *cp <= '9') cp++; + if (cp > &command[4]) { + timeout_secs = atoi(&command[4]); + if (*cp == ' ') { + cp++; // skip the space + from->extra.sensor.min_deltas_len = compileLPPSpec(cp, from->extra.sensor.min_deltas, sizeof(from->extra.sensor.min_deltas)); + } + } } from->extra.sensor.scope_region_id = r ? r->id : 0; - if (from->extra.sensor.scope_region_id) { - strcpy(reply, "OK - subscribed"); + from->extra.sensor.expiry_timestamp = r ? getRTCClock()->getCurrentTime() + timeout_secs : 0; + if (from->extra.sensor.expiry_timestamp) { + DateTime dt = DateTime(from->extra.sensor.expiry_timestamp); + sprintf(reply, "OK - sub expires: %02d:%02d (UTC)", dt.hour(), dt.minute()); } else { strcpy(reply, "Err - region scope needed"); } @@ -853,7 +921,7 @@ void SensorMesh::onAckRecv(mesh::Packet* packet, uint32_t ack_crc) { SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables) : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables), - region_map(key_store), + region_map(key_store), temp_map(key_store), _cli(board, rtc, sensors, region_map, acl, &_prefs, this), telemetry(MAX_PACKET_PAYLOAD - 4) { @@ -864,6 +932,7 @@ SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::Millise set_radio_at = revert_radio_at = 0; recv_pkt_region = NULL; prev_telem_size = 0; + region_load_active = false; // defaults _prefs.airtime_factor = 1.0; @@ -1110,6 +1179,7 @@ void SensorMesh::loop() { if (c->permissions == 0 || c->extra.sensor.scope_region_id == 0) continue; // skip deleted entries, or Not subscribed to deltas RegionEntry* r = region_map.findById(c->extra.sensor.scope_region_id); if (r == NULL) continue; // unknown region scope + if (curr > c->extra.sensor.expiry_timestamp) continue; // subscription now expired if (telemHasChanged(c->extra.sensor.min_deltas, c->extra.sensor.min_deltas_len)) { TransportKey scope; if (region_map.getTransportKeysFor(*r, &scope, 1) > 0) { diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index 6d5857d0..e0e03c81 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -78,6 +78,9 @@ public: void saveIdentity(const mesh::LocalIdentity& new_id) override; void clearStats() override { } void applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, int timeout_mins) override; + void startRegionsLoad() override; + bool saveRegions() override; + void onDefaultRegionChanged(const RegionEntry* r) override; float getTelemValue(uint8_t channel, uint8_t type); @@ -148,8 +151,9 @@ private: uint8_t prev_telem_size; uint8_t prev_telem[MAX_PACKET_PAYLOAD - 4]; TransportKeyStore key_store; - RegionMap region_map; + RegionMap region_map, temp_map; RegionEntry* recv_pkt_region; + RegionEntry* load_stack[8]; TransportKey default_scope; uint32_t last_read_time; int matching_peer_indexes[MAX_SEARCH_RESULTS]; @@ -160,6 +164,7 @@ private: float pending_bw; uint8_t pending_sf; uint8_t pending_cr; + bool region_load_active; bool telemHasChanged(const uint8_t* min_deltas, uint8_t min_deltas_len); uint8_t handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data, bool is_flood); diff --git a/src/helpers/ClientACL.h b/src/helpers/ClientACL.h index 9fde35ec..1e9f472d 100644 --- a/src/helpers/ClientACL.h +++ b/src/helpers/ClientACL.h @@ -29,6 +29,7 @@ struct ClientInfo { uint8_t push_failures; } room; struct { + uint32_t expiry_timestamp; // epoch seconds uint16_t scope_region_id; // scope to use when sending telemetry to this client/subscriber uint8_t min_deltas_len; uint8_t min_deltas[14]; // LPP encoded From 676169b7778c54b95415b4dafc8389edbb17c4f1 Mon Sep 17 00:00:00 2001 From: Michael Graff <mgraff@cardinalhq.io> Date: Fri, 4 Sep 2026 20:10:20 -0500 Subject: [PATCH 189/381] Add WiFi companion support for Pico W SerialWifiInterface has no ESP32-specific code, so move it to helpers/wifi and reuse it on RP2040. Guard the ESP32-only WiFi event/auto-reconnect calls and poll link state on RP2040 instead. --- examples/companion_radio/main.cpp | 24 ++++++++++----- platformio.ini | 1 + .../{esp32 => wifi}/SerialWifiInterface.cpp | 0 .../{esp32 => wifi}/SerialWifiInterface.h | 0 variants/rpi_picow/platformio.ini | 30 ++++++++++--------- 5 files changed, 34 insertions(+), 21 deletions(-) rename src/helpers/{esp32 => wifi}/SerialWifiInterface.cpp (100%) rename src/helpers/{esp32 => wifi}/SerialWifiInterface.h (100%) diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index 89f0e6cb..7c8c12b9 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -36,9 +36,8 @@ MultiSerialInterface interface_manager; #ifndef TCP_PORT #define TCP_PORT 5000 #endif - #ifdef ESP32 - // include esp32 wifi interface - #include <helpers/esp32/SerialWifiInterface.h> + #if defined(ESP32) || defined(RP2040_PLATFORM) + #include <helpers/wifi/SerialWifiInterface.h> SerialWifiInterface wifi_interface; #else #error "SerialWifiInterface is not defined for this platform" @@ -108,7 +107,7 @@ void halt() { } /* WIFI RECONNECT TRACKERS */ -#if defined(ESP32) && defined(WIFI_SSID) +#ifdef WIFI_SSID bool wifi_needs_reconnect = false; unsigned long last_wifi_reconnect_attempt = 0; #endif @@ -192,6 +191,7 @@ void setup() { // add wifi interface #ifdef WIFI_SSID +#if defined(ESP32) board.setInhibitSleep(true); // prevent sleep when WiFi is active WiFi.setAutoReconnect(true); @@ -204,6 +204,7 @@ void setup() { wifi_needs_reconnect = false; } }); +#endif WiFi.begin(WIFI_SSID, WIFI_PWD); wifi_interface.begin(TCP_PORT); @@ -262,12 +263,21 @@ void loop() { #endif } -#if defined(ESP32) && defined(WIFI_SSID) +#ifdef WIFI_SSID + // RP2040 has no WiFi event callbacks, so poll the link state instead + #if defined(RP2040_PLATFORM) + wifi_needs_reconnect = (WiFi.status() != WL_CONNECTED); + #endif + // Safely attempt to reconnect every 10 seconds if flagged if (wifi_needs_reconnect && (millis() - last_wifi_reconnect_attempt > 10000)) { WIFI_DEBUG_PRINTLN("Attempting manual WiFi reconnect..."); - WiFi.disconnect(); - WiFi.reconnect(); + #if defined(RP2040_PLATFORM) + WiFi.begin(WIFI_SSID, WIFI_PWD); // no reconnect() on this platform + #else + WiFi.disconnect(); + WiFi.reconnect(); + #endif last_wifi_reconnect_attempt = millis(); } #endif diff --git a/platformio.ini b/platformio.ini index 2219c978..622b01e2 100644 --- a/platformio.ini +++ b/platformio.ini @@ -64,6 +64,7 @@ build_flags = ${arduino_base.build_flags} -D ESP32_PLATFORM ; -D ESP32_CPU_FREQ=80 ; change it to your need build_src_filter = ${arduino_base.build_src_filter} + +<helpers/wifi/*.cpp> [esp32_ota] lib_deps = diff --git a/src/helpers/esp32/SerialWifiInterface.cpp b/src/helpers/wifi/SerialWifiInterface.cpp similarity index 100% rename from src/helpers/esp32/SerialWifiInterface.cpp rename to src/helpers/wifi/SerialWifiInterface.cpp diff --git a/src/helpers/esp32/SerialWifiInterface.h b/src/helpers/wifi/SerialWifiInterface.h similarity index 100% rename from src/helpers/esp32/SerialWifiInterface.h rename to src/helpers/wifi/SerialWifiInterface.h diff --git a/variants/rpi_picow/platformio.ini b/variants/rpi_picow/platformio.ini index 0fe8c436..32944a9a 100644 --- a/variants/rpi_picow/platformio.ini +++ b/variants/rpi_picow/platformio.ini @@ -81,20 +81,22 @@ lib_ignore = BLE ; lib_deps = ${rpi_picow.lib_deps} ; densaugeo/base64 @ ~1.4.0 -; [env:PicoW_companion_radio_wifi] -; extends = rpi_picow -; build_flags = ${rpi_picow.build_flags} -; -D MAX_CONTACTS=100 -; -D MAX_GROUP_CHANNELS=8 -; -D WIFI_DEBUG_LOGGING=1 -; -D WIFI_SSID='"myssid"' -; -D WIFI_PWD='"mypwd"' -; ; -D MESH_PACKET_LOGGING=1 -; ; -D MESH_DEBUG=1 -; build_src_filter = ${rpi_picow.build_src_filter} -; +<../examples/companion_radio/*.cpp> -; lib_deps = ${rpi_picow.lib_deps} -; densaugeo/base64 @ ~1.4.0 +[env:PicoW_companion_radio_wifi] +extends = rpi_picow +build_flags = ${rpi_picow.build_flags} + -D MAX_CONTACTS=100 + -D MAX_GROUP_CHANNELS=8 + -D WIFI_DEBUG_LOGGING=1 + -D WIFI_SSID='"myssid"' + -D WIFI_PWD='"mypwd"' +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${rpi_picow.build_src_filter} + +<helpers/wifi/*.cpp> + +<../examples/companion_radio/*.cpp> +lib_deps = ${rpi_picow.lib_deps} + densaugeo/base64 @ ~1.4.0 +lib_ignore = BLE [env:PicoW_terminal_chat] extends = rpi_picow From 48cc30777d14aed174abfe69983d1a4c05f52374 Mon Sep 17 00:00:00 2001 From: Michael Graff <mgraff@cardinalhq.io> Date: Fri, 4 Sep 2026 20:18:51 -0500 Subject: [PATCH 190/381] Allow WiFi credentials to be set at runtime Store ssid/pwd in NodePrefs and set them with 'set wifi.ssid' / 'set wifi.pwd' over USB serial; build-time WIFI_SSID/WIFI_PWD stay as the fallback. Headless WiFi builds get the config CLI on Serial, which is otherwise unused there. --- examples/companion_radio/MyMesh.cpp | 34 ++++++++++++++++++++++++++++ examples/companion_radio/NodePrefs.h | 27 +++++++++++++++++++++- examples/companion_radio/main.cpp | 13 +++++++++-- 3 files changed, 71 insertions(+), 3 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index ee8114ca..8550890e 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -932,6 +932,7 @@ MyMesh::MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMe _serial(NULL), telemetry(MAX_PACKET_PAYLOAD - 4), _store(&store), _ui(ui), _iter(0) { _iter_started = false; _cli_rescue = false; + cli_command[0] = 0; offline_queue_len = 0; app_target_ver = 0; clearPendingReqs(); @@ -2156,6 +2157,35 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* return true; } +#ifdef WIFI_SSID + // local console only: these are credentials, and remote admin has no business with them + if (sender_timestamp == 0) { + if (memcmp(command, "set wifi.ssid ", 14) == 0) { + StrHelper::strncpy(_prefs.wifi_ssid, &command[14], sizeof(_prefs.wifi_ssid)); + savePrefs(); + sprintf(reply, "> wifi.ssid is now %s (set wifi.pwd too, then reboot)", _prefs.wifi_ssid); + return true; + } + if (memcmp(command, "set wifi.pwd ", 13) == 0) { + StrHelper::strncpy(_prefs.wifi_pwd, &command[13], sizeof(_prefs.wifi_pwd)); + savePrefs(); + strcpy(reply, "> wifi.pwd updated (reboot to apply)"); + return true; + } + if (strcmp(command, "set wifi.clear") == 0) { + _prefs.wifi_ssid[0] = 0; + _prefs.wifi_pwd[0] = 0; + savePrefs(); + strcpy(reply, "> wifi config cleared, using build-time credentials (reboot to apply)"); + return true; + } + if (strcmp(command, "get wifi.ssid") == 0) { // no 'get wifi.pwd', by design + sprintf(reply, "> %s", _prefs.wifi_ssid[0] ? _prefs.wifi_ssid : "(build-time)"); + return true; + } + } +#endif + if (strcmp(command, "board") == 0) { strcpy(reply, board.getManufacturerName()); return true; @@ -2386,6 +2416,10 @@ void MyMesh::loop() { checkCLIRescueCmd(); } else { checkSerialInterface(); +#if defined(WIFI_SSID) && !defined(ENABLE_USB_INTERFACE) + // headless WiFi build: USB serial isn't a companion transport, so use it for config + checkCLIRescueCmd(); +#endif } // is there are pending dirty contacts write needed? diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index f6f9b887..c725c317 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -44,6 +44,10 @@ public: char default_scope_name[31]; uint8_t default_scope_key[16]; int8_t tz_offset = 0; +#ifdef WIFI_SSID + char wifi_ssid[33] = {0}; // if empty, the compile-time WIFI_SSID is used + char wifi_pwd[64] = {0}; +#endif private: class RadioPrefs : public CommonRadioPrefs { @@ -160,6 +164,20 @@ private: DynamicConfigSerializer custom; +#ifdef WIFI_SSID + class WiFiPrefs : public ConfigSerializer { + NodePrefs* _parent; + protected: + void structure() override { + def("ssid", _parent->wifi_ssid, sizeof(_parent->wifi_ssid)); + def("pwd", _parent->wifi_pwd, sizeof(_parent->wifi_pwd)); + } + public: + WiFiPrefs(NodePrefs* parent) : _parent(parent) { } + }; + WiFiPrefs wifi; +#endif + protected: void structure() override { def("name", node_name, sizeof(node_name)); @@ -172,9 +190,16 @@ protected: def("repeat", repeat); def("comp", companion); def("custom", custom); +#ifdef WIFI_SSID + def("wifi", wifi); +#endif } public: - NodePrefs() : radio(this), gps(this), companion(this), custom(&radio) { + NodePrefs() : radio(this), gps(this), companion(this), custom(&radio) +#ifdef WIFI_SSID + , wifi(this) +#endif + { node_name[0] = 0; default_scope_name[0] = 0; memset(default_scope_key, 0, sizeof(default_scope_key)); diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index 7c8c12b9..64aa3d26 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -110,6 +110,8 @@ void halt() { #ifdef WIFI_SSID bool wifi_needs_reconnect = false; unsigned long last_wifi_reconnect_attempt = 0; + const char* wifi_ssid = WIFI_SSID; // replaced by stored prefs, if set + const char* wifi_pwd = WIFI_PWD; #endif void setup() { @@ -206,7 +208,14 @@ void setup() { }); #endif - WiFi.begin(WIFI_SSID, WIFI_PWD); + // stored credentials win over the build-time ones ('set wifi.ssid <x>' over USB serial) + if (the_mesh.getNodePrefs()->wifi_ssid[0]) { + wifi_ssid = the_mesh.getNodePrefs()->wifi_ssid; + wifi_pwd = the_mesh.getNodePrefs()->wifi_pwd; + } + WIFI_DEBUG_PRINTLN("connecting to %s", wifi_ssid); + + WiFi.begin(wifi_ssid, wifi_pwd); wifi_interface.begin(TCP_PORT); interface_manager.addInterface(InterfaceType::WiFi, &wifi_interface); #endif @@ -273,7 +282,7 @@ void loop() { if (wifi_needs_reconnect && (millis() - last_wifi_reconnect_attempt > 10000)) { WIFI_DEBUG_PRINTLN("Attempting manual WiFi reconnect..."); #if defined(RP2040_PLATFORM) - WiFi.begin(WIFI_SSID, WIFI_PWD); // no reconnect() on this platform + WiFi.begin(wifi_ssid, wifi_pwd); // no reconnect() on this platform #else WiFi.disconnect(); WiFi.reconnect(); From 0f0c1dc75aaf823d939041d7b2285e3668739486 Mon Sep 17 00:00:00 2001 From: Michael Graff <mgraff@cardinalhq.io> Date: Fri, 4 Sep 2026 20:33:40 -0500 Subject: [PATCH 191/381] Fix blocking WiFi connect on RP2040, log link state arduino-pico's WiFi.begin() blocks for up to 2x its 15s timeout, which stalled the mesh loop on every reconnect attempt; use beginNoBlock(). Log the IP when the link comes up, and the status code when retrying. --- examples/companion_radio/main.cpp | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index 64aa3d26..f0c12908 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -112,6 +112,7 @@ void halt() { unsigned long last_wifi_reconnect_attempt = 0; const char* wifi_ssid = WIFI_SSID; // replaced by stored prefs, if set const char* wifi_pwd = WIFI_PWD; + bool wifi_was_connected = false; #endif void setup() { @@ -215,7 +216,11 @@ void setup() { } WIFI_DEBUG_PRINTLN("connecting to %s", wifi_ssid); +#if defined(RP2040_PLATFORM) + WiFi.beginNoBlock(wifi_ssid, wifi_pwd); // begin() blocks for up to 2x its 15s timeout +#else WiFi.begin(wifi_ssid, wifi_pwd); +#endif wifi_interface.begin(TCP_PORT); interface_manager.addInterface(InterfaceType::WiFi, &wifi_interface); #endif @@ -276,13 +281,21 @@ void loop() { // RP2040 has no WiFi event callbacks, so poll the link state instead #if defined(RP2040_PLATFORM) wifi_needs_reconnect = (WiFi.status() != WL_CONNECTED); + if (wifi_was_connected == wifi_needs_reconnect) { // link state changed + wifi_was_connected = !wifi_needs_reconnect; + if (wifi_was_connected) { + WIFI_DEBUG_PRINTLN("connected, listening on %s:%d", WiFi.localIP().toString().c_str(), TCP_PORT); + } else { + WIFI_DEBUG_PRINTLN("link lost"); + } + } #endif // Safely attempt to reconnect every 10 seconds if flagged if (wifi_needs_reconnect && (millis() - last_wifi_reconnect_attempt > 10000)) { - WIFI_DEBUG_PRINTLN("Attempting manual WiFi reconnect..."); + WIFI_DEBUG_PRINTLN("Attempting manual WiFi reconnect to %s (status %d)...", wifi_ssid, WiFi.status()); #if defined(RP2040_PLATFORM) - WiFi.begin(wifi_ssid, wifi_pwd); // no reconnect() on this platform + WiFi.beginNoBlock(wifi_ssid, wifi_pwd); // no reconnect() on this platform #else WiFi.disconnect(); WiFi.reconnect(); From 02cc250fc29a1556d7aa62888cfc1e6597510aec Mon Sep 17 00:00:00 2001 From: Michael Graff <mgraff@cardinalhq.io> Date: Fri, 4 Sep 2026 20:57:01 -0500 Subject: [PATCH 192/381] Address review findings on WiFi companion support - scope the serial config CLI to RP2040; it was exposing the rescue CLI (cat/rm/erase) on every ESP32 WiFi build, which gates it behind a physical long-press - bound and space out RP2040 rejoins: the core's join busy-waits, so cap it at 5s and retry every 30s instead of every 10s - stamp the reconnect timer in setup(), so the first loop() doesn't tear down an association that is still finishing DHCP - treat stored credentials as a pair, and pass NULL (not "") for an open network - teach build_as_lib.py where SerialWifiInterface moved --- build_as_lib.py | 2 ++ examples/companion_radio/MyMesh.cpp | 5 +++-- examples/companion_radio/main.cpp | 24 ++++++++++++++++++++---- 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/build_as_lib.py b/build_as_lib.py index d8e95378..fbc7c15a 100644 --- a/build_as_lib.py +++ b/build_as_lib.py @@ -20,10 +20,12 @@ for item in menv.get("CPPDEFINES", []): src_filter.append("+<helpers/stm32/*>") elif item == "ESP32": src_filter.append("+<helpers/esp32/*>") + src_filter.append("+<helpers/wifi/*>") elif item == "NRF52_PLATFORM": src_filter.append("+<helpers/nrf52/*>") elif item == "RP2040_PLATFORM": src_filter.append("+<helpers/rp2040/*>") + src_filter.append("+<helpers/wifi/*>") # DISPLAY HANDLING elif isinstance(item, tuple) and item[0] == "DISPLAY_CLASS": diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 8550890e..a8e305a6 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2416,8 +2416,9 @@ void MyMesh::loop() { checkCLIRescueCmd(); } else { checkSerialInterface(); -#if defined(WIFI_SSID) && !defined(ENABLE_USB_INTERFACE) - // headless WiFi build: USB serial isn't a companion transport, so use it for config +#if defined(WIFI_SSID) && defined(RP2040_PLATFORM) && !defined(ENABLE_USB_INTERFACE) + // RP2040 WiFi builds are headless and have no way into the rescue CLI (that needs a + // display + long-press), so serve config commands on the otherwise unused USB serial checkCLIRescueCmd(); #endif } diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index f0c12908..ff0794ab 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -36,6 +36,12 @@ MultiSerialInterface interface_manager; #ifndef TCP_PORT #define TCP_PORT 5000 #endif + #ifndef WIFI_RETRY_INTERVAL + #define WIFI_RETRY_INTERVAL 30000 // millis between reconnect attempts + #endif + #ifndef WIFI_RETRY_TIMEOUT + #define WIFI_RETRY_TIMEOUT 5000 // RP2040: cap on how long one join may block loop() + #endif #if defined(ESP32) || defined(RP2040_PLATFORM) #include <helpers/wifi/SerialWifiInterface.h> SerialWifiInterface wifi_interface; @@ -209,15 +215,23 @@ void setup() { }); #endif - // stored credentials win over the build-time ones ('set wifi.ssid <x>' over USB serial) + // stored credentials win over the build-time ones ('set wifi.ssid <x>' over USB serial). + // they are taken as a pair, so 'set wifi.ssid' alone gives an open-network join, not a + // silent fallback to the build-time password of a different network. if (the_mesh.getNodePrefs()->wifi_ssid[0]) { wifi_ssid = the_mesh.getNodePrefs()->wifi_ssid; wifi_pwd = the_mesh.getNodePrefs()->wifi_pwd; } + if (wifi_pwd[0] == 0) wifi_pwd = NULL; // NULL (not "") selects an open network WIFI_DEBUG_PRINTLN("connecting to %s", wifi_ssid); #if defined(RP2040_PLATFORM) - WiFi.beginNoBlock(wifi_ssid, wifi_pwd); // begin() blocks for up to 2x its 15s timeout + // ponytail: the join itself blocks inside the core (CYW43::begin busy-waits for the + // association), so every attempt stalls the mesh loop. beginNoBlock() only skips the + // extra DHCP wait. Give the first connect a full window, then bound the retries below. + // Upgrade path if the stall ever matters: run WiFi on core1. + WiFi.beginNoBlock(wifi_ssid, wifi_pwd); + last_wifi_reconnect_attempt = millis(); // let DHCP finish before the poll can retry #else WiFi.begin(wifi_ssid, wifi_pwd); #endif @@ -291,10 +305,12 @@ void loop() { } #endif - // Safely attempt to reconnect every 10 seconds if flagged - if (wifi_needs_reconnect && (millis() - last_wifi_reconnect_attempt > 10000)) { + // Safely attempt to reconnect if flagged. On RP2040 each attempt blocks the mesh loop + // for up to WIFI_RETRY_TIMEOUT, so retry less often and cap how long a join may stall. + if (wifi_needs_reconnect && (millis() - last_wifi_reconnect_attempt > WIFI_RETRY_INTERVAL)) { WIFI_DEBUG_PRINTLN("Attempting manual WiFi reconnect to %s (status %d)...", wifi_ssid, WiFi.status()); #if defined(RP2040_PLATFORM) + WiFi.setTimeout(WIFI_RETRY_TIMEOUT); WiFi.beginNoBlock(wifi_ssid, wifi_pwd); // no reconnect() on this platform #else WiFi.disconnect(); From b9fbf072abbe46dbb307919d3e7271216c81fa9a Mon Sep 17 00:00:00 2001 From: Michael Graff <mgraff@cardinalhq.io> Date: Sat, 5 Sep 2026 21:15:12 -0500 Subject: [PATCH 193/381] Fix config parser aborting on an empty object 'custom:{}' (a DynamicConfigSerializer with nothing set) hits EXPECT_KEY with a '}' and returns TOK_ERROR, so loadSerial stops there and silently drops every property after it. Nothing follows 'custom' in NodePrefs today, so it goes unnoticed until you add one. Also include stdlib.h, which Arduino.h was providing on-device but not in the native test build. --- src/helpers/ConfigSerializer.cpp | 2 + .../test_config_serializer.cpp | 41 +++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/src/helpers/ConfigSerializer.cpp b/src/helpers/ConfigSerializer.cpp index adff147f..36aff5cc 100644 --- a/src/helpers/ConfigSerializer.cpp +++ b/src/helpers/ConfigSerializer.cpp @@ -1,4 +1,5 @@ #include "ConfigSerializer.h" +#include <stdlib.h> // atoi/atol/atof (Arduino.h pulls this in on-device, native builds do not) bool ConfigSerializer::saveSerial(Stream& s) { Context context(&s, OP::WRITE); @@ -62,6 +63,7 @@ int ConfigSerializer::Context::readNext() { case EXPECT_COMMA_OR_KEY: if (c == ',') { rd_mode = EXPECT_KEY; return TOK_WHITESPACE; } case EXPECT_KEY: + if (rd_len == 0 && c == '}') { rd_mode = EXPECT_COMMA_OR_KEY_OR_CLOSE; return TOK_END_OBJ; } // empty object, eg. 'custom:{}' if (rd_len > 0 && c == ':') { rd_buf[rd_len] = 0; rd_len = 0; rd_mode = EXPECT_VAL_OR_OBJ; return TOK_KEY; } if (rd_len == 0 && is_whitespace(c)) return TOK_WHITESPACE; if (rd_len < CONFIG_MAX_KEYLEN-1 && is_key_char(c)) { rd_buf[rd_len++] = c; return TOK_WHITESPACE; } diff --git a/test/test_config_serializer/test_config_serializer.cpp b/test/test_config_serializer/test_config_serializer.cpp index dec55483..80d5e780 100644 --- a/test/test_config_serializer/test_config_serializer.cpp +++ b/test/test_config_serializer/test_config_serializer.cpp @@ -185,6 +185,47 @@ TEST(ConfigSerializer, LoadSerial_IgnoreUnknowns) { EXPECT_TRUE(match); } +class TestNested : public ConfigSerializer { + class Inner : public ConfigSerializer { + protected: + void structure() override { } // no properties, so it writes as '{}' + }; + Inner inner; + protected: + void structure() override { + def("age", age); + def("inner", inner); + def("name", name, sizeof(name)); // comes *after* the empty sub-object + } + public: + int32_t age; + char name[16]; +}; + +TEST(ConfigSerializer, LoadSerial_EmptyObject) { + MockInputStream s("{age:" TEST_INT_S ",inner:{},name:\"Scott\"}"); + TestNested data; + data.name[0] = 0; + + bool success = data.loadSerial(s); + EXPECT_TRUE(success); + + EXPECT_EQ(TEST_INT, data.age); + bool match = strcmp("Scott", data.name) == 0; + EXPECT_TRUE(match); // properties after an empty object must still load +} + +TEST(ConfigSerializer, LoadSerial_EmptyObjectWithWhitespace) { + MockInputStream s("{age:" TEST_INT_S ",inner:{ },name:\"Scott\"}"); + TestNested data; + data.name[0] = 0; + + bool success = data.loadSerial(s); + EXPECT_TRUE(success); + bool match = strcmp("Scott", data.name) == 0; + EXPECT_TRUE(match); +} + TEST(DynamicConfigSerializer, GetSet_Basic) { DynamicConfigSerializer data; From 552351457c03de6e99ce7e9bfc20cf46855c5c82 Mon Sep 17 00:00:00 2001 From: Rastislav Vysoky <recrof@gmail.com> Date: Sun, 6 Sep 2026 15:14:35 +0200 Subject: [PATCH 194/381] Companion CLI: fixed txdelay, direct.txdelay, agc.reset.interval, int.thresh --- examples/companion_radio/MyMesh.cpp | 10 +++++++--- examples/companion_radio/MyMesh.h | 3 +++ examples/companion_radio/NodePrefs.h | 28 ++++++++++++++++------------ 3 files changed, 26 insertions(+), 15 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index f5a4a5a9..53e6f4d5 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -261,7 +261,7 @@ float MyMesh::getAirtimeBudgetFactor() const { } int MyMesh::getInterferenceThreshold() const { - return 0; // disabled for now, until currentRSSI() problem is resolved + return _prefs.interference_threshold; } bool MyMesh::getCADEnabled() const { return _prefs.cad_enabled; @@ -273,11 +273,11 @@ int MyMesh::calcRxDelay(float score, uint32_t air_time) const { } uint32_t MyMesh::getRetransmitDelay(const mesh::Packet *packet) { - uint32_t t = (_radio->getEstAirtimeFor(packet->getPathByteLen() + packet->payload_len + 2) * 0.5f); + uint32_t t = (_radio->getEstAirtimeFor(packet->getPathByteLen() + packet->payload_len + 2) * _prefs.tx_delay_factor); return getRNG()->nextInt(0, 5*t + 1); } uint32_t MyMesh::getDirectRetransmitDelay(const mesh::Packet *packet) { - uint32_t t = (_radio->getEstAirtimeFor(packet->getPathByteLen() + packet->payload_len + 2) * 0.2f); + uint32_t t = (_radio->getEstAirtimeFor(packet->getPathByteLen() + packet->payload_len + 2) * _prefs.direct_tx_delay_factor); return getRNG()->nextInt(0, 5*t + 1); } @@ -890,6 +890,8 @@ MyMesh::MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMe // defaults _prefs.airtime_factor = 1.0; + _prefs.tx_delay_factor = 0.5f; + _prefs.direct_tx_delay_factor = 0.2f; strcpy(_prefs.node_name, "NONAME"); _prefs.freq = LORA_FREQ; _prefs.sf = LORA_SF; @@ -952,6 +954,8 @@ void MyMesh::begin(bool has_display) { // sanitise bad pref values _prefs.rx_delay_base = constrain(_prefs.rx_delay_base, 0, 20.0f); + _prefs.tx_delay_factor = constrain(_prefs.tx_delay_factor, 0, 2.0f); + _prefs.direct_tx_delay_factor = constrain(_prefs.direct_tx_delay_factor, 0, 2.0f); _prefs.airtime_factor = constrain(_prefs.airtime_factor, 0, 9.0f); _prefs.freq = constrain(_prefs.freq, 150.0f, 2500.0f); _prefs.bw = constrain(_prefs.bw, 7.8f, 500.0f); diff --git a/examples/companion_radio/MyMesh.h b/examples/companion_radio/MyMesh.h index 780de35d..4aab11cd 100644 --- a/examples/companion_radio/MyMesh.h +++ b/examples/companion_radio/MyMesh.h @@ -106,6 +106,9 @@ protected: float getAirtimeBudgetFactor() const override; int getInterferenceThreshold() const override; bool getCADEnabled() const override; + int getAGCResetInterval() const override { + return ((int)_prefs.agc_reset_interval) * 4000; // milliseconds + } int calcRxDelay(float score, uint32_t air_time) const override; uint32_t getRetransmitDelay(const mesh::Packet *packet) override; uint32_t getDirectRetransmitDelay(const mesh::Packet *packet) override; diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index c8a9ab83..4581185e 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -27,6 +27,8 @@ public: uint8_t telemetry_mode_loc = 0; uint8_t telemetry_mode_env = 0; float rx_delay_base = 0; + float tx_delay_factor = 0; + float direct_tx_delay_factor = 0; uint32_t ble_pin = 0; uint8_t advert_loc_policy = 0; uint8_t buzzer_quiet = 0; @@ -41,6 +43,8 @@ public: uint8_t path_hash_mode = 0; // which path mode to use when sending uint8_t autoadd_max_hops = 0; // 0 = no limit, 1 = direct (0 hops), N = up to N-1 hops (max 64) uint8_t cad_enabled = 0; + uint8_t interference_threshold = 0; + uint8_t agc_reset_interval = 0; // secs / 4 char default_scope_name[31]; uint8_t default_scope_key[16]; @@ -54,16 +58,16 @@ private: def("sf", _parent->sf); def("cr", _parent->cr); def("cad", _parent->cad_enabled); - //def("int_thr", _parent->interference_threshold); + def("int_thr", _parent->interference_threshold); def("rxgain", _parent->rx_boosted_gain); def("fem_rxgain", _parent->radio_fem_rxgain); // fem_rxgain WAS mapped to wrong JSON property previously def("fem_txgain", _parent->radio_fem_txgain); def("tx", _parent->tx_power_dbm); def("af", _parent->airtime_factor); def("rxdelay", _parent->rx_delay_base); - //def("f_txdelay", _parent->tx_delay_factor); currently hard-coded - //def("d_txdelay", _parent->direct_tx_delay_factor); currently hard-coded - //def("agc_int", _parent->agc_reset_interval); + def("f_txdelay", _parent->tx_delay_factor); + def("d_txdelay", _parent->direct_tx_delay_factor); + def("agc_int", _parent->agc_reset_interval); def("hash_mode", _parent->path_hash_mode); def("multi_ack", _parent->multi_acks); } @@ -83,24 +87,24 @@ private: void setAirtimeFactor(float af) override { _parent->airtime_factor = af; markDirty(); } bool isCadEnabled() const override { return _parent->cad_enabled; } void setCadEnabled(bool en) override { _parent->cad_enabled = en; markDirty(); } - uint8_t getIntThresh() const override { return 0; } - void setIntThresh(uint8_t t) override { /* no-op */ } + uint8_t getIntThresh() const override { return _parent->interference_threshold; } + void setIntThresh(uint8_t t) override { _parent->interference_threshold = t; markDirty(); } uint8_t getRxGain() const override { return _parent->rx_boosted_gain; } void setRxGain(uint8_t g) override { _parent->rx_boosted_gain = g; markDirty(); } uint8_t getTxPower() const override { return _parent->tx_power_dbm; } void setTxPower(uint8_t dbm) override { _parent->tx_power_dbm = dbm; markDirty(); } float getRxDelay() const override { return _parent->rx_delay_base; } void setRxDelay(float d) override { _parent->rx_delay_base = d; markDirty(); } - uint8_t getAgcResetInt() const override { return 0; } - void setAgcResetInt(uint8_t secs) override { /* no-op */ } + uint8_t getAgcResetInt() const override { return _parent->agc_reset_interval * 4; } + void setAgcResetInt(uint8_t secs) override { _parent->agc_reset_interval = secs / 4; markDirty(); } uint8_t getHashMode() const override { return _parent->path_hash_mode; } void setHashMode(uint8_t m) override { _parent->path_hash_mode = m; markDirty(); } uint8_t getMultiAcks() const override { return _parent->multi_acks; } void setMultiAcks(uint8_t m) override { _parent->multi_acks = m; markDirty(); } - float getFloodTxDelay() const override { return 0.5f; } // currently hard-coded - void setFloodTxDelay(float d) override { /* no-op */ } - float getDirectTxDelay() const override { return 0.2f; } // currently hard-coded - void setDirectTxDelay(float d) override { /* no-op */ } + float getFloodTxDelay() const override { return _parent->tx_delay_factor; } + void setFloodTxDelay(float d) override { _parent->tx_delay_factor = d; markDirty(); } + float getDirectTxDelay() const override { return _parent->direct_tx_delay_factor; } + void setDirectTxDelay(float d) override { _parent->direct_tx_delay_factor = d; markDirty(); } uint8_t getFEMRxGain() const override { return _parent->radio_fem_rxgain; } void setFEMRxGain(uint8_t g) override { _parent->radio_fem_rxgain = g; markDirty(); } uint8_t getFEMTxGain() const override { return _parent->radio_fem_txgain; } From 5344e73dec2a46f62308aaa232c1594a94e2d400 Mon Sep 17 00:00:00 2001 From: Michael Graff <mgraff@cardinalhq.io> Date: Sun, 6 Sep 2026 20:15:45 -0500 Subject: [PATCH 195/381] Add BLE companion support for Pico W --- examples/companion_radio/main.cpp | 4 + src/helpers/rp2040/SerialBLEInterface.cpp | 198 ++++++++++++++++++++++ src/helpers/rp2040/SerialBLEInterface.h | 75 ++++++++ variants/rpi_picow/platformio.ini | 50 ++++-- 4 files changed, 314 insertions(+), 13 deletions(-) create mode 100644 src/helpers/rp2040/SerialBLEInterface.cpp create mode 100644 src/helpers/rp2040/SerialBLEInterface.h diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index ff0794ab..85923a15 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -26,6 +26,10 @@ MultiSerialInterface interface_manager; // include nrf52 bluetooth interface #include <helpers/nrf52/SerialBLEInterface.h> SerialBLEInterface bluetooth_interface; + #elif defined(RP2040_PLATFORM) + // include rp2040 (Pico W / CYW43) bluetooth interface + #include <helpers/rp2040/SerialBLEInterface.h> + SerialBLEInterface bluetooth_interface; #else #error "SerialBLEInterface is not defined for this platform" #endif diff --git a/src/helpers/rp2040/SerialBLEInterface.cpp b/src/helpers/rp2040/SerialBLEInterface.cpp new file mode 100644 index 00000000..f0321003 --- /dev/null +++ b/src/helpers/rp2040/SerialBLEInterface.cpp @@ -0,0 +1,198 @@ +#include "SerialBLEInterface.h" +#include <BluetoothLock.h> +#include <stdio.h> +#include <string.h> + +// Nordic UART 6E4000xx-B5A3-F393-E0A9-E50E24DCCA9E, as raw bytes: the core lib's string +// parser uses sscanf("%llx"), which newlib-nano on the RP2040 doesn't support (yields all zeros) +#define NUS_UUID(n) { 0x6E, 0x40, 0x00, n, 0xB5, 0xA3, 0xF3, 0x93, 0xE0, 0xA9, 0xE5, 0x0E, 0x24, 0xDC, 0xCA, 0x9E } +static const uint8_t SERVICE_UUID[16] = NUS_UUID(0x01); +static const uint8_t CHARACTERISTIC_UUID_RX[16] = NUS_UUID(0x02); +static const uint8_t CHARACTERISTIC_UUID_TX[16] = NUS_UUID(0x03); + +// The BLE core lib's own setValue()/notify path reallocs the value buffer on every call, +// so a second frame queued before the radio drained the first would corrupt it. We keep our +// own frame queue and drive att_server_notify() from the can-send-now callback instead. + +SerialBLEInterface::SerialBLEInterface() + : BLEService(BLEUUID(SERVICE_UUID)), + _rx(BLEUUID(CHARACTERISTIC_UUID_RX), BLEWrite, nullptr, ATT_SECURITY_AUTHENTICATED, ATT_SECURITY_AUTHENTICATED), + _tx(BLEUUID(CHARACTERISTIC_UUID_TX), BLERead | BLENotify, nullptr, ATT_SECURITY_AUTHENTICATED, ATT_SECURITY_AUTHENTICATED) +{ + _isEnabled = false; + _tx_pending = false; + send_queue_len = 0; + recv_queue_len = 0; + memset(&_can_send, 0, sizeof(_can_send)); + _rx.setCallbacks(this); + addCharacteristic(&_rx); + addCharacteristic(&_tx); +} + +void SerialBLEInterface::begin(const char* prefix, char* name, uint32_t pin_code) { + // JustWorks here only makes the server request pairing on connect; caps are overridden below + BLE.setSecurity(BLESecurityJustWorks); + // adv data carries the 128-bit service UUID, leaving room for only 8 name chars; + // the full name goes in the scan response + BLE.begin(prefix); + + if (strcmp(name, "@@MAC") == 0) { + bd_addr_t a; + gap_local_bd_addr(a); + sprintf(name, "%02X%02X%02X%02X%02X%02X", a[0], a[1], a[2], a[3], a[4], a[5]); // modify (IN-OUT param) + } + char dev_name[32+16]; + snprintf(dev_name, sizeof(dev_name), "%s%s", prefix, name); + + BLE.server()->setName(dev_name); // GAP device name characteristic + BLE.server()->addService(this); + BLE.server()->setCallbacks(this); + + // static passkey pairing with MITM protection, matching the esp32/nrf52 interfaces + sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_ONLY); + sm_set_authentication_requirements(SM_AUTHREQ_MITM_PROTECTION | SM_AUTHREQ_BONDING); + sm_use_fixed_passkey_in_display_role(pin_code); + + size_t n = strlen(dev_name); + if (n > sizeof(_scan_rsp) - 2) n = sizeof(_scan_rsp) - 2; + _scan_rsp[0] = n + 1; + _scan_rsp[1] = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME; + memcpy(&_scan_rsp[2], dev_name, n); + gap_scan_response_set_data(n + 2, _scan_rsp); + + BLE_DEBUG_PRINTLN("begin: name=%s", dev_name); +} + +void SerialBLEInterface::clearBuffers() { + send_queue_len = 0; + recv_queue_len = 0; + _tx_pending = false; // a stale registration just fires into an empty queue; BTstack ignores double-adds +} + +void SerialBLEInterface::onConnect(BLEServer* s) { + BLE_DEBUG_PRINTLN("connected handle=0x%04X", _tx.conHandle()); + clearBuffers(); +} + +void SerialBLEInterface::onDisconnect(BLEServer* s) { + BLE_DEBUG_PRINTLN("disconnected"); + clearBuffers(); // BTstack re-enables advertising on its own +} + +void SerialBLEInterface::onWrite(BLECharacteristic* c) { + if (c != &_rx) return; + size_t len = _rx.valueLen(); + if (len == 0 || len > MAX_FRAME_SIZE) { + BLE_DEBUG_PRINTLN("onWrite: bad frame len=%u", (unsigned)len); + return; + } + if (recv_queue_len >= FRAME_QUEUE_SIZE) { + BLE_DEBUG_PRINTLN("onWrite: recv queue full, dropping frame"); + return; + } + recv_queue[recv_queue_len].len = len; + memcpy(recv_queue[recv_queue_len].buf, _rx.valueData(), len); + recv_queue_len++; +} + +// caller holds the BT lock (or is in the BT context) +void SerialBLEInterface::kickSend() { + if (_tx_pending) return; + _tx_pending = true; + _can_send.callback = onCanSend; + _can_send.context = this; + if (att_server_register_can_send_now_callback(&_can_send, _tx.conHandle()) != 0) { + _tx_pending = false; + } +} + +// BT context: one notification per can-send-now, re-arm while frames remain +void SerialBLEInterface::sendNext() { + _tx_pending = false; + if (send_queue_len == 0) return; + if (!isConnected()) { + BLE_DEBUG_PRINTLN("sendNext: not connected, clearing send queue"); + send_queue_len = 0; + return; + } + uint16_t h = _tx.conHandle(); + Frame& f = send_queue[0]; + uint16_t mtu = att_server_get_mtu(h); + if (f.len + 3 > mtu) { + // att would silently truncate; drop instead (client must negotiate MTU >= MAX_FRAME_SIZE+3) + BLE_DEBUG_PRINTLN("sendNext: frame len=%u exceeds mtu=%u, dropping", f.len, mtu); + } else { + uint8_t err = att_server_notify(h, _tx.valueHandle(), f.buf, f.len); + if (err == BTSTACK_ACL_BUFFERS_FULL) { + kickSend(); + return; + } + if (err) { + BLE_DEBUG_PRINTLN("sendNext: notify failed err=%u, dropping", err); + } else { + BLE_DEBUG_PRINTLN("writeBytes: sz=%u, hdr=%u", f.len, f.buf[0]); + } + } + send_queue_len--; + memmove(&send_queue[0], &send_queue[1], send_queue_len * sizeof(Frame)); + if (send_queue_len > 0) kickSend(); +} + +void SerialBLEInterface::enable() { + if (_isEnabled) return; + _isEnabled = true; + clearBuffers(); + BLE.startAdvertising(true); +} + +void SerialBLEInterface::disconnect() { + uint16_t h = _tx.conHandle(); + if (h) gap_disconnect(h); +} + +void SerialBLEInterface::disable() { + _isEnabled = false; + BLE_DEBUG_PRINTLN("disable"); + disconnect(); + BLE.stopAdvertising(); +} + +bool SerialBLEInterface::isConnected() const { + // notifications can only be enabled once the link is authenticated (CCCD inherits the perms) + return _isEnabled && _tx.conHandle() != 0 && _tx.notifyEnabled(); +} + +bool SerialBLEInterface::isWriteBusy() const { + return send_queue_len >= (FRAME_QUEUE_SIZE * 2 / 3); +} + +size_t SerialBLEInterface::writeFrame(const uint8_t src[], size_t len) { + if (len == 0 || len > MAX_FRAME_SIZE) { + BLE_DEBUG_PRINTLN("writeFrame(), frame too big, len=%u", (unsigned)len); + return 0; + } + if (!isConnected()) return 0; + + BluetoothLock lock; + if (send_queue_len >= FRAME_QUEUE_SIZE) { + BLE_DEBUG_PRINTLN("writeFrame(), send_queue is full!"); + return 0; + } + send_queue[send_queue_len].len = len; + memcpy(send_queue[send_queue_len].buf, src, len); + send_queue_len++; + kickSend(); + return len; +} + +size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) { + BluetoothLock lock; + if (recv_queue_len == 0) return 0; + + size_t len = recv_queue[0].len; + memcpy(dest, recv_queue[0].buf, len); + recv_queue_len--; + memmove(&recv_queue[0], &recv_queue[1], recv_queue_len * sizeof(Frame)); + BLE_DEBUG_PRINTLN("readBytes: sz=%u, hdr=%u", (unsigned)len, dest[0]); + return len; +} diff --git a/src/helpers/rp2040/SerialBLEInterface.h b/src/helpers/rp2040/SerialBLEInterface.h new file mode 100644 index 00000000..2e085a6c --- /dev/null +++ b/src/helpers/rp2040/SerialBLEInterface.h @@ -0,0 +1,75 @@ +#pragma once + +#include "../BaseSerialInterface.h" +#include <BLE.h> +#include <btstack.h> + +// Nordic UART service over the arduino-pico BLE library (BTstack on the CYW43). +// Build with -D PIO_FRAMEWORK_ARDUINO_ENABLE_BLUETOOTH so the core links liblwip-bt. +class SerialBLEInterface : public BaseSerialInterface, BLEService, BLEServerCallbacks, BLECharacteristicCallbacks { + // subclass only to reach the protected connection/notify state + struct Characteristic : public BLECharacteristic { + using BLECharacteristic::BLECharacteristic; + uint16_t valueHandle() const { return _valueHandle; } + uint16_t conHandle() const { return con_handle; } + bool notifyEnabled() const { return _notificationEnabled; } + }; + + struct Frame { + uint8_t len; + uint8_t buf[MAX_FRAME_SIZE]; + }; + + #define FRAME_QUEUE_SIZE 8 + + Characteristic _rx; + Characteristic _tx; + bool _isEnabled; + bool _tx_pending; // a can-send-now callback is registered + btstack_context_callback_registration_t _can_send; + uint8_t _scan_rsp[31]; // complete local name; BTstack keeps the pointer + + uint8_t send_queue_len; + Frame send_queue[FRAME_QUEUE_SIZE]; + uint8_t recv_queue_len; + Frame recv_queue[FRAME_QUEUE_SIZE]; + + void clearBuffers(); + void kickSend(); + void sendNext(); + static void onCanSend(void* ctx) { ((SerialBLEInterface*)ctx)->sendNext(); } + + // BLE library callbacks (run in the BT context) + void onWrite(BLECharacteristic* c) override; + void onConnect(BLEServer* s) override; + void onDisconnect(BLEServer* s) override; + +public: + SerialBLEInterface(); + + /** + * init the BLE interface. + * @param prefix a prefix for the device name + * @param name IN/OUT - a name for the device (combined with prefix). If "@@MAC", is modified and returned + * @param pin_code the BLE security pin + */ + void begin(const char* prefix, char* name, uint32_t pin_code); + + void disconnect(); + 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 diff --git a/variants/rpi_picow/platformio.ini b/variants/rpi_picow/platformio.ini index 32944a9a..c4180650 100644 --- a/variants/rpi_picow/platformio.ini +++ b/variants/rpi_picow/platformio.ini @@ -67,19 +67,43 @@ lib_deps = ${rpi_picow.lib_deps} densaugeo/base64 @ ~1.4.0 lib_ignore = BLE -; [env:PicoW_companion_radio_ble] -; extends = rpi_picow -; build_flags = ${rpi_picow.build_flags} -; -D MAX_CONTACTS=100 -; -D MAX_GROUP_CHANNELS=8 -; -D BLE_PIN_CODE=123456 -; -D BLE_DEBUG_LOGGING=1 -; ; -D MESH_PACKET_LOGGING=1 -; ; -D MESH_DEBUG=1 -; build_src_filter = ${rpi_picow.build_src_filter} -; +<../examples/companion_radio/*.cpp> -; lib_deps = ${rpi_picow.lib_deps} -; densaugeo/base64 @ ~1.4.0 +[env:PicoW_companion_radio_ble] +extends = rpi_picow +build_flags = ${rpi_picow.build_flags} + -D MAX_CONTACTS=100 + -D MAX_GROUP_CHANNELS=8 + -D PIO_FRAMEWORK_ARDUINO_ENABLE_BLUETOOTH + -D BLE_PIN_CODE=123456 + -D BLE_DEBUG_LOGGING=1 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${rpi_picow.build_src_filter} + +<helpers/rp2040/SerialBLEInterface.cpp> + +<../examples/companion_radio/*.cpp> +lib_deps = ${rpi_picow.lib_deps} + densaugeo/base64 @ ~1.4.0 + +; USB + WiFi + BLE together; the interface manager fans frames out to all of them +[env:PicoW_companion_radio_all] +extends = rpi_picow +build_flags = ${rpi_picow.build_flags} + -D MAX_CONTACTS=100 + -D MAX_GROUP_CHANNELS=8 + -D ENABLE_USB_INTERFACE + -D PIO_FRAMEWORK_ARDUINO_ENABLE_BLUETOOTH + -D BLE_PIN_CODE=123456 + -D BLE_DEBUG_LOGGING=1 + -D WIFI_DEBUG_LOGGING=1 + -D WIFI_SSID='"myssid"' + -D WIFI_PWD='"mypwd"' +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${rpi_picow.build_src_filter} + +<helpers/rp2040/SerialBLEInterface.cpp> + +<helpers/wifi/*.cpp> + +<../examples/companion_radio/*.cpp> +lib_deps = ${rpi_picow.lib_deps} + densaugeo/base64 @ ~1.4.0 [env:PicoW_companion_radio_wifi] extends = rpi_picow From b0e7bc385aa86a2a1259098269ab2e61ec3d944c Mon Sep 17 00:00:00 2001 From: Michael Graff <mgraff@cardinalhq.io> Date: Sun, 6 Sep 2026 20:43:37 -0500 Subject: [PATCH 196/381] Fix review findings on Pico W WiFi/BLE --- examples/companion_radio/MyMesh.cpp | 3 ++- examples/companion_radio/main.cpp | 21 +++++++++++++-------- src/helpers/rp2040/SerialBLEInterface.cpp | 3 +++ variants/rpi_picow/platformio.ini | 4 ++-- 4 files changed, 20 insertions(+), 11 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index a8e305a6..4eea0b2f 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2158,7 +2158,8 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* } #ifdef WIFI_SSID - // local console only: these are credentials, and remote admin has no business with them + // not accepted from the remote mesh CLI (timestamp != 0): these are credentials. The app + // over USB/BLE/WiFi and the serial console (timestamp 0) may set them. if (sender_timestamp == 0) { if (memcmp(command, "set wifi.ssid ", 14) == 0) { StrHelper::strncpy(_prefs.wifi_ssid, &command[14], sizeof(_prefs.wifi_ssid)); diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index 85923a15..6b6d7cf7 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -41,7 +41,11 @@ MultiSerialInterface interface_manager; #define TCP_PORT 5000 #endif #ifndef WIFI_RETRY_INTERVAL - #define WIFI_RETRY_INTERVAL 30000 // millis between reconnect attempts + #if defined(RP2040_PLATFORM) + #define WIFI_RETRY_INTERVAL 30000 // each attempt blocks loop(), so retry less often + #else + #define WIFI_RETRY_INTERVAL 10000 // millis between reconnect attempts + #endif #endif #ifndef WIFI_RETRY_TIMEOUT #define WIFI_RETRY_TIMEOUT 5000 // RP2040: cap on how long one join may block loop() @@ -120,8 +124,8 @@ void halt() { #ifdef WIFI_SSID bool wifi_needs_reconnect = false; unsigned long last_wifi_reconnect_attempt = 0; - const char* wifi_ssid = WIFI_SSID; // replaced by stored prefs, if set - const char* wifi_pwd = WIFI_PWD; + char wifi_ssid[33] = WIFI_SSID; // replaced by stored prefs at boot, if set + char wifi_pwd[64] = WIFI_PWD; bool wifi_was_connected = false; #endif @@ -220,13 +224,14 @@ void setup() { #endif // stored credentials win over the build-time ones ('set wifi.ssid <x>' over USB serial). - // they are taken as a pair, so 'set wifi.ssid' alone gives an open-network join, not a - // silent fallback to the build-time password of a different network. + // they are taken as a pair, so 'set wifi.ssid' alone gives an empty password, not a + // silent fallback to the build-time password of a different network. Copied out of prefs + // so 'set wifi.*' edits only take effect on reboot, as their replies promise. + // (No NULL-for-open-network: the RP2040 core does strlen() on the password unguarded.) if (the_mesh.getNodePrefs()->wifi_ssid[0]) { - wifi_ssid = the_mesh.getNodePrefs()->wifi_ssid; - wifi_pwd = the_mesh.getNodePrefs()->wifi_pwd; + strcpy(wifi_ssid, the_mesh.getNodePrefs()->wifi_ssid); + strcpy(wifi_pwd, the_mesh.getNodePrefs()->wifi_pwd); } - if (wifi_pwd[0] == 0) wifi_pwd = NULL; // NULL (not "") selects an open network WIFI_DEBUG_PRINTLN("connecting to %s", wifi_ssid); #if defined(RP2040_PLATFORM) diff --git a/src/helpers/rp2040/SerialBLEInterface.cpp b/src/helpers/rp2040/SerialBLEInterface.cpp index f0321003..a1fa487e 100644 --- a/src/helpers/rp2040/SerialBLEInterface.cpp +++ b/src/helpers/rp2040/SerialBLEInterface.cpp @@ -1,3 +1,5 @@ +// only built when the env enables the core BLE stack (build_as_lib.py globs this dir) +#ifdef PIO_FRAMEWORK_ARDUINO_ENABLE_BLUETOOTH #include "SerialBLEInterface.h" #include <BluetoothLock.h> #include <stdio.h> @@ -196,3 +198,4 @@ size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) { BLE_DEBUG_PRINTLN("readBytes: sz=%u, hdr=%u", (unsigned)len, dest[0]); return len; } +#endif diff --git a/variants/rpi_picow/platformio.ini b/variants/rpi_picow/platformio.ini index c4180650..f99b1341 100644 --- a/variants/rpi_picow/platformio.ini +++ b/variants/rpi_picow/platformio.ini @@ -92,8 +92,8 @@ build_flags = ${rpi_picow.build_flags} -D ENABLE_USB_INTERFACE -D PIO_FRAMEWORK_ARDUINO_ENABLE_BLUETOOTH -D BLE_PIN_CODE=123456 - -D BLE_DEBUG_LOGGING=1 - -D WIFI_DEBUG_LOGGING=1 +; NOTE: DO NOT ENABLE --> -D BLE_DEBUG_LOGGING=1 (shares Serial with the USB interface) +; NOTE: DO NOT ENABLE --> -D WIFI_DEBUG_LOGGING=1 -D WIFI_SSID='"myssid"' -D WIFI_PWD='"mypwd"' ; -D MESH_PACKET_LOGGING=1 From 233a46efeb3fef3c81d94df85eeb0f2fee268b4a Mon Sep 17 00:00:00 2001 From: Michael Graff <mgraff@cardinalhq.io> Date: Sun, 6 Sep 2026 21:28:04 -0500 Subject: [PATCH 197/381] Address review: per-variant wifi src, real SSID reply, rename PicoW env --- examples/companion_radio/MyMesh.cpp | 2 +- platformio.ini | 1 - variants/heltec_rc32/platformio.ini | 2 ++ variants/heltec_tracker_v2/platformio.ini | 1 + variants/heltec_v2/platformio.ini | 1 + variants/heltec_v3/platformio.ini | 2 ++ variants/heltec_v4/platformio.ini | 2 ++ variants/heltec_v4_r8/platformio.ini | 2 ++ variants/lilygo_tbeam_1w/platformio.ini | 1 + variants/lilygo_tbeam_supreme_SX1262/platformio.ini | 1 + variants/lilygo_tlora_v2_1/platformio.ini | 1 + variants/meshnology_w12/platformio.ini | 1 + variants/nibble_screen_connect/platformio.ini | 1 + variants/nibble_zero_connect/platformio.ini | 1 + variants/rak3112/platformio.ini | 1 + variants/rpi_picow/platformio.ini | 2 +- variants/station_g2/platformio.ini | 1 + variants/station_g3_esp32/platformio.ini | 1 + variants/thinknode_m2/platformio.ini | 1 + variants/thinknode_m5/platformio.ini | 1 + variants/thinknode_m7/platformio.ini | 1 + variants/thinknode_m9/platformio.ini | 1 + variants/xiao_c3/platformio.ini | 1 + variants/xiao_s3_wio/platformio.ini | 1 + 24 files changed, 27 insertions(+), 3 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 4eea0b2f..e835d8ef 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2181,7 +2181,7 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* return true; } if (strcmp(command, "get wifi.ssid") == 0) { // no 'get wifi.pwd', by design - sprintf(reply, "> %s", _prefs.wifi_ssid[0] ? _prefs.wifi_ssid : "(build-time)"); + sprintf(reply, "> %s", _prefs.wifi_ssid[0] ? _prefs.wifi_ssid : WIFI_SSID); return true; } } diff --git a/platformio.ini b/platformio.ini index 622b01e2..2219c978 100644 --- a/platformio.ini +++ b/platformio.ini @@ -64,7 +64,6 @@ build_flags = ${arduino_base.build_flags} -D ESP32_PLATFORM ; -D ESP32_CPU_FREQ=80 ; change it to your need build_src_filter = ${arduino_base.build_src_filter} - +<helpers/wifi/*.cpp> [esp32_ota] lib_deps = diff --git a/variants/heltec_rc32/platformio.ini b/variants/heltec_rc32/platformio.ini index 354004f0..df986cf0 100644 --- a/variants/heltec_rc32/platformio.ini +++ b/variants/heltec_rc32/platformio.ini @@ -185,6 +185,7 @@ build_src_filter = ${Heltec_RC32.build_src_filter} +<helpers/ui/buzzer.cpp> +<helpers/ui/NullDisplayDriver.cpp> +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = @@ -324,6 +325,7 @@ build_flags = build_src_filter = ${Heltec_RC32_with_display.build_src_filter} +<helpers/ui/buzzer.cpp> +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = diff --git a/variants/heltec_tracker_v2/platformio.ini b/variants/heltec_tracker_v2/platformio.ini index d040b72f..178508d8 100644 --- a/variants/heltec_tracker_v2/platformio.ini +++ b/variants/heltec_tracker_v2/platformio.ini @@ -195,6 +195,7 @@ build_src_filter = ${Heltec_tracker_v2.build_src_filter} +<helpers/ui/ST7735Display.cpp> +<helpers/ui/MomentaryButton.cpp> +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = diff --git a/variants/heltec_v2/platformio.ini b/variants/heltec_v2/platformio.ini index 78561a14..28e80554 100644 --- a/variants/heltec_v2/platformio.ini +++ b/variants/heltec_v2/platformio.ini @@ -189,6 +189,7 @@ build_flags = ; -D MESH_DEBUG=1 build_src_filter = ${Heltec_lora32_v2.build_src_filter} +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<helpers/ui/SSD1306Display.cpp> +<helpers/ui/MomentaryButton.cpp> +<../examples/companion_radio/*.cpp> diff --git a/variants/heltec_v3/platformio.ini b/variants/heltec_v3/platformio.ini index 65e636eb..27541a8a 100644 --- a/variants/heltec_v3/platformio.ini +++ b/variants/heltec_v3/platformio.ini @@ -198,6 +198,7 @@ build_src_filter = ${Heltec_lora32_v3.build_src_filter} +<helpers/ui/SSD1306Display.cpp> +<helpers/ui/MomentaryButton.cpp> +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = @@ -350,6 +351,7 @@ build_flags = ; -D MESH_DEBUG=1 build_src_filter = ${Heltec_lora32_v3.build_src_filter} +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<../examples/companion_radio/*.cpp> lib_deps = ${Heltec_lora32_v3.lib_deps} diff --git a/variants/heltec_v4/platformio.ini b/variants/heltec_v4/platformio.ini index d718c006..25f9ee3b 100644 --- a/variants/heltec_v4/platformio.ini +++ b/variants/heltec_v4/platformio.ini @@ -241,6 +241,7 @@ build_src_filter = ${heltec_v4_oled.build_src_filter} +<helpers/ui/SSD1306Display.cpp> +<helpers/ui/MomentaryButton.cpp> +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = @@ -406,6 +407,7 @@ build_src_filter = ${heltec_v4_tft.build_src_filter} +<helpers/ui/ST7789LCDDisplay.cpp> +<helpers/ui/MomentaryButton.cpp> +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = diff --git a/variants/heltec_v4_r8/platformio.ini b/variants/heltec_v4_r8/platformio.ini index f523ebf9..8c2feb94 100644 --- a/variants/heltec_v4_r8/platformio.ini +++ b/variants/heltec_v4_r8/platformio.ini @@ -186,6 +186,7 @@ build_src_filter = ${heltec_v4_r8_oled.build_src_filter} +<helpers/ui/SSD1306Display.cpp> +<helpers/ui/MomentaryButton.cpp> +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = @@ -311,6 +312,7 @@ build_src_filter = ${heltec_v4_r8_tft.build_src_filter} +<helpers/ui/ST7789LCDDisplay.cpp> +<helpers/ui/MomentaryButton.cpp> +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = diff --git a/variants/lilygo_tbeam_1w/platformio.ini b/variants/lilygo_tbeam_1w/platformio.ini index 0f604fac..16db0257 100644 --- a/variants/lilygo_tbeam_1w/platformio.ini +++ b/variants/lilygo_tbeam_1w/platformio.ini @@ -165,6 +165,7 @@ build_flags = ; -D MESH_DEBUG=1 build_src_filter = ${LilyGo_TBeam_1W.build_src_filter} +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = diff --git a/variants/lilygo_tbeam_supreme_SX1262/platformio.ini b/variants/lilygo_tbeam_supreme_SX1262/platformio.ini index 8bfc4093..a9991f25 100644 --- a/variants/lilygo_tbeam_supreme_SX1262/platformio.ini +++ b/variants/lilygo_tbeam_supreme_SX1262/platformio.ini @@ -160,6 +160,7 @@ build_flags = ; -D CORE_DEBUG_LEVEL=4 build_src_filter = ${T_Beam_S3_Supreme_SX1262.build_src_filter} +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<helpers/ui/MomentaryButton.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> diff --git a/variants/lilygo_tlora_v2_1/platformio.ini b/variants/lilygo_tlora_v2_1/platformio.ini index 1aea74d2..cf24a5d5 100644 --- a/variants/lilygo_tlora_v2_1/platformio.ini +++ b/variants/lilygo_tlora_v2_1/platformio.ini @@ -140,6 +140,7 @@ build_flags = -D OFFLINE_QUEUE_SIZE=128 build_src_filter = ${LilyGo_TLora_V2_1_1_6.build_src_filter} +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<helpers/ui/MomentaryButton.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> diff --git a/variants/meshnology_w12/platformio.ini b/variants/meshnology_w12/platformio.ini index 8255e46c..c0e8c80d 100644 --- a/variants/meshnology_w12/platformio.ini +++ b/variants/meshnology_w12/platformio.ini @@ -184,6 +184,7 @@ build_src_filter = ${meshnology_w12.build_src_filter} +<helpers/ui/SSD1306Display.cpp> +<helpers/ui/MomentaryButton.cpp> +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = diff --git a/variants/nibble_screen_connect/platformio.ini b/variants/nibble_screen_connect/platformio.ini index 112181df..3c5049e0 100644 --- a/variants/nibble_screen_connect/platformio.ini +++ b/variants/nibble_screen_connect/platformio.ini @@ -154,6 +154,7 @@ build_src_filter = ${nibble_screen_connect_base.build_src_filter} +<helpers/ui/SSD1306Display.cpp> +<helpers/ui/MomentaryButton.cpp> +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = diff --git a/variants/nibble_zero_connect/platformio.ini b/variants/nibble_zero_connect/platformio.ini index 1161743e..9789eabf 100644 --- a/variants/nibble_zero_connect/platformio.ini +++ b/variants/nibble_zero_connect/platformio.ini @@ -150,6 +150,7 @@ build_src_filter = ${nibble_zero_connect_base.build_src_filter} +<helpers/ui/SSD1306Display.cpp> +<helpers/ui/MomentaryButton.cpp> +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = diff --git a/variants/rak3112/platformio.ini b/variants/rak3112/platformio.ini index 8bd3c597..2fee8c26 100644 --- a/variants/rak3112/platformio.ini +++ b/variants/rak3112/platformio.ini @@ -182,6 +182,7 @@ build_flags = ; -D MESH_DEBUG=1 build_src_filter = ${rak3112.build_src_filter} +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-orig/*.cpp> lib_deps = diff --git a/variants/rpi_picow/platformio.ini b/variants/rpi_picow/platformio.ini index f99b1341..e54d86a6 100644 --- a/variants/rpi_picow/platformio.ini +++ b/variants/rpi_picow/platformio.ini @@ -84,7 +84,7 @@ lib_deps = ${rpi_picow.lib_deps} densaugeo/base64 @ ~1.4.0 ; USB + WiFi + BLE together; the interface manager fans frames out to all of them -[env:PicoW_companion_radio_all] +[env:PicoW_companion_radio] extends = rpi_picow build_flags = ${rpi_picow.build_flags} -D MAX_CONTACTS=100 diff --git a/variants/station_g2/platformio.ini b/variants/station_g2/platformio.ini index bdb7ee0c..d8bdd5e8 100644 --- a/variants/station_g2/platformio.ini +++ b/variants/station_g2/platformio.ini @@ -234,6 +234,7 @@ build_flags = ; -D MESH_DEBUG=1 build_src_filter = ${Station_G2.build_src_filter} +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = diff --git a/variants/station_g3_esp32/platformio.ini b/variants/station_g3_esp32/platformio.ini index 074d6a2e..477c135b 100644 --- a/variants/station_g3_esp32/platformio.ini +++ b/variants/station_g3_esp32/platformio.ini @@ -149,6 +149,7 @@ build_flags = ; -D MESH_DEBUG=1 build_src_filter = ${Station_G3_ESP32.build_src_filter} +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = diff --git a/variants/thinknode_m2/platformio.ini b/variants/thinknode_m2/platformio.ini index 583f913c..c1f5612a 100644 --- a/variants/thinknode_m2/platformio.ini +++ b/variants/thinknode_m2/platformio.ini @@ -184,6 +184,7 @@ build_flags = -D WIFI_PWD='"mypwd"' build_src_filter = ${ThinkNode_M2.build_src_filter} +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<helpers/ui/MomentaryButton.cpp> +<helpers/ui/buzzer.cpp> +<../examples/companion_radio/*.cpp> diff --git a/variants/thinknode_m5/platformio.ini b/variants/thinknode_m5/platformio.ini index 5e85b649..f64e4e77 100644 --- a/variants/thinknode_m5/platformio.ini +++ b/variants/thinknode_m5/platformio.ini @@ -198,6 +198,7 @@ build_flags = -D WIFI_PWD='"mypwd"' build_src_filter = ${ThinkNode_M5.build_src_filter} +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<helpers/ui/MomentaryButton.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> diff --git a/variants/thinknode_m7/platformio.ini b/variants/thinknode_m7/platformio.ini index 7d9892e5..508fc813 100644 --- a/variants/thinknode_m7/platformio.ini +++ b/variants/thinknode_m7/platformio.ini @@ -145,6 +145,7 @@ build_flags = ; -D MESH_PACKET_LOGGING=1 build_src_filter = ${ThinkNode_M7.build_src_filter} +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<helpers/ui/MomentaryButton.cpp> +<helpers/ui/NullDisplayDriver.cpp> +<../examples/companion_radio/*.cpp> diff --git a/variants/thinknode_m9/platformio.ini b/variants/thinknode_m9/platformio.ini index 09b1391d..085ab7d5 100755 --- a/variants/thinknode_m9/platformio.ini +++ b/variants/thinknode_m9/platformio.ini @@ -146,6 +146,7 @@ build_flags = ; -D MESH_PACKET_LOGGING=1 build_src_filter = ${ThinkNode_M9.build_src_filter} +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<helpers/ui/buzzer.cpp> +<helpers/ui/MomentaryButton.cpp> +<../examples/companion_radio/*.cpp> diff --git a/variants/xiao_c3/platformio.ini b/variants/xiao_c3/platformio.ini index c9c107c6..cca2907a 100644 --- a/variants/xiao_c3/platformio.ini +++ b/variants/xiao_c3/platformio.ini @@ -115,6 +115,7 @@ extends = Xiao_esp32_C3 build_src_filter = ${Xiao_esp32_C3.build_src_filter} +<../examples/companion_radio/*.cpp> +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> build_flags = ${Xiao_esp32_C3.build_flags} -D MAX_CONTACTS=350 diff --git a/variants/xiao_s3_wio/platformio.ini b/variants/xiao_s3_wio/platformio.ini index 293a13c1..de656c44 100644 --- a/variants/xiao_s3_wio/platformio.ini +++ b/variants/xiao_s3_wio/platformio.ini @@ -202,6 +202,7 @@ extends = Xiao_S3_WIO build_src_filter = ${Xiao_S3_WIO.build_src_filter} +<helpers/ui/NullDisplayDriver.cpp> +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<helpers/ui/MomentaryButton.cpp> +<../examples/companion_radio/*.cpp> build_flags = From fe8d6147d46a43db16fc3b7575c69eb1038326da Mon Sep 17 00:00:00 2001 From: Michael Graff <mgraff@cardinalhq.io> Date: Sun, 6 Sep 2026 21:44:47 -0500 Subject: [PATCH 198/381] Add get wifi.status and get wifi.ip CLI commands --- examples/companion_radio/MyMesh.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index e835d8ef..76e0dfde 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -1,6 +1,9 @@ #include "MyMesh.h" #include <Arduino.h> // needed for PlatformIO +#ifdef WIFI_SSID +#include <WiFi.h> +#endif #include <Mesh.h> #define CMD_APP_START 1 @@ -2184,6 +2187,18 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* sprintf(reply, "> %s", _prefs.wifi_ssid[0] ? _prefs.wifi_ssid : WIFI_SSID); return true; } + if (strcmp(command, "get wifi.status") == 0) { + strcpy(reply, WiFi.status() == WL_CONNECTED ? "> connected" : "> disconnected"); + return true; + } + if (strcmp(command, "get wifi.ip") == 0) { + if (WiFi.status() == WL_CONNECTED) { + sprintf(reply, "> %s", WiFi.localIP().toString().c_str()); + } else { + strcpy(reply, "> (not connected)"); + } + return true; + } } #endif From 0bb10d3902052a393723fbc71f45381cb61c53be Mon Sep 17 00:00:00 2001 From: Michael Graff <mgraff@cardinalhq.io> Date: Sun, 6 Sep 2026 21:56:25 -0500 Subject: [PATCH 199/381] Add wifi.enabled pref and CLI; skip WiFi when disabled or SSID blank --- examples/companion_radio/MyMesh.cpp | 10 +++ examples/companion_radio/NodePrefs.h | 2 + examples/companion_radio/main.cpp | 95 +++++++++++++++------------- 3 files changed, 64 insertions(+), 43 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 76e0dfde..2886ceb6 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2187,6 +2187,16 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* sprintf(reply, "> %s", _prefs.wifi_ssid[0] ? _prefs.wifi_ssid : WIFI_SSID); return true; } + if (memcmp(command, "set wifi.enabled ", 17) == 0) { + _prefs.wifi_enabled = atoi(&command[17]) ? 1 : 0; + savePrefs(); + sprintf(reply, "> wifi.enabled is now %d (reboot to apply)", _prefs.wifi_enabled); + return true; + } + if (strcmp(command, "get wifi.enabled") == 0) { + sprintf(reply, "> %d", _prefs.wifi_enabled); + return true; + } if (strcmp(command, "get wifi.status") == 0) { strcpy(reply, WiFi.status() == WL_CONNECTED ? "> connected" : "> disconnected"); return true; diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index c725c317..03323675 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -47,6 +47,7 @@ public: #ifdef WIFI_SSID char wifi_ssid[33] = {0}; // if empty, the compile-time WIFI_SSID is used char wifi_pwd[64] = {0}; + uint8_t wifi_enabled = 1; // 0 = never bring up WiFi (credentials may still be baked in) #endif private: @@ -171,6 +172,7 @@ private: void structure() override { def("ssid", _parent->wifi_ssid, sizeof(_parent->wifi_ssid)); def("pwd", _parent->wifi_pwd, sizeof(_parent->wifi_pwd)); + def("enabled", _parent->wifi_enabled); } public: WiFiPrefs(NodePrefs* parent) : _parent(parent) { } diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index 6b6d7cf7..cf761095 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -127,6 +127,7 @@ void halt() { char wifi_ssid[33] = WIFI_SSID; // replaced by stored prefs at boot, if set char wifi_pwd[64] = WIFI_PWD; bool wifi_was_connected = false; + bool wifi_enabled = false; // set at boot from prefs; false also when the effective SSID is blank #endif void setup() { @@ -208,21 +209,6 @@ void setup() { // add wifi interface #ifdef WIFI_SSID -#if defined(ESP32) - board.setInhibitSleep(true); // prevent sleep when WiFi is active - WiFi.setAutoReconnect(true); - - WiFi.onEvent([](WiFiEvent_t event, WiFiEventInfo_t info){ - if (event == ARDUINO_EVENT_WIFI_STA_DISCONNECTED) { - WIFI_DEBUG_PRINTLN("WiFi disconnected. Flagging for reconnect..."); - wifi_needs_reconnect = true; - } else if (event == ARDUINO_EVENT_WIFI_STA_GOT_IP) { - WIFI_DEBUG_PRINTLN("WiFi connected successfully!"); - wifi_needs_reconnect = false; - } - }); -#endif - // stored credentials win over the build-time ones ('set wifi.ssid <x>' over USB serial). // they are taken as a pair, so 'set wifi.ssid' alone gives an empty password, not a // silent fallback to the build-time password of a different network. Copied out of prefs @@ -232,20 +218,41 @@ void setup() { strcpy(wifi_ssid, the_mesh.getNodePrefs()->wifi_ssid); strcpy(wifi_pwd, the_mesh.getNodePrefs()->wifi_pwd); } - WIFI_DEBUG_PRINTLN("connecting to %s", wifi_ssid); + // 'set wifi.enabled 0' or a build with blank credentials leaves the radio off entirely + wifi_enabled = the_mesh.getNodePrefs()->wifi_enabled && wifi_ssid[0]; + if (wifi_enabled) { +#if defined(ESP32) + board.setInhibitSleep(true); // prevent sleep when WiFi is active + WiFi.setAutoReconnect(true); + + WiFi.onEvent([](WiFiEvent_t event, WiFiEventInfo_t info){ + if (event == ARDUINO_EVENT_WIFI_STA_DISCONNECTED) { + WIFI_DEBUG_PRINTLN("WiFi disconnected. Flagging for reconnect..."); + wifi_needs_reconnect = true; + } else if (event == ARDUINO_EVENT_WIFI_STA_GOT_IP) { + WIFI_DEBUG_PRINTLN("WiFi connected successfully!"); + wifi_needs_reconnect = false; + } + }); +#endif + + WIFI_DEBUG_PRINTLN("connecting to %s", wifi_ssid); #if defined(RP2040_PLATFORM) - // ponytail: the join itself blocks inside the core (CYW43::begin busy-waits for the - // association), so every attempt stalls the mesh loop. beginNoBlock() only skips the - // extra DHCP wait. Give the first connect a full window, then bound the retries below. - // Upgrade path if the stall ever matters: run WiFi on core1. - WiFi.beginNoBlock(wifi_ssid, wifi_pwd); - last_wifi_reconnect_attempt = millis(); // let DHCP finish before the poll can retry + // ponytail: the join itself blocks inside the core (CYW43::begin busy-waits for the + // association), so every attempt stalls the mesh loop. beginNoBlock() only skips the + // extra DHCP wait. Give the first connect a full window, then bound the retries below. + // Upgrade path if the stall ever matters: run WiFi on core1. + WiFi.beginNoBlock(wifi_ssid, wifi_pwd); + last_wifi_reconnect_attempt = millis(); // let DHCP finish before the poll can retry #else - WiFi.begin(wifi_ssid, wifi_pwd); + WiFi.begin(wifi_ssid, wifi_pwd); #endif - wifi_interface.begin(TCP_PORT); - interface_manager.addInterface(InterfaceType::WiFi, &wifi_interface); + wifi_interface.begin(TCP_PORT); + interface_manager.addInterface(InterfaceType::WiFi, &wifi_interface); + } else { + WIFI_DEBUG_PRINTLN("wifi disabled"); + } #endif // add usb interface @@ -301,31 +308,33 @@ void loop() { } #ifdef WIFI_SSID - // RP2040 has no WiFi event callbacks, so poll the link state instead + if (wifi_enabled) { + // RP2040 has no WiFi event callbacks, so poll the link state instead #if defined(RP2040_PLATFORM) - wifi_needs_reconnect = (WiFi.status() != WL_CONNECTED); - if (wifi_was_connected == wifi_needs_reconnect) { // link state changed - wifi_was_connected = !wifi_needs_reconnect; - if (wifi_was_connected) { - WIFI_DEBUG_PRINTLN("connected, listening on %s:%d", WiFi.localIP().toString().c_str(), TCP_PORT); - } else { - WIFI_DEBUG_PRINTLN("link lost"); + wifi_needs_reconnect = (WiFi.status() != WL_CONNECTED); + if (wifi_was_connected == wifi_needs_reconnect) { // link state changed + wifi_was_connected = !wifi_needs_reconnect; + if (wifi_was_connected) { + WIFI_DEBUG_PRINTLN("connected, listening on %s:%d", WiFi.localIP().toString().c_str(), TCP_PORT); + } else { + WIFI_DEBUG_PRINTLN("link lost"); + } } - } #endif - // Safely attempt to reconnect if flagged. On RP2040 each attempt blocks the mesh loop - // for up to WIFI_RETRY_TIMEOUT, so retry less often and cap how long a join may stall. - if (wifi_needs_reconnect && (millis() - last_wifi_reconnect_attempt > WIFI_RETRY_INTERVAL)) { - WIFI_DEBUG_PRINTLN("Attempting manual WiFi reconnect to %s (status %d)...", wifi_ssid, WiFi.status()); + // Safely attempt to reconnect if flagged. On RP2040 each attempt blocks the mesh loop + // for up to WIFI_RETRY_TIMEOUT, so retry less often and cap how long a join may stall. + if (wifi_needs_reconnect && (millis() - last_wifi_reconnect_attempt > WIFI_RETRY_INTERVAL)) { + WIFI_DEBUG_PRINTLN("Attempting manual WiFi reconnect to %s (status %d)...", wifi_ssid, WiFi.status()); #if defined(RP2040_PLATFORM) - WiFi.setTimeout(WIFI_RETRY_TIMEOUT); - WiFi.beginNoBlock(wifi_ssid, wifi_pwd); // no reconnect() on this platform + WiFi.setTimeout(WIFI_RETRY_TIMEOUT); + WiFi.beginNoBlock(wifi_ssid, wifi_pwd); // no reconnect() on this platform #else - WiFi.disconnect(); - WiFi.reconnect(); + WiFi.disconnect(); + WiFi.reconnect(); #endif - last_wifi_reconnect_attempt = millis(); + last_wifi_reconnect_attempt = millis(); + } } #endif } From ca3adef039d5bae8f2148c6ed84221201825573e Mon Sep 17 00:00:00 2001 From: Michael Graff <mgraff@cardinalhq.io> Date: Sun, 6 Sep 2026 22:05:29 -0500 Subject: [PATCH 200/381] Default wifi.enabled to 0 --- examples/companion_radio/NodePrefs.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index 03323675..68facfbe 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -47,7 +47,7 @@ public: #ifdef WIFI_SSID char wifi_ssid[33] = {0}; // if empty, the compile-time WIFI_SSID is used char wifi_pwd[64] = {0}; - uint8_t wifi_enabled = 1; // 0 = never bring up WiFi (credentials may still be baked in) + uint8_t wifi_enabled = 0; // off until 'set wifi.enabled 1' (credentials may still be baked in) #endif private: From 1a664ab6c6827d58d8cefde0426ac280a5c46c01 Mon Sep 17 00:00:00 2001 From: Michael Graff <mgraff@cardinalhq.io> Date: Sun, 6 Sep 2026 22:18:00 -0500 Subject: [PATCH 201/381] WiFi on/off tri-state: on when SSID set unless explicitly disabled; PicoW ships no default SSID --- examples/companion_radio/MyMesh.cpp | 13 +++++++++---- examples/companion_radio/NodePrefs.h | 7 ++++++- examples/companion_radio/main.cpp | 4 ++-- variants/rpi_picow/platformio.ini | 8 ++++---- 4 files changed, 21 insertions(+), 11 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 2886ceb6..b2c99288 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2184,17 +2184,22 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* return true; } if (strcmp(command, "get wifi.ssid") == 0) { // no 'get wifi.pwd', by design - sprintf(reply, "> %s", _prefs.wifi_ssid[0] ? _prefs.wifi_ssid : WIFI_SSID); + sprintf(reply, "> %s", _prefs.wifiSSID()[0] ? _prefs.wifiSSID() : "(not set)"); return true; } if (memcmp(command, "set wifi.enabled ", 17) == 0) { - _prefs.wifi_enabled = atoi(&command[17]) ? 1 : 0; + uint8_t en = atoi(&command[17]) ? 1 : 0; + if (en && !_prefs.wifiSSID()[0]) { + strcpy(reply, "> set wifi.ssid first"); + return true; + } + _prefs.wifi_enabled = en; savePrefs(); - sprintf(reply, "> wifi.enabled is now %d (reboot to apply)", _prefs.wifi_enabled); + sprintf(reply, "> wifi.enabled is now %d (reboot to apply)", en); return true; } if (strcmp(command, "get wifi.enabled") == 0) { - sprintf(reply, "> %d", _prefs.wifi_enabled); + sprintf(reply, "> %d", _prefs.wifiEnabled() ? 1 : 0); return true; } if (strcmp(command, "get wifi.status") == 0) { diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index 68facfbe..85cdebb2 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -47,7 +47,12 @@ public: #ifdef WIFI_SSID char wifi_ssid[33] = {0}; // if empty, the compile-time WIFI_SSID is used char wifi_pwd[64] = {0}; - uint8_t wifi_enabled = 0; // off until 'set wifi.enabled 1' (credentials may still be baked in) + uint8_t wifi_enabled = 2; // 0 = off, 1 = on, 2 = never set (treated as on) + + // effective SSID: stored prefs win over the build-time one + const char* wifiSSID() const { return wifi_ssid[0] ? wifi_ssid : WIFI_SSID; } + // WiFi runs only when there is an SSID and it hasn't been explicitly turned off + bool wifiEnabled() const { return wifiSSID()[0] && wifi_enabled != 0; } #endif private: diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index cf761095..d461a36d 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -218,8 +218,8 @@ void setup() { strcpy(wifi_ssid, the_mesh.getNodePrefs()->wifi_ssid); strcpy(wifi_pwd, the_mesh.getNodePrefs()->wifi_pwd); } - // 'set wifi.enabled 0' or a build with blank credentials leaves the radio off entirely - wifi_enabled = the_mesh.getNodePrefs()->wifi_enabled && wifi_ssid[0]; + // 'set wifi.enabled 0', or no SSID from either prefs or the build, leaves the radio off entirely + wifi_enabled = the_mesh.getNodePrefs()->wifiEnabled(); if (wifi_enabled) { #if defined(ESP32) board.setInhibitSleep(true); // prevent sleep when WiFi is active diff --git a/variants/rpi_picow/platformio.ini b/variants/rpi_picow/platformio.ini index e54d86a6..763c96bc 100644 --- a/variants/rpi_picow/platformio.ini +++ b/variants/rpi_picow/platformio.ini @@ -94,8 +94,8 @@ build_flags = ${rpi_picow.build_flags} -D BLE_PIN_CODE=123456 ; NOTE: DO NOT ENABLE --> -D BLE_DEBUG_LOGGING=1 (shares Serial with the USB interface) ; NOTE: DO NOT ENABLE --> -D WIFI_DEBUG_LOGGING=1 - -D WIFI_SSID='"myssid"' - -D WIFI_PWD='"mypwd"' + -D WIFI_SSID='""' ; no default network, configure with 'set wifi.ssid' / 'set wifi.pwd' + -D WIFI_PWD='""' ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${rpi_picow.build_src_filter} @@ -111,8 +111,8 @@ build_flags = ${rpi_picow.build_flags} -D MAX_CONTACTS=100 -D MAX_GROUP_CHANNELS=8 -D WIFI_DEBUG_LOGGING=1 - -D WIFI_SSID='"myssid"' - -D WIFI_PWD='"mypwd"' + -D WIFI_SSID='""' ; no default network, configure with 'set wifi.ssid' / 'set wifi.pwd' + -D WIFI_PWD='""' ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${rpi_picow.build_src_filter} From d0f96becb11e423e83e1446ba4426a6ce4f07e2e Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Mon, 7 Sep 2026 13:56:47 +1000 Subject: [PATCH 202/381] * CLI: removed "sub" and "unsub" (cannot support via command line) * _SUBSCRIBE: binary req/resp payload changes (now keeps supplied 'push_tag') * Sensor: added MCU temperature support in telemetry --- examples/simple_sensor/SensorMesh.cpp | 112 ++++++-------------------- src/helpers/ClientACL.h | 1 + 2 files changed, 27 insertions(+), 86 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index c3f2d9b0..8c6b06a6 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -55,8 +55,10 @@ #define REQ_TYPE_GET_TELEMETRY_DATA 0x03 #define REQ_TYPE_GET_AVG_MIN_MAX 0x04 #define REQ_TYPE_GET_ACCESS_LIST 0x05 -#define REQ_TYPE_SUBSCRIBE 0x10 -#define REQ_TYPE_UNSUBSCRIBE 0x11 +#define REQ_TYPE_GET_NEIGHBOURS 0x06 // repeater only (at present) + +#define REQ_TYPE_SUBSCRIBE 0x08 +#define REQ_TYPE_UNSUBSCRIBE 0x09 #define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ @@ -193,43 +195,6 @@ static float findTelemValue(const uint8_t* buf, uint8_t size, uint8_t channel, u return 0.0f; // not found } -static uint8_t compileLPPSpec(char* txt, uint8_t* dest, size_t max_len) { - const char* parts[3]; - int n = mesh::Utils::parseTextParts(txt, parts, 3, ','); - uint8_t len = 0; - for (int i = 0; i < n && len + 6 <= max_len; i++) { - const char* cp = strchr(parts[i], ':'); - if (cp) { - uint8_t t; - float factor = 1.0f; - cp++; // skip the ':' - char* ep = strchr(cp, 0) - 1; // find LAST char - if (*ep == 'V') { // Volts - t = LPP_VOLTAGE; - } else if (*ep == 'W') { // Watts - t = LPP_POWER; - } else if (*ep == 'C') { // Celcius - t = LPP_TEMPERATURE; - } else if (*ep == 'P') { // Pascals - t = LPP_BAROMETRIC_PRESSURE; - } else if (*ep == 'A') { // Amps - t = LPP_CURRENT; - } else if (*ep == 'm') { - t = LPP_DISTANCE; factor = 0.001f; - } else { - t = 0; - } - - if (t) { - dest[len++] = atoi(parts[i]); // channel number - dest[len++] = t; // LPP type - len += putFloat(&dest[len], atof(cp) * factor, getDataSize(t), getMultiplier(t), isSigned(t)); - } - } - } - return len; -} - /* ------------------ end Cayenne LPP helpers ----------------------*/ bool SensorMesh::telemHasChanged(const uint8_t* min_deltas, uint8_t min_deltas_len) { @@ -269,6 +234,10 @@ uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, u // query other sensors -- target specific sensors.querySensors(0xFF & perm_mask, telemetry); // allow all telemetry permissions for admin or guest // TODO: let requester know permissions they have: telemetry.addPresence(TELEM_CHANNEL_SELF, perms); + float temperature = board.getMCUTemperature(); + if (!isnan(temperature)) { // Supported boards with built-in temperature sensor. ESP32-C3 may return NAN + telemetry.addTemperature(TELEM_CHANNEL_SELF, temperature); // Built-in MCU Temperature + } uint8_t tlen = telemetry.getSize(); memcpy(&reply_data[4], telemetry.getBuffer(), tlen); @@ -322,10 +291,11 @@ uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, u return ofs; } } - if (req_type == REQ_TYPE_SUBSCRIBE && payload_len >= 4 && (perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { + if (req_type == REQ_TYPE_SUBSCRIBE && payload_len >= 8 && (perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { + memcpy(&from->extra.sensor.push_tag, &payload[0], 4); uint16_t timeout_secs; - memcpy(&timeout_secs, &payload[0], 2); - uint8_t reserved = payload[2]; + memcpy(&timeout_secs, &payload[4], 2); + uint8_t reserved = payload[6]; RegionEntry* r; if (recv_pkt_region && !recv_pkt_region->isWildcard()) { // use request scope r = recv_pkt_region; @@ -334,16 +304,17 @@ uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, u } from->extra.sensor.scope_region_id = r ? r->id : 0; from->extra.sensor.expiry_timestamp = r ? getRTCClock()->getCurrentTime() + timeout_secs : 0; - from->extra.sensor.min_deltas_len = payload[3]; + from->extra.sensor.min_deltas_len = min(sizeof(from->extra.sensor.min_deltas), (size_t)payload[7]); // NOTE: curr impl truncates LPP min_diffs spec (re-do if better impl is needed) - memcpy(from->extra.sensor.min_deltas, &payload[4], min(sizeof(from->extra.sensor.min_deltas), (size_t)payload[3])); + memcpy(from->extra.sensor.min_deltas, &payload[8], from->extra.sensor.min_deltas_len); memcpy(&reply_data[4], &from->extra.sensor.expiry_timestamp, 4); // reply with actual expiry timestamp (or 0 for error) strcpy((char *)&reply_data[8], r ? r->name : ""); // reply with name of scope that will be used - return 6 + strlen((char *)&reply_data[8]); + return 8 + strlen((char *)&reply_data[8]); } if (req_type == REQ_TYPE_UNSUBSCRIBE && (perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { from->extra.sensor.scope_region_id = 0; + from->extra.sensor.push_tag = 0; from->extra.sensor.expiry_timestamp = 0; // REVISIT: maybe return some stats, eg total number of telemetry pushes since SUBSCRIBE? reply_data[4] = 0; // success @@ -597,43 +568,6 @@ void SensorMesh::handleCommand(ClientInfo* from, uint32_t sender_timestamp, char Serial.printf("\n"); } reply[0] = 0; - } else if (from != NULL && memcmp(command, "sub", 3) == 0 && (command[3] == ' ' || command[3] == 0)) { // subscribe - uint8_t perms = from->isAdmin() ? 0xFF : from->permissions; - if ((perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { - RegionEntry* r; - if (recv_pkt_region && !recv_pkt_region->isWildcard()) { // use request scope - r = recv_pkt_region; - } else { // use default scope - r = region_map.getDefaultRegion(); - } - // defaults: - from->extra.sensor.min_deltas_len = 0; // no minimums (telemetry just needs to CHANGE) - uint16_t timeout_secs = 30*60; // expires after 30 mins - if (command[3] == ' ') { // eg. "sub 300 1:0.2V" - char* cp = &command[4]; - while (*cp >= '0' && *cp <= '9') cp++; - if (cp > &command[4]) { - timeout_secs = atoi(&command[4]); - if (*cp == ' ') { - cp++; // skip the space - from->extra.sensor.min_deltas_len = compileLPPSpec(cp, from->extra.sensor.min_deltas, sizeof(from->extra.sensor.min_deltas)); - } - } - } - from->extra.sensor.scope_region_id = r ? r->id : 0; - from->extra.sensor.expiry_timestamp = r ? getRTCClock()->getCurrentTime() + timeout_secs : 0; - if (from->extra.sensor.expiry_timestamp) { - DateTime dt = DateTime(from->extra.sensor.expiry_timestamp); - sprintf(reply, "OK - sub expires: %02d:%02d (UTC)", dt.hour(), dt.minute()); - } else { - strcpy(reply, "Err - region scope needed"); - } - } else { - strcpy(reply, "Err - no permission"); - } - } else if (from != NULL && strcmp(command, "unsub") == 0) { // unsubscribe - from->extra.sensor.scope_region_id = 0; - strcpy(reply, "OK - unsubscribed"); } else if (memcmp(command, "io ", 2) == 0) { // io {value}: write, io: read if (command[2] == ' ') { // it's a write uint32_t val; @@ -1172,6 +1106,11 @@ void SensorMesh::loop() { telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f); // query other sensors -- target specific sensors.querySensors(0xFF, telemetry); // allow all telemetry permissions + // This MCU temperature will be overridden by external sensors (if any) + float temperature = board.getMCUTemperature(); + if (!isnan(temperature)) { // Supported boards with built-in temperature sensor. ESP32-C3 may return NAN + telemetry.addTemperature(TELEM_CHANNEL_SELF, temperature); // Built-in MCU Temperature + } // compare with previous telemetry, check if any deltas are greater than subscriber minimums for (int i = 0; i < acl.getNumClients(); i++) { @@ -1184,11 +1123,12 @@ void SensorMesh::loop() { TransportKey scope; if (region_map.getTransportKeysFor(*r, &scope, 1) > 0) { uint8_t tlen = telemetry.getSize(); - uint32_t timestamp = getRTCClock()->getCurrentTimeUnique(); // this will be an unknown 'tag' to the client - memcpy(reply_data, ×tamp, 4); - memcpy(&reply_data[4], telemetry.getBuffer(), tlen); + memcpy(reply_data, &c->extra.sensor.push_tag, 4); + uint32_t timestamp = getRTCClock()->getCurrentTimeUnique(); + memcpy(&reply_data[4], ×tamp, 4); + memcpy(&reply_data[8], telemetry.getBuffer(), tlen); - mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, c->id, c->shared_secret, reply_data, 4 + tlen); + mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, c->id, c->shared_secret, reply_data, 8 + tlen); if (reply) { if (c->out_path_len != OUT_PATH_UNKNOWN) { // we have an out_path, so send DIRECT sendDirect(reply, c->out_path, c->out_path_len, 0); diff --git a/src/helpers/ClientACL.h b/src/helpers/ClientACL.h index 1e9f472d..39e71f2c 100644 --- a/src/helpers/ClientACL.h +++ b/src/helpers/ClientACL.h @@ -30,6 +30,7 @@ struct ClientInfo { } room; struct { uint32_t expiry_timestamp; // epoch seconds + uint32_t push_tag; uint16_t scope_region_id; // scope to use when sending telemetry to this client/subscriber uint8_t min_deltas_len; uint8_t min_deltas[14]; // LPP encoded From d683b178ede2b6f9138f273207e1ed312d284253 Mon Sep 17 00:00:00 2001 From: Wessel Nieboer <wessel@weebl.me> Date: Mon, 2 Mar 2026 10:11:51 +0100 Subject: [PATCH 203/381] Fix 1970 date after crash/watchdog/brownout reset on ESP32 Currently, time is only set to ~2024 when it powers on cleanly. When time is lost, this results in time dropping to 1970. Save time as backup to RTC slow memory. Should fix time staying accurate during brownouts etc. --- src/helpers/ESP32Board.h | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/src/helpers/ESP32Board.h b/src/helpers/ESP32Board.h index 75428bc6..3d1b97f4 100644 --- a/src/helpers/ESP32Board.h +++ b/src/helpers/ESP32Board.h @@ -200,19 +200,30 @@ public: } }; +static RTC_NOINIT_ATTR uint32_t _rtc_backup_time; +static RTC_NOINIT_ATTR uint32_t _rtc_backup_magic; +#define RTC_BACKUP_MAGIC 0xAA55CC33 +#define RTC_TIME_MIN 1772323200 // 1 Mar 2026 + class ESP32RTCClock : public mesh::RTCClock { public: ESP32RTCClock() { } void begin() { esp_reset_reason_t reason = esp_reset_reason(); - if (reason == ESP_RST_POWERON) { - // start with some date/time in the recent past - struct timeval tv; - tv.tv_sec = 1715770351; // 15 May 2024, 8:50pm + if (reason == ESP_RST_DEEPSLEEP) { + return; // ESP-IDF preserves system time across deep sleep + } + // All other resets (power-on, crash, WDT, brownout) lose system time. + // Restore from RTC backup if valid, otherwise use hardcoded seed. + struct timeval tv; + if (_rtc_backup_magic == RTC_BACKUP_MAGIC && _rtc_backup_time > RTC_TIME_MIN) { + tv.tv_sec = _rtc_backup_time; + } else { + tv.tv_sec = 1772323200; // 1 Mar 2026 + } tv.tv_usec = 0; settimeofday(&tv, NULL); } - } uint32_t getCurrentTime() override { time_t _now; time(&_now); @@ -223,6 +234,16 @@ public: tv.tv_sec = time; tv.tv_usec = 0; settimeofday(&tv, NULL); + _rtc_backup_time = time; + _rtc_backup_magic = RTC_BACKUP_MAGIC; + } + void tick() override { + time_t now; + time(&now); + if (now > RTC_TIME_MIN && (uint32_t)now != _rtc_backup_time) { + _rtc_backup_time = (uint32_t)now; + _rtc_backup_magic = RTC_BACKUP_MAGIC; + } } }; From db07f52349dad23e2e8cd7b1ab599efbabf4ef2a Mon Sep 17 00:00:00 2001 From: Wessel <wessel@weebl.me> Date: Fri, 5 Jun 2026 19:00:33 +0200 Subject: [PATCH 204/381] Update src/helpers/ESP32Board.h Co-authored-by: Dan McGee <dpmcgee@gmail.com> --- src/helpers/ESP32Board.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/helpers/ESP32Board.h b/src/helpers/ESP32Board.h index 3d1b97f4..3f95e692 100644 --- a/src/helpers/ESP32Board.h +++ b/src/helpers/ESP32Board.h @@ -219,7 +219,7 @@ public: if (_rtc_backup_magic == RTC_BACKUP_MAGIC && _rtc_backup_time > RTC_TIME_MIN) { tv.tv_sec = _rtc_backup_time; } else { - tv.tv_sec = 1772323200; // 1 Mar 2026 + tv.tv_sec = RTC_TIME_MIN; } tv.tv_usec = 0; settimeofday(&tv, NULL); From 170491b34c7c4829f4484e5eb32796333c63265e Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Tue, 8 Sep 2026 18:25:34 +1200 Subject: [PATCH 205/381] allow toggling wifi enabled regardless of stored ssid --- examples/companion_radio/MyMesh.cpp | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index b2c99288..9a5986f9 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2188,14 +2188,9 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* return true; } if (memcmp(command, "set wifi.enabled ", 17) == 0) { - uint8_t en = atoi(&command[17]) ? 1 : 0; - if (en && !_prefs.wifiSSID()[0]) { - strcpy(reply, "> set wifi.ssid first"); - return true; - } - _prefs.wifi_enabled = en; + _prefs.wifi_enabled = atoi(&command[17]) ? 1 : 0; savePrefs(); - sprintf(reply, "> wifi.enabled is now %d (reboot to apply)", en); + sprintf(reply, "> wifi.enabled is now %d (reboot to apply)", _prefs.wifi_enabled); return true; } if (strcmp(command, "get wifi.enabled") == 0) { From 7eb95d62b195a714a82ae6716698d8e7954efe2c Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Tue, 8 Sep 2026 18:30:00 +1200 Subject: [PATCH 206/381] simplify response message --- examples/companion_radio/MyMesh.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 9a5986f9..f745ab2b 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2180,7 +2180,7 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* _prefs.wifi_ssid[0] = 0; _prefs.wifi_pwd[0] = 0; savePrefs(); - strcpy(reply, "> wifi config cleared, using build-time credentials (reboot to apply)"); + strcpy(reply, "> wifi config cleared (reboot to apply)"); return true; } if (strcmp(command, "get wifi.ssid") == 0) { // no 'get wifi.pwd', by design From 24b2e5e03d9d383f421910a8e8caa225c8acd984 Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Tue, 8 Sep 2026 18:33:37 +1200 Subject: [PATCH 207/381] allow remote management of wifi as user has cli permission --- examples/companion_radio/MyMesh.cpp | 90 ++++++++++++++--------------- 1 file changed, 43 insertions(+), 47 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index f745ab2b..4e85e3cb 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2161,54 +2161,50 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* } #ifdef WIFI_SSID - // not accepted from the remote mesh CLI (timestamp != 0): these are credentials. The app - // over USB/BLE/WiFi and the serial console (timestamp 0) may set them. - if (sender_timestamp == 0) { - if (memcmp(command, "set wifi.ssid ", 14) == 0) { - StrHelper::strncpy(_prefs.wifi_ssid, &command[14], sizeof(_prefs.wifi_ssid)); - savePrefs(); - sprintf(reply, "> wifi.ssid is now %s (set wifi.pwd too, then reboot)", _prefs.wifi_ssid); - return true; - } - if (memcmp(command, "set wifi.pwd ", 13) == 0) { - StrHelper::strncpy(_prefs.wifi_pwd, &command[13], sizeof(_prefs.wifi_pwd)); - savePrefs(); - strcpy(reply, "> wifi.pwd updated (reboot to apply)"); - return true; - } - if (strcmp(command, "set wifi.clear") == 0) { - _prefs.wifi_ssid[0] = 0; - _prefs.wifi_pwd[0] = 0; - savePrefs(); - strcpy(reply, "> wifi config cleared (reboot to apply)"); - return true; - } - if (strcmp(command, "get wifi.ssid") == 0) { // no 'get wifi.pwd', by design - sprintf(reply, "> %s", _prefs.wifiSSID()[0] ? _prefs.wifiSSID() : "(not set)"); - return true; - } - if (memcmp(command, "set wifi.enabled ", 17) == 0) { - _prefs.wifi_enabled = atoi(&command[17]) ? 1 : 0; - savePrefs(); - sprintf(reply, "> wifi.enabled is now %d (reboot to apply)", _prefs.wifi_enabled); - return true; - } - if (strcmp(command, "get wifi.enabled") == 0) { - sprintf(reply, "> %d", _prefs.wifiEnabled() ? 1 : 0); - return true; - } - if (strcmp(command, "get wifi.status") == 0) { - strcpy(reply, WiFi.status() == WL_CONNECTED ? "> connected" : "> disconnected"); - return true; - } - if (strcmp(command, "get wifi.ip") == 0) { - if (WiFi.status() == WL_CONNECTED) { - sprintf(reply, "> %s", WiFi.localIP().toString().c_str()); - } else { - strcpy(reply, "> (not connected)"); - } - return true; + if (memcmp(command, "set wifi.ssid ", 14) == 0) { + StrHelper::strncpy(_prefs.wifi_ssid, &command[14], sizeof(_prefs.wifi_ssid)); + savePrefs(); + sprintf(reply, "> wifi.ssid is now %s (set wifi.pwd too, then reboot)", _prefs.wifi_ssid); + return true; + } + if (memcmp(command, "set wifi.pwd ", 13) == 0) { + StrHelper::strncpy(_prefs.wifi_pwd, &command[13], sizeof(_prefs.wifi_pwd)); + savePrefs(); + strcpy(reply, "> wifi.pwd updated (reboot to apply)"); + return true; + } + if (strcmp(command, "set wifi.clear") == 0) { + _prefs.wifi_ssid[0] = 0; + _prefs.wifi_pwd[0] = 0; + savePrefs(); + strcpy(reply, "> wifi config cleared (reboot to apply)"); + return true; + } + if (strcmp(command, "get wifi.ssid") == 0) { // no 'get wifi.pwd', by design + sprintf(reply, "> %s", _prefs.wifiSSID()[0] ? _prefs.wifiSSID() : "(not set)"); + return true; + } + if (memcmp(command, "set wifi.enabled ", 17) == 0) { + _prefs.wifi_enabled = atoi(&command[17]) ? 1 : 0; + savePrefs(); + sprintf(reply, "> wifi.enabled is now %d (reboot to apply)", _prefs.wifi_enabled); + return true; + } + if (strcmp(command, "get wifi.enabled") == 0) { + sprintf(reply, "> %d", _prefs.wifiEnabled() ? 1 : 0); + return true; + } + if (strcmp(command, "get wifi.status") == 0) { + strcpy(reply, WiFi.status() == WL_CONNECTED ? "> connected" : "> disconnected"); + return true; + } + if (strcmp(command, "get wifi.ip") == 0) { + if (WiFi.status() == WL_CONNECTED) { + sprintf(reply, "> %s", WiFi.localIP().toString().c_str()); + } else { + strcpy(reply, "> (not connected)"); } + return true; } #endif From a4efe91fe872b5bace51ba62b99a542e3e36c00e Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Tue, 8 Sep 2026 16:35:31 +1000 Subject: [PATCH 208/381] fix: LR2021 to use correct macro for IRQ_DETECTED in startReceive() --- src/helpers/radiolib/CustomLR2021.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/helpers/radiolib/CustomLR2021.h b/src/helpers/radiolib/CustomLR2021.h index a89ae943..0255b93c 100644 --- a/src/helpers/radiolib/CustomLR2021.h +++ b/src/helpers/radiolib/CustomLR2021.h @@ -72,7 +72,7 @@ class CustomLR2021 : public LR2021 { int16_t startReceive() override { // include the PREAMBLE_DETECTED irq bit in reported flags - return LR2021::startReceive(RADIOLIB_LR2021_RX_TIMEOUT_INF, RADIOLIB_IRQ_RX_DEFAULT_FLAGS | (1UL << RADIOLIB_LR2021_IRQ_PREAMBLE_DETECTED), RADIOLIB_IRQ_RX_DEFAULT_MASK, 0); + return LR2021::startReceive(RADIOLIB_LR2021_RX_TIMEOUT_INF, RADIOLIB_IRQ_RX_DEFAULT_FLAGS | (1UL << RADIOLIB_IRQ_PREAMBLE_DETECTED), RADIOLIB_IRQ_RX_DEFAULT_MASK, 0); } bool isReceiving() { From a3ba88575385e0cbb3b4dea03522dcc927270cfd Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Tue, 8 Sep 2026 17:55:02 +1000 Subject: [PATCH 209/381] * refactor: LPP helpers moved to LPPData class --- examples/simple_sensor/SensorMesh.cpp | 126 +++----------------- src/helpers/sensors/LPPDataHelpers.h | 159 ++++++++++++++++++-------- 2 files changed, 128 insertions(+), 157 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 8c6b06a6..de58e2b1 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -1,5 +1,6 @@ #include "SensorMesh.h" #include <helpers/RoutingPolicy.h> +#include <helpers/sensors/LPPDataHelpers.h> /* ------------------------------ Config -------------------------------- */ @@ -80,103 +81,6 @@ static File openAppend(FILESYSTEM* _fs, const char* fname) { /* --------------------- Cayenne LPP helpers ----------------------------*/ -static uint8_t getDataSize(uint8_t type) { - switch (type) { - case LPP_GPS: - return 9; - case LPP_POLYLINE: - return 8; // TODO: this is MINIMIUM - case LPP_GYROMETER: - case LPP_ACCELEROMETER: - return 6; - case LPP_GENERIC_SENSOR: - case LPP_FREQUENCY: - case LPP_DISTANCE: - case LPP_ENERGY: - case LPP_UNIXTIME: - return 4; - case LPP_COLOUR: - return 3; - case LPP_ANALOG_INPUT: - case LPP_ANALOG_OUTPUT: - case LPP_LUMINOSITY: - case LPP_TEMPERATURE: - case LPP_CONCENTRATION: - case LPP_BAROMETRIC_PRESSURE: - case LPP_RELATIVE_HUMIDITY: - case LPP_ALTITUDE: - case LPP_VOLTAGE: - case LPP_CURRENT: - case LPP_DIRECTION: - case LPP_POWER: - return 2; - } - return 1; -} - -static uint32_t getMultiplier(uint8_t type) { - switch (type) { - case LPP_CURRENT: - case LPP_DISTANCE: - case LPP_ENERGY: - return 1000; - case LPP_VOLTAGE: - case LPP_ANALOG_INPUT: - case LPP_ANALOG_OUTPUT: - return 100; - case LPP_TEMPERATURE: - case LPP_BAROMETRIC_PRESSURE: - case LPP_RELATIVE_HUMIDITY: - return 10; - } - return 1; -} - -static bool isSigned(uint8_t type) { - return type == LPP_ALTITUDE || type == LPP_TEMPERATURE || type == LPP_GYROMETER || - type == LPP_ANALOG_INPUT || type == LPP_ANALOG_OUTPUT || type == LPP_GPS || type == LPP_ACCELEROMETER; -} - -static float getFloat(const uint8_t * buffer, uint8_t size, uint32_t multiplier, bool is_signed) { - uint32_t value = 0; - for (uint8_t i = 0; i < size; i++) { - value = (value << 8) + buffer[i]; - } - - int sign = 1; - if (is_signed) { - uint32_t bit = 1ul << ((size * 8) - 1); - if ((value & bit) == bit) { - value = (bit << 1) - value; - sign = -1; - } - } - return sign * ((float) value / multiplier); -} - -static uint8_t putFloat(uint8_t * dest, float value, uint8_t size, uint32_t multiplier, bool is_signed) { - // check sign - bool sign = value < 0; - if (sign) value = -value; - - // get value to store - uint32_t v = value * multiplier; - - // format an uint32_t as if it was an int32_t - if (is_signed & sign) { - uint32_t mask = (1 << (size * 8)) - 1; - v = v & mask; - if (sign) v = mask - v + 1; - } - - // add bytes (MSB first) - for (uint8_t i=1; i<=size; i++) { - dest[size - i] = (v & 0xFF); - v >>= 8; - } - return size; -} - static float findTelemValue(const uint8_t* buf, uint8_t size, uint8_t channel, uint8_t type) { uint8_t i = 0; @@ -185,10 +89,10 @@ static float findTelemValue(const uint8_t* buf, uint8_t size, uint8_t channel, u uint8_t ch = buf[i++]; // Get data type uint8_t t = buf[i++]; - uint8_t sz = getDataSize(t); + uint8_t sz = LPPData::getDataSize(t); if (ch == channel && t == type) { - return getFloat(&buf[i], sz, getMultiplier(t), isSigned(t)); + return LPPData::getFloat(&buf[i], sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); } i += sz; // skip } @@ -209,10 +113,10 @@ bool SensorMesh::telemHasChanged(const uint8_t* min_deltas, uint8_t min_deltas_l uint8_t ch = buf[i++]; // Get data type uint8_t t = buf[i++]; - uint8_t sz = getDataSize(t); + uint8_t sz = LPPData::getDataSize(t); - float v = getFloat(&buf[i], sz, getMultiplier(t), isSigned(t)); - float pv = getFloat(&prev_telem[i], sz, getMultiplier(t), isSigned(t)); + float v = LPPData::getFloat(&buf[i], sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); + float pv = LPPData::getFloat(&prev_telem[i], sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); float min_delta = findTelemValue(min_deltas, min_deltas_len, ch, t); if (abs(v - pv) > min_delta) return true; // Yes, has changed @@ -268,12 +172,12 @@ uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, u auto d = &data[i]; reply_data[ofs++] = d->_channel; reply_data[ofs++] = d->_lpp_type; - uint8_t sz = getDataSize(d->_lpp_type); - uint32_t mult = getMultiplier(d->_lpp_type); - bool is_signed = isSigned(d->_lpp_type); - ofs += putFloat(&reply_data[ofs], d->_min, sz, mult, is_signed); - ofs += putFloat(&reply_data[ofs], d->_max, sz, mult, is_signed); - ofs += putFloat(&reply_data[ofs], d->_avg, sz, mult, is_signed); + uint8_t sz = LPPData::getDataSize(d->_lpp_type); + uint32_t mult = LPPData::getMultiplier(d->_lpp_type); + bool is_signed = LPPData::isSigned(d->_lpp_type); + ofs += LPPData::putFloat(&reply_data[ofs], d->_min, sz, mult, is_signed); + ofs += LPPData::putFloat(&reply_data[ofs], d->_max, sz, mult, is_signed); + ofs += LPPData::putFloat(&reply_data[ofs], d->_avg, sz, mult, is_signed); } return ofs; } @@ -317,9 +221,9 @@ uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, u from->extra.sensor.push_tag = 0; from->extra.sensor.expiry_timestamp = 0; // REVISIT: maybe return some stats, eg total number of telemetry pushes since SUBSCRIBE? - reply_data[4] = 0; // success - getRNG()->random(&reply_data[5], 3); // just some entropy for better packet-hash uniqueness - return 8; + memset(&reply_data[4], 0, 8); // success + getRNG()->random(&reply_data[12], 2); // just some entropy for better packet-hash uniqueness + return 12 + 2; } return 0; // unknown command } diff --git a/src/helpers/sensors/LPPDataHelpers.h b/src/helpers/sensors/LPPDataHelpers.h index 70a036c4..db49cade 100644 --- a/src/helpers/sensors/LPPDataHelpers.h +++ b/src/helpers/sensors/LPPDataHelpers.h @@ -63,12 +63,66 @@ #define LPP_ERROR_OVERFLOW 1 #define LPP_ERROR_UNKOWN_TYPE 2 -class LPPReader { - const uint8_t* _buf; - uint8_t _len; - uint8_t _pos; +class LPPData { +public: + static uint8_t getDataSize(uint8_t type) { + switch (type) { + case LPP_GPS: + return 9; + case LPP_POLYLINE: + return 8; // TODO: this is MINIMIUM + case LPP_GYROMETER: + case LPP_ACCELEROMETER: + return 6; + case LPP_GENERIC_SENSOR: + case LPP_FREQUENCY: + case LPP_DISTANCE: + case LPP_ENERGY: + case LPP_UNIXTIME: + return 4; + case LPP_COLOUR: + return 3; + case LPP_ANALOG_INPUT: + case LPP_ANALOG_OUTPUT: + case LPP_LUMINOSITY: + case LPP_TEMPERATURE: + case LPP_CONCENTRATION: + case LPP_BAROMETRIC_PRESSURE: + case LPP_RELATIVE_HUMIDITY: + case LPP_ALTITUDE: + case LPP_VOLTAGE: + case LPP_CURRENT: + case LPP_DIRECTION: + case LPP_POWER: + return 2; + } + return 1; + } - float getFloat(const uint8_t * buffer, uint8_t size, uint32_t multiplier, bool is_signed) { + static uint32_t getMultiplier(uint8_t type) { + switch (type) { + case LPP_CURRENT: + case LPP_DISTANCE: + case LPP_ENERGY: + return 1000; + case LPP_VOLTAGE: + case LPP_ANALOG_INPUT: + case LPP_ANALOG_OUTPUT: + return 100; + case LPP_TEMPERATURE: + case LPP_BAROMETRIC_PRESSURE: + case LPP_RELATIVE_HUMIDITY: + return 10; + } + return 1; + } + + static bool isSigned(uint8_t type) { + return type == LPP_ALTITUDE || type == LPP_TEMPERATURE || type == LPP_GYROMETER || + type == LPP_ANALOG_INPUT || type == LPP_ANALOG_OUTPUT || type == LPP_GPS || type == LPP_ACCELEROMETER; + } + + static float getFloat(const uint8_t * buffer, uint8_t size, uint32_t multiplier, bool is_signed) { uint32_t value = 0; for (uint8_t i = 0; i < size; i++) { value = (value << 8) + buffer[i]; @@ -85,6 +139,36 @@ class LPPReader { return sign * ((float) value / multiplier); } + static uint8_t putFloat(uint8_t * dest, float value, uint8_t size, uint32_t multiplier, bool is_signed) { + // check sign + bool sign = value < 0; + if (sign) value = -value; + + // get value to store + uint32_t v = value * multiplier; + + // format an uint32_t as if it was an int32_t + if (is_signed & sign) { + uint32_t mask = (1 << (size * 8)) - 1; + v = v & mask; + if (sign) v = mask - v + 1; + } + + // add bytes (MSB first) + for (uint8_t i=1; i<=size; i++) { + dest[size - i] = (v & 0xFF); + v >>= 8; + } + return size; + } + +}; + +class LPPReader { + const uint8_t* _buf; + uint8_t _len; + uint8_t _pos; + public: LPPReader(const uint8_t buf[], uint8_t len) : _buf(buf), _len(len), _pos(0) { } @@ -103,72 +187,42 @@ public: } bool readGPS(float& lat, float& lon, float& alt) { - lat = getFloat(&_buf[_pos], 3, 10000, true); _pos += 3; - lon = getFloat(&_buf[_pos], 3, 10000, true); _pos += 3; - alt = getFloat(&_buf[_pos], 3, 100, true); _pos += 3; + lat = LPPData::getFloat(&_buf[_pos], 3, 10000, true); _pos += 3; + lon = LPPData::getFloat(&_buf[_pos], 3, 10000, true); _pos += 3; + alt = LPPData::getFloat(&_buf[_pos], 3, 100, true); _pos += 3; return _pos <= _len; } bool readVoltage(float& voltage) { - voltage = getFloat(&_buf[_pos], 2, 100, false); _pos += 2; + voltage = LPPData::getFloat(&_buf[_pos], 2, 100, false); _pos += 2; return _pos <= _len; } bool readCurrent(float& amps) { - amps = getFloat(&_buf[_pos], 2, 1000, true); _pos += 2; + amps = LPPData::getFloat(&_buf[_pos], 2, 1000, true); _pos += 2; return _pos <= _len; } bool readPower(float& watts) { - watts = getFloat(&_buf[_pos], 2, 1, false); _pos += 2; + watts = LPPData::getFloat(&_buf[_pos], 2, 1, false); _pos += 2; return _pos <= _len; } bool readTemperature(float& degrees_c) { - degrees_c = getFloat(&_buf[_pos], 2, 10, true); _pos += 2; + degrees_c = LPPData::getFloat(&_buf[_pos], 2, 10, true); _pos += 2; return _pos <= _len; } bool readPressure(float& pa) { - pa = getFloat(&_buf[_pos], 2, 10, false); _pos += 2; + pa = LPPData::getFloat(&_buf[_pos], 2, 10, false); _pos += 2; return _pos <= _len; } bool readRelativeHumidity(float& pct) { - pct = getFloat(&_buf[_pos], 1, 2, false); _pos += 1; + pct = LPPData::getFloat(&_buf[_pos], 1, 2, false); _pos += 1; return _pos <= _len; } bool readAltitude(float& m) { - m = getFloat(&_buf[_pos], 2, 1, true); _pos += 2; + m = LPPData::getFloat(&_buf[_pos], 2, 1, true); _pos += 2; return _pos <= _len; } void skipData(uint8_t type) { - switch (type) { - case LPP_GPS: - _pos += 9; break; - case LPP_POLYLINE: - _pos += 8; break; // TODO: this is MINIMUM - case LPP_GYROMETER: - case LPP_ACCELEROMETER: - _pos += 6; break; - case LPP_GENERIC_SENSOR: - case LPP_FREQUENCY: - case LPP_DISTANCE: - case LPP_ENERGY: - case LPP_UNIXTIME: - _pos += 4; break; - case LPP_COLOUR: - _pos += 3; break; - case LPP_ANALOG_INPUT: - case LPP_ANALOG_OUTPUT: - case LPP_LUMINOSITY: - case LPP_TEMPERATURE: - case LPP_CONCENTRATION: - case LPP_BAROMETRIC_PRESSURE: - case LPP_ALTITUDE: - case LPP_VOLTAGE: - case LPP_CURRENT: - case LPP_DIRECTION: - case LPP_POWER: - _pos += 2; break; - default: - _pos++; - } + _pos += LPPData::getDataSize(type); } }; @@ -185,6 +239,19 @@ class LPPWriter { public: LPPWriter(uint8_t buf[], uint8_t max_len): _buf(buf), _max_len(max_len), _len(0) { } + bool writeData(uint8_t channel, uint8_t type, float v) { + uint8_t sz = LPPData::getDataSize(type); + bool s = LPPData::isSigned(type); + uint32_t mul = LPPData::getMultiplier(type); + if (_len + 2 + sz <= _max_len) { + _buf[_len++] = channel; + _buf[_len++] = type; + _len += LPPData::putFloat(&_buf[_len], v, sz, mul, s); + return true; + } + return false; + } + bool writeVoltage(uint8_t channel, float voltage) { if (_len + 4 <= _max_len) { _buf[_len++] = channel; From 5be7b3c4ba0fb1ac27b4edf8ba417351b2ecc154 Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Tue, 8 Sep 2026 21:30:17 +1200 Subject: [PATCH 210/381] simplify and remove 2 as a wifi enabled state --- examples/companion_radio/MyMesh.cpp | 4 ++-- examples/companion_radio/NodePrefs.h | 9 +++------ examples/companion_radio/main.cpp | 6 +++--- 3 files changed, 8 insertions(+), 11 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 4e85e3cb..7a380e98 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2181,7 +2181,7 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* return true; } if (strcmp(command, "get wifi.ssid") == 0) { // no 'get wifi.pwd', by design - sprintf(reply, "> %s", _prefs.wifiSSID()[0] ? _prefs.wifiSSID() : "(not set)"); + sprintf(reply, "> %s", _prefs.getWifiSSID()[0] ? _prefs.getWifiSSID() : "(not set)"); return true; } if (memcmp(command, "set wifi.enabled ", 17) == 0) { @@ -2191,7 +2191,7 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* return true; } if (strcmp(command, "get wifi.enabled") == 0) { - sprintf(reply, "> %d", _prefs.wifiEnabled() ? 1 : 0); + sprintf(reply, "> %d", _prefs.wifi_enabled); return true; } if (strcmp(command, "get wifi.status") == 0) { diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index 85cdebb2..ed408f9a 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -47,12 +47,9 @@ public: #ifdef WIFI_SSID char wifi_ssid[33] = {0}; // if empty, the compile-time WIFI_SSID is used char wifi_pwd[64] = {0}; - uint8_t wifi_enabled = 2; // 0 = off, 1 = on, 2 = never set (treated as on) - - // effective SSID: stored prefs win over the build-time one - const char* wifiSSID() const { return wifi_ssid[0] ? wifi_ssid : WIFI_SSID; } - // WiFi runs only when there is an SSID and it hasn't been explicitly turned off - bool wifiEnabled() const { return wifiSSID()[0] && wifi_enabled != 0; } + uint8_t wifi_enabled = 1; // enabled by default to allow wifi only builds to work. wifi won't be started if ssid is empty + // use ssid from prefs, or fallback to ssid from build flags + const char* getWifiSSID() const { return wifi_ssid[0] ? wifi_ssid : WIFI_SSID; } #endif private: diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index d461a36d..bfcd2682 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -218,9 +218,9 @@ void setup() { strcpy(wifi_ssid, the_mesh.getNodePrefs()->wifi_ssid); strcpy(wifi_pwd, the_mesh.getNodePrefs()->wifi_pwd); } - // 'set wifi.enabled 0', or no SSID from either prefs or the build, leaves the radio off entirely - wifi_enabled = the_mesh.getNodePrefs()->wifiEnabled(); - if (wifi_enabled) { + // only start wifi if enabled and ssid is not empty + wifi_enabled = the_mesh.getNodePrefs()->wifi_enabled; + if (wifi_enabled && wifi_ssid[0]) { #if defined(ESP32) board.setInhibitSleep(true); // prevent sleep when WiFi is active WiFi.setAutoReconnect(true); From 85ad99599d639460e22744d5a9c55a196164d7b0 Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Tue, 8 Sep 2026 22:18:22 +1200 Subject: [PATCH 211/381] tidy comments --- examples/companion_radio/main.cpp | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index bfcd2682..d886b804 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -209,11 +209,7 @@ void setup() { // add wifi interface #ifdef WIFI_SSID - // stored credentials win over the build-time ones ('set wifi.ssid <x>' over USB serial). - // they are taken as a pair, so 'set wifi.ssid' alone gives an empty password, not a - // silent fallback to the build-time password of a different network. Copied out of prefs - // so 'set wifi.*' edits only take effect on reboot, as their replies promise. - // (No NULL-for-open-network: the RP2040 core does strlen() on the password unguarded.) + // use wifi ssid and password from prefs if ssid is not empty, otherwise use the build flag defaults if (the_mesh.getNodePrefs()->wifi_ssid[0]) { strcpy(wifi_ssid, the_mesh.getNodePrefs()->wifi_ssid); strcpy(wifi_pwd, the_mesh.getNodePrefs()->wifi_pwd); @@ -239,10 +235,9 @@ void setup() { WIFI_DEBUG_PRINTLN("connecting to %s", wifi_ssid); #if defined(RP2040_PLATFORM) - // ponytail: the join itself blocks inside the core (CYW43::begin busy-waits for the + // the join itself blocks inside the core (CYW43::begin busy-waits for the // association), so every attempt stalls the mesh loop. beginNoBlock() only skips the // extra DHCP wait. Give the first connect a full window, then bound the retries below. - // Upgrade path if the stall ever matters: run WiFi on core1. WiFi.beginNoBlock(wifi_ssid, wifi_pwd); last_wifi_reconnect_attempt = millis(); // let DHCP finish before the poll can retry #else From bc333d89fa4a57321482a31318b5921c54bae0fc Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Tue, 8 Sep 2026 22:54:50 +1200 Subject: [PATCH 212/381] add new ENABLE_WIFI_INTERFACE build flag for companions without providing ssid and pwd --- examples/companion_radio/MyMesh.cpp | 6 +++--- examples/companion_radio/NodePrefs.h | 11 +++++++---- examples/companion_radio/main.cpp | 14 ++++++++++---- examples/companion_radio/ui-new/UITask.cpp | 4 ++-- examples/companion_radio/ui-tiny/UITask.cpp | 4 ++-- variants/heltec_rc32/platformio.ini | 2 ++ variants/heltec_tracker_v2/platformio.ini | 1 + variants/heltec_v2/platformio.ini | 1 + variants/heltec_v3/platformio.ini | 2 ++ variants/heltec_v4/platformio.ini | 2 ++ variants/heltec_v4_r8/platformio.ini | 2 ++ variants/lilygo_tbeam_1w/platformio.ini | 1 + .../lilygo_tbeam_supreme_SX1262/platformio.ini | 1 + variants/lilygo_tlora_v2_1/platformio.ini | 1 + variants/meshnology_w12/platformio.ini | 1 + variants/nibble_screen_connect/platformio.ini | 1 + variants/nibble_zero_connect/platformio.ini | 1 + variants/rak3112/platformio.ini | 1 + variants/rpi_picow/platformio.ini | 4 ++-- variants/station_g2/platformio.ini | 1 + variants/station_g3_esp32/platformio.ini | 1 + variants/thinknode_m2/platformio.ini | 1 + variants/thinknode_m5/platformio.ini | 1 + variants/thinknode_m7/platformio.ini | 1 + variants/thinknode_m9/platformio.ini | 1 + variants/xiao_c3/platformio.ini | 1 + variants/xiao_s3_wio/platformio.ini | 1 + 27 files changed, 51 insertions(+), 17 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 7a380e98..2d7d1491 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -1,7 +1,7 @@ #include "MyMesh.h" #include <Arduino.h> // needed for PlatformIO -#ifdef WIFI_SSID +#ifdef ENABLE_WIFI_INTERFACE #include <WiFi.h> #endif #include <Mesh.h> @@ -2160,7 +2160,7 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* return true; } -#ifdef WIFI_SSID +#ifdef ENABLE_WIFI_INTERFACE if (memcmp(command, "set wifi.ssid ", 14) == 0) { StrHelper::strncpy(_prefs.wifi_ssid, &command[14], sizeof(_prefs.wifi_ssid)); savePrefs(); @@ -2438,7 +2438,7 @@ void MyMesh::loop() { checkCLIRescueCmd(); } else { checkSerialInterface(); -#if defined(WIFI_SSID) && defined(RP2040_PLATFORM) && !defined(ENABLE_USB_INTERFACE) +#if defined(ENABLE_WIFI_INTERFACE) && defined(RP2040_PLATFORM) && !defined(ENABLE_USB_INTERFACE) // RP2040 WiFi builds are headless and have no way into the rescue CLI (that needs a // display + long-press), so serve config commands on the otherwise unused USB serial checkCLIRescueCmd(); diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index ed408f9a..cf1914d0 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -44,7 +44,10 @@ public: char default_scope_name[31]; uint8_t default_scope_key[16]; int8_t tz_offset = 0; -#ifdef WIFI_SSID +#ifdef ENABLE_WIFI_INTERFACE + #ifndef WIFI_SSID + #define WIFI_SSID "" + #endif char wifi_ssid[33] = {0}; // if empty, the compile-time WIFI_SSID is used char wifi_pwd[64] = {0}; uint8_t wifi_enabled = 1; // enabled by default to allow wifi only builds to work. wifi won't be started if ssid is empty @@ -167,7 +170,7 @@ private: DynamicConfigSerializer custom; -#ifdef WIFI_SSID +#ifdef ENABLE_WIFI_INTERFACE class WiFiPrefs : public ConfigSerializer { NodePrefs* _parent; protected: @@ -194,13 +197,13 @@ protected: def("repeat", repeat); def("comp", companion); def("custom", custom); -#ifdef WIFI_SSID +#ifdef ENABLE_WIFI_INTERFACE def("wifi", wifi); #endif } public: NodePrefs() : radio(this), gps(this), companion(this), custom(&radio) -#ifdef WIFI_SSID +#ifdef ENABLE_WIFI_INTERFACE , wifi(this) #endif { diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index d886b804..6dc9acdc 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -36,7 +36,13 @@ MultiSerialInterface interface_manager; #endif // include wifi interface -#ifdef WIFI_SSID +#ifdef ENABLE_WIFI_INTERFACE + #ifndef WIFI_SSID + #define WIFI_SSID "" + #endif + #ifndef WIFI_PWD + #define WIFI_PWD "" + #endif #ifndef TCP_PORT #define TCP_PORT 5000 #endif @@ -121,7 +127,7 @@ void halt() { } /* WIFI RECONNECT TRACKERS */ -#ifdef WIFI_SSID +#ifdef ENABLE_WIFI_INTERFACE bool wifi_needs_reconnect = false; unsigned long last_wifi_reconnect_attempt = 0; char wifi_ssid[33] = WIFI_SSID; // replaced by stored prefs at boot, if set @@ -208,7 +214,7 @@ void setup() { #endif // add wifi interface -#ifdef WIFI_SSID +#ifdef ENABLE_WIFI_INTERFACE // use wifi ssid and password from prefs if ssid is not empty, otherwise use the build flag defaults if (the_mesh.getNodePrefs()->wifi_ssid[0]) { strcpy(wifi_ssid, the_mesh.getNodePrefs()->wifi_ssid); @@ -302,7 +308,7 @@ void loop() { #endif } -#ifdef WIFI_SSID +#ifdef ENABLE_WIFI_INTERFACE if (wifi_enabled) { // RP2040 has no WiFi event callbacks, so poll the link state instead #if defined(RP2040_PLATFORM) diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index 2c79ab91..53ae480c 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -3,7 +3,7 @@ #include "../MyMesh.h" #include "target.h" #include <time.h> -#ifdef WIFI_SSID +#ifdef ENABLE_WIFI_INTERFACE #include <WiFi.h> #endif @@ -260,7 +260,7 @@ public: sprintf(tmp, "%02d/%02d/%d", dt.day(), dt.month(), dt.year()); display.drawTextCentered(display.width() / 2, 80, tmp); #endif - #ifdef WIFI_SSID + #ifdef ENABLE_WIFI_INTERFACE IPAddress ip = WiFi.localIP(); snprintf(tmp, sizeof(tmp), "IP: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); display.setTextSize(1); diff --git a/examples/companion_radio/ui-tiny/UITask.cpp b/examples/companion_radio/ui-tiny/UITask.cpp index b6bdbcf4..9ecd66f1 100644 --- a/examples/companion_radio/ui-tiny/UITask.cpp +++ b/examples/companion_radio/ui-tiny/UITask.cpp @@ -4,7 +4,7 @@ #include "target.h" #include "u8g2_icons.h" -#ifdef WIFI_SSID +#ifdef ENABLE_WIFI_INTERFACE #include <WiFi.h> #endif @@ -173,7 +173,7 @@ public: display.setCursor(0, 19); display.print(tmp); - #ifdef WIFI_SSID + #ifdef ENABLE_WIFI_INTERFACE IPAddress ip = WiFi.localIP(); snprintf(tmp, sizeof(tmp), "IP: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); display.setTextSize(1); diff --git a/variants/heltec_rc32/platformio.ini b/variants/heltec_rc32/platformio.ini index df986cf0..2f07c021 100644 --- a/variants/heltec_rc32/platformio.ini +++ b/variants/heltec_rc32/platformio.ini @@ -173,6 +173,7 @@ extends = Heltec_RC32 build_flags = ${Heltec_RC32.build_flags} -I examples/companion_radio/ui-new + -D ENABLE_WIFI_INTERFACE -D DISPLAY_CLASS=NullDisplayDriver -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 @@ -315,6 +316,7 @@ extends = Heltec_RC32_with_display build_flags = ${Heltec_RC32_with_display.build_flags} -I examples/companion_radio/ui-new + -D ENABLE_WIFI_INTERFACE -D UI_HAS_ROTARY_INPUT -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 diff --git a/variants/heltec_tracker_v2/platformio.ini b/variants/heltec_tracker_v2/platformio.ini index 178508d8..5fd9edab 100644 --- a/variants/heltec_tracker_v2/platformio.ini +++ b/variants/heltec_tracker_v2/platformio.ini @@ -182,6 +182,7 @@ extends = Heltec_tracker_v2 build_flags = ${Heltec_tracker_v2.build_flags} -I examples/companion_radio/ui-new + -D ENABLE_WIFI_INTERFACE -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D DISPLAY_CLASS=ST7735Display diff --git a/variants/heltec_v2/platformio.ini b/variants/heltec_v2/platformio.ini index 28e80554..6435936e 100644 --- a/variants/heltec_v2/platformio.ini +++ b/variants/heltec_v2/platformio.ini @@ -178,6 +178,7 @@ extends = Heltec_lora32_v2 build_flags = ${Heltec_lora32_v2.build_flags} -I examples/companion_radio/ui-new + -D ENABLE_WIFI_INTERFACE -D DISPLAY_CLASS=SSD1306Display -D MAX_CONTACTS=160 -D MAX_GROUP_CHANNELS=8 diff --git a/variants/heltec_v3/platformio.ini b/variants/heltec_v3/platformio.ini index 27541a8a..a2b159ec 100644 --- a/variants/heltec_v3/platformio.ini +++ b/variants/heltec_v3/platformio.ini @@ -185,6 +185,7 @@ extends = Heltec_lora32_v3 build_flags = ${Heltec_lora32_v3.build_flags} -I examples/companion_radio/ui-new + -D ENABLE_WIFI_INTERFACE -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D DISPLAY_CLASS=SSD1306Display @@ -341,6 +342,7 @@ lib_deps = extends = Heltec_lora32_v3 build_flags = ${Heltec_lora32_v3.build_flags} + -D ENABLE_WIFI_INTERFACE -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D WIFI_DEBUG_LOGGING=1 diff --git a/variants/heltec_v4/platformio.ini b/variants/heltec_v4/platformio.ini index 25f9ee3b..96b3eec0 100644 --- a/variants/heltec_v4/platformio.ini +++ b/variants/heltec_v4/platformio.ini @@ -228,6 +228,7 @@ extends = heltec_v4_oled build_flags = ${heltec_v4_oled.build_flags} -I examples/companion_radio/ui-new + -D ENABLE_WIFI_INTERFACE -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 @@ -394,6 +395,7 @@ extends = heltec_v4_tft build_flags = ${heltec_v4_tft.build_flags} -I examples/companion_radio/ui-new + -D ENABLE_WIFI_INTERFACE -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 diff --git a/variants/heltec_v4_r8/platformio.ini b/variants/heltec_v4_r8/platformio.ini index 8c2feb94..7611cc1c 100644 --- a/variants/heltec_v4_r8/platformio.ini +++ b/variants/heltec_v4_r8/platformio.ini @@ -175,6 +175,7 @@ extends = heltec_v4_r8_oled build_flags = ${heltec_v4_r8_oled.build_flags} -I examples/companion_radio/ui-new + -D ENABLE_WIFI_INTERFACE -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 @@ -301,6 +302,7 @@ extends = heltec_v4_r8_tft build_flags = ${heltec_v4_r8_tft.build_flags} -I examples/companion_radio/ui-new + -D ENABLE_WIFI_INTERFACE -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 diff --git a/variants/lilygo_tbeam_1w/platformio.ini b/variants/lilygo_tbeam_1w/platformio.ini index 16db0257..ab9c9e67 100644 --- a/variants/lilygo_tbeam_1w/platformio.ini +++ b/variants/lilygo_tbeam_1w/platformio.ini @@ -153,6 +153,7 @@ extends = LilyGo_TBeam_1W build_flags = ${LilyGo_TBeam_1W.build_flags} -I examples/companion_radio/ui-new + -D ENABLE_WIFI_INTERFACE -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 diff --git a/variants/lilygo_tbeam_supreme_SX1262/platformio.ini b/variants/lilygo_tbeam_supreme_SX1262/platformio.ini index a9991f25..af4a8eaf 100644 --- a/variants/lilygo_tbeam_supreme_SX1262/platformio.ini +++ b/variants/lilygo_tbeam_supreme_SX1262/platformio.ini @@ -148,6 +148,7 @@ extends = T_Beam_S3_Supreme_SX1262 build_flags = ${T_Beam_S3_Supreme_SX1262.build_flags} -I examples/companion_radio/ui-new + -D ENABLE_WIFI_INTERFACE -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 diff --git a/variants/lilygo_tlora_v2_1/platformio.ini b/variants/lilygo_tlora_v2_1/platformio.ini index cf24a5d5..dc60b6f7 100644 --- a/variants/lilygo_tlora_v2_1/platformio.ini +++ b/variants/lilygo_tlora_v2_1/platformio.ini @@ -132,6 +132,7 @@ extends = LilyGo_TLora_V2_1_1_6 build_flags = ${LilyGo_TLora_V2_1_1_6.build_flags} -I examples/companion_radio/ui-new + -D ENABLE_WIFI_INTERFACE -D MAX_CONTACTS=160 -D MAX_GROUP_CHANNELS=8 -D WIFI_SSID='"ssid"' diff --git a/variants/meshnology_w12/platformio.ini b/variants/meshnology_w12/platformio.ini index c0e8c80d..ffab9d57 100644 --- a/variants/meshnology_w12/platformio.ini +++ b/variants/meshnology_w12/platformio.ini @@ -171,6 +171,7 @@ extends = meshnology_w12 build_flags = ${meshnology_w12.build_flags} -I examples/companion_radio/ui-new + -D ENABLE_WIFI_INTERFACE -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 diff --git a/variants/nibble_screen_connect/platformio.ini b/variants/nibble_screen_connect/platformio.ini index 3c5049e0..0f8d31de 100644 --- a/variants/nibble_screen_connect/platformio.ini +++ b/variants/nibble_screen_connect/platformio.ini @@ -143,6 +143,7 @@ extends = nibble_screen_connect_base build_flags = ${nibble_screen_connect_base.build_flags} -I examples/companion_radio/ui-new + -D ENABLE_WIFI_INTERFACE -D DISPLAY_CLASS=SSD1306Display -D MAX_CONTACTS=300 -D MAX_GROUP_CHANNELS=8 diff --git a/variants/nibble_zero_connect/platformio.ini b/variants/nibble_zero_connect/platformio.ini index 9789eabf..c7e7b076 100644 --- a/variants/nibble_zero_connect/platformio.ini +++ b/variants/nibble_zero_connect/platformio.ini @@ -140,6 +140,7 @@ extends = nibble_zero_connect_base build_flags = ${nibble_zero_connect_base.build_flags} -I examples/companion_radio/ui-new + -D ENABLE_WIFI_INTERFACE -D DISPLAY_CLASS=SSD1306Display -D MAX_CONTACTS=300 -D MAX_GROUP_CHANNELS=8 diff --git a/variants/rak3112/platformio.ini b/variants/rak3112/platformio.ini index 2fee8c26..5f3b905b 100644 --- a/variants/rak3112/platformio.ini +++ b/variants/rak3112/platformio.ini @@ -172,6 +172,7 @@ extends = rak3112 build_flags = ${rak3112.build_flags} -I examples/companion_radio/ui-orig + -D ENABLE_WIFI_INTERFACE -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D WIFI_DEBUG_LOGGING=1 diff --git a/variants/rpi_picow/platformio.ini b/variants/rpi_picow/platformio.ini index 763c96bc..9814f397 100644 --- a/variants/rpi_picow/platformio.ini +++ b/variants/rpi_picow/platformio.ini @@ -90,12 +90,11 @@ build_flags = ${rpi_picow.build_flags} -D MAX_CONTACTS=100 -D MAX_GROUP_CHANNELS=8 -D ENABLE_USB_INTERFACE + -D ENABLE_WIFI_INTERFACE -D PIO_FRAMEWORK_ARDUINO_ENABLE_BLUETOOTH -D BLE_PIN_CODE=123456 ; NOTE: DO NOT ENABLE --> -D BLE_DEBUG_LOGGING=1 (shares Serial with the USB interface) ; NOTE: DO NOT ENABLE --> -D WIFI_DEBUG_LOGGING=1 - -D WIFI_SSID='""' ; no default network, configure with 'set wifi.ssid' / 'set wifi.pwd' - -D WIFI_PWD='""' ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${rpi_picow.build_src_filter} @@ -108,6 +107,7 @@ lib_deps = ${rpi_picow.lib_deps} [env:PicoW_companion_radio_wifi] extends = rpi_picow build_flags = ${rpi_picow.build_flags} + -D ENABLE_WIFI_INTERFACE -D MAX_CONTACTS=100 -D MAX_GROUP_CHANNELS=8 -D WIFI_DEBUG_LOGGING=1 diff --git a/variants/station_g2/platformio.ini b/variants/station_g2/platformio.ini index d8bdd5e8..c1ae765f 100644 --- a/variants/station_g2/platformio.ini +++ b/variants/station_g2/platformio.ini @@ -224,6 +224,7 @@ extends = Station_G2 build_flags = ${Station_G2.build_flags} -I examples/companion_radio/ui-new + -D ENABLE_WIFI_INTERFACE -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D WIFI_DEBUG_LOGGING=1 diff --git a/variants/station_g3_esp32/platformio.ini b/variants/station_g3_esp32/platformio.ini index 477c135b..7006d939 100644 --- a/variants/station_g3_esp32/platformio.ini +++ b/variants/station_g3_esp32/platformio.ini @@ -139,6 +139,7 @@ extends = Station_G3_ESP32 build_flags = ${Station_G3_ESP32.build_flags} -I examples/companion_radio/ui-new + -D ENABLE_WIFI_INTERFACE -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D WIFI_DEBUG_LOGGING=1 diff --git a/variants/thinknode_m2/platformio.ini b/variants/thinknode_m2/platformio.ini index c1f5612a..862c7154 100644 --- a/variants/thinknode_m2/platformio.ini +++ b/variants/thinknode_m2/platformio.ini @@ -176,6 +176,7 @@ extends = ThinkNode_M2 build_flags = ${ThinkNode_M2.build_flags} -I examples/companion_radio/ui-new + -D ENABLE_WIFI_INTERFACE -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 diff --git a/variants/thinknode_m5/platformio.ini b/variants/thinknode_m5/platformio.ini index f64e4e77..a3f348b3 100644 --- a/variants/thinknode_m5/platformio.ini +++ b/variants/thinknode_m5/platformio.ini @@ -190,6 +190,7 @@ extends = ThinkNode_M5 build_flags = ${ThinkNode_M5.build_flags} -I examples/companion_radio/ui-new + -D ENABLE_WIFI_INTERFACE -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 diff --git a/variants/thinknode_m7/platformio.ini b/variants/thinknode_m7/platformio.ini index 508fc813..5606d482 100644 --- a/variants/thinknode_m7/platformio.ini +++ b/variants/thinknode_m7/platformio.ini @@ -135,6 +135,7 @@ extends = ThinkNode_M7 build_flags = ${ThinkNode_M7.build_flags} -I examples/companion_radio/ui-orig + -D ENABLE_WIFI_INTERFACE -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D DISPLAY_CLASS=NullDisplayDriver diff --git a/variants/thinknode_m9/platformio.ini b/variants/thinknode_m9/platformio.ini index 085ab7d5..d4983491 100755 --- a/variants/thinknode_m9/platformio.ini +++ b/variants/thinknode_m9/platformio.ini @@ -137,6 +137,7 @@ extends = ThinkNode_M9 build_flags = ${ThinkNode_M9.build_flags} -I examples/companion_radio/ui-new + -D ENABLE_WIFI_INTERFACE -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D WIFI_DEBUG_LOGGING=1 diff --git a/variants/xiao_c3/platformio.ini b/variants/xiao_c3/platformio.ini index cca2907a..62e6fd21 100644 --- a/variants/xiao_c3/platformio.ini +++ b/variants/xiao_c3/platformio.ini @@ -118,6 +118,7 @@ build_src_filter = ${Xiao_esp32_C3.build_src_filter} +<helpers/wifi/*.cpp> build_flags = ${Xiao_esp32_C3.build_flags} + -D ENABLE_WIFI_INTERFACE -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 diff --git a/variants/xiao_s3_wio/platformio.ini b/variants/xiao_s3_wio/platformio.ini index de656c44..3bb95607 100644 --- a/variants/xiao_s3_wio/platformio.ini +++ b/variants/xiao_s3_wio/platformio.ini @@ -208,6 +208,7 @@ build_src_filter = ${Xiao_S3_WIO.build_src_filter} build_flags = ${Xiao_S3_WIO.build_flags} -I examples/companion_radio/ui-new + -D ENABLE_WIFI_INTERFACE -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 From 8adad96e8640ea111a05389a94e575e5b731156f Mon Sep 17 00:00:00 2001 From: Yoshi Walsh <yoshi@yoshiwalsh.me> Date: Wed, 9 Sep 2026 17:42:35 +1000 Subject: [PATCH 213/381] Fix Git error during project configuration Previously project configuration would fail with "fatal: couldn't find remote ref d541301" (git v2.55.0) Per https://git-scm.com/docs/git-fetch#Documentation/git-fetch.txt-refspec, the <src> needs to be either a ref or a "**fully spelled** hex object name" This requirement is also mentioned in this SO answer: https://stackoverflow.com/a/30701724 After this change, project configuration now succeeds. 219812 --- platformio.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platformio.ini b/platformio.ini index 2219c978..de4d6c29 100644 --- a/platformio.ini +++ b/platformio.ini @@ -85,7 +85,7 @@ platform_packages = ; use internal fork that includes patch to ble stack to prevent firmware lockup during rapid connect/disconnect ; https://github.com/meshcore-dev/MeshCore/pull/1177 ; https://github.com/meshcore-dev/MeshCore/pull/1295 - framework-arduinoadafruitnrf52 @ https://github.com/meshcore-dev/Adafruit_nRF52_Arduino#d541301 + framework-arduinoadafruitnrf52 @ https://github.com/meshcore-dev/Adafruit_nRF52_Arduino#d541301665b40959682252911e57b11df3ee651a platformio/toolchain-gccarmnoneeabi@^1.140201.0 extra_scripts = create-uf2.py build_flags = ${arduino_base.build_flags} From d5b4315672b6db4dd512d660f95045dbd4cce101 Mon Sep 17 00:00:00 2001 From: tekk <tekk.sk@gmail.com> Date: Wed, 9 Sep 2026 22:10:41 +0200 Subject: [PATCH 214/381] fix(companion): gate CMD_SEND_CHANNEL_DATA payload on MAX_GROUP_DATA_LENGTH Payloads of 166 or 167 bytes previously passed the frame-sized bound (MAX_CHANNEL_DATA_LENGTH = 167) but were rejected by sendGroupData against MAX_GROUP_DATA_LENGTH (165), causing ERR_CODE_TABLE_FULL (retry later) to be returned instead of ERR_CODE_ILLEGAL_ARG. Fixes #3345 --- examples/companion_radio/MyMesh.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 317cf284..d96e0f76 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -1270,8 +1270,8 @@ void MyMesh::handleCmdFrame(size_t len) { writeErrFrame(ERR_CODE_NOT_FOUND); // bad channel_idx } else if (data_type == DATA_TYPE_RESERVED) { writeErrFrame(ERR_CODE_ILLEGAL_ARG); - } else if (payload_len > MAX_CHANNEL_DATA_LENGTH) { - MESH_DEBUG_PRINTLN("CMD_SEND_CHANNEL_DATA payload too long: %d > %d", payload_len, MAX_CHANNEL_DATA_LENGTH); + } else if (payload_len > MAX_GROUP_DATA_LENGTH) { + MESH_DEBUG_PRINTLN("CMD_SEND_CHANNEL_DATA payload too long: %d > %d", payload_len, MAX_GROUP_DATA_LENGTH); writeErrFrame(ERR_CODE_ILLEGAL_ARG); } else if (sendGroupData(channel.channel, path, path_len, data_type, payload, payload_len)) { writeOKFrame(); From 133ef6ff5494722c5b253a9050aaf2cf93ae9788 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Br=C3=A1zio?= <jbrazio@gmail.com> Date: Thu, 10 Sep 2026 09:17:37 +0100 Subject: [PATCH 215/381] Validate set af input to prevent out-of-range airtime factors --- src/helpers/CommonRadioPrefs.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/helpers/CommonRadioPrefs.cpp b/src/helpers/CommonRadioPrefs.cpp index a25df880..9d92cad9 100644 --- a/src/helpers/CommonRadioPrefs.cpp +++ b/src/helpers/CommonRadioPrefs.cpp @@ -67,8 +67,14 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest return true; } if (memcmp(command, "set af ", 7) == 0) { - setAirtimeFactor(atof(&command[7])); - strcpy(reply, "OK"); + char* end; + float af = strtof(&command[7], &end); + if (end == &command[7] || af < 0 || af > 9) { + strcpy(reply, "ERROR: af must be 0-9"); + } else { + setAirtimeFactor(af); + strcpy(reply, "OK"); + } return true; } From 074ec3fff1f6161d735066b84bf57f8387de31ef Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Sat, 12 Sep 2026 16:53:45 +1000 Subject: [PATCH 216/381] * telemHasChanged() mod, so that only _specified_ min_delta values are considered. --- examples/simple_sensor/SensorMesh.cpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index de58e2b1..4f2ed8bf 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -81,7 +81,7 @@ static File openAppend(FILESYSTEM* _fs, const char* fname) { /* --------------------- Cayenne LPP helpers ----------------------------*/ -static float findTelemValue(const uint8_t* buf, uint8_t size, uint8_t channel, uint8_t type) { +static float findTelemValue(const uint8_t* buf, uint8_t size, uint8_t channel, uint8_t type, float def_value) { uint8_t i = 0; while (i + 2 < size) { @@ -96,7 +96,7 @@ static float findTelemValue(const uint8_t* buf, uint8_t size, uint8_t channel, u } i += sz; // skip } - return 0.0f; // not found + return def_value; // not found } /* ------------------ end Cayenne LPP helpers ----------------------*/ @@ -117,12 +117,14 @@ bool SensorMesh::telemHasChanged(const uint8_t* min_deltas, uint8_t min_deltas_l float v = LPPData::getFloat(&buf[i], sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); float pv = LPPData::getFloat(&prev_telem[i], sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); - float min_delta = findTelemValue(min_deltas, min_deltas_len, ch, t); + float min_delta = min_deltas_len > 0 + ? findTelemValue(min_deltas, min_deltas_len, ch, t, 1.0e+16f) // default is just something BIG + : 0.0f; // for ANY change if (abs(v - pv) > min_delta) return true; // Yes, has changed i += sz; // skip } - return false; // no changes + return false; // no changes (OR none of the -specified- telemetry values changed by min_delta) } uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len) { @@ -961,7 +963,7 @@ void SensorMesh::formatPacketStatsReply(char *reply) { } float SensorMesh::getTelemValue(uint8_t channel, uint8_t type) { - return findTelemValue(telemetry.getBuffer(), telemetry.getSize(), channel, type); + return findTelemValue(telemetry.getBuffer(), telemetry.getSize(), channel, type, 0.0f); } bool SensorMesh::getGPS(uint8_t channel, float& lat, float& lon, float& alt) { From c0f3bdeb6081743ee2fa669a6ab96da29643352a Mon Sep 17 00:00:00 2001 From: TJ Downes <273720+tjdownes@users.noreply.github.com> Date: Sat, 25 Jul 2026 12:38:55 -0700 Subject: [PATCH 217/381] Add Muzi Base board support (Duo + Uno + SuperIO) One nRF52840 variant shared across both radios, picked per env: Duo runs the LR1121, Uno the SX1262. Same PCB, only the radio and its DIO1 pin change. SuperIO adds the SH1107 OLED, GPS, buzzer and joystick. GPS is driven by the 3-position mode switch (Mode 2 = on), polled live the way thinknode_m1 does it. Five quick user-button presses power the unit off; a press wakes it back on (arms the button as an nRF52 GPIO SENSE source before SYSTEMOFF). Consolidates #2054 and andyshinn's shared-base/uno work, rebased on dev. Co-authored-by: lbibass <ewdries02@gmail.com> Co-authored-by: Andy Shinn <andys@andyshinn.as> --- boards/muzi_base.json | 72 +++++ src/helpers/radiolib/CustomLR1121.h | 41 +++ src/helpers/radiolib/CustomLR1121Wrapper.h | 50 ++++ src/helpers/ui/SH1107Display.cpp | 113 +++++++ src/helpers/ui/SH1107Display.h | 43 +++ variants/muzi_base/muzi_baseBoard.cpp | 52 ++++ variants/muzi_base/muzi_baseBoard.h | 48 +++ variants/muzi_base/platformio.ini | 326 +++++++++++++++++++++ variants/muzi_base/target.cpp | 162 ++++++++++ variants/muzi_base/target.h | 64 ++++ variants/muzi_base/variant.cpp | 90 ++++++ variants/muzi_base/variant.h | 169 +++++++++++ 12 files changed, 1230 insertions(+) create mode 100644 boards/muzi_base.json create mode 100644 src/helpers/radiolib/CustomLR1121.h create mode 100644 src/helpers/radiolib/CustomLR1121Wrapper.h create mode 100644 src/helpers/ui/SH1107Display.cpp create mode 100644 src/helpers/ui/SH1107Display.h create mode 100644 variants/muzi_base/muzi_baseBoard.cpp create mode 100644 variants/muzi_base/muzi_baseBoard.h create mode 100644 variants/muzi_base/platformio.ini create mode 100644 variants/muzi_base/target.cpp create mode 100644 variants/muzi_base/target.h create mode 100644 variants/muzi_base/variant.cpp create mode 100644 variants/muzi_base/variant.h diff --git a/boards/muzi_base.json b/boards/muzi_base.json new file mode 100644 index 00000000..1b2cf7df --- /dev/null +++ b/boards/muzi_base.json @@ -0,0 +1,72 @@ +{ + "build": { + "arduino": { + "ldscript": "nrf52840_s140_v6.ld" + }, + "core": "nRF5", + "cpu": "cortex-m4", + "extra_flags": "-DARDUINO_NRF52840_MUZI_BASE -DNRF52840_XXAA", + "f_cpu": "64000000L", + "hwids": [ + [ + "0x239A", + "0x4405" + ], + [ + "0x239A", + "0x0029" + ], + [ + "0x239A", + "0x002A" + ] + ], + "usb_product": "muzi_base", + "mcu": "nrf52840", + "variant": "MUZI_BASE", + "bsp": { + "name": "adafruit" + }, + "softdevice": { + "sd_flags": "-DS140", + "sd_name": "s140", + "sd_version": "6.1.1", + "sd_fwid": "0x00B6" + }, + "bootloader": { + "settings_addr": "0xFF000" + } + }, + "connectivity": [ + "bluetooth" + ], + "debug": { + "jlink_device": "nRF52840_xxAA", + "onboard_tools": [ + "jlink" + ], + "svd_path": "nrf52840.svd", + "openocd_target": "nrf52.cfg" + }, + "frameworks": [ + "arduino" + ], + "name": "Muzi Base", + "upload": { + "maximum_ram_size": 248832, + "maximum_size": 815104, + "speed": 115200, + "use_1200bps_touch": true, + "require_upload_port": true, + "wait_for_upload_port": true, + "protocol": "nrfutil", + "protocols": [ + "jlink", + "nrfjprog", + "nrfutil", + "stlink" + ] + }, + "url": "https://github.com/muzi-works", + "vendor": "MuziWorks" +} diff --git a/src/helpers/radiolib/CustomLR1121.h b/src/helpers/radiolib/CustomLR1121.h new file mode 100644 index 00000000..873bfabc --- /dev/null +++ b/src/helpers/radiolib/CustomLR1121.h @@ -0,0 +1,41 @@ +#pragma once + +#include <RadioLib.h> +#include "MeshCore.h" + +class CustomLR1121 : public LR1121 { + bool _rx_boosted = false; + + public: + CustomLR1121(Module *mod) : LR1121(mod) { } + + size_t getPacketLength(bool update) override { + size_t len = LR1121::getPacketLength(update); + if (len == 0 && getIrqStatus() & RADIOLIB_LR11X0_IRQ_HEADER_ERR) { + // we've just received a corrupted packet + // this may have triggered a bug causing subsequent packets to be shifted + // call standby() to return radio to known-good state + // recvRaw will call startReceive() to restart rx + MESH_DEBUG_PRINTLN("LR1121: got header err, calling standby()"); + standby(); + } + return len; + } + + float getFreqMHz() const { return freqMHz; } + + int16_t setRxBoostedGainMode(bool en) { + _rx_boosted = en; + return LR1121::setRxBoostedGainMode(en); + } + + bool getRxBoostedGainMode() const { return _rx_boosted; } + + bool isReceiving() { + uint16_t irq = getIrqStatus(); + bool detected = ((irq & RADIOLIB_LR11X0_IRQ_SYNC_WORD_HEADER_VALID) || (irq & RADIOLIB_LR11X0_IRQ_PREAMBLE_DETECTED)); + return detected; + } + uint8_t getSpreadingFactor() const { return spreadingFactor; } + +}; \ No newline at end of file diff --git a/src/helpers/radiolib/CustomLR1121Wrapper.h b/src/helpers/radiolib/CustomLR1121Wrapper.h new file mode 100644 index 00000000..5361ee23 --- /dev/null +++ b/src/helpers/radiolib/CustomLR1121Wrapper.h @@ -0,0 +1,50 @@ +#pragma once + +#include "CustomLR1121.h" +#include "RadioLibWrappers.h" +#include "LR11x0Reset.h" + +class CustomLR1121Wrapper : public RadioLibWrapper { +public: + CustomLR1121Wrapper(CustomLR1121& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { } + + void setParams(float freq, float bw, uint8_t sf, uint8_t cr) override { + ((CustomLR1121 *)_radio)->setFrequency(freq); + ((CustomLR1121 *)_radio)->setSpreadingFactor(sf); + ((CustomLR1121 *)_radio)->setBandwidth(bw); + ((CustomLR1121 *)_radio)->setCodingRate(cr); + updatePreamble(sf); + } + + void doResetAGC() override { lr11x0ResetAGC((LR11x0 *)_radio, ((CustomLR1121 *)_radio)->getFreqMHz(), getRxBoostedGainMode()); } + bool isReceivingPacket() override { + return ((CustomLR1121 *)_radio)->isReceiving(); + } + float getCurrentRSSI() override { + float rssi = -110; + ((CustomLR1121 *)_radio)->getRssiInst(&rssi); + return rssi; + } + + void onSendFinished() override { + RadioLibWrapper::onSendFinished(); + _radio->setPreambleLength(preambleLengthForSF(getSpreadingFactor())); // overcomes weird issues with small and big pkts + } + + uint32_t getEstAirtimeFor(int len_bytes) override { + auto airtime = RadioLibWrapper::getEstAirtimeFor(len_bytes); + return airtime < 200 ? 200 : airtime; // at least 200 millis + } + + float getLastRSSI() const override { return ((CustomLR1121 *)_radio)->getRSSI(); } + float getLastSNR() const override { return ((CustomLR1121 *)_radio)->getSNR(); } + + uint8_t getSpreadingFactor() const override { return ((CustomLR1121 *)_radio)->getSpreadingFactor(); } + + bool setRxBoostedGainMode(bool en) override { + return ((CustomLR1121 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE; + } + bool getRxBoostedGainMode() const override { + return ((CustomLR1121 *)_radio)->getRxBoostedGainMode(); + } +}; diff --git a/src/helpers/ui/SH1107Display.cpp b/src/helpers/ui/SH1107Display.cpp new file mode 100644 index 00000000..09bf424f --- /dev/null +++ b/src/helpers/ui/SH1107Display.cpp @@ -0,0 +1,113 @@ +#include "SH1107Display.h" +#include <Adafruit_GrayOLED.h> +#include "Adafruit_SH110X.h" + +#ifndef DISPLAY_ROTATION +#define DISPLAY_ROTATION 0 +#endif + +ColorVal UIColor::window_bkg = SH110X_BLACK; +ColorVal UIColor::title_bkg = SH110X_BLACK; +ColorVal UIColor::title_txt = SH110X_WHITE; +ColorVal UIColor::primary_txt = SH110X_WHITE; +ColorVal UIColor::secondary_txt = SH110X_WHITE; +ColorVal UIColor::warning_txt = SH110X_WHITE; +ColorVal UIColor::popup_bkg = SH110X_BLACK; +ColorVal UIColor::popup_txt = SH110X_WHITE; +ColorVal UIColor::corp_blue = SH110X_WHITE; + +bool SH1107Display::i2c_probe(TwoWire &wire, uint8_t addr) +{ + wire.beginTransmission(addr); + uint8_t error = wire.endTransmission(); + return (error == 0); +} + +bool SH1107Display::begin() +{ + bool result = display.begin(DISPLAY_ADDRESS, true) && i2c_probe(Wire, DISPLAY_ADDRESS); + if (result) { + display.setRotation(DISPLAY_ROTATION); + } + return result; +} + +void SH1107Display::turnOn() +{ + display.oled_command(SH110X_DISPLAYON); + uint8_t cmd[] = {0xD5, 0xF0}; + display.oled_commandList(cmd, 2); + _isOn = true; +} + +void SH1107Display::turnOff() +{ + display.oled_command(SH110X_DISPLAYOFF); + _isOn = false; +} + +void SH1107Display::clear() +{ + display.clearDisplay(); + display.display(); +} + +void SH1107Display::startFrame(ColorVal bkg) +{ + display.clearDisplay(); // TODO: apply 'bkg' + display.setContrast(120); // 0-127. default setting was causing some flickering. + // display.SH110X_SETPRECHARGE(255); + _color = SH110X_WHITE; + display.setTextColor(_color); + display.setTextSize(1); + display.cp437(true); // Use full 256 char 'Code Page 437' font +} + +void SH1107Display::setTextSize(int sz) +{ + display.setTextSize(sz); +} + +void SH1107Display::setColor(ColorVal c) +{ + _color = (c != 0) ? SH110X_WHITE : SH110X_BLACK; + display.setTextColor(_color); +} + +void SH1107Display::setCursor(int x, int y) +{ + display.setCursor(x, y); +} + +void SH1107Display::print(const char *str) +{ + display.print(str); +} + +void SH1107Display::fillRect(int x, int y, int w, int h) +{ + display.fillRect(x, y, w, h, _color); +} + +void SH1107Display::drawRect(int x, int y, int w, int h) +{ + display.drawRect(x, y, w, h, _color); +} + +void SH1107Display::drawXbm(int x, int y, const uint8_t *bits, int w, int h) +{ + display.drawBitmap(x, y, bits, w, h, SH110X_WHITE); +} + +uint16_t SH1107Display::getTextWidth(const char *str) +{ + int16_t x1, y1; + uint16_t w, h; + display.getTextBounds(str, 0, 0, &x1, &y1, &w, &h); + return w; +} + +void SH1107Display::endFrame() +{ + display.display(); +} diff --git a/src/helpers/ui/SH1107Display.h b/src/helpers/ui/SH1107Display.h new file mode 100644 index 00000000..417184c2 --- /dev/null +++ b/src/helpers/ui/SH1107Display.h @@ -0,0 +1,43 @@ +#pragma once + +#include "DisplayDriver.h" +#include <Wire.h> +#include <Adafruit_GFX.h> +#define SH110X_NO_SPLASH +#include <Adafruit_SH110X.h> + +#ifndef PIN_OLED_RESET +#define PIN_OLED_RESET -1 +#endif + +#ifndef DISPLAY_ADDRESS +#define DISPLAY_ADDRESS 0x3c +#endif + +class SH1107Display : public DisplayDriver +{ + Adafruit_SH1107 display; + bool _isOn; + uint8_t _color; + + bool i2c_probe(TwoWire &wire, uint8_t addr); + +public: + SH1107Display() : DisplayDriver(128, 128), display(128, 128, &Wire, PIN_OLED_RESET) { _isOn = false; } + bool begin(); + + bool isOn() override { return _isOn; } + void turnOn() override; + void turnOff() override; + void clear() override; + void startFrame(ColorVal bkg = UIColor::window_bkg) override; + void setTextSize(int sz) override; + void setColor(ColorVal c) override; + void setCursor(int x, int y) override; + void print(const char *str) override; + void fillRect(int x, int y, int w, int h) override; + void drawRect(int x, int y, int w, int h) override; + void drawXbm(int x, int y, const uint8_t *bits, int w, int h) override; + uint16_t getTextWidth(const char *str) override; + void endFrame() override; +}; diff --git a/variants/muzi_base/muzi_baseBoard.cpp b/variants/muzi_base/muzi_baseBoard.cpp new file mode 100644 index 00000000..ed713fa0 --- /dev/null +++ b/variants/muzi_base/muzi_baseBoard.cpp @@ -0,0 +1,52 @@ +#include <Arduino.h> +#include <Wire.h> + +#include "muzi_baseBoard.h" + +#ifdef NRF52_POWER_MANAGEMENT +const PowerMgtConfig power_config = { + .lpcomp_ain_channel = PWRMGT_LPCOMP_AIN, + .lpcomp_refsel = PWRMGT_LPCOMP_REFSEL, + .voltage_bootlock = PWRMGT_VOLTAGE_BOOTLOCK +}; + +void muzi_baseBoard::initiateShutdown(uint8_t reason) { + // Disable LoRa module power before shutdown + if (reason == SHUTDOWN_REASON_LOW_VOLTAGE || + reason == SHUTDOWN_REASON_BOOT_PROTECT) { + configureVoltageWake(power_config.lpcomp_ain_channel, power_config.lpcomp_refsel); + } + + enterSystemOff(reason); +} +#endif // NRF52_POWER_MANAGEMENT + +void muzi_baseBoard::begin() { + NRF52BoardDCDC::begin(); + pinMode(PIN_VBAT_READ, INPUT); +#ifdef muzi_base_superIO + // 12V rail is only needed for the superIO display + pinMode(SCREEN_12V_ENABLE, OUTPUT); + digitalWrite(SCREEN_12V_ENABLE, HIGH); // Enable 12V power for SH1107 display + delay(250); +#endif + Wire.begin(); + // delay(1000); // wait for display to initialize. otherwise it doesn't come up on boot. + +#ifdef PIN_USER_BTN + pinMode(PIN_USER_BTN, INPUT_PULLUP); +#endif + pinMode(PIN_BUTTON1, INPUT_PULLUP); + pinMode(PIN_BUTTON2, INPUT_PULLUP); + pinMode(PIN_BUTTON3, INPUT_PULLUP); + pinMode(PIN_BUTTON4, INPUT_PULLUP); + pinMode(PIN_BUTTON5, INPUT_PULLUP); + pinMode(PIN_BUTTON6, INPUT_PULLUP); + +// #if defined(PIN_BOARD_SDA) && defined(PIN_BOARD_SCL) +// Wire.setPins(PIN_BOARD_SDA, PIN_BOARD_SCL); +// #endif +#ifdef NRF52_POWER_MANAGEMENT + checkBootVoltage(&power_config); +#endif +} diff --git a/variants/muzi_base/muzi_baseBoard.h b/variants/muzi_base/muzi_baseBoard.h new file mode 100644 index 00000000..e5412b6a --- /dev/null +++ b/variants/muzi_base/muzi_baseBoard.h @@ -0,0 +1,48 @@ +#pragma once + +#include <MeshCore.h> +#include <Arduino.h> +#include <helpers/NRF52Board.h> + +// The Muzi Base PCB ships in two radio flavors. Keep the user-facing identity +// (OTA/DFU name and reported manufacturer) distinct per radio even though the +// board logic is shared. +#if defined(USE_SX1262) + #define MUZI_BASE_OTA_NAME "MUZI_BASE_UNO_OTA" + #define MUZI_BASE_MFR_NAME "Muzi Base Uno" +#else + #define MUZI_BASE_OTA_NAME "MUZI_BASE_DUO_OTA" + #define MUZI_BASE_MFR_NAME "Muzi Base Duo" +#endif + +class muzi_baseBoard : public NRF52BoardDCDC { +protected: +#ifdef NRF52_POWER_MANAGEMENT + void initiateShutdown(uint8_t reason) override; +#endif + +public: + muzi_baseBoard() : NRF52Board(MUZI_BASE_OTA_NAME) {} + void begin(); + + #define BATTERY_SAMPLES 8 + + uint16_t getBattMilliVolts() override { + analogReadResolution(12); + analogReference(AR_INTERNAL_3_0); + delay(1); + + uint32_t raw = 0; + for (int i = 0; i < BATTERY_SAMPLES; i++) { + raw += analogRead(PIN_VBAT_READ); + } + raw = raw / BATTERY_SAMPLES; + + // ADC_MULTIPLIER is the voltage divider ratio + return (raw * ADC_MULTIPLIER * AREF_VOLTAGE) / 4.096; + } + + const char* getManufacturerName() const override { + return MUZI_BASE_MFR_NAME; + } +}; diff --git a/variants/muzi_base/platformio.ini b/variants/muzi_base/platformio.ini new file mode 100644 index 00000000..eb35d569 --- /dev/null +++ b/variants/muzi_base/platformio.ini @@ -0,0 +1,326 @@ +; ============================================================================ +; Muzi Base (MuziWorks) +; +; One nRF52840 board, shipped in two radio flavors. The radio is selected per +; environment; all board logic lives in variants/muzi_base and is shared: +; muzi_base_duo_* -> LR1121 (USE_LR1121) +; muzi_base_uno_* -> SX1262 (USE_SX1262) +; ============================================================================ + +[muzi_base_common] +extends = nrf52_base +board = muzi_base +board_build.ldscript = boards/nrf52840_s140_v6.ld +build_flags = ${nrf52_base.build_flags} + -I src/helpers/nrf52 + -I lib/nrf52/s140_nrf52_6.1.1_API/include + -I lib/nrf52/s140_nrf52_6.1.1_API/include/nrf52 + -I variants/muzi_base + -I src/helpers/ui + -D muzi_base + -D NRF52_POWER_MANAGEMENT + -D PIN_USER_BTN=PIN_BUTTON1 + -D USER_BTN_PRESSED=LOW + -D PIN_STATUS_LED=35 + -D LORA_TX_POWER=22 + -D P_LORA_BUSY=LORA_BUSY + -D P_LORA_SCLK=LORA_SCLK + -D P_LORA_NSS=LORA_NSS + -D P_LORA_DIO_1=LORA_DIO_1 + -D P_LORA_MISO=LORA_MISO + -D P_LORA_MOSI=LORA_MOSI + -D P_LORA_RESET=LORA_RESET + -D QSPIFLASH=1 +build_src_filter = ${nrf52_base.build_src_filter} + +<helpers/*.cpp> + +<helpers/sensors> + +<../variants/muzi_base> +debug_tool = jlink +upload_protocol = nrfutil +lib_deps = + ${nrf52_base.lib_deps} + ${sensor_base.lib_deps} + +; --------------------------------------------------------------------------- +; Radio selection (Duo = LR1121, Uno = SX1262). The matching radio pins / TCXO +; / RF-switch defines are picked up in variant.h via USE_LR1121 / USE_SX1262. +; --------------------------------------------------------------------------- +[muzi_base_duo] +extends = muzi_base_common +build_flags = ${muzi_base_common.build_flags} + -D USE_LR1121 + -D RADIO_CLASS=CustomLR1121 + -D WRAPPER_CLASS=CustomLR1121Wrapper + -D RF_SWITCH_TABLE + -D RX_BOOSTED_GAIN=true + -D LR11X0_DIO_AS_RF_SWITCH=true + -D LR11X0_DIO3_TCXO_VOLTAGE=3.0 + +[muzi_base_uno] +extends = muzi_base_common +build_flags = ${muzi_base_common.build_flags} + -D USE_SX1262 + -D RADIO_CLASS=CustomSX1262 + -D WRAPPER_CLASS=CustomSX1262Wrapper + -D SX126X_RX_BOOSTED_GAIN=1 + -D SX126X_CURRENT_LIMIT=140 + -D SX126X_DIO2_AS_RF_SWITCH=1 + -D SX126X_DIO3_TCXO_VOLTAGE=3.3 + +; =========================================================================== +; Duo (LR1121) environments +; =========================================================================== +[env:muzi_base_duo_repeater] +extends = muzi_base_duo +build_flags = ${muzi_base_duo.build_flags} + -I examples/companion_radio/ui-new + -D ADVERT_NAME='"Muzi Base Repeater"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=50 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${muzi_base_duo.build_src_filter} + +<../examples/simple_repeater> +lib_deps = ${muzi_base_duo.lib_deps} + +[env:muzi_base_duo_room_server] +extends = muzi_base_duo +build_flags = ${muzi_base_duo.build_flags} + -I examples/companion_radio/ui-new + -D ADVERT_NAME='"Muzi Base Room"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D ROOM_PASSWORD='"hello"' +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${muzi_base_duo.build_src_filter} + +<../examples/simple_room_server> +lib_deps = ${muzi_base_duo.lib_deps} + +[env:muzi_base_duo_companion_radio_usb] +extends = muzi_base_duo +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 708608 +build_flags = ${muzi_base_duo.build_flags} + -I examples/companion_radio/ui-new + -D MAX_CONTACTS=500 ;can increase number of contacts since we have a ton of extra flash. + -D MAX_GROUP_CHANNELS=40 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 + -D OFFLINE_QUEUE_SIZE=256 + -D DISPLAY_CLASS=NullDisplayDriver +build_src_filter = ${muzi_base_duo.build_src_filter} + +<helpers/ui/NullDisplayDriver.cpp> + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = ${muzi_base_duo.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[env:muzi_base_duo_companion_radio_ble] +extends = muzi_base_duo +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 708608 +build_flags = ${muzi_base_duo.build_flags} + -I examples/companion_radio/ui-new + -D MAX_CONTACTS=500 ;can increase number of contacts since we have a ton of extra flash. + -D MAX_GROUP_CHANNELS=40 + -D BLE_PIN_CODE=123456 + -D BLE_TX_POWER=0 + -D QSPIFLASH=1 +; -D BLE_DEBUG_LOGGING=1 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 + -D OFFLINE_QUEUE_SIZE=256 + -D DISPLAY_CLASS=NullDisplayDriver + ; -D ADVERT_NAME='"@@MAC"' +build_src_filter = ${muzi_base_duo.build_src_filter} + +<helpers/nrf52/SerialBLEInterface.cpp> + +<helpers/sensors> + +<helpers/ui/NullDisplayDriver.cpp> + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = ${muzi_base_duo.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[muzi_base_duo_superIO] +extends = muzi_base_duo +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 708608 +build_flags = ${muzi_base_duo.build_flags} + -D muzi_base_superIO + -D UI_HAS_JOYSTICK=1 + -D OFFLINE_QUEUE_SIZE=256 + -D DISPLAY_CLASS=SH1107Display + -D DISPLAY_ROTATION=2 + -D ENV_INCLUDE_GPS=1 + -D ENV_SKIP_GPS_DETECT + -D PIN_BUZZER=22 +build_src_filter = ${muzi_base_duo.build_src_filter} + +<helpers/nrf52/SerialBLEInterface.cpp> + +<helpers/sensors> + +<helpers/ui/SH1107Display.cpp> + +<helpers/ui/buzzer.cpp> + +<helpers/ui/MomentaryButton.cpp> +lib_deps = ${muzi_base_duo.lib_deps} + densaugeo/base64 @ ~1.4.0 + stevemarple/MicroNMEA @ ^2.0.6 + end2endzone/NonBlockingRTTTL@^1.3.0 + adafruit/Adafruit SH110X@^2.1.14 + artronshop/ArtronShop_RX8130CE@1.0.0 + adafruit/Adafruit GFX Library @ ^1.12.1 +debug_tool = jlink +upload_protocol = nrfutil + +[env:muzi_base_duo_companion_radio_ble_superIO] +extends = muzi_base_duo_superIO +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 708608 +build_flags = ${muzi_base_duo_superIO.build_flags} + -D MAX_CONTACTS=500 ; can increase number of contacts since we have a ton of extra flash. + -D MAX_GROUP_CHANNELS=40 + -I examples/companion_radio/ui-new + -D BLE_PIN_CODE=123456 + -D BLE_TX_POWER=0 + -D QSPIFLASH=1 +; -D BLE_DEBUG_LOGGING=1 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 + -D OFFLINE_QUEUE_SIZE=256 +build_src_filter = ${muzi_base_duo_superIO.build_src_filter} + +<helpers/nrf52/SerialBLEInterface.cpp> + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = + ${muzi_base_duo_superIO.lib_deps} + +; =========================================================================== +; Uno (SX1262) environments +; =========================================================================== +[env:muzi_base_uno_repeater] +extends = muzi_base_uno +build_flags = ${muzi_base_uno.build_flags} + -I examples/companion_radio/ui-new + -D ADVERT_NAME='"Muzi Base Repeater"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=50 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${muzi_base_uno.build_src_filter} + +<../examples/simple_repeater> +lib_deps = ${muzi_base_uno.lib_deps} + +[env:muzi_base_uno_room_server] +extends = muzi_base_uno +build_flags = ${muzi_base_uno.build_flags} + -I examples/companion_radio/ui-new + -D ADVERT_NAME='"Muzi Base Room"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D ROOM_PASSWORD='"hello"' +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${muzi_base_uno.build_src_filter} + +<../examples/simple_room_server> +lib_deps = ${muzi_base_uno.lib_deps} + +[env:muzi_base_uno_companion_radio_usb] +extends = muzi_base_uno +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 708608 +build_flags = ${muzi_base_uno.build_flags} + -I examples/companion_radio/ui-new + -D MAX_CONTACTS=500 ;can increase number of contacts since we have a ton of extra flash. + -D MAX_GROUP_CHANNELS=40 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 + -D OFFLINE_QUEUE_SIZE=256 + -D DISPLAY_CLASS=NullDisplayDriver +build_src_filter = ${muzi_base_uno.build_src_filter} + +<helpers/ui/NullDisplayDriver.cpp> + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = ${muzi_base_uno.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[env:muzi_base_uno_companion_radio_ble] +extends = muzi_base_uno +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 708608 +build_flags = ${muzi_base_uno.build_flags} + -I examples/companion_radio/ui-new + -D MAX_CONTACTS=500 ;can increase number of contacts since we have a ton of extra flash. + -D MAX_GROUP_CHANNELS=40 + -D BLE_PIN_CODE=123456 + -D BLE_TX_POWER=0 + -D QSPIFLASH=1 +; -D BLE_DEBUG_LOGGING=1 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 + -D OFFLINE_QUEUE_SIZE=256 + -D DISPLAY_CLASS=NullDisplayDriver + ; -D ADVERT_NAME='"@@MAC"' +build_src_filter = ${muzi_base_uno.build_src_filter} + +<helpers/nrf52/SerialBLEInterface.cpp> + +<helpers/sensors> + +<helpers/ui/NullDisplayDriver.cpp> + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = ${muzi_base_uno.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[muzi_base_uno_superIO] +extends = muzi_base_uno +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 708608 +build_flags = ${muzi_base_uno.build_flags} + -D muzi_base_superIO + -D UI_HAS_JOYSTICK=1 + -D OFFLINE_QUEUE_SIZE=256 + -D DISPLAY_CLASS=SH1107Display + -D DISPLAY_ROTATION=2 + -D ENV_INCLUDE_GPS=1 + -D ENV_SKIP_GPS_DETECT + -D PIN_BUZZER=22 +build_src_filter = ${muzi_base_uno.build_src_filter} + +<helpers/nrf52/SerialBLEInterface.cpp> + +<helpers/sensors> + +<helpers/ui/SH1107Display.cpp> + +<helpers/ui/buzzer.cpp> + +<helpers/ui/MomentaryButton.cpp> +lib_deps = ${muzi_base_uno.lib_deps} + densaugeo/base64 @ ~1.4.0 + stevemarple/MicroNMEA @ ^2.0.6 + end2endzone/NonBlockingRTTTL@^1.3.0 + adafruit/Adafruit SH110X@^2.1.14 + artronshop/ArtronShop_RX8130CE@1.0.0 + adafruit/Adafruit GFX Library @ ^1.12.1 +debug_tool = jlink +upload_protocol = nrfutil + +[env:muzi_base_uno_companion_radio_ble_superIO] +extends = muzi_base_uno_superIO +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 708608 +build_flags = ${muzi_base_uno_superIO.build_flags} + -D MAX_CONTACTS=500 ; can increase number of contacts since we have a ton of extra flash. + -D MAX_GROUP_CHANNELS=40 + -I examples/companion_radio/ui-new + -D BLE_PIN_CODE=123456 + -D BLE_TX_POWER=0 + -D QSPIFLASH=1 +; -D BLE_DEBUG_LOGGING=1 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 + -D OFFLINE_QUEUE_SIZE=256 +build_src_filter = ${muzi_base_uno_superIO.build_src_filter} + +<helpers/nrf52/SerialBLEInterface.cpp> + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = + ${muzi_base_uno_superIO.lib_deps} diff --git a/variants/muzi_base/target.cpp b/variants/muzi_base/target.cpp new file mode 100644 index 00000000..2af0c710 --- /dev/null +++ b/variants/muzi_base/target.cpp @@ -0,0 +1,162 @@ +#include <Arduino.h> +#include <nrf_gpio.h> +#include "target.h" +#include "variant.h" + +muzi_baseBoard board; + +RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, SPI); + +WRAPPER_CLASS radio_driver(radio, board); + +VolatileRTCClock fallback_clock; +AutoDiscoverRTCClock rtc_clock(fallback_clock); +#if ENV_INCLUDE_GPS + #include <helpers/sensors/MicroNMEALocationProvider.h> + MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + MuziBaseSensorManager sensors = MuziBaseSensorManager(nmea); +#else + MuziBaseSensorManager sensors; +#endif + +// user button for the N-click power-off. single-click mode (multiclick off) so +// each press is its own CLICK; we count them ourselves. reliable across the +// idle-sleep loop because it's the same MomentaryButton the UI navigates with. +static MomentaryButton pwr_btn(PIN_USER_BTN, 0, true, true, false); + +// power off, arming the user button as a wake source first so a later press +// turns it back on. wait for the button to release (the 5th click already fires +// on release, so this returns quickly), then set nRF52 GPIO SENSE (press = LOW); +// it survives into SYSTEMOFF because shutdownPeripherals() doesn't touch this pin. +static void muziPowerOff() { + uint32_t t0 = millis(); + while (digitalRead(PIN_USER_BTN) == USER_BTN_PRESSED && (millis() - t0) < 3000) { delay(5); } + delay(50); // settle + nrf_gpio_cfg_sense_input(g_ADigitalPinMap[PIN_USER_BTN], NRF_GPIO_PIN_PULLUP, NRF_GPIO_PIN_SENSE_LOW); + board.powerOff(); // shutdownPeripherals() + SYSTEMOFF +} + +bool MuziBaseSensorManager::begin() { + pwr_btn.begin(); + bool ok = EnvironmentSensorManager::begin(); +#if ENV_INCLUDE_GPS + pinMode(PIN_GPS_SWITCH, INPUT); + _last_gps_sw = digitalRead(PIN_GPS_SWITCH); // initial gps state from the switch + if (_last_gps_sw == HIGH) start_gps(); else stop_gps(); +#endif + return ok; +} + +void MuziBaseSensorManager::loop() { + // user button: USER_BTN_POWER_OFF_CLICKS quick clicks -> power off + if (pwr_btn.check() == BUTTON_EVENT_CLICK) { + unsigned long t = millis(); + if (t - _pwr_last_click > 2000) _pwr_clicks = 0; // restart if too slow + _pwr_last_click = t; + if (++_pwr_clicks >= USER_BTN_POWER_OFF_CLICKS) muziPowerOff(); + } +#if ENV_INCLUDE_GPS + unsigned long now = millis(); + if (now > _next_sw_check) { // check the mode switch ~once a sec + _next_sw_check = now + 1000; + int sw = digitalRead(PIN_GPS_SWITCH); + if (sw != _last_gps_sw) { + _last_gps_sw = sw; + if (sw == HIGH) start_gps(); else stop_gps(); + } + } +#endif + EnvironmentSensorManager::loop(); +} + +#ifdef DISPLAY_CLASS + DISPLAY_CLASS display; + MomentaryButton user_btn(PIN_USER_BTN, 1000, true, false, false); + MomentaryButton joystick_left(JOYSTICK_LEFT, 1000, true, false, false); + MomentaryButton joystick_right(JOYSTICK_RIGHT, 1000, true, false, false); + MomentaryButton back_btn(PIN_BACK_BTN, 1000, true, false, true); +#endif + +#if defined(USE_LR1121) + #ifndef LORA_CR + #define LORA_CR 5 + #endif + + #ifdef RF_SWITCH_TABLE + static const uint32_t rfswitch_dios[Module::RFSWITCH_MAX_PINS] = { + RADIOLIB_LR11X0_DIO5, + RADIOLIB_LR11X0_DIO6, + RADIOLIB_NC + }; + + static const Module::RfSwitchMode_t rfswitch_table[] = { + // mode DIO5 DIO6 + { LR11x0::MODE_STBY, {LOW, LOW}}, + { LR11x0::MODE_RX, {HIGH, LOW}}, + { LR11x0::MODE_TX, {LOW, HIGH}}, + { LR11x0::MODE_TX_HP, {LOW, HIGH}}, + { LR11x0::MODE_TX_HF, {LOW, LOW}}, + { LR11x0::MODE_GNSS, {LOW, LOW}}, + { LR11x0::MODE_WIFI, {LOW, LOW}}, + END_OF_MODE_TABLE, + }; + #endif +#endif // USE_LR1121 + +bool radio_init() { + //rtc_clock.begin(Wire); + +#if defined(USE_LR1121) + #ifdef LR11X0_DIO3_TCXO_VOLTAGE + float tcxo = LR11X0_DIO3_TCXO_VOLTAGE; + #else + float tcxo = 1.6f; + #endif + + SPI.setPins(P_LORA_MISO, P_LORA_SCLK, P_LORA_MOSI); + SPI.begin(); + int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, RADIOLIB_LR11X0_LORA_SYNC_WORD_PRIVATE, LORA_TX_POWER, 16, tcxo); + if (status != RADIOLIB_ERR_NONE) { + Serial.print("ERROR: radio init failed: "); + Serial.println(status); + return false; // fail + } + + radio.setCRC(2); + radio.explicitHeader(); + + #ifdef RF_SWITCH_TABLE + radio.setRfSwitchTable(rfswitch_dios, rfswitch_table); + #endif + #ifdef RX_BOOSTED_GAIN + radio.setRxBoostedGainMode(RX_BOOSTED_GAIN); + #endif + + return true; // success +#else // USE_SX1262 + // CustomSX1262::std_init() configures the SPI pins, runs begin() with the + // TCXO-voltage fallback, sets CRC, current limit, the DIO2 RF switch, and + // RX boosted gain from the SX126X_* build flags. + return radio.std_init(&SPI); +#endif +} + +uint32_t radio_get_rng_seed() { + return radio.random(0x7FFFFFFF); +} + +void radio_set_params(float freq, float bw, uint8_t sf, uint8_t cr) { + radio.setFrequency(freq); + radio.setSpreadingFactor(sf); + radio.setBandwidth(bw); + radio.setCodingRate(cr); +} + +void radio_set_tx_power(int8_t dbm) { + radio.setOutputPower(dbm); +} + +mesh::LocalIdentity radio_new_identity() { + RadioNoiseListener rng(radio); + return mesh::LocalIdentity(&rng); // create new random identity +} diff --git a/variants/muzi_base/target.h b/variants/muzi_base/target.h new file mode 100644 index 00000000..cbcfff14 --- /dev/null +++ b/variants/muzi_base/target.h @@ -0,0 +1,64 @@ +#pragma once + +#define RADIOLIB_STATIC_ONLY 1 +#include <RadioLib.h> +#include <helpers/radiolib/RadioLibWrappers.h> +#include "muzi_baseBoard.h" +#if defined(USE_LR1121) + #include <helpers/radiolib/CustomLR1121Wrapper.h> +#elif defined(USE_SX1262) + #include <helpers/radiolib/CustomSX1262Wrapper.h> +#else + #error "muzi_base: no radio selected (define USE_LR1121 or USE_SX1262)" +#endif +#include <helpers/ArduinoHelpers.h> +#include <helpers/SensorManager.h> +#include <helpers/sensors/LocationProvider.h> +#include <helpers/AutoDiscoverRTCClock.h> +#include <helpers/sensors/EnvironmentSensorManager.h> // Added: Include for EnvironmentSensorManager +#include <helpers/ui/MomentaryButton.h> + + +#ifdef muzi_base_superIO + #include <helpers/ui/SH1107Display.h> + extern DISPLAY_CLASS display; + extern MomentaryButton user_btn; + extern MomentaryButton joystick_left; + extern MomentaryButton joystick_right; + extern MomentaryButton back_btn; +#elif defined(DISPLAY_CLASS) + #include "helpers/ui/NullDisplayDriver.h" + extern DISPLAY_CLASS display; + extern MomentaryButton user_btn; +#endif + +extern muzi_baseBoard board; +extern WRAPPER_CLASS radio_driver; +extern AutoDiscoverRTCClock rtc_clock; + +// muzi sensor manager, polled from main loop via sensors.loop(): +// - user button: USER_BTN_POWER_OFF_CLICKS quick presses -> power off (all builds) +// - gps mode switch on/off (superIO only, see thinknode_m1) +class MuziBaseSensorManager : public EnvironmentSensorManager { + unsigned long _pwr_last_click = 0; + uint8_t _pwr_clicks = 0; +#if ENV_INCLUDE_GPS + int _last_gps_sw = -1; + unsigned long _next_sw_check = 0; +#endif +public: +#if ENV_INCLUDE_GPS + MuziBaseSensorManager(LocationProvider& location) : EnvironmentSensorManager(location) {} +#else + MuziBaseSensorManager() {} +#endif + bool begin() override; + void loop() override; +}; +extern MuziBaseSensorManager sensors; + +bool radio_init(); +uint32_t radio_get_rng_seed(); +void radio_set_params(float freq, float bw, uint8_t sf, uint8_t cr); +void radio_set_tx_power(int8_t dbm); +mesh::LocalIdentity radio_new_identity(); diff --git a/variants/muzi_base/variant.cpp b/variants/muzi_base/variant.cpp new file mode 100644 index 00000000..b179af8a --- /dev/null +++ b/variants/muzi_base/variant.cpp @@ -0,0 +1,90 @@ +/* + * 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, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, +// P1 pins. + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, +}; + +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(PIN_VBAT_READ, INPUT); + pinMode(PIN_BATTERY_CHARGING, INPUT); + pinMode(PIN_CHARGER_FAULT, INPUT); + pinMode(PIN_BUTTON1, INPUT); + pinMode(PIN_BUTTON2, INPUT); + pinMode(PIN_BUTTON3, INPUT); + pinMode(PIN_BUTTON4, INPUT); + pinMode(PIN_BUTTON5, INPUT); + pinMode(PIN_BUTTON6, INPUT); + pinMode(LED_PIN, OUTPUT); + pinMode(LED_BLUE, OUTPUT); + digitalWrite(LED_PIN, LOW); + digitalWrite(LED_BLUE, LOW); + pinMode(BUZZER_PIN, OUTPUT); + digitalWrite(BUZZER_PIN, LOW); // turn off buzzer at start. don't leave it high. + // gps power is driven by the sensor manager (mode switch). off to start. + pinMode(PIN_GPS_EN, OUTPUT); + digitalWrite(PIN_GPS_EN, LOW); + + pinMode(SCREEN_12V_ENABLE, OUTPUT); + digitalWrite(SCREEN_12V_ENABLE, LOW); // disable 12V power for SH1107 display for now. +} diff --git a/variants/muzi_base/variant.h b/variants/muzi_base/variant.h new file mode 100644 index 00000000..b007c1f8 --- /dev/null +++ b/variants/muzi_base/variant.h @@ -0,0 +1,169 @@ +/* + * 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 PIN_VBAT_READ (31) // P0.31 +#define BATTERY_SENSE_RESOLUTION_BITS 12 +#define BATTERY_SENSE_RESOLUTION 4096.0 +#define AREF_VOLTAGE 3.0 +#define VBAT_AR_INTERNAL AR_INTERNAL_3_0 +#define ADC_MULTIPLIER 1.537 +#define ADC_RESOLUTION 14 +#define PIN_BATTERY_CHARGING (32+2) // P1.02 STAT2 +#define PIN_CHARGER_FAULT (27) // P0.27 STAT1 this pin is disabled on meshtastic. +// BQ25185 has 2 status pins: STAT1 and STAT2. Both are high when not charging. STAT1 high, STAT2 low: charging. Recoverable fault: STAT1 low, STAT2 high. Unrecoverable fault: both low. +// We only need to detect charging vs not charging, but someone else can use the fault pin to log when the battery gets too hot or cold. + +// Power management boot protection threshold (millivolts) +#define PWRMGT_VOLTAGE_BOOTLOCK 3100 // Won't boot below this voltage (mV). BB15 battery min voltage is 3v, 3100mV is minimum batt in meshtastic code. + +// LPCOMP wake configuration (voltage recovery from SYSTEMOFF) +#define PWRMGT_LPCOMP_AIN 7 // AIN7 = P0.31 = PIN_VBAT_READ +#define PWRMGT_LPCOMP_REFSEL 4 // 5/8 VDD (~3.13-3.44V) was the default on RAK4631. should still apply here. + +// Other pins +#define PIN_AREF (-1) +#define SCREEN_12V_ENABLE (23) // SH1107 OLED controller has a pin that needs to be enabled to turn on the screen. + +static const uint8_t AREF = (PIN_AREF); // not used + +//////////////////////////////////////////////////////////////////////////////// +// 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 (19) // P0.19 used for GPS RX +#define PIN_SERIAL1_TX (20) // P0.20 used for GPS TX + +//////////////////////////////////////////////////////////////////////////////// +// I2C pin definition + +#define HAS_WIRE (1) +#define WIRE_INTERFACES_COUNT (2) + +#define PIN_WIRE1_SDA (4) // P0.4 +#define PIN_WIRE1_SCL (6) // P0.6 +#define PIN_WIRE_SDA (24) // P0.24 OLED I2C +#define PIN_WIRE_SCL (25) // P0.25 OLED I2C +#define I2C_NO_RESCAN +// #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 (32+15) // internally connected to p1.15 +#define PIN_SPI_MOSI (32+14) // internally connected to p1.14 +#define PIN_SPI_SCK (32+13) // internally connected to p1.13 +#define PIN_SPI_NSS (32+12) // internally connected to p1.12 + +//////////////////////////////////////////////////////////////////////////////// +// Builtin LEDs + +#define LED_BUILTIN (35) +#define LED_BLUE (-1) // P1.04 turned off, because the blue LED was annoying. +// #define LED_GREEN (35) // P1.03 +#define LED_PIN LED_BUILTIN + +#define LED_STATE_ON LOW + +//////////////////////////////////////////////////////////////////////////////// +// Builtin buttons +#define PIN_BUTTON1 (10) // P0.10 Menu / User Button | on superIO, this is in the center of the "D-Pad", but it's also the button on the Uno/Duo. +#define PIN_BUTTON2 (21) // Joystick Up +#define PIN_BUTTON3 (17) // Joystick Down +#define PIN_BUTTON4 (37) // Joystick Left +#define PIN_BUTTON5 (16) // Joystick Right +#define PIN_BUTTON6 (15) // Back / Cancel Button. +#define JOYSTICK_PRESS PIN_BUTTON1 +#define JOYSTICK_UP PIN_BUTTON2 +#define JOYSTICK_DOWN PIN_BUTTON3 +#define JOYSTICK_LEFT PIN_BUTTON4 +#define JOYSTICK_RIGHT PIN_BUTTON5 +#define PIN_BACK_BTN PIN_BUTTON6 + +// quick user-button presses that power the device off (per Muzi's docs) +#ifndef USER_BTN_POWER_OFF_CLICKS +#define USER_BTN_POWER_OFF_CLICKS 5 +#endif + +//////////////////////////////////////////////////////////////////////////////// +// LoRa radio +// +// The Muzi Base PCB is populated with one of two radios: +// * Base Uno -> SX1262 (USE_SX1262) +// * Base Duo -> LR1121 (USE_LR1121) +// Both share NSS/SCLK/MISO/MOSI/RESET/BUSY. The only pin difference is the +// radio IRQ (DIO1): the SX1262 routes it to P1.06, the LR1121 to P1.08. +// (see Meshtastic muzi_base variant, which defines both radios on this board) + +#define LORA_NSS (PIN_SPI_NSS) // P1.12 +#define LORA_RESET (32+10) // P1.10 +#define LORA_BUSY (32+11) // P1.11 +#define LORA_SCLK (PIN_SPI_SCK) // P1.13 +#define LORA_MISO (PIN_SPI_MISO) // P1.15 +#define LORA_MOSI (PIN_SPI_MOSI) // P1.14 + +// only the IRQ pin differs per radio. rf-switch/tcxo defines are in platformio.ini +#if defined(USE_LR1121) + #define LORA_DIO_1 (32+8) // P1.08 LR1121 IRQ/DIO1 +#elif defined(USE_SX1262) + #define LORA_DIO_1 (32+6) // P1.06 SX1262 IRQ/DIO1 +#else + #error "muzi_base: no radio selected (define USE_LR1121 or USE_SX1262)" +#endif + +//////////////////////////////////////////////////////////////////////////////// +// QSPI Flash +#define PIN_QSPI_SCK (0 + 3) +#define PIN_QSPI_CS (0 + 26) +#define PIN_QSPI_IO0 (0 + 30) +#define PIN_QSPI_IO1 (0 + 29) +#define PIN_QSPI_IO2 (0 + 28) +#define PIN_QSPI_IO3 (0 + 2) + +#define EXTERNAL_FLASH_DEVICES W25Q128JVPQ +#define EXTERNAL_FLASH_USE_QSPI + +//////////////////////////////////////////////////////////////////////////////// +// GPS +#define HAS_GPS 1 +#define PIN_GPS_RX PIN_SERIAL1_RX +#define PIN_GPS_TX PIN_SERIAL1_TX +#define PIN_GPS_EN (32+1) // P1.01 PWR_IO2 on schematic. gps power, driven by the sensor manager. + +// superIO 3-position mode switch (pins from the meshtastic muzi_base variant). +// "Mode 2" reads HIGH on PIN_GPS_SWITCH and turns the gps on. +#define SWITCH_MODE1 (32+9) // P1.09 +#define SWITCH_MODE2 (12) // P0.12 +#define PIN_GPS_SWITCH SWITCH_MODE2 + +//////////////////////////////////////////////////////////////////////////////// +// Buzzer + +#define BUZZER_PIN (22) // P0.22 same load switch design as GPS_EN. From b86ae062886acd99ecc05acb6c9d8655e34d7b92 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Sun, 13 Sep 2026 11:05:38 +1000 Subject: [PATCH 218/381] * min_deltas now mandatory --- examples/simple_sensor/SensorMesh.cpp | 49 ++++++++++++++------------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 4f2ed8bf..54bce50d 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -102,29 +102,24 @@ static float findTelemValue(const uint8_t* buf, uint8_t size, uint8_t channel, u /* ------------------ end Cayenne LPP helpers ----------------------*/ bool SensorMesh::telemHasChanged(const uint8_t* min_deltas, uint8_t min_deltas_len) { - if (telemetry.getSize() != prev_telem_size) return true; - auto buf = telemetry.getBuffer(); uint8_t size = telemetry.getSize(); uint8_t i = 0; - while (i + 2 < size) { - // Get channel # - uint8_t ch = buf[i++]; - // Get data type - uint8_t t = buf[i++]; + while (i + 2 < min_deltas_len) { + uint8_t ch = min_deltas[i++]; // Get channel # + uint8_t t = min_deltas[i++]; // Get data type uint8_t sz = LPPData::getDataSize(t); - float v = LPPData::getFloat(&buf[i], sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); - float pv = LPPData::getFloat(&prev_telem[i], sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); - float min_delta = min_deltas_len > 0 - ? findTelemValue(min_deltas, min_deltas_len, ch, t, 1.0e+16f) // default is just something BIG - : 0.0f; // for ANY change + float min_delta = LPPData::getFloat(&min_deltas[i], sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); + + float v = findTelemValue(buf, size, ch, t, 0.0f); + float pv = findTelemValue(prev_telem, prev_telem_size, ch, t, 0.0f); if (abs(v - pv) > min_delta) return true; // Yes, has changed i += sz; // skip } - return false; // no changes (OR none of the -specified- telemetry values changed by min_delta) + return false; // none of the -specified- telemetry values changed by min_delta } uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len) { @@ -202,26 +197,34 @@ uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, u uint16_t timeout_secs; memcpy(&timeout_secs, &payload[4], 2); uint8_t reserved = payload[6]; + uint8_t min_deltas_len = payload[7]; RegionEntry* r; if (recv_pkt_region && !recv_pkt_region->isWildcard()) { // use request scope r = recv_pkt_region; } else { // use default scope r = region_map.getDefaultRegion(); } - from->extra.sensor.scope_region_id = r ? r->id : 0; - from->extra.sensor.expiry_timestamp = r ? getRTCClock()->getCurrentTime() + timeout_secs : 0; - from->extra.sensor.min_deltas_len = min(sizeof(from->extra.sensor.min_deltas), (size_t)payload[7]); - // NOTE: curr impl truncates LPP min_diffs spec (re-do if better impl is needed) - memcpy(from->extra.sensor.min_deltas, &payload[8], from->extra.sensor.min_deltas_len); - - memcpy(&reply_data[4], &from->extra.sensor.expiry_timestamp, 4); // reply with actual expiry timestamp (or 0 for error) - strcpy((char *)&reply_data[8], r ? r->name : ""); // reply with name of scope that will be used - return 8 + strlen((char *)&reply_data[8]); + uint8_t reply_len; + if (r && min_deltas_len >= 3 && min_deltas_len <= sizeof(from->extra.sensor.min_deltas)) { + from->extra.sensor.scope_region_id = r->id; + from->extra.sensor.expiry_timestamp = getRTCClock()->getCurrentTime() + timeout_secs; + from->extra.sensor.min_deltas_len = min_deltas_len; + memcpy(from->extra.sensor.min_deltas, &payload[8], min_deltas_len); + // reply with actual expiry timestamp + memcpy(&reply_data[4], &from->extra.sensor.expiry_timestamp, 4); + strcpy((char *)&reply_data[8], r ? r->name : ""); // reply with name of scope that will be used + reply_len = 8 + strlen((char *)&reply_data[8]); + } else { + memset(&reply_data[4], 0, 4); // expiry timestamp (0 for error) + reply_len = 8; + } + return reply_len; } if (req_type == REQ_TYPE_UNSUBSCRIBE && (perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { from->extra.sensor.scope_region_id = 0; from->extra.sensor.push_tag = 0; from->extra.sensor.expiry_timestamp = 0; + from->extra.sensor.min_deltas_len = 0; // REVISIT: maybe return some stats, eg total number of telemetry pushes since SUBSCRIBE? memset(&reply_data[4], 0, 8); // success getRNG()->random(&reply_data[12], 2); // just some entropy for better packet-hash uniqueness @@ -1021,7 +1024,7 @@ void SensorMesh::loop() { // compare with previous telemetry, check if any deltas are greater than subscriber minimums for (int i = 0; i < acl.getNumClients(); i++) { auto c = acl.getClientByIdx(i); - if (c->permissions == 0 || c->extra.sensor.scope_region_id == 0) continue; // skip deleted entries, or Not subscribed to deltas + if (c->permissions == 0 || c->extra.sensor.scope_region_id == 0 || c->extra.sensor.min_deltas_len == 0) continue; // skip deleted entries, or Not subscribed to deltas RegionEntry* r = region_map.findById(c->extra.sensor.scope_region_id); if (r == NULL) continue; // unknown region scope if (curr > c->extra.sensor.expiry_timestamp) continue; // subscription now expired From b074e4f992b154f84b1a194c9351aad9ecbfc8a4 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Sun, 13 Sep 2026 11:40:25 +1000 Subject: [PATCH 219/381] * request payload doco --- docs/payloads.md | 52 ++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 44 insertions(+), 8 deletions(-) diff --git a/docs/payloads.md b/docs/payloads.md index fb9cbaf9..493f628c 100644 --- a/docs/payloads.md +++ b/docs/payloads.md @@ -93,6 +93,7 @@ Returned path messages provide a description of the route a packet took from the | Field | Size (bytes) | Description | |--------------|-----------------|------------------------------------------| | timestamp | 4 | sender time (unix timestamp) | +| req type | 1 | request sub type | | request data | rest of payload | application-defined request payload body | For the common chat/server helpers in `BaseChatMesh`, the current request type values are: @@ -100,7 +101,13 @@ For the common chat/server helpers in `BaseChatMesh`, the current request type v | Value | Name | Description | |--------|-----------|----------------------------------------------------| | `0x01` | get stats | get stats of repeater or room server | -| `0x02` | keepalive | keep-alive request used for maintained connections | +| `0x02` | keepalive | (deprecated) | +| `0x03` | get telemetry | request node telemetry | +| `0x04` | get min/max/avg | get sensor node stats on time series data | +| `0x05` | get acl | node ACL query | +| `0x06` | get neighbors | node neighbors query | +| `0x08` | subscribe | subscribe to telemetry push | +| `0x09` | ubsubscribe | unsubscribe from telemetry push | #### Get stats @@ -125,21 +132,50 @@ Gets information about the node, possibly including the following: * Number posted (?) * Number of post pushes (?) -#### Get telemetry data - -Not defined in `BaseChatMesh`. Sensor- and application-specific request payloads may be implemented by higher-level firmware. - #### Get Telemetry -Not defined in `BaseChatMesh`. +| Field | Size (bytes) | Description | +|----------------|--------------|------------------------------| +| timestamp | 4 | sender time (unix timestamp) | +| req type | 1 | 0x03 (request sub type) | +| permission mask | 1 | bitwise inverse mask to AND to permissions (0 = get ALL telem values) | #### Get Min/Max/Ave (Sensor nodes) -Not defined in `BaseChatMesh`. +| Field | Size (bytes) | Description | +|----------------|--------------|------------------------------| +| timestamp | 4 | sender time (unix timestamp) | +| req type | 1 | 0x04 (request sub type) | +| start | 4 | starting time, seconds ago | +| end | 4 | ending time, seconds ago | +| reserved | 2 | should be zeroes | + +#### Subscribe to Telemetry push - (Sensor nodes) + +| Field | Size (bytes) | Description | +|----------------|--------------|------------------------------| +| timestamp | 4 | sender time (unix timestamp) | +| req type | 1 | 0x08 (request sub type) | +| push tag | 4 | 32-bit tag to be used in telemetry push _REPLY payloads | +| timeout secs | 2 | subscription timeout (seconds) | +| reserved | 1 | should be zero | +| min deltas len | 1 | byte length of LPP encoded min_deltas | +| min deltas | (variable) | LPP encoded min_deltas | + +#### Unsubscribe from Telemetry push - (Sensor nodes) + +| Field | Size (bytes) | Description | +|----------------|--------------|------------------------------| +| timestamp | 4 | sender time (unix timestamp) | +| req type | 1 | 0x09 (request sub type) | #### Get Access List -Not defined in `BaseChatMesh`. +| Field | Size (bytes) | Description | +|----------------|--------------|------------------------------| +| timestamp | 4 | sender time (unix timestamp) | +| req type | 1 | 0x05 (request sub type) | +| reserved | 2 | should be zeroes | #### Get Neighbors From ecdbb9ccf6be8de1e9362071476da516c03e0eba Mon Sep 17 00:00:00 2001 From: TadyTheFish <tady.the.fish@gmail.com> Date: Sun, 9 Aug 2026 21:27:22 +0200 Subject: [PATCH 220/381] Enable INA226 support for ProMicro nRF52840 --- variants/promicro/platformio.ini | 2 ++ 1 file changed, 2 insertions(+) diff --git a/variants/promicro/platformio.ini b/variants/promicro/platformio.ini index 90cb475f..da27c2fa 100644 --- a/variants/promicro/platformio.ini +++ b/variants/promicro/platformio.ini @@ -23,6 +23,7 @@ build_flags = ${nrf52_base.build_flags} -D ENV_INCLUDE_BMP280=1 -D ENV_INCLUDE_INA3221=1 -D ENV_INCLUDE_INA219=1 + -D ENV_INCLUDE_INA226=1 build_src_filter = ${nrf52_base.build_src_filter} +<helpers/sensors> +<../variants/promicro> @@ -34,6 +35,7 @@ lib_deps= ${nrf52_base.lib_deps} adafruit/Adafruit BME280 Library @ ^2.3.0 adafruit/Adafruit BMP280 Library@^2.6.8 stevemarple/MicroNMEA @ ^2.0.6 + robtillaart/INA226@^0.6.6 [env:ProMicro_repeater] extends = Promicro From 1c43df5cadc956e02cec893740cd15b330a67b43 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Mon, 14 Sep 2026 20:23:10 +1000 Subject: [PATCH 221/381] * fix for telemHasChanged() --- examples/simple_sensor/SensorMesh.cpp | 41 ++++++++++++++++++--------- examples/simple_sensor/SensorMesh.h | 4 +-- src/helpers/ClientACL.h | 1 + 3 files changed, 30 insertions(+), 16 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 54bce50d..70a619f7 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -101,25 +101,43 @@ static float findTelemValue(const uint8_t* buf, uint8_t size, uint8_t channel, u /* ------------------ end Cayenne LPP helpers ----------------------*/ -bool SensorMesh::telemHasChanged(const uint8_t* min_deltas, uint8_t min_deltas_len) { +bool SensorMesh::telemHasChanged(ClientInfo* c) { auto buf = telemetry.getBuffer(); uint8_t size = telemetry.getSize(); uint8_t i = 0; + bool changed = false; - while (i + 2 < min_deltas_len) { - uint8_t ch = min_deltas[i++]; // Get channel # - uint8_t t = min_deltas[i++]; // Get data type + while (i + 2 < c->extra.sensor.min_deltas_len) { + uint8_t ch = c->extra.sensor.min_deltas[i]; // Get channel # + uint8_t t = c->extra.sensor.min_deltas[i + 1]; // Get data type uint8_t sz = LPPData::getDataSize(t); - float min_delta = LPPData::getFloat(&min_deltas[i], sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); + float min_delta = LPPData::getFloat(&c->extra.sensor.min_deltas[i + 2], sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); + float pv = LPPData::getFloat(&c->extra.sensor.prev_telem[i + 2], sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); float v = findTelemValue(buf, size, ch, t, 0.0f); - float pv = findTelemValue(prev_telem, prev_telem_size, ch, t, 0.0f); - if (abs(v - pv) > min_delta) return true; // Yes, has changed + if (abs(v - pv) > min_delta) changed = true; // Yes, has changed - i += sz; // skip + i += 2 + sz; // skip } - return false; // none of the -specified- telemetry values changed by min_delta + if (changed) { + // take snapshot of all _monitored_ telem values, for next cycle + i = 0; + while (i + 2 < c->extra.sensor.min_deltas_len) { + uint8_t ch = c->extra.sensor.min_deltas[i]; // Get channel # + uint8_t t = c->extra.sensor.min_deltas[i + 1]; // Get data type + uint8_t sz = LPPData::getDataSize(t); + + c->extra.sensor.prev_telem[i] = ch; + c->extra.sensor.prev_telem[i + 1] = t; + + float v = findTelemValue(buf, size, ch, t, 0.0f); + LPPData::putFloat(&c->extra.sensor.prev_telem[i + 2], v, sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); + + i += 2 + sz; // skip + } + } + return changed; } uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len) { @@ -774,7 +792,6 @@ SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::Millise num_alert_tasks = 0; set_radio_at = revert_radio_at = 0; recv_pkt_region = NULL; - prev_telem_size = 0; region_load_active = false; // defaults @@ -1028,7 +1045,7 @@ void SensorMesh::loop() { RegionEntry* r = region_map.findById(c->extra.sensor.scope_region_id); if (r == NULL) continue; // unknown region scope if (curr > c->extra.sensor.expiry_timestamp) continue; // subscription now expired - if (telemHasChanged(c->extra.sensor.min_deltas, c->extra.sensor.min_deltas_len)) { + if (telemHasChanged(c)) { TransportKey scope; if (region_map.getTransportKeysFor(*r, &scope, 1) > 0) { uint8_t tlen = telemetry.getSize(); @@ -1048,8 +1065,6 @@ void SensorMesh::loop() { } } } - memcpy(prev_telem, telemetry.getBuffer(), telemetry.getSize()); // save snapshot for next compare cycle - prev_telem_size = telemetry.getSize(); onSensorDataRead(); diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index e0e03c81..6b7a32fe 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -148,8 +148,6 @@ private: uint8_t reply_data[MAX_PACKET_PAYLOAD]; unsigned long dirty_contacts_expiry; CayenneLPP telemetry; - uint8_t prev_telem_size; - uint8_t prev_telem[MAX_PACKET_PAYLOAD - 4]; TransportKeyStore key_store; RegionMap region_map, temp_map; RegionEntry* recv_pkt_region; @@ -166,7 +164,7 @@ private: uint8_t pending_cr; bool region_load_active; - bool telemHasChanged(const uint8_t* min_deltas, uint8_t min_deltas_len); + bool telemHasChanged(ClientInfo* c); uint8_t handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data, bool is_flood); uint8_t handleRequest(ClientInfo* from, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len); mesh::Packet* createSelfAdvert(); diff --git a/src/helpers/ClientACL.h b/src/helpers/ClientACL.h index 39e71f2c..9938bc1e 100644 --- a/src/helpers/ClientACL.h +++ b/src/helpers/ClientACL.h @@ -34,6 +34,7 @@ struct ClientInfo { uint16_t scope_region_id; // scope to use when sending telemetry to this client/subscriber uint8_t min_deltas_len; uint8_t min_deltas[14]; // LPP encoded + uint8_t prev_telem[14]; // LPP encoded } sensor; } extra; From da225c0c5ef8aeb8a3a027c0537e7b42480c2deb Mon Sep 17 00:00:00 2001 From: Avamander <avamander@gmail.com> Date: Mon, 14 Sep 2026 17:53:50 +0300 Subject: [PATCH 222/381] Fix Heltec Mesh Node T1 GNSS pins --- variants/heltec_t1/variant.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/variants/heltec_t1/variant.h b/variants/heltec_t1/variant.h index b52aeba0..72b9a9ed 100644 --- a/variants/heltec_t1/variant.h +++ b/variants/heltec_t1/variant.h @@ -131,8 +131,8 @@ #define GPS_EN_ACTIVE LOW #define PIN_GPS_EN_ACTIVE LOW #define PIN_GPS_PPS (32 + 9) -#define GPS_TX_PIN (0 + 8) -#define GPS_RX_PIN (0 + 7) +#define GPS_RX_PIN (0 + 8) +#define GPS_TX_PIN (0 + 7) #define PIN_GPS_TX GPS_TX_PIN #define PIN_GPS_RX GPS_RX_PIN From f189c7450c27b65070207249f95ef811b22c1091 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Tue, 15 Sep 2026 17:17:48 +1000 Subject: [PATCH 223/381] * subscribe response now returns expiry_secs (not timestamp) --- examples/simple_sensor/SensorMesh.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 70a619f7..b1860668 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -228,12 +228,13 @@ uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, u from->extra.sensor.expiry_timestamp = getRTCClock()->getCurrentTime() + timeout_secs; from->extra.sensor.min_deltas_len = min_deltas_len; memcpy(from->extra.sensor.min_deltas, &payload[8], min_deltas_len); - // reply with actual expiry timestamp - memcpy(&reply_data[4], &from->extra.sensor.expiry_timestamp, 4); + // reply with actual expiry seconds (we could modify/impose restriction) + memcpy(&reply_data[4], &timeout_secs, 2); + memset(&reply_data[6], 0, 2); // reserved strcpy((char *)&reply_data[8], r ? r->name : ""); // reply with name of scope that will be used reply_len = 8 + strlen((char *)&reply_data[8]); } else { - memset(&reply_data[4], 0, 4); // expiry timestamp (0 for error) + memset(&reply_data[4], 0, 4); // expiry secs (0 for error) reply_len = 8; } return reply_len; From 2afb5af26ca043e106a0905650d8f3d9418de1b6 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Tue, 15 Sep 2026 18:41:11 +1000 Subject: [PATCH 224/381] * refactor to support new Board::handleCommand(), and "get/set radio.fem.*" commands --- .../wio-tracker-l1-1w/WioTrackerL1Board.cpp | 51 ++++++++++++++++++- .../wio-tracker-l1-1w/WioTrackerL1Board.h | 10 ++-- 2 files changed, 55 insertions(+), 6 deletions(-) diff --git a/variants/wio-tracker-l1-1w/WioTrackerL1Board.cpp b/variants/wio-tracker-l1-1w/WioTrackerL1Board.cpp index 8210c24e..c6dbdbf5 100644 --- a/variants/wio-tracker-l1-1w/WioTrackerL1Board.cpp +++ b/variants/wio-tracker-l1-1w/WioTrackerL1Board.cpp @@ -15,7 +15,6 @@ void WioTrackerL1Board::begin() { pinMode(PIN_BUTTON4, INPUT_PULLUP); pinMode(PIN_BUTTON5, INPUT_PULLUP); pinMode(PIN_BUTTON6, INPUT_PULLUP); - #if defined(PIN_WIRE_SDA) && defined(PIN_WIRE_SCL) Wire.setPins(PIN_WIRE_SDA, PIN_WIRE_SCL); @@ -32,9 +31,57 @@ void WioTrackerL1Board::begin() { delay(10); // give sx1262 some time to power up } - + bool WioTrackerL1Board::setLoRaFemPaGainEnabled(bool enable) { _is_pa_enabled = enable; digitalWrite(SX126X_POWER_EN, enable ? HIGH : LOW); // enable/disable the 1W PA return true; } + +void WioTrackerL1Board::attachDynamicPrefs(KeyValueStore* prefs) { + _prefs = prefs; + + char gain[8]; + + gain[0] = 0; + _prefs->getByKey("fem_txgain", gain, 7); // get initial values + setLoRaFemPaGainEnabled(strcmp(gain, "1") == 0); +} + +bool WioTrackerL1Board::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { + if (strcmp(command, "get radio.fem.rxgain") == 0) { + strcpy(reply, "Error: unsupported"); + return true; + } + if (memcmp(command, "set radio.fem.rxgain ", 21) == 0) { + strcpy(reply, "Error: unsupported"); + return true; + } + + if (strcmp(command, "get radio.fem.txgain") == 0) { + sprintf(reply, "> %s", isLoRaFemPaGainEnabled() ? "on" : "off"); + return true; + } + if (memcmp(command, "set radio.fem.txgain ", 21) == 0) { + if (memcmp(&command[21], "on", 2) == 0) { + if (setLoRaFemPaGainEnabled(true)) { + _prefs->setByKey("fem_txgain", "1"); + strcpy(reply, "OK - LoRa FEM TX gain on"); + } else { + strcpy(reply, "Error: failed to apply LoRa FEM TX gain"); + } + } else if (memcmp(&command[21], "off", 3) == 0) { + if (setLoRaFemPaGainEnabled(false)) { + _prefs->setByKey("fem_txgain", "0"); + strcpy(reply, "OK - LoRa FEM TX gain off"); + } else { + strcpy(reply, "Error: failed to apply LoRa FEM TX gain"); + } + } else { + strcpy(reply, "Error: state must be on or off"); + } + return true; + } + + return false; // not handled +} diff --git a/variants/wio-tracker-l1-1w/WioTrackerL1Board.h b/variants/wio-tracker-l1-1w/WioTrackerL1Board.h index c5a60944..798145db 100644 --- a/variants/wio-tracker-l1-1w/WioTrackerL1Board.h +++ b/variants/wio-tracker-l1-1w/WioTrackerL1Board.h @@ -8,10 +8,16 @@ class WioTrackerL1Board : public NRF52BoardDCDC { protected: uint8_t btn_prev_state; bool _is_pa_enabled = false; + KeyValueStore* _prefs = NULL; + + bool setLoRaFemPaGainEnabled(bool enable); + bool isLoRaFemPaGainEnabled() const { return _is_pa_enabled; } public: WioTrackerL1Board() : NRF52Board("WioTrackerL1 OTA") {} void begin(); + void attachDynamicPrefs(KeyValueStore* prefs); + bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; #if defined(P_LORA_TX_LED) void onBeforeTransmit() override { @@ -35,10 +41,6 @@ public: return "Seeed Wio Tracker L1"; } - bool canControlLoRaFemPaGain() const override { return true; } - bool setLoRaFemPaGainEnabled(bool enable) override; - bool isLoRaFemPaGainEnabled() const override { return _is_pa_enabled; } - void powerOff() override { setLoRaFemPaGainEnabled(false); // turn Off PA NRF52Board::powerOff(); From b0317bb3bb37e438fd26ddc8767e3ea2fcbb1748 Mon Sep 17 00:00:00 2001 From: Und3r_1337 <dev@chappe05.fr> Date: Wed, 16 Sep 2026 00:03:54 +0200 Subject: [PATCH 225/381] fix(config): allow digits in config keys so keys like gr_1hop round-trip --- src/helpers/ConfigSerializer.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/helpers/ConfigSerializer.cpp b/src/helpers/ConfigSerializer.cpp index 36aff5cc..daf834b2 100644 --- a/src/helpers/ConfigSerializer.cpp +++ b/src/helpers/ConfigSerializer.cpp @@ -24,7 +24,9 @@ static bool is_whitespace(char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; } static bool is_key_char(char c) { - return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_'; + // digits are allowed: keys like gr_1hop contain one, otherwise loadSerial + // fails at that key and prefs stop reloading after a reboot + return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_'; } static bool is_value_char(char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || c == '-' || c == '.'; From ab3cb11a18e06a0ce7190e0144f6f63a44ae4119 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Wed, 16 Sep 2026 21:03:44 +1000 Subject: [PATCH 226/381] * refactor: removed UITask dependency from MyMesh. New MyMesh::Listener interface * UITask's are now a MyMesh task Listener --- examples/companion_radio/AbstractUITask.h | 11 ++--- examples/companion_radio/MyMesh.cpp | 48 +++++++-------------- examples/companion_radio/MyMesh.h | 14 ++++-- examples/companion_radio/main.cpp | 7 +-- examples/companion_radio/ui-new/UITask.cpp | 48 ++++++++++++++++----- examples/companion_radio/ui-new/UITask.h | 7 ++- examples/companion_radio/ui-orig/UITask.cpp | 47 +++++++++++++++++--- examples/companion_radio/ui-orig/UITask.h | 8 +++- examples/companion_radio/ui-tiny/UITask.cpp | 30 +++++++++++-- examples/companion_radio/ui-tiny/UITask.h | 7 ++- 10 files changed, 152 insertions(+), 75 deletions(-) diff --git a/examples/companion_radio/AbstractUITask.h b/examples/companion_radio/AbstractUITask.h index b25b1442..d927c1a3 100644 --- a/examples/companion_radio/AbstractUITask.h +++ b/examples/companion_radio/AbstractUITask.h @@ -12,6 +12,7 @@ #endif #include "NodePrefs.h" +#include "MyMesh.h" enum class UIEventType { none, @@ -22,25 +23,21 @@ enum class UIEventType { ack }; -class AbstractUITask { +class AbstractUITask : public MyMesh::Listener { protected: mesh::MainBoard* _board; MultiSerialInterface* _interfaceManager; - bool _connected; AbstractUITask(mesh::MainBoard* board, MultiSerialInterface* interfaceManager) : _board(board), _interfaceManager(interfaceManager) { - _connected = false; } public: - void setHasConnection(bool connected) { _connected = connected; } - bool hasConnection() const { return _connected; } + bool hasConnection() const { return _interfaceManager->isConnected(); } uint16_t getBattMilliVolts() const { return _board->getBattMilliVolts(); } bool isBluetoothEnabled() const { return _interfaceManager->isBluetoothEnabled(); } void enableBluetooth() { _interfaceManager->enableBluetooth(); } void disableBluetooth() { _interfaceManager->disableBluetooth(); } - virtual void msgRead(int msgcount) = 0; - virtual void newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount) = 0; + virtual void notify(UIEventType t = UIEventType::none) = 0; virtual void loop() = 0; }; diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 01a7473a..7becb0df 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -368,10 +368,6 @@ void MyMesh::onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path memcpy(&out_frame[1], contact.id.pub_key, PUB_KEY_SIZE); _serial->writeFrame(out_frame, 1 + PUB_KEY_SIZE); } - } else { -#ifdef DISPLAY_CLASS - if (_ui) _ui->notify(UIEventType::newContactMessage); -#endif } // add inbound-path to mem cache @@ -395,6 +391,8 @@ void MyMesh::onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path p->path_len = mesh::Packet::copyPath(p->path, path, path_len); } + if (_listener) _listener->onDiscoveredContact(contact, is_new, path_len, path); + if (!is_new) dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); // only schedule lazy write for contacts that are in contacts[] } @@ -520,16 +518,12 @@ void MyMesh::queueMessage(const ContactInfo &from, uint8_t txt_type, mesh::Packe _serial->writeFrame(frame, 1); } -#ifdef DISPLAY_CLASS // we only want to show text messages on display, not cli data bool should_display = txt_type == TXT_TYPE_PLAIN || txt_type == TXT_TYPE_SIGNED_PLAIN; - if (should_display && _ui) { - _ui->newMsg(path_len, from.name, text, offline_queue_len); - if (!_serial->isConnected()) { - _ui->notify(UIEventType::contactMessage); - } + if (should_display && _listener) { + _listener->onMessageRecv(path_len, from.name, text); + _listener->onQueueSizeChanged(offline_queue_len); } -#endif } bool MyMesh::filterRecvFloodPacket(mesh::Packet* packet) { @@ -640,20 +634,16 @@ void MyMesh::onChannelMessageRecv(const mesh::GroupChannel &channel, mesh::Packe uint8_t frame[1]; frame[0] = PUSH_CODE_MSG_WAITING; // send push 'tickle' _serial->writeFrame(frame, 1); - } else { -#ifdef DISPLAY_CLASS - if (_ui) _ui->notify(UIEventType::channelMessage); -#endif } -#ifdef DISPLAY_CLASS - // Get the channel name from the channel index - const char *channel_name = "Unknown"; - ChannelDetails channel_details; - if (getChannel(channel_idx, channel_details)) { - channel_name = channel_details.name; + if (_listener) { + // Get the channel name from the channel index + ChannelDetails channel_details; + if (!getChannel(channel_idx, channel_details)) { + strcpy(channel_details.name, "Unknown"); + } + _listener->onChannelMsgRecv(channel_details, path_len, text); + _listener->onQueueSizeChanged(offline_queue_len); } - if (_ui) _ui->newMsg(path_len, channel_name, text, offline_queue_len); -#endif } void MyMesh::onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint16_t data_type, @@ -930,9 +920,9 @@ uint32_t MyMesh::calcDirectTimeoutMillisFor(uint32_t pkt_airtime_millis, uint8_t void MyMesh::onSendTimeout() {} -MyMesh::MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMeshTables &tables, DataStore& store, AbstractUITask* ui) +MyMesh::MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMeshTables &tables, DataStore& store) : BaseChatMesh(radio, *new ArduinoMillis(), rng, rtc, *new StaticPoolPacketManager(16), tables), - _serial(NULL), telemetry(MAX_PACKET_PAYLOAD - 4), _store(&store), _ui(ui), _iter(0) { + _serial(NULL), telemetry(MAX_PACKET_PAYLOAD - 4), _store(&store), _listener(NULL), _iter(0) { _iter_started = false; _cli_rescue = false; cli_command[0] = 0; @@ -1463,9 +1453,7 @@ void MyMesh::handleCmdFrame(size_t len) { int out_len; if ((out_len = getFromOfflineQueue(out_frame)) > 0) { _serial->writeFrame(out_frame, out_len); -#ifdef DISPLAY_CLASS - if (_ui) _ui->msgRead(offline_queue_len); -#endif + if (_listener) _listener->onQueueSizeChanged(offline_queue_len); } else { out_frame[0] = RESP_CODE_NO_MORE_MESSAGES; _serial->writeFrame(out_frame, 1); @@ -2466,10 +2454,6 @@ void MyMesh::loop() { saveContacts(); dirty_contacts_expiry = 0; } - -#ifdef DISPLAY_CLASS - if (_ui) _ui->setHasConnection(_serial->isConnected()); -#endif } bool MyMesh::advert() { diff --git a/examples/companion_radio/MyMesh.h b/examples/companion_radio/MyMesh.h index 3b98a4f6..be7bc40a 100644 --- a/examples/companion_radio/MyMesh.h +++ b/examples/companion_radio/MyMesh.h @@ -2,7 +2,6 @@ #include <Arduino.h> #include <Mesh.h> -#include "AbstractUITask.h" /*------------ Frame Protocol --------------*/ #define FIRMWARE_VER_CODE 14 @@ -96,10 +95,19 @@ struct DiscoveredNode { class MyMesh : public BaseChatMesh, public DataStoreHost { public: - MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMeshTables &tables, DataStore& store, AbstractUITask* ui=NULL); + class Listener { + public: + virtual void onMessageRecv(uint8_t path_len, const char* from_name, const char* text) = 0; + virtual void onChannelMsgRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) = 0; + virtual void onQueueSizeChanged(int msgcount) = 0; + virtual void onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) = 0; + }; + + MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMeshTables &tables, DataStore& store); void begin(bool has_display); void startInterface(BaseSerialInterface &serial); + void setListener(Listener* listener) { _listener = listener; } const char *getNodeName(); NodePrefs *getNodePrefs(); @@ -237,7 +245,7 @@ private: uint32_t pending_telemetry, pending_discovery; // pending _TELEMETRY_REQ uint32_t pending_req; // pending _BINARY_REQ BaseSerialInterface *_serial; - AbstractUITask* _ui; + Listener* _listener; ContactsIterator _iter; uint32_t _iter_filter_since; diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index 6dc9acdc..857acf45 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -114,11 +114,7 @@ MultiSerialInterface interface_manager; StdRNG fast_rng; SimpleMeshTables tables; -MyMesh the_mesh(radio_driver, fast_rng, rtc_clock, tables, store - #ifdef DISPLAY_CLASS - , &ui_task - #endif -); +MyMesh the_mesh(radio_driver, fast_rng, rtc_clock, tables, store); /* END GLOBAL OBJECTS */ @@ -285,6 +281,7 @@ void setup() { #ifdef DISPLAY_CLASS ui_task.begin(disp, &sensors, the_mesh.getNodePrefs()); // still want to pass this in as dependency, as prefs might be moved + the_mesh.setListener(&ui_task); #endif board.onBootComplete(); diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index 53ae480c..fc6707e2 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -751,17 +751,7 @@ switch(t){ #endif } - -void UITask::msgRead(int msgcount) { - _msgcount = msgcount; - if (msgcount == 0) { - gotoHomeScreen(); - } -} - -void UITask::newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount) { - _msgcount = msgcount; - +void UITask::onMessageRecv(uint8_t path_len, const char* from_name, const char* text) { ((MsgPreviewScreen *) msg_preview)->addPreview(path_len, from_name, text); setCurrScreen(msg_preview); @@ -774,6 +764,42 @@ void UITask::newMsg(uint8_t path_len, const char* from_name, const char* text, i _next_refresh = 100; // trigger refresh } } + + if (!hasConnection()) { + notify(UIEventType::contactMessage); + } +} + +void UITask::onChannelMsgRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) { + ((MsgPreviewScreen *) msg_preview)->addPreview(path_len, channel_details.name, text); + setCurrScreen(msg_preview); + + if (_display != NULL) { + if (!_display->isOn() && !hasConnection()) { + _display->turnOn(); + } + if (_display->isOn()) { + _auto_off = millis() + AUTO_OFF_MILLIS; // extend the auto-off timer + _next_refresh = 100; // trigger refresh + } + } + + if (!hasConnection()) { + notify(UIEventType::channelMessage); + } +} + +void UITask::onQueueSizeChanged(int msgcount) { + _msgcount = msgcount; + if (msgcount == 0) { + gotoHomeScreen(); + } +} + +void UITask::onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) { + if (!hasConnection()) { + notify(UIEventType::newContactMessage); + } } void UITask::userLedHandler() { diff --git a/examples/companion_radio/ui-new/UITask.h b/examples/companion_radio/ui-new/UITask.h index 52d3ffa1..e1200953 100644 --- a/examples/companion_radio/ui-new/UITask.h +++ b/examples/companion_radio/ui-new/UITask.h @@ -90,10 +90,13 @@ public: bool getGPSState(); void toggleGPS(); + // MyMesh::Listener + void onMessageRecv(uint8_t path_len, const char* from_name, const char* text) override; + void onChannelMsgRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) override; + void onQueueSizeChanged(int offline_queue_size) override; + void onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) override; // from AbstractUITask - void msgRead(int msgcount) override; - void newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount) override; void notify(UIEventType t = UIEventType::none) override; void loop() override; diff --git a/examples/companion_radio/ui-orig/UITask.cpp b/examples/companion_radio/ui-orig/UITask.cpp index b49b05dd..08c84587 100644 --- a/examples/companion_radio/ui-orig/UITask.cpp +++ b/examples/companion_radio/ui-orig/UITask.cpp @@ -126,7 +126,7 @@ switch(t){ // Serial.println((int) t); } -void UITask::msgRead(int msgcount) { +void UITask::onQueueSizeChanged(int msgcount) { _msgcount = msgcount; if (msgcount == 0) { clearMsgPreview(); @@ -139,9 +139,7 @@ void UITask::clearMsgPreview() { _need_refresh = true; } -void UITask::newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount) { - _msgcount = msgcount; - +void UITask::onMessageRecv(uint8_t path_len, const char* from_name, const char* text) { #ifdef HAS_DRV2605 vibration.trigger(); // vibrate even while the app is connected (honors quiet + cooldown) #endif @@ -158,10 +156,45 @@ void UITask::newMsg(uint8_t path_len, const char* from_name, const char* text, i _display->turnOn(); } if (_display->isOn()) { - _auto_off = millis() + AUTO_OFF_MILLIS; // extend the auto-off timer - _need_refresh = true; + _auto_off = millis() + AUTO_OFF_MILLIS; // extend the auto-off timer + _need_refresh = true; } } + if (!hasConnection()) { + notify(UIEventType::contactMessage); + } +} + +void UITask::onChannelMsgRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) { +#ifdef HAS_DRV2605 + vibration.trigger(); // vibrate even while the app is connected (honors quiet + cooldown) +#endif + + if (path_len == 0xFF) { + sprintf(_origin, "(F) %s", channel_details.name); + } else { + sprintf(_origin, "(%d) %s", (uint32_t) path_len, channel_details.name); + } + StrHelper::strncpy(_msg, text, sizeof(_msg)); + + if (_display != NULL) { + if (!_display->isOn() && !hasConnection()) { + _display->turnOn(); + } + if (_display->isOn()) { + _auto_off = millis() + AUTO_OFF_MILLIS; // extend the auto-off timer + _need_refresh = true; + } + } + if (!hasConnection()) { + notify(UIEventType::channelMessage); + } +} + +void UITask::onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) { + if (!hasConnection()) { + notify(UIEventType::newContactMessage); + } } void UITask::renderBatteryIndicator(uint16_t batteryMilliVolts) { @@ -262,7 +295,7 @@ void UITask::renderCurrScreen() { _display->print(tmp); // BT pin - if (!_connected && the_mesh.getBLEPin() != 0) { + if (!hasConnection() && the_mesh.getBLEPin() != 0) { _display->setColor(UIColor::warning_txt); _display->setTextSize(2); _display->setCursor(0, 43); diff --git a/examples/companion_radio/ui-orig/UITask.h b/examples/companion_radio/ui-orig/UITask.h index 02d126e8..38141479 100644 --- a/examples/companion_radio/ui-orig/UITask.h +++ b/examples/companion_radio/ui-orig/UITask.h @@ -70,9 +70,13 @@ public: bool hasDisplay() const { return _display != NULL; } void clearMsgPreview(); + // MyMesh::Listener + void onMessageRecv(uint8_t path_len, const char* from_name, const char* text) override; + void onChannelMsgRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) override; + void onQueueSizeChanged(int offline_queue_size) override; + void onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) override; + // from AbstractUITask - void msgRead(int msgcount) override; - void newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount) override; void notify(UIEventType t = UIEventType::none) override; void loop() override; diff --git a/examples/companion_radio/ui-tiny/UITask.cpp b/examples/companion_radio/ui-tiny/UITask.cpp index 9ecd66f1..8a8b77b5 100644 --- a/examples/companion_radio/ui-tiny/UITask.cpp +++ b/examples/companion_radio/ui-tiny/UITask.cpp @@ -503,16 +503,14 @@ switch(t){ } -void UITask::msgRead(int msgcount) { +void UITask::onQueueSizeChanged(int msgcount) { _msgcount = msgcount; if (msgcount == 0) { gotoHomeScreen(); } } -void UITask::newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount) { - _msgcount = msgcount; - +void UITask::onMessageRecv(uint8_t path_len, const char* from_name, const char* text) { if (_display != NULL) { if (!_display->isOn() && !hasConnection()) { _display->turnOn(); @@ -522,6 +520,30 @@ void UITask::newMsg(uint8_t path_len, const char* from_name, const char* text, i _next_refresh = 100; // trigger refresh } } + if (!hasConnection()) { + notify(UIEventType::contactMessage); + } +} + +void UITask::onChannelMsgRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) { + if (_display != NULL) { + if (!_display->isOn() && !hasConnection()) { + _display->turnOn(); + } + if (_display->isOn()) { + _auto_off = millis() + AUTO_OFF_MILLIS; // extend the auto-off timer + _next_refresh = 100; // trigger refresh + } + } + if (!hasConnection()) { + notify(UIEventType::channelMessage); + } +} + +void UITask::onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) { + if (!hasConnection()) { + notify(UIEventType::newContactMessage); + } } void UITask::userLedHandler() { diff --git a/examples/companion_radio/ui-tiny/UITask.h b/examples/companion_radio/ui-tiny/UITask.h index dc689478..925e8d71 100644 --- a/examples/companion_radio/ui-tiny/UITask.h +++ b/examples/companion_radio/ui-tiny/UITask.h @@ -98,10 +98,13 @@ public: bool getGPSState(); void toggleGPS(); + // MyMesh::Listener + void onMessageRecv(uint8_t path_len, const char* from_name, const char* text) override; + void onChannelMsgRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) override; + void onQueueSizeChanged(int offline_queue_size) override; + void onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) override; // from AbstractUITask - void msgRead(int msgcount) override; - void newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount) override; void notify(UIEventType t = UIEventType::none) override; void loop() override; From 70d0997901cb33b55126a84f6017a283ee1eae68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaros=C5=82aw=20Doma=C5=84ski?= <domanoid@gmail.com> Date: Wed, 16 Sep 2026 22:28:55 +0200 Subject: [PATCH 227/381] Enable DC/DC in shared LR1110 initialization --- src/helpers/radiolib/CustomLR1110.h | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/helpers/radiolib/CustomLR1110.h b/src/helpers/radiolib/CustomLR1110.h index 75674a1d..f0fde435 100644 --- a/src/helpers/radiolib/CustomLR1110.h +++ b/src/helpers/radiolib/CustomLR1110.h @@ -13,6 +13,16 @@ class CustomLR1110 : public LR1110 { public: CustomLR1110(Module *mod) : LR1110(mod) { } + int16_t begin(float freq = 434.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, + uint8_t syncWord = RADIOLIB_LR11X0_LORA_SYNC_WORD_PRIVATE, int8_t power = 10, + uint16_t preambleLength = 8, float tcxoVoltage = 1.6) { + int16_t state = LR1110::begin(freq, bw, sf, cr, syncWord, power, preambleLength, + tcxoVoltage); + // RadioLib begin() defaults to LDO; use the LR1110 DC/DC regulator. + if (state == RADIOLIB_ERR_NONE) state = setRegulatorDCDC(); + return state; + } + size_t getPacketLength(bool update) override { size_t len = LR1110::getPacketLength(update); if (len == 0 && getIrqStatus() & RADIOLIB_LR11X0_IRQ_HEADER_ERR) { From e72c9c37595de11ec9273752575f23edd1c912da Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Thu, 17 Sep 2026 13:45:33 +1000 Subject: [PATCH 228/381] * refactored the UI_DISCOVER_* feature --- examples/companion_radio/MyMesh.cpp | 64 ++---------------- examples/companion_radio/MyMesh.h | 35 ++-------- examples/companion_radio/ui-new/UITask.cpp | 72 +++++++++++++++++---- examples/companion_radio/ui-new/UITask.h | 23 ++++++- examples/companion_radio/ui-orig/UITask.cpp | 12 +++- examples/companion_radio/ui-orig/UITask.h | 3 +- examples/companion_radio/ui-tiny/UITask.cpp | 8 ++- examples/companion_radio/ui-tiny/UITask.h | 3 +- 8 files changed, 112 insertions(+), 108 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 7becb0df..6e570ea5 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -139,10 +139,6 @@ #define ERR_CODE_FILE_IO_ERROR 5 #define ERR_CODE_ILLEGAL_ARG 6 -// Copied from simple_repeater (could probably be shared) -#define CTL_TYPE_NODE_DISCOVER_REQ 0x80 -#define CTL_TYPE_NODE_DISCOVER_RESP 0x90 - #define MAX_SIGN_DATA_LEN (8 * 1024) // 8K // Auto-add config bitmask @@ -410,53 +406,6 @@ int MyMesh::getRecentlyHeard(AdvertPath dest[], int max_num) { return max_num; } -#if defined(DISPLAY_CLASS) && !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) -int MyMesh::getDiscoveredNodes(DiscoveredNode nodes[], int max_num) { - if (max_num > DISCOVERED_NODES_TABLE_SIZE) max_num = DISCOVERED_NODES_TABLE_SIZE; - if (max_num > disc_nodes_count) max_num = disc_nodes_count; - - for (int i = 0; i < max_num; i++) { - nodes[i] = discovered_nodes[i]; - } - return max_num; -} - -bool MyMesh::requestRepeatersDiscovery() { - uint8_t cmd_bytes[6]; - cmd_bytes[0] = CTL_TYPE_NODE_DISCOVER_REQ | 1; // DISCOVER_REQ | prefix only - cmd_bytes[1] = 0xFF; // Repeaters - getRNG()->random(&cmd_bytes[2], 4); // tag - disc_nodes_count = 0; - disc_node_req_tag = *((uint32_t*)&cmd_bytes[2]); - mesh::Packet* req = createControlData(cmd_bytes, sizeof(cmd_bytes)); - if (req) { - sendZeroHop(req); - return true; - } - return false; -} - -void MyMesh::checkControlDataForPendingDiscovery(uint8_t payload[], size_t p_len) { - if ((p_len < 12) - || (payload[0] & 0xF0 != CTL_TYPE_NODE_DISCOVER_RESP) - || (disc_nodes_count >= DISCOVERED_NODES_TABLE_SIZE) - || (memcmp(&payload[2], &disc_node_req_tag, 4))) { - return; - } - memcpy(&discovered_nodes[disc_nodes_count].pubkey_prefix, &payload[6], 8); - discovered_nodes[disc_nodes_count].type = payload[0] & 0xF; - discovered_nodes[disc_nodes_count].snr_out = ((int8_t)payload[1]) / 4.0; - discovered_nodes[disc_nodes_count].snr_in = _radio->getLastSNR(); - ContactInfo* c = lookupContactByPubKey(&payload[6], 8); - if (c != NULL) { - strncpy(discovered_nodes[disc_nodes_count].name, c->name, 32); - } else { - discovered_nodes[disc_nodes_count].name[0] = 0; - } - disc_nodes_count ++; -} -#endif - void MyMesh::onContactPathUpdated(const ContactInfo &contact) { out_frame[0] = PUSH_CODE_PATH_UPDATED; memcpy(&out_frame[1], contact.id.pub_key, PUB_KEY_SIZE); @@ -518,10 +467,8 @@ void MyMesh::queueMessage(const ContactInfo &from, uint8_t txt_type, mesh::Packe _serial->writeFrame(frame, 1); } - // we only want to show text messages on display, not cli data - bool should_display = txt_type == TXT_TYPE_PLAIN || txt_type == TXT_TYPE_SIGNED_PLAIN; - if (should_display && _listener) { - _listener->onMessageRecv(path_len, from.name, text); + if (_listener) { + _listener->onMessageRecv(from, txt_type, sender_timestamp, path_len, text); _listener->onQueueSizeChanged(offline_queue_len); } } @@ -840,9 +787,6 @@ void MyMesh::onControlDataRecv(mesh::Packet *packet) { MESH_DEBUG_PRINTLN("onControlDataRecv(), payload_len too long: %d", packet->payload_len); return; } -#if defined(DISPLAY_CLASS) && !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) - checkControlDataForPendingDiscovery(packet->payload, packet->payload_len); -#endif int i = 0; out_frame[i++] = PUSH_CODE_CONTROL_DATA; out_frame[i++] = (int8_t)(_radio->getLastSNR() * 4); @@ -856,6 +800,8 @@ void MyMesh::onControlDataRecv(mesh::Packet *packet) { } else { MESH_DEBUG_PRINTLN("onControlDataRecv(), data received while app offline"); } + + if (_listener) _listener->onControlDataRecv(packet); } void MyMesh::onRawDataRecv(mesh::Packet *packet) { @@ -1039,7 +985,7 @@ void MyMesh::begin(bool has_display) { resetContacts(); _store->loadContacts(this); bootstrapRTCfromContacts(); - addChannel("Public", PUBLIC_GROUP_PSK); // pre-configure Andy's public channel + addChannel("Public", PUBLIC_GROUP_PSK); // pre-configure public channel _store->loadChannels(this); radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr); diff --git a/examples/companion_radio/MyMesh.h b/examples/companion_radio/MyMesh.h index be7bc40a..f1128624 100644 --- a/examples/companion_radio/MyMesh.h +++ b/examples/companion_radio/MyMesh.h @@ -75,6 +75,10 @@ #define REQ_TYPE_KEEP_ALIVE 0x02 #define REQ_TYPE_GET_TELEMETRY_DATA 0x03 +// Copied from simple_repeater +#define CTL_TYPE_NODE_DISCOVER_REQ 0x80 +#define CTL_TYPE_NODE_DISCOVER_RESP 0x90 + struct AdvertPath { uint8_t pubkey_prefix[7]; uint8_t path_len; @@ -83,24 +87,15 @@ struct AdvertPath { uint8_t path[MAX_PATH_SIZE]; }; -#if defined(DISPLAY_CLASS) && !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) -struct DiscoveredNode { - uint8_t pubkey_prefix[9]; - float snr_in; - float snr_out; - char name[32]; - uint8_t type; -}; -#endif - class MyMesh : public BaseChatMesh, public DataStoreHost { public: class Listener { public: - virtual void onMessageRecv(uint8_t path_len, const char* from_name, const char* text) = 0; + virtual void onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, uint8_t path_len, const char* text) = 0; virtual void onChannelMsgRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) = 0; virtual void onQueueSizeChanged(int msgcount) = 0; virtual void onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) = 0; + virtual void onControlDataRecv(const mesh::Packet* packet) = 0; }; MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMeshTables &tables, DataStore& store); @@ -120,11 +115,6 @@ public: int getRecentlyHeard(AdvertPath dest[], int max_num); -#if defined(DISPLAY_CLASS) && !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) - bool requestRepeatersDiscovery(); - int getDiscoveredNodes(DiscoveredNode nodes[], int max_num); -#endif - protected: float getAirtimeBudgetFactor() const override; int getInterferenceThreshold() const override; @@ -287,19 +277,6 @@ private: #define ADVERT_PATH_TABLE_SIZE 16 AdvertPath advert_paths[ADVERT_PATH_TABLE_SIZE]; // circular table - -#if defined(DISPLAY_CLASS) && !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) - #ifdef UI_RECENT_LIST_SIZE - #define DISCOVERED_NODES_TABLE_SIZE UI_RECENT_LIST_SIZE - #else - #define DISCOVERED_NODES_TABLE_SIZE 4 - #endif - DiscoveredNode discovered_nodes[DISCOVERED_NODES_TABLE_SIZE]; // not circular, latest discovered nodes are not kept - uint32_t disc_node_req_tag = 0; - uint32_t disc_nodes_count = 0; - - void checkControlDataForPendingDiscovery(uint8_t payload[], size_t p_len); -#endif }; extern MyMesh the_mesh; diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index fc6707e2..33a4e192 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -99,7 +99,7 @@ class HomeScreen : public UIScreen { #if UI_SENSORS_PAGE == 1 SENSORS, #endif -#if !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) +#if UI_DISCOVER_SCREEN DISCOVERY, #endif #ifndef UI_NO_HIBERNATE @@ -115,8 +115,10 @@ class HomeScreen : public UIScreen { uint8_t _page; bool _shutdown_init; AdvertPath recent[UI_RECENT_LIST_SIZE]; -#if !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) - DiscoveredNode discovered[UI_RECENT_LIST_SIZE]; +#if UI_DISCOVER_SCREEN + DiscoveredNode discovered[DISCOVERED_NODES_TABLE_SIZE]; // not circular, latest discovered nodes are not kept + uint32_t disc_node_req_tag = 0; + uint32_t disc_nodes_count = 0; uint32_t discovery_req_time = 0; bool discovery_disp_names = true; // by default desplay names if available (removes SNR_O) #endif @@ -206,6 +208,40 @@ public: : _task(task), _rtc(rtc), _sensors(sensors), _node_prefs(node_prefs), _page(0), _shutdown_init(false), sensors_lpp(200) { } +#if UI_DISCOVER_SCREEN + bool sendDiscoverRequest() { + uint8_t cmd_bytes[6]; + cmd_bytes[0] = CTL_TYPE_NODE_DISCOVER_REQ | 1; // DISCOVER_REQ | prefix only + cmd_bytes[1] = 0xFF; // Repeaters + the_mesh.getRNG()->random((uint8_t *) &disc_node_req_tag, 4); // generate random tag + memcpy(&cmd_bytes[2], &disc_node_req_tag, 4); + disc_nodes_count = 0; + mesh::Packet* req = the_mesh.createControlData(cmd_bytes, sizeof(cmd_bytes)); + if (req) { + the_mesh.sendZeroHop(req); + discovery_req_time = millis(); + return true; + } + return false; + } + + void handleDiscoverResponse(const mesh::Packet* packet) { + if (disc_nodes_count < DISCOVERED_NODES_TABLE_SIZE && memcmp(&packet->payload[2], &disc_node_req_tag, 4) == 0) { + auto d = &discovered[disc_nodes_count++]; + memcpy(d->pubkey_prefix, &packet->payload[6], 8); + d->type = packet->payload[0] & 0xF; + d->snr_out = ((int8_t)packet->payload[1]) / 4.0; + d->snr_in = radio_driver.getLastSNR(); + ContactInfo* c = the_mesh.lookupContactByPubKey(&packet->payload[6], 8); + if (c != NULL) { + strncpy(d->name, c->name, 32); + } else { + d->name[0] = 0; + } + } + } +#endif + void poll() override { if (_shutdown_init && !_task->isButtonPressed()) { // must wait for USR button to be released _task->shutdown(); @@ -464,9 +500,9 @@ public: if (sensors_scroll) sensors_scroll_offset = (sensors_scroll_offset+1)%sensors_nb; else sensors_scroll_offset = 0; #endif -#if !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) +#if UI_DISCOVER_SCREEN } else if (_page == HomePage::DISCOVERY) { - int count = the_mesh.getDiscoveredNodes(discovered, UI_RECENT_LIST_SIZE); + int count = disc_nodes_count; display.setColor(UIColor::primary_txt); int y = 20; for (int i = 0; i < count; i++, y += 11) { @@ -493,8 +529,8 @@ public: } if (millis() < discovery_req_time + 5000) { return 1000; // more frequent updates just after req - } else if (count < UI_RECENT_LIST_SIZE -1) { // show only 5 sec after last disc - y = 10 + 11 * UI_RECENT_LIST_SIZE; + } else if (count < DISCOVERED_NODES_TABLE_SIZE -1) { // show only 5 sec after last disc + y = 10 + 11 * DISCOVERED_NODES_TABLE_SIZE; display.drawTextCentered(display.width() / 2, y, "discover: " PRESS_LABEL); } #endif @@ -525,7 +561,7 @@ public: if (_page == HomePage::RECENT) { _task->showAlert("Recent adverts", 800); } -#if !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) +#if UI_DISCOVER_SCREEN if (_page == HomePage::DISCOVERY) { _task->showAlert("Repeater disc", 800); } @@ -562,11 +598,10 @@ public: return true; } #endif -#if !(defined(UI_NO_DISCOVER_SCREEN) && (UI_NO_DISCOVER_SCREEN + 0 != 0)) +#if UI_DISCOVER_SCREEN if (c == KEY_ENTER && _page == HomePage::DISCOVERY) { if (millis() > discovery_req_time + 5000) { // rate limiter - the_mesh.requestRepeatersDiscovery(); - discovery_req_time = millis(); + sendDiscoverRequest(); } return true; } @@ -751,8 +786,11 @@ switch(t){ #endif } -void UITask::onMessageRecv(uint8_t path_len, const char* from_name, const char* text) { - ((MsgPreviewScreen *) msg_preview)->addPreview(path_len, from_name, text); +void UITask::onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, uint8_t path_len, const char* text) { + // we only want to show text messages on display, not cli data + if (!(txt_type == TXT_TYPE_PLAIN || txt_type == TXT_TYPE_SIGNED_PLAIN)) return; + + ((MsgPreviewScreen *) msg_preview)->addPreview(path_len, from.name, text); setCurrScreen(msg_preview); if (_display != NULL) { @@ -802,6 +840,14 @@ void UITask::onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path } } +void UITask::onControlDataRecv(const mesh::Packet* packet) { +#if UI_DISCOVER_SCREEN + if (packet->payload_len >= 12 && (packet->payload[0] & 0xF0) == CTL_TYPE_NODE_DISCOVER_RESP) { + ((HomeScreen *) home)->handleDiscoverResponse(packet); + } +#endif +} + void UITask::userLedHandler() { #ifdef PIN_STATUS_LED int cur_time = millis(); diff --git a/examples/companion_radio/ui-new/UITask.h b/examples/companion_radio/ui-new/UITask.h index e1200953..842b1ac9 100644 --- a/examples/companion_radio/ui-new/UITask.h +++ b/examples/companion_radio/ui-new/UITask.h @@ -22,6 +22,26 @@ #include "../AbstractUITask.h" #include "../NodePrefs.h" +#ifndef UI_DISCOVER_SCREEN + #define UI_DISCOVER_SCREEN 1 +#endif + +#if UI_DISCOVER_SCREEN + #ifdef UI_RECENT_LIST_SIZE + #define DISCOVERED_NODES_TABLE_SIZE UI_RECENT_LIST_SIZE + #else + #define DISCOVERED_NODES_TABLE_SIZE 4 + #endif + +struct DiscoveredNode { + float snr_in; + float snr_out; + uint8_t pubkey_prefix[9]; + uint8_t type; + char name[32]; +}; +#endif + class UITask : public AbstractUITask { DisplayDriver* _display; SensorManager* _sensors; @@ -91,10 +111,11 @@ public: void toggleGPS(); // MyMesh::Listener - void onMessageRecv(uint8_t path_len, const char* from_name, const char* text) override; + void onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, uint8_t path_len, const char* text) override; void onChannelMsgRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) override; void onQueueSizeChanged(int offline_queue_size) override; void onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) override; + void onControlDataRecv(const mesh::Packet* packet) override; // from AbstractUITask void notify(UIEventType t = UIEventType::none) override; diff --git a/examples/companion_radio/ui-orig/UITask.cpp b/examples/companion_radio/ui-orig/UITask.cpp index 08c84587..45a81da9 100644 --- a/examples/companion_radio/ui-orig/UITask.cpp +++ b/examples/companion_radio/ui-orig/UITask.cpp @@ -139,15 +139,18 @@ void UITask::clearMsgPreview() { _need_refresh = true; } -void UITask::onMessageRecv(uint8_t path_len, const char* from_name, const char* text) { +void UITask::onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, uint8_t path_len, const char* text) { + // we only want to show text messages on display, not cli data + if (!(txt_type == TXT_TYPE_PLAIN || txt_type == TXT_TYPE_SIGNED_PLAIN)) return; + #ifdef HAS_DRV2605 vibration.trigger(); // vibrate even while the app is connected (honors quiet + cooldown) #endif if (path_len == 0xFF) { - sprintf(_origin, "(F) %s", from_name); + sprintf(_origin, "(F) %s", from.name); } else { - sprintf(_origin, "(%d) %s", (uint32_t) path_len, from_name); + sprintf(_origin, "(%d) %s", (uint32_t) path_len, from.name); } StrHelper::strncpy(_msg, text, sizeof(_msg)); @@ -197,6 +200,9 @@ void UITask::onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path } } +void UITask::onControlDataRecv(const mesh::Packet* packet) { +} + void UITask::renderBatteryIndicator(uint16_t batteryMilliVolts) { // Convert millivolts to percentage #ifndef BATT_MIN_MILLIVOLTS diff --git a/examples/companion_radio/ui-orig/UITask.h b/examples/companion_radio/ui-orig/UITask.h index 38141479..553dc7d0 100644 --- a/examples/companion_radio/ui-orig/UITask.h +++ b/examples/companion_radio/ui-orig/UITask.h @@ -71,10 +71,11 @@ public: void clearMsgPreview(); // MyMesh::Listener - void onMessageRecv(uint8_t path_len, const char* from_name, const char* text) override; + void onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, uint8_t path_len, const char* text) override; void onChannelMsgRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) override; void onQueueSizeChanged(int offline_queue_size) override; void onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) override; + void onControlDataRecv(const mesh::Packet* packet) override; // from AbstractUITask void notify(UIEventType t = UIEventType::none) override; diff --git a/examples/companion_radio/ui-tiny/UITask.cpp b/examples/companion_radio/ui-tiny/UITask.cpp index 8a8b77b5..71a8bb21 100644 --- a/examples/companion_radio/ui-tiny/UITask.cpp +++ b/examples/companion_radio/ui-tiny/UITask.cpp @@ -510,7 +510,10 @@ void UITask::onQueueSizeChanged(int msgcount) { } } -void UITask::onMessageRecv(uint8_t path_len, const char* from_name, const char* text) { +void UITask::onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, uint8_t path_len, const char* text) { + // we only want to show text messages on display, not cli data + if (!(txt_type == TXT_TYPE_PLAIN || txt_type == TXT_TYPE_SIGNED_PLAIN)) return; + if (_display != NULL) { if (!_display->isOn() && !hasConnection()) { _display->turnOn(); @@ -546,6 +549,9 @@ void UITask::onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path } } +void UITask::onControlDataRecv(const mesh::Packet* packet) { +} + void UITask::userLedHandler() { #ifdef PIN_STATUS_LED int cur_time = millis(); diff --git a/examples/companion_radio/ui-tiny/UITask.h b/examples/companion_radio/ui-tiny/UITask.h index 925e8d71..48c697b9 100644 --- a/examples/companion_radio/ui-tiny/UITask.h +++ b/examples/companion_radio/ui-tiny/UITask.h @@ -99,10 +99,11 @@ public: void toggleGPS(); // MyMesh::Listener - void onMessageRecv(uint8_t path_len, const char* from_name, const char* text) override; + void onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, uint8_t path_len, const char* text) override; void onChannelMsgRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) override; void onQueueSizeChanged(int offline_queue_size) override; void onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) override; + void onControlDataRecv(const mesh::Packet* packet) override; // from AbstractUITask void notify(UIEventType t = UIEventType::none) override; From 5ce665754698cc30eae6bfc3710ca56da7a04fa5 Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Thu, 17 Sep 2026 15:52:46 +1200 Subject: [PATCH 229/381] add missing null display driver class for thinknode m7 ethernet variant --- variants/thinknode_m7/platformio.ini | 1 + 1 file changed, 1 insertion(+) diff --git a/variants/thinknode_m7/platformio.ini b/variants/thinknode_m7/platformio.ini index 5606d482..69b38e33 100644 --- a/variants/thinknode_m7/platformio.ini +++ b/variants/thinknode_m7/platformio.ini @@ -169,6 +169,7 @@ build_src_filter = ${ThinkNode_M7.build_src_filter} ${ThinkNode_M7_ethernet.build_src_filter} +<helpers/esp32/*.cpp> +<helpers/ui/MomentaryButton.cpp> + +<helpers/ui/NullDisplayDriver.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-orig/*.cpp> lib_deps = ${ThinkNode_M7.lib_deps} From 083c2d6277ca4d05605dc8469377857a3c3ee5c7 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Thu, 17 Sep 2026 14:25:41 +1000 Subject: [PATCH 230/381] * MyMesh::begin() refactor, removing last display concepts --- examples/companion_radio/MyMesh.cpp | 24 ++++------------ examples/companion_radio/MyMesh.h | 3 +- examples/companion_radio/main.cpp | 43 +++++++++++++++-------------- 3 files changed, 29 insertions(+), 41 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 6e570ea5..409fed9f 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -911,7 +911,7 @@ MyMesh::MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMe #endif } -void MyMesh::begin(bool has_display) { +void MyMesh::begin() { BaseChatMesh::begin(); if (!_store->loadMainIdentity(self_id)) { @@ -963,24 +963,7 @@ void MyMesh::begin(bool has_display) { _prefs.gps_enabled = constrain(_prefs.gps_enabled, 0, 1); // Ensure boolean 0 or 1 _prefs.gps_interval = constrain(_prefs.gps_interval, 0, 86400); // Max 24 hours -#ifdef BLE_PIN_CODE // 123456 by default - if (_prefs.ble_pin == 0) { -#ifdef DISPLAY_CLASS - if (has_display && BLE_PIN_CODE == 123456) { - StdRNG rng; - _active_ble_pin = rng.nextInt(100000, 999999); // random pin each session - } else { - _active_ble_pin = BLE_PIN_CODE; // otherwise static pin - } -#else - _active_ble_pin = BLE_PIN_CODE; // otherwise static pin -#endif - } else { - _active_ble_pin = _prefs.ble_pin; - } -#else - _active_ble_pin = 0; -#endif + _active_ble_pin = _prefs.ble_pin; resetContacts(); _store->loadContacts(this); @@ -1007,6 +990,9 @@ NodePrefs *MyMesh::getNodePrefs() { uint32_t MyMesh::getBLEPin() { return _active_ble_pin; } +void MyMesh::setBLEPin(uint32_t active_pin) { + _active_ble_pin = active_pin; +} struct FreqRange { uint32_t lower_freq, upper_freq; diff --git a/examples/companion_radio/MyMesh.h b/examples/companion_radio/MyMesh.h index f1128624..7bfbb292 100644 --- a/examples/companion_radio/MyMesh.h +++ b/examples/companion_radio/MyMesh.h @@ -100,13 +100,14 @@ public: MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMeshTables &tables, DataStore& store); - void begin(bool has_display); + void begin(); void startInterface(BaseSerialInterface &serial); void setListener(Listener* listener) { _listener = listener; } const char *getNodeName(); NodePrefs *getNodePrefs(); uint32_t getBLEPin(); + void setBLEPin(uint32_t active_pin); void loop(); void handleCmdFrame(size_t len); diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index 857acf45..efc31779 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -172,37 +172,38 @@ void setup() { #endif #endif store.begin(); - the_mesh.begin( - #ifdef DISPLAY_CLASS - disp != NULL - #else - false - #endif - ); + the_mesh.begin(); #elif defined(RP2040_PLATFORM) LittleFS.begin(); store.begin(); - the_mesh.begin( - #ifdef DISPLAY_CLASS - disp != NULL - #else - false - #endif - ); + the_mesh.begin(); #elif defined(ESP32) SPIFFS.begin(true); store.begin(); - the_mesh.begin( - #ifdef DISPLAY_CLASS - disp != NULL - #else - false - #endif - ); + the_mesh.begin(); #else #error "need to define filesystem" #endif +#ifdef BLE_PIN_CODE // 123456 by default + if (the_mesh.getNodePrefs()->ble_pin == 0) { +#ifdef DISPLAY_CLASS + if (disp != NULL && BLE_PIN_CODE == 123456) { + StdRNG rng; + the_mesh.setBLEPin(rng.nextInt(100000, 999999)); // random pin each session + } else { + the_mesh.setBLEPin(BLE_PIN_CODE); // otherwise static pin + } +#else + the_mesh.setBLEPin(BLE_PIN_CODE); // otherwise static pin +#endif + } else { + the_mesh.setBLEPin(the_mesh.getNodePrefs()->ble_pin); + } +#else + the_mesh.setBLEPin(0); +#endif + // add bluetooth interface #if defined(BLE_PIN_CODE) bluetooth_interface.begin(BLE_NAME_PREFIX, the_mesh.getNodePrefs()->node_name, the_mesh.getBLEPin()); From 8e21a7cf3bee2cbb84cbcc8ceeed7ee5b34b625f Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Thu, 17 Sep 2026 17:33:36 +1000 Subject: [PATCH 231/381] * more MyMesh::Listener interface hooks --- examples/companion_radio/MyMesh.cpp | 20 +++++++++++++++++++- examples/companion_radio/MyMesh.h | 15 ++++++++++++--- examples/companion_radio/ui-new/UITask.cpp | 2 +- examples/companion_radio/ui-new/UITask.h | 2 +- examples/companion_radio/ui-orig/UITask.cpp | 5 +---- examples/companion_radio/ui-orig/UITask.h | 3 +-- examples/companion_radio/ui-tiny/UITask.cpp | 5 +---- examples/companion_radio/ui-tiny/UITask.h | 3 +-- 8 files changed, 37 insertions(+), 18 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 409fed9f..61288a6e 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -415,6 +415,11 @@ void MyMesh::onContactPathUpdated(const ContactInfo &contact) { } ContactInfo* MyMesh::processAck(const uint8_t *data) { + if (_listener) { + uint32_t ack_crc; + memcpy(&ack_crc, data, 4); + _listener->onACKRecv(ack_crc); + } // see if matches any in a table for (int i = 0; i < EXPECTED_ACK_TABLE_SIZE; i++) { if (memcmp(data, &expected_ack_table[i].ack, 4) == 0) { // got an ACK from recipient @@ -588,7 +593,7 @@ void MyMesh::onChannelMessageRecv(const mesh::GroupChannel &channel, mesh::Packe if (!getChannel(channel_idx, channel_details)) { strcpy(channel_details.name, "Unknown"); } - _listener->onChannelMsgRecv(channel_details, path_len, text); + _listener->onChannelMessageRecv(channel_details, path_len, text); _listener->onQueueSizeChanged(offline_queue_len); } } @@ -626,6 +631,9 @@ void MyMesh::onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet * frame[0] = PUSH_CODE_MSG_WAITING; // send push 'tickle' _serial->writeFrame(frame, 1); } + if (_listener) { + _listener->onChannelDataRecv(channel, pkt, data_type, data, data_len); + } } uint8_t MyMesh::onContactRequest(const ContactInfo &contact, uint32_t sender_timestamp, const uint8_t *data, @@ -673,6 +681,8 @@ uint8_t MyMesh::onContactRequest(const ContactInfo &contact, uint32_t sender_tim memcpy(&reply[4], telemetry.getBuffer(), tlen); return 4 + tlen; } + } else if (_listener) { + return _listener->onUnhandledRequest(contact, sender_timestamp, data, len, reply); } return 0; // unknown } @@ -748,6 +758,8 @@ void MyMesh::onContactResponse(const ContactInfo &contact, const uint8_t *data, memcpy(&out_frame[i], &data[4], len - 4); i += (len - 4); _serial->writeFrame(out_frame, i); + } else if (_listener && len > 4) { + _listener->onUnhandledResponse(contact, tag, &data[4], len - 4); } } @@ -822,6 +834,9 @@ void MyMesh::onRawDataRecv(mesh::Packet *packet) { } else { MESH_DEBUG_PRINTLN("onRawDataRecv(), data received while app offline"); } + if (_listener) { + _listener->onRawDataRecv(packet); + } } void MyMesh::onTraceRecv(mesh::Packet *packet, uint32_t tag, uint32_t auth_code, uint8_t flags, @@ -852,6 +867,9 @@ void MyMesh::onTraceRecv(mesh::Packet *packet, uint32_t tag, uint32_t auth_code, } else { MESH_DEBUG_PRINTLN("onTraceRecv(), data received while app offline"); } + if (_listener) { + _listener->onTraceRecv(packet, tag, auth_code, flags, path_snrs, path_hashes, path_len); + } } uint32_t MyMesh::calcFloodTimeoutMillisFor(uint32_t pkt_airtime_millis) const { diff --git a/examples/companion_radio/MyMesh.h b/examples/companion_radio/MyMesh.h index 7bfbb292..667b19e1 100644 --- a/examples/companion_radio/MyMesh.h +++ b/examples/companion_radio/MyMesh.h @@ -92,10 +92,19 @@ public: class Listener { public: virtual void onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, uint8_t path_len, const char* text) = 0; - virtual void onChannelMsgRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) = 0; + virtual void onChannelMessageRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) = 0; virtual void onQueueSizeChanged(int msgcount) = 0; - virtual void onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) = 0; - virtual void onControlDataRecv(const mesh::Packet* packet) = 0; + virtual void onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) { } + virtual void onControlDataRecv(const mesh::Packet* packet) { } + virtual void onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint16_t data_type, + const uint8_t *data, size_t data_len) { } + virtual void onACKRecv(uint32_t ack_crc) { } + virtual uint8_t onUnhandledRequest(const ContactInfo &contact, uint32_t sender_timestamp, const uint8_t *data, + uint8_t len, uint8_t *reply) { return 0; /* unknown request type */ } + virtual void onUnhandledResponse(const ContactInfo &from, uint32_t tag, const uint8_t* data, uint8_t len) { } + virtual void onTraceRecv(mesh::Packet *packet, uint32_t tag, uint32_t auth_code, uint8_t flags, + const uint8_t *path_snrs, const uint8_t *path_hashes, uint8_t path_len) { } + virtual void onRawDataRecv(mesh::Packet *packet) { } }; MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMeshTables &tables, DataStore& store); diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index 33a4e192..8457367a 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -808,7 +808,7 @@ void UITask::onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t s } } -void UITask::onChannelMsgRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) { +void UITask::onChannelMessageRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) { ((MsgPreviewScreen *) msg_preview)->addPreview(path_len, channel_details.name, text); setCurrScreen(msg_preview); diff --git a/examples/companion_radio/ui-new/UITask.h b/examples/companion_radio/ui-new/UITask.h index 842b1ac9..47928a17 100644 --- a/examples/companion_radio/ui-new/UITask.h +++ b/examples/companion_radio/ui-new/UITask.h @@ -112,7 +112,7 @@ public: // MyMesh::Listener void onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, uint8_t path_len, const char* text) override; - void onChannelMsgRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) override; + void onChannelMessageRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) override; void onQueueSizeChanged(int offline_queue_size) override; void onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) override; void onControlDataRecv(const mesh::Packet* packet) override; diff --git a/examples/companion_radio/ui-orig/UITask.cpp b/examples/companion_radio/ui-orig/UITask.cpp index 45a81da9..42e4ab79 100644 --- a/examples/companion_radio/ui-orig/UITask.cpp +++ b/examples/companion_radio/ui-orig/UITask.cpp @@ -168,7 +168,7 @@ void UITask::onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t s } } -void UITask::onChannelMsgRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) { +void UITask::onChannelMessageRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) { #ifdef HAS_DRV2605 vibration.trigger(); // vibrate even while the app is connected (honors quiet + cooldown) #endif @@ -200,9 +200,6 @@ void UITask::onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path } } -void UITask::onControlDataRecv(const mesh::Packet* packet) { -} - void UITask::renderBatteryIndicator(uint16_t batteryMilliVolts) { // Convert millivolts to percentage #ifndef BATT_MIN_MILLIVOLTS diff --git a/examples/companion_radio/ui-orig/UITask.h b/examples/companion_radio/ui-orig/UITask.h index 553dc7d0..bb879cb6 100644 --- a/examples/companion_radio/ui-orig/UITask.h +++ b/examples/companion_radio/ui-orig/UITask.h @@ -72,10 +72,9 @@ public: // MyMesh::Listener void onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, uint8_t path_len, const char* text) override; - void onChannelMsgRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) override; + void onChannelMessageRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) override; void onQueueSizeChanged(int offline_queue_size) override; void onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) override; - void onControlDataRecv(const mesh::Packet* packet) override; // from AbstractUITask void notify(UIEventType t = UIEventType::none) override; diff --git a/examples/companion_radio/ui-tiny/UITask.cpp b/examples/companion_radio/ui-tiny/UITask.cpp index 71a8bb21..607ac89c 100644 --- a/examples/companion_radio/ui-tiny/UITask.cpp +++ b/examples/companion_radio/ui-tiny/UITask.cpp @@ -528,7 +528,7 @@ void UITask::onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t s } } -void UITask::onChannelMsgRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) { +void UITask::onChannelMessageRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) { if (_display != NULL) { if (!_display->isOn() && !hasConnection()) { _display->turnOn(); @@ -549,9 +549,6 @@ void UITask::onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path } } -void UITask::onControlDataRecv(const mesh::Packet* packet) { -} - void UITask::userLedHandler() { #ifdef PIN_STATUS_LED int cur_time = millis(); diff --git a/examples/companion_radio/ui-tiny/UITask.h b/examples/companion_radio/ui-tiny/UITask.h index 48c697b9..83591d89 100644 --- a/examples/companion_radio/ui-tiny/UITask.h +++ b/examples/companion_radio/ui-tiny/UITask.h @@ -100,10 +100,9 @@ public: // MyMesh::Listener void onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, uint8_t path_len, const char* text) override; - void onChannelMsgRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) override; + void onChannelMessageRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) override; void onQueueSizeChanged(int offline_queue_size) override; void onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) override; - void onControlDataRecv(const mesh::Packet* packet) override; // from AbstractUITask void notify(UIEventType t = UIEventType::none) override; From 6a711d0d6eb580d77fe26d950816afcd4a3f6318 Mon Sep 17 00:00:00 2001 From: Blake Latchford <github.demote149@passmail.com> Date: Tue, 8 Sep 2026 16:57:12 -0400 Subject: [PATCH 232/381] Extend WiFi disconnect logging to specify reason Today if a user builds firmware with an incorrect WiFi SSID or password, they get a generic `WiFi disconnected.` error message. Extend logging to descirbe the reason that WiFi was disconnected. I gathered the updated logs for the 3 scenarios below. ``` WiFi: Attempting manual WiFi reconnect... WiFi: WiFi disconnected (reason=ASSOC_LEAVE). Flagging for reconnect... WiFi: WiFi disconnected (reason=4WAY_HANDSHAKE_TIMEOUT). Flagging for reconnect... WiFi: WiFi disconnected (reason=4WAY_HANDSHAKE_TIMEOUT). Flagging for reconnect... WiFi: WiFi disconnected (reason=4WAY_HANDSHAKE_TIMEOUT). Flagging for reconnect... ``` ``` WiFi: WiFi disconnected (reason=NO_AP_FOUND). Flagging for reconnect... ``` ``` WiFi: WiFi connected successfully! WiFi: Got connection ``` --- examples/companion_radio/main.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index 6dc9acdc..0e989999 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -229,7 +229,8 @@ void setup() { WiFi.onEvent([](WiFiEvent_t event, WiFiEventInfo_t info){ if (event == ARDUINO_EVENT_WIFI_STA_DISCONNECTED) { - WIFI_DEBUG_PRINTLN("WiFi disconnected. Flagging for reconnect..."); + WIFI_DEBUG_PRINTLN("WiFi disconnected (reason=%s). Flagging for reconnect...", + WiFi.disconnectReasonName((wifi_err_reason_t)info.wifi_sta_disconnected.reason)); wifi_needs_reconnect = true; } else if (event == ARDUINO_EVENT_WIFI_STA_GOT_IP) { WIFI_DEBUG_PRINTLN("WiFi connected successfully!"); From ab315cae3006ed8c6be15453ba376a17e4c5a016 Mon Sep 17 00:00:00 2001 From: Blake Latchford <github.demote149@passmail.com> Date: Thu, 17 Sep 2026 22:12:53 -0400 Subject: [PATCH 233/381] Pin Radiolab for stm32 and replace ltoa MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The major rev from 19.x to 20.x breaks Radiolab, so pin it for now. This should fix the failing wio-e5-mini_repeater builds. ltoa is removed upstream, so it was replaced with snprintf. The p[] buffer is always 16 bytes. Copy/paste for why claude thinks this is fine below, but also if this is broken it wouldn't be new. ``` exp2 in [23, 30] (int_part = mantissa << (exp2 - 23)): this is where int_part can reach its true max, up to 2,147,483,520 — 10 digits. That's what the snprintf bound of 11 (10 digits + NUL) is sized for. But in this branch frac_part is never assigned anything other than its initial 0, so only *p++ = '0' runs for the fraction — 1 char, not 7. exp2 in [0, 22] (int_part = mantissa >> (23 - exp2)): this is the only branch where frac_part can also be nonzero and enter the 7-digit loop. Here int_part < 2^23 by construction, so it's capped at 7 digits, never 10. ``` --- platformio.ini | 4 +++- src/helpers/TxtDataHelpers.cpp | 9 ++++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/platformio.ini b/platformio.ini index de4d6c29..f296f838 100644 --- a/platformio.ini +++ b/platformio.ini @@ -110,7 +110,9 @@ build_flags = ${arduino_base.build_flags} [stm32_base] extends = arduino_base -platform = ststm32 +; Pinned pending upstream fix for upstream conversions. +; https://github.com/jgromes/RadioLib/issues/1873 +platform = ststm32@19.7.1 extra_scripts = post:arch/stm32/build_hex.py build_flags = ${arduino_base.build_flags} -D STM32_PLATFORM diff --git a/src/helpers/TxtDataHelpers.cpp b/src/helpers/TxtDataHelpers.cpp index d327931f..f2621c0d 100644 --- a/src/helpers/TxtDataHelpers.cpp +++ b/src/helpers/TxtDataHelpers.cpp @@ -27,8 +27,9 @@ bool StrHelper::isBlank(const char* str) { } #include <Arduino.h> +#include <stdio.h> -union int32_Float_t +union int32_Float_t { int32_t Long; float Float; @@ -100,11 +101,9 @@ static void _ftoa(float f, char *p, int *status) *p++ = '-'; if (int_part == 0) *p++ = '0'; - else + else { - ltoa(int_part, p, 10); - while (*p) - p++; + p += snprintf(p, 11, "%ld", (long)int_part); } *p++ = '.'; if (frac_part == 0) From 6d2dcafdd07712a292aaa3b0d22ca4cd6a66a25e Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Fri, 18 Sep 2026 18:17:52 +1200 Subject: [PATCH 234/381] added reboot, shutdown and poweroff to companion cli commands --- examples/companion_radio/MyMesh.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 01a7473a..c38fa70a 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2146,6 +2146,16 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* return true; } + if (strcmp(command, "reboot") == 0) { + board.reboot(); // doesn't return + return true; + } + + if (strcmp(command, "poweroff") == 0 || strcmp(command, "shutdown") == 0) { + board.powerOff(); // doesn't return + return true; + } + if (memcmp(command, "set name ", 9) == 0) { if (AdvertDataParser::isValidName(&command[9])) { StrHelper::strncpy(_prefs.node_name, &command[9], sizeof(_prefs.node_name)); From 10f19b3cda0212ff3b913dba9f5a6f0b513a7714 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Fri, 18 Sep 2026 19:03:20 +1000 Subject: [PATCH 235/381] * fix for X1 --- examples/companion_radio/ui-orig/UITask.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/companion_radio/ui-orig/UITask.cpp b/examples/companion_radio/ui-orig/UITask.cpp index 42e4ab79..a717a540 100644 --- a/examples/companion_radio/ui-orig/UITask.cpp +++ b/examples/companion_radio/ui-orig/UITask.cpp @@ -408,7 +408,7 @@ void UITask::userLedHandler() { statusLedWrite(255, 0, 0); // red: battery low } else if (_msgcount > 0) { statusLedWrite(255, 90, 0); // amber: unread messages - } else if (_connected) { + } else if (hasConnection()) { statusLedWrite(0, 0, 255); // blue: app connected } else { statusLedWrite(0, 255, 0); // green: heartbeat From 39ba9ddb15df6ab801ab7480f24da0277d578f63 Mon Sep 17 00:00:00 2001 From: Kevin Le <vinhdat82@gmail.com> Date: Sat, 19 Sep 2026 11:26:42 +0700 Subject: [PATCH 236/381] Off LED before powering off for repeater --- examples/simple_repeater/UITask.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/examples/simple_repeater/UITask.cpp b/examples/simple_repeater/UITask.cpp index e7225557..e0b6a41d 100644 --- a/examples/simple_repeater/UITask.cpp +++ b/examples/simple_repeater/UITask.cpp @@ -140,8 +140,10 @@ void UITask::loop() { } if (_powering_off_at > 0) { // power off timer armed -#ifdef LED_PIN +#if defined(LED_PIN) && defined(LED_STATE_ON) digitalWrite(LED_PIN, LED_STATE_ON); // switch on the led until poweroff + delay(1000); + digitalWrite(LED_PIN, !LED_STATE_ON); // off LED #endif if (millis() > _powering_off_at) { _board->powerOff(); // should not return From 9456aac555934fd12576e7e6ea70bdc12578003b Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Sat, 19 Sep 2026 20:13:18 +1000 Subject: [PATCH 237/381] * misc --- examples/companion_radio/MyMesh.cpp | 6 +++--- examples/companion_radio/MyMesh.h | 13 +++++++------ examples/companion_radio/ui-new/UITask.cpp | 8 +++++--- examples/companion_radio/ui-new/UITask.h | 10 +++++++--- examples/companion_radio/ui-orig/UITask.cpp | 6 ++++-- examples/companion_radio/ui-orig/UITask.h | 4 ++-- examples/companion_radio/ui-tiny/UITask.cpp | 4 ++-- examples/companion_radio/ui-tiny/UITask.h | 4 ++-- 8 files changed, 32 insertions(+), 23 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 61288a6e..e1b031a9 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -473,7 +473,7 @@ void MyMesh::queueMessage(const ContactInfo &from, uint8_t txt_type, mesh::Packe } if (_listener) { - _listener->onMessageRecv(from, txt_type, sender_timestamp, path_len, text); + _listener->onMessageRecv(pkt, from, txt_type, sender_timestamp, text); _listener->onQueueSizeChanged(offline_queue_len); } } @@ -593,7 +593,7 @@ void MyMesh::onChannelMessageRecv(const mesh::GroupChannel &channel, mesh::Packe if (!getChannel(channel_idx, channel_details)) { strcpy(channel_details.name, "Unknown"); } - _listener->onChannelMessageRecv(channel_details, path_len, text); + _listener->onChannelMessageRecv(pkt, channel_details, text); _listener->onQueueSizeChanged(offline_queue_len); } } @@ -632,7 +632,7 @@ void MyMesh::onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet * _serial->writeFrame(frame, 1); } if (_listener) { - _listener->onChannelDataRecv(channel, pkt, data_type, data, data_len); + _listener->onChannelDataRecv(pkt, channel, data_type, data, data_len); } } diff --git a/examples/companion_radio/MyMesh.h b/examples/companion_radio/MyMesh.h index 667b19e1..9f077c30 100644 --- a/examples/companion_radio/MyMesh.h +++ b/examples/companion_radio/MyMesh.h @@ -91,20 +91,21 @@ class MyMesh : public BaseChatMesh, public DataStoreHost { public: class Listener { public: - virtual void onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, uint8_t path_len, const char* text) = 0; - virtual void onChannelMessageRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) = 0; + virtual void onMessageRecv(mesh::Packet *pkt, const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, const char* text) = 0; + virtual void onChannelMessageRecv(mesh::Packet *pkt, ChannelDetails& channel_details, const char* text) = 0; virtual void onQueueSizeChanged(int msgcount) = 0; virtual void onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) { } - virtual void onControlDataRecv(const mesh::Packet* packet) { } - virtual void onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint16_t data_type, + virtual void onControlDataRecv(const mesh::Packet* pkt) { } + virtual void onChannelDataRecv(mesh::Packet *pkt, const mesh::GroupChannel &channel, uint16_t data_type, const uint8_t *data, size_t data_len) { } virtual void onACKRecv(uint32_t ack_crc) { } virtual uint8_t onUnhandledRequest(const ContactInfo &contact, uint32_t sender_timestamp, const uint8_t *data, uint8_t len, uint8_t *reply) { return 0; /* unknown request type */ } virtual void onUnhandledResponse(const ContactInfo &from, uint32_t tag, const uint8_t* data, uint8_t len) { } - virtual void onTraceRecv(mesh::Packet *packet, uint32_t tag, uint32_t auth_code, uint8_t flags, + virtual void onTraceRecv(mesh::Packet *pkt, uint32_t tag, uint32_t auth_code, uint8_t flags, const uint8_t *path_snrs, const uint8_t *path_hashes, uint8_t path_len) { } - virtual void onRawDataRecv(mesh::Packet *packet) { } + virtual void onRawDataRecv(mesh::Packet *pkt) { } + virtual ~Listener() { } }; MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMeshTables &tables, DataStore& store); diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index 8457367a..181bc832 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -786,10 +786,11 @@ switch(t){ #endif } -void UITask::onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, uint8_t path_len, const char* text) { +void UITask::onMessageRecv(mesh::Packet *pkt, const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, const char* text) { // we only want to show text messages on display, not cli data if (!(txt_type == TXT_TYPE_PLAIN || txt_type == TXT_TYPE_SIGNED_PLAIN)) return; + uint8_t path_len = pkt->isRouteFlood() ? pkt->path_len : 0xFF; ((MsgPreviewScreen *) msg_preview)->addPreview(path_len, from.name, text); setCurrScreen(msg_preview); @@ -808,7 +809,8 @@ void UITask::onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t s } } -void UITask::onChannelMessageRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) { +void UITask::onChannelMessageRecv(mesh::Packet *pkt, ChannelDetails& channel_details, const char* text) { + uint8_t path_len = pkt->isRouteFlood() ? pkt->path_len : 0xFF; ((MsgPreviewScreen *) msg_preview)->addPreview(path_len, channel_details.name, text); setCurrScreen(msg_preview); @@ -842,7 +844,7 @@ void UITask::onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path void UITask::onControlDataRecv(const mesh::Packet* packet) { #if UI_DISCOVER_SCREEN - if (packet->payload_len >= 12 && (packet->payload[0] & 0xF0) == CTL_TYPE_NODE_DISCOVER_RESP) { + if (packet->payload_len >= 14 && (packet->payload[0] & 0xF0) == CTL_TYPE_NODE_DISCOVER_RESP) { ((HomeScreen *) home)->handleDiscoverResponse(packet); } #endif diff --git a/examples/companion_radio/ui-new/UITask.h b/examples/companion_radio/ui-new/UITask.h index 47928a17..361b04d0 100644 --- a/examples/companion_radio/ui-new/UITask.h +++ b/examples/companion_radio/ui-new/UITask.h @@ -22,6 +22,10 @@ #include "../AbstractUITask.h" #include "../NodePrefs.h" +#ifdef UI_NO_DISCOVER_SCREEN + #error "UI_NO_DISCOVER_SCREEN is obsolete - use -D UI_DISCOVER_SCREEN=0 instead" +#endif + #ifndef UI_DISCOVER_SCREEN #define UI_DISCOVER_SCREEN 1 #endif @@ -111,11 +115,11 @@ public: void toggleGPS(); // MyMesh::Listener - void onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, uint8_t path_len, const char* text) override; - void onChannelMessageRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) override; + void onMessageRecv(mesh::Packet *pkt, const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, const char* text) override; + void onChannelMessageRecv(mesh::Packet *pkt, ChannelDetails& channel_details, const char* text) override; void onQueueSizeChanged(int offline_queue_size) override; void onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) override; - void onControlDataRecv(const mesh::Packet* packet) override; + void onControlDataRecv(const mesh::Packet* pkt) override; // from AbstractUITask void notify(UIEventType t = UIEventType::none) override; diff --git a/examples/companion_radio/ui-orig/UITask.cpp b/examples/companion_radio/ui-orig/UITask.cpp index a717a540..db8772f4 100644 --- a/examples/companion_radio/ui-orig/UITask.cpp +++ b/examples/companion_radio/ui-orig/UITask.cpp @@ -139,7 +139,7 @@ void UITask::clearMsgPreview() { _need_refresh = true; } -void UITask::onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, uint8_t path_len, const char* text) { +void UITask::onMessageRecv(mesh::Packet *pkt, const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, const char* text) { // we only want to show text messages on display, not cli data if (!(txt_type == TXT_TYPE_PLAIN || txt_type == TXT_TYPE_SIGNED_PLAIN)) return; @@ -147,6 +147,7 @@ void UITask::onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t s vibration.trigger(); // vibrate even while the app is connected (honors quiet + cooldown) #endif + uint8_t path_len = pkt->isRouteFlood() ? pkt->path_len : 0xFF; if (path_len == 0xFF) { sprintf(_origin, "(F) %s", from.name); } else { @@ -168,11 +169,12 @@ void UITask::onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t s } } -void UITask::onChannelMessageRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) { +void UITask::onChannelMessageRecv(mesh::Packet *pkt, ChannelDetails& channel_details, const char* text) { #ifdef HAS_DRV2605 vibration.trigger(); // vibrate even while the app is connected (honors quiet + cooldown) #endif + uint8_t path_len = pkt->isRouteFlood() ? pkt->path_len : 0xFF; if (path_len == 0xFF) { sprintf(_origin, "(F) %s", channel_details.name); } else { diff --git a/examples/companion_radio/ui-orig/UITask.h b/examples/companion_radio/ui-orig/UITask.h index bb879cb6..d5f79898 100644 --- a/examples/companion_radio/ui-orig/UITask.h +++ b/examples/companion_radio/ui-orig/UITask.h @@ -71,8 +71,8 @@ public: void clearMsgPreview(); // MyMesh::Listener - void onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, uint8_t path_len, const char* text) override; - void onChannelMessageRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) override; + void onMessageRecv(mesh::Packet *pkt, const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, const char* text) override; + void onChannelMessageRecv(mesh::Packet *pkt, ChannelDetails& channel_details, const char* text) override; void onQueueSizeChanged(int offline_queue_size) override; void onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) override; diff --git a/examples/companion_radio/ui-tiny/UITask.cpp b/examples/companion_radio/ui-tiny/UITask.cpp index 607ac89c..7b70f836 100644 --- a/examples/companion_radio/ui-tiny/UITask.cpp +++ b/examples/companion_radio/ui-tiny/UITask.cpp @@ -510,7 +510,7 @@ void UITask::onQueueSizeChanged(int msgcount) { } } -void UITask::onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, uint8_t path_len, const char* text) { +void UITask::onMessageRecv(mesh::Packet *pkt, const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, const char* text) { // we only want to show text messages on display, not cli data if (!(txt_type == TXT_TYPE_PLAIN || txt_type == TXT_TYPE_SIGNED_PLAIN)) return; @@ -528,7 +528,7 @@ void UITask::onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t s } } -void UITask::onChannelMessageRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) { +void UITask::onChannelMessageRecv(mesh::Packet *pkt, ChannelDetails& channel_details, const char* text) { if (_display != NULL) { if (!_display->isOn() && !hasConnection()) { _display->turnOn(); diff --git a/examples/companion_radio/ui-tiny/UITask.h b/examples/companion_radio/ui-tiny/UITask.h index 83591d89..084919aa 100644 --- a/examples/companion_radio/ui-tiny/UITask.h +++ b/examples/companion_radio/ui-tiny/UITask.h @@ -99,8 +99,8 @@ public: void toggleGPS(); // MyMesh::Listener - void onMessageRecv(const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, uint8_t path_len, const char* text) override; - void onChannelMessageRecv(ChannelDetails& channel_details, uint8_t path_len, const char* text) override; + void onMessageRecv(mesh::Packet *pkt, const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, const char* text) override; + void onChannelMessageRecv(mesh::Packet *pkt, ChannelDetails& channel_details, const char* text) override; void onQueueSizeChanged(int offline_queue_size) override; void onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) override; From 66f2d49db6e2ab7c549998c5020a442169a06ea9 Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Sun, 20 Sep 2026 14:22:13 +1200 Subject: [PATCH 238/381] allow fetching configured wifi password via companion cli --- examples/companion_radio/MyMesh.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index c38fa70a..79b4a8ce 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2191,6 +2191,10 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* strcpy(reply, "> wifi.pwd updated (reboot to apply)"); return true; } + if (strcmp(command, "get wifi.pwd") == 0) { + sprintf(reply, "> %s", _prefs.wifi_pwd); + return true; + } if (strcmp(command, "set wifi.clear") == 0) { _prefs.wifi_ssid[0] = 0; _prefs.wifi_pwd[0] = 0; @@ -2198,7 +2202,7 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* strcpy(reply, "> wifi config cleared (reboot to apply)"); return true; } - if (strcmp(command, "get wifi.ssid") == 0) { // no 'get wifi.pwd', by design + if (strcmp(command, "get wifi.ssid") == 0) { sprintf(reply, "> %s", _prefs.getWifiSSID()[0] ? _prefs.getWifiSSID() : "(not set)"); return true; } From e5dff422f320dd783770195862e63fbc00188cdf Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Sun, 20 Sep 2026 15:11:21 +1200 Subject: [PATCH 239/381] add wifi support to thinknode m7 ble variant --- variants/thinknode_m7/platformio.ini | 2 ++ 1 file changed, 2 insertions(+) diff --git a/variants/thinknode_m7/platformio.ini b/variants/thinknode_m7/platformio.ini index 69b38e33..128b1244 100644 --- a/variants/thinknode_m7/platformio.ini +++ b/variants/thinknode_m7/platformio.ini @@ -98,11 +98,13 @@ build_flags = -D MAX_GROUP_CHANNELS=40 -D BLE_PIN_CODE=123456 -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_WIFI_INTERFACE ; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 build_src_filter = ${ThinkNode_M7.build_src_filter} ${ThinkNode_M7_ethernet.build_src_filter} +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<helpers/ui/MomentaryButton.cpp> +<helpers/ui/NullDisplayDriver.cpp> +<../examples/companion_radio/*.cpp> From ba0f4ec753e3a132ee396e4e4f9f98f290370cb6 Mon Sep 17 00:00:00 2001 From: TJ Downes <273720+tjdownes@users.noreply.github.com> Date: Sat, 19 Sep 2026 21:47:24 -0700 Subject: [PATCH 240/381] Address review feedback on Muzi Base support - rename the board class and files to MuziBaseBoard - uppercase the build flags (MUZI_BASE, MUZI_BASE_SUPERIO) - name the superIO envs muzi_base_{duo,uno}_superIO_companion_radio_ble so build.sh picks them up - set MAX_CONTACTS to 350 like the other variants - move the pin setup from initVariant() into MuziBaseBoard::begin() --- .../{muzi_baseBoard.cpp => MuziBaseBoard.cpp} | 20 ++++++++++--- .../{muzi_baseBoard.h => MuziBaseBoard.h} | 4 +-- variants/muzi_base/platformio.ini | 22 +++++++-------- variants/muzi_base/target.cpp | 2 +- variants/muzi_base/target.h | 6 ++-- variants/muzi_base/variant.cpp | 28 ------------------- 6 files changed, 33 insertions(+), 49 deletions(-) rename variants/muzi_base/{muzi_baseBoard.cpp => MuziBaseBoard.cpp} (69%) rename variants/muzi_base/{muzi_baseBoard.h => MuziBaseBoard.h} (91%) diff --git a/variants/muzi_base/muzi_baseBoard.cpp b/variants/muzi_base/MuziBaseBoard.cpp similarity index 69% rename from variants/muzi_base/muzi_baseBoard.cpp rename to variants/muzi_base/MuziBaseBoard.cpp index ed713fa0..a104c550 100644 --- a/variants/muzi_base/muzi_baseBoard.cpp +++ b/variants/muzi_base/MuziBaseBoard.cpp @@ -1,7 +1,7 @@ #include <Arduino.h> #include <Wire.h> -#include "muzi_baseBoard.h" +#include "MuziBaseBoard.h" #ifdef NRF52_POWER_MANAGEMENT const PowerMgtConfig power_config = { @@ -10,7 +10,7 @@ const PowerMgtConfig power_config = { .voltage_bootlock = PWRMGT_VOLTAGE_BOOTLOCK }; -void muzi_baseBoard::initiateShutdown(uint8_t reason) { +void MuziBaseBoard::initiateShutdown(uint8_t reason) { // Disable LoRa module power before shutdown if (reason == SHUTDOWN_REASON_LOW_VOLTAGE || reason == SHUTDOWN_REASON_BOOT_PROTECT) { @@ -21,14 +21,26 @@ void muzi_baseBoard::initiateShutdown(uint8_t reason) { } #endif // NRF52_POWER_MANAGEMENT -void muzi_baseBoard::begin() { +void MuziBaseBoard::begin() { NRF52BoardDCDC::begin(); pinMode(PIN_VBAT_READ, INPUT); -#ifdef muzi_base_superIO + pinMode(PIN_BATTERY_CHARGING, INPUT); + pinMode(PIN_CHARGER_FAULT, INPUT); + pinMode(LED_PIN, OUTPUT); + digitalWrite(LED_PIN, LOW); + // output latches default to HIGH, so pull these low right after enabling + pinMode(BUZZER_PIN, OUTPUT); + digitalWrite(BUZZER_PIN, LOW); + // gps power is driven by the sensor manager (mode switch). off to start. + pinMode(PIN_GPS_EN, OUTPUT); + digitalWrite(PIN_GPS_EN, LOW); // 12V rail is only needed for the superIO display pinMode(SCREEN_12V_ENABLE, OUTPUT); +#ifdef MUZI_BASE_SUPERIO digitalWrite(SCREEN_12V_ENABLE, HIGH); // Enable 12V power for SH1107 display delay(250); +#else + digitalWrite(SCREEN_12V_ENABLE, LOW); #endif Wire.begin(); // delay(1000); // wait for display to initialize. otherwise it doesn't come up on boot. diff --git a/variants/muzi_base/muzi_baseBoard.h b/variants/muzi_base/MuziBaseBoard.h similarity index 91% rename from variants/muzi_base/muzi_baseBoard.h rename to variants/muzi_base/MuziBaseBoard.h index e5412b6a..a5a4abbe 100644 --- a/variants/muzi_base/muzi_baseBoard.h +++ b/variants/muzi_base/MuziBaseBoard.h @@ -15,14 +15,14 @@ #define MUZI_BASE_MFR_NAME "Muzi Base Duo" #endif -class muzi_baseBoard : public NRF52BoardDCDC { +class MuziBaseBoard : public NRF52BoardDCDC { protected: #ifdef NRF52_POWER_MANAGEMENT void initiateShutdown(uint8_t reason) override; #endif public: - muzi_baseBoard() : NRF52Board(MUZI_BASE_OTA_NAME) {} + MuziBaseBoard() : NRF52Board(MUZI_BASE_OTA_NAME) {} void begin(); #define BATTERY_SAMPLES 8 diff --git a/variants/muzi_base/platformio.ini b/variants/muzi_base/platformio.ini index eb35d569..46a0ae4d 100644 --- a/variants/muzi_base/platformio.ini +++ b/variants/muzi_base/platformio.ini @@ -17,7 +17,7 @@ build_flags = ${nrf52_base.build_flags} -I lib/nrf52/s140_nrf52_6.1.1_API/include/nrf52 -I variants/muzi_base -I src/helpers/ui - -D muzi_base + -D MUZI_BASE -D NRF52_POWER_MANAGEMENT -D PIN_USER_BTN=PIN_BUTTON1 -D USER_BTN_PRESSED=LOW @@ -106,7 +106,7 @@ board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld board_upload.maximum_size = 708608 build_flags = ${muzi_base_duo.build_flags} -I examples/companion_radio/ui-new - -D MAX_CONTACTS=500 ;can increase number of contacts since we have a ton of extra flash. + -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 @@ -125,7 +125,7 @@ board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld board_upload.maximum_size = 708608 build_flags = ${muzi_base_duo.build_flags} -I examples/companion_radio/ui-new - -D MAX_CONTACTS=500 ;can increase number of contacts since we have a ton of extra flash. + -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D BLE_PIN_CODE=123456 -D BLE_TX_POWER=0 @@ -150,7 +150,7 @@ extends = muzi_base_duo board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld board_upload.maximum_size = 708608 build_flags = ${muzi_base_duo.build_flags} - -D muzi_base_superIO + -D MUZI_BASE_SUPERIO -D UI_HAS_JOYSTICK=1 -D OFFLINE_QUEUE_SIZE=256 -D DISPLAY_CLASS=SH1107Display @@ -174,12 +174,12 @@ lib_deps = ${muzi_base_duo.lib_deps} debug_tool = jlink upload_protocol = nrfutil -[env:muzi_base_duo_companion_radio_ble_superIO] +[env:muzi_base_duo_superIO_companion_radio_ble] extends = muzi_base_duo_superIO board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld board_upload.maximum_size = 708608 build_flags = ${muzi_base_duo_superIO.build_flags} - -D MAX_CONTACTS=500 ; can increase number of contacts since we have a ton of extra flash. + -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -I examples/companion_radio/ui-new -D BLE_PIN_CODE=123456 @@ -235,7 +235,7 @@ board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld board_upload.maximum_size = 708608 build_flags = ${muzi_base_uno.build_flags} -I examples/companion_radio/ui-new - -D MAX_CONTACTS=500 ;can increase number of contacts since we have a ton of extra flash. + -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 @@ -254,7 +254,7 @@ board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld board_upload.maximum_size = 708608 build_flags = ${muzi_base_uno.build_flags} -I examples/companion_radio/ui-new - -D MAX_CONTACTS=500 ;can increase number of contacts since we have a ton of extra flash. + -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D BLE_PIN_CODE=123456 -D BLE_TX_POWER=0 @@ -279,7 +279,7 @@ extends = muzi_base_uno board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld board_upload.maximum_size = 708608 build_flags = ${muzi_base_uno.build_flags} - -D muzi_base_superIO + -D MUZI_BASE_SUPERIO -D UI_HAS_JOYSTICK=1 -D OFFLINE_QUEUE_SIZE=256 -D DISPLAY_CLASS=SH1107Display @@ -303,12 +303,12 @@ lib_deps = ${muzi_base_uno.lib_deps} debug_tool = jlink upload_protocol = nrfutil -[env:muzi_base_uno_companion_radio_ble_superIO] +[env:muzi_base_uno_superIO_companion_radio_ble] extends = muzi_base_uno_superIO board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld board_upload.maximum_size = 708608 build_flags = ${muzi_base_uno_superIO.build_flags} - -D MAX_CONTACTS=500 ; can increase number of contacts since we have a ton of extra flash. + -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -I examples/companion_radio/ui-new -D BLE_PIN_CODE=123456 diff --git a/variants/muzi_base/target.cpp b/variants/muzi_base/target.cpp index 2af0c710..5bd846c9 100644 --- a/variants/muzi_base/target.cpp +++ b/variants/muzi_base/target.cpp @@ -3,7 +3,7 @@ #include "target.h" #include "variant.h" -muzi_baseBoard board; +MuziBaseBoard board; RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, SPI); diff --git a/variants/muzi_base/target.h b/variants/muzi_base/target.h index cbcfff14..45cd595f 100644 --- a/variants/muzi_base/target.h +++ b/variants/muzi_base/target.h @@ -3,7 +3,7 @@ #define RADIOLIB_STATIC_ONLY 1 #include <RadioLib.h> #include <helpers/radiolib/RadioLibWrappers.h> -#include "muzi_baseBoard.h" +#include "MuziBaseBoard.h" #if defined(USE_LR1121) #include <helpers/radiolib/CustomLR1121Wrapper.h> #elif defined(USE_SX1262) @@ -19,7 +19,7 @@ #include <helpers/ui/MomentaryButton.h> -#ifdef muzi_base_superIO +#ifdef MUZI_BASE_SUPERIO #include <helpers/ui/SH1107Display.h> extern DISPLAY_CLASS display; extern MomentaryButton user_btn; @@ -32,7 +32,7 @@ extern MomentaryButton user_btn; #endif -extern muzi_baseBoard board; +extern MuziBaseBoard board; extern WRAPPER_CLASS radio_driver; extern AutoDiscoverRTCClock rtc_clock; diff --git a/variants/muzi_base/variant.cpp b/variants/muzi_base/variant.cpp index b179af8a..cbde3355 100644 --- a/variants/muzi_base/variant.cpp +++ b/variants/muzi_base/variant.cpp @@ -60,31 +60,3 @@ const uint32_t g_ADigitalPinMap[PINS_COUNT + 1] = 46, 47, }; - -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(PIN_VBAT_READ, INPUT); - pinMode(PIN_BATTERY_CHARGING, INPUT); - pinMode(PIN_CHARGER_FAULT, INPUT); - pinMode(PIN_BUTTON1, INPUT); - pinMode(PIN_BUTTON2, INPUT); - pinMode(PIN_BUTTON3, INPUT); - pinMode(PIN_BUTTON4, INPUT); - pinMode(PIN_BUTTON5, INPUT); - pinMode(PIN_BUTTON6, INPUT); - pinMode(LED_PIN, OUTPUT); - pinMode(LED_BLUE, OUTPUT); - digitalWrite(LED_PIN, LOW); - digitalWrite(LED_BLUE, LOW); - pinMode(BUZZER_PIN, OUTPUT); - digitalWrite(BUZZER_PIN, LOW); // turn off buzzer at start. don't leave it high. - // gps power is driven by the sensor manager (mode switch). off to start. - pinMode(PIN_GPS_EN, OUTPUT); - digitalWrite(PIN_GPS_EN, LOW); - - pinMode(SCREEN_12V_ENABLE, OUTPUT); - digitalWrite(SCREEN_12V_ENABLE, LOW); // disable 12V power for SH1107 display for now. -} From 8485a51c18ef774bae1e75bb123978192a4d04fe Mon Sep 17 00:00:00 2001 From: TJ Downes <273720+tjdownes@users.noreply.github.com> Date: Sun, 20 Sep 2026 03:46:25 -0700 Subject: [PATCH 241/381] Use the default BLE TX power on Muzi Base Drop BLE_TX_POWER=0 from the companion envs so they use the default of 4 dBm, like most other variants. The lower power was carried over from the original Base Duo PR and real-world range is better at the default. --- variants/muzi_base/platformio.ini | 4 ---- 1 file changed, 4 deletions(-) diff --git a/variants/muzi_base/platformio.ini b/variants/muzi_base/platformio.ini index 46a0ae4d..72a3ecac 100644 --- a/variants/muzi_base/platformio.ini +++ b/variants/muzi_base/platformio.ini @@ -128,7 +128,6 @@ build_flags = ${muzi_base_duo.build_flags} -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D BLE_PIN_CODE=123456 - -D BLE_TX_POWER=0 -D QSPIFLASH=1 ; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 @@ -183,7 +182,6 @@ build_flags = ${muzi_base_duo_superIO.build_flags} -D MAX_GROUP_CHANNELS=40 -I examples/companion_radio/ui-new -D BLE_PIN_CODE=123456 - -D BLE_TX_POWER=0 -D QSPIFLASH=1 ; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 @@ -257,7 +255,6 @@ build_flags = ${muzi_base_uno.build_flags} -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D BLE_PIN_CODE=123456 - -D BLE_TX_POWER=0 -D QSPIFLASH=1 ; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 @@ -312,7 +309,6 @@ build_flags = ${muzi_base_uno_superIO.build_flags} -D MAX_GROUP_CHANNELS=40 -I examples/companion_radio/ui-new -D BLE_PIN_CODE=123456 - -D BLE_TX_POWER=0 -D QSPIFLASH=1 ; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 From 7fe4e78dc1594106e6203a627b85c7a1cf715798 Mon Sep 17 00:00:00 2001 From: Blake Latchford <github.demote149@passmail.com> Date: Sun, 20 Sep 2026 15:16:33 -0400 Subject: [PATCH 242/381] Add missing include, and revert removal of lota --- src/helpers/TxtDataHelpers.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/helpers/TxtDataHelpers.cpp b/src/helpers/TxtDataHelpers.cpp index f2621c0d..4358c8b8 100644 --- a/src/helpers/TxtDataHelpers.cpp +++ b/src/helpers/TxtDataHelpers.cpp @@ -28,6 +28,10 @@ bool StrHelper::isBlank(const char* str) { #include <Arduino.h> #include <stdio.h> +#if __has_include(<api/itoa.h>) +// https://github.com/stm32duino/Arduino_Core_STM32/issues/3084 +#include <api/itoa.h> +#endif union int32_Float_t { @@ -103,7 +107,9 @@ static void _ftoa(float f, char *p, int *status) *p++ = '0'; else { - p += snprintf(p, 11, "%ld", (long)int_part); + ltoa(int_part, p, 10); + while (*p) + p++; } *p++ = '.'; if (frac_part == 0) From ea2d2f36ce24eba14603de67158d6a0b30256455 Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Sat, 29 Aug 2026 17:57:06 -0400 Subject: [PATCH 243/381] m4: inital port --- boards/thinknode_m4.json | 72 ++++++++++++ variants/thinknode_m4/ThinkNodeM4Board.cpp | 46 ++++++++ variants/thinknode_m4/ThinkNodeM4Board.h | 61 ++++++++++ variants/thinknode_m4/platformio.ini | 130 +++++++++++++++++++++ variants/thinknode_m4/target.cpp | 84 +++++++++++++ variants/thinknode_m4/target.h | 26 +++++ variants/thinknode_m4/variant.cpp | 94 +++++++++++++++ variants/thinknode_m4/variant.h | 106 +++++++++++++++++ 8 files changed, 619 insertions(+) create mode 100644 boards/thinknode_m4.json create mode 100644 variants/thinknode_m4/ThinkNodeM4Board.cpp create mode 100644 variants/thinknode_m4/ThinkNodeM4Board.h create mode 100644 variants/thinknode_m4/platformio.ini create mode 100644 variants/thinknode_m4/target.cpp create mode 100644 variants/thinknode_m4/target.h create mode 100644 variants/thinknode_m4/variant.cpp create mode 100644 variants/thinknode_m4/variant.h diff --git a/boards/thinknode_m4.json b/boards/thinknode_m4.json new file mode 100644 index 00000000..babc3e52 --- /dev/null +++ b/boards/thinknode_m4.json @@ -0,0 +1,72 @@ +{ + "build": { + "arduino": { + "ldscript": "nrf52840_s140_v6.ld" + }, + "core": "nRF5", + "cpu": "cortex-m4", + "extra_flags": "-DNRF52840_XXAA", + "f_cpu": "64000000L", + "hwids": [ + [ + "0x239A", + "0x4405" + ], + [ + "0x239A", + "0x0029" + ], + [ + "0x239A", + "0x002A" + ] + ], + "usb_product": "elecrow_thinknode_m4", + "mcu": "nrf52840", + "variant": "ELECROW-ThinkNode-M4", + "bsp": { + "name": "adafruit" + }, + "softdevice": { + "sd_flags": "-DS140", + "sd_name": "s140", + "sd_version": "6.1.1", + "sd_fwid": "0x00B6" + }, + "bootloader": { + "settings_addr": "0xFF000" + } + }, + "connectivity": [ + "bluetooth" + ], + "debug": { + "jlink_device": "nRF52840_xxAA", + "onboard_tools": [ + "jlink" + ], + "svd_path": "nrf52840.svd", + "openocd_target": "nrf52.cfg" + }, + "frameworks": [ + "arduino" + ], + "name": "elecrow nrf", + "upload": { + "maximum_ram_size": 235520, + "maximum_size": 815104, + "speed": 115200, + "use_1200bps_touch": true, + "require_upload_port": true, + "wait_for_upload_port": true, + "protocol": "nrfutil", + "protocols": [ + "jlink", + "nrfjprog", + "nrfutil", + "stlink" + ] + }, + "url": "https://github.com/Elecrow-RD", + "vendor": "ELECROW" +} \ No newline at end of file diff --git a/variants/thinknode_m4/ThinkNodeM4Board.cpp b/variants/thinknode_m4/ThinkNodeM4Board.cpp new file mode 100644 index 00000000..4a144a3a --- /dev/null +++ b/variants/thinknode_m4/ThinkNodeM4Board.cpp @@ -0,0 +1,46 @@ +#include <Arduino.h> +#include "ThinkNodeM4Board.h" +#include <Wire.h> + +#include <bluefruit.h> + +void ThinkNodeM4Board::begin() { + NRF52Board::begin(); + btn_prev_state = HIGH; + + Wire.begin(); + battery_serial->begin(4800); + + delay(10); // give sx1262 some time to power up +} + +uint16_t ThinkNodeM4Board::getBattMilliVolts() { + int tentatives = 10; + uint8_t data[5]; + uint8_t b; + + if (battery_serial->available() < 10) + return bat_level_mv; + + // discard old data + while (battery_serial->available() > 10) + battery_serial->read(); + + // synchronize + while((b = battery_serial->read()) != 0xFE) { + if (tentatives-- == 0) { + MESH_DEBUG_PRINTLN("Could not find battery frame start %x", b); + return bat_level_mv; + } + } + battery_serial->readBytes(data, 5); + + if (data[4] != 0xFD) { + MESH_DEBUG_PRINTLN("Invalid battery frame end %x", data[4]); + return bat_level_mv; + } + bat_level_percent = data[0]; + //MESH_DEBUG_PRINTLN("Battery level %d\%", bat_level_percent); + bat_level_mv = 2 * (data[1]*1000. + data[2]*10. + data[3]/10.); + return bat_level_mv; +} diff --git a/variants/thinknode_m4/ThinkNodeM4Board.h b/variants/thinknode_m4/ThinkNodeM4Board.h new file mode 100644 index 00000000..ba7d95be --- /dev/null +++ b/variants/thinknode_m4/ThinkNodeM4Board.h @@ -0,0 +1,61 @@ +#pragma once + +#include <Arduino.h> +#include <MeshCore.h> +#include <helpers/NRF52Board.h> + +class ThinkNodeM4Board : public NRF52BoardDCDC { +protected: +#if NRF52_POWER_MANAGEMENT + void initiateShutdown(uint8_t reason) override; +#endif + uint8_t btn_prev_state; + HardwareSerial * battery_serial; + uint16_t bat_level_mv = 0; + uint8_t bat_level_percent =0; + +public: + ThinkNodeM4Board() : NRF52Board("THINKNODE_M3_OTA"), battery_serial(&Serial2) {} + void begin(); + uint16_t getBattMilliVolts() override; + +#ifdef P_LORA_TX_LED + void onBeforeTransmit() override { + digitalWrite(P_LORA_TX_LED, LED_STATE_ON); // turn TX LED on + } + void onAfterTransmit() override { + digitalWrite(P_LORA_TX_LED, !LED_STATE_ON); // turn TX LED off + } +#endif + + const char* getManufacturerName() const override { + return "Elecrow ThinkNode M4"; + } + + int buttonStateChanged() { + #ifdef BUTTON_PIN + uint8_t v = digitalRead(BUTTON_PIN); + if (v != btn_prev_state) { + btn_prev_state = v; + return (v == USER_BTN_PRESSED) ? 1 : -1; + } + #endif + return 0; + } + + void shutdownPeripherals() override { + // shutdown common peripherals + NRF52Board::shutdownPeripherals(); + + digitalWrite(LED_BAT1, LOW); + digitalWrite(LED_BAT2, LOW); + digitalWrite(LED_BAT3, LOW); + digitalWrite(LED_BAT4, LOW); + digitalWrite(LED_STATUS, LOW); + digitalWrite(LED_PIN, LOW); + + digitalWrite(PIN_PWR_EN, LOW); + digitalWrite(I2C_POWER, !I2C_POWER_ACTIVE); + digitalWrite(PIN_GPS_POWER, !GPS_POWER_ACTIVE); + } +}; diff --git a/variants/thinknode_m4/platformio.ini b/variants/thinknode_m4/platformio.ini new file mode 100644 index 00000000..ab8417e9 --- /dev/null +++ b/variants/thinknode_m4/platformio.ini @@ -0,0 +1,130 @@ +[ThinkNode_M4] +extends = nrf52_base +board = thinknode_m4 +board_build.ldscript = boards/nrf52840_s140_v6.ld +build_flags = ${nrf52_base.build_flags} + -I src/helpers/nrf52 + -I lib/nrf52/s140_nrf52_6.1.1_API/include + -I lib/nrf52/s140_nrf52_6.1.1_API/include/nrf52 + -I variants/thinknode_m4 + -I src/helpers/ui + -D THINKNODE_M4 + -D PIN_USER_BTN=12 + -D PIN_STATUS_LED=LED_STATUS + -D RADIO_CLASS=CustomLR1110 + -D WRAPPER_CLASS=CustomLR1110Wrapper + -D LORA_TX_POWER=22 + -D RF_SWITCH_TABLE + -D RX_BOOSTED_GAIN=true + -D P_LORA_BUSY=26 + -D P_LORA_SCLK=6 + -D P_LORA_NSS=27 + -D P_LORA_DIO_1=12 + -D P_LORA_MISO=8 + -D P_LORA_MOSI=7 + -D P_LORA_RESET=40 + -D P_LORA_TX_LED=LED_TX + -D LR11X0_DIO_AS_RF_SWITCH=true + -D LR11X0_DIO3_TCXO_VOLTAGE=1.6 + -D ENV_INCLUDE_GPS=1 +; -D MESH_DEBUG=1 +; -D GPS_NMEA_DEBUG=1 +build_src_filter = ${nrf52_base.build_src_filter} + +<helpers/*.cpp> + +<../variants/thinknode_m4> + +<helpers/sensors> +debug_tool = stlink +upload_protocol = nrfutil +lib_deps= ${nrf52_base.lib_deps} + +[env:ThinkNode_M4_repeater] +extends = ThinkNode_M4 +build_flags = ${ThinkNode_M4.build_flags} + -I examples/companion_radio/ui-orig + -D ADVERT_NAME='"ThinkNode_M4 Repeater"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=50 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${ThinkNode_M4.build_src_filter} + +<../examples/simple_repeater> +lib_deps = ${ThinkNode_M4.lib_deps} + stevemarple/MicroNMEA @ ^2.0.6 + +[env:ThinkNode_M4_room_server] +extends = ThinkNode_M4 +build_flags = ${ThinkNode_M4.build_flags} + -I examples/companion_radio/ui-orig + -D ADVERT_NAME='"ThinkNode_M4 Room"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D ROOM_PASSWORD='"hello"' +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 + -D RF_SWITCH_TABLE +build_src_filter = ${ThinkNode_M4.build_src_filter} + +<../examples/simple_room_server> +lib_deps = ${ThinkNode_M4.lib_deps} + stevemarple/MicroNMEA @ ^2.0.6 + +[env:ThinkNode_M4_companion_radio_usb] +extends = ThinkNode_M4 +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 708608 +build_flags = ${ThinkNode_M4.build_flags} + -I examples/companion_radio/ui-orig + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 + -D OFFLINE_QUEUE_SIZE=256 + -D DISPLAY_CLASS=NullDisplayDriver + -D PIN_BUZZER=23 + -D PIN_BUZZER_EN=36 + -D ENABLE_USB_INTERFACE +build_src_filter = ${ThinkNode_M4.build_src_filter} + +<helpers/ui/buzzer.cpp> + +<helpers/ui/NullDisplayDriver.cpp> + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-orig/*.cpp> +lib_deps = ${ThinkNode_M4.lib_deps} + densaugeo/base64 @ ~1.4.0 + stevemarple/MicroNMEA @ ^2.0.6 + end2endzone/NonBlockingRTTTL@^1.3.0 + +[env:ThinkNode_M4_companion_radio_ble] +extends = ThinkNode_M4 +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 708608 +build_flags = ${ThinkNode_M4.build_flags} + -I examples/companion_radio/ui-orig + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D BLE_PIN_CODE=123456 + -D BLE_TX_POWER=0 +; -D BLE_DEBUG_LOGGING=1 +; -D MESH_PACKET_LOGGING=1 + -D OFFLINE_QUEUE_SIZE=256 + -D DISPLAY_CLASS=NullDisplayDriver + -D PIN_BUZZER=23 + -D PIN_BUZZER_EN=36 +build_src_filter = ${ThinkNode_M4.build_src_filter} + +<helpers/nrf52/SerialBLEInterface.cpp> + +<helpers/ui/buzzer.cpp> + +<helpers/ui/NullDisplayDriver.cpp> + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-orig/*.cpp> +lib_deps = ${ThinkNode_M4.lib_deps} + densaugeo/base64 @ ~1.4.0 + stevemarple/MicroNMEA @ ^2.0.6 + end2endzone/NonBlockingRTTTL@^1.3.0 + +[env:ThinkNode_M4_kiss_modem] +extends = ThinkNode_M4 +build_src_filter = ${ThinkNode_M4.build_src_filter} + +<../examples/kiss_modem/> +lib_deps = ${ThinkNode_M4.lib_deps} + stevemarple/MicroNMEA @ ^2.0.6 diff --git a/variants/thinknode_m4/target.cpp b/variants/thinknode_m4/target.cpp new file mode 100644 index 00000000..7da3f400 --- /dev/null +++ b/variants/thinknode_m4/target.cpp @@ -0,0 +1,84 @@ +#include <Arduino.h> +#include "target.h" +#include <helpers/sensors/MicroNMEALocationProvider.h> + +ThinkNodeM4Board board; + +RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, SPI); + +WRAPPER_CLASS radio_driver(radio, board); + +VolatileRTCClock fallback_clock; +AutoDiscoverRTCClock rtc_clock(fallback_clock); +#ifdef ENV_INCLUDE_GPS +MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); +#else +EnvironmentSensorManager sensors = EnvironmentSensorManager(); +#endif + +#ifdef DISPLAY_CLASS + NullDisplayDriver display; +#endif + +#ifndef LORA_CR + #define LORA_CR 5 +#endif + +#ifdef RF_SWITCH_TABLE +static const uint32_t rfswitch_dios[Module::RFSWITCH_MAX_PINS] = { + RADIOLIB_LR11X0_DIO5, + RADIOLIB_LR11X0_DIO6, + RADIOLIB_NC, + RADIOLIB_NC, + RADIOLIB_NC +}; + +static const Module::RfSwitchMode_t rfswitch_table[] = { + // mode DIO5 DIO6 + { LR11x0::MODE_STBY, {LOW , LOW }}, + { LR11x0::MODE_RX, {HIGH, LOW }}, + { LR11x0::MODE_TX, {HIGH, HIGH }}, + { LR11x0::MODE_TX_HP, {LOW , HIGH }}, + { LR11x0::MODE_TX_HF, {LOW , LOW }}, + { LR11x0::MODE_GNSS, {LOW , LOW }}, + { LR11x0::MODE_WIFI, {LOW , LOW }}, + END_OF_MODE_TABLE, +}; +#endif + +bool radio_init() { + rtc_clock.begin(Wire); + +#ifdef LR11X0_DIO3_TCXO_VOLTAGE + float tcxo = LR11X0_DIO3_TCXO_VOLTAGE; +#else + float tcxo = 1.6f; +#endif + + SPI.setPins(P_LORA_MISO, P_LORA_SCLK, P_LORA_MOSI); + SPI.begin(); + int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, RADIOLIB_LR11X0_LORA_SYNC_WORD_PRIVATE, LORA_TX_POWER, 16, tcxo); + if (status != RADIOLIB_ERR_NONE) { + Serial.print("ERROR: radio init failed: "); + Serial.println(status); + return false; // fail + } + + radio.setCRC(2); + radio.explicitHeader(); + +#ifdef RF_SWITCH_TABLE + radio.setRfSwitchTable(rfswitch_dios, rfswitch_table); +#endif +#ifdef RX_BOOSTED_GAIN + radio.setRxBoostedGainMode(RX_BOOSTED_GAIN); +#endif + + return true; // success +} + +mesh::LocalIdentity radio_new_identity() { + RadioNoiseListener rng(radio); + return mesh::LocalIdentity(&rng); // create new random identity +} \ No newline at end of file diff --git a/variants/thinknode_m4/target.h b/variants/thinknode_m4/target.h new file mode 100644 index 00000000..1135f5e8 --- /dev/null +++ b/variants/thinknode_m4/target.h @@ -0,0 +1,26 @@ +#pragma once + +#define RADIOLIB_STATIC_ONLY 1 +#include <RadioLib.h> +#include <helpers/radiolib/RadioLibWrappers.h> +#include "ThinkNodeM4Board.h" +#include <helpers/radiolib/CustomLR1110Wrapper.h> +#include <helpers/ArduinoHelpers.h> +#include <helpers/sensors/EnvironmentSensorManager.h> +#include <helpers/sensors/LocationProvider.h> +#include <helpers/AutoDiscoverRTCClock.h> +#ifdef DISPLAY_CLASS + #include "NullDisplayDriver.h" +#endif + +#ifdef DISPLAY_CLASS + extern NullDisplayDriver display; +#endif + +extern ThinkNodeM4Board board; +extern WRAPPER_CLASS radio_driver; +extern AutoDiscoverRTCClock rtc_clock; +extern EnvironmentSensorManager sensors; + +bool radio_init(); +mesh::LocalIdentity radio_new_identity(); diff --git a/variants/thinknode_m4/variant.cpp b/variants/thinknode_m4/variant.cpp new file mode 100644 index 00000000..7bf17bb8 --- /dev/null +++ b/variants/thinknode_m4/variant.cpp @@ -0,0 +1,94 @@ +/* + * 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[] = +{ + 0, // P0.00 + 1, // P0.01 + 2, // P0.02 + 3, // P0.03 + 4, // P0.04 + 5, // P0.05 + 6, // P0.06 + 7, // P0.07 + 8, // P0.08 + 9, // P0.09 + 10, // P0.10 + 11, // P0.11 + 12, // P0.12 + 13, // P0.13 + 14, // P0.14 + 15, // P0.15 + 16, // P0.16 + 17, // P0.17 + 18, // P0.18 + 19, // P0.19 + 20, // P0.20 + 21, // P0.21 + 22, // P0.22 + 23, // P0.23 + 24, // P0.24 + 25, // P0.25 + 26, // P0.26 + 27, // P0.27 + 28, // P0.28 + 29, // P0.29 + 30, // P0.30 + 31, // P0.31 + 32, // P1.00 + 33, // P1.01 + 34, // P1.02 + 35, // P1.03 + 36, // P1.04 + 37, // P1.05 + 38, // P1.06 + 39, // P1.07 + 40, // P1.08 + 41, // P1.09 + 42, // P1.10 + 43, // P1.11 + 44, // P1.12 + 45, // P1.13 + 46, // P1.14 + 47, // P1.15 +}; + +void initVariant() +{ +/* TODO */ + pinMode(PIN_PWR_EN, OUTPUT); + pinMode(I2C_POWER, OUTPUT); + + digitalWrite(PIN_PWR_EN, HIGH); + digitalWrite(I2C_POWER, I2C_POWER_ACTIVE); + + pinMode(LED_STATUS, OUTPUT); + pinMode(LED_PIN, OUTPUT); + pinMode(LED_BAT1, OUTPUT); + pinMode(LED_BAT2, OUTPUT); + pinMode(LED_BAT3, OUTPUT); + pinMode(LED_BAT4, OUTPUT); + + digitalWrite(LED_BAT1, LOW); + digitalWrite(LED_BAT2, LOW); + digitalWrite(LED_BAT3, LOW); + digitalWrite(LED_BAT4, LOW); + digitalWrite(LED_STATUS, LOW); + digitalWrite(LED_PIN, LOW); + + pinMode(BUTTON_PIN, INPUT_PULLUP); + + pinMode(PIN_GPS_POWER, OUTPUT); + pinMode(PIN_GPS_EN, OUTPUT); + + // Power on gps but in standby + digitalWrite(PIN_GPS_EN, !GPS_EN_ACTIVE); + digitalWrite(PIN_GPS_POWER, GPS_POWER_ACTIVE); +} diff --git a/variants/thinknode_m4/variant.h b/variants/thinknode_m4/variant.h new file mode 100644 index 00000000..cc483184 --- /dev/null +++ b/variants/thinknode_m4/variant.h @@ -0,0 +1,106 @@ +/* + * 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 + +//////////////////////////////////////////////////////////////////////////////// +// Number of pins + +#define PINS_COUNT (48) +#define NUM_DIGITAL_PINS (48) +#define NUM_ANALOG_INPUTS (1) +#define NUM_ANALOG_OUTPUTS (0) + +//////////////////////////////////////////////////////////////////////////////// +// Power + +#define NRF_APM // detect usb power + +#define EXT_CHRG_DETECT (38) +// Power to radio +#define PIN_PWR_EN (11) + +// I2C bus power +#define I2C_POWER (32) +#define I2C_POWER_ACTIVE LOW + +#define PIN_BAT_RX (5) +#define PIN_BAT_TX (30) + +//////////////////////////////////////////////////////////////////////////////// +// UART pin definition + +#define PIN_SERIAL1_RX PIN_GPS_TX +#define PIN_SERIAL1_TX PIN_GPS_RX + +#define PIN_SERIAL2_RX PIN_BAT_TX +#define PIN_SERIAL2_TX PIN_BAT_RX + +//////////////////////////////////////////////////////////////////////////////// +// I2C pin definition + +#define HAS_WIRE (1) +#define WIRE_INTERFACES_COUNT (1) + +#define PIN_WIRE_SDA (23) +#define PIN_WIRE_SCL (25) +#define I2C_NO_RESCAN + +//////////////////////////////////////////////////////////////////////////////// +// SPI pin definition + +#define SPI_INTERFACES_COUNT (1) + +#define PIN_SPI_MISO (8) +#define PIN_SPI_MOSI (7) +#define PIN_SPI_SCK (6) +#define PIN_SPI_NSS (27) + +//////////////////////////////////////////////////////////////////////////////// +// Builtin LEDs + +#define LED_BLUE (-1) // disable blue led +#define LED_STATUS (13) // blue +#define LED_PIN (41) // red +#define LED_TX LED_PIN +#define LED_BUILTIN LED_BLUE +#define LED_STATE_ON HIGH + +#define LED_BAT1 (15) +#define LED_BAT2 (17) +#define LED_BAT3 (34) +#define LED_BAT4 (36) + +//////////////////////////////////////////////////////////////////////////////// +// Builtin buttons + +#define PIN_BUTTON1 (4) +#define BUTTON_PIN PIN_BUTTON1 +#define USER_BTN_PRESSED HIGH + +//////////////////////////////////////////////////////////////////////////////// +// GPS + +#define HAS_GPS 1 +#define GPS_BAUDRATE 9600 +#define PIN_GPS_RX (44) +#define PIN_GPS_TX (46) + +#define PIN_GPS_POWER (14) +#define GPS_POWER_ACTIVE LOW +#define PIN_GPS_EN (43) +#define GPS_EN_ACTIVE LOW +#define PIN_GPS_RESET (3) +#define GPS_RESET_ACTIVE HIGH From 05638d36b1227f0aacf3c6c5431baee776ebeeb3 Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Sun, 20 Sep 2026 16:13:15 -0400 Subject: [PATCH 244/381] M4: Handle poweroff --- variants/thinknode_m4/ThinkNodeM4Board.h | 14 ++++++++++++++ variants/thinknode_m4/platformio.ini | 2 +- variants/thinknode_m4/variant.h | 2 +- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/variants/thinknode_m4/ThinkNodeM4Board.h b/variants/thinknode_m4/ThinkNodeM4Board.h index ba7d95be..c05de911 100644 --- a/variants/thinknode_m4/ThinkNodeM4Board.h +++ b/variants/thinknode_m4/ThinkNodeM4Board.h @@ -47,6 +47,16 @@ public: // shutdown common peripherals NRF52Board::shutdownPeripherals(); + #ifdef LED_STATUS + digitalWrite(LED_STATUS, HIGH); + #endif + #ifdef BUTTON_PIN + while(!digitalRead(BUTTON_PIN)); + #endif + #ifdef LED_STATUS + digitalWrite(LED_STATUS, LOW); + #endif + digitalWrite(LED_BAT1, LOW); digitalWrite(LED_BAT2, LOW); digitalWrite(LED_BAT3, LOW); @@ -57,5 +67,9 @@ public: digitalWrite(PIN_PWR_EN, LOW); digitalWrite(I2C_POWER, !I2C_POWER_ACTIVE); digitalWrite(PIN_GPS_POWER, !GPS_POWER_ACTIVE); + + #ifdef BUTTON_PIN + nrf_gpio_cfg_sense_input(BUTTON_PIN, NRF_GPIO_PIN_NOPULL, NRF_GPIO_PIN_SENSE_LOW); + #endif } }; diff --git a/variants/thinknode_m4/platformio.ini b/variants/thinknode_m4/platformio.ini index ab8417e9..06762f88 100644 --- a/variants/thinknode_m4/platformio.ini +++ b/variants/thinknode_m4/platformio.ini @@ -9,7 +9,7 @@ build_flags = ${nrf52_base.build_flags} -I variants/thinknode_m4 -I src/helpers/ui -D THINKNODE_M4 - -D PIN_USER_BTN=12 + -D PIN_USER_BTN=4 -D PIN_STATUS_LED=LED_STATUS -D RADIO_CLASS=CustomLR1110 -D WRAPPER_CLASS=CustomLR1110Wrapper diff --git a/variants/thinknode_m4/variant.h b/variants/thinknode_m4/variant.h index cc483184..6e355d7f 100644 --- a/variants/thinknode_m4/variant.h +++ b/variants/thinknode_m4/variant.h @@ -88,7 +88,7 @@ #define PIN_BUTTON1 (4) #define BUTTON_PIN PIN_BUTTON1 -#define USER_BTN_PRESSED HIGH +#define USER_BTN_PRESSED LOW //////////////////////////////////////////////////////////////////////////////// // GPS From 10e94e605d192ec7914b586c4099ee761736ab5b Mon Sep 17 00:00:00 2001 From: Ev Lbibass <27320050+lbibass@users.noreply.github.com> Date: Sun, 20 Sep 2026 20:38:05 -0400 Subject: [PATCH 245/381] update structure of LR1121 to match LR1110 files. Implement DC-DC on LR1121 radio. saves about 30% power consumption at idle. --- src/helpers/radiolib/CustomLR1121.h | 74 ++++++++++++++++++++-- src/helpers/radiolib/CustomLR1121Wrapper.h | 3 + 2 files changed, 72 insertions(+), 5 deletions(-) diff --git a/src/helpers/radiolib/CustomLR1121.h b/src/helpers/radiolib/CustomLR1121.h index 873bfabc..67e3b52a 100644 --- a/src/helpers/radiolib/CustomLR1121.h +++ b/src/helpers/radiolib/CustomLR1121.h @@ -4,11 +4,25 @@ #include "MeshCore.h" class CustomLR1121 : public LR1121 { + uint32_t _preambleMillis = 66; + uint32_t _maxPayloadMillis = 3934; + uint32_t _activityAt = 0; + bool _headerSeen = false; bool _rx_boosted = false; public: CustomLR1121(Module *mod) : LR1121(mod) { } + int16_t begin(float freq = 434.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, + uint8_t syncWord = RADIOLIB_LR11X0_LORA_SYNC_WORD_PRIVATE, int8_t power = 10, + uint16_t preambleLength = 8, float tcxoVoltage = 1.6) { + int16_t state = LR1121::begin(freq, bw, sf, cr, syncWord, power, preambleLength, + tcxoVoltage); + // RadioLib begin() defaults to LDO; use the LR1121 DC/DC regulator. + if (state == RADIOLIB_ERR_NONE) state = setRegulatorDCDC(); + return state; + } + size_t getPacketLength(bool update) override { size_t len = LR1121::getPacketLength(update); if (len == 0 && getIrqStatus() & RADIOLIB_LR11X0_IRQ_HEADER_ERR) { @@ -31,11 +45,61 @@ class CustomLR1121 : public LR1121 { bool getRxBoostedGainMode() const { return _rx_boosted; } - bool isReceiving() { - uint16_t irq = getIrqStatus(); - bool detected = ((irq & RADIOLIB_LR11X0_IRQ_SYNC_WORD_HEADER_VALID) || (irq & RADIOLIB_LR11X0_IRQ_PREAMBLE_DETECTED)); - return detected; + int16_t startReceive() override { + // include the PREAMBLE_DETECTED irq bit in reported flags. + return LR1121::startReceive(RADIOLIB_LR11X0_RX_TIMEOUT_INF, RADIOLIB_IRQ_RX_DEFAULT_FLAGS | (1UL << RADIOLIB_IRQ_PREAMBLE_DETECTED), RADIOLIB_IRQ_RX_DEFAULT_MASK, 0); } - uint8_t getSpreadingFactor() const { return spreadingFactor; } + bool isReceiving() { + uint32_t irq = getIrqStatus(); + bool preamble = irq & RADIOLIB_LR11X0_IRQ_PREAMBLE_DETECTED; // bit 4 + bool header = irq & RADIOLIB_LR11X0_IRQ_SYNC_WORD_HEADER_VALID; // bit 5 + bool hdrErr = irq & RADIOLIB_LR11X0_IRQ_HEADER_ERR; // bit 6 + uint32_t now = millis(); + if (hdrErr) { + clearIrqState(RADIOLIB_LR11X0_IRQ_PREAMBLE_DETECTED | RADIOLIB_LR11X0_IRQ_SYNC_WORD_HEADER_VALID | RADIOLIB_LR11X0_IRQ_HEADER_ERR); + _activityAt = 0; + _headerSeen = false; + return false; + } + if (!header && _headerSeen) { + // something cleared the header flag, reset our state. + _activityAt = 0; _headerSeen = false; + return false; + } + if (header) { + if (!_headerSeen) { _headerSeen = true; _activityAt = now; }; + if (now - _activityAt > _maxPayloadMillis) { + MESH_DEBUG_PRINTLN("Clearing header IRQ after %ums", _maxPayloadMillis); + clearIrqState(RADIOLIB_LR11X0_IRQ_PREAMBLE_DETECTED | RADIOLIB_LR11X0_IRQ_SYNC_WORD_HEADER_VALID | RADIOLIB_LR11X0_IRQ_HEADER_ERR); + _activityAt = 0; _headerSeen = false; + return false; + } + return true; + } + if (preamble) { + if (_activityAt == 0) _activityAt = now; + if (now - _activityAt > _preambleMillis) { + clearIrqState(RADIOLIB_LR11X0_IRQ_PREAMBLE_DETECTED); + _activityAt = 0; + MESH_DEBUG_PRINTLN("Clearing preamble IRQ after %ums", _preambleMillis); + + return false; + } + return true; + } + _activityAt = 0; _headerSeen = false; + return false; + } + + void setPreambleMillis(uint32_t preambleMillis) { + _preambleMillis = preambleMillis; + MESH_DEBUG_PRINTLN("Set _preambleMillis=%u", _preambleMillis); + } + void setMaxPayloadMillis(uint32_t payloadMillis) { + _maxPayloadMillis = payloadMillis; + MESH_DEBUG_PRINTLN("Set _maxPayloadMillis=%u", _maxPayloadMillis); + } + + uint8_t getSpreadingFactor() const { return spreadingFactor; } }; \ No newline at end of file diff --git a/src/helpers/radiolib/CustomLR1121Wrapper.h b/src/helpers/radiolib/CustomLR1121Wrapper.h index 5361ee23..5a754cee 100644 --- a/src/helpers/radiolib/CustomLR1121Wrapper.h +++ b/src/helpers/radiolib/CustomLR1121Wrapper.h @@ -14,6 +14,9 @@ public: ((CustomLR1121 *)_radio)->setBandwidth(bw); ((CustomLR1121 *)_radio)->setCodingRate(cr); updatePreamble(sf); + PacketMillis pm = calcMaxPacketMillis(sf, bw, cr, preambleLengthForSF(sf)); + ((CustomLR1121 *)_radio)->setPreambleMillis(pm.preambleMillis); + ((CustomLR1121 *)_radio)->setMaxPayloadMillis(pm.payloadMillis); } void doResetAGC() override { lr11x0ResetAGC((LR11x0 *)_radio, ((CustomLR1121 *)_radio)->getFreqMHz(), getRxBoostedGainMode()); } From 7fe8287a329abc216a2c02fb973ef7514451f5e3 Mon Sep 17 00:00:00 2001 From: Wessel Nieboer <wessel@weebl.me> Date: Mon, 21 Sep 2026 15:55:44 +0200 Subject: [PATCH 246/381] Thinknode m4 - don't touch crystal and OTA name --- variants/thinknode_m4/ThinkNodeM4Board.h | 2 +- variants/thinknode_m4/variant.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/variants/thinknode_m4/ThinkNodeM4Board.h b/variants/thinknode_m4/ThinkNodeM4Board.h index c05de911..c2cae54b 100644 --- a/variants/thinknode_m4/ThinkNodeM4Board.h +++ b/variants/thinknode_m4/ThinkNodeM4Board.h @@ -15,7 +15,7 @@ protected: uint8_t bat_level_percent =0; public: - ThinkNodeM4Board() : NRF52Board("THINKNODE_M3_OTA"), battery_serial(&Serial2) {} + ThinkNodeM4Board() : NRF52Board("THINKNODE_M4_OTA"), battery_serial(&Serial2) {} void begin(); uint16_t getBattMilliVolts() override; diff --git a/variants/thinknode_m4/variant.cpp b/variants/thinknode_m4/variant.cpp index 7bf17bb8..fbdb08e2 100644 --- a/variants/thinknode_m4/variant.cpp +++ b/variants/thinknode_m4/variant.cpp @@ -10,8 +10,8 @@ const uint32_t g_ADigitalPinMap[] = { - 0, // P0.00 - 1, // P0.01 + 0xff, // P0.00 - LFXO (do not use) + 0xff, // P0.01 - LFXO (do not use) 2, // P0.02 3, // P0.03 4, // P0.04 From e1877c015b5b5f1d8a70118b353c890e3d5ca384 Mon Sep 17 00:00:00 2001 From: Blake Latchford <github.demote149@passmail.com> Date: Mon, 21 Sep 2026 12:26:36 -0400 Subject: [PATCH 247/381] Constrain `agc.reset.interval` and allow intervals > 255s --- docs/cli_commands.md | 2 +- examples/companion_radio/NodePrefs.h | 4 ++-- src/helpers/CommonCLI.h | 4 ++-- src/helpers/CommonRadioPrefs.cpp | 4 +++- src/helpers/CommonRadioPrefs.h | 4 ++-- 5 files changed, 10 insertions(+), 8 deletions(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index f4a43fad..9fde4d43 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -628,7 +628,7 @@ This document provides an overview of CLI commands that can be sent to MeshCore - `set agc.reset.interval <value>` **Parameters:** -- `value`: Interval in seconds rounded down to a multiple of 4 (17 becomes 16). 0 to disable. +- `value`: Interval in seconds, 0-1020, rounded down to a multiple of 4 (17 becomes 16). 0 to disable. **Default:** `0.0` diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index 4b169d73..46a3dbb7 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -106,8 +106,8 @@ private: void setTxPower(uint8_t dbm) override { _parent->tx_power_dbm = dbm; markDirty(); } float getRxDelay() const override { return _parent->rx_delay_base; } void setRxDelay(float d) override { _parent->rx_delay_base = d; markDirty(); } - uint8_t getAgcResetInt() const override { return _parent->agc_reset_interval * 4; } - void setAgcResetInt(uint8_t secs) override { _parent->agc_reset_interval = secs / 4; markDirty(); } + uint16_t getAgcResetInt() const override { return _parent->agc_reset_interval * 4; } + void setAgcResetInt(uint16_t secs) override { _parent->agc_reset_interval = secs / 4; markDirty(); } uint8_t getHashMode() const override { return _parent->path_hash_mode; } void setHashMode(uint8_t m) override { _parent->path_hash_mode = m; markDirty(); } uint8_t getMultiAcks() const override { return _parent->multi_acks; } diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 8591cdc1..2759b0c4 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -119,8 +119,8 @@ private: void setTxPower(uint8_t dbm) override { _parent->tx_power_dbm = dbm; markDirty(); } float getRxDelay() const override { return _parent->rx_delay_base; } void setRxDelay(float d) override { _parent->rx_delay_base = d; markDirty(); } - uint8_t getAgcResetInt() const override { return _parent->agc_reset_interval * 4; } - void setAgcResetInt(uint8_t secs) override { _parent->agc_reset_interval = secs / 4; markDirty(); } + uint16_t getAgcResetInt() const override { return _parent->agc_reset_interval * 4; } + void setAgcResetInt(uint16_t secs) override { _parent->agc_reset_interval = secs / 4; markDirty(); } uint8_t getHashMode() const override { return _parent->path_hash_mode; } void setHashMode(uint8_t m) override { _parent->path_hash_mode = m; markDirty(); } uint8_t getMultiAcks() const override { return _parent->multi_acks; } diff --git a/src/helpers/CommonRadioPrefs.cpp b/src/helpers/CommonRadioPrefs.cpp index 9d92cad9..41b17993 100644 --- a/src/helpers/CommonRadioPrefs.cpp +++ b/src/helpers/CommonRadioPrefs.cpp @@ -165,7 +165,9 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest return true; } if (memcmp(command, "set agc.reset.interval ", 23) == 0) { - setAgcResetInt(atoi(&command[23])); + int secs = atoi(&command[23]); + secs = constrain(secs, 0, 255 * 4); + setAgcResetInt((uint16_t) secs); sprintf(reply, "OK - interval rounded to %d", (uint32_t) getAgcResetInt()); return true; } diff --git a/src/helpers/CommonRadioPrefs.h b/src/helpers/CommonRadioPrefs.h index 96895bb2..0e83ca9d 100644 --- a/src/helpers/CommonRadioPrefs.h +++ b/src/helpers/CommonRadioPrefs.h @@ -41,8 +41,8 @@ public: virtual float getRxDelay() const = 0; virtual void setRxDelay(float d) = 0; - virtual uint8_t getAgcResetInt() const = 0; - virtual void setAgcResetInt(uint8_t secs) = 0; + virtual uint16_t getAgcResetInt() const = 0; + virtual void setAgcResetInt(uint16_t secs) = 0; virtual uint8_t getHashMode() const = 0; virtual void setHashMode(uint8_t m) = 0; From ba345d486cba4f460e904e4c4439b5b0a957eba2 Mon Sep 17 00:00:00 2001 From: Wolfram Keil <keil@keil.systems> Date: Thu, 27 Aug 2026 21:38:46 +0200 Subject: [PATCH 248/381] Add board loop hook for periodic work --- examples/simple_repeater/main.cpp | 2 ++ examples/simple_sensor/main.cpp | 2 ++ src/MeshCore.h | 4 ++++ 3 files changed, 8 insertions(+) diff --git a/examples/simple_repeater/main.cpp b/examples/simple_repeater/main.cpp index 1f71da74..d475b13d 100644 --- a/examples/simple_repeater/main.cpp +++ b/examples/simple_repeater/main.cpp @@ -165,6 +165,8 @@ void loop() { command[0] = 0; // reset command buffer } + board.loop(); // let the board feed its watchdog, run periodic housekeeping + #ifdef ETHERNET_ENABLED ethernet_loop_maintain(); if (ethernet_read_line(ethernet_command, sizeof(ethernet_command))) { diff --git a/examples/simple_sensor/main.cpp b/examples/simple_sensor/main.cpp index 749ff6ef..db1c5279 100644 --- a/examples/simple_sensor/main.cpp +++ b/examples/simple_sensor/main.cpp @@ -153,6 +153,8 @@ void loop() { command[0] = 0; // reset command buffer } + board.loop(); // let the board feed its watchdog, run periodic housekeeping + the_mesh.loop(); sensors.loop(); #ifdef DISPLAY_CLASS diff --git a/src/MeshCore.h b/src/MeshCore.h index 4bc9d3db..2a3582de 100644 --- a/src/MeshCore.h +++ b/src/MeshCore.h @@ -76,6 +76,10 @@ public: virtual const char* getShutdownReasonString(uint8_t reason) { return "Not available"; } virtual bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { return false; } + + // Called from the example main loops. Lets a board feed its watchdog and + // run periodic housekeeping. Default no-op. + virtual void loop() { /* no op */ } }; /** From 0812e09b408ae84584af313e81617408c69301d2 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Tue, 22 Sep 2026 18:01:15 +1000 Subject: [PATCH 249/381] missing board.loop() in companion, room server, kiss modem. --- examples/companion_radio/main.cpp | 1 + examples/kiss_modem/main.cpp | 4 +++- examples/simple_room_server/main.cpp | 1 + 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index 4bc75a81..839d4958 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -297,6 +297,7 @@ void loop() { ui_task.loop(); #endif rtc_clock.tick(); + board.loop(); #ifdef HAS_EXTERNAL_WATCHDOG external_watchdog.loop(); #endif diff --git a/examples/kiss_modem/main.cpp b/examples/kiss_modem/main.cpp index 5836a694..44b2a3df 100644 --- a/examples/kiss_modem/main.cpp +++ b/examples/kiss_modem/main.cpp @@ -113,7 +113,7 @@ void setup() { uint32_t start = millis(); while (!Serial && millis() - start < 3000) delay(10); delay(100); -#if defined(ESP32) && ARDUINO_USB_MODE +#if defined(ESP32) && defined(ARDUINO_USB_CDC_ON_BOOT) && ARDUINO_USB_CDC_ON_BOOT Serial.setTxTimeoutMs(USB_TX_TIMEOUT_MS); Serial.setTxBufferSize(USB_TX_BUFFER_SIZE); #endif @@ -149,6 +149,8 @@ void loop() { } } + board.loop(); + if ((uint32_t)(millis() - next_noise_floor_calib_ms) >= NOISE_FLOOR_CALIB_INTERVAL_MS) { radio_driver.triggerNoiseFloorCalibrate(0); next_noise_floor_calib_ms = millis(); diff --git a/examples/simple_room_server/main.cpp b/examples/simple_room_server/main.cpp index 227ee2cb..65fc55ef 100644 --- a/examples/simple_room_server/main.cpp +++ b/examples/simple_room_server/main.cpp @@ -162,6 +162,7 @@ void loop() { ui_task.loop(); #endif rtc_clock.tick(); + board.loop(); #ifdef HAS_EXTERNAL_WATCHDOG external_watchdog.loop(); #endif From caff7790c4ba46f445a2665ad6e150483ebf88b5 Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Wed, 23 Sep 2026 15:04:51 +1200 Subject: [PATCH 250/381] fix heltec ct62 boot loop --- variants/heltec_ct62/platformio.ini | 1 + 1 file changed, 1 insertion(+) diff --git a/variants/heltec_ct62/platformio.ini b/variants/heltec_ct62/platformio.ini index 401a30d2..f98f8d4a 100644 --- a/variants/heltec_ct62/platformio.ini +++ b/variants/heltec_ct62/platformio.ini @@ -1,6 +1,7 @@ [Heltec_ct62] extends = esp32_base board = esp32-c3-devkitm-1 +board_build.partitions = min_spiffs.csv ; get around 4mb flash limit build_flags = ${esp32_base.build_flags} -I variants/heltec_ct62 From fa18757f2c8a4fd160b903d8ecc982f69e7e018c Mon Sep 17 00:00:00 2001 From: agessaman <adam@gessaman.com> Date: Wed, 23 Sep 2026 15:43:01 -0700 Subject: [PATCH 251/381] kiss_modem: add AGC reset interval and FEM gain control (protocol v2) Add SetHardware sub-commands so a host can probe and configure per-board RF front-end settings: - GetCapabilities (0x1B): uint32 feature bits (AGC, FEM RX, FEM TX) - Set/GetAgcResetInterval (0x1C/0x1D): 0-1020 s, 4 s resolution, 0 disables; default stays 30 s - Set/GetFemState (0x1E/0x1F): apply/value masks for FEM RX (LNA) and TX (PA) gain; all-or-nothing, Unsupported (0x08) if any requested bit is not controllable on this board The AGC scheduler moves from main.cpp into KissModem so it is configurable and unit-tested. FEM changes that arrive mid-TX are deferred until the packet ends, since board setters drive FEM pins directly. MainBoard gains virtual FEM hooks (canControl/set/is for LNA and PA gain). Boards that already implemented these methods privately now expose them as overrides: Heltec V4, V4 R8, T096, Tracker V2, Station G3 and Wio Tracker L1 1W. KISS_FIRMWARE_VERSION bumped to 2. --- docs/kiss_modem_protocol.md | 70 ++++- examples/kiss_modem/KissModem.cpp | 134 +++++++++ examples/kiss_modem/KissModem.h | 37 ++- examples/kiss_modem/main.cpp | 9 - src/MeshCore.h | 8 + test/mocks/Mesh.h | 7 + test/test_kiss_modem/test_hw_controls.cpp | 278 ++++++++++++++++++ variants/heltec_t096/T096Board.h | 6 +- .../heltec_tracker_v2/HeltecTrackerV2Board.h | 6 +- variants/heltec_v4/HeltecV4Board.h | 6 +- variants/heltec_v4_r8/HeltecV4R8Board.h | 5 +- variants/heltec_v4_r8/LoRaFEMControl.h | 2 +- variants/station_g3_esp32/StationG3Board.h | 10 +- .../wio-tracker-l1-1w/WioTrackerL1Board.h | 6 +- 14 files changed, 553 insertions(+), 31 deletions(-) create mode 100644 test/test_kiss_modem/test_hw_controls.cpp diff --git a/docs/kiss_modem_protocol.md b/docs/kiss_modem_protocol.md index 3f4dbf9c..9b8aaa4b 100644 --- a/docs/kiss_modem_protocol.md +++ b/docs/kiss_modem_protocol.md @@ -118,10 +118,15 @@ MeshCore-specific functionality uses the standard KISS SetHardware command. The | Reboot | `0x18` | - | | SetSignalReport | `0x19` | Enable (1): 0x00=disable, nonzero=enable | | GetSignalReport | `0x1A` | - | +| GetCapabilities | `0x1B` | - | +| SetAgcResetInterval | `0x1C` | Seconds (2): 0=disable, 0-1020 | +| GetAgcResetInterval | `0x1D` | - | +| SetFemState | `0x1E` | Apply mask (1) + Value mask (1) | +| GetFemState | `0x1F` | - | ### Response Sub-commands (TNC to Host) -Response codes use the high-bit convention: `response = command | 0x80`. Generic and unsolicited responses use the `0xF0`+ range. +Response codes use the high-bit convention: `response = command | 0x80`. Generic and unsolicited responses use the `0xF0`+ range. Set commands that report state (SetSignalReport, SetAgcResetInterval, SetFemState) reply with the matching Get response, so `0x9C` and `0x9E` are never sent. | Sub-command | Value | Data | |--------------|--------|-----------------------------------------| @@ -147,6 +152,9 @@ Response codes use the high-bit convention: `response = command | 0x80`. Generic | DeviceName | `0x96` | Name (variable, UTF-8) | | Pong | `0x97` | - | | SignalReport | `0x9A` | Status (1): 0x00=disabled, 0x01=enabled | +| Capabilities | `0x9B` | Feature bits (4) | +| AgcResetInterval | `0x9D` | Effective seconds (2) | +| FemState | `0x9F` | Capability mask (1) + Value mask (1) | | OK | `0xF0` | - | | Error | `0xF1` | Error code (1) | | TxDone | `0xF8` | Result (1): 0x00=failed, 0x01=success | @@ -163,6 +171,7 @@ Response codes use the high-bit convention: `response = command | 0x80`. Generic | UnknownCmd | `0x05` | Unknown sub-command | | EncryptFailed | `0x06` | Encryption failed | | TxBusy | `0x07` | Radio TX busy, or host output queue full | +| Unsupported | `0x08` | Command known, but not supported by this board | ### Unsolicited Events @@ -215,7 +224,64 @@ All values little-endian. |-------------|---------|-----------------------| | Noise floor | 2 bytes | int16_t, dBm (signed) | -The modem recalibrates the noise floor every 2 seconds with an AGC reset every 30 seconds. +The modem recalibrates the noise floor every 2 seconds. AGC resets follow the configured AGC reset interval (default 30 seconds). + +### Capabilities (Capabilities response) + +All values little-endian. Hosts should probe capabilities rather than infer them from the firmware version: boards running the same version expose different hardware controls. Firmware older than version 2 answers GetCapabilities with `UnknownCmd`; treat that as no capabilities. + +| Field | Size | Description | +|--------------|---------|--------------------| +| Feature bits | 4 bytes | uint32_t, see below | + +| Bit | Value | Description | +|-----|--------|-------------------------------------------| +| 0 | `0x01` | AGC reset interval control (always set) | +| 1 | `0x02` | External FEM RX (LNA) gain control | +| 2 | `0x04` | External FEM TX (PA) gain control | + +Remaining bits are reserved and sent as 0. + +### AGC Reset Interval (SetAgcResetInterval / AgcResetInterval response) + +All values little-endian. + +| Field | Size | Description | +|---------|---------|-------------------------------------------| +| Seconds | 2 bytes | uint16_t, 0 = disabled, maximum 1020 | + +The modem periodically resets the radio's AGC while idle (no transmission in progress and host output not backed up). The interval has 4-second resolution, matching the MeshCore `agc.reset.interval` setting: requested values are rounded down to a multiple of 4, so 1-3 disable the reset. Values above 1020 return `InvalidParam`. SetAgcResetInterval replies with the AgcResetInterval response carrying the effective value, and restarts the countdown from the time of the request. + +The default is 30 seconds. The setting is not persisted; hosts should re-send it after reconnecting or rebooting the modem. + +### FEM State (SetFemState / FemState response) + +Controls the board's external LoRa front-end module gain. This is separate from the radio chip's own RX boosted gain. TX/RX switching of the FEM is handled by the board and is not affected by these settings. + +| Bit | Value | Description | +|-----|--------|---------------------------------| +| 0 | `0x01` | RX gain (LNA enabled) | +| 1 | `0x02` | TX gain (PA high gain enabled) | + +SetFemState data: + +| Field | Size | Description | +|------------|--------|------------------------------------------------| +| Apply mask | 1 byte | Bits to change; bits not set are left as-is | +| Value mask | 1 byte | New value for each bit in the apply mask | + +FemState response data: + +| Field | Size | Description | +|-----------------|--------|---------------------------------------------------| +| Capability mask | 1 byte | Bits this board can control | +| Value mask | 1 byte | Current state; always 0 for uncontrollable bits | + +Example: enable RX gain without changing TX gain: apply `0x01`, value `0x01`. + +If any bit in the apply mask is not in the board's capability mask (including reserved bits), the modem replies `Unsupported` and changes nothing. On success, SetFemState replies with the FemState response carrying the new state. A request received while a packet is on air is applied as soon as that transmission ends, and the FemState response is sent then; a second request during the same transmission returns `TxBusy`. Capabilities come from the board, so a board with a fixed, board-managed FEM (for example RAK3401) reports none. + +The setting is not persisted; the board's power-on default applies after reboot. ### Stats (Stats response) diff --git a/examples/kiss_modem/KissModem.cpp b/examples/kiss_modem/KissModem.cpp index 7dcfc8d7..5b61e83c 100644 --- a/examples/kiss_modem/KissModem.cpp +++ b/examples/kiss_modem/KissModem.cpp @@ -22,6 +22,11 @@ KissModem::KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& r _getStatsCallback = nullptr; _config = {0, 0, 0, 0, 0}; _signal_report_enabled = true; + _agc_reset_interval_sec = KISS_AGC_RESET_DEFAULT_SEC; + _next_agc_reset_ms = 0; + _fem_deferred = false; + _fem_deferred_apply = 0; + _fem_deferred_value = 0; resetOutputQueue(); } @@ -31,6 +36,8 @@ void KissModem::begin() { _rx_active = false; _has_pending_tx = false; _tx_state = TX_IDLE; + _fem_deferred = false; + _next_agc_reset_ms = millis() + (uint32_t)_agc_reset_interval_sec * 1000; resetOutputQueue(); } @@ -240,10 +247,24 @@ void KissModem::loop() { } processTx(); + processDeferredFem(); + maybeResetAgc(); tryFlushFrames(); queuePendingBusyError(); } +void KissModem::maybeResetAgc() { + if (_agc_reset_interval_sec == 0) return; + // same guard as the RX path in main.cpp, so receive is restarted right after the reset + if (_tx_state != TX_IDLE || isHostOutputBackedUp()) return; + + uint32_t now = millis(); + if ((int32_t)(now - _next_agc_reset_ms) >= 0) { + _radio.resetAGC(); + _next_agc_reset_ms = now + (uint32_t)_agc_reset_interval_sec * 1000; + } +} + void KissModem::processFrame() { if (_rx_len < 1) return; @@ -381,6 +402,21 @@ void KissModem::handleHardwareCommand(uint8_t sub_cmd, const uint8_t* data, uint case HW_CMD_GET_SIGNAL_REPORT: handleGetSignalReport(); break; + case HW_CMD_GET_CAPABILITIES: + handleGetCapabilities(); + break; + case HW_CMD_SET_AGC_RESET_INTERVAL: + handleSetAgcResetInterval(data, len); + break; + case HW_CMD_GET_AGC_RESET_INTERVAL: + handleGetAgcResetInterval(); + break; + case HW_CMD_SET_FEM_STATE: + handleSetFemState(data, len); + break; + case HW_CMD_GET_FEM_STATE: + handleGetFemState(); + break; default: writeHardwareError(HW_ERR_UNKNOWN_CMD); break; @@ -732,3 +768,101 @@ void KissModem::handleGetSignalReport() { uint8_t val = _signal_report_enabled ? 0x01 : 0x00; writeHardwareFrame(HW_RESP(HW_CMD_GET_SIGNAL_REPORT), &val, 1); } + +void KissModem::handleGetCapabilities() { + uint32_t caps = HW_CAP_AGC_RESET; + if (_board.canControlLoRaFemLna()) caps |= HW_CAP_FEM_RX_GAIN; + if (_board.canControlLoRaFemPaGain()) caps |= HW_CAP_FEM_TX_GAIN; + uint8_t buf[4] = { (uint8_t)caps, (uint8_t)(caps >> 8), (uint8_t)(caps >> 16), (uint8_t)(caps >> 24) }; + writeHardwareFrame(HW_RESP(HW_CMD_GET_CAPABILITIES), buf, 4); +} + +void KissModem::handleSetAgcResetInterval(const uint8_t* data, uint16_t len) { + if (len < 2) { + writeHardwareError(HW_ERR_INVALID_LENGTH); + return; + } + uint16_t secs = (uint16_t)(data[0] | (data[1] << 8)); + if (secs > KISS_AGC_RESET_MAX_SEC) { + writeHardwareError(HW_ERR_INVALID_PARAM); + return; + } + _agc_reset_interval_sec = secs - (secs % KISS_AGC_RESET_STEP_SEC); + _next_agc_reset_ms = millis() + (uint32_t)_agc_reset_interval_sec * 1000; + handleGetAgcResetInterval(); +} + +void KissModem::handleGetAgcResetInterval() { + uint8_t buf[2] = { (uint8_t)_agc_reset_interval_sec, (uint8_t)(_agc_reset_interval_sec >> 8) }; + writeHardwareFrame(HW_RESP(HW_CMD_GET_AGC_RESET_INTERVAL), buf, 2); +} + +uint8_t KissModem::femCapabilityMask() const { + uint8_t mask = 0; + if (_board.canControlLoRaFemLna()) mask |= HW_FEM_RX_GAIN; + if (_board.canControlLoRaFemPaGain()) mask |= HW_FEM_TX_GAIN; + return mask; +} + +uint8_t KissModem::femValueMask() const { + uint8_t mask = 0; + if (_board.canControlLoRaFemLna() && _board.isLoRaFemLnaEnabled()) mask |= HW_FEM_RX_GAIN; + if (_board.canControlLoRaFemPaGain() && _board.isLoRaFemPaGainEnabled()) mask |= HW_FEM_TX_GAIN; + return mask; +} + +void KissModem::writeFemState() { + uint8_t buf[2] = { femCapabilityMask(), femValueMask() }; + writeHardwareFrame(HW_RESP(HW_CMD_GET_FEM_STATE), buf, 2); +} + +void KissModem::applyFemState(uint8_t apply_mask, uint8_t value_mask) { + bool ok = true; + if (apply_mask & HW_FEM_RX_GAIN) { + ok &= _board.setLoRaFemLnaEnabled((value_mask & HW_FEM_RX_GAIN) != 0); + } + if (apply_mask & HW_FEM_TX_GAIN) { + ok &= _board.setLoRaFemPaGainEnabled((value_mask & HW_FEM_TX_GAIN) != 0); + } + if (ok) { + writeFemState(); + } else { + writeHardwareError(HW_ERR_UNSUPPORTED); + } +} + +void KissModem::processDeferredFem() { + if (!_fem_deferred || _tx_state == TX_SENDING) return; + _fem_deferred = false; + applyFemState(_fem_deferred_apply, _fem_deferred_value); +} + +void KissModem::handleSetFemState(const uint8_t* data, uint16_t len) { + if (len < 2) { + writeHardwareError(HW_ERR_INVALID_LENGTH); + return; + } + uint8_t apply_mask = data[0]; + uint8_t value_mask = data[1]; + // validate every requested bit before touching hardware so a request is all-or-nothing + if (apply_mask & ~femCapabilityMask()) { + writeHardwareError(HW_ERR_UNSUPPORTED); + return; + } + if (_tx_state == TX_SENDING) { + // board setters drive FEM pins directly; changing them mid-packet would corrupt the TX + if (_fem_deferred) { + writeHardwareError(HW_ERR_TX_BUSY); + return; + } + _fem_deferred = true; + _fem_deferred_apply = apply_mask; + _fem_deferred_value = value_mask; + return; + } + applyFemState(apply_mask, value_mask); +} + +void KissModem::handleGetFemState() { + writeFemState(); +} diff --git a/examples/kiss_modem/KissModem.h b/examples/kiss_modem/KissModem.h index a23e459b..751fb336 100644 --- a/examples/kiss_modem/KissModem.h +++ b/examples/kiss_modem/KissModem.h @@ -62,6 +62,11 @@ #define HW_CMD_REBOOT 0x18 #define HW_CMD_SET_SIGNAL_REPORT 0x19 #define HW_CMD_GET_SIGNAL_REPORT 0x1A +#define HW_CMD_GET_CAPABILITIES 0x1B +#define HW_CMD_SET_AGC_RESET_INTERVAL 0x1C +#define HW_CMD_GET_AGC_RESET_INTERVAL 0x1D +#define HW_CMD_SET_FEM_STATE 0x1E +#define HW_CMD_GET_FEM_STATE 0x1F /* Response code = command code | 0x80. Generic / unsolicited use 0xF0+. */ #define HW_RESP(cmd) ((cmd) | 0x80) @@ -81,8 +86,22 @@ #define HW_ERR_UNKNOWN_CMD 0x05 #define HW_ERR_ENCRYPT_FAILED 0x06 #define HW_ERR_TX_BUSY 0x07 +#define HW_ERR_UNSUPPORTED 0x08 -#define KISS_FIRMWARE_VERSION 1 +/* GetCapabilities feature bits */ +#define HW_CAP_AGC_RESET (1UL << 0) +#define HW_CAP_FEM_RX_GAIN (1UL << 1) +#define HW_CAP_FEM_TX_GAIN (1UL << 2) + +/* SetFemState / GetFemState mask bits */ +#define HW_FEM_RX_GAIN (1 << 0) +#define HW_FEM_TX_GAIN (1 << 1) + +#define KISS_AGC_RESET_DEFAULT_SEC 30 +#define KISS_AGC_RESET_MAX_SEC 1020 +#define KISS_AGC_RESET_STEP_SEC 4 + +#define KISS_FIRMWARE_VERSION 2 typedef void (*SetRadioCallback)(float freq, float bw, uint8_t sf, uint8_t cr); typedef void (*SetTxPowerCallback)(uint8_t power); @@ -139,6 +158,11 @@ class KissModem { RadioConfig _config; bool _signal_report_enabled; + uint16_t _agc_reset_interval_sec; + uint32_t _next_agc_reset_ms; + bool _fem_deferred; + uint8_t _fem_deferred_apply; + uint8_t _fem_deferred_value; uint8_t _tx_frame_buf[KISS_TX_FRAME_QUEUE_DEPTH][KISS_MAX_ENCODED_FRAME_SIZE]; uint16_t _tx_frame_len[KISS_TX_FRAME_QUEUE_DEPTH]; uint16_t _tx_frame_written[KISS_TX_FRAME_QUEUE_DEPTH]; @@ -165,6 +189,12 @@ class KissModem { void processFrame(); void handleHardwareCommand(uint8_t sub_cmd, const uint8_t* data, uint16_t len); void processTx(); + void maybeResetAgc(); + uint8_t femCapabilityMask() const; + uint8_t femValueMask() const; + void writeFemState(); + void applyFemState(uint8_t apply_mask, uint8_t value_mask); + void processDeferredFem(); void handleGetIdentity(); void handleGetRandom(const uint8_t* data, uint16_t len); @@ -192,6 +222,11 @@ class KissModem { void handleGetDeviceName(); void handleSetSignalReport(const uint8_t* data, uint16_t len); void handleGetSignalReport(); + void handleGetCapabilities(); + void handleSetAgcResetInterval(const uint8_t* data, uint16_t len); + void handleGetAgcResetInterval(); + void handleSetFemState(const uint8_t* data, uint16_t len); + void handleGetFemState(); public: KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& rng, diff --git a/examples/kiss_modem/main.cpp b/examples/kiss_modem/main.cpp index 44b2a3df..8835418d 100644 --- a/examples/kiss_modem/main.cpp +++ b/examples/kiss_modem/main.cpp @@ -19,7 +19,6 @@ #endif #define NOISE_FLOOR_CALIB_INTERVAL_MS 2000 -#define AGC_RESET_INTERVAL_MS 30000 #define USB_TX_TIMEOUT_MS 50 #define USB_TX_BUFFER_SIZE 1024 @@ -27,7 +26,6 @@ StdRNG rng; mesh::LocalIdentity identity; KissModem* modem; static uint32_t next_noise_floor_calib_ms = 0; -static uint32_t next_agc_reset_ms = 0; void halt() { while (1) ; @@ -133,13 +131,6 @@ void loop() { modem->loop(); if (!modem->isActuallyTransmitting() && !modem->isHostOutputBackedUp()) { - if (!modem->isTxBusy()) { - if ((uint32_t)(millis() - next_agc_reset_ms) >= AGC_RESET_INTERVAL_MS) { - radio_driver.resetAGC(); - next_agc_reset_ms = millis(); - } - } - uint8_t rx_buf[256]; int rx_len = radio_driver.recvRaw(rx_buf, sizeof(rx_buf)); if (rx_len > 0) { diff --git a/src/MeshCore.h b/src/MeshCore.h index 2a3582de..5fdb064c 100644 --- a/src/MeshCore.h +++ b/src/MeshCore.h @@ -77,6 +77,14 @@ public: virtual bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { return false; } + // External LoRa front-end (FEM) gain control. Boards without a controllable FEM keep these defaults. + virtual bool canControlLoRaFemLna() const { return false; } + virtual bool setLoRaFemLnaEnabled(bool enable) { return false; } + virtual bool isLoRaFemLnaEnabled() const { return false; } + virtual bool canControlLoRaFemPaGain() const { return false; } + virtual bool setLoRaFemPaGainEnabled(bool enable) { return false; } + virtual bool isLoRaFemPaGainEnabled() const { return false; } + // Called from the example main loops. Lets a board feed its watchdog and // run periodic housekeeping. Default no-op. virtual void loop() { /* no op */ } diff --git a/test/mocks/Mesh.h b/test/mocks/Mesh.h index b6c263c1..29a29b82 100644 --- a/test/mocks/Mesh.h +++ b/test/mocks/Mesh.h @@ -13,6 +13,7 @@ public: virtual bool isSendComplete() { return true; } virtual void onSendFinished() {} virtual int16_t getNoiseFloor() { return -120; } + virtual void resetAGC() {} }; class MainBoard { @@ -22,6 +23,12 @@ public: virtual float getMCUTemperature() { return 25.0f; } virtual const char* getManufacturerName() { return "mock-board"; } virtual void reboot() {} + virtual bool canControlLoRaFemLna() const { return false; } + virtual bool setLoRaFemLnaEnabled(bool) { return false; } + virtual bool isLoRaFemLnaEnabled() const { return false; } + virtual bool canControlLoRaFemPaGain() const { return false; } + virtual bool setLoRaFemPaGainEnabled(bool) { return false; } + virtual bool isLoRaFemPaGainEnabled() const { return false; } }; } diff --git a/test/test_kiss_modem/test_hw_controls.cpp b/test/test_kiss_modem/test_hw_controls.cpp new file mode 100644 index 00000000..ad6f1e36 --- /dev/null +++ b/test/test_kiss_modem/test_hw_controls.cpp @@ -0,0 +1,278 @@ +#include <gtest/gtest.h> + +#include <queue> +#include <vector> + +#include "KissModem.h" + +namespace { + +class RecordingStream : public Stream { +public: + void pushRx(const std::vector<uint8_t>& bytes) { + for (uint8_t b : bytes) _rx.push(b); + } + + int availableForWrite() override { return 4096; } + size_t write(const uint8_t* buffer, size_t size) override { + _writes.insert(_writes.end(), buffer, buffer + size); + return size; + } + size_t write(uint8_t b) override { return write(&b, 1); } + int available() override { return (int)_rx.size(); } + int read() override { + if (_rx.empty()) return -1; + int b = _rx.front(); + _rx.pop(); + return b; + } + + // Decoded SetHardware payloads (sub-command + data), consumed on read. + std::vector<std::vector<uint8_t>> takeHardwareFrames() { + std::vector<std::vector<uint8_t>> frames; + std::vector<uint8_t> cur; + bool in_frame = false, esc = false; + for (uint8_t b : _writes) { + if (b == KISS_FEND) { + if (in_frame && cur.size() > 1 && cur[0] == KISS_CMD_SETHARDWARE) { + frames.emplace_back(cur.begin() + 1, cur.end()); + } + cur.clear(); + in_frame = true; + continue; + } + if (b == KISS_FESC) { esc = true; continue; } + if (esc) { b = (b == KISS_TFEND) ? KISS_FEND : KISS_FESC; esc = false; } + cur.push_back(b); + } + _writes.clear(); + return frames; + } + +private: + std::queue<uint8_t> _rx; + std::vector<uint8_t> _writes; +}; + +class ZeroRNG : public mesh::RNG { +public: + void random(uint8_t* dest, size_t sz) override { memset(dest, 0, sz); } +}; + +class AgcRadio : public mesh::Radio { +public: + bool startSendRaw(const uint8_t*, uint16_t) override { return true; } + bool isSendComplete() override { return send_complete; } + void resetAGC() override { agc_resets++; } + + bool send_complete = true; + int agc_resets = 0; +}; + +class FemBoard : public mesh::MainBoard { +public: + const char* getManufacturerName() override { return "fem-board"; } + + bool canControlLoRaFemLna() const override { return has_lna; } + bool setLoRaFemLnaEnabled(bool enable) override { + if (!has_lna) return false; + lna = enable; + lna_sets++; + return true; + } + bool isLoRaFemLnaEnabled() const override { return lna; } + + bool canControlLoRaFemPaGain() const override { return has_pa; } + bool setLoRaFemPaGainEnabled(bool enable) override { + if (!has_pa) return false; + pa = enable; + pa_sets++; + return true; + } + bool isLoRaFemPaGainEnabled() const override { return pa; } + + bool has_lna = false, has_pa = false; + bool lna = false, pa = false; + int lna_sets = 0, pa_sets = 0; +}; + +class NoSensors : public SensorManager { +public: + bool querySensors(uint8_t, CayenneLPP&) override { return false; } +}; + +class KissHwControlTest : public ::testing::Test { +protected: + RecordingStream serial; + mesh::LocalIdentity identity; + ZeroRNG rng; + AgcRadio radio; + FemBoard board; + NoSensors sensors; + KissModem modem; + + KissHwControlTest() : modem(serial, identity, rng, radio, board, sensors) { + g_mock_millis = 1000; + modem.begin(); + } + + std::vector<std::vector<uint8_t>> hw(const std::vector<uint8_t>& payload) { + std::vector<uint8_t> frame = {KISS_FEND, KISS_CMD_SETHARDWARE}; + frame.insert(frame.end(), payload.begin(), payload.end()); + frame.push_back(KISS_FEND); + serial.pushRx(frame); + modem.loop(); + return serial.takeHardwareFrames(); + } + + std::vector<uint8_t> hw1(const std::vector<uint8_t>& payload) { + auto frames = hw(payload); + EXPECT_EQ(frames.size(), 1U); + return frames.empty() ? std::vector<uint8_t>{} : frames[0]; + } + + void advance(uint32_t ms) { + g_mock_millis += ms; + modem.loop(); + } + + void startTxAndHold() { + radio.send_complete = false; + serial.pushRx({KISS_FEND, KISS_CMD_DATA, 0x42, KISS_FEND}); + modem.loop(); + modem.loop(); + advance((uint32_t)KISS_DEFAULT_TXDELAY * 10); + ASSERT_TRUE(modem.isActuallyTransmitting()); + } +}; + +const std::vector<uint8_t> ERR_UNSUPPORTED = {HW_RESP_ERROR, HW_ERR_UNSUPPORTED}; + +TEST_F(KissHwControlTest, VersionIsTwo) { + EXPECT_EQ(hw1({HW_CMD_GET_VERSION}), (std::vector<uint8_t>{HW_RESP(HW_CMD_GET_VERSION), 2, 0})); +} + +TEST_F(KissHwControlTest, CapabilitiesOnBareBoardAreAgcOnly) { + EXPECT_EQ(hw1({HW_CMD_GET_CAPABILITIES}), (std::vector<uint8_t>{0x9B, 0x01, 0x00, 0x00, 0x00})); +} + +TEST_F(KissHwControlTest, CapabilitiesReflectBoardFem) { + board.has_lna = true; + EXPECT_EQ(hw1({HW_CMD_GET_CAPABILITIES}), (std::vector<uint8_t>{0x9B, 0x03, 0x00, 0x00, 0x00})); + board.has_pa = true; + EXPECT_EQ(hw1({HW_CMD_GET_CAPABILITIES}), (std::vector<uint8_t>{0x9B, 0x07, 0x00, 0x00, 0x00})); +} + +TEST_F(KissHwControlTest, AgcIntervalDefaultsToThirtySeconds) { + EXPECT_EQ(hw1({HW_CMD_GET_AGC_RESET_INTERVAL}), (std::vector<uint8_t>{0x9D, 30, 0})); +} + +TEST_F(KissHwControlTest, AgcIntervalSetReturnsEffectiveRoundedValue) { + EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 10, 0}), (std::vector<uint8_t>{0x9D, 8, 0})); + EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 4, 0}), (std::vector<uint8_t>{0x9D, 4, 0})); + EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 0xFC, 0x03}), (std::vector<uint8_t>{0x9D, 0xFC, 0x03})); + EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 0, 0}), (std::vector<uint8_t>{0x9D, 0, 0})); + EXPECT_EQ(hw1({HW_CMD_GET_AGC_RESET_INTERVAL}), (std::vector<uint8_t>{0x9D, 0, 0})); +} + +TEST_F(KissHwControlTest, AgcIntervalRejectsOutOfRangeAndShortPayload) { + EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 0xFD, 0x03}), (std::vector<uint8_t>{HW_RESP_ERROR, HW_ERR_INVALID_PARAM})); + EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 4}), (std::vector<uint8_t>{HW_RESP_ERROR, HW_ERR_INVALID_LENGTH})); + EXPECT_EQ(hw1({HW_CMD_GET_AGC_RESET_INTERVAL}), (std::vector<uint8_t>{0x9D, 30, 0})); +} + +TEST_F(KissHwControlTest, AgcResetsOnDefaultSchedule) { + advance(29999); + EXPECT_EQ(radio.agc_resets, 0); + advance(1); + EXPECT_EQ(radio.agc_resets, 1); + advance(29999); + EXPECT_EQ(radio.agc_resets, 1); + advance(1); + EXPECT_EQ(radio.agc_resets, 2); +} + +TEST_F(KissHwControlTest, AgcZeroDisablesResets) { + hw({HW_CMD_SET_AGC_RESET_INTERVAL, 0, 0}); + for (int i = 0; i < 10; i++) advance(60000); + EXPECT_EQ(radio.agc_resets, 0); +} + +TEST_F(KissHwControlTest, AgcIntervalChangeRestartsDeadline) { + hw({HW_CMD_SET_AGC_RESET_INTERVAL, 0x2C, 0x01}); // 300 s + advance(100000); + hw({HW_CMD_SET_AGC_RESET_INTERVAL, 4, 0}); + EXPECT_EQ(radio.agc_resets, 0); + advance(3999); + EXPECT_EQ(radio.agc_resets, 0); + advance(1); + EXPECT_EQ(radio.agc_resets, 1); +} + +TEST_F(KissHwControlTest, AgcResetWaitsForTxToFinish) { + hw({HW_CMD_SET_AGC_RESET_INTERVAL, 4, 0}); + startTxAndHold(); + advance(10000); + EXPECT_EQ(radio.agc_resets, 0); + radio.send_complete = true; + modem.loop(); // TX done -> TX_DONE_PENDING + modem.loop(); // TxDone flushed -> idle, overdue reset runs + EXPECT_EQ(radio.agc_resets, 1); +} + +TEST_F(KissHwControlTest, FemUnsupportedOnBareBoard) { + EXPECT_EQ(hw1({HW_CMD_GET_FEM_STATE}), (std::vector<uint8_t>{0x9F, 0x00, 0x00})); + EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}), ERR_UNSUPPORTED); + EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_TX_GAIN, 0}), ERR_UNSUPPORTED); +} + +TEST_F(KissHwControlTest, FemSetRxLeavesTxUntouched) { + board.has_lna = board.has_pa = true; + board.pa = true; + EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}), (std::vector<uint8_t>{0x9F, 0x03, 0x03})); + EXPECT_TRUE(board.lna); + EXPECT_EQ(board.pa_sets, 0); + + EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_TX_GAIN, 0}), (std::vector<uint8_t>{0x9F, 0x03, 0x01})); + EXPECT_FALSE(board.pa); + EXPECT_EQ(board.lna_sets, 1); +} + +TEST_F(KissHwControlTest, FemPartialCapabilityRejectsWholeRequest) { + board.has_lna = true; + EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN | HW_FEM_TX_GAIN, HW_FEM_RX_GAIN | HW_FEM_TX_GAIN}), ERR_UNSUPPORTED); + EXPECT_EQ(board.lna_sets, 0); + EXPECT_EQ(hw1({HW_CMD_GET_FEM_STATE}), (std::vector<uint8_t>{0x9F, 0x01, 0x00})); +} + +TEST_F(KissHwControlTest, FemUnknownBitsAreUnsupported) { + board.has_lna = board.has_pa = true; + EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, 0x04, 0x04}), ERR_UNSUPPORTED); +} + +TEST_F(KissHwControlTest, FemShortPayloadIsInvalidLength) { + EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN}), (std::vector<uint8_t>{HW_RESP_ERROR, HW_ERR_INVALID_LENGTH})); +} + +TEST_F(KissHwControlTest, FemSetDuringTxIsDeferredUntilTxCompletes) { + board.has_lna = true; + startTxAndHold(); + serial.takeHardwareFrames(); + + EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}).empty()); + EXPECT_EQ(board.lna_sets, 0); + EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, 0}), (std::vector<uint8_t>{HW_RESP_ERROR, HW_ERR_TX_BUSY})); + + radio.send_complete = true; + modem.loop(); + auto frames = serial.takeHardwareFrames(); + ASSERT_EQ(frames.size(), 1U); + EXPECT_EQ(frames[0], (std::vector<uint8_t>{0x9F, 0x01, 0x01})); + EXPECT_TRUE(board.lna); + modem.loop(); + frames = serial.takeHardwareFrames(); + ASSERT_EQ(frames.size(), 1U); + EXPECT_EQ(frames[0], (std::vector<uint8_t>{HW_RESP_TX_DONE, 0x01})); +} + +} // namespace diff --git a/variants/heltec_t096/T096Board.h b/variants/heltec_t096/T096Board.h index e926c8a6..66fa5047 100644 --- a/variants/heltec_t096/T096Board.h +++ b/variants/heltec_t096/T096Board.h @@ -16,9 +16,6 @@ protected: #endif void variant_shutdown(); - bool setLoRaFemLnaEnabled(bool enable); - bool isLoRaFemLnaEnabled() const; - public: RefCountedDigitalPin periph_power; LoRaFEMControl loRaFEMControl; @@ -27,6 +24,9 @@ public: void begin(); void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; + bool canControlLoRaFemLna() const override { return loRaFEMControl.isLnaCanControl(); } + bool setLoRaFemLnaEnabled(bool enable) override; + bool isLoRaFemLnaEnabled() const override; void onBeforeTransmit(void) override; void onAfterTransmit(void) override; diff --git a/variants/heltec_tracker_v2/HeltecTrackerV2Board.h b/variants/heltec_tracker_v2/HeltecTrackerV2Board.h index 5fed2b65..34454cac 100644 --- a/variants/heltec_tracker_v2/HeltecTrackerV2Board.h +++ b/variants/heltec_tracker_v2/HeltecTrackerV2Board.h @@ -8,9 +8,6 @@ class HeltecTrackerV2Board : public ESP32Board { KeyValueStore* _prefs = NULL; - bool setLoRaFemLnaEnabled(bool enable); - bool isLoRaFemLnaEnabled() const; - public: RefCountedDigitalPin periph_power; LoRaFEMControl loRaFEMControl; @@ -20,6 +17,9 @@ public: void begin(); void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; + bool canControlLoRaFemLna() const override { return loRaFEMControl.isLnaCanControl(); } + bool setLoRaFemLnaEnabled(bool enable) override; + bool isLoRaFemLnaEnabled() const override; void onBeforeTransmit(void) override; void onAfterTransmit(void) override; diff --git a/variants/heltec_v4/HeltecV4Board.h b/variants/heltec_v4/HeltecV4Board.h index 79a690e8..bd3bdb25 100644 --- a/variants/heltec_v4/HeltecV4Board.h +++ b/variants/heltec_v4/HeltecV4Board.h @@ -12,9 +12,6 @@ class HeltecV4Board : public ESP32Board { KeyValueStore* _prefs = NULL; - bool setLoRaFemLnaEnabled(bool enable); - bool isLoRaFemLnaEnabled() const; - protected: float adc_mult = ADC_MULTIPLIER; @@ -26,6 +23,9 @@ public: void begin(); void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; + bool canControlLoRaFemLna() const override { return loRaFEMControl.isLnaCanControl(); } + bool setLoRaFemLnaEnabled(bool enable) override; + bool isLoRaFemLnaEnabled() const override; void onBeforeTransmit(void) override; void onAfterTransmit(void) override; diff --git a/variants/heltec_v4_r8/HeltecV4R8Board.h b/variants/heltec_v4_r8/HeltecV4R8Board.h index 7ab29f96..c34ee449 100644 --- a/variants/heltec_v4_r8/HeltecV4R8Board.h +++ b/variants/heltec_v4_r8/HeltecV4R8Board.h @@ -13,8 +13,6 @@ class HeltecV4R8Board : public ESP32Board { KeyValueStore* _prefs = NULL; - bool setLoRaFemLnaEnabled(bool enable); - bool isLoRaFemLnaEnabled() const; protected: float adc_mult = ADC_MULTIPLIER; @@ -27,6 +25,9 @@ public: void begin(); void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; + bool canControlLoRaFemLna() const override { return loRaFEMControl.isLnaCanControl(); } + bool setLoRaFemLnaEnabled(bool enable) override; + bool isLoRaFemLnaEnabled() const override; void onBeforeTransmit(void) override; void onAfterTransmit(void) override; diff --git a/variants/heltec_v4_r8/LoRaFEMControl.h b/variants/heltec_v4_r8/LoRaFEMControl.h index 4b74c2e2..52d7a0f8 100644 --- a/variants/heltec_v4_r8/LoRaFEMControl.h +++ b/variants/heltec_v4_r8/LoRaFEMControl.h @@ -15,7 +15,7 @@ public: void setRxModeEnable(void); void setRxModeEnableWhenMCUSleep(void); void setLNAEnable(bool enabled); - bool isLnaCanControl(void) { return true; } + bool isLnaCanControl(void) const { return true; } void setLnaCanControl(bool can_control) { } bool isLNAEnabled(void) const { return lna_enabled; } LoRaFEMType getFEMType(void) const { return KCT8103L_PA; } diff --git a/variants/station_g3_esp32/StationG3Board.h b/variants/station_g3_esp32/StationG3Board.h index b4c5838c..f8cb75cb 100644 --- a/variants/station_g3_esp32/StationG3Board.h +++ b/variants/station_g3_esp32/StationG3Board.h @@ -8,10 +8,6 @@ class StationG3Board : public ESP32Board { KeyValueStore* _prefs = NULL; - bool setLoRaFemLnaEnabled(bool enable); - bool isLoRaFemLnaEnabled() const; - bool setLoRaFemPaGainEnabled(bool enable); - bool isLoRaFemPaGainEnabled() const; public: LoRaFEMControl loRaFEMControl; @@ -34,6 +30,12 @@ public: void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; + bool canControlLoRaFemLna() const override { return loRaFEMControl.canControlLNA(); } + bool setLoRaFemLnaEnabled(bool enable) override; + bool isLoRaFemLnaEnabled() const override; + bool canControlLoRaFemPaGain() const override { return loRaFEMControl.canControlPAGain(); } + bool setLoRaFemPaGainEnabled(bool enable) override; + bool isLoRaFemPaGainEnabled() const override; void setPrimaryLNAEnable(bool enabled) { loRaFEMControl.setLNAEnable(enabled); diff --git a/variants/wio-tracker-l1-1w/WioTrackerL1Board.h b/variants/wio-tracker-l1-1w/WioTrackerL1Board.h index 798145db..7dde409d 100644 --- a/variants/wio-tracker-l1-1w/WioTrackerL1Board.h +++ b/variants/wio-tracker-l1-1w/WioTrackerL1Board.h @@ -10,14 +10,14 @@ protected: bool _is_pa_enabled = false; KeyValueStore* _prefs = NULL; - bool setLoRaFemPaGainEnabled(bool enable); - bool isLoRaFemPaGainEnabled() const { return _is_pa_enabled; } - public: WioTrackerL1Board() : NRF52Board("WioTrackerL1 OTA") {} void begin(); void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; + bool canControlLoRaFemPaGain() const override { return true; } + bool setLoRaFemPaGainEnabled(bool enable) override; + bool isLoRaFemPaGainEnabled() const override { return _is_pa_enabled; } #if defined(P_LORA_TX_LED) void onBeforeTransmit() override { From a087a5198fd11b68f69dba075fe7d6fd0d72109a Mon Sep 17 00:00:00 2001 From: agessaman <adam@gessaman.com> Date: Wed, 23 Sep 2026 15:51:05 -0700 Subject: [PATCH 252/381] kiss_modem: only set USB TX buffer size on HWCDC builds USBCDC (ARDUINO_USB_MODE=0, TinyUSB) has no setTxBufferSize, which broke the Station G3 and Heltec Tracker V2 KISS builds. --- examples/kiss_modem/main.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/examples/kiss_modem/main.cpp b/examples/kiss_modem/main.cpp index 8835418d..3d815d96 100644 --- a/examples/kiss_modem/main.cpp +++ b/examples/kiss_modem/main.cpp @@ -113,7 +113,10 @@ void setup() { delay(100); #if defined(ESP32) && defined(ARDUINO_USB_CDC_ON_BOOT) && ARDUINO_USB_CDC_ON_BOOT Serial.setTxTimeoutMs(USB_TX_TIMEOUT_MS); +#if defined(ARDUINO_USB_MODE) && ARDUINO_USB_MODE + // HWCDC only; TinyUSB's USBCDC TX buffer is fixed at build time Serial.setTxBufferSize(USB_TX_BUFFER_SIZE); +#endif #endif modem = new KissModem(Serial, identity, rng, radio_driver, board, sensors); #endif From 0d648e4a18a692adf6c84fe3d8bb4737fb8e1551 Mon Sep 17 00:00:00 2001 From: agessaman <adam@gessaman.com> Date: Wed, 23 Sep 2026 16:11:29 -0700 Subject: [PATCH 253/381] kiss_modem: keep FEM replies ordered and deliverable; drop Wio FEM control - Wio Tracker L1 1W no longer advertises TX gain control: its setter drives LORA_PWR_EN, the shared LDO for the SX1262 and the PA, so "gain off" would power down the radio. - A SetFemState that arrives mid-TX is now applied after TxDone is queued, so its reply follows TxDone. - SetFemState replies (immediate or deferred) are retained until they fit in the host output queue instead of being dropped, so a change that took effect is always acknowledged. - GetFemState replies queue behind an outstanding SetFemState reply; a further SetFemState returns TxBusy until it clears. --- docs/kiss_modem_protocol.md | 2 +- examples/kiss_modem/KissModem.cpp | 64 ++++++++++---- examples/kiss_modem/KissModem.h | 8 +- test/test_kiss_modem/test_hw_controls.cpp | 83 +++++++++++++++++-- .../wio-tracker-l1-1w/WioTrackerL1Board.h | 6 +- 5 files changed, 131 insertions(+), 32 deletions(-) diff --git a/docs/kiss_modem_protocol.md b/docs/kiss_modem_protocol.md index 9b8aaa4b..1a668cc4 100644 --- a/docs/kiss_modem_protocol.md +++ b/docs/kiss_modem_protocol.md @@ -279,7 +279,7 @@ FemState response data: Example: enable RX gain without changing TX gain: apply `0x01`, value `0x01`. -If any bit in the apply mask is not in the board's capability mask (including reserved bits), the modem replies `Unsupported` and changes nothing. On success, SetFemState replies with the FemState response carrying the new state. A request received while a packet is on air is applied as soon as that transmission ends, and the FemState response is sent then; a second request during the same transmission returns `TxBusy`. Capabilities come from the board, so a board with a fixed, board-managed FEM (for example RAK3401) reports none. +If any bit in the apply mask is not in the board's capability mask (including reserved bits), the modem replies `Unsupported` and changes nothing. On success, SetFemState replies with the FemState response carrying the new state. A SetFemState received while a packet is on air (before its TxDone is queued) is held and applied after TxDone, so its FemState response follows TxDone. While a SetFemState is held or its response is still waiting for output space, GetFemState responses are queued behind it in order, and a further SetFemState returns `TxBusy`. Capabilities come from the board, so a board with a fixed, board-managed FEM (for example RAK3401) reports none. The setting is not persisted; the board's power-on default applies after reboot. diff --git a/examples/kiss_modem/KissModem.cpp b/examples/kiss_modem/KissModem.cpp index 5b61e83c..af678bbe 100644 --- a/examples/kiss_modem/KissModem.cpp +++ b/examples/kiss_modem/KissModem.cpp @@ -27,6 +27,9 @@ KissModem::KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& r _fem_deferred = false; _fem_deferred_apply = 0; _fem_deferred_value = 0; + _fem_reply_pending = false; + _fem_reply_ok = false; + _fem_deferred_gets = 0; resetOutputQueue(); } @@ -37,6 +40,8 @@ void KissModem::begin() { _has_pending_tx = false; _tx_state = TX_IDLE; _fem_deferred = false; + _fem_reply_pending = false; + _fem_deferred_gets = 0; _next_agc_reset_ms = millis() + (uint32_t)_agc_reset_interval_sec * 1000; resetOutputQueue(); } @@ -811,12 +816,16 @@ uint8_t KissModem::femValueMask() const { return mask; } -void KissModem::writeFemState() { +bool KissModem::queueFemReply(bool ok, bool mark_busy_error) { + if (!ok) { + const uint8_t err = HW_ERR_UNSUPPORTED; + return queueHardwareFrame(HW_RESP_ERROR, &err, 1, mark_busy_error); + } uint8_t buf[2] = { femCapabilityMask(), femValueMask() }; - writeHardwareFrame(HW_RESP(HW_CMD_GET_FEM_STATE), buf, 2); + return queueHardwareFrame(HW_RESP(HW_CMD_GET_FEM_STATE), buf, 2, mark_busy_error); } -void KissModem::applyFemState(uint8_t apply_mask, uint8_t value_mask) { +bool KissModem::applyFemState(uint8_t apply_mask, uint8_t value_mask) { bool ok = true; if (apply_mask & HW_FEM_RX_GAIN) { ok &= _board.setLoRaFemLnaEnabled((value_mask & HW_FEM_RX_GAIN) != 0); @@ -824,17 +833,26 @@ void KissModem::applyFemState(uint8_t apply_mask, uint8_t value_mask) { if (apply_mask & HW_FEM_TX_GAIN) { ok &= _board.setLoRaFemPaGainEnabled((value_mask & HW_FEM_TX_GAIN) != 0); } - if (ok) { - writeFemState(); - } else { - writeHardwareError(HW_ERR_UNSUPPORTED); - } + return ok; } void KissModem::processDeferredFem() { - if (!_fem_deferred || _tx_state == TX_SENDING) return; - _fem_deferred = false; - applyFemState(_fem_deferred_apply, _fem_deferred_value); + // wait for TxDone to be queued so the host sees the TX result before the FEM change + if (_fem_deferred && _tx_state != TX_SENDING && _tx_state != TX_DONE_PENDING) { + _fem_reply_ok = applyFemState(_fem_deferred_apply, _fem_deferred_value); + _fem_deferred = false; + _fem_reply_pending = true; + } + if (_fem_deferred) return; + // replies are retained until queued, and GetFemState replies stay behind the Set reply + if (_fem_reply_pending) { + if (!queueFemReply(_fem_reply_ok, false)) return; + _fem_reply_pending = false; + } + while (_fem_deferred_gets > 0) { + if (!queueFemReply(true, false)) return; + _fem_deferred_gets--; + } } void KissModem::handleSetFemState(const uint8_t* data, uint16_t len) { @@ -849,20 +867,30 @@ void KissModem::handleSetFemState(const uint8_t* data, uint16_t len) { writeHardwareError(HW_ERR_UNSUPPORTED); return; } - if (_tx_state == TX_SENDING) { + if (isFemReplyQueued()) { + writeHardwareError(HW_ERR_TX_BUSY); + return; + } + if (_tx_state == TX_SENDING || _tx_state == TX_DONE_PENDING) { // board setters drive FEM pins directly; changing them mid-packet would corrupt the TX - if (_fem_deferred) { - writeHardwareError(HW_ERR_TX_BUSY); - return; - } _fem_deferred = true; _fem_deferred_apply = apply_mask; _fem_deferred_value = value_mask; return; } - applyFemState(apply_mask, value_mask); + _fem_reply_ok = applyFemState(apply_mask, value_mask); + _fem_reply_pending = true; + processDeferredFem(); } void KissModem::handleGetFemState() { - writeFemState(); + if (isFemReplyQueued()) { + if (_fem_deferred_gets == UINT8_MAX) { + writeHardwareError(HW_ERR_TX_BUSY); + return; + } + _fem_deferred_gets++; + return; + } + queueFemReply(true, true); } diff --git a/examples/kiss_modem/KissModem.h b/examples/kiss_modem/KissModem.h index 751fb336..25184217 100644 --- a/examples/kiss_modem/KissModem.h +++ b/examples/kiss_modem/KissModem.h @@ -163,6 +163,9 @@ class KissModem { bool _fem_deferred; uint8_t _fem_deferred_apply; uint8_t _fem_deferred_value; + bool _fem_reply_pending; + bool _fem_reply_ok; + uint8_t _fem_deferred_gets; uint8_t _tx_frame_buf[KISS_TX_FRAME_QUEUE_DEPTH][KISS_MAX_ENCODED_FRAME_SIZE]; uint16_t _tx_frame_len[KISS_TX_FRAME_QUEUE_DEPTH]; uint16_t _tx_frame_written[KISS_TX_FRAME_QUEUE_DEPTH]; @@ -192,8 +195,9 @@ class KissModem { void maybeResetAgc(); uint8_t femCapabilityMask() const; uint8_t femValueMask() const; - void writeFemState(); - void applyFemState(uint8_t apply_mask, uint8_t value_mask); + bool queueFemReply(bool ok, bool mark_busy_error); + bool applyFemState(uint8_t apply_mask, uint8_t value_mask); + bool isFemReplyQueued() const { return _fem_deferred || _fem_reply_pending || _fem_deferred_gets > 0; } void processDeferredFem(); void handleGetIdentity(); diff --git a/test/test_kiss_modem/test_hw_controls.cpp b/test/test_kiss_modem/test_hw_controls.cpp index ad6f1e36..614ccc24 100644 --- a/test/test_kiss_modem/test_hw_controls.cpp +++ b/test/test_kiss_modem/test_hw_controls.cpp @@ -13,8 +13,9 @@ public: for (uint8_t b : bytes) _rx.push(b); } - int availableForWrite() override { return 4096; } + int availableForWrite() override { return blocked ? 0 : 4096; } size_t write(const uint8_t* buffer, size_t size) override { + if (blocked) return 0; _writes.insert(_writes.end(), buffer, buffer + size); return size; } @@ -49,6 +50,8 @@ public: return frames; } + bool blocked = false; + private: std::queue<uint8_t> _rx; std::vector<uint8_t> _writes; @@ -254,7 +257,7 @@ TEST_F(KissHwControlTest, FemShortPayloadIsInvalidLength) { EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN}), (std::vector<uint8_t>{HW_RESP_ERROR, HW_ERR_INVALID_LENGTH})); } -TEST_F(KissHwControlTest, FemSetDuringTxIsDeferredUntilTxCompletes) { +TEST_F(KissHwControlTest, FemSetDuringTxIsDeferredUntilAfterTxDone) { board.has_lna = true; startTxAndHold(); serial.takeHardwareFrames(); @@ -264,15 +267,79 @@ TEST_F(KissHwControlTest, FemSetDuringTxIsDeferredUntilTxCompletes) { EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, 0}), (std::vector<uint8_t>{HW_RESP_ERROR, HW_ERR_TX_BUSY})); radio.send_complete = true; + modem.loop(); // TX done -> TX_DONE_PENDING; FEM still held + modem.loop(); // TxDone queued -> idle; FEM applied + auto frames = serial.takeHardwareFrames(); + ASSERT_EQ(frames.size(), 2U); + EXPECT_EQ(frames[0], (std::vector<uint8_t>{HW_RESP_TX_DONE, 0x01})); + EXPECT_EQ(frames[1], (std::vector<uint8_t>{0x9F, 0x01, 0x01})); + EXPECT_TRUE(board.lna); + EXPECT_EQ(board.lna_sets, 1); +} + +TEST_F(KissHwControlTest, FemGetDuringDeferredSetIsAnsweredAfterSet) { + board.has_lna = true; + startTxAndHold(); + serial.takeHardwareFrames(); + + EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}).empty()); + EXPECT_TRUE(hw({HW_CMD_GET_FEM_STATE}).empty()); + + radio.send_complete = true; + modem.loop(); modem.loop(); auto frames = serial.takeHardwareFrames(); - ASSERT_EQ(frames.size(), 1U); - EXPECT_EQ(frames[0], (std::vector<uint8_t>{0x9F, 0x01, 0x01})); - EXPECT_TRUE(board.lna); - modem.loop(); - frames = serial.takeHardwareFrames(); - ASSERT_EQ(frames.size(), 1U); + ASSERT_EQ(frames.size(), 3U); EXPECT_EQ(frames[0], (std::vector<uint8_t>{HW_RESP_TX_DONE, 0x01})); + EXPECT_EQ(frames[1], (std::vector<uint8_t>{0x9F, 0x01, 0x01})); + EXPECT_EQ(frames[2], (std::vector<uint8_t>{0x9F, 0x01, 0x01})); +} + +TEST_F(KissHwControlTest, DeferredFemRepliesSurviveHostBackpressure) { + board.has_lna = true; + hw({HW_CMD_SET_SIGNAL_REPORT, 0}); // one output frame per RX packet + startTxAndHold(); + serial.takeHardwareFrames(); + EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}).empty()); + EXPECT_TRUE(hw({HW_CMD_GET_FEM_STATE}).empty()); + + // with writes blocked: RX packet takes slot 1, TxDone slot 2, so the Set reply cannot be queued + serial.blocked = true; + static constexpr uint8_t PKT[] = {0x01}; + modem.onPacketReceived(0, 0, PKT, sizeof(PKT)); + radio.send_complete = true; + for (int i = 0; i < 5; i++) modem.loop(); + EXPECT_TRUE(board.lna); // applied once TxDone was queued, reply still held + + serial.blocked = false; + for (int i = 0; i < 5; i++) modem.loop(); + EXPECT_EQ(board.lna_sets, 1); + + auto frames = serial.takeHardwareFrames(); + ASSERT_EQ(frames.size(), 3U); + EXPECT_EQ(frames[0], (std::vector<uint8_t>{HW_RESP_TX_DONE, 0x01})); + EXPECT_EQ(frames[1], (std::vector<uint8_t>{0x9F, 0x01, 0x01})); + EXPECT_EQ(frames[2], (std::vector<uint8_t>{0x9F, 0x01, 0x01})); +} + +TEST_F(KissHwControlTest, ImmediateFemReplySurvivesHostBackpressure) { + board.has_lna = true; + hw({HW_CMD_SET_SIGNAL_REPORT, 0}); + + serial.blocked = true; + static constexpr uint8_t PKT[] = {0x01}; + modem.onPacketReceived(0, 0, PKT, sizeof(PKT)); + modem.onPacketReceived(0, 0, PKT, sizeof(PKT)); // output queue now full + serial.pushRx({KISS_FEND, KISS_CMD_SETHARDWARE, HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN, KISS_FEND}); + modem.loop(); + EXPECT_TRUE(board.lna); + + serial.blocked = false; + for (int i = 0; i < 5; i++) modem.loop(); + auto frames = serial.takeHardwareFrames(); + ASSERT_EQ(frames.size(), 1U); // FemState, not TxBusy + EXPECT_EQ(frames[0], (std::vector<uint8_t>{0x9F, 0x01, 0x01})); + EXPECT_EQ(board.lna_sets, 1); } } // namespace diff --git a/variants/wio-tracker-l1-1w/WioTrackerL1Board.h b/variants/wio-tracker-l1-1w/WioTrackerL1Board.h index 7dde409d..798145db 100644 --- a/variants/wio-tracker-l1-1w/WioTrackerL1Board.h +++ b/variants/wio-tracker-l1-1w/WioTrackerL1Board.h @@ -10,14 +10,14 @@ protected: bool _is_pa_enabled = false; KeyValueStore* _prefs = NULL; + bool setLoRaFemPaGainEnabled(bool enable); + bool isLoRaFemPaGainEnabled() const { return _is_pa_enabled; } + public: WioTrackerL1Board() : NRF52Board("WioTrackerL1 OTA") {} void begin(); void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; - bool canControlLoRaFemPaGain() const override { return true; } - bool setLoRaFemPaGainEnabled(bool enable) override; - bool isLoRaFemPaGainEnabled() const override { return _is_pa_enabled; } #if defined(P_LORA_TX_LED) void onBeforeTransmit() override { From 8cefda9612011bd35b592cd610c40953c8e7815a Mon Sep 17 00:00:00 2001 From: agessaman <adam@gessaman.com> Date: Wed, 23 Sep 2026 16:59:39 -0700 Subject: [PATCH 254/381] kiss_modem: add radio chip boosted RX gain control Add SetRxBoostedGain (0x20) / GetRxBoostedGain (0x21, reply 0xA1) and capability bit 3, the KISS equivalent of the radio.rxgain CLI setting. It is separate from FEM RX gain; a board may support either or both. - Support is declared by the driver via a new RadioLibWrapper::supportsRxBoostedGain() (SX1262, SX1268, LLCC68, LR1110, LR1121, LR2021), so nothing is written to the radio at boot. - The set is refused with TxBusy during TX or while host output is backed up. Otherwise any completed RX packet is delivered first, because some drivers (LR2021) drop to standby to apply the gain. - The reply always carries the state read back from the radio. Driver fixes found along the way, which also affect the radio.rxgain CLI in regular firmware: - CustomLR2021 never updated its cached gain state, so the getter always reported off. It now tracks the applied level per RX path and rolls RadioLib's cached level back if a write fails. - CustomLR1110/LR1121 cached the requested state even when the write failed. - lr11x0ResetAGC only reapplied the gain when RX_BOOSTED_GAIN was defined, so a runtime setting was lost on the next AGC reset. --- docs/kiss_modem_protocol.md | 16 ++- examples/kiss_modem/KissModem.cpp | 45 +++++++++ examples/kiss_modem/KissModem.h | 18 ++++ examples/kiss_modem/main.cpp | 30 ++++-- src/helpers/radiolib/CustomLLCC68Wrapper.h | 1 + src/helpers/radiolib/CustomLR1110.h | 5 +- src/helpers/radiolib/CustomLR1110Wrapper.h | 1 + src/helpers/radiolib/CustomLR1121.h | 5 +- src/helpers/radiolib/CustomLR1121Wrapper.h | 1 + src/helpers/radiolib/CustomLR2021.h | 20 +++- src/helpers/radiolib/CustomLR2021Wrapper.h | 1 + src/helpers/radiolib/CustomSX1262Wrapper.h | 1 + src/helpers/radiolib/CustomSX1268Wrapper.h | 1 + src/helpers/radiolib/LR11x0Reset.h | 3 +- src/helpers/radiolib/RadioLibWrappers.h | 1 + test/test_kiss_modem/test_hw_controls.cpp | 112 +++++++++++++++++++++ 16 files changed, 245 insertions(+), 16 deletions(-) diff --git a/docs/kiss_modem_protocol.md b/docs/kiss_modem_protocol.md index 1a668cc4..cb7be8b3 100644 --- a/docs/kiss_modem_protocol.md +++ b/docs/kiss_modem_protocol.md @@ -123,10 +123,12 @@ MeshCore-specific functionality uses the standard KISS SetHardware command. The | GetAgcResetInterval | `0x1D` | - | | SetFemState | `0x1E` | Apply mask (1) + Value mask (1) | | GetFemState | `0x1F` | - | +| SetRxBoostedGain | `0x20` | Enable (1): 0x00=disable, nonzero=enable | +| GetRxBoostedGain | `0x21` | - | ### Response Sub-commands (TNC to Host) -Response codes use the high-bit convention: `response = command | 0x80`. Generic and unsolicited responses use the `0xF0`+ range. Set commands that report state (SetSignalReport, SetAgcResetInterval, SetFemState) reply with the matching Get response, so `0x9C` and `0x9E` are never sent. +Response codes use the high-bit convention: `response = command | 0x80`. Generic and unsolicited responses use the `0xF0`+ range. Set commands that report state (SetSignalReport, SetAgcResetInterval, SetFemState, SetRxBoostedGain) reply with the matching Get response, so `0x9C`, `0x9E` and `0xA0` are never sent. | Sub-command | Value | Data | |--------------|--------|-----------------------------------------| @@ -155,6 +157,7 @@ Response codes use the high-bit convention: `response = command | 0x80`. Generic | Capabilities | `0x9B` | Feature bits (4) | | AgcResetInterval | `0x9D` | Effective seconds (2) | | FemState | `0x9F` | Capability mask (1) + Value mask (1) | +| RxBoostedGain | `0xA1` | Status (1): 0x00=disabled, 0x01=enabled | | OK | `0xF0` | - | | Error | `0xF1` | Error code (1) | | TxDone | `0xF8` | Result (1): 0x00=failed, 0x01=success | @@ -239,6 +242,7 @@ All values little-endian. Hosts should probe capabilities rather than infer them | 0 | `0x01` | AGC reset interval control (always set) | | 1 | `0x02` | External FEM RX (LNA) gain control | | 2 | `0x04` | External FEM TX (PA) gain control | +| 3 | `0x08` | Radio chip boosted RX gain control | Remaining bits are reserved and sent as 0. @@ -283,6 +287,16 @@ If any bit in the apply mask is not in the board's capability mask (including re The setting is not persisted; the board's power-on default applies after reboot. +### RX Boosted Gain (SetRxBoostedGain / RxBoostedGain response) + +Controls the radio chip's own boosted RX gain mode (SX1262, SX1268, LLCC68, LR11x0, LR2021), the equivalent of the MeshCore `radio.rxgain` setting. This is independent of the external FEM RX gain controlled by SetFemState; a board can support either, both or neither. + +| Field | Size | Description | +|--------|--------|------------------------------------| +| Status | 1 byte | 0x00 = power-saving, 0x01 = boosted | + +SetRxBoostedGain always replies with the RxBoostedGain response carrying the effective state read back from the radio; if it differs from the requested value, the change did not take effect. Some radios must drop to standby to apply it, so the modem replies `TxBusy` and changes nothing while a packet is on air or host output is backed up; retry later. Before applying, any completed received packet is delivered to the host first. A packet still being received at that moment can be lost. Radios whose driver has no boosted RX gain control (for example SX127x and STM32WLx) do not set capability bit 3 and reply `Unsupported` to both commands. The power-on default is the build's `SX126X_RX_BOOSTED_GAIN` setting; the value is not persisted, and periodic AGC resets preserve it. + ### Stats (Stats response) All values little-endian. diff --git a/examples/kiss_modem/KissModem.cpp b/examples/kiss_modem/KissModem.cpp index af678bbe..221c40b1 100644 --- a/examples/kiss_modem/KissModem.cpp +++ b/examples/kiss_modem/KissModem.cpp @@ -20,6 +20,9 @@ KissModem::KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& r _setTxPowerCallback = nullptr; _getCurrentRssiCallback = nullptr; _getStatsCallback = nullptr; + _setRxBoostedGainCallback = nullptr; + _getRxBoostedGainCallback = nullptr; + _pollRxCallback = nullptr; _config = {0, 0, 0, 0, 0}; _signal_report_enabled = true; _agc_reset_interval_sec = KISS_AGC_RESET_DEFAULT_SEC; @@ -422,6 +425,12 @@ void KissModem::handleHardwareCommand(uint8_t sub_cmd, const uint8_t* data, uint case HW_CMD_GET_FEM_STATE: handleGetFemState(); break; + case HW_CMD_SET_RX_BOOSTED_GAIN: + handleSetRxBoostedGain(data, len); + break; + case HW_CMD_GET_RX_BOOSTED_GAIN: + handleGetRxBoostedGain(); + break; default: writeHardwareError(HW_ERR_UNKNOWN_CMD); break; @@ -778,6 +787,7 @@ void KissModem::handleGetCapabilities() { uint32_t caps = HW_CAP_AGC_RESET; if (_board.canControlLoRaFemLna()) caps |= HW_CAP_FEM_RX_GAIN; if (_board.canControlLoRaFemPaGain()) caps |= HW_CAP_FEM_TX_GAIN; + if (_setRxBoostedGainCallback && _getRxBoostedGainCallback) caps |= HW_CAP_RX_BOOSTED_GAIN; uint8_t buf[4] = { (uint8_t)caps, (uint8_t)(caps >> 8), (uint8_t)(caps >> 16), (uint8_t)(caps >> 24) }; writeHardwareFrame(HW_RESP(HW_CMD_GET_CAPABILITIES), buf, 4); } @@ -894,3 +904,38 @@ void KissModem::handleGetFemState() { } queueFemReply(true, true); } + +void KissModem::handleSetRxBoostedGain(const uint8_t* data, uint16_t len) { + if (len < 1) { + writeHardwareError(HW_ERR_INVALID_LENGTH); + return; + } + if (!_setRxBoostedGainCallback || !_getRxBoostedGainCallback) { + writeHardwareError(HW_ERR_UNSUPPORTED); + return; + } + // some drivers (LR2021) drop to standby to apply the gain, which would abort a TX and + // discard a completed RX packet; so never during TX, and only after draining RX + if (_tx_state == TX_SENDING || isHostOutputBackedUp()) { + writeHardwareError(HW_ERR_TX_BUSY); + return; + } + if (_pollRxCallback) _pollRxCallback(); + tryFlushFrames(); + if (_tx_frame_count >= KISS_TX_FRAME_QUEUE_DEPTH) { + writeHardwareError(HW_ERR_TX_BUSY); // no room left for the reply; change nothing + return; + } + // always reply with the state read back, so a failed or partial write is never misreported + _setRxBoostedGainCallback(data[0] != 0x00); + handleGetRxBoostedGain(); +} + +void KissModem::handleGetRxBoostedGain() { + if (!_getRxBoostedGainCallback) { + writeHardwareError(HW_ERR_UNSUPPORTED); + return; + } + uint8_t val = _getRxBoostedGainCallback() ? 0x01 : 0x00; + writeHardwareFrame(HW_RESP(HW_CMD_GET_RX_BOOSTED_GAIN), &val, 1); +} diff --git a/examples/kiss_modem/KissModem.h b/examples/kiss_modem/KissModem.h index 25184217..ffe89191 100644 --- a/examples/kiss_modem/KissModem.h +++ b/examples/kiss_modem/KissModem.h @@ -67,6 +67,8 @@ #define HW_CMD_GET_AGC_RESET_INTERVAL 0x1D #define HW_CMD_SET_FEM_STATE 0x1E #define HW_CMD_GET_FEM_STATE 0x1F +#define HW_CMD_SET_RX_BOOSTED_GAIN 0x20 +#define HW_CMD_GET_RX_BOOSTED_GAIN 0x21 /* Response code = command code | 0x80. Generic / unsolicited use 0xF0+. */ #define HW_RESP(cmd) ((cmd) | 0x80) @@ -92,6 +94,7 @@ #define HW_CAP_AGC_RESET (1UL << 0) #define HW_CAP_FEM_RX_GAIN (1UL << 1) #define HW_CAP_FEM_TX_GAIN (1UL << 2) +#define HW_CAP_RX_BOOSTED_GAIN (1UL << 3) /* SetFemState / GetFemState mask bits */ #define HW_FEM_RX_GAIN (1 << 0) @@ -107,6 +110,9 @@ typedef void (*SetRadioCallback)(float freq, float bw, uint8_t sf, uint8_t cr); typedef void (*SetTxPowerCallback)(uint8_t power); typedef float (*GetCurrentRssiCallback)(); typedef void (*GetStatsCallback)(uint32_t* rx, uint32_t* tx, uint32_t* errors); +typedef bool (*SetRxBoostedGainCallback)(bool enable); +typedef bool (*GetRxBoostedGainCallback)(); +typedef void (*PollRxCallback)(); struct RadioConfig { uint32_t freq_hz; @@ -155,6 +161,9 @@ class KissModem { SetTxPowerCallback _setTxPowerCallback; GetCurrentRssiCallback _getCurrentRssiCallback; GetStatsCallback _getStatsCallback; + SetRxBoostedGainCallback _setRxBoostedGainCallback; + GetRxBoostedGainCallback _getRxBoostedGainCallback; + PollRxCallback _pollRxCallback; RadioConfig _config; bool _signal_report_enabled; @@ -231,6 +240,8 @@ class KissModem { void handleGetAgcResetInterval(); void handleSetFemState(const uint8_t* data, uint16_t len); void handleGetFemState(); + void handleSetRxBoostedGain(const uint8_t* data, uint16_t len); + void handleGetRxBoostedGain(); public: KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& rng, @@ -243,6 +254,13 @@ public: void setTxPowerCallback(SetTxPowerCallback cb) { _setTxPowerCallback = cb; } void setGetCurrentRssiCallback(GetCurrentRssiCallback cb) { _getCurrentRssiCallback = cb; } void setGetStatsCallback(GetStatsCallback cb) { _getStatsCallback = cb; } + // Only register these when the radio supports boosted RX gain; they define the capability. + // Delivers any completed RX packet to the host; called before settings that restart the receiver. + void setPollRxCallback(PollRxCallback cb) { _pollRxCallback = cb; } + void setRxBoostedGainCallbacks(SetRxBoostedGainCallback set_cb, GetRxBoostedGainCallback get_cb) { + _setRxBoostedGainCallback = set_cb; + _getRxBoostedGainCallback = get_cb; + } void onPacketReceived(int8_t snr, int8_t rssi, const uint8_t* packet, uint16_t len); bool isTxBusy() const { return _tx_state != TX_IDLE; } diff --git a/examples/kiss_modem/main.cpp b/examples/kiss_modem/main.cpp index 3d815d96..dd1ee14f 100644 --- a/examples/kiss_modem/main.cpp +++ b/examples/kiss_modem/main.cpp @@ -73,6 +73,24 @@ void onGetStats(uint32_t* rx, uint32_t* tx, uint32_t* errors) { *errors = radio_driver.getPacketsRecvErrors(); } +void pollRadioRx() { + uint8_t rx_buf[256]; + int rx_len = radio_driver.recvRaw(rx_buf, sizeof(rx_buf)); + if (rx_len > 0) { + int8_t snr = (int8_t)(radio_driver.getLastSNR() * 4); + int8_t rssi = (int8_t)radio_driver.getLastRSSI(); + modem->onPacketReceived(snr, rssi, rx_buf, rx_len); + } +} + +bool onSetRxBoostedGain(bool enable) { + return radio_driver.setRxBoostedGainMode(enable); +} + +bool onGetRxBoostedGain() { + return radio_driver.getRxBoostedGainMode(); +} + void setup() { board.begin(); @@ -125,6 +143,10 @@ void setup() { modem->setTxPowerCallback(onSetTxPower); modem->setGetCurrentRssiCallback(onGetCurrentRssi); modem->setGetStatsCallback(onGetStats); + modem->setPollRxCallback(pollRadioRx); + if (radio_driver.supportsRxBoostedGain()) { + modem->setRxBoostedGainCallbacks(onSetRxBoostedGain, onGetRxBoostedGain); + } modem->begin(); board.onBootComplete(); @@ -134,13 +156,7 @@ void loop() { modem->loop(); if (!modem->isActuallyTransmitting() && !modem->isHostOutputBackedUp()) { - uint8_t rx_buf[256]; - int rx_len = radio_driver.recvRaw(rx_buf, sizeof(rx_buf)); - if (rx_len > 0) { - int8_t snr = (int8_t)(radio_driver.getLastSNR() * 4); - int8_t rssi = (int8_t)radio_driver.getLastRSSI(); - modem->onPacketReceived(snr, rssi, rx_buf, rx_len); - } + pollRadioRx(); } board.loop(); diff --git a/src/helpers/radiolib/CustomLLCC68Wrapper.h b/src/helpers/radiolib/CustomLLCC68Wrapper.h index ae0fe0a2..89d5e1bc 100644 --- a/src/helpers/radiolib/CustomLLCC68Wrapper.h +++ b/src/helpers/radiolib/CustomLLCC68Wrapper.h @@ -37,6 +37,7 @@ public: void doResetAGC() override { sx126xResetAGC((SX126x *)_radio); } + bool supportsRxBoostedGain() const override { return true; } bool setRxBoostedGainMode(bool en) override { return ((CustomLLCC68 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE; } diff --git a/src/helpers/radiolib/CustomLR1110.h b/src/helpers/radiolib/CustomLR1110.h index f0fde435..0d430c1d 100644 --- a/src/helpers/radiolib/CustomLR1110.h +++ b/src/helpers/radiolib/CustomLR1110.h @@ -39,8 +39,9 @@ class CustomLR1110 : public LR1110 { float getFreqMHz() const { return freqMHz; } int16_t setRxBoostedGainMode(bool en) { - _rx_boosted = en; - return LR1110::setRxBoostedGainMode(en); + int16_t status = LR1110::setRxBoostedGainMode(en); + if (status == RADIOLIB_ERR_NONE) _rx_boosted = en; + return status; } bool getRxBoostedGainMode() const { return _rx_boosted; } diff --git a/src/helpers/radiolib/CustomLR1110Wrapper.h b/src/helpers/radiolib/CustomLR1110Wrapper.h index e7aaeb93..bf2e8370 100644 --- a/src/helpers/radiolib/CustomLR1110Wrapper.h +++ b/src/helpers/radiolib/CustomLR1110Wrapper.h @@ -43,6 +43,7 @@ public: uint8_t getSpreadingFactor() const override { return ((CustomLR1110 *)_radio)->getSpreadingFactor(); } + bool supportsRxBoostedGain() const override { return true; } bool setRxBoostedGainMode(bool en) override { return ((CustomLR1110 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE; } diff --git a/src/helpers/radiolib/CustomLR1121.h b/src/helpers/radiolib/CustomLR1121.h index 67e3b52a..eaa55be8 100644 --- a/src/helpers/radiolib/CustomLR1121.h +++ b/src/helpers/radiolib/CustomLR1121.h @@ -39,8 +39,9 @@ class CustomLR1121 : public LR1121 { float getFreqMHz() const { return freqMHz; } int16_t setRxBoostedGainMode(bool en) { - _rx_boosted = en; - return LR1121::setRxBoostedGainMode(en); + int16_t status = LR1121::setRxBoostedGainMode(en); + if (status == RADIOLIB_ERR_NONE) _rx_boosted = en; + return status; } bool getRxBoostedGainMode() const { return _rx_boosted; } diff --git a/src/helpers/radiolib/CustomLR1121Wrapper.h b/src/helpers/radiolib/CustomLR1121Wrapper.h index 5a754cee..d5620b45 100644 --- a/src/helpers/radiolib/CustomLR1121Wrapper.h +++ b/src/helpers/radiolib/CustomLR1121Wrapper.h @@ -44,6 +44,7 @@ public: uint8_t getSpreadingFactor() const override { return ((CustomLR1121 *)_radio)->getSpreadingFactor(); } + bool supportsRxBoostedGain() const override { return true; } bool setRxBoostedGainMode(bool en) override { return ((CustomLR1121 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE; } diff --git a/src/helpers/radiolib/CustomLR2021.h b/src/helpers/radiolib/CustomLR2021.h index 0255b93c..d08d3dc7 100644 --- a/src/helpers/radiolib/CustomLR2021.h +++ b/src/helpers/radiolib/CustomLR2021.h @@ -8,7 +8,9 @@ class CustomLR2021 : public LR2021 { uint32_t _maxPayloadMillis = 3934; uint32_t _activityAt = 0; bool _headerSeen = false; - bool _rx_boosted = false; + // last applied gain level per RX path, mirroring RadioLib's gainModeLf/gainModeHf defaults + uint8_t _rx_gain_lf = RADIOLIB_LR2021_RX_BOOST_LF; + uint8_t _rx_gain_hf = RADIOLIB_LR2021_RX_BOOST_HF; public: CustomLR2021(Module *mod) : LR2021(mod) { irqDioNum = LR2021_IRQ_DIO; } @@ -68,7 +70,21 @@ class CustomLR2021 : public LR2021 { float getFreqMHz() const { return freqMHz; } - bool getRxBoostedGainMode() const { return _rx_boosted; } + bool isHighFreqPath() const { return freqMHz > RADIOLIB_LR2021_LF_CUTOFF_FREQ; } + + int16_t setRxBoostedGainMode(uint8_t level) { + uint8_t& applied = isHighFreqPath() ? _rx_gain_hf : _rx_gain_lf; + int16_t status = LR2021::setRxBoostedGainMode(level); + if (status == RADIOLIB_ERR_NONE) { + applied = level; + } else { + // RadioLib caches the level before sending it; restore it so the next startReceive keeps the old gain + LR2021::setRxBoostedGainMode(applied); + } + return status; + } + + bool getRxBoostedGainMode() const { return (isHighFreqPath() ? _rx_gain_hf : _rx_gain_lf) != 0; } int16_t startReceive() override { // include the PREAMBLE_DETECTED irq bit in reported flags diff --git a/src/helpers/radiolib/CustomLR2021Wrapper.h b/src/helpers/radiolib/CustomLR2021Wrapper.h index 8299e2bf..ca0affb6 100644 --- a/src/helpers/radiolib/CustomLR2021Wrapper.h +++ b/src/helpers/radiolib/CustomLR2021Wrapper.h @@ -93,6 +93,7 @@ public: uint8_t getSpreadingFactor() const override { return ((CustomLR2021 *)_radio)->getSpreadingFactor(); } + bool supportsRxBoostedGain() const override { return true; } bool setRxBoostedGainMode(bool en) override { ((CustomLR2021 *)_radio)->standby(); // LR2021 must be in standby to accept setRxBoostedGainMode int16_t status = ((CustomLR2021 *)_radio)->setRxBoostedGainMode(en ? LR2021_RX_BOOST_LEVEL: 0); diff --git a/src/helpers/radiolib/CustomSX1262Wrapper.h b/src/helpers/radiolib/CustomSX1262Wrapper.h index be314471..0caf0f1f 100644 --- a/src/helpers/radiolib/CustomSX1262Wrapper.h +++ b/src/helpers/radiolib/CustomSX1262Wrapper.h @@ -41,6 +41,7 @@ public: ((CustomSX1262 *)_radio)->sleep(false); } + bool supportsRxBoostedGain() const override { return true; } bool setRxBoostedGainMode(bool en) override { return ((CustomSX1262 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE; } diff --git a/src/helpers/radiolib/CustomSX1268Wrapper.h b/src/helpers/radiolib/CustomSX1268Wrapper.h index 70f5dabd..9fef1184 100644 --- a/src/helpers/radiolib/CustomSX1268Wrapper.h +++ b/src/helpers/radiolib/CustomSX1268Wrapper.h @@ -38,6 +38,7 @@ public: } uint8_t getSpreadingFactor() const override { return ((CustomSX1268 *)_radio)->spreadingFactor; } + bool supportsRxBoostedGain() const override { return true; } bool setRxBoostedGainMode(bool en) override { return ((CustomSX1268 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE; } diff --git a/src/helpers/radiolib/LR11x0Reset.h b/src/helpers/radiolib/LR11x0Reset.h index cdfc1f9f..3a10ff00 100644 --- a/src/helpers/radiolib/LR11x0Reset.h +++ b/src/helpers/radiolib/LR11x0Reset.h @@ -15,7 +15,6 @@ inline void lr11x0ResetAGC(LR11x0* radio, float freqMHz, bool rx_boost_gain) { // Re-calibrate for the actual operating frequency (band=4MHz matches RadioLib default). radio->calibrateImageRejection(freqMHz - 4.0f, freqMHz + 4.0f); -#ifdef RX_BOOSTED_GAIN + // always reapply: the gain may have been changed at runtime even when no build default is set radio->setRxBoostedGainMode(rx_boost_gain); -#endif } diff --git a/src/helpers/radiolib/RadioLibWrappers.h b/src/helpers/radiolib/RadioLibWrappers.h index 77dd9311..9b367ee4 100644 --- a/src/helpers/radiolib/RadioLibWrappers.h +++ b/src/helpers/radiolib/RadioLibWrappers.h @@ -75,6 +75,7 @@ public: float packetScore(float snr, int packet_len) override { return packetScoreInt(snr, 10, packet_len); } // assume sf=10 + virtual bool supportsRxBoostedGain() const { return false; } virtual bool setRxBoostedGainMode(bool) { return false; } virtual bool getRxBoostedGainMode() const { return false; } diff --git a/test/test_kiss_modem/test_hw_controls.cpp b/test/test_kiss_modem/test_hw_controls.cpp index 614ccc24..37b1b929 100644 --- a/test/test_kiss_modem/test_hw_controls.cpp +++ b/test/test_kiss_modem/test_hw_controls.cpp @@ -149,6 +149,29 @@ protected: } }; +bool g_rx_boost = false; +bool g_rx_boost_set_ok = true; +int g_rx_boost_sets = 0; +bool fakeSetRxBoost(bool en) { + g_rx_boost_sets++; + if (!g_rx_boost_set_ok) return false; + g_rx_boost = en; + return true; +} +bool fakeGetRxBoost() { return g_rx_boost; } + +KissModem* g_poll_modem = nullptr; +bool g_poll_has_packet = false; +int g_polls = 0; +void fakePollRx() { + g_polls++; + if (g_poll_has_packet && g_poll_modem) { + static constexpr uint8_t PKT[] = {0x55}; + g_poll_has_packet = false; + g_poll_modem->onPacketReceived(4, -80, PKT, sizeof(PKT)); + } +} + const std::vector<uint8_t> ERR_UNSUPPORTED = {HW_RESP_ERROR, HW_ERR_UNSUPPORTED}; TEST_F(KissHwControlTest, VersionIsTwo) { @@ -342,4 +365,93 @@ TEST_F(KissHwControlTest, ImmediateFemReplySurvivesHostBackpressure) { EXPECT_EQ(board.lna_sets, 1); } +class KissRxBoostTest : public KissHwControlTest { +protected: + KissRxBoostTest() { + g_rx_boost = true; + g_rx_boost_set_ok = true; + g_rx_boost_sets = 0; + modem.setRxBoostedGainCallbacks(fakeSetRxBoost, fakeGetRxBoost); + g_poll_modem = &modem; + g_poll_has_packet = false; + g_polls = 0; + modem.setPollRxCallback(fakePollRx); + } +}; + +TEST_F(KissHwControlTest, RxBoostedGainUnsupportedWithoutCallbacks) { + EXPECT_EQ(hw1({HW_CMD_GET_RX_BOOSTED_GAIN}), ERR_UNSUPPORTED); + EXPECT_EQ(hw1({HW_CMD_SET_RX_BOOSTED_GAIN, 1}), ERR_UNSUPPORTED); +} + +TEST_F(KissRxBoostTest, CapabilityAdvertised) { + EXPECT_EQ(hw1({HW_CMD_GET_CAPABILITIES}), (std::vector<uint8_t>{0x9B, 0x09, 0x00, 0x00, 0x00})); +} + +TEST_F(KissRxBoostTest, GetReportsCurrentState) { + EXPECT_EQ(hw1({HW_CMD_GET_RX_BOOSTED_GAIN}), (std::vector<uint8_t>{0xA1, 0x01})); +} + +TEST_F(KissRxBoostTest, SetRepliesWithEffectiveState) { + EXPECT_EQ(hw1({HW_CMD_SET_RX_BOOSTED_GAIN, 0}), (std::vector<uint8_t>{0xA1, 0x00})); + EXPECT_FALSE(g_rx_boost); + EXPECT_EQ(hw1({HW_CMD_SET_RX_BOOSTED_GAIN, 0x7F}), (std::vector<uint8_t>{0xA1, 0x01})); + EXPECT_TRUE(g_rx_boost); +} + +TEST_F(KissRxBoostTest, SetFailureRepliesWithUnchangedState) { + g_rx_boost_set_ok = false; + EXPECT_EQ(hw1({HW_CMD_SET_RX_BOOSTED_GAIN, 0}), (std::vector<uint8_t>{0xA1, 0x01})); + EXPECT_TRUE(g_rx_boost); +} + +TEST_F(KissRxBoostTest, SetDuringTxIsRejectedWithoutTouchingRadio) { + startTxAndHold(); + serial.takeHardwareFrames(); + EXPECT_EQ(hw1({HW_CMD_SET_RX_BOOSTED_GAIN, 0}), (std::vector<uint8_t>{HW_RESP_ERROR, HW_ERR_TX_BUSY})); + EXPECT_EQ(g_rx_boost_sets, 0); + EXPECT_EQ(hw1({HW_CMD_GET_RX_BOOSTED_GAIN}), (std::vector<uint8_t>{0xA1, 0x01})); +} + +TEST_F(KissRxBoostTest, SetShortPayloadIsInvalidLength) { + EXPECT_EQ(hw1({HW_CMD_SET_RX_BOOSTED_GAIN}), (std::vector<uint8_t>{HW_RESP_ERROR, HW_ERR_INVALID_LENGTH})); + EXPECT_EQ(g_rx_boost_sets, 0); +} + +TEST_F(KissRxBoostTest, CompletedRxPacketIsDeliveredBeforeGainChange) { + g_poll_has_packet = true; + auto frames = hw({HW_CMD_SET_RX_BOOSTED_GAIN, 0}); + EXPECT_EQ(g_polls, 1); + EXPECT_FALSE(g_rx_boost); + ASSERT_EQ(frames.size(), 2U); // RxMeta for the drained packet, then the gain reply + EXPECT_EQ(frames[0][0], HW_RESP_RX_META); + EXPECT_EQ(frames[1], (std::vector<uint8_t>{0xA1, 0x00})); +} + +TEST_F(KissRxBoostTest, NoRoomForReplyAfterDrainChangesNothing) { + serial.blocked = true; + g_poll_has_packet = true; // data + meta fill both output slots + serial.pushRx({KISS_FEND, KISS_CMD_SETHARDWARE, HW_CMD_SET_RX_BOOSTED_GAIN, 0, KISS_FEND}); + modem.loop(); + EXPECT_EQ(g_rx_boost_sets, 0); + EXPECT_TRUE(g_rx_boost); + + serial.blocked = false; + for (int i = 0; i < 5; i++) modem.loop(); + auto frames = serial.takeHardwareFrames(); + ASSERT_EQ(frames.size(), 2U); + EXPECT_EQ(frames[0][0], HW_RESP_RX_META); + EXPECT_EQ(frames[1], (std::vector<uint8_t>{HW_RESP_ERROR, HW_ERR_TX_BUSY})); +} + +TEST_F(KissRxBoostTest, SetWhileHostOutputBackedUpIsRejected) { + serial.blocked = true; + static constexpr uint8_t PKT[] = {0x01}; + modem.onPacketReceived(0, 0, PKT, sizeof(PKT)); + serial.pushRx({KISS_FEND, KISS_CMD_SETHARDWARE, HW_CMD_SET_RX_BOOSTED_GAIN, 0, KISS_FEND}); + modem.loop(); + EXPECT_EQ(g_polls, 0); + EXPECT_EQ(g_rx_boost_sets, 0); +} + } // namespace From 7652ec5c267a6780adda6767bd260edc1c58653c Mon Sep 17 00:00:00 2001 From: agessaman <adam@gessaman.com> Date: Wed, 23 Sep 2026 17:31:20 -0700 Subject: [PATCH 255/381] kiss_modem: reach FEM gain through the board's radio.fem CLI commands Boards own their FEM control through handleCommand() ("get/set radio.fem.rxgain|txgain"). Use that instead of a parallel set of FEM virtuals on MainBoard, so any board that implements the commands works in KISS with no extra code. - Remove the six FEM virtuals from MainBoard and the board overrides. - KissModem talks to the board in one adapter. A gain counts as controllable only if "get" replies exactly "> on" or "> off". "set" is checked by reading the state back, never by its reply wording. - SetFemState always replies with the read-back state once the requested bits pass the capability check. - Guard the boards' prefs writes against a NULL store. KISS attaches no prefs, so "set radio.fem.*" would dereference NULL. - Wio Tracker L1 1W TX gain is exposed again, matching its CLI. --- docs/kiss_modem_protocol.md | 2 +- examples/kiss_modem/KissModem.cpp | 92 ++++++++++++------- examples/kiss_modem/KissModem.h | 13 ++- src/MeshCore.h | 8 -- test/mocks/Mesh.h | 7 +- test/test_kiss_modem/test_hw_controls.cpp | 76 +++++++++++---- variants/heltec_t096/T096Board.cpp | 4 +- variants/heltec_t096/T096Board.h | 6 +- .../HeltecTrackerV2Board.cpp | 4 +- .../heltec_tracker_v2/HeltecTrackerV2Board.h | 6 +- variants/heltec_v4/HeltecV4Board.cpp | 4 +- variants/heltec_v4/HeltecV4Board.h | 6 +- variants/heltec_v4_r8/HeltecV4R8Board.cpp | 4 +- variants/heltec_v4_r8/HeltecV4R8Board.h | 5 +- variants/heltec_v4_r8/LoRaFEMControl.h | 2 +- variants/station_g3_esp32/StationG3Board.cpp | 8 +- variants/station_g3_esp32/StationG3Board.h | 10 +- .../wio-tracker-l1-1w/WioTrackerL1Board.cpp | 4 +- 18 files changed, 161 insertions(+), 100 deletions(-) diff --git a/docs/kiss_modem_protocol.md b/docs/kiss_modem_protocol.md index cb7be8b3..a37c4561 100644 --- a/docs/kiss_modem_protocol.md +++ b/docs/kiss_modem_protocol.md @@ -283,7 +283,7 @@ FemState response data: Example: enable RX gain without changing TX gain: apply `0x01`, value `0x01`. -If any bit in the apply mask is not in the board's capability mask (including reserved bits), the modem replies `Unsupported` and changes nothing. On success, SetFemState replies with the FemState response carrying the new state. A SetFemState received while a packet is on air (before its TxDone is queued) is held and applied after TxDone, so its FemState response follows TxDone. While a SetFemState is held or its response is still waiting for output space, GetFemState responses are queued behind it in order, and a further SetFemState returns `TxBusy`. Capabilities come from the board, so a board with a fixed, board-managed FEM (for example RAK3401) reports none. +If any bit in the apply mask is not in the board's capability mask (including reserved bits), the modem replies `Unsupported` and changes nothing. Otherwise SetFemState replies with the FemState response carrying the state read back from the board; if a bit differs from the request, that change did not take effect. A SetFemState received while a packet is on air (before its TxDone is queued) is held and applied after TxDone, so its FemState response follows TxDone. While a SetFemState is held or its response is still waiting for output space, GetFemState responses are queued behind it in order, and a further SetFemState returns `TxBusy`. Capabilities come from the board's own `get/set radio.fem.rxgain` and `radio.fem.txgain` CLI commands (see [cli_commands.md](./cli_commands.md)): a gain is controllable when the board answers `get` with `> on` or `> off`. Any board that implements those commands is supported without KISS changes, and a board with a fixed, board-managed FEM (for example RAK3401) reports none. Changes made over KISS are not saved to the board's preferences. The setting is not persisted; the board's power-on default applies after reboot. diff --git a/examples/kiss_modem/KissModem.cpp b/examples/kiss_modem/KissModem.cpp index 221c40b1..a6950bff 100644 --- a/examples/kiss_modem/KissModem.cpp +++ b/examples/kiss_modem/KissModem.cpp @@ -1,5 +1,6 @@ #include "KissModem.h" #include <CayenneLPP.h> +#include <stdio.h> KissModem::KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& rng, mesh::Radio& radio, mesh::MainBoard& board, SensorManager& sensors) @@ -31,7 +32,6 @@ KissModem::KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& r _fem_deferred_apply = 0; _fem_deferred_value = 0; _fem_reply_pending = false; - _fem_reply_ok = false; _fem_deferred_gets = 0; resetOutputQueue(); } @@ -785,8 +785,10 @@ void KissModem::handleGetSignalReport() { void KissModem::handleGetCapabilities() { uint32_t caps = HW_CAP_AGC_RESET; - if (_board.canControlLoRaFemLna()) caps |= HW_CAP_FEM_RX_GAIN; - if (_board.canControlLoRaFemPaGain()) caps |= HW_CAP_FEM_TX_GAIN; + uint8_t fem_caps, fem_values; + readFemState(&fem_caps, &fem_values); + if (fem_caps & HW_FEM_RX_GAIN) caps |= HW_CAP_FEM_RX_GAIN; + if (fem_caps & HW_FEM_TX_GAIN) caps |= HW_CAP_FEM_TX_GAIN; if (_setRxBoostedGainCallback && _getRxBoostedGainCallback) caps |= HW_CAP_RX_BOOSTED_GAIN; uint8_t buf[4] = { (uint8_t)caps, (uint8_t)(caps >> 8), (uint8_t)(caps >> 16), (uint8_t)(caps >> 24) }; writeHardwareFrame(HW_RESP(HW_CMD_GET_CAPABILITIES), buf, 4); @@ -812,55 +814,81 @@ void KissModem::handleGetAgcResetInterval() { writeHardwareFrame(HW_RESP(HW_CMD_GET_AGC_RESET_INTERVAL), buf, 2); } -uint8_t KissModem::femCapabilityMask() const { - uint8_t mask = 0; - if (_board.canControlLoRaFemLna()) mask |= HW_FEM_RX_GAIN; - if (_board.canControlLoRaFemPaGain()) mask |= HW_FEM_TX_GAIN; - return mask; +// FEM gain is reached through the board's own "radio.fem.*" CLI commands, the same ones users run. +static const char* femGainName(uint8_t bit) { + return bit == HW_FEM_RX_GAIN ? "rxgain" : "txgain"; } -uint8_t KissModem::femValueMask() const { - uint8_t mask = 0; - if (_board.canControlLoRaFemLna() && _board.isLoRaFemLnaEnabled()) mask |= HW_FEM_RX_GAIN; - if (_board.canControlLoRaFemPaGain() && _board.isLoRaFemPaGainEnabled()) mask |= HW_FEM_TX_GAIN; - return mask; -} - -bool KissModem::queueFemReply(bool ok, bool mark_busy_error) { - if (!ok) { - const uint8_t err = HW_ERR_UNSUPPORTED; - return queueHardwareFrame(HW_RESP_ERROR, &err, 1, mark_busy_error); +// Anything but an exact "> on" / "> off" (not handled, "Error: ...", unexpected text) means unsupported. +bool KissModem::queryFemGain(uint8_t bit, bool* enabled) { + char cmd[32]; + char reply[KISS_BOARD_REPLY_SIZE] = { 0 }; + snprintf(cmd, sizeof(cmd), "get radio.fem.%s", femGainName(bit)); + if (!_board.handleCommand(cmd, 0, reply)) return false; + if (strcmp(reply, "> on") == 0) { + *enabled = true; + } else if (strcmp(reply, "> off") == 0) { + *enabled = false; + } else { + return false; } - uint8_t buf[2] = { femCapabilityMask(), femValueMask() }; + return true; +} + +// Success is judged by reading the state back, not by the wording of the set reply. +bool KissModem::setFemGain(uint8_t bit, bool enable) { + char cmd[32]; + char reply[KISS_BOARD_REPLY_SIZE] = { 0 }; + snprintf(cmd, sizeof(cmd), "set radio.fem.%s %s", femGainName(bit), enable ? "on" : "off"); + _board.handleCommand(cmd, 0, reply); + bool now; + return queryFemGain(bit, &now) && now == enable; +} + +void KissModem::readFemState(uint8_t* caps, uint8_t* values) { + *caps = 0; + *values = 0; + const uint8_t bits[] = { HW_FEM_RX_GAIN, HW_FEM_TX_GAIN }; + for (uint8_t bit : bits) { + bool enabled; + if (queryFemGain(bit, &enabled)) { + *caps |= bit; + if (enabled) *values |= bit; + } + } +} + +bool KissModem::queueFemReply(bool mark_busy_error) { + uint8_t buf[2]; + readFemState(&buf[0], &buf[1]); return queueHardwareFrame(HW_RESP(HW_CMD_GET_FEM_STATE), buf, 2, mark_busy_error); } -bool KissModem::applyFemState(uint8_t apply_mask, uint8_t value_mask) { - bool ok = true; +// The reply always carries the read-back state, so a bit that failed to apply shows its real value. +void KissModem::applyFemState(uint8_t apply_mask, uint8_t value_mask) { if (apply_mask & HW_FEM_RX_GAIN) { - ok &= _board.setLoRaFemLnaEnabled((value_mask & HW_FEM_RX_GAIN) != 0); + setFemGain(HW_FEM_RX_GAIN, (value_mask & HW_FEM_RX_GAIN) != 0); } if (apply_mask & HW_FEM_TX_GAIN) { - ok &= _board.setLoRaFemPaGainEnabled((value_mask & HW_FEM_TX_GAIN) != 0); + setFemGain(HW_FEM_TX_GAIN, (value_mask & HW_FEM_TX_GAIN) != 0); } - return ok; } void KissModem::processDeferredFem() { // wait for TxDone to be queued so the host sees the TX result before the FEM change if (_fem_deferred && _tx_state != TX_SENDING && _tx_state != TX_DONE_PENDING) { - _fem_reply_ok = applyFemState(_fem_deferred_apply, _fem_deferred_value); + applyFemState(_fem_deferred_apply, _fem_deferred_value); _fem_deferred = false; _fem_reply_pending = true; } if (_fem_deferred) return; // replies are retained until queued, and GetFemState replies stay behind the Set reply if (_fem_reply_pending) { - if (!queueFemReply(_fem_reply_ok, false)) return; + if (!queueFemReply(false)) return; _fem_reply_pending = false; } while (_fem_deferred_gets > 0) { - if (!queueFemReply(true, false)) return; + if (!queueFemReply(false)) return; _fem_deferred_gets--; } } @@ -873,7 +901,9 @@ void KissModem::handleSetFemState(const uint8_t* data, uint16_t len) { uint8_t apply_mask = data[0]; uint8_t value_mask = data[1]; // validate every requested bit before touching hardware so a request is all-or-nothing - if (apply_mask & ~femCapabilityMask()) { + uint8_t fem_caps, fem_values; + readFemState(&fem_caps, &fem_values); + if (apply_mask & ~fem_caps) { writeHardwareError(HW_ERR_UNSUPPORTED); return; } @@ -888,7 +918,7 @@ void KissModem::handleSetFemState(const uint8_t* data, uint16_t len) { _fem_deferred_value = value_mask; return; } - _fem_reply_ok = applyFemState(apply_mask, value_mask); + applyFemState(apply_mask, value_mask); _fem_reply_pending = true; processDeferredFem(); } @@ -902,7 +932,7 @@ void KissModem::handleGetFemState() { _fem_deferred_gets++; return; } - queueFemReply(true, true); + queueFemReply(true); } void KissModem::handleSetRxBoostedGain(const uint8_t* data, uint16_t len) { diff --git a/examples/kiss_modem/KissModem.h b/examples/kiss_modem/KissModem.h index ffe89191..572999c4 100644 --- a/examples/kiss_modem/KissModem.h +++ b/examples/kiss_modem/KissModem.h @@ -100,6 +100,9 @@ #define HW_FEM_RX_GAIN (1 << 0) #define HW_FEM_TX_GAIN (1 << 1) +/* Matches the CLI reply buffer boards write into from handleCommand() */ +#define KISS_BOARD_REPLY_SIZE 160 + #define KISS_AGC_RESET_DEFAULT_SEC 30 #define KISS_AGC_RESET_MAX_SEC 1020 #define KISS_AGC_RESET_STEP_SEC 4 @@ -173,7 +176,6 @@ class KissModem { uint8_t _fem_deferred_apply; uint8_t _fem_deferred_value; bool _fem_reply_pending; - bool _fem_reply_ok; uint8_t _fem_deferred_gets; uint8_t _tx_frame_buf[KISS_TX_FRAME_QUEUE_DEPTH][KISS_MAX_ENCODED_FRAME_SIZE]; uint16_t _tx_frame_len[KISS_TX_FRAME_QUEUE_DEPTH]; @@ -202,10 +204,11 @@ class KissModem { void handleHardwareCommand(uint8_t sub_cmd, const uint8_t* data, uint16_t len); void processTx(); void maybeResetAgc(); - uint8_t femCapabilityMask() const; - uint8_t femValueMask() const; - bool queueFemReply(bool ok, bool mark_busy_error); - bool applyFemState(uint8_t apply_mask, uint8_t value_mask); + bool queryFemGain(uint8_t bit, bool* enabled); + bool setFemGain(uint8_t bit, bool enable); + void readFemState(uint8_t* caps, uint8_t* values); + bool queueFemReply(bool mark_busy_error); + void applyFemState(uint8_t apply_mask, uint8_t value_mask); bool isFemReplyQueued() const { return _fem_deferred || _fem_reply_pending || _fem_deferred_gets > 0; } void processDeferredFem(); diff --git a/src/MeshCore.h b/src/MeshCore.h index 5fdb064c..2a3582de 100644 --- a/src/MeshCore.h +++ b/src/MeshCore.h @@ -77,14 +77,6 @@ public: virtual bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { return false; } - // External LoRa front-end (FEM) gain control. Boards without a controllable FEM keep these defaults. - virtual bool canControlLoRaFemLna() const { return false; } - virtual bool setLoRaFemLnaEnabled(bool enable) { return false; } - virtual bool isLoRaFemLnaEnabled() const { return false; } - virtual bool canControlLoRaFemPaGain() const { return false; } - virtual bool setLoRaFemPaGainEnabled(bool enable) { return false; } - virtual bool isLoRaFemPaGainEnabled() const { return false; } - // Called from the example main loops. Lets a board feed its watchdog and // run periodic housekeeping. Default no-op. virtual void loop() { /* no op */ } diff --git a/test/mocks/Mesh.h b/test/mocks/Mesh.h index 29a29b82..33c437f2 100644 --- a/test/mocks/Mesh.h +++ b/test/mocks/Mesh.h @@ -23,12 +23,7 @@ public: virtual float getMCUTemperature() { return 25.0f; } virtual const char* getManufacturerName() { return "mock-board"; } virtual void reboot() {} - virtual bool canControlLoRaFemLna() const { return false; } - virtual bool setLoRaFemLnaEnabled(bool) { return false; } - virtual bool isLoRaFemLnaEnabled() const { return false; } - virtual bool canControlLoRaFemPaGain() const { return false; } - virtual bool setLoRaFemPaGainEnabled(bool) { return false; } - virtual bool isLoRaFemPaGainEnabled() const { return false; } + virtual bool handleCommand(const char*, uint32_t, char*) { return false; } }; } diff --git a/test/test_kiss_modem/test_hw_controls.cpp b/test/test_kiss_modem/test_hw_controls.cpp index 37b1b929..16ef50df 100644 --- a/test/test_kiss_modem/test_hw_controls.cpp +++ b/test/test_kiss_modem/test_hw_controls.cpp @@ -72,31 +72,50 @@ public: int agc_resets = 0; }; +// Implements FEM through the "radio.fem.*" CLI text, worded like the Heltec / Station G3 boards. class FemBoard : public mesh::MainBoard { public: const char* getManufacturerName() override { return "fem-board"; } - bool canControlLoRaFemLna() const override { return has_lna; } - bool setLoRaFemLnaEnabled(bool enable) override { - if (!has_lna) return false; - lna = enable; - lna_sets++; - return true; + bool handleCommand(const char* command, uint32_t, char* reply) override { + commands++; + if (handleGain(command, reply, "rxgain", has_lna, lna, lna_sets, lna_sticks)) return true; + if (handleGain(command, reply, "txgain", has_pa, pa, pa_sets, pa_sticks)) return true; + return false; } - bool isLoRaFemLnaEnabled() const override { return lna; } - - bool canControlLoRaFemPaGain() const override { return has_pa; } - bool setLoRaFemPaGainEnabled(bool enable) override { - if (!has_pa) return false; - pa = enable; - pa_sets++; - return true; - } - bool isLoRaFemPaGainEnabled() const override { return pa; } bool has_lna = false, has_pa = false; bool lna = false, pa = false; int lna_sets = 0, pa_sets = 0; + bool lna_sticks = false, pa_sticks = false; // set reports OK but the state does not change + bool unhandled = false; // board does not implement radio.fem.* at all + const char* odd_get_reply = nullptr; // unexpected get wording + int commands = 0; + +private: + bool handleGain(const char* command, char* reply, const char* name, bool has, bool& state, int& sets, bool sticks) { + if (unhandled) return false; + char get_cmd[32], set_cmd[32]; + snprintf(get_cmd, sizeof(get_cmd), "get radio.fem.%s", name); + snprintf(set_cmd, sizeof(set_cmd), "set radio.fem.%s ", name); + if (strcmp(command, get_cmd) == 0) { + if (!has) strcpy(reply, "Error: unsupported"); + else if (odd_get_reply) strcpy(reply, odd_get_reply); + else sprintf(reply, "> %s", state ? "on" : "off"); + return true; + } + if (strncmp(command, set_cmd, strlen(set_cmd)) == 0) { + if (!has) { + strcpy(reply, "Error: unsupported"); + } else { + sets++; + if (!sticks) state = strcmp(command + strlen(set_cmd), "on") == 0; + strcpy(reply, "OK - LoRa FEM gain changed"); + } + return true; + } + return false; + } }; class NoSensors : public SensorManager { @@ -276,6 +295,31 @@ TEST_F(KissHwControlTest, FemUnknownBitsAreUnsupported) { EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, 0x04, 0x04}), ERR_UNSUPPORTED); } +TEST_F(KissHwControlTest, FemUnhandledCommandsMeanUnsupported) { + board.has_lna = board.has_pa = true; + board.unhandled = true; + EXPECT_EQ(hw1({HW_CMD_GET_FEM_STATE}), (std::vector<uint8_t>{0x9F, 0x00, 0x00})); + EXPECT_EQ(hw1({HW_CMD_GET_CAPABILITIES}), (std::vector<uint8_t>{0x9B, 0x01, 0x00, 0x00, 0x00})); + EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}), ERR_UNSUPPORTED); +} + +TEST_F(KissHwControlTest, FemUnexpectedGetWordingMeansUnsupported) { + board.has_lna = true; + board.odd_get_reply = "> enabled"; + EXPECT_EQ(hw1({HW_CMD_GET_FEM_STATE}), (std::vector<uint8_t>{0x9F, 0x00, 0x00})); + EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}), ERR_UNSUPPORTED); + EXPECT_EQ(board.lna_sets, 0); +} + +TEST_F(KissHwControlTest, FemSetThatDoesNotTakeRepliesWithReadBackState) { + board.has_lna = board.has_pa = true; + board.lna_sticks = true; // board says OK but LNA stays off + EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN | HW_FEM_TX_GAIN, HW_FEM_RX_GAIN | HW_FEM_TX_GAIN}), + (std::vector<uint8_t>{0x9F, 0x03, 0x02})); + EXPECT_FALSE(board.lna); + EXPECT_TRUE(board.pa); +} + TEST_F(KissHwControlTest, FemShortPayloadIsInvalidLength) { EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN}), (std::vector<uint8_t>{HW_RESP_ERROR, HW_ERR_INVALID_LENGTH})); } diff --git a/variants/heltec_t096/T096Board.cpp b/variants/heltec_t096/T096Board.cpp index ea26d2cc..47ad8d96 100644 --- a/variants/heltec_t096/T096Board.cpp +++ b/variants/heltec_t096/T096Board.cpp @@ -158,14 +158,14 @@ bool T096Board::handleCommand(const char* command, uint32_t sender_timestamp, ch strcpy(reply, "Error: unsupported"); } else if (memcmp(&command[21], "on", 2) == 0) { if (setLoRaFemLnaEnabled(true)) { - _prefs->setByKey("fem_rxgain", "1"); + if (_prefs) _prefs->setByKey("fem_rxgain", "1"); strcpy(reply, "OK - LoRa FEM RX gain on"); } else { strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); } } else if (memcmp(&command[21], "off", 3) == 0) { if (setLoRaFemLnaEnabled(false)) { - _prefs->setByKey("fem_rxgain", "0"); + if (_prefs) _prefs->setByKey("fem_rxgain", "0"); strcpy(reply, "OK - LoRa FEM RX gain off"); } else { strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); diff --git a/variants/heltec_t096/T096Board.h b/variants/heltec_t096/T096Board.h index 66fa5047..e926c8a6 100644 --- a/variants/heltec_t096/T096Board.h +++ b/variants/heltec_t096/T096Board.h @@ -16,6 +16,9 @@ protected: #endif void variant_shutdown(); + bool setLoRaFemLnaEnabled(bool enable); + bool isLoRaFemLnaEnabled() const; + public: RefCountedDigitalPin periph_power; LoRaFEMControl loRaFEMControl; @@ -24,9 +27,6 @@ public: void begin(); void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; - bool canControlLoRaFemLna() const override { return loRaFEMControl.isLnaCanControl(); } - bool setLoRaFemLnaEnabled(bool enable) override; - bool isLoRaFemLnaEnabled() const override; void onBeforeTransmit(void) override; void onAfterTransmit(void) override; diff --git a/variants/heltec_tracker_v2/HeltecTrackerV2Board.cpp b/variants/heltec_tracker_v2/HeltecTrackerV2Board.cpp index 753824a0..95d56699 100644 --- a/variants/heltec_tracker_v2/HeltecTrackerV2Board.cpp +++ b/variants/heltec_tracker_v2/HeltecTrackerV2Board.cpp @@ -99,14 +99,14 @@ bool HeltecTrackerV2Board::handleCommand(const char* command, uint32_t sender_ti strcpy(reply, "Error: unsupported"); } else if (memcmp(&command[21], "on", 2) == 0) { if (setLoRaFemLnaEnabled(true)) { - _prefs->setByKey("fem_rxgain", "1"); + if (_prefs) _prefs->setByKey("fem_rxgain", "1"); strcpy(reply, "OK - LoRa FEM RX gain on"); } else { strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); } } else if (memcmp(&command[21], "off", 3) == 0) { if (setLoRaFemLnaEnabled(false)) { - _prefs->setByKey("fem_rxgain", "0"); + if (_prefs) _prefs->setByKey("fem_rxgain", "0"); strcpy(reply, "OK - LoRa FEM RX gain off"); } else { strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); diff --git a/variants/heltec_tracker_v2/HeltecTrackerV2Board.h b/variants/heltec_tracker_v2/HeltecTrackerV2Board.h index 34454cac..5fed2b65 100644 --- a/variants/heltec_tracker_v2/HeltecTrackerV2Board.h +++ b/variants/heltec_tracker_v2/HeltecTrackerV2Board.h @@ -8,6 +8,9 @@ class HeltecTrackerV2Board : public ESP32Board { KeyValueStore* _prefs = NULL; + bool setLoRaFemLnaEnabled(bool enable); + bool isLoRaFemLnaEnabled() const; + public: RefCountedDigitalPin periph_power; LoRaFEMControl loRaFEMControl; @@ -17,9 +20,6 @@ public: void begin(); void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; - bool canControlLoRaFemLna() const override { return loRaFEMControl.isLnaCanControl(); } - bool setLoRaFemLnaEnabled(bool enable) override; - bool isLoRaFemLnaEnabled() const override; void onBeforeTransmit(void) override; void onAfterTransmit(void) override; diff --git a/variants/heltec_v4/HeltecV4Board.cpp b/variants/heltec_v4/HeltecV4Board.cpp index 794257d7..2d941bd8 100644 --- a/variants/heltec_v4/HeltecV4Board.cpp +++ b/variants/heltec_v4/HeltecV4Board.cpp @@ -100,14 +100,14 @@ bool HeltecV4Board::handleCommand(const char* command, uint32_t sender_timestamp strcpy(reply, "Error: unsupported"); } else if (memcmp(&command[21], "on", 2) == 0) { if (setLoRaFemLnaEnabled(true)) { - _prefs->setByKey("fem_rxgain", "1"); + if (_prefs) _prefs->setByKey("fem_rxgain", "1"); strcpy(reply, "OK - LoRa FEM RX gain on"); } else { strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); } } else if (memcmp(&command[21], "off", 3) == 0) { if (setLoRaFemLnaEnabled(false)) { - _prefs->setByKey("fem_rxgain", "0"); + if (_prefs) _prefs->setByKey("fem_rxgain", "0"); strcpy(reply, "OK - LoRa FEM RX gain off"); } else { strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); diff --git a/variants/heltec_v4/HeltecV4Board.h b/variants/heltec_v4/HeltecV4Board.h index bd3bdb25..79a690e8 100644 --- a/variants/heltec_v4/HeltecV4Board.h +++ b/variants/heltec_v4/HeltecV4Board.h @@ -12,6 +12,9 @@ class HeltecV4Board : public ESP32Board { KeyValueStore* _prefs = NULL; + bool setLoRaFemLnaEnabled(bool enable); + bool isLoRaFemLnaEnabled() const; + protected: float adc_mult = ADC_MULTIPLIER; @@ -23,9 +26,6 @@ public: void begin(); void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; - bool canControlLoRaFemLna() const override { return loRaFEMControl.isLnaCanControl(); } - bool setLoRaFemLnaEnabled(bool enable) override; - bool isLoRaFemLnaEnabled() const override; void onBeforeTransmit(void) override; void onAfterTransmit(void) override; diff --git a/variants/heltec_v4_r8/HeltecV4R8Board.cpp b/variants/heltec_v4_r8/HeltecV4R8Board.cpp index ea2cfbed..d4860ab4 100644 --- a/variants/heltec_v4_r8/HeltecV4R8Board.cpp +++ b/variants/heltec_v4_r8/HeltecV4R8Board.cpp @@ -122,14 +122,14 @@ bool HeltecV4R8Board::handleCommand(const char* command, uint32_t sender_timesta strcpy(reply, "Error: unsupported"); } else if (memcmp(&command[21], "on", 2) == 0) { if (setLoRaFemLnaEnabled(true)) { - _prefs->setByKey("fem_rxgain", "1"); + if (_prefs) _prefs->setByKey("fem_rxgain", "1"); strcpy(reply, "OK - LoRa FEM RX gain on"); } else { strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); } } else if (memcmp(&command[21], "off", 3) == 0) { if (setLoRaFemLnaEnabled(false)) { - _prefs->setByKey("fem_rxgain", "0"); + if (_prefs) _prefs->setByKey("fem_rxgain", "0"); strcpy(reply, "OK - LoRa FEM RX gain off"); } else { strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); diff --git a/variants/heltec_v4_r8/HeltecV4R8Board.h b/variants/heltec_v4_r8/HeltecV4R8Board.h index c34ee449..7ab29f96 100644 --- a/variants/heltec_v4_r8/HeltecV4R8Board.h +++ b/variants/heltec_v4_r8/HeltecV4R8Board.h @@ -13,6 +13,8 @@ class HeltecV4R8Board : public ESP32Board { KeyValueStore* _prefs = NULL; + bool setLoRaFemLnaEnabled(bool enable); + bool isLoRaFemLnaEnabled() const; protected: float adc_mult = ADC_MULTIPLIER; @@ -25,9 +27,6 @@ public: void begin(); void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; - bool canControlLoRaFemLna() const override { return loRaFEMControl.isLnaCanControl(); } - bool setLoRaFemLnaEnabled(bool enable) override; - bool isLoRaFemLnaEnabled() const override; void onBeforeTransmit(void) override; void onAfterTransmit(void) override; diff --git a/variants/heltec_v4_r8/LoRaFEMControl.h b/variants/heltec_v4_r8/LoRaFEMControl.h index 52d7a0f8..4b74c2e2 100644 --- a/variants/heltec_v4_r8/LoRaFEMControl.h +++ b/variants/heltec_v4_r8/LoRaFEMControl.h @@ -15,7 +15,7 @@ public: void setRxModeEnable(void); void setRxModeEnableWhenMCUSleep(void); void setLNAEnable(bool enabled); - bool isLnaCanControl(void) const { return true; } + bool isLnaCanControl(void) { return true; } void setLnaCanControl(bool can_control) { } bool isLNAEnabled(void) const { return lna_enabled; } LoRaFEMType getFEMType(void) const { return KCT8103L_PA; } diff --git a/variants/station_g3_esp32/StationG3Board.cpp b/variants/station_g3_esp32/StationG3Board.cpp index 277c2b8b..9e8ef112 100644 --- a/variants/station_g3_esp32/StationG3Board.cpp +++ b/variants/station_g3_esp32/StationG3Board.cpp @@ -65,14 +65,14 @@ bool StationG3Board::handleCommand(const char* command, uint32_t sender_timestam strcpy(reply, "Error: unsupported"); } else if (memcmp(&command[21], "on", 2) == 0) { if (setLoRaFemLnaEnabled(true)) { - _prefs->setByKey("fem_rxgain", "1"); + if (_prefs) _prefs->setByKey("fem_rxgain", "1"); strcpy(reply, "OK - LoRa FEM RX gain on"); } else { strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); } } else if (memcmp(&command[21], "off", 3) == 0) { if (setLoRaFemLnaEnabled(false)) { - _prefs->setByKey("fem_rxgain", "0"); + if (_prefs) _prefs->setByKey("fem_rxgain", "0"); strcpy(reply, "OK - LoRa FEM RX gain off"); } else { strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); @@ -96,14 +96,14 @@ bool StationG3Board::handleCommand(const char* command, uint32_t sender_timestam strcpy(reply, "Error: unsupported"); } else if (memcmp(&command[21], "on", 2) == 0) { if (setLoRaFemPaGainEnabled(true)) { - _prefs->setByKey("fem_txgain", "1"); + if (_prefs) _prefs->setByKey("fem_txgain", "1"); strcpy(reply, "OK - LoRa FEM TX gain on"); } else { strcpy(reply, "Error: failed to apply LoRa FEM TX gain"); } } else if (memcmp(&command[21], "off", 3) == 0) { if (setLoRaFemPaGainEnabled(false)) { - _prefs->setByKey("fem_txgain", "0"); + if (_prefs) _prefs->setByKey("fem_txgain", "0"); strcpy(reply, "OK - LoRa FEM TX gain off"); } else { strcpy(reply, "Error: failed to apply LoRa FEM TX gain"); diff --git a/variants/station_g3_esp32/StationG3Board.h b/variants/station_g3_esp32/StationG3Board.h index f8cb75cb..b4c5838c 100644 --- a/variants/station_g3_esp32/StationG3Board.h +++ b/variants/station_g3_esp32/StationG3Board.h @@ -8,6 +8,10 @@ class StationG3Board : public ESP32Board { KeyValueStore* _prefs = NULL; + bool setLoRaFemLnaEnabled(bool enable); + bool isLoRaFemLnaEnabled() const; + bool setLoRaFemPaGainEnabled(bool enable); + bool isLoRaFemPaGainEnabled() const; public: LoRaFEMControl loRaFEMControl; @@ -30,12 +34,6 @@ public: void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; - bool canControlLoRaFemLna() const override { return loRaFEMControl.canControlLNA(); } - bool setLoRaFemLnaEnabled(bool enable) override; - bool isLoRaFemLnaEnabled() const override; - bool canControlLoRaFemPaGain() const override { return loRaFEMControl.canControlPAGain(); } - bool setLoRaFemPaGainEnabled(bool enable) override; - bool isLoRaFemPaGainEnabled() const override; void setPrimaryLNAEnable(bool enabled) { loRaFEMControl.setLNAEnable(enabled); diff --git a/variants/wio-tracker-l1-1w/WioTrackerL1Board.cpp b/variants/wio-tracker-l1-1w/WioTrackerL1Board.cpp index c6dbdbf5..69b33f75 100644 --- a/variants/wio-tracker-l1-1w/WioTrackerL1Board.cpp +++ b/variants/wio-tracker-l1-1w/WioTrackerL1Board.cpp @@ -65,14 +65,14 @@ bool WioTrackerL1Board::handleCommand(const char* command, uint32_t sender_times if (memcmp(command, "set radio.fem.txgain ", 21) == 0) { if (memcmp(&command[21], "on", 2) == 0) { if (setLoRaFemPaGainEnabled(true)) { - _prefs->setByKey("fem_txgain", "1"); + if (_prefs) _prefs->setByKey("fem_txgain", "1"); strcpy(reply, "OK - LoRa FEM TX gain on"); } else { strcpy(reply, "Error: failed to apply LoRa FEM TX gain"); } } else if (memcmp(&command[21], "off", 3) == 0) { if (setLoRaFemPaGainEnabled(false)) { - _prefs->setByKey("fem_txgain", "0"); + if (_prefs) _prefs->setByKey("fem_txgain", "0"); strcpy(reply, "OK - LoRa FEM TX gain off"); } else { strcpy(reply, "Error: failed to apply LoRa FEM TX gain"); From 09ee2e1223eb4478e7421077f08fc218d9461fa2 Mon Sep 17 00:00:00 2001 From: agessaman <adam@gessaman.com> Date: Wed, 23 Sep 2026 17:41:14 -0700 Subject: [PATCH 256/381] kiss_modem: answer FEM requests strictly in arrival order A second SetFemState sent while the first was held for a TX got an immediate TxBusy, which reached the host before the first request's reply. With no request IDs, the host could not tell which Set failed. FEM requests now go through a small ordered queue (Set, Get and their error replies). Sets still wait for TxDone to be queued and apply once. Each reply is kept until it can be queued. Capability checks happen in order at processing time. Only an overflow (more than 4 waiting) replies TxBusy immediately. --- docs/kiss_modem_protocol.md | 2 +- examples/kiss_modem/KissModem.cpp | 107 ++++++++++------------ examples/kiss_modem/KissModem.h | 30 ++++-- test/test_kiss_modem/test_hw_controls.cpp | 50 +++++++++- 4 files changed, 117 insertions(+), 72 deletions(-) diff --git a/docs/kiss_modem_protocol.md b/docs/kiss_modem_protocol.md index a37c4561..5eb09738 100644 --- a/docs/kiss_modem_protocol.md +++ b/docs/kiss_modem_protocol.md @@ -283,7 +283,7 @@ FemState response data: Example: enable RX gain without changing TX gain: apply `0x01`, value `0x01`. -If any bit in the apply mask is not in the board's capability mask (including reserved bits), the modem replies `Unsupported` and changes nothing. Otherwise SetFemState replies with the FemState response carrying the state read back from the board; if a bit differs from the request, that change did not take effect. A SetFemState received while a packet is on air (before its TxDone is queued) is held and applied after TxDone, so its FemState response follows TxDone. While a SetFemState is held or its response is still waiting for output space, GetFemState responses are queued behind it in order, and a further SetFemState returns `TxBusy`. Capabilities come from the board's own `get/set radio.fem.rxgain` and `radio.fem.txgain` CLI commands (see [cli_commands.md](./cli_commands.md)): a gain is controllable when the board answers `get` with `> on` or `> off`. Any board that implements those commands is supported without KISS changes, and a board with a fixed, board-managed FEM (for example RAK3401) reports none. Changes made over KISS are not saved to the board's preferences. +If any bit in the apply mask is not in the board's capability mask (including reserved bits), the modem replies `Unsupported` and changes nothing. Otherwise SetFemState replies with the FemState response carrying the state read back from the board; if a bit differs from the request, that change did not take effect. SetFemState and GetFemState requests, including their error replies, are answered strictly in the order received. A SetFemState received while a packet is on air (before its TxDone is queued) is held and applied after TxDone, so its reply follows TxDone, and FEM requests that arrive after it wait behind it. Up to 4 FEM requests can wait; beyond that the modem replies `TxBusy` immediately. Capabilities come from the board's own `get/set radio.fem.rxgain` and `radio.fem.txgain` CLI commands (see [cli_commands.md](./cli_commands.md)): a gain is controllable when the board answers `get` with `> on` or `> off`. Any board that implements those commands is supported without KISS changes, and a board with a fixed, board-managed FEM (for example RAK3401) reports none. Changes made over KISS are not saved to the board's preferences. The setting is not persisted; the board's power-on default applies after reboot. diff --git a/examples/kiss_modem/KissModem.cpp b/examples/kiss_modem/KissModem.cpp index a6950bff..4d9cdbdb 100644 --- a/examples/kiss_modem/KissModem.cpp +++ b/examples/kiss_modem/KissModem.cpp @@ -28,11 +28,8 @@ KissModem::KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& r _signal_report_enabled = true; _agc_reset_interval_sec = KISS_AGC_RESET_DEFAULT_SEC; _next_agc_reset_ms = 0; - _fem_deferred = false; - _fem_deferred_apply = 0; - _fem_deferred_value = 0; - _fem_reply_pending = false; - _fem_deferred_gets = 0; + _fem_op_head = 0; + _fem_op_count = 0; resetOutputQueue(); } @@ -42,9 +39,8 @@ void KissModem::begin() { _rx_active = false; _has_pending_tx = false; _tx_state = TX_IDLE; - _fem_deferred = false; - _fem_reply_pending = false; - _fem_deferred_gets = 0; + _fem_op_head = 0; + _fem_op_count = 0; _next_agc_reset_ms = millis() + (uint32_t)_agc_reset_interval_sec * 1000; resetOutputQueue(); } @@ -255,7 +251,7 @@ void KissModem::loop() { } processTx(); - processDeferredFem(); + processFemOps(); maybeResetAgc(); tryFlushFrames(); queuePendingBusyError(); @@ -858,10 +854,10 @@ void KissModem::readFemState(uint8_t* caps, uint8_t* values) { } } -bool KissModem::queueFemReply(bool mark_busy_error) { +bool KissModem::queueFemReply() { uint8_t buf[2]; readFemState(&buf[0], &buf[1]); - return queueHardwareFrame(HW_RESP(HW_CMD_GET_FEM_STATE), buf, 2, mark_busy_error); + return queueHardwareFrame(HW_RESP(HW_CMD_GET_FEM_STATE), buf, 2, false); } // The reply always carries the read-back state, so a bit that failed to apply shows its real value. @@ -874,65 +870,58 @@ void KissModem::applyFemState(uint8_t apply_mask, uint8_t value_mask) { } } -void KissModem::processDeferredFem() { - // wait for TxDone to be queued so the host sees the TX result before the FEM change - if (_fem_deferred && _tx_state != TX_SENDING && _tx_state != TX_DONE_PENDING) { - applyFemState(_fem_deferred_apply, _fem_deferred_value); - _fem_deferred = false; - _fem_reply_pending = true; +void KissModem::enqueueFemOp(FemOpKind kind, uint8_t apply_mask, uint8_t value_mask) { + if (_fem_op_count >= KISS_FEM_OP_QUEUE_DEPTH) { + writeHardwareError(HW_ERR_TX_BUSY); // too many FEM requests waiting + return; } - if (_fem_deferred) return; - // replies are retained until queued, and GetFemState replies stay behind the Set reply - if (_fem_reply_pending) { - if (!queueFemReply(false)) return; - _fem_reply_pending = false; - } - while (_fem_deferred_gets > 0) { - if (!queueFemReply(false)) return; - _fem_deferred_gets--; + FemOp& op = _fem_ops[(_fem_op_head + _fem_op_count) % KISS_FEM_OP_QUEUE_DEPTH]; + op.kind = kind; + op.apply_mask = apply_mask; + op.value_mask = value_mask; + op.applied = false; + _fem_op_count++; + processFemOps(); +} + +// Every FEM reply goes out in request order. A Set waits until TxDone is queued, since board +// setters drive FEM pins directly; each reply is retained until there is room to queue it. +void KissModem::processFemOps() { + while (_fem_op_count > 0) { + FemOp& op = _fem_ops[_fem_op_head]; + if (op.kind == FEM_OP_ERROR) { + if (!queueHardwareFrame(HW_RESP_ERROR, &op.value_mask, 1, false)) return; + } else { + if (op.kind == FEM_OP_SET && !op.applied) { + if (_tx_state == TX_SENDING || _tx_state == TX_DONE_PENDING) return; + uint8_t caps, values; + readFemState(&caps, &values); + if (op.apply_mask & ~caps) { + // all-or-nothing: any bit the board cannot control rejects the whole request + op.kind = FEM_OP_ERROR; + op.value_mask = HW_ERR_UNSUPPORTED; + continue; + } + applyFemState(op.apply_mask, op.value_mask); + op.applied = true; + } + if (!queueFemReply()) return; + } + _fem_op_head = (uint8_t)((_fem_op_head + 1) % KISS_FEM_OP_QUEUE_DEPTH); + _fem_op_count--; } } void KissModem::handleSetFemState(const uint8_t* data, uint16_t len) { if (len < 2) { - writeHardwareError(HW_ERR_INVALID_LENGTH); + enqueueFemOp(FEM_OP_ERROR, 0, HW_ERR_INVALID_LENGTH); return; } - uint8_t apply_mask = data[0]; - uint8_t value_mask = data[1]; - // validate every requested bit before touching hardware so a request is all-or-nothing - uint8_t fem_caps, fem_values; - readFemState(&fem_caps, &fem_values); - if (apply_mask & ~fem_caps) { - writeHardwareError(HW_ERR_UNSUPPORTED); - return; - } - if (isFemReplyQueued()) { - writeHardwareError(HW_ERR_TX_BUSY); - return; - } - if (_tx_state == TX_SENDING || _tx_state == TX_DONE_PENDING) { - // board setters drive FEM pins directly; changing them mid-packet would corrupt the TX - _fem_deferred = true; - _fem_deferred_apply = apply_mask; - _fem_deferred_value = value_mask; - return; - } - applyFemState(apply_mask, value_mask); - _fem_reply_pending = true; - processDeferredFem(); + enqueueFemOp(FEM_OP_SET, data[0], data[1]); } void KissModem::handleGetFemState() { - if (isFemReplyQueued()) { - if (_fem_deferred_gets == UINT8_MAX) { - writeHardwareError(HW_ERR_TX_BUSY); - return; - } - _fem_deferred_gets++; - return; - } - queueFemReply(true); + enqueueFemOp(FEM_OP_GET, 0, 0); } void KissModem::handleSetRxBoostedGain(const uint8_t* data, uint16_t len) { diff --git a/examples/kiss_modem/KissModem.h b/examples/kiss_modem/KissModem.h index 572999c4..24021bdb 100644 --- a/examples/kiss_modem/KissModem.h +++ b/examples/kiss_modem/KissModem.h @@ -103,6 +103,9 @@ /* Matches the CLI reply buffer boards write into from handleCommand() */ #define KISS_BOARD_REPLY_SIZE 160 +/* FEM requests are answered strictly in arrival order; this many may wait (e.g. during a TX) */ +#define KISS_FEM_OP_QUEUE_DEPTH 4 + #define KISS_AGC_RESET_DEFAULT_SEC 30 #define KISS_AGC_RESET_MAX_SEC 1020 #define KISS_AGC_RESET_STEP_SEC 4 @@ -125,6 +128,19 @@ struct RadioConfig { uint8_t tx_power; }; +enum FemOpKind : uint8_t { + FEM_OP_SET, + FEM_OP_GET, + FEM_OP_ERROR +}; + +struct FemOp { + FemOpKind kind; + uint8_t apply_mask; // FEM_OP_SET + uint8_t value_mask; // FEM_OP_SET; error code for FEM_OP_ERROR + bool applied; // FEM_OP_SET: hardware changed, reply still to be queued +}; + enum TxState { TX_IDLE, TX_WAIT_CLEAR, @@ -172,11 +188,9 @@ class KissModem { bool _signal_report_enabled; uint16_t _agc_reset_interval_sec; uint32_t _next_agc_reset_ms; - bool _fem_deferred; - uint8_t _fem_deferred_apply; - uint8_t _fem_deferred_value; - bool _fem_reply_pending; - uint8_t _fem_deferred_gets; + FemOp _fem_ops[KISS_FEM_OP_QUEUE_DEPTH]; + uint8_t _fem_op_head; + uint8_t _fem_op_count; uint8_t _tx_frame_buf[KISS_TX_FRAME_QUEUE_DEPTH][KISS_MAX_ENCODED_FRAME_SIZE]; uint16_t _tx_frame_len[KISS_TX_FRAME_QUEUE_DEPTH]; uint16_t _tx_frame_written[KISS_TX_FRAME_QUEUE_DEPTH]; @@ -207,10 +221,10 @@ class KissModem { bool queryFemGain(uint8_t bit, bool* enabled); bool setFemGain(uint8_t bit, bool enable); void readFemState(uint8_t* caps, uint8_t* values); - bool queueFemReply(bool mark_busy_error); + bool queueFemReply(); void applyFemState(uint8_t apply_mask, uint8_t value_mask); - bool isFemReplyQueued() const { return _fem_deferred || _fem_reply_pending || _fem_deferred_gets > 0; } - void processDeferredFem(); + void enqueueFemOp(FemOpKind kind, uint8_t apply_mask, uint8_t value_mask); + void processFemOps(); void handleGetIdentity(); void handleGetRandom(const uint8_t* data, uint16_t len); diff --git a/test/test_kiss_modem/test_hw_controls.cpp b/test/test_kiss_modem/test_hw_controls.cpp index 16ef50df..e0fdd729 100644 --- a/test/test_kiss_modem/test_hw_controls.cpp +++ b/test/test_kiss_modem/test_hw_controls.cpp @@ -330,20 +330,62 @@ TEST_F(KissHwControlTest, FemSetDuringTxIsDeferredUntilAfterTxDone) { serial.takeHardwareFrames(); EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}).empty()); + EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, 0}).empty()); // queued behind the first EXPECT_EQ(board.lna_sets, 0); - EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, 0}), (std::vector<uint8_t>{HW_RESP_ERROR, HW_ERR_TX_BUSY})); radio.send_complete = true; modem.loop(); // TX done -> TX_DONE_PENDING; FEM still held - modem.loop(); // TxDone queued -> idle; FEM applied + modem.loop(); // TxDone queued -> idle; FEM applied in order + for (int i = 0; i < 3; i++) modem.loop(); auto frames = serial.takeHardwareFrames(); - ASSERT_EQ(frames.size(), 2U); + ASSERT_EQ(frames.size(), 3U); EXPECT_EQ(frames[0], (std::vector<uint8_t>{HW_RESP_TX_DONE, 0x01})); EXPECT_EQ(frames[1], (std::vector<uint8_t>{0x9F, 0x01, 0x01})); - EXPECT_TRUE(board.lna); + EXPECT_EQ(frames[2], (std::vector<uint8_t>{0x9F, 0x01, 0x00})); + EXPECT_FALSE(board.lna); + EXPECT_EQ(board.lna_sets, 2); +} + +TEST_F(KissHwControlTest, PipelinedFemRequestsAreAnsweredInArrivalOrder) { + board.has_lna = true; + startTxAndHold(); + serial.takeHardwareFrames(); + + EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}).empty()); + EXPECT_TRUE(hw({HW_CMD_GET_FEM_STATE}).empty()); + EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_TX_GAIN, HW_FEM_TX_GAIN}).empty()); // unsupported bit + EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN}).empty()); // short payload + + radio.send_complete = true; + for (int i = 0; i < 6; i++) modem.loop(); + auto frames = serial.takeHardwareFrames(); + ASSERT_EQ(frames.size(), 5U); + EXPECT_EQ(frames[0], (std::vector<uint8_t>{HW_RESP_TX_DONE, 0x01})); + EXPECT_EQ(frames[1], (std::vector<uint8_t>{0x9F, 0x01, 0x01})); + EXPECT_EQ(frames[2], (std::vector<uint8_t>{0x9F, 0x01, 0x01})); + EXPECT_EQ(frames[3], ERR_UNSUPPORTED); + EXPECT_EQ(frames[4], (std::vector<uint8_t>{HW_RESP_ERROR, HW_ERR_INVALID_LENGTH})); EXPECT_EQ(board.lna_sets, 1); } +TEST_F(KissHwControlTest, FemQueueOverflowRepliesTxBusyImmediately) { + board.has_lna = true; + startTxAndHold(); + serial.takeHardwareFrames(); + for (int i = 0; i < KISS_FEM_OP_QUEUE_DEPTH; i++) { + EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}).empty()); + } + EXPECT_EQ(hw1({HW_CMD_GET_FEM_STATE}), (std::vector<uint8_t>{HW_RESP_ERROR, HW_ERR_TX_BUSY})); + EXPECT_EQ(board.lna_sets, 0); +} + +TEST_F(KissHwControlTest, FemGetWithNothingQueuedIsAnsweredDuringTx) { + board.has_lna = true; + startTxAndHold(); + serial.takeHardwareFrames(); + EXPECT_EQ(hw1({HW_CMD_GET_FEM_STATE}), (std::vector<uint8_t>{0x9F, 0x01, 0x00})); +} + TEST_F(KissHwControlTest, FemGetDuringDeferredSetIsAnsweredAfterSet) { board.has_lna = true; startTxAndHold(); From bc4d0227fe08b89f289f2a5a3226b2fab61ca74b Mon Sep 17 00:00:00 2001 From: agessaman <adam@gessaman.com> Date: Wed, 23 Sep 2026 18:51:03 -0700 Subject: [PATCH 257/381] kiss_modem: default AGC reset interval to 32 s The AGC interval is set in 4 s steps, matching MeshCore's agc.reset.interval, so the old 30 s default could not be restored by a host: setting 30 gives 28. Found on hardware. Use 32 s, the nearest multiple of 4 above it. --- docs/kiss_modem_protocol.md | 4 ++-- examples/kiss_modem/KissModem.h | 2 +- test/test_kiss_modem/test_hw_controls.cpp | 13 ++++++++----- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/docs/kiss_modem_protocol.md b/docs/kiss_modem_protocol.md index 5eb09738..5075cf4c 100644 --- a/docs/kiss_modem_protocol.md +++ b/docs/kiss_modem_protocol.md @@ -227,7 +227,7 @@ All values little-endian. |-------------|---------|-----------------------| | Noise floor | 2 bytes | int16_t, dBm (signed) | -The modem recalibrates the noise floor every 2 seconds. AGC resets follow the configured AGC reset interval (default 30 seconds). +The modem recalibrates the noise floor every 2 seconds. AGC resets follow the configured AGC reset interval (default 32 seconds). ### Capabilities (Capabilities response) @@ -256,7 +256,7 @@ All values little-endian. The modem periodically resets the radio's AGC while idle (no transmission in progress and host output not backed up). The interval has 4-second resolution, matching the MeshCore `agc.reset.interval` setting: requested values are rounded down to a multiple of 4, so 1-3 disable the reset. Values above 1020 return `InvalidParam`. SetAgcResetInterval replies with the AgcResetInterval response carrying the effective value, and restarts the countdown from the time of the request. -The default is 30 seconds. The setting is not persisted; hosts should re-send it after reconnecting or rebooting the modem. +The default is 32 seconds (previously a fixed 30; changed so the default is a settable 4-second multiple). The setting is not persisted; hosts should re-send it after reconnecting or rebooting the modem. ### FEM State (SetFemState / FemState response) diff --git a/examples/kiss_modem/KissModem.h b/examples/kiss_modem/KissModem.h index 24021bdb..bee41634 100644 --- a/examples/kiss_modem/KissModem.h +++ b/examples/kiss_modem/KissModem.h @@ -106,7 +106,7 @@ /* FEM requests are answered strictly in arrival order; this many may wait (e.g. during a TX) */ #define KISS_FEM_OP_QUEUE_DEPTH 4 -#define KISS_AGC_RESET_DEFAULT_SEC 30 +#define KISS_AGC_RESET_DEFAULT_SEC 32 // a multiple of the 4 s step, so hosts can set it back #define KISS_AGC_RESET_MAX_SEC 1020 #define KISS_AGC_RESET_STEP_SEC 4 diff --git a/test/test_kiss_modem/test_hw_controls.cpp b/test/test_kiss_modem/test_hw_controls.cpp index e0fdd729..2b0b779e 100644 --- a/test/test_kiss_modem/test_hw_controls.cpp +++ b/test/test_kiss_modem/test_hw_controls.cpp @@ -208,8 +208,11 @@ TEST_F(KissHwControlTest, CapabilitiesReflectBoardFem) { EXPECT_EQ(hw1({HW_CMD_GET_CAPABILITIES}), (std::vector<uint8_t>{0x9B, 0x07, 0x00, 0x00, 0x00})); } -TEST_F(KissHwControlTest, AgcIntervalDefaultsToThirtySeconds) { - EXPECT_EQ(hw1({HW_CMD_GET_AGC_RESET_INTERVAL}), (std::vector<uint8_t>{0x9D, 30, 0})); +TEST_F(KissHwControlTest, AgcIntervalDefaultsToThirtyTwoSeconds) { + EXPECT_EQ(hw1({HW_CMD_GET_AGC_RESET_INTERVAL}), (std::vector<uint8_t>{0x9D, 32, 0})); + // the default must be restorable, i.e. a multiple of the 4 s step + EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 4, 0}), (std::vector<uint8_t>{0x9D, 4, 0})); + EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, KISS_AGC_RESET_DEFAULT_SEC, 0}), (std::vector<uint8_t>{0x9D, KISS_AGC_RESET_DEFAULT_SEC, 0})); } TEST_F(KissHwControlTest, AgcIntervalSetReturnsEffectiveRoundedValue) { @@ -223,15 +226,15 @@ TEST_F(KissHwControlTest, AgcIntervalSetReturnsEffectiveRoundedValue) { TEST_F(KissHwControlTest, AgcIntervalRejectsOutOfRangeAndShortPayload) { EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 0xFD, 0x03}), (std::vector<uint8_t>{HW_RESP_ERROR, HW_ERR_INVALID_PARAM})); EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 4}), (std::vector<uint8_t>{HW_RESP_ERROR, HW_ERR_INVALID_LENGTH})); - EXPECT_EQ(hw1({HW_CMD_GET_AGC_RESET_INTERVAL}), (std::vector<uint8_t>{0x9D, 30, 0})); + EXPECT_EQ(hw1({HW_CMD_GET_AGC_RESET_INTERVAL}), (std::vector<uint8_t>{0x9D, 32, 0})); } TEST_F(KissHwControlTest, AgcResetsOnDefaultSchedule) { - advance(29999); + advance(31999); EXPECT_EQ(radio.agc_resets, 0); advance(1); EXPECT_EQ(radio.agc_resets, 1); - advance(29999); + advance(31999); EXPECT_EQ(radio.agc_resets, 1); advance(1); EXPECT_EQ(radio.agc_resets, 2); From 49d0dd31411cac824a4668d76c8949f002b5fe43 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Thu, 24 Sep 2026 13:35:27 +1000 Subject: [PATCH 258/381] increased MAX_SEARCH_RESULTS to 24. (was 8) Closes #3243 --- examples/simple_sensor/SensorMesh.h | 2 +- src/helpers/BaseChatMesh.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index 6b7a32fe..8b421081 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -43,7 +43,7 @@ #define FIRMWARE_ROLE "sensor" -#define MAX_SEARCH_RESULTS 8 +#define MAX_SEARCH_RESULTS 24 #define MAX_CONCURRENT_ALERTS 4 class SensorMesh : public mesh::Mesh, public CommonCLICallbacks { diff --git a/src/helpers/BaseChatMesh.h b/src/helpers/BaseChatMesh.h index 0a8fdef4..835384b7 100644 --- a/src/helpers/BaseChatMesh.h +++ b/src/helpers/BaseChatMesh.h @@ -9,7 +9,7 @@ #include "ContactInfo.h" -#define MAX_SEARCH_RESULTS 8 +#define MAX_SEARCH_RESULTS 24 #define MSG_SEND_FAILED 0 #define MSG_SEND_SENT_FLOOD 1 From 5c8ee09635020fdf7a307620bea764445c4977ba Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Thu, 24 Sep 2026 13:49:57 +1000 Subject: [PATCH 259/381] * changed onUnhandledResponse() to return true if handled/consumed * unhandled responses (eg. push telemetry) now sent to app as PUSH_CODE_BINARY_RESPONSE frames --- examples/companion_radio/MyMesh.cpp | 17 +++++++++++++++-- examples/companion_radio/MyMesh.h | 2 +- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 66efc6b0..f32ea67a 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -758,8 +758,21 @@ void MyMesh::onContactResponse(const ContactInfo &contact, const uint8_t *data, memcpy(&out_frame[i], &data[4], len - 4); i += (len - 4); _serial->writeFrame(out_frame, i); - } else if (_listener && len > 4) { - _listener->onUnhandledResponse(contact, tag, &data[4], len - 4); + } else { + bool handled; + if (_listener && len > 4) { + handled = _listener->onUnhandledResponse(contact, tag, &data[4], len - 4); + } else { + handled = false; + } + if (!handled) { // let the app know about unknown/unhandled responses (eg. push telemetry packets) + int i = 0; + out_frame[i++] = PUSH_CODE_BINARY_RESPONSE; + out_frame[i++] = 0; // reserved + memcpy(&out_frame[i], data, len); + i += len; + _serial->writeFrame(out_frame, i); + } } } diff --git a/examples/companion_radio/MyMesh.h b/examples/companion_radio/MyMesh.h index 9f077c30..52a22cb4 100644 --- a/examples/companion_radio/MyMesh.h +++ b/examples/companion_radio/MyMesh.h @@ -101,7 +101,7 @@ public: virtual void onACKRecv(uint32_t ack_crc) { } virtual uint8_t onUnhandledRequest(const ContactInfo &contact, uint32_t sender_timestamp, const uint8_t *data, uint8_t len, uint8_t *reply) { return 0; /* unknown request type */ } - virtual void onUnhandledResponse(const ContactInfo &from, uint32_t tag, const uint8_t* data, uint8_t len) { } + virtual bool onUnhandledResponse(const ContactInfo &from, uint32_t tag, const uint8_t* data, uint8_t len) { return false; /* not handled */ } virtual void onTraceRecv(mesh::Packet *pkt, uint32_t tag, uint32_t auth_code, uint8_t flags, const uint8_t *path_snrs, const uint8_t *path_hashes, uint8_t path_len) { } virtual void onRawDataRecv(mesh::Packet *pkt) { } From 990ea55e2d664140a7f4a913efe3fac1add95859 Mon Sep 17 00:00:00 2001 From: agessaman <adam@gessaman.com> Date: Wed, 23 Sep 2026 21:56:27 -0700 Subject: [PATCH 260/381] radiolib: reapply runtime RX boosted gain on SX126x AGC reset sx126xResetAGC only restored the gain when the build defined SX126X_RX_BOOSTED_GAIN, so a gain set at runtime was lost on reset. Match lr11x0ResetAGC and always reapply. Also pass the gain state from the LLCC68 wrapper, whose call did not match the helper's signature. --- src/helpers/radiolib/CustomLLCC68Wrapper.h | 2 +- src/helpers/radiolib/SX126xReset.h | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/helpers/radiolib/CustomLLCC68Wrapper.h b/src/helpers/radiolib/CustomLLCC68Wrapper.h index 89d5e1bc..e96ae663 100644 --- a/src/helpers/radiolib/CustomLLCC68Wrapper.h +++ b/src/helpers/radiolib/CustomLLCC68Wrapper.h @@ -35,7 +35,7 @@ public: } uint8_t getSpreadingFactor() const override { return ((CustomLLCC68 *)_radio)->spreadingFactor; } - void doResetAGC() override { sx126xResetAGC((SX126x *)_radio); } + void doResetAGC() override { sx126xResetAGC((SX126x *)_radio, getRxBoostedGainMode()); } bool supportsRxBoostedGain() const override { return true; } bool setRxBoostedGainMode(bool en) override { diff --git a/src/helpers/radiolib/SX126xReset.h b/src/helpers/radiolib/SX126xReset.h index 472eb33b..bce84191 100644 --- a/src/helpers/radiolib/SX126xReset.h +++ b/src/helpers/radiolib/SX126xReset.h @@ -25,9 +25,8 @@ inline void sx126xResetAGC(SX126x* radio, bool rx_boost_gain) { #ifdef SX126X_DIO2_AS_RF_SWITCH radio->setDio2AsRfSwitch(SX126X_DIO2_AS_RF_SWITCH); #endif -#ifdef SX126X_RX_BOOSTED_GAIN + // always reapply: the gain may have been changed at runtime even when no build default is set radio->setRxBoostedGainMode(rx_boost_gain); -#endif #ifdef SX126X_REGISTER_PATCH uint8_t r_data = 0; radio->readRegister(0x8B5, &r_data, 1); From c760aaca6a9bb9cf1f7d7ef322be95179f8d6e4b Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Fri, 25 Sep 2026 16:55:17 +1200 Subject: [PATCH 261/381] disable hibernate ui on 1watt wio tracker variant --- variants/wio-tracker-l1-1w/platformio.ini | 2 ++ 1 file changed, 2 insertions(+) diff --git a/variants/wio-tracker-l1-1w/platformio.ini b/variants/wio-tracker-l1-1w/platformio.ini index e5b4a3be..7d3c2dc3 100644 --- a/variants/wio-tracker-l1-1w/platformio.ini +++ b/variants/wio-tracker-l1-1w/platformio.ini @@ -65,6 +65,7 @@ build_flags = ${WioTrackerL1-1W.build_flags} -D MAX_GROUP_CHANNELS=40 -D DISPLAY_CLASS=SH1106Display -D UI_HAS_JOYSTICK=1 + -D UI_NO_HIBERNATE -D OFFLINE_QUEUE_SIZE=256 -D PIN_BUZZER=12 -D QSPIFLASH=1 @@ -96,6 +97,7 @@ build_flags = ${WioTrackerL1-1W.build_flags} -D OFFLINE_QUEUE_SIZE=256 -D DISPLAY_CLASS=SH1106Display -D UI_HAS_JOYSTICK=1 + -D UI_NO_HIBERNATE -D PIN_BUZZER=12 -D QSPIFLASH=1 -D RADIO_FEM_TXGAIN=1 From 2a26f08d744acb01bedf2d0f6d0704134bfffac4 Mon Sep 17 00:00:00 2001 From: Marcel Verdult <marcel@verdult.de> Date: Sat, 26 Sep 2026 14:07:28 +0200 Subject: [PATCH 262/381] Fix RAK11310 build: add no-op attachDynamicPrefs() --- variants/rak11310/RAK11310Board.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/variants/rak11310/RAK11310Board.h b/variants/rak11310/RAK11310Board.h index ea0f15e2..5b75ac36 100644 --- a/variants/rak11310/RAK11310Board.h +++ b/variants/rak11310/RAK11310Board.h @@ -2,6 +2,7 @@ #include <Arduino.h> #include <MeshCore.h> +#include <helpers/KeyValueStore.h> // from https://github.com/RAKWireless/RAK11300-AT-Command-Firmware/blob/9c48409a43620a828d653501d536473200aa33af/RAK11300-AT-Arduino/batt.cpp#L17-L19 #define VBAT_MV_PER_LSB (0.806F) // 3.0V ADC range and 12 - bit ADC resolution = 3300mV / 4096 @@ -46,4 +47,6 @@ public: void reboot() override { rp2040.reboot(); } bool startOTAUpdate(const char *id, char reply[]) override; + + void attachDynamicPrefs(KeyValueStore* prefs) { } // no-op }; From a1b5655af190b75ded7282c32800119202b60d78 Mon Sep 17 00:00:00 2001 From: Marcel Verdult <marcel@verdult.de> Date: Sat, 26 Sep 2026 20:39:23 +0200 Subject: [PATCH 263/381] Fix ThinkNode M8 repeater/room server build: compile sensor helpers for all envs --- variants/thinknode_m8/platformio.ini | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/variants/thinknode_m8/platformio.ini b/variants/thinknode_m8/platformio.ini index db19e446..57f2a938 100644 --- a/variants/thinknode_m8/platformio.ini +++ b/variants/thinknode_m8/platformio.ini @@ -40,6 +40,7 @@ build_flags = ${nrf52_base.build_flags} -D LORA_TX_POWER=22 build_src_filter = ${nrf52_base.build_src_filter} +<helpers/*.cpp> + +<helpers/sensors> +<ThinkNodeM8Board.cpp> +<../variants/thinknode_m8> lib_deps = @@ -110,7 +111,6 @@ build_src_filter = ${ThinkNode_M8.build_src_filter} +<helpers/ui/buzzer.cpp> +<helpers/ui/MomentaryButton.cpp> +<helpers/ui/RotaryInputGPIO.cpp> - +<helpers/sensors/EnvironmentSensorManager.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = @@ -144,7 +144,6 @@ build_src_filter = ${ThinkNode_M8.build_src_filter} +<helpers/ui/buzzer.cpp> +<helpers/ui/MomentaryButton.cpp> +<helpers/ui/RotaryInputGPIO.cpp> - +<helpers/sensors/EnvironmentSensorManager.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = From b463f4dbd1659bab1a7d845540934fb0d3abf68e Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Tue, 29 Sep 2026 20:10:51 +1000 Subject: [PATCH 264/381] feat: add waitFor() and drain() to LocationProvider to support sending commands to GPS --- src/helpers/sensors/LocationProvider.h | 2 ++ .../sensors/MicroNMEALocationProvider.h | 21 +++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/helpers/sensors/LocationProvider.h b/src/helpers/sensors/LocationProvider.h index 81d08652..e11b738b 100644 --- a/src/helpers/sensors/LocationProvider.h +++ b/src/helpers/sensors/LocationProvider.h @@ -17,6 +17,8 @@ public: virtual bool isValid() = 0; virtual long getTimestamp() = 0; virtual void sendSentence(const char * sentence); + virtual bool waitFor(const char* prefix, uint32_t timeout_ms) { return false; } + virtual void drain() { } virtual void reset() = 0; virtual void begin() = 0; virtual void stop() = 0; diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index b66cb114..e559ad01 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -129,10 +129,31 @@ public : return dt.unixtime(); } + void drain() { while (_gps_serial->available()) _gps_serial->read(); } + + const char* getSentence() const { return nmea.getSentence(); } + void sendSentence(const char *sentence) override { nmea.sendSentence(*_gps_serial, sentence); } + bool waitFor(const char* prefix, uint32_t timeout_ms) { + size_t plen = strlen(prefix); + uint32_t timeout = millis() + timeout_ms; + while ((int32_t)(millis() - timeout) < 0) { + if (_gps_serial->available()) { + char c = _gps_serial->read(); + #ifdef GPS_NMEA_DEBUG + Serial.print(c); + #endif + if (nmea.process(c) && strncmp(nmea.getSentence(), prefix, plen) == 0) return true; + } else { + yield(); + } + } + return false; + } + void loop() override { while (_gps_serial->available()) { From 3f1057c9a0226891491b9085c95304437ecccf0d Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Tue, 29 Sep 2026 20:12:08 +1000 Subject: [PATCH 265/381] feat: add AirohaSleep.h helper for faster fix on AG3335 based GPS --- src/helpers/sensors/AirohaSleep.h | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 src/helpers/sensors/AirohaSleep.h diff --git a/src/helpers/sensors/AirohaSleep.h b/src/helpers/sensors/AirohaSleep.h new file mode 100644 index 00000000..6637d0fb --- /dev/null +++ b/src/helpers/sensors/AirohaSleep.h @@ -0,0 +1,19 @@ +#pragma once +#include <helpers/sensors/LocationProvider.h> + +// Board must keep the GPS RTC backup pin powered and can cut GPS power once we return. +// Returns true if the command was acked within 3 attempts, otherwise returns false. +static inline bool airohaEnterSleep(LocationProvider* nmea) { + for (uint8_t attempt = 0; attempt < 3; attempt++) { + nmea->drain(); + nmea->sendSentence("$PAIR650,0"); + if (nmea->waitFor("$PAIR001,650,0", 50)) { // wait for the command received signal + #ifdef GPS_NMEA_DEBUG + Serial.printf("Airoha RTC Backup sleep command accepted by GPS after %u attempts\r\n", attempt + 1); + #endif + nmea->waitFor("$PAIR650,0", 50); // give the GPS 50ms grace to signal it is ready for sleep + return true; + } + } + return false; +} \ No newline at end of file From 58dac7899b132310da778084aaaa595d7eb6cf4f Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Tue, 29 Sep 2026 20:14:19 +1000 Subject: [PATCH 266/381] MeshTracker X1 GPS: use RTC backup for faster fix --- variants/meshtracker_x1/target.cpp | 38 ++++++++---------------------- 1 file changed, 10 insertions(+), 28 deletions(-) diff --git a/variants/meshtracker_x1/target.cpp b/variants/meshtracker_x1/target.cpp index d6d548b5..5b90d660 100644 --- a/variants/meshtracker_x1/target.cpp +++ b/variants/meshtracker_x1/target.cpp @@ -1,6 +1,7 @@ #include <Arduino.h> #include "target.h" #include <helpers/sensors/MicroNMEALocationProvider.h> +#include <helpers/sensors/AirohaSleep.h> MeshTrackerX1Board board; @@ -27,46 +28,27 @@ mesh::LocalIdentity radio_new_identity() { void MeshTrackerX1SensorManager::start_gps() { gps_active = true; - // this init sequence comes from seeed examples and deals with all gps pins - pinMode(GPS_EN, OUTPUT); digitalWrite(GPS_EN, HIGH); delay(10); - pinMode(GPS_VRTC_EN, OUTPUT); - digitalWrite(GPS_VRTC_EN, HIGH); - delay(10); - - pinMode(GPS_RESET, OUTPUT); - digitalWrite(GPS_RESET, HIGH); - delay(10); - digitalWrite(GPS_RESET, LOW); - - pinMode(GPS_SLEEP_INT, OUTPUT); - digitalWrite(GPS_SLEEP_INT, HIGH); - pinMode(GPS_RTC_INT, OUTPUT); - digitalWrite(GPS_RTC_INT, LOW); -} - -void MeshTrackerX1SensorManager::sleep_gps() { - gps_active = false; - digitalWrite(GPS_VRTC_EN, HIGH); // keep RTC alive for faster fix on wake - digitalWrite(GPS_EN, LOW); - digitalWrite(GPS_RESET, LOW); - digitalWrite(GPS_SLEEP_INT, HIGH); + digitalWrite(GPS_RTC_INT, HIGH); + delay(5); digitalWrite(GPS_RTC_INT, LOW); } void MeshTrackerX1SensorManager::stop_gps() { gps_active = false; - digitalWrite(GPS_VRTC_EN, LOW); + digitalWrite(GPS_VRTC_EN, HIGH); // keep GPS RTC alive for faster fix on wake + digitalWrite(GPS_RTC_INT, LOW); // make sure this is LOW so we can pulse it to wake + airohaEnterSleep(_nmea); digitalWrite(GPS_EN, LOW); - digitalWrite(GPS_RESET, LOW); - digitalWrite(GPS_SLEEP_INT, HIGH); - digitalWrite(GPS_RTC_INT, LOW); } bool MeshTrackerX1SensorManager::begin() { // init GPS Serial1.begin(GPS_BAUD_RATE); + digitalWrite(GPS_RESET, HIGH); + delay(10); + digitalWrite(GPS_RESET, LOW); // init SPA06-003 barometer baro_ok = spa06.begin(SPA06_003_DEFAULT_ADDR, &Wire) || spa06.begin(0x76, &Wire); @@ -122,7 +104,7 @@ const char* MeshTrackerX1SensorManager::getSettingValue(int i) const { bool MeshTrackerX1SensorManager::setSettingValue(const char* name, const char* value) { if (strcmp(name, "gps") == 0) { if (strcmp(value, "0") == 0) { - sleep_gps(); // sleep for faster fix ! + stop_gps(); } else { start_gps(); } From ed1a763c4929da1aebe1c6f96c2d0be6036f596a Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Tue, 29 Sep 2026 20:16:32 +1000 Subject: [PATCH 267/381] T1000e GPS: use RTC backup for faster fix --- variants/t1000-e/target.cpp | 48 ++++++++---------------------------- variants/t1000-e/variant.cpp | 8 +++--- 2 files changed, 14 insertions(+), 42 deletions(-) diff --git a/variants/t1000-e/target.cpp b/variants/t1000-e/target.cpp index 42532827..70a64359 100644 --- a/variants/t1000-e/target.cpp +++ b/variants/t1000-e/target.cpp @@ -2,6 +2,7 @@ #include "t1000e_sensors.h" #include "target.h" #include <helpers/sensors/MicroNMEALocationProvider.h> +#include <helpers/sensors/AirohaSleep.h> T1000eBoard board; @@ -81,56 +82,28 @@ mesh::LocalIdentity radio_new_identity() { void T1000SensorManager::start_gps() { gps_active = true; - //_nmea->begin(); - // this init sequence should be better - // comes from seeed examples and deals with all gps pins - pinMode(GPS_EN, OUTPUT); digitalWrite(GPS_EN, HIGH); delay(10); - pinMode(GPS_VRTC_EN, OUTPUT); - digitalWrite(GPS_VRTC_EN, HIGH); - delay(10); - - pinMode(GPS_RESET, OUTPUT); - digitalWrite(GPS_RESET, HIGH); - delay(10); - digitalWrite(GPS_RESET, LOW); - - pinMode(GPS_SLEEP_INT, OUTPUT); - digitalWrite(GPS_SLEEP_INT, HIGH); - pinMode(GPS_RTC_INT, OUTPUT); + digitalWrite(GPS_RTC_INT, HIGH); + delay(5); digitalWrite(GPS_RTC_INT, LOW); - pinMode(GPS_RESETB, INPUT_PULLUP); -} - -void T1000SensorManager::sleep_gps() { - gps_active = false; - digitalWrite(GPS_VRTC_EN, HIGH); - digitalWrite(GPS_EN, LOW); - digitalWrite(GPS_RESET, HIGH); - digitalWrite(GPS_SLEEP_INT, HIGH); - digitalWrite(GPS_RTC_INT, LOW); - pinMode(GPS_RESETB, OUTPUT); - digitalWrite(GPS_RESETB, LOW); - //_nmea->stop(); } void T1000SensorManager::stop_gps() { gps_active = false; - digitalWrite(GPS_VRTC_EN, LOW); + digitalWrite(GPS_VRTC_EN, HIGH); // keep GPS RTC alive for faster fix on wake + digitalWrite(GPS_RTC_INT, LOW); // make sure this is LOW so we can pulse it to wake + airohaEnterSleep(_nmea); // send command to put the GPS into RTC backup sleep digitalWrite(GPS_EN, LOW); - digitalWrite(GPS_RESET, HIGH); - digitalWrite(GPS_SLEEP_INT, HIGH); - digitalWrite(GPS_RTC_INT, LOW); - pinMode(GPS_RESETB, OUTPUT); - digitalWrite(GPS_RESETB, LOW); - //_nmea->stop(); } bool T1000SensorManager::begin() { // init GPS Serial1.begin(115200); + digitalWrite(GPS_RESET, HIGH); + delay(10); + digitalWrite(GPS_RESET, LOW); return true; } @@ -156,7 +129,6 @@ void T1000SensorManager::loop() { node_lat = ((double)_nmea->getLatitude())/1000000.; node_lon = ((double)_nmea->getLongitude())/1000000.; node_altitude = ((double)_nmea->getAltitude()) / 1000.0; - //Serial.printf("lat %f lon %f\r\n", _lat, _lon); } next_gps_update = millis() + 1000; } @@ -176,7 +148,7 @@ const char* T1000SensorManager::getSettingValue(int i) const { bool T1000SensorManager::setSettingValue(const char* name, const char* value) { if (strcmp(name, "gps") == 0) { if (strcmp(value, "0") == 0) { - sleep_gps(); // sleep for faster fix ! + stop_gps(); } else { start_gps(); } diff --git a/variants/t1000-e/variant.cpp b/variants/t1000-e/variant.cpp index ed21fd68..fc30a619 100644 --- a/variants/t1000-e/variant.cpp +++ b/variants/t1000-e/variant.cpp @@ -71,7 +71,7 @@ void initVariant() pinMode(LUX_SENSOR, INPUT); pinMode(EXT_CHRG_DETECT, INPUT); pinMode(EXT_PWR_DETECT, INPUT); - pinMode(GPS_RESETB, INPUT); + pinMode(GPS_RESETB, INPUT_PULLUP); pinMode(PIN_BUTTON1, INPUT); pinMode(PIN_3V3_EN, OUTPUT); @@ -89,10 +89,10 @@ void initVariant() digitalWrite(PIN_3V3_ACC_EN, LOW); digitalWrite(BUZZER_EN, LOW); digitalWrite(SENSOR_EN, LOW); - digitalWrite(GPS_EN, LOW); + digitalWrite(GPS_EN, HIGH); digitalWrite(GPS_RESET, LOW); - digitalWrite(GPS_VRTC_EN, LOW); - digitalWrite(GPS_SLEEP_INT, HIGH); + digitalWrite(GPS_VRTC_EN, HIGH); + digitalWrite(GPS_SLEEP_INT, LOW); digitalWrite(GPS_RTC_INT, LOW); digitalWrite(LED_PIN, LOW); } From e616e3c94203896441d2c3909a25ad7ceb728d60 Mon Sep 17 00:00:00 2001 From: Huw Duddy <37787853+oltaco@users.noreply.github.com> Date: Thu, 1 Oct 2026 22:17:44 +1000 Subject: [PATCH 268/381] Revert "Fix Heltec Mesh Node T1 GNSS pins" --- variants/heltec_t1/variant.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/variants/heltec_t1/variant.h b/variants/heltec_t1/variant.h index 70ec23f7..de40ea64 100644 --- a/variants/heltec_t1/variant.h +++ b/variants/heltec_t1/variant.h @@ -137,8 +137,8 @@ #define GPS_EN_ACTIVE LOW #define PIN_GPS_EN_ACTIVE LOW #define PIN_GPS_PPS (32 + 9) -#define GPS_RX_PIN (0 + 8) -#define GPS_TX_PIN (0 + 7) +#define GPS_TX_PIN (0 + 8) +#define GPS_RX_PIN (0 + 7) #define PIN_GPS_TX GPS_TX_PIN #define PIN_GPS_RX GPS_RX_PIN From ec565e06bffd3ea41c297bb23e99d7537ef5f874 Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Fri, 2 Oct 2026 07:35:34 +1000 Subject: [PATCH 269/381] fix bad comment format --- src/helpers/nrf52/SerialBLEInterface.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/helpers/nrf52/SerialBLEInterface.cpp b/src/helpers/nrf52/SerialBLEInterface.cpp index 2e5626a8..fa091c03 100644 --- a/src/helpers/nrf52/SerialBLEInterface.cpp +++ b/src/helpers/nrf52/SerialBLEInterface.cpp @@ -129,10 +129,10 @@ void SerialBLEInterface::begin(const char* prefix, char* name, uint32_t pin_code char charpin[20]; snprintf(charpin, sizeof(charpin), "%lu", (unsigned long)pin_code); - #ifdef DISABLE_BLE_LED \\ use variant platformio.ini build_flags macro: -D DISABLE_BLE_LED - Bluefruit.autoConnLed(false); \\ false removes the automatic control of the LED by the Bluefruit library + #ifdef DISABLE_BLE_LED // use variant platformio.ini build_flags macro: -D DISABLE_BLE_LED + Bluefruit.autoConnLed(false); // false removes the automatic control of the LED by the Bluefruit library #else - Bluefruit.autoConnLed(true); \\ true leaves the default automatic control of the LED by the Bluefruit library + Bluefruit.autoConnLed(true); // true leaves the default automatic control of the LED by the Bluefruit library #endif // If we want to control BLE LED ourselves, uncomment this: From c10ea278ff94cca3b27733276f9aa93d0c19860b Mon Sep 17 00:00:00 2001 From: taco <taco@sly.nu> Date: Fri, 2 Oct 2026 07:40:42 +1000 Subject: [PATCH 270/381] tidy: remove old commented Bluefruit.autoConnLed(false) --- src/helpers/nrf52/SerialBLEInterface.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/helpers/nrf52/SerialBLEInterface.cpp b/src/helpers/nrf52/SerialBLEInterface.cpp index fa091c03..6ed16bc8 100644 --- a/src/helpers/nrf52/SerialBLEInterface.cpp +++ b/src/helpers/nrf52/SerialBLEInterface.cpp @@ -135,8 +135,6 @@ void SerialBLEInterface::begin(const char* prefix, char* name, uint32_t pin_code Bluefruit.autoConnLed(true); // true leaves the default automatic control of the LED by the Bluefruit library #endif - // If we want to control BLE LED ourselves, uncomment this: - // Bluefruit.autoConnLed(false); Bluefruit.configPrphBandwidth(BANDWIDTH_MAX); Bluefruit.begin(); From 48aae4072dd527a75fd7a50fe12790302f1bd5e1 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Sun, 4 Oct 2026 15:02:00 +1100 Subject: [PATCH 271/381] * don't respond to DISCOVER requests if node has adverts turned off. (isHiddenNode()) --- examples/simple_repeater/MyMesh.cpp | 1 + examples/simple_repeater/MyMesh.h | 3 +++ 2 files changed, 4 insertions(+) diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index ca6a3e60..61b6c149 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -790,6 +790,7 @@ void MyMesh::onControlDataRecv(mesh::Packet* packet) { uint8_t type = packet->payload[0] & 0xF0; // just test upper 4 bits if (type == CTL_TYPE_NODE_DISCOVER_REQ && packet->payload_len >= 6 && !_prefs.disable_fwd && discover_limiter.allow(rtc_clock.getCurrentTime()) + && !isHiddenNode() // this node wishes to NOT be discoverable ) { int i = 1; uint8_t filter = packet->payload[i++]; diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index cac6c4a2..a9ac453a 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -187,6 +187,9 @@ public: NodePrefs* getNodePrefs() { return &_prefs; } + bool isHiddenNode() const { + return _prefs.advert_interval == 0 && _prefs.flood_advert_interval == 0; + } void savePrefs() override { _cli.savePrefs(_fs); From 2546d47055bd12ae23f8f533875a26165078c0f6 Mon Sep 17 00:00:00 2001 From: Sebastian Muszynski <basti@linkt.de> Date: Tue, 6 Oct 2026 18:50:15 +0200 Subject: [PATCH 272/381] Use consistent `_OTA` suffix for nRF52 OTA BLE names --- variants/lilygo_t_impulse_plus/TImpulsePlusBoard.h | 2 +- variants/meshtiny/MeshtinyBoard.h | 2 +- variants/wio-tracker-l1-1w/WioTrackerL1Board.h | 2 +- variants/wio-tracker-l1/WioTrackerL1Board.h | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/variants/lilygo_t_impulse_plus/TImpulsePlusBoard.h b/variants/lilygo_t_impulse_plus/TImpulsePlusBoard.h index 30bbc3a5..f7ef536b 100644 --- a/variants/lilygo_t_impulse_plus/TImpulsePlusBoard.h +++ b/variants/lilygo_t_impulse_plus/TImpulsePlusBoard.h @@ -9,7 +9,7 @@ protected: uint8_t btn_prev_state; public: - TImpulsePlusBoard() : NRF52Board("T-Impulse-Plus OTA") {} + TImpulsePlusBoard() : NRF52Board("T-Impulse-Plus_OTA") {} void begin(); #if defined(P_LORA_TX_LED) diff --git a/variants/meshtiny/MeshtinyBoard.h b/variants/meshtiny/MeshtinyBoard.h index 67a521fe..21673d0a 100644 --- a/variants/meshtiny/MeshtinyBoard.h +++ b/variants/meshtiny/MeshtinyBoard.h @@ -9,7 +9,7 @@ protected: uint8_t btn_prev_state; public: - MeshtinyBoard() : NRF52Board("Meshtiny OTA") {} + MeshtinyBoard() : NRF52Board("Meshtiny_OTA") {} void begin(); #if defined(P_LORA_TX_LED) diff --git a/variants/wio-tracker-l1-1w/WioTrackerL1Board.h b/variants/wio-tracker-l1-1w/WioTrackerL1Board.h index 798145db..f6164e47 100644 --- a/variants/wio-tracker-l1-1w/WioTrackerL1Board.h +++ b/variants/wio-tracker-l1-1w/WioTrackerL1Board.h @@ -14,7 +14,7 @@ protected: bool isLoRaFemPaGainEnabled() const { return _is_pa_enabled; } public: - WioTrackerL1Board() : NRF52Board("WioTrackerL1 OTA") {} + WioTrackerL1Board() : NRF52Board("WioTrackerL1_OTA") {} void begin(); void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; diff --git a/variants/wio-tracker-l1/WioTrackerL1Board.h b/variants/wio-tracker-l1/WioTrackerL1Board.h index e376e066..99e852bb 100644 --- a/variants/wio-tracker-l1/WioTrackerL1Board.h +++ b/variants/wio-tracker-l1/WioTrackerL1Board.h @@ -9,7 +9,7 @@ protected: uint8_t btn_prev_state; public: - WioTrackerL1Board() : NRF52Board("WioTrackerL1 OTA") {} + WioTrackerL1Board() : NRF52Board("WioTrackerL1_OTA") {} void begin(); #if defined(P_LORA_TX_LED) From f7b2acf2a013d805b15446fb9b3e73ef91faeccc Mon Sep 17 00:00:00 2001 From: quyenlt298 <61147413+quyenlt298@users.noreply.github.com> Date: Wed, 7 Oct 2026 13:09:36 +0700 Subject: [PATCH 273/381] Add Nelos allocation for GroupData --- docs/number_allocations.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/number_allocations.md b/docs/number_allocations.md index b8cc22a2..79cc90b8 100644 --- a/docs/number_allocations.md +++ b/docs/number_allocations.md @@ -19,6 +19,7 @@ Once you have a working app/project, you need to be able to demonstrate it exist | 0110 - 011F | Ripple | ripple_biz@protonmail.com — https://buymeacoffee.com/ripplebiz | | 0120 | MCO Advanced | most.original.address@gmail.com — https://hdden.ru/MCOa/ | | 0130 - 013F | StreamSensor | william@housedillon.com - https://housedillon.com/blog/lora-e5-with-seeed-fusion | +| 0140 | Nelos | support@nelos.app — https://nelos.app | | FF00 - FFFF | -reserved for testing/dev- | | (add rows, inside the range 0100 - FEFF for custom apps) From 68b8163fe7a650e669d182095342f706728147b0 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Thu, 8 Oct 2026 19:56:45 +1100 Subject: [PATCH 274/381] * treat transport code 0 the same as un-scoped. --- src/helpers/RegionMap.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/helpers/RegionMap.cpp b/src/helpers/RegionMap.cpp index 4667e003..d8d77380 100644 --- a/src/helpers/RegionMap.cpp +++ b/src/helpers/RegionMap.cpp @@ -188,6 +188,7 @@ int RegionMap::getTransportKeysFor(const RegionEntry& src, TransportKey dest[], } RegionEntry* RegionMap::findMatch(mesh::Packet* packet, uint8_t mask) { + if (packet->transport_codes[0] == 0) return &wildcard; for (int i = 0; i < num_regions; i++) { auto region = ®ions[i]; if ((region->flags & mask) == 0) { // does region allow this? (per 'mask' param) From 7369c647522727509b185133b0c5d2b77d5a71de Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Mon, 12 Oct 2026 10:44:42 +1100 Subject: [PATCH 275/381] * ACK forwarding (in direct mode) had zero delay --- src/Mesh.cpp | 12 ++++++------ src/Mesh.h | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Mesh.cpp b/src/Mesh.cpp index c11f37ca..9dc42f0b 100644 --- a/src/Mesh.cpp +++ b/src/Mesh.cpp @@ -87,13 +87,14 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) { } if (self_id.isHashMatch(pkt->path, pkt->getPathHashSize()) && allowPacketForward(pkt)) { + uint32_t d = getDirectRetransmitDelay(pkt); if (pkt->getPayloadType() == PAYLOAD_TYPE_MULTIPART) { - return forwardMultipartDirect(pkt); + return forwardMultipartDirect(pkt, d); } else if (pkt->getPayloadType() == PAYLOAD_TYPE_ACK) { if (!_tables->wasSeen(pkt)) { // don't retransmit! _tables->markSeen(pkt); removeSelfFromPath(pkt); - routeDirectRecvAcks(pkt, 0); + routeDirectRecvAcks(pkt, d); } return ACTION_RELEASE; } @@ -102,7 +103,6 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) { _tables->markSeen(pkt); removeSelfFromPath(pkt); - uint32_t d = getDirectRetransmitDelay(pkt); return ACTION_RETRANSMIT_DELAYED(0, d); // Routed traffic is HIGHEST priority } } @@ -356,7 +356,7 @@ DispatcherAction Mesh::routeRecvPacket(Packet* packet) { return ACTION_RELEASE; } -DispatcherAction Mesh::forwardMultipartDirect(Packet* pkt) { +DispatcherAction Mesh::forwardMultipartDirect(Packet* pkt, uint32_t delay_millis) { uint8_t remaining = pkt->payload[0] >> 4; // num of packets in this multipart sequence still to be sent uint8_t type = pkt->payload[0] & 0x0F; @@ -370,7 +370,7 @@ DispatcherAction Mesh::forwardMultipartDirect(Packet* pkt) { if (!_tables->wasSeen(&tmp)) { // don't retransmit! _tables->markSeen(&tmp); removeSelfFromPath(&tmp); - routeDirectRecvAcks(&tmp, ((uint32_t)remaining + 1) * 300); // expect multipart ACKs 300ms apart (x2) + routeDirectRecvAcks(&tmp, delay_millis + ((uint32_t)remaining + 1) * 300); // expect multipart ACKs 300ms apart (x2) } } return ACTION_RELEASE; @@ -380,13 +380,13 @@ void Mesh::routeDirectRecvAcks(Packet* packet, uint32_t delay_millis) { if (!packet->isMarkedDoNotRetransmit()) { uint8_t extra = getExtraAckTransmitCount(); while (extra > 0) { - delay_millis += getDirectRetransmitDelay(packet) + 300; auto a1 = createMultiAck(packet->payload, packet->payload_len, extra); if (a1) { a1->path_len = Packet::copyPath(a1->path, packet->path, packet->path_len); a1->header &= ~PH_ROUTE_MASK; a1->header |= ROUTE_TYPE_DIRECT; sendPacket(a1, 0, delay_millis); + delay_millis += 300; } extra--; } diff --git a/src/Mesh.h b/src/Mesh.h index 49a299a6..22bb5c6d 100644 --- a/src/Mesh.h +++ b/src/Mesh.h @@ -32,7 +32,7 @@ class Mesh : public Dispatcher { void removeSelfFromPath(Packet* packet); void routeDirectRecvAcks(Packet* packet, uint32_t delay_millis); //void routeRecvAcks(Packet* packet, uint32_t delay_millis); - DispatcherAction forwardMultipartDirect(Packet* pkt); + DispatcherAction forwardMultipartDirect(Packet* pkt, uint32_t delay_millis); protected: DispatcherAction onRecvPacket(Packet* pkt) override; From 223389e9367af990cc8f928294dc7cf9ee3d7472 Mon Sep 17 00:00:00 2001 From: agessaman <adam@gessaman.com> Date: Sun, 11 Oct 2026 20:51:18 -0700 Subject: [PATCH 276/381] feat(variants): add Waveshare ESP32-S3-LR1121 ESP32-S3FH4R2 (4MB flash, 2MB PSRAM, native USB-CDC) with an LR1121. Pins, the DIO5/DIO6 RF switch table and the 1.8 V TCXO follow the HF schematic and Waveshare's examples. Envs: repeater, room server, companion USB/BLE and KISS modem, all on min_spiffs so roles share one partition layout. Only RFO_HP_LF is wired (R4 on RFO_LP_LF is not fitted), so the new opt-in LR1121_FORCE_HP_PA flag keeps RadioLib on the HP PA at <= 14 dBm, where it would otherwise select the unconnected LP PA. --- src/helpers/radiolib/CustomLR1121.h | 7 ++ .../WaveshareS3LR1121Board.h | 11 ++ .../waveshare_esp32s3_lr1121/platformio.ini | 102 ++++++++++++++++++ variants/waveshare_esp32s3_lr1121/target.cpp | 63 +++++++++++ variants/waveshare_esp32s3_lr1121/target.h | 17 +++ 5 files changed, 200 insertions(+) create mode 100644 variants/waveshare_esp32s3_lr1121/WaveshareS3LR1121Board.h create mode 100644 variants/waveshare_esp32s3_lr1121/platformio.ini create mode 100644 variants/waveshare_esp32s3_lr1121/target.cpp create mode 100644 variants/waveshare_esp32s3_lr1121/target.h diff --git a/src/helpers/radiolib/CustomLR1121.h b/src/helpers/radiolib/CustomLR1121.h index 67e3b52a..e8c6c431 100644 --- a/src/helpers/radiolib/CustomLR1121.h +++ b/src/helpers/radiolib/CustomLR1121.h @@ -36,6 +36,13 @@ class CustomLR1121 : public LR1121 { return len; } +#ifdef LR1121_FORCE_HP_PA + // boards with only RFO_HP_LF wired: stop RadioLib switching to the LP PA at <= 14 dBm (2.4 GHz still uses the HF PA) + int16_t setOutputPower(int8_t power) override { + return LR1121::setOutputPower(power, true); + } +#endif + float getFreqMHz() const { return freqMHz; } int16_t setRxBoostedGainMode(bool en) { diff --git a/variants/waveshare_esp32s3_lr1121/WaveshareS3LR1121Board.h b/variants/waveshare_esp32s3_lr1121/WaveshareS3LR1121Board.h new file mode 100644 index 00000000..8307ba50 --- /dev/null +++ b/variants/waveshare_esp32s3_lr1121/WaveshareS3LR1121Board.h @@ -0,0 +1,11 @@ +#pragma once + +#include <Arduino.h> +#include <helpers/ESP32Board.h> + +class WaveshareS3LR1121Board : public ESP32Board { +public: + const char* getManufacturerName() const override { + return "Waveshare ESP32-S3-LR1121"; + } +}; diff --git a/variants/waveshare_esp32s3_lr1121/platformio.ini b/variants/waveshare_esp32s3_lr1121/platformio.ini new file mode 100644 index 00000000..8e7b52d4 --- /dev/null +++ b/variants/waveshare_esp32s3_lr1121/platformio.ini @@ -0,0 +1,102 @@ +; Waveshare ESP32-S3-LR1121 (HF: 850-930 MHz + 2.4 GHz) +; ESP32-S3FH4R2 (4MB flash, 2MB PSRAM), native USB-CDC via the Tiny-Adapter FPC. +; No user LED, battery sense or user button (BOOT is GPIO0). +[Waveshare_S3_LR1121] +extends = esp32_base +board = esp32-s3-zero +; min_spiffs: 1.9MB OTA app slots; one layout for every role so switching roles keeps the filesystem +board_build.partitions = min_spiffs.csv +build_flags = ${esp32_base.build_flags} + -I variants/waveshare_esp32s3_lr1121 + -D BOARD_HAS_PSRAM + -D P_LORA_DIO_1=38 + -D P_LORA_NSS=42 + -D P_LORA_RESET=39 + -D P_LORA_BUSY=41 + -D P_LORA_SCLK=40 + -D P_LORA_MISO=46 + -D P_LORA_MOSI=45 + -D RADIO_CLASS=CustomLR1121 + -D WRAPPER_CLASS=CustomLR1121Wrapper + -D LR11X0_DIO3_TCXO_VOLTAGE=1.8 + -D LR1121_FORCE_HP_PA ; RFO_LP_LF is not fitted (R4 NC) + -D RX_BOOSTED_GAIN=true + -D LORA_TX_POWER=22 +build_src_filter = ${esp32_base.build_src_filter} + +<../variants/waveshare_esp32s3_lr1121> +lib_deps = + ${esp32_base.lib_deps} + +[env:Waveshare_S3_LR1121_repeater] +extends = Waveshare_S3_LR1121 +build_flags = + ${Waveshare_S3_LR1121.build_flags} + -D ADVERT_NAME='"Waveshare LR1121 Repeater"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=50 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${Waveshare_S3_LR1121.build_src_filter} + +<../examples/simple_repeater/*.cpp> +lib_deps = + ${Waveshare_S3_LR1121.lib_deps} + ${esp32_ota.lib_deps} + +[env:Waveshare_S3_LR1121_room_server] +extends = Waveshare_S3_LR1121 +build_flags = + ${Waveshare_S3_LR1121.build_flags} + -D ADVERT_NAME='"Waveshare LR1121 Room"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D ROOM_PASSWORD='"hello"' +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${Waveshare_S3_LR1121.build_src_filter} + +<../examples/simple_room_server> +lib_deps = + ${Waveshare_S3_LR1121.lib_deps} + ${esp32_ota.lib_deps} + +[env:Waveshare_S3_LR1121_companion_radio_usb] +extends = Waveshare_S3_LR1121 +build_flags = + ${Waveshare_S3_LR1121.build_flags} + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_USB_INTERFACE +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${Waveshare_S3_LR1121.build_src_filter} + +<helpers/esp32/*.cpp> + +<../examples/companion_radio/*.cpp> +lib_deps = + ${Waveshare_S3_LR1121.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[env:Waveshare_S3_LR1121_companion_radio_ble] +extends = Waveshare_S3_LR1121 +build_flags = + ${Waveshare_S3_LR1121.build_flags} + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D OFFLINE_QUEUE_SIZE=256 + -D BLE_PIN_CODE=123456 +; -D BLE_DEBUG_LOGGING=1 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${Waveshare_S3_LR1121.build_src_filter} + +<helpers/esp32/*.cpp> + +<../examples/companion_radio/*.cpp> +lib_deps = + ${Waveshare_S3_LR1121.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[env:Waveshare_S3_LR1121_kiss_modem] +extends = Waveshare_S3_LR1121 +build_src_filter = ${Waveshare_S3_LR1121.build_src_filter} + +<../examples/kiss_modem/> diff --git a/variants/waveshare_esp32s3_lr1121/target.cpp b/variants/waveshare_esp32s3_lr1121/target.cpp new file mode 100644 index 00000000..56775c4c --- /dev/null +++ b/variants/waveshare_esp32s3_lr1121/target.cpp @@ -0,0 +1,63 @@ +#include <Arduino.h> +#include "target.h" + +WaveshareS3LR1121Board board; + +static SPIClass spi; +RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi); +WRAPPER_CLASS radio_driver(radio, board); + +ESP32RTCClock fallback_clock; +AutoDiscoverRTCClock rtc_clock(fallback_clock); +SensorManager sensors; + +#ifndef LORA_CR + #define LORA_CR 5 +#endif + +// DIO5/DIO6 drive the RTC6603SP sub-GHz T/R switch; the 2.4 GHz port (RFIO_HF) is unswitched +static const uint32_t rfswitch_dios[Module::RFSWITCH_MAX_PINS] = { + RADIOLIB_LR11X0_DIO5, + RADIOLIB_LR11X0_DIO6, + RADIOLIB_NC +}; + +static const Module::RfSwitchMode_t rfswitch_table[] = { + // mode DIO5 DIO6 + { LR11x0::MODE_STBY, {LOW, LOW}}, + { LR11x0::MODE_RX, {HIGH, LOW}}, + { LR11x0::MODE_TX, {LOW, HIGH}}, + { LR11x0::MODE_TX_HP, {LOW, HIGH}}, + { LR11x0::MODE_TX_HF, {LOW, LOW}}, + { LR11x0::MODE_GNSS, {LOW, LOW}}, + { LR11x0::MODE_WIFI, {LOW, LOW}}, + END_OF_MODE_TABLE, +}; + +bool radio_init() { + fallback_clock.begin(); + rtc_clock.begin(Wire); + + spi.begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI); + int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, RADIOLIB_LR11X0_LORA_SYNC_WORD_PRIVATE, + LORA_TX_POWER, 16, LR11X0_DIO3_TCXO_VOLTAGE); + if (status != RADIOLIB_ERR_NONE) { + Serial.print("ERROR: radio init failed: "); + Serial.println(status); + return false; + } + + radio.setCRC(2); + radio.explicitHeader(); + radio.setRfSwitchTable(rfswitch_dios, rfswitch_table); +#ifdef RX_BOOSTED_GAIN + radio.setRxBoostedGainMode(RX_BOOSTED_GAIN); +#endif + + return true; +} + +mesh::LocalIdentity radio_new_identity() { + RadioNoiseListener rng(radio); + return mesh::LocalIdentity(&rng); +} diff --git a/variants/waveshare_esp32s3_lr1121/target.h b/variants/waveshare_esp32s3_lr1121/target.h new file mode 100644 index 00000000..461509e5 --- /dev/null +++ b/variants/waveshare_esp32s3_lr1121/target.h @@ -0,0 +1,17 @@ +#pragma once + +#define RADIOLIB_STATIC_ONLY 1 +#include <RadioLib.h> +#include <helpers/radiolib/RadioLibWrappers.h> +#include <helpers/radiolib/CustomLR1121Wrapper.h> +#include <helpers/AutoDiscoverRTCClock.h> +#include <helpers/SensorManager.h> +#include "WaveshareS3LR1121Board.h" + +extern WaveshareS3LR1121Board board; +extern WRAPPER_CLASS radio_driver; +extern AutoDiscoverRTCClock rtc_clock; +extern SensorManager sensors; + +bool radio_init(); +mesh::LocalIdentity radio_new_identity(); From 58721ae6fb006e739ea450ae55ecb238fe14d8b4 Mon Sep 17 00:00:00 2001 From: agessaman <adam@gessaman.com> Date: Sun, 11 Oct 2026 20:53:23 -0700 Subject: [PATCH 277/381] fix(radiolib): keep LR1121 tx power valid across sub-GHz and 2.4 GHz - Clip requested power to the active PA's range instead of failing. A stored 22 dBm was rejected at 2.4 GHz (HF PA max 13 dBm), and since setTxPower ignores errors the sub-GHz PA stayed configured. - Re-apply the requested power after every successful retune: PA choice depends on the band, and set radio / tempradio only call setParams. --- src/helpers/radiolib/CustomLR1121.h | 30 +++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/src/helpers/radiolib/CustomLR1121.h b/src/helpers/radiolib/CustomLR1121.h index e8c6c431..7182d1d5 100644 --- a/src/helpers/radiolib/CustomLR1121.h +++ b/src/helpers/radiolib/CustomLR1121.h @@ -9,6 +9,8 @@ class CustomLR1121 : public LR1121 { uint32_t _activityAt = 0; bool _headerSeen = false; bool _rx_boosted = false; + int8_t _txPower = 0; + bool _txPowerSet = false; public: CustomLR1121(Module *mod) : LR1121(mod) { } @@ -36,12 +38,32 @@ class CustomLR1121 : public LR1121 { return len; } -#ifdef LR1121_FORCE_HP_PA - // boards with only RFO_HP_LF wired: stop RadioLib switching to the LP PA at <= 14 dBm (2.4 GHz still uses the HF PA) + using LR1121::setOutputPower; + using LR1121::setFrequency; + int16_t setOutputPower(int8_t power) override { - return LR1121::setOutputPower(power, true); - } +#ifdef LR1121_FORCE_HP_PA + const bool force_hp = true; // boards with only RFO_HP_LF wired: never select the LP PA +#else + const bool force_hp = false; #endif + // clip to the active PA's range (HF PA tops out at 13 dBm) rather than fail and keep the other band's PA + int8_t clipped = power; + checkOutputPower(power, &clipped, force_hp); + int16_t state = LR1121::setOutputPower(clipped, force_hp); + if (state == RADIOLIB_ERR_NONE) { + _txPower = power; + _txPowerSet = true; + } + return state; + } + + int16_t setFrequency(float freq) override { + int16_t state = LR1121::setFrequency(freq); + // PA selection depends on the band, and set radio / tempradio don't call setTxPower + if (state == RADIOLIB_ERR_NONE && _txPowerSet) state = setOutputPower(_txPower); + return state; + } float getFreqMHz() const { return freqMHz; } From 5f2deeb8759e9808a8d90743250ac301c6ecee4d Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Wed, 14 Oct 2026 11:48:58 +1100 Subject: [PATCH 278/381] * Room: "set repeat" CLI now deprecated --- examples/simple_room_server/MyMesh.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/examples/simple_room_server/MyMesh.cpp b/examples/simple_room_server/MyMesh.cpp index 71b8d32a..458537e6 100644 --- a/examples/simple_room_server/MyMesh.cpp +++ b/examples/simple_room_server/MyMesh.cpp @@ -983,6 +983,8 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply addSystemPost(msg); snprintf(reply, MAX_POST_TEXT_LEN, "OK"); } + } else if (memcmp(command, "set repeat ", 11) == 0) { + strcpy(reply, "ERR - repeat now deprecated"); } else{ _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands } From 174582e8a152b66f66d3882ec43f3884c8efbf55 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Wed, 14 Oct 2026 12:21:38 +1100 Subject: [PATCH 279/381] * only 'repeat on' now intercepted --- examples/simple_room_server/MyMesh.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/simple_room_server/MyMesh.cpp b/examples/simple_room_server/MyMesh.cpp index 458537e6..da4c776c 100644 --- a/examples/simple_room_server/MyMesh.cpp +++ b/examples/simple_room_server/MyMesh.cpp @@ -983,7 +983,7 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply addSystemPost(msg); snprintf(reply, MAX_POST_TEXT_LEN, "OK"); } - } else if (memcmp(command, "set repeat ", 11) == 0) { + } else if (memcmp(command, "set repeat on", 13) == 0) { strcpy(reply, "ERR - repeat now deprecated"); } else{ _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands From 18acb44839779ed530a87418b9d3cdb4a2edbfbc Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Wed, 14 Oct 2026 15:05:00 +1300 Subject: [PATCH 280/381] enable wifi interface for heltec v3 ble variant --- variants/heltec_v3/platformio.ini | 2 ++ 1 file changed, 2 insertions(+) diff --git a/variants/heltec_v3/platformio.ini b/variants/heltec_v3/platformio.ini index a2b159ec..e60e35e0 100644 --- a/variants/heltec_v3/platformio.ini +++ b/variants/heltec_v3/platformio.ini @@ -168,12 +168,14 @@ build_flags = -D AUTO_SHUTDOWN_MILLIVOLTS=3400 -D BLE_DEBUG_LOGGING=1 -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_WIFI_INTERFACE ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${Heltec_lora32_v3.build_src_filter} +<helpers/ui/SSD1306Display.cpp> +<helpers/ui/MomentaryButton.cpp> +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = From bcc5ccfbf01c9683f8ec03959c0a303362645644 Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Wed, 14 Oct 2026 15:16:55 +1300 Subject: [PATCH 281/381] enable wifi interface for heltec v4 ble variant --- variants/heltec_v4/platformio.ini | 2 ++ 1 file changed, 2 insertions(+) diff --git a/variants/heltec_v4/platformio.ini b/variants/heltec_v4/platformio.ini index 96b3eec0..76e8e714 100644 --- a/variants/heltec_v4/platformio.ini +++ b/variants/heltec_v4/platformio.ini @@ -211,12 +211,14 @@ build_flags = -D AUTO_SHUTDOWN_MILLIVOLTS=3400 -D BLE_DEBUG_LOGGING=1 -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_WIFI_INTERFACE ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${heltec_v4_oled.build_src_filter} +<helpers/ui/SSD1306Display.cpp> +<helpers/ui/MomentaryButton.cpp> +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = From 3448d0694321ed9fba076c8e9f6dd252c9992fd9 Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Wed, 14 Oct 2026 16:29:41 +1300 Subject: [PATCH 282/381] rework companion ui for ip address so it fits in multi interface variants --- examples/companion_radio/ui-new/UITask.cpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index 181bc832..bc25de79 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -281,10 +281,17 @@ public: if (_page == HomePage::FIRST) { display.setColor(UIColor::primary_txt); + #ifdef ENABLE_WIFI_INTERFACE + // smaller unread message ui for wifi variants + display.setTextSize(1); + sprintf(tmp, "Unread Msg: %d", _task->getMsgCount()); + display.drawTextCentered(display.width() / 2, 22, tmp); + #else + // larger unread message ui for non wifi variants display.setTextSize(2); sprintf(tmp, "MSG: %d", _task->getMsgCount()); display.drawTextCentered(display.width() / 2, 22, tmp); - + #endif #ifdef UI_SHOW_CLOCK display.setTextSize(3); uint32_t now = _rtc->getCurrentTime(); @@ -300,7 +307,7 @@ public: IPAddress ip = WiFi.localIP(); snprintf(tmp, sizeof(tmp), "IP: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); display.setTextSize(1); - display.drawTextCentered(display.width() / 2, 54, tmp); + display.drawTextCentered(display.width() / 2, 32, tmp); #endif if (_task->hasConnection()) { display.setColor(UIColor::warning_txt); From 59663042a8363125996bd4dab72d697d23fa0c24 Mon Sep 17 00:00:00 2001 From: Rastislav Vysoky <recrof@gmail.com> Date: Thu, 15 Oct 2026 09:57:31 +0200 Subject: [PATCH 283/381] added dynamic wifi to: heltec wsl3, v4r8, wireless paper; rak 3112; xiao s3 (wio) --- variants/heltec_v3/platformio.ini | 4 +++- variants/heltec_v4_r8/platformio.ini | 2 ++ variants/heltec_wireless_paper/platformio.ini | 4 +++- variants/rak3112/platformio.ini | 4 +++- variants/xiao_s3/platformio.ini | 2 ++ variants/xiao_s3_wio/platformio.ini | 2 ++ 6 files changed, 15 insertions(+), 3 deletions(-) diff --git a/variants/heltec_v3/platformio.ini b/variants/heltec_v3/platformio.ini index e60e35e0..06c02856 100644 --- a/variants/heltec_v3/platformio.ini +++ b/variants/heltec_v3/platformio.ini @@ -314,12 +314,14 @@ build_flags = -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D BLE_PIN_CODE=123456 - -D BLE_DEBUG_LOGGING=1 -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_WIFI_INTERFACE +; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${Heltec_lora32_v3.build_src_filter} +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<../examples/companion_radio/*.cpp> lib_deps = ${Heltec_lora32_v3.lib_deps} diff --git a/variants/heltec_v4_r8/platformio.ini b/variants/heltec_v4_r8/platformio.ini index 7611cc1c..e22ca8f5 100644 --- a/variants/heltec_v4_r8/platformio.ini +++ b/variants/heltec_v4_r8/platformio.ini @@ -160,10 +160,12 @@ build_flags = -D AUTO_SHUTDOWN_MILLIVOLTS=3400 -D BLE_DEBUG_LOGGING=1 -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_WIFI_INTERFACE build_src_filter = ${heltec_v4_r8_oled.build_src_filter} +<helpers/ui/SSD1306Display.cpp> +<helpers/ui/MomentaryButton.cpp> +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = diff --git a/variants/heltec_wireless_paper/platformio.ini b/variants/heltec_wireless_paper/platformio.ini index 55ed62b3..56f95b2f 100644 --- a/variants/heltec_wireless_paper/platformio.ini +++ b/variants/heltec_wireless_paper/platformio.ini @@ -52,11 +52,13 @@ build_flags = -D MAX_GROUP_CHANNELS=40 -D DISPLAY_CLASS=E213Display -D BLE_PIN_CODE=123456 ; dynamic, random PIN - -D BLE_DEBUG_LOGGING=1 -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_WIFI_INTERFACE +; -D BLE_DEBUG_LOGGING=1 build_src_filter = ${Heltec_Wireless_Paper_base.build_src_filter} +<helpers/ui/E213Display.cpp> +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = diff --git a/variants/rak3112/platformio.ini b/variants/rak3112/platformio.ini index 5f3b905b..d181388b 100644 --- a/variants/rak3112/platformio.ini +++ b/variants/rak3112/platformio.ini @@ -155,12 +155,14 @@ build_flags = -D MAX_GROUP_CHANNELS=40 -D BLE_PIN_CODE=123456 ; dynamic, random PIN -D AUTO_SHUTDOWN_MILLIVOLTS=3400 - -D BLE_DEBUG_LOGGING=1 -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_WIFI_INTERFACE +; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${rak3112.build_src_filter} +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-orig/*.cpp> lib_deps = diff --git a/variants/xiao_s3/platformio.ini b/variants/xiao_s3/platformio.ini index 1632d112..b8ae7973 100644 --- a/variants/xiao_s3/platformio.ini +++ b/variants/xiao_s3/platformio.ini @@ -100,12 +100,14 @@ build_flags = -D BLE_PIN_CODE=123456 -D DISPLAY_CLASS=SSD1306Display -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_WIFI_INTERFACE ; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${Xiao_S3.build_src_filter} +<helpers/ui/SSD1306Display.cpp> +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<helpers/ui/MomentaryButton.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> diff --git a/variants/xiao_s3_wio/platformio.ini b/variants/xiao_s3_wio/platformio.ini index 3bb95607..5a2ef106 100644 --- a/variants/xiao_s3_wio/platformio.ini +++ b/variants/xiao_s3_wio/platformio.ini @@ -160,12 +160,14 @@ build_flags = -D BLE_PIN_CODE=123456 -D DISPLAY_CLASS=SSD1306Display -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_WIFI_INTERFACE ; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${Xiao_S3_WIO.build_src_filter} +<helpers/ui/SSD1306Display.cpp> +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<helpers/ui/MomentaryButton.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> From a4f1601df3fccb130375a82d752014ee30291dbd Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Thu, 15 Oct 2026 19:42:01 +1100 Subject: [PATCH 284/381] * version 1.18.0 --- examples/companion_radio/MyMesh.h | 4 ++-- examples/simple_repeater/MyMesh.h | 4 ++-- examples/simple_room_server/MyMesh.h | 4 ++-- examples/simple_sensor/SensorMesh.h | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/examples/companion_radio/MyMesh.h b/examples/companion_radio/MyMesh.h index 52a22cb4..944790df 100644 --- a/examples/companion_radio/MyMesh.h +++ b/examples/companion_radio/MyMesh.h @@ -7,11 +7,11 @@ #define FIRMWARE_VER_CODE 14 #ifndef FIRMWARE_BUILD_DATE -#define FIRMWARE_BUILD_DATE "14 Aug 2026" +#define FIRMWARE_BUILD_DATE "15 Oct 2026" #endif #ifndef FIRMWARE_VERSION -#define FIRMWARE_VERSION "v1.17.1" +#define FIRMWARE_VERSION "v1.18.0" #endif #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index a9ac453a..dc893258 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -67,11 +67,11 @@ struct NeighbourInfo { }; #ifndef FIRMWARE_BUILD_DATE - #define FIRMWARE_BUILD_DATE "14 Aug 2026" + #define FIRMWARE_BUILD_DATE "15 Oct 2026" #endif #ifndef FIRMWARE_VERSION - #define FIRMWARE_VERSION "v1.17.1" + #define FIRMWARE_VERSION "v1.18.0" #endif #define FIRMWARE_ROLE "repeater" diff --git a/examples/simple_room_server/MyMesh.h b/examples/simple_room_server/MyMesh.h index 5cf949c6..4dee8bdb 100644 --- a/examples/simple_room_server/MyMesh.h +++ b/examples/simple_room_server/MyMesh.h @@ -28,11 +28,11 @@ /* ------------------------------ Config -------------------------------- */ #ifndef FIRMWARE_BUILD_DATE - #define FIRMWARE_BUILD_DATE "14 Aug 2026" + #define FIRMWARE_BUILD_DATE "15 Oct 2026" #endif #ifndef FIRMWARE_VERSION - #define FIRMWARE_VERSION "v1.17.1" + #define FIRMWARE_VERSION "v1.18.0" #endif #ifndef LORA_FREQ diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index 8b421081..590ca0c7 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -34,11 +34,11 @@ #define PERM_RECV_ALERTS_HI (1 << 7) // high priority alerts #ifndef FIRMWARE_BUILD_DATE - #define FIRMWARE_BUILD_DATE "14 Aug 2026" + #define FIRMWARE_BUILD_DATE "15 Oct 2026" #endif #ifndef FIRMWARE_VERSION - #define FIRMWARE_VERSION "v1.17.1" + #define FIRMWARE_VERSION "v1.18.0" #endif #define FIRMWARE_ROLE "sensor" From 05cd36d2ec884a999db1551ee930c741b562098d Mon Sep 17 00:00:00 2001 From: R0ck <develop@hectospark.co.uk> Date: Thu, 15 Oct 2026 19:33:35 +0100 Subject: [PATCH 285/381] Add T1000-E custom CLI command to toggle the buzzer --- variants/t1000-e/T1000eBoard.cpp | 70 +++++++++++++++++++++++++++++++- variants/t1000-e/T1000eBoard.h | 8 ++++ 2 files changed, 77 insertions(+), 1 deletion(-) diff --git a/variants/t1000-e/T1000eBoard.cpp b/variants/t1000-e/T1000eBoard.cpp index 0d390f79..a4713017 100644 --- a/variants/t1000-e/T1000eBoard.cpp +++ b/variants/t1000-e/T1000eBoard.cpp @@ -3,6 +3,10 @@ #include "T1000eBoard.h" +#ifdef PIN_BUZZER_EN + #include <NonBlockingRtttl.h> +#endif + void T1000eBoard::begin() { NRF52BoardDCDC::begin(); btn_prev_state = HIGH; @@ -20,4 +24,68 @@ void T1000eBoard::begin() { Wire.begin(); delay(10); // give sx1262 some time to power up -} \ No newline at end of file +} + +void T1000eBoard::attachDynamicPrefs(KeyValueStore* prefs) { + _prefs = prefs; +#ifdef PIN_BUZZER_EN + char val[8]; + val[0] = 0; + _prefs->getByKey("buzzer", val, sizeof(val)); + _buzzer_muted = strcmp(val, "0") == 0; +#endif +} + +#ifdef PIN_BUZZER_EN +static void playTune(const char* tune) { + if (rtttl::isPlaying()) rtttl::stop(); + rtttl::begin(PIN_BUZZER, tune); +} +#endif + +void T1000eBoard::setBuzzerEnabled(bool enable) { +#ifdef PIN_BUZZER_EN + _buzzer_muted = !enable; + digitalWrite(PIN_BUZZER_EN, enable ? HIGH : LOW); +#endif +} + +void T1000eBoard::loop() { + NRF52BoardDCDC::loop(); +#ifdef PIN_BUZZER_EN + if (!rtttl::done()) rtttl::play(); + if (_buzzer_mute_pending && rtttl::done()) { // mute once the confirmation beep has finished + _buzzer_mute_pending = false; + setBuzzerEnabled(false); + } + if (_buzzer_muted) digitalWrite(PIN_BUZZER_EN, LOW); // keep it off even if the UI re-enables it +#endif +} + +bool T1000eBoard::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { +#ifdef PIN_BUZZER_EN + if (strcmp(command, "get buzzer") == 0) { + sprintf(reply, "> %s", (_buzzer_muted || _buzzer_mute_pending) ? "off" : "on"); + return true; + } + if (memcmp(command, "set buzzer ", 11) == 0) { + if (strcmp(&command[11], "on") == 0) { + _buzzer_mute_pending = false; + setBuzzerEnabled(true); + if (_prefs) _prefs->setByKey("buzzer", "1"); + playTune("MsgRcv3:d=4,o=6,b=200:32e,32g,32b,16c7"); // same tune as a new message + strcpy(reply, "OK - buzzer on"); + } else if (strcmp(&command[11], "off") == 0) { + setBuzzerEnabled(true); + _buzzer_mute_pending = true; + if (_prefs) _prefs->setByKey("buzzer", "0"); + playTune("ack:d=32,o=8,b=120:c"); // same beep as an ack, before going quiet + strcpy(reply, "OK - buzzer off"); + } else { + strcpy(reply, "Error: state must be on or off"); + } + return true; + } +#endif + return false; // not handled +} diff --git a/variants/t1000-e/T1000eBoard.h b/variants/t1000-e/T1000eBoard.h index ba8bf0c1..846c7df2 100644 --- a/variants/t1000-e/T1000eBoard.h +++ b/variants/t1000-e/T1000eBoard.h @@ -7,10 +7,18 @@ class T1000eBoard : public NRF52BoardDCDC { protected: uint8_t btn_prev_state; + KeyValueStore* _prefs = NULL; + bool _buzzer_muted = false; + bool _buzzer_mute_pending = false; + + void setBuzzerEnabled(bool enable); public: T1000eBoard() : NRF52Board("T1000E_OTA") {} void begin(); + void attachDynamicPrefs(KeyValueStore* prefs); + bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; + void loop() override; uint16_t getBattMilliVolts() override { #ifdef BATTERY_PIN From bb84f293b79885dbaedaa83b2eaba10519b078fb Mon Sep 17 00:00:00 2001 From: R0ck <develop@hectospark.co.uk> Date: Thu, 15 Oct 2026 20:12:13 +0100 Subject: [PATCH 286/381] Fix off-by-one when loading the T1000-E buzzer setting --- variants/t1000-e/T1000eBoard.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/variants/t1000-e/T1000eBoard.cpp b/variants/t1000-e/T1000eBoard.cpp index a4713017..ff42f5e4 100644 --- a/variants/t1000-e/T1000eBoard.cpp +++ b/variants/t1000-e/T1000eBoard.cpp @@ -31,7 +31,7 @@ void T1000eBoard::attachDynamicPrefs(KeyValueStore* prefs) { #ifdef PIN_BUZZER_EN char val[8]; val[0] = 0; - _prefs->getByKey("buzzer", val, sizeof(val)); + _prefs->getByKey("buzzer", val, sizeof(val) - 1); _buzzer_muted = strcmp(val, "0") == 0; #endif } From 0769d68ed628c9cf346057f33df3c94ef5f82f60 Mon Sep 17 00:00:00 2001 From: R0ck <develop@hectospark.co.uk> Date: Thu, 15 Oct 2026 20:12:23 +0100 Subject: [PATCH 287/381] Report an error when the buzzer setting fails to save --- variants/t1000-e/T1000eBoard.cpp | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/variants/t1000-e/T1000eBoard.cpp b/variants/t1000-e/T1000eBoard.cpp index ff42f5e4..9bdeff89 100644 --- a/variants/t1000-e/T1000eBoard.cpp +++ b/variants/t1000-e/T1000eBoard.cpp @@ -70,17 +70,23 @@ bool T1000eBoard::handleCommand(const char* command, uint32_t sender_timestamp, } if (memcmp(command, "set buzzer ", 11) == 0) { if (strcmp(&command[11], "on") == 0) { - _buzzer_mute_pending = false; - setBuzzerEnabled(true); - if (_prefs) _prefs->setByKey("buzzer", "1"); - playTune("MsgRcv3:d=4,o=6,b=200:32e,32g,32b,16c7"); // same tune as a new message - strcpy(reply, "OK - buzzer on"); + if (_prefs && !_prefs->setByKey("buzzer", "1")) { + strcpy(reply, "Error: failed to save buzzer setting"); + } else { + _buzzer_mute_pending = false; + setBuzzerEnabled(true); + playTune("MsgRcv3:d=4,o=6,b=200:32e,32g,32b,16c7"); // same tune as a new message + strcpy(reply, "OK - buzzer on"); + } } else if (strcmp(&command[11], "off") == 0) { - setBuzzerEnabled(true); - _buzzer_mute_pending = true; - if (_prefs) _prefs->setByKey("buzzer", "0"); - playTune("ack:d=32,o=8,b=120:c"); // same beep as an ack, before going quiet - strcpy(reply, "OK - buzzer off"); + if (_prefs && !_prefs->setByKey("buzzer", "0")) { + strcpy(reply, "Error: failed to save buzzer setting"); + } else { + setBuzzerEnabled(true); + _buzzer_mute_pending = true; + playTune("ack:d=32,o=8,b=120:c"); // same beep as an ack, before going quiet + strcpy(reply, "OK - buzzer off"); + } } else { strcpy(reply, "Error: state must be on or off"); } From da9329b09634c24e1bed9d952343e0c1268ce814 Mon Sep 17 00:00:00 2001 From: amdoolittle <amdoolittle@gmail.com> Date: Fri, 16 Oct 2026 10:04:44 -0700 Subject: [PATCH 288/381] Remove BLE screen when BLE not available --- examples/companion_radio/ui-new/UITask.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index bc25de79..60106d1c 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -91,7 +91,9 @@ class HomeScreen : public UIScreen { FIRST, RECENT, RADIO, +#ifdef BLE_PIN_CODE BLUETOOTH, +# endif ADVERT, #if ENV_INCLUDE_GPS == 1 GPS, @@ -372,6 +374,7 @@ public: display.setCursor(0, 53); sprintf(tmp, "Noise floor: %d", radio_driver.getNoiseFloor()); display.print(tmp); +#ifdef BLE_PIN_CODE } else if (_page == HomePage::BLUETOOTH) { display.setColor(UIColor::corp_blue); display.drawXbm((display.width() - 32) / 2, 18, @@ -380,6 +383,7 @@ public: display.setColor(UIColor::secondary_txt); display.setTextSize(1); display.drawTextCentered(display.width() / 2, 64 - 11, "toggle: " PRESS_LABEL); +#endif } else if (_page == HomePage::ADVERT) { display.setColor(UIColor::corp_blue); display.drawXbm((display.width() - 32) / 2, 18, advert_icon, 32, 32); @@ -575,6 +579,7 @@ public: #endif return true; } +#ifdef BLE_PIN_CODE if (c == KEY_ENTER && _page == HomePage::BLUETOOTH) { if (_task->isBluetoothEnabled()) { // toggle Bluetooth on/off _task->disableBluetooth(); @@ -583,6 +588,7 @@ public: } return true; } +#endif if (c == KEY_ENTER && _page == HomePage::ADVERT) { _task->notify(UIEventType::ack); if (the_mesh.advert()) { From 7bbc19b010fd5661f8197f1aee2abb1885c1baca Mon Sep 17 00:00:00 2001 From: amdoolittle <amdoolittle@gmail.com> Date: Fri, 16 Oct 2026 17:30:19 -0700 Subject: [PATCH 289/381] Update UITask.cpp Housekeeping: removed unnecessary space --- examples/companion_radio/ui-new/UITask.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index 60106d1c..6e38c1fb 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -93,7 +93,7 @@ class HomeScreen : public UIScreen { RADIO, #ifdef BLE_PIN_CODE BLUETOOTH, -# endif +#endif ADVERT, #if ENV_INCLUDE_GPS == 1 GPS, From 6dc7f2b0470037814bc9c889dfbf7961ca408c37 Mon Sep 17 00:00:00 2001 From: agessaman <adam@gessaman.com> Date: Fri, 16 Oct 2026 19:02:23 -0700 Subject: [PATCH 290/381] feat(rak3401): auto-sleep optional onboard SX1262 Use the existing RAK3401 firmware roles for RAK4631 cores paired with a RAK13302. Probe the optional onboard radio and put it into cold sleep before handing SPI to the primary radio, removing seven duplicate build environments. Preserve BUSY startup readiness, release probe pulls before sleep, and disconnect unused GPIO input buffers during cleanup. Add focused tests for sequencing, missing signatures, timeouts, and failed sleep readback. Validated with four native tests, seven firmware-role builds, and repeater boot checks on RAK4631 + RAK13302. Supply current was not measured. --- platformio.ini | 6 + .../test_onboard_radio.cpp | 66 +++++++++ variants/rak3401/OnboardRadioSleep.h | 34 +++++ variants/rak3401/platformio.ini | 125 ------------------ variants/rak3401/target.cpp | 110 ++++++++++----- variants/rak3401/variant.h | 7 +- 6 files changed, 184 insertions(+), 164 deletions(-) create mode 100644 test/test_rak3401_onboard_radio/test_onboard_radio.cpp create mode 100644 variants/rak3401/OnboardRadioSleep.h diff --git a/platformio.ini b/platformio.ini index e78124a4..e305d177 100644 --- a/platformio.ini +++ b/platformio.ini @@ -173,6 +173,12 @@ build_src_filter = lib_deps = google/googletest @ 1.17.0 +[env:native_rak3401_onboard_radio] +; Header-only tests without unrelated production sources; also included in env:native CI. +extends = env:native +test_build_src = no +test_filter = test_rak3401_onboard_radio + [env:native_kiss_modem] platform = native test_framework = googletest diff --git a/test/test_rak3401_onboard_radio/test_onboard_radio.cpp b/test/test_rak3401_onboard_radio/test_onboard_radio.cpp new file mode 100644 index 00000000..cc616612 --- /dev/null +++ b/test/test_rak3401_onboard_radio/test_onboard_radio.cpp @@ -0,0 +1,66 @@ +#include <gtest/gtest.h> +#include <array> +#include <string> +#include "../../variants/rak3401/OnboardRadioSleep.h" + +namespace { +struct FakeRadioIO { + std::string version = "SX1261"; + std::array<bool, 3> ready = {true, true, true}; + std::string calls; + unsigned waits = 0; + bool probePulls = true; + + void begin() { calls += "begin "; } + void reset() { calls += "reset "; } + bool waitBusy(bool high, unsigned timeout) { + calls += high ? "busy-high " : "busy-low "; + EXPECT_EQ(timeout, 20u); + if (high) EXPECT_FALSE(probePulls); + const bool result = ready.at(waits++); + return result; + } + void readVersion(char* out) { calls += "version "; memcpy(out, version.data(), 6); } + void releaseProbePulls() { calls += "release-pulls "; probePulls = false; } + void sleep() { EXPECT_FALSE(probePulls); calls += "sleep "; } + void end() { calls += "end "; } +}; +} + +TEST(RakOnboardRadio, PresentRadioSleepsBeforeBusRelease) { + FakeRadioIO io; + EXPECT_EQ(rak3401::sleepOnboardRadio(io, "SX1261"), rak3401::OnboardRadioState::Asleep); + EXPECT_EQ(io.calls, "begin reset busy-low version release-pulls busy-low sleep busy-high end "); +} + +TEST(RakOnboardRadio, AbsentAndFloatingResponsesNeverReceiveSleep) { + for (const std::string version : {std::string(6, '\0'), std::string(6, '\xff'), std::string("SX126X")}) { + FakeRadioIO io; + io.version = version; + EXPECT_EQ(rak3401::sleepOnboardRadio(io, "SX1261"), rak3401::OnboardRadioState::Absent); + EXPECT_EQ(io.calls, "begin reset busy-low version end "); + } +} + +TEST(RakOnboardRadio, BusyTimeoutsReleaseBusWithoutSleep) { + for (unsigned failure = 0; failure < 2; failure++) { + FakeRadioIO io; + io.ready[failure] = false; + EXPECT_EQ(rak3401::sleepOnboardRadio(io, "SX1261"), rak3401::OnboardRadioState::BusyTimeout); + EXPECT_EQ(io.calls.find("sleep "), std::string::npos); + EXPECT_EQ(io.calls, failure == 0 ? "begin reset busy-low end " : + "begin reset busy-low version release-pulls busy-low end "); + } +} + +TEST(RakOnboardRadio, MissingSleepReadbackIsReportedAndBusReleased) { + FakeRadioIO io; + io.ready[2] = false; + EXPECT_EQ(rak3401::sleepOnboardRadio(io, "SX1261"), rak3401::OnboardRadioState::SleepFailed); + EXPECT_EQ(io.calls.substr(io.calls.size() - 4), "end "); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/variants/rak3401/OnboardRadioSleep.h b/variants/rak3401/OnboardRadioSleep.h new file mode 100644 index 00000000..7f6d1c55 --- /dev/null +++ b/variants/rak3401/OnboardRadioSleep.h @@ -0,0 +1,34 @@ +#pragma once + +#include <string.h> + +namespace rak3401 { + +enum class OnboardRadioState { Absent, Asleep, BusyTimeout, SleepFailed }; + +// IO owns the temporary SPI pin assignment; every outcome must release it. +template <typename IO> +OnboardRadioState sleepOnboardRadio(IO& io, const char* expectedVersion) { + io.begin(); + io.reset(); + const auto state = [&]() { + // A missing chip also times out: BUSY is pulled high until a radio drives it low. + if (!io.waitBusy(false, 20)) return OnboardRadioState::BusyTimeout; + + char version[6]; + io.readVersion(version); + if (memcmp(version, expectedVersion, sizeof(version)) != 0) { + return OnboardRadioState::Absent; + } + io.releaseProbePulls(); + if (!io.waitBusy(false, 20)) return OnboardRadioState::BusyTimeout; + + io.sleep(); + // Reading over SPI here would wake the radio again. BUSY is a passive check. + return io.waitBusy(true, 20) ? OnboardRadioState::Asleep : OnboardRadioState::SleepFailed; + }(); + io.end(); + return state; +} + +} diff --git a/variants/rak3401/platformio.ini b/variants/rak3401/platformio.ini index 56883e75..48e71922 100644 --- a/variants/rak3401/platformio.ini +++ b/variants/rak3401/platformio.ini @@ -134,128 +134,3 @@ build_src_filter = ${rak3401.build_src_filter} extends = rak3401 build_src_filter = ${rak3401.build_src_filter} +<../examples/kiss_modem/> - -; ------------------------- RAK4631 core + RAK13302 ------------------------- -; Same RF hardware as the RAK3401 1W kit, but the RAK4631 core carries a second, -; unused SX1262 that would otherwise idle in standby forever. These envs match -; the RAK_3401_* ones and additionally cold-sleep that radio at boot. -; Do not flash them to a genuine RAK3401 -- there is no onboard radio to sleep. - -[rak4631_13302] -extends = rak3401 -board = rak4631 -build_flags = ${rak3401.build_flags} - -D RAK4631_ONBOARD_SX1262_SLEEP -build_src_filter = ${rak3401.build_src_filter} -lib_deps = ${rak3401.lib_deps} - -[env:RAK_4631_13302_repeater] -extends = rak4631_13302 -build_flags = - ${rak4631_13302.build_flags} - -D DISPLAY_CLASS=SSD1306Display - -D ADVERT_NAME='"RAK4631 1W Repeater"' - -D ADVERT_LAT=0.0 - -D ADVERT_LON=0.0 - -D ADMIN_PASSWORD='"password"' - -D MAX_NEIGHBOURS=50 - ;-D MESH_PACKET_LOGGING=1 - ;-D MESH_DEBUG=1 -build_src_filter = ${rak4631_13302.build_src_filter} - +<helpers/ui/SSD1306Display.cpp> - +<../examples/simple_repeater> - -[env:RAK_4631_13302_room_server] -extends = rak4631_13302 -build_flags = - ${rak4631_13302.build_flags} - -D DISPLAY_CLASS=SSD1306Display - -D ADVERT_NAME='"Test Room"' - -D ADVERT_LAT=0.0 - -D ADVERT_LON=0.0 - -D ADMIN_PASSWORD='"password"' - -D ROOM_PASSWORD='"hello"' - ;-D MESH_PACKET_LOGGING=1 - ;-D MESH_DEBUG=1 -build_src_filter = ${rak4631_13302.build_src_filter} - +<helpers/ui/SSD1306Display.cpp> - +<../examples/simple_room_server> - -[env:RAK_4631_13302_companion_radio_usb] -extends = rak4631_13302 -board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld -board_upload.maximum_size = 712704 -build_flags = - ${rak4631_13302.build_flags} - -I examples/companion_radio/ui-new - -D PIN_USER_BTN_ANA=31 - -D DISPLAY_CLASS=SSD1306Display - -D MAX_CONTACTS=350 - -D MAX_GROUP_CHANNELS=40 - -D ENABLE_USB_INTERFACE -; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 -; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 -build_src_filter = ${rak4631_13302.build_src_filter} - +<../examples/companion_radio/*.cpp> - +<../examples/companion_radio/ui-new/*.cpp> -lib_deps = - ${rak4631_13302.lib_deps} - densaugeo/base64 @ ~1.4.0 - -[env:RAK_4631_13302_companion_radio_ble] -extends = rak4631_13302 -board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld -board_upload.maximum_size = 712704 -build_flags = - ${rak4631_13302.build_flags} - -I examples/companion_radio/ui-new - -D PIN_USER_BTN_ANA=31 - -D DISPLAY_CLASS=SSD1306Display - -D MAX_CONTACTS=350 - -D MAX_GROUP_CHANNELS=40 - -D BLE_PIN_CODE=123456 - -D BLE_DEBUG_LOGGING=1 - -D OFFLINE_QUEUE_SIZE=256 - ;-D MESH_PACKET_LOGGING=1 - ;-D MESH_DEBUG=1 -build_src_filter = ${rak4631_13302.build_src_filter} - +<helpers/nrf52/SerialBLEInterface.cpp> - +<../examples/companion_radio/*.cpp> - +<../examples/companion_radio/ui-new/*.cpp> -lib_deps = - ${rak4631_13302.lib_deps} - densaugeo/base64 @ ~1.4.0 - -[env:RAK_4631_13302_terminal_chat] -extends = rak4631_13302 -build_flags = - ${rak4631_13302.build_flags} - -D MAX_CONTACTS=100 - -D MAX_GROUP_CHANNELS=1 - ;-D MESH_PACKET_LOGGING=1 - ;-D MESH_DEBUG=1 -build_src_filter = ${rak4631_13302.build_src_filter} - +<../examples/simple_secure_chat/main.cpp> -lib_deps = - ${rak4631_13302.lib_deps} - densaugeo/base64 @ ~1.4.0 - -[env:RAK_4631_13302_sensor] -extends = rak4631_13302 -build_flags = - ${rak4631_13302.build_flags} - -D DISPLAY_CLASS=SSD1306Display - -D ADVERT_NAME='"RAK4631 Sensor"' - -D ADVERT_LAT=0.0 - -D ADVERT_LON=0.0 - -D ADMIN_PASSWORD='"password"' - ;-D MESH_PACKET_LOGGING=1 - ;-D MESH_DEBUG=1 -build_src_filter = ${rak4631_13302.build_src_filter} - +<helpers/ui/SSD1306Display.cpp> - +<../examples/simple_sensor> - -[env:RAK_4631_13302_kiss_modem] -extends = rak4631_13302 -build_src_filter = ${rak4631_13302.build_src_filter} - +<../examples/kiss_modem/> diff --git a/variants/rak3401/target.cpp b/variants/rak3401/target.cpp index dac12ede..b9d142b3 100644 --- a/variants/rak3401/target.cpp +++ b/variants/rak3401/target.cpp @@ -1,6 +1,8 @@ #include <Arduino.h> #include "target.h" #include <helpers/ArduinoHelpers.h> +#include "OnboardRadioSleep.h" +#include <nrf_gpio.h> RAK3401Board board; @@ -32,49 +34,91 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); EnvironmentSensorManager sensors; #endif -#ifdef RAK4631_ONBOARD_SX1262_SLEEP -// With a RAK13302 fitted the RAK4631's own SX1262 never gets initialized, so it -// sits in STDBY_RC drawing standby current for the life of the board. Firmware -// cannot cut its supply -- P1.05 is the RF switch rail, not the radio's -- so -// bring it up on its own pins just long enough to put it into cold sleep. -static void sleep_onboard_radio() { - pinMode(ONBOARD_LORA_ANT_SW, OUTPUT); - digitalWrite(ONBOARD_LORA_ANT_SW, LOW); // nothing downstream needs the RF switch +namespace { +class OnboardRadioIO { +public: + void begin() { + digitalWrite(ONBOARD_LORA_NSS, HIGH); + pinMode(ONBOARD_LORA_NSS, OUTPUT); + digitalWrite(ONBOARD_LORA_RESET, HIGH); + pinMode(ONBOARD_LORA_RESET, OUTPUT); + digitalWrite(ONBOARD_LORA_ANT_SW, LOW); + pinMode(ONBOARD_LORA_ANT_SW, OUTPUT); + // BUSY is weakly pulled high during startup; never override it with a pull-down. + pinMode(ONBOARD_LORA_BUSY, INPUT_PULLUP); + SPI.setPins(ONBOARD_LORA_MISO, ONBOARD_LORA_SCLK, ONBOARD_LORA_MOSI); + SPI.begin(); + pinMode(ONBOARD_LORA_MISO, INPUT_PULLDOWN); + } - SPI.setPins(ONBOARD_LORA_MISO, ONBOARD_LORA_SCLK, ONBOARD_LORA_MOSI); - SPI.begin(); + void reset() { + digitalWrite(ONBOARD_LORA_RESET, LOW); + delay(1); + digitalWrite(ONBOARD_LORA_RESET, HIGH); + delay(5); + } - Module mod(ONBOARD_LORA_NSS, ONBOARD_LORA_DIO_1, ONBOARD_LORA_RESET, ONBOARD_LORA_BUSY, SPI); - SX1262 onboard(&mod); + bool waitBusy(bool high, uint32_t timeout) { + uint32_t start = millis(); + while ((digitalRead(ONBOARD_LORA_BUSY) != LOW) != high) { + if (millis() - start >= timeout) return false; + delay(1); + } + return true; + } - // BUSY is driven low in STDBY_RC and high while asleep, so it doubles as a - // non-invasive readback of what state we found the chip in and left it in. - pinMode(ONBOARD_LORA_BUSY, INPUT); - int busy_before = digitalRead(ONBOARD_LORA_BUSY); + void readVersion(char* version) { + SPI.beginTransaction(SPISettings(2000000, MSBFIRST, SPI_MODE0)); + digitalWrite(ONBOARD_LORA_NSS, LOW); + SPI.transfer(RADIOLIB_SX126X_CMD_READ_REGISTER); + SPI.transfer(RADIOLIB_SX126X_REG_VERSION_STRING >> 8); + SPI.transfer(RADIOLIB_SX126X_REG_VERSION_STRING & 0xFF); + SPI.transfer(0); + for (unsigned i = 0; i < 6; i++) version[i] = SPI.transfer(0); + digitalWrite(ONBOARD_LORA_NSS, HIGH); + SPI.endTransaction(); + } - // begin() resets the chip and leaves it in standby. A TCXO calibration failure - // still leaves SPI usable, so issue the sleep regardless of what it returns. - int status = onboard.begin(434.0f, 125.0f, 9, 7, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, - 0, 8, ONBOARD_LORA_TCXO_VOLTAGE, false); - int slept = onboard.sleep(false); // cold sleep: config discarded, RTC off - delay(2); - int busy_after = digitalRead(ONBOARD_LORA_BUSY); - MESH_DEBUG_PRINTLN("onboard SX1262: begin=%d sleep=%d busy %d->%d", - status, slept, busy_before, busy_after); + void releaseProbePulls() { + pinMode(ONBOARD_LORA_BUSY, INPUT); + pinMode(ONBOARD_LORA_MISO, INPUT); + } - SPI.end(); // release SPIM3 so std_init() can repin it onto the RAK13302 + void sleep() { + SPI.beginTransaction(SPISettings(2000000, MSBFIRST, SPI_MODE0)); + digitalWrite(ONBOARD_LORA_NSS, LOW); + SPI.transfer(RADIOLIB_SX126X_CMD_SET_SLEEP); + SPI.transfer(RADIOLIB_SX126X_SLEEP_START_COLD | RADIOLIB_SX126X_SLEEP_RTC_OFF); + digitalWrite(ONBOARD_LORA_NSS, HIGH); + SPI.endTransaction(); + delay(1); + } - // The SX1262 wakes on an NSS falling edge, so keep NSS driven high from here on. - digitalWrite(ONBOARD_LORA_NSS, HIGH); - pinMode(ONBOARD_LORA_NSS, OUTPUT); + void end() { + SPI.end(); + // INPUT leaves buffers enabled on floating pins; restore Nordic's disconnected default. + nrf_gpio_cfg_default(g_ADigitalPinMap[ONBOARD_LORA_SCLK]); + nrf_gpio_cfg_default(g_ADigitalPinMap[ONBOARD_LORA_MOSI]); + nrf_gpio_cfg_default(g_ADigitalPinMap[ONBOARD_LORA_MISO]); + nrf_gpio_cfg_default(g_ADigitalPinMap[ONBOARD_LORA_BUSY]); + // An NSS falling edge wakes the radio, so leave it driven high. + digitalWrite(ONBOARD_LORA_NSS, HIGH); + } +}; } -#endif bool radio_init() { rtc_clock.begin(Wire); -#ifdef RAK4631_ONBOARD_SX1262_SLEEP - sleep_onboard_radio(); -#endif + // Called once from setup, before SPI is started for the RAK13302. + OnboardRadioIO onboard; + const uint32_t started = millis(); + // The SX1262 version register shares the "SX1261" prefix used by RadioLib. + const auto state = rak3401::sleepOnboardRadio(onboard, RADIOLIB_SX1262_CHIP_TYPE); + const char* outcome = state == rak3401::OnboardRadioState::Absent ? "absent" : + state == rak3401::OnboardRadioState::Asleep ? "asleep" : + state == rak3401::OnboardRadioState::BusyTimeout ? "busy-timeout" : "sleep-failed"; + MESH_DEBUG_PRINTLN("onboard SX1262: %s elapsed=%lu ms", outcome, + (unsigned long)(millis() - started)); return radio.std_init(&SPI); } diff --git a/variants/rak3401/variant.h b/variants/rak3401/variant.h index 0576dadb..779cb3cd 100644 --- a/variants/rak3401/variant.h +++ b/variants/rak3401/variant.h @@ -175,10 +175,7 @@ static const uint8_t AREF = PIN_AREF; #define P_LORA_BUSY SX126X_BUSY #define P_LORA_RESET SX126X_RESET -// The RAK4631 core carries its own SX1262, which is unused when a RAK13302 -// supplies the RF path. RAK4631_ONBOARD_SX1262_SLEEP builds put it into cold -// sleep at boot; on a genuine RAK3401 these pins are unconnected. -#ifdef RAK4631_ONBOARD_SX1262_SLEEP +// Optional RAK4631 onboard radio; these internal pins are unused on RAK3401. #define ONBOARD_LORA_NSS (42) // P1.10 #define ONBOARD_LORA_SCLK (43) // P1.11 #define ONBOARD_LORA_MOSI (44) // P1.12 @@ -187,8 +184,6 @@ static const uint8_t AREF = PIN_AREF; #define ONBOARD_LORA_DIO_1 (47) // P1.15 #define ONBOARD_LORA_RESET (38) // P1.06 #define ONBOARD_LORA_ANT_SW (37) // P1.05, powers the onboard RF switch -#define ONBOARD_LORA_TCXO_VOLTAGE 1.8 -#endif // enables 3.3V periphery like GPS or IO Module // Do not toggle this for GPS power savings From a763fd4c91034a8f3b497eaccca90a36e95a60ab Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Sat, 17 Oct 2026 15:16:38 +1300 Subject: [PATCH 291/381] timezone offset is now stored as float to allow half hour offsets --- examples/companion_radio/MyMesh.cpp | 4 ++-- examples/companion_radio/NodePrefs.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index f32ea67a..99a9aa30 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2192,11 +2192,11 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* } if (strcmp(command, "get tz.offset") == 0) { - sprintf(reply, "> %d", _prefs.tz_offset); + sprintf(reply, "> %.1f", _prefs.tz_offset); return true; } if (memcmp(command, "set tz.offset ", 14) == 0) { - int8_t tz = atof(&command[14]); + float tz = atof(&command[14]); if (tz < -12 || tz > 14) { strcpy(reply, "Error, must be from -12 to +14"); } else { diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index 46a3dbb7..3cceed56 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -47,7 +47,7 @@ public: uint8_t agc_reset_interval = 0; // secs / 4 char default_scope_name[31]; uint8_t default_scope_key[16]; - int8_t tz_offset = 0; + float tz_offset = 0; #ifdef ENABLE_WIFI_INTERFACE #ifndef WIFI_SSID #define WIFI_SSID "" From c2c5de52be11980f6c6fee43c2580b546143c213 Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Sat, 17 Oct 2026 15:22:46 +1300 Subject: [PATCH 292/381] tz_offset should be treated as float when down casting calculation result to int32 --- examples/companion_radio/ui-new/UITask.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index bc25de79..e3488853 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -295,7 +295,7 @@ public: #ifdef UI_SHOW_CLOCK display.setTextSize(3); uint32_t now = _rtc->getCurrentTime(); - now += (int32_t)_node_prefs->tz_offset * 3600; + now += (int32_t)(_node_prefs->tz_offset * 3600); DateTime dt (now); sprintf(tmp, "%02d:%02d", dt.hour(), dt.minute()); display.drawTextCentered(display.width() / 2, 60, tmp); From 277cae93ac719f76c082df9c1326d687f829ce47 Mon Sep 17 00:00:00 2001 From: agessaman <adam@gessaman.com> Date: Fri, 16 Oct 2026 20:46:04 -0700 Subject: [PATCH 293/381] fix(rak3401): sleep onboard SX1262 before boot voltage check Move the onboard radio probe into RAK3401Board::begin() so a low-voltage SYSTEMOFF at boot no longer leaves the RAK4631's onboard SX1262 in standby. Add board startup tests and run them in CI. --- .github/workflows/run-unit-tests.yml | 2 +- platformio.ini | 8 ++- .../mocks/Arduino.h | 18 +++++ test/test_rak3401_board_startup/mocks/Wire.h | 6 ++ .../mocks/helpers/NRF52Board.h | 44 ++++++++++++ .../test_board_startup.cpp | 70 +++++++++++++++++++ variants/rak3401/OnboardRadioSleep.h | 3 + variants/rak3401/RAK3401Board.cpp | 3 + variants/rak3401/target.cpp | 9 ++- 9 files changed, 157 insertions(+), 6 deletions(-) create mode 100644 test/test_rak3401_board_startup/mocks/Arduino.h create mode 100644 test/test_rak3401_board_startup/mocks/Wire.h create mode 100644 test/test_rak3401_board_startup/mocks/helpers/NRF52Board.h create mode 100644 test/test_rak3401_board_startup/test_board_startup.cpp diff --git a/.github/workflows/run-unit-tests.yml b/.github/workflows/run-unit-tests.yml index 5d48f4c6..f8145ecd 100644 --- a/.github/workflows/run-unit-tests.yml +++ b/.github/workflows/run-unit-tests.yml @@ -20,7 +20,7 @@ jobs: uses: ./.github/actions/setup-build-environment - name: Run Unit Tests - run: pio test -e native -e native_kiss_modem -vv + run: pio test -e native -e native_kiss_modem -e native_rak3401_onboard_radio -vv - name: Upload Test Results # Upload test results even if the test step failed. diff --git a/platformio.ini b/platformio.ini index e305d177..ef6b1f39 100644 --- a/platformio.ini +++ b/platformio.ini @@ -165,6 +165,7 @@ build_flags = -std=c++17 -I test/mocks test_build_src = yes test_ignore = test_kiss_modem + test_rak3401_board_startup build_src_filter = -<*> +<../src/Utils.cpp> @@ -174,10 +175,13 @@ lib_deps = google/googletest @ 1.17.0 [env:native_rak3401_onboard_radio] -; Header-only tests without unrelated production sources; also included in env:native CI. +; Board startup needs isolated GPIO and power-management mocks. extends = env:native test_build_src = no -test_filter = test_rak3401_onboard_radio +test_filter = test_rak3401_* +test_ignore = +build_flags = -I test/test_rak3401_board_startup/mocks + ${env:native.build_flags} [env:native_kiss_modem] platform = native diff --git a/test/test_rak3401_board_startup/mocks/Arduino.h b/test/test_rak3401_board_startup/mocks/Arduino.h new file mode 100644 index 00000000..d505af36 --- /dev/null +++ b/test/test_rak3401_board_startup/mocks/Arduino.h @@ -0,0 +1,18 @@ +#pragma once + +#include "../../mocks/Arduino.h" + +#define NRF52_POWER_MANAGEMENT 1 +#define PWRMGT_LPCOMP_AIN 3 +#define PWRMGT_LPCOMP_REFSEL 4 +#define PWRMGT_VOLTAGE_BOOTLOCK 3300 +#define SX126X_POWER_EN 21 +#define INPUT 0 +#define OUTPUT 1 +#define LOW 0 +#define HIGH 1 + +void pinMode(uint32_t pin, uint32_t mode); +void digitalWrite(uint32_t pin, uint32_t value); +void analogReadResolution(uint32_t bits); +uint32_t analogRead(uint32_t pin); diff --git a/test/test_rak3401_board_startup/mocks/Wire.h b/test/test_rak3401_board_startup/mocks/Wire.h new file mode 100644 index 00000000..c24e6306 --- /dev/null +++ b/test/test_rak3401_board_startup/mocks/Wire.h @@ -0,0 +1,6 @@ +#pragma once + +struct StartupWire { + void begin() {} +}; +inline StartupWire Wire; diff --git a/test/test_rak3401_board_startup/mocks/helpers/NRF52Board.h b/test/test_rak3401_board_startup/mocks/helpers/NRF52Board.h new file mode 100644 index 00000000..96c892ae --- /dev/null +++ b/test/test_rak3401_board_startup/mocks/helpers/NRF52Board.h @@ -0,0 +1,44 @@ +#pragma once + +#include <Arduino.h> +#include <string> +#include <vector> + +#define SHUTDOWN_REASON_LOW_VOLTAGE 0x4C +#define SHUTDOWN_REASON_BOOT_PROTECT 0x42 + +struct PowerMgtConfig { + uint8_t lpcomp_ain_channel; + uint8_t lpcomp_refsel; + uint16_t voltage_bootlock; +}; + +namespace startup_test { +extern std::vector<std::string> events; +extern bool permitBoot; +struct SystemOff { uint8_t reason; }; +} + +class NRF52Board { +protected: + bool checkBootVoltage(const PowerMgtConfig*) { + startup_test::events.push_back("voltage"); + if (!startup_test::permitBoot) initiateShutdown(SHUTDOWN_REASON_BOOT_PROTECT); + return true; + } + virtual void initiateShutdown(uint8_t reason) { enterSystemOff(reason); } + void configureVoltageWake(uint8_t, uint8_t) {} + void enterSystemOff(uint8_t reason) { + startup_test::events.push_back("off"); + throw startup_test::SystemOff{reason}; + } +public: + explicit NRF52Board(const char* = nullptr) {} + virtual uint16_t getBattMilliVolts() = 0; + virtual const char* getManufacturerName() const = 0; +}; + +class NRF52BoardDCDC : virtual public NRF52Board { +public: + void begin() {} +}; diff --git a/test/test_rak3401_board_startup/test_board_startup.cpp b/test/test_rak3401_board_startup/test_board_startup.cpp new file mode 100644 index 00000000..0bbf2e5a --- /dev/null +++ b/test/test_rak3401_board_startup/test_board_startup.cpp @@ -0,0 +1,70 @@ +#include <gtest/gtest.h> +#include <array> +// Exercise the real startup code with a power-management stub that stops at SYSTEMOFF. +#include "../../variants/rak3401/RAK3401Board.cpp" + +namespace startup_test { +std::vector<std::string> events; +bool permitBoot; +std::array<uint32_t, 48> outputs; +rak3401::OnboardRadioState radioState; +} + +void pinMode(uint32_t, uint32_t) {} +void digitalWrite(uint32_t pin, uint32_t value) { startup_test::outputs.at(pin) = value; } +void analogReadResolution(uint32_t) {} +uint32_t analogRead(uint32_t) { return 2500; } + +rak3401::OnboardRadioState rak3401::sleepOnboardRadio() { + startup_test::events.push_back("onboard"); + return startup_test::radioState; +} + +class RakBoardStartup : public testing::Test { +protected: + void SetUp() override { + startup_test::events.clear(); + startup_test::outputs.fill(HIGH); + startup_test::permitBoot = true; + startup_test::radioState = rak3401::OnboardRadioState::Asleep; + } +}; + +TEST_F(RakBoardStartup, OnboardRadioHandledBeforeVoltageCheck) { + RAK3401Board board; + board.begin(); + EXPECT_EQ(startup_test::events, (std::vector<std::string>{"onboard", "voltage"})); + EXPECT_EQ(startup_test::outputs.at(SX126X_POWER_EN), HIGH); + EXPECT_EQ(startup_test::outputs.at(PIN_3V3_EN), HIGH); +} + +TEST_F(RakBoardStartup, LowVoltageExitStillHandlesOnboardRadio) { + startup_test::permitBoot = false; + RAK3401Board board; + try { + board.begin(); + FAIL() << "Expected protective shutdown"; + } catch (const startup_test::SystemOff& off) { + EXPECT_EQ(off.reason, SHUTDOWN_REASON_BOOT_PROTECT); + } + EXPECT_EQ(startup_test::events, (std::vector<std::string>{"onboard", "voltage", "off"})); + EXPECT_EQ(startup_test::outputs.at(SX126X_POWER_EN), LOW); + EXPECT_EQ(startup_test::outputs.at(PIN_3V3_EN), LOW); +} + +TEST_F(RakBoardStartup, OptionalRadioFailuresDoNotBypassBootProtection) { + for (auto state : {rak3401::OnboardRadioState::Absent, rak3401::OnboardRadioState::BusyTimeout, + rak3401::OnboardRadioState::SleepFailed}) { + startup_test::events.clear(); + startup_test::permitBoot = false; + startup_test::radioState = state; + RAK3401Board board; + EXPECT_THROW(board.begin(), startup_test::SystemOff); + EXPECT_EQ(startup_test::events, (std::vector<std::string>{"onboard", "voltage", "off"})); + } +} + +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/variants/rak3401/OnboardRadioSleep.h b/variants/rak3401/OnboardRadioSleep.h index 7f6d1c55..a9690cbf 100644 --- a/variants/rak3401/OnboardRadioSleep.h +++ b/variants/rak3401/OnboardRadioSleep.h @@ -6,6 +6,9 @@ namespace rak3401 { enum class OnboardRadioState { Absent, Asleep, BusyTimeout, SleepFailed }; +// Board startup only, before the primary radio starts SPI. +OnboardRadioState sleepOnboardRadio(); + // IO owns the temporary SPI pin assignment; every outcome must release it. template <typename IO> OnboardRadioState sleepOnboardRadio(IO& io, const char* expectedVersion) { diff --git a/variants/rak3401/RAK3401Board.cpp b/variants/rak3401/RAK3401Board.cpp index cbf7c108..6f59be40 100644 --- a/variants/rak3401/RAK3401Board.cpp +++ b/variants/rak3401/RAK3401Board.cpp @@ -2,6 +2,7 @@ #include <Wire.h> #include "RAK3401Board.h" +#include "OnboardRadioSleep.h" #ifdef NRF52_POWER_MANAGEMENT // Static configuration for power management @@ -30,6 +31,8 @@ void RAK3401Board::initiateShutdown(uint8_t reason) { void RAK3401Board::begin() { NRF52BoardDCDC::begin(); + // Voltage protection can enter SYSTEMOFF before radio_init() is reached. + rak3401::sleepOnboardRadio(); pinMode(PIN_VBAT_READ, INPUT); #ifdef PIN_USER_BTN pinMode(PIN_USER_BTN, INPUT_PULLUP); diff --git a/variants/rak3401/target.cpp b/variants/rak3401/target.cpp index b9d142b3..bd971c55 100644 --- a/variants/rak3401/target.cpp +++ b/variants/rak3401/target.cpp @@ -107,9 +107,7 @@ public: }; } -bool radio_init() { - rtc_clock.begin(Wire); - // Called once from setup, before SPI is started for the RAK13302. +rak3401::OnboardRadioState rak3401::sleepOnboardRadio() { OnboardRadioIO onboard; const uint32_t started = millis(); // The SX1262 version register shares the "SX1261" prefix used by RadioLib. @@ -119,6 +117,11 @@ bool radio_init() { state == rak3401::OnboardRadioState::BusyTimeout ? "busy-timeout" : "sleep-failed"; MESH_DEBUG_PRINTLN("onboard SX1262: %s elapsed=%lu ms", outcome, (unsigned long)(millis() - started)); + return state; +} + +bool radio_init() { + rtc_clock.begin(Wire); return radio.std_init(&SPI); } From 757e84647ce1483ce775fc5abd4c459f2d8a95ef Mon Sep 17 00:00:00 2001 From: amdoolittle <amdoolittle@gmail.com> Date: Fri, 16 Oct 2026 22:39:26 -0700 Subject: [PATCH 294/381] Added WiFi to TFT BLE version of Heltec V4 --- variants/heltec_v4/platformio.ini | 2 ++ 1 file changed, 2 insertions(+) diff --git a/variants/heltec_v4/platformio.ini b/variants/heltec_v4/platformio.ini index 76e8e714..c91e31a8 100644 --- a/variants/heltec_v4/platformio.ini +++ b/variants/heltec_v4/platformio.ini @@ -380,12 +380,14 @@ build_flags = -D AUTO_SHUTDOWN_MILLIVOLTS=3400 -D BLE_DEBUG_LOGGING=1 -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_WIFI_INTERFACE ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${heltec_v4_tft.build_src_filter} +<helpers/ui/ST7789LCDDisplay.cpp> +<helpers/ui/MomentaryButton.cpp> +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = From b2bde37fe4e9d58e02e97d30982809792c0f57f3 Mon Sep 17 00:00:00 2001 From: rado <6479266+rbrus@users.noreply.github.com> Date: Sat, 17 Oct 2026 09:36:33 +0200 Subject: [PATCH 295/381] Fix unsigned conversion of negative TX power in CommonRadioPrefs --- examples/companion_radio/NodePrefs.h | 4 +- src/helpers/CommonCLI.h | 4 +- src/helpers/CommonRadioPrefs.h | 4 +- .../test_companion_node_prefs.cpp | 57 +++++++++++++++++++ 4 files changed, 63 insertions(+), 6 deletions(-) diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index 3cceed56..1cc5b501 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -102,8 +102,8 @@ private: void setIntThresh(uint8_t t) override { _parent->interference_threshold = t; markDirty(); } uint8_t getRxGain() const override { return _parent->rx_boosted_gain; } void setRxGain(uint8_t g) override { _parent->rx_boosted_gain = g; markDirty(); } - uint8_t getTxPower() const override { return _parent->tx_power_dbm; } - void setTxPower(uint8_t dbm) override { _parent->tx_power_dbm = dbm; markDirty(); } + int8_t getTxPower() const override { return _parent->tx_power_dbm; } + void setTxPower(int8_t dbm) override { _parent->tx_power_dbm = dbm; markDirty(); } float getRxDelay() const override { return _parent->rx_delay_base; } void setRxDelay(float d) override { _parent->rx_delay_base = d; markDirty(); } uint16_t getAgcResetInt() const override { return _parent->agc_reset_interval * 4; } diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 2759b0c4..675df7a4 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -115,8 +115,8 @@ private: void setIntThresh(uint8_t t) override { _parent->interference_threshold = t; markDirty(); } uint8_t getRxGain() const override { return _parent->rx_boosted_gain; } void setRxGain(uint8_t g) override { _parent->rx_boosted_gain = g; markDirty(); } - uint8_t getTxPower() const override { return _parent->tx_power_dbm; } - void setTxPower(uint8_t dbm) override { _parent->tx_power_dbm = dbm; markDirty(); } + int8_t getTxPower() const override { return _parent->tx_power_dbm; } + void setTxPower(int8_t dbm) override { _parent->tx_power_dbm = dbm; markDirty(); } float getRxDelay() const override { return _parent->rx_delay_base; } void setRxDelay(float d) override { _parent->rx_delay_base = d; markDirty(); } uint16_t getAgcResetInt() const override { return _parent->agc_reset_interval * 4; } diff --git a/src/helpers/CommonRadioPrefs.h b/src/helpers/CommonRadioPrefs.h index 0e83ca9d..d0083b8c 100644 --- a/src/helpers/CommonRadioPrefs.h +++ b/src/helpers/CommonRadioPrefs.h @@ -35,8 +35,8 @@ public: virtual uint8_t getRxGain() const = 0; virtual void setRxGain(uint8_t g) = 0; - virtual uint8_t getTxPower() const = 0; - virtual void setTxPower(uint8_t dbm) = 0; + virtual int8_t getTxPower() const = 0; + virtual void setTxPower(int8_t dbm) = 0; virtual float getRxDelay() const = 0; virtual void setRxDelay(float d) = 0; diff --git a/test/test_companion_node_prefs/test_companion_node_prefs.cpp b/test/test_companion_node_prefs/test_companion_node_prefs.cpp index 433c9710..ab5e0f90 100644 --- a/test/test_companion_node_prefs/test_companion_node_prefs.cpp +++ b/test/test_companion_node_prefs/test_companion_node_prefs.cpp @@ -6,6 +6,32 @@ #include "../../examples/companion_radio/NodePrefs.h" +bool CommonRadioPrefs::getByKey(const char* key, char* value, size_t max_len) { + if (strcmp(key, "fem_rxgain") == 0) { + snprintf(value, max_len, "%d", (uint32_t)getFEMRxGain()); + return true; + } + if (strcmp(key, "fem_txgain") == 0) { + snprintf(value, max_len, "%d", (uint32_t)getFEMTxGain()); + return true; + } + return false; +} + +bool CommonRadioPrefs::setByKey(const char* key, const char* value) { + if (strcmp(key, "fem_rxgain") == 0) { + setFEMRxGain(atoi(value)); + markDirty(); + return true; + } + if (strcmp(key, "fem_txgain") == 0) { + setFEMTxGain(atoi(value)); + markDirty(); + return true; + } + return false; +} + class ReplayStream : public Stream { const char* _text; int _pos = 0; @@ -77,6 +103,37 @@ TEST(CompanionNodePrefs, RxGainSettingsRoundTripIndependently) { } #endif +TEST(CompanionNodePrefs, NegativeTxPowerPreservedAsSigned) { + NodePrefs prefs; + CommonRadioPrefs* radio = prefs.getRadioPrefs(); + + radio->setTxPower(-9); + EXPECT_EQ(-9, prefs.tx_power_dbm); + EXPECT_EQ(-9, radio->getTxPower()); + EXPECT_EQ(-9, static_cast<int32_t>(radio->getTxPower())); + + char reply[32]; + snprintf(reply, sizeof(reply), "> %d", static_cast<int32_t>(radio->getTxPower())); + EXPECT_STREQ("> -9", reply); +} + +TEST(CompanionNodePrefs, NegativeTxPowerRoundTripsSerial) { + NodePrefs saved; + saved.getRadioPrefs()->setTxPower(-9); + + CaptureStream output; + ASSERT_TRUE(saved.saveSerial(output)); + EXPECT_NE(std::string::npos, output.text().find("tx:-9")); + + ReplayStream input("{radio:{tx:-9}}"); + NodePrefs loaded; + loaded.tx_power_dbm = 22; + + ASSERT_TRUE(loaded.loadSerial(input)); + EXPECT_EQ(-9, loaded.tx_power_dbm); + EXPECT_EQ(-9, loaded.getRadioPrefs()->getTxPower()); +} + int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); From 5f967d818a660c6a650b4a67d2510937a9b86497 Mon Sep 17 00:00:00 2001 From: Confituurke <9595028+Confituurke@users.noreply.github.com> Date: Sat, 17 Oct 2026 13:03:06 +0200 Subject: [PATCH 296/381] Show quarter-hour timezone offsets with two decimals 'get tz.offset' printed one decimal, so a UTC+5:45 offset (5.75) read back as 5.8. Print two decimals when the offset is on a quarter hour (x.25 / x.75); everything else keeps one decimal. --- examples/companion_radio/MyMesh.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 99a9aa30..2ea539db 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2192,7 +2192,7 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* } if (strcmp(command, "get tz.offset") == 0) { - sprintf(reply, "> %.1f", _prefs.tz_offset); + sprintf(reply, ((int)(_prefs.tz_offset * 4) % 2) ? "> %.2f" : "> %.1f", _prefs.tz_offset); return true; } if (memcmp(command, "set tz.offset ", 14) == 0) { From bae1b189d40241d4c294ef08437b2b89f4eb692b Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 17 Oct 2026 23:08:26 +0200 Subject: [PATCH 297/381] Add repeater environment for Wio Tracker L1 E-Ink Adds WioTrackerL1Eink_repeater, based on the OLED WioTrackerL1_repeater env but using the E-Ink base config and GxEPDDisplay. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012uhHFHwrigVgmzkD9GFAfA --- variants/wio-tracker-l1-eink/platformio.ini | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/variants/wio-tracker-l1-eink/platformio.ini b/variants/wio-tracker-l1-eink/platformio.ini index 2c74bade..08f759b7 100644 --- a/variants/wio-tracker-l1-eink/platformio.ini +++ b/variants/wio-tracker-l1-eink/platformio.ini @@ -69,6 +69,21 @@ lib_deps = ${WioTrackerL1Eink.lib_deps} end2endzone/NonBlockingRTTTL@^1.3.0 debug_tool=stlink +[env:WioTrackerL1Eink_repeater] +extends = WioTrackerL1Eink +build_src_filter = ${WioTrackerL1Eink.build_src_filter} + +<../examples/simple_repeater> +build_flags = + ${WioTrackerL1Eink.build_flags} + -D ADVERT_NAME='"WioTrackerL1 Eink Repeater"' + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=50 + -D DISPLAY_CLASS=GxEPDDisplay +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +lib_deps = ${WioTrackerL1Eink.lib_deps} + adafruit/RTClib @ ^2.1.3 + [env:WioTrackerL1Eink_kiss_modem] extends = WioTrackerL1Eink build_src_filter = ${WioTrackerL1Eink.build_src_filter} From 36f2b1d163ed158688e0a50e681b57e5123503a1 Mon Sep 17 00:00:00 2001 From: R0ck <develop@hectospark.co.uk> Date: Sat, 17 Oct 2026 23:27:43 +0100 Subject: [PATCH 298/381] Remove the acknowledgement tones --- variants/t1000-e/T1000eBoard.cpp | 24 ++---------------------- variants/t1000-e/T1000eBoard.h | 1 - 2 files changed, 2 insertions(+), 23 deletions(-) diff --git a/variants/t1000-e/T1000eBoard.cpp b/variants/t1000-e/T1000eBoard.cpp index 9bdeff89..649ae9d6 100644 --- a/variants/t1000-e/T1000eBoard.cpp +++ b/variants/t1000-e/T1000eBoard.cpp @@ -3,10 +3,6 @@ #include "T1000eBoard.h" -#ifdef PIN_BUZZER_EN - #include <NonBlockingRtttl.h> -#endif - void T1000eBoard::begin() { NRF52BoardDCDC::begin(); btn_prev_state = HIGH; @@ -36,13 +32,6 @@ void T1000eBoard::attachDynamicPrefs(KeyValueStore* prefs) { #endif } -#ifdef PIN_BUZZER_EN -static void playTune(const char* tune) { - if (rtttl::isPlaying()) rtttl::stop(); - rtttl::begin(PIN_BUZZER, tune); -} -#endif - void T1000eBoard::setBuzzerEnabled(bool enable) { #ifdef PIN_BUZZER_EN _buzzer_muted = !enable; @@ -53,11 +42,6 @@ void T1000eBoard::setBuzzerEnabled(bool enable) { void T1000eBoard::loop() { NRF52BoardDCDC::loop(); #ifdef PIN_BUZZER_EN - if (!rtttl::done()) rtttl::play(); - if (_buzzer_mute_pending && rtttl::done()) { // mute once the confirmation beep has finished - _buzzer_mute_pending = false; - setBuzzerEnabled(false); - } if (_buzzer_muted) digitalWrite(PIN_BUZZER_EN, LOW); // keep it off even if the UI re-enables it #endif } @@ -65,7 +49,7 @@ void T1000eBoard::loop() { bool T1000eBoard::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { #ifdef PIN_BUZZER_EN if (strcmp(command, "get buzzer") == 0) { - sprintf(reply, "> %s", (_buzzer_muted || _buzzer_mute_pending) ? "off" : "on"); + sprintf(reply, "> %s", _buzzer_muted ? "off" : "on"); return true; } if (memcmp(command, "set buzzer ", 11) == 0) { @@ -73,18 +57,14 @@ bool T1000eBoard::handleCommand(const char* command, uint32_t sender_timestamp, if (_prefs && !_prefs->setByKey("buzzer", "1")) { strcpy(reply, "Error: failed to save buzzer setting"); } else { - _buzzer_mute_pending = false; setBuzzerEnabled(true); - playTune("MsgRcv3:d=4,o=6,b=200:32e,32g,32b,16c7"); // same tune as a new message strcpy(reply, "OK - buzzer on"); } } else if (strcmp(&command[11], "off") == 0) { if (_prefs && !_prefs->setByKey("buzzer", "0")) { strcpy(reply, "Error: failed to save buzzer setting"); } else { - setBuzzerEnabled(true); - _buzzer_mute_pending = true; - playTune("ack:d=32,o=8,b=120:c"); // same beep as an ack, before going quiet + setBuzzerEnabled(false); strcpy(reply, "OK - buzzer off"); } } else { diff --git a/variants/t1000-e/T1000eBoard.h b/variants/t1000-e/T1000eBoard.h index 846c7df2..e6ceb4fe 100644 --- a/variants/t1000-e/T1000eBoard.h +++ b/variants/t1000-e/T1000eBoard.h @@ -9,7 +9,6 @@ protected: uint8_t btn_prev_state; KeyValueStore* _prefs = NULL; bool _buzzer_muted = false; - bool _buzzer_mute_pending = false; void setBuzzerEnabled(bool enable); From b9fa77ed69cdb03229801f086eae79e02305f937 Mon Sep 17 00:00:00 2001 From: R0ck <develop@hectospark.co.uk> Date: Sat, 17 Oct 2026 23:37:14 +0100 Subject: [PATCH 299/381] Move to companion firmware, remove from varient --- examples/companion_radio/MyMesh.cpp | 17 +++++++++ variants/t1000-e/T1000eBoard.cpp | 56 +---------------------------- variants/t1000-e/T1000eBoard.h | 7 ---- 3 files changed, 18 insertions(+), 62 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index f32ea67a..ebe0636a 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2122,6 +2122,23 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* return true; } +#ifdef PIN_BUZZER + if (strcmp(command, "get buzzer") == 0) { + sprintf(reply, "> %s", _prefs.buzzer_quiet ? "off" : "on"); + return true; + } + if (memcmp(command, "set buzzer ", 11) == 0) { + if (strcmp(&command[11], "on") == 0 || strcmp(&command[11], "off") == 0) { + _prefs.buzzer_quiet = strcmp(&command[11], "off") == 0; + savePrefs(); + strcpy(reply, "OK"); + } else { + strcpy(reply, "Error: state must be on or off"); + } + return true; + } +#endif + if (memcmp(command, "set pin ", 8) == 0) { _prefs.ble_pin = atoi(&command[8]); savePrefs(); diff --git a/variants/t1000-e/T1000eBoard.cpp b/variants/t1000-e/T1000eBoard.cpp index 649ae9d6..0d390f79 100644 --- a/variants/t1000-e/T1000eBoard.cpp +++ b/variants/t1000-e/T1000eBoard.cpp @@ -20,58 +20,4 @@ void T1000eBoard::begin() { Wire.begin(); delay(10); // give sx1262 some time to power up -} - -void T1000eBoard::attachDynamicPrefs(KeyValueStore* prefs) { - _prefs = prefs; -#ifdef PIN_BUZZER_EN - char val[8]; - val[0] = 0; - _prefs->getByKey("buzzer", val, sizeof(val) - 1); - _buzzer_muted = strcmp(val, "0") == 0; -#endif -} - -void T1000eBoard::setBuzzerEnabled(bool enable) { -#ifdef PIN_BUZZER_EN - _buzzer_muted = !enable; - digitalWrite(PIN_BUZZER_EN, enable ? HIGH : LOW); -#endif -} - -void T1000eBoard::loop() { - NRF52BoardDCDC::loop(); -#ifdef PIN_BUZZER_EN - if (_buzzer_muted) digitalWrite(PIN_BUZZER_EN, LOW); // keep it off even if the UI re-enables it -#endif -} - -bool T1000eBoard::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { -#ifdef PIN_BUZZER_EN - if (strcmp(command, "get buzzer") == 0) { - sprintf(reply, "> %s", _buzzer_muted ? "off" : "on"); - return true; - } - if (memcmp(command, "set buzzer ", 11) == 0) { - if (strcmp(&command[11], "on") == 0) { - if (_prefs && !_prefs->setByKey("buzzer", "1")) { - strcpy(reply, "Error: failed to save buzzer setting"); - } else { - setBuzzerEnabled(true); - strcpy(reply, "OK - buzzer on"); - } - } else if (strcmp(&command[11], "off") == 0) { - if (_prefs && !_prefs->setByKey("buzzer", "0")) { - strcpy(reply, "Error: failed to save buzzer setting"); - } else { - setBuzzerEnabled(false); - strcpy(reply, "OK - buzzer off"); - } - } else { - strcpy(reply, "Error: state must be on or off"); - } - return true; - } -#endif - return false; // not handled -} +} \ No newline at end of file diff --git a/variants/t1000-e/T1000eBoard.h b/variants/t1000-e/T1000eBoard.h index e6ceb4fe..ba8bf0c1 100644 --- a/variants/t1000-e/T1000eBoard.h +++ b/variants/t1000-e/T1000eBoard.h @@ -7,17 +7,10 @@ class T1000eBoard : public NRF52BoardDCDC { protected: uint8_t btn_prev_state; - KeyValueStore* _prefs = NULL; - bool _buzzer_muted = false; - - void setBuzzerEnabled(bool enable); public: T1000eBoard() : NRF52Board("T1000E_OTA") {} void begin(); - void attachDynamicPrefs(KeyValueStore* prefs); - bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; - void loop() override; uint16_t getBattMilliVolts() override { #ifdef BATTERY_PIN From edb94d3fdcd0fb91397fa37720e39e132bf4865d Mon Sep 17 00:00:00 2001 From: R0ck <develop@hectospark.co.uk> Date: Sat, 17 Oct 2026 23:53:27 +0100 Subject: [PATCH 300/381] Apply buzzer setting changes in the UI so no reboot needed. --- examples/companion_radio/ui-new/UITask.cpp | 1 + examples/companion_radio/ui-orig/UITask.cpp | 1 + examples/companion_radio/ui-tiny/UITask.cpp | 1 + 3 files changed, 3 insertions(+) diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index bc25de79..e43fc5ea 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -1015,6 +1015,7 @@ void UITask::loop() { userLedHandler(); #ifdef PIN_BUZZER + if (buzzer.isQuiet() != (bool)_node_prefs->buzzer_quiet) buzzer.quiet(_node_prefs->buzzer_quiet); if (buzzer.isPlaying()) buzzer.loop(); #endif diff --git a/examples/companion_radio/ui-orig/UITask.cpp b/examples/companion_radio/ui-orig/UITask.cpp index db8772f4..8ae57c7a 100644 --- a/examples/companion_radio/ui-orig/UITask.cpp +++ b/examples/companion_radio/ui-orig/UITask.cpp @@ -485,6 +485,7 @@ void UITask::loop() { userLedHandler(); #ifdef PIN_BUZZER + if (buzzer.isQuiet() != (bool)_node_prefs->buzzer_quiet) buzzer.quiet(_node_prefs->buzzer_quiet); if (buzzer.isPlaying()) buzzer.loop(); #endif diff --git a/examples/companion_radio/ui-tiny/UITask.cpp b/examples/companion_radio/ui-tiny/UITask.cpp index 7b70f836..6bf33849 100644 --- a/examples/companion_radio/ui-tiny/UITask.cpp +++ b/examples/companion_radio/ui-tiny/UITask.cpp @@ -691,6 +691,7 @@ void UITask::loop() { userLedHandler(); #ifdef PIN_BUZZER + if (buzzer.isQuiet() != (bool)_node_prefs->buzzer_quiet) buzzer.quiet(_node_prefs->buzzer_quiet); if (buzzer.isPlaying()) buzzer.loop(); #endif From ad0324d354fa9238095956c3d0fb2d701a843e37 Mon Sep 17 00:00:00 2001 From: Radek <“6479266+rbrus@users.noreply.github.com”> Date: Sun, 18 Oct 2026 09:21:53 +0200 Subject: [PATCH 301/381] added dynamic wifi to: lilygo t-beam supreme sx1262 ble companion --- variants/lilygo_tbeam_supreme_SX1262/platformio.ini | 2 ++ 1 file changed, 2 insertions(+) diff --git a/variants/lilygo_tbeam_supreme_SX1262/platformio.ini b/variants/lilygo_tbeam_supreme_SX1262/platformio.ini index af4a8eaf..18a82802 100644 --- a/variants/lilygo_tbeam_supreme_SX1262/platformio.ini +++ b/variants/lilygo_tbeam_supreme_SX1262/platformio.ini @@ -131,11 +131,13 @@ build_flags = -D MAX_GROUP_CHANNELS=40 -D BLE_PIN_CODE=123456 -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_WIFI_INTERFACE ; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=8 ; -D MESH_DEBUG=1 build_src_filter = ${T_Beam_S3_Supreme_SX1262.build_src_filter} +<helpers/esp32/*.cpp> + +<helpers/wifi/*.cpp> +<helpers/ui/MomentaryButton.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> From c2d01f3c416c59107d24e01d138bf0ae18a44829 Mon Sep 17 00:00:00 2001 From: Marcel Verdult <marcel@verdult.de> Date: Mon, 19 Oct 2026 23:19:42 +0200 Subject: [PATCH 302/381] fix(meshtracker_x1): inherit MicroNMEA in every environment of the variant What changes - variants/meshtracker_x1/platformio.ini moves stevemarple/MicroNMEA from the four environments that listed it into the [MeshTracker_X1] base section, the way nano_g2_ultra already keeps it, and drops the four copies. Why - MeshTracker_X1_kiss_modem was the one environment of this variant that did not list the library, so it did not build: src/helpers/sensors/MicroNMEALocationProvider.h:4: fatal error: MicroNMEA.h: No such file or directory variants/meshtracker_x1/target.cpp includes the location provider unconditionally and every environment of this variant compiles target.cpp, so every one of them needs the library. Putting it in the base section makes that true by construction rather than by repeating the line and hoping none is forgotten, which is exactly what happened here. Compatibility - All five environments of the variant were built, which is the whole reach of this change. MeshTracker_X1_kiss_modem now builds (text 240180, bss 18236; on unchanged dev it does not build at all). For the four that already built, text and bss are byte for byte identical to a build from unchanged dev c9fa617c with the same toolchain, so inheriting the library instead of listing it changes nothing for them: MeshTracker_X1_repeater text 299524 bss 32024, _room_server 292020 / 35740, _companion_radio_usb 316356 / 141000, _companion_radio_ble 322036 / 145432, each text +0 and bss +0 against dev. --- variants/meshtracker_x1/platformio.ini | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/variants/meshtracker_x1/platformio.ini b/variants/meshtracker_x1/platformio.ini index 2194d48d..80286460 100644 --- a/variants/meshtracker_x1/platformio.ini +++ b/variants/meshtracker_x1/platformio.ini @@ -34,6 +34,7 @@ build_src_filter = ${nrf52_base.build_src_filter} +<../variants/meshtracker_x1> lib_deps = ${nrf52_base.lib_deps} https://github.com/adafruit/Adafruit_SPA06_003/archive/refs/tags/1.0.2.zip + stevemarple/MicroNMEA @ ^2.0.6 debug_tool = jlink upload_protocol = nrfutil @@ -51,7 +52,6 @@ build_flags = ${MeshTracker_X1.build_flags} build_src_filter = ${MeshTracker_X1.build_src_filter} +<../examples/simple_repeater> lib_deps = ${MeshTracker_X1.lib_deps} - stevemarple/MicroNMEA @ ^2.0.6 [env:MeshTracker_X1_room_server] extends = MeshTracker_X1 @@ -67,7 +67,6 @@ build_flags = ${MeshTracker_X1.build_flags} build_src_filter = ${MeshTracker_X1.build_src_filter} +<../examples/simple_room_server> lib_deps = ${MeshTracker_X1.lib_deps} - stevemarple/MicroNMEA @ ^2.0.6 [env:MeshTracker_X1_companion_radio_usb] extends = MeshTracker_X1 @@ -94,7 +93,6 @@ build_src_filter = ${MeshTracker_X1.build_src_filter} +<../examples/companion_radio/ui-orig/*.cpp> lib_deps = ${MeshTracker_X1.lib_deps} densaugeo/base64 @ ~1.4.0 - stevemarple/MicroNMEA @ ^2.0.6 end2endzone/NonBlockingRTTTL@^1.3.0 adafruit/Adafruit DRV2605 Library @ ^1.2.4 @@ -127,7 +125,6 @@ build_src_filter = ${MeshTracker_X1.build_src_filter} +<../examples/companion_radio/ui-orig/*.cpp> lib_deps = ${MeshTracker_X1.lib_deps} densaugeo/base64 @ ~1.4.0 - stevemarple/MicroNMEA @ ^2.0.6 end2endzone/NonBlockingRTTTL@^1.3.0 adafruit/Adafruit DRV2605 Library @ ^1.2.4 From adb01c473e966f0cf8b19960906357d79bb70853 Mon Sep 17 00:00:00 2001 From: rado <6479266+rbrus@users.noreply.github.com> Date: Tue, 20 Oct 2026 05:56:02 +0200 Subject: [PATCH 303/381] Skip empty anon contact slots in peer/contact lookups (prevent null-key ECDH sink) --- src/helpers/BaseChatMesh.cpp | 10 +- src/helpers/ContactInfo.h | 6 + .../test_empty_contact_slots.cpp | 230 ++++++++++++++++++ 3 files changed, 245 insertions(+), 1 deletion(-) create mode 100644 test/test_empty_contact_slots/test_empty_contact_slots.cpp diff --git a/src/helpers/BaseChatMesh.cpp b/src/helpers/BaseChatMesh.cpp index 28592415..2c9ad745 100644 --- a/src/helpers/BaseChatMesh.cpp +++ b/src/helpers/BaseChatMesh.cpp @@ -128,6 +128,7 @@ void BaseChatMesh::onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, ContactInfo* from = NULL; for (int i = 0; i < num_contacts; i++) { + if (contacts[i].isEmptySlot()) continue; if (id.matches(contacts[i].id)) { // is from one of our contacts from = &contacts[i]; if (timestamp <= from->last_advert_timestamp) { // check for replay attacks!! @@ -203,6 +204,11 @@ void BaseChatMesh::onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, int BaseChatMesh::searchPeersByHash(const uint8_t* hash) { int n = 0; for (int i = 0; i < num_contacts && n < MAX_SEARCH_RESULTS; i++) { + // Skip empty/unconfigured anon slots. An empty slot has an all-zero pub_key + // (an order-4 Edwards25519 point whose clamped X25519 key exchange yields an + // all-zero shared secret for any private key) and would otherwise match + // src_hash == 0x00 as a null-key peer sink while consuming search slots. + if (contacts[i].isEmptySlot()) continue; if (contacts[i].id.isHashMatch(hash)) { matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods) } @@ -866,6 +872,7 @@ ContactInfo* BaseChatMesh::searchContactsByPrefix(const char* name_prefix) { int len = strlen(name_prefix); for (int i = 0; i < num_contacts; i++) { auto c = &contacts[i]; + if (c->isEmptySlot() || c->name[0] == 0) continue; if (memcmp(c->name, name_prefix, len) == 0) return c; } return NULL; // not found @@ -874,6 +881,7 @@ ContactInfo* BaseChatMesh::searchContactsByPrefix(const char* name_prefix) { ContactInfo* BaseChatMesh::lookupContactByPubKey(const uint8_t* pub_key, int prefix_len) { for (int i = 0; i < num_contacts; i++) { auto c = &contacts[i]; + if (c->isEmptySlot()) continue; if (memcmp(c->id.pub_key, pub_key, prefix_len) == 0) return c; } return NULL; // not found @@ -891,7 +899,7 @@ bool BaseChatMesh::addContact(const ContactInfo& contact) { bool BaseChatMesh::removeContact(ContactInfo& contact) { int idx = 0; - while (idx < num_contacts && !contacts[idx].id.matches(contact.id)) { + while (idx < num_contacts && (contacts[idx].isEmptySlot() || !contacts[idx].id.matches(contact.id))) { idx++; } if (idx >= num_contacts) return false; // not found diff --git a/src/helpers/ContactInfo.h b/src/helpers/ContactInfo.h index 5a156c82..a401117e 100644 --- a/src/helpers/ContactInfo.h +++ b/src/helpers/ContactInfo.h @@ -31,6 +31,12 @@ struct ContactInfo { bool isTelemLocAllowed() const { return flags & 0x04; } bool isTelemEnvAllowed() const { return flags & 0x08; } bool isRemoteCLIAllowed() const { return flags & 0x10; } + bool isEmptySlot() const { + for (int i = 0; i < PUB_KEY_SIZE; i++) { + if (id.pub_key[i] != 0) return false; + } + return true; + } private: mutable uint8_t shared_secret[PUB_KEY_SIZE]; diff --git a/test/test_empty_contact_slots/test_empty_contact_slots.cpp b/test/test_empty_contact_slots/test_empty_contact_slots.cpp new file mode 100644 index 00000000..cb4d5912 --- /dev/null +++ b/test/test_empty_contact_slots/test_empty_contact_slots.cpp @@ -0,0 +1,230 @@ +#include <gtest/gtest.h> +#include <cstring> +#include <ed_25519.h> + +#include "Dispatcher.cpp" +#include "Mesh.cpp" +#include "helpers/AdvertDataHelpers.cpp" +#include "helpers/BaseChatMesh.cpp" + +void StrHelper::strncpy(char* dest, const char* src, size_t buf_sz) { + if (buf_sz == 0) return; + std::strncpy(dest, src, buf_sz - 1); + dest[buf_sz - 1] = 0; +} + +namespace mesh { + +Identity::Identity() { + memset(pub_key, 0, sizeof(pub_key)); +} + +bool Identity::verify(const uint8_t*, const uint8_t*, int) const { + return true; +} + +LocalIdentity::LocalIdentity() : Identity() { + memset(prv_key, 0, sizeof(prv_key)); +} + +void LocalIdentity::sign(uint8_t* sig, const uint8_t*, int) const { + memset(sig, 0, SIGNATURE_SIZE); +} + +void LocalIdentity::calcSharedSecret(uint8_t* secret, const uint8_t* other_pub_key) const { + ed25519_key_exchange(secret, other_pub_key, prv_key); +} + +} // namespace mesh + +namespace { + +class DummyRadio : public mesh::Radio { +public: + int recvRaw(uint8_t*, int) override { return 0; } + uint32_t getEstAirtimeFor(int) override { return 10; } + float packetScore(float, int) override { return 1.0f; } + bool startSendRaw(const uint8_t*, int) override { return true; } + bool isSendComplete() override { return true; } + void onSendFinished() override {} + bool isInRecvMode() const override { return true; } +}; + +class DummyMillisecondClock : public mesh::MillisecondClock { +public: + unsigned long getMillis() override { return 1000; } +}; + +class DummyRNG : public mesh::RNG { +public: + void random(uint8_t* dest, size_t len) override { memset(dest, 0x42, len); } +}; + +class DummyRTCClock : public mesh::RTCClock { + uint32_t _now = 1700000000; +public: + uint32_t getCurrentTime() override { return _now; } + void setCurrentTime(uint32_t time) override { _now = time; } +}; + +class DummyPacketManager : public mesh::PacketManager { +public: + mesh::Packet* allocNew() override { return nullptr; } + void free(mesh::Packet*) override {} + void queueOutbound(mesh::Packet*, uint8_t, uint32_t) override {} + mesh::Packet* getNextOutbound(uint32_t) override { return nullptr; } + int getOutboundCount(uint32_t) const override { return 0; } + int getOutboundTotal() const override { return 0; } + int getFreeCount() const override { return 16; } + mesh::Packet* getOutboundByIdx(int) override { return nullptr; } + mesh::Packet* removeOutboundByIdx(int) override { return nullptr; } + void queueInbound(mesh::Packet*, uint32_t) override {} + mesh::Packet* getNextInbound(uint32_t) override { return nullptr; } +}; + +class DummyMeshTables : public mesh::MeshTables { +public: + bool wasSeen(const mesh::Packet*) override { return false; } + void markSeen(const mesh::Packet*) override {} + void clear(const mesh::Packet*) override {} +}; + +class TestChatMesh : public BaseChatMesh { +public: + int messages_received = 0; + + TestChatMesh(mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, + mesh::RTCClock& rtc, mesh::PacketManager& mgr, mesh::MeshTables& tables) + : BaseChatMesh(radio, ms, rng, rtc, mgr, tables) {} + + void onDiscoveredContact(ContactInfo&, bool, uint8_t, const uint8_t*) override {} + ContactInfo* processAck(const uint8_t*) override { return nullptr; } + void onContactPathUpdated(const ContactInfo&) override {} + void onMessageRecv(const ContactInfo&, mesh::Packet*, uint32_t, const char*) override { + messages_received++; + } + void onCommandDataRecv(const ContactInfo&, mesh::Packet*, uint32_t, const char*) override {} + void onCLICommandRecv(const ContactInfo&, mesh::Packet*, uint32_t, const char*, char*) override {} + void onSignedMessageRecv(const ContactInfo&, mesh::Packet*, uint32_t, const uint8_t*, const char*) override {} + void onChannelMessageRecv(const mesh::GroupChannel&, mesh::Packet*, uint32_t, const char*) override {} + uint8_t onContactRequest(const ContactInfo&, uint32_t, const uint8_t*, uint8_t, uint8_t*) override { return 0; } + void onContactResponse(const ContactInfo&, const uint8_t*, uint8_t) override {} + uint32_t calcFloodTimeoutMillisFor(uint32_t) const override { return 1000; } + uint32_t calcDirectTimeoutMillisFor(uint32_t, uint8_t) const override { return 1000; } + void onSendTimeout() override {} + + using BaseChatMesh::resetContacts; + using BaseChatMesh::searchPeersByHash; + using BaseChatMesh::getPeerSharedSecret; + using mesh::Mesh::onRecvPacket; +}; + +struct MeshFixture { + DummyRadio radio; + DummyMillisecondClock ms; + DummyRNG rng; + DummyRTCClock rtc; + DummyPacketManager mgr; + DummyMeshTables tables; + TestChatMesh chat{radio, ms, rng, rtc, mgr, tables}; +}; + +} // namespace + +TEST(EmptyContactSlots, ZeroPubKeyProducesAllZeroSharedSecretForAnyPrivateKey) { + ContactInfo empty_slot; + memset(&empty_slot, 0, sizeof(empty_slot)); + EXPECT_TRUE(empty_slot.isEmptySlot()); + + uint8_t raw_prv[PRV_KEY_SIZE]; + for (int i = 0; i < PRV_KEY_SIZE; i++) { + raw_prv[i] = static_cast<uint8_t>(0xA5 ^ (i * 13 + 7)); + } + uint8_t secret[PUB_KEY_SIZE]; + ed25519_key_exchange(secret, empty_slot.id.pub_key, raw_prv); + + uint8_t expected_zeroes[PUB_KEY_SIZE] = { 0 }; + EXPECT_EQ(0, memcmp(secret, expected_zeroes, PUB_KEY_SIZE)); +} + +TEST(EmptyContactSlots, NullKeyPeerPacketIsRejectedWhenAnonSlotsAreEmpty) { + MeshFixture fx; + fx.chat.self_id.pub_key[0] = 0x42; + + // Craft a PAYLOAD_TYPE_TXT_MSG addressed to self_id (dest_hash=0x42) with src_hash=0x00, + // encrypted and MAC'd under the all-zero 32-byte key that an empty ContactInfo slot derives. + uint8_t zero_secret[PUB_KEY_SIZE] = { 0 }; + uint8_t plaintext[16] = { 0 }; + uint32_t ts = 1700000001; + memcpy(plaintext, &ts, 4); + plaintext[4] = (TXT_TYPE_PLAIN << 2); + strcpy(reinterpret_cast<char*>(&plaintext[5]), "forged"); + + mesh::Packet pkt; + pkt.header = ROUTE_TYPE_FLOOD | (PAYLOAD_TYPE_TXT_MSG << PH_TYPE_SHIFT); + pkt.path_len = 0; + pkt.payload[0] = 0x42; // dest_hash (matches fx.chat.self_id) + pkt.payload[1] = 0x00; // src_hash (matches all-zero pub_key if empty slots are not skipped) + int enc_len = mesh::Utils::encryptThenMAC(zero_secret, &pkt.payload[2], plaintext, 12); + pkt.payload_len = static_cast<uint8_t>(2 + enc_len); + + fx.chat.onRecvPacket(&pkt); + EXPECT_EQ(0, fx.chat.messages_received); +} + +TEST(EmptyContactSlots, SearchPeersByHashSkipsEmptyAnonSlotsAndFindsRealZeroPrefixPeer) { + MeshFixture fx; + const uint8_t zero_hash = 0x00; + + // Freshly reset contacts has MAX_ANON_CONTACTS (8) zeroed transient slots. + EXPECT_EQ(0, fx.chat.searchPeersByHash(&zero_hash)); + + // Add a legitimate permanent contact whose public key starts with 0x00. + ContactInfo peer; + memset(&peer, 0, sizeof(peer)); + peer.type = ADV_TYPE_CHAT; + peer.lastmod = 1700000100; + strcpy(peer.name, "Alice"); + peer.id.pub_key[0] = 0x00; + for (int i = 1; i < PUB_KEY_SIZE; i++) { + peer.id.pub_key[i] = static_cast<uint8_t>(i); + } + ASSERT_TRUE(fx.chat.addContact(peer)); + + // Only the populated contact at index MAX_ANON_CONTACTS should match. + EXPECT_EQ(1, fx.chat.searchPeersByHash(&zero_hash)); + + // Lookup by pubkey and name prefix must also skip the empty transient slots. + uint8_t zero_prefix[6] = { 0 }; + EXPECT_EQ(nullptr, fx.chat.lookupContactByPubKey(zero_prefix, sizeof(zero_prefix))); + + ContactInfo* found = fx.chat.lookupContactByPubKey(peer.id.pub_key, 6); + ASSERT_NE(nullptr, found); + EXPECT_STREQ("Alice", found->name); + + ContactInfo* by_name = fx.chat.searchContactsByPrefix(""); + ASSERT_NE(nullptr, by_name); + EXPECT_STREQ("Alice", by_name->name); +} + +TEST(EmptyContactSlots, PopulatedTransientAnonSlotStillMatchesEvenWhenLastmodIsZero) { + MeshFixture fx; + const uint8_t zero_hash = 0x00; + + ContactInfo anon; + memset(&anon, 0, sizeof(anon)); + anon.type = ADV_TYPE_NONE; + anon.lastmod = 0; // e.g. RTC not yet initialised on nRF52 + anon.id.pub_key[0] = 0x00; + anon.id.pub_key[1] = 0x7F; + ASSERT_TRUE(fx.chat.addContact(anon)); + + EXPECT_FALSE(anon.isEmptySlot()); + EXPECT_EQ(1, fx.chat.searchPeersByHash(&zero_hash)); + EXPECT_NE(nullptr, fx.chat.lookupContactByPubKey(anon.id.pub_key, PUB_KEY_SIZE)); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} From e296c49580a487e69319445af4262d899d88b8aa Mon Sep 17 00:00:00 2001 From: Luca Olivieri <gliolivieri@live.it> Date: Tue, 20 Oct 2026 19:58:14 +0200 Subject: [PATCH 304/381] Add LilyGO T3 STM32 support --- .github/workflows/pr-build-check.yml | 2 + README.md | 1 + boards/lilygo_t3_stm32.json | 32 ++++++++ src/helpers/ui/SSD1306Display.cpp | 7 +- src/helpers/ui/SSD1306Display.h | 8 ++ variants/lilygo_t3_stm32/README.md | 66 +++++++++++++++ variants/lilygo_t3_stm32/STM32ArduinoCompat.h | 11 +++ variants/lilygo_t3_stm32/platformio.ini | 52 ++++++++++++ variants/lilygo_t3_stm32/target.cpp | 82 +++++++++++++++++++ variants/lilygo_t3_stm32/target.h | 28 +++++++ 10 files changed, 288 insertions(+), 1 deletion(-) create mode 100644 boards/lilygo_t3_stm32.json create mode 100644 variants/lilygo_t3_stm32/README.md create mode 100644 variants/lilygo_t3_stm32/STM32ArduinoCompat.h create mode 100644 variants/lilygo_t3_stm32/platformio.ini create mode 100644 variants/lilygo_t3_stm32/target.cpp create mode 100644 variants/lilygo_t3_stm32/target.h diff --git a/.github/workflows/pr-build-check.yml b/.github/workflows/pr-build-check.yml index cebf0cfe..0dcb159e 100644 --- a/.github/workflows/pr-build-check.yml +++ b/.github/workflows/pr-build-check.yml @@ -40,6 +40,8 @@ jobs: - PicoW_repeater # STM32 - wio-e5-mini_repeater + - LilyGo_T3_STM32_repeater + - LilyGo_T3_STM32_companion_radio_usb # ESP32-C6 - LilyGo_Tlora_C6_repeater_ # LR1110 (nRF52) diff --git a/README.md b/README.md index 6cc45d7f..a8f72e0f 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ For developers: - Install [PlatformIO](https://docs.platformio.org) in [Visual Studio Code](https://code.visualstudio.com). - Clone and open the MeshCore repository in Visual Studio Code. +- For the LilyGO T3 STM32, see the [board build and flashing guide](./variants/lilygo_t3_stm32/README.md). - See the example applications you can modify and run: - [Companion Radio](./examples/companion_radio) - For use with an external chat app, over BLE, USB or Wi-Fi. - [KISS Modem](./examples/kiss_modem) - Serial KISS protocol bridge for host applications. ([protocol docs](./docs/kiss_modem_protocol.md)) diff --git a/boards/lilygo_t3_stm32.json b/boards/lilygo_t3_stm32.json new file mode 100644 index 00000000..3f323402 --- /dev/null +++ b/boards/lilygo_t3_stm32.json @@ -0,0 +1,32 @@ +{ + "build": { + "arduino": { + "variant_h": "variant_generic.h" + }, + "core": "stm32", + "cpu": "cortex-m4", + "extra_flags": "-DSTM32WL -DSTM32WLxx -DSTM32WL55xx", + "f_cpu": "48000000L", + "framework_extra_flags": { + "arduino": "-DUSE_CM4_STARTUP_FILE -DARDUINO_GENERIC_WL55CCUX" + }, + "mcu": "stm32wl55ccu6", + "product_line": "STM32WL55xx", + "variant": "STM32WLxx/WL54CCU_WL55CCU_WLE4C(8-B-C)U_WLE5C(8-B-C)U" + }, + "debug": { + "jlink_device": "STM32WL55CC", + "openocd_target": "stm32wlx", + "svd_path": "STM32WL5x_CM4.svd" + }, + "frameworks": ["arduino"], + "name": "LilyGO T3 STM32 V1.0 (STM32WL55CCU6)", + "upload": { + "maximum_ram_size": 65536, + "maximum_size": 262144, + "protocol": "serial", + "protocols": ["serial", "stlink", "jlink"] + }, + "url": "https://github.com/Xinyuan-LilyGO/T3-STM32", + "vendor": "LilyGO" +} diff --git a/src/helpers/ui/SSD1306Display.cpp b/src/helpers/ui/SSD1306Display.cpp index ab2d77fb..4c33f6f8 100644 --- a/src/helpers/ui/SSD1306Display.cpp +++ b/src/helpers/ui/SSD1306Display.cpp @@ -25,7 +25,12 @@ bool SSD1306Display::begin() { #ifdef DISPLAY_ROTATION display.setRotation(DISPLAY_ROTATION); #endif - return display.begin(SSD1306_SWITCHCAPVCC, DISPLAY_ADDRESS, true, false) && i2c_probe(Wire, DISPLAY_ADDRESS); + bool success = display.begin(SSD1306_SWITCHCAPVCC, DISPLAY_ADDRESS, true, false); + #if defined(PIN_OLED_CS) && defined(PIN_OLED_DC) + return success; + #else + return success && i2c_probe(Wire, DISPLAY_ADDRESS); + #endif } void SSD1306Display::turnOn() { diff --git a/src/helpers/ui/SSD1306Display.h b/src/helpers/ui/SSD1306Display.h index 5dabbc58..e8f1ded3 100644 --- a/src/helpers/ui/SSD1306Display.h +++ b/src/helpers/ui/SSD1306Display.h @@ -15,6 +15,10 @@ #define DISPLAY_ADDRESS 0x3C #endif +#if defined(PIN_OLED_CS) != defined(PIN_OLED_DC) + #error "SPI OLED requires both PIN_OLED_CS and PIN_OLED_DC" +#endif + class SSD1306Display : public DisplayDriver { Adafruit_SSD1306 display; bool _isOn; @@ -24,7 +28,11 @@ class SSD1306Display : public DisplayDriver { bool i2c_probe(TwoWire& wire, uint8_t addr); public: SSD1306Display(RefCountedDigitalPin* peripher_power=NULL) : DisplayDriver(128, 64), +#if defined(PIN_OLED_CS) && defined(PIN_OLED_DC) + display(128, 64, &SPI, PIN_OLED_DC, PIN_OLED_RESET, PIN_OLED_CS), +#else display(128, 64, &Wire, PIN_OLED_RESET), +#endif _peripher_power(peripher_power) { _isOn = false; diff --git a/variants/lilygo_t3_stm32/README.md b/variants/lilygo_t3_stm32/README.md new file mode 100644 index 00000000..2686aa7f --- /dev/null +++ b/variants/lilygo_t3_stm32/README.md @@ -0,0 +1,66 @@ +# LilyGO T3 STM32 V1.0 + +MVP support for the STM32WL55CCU6 board with its integrated Sub-GHz radio and +128×64 SSD1315 SPI OLED. Supports a USB companion and a repeater, with a default +transmit power of **20 dBm**. The companion uses USB serial; the board has no BLE. + +## Build + +```sh +pio run -e LilyGo_T3_STM32_companion_radio_usb +pio run -e LilyGo_T3_STM32_repeater +``` + +The companion supports 100 contacts and eight channels. Radio settings inherit +the repository defaults; select settings appropriate to the board's RF band. +Existing saved preferences override build defaults. + +## Flash and connect + +Connect the USB serial port. Hold BOOT, press and release RST, then release BOOT: + +```sh +pio run -e LilyGo_T3_STM32_companion_radio_usb -t upload --upload-port /dev/ttyACM0 +``` + +Choose your actual serial port, then press RST after programming. The repeater +CLI and USB companion protocol both use USART1 at **115200 baud**. + +The bundled `stm32flash` 0.7 may reject device ID `0x497` due to an +[upstream packaging issue](https://github.com/platformio/platform-ststm32/issues/899). +Use an updated [stm32flash](https://sourceforge.net/p/stm32flash/code/ci/master/tree/) +with STM32WL support, or STM32CubeProgrammer in UART mode. For CubeProgrammer, +use `.pio/build/<environment>/firmware.hex`, or `firmware.bin` at `0x08000000`. +ST-Link and J-Link uploads are also available through the board's SWD connector. + +Application flash is limited to **224 KiB**. InternalFS occupies the final +32 KiB at `0x08038000`–`0x0803FFFF`; preserve it when updating to retain the +identity and settings. + +## Hardware mapping + +| Function | Pins / setting | +| --- | --- | +| USART1 | TX PA9, RX PA10 | +| Radio RF switch | PB2/PB6: idle 0/0, RX 1/0, HP TX 0/1 | +| Radio oscillator | 32 MHz crystal; TCXO mode disabled | +| SPI1 | SCK PA5, MISO PA6, MOSI PA7 | +| OLED | CS PB12, DC PA8, no software reset pin | +| SD card | CS PA4, held high | +| User button | PH3/BOOT, active high | +| LEDs | PA0/PA1, left off | + +Initialization follows the manufacturer's +[hardware files](https://github.com/Xinyuan-LilyGO/T3-STM32/tree/master/hardware) +and [reference firmware](https://github.com/Xinyuan-LilyGO/T3-STM32/tree/master/examples/6_SubGHz_TXRX). + +## MVP validation and limitations + +Hardware checks covered OLED startup, USB companion communication, advertisement +reception, Public message transmission, and matching repeater trace replies at +20 dBm. Public packets were captured and decrypted independently. Some repeater +pings timed out; long-term reliability has not been established. Higher transmit +powers are outside the validated MVP setting. + +The repeater builds successfully; forwarding has not been hardware-tested. +Battery telemetry, SD storage, and low-power optimization are not implemented. diff --git a/variants/lilygo_t3_stm32/STM32ArduinoCompat.h b/variants/lilygo_t3_stm32/STM32ArduinoCompat.h new file mode 100644 index 00000000..4c705c20 --- /dev/null +++ b/variants/lilygo_t3_stm32/STM32ArduinoCompat.h @@ -0,0 +1,11 @@ +#pragma once + +#ifdef __cplusplus + // Include the device headers first so subsequent Arduino includes cannot + // reintroduce the peripheral macro. It conflicts with both mesh::RNG and + // Crypto's global RNG object. Leave C HAL sources' register macros intact. + #include <Arduino.h> + #ifdef RNG + #undef RNG + #endif +#endif diff --git a/variants/lilygo_t3_stm32/platformio.ini b/variants/lilygo_t3_stm32/platformio.ini new file mode 100644 index 00000000..ba56cf52 --- /dev/null +++ b/variants/lilygo_t3_stm32/platformio.ini @@ -0,0 +1,52 @@ +[lilygo_t3_stm32] +extends = stm32_base +board = lilygo_t3_stm32 +board_upload.maximum_size = 229376 ; final 32 KiB reserved for InternalFS +build_flags = ${stm32_base.build_flags} + -include variants/lilygo_t3_stm32/STM32ArduinoCompat.h + -I variants/lilygo_t3_stm32 + -D RADIO_CLASS=CustomSTM32WLx + -D WRAPPER_CLASS=CustomSTM32WLxWrapper + -D LORA_TX_POWER=20 + -D SX126X_CURRENT_LIMIT=140 + -D RX_BOOSTED_GAIN=true + -D STM32WL_TCXO_VOLTAGE=0 ; crystal oscillator; manufacturer sets IS_TCXO_SUPPORTED=0 + -D PIN_SERIAL_TX=PA9 + -D PIN_SERIAL_RX=PA10 + -D SERIAL_UART_INSTANCE=1 + -D PIN_SPI_SCK=PA5 + -D PIN_SPI_MISO=PA6 + -D PIN_SPI_MOSI=PA7 + -D PIN_OLED_CS=PB12 + -D PIN_OLED_DC=PA8 + -D PIN_OLED_RESET=-1 + -D PIN_USER_BTN=PH3 + -D USER_BTN_PRESSED=HIGH + -D DISPLAY_CLASS=SSD1306Display +build_src_filter = ${stm32_base.build_src_filter} + +<../variants/lilygo_t3_stm32> + +<helpers/ui/SSD1306Display.cpp> +lib_deps = ${stm32_base.lib_deps} + adafruit/Adafruit SSD1306 @ ^2.5.13 + +[env:LilyGo_T3_STM32_repeater] +extends = lilygo_t3_stm32 +build_flags = ${lilygo_t3_stm32.build_flags} + -D ADVERT_NAME='"T3 STM32 Repeater"' + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=50 +build_src_filter = ${lilygo_t3_stm32.build_src_filter} + +<../examples/simple_repeater/*.cpp> + +[env:LilyGo_T3_STM32_companion_radio_usb] +extends = lilygo_t3_stm32 +build_flags = ${lilygo_t3_stm32.build_flags} + -I examples/companion_radio/ui-orig + -D MAX_CONTACTS=100 + -D MAX_GROUP_CHANNELS=8 + -D ENABLE_USB_INTERFACE +build_src_filter = ${lilygo_t3_stm32.build_src_filter} + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-orig/*.cpp> +lib_deps = ${lilygo_t3_stm32.lib_deps} + densaugeo/base64 @ ~1.4.0 diff --git a/variants/lilygo_t3_stm32/target.cpp b/variants/lilygo_t3_stm32/target.cpp new file mode 100644 index 00000000..f98783fe --- /dev/null +++ b/variants/lilygo_t3_stm32/target.cpp @@ -0,0 +1,82 @@ +#include <Arduino.h> +#include <SPI.h> +#include "target.h" + +LilyGoT3STM32Board board; +RADIO_CLASS radio = new STM32WLx_Module(); +WRAPPER_CLASS radio_driver(radio, board); +VolatileRTCClock rtc_clock; +SensorManager sensors; +DISPLAY_CLASS display; +// PH3 is also BOOT0: the board's button is active high with an external pull-down. +MomentaryButton user_btn(PIN_USER_BTN, 1000, false); + +static const uint32_t rfswitch_pins[] = { + PB2, PB6, RADIOLIB_NC, RADIOLIB_NC, RADIOLIB_NC +}; +static const Module::RfSwitchMode_t rfswitch_table[] = { + {STM32WLx::MODE_IDLE, {LOW, LOW}}, + {STM32WLx::MODE_RX, {HIGH, LOW}}, + {STM32WLx::MODE_TX_HP, {LOW, HIGH}}, + END_OF_MODE_TABLE, +}; + +void LilyGoT3STM32Board::begin() { + STM32Board::begin(); + + // The SD card shares SPI1 with the OLED; keep it deselected. + digitalWrite(PA4, HIGH); + pinMode(PA4, OUTPUT); + digitalWrite(PIN_OLED_CS, HIGH); + pinMode(PIN_OLED_CS, OUTPUT); + pinMode(PIN_USER_BTN, INPUT); + // Both onboard LEDs are active high. Leave them off until explicitly needed. + digitalWrite(PA0, LOW); + pinMode(PA0, OUTPUT); + digitalWrite(PA1, LOW); + pinMode(PA1, OUTPUT); + + SPI.setSCLK(PIN_SPI_SCK); + SPI.setMISO(PIN_SPI_MISO); + SPI.setMOSI(PIN_SPI_MOSI); + SPI.begin(); + delay(200); // OLED power-on settling time used by the manufacturer's example. +} + +#ifndef LORA_CR + #define LORA_CR 5 +#endif + +static bool check_radio_status(int status, const char* stage) { + if (status == RADIOLIB_ERR_NONE) return true; + + Serial.print("ERROR: "); + Serial.print(stage); + Serial.print(": "); + Serial.println(status); + return false; +} + +bool radio_init() { + radio.setRfSwitchTable(rfswitch_pins, rfswitch_table); + int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, + RADIOLIB_SX126X_SYNC_WORD_PRIVATE, LORA_TX_POWER, + 16, STM32WL_TCXO_VOLTAGE, 0); + if (!check_radio_status(status, "radio.begin")) return false; + + // Match the manufacturer's 3.3 V power-LDO trim (REG_DRV_CTRL). + const uint8_t power_ldo_3v3 = 0x0E; + status = radio.writeRegister(0x091F, &power_ldo_3v3, 1); + if (!check_radio_status(status, "power LDO trim")) return false; + + status = radio.setCurrentLimit(SX126X_CURRENT_LIMIT); + if (!check_radio_status(status, "current limit")) return false; + status = radio.setRxBoostedGainMode(RX_BOOSTED_GAIN); + if (!check_radio_status(status, "RX gain")) return false; + return check_radio_status(radio.setCRC(1), "CRC"); +} + +mesh::LocalIdentity radio_new_identity() { + RadioNoiseListener rng(radio); + return mesh::LocalIdentity(&rng); +} diff --git a/variants/lilygo_t3_stm32/target.h b/variants/lilygo_t3_stm32/target.h new file mode 100644 index 00000000..83235cbd --- /dev/null +++ b/variants/lilygo_t3_stm32/target.h @@ -0,0 +1,28 @@ +#pragma once + +#include <RadioLib.h> +#include <helpers/stm32/STM32Board.h> +#include <helpers/radiolib/CustomSTM32WLxWrapper.h> +#include <helpers/ArduinoHelpers.h> +#include <helpers/SensorManager.h> +#include <helpers/ui/SSD1306Display.h> +#include <helpers/ui/MomentaryButton.h> + +class LilyGoT3STM32Board : public STM32Board { +public: + void begin() override; + + const char* getManufacturerName() const override { + return "LilyGO T3 STM32"; + } +}; + +extern LilyGoT3STM32Board board; +extern WRAPPER_CLASS radio_driver; +extern VolatileRTCClock rtc_clock; +extern SensorManager sensors; +extern DISPLAY_CLASS display; +extern MomentaryButton user_btn; + +bool radio_init(); +mesh::LocalIdentity radio_new_identity(); From 75ea17ea46be98e40fda8a99b64d9d2cd2fc8cfe Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Wed, 21 Oct 2026 15:41:11 +1300 Subject: [PATCH 305/381] implement new auto detect display for sh1106 and ssd1306 --- src/helpers/ui/AutoDetectDisplay.cpp | 45 ++++++++++++++++++++++++++++ src/helpers/ui/AutoDetectDisplay.h | 32 ++++++++++++++++++++ src/helpers/ui/SH1106Display.cpp | 18 +++++------ variants/rak4631/platformio.ini | 23 +++++++------- variants/rak4631/target.h | 2 +- 5 files changed, 100 insertions(+), 20 deletions(-) create mode 100644 src/helpers/ui/AutoDetectDisplay.cpp create mode 100644 src/helpers/ui/AutoDetectDisplay.h diff --git a/src/helpers/ui/AutoDetectDisplay.cpp b/src/helpers/ui/AutoDetectDisplay.cpp new file mode 100644 index 00000000..e3537ab2 --- /dev/null +++ b/src/helpers/ui/AutoDetectDisplay.cpp @@ -0,0 +1,45 @@ +#include "AutoDetectDisplay.h" +#include <MeshCore.h> + +int AutoDetectDisplay::getDisplayStatus(TwoWire& wire, uint8_t addr) { + int status = -1; + for(int i = 0; i < 4; i++){ + + // request display status + wire.beginTransmission(addr); + wire.write((uint8_t)0x00); + + // ensure response received + if (wire.endTransmission() != 0) return -1; // expect success + if (wire.requestFrom((int)addr, 1) == 0) return -1; // expect at least 1 byte + + // ensure two consecutive reads are the same + int previous = status; + status = wire.read() & 0x0F; + if(status == previous){ + break; + } + + } + return status; +} + +bool AutoDetectDisplay::begin() { + + // request status from display address + int status = getDisplayStatus(Wire, DISPLAY_ADDRESS); + MESH_DEBUG_PRINTLN("AutoDetectDisplay: status=0x%02X", status); + + // detect SH1106 + if(status == 0x00 || status == 0x08){ + MESH_DEBUG_PRINTLN("AutoDetectDisplay: SH1106 detected"); + _impl = &_sh1106; + return _sh1106.begin(); + } + + // fallback to SSD1306 + MESH_DEBUG_PRINTLN("AutoDetectDisplay: falling back to SSD1306"); + _impl = &_ssd1306; + return _ssd1306.begin(); + +} diff --git a/src/helpers/ui/AutoDetectDisplay.h b/src/helpers/ui/AutoDetectDisplay.h new file mode 100644 index 00000000..7208d4f5 --- /dev/null +++ b/src/helpers/ui/AutoDetectDisplay.h @@ -0,0 +1,32 @@ +#pragma once + +#include "DisplayDriver.h" +#include "SSD1306Display.h" +#include "SH1106Display.h" + +// Auto detects SH1106 display at runtime, otherwise falls back to using SSD1306 +class AutoDetectDisplay : public DisplayDriver { + DisplayDriver* _impl; + SSD1306Display _ssd1306; + SH1106Display _sh1106; + + int getDisplayStatus(TwoWire& wire, uint8_t addr); +public: + AutoDetectDisplay() : DisplayDriver(128, 64), _impl(&_ssd1306) { } + bool begin(); + + bool isOn() override { return _impl->isOn(); } + void turnOn() override { _impl->turnOn(); } + void turnOff() override { _impl->turnOff(); } + void clear() override { _impl->clear(); } + void startFrame(ColorVal bkg = UIColor::window_bkg) override { _impl->startFrame(bkg); } + void setTextSize(int sz) override { _impl->setTextSize(sz); } + void setColor(ColorVal c) override { _impl->setColor(c); } + void setCursor(int x, int y) override { _impl->setCursor(x, y); } + void print(const char* str) override { _impl->print(str); } + void fillRect(int x, int y, int w, int h) override { _impl->fillRect(x, y, w, h); } + void drawRect(int x, int y, int w, int h) override { _impl->drawRect(x, y, w, h); } + void drawXbm(int x, int y, const uint8_t* bits, int w, int h) override { _impl->drawXbm(x, y, bits, w, h); } + uint16_t getTextWidth(const char* str) override { return _impl->getTextWidth(str); } + void endFrame() override { _impl->endFrame(); } +}; diff --git a/src/helpers/ui/SH1106Display.cpp b/src/helpers/ui/SH1106Display.cpp index 8b91d857..e290b355 100644 --- a/src/helpers/ui/SH1106Display.cpp +++ b/src/helpers/ui/SH1106Display.cpp @@ -10,15 +10,15 @@ bool SH1106Display::i2c_probe(TwoWire &wire, uint8_t addr) } // Color scheme -ColorVal UIColor::window_bkg = SH110X_BLACK; -ColorVal UIColor::title_bkg = SH110X_BLACK; -ColorVal UIColor::title_txt = SH110X_WHITE; -ColorVal UIColor::primary_txt = SH110X_WHITE; -ColorVal UIColor::secondary_txt = SH110X_WHITE; -ColorVal UIColor::warning_txt = SH110X_WHITE; -ColorVal UIColor::popup_bkg = SH110X_BLACK; -ColorVal UIColor::popup_txt = SH110X_WHITE; -ColorVal UIColor::corp_blue = SH110X_WHITE; +__attribute__((weak)) ColorVal UIColor::window_bkg = SH110X_BLACK; +__attribute__((weak)) ColorVal UIColor::title_bkg = SH110X_BLACK; +__attribute__((weak)) ColorVal UIColor::title_txt = SH110X_WHITE; +__attribute__((weak)) ColorVal UIColor::primary_txt = SH110X_WHITE; +__attribute__((weak)) ColorVal UIColor::secondary_txt = SH110X_WHITE; +__attribute__((weak)) ColorVal UIColor::warning_txt = SH110X_WHITE; +__attribute__((weak)) ColorVal UIColor::popup_bkg = SH110X_BLACK; +__attribute__((weak)) ColorVal UIColor::popup_txt = SH110X_WHITE; +__attribute__((weak)) ColorVal UIColor::corp_blue = SH110X_WHITE; bool SH1106Display::begin() { diff --git a/variants/rak4631/platformio.ini b/variants/rak4631/platformio.ini index d2781d9f..4c13b0d7 100644 --- a/variants/rak4631/platformio.ini +++ b/variants/rak4631/platformio.ini @@ -28,11 +28,14 @@ build_src_filter = ${nrf52_base.build_src_filter} +<../variants/rak4631> +<helpers/sensors> +<helpers/ui/SSD1306Display.cpp> + +<helpers/ui/SH1106Display.cpp> + +<helpers/ui/AutoDetectDisplay.cpp> +<helpers/ui/MomentaryButton.cpp> lib_deps = ${nrf52_base.lib_deps} ${sensor_base.lib_deps} adafruit/Adafruit SSD1306 @ ^2.5.13 + adafruit/Adafruit SH110X @ ^2.1.13 sparkfun/SparkFun u-blox GNSS Arduino Library@^2.2.27 boschsensortec/BSEC Software Library @ ^1.8.1492 @@ -40,7 +43,7 @@ lib_deps = extends = rak4631 build_flags = ${rak4631.build_flags} - -D DISPLAY_CLASS=SSD1306Display + -D DISPLAY_CLASS=AutoDetectDisplay -D ADVERT_NAME='"RAK4631 Repeater"' -D ADVERT_LAT=0.0 -D ADVERT_LON=0.0 @@ -56,7 +59,7 @@ build_src_filter = ${rak4631.build_src_filter} extends = rak4631 build_flags = ${rak4631.build_flags} - -D DISPLAY_CLASS=SSD1306Display + -D DISPLAY_CLASS=AutoDetectDisplay -D ADVERT_NAME='"RAK4631 Repeater"' -D ADVERT_LAT=0.0 -D ADVERT_LON=0.0 @@ -75,7 +78,7 @@ lib_deps = extends = rak4631 build_flags = ${rak4631.build_flags} - -D DISPLAY_CLASS=SSD1306Display + -D DISPLAY_CLASS=AutoDetectDisplay -D ADVERT_NAME='"RS232 Bridge"' -D ADVERT_LAT=0.0 -D ADVERT_LON=0.0 @@ -98,7 +101,7 @@ build_src_filter = ${rak4631.build_src_filter} extends = rak4631 build_flags = ${rak4631.build_flags} - -D DISPLAY_CLASS=SSD1306Display + -D DISPLAY_CLASS=AutoDetectDisplay -D ADVERT_NAME='"RS232 Bridge"' -D ADVERT_LAT=0.0 -D ADVERT_LON=0.0 @@ -121,7 +124,7 @@ build_src_filter = ${rak4631.build_src_filter} extends = rak4631 build_flags = ${rak4631.build_flags} - -D DISPLAY_CLASS=SSD1306Display + -D DISPLAY_CLASS=AutoDetectDisplay -D ADVERT_NAME='"Test Room"' -D ADVERT_LAT=0.0 -D ADVERT_LON=0.0 @@ -137,7 +140,7 @@ build_src_filter = ${rak4631.build_src_filter} extends = rak4631 build_flags = ${rak4631.build_flags} - -D DISPLAY_CLASS=SSD1306Display + -D DISPLAY_CLASS=AutoDetectDisplay -D ADVERT_NAME='"RAK4631 Room Server"' -D ADVERT_LAT=0.0 -D ADVERT_LON=0.0 @@ -161,7 +164,7 @@ build_flags = -I examples/companion_radio/ui-new -D PIN_USER_BTN=9 -D PIN_USER_BTN_ANA=31 - -D DISPLAY_CLASS=SSD1306Display + -D DISPLAY_CLASS=AutoDetectDisplay -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D ENABLE_USB_INTERFACE @@ -186,7 +189,7 @@ build_flags = -I examples/companion_radio/ui-new -D PIN_USER_BTN=9 -D PIN_USER_BTN_ANA=31 - -D DISPLAY_CLASS=SSD1306Display + -D DISPLAY_CLASS=AutoDetectDisplay -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D ETHERNET_ENABLED=1 @@ -215,7 +218,7 @@ build_flags = -I examples/companion_radio/ui-new -D PIN_USER_BTN=9 -D PIN_USER_BTN_ANA=31 - -D DISPLAY_CLASS=SSD1306Display + -D DISPLAY_CLASS=AutoDetectDisplay -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D BLE_PIN_CODE=123456 @@ -251,7 +254,7 @@ lib_deps = extends = rak4631 build_flags = ${rak4631.build_flags} - -D DISPLAY_CLASS=SSD1306Display + -D DISPLAY_CLASS=AutoDetectDisplay -D ADVERT_NAME='"RAK4631 Sensor"' -D ADVERT_LAT=0.0 -D ADVERT_LON=0.0 diff --git a/variants/rak4631/target.h b/variants/rak4631/target.h index 1529f904..c04cd4e4 100644 --- a/variants/rak4631/target.h +++ b/variants/rak4631/target.h @@ -9,7 +9,7 @@ #include <helpers/sensors/EnvironmentSensorManager.h> #ifdef DISPLAY_CLASS - #include <helpers/ui/SSD1306Display.h> + #include <helpers/ui/AutoDetectDisplay.h> extern DISPLAY_CLASS display; #include <helpers/ui/MomentaryButton.h> extern MomentaryButton user_btn; From 8c4769d1ed7ccd8690eb228d732150b9a3fb1c5f Mon Sep 17 00:00:00 2001 From: Confituurke <9595028+Confituurke@users.noreply.github.com> Date: Wed, 21 Oct 2026 11:24:34 +0200 Subject: [PATCH 306/381] Use two decimals only for exact quarter-hour offsets --- examples/companion_radio/MyMesh.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 2ea539db..cc6340bb 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2192,7 +2192,8 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* } if (strcmp(command, "get tz.offset") == 0) { - sprintf(reply, ((int)(_prefs.tz_offset * 4) % 2) ? "> %.2f" : "> %.1f", _prefs.tz_offset); + float q = _prefs.tz_offset * 4; + sprintf(reply, (q == (int)q && ((int)q & 1)) ? "> %.2f" : "> %.1f", _prefs.tz_offset); return true; } if (memcmp(command, "set tz.offset ", 14) == 0) { From d1d06b92ab6b8879e0eed909df237bb224136ae3 Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Wed, 21 Oct 2026 14:08:56 -0400 Subject: [PATCH 307/381] refactoring eink devices behaviour --- examples/companion_radio/ui-new/UITask.cpp | 44 ++++++++++++++++------ examples/companion_radio/ui-new/UITask.h | 3 +- src/helpers/ui/DisplayDriver.h | 1 + src/helpers/ui/GxEPDDisplay.cpp | 6 ++- src/helpers/ui/GxEPDDisplay.h | 1 + variants/lilygo_techo/platformio.ini | 8 ++-- variants/lilygo_techo/target.cpp | 1 + variants/lilygo_techo/target.h | 1 + variants/thinknode_m1/platformio.ini | 7 ++++ variants/thinknode_m1/target.cpp | 1 + variants/thinknode_m1/target.h | 1 + variants/thinknode_m5/platformio.ini | 7 +++- variants/thinknode_m5/target.cpp | 1 + variants/thinknode_m5/target.h | 1 + variants/thinknode_m8/platformio.ini | 11 +++--- variants/thinknode_m8/target.cpp | 1 + variants/thinknode_m8/target.h | 1 + 17 files changed, 71 insertions(+), 25 deletions(-) diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index d48647b3..de9e8f58 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -197,11 +197,10 @@ class HomeScreen : public UIScreen { sensors_nb ++; } sensors_scroll = sensors_nb > UI_RECENT_LIST_SIZE; -#if AUTO_OFF_MILLIS > 0 - next_sensors_refresh = millis() + 5000; // refresh sensor values every 5 sec -#else - next_sensors_refresh = millis() + 60000; // refresh sensor values every 1 min -#endif + if (display.isEink()) // preserve eink displays + next_sensors_refresh = millis() + 60000; // refresh sensor values every 1 min + else + next_sensors_refresh = millis() + 5000; // refresh sensor values every 5 sec } } @@ -703,11 +702,7 @@ public: display.translateUTF8ToBlocks(filtered_msg, p->msg, sizeof(filtered_msg)); display.printWordWrap(filtered_msg, display.width()); -#if AUTO_OFF_MILLIS==0 // probably e-ink - return 10000; // 10 s -#else - return 1000; // next render after 1000 ms -#endif + return display.isEink() ? 10000 : 1000; // 10 s for eink } bool handleInput(char c) override { @@ -739,6 +734,9 @@ void UITask::begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* no #if defined(PIN_USER_BTN_ANA) analog_btn.begin(); #endif +#if defined(BACKLIGHT_BTN) + backlight_btn.begin(); +#endif _node_prefs = node_prefs; @@ -1002,13 +1000,30 @@ void UITask::loop() { #endif #if defined(BACKLIGHT_BTN) if (millis() > next_backlight_btn_check) { - bool touch_state = digitalRead(PIN_BUTTON2); + if (backlight_btn.isPressed()) { + if (!_display->isOn()) { + _display->turnOn(); + _next_refresh = 0; + } + _auto_off = millis() + AUTO_OFF_MILLIS; // extend auto-off timer + backlight_btn_pressed_at = millis(); // still pressed + } + bool touch_state = (millis() - backlight_btn_pressed_at > 5000); + // Backlight button events + int bev = backlight_btn.check(); + if (bev == BUTTON_EVENT_DOUBLE_CLICK) { + _display->forceFullRefresh(); + } else if (bev == BUTTON_EVENT_TRIPLE_CLICK) { + _display->blankScreen(); + _display->turnOff(); + backlight_btn_pressed_at = 0; + } #if defined(DISP_BACKLIGHT) digitalWrite(DISP_BACKLIGHT, !touch_state); #elif defined(EXP_PIN_BACKLIGHT) expander.digitalWrite(EXP_PIN_BACKLIGHT, !touch_state); #endif - next_backlight_btn_check = millis() + 300; + next_backlight_btn_check = millis() + 100; } #endif @@ -1056,6 +1071,11 @@ void UITask::loop() { } #endif if (millis() > _auto_off) { + #ifdef EINK_SCREENOFF_BLANK + if (curr != msg_preview) { // don't blank if messages are waiting + display.blankScreen(); + } + #endif _display->turnOff(); } #endif diff --git a/examples/companion_radio/ui-new/UITask.h b/examples/companion_radio/ui-new/UITask.h index 361b04d0..4d44bfe1 100644 --- a/examples/companion_radio/ui-new/UITask.h +++ b/examples/companion_radio/ui-new/UITask.h @@ -61,7 +61,8 @@ class UITask : public AbstractUITask { unsigned long _alert_expiry; int _msgcount; unsigned long ui_started_at, next_batt_chck; - int next_backlight_btn_check = 0; + unsigned long next_backlight_btn_check = 0; + unsigned long backlight_btn_pressed_at = 0; #ifdef PIN_STATUS_LED int led_state = 0; int next_led_change = 0; diff --git a/src/helpers/ui/DisplayDriver.h b/src/helpers/ui/DisplayDriver.h index 3e9e2dde..cbef3f98 100644 --- a/src/helpers/ui/DisplayDriver.h +++ b/src/helpers/ui/DisplayDriver.h @@ -27,6 +27,7 @@ public: virtual void turnOn() = 0; virtual void turnOff() = 0; virtual void clear() = 0; + virtual void blankScreen() {} // to cleanly erase screen before turning off virtual void startFrame(ColorVal bkg = UIColor::window_bkg) = 0; virtual void setTextSize(int sz) = 0; virtual void setColor(ColorVal c) = 0; diff --git a/src/helpers/ui/GxEPDDisplay.cpp b/src/helpers/ui/GxEPDDisplay.cpp index 332157eb..21b00afc 100644 --- a/src/helpers/ui/GxEPDDisplay.cpp +++ b/src/helpers/ui/GxEPDDisplay.cpp @@ -82,13 +82,17 @@ void GxEPDDisplay::turnOff() { expander.digitalWrite(EXP_PIN_BACKLIGHT, LOW); #endif _isOn = false; + last_display_crc_value=0; + display.hibernate(); +} + +void GxEPDDisplay::blankScreen() { // do full refresh before powering off to clear screen // no full refresh needed at wakeup display.clearScreen(0xFF); // Clears microcontroller side RAM display.writeScreenBuffer(0xFF); // Forces 0xFF (White) into the display controller's history registers resetPartialRefreshCounter(); last_display_crc_value=0; - display.hibernate(); } void GxEPDDisplay::clear() { diff --git a/src/helpers/ui/GxEPDDisplay.h b/src/helpers/ui/GxEPDDisplay.h index 8a37b72c..99b25d15 100644 --- a/src/helpers/ui/GxEPDDisplay.h +++ b/src/helpers/ui/GxEPDDisplay.h @@ -61,6 +61,7 @@ public: void turnOn() override; void turnOff() override; void clear() override; + void blankScreen() override; void startFrame(ColorVal bkg = UIColor::window_bkg) override; void setTextSize(int sz) override; void setColor(ColorVal c) override; diff --git a/variants/lilygo_techo/platformio.ini b/variants/lilygo_techo/platformio.ini index 81da2e48..14040622 100644 --- a/variants/lilygo_techo/platformio.ini +++ b/variants/lilygo_techo/platformio.ini @@ -32,8 +32,12 @@ build_flags = ${nrf52_base.build_flags} -D PIN_GPS_RESET_ACTIVE=LOW -D TELEM_BME280_ADDRESS=0x77 -D DISPLAY_CLASS=GxEPDDisplay + -D EINK_SCREENOFF_BLANK + -D UI_RECENT_LIST_SIZE=9 + -D UI_MSG_PREVIEW_SIZE=165 + -D EINK_MAX_PARTIAL_REFRESH=60 + -D AUTO_OFF_MILLIS=1800000 -D BACKLIGHT_BTN=PIN_BUTTON2 - -D AUTO_OFF_MILLIS=0 build_src_filter = ${nrf52_base.build_src_filter} +<helpers/*.cpp> +<TechoBoard.cpp> @@ -91,7 +95,6 @@ build_flags = -D BLE_PIN_CODE=123456 ; -D BLE_DEBUG_LOGGING=1 -D OFFLINE_QUEUE_SIZE=256 - -D UI_RECENT_LIST_SIZE=9 -D UI_SENSORS_PAGE=1 -D UI_GPS_PAGE=1 ; -D MESH_PACKET_LOGGING=1 @@ -116,7 +119,6 @@ build_flags = -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 - -D UI_RECENT_LIST_SIZE=9 -D UI_SENSORS_PAGE=1 -D AUTO_SHUTDOWN_MILLIVOLTS=3300 -D QSPIFLASH=1 diff --git a/variants/lilygo_techo/target.cpp b/variants/lilygo_techo/target.cpp index 278fc76d..12b40d7e 100644 --- a/variants/lilygo_techo/target.cpp +++ b/variants/lilygo_techo/target.cpp @@ -23,6 +23,7 @@ EnvironmentSensorManager sensors = EnvironmentSensorManager(); #ifdef DISPLAY_CLASS DISPLAY_CLASS display; MomentaryButton user_btn(PIN_USER_BTN, 1000, true); + MomentaryButton backlight_btn(BACKLIGHT_BTN, 1000, true); #endif bool radio_init() { diff --git a/variants/lilygo_techo/target.h b/variants/lilygo_techo/target.h index 2b8a1783..a1668f03 100644 --- a/variants/lilygo_techo/target.h +++ b/variants/lilygo_techo/target.h @@ -22,6 +22,7 @@ extern EnvironmentSensorManager sensors; #ifdef DISPLAY_CLASS extern DISPLAY_CLASS display; extern MomentaryButton user_btn; + extern MomentaryButton backlight_btn; #endif bool radio_init(); diff --git a/variants/thinknode_m1/platformio.ini b/variants/thinknode_m1/platformio.ini index 89c48403..2e1aa48f 100644 --- a/variants/thinknode_m1/platformio.ini +++ b/variants/thinknode_m1/platformio.ini @@ -24,6 +24,13 @@ build_flags = ${nrf52_base.build_flags} -D SX126X_RX_BOOSTED_GAIN=1 -D LORA_TX_POWER=22 -D P_LORA_TX_LED=13 + -D UI_RECENT_LIST_SIZE=9 + -D UI_MSG_PREVIEW_SIZE=165 + -D EINK_MAX_PARTIAL_REFRESH=60 + -D BACKLIGHT_BTN=PIN_BUTTON2 + -D AUTO_OFF_MILLIS=1800000 + -D UI_NO_HIBERNATE + -D DISABLE_DIAGNOSTIC_OUTPUT build_src_filter = ${nrf52_base.build_src_filter} +<helpers/*.cpp> +<ThinkNodeM1Board.cpp> diff --git a/variants/thinknode_m1/target.cpp b/variants/thinknode_m1/target.cpp index 69306fc0..c430cee0 100644 --- a/variants/thinknode_m1/target.cpp +++ b/variants/thinknode_m1/target.cpp @@ -17,6 +17,7 @@ ThinkNodeM1SensorManager sensors = ThinkNodeM1SensorManager(nmea); #ifdef DISPLAY_CLASS DISPLAY_CLASS display; MomentaryButton user_btn(PIN_USER_BTN, 1000, true); + MomentaryButton backlight_btn(BACKLIGHT_BTN, 1000, true); #endif bool radio_init() { diff --git a/variants/thinknode_m1/target.h b/variants/thinknode_m1/target.h index ec1297be..d2d6aed1 100644 --- a/variants/thinknode_m1/target.h +++ b/variants/thinknode_m1/target.h @@ -40,6 +40,7 @@ extern ThinkNodeM1SensorManager sensors; #ifdef DISPLAY_CLASS extern DISPLAY_CLASS display; extern MomentaryButton user_btn; + extern MomentaryButton backlight_btn; #endif bool radio_init(); diff --git a/variants/thinknode_m5/platformio.ini b/variants/thinknode_m5/platformio.ini index a3f348b3..ed187dd2 100644 --- a/variants/thinknode_m5/platformio.ini +++ b/variants/thinknode_m5/platformio.ini @@ -26,8 +26,12 @@ build_flags = ${esp32_base.build_flags} -D EINK_SCALE_Y=1.5625f -D EINK_X_OFFSET=0 -D EINK_Y_OFFSET=10 + -D UI_RECENT_LIST_SIZE=9 + -D UI_MSG_PREVIEW_SIZE=165 + -D EINK_MAX_PARTIAL_REFRESH=60 -D BACKLIGHT_BTN=PIN_BUTTON2 - -D AUTO_OFF_MILLIS=0 + -D AUTO_OFF_MILLIS=1800000 + -D UI_NO_HIBERNATE -D DISABLE_DIAGNOSTIC_OUTPUT -D SX126X_DIO2_AS_RF_SWITCH=true -D SX126X_DIO3_TCXO_VOLTAGE=3.3 @@ -150,7 +154,6 @@ build_flags = -D MAX_GROUP_CHANNELS=40 -D BLE_PIN_CODE=123456 -D OFFLINE_QUEUE_SIZE=256 - -D UI_RECENT_LIST_SIZE=9 ; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 ; -D GPS_NMEA_DEBUG diff --git a/variants/thinknode_m5/target.cpp b/variants/thinknode_m5/target.cpp index be534f67..ec524df7 100644 --- a/variants/thinknode_m5/target.cpp +++ b/variants/thinknode_m5/target.cpp @@ -26,6 +26,7 @@ EnvironmentSensorManager sensors = EnvironmentSensorManager(); #ifdef DISPLAY_CLASS DISPLAY_CLASS display; MomentaryButton user_btn(PIN_USER_BTN, 1000, true); + MomentaryButton backlight_btn(BACKLIGHT_BTN, 1000, true); #endif bool radio_init() { diff --git a/variants/thinknode_m5/target.h b/variants/thinknode_m5/target.h index a613e390..7cce1edb 100644 --- a/variants/thinknode_m5/target.h +++ b/variants/thinknode_m5/target.h @@ -24,6 +24,7 @@ extern PCA9557 expander; #ifdef DISPLAY_CLASS extern DISPLAY_CLASS display; extern MomentaryButton user_btn; + extern MomentaryButton backlight_btn; #endif bool radio_init(); diff --git a/variants/thinknode_m8/platformio.ini b/variants/thinknode_m8/platformio.ini index db19e446..2c07038f 100644 --- a/variants/thinknode_m8/platformio.ini +++ b/variants/thinknode_m8/platformio.ini @@ -18,12 +18,16 @@ build_flags = ${nrf52_base.build_flags} -D P_LORA_SCLK=19 -D P_LORA_MISO=22 -D P_LORA_MOSI=20 - -D UI_SHOW_CLOCK=1 + -D DISPLAY_ROTATION=4 -D UI_HAS_ROTARY_INPUT=1 -D UI_HAS_NAV_INPUT=1 -D UI_RECENT_LIST_SIZE=9 -D UI_MSG_PREVIEW_SIZE=165 -D EINK_MAX_PARTIAL_REFRESH=60 + -D AUTO_OFF_MILLIS=1800000 + -D BACKLIGHT_BTN=PIN_BUTTON2 + -D UI_SHOW_CLOCK=1 + -D EINK_SCREENOFF_BLANK -D EINK_DISPLAY_MODEL=GxEPD2_154_D67 ; -D EINK_DISPLAY_MODEL=GxEPD2_154_GDEY0154D67 ; -D EINK_DISPLAY_MODEL=GxEPD2_150_BN @@ -92,10 +96,7 @@ build_flags = -D MAX_GROUP_CHANNELS=40 -D BLE_PIN_CODE=123456 # -D BLE_DEBUG_LOGGING=1 - -D DISPLAY_ROTATION=4 -D DISPLAY_CLASS=GxEPDDisplay - -D BACKLIGHT_BTN=PIN_BUTTON2 - -D AUTO_OFF_MILLIS=0 -D OFFLINE_QUEUE_SIZE=256 -D PIN_BUZZER=33 -D AUTO_SHUTDOWN_MILLIVOLTS=3300 @@ -133,8 +134,6 @@ build_flags = -D DISPLAY_ROTATION=4 -D QSPIFLASH=1 -D DISPLAY_CLASS=GxEPDDisplay - -D BACKLIGHT_BTN=PIN_BUTTON2 - -D AUTO_OFF_MILLIS=0 -D OFFLINE_QUEUE_SIZE=256 -D PIN_BUZZER=6 -D AUTO_SHUTDOWN_MILLIVOLTS=3300 diff --git a/variants/thinknode_m8/target.cpp b/variants/thinknode_m8/target.cpp index ac4ac100..69f3cc52 100644 --- a/variants/thinknode_m8/target.cpp +++ b/variants/thinknode_m8/target.cpp @@ -23,6 +23,7 @@ EnvironmentSensorManager sensors = EnvironmentSensorManager(); DISPLAY_CLASS display; MomentaryButton user_btn(PIN_USER_BTN, 1000, true); RotaryInputGPIO rotary_input(PIN_BUTTON1_A, PIN_BUTTON1_B); + MomentaryButton backlight_btn(BACKLIGHT_BTN, 1000, true); #endif bool radio_init() { diff --git a/variants/thinknode_m8/target.h b/variants/thinknode_m8/target.h index c3402a01..39928506 100644 --- a/variants/thinknode_m8/target.h +++ b/variants/thinknode_m8/target.h @@ -23,6 +23,7 @@ extern EnvironmentSensorManager sensors; #ifdef DISPLAY_CLASS extern DISPLAY_CLASS display; extern MomentaryButton user_btn; + extern MomentaryButton backlight_btn; extern RotaryInputGPIO rotary_input; #endif From afbab2de1652f35dca0aa010db3d7f3925de2f66 Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Wed, 21 Oct 2026 17:13:27 -0400 Subject: [PATCH 308/381] DisplayDriver: fixing alignment issue in vtable for nrf52 and epd display --- examples/companion_radio/ui-new/UITask.cpp | 6 +++++- src/helpers/ui/DisplayDriver.h | 3 ++- src/helpers/ui/GxEPDDisplay.cpp | 7 +++++-- src/helpers/ui/GxEPDDisplay.h | 3 ++- variants/lilygo_techo/platformio.ini | 2 +- variants/thinknode_m1/platformio.ini | 2 +- variants/thinknode_m5/platformio.ini | 2 +- variants/thinknode_m8/platformio.ini | 2 +- 8 files changed, 18 insertions(+), 9 deletions(-) diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index de9e8f58..6e987f87 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -955,7 +955,9 @@ void UITask::loop() { if (ev == BUTTON_EVENT_CLICK) { c = checkDisplayOn(KEY_ENTER); } else if (ev == BUTTON_EVENT_LONG_PRESS) { + display.blankScreen(); display.turnOff(); + display.powerOff(); } else if (ev == BUTTON_EVENT_DOUBLE_CLICK) { c = handleDoubleClick(KEY_SELECT); } else if (ev == BUTTON_EVENT_TRIPLE_CLICK) { @@ -1016,6 +1018,7 @@ void UITask::loop() { } else if (bev == BUTTON_EVENT_TRIPLE_CLICK) { _display->blankScreen(); _display->turnOff(); + _display->powerOff(); backlight_btn_pressed_at = 0; } #if defined(DISP_BACKLIGHT) @@ -1073,7 +1076,8 @@ void UITask::loop() { if (millis() > _auto_off) { #ifdef EINK_SCREENOFF_BLANK if (curr != msg_preview) { // don't blank if messages are waiting - display.blankScreen(); + _display->blankScreen(); + _display->powerOff(); } #endif _display->turnOff(); diff --git a/src/helpers/ui/DisplayDriver.h b/src/helpers/ui/DisplayDriver.h index cbef3f98..58147aa0 100644 --- a/src/helpers/ui/DisplayDriver.h +++ b/src/helpers/ui/DisplayDriver.h @@ -26,8 +26,9 @@ public: virtual void forceFullRefresh() {} // next refresh will be full for eink virtual void turnOn() = 0; virtual void turnOff() = 0; - virtual void clear() = 0; virtual void blankScreen() {} // to cleanly erase screen before turning off + virtual void powerOff() {} + virtual void clear() = 0; virtual void startFrame(ColorVal bkg = UIColor::window_bkg) = 0; virtual void setTextSize(int sz) = 0; virtual void setColor(ColorVal c) = 0; diff --git a/src/helpers/ui/GxEPDDisplay.cpp b/src/helpers/ui/GxEPDDisplay.cpp index 21b00afc..ce09423e 100644 --- a/src/helpers/ui/GxEPDDisplay.cpp +++ b/src/helpers/ui/GxEPDDisplay.cpp @@ -75,7 +75,11 @@ void GxEPDDisplay::turnOn() { } } -void GxEPDDisplay::turnOff() { +void GxEPDDisplay::powerOff() { + display.hibernate(); +} + +void GxEPDDisplay::turnOff() { // Only stops refresh #if defined(DISP_BACKLIGHT) && !defined(BACKLIGHT_BTN) digitalWrite(DISP_BACKLIGHT, LOW); #elif defined(EXP_PIN_BACKLIGHT) && !defined(BACKLIGHT_BTN) @@ -83,7 +87,6 @@ void GxEPDDisplay::turnOff() { #endif _isOn = false; last_display_crc_value=0; - display.hibernate(); } void GxEPDDisplay::blankScreen() { diff --git a/src/helpers/ui/GxEPDDisplay.h b/src/helpers/ui/GxEPDDisplay.h index 99b25d15..46274402 100644 --- a/src/helpers/ui/GxEPDDisplay.h +++ b/src/helpers/ui/GxEPDDisplay.h @@ -60,8 +60,9 @@ public: void resetPartialRefreshCounter() { _cycles_before_full_refresh = max_partial_refresh; }; void turnOn() override; void turnOff() override; - void clear() override; void blankScreen() override; + void powerOff() override; + void clear() override; void startFrame(ColorVal bkg = UIColor::window_bkg) override; void setTextSize(int sz) override; void setColor(ColorVal c) override; diff --git a/variants/lilygo_techo/platformio.ini b/variants/lilygo_techo/platformio.ini index 14040622..eb4a69e2 100644 --- a/variants/lilygo_techo/platformio.ini +++ b/variants/lilygo_techo/platformio.ini @@ -36,7 +36,7 @@ build_flags = ${nrf52_base.build_flags} -D UI_RECENT_LIST_SIZE=9 -D UI_MSG_PREVIEW_SIZE=165 -D EINK_MAX_PARTIAL_REFRESH=60 - -D AUTO_OFF_MILLIS=1800000 + -D AUTO_OFF_MILLIS=900000 -D BACKLIGHT_BTN=PIN_BUTTON2 build_src_filter = ${nrf52_base.build_src_filter} +<helpers/*.cpp> diff --git a/variants/thinknode_m1/platformio.ini b/variants/thinknode_m1/platformio.ini index 2e1aa48f..c775ae3f 100644 --- a/variants/thinknode_m1/platformio.ini +++ b/variants/thinknode_m1/platformio.ini @@ -28,7 +28,7 @@ build_flags = ${nrf52_base.build_flags} -D UI_MSG_PREVIEW_SIZE=165 -D EINK_MAX_PARTIAL_REFRESH=60 -D BACKLIGHT_BTN=PIN_BUTTON2 - -D AUTO_OFF_MILLIS=1800000 + -D AUTO_OFF_MILLIS=900000 -D UI_NO_HIBERNATE -D DISABLE_DIAGNOSTIC_OUTPUT build_src_filter = ${nrf52_base.build_src_filter} diff --git a/variants/thinknode_m5/platformio.ini b/variants/thinknode_m5/platformio.ini index ed187dd2..1980575e 100644 --- a/variants/thinknode_m5/platformio.ini +++ b/variants/thinknode_m5/platformio.ini @@ -30,7 +30,7 @@ build_flags = ${esp32_base.build_flags} -D UI_MSG_PREVIEW_SIZE=165 -D EINK_MAX_PARTIAL_REFRESH=60 -D BACKLIGHT_BTN=PIN_BUTTON2 - -D AUTO_OFF_MILLIS=1800000 + -D AUTO_OFF_MILLIS=900000 -D UI_NO_HIBERNATE -D DISABLE_DIAGNOSTIC_OUTPUT -D SX126X_DIO2_AS_RF_SWITCH=true diff --git a/variants/thinknode_m8/platformio.ini b/variants/thinknode_m8/platformio.ini index 2c07038f..47d3a3fc 100644 --- a/variants/thinknode_m8/platformio.ini +++ b/variants/thinknode_m8/platformio.ini @@ -24,7 +24,7 @@ build_flags = ${nrf52_base.build_flags} -D UI_RECENT_LIST_SIZE=9 -D UI_MSG_PREVIEW_SIZE=165 -D EINK_MAX_PARTIAL_REFRESH=60 - -D AUTO_OFF_MILLIS=1800000 + -D AUTO_OFF_MILLIS=900000 -D BACKLIGHT_BTN=PIN_BUTTON2 -D UI_SHOW_CLOCK=1 -D EINK_SCREENOFF_BLANK From 97a6ff714c8809c88fafc628b388f882082f7d38 Mon Sep 17 00:00:00 2001 From: Marcel Verdult <marcel@verdult.de> Date: Thu, 22 Oct 2026 09:33:07 +0000 Subject: [PATCH 309/381] fix(chat): refuse a negative text length for a group message CMD_SEND_CHANNEL_TXT_MSG reads txt_type, channel_idx and a 4 byte timestamp, so the frame needs 7 bytes before the text starts, and the branch had no length guard. For a shorter frame "len - i" is computed in size_t, wraps, and reaches sendGroupMessage() as a negative int. The clamp there tests "text_len + prefix_len > MAX_TEXT_LEN", which a negative value passes, and the following memcpy() converts the length back to a size_t: a 3 byte frame asks for 4294967292 bytes into a 197 byte stack buffer. Two guards, because there are two mistakes. The branch now states its minimum like most other branches of handleCmdFrame do, so a frame below 7 bytes is answered through the existing path instead of being parsed. And sendGroupMessage() refuses a negative length the way sendGroupData() in the same file already does, which protects every other caller. A frame of exactly 7 bytes keeps working and sends an empty message, as before. Evidence. On a T-Echo running dev c9fa617c, built with FIRMWARE_BUILD_DATE "f1-dev" and confirmed by "ver => v1.18.0 (Build: f1-dev)": CH_TXT len=7 -> RESP_CODE_OK GET_STATS core -> uptime=78s CH_TXT len=3 -> NO REPLY DEVICE_QUERY -> NO REPLY (three times over 8 s, node never came back) --- examples/companion_radio/MyMesh.cpp | 4 +++- src/helpers/BaseChatMesh.cpp | 5 +++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 99a9aa30..d74050be 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -1175,7 +1175,9 @@ void MyMesh::handleCmdFrame(size_t len) { ? ERR_CODE_NOT_FOUND : ERR_CODE_UNSUPPORTED_CMD); // unknown recipient, or unsupported TXT_TYPE_* } - } else if (cmd_frame[0] == CMD_SEND_CHANNEL_TXT_MSG) { // send GroupChannel text msg + } else if (cmd_frame[0] == CMD_SEND_CHANNEL_TXT_MSG && len >= 7) { // send GroupChannel text msg + // 7 = code, txt_type, channel_idx and the 4 byte timestamp; the text may be empty. + // Without this the text length below is computed as len - 7 and turns negative. int i = 1; uint8_t txt_type = cmd_frame[i++]; // should be TXT_TYPE_PLAIN uint8_t channel_idx = cmd_frame[i++]; diff --git a/src/helpers/BaseChatMesh.cpp b/src/helpers/BaseChatMesh.cpp index 28592415..2637bc32 100644 --- a/src/helpers/BaseChatMesh.cpp +++ b/src/helpers/BaseChatMesh.cpp @@ -516,6 +516,11 @@ int BaseChatMesh::sendCommandData(const ContactInfo& recipient, uint32_t timest } bool BaseChatMesh::sendGroupMessage(uint32_t timestamp, mesh::GroupChannel& channel, const char* sender_name, const char* text, int text_len) { + if (text_len < 0) { // memcpy() below would read this as a size_t, so clamping cannot catch it + MESH_DEBUG_PRINTLN("sendGroupMessage: invalid negative text_len=%d", text_len); + return false; + } + uint8_t temp[5+MAX_TEXT_LEN+32]; memcpy(temp, ×tamp, 4); // mostly an extra blob to help make packet_hash unique temp[4] = 0; // TXT_TYPE_PLAIN From e97de59b57376a6428961296d093e4f9d29d970b Mon Sep 17 00:00:00 2001 From: Marcel Verdult <marcel@verdult.de> Date: Thu, 22 Oct 2026 09:42:58 +0000 Subject: [PATCH 310/381] fix(radio): refuse "nan" for the airtime factor "set af nan" is accepted and stores a NaN in airtime_factor, the duty cycle budget the roles hand to their airtime accounting. strtof() consumes the token, so the parse guard does not fire, and no ordered comparison is true for a NaN, so "af < 0 || af > 9" cannot reject it. "set dutycycle" writes the same field and has the same hole. Both commands now check the text before it is parsed: after optional white space and sign, a number has to start with a digit or a '.'. That refuses "nan", "inf" and their variants, and keeps every spelling that was accepted before (signs, leading white space, ".5"). The ranges and both reply strings are unchanged. The check is on the text rather than on the parsed float on purpose. nRF52 builds use -Ofast, and under -ffast-math the compiler may assume a float is never NaN or infinite. A test on the value, even one that reads its bits, can then be folded away: clang does exactly that with a bit test at -Ofast, while arm-none-eabi-gcc keeps it. A character test does not depend on that. --- src/helpers/CommonRadioPrefs.cpp | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/helpers/CommonRadioPrefs.cpp b/src/helpers/CommonRadioPrefs.cpp index 41b17993..44e0eba3 100644 --- a/src/helpers/CommonRadioPrefs.cpp +++ b/src/helpers/CommonRadioPrefs.cpp @@ -2,6 +2,22 @@ #include "TxtDataHelpers.h" #include "Utils.h" #include "target.h" +#include <ctype.h> + +namespace { + +// strtof() and atof() also read "nan" and "inf". A NaN cannot be refused by a +// range check: no ordered comparison is true for it, and under -ffast-math, +// which nRF52 builds use, the compiler may assume it never occurs and fold any +// test on the parsed value away. So the text is checked before it is parsed: +// after optional white space and sign, a number starts with a digit or a '.'. +bool looksLikeANumber(const char* s) { + while (isspace((unsigned char)*s)) s++; + if (*s == '+' || *s == '-') s++; + return isdigit((unsigned char)*s) || *s == '.'; +} + +} // namespace bool CommonRadioPrefs::getByKey(const char* key, char* value, size_t max_len) { if (strcmp(key, "fem_rxgain") == 0) { @@ -69,7 +85,7 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest if (memcmp(command, "set af ", 7) == 0) { char* end; float af = strtof(&command[7], &end); - if (end == &command[7] || af < 0 || af > 9) { + if (end == &command[7] || !looksLikeANumber(&command[7]) || af < 0 || af > 9) { strcpy(reply, "ERROR: af must be 0-9"); } else { setAirtimeFactor(af); @@ -87,7 +103,7 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest } if (memcmp(command, "set dutycycle ", 14) == 0) { float dc = atof(&command[14]); - if (dc < 1 || dc > 100) { + if (!looksLikeANumber(&command[14]) || dc < 1 || dc > 100) { strcpy(reply, "ERROR: dutycycle must be 1-100"); } else { setAirtimeFactor((100.0f / dc) - 1.0f); From ff0ce69c1614da7dab2eb482a8e289ae00806833 Mon Sep 17 00:00:00 2001 From: Martin-hub1 <thetstyle@163.com> Date: Thu, 22 Oct 2026 17:53:57 +0800 Subject: [PATCH 311/381] Add DFRobot LoRaWAN ESP32-S3 Companion BLE firmware Add a board variant for the DFRobot DFR1195 (ESP32-S3-WROOM-1-N4, SX1262, 80x160 ST7735S) and a Companion BLE environment. The display and radio use separate SPI controllers: the SX1262 is on FSPI and the ST7735 is on HSPI. ST7735Display selects that HSPI bus and the 160x80 init sequence only when DFROBOT_LORAWAN_ESP32S3 is defined. --- boards/dfrobot_lorawan_esp32s3.json | 39 ++++++++++ src/helpers/ui/ST7735Display.cpp | 5 +- .../DFRobotLoRaBoard.cpp | 20 +++++ .../DFRobotLoRaBoard.h | 15 ++++ .../dfrobot_lorawan_esp32s3/platformio.ini | 73 +++++++++++++++++++ variants/dfrobot_lorawan_esp32s3/target.cpp | 34 +++++++++ variants/dfrobot_lorawan_esp32s3/target.h | 26 +++++++ 7 files changed, 210 insertions(+), 2 deletions(-) create mode 100644 boards/dfrobot_lorawan_esp32s3.json create mode 100644 variants/dfrobot_lorawan_esp32s3/DFRobotLoRaBoard.cpp create mode 100644 variants/dfrobot_lorawan_esp32s3/DFRobotLoRaBoard.h create mode 100644 variants/dfrobot_lorawan_esp32s3/platformio.ini create mode 100644 variants/dfrobot_lorawan_esp32s3/target.cpp create mode 100644 variants/dfrobot_lorawan_esp32s3/target.h diff --git a/boards/dfrobot_lorawan_esp32s3.json b/boards/dfrobot_lorawan_esp32s3.json new file mode 100644 index 00000000..62e6cfed --- /dev/null +++ b/boards/dfrobot_lorawan_esp32s3.json @@ -0,0 +1,39 @@ +{ + "build": { + "arduino": { + "ldscript": "esp32s3_out.ld" + }, + "core": "esp32", + "extra_flags": [ + "-D ARDUINO_USB_CDC_ON_BOOT=0", + "-D ARDUINO_USB_MSC_ON_BOOT=0", + "-D ARDUINO_USB_DFU_ON_BOOT=0", + "-D ARDUINO_USB_MODE=0", + "-D ARDUINO_RUNNING_CORE=1", + "-D ARDUINO_EVENT_RUNNING_CORE=1" + ], + "f_cpu": "240000000L", + "f_flash": "80000000L", + "flash_mode": "qio", + "hwids": [["0x303A", "0x1001"]], + "mcu": "esp32s3", + "variant": "esp32s3" + }, + "connectivity": ["wifi", "bluetooth", "lora"], + "debug": { + "default_tool": "esp-builtin", + "onboard_tools": ["esp-builtin"], + "openocd_target": "esp32s3.cfg" + }, + "frameworks": ["arduino", "espidf"], + "name": "DFRobot LoRaWAN ESP32-S3 (4 MB Flash, No PSRAM)", + "upload": { + "flash_size": "4MB", + "maximum_ram_size": 524288, + "maximum_size": 4194304, + "require_upload_port": true, + "speed": 921600 + }, + "url": "https://www.dfrobot.com", + "vendor": "DFRobot" +} diff --git a/src/helpers/ui/ST7735Display.cpp b/src/helpers/ui/ST7735Display.cpp index 344f5b1d..9143ee01 100644 --- a/src/helpers/ui/ST7735Display.cpp +++ b/src/helpers/ui/ST7735Display.cpp @@ -102,7 +102,8 @@ static TFT_eSPI lcd = TFT_eSPI(160, 80); static uint32_t curr_color; -#if defined(HELTEC_LORA_V3) || defined(HELTEC_TRACKER_V2) +#if defined(HELTEC_LORA_V3) || defined(HELTEC_TRACKER_V2) || defined(DFROBOT_LORAWAN_ESP32S3) + // ESP32-S3: HSPI is SPI3. The SX1262 uses FSPI (SPI2) so the two buses do not share a controller. static SPIClass tft_spi(HSPI); #define _spi (&tft_spi) #else @@ -490,7 +491,7 @@ void ST7735Display::_resetAndInit() { // run init commands displayInit(Rcmd1); -#if defined(HELTEC_TRACKER_V2) || defined(HELTEC_T096) +#if defined(HELTEC_TRACKER_V2) || defined(HELTEC_T096) || defined(DFROBOT_LORAWAN_ESP32S3) displayInit(Rcmd2green160x80); //uint8_t madctl = ST77XX_MADCTL_MY | ST77XX_MADCTL_MV |ST7735_MADCTL_BGR;//Adjust color to BGR //display.sendCommand(ST77XX_MADCTL, &madctl, 1); diff --git a/variants/dfrobot_lorawan_esp32s3/DFRobotLoRaBoard.cpp b/variants/dfrobot_lorawan_esp32s3/DFRobotLoRaBoard.cpp new file mode 100644 index 00000000..fd04a971 --- /dev/null +++ b/variants/dfrobot_lorawan_esp32s3/DFRobotLoRaBoard.cpp @@ -0,0 +1,20 @@ +#include "DFRobotLoRaBoard.h" + +void DFRobotLoRaBoard::begin() { + // SX1262 module power. Held high for the whole boot; Companion does not + // drop into deep sleep, so the pin does not need an RTC hold. + pinMode(LORA_POWER_EN, OUTPUT); + digitalWrite(LORA_POWER_EN, HIGH); + delay(10); + + periph_power.begin(); + + pinMode(PIN_LED, OUTPUT); + digitalWrite(PIN_LED, HIGH); + + ESP32Board::begin(); +} + +const char* DFRobotLoRaBoard::getManufacturerName() const { + return "DFRobot LoRaWAN ESP32-S3"; +} diff --git a/variants/dfrobot_lorawan_esp32s3/DFRobotLoRaBoard.h b/variants/dfrobot_lorawan_esp32s3/DFRobotLoRaBoard.h new file mode 100644 index 00000000..80423486 --- /dev/null +++ b/variants/dfrobot_lorawan_esp32s3/DFRobotLoRaBoard.h @@ -0,0 +1,15 @@ +#pragma once + +#include <Arduino.h> +#include <helpers/RefCountedDigitalPin.h> +#include <helpers/ESP32Board.h> + +class DFRobotLoRaBoard : public ESP32Board { +public: + RefCountedDigitalPin periph_power; + + DFRobotLoRaBoard() : periph_power(PIN_VEXT_EN, PIN_VEXT_EN_ACTIVE) { } + + void begin(); + const char* getManufacturerName() const override; +}; diff --git a/variants/dfrobot_lorawan_esp32s3/platformio.ini b/variants/dfrobot_lorawan_esp32s3/platformio.ini new file mode 100644 index 00000000..0f69e276 --- /dev/null +++ b/variants/dfrobot_lorawan_esp32s3/platformio.ini @@ -0,0 +1,73 @@ +; DFRobot LoRaWAN ESP32-S3 (DFR1195) +; ESP32-S3-WROOM-1-N4 (4 MB flash, no PSRAM), SX1262, SPI ST7735S 80x160. +; Pin map follows variants/esp32s3/DFRobot_LoRaWAN_ESP32-S3 in the Meshtastic tree. +; LoRa is on FSPI. The display is on HSPI (SPI3), matching ST7735_SPI_HOST. +[DFRobot_LoRaWAN_ESP32S3] +extends = esp32_base +board = dfrobot_lorawan_esp32s3 +; 4 MB module: app slots are 1.9 MB. The default 4 MB table only leaves 1.25 MB. +board_build.partitions = min_spiffs.csv +build_flags = + ${esp32_base.build_flags} + -I variants/dfrobot_lorawan_esp32s3 + -D DFROBOT_LORAWAN_ESP32S3 + -D ESP32_CPU_FREQ=80 + -D RADIO_CLASS=CustomSX1262 + -D WRAPPER_CLASS=CustomSX1262Wrapper + -D LORA_TX_POWER=22 + -D P_LORA_NSS=10 + -D P_LORA_DIO_1=4 + -D P_LORA_RESET=41 + -D P_LORA_BUSY=40 + -D P_LORA_SCLK=7 + -D P_LORA_MISO=5 + -D P_LORA_MOSI=6 + -D LORA_POWER_EN=42 + -D SX126X_DIO2_AS_RF_SWITCH=true + -D SX126X_DIO3_TCXO_VOLTAGE=3.3 + -D SX126X_CURRENT_LIMIT=140 + -D SX126X_RX_BOOSTED_GAIN=1 + -D PIN_USER_BTN=18 + -D PIN_LED=21 + -D PIN_VEXT_EN=48 + -D PIN_VEXT_EN_ACTIVE=LOW + -D PIN_BOARD_SDA=8 + -D PIN_BOARD_SCL=9 + -D PIN_TFT_CS=17 + -D PIN_TFT_DC=14 + -D PIN_TFT_RST=15 + -D PIN_TFT_SDA=11 + -D PIN_TFT_SCL=12 + -D PIN_TFT_LEDA_CTL=16 + -D PIN_TFT_LEDA_CTL_ACTIVE=HIGH +build_src_filter = ${esp32_base.build_src_filter} + +<../variants/dfrobot_lorawan_esp32s3> +lib_deps = + ${esp32_base.lib_deps} + bodmer/TFT_eSPI @ ^2.4.31 + +; Landscape UI on the 80x160 panel. Use 3 if the picture is upside down. +[env:DFRobot_LoRaWAN_ESP32S3_companion_radio_ble] +extends = DFRobot_LoRaWAN_ESP32S3 +build_flags = + ${DFRobot_LoRaWAN_ESP32S3.build_flags} + -I src/helpers/ui + -I examples/companion_radio/ui-new + -D DISPLAY_ROTATION=3 + -D DISPLAY_CLASS=ST7735Display + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D BLE_PIN_CODE=123456 + -D OFFLINE_QUEUE_SIZE=256 +; -D BLE_DEBUG_LOGGING=1 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${DFRobot_LoRaWAN_ESP32S3.build_src_filter} + +<helpers/esp32/SerialBLEInterface.cpp> + +<helpers/ui/MomentaryButton.cpp> + +<helpers/ui/ST7735Display.cpp> + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = + ${DFRobot_LoRaWAN_ESP32S3.lib_deps} + densaugeo/base64 @ ~1.4.0 diff --git a/variants/dfrobot_lorawan_esp32s3/target.cpp b/variants/dfrobot_lorawan_esp32s3/target.cpp new file mode 100644 index 00000000..bf723516 --- /dev/null +++ b/variants/dfrobot_lorawan_esp32s3/target.cpp @@ -0,0 +1,34 @@ +#include <Arduino.h> +#include <SPI.h> +#include "target.h" + +DFRobotLoRaBoard board; + +// FSPI is SPI2. The ST7735 driver takes HSPI (SPI3); the default SPIClass +// constructor on ESP32-S3 is HSPI and would collide with the display. +static SPIClass spi(FSPI); +RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi); + +WRAPPER_CLASS radio_driver(radio, board); + +ESP32RTCClock fallback_clock; +AutoDiscoverRTCClock rtc_clock(fallback_clock); +SensorManager sensors; + +#ifdef DISPLAY_CLASS + DISPLAY_CLASS display(&board.periph_power); + // Active-low button, internal pull-up. + MomentaryButton user_btn(PIN_USER_BTN, 1000, true, true); +#endif + +bool radio_init() { + fallback_clock.begin(); + rtc_clock.begin(Wire); + + return radio.std_init(&spi); +} + +mesh::LocalIdentity radio_new_identity() { + RadioNoiseListener rng(radio); + return mesh::LocalIdentity(&rng); // create new random identity +} diff --git a/variants/dfrobot_lorawan_esp32s3/target.h b/variants/dfrobot_lorawan_esp32s3/target.h new file mode 100644 index 00000000..07cec79b --- /dev/null +++ b/variants/dfrobot_lorawan_esp32s3/target.h @@ -0,0 +1,26 @@ +#pragma once + +#define RADIOLIB_STATIC_ONLY 1 +#include <RadioLib.h> +#include <helpers/radiolib/RadioLibWrappers.h> +#include <DFRobotLoRaBoard.h> +#include <helpers/radiolib/CustomSX1262Wrapper.h> +#include <helpers/AutoDiscoverRTCClock.h> +#include <helpers/SensorManager.h> +#ifdef DISPLAY_CLASS + #include <helpers/ui/ST7735Display.h> + #include <helpers/ui/MomentaryButton.h> +#endif + +extern DFRobotLoRaBoard board; +extern WRAPPER_CLASS radio_driver; +extern AutoDiscoverRTCClock rtc_clock; +extern SensorManager sensors; + +#ifdef DISPLAY_CLASS + extern DISPLAY_CLASS display; + extern MomentaryButton user_btn; +#endif + +bool radio_init(); +mesh::LocalIdentity radio_new_identity(); From fded88ac6a97008a1e8d87bb150f85ac0f898fa8 Mon Sep 17 00:00:00 2001 From: Blake Latchford <github.demote149@passmail.com> Date: Thu, 22 Oct 2026 17:57:33 -0400 Subject: [PATCH 312/381] Fix broken KISS modem build on 6 ESP32-S3 platforms Broken out from PR #3496 which has been open for a month. --- examples/kiss_modem/main.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/examples/kiss_modem/main.cpp b/examples/kiss_modem/main.cpp index 44b2a3df..bb77c23d 100644 --- a/examples/kiss_modem/main.cpp +++ b/examples/kiss_modem/main.cpp @@ -115,7 +115,10 @@ void setup() { delay(100); #if defined(ESP32) && defined(ARDUINO_USB_CDC_ON_BOOT) && ARDUINO_USB_CDC_ON_BOOT Serial.setTxTimeoutMs(USB_TX_TIMEOUT_MS); +#if defined(ARDUINO_USB_MODE) && ARDUINO_USB_MODE + // HWCDC only; TinyUSB's USBCDC TX buffer is fixed at build time Serial.setTxBufferSize(USB_TX_BUFFER_SIZE); +#endif #endif modem = new KissModem(Serial, identity, rng, radio_driver, board, sensors); #endif From ff4c28985c18ce58db8d4c495674df3f5e641259 Mon Sep 17 00:00:00 2001 From: Luca Olivieri <gliolivieri@live.it> Date: Fri, 23 Oct 2026 21:35:02 +0200 Subject: [PATCH 313/381] Added INA219 sensor --- .github/workflows/pr-build-check.yml | 2 ++ variants/lilygo_t3_stm32/README.md | 37 ++++++++++++++++++++++++- variants/lilygo_t3_stm32/platformio.ini | 29 +++++++++++++++++++ variants/lilygo_t3_stm32/target.cpp | 12 ++++++++ variants/lilygo_t3_stm32/target.h | 10 ++++++- 5 files changed, 88 insertions(+), 2 deletions(-) diff --git a/.github/workflows/pr-build-check.yml b/.github/workflows/pr-build-check.yml index 0dcb159e..529a1a21 100644 --- a/.github/workflows/pr-build-check.yml +++ b/.github/workflows/pr-build-check.yml @@ -42,6 +42,8 @@ jobs: - wio-e5-mini_repeater - LilyGo_T3_STM32_repeater - LilyGo_T3_STM32_companion_radio_usb + - LilyGo_T3_STM32_repeater_ina219 + - LilyGo_T3_STM32_companion_radio_usb_ina219 # ESP32-C6 - LilyGo_Tlora_C6_repeater_ # LR1110 (nRF52) diff --git a/variants/lilygo_t3_stm32/README.md b/variants/lilygo_t3_stm32/README.md index 2686aa7f..efc12c5c 100644 --- a/variants/lilygo_t3_stm32/README.md +++ b/variants/lilygo_t3_stm32/README.md @@ -15,6 +15,41 @@ The companion supports 100 contacts and eight channels. Radio settings inherit the repository defaults; select settings appropriate to the board's RF band. Existing saved preferences override build defaults. +## Optional INA219 telemetry + +The INA219 builds use MeshCore's existing environment sensor driver to report +voltage, current, and power. Build either role with: + +```sh +pio run -e LilyGo_T3_STM32_repeater_ina219 +pio run -e LilyGo_T3_STM32_companion_radio_usb_ina219 +``` + +Connect the sensor's logic supply to **3.3 V** and use a common ground: + +| INA219 connection | T3 STM32 connection | +| --- | --- | +| VCC / logic supply | 3.3 V | +| GND | GND | +| SDA | PB7 (JP2 pin 9) | +| SCL | PB8 (JP2 pin 10) | + +PB7/PB8 are the alternate I2C1 pins exposed on the board headers. The default +STM32 I2C pins, PA9/PA10, are reserved for USB serial. The OLED uses SPI. +The sensor is detected at startup at address **0x40**; to use another address, +override `TELEM_INA219_ADDRESS` in the build flags. An absent sensor produces no +additional telemetry. The base builds do not initialize I2C or include the driver. + +The measurement terminals (VIN+ and VIN-) go in series with the positive supply +of the circuit being measured; these are separate from the sensor's logic supply. +See the [INA219 wiring guide](https://learn.adafruit.com/adafruit-ina219-current-sensor-breakout/wiring). +USB power can bypass a sensor placed only in the battery lead. + +Readings use environment telemetry permissions. Existing telemetry encodes current +in 1 mA steps and power in whole watts; it does not provide accumulated mAh or +battery percentage. INA219 telemetry has been confirmed on hardware with the +repeater build; the USB companion sensor build has been compile-tested only. + ## Flash and connect Connect the USB serial port. Hold BOOT, press and release RST, then release BOOT: @@ -63,4 +98,4 @@ pings timed out; long-term reliability has not been established. Higher transmit powers are outside the validated MVP setting. The repeater builds successfully; forwarding has not been hardware-tested. -Battery telemetry, SD storage, and low-power optimization are not implemented. +Built-in battery telemetry, SD storage, and low-power optimization are not implemented. diff --git a/variants/lilygo_t3_stm32/platformio.ini b/variants/lilygo_t3_stm32/platformio.ini index ba56cf52..39e059b7 100644 --- a/variants/lilygo_t3_stm32/platformio.ini +++ b/variants/lilygo_t3_stm32/platformio.ini @@ -50,3 +50,32 @@ build_src_filter = ${lilygo_t3_stm32.build_src_filter} +<../examples/companion_radio/ui-orig/*.cpp> lib_deps = ${lilygo_t3_stm32.lib_deps} densaugeo/base64 @ ~1.4.0 + +; Optional INA219 telemetry on I2C1. Keep the base builds sensor-free. +[lilygo_t3_stm32_ina219] +build_flags = + -D ENV_INCLUDE_INA219=1 + -D PIN_WIRE_SDA=PB7 + -D PIN_WIRE_SCL=PB8 +build_src_filter = + +<helpers/sensors/EnvironmentSensorManager.cpp> +lib_deps = + adafruit/Adafruit INA219 @ ^1.2.3 + +[env:LilyGo_T3_STM32_repeater_ina219] +extends = env:LilyGo_T3_STM32_repeater +build_flags = ${env:LilyGo_T3_STM32_repeater.build_flags} + ${lilygo_t3_stm32_ina219.build_flags} +build_src_filter = ${env:LilyGo_T3_STM32_repeater.build_src_filter} + ${lilygo_t3_stm32_ina219.build_src_filter} +lib_deps = ${lilygo_t3_stm32.lib_deps} + ${lilygo_t3_stm32_ina219.lib_deps} + +[env:LilyGo_T3_STM32_companion_radio_usb_ina219] +extends = env:LilyGo_T3_STM32_companion_radio_usb +build_flags = ${env:LilyGo_T3_STM32_companion_radio_usb.build_flags} + ${lilygo_t3_stm32_ina219.build_flags} +build_src_filter = ${env:LilyGo_T3_STM32_companion_radio_usb.build_src_filter} + ${lilygo_t3_stm32_ina219.build_src_filter} +lib_deps = ${env:LilyGo_T3_STM32_companion_radio_usb.lib_deps} + ${lilygo_t3_stm32_ina219.lib_deps} diff --git a/variants/lilygo_t3_stm32/target.cpp b/variants/lilygo_t3_stm32/target.cpp index f98783fe..b7a14c48 100644 --- a/variants/lilygo_t3_stm32/target.cpp +++ b/variants/lilygo_t3_stm32/target.cpp @@ -1,12 +1,19 @@ #include <Arduino.h> #include <SPI.h> +#if ENV_INCLUDE_INA219 + #include <Wire.h> +#endif #include "target.h" LilyGoT3STM32Board board; RADIO_CLASS radio = new STM32WLx_Module(); WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock rtc_clock; +#if ENV_INCLUDE_INA219 +EnvironmentSensorManager sensors; +#else SensorManager sensors; +#endif DISPLAY_CLASS display; // PH3 is also BOOT0: the board's button is active high with an external pull-down. MomentaryButton user_btn(PIN_USER_BTN, 1000, false); @@ -24,6 +31,11 @@ static const Module::RfSwitchMode_t rfswitch_table[] = { void LilyGoT3STM32Board::begin() { STM32Board::begin(); +#if ENV_INCLUDE_INA219 + // These builds remap Wire to PB7/PB8; PA9/PA10 are used by USART1. + Wire.begin(); +#endif + // The SD card shares SPI1 with the OLED; keep it deselected. digitalWrite(PA4, HIGH); pinMode(PA4, OUTPUT); diff --git a/variants/lilygo_t3_stm32/target.h b/variants/lilygo_t3_stm32/target.h index 83235cbd..2db3173b 100644 --- a/variants/lilygo_t3_stm32/target.h +++ b/variants/lilygo_t3_stm32/target.h @@ -4,7 +4,11 @@ #include <helpers/stm32/STM32Board.h> #include <helpers/radiolib/CustomSTM32WLxWrapper.h> #include <helpers/ArduinoHelpers.h> -#include <helpers/SensorManager.h> +#if ENV_INCLUDE_INA219 + #include <helpers/sensors/EnvironmentSensorManager.h> +#else + #include <helpers/SensorManager.h> +#endif #include <helpers/ui/SSD1306Display.h> #include <helpers/ui/MomentaryButton.h> @@ -20,7 +24,11 @@ public: extern LilyGoT3STM32Board board; extern WRAPPER_CLASS radio_driver; extern VolatileRTCClock rtc_clock; +#if ENV_INCLUDE_INA219 +extern EnvironmentSensorManager sensors; +#else extern SensorManager sensors; +#endif extern DISPLAY_CLASS display; extern MomentaryButton user_btn; From e8be1ad6b21e5957ec6048f9ab0d27c39913470b Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Sat, 24 Oct 2026 10:16:56 -0400 Subject: [PATCH 314/381] UiTask: better cleaning of eink screens when hibernating --- examples/companion_radio/ui-new/UITask.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index 6e987f87..aced739d 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -908,9 +908,11 @@ void UITask::shutdown(bool restart){ if (restart) { _board->reboot(); } else { - display.forceFullRefresh(); - display.clear(); - display.endFrame(); + if (_display->isEink()) { + _display->blankScreen(); + _display->turnOff(); + _display->powerOff(); + } // Power off board including radio, display, GPS and components _board->powerOff(); } From f0ea4620caac782a5be3ab2ed555daa5ce2aa872 Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Sat, 24 Oct 2026 11:15:28 -0400 Subject: [PATCH 315/381] thinknode_m1: fix button2 definition --- variants/thinknode_m1/variant.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/variants/thinknode_m1/variant.h b/variants/thinknode_m1/variant.h index f7f52a6a..e096f3ca 100644 --- a/variants/thinknode_m1/variant.h +++ b/variants/thinknode_m1/variant.h @@ -81,7 +81,7 @@ #define BUTTON_PIN PIN_BUTTON1 #define PIN_USER_BTN BUTTON_PIN -#define PIN_BUTTON2 (11) +#define PIN_BUTTON2 (39) #define BUTTON_PIN2 PIN_BUTTON2 #define EXTERNAL_FLASH_DEVICES MX25R1635F From 81fa5d7f5a944b413abaa891f4858b9844620cdc Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Sat, 24 Oct 2026 13:26:06 -0400 Subject: [PATCH 316/381] ThinknodeM1: update eink driver --- variants/thinknode_m1/platformio.ini | 5 +++++ variants/thinknode_m1/variant.h | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/variants/thinknode_m1/platformio.ini b/variants/thinknode_m1/platformio.ini index c775ae3f..7c620e2e 100644 --- a/variants/thinknode_m1/platformio.ini +++ b/variants/thinknode_m1/platformio.ini @@ -27,6 +27,11 @@ build_flags = ${nrf52_base.build_flags} -D UI_RECENT_LIST_SIZE=9 -D UI_MSG_PREVIEW_SIZE=165 -D EINK_MAX_PARTIAL_REFRESH=60 + -D EINK_DISPLAY_MODEL=GxEPD2_154_D67 + -D EINK_SCALE_X=1.5625f + -D EINK_SCALE_Y=1.5625f + -D EINK_X_OFFSET=0 + -D EINK_Y_OFFSET=10 -D BACKLIGHT_BTN=PIN_BUTTON2 -D AUTO_OFF_MILLIS=900000 -D UI_NO_HIBERNATE diff --git a/variants/thinknode_m1/variant.h b/variants/thinknode_m1/variant.h index e096f3ca..aecf197e 100644 --- a/variants/thinknode_m1/variant.h +++ b/variants/thinknode_m1/variant.h @@ -131,6 +131,11 @@ extern const int SCK; #define DISP_BUSY (3) #define DISP_BACKLIGHT (43) +#define PIN_DISPLAY_CS DISP_CS +#define PIN_DISPLAY_DC DISP_DC +#define PIN_DISPLAY_RST DISP_RST +#define PIN_DISPLAY_BUSY DISP_BUSY + //////////////////////////////////////////////////////////////////////////////// // GPS From 6f9b3ba15515909bb051141edea79178a8c28b9b Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Sun, 25 Oct 2026 17:49:16 -0400 Subject: [PATCH 317/381] ThinknodeM5: enable wifi in usb companion --- variants/thinknode_m5/platformio.ini | 2 ++ 1 file changed, 2 insertions(+) diff --git a/variants/thinknode_m5/platformio.ini b/variants/thinknode_m5/platformio.ini index 1980575e..a9761597 100644 --- a/variants/thinknode_m5/platformio.ini +++ b/variants/thinknode_m5/platformio.ini @@ -177,12 +177,14 @@ build_flags = -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 -D ENABLE_USB_INTERFACE + -D ENABLE_WIFI_INTERFACE build_src_filter = ${ThinkNode_M5.build_src_filter} +<helpers/esp32/*.cpp> +<helpers/ui/MomentaryButton.cpp> +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> +<helpers/ui/buzzer.cpp> + +<helpers/wifi/*.cpp> lib_deps = ${ThinkNode_M5.lib_deps} densaugeo/base64 @ ~1.4.0 From 8e0e5b81104dcdc971a195d506896f8b9140cac3 Mon Sep 17 00:00:00 2001 From: Blake Latchford <github.demote149@passmail.com> Date: Sun, 25 Oct 2026 21:45:10 -0400 Subject: [PATCH 318/381] Saturate duplicate packet stats instead of wrapping Tested on a Heltec V4 repeater with the counter seeded at 65530. Fixes #3255 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- examples/simple_repeater/MyMesh.cpp | 4 ++-- examples/simple_room_server/MyMesh.cpp | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index 61b6c149..b50d19d0 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -229,8 +229,8 @@ int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t stats.n_recv_direct = getNumRecvDirect(); stats.err_events = _err_flags; stats.last_snr = (int16_t)(radio_driver.getLastSNR() * 4); - stats.n_direct_dups = ((SimpleMeshTables *)getTables())->getNumDirectDups(); - stats.n_flood_dups = ((SimpleMeshTables *)getTables())->getNumFloodDups(); + stats.n_direct_dups = std::min<uint32_t>(((SimpleMeshTables *)getTables())->getNumDirectDups(), 0xFFFF); + stats.n_flood_dups = std::min<uint32_t>(((SimpleMeshTables *)getTables())->getNumFloodDups(), 0xFFFF); stats.total_rx_air_time_secs = getReceiveAirTime() / 1000; stats.n_recv_errors = radio_driver.getPacketsRecvErrors(); memcpy(&reply_data[4], &stats, sizeof(stats)); diff --git a/examples/simple_room_server/MyMesh.cpp b/examples/simple_room_server/MyMesh.cpp index da4c776c..935fd7f9 100644 --- a/examples/simple_room_server/MyMesh.cpp +++ b/examples/simple_room_server/MyMesh.cpp @@ -1,4 +1,5 @@ #include "MyMesh.h" +#include <algorithm> #define REPLY_DELAY_MILLIS 1500 #define PUSH_NOTIFY_DELAY_MILLIS 2000 @@ -170,8 +171,8 @@ int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t stats.n_recv_direct = getNumRecvDirect(); stats.err_events = _err_flags; stats.last_snr = (int16_t)(radio_driver.getLastSNR() * 4); - stats.n_direct_dups = ((SimpleMeshTables *)getTables())->getNumDirectDups(); - stats.n_flood_dups = ((SimpleMeshTables *)getTables())->getNumFloodDups(); + stats.n_direct_dups = std::min<uint32_t>(((SimpleMeshTables *)getTables())->getNumDirectDups(), 0xFFFF); + stats.n_flood_dups = std::min<uint32_t>(((SimpleMeshTables *)getTables())->getNumFloodDups(), 0xFFFF); stats.n_posted = _num_posted; stats.n_post_push = _num_post_pushes; From ab64c87c384b11c283f6078c29304c2507ddd26e Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Mon, 26 Oct 2026 20:29:39 +1100 Subject: [PATCH 319/381] * scope 0 rule fixes --- src/helpers/RegionMap.cpp | 2 +- src/helpers/RoutingPolicy.h | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/helpers/RegionMap.cpp b/src/helpers/RegionMap.cpp index d8d77380..16a8e1ff 100644 --- a/src/helpers/RegionMap.cpp +++ b/src/helpers/RegionMap.cpp @@ -188,7 +188,7 @@ int RegionMap::getTransportKeysFor(const RegionEntry& src, TransportKey dest[], } RegionEntry* RegionMap::findMatch(mesh::Packet* packet, uint8_t mask) { - if (packet->transport_codes[0] == 0) return &wildcard; + if (packet->transport_codes[0] == 0) return (wildcard.flags & mask) == 0 ? &wildcard : NULL; for (int i = 0; i < num_regions; i++) { auto region = ®ions[i]; if ((region->flags & mask) == 0) { // does region allow this? (per 'mask' param) diff --git a/src/helpers/RoutingPolicy.h b/src/helpers/RoutingPolicy.h index 5251a590..225e5cd4 100644 --- a/src/helpers/RoutingPolicy.h +++ b/src/helpers/RoutingPolicy.h @@ -17,6 +17,7 @@ inline bool isFloodHopLimitExceeded(const Packet* packet, uint8_t flood_max, uint8_t hops = packet->getPathHashCount(); if (hops >= flood_max) return true; if (packet->getRouteType() == ROUTE_TYPE_FLOOD && hops >= flood_max_unscoped) return true; + if (packet->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD && packet->transport_codes[0] == 0 && hops >= flood_max_unscoped) return true; // scope 0, treat as unscoped if (packet->getPayloadType() == PAYLOAD_TYPE_ADVERT && hops >= flood_max_advert) return true; return false; } From f889b7d8a21a0a011d146b3bc11bb1ef161363d0 Mon Sep 17 00:00:00 2001 From: Scott Powell <ripple_biz@protonmail.com> Date: Mon, 26 Oct 2026 20:39:46 +1100 Subject: [PATCH 320/381] * unit test fix --- test/test_routing_policy/test_routing_policy.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/test_routing_policy/test_routing_policy.cpp b/test/test_routing_policy/test_routing_policy.cpp index bba9ec79..3f7faf30 100644 --- a/test/test_routing_policy/test_routing_policy.cpp +++ b/test/test_routing_policy/test_routing_policy.cpp @@ -8,6 +8,9 @@ static Packet makeFlood(uint8_t route_type, uint8_t payload_type, uint8_t hops) p.header = route_type | (payload_type << PH_TYPE_SHIFT); p.setPathHashSizeAndCount(1, hops); p.payload_len = 1; + if (route_type == ROUTE_TYPE_TRANSPORT_FLOOD) { + p.transport_codes[0] = 1; // has to be non-zero + } return p; } From 2270b931fa404475364387e6135554e609e3b416 Mon Sep 17 00:00:00 2001 From: Marcel Verdult <marcel@verdult.de> Date: Fri, 23 Oct 2026 01:30:57 +0200 Subject: [PATCH 321/381] fix(esp32): define the RTC backup of ESP32RTCClock once ESP32Board.h defined _rtc_backup_time and _rtc_backup_magic as static in the header, so every translation unit that includes it has its own copy, and the inline members of ESP32RTCClock read and write the copy of the unit they are compiled in. Today one unit per image uses them; a second one could restore a copy that setCurrentTime() never wrote. The header now declares them, and ESP32Board.cpp defines them once. --- src/helpers/ESP32Board.cpp | 4 ++++ src/helpers/ESP32Board.h | 7 +++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/helpers/ESP32Board.cpp b/src/helpers/ESP32Board.cpp index a55abb26..d190fca1 100644 --- a/src/helpers/ESP32Board.cpp +++ b/src/helpers/ESP32Board.cpp @@ -3,6 +3,10 @@ #include "ESP32Board.h" #include <target.h> +// The RTC backup of ESP32RTCClock, declared in ESP32Board.h. +RTC_NOINIT_ATTR uint32_t _rtc_backup_time; +RTC_NOINIT_ATTR uint32_t _rtc_backup_magic; + #if defined(ADMIN_PASSWORD) && !defined(DISABLE_WIFI_OTA) // Repeater or Room Server only #include <WiFi.h> #include <AsyncTCP.h> diff --git a/src/helpers/ESP32Board.h b/src/helpers/ESP32Board.h index 3f95e692..cd274cd9 100644 --- a/src/helpers/ESP32Board.h +++ b/src/helpers/ESP32Board.h @@ -200,8 +200,11 @@ public: } }; -static RTC_NOINIT_ATTR uint32_t _rtc_backup_time; -static RTC_NOINIT_ATTR uint32_t _rtc_backup_magic; +// The time ESP32RTCClock restores after a reset, in RTC memory that a reset does +// not clear. Defined once, in ESP32Board.cpp: the inline members below run in +// every translation unit that uses them and must all see the same backup. +extern uint32_t _rtc_backup_time; +extern uint32_t _rtc_backup_magic; #define RTC_BACKUP_MAGIC 0xAA55CC33 #define RTC_TIME_MIN 1772323200 // 1 Mar 2026 From 8a33082b59d1f0da9758d1f0437d602900da87fc Mon Sep 17 00:00:00 2001 From: WayenWeng <jinyuan.weng@seeed.cc> Date: Tue, 27 Oct 2026 10:44:36 +0800 Subject: [PATCH 322/381] fix(radio): put LR2021 in standby before re-config in setParams --- src/helpers/radiolib/CustomLR2021Wrapper.h | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/src/helpers/radiolib/CustomLR2021Wrapper.h b/src/helpers/radiolib/CustomLR2021Wrapper.h index 8299e2bf..c60bfda3 100644 --- a/src/helpers/radiolib/CustomLR2021Wrapper.h +++ b/src/helpers/radiolib/CustomLR2021Wrapper.h @@ -16,15 +16,23 @@ public: CustomLR2021Wrapper(CustomLR2021& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { } void setParams(float freq, float bw, uint8_t sf, uint8_t cr) override { - ((CustomLR2021 *)_radio)->setFrequency(freq); - ((CustomLR2021 *)_radio)->setSpreadingFactor(sf); - ((CustomLR2021 *)_radio)->setBandwidth(bw); - ((CustomLR2021 *)_radio)->setCodingRate(cr); + auto r = (CustomLR2021 *)_radio; + // LR2021 only accepts RF/modulation config commands while in STANDBY mode. + // Re-configuring while in continuous RX gets silently rejected (-706), + // which broke hot frequency changes over BLE. + int16_t status = r->standby(); + if (status != RADIOLIB_ERR_NONE) { MESH_DEBUG_PRINTLN("CustomLR2021Wrapper: standby() -> %d", status); } + if ((status = r->setFrequency(freq)) != RADIOLIB_ERR_NONE) { MESH_DEBUG_PRINTLN("CustomLR2021Wrapper: setFrequency() -> %d", status); } + if ((status = r->setSpreadingFactor(sf)) != RADIOLIB_ERR_NONE) { MESH_DEBUG_PRINTLN("CustomLR2021Wrapper: setSpreadingFactor() -> %d", status); } + if ((status = r->setBandwidth(bw)) != RADIOLIB_ERR_NONE) { MESH_DEBUG_PRINTLN("CustomLR2021Wrapper: setBandwidth() -> %d", status); } + if ((status = r->setCodingRate(cr)) != RADIOLIB_ERR_NONE) { MESH_DEBUG_PRINTLN("CustomLR2021Wrapper: setCodingRate() -> %d", status); } updatePreamble(sf); - applySideDetectorConfig(); + // internal idle() sets STATE_IDLE, which triggers a startReceive() on the next loop + status = applySideDetectorConfig(); + if (status != RADIOLIB_ERR_NONE) { MESH_DEBUG_PRINTLN("CustomLR2021Wrapper: applySideDetectorConfig() -> %d", status); } PacketMillis pm = calcMaxPacketMillis(sf, bw, cr, preambleLengthForSF(sf)); - ((CustomLR2021 *)_radio)->setPreambleMillis(pm.preambleMillis); - ((CustomLR2021 *)_radio)->setMaxPayloadMillis(pm.payloadMillis); + r->setPreambleMillis(pm.preambleMillis); // pure in-memory setters, no standby needed + r->setMaxPayloadMillis(pm.payloadMillis); } From 4d93dfbc04645162697aec26618e7b73ebee69bf Mon Sep 17 00:00:00 2001 From: rado <6479266+rbrus@users.noreply.github.com> Date: Tue, 27 Oct 2026 07:21:24 +0100 Subject: [PATCH 323/381] Drop unit tests per review feedback --- .../test_companion_node_prefs.cpp | 57 ------------------- 1 file changed, 57 deletions(-) diff --git a/test/test_companion_node_prefs/test_companion_node_prefs.cpp b/test/test_companion_node_prefs/test_companion_node_prefs.cpp index ab5e0f90..433c9710 100644 --- a/test/test_companion_node_prefs/test_companion_node_prefs.cpp +++ b/test/test_companion_node_prefs/test_companion_node_prefs.cpp @@ -6,32 +6,6 @@ #include "../../examples/companion_radio/NodePrefs.h" -bool CommonRadioPrefs::getByKey(const char* key, char* value, size_t max_len) { - if (strcmp(key, "fem_rxgain") == 0) { - snprintf(value, max_len, "%d", (uint32_t)getFEMRxGain()); - return true; - } - if (strcmp(key, "fem_txgain") == 0) { - snprintf(value, max_len, "%d", (uint32_t)getFEMTxGain()); - return true; - } - return false; -} - -bool CommonRadioPrefs::setByKey(const char* key, const char* value) { - if (strcmp(key, "fem_rxgain") == 0) { - setFEMRxGain(atoi(value)); - markDirty(); - return true; - } - if (strcmp(key, "fem_txgain") == 0) { - setFEMTxGain(atoi(value)); - markDirty(); - return true; - } - return false; -} - class ReplayStream : public Stream { const char* _text; int _pos = 0; @@ -103,37 +77,6 @@ TEST(CompanionNodePrefs, RxGainSettingsRoundTripIndependently) { } #endif -TEST(CompanionNodePrefs, NegativeTxPowerPreservedAsSigned) { - NodePrefs prefs; - CommonRadioPrefs* radio = prefs.getRadioPrefs(); - - radio->setTxPower(-9); - EXPECT_EQ(-9, prefs.tx_power_dbm); - EXPECT_EQ(-9, radio->getTxPower()); - EXPECT_EQ(-9, static_cast<int32_t>(radio->getTxPower())); - - char reply[32]; - snprintf(reply, sizeof(reply), "> %d", static_cast<int32_t>(radio->getTxPower())); - EXPECT_STREQ("> -9", reply); -} - -TEST(CompanionNodePrefs, NegativeTxPowerRoundTripsSerial) { - NodePrefs saved; - saved.getRadioPrefs()->setTxPower(-9); - - CaptureStream output; - ASSERT_TRUE(saved.saveSerial(output)); - EXPECT_NE(std::string::npos, output.text().find("tx:-9")); - - ReplayStream input("{radio:{tx:-9}}"); - NodePrefs loaded; - loaded.tx_power_dbm = 22; - - ASSERT_TRUE(loaded.loadSerial(input)); - EXPECT_EQ(-9, loaded.tx_power_dbm); - EXPECT_EQ(-9, loaded.getRadioPrefs()->getTxPower()); -} - int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); From 15c58df0d99c1e0999e473a9a08d8ebc57ce2f72 Mon Sep 17 00:00:00 2001 From: Rastislav Vysoky <recrof@gmail.com> Date: Tue, 27 Oct 2026 07:42:32 +0100 Subject: [PATCH 324/381] bump RadioLib to 7.8.1 --- platformio.ini | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/platformio.ini b/platformio.ini index f296f838..92c94204 100644 --- a/platformio.ini +++ b/platformio.ini @@ -19,8 +19,7 @@ monitor_speed = 115200 lib_deps = SPI Wire - ;jgromes/RadioLib @ ^7.7.1 - https://github.com/jgromes/RadioLib.git#6d8934836678d8894e3d556550475b37dce3e2b6 + jgromes/RadioLib @ 7.8.1 rweather/Crypto @ ^0.4.0 adafruit/RTClib @ ^2.1.3 melopero/Melopero RV3028 @ ^1.1.0 From b2997ef0d373203a6a5287f1ce3a90c2750e8234 Mon Sep 17 00:00:00 2001 From: akalinin-softvelum <142931037+akalinin-softvelum@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:20:36 +0000 Subject: [PATCH 325/381] T-Echo: use GxEPD2_154_D67 e-ink driver T-Echo used the fallback GxEPD2_150_BN; on my unit every refresh hit the 10 s busy timeout. Switch to GxEPD2_154_D67 like Meshtastic. --- variants/lilygo_techo/platformio.ini | 5 +++++ variants/lilygo_techo/variant.h | 6 ++++++ 2 files changed, 11 insertions(+) diff --git a/variants/lilygo_techo/platformio.ini b/variants/lilygo_techo/platformio.ini index eb4a69e2..ba39549e 100644 --- a/variants/lilygo_techo/platformio.ini +++ b/variants/lilygo_techo/platformio.ini @@ -32,6 +32,11 @@ build_flags = ${nrf52_base.build_flags} -D PIN_GPS_RESET_ACTIVE=LOW -D TELEM_BME280_ADDRESS=0x77 -D DISPLAY_CLASS=GxEPDDisplay + -D EINK_DISPLAY_MODEL=GxEPD2_154_D67 + -D EINK_SCALE_X=1.5625f + -D EINK_SCALE_Y=1.5625f + -D EINK_X_OFFSET=0 + -D EINK_Y_OFFSET=10 -D EINK_SCREENOFF_BLANK -D UI_RECENT_LIST_SIZE=9 -D UI_MSG_PREVIEW_SIZE=165 diff --git a/variants/lilygo_techo/variant.h b/variants/lilygo_techo/variant.h index 1de62d91..d11aac58 100644 --- a/variants/lilygo_techo/variant.h +++ b/variants/lilygo_techo/variant.h @@ -131,6 +131,12 @@ extern const int SCK; #define DISP_BUSY (3) #define DISP_BACKLIGHT (43) +// used by GxEPDDisplay when EINK_DISPLAY_MODEL is set +#define PIN_DISPLAY_CS DISP_CS +#define PIN_DISPLAY_DC DISP_DC +#define PIN_DISPLAY_RST DISP_RST +#define PIN_DISPLAY_BUSY DISP_BUSY + //////////////////////////////////////////////////////////////////////////////// // GPS From a1528cc36f02ecb770c2f677dd6a0d235d57b2c6 Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Tue, 27 Oct 2026 15:41:36 -0400 Subject: [PATCH 326/381] Remove unused buttonStateChanged from some variants --- variants/meshtracker_x1/MeshTrackerX1Board.cpp | 1 - variants/meshtracker_x1/MeshTrackerX1Board.h | 14 -------------- variants/promicro/PromicroBoard.cpp | 1 - variants/promicro/PromicroBoard.h | 12 ------------ variants/t1000-e/T1000eBoard.cpp | 1 - variants/t1000-e/T1000eBoard.h | 14 -------------- variants/thinknode_m3/ThinkNodeM3Board.cpp | 1 - variants/thinknode_m3/ThinkNodeM3Board.h | 12 ------------ variants/thinknode_m4/ThinkNodeM4Board.cpp | 1 - variants/thinknode_m4/ThinkNodeM4Board.h | 12 ------------ 10 files changed, 69 deletions(-) diff --git a/variants/meshtracker_x1/MeshTrackerX1Board.cpp b/variants/meshtracker_x1/MeshTrackerX1Board.cpp index 56e537a2..94c20a63 100644 --- a/variants/meshtracker_x1/MeshTrackerX1Board.cpp +++ b/variants/meshtracker_x1/MeshTrackerX1Board.cpp @@ -5,7 +5,6 @@ void MeshTrackerX1Board::begin() { NRF52BoardDCDC::begin(); - btn_prev_state = LOW; // button is active HIGH #ifdef BUTTON_PIN pinMode(BATTERY_PIN, INPUT); diff --git a/variants/meshtracker_x1/MeshTrackerX1Board.h b/variants/meshtracker_x1/MeshTrackerX1Board.h index 51f022e0..d332244f 100644 --- a/variants/meshtracker_x1/MeshTrackerX1Board.h +++ b/variants/meshtracker_x1/MeshTrackerX1Board.h @@ -5,9 +5,6 @@ #include <helpers/NRF52Board.h> class MeshTrackerX1Board : public NRF52BoardDCDC { -protected: - uint8_t btn_prev_state; - public: MeshTrackerX1Board() : NRF52Board("X1_OTA") {} void begin(); @@ -35,17 +32,6 @@ public: return "Seeed SenseCAP MeshTracker X1"; } - int buttonStateChanged() { - #ifdef BUTTON_PIN - uint8_t v = digitalRead(BUTTON_PIN); - if (v != btn_prev_state) { - btn_prev_state = v; - return (v == USER_BTN_PRESSED) ? 1 : -1; - } - #endif - return 0; - } - void powerOff() override { #ifdef HAS_GPS digitalWrite(GPS_VRTC_EN, LOW); diff --git a/variants/promicro/PromicroBoard.cpp b/variants/promicro/PromicroBoard.cpp index 7011521b..aba80878 100644 --- a/variants/promicro/PromicroBoard.cpp +++ b/variants/promicro/PromicroBoard.cpp @@ -5,7 +5,6 @@ void PromicroBoard::begin() { NRF52Board::begin(); - btn_prev_state = HIGH; pinMode(PIN_VBAT_READ, INPUT); diff --git a/variants/promicro/PromicroBoard.h b/variants/promicro/PromicroBoard.h index ee16c965..605b0365 100644 --- a/variants/promicro/PromicroBoard.h +++ b/variants/promicro/PromicroBoard.h @@ -9,7 +9,6 @@ class PromicroBoard : public NRF52BoardDCDC { protected: - uint8_t btn_prev_state; float adc_mult = ADC_MULTIPLIER; public: @@ -48,15 +47,4 @@ public: const char* getManufacturerName() const override { return "ProMicro DIY"; } - - 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; - } }; diff --git a/variants/t1000-e/T1000eBoard.cpp b/variants/t1000-e/T1000eBoard.cpp index 0d390f79..1d3ce423 100644 --- a/variants/t1000-e/T1000eBoard.cpp +++ b/variants/t1000-e/T1000eBoard.cpp @@ -5,7 +5,6 @@ void T1000eBoard::begin() { NRF52BoardDCDC::begin(); - btn_prev_state = HIGH; #ifdef BUTTON_PIN pinMode(BATTERY_PIN, INPUT); diff --git a/variants/t1000-e/T1000eBoard.h b/variants/t1000-e/T1000eBoard.h index ba8bf0c1..653bea61 100644 --- a/variants/t1000-e/T1000eBoard.h +++ b/variants/t1000-e/T1000eBoard.h @@ -5,9 +5,6 @@ #include <helpers/NRF52Board.h> class T1000eBoard : public NRF52BoardDCDC { -protected: - uint8_t btn_prev_state; - public: T1000eBoard() : NRF52Board("T1000E_OTA") {} void begin(); @@ -38,17 +35,6 @@ public: 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 == USER_BTN_PRESSED) ? 1 : -1; - } - #endif - return 0; - } - void powerOff() override { #ifdef HAS_GPS digitalWrite(GPS_VRTC_EN, LOW); diff --git a/variants/thinknode_m3/ThinkNodeM3Board.cpp b/variants/thinknode_m3/ThinkNodeM3Board.cpp index ac513ade..518d15bd 100644 --- a/variants/thinknode_m3/ThinkNodeM3Board.cpp +++ b/variants/thinknode_m3/ThinkNodeM3Board.cpp @@ -6,7 +6,6 @@ void ThinkNodeM3Board::begin() { NRF52Board::begin(); - btn_prev_state = HIGH; Wire.begin(); diff --git a/variants/thinknode_m3/ThinkNodeM3Board.h b/variants/thinknode_m3/ThinkNodeM3Board.h index 9e8f4989..bbd69d26 100644 --- a/variants/thinknode_m3/ThinkNodeM3Board.h +++ b/variants/thinknode_m3/ThinkNodeM3Board.h @@ -11,7 +11,6 @@ protected: #if NRF52_POWER_MANAGEMENT void initiateShutdown(uint8_t reason) override; #endif - uint8_t btn_prev_state; public: ThinkNodeM3Board() : NRF52Board("THINKNODE_M3_OTA") {} @@ -31,17 +30,6 @@ public: return "Elecrow ThinkNode M3"; } - 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() override { // turn off all leds, sd_power_system_off will not do this for us digitalWrite(PIN_LED_BLUE, !LED_STATE_ON); diff --git a/variants/thinknode_m4/ThinkNodeM4Board.cpp b/variants/thinknode_m4/ThinkNodeM4Board.cpp index 4a144a3a..281983ae 100644 --- a/variants/thinknode_m4/ThinkNodeM4Board.cpp +++ b/variants/thinknode_m4/ThinkNodeM4Board.cpp @@ -6,7 +6,6 @@ void ThinkNodeM4Board::begin() { NRF52Board::begin(); - btn_prev_state = HIGH; Wire.begin(); battery_serial->begin(4800); diff --git a/variants/thinknode_m4/ThinkNodeM4Board.h b/variants/thinknode_m4/ThinkNodeM4Board.h index c2cae54b..63de1ff2 100644 --- a/variants/thinknode_m4/ThinkNodeM4Board.h +++ b/variants/thinknode_m4/ThinkNodeM4Board.h @@ -9,7 +9,6 @@ protected: #if NRF52_POWER_MANAGEMENT void initiateShutdown(uint8_t reason) override; #endif - uint8_t btn_prev_state; HardwareSerial * battery_serial; uint16_t bat_level_mv = 0; uint8_t bat_level_percent =0; @@ -32,17 +31,6 @@ public: return "Elecrow ThinkNode M4"; } - int buttonStateChanged() { - #ifdef BUTTON_PIN - uint8_t v = digitalRead(BUTTON_PIN); - if (v != btn_prev_state) { - btn_prev_state = v; - return (v == USER_BTN_PRESSED) ? 1 : -1; - } - #endif - return 0; - } - void shutdownPeripherals() override { // shutdown common peripherals NRF52Board::shutdownPeripherals(); From 33eb7434f973ff908927ea22ffead0845739e9b7 Mon Sep 17 00:00:00 2001 From: Amoulier <19624653+Amoulier@users.noreply.github.com> Date: Wed, 28 Oct 2026 18:56:16 -0400 Subject: [PATCH 327/381] Initialize the RadioLib receive error counter --- src/helpers/radiolib/RadioLibWrappers.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/helpers/radiolib/RadioLibWrappers.h b/src/helpers/radiolib/RadioLibWrappers.h index 77dd9311..4b842f3d 100644 --- a/src/helpers/radiolib/RadioLibWrappers.h +++ b/src/helpers/radiolib/RadioLibWrappers.h @@ -29,7 +29,10 @@ protected: virtual void doResetAGC(); public: - RadioLibWrapper(PhysicalLayer& radio, mesh::MainBoard& board) : _radio(&radio), _board(&board), _preamble_sf(0) { n_recv = n_sent = 0; } + RadioLibWrapper(PhysicalLayer& radio, mesh::MainBoard& board) + : _radio(&radio), _board(&board), _preamble_sf(0) { + n_recv = n_sent = n_recv_errors = 0; + } void begin() override; virtual void powerOff() { _radio->sleep(); } From 180c22ba79bbd447ae35614b8a2b3963a69f08ab Mon Sep 17 00:00:00 2001 From: Blake Latchford <github.demote149@passmail.com> Date: Wed, 28 Oct 2026 20:46:00 -0400 Subject: [PATCH 328/381] Fix Generic_ESPNOW_* builds on boards without a LoRa radio Compile out code when the corresponding macro defines are missing. Failing builds: comp_radio_usb, repeatr, room_svr, terminal_chat Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/helpers/ESP32Board.cpp | 2 ++ src/helpers/ESP32Board.h | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/src/helpers/ESP32Board.cpp b/src/helpers/ESP32Board.cpp index d190fca1..4cad7536 100644 --- a/src/helpers/ESP32Board.cpp +++ b/src/helpers/ESP32Board.cpp @@ -63,11 +63,13 @@ void ESP32Board::enterDeepSleep(uint32_t secs) { radio_driver.powerOff(); // Keep LoRa inactive during deepsleep +#ifdef P_LORA_NSS digitalWrite(P_LORA_NSS, HIGH); #if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6) gpio_hold_en((gpio_num_t)P_LORA_NSS); #else rtc_gpio_hold_en((gpio_num_t)P_LORA_NSS); +#endif #endif // Power off GPS if any diff --git a/src/helpers/ESP32Board.h b/src/helpers/ESP32Board.h index cd274cd9..a4798125 100644 --- a/src/helpers/ESP32Board.h +++ b/src/helpers/ESP32Board.h @@ -69,9 +69,11 @@ public: virtual void powerOff() override; void enterDeepSleep(uint32_t secs); +#ifdef P_LORA_DIO_1 uint32_t getIRQGpio() override { return P_LORA_DIO_1; // default for SX1262 } +#endif void sleep(uint32_t secs) override { // Skip if not allow to sleep @@ -82,6 +84,10 @@ public: // Set GPIO wakeup gpio_num_t wakeupPin = (gpio_num_t)getIRQGpio(); + if (wakeupPin == GPIO_NUM_NC) { // no radio IRQ pin to wake on + delay(1); + return; + } // Configure timer wakeup if (secs > 0) { From 1d88a709bd0853794eebcb4c92862010290042c7 Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Mon, 26 Oct 2026 15:04:08 -0400 Subject: [PATCH 329/381] ui: add some parameters to the cli (mostly regarding eink behaviour) --- docs/companion_cli.md | 472 +++++++++++++++++++++ examples/companion_radio/MyMesh.cpp | 102 +++++ examples/companion_radio/NodePrefs.h | 55 +++ examples/companion_radio/ui-new/UITask.cpp | 175 ++++---- examples/companion_radio/ui-new/UITask.h | 2 +- src/helpers/ui/DisplayDriver.h | 4 +- src/helpers/ui/GxEPDDisplay.cpp | 71 ++-- src/helpers/ui/GxEPDDisplay.h | 23 +- variants/lilygo_techo/platformio.ini | 3 +- variants/thinknode_m1/platformio.ini | 3 +- variants/thinknode_m5/platformio.ini | 3 +- variants/thinknode_m8/platformio.ini | 4 +- 12 files changed, 784 insertions(+), 133 deletions(-) create mode 100644 docs/companion_cli.md diff --git a/docs/companion_cli.md b/docs/companion_cli.md new file mode 100644 index 00000000..31a05584 --- /dev/null +++ b/docs/companion_cli.md @@ -0,0 +1,472 @@ +# Companion CLI + +Since version 1.18 meshcore companion radio firmware has a CLI interface, which can be accessed locally (through companion radio protocol) or remotely via the network. + +## Navigation +- [Operational](#operational) +- [Configuration](#configuration) + - [System](#system) + - [Radio](#radio) + - [BLE](#ble) + - [Wifi](#wifi) + - [UI](#ui) + +## Operational + +### Reboot the node +**Usage:** +- `reboot` + +**Note:** No reply is sent. + +--- + +### Power-off the node +**Usage:** +- `poweroff`, or +- `shutdown` + +**Note:** No reply is sent. + +--- + +## Configuration + +### System + +#### View or change this node's name +**Usage:** +- `get name` +- `set name <name>` + +**Parameters:** +- `name`: Node name + +**Set by build flag:** `ADVERT_NAME` + +**Default:** Varies by board + +**Note:** Advertised names can use up to 23 bytes when location is included and 31 bytes otherwise. Emoji and Unicode characters may take more than one byte. Names that exceed the available advert space are truncated at a valid UTF-8 code point boundary. + +--- + +#### View this node's firmware version +**Usage:** `ver` + +--- + +#### Configure this node's timezone +**Usage:** +- `set tz.offset <offset>` +- `get tz.offset` + +**Parameters:** +- `offset`: float value of the offset in hours + +--- + +### Radio + +Radio parameters are common to all roles and handled by `CommonRadioPrefs`. + +#### View or change this node's radio parameters +**Usage:** +- `get radio` +- `set radio <freq>,<bw>,<sf>,<cr>` + +**Parameters:** +- `freq`: Frequency in MHz +- `bw`: Bandwidth in kHz +- `sf`: Spreading factor (5-12) +- `cr`: Coding rate (5-8) + +**Set by build flag:** `LORA_FREQ`, `LORA_BW`, `LORA_SF`, `LORA_CR` + +**Default:** `869.618,62.5,8,5` + +**Note:** Requires reboot to apply + +--- + +#### View or change this node's transmit power +**Usage:** +- `get tx` +- `set tx <dbm>` + +**Parameters:** +- `dbm`: Power level in dBm (1-22) + +**Set by build flag:** `LORA_TX_POWER` + +**Default:** Varies by board + +**Notes:** This setting only controls the power level of the LoRa chip. Some nodes have an additional power amplifier stage which increases the total output. Refer to the node's manual for the correct setting to use. **Setting a value too high may violate the laws in your country.** + +--- + +#### View or change this node's frequency +**Usage:** +- `get freq` +- `set freq <frequency>` + +**Parameters:** +- `frequency`: Frequency in MHz + +**Default:** `869.618` + +**Note:** Requires reboot to apply +**Serial Only:** `set freq <frequency>` + +--- + +#### View or change this node's rx boosted gain mode (SX12xx and LR1110) +**Usage:** +- `get radio.rxgain` +- `set radio.rxgain <state>` + +**Parameters:** + - `state`: `on`|`off` + +**Default:** `on` + +--- + +#### View or change the LoRa FEM receive-path gain state on supported boards +**Usage:** +- `get radio.fem.rxgain` +- `set radio.fem.rxgain <state>` + +**Parameters:** +- `state`: `on`|`off` + +**Notes:** +- This controls the external LoRa FEM receive-path LNA where the board supports it. +- This is separate from `radio.rxgain`, which controls the radio chip receive gain mode. + +--- + +#### View or change the LoRa FEM transmit-path gain state on supported boards +**Usage:** +- `get radio.fem.txgain` +- `set radio.fem.txgain <state>` + +**Parameters:** +- `state`: `on`|`off` + +**Notes:** +- This controls a software-selectable external LoRa FEM transmit gain where the board supports it. +- On Station G3, remove the PA PL1 jumper to allow software control. `on` selects PA PL1 high/short and `off` selects PA PL1 low/open. The PA PL2 hardware jumper determines whether this switches between power levels 1/3 or 2/4. +- Select an operating level and SX1262 transmit power that comply with local RF limits and the Station G3 power-supply requirements. +- The setting is saved immediately, but on Station G3 the level is applied to the hardware at the start of the next transmit, so that the PA supply rail is never re-targeted while the PA is being driven. `get` reports the configured state, which may lead the hardware until the node next transmits. + +--- + +#### View or change the duty cycle limit +**Usage:** +- `get dutycycle` +- `set dutycycle <value>` + +**Parameters:** +- `value`: Duty cycle percentage (1-100) + +**Default:** `50%` (equivalent to airtime factor 1.0) + +**Examples:** +- `set dutycycle 100` — no duty cycle limit +- `set dutycycle 50` — 50% duty cycle (default) +- `set dutycycle 10` — 10% duty cycle +- `set dutycycle 1` — 1% duty cycle (strictest EU requirement) + +> **Note:** Added in firmware v1.15.0 + +--- + +#### View or change the airtime factor (duty cycle limit) +> **Deprecated** as of firmware v1.15.0. Use [`get/set dutycycle`](#view-or-change-the-duty-cycle-limit) instead. + +**Usage:** +- `get af` +- `set af <value>` + +**Parameters:** +- `value`: Airtime factor (0-9). After each transmission, the repeater enforces a silent period of approximately the on-air transmission time multiplied by the value. This results in a long-term duty cycle of roughly 1 divided by (1 plus the value). For example: + - `af = 1` → ~50% duty + - `af = 2` → ~33% duty + - `af = 3` → ~25% duty + - `af = 9` → ~10% duty + You are responsible for choosing a value that is appropriate for your jurisdiction and channel plan (for example EU 868 Mhz 10% duty cycle regulation). + +**Default:** `1.0` + +--- + +#### View or change the local interference threshold +**Usage:** +- `get int.thresh` +- `set int.thresh <value>` + +**Parameters:** +- `value`: Interference threshold value + +**Default:** `0.0` + +--- + +#### Enable or disable hardware Channel Activity Detection (CAD) +**Usage:** +- `get cad` +- `set cad <on|off>` + +**Description:** When enabled, the radio performs a hardware Channel Activity Detection scan before transmitting and defers if the channel is busy. Runs independently of `int.thresh` — either, both, or none may be active. + +**Parameters:** +- `on|off`: Enable or disable hardware CAD + +**Default:** `off` + +--- + +#### View or change the AGC Reset Interval +**Usage:** +- `get agc.reset.interval` +- `set agc.reset.interval <value>` + +**Parameters:** +- `value`: Interval in seconds, 0-1020, rounded down to a multiple of 4 (17 becomes 16). 0 to disable. + +**Default:** `0.0` + +--- + +#### Enable or disable Multi-Acks support +**Usage:** +- `get multi.acks` +- `set multi.acks <state>` + +**Parameters:** +- `state`: `0` (disable) or `1` (enable) + +**Default:** `0` + +--- + +#### View or change this node's advert path hash size +**Usage:** +- `get path.hash.mode` +- `set path.hash.mode <value>` + +**Parameters:** +- `value`: Path hash size (0-2) + - `0`: 1 Byte hash size (256 unique ids)[64 max flood] + - `1`: 2 Byte hash size (65,536 unique ids)[32 max flood] + - `2`: 3 Byte hash size (16,777,216 unique ids)[21 max flood] + - `3`: DO NOT USE (Reserved) + +**Default:** `0` + +**Note:** the 'path.hash.mode' sets the low-level ID/hash encoding size used when the repeater adverts. This setting has no impact on what packet ID/hash size this repeater forwards, all sizes should be forwarded on firmware >= 1.14. This feature was added in firmware 1.14 +#### View or change the retransmit delay factor for flood traffic +**Usage:** +- `get txdelay` +- `set txdelay <value>` + +**Parameters:** +- `value`: Transmit delay factor (0-2) + +**Default:** `0.5` + +**Note:** When multiple nearby repeaters all hear the same flood packet, each waits a random amount of time before retransmitting to avoid simultaneous collisions. This factor scales the size of that random window. Higher values reduce collision risk at the cost of added latency. `0` disables the window entirely. + +--- + +#### View or change the retransmit delay factor for direct traffic +**Usage:** +- `get direct.txdelay` +- `set direct.txdelay <value>` + +**Parameters:** +- `value`: Direct transmit delay factor (0-2) + +**Default:** `0.3` (Repeater) - `0.2` (Room Server, Sensor) + +**Note:** Same collision-avoidance random window as `txdelay`, but applied to direct (non-flood, routed) traffic. The default is lower because direct packets are addressed to a specific next hop, so far fewer nodes compete to retransmit them. + +--- + +#### [Experimental] View or change the processing delay for received traffic +**Usage:** +- `get rxdelay` +- `set rxdelay <value>` + +**Parameters:** +- `value`: Receive delay base (0-20) + +**Default:** `0.0` + +**Note:** When enabled, repeaters that received a flood packet with a weak signal are held in a delay queue before processing, while those that received it with a strong signal process it immediately. This gives strong-signal paths forwarding priority. By the time weak-signal nodes process their copy, the packet may have already propagated and will be suppressed as a duplicate, reducing redundant retransmissions. + +--- + +### BLE + +#### Change BLE PIN +**Usage:** +- `set pin <pin>` + +**Parameters:** +- `pin`: New BLE PIN + +**Set by build flag:** `BLE_PIN_CODE` + +--- + +### Wifi + +#### Get status +**Usage:** +- `get wifi.status` +- `get wifi.ip` + +--- + +#### Toggle +**Usage:** +- `set wifi.enabled <value>` +- `get wifi.enabled` + +**Parameters:** +- `value`: `0` (disable) or `1` (enable) + +--- + +#### Set SSID +**Usage:** +- `set wifi.ssid <value>` +- `get wifi.ssid` + +**Parameters:** +- `value`: ssid as a string + +--- + +#### Set password +**Usage:** +- `set wifi.pwd <value>` +- `get wifi.pwd` + +**Parameters:** +- `value`: password string + +--- + +### UI + +#### Show clock +**Usage:** +- `set ui.show_clock <state>` +- `get ui.show_clock` + +**Parameters:** +- `state`: `0` (disable) or `1` (enable) + +**Default:** `0` (or `UI_SHOW_CLOCK` build flag) + +--- + +#### Node discovery screen shows nodes names +**Usage:** +- `set ui.nd_name <state>` +- `get ui.nd_name` + +**Parameters:** +- `state`: `1` (show name) or `0` (show pubkey_prefix) + +**Default:** `1` + +**Note:** When showing name, there is not always enough space to draw both incoming and outgoing snr values. + +--- + +#### Auto-off screen +**Usage:** +- `set ui.auto_off_delay <delay>` +- `get ui.auto_off_delay` + +**Parameters:** +- `delay`: in seconds (`0` means always on) + +**Default:** `15` (or set by `AUTO_OFF_MILLIS` build flag (in ms)) + +**Note:** +On e-ink displays, when turned off, the screen is not necessarily blanked, see `ui.auto_off_blank` and `ui.backlight_delay`. + +When screen is not blanked, it is not refreshed any more. To let the user aware of that, a sleep icon is shown. + +--- + +#### Display backlight timeout +**Usage:** +- `set ui.backlight_delay <delay>` +- `get ui.backlight_delay` + +**Parameters:** +- `delay`: in seconds + - `0` means no timeout + - `-2` means always off + - `-1` means always on + +**Note:** +When set to `0`, backlight can only be triggered using backlight btn. + +--- + +#### When to turn backlight on +**Usage:** +- `set ui.backlight_on_keys <state>` +- `get ui.backlight_on_keys` +- `set ui.backlight_on_msgs <state>` +- `get ui.backlight_on_msgs` + +**Parameters:** +- `state`: `0` (disable) or `1` (enable) + +**Default:** +- `ui.backlight_on_msgs = 0` +- `ui.backlight_on_keys = 0` if there is a backlight button on the board, else `1` + +**Note:** +By default backlight is triggered by backlight button if present (as long as the button is pressed backlight is on, and is turned off after a delay). +These toggles permits to toggle backlight when keys are pressed or when a message arrives (it acts as a notification signal). +If `backlight_delay` is set to `0` then this setting has no effect, backlight won't be turned on. + +--- + +#### Control if eink screen should be blanked +**Usage:** +- `set ui.auto_off_blank <state>` +- `get ui.auto_off_blank` + +**Parameters:** +- `state`: `0` (disable) or `1` (enable) + +**Default:** `0` (or set by `UI_SCREENOFF_BLANK` build flag) + +**Note:** +If disabled, when screen is shut the displays stays on screen and is not updated (an sleep icons covers battery to show the screen is sleeping). + +When screen is blanked, the controller is also put into hibernation, which should preserve the screen a little and some battery ... + +--- + +#### Maximum number of partial refreshes +**Usage:** +- `set ui.max_partial <value>` +- `get ui.max_partial` + +**Parmeters:** +- `value`: max partial refreshes before doing a full refresh + +**Default:** 0 (no partial refresh or set by `EINK_MAX_PARTIAL_REFRESH` build flag) + +**Note:** +Forcing full refresh helps revives the screen when some tearing appears (under certain environmental conditions). If you see some tearing appearing, you can force full refresh on your screen manually by double clicking the backlight button. If tearing reappears often, use this setting to force full refresh every `value` partial refreshes. \ No newline at end of file diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 6112b2db..8a8f7f1d 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2209,6 +2209,108 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* } return true; } +#ifdef DISPLAY_CLASS + if (memcmp(command, "set ui.show_clock", 17) == 0) { + _prefs.ui_show_clock = atoi(&command[17]) ? 1 : 0; + savePrefs(); + sprintf(reply, "> now %d", _prefs.ui_show_clock); + return true; + } + if (memcmp(command, "set ui.auto_off_delay", 21) == 0) { + _prefs.ui_auto_off_delay = atoi(&command[21]); + savePrefs(); + sprintf(reply, "> now %d seconds", _prefs.ui_auto_off_delay); + return true; + } + if (memcmp(command, "set ui.backlight_delay", 22) == 0) { + _prefs.ui_backlight_delay = atoi(&command[22]); + savePrefs(); + if (_prefs.ui_backlight_delay >= 0) + sprintf(reply, "> now %d seconds", _prefs.ui_backlight_delay); + else if (_prefs.ui_backlight_delay == -1) + sprintf(reply, "> now always on (-1)"); + else + sprintf(reply, "> now disabled (<-1)"); + return true; + } + if (memcmp(command, "set ui.backlight_on_keys", 24) == 0) { + _prefs.ui_backlight_on_keys = atoi(&command[24]); + savePrefs(); + sprintf(reply, "> now %d", _prefs.ui_backlight_on_keys); + return true; + } + if (memcmp(command, "set ui.backlight_on_msgs", 24) == 0) { + _prefs.ui_backlight_on_msgs = atoi(&command[24]); + savePrefs(); + sprintf(reply, "> now %d", _prefs.ui_backlight_on_msgs); + return true; + } + if (memcmp(command, "set ui.auto_off_blank", 21) == 0) { + _prefs.ui_auto_off_blank = atoi(&command[21]); + savePrefs(); + sprintf(reply, "> now %d", _prefs.ui_auto_off_blank); + return true; + } + if (memcmp(command, "set ui.auto_off_keep_msgs", 25) == 0) { + _prefs.ui_auto_off_keep_msgs = atoi(&command[25]); + savePrefs(); + sprintf(reply, "> now %d", _prefs.ui_auto_off_keep_msgs); + return true; + } + if (memcmp(command, "set ui.max_partial", 18) == 0) { + _prefs.ui_max_partial = atoi(&command[18]); + savePrefs(); + sprintf(reply, "> now %d (applied at next screen wakeup)", _prefs.ui_max_partial); + return true; + } + if (memcmp(command, "set ui.nd_name", 14) == 0) { + _prefs.ui_nd_name = atoi(&command[14]); + savePrefs(); + sprintf(reply, "> ui.nd_name is now %d", _prefs.ui_nd_name); + return true; + } + if (memcmp(command, "get ui.show_clock", 17) == 0) { + sprintf(reply, "> %d", _prefs.ui_show_clock); + return true; + } + if (memcmp(command, "get ui.auto_off_delay", 21) == 0) { + sprintf(reply, "> %d seconds", _prefs.ui_auto_off_delay); + return true; + } + if (memcmp(command, "get ui.backlight_delay", 22) == 0) { + if (_prefs.ui_backlight_delay >= 0) + sprintf(reply, "> %d seconds", _prefs.ui_backlight_delay); + else if (_prefs.ui_backlight_delay == -1) + sprintf(reply, "> always on (-1)"); + else + sprintf(reply, "> disabled (<-1)"); + return true; + } + if (memcmp(command, "get ui.backlight_on_keys", 24) == 0) { + sprintf(reply, "> %d", _prefs.ui_backlight_on_keys); + return true; + } + if (memcmp(command, "get ui.backlight_on_msgs", 24) == 0) { + sprintf(reply, "> %d", _prefs.ui_backlight_on_msgs); + return true; + } + if (memcmp(command, "get ui.auto_off_blank", 21) == 0) { + sprintf(reply, "> %d", _prefs.ui_auto_off_blank); + return true; + } + if (memcmp(command, "get ui.auto_off_keep_msgs", 25) == 0) { + sprintf(reply, "> %d", _prefs.ui_auto_off_keep_msgs); + return true; + } + if (memcmp(command, "get ui.max_partial", 18) == 0) { + sprintf(reply, "> %d", _prefs.ui_max_partial); + return true; + } + if (memcmp(command, "get ui.nd_name", 14) == 0) { + sprintf(reply, "> %d", _prefs.ui_nd_name); + return true; + } +#endif return false; // not handled } diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index 1cc5b501..c5d1df04 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -58,6 +58,34 @@ public: // use ssid from prefs, or fallback to ssid from build flags const char* getWifiSSID() const { return wifi_ssid[0] ? wifi_ssid : WIFI_SSID; } #endif +#ifdef DISPLAY_CLASS + #ifndef UI_SHOW_CLOCK + #define UI_SHOW_CLOCK 0 + #endif + #ifndef AUTO_OFF_MILLIS + #define AUTO_OFF_MILLIS 15000 + #endif + #ifndef EINK_MAX_PARTIAL_REFRESH + #define EINK_MAX_PARTIAL_REFRESH 0 + #endif + uint8_t ui_show_clock = UI_SHOW_CLOCK; + uint32_t ui_auto_off_delay = AUTO_OFF_MILLIS / 1000; + int32_t ui_backlight_delay = 5; + #if defined(BACKLIGHT_BTN) + uint8_t ui_backlight_on_keys = 0; + #else + uint8_t ui_backlight_on_keys = 1; + #endif + uint8_t ui_backlight_on_msgs = 0; +#ifdef UI_SCREENOFF_BLANK + uint8_t ui_auto_off_blank = 1; +#else + uint8_t ui_auto_off_blank = 0; +#endif + uint8_t ui_auto_off_keep_msgs = 1; + uint8_t ui_max_partial = EINK_MAX_PARTIAL_REFRESH; + uint8_t ui_nd_name = 1; +#endif private: class RadioPrefs : public CommonRadioPrefs { @@ -189,6 +217,27 @@ private: WiFiPrefs wifi; #endif +#ifdef DISPLAY_CLASS + class UI_Prefs : public ConfigSerializer { + NodePrefs* _parent; + protected: + void structure() override { + def("show_clock", _parent->ui_show_clock); + def("auto_off", _parent->ui_auto_off_delay); + def("bl_dly", _parent->ui_backlight_delay); + def("bl_keys", _parent->ui_backlight_on_keys); + def("bl_msgs", _parent->ui_backlight_on_msgs); + def("max_partial", _parent->ui_max_partial); + def("off_blank", _parent->ui_auto_off_blank); + def("off_keep_msgs", _parent->ui_auto_off_keep_msgs); + def("nd_name", _parent->ui_nd_name); + } + public: + UI_Prefs(NodePrefs* parent) : _parent(parent) {} + }; + UI_Prefs ui; +#endif + protected: void structure() override { def("name", node_name, sizeof(node_name)); @@ -203,12 +252,18 @@ protected: def("custom", custom); #ifdef ENABLE_WIFI_INTERFACE def("wifi", wifi); +#endif +#ifdef DISPLAY_CLASS + def("ui", ui); #endif } public: NodePrefs() : radio(this), gps(this), companion(this), custom(&radio) #ifdef ENABLE_WIFI_INTERFACE , wifi(this) +#endif +#ifdef DISPLAY_CLASS + , ui(this) #endif { node_name[0] = 0; diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index aced739d..89008d7a 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -122,7 +122,6 @@ class HomeScreen : public UIScreen { uint32_t disc_node_req_tag = 0; uint32_t disc_nodes_count = 0; uint32_t discovery_req_time = 0; - bool discovery_disp_names = true; // by default desplay names if available (removes SNR_O) #endif void renderBatteryIndicator(DisplayDriver& display, uint16_t batteryMilliVolts) { @@ -293,17 +292,17 @@ public: sprintf(tmp, "MSG: %d", _task->getMsgCount()); display.drawTextCentered(display.width() / 2, 22, tmp); #endif - #ifdef UI_SHOW_CLOCK - display.setTextSize(3); - uint32_t now = _rtc->getCurrentTime(); - now += (int32_t)(_node_prefs->tz_offset * 3600); - DateTime dt (now); - sprintf(tmp, "%02d:%02d", dt.hour(), dt.minute()); - display.drawTextCentered(display.width() / 2, 60, tmp); - display.setTextSize(1); - sprintf(tmp, "%02d/%02d/%d", dt.day(), dt.month(), dt.year()); - display.drawTextCentered(display.width() / 2, 80, tmp); - #endif + if (_node_prefs->ui_show_clock) { + display.setTextSize(3); + uint32_t now = _rtc->getCurrentTime(); + now += (int32_t)(_node_prefs->tz_offset * 3600); + DateTime dt (now); + sprintf(tmp, "%02d:%02d", dt.hour(), dt.minute()); + display.drawTextCentered(display.width() / 2, 60, tmp); + display.setTextSize(1); + sprintf(tmp, "%02d/%02d/%d", dt.day(), dt.month(), dt.year()); + display.drawTextCentered(display.width() / 2, 80, tmp); + } #ifdef ENABLE_WIFI_INTERFACE IPAddress ip = WiFi.localIP(); snprintf(tmp, sizeof(tmp), "IP: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); @@ -313,21 +312,20 @@ public: if (_task->hasConnection()) { display.setColor(UIColor::warning_txt); display.setTextSize(1); - #ifdef UI_SHOW_CLOCK - display.drawTextCentered(display.width() / 2, 110, "< Connected >"); - #else - display.drawTextCentered(display.width() / 2, 43, "< Connected >"); - #endif + if (_node_prefs->ui_show_clock) + display.drawTextCentered(display.width() / 2, 110, "< Connected >"); + else + display.drawTextCentered(display.width() / 2, 43, "< Connected >"); } else if (the_mesh.getBLEPin() != 0) { // BT pin display.setColor(UIColor::warning_txt); sprintf(tmp, "Pin:%d", the_mesh.getBLEPin()); - #ifdef UI_SHOW_CLOCK - display.setTextSize(1); - display.drawTextCentered(display.width() / 2, 110, tmp); - #else - display.setTextSize(2); - display.drawTextCentered(display.width() / 2, 43, tmp); - #endif + if (_node_prefs->ui_show_clock) { + display.setTextSize(1); + display.drawTextCentered(display.width() / 2, 110, tmp); + } else { + display.setTextSize(2); + display.drawTextCentered(display.width() / 2, 43, tmp); + } } } else if (_page == HomePage::RECENT) { the_mesh.getRecentlyHeard(recent, UI_RECENT_LIST_SIZE); @@ -518,7 +516,7 @@ public: for (int i = 0; i < count; i++, y += 11) { char name[32]; auto a = &discovered[i]; - if ((a->name[0] == 0) || !discovery_disp_names) { + if ((a->name[0] == 0) || !_node_prefs->ui_nd_name) { mesh::Utils::toHex(name, a->pubkey_prefix, 4); } else { strncpy(name, a->name, 32); @@ -618,7 +616,7 @@ public: return true; } if (c == KEY_SELECT && _page == HomePage::DISCOVERY) { - discovery_disp_names = !discovery_disp_names; + _node_prefs->ui_nd_name = !_node_prefs->ui_nd_name; return true; } #endif @@ -726,7 +724,6 @@ public: void UITask::begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* node_prefs) { _display = display; _sensors = sensors; - _auto_off = millis() + AUTO_OFF_MILLIS; #if defined(PIN_USER_BTN) user_btn.begin(); @@ -739,9 +736,11 @@ void UITask::begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* no #endif _node_prefs = node_prefs; + _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; + _backlight_off = millis() + _node_prefs->ui_backlight_delay * 1000; if (_display != NULL) { - _display->turnOn(); + _display->turnOn(_node_prefs->ui_max_partial); } #ifdef PIN_BUZZER @@ -807,11 +806,14 @@ void UITask::onMessageRecv(mesh::Packet *pkt, const ContactInfo &from, uint8_t t if (_display != NULL) { if (!_display->isOn() && !hasConnection()) { - _display->turnOn(); + _display->turnOn(_node_prefs->ui_max_partial); } if (_display->isOn()) { - _auto_off = millis() + AUTO_OFF_MILLIS; // extend the auto-off timer - _next_refresh = 100; // trigger refresh + _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; // extend the auto-off timer + _next_refresh = 100; // trigger refresh + if (_node_prefs->ui_backlight_on_msgs) { + _backlight_off = millis() + _node_prefs->ui_backlight_delay * 1000; + } } } @@ -827,10 +829,10 @@ void UITask::onChannelMessageRecv(mesh::Packet *pkt, ChannelDetails& channel_det if (_display != NULL) { if (!_display->isOn() && !hasConnection()) { - _display->turnOn(); + _display->turnOn(_node_prefs->ui_max_partial); } if (_display->isOn()) { - _auto_off = millis() + AUTO_OFF_MILLIS; // extend the auto-off timer + _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; // extend the auto-off timer _next_refresh = 100; // trigger refresh } } @@ -909,9 +911,7 @@ void UITask::shutdown(bool restart){ _board->reboot(); } else { if (_display->isEink()) { - _display->blankScreen(); - _display->turnOff(); - _display->powerOff(); + _display->turnOff(true); } // Power off board including radio, display, GPS and components _board->powerOff(); @@ -957,9 +957,7 @@ void UITask::loop() { if (ev == BUTTON_EVENT_CLICK) { c = checkDisplayOn(KEY_ENTER); } else if (ev == BUTTON_EVENT_LONG_PRESS) { - display.blankScreen(); - display.turnOff(); - display.powerOff(); + display.turnOff(true); } else if (ev == BUTTON_EVENT_DOUBLE_CLICK) { c = handleDoubleClick(KEY_SELECT); } else if (ev == BUTTON_EVENT_TRIPLE_CLICK) { @@ -979,11 +977,11 @@ void UITask::loop() { #endif #if defined(UI_HAS_ROTARY_INPUT) RotaryInputEvent rotaryEv = rotary_input.poll(); - if (c == 0 && _display != NULL && _display->isOn()) { + if (c == 0 && _display != NULL) { if (rotaryEv == RotaryInputEvent::Next) { - c = KEY_NEXT; + c = checkDisplayOn(KEY_NEXT); } else if (rotaryEv == RotaryInputEvent::Prev) { - c = KEY_PREV; + c = checkDisplayOn(KEY_PREV); } } #endif @@ -1002,39 +1000,52 @@ void UITask::loop() { _analogue_pin_read_millis = millis(); } #endif +#if defined(DISP_BACKLIGHT) || defined(EXP_PIN_BACKLIGHT) #if defined(BACKLIGHT_BTN) if (millis() > next_backlight_btn_check) { if (backlight_btn.isPressed()) { if (!_display->isOn()) { - _display->turnOn(); + _display->turnOn(_node_prefs->ui_max_partial); _next_refresh = 0; } - _auto_off = millis() + AUTO_OFF_MILLIS; // extend auto-off timer - backlight_btn_pressed_at = millis(); // still pressed + _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; // extend auto-off timer + _backlight_off = millis() + _node_prefs->ui_backlight_delay * 1000; // extend auto_off for backlight } - bool touch_state = (millis() - backlight_btn_pressed_at > 5000); - // Backlight button events - int bev = backlight_btn.check(); - if (bev == BUTTON_EVENT_DOUBLE_CLICK) { - _display->forceFullRefresh(); - } else if (bev == BUTTON_EVENT_TRIPLE_CLICK) { - _display->blankScreen(); - _display->turnOff(); - _display->powerOff(); - backlight_btn_pressed_at = 0; - } -#if defined(DISP_BACKLIGHT) - digitalWrite(DISP_BACKLIGHT, !touch_state); -#elif defined(EXP_PIN_BACKLIGHT) - expander.digitalWrite(EXP_PIN_BACKLIGHT, !touch_state); -#endif next_backlight_btn_check = millis() + 100; } + int bev = backlight_btn.check(); + if (bev == BUTTON_EVENT_DOUBLE_CLICK) { + _display->forceFullRefresh(); + } else if (bev == BUTTON_EVENT_TRIPLE_CLICK) { + _display->turnOff(true); + _backlight_off = 0; + } +#endif + + bool backlight_state; + if (_node_prefs->ui_backlight_delay == -1) { + backlight_state = true; + } else if (_node_prefs->ui_backlight_delay < -1) { + backlight_state = false; + } else if (_node_prefs->ui_backlight_delay == 0) { + backlight_state = false; + #ifdef BACKLIGHT_BTN + backlight_state = backlight_btn.isPressed(); + #endif + } else { + backlight_state = (millis() < _backlight_off); + } + +#if defined(DISP_BACKLIGHT) + digitalWrite(DISP_BACKLIGHT, backlight_state); +#elif defined(EXP_PIN_BACKLIGHT) + expander.digitalWrite(EXP_PIN_BACKLIGHT, backlight_state); +#endif #endif if (c != 0 && curr) { curr->handleInput(c); - _auto_off = millis() + AUTO_OFF_MILLIS; // extend auto-off timer + _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; // extend auto-off timer _next_refresh = 100; // trigger refresh } @@ -1065,26 +1076,27 @@ void UITask::loop() { } _display->endFrame(); } -#if AUTO_OFF_MILLIS > 0 + if (_node_prefs->ui_auto_off_delay > 0) { #ifdef KEEP_DISPLAY_ON_USB - // Opt-in: refresh the auto-off deadline while externally powered, so the - // timer counts from the moment external power is removed. Off by default - // because OLED panels burn in quickly; only enable for LCD targets or - // where the display is replaceable. - if (board.isExternalPowered()) { - _auto_off = millis() + AUTO_OFF_MILLIS; - } + // Opt-in: refresh the auto-off deadline while externally powered, so the + // timer counts from the moment external power is removed. Off by default + // because OLED panels burn in quickly; only enable for LCD targets or + // where the display is replaceable. + if (board.isExternalPowered()) { + _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; + } #endif - if (millis() > _auto_off) { - #ifdef EINK_SCREENOFF_BLANK - if (curr != msg_preview) { // don't blank if messages are waiting - _display->blankScreen(); - _display->powerOff(); + if (millis() > _auto_off) { + if (_node_prefs->ui_auto_off_blank && + !(_node_prefs->ui_auto_off_keep_msgs + && curr == msg_preview)) { + // don't blank if messages are waiting + _display->turnOff(true); + } else { + _display->turnOff(); } - #endif - _display->turnOff(); + } } -#endif } #ifdef PIN_VIBRATION @@ -1116,10 +1128,13 @@ void UITask::loop() { char UITask::checkDisplayOn(char c) { if (_display != NULL) { if (!_display->isOn()) { - _display->turnOn(); // turn display on and consume event + _display->turnOn(_node_prefs->ui_max_partial); // turn display on and consume event c = 0; } - _auto_off = millis() + AUTO_OFF_MILLIS; // extend auto-off timer + _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; // extend auto-off timer + if (_node_prefs->ui_backlight_on_keys) { + _backlight_off = millis() + _node_prefs->ui_backlight_delay * 1000; + } _next_refresh = 0; // trigger refresh } return c; diff --git a/examples/companion_radio/ui-new/UITask.h b/examples/companion_radio/ui-new/UITask.h index 4d44bfe1..61831488 100644 --- a/examples/companion_radio/ui-new/UITask.h +++ b/examples/companion_radio/ui-new/UITask.h @@ -62,7 +62,7 @@ class UITask : public AbstractUITask { int _msgcount; unsigned long ui_started_at, next_batt_chck; unsigned long next_backlight_btn_check = 0; - unsigned long backlight_btn_pressed_at = 0; + unsigned long _backlight_off = 0; #ifdef PIN_STATUS_LED int led_state = 0; int next_led_change = 0; diff --git a/src/helpers/ui/DisplayDriver.h b/src/helpers/ui/DisplayDriver.h index 58147aa0..0e41dab5 100644 --- a/src/helpers/ui/DisplayDriver.h +++ b/src/helpers/ui/DisplayDriver.h @@ -25,9 +25,9 @@ public: virtual bool isEink() { return false; } // default to non-eink, override in eink drivers virtual void forceFullRefresh() {} // next refresh will be full for eink virtual void turnOn() = 0; + virtual void turnOn(int max_partial) { turnOn(); } virtual void turnOff() = 0; - virtual void blankScreen() {} // to cleanly erase screen before turning off - virtual void powerOff() {} + virtual void turnOff(bool blank) { turnOff(); } virtual void clear() = 0; virtual void startFrame(ColorVal bkg = UIColor::window_bkg) = 0; virtual void setTextSize(int sz) = 0; diff --git a/src/helpers/ui/GxEPDDisplay.cpp b/src/helpers/ui/GxEPDDisplay.cpp index ce09423e..d7f9562b 100644 --- a/src/helpers/ui/GxEPDDisplay.cpp +++ b/src/helpers/ui/GxEPDDisplay.cpp @@ -1,11 +1,6 @@ #include "GxEPDDisplay.h" -#ifdef EXP_PIN_BACKLIGHT - #include <PCA9557.h> - extern PCA9557 expander; -#endif - #ifndef DISPLAY_ROTATION #define DISPLAY_ROTATION 3 #endif @@ -52,7 +47,7 @@ bool GxEPDDisplay::begin() { } display.setPartialWindow(0, 0, display.width(), display.height()); - resetPartialRefreshCounter(); + _partial_refresh_count = 0; #if DISP_BACKLIGHT digitalWrite(DISP_BACKLIGHT, LOW); @@ -65,26 +60,43 @@ bool GxEPDDisplay::begin() { void GxEPDDisplay::turnOn() { if (!_init) begin(); -#if defined(DISP_BACKLIGHT) && !defined(BACKLIGHT_BTN) - digitalWrite(DISP_BACKLIGHT, HIGH); -#elif defined(EXP_PIN_BACKLIGHT) && !defined(BACKLIGHT_BTN) - expander.digitalWrite(EXP_PIN_BACKLIGHT, HIGH); -#endif if (!_isOn) { _isOn = true; } } -void GxEPDDisplay::powerOff() { - display.hibernate(); +void GxEPDDisplay::turnOn(int max_partial) { + setMaxPartialRefresh(max_partial); + turnOn(); } -void GxEPDDisplay::turnOff() { // Only stops refresh -#if defined(DISP_BACKLIGHT) && !defined(BACKLIGHT_BTN) - digitalWrite(DISP_BACKLIGHT, LOW); -#elif defined(EXP_PIN_BACKLIGHT) && !defined(BACKLIGHT_BTN) - expander.digitalWrite(EXP_PIN_BACKLIGHT, LOW); -#endif +// 24x24 sleep icon, MSB-first (matches GxEPDDisplay::drawXbm) +static const uint8_t sleep_icon_24x24[] = { + 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00, 0xe0, 0x0e, 0x03, 0xc0, 0x18, + 0x0f, 0x80, 0x70, 0x1f, 0x80, 0xff, 0x3f, 0x80, 0xff, 0x3f, 0x00, 0x00, + 0x7f, 0x3f, 0x00, 0x7f, 0x3f, 0x00, 0xff, 0x0e, 0x00, 0xff, 0x1c, 0x7c, + 0xff, 0xbf, 0x7c, 0xff, 0xbf, 0x38, 0xff, 0xc0, 0x7c, 0xff, 0xe0, 0x7c, + 0xff, 0xf0, 0x00, 0x7f, 0xfc, 0x00, 0x7f, 0xff, 0xf8, 0x3f, 0xff, 0xf0, + 0x1f, 0xff, 0xf0, 0x0f, 0xff, 0xe0, 0x07, 0xff, 0x80, 0x01, 0xff, 0x00 +}; + +void GxEPDDisplay::drawSleepIcon() { + const int W = 24, H = 24; + int x = (int)(display.width() / scale_x) - W; // top-right, logical coordinates + int y = 0; + + display.fillRect((x - 5) * scale_x - 1, y * scale_y, (W+5) * scale_x + 2, (H-2) * scale_y + 1, GxEPD_WHITE); + _curr_color = GxEPD_BLACK; + drawXbm(x, y, sleep_icon_24x24, W, H); + display.display(true); +} + +void GxEPDDisplay::turnOff(bool blank) { + if (blank) { + blankScreen(); + } else { + drawSleepIcon(); + } _isOn = false; last_display_crc_value=0; } @@ -94,8 +106,10 @@ void GxEPDDisplay::blankScreen() { // no full refresh needed at wakeup display.clearScreen(0xFF); // Clears microcontroller side RAM display.writeScreenBuffer(0xFF); // Forces 0xFF (White) into the display controller's history registers - resetPartialRefreshCounter(); - last_display_crc_value=0; + _partial_refresh_count = 0; + last_display_crc_value = 0; + // we can hibernate as screen has been cleaned + display.hibernate(); } void GxEPDDisplay::clear() { @@ -108,15 +122,18 @@ void GxEPDDisplay::startFrame(ColorVal bkg) { display.fillScreen(bkg); display.setTextColor(_curr_color = UIColor::primary_txt); display_crc.reset(); - if (_cycles_before_full_refresh != 0) { - display.setPartialWindow(0, 0, display.width(), display.height()); - } else { + if (_force_full_refresh + || (_max_partial_refresh > 0 + && _partial_refresh_count >= _max_partial_refresh)) { // forces a full wipe of the screen ... display.clearScreen(0xFF); // Clears microcontroller side RAM display.writeScreenBuffer(0xFF); // Forces 0xFF (White) into the display controller's history registers // we'll need a partial refresh after that (whatever crc value is) last_display_crc_value = 0; - resetPartialRefreshCounter(); + _partial_refresh_count = 0; + _force_full_refresh = false; + } else { + display.setPartialWindow(0, 0, display.width(), display.height()); } } @@ -223,9 +240,7 @@ void GxEPDDisplay::endFrame() { uint32_t crc = display_crc.finalize(); if (crc != last_display_crc_value) { display.display(true); - if (_cycles_before_full_refresh > 0) { - _cycles_before_full_refresh--; - } + _partial_refresh_count++; } last_display_crc_value = crc; } diff --git a/src/helpers/ui/GxEPDDisplay.h b/src/helpers/ui/GxEPDDisplay.h index 46274402..9d918443 100644 --- a/src/helpers/ui/GxEPDDisplay.h +++ b/src/helpers/ui/GxEPDDisplay.h @@ -16,12 +16,6 @@ #include "DisplayDriver.h" -#ifndef EINK_MAX_PARTIAL_REFRESH - // 60 to prevent ghosting when refreshing every minute ... - // set to -1 to disable the counter - #define EINK_MAX_PARTIAL_REFRESH -1 -#endif - class GxEPDDisplay : public DisplayDriver { #if defined(EINK_DISPLAY_MODEL) @@ -42,8 +36,9 @@ class GxEPDDisplay : public DisplayDriver { uint16_t _curr_color; CRC32 display_crc; int last_display_crc_value = 0; - int _cycles_before_full_refresh; - int max_partial_refresh = EINK_MAX_PARTIAL_REFRESH; // so this can be changed by an option after + bool _force_full_refresh = false; + int _partial_refresh_count = 0; + int _max_partial_refresh = 0; public: #if defined(EINK_DISPLAY_MODEL) @@ -56,12 +51,13 @@ public: bool isOn() override { return _isOn; } bool isEink() override { return true; } - void forceFullRefresh() override { _cycles_before_full_refresh = 0; }; - void resetPartialRefreshCounter() { _cycles_before_full_refresh = max_partial_refresh; }; + void forceFullRefresh() override { _force_full_refresh = true; } + void turnOn(int max_partial) override; void turnOn() override; - void turnOff() override; - void blankScreen() override; - void powerOff() override; + void turnOff(bool blank) override; + void turnOff() override { turnOff(false); } + virtual void blankScreen(); + virtual void setMaxPartialRefresh(int count) {_max_partial_refresh = count; } void clear() override; void startFrame(ColorVal bkg = UIColor::window_bkg) override; void setTextSize(int sz) override; @@ -71,6 +67,7 @@ public: void fillRect(int x, int y, int w, int h) override; void drawRect(int x, int y, int w, int h) override; void drawXbm(int x, int y, const uint8_t* bits, int w, int h) override; + void drawSleepIcon(); uint16_t getTextWidth(const char* str) override; void endFrame() override; }; diff --git a/variants/lilygo_techo/platformio.ini b/variants/lilygo_techo/platformio.ini index ba39549e..896e42a6 100644 --- a/variants/lilygo_techo/platformio.ini +++ b/variants/lilygo_techo/platformio.ini @@ -40,8 +40,7 @@ build_flags = ${nrf52_base.build_flags} -D EINK_SCREENOFF_BLANK -D UI_RECENT_LIST_SIZE=9 -D UI_MSG_PREVIEW_SIZE=165 - -D EINK_MAX_PARTIAL_REFRESH=60 - -D AUTO_OFF_MILLIS=900000 + -D AUTO_OFF_MILLIS=300000 -D BACKLIGHT_BTN=PIN_BUTTON2 build_src_filter = ${nrf52_base.build_src_filter} +<helpers/*.cpp> diff --git a/variants/thinknode_m1/platformio.ini b/variants/thinknode_m1/platformio.ini index 7c620e2e..03b0eb4e 100644 --- a/variants/thinknode_m1/platformio.ini +++ b/variants/thinknode_m1/platformio.ini @@ -26,14 +26,13 @@ build_flags = ${nrf52_base.build_flags} -D P_LORA_TX_LED=13 -D UI_RECENT_LIST_SIZE=9 -D UI_MSG_PREVIEW_SIZE=165 - -D EINK_MAX_PARTIAL_REFRESH=60 -D EINK_DISPLAY_MODEL=GxEPD2_154_D67 -D EINK_SCALE_X=1.5625f -D EINK_SCALE_Y=1.5625f -D EINK_X_OFFSET=0 -D EINK_Y_OFFSET=10 -D BACKLIGHT_BTN=PIN_BUTTON2 - -D AUTO_OFF_MILLIS=900000 + -D AUTO_OFF_MILLIS=300000 ; 5 minutes -D UI_NO_HIBERNATE -D DISABLE_DIAGNOSTIC_OUTPUT build_src_filter = ${nrf52_base.build_src_filter} diff --git a/variants/thinknode_m5/platformio.ini b/variants/thinknode_m5/platformio.ini index a9761597..d2b791a3 100644 --- a/variants/thinknode_m5/platformio.ini +++ b/variants/thinknode_m5/platformio.ini @@ -28,9 +28,8 @@ build_flags = ${esp32_base.build_flags} -D EINK_Y_OFFSET=10 -D UI_RECENT_LIST_SIZE=9 -D UI_MSG_PREVIEW_SIZE=165 - -D EINK_MAX_PARTIAL_REFRESH=60 -D BACKLIGHT_BTN=PIN_BUTTON2 - -D AUTO_OFF_MILLIS=900000 + -D AUTO_OFF_MILLIS=300000 -D UI_NO_HIBERNATE -D DISABLE_DIAGNOSTIC_OUTPUT -D SX126X_DIO2_AS_RF_SWITCH=true diff --git a/variants/thinknode_m8/platformio.ini b/variants/thinknode_m8/platformio.ini index 5282f280..fdbaea1f 100644 --- a/variants/thinknode_m8/platformio.ini +++ b/variants/thinknode_m8/platformio.ini @@ -23,11 +23,9 @@ build_flags = ${nrf52_base.build_flags} -D UI_HAS_NAV_INPUT=1 -D UI_RECENT_LIST_SIZE=9 -D UI_MSG_PREVIEW_SIZE=165 - -D EINK_MAX_PARTIAL_REFRESH=60 - -D AUTO_OFF_MILLIS=900000 + -D AUTO_OFF_MILLIS=300000 -D BACKLIGHT_BTN=PIN_BUTTON2 -D UI_SHOW_CLOCK=1 - -D EINK_SCREENOFF_BLANK -D EINK_DISPLAY_MODEL=GxEPD2_154_D67 ; -D EINK_DISPLAY_MODEL=GxEPD2_154_GDEY0154D67 ; -D EINK_DISPLAY_MODEL=GxEPD2_150_BN From d8b5724c38395df188b479568346ea30b8a2338b Mon Sep 17 00:00:00 2001 From: akalinin-softvelum <142931037+akalinin-softvelum@users.noreply.github.com> Date: Tue, 27 Oct 2026 15:52:54 +0000 Subject: [PATCH 330/381] companion: keep mesh/BLE running during e-ink panel refresh Use GxEPD2's busy callback to run the mesh, interface and sensor loops (loopCore(), shared with loop()) while the panel refreshes, instead of blocking the main loop. Covers the partial refresh in endFrame(), the full wipe in startFrame(), and the sleep icon / blank refresh on turnOff(). --- examples/companion_radio/main.cpp | 25 ++++++++++++++++++++++++- src/helpers/ui/DisplayDriver.h | 1 + src/helpers/ui/GxEPDDisplay.cpp | 9 +++++++++ src/helpers/ui/GxEPDDisplay.h | 7 +++++++ 4 files changed, 41 insertions(+), 1 deletion(-) diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index 839d4958..9ed3bdcd 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -132,6 +132,10 @@ void halt() { bool wifi_enabled = false; // set at boot from prefs; false also when the effective SSID is blank #endif +#ifdef DISPLAY_CLASS +static void loopDuringDisplayRefresh(); +#endif + void setup() { Serial.begin(115200); board.begin(); @@ -284,15 +288,34 @@ void setup() { #ifdef DISPLAY_CLASS ui_task.begin(disp, &sensors, the_mesh.getNodePrefs()); // still want to pass this in as dependency, as prefs might be moved the_mesh.setListener(&ui_task); + if (disp != NULL) disp->setBusyHook(loopDuringDisplayRefresh); #endif board.onBootComplete(); } -void loop() { +// Work that must keep running even while the UI is blocked (e.g. by an e-ink refresh). +// Called from loop() and from the display busy hook, so both always run the same set. +static void loopCore() { the_mesh.loop(); interface_manager.loop(); sensors.loop(); +} + +#ifdef DISPLAY_CLASS +// Runs from inside the e-ink busy wait, so radio/BLE/sensors keep going during a panel refresh. +// Must not touch the display: UI listener callbacks only update state and schedule the next frame. +static void loopDuringDisplayRefresh() { + static bool active = false; + if (active) return; + active = true; + loopCore(); + active = false; +} +#endif + +void loop() { + loopCore(); #ifdef DISPLAY_CLASS ui_task.loop(); #endif diff --git a/src/helpers/ui/DisplayDriver.h b/src/helpers/ui/DisplayDriver.h index 0e41dab5..2fd22977 100644 --- a/src/helpers/ui/DisplayDriver.h +++ b/src/helpers/ui/DisplayDriver.h @@ -24,6 +24,7 @@ public: virtual bool isOn() = 0; virtual bool isEink() { return false; } // default to non-eink, override in eink drivers virtual void forceFullRefresh() {} // next refresh will be full for eink + virtual void setBusyHook(void (*hook)()) {} // eink: hook is called repeatedly while waiting for panel refresh virtual void turnOn() = 0; virtual void turnOn(int max_partial) { turnOn(); } virtual void turnOff() = 0; diff --git a/src/helpers/ui/GxEPDDisplay.cpp b/src/helpers/ui/GxEPDDisplay.cpp index d7f9562b..209d1b46 100644 --- a/src/helpers/ui/GxEPDDisplay.cpp +++ b/src/helpers/ui/GxEPDDisplay.cpp @@ -88,7 +88,9 @@ void GxEPDDisplay::drawSleepIcon() { display.fillRect((x - 5) * scale_x - 1, y * scale_y, (W+5) * scale_x + 2, (H-2) * scale_y + 1, GxEPD_WHITE); _curr_color = GxEPD_BLACK; drawXbm(x, y, sleep_icon_24x24, W, H); + if (_busy_hook) display.epd2.setBusyCallback(busyCallback, this); display.display(true); + display.epd2.setBusyCallback(NULL); } void GxEPDDisplay::turnOff(bool blank) { @@ -104,8 +106,10 @@ void GxEPDDisplay::turnOff(bool blank) { void GxEPDDisplay::blankScreen() { // do full refresh before powering off to clear screen // no full refresh needed at wakeup + if (_busy_hook) display.epd2.setBusyCallback(busyCallback, this); display.clearScreen(0xFF); // Clears microcontroller side RAM display.writeScreenBuffer(0xFF); // Forces 0xFF (White) into the display controller's history registers + display.epd2.setBusyCallback(NULL); _partial_refresh_count = 0; last_display_crc_value = 0; // we can hibernate as screen has been cleaned @@ -126,8 +130,10 @@ void GxEPDDisplay::startFrame(ColorVal bkg) { || (_max_partial_refresh > 0 && _partial_refresh_count >= _max_partial_refresh)) { // forces a full wipe of the screen ... + if (_busy_hook) display.epd2.setBusyCallback(busyCallback, this); display.clearScreen(0xFF); // Clears microcontroller side RAM display.writeScreenBuffer(0xFF); // Forces 0xFF (White) into the display controller's history registers + display.epd2.setBusyCallback(NULL); // we'll need a partial refresh after that (whatever crc value is) last_display_crc_value = 0; _partial_refresh_count = 0; @@ -239,7 +245,10 @@ void GxEPDDisplay::endFrame() { if (_isOn == false) return; uint32_t crc = display_crc.finalize(); if (crc != last_display_crc_value) { + // keep the rest of the firmware running while the panel refreshes (~0.5s partial) + if (_busy_hook) display.epd2.setBusyCallback(busyCallback, this); display.display(true); + display.epd2.setBusyCallback(NULL); _partial_refresh_count++; } last_display_crc_value = crc; diff --git a/src/helpers/ui/GxEPDDisplay.h b/src/helpers/ui/GxEPDDisplay.h index 9d918443..0aeaeca9 100644 --- a/src/helpers/ui/GxEPDDisplay.h +++ b/src/helpers/ui/GxEPDDisplay.h @@ -39,6 +39,12 @@ class GxEPDDisplay : public DisplayDriver { bool _force_full_refresh = false; int _partial_refresh_count = 0; int _max_partial_refresh = 0; + void (*_busy_hook)() = NULL; + + static void busyCallback(const void* self) { + ((const GxEPDDisplay*)self)->_busy_hook(); + delay(1); // same as GxEPD2 does without a callback + } public: #if defined(EINK_DISPLAY_MODEL) @@ -53,6 +59,7 @@ public: bool isEink() override { return true; } void forceFullRefresh() override { _force_full_refresh = true; } void turnOn(int max_partial) override; + void setBusyHook(void (*hook)()) override { _busy_hook = hook; } void turnOn() override; void turnOff(bool blank) override; void turnOff() override { turnOff(false); } From e184a81423d700b8437602e4d50b76e64485cd9b Mon Sep 17 00:00:00 2001 From: akalinin-softvelum <142931037+akalinin-softvelum@users.noreply.github.com> Date: Thu, 29 Oct 2026 13:21:11 +0000 Subject: [PATCH 331/381] companion: enable e-ink refresh loop only with EINK_REFRESH_LOOP Only builds that define EINK_REFRESH_LOOP install the busy hook; for now the T-Echo companion BLE/USB envs. --- examples/companion_radio/main.cpp | 6 ++++-- variants/lilygo_techo/platformio.ini | 2 ++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index 9ed3bdcd..cfc2b2bf 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -132,7 +132,7 @@ void halt() { bool wifi_enabled = false; // set at boot from prefs; false also when the effective SSID is blank #endif -#ifdef DISPLAY_CLASS +#if defined(DISPLAY_CLASS) && defined(EINK_REFRESH_LOOP) static void loopDuringDisplayRefresh(); #endif @@ -288,7 +288,9 @@ void setup() { #ifdef DISPLAY_CLASS ui_task.begin(disp, &sensors, the_mesh.getNodePrefs()); // still want to pass this in as dependency, as prefs might be moved the_mesh.setListener(&ui_task); +#ifdef EINK_REFRESH_LOOP if (disp != NULL) disp->setBusyHook(loopDuringDisplayRefresh); +#endif #endif board.onBootComplete(); @@ -302,7 +304,7 @@ static void loopCore() { sensors.loop(); } -#ifdef DISPLAY_CLASS +#if defined(DISPLAY_CLASS) && defined(EINK_REFRESH_LOOP) // Runs from inside the e-ink busy wait, so radio/BLE/sensors keep going during a panel refresh. // Must not touch the display: UI listener callbacks only update state and schedule the next frame. static void loopDuringDisplayRefresh() { diff --git a/variants/lilygo_techo/platformio.ini b/variants/lilygo_techo/platformio.ini index 896e42a6..2c2a3e43 100644 --- a/variants/lilygo_techo/platformio.ini +++ b/variants/lilygo_techo/platformio.ini @@ -93,6 +93,7 @@ build_flags = ${LilyGo_T-Echo.build_flags} -I src/helpers/ui -I examples/companion_radio/ui-new + -D EINK_REFRESH_LOOP -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D QSPIFLASH=1 @@ -120,6 +121,7 @@ build_flags = ${LilyGo_T-Echo.build_flags} -I src/helpers/ui -I examples/companion_radio/ui-new + -D EINK_REFRESH_LOOP -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 From 54b90cbdfa459830eebdd0c46207341b065cbbbf Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko <tishenko.alexandr@gmail.com> Date: Thu, 29 Oct 2026 23:49:49 +0200 Subject: [PATCH 332/381] Fix possible reply buffer overflow in 'sensor list' 'sensor list' appended 'name=value' lines into the 160-byte CLI reply with unbounded sprintf, only checking the position before each write (< 134). A single long value (or several medium ones) could write past the end of the buffer. Write each entry with snprintf against the remaining space, keep room for the '... next:N' paging hint, and move entries that do not fit to the next page. Also guard against NULL names/values from a sensor manager. --- src/helpers/CommonCLI.cpp | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index 04199e24..5d7501d9 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -326,18 +326,26 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re if (start >= end) { strcpy(reply, "no custom var"); } else { + const int reply_max = 160; // callers pass a 160-byte reply buffer + const int next_reserve = 16; // room for "... next:NNN" sprintf(dp, "%d vars\n", end); dp = strchr(dp, 0); int i; - for (i = start; i < end && (dp-reply < 134); i++) { - sprintf(dp, "%s=%s\n", - _sensors->getSettingName(i), - _sensors->getSettingValue(i)); + for (i = start; i < end; i++) { + const char* name = _sensors->getSettingName(i); + const char* value = _sensors->getSettingValue(i); + if (name == NULL) name = "?"; + if (value == NULL) value = ""; + int room = reply_max - next_reserve - (int)(dp - reply); + int need = snprintf(NULL, 0, "%s=%s\n", name, value); + if (need >= room && i > start) break; // continue on the next page + snprintf(dp, room, "%s=%s\n", name, value); // a single oversized entry is truncated dp = strchr(dp, 0); + if (need >= room) { i++; break; } } if (i < end) { - sprintf(dp, "... next:%d", i); - } else { + snprintf(dp, reply_max - (int)(dp - reply), "... next:%d", i); + } else if (dp > reply && *(dp-1) == '\n') { *(dp-1) = 0; // remove last CR } } From fee7a5a4c10a6e0d330ccb2a57592aabb557c64e Mon Sep 17 00:00:00 2001 From: zxw <2680562856@qq.com> Date: Thu, 15 Oct 2026 17:37:39 +0800 Subject: [PATCH 333/381] feat: Add low-power white status LED for SenseCAP Solar P1 Pro Add a dimmed heartbeat for the SenseCAP Solar (P1 Pro) white LED in the repeater firmware, implemented entirely as a SenseCapSolarBoard::loop() override so no example main.cpp needs to be touched: - 100 ms pulse every 5 s, dimmed to 10% brightness via hardware PWM (NRF_PWM0 / HwPWM0, 1 kHz, COUNTERTOP 16000, compare 1600) - during the 4.9 s off phase the PWM peripheral is stopped (ENABLE=0), the pin is released (PSEL disconnect) and GPIO 11 is held LOW, so no HFCLK is demanded between pulses - on successful application-level "start ota" the PWM is stopped and the white LED goes steady full-brightness while BLE OTA is advertised; on failed start the heartbeat keeps blinking - powerOff() stops/releases the heartbeat PWM before shutting the LED off - non-blocking millis() timing with wrap-safe unsigned arithmetic - gated by SENSECAP_SOLAR_WHITE_LED, defined only in the SenseCap_Solar_repeater PlatformIO env, so the room-server and companion firmwares sharing this board class are unaffected No changes to LoRa/repeater forwarding, the blue TX LED, charging LEDs, GPS, power management, config storage or the bootloader. --- .../sensecap_solar/SenseCapSolarBoard.cpp | 77 +++++++++++++++++++ variants/sensecap_solar/SenseCapSolarBoard.h | 23 ++++++ variants/sensecap_solar/platformio.ini | 2 + 3 files changed, 102 insertions(+) diff --git a/variants/sensecap_solar/SenseCapSolarBoard.cpp b/variants/sensecap_solar/SenseCapSolarBoard.cpp index da7964c9..058c1620 100644 --- a/variants/sensecap_solar/SenseCapSolarBoard.cpp +++ b/variants/sensecap_solar/SenseCapSolarBoard.cpp @@ -1,5 +1,6 @@ #include <Arduino.h> #include <Wire.h> +#include <HardwarePWM.h> #include "SenseCapSolarBoard.h" @@ -50,6 +51,9 @@ void SenseCapSolarBoard::begin() { #ifdef LED_WHITE pinMode(LED_WHITE, OUTPUT); digitalWrite(LED_WHITE, LOW); +#ifdef SENSECAP_SOLAR_WHITE_LED + white_led_last_pulse_at_ = millis(); // first heartbeat pulse 5 s after boot +#endif #endif #ifdef LED_BLUE pinMode(LED_BLUE, OUTPUT); @@ -67,3 +71,76 @@ void SenseCapSolarBoard::begin() { delay(10); // give sx1262 some time to power up } + +#ifdef SENSECAP_SOLAR_WHITE_LED +// Dimmed WHITE heartbeat using hardware PWM (repeater builds only). +// +// Peripheral audit for this firmware: no analogWrite()/tone() callers, no +// NeoPixel/Servo, Bluefruit52Lib uses no PWM, SoftDevice S140 does not own +// any PWM instance -> NRF_PWM0 (HwPWM0) is free. takeOwnership() fences the +// instance so a future analogWrite() caller cannot claim it. +// +// Timing: base clock 16 MHz (DIV_1), COUNTERTOP 16000 -> exactly 1 kHz. +// Duty: HardwarePWM non-inverted values place bit15 (active-HIGH polarity), +// so compare 1600 => HIGH for [0,1600)/16000 => 10% duty, active-high. +static const uint32_t WHITE_LED_PWM_TOKEN = 0x5031574C; // 'P1WL' +static const uint16_t WHITE_LED_PWM_TOP = 16000; // 16 MHz / 16000 = 1 kHz +static const uint16_t WHITE_LED_PWM_DUTY = 1600; // 1600 / 16000 = 10 % +static_assert(WHITE_LED_PWM_TOP <= 0x7FFF, "PWM compare values are 15-bit"); +static_assert(WHITE_LED_PWM_DUTY < WHITE_LED_PWM_TOP, "duty must stay below COUNTERTOP"); + +void SenseCapSolarBoard::whiteLedHeartbeatOn() { + HwPWM0.takeOwnership(WHITE_LED_PWM_TOKEN); // no-op once owned; keeps analogWrite away + HwPWM0.setClockDiv(PWM_PRESCALER_PRESCALER_DIV_1); // 16 MHz base clock + HwPWM0.setMaxValue(WHITE_LED_PWM_TOP); // 1 kHz period + HwPWM0.addPin(LED_WHITE); // drives pin LOW, connects PSEL + HwPWM0.writePin(LED_WHITE, WHITE_LED_PWM_DUTY); // enables + starts 10% PWM +} + +void SenseCapSolarBoard::whiteLedHeartbeatOff() { + HwPWM0.stop(); // ENABLE=0: waveform and its HFCLK demand stop + if (HwPWM0.checkPin(LED_WHITE)) { + HwPWM0.removePin(LED_WHITE); // disconnect PSEL; GPIO block drives again + } + pinMode(LED_WHITE, OUTPUT); + digitalWrite(LED_WHITE, LOW); // deterministic LOW during the 4900 ms off phase +} + +// 100 ms pulse every 5000 ms, non-blocking millis() with wrap-safe unsigned +// arithmetic. Called from loop(); frozen while the OTA steady-on owns the LED. +void SenseCapSolarBoard::updateWhiteStatusLed() { + if (white_led_ota_active_) return; + + const uint32_t now = millis(); + const uint32_t elapsed = (uint32_t)(now - white_led_last_pulse_at_); + if (white_led_pulse_active_ && elapsed >= 100U) { + whiteLedHeartbeatOff(); // stop PWM, pin LOW + white_led_pulse_active_ = false; + } + if (!white_led_pulse_active_ && elapsed >= 5000U) { + whiteLedHeartbeatOn(); // 1 kHz hardware PWM, 10% duty + white_led_pulse_active_ = true; + white_led_last_pulse_at_ = now; + } +} + +void SenseCapSolarBoard::loop() { + mesh::MainBoard::loop(); // keep base housekeeping (watchdog etc.) if it ever gains any + updateWhiteStatusLed(); +} + +// `start ota` keeps WHITE on for as long as the application is advertising +// its BLE OTA service. The heartbeat PWM is stopped and the pin released +// first, so steady-on is a plain full-brightness GPIO drive (no PWM vs +// digitalWrite conflict). On a failed start nothing changes: the heartbeat +// keeps its normal blinking. +bool SenseCapSolarBoard::startOTAUpdate(const char *id, char reply[]) { + const bool started = NRF52Board::startOTAUpdate(id, reply); + if (started) { + white_led_ota_active_ = true; + whiteLedHeartbeatOff(); + digitalWrite(LED_WHITE, LED_STATE_ON); + } + return started; +} +#endif // SENSECAP_SOLAR_WHITE_LED diff --git a/variants/sensecap_solar/SenseCapSolarBoard.h b/variants/sensecap_solar/SenseCapSolarBoard.h index 5a8861c2..1b4b5711 100644 --- a/variants/sensecap_solar/SenseCapSolarBoard.h +++ b/variants/sensecap_solar/SenseCapSolarBoard.h @@ -5,6 +5,19 @@ #include <helpers/NRF52Board.h> class SenseCapSolarBoard : public NRF52BoardDCDC { +#ifdef SENSECAP_SOLAR_WHITE_LED + // Dimmed white-LED heartbeat state (repeater builds only; enabled with + // -D SENSECAP_SOLAR_WHITE_LED in the PlatformIO env, so room-server and + // companion firmwares sharing this board class are unaffected). + bool white_led_ota_active_ = false; + bool white_led_pulse_active_ = false; + uint32_t white_led_last_pulse_at_ = 0; + + void whiteLedHeartbeatOn(); // start 1 kHz PWM at 10% duty on LED_WHITE + void whiteLedHeartbeatOff(); // stop/release PWM, hold LED_WHITE LOW + void updateWhiteStatusLed(); // non-blocking 100 ms pulse every 5000 ms +#endif + protected: #ifdef NRF52_POWER_MANAGEMENT void initiateShutdown(uint8_t reason) override; @@ -14,6 +27,13 @@ public: SenseCapSolarBoard() : NRF52Board("SENSECAP_SOLAR_OTA") {} void begin(); +#ifdef SENSECAP_SOLAR_WHITE_LED + // Runs the white-LED heartbeat; invoked by the example main loops via the + // existing board.loop() call (mesh::MainBoard::loop() is a no-op by default). + void loop() override; + bool startOTAUpdate(const char *id, char reply[]) override; +#endif + #if defined(P_LORA_TX_LED) void onBeforeTransmit() override { digitalWrite(P_LORA_TX_LED, HIGH); // turn TX LED on @@ -38,6 +58,9 @@ public: } void powerOff() override { +#ifdef SENSECAP_SOLAR_WHITE_LED + whiteLedHeartbeatOff(); // stop/release the heartbeat PWM before shutdown +#endif digitalWrite(LED_WHITE, LOW); digitalWrite(LED_BLUE, LOW); diff --git a/variants/sensecap_solar/platformio.ini b/variants/sensecap_solar/platformio.ini index a2a9c85a..60e11e9f 100644 --- a/variants/sensecap_solar/platformio.ini +++ b/variants/sensecap_solar/platformio.ini @@ -45,6 +45,8 @@ build_flags = -D ADVERT_LON=0.0 -D ADMIN_PASSWORD='"password"' -D MAX_NEIGHBOURS=50 +; dimmed white-LED heartbeat + OTA steady-on (repeater builds only) + -D SENSECAP_SOLAR_WHITE_LED=1 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${SenseCap_Solar.build_src_filter} From 93254adbca827a768bdbf8ad35b6221ecc44ee2f Mon Sep 17 00:00:00 2001 From: R0ck <develop@hectospark.co.uk> Date: Fri, 30 Oct 2026 14:05:25 +0000 Subject: [PATCH 334/381] radiolib: drop received packets whose LoRa header says no CRC. --- src/helpers/radiolib/CustomLLCC68Wrapper.h | 5 +++++ src/helpers/radiolib/CustomLR1110Wrapper.h | 5 +++++ src/helpers/radiolib/CustomLR1121Wrapper.h | 5 +++++ src/helpers/radiolib/CustomLR2021Wrapper.h | 5 +++++ src/helpers/radiolib/CustomSTM32WLxWrapper.h | 5 +++++ src/helpers/radiolib/CustomSX1262Wrapper.h | 5 +++++ src/helpers/radiolib/CustomSX1268Wrapper.h | 5 +++++ src/helpers/radiolib/RadioLibWrappers.cpp | 3 +++ src/helpers/radiolib/RadioLibWrappers.h | 1 + 9 files changed, 39 insertions(+) diff --git a/src/helpers/radiolib/CustomLLCC68Wrapper.h b/src/helpers/radiolib/CustomLLCC68Wrapper.h index ae0fe0a2..36cde0f6 100644 --- a/src/helpers/radiolib/CustomLLCC68Wrapper.h +++ b/src/helpers/radiolib/CustomLLCC68Wrapper.h @@ -20,6 +20,11 @@ public: } + bool lastRxHadCRC() override { + bool crc = true; + ((CustomLLCC68 *)_radio)->getLoRaRxHeaderInfo(NULL, &crc); + return crc; + } bool isReceivingPacket() override { return ((CustomLLCC68 *)_radio)->isReceiving(); } diff --git a/src/helpers/radiolib/CustomLR1110Wrapper.h b/src/helpers/radiolib/CustomLR1110Wrapper.h index e7aaeb93..66bcb3b4 100644 --- a/src/helpers/radiolib/CustomLR1110Wrapper.h +++ b/src/helpers/radiolib/CustomLR1110Wrapper.h @@ -19,6 +19,11 @@ public: ((CustomLR1110 *)_radio)->setMaxPayloadMillis(pm.payloadMillis); } + bool lastRxHadCRC() override { + bool crc = true; + ((CustomLR1110 *)_radio)->getLoRaRxHeaderInfo(NULL, &crc); + return crc; + } bool isReceivingPacket() override { return ((CustomLR1110 *)_radio)->isReceiving(); } diff --git a/src/helpers/radiolib/CustomLR1121Wrapper.h b/src/helpers/radiolib/CustomLR1121Wrapper.h index 5a754cee..70912f1e 100644 --- a/src/helpers/radiolib/CustomLR1121Wrapper.h +++ b/src/helpers/radiolib/CustomLR1121Wrapper.h @@ -20,6 +20,11 @@ public: } void doResetAGC() override { lr11x0ResetAGC((LR11x0 *)_radio, ((CustomLR1121 *)_radio)->getFreqMHz(), getRxBoostedGainMode()); } + bool lastRxHadCRC() override { + bool crc = true; + ((CustomLR1121 *)_radio)->getLoRaRxHeaderInfo(NULL, &crc); + return crc; + } bool isReceivingPacket() override { return ((CustomLR1121 *)_radio)->isReceiving(); } diff --git a/src/helpers/radiolib/CustomLR2021Wrapper.h b/src/helpers/radiolib/CustomLR2021Wrapper.h index c60bfda3..81c2feac 100644 --- a/src/helpers/radiolib/CustomLR2021Wrapper.h +++ b/src/helpers/radiolib/CustomLR2021Wrapper.h @@ -81,6 +81,11 @@ public: return tSym; } + bool lastRxHadCRC() override { + bool crc = true; + ((CustomLR2021 *)_radio)->getLoRaRxHeaderInfo(NULL, &crc); + return crc; + } bool isReceivingPacket() override { return ((CustomLR2021 *)_radio)->isReceiving(); } diff --git a/src/helpers/radiolib/CustomSTM32WLxWrapper.h b/src/helpers/radiolib/CustomSTM32WLxWrapper.h index a4ba4971..bc93de75 100644 --- a/src/helpers/radiolib/CustomSTM32WLxWrapper.h +++ b/src/helpers/radiolib/CustomSTM32WLxWrapper.h @@ -20,6 +20,11 @@ public: ((CustomSTM32WLx *)_radio)->setMaxPayloadMillis(pm.payloadMillis); } + bool lastRxHadCRC() override { + bool crc = true; + ((CustomSTM32WLx *)_radio)->getLoRaRxHeaderInfo(NULL, &crc); + return crc; + } bool isReceivingPacket() override { return ((CustomSTM32WLx *)_radio)->isReceiving(); } diff --git a/src/helpers/radiolib/CustomSX1262Wrapper.h b/src/helpers/radiolib/CustomSX1262Wrapper.h index be314471..cdd195fb 100644 --- a/src/helpers/radiolib/CustomSX1262Wrapper.h +++ b/src/helpers/radiolib/CustomSX1262Wrapper.h @@ -23,6 +23,11 @@ public: ((CustomSX1262 *)_radio)->setMaxPayloadMillis(pm.payloadMillis); } + bool lastRxHadCRC() override { + bool crc = true; + ((CustomSX1262 *)_radio)->getLoRaRxHeaderInfo(NULL, &crc); + return crc; + } bool isReceivingPacket() override { return ((CustomSX1262 *)_radio)->isReceiving(); } diff --git a/src/helpers/radiolib/CustomSX1268Wrapper.h b/src/helpers/radiolib/CustomSX1268Wrapper.h index 70f5dabd..ec11f147 100644 --- a/src/helpers/radiolib/CustomSX1268Wrapper.h +++ b/src/helpers/radiolib/CustomSX1268Wrapper.h @@ -23,6 +23,11 @@ public: ((CustomSX1268 *)_radio)->setMaxPayloadMillis(pm.payloadMillis); } + bool lastRxHadCRC() override { + bool crc = true; + ((CustomSX1268 *)_radio)->getLoRaRxHeaderInfo(NULL, &crc); + return crc; + } bool isReceivingPacket() override { return ((CustomSX1268 *)_radio)->isReceiving(); } diff --git a/src/helpers/radiolib/RadioLibWrappers.cpp b/src/helpers/radiolib/RadioLibWrappers.cpp index e4d2ba1c..0faeebac 100644 --- a/src/helpers/radiolib/RadioLibWrappers.cpp +++ b/src/helpers/radiolib/RadioLibWrappers.cpp @@ -132,6 +132,9 @@ int RadioLibWrapper::recvRaw(uint8_t* bytes, int sz) { if (len > 0) { if (len > sz) { len = sz; } int err = _radio->readData(bytes, len); + if (err == RADIOLIB_ERR_NONE && !lastRxHadCRC()) { + err = RADIOLIB_ERR_LORA_HEADER_DAMAGED; // header says no CRC, so the payload was never checked + } if (err != RADIOLIB_ERR_NONE) { MESH_DEBUG_PRINTLN("RadioLibWrapper: error: readData(%d)", err); len = 0; diff --git a/src/helpers/radiolib/RadioLibWrappers.h b/src/helpers/radiolib/RadioLibWrappers.h index 77dd9311..9f572572 100644 --- a/src/helpers/radiolib/RadioLibWrappers.h +++ b/src/helpers/radiolib/RadioLibWrappers.h @@ -26,6 +26,7 @@ protected: void startRecv(); float packetScoreInt(float snr, int sf, int packet_len); virtual bool isReceivingPacket() =0; + virtual bool lastRxHadCRC() { return true; } virtual void doResetAGC(); public: From 90ffa57c5f999f109f698090e3c270987b2524f1 Mon Sep 17 00:00:00 2001 From: Juraj Bednar <juraj@bednar.io> Date: Sun, 1 Nov 2026 13:32:38 +0100 Subject: [PATCH 335/381] Add Road Events allocation for GroupData --- docs/number_allocations.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/number_allocations.md b/docs/number_allocations.md index 79cc90b8..44cd25bf 100644 --- a/docs/number_allocations.md +++ b/docs/number_allocations.md @@ -20,6 +20,7 @@ Once you have a working app/project, you need to be able to demonstrate it exist | 0120 | MCO Advanced | most.original.address@gmail.com — https://hdden.ru/MCOa/ | | 0130 - 013F | StreamSensor | william@housedillon.com - https://housedillon.com/blog/lora-e5-with-seeed-fusion | | 0140 | Nelos | support@nelos.app — https://nelos.app | +| 0150 | Road Events | juraj@bednar.io — https://github.com/jooray/roadbeacon/blob/main/nips/road-events.md | | FF00 - FFFF | -reserved for testing/dev- | | (add rows, inside the range 0100 - FEFF for custom apps) From 287c5e21cf2867477cfe94fd6c5afc905fd11526 Mon Sep 17 00:00:00 2001 From: Will MacGregor <will@jsisensors.ca> Date: Wed, 4 Nov 2026 09:46:27 -0500 Subject: [PATCH 336/381] Enable simple_room_server on the STM32 platform The room server gated its filesystem paths on NRF52_PLATFORM only, so an STM32 build fell through to the ESP32 branch and failed to compile: MyMesh.cpp:147: no matching function for call to 'Adafruit_LittleFS::open(const char*&, const char [2], bool)' main.cpp:69: 'store' was not declared in this scope STM32 uses the same InternalFS / Adafruit_LittleFS API as nRF52, including append semantics (FILE_O_WRITE opens LFS_O_RDWR|LFS_O_CREAT and then seeks to the end), so the nRF52 branch is already correct for it. Add STM32_PLATFORM alongside NRF52_PLATFORM in the four remaining gates; saveIdentity() already did this. This unblocks the room_server example on the existing STM32WL boards (wio-e5-mini, wio-e5-dev, rak3x72, tiny_relay) as well as new ones. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --- examples/simple_room_server/MyMesh.cpp | 4 ++-- examples/simple_room_server/MyMesh.h | 2 +- examples/simple_room_server/main.cpp | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/simple_room_server/MyMesh.cpp b/examples/simple_room_server/MyMesh.cpp index 935fd7f9..b1a88dd8 100644 --- a/examples/simple_room_server/MyMesh.cpp +++ b/examples/simple_room_server/MyMesh.cpp @@ -140,7 +140,7 @@ mesh::Packet *MyMesh::createSelfAdvert() { } File MyMesh::openAppend(const char *fname) { -#if defined(NRF52_PLATFORM) +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) return _fs->open(fname, FILE_O_WRITE); #elif defined(RP2040_PLATFORM) return _fs->open(fname, "a"); @@ -782,7 +782,7 @@ void MyMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, } bool MyMesh::formatFileSystem() { -#if defined(NRF52_PLATFORM) +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) return InternalFS.format(); #elif defined(RP2040_PLATFORM) return LittleFS.format(); diff --git a/examples/simple_room_server/MyMesh.h b/examples/simple_room_server/MyMesh.h index 4dee8bdb..974e633a 100644 --- a/examples/simple_room_server/MyMesh.h +++ b/examples/simple_room_server/MyMesh.h @@ -3,7 +3,7 @@ #include <Arduino.h> // needed for PlatformIO #include <Mesh.h> -#if defined(NRF52_PLATFORM) +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) #include <InternalFileSystem.h> #elif defined(RP2040_PLATFORM) #include <LittleFS.h> diff --git a/examples/simple_room_server/main.cpp b/examples/simple_room_server/main.cpp index 65fc55ef..4bfad4e5 100644 --- a/examples/simple_room_server/main.cpp +++ b/examples/simple_room_server/main.cpp @@ -50,7 +50,7 @@ void setup() { fast_rng.begin(radio_driver.getRngSeed()); FILESYSTEM* fs; -#if defined(NRF52_PLATFORM) +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) InternalFS.begin(); fs = &InternalFS; IdentityStore store(InternalFS, ""); From afb56bb976bccb9cf95d44fe8aff2f6dca13b47d Mon Sep 17 00:00:00 2001 From: Will MacGregor <will@jsisensors.ca> Date: Wed, 4 Nov 2026 09:46:40 -0500 Subject: [PATCH 337/381] Add variant for ST Nucleo-WL55JC1 Adds repeater, room_server, companion_radio_usb and kiss_modem environments for the NUCLEO-WL55JC1 (STM32WL55JC, integrated SubGHz radio). Notes on the board setup: - Uses the upstream nucleo_wl55jc board. PlatformIO's boards_remap maps it to the core's NUCLEO_WL55JC1 variant, so the LEDs, user buttons and the LPUART1 -> ST-LINK VCP serial mapping all come from the core rather than being redefined here. - The RF switch table is built from the core's LORAWAN_RFSWITCH_* macros (SP3T front end on PC3/PC4/PC5) so it tracks upstream if those are ever revised. Both RFO_LP and RFO_HP are registered, so RadioLib selects HP above 14 dBm and LP below it. - board_build.extra_flags pins the device to STM32WL55xx. The stock board manifest declares product_line STM32WL55xx but extra_flags -DSTM32WLE5xx; that only works because every #elif chain happens to test WL55xx first. - The Nucleo's LD1..LD3 are driven active HIGH, so the TX LED hooks are inverted relative to STM32Board's active-LOW default. - 32 KB reserved at the top of flash for LittleFS, as on the other STM32WL variants. Verified on hardware: all four environments build; repeater and room_server flash and run over ST-LINK; identity and prefs persist across reboot and across a firmware swap; and GPIOC reads back the documented RX levels at idle, confirming the front-end switch is driven correctly. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --- variants/nucleo_wl55jc/platformio.ini | 57 +++++++++++++++++++++++ variants/nucleo_wl55jc/target.cpp | 65 +++++++++++++++++++++++++++ variants/nucleo_wl55jc/target.h | 47 +++++++++++++++++++ variants/nucleo_wl55jc/variant.h | 5 +++ 4 files changed, 174 insertions(+) create mode 100644 variants/nucleo_wl55jc/platformio.ini create mode 100644 variants/nucleo_wl55jc/target.cpp create mode 100644 variants/nucleo_wl55jc/target.h create mode 100644 variants/nucleo_wl55jc/variant.h diff --git a/variants/nucleo_wl55jc/platformio.ini b/variants/nucleo_wl55jc/platformio.ini new file mode 100644 index 00000000..0de5ba6f --- /dev/null +++ b/variants/nucleo_wl55jc/platformio.ini @@ -0,0 +1,57 @@ +[nucleo_wl55jc] +extends = stm32_base +board = nucleo_wl55jc +; The upstream board manifest tags the part as STM32WLE5xx even though its +; product_line is STM32WL55xx. Pin both to WL55 so a single device header and +; startup file (startup_stm32wl55xx_cm4.s) are in play. +board_build.extra_flags = -DSTM32WL -DSTM32WLxx -DSTM32WL55xx +board_upload.maximum_size = 229376 ; 32kb at the top of flash reserved for LittleFS +build_flags = ${stm32_base.build_flags} + -D RADIO_CLASS=CustomSTM32WLx + -D WRAPPER_CLASS=CustomSTM32WLxWrapper + -D LORA_TX_POWER=22 + -D SPI_INTERFACES_COUNT=0 + -D RX_BOOSTED_GAIN=true + -D STM32WL_TCXO_VOLTAGE=1.7 + -D P_LORA_TX_LED=LED_BLUE + -D PIN_USER_BTN=USER_BTN + -D USER_BTN_PRESSED=LOW + -I variants/nucleo_wl55jc +build_src_filter = ${stm32_base.build_src_filter} + +<../variants/nucleo_wl55jc> + +[env:nucleo_wl55jc_repeater] +extends = nucleo_wl55jc +build_flags = ${nucleo_wl55jc.build_flags} + -D ADVERT_NAME='"Nucleo WL55JC Repeater"' + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=50 +build_src_filter = ${nucleo_wl55jc.build_src_filter} + +<../examples/simple_repeater/*.cpp> + +[env:nucleo_wl55jc_companion_radio_usb] +extends = nucleo_wl55jc +build_flags = ${nucleo_wl55jc.build_flags} + -D MAX_CONTACTS=100 + -D MAX_GROUP_CHANNELS=8 + -D ENABLE_USB_INTERFACE ; binds to Serial, i.e. the ST-LINK virtual COM port +build_src_filter = ${nucleo_wl55jc.build_src_filter} + +<../examples/companion_radio/*.cpp> +lib_deps = ${nucleo_wl55jc.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[env:nucleo_wl55jc_kiss_modem] +extends = nucleo_wl55jc +build_src_filter = ${nucleo_wl55jc.build_src_filter} + +<../examples/kiss_modem/> + +[env:nucleo_wl55jc_room_server] +extends = nucleo_wl55jc +build_flags = ${nucleo_wl55jc.build_flags} + -D ADVERT_NAME='"Nucleo WL55JC Room"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D ROOM_PASSWORD='"hello"' +build_src_filter = ${nucleo_wl55jc.build_src_filter} + +<../examples/simple_room_server> diff --git a/variants/nucleo_wl55jc/target.cpp b/variants/nucleo_wl55jc/target.cpp new file mode 100644 index 00000000..8e773adf --- /dev/null +++ b/variants/nucleo_wl55jc/target.cpp @@ -0,0 +1,65 @@ +#include <Arduino.h> +#include "target.h" +#include <helpers/ArduinoHelpers.h> + +NucleoWL55JCBoard board; + +RADIO_CLASS radio = new STM32WLx_Module(); + +WRAPPER_CLASS radio_driver(radio, board); + +// The NUCLEO-WL55JC1 drives an SP3T front-end switch from FE_CTRL1..3 (PC4, PC5, PC3), +// routing the single SMA between RX, RFO_LP and RFO_HP. Pin order and levels are taken +// straight from the core's board definition (variant_NUCLEO_WL55JC1.h) so they stay in +// sync with upstream. +static const uint32_t rfswitch_pins[] = {LORAWAN_RFSWITCH_PINS, RADIOLIB_NC, RADIOLIB_NC}; +static const Module::RfSwitchMode_t rfswitch_table[] = { + {STM32WLx::MODE_IDLE, {LORAWAN_RFSWITCH_OFF_VALUES}}, + {STM32WLx::MODE_RX, {LORAWAN_RFSWITCH_RX_VALUES}}, + {STM32WLx::MODE_TX_LP, {LORAWAN_RFSWITCH_RFO_LP_VALUES}}, + {STM32WLx::MODE_TX_HP, {LORAWAN_RFSWITCH_RFO_HP_VALUES}}, + END_OF_MODE_TABLE, +}; + +VolatileRTCClock rtc_clock; +SensorManager sensors; + +#ifndef LORA_CR + #define LORA_CR 5 +#endif + +#ifndef STM32WL_TCXO_VOLTAGE + // The board is fitted with a 32MHz TCXO powered from the radio's DIO3 at 1.7V + #define STM32WL_TCXO_VOLTAGE 1.7 +#endif + +#ifndef LORA_TX_POWER + #define LORA_TX_POWER 22 +#endif + +bool radio_init() { + radio.setRfSwitchTable(rfswitch_pins, rfswitch_table); + + // Both PA paths are registered above, so RadioLib picks RFO_HP whenever the + // requested power is above 14dBm, and RFO_LP below that. + int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, LORA_TX_POWER, 16, STM32WL_TCXO_VOLTAGE, 0); + + if (status != RADIOLIB_ERR_NONE) { + Serial.print("ERROR: radio init failed: "); + Serial.println(status); + return false; // fail + } + + #ifdef RX_BOOSTED_GAIN + radio.setRxBoostedGainMode(RX_BOOSTED_GAIN); + #endif + + radio.setCRC(1); + + return true; // success +} + +mesh::LocalIdentity radio_new_identity() { + RadioNoiseListener rng(radio); + return mesh::LocalIdentity(&rng); // create new random identity +} diff --git a/variants/nucleo_wl55jc/target.h b/variants/nucleo_wl55jc/target.h new file mode 100644 index 00000000..4b1c3ada --- /dev/null +++ b/variants/nucleo_wl55jc/target.h @@ -0,0 +1,47 @@ +#pragma once + +#define RADIOLIB_STATIC_ONLY 1 +#include <RadioLib.h> +#include <helpers/radiolib/RadioLibWrappers.h> +#include <helpers/stm32/STM32Board.h> +#include <helpers/radiolib/CustomSTM32WLxWrapper.h> +#include <helpers/ArduinoHelpers.h> +#include <helpers/SensorManager.h> + +class NucleoWL55JCBoard : public STM32Board { +public: + void begin() override { + STM32Board::begin(); + + pinMode(P_LORA_TX_LED, OUTPUT); + digitalWrite(P_LORA_TX_LED, LOW); // see note on LED polarity below + pinMode(PIN_USER_BTN, INPUT_PULLUP); + } + + const char* getManufacturerName() const override { + return "ST Nucleo WL55JC1"; + } + + // LD1..LD3 on the Nucleo are driven active HIGH, whereas STM32Board's + // default TX-LED handling assumes the active LOW wiring used by the + // Wio-E5 boards. Invert both halves here. + 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 + } + + // No battery on this dev board, it is USB/ST-LINK powered. + uint16_t getBattMilliVolts() override { + return 0; + } +}; + +extern NucleoWL55JCBoard board; +extern WRAPPER_CLASS radio_driver; +extern VolatileRTCClock rtc_clock; +extern SensorManager sensors; + +bool radio_init(); +mesh::LocalIdentity radio_new_identity(); diff --git a/variants/nucleo_wl55jc/variant.h b/variants/nucleo_wl55jc/variant.h new file mode 100644 index 00000000..a006d1f1 --- /dev/null +++ b/variants/nucleo_wl55jc/variant.h @@ -0,0 +1,5 @@ +#pragma once + +#include <variant_NUCLEO_WL55JC1.h> + +#undef RNG From 9af19c870c6236d0aa310137badd7616c5116cd0 Mon Sep 17 00:00:00 2001 From: Will MacGregor <will@jsisensors.ca> Date: Wed, 4 Nov 2026 09:51:33 -0500 Subject: [PATCH 338/381] Build nucleo_wl55jc_repeater in PR build check Adds the new variant to the PR build matrix, next to the existing STM32 entry, so it is covered by CI going forward. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --- .github/workflows/pr-build-check.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/pr-build-check.yml b/.github/workflows/pr-build-check.yml index cebf0cfe..1d431451 100644 --- a/.github/workflows/pr-build-check.yml +++ b/.github/workflows/pr-build-check.yml @@ -40,6 +40,7 @@ jobs: - PicoW_repeater # STM32 - wio-e5-mini_repeater + - nucleo_wl55jc_repeater # ESP32-C6 - LilyGo_Tlora_C6_repeater_ # LR1110 (nRF52) From 1e135e0bd2547f56292dd5bb6ee5ebbbb468f752 Mon Sep 17 00:00:00 2001 From: Li Hardy Extreme <li.hardy.extreme@gmail.com> Date: Fri, 6 Nov 2026 00:10:59 +0100 Subject: [PATCH 339/381] feat: mDNS ESP32 - enable local network discovery over mDNS --- examples/companion_radio/main.cpp | 32 +++++++++++++++++++++++++++++++ variants/heltec_v4/platformio.ini | 2 ++ 2 files changed, 34 insertions(+) diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index 839d4958..1ff74470 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -2,6 +2,11 @@ #include <Mesh.h> #include "MyMesh.h" +#if defined(ENABLE_WIFI_INTERFACE) && defined(ENABLE_ESP_MDNS) +#define HAS_ESP_MDNS +#include <ESPmDNS.h> +#endif + // Believe it or not, this std C function is busted on some platforms! static uint32_t _atoi(const char* sp) { uint32_t n = 0; @@ -266,6 +271,33 @@ void setup() { interface_manager.addInterface(InterfaceType::Ethernet, ðernet_interface); #endif +#ifdef HAS_ESP_MDNS + String nodeName = the_mesh.getNodeName(); + String sanitizedNodeName; + sanitizedNodeName.reserve(nodeName.length()); + for (size_t i = 0; i < nodeName.length(); ++i) { + const char c = nodeName[i]; + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || c == '-' || c == '_') { + sanitizedNodeName += c; + } + } + + String mdnsName = "meshcore_"; + mdnsName += sanitizedNodeName; + if (!MDNS.begin(mdnsName.c_str())) { + WIFI_DEBUG_PRINTLN("mDNS failed to start!"); + } else { + MDNS.addService("meshcore", "tcp", TCP_PORT); + MDNS.addServiceTxt("meshcore", "tcp", "node-name", the_mesh.getNodeName()); + MDNS.addServiceTxt("meshcore", "tcp", "firmware-version", FIRMWARE_VERSION); + String protocol; protocol+=FIRMWARE_VER_CODE; + MDNS.addServiceTxt("meshcore", "tcp", "protocol-version", protocol.c_str()); + MDNS.addServiceTxt("meshcore", "tcp", "build-date", __DATE__); + MDNS.addServiceTxt("meshcore", "tcp", "build-time", __TIME__); + } +#endif + // add hardware serial interface #if defined(SERIAL_RX) companion_serial.setPins(SERIAL_RX, SERIAL_TX); diff --git a/variants/heltec_v4/platformio.ini b/variants/heltec_v4/platformio.ini index c91e31a8..69ac9ad8 100644 --- a/variants/heltec_v4/platformio.ini +++ b/variants/heltec_v4/platformio.ini @@ -212,6 +212,7 @@ build_flags = -D BLE_DEBUG_LOGGING=1 -D OFFLINE_QUEUE_SIZE=256 -D ENABLE_WIFI_INTERFACE + -D ENABLE_ESP_MDNS ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${heltec_v4_oled.build_src_filter} @@ -231,6 +232,7 @@ build_flags = ${heltec_v4_oled.build_flags} -I examples/companion_radio/ui-new -D ENABLE_WIFI_INTERFACE + -D ENABLE_ESP_MDNS -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 From c5a0673d678512acb261625c9977dd7d5607d342 Mon Sep 17 00:00:00 2001 From: Rastislav Vysoky <recrof@gmail.com> Date: Sat, 7 Nov 2026 00:35:47 +0100 Subject: [PATCH 340/381] added rp2350 support, harmonized companions with other variants --- platformio.ini | 3 +- variants/rpi_picow/PicoWBoard.h | 4 + variants/rpi_picow/platformio.ini | 135 ++++++++++++++++++++---------- 3 files changed, 97 insertions(+), 45 deletions(-) diff --git a/platformio.ini b/platformio.ini index 92c94204..9ad9c890 100644 --- a/platformio.ini +++ b/platformio.ini @@ -101,7 +101,8 @@ lib_deps = extends = arduino_base upload_protocol = picotool board_build.core = earlephilhower -platform = https://github.com/maxgerhardt/platform-raspberrypi.git ; framework-arduinopico @ 1.50600.0+sha.6a1d13e9 +platform = https://github.com/maxgerhardt/platform-raspberrypi.git +platform_packages = framework-arduinopico @ https://github.com/earlephilhower/arduino-pico.git#6a1d13e960e0854da2bf328b1a5fc05481d89aba build_flags = ${arduino_base.build_flags} -D RP2040_PLATFORM diff --git a/variants/rpi_picow/PicoWBoard.h b/variants/rpi_picow/PicoWBoard.h index e64590f2..1660fe91 100644 --- a/variants/rpi_picow/PicoWBoard.h +++ b/variants/rpi_picow/PicoWBoard.h @@ -42,7 +42,11 @@ public: } const char* getManufacturerName() const override { + #if defined(PICO_RP2350) + return "Pico 2 W"; + #else return "Pico W"; + #endif } void reboot() override { diff --git a/variants/rpi_picow/platformio.ini b/variants/rpi_picow/platformio.ini index 9814f397..94fc40aa 100644 --- a/variants/rpi_picow/platformio.ini +++ b/variants/rpi_picow/platformio.ini @@ -56,8 +56,8 @@ build_src_filter = ${rpi_picow.build_src_filter} [env:PicoW_companion_radio_usb] extends = rpi_picow build_flags = ${rpi_picow.build_flags} - -D MAX_CONTACTS=100 - -D MAX_GROUP_CHANNELS=8 + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 -D ENABLE_USB_INTERFACE ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 @@ -70,33 +70,14 @@ lib_ignore = BLE [env:PicoW_companion_radio_ble] extends = rpi_picow build_flags = ${rpi_picow.build_flags} - -D MAX_CONTACTS=100 - -D MAX_GROUP_CHANNELS=8 + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 -D PIO_FRAMEWORK_ARDUINO_ENABLE_BLUETOOTH + -D ENABLE_WIFI_INTERFACE -D BLE_PIN_CODE=123456 -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 -build_src_filter = ${rpi_picow.build_src_filter} - +<helpers/rp2040/SerialBLEInterface.cpp> - +<../examples/companion_radio/*.cpp> -lib_deps = ${rpi_picow.lib_deps} - densaugeo/base64 @ ~1.4.0 - -; USB + WiFi + BLE together; the interface manager fans frames out to all of them -[env:PicoW_companion_radio] -extends = rpi_picow -build_flags = ${rpi_picow.build_flags} - -D MAX_CONTACTS=100 - -D MAX_GROUP_CHANNELS=8 - -D ENABLE_USB_INTERFACE - -D ENABLE_WIFI_INTERFACE - -D PIO_FRAMEWORK_ARDUINO_ENABLE_BLUETOOTH - -D BLE_PIN_CODE=123456 -; NOTE: DO NOT ENABLE --> -D BLE_DEBUG_LOGGING=1 (shares Serial with the USB interface) -; NOTE: DO NOT ENABLE --> -D WIFI_DEBUG_LOGGING=1 -; -D MESH_PACKET_LOGGING=1 -; -D MESH_DEBUG=1 build_src_filter = ${rpi_picow.build_src_filter} +<helpers/rp2040/SerialBLEInterface.cpp> +<helpers/wifi/*.cpp> @@ -104,29 +85,11 @@ build_src_filter = ${rpi_picow.build_src_filter} lib_deps = ${rpi_picow.lib_deps} densaugeo/base64 @ ~1.4.0 -[env:PicoW_companion_radio_wifi] -extends = rpi_picow -build_flags = ${rpi_picow.build_flags} - -D ENABLE_WIFI_INTERFACE - -D MAX_CONTACTS=100 - -D MAX_GROUP_CHANNELS=8 - -D WIFI_DEBUG_LOGGING=1 - -D WIFI_SSID='""' ; no default network, configure with 'set wifi.ssid' / 'set wifi.pwd' - -D WIFI_PWD='""' -; -D MESH_PACKET_LOGGING=1 -; -D MESH_DEBUG=1 -build_src_filter = ${rpi_picow.build_src_filter} - +<helpers/wifi/*.cpp> - +<../examples/companion_radio/*.cpp> -lib_deps = ${rpi_picow.lib_deps} - densaugeo/base64 @ ~1.4.0 -lib_ignore = BLE - [env:PicoW_terminal_chat] extends = rpi_picow build_flags = ${rpi_picow.build_flags} - -D MAX_CONTACTS=100 - -D MAX_GROUP_CHANNELS=1 + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${rpi_picow.build_src_filter} @@ -138,3 +101,87 @@ lib_deps = ${rpi_picow.lib_deps} extends = rpi_picow build_src_filter = ${rpi_picow.build_src_filter} +<../examples/kiss_modem/> + +[rpi_pico2w] +extends = rp2040_base +board = rpipico2w +board_build.core = earlephilhower +board_build.filesystem_size = 0.5m +build_flags = ${rpi_picow.build_flags} +build_src_filter = ${rpi_picow.build_src_filter} +lib_deps = ${rpi_picow.lib_deps} + +[env:Pico2W_repeater] +extends = rpi_pico2w +build_flags = ${rpi_pico2w.build_flags} + -D ADVERT_NAME='"Pico2W Repeater"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=50 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${rpi_pico2w.build_src_filter} + +<../examples/simple_repeater> + +[env:Pico2W_room_server] +extends = rpi_pico2w +build_flags = ${rpi_pico2w.build_flags} + -D ADVERT_NAME='"Test Room"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D ROOM_PASSWORD='"hello"' +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${rpi_pico2w.build_src_filter} + +<../examples/simple_room_server> + +[env:Pico2W_companion_radio_usb] +extends = rpi_pico2w +build_flags = ${rpi_pico2w.build_flags} + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE +; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 +; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 +build_src_filter = ${rpi_pico2w.build_src_filter} + +<../examples/companion_radio/*.cpp> +lib_deps = ${rpi_pico2w.lib_deps} + densaugeo/base64 @ ~1.4.0 +lib_ignore = BLE + +[env:Pico2W_companion_radio_ble] +extends = rpi_pico2w +build_flags = ${rpi_pico2w.build_flags} + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D PIO_FRAMEWORK_ARDUINO_ENABLE_BLUETOOTH + -D ENABLE_WIFI_INTERFACE + -D BLE_PIN_CODE=123456 + -D BLE_DEBUG_LOGGING=1 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${rpi_pico2w.build_src_filter} + +<helpers/rp2040/SerialBLEInterface.cpp> + +<helpers/wifi/*.cpp> + +<../examples/companion_radio/*.cpp> +lib_deps = ${rpi_pico2w.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[env:Pico2W_terminal_chat] +extends = rpi_pico2w +build_flags = ${rpi_pico2w.build_flags} + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${rpi_pico2w.build_src_filter} + +<../examples/simple_secure_chat/main.cpp> +lib_deps = ${rpi_pico2w.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[env:Pico2W_kiss_modem] +extends = rpi_pico2w +build_src_filter = ${rpi_pico2w.build_src_filter} + +<../examples/kiss_modem/> From 683680d83b0f475db1cc2a5bac4f58ff10e69687 Mon Sep 17 00:00:00 2001 From: Rastislav Vysoky <recrof@gmail.com> Date: Sat, 7 Nov 2026 00:49:21 +0100 Subject: [PATCH 341/381] fix: pin to 5.6.0 --- platformio.ini | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/platformio.ini b/platformio.ini index 9ad9c890..f66fbf2e 100644 --- a/platformio.ini +++ b/platformio.ini @@ -101,8 +101,8 @@ lib_deps = extends = arduino_base upload_protocol = picotool board_build.core = earlephilhower -platform = https://github.com/maxgerhardt/platform-raspberrypi.git -platform_packages = framework-arduinopico @ https://github.com/earlephilhower/arduino-pico.git#6a1d13e960e0854da2bf328b1a5fc05481d89aba +; commit points to framework-arduinopico 5.6.0 +platform = https://github.com/maxgerhardt/platform-raspberrypi.git#4e22a0dcdd94eead72fdf56ea59a3d7c8aa2f379 build_flags = ${arduino_base.build_flags} -D RP2040_PLATFORM From 02081ba500c3cc4d3c3410a4fb6feae30e1b3501 Mon Sep 17 00:00:00 2001 From: Blake Latchford <github.demote149@passmail.com> Date: Sat, 7 Nov 2026 10:21:01 -0500 Subject: [PATCH 342/381] Incorporate PR Backtesting into CONTRIBUTING.md I used an LLM to review what changes the likelihood of a PR getting merged. I then asked it to select potential changes based on its findings. I selected from those options and carefully guided the LLM to produce several pull requests. I fed the subset of PRs that failed back into the skill and discovered additional missing factors. --- CONTRIBUTING.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b998610e..da30c3ae 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -18,6 +18,15 @@ Thanks for considering contributing to this project! ### 3. Submitting Code Changes (Pull Requests) +The project receives far more code than it is able to process. +To increase the likelihood of your PR being accepted, please consider +the following: + +- **Keep it small.** Changes of about 10 lines or fewer were merged 64% of the time; changes over 1000 lines, 10%. +- **Keep the description short.** A few sentences on what changed and why is enough. Longer descriptions were merged less often. +- **Build a track record with small fixes first.** First-time contributors were merged 31% of the time, rising to 74% after 10 merged PRs. +- **Open the PR when it is ready for review, not as a draft.** + #### Small fixes (typos, comments, examples, small bug fixes) → Just open a pull request — no prior issue needed @@ -52,6 +61,15 @@ Please follow the existing C++ style (per the .clang-format) (But consistency with existing code is more important than strict rules) +## LLM Agent Specific Advice + +- **Have a human read and understand every line before opening the PR.** Check every claim in the description against the code. +- **Search open PRs first** so you don't duplicate one that's already waiting. +- **Pick a subsystem maintainers are actively merging in.** If several PRs for the same board or feature have sat for weeks with no response, a new one will likely sit too. +- **Prefer low-risk changes.** Build fixes and documentation fixes merge most often (about 61% and 64%). Changes to protocol or behavior, and crash or overflow fixes, get much more scrutiny. +- **Make a minimal diff in the existing style.** Don't reformat, rename, or "tidy" code next to your change. +- **Don't use a templated description.** Lots of headings and boilerplate on a small change reads as generated. Just say what changed, why, and what hardware you tested on. + ## Thank You! > [!NOTE] From 2f00b0e83a8434bbbab14d20328826e5fc146233 Mon Sep 17 00:00:00 2001 From: anders-dc <anders@adamsgaard.dk> Date: Sun, 8 Nov 2026 11:01:05 +0100 Subject: [PATCH 343/381] fix(companion): guard null _serial in contact overwrite and full callbacks --- examples/companion_radio/MyMesh.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 755c56d1..28e5c3ec 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -341,7 +341,7 @@ uint8_t MyMesh::getAutoAddMaxHops() const { void MyMesh::onContactOverwrite(const uint8_t* pub_key) { _store->deleteBlobByKey(pub_key, PUB_KEY_SIZE); // delete from storage - if (_serial->isConnected()) { + if (_serial && _serial->isConnected()) { out_frame[0] = PUSH_CODE_CONTACT_DELETED; memcpy(&out_frame[1], pub_key, PUB_KEY_SIZE); _serial->writeFrame(out_frame, 1 + PUB_KEY_SIZE); @@ -349,7 +349,7 @@ void MyMesh::onContactOverwrite(const uint8_t* pub_key) { } void MyMesh::onContactsFull() { - if (_serial->isConnected()) { + if (_serial && _serial->isConnected()) { out_frame[0] = PUSH_CODE_CONTACTS_FULL; _serial->writeFrame(out_frame, 1); } From 81afafcb357e832d46aef4f4a79540044ee7158d Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Sun, 1 Nov 2026 20:08:16 -0400 Subject: [PATCH 344/381] gps: add GpsDriver, handle the hardware and software switches in the drivers --- examples/companion_radio/ui-new/UITask.cpp | 8 +- examples/companion_radio/ui-tiny/UITask.cpp | 8 +- examples/simple_repeater/MyMesh.h | 3 + examples/simple_room_server/MyMesh.h | 3 + examples/simple_sensor/SensorMesh.h | 3 + src/helpers/CommonCLI.cpp | 18 ++ src/helpers/CommonCLI.h | 2 + src/helpers/sensors/AirohaGpsDriver.h | 83 +++++ .../sensors/EnvironmentSensorManager.cpp | 249 ++------------- .../sensors/EnvironmentSensorManager.h | 5 - src/helpers/sensors/GpsDriver.h | 18 ++ src/helpers/sensors/LocationProvider.h | 19 ++ .../sensors/MicroNMEALocationProvider.h | 293 +++++++++--------- src/helpers/sensors/NmeaGpsDriver.h | 262 ++++++++++++++++ src/helpers/sensors/RakGpsDriver.h | 112 +++++++ src/helpers/sensors/RakLocationProvider.h | 144 +++++++++ variants/gat562_30s_mesh_kit/target.cpp | 7 +- variants/lilygo_techo/target.cpp | 5 +- variants/rak3401/target.cpp | 8 +- variants/rak4631/target.cpp | 7 +- variants/t1000-e/platformio.ini | 1 + variants/t1000-e/target.cpp | 24 +- variants/t1000-e/target.h | 6 +- variants/thinknode_m1/target.cpp | 59 +--- variants/thinknode_m1/target.h | 3 - variants/thinknode_m1/variant.h | 2 + variants/thinknode_m5/target.cpp | 5 +- variants/thinknode_m5/variant.h | 3 +- 28 files changed, 892 insertions(+), 468 deletions(-) create mode 100644 src/helpers/sensors/AirohaGpsDriver.h create mode 100644 src/helpers/sensors/GpsDriver.h create mode 100644 src/helpers/sensors/NmeaGpsDriver.h create mode 100644 src/helpers/sensors/RakGpsDriver.h create mode 100644 src/helpers/sensors/RakLocationProvider.h diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index 55cae1fe..cfe34cf2 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -392,16 +392,16 @@ public: char buf[50]; int y = 18; bool gps_state = _task->getGPSState(); -#ifdef PIN_GPS_SWITCH - bool hw_gps_state = digitalRead(PIN_GPS_SWITCH); + bool hw_gps_state = nmea != NULL && nmea->isHardwareEnabled(); + if (nmea != NULL && nmea->hasHardwareEnableState()) { if (gps_state != hw_gps_state) { strcpy(buf, gps_state ? "gps off(hw)" : "gps off(sw)"); } else { strcpy(buf, gps_state ? "gps on" : "gps off"); } -#else + } else { strcpy(buf, gps_state ? "gps on" : "gps off"); -#endif + } display.setColor(UIColor::primary_txt); display.drawTextLeftAlign(0, y, buf); if (nmea == NULL) { diff --git a/examples/companion_radio/ui-tiny/UITask.cpp b/examples/companion_radio/ui-tiny/UITask.cpp index 6bf33849..035340a8 100644 --- a/examples/companion_radio/ui-tiny/UITask.cpp +++ b/examples/companion_radio/ui-tiny/UITask.cpp @@ -254,16 +254,16 @@ public: char buf[50]; int y = 8; bool gps_state = _task->getGPSState(); -#ifdef PIN_GPS_SWITCH - bool hw_gps_state = digitalRead(PIN_GPS_SWITCH); + bool hw_gps_state = nmea != NULL && nmea->isHardwareEnabled(); + if (nmea != NULL && nmea->hasHardwareEnableState()) { if (gps_state != hw_gps_state) { strcpy(buf, gps_state ? "gps off(hw)" : "gps off(sw)"); } else { strcpy(buf, gps_state ? "gps on" : "gps off"); } -#else + } else { strcpy(buf, gps_state ? "gps on" : "gps off"); -#endif + } display.setColor(UIColor::primary_txt); display.drawTextLeftAlign(0, y, buf); if (nmea == NULL) { diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index dc893258..1d975a94 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -159,6 +159,9 @@ protected: #if ENV_INCLUDE_GPS == 1 void applyGpsPrefs() { + char period[11]; + snprintf(period, sizeof(period), "%lu", (unsigned long)_prefs.gps_period); + sensors.setSettingValue("gps_period", period); sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0"); } #endif diff --git a/examples/simple_room_server/MyMesh.h b/examples/simple_room_server/MyMesh.h index 4dee8bdb..5f8de73a 100644 --- a/examples/simple_room_server/MyMesh.h +++ b/examples/simple_room_server/MyMesh.h @@ -168,6 +168,9 @@ protected: #if ENV_INCLUDE_GPS == 1 void applyGpsPrefs() { + char period[11]; + snprintf(period, sizeof(period), "%lu", (unsigned long)_prefs.gps_period); + sensors.setSettingValue("gps_period", period); sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0"); } #endif diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index 590ca0c7..b93939de 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -173,6 +173,9 @@ private: #if ENV_INCLUDE_GPS == 1 void applyGpsPrefs() { + char period[11]; + snprintf(period, sizeof(period), "%lu", (unsigned long)_prefs.gps_period); + sensors.setSettingValue("gps_period", period); sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0"); } #endif diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index 5d7501d9..613f2578 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -368,6 +368,24 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re } else { strcpy(reply, "gps toggle not found"); } + } else if (memcmp(command, "gps period ", 11) == 0) { + char* end = nullptr; + unsigned long period = strtoul(command + 11, &end, 10); + if (command[11] == '\0' || *end != '\0' || period > 86400) { + strcpy(reply, "gps period must be 0-86400 seconds"); + } else { + char period_value[11]; + snprintf(period_value, sizeof(period_value), "%lu", period); + if (_sensors->setSettingValue("gps_period", period_value) && + _sensors->setSettingValue("gps", "1")) { + _prefs->gps_period = (uint32_t)period; + _prefs->gps_enabled = 1; + savePrefs(); + strcpy(reply, "ok"); + } else { + strcpy(reply, "gps provider not found"); + } + } } else if (memcmp(command, "gps sync", 8) == 0) { LocationProvider * l = _sensors->getLocationProvider(); if (l != NULL) { diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 675df7a4..06778a60 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -61,6 +61,7 @@ public: // Gps settings uint8_t gps_enabled = 0; uint32_t gps_interval = 0; // in seconds + uint32_t gps_period = 0; // periodic acquisition interval in seconds uint8_t advert_loc_policy = 0; uint32_t discovery_mod_timestamp = 0; float adc_multiplier = 0; @@ -158,6 +159,7 @@ private: void structure() override { def("en", _parent->gps_enabled); // boolean def("int", _parent->gps_interval); // interval in seconds + def("period", _parent->gps_period); // periodic acquisition interval in seconds def("adv_loc", _parent->advert_loc_policy); } public: diff --git a/src/helpers/sensors/AirohaGpsDriver.h b/src/helpers/sensors/AirohaGpsDriver.h new file mode 100644 index 00000000..36d5eb6b --- /dev/null +++ b/src/helpers/sensors/AirohaGpsDriver.h @@ -0,0 +1,83 @@ +#pragma once + +#include "NmeaGpsDriver.h" + +class AirohaGpsDriver : public NmeaGpsDriver { + bool waitFor(const char* prefix, uint32_t timeout_ms) { // TODO: Refactor so it doesn't block the loop ! + char sentence[100]; + size_t length = 0; + const size_t prefixLength = strlen(prefix); + const uint32_t deadline = millis() + timeout_ms; + + while ((int32_t)(millis() - deadline) < 0) { + if (available() <= 0) { + yield(); + continue; + } + + const char c = (char)read(); +#ifdef GPS_NMEA_DEBUG + Serial.print(c); +#endif + if (c == '$') length = 0; + if (length < sizeof(sentence) - 1) { + sentence[length++] = c; + sentence[length] = '\0'; + if (length >= prefixLength && strncmp(sentence, prefix, prefixLength) == 0) { + return true; + } + } + } + return false; + } + + void enterBackupSleep() { + for (uint8_t attempt = 0; attempt < 3; attempt++) { + drain(); + sendNmeaSentence("$PAIR650,0"); + if (waitFor("$PAIR001,650,0", 50)) { +#ifdef GPS_NMEA_DEBUG + Serial.printf("Airoha RTC backup sleep accepted after %u attempts\r\n", attempt + 1); +#endif + waitFor("$PAIR650,0", 50); + return; + } + } + } + +public: + AirohaGpsDriver(HardwareSerial& serial) + : NmeaGpsDriver(serial, -1, -1, -1, -1, nullptr, HIGH, LOW, 115200) {} + + void initialize() { + NmeaGpsDriver::begin(); + reset(); + } + + void begin() override { + NmeaGpsDriver::begin(); + digitalWrite(GPS_EN, HIGH); + delay(10); + digitalWrite(GPS_RTC_INT, HIGH); + delay(5); + digitalWrite(GPS_RTC_INT, LOW); + } + + void reset() override { + digitalWrite(GPS_RESET, HIGH); + delay(10); + digitalWrite(GPS_RESET, LOW); + } + + void stop() override { + digitalWrite(GPS_VRTC_EN, HIGH); + digitalWrite(GPS_RTC_INT, LOW); + enterBackupSleep(); + digitalWrite(GPS_EN, LOW); + NmeaGpsDriver::stop(); + } + + bool isEnabled() const override { + return digitalRead(GPS_EN) == HIGH; + } +}; diff --git a/src/helpers/sensors/EnvironmentSensorManager.cpp b/src/helpers/sensors/EnvironmentSensorManager.cpp index 0dc892c3..2861fac2 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.cpp +++ b/src/helpers/sensors/EnvironmentSensorManager.cpp @@ -160,56 +160,6 @@ static Adafruit_VL53L0X VL53L0X; static RAK12035_SoilMoisture RAK12035; #endif -#if ENV_INCLUDE_GPS && defined(RAK_BOARD) && !defined(RAK_WISMESH_TAG) -#define RAK_WISBLOCK_GPS -#endif - -#ifdef RAK_WISBLOCK_GPS -static uint32_t gpsResetPin = 0; -static bool i2cGPSFlag = false; -static bool serialGPSFlag = false; -#ifndef TELEM_RAK12500_ADDRESS -#define TELEM_RAK12500_ADDRESS 0x42 //RAK12500 Ublox GPS via i2c -#endif -#include <SparkFun_u-blox_GNSS_Arduino_Library.h> -static SFE_UBLOX_GNSS ublox_GNSS; - -class RAK12500LocationProvider : public LocationProvider { - long _lat = 0; - long _lng = 0; - long _alt = 0; - int _sats = 0; - long _epoch = 0; - bool _fix = false; -public: - long getLatitude() override { return _lat; } - long getLongitude() override { return _lng; } - long getAltitude() override { return _alt; } - long satellitesCount() override { return _sats; } - bool isValid() override { return _fix; } - long getTimestamp() override { return _epoch; } - void sendSentence(const char * sentence) override { } - void reset() override { } - void begin() override { } - void stop() override { } - void loop() override { - if (ublox_GNSS.getGnssFixOk(8)) { - _fix = true; - _lat = ublox_GNSS.getLatitude(2) / 10; - _lng = ublox_GNSS.getLongitude(2) / 10; - _alt = ublox_GNSS.getAltitude(2); - _sats = ublox_GNSS.getSIV(2); - } else { - _fix = false; - } - _epoch = ublox_GNSS.getUnixEpoch(2); - } - bool isEnabled() override { return true; } -}; - -static RAK12500LocationProvider RAK12500_provider; -#endif - // ============================================================ // I2C bus scanner // Probes every valid address and records which ones ACK. @@ -624,12 +574,8 @@ static const size_t SENSOR_TABLE_SIZE = (sizeof(SENSOR_TABLE) / sizeof(SENSOR_TA bool EnvironmentSensorManager::begin() { #if ENV_INCLUDE_GPS - #ifdef RAK_WISBLOCK_GPS - rakGPSInit(); - #else initBasicGPS(); #endif - #endif #if ENV_PIN_SDA && ENV_PIN_SCL #ifdef NRF52_PLATFORM @@ -684,9 +630,11 @@ bool EnvironmentSensorManager::begin() { bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, CayenneLPP& telemetry) { next_available_channel = TELEM_CHANNEL_SELF + 1; - if (requester_permissions & TELEM_PERM_LOCATION && gps_active) { + #if ENV_INCLUDE_GPS + if (requester_permissions & TELEM_PERM_LOCATION && _location->isEnabled()) { telemetry.addGPS(TELEM_CHANNEL_SELF, node_lat, node_lon, node_altitude); } + #endif if (requester_permissions & TELEM_PERM_ENVIRONMENT) { for (int i = 0; i < _active_sensor_count; i++) { @@ -702,7 +650,7 @@ bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, Cayen int EnvironmentSensorManager::getNumSettings() const { int settings = 0; #if ENV_INCLUDE_GPS - if (gps_detected) settings++; // only show GPS setting if GPS is detected + if (gps_detected) settings += 2; // GPS enablement and periodic acquisition #endif return settings; } @@ -713,6 +661,9 @@ const char* EnvironmentSensorManager::getSettingName(int i) const { if (gps_detected && i == settings++) { return "gps"; } + if (gps_detected && i == settings++) { + return "gps_period"; + } #endif return NULL; } @@ -721,7 +672,13 @@ const char* EnvironmentSensorManager::getSettingValue(int i) const { int settings = 0; #if ENV_INCLUDE_GPS if (gps_detected && i == settings++) { - return gps_active ? "1" : "0"; + return _location->isGpsOn() ? "1" : "0"; + } + if (gps_detected && i == settings++) { + static char period[11]; + snprintf(period, sizeof(period), "%lu", + (unsigned long)_location->getGpsPeriod()); + return period; } #endif return NULL; @@ -737,6 +694,13 @@ bool EnvironmentSensorManager::setSettingValue(const char* name, const char* val } return true; } + if (gps_detected && strcmp(name, "gps_period") == 0) { + char* end = nullptr; + unsigned long period = strtoul(value, &end, 10); + if (*value == '\0' || *end != '\0' || period > 86400) return false; + _location->setGpsPeriod((uint32_t)period); + return true; + } if (strcmp(name, "gps_interval") == 0) { uint32_t interval_seconds = atoi(value); gps_update_interval_sec = interval_seconds > 0 ? interval_seconds : 1; @@ -748,157 +712,35 @@ bool EnvironmentSensorManager::setSettingValue(const char* name, const char* val #if ENV_INCLUDE_GPS void EnvironmentSensorManager::initBasicGPS() { - - Serial1.setPins(PIN_GPS_TX, PIN_GPS_RX); - - #ifdef GPS_BAUD_RATE - Serial1.begin(GPS_BAUD_RATE); - #else - Serial1.begin(9600); - #endif - - // Try to detect if GPS is physically connected to determine if we should expose the setting - _location->begin(); - _location->reset(); + start_gps(); #ifndef PIN_GPS_EN MESH_DEBUG_PRINTLN("No GPS wake/reset pin found for this board. Continuing on..."); #endif - // Give the GPS time to power up and emit its first NMEA sentence. Cold-start - // modules can take several seconds, so poll for up to ~5s instead of checking - // once after a fixed 1s delay -- returning as soon as any data appears, so - // fast modules add no boot delay (issue #2258). #ifdef ENV_SKIP_GPS_DETECT gps_detected = true; #else - gps_detected = false; - for (int i = 0; i < 20 && !gps_detected; i++) { - delay(250); - gps_detected = (Serial1.available() > 0); - } + gps_detected = _location->detect(5000); #endif if (gps_detected) { MESH_DEBUG_PRINTLN("GPS detected"); - #ifdef PERSISTANT_GPS - gps_active = true; + #if defined(PERSISTANT_GPS) return; + #else + if (_location->keepEnabledAfterDetection()) { + return; + } #endif } else { MESH_DEBUG_PRINTLN("No GPS detected"); } - _location->stop(); - gps_active = false; //Set GPS visibility off until setting is changed -} - -// gps code for rak might be moved to MicroNMEALoactionProvider -// or make a new location provider ... -#ifdef RAK_WISBLOCK_GPS -void EnvironmentSensorManager::rakGPSInit(){ - - Serial1.setPins(PIN_GPS_TX, PIN_GPS_RX); - - #ifdef GPS_BAUD_RATE - Serial1.begin(GPS_BAUD_RATE); - #else - Serial1.begin(9600); - #endif - - //search for the correct IO standby pin depending on socket used - if(gpsIsAwake(WB_IO2)){ - } - else if(gpsIsAwake(WB_IO4)){ - } - else if(gpsIsAwake(WB_IO5)){ - } - else{ - MESH_DEBUG_PRINTLN("No GPS found"); - gps_active = false; - gps_detected = false; - Serial1.end(); - return; - } - - #ifndef FORCE_GPS_ALIVE // for use with repeaters, until GPS toggle is implimented - //Now that GPS is found and set up, set to sleep for initial state stop_gps(); - #endif } -bool EnvironmentSensorManager::gpsIsAwake(uint8_t ioPin){ - - #if defined(ETHERNET_ENABLED) && defined(RAK_BOARD) - if (ioPin == WB_IO2) { - // WB_IO2 powers the Ethernet module on RAK baseboards. - return false; - } - #endif - - #ifndef RAK_3401 - //set initial waking state - pinMode(ioPin,OUTPUT); - digitalWrite(ioPin,LOW); - delay(500); - digitalWrite(ioPin,HIGH); - #endif - - // give gps time to power up - delay(500); - - //Try to init RAK12500 on I2C - if (ublox_GNSS.begin(Wire) == true){ - MESH_DEBUG_PRINTLN("RAK12500 GPS init correctly with pin %i",ioPin); - ublox_GNSS.setI2COutput(COM_TYPE_UBX); - ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_GPS); - ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_GALILEO); - ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_GLONASS); - ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_SBAS); - ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_BEIDOU); - ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_IMES); - ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_QZSS); - ublox_GNSS.setMeasurementRate(1000); - ublox_GNSS.saveConfigSelective(VAL_CFG_SUBSEC_IOPORT); - gpsResetPin = ioPin; - i2cGPSFlag = true; - gps_active = true; - gps_detected = true; - - _location = &RAK12500_provider; - return true; - } else if (Serial1.available()) { - MESH_DEBUG_PRINTLN("Serial GPS init correctly and is turned on"); -#ifdef PIN_GPS_EN - if(PIN_GPS_EN){ - gpsResetPin = PIN_GPS_EN; - } -#endif - serialGPSFlag = true; - gps_active = true; - gps_detected = true; - return true; - } - - #ifndef RAK_3401 - pinMode(ioPin, INPUT); - #endif - MESH_DEBUG_PRINTLN("GPS did not init with this IO pin... try the next"); - return false; -} -#endif - void EnvironmentSensorManager::start_gps() { - gps_active = true; - #ifdef RAK_WISBLOCK_GPS - #ifndef RAK_3401 - pinMode(gpsResetPin, OUTPUT); - digitalWrite(gpsResetPin, HIGH); - #endif - return; - #endif - - _location->begin(); - _location->reset(); + _location->setGpsOn(true); #ifndef PIN_GPS_EN MESH_DEBUG_PRINTLN("Start GPS is N/A on this board. Actual GPS state unchanged"); @@ -906,20 +748,11 @@ void EnvironmentSensorManager::start_gps() { } void EnvironmentSensorManager::stop_gps() { - gps_active = false; - #ifdef RAK_WISBLOCK_GPS - #ifndef RAK_3401 // rak3401 shouldn't turn off WB_IO2 as it powers the PA - pinMode(gpsResetPin, OUTPUT); - digitalWrite(gpsResetPin, LOW); - #endif - return; - #endif + _location->setGpsOn(false); - _location->stop(); - - #ifndef PIN_GPS_EN +#ifndef PIN_GPS_EN MESH_DEBUG_PRINTLN("Stop GPS is N/A on this board. Actual GPS state unchanged"); - #endif +#endif } #endif // ENV_INCLUDE_GPS @@ -928,30 +761,16 @@ void EnvironmentSensorManager::loop() { #if ENV_INCLUDE_GPS static unsigned long next_gps_update = 0; - if (gps_active) { - _location->loop(); - } + _location->loop(); if ((long)(millis() - next_gps_update) > 0) { - if(gps_active){ - #ifdef RAK_WISBLOCK_GPS - if ((i2cGPSFlag || serialGPSFlag) && _location->isValid()) { + if (_location->isEnabled() && _location->isValid()) { node_lat = ((double)_location->getLatitude())/1000000.; node_lon = ((double)_location->getLongitude())/1000000.; MESH_DEBUG_PRINTLN("lat %f lon %f", node_lat, node_lon); node_altitude = ((double)_location->getAltitude()) / 1000.0; MESH_DEBUG_PRINTLN("lat %f lon %f alt %f", node_lat, node_lon, node_altitude); } - #else - if (_location->isValid()) { - node_lat = ((double)_location->getLatitude())/1000000.; - node_lon = ((double)_location->getLongitude())/1000000.; - MESH_DEBUG_PRINTLN("lat %f lon %f", node_lat, node_lon); - node_altitude = ((double)_location->getAltitude()) / 1000.0; - MESH_DEBUG_PRINTLN("lat %f lon %f alt %f", node_lat, node_lon, node_altitude); - } - #endif - } next_gps_update = millis() + (gps_update_interval_sec * 1000); } #endif diff --git a/src/helpers/sensors/EnvironmentSensorManager.h b/src/helpers/sensors/EnvironmentSensorManager.h index 17706cbc..425415a1 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.h +++ b/src/helpers/sensors/EnvironmentSensorManager.h @@ -20,7 +20,6 @@ protected: uint8_t next_available_channel = TELEM_CHANNEL_SELF + 1; bool gps_detected = false; - bool gps_active = false; uint32_t gps_update_interval_sec = 1; #if ENV_INCLUDE_GPS @@ -28,10 +27,6 @@ protected: void start_gps(); void stop_gps(); void initBasicGPS(); - #ifdef RAK_BOARD - void rakGPSInit(); - bool gpsIsAwake(uint8_t ioPin); - #endif #endif public: diff --git a/src/helpers/sensors/GpsDriver.h b/src/helpers/sensors/GpsDriver.h new file mode 100644 index 00000000..b8cf4a5d --- /dev/null +++ b/src/helpers/sensors/GpsDriver.h @@ -0,0 +1,18 @@ +#pragma once + +#include <stdint.h> + +class GpsDriver { +public: + virtual ~GpsDriver() = default; + + virtual void begin() = 0; + virtual void reset() = 0; + virtual void stop() = 0; + virtual bool isEnabled() const = 0; + virtual bool hasHardwareEnableState() const { return false; } + virtual bool isHardwareEnabled() const { return true; } + // Returns true when the switch explicitly enables GPS in software. + virtual bool pollGpsSwitch() { return false; } + virtual bool detect(uint32_t timeout_ms) = 0; +}; diff --git a/src/helpers/sensors/LocationProvider.h b/src/helpers/sensors/LocationProvider.h index bc4f1fe7..93cecf5b 100644 --- a/src/helpers/sensors/LocationProvider.h +++ b/src/helpers/sensors/LocationProvider.h @@ -8,8 +8,11 @@ class LocationProvider { protected: bool _time_sync_needed = true; + bool _gpsOn = false; public: + virtual ~LocationProvider() = default; + virtual void syncTime() { _time_sync_needed = true; } virtual bool waitingTimeSync() { return _time_sync_needed; } virtual long getLatitude() = 0; @@ -21,6 +24,22 @@ public: virtual void sendSentence(const char * sentence); virtual bool waitFor(const char* prefix, uint32_t timeout_ms) { return false; } virtual void drain() { } + virtual bool detect(uint32_t timeout_ms) { return false; } + virtual bool keepEnabledAfterDetection() const { return false; } + virtual void setGpsPeriod(uint32_t seconds) { } + virtual uint32_t getGpsPeriod() const { return 0; } + virtual bool hasHardwareEnableState() const { return false; } + virtual bool isHardwareEnabled() const { return true; } + virtual bool isGpsOn() const { return _gpsOn; } + virtual void setGpsOn(bool on) { + _gpsOn = on; + if (on) { + begin(); + reset(); + } else { + stop(); + } + } virtual void reset() = 0; virtual void begin() = 0; virtual void stop() = 0; diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index 37ef5762..2e9ff9cc 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -1,69 +1,30 @@ #pragma once +#include "NmeaGpsDriver.h" #include "LocationProvider.h" #include <MicroNMEA.h> #include <RTClib.h> -#include <helpers/RefCountedDigitalPin.h> #include <string.h> -#ifndef GPS_EN - #ifdef PIN_GPS_EN - #define GPS_EN PIN_GPS_EN - #else - #define GPS_EN (-1) - #endif -#endif - -#ifndef GPS_EN_ACTIVE - #ifdef PIN_GPS_EN_ACTIVE - #define GPS_EN_ACTIVE PIN_GPS_EN_ACTIVE - #else - #define GPS_EN_ACTIVE HIGH - #endif -#endif - -#ifndef GPS_RESET - #ifdef PIN_GPS_RESET - #define GPS_RESET PIN_GPS_RESET - #else - #define GPS_RESET (-1) - #endif -#endif - -#ifndef GPS_RESET_ACTIVE - #ifdef PIN_GPS_RESET_ACTIVE - #define GPS_RESET_ACTIVE PIN_GPS_RESET_ACTIVE - #else - #define GPS_RESET_ACTIVE LOW - #endif +#ifndef GPS_PERIODIC_ACQUISITION_TIMEOUT_MS + #define GPS_PERIODIC_ACQUISITION_TIMEOUT_MS 120000UL #endif class MicroNMEALocationProvider : public LocationProvider { char _nmeaBuffer[100]; MicroNMEA nmea; mesh::RTCClock* _clock; - Stream* _gps_serial; - RefCountedDigitalPin* _peripher_power; - int8_t _claims = 0; - int _pin_reset; - int _pin_en; + NmeaGpsDriver* _driver; + bool _ownsDriver = false; unsigned long next_check = 0; long time_valid = 0; unsigned long _last_time_sync = 0; - static const unsigned long TIME_SYNC_INTERVAL = 1800000; // Re-sync every 30 minutes + uint32_t _gpsPeriodSeconds = 0; + unsigned long _nextAcquisition = 0; + unsigned long _acquisitionStarted = 0; + bool _acquiringPeriodically = false; + static const unsigned long TIME_SYNC_INTERVAL = 1800000; -#ifdef GPS_L76K - void configureL76K() { - // Reapply the constellation mode at each provider start instead of - // assuming it survives a receiver power cycle. - // Mode 7 enables GPS + BeiDou + GLONASS. - delay(250); - MicroNMEA::sendSentence(*_gps_serial, "$PCAS04,7"); - delay(250); - } -#endif - // Observation-only diagnostics. These fields do not change GPS power, - // timing, reset behaviour, or parser input. uint32_t _uart_bytes = 0; uint32_t _nmea_checksum_ok = 0; uint32_t _nmea_checksum_bad = 0; @@ -88,79 +49,121 @@ class MicroNMEALocationProvider : public LocationProvider { } } -public : - MicroNMEALocationProvider(Stream& ser, mesh::RTCClock* clock = NULL, int pin_reset = GPS_RESET, int pin_en = GPS_EN,RefCountedDigitalPin* peripher_power=NULL) : - nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), _gps_serial(&ser), _peripher_power(peripher_power), _pin_reset(pin_reset), _pin_en(pin_en) { - if (_pin_reset != -1) { - pinMode(_pin_reset, OUTPUT); - digitalWrite(_pin_reset, GPS_RESET_ACTIVE); - } - if (_pin_en != -1) { - pinMode(_pin_en, OUTPUT); - digitalWrite(_pin_en, !GPS_EN_ACTIVE); - } + void startPeriodicAcquisition() { + nmea.clear(); + time_valid = 0; + _driver->begin(); + _driver->reset(); + _acquiringPeriodically = true; + _acquisitionStarted = millis(); } - void claim() { - _claims++; - if (_peripher_power) _peripher_power->claim(); + void finishPeriodicAcquisition() { + _driver->stop(); + _acquiringPeriodically = false; + _nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL; } - void release() { - if (_claims == 0) return; // avoid negative _claims - _claims--; - if (_peripher_power) _peripher_power->release(); + void updateTime() { + if (!isValid()) time_valid = 0; + + if ((long)(millis() - next_check) <= 0) return; + next_check = millis() + 1000; + + if (!_time_sync_needed && _clock != nullptr && + (millis() - _last_time_sync) > TIME_SYNC_INTERVAL) { + _time_sync_needed = true; + } + if (_time_sync_needed && time_valid > 2 && _clock != nullptr) { + _clock->setCurrentTime(getTimestamp()); + _time_sync_needed = false; + _last_time_sync = millis(); + } + if (isValid()) time_valid++; + } + +public: + MicroNMEALocationProvider(NmeaGpsDriver& driver, mesh::RTCClock* clock = nullptr) + : nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), _driver(&driver) {} + + // Temporary migration adapter for targets and downstream boards. New code + // should inject a GpsDriver; this constructor will be removed once targets + // have been migrated. + MicroNMEALocationProvider(HardwareSerial& serial, mesh::RTCClock* clock = nullptr, + int pin_reset = GPS_RESET, int pin_en = GPS_EN, + RefCountedDigitalPin* peripher_power = nullptr) + : nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), + _driver(new NmeaGpsDriver(serial, PIN_GPS_TX, PIN_GPS_RX, pin_reset, pin_en, + peripher_power)), + _ownsDriver(true) {} + + MicroNMEALocationProvider(Stream& serial, mesh::RTCClock* clock = nullptr, + int pin_reset = GPS_RESET, int pin_en = GPS_EN, + RefCountedDigitalPin* peripher_power = nullptr) + : nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), + _driver(new NmeaGpsDriver(serial, PIN_GPS_TX, PIN_GPS_RX, pin_reset, pin_en, + peripher_power)), + _ownsDriver(true) {} + + ~MicroNMEALocationProvider() override { + if (_ownsDriver) delete _driver; } void begin() override { _begin_calls++; - claim(); - if (_pin_en != -1) { - digitalWrite(_pin_en, GPS_EN_ACTIVE); - } - if (_pin_reset != -1) { - digitalWrite(_pin_reset, !GPS_RESET_ACTIVE); + _driver->begin(); + if (_gpsPeriodSeconds > 0 && _driver->isEnabled()) { + nmea.clear(); + time_valid = 0; + _acquiringPeriodically = true; + _acquisitionStarted = millis(); } } void reset() override { - if (_pin_reset != -1) { - digitalWrite(_pin_reset, GPS_RESET_ACTIVE); - delay(10); - digitalWrite(_pin_reset, !GPS_RESET_ACTIVE); - } -#ifdef GPS_L76K - // EnvironmentSensorManager calls reset() immediately after begin(). - // Configure only after that reset so the setting is not discarded. - configureL76K(); -#endif + _driver->reset(); } void stop() override { _stop_calls++; - if (_pin_en != -1) { - digitalWrite(_pin_en, !GPS_EN_ACTIVE); - } - if (_pin_reset != -1) { - digitalWrite(_pin_reset, GPS_RESET_ACTIVE); - } - release(); + _acquiringPeriodically = false; + _driver->stop(); } bool isEnabled() override { - // directly read the enable pin if present as gps can be - // activated/deactivated outside of here ... - if (_pin_en != -1) { - return digitalRead(_pin_en) == GPS_EN_ACTIVE; - } else { - return true; // no enable so must be active - } + return _driver->isEnabled(); + } + + bool hasHardwareEnableState() const override { + return _driver->hasHardwareEnableState(); + } + + bool isHardwareEnabled() const override { + return _driver->isHardwareEnabled(); + } + + bool detect(uint32_t timeout_ms) override { + return _driver->detect(timeout_ms); + } + + void setGpsPeriod(uint32_t seconds) override { + _gpsPeriodSeconds = seconds; + _nextAcquisition = millis(); + _acquiringPeriodically = false; + } + + uint32_t getGpsPeriod() const override { + return _gpsPeriodSeconds; + } + + void syncTime() override { + nmea.clear(); + LocationProvider::syncTime(); } - void syncTime() override { nmea.clear(); LocationProvider::syncTime(); } long getLatitude() override { return nmea.getLatitude(); } long getLongitude() override { return nmea.getLongitude(); } - long getAltitude() override { + long getAltitude() override { long alt = 0; nmea.getAltitude(alt); return alt; @@ -168,29 +171,31 @@ public : long satellitesCount() override { return nmea.getNumSatellites(); } bool isValid() override { return nmea.isValid(); } - long getTimestamp() override { - DateTime dt(nmea.getYear(), nmea.getMonth(),nmea.getDay(),nmea.getHour(),nmea.getMinute(),nmea.getSecond()); + long getTimestamp() override { + DateTime dt(nmea.getYear(), nmea.getMonth(), nmea.getDay(), + nmea.getHour(), nmea.getMinute(), nmea.getSecond()); return dt.unixtime(); - } - - void drain() { while (_gps_serial->available()) _gps_serial->read(); } - - const char* getSentence() const { return nmea.getSentence(); } - - void sendSentence(const char *sentence) override { - nmea.sendSentence(*_gps_serial, sentence); } - bool waitFor(const char* prefix, uint32_t timeout_ms) { - size_t plen = strlen(prefix); - uint32_t timeout = millis() + timeout_ms; - while ((int32_t)(millis() - timeout) < 0) { - if (_gps_serial->available()) { - char c = _gps_serial->read(); - #ifdef GPS_NMEA_DEBUG + void drain() override { _driver->drain(); } + const char* getSentence() const { return nmea.getSentence(); } + + void sendSentence(const char* sentence) override { + _driver->sendNmeaSentence(sentence); + } + + bool waitFor(const char* prefix, uint32_t timeout_ms) override { + const size_t prefixLength = strlen(prefix); + const uint32_t deadline = millis() + timeout_ms; + while ((int32_t)(millis() - deadline) < 0) { + if (_driver->available() > 0) { + const char c = (char)_driver->read(); +#ifdef GPS_NMEA_DEBUG Serial.print(c); - #endif - if (nmea.process(c) && strncmp(nmea.getSentence(), prefix, plen) == 0) return true; +#endif + if (nmea.process(c) && strncmp(nmea.getSentence(), prefix, prefixLength) == 0) { + return true; + } } else { yield(); } @@ -199,34 +204,35 @@ public : } void loop() override { + if (_driver->pollGpsSwitch()) _gpsOn = true; - while (_gps_serial->available()) { - char c = _gps_serial->read(); + if (_gpsOn && _gpsPeriodSeconds > 0 && !_acquiringPeriodically && + (long)(millis() - _nextAcquisition) >= 0) { + startPeriodicAcquisition(); + } + + while (_driver->available() > 0) { + const char c = (char)_driver->read(); _uart_bytes++; _last_uart_ms = millis(); _uart_seen = true; - #ifdef GPS_NMEA_DEBUG +#ifdef GPS_NMEA_DEBUG Serial.print(c); - #endif - bool parsed = nmea.process(c); +#endif + const bool parsed = nmea.process(c); - // MicroNMEA leaves the completed sentence in its buffer after the - // first line terminator. CRLF therefore counts once: CR observes the - // sentence, then LF clears the now-empty buffer. if ((c == '\0' || c == '\r' || c == '\n') && nmea.getSentence()[0] != '\0') { if (MicroNMEA::testChecksum(nmea.getSentence())) { _nmea_checksum_ok++; _last_nmea_ms = millis(); _nmea_seen = true; - // Refresh fix age only when a newly parsed GGA/RMC sentence - // carries a valid fix. Other valid NMEA sentences must not - // make an old position look fresh. - const char* message_id = nmea.getMessageID(); + const char* messageId = nmea.getMessageID(); if (parsed && isValid() && - (strcmp(message_id, "GGA") == 0 || strcmp(message_id, "RMC") == 0)) { + (strcmp(messageId, "GGA") == 0 || strcmp(messageId, "RMC") == 0)) { _last_fix_ms = millis(); _fix_seen = true; + if (_acquiringPeriodically) finishPeriodicAcquisition(); } } else { _nmea_checksum_bad++; @@ -234,25 +240,12 @@ public : } } - if (!isValid()) time_valid = 0; - - if ((long)(millis() - next_check) > 0) { - next_check = millis() + 1000; - // Re-enable time sync periodically when GPS has valid fix - if (!_time_sync_needed && _clock != NULL && (millis() - _last_time_sync) > TIME_SYNC_INTERVAL) { - _time_sync_needed = true; - } - if (_time_sync_needed && time_valid > 2) { - if (_clock != NULL) { - _clock->setCurrentTime(getTimestamp()); - _time_sync_needed = false; - _last_time_sync = millis(); - } - } - if (isValid()) { - time_valid ++; - } + if (_acquiringPeriodically && + (uint32_t)(millis() - _acquisitionStarted) >= GPS_PERIODIC_ACQUISITION_TIMEOUT_MS) { + finishPeriodicAcquisition(); } + + updateTime(); } void formatDiagnostics(char* out, size_t out_size) override { @@ -265,8 +258,6 @@ public : formatAge(nmea_age, sizeof(nmea_age), _nmea_seen, _last_nmea_ms); formatAge(fix_age, sizeof(fix_age), _fix_seen, _last_fix_ms); - // Compact enough for CommonCLI's 160-byte reply buffer, including the - // "req:" prefix added by CommonCLI. snprintf(out, out_size, "en:%u ub:%lu ua:%s ok:%lu bad:%lu na:%s sat:%ld fix:%u fa:%s bc:%lu sc:%lu", isEnabled() ? 1U : 0U, diff --git a/src/helpers/sensors/NmeaGpsDriver.h b/src/helpers/sensors/NmeaGpsDriver.h new file mode 100644 index 00000000..f9ea5124 --- /dev/null +++ b/src/helpers/sensors/NmeaGpsDriver.h @@ -0,0 +1,262 @@ +#pragma once + +#include "GpsDriver.h" + +#include <Arduino.h> +#include <helpers/RefCountedDigitalPin.h> + +#ifndef PIN_GPS_TX + #define PIN_GPS_TX (-1) +#endif + +#ifndef PIN_GPS_RX + #define PIN_GPS_RX (-1) +#endif + +#ifndef GPS_EN + #ifdef PIN_GPS_EN + #define GPS_EN PIN_GPS_EN + #else + #define GPS_EN (-1) + #endif +#endif + +#ifndef GPS_EN_ACTIVE + #ifdef PIN_GPS_EN_ACTIVE + #define GPS_EN_ACTIVE PIN_GPS_EN_ACTIVE + #else + #define GPS_EN_ACTIVE HIGH + #endif +#endif + +#ifndef GPS_RESET + #ifdef PIN_GPS_RESET + #define GPS_RESET PIN_GPS_RESET + #else + #define GPS_RESET (-1) + #endif +#endif + +#ifndef GPS_RESET_ACTIVE + #ifdef PIN_GPS_RESET_ACTIVE + #define GPS_RESET_ACTIVE PIN_GPS_RESET_ACTIVE + #else + #define GPS_RESET_ACTIVE LOW + #endif +#endif + +#ifndef GPS_BAUD_RATE + #define GPS_BAUD_RATE 9600 +#endif + +#ifndef PIN_GPS_SWITCH + #define PIN_GPS_SWITCH (-1) +#endif + +#ifndef GPS_SWITCH_ACTIVE + #define GPS_SWITCH_ACTIVE HIGH +#endif + +#ifndef GPS_SWITCH_IS_HARDWARE + #define GPS_SWITCH_IS_HARDWARE 1 +#endif + +#ifndef GPS_SWITCH_TURNS_GPS_ON + #define GPS_SWITCH_TURNS_GPS_ON 0 +#endif + +class NmeaGpsDriver : public GpsDriver { + Stream* _stream = nullptr; + HardwareSerial* _hardwareSerial = nullptr; + RefCountedDigitalPin* _peripheralPower = nullptr; + int _txPin = -1; + int _rxPin = -1; + int _resetPin = -1; + int _enablePin = -1; + int _enableActive = HIGH; + int _resetActive = LOW; + uint32_t _baudRate = 9600; + int _hardwareEnablePin = -1; + int _hardwareEnableActive = HIGH; + bool _started = false; +#if !GPS_SWITCH_IS_HARDWARE + bool _requestedOn = false; + bool _switchStateKnown = false; + bool _lastSwitchEnabled = false; + unsigned long _nextSwitchPoll = 0; +#endif + + void startHardware() { + if (_stream == nullptr || _started) return; + + if (_hardwareSerial != nullptr) { +#ifdef ESP32_PLATFORM + _hardwareSerial->setPins(_txPin, _rxPin); +#endif + _hardwareSerial->begin(_baudRate); + } + + if (_peripheralPower != nullptr) _peripheralPower->claim(); + + if (_enablePin != -1) digitalWrite(_enablePin, _enableActive); + if (_resetPin != -1) digitalWrite(_resetPin, !_resetActive); + _started = true; + } + + void stopHardware() { + if (!_started) return; + + if (_enablePin != -1) digitalWrite(_enablePin, !_enableActive); + if (_resetPin != -1) digitalWrite(_resetPin, _resetActive); + + if (_peripheralPower != nullptr) _peripheralPower->release(); + _started = false; + } + +public: + NmeaGpsDriver() = default; + + NmeaGpsDriver(Stream& stream, int txPin = PIN_GPS_TX, int rxPin = PIN_GPS_RX, + int resetPin = GPS_RESET, int enablePin = GPS_EN, + RefCountedDigitalPin* peripheralPower = nullptr, + int enableActive = GPS_EN_ACTIVE, int resetActive = GPS_RESET_ACTIVE, + uint32_t baudRate = GPS_BAUD_RATE, + int hardwareEnablePin = PIN_GPS_SWITCH, + int hardwareEnableActive = GPS_SWITCH_ACTIVE) + : _stream(&stream), _peripheralPower(peripheralPower), _txPin(txPin), _rxPin(rxPin), + _resetPin(resetPin), _enablePin(enablePin), _enableActive(enableActive), + _resetActive(resetActive), _baudRate(baudRate), + _hardwareEnablePin(hardwareEnablePin), _hardwareEnableActive(hardwareEnableActive) { + if (_resetPin != -1) { + pinMode(_resetPin, OUTPUT); + digitalWrite(_resetPin, _resetActive); + } + if (_enablePin != -1) { + pinMode(_enablePin, OUTPUT); + digitalWrite(_enablePin, !_enableActive); + } + if (_hardwareEnablePin != -1) { + pinMode(_hardwareEnablePin, INPUT); + } + } + + NmeaGpsDriver(HardwareSerial& serial, int txPin = PIN_GPS_TX, int rxPin = PIN_GPS_RX, + int resetPin = GPS_RESET, int enablePin = GPS_EN, + RefCountedDigitalPin* peripheralPower = nullptr, + int enableActive = GPS_EN_ACTIVE, int resetActive = GPS_RESET_ACTIVE, + uint32_t baudRate = GPS_BAUD_RATE, + int hardwareEnablePin = PIN_GPS_SWITCH, + int hardwareEnableActive = GPS_SWITCH_ACTIVE) + : NmeaGpsDriver(static_cast<Stream&>(serial), txPin, rxPin, resetPin, enablePin, + peripheralPower, enableActive, resetActive, baudRate, + hardwareEnablePin, hardwareEnableActive) { + _hardwareSerial = &serial; + } + + void begin() override { +#if !GPS_SWITCH_IS_HARDWARE + _requestedOn = true; + if (!isHardwareEnabled()) return; +#endif + startHardware(); + } + + void reset() override { + if (!_started) return; + if (_resetPin != -1) { + digitalWrite(_resetPin, _resetActive); + delay(10); + digitalWrite(_resetPin, !_resetActive); + } + +#ifdef GPS_L76K + delay(250); + sendNmeaSentence("$PCAS04,7"); + delay(250); +#endif + } + + void stop() override { +#if !GPS_SWITCH_IS_HARDWARE + _requestedOn = false; +#endif + stopHardware(); + } + + bool isEnabled() const override { + return _started && isHardwareEnabled(); + } + + bool hasHardwareEnableState() const override { + return _hardwareEnablePin != -1; + } + + bool isHardwareEnabled() const override { + return _hardwareEnablePin == -1 || + digitalRead(_hardwareEnablePin) == _hardwareEnableActive; + } + + bool pollGpsSwitch() override { +#if !GPS_SWITCH_IS_HARDWARE + if (_hardwareEnablePin == -1 || + (long)(millis() - _nextSwitchPoll) < 0) return false; + + _nextSwitchPoll = millis() + 1000; + const bool switchEnabled = isHardwareEnabled(); + const bool enablesGps = GPS_SWITCH_TURNS_GPS_ON && _switchStateKnown && + !_lastSwitchEnabled && switchEnabled; + _switchStateKnown = true; + _lastSwitchEnabled = switchEnabled; + + if (enablesGps) _requestedOn = true; + if (_requestedOn && switchEnabled) { + startHardware(); + } else { + stopHardware(); + } + return enablesGps; +#else + return false; +#endif + } + + bool detect(uint32_t timeout_ms) override { + if (available() > 0) return true; + + const uint32_t deadline = millis() + timeout_ms; + while ((int32_t)(millis() - deadline) < 0) { + if (available() > 0) return true; + delay(10); + } + return false; + } + + int available() { + return _stream == nullptr ? 0 : _stream->available(); + } + + int read() { + return _stream == nullptr ? -1 : _stream->read(); + } + + void drain() { + while (available() > 0) read(); + } + + void sendNmeaSentence(const char* sentence) { + if (_stream == nullptr || sentence == nullptr || sentence[0] != '$') return; + + uint8_t checksum = 0; + const char* p = sentence + 1; + while (*p != '\0' && *p != '*') checksum ^= (uint8_t)*p++; + + _stream->print(sentence); + if (*p == '\0') { + char checksumSuffix[6]; + snprintf(checksumSuffix, sizeof(checksumSuffix), "*%02X\r\n", checksum); + _stream->print(checksumSuffix); + } else { + _stream->print("\r\n"); + } + } +}; diff --git a/src/helpers/sensors/RakGpsDriver.h b/src/helpers/sensors/RakGpsDriver.h new file mode 100644 index 00000000..fb4b772b --- /dev/null +++ b/src/helpers/sensors/RakGpsDriver.h @@ -0,0 +1,112 @@ +#pragma once + +#include "NmeaGpsDriver.h" + +#include <SparkFun_u-blox_GNSS_Arduino_Library.h> + +class RakGpsDriver : public GpsDriver { + NmeaGpsDriver _serialDriver; + TwoWire& _wire; + SFE_UBLOX_GNSS _gnss; + uint8_t _powerPin = 0; + bool _usingRak12500 = false; + bool _detected = false; + + bool probeRak12500(uint8_t powerPin) { +#if defined(ETHERNET_ENABLED) && defined(RAK_BOARD) + if (powerPin == WB_IO2) return false; +#endif + +#ifndef RAK_3401 + pinMode(powerPin, OUTPUT); + digitalWrite(powerPin, LOW); + delay(500); + digitalWrite(powerPin, HIGH); +#endif + delay(500); + + if (_gnss.begin(_wire)) { + _gnss.setI2COutput(COM_TYPE_UBX); + _gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_GPS); + _gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_GALILEO); + _gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_GLONASS); + _gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_SBAS); + _gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_BEIDOU); + _gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_IMES); + _gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_QZSS); + _gnss.setMeasurementRate(1000); + _gnss.saveConfigSelective(VAL_CFG_SUBSEC_IOPORT); + _powerPin = powerPin; + _usingRak12500 = true; + return true; + } + +#ifndef RAK_3401 + pinMode(powerPin, INPUT); +#endif + return false; + } + +public: + RakGpsDriver(HardwareSerial& serial = Serial1, TwoWire& wire = Wire) + : _serialDriver(serial), _wire(wire) {} + + void begin() override { + if (_usingRak12500) { +#ifndef RAK_3401 + pinMode(_powerPin, OUTPUT); + digitalWrite(_powerPin, HIGH); +#endif + return; + } + _serialDriver.begin(); + } + + void reset() override { + if (!_usingRak12500) _serialDriver.reset(); + } + + void stop() override { + if (_usingRak12500) { +#ifndef RAK_3401 + pinMode(_powerPin, OUTPUT); + digitalWrite(_powerPin, LOW); +#endif + return; + } + _serialDriver.stop(); + } + + bool isEnabled() const override { + return _usingRak12500 ? true : _serialDriver.isEnabled(); + } + + bool detect(uint32_t) override { + if (_detected) return true; + + _serialDriver.begin(); + if (probeRak12500(WB_IO2) || probeRak12500(WB_IO4) || probeRak12500(WB_IO5)) { + _detected = true; + return true; + } + + if (_serialDriver.detect(0)) { + _detected = true; + return true; + } + + _serialDriver.stop(); + return false; + } + + bool usesRak12500() const { return _usingRak12500; } + bool isDetected() const { return _detected; } + NmeaGpsDriver& nmeaDriver() { return _serialDriver; } + + bool hasFix() { return _usingRak12500 && _gnss.getGnssFixOk(8); } + long getLatitude() { return _gnss.getLatitude(2) / 10; } + long getLongitude() { return _gnss.getLongitude(2) / 10; } + long getAltitude() { return _gnss.getAltitude(2); } + long getSatellites() { return _gnss.getSIV(2); } + long getTimestamp() { return _gnss.getUnixEpoch(2); } +}; diff --git a/src/helpers/sensors/RakLocationProvider.h b/src/helpers/sensors/RakLocationProvider.h new file mode 100644 index 00000000..c909b7c4 --- /dev/null +++ b/src/helpers/sensors/RakLocationProvider.h @@ -0,0 +1,144 @@ +#pragma once + +#include "MicroNMEALocationProvider.h" +#include "RakGpsDriver.h" + +class RakLocationProvider : public LocationProvider { + RakGpsDriver& _driver; + MicroNMEALocationProvider _nmea; + uint32_t _gpsPeriodSeconds = 0; + unsigned long _nextAcquisition = 0; + unsigned long _acquisitionStarted = 0; + bool _acquiringPeriodically = false; + +public: + RakLocationProvider(RakGpsDriver& driver, mesh::RTCClock* clock = nullptr) + : _driver(driver), _nmea(driver.nmeaDriver(), clock) {} + + void syncTime() override { + LocationProvider::syncTime(); + if (!_driver.usesRak12500()) _nmea.syncTime(); + } + + long getLatitude() override { + return _driver.usesRak12500() ? _driver.getLatitude() : _nmea.getLatitude(); + } + + long getLongitude() override { + return _driver.usesRak12500() ? _driver.getLongitude() : _nmea.getLongitude(); + } + + long getAltitude() override { + return _driver.usesRak12500() ? _driver.getAltitude() : _nmea.getAltitude(); + } + + long satellitesCount() override { + return _driver.usesRak12500() ? _driver.getSatellites() : _nmea.satellitesCount(); + } + + bool isValid() override { + return _driver.usesRak12500() ? _driver.hasFix() : _nmea.isValid(); + } + + long getTimestamp() override { + return _driver.usesRak12500() ? _driver.getTimestamp() : _nmea.getTimestamp(); + } + + void sendSentence(const char* sentence) override { + if (!_driver.usesRak12500()) _nmea.sendSentence(sentence); + } + + bool waitFor(const char* prefix, uint32_t timeout_ms) override { + return _driver.usesRak12500() ? false : _nmea.waitFor(prefix, timeout_ms); + } + + void drain() override { + if (!_driver.usesRak12500()) _nmea.drain(); + } + + void reset() override { + _driver.reset(); + } + + void begin() override { + if (_driver.isDetected() && _driver.usesRak12500()) { + _driver.begin(); + _acquiringPeriodically = _gpsPeriodSeconds > 0; + _acquisitionStarted = millis(); + } else if (_driver.isDetected()) { + _nmea.begin(); + } else { + _driver.begin(); + } + } + + void stop() override { + _acquiringPeriodically = false; + if (_driver.usesRak12500()) { + _driver.stop(); + } else { + _nmea.stop(); + } + } + + bool detect(uint32_t timeout_ms) override { + if (!_driver.detect(timeout_ms)) return false; + + if (_driver.usesRak12500()) { + _acquiringPeriodically = _gpsPeriodSeconds > 0; + _acquisitionStarted = millis(); + } else { + _nmea.setGpsPeriod(_gpsPeriodSeconds); + _nmea.begin(); + } + return true; + } + + bool keepEnabledAfterDetection() const override { +#ifdef FORCE_GPS_ALIVE + return true; +#else + return false; +#endif + } + + void loop() override { + if (_driver.usesRak12500()) { + if (_gpsOn && _gpsPeriodSeconds > 0) { + if (!_acquiringPeriodically && + (long)(millis() - _nextAcquisition) >= 0) { + _driver.begin(); + _acquiringPeriodically = true; + _acquisitionStarted = millis(); + } + if (_acquiringPeriodically && isValid()) { + _driver.stop(); + _acquiringPeriodically = false; + _nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL; + } else if (_acquiringPeriodically && + (uint32_t)(millis() - _acquisitionStarted) >= + GPS_PERIODIC_ACQUISITION_TIMEOUT_MS) { + _driver.stop(); + _acquiringPeriodically = false; + _nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL; + } + } + } else { + _nmea.loop(); + } + } + + bool isEnabled() override { + return _driver.isEnabled(); + } + + void setGpsPeriod(uint32_t seconds) override { + _gpsPeriodSeconds = seconds; + _nextAcquisition = millis(); + if (!_driver.usesRak12500()) _nmea.setGpsPeriod(seconds); + } + + uint32_t getGpsPeriod() const override { + return _gpsPeriodSeconds; + } +}; diff --git a/variants/gat562_30s_mesh_kit/target.cpp b/variants/gat562_30s_mesh_kit/target.cpp index 8f84a7a1..ba81a690 100644 --- a/variants/gat562_30s_mesh_kit/target.cpp +++ b/variants/gat562_30s_mesh_kit/target.cpp @@ -26,9 +26,10 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS - #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); - EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); + #include <helpers/sensors/RakLocationProvider.h> + RakGpsDriver gps_driver; + RakLocationProvider location(gps_driver, &rtc_clock); + EnvironmentSensorManager sensors(location); #else EnvironmentSensorManager sensors; #endif diff --git a/variants/lilygo_techo/target.cpp b/variants/lilygo_techo/target.cpp index 12b40d7e..394d79c5 100644 --- a/variants/lilygo_techo/target.cpp +++ b/variants/lilygo_techo/target.cpp @@ -13,7 +13,8 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea = MicroNMEALocationProvider(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); @@ -36,5 +37,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - - diff --git a/variants/rak3401/target.cpp b/variants/rak3401/target.cpp index 5309e6b2..26501977 100644 --- a/variants/rak3401/target.cpp +++ b/variants/rak3401/target.cpp @@ -25,9 +25,10 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS - #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); - EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); + #include <helpers/sensors/RakLocationProvider.h> + RakGpsDriver gps_driver; + RakLocationProvider location(gps_driver, &rtc_clock); + EnvironmentSensorManager sensors(location); #else EnvironmentSensorManager sensors; #endif @@ -41,4 +42,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/rak4631/target.cpp b/variants/rak4631/target.cpp index a41ba720..06ccd23d 100644 --- a/variants/rak4631/target.cpp +++ b/variants/rak4631/target.cpp @@ -25,9 +25,10 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS - #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); - EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); + #include <helpers/sensors/RakLocationProvider.h> + RakGpsDriver gps_driver; + RakLocationProvider location(gps_driver, &rtc_clock); + EnvironmentSensorManager sensors(location); #else EnvironmentSensorManager sensors; #endif diff --git a/variants/t1000-e/platformio.ini b/variants/t1000-e/platformio.ini index 8456dc91..ab8b0de0 100644 --- a/variants/t1000-e/platformio.ini +++ b/variants/t1000-e/platformio.ini @@ -106,6 +106,7 @@ build_flags = ${t1000-e.build_flags} ; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 +; -D GPS_NMEA_DEBUG -D OFFLINE_QUEUE_SIZE=256 -D DISPLAY_CLASS=NullDisplayDriver -D PIN_BUZZER=25 diff --git a/variants/t1000-e/target.cpp b/variants/t1000-e/target.cpp index 70a64359..0d7710b3 100644 --- a/variants/t1000-e/target.cpp +++ b/variants/t1000-e/target.cpp @@ -1,8 +1,8 @@ #include <Arduino.h> #include "t1000e_sensors.h" #include "target.h" +#include <helpers/sensors/AirohaGpsDriver.h> #include <helpers/sensors/MicroNMEALocationProvider.h> -#include <helpers/sensors/AirohaSleep.h> T1000eBoard board; @@ -11,8 +11,9 @@ RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BU WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock rtc_clock; -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); -T1000SensorManager sensors = T1000SensorManager(nmea); +AirohaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); +T1000SensorManager sensors(nmea, gps_driver); #ifdef DISPLAY_CLASS NullDisplayDriver display; @@ -82,28 +83,17 @@ mesh::LocalIdentity radio_new_identity() { void T1000SensorManager::start_gps() { gps_active = true; - digitalWrite(GPS_EN, HIGH); - delay(10); - digitalWrite(GPS_RTC_INT, HIGH); - delay(5); - digitalWrite(GPS_RTC_INT, LOW); + _nmea->begin(); } void T1000SensorManager::stop_gps() { gps_active = false; - digitalWrite(GPS_VRTC_EN, HIGH); // keep GPS RTC alive for faster fix on wake - digitalWrite(GPS_RTC_INT, LOW); // make sure this is LOW so we can pulse it to wake - airohaEnterSleep(_nmea); // send command to put the GPS into RTC backup sleep - digitalWrite(GPS_EN, LOW); + _nmea->stop(); } bool T1000SensorManager::begin() { - // init GPS - Serial1.begin(115200); - digitalWrite(GPS_RESET, HIGH); - delay(10); - digitalWrite(GPS_RESET, LOW); + _gps_driver->initialize(); return true; } diff --git a/variants/t1000-e/target.h b/variants/t1000-e/target.h index db003cc5..4a1a2bb7 100644 --- a/variants/t1000-e/target.h +++ b/variants/t1000-e/target.h @@ -12,15 +12,19 @@ #include "NullDisplayDriver.h" #endif +class AirohaGpsDriver; + class T1000SensorManager: public SensorManager { bool gps_active = false; LocationProvider * _nmea; + AirohaGpsDriver* _gps_driver; void start_gps(); void sleep_gps(); void stop_gps(); public: - T1000SensorManager(LocationProvider &nmea): _nmea(&nmea) { } + T1000SensorManager(LocationProvider &nmea, AirohaGpsDriver& gps_driver) + : _nmea(&nmea), _gps_driver(&gps_driver) { } bool begin() override; bool querySensors(uint8_t requester_permissions, CayenneLPP& telemetry) override; void loop() override; diff --git a/variants/thinknode_m1/target.cpp b/variants/thinknode_m1/target.cpp index c430cee0..78f5a88e 100644 --- a/variants/thinknode_m1/target.cpp +++ b/variants/thinknode_m1/target.cpp @@ -2,6 +2,7 @@ #include "target.h" #include <helpers/ArduinoHelpers.h> #include <helpers/sensors/MicroNMEALocationProvider.h> +#include <helpers/sensors/NmeaGpsDriver.h> ThinkNodeM1Board board; @@ -11,7 +12,8 @@ WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea = MicroNMEALocationProvider(gps_driver, &rtc_clock); ThinkNodeM1SensorManager sensors = ThinkNodeM1SensorManager(nmea); #ifdef DISPLAY_CLASS @@ -31,34 +33,15 @@ mesh::LocalIdentity radio_new_identity() { } void ThinkNodeM1SensorManager::start_gps() { - if (!gps_active) { - gps_active = true; - _location->begin(); - } + _location->setGpsOn(true); } void ThinkNodeM1SensorManager::stop_gps() { - if (gps_active) { - gps_active = false; - _location->stop(); - } + _location->setGpsOn(false); } bool ThinkNodeM1SensorManager::begin() { - Serial1.begin(9600); - - // Initialize GPS switch pin - pinMode(PIN_GPS_SWITCH, INPUT); - last_gps_switch_state = digitalRead(PIN_GPS_SWITCH); - - // Initialize GPS power pin - pinMode(GPS_EN, OUTPUT); - - // Check initial switch state to determine if GPS should be active - if (last_gps_switch_state == HIGH) { // Switch is HIGH when ON - start_gps(); - } - + start_gps(); return true; } @@ -71,36 +54,11 @@ bool ThinkNodeM1SensorManager::querySensors(uint8_t requester_permissions, Cayen void ThinkNodeM1SensorManager::loop() { static long next_gps_update = 0; - static long last_switch_check = 0; - - // Check GPS switch state every second - if (millis() - last_switch_check > 1000) { - bool current_switch_state = digitalRead(PIN_GPS_SWITCH); - - // Detect switch state change - if (current_switch_state != last_gps_switch_state) { - last_gps_switch_state = current_switch_state; - - if (current_switch_state == HIGH) { // Switch is ON - MESH_DEBUG_PRINTLN("GPS switch ON"); - start_gps(); - } else { // Switch is OFF - MESH_DEBUG_PRINTLN("GPS switch OFF"); - stop_gps(); - } - } - - last_switch_check = millis(); - } - - if (!gps_active) { - return; // GPS is not active, skip further processing - } _location->loop(); if (millis() > next_gps_update) { - if (_location->isValid()) { + if (_location->isEnabled() && _location->isValid()) { node_lat = ((double)_location->getLatitude())/1000000.; node_lon = ((double)_location->getLongitude())/1000000.; node_altitude = ((double)_location->getAltitude()) / 1000.0; @@ -120,7 +78,7 @@ const char* ThinkNodeM1SensorManager::getSettingName(int i) const { const char* ThinkNodeM1SensorManager::getSettingValue(int i) const { if (i == 0) { - return gps_active ? "1" : "0"; + return _location->isGpsOn() ? "1" : "0"; } return NULL; } @@ -136,4 +94,3 @@ bool ThinkNodeM1SensorManager::setSettingValue(const char* name, const char* val } return false; // not supported } - diff --git a/variants/thinknode_m1/target.h b/variants/thinknode_m1/target.h index d2d6aed1..9c8a6e80 100644 --- a/variants/thinknode_m1/target.h +++ b/variants/thinknode_m1/target.h @@ -14,8 +14,6 @@ #endif class ThinkNodeM1SensorManager : public SensorManager { - bool gps_active = false; - bool last_gps_switch_state = false; LocationProvider* _location; void start_gps(); @@ -45,4 +43,3 @@ extern ThinkNodeM1SensorManager sensors; bool radio_init(); mesh::LocalIdentity radio_new_identity(); - diff --git a/variants/thinknode_m1/variant.h b/variants/thinknode_m1/variant.h index aecf197e..3e3f03a7 100644 --- a/variants/thinknode_m1/variant.h +++ b/variants/thinknode_m1/variant.h @@ -146,3 +146,5 @@ extern const int SCK; #define PIN_GPS_PPS (36) #define PIN_GPS_STANDBY (34) #define PIN_GPS_SWITCH (33) +#define GPS_SWITCH_IS_HARDWARE (0) +#define GPS_SWITCH_TURNS_GPS_ON (1) diff --git a/variants/thinknode_m5/target.cpp b/variants/thinknode_m5/target.cpp index ec524df7..0ed9a0d0 100644 --- a/variants/thinknode_m5/target.cpp +++ b/variants/thinknode_m5/target.cpp @@ -17,7 +17,8 @@ ESP32RTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea = MicroNMEALocationProvider(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); @@ -46,5 +47,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - - diff --git a/variants/thinknode_m5/variant.h b/variants/thinknode_m5/variant.h index 9b82416b..fefb45d1 100644 --- a/variants/thinknode_m5/variant.h +++ b/variants/thinknode_m5/variant.h @@ -25,4 +25,5 @@ #define PIN_GPS_RESET (13) #define PIN_GPS_RX (20) #define PIN_GPS_TX (19) -#define PIN_GPS_SWITCH (10) \ No newline at end of file +#define PIN_GPS_SWITCH (10) +#define GPS_SWITCH_IS_HARDWARE (1) \ No newline at end of file From dea38936d7c24a3680044ca9871bf6bcf775cd29 Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Mon, 2 Nov 2026 11:09:16 -0400 Subject: [PATCH 345/381] gps: move the gps CLI to GpsPrefs and convert all targets --- examples/companion_radio/MyMesh.cpp | 5 + examples/companion_radio/MyMesh.h | 11 +- examples/companion_radio/NodePrefs.h | 14 ++- examples/companion_radio/ui-new/UITask.cpp | 8 +- examples/companion_radio/ui-orig/UITask.cpp | 5 +- examples/companion_radio/ui-tiny/UITask.cpp | 8 +- examples/simple_repeater/MyMesh.h | 12 +- examples/simple_room_server/MyMesh.h | 12 +- examples/simple_sensor/SensorMesh.h | 10 +- src/helpers/CommonCLI.cpp | 76 +----------- src/helpers/CommonCLI.h | 12 +- src/helpers/CommonGpsPrefs.cpp | 110 ++++++++++++++++++ src/helpers/CommonGpsPrefs.h | 26 +++++ .../sensors/EnvironmentSensorManager.cpp | 18 +-- variants/gat562_mesh_evb_pro/target.cpp | 3 +- variants/gat562_mesh_tracker_pro/target.cpp | 3 +- variants/heltec_mesh_solar/target.cpp | 15 +-- variants/heltec_mesh_solar/target.h | 1 - variants/heltec_rc32/target.cpp | 4 +- variants/heltec_t096/target.cpp | 4 +- variants/heltec_t1/target.cpp | 4 +- variants/heltec_t114/target.cpp | 3 +- variants/heltec_tower_v2/target.cpp | 3 +- variants/heltec_tracker/target.cpp | 30 +++-- variants/heltec_tracker/target.h | 1 - variants/heltec_tracker_v2/target.cpp | 5 +- variants/heltec_v3/target.cpp | 4 +- variants/heltec_v4/target.cpp | 4 +- variants/heltec_v4_r8/target.cpp | 4 +- variants/keepteen_lt1/target.cpp | 4 +- variants/lilygo_t_impulse_plus/target.cpp | 4 +- variants/lilygo_tbeam_1w/target.cpp | 4 +- variants/lilygo_tbeam_SX1262/target.cpp | 4 +- variants/lilygo_tbeam_SX1276/target.cpp | 3 +- .../lilygo_tbeam_supreme_SX1262/target.cpp | 4 +- variants/lilygo_tdeck/target.cpp | 3 +- variants/lilygo_techo_card/target.cpp | 3 +- variants/lilygo_techo_lite/target.cpp | 4 +- variants/meshadventurer/target.cpp | 19 ++- variants/meshadventurer/target.h | 3 +- variants/meshnology_w12/target.cpp | 4 +- variants/meshtracker_x1/target.cpp | 27 ++--- variants/meshtracker_x1/target.h | 2 - variants/minewsemi_me25ls01/target.cpp | 3 +- variants/muzi_base/target.cpp | 22 +--- variants/muzi_base/target.h | 6 +- variants/muzi_base/variant.h | 2 + variants/muziworks_r1_neo/target.cpp | 3 +- variants/nano_g2_ultra/NanoG2UltraGpsDriver.h | 31 +++++ variants/nano_g2_ultra/target.cpp | 35 ++---- variants/nano_g2_ultra/target.h | 8 +- variants/promicro/target.cpp | 4 +- variants/rak3112/target.cpp | 4 +- variants/rak_wismesh_tag/target.cpp | 4 +- variants/sensecap_indicator-espnow/target.cpp | 3 +- variants/sensecap_solar/target.cpp | 4 +- variants/station_g2/target.cpp | 4 +- variants/station_g3_esp32/target.cpp | 3 +- variants/t1000-e/target.cpp | 10 +- variants/t1000-e/target.h | 1 - variants/thinknode_m3/target.cpp | 3 +- variants/thinknode_m4/target.cpp | 3 +- variants/thinknode_m6/target.cpp | 4 +- variants/thinknode_m7/target.cpp | 4 +- variants/thinknode_m8/target.cpp | 3 +- variants/thinknode_m9/target.cpp | 3 +- variants/wio-tracker-l1-1w/target.cpp | 4 +- variants/wio-tracker-l1/target.cpp | 4 +- variants/xiao_c3/target.cpp | 4 +- 69 files changed, 381 insertions(+), 301 deletions(-) create mode 100644 src/helpers/CommonGpsPrefs.cpp create mode 100644 src/helpers/CommonGpsPrefs.h create mode 100644 variants/nano_g2_ultra/NanoG2UltraGpsDriver.h diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 755c56d1..d12c7b8a 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2093,6 +2093,11 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* return true; } + if (_prefs.getGpsPrefs()->handleCommand(command, sensors, reply)) { + if (_prefs.getGpsPrefs()->isDirty()) { savePrefs(); } + return true; + } + // hook for variant-specific CLI processing if (board.handleCommand(command, sender_timestamp, reply)) { if (_prefs.isDirty()) { savePrefs(); } diff --git a/examples/companion_radio/MyMesh.h b/examples/companion_radio/MyMesh.h index 944790df..846708b5 100644 --- a/examples/companion_radio/MyMesh.h +++ b/examples/companion_radio/MyMesh.h @@ -203,12 +203,13 @@ public: #if ENV_INCLUDE_GPS == 1 void applyGpsPrefs() { - sensors.setSettingValue("gps", _prefs.gps_enabled ? "1" : "0"); - if (_prefs.gps_interval > 0) { - char interval_str[12]; // Max: 24 hours = 86400 seconds (5 digits + null) - sprintf(interval_str, "%u", _prefs.gps_interval); - sensors.setSettingValue("gps_interval", interval_str); + if (_prefs.gps_interval > 0 && + sensors.getSettingByKey("gps_interval") != nullptr) { + char interval[11]; + snprintf(interval, sizeof(interval), "%lu", (unsigned long)_prefs.gps_interval); + sensors.setSettingValue("gps_interval", interval); } + _prefs.getGpsPrefs()->apply(sensors); } #endif diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index c5d1df04..a54eca75 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -2,6 +2,7 @@ #include <cstdint> // For uint8_t, uint32_t #include <helpers/ConfigSerializer.h> #include <helpers/CommonRadioPrefs.h> +#include <helpers/CommonGpsPrefs.h> #include <helpers/DynamicConfigSerializer.h> #define TELEM_MODE_DENY 0 @@ -35,6 +36,7 @@ public: uint8_t vibe_quiet = 0; uint8_t gps_enabled = 0; // GPS enabled flag (0=disabled, 1=enabled) uint32_t gps_interval = 0; // GPS read interval in seconds + uint32_t gps_period = 0; // periodic acquisition interval in seconds uint8_t autoadd_config = 0; // bitmask for auto-add contacts config uint8_t rx_boosted_gain = 0; // SX126x RX boosted gain mode (0=power saving, 1=boosted) uint8_t radio_fem_rxgain = 0; // external LoRa FEM RX gain (LNA) @@ -151,16 +153,21 @@ private: }; RadioPrefs radio; - class GPSPrefs : public ConfigSerializer { // COPIED from CommonCLI (for now) + class GPSPrefs : public CommonGpsPrefs { NodePrefs* _parent; protected: void structure() override { def("en", _parent->gps_enabled); // boolean def("int", _parent->gps_interval); // interval in seconds + def("period", _parent->gps_period); // periodic acquisition interval in seconds def("adv_loc", _parent->advert_loc_policy); } public: GPSPrefs(NodePrefs* parent) : _parent(parent) { } + bool isGpsEnabled() const override { return _parent->gps_enabled; } + void setGpsEnabled(bool enabled) override { _parent->gps_enabled = enabled; markDirty(); } + uint32_t getGpsPeriod() const override { return _parent->gps_period; } + void setGpsPeriod(uint32_t seconds) override { _parent->gps_period = seconds; markDirty(); } }; GPSPrefs gps; @@ -275,8 +282,9 @@ public: void setRepeatEn(bool en) { repeat.disable_fwd = en ? 0 : 1; } CommonRadioPrefs* getRadioPrefs() { return &radio; } + CommonGpsPrefs* getGpsPrefs() { return &gps; } KeyValueStore* getCustom() { return &custom; } - bool isDirty() const override { return ConfigSerializer::isDirty() || radio.isDirty() || custom.isDirty(); } - void clearDirty() override { ConfigSerializer::clearDirty(); radio.clearDirty(); custom.clearDirty(); } + bool isDirty() const override { return ConfigSerializer::isDirty() || radio.isDirty() || gps.isDirty() || custom.isDirty(); } + void clearDirty() override { ConfigSerializer::clearDirty(); radio.clearDirty(); gps.clearDirty(); custom.clearDirty(); } }; diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index cfe34cf2..a1400669 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -1182,16 +1182,14 @@ void UITask::toggleGPS() { for (int i = 0; i < num; i++) { if (strcmp(_sensors->getSettingName(i), "gps") == 0) { if (strcmp(_sensors->getSettingValue(i), "1") == 0) { - _sensors->setSettingValue("gps", "0"); - _node_prefs->gps_enabled = 0; + _node_prefs->getGpsPrefs()->setGpsEnabled(*_sensors, false); notify(UIEventType::ack); } else { - _sensors->setSettingValue("gps", "1"); - _node_prefs->gps_enabled = 1; + _node_prefs->getGpsPrefs()->setGpsEnabled(*_sensors, true); notify(UIEventType::ack); } the_mesh.savePrefs(); - showAlert(_node_prefs->gps_enabled ? "GPS: Enabled" : "GPS: Disabled", 800); + showAlert(_node_prefs->getGpsPrefs()->isGpsEnabled() ? "GPS: Enabled" : "GPS: Disabled", 800); _next_refresh = 0; break; } diff --git a/examples/companion_radio/ui-orig/UITask.cpp b/examples/companion_radio/ui-orig/UITask.cpp index 8ae57c7a..c2fd80fb 100644 --- a/examples/companion_radio/ui-orig/UITask.cpp +++ b/examples/companion_radio/ui-orig/UITask.cpp @@ -609,14 +609,15 @@ void UITask::handleButtonQuadruplePress() { for (int i = 0; i < num; i++) { if (strcmp(_sensors->getSettingName(i), "gps") == 0) { if (strcmp(_sensors->getSettingValue(i), "1") == 0) { - _sensors->setSettingValue("gps", "0"); + _node_prefs->getGpsPrefs()->setGpsEnabled(*_sensors, false); notify(UIEventType::ack); sprintf(_alert, "GPS: Disabled"); } else { - _sensors->setSettingValue("gps", "1"); + _node_prefs->getGpsPrefs()->setGpsEnabled(*_sensors, true); notify(UIEventType::ack); sprintf(_alert, "GPS: Enabled"); } + the_mesh.savePrefs(); break; } } diff --git a/examples/companion_radio/ui-tiny/UITask.cpp b/examples/companion_radio/ui-tiny/UITask.cpp index 035340a8..1b48cca8 100644 --- a/examples/companion_radio/ui-tiny/UITask.cpp +++ b/examples/companion_radio/ui-tiny/UITask.cpp @@ -833,16 +833,14 @@ void UITask::toggleGPS() { for (int i = 0; i < num; i++) { if (strcmp(_sensors->getSettingName(i), "gps") == 0) { if (strcmp(_sensors->getSettingValue(i), "1") == 0) { - _sensors->setSettingValue("gps", "0"); - _node_prefs->gps_enabled = 0; + _node_prefs->getGpsPrefs()->setGpsEnabled(*_sensors, false); notify(UIEventType::ack); } else { - _sensors->setSettingValue("gps", "1"); - _node_prefs->gps_enabled = 1; + _node_prefs->getGpsPrefs()->setGpsEnabled(*_sensors, true); notify(UIEventType::ack); } the_mesh.savePrefs(); - showAlert(_node_prefs->gps_enabled ? "GPS: Enabled" : "GPS: Disabled", 800); + showAlert(_node_prefs->getGpsPrefs()->isGpsEnabled() ? "GPS: Enabled" : "GPS: Disabled", 800); _next_refresh = 0; break; } diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index 1d975a94..7e4cfd4f 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -159,10 +159,14 @@ protected: #if ENV_INCLUDE_GPS == 1 void applyGpsPrefs() { - char period[11]; - snprintf(period, sizeof(period), "%lu", (unsigned long)_prefs.gps_period); - sensors.setSettingValue("gps_period", period); - sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0"); + if (sensors.getSettingByKey("gps_interval") != nullptr) { + // gps_interval was introduced only for EnvironmentSensorManager + // and has little interest ... kept only as a legacy + char interval[11]; + snprintf(interval, sizeof(interval), "%lu", (unsigned long)_prefs.gps_interval); + sensors.setSettingValue("gps_interval", interval); + } + _prefs.getGpsPrefs()->apply(sensors); } #endif diff --git a/examples/simple_room_server/MyMesh.h b/examples/simple_room_server/MyMesh.h index 5f8de73a..11367b12 100644 --- a/examples/simple_room_server/MyMesh.h +++ b/examples/simple_room_server/MyMesh.h @@ -168,10 +168,14 @@ protected: #if ENV_INCLUDE_GPS == 1 void applyGpsPrefs() { - char period[11]; - snprintf(period, sizeof(period), "%lu", (unsigned long)_prefs.gps_period); - sensors.setSettingValue("gps_period", period); - sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0"); + if (sensors.getSettingByKey("gps_interval") != nullptr) { + // gps_interval was introduced only for EnvironmentSensorManager + // and has little interest ... kept only as a legacy + char interval[11]; + snprintf(interval, sizeof(interval), "%lu", (unsigned long)_prefs.gps_interval); + sensors.setSettingValue("gps_interval", interval); + } + _prefs.getGpsPrefs()->apply(sensors); } #endif diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index b93939de..e6746d47 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -173,10 +173,12 @@ private: #if ENV_INCLUDE_GPS == 1 void applyGpsPrefs() { - char period[11]; - snprintf(period, sizeof(period), "%lu", (unsigned long)_prefs.gps_period); - sensors.setSettingValue("gps_period", period); - sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0"); + if (sensors.getSettingByKey("gps_interval") != nullptr) { + char interval[11]; + snprintf(interval, sizeof(interval), "%lu", (unsigned long)_prefs.gps_interval); + sensors.setSettingValue("gps_interval", interval); + } + _prefs.getGpsPrefs()->apply(sensors); } #endif }; diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index 613f2578..ed1b5199 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -349,65 +349,11 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re *(dp-1) = 0; // remove last CR } } + } else if (_prefs->getGpsPrefs()->handleCommand(command, *_sensors, reply)) { + if (_prefs->getGpsPrefs()->isDirty()) savePrefs(); } else if (memcmp(command, "region", 6) == 0) { handleRegionCmd(command, reply); #if ENV_INCLUDE_GPS == 1 - } else if (memcmp(command, "gps on", 6) == 0) { - if (_sensors->setSettingValue("gps", "1")) { - _prefs->gps_enabled = 1; - savePrefs(); - strcpy(reply, "ok"); - } else { - strcpy(reply, "gps toggle not found"); - } - } else if (memcmp(command, "gps off", 7) == 0) { - if (_sensors->setSettingValue("gps", "0")) { - _prefs->gps_enabled = 0; - savePrefs(); - strcpy(reply, "ok"); - } else { - strcpy(reply, "gps toggle not found"); - } - } else if (memcmp(command, "gps period ", 11) == 0) { - char* end = nullptr; - unsigned long period = strtoul(command + 11, &end, 10); - if (command[11] == '\0' || *end != '\0' || period > 86400) { - strcpy(reply, "gps period must be 0-86400 seconds"); - } else { - char period_value[11]; - snprintf(period_value, sizeof(period_value), "%lu", period); - if (_sensors->setSettingValue("gps_period", period_value) && - _sensors->setSettingValue("gps", "1")) { - _prefs->gps_period = (uint32_t)period; - _prefs->gps_enabled = 1; - savePrefs(); - strcpy(reply, "ok"); - } else { - strcpy(reply, "gps provider not found"); - } - } - } else if (memcmp(command, "gps sync", 8) == 0) { - LocationProvider * l = _sensors->getLocationProvider(); - if (l != NULL) { - l->syncTime(); - strcpy(reply, "ok"); - } else { - strcpy(reply, "gps provider not found"); - } - } else if (strcmp(command, "gps diag") == 0) { - LocationProvider * l = _sensors->getLocationProvider(); - if (l != NULL) { - const char* setting = _sensors->getSettingByKey("gps"); - bool requested = setting != NULL && strcmp(setting, "1") == 0; - int prefix_len = snprintf(reply, 160, "req:%u ", requested ? 1U : 0U); - if (prefix_len < 0 || prefix_len >= 160) { - reply[159] = 0; - } else { - l->formatDiagnostics(reply + prefix_len, 160 - prefix_len); - } - } else { - strcpy(reply, "gps provider not found"); - } } else if (memcmp(command, "gps setloc", 10) == 0) { _prefs->node_lat = _sensors->node_lat; _prefs->node_lon = _sensors->node_lon; @@ -443,24 +389,6 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re } else { strcpy(reply, "error"); } - } else if (memcmp(command, "gps", 3) == 0) { - LocationProvider * l = _sensors->getLocationProvider(); - if (l != NULL) { - bool enabled = l->isEnabled(); // is EN pin on ? - bool fix = l->isValid(); // has fix ? - int sats = l->satellitesCount(); - bool active = !strcmp(_sensors->getSettingByKey("gps"), "1"); - if (enabled) { - sprintf(reply, "on, %s, %s, %d sats", - active?"active":"deactivated", - fix?"fix":"no fix", - sats); - } else { - strcpy(reply, "off"); - } - } else { - strcpy(reply, "Can't find GPS"); - } #endif } else if (memcmp(command, "powersaving on", 14) == 0) { #if defined(NRF52_PLATFORM) diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 06778a60..33e27d2d 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -7,6 +7,7 @@ #include <helpers/RegionMap.h> #include <helpers/ConfigSerializer.h> #include <helpers/CommonRadioPrefs.h> +#include <helpers/CommonGpsPrefs.h> #include <helpers/DynamicConfigSerializer.h> #if defined(WITH_RS232_BRIDGE) || defined(WITH_ESPNOW_BRIDGE) @@ -153,7 +154,7 @@ private: }; BridgePrefs bridge; - class GPSPrefs : public ConfigSerializer { + class GPSPrefs : public CommonGpsPrefs { NodePrefs* _parent; protected: void structure() override { @@ -164,6 +165,10 @@ private: } public: GPSPrefs(NodePrefs* parent) : _parent(parent) { } + bool isGpsEnabled() const override { return _parent->gps_enabled; } + void setGpsEnabled(bool enabled) override { _parent->gps_enabled = enabled; markDirty(); } + uint32_t getGpsPeriod() const override { return _parent->gps_period; } + void setGpsPeriod(uint32_t seconds) override { _parent->gps_period = seconds; markDirty(); } }; GPSPrefs gps; @@ -236,10 +241,11 @@ public: } CommonRadioPrefs* getRadioPrefs() { return &radio; } + CommonGpsPrefs* getGpsPrefs() { return &gps; } KeyValueStore* getCustom() { return &custom; } - bool isDirty() const override { return ConfigSerializer::isDirty() || radio.isDirty() || custom.isDirty(); } - void clearDirty() override { ConfigSerializer::clearDirty(); radio.clearDirty(); custom.clearDirty(); } + bool isDirty() const override { return ConfigSerializer::isDirty() || radio.isDirty() || gps.isDirty() || custom.isDirty(); } + void clearDirty() override { ConfigSerializer::clearDirty(); radio.clearDirty(); gps.clearDirty(); custom.clearDirty(); } }; class CommonCLICallbacks { diff --git a/src/helpers/CommonGpsPrefs.cpp b/src/helpers/CommonGpsPrefs.cpp new file mode 100644 index 00000000..fe29c0c0 --- /dev/null +++ b/src/helpers/CommonGpsPrefs.cpp @@ -0,0 +1,110 @@ +#include "CommonGpsPrefs.h" +#include <helpers/sensors/LocationProvider.h> + +bool CommonGpsPrefs::setGpsEnabled(SensorManager& sensors, bool enabled) { + LocationProvider* location = sensors.getLocationProvider(); + if (location == nullptr) return false; + location->setGpsOn(enabled); + setGpsEnabled(enabled); + return true; +} + +bool CommonGpsPrefs::setGpsPeriod(SensorManager& sensors, uint32_t seconds) { + LocationProvider* location = sensors.getLocationProvider(); + if (location == nullptr) return false; + location->setGpsPeriod(seconds); + setGpsPeriod(seconds); + return true; +} + +bool CommonGpsPrefs::apply(SensorManager& sensors) const { + LocationProvider* location = sensors.getLocationProvider(); + if (location == nullptr) return false; + location->setGpsPeriod(getGpsPeriod()); + location->setGpsOn(isGpsEnabled()); + return true; +} + +bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, char* reply) { + if (strcmp(command, "gps") == 0) { + LocationProvider* location = sensors.getLocationProvider(); + char mode[32]; + if (getGpsPeriod() == 0) { + strcpy(mode, "tracking"); + } else { + snprintf(mode, sizeof(mode), "periodic (%lus)", + (unsigned long)getGpsPeriod()); + } + if (location == nullptr) { + strcpy(reply, "gps provider not found"); + } else if (location->isEnabled()) { + sprintf(reply, "on, %s, %s, %d sats, mode: %s", + isGpsEnabled() ? "active" : "deactivated", + location->isValid() ? "fix" : "no fix", + location->satellitesCount(), mode); + } else { + snprintf(reply, 160, "off, mode: %s", mode); + } + return true; + } + if (memcmp(command, "gps on", 6) == 0) { + if (!setGpsEnabled(sensors, true)) { + strcpy(reply, "gps toggle not found"); + } else { + strcpy(reply, "ok"); + } + return true; + } + if (memcmp(command, "gps off", 7) == 0) { + if (!setGpsEnabled(sensors, false)) { + strcpy(reply, "gps toggle not found"); + } else { + strcpy(reply, "ok"); + } + return true; + } + if (strcmp(command, "gps period") == 0) { + if (getGpsPeriod() == 0) { + strcpy(reply, "> 0 (continuous)"); + } else { + sprintf(reply, "> %lu", (unsigned long)getGpsPeriod()); + } + return true; + } + if (memcmp(command, "gps period ", 11) == 0) { + char* end = nullptr; + unsigned long period = strtoul(command + 11, &end, 10); + if (command[11] == '\0' || *end != '\0' || period > 86400) { + strcpy(reply, "gps period must be 0-86400 seconds"); + } else { + if (!setGpsPeriod(sensors, (uint32_t)period) || + !setGpsEnabled(sensors, true)) { + strcpy(reply, "gps provider not found"); + } else { + strcpy(reply, "ok"); + } + } + return true; + } + if (memcmp(command, "gps sync", 8) == 0) { + LocationProvider* location = sensors.getLocationProvider(); + if (location == nullptr) { + strcpy(reply, "gps provider not found"); + } else { + location->syncTime(); + strcpy(reply, "ok"); + } + return true; + } + if (strcmp(command, "gps diag") == 0) { + LocationProvider* location = sensors.getLocationProvider(); + if (location == nullptr) { + strcpy(reply, "gps provider not found"); + } else { + int prefix = snprintf(reply, 160, "req:%u ", isGpsEnabled() ? 1U : 0U); + if (prefix >= 0 && prefix < 160) location->formatDiagnostics(reply + prefix, 160 - prefix); + } + return true; + } + return false; +} diff --git a/src/helpers/CommonGpsPrefs.h b/src/helpers/CommonGpsPrefs.h new file mode 100644 index 00000000..25cce1b1 --- /dev/null +++ b/src/helpers/CommonGpsPrefs.h @@ -0,0 +1,26 @@ +#pragma once + +#include "ConfigSerializer.h" +#include "SensorManager.h" + +class CommonGpsPrefs : public ConfigSerializer { + bool _is_dirty = false; + +protected: + CommonGpsPrefs() = default; + +public: + void markDirty() { _is_dirty = true; } + void clearDirty() { _is_dirty = false; } + bool isDirty() const { return _is_dirty; } + + virtual bool isGpsEnabled() const = 0; + virtual void setGpsEnabled(bool enabled) = 0; + virtual uint32_t getGpsPeriod() const = 0; + virtual void setGpsPeriod(uint32_t seconds) = 0; + + bool setGpsEnabled(SensorManager& sensors, bool enabled); + bool setGpsPeriod(SensorManager& sensors, uint32_t seconds); + bool apply(SensorManager& sensors) const; + bool handleCommand(const char* command, SensorManager& sensors, char* reply); +}; diff --git a/src/helpers/sensors/EnvironmentSensorManager.cpp b/src/helpers/sensors/EnvironmentSensorManager.cpp index 2861fac2..2cf8b66b 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.cpp +++ b/src/helpers/sensors/EnvironmentSensorManager.cpp @@ -650,7 +650,7 @@ bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, Cayen int EnvironmentSensorManager::getNumSettings() const { int settings = 0; #if ENV_INCLUDE_GPS - if (gps_detected) settings += 2; // GPS enablement and periodic acquisition + if (gps_detected) settings += 1; // GPS enablement #endif return settings; } @@ -661,9 +661,6 @@ const char* EnvironmentSensorManager::getSettingName(int i) const { if (gps_detected && i == settings++) { return "gps"; } - if (gps_detected && i == settings++) { - return "gps_period"; - } #endif return NULL; } @@ -674,12 +671,6 @@ const char* EnvironmentSensorManager::getSettingValue(int i) const { if (gps_detected && i == settings++) { return _location->isGpsOn() ? "1" : "0"; } - if (gps_detected && i == settings++) { - static char period[11]; - snprintf(period, sizeof(period), "%lu", - (unsigned long)_location->getGpsPeriod()); - return period; - } #endif return NULL; } @@ -694,13 +685,6 @@ bool EnvironmentSensorManager::setSettingValue(const char* name, const char* val } return true; } - if (gps_detected && strcmp(name, "gps_period") == 0) { - char* end = nullptr; - unsigned long period = strtoul(value, &end, 10); - if (*value == '\0' || *end != '\0' || period > 86400) return false; - _location->setGpsPeriod((uint32_t)period); - return true; - } if (strcmp(name, "gps_interval") == 0) { uint32_t interval_seconds = atoi(value); gps_update_interval_sec = interval_seconds > 0 ? interval_seconds : 1; diff --git a/variants/gat562_mesh_evb_pro/target.cpp b/variants/gat562_mesh_evb_pro/target.cpp index 8dc203de..0aac297a 100644 --- a/variants/gat562_mesh_evb_pro/target.cpp +++ b/variants/gat562_mesh_evb_pro/target.cpp @@ -26,7 +26,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; diff --git a/variants/gat562_mesh_tracker_pro/target.cpp b/variants/gat562_mesh_tracker_pro/target.cpp index d16b4538..225aa161 100644 --- a/variants/gat562_mesh_tracker_pro/target.cpp +++ b/variants/gat562_mesh_tracker_pro/target.cpp @@ -27,7 +27,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; diff --git a/variants/heltec_mesh_solar/target.cpp b/variants/heltec_mesh_solar/target.cpp index 94e2684c..9468f8fc 100644 --- a/variants/heltec_mesh_solar/target.cpp +++ b/variants/heltec_mesh_solar/target.cpp @@ -11,7 +11,8 @@ WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); SolarSensorManager sensors = SolarSensorManager(nmea); SolarExternalWatchdog external_watchdog; @@ -30,17 +31,11 @@ mesh::LocalIdentity radio_new_identity() { } void SolarSensorManager::start_gps() { - if (!gps_active) { - gps_active = true; - _location->begin(); - } + _location->setGpsOn(true); } void SolarSensorManager::stop_gps() { - if (gps_active) { - gps_active = false; - _location->stop(); - } + _location->setGpsOn(false); } bool SolarSensorManager::begin() { @@ -91,7 +86,7 @@ const char* SolarSensorManager::getSettingName(int i) const { const char* SolarSensorManager::getSettingValue(int i) const { if (gps_detected && i == 0) { - return gps_active ? "1" : "0"; + return _location->isGpsOn() ? "1" : "0"; } return NULL; } diff --git a/variants/heltec_mesh_solar/target.h b/variants/heltec_mesh_solar/target.h index 8e13a960..97550a00 100644 --- a/variants/heltec_mesh_solar/target.h +++ b/variants/heltec_mesh_solar/target.h @@ -14,7 +14,6 @@ #endif class SolarSensorManager : public SensorManager { - bool gps_active = false; bool gps_detected = false; LocationProvider* _location; diff --git a/variants/heltec_rc32/target.cpp b/variants/heltec_rc32/target.cpp index cc7e4deb..e095baab 100644 --- a/variants/heltec_rc32/target.cpp +++ b/variants/heltec_rc32/target.cpp @@ -20,7 +20,9 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, PIN_GPS_RESET, PIN_GPS_EN); + NmeaGpsDriver gps_driver(Serial1, PIN_GPS_TX, PIN_GPS_RX, PIN_GPS_RESET, + PIN_GPS_EN); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; diff --git a/variants/heltec_t096/target.cpp b/variants/heltec_t096/target.cpp index 30509977..d0c2c07e 100644 --- a/variants/heltec_t096/target.cpp +++ b/variants/heltec_t096/target.cpp @@ -22,7 +22,9 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, GPS_RESET, GPS_EN, &board.periph_power); +NmeaGpsDriver gps_driver(Serial1, PIN_GPS_TX, PIN_GPS_RX, GPS_RESET, GPS_EN, + &board.periph_power); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; diff --git a/variants/heltec_t1/target.cpp b/variants/heltec_t1/target.cpp index af771582..1d9c8baa 100644 --- a/variants/heltec_t1/target.cpp +++ b/variants/heltec_t1/target.cpp @@ -21,7 +21,9 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, GPS_RESET, GPS_EN, &board.periph_power); +NmeaGpsDriver gps_driver(Serial1, PIN_GPS_TX, PIN_GPS_RX, GPS_RESET, GPS_EN, + &board.periph_power); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; diff --git a/variants/heltec_t114/target.cpp b/variants/heltec_t114/target.cpp index 90a902f8..dc62f83b 100644 --- a/variants/heltec_t114/target.cpp +++ b/variants/heltec_t114/target.cpp @@ -22,7 +22,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; diff --git a/variants/heltec_tower_v2/target.cpp b/variants/heltec_tower_v2/target.cpp index ec8e7a17..ae627a0b 100644 --- a/variants/heltec_tower_v2/target.cpp +++ b/variants/heltec_tower_v2/target.cpp @@ -12,7 +12,8 @@ WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); TowerV2ExternalWatchdog external_watchdog; diff --git a/variants/heltec_tracker/target.cpp b/variants/heltec_tracker/target.cpp index f32c41ff..5903f659 100644 --- a/variants/heltec_tracker/target.cpp +++ b/variants/heltec_tracker/target.cpp @@ -17,7 +17,20 @@ WRAPPER_CLASS radio_driver(radio, board); ESP32RTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); // GPS_EN (GPIO35) drives N-ch MOSFET → P-ch high-side switch; GPS_RESET (GPIO36) active LOW -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, GPS_RESET, GPS_EN, &board.periph_power); +class HeltecTrackerGpsDriver : public NmeaGpsDriver { +public: + HeltecTrackerGpsDriver() + : NmeaGpsDriver(Serial1, PIN_GPS_TX, PIN_GPS_RX, GPS_RESET, GPS_EN, + &board.periph_power) {} + + void begin() override { + NmeaGpsDriver::begin(); + sendNmeaSentence("$CFGSYS,h35155*68"); + } +}; + +HeltecTrackerGpsDriver gps_driver; +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); HWTSensorManager sensors = HWTSensorManager(nmea); #ifdef DISPLAY_CLASS @@ -43,18 +56,11 @@ mesh::LocalIdentity radio_new_identity() { } void HWTSensorManager::start_gps() { - if (!gps_active) { - _location->begin(); // Claims periph_power via RefCountedDigitalPin - gps_active = true; - Serial1.println("$CFGSYS,h35155*68"); // Configure GPS for all constellations - } + _location->setGpsOn(true); } void HWTSensorManager::stop_gps() { - if (gps_active) { - gps_active = false; - _location->stop(); // Releases periph_power via RefCountedDigitalPin - } + _location->setGpsOn(false); } bool HWTSensorManager::begin() { @@ -76,7 +82,7 @@ void HWTSensorManager::loop() { _location->loop(); if (millis() > next_gps_update) { - if (gps_active && _location->isValid()) { + if (_location->isEnabled() && _location->isValid()) { node_lat = ((double)_location->getLatitude())/1000000.; node_lon = ((double)_location->getLongitude())/1000000.; node_altitude = ((double)_location->getAltitude()) / 1000.0; @@ -93,7 +99,7 @@ const char* HWTSensorManager::getSettingName(int i) const { } const char* HWTSensorManager::getSettingValue(int i) const { if (i == 0) { - return gps_active ? "1" : "0"; + return _location->isGpsOn() ? "1" : "0"; } return NULL; } diff --git a/variants/heltec_tracker/target.h b/variants/heltec_tracker/target.h index 2931eda8..f6fea637 100644 --- a/variants/heltec_tracker/target.h +++ b/variants/heltec_tracker/target.h @@ -14,7 +14,6 @@ #endif class HWTSensorManager : public SensorManager { - bool gps_active = false; LocationProvider * _location; void start_gps(); diff --git a/variants/heltec_tracker_v2/target.cpp b/variants/heltec_tracker_v2/target.cpp index c48a29f6..12b01bcc 100644 --- a/variants/heltec_tracker_v2/target.cpp +++ b/variants/heltec_tracker_v2/target.cpp @@ -17,7 +17,9 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, GPS_RESET, GPS_EN, &board.periph_power); + NmeaGpsDriver gps_driver(Serial1, PIN_GPS_TX, PIN_GPS_RX, GPS_RESET, GPS_EN, + &board.periph_power); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -43,4 +45,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/heltec_v3/target.cpp b/variants/heltec_v3/target.cpp index e6af466a..f2f712eb 100644 --- a/variants/heltec_v3/target.cpp +++ b/variants/heltec_v3/target.cpp @@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -43,4 +44,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/heltec_v4/target.cpp b/variants/heltec_v4/target.cpp index 8483f276..0f87c6b3 100644 --- a/variants/heltec_v4/target.cpp +++ b/variants/heltec_v4/target.cpp @@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -43,4 +44,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/heltec_v4_r8/target.cpp b/variants/heltec_v4_r8/target.cpp index 0b38531e..27e9f468 100644 --- a/variants/heltec_v4_r8/target.cpp +++ b/variants/heltec_v4_r8/target.cpp @@ -17,7 +17,9 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, GPS_RESET, GPS_EN, &board.periph_power); + NmeaGpsDriver gps_driver(Serial1, PIN_GPS_TX, PIN_GPS_RX, GPS_RESET, GPS_EN, + &board.periph_power); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; diff --git a/variants/keepteen_lt1/target.cpp b/variants/keepteen_lt1/target.cpp index f1879ac5..dd7c6741 100644 --- a/variants/keepteen_lt1/target.cpp +++ b/variants/keepteen_lt1/target.cpp @@ -12,7 +12,8 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -34,4 +35,3 @@ mesh::LocalIdentity radio_new_identity() { return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/lilygo_t_impulse_plus/target.cpp b/variants/lilygo_t_impulse_plus/target.cpp index 87b3dbfe..b6b0c82c 100644 --- a/variants/lilygo_t_impulse_plus/target.cpp +++ b/variants/lilygo_t_impulse_plus/target.cpp @@ -13,7 +13,8 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); @@ -34,4 +35,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/lilygo_tbeam_1w/target.cpp b/variants/lilygo_tbeam_1w/target.cpp index 6755df09..db11747f 100644 --- a/variants/lilygo_tbeam_1w/target.cpp +++ b/variants/lilygo_tbeam_1w/target.cpp @@ -19,7 +19,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -47,4 +48,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); } - diff --git a/variants/lilygo_tbeam_SX1262/target.cpp b/variants/lilygo_tbeam_SX1262/target.cpp index 6e5292a7..b97dda41 100644 --- a/variants/lilygo_tbeam_SX1262/target.cpp +++ b/variants/lilygo_tbeam_SX1262/target.cpp @@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -38,4 +39,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/lilygo_tbeam_SX1276/target.cpp b/variants/lilygo_tbeam_SX1276/target.cpp index 30f23dab..be7c8287 100644 --- a/variants/lilygo_tbeam_SX1276/target.cpp +++ b/variants/lilygo_tbeam_SX1276/target.cpp @@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; diff --git a/variants/lilygo_tbeam_supreme_SX1262/target.cpp b/variants/lilygo_tbeam_supreme_SX1262/target.cpp index a0b765bf..86b9116c 100644 --- a/variants/lilygo_tbeam_supreme_SX1262/target.cpp +++ b/variants/lilygo_tbeam_supreme_SX1262/target.cpp @@ -19,7 +19,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -35,4 +36,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/lilygo_tdeck/target.cpp b/variants/lilygo_tdeck/target.cpp index d20c56a3..4084a73b 100644 --- a/variants/lilygo_tdeck/target.cpp +++ b/variants/lilygo_tdeck/target.cpp @@ -14,7 +14,8 @@ WRAPPER_CLASS radio_driver(radio, board); ESP32RTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); -MicroNMEALocationProvider gps(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider gps(gps_driver, &rtc_clock); EnvironmentSensorManager sensors(gps); #ifdef DISPLAY_CLASS diff --git a/variants/lilygo_techo_card/target.cpp b/variants/lilygo_techo_card/target.cpp index 8bbe0363..ea74bd0c 100644 --- a/variants/lilygo_techo_card/target.cpp +++ b/variants/lilygo_techo_card/target.cpp @@ -13,7 +13,8 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); diff --git a/variants/lilygo_techo_lite/target.cpp b/variants/lilygo_techo_lite/target.cpp index 95a62fcd..6d199fff 100644 --- a/variants/lilygo_techo_lite/target.cpp +++ b/variants/lilygo_techo_lite/target.cpp @@ -13,7 +13,8 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); @@ -35,4 +36,3 @@ mesh::LocalIdentity radio_new_identity() { return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/meshadventurer/target.cpp b/variants/meshadventurer/target.cpp index 8795a4cb..faf2e30e 100644 --- a/variants/meshadventurer/target.cpp +++ b/variants/meshadventurer/target.cpp @@ -11,7 +11,8 @@ WRAPPER_CLASS radio_driver(radio, board); ESP32RTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); MASensorManager sensors = MASensorManager(nmea); #ifdef DISPLAY_CLASS @@ -37,17 +38,13 @@ mesh::LocalIdentity radio_new_identity() { void MASensorManager::start_gps() { - if(!gps_active) { - MESH_DEBUG_PRINTLN("starting GPS"); - gps_active = true; - } + MESH_DEBUG_PRINTLN("starting GPS"); + _location->setGpsOn(true); } void MASensorManager::stop_gps() { - if(gps_active) { - MESH_DEBUG_PRINTLN("stopping GPS"); - gps_active = false; - } + MESH_DEBUG_PRINTLN("stopping GPS"); + _location->setGpsOn(false); } bool MASensorManager::begin() { @@ -67,7 +64,7 @@ bool MASensorManager::querySensors(uint8_t requester_permissions, CayenneLPP& te void MASensorManager::loop() { static long next_gps_update = 0; _location->loop(); - if(millis() > next_gps_update && gps_active) { + if(millis() > next_gps_update && _location->isEnabled()) { if(_location->isValid()) { node_lat = ((double)_location->getLatitude()) / 1000000.; node_lon = ((double)_location->getLongitude()) / 1000000.; @@ -85,7 +82,7 @@ const char* MASensorManager::getSettingName(int i) const { } const char* MASensorManager::getSettingValue(int i) const { if(i == 0) { - return gps_active ? "1" : "0"; + return _location->isGpsOn() ? "1" : "0"; } return NULL; } diff --git a/variants/meshadventurer/target.h b/variants/meshadventurer/target.h index 0749565d..9581d422 100644 --- a/variants/meshadventurer/target.h +++ b/variants/meshadventurer/target.h @@ -15,8 +15,7 @@ #endif class MASensorManager : public SensorManager { - bool gps_active = false; - LocationProvider * _location; + LocationProvider* _location; void start_gps(); void stop_gps(); diff --git a/variants/meshnology_w12/target.cpp b/variants/meshnology_w12/target.cpp index bf04ba36..a3d6089f 100644 --- a/variants/meshnology_w12/target.cpp +++ b/variants/meshnology_w12/target.cpp @@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -70,4 +71,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/meshtracker_x1/target.cpp b/variants/meshtracker_x1/target.cpp index 5b90d660..2dee0ebd 100644 --- a/variants/meshtracker_x1/target.cpp +++ b/variants/meshtracker_x1/target.cpp @@ -1,7 +1,7 @@ #include <Arduino.h> #include "target.h" +#include <helpers/sensors/AirohaGpsDriver.h> #include <helpers/sensors/MicroNMEALocationProvider.h> -#include <helpers/sensors/AirohaSleep.h> MeshTrackerX1Board board; @@ -10,7 +10,8 @@ RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BU WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock rtc_clock; -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +AirohaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); MeshTrackerX1SensorManager sensors = MeshTrackerX1SensorManager(nmea); #ifdef DISPLAY_CLASS @@ -27,28 +28,16 @@ mesh::LocalIdentity radio_new_identity() { } void MeshTrackerX1SensorManager::start_gps() { - gps_active = true; - digitalWrite(GPS_EN, HIGH); - delay(10); - digitalWrite(GPS_RTC_INT, HIGH); - delay(5); - digitalWrite(GPS_RTC_INT, LOW); + _nmea->setGpsOn(true); } void MeshTrackerX1SensorManager::stop_gps() { - gps_active = false; - digitalWrite(GPS_VRTC_EN, HIGH); // keep GPS RTC alive for faster fix on wake - digitalWrite(GPS_RTC_INT, LOW); // make sure this is LOW so we can pulse it to wake - airohaEnterSleep(_nmea); - digitalWrite(GPS_EN, LOW); + _nmea->setGpsOn(false); } bool MeshTrackerX1SensorManager::begin() { // init GPS - Serial1.begin(GPS_BAUD_RATE); - digitalWrite(GPS_RESET, HIGH); - delay(10); - digitalWrite(GPS_RESET, LOW); + gps_driver.initialize(); // init SPA06-003 barometer baro_ok = spa06.begin(SPA06_003_DEFAULT_ADDR, &Wire) || spa06.begin(0x76, &Wire); @@ -81,7 +70,7 @@ void MeshTrackerX1SensorManager::loop() { _nmea->loop(); if (millis() > next_gps_update) { - if (gps_active && _nmea->isValid()) { + if (_nmea->isEnabled() && _nmea->isValid()) { node_lat = ((double)_nmea->getLatitude())/1000000.; node_lon = ((double)_nmea->getLongitude())/1000000.; node_altitude = ((double)_nmea->getAltitude()) / 1000.0; @@ -97,7 +86,7 @@ const char* MeshTrackerX1SensorManager::getSettingName(int i) const { } const char* MeshTrackerX1SensorManager::getSettingValue(int i) const { if (i == 0) { - return gps_active ? "1" : "0"; + return _nmea->isGpsOn() ? "1" : "0"; } return NULL; } diff --git a/variants/meshtracker_x1/target.h b/variants/meshtracker_x1/target.h index 9741efb6..e678e29c 100644 --- a/variants/meshtracker_x1/target.h +++ b/variants/meshtracker_x1/target.h @@ -14,13 +14,11 @@ #endif class MeshTrackerX1SensorManager: public SensorManager { - bool gps_active = false; bool baro_ok = false; Adafruit_SPA06_003 spa06; LocationProvider * _nmea; void start_gps(); - void sleep_gps(); void stop_gps(); public: MeshTrackerX1SensorManager(LocationProvider &nmea): _nmea(&nmea) { } diff --git a/variants/minewsemi_me25ls01/target.cpp b/variants/minewsemi_me25ls01/target.cpp index 41fc71a7..8d9a6e07 100644 --- a/variants/minewsemi_me25ls01/target.cpp +++ b/variants/minewsemi_me25ls01/target.cpp @@ -10,7 +10,8 @@ VolatileRTCClock rtc_clock; extern EnvironmentSensorManager sensors; #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; diff --git a/variants/muzi_base/target.cpp b/variants/muzi_base/target.cpp index 5bd846c9..b65bafa1 100644 --- a/variants/muzi_base/target.cpp +++ b/variants/muzi_base/target.cpp @@ -13,7 +13,8 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); MuziBaseSensorManager sensors = MuziBaseSensorManager(nmea); #else MuziBaseSensorManager sensors; @@ -38,13 +39,7 @@ static void muziPowerOff() { bool MuziBaseSensorManager::begin() { pwr_btn.begin(); - bool ok = EnvironmentSensorManager::begin(); -#if ENV_INCLUDE_GPS - pinMode(PIN_GPS_SWITCH, INPUT); - _last_gps_sw = digitalRead(PIN_GPS_SWITCH); // initial gps state from the switch - if (_last_gps_sw == HIGH) start_gps(); else stop_gps(); -#endif - return ok; + return EnvironmentSensorManager::begin(); } void MuziBaseSensorManager::loop() { @@ -55,17 +50,6 @@ void MuziBaseSensorManager::loop() { _pwr_last_click = t; if (++_pwr_clicks >= USER_BTN_POWER_OFF_CLICKS) muziPowerOff(); } -#if ENV_INCLUDE_GPS - unsigned long now = millis(); - if (now > _next_sw_check) { // check the mode switch ~once a sec - _next_sw_check = now + 1000; - int sw = digitalRead(PIN_GPS_SWITCH); - if (sw != _last_gps_sw) { - _last_gps_sw = sw; - if (sw == HIGH) start_gps(); else stop_gps(); - } - } -#endif EnvironmentSensorManager::loop(); } diff --git a/variants/muzi_base/target.h b/variants/muzi_base/target.h index 45cd595f..3f7dcbf5 100644 --- a/variants/muzi_base/target.h +++ b/variants/muzi_base/target.h @@ -38,14 +38,10 @@ extern AutoDiscoverRTCClock rtc_clock; // muzi sensor manager, polled from main loop via sensors.loop(): // - user button: USER_BTN_POWER_OFF_CLICKS quick presses -> power off (all builds) -// - gps mode switch on/off (superIO only, see thinknode_m1) +// gps mode is now handled by GpsDriver on superIO class MuziBaseSensorManager : public EnvironmentSensorManager { unsigned long _pwr_last_click = 0; uint8_t _pwr_clicks = 0; -#if ENV_INCLUDE_GPS - int _last_gps_sw = -1; - unsigned long _next_sw_check = 0; -#endif public: #if ENV_INCLUDE_GPS MuziBaseSensorManager(LocationProvider& location) : EnvironmentSensorManager(location) {} diff --git a/variants/muzi_base/variant.h b/variants/muzi_base/variant.h index b007c1f8..0c1245a8 100644 --- a/variants/muzi_base/variant.h +++ b/variants/muzi_base/variant.h @@ -162,6 +162,8 @@ static const uint8_t AREF = (PIN_AREF); // not used #define SWITCH_MODE1 (32+9) // P1.09 #define SWITCH_MODE2 (12) // P0.12 #define PIN_GPS_SWITCH SWITCH_MODE2 +#define GPS_SWITCH_IS_HARDWARE (0) +#define GPS_SWITCH_TURNS_GPS_ON (1) //////////////////////////////////////////////////////////////////////////////// // Buzzer diff --git a/variants/muziworks_r1_neo/target.cpp b/variants/muziworks_r1_neo/target.cpp index f667a282..3081de2c 100644 --- a/variants/muziworks_r1_neo/target.cpp +++ b/variants/muziworks_r1_neo/target.cpp @@ -20,7 +20,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; diff --git a/variants/nano_g2_ultra/NanoG2UltraGpsDriver.h b/variants/nano_g2_ultra/NanoG2UltraGpsDriver.h new file mode 100644 index 00000000..3772084b --- /dev/null +++ b/variants/nano_g2_ultra/NanoG2UltraGpsDriver.h @@ -0,0 +1,31 @@ +#pragma once + +#include <helpers/sensors/NmeaGpsDriver.h> + +class NanoG2UltraGpsDriver : public NmeaGpsDriver { +public: + NanoG2UltraGpsDriver(HardwareSerial& serial) : NmeaGpsDriver(serial) { + pinMode(PIN_GPS_STANDBY, OUTPUT); + digitalWrite(PIN_GPS_STANDBY, LOW); + } + + void begin() override { + if (isEnabled()) return; + + digitalWrite(PIN_GPS_STANDBY, HIGH); + NmeaGpsDriver::begin(); + delay(1000); + } + + void stop() override { + NmeaGpsDriver::stop(); + digitalWrite(PIN_GPS_STANDBY, LOW); + } + + bool detectAtBoot() { + begin(); + const bool wasActive = detect(0); + if (!wasActive) stop(); + return wasActive; + } +}; diff --git a/variants/nano_g2_ultra/target.cpp b/variants/nano_g2_ultra/target.cpp index 69a2772c..ee258f2d 100644 --- a/variants/nano_g2_ultra/target.cpp +++ b/variants/nano_g2_ultra/target.cpp @@ -3,6 +3,7 @@ #include <Arduino.h> #include <helpers/ArduinoHelpers.h> #include <helpers/sensors/MicroNMEALocationProvider.h> +#include "NanoG2UltraGpsDriver.h" NanoG2Ultra board; @@ -12,8 +13,10 @@ WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); -NanoG2UltraSensorManager sensors = NanoG2UltraSensorManager(nmea); +// NanoG2UltraGpsDriver now handles the special init needed for NanoG2 +NanoG2UltraGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); +NanoG2UltraSensorManager sensors = NanoG2UltraSensorManager(nmea, gps_driver); #ifdef DISPLAY_CLASS DISPLAY_CLASS display; @@ -27,35 +30,19 @@ bool radio_init() { void NanoG2UltraSensorManager::start_gps() { MESH_DEBUG_PRINTLN("Starting GPS"); - if (!gps_active) { - digitalWrite(PIN_GPS_STANDBY, HIGH); // Wake GPS from standby - Serial1.setPins(PIN_GPS_TX, PIN_GPS_RX); - Serial1.begin(9600); - MESH_DEBUG_PRINTLN("Waiting for gps to power up"); - delay(1000); - gps_active = true; - } - _location->begin(); + _location->setGpsOn(true); } void NanoG2UltraSensorManager::stop_gps() { MESH_DEBUG_PRINTLN("Stopping GPS"); - if (gps_active) { - digitalWrite(PIN_GPS_STANDBY, LOW); // sleep GPS - gps_active = false; - } - _location->stop(); + _location->setGpsOn(false); } bool NanoG2UltraSensorManager::begin() { - digitalWrite(PIN_GPS_STANDBY, HIGH); // Wake GPS from standby - Serial1.setPins(PIN_GPS_TX, PIN_GPS_RX); - Serial1.begin(9600); MESH_DEBUG_PRINTLN("Checking GPS switch state"); - delay(1000); // Check initial switch state to determine if GPS should be active - if (Serial1.available() > 0) { + if (_gps_driver->detectAtBoot()) { MESH_DEBUG_PRINTLN("GPS was on at boot, GPS enabled"); start_gps(); } else { @@ -75,14 +62,14 @@ bool NanoG2UltraSensorManager::querySensors(uint8_t requester_permissions, Cayen void NanoG2UltraSensorManager::loop() { static long next_gps_update = 0; - if (!gps_active) { + if (!_location->isEnabled()) { return; // GPS is not active, skip further processing } _location->loop(); if (millis() > next_gps_update) { - if (_location->isValid()) { + if (_location->isEnabled() && _location->isValid()) { node_lat = ((double)_location->getLatitude()) / 1000000.; node_lon = ((double)_location->getLongitude()) / 1000000.; node_altitude = ((double)_location->getAltitude()) / 1000.0; @@ -105,7 +92,7 @@ const char *NanoG2UltraSensorManager::getSettingName(int i) const { const char *NanoG2UltraSensorManager::getSettingValue(int i) const { if (i == 0) { - return gps_active ? "1" : "0"; + return _location->isGpsOn() ? "1" : "0"; } return NULL; } diff --git a/variants/nano_g2_ultra/target.h b/variants/nano_g2_ultra/target.h index 5c6ebee1..d540b9ec 100644 --- a/variants/nano_g2_ultra/target.h +++ b/variants/nano_g2_ultra/target.h @@ -14,15 +14,18 @@ #endif #include <helpers/sensors/LocationProvider.h> +class NanoG2UltraGpsDriver; + class NanoG2UltraSensorManager : public SensorManager { - bool gps_active = false; LocationProvider *_location; + NanoG2UltraGpsDriver *_gps_driver; void start_gps(); void stop_gps(); public: - NanoG2UltraSensorManager(LocationProvider &location) : _location(&location) {} + NanoG2UltraSensorManager(LocationProvider &location, NanoG2UltraGpsDriver &gps_driver) + : _location(&location), _gps_driver(&gps_driver) {} bool begin() override; bool querySensors(uint8_t requester_permissions, CayenneLPP &telemetry) override; void loop() override; @@ -44,4 +47,3 @@ extern MomentaryButton user_btn; bool radio_init(); mesh::LocalIdentity radio_new_identity(); - diff --git a/variants/promicro/target.cpp b/variants/promicro/target.cpp index b5a74c90..5758d9cd 100644 --- a/variants/promicro/target.cpp +++ b/variants/promicro/target.cpp @@ -12,7 +12,8 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -34,4 +35,3 @@ mesh::LocalIdentity radio_new_identity() { return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/rak3112/target.cpp b/variants/rak3112/target.cpp index 9df1bf8f..9b1d11a0 100644 --- a/variants/rak3112/target.cpp +++ b/variants/rak3112/target.cpp @@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -43,4 +44,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/rak_wismesh_tag/target.cpp b/variants/rak_wismesh_tag/target.cpp index cdf81f4f..3e80ae63 100644 --- a/variants/rak_wismesh_tag/target.cpp +++ b/variants/rak_wismesh_tag/target.cpp @@ -22,7 +22,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -37,4 +38,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/sensecap_indicator-espnow/target.cpp b/variants/sensecap_indicator-espnow/target.cpp index c84d1883..4895447c 100644 --- a/variants/sensecap_indicator-espnow/target.cpp +++ b/variants/sensecap_indicator-espnow/target.cpp @@ -8,7 +8,8 @@ ESPNOWRadio radio_driver; ESP32RTCClock rtc_clock; #if defined(ENV_INCLUDE_GPS) -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, (mesh::RTCClock*)&rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, (mesh::RTCClock*)&rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); diff --git a/variants/sensecap_solar/target.cpp b/variants/sensecap_solar/target.cpp index 46641517..11586ecd 100644 --- a/variants/sensecap_solar/target.cpp +++ b/variants/sensecap_solar/target.cpp @@ -13,7 +13,8 @@ WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); @@ -29,4 +30,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/station_g2/target.cpp b/variants/station_g2/target.cpp index 8018c20e..f5365eb5 100644 --- a/variants/station_g2/target.cpp +++ b/variants/station_g2/target.cpp @@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -44,4 +45,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/station_g3_esp32/target.cpp b/variants/station_g3_esp32/target.cpp index d3de074b..189169d2 100644 --- a/variants/station_g3_esp32/target.cpp +++ b/variants/station_g3_esp32/target.cpp @@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; diff --git a/variants/t1000-e/target.cpp b/variants/t1000-e/target.cpp index 0d7710b3..b96d01f8 100644 --- a/variants/t1000-e/target.cpp +++ b/variants/t1000-e/target.cpp @@ -82,13 +82,11 @@ mesh::LocalIdentity radio_new_identity() { } void T1000SensorManager::start_gps() { - gps_active = true; - _nmea->begin(); + _nmea->setGpsOn(true); } void T1000SensorManager::stop_gps() { - gps_active = false; - _nmea->stop(); + _nmea->setGpsOn(false); } @@ -115,7 +113,7 @@ void T1000SensorManager::loop() { _nmea->loop(); if (millis() > next_gps_update) { - if (gps_active && _nmea->isValid()) { + if (_nmea->isEnabled() && _nmea->isValid()) { node_lat = ((double)_nmea->getLatitude())/1000000.; node_lon = ((double)_nmea->getLongitude())/1000000.; node_altitude = ((double)_nmea->getAltitude()) / 1000.0; @@ -131,7 +129,7 @@ const char* T1000SensorManager::getSettingName(int i) const { } const char* T1000SensorManager::getSettingValue(int i) const { if (i == 0) { - return gps_active ? "1" : "0"; + return _nmea->isGpsOn() ? "1" : "0"; } return NULL; } diff --git a/variants/t1000-e/target.h b/variants/t1000-e/target.h index 4a1a2bb7..68508bcb 100644 --- a/variants/t1000-e/target.h +++ b/variants/t1000-e/target.h @@ -15,7 +15,6 @@ class AirohaGpsDriver; class T1000SensorManager: public SensorManager { - bool gps_active = false; LocationProvider * _nmea; AirohaGpsDriver* _gps_driver; diff --git a/variants/thinknode_m3/target.cpp b/variants/thinknode_m3/target.cpp index 1e6c2ad1..bb5746ca 100644 --- a/variants/thinknode_m3/target.cpp +++ b/variants/thinknode_m3/target.cpp @@ -11,7 +11,8 @@ WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); diff --git a/variants/thinknode_m4/target.cpp b/variants/thinknode_m4/target.cpp index 7da3f400..59a898f5 100644 --- a/variants/thinknode_m4/target.cpp +++ b/variants/thinknode_m4/target.cpp @@ -11,7 +11,8 @@ WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); diff --git a/variants/thinknode_m6/target.cpp b/variants/thinknode_m6/target.cpp index de167194..061f7ad4 100644 --- a/variants/thinknode_m6/target.cpp +++ b/variants/thinknode_m6/target.cpp @@ -12,7 +12,8 @@ WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); @@ -32,4 +33,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/thinknode_m7/target.cpp b/variants/thinknode_m7/target.cpp index f4b898d8..8e7e8a05 100644 --- a/variants/thinknode_m7/target.cpp +++ b/variants/thinknode_m7/target.cpp @@ -12,7 +12,8 @@ ESP32RTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); @@ -81,4 +82,3 @@ mesh::LocalIdentity radio_new_identity() { return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/thinknode_m8/target.cpp b/variants/thinknode_m8/target.cpp index 69f3cc52..04496d3f 100644 --- a/variants/thinknode_m8/target.cpp +++ b/variants/thinknode_m8/target.cpp @@ -13,7 +13,8 @@ WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); diff --git a/variants/thinknode_m9/target.cpp b/variants/thinknode_m9/target.cpp index 3cbd7d75..990f0388 100644 --- a/variants/thinknode_m9/target.cpp +++ b/variants/thinknode_m9/target.cpp @@ -11,7 +11,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); diff --git a/variants/wio-tracker-l1-1w/target.cpp b/variants/wio-tracker-l1-1w/target.cpp index 7a573258..cd4b8dac 100644 --- a/variants/wio-tracker-l1-1w/target.cpp +++ b/variants/wio-tracker-l1-1w/target.cpp @@ -13,7 +13,8 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); @@ -37,4 +38,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/wio-tracker-l1/target.cpp b/variants/wio-tracker-l1/target.cpp index 7a573258..cd4b8dac 100644 --- a/variants/wio-tracker-l1/target.cpp +++ b/variants/wio-tracker-l1/target.cpp @@ -13,7 +13,8 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); @@ -37,4 +38,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/xiao_c3/target.cpp b/variants/xiao_c3/target.cpp index 7f30dc8b..d3bbdf1c 100644 --- a/variants/xiao_c3/target.cpp +++ b/variants/xiao_c3/target.cpp @@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -39,4 +40,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - From e58be9ab11b8c7a22b08c19dbb78d7bc895a1cef Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Mon, 2 Nov 2026 12:45:05 -0400 Subject: [PATCH 346/381] gps: cache the last fix in LocationProvider (isValid vs hasValidFix), fix and status commands --- docs/cli_commands.md | 37 +++++++++++-- docs/companion_cli.md | 52 +++++++++++++++++++ src/helpers/CommonGpsPrefs.cpp | 48 ++++++++++++++--- src/helpers/sensors/LocationProvider.h | 21 +++++++- .../sensors/MicroNMEALocationProvider.h | 35 +++++++++---- src/helpers/sensors/RakLocationProvider.h | 48 ++++++++++++----- 6 files changed, 208 insertions(+), 33 deletions(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 9fde4d43..eb8c6b20 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -999,9 +999,16 @@ region save --- ### GPS (When GPS support is compiled in) -#### View or change GPS state +#### View GPS state **Usage:** - `gps` + +**Note:** Reports the requested state, receiver activity, last-fix status (last fix gives number of sats and how long ago was the fix), and mode. In periodic mode, `waiting` means the receiver is off between acquisitions; the last fix remains available. `off(hw)` means a hardware GPS switch is off. + +--- + +#### Change GPS state +**Usage:** - `gps <state>` **Parameters:** @@ -1009,9 +1016,25 @@ region save **Default:** `off` -**Note:** Output format: -- `off` when the GPS hardware is disabled -- `on, {active|deactivated}, {fix|no fix}, {sat count} sats` when the GPS hardware is enabled +--- + +#### View or change the GPS acquisition period +**Usage:** +- `gps period` +- `gps period <seconds>` + +**Parameters:** +- `seconds`: `0` for continuous tracking, or `1`-`86400` for periodic acquisition + +**Note:** A periodic acquisition stops after receiving a valid fix, then resumes after the configured period. + +--- + +#### View the last GPS fix +**Usage:** +- `gps fix` + +**Note:** Returns the last valid latitude, longitude, altitude, and elapsed time since the fix. Returns `no fix` until a valid fix is received. --- @@ -1021,6 +1044,12 @@ region save --- +#### View GPS diagnostics +**Usage:** +- `gps diag` + +--- + #### Set this node's location based on the GPS coordinates **Usage:** - `gps setloc` diff --git a/docs/companion_cli.md b/docs/companion_cli.md index 31a05584..24843269 100644 --- a/docs/companion_cli.md +++ b/docs/companion_cli.md @@ -7,6 +7,7 @@ Since version 1.18 meshcore companion radio firmware has a CLI interface, which - [Configuration](#configuration) - [System](#system) - [Radio](#radio) + - [GPS](#gps) - [BLE](#ble) - [Wifi](#wifi) - [UI](#ui) @@ -119,6 +120,57 @@ Radio parameters are common to all roles and handled by `CommonRadioPrefs`. --- +### GPS + +#### View GPS state +**Usage:** +- `gps` + +**Note:** Reports the requested state, receiver activity, last-fix status (last fix gives number of sats and how long ago was the fix), and mode. In periodic mode, `waiting` means the receiver is off between acquisitions; the last fix remains available. `off(hw)` means a hardware GPS switch is off. + +--- + +#### Change GPS state +**Usage:** +- `gps <state>` + +**Parameters:** +- `state`: `on`|`off` + +--- + +#### View or change the GPS acquisition period +**Usage:** +- `gps period` +- `gps period <seconds>` + +**Parameters:** +- `seconds`: `0` for continuous tracking, or `1`-`86400` for periodic acquisition + +**Note:** A periodic acquisition stops after receiving a valid fix, then resumes after the configured period. + +--- + +#### View the last GPS fix +**Usage:** +- `gps fix` + +**Note:** Returns the last valid latitude, longitude, altitude, and elapsed time since the fix. Returns `no fix` until a valid fix is received. + +--- + +#### Sync this node's clock with GPS time +**Usage:** +- `gps sync` + +--- + +#### View GPS diagnostics +**Usage:** +- `gps diag` + +--- + #### View or change this node's rx boosted gain mode (SX12xx and LR1110) **Usage:** - `get radio.rxgain` diff --git a/src/helpers/CommonGpsPrefs.cpp b/src/helpers/CommonGpsPrefs.cpp index fe29c0c0..248ae540 100644 --- a/src/helpers/CommonGpsPrefs.cpp +++ b/src/helpers/CommonGpsPrefs.cpp @@ -37,13 +37,49 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, } if (location == nullptr) { strcpy(reply, "gps provider not found"); - } else if (location->isEnabled()) { - sprintf(reply, "on, %s, %s, %d sats, mode: %s", - isGpsEnabled() ? "active" : "deactivated", - location->isValid() ? "fix" : "no fix", - location->satellitesCount(), mode); + } else if (location->isGpsOn()) { + const char* activity = "active"; + if (!location->isEnabled()) { + if (location->hasHardwareEnableState() && !location->isHardwareEnabled()) { + activity = "off(hw)"; + } else if (getGpsPeriod() > 0) { + activity = "waiting"; + } else { + activity = "inactive"; + } + } + char fix[32]; + if (location->hasValidFix()) { + snprintf(fix, sizeof(fix), "%ld sats %lus ago", + location->satellitesCount(), (unsigned long)location->getLastFixAge()); + } else { + strcpy(fix, "no fix"); + } + snprintf(reply, 160, "on, %s, %s, mode: %s", activity, fix, mode); + } + return true; + } + if (strcmp(command, "gps fix") == 0) { + LocationProvider* location = sensors.getLocationProvider(); + if (location == nullptr) { + strcpy(reply, "gps provider not found"); + } else if (!location->hasValidFix()) { + strcpy(reply, "no fix"); } else { - snprintf(reply, 160, "off, mode: %s", mode); + const long latitude = location->getLatitude(); + const long longitude = location->getLongitude(); + const uint32_t fixAge = location->getLastFixAge(); + char age[24]; + if (fixAge == UINT32_MAX) { + strcpy(age, "age unavailable"); + } else { + snprintf(age, sizeof(age), "%lus ago", (unsigned long)fixAge); + } + snprintf(reply, 160, "%s%ld.%06ld, %s%ld.%06ld, %ldm, %s", + latitude < 0 ? "-" : "", labs(latitude) / 1000000L, + labs(latitude) % 1000000L, + longitude < 0 ? "-" : "", labs(longitude) / 1000000L, + labs(longitude) % 1000000L, location->getAltitude() / 1000L, age); } return true; } diff --git a/src/helpers/sensors/LocationProvider.h b/src/helpers/sensors/LocationProvider.h index 93cecf5b..dc316e1d 100644 --- a/src/helpers/sensors/LocationProvider.h +++ b/src/helpers/sensors/LocationProvider.h @@ -6,9 +6,22 @@ class LocationProvider { +public: + // Last valid fix, always filled in one go so readers get a consistent snapshot. + struct LastFix { + bool valid = false; + long latitude = 0; + long longitude = 0; + long altitude = 0; + long satellites = 0; + long timestamp = 0; + unsigned long acquiredAt = 0; // millis() when the fix was stored + }; + protected: bool _time_sync_needed = true; bool _gpsOn = false; + LastFix _lastFix; public: virtual ~LocationProvider() = default; @@ -19,7 +32,9 @@ public: virtual long getLongitude() = 0; virtual long getAltitude() = 0; virtual long satellitesCount() = 0; - virtual bool isValid() = 0; + virtual bool isValid() = 0; // current fix is valid + virtual bool hasValidFix() { return getLastFix().valid || isValid(); } // a valid fix was obtained at some point + virtual LastFix getLastFix() const { return _lastFix; } // snapshot of the last valid fix virtual long getTimestamp() = 0; virtual void sendSentence(const char * sentence); virtual bool waitFor(const char* prefix, uint32_t timeout_ms) { return false; } @@ -28,6 +43,10 @@ public: virtual bool keepEnabledAfterDetection() const { return false; } virtual void setGpsPeriod(uint32_t seconds) { } virtual uint32_t getGpsPeriod() const { return 0; } + virtual uint32_t getLastFixAge() const { // in seconds, UINT32_MAX if never + const LastFix f = getLastFix(); + return f.valid ? (uint32_t)(millis() - f.acquiredAt) / 1000UL : UINT32_MAX; + } virtual bool hasHardwareEnableState() const { return false; } virtual bool isHardwareEnabled() const { return true; } virtual bool isGpsOn() const { return _gpsOn; } diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index 2e9ff9cc..cceffd8c 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -32,10 +32,8 @@ class MicroNMEALocationProvider : public LocationProvider { uint32_t _stop_calls = 0; unsigned long _last_uart_ms = 0; unsigned long _last_nmea_ms = 0; - unsigned long _last_fix_ms = 0; bool _uart_seen = false; bool _nmea_seen = false; - bool _fix_seen = false; static uint32_t ageMs(unsigned long timestamp) { return (uint32_t)(millis() - timestamp); @@ -64,6 +62,18 @@ class MicroNMEALocationProvider : public LocationProvider { _nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL; } + void saveFix() { + LastFix fix; + fix.latitude = nmea.getLatitude(); + fix.longitude = nmea.getLongitude(); + nmea.getAltitude(fix.altitude); + fix.satellites = nmea.getNumSatellites(); + fix.timestamp = getTimestamp(); + fix.acquiredAt = millis(); + fix.valid = true; + _lastFix = fix; + } + void updateTime() { if (!isValid()) time_valid = 0; @@ -161,17 +171,25 @@ public: LocationProvider::syncTime(); } - long getLatitude() override { return nmea.getLatitude(); } - long getLongitude() override { return nmea.getLongitude(); } + long getLatitude() override { + return nmea.isValid() ? nmea.getLatitude() : _lastFix.latitude; + } + long getLongitude() override { + return nmea.isValid() ? nmea.getLongitude() : _lastFix.longitude; + } long getAltitude() override { + if (!nmea.isValid()) return _lastFix.altitude; long alt = 0; nmea.getAltitude(alt); return alt; } - long satellitesCount() override { return nmea.getNumSatellites(); } + long satellitesCount() override { + return nmea.isValid() ? nmea.getNumSatellites() : _lastFix.satellites; + } bool isValid() override { return nmea.isValid(); } long getTimestamp() override { + if (!nmea.isValid()) return _lastFix.timestamp; DateTime dt(nmea.getYear(), nmea.getMonth(), nmea.getDay(), nmea.getHour(), nmea.getMinute(), nmea.getSecond()); return dt.unixtime(); @@ -228,10 +246,9 @@ public: _nmea_seen = true; const char* messageId = nmea.getMessageID(); - if (parsed && isValid() && + if (parsed && nmea.isValid() && (strcmp(messageId, "GGA") == 0 || strcmp(messageId, "RMC") == 0)) { - _last_fix_ms = millis(); - _fix_seen = true; + saveFix(); if (_acquiringPeriodically) finishPeriodicAcquisition(); } } else { @@ -256,7 +273,7 @@ public: char fix_age[11]; formatAge(uart_age, sizeof(uart_age), _uart_seen, _last_uart_ms); formatAge(nmea_age, sizeof(nmea_age), _nmea_seen, _last_nmea_ms); - formatAge(fix_age, sizeof(fix_age), _fix_seen, _last_fix_ms); + formatAge(fix_age, sizeof(fix_age), _lastFix.valid, _lastFix.acquiredAt); snprintf(out, out_size, "en:%u ub:%lu ua:%s ok:%lu bad:%lu na:%s sat:%ld fix:%u fa:%s bc:%lu sc:%lu", diff --git a/src/helpers/sensors/RakLocationProvider.h b/src/helpers/sensors/RakLocationProvider.h index c909b7c4..db0b957b 100644 --- a/src/helpers/sensors/RakLocationProvider.h +++ b/src/helpers/sensors/RakLocationProvider.h @@ -11,6 +11,18 @@ class RakLocationProvider : public LocationProvider { unsigned long _acquisitionStarted = 0; bool _acquiringPeriodically = false; + void saveRak12500Fix() { + LastFix fix; + fix.latitude = _driver.getLatitude(); + fix.longitude = _driver.getLongitude(); + fix.altitude = _driver.getAltitude(); + fix.satellites = _driver.getSatellites(); + fix.timestamp = _driver.getTimestamp(); + fix.acquiredAt = millis(); + fix.valid = true; + _lastFix = fix; + } + public: RakLocationProvider(RakGpsDriver& driver, mesh::RTCClock* clock = nullptr) : _driver(driver), _nmea(driver.nmeaDriver(), clock) {} @@ -21,27 +33,31 @@ public: } long getLatitude() override { - return _driver.usesRak12500() ? _driver.getLatitude() : _nmea.getLatitude(); + return _driver.usesRak12500() ? _lastFix.latitude : _nmea.getLatitude(); } long getLongitude() override { - return _driver.usesRak12500() ? _driver.getLongitude() : _nmea.getLongitude(); + return _driver.usesRak12500() ? _lastFix.longitude : _nmea.getLongitude(); } long getAltitude() override { - return _driver.usesRak12500() ? _driver.getAltitude() : _nmea.getAltitude(); + return _driver.usesRak12500() ? _lastFix.altitude : _nmea.getAltitude(); } long satellitesCount() override { - return _driver.usesRak12500() ? _driver.getSatellites() : _nmea.satellitesCount(); + return _driver.usesRak12500() ? _lastFix.satellites : _nmea.satellitesCount(); } bool isValid() override { return _driver.usesRak12500() ? _driver.hasFix() : _nmea.isValid(); } + LastFix getLastFix() const override { + return _driver.usesRak12500() ? _lastFix : _nmea.getLastFix(); + } + long getTimestamp() override { - return _driver.usesRak12500() ? _driver.getTimestamp() : _nmea.getTimestamp(); + return _driver.usesRak12500() ? _lastFix.timestamp : _nmea.getTimestamp(); } void sendSentence(const char* sentence) override { @@ -104,18 +120,24 @@ public: void loop() override { if (_driver.usesRak12500()) { - if (_gpsOn && _gpsPeriodSeconds > 0) { - if (!_acquiringPeriodically && - (long)(millis() - _nextAcquisition) >= 0) { - _driver.begin(); - _acquiringPeriodically = true; - _acquisitionStarted = millis(); + if (_gpsOn) { + if (_gpsPeriodSeconds > 0) { + if (!_acquiringPeriodically && + (long)(millis() - _nextAcquisition) >= 0) { + _driver.begin(); + _acquiringPeriodically = true; + _acquisitionStarted = millis(); + } } - if (_acquiringPeriodically && isValid()) { + + const bool hasCurrentFix = _driver.hasFix(); + if (hasCurrentFix) saveRak12500Fix(); + + if (_gpsPeriodSeconds > 0 && _acquiringPeriodically && hasCurrentFix) { _driver.stop(); _acquiringPeriodically = false; _nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL; - } else if (_acquiringPeriodically && + } else if (_gpsPeriodSeconds > 0 && _acquiringPeriodically && (uint32_t)(millis() - _acquisitionStarted) >= GPS_PERIODIC_ACQUISITION_TIMEOUT_MS) { _driver.stop(); From e9d197cf795d8414841e5f7586cc57b0b94dd16e Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Tue, 3 Nov 2026 15:52:59 -0400 Subject: [PATCH 347/381] gps: periodic acquisition rules (timeout, sats and settle time), isEnabled renamed isActive --- src/helpers/CommonGpsPrefs.cpp | 4 ++- src/helpers/sensors/AirohaGpsDriver.h | 2 +- .../sensors/EnvironmentSensorManager.cpp | 4 +-- src/helpers/sensors/GpsDriver.h | 2 +- src/helpers/sensors/LocationProvider.h | 4 +-- .../sensors/MicroNMEALocationProvider.h | 33 +++++++++++++++---- src/helpers/sensors/NmeaGpsDriver.h | 2 +- src/helpers/sensors/RakGpsDriver.h | 4 +-- src/helpers/sensors/RakLocationProvider.h | 11 +++++-- 9 files changed, 46 insertions(+), 20 deletions(-) diff --git a/src/helpers/CommonGpsPrefs.cpp b/src/helpers/CommonGpsPrefs.cpp index 248ae540..e08878a6 100644 --- a/src/helpers/CommonGpsPrefs.cpp +++ b/src/helpers/CommonGpsPrefs.cpp @@ -39,7 +39,7 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, strcpy(reply, "gps provider not found"); } else if (location->isGpsOn()) { const char* activity = "active"; - if (!location->isEnabled()) { + if (!location->isActive()) { if (location->hasHardwareEnableState() && !location->isHardwareEnabled()) { activity = "off(hw)"; } else if (getGpsPeriod() > 0) { @@ -56,6 +56,8 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, strcpy(fix, "no fix"); } snprintf(reply, 160, "on, %s, %s, mode: %s", activity, fix, mode); + } else { + snprintf(reply, 160, "off, mode: %s", mode); } return true; } diff --git a/src/helpers/sensors/AirohaGpsDriver.h b/src/helpers/sensors/AirohaGpsDriver.h index 36d5eb6b..cd94d419 100644 --- a/src/helpers/sensors/AirohaGpsDriver.h +++ b/src/helpers/sensors/AirohaGpsDriver.h @@ -77,7 +77,7 @@ public: NmeaGpsDriver::stop(); } - bool isEnabled() const override { + bool isActive() const override { return digitalRead(GPS_EN) == HIGH; } }; diff --git a/src/helpers/sensors/EnvironmentSensorManager.cpp b/src/helpers/sensors/EnvironmentSensorManager.cpp index 2cf8b66b..ee942df1 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.cpp +++ b/src/helpers/sensors/EnvironmentSensorManager.cpp @@ -631,7 +631,7 @@ bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, Cayen next_available_channel = TELEM_CHANNEL_SELF + 1; #if ENV_INCLUDE_GPS - if (requester_permissions & TELEM_PERM_LOCATION && _location->isEnabled()) { + if (requester_permissions & TELEM_PERM_LOCATION && _location->isGpsOn()) { telemetry.addGPS(TELEM_CHANNEL_SELF, node_lat, node_lon, node_altitude); } #endif @@ -748,7 +748,7 @@ void EnvironmentSensorManager::loop() { _location->loop(); if ((long)(millis() - next_gps_update) > 0) { - if (_location->isEnabled() && _location->isValid()) { + if (_location->isGpsOn() && _location->hasValidFix()) { node_lat = ((double)_location->getLatitude())/1000000.; node_lon = ((double)_location->getLongitude())/1000000.; MESH_DEBUG_PRINTLN("lat %f lon %f", node_lat, node_lon); diff --git a/src/helpers/sensors/GpsDriver.h b/src/helpers/sensors/GpsDriver.h index b8cf4a5d..b17a6b27 100644 --- a/src/helpers/sensors/GpsDriver.h +++ b/src/helpers/sensors/GpsDriver.h @@ -9,7 +9,7 @@ public: virtual void begin() = 0; virtual void reset() = 0; virtual void stop() = 0; - virtual bool isEnabled() const = 0; + virtual bool isActive() const = 0; virtual bool hasHardwareEnableState() const { return false; } virtual bool isHardwareEnabled() const { return true; } // Returns true when the switch explicitly enables GPS in software. diff --git a/src/helpers/sensors/LocationProvider.h b/src/helpers/sensors/LocationProvider.h index dc316e1d..5bb6ec6a 100644 --- a/src/helpers/sensors/LocationProvider.h +++ b/src/helpers/sensors/LocationProvider.h @@ -63,14 +63,14 @@ public: virtual void begin() = 0; virtual void stop() = 0; virtual void loop() = 0; - virtual bool isEnabled() = 0; + virtual bool isActive() = 0; // Format compact diagnostics in the caller-provided buffer. Providers that // have more information (for example UART counters) can override this. virtual void formatDiagnostics(char* out, size_t out_size) { if (out_size == 0) return; snprintf(out, out_size, "en:%u sat:%ld fix:%u", - isEnabled() ? 1U : 0U, + isActive() ? 1U : 0U, satellitesCount(), isValid() ? 1U : 0U); } diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index cceffd8c..b07f486b 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -7,7 +7,16 @@ #include <string.h> #ifndef GPS_PERIODIC_ACQUISITION_TIMEOUT_MS - #define GPS_PERIODIC_ACQUISITION_TIMEOUT_MS 120000UL + #define GPS_PERIODIC_ACQUISITION_TIMEOUT_MS 300000UL +#endif + +// in periodic mode, keep reading after the first valid fix until enough satellites +// are used or the settle time has elapsed +#ifndef GPS_MIN_SATS_FOR_FIX + #define GPS_MIN_SATS_FOR_FIX 5 +#endif +#ifndef GPS_FIX_SETTLE_MS + #define GPS_FIX_SETTLE_MS 10000UL #endif class MicroNMEALocationProvider : public LocationProvider { @@ -22,6 +31,7 @@ class MicroNMEALocationProvider : public LocationProvider { uint32_t _gpsPeriodSeconds = 0; unsigned long _nextAcquisition = 0; unsigned long _acquisitionStarted = 0; + unsigned long _firstFixInWindow = 0; bool _acquiringPeriodically = false; static const unsigned long TIME_SYNC_INTERVAL = 1800000; @@ -54,6 +64,7 @@ class MicroNMEALocationProvider : public LocationProvider { _driver->reset(); _acquiringPeriodically = true; _acquisitionStarted = millis(); + _firstFixInWindow = 0; } void finishPeriodicAcquisition() { @@ -122,11 +133,12 @@ public: void begin() override { _begin_calls++; _driver->begin(); - if (_gpsPeriodSeconds > 0 && _driver->isEnabled()) { + if (_gpsPeriodSeconds > 0 && _driver->isActive()) { nmea.clear(); time_valid = 0; _acquiringPeriodically = true; _acquisitionStarted = millis(); + _firstFixInWindow = 0; } } @@ -140,8 +152,8 @@ public: _driver->stop(); } - bool isEnabled() override { - return _driver->isEnabled(); + bool isActive() override { + return _driver->isActive(); } bool hasHardwareEnableState() const override { @@ -249,7 +261,13 @@ public: if (parsed && nmea.isValid() && (strcmp(messageId, "GGA") == 0 || strcmp(messageId, "RMC") == 0)) { saveFix(); - if (_acquiringPeriodically) finishPeriodicAcquisition(); + if (_acquiringPeriodically) { + if (_firstFixInWindow == 0) _firstFixInWindow = millis(); + if (nmea.getNumSatellites() >= GPS_MIN_SATS_FOR_FIX || + (uint32_t)(millis() - _firstFixInWindow) >= GPS_FIX_SETTLE_MS) { + finishPeriodicAcquisition(); + } + } } } else { _nmea_checksum_bad++; @@ -257,7 +275,8 @@ public: } } - if (_acquiringPeriodically && + // no timeout until a first fix has been obtained (cold start can be long) + if (_acquiringPeriodically && _lastFix.valid && (uint32_t)(millis() - _acquisitionStarted) >= GPS_PERIODIC_ACQUISITION_TIMEOUT_MS) { finishPeriodicAcquisition(); } @@ -277,7 +296,7 @@ public: snprintf(out, out_size, "en:%u ub:%lu ua:%s ok:%lu bad:%lu na:%s sat:%ld fix:%u fa:%s bc:%lu sc:%lu", - isEnabled() ? 1U : 0U, + isActive() ? 1U : 0U, (unsigned long)_uart_bytes, uart_age, (unsigned long)_nmea_checksum_ok, diff --git a/src/helpers/sensors/NmeaGpsDriver.h b/src/helpers/sensors/NmeaGpsDriver.h index f9ea5124..abecb817 100644 --- a/src/helpers/sensors/NmeaGpsDriver.h +++ b/src/helpers/sensors/NmeaGpsDriver.h @@ -183,7 +183,7 @@ public: stopHardware(); } - bool isEnabled() const override { + bool isActive() const override { return _started && isHardwareEnabled(); } diff --git a/src/helpers/sensors/RakGpsDriver.h b/src/helpers/sensors/RakGpsDriver.h index fb4b772b..b3754852 100644 --- a/src/helpers/sensors/RakGpsDriver.h +++ b/src/helpers/sensors/RakGpsDriver.h @@ -77,8 +77,8 @@ public: _serialDriver.stop(); } - bool isEnabled() const override { - return _usingRak12500 ? true : _serialDriver.isEnabled(); + bool isActive() const override { + return _usingRak12500 ? true : _serialDriver.isActive(); } bool detect(uint32_t) override { diff --git a/src/helpers/sensors/RakLocationProvider.h b/src/helpers/sensors/RakLocationProvider.h index db0b957b..57ceb5e9 100644 --- a/src/helpers/sensors/RakLocationProvider.h +++ b/src/helpers/sensors/RakLocationProvider.h @@ -137,7 +137,7 @@ public: _driver.stop(); _acquiringPeriodically = false; _nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL; - } else if (_gpsPeriodSeconds > 0 && _acquiringPeriodically && + } else if (_gpsPeriodSeconds > 0 && _acquiringPeriodically && _lastFix.valid && (uint32_t)(millis() - _acquisitionStarted) >= GPS_PERIODIC_ACQUISITION_TIMEOUT_MS) { _driver.stop(); @@ -150,8 +150,8 @@ public: } } - bool isEnabled() override { - return _driver.isEnabled(); + bool isActive() override { + return _driver.isActive(); } void setGpsPeriod(uint32_t seconds) override { @@ -163,4 +163,9 @@ public: uint32_t getGpsPeriod() const override { return _gpsPeriodSeconds; } + + void setGpsOn(bool on) override { + if (_driver.usesRak12500()) LocationProvider::setGpsOn(on); + else { _gpsOn = on; _nmea.setGpsOn(on); } + } }; From a0c5854b591ccef21061009c05932aa334722978 Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Tue, 3 Nov 2026 21:10:01 -0400 Subject: [PATCH 348/381] rak_gps: simplify the rak driver, which now only handles i2c, for nmea use nmea driver directly --- .../{RakGpsDriver.h => RakI2cGpsDriver.h} | 50 +++++--------- src/helpers/sensors/RakLocationProvider.h | 67 ++++++++++++------- variants/gat562_30s_mesh_kit/target.cpp | 2 +- variants/rak3401/target.cpp | 2 +- variants/rak4631/target.cpp | 2 +- 5 files changed, 61 insertions(+), 62 deletions(-) rename src/helpers/sensors/{RakGpsDriver.h => RakI2cGpsDriver.h} (65%) diff --git a/src/helpers/sensors/RakGpsDriver.h b/src/helpers/sensors/RakI2cGpsDriver.h similarity index 65% rename from src/helpers/sensors/RakGpsDriver.h rename to src/helpers/sensors/RakI2cGpsDriver.h index b3754852..ac76e069 100644 --- a/src/helpers/sensors/RakGpsDriver.h +++ b/src/helpers/sensors/RakI2cGpsDriver.h @@ -1,16 +1,16 @@ #pragma once -#include "NmeaGpsDriver.h" +#include "GpsDriver.h" #include <SparkFun_u-blox_GNSS_Arduino_Library.h> -class RakGpsDriver : public GpsDriver { - NmeaGpsDriver _serialDriver; +// Driver for the RAK12500 (u-blox, I2C). Serial NMEA modules are handled by NmeaGpsDriver. +class RakI2cGpsDriver : public GpsDriver { TwoWire& _wire; SFE_UBLOX_GNSS _gnss; uint8_t _powerPin = 0; - bool _usingRak12500 = false; bool _detected = false; + bool _started = false; bool probeRak12500(uint8_t powerPin) { #if defined(ETHERNET_ENABLED) && defined(RAK_BOARD) @@ -37,7 +37,6 @@ class RakGpsDriver : public GpsDriver { _gnss.setMeasurementRate(1000); _gnss.saveConfigSelective(VAL_CFG_SUBSEC_IOPORT); _powerPin = powerPin; - _usingRak12500 = true; return true; } @@ -48,62 +47,47 @@ class RakGpsDriver : public GpsDriver { } public: - RakGpsDriver(HardwareSerial& serial = Serial1, TwoWire& wire = Wire) - : _serialDriver(serial), _wire(wire) {} + RakI2cGpsDriver(TwoWire& wire = Wire) : _wire(wire) {} void begin() override { - if (_usingRak12500) { + if (!_detected) return; #ifndef RAK_3401 - pinMode(_powerPin, OUTPUT); - digitalWrite(_powerPin, HIGH); + pinMode(_powerPin, OUTPUT); + digitalWrite(_powerPin, HIGH); #endif - return; - } - _serialDriver.begin(); + _started = true; } - void reset() override { - if (!_usingRak12500) _serialDriver.reset(); - } + void reset() override {} void stop() override { - if (_usingRak12500) { + if (_detected) { #ifndef RAK_3401 pinMode(_powerPin, OUTPUT); digitalWrite(_powerPin, LOW); #endif - return; } - _serialDriver.stop(); + _started = false; } bool isActive() const override { - return _usingRak12500 ? true : _serialDriver.isActive(); + return _started; } + // Probes the I2C module on the possible power pins; the module is left powered. bool detect(uint32_t) override { if (_detected) return true; - _serialDriver.begin(); if (probeRak12500(WB_IO2) || probeRak12500(WB_IO4) || probeRak12500(WB_IO5)) { _detected = true; - return true; + _started = true; } - - if (_serialDriver.detect(0)) { - _detected = true; - return true; - } - - _serialDriver.stop(); - return false; + return _detected; } - bool usesRak12500() const { return _usingRak12500; } bool isDetected() const { return _detected; } - NmeaGpsDriver& nmeaDriver() { return _serialDriver; } - bool hasFix() { return _usingRak12500 && _gnss.getGnssFixOk(8); } + bool hasFix() { return _started && _gnss.getGnssFixOk(8); } long getLatitude() { return _gnss.getLatitude(2) / 10; } long getLongitude() { return _gnss.getLongitude(2) / 10; } long getAltitude() { return _gnss.getAltitude(2); } diff --git a/src/helpers/sensors/RakLocationProvider.h b/src/helpers/sensors/RakLocationProvider.h index 57ceb5e9..d2c755e6 100644 --- a/src/helpers/sensors/RakLocationProvider.h +++ b/src/helpers/sensors/RakLocationProvider.h @@ -1,11 +1,15 @@ #pragma once #include "MicroNMEALocationProvider.h" -#include "RakGpsDriver.h" +#include "NmeaGpsDriver.h" +#include "RakI2cGpsDriver.h" class RakLocationProvider : public LocationProvider { - RakGpsDriver& _driver; + RakI2cGpsDriver& _driver; // RAK12500 (I2C) + NmeaGpsDriver _nmeaDriver; // serial NMEA module MicroNMEALocationProvider _nmea; + bool _detected = false; + bool _useI2c = false; uint32_t _gpsPeriodSeconds = 0; unsigned long _nextAcquisition = 0; unsigned long _acquisitionStarted = 0; @@ -24,73 +28,74 @@ class RakLocationProvider : public LocationProvider { } public: - RakLocationProvider(RakGpsDriver& driver, mesh::RTCClock* clock = nullptr) - : _driver(driver), _nmea(driver.nmeaDriver(), clock) {} + RakLocationProvider(RakI2cGpsDriver& driver, mesh::RTCClock* clock = nullptr, + HardwareSerial& serial = Serial1) + : _driver(driver), _nmeaDriver(serial), _nmea(_nmeaDriver, clock) {} void syncTime() override { LocationProvider::syncTime(); - if (!_driver.usesRak12500()) _nmea.syncTime(); + if (!_useI2c) _nmea.syncTime(); } long getLatitude() override { - return _driver.usesRak12500() ? _lastFix.latitude : _nmea.getLatitude(); + return _useI2c ? _lastFix.latitude : _nmea.getLatitude(); } long getLongitude() override { - return _driver.usesRak12500() ? _lastFix.longitude : _nmea.getLongitude(); + return _useI2c ? _lastFix.longitude : _nmea.getLongitude(); } long getAltitude() override { - return _driver.usesRak12500() ? _lastFix.altitude : _nmea.getAltitude(); + return _useI2c ? _lastFix.altitude : _nmea.getAltitude(); } long satellitesCount() override { - return _driver.usesRak12500() ? _lastFix.satellites : _nmea.satellitesCount(); + return _useI2c ? _lastFix.satellites : _nmea.satellitesCount(); } bool isValid() override { - return _driver.usesRak12500() ? _driver.hasFix() : _nmea.isValid(); + return _useI2c ? _driver.hasFix() : _nmea.isValid(); } LastFix getLastFix() const override { - return _driver.usesRak12500() ? _lastFix : _nmea.getLastFix(); + return _useI2c ? _lastFix : _nmea.getLastFix(); } long getTimestamp() override { - return _driver.usesRak12500() ? _lastFix.timestamp : _nmea.getTimestamp(); + return _useI2c ? _lastFix.timestamp : _nmea.getTimestamp(); } void sendSentence(const char* sentence) override { - if (!_driver.usesRak12500()) _nmea.sendSentence(sentence); + if (!_useI2c) _nmea.sendSentence(sentence); } bool waitFor(const char* prefix, uint32_t timeout_ms) override { - return _driver.usesRak12500() ? false : _nmea.waitFor(prefix, timeout_ms); + return _useI2c ? false : _nmea.waitFor(prefix, timeout_ms); } void drain() override { - if (!_driver.usesRak12500()) _nmea.drain(); + if (!_useI2c) _nmea.drain(); } void reset() override { - _driver.reset(); + if (!_useI2c) _nmea.reset(); } void begin() override { - if (_driver.isDetected() && _driver.usesRak12500()) { + if (_detected && _useI2c) { _driver.begin(); _acquiringPeriodically = _gpsPeriodSeconds > 0; _acquisitionStarted = millis(); - } else if (_driver.isDetected()) { + } else if (_detected) { _nmea.begin(); } else { - _driver.begin(); + _nmeaDriver.begin(); } } void stop() override { _acquiringPeriodically = false; - if (_driver.usesRak12500()) { + if (_useI2c) { _driver.stop(); } else { _nmea.stop(); @@ -98,9 +103,19 @@ public: } bool detect(uint32_t timeout_ms) override { - if (!_driver.detect(timeout_ms)) return false; + if (_detected) return true; - if (_driver.usesRak12500()) { + // the serial module is started first, then the I2C module is probed + _nmeaDriver.begin(); + if (_driver.detect(timeout_ms)) { + _useI2c = true; + } else if (!_nmeaDriver.detect(0)) { + _nmeaDriver.stop(); + return false; + } + _detected = true; + + if (_useI2c) { _acquiringPeriodically = _gpsPeriodSeconds > 0; _acquisitionStarted = millis(); } else { @@ -119,7 +134,7 @@ public: } void loop() override { - if (_driver.usesRak12500()) { + if (_useI2c) { if (_gpsOn) { if (_gpsPeriodSeconds > 0) { if (!_acquiringPeriodically && @@ -151,13 +166,13 @@ public: } bool isActive() override { - return _driver.isActive(); + return _useI2c ? _driver.isActive() : _nmea.isActive(); } void setGpsPeriod(uint32_t seconds) override { _gpsPeriodSeconds = seconds; _nextAcquisition = millis(); - if (!_driver.usesRak12500()) _nmea.setGpsPeriod(seconds); + if (!_useI2c) _nmea.setGpsPeriod(seconds); } uint32_t getGpsPeriod() const override { @@ -165,7 +180,7 @@ public: } void setGpsOn(bool on) override { - if (_driver.usesRak12500()) LocationProvider::setGpsOn(on); + if (_useI2c) LocationProvider::setGpsOn(on); else { _gpsOn = on; _nmea.setGpsOn(on); } } }; diff --git a/variants/gat562_30s_mesh_kit/target.cpp b/variants/gat562_30s_mesh_kit/target.cpp index ba81a690..96e38a79 100644 --- a/variants/gat562_30s_mesh_kit/target.cpp +++ b/variants/gat562_30s_mesh_kit/target.cpp @@ -27,7 +27,7 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/RakLocationProvider.h> - RakGpsDriver gps_driver; + RakI2cGpsDriver gps_driver; RakLocationProvider location(gps_driver, &rtc_clock); EnvironmentSensorManager sensors(location); #else diff --git a/variants/rak3401/target.cpp b/variants/rak3401/target.cpp index 26501977..58c0e1d7 100644 --- a/variants/rak3401/target.cpp +++ b/variants/rak3401/target.cpp @@ -26,7 +26,7 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/RakLocationProvider.h> - RakGpsDriver gps_driver; + RakI2cGpsDriver gps_driver; RakLocationProvider location(gps_driver, &rtc_clock); EnvironmentSensorManager sensors(location); #else diff --git a/variants/rak4631/target.cpp b/variants/rak4631/target.cpp index 06ccd23d..158de2b5 100644 --- a/variants/rak4631/target.cpp +++ b/variants/rak4631/target.cpp @@ -26,7 +26,7 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/RakLocationProvider.h> - RakGpsDriver gps_driver; + RakI2cGpsDriver gps_driver; RakLocationProvider location(gps_driver, &rtc_clock); EnvironmentSensorManager sensors(location); #else From 53037037507c64c72b02c74d75a85a2219166f0b Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Tue, 3 Nov 2026 21:29:21 -0400 Subject: [PATCH 349/381] gps: adapt ui-new and the sensor managers --- examples/companion_radio/ui-new/UITask.cpp | 51 ++++++++++++++++--- variants/heltec_mesh_solar/target.cpp | 2 +- variants/heltec_tracker/target.cpp | 2 +- variants/meshadventurer/target.cpp | 4 +- variants/meshtracker_x1/target.cpp | 2 +- variants/nano_g2_ultra/NanoG2UltraGpsDriver.h | 2 +- variants/nano_g2_ultra/target.cpp | 4 +- variants/t1000-e/target.cpp | 2 +- variants/thinknode_m1/target.cpp | 2 +- 9 files changed, 53 insertions(+), 18 deletions(-) diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index a1400669..6b6af33e 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -86,6 +86,30 @@ public: } }; +#if ENV_INCLUDE_GPS == 1 +// exact period with the largest unit that divides it: "30s", "5m", "2h" +static void formatGpsPeriod(char* buf, size_t size, uint32_t seconds) { + if (seconds % 3600 == 0) { + snprintf(buf, size, "%luh", (unsigned long)(seconds / 3600)); + } else if (seconds % 60 == 0) { + snprintf(buf, size, "%lum", (unsigned long)(seconds / 60)); + } else { + snprintf(buf, size, "%lus", (unsigned long)seconds); + } +} + +// age of the last fix, rounded down to a single unit: "45s", "12m", "3h" +static void formatFixAge(char* buf, size_t size, uint32_t seconds) { + if (seconds < 60) { + snprintf(buf, size, "%lus", (unsigned long)seconds); + } else if (seconds < 3600) { + snprintf(buf, size, "%lum", (unsigned long)(seconds / 60)); + } else { + snprintf(buf, size, "%luh", (unsigned long)(seconds / 3600)); + } +} +#endif + class HomeScreen : public UIScreen { enum HomePage { FIRST, @@ -393,14 +417,26 @@ public: int y = 18; bool gps_state = _task->getGPSState(); bool hw_gps_state = nmea != NULL && nmea->isHardwareEnabled(); - if (nmea != NULL && nmea->hasHardwareEnableState()) { - if (gps_state != hw_gps_state) { - strcpy(buf, gps_state ? "gps off(hw)" : "gps off(sw)"); - } else { - strcpy(buf, gps_state ? "gps on" : "gps off"); + uint32_t period = nmea != NULL ? nmea->getGpsPeriod() : 0; + char fix_buf[12] = ""; + if (nmea != NULL) { + uint32_t fix_age = nmea->getLastFixAge(); + if (fix_age == UINT32_MAX) { + strcpy(fix_buf, "no fix"); + } else { + formatFixAge(fix_buf, sizeof(fix_buf), fix_age); + } } + if (nmea != NULL && nmea->hasHardwareEnableState() && gps_state != hw_gps_state) { + strcpy(buf, gps_state ? "gps off(hw)" : "gps off(sw)"); + } else if (!gps_state) { + strcpy(buf, "gps off"); + } else if (period == 0) { + strcpy(buf, "gps on"); } else { - strcpy(buf, gps_state ? "gps on" : "gps off"); + char per[12]; + formatGpsPeriod(per, sizeof(per), period); + snprintf(buf, sizeof(buf), "%s (%s)", nmea != NULL && nmea->isActive() ? "active" : "sleep", per); } display.setColor(UIColor::primary_txt); display.drawTextLeftAlign(0, y, buf); @@ -410,8 +446,7 @@ public: display.drawTextLeftAlign(0, y, "Can't access GPS"); } else { display.setColor(UIColor::primary_txt); - strcpy(buf, nmea->isValid()?"fix":"no fix"); - display.drawTextRightAlign(display.width()-1, y, buf); + display.drawTextRightAlign(display.width()-1, y, fix_buf); y = y + 12; display.setColor(UIColor::secondary_txt); display.drawTextLeftAlign(0, y, "sat"); diff --git a/variants/heltec_mesh_solar/target.cpp b/variants/heltec_mesh_solar/target.cpp index 9468f8fc..9e7fb04d 100644 --- a/variants/heltec_mesh_solar/target.cpp +++ b/variants/heltec_mesh_solar/target.cpp @@ -66,7 +66,7 @@ void SolarSensorManager::loop() { _location->loop(); if (millis() > next_gps_update) { - if (_location->isValid()) { + if (_location->isGpsOn() && _location->hasValidFix()) { node_lat = ((double)_location->getLatitude())/1000000.; node_lon = ((double)_location->getLongitude())/1000000.; node_altitude = ((double)_location->getAltitude()) / 1000.0; diff --git a/variants/heltec_tracker/target.cpp b/variants/heltec_tracker/target.cpp index 5903f659..041cb2b8 100644 --- a/variants/heltec_tracker/target.cpp +++ b/variants/heltec_tracker/target.cpp @@ -82,7 +82,7 @@ void HWTSensorManager::loop() { _location->loop(); if (millis() > next_gps_update) { - if (_location->isEnabled() && _location->isValid()) { + if (_location->isGpsOn() && _location->hasValidFix()) { node_lat = ((double)_location->getLatitude())/1000000.; node_lon = ((double)_location->getLongitude())/1000000.; node_altitude = ((double)_location->getAltitude()) / 1000.0; diff --git a/variants/meshadventurer/target.cpp b/variants/meshadventurer/target.cpp index faf2e30e..827e23b7 100644 --- a/variants/meshadventurer/target.cpp +++ b/variants/meshadventurer/target.cpp @@ -64,8 +64,8 @@ bool MASensorManager::querySensors(uint8_t requester_permissions, CayenneLPP& te void MASensorManager::loop() { static long next_gps_update = 0; _location->loop(); - if(millis() > next_gps_update && _location->isEnabled()) { - if(_location->isValid()) { + if(millis() > next_gps_update && _location->isGpsOn()) { + if(_location->hasValidFix()) { node_lat = ((double)_location->getLatitude()) / 1000000.; node_lon = ((double)_location->getLongitude()) / 1000000.; node_altitude = ((double)_location->getAltitude()) / 1000.0; diff --git a/variants/meshtracker_x1/target.cpp b/variants/meshtracker_x1/target.cpp index 2dee0ebd..84e0870e 100644 --- a/variants/meshtracker_x1/target.cpp +++ b/variants/meshtracker_x1/target.cpp @@ -70,7 +70,7 @@ void MeshTrackerX1SensorManager::loop() { _nmea->loop(); if (millis() > next_gps_update) { - if (_nmea->isEnabled() && _nmea->isValid()) { + if (_nmea->isGpsOn() && _nmea->hasValidFix()) { node_lat = ((double)_nmea->getLatitude())/1000000.; node_lon = ((double)_nmea->getLongitude())/1000000.; node_altitude = ((double)_nmea->getAltitude()) / 1000.0; diff --git a/variants/nano_g2_ultra/NanoG2UltraGpsDriver.h b/variants/nano_g2_ultra/NanoG2UltraGpsDriver.h index 3772084b..7e3bd109 100644 --- a/variants/nano_g2_ultra/NanoG2UltraGpsDriver.h +++ b/variants/nano_g2_ultra/NanoG2UltraGpsDriver.h @@ -10,7 +10,7 @@ public: } void begin() override { - if (isEnabled()) return; + if (isActive()) return; digitalWrite(PIN_GPS_STANDBY, HIGH); NmeaGpsDriver::begin(); diff --git a/variants/nano_g2_ultra/target.cpp b/variants/nano_g2_ultra/target.cpp index ee258f2d..fedc48e7 100644 --- a/variants/nano_g2_ultra/target.cpp +++ b/variants/nano_g2_ultra/target.cpp @@ -62,14 +62,14 @@ bool NanoG2UltraSensorManager::querySensors(uint8_t requester_permissions, Cayen void NanoG2UltraSensorManager::loop() { static long next_gps_update = 0; - if (!_location->isEnabled()) { + if (!_location->isGpsOn()) { return; // GPS is not active, skip further processing } _location->loop(); if (millis() > next_gps_update) { - if (_location->isEnabled() && _location->isValid()) { + if (_location->isGpsOn() && _location->hasValidFix()) { node_lat = ((double)_location->getLatitude()) / 1000000.; node_lon = ((double)_location->getLongitude()) / 1000000.; node_altitude = ((double)_location->getAltitude()) / 1000.0; diff --git a/variants/t1000-e/target.cpp b/variants/t1000-e/target.cpp index b96d01f8..609c32bc 100644 --- a/variants/t1000-e/target.cpp +++ b/variants/t1000-e/target.cpp @@ -113,7 +113,7 @@ void T1000SensorManager::loop() { _nmea->loop(); if (millis() > next_gps_update) { - if (_nmea->isEnabled() && _nmea->isValid()) { + if (_nmea->isGpsOn() && _nmea->hasValidFix()) { node_lat = ((double)_nmea->getLatitude())/1000000.; node_lon = ((double)_nmea->getLongitude())/1000000.; node_altitude = ((double)_nmea->getAltitude()) / 1000.0; diff --git a/variants/thinknode_m1/target.cpp b/variants/thinknode_m1/target.cpp index 78f5a88e..4183c514 100644 --- a/variants/thinknode_m1/target.cpp +++ b/variants/thinknode_m1/target.cpp @@ -58,7 +58,7 @@ void ThinkNodeM1SensorManager::loop() { _location->loop(); if (millis() > next_gps_update) { - if (_location->isEnabled() && _location->isValid()) { + if (_location->isGpsOn() && _location->hasValidFix()) { node_lat = ((double)_location->getLatitude())/1000000.; node_lon = ((double)_location->getLongitude())/1000000.; node_altitude = ((double)_location->getAltitude()) / 1000.0; From 47959b8960701209bf5012f77c43444eb93f9821 Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Wed, 4 Nov 2026 09:02:38 -0400 Subject: [PATCH 350/381] gps: fix_stats command --- docs/cli_commands.md | 8 +++++ docs/companion_cli.md | 8 +++++ src/helpers/CommonGpsPrefs.cpp | 32 +++++++++++++++-- src/helpers/sensors/LocationProvider.h | 20 +++++++++++ .../sensors/MicroNMEALocationProvider.h | 35 ++++++++++++++----- src/helpers/sensors/RakLocationProvider.h | 13 ++++++- 6 files changed, 105 insertions(+), 11 deletions(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index eb8c6b20..d7b8d5d0 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1044,6 +1044,14 @@ region save --- +#### View GPS time to first fix statistics +**Usage:** +- `gps fix_stats` + +**Output:** `ttf:<last>/<max> ok:<n> miss:<n>`: last and maximum time between a start of the GPS and its first valid fix, then the last count of consecutive starts with a fix (`ok`) or without one (`miss`). + +--- + #### View GPS diagnostics **Usage:** - `gps diag` diff --git a/docs/companion_cli.md b/docs/companion_cli.md index 24843269..0b3a27df 100644 --- a/docs/companion_cli.md +++ b/docs/companion_cli.md @@ -165,6 +165,14 @@ Radio parameters are common to all roles and handled by `CommonRadioPrefs`. --- +#### View GPS time to first fix statistics +**Usage:** +- `gps fix_stats` + +**Output:** `ttf:<last>/<max> ok:<n> miss:<n>`: last and maximum time between a start of the GPS and its first valid fix, then the last count of consecutive starts with a fix (`ok`) or without one (`miss`). + +--- + #### View GPS diagnostics **Usage:** - `gps diag` diff --git a/src/helpers/CommonGpsPrefs.cpp b/src/helpers/CommonGpsPrefs.cpp index e08878a6..c4936d4f 100644 --- a/src/helpers/CommonGpsPrefs.cpp +++ b/src/helpers/CommonGpsPrefs.cpp @@ -25,6 +25,17 @@ bool CommonGpsPrefs::apply(SensorManager& sensors) const { return true; } +// single unit, rounded down: "45s", "12m", "3h" +static void formatDuration(char* buf, size_t size, uint32_t seconds) { + if (seconds < 60) { + snprintf(buf, size, "%lus", (unsigned long)seconds); + } else if (seconds < 3600) { + snprintf(buf, size, "%lum", (unsigned long)(seconds / 60)); + } else { + snprintf(buf, size, "%luh", (unsigned long)(seconds / 3600)); + } +} + bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, char* reply) { if (strcmp(command, "gps") == 0) { LocationProvider* location = sensors.getLocationProvider(); @@ -50,8 +61,9 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, } char fix[32]; if (location->hasValidFix()) { - snprintf(fix, sizeof(fix), "%ld sats %lus ago", - location->satellitesCount(), (unsigned long)location->getLastFixAge()); + char age[12]; + formatDuration(age, sizeof(age), location->getLastFixAge()); + snprintf(fix, sizeof(fix), "%ld sats %s ago", location->satellitesCount(), age); } else { strcpy(fix, "no fix"); } @@ -134,6 +146,22 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, } return true; } + if (strcmp(command, "gps fix_stats") == 0) { + LocationProvider* location = sensors.getLocationProvider(); + if (location == nullptr) { + strcpy(reply, "gps provider not found"); + } else { + const LocationProvider::FixStats s = location->getFixStats(); + char last[12] = "-", max[12] = "-"; + if (s.maxTtffMs > 0) { + formatDuration(last, sizeof(last), (s.lastTtffMs + 500) / 1000); + formatDuration(max, sizeof(max), (s.maxTtffMs + 500) / 1000); + } + snprintf(reply, 160, "ttf:%s/%s ok:%lu miss:%lu", last, max, + (unsigned long)s.consecutiveFixes, (unsigned long)s.consecutiveMisses); + } + return true; + } if (strcmp(command, "gps diag") == 0) { LocationProvider* location = sensors.getLocationProvider(); if (location == nullptr) { diff --git a/src/helpers/sensors/LocationProvider.h b/src/helpers/sensors/LocationProvider.h index 5bb6ec6a..3d7abd7a 100644 --- a/src/helpers/sensors/LocationProvider.h +++ b/src/helpers/sensors/LocationProvider.h @@ -18,10 +18,29 @@ public: unsigned long acquiredAt = 0; // millis() when the fix was stored }; + struct FixStats { + uint32_t lastTtffMs = 0; //time to first fix in ms + uint32_t maxTtffMs = 0; + uint32_t consecutiveFixes = 0; + uint32_t consecutiveMisses = 0; + }; + protected: bool _time_sync_needed = true; bool _gpsOn = false; LastFix _lastFix; + FixStats _fixStats; + + void fixStatsFix(uint32_t ttffMs) { + _fixStats.lastTtffMs = ttffMs; + if (ttffMs > _fixStats.maxTtffMs) _fixStats.maxTtffMs = ttffMs; + _fixStats.consecutiveFixes++; + _fixStats.consecutiveMisses = 0; + } + void fixStatsMiss() { + _fixStats.consecutiveMisses++; + _fixStats.consecutiveFixes = 0; + } public: virtual ~LocationProvider() = default; @@ -35,6 +54,7 @@ public: virtual bool isValid() = 0; // current fix is valid virtual bool hasValidFix() { return getLastFix().valid || isValid(); } // a valid fix was obtained at some point virtual LastFix getLastFix() const { return _lastFix; } // snapshot of the last valid fix + virtual FixStats getFixStats() const { return _fixStats; } virtual long getTimestamp() = 0; virtual void sendSentence(const char * sentence); virtual bool waitFor(const char* prefix, uint32_t timeout_ms) { return false; } diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index b07f486b..3c2adc6e 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -68,21 +68,30 @@ class MicroNMEALocationProvider : public LocationProvider { } void finishPeriodicAcquisition() { + if (_firstFixInWindow == 0) fixStatsMiss(); _driver->stop(); _acquiringPeriodically = false; _nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL; } - void saveFix() { + bool saveFix() { + // only store a fix when the snapshot is coherent (sats > 0). + // Returns true if the fix was stored. + if (nmea.getNumSatellites() == 0) return false; + LastFix fix; fix.latitude = nmea.getLatitude(); fix.longitude = nmea.getLongitude(); - nmea.getAltitude(fix.altitude); + // altitude comes from GGA only: keep the previous one if not available + if (!nmea.getAltitude(fix.altitude)) { + fix.altitude = _lastFix.valid ? _lastFix.altitude : 0; + } fix.satellites = nmea.getNumSatellites(); fix.timestamp = getTimestamp(); fix.acquiredAt = millis(); fix.valid = true; _lastFix = fix; + return true; } void updateTime() { @@ -132,7 +141,12 @@ public: void begin() override { _begin_calls++; + const bool wasActive = _driver->isActive(); _driver->begin(); + if (!wasActive) { + _acquisitionStarted = millis(); + _firstFixInWindow = 0; + } if (_gpsPeriodSeconds > 0 && _driver->isActive()) { nmea.clear(); time_valid = 0; @@ -183,20 +197,22 @@ public: LocationProvider::syncTime(); } + // Position, altitude and satellite count describe the last saved fix + // Before the first saved fix, fall back to the live parser state. long getLatitude() override { - return nmea.isValid() ? nmea.getLatitude() : _lastFix.latitude; + return _lastFix.valid ? _lastFix.latitude : nmea.getLatitude(); } long getLongitude() override { - return nmea.isValid() ? nmea.getLongitude() : _lastFix.longitude; + return _lastFix.valid ? _lastFix.longitude : nmea.getLongitude(); } long getAltitude() override { - if (!nmea.isValid()) return _lastFix.altitude; + if (_lastFix.valid) return _lastFix.altitude; long alt = 0; nmea.getAltitude(alt); return alt; } long satellitesCount() override { - return nmea.isValid() ? nmea.getNumSatellites() : _lastFix.satellites; + return _lastFix.valid ? _lastFix.satellites : nmea.getNumSatellites(); } bool isValid() override { return nmea.isValid(); } @@ -260,9 +276,12 @@ public: const char* messageId = nmea.getMessageID(); if (parsed && nmea.isValid() && (strcmp(messageId, "GGA") == 0 || strcmp(messageId, "RMC") == 0)) { - saveFix(); + if (!saveFix()) continue; // incoherent snapshot + if (_firstFixInWindow == 0) { + _firstFixInWindow = millis(); + fixStatsFix((uint32_t)(_firstFixInWindow - _acquisitionStarted)); + } if (_acquiringPeriodically) { - if (_firstFixInWindow == 0) _firstFixInWindow = millis(); if (nmea.getNumSatellites() >= GPS_MIN_SATS_FOR_FIX || (uint32_t)(millis() - _firstFixInWindow) >= GPS_FIX_SETTLE_MS) { finishPeriodicAcquisition(); diff --git a/src/helpers/sensors/RakLocationProvider.h b/src/helpers/sensors/RakLocationProvider.h index d2c755e6..7deddf43 100644 --- a/src/helpers/sensors/RakLocationProvider.h +++ b/src/helpers/sensors/RakLocationProvider.h @@ -57,6 +57,10 @@ public: return _useI2c ? _driver.hasFix() : _nmea.isValid(); } + FixStats getFixStats() const override { + return _useI2c ? _fixStats : _nmea.getFixStats(); + } + LastFix getLastFix() const override { return _useI2c ? _lastFix : _nmea.getLastFix(); } @@ -146,7 +150,13 @@ public: } const bool hasCurrentFix = _driver.hasFix(); - if (hasCurrentFix) saveRak12500Fix(); + if (hasCurrentFix) { + // first fix since the start + if (!_lastFix.valid || (long)(_lastFix.acquiredAt - _acquisitionStarted) < 0) { + fixStatsFix((uint32_t)(millis() - _acquisitionStarted)); + } + saveRak12500Fix(); + } if (_gpsPeriodSeconds > 0 && _acquiringPeriodically && hasCurrentFix) { _driver.stop(); @@ -155,6 +165,7 @@ public: } else if (_gpsPeriodSeconds > 0 && _acquiringPeriodically && _lastFix.valid && (uint32_t)(millis() - _acquisitionStarted) >= GPS_PERIODIC_ACQUISITION_TIMEOUT_MS) { + fixStatsMiss(); _driver.stop(); _acquiringPeriodically = false; _nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL; From bd21096ce0282851958dcef6d4422d56094df373 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?N=C3=ADckolas=20Goline?= <nickolas.goline+github@gmail.com> Date: Wed, 4 Nov 2026 13:36:33 -0300 Subject: [PATCH 351/381] muzi_base: fix GPS UART pins and re-enable ATGM336H NMEA output The refactor no longer calls Serial1.setPins() on nRF52, so Serial1 uses PIN_SERIAL1_RX/TX directly. Those were swapped (the GPS transmits on P0.20), so no data was received. Fix them and define PIN_GPS_TX/RX by the gps module's side, as other variants do. The ATGM336H keeps its NMEA output config across power cycles, and other firmware may leave every sentence disabled. Re-enable GGA + RMC after each power-up. --- variants/muzi_base/target.cpp | 12 ++++++++++++ variants/muzi_base/target.h | 4 ++++ variants/muzi_base/variant.h | 8 ++++---- 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/variants/muzi_base/target.cpp b/variants/muzi_base/target.cpp index b65bafa1..6653ada1 100644 --- a/variants/muzi_base/target.cpp +++ b/variants/muzi_base/target.cpp @@ -50,6 +50,18 @@ void MuziBaseSensorManager::loop() { _pwr_last_click = t; if (++_pwr_clicks >= USER_BTN_POWER_OFF_CLICKS) muziPowerOff(); } +#if ENV_INCLUDE_GPS + // the ATGM336H keeps its nmea output config across power cycles (backup + // supply), and other firmware may have turned every sentence off. re-enable + // GGA + RMC after each power-up, once the module has booted. + bool gps_on = _location->isActive(); + if (gps_on && !_gps_was_active) _gps_cfg_at = millis() + 1000; + _gps_was_active = gps_on; + if (_gps_cfg_at && gps_on && (long)(millis() - _gps_cfg_at) > 0) { + _gps_cfg_at = 0; + _location->sendSentence("$PCAS03,1,0,0,0,1,0,0,0,0,0,,,0,0"); + } +#endif EnvironmentSensorManager::loop(); } diff --git a/variants/muzi_base/target.h b/variants/muzi_base/target.h index 3f7dcbf5..0c143e1b 100644 --- a/variants/muzi_base/target.h +++ b/variants/muzi_base/target.h @@ -42,6 +42,10 @@ extern AutoDiscoverRTCClock rtc_clock; class MuziBaseSensorManager : public EnvironmentSensorManager { unsigned long _pwr_last_click = 0; uint8_t _pwr_clicks = 0; +#if ENV_INCLUDE_GPS + unsigned long _gps_cfg_at = 0; + bool _gps_was_active = false; +#endif public: #if ENV_INCLUDE_GPS MuziBaseSensorManager(LocationProvider& location) : EnvironmentSensorManager(location) {} diff --git a/variants/muzi_base/variant.h b/variants/muzi_base/variant.h index 0c1245a8..d42804f6 100644 --- a/variants/muzi_base/variant.h +++ b/variants/muzi_base/variant.h @@ -54,8 +54,8 @@ static const uint8_t AREF = (PIN_AREF); // not used //////////////////////////////////////////////////////////////////////////////// // UART pin definition -#define PIN_SERIAL1_RX (19) // P0.19 used for GPS RX -#define PIN_SERIAL1_TX (20) // P0.20 used for GPS TX +#define PIN_SERIAL1_RX (20) // P0.20, data from the gps +#define PIN_SERIAL1_TX (19) // P0.19, data to the gps //////////////////////////////////////////////////////////////////////////////// // I2C pin definition @@ -153,8 +153,8 @@ static const uint8_t AREF = (PIN_AREF); // not used //////////////////////////////////////////////////////////////////////////////// // GPS #define HAS_GPS 1 -#define PIN_GPS_RX PIN_SERIAL1_RX -#define PIN_GPS_TX PIN_SERIAL1_TX +#define PIN_GPS_TX PIN_SERIAL1_RX // gps module's TX pin +#define PIN_GPS_RX PIN_SERIAL1_TX // gps module's RX pin #define PIN_GPS_EN (32+1) // P1.01 PWR_IO2 on schematic. gps power, driven by the sensor manager. // superIO 3-position mode switch (pins from the meshtastic muzi_base variant). From a134188c62a7f7bdfaa1bd429fc2a2dad44ebe75 Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Wed, 4 Nov 2026 16:30:44 -0400 Subject: [PATCH 352/381] gps: serial pin and configuration fixes (nrf52, meshadventurer, tracker_v1, heltec_tracker) --- src/helpers/sensors/AirohaGpsDriver.h | 4 +- src/helpers/sensors/AirohaSleep.h | 19 ------- .../sensors/MicroNMEALocationProvider.h | 10 +--- src/helpers/sensors/NmeaGpsDriver.h | 55 +++++++++---------- src/helpers/sensors/RakLocationProvider.h | 2 +- variants/heltec_tracker/platformio.ini | 4 +- variants/heltec_tracker/target.cpp | 14 +++-- variants/meshadventurer/platformio.ini | 4 +- variants/meshadventurer/target.cpp | 4 +- variants/nano_g2_ultra/NanoG2UltraGpsDriver.h | 2 +- variants/t1000-e/variant.h | 2 + 11 files changed, 48 insertions(+), 72 deletions(-) delete mode 100644 src/helpers/sensors/AirohaSleep.h diff --git a/src/helpers/sensors/AirohaGpsDriver.h b/src/helpers/sensors/AirohaGpsDriver.h index cd94d419..9ba8a55d 100644 --- a/src/helpers/sensors/AirohaGpsDriver.h +++ b/src/helpers/sensors/AirohaGpsDriver.h @@ -46,8 +46,8 @@ class AirohaGpsDriver : public NmeaGpsDriver { } public: - AirohaGpsDriver(HardwareSerial& serial) - : NmeaGpsDriver(serial, -1, -1, -1, -1, nullptr, HIGH, LOW, 115200) {} + AirohaGpsDriver(UART_TYPE& serial) + : NmeaGpsDriver(serial, -1, -1, -1, -1, nullptr, HIGH, LOW, GPS_BAUD_RATE) {} void initialize() { NmeaGpsDriver::begin(); diff --git a/src/helpers/sensors/AirohaSleep.h b/src/helpers/sensors/AirohaSleep.h deleted file mode 100644 index 6637d0fb..00000000 --- a/src/helpers/sensors/AirohaSleep.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once -#include <helpers/sensors/LocationProvider.h> - -// Board must keep the GPS RTC backup pin powered and can cut GPS power once we return. -// Returns true if the command was acked within 3 attempts, otherwise returns false. -static inline bool airohaEnterSleep(LocationProvider* nmea) { - for (uint8_t attempt = 0; attempt < 3; attempt++) { - nmea->drain(); - nmea->sendSentence("$PAIR650,0"); - if (nmea->waitFor("$PAIR001,650,0", 50)) { // wait for the command received signal - #ifdef GPS_NMEA_DEBUG - Serial.printf("Airoha RTC Backup sleep command accepted by GPS after %u attempts\r\n", attempt + 1); - #endif - nmea->waitFor("$PAIR650,0", 50); // give the GPS 50ms grace to signal it is ready for sleep - return true; - } - } - return false; -} \ No newline at end of file diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index 3c2adc6e..db279acb 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -119,15 +119,7 @@ public: // Temporary migration adapter for targets and downstream boards. New code // should inject a GpsDriver; this constructor will be removed once targets // have been migrated. - MicroNMEALocationProvider(HardwareSerial& serial, mesh::RTCClock* clock = nullptr, - int pin_reset = GPS_RESET, int pin_en = GPS_EN, - RefCountedDigitalPin* peripher_power = nullptr) - : nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), - _driver(new NmeaGpsDriver(serial, PIN_GPS_TX, PIN_GPS_RX, pin_reset, pin_en, - peripher_power)), - _ownsDriver(true) {} - - MicroNMEALocationProvider(Stream& serial, mesh::RTCClock* clock = nullptr, + MicroNMEALocationProvider(UART_TYPE& serial, mesh::RTCClock* clock = nullptr, int pin_reset = GPS_RESET, int pin_en = GPS_EN, RefCountedDigitalPin* peripher_power = nullptr) : nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), diff --git a/src/helpers/sensors/NmeaGpsDriver.h b/src/helpers/sensors/NmeaGpsDriver.h index abecb817..25acff45 100644 --- a/src/helpers/sensors/NmeaGpsDriver.h +++ b/src/helpers/sensors/NmeaGpsDriver.h @@ -5,6 +5,14 @@ #include <Arduino.h> #include <helpers/RefCountedDigitalPin.h> +#ifndef UART_TYPE +#ifdef NRF52_PLATFORM + #define UART_TYPE Uart +#else + #define UART_TYPE HardwareSerial +#endif +#endif + #ifndef PIN_GPS_TX #define PIN_GPS_TX (-1) #endif @@ -46,7 +54,11 @@ #endif #ifndef GPS_BAUD_RATE - #define GPS_BAUD_RATE 9600 + #ifdef GPS_BAUDRATE + #define GPS_BAUD_RATE GPS_BAUDRATE + #else + #define GPS_BAUD_RATE 9600 + #endif #endif #ifndef PIN_GPS_SWITCH @@ -66,8 +78,8 @@ #endif class NmeaGpsDriver : public GpsDriver { - Stream* _stream = nullptr; - HardwareSerial* _hardwareSerial = nullptr; + UART_TYPE* _hardwareSerial = nullptr; + RefCountedDigitalPin* _peripheralPower = nullptr; int _txPin = -1; int _rxPin = -1; @@ -87,12 +99,12 @@ class NmeaGpsDriver : public GpsDriver { #endif void startHardware() { - if (_stream == nullptr || _started) return; + if (_hardwareSerial == nullptr || _started) return; if (_hardwareSerial != nullptr) { -#ifdef ESP32_PLATFORM - _hardwareSerial->setPins(_txPin, _rxPin); -#endif + if (_txPin != -1 && _rxPin != -1) { + _hardwareSerial->setPins(_txPin, _rxPin); + } _hardwareSerial->begin(_baudRate); } @@ -116,14 +128,14 @@ class NmeaGpsDriver : public GpsDriver { public: NmeaGpsDriver() = default; - NmeaGpsDriver(Stream& stream, int txPin = PIN_GPS_TX, int rxPin = PIN_GPS_RX, + NmeaGpsDriver(UART_TYPE& serial, int txPin = PIN_GPS_TX, int rxPin = PIN_GPS_RX, int resetPin = GPS_RESET, int enablePin = GPS_EN, RefCountedDigitalPin* peripheralPower = nullptr, int enableActive = GPS_EN_ACTIVE, int resetActive = GPS_RESET_ACTIVE, uint32_t baudRate = GPS_BAUD_RATE, int hardwareEnablePin = PIN_GPS_SWITCH, int hardwareEnableActive = GPS_SWITCH_ACTIVE) - : _stream(&stream), _peripheralPower(peripheralPower), _txPin(txPin), _rxPin(rxPin), + : _hardwareSerial(&serial), _peripheralPower(peripheralPower), _txPin(txPin), _rxPin(rxPin), _resetPin(resetPin), _enablePin(enablePin), _enableActive(enableActive), _resetActive(resetActive), _baudRate(baudRate), _hardwareEnablePin(hardwareEnablePin), _hardwareEnableActive(hardwareEnableActive) { @@ -140,19 +152,6 @@ public: } } - NmeaGpsDriver(HardwareSerial& serial, int txPin = PIN_GPS_TX, int rxPin = PIN_GPS_RX, - int resetPin = GPS_RESET, int enablePin = GPS_EN, - RefCountedDigitalPin* peripheralPower = nullptr, - int enableActive = GPS_EN_ACTIVE, int resetActive = GPS_RESET_ACTIVE, - uint32_t baudRate = GPS_BAUD_RATE, - int hardwareEnablePin = PIN_GPS_SWITCH, - int hardwareEnableActive = GPS_SWITCH_ACTIVE) - : NmeaGpsDriver(static_cast<Stream&>(serial), txPin, rxPin, resetPin, enablePin, - peripheralPower, enableActive, resetActive, baudRate, - hardwareEnablePin, hardwareEnableActive) { - _hardwareSerial = &serial; - } - void begin() override { #if !GPS_SWITCH_IS_HARDWARE _requestedOn = true; @@ -232,11 +231,11 @@ public: } int available() { - return _stream == nullptr ? 0 : _stream->available(); + return _hardwareSerial == nullptr ? 0 : _hardwareSerial->available(); } int read() { - return _stream == nullptr ? -1 : _stream->read(); + return _hardwareSerial == nullptr ? -1 : _hardwareSerial->read(); } void drain() { @@ -244,19 +243,19 @@ public: } void sendNmeaSentence(const char* sentence) { - if (_stream == nullptr || sentence == nullptr || sentence[0] != '$') return; + if (_hardwareSerial == nullptr || sentence == nullptr || sentence[0] != '$') return; uint8_t checksum = 0; const char* p = sentence + 1; while (*p != '\0' && *p != '*') checksum ^= (uint8_t)*p++; - _stream->print(sentence); + _hardwareSerial->print(sentence); if (*p == '\0') { char checksumSuffix[6]; snprintf(checksumSuffix, sizeof(checksumSuffix), "*%02X\r\n", checksum); - _stream->print(checksumSuffix); + _hardwareSerial->print(checksumSuffix); } else { - _stream->print("\r\n"); + _hardwareSerial->print("\r\n"); } } }; diff --git a/src/helpers/sensors/RakLocationProvider.h b/src/helpers/sensors/RakLocationProvider.h index 7deddf43..094e70ec 100644 --- a/src/helpers/sensors/RakLocationProvider.h +++ b/src/helpers/sensors/RakLocationProvider.h @@ -29,7 +29,7 @@ class RakLocationProvider : public LocationProvider { public: RakLocationProvider(RakI2cGpsDriver& driver, mesh::RTCClock* clock = nullptr, - HardwareSerial& serial = Serial1) + UART_TYPE& serial = Serial1) : _driver(driver), _nmeaDriver(serial), _nmea(_nmeaDriver, clock) {} void syncTime() override { diff --git a/variants/heltec_tracker/platformio.ini b/variants/heltec_tracker/platformio.ini index 75d1cadf..3affd8ae 100644 --- a/variants/heltec_tracker/platformio.ini +++ b/variants/heltec_tracker/platformio.ini @@ -31,8 +31,8 @@ build_flags = -D USE_PIN_TFT=1 -D PIN_VEXT_EN=3 ; Vext is connected to VDD which is also connected to OLED & GPS -D PIN_TFT_LEDA_CTL=21 ; LEDK (switches on/off via mosfet to create the ground) - -D PIN_GPS_RX=33 - -D PIN_GPS_TX=34 + -D PIN_GPS_TX=33 ; GPS module TX -> MCU RX (GPIO33) + -D PIN_GPS_RX=34 ; GPS module RX <- MCU TX (GPIO34) -D PIN_GPS_EN=35 ; N-ch MOSFET Q2 drives P-ch high-side switch → active HIGH (default) -D PIN_GPS_RESET=36 -D PIN_GPS_RESET_ACTIVE=LOW diff --git a/variants/heltec_tracker/target.cpp b/variants/heltec_tracker/target.cpp index 041cb2b8..67f98306 100644 --- a/variants/heltec_tracker/target.cpp +++ b/variants/heltec_tracker/target.cpp @@ -23,9 +23,14 @@ public: : NmeaGpsDriver(Serial1, PIN_GPS_TX, PIN_GPS_RX, GPS_RESET, GPS_EN, &board.periph_power) {} - void begin() override { - NmeaGpsDriver::begin(); - sendNmeaSentence("$CFGSYS,h35155*68"); + void reset() override { + NmeaGpsDriver::reset(); + // Send configuration after reset + if (isActive()) { + delay(250); + sendNmeaSentence("$CFGSYS,h35155*68"); + // TODO: remove active wait (250ms is a lot) + } } }; @@ -64,8 +69,7 @@ void HWTSensorManager::stop_gps() { } bool HWTSensorManager::begin() { - // init GPS port - Serial1.begin(115200, SERIAL_8N1, PIN_GPS_RX, PIN_GPS_TX); + // the GPS UART (pins, baud rate) is now configured by gps_driver when the GPS is started return true; } diff --git a/variants/meshadventurer/platformio.ini b/variants/meshadventurer/platformio.ini index 4af0f7f7..5e35251c 100644 --- a/variants/meshadventurer/platformio.ini +++ b/variants/meshadventurer/platformio.ini @@ -23,8 +23,8 @@ build_flags = -D SX126X_DIO2_AS_RF_SWITCH=false -D SX126X_DIO3_TCXO_VOLTAGE=1.8 -D SX126X_RX_BOOSTED_GAIN=1 - -D PIN_GPS_RX=12 - -D PIN_GPS_TX=15 + -D PIN_GPS_TX=12 ; GPS module TX -> MCU RX (GPIO12) + -D PIN_GPS_RX=15 ; GPS module RX <- MCU TX (GPIO15) -D DISPLAY_CLASS=SSD1306Display build_src_filter = ${esp32_base.build_src_filter} +<../variants/meshadventurer> diff --git a/variants/meshadventurer/target.cpp b/variants/meshadventurer/target.cpp index 827e23b7..1ccfe151 100644 --- a/variants/meshadventurer/target.cpp +++ b/variants/meshadventurer/target.cpp @@ -48,9 +48,7 @@ void MASensorManager::stop_gps() { } bool MASensorManager::begin() { - Serial1.setPins(PIN_GPS_RX, PIN_GPS_TX); - Serial1.begin(9600); - delay(500); + // the GPS UART (pins, baud rate) is now configured by gps_driver when the GPS is started return true; } diff --git a/variants/nano_g2_ultra/NanoG2UltraGpsDriver.h b/variants/nano_g2_ultra/NanoG2UltraGpsDriver.h index 7e3bd109..76270d32 100644 --- a/variants/nano_g2_ultra/NanoG2UltraGpsDriver.h +++ b/variants/nano_g2_ultra/NanoG2UltraGpsDriver.h @@ -4,7 +4,7 @@ class NanoG2UltraGpsDriver : public NmeaGpsDriver { public: - NanoG2UltraGpsDriver(HardwareSerial& serial) : NmeaGpsDriver(serial) { + NanoG2UltraGpsDriver(UART_TYPE& serial) : NmeaGpsDriver(serial) { pinMode(PIN_GPS_STANDBY, OUTPUT); digitalWrite(PIN_GPS_STANDBY, LOW); } diff --git a/variants/t1000-e/variant.h b/variants/t1000-e/variant.h index bd509073..17a5538c 100644 --- a/variants/t1000-e/variant.h +++ b/variants/t1000-e/variant.h @@ -117,6 +117,8 @@ #define GPS_RTC_INT (15) // P0.15 #define GPS_RESETB (46) // P1.14 +#define GPS_BAUDRATE 115200 + //////////////////////////////////////////////////////////////////////////////// // Temp+Lux Sensor From d41aee832e4252ebe2ab87899ee55f1217b798fe Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Wed, 4 Nov 2026 20:34:28 -0400 Subject: [PATCH 353/381] gps: guard the clock sync against stalled and too old fixes --- src/helpers/sensors/MicroNMEALocationProvider.h | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index db279acb..dddcce19 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -70,6 +70,8 @@ class MicroNMEALocationProvider : public LocationProvider { void finishPeriodicAcquisition() { if (_firstFixInWindow == 0) fixStatsMiss(); _driver->stop(); + nmea.clear(); // the parser keeps the last time as valid otherwise + time_valid = 0; _acquiringPeriodically = false; _nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL; } @@ -95,7 +97,7 @@ class MicroNMEALocationProvider : public LocationProvider { } void updateTime() { - if (!isValid()) time_valid = 0; + if (!isValid() || (millis() - _last_nmea_ms) > 2000) time_valid = 0; // no stale time if ((long)(millis() - next_check) <= 0) return; next_check = millis() + 1000; @@ -156,6 +158,8 @@ public: _stop_calls++; _acquiringPeriodically = false; _driver->stop(); + nmea.clear(); + time_valid = 0; } bool isActive() override { @@ -274,7 +278,9 @@ public: fixStatsFix((uint32_t)(_firstFixInWindow - _acquisitionStarted)); } if (_acquiringPeriodically) { - if (nmea.getNumSatellites() >= GPS_MIN_SATS_FOR_FIX || + // stay on until a pending time sync is done (or the settle time is over) + const bool synced = _clock == nullptr || !_time_sync_needed; + if ((nmea.getNumSatellites() >= GPS_MIN_SATS_FOR_FIX && synced) || (uint32_t)(millis() - _firstFixInWindow) >= GPS_FIX_SETTLE_MS) { finishPeriodicAcquisition(); } From 539b55b7724fd56ccf1880fd9081b9151e0155d5 Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Thu, 5 Nov 2026 10:16:28 -0400 Subject: [PATCH 354/381] gps: move detection into LocationProvider, remove the legacy constructor --- .../sensors/EnvironmentSensorManager.cpp | 23 ++----------------- src/helpers/sensors/LocationProvider.h | 16 +++++++++++++ .../sensors/MicroNMEALocationProvider.h | 16 ------------- 3 files changed, 18 insertions(+), 37 deletions(-) diff --git a/src/helpers/sensors/EnvironmentSensorManager.cpp b/src/helpers/sensors/EnvironmentSensorManager.cpp index ee942df1..eafa11a3 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.cpp +++ b/src/helpers/sensors/EnvironmentSensorManager.cpp @@ -696,31 +696,12 @@ bool EnvironmentSensorManager::setSettingValue(const char* name, const char* val #if ENV_INCLUDE_GPS void EnvironmentSensorManager::initBasicGPS() { - start_gps(); - #ifndef PIN_GPS_EN MESH_DEBUG_PRINTLN("No GPS wake/reset pin found for this board. Continuing on..."); #endif -#ifdef ENV_SKIP_GPS_DETECT - gps_detected = true; -#else - gps_detected = _location->detect(5000); -#endif - - if (gps_detected) { - MESH_DEBUG_PRINTLN("GPS detected"); - #if defined(PERSISTANT_GPS) - return; - #else - if (_location->keepEnabledAfterDetection()) { - return; - } - #endif - } else { - MESH_DEBUG_PRINTLN("No GPS detected"); - } - stop_gps(); + gps_detected = _location->autoDetect(); + MESH_DEBUG_PRINTLN("%s", gps_detected ? "GPS detected" : "No GPS detected"); } void EnvironmentSensorManager::start_gps() { diff --git a/src/helpers/sensors/LocationProvider.h b/src/helpers/sensors/LocationProvider.h index 3d7abd7a..ad2bba1d 100644 --- a/src/helpers/sensors/LocationProvider.h +++ b/src/helpers/sensors/LocationProvider.h @@ -61,6 +61,22 @@ public: virtual void drain() { } virtual bool detect(uint32_t timeout_ms) { return false; } virtual bool keepEnabledAfterDetection() const { return false; } + // Power on, detect, then leave the GPS on or off as the board wants. + // Returns true if a GPS is present. + virtual bool autoDetect() { + setGpsOn(true); + #ifdef ENV_SKIP_GPS_DETECT + bool found = true; + #else + bool found = detect(5000); + #endif + #ifdef PERSISTANT_GPS + if (found) return true; + #endif + if (found && keepEnabledAfterDetection()) return true; + setGpsOn(false); + return found; + } virtual void setGpsPeriod(uint32_t seconds) { } virtual uint32_t getGpsPeriod() const { return 0; } virtual uint32_t getLastFixAge() const { // in seconds, UINT32_MAX if never diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index dddcce19..ea87ad19 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -24,7 +24,6 @@ class MicroNMEALocationProvider : public LocationProvider { MicroNMEA nmea; mesh::RTCClock* _clock; NmeaGpsDriver* _driver; - bool _ownsDriver = false; unsigned long next_check = 0; long time_valid = 0; unsigned long _last_time_sync = 0; @@ -118,21 +117,6 @@ public: MicroNMEALocationProvider(NmeaGpsDriver& driver, mesh::RTCClock* clock = nullptr) : nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), _driver(&driver) {} - // Temporary migration adapter for targets and downstream boards. New code - // should inject a GpsDriver; this constructor will be removed once targets - // have been migrated. - MicroNMEALocationProvider(UART_TYPE& serial, mesh::RTCClock* clock = nullptr, - int pin_reset = GPS_RESET, int pin_en = GPS_EN, - RefCountedDigitalPin* peripher_power = nullptr) - : nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), - _driver(new NmeaGpsDriver(serial, PIN_GPS_TX, PIN_GPS_RX, pin_reset, pin_en, - peripher_power)), - _ownsDriver(true) {} - - ~MicroNMEALocationProvider() override { - if (_ownsDriver) delete _driver; - } - void begin() override { _begin_calls++; const bool wasActive = _driver->isActive(); From 93d165dd8cdc72301870ec1e8a83fd64f69ef899 Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Sat, 7 Nov 2026 09:05:11 -0400 Subject: [PATCH 355/381] gps: once command --- src/helpers/CommonGpsPrefs.cpp | 27 ++++++++++++++++++ src/helpers/sensors/LocationProvider.h | 1 + .../sensors/MicroNMEALocationProvider.h | 28 +++++++++++++++++++ src/helpers/sensors/RakLocationProvider.h | 8 ++++++ 4 files changed, 64 insertions(+) diff --git a/src/helpers/CommonGpsPrefs.cpp b/src/helpers/CommonGpsPrefs.cpp index c4936d4f..926efe71 100644 --- a/src/helpers/CommonGpsPrefs.cpp +++ b/src/helpers/CommonGpsPrefs.cpp @@ -97,6 +97,33 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, } return true; } + if (memcmp(command, "gps once", 8) == 0) { // before "gps on" + LocationProvider* location = sensors.getLocationProvider(); + + if (location == nullptr) { + strcpy(reply, "gps provider not found"); + return true; + } + + if (location->hasHardwareEnableState() && !location->isHardwareEnabled()) { + strcpy(reply, "gps hw switch off"); + return true; + } + + if (strstr(command, " -s") != nullptr) location->syncTime(); + + const char* state = !location->isGpsOn() ? "turning on and acquiring" + : (location->getGpsPeriod() > 0 && !location->isActive()) ? "waking gps" + : "gps already on"; + + if (location->startOnce()) { + snprintf(reply, 160, "ok (%s)", state); + } else { + strcpy(reply, "gps once not supported"); + } + + return true; + } if (memcmp(command, "gps on", 6) == 0) { if (!setGpsEnabled(sensors, true)) { strcpy(reply, "gps toggle not found"); diff --git a/src/helpers/sensors/LocationProvider.h b/src/helpers/sensors/LocationProvider.h index ad2bba1d..b15c0ed2 100644 --- a/src/helpers/sensors/LocationProvider.h +++ b/src/helpers/sensors/LocationProvider.h @@ -86,6 +86,7 @@ public: virtual bool hasHardwareEnableState() const { return false; } virtual bool isHardwareEnabled() const { return true; } virtual bool isGpsOn() const { return _gpsOn; } + virtual bool startOnce() { return false; } virtual void setGpsOn(bool on) { _gpsOn = on; if (on) { diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index ea87ad19..9a6d8006 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -32,6 +32,7 @@ class MicroNMEALocationProvider : public LocationProvider { unsigned long _acquisitionStarted = 0; unsigned long _firstFixInWindow = 0; bool _acquiringPeriodically = false; + unsigned long _onceDeadline = 0; static const unsigned long TIME_SYNC_INTERVAL = 1800000; uint32_t _uart_bytes = 0; @@ -119,6 +120,7 @@ public: void begin() override { _begin_calls++; + _onceDeadline = 0; const bool wasActive = _driver->isActive(); _driver->begin(); if (!wasActive) { @@ -140,6 +142,7 @@ public: void stop() override { _stop_calls++; + _onceDeadline = 0; _acquiringPeriodically = false; _driver->stop(); nmea.clear(); @@ -172,6 +175,16 @@ public: return _gpsPeriodSeconds; } + bool startOnce() override { + if (_gpsOn) { // already on, acquire now + _nextAcquisition = millis(); + return true; + } + setGpsOn(true); + _onceDeadline = millis() + GPS_PERIODIC_ACQUISITION_TIMEOUT_MS; + return true; + } + void syncTime() override { nmea.clear(); LocationProvider::syncTime(); @@ -232,6 +245,21 @@ public: void loop() override { if (_driver->pollGpsSwitch()) _gpsOn = true; + if (_onceDeadline != 0) { + if (_firstFixInWindow != 0 && (long)(_onceDeadline - (millis() + GPS_FIX_SETTLE_MS)) > 0) { + _onceDeadline = millis() + GPS_FIX_SETTLE_MS; + } + if ((long)(millis() - _onceDeadline) >= 0) { + if (_driver->isActive()) { + setGpsOn(false); + } else { // do not stop twice + _gpsOn = false; + _onceDeadline = 0; + _acquiringPeriodically = false; + } + } + } + if (_gpsOn && _gpsPeriodSeconds > 0 && !_acquiringPeriodically && (long)(millis() - _nextAcquisition) >= 0) { startPeriodicAcquisition(); diff --git a/src/helpers/sensors/RakLocationProvider.h b/src/helpers/sensors/RakLocationProvider.h index 094e70ec..6ad05125 100644 --- a/src/helpers/sensors/RakLocationProvider.h +++ b/src/helpers/sensors/RakLocationProvider.h @@ -190,6 +190,14 @@ public: return _gpsPeriodSeconds; } + bool isGpsOn() const override { + return _useI2c ? _gpsOn : _nmea.isGpsOn(); + } + + bool startOnce() override { + return _useI2c ? false : _nmea.startOnce(); // not supported on the RAK12500 + } + void setGpsOn(bool on) override { if (_useI2c) LocationProvider::setGpsOn(on); else { _gpsOn = on; _nmea.setGpsOn(on); } From 6b34ae96dfd7df221911705e10077fd82d83269b Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Sat, 7 Nov 2026 13:45:40 -0400 Subject: [PATCH 356/381] gps: Rework the CLI - more consistency with other cli commands - new format for gps fix - gps format accepts postfix (s/m/d/h) - documentation --- docs/cli_commands.md | 27 +++++- docs/companion_cli.md | 27 +++++- src/helpers/CommonCLI.cpp | 12 +-- src/helpers/CommonGpsPrefs.cpp | 89 ++++++++++--------- src/helpers/sensors/LocationProvider.h | 1 + .../sensors/MicroNMEALocationProvider.h | 4 + src/helpers/sensors/RakLocationProvider.h | 4 + 7 files changed, 110 insertions(+), 54 deletions(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index d7b8d5d0..44ff3a25 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1021,10 +1021,10 @@ region save #### View or change the GPS acquisition period **Usage:** - `gps period` -- `gps period <seconds>` +- `gps period <value>` **Parameters:** -- `seconds`: `0` for continuous tracking, or `1`-`86400` for periodic acquisition +- `value`: `0` for continuous tracking, or a period. The value can be postfixed with `s`, `m`, `h` or `d` to specify the unit (seconds by default). **Note:** A periodic acquisition stops after receiving a valid fix, then resumes after the configured period. @@ -1034,7 +1034,12 @@ region save **Usage:** - `gps fix` -**Note:** Returns the last valid latitude, longitude, altitude, and elapsed time since the fix. Returns `no fix` until a valid fix is received. +**Output:** +- `> Fix (n sat): <lat>, <lon>`: the GPS currently has a fix. +- `> Last fix <age> ago (n sat)[, acq <time>]: <lat>, <lon>`: position of the last valid fix; `acq` is shown only while the receiver is running and shows how for how long the gps has been trying to get a fix. +- `> No fix[, acq <time>]`: no valid fix since the node started. + +**Note:** Ages and durations are given in `s`, `m` or `h`. --- @@ -1044,11 +1049,25 @@ region save --- +#### On demand GPS fix +**Usage:** +- `gps once` +- `gps once -s` + +**Parameters:** +- `-s`: also sync this node's clock with GPS time (as `gps sync`) + +**Note:** Starts an acquisition now. If the GPS is off, it is switched and kept on until a valid fix and then turned off. + +**Reply:** `OK - turning on and acquiring` (GPS was off), `OK - waking gps` (periodic mode, receiver off between acquisitions) or `OK - gps already on`. `Error, gps hw switch off` if a hardware GPS switch is off, `Error, gps once not supported`. + +--- + #### View GPS time to first fix statistics **Usage:** - `gps fix_stats` -**Output:** `ttf:<last>/<max> ok:<n> miss:<n>`: last and maximum time between a start of the GPS and its first valid fix, then the last count of consecutive starts with a fix (`ok`) or without one (`miss`). +**Output:** `> ttf:<last>/<max> ok:<n> miss:<n>`: last and maximum time between a start of the GPS and its first valid fix, then the last count of consecutive starts with a fix (`ok`) or without one (`miss`). --- diff --git a/docs/companion_cli.md b/docs/companion_cli.md index 0b3a27df..eecc5f82 100644 --- a/docs/companion_cli.md +++ b/docs/companion_cli.md @@ -142,10 +142,10 @@ Radio parameters are common to all roles and handled by `CommonRadioPrefs`. #### View or change the GPS acquisition period **Usage:** - `gps period` -- `gps period <seconds>` +- `gps period <value>` **Parameters:** -- `seconds`: `0` for continuous tracking, or `1`-`86400` for periodic acquisition +- `value`: `0` for continuous tracking, or a period. The value can be postfixed with `s`, `m`, `h` or `d` to specify the unit (seconds by default). **Note:** A periodic acquisition stops after receiving a valid fix, then resumes after the configured period. @@ -155,7 +155,12 @@ Radio parameters are common to all roles and handled by `CommonRadioPrefs`. **Usage:** - `gps fix` -**Note:** Returns the last valid latitude, longitude, altitude, and elapsed time since the fix. Returns `no fix` until a valid fix is received. +**Output:** +- `> Fix (n sat): <lat>, <lon>`: the GPS currently has a fix. +- `> Last fix <age> ago (n sat)[, acq <time>]: <lat>, <lon>`: position of the last valid fix; `acq` is shown only while the receiver is running and shows how for how long the gps has been trying to get a fix. +- `> No fix[, acq <time>]`: no valid fix since the node started. + +**Note:** Ages and durations are given in `s`, `m` or `h`. --- @@ -165,11 +170,25 @@ Radio parameters are common to all roles and handled by `CommonRadioPrefs`. --- +#### On demand GPS fix +**Usage:** +- `gps once` +- `gps once -s` + +**Parameters:** +- `-s`: also sync this node's clock with GPS time (as `gps sync`) + +**Note:** Starts an acquisition now. If the GPS is off, it is switched and kept on until a valid fix and then turned off. + +**Reply:** `OK - turning on and acquiring` (GPS was off), `OK - waking gps` (periodic mode, receiver off between acquisitions) or `OK - gps already on`. `Error, gps hw switch off` if a hardware GPS switch is off, `Error, gps once not supported`. + +--- + #### View GPS time to first fix statistics **Usage:** - `gps fix_stats` -**Output:** `ttf:<last>/<max> ok:<n> miss:<n>`: last and maximum time between a start of the GPS and its first valid fix, then the last count of consecutive starts with a fix (`ok`) or without one (`miss`). +**Output:** `> ttf:<last>/<max> ok:<n> miss:<n>`: last and maximum time between a start of the GPS and its first valid fix, then the last count of consecutive starts with a fix (`ok`) or without one (`miss`). --- diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index ed1b5199..978f9e06 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -358,7 +358,7 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re _prefs->node_lat = _sensors->node_lat; _prefs->node_lon = _sensors->node_lon; savePrefs(); - strcpy(reply, "ok"); + strcpy(reply, "OK"); } else if (memcmp(command, "gps advert", 10) == 0) { if (strlen(command) == 10) { switch (_prefs->advert_loc_policy) { @@ -372,22 +372,22 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re strcpy(reply, "> share"); break; default: - strcpy(reply, "error"); + strcpy(reply, "Error, invalid policy"); } } else if (memcmp(command+11, "none", 4) == 0) { _prefs->advert_loc_policy = ADVERT_LOC_NONE; savePrefs(); - strcpy(reply, "ok"); + strcpy(reply, "OK"); } else if (memcmp(command+11, "share", 5) == 0) { _prefs->advert_loc_policy = ADVERT_LOC_SHARE; savePrefs(); - strcpy(reply, "ok"); + strcpy(reply, "OK"); } else if (memcmp(command+11, "prefs", 5) == 0) { _prefs->advert_loc_policy = ADVERT_LOC_PREFS; savePrefs(); - strcpy(reply, "ok"); + strcpy(reply, "OK"); } else { - strcpy(reply, "error"); + strcpy(reply, "Error, invalid policy"); } #endif } else if (memcmp(command, "powersaving on", 14) == 0) { diff --git a/src/helpers/CommonGpsPrefs.cpp b/src/helpers/CommonGpsPrefs.cpp index 926efe71..f840f0a2 100644 --- a/src/helpers/CommonGpsPrefs.cpp +++ b/src/helpers/CommonGpsPrefs.cpp @@ -41,13 +41,13 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, LocationProvider* location = sensors.getLocationProvider(); char mode[32]; if (getGpsPeriod() == 0) { - strcpy(mode, "tracking"); + strcpy(mode, "continuous"); } else { snprintf(mode, sizeof(mode), "periodic (%lus)", (unsigned long)getGpsPeriod()); } if (location == nullptr) { - strcpy(reply, "gps provider not found"); + strcpy(reply, "Error, gps provider not found"); } else if (location->isGpsOn()) { const char* activity = "active"; if (!location->isActive()) { @@ -67,33 +67,38 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, } else { strcpy(fix, "no fix"); } - snprintf(reply, 160, "on, %s, %s, mode: %s", activity, fix, mode); + snprintf(reply, 160, "> on, %s, %s, %s", activity, fix, mode); } else { - snprintf(reply, 160, "off, mode: %s", mode); + snprintf(reply, 160, "> off, %s", mode); } return true; } if (strcmp(command, "gps fix") == 0) { LocationProvider* location = sensors.getLocationProvider(); + char acq[16] = ""; if (location == nullptr) { - strcpy(reply, "gps provider not found"); - } else if (!location->hasValidFix()) { - strcpy(reply, "no fix"); + strcpy(reply, "Error, gps provider not found"); + return true; + } + if (location->isActive()) { + char t[12]; + formatDuration(t, sizeof(t), location->getAcquisitionAge()); + snprintf(acq, sizeof(acq), "acq %s", t); + } + if (!location->hasValidFix()) { + snprintf(reply, 160, "> No fix%s%s", acq[0] ? ", " : "", acq); } else { const long latitude = location->getLatitude(); const long longitude = location->getLongitude(); - const uint32_t fixAge = location->getLastFixAge(); - char age[24]; - if (fixAge == UINT32_MAX) { - strcpy(age, "age unavailable"); + char pos[40]; + snprintf(pos, sizeof(pos), "%.6f, %.6f", latitude / 1e6, longitude / 1e6); + if (location->isValid()) { + snprintf(reply, 160, "> Fix (%d sat): %s", location->satellitesCount(), pos); } else { - snprintf(age, sizeof(age), "%lus ago", (unsigned long)fixAge); + char age[12]; + formatDuration(age, sizeof(age), location->getLastFixAge()); + snprintf(reply, 160, "> Fix %s ago (%d sat)%s%s: %s", age, location->satellitesCount(),acq[0] ? ", " : "", acq, pos); } - snprintf(reply, 160, "%s%ld.%06ld, %s%ld.%06ld, %ldm, %s", - latitude < 0 ? "-" : "", labs(latitude) / 1000000L, - labs(latitude) % 1000000L, - longitude < 0 ? "-" : "", labs(longitude) / 1000000L, - labs(longitude) % 1000000L, location->getAltitude() / 1000L, age); } return true; } @@ -101,12 +106,12 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, LocationProvider* location = sensors.getLocationProvider(); if (location == nullptr) { - strcpy(reply, "gps provider not found"); + strcpy(reply, "Error, gps provider not found"); return true; } if (location->hasHardwareEnableState() && !location->isHardwareEnabled()) { - strcpy(reply, "gps hw switch off"); + strcpy(reply, "Error, gps hw switch off"); return true; } @@ -117,26 +122,26 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, : "gps already on"; if (location->startOnce()) { - snprintf(reply, 160, "ok (%s)", state); + snprintf(reply, 160, "OK - %s", state); } else { - strcpy(reply, "gps once not supported"); + strcpy(reply, "Error, gps once not supported"); } return true; } if (memcmp(command, "gps on", 6) == 0) { if (!setGpsEnabled(sensors, true)) { - strcpy(reply, "gps toggle not found"); + strcpy(reply, "Error, gps toggle not found"); } else { - strcpy(reply, "ok"); + strcpy(reply, "OK"); } return true; } if (memcmp(command, "gps off", 7) == 0) { if (!setGpsEnabled(sensors, false)) { - strcpy(reply, "gps toggle not found"); + strcpy(reply, "Error, gps toggle not found"); } else { - strcpy(reply, "ok"); + strcpy(reply, "OK"); } return true; } @@ -149,34 +154,38 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, return true; } if (memcmp(command, "gps period ", 11) == 0) { - char* end = nullptr; + char* end; unsigned long period = strtoul(command + 11, &end, 10); - if (command[11] == '\0' || *end != '\0' || period > 86400) { - strcpy(reply, "gps period must be 0-86400 seconds"); + unsigned long mult = 1; + if (*end == 'm') mult = 60; + else if (*end == 'h') mult = 3600; + else if (*end == 'd') mult = 86400; + if (mult > 1 || *end == 's') end++; // skip the suffix char + + if (command[11] == '\0' || *end != '\0') { + strcpy(reply, "Error, invalid gps period"); + } else if (!setGpsPeriod(sensors, (uint32_t)(period * mult)) || + !setGpsEnabled(sensors, true)) { + strcpy(reply, "Error, gps provider not found"); } else { - if (!setGpsPeriod(sensors, (uint32_t)period) || - !setGpsEnabled(sensors, true)) { - strcpy(reply, "gps provider not found"); - } else { - strcpy(reply, "ok"); - } + strcpy(reply, "OK"); } return true; } if (memcmp(command, "gps sync", 8) == 0) { LocationProvider* location = sensors.getLocationProvider(); if (location == nullptr) { - strcpy(reply, "gps provider not found"); + strcpy(reply, "Error, gps provider not found"); } else { location->syncTime(); - strcpy(reply, "ok"); + strcpy(reply, "OK"); } return true; } if (strcmp(command, "gps fix_stats") == 0) { LocationProvider* location = sensors.getLocationProvider(); if (location == nullptr) { - strcpy(reply, "gps provider not found"); + strcpy(reply, "Error, gps provider not found"); } else { const LocationProvider::FixStats s = location->getFixStats(); char last[12] = "-", max[12] = "-"; @@ -184,7 +193,7 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, formatDuration(last, sizeof(last), (s.lastTtffMs + 500) / 1000); formatDuration(max, sizeof(max), (s.maxTtffMs + 500) / 1000); } - snprintf(reply, 160, "ttf:%s/%s ok:%lu miss:%lu", last, max, + snprintf(reply, 160, "> ttf:%s/%s ok:%lu miss:%lu", last, max, (unsigned long)s.consecutiveFixes, (unsigned long)s.consecutiveMisses); } return true; @@ -192,9 +201,9 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, if (strcmp(command, "gps diag") == 0) { LocationProvider* location = sensors.getLocationProvider(); if (location == nullptr) { - strcpy(reply, "gps provider not found"); + strcpy(reply, "Error, gps provider not found"); } else { - int prefix = snprintf(reply, 160, "req:%u ", isGpsEnabled() ? 1U : 0U); + int prefix = snprintf(reply, 160, "> req:%u ", isGpsEnabled() ? 1U : 0U); if (prefix >= 0 && prefix < 160) location->formatDiagnostics(reply + prefix, 160 - prefix); } return true; diff --git a/src/helpers/sensors/LocationProvider.h b/src/helpers/sensors/LocationProvider.h index b15c0ed2..52093d87 100644 --- a/src/helpers/sensors/LocationProvider.h +++ b/src/helpers/sensors/LocationProvider.h @@ -86,6 +86,7 @@ public: virtual bool hasHardwareEnableState() const { return false; } virtual bool isHardwareEnabled() const { return true; } virtual bool isGpsOn() const { return _gpsOn; } + virtual uint32_t getAcquisitionAge() const { return 0; } virtual bool startOnce() { return false; } virtual void setGpsOn(bool on) { _gpsOn = on; diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index 9a6d8006..f3442bd5 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -175,6 +175,10 @@ public: return _gpsPeriodSeconds; } + uint32_t getAcquisitionAge() const override { + return (uint32_t)(millis() - _acquisitionStarted) / 1000UL; + } + bool startOnce() override { if (_gpsOn) { // already on, acquire now _nextAcquisition = millis(); diff --git a/src/helpers/sensors/RakLocationProvider.h b/src/helpers/sensors/RakLocationProvider.h index 6ad05125..db437b95 100644 --- a/src/helpers/sensors/RakLocationProvider.h +++ b/src/helpers/sensors/RakLocationProvider.h @@ -194,6 +194,10 @@ public: return _useI2c ? _gpsOn : _nmea.isGpsOn(); } + uint32_t getAcquisitionAge() const override { + return _useI2c ? (uint32_t)(millis() - _acquisitionStarted) / 1000UL : _nmea.getAcquisitionAge(); + } + bool startOnce() override { return _useI2c ? false : _nmea.startOnce(); // not supported on the RAK12500 } From b2e46335e5d97c12d1e7c957404e34723ee548f6 Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Sat, 7 Nov 2026 18:41:52 -0400 Subject: [PATCH 357/381] ui_task: let user choose if enter in gps screen toggles or triggers gps --- docs/companion_cli.md | 14 ++++++++++++++ examples/companion_radio/MyMesh.cpp | 12 ++++++++++++ examples/companion_radio/NodePrefs.h | 6 ++++++ examples/companion_radio/ui-new/UITask.cpp | 11 ++++++++++- examples/companion_radio/ui-new/UITask.h | 1 + 5 files changed, 43 insertions(+), 1 deletion(-) diff --git a/docs/companion_cli.md b/docs/companion_cli.md index eecc5f82..6366d2a4 100644 --- a/docs/companion_cli.md +++ b/docs/companion_cli.md @@ -452,6 +452,20 @@ Radio parameters are common to all roles and handled by `CommonRadioPrefs`. --- +#### GPS key action +**Usage:** +- `set ui.gps_action <action>` +- `get ui.gps_action` + +**Parameters:** +- `action`: `toggle` (or `0`) to switch the GPS on and off, `once` (or `trigger`, `1`) to acquire a fix on demand, as `gps once` + +**Default:** `toggle`, or `once` on boards with a GPS switch + +**Note:** Only used by the `ui-new` screens for now. + +--- + #### Node discovery screen shows nodes names **Usage:** - `set ui.nd_name <state>` diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index d12c7b8a..e3ec01f3 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2291,6 +2291,18 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* sprintf(reply, "> ui.nd_name is now %d", _prefs.ui_nd_name); return true; } + if (memcmp(command, "set ui.gps_action", 17) == 0) { + const char* v = &command[17]; + while (*v == ' ') v++; + _prefs.ui_gps_action = (memcmp(v, "once", 4) == 0 || memcmp(v, "trigger", 7) == 0 || *v == '1') ? 1 : 0; // anything else: toggle + savePrefs(); + sprintf(reply, "> now %s", _prefs.ui_gps_action ? "once" : "toggle"); + return true; + } + if (memcmp(command, "get ui.gps_action", 17) == 0) { + sprintf(reply, "> %s", _prefs.ui_gps_action ? "once" : "toggle"); + return true; + } if (memcmp(command, "get ui.show_clock", 17) == 0) { sprintf(reply, "> %d", _prefs.ui_show_clock); return true; diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index a54eca75..db019370 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -87,6 +87,11 @@ public: uint8_t ui_auto_off_keep_msgs = 1; uint8_t ui_max_partial = EINK_MAX_PARTIAL_REFRESH; uint8_t ui_nd_name = 1; +#ifdef PIN_GPS_SWITCH + uint8_t ui_gps_action = 1; +#else + uint8_t ui_gps_action = 0; +#endif #endif private: @@ -238,6 +243,7 @@ private: def("off_blank", _parent->ui_auto_off_blank); def("off_keep_msgs", _parent->ui_auto_off_keep_msgs); def("nd_name", _parent->ui_nd_name); + def("gps_act", _parent->ui_gps_action); } public: UI_Prefs(NodePrefs* parent) : _parent(parent) {} diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index 6b6af33e..ee225341 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -632,7 +632,7 @@ public: } #if ENV_INCLUDE_GPS == 1 if (c == KEY_ENTER && _page == HomePage::GPS) { - _task->toggleGPS(); + if (_node_prefs->ui_gps_action == 1) _task->triggerGPS(); else _task->toggleGPS(); return true; } #endif @@ -1232,6 +1232,15 @@ void UITask::toggleGPS() { } } +void UITask::triggerGPS() { + LocationProvider* location = _sensors != NULL ? _sensors->getLocationProvider() : NULL; + if (location != NULL && !(location->hasHardwareEnableState() && !location->isHardwareEnabled()) + && location->startOnce()) { + notify(UIEventType::ack); + } + _next_refresh = 0; +} + void UITask::toggleBuzzer() { // Toggle buzzer quiet mode #ifdef PIN_BUZZER diff --git a/examples/companion_radio/ui-new/UITask.h b/examples/companion_radio/ui-new/UITask.h index 61831488..045b1060 100644 --- a/examples/companion_radio/ui-new/UITask.h +++ b/examples/companion_radio/ui-new/UITask.h @@ -114,6 +114,7 @@ public: void toggleBuzzer(); bool getGPSState(); void toggleGPS(); + void triggerGPS(); // MyMesh::Listener void onMessageRecv(mesh::Packet *pkt, const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, const char* text) override; From 017005d1cf85dbec0f5c16a33ec56627ab65fd01 Mon Sep 17 00:00:00 2001 From: Martin Boissonneault <19229816+Ve2mrx@users.noreply.github.com> Date: Sat, 7 Nov 2026 21:50:27 -0500 Subject: [PATCH 358/381] rak4631: let the serial GPS switch the WB_IO2 rail (opt-in) On a RAK19007 the RAK12501's supply is 3V3_S, switched by WB_IO2, so gps off, periodic mode and shutdown left it powered. Pass WB_IO2 to the NMEA driver as peripheralPower under GPS_RAIL_POWER_CONTROL, set by the new RAK_4631_repeater_gps_power env. It is opt-in because the rail feeds every slot module, and refused with ETHERNET_ENABLED (RAK13800). The RAK12500 (I2C) driver keeps switching its own power pin, so this only applies on the NMEA path. RefCountedDigitalPin now sets OUTPUT on claim and release: WB_IO2 left as an input (as probeRak12500() leaves it after a failed probe) keeps 3V3_S in its last state, so writing the latch alone did not cut it. Measured with a KM003C, battery and panel out: gps off 40.5 -> 12.4 mA, shutdown 29.7 -> 1.30 mA. --- src/helpers/RefCountedDigitalPin.h | 4 ++++ src/helpers/sensors/RakLocationProvider.h | 8 ++++++-- variants/rak4631/platformio.ini | 8 ++++++++ variants/rak4631/target.cpp | 9 +++++++++ 4 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/helpers/RefCountedDigitalPin.h b/src/helpers/RefCountedDigitalPin.h index f30c4c58..b971ba98 100644 --- a/src/helpers/RefCountedDigitalPin.h +++ b/src/helpers/RefCountedDigitalPin.h @@ -14,10 +14,13 @@ public: digitalWrite(_pin, !_active); // initial state } + // Both set the level, then make the pin an output again, since other code may have left it + // an input. On a RAK19007 with a RAK12501, WB_IO2 left as an input keeps 3V3_S in its last state. void claim() { _claims++; if (_claims > 0) { digitalWrite(_pin, _active); + pinMode(_pin, OUTPUT); } } @@ -27,6 +30,7 @@ public: _claims--; if (_claims == 0) { digitalWrite(_pin, !_active); + pinMode(_pin, OUTPUT); } } }; diff --git a/src/helpers/sensors/RakLocationProvider.h b/src/helpers/sensors/RakLocationProvider.h index db437b95..903546ba 100644 --- a/src/helpers/sensors/RakLocationProvider.h +++ b/src/helpers/sensors/RakLocationProvider.h @@ -28,9 +28,11 @@ class RakLocationProvider : public LocationProvider { } public: + // serialPower, if given, switches the serial module's supply (WB_IO2 on WisBlock bases). RakLocationProvider(RakI2cGpsDriver& driver, mesh::RTCClock* clock = nullptr, - UART_TYPE& serial = Serial1) - : _driver(driver), _nmeaDriver(serial), _nmea(_nmeaDriver, clock) {} + UART_TYPE& serial = Serial1, RefCountedDigitalPin* serialPower = nullptr) + : _driver(driver), _nmeaDriver(serial, PIN_GPS_TX, PIN_GPS_RX, GPS_RESET, GPS_EN, serialPower), + _nmea(_nmeaDriver, clock) {} void syncTime() override { LocationProvider::syncTime(); @@ -112,6 +114,8 @@ public: // the serial module is started first, then the I2C module is probed _nmeaDriver.begin(); if (_driver.detect(timeout_ms)) { + // The serial driver keeps its claim on serialPower, so the rail stays as it is without one. + // The RAK12500 driver switches its own power pin, and serialPower is only used on the serial path. _useI2c = true; } else if (!_nmeaDriver.detect(0)) { _nmeaDriver.stop(); diff --git a/variants/rak4631/platformio.ini b/variants/rak4631/platformio.ini index 4c13b0d7..c5d94d51 100644 --- a/variants/rak4631/platformio.ini +++ b/variants/rak4631/platformio.ini @@ -55,6 +55,14 @@ build_src_filter = ${rak4631.build_src_filter} +<helpers/ui/SSD1306Display.cpp> +<../examples/simple_repeater> +; Lets `gps off`, periodic mode and shutdown cut the power to a serial GPS (RAK12501). +; WB_IO2 switches the shared 3V3_S slot rail, so this also powers down any other slot module. +[env:RAK_4631_repeater_gps_power] +extends = env:RAK_4631_repeater +build_flags = + ${env:RAK_4631_repeater.build_flags} + -D GPS_RAIL_POWER_CONTROL + [env:RAK_4631_repeater_ethernet] extends = rak4631 build_flags = diff --git a/variants/rak4631/target.cpp b/variants/rak4631/target.cpp index 158de2b5..813cb807 100644 --- a/variants/rak4631/target.cpp +++ b/variants/rak4631/target.cpp @@ -27,7 +27,16 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/RakLocationProvider.h> RakI2cGpsDriver gps_driver; + #ifdef GPS_RAIL_POWER_CONTROL + #ifdef ETHERNET_ENABLED + #error "GPS_RAIL_POWER_CONTROL would cut the RAK13800's power, which also comes from WB_IO2" + #endif + // WB_IO2 switches 3V3_S, which powers the serial GPS and every other slot module. + RefCountedDigitalPin gps_rail(WB_IO2); + RakLocationProvider location(gps_driver, &rtc_clock, Serial1, &gps_rail); + #else RakLocationProvider location(gps_driver, &rtc_clock); + #endif EnvironmentSensorManager sensors(location); #else EnvironmentSensorManager sensors; From 64f75005b5f17837eb4f0cc37ed4d843a3b155f6 Mon Sep 17 00:00:00 2001 From: Maxwell <mxwcookie@gmail.com> Date: Sun, 8 Nov 2026 16:34:54 +0200 Subject: [PATCH 359/381] Add min/max/avg history queries to repeaters Move TimeSeriesData from simple_sensor into src/helpers and drive it with monotonic uptime, so RTC changes cannot stall recording or break queries. Keep the old RTCClock* overloads as deprecated for custom sensor sketches. Record 24h of battery, noise floor, TX/RX airtime % and MCU temperature on repeaters and answer the existing 0x04 min/max/avg request using the same format as sensor nodes. No packets are sent by this feature. REPEATER_HISTORY_SLOTS=0 removes it; default off on STM32/RP2040. Add native tests for TimeSeriesData and document the request and channels. --- docs/cli_commands.md | 7 ++ docs/payloads.md | 26 +++- docs/repeater_history.md | 84 +++++++++++++ examples/simple_repeater/MyMesh.cpp | 108 +++++++++++++++- examples/simple_repeater/MyMesh.h | 26 ++++ examples/simple_sensor/SensorMesh.cpp | 12 +- examples/simple_sensor/SensorMesh.h | 5 +- examples/simple_sensor/TimeSeriesData.cpp | 45 ------- examples/simple_sensor/TimeSeriesData.h | 29 +---- examples/simple_sensor/main.cpp | 5 +- platformio.ini | 1 + src/helpers/TimeSeriesData.cpp | 91 ++++++++++++++ src/helpers/TimeSeriesData.h | 38 ++++++ test/test_time_series/test_time_series.cpp | 138 +++++++++++++++++++++ 14 files changed, 530 insertions(+), 85 deletions(-) create mode 100644 docs/repeater_history.md delete mode 100644 examples/simple_sensor/TimeSeriesData.cpp create mode 100644 src/helpers/TimeSeriesData.cpp create mode 100644 src/helpers/TimeSeriesData.h create mode 100644 test/test_time_series/test_time_series.cpp diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 9fde4d43..c19473fe 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1175,6 +1175,13 @@ region save --- +### Repeater health history + +History is queried over the mesh using the sensor-compatible `0x04` min/max/average +request; there is no history CLI command. Retention and recording interval are controlled +by `REPEATER_HISTORY_SLOTS` and `REPEATER_HISTORY_INTERVAL_SECS` at build time. +See [Repeater health history](repeater_history.md) for the channel mapping and flags. + ### Ethernet (when Ethernet support is compiled in) Ethernet support is available on RAK4631 boards with a RAK13800 (W5100S) Ethernet module. Use the `_ethernet` firmware variants (e.g. `RAK_4631_repeater_ethernet`) to enable this feature. diff --git a/docs/payloads.md b/docs/payloads.md index 493f628c..c60a78d6 100644 --- a/docs/payloads.md +++ b/docs/payloads.md @@ -103,7 +103,7 @@ For the common chat/server helpers in `BaseChatMesh`, the current request type v | `0x01` | get stats | get stats of repeater or room server | | `0x02` | keepalive | (deprecated) | | `0x03` | get telemetry | request node telemetry | -| `0x04` | get min/max/avg | get sensor node stats on time series data | +| `0x04` | get min/max/avg | get sensor or repeater time series statistics | | `0x05` | get acl | node ACL query | | `0x06` | get neighbors | node neighbors query | | `0x08` | subscribe | subscribe to telemetry push | @@ -140,7 +140,7 @@ Gets information about the node, possibly including the following: | req type | 1 | 0x03 (request sub type) | | permission mask | 1 | bitwise inverse mask to AND to permissions (0 = get ALL telem values) | -#### Get Min/Max/Ave (Sensor nodes) +#### Get Min/Max/Ave (Sensor and repeater nodes) | Field | Size (bytes) | Description | |----------------|--------------|------------------------------| @@ -150,6 +150,28 @@ Gets information about the node, possibly including the following: | end | 4 | ending time, seconds ago | | reserved | 2 | should be zeroes | +Requires an authenticated client with the READ_ONLY role or higher. The range includes +samples whose age is `end <= age < start`, in seconds. Request integers are little-endian. +The repeater uses exactly the sensor request and response layout. + +The response body (after decryption) is: + +| Field | Size (bytes) | Description | +|----------------|--------------|-------------| +| tag | 4 | echoed request timestamp, little-endian | +| current time | 4 | current node RTC Unix time, little-endian | +| series | variable | up to 8 series records, described below | + +Each series record contains a channel byte, an LPP type byte, then min, max, and average +in that order. Each value uses the type's Cayenne LPP size, multiplier, sign, and +big-endian encoding. There is no count byte; parse records to the end of the response. +Nonzero reserved bytes return only the tag and current time. + +Repeater history is pull-only, uses uptime internally, and omits series with no valid +samples in the requested range. Its returned current time still comes from the RTC; +an unset or corrected RTC does not affect sampling or range selection. See +[Repeater health history](repeater_history.md) for channels, retention, and build flags. + #### Subscribe to Telemetry push - (Sensor nodes) | Field | Size (bytes) | Description | diff --git a/docs/repeater_history.md b/docs/repeater_history.md new file mode 100644 index 00000000..35b37d82 --- /dev/null +++ b/docs/repeater_history.md @@ -0,0 +1,84 @@ +# Repeater health history + +The simple repeater keeps health samples in RAM and answers mesh request +`REQ_TYPE_GET_AVG_MIN_MAX` (`0x04`). A logged-in client needs READ_ONLY access or +higher. This is pull-only: recording history sends no packets. Existing GET_STATUS +and telemetry responses are unchanged. + +## Series + +| Channel | LPP type | Value recorded each interval | +|---------|----------|------------------------------| +| 200 | `LPP_VOLTAGE` (116) | Battery voltage in V, averaged from periodic reads every 15 seconds | +| 201 | `LPP_ANALOG_INPUT` (2, signed) | Radio noise floor in dBm at the end of the interval | +| 202 | `LPP_PERCENTAGE` (120) | TX airtime percentage over the elapsed interval | +| 203 | `LPP_PERCENTAGE` (120) | RX airtime percentage over the elapsed interval | +| 204 | `LPP_TEMPERATURE` (103) | MCU temperature in degrees C, when supported | + +These channels are dedicated to history. Existing self telemetry and GPS use channel 1; +`EnvironmentSensorManager` assigns at most 16 active entries to channels 2–17. Channels +200–204 therefore do not collide with current repeater telemetry. Custom sensor managers +should leave this range free. History channels do not change the channels in `0x03`. + +Battery averaging reduces the effect of short voltage dips during transmission. Noise +floor and temperature are point samples. Recording advances on fixed interval boundaries +without accumulating loop delays; the airtime denominator uses a separate actual +measurement timestamp. TX/RX values are unsigned counter deltas in +milliseconds divided by the actual elapsed interval, multiplied by 100. Percentages +use the sensor protocol's integer LPP encoding, so fractional percentages are truncated. +NaN temperatures and the radio driver's uncalibrated noise-floor sentinel (0 dBm) +are skipped. At most five series are returned, below the eight-series reply limit. + +## Query and retention + +Use the [sensor-compatible `0x04` request](payloads.md#get-minmaxave-sensor-and-repeater-nodes): +start and end are seconds ago, followed by two zero reserved bytes. For example, +`start=3600, end=0` selects samples from the last hour, including age zero and excluding +age 3600. The reply echoes the request timestamp, adds the current RTC time, and then +encodes each series as channel, LPP type, min, max, average. There is no series count. +Empty series are omitted; an empty range returns just the eight-byte header. + +Sampling and queries use monotonic uptime, accumulated across `millis()` wraps. The +RTC is used only for the response timestamp. Samples occupy a fixed interval grid +anchored at the first valid sample. Missed intervals are empty (NaN) slots; a gap +at least as long as the ring capacity expires the old ring. Late readings are assigned +to their interval boundary, so their reported age can differ by less than one interval. +Only one timestamp is stored per series. +Unsigned second differences handle seconds-counter wrap; retained samples and query +ranges must span less than one full 32-bit seconds cycle (about 136 years). + +The first sample is recorded after one interval. Each series retains the configured +number of interval slots, including missing intervals. History is lost on reboot and +is not written to flash. + +## Build flags + +| Flag | Default | Description | +|------|---------|-------------| +| `REPEATER_HISTORY_INTERVAL_SECS` | `300` | Positive recording interval in seconds | +| `REPEATER_HISTORY_SLOTS` | `288`, or `0` on STM32/RP2040 | Interval slots per series; nominally 24 hours at five-minute intervals when enabled | + +Set these using PlatformIO `build_flags`, for example `-D REPEATER_HISTORY_SLOTS=144` +for nominally 12 hours. `-D REPEATER_HISTORY_SLOTS=0` removes history members, +allocations, sampling, and handling of `0x04` entirely. STM32 and RP2040 builds default +to disabled history to conserve RAM; they can explicitly opt in with a smaller slot count. +There are no history CLI settings. + +For both nRF52 and ESP32, sample storage is `5 * slots * 4` bytes (one float per +interval), or 5,760 bytes at the defaults. Comparing enabled and disabled builds shows +168 additional bytes in the enclosing mesh object on both platforms (including padding), +for a total of 5,928 bytes plus allocator overhead for five arrays. Unsupported temperature still reserves +its series storage. Query results use temporary stack space, not retained history RAM. + +## Custom sensor sketch compatibility + +The old `examples/simple_sensor/TimeSeriesData.h` include forwards to the shared helper. +Deprecated `RTCClock*` overloads remain available for existing custom sketches. They +ignore the RTC and use a shared, wrap-safe `millis()` accumulator; callers should migrate +to explicit monotonic seconds. Call the legacy API regularly enough to observe each +`millis()` wrap (less than about 49 days between calls), and use one clock API consistently +for each series. The shared legacy clock is linked only when these overloads are used. + +The integer literal `0` is ambiguous between the seconds and pointer overloads. Use a +`uint32_t` variable (or `uint32_t(0)`) for uptime zero, and `nullptr` for a legacy null +clock argument. diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index b50d19d0..99cd35bb 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -1,5 +1,8 @@ #include "MyMesh.h" #include <algorithm> +#if REPEATER_HISTORY_SLOTS > 0 +#include <helpers/sensors/LPPDataHelpers.h> +#endif /* ------------------------------ Config -------------------------------- */ @@ -46,6 +49,9 @@ #define REQ_TYPE_GET_STATUS 0x01 // same as _GET_STATS #define REQ_TYPE_KEEP_ALIVE 0x02 #define REQ_TYPE_GET_TELEMETRY_DATA 0x03 +#if REPEATER_HISTORY_SLOTS > 0 +#define REQ_TYPE_GET_AVG_MIN_MAX 0x04 +#endif #define REQ_TYPE_GET_ACCESS_LIST 0x05 #define REQ_TYPE_GET_NEIGHBOURS 0x06 #define REQ_TYPE_GET_OWNER_INFO 0x07 // FIRMWARE_VER_LEVEL >= 2 @@ -209,6 +215,7 @@ uint8_t MyMesh::handleAnonClockReq(const mesh::Identity& sender, uint32_t sender } int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t *payload, size_t payload_len) { + if (payload_len == 0) return 0; // uint32_t now = getRTCClock()->getCurrentTimeUnique(); // memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag') @@ -259,6 +266,48 @@ int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t memcpy(&reply_data[4], telemetry.getBuffer(), tlen); return 4 + tlen; // reply_len } +#if REPEATER_HISTORY_SLOTS > 0 + if (payload[0] == REQ_TYPE_GET_AVG_MIN_MAX && payload_len >= 11 && + (sender->permissions & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { + uint32_t start_secs_ago, end_secs_ago; + memcpy(&start_secs_ago, &payload[1], 4); + memcpy(&end_secs_ago, &payload[5], 4); + MinMaxAvg data[8]; + int n = 0; + if (payload[9] == 0 && payload[10] == 0) { + uint32_t now_secs = uptime_millis / 1000; + battery_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n++], HISTORY_BATTERY, + LPP_VOLTAGE); + noise_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n++], HISTORY_NOISE, + LPP_ANALOG_INPUT); + tx_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n++], HISTORY_TX, + LPP_PERCENTAGE); + rx_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n++], HISTORY_RX, + LPP_PERCENTAGE); + temperature_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n], HISTORY_TEMPERATURE, + LPP_TEMPERATURE); + // Unsupported temperature sensors and empty ranges have no encodable LPP value. + if (!isnan(data[n]._avg)) n++; + } + uint8_t ofs = 4; + uint32_t now = getRTCClock()->getCurrentTime(); + memcpy(&reply_data[ofs], &now, 4); + ofs += 4; + for (int i = 0; i < n; i++) { + auto d = &data[i]; + if (isnan(d->_avg)) continue; + reply_data[ofs++] = d->_channel; + reply_data[ofs++] = d->_lpp_type; + uint8_t sz = LPPData::getDataSize(d->_lpp_type); + uint32_t mult = LPPData::getMultiplier(d->_lpp_type); + bool is_signed = LPPData::isSigned(d->_lpp_type); + ofs += LPPData::putFloat(&reply_data[ofs], d->_min, sz, mult, is_signed); + ofs += LPPData::putFloat(&reply_data[ofs], d->_max, sz, mult, is_signed); + ofs += LPPData::putFloat(&reply_data[ofs], d->_avg, sz, mult, is_signed); + } + return ofs; + } +#endif if (payload[0] == REQ_TYPE_GET_ACCESS_LIST && sender->isAdmin()) { uint8_t res1 = payload[1]; // reserved for future (extra query params) uint8_t res2 = payload[2]; @@ -862,6 +911,13 @@ void MyMesh::sendNodeDiscoverReq() { MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondClock &ms, mesh::RNG &rng, mesh::RTCClock &rtc, mesh::MeshTables &tables) : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables), +#if REPEATER_HISTORY_SLOTS > 0 + battery_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS), + noise_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS), + tx_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS), + rx_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS), + temperature_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS), +#endif region_map(key_store), temp_map(key_store), _cli(board, rtc, sensors, region_map, acl, &_prefs, this), telemetry(MAX_PACKET_PAYLOAD - 4), @@ -876,6 +932,12 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc { last_millis = 0; uptime_millis = 0; +#if REPEATER_HISTORY_SLOTS > 0 + history_last_secs = history_battery_secs = history_airtime_secs = 0; + history_tx_millis = history_rx_millis = 0; + history_battery_total = 0; + history_battery_count = 0; +#endif next_local_advert = next_flood_advert = 0; dirty_contacts_expiry = 0; set_radio_at = revert_radio_at = 0; @@ -1286,7 +1348,48 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply } } +#if REPEATER_HISTORY_SLOTS > 0 +void MyMesh::recordHistory() { + uint32_t now_secs = uptime_millis / 1000; + // Average periodic reads without repeatedly enabling the battery divider. + if (uint32_t(now_secs - history_battery_secs) >= 15) { + history_battery_total += board.getBattMilliVolts(); + history_battery_count++; + history_battery_secs = now_secs; + } + uint32_t elapsed_secs = now_secs - history_last_secs; + if (elapsed_secs < REPEATER_HISTORY_INTERVAL_SECS) return; + // Advance the sampling grid without accumulating loop delays or replaying missed slots. + history_last_secs += (elapsed_secs / REPEATER_HISTORY_INTERVAL_SECS) * REPEATER_HISTORY_INTERVAL_SECS; + uint32_t airtime_elapsed_secs = now_secs - history_airtime_secs; + + if (history_battery_count > 0) { + battery_history.recordData(history_last_secs, history_battery_total / history_battery_count / 1000.0f); + } + int noise_floor = _radio->getNoiseFloor(); + if (noise_floor != 0) noise_history.recordData(history_last_secs, noise_floor); // zero means uncalibrated + uint32_t tx_millis = getTotalAirTime(); + uint32_t rx_millis = getReceiveAirTime(); + // Counters are milliseconds; unsigned subtraction also handles their wrap. + tx_history.recordData(history_last_secs, uint32_t(tx_millis - history_tx_millis) / (airtime_elapsed_secs * 10.0f)); + rx_history.recordData(history_last_secs, uint32_t(rx_millis - history_rx_millis) / (airtime_elapsed_secs * 10.0f)); + temperature_history.recordData(history_last_secs, board.getMCUTemperature()); // ignores NaN + history_airtime_secs = now_secs; + history_tx_millis = tx_millis; + history_rx_millis = rx_millis; + history_battery_total = 0; + history_battery_count = 0; +} +#endif + void MyMesh::loop() { + // Update before dispatching requests, including across millis() wrap. + uint32_t now = millis(); + uptime_millis += uint32_t(now - last_millis); + last_millis = now; +#if REPEATER_HISTORY_SLOTS > 0 + recordHistory(); +#endif #ifdef WITH_BRIDGE bridge.loop(); #endif @@ -1324,11 +1427,6 @@ void MyMesh::loop() { acl.save(_fs); dirty_contacts_expiry = 0; } - - // update uptime - uint32_t now = millis(); - uptime_millis += now - last_millis; - last_millis = now; } // To check if there is pending work diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index dc893258..2fbdd872 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -37,6 +37,22 @@ #include <helpers/RoutingPolicy.h> #include "RateLimiter.h" +#ifndef REPEATER_HISTORY_SLOTS +#if defined(STM32_PLATFORM) || defined(RP2040_PLATFORM) +#define REPEATER_HISTORY_SLOTS 0 +#else +#define REPEATER_HISTORY_SLOTS 288 +#endif +#endif +#ifndef REPEATER_HISTORY_INTERVAL_SECS +#define REPEATER_HISTORY_INTERVAL_SECS 300 +#endif + +#if REPEATER_HISTORY_SLOTS > 0 +#include <helpers/TimeSeriesData.h> +static_assert(REPEATER_HISTORY_INTERVAL_SECS > 0, "History interval must be positive"); +#endif + #ifdef WITH_BRIDGE extern AbstractBridge* bridge; #endif @@ -82,6 +98,16 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { FILESYSTEM* _fs; uint32_t last_millis; uint64_t uptime_millis; +#if REPEATER_HISTORY_SLOTS > 0 + // Dedicated history channels 200..204; environment telemetry occupies 1..17. + enum { HISTORY_BATTERY = 200, HISTORY_NOISE, HISTORY_TX, HISTORY_RX, HISTORY_TEMPERATURE }; + TimeSeriesData battery_history, noise_history, tx_history, rx_history, temperature_history; + uint32_t history_last_secs, history_battery_secs, history_airtime_secs; + uint32_t history_tx_millis, history_rx_millis; + float history_battery_total; + uint32_t history_battery_count; + void recordHistory(); +#endif unsigned long next_local_advert, next_flood_advert; bool _logging; NodePrefs _prefs; diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index b1860668..bb747f63 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -789,7 +789,9 @@ SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::Millise { next_local_advert = next_flood_advert = 0; dirty_contacts_expiry = 0; - last_read_time = 0; + last_read_time = uint32_t(0) - SENSOR_READ_INTERVAL_SECS; // read immediately on the first loop + last_millis = 0; + uptime_millis = 0; num_alert_tasks = 0; set_radio_at = revert_radio_at = 0; recv_pkt_region = NULL; @@ -999,6 +1001,9 @@ bool SensorMesh::getGPS(uint8_t channel, float& lat, float& lon, float& alt) { } void SensorMesh::loop() { + uint32_t now = millis(); + uptime_millis += uint32_t(now - last_millis); + last_millis = now; mesh::Mesh::loop(); if (next_flood_advert && millisHasNowPassed(next_flood_advert)) { @@ -1028,7 +1033,8 @@ void SensorMesh::loop() { } uint32_t curr = getRTCClock()->getCurrentTime(); - if (curr >= last_read_time + SENSOR_READ_INTERVAL_SECS) { + uint32_t uptime_secs = getUptimeSeconds(); + if (uint32_t(uptime_secs - last_read_time) >= SENSOR_READ_INTERVAL_SECS) { telemetry.reset(); telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f); // query other sensors -- target specific @@ -1069,7 +1075,7 @@ void SensorMesh::loop() { onSensorDataRead(); - last_read_time = curr; + last_read_time = uptime_secs; } // check the alert send queue diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index 590ca0c7..e98fa571 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -3,7 +3,7 @@ #include <Arduino.h> // needed for PlatformIO #include <Mesh.h> -#include "TimeSeriesData.h" +#include <helpers/TimeSeriesData.h> #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) #include <InternalFileSystem.h> @@ -88,6 +88,7 @@ public: void sendFloodReply(mesh::Packet* packet, unsigned long delay_millis, uint8_t path_hash_size); protected: + uint32_t getUptimeSeconds() const { return uptime_millis / 1000; } // current telemetry data queries float getVoltage(uint8_t channel) { return getTelemValue(channel, LPP_VOLTAGE); } float getCurrent(uint8_t channel) { return getTelemValue(channel, LPP_CURRENT); } @@ -154,6 +155,8 @@ private: RegionEntry* load_stack[8]; TransportKey default_scope; uint32_t last_read_time; + uint32_t last_millis; + uint64_t uptime_millis; int matching_peer_indexes[MAX_SEARCH_RESULTS]; int num_alert_tasks; Trigger* alert_tasks[MAX_CONCURRENT_ALERTS]; diff --git a/examples/simple_sensor/TimeSeriesData.cpp b/examples/simple_sensor/TimeSeriesData.cpp deleted file mode 100644 index f6157f9a..00000000 --- a/examples/simple_sensor/TimeSeriesData.cpp +++ /dev/null @@ -1,45 +0,0 @@ -#include "TimeSeriesData.h" - -void TimeSeriesData::recordData(mesh::RTCClock* clock, float value) { - uint32_t now = clock->getCurrentTime(); - if (now >= last_timestamp + interval_secs) { - last_timestamp = now; - - data[next] = value; // append to cycle table - next = (next + 1) % num_slots; - } -} - -void TimeSeriesData::calcMinMaxAvg(mesh::RTCClock* clock, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg* dest, uint8_t channel, uint8_t lpp_type) const { - int i = next, n = num_slots; - uint32_t ago = clock->getCurrentTime() - last_timestamp; - int num_values = 0; - float total = 0.0f; - - dest->_channel = channel; - dest->_lpp_type = lpp_type; - - // start at most recet recording, back-track through to oldest - while (n > 0) { - n--; - i = (i + num_slots - 1) % num_slots; // go back by one - if (ago >= end_secs_ago && ago < start_secs_ago) { // filter by the desired time range - float v = data[i]; - num_values++; - total += v; - if (num_values == 1) { - dest->_max = dest->_min = v; - } else { - if (v < dest->_min) dest->_min = v; - if (v > dest->_max) dest->_max = v; - } - } - ago += interval_secs; - } - // calc average - if (num_values > 0) { - dest->_avg = total / num_values; - } else { - dest->_max = dest->_min = dest->_avg = NAN; - } -} diff --git a/examples/simple_sensor/TimeSeriesData.h b/examples/simple_sensor/TimeSeriesData.h index 6efa7834..41bf3189 100644 --- a/examples/simple_sensor/TimeSeriesData.h +++ b/examples/simple_sensor/TimeSeriesData.h @@ -1,29 +1,4 @@ #pragma once -#include <Arduino.h> -#include <Mesh.h> - -struct MinMaxAvg { - float _min, _max, _avg; - uint8_t _lpp_type, _channel; -}; - -class TimeSeriesData { - float* data; - int num_slots, next; - uint32_t last_timestamp; - uint32_t interval_secs; - -public: - TimeSeriesData(float* array, int num, uint32_t secs) : num_slots(num), data(array), last_timestamp(0), next(0), interval_secs(secs) { - memset(data, 0, sizeof(float)*num); - } - TimeSeriesData(int num, uint32_t secs) : num_slots(num), last_timestamp(0), next(0), interval_secs(secs) { - data = new float[num]; - memset(data, 0, sizeof(float)*num); - } - - void recordData(mesh::RTCClock* clock, float value); - void calcMinMaxAvg(mesh::RTCClock* clock, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg* dest, uint8_t channel, uint8_t lpp_type) const; -}; - +// Compatibility include for custom sensor sketches; implementation lives in src/helpers. +#include <helpers/TimeSeriesData.h> diff --git a/examples/simple_sensor/main.cpp b/examples/simple_sensor/main.cpp index 66991daa..6d455f73 100644 --- a/examples/simple_sensor/main.cpp +++ b/examples/simple_sensor/main.cpp @@ -21,13 +21,14 @@ protected: void onSensorDataRead() override { float batt_voltage = getVoltage(TELEM_CHANNEL_SELF); - battery_data.recordData(getRTCClock(), batt_voltage); // record battery + battery_data.recordData(getUptimeSeconds(), batt_voltage); // record battery alertIf(batt_voltage < 3.4f, critical_batt, HIGH_PRI_ALERT, "Battery is critical!"); alertIf(batt_voltage < 3.6f, low_batt, LOW_PRI_ALERT, "Battery is low"); } int querySeriesData(uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg dest[], int max_num) override { - battery_data.calcMinMaxAvg(getRTCClock(), start_secs_ago, end_secs_ago, &dest[0], TELEM_CHANNEL_SELF, LPP_VOLTAGE); + battery_data.calcMinMaxAvg(getUptimeSeconds(), start_secs_ago, end_secs_ago, &dest[0], TELEM_CHANNEL_SELF, + LPP_VOLTAGE); return 1; } diff --git a/platformio.ini b/platformio.ini index f66fbf2e..7fdc8b64 100644 --- a/platformio.ini +++ b/platformio.ini @@ -174,6 +174,7 @@ build_src_filter = +<../src/Packet.cpp> +<../src/helpers/ConfigSerializer.cpp> +<../src/helpers/DynamicConfigSerializer.cpp> + +<../src/helpers/TimeSeriesData.cpp> lib_deps = google/googletest @ 1.17.0 diff --git a/src/helpers/TimeSeriesData.cpp b/src/helpers/TimeSeriesData.cpp new file mode 100644 index 00000000..371433c6 --- /dev/null +++ b/src/helpers/TimeSeriesData.cpp @@ -0,0 +1,91 @@ +#include "TimeSeriesData.h" + +#include <Arduino.h> +#include <math.h> + +TimeSeriesData::TimeSeriesData(float *array, int num, uint32_t secs) + : data(array), num_slots(num > 0 ? num : 0), next(0), count(0), last_timestamp(0), interval_secs(secs), + owns_data(array == nullptr) { + if (num_slots > 0) { + if (owns_data) data = new float[num_slots]; + } +} + +TimeSeriesData::~TimeSeriesData() { + if (owns_data) delete[] data; +} + +void TimeSeriesData::recordData(uint32_t now_secs, float value) { + if (num_slots == 0 || isnan(value)) return; + uint32_t steps = 1; + if (count > 0 && interval_secs > 0) { + uint32_t elapsed = now_secs - last_timestamp; + if (elapsed < interval_secs) return; + steps = elapsed / interval_secs; + last_timestamp += steps * interval_secs; // keep a fixed sampling grid + } else { + last_timestamp = now_secs; + } + + // A long pause expires the whole ring in O(capacity), never O(elapsed time). + if (steps >= uint32_t(num_slots)) { + next = count = 0; + } else { + for (uint32_t i = 1; i < steps; i++) { + data[next] = NAN; + next = (next + 1) % num_slots; + if (count < num_slots) count++; + } + } + + data[next] = value; + next = (next + 1) % num_slots; + if (count < num_slots) count++; +} + +void TimeSeriesData::calcMinMaxAvg(uint32_t now_secs, uint32_t start_secs_ago, uint32_t end_secs_ago, + MinMaxAvg *dest, uint8_t channel, uint8_t lpp_type) const { + dest->_channel = channel; + dest->_lpp_type = lpp_type; + dest->_min = dest->_max = dest->_avg = NAN; + int num_values = 0; + float total = 0.0f; + int i = next; + uint64_t ago = uint32_t(now_secs - last_timestamp); + for (int n = 0; n < count; n++) { + i = (i + num_slots - 1) % num_slots; + if (ago >= end_secs_ago && ago < start_secs_ago && !isnan(data[i])) { + float v = data[i]; + if (num_values == 0) { + dest->_min = dest->_max = v; + } else { + if (v < dest->_min) dest->_min = v; + if (v > dest->_max) dest->_max = v; + } + total += v; + num_values++; + } + ago += interval_secs; + } + if (num_values > 0) dest->_avg = total / num_values; +} + +// Shared only by legacy callers; never consult the RTC, even after a time sync. +// At least one legacy call is required per millis() wrap (about 49 days). +static uint32_t legacyMonotonicSeconds() { + static uint32_t last_millis = 0; + static uint64_t uptime_millis = 0; + uint32_t now = millis(); + uptime_millis += uint32_t(now - last_millis); + last_millis = now; + return uptime_millis / 1000; +} + +void TimeSeriesData::recordData(mesh::RTCClock *, float value) { + recordData(legacyMonotonicSeconds(), value); +} + +void TimeSeriesData::calcMinMaxAvg(mesh::RTCClock *, uint32_t start_secs_ago, uint32_t end_secs_ago, + MinMaxAvg *dest, uint8_t channel, uint8_t lpp_type) const { + calcMinMaxAvg(legacyMonotonicSeconds(), start_secs_ago, end_secs_ago, dest, channel, lpp_type); +} diff --git a/src/helpers/TimeSeriesData.h b/src/helpers/TimeSeriesData.h new file mode 100644 index 00000000..3b7cdd47 --- /dev/null +++ b/src/helpers/TimeSeriesData.h @@ -0,0 +1,38 @@ +#pragma once + +#include <stdint.h> + +namespace mesh { +class RTCClock; +} + +struct MinMaxAvg { + float _min, _max, _avg; + uint8_t _lpp_type, _channel; +}; + +class TimeSeriesData { + float *data; + int num_slots, next, count; + uint32_t last_timestamp, interval_secs; + bool owns_data; + +public: + TimeSeriesData(float *array, int num, uint32_t secs); + TimeSeriesData(int num, uint32_t secs) : TimeSeriesData(nullptr, num, secs) {} + ~TimeSeriesData(); + TimeSeriesData(const TimeSeriesData &) = delete; + TimeSeriesData &operator=(const TimeSeriesData &) = delete; + + // Caller supplies monotonic seconds, accumulated across millisecond clock wraps. + void recordData(uint32_t now_secs, float value); + void calcMinMaxAvg(uint32_t now_secs, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg *dest, + uint8_t channel, uint8_t lpp_type) const; + + // Compatibility for custom sensor sketches. The RTC argument is ignored. + [[deprecated("Pass monotonic seconds instead of RTCClock*")]] + void recordData(mesh::RTCClock *clock, float value); + [[deprecated("Pass monotonic seconds instead of RTCClock*")]] + void calcMinMaxAvg(mesh::RTCClock *clock, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg *dest, + uint8_t channel, uint8_t lpp_type) const; +}; diff --git a/test/test_time_series/test_time_series.cpp b/test/test_time_series/test_time_series.cpp new file mode 100644 index 00000000..eeb1aa6e --- /dev/null +++ b/test/test_time_series/test_time_series.cpp @@ -0,0 +1,138 @@ +#include <Arduino.h> +#include <MeshCore.h> +#include <cmath> +#include <gtest/gtest.h> +#include <helpers/TimeSeriesData.h> +#include <utility> + +static MinMaxAvg query(const TimeSeriesData &series, uint32_t now, uint32_t start, uint32_t end) { + MinMaxAvg result; + series.calcMinMaxAvg(now, start, end, &result, 200, 116); + return result; +} + +TEST(TimeSeriesData, RingWrapKeepsNewestSamples) { + TimeSeriesData series(3, 10); + for (uint32_t i = 1; i <= 5; i++) + series.recordData(i * 10, float(i)); + auto result = query(series, 50, 100, 0); + EXPECT_FLOAT_EQ(result._min, 3); + EXPECT_FLOAT_EQ(result._max, 5); + EXPECT_FLOAT_EQ(result._avg, 4); + EXPECT_EQ(result._channel, 200); + EXPECT_EQ(result._lpp_type, 116); +} + +TEST(TimeSeriesData, RangeIncludesEndAndExcludesStart) { + TimeSeriesData series(4, 10); + series.recordData(10, -5); + series.recordData(20, -3); + series.recordData(30, -1); + series.recordData(40, 7); + auto result = query(series, 40, 30, 10); + EXPECT_FLOAT_EQ(result._min, -3); + EXPECT_FLOAT_EQ(result._max, -1); + EXPECT_FLOAT_EQ(result._avg, -2); +} + +TEST(TimeSeriesData, EmptyAndUnwrittenRangesReturnNaN) { + TimeSeriesData series(4, 10); + EXPECT_TRUE(std::isnan(query(series, 0, 100, 0)._avg)); + series.recordData(10, 4); + for (auto range : { std::pair<uint32_t, uint32_t>(100, 1), { 0, 0 }, { 1, 10 } }) { + auto result = query(series, 10, range.first, range.second); + EXPECT_TRUE(std::isnan(result._min)); + EXPECT_TRUE(std::isnan(result._max)); + EXPECT_TRUE(std::isnan(result._avg)); + } +} + +TEST(TimeSeriesData, CadenceAndNaNSamples) { + float storage[3]; + TimeSeriesData series(storage, 3, 10); + series.recordData(uint32_t(0), 2); // uptime zero is a valid first sample + series.recordData(9, 100); + EXPECT_FLOAT_EQ(query(series, 9, 100, 0)._avg, 2); + series.recordData(10, 4); + series.recordData(19, 100); + series.recordData(20, NAN); + series.recordData(20, 6); + EXPECT_FLOAT_EQ(query(series, 20, 100, 0)._avg, 4); +} + +TEST(TimeSeriesData, LargeGapsExpireOldSamplesAndDoNotStall) { + TimeSeriesData series(4, 300); + series.recordData(300, 1); + const uint32_t later = UINT32_MAX / 300 * 300; + series.recordData(later, 3); + EXPECT_FLOAT_EQ(query(series, later, 301, 0)._avg, 3); + EXPECT_FLOAT_EQ(query(series, later, UINT32_MAX, 0)._avg, 3); + series.recordData(later + uint32_t(300), 5); // seconds counter wrap + auto result = query(series, later + uint32_t(300), 301, 0); + EXPECT_FLOAT_EQ(result._min, 3); + EXPECT_FLOAT_EQ(result._max, 5); + EXPECT_FLOAT_EQ(result._avg, 4); +} + +TEST(TimeSeriesData, MissingIntervalsAreEmptyInsteadOfMovingOldSamplesForward) { + TimeSeriesData series(5, 10); + series.recordData(10, 2); + series.recordData(40, 8); + EXPECT_TRUE(std::isnan(query(series, 40, 30, 1)._avg)); + EXPECT_FLOAT_EQ(query(series, 40, 31, 0)._avg, 5); + series.recordData(52, 10); // late read belongs to the fixed slot at 50 + EXPECT_FLOAT_EQ(query(series, 52, 3, 0)._avg, 10); + EXPECT_TRUE(std::isnan(query(series, 52, 2, 0)._avg)); +} + +TEST(TimeSeriesData, QueryAgeDoesNotOverflowWhileWalkingTheRing) { + TimeSeriesData series(3, 10); + series.recordData(10, 1); + series.recordData(20, 2); + EXPECT_TRUE(std::isnan(query(series, uint32_t(20 + (UINT32_MAX - 5)), 100, 0)._avg)); +} + +TEST(TimeSeriesData, LegacyClockAPIUsesMonotonicTimeAcrossRTCAndMillisWrap) { + class Clock : public mesh::RTCClock { + public: + uint32_t time = 100000; + int reads = 0; + uint32_t getCurrentTime() override { + reads++; + return time; + } + void setCurrentTime(uint32_t value) override { time = value; } + } clock; + TimeSeriesData series(3, 1); + g_mock_millis = UINT32_MAX - 499; + series.recordData(&clock, 2); + clock.setCurrentTime(0); + g_mock_millis = 500; + series.recordData(&clock, 4); + MinMaxAvg result; + series.calcMinMaxAvg(&clock, 2, 0, &result, 1, 116); + EXPECT_FLOAT_EQ(result._avg, 3); + EXPECT_EQ(clock.reads, 0); +} + +TEST(TimeSeriesData, MillisecondCounterWrapDoesNotResetSeconds) { + TimeSeriesData series(3, 1); + uint32_t last_millis = UINT32_MAX - 499; + uint64_t uptime_millis = last_millis; + series.recordData(uint32_t(uptime_millis / 1000), 1); + uint32_t now = 500; + uptime_millis += uint32_t(now - last_millis); + series.recordData(uint32_t(uptime_millis / 1000), 3); + EXPECT_FLOAT_EQ(query(series, uint32_t(uptime_millis / 1000), 2, 0)._avg, 2); +} + +TEST(TimeSeriesData, ZeroCapacityIsEmpty) { + TimeSeriesData series(0, 10); + series.recordData(100, 1); + EXPECT_TRUE(std::isnan(query(series, 100, 1000, 0)._avg)); +} + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} From 3f23ba9b2dd2cfc471842d8ddbd6e71f0549118b Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko <tishenko.alexandr@gmail.com> Date: Sun, 8 Nov 2026 18:07:58 +0200 Subject: [PATCH 360/381] Companion: set/get adc.multiplier CLI command, persisted in prefs Repeaters, room servers and sensors already let the battery ADC multiplier be tuned with 'set adc.multiplier' (CommonCLI). The companion firmware had no equivalent, so a board whose divider differs from the build default (common on DIY ProMicro / Faketec boards) always reported a wrong battery voltage. Adds the same command to the companion CLI. The value is stored in the companion prefs (comp.adc_mult, 0 = board default) and applied at startup via MainBoard::setAdcMultiplier(). --- docs/companion_cli.md | 14 ++++++++++++++ examples/companion_radio/MyMesh.cpp | 29 ++++++++++++++++++++++++++++ examples/companion_radio/NodePrefs.h | 2 ++ 3 files changed, 45 insertions(+) diff --git a/docs/companion_cli.md b/docs/companion_cli.md index 31a05584..cbc4773a 100644 --- a/docs/companion_cli.md +++ b/docs/companion_cli.md @@ -65,6 +65,20 @@ Since version 1.18 meshcore companion radio firmware has a CLI interface, which --- +#### Fine-tune the battery reading +**Usage:** +- `get adc.multiplier` +- `set adc.multiplier <value>` + +**Parameters:** +- `value`: ADC multiplier (0.0-10.0) + +**Default:** `0.0` (value defined by board) + +**Note:** Returns "Error: unsupported" if the board doesn't support it. Same command as on repeaters, for boards whose battery divider resistors vary (e.g. DIY ProMicro / Faketec). + +--- + ### Radio Radio parameters are common to all roles and handled by `CommonRadioPrefs`. diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 755c56d1..fd7dcd18 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -993,6 +993,8 @@ void MyMesh::begin() { _prefs.tx_power_dbm = constrain(_prefs.tx_power_dbm, -9, MAX_LORA_TX_POWER); _prefs.gps_enabled = constrain(_prefs.gps_enabled, 0, 1); // Ensure boolean 0 or 1 _prefs.gps_interval = constrain(_prefs.gps_interval, 0, 86400); // Max 24 hours + _prefs.adc_multiplier = constrain(_prefs.adc_multiplier, 0.0f, 10.0f); + if (!board.setAdcMultiplier(_prefs.adc_multiplier)) _prefs.adc_multiplier = 0.0f; _active_ble_pin = _prefs.ble_pin; @@ -2210,6 +2212,33 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* return true; } + if (memcmp(command, "set adc.multiplier ", 19) == 0) { // same as CommonCLI + float mult = atof(&command[19]); + if (mult < 0.0f || mult > 10.0f) { + strcpy(reply, "Error, must be from 0 to 10"); + } else if (board.setAdcMultiplier(mult)) { + _prefs.adc_multiplier = mult; + savePrefs(); + if (mult == 0.0f) { + strcpy(reply, "OK - using default board multiplier"); + } else { + sprintf(reply, "OK - multiplier set to %.3f", mult); + } + } else { + strcpy(reply, "Error: unsupported"); + } + return true; + } + if (strcmp(command, "get adc.multiplier") == 0) { + float mult = board.getAdcMultiplier(); + if (mult == 0.0f) { + strcpy(reply, "Error: unsupported"); + } else { + sprintf(reply, "> %.3f", mult); + } + return true; + } + if (strcmp(command, "get tz.offset") == 0) { float q = _prefs.tz_offset * 4; sprintf(reply, (q == (int)q && ((int)q & 1)) ? "> %.2f" : "> %.1f", _prefs.tz_offset); diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index c5d1df04..88770dcf 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -48,6 +48,7 @@ public: char default_scope_name[31]; uint8_t default_scope_key[16]; float tz_offset = 0; + float adc_multiplier = 0; // battery ADC multiplier, 0 = board default #ifdef ENABLE_WIFI_INTERFACE #ifndef WIFI_SSID #define WIFI_SSID "" @@ -194,6 +195,7 @@ private: def("tel_loc", _parent->telemetry_mode_loc); def("tel_env", _parent->telemetry_mode_env); def("tz_offset", _parent->tz_offset); + def("adc_mult", _parent->adc_multiplier); } public: CompanionPrefs(NodePrefs* parent) : _parent(parent) { } From 978f2662c686f98beec0884c14be5df29053a376 Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko <tishenko.alexandr@gmail.com> Date: Sun, 8 Nov 2026 23:24:29 +0200 Subject: [PATCH 361/381] NmeaGpsDriver: optional UART baud rate autodetection (GPS_BAUD_AUTODETECT) Bytes arriving on the UART does not mean the baud rate is right: at the wrong rate the parser only sees garbage and never gets a fix. Modules such as the M5Stack GROVE GPS now default to 115200, while boards configure 9600. With GPS_BAUD_AUTODETECT, detect() probes common GNSS rates, starting with the configured one, and keeps the first one that yields an NMEA sentence with a valid checksum. The rate is stored in the driver, so later power cycles reopen the UART with it. Without the flag nothing changes. Ported from #3729 onto the GpsDriver refactor. --- src/helpers/sensors/NmeaGpsDriver.h | 79 +++++++++++++++++++++++++++-- 1 file changed, 74 insertions(+), 5 deletions(-) diff --git a/src/helpers/sensors/NmeaGpsDriver.h b/src/helpers/sensors/NmeaGpsDriver.h index 25acff45..37cb92b2 100644 --- a/src/helpers/sensors/NmeaGpsDriver.h +++ b/src/helpers/sensors/NmeaGpsDriver.h @@ -4,6 +4,9 @@ #include <Arduino.h> #include <helpers/RefCountedDigitalPin.h> +#include <MeshCore.h> +#include <stdlib.h> +#include <string.h> #ifndef UART_TYPE #ifdef NRF52_PLATFORM @@ -115,6 +118,68 @@ class NmeaGpsDriver : public GpsDriver { _started = true; } +#ifdef GPS_BAUD_AUTODETECT + void reopenSerial(uint32_t baud) { + _hardwareSerial->end(); + if (_txPin != -1 && _rxPin != -1) { + _hardwareSerial->setPins(_txPin, _rxPin); + } + _hardwareSerial->begin(baud); + drain(); + } + + // True if a complete NMEA sentence with a valid checksum arrives within timeout_ms. + bool seesValidNmea(uint32_t timeout_ms) { + char line[100]; + int len = -1; // -1 = waiting for '$' + const uint32_t start = millis(); + while ((uint32_t)(millis() - start) < timeout_ms) { + if (available() <= 0) { delay(2); continue; } + const char c = (char)read(); + if (c == '$') { len = 0; continue; } + if (len < 0) continue; + if (c == '\r' || c == '\n') { + line[len] = '\0'; + const char* star = strchr(line, '*'); + if (star != nullptr && strlen(star) >= 3) { + uint8_t sum = 0; + for (const char* p = line; p < star; p++) sum ^= (uint8_t)*p; + if (sum == (uint8_t)strtoul(star + 1, nullptr, 16)) return true; + } + len = -1; + } else if (len < (int)sizeof(line) - 1) { + line[len++] = c; + } else { + len = -1; // longer than any NMEA sentence: wrong baud rate + } + } + return false; + } + + // Bytes arriving does not mean the baud rate is right: at the wrong rate the + // parser only sees garbage and never gets a fix. Probe common GNSS rates, + // starting with the configured one, and keep the first that yields valid NMEA. + // The rate is kept in _baudRate, so later power cycles reopen the UART with it. + void detectBaudRate() { + static const uint32_t bauds[] = { GPS_BAUD_RATE, 9600, 115200, 38400, 57600, 19200, 4800 }; + const uint32_t configured = _baudRate; + for (size_t i = 0; i < sizeof(bauds) / sizeof(bauds[0]); i++) { + bool tried = false; + for (size_t j = 0; j < i; j++) tried |= (bauds[j] == bauds[i]); + if (tried) continue; + reopenSerial(bauds[i]); + if (seesValidNmea(2000)) { + _baudRate = bauds[i]; + MESH_DEBUG_PRINTLN("GPS baud rate: %lu", (unsigned long)_baudRate); + return; + } + } + _baudRate = configured; + reopenSerial(_baudRate); + MESH_DEBUG_PRINTLN("GPS baud rate not detected, using %lu", (unsigned long)_baudRate); + } +#endif + void stopHardware() { if (!_started) return; @@ -220,14 +285,18 @@ public: } bool detect(uint32_t timeout_ms) override { - if (available() > 0) return true; + bool found = available() > 0; const uint32_t deadline = millis() + timeout_ms; - while ((int32_t)(millis() - deadline) < 0) { - if (available() > 0) return true; - delay(10); + while (!found && (int32_t)(millis() - deadline) < 0) { + found = available() > 0; + if (!found) delay(10); } - return false; +#ifdef GPS_BAUD_AUTODETECT + // only on a real detection (timeout > 0), not on the quick "still active?" polls + if (found && timeout_ms > 0 && _started && _hardwareSerial != nullptr) detectBaudRate(); +#endif + return found; } int available() { From 6b3da8a2b1eb58d1a4cc7c2a1b935237c70f43e0 Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko <tishenko.alexandr@gmail.com> Date: Sun, 8 Nov 2026 23:37:54 +0200 Subject: [PATCH 362/381] GPS: optional anti-spoofing guard for position and time (GPS_GUARD) A spoofed GPS signal can move a fixed node anywhere and set its clock to any time; the clock only moves forward, so a time pushed into the future breaks timestamps and replay protection until fixed by hand. With GPS_GUARD, MicroNMEALocationProvider asks a GpsGuard before a fix is stored as the last fix (satellites, HDOP, optional region box, fence around the configured position, jump speed, N stable fixes) and before GPS time is written to the clock (trusted fix current, not before the build date, small steps once the clock is valid, drift-sized after the first sync). Without a trusted fix no live position is reported. CLI in CommonGpsPrefs: 'gps guard', 'gps guard accept', 'gps fence', 'gps ref'; CommonCLI keeps the reference on set lat/lon and gps setloc, resets the time anchor on manual clock sets and adds 'time force'. Ported from #3736 onto the GpsDriver/LocationProvider refactor. --- docs/cli_commands.md | 17 ++ src/helpers/CommonCLI.cpp | 15 + src/helpers/CommonCLI.h | 5 + src/helpers/CommonGpsPrefs.cpp | 63 ++++ src/helpers/CommonGpsPrefs.h | 5 + .../sensors/EnvironmentSensorManager.cpp | 10 + src/helpers/sensors/GpsGuard.h | 275 ++++++++++++++++++ src/helpers/sensors/LocationProvider.h | 7 + .../sensors/MicroNMEALocationProvider.h | 54 +++- src/helpers/sensors/RakLocationProvider.h | 17 ++ 10 files changed, 466 insertions(+), 2 deletions(-) create mode 100644 src/helpers/sensors/GpsGuard.h diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 44ff3a25..e21b6a8e 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -69,6 +69,8 @@ This document provides an overview of CLI commands that can be sent to MeshCore **Parameters:** - `epoch_seconds`: Unix epoch time +**Note:** The clock only moves forward. To set it back (e.g. after the clock was pushed into the future by a wrong GPS time) use `time force <epoch_seconds>`. + --- ### Send a flood advert @@ -1077,6 +1079,21 @@ region save --- +#### GPS anti-spoofing guard (When built with `GPS_GUARD`) +With `GPS_GUARD`, a fix becomes the node's last fix (position, telemetry, adverts) only after it passes plausibility checks: at least `GPS_GUARD_MIN_SATS` satellites, HDOP ≤ `GPS_GUARD_MAX_HDOP10`/10, inside the optional build-time region (`GPS_GUARD_LAT_MIN/MAX`, `GPS_GUARD_LON_MIN/MAX`), within the fence around the node's configured `lat`/`lon` (if set), no jump faster than `GPS_GUARD_MAX_SPEED_KMH`, and `GPS_GUARD_STABLE_FIXES` consistent fixes in a row. An unverified position is never reported. + +GPS time is written to the clock only while such a fix is current, never earlier than the firmware build date, and, once the clock is valid, only within `GPS_GUARD_TIME_MAX_STEP` seconds for the first sync and within clock drift (`GPS_GUARD_TIME_DRIFT_BASE` s + `GPS_GUARD_TIME_DRIFT_PPM`) afterwards. Setting the clock manually (`time`, `time force`, `clock sync`) resets that anchor. + +Covers serial NMEA receivers (`MicroNMEALocationProvider`). + +**Usage:** +- `gps guard`: status, e.g. `> ok 7sat time ok +1s`, `> rej region time rej nofix`, or `... ALERT gps-clk +3600s 75m` when a trusted fix has disagreed with the clock by the same offset for `GPS_GUARD_ALERT_MIN` minutes. While the alert is active, the offset in hours is also reported in telemetry on the next free channel. +- `gps guard accept`: while an alert is active, confirm that the GPS time is right and apply it to the clock. +- `gps fence`, `gps fence <metres>`: fence radius around the configured `lat`/`lon` (`0` = off). Default `GPS_GUARD_FENCE_M` (1000), not saved. +- `gps ref`: the reference position; follows `set lat`, `set lon` and `gps setloc`. + +--- + #### Set this node's location based on the GPS coordinates **Usage:** - `gps setloc` diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index 978f9e06..fa3ad789 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -211,6 +211,7 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re uint32_t curr = getRTCClock()->getCurrentTime(); if (sender_timestamp > curr) { getRTCClock()->setCurrentTime(sender_timestamp + 1); + CommonGpsPrefs::onClockSetManually(*_sensors); uint32_t now = getRTCClock()->getCurrentTime(); DateTime dt = DateTime(now); sprintf(reply, "OK - clock set: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year()); @@ -225,11 +226,22 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re uint32_t now = getRTCClock()->getCurrentTime(); DateTime dt = DateTime(now); sprintf(reply, "%02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year()); + } else if (memcmp(command, "time force ", 11) == 0) { // set time, allowing it to go backwards + uint32_t secs = _atoi(&command[11]); + if (secs > 1700000000UL) { + getRTCClock()->setCurrentTime(secs); + CommonGpsPrefs::onClockSetManually(*_sensors); + DateTime dt = DateTime(getRTCClock()->getCurrentTime()); + sprintf(reply, "OK - clock forced: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year()); + } else { + strcpy(reply, "ERR: invalid epoch"); + } } else if (memcmp(command, "time ", 5) == 0) { // set time (to epoch seconds) uint32_t secs = _atoi(&command[5]); uint32_t curr = getRTCClock()->getCurrentTime(); if (secs > curr) { getRTCClock()->setCurrentTime(secs); + CommonGpsPrefs::onClockSetManually(*_sensors); uint32_t now = getRTCClock()->getCurrentTime(); DateTime dt = DateTime(now); sprintf(reply, "OK - clock set: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year()); @@ -357,6 +369,7 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re } else if (memcmp(command, "gps setloc", 10) == 0) { _prefs->node_lat = _sensors->node_lat; _prefs->node_lon = _sensors->node_lon; + _prefs->getGpsPrefs()->applyGuardReference(*_sensors); savePrefs(); strcpy(reply, "OK"); } else if (memcmp(command, "gps advert", 10) == 0) { @@ -495,10 +508,12 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep 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]); + _prefs->getGpsPrefs()->applyGuardReference(*_sensors); savePrefs(); strcpy(reply, "OK"); } else if (memcmp(config, "lon ", 4) == 0) { _prefs->node_lon = atof(&config[4]); + _prefs->getGpsPrefs()->applyGuardReference(*_sensors); savePrefs(); strcpy(reply, "OK"); } else if (memcmp(config, "flood.max.unscoped ", 19) == 0) { diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 33e27d2d..823f6c0f 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -169,6 +169,11 @@ private: void setGpsEnabled(bool enabled) override { _parent->gps_enabled = enabled; markDirty(); } uint32_t getGpsPeriod() const override { return _parent->gps_period; } void setGpsPeriod(uint32_t seconds) override { _parent->gps_period = seconds; markDirty(); } + bool getGuardReference(double& lat, double& lon) const override { + lat = _parent->node_lat; + lon = _parent->node_lon; + return true; + } }; GPSPrefs gps; diff --git a/src/helpers/CommonGpsPrefs.cpp b/src/helpers/CommonGpsPrefs.cpp index f840f0a2..8faf01a6 100644 --- a/src/helpers/CommonGpsPrefs.cpp +++ b/src/helpers/CommonGpsPrefs.cpp @@ -1,5 +1,8 @@ #include "CommonGpsPrefs.h" #include <helpers/sensors/LocationProvider.h> +#ifdef GPS_GUARD +#include <helpers/sensors/GpsGuard.h> +#endif bool CommonGpsPrefs::setGpsEnabled(SensorManager& sensors, bool enabled) { LocationProvider* location = sensors.getLocationProvider(); @@ -17,9 +20,28 @@ bool CommonGpsPrefs::setGpsPeriod(SensorManager& sensors, uint32_t seconds) { return true; } +void CommonGpsPrefs::applyGuardReference(SensorManager& sensors) const { +#ifdef GPS_GUARD + LocationProvider* location = sensors.getLocationProvider(); + GpsGuard* guard = location != nullptr ? location->getGuard() : nullptr; + double lat, lon; + if (guard != nullptr && getGuardReference(lat, lon)) guard->setReference(lat, lon); +#endif +} + +// The clock was set by hand: the guard drops its GPS time anchor and any alert. +void CommonGpsPrefs::onClockSetManually(SensorManager& sensors) { +#ifdef GPS_GUARD + LocationProvider* location = sensors.getLocationProvider(); + GpsGuard* guard = location != nullptr ? location->getGuard() : nullptr; + if (guard != nullptr) guard->clockSetManually(); +#endif +} + bool CommonGpsPrefs::apply(SensorManager& sensors) const { LocationProvider* location = sensors.getLocationProvider(); if (location == nullptr) return false; + applyGuardReference(sensors); location->setGpsPeriod(getGpsPeriod()); location->setGpsOn(isGpsEnabled()); return true; @@ -198,6 +220,47 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, } return true; } +#ifdef GPS_GUARD + if (memcmp(command, "gps guard", 9) == 0 || memcmp(command, "gps fence", 9) == 0 || + strcmp(command, "gps ref") == 0) { + LocationProvider* location = sensors.getLocationProvider(); + GpsGuard* guard = location != nullptr ? location->getGuard() : nullptr; + if (guard == nullptr) { + strcpy(reply, "Error, gps guard not supported"); + } else if (strcmp(command, "gps guard") == 0) { + reply[0] = '>'; reply[1] = ' '; + guard->formatStatus(reply + 2, 158); + } else if (strcmp(command, "gps guard accept") == 0) { + // operator confirms that the alerted GPS time is right: apply it to the clock + long offset; + if (!guard->isTimeAlert()) { + strcpy(reply, "Error, no time alert"); + } else if (!location->getClockOffset(offset) || + !guard->acceptAlertedTime(offset, (uint32_t)location->getTimestamp()) || + !location->applyTimeNow()) { + strcpy(reply, "Error, no current trusted fix with the alerted time"); + } else { + strcpy(reply, "OK - clock set from GPS"); + } + } else if (strcmp(command, "gps fence") == 0) { + sprintf(reply, "> %lu", (unsigned long)guard->getFence()); + } else if (memcmp(command, "gps fence ", 10) == 0) { + char* end; + unsigned long metres = strtoul(command + 10, &end, 10); + if (command[10] == '�' || *end != '�') { + strcpy(reply, "Error, invalid fence"); + } else { + guard->setFence((uint32_t)metres); + strcpy(reply, "OK"); + } + } else if (strcmp(command, "gps ref") == 0) { + snprintf(reply, 160, "> %.6f, %.6f", guard->getRefLat(), guard->getRefLon()); + } else { + return false; + } + return true; + } +#endif if (strcmp(command, "gps diag") == 0) { LocationProvider* location = sensors.getLocationProvider(); if (location == nullptr) { diff --git a/src/helpers/CommonGpsPrefs.h b/src/helpers/CommonGpsPrefs.h index 25cce1b1..7a7d5744 100644 --- a/src/helpers/CommonGpsPrefs.h +++ b/src/helpers/CommonGpsPrefs.h @@ -19,7 +19,12 @@ public: virtual uint32_t getGpsPeriod() const = 0; virtual void setGpsPeriod(uint32_t seconds) = 0; + // Reference position for the anti-spoofing guard (GPS_GUARD), e.g. the configured node position. + virtual bool getGuardReference(double& lat, double& lon) const { return false; } + bool setGpsEnabled(SensorManager& sensors, bool enabled); + void applyGuardReference(SensorManager& sensors) const; + static void onClockSetManually(SensorManager& sensors); bool setGpsPeriod(SensorManager& sensors, uint32_t seconds); bool apply(SensorManager& sensors) const; bool handleCommand(const char* command, SensorManager& sensors, char* reply); diff --git a/src/helpers/sensors/EnvironmentSensorManager.cpp b/src/helpers/sensors/EnvironmentSensorManager.cpp index eafa11a3..d8f2d1d8 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.cpp +++ b/src/helpers/sensors/EnvironmentSensorManager.cpp @@ -1,6 +1,9 @@ #include "EnvironmentSensorManager.h" #include <Wire.h> +#if ENV_INCLUDE_GPS && defined(GPS_GUARD) +#include <helpers/sensors/GpsGuard.h> +#endif #if ENV_PIN_SDA && ENV_PIN_SCL #define TELEM_WIRE &Wire1 // Use Wire1 as the I2C bus for Environment Sensors @@ -641,6 +644,13 @@ bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, Cayen _active_sensors[i].query(next_available_channel, _active_sensors[i].sub_channel, telemetry); next_available_channel++; } + #if ENV_INCLUDE_GPS && defined(GPS_GUARD) + // GPS-vs-clock offset in hours on its own channel while the guard's time alert is active + GpsGuard* guard = _location->getGuard(); + if (guard != nullptr && guard->isTimeAlert()) { + telemetry.addAnalogInput(next_available_channel++, guard->getAlertOffset() / 3600.0f); + } + #endif } return true; diff --git a/src/helpers/sensors/GpsGuard.h b/src/helpers/sensors/GpsGuard.h new file mode 100644 index 00000000..238bc7e8 --- /dev/null +++ b/src/helpers/sensors/GpsGuard.h @@ -0,0 +1,275 @@ +#pragma once + +// GPS anti-spoofing guard (opt-in with GPS_GUARD). +// +// A location provider asks the guard before it stores a fix as its last fix and before it +// writes GPS time to the clock: +// - acceptFix(): plausibility checks (satellites, HDOP, optional build-time region, distance +// from a reference position, jump speed) and N consecutive consistent fixes; +// - acceptTime(): GPS time only while a trusted fix is current, not before this firmware +// was built, and once the clock is valid only small corrections (clock drift after the +// first accepted sync), so a spoofer cannot walk the clock away. +// A trusted fix that keeps disagreeing with the clock by the same offset raises an alert; +// the operator can then accept that GPS time (acceptAlertedTime()). + +#include <Arduino.h> +#include <MeshCore.h> +#include <RTClib.h> +#include <math.h> +#include <stdio.h> +#include <stdlib.h> + +#ifndef GPS_GUARD_MIN_SATS + #define GPS_GUARD_MIN_SATS 4 +#endif +#ifndef GPS_GUARD_MAX_HDOP10 + #define GPS_GUARD_MAX_HDOP10 40 // HDOP 4.0 +#endif +#ifndef GPS_GUARD_FENCE_M + #define GPS_GUARD_FENCE_M 1000 // max distance from the reference position (0 = off) +#endif +#ifndef GPS_GUARD_STABLE_FIXES + #define GPS_GUARD_STABLE_FIXES 5 // consecutive consistent fixes (one per GPS second) +#endif +#ifndef GPS_GUARD_STABLE_M + #define GPS_GUARD_STABLE_M 100 +#endif +#ifndef GPS_GUARD_MAX_SPEED_KMH + #define GPS_GUARD_MAX_SPEED_KMH 250 // jump limit relative to the last trusted fix +#endif +#ifndef GPS_GUARD_TIME_MAX_STEP + #define GPS_GUARD_TIME_MAX_STEP 600 // max GPS-vs-clock correction (s) once the clock is valid +#endif +#ifndef GPS_GUARD_TIME_DRIFT_BASE + #define GPS_GUARD_TIME_DRIFT_BASE 5 // after the first sync: fixed allowance (s) ... +#endif +#ifndef GPS_GUARD_TIME_DRIFT_PPM + #define GPS_GUARD_TIME_DRIFT_PPM 100 // ... plus clock drift since that sync (~8.6 s/day) +#endif +#ifndef GPS_GUARD_ALERT_MIN + #define GPS_GUARD_ALERT_MIN 60 // alert after GPS disagrees with the clock this long ... +#endif +#ifndef GPS_GUARD_ALERT_TOLERANCE + #define GPS_GUARD_ALERT_TOLERANCE 60 // ... by an offset that stays within this many seconds +#endif +#ifndef GPS_GUARD_TRUSTED_MS + #define GPS_GUARD_TRUSTED_MS 5000 // a trusted fix is "current" for this long +#endif + +class GpsGuard { + double _ref_lat = 0, _ref_lon = 0; // 0,0 = no reference position + uint32_t _fence_m = GPS_GUARD_FENCE_M; + + bool _have_trusted = false; + unsigned long _last_trusted_ms = 0; + double _last_trusted_lat = 0, _last_trusted_lon = 0; + double _cand_lat = 0, _cand_lon = 0; + uint32_t _cand_time = 0; // GPS second of the last counted candidate + uint32_t _rej_log_time = 0; // GPS second of the last logged rejection + uint8_t _stable_count = 0; + char _fix_status[24] = "no fix"; + + char _time_status[24] = "-"; + bool _time_accepted = false; // a GPS time sync was accepted (drift budget anchor) + unsigned long _last_time_accept_ms = 0; + bool _time_disagree = false; + long _time_disagree_offset = 0; // GPS minus clock, seconds + unsigned long _time_disagree_since_ms = 0; + bool _time_alert = false; + + static double distanceM(double lat1, double lon1, double lat2, double lon2) { + const double R = 6371000.0, D2R = 0.017453292519943295; + double dlat = (lat2 - lat1) * D2R, dlon = (lon2 - lon1) * D2R; + double a = sin(dlat / 2) * sin(dlat / 2) + + cos(lat1 * D2R) * cos(lat2 * D2R) * sin(dlon / 2) * sin(dlon / 2); + return 2 * R * atan2(sqrt(a), sqrt(1 - a)); + } + + bool trustedFixIsCurrent() const { + return _have_trusted && (uint32_t)(millis() - _last_trusted_ms) <= GPS_GUARD_TRUSTED_MS; + } + + void trackTimeDisagreement(long offset) { + const unsigned long now = millis(); + if (!_time_disagree || labs(offset - _time_disagree_offset) > GPS_GUARD_ALERT_TOLERANCE) { + _time_disagree = true; + _time_disagree_offset = offset; + _time_disagree_since_ms = now; + _time_alert = false; + return; + } + if (!_time_alert && (uint32_t)(now - _time_disagree_since_ms) >= GPS_GUARD_ALERT_MIN * 60000UL) { + _time_alert = true; + MESH_DEBUG_PRINTLN("GPS TIME ALERT: GPS differs from clock by %lds for %u min", offset, GPS_GUARD_ALERT_MIN); + } + } + +public: + // Plausible GPS time window: not before this firmware was built, at most 10 years after. + static uint32_t minEpoch() { + static const uint32_t min_epoch = DateTime(__DATE__, __TIME__).unixtime() - 86400; + return min_epoch; + } + static uint32_t maxEpoch() { return minEpoch() + 10UL * 365 * 86400; } + + void setReference(double lat, double lon) { _ref_lat = lat; _ref_lon = lon; } + double getRefLat() const { return _ref_lat; } + double getRefLon() const { return _ref_lon; } + void setFence(uint32_t metres) { _fence_m = metres; } + uint32_t getFence() const { return _fence_m; } + bool hasTrustedFix() const { return _have_trusted; } + bool isTimeAlert() const { return _time_alert; } + long getAlertOffset() const { return _time_disagree_offset; } + + // Fix as reported by the receiver: lat/lon in micro-degrees, HDOP in tenths (255 = unknown), + // gps_time = UTC epoch of the fix. Returns true if the fix can be stored as trusted. + bool acceptFix(long lat_e6, long lon_e6, long sats, uint8_t hdop10, uint32_t gps_time) { + const double lat = lat_e6 / 1000000.0; + const double lon = lon_e6 / 1000000.0; + const unsigned long now = millis(); + + const char* why = NULL; + double dist = 0; + if (sats < GPS_GUARD_MIN_SATS) { + why = "sats"; + } else if (hdop10 == 255 || hdop10 > GPS_GUARD_MAX_HDOP10) { + why = "hdop"; + } +#if defined(GPS_GUARD_LAT_MIN) && defined(GPS_GUARD_LAT_MAX) && defined(GPS_GUARD_LON_MIN) && defined(GPS_GUARD_LON_MAX) + else if (lat < GPS_GUARD_LAT_MIN || lat > GPS_GUARD_LAT_MAX || lon < GPS_GUARD_LON_MIN || lon > GPS_GUARD_LON_MAX) { + why = "region"; + } +#endif + else if (_fence_m > 0 && (_ref_lat != 0 || _ref_lon != 0) && + (dist = distanceM(_ref_lat, _ref_lon, lat, lon)) > _fence_m) { + why = "fence"; + } else if (_have_trusted) { + dist = distanceM(_last_trusted_lat, _last_trusted_lon, lat, lon); + double secs = (uint32_t)(now - _last_trusted_ms) / 1000.0; + if (secs < 1) secs = 1; + if (dist / secs > GPS_GUARD_MAX_SPEED_KMH / 3.6) why = "jump"; + } + + if (why) { + _stable_count = 0; + if (dist > 0) { + snprintf(_fix_status, sizeof(_fix_status), "rej %s %.1fkm", why, dist / 1000.0); + } else { + snprintf(_fix_status, sizeof(_fix_status), "rej %s", why); + } + if (gps_time == 0 || gps_time != _rej_log_time) { // GGA and RMC report the same second: log it once + _rej_log_time = gps_time; + MESH_DEBUG_PRINTLN("GPS fix rejected (%s): %f,%f sats=%ld hdop=%u", why, lat, lon, sats, hdop10); + } + return false; + } + + if (!_have_trusted || _stable_count < GPS_GUARD_STABLE_FIXES) { + // Require several consecutive, mutually consistent fixes. GGA and RMC report the + // same GPS second: count each second once. + if (_stable_count > 0 && distanceM(_cand_lat, _cand_lon, lat, lon) > GPS_GUARD_STABLE_M) { + _stable_count = 0; + } + if (_stable_count == 0 || gps_time != _cand_time) { + if (_stable_count < 255) _stable_count++; + } + _cand_lat = lat; + _cand_lon = lon; + _cand_time = gps_time; + if (_stable_count < GPS_GUARD_STABLE_FIXES) { + snprintf(_fix_status, sizeof(_fix_status), "settle %u/%u", _stable_count, GPS_GUARD_STABLE_FIXES); + return false; + } + } + + if (!_have_trusted) { + MESH_DEBUG_PRINTLN("GPS fix trusted: %f,%f sats=%ld hdop=%u", lat, lon, sats, hdop10); + } + _have_trusted = true; + _last_trusted_ms = now; + _last_trusted_lat = lat; + _last_trusted_lon = lon; + snprintf(_fix_status, sizeof(_fix_status), "ok %ldsat", sats); + return true; + } + + // No usable fix right now (e.g. receiver lost the fix): restart the consistency count. + void noFix(long sats) { + _stable_count = 0; + snprintf(_fix_status, sizeof(_fix_status), "no fix %ldsat", sats); + } + + // GPS time is only written to the clock while a trusted fix is current, it is not + // older than this firmware, and (once the clock is valid) it only nudges the clock. + bool acceptTime(uint32_t gps_time, uint32_t clock_time) { + const char* why = NULL; + long step = 0; + if (!trustedFixIsCurrent()) { + why = "nofix"; + } else if (gps_time < minEpoch() || gps_time > maxEpoch()) { + why = "range"; + } else if (clock_time >= minEpoch()) { // clock already holds a plausible time + step = (long)gps_time - (long)clock_time; + long limit = GPS_GUARD_TIME_MAX_STEP; + if (_time_accepted) { + // After the first accepted sync only allow corrections the size of real clock + // drift, so a spoofer cannot walk the clock away in many small steps. + uint32_t elapsed_s = (uint32_t)(millis() - _last_time_accept_ms) / 1000; + limit = GPS_GUARD_TIME_DRIFT_BASE + (long)((uint64_t)elapsed_s * GPS_GUARD_TIME_DRIFT_PPM / 1000000UL); + if (limit > GPS_GUARD_TIME_MAX_STEP) limit = GPS_GUARD_TIME_MAX_STEP; + } + if (labs(step) > limit) why = "step"; + } + + if (why) { + if (step != 0) { + snprintf(_time_status, sizeof(_time_status), "rej %s %lds", why, step); + trackTimeDisagreement(step); + } else { + snprintf(_time_status, sizeof(_time_status), "rej %s", why); + } + return false; + } + snprintf(_time_status, sizeof(_time_status), "ok %+lds", (long)gps_time - (long)clock_time); + // Every accepted sync anchors the drift budget (fail closed: no walking the clock in + // repeated MAX_STEP jumps). A wrongly anchored time is recovered with a manual clock + // set, which resets the anchor (clockSetManually()). + _time_disagree = false; + _time_alert = false; + _time_accepted = true; + _last_time_accept_ms = millis(); + return true; + } + + // The clock was set by hand: drop the drift anchor and any alert. + void clockSetManually() { + _time_accepted = false; + _time_disagree = false; + _time_alert = false; + } + + // Operator confirms that the alerted GPS time is right. offset = current GPS minus clock. + // Returns true if the caller may write the GPS time to the clock now. + bool acceptAlertedTime(long offset, uint32_t gps_time) { + if (!_time_alert || !trustedFixIsCurrent()) return false; + if (labs(offset - _time_disagree_offset) > GPS_GUARD_ALERT_TOLERANCE) return false; // not the alerted offset + if (gps_time < minEpoch() || gps_time > maxEpoch()) return false; + _time_accepted = true; + _last_time_accept_ms = millis(); + _time_disagree = false; + _time_alert = false; + snprintf(_time_status, sizeof(_time_status), "ok manual"); + return true; + } + + // e.g. "ok 7sat time ok +1s", "rej region time rej nofix", + // "ok 9sat time rej step 3600s ALERT gps-clk +3600s 75m" + void formatStatus(char* out, size_t out_size) const { + if (_time_alert) { + snprintf(out, out_size, "%s time %s ALERT gps-clk %+lds %lum", _fix_status, _time_status, + _time_disagree_offset, (unsigned long)((uint32_t)(millis() - _time_disagree_since_ms) / 60000)); + } else { + snprintf(out, out_size, "%s time %s", _fix_status, _time_status); + } + } +}; diff --git a/src/helpers/sensors/LocationProvider.h b/src/helpers/sensors/LocationProvider.h index 52093d87..5b5b69c0 100644 --- a/src/helpers/sensors/LocationProvider.h +++ b/src/helpers/sensors/LocationProvider.h @@ -5,6 +5,8 @@ #include <stdio.h> +class GpsGuard; + class LocationProvider { public: // Last valid fix, always filled in one go so readers get a consistent snapshot. @@ -105,6 +107,11 @@ public: // Format compact diagnostics in the caller-provided buffer. Providers that // have more information (for example UART counters) can override this. + // Anti-spoofing guard (GPS_GUARD), nullptr if this provider has none + virtual GpsGuard* getGuard() { return nullptr; } + virtual bool getClockOffset(long& offset) { return false; } // GPS time minus clock time + virtual bool applyTimeNow() { return false; } // write GPS time to the clock now + virtual void formatDiagnostics(char* out, size_t out_size) { if (out_size == 0) return; snprintf(out, out_size, "en:%u sat:%ld fix:%u", diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index f3442bd5..bc9f5efa 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -5,6 +5,9 @@ #include <MicroNMEA.h> #include <RTClib.h> #include <string.h> +#ifdef GPS_GUARD +#include "GpsGuard.h" +#endif #ifndef GPS_PERIODIC_ACQUISITION_TIMEOUT_MS #define GPS_PERIODIC_ACQUISITION_TIMEOUT_MS 300000UL @@ -44,6 +47,9 @@ class MicroNMEALocationProvider : public LocationProvider { unsigned long _last_nmea_ms = 0; bool _uart_seen = false; bool _nmea_seen = false; +#ifdef GPS_GUARD + GpsGuard _guard; +#endif static uint32_t ageMs(unsigned long timestamp) { return (uint32_t)(millis() - timestamp); @@ -80,6 +86,11 @@ class MicroNMEALocationProvider : public LocationProvider { // only store a fix when the snapshot is coherent (sats > 0). // Returns true if the fix was stored. if (nmea.getNumSatellites() == 0) return false; +#ifdef GPS_GUARD + // only plausible, stable fixes become the last fix (position, telemetry, time sync) + if (!_guard.acceptFix(nmea.getLatitude(), nmea.getLongitude(), nmea.getNumSatellites(), + nmea.getHDOP(), getTimestamp())) return false; +#endif LastFix fix; fix.latitude = nmea.getLatitude(); @@ -106,7 +117,7 @@ class MicroNMEALocationProvider : public LocationProvider { (millis() - _last_time_sync) > TIME_SYNC_INTERVAL) { _time_sync_needed = true; } - if (_time_sync_needed && time_valid > 2 && _clock != nullptr) { + if (_time_sync_needed && time_valid > 2 && _clock != nullptr && timeSyncAllowed()) { _clock->setCurrentTime(getTimestamp()); _time_sync_needed = false; _last_time_sync = millis(); @@ -114,6 +125,14 @@ class MicroNMEALocationProvider : public LocationProvider { if (isValid()) time_valid++; } + bool timeSyncAllowed() { +#ifdef GPS_GUARD + return _guard.acceptTime(getTimestamp(), _clock->getCurrentTime()); +#else + return true; +#endif + } + public: MicroNMEALocationProvider(NmeaGpsDriver& driver, mesh::RTCClock* clock = nullptr) : nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), _driver(&driver) {} @@ -195,7 +214,15 @@ public: } // Position, altitude and satellite count describe the last saved fix - // Before the first saved fix, fall back to the live parser state. + // Before the first saved fix, fall back to the live parser state + // (not with GPS_GUARD: an unverified position is never reported). +#ifdef GPS_GUARD + GpsGuard* getGuard() override { return &_guard; } + bool hasValidFix() override { return _lastFix.valid; } + long getLatitude() override { return _lastFix.latitude; } + long getLongitude() override { return _lastFix.longitude; } + long getAltitude() override { return _lastFix.altitude; } +#else long getLatitude() override { return _lastFix.valid ? _lastFix.latitude : nmea.getLatitude(); } @@ -208,6 +235,23 @@ public: nmea.getAltitude(alt); return alt; } +#endif + + // GPS time minus clock time, from a current fix with a settled time + bool getClockOffset(long& offset) override { + if (_clock == nullptr || !isValid() || time_valid < 3) return false; + offset = (long)getTimestamp() - (long)_clock->getCurrentTime(); + return true; + } + + // write the current GPS time to the clock now (caller has done its own checks) + bool applyTimeNow() override { + if (_clock == nullptr || !isValid() || time_valid < 3) return false; + _clock->setCurrentTime(getTimestamp()); + _time_sync_needed = false; + _last_time_sync = millis(); + return true; + } long satellitesCount() override { return _lastFix.valid ? _lastFix.satellites : nmea.getNumSatellites(); } @@ -286,6 +330,12 @@ public: _nmea_seen = true; const char* messageId = nmea.getMessageID(); +#ifdef GPS_GUARD + if (parsed && !nmea.isValid() && + (strcmp(messageId, "GGA") == 0 || strcmp(messageId, "RMC") == 0)) { + _guard.noFix(nmea.getNumSatellites()); + } +#endif if (parsed && nmea.isValid() && (strcmp(messageId, "GGA") == 0 || strcmp(messageId, "RMC") == 0)) { if (!saveFix()) continue; // incoherent snapshot diff --git a/src/helpers/sensors/RakLocationProvider.h b/src/helpers/sensors/RakLocationProvider.h index 903546ba..2dda12a5 100644 --- a/src/helpers/sensors/RakLocationProvider.h +++ b/src/helpers/sensors/RakLocationProvider.h @@ -71,6 +71,23 @@ public: return _useI2c ? _lastFix.timestamp : _nmea.getTimestamp(); } + // the anti-spoofing guard (GPS_GUARD) only covers the serial NMEA path + GpsGuard* getGuard() override { + return _useI2c ? nullptr : _nmea.getGuard(); + } + + bool hasValidFix() override { + return _useI2c ? LocationProvider::hasValidFix() : _nmea.hasValidFix(); + } + + bool getClockOffset(long& offset) override { + return _useI2c ? false : _nmea.getClockOffset(offset); + } + + bool applyTimeNow() override { + return _useI2c ? false : _nmea.applyTimeNow(); + } + void sendSentence(const char* sentence) override { if (!_useI2c) _nmea.sendSentence(sentence); } From 1c9adb46cbc3470db723834cb2bb70c4f082b95c Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko <tishenko.alexandr@gmail.com> Date: Mon, 9 Nov 2026 22:15:45 +0200 Subject: [PATCH 363/381] GpsGuard: do not show a stale time ok without a current trusted fix --- src/helpers/sensors/GpsGuard.h | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/helpers/sensors/GpsGuard.h b/src/helpers/sensors/GpsGuard.h index 238bc7e8..eed387ba 100644 --- a/src/helpers/sensors/GpsGuard.h +++ b/src/helpers/sensors/GpsGuard.h @@ -265,11 +265,14 @@ public: // e.g. "ok 7sat time ok +1s", "rej region time rej nofix", // "ok 9sat time rej step 3600s ALERT gps-clk +3600s 75m" void formatStatus(char* out, size_t out_size) const { + // The time status is only refreshed when a sync is due: without a current trusted fix, + // do not keep showing an old "ok" as if GPS time were usable now. + const char* time_status = (_time_status[0] == 'o' && !trustedFixIsCurrent()) ? "rej nofix" : _time_status; if (_time_alert) { - snprintf(out, out_size, "%s time %s ALERT gps-clk %+lds %lum", _fix_status, _time_status, + snprintf(out, out_size, "%s time %s ALERT gps-clk %+lds %lum", _fix_status, time_status, _time_disagree_offset, (unsigned long)((uint32_t)(millis() - _time_disagree_since_ms) / 60000)); } else { - snprintf(out, out_size, "%s time %s", _fix_status, _time_status); + snprintf(out, out_size, "%s time %s", _fix_status, time_status); } } }; From f5cbc18b83f9c99b76595e4be55da4eea814807d Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko <tishenko.alexandr@gmail.com> Date: Mon, 9 Nov 2026 22:30:24 +0200 Subject: [PATCH 364/381] GPS guard: drop time force, it goes to a separate PR --- docs/cli_commands.md | 4 +--- src/helpers/CommonCLI.cpp | 10 ---------- 2 files changed, 1 insertion(+), 13 deletions(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index e21b6a8e..69a1347e 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -69,8 +69,6 @@ This document provides an overview of CLI commands that can be sent to MeshCore **Parameters:** - `epoch_seconds`: Unix epoch time -**Note:** The clock only moves forward. To set it back (e.g. after the clock was pushed into the future by a wrong GPS time) use `time force <epoch_seconds>`. - --- ### Send a flood advert @@ -1082,7 +1080,7 @@ region save #### GPS anti-spoofing guard (When built with `GPS_GUARD`) With `GPS_GUARD`, a fix becomes the node's last fix (position, telemetry, adverts) only after it passes plausibility checks: at least `GPS_GUARD_MIN_SATS` satellites, HDOP ≤ `GPS_GUARD_MAX_HDOP10`/10, inside the optional build-time region (`GPS_GUARD_LAT_MIN/MAX`, `GPS_GUARD_LON_MIN/MAX`), within the fence around the node's configured `lat`/`lon` (if set), no jump faster than `GPS_GUARD_MAX_SPEED_KMH`, and `GPS_GUARD_STABLE_FIXES` consistent fixes in a row. An unverified position is never reported. -GPS time is written to the clock only while such a fix is current, never earlier than the firmware build date, and, once the clock is valid, only within `GPS_GUARD_TIME_MAX_STEP` seconds for the first sync and within clock drift (`GPS_GUARD_TIME_DRIFT_BASE` s + `GPS_GUARD_TIME_DRIFT_PPM`) afterwards. Setting the clock manually (`time`, `time force`, `clock sync`) resets that anchor. +GPS time is written to the clock only while such a fix is current, never earlier than the firmware build date, and, once the clock is valid, only within `GPS_GUARD_TIME_MAX_STEP` seconds for the first sync and within clock drift (`GPS_GUARD_TIME_DRIFT_BASE` s + `GPS_GUARD_TIME_DRIFT_PPM`) afterwards. Setting the clock manually (`time`, `clock sync`) resets that anchor. Covers serial NMEA receivers (`MicroNMEALocationProvider`). diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index fa3ad789..2c79bae1 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -226,16 +226,6 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re uint32_t now = getRTCClock()->getCurrentTime(); DateTime dt = DateTime(now); sprintf(reply, "%02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year()); - } else if (memcmp(command, "time force ", 11) == 0) { // set time, allowing it to go backwards - uint32_t secs = _atoi(&command[11]); - if (secs > 1700000000UL) { - getRTCClock()->setCurrentTime(secs); - CommonGpsPrefs::onClockSetManually(*_sensors); - DateTime dt = DateTime(getRTCClock()->getCurrentTime()); - sprintf(reply, "OK - clock forced: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year()); - } else { - strcpy(reply, "ERR: invalid epoch"); - } } else if (memcmp(command, "time ", 5) == 0) { // set time (to epoch seconds) uint32_t secs = _atoi(&command[5]); uint32_t curr = getRTCClock()->getCurrentTime(); From faabf349504801a3ed7e6af0232f19a7e65ec188 Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko <tishenko.alexandr@gmail.com> Date: Mon, 9 Nov 2026 22:54:18 +0200 Subject: [PATCH 365/381] GpsGuard: let GPS correct a clock outside the plausible window --- docs/cli_commands.md | 2 +- src/helpers/sensors/GpsGuard.h | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 69a1347e..babd7102 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1080,7 +1080,7 @@ region save #### GPS anti-spoofing guard (When built with `GPS_GUARD`) With `GPS_GUARD`, a fix becomes the node's last fix (position, telemetry, adverts) only after it passes plausibility checks: at least `GPS_GUARD_MIN_SATS` satellites, HDOP ≤ `GPS_GUARD_MAX_HDOP10`/10, inside the optional build-time region (`GPS_GUARD_LAT_MIN/MAX`, `GPS_GUARD_LON_MIN/MAX`), within the fence around the node's configured `lat`/`lon` (if set), no jump faster than `GPS_GUARD_MAX_SPEED_KMH`, and `GPS_GUARD_STABLE_FIXES` consistent fixes in a row. An unverified position is never reported. -GPS time is written to the clock only while such a fix is current, never earlier than the firmware build date, and, once the clock is valid, only within `GPS_GUARD_TIME_MAX_STEP` seconds for the first sync and within clock drift (`GPS_GUARD_TIME_DRIFT_BASE` s + `GPS_GUARD_TIME_DRIFT_PPM`) afterwards. Setting the clock manually (`time`, `clock sync`) resets that anchor. +GPS time is written to the clock only while such a fix is current, never earlier than the firmware build date, and, once the clock holds a plausible time (from the build date to 10 years after it), only within `GPS_GUARD_TIME_MAX_STEP` seconds for the first sync and within clock drift (`GPS_GUARD_TIME_DRIFT_BASE` s + `GPS_GUARD_TIME_DRIFT_PPM`) afterwards. Setting the clock manually (`time`, `clock sync`) resets that anchor. A clock outside that window (e.g. a bogus date in 2080) is corrected by the first trusted fix. Covers serial NMEA receivers (`MicroNMEALocationProvider`). diff --git a/src/helpers/sensors/GpsGuard.h b/src/helpers/sensors/GpsGuard.h index eed387ba..bd26aee0 100644 --- a/src/helpers/sensors/GpsGuard.h +++ b/src/helpers/sensors/GpsGuard.h @@ -200,7 +200,7 @@ public: } // GPS time is only written to the clock while a trusted fix is current, it is not - // older than this firmware, and (once the clock is valid) it only nudges the clock. + // older than this firmware, and (once the clock is plausible) it only nudges the clock. bool acceptTime(uint32_t gps_time, uint32_t clock_time) { const char* why = NULL; long step = 0; @@ -208,7 +208,9 @@ public: why = "nofix"; } else if (gps_time < minEpoch() || gps_time > maxEpoch()) { why = "range"; - } else if (clock_time >= minEpoch()) { // clock already holds a plausible time + } else if (clock_time >= minEpoch() && clock_time <= maxEpoch()) { + // The clock already holds a plausible time. A clock outside that window (e.g. a + // bogus 2080 date at boot) is treated like an unset one, so GPS can correct it. step = (long)gps_time - (long)clock_time; long limit = GPS_GUARD_TIME_MAX_STEP; if (_time_accepted) { From ca5ccddc85f61fefb1d49849d33fb37386f6fd31 Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko <tishenko.alexandr@gmail.com> Date: Mon, 9 Nov 2026 22:59:47 +0200 Subject: [PATCH 366/381] NmeaGpsDriver: baud rates to probe come from the board, not a build flag --- src/helpers/sensors/NmeaGpsDriver.h | 60 ++++++++++++++++------------- variants/promicro/target.cpp | 7 +++- 2 files changed, 40 insertions(+), 27 deletions(-) diff --git a/src/helpers/sensors/NmeaGpsDriver.h b/src/helpers/sensors/NmeaGpsDriver.h index 37cb92b2..dfe75a4f 100644 --- a/src/helpers/sensors/NmeaGpsDriver.h +++ b/src/helpers/sensors/NmeaGpsDriver.h @@ -91,6 +91,8 @@ class NmeaGpsDriver : public GpsDriver { int _enableActive = HIGH; int _resetActive = LOW; uint32_t _baudRate = 9600; + const uint32_t* _probeBauds = nullptr; // optional rates to try in detect(), set by the board + uint8_t _probeCount = 0; int _hardwareEnablePin = -1; int _hardwareEnableActive = HIGH; bool _started = false; @@ -118,7 +120,6 @@ class NmeaGpsDriver : public GpsDriver { _started = true; } -#ifdef GPS_BAUD_AUTODETECT void reopenSerial(uint32_t baud) { _hardwareSerial->end(); if (_txPin != -1 && _rxPin != -1) { @@ -157,28 +158,26 @@ class NmeaGpsDriver : public GpsDriver { } // Bytes arriving does not mean the baud rate is right: at the wrong rate the - // parser only sees garbage and never gets a fix. Probe common GNSS rates, - // starting with the configured one, and keep the first that yields valid NMEA. - // The rate is kept in _baudRate, so later power cycles reopen the UART with it. - void detectBaudRate() { - static const uint32_t bauds[] = { GPS_BAUD_RATE, 9600, 115200, 38400, 57600, 19200, 4800 }; - const uint32_t configured = _baudRate; - for (size_t i = 0; i < sizeof(bauds) / sizeof(bauds[0]); i++) { - bool tried = false; - for (size_t j = 0; j < i; j++) tried |= (bauds[j] == bauds[i]); - if (tried) continue; - reopenSerial(bauds[i]); - if (seesValidNmea(2000)) { - _baudRate = bauds[i]; - MESH_DEBUG_PRINTLN("GPS baud rate: %lu", (unsigned long)_baudRate); - return; - } - } - _baudRate = configured; - reopenSerial(_baudRate); - MESH_DEBUG_PRINTLN("GPS baud rate not detected, using %lu", (unsigned long)_baudRate); + // parser only sees garbage and never gets a fix. Try the configured rate, then the + // board's list, and keep the first that yields valid NMEA. The rate is kept in + // _baudRate, so later power cycles reopen the UART with it. + bool tryBaudRate(uint32_t baud) { + reopenSerial(baud); + if (!seesValidNmea(2000)) return false; + _baudRate = baud; + MESH_DEBUG_PRINTLN("GPS baud rate: %lu", (unsigned long)_baudRate); + return true; + } + + void detectBaudRate() { + const uint32_t configured = _baudRate; + if (tryBaudRate(configured)) return; + for (uint8_t i = 0; i < _probeCount; i++) { + if (_probeBauds[i] != configured && tryBaudRate(_probeBauds[i])) return; + } + reopenSerial(configured); + MESH_DEBUG_PRINTLN("GPS baud rate not detected, using %lu", (unsigned long)configured); } -#endif void stopHardware() { if (!_started) return; @@ -199,10 +198,12 @@ public: int enableActive = GPS_EN_ACTIVE, int resetActive = GPS_RESET_ACTIVE, uint32_t baudRate = GPS_BAUD_RATE, int hardwareEnablePin = PIN_GPS_SWITCH, - int hardwareEnableActive = GPS_SWITCH_ACTIVE) + int hardwareEnableActive = GPS_SWITCH_ACTIVE, + const uint32_t* probeBauds = nullptr, uint8_t probeCount = 0) : _hardwareSerial(&serial), _peripheralPower(peripheralPower), _txPin(txPin), _rxPin(rxPin), _resetPin(resetPin), _enablePin(enablePin), _enableActive(enableActive), _resetActive(resetActive), _baudRate(baudRate), + _probeBauds(probeBauds), _probeCount(probeBauds != nullptr ? probeCount : 0), _hardwareEnablePin(hardwareEnablePin), _hardwareEnableActive(hardwareEnableActive) { if (_resetPin != -1) { pinMode(_resetPin, OUTPUT); @@ -217,6 +218,13 @@ public: } } + // Board with a GPS whose baud rate is not known in advance: detect() also tries the + // rates in probeBauds (after the configured one). The array must stay valid (static). + NmeaGpsDriver(UART_TYPE& serial, const uint32_t* probeBauds, uint8_t probeCount) + : NmeaGpsDriver(serial, PIN_GPS_TX, PIN_GPS_RX, GPS_RESET, GPS_EN, nullptr, + GPS_EN_ACTIVE, GPS_RESET_ACTIVE, GPS_BAUD_RATE, PIN_GPS_SWITCH, + GPS_SWITCH_ACTIVE, probeBauds, probeCount) {} + void begin() override { #if !GPS_SWITCH_IS_HARDWARE _requestedOn = true; @@ -292,10 +300,10 @@ public: found = available() > 0; if (!found) delay(10); } -#ifdef GPS_BAUD_AUTODETECT // only on a real detection (timeout > 0), not on the quick "still active?" polls - if (found && timeout_ms > 0 && _started && _hardwareSerial != nullptr) detectBaudRate(); -#endif + if (found && timeout_ms > 0 && _probeCount > 0 && _started && _hardwareSerial != nullptr) { + detectBaudRate(); + } return found; } diff --git a/variants/promicro/target.cpp b/variants/promicro/target.cpp index 5758d9cd..4cdeb6e0 100644 --- a/variants/promicro/target.cpp +++ b/variants/promicro/target.cpp @@ -12,7 +12,12 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - NmeaGpsDriver gps_driver(Serial1); + #ifdef GPS_BAUD_PROBE_LIST // e.g. -D GPS_BAUD_PROBE_LIST=9600,38400,115200 + static const uint32_t gps_probe_bauds[] = { GPS_BAUD_PROBE_LIST }; + NmeaGpsDriver gps_driver(Serial1, gps_probe_bauds, sizeof(gps_probe_bauds) / sizeof(gps_probe_bauds[0])); + #else + NmeaGpsDriver gps_driver(Serial1); + #endif MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else From 6291f9156a9e359a185360911701b45c88de6ed8 Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko <tishenko.alexandr@gmail.com> Date: Mon, 9 Nov 2026 23:16:29 +0200 Subject: [PATCH 367/381] GPS guard: save gps fence in the GPS prefs --- docs/cli_commands.md | 2 +- examples/companion_radio/NodePrefs.h | 10 ++++++++++ src/helpers/CommonCLI.h | 10 ++++++++++ src/helpers/CommonGpsPrefs.cpp | 5 ++++- src/helpers/CommonGpsPrefs.h | 3 +++ 5 files changed, 28 insertions(+), 2 deletions(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index babd7102..74db9e5c 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1087,7 +1087,7 @@ Covers serial NMEA receivers (`MicroNMEALocationProvider`). **Usage:** - `gps guard`: status, e.g. `> ok 7sat time ok +1s`, `> rej region time rej nofix`, or `... ALERT gps-clk +3600s 75m` when a trusted fix has disagreed with the clock by the same offset for `GPS_GUARD_ALERT_MIN` minutes. While the alert is active, the offset in hours is also reported in telemetry on the next free channel. - `gps guard accept`: while an alert is active, confirm that the GPS time is right and apply it to the clock. -- `gps fence`, `gps fence <metres>`: fence radius around the configured `lat`/`lon` (`0` = off). Default `GPS_GUARD_FENCE_M` (1000), not saved. +- `gps fence`, `gps fence <metres>`: fence radius around the configured `lat`/`lon` (`0` = off). Default `GPS_GUARD_FENCE_M` (1000); a value set here is saved. - `gps ref`: the reference position; follows `set lat`, `set lon` and `gps setloc`. --- diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index db019370..7758354a 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -37,6 +37,7 @@ public: uint8_t gps_enabled = 0; // GPS enabled flag (0=disabled, 1=enabled) uint32_t gps_interval = 0; // GPS read interval in seconds uint32_t gps_period = 0; // periodic acquisition interval in seconds + int32_t gps_fence = -1; // GPS_GUARD fence in metres, 0 = off, -1 = build default uint8_t autoadd_config = 0; // bitmask for auto-add contacts config uint8_t rx_boosted_gain = 0; // SX126x RX boosted gain mode (0=power saving, 1=boosted) uint8_t radio_fem_rxgain = 0; // external LoRa FEM RX gain (LNA) @@ -166,6 +167,9 @@ private: def("int", _parent->gps_interval); // interval in seconds def("period", _parent->gps_period); // periodic acquisition interval in seconds def("adv_loc", _parent->advert_loc_policy); +#ifdef GPS_GUARD + def("fence", _parent->gps_fence); +#endif } public: GPSPrefs(NodePrefs* parent) : _parent(parent) { } @@ -173,6 +177,12 @@ private: void setGpsEnabled(bool enabled) override { _parent->gps_enabled = enabled; markDirty(); } uint32_t getGpsPeriod() const override { return _parent->gps_period; } void setGpsPeriod(uint32_t seconds) override { _parent->gps_period = seconds; markDirty(); } + bool getGuardFence(uint32_t& metres) const override { + if (_parent->gps_fence < 0) return false; + metres = (uint32_t)_parent->gps_fence; + return true; + } + void setGuardFence(uint32_t metres) override { _parent->gps_fence = (int32_t)metres; markDirty(); } }; GPSPrefs gps; diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 823f6c0f..fa39d587 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -63,6 +63,7 @@ public: uint8_t gps_enabled = 0; uint32_t gps_interval = 0; // in seconds uint32_t gps_period = 0; // periodic acquisition interval in seconds + int32_t gps_fence = -1; // GPS_GUARD fence in metres, 0 = off, -1 = build default uint8_t advert_loc_policy = 0; uint32_t discovery_mod_timestamp = 0; float adc_multiplier = 0; @@ -162,6 +163,9 @@ private: def("int", _parent->gps_interval); // interval in seconds def("period", _parent->gps_period); // periodic acquisition interval in seconds def("adv_loc", _parent->advert_loc_policy); +#ifdef GPS_GUARD + def("fence", _parent->gps_fence); +#endif } public: GPSPrefs(NodePrefs* parent) : _parent(parent) { } @@ -169,6 +173,12 @@ private: void setGpsEnabled(bool enabled) override { _parent->gps_enabled = enabled; markDirty(); } uint32_t getGpsPeriod() const override { return _parent->gps_period; } void setGpsPeriod(uint32_t seconds) override { _parent->gps_period = seconds; markDirty(); } + bool getGuardFence(uint32_t& metres) const override { + if (_parent->gps_fence < 0) return false; + metres = (uint32_t)_parent->gps_fence; + return true; + } + void setGuardFence(uint32_t metres) override { _parent->gps_fence = (int32_t)metres; markDirty(); } bool getGuardReference(double& lat, double& lon) const override { lat = _parent->node_lat; lon = _parent->node_lon; diff --git a/src/helpers/CommonGpsPrefs.cpp b/src/helpers/CommonGpsPrefs.cpp index 8faf01a6..16177559 100644 --- a/src/helpers/CommonGpsPrefs.cpp +++ b/src/helpers/CommonGpsPrefs.cpp @@ -26,6 +26,8 @@ void CommonGpsPrefs::applyGuardReference(SensorManager& sensors) const { GpsGuard* guard = location != nullptr ? location->getGuard() : nullptr; double lat, lon; if (guard != nullptr && getGuardReference(lat, lon)) guard->setReference(lat, lon); + uint32_t fence; + if (guard != nullptr && getGuardFence(fence)) guard->setFence(fence); #endif } @@ -247,10 +249,11 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, } else if (memcmp(command, "gps fence ", 10) == 0) { char* end; unsigned long metres = strtoul(command + 10, &end, 10); - if (command[10] == '�' || *end != '�') { + if (command[10] == '\0' || *end != '\0' || metres > 20000000UL) { // at most half the Earth strcpy(reply, "Error, invalid fence"); } else { guard->setFence((uint32_t)metres); + setGuardFence((uint32_t)metres); // saved by the caller (isDirty) strcpy(reply, "OK"); } } else if (strcmp(command, "gps ref") == 0) { diff --git a/src/helpers/CommonGpsPrefs.h b/src/helpers/CommonGpsPrefs.h index 7a7d5744..3fa1c9b2 100644 --- a/src/helpers/CommonGpsPrefs.h +++ b/src/helpers/CommonGpsPrefs.h @@ -21,6 +21,9 @@ public: // Reference position for the anti-spoofing guard (GPS_GUARD), e.g. the configured node position. virtual bool getGuardReference(double& lat, double& lon) const { return false; } + // Saved fence radius for the guard; false = not set, use the build default. + virtual bool getGuardFence(uint32_t& metres) const { return false; } + virtual void setGuardFence(uint32_t metres) { } bool setGpsEnabled(SensorManager& sensors, bool enabled); void applyGuardReference(SensorManager& sensors) const; From 3da13dd91af9a90a524f9beee71b898cbaf10045 Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko <tishenko.alexandr@gmail.com> Date: Mon, 9 Nov 2026 23:50:48 +0200 Subject: [PATCH 368/381] GPS guard: gps guard on/off, saved in the GPS prefs --- docs/cli_commands.md | 1 + examples/companion_radio/NodePrefs.h | 7 +++++++ src/helpers/CommonCLI.h | 7 +++++++ src/helpers/CommonGpsPrefs.cpp | 7 +++++++ src/helpers/CommonGpsPrefs.h | 3 +++ src/helpers/sensors/GpsGuard.h | 20 ++++++++++++++++++++ 6 files changed, 45 insertions(+) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 74db9e5c..754f5120 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1086,6 +1086,7 @@ Covers serial NMEA receivers (`MicroNMEALocationProvider`). **Usage:** - `gps guard`: status, e.g. `> ok 7sat time ok +1s`, `> rej region time rej nofix`, or `... ALERT gps-clk +3600s 75m` when a trusted fix has disagreed with the clock by the same offset for `GPS_GUARD_ALERT_MIN` minutes. While the alert is active, the offset in hours is also reported in telemetry on the next free channel. +- `gps guard on`, `gps guard off`: turn the guard on or off (saved, default on). While off, every fix and GPS time is accepted and `gps guard` shows `off`. - `gps guard accept`: while an alert is active, confirm that the GPS time is right and apply it to the clock. - `gps fence`, `gps fence <metres>`: fence radius around the configured `lat`/`lon` (`0` = off). Default `GPS_GUARD_FENCE_M` (1000); a value set here is saved. - `gps ref`: the reference position; follows `set lat`, `set lon` and `gps setloc`. diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index 7758354a..6aa3d47c 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -38,6 +38,7 @@ public: uint32_t gps_interval = 0; // GPS read interval in seconds uint32_t gps_period = 0; // periodic acquisition interval in seconds int32_t gps_fence = -1; // GPS_GUARD fence in metres, 0 = off, -1 = build default + uint8_t gps_guard = 1; // GPS_GUARD on/off uint8_t autoadd_config = 0; // bitmask for auto-add contacts config uint8_t rx_boosted_gain = 0; // SX126x RX boosted gain mode (0=power saving, 1=boosted) uint8_t radio_fem_rxgain = 0; // external LoRa FEM RX gain (LNA) @@ -169,6 +170,7 @@ private: def("adv_loc", _parent->advert_loc_policy); #ifdef GPS_GUARD def("fence", _parent->gps_fence); + def("guard", _parent->gps_guard); #endif } public: @@ -183,6 +185,11 @@ private: return true; } void setGuardFence(uint32_t metres) override { _parent->gps_fence = (int32_t)metres; markDirty(); } + bool getGuardEnabled(bool& enabled) const override { + enabled = _parent->gps_guard != 0; + return true; + } + void setGuardEnabled(bool enabled) override { _parent->gps_guard = enabled ? 1 : 0; markDirty(); } }; GPSPrefs gps; diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index fa39d587..cb85f6f9 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -64,6 +64,7 @@ public: uint32_t gps_interval = 0; // in seconds uint32_t gps_period = 0; // periodic acquisition interval in seconds int32_t gps_fence = -1; // GPS_GUARD fence in metres, 0 = off, -1 = build default + uint8_t gps_guard = 1; // GPS_GUARD on/off uint8_t advert_loc_policy = 0; uint32_t discovery_mod_timestamp = 0; float adc_multiplier = 0; @@ -165,6 +166,7 @@ private: def("adv_loc", _parent->advert_loc_policy); #ifdef GPS_GUARD def("fence", _parent->gps_fence); + def("guard", _parent->gps_guard); #endif } public: @@ -179,6 +181,11 @@ private: return true; } void setGuardFence(uint32_t metres) override { _parent->gps_fence = (int32_t)metres; markDirty(); } + bool getGuardEnabled(bool& enabled) const override { + enabled = _parent->gps_guard != 0; + return true; + } + void setGuardEnabled(bool enabled) override { _parent->gps_guard = enabled ? 1 : 0; markDirty(); } bool getGuardReference(double& lat, double& lon) const override { lat = _parent->node_lat; lon = _parent->node_lon; diff --git a/src/helpers/CommonGpsPrefs.cpp b/src/helpers/CommonGpsPrefs.cpp index 16177559..cdc889d0 100644 --- a/src/helpers/CommonGpsPrefs.cpp +++ b/src/helpers/CommonGpsPrefs.cpp @@ -28,6 +28,8 @@ void CommonGpsPrefs::applyGuardReference(SensorManager& sensors) const { if (guard != nullptr && getGuardReference(lat, lon)) guard->setReference(lat, lon); uint32_t fence; if (guard != nullptr && getGuardFence(fence)) guard->setFence(fence); + bool enabled; + if (guard != nullptr && getGuardEnabled(enabled)) guard->setEnabled(enabled); #endif } @@ -232,6 +234,11 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, } else if (strcmp(command, "gps guard") == 0) { reply[0] = '>'; reply[1] = ' '; guard->formatStatus(reply + 2, 158); + } else if (strcmp(command, "gps guard on") == 0 || strcmp(command, "gps guard off") == 0) { + const bool enabled = command[11] == 'n'; + guard->setEnabled(enabled); + setGuardEnabled(enabled); // saved by the caller (isDirty) + strcpy(reply, "OK"); } else if (strcmp(command, "gps guard accept") == 0) { // operator confirms that the alerted GPS time is right: apply it to the clock long offset; diff --git a/src/helpers/CommonGpsPrefs.h b/src/helpers/CommonGpsPrefs.h index 3fa1c9b2..c1e30b8e 100644 --- a/src/helpers/CommonGpsPrefs.h +++ b/src/helpers/CommonGpsPrefs.h @@ -24,6 +24,9 @@ public: // Saved fence radius for the guard; false = not set, use the build default. virtual bool getGuardFence(uint32_t& metres) const { return false; } virtual void setGuardFence(uint32_t metres) { } + // Saved on/off state of the guard; false = not set, guard on. + virtual bool getGuardEnabled(bool& enabled) const { return false; } + virtual void setGuardEnabled(bool enabled) { } bool setGpsEnabled(SensorManager& sensors, bool enabled); void applyGuardReference(SensorManager& sensors) const; diff --git a/src/helpers/sensors/GpsGuard.h b/src/helpers/sensors/GpsGuard.h index bd26aee0..cf713033 100644 --- a/src/helpers/sensors/GpsGuard.h +++ b/src/helpers/sensors/GpsGuard.h @@ -57,6 +57,7 @@ #endif class GpsGuard { + bool _enabled = true; // off: every fix and GPS time passes, as without GPS_GUARD double _ref_lat = 0, _ref_lon = 0; // 0,0 = no reference position uint32_t _fence_m = GPS_GUARD_FENCE_M; @@ -118,6 +119,19 @@ public: void setFence(uint32_t metres) { _fence_m = metres; } uint32_t getFence() const { return _fence_m; } bool hasTrustedFix() const { return _have_trusted; } + bool isEnabled() const { return _enabled; } + void setEnabled(bool enabled) { + if (enabled == _enabled) return; + _enabled = enabled; + // start over: a re-enabled guard needs fresh stable fixes, and no alert survives + _have_trusted = false; + _stable_count = 0; + _time_accepted = false; + _time_disagree = false; + _time_alert = false; + strcpy(_fix_status, "no fix"); + strcpy(_time_status, "-"); + } bool isTimeAlert() const { return _time_alert; } long getAlertOffset() const { return _time_disagree_offset; } @@ -127,6 +141,7 @@ public: const double lat = lat_e6 / 1000000.0; const double lon = lon_e6 / 1000000.0; const unsigned long now = millis(); + if (!_enabled) return true; const char* why = NULL; double dist = 0; @@ -202,6 +217,7 @@ public: // GPS time is only written to the clock while a trusted fix is current, it is not // older than this firmware, and (once the clock is plausible) it only nudges the clock. bool acceptTime(uint32_t gps_time, uint32_t clock_time) { + if (!_enabled) return true; const char* why = NULL; long step = 0; if (!trustedFixIsCurrent()) { @@ -267,6 +283,10 @@ public: // e.g. "ok 7sat time ok +1s", "rej region time rej nofix", // "ok 9sat time rej step 3600s ALERT gps-clk +3600s 75m" void formatStatus(char* out, size_t out_size) const { + if (!_enabled) { + snprintf(out, out_size, "off"); + return; + } // The time status is only refreshed when a sync is due: without a current trusted fix, // do not keep showing an old "ok" as if GPS time were usable now. const char* time_status = (_time_status[0] == 'o' && !trustedFixIsCurrent()) ? "rej nofix" : _time_status; From 6ce010fbfe8f6b78271d72a4cba270b6c7165773 Mon Sep 17 00:00:00 2001 From: dahuib <dahuib@users.noreply.github.com> Date: Tue, 10 Nov 2026 15:57:32 +0100 Subject: [PATCH 369/381] Support RAK16000 (INA219 at 0x41) on dev --- .../sensors/EnvironmentSensorManager.cpp | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/helpers/sensors/EnvironmentSensorManager.cpp b/src/helpers/sensors/EnvironmentSensorManager.cpp index d8f2d1d8..278677de 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.cpp +++ b/src/helpers/sensors/EnvironmentSensorManager.cpp @@ -328,14 +328,17 @@ static void query_ina3221(uint8_t ch, uint8_t sub_ch, CayenneLPP& lpp) { #endif #if ENV_INCLUDE_INA219 -static uint8_t init_ina219(TwoWire* wire, uint8_t) { - // INA219 static instance was constructed with the address; begin() uses it. - return INA219.begin(wire) ? 1 : 0; +static Adafruit_INA219 INA219_ALT((TELEM_INA219_ADDRESS == 0x40) ? 0x41 : 0x40); +static Adafruit_INA219* active_ina219 = &INA219; + +static uint8_t init_ina219(TwoWire* wire, uint8_t addr) { + active_ina219 = (addr == TELEM_INA219_ADDRESS) ? &INA219 : &INA219_ALT; + return active_ina219->begin(wire) ? 1 : 0; } static void query_ina219(uint8_t ch, uint8_t, CayenneLPP& lpp) { - lpp.addVoltage(ch, INA219.getBusVoltage_V()); - lpp.addCurrent(ch, INA219.getCurrent_mA() / 1000.0f); - lpp.addPower(ch, INA219.getPower_mW() / 1000.0f); + lpp.addVoltage(ch, active_ina219->getBusVoltage_V()); + lpp.addCurrent(ch, active_ina219->getCurrent_mA() / 1000.0f); + lpp.addPower(ch, active_ina219->getPower_mW() / 1000.0f); } #endif @@ -507,6 +510,7 @@ struct SensorDef { }; #define TELEM_BOSCH_ALT_ADDR(addr) ((uint8_t)((addr) == 0x76 ? 0x77 : 0x76)) +#define TELEM_INA219_ALT_ADDR(addr) ((uint8_t)((addr) == 0x40 ? 0x41 : 0x40)) static const SensorDef SENSOR_TABLE[] = { #if ENV_INCLUDE_AHTX0 @@ -542,6 +546,7 @@ static const SensorDef SENSOR_TABLE[] = { #endif #if ENV_INCLUDE_INA219 { TELEM_INA219_ADDRESS, "INA219", init_ina219, query_ina219 }, + { TELEM_INA219_ALT_ADDR(TELEM_INA219_ADDRESS), "INA219", init_ina219, query_ina219 }, #endif #if ENV_INCLUDE_INA260 { TELEM_INA260_ADDRESS, "INA260", init_ina260, query_ina260 }, @@ -565,6 +570,7 @@ static const SensorDef SENSOR_TABLE[] = { }; #undef TELEM_BOSCH_ALT_ADDR +#undef TELEM_INA219_ALT_ADDR static const size_t SENSOR_TABLE_SIZE = (sizeof(SENSOR_TABLE) / sizeof(SENSOR_TABLE[0])) - 1; From 474021f10a401a42beb20c6d88c4e3c060aeb5f5 Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Tue, 10 Nov 2026 11:52:38 -0400 Subject: [PATCH 370/381] eink: some updates (busy loop + hibernate when screen off) --- src/helpers/ui/GxEPDDisplay.cpp | 3 +-- variants/thinknode_m1/platformio.ini | 1 + variants/thinknode_m5/platformio.ini | 1 + variants/thinknode_m8/platformio.ini | 3 ++- variants/wio-tracker-l1-eink/platformio.ini | 1 + 5 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/helpers/ui/GxEPDDisplay.cpp b/src/helpers/ui/GxEPDDisplay.cpp index 209d1b46..47a7d6e0 100644 --- a/src/helpers/ui/GxEPDDisplay.cpp +++ b/src/helpers/ui/GxEPDDisplay.cpp @@ -101,6 +101,7 @@ void GxEPDDisplay::turnOff(bool blank) { } _isOn = false; last_display_crc_value=0; + display.hibernate(); } void GxEPDDisplay::blankScreen() { @@ -112,8 +113,6 @@ void GxEPDDisplay::blankScreen() { display.epd2.setBusyCallback(NULL); _partial_refresh_count = 0; last_display_crc_value = 0; - // we can hibernate as screen has been cleaned - display.hibernate(); } void GxEPDDisplay::clear() { diff --git a/variants/thinknode_m1/platformio.ini b/variants/thinknode_m1/platformio.ini index 03b0eb4e..ae00d28e 100644 --- a/variants/thinknode_m1/platformio.ini +++ b/variants/thinknode_m1/platformio.ini @@ -35,6 +35,7 @@ build_flags = ${nrf52_base.build_flags} -D AUTO_OFF_MILLIS=300000 ; 5 minutes -D UI_NO_HIBERNATE -D DISABLE_DIAGNOSTIC_OUTPUT + -D EINK_REFRESH_LOOP build_src_filter = ${nrf52_base.build_src_filter} +<helpers/*.cpp> +<ThinkNodeM1Board.cpp> diff --git a/variants/thinknode_m5/platformio.ini b/variants/thinknode_m5/platformio.ini index d2b791a3..b2c7201e 100644 --- a/variants/thinknode_m5/platformio.ini +++ b/variants/thinknode_m5/platformio.ini @@ -44,6 +44,7 @@ build_flags = ${esp32_base.build_flags} -D ENV_INCLUDE_GPS=1 -D PERSISTANT_GPS=1 -D ENV_SKIP_GPS_DETECT=1 + -D EINK_REFRESH_LOOP build_src_filter = ${esp32_base.build_src_filter} +<helpers/sensors/EnvironmentSensorManager.cpp> +<helpers/ui/MomentaryButton.cpp> diff --git a/variants/thinknode_m8/platformio.ini b/variants/thinknode_m8/platformio.ini index fdbaea1f..2f8fb9e5 100644 --- a/variants/thinknode_m8/platformio.ini +++ b/variants/thinknode_m8/platformio.ini @@ -32,7 +32,8 @@ build_flags = ${nrf52_base.build_flags} -D EINK_SCALE_X=1.5625f -D EINK_SCALE_Y=1.5625f -D EINK_X_OFFSET=0 - -D EINK_Y_OFFSET=10 + -D EINK_Y_OFFSET=10 + -D EINK_REFRESH_LOOP -D DISABLE_DIAGNOSTIC_OUTPUT -D SX126X_POWER_EN=37 -D SX126X_DIO2_AS_RF_SWITCH=true diff --git a/variants/wio-tracker-l1-eink/platformio.ini b/variants/wio-tracker-l1-eink/platformio.ini index 2c74bade..1c8e9ede 100644 --- a/variants/wio-tracker-l1-eink/platformio.ini +++ b/variants/wio-tracker-l1-eink/platformio.ini @@ -27,6 +27,7 @@ build_flags = ${nrf52_base.build_flags} -D GPS_BAUD_RATE=9600 -D ENV_PIN_SDA=PIN_WIRE1_SDA -D ENV_PIN_SCL=PIN_WIRE1_SCL + -D EINK_REFRESH_LOOP build_src_filter = ${nrf52_base.build_src_filter} +<WioTrackerL1Board.cpp> +<../variants/wio-tracker-l1> From 790f4d3f0890b9f30c234af8c474fca1f99a6e3a Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko <tishenko.alexandr@gmail.com> Date: Tue, 10 Nov 2026 19:33:38 +0200 Subject: [PATCH 371/381] GPS: GPS_BAUD_PROBE_LIST as a build flag for any NmeaGpsDriver; enable on Station G2/G3 The probe list was wired only in variants/promicro/target.cpp. It is now the default list of NmeaGpsDriver when GPS_BAUD_PROBE_LIST is set, so a variant enables baud autodetection with a build flag alone. Station G2 and G3 enable it: their Grove UART connector is used with M5Stack Unit GPS modules, which default to 115200. --- src/helpers/sensors/NmeaGpsDriver.h | 14 +++++++++++++- variants/promicro/target.cpp | 7 +------ variants/station_g2/platformio.ini | 1 + variants/station_g3_esp32/platformio.ini | 1 + 4 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/helpers/sensors/NmeaGpsDriver.h b/src/helpers/sensors/NmeaGpsDriver.h index dfe75a4f..9beacdc2 100644 --- a/src/helpers/sensors/NmeaGpsDriver.h +++ b/src/helpers/sensors/NmeaGpsDriver.h @@ -64,6 +64,18 @@ #endif #endif +// Optional rates detect() tries after GPS_BAUD_RATE, for GPS modules whose baud rate is +// not known in advance (e.g. -D GPS_BAUD_PROBE_LIST=9600,115200,38400). Used by every +// NmeaGpsDriver that does not pass its own list. +#ifdef GPS_BAUD_PROBE_LIST + static const uint32_t NMEA_GPS_PROBE_BAUDS[] = { GPS_BAUD_PROBE_LIST }; + #define GPS_PROBE_BAUDS NMEA_GPS_PROBE_BAUDS + #define GPS_PROBE_COUNT ((uint8_t)(sizeof(NMEA_GPS_PROBE_BAUDS) / sizeof(NMEA_GPS_PROBE_BAUDS[0]))) +#else + #define GPS_PROBE_BAUDS nullptr + #define GPS_PROBE_COUNT 0 +#endif + #ifndef PIN_GPS_SWITCH #define PIN_GPS_SWITCH (-1) #endif @@ -199,7 +211,7 @@ public: uint32_t baudRate = GPS_BAUD_RATE, int hardwareEnablePin = PIN_GPS_SWITCH, int hardwareEnableActive = GPS_SWITCH_ACTIVE, - const uint32_t* probeBauds = nullptr, uint8_t probeCount = 0) + const uint32_t* probeBauds = GPS_PROBE_BAUDS, uint8_t probeCount = GPS_PROBE_COUNT) : _hardwareSerial(&serial), _peripheralPower(peripheralPower), _txPin(txPin), _rxPin(rxPin), _resetPin(resetPin), _enablePin(enablePin), _enableActive(enableActive), _resetActive(resetActive), _baudRate(baudRate), diff --git a/variants/promicro/target.cpp b/variants/promicro/target.cpp index 4cdeb6e0..5758d9cd 100644 --- a/variants/promicro/target.cpp +++ b/variants/promicro/target.cpp @@ -12,12 +12,7 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include <helpers/sensors/MicroNMEALocationProvider.h> - #ifdef GPS_BAUD_PROBE_LIST // e.g. -D GPS_BAUD_PROBE_LIST=9600,38400,115200 - static const uint32_t gps_probe_bauds[] = { GPS_BAUD_PROBE_LIST }; - NmeaGpsDriver gps_driver(Serial1, gps_probe_bauds, sizeof(gps_probe_bauds) / sizeof(gps_probe_bauds[0])); - #else - NmeaGpsDriver gps_driver(Serial1); - #endif + NmeaGpsDriver gps_driver(Serial1); MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else diff --git a/variants/station_g2/platformio.ini b/variants/station_g2/platformio.ini index c1ae765f..c4fd344d 100644 --- a/variants/station_g2/platformio.ini +++ b/variants/station_g2/platformio.ini @@ -25,6 +25,7 @@ build_flags = -D PIN_USER_BTN=38 -D PIN_GPS_RX=15 -D PIN_GPS_TX=7 + -D GPS_BAUD_PROBE_LIST=9600,115200,38400 ; Grove UART GPS units (e.g. M5Stack Unit GPS v1.1) default to 115200 -D SX126X_DIO2_AS_RF_SWITCH=true -D SX126X_DIO3_TCXO_VOLTAGE=1.8 -D SX126X_CURRENT_LIMIT=140 diff --git a/variants/station_g3_esp32/platformio.ini b/variants/station_g3_esp32/platformio.ini index 7006d939..2ce8bb39 100644 --- a/variants/station_g3_esp32/platformio.ini +++ b/variants/station_g3_esp32/platformio.ini @@ -29,6 +29,7 @@ build_flags = -D PIN_USER_BTN=38 -D PIN_GPS_RX=15 -D PIN_GPS_TX=7 + -D GPS_BAUD_PROBE_LIST=9600,115200,38400 ; Grove UART GPS units (e.g. M5Stack Unit GPS v1.1) default to 115200 -D SX126X_DIO2_AS_RF_SWITCH=true -D SX126X_DIO3_TCXO_VOLTAGE=1.8 -D SX126X_CURRENT_LIMIT=140 From e1a445b9678222e9818ed4a180b0fd99245c9d2e Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko <tishenko.alexandr@gmail.com> Date: Wed, 11 Nov 2026 01:48:12 +0200 Subject: [PATCH 372/381] GPS guard: show "time wait" instead of "rej nofix" between fixes When the last GPS time check passed but there is no current trusted fix (e.g. the GPS is asleep between periodic fixes), gps guard showed "time rej nofix", which reads like a rejection although the clock is fine. Show "time wait" instead. A real rejection without a trusted fix (GPS time arriving while fixes are rejected) still shows "rej nofix". --- docs/cli_commands.md | 2 +- src/helpers/sensors/GpsGuard.h | 9 +++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 1488c646..5d2ac70e 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1085,7 +1085,7 @@ GPS time is written to the clock only while such a fix is current, never earlier Covers serial NMEA receivers (`MicroNMEALocationProvider`). **Usage:** -- `gps guard`: status, e.g. `> ok 7sat time ok +1s`, `> rej region time rej nofix`, or `... ALERT gps-clk +3600s 75m` when a trusted fix has disagreed with the clock by the same offset for `GPS_GUARD_ALERT_MIN` minutes. While the alert is active, the offset in hours is also reported in telemetry on the next free channel. +- `gps guard`: status, e.g. `> ok 7sat time ok +1s`, `> rej region time rej nofix`, `> ok 7sat time wait` (last check passed, no current trusted fix to check again, e.g. GPS asleep between periodic fixes), or `... ALERT gps-clk +3600s 75m` when a trusted fix has disagreed with the clock by the same offset for `GPS_GUARD_ALERT_MIN` minutes. While the alert is active, the offset in hours is also reported in telemetry on the next free channel. - `gps guard on`, `gps guard off`: turn the guard on or off (saved, default on). While off, every fix and GPS time is accepted and `gps guard` shows `off`. - `gps guard accept`: while an alert is active, confirm that the GPS time is right and apply it to the clock. - `gps fence`, `gps fence <metres>`: fence radius around the configured `lat`/`lon` (`0` = off). Default `GPS_GUARD_FENCE_M` (1000); a value set here is saved. diff --git a/src/helpers/sensors/GpsGuard.h b/src/helpers/sensors/GpsGuard.h index cf713033..66f4b92f 100644 --- a/src/helpers/sensors/GpsGuard.h +++ b/src/helpers/sensors/GpsGuard.h @@ -280,16 +280,17 @@ public: return true; } - // e.g. "ok 7sat time ok +1s", "rej region time rej nofix", + // e.g. "ok 7sat time ok +1s", "ok 7sat time wait", "rej region time rej nofix", // "ok 9sat time rej step 3600s ALERT gps-clk +3600s 75m" void formatStatus(char* out, size_t out_size) const { if (!_enabled) { snprintf(out, out_size, "off"); return; } - // The time status is only refreshed when a sync is due: without a current trusted fix, - // do not keep showing an old "ok" as if GPS time were usable now. - const char* time_status = (_time_status[0] == 'o' && !trustedFixIsCurrent()) ? "rej nofix" : _time_status; + // The time status is only refreshed when a sync is due. Without a current trusted fix + // (e.g. GPS asleep between periodic fixes) an old "ok" is not shown as current: the last + // check passed and the next one waits for a trusted fix. + const char* time_status = (_time_status[0] == 'o' && !trustedFixIsCurrent()) ? "wait" : _time_status; if (_time_alert) { snprintf(out, out_size, "%s time %s ALERT gps-clk %+lds %lum", _fix_status, time_status, _time_disagree_offset, (unsigned long)((uint32_t)(millis() - _time_disagree_since_ms) / 60000)); From f02d9d9e47f11dbc48887e8e0f85119054cd624f Mon Sep 17 00:00:00 2001 From: Valentin Metz <Valentin-Metz@users.noreply.github.com> Date: Wed, 11 Nov 2026 05:23:22 +0100 Subject: [PATCH 373/381] Fix stack-buffer overflow in CLI reply buffers The remote-CLI reply buffers in onPeerDataRecv() (repeater, room server, sensor) and BaseChatMesh were sized temp[166] for a 5-byte datagram header plus 161 bytes of reply. But MyMesh::handleCommand() first reflects a 3-byte correlation prefix (e.g. 'aa|') into the reply, after which CommonCLI commands may write up to 160 chars + NUL into the remaining 158 bytes -- overflowing the buffer by 2 bytes (e.g. a full 'regions' listing via exportTo(reply, 160)). Triggering this remotely crashes the node (observed as an unresponsive repeater after a prefixed 'regions' query); the 2 out-of-bounds bytes are a printable region-name character and a NUL. Size the buffers for the full worst case instead: 5 header + 3 prefix + 160 reply + 1 NUL = 169. Verified with a host ASan harness reproducing the exact layout: prefixed 'regions' with a 25-region listing overflowed temp[166] (BufStream::write, RegionMap.cpp) and now passes clean with temp[169]; unprefixed (serial) path unaffected. --- examples/simple_repeater/MyMesh.cpp | 3 ++- examples/simple_room_server/MyMesh.cpp | 3 ++- examples/simple_sensor/SensorMesh.cpp | 3 ++- src/helpers/BaseChatMesh.cpp | 3 ++- 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index 99cd35bb..7d06811f 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -779,7 +779,8 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, } } - uint8_t temp[166]; + // 5-byte datagram header + 3-byte reflected CLI prefix + 160-byte reply text + NUL + uint8_t temp[169]; char *command = (char *)&data[5]; char *reply = (char *)&temp[5]; if (is_retry) { diff --git a/examples/simple_room_server/MyMesh.cpp b/examples/simple_room_server/MyMesh.cpp index b1a88dd8..c1a6b09f 100644 --- a/examples/simple_room_server/MyMesh.cpp +++ b/examples/simple_room_server/MyMesh.cpp @@ -462,7 +462,8 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, mesh::Utils::sha256((uint8_t *)&ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key, PUB_KEY_SIZE); - uint8_t temp[166]; + // 5-byte datagram header + 3-byte reflected CLI prefix + 160-byte reply text + NUL + uint8_t temp[169]; bool send_ack; if (flags == TXT_TYPE_CLI_DATA || flags == TXT_TYPE_CLI_COMMAND) { if (client->isAdmin()) { diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index bb747f63..2798c690 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -667,7 +667,8 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i // len can be > original length, but 'text' will be padded with zeroes data[len] = 0; // need to make a C string again, with null terminator - uint8_t temp[166]; + // 5-byte datagram header + 3-byte reflected CLI prefix + 160-byte reply text + NUL + uint8_t temp[169]; char *command = (char *) &data[5]; char *reply = (char *) &temp[5]; handleCommand(from, sender_timestamp, command, reply); diff --git a/src/helpers/BaseChatMesh.cpp b/src/helpers/BaseChatMesh.cpp index 4368d17f..58c08dea 100644 --- a/src/helpers/BaseChatMesh.cpp +++ b/src/helpers/BaseChatMesh.cpp @@ -266,7 +266,8 @@ void BaseChatMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender onCommandDataRecv(from, packet, sender_timestamp, text); // let UI know // NOTE: no ack expected for CLI_DATA replies } else if (flags == TXT_TYPE_CLI_COMMAND) { - uint8_t temp[166]; + // 5-byte datagram header + 3-byte reflected CLI prefix + 160-byte reply text + NUL + uint8_t temp[169]; char *command = (char *)&data[5]; char *reply = (char *)&temp[5]; *reply = 0; From b3b227b773529e41a44748da78b4c5e936afa05c Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Wed, 11 Nov 2026 07:26:01 -0400 Subject: [PATCH 374/381] tests: revert rak13302 tests --- .github/workflows/run-unit-tests.yml | 2 +- platformio.ini | 10 --- .../mocks/Arduino.h | 18 ----- test/test_rak3401_board_startup/mocks/Wire.h | 6 -- .../mocks/helpers/NRF52Board.h | 44 ------------ .../test_board_startup.cpp | 70 ------------------- .../test_onboard_radio.cpp | 66 ----------------- 7 files changed, 1 insertion(+), 215 deletions(-) delete mode 100644 test/test_rak3401_board_startup/mocks/Arduino.h delete mode 100644 test/test_rak3401_board_startup/mocks/Wire.h delete mode 100644 test/test_rak3401_board_startup/mocks/helpers/NRF52Board.h delete mode 100644 test/test_rak3401_board_startup/test_board_startup.cpp delete mode 100644 test/test_rak3401_onboard_radio/test_onboard_radio.cpp diff --git a/.github/workflows/run-unit-tests.yml b/.github/workflows/run-unit-tests.yml index f8145ecd..5d48f4c6 100644 --- a/.github/workflows/run-unit-tests.yml +++ b/.github/workflows/run-unit-tests.yml @@ -20,7 +20,7 @@ jobs: uses: ./.github/actions/setup-build-environment - name: Run Unit Tests - run: pio test -e native -e native_kiss_modem -e native_rak3401_onboard_radio -vv + run: pio test -e native -e native_kiss_modem -vv - name: Upload Test Results # Upload test results even if the test step failed. diff --git a/platformio.ini b/platformio.ini index c33105c9..7fdc8b64 100644 --- a/platformio.ini +++ b/platformio.ini @@ -168,7 +168,6 @@ build_flags = -std=c++17 -I test/mocks test_build_src = yes test_ignore = test_kiss_modem - test_rak3401_board_startup build_src_filter = -<*> +<../src/Utils.cpp> @@ -179,15 +178,6 @@ build_src_filter = lib_deps = google/googletest @ 1.17.0 -[env:native_rak3401_onboard_radio] -; Board startup needs isolated GPIO and power-management mocks. -extends = env:native -test_build_src = no -test_filter = test_rak3401_* -test_ignore = -build_flags = -I test/test_rak3401_board_startup/mocks - ${env:native.build_flags} - [env:native_kiss_modem] platform = native test_framework = googletest diff --git a/test/test_rak3401_board_startup/mocks/Arduino.h b/test/test_rak3401_board_startup/mocks/Arduino.h deleted file mode 100644 index d505af36..00000000 --- a/test/test_rak3401_board_startup/mocks/Arduino.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once - -#include "../../mocks/Arduino.h" - -#define NRF52_POWER_MANAGEMENT 1 -#define PWRMGT_LPCOMP_AIN 3 -#define PWRMGT_LPCOMP_REFSEL 4 -#define PWRMGT_VOLTAGE_BOOTLOCK 3300 -#define SX126X_POWER_EN 21 -#define INPUT 0 -#define OUTPUT 1 -#define LOW 0 -#define HIGH 1 - -void pinMode(uint32_t pin, uint32_t mode); -void digitalWrite(uint32_t pin, uint32_t value); -void analogReadResolution(uint32_t bits); -uint32_t analogRead(uint32_t pin); diff --git a/test/test_rak3401_board_startup/mocks/Wire.h b/test/test_rak3401_board_startup/mocks/Wire.h deleted file mode 100644 index c24e6306..00000000 --- a/test/test_rak3401_board_startup/mocks/Wire.h +++ /dev/null @@ -1,6 +0,0 @@ -#pragma once - -struct StartupWire { - void begin() {} -}; -inline StartupWire Wire; diff --git a/test/test_rak3401_board_startup/mocks/helpers/NRF52Board.h b/test/test_rak3401_board_startup/mocks/helpers/NRF52Board.h deleted file mode 100644 index 96c892ae..00000000 --- a/test/test_rak3401_board_startup/mocks/helpers/NRF52Board.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once - -#include <Arduino.h> -#include <string> -#include <vector> - -#define SHUTDOWN_REASON_LOW_VOLTAGE 0x4C -#define SHUTDOWN_REASON_BOOT_PROTECT 0x42 - -struct PowerMgtConfig { - uint8_t lpcomp_ain_channel; - uint8_t lpcomp_refsel; - uint16_t voltage_bootlock; -}; - -namespace startup_test { -extern std::vector<std::string> events; -extern bool permitBoot; -struct SystemOff { uint8_t reason; }; -} - -class NRF52Board { -protected: - bool checkBootVoltage(const PowerMgtConfig*) { - startup_test::events.push_back("voltage"); - if (!startup_test::permitBoot) initiateShutdown(SHUTDOWN_REASON_BOOT_PROTECT); - return true; - } - virtual void initiateShutdown(uint8_t reason) { enterSystemOff(reason); } - void configureVoltageWake(uint8_t, uint8_t) {} - void enterSystemOff(uint8_t reason) { - startup_test::events.push_back("off"); - throw startup_test::SystemOff{reason}; - } -public: - explicit NRF52Board(const char* = nullptr) {} - virtual uint16_t getBattMilliVolts() = 0; - virtual const char* getManufacturerName() const = 0; -}; - -class NRF52BoardDCDC : virtual public NRF52Board { -public: - void begin() {} -}; diff --git a/test/test_rak3401_board_startup/test_board_startup.cpp b/test/test_rak3401_board_startup/test_board_startup.cpp deleted file mode 100644 index 0bbf2e5a..00000000 --- a/test/test_rak3401_board_startup/test_board_startup.cpp +++ /dev/null @@ -1,70 +0,0 @@ -#include <gtest/gtest.h> -#include <array> -// Exercise the real startup code with a power-management stub that stops at SYSTEMOFF. -#include "../../variants/rak3401/RAK3401Board.cpp" - -namespace startup_test { -std::vector<std::string> events; -bool permitBoot; -std::array<uint32_t, 48> outputs; -rak3401::OnboardRadioState radioState; -} - -void pinMode(uint32_t, uint32_t) {} -void digitalWrite(uint32_t pin, uint32_t value) { startup_test::outputs.at(pin) = value; } -void analogReadResolution(uint32_t) {} -uint32_t analogRead(uint32_t) { return 2500; } - -rak3401::OnboardRadioState rak3401::sleepOnboardRadio() { - startup_test::events.push_back("onboard"); - return startup_test::radioState; -} - -class RakBoardStartup : public testing::Test { -protected: - void SetUp() override { - startup_test::events.clear(); - startup_test::outputs.fill(HIGH); - startup_test::permitBoot = true; - startup_test::radioState = rak3401::OnboardRadioState::Asleep; - } -}; - -TEST_F(RakBoardStartup, OnboardRadioHandledBeforeVoltageCheck) { - RAK3401Board board; - board.begin(); - EXPECT_EQ(startup_test::events, (std::vector<std::string>{"onboard", "voltage"})); - EXPECT_EQ(startup_test::outputs.at(SX126X_POWER_EN), HIGH); - EXPECT_EQ(startup_test::outputs.at(PIN_3V3_EN), HIGH); -} - -TEST_F(RakBoardStartup, LowVoltageExitStillHandlesOnboardRadio) { - startup_test::permitBoot = false; - RAK3401Board board; - try { - board.begin(); - FAIL() << "Expected protective shutdown"; - } catch (const startup_test::SystemOff& off) { - EXPECT_EQ(off.reason, SHUTDOWN_REASON_BOOT_PROTECT); - } - EXPECT_EQ(startup_test::events, (std::vector<std::string>{"onboard", "voltage", "off"})); - EXPECT_EQ(startup_test::outputs.at(SX126X_POWER_EN), LOW); - EXPECT_EQ(startup_test::outputs.at(PIN_3V3_EN), LOW); -} - -TEST_F(RakBoardStartup, OptionalRadioFailuresDoNotBypassBootProtection) { - for (auto state : {rak3401::OnboardRadioState::Absent, rak3401::OnboardRadioState::BusyTimeout, - rak3401::OnboardRadioState::SleepFailed}) { - startup_test::events.clear(); - startup_test::permitBoot = false; - startup_test::radioState = state; - RAK3401Board board; - EXPECT_THROW(board.begin(), startup_test::SystemOff); - EXPECT_EQ(startup_test::events, (std::vector<std::string>{"onboard", "voltage", "off"})); - } -} - -int main(int argc, char** argv) { - testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} diff --git a/test/test_rak3401_onboard_radio/test_onboard_radio.cpp b/test/test_rak3401_onboard_radio/test_onboard_radio.cpp deleted file mode 100644 index cc616612..00000000 --- a/test/test_rak3401_onboard_radio/test_onboard_radio.cpp +++ /dev/null @@ -1,66 +0,0 @@ -#include <gtest/gtest.h> -#include <array> -#include <string> -#include "../../variants/rak3401/OnboardRadioSleep.h" - -namespace { -struct FakeRadioIO { - std::string version = "SX1261"; - std::array<bool, 3> ready = {true, true, true}; - std::string calls; - unsigned waits = 0; - bool probePulls = true; - - void begin() { calls += "begin "; } - void reset() { calls += "reset "; } - bool waitBusy(bool high, unsigned timeout) { - calls += high ? "busy-high " : "busy-low "; - EXPECT_EQ(timeout, 20u); - if (high) EXPECT_FALSE(probePulls); - const bool result = ready.at(waits++); - return result; - } - void readVersion(char* out) { calls += "version "; memcpy(out, version.data(), 6); } - void releaseProbePulls() { calls += "release-pulls "; probePulls = false; } - void sleep() { EXPECT_FALSE(probePulls); calls += "sleep "; } - void end() { calls += "end "; } -}; -} - -TEST(RakOnboardRadio, PresentRadioSleepsBeforeBusRelease) { - FakeRadioIO io; - EXPECT_EQ(rak3401::sleepOnboardRadio(io, "SX1261"), rak3401::OnboardRadioState::Asleep); - EXPECT_EQ(io.calls, "begin reset busy-low version release-pulls busy-low sleep busy-high end "); -} - -TEST(RakOnboardRadio, AbsentAndFloatingResponsesNeverReceiveSleep) { - for (const std::string version : {std::string(6, '\0'), std::string(6, '\xff'), std::string("SX126X")}) { - FakeRadioIO io; - io.version = version; - EXPECT_EQ(rak3401::sleepOnboardRadio(io, "SX1261"), rak3401::OnboardRadioState::Absent); - EXPECT_EQ(io.calls, "begin reset busy-low version end "); - } -} - -TEST(RakOnboardRadio, BusyTimeoutsReleaseBusWithoutSleep) { - for (unsigned failure = 0; failure < 2; failure++) { - FakeRadioIO io; - io.ready[failure] = false; - EXPECT_EQ(rak3401::sleepOnboardRadio(io, "SX1261"), rak3401::OnboardRadioState::BusyTimeout); - EXPECT_EQ(io.calls.find("sleep "), std::string::npos); - EXPECT_EQ(io.calls, failure == 0 ? "begin reset busy-low end " : - "begin reset busy-low version release-pulls busy-low end "); - } -} - -TEST(RakOnboardRadio, MissingSleepReadbackIsReportedAndBusReleased) { - FakeRadioIO io; - io.ready[2] = false; - EXPECT_EQ(rak3401::sleepOnboardRadio(io, "SX1261"), rak3401::OnboardRadioState::SleepFailed); - EXPECT_EQ(io.calls.substr(io.calls.size() - 4), "end "); -} - -int main(int argc, char** argv) { - ::testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} From 5662e79a780a23da5477205fde1eaf127bb6971c Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Wed, 11 Nov 2026 07:37:24 -0400 Subject: [PATCH 375/381] companion_radio: rewrite mdns part removing String class --- examples/companion_radio/main.cpp | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index c534772c..367d7bfa 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -276,27 +276,30 @@ void setup() { #endif #ifdef HAS_ESP_MDNS - String nodeName = the_mesh.getNodeName(); - String sanitizedNodeName; - sanitizedNodeName.reserve(nodeName.length()); - for (size_t i = 0; i < nodeName.length(); ++i) { + const char* nodeName = the_mesh.getNodeName(); + + // "meshcore_" prefix + sanitized node name, capped at 63 chars (max DNS label length) + char mdnsName[64]; + const size_t prefixLen = snprintf(mdnsName, sizeof(mdnsName), "meshcore_"); + size_t pos = prefixLen; + for (size_t i = 0; nodeName[i] != '\0' && pos < sizeof(mdnsName) - 1; ++i) { const char c = nodeName[i]; if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_') { - sanitizedNodeName += c; + mdnsName[pos++] = c; } } + mdnsName[pos] = '\0'; - String mdnsName = "meshcore_"; - mdnsName += sanitizedNodeName; - if (!MDNS.begin(mdnsName.c_str())) { + if (!MDNS.begin(mdnsName)) { WIFI_DEBUG_PRINTLN("mDNS failed to start!"); } else { MDNS.addService("meshcore", "tcp", TCP_PORT); - MDNS.addServiceTxt("meshcore", "tcp", "node-name", the_mesh.getNodeName()); + MDNS.addServiceTxt("meshcore", "tcp", "node-name", nodeName); MDNS.addServiceTxt("meshcore", "tcp", "firmware-version", FIRMWARE_VERSION); - String protocol; protocol+=FIRMWARE_VER_CODE; - MDNS.addServiceTxt("meshcore", "tcp", "protocol-version", protocol.c_str()); + char protocol[12]; + snprintf(protocol, sizeof(protocol), "%d", (int)FIRMWARE_VER_CODE); + MDNS.addServiceTxt("meshcore", "tcp", "protocol-version", protocol); MDNS.addServiceTxt("meshcore", "tcp", "build-date", __DATE__); MDNS.addServiceTxt("meshcore", "tcp", "build-time", __TIME__); } From cefd4c76cf28377b800262788090bcc91808a43b Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Wed, 11 Nov 2026 07:49:41 -0400 Subject: [PATCH 376/381] Revert "Merge pull request #3784 from Maxwell456/feature/repeater-history" This reverts commit 66d404eac8e2be6fdfeeffda0bdf15f0bf9285ec, reversing changes made to 1c4b237d7303a1ee48324fb12eeb64331725f498. --- docs/cli_commands.md | 7 -- docs/payloads.md | 26 +--- docs/repeater_history.md | 84 ------------- examples/simple_repeater/MyMesh.cpp | 108 +--------------- examples/simple_repeater/MyMesh.h | 26 ---- examples/simple_sensor/SensorMesh.cpp | 12 +- examples/simple_sensor/SensorMesh.h | 5 +- examples/simple_sensor/TimeSeriesData.cpp | 45 +++++++ examples/simple_sensor/TimeSeriesData.h | 29 ++++- examples/simple_sensor/main.cpp | 5 +- platformio.ini | 1 - src/helpers/TimeSeriesData.cpp | 91 -------------- src/helpers/TimeSeriesData.h | 38 ------ test/test_time_series/test_time_series.cpp | 138 --------------------- 14 files changed, 85 insertions(+), 530 deletions(-) delete mode 100644 docs/repeater_history.md create mode 100644 examples/simple_sensor/TimeSeriesData.cpp delete mode 100644 src/helpers/TimeSeriesData.cpp delete mode 100644 src/helpers/TimeSeriesData.h delete mode 100644 test/test_time_series/test_time_series.cpp diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 1488c646..754f5120 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1247,13 +1247,6 @@ Covers serial NMEA receivers (`MicroNMEALocationProvider`). --- -### Repeater health history - -History is queried over the mesh using the sensor-compatible `0x04` min/max/average -request; there is no history CLI command. Retention and recording interval are controlled -by `REPEATER_HISTORY_SLOTS` and `REPEATER_HISTORY_INTERVAL_SECS` at build time. -See [Repeater health history](repeater_history.md) for the channel mapping and flags. - ### Ethernet (when Ethernet support is compiled in) Ethernet support is available on RAK4631 boards with a RAK13800 (W5100S) Ethernet module. Use the `_ethernet` firmware variants (e.g. `RAK_4631_repeater_ethernet`) to enable this feature. diff --git a/docs/payloads.md b/docs/payloads.md index c60a78d6..493f628c 100644 --- a/docs/payloads.md +++ b/docs/payloads.md @@ -103,7 +103,7 @@ For the common chat/server helpers in `BaseChatMesh`, the current request type v | `0x01` | get stats | get stats of repeater or room server | | `0x02` | keepalive | (deprecated) | | `0x03` | get telemetry | request node telemetry | -| `0x04` | get min/max/avg | get sensor or repeater time series statistics | +| `0x04` | get min/max/avg | get sensor node stats on time series data | | `0x05` | get acl | node ACL query | | `0x06` | get neighbors | node neighbors query | | `0x08` | subscribe | subscribe to telemetry push | @@ -140,7 +140,7 @@ Gets information about the node, possibly including the following: | req type | 1 | 0x03 (request sub type) | | permission mask | 1 | bitwise inverse mask to AND to permissions (0 = get ALL telem values) | -#### Get Min/Max/Ave (Sensor and repeater nodes) +#### Get Min/Max/Ave (Sensor nodes) | Field | Size (bytes) | Description | |----------------|--------------|------------------------------| @@ -150,28 +150,6 @@ Gets information about the node, possibly including the following: | end | 4 | ending time, seconds ago | | reserved | 2 | should be zeroes | -Requires an authenticated client with the READ_ONLY role or higher. The range includes -samples whose age is `end <= age < start`, in seconds. Request integers are little-endian. -The repeater uses exactly the sensor request and response layout. - -The response body (after decryption) is: - -| Field | Size (bytes) | Description | -|----------------|--------------|-------------| -| tag | 4 | echoed request timestamp, little-endian | -| current time | 4 | current node RTC Unix time, little-endian | -| series | variable | up to 8 series records, described below | - -Each series record contains a channel byte, an LPP type byte, then min, max, and average -in that order. Each value uses the type's Cayenne LPP size, multiplier, sign, and -big-endian encoding. There is no count byte; parse records to the end of the response. -Nonzero reserved bytes return only the tag and current time. - -Repeater history is pull-only, uses uptime internally, and omits series with no valid -samples in the requested range. Its returned current time still comes from the RTC; -an unset or corrected RTC does not affect sampling or range selection. See -[Repeater health history](repeater_history.md) for channels, retention, and build flags. - #### Subscribe to Telemetry push - (Sensor nodes) | Field | Size (bytes) | Description | diff --git a/docs/repeater_history.md b/docs/repeater_history.md deleted file mode 100644 index 35b37d82..00000000 --- a/docs/repeater_history.md +++ /dev/null @@ -1,84 +0,0 @@ -# Repeater health history - -The simple repeater keeps health samples in RAM and answers mesh request -`REQ_TYPE_GET_AVG_MIN_MAX` (`0x04`). A logged-in client needs READ_ONLY access or -higher. This is pull-only: recording history sends no packets. Existing GET_STATUS -and telemetry responses are unchanged. - -## Series - -| Channel | LPP type | Value recorded each interval | -|---------|----------|------------------------------| -| 200 | `LPP_VOLTAGE` (116) | Battery voltage in V, averaged from periodic reads every 15 seconds | -| 201 | `LPP_ANALOG_INPUT` (2, signed) | Radio noise floor in dBm at the end of the interval | -| 202 | `LPP_PERCENTAGE` (120) | TX airtime percentage over the elapsed interval | -| 203 | `LPP_PERCENTAGE` (120) | RX airtime percentage over the elapsed interval | -| 204 | `LPP_TEMPERATURE` (103) | MCU temperature in degrees C, when supported | - -These channels are dedicated to history. Existing self telemetry and GPS use channel 1; -`EnvironmentSensorManager` assigns at most 16 active entries to channels 2–17. Channels -200–204 therefore do not collide with current repeater telemetry. Custom sensor managers -should leave this range free. History channels do not change the channels in `0x03`. - -Battery averaging reduces the effect of short voltage dips during transmission. Noise -floor and temperature are point samples. Recording advances on fixed interval boundaries -without accumulating loop delays; the airtime denominator uses a separate actual -measurement timestamp. TX/RX values are unsigned counter deltas in -milliseconds divided by the actual elapsed interval, multiplied by 100. Percentages -use the sensor protocol's integer LPP encoding, so fractional percentages are truncated. -NaN temperatures and the radio driver's uncalibrated noise-floor sentinel (0 dBm) -are skipped. At most five series are returned, below the eight-series reply limit. - -## Query and retention - -Use the [sensor-compatible `0x04` request](payloads.md#get-minmaxave-sensor-and-repeater-nodes): -start and end are seconds ago, followed by two zero reserved bytes. For example, -`start=3600, end=0` selects samples from the last hour, including age zero and excluding -age 3600. The reply echoes the request timestamp, adds the current RTC time, and then -encodes each series as channel, LPP type, min, max, average. There is no series count. -Empty series are omitted; an empty range returns just the eight-byte header. - -Sampling and queries use monotonic uptime, accumulated across `millis()` wraps. The -RTC is used only for the response timestamp. Samples occupy a fixed interval grid -anchored at the first valid sample. Missed intervals are empty (NaN) slots; a gap -at least as long as the ring capacity expires the old ring. Late readings are assigned -to their interval boundary, so their reported age can differ by less than one interval. -Only one timestamp is stored per series. -Unsigned second differences handle seconds-counter wrap; retained samples and query -ranges must span less than one full 32-bit seconds cycle (about 136 years). - -The first sample is recorded after one interval. Each series retains the configured -number of interval slots, including missing intervals. History is lost on reboot and -is not written to flash. - -## Build flags - -| Flag | Default | Description | -|------|---------|-------------| -| `REPEATER_HISTORY_INTERVAL_SECS` | `300` | Positive recording interval in seconds | -| `REPEATER_HISTORY_SLOTS` | `288`, or `0` on STM32/RP2040 | Interval slots per series; nominally 24 hours at five-minute intervals when enabled | - -Set these using PlatformIO `build_flags`, for example `-D REPEATER_HISTORY_SLOTS=144` -for nominally 12 hours. `-D REPEATER_HISTORY_SLOTS=0` removes history members, -allocations, sampling, and handling of `0x04` entirely. STM32 and RP2040 builds default -to disabled history to conserve RAM; they can explicitly opt in with a smaller slot count. -There are no history CLI settings. - -For both nRF52 and ESP32, sample storage is `5 * slots * 4` bytes (one float per -interval), or 5,760 bytes at the defaults. Comparing enabled and disabled builds shows -168 additional bytes in the enclosing mesh object on both platforms (including padding), -for a total of 5,928 bytes plus allocator overhead for five arrays. Unsupported temperature still reserves -its series storage. Query results use temporary stack space, not retained history RAM. - -## Custom sensor sketch compatibility - -The old `examples/simple_sensor/TimeSeriesData.h` include forwards to the shared helper. -Deprecated `RTCClock*` overloads remain available for existing custom sketches. They -ignore the RTC and use a shared, wrap-safe `millis()` accumulator; callers should migrate -to explicit monotonic seconds. Call the legacy API regularly enough to observe each -`millis()` wrap (less than about 49 days between calls), and use one clock API consistently -for each series. The shared legacy clock is linked only when these overloads are used. - -The integer literal `0` is ambiguous between the seconds and pointer overloads. Use a -`uint32_t` variable (or `uint32_t(0)`) for uptime zero, and `nullptr` for a legacy null -clock argument. diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index 7d06811f..21f833a5 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -1,8 +1,5 @@ #include "MyMesh.h" #include <algorithm> -#if REPEATER_HISTORY_SLOTS > 0 -#include <helpers/sensors/LPPDataHelpers.h> -#endif /* ------------------------------ Config -------------------------------- */ @@ -49,9 +46,6 @@ #define REQ_TYPE_GET_STATUS 0x01 // same as _GET_STATS #define REQ_TYPE_KEEP_ALIVE 0x02 #define REQ_TYPE_GET_TELEMETRY_DATA 0x03 -#if REPEATER_HISTORY_SLOTS > 0 -#define REQ_TYPE_GET_AVG_MIN_MAX 0x04 -#endif #define REQ_TYPE_GET_ACCESS_LIST 0x05 #define REQ_TYPE_GET_NEIGHBOURS 0x06 #define REQ_TYPE_GET_OWNER_INFO 0x07 // FIRMWARE_VER_LEVEL >= 2 @@ -215,7 +209,6 @@ uint8_t MyMesh::handleAnonClockReq(const mesh::Identity& sender, uint32_t sender } int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t *payload, size_t payload_len) { - if (payload_len == 0) return 0; // uint32_t now = getRTCClock()->getCurrentTimeUnique(); // memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag') @@ -266,48 +259,6 @@ int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t memcpy(&reply_data[4], telemetry.getBuffer(), tlen); return 4 + tlen; // reply_len } -#if REPEATER_HISTORY_SLOTS > 0 - if (payload[0] == REQ_TYPE_GET_AVG_MIN_MAX && payload_len >= 11 && - (sender->permissions & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { - uint32_t start_secs_ago, end_secs_ago; - memcpy(&start_secs_ago, &payload[1], 4); - memcpy(&end_secs_ago, &payload[5], 4); - MinMaxAvg data[8]; - int n = 0; - if (payload[9] == 0 && payload[10] == 0) { - uint32_t now_secs = uptime_millis / 1000; - battery_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n++], HISTORY_BATTERY, - LPP_VOLTAGE); - noise_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n++], HISTORY_NOISE, - LPP_ANALOG_INPUT); - tx_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n++], HISTORY_TX, - LPP_PERCENTAGE); - rx_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n++], HISTORY_RX, - LPP_PERCENTAGE); - temperature_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n], HISTORY_TEMPERATURE, - LPP_TEMPERATURE); - // Unsupported temperature sensors and empty ranges have no encodable LPP value. - if (!isnan(data[n]._avg)) n++; - } - uint8_t ofs = 4; - uint32_t now = getRTCClock()->getCurrentTime(); - memcpy(&reply_data[ofs], &now, 4); - ofs += 4; - for (int i = 0; i < n; i++) { - auto d = &data[i]; - if (isnan(d->_avg)) continue; - reply_data[ofs++] = d->_channel; - reply_data[ofs++] = d->_lpp_type; - uint8_t sz = LPPData::getDataSize(d->_lpp_type); - uint32_t mult = LPPData::getMultiplier(d->_lpp_type); - bool is_signed = LPPData::isSigned(d->_lpp_type); - ofs += LPPData::putFloat(&reply_data[ofs], d->_min, sz, mult, is_signed); - ofs += LPPData::putFloat(&reply_data[ofs], d->_max, sz, mult, is_signed); - ofs += LPPData::putFloat(&reply_data[ofs], d->_avg, sz, mult, is_signed); - } - return ofs; - } -#endif if (payload[0] == REQ_TYPE_GET_ACCESS_LIST && sender->isAdmin()) { uint8_t res1 = payload[1]; // reserved for future (extra query params) uint8_t res2 = payload[2]; @@ -912,13 +863,6 @@ void MyMesh::sendNodeDiscoverReq() { MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondClock &ms, mesh::RNG &rng, mesh::RTCClock &rtc, mesh::MeshTables &tables) : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables), -#if REPEATER_HISTORY_SLOTS > 0 - battery_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS), - noise_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS), - tx_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS), - rx_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS), - temperature_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS), -#endif region_map(key_store), temp_map(key_store), _cli(board, rtc, sensors, region_map, acl, &_prefs, this), telemetry(MAX_PACKET_PAYLOAD - 4), @@ -933,12 +877,6 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc { last_millis = 0; uptime_millis = 0; -#if REPEATER_HISTORY_SLOTS > 0 - history_last_secs = history_battery_secs = history_airtime_secs = 0; - history_tx_millis = history_rx_millis = 0; - history_battery_total = 0; - history_battery_count = 0; -#endif next_local_advert = next_flood_advert = 0; dirty_contacts_expiry = 0; set_radio_at = revert_radio_at = 0; @@ -1349,48 +1287,7 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply } } -#if REPEATER_HISTORY_SLOTS > 0 -void MyMesh::recordHistory() { - uint32_t now_secs = uptime_millis / 1000; - // Average periodic reads without repeatedly enabling the battery divider. - if (uint32_t(now_secs - history_battery_secs) >= 15) { - history_battery_total += board.getBattMilliVolts(); - history_battery_count++; - history_battery_secs = now_secs; - } - uint32_t elapsed_secs = now_secs - history_last_secs; - if (elapsed_secs < REPEATER_HISTORY_INTERVAL_SECS) return; - // Advance the sampling grid without accumulating loop delays or replaying missed slots. - history_last_secs += (elapsed_secs / REPEATER_HISTORY_INTERVAL_SECS) * REPEATER_HISTORY_INTERVAL_SECS; - uint32_t airtime_elapsed_secs = now_secs - history_airtime_secs; - - if (history_battery_count > 0) { - battery_history.recordData(history_last_secs, history_battery_total / history_battery_count / 1000.0f); - } - int noise_floor = _radio->getNoiseFloor(); - if (noise_floor != 0) noise_history.recordData(history_last_secs, noise_floor); // zero means uncalibrated - uint32_t tx_millis = getTotalAirTime(); - uint32_t rx_millis = getReceiveAirTime(); - // Counters are milliseconds; unsigned subtraction also handles their wrap. - tx_history.recordData(history_last_secs, uint32_t(tx_millis - history_tx_millis) / (airtime_elapsed_secs * 10.0f)); - rx_history.recordData(history_last_secs, uint32_t(rx_millis - history_rx_millis) / (airtime_elapsed_secs * 10.0f)); - temperature_history.recordData(history_last_secs, board.getMCUTemperature()); // ignores NaN - history_airtime_secs = now_secs; - history_tx_millis = tx_millis; - history_rx_millis = rx_millis; - history_battery_total = 0; - history_battery_count = 0; -} -#endif - void MyMesh::loop() { - // Update before dispatching requests, including across millis() wrap. - uint32_t now = millis(); - uptime_millis += uint32_t(now - last_millis); - last_millis = now; -#if REPEATER_HISTORY_SLOTS > 0 - recordHistory(); -#endif #ifdef WITH_BRIDGE bridge.loop(); #endif @@ -1428,6 +1325,11 @@ void MyMesh::loop() { acl.save(_fs); dirty_contacts_expiry = 0; } + + // update uptime + uint32_t now = millis(); + uptime_millis += now - last_millis; + last_millis = now; } // To check if there is pending work diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index f30eedd0..7e4cfd4f 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -37,22 +37,6 @@ #include <helpers/RoutingPolicy.h> #include "RateLimiter.h" -#ifndef REPEATER_HISTORY_SLOTS -#if defined(STM32_PLATFORM) || defined(RP2040_PLATFORM) -#define REPEATER_HISTORY_SLOTS 0 -#else -#define REPEATER_HISTORY_SLOTS 288 -#endif -#endif -#ifndef REPEATER_HISTORY_INTERVAL_SECS -#define REPEATER_HISTORY_INTERVAL_SECS 300 -#endif - -#if REPEATER_HISTORY_SLOTS > 0 -#include <helpers/TimeSeriesData.h> -static_assert(REPEATER_HISTORY_INTERVAL_SECS > 0, "History interval must be positive"); -#endif - #ifdef WITH_BRIDGE extern AbstractBridge* bridge; #endif @@ -98,16 +82,6 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { FILESYSTEM* _fs; uint32_t last_millis; uint64_t uptime_millis; -#if REPEATER_HISTORY_SLOTS > 0 - // Dedicated history channels 200..204; environment telemetry occupies 1..17. - enum { HISTORY_BATTERY = 200, HISTORY_NOISE, HISTORY_TX, HISTORY_RX, HISTORY_TEMPERATURE }; - TimeSeriesData battery_history, noise_history, tx_history, rx_history, temperature_history; - uint32_t history_last_secs, history_battery_secs, history_airtime_secs; - uint32_t history_tx_millis, history_rx_millis; - float history_battery_total; - uint32_t history_battery_count; - void recordHistory(); -#endif unsigned long next_local_advert, next_flood_advert; bool _logging; NodePrefs _prefs; diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 2798c690..4916ddcd 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -790,9 +790,7 @@ SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::Millise { next_local_advert = next_flood_advert = 0; dirty_contacts_expiry = 0; - last_read_time = uint32_t(0) - SENSOR_READ_INTERVAL_SECS; // read immediately on the first loop - last_millis = 0; - uptime_millis = 0; + last_read_time = 0; num_alert_tasks = 0; set_radio_at = revert_radio_at = 0; recv_pkt_region = NULL; @@ -1002,9 +1000,6 @@ bool SensorMesh::getGPS(uint8_t channel, float& lat, float& lon, float& alt) { } void SensorMesh::loop() { - uint32_t now = millis(); - uptime_millis += uint32_t(now - last_millis); - last_millis = now; mesh::Mesh::loop(); if (next_flood_advert && millisHasNowPassed(next_flood_advert)) { @@ -1034,8 +1029,7 @@ void SensorMesh::loop() { } uint32_t curr = getRTCClock()->getCurrentTime(); - uint32_t uptime_secs = getUptimeSeconds(); - if (uint32_t(uptime_secs - last_read_time) >= SENSOR_READ_INTERVAL_SECS) { + if (curr >= last_read_time + SENSOR_READ_INTERVAL_SECS) { telemetry.reset(); telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f); // query other sensors -- target specific @@ -1076,7 +1070,7 @@ void SensorMesh::loop() { onSensorDataRead(); - last_read_time = uptime_secs; + last_read_time = curr; } // check the alert send queue diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index f1431f6f..e6746d47 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -3,7 +3,7 @@ #include <Arduino.h> // needed for PlatformIO #include <Mesh.h> -#include <helpers/TimeSeriesData.h> +#include "TimeSeriesData.h" #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) #include <InternalFileSystem.h> @@ -88,7 +88,6 @@ public: void sendFloodReply(mesh::Packet* packet, unsigned long delay_millis, uint8_t path_hash_size); protected: - uint32_t getUptimeSeconds() const { return uptime_millis / 1000; } // current telemetry data queries float getVoltage(uint8_t channel) { return getTelemValue(channel, LPP_VOLTAGE); } float getCurrent(uint8_t channel) { return getTelemValue(channel, LPP_CURRENT); } @@ -155,8 +154,6 @@ private: RegionEntry* load_stack[8]; TransportKey default_scope; uint32_t last_read_time; - uint32_t last_millis; - uint64_t uptime_millis; int matching_peer_indexes[MAX_SEARCH_RESULTS]; int num_alert_tasks; Trigger* alert_tasks[MAX_CONCURRENT_ALERTS]; diff --git a/examples/simple_sensor/TimeSeriesData.cpp b/examples/simple_sensor/TimeSeriesData.cpp new file mode 100644 index 00000000..f6157f9a --- /dev/null +++ b/examples/simple_sensor/TimeSeriesData.cpp @@ -0,0 +1,45 @@ +#include "TimeSeriesData.h" + +void TimeSeriesData::recordData(mesh::RTCClock* clock, float value) { + uint32_t now = clock->getCurrentTime(); + if (now >= last_timestamp + interval_secs) { + last_timestamp = now; + + data[next] = value; // append to cycle table + next = (next + 1) % num_slots; + } +} + +void TimeSeriesData::calcMinMaxAvg(mesh::RTCClock* clock, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg* dest, uint8_t channel, uint8_t lpp_type) const { + int i = next, n = num_slots; + uint32_t ago = clock->getCurrentTime() - last_timestamp; + int num_values = 0; + float total = 0.0f; + + dest->_channel = channel; + dest->_lpp_type = lpp_type; + + // start at most recet recording, back-track through to oldest + while (n > 0) { + n--; + i = (i + num_slots - 1) % num_slots; // go back by one + if (ago >= end_secs_ago && ago < start_secs_ago) { // filter by the desired time range + float v = data[i]; + num_values++; + total += v; + if (num_values == 1) { + dest->_max = dest->_min = v; + } else { + if (v < dest->_min) dest->_min = v; + if (v > dest->_max) dest->_max = v; + } + } + ago += interval_secs; + } + // calc average + if (num_values > 0) { + dest->_avg = total / num_values; + } else { + dest->_max = dest->_min = dest->_avg = NAN; + } +} diff --git a/examples/simple_sensor/TimeSeriesData.h b/examples/simple_sensor/TimeSeriesData.h index 41bf3189..6efa7834 100644 --- a/examples/simple_sensor/TimeSeriesData.h +++ b/examples/simple_sensor/TimeSeriesData.h @@ -1,4 +1,29 @@ #pragma once -// Compatibility include for custom sensor sketches; implementation lives in src/helpers. -#include <helpers/TimeSeriesData.h> +#include <Arduino.h> +#include <Mesh.h> + +struct MinMaxAvg { + float _min, _max, _avg; + uint8_t _lpp_type, _channel; +}; + +class TimeSeriesData { + float* data; + int num_slots, next; + uint32_t last_timestamp; + uint32_t interval_secs; + +public: + TimeSeriesData(float* array, int num, uint32_t secs) : num_slots(num), data(array), last_timestamp(0), next(0), interval_secs(secs) { + memset(data, 0, sizeof(float)*num); + } + TimeSeriesData(int num, uint32_t secs) : num_slots(num), last_timestamp(0), next(0), interval_secs(secs) { + data = new float[num]; + memset(data, 0, sizeof(float)*num); + } + + void recordData(mesh::RTCClock* clock, float value); + void calcMinMaxAvg(mesh::RTCClock* clock, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg* dest, uint8_t channel, uint8_t lpp_type) const; +}; + diff --git a/examples/simple_sensor/main.cpp b/examples/simple_sensor/main.cpp index 6d455f73..66991daa 100644 --- a/examples/simple_sensor/main.cpp +++ b/examples/simple_sensor/main.cpp @@ -21,14 +21,13 @@ protected: void onSensorDataRead() override { float batt_voltage = getVoltage(TELEM_CHANNEL_SELF); - battery_data.recordData(getUptimeSeconds(), batt_voltage); // record battery + battery_data.recordData(getRTCClock(), batt_voltage); // record battery alertIf(batt_voltage < 3.4f, critical_batt, HIGH_PRI_ALERT, "Battery is critical!"); alertIf(batt_voltage < 3.6f, low_batt, LOW_PRI_ALERT, "Battery is low"); } int querySeriesData(uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg dest[], int max_num) override { - battery_data.calcMinMaxAvg(getUptimeSeconds(), start_secs_ago, end_secs_ago, &dest[0], TELEM_CHANNEL_SELF, - LPP_VOLTAGE); + battery_data.calcMinMaxAvg(getRTCClock(), start_secs_ago, end_secs_ago, &dest[0], TELEM_CHANNEL_SELF, LPP_VOLTAGE); return 1; } diff --git a/platformio.ini b/platformio.ini index 7fdc8b64..f66fbf2e 100644 --- a/platformio.ini +++ b/platformio.ini @@ -174,7 +174,6 @@ build_src_filter = +<../src/Packet.cpp> +<../src/helpers/ConfigSerializer.cpp> +<../src/helpers/DynamicConfigSerializer.cpp> - +<../src/helpers/TimeSeriesData.cpp> lib_deps = google/googletest @ 1.17.0 diff --git a/src/helpers/TimeSeriesData.cpp b/src/helpers/TimeSeriesData.cpp deleted file mode 100644 index 371433c6..00000000 --- a/src/helpers/TimeSeriesData.cpp +++ /dev/null @@ -1,91 +0,0 @@ -#include "TimeSeriesData.h" - -#include <Arduino.h> -#include <math.h> - -TimeSeriesData::TimeSeriesData(float *array, int num, uint32_t secs) - : data(array), num_slots(num > 0 ? num : 0), next(0), count(0), last_timestamp(0), interval_secs(secs), - owns_data(array == nullptr) { - if (num_slots > 0) { - if (owns_data) data = new float[num_slots]; - } -} - -TimeSeriesData::~TimeSeriesData() { - if (owns_data) delete[] data; -} - -void TimeSeriesData::recordData(uint32_t now_secs, float value) { - if (num_slots == 0 || isnan(value)) return; - uint32_t steps = 1; - if (count > 0 && interval_secs > 0) { - uint32_t elapsed = now_secs - last_timestamp; - if (elapsed < interval_secs) return; - steps = elapsed / interval_secs; - last_timestamp += steps * interval_secs; // keep a fixed sampling grid - } else { - last_timestamp = now_secs; - } - - // A long pause expires the whole ring in O(capacity), never O(elapsed time). - if (steps >= uint32_t(num_slots)) { - next = count = 0; - } else { - for (uint32_t i = 1; i < steps; i++) { - data[next] = NAN; - next = (next + 1) % num_slots; - if (count < num_slots) count++; - } - } - - data[next] = value; - next = (next + 1) % num_slots; - if (count < num_slots) count++; -} - -void TimeSeriesData::calcMinMaxAvg(uint32_t now_secs, uint32_t start_secs_ago, uint32_t end_secs_ago, - MinMaxAvg *dest, uint8_t channel, uint8_t lpp_type) const { - dest->_channel = channel; - dest->_lpp_type = lpp_type; - dest->_min = dest->_max = dest->_avg = NAN; - int num_values = 0; - float total = 0.0f; - int i = next; - uint64_t ago = uint32_t(now_secs - last_timestamp); - for (int n = 0; n < count; n++) { - i = (i + num_slots - 1) % num_slots; - if (ago >= end_secs_ago && ago < start_secs_ago && !isnan(data[i])) { - float v = data[i]; - if (num_values == 0) { - dest->_min = dest->_max = v; - } else { - if (v < dest->_min) dest->_min = v; - if (v > dest->_max) dest->_max = v; - } - total += v; - num_values++; - } - ago += interval_secs; - } - if (num_values > 0) dest->_avg = total / num_values; -} - -// Shared only by legacy callers; never consult the RTC, even after a time sync. -// At least one legacy call is required per millis() wrap (about 49 days). -static uint32_t legacyMonotonicSeconds() { - static uint32_t last_millis = 0; - static uint64_t uptime_millis = 0; - uint32_t now = millis(); - uptime_millis += uint32_t(now - last_millis); - last_millis = now; - return uptime_millis / 1000; -} - -void TimeSeriesData::recordData(mesh::RTCClock *, float value) { - recordData(legacyMonotonicSeconds(), value); -} - -void TimeSeriesData::calcMinMaxAvg(mesh::RTCClock *, uint32_t start_secs_ago, uint32_t end_secs_ago, - MinMaxAvg *dest, uint8_t channel, uint8_t lpp_type) const { - calcMinMaxAvg(legacyMonotonicSeconds(), start_secs_ago, end_secs_ago, dest, channel, lpp_type); -} diff --git a/src/helpers/TimeSeriesData.h b/src/helpers/TimeSeriesData.h deleted file mode 100644 index 3b7cdd47..00000000 --- a/src/helpers/TimeSeriesData.h +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once - -#include <stdint.h> - -namespace mesh { -class RTCClock; -} - -struct MinMaxAvg { - float _min, _max, _avg; - uint8_t _lpp_type, _channel; -}; - -class TimeSeriesData { - float *data; - int num_slots, next, count; - uint32_t last_timestamp, interval_secs; - bool owns_data; - -public: - TimeSeriesData(float *array, int num, uint32_t secs); - TimeSeriesData(int num, uint32_t secs) : TimeSeriesData(nullptr, num, secs) {} - ~TimeSeriesData(); - TimeSeriesData(const TimeSeriesData &) = delete; - TimeSeriesData &operator=(const TimeSeriesData &) = delete; - - // Caller supplies monotonic seconds, accumulated across millisecond clock wraps. - void recordData(uint32_t now_secs, float value); - void calcMinMaxAvg(uint32_t now_secs, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg *dest, - uint8_t channel, uint8_t lpp_type) const; - - // Compatibility for custom sensor sketches. The RTC argument is ignored. - [[deprecated("Pass monotonic seconds instead of RTCClock*")]] - void recordData(mesh::RTCClock *clock, float value); - [[deprecated("Pass monotonic seconds instead of RTCClock*")]] - void calcMinMaxAvg(mesh::RTCClock *clock, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg *dest, - uint8_t channel, uint8_t lpp_type) const; -}; diff --git a/test/test_time_series/test_time_series.cpp b/test/test_time_series/test_time_series.cpp deleted file mode 100644 index eeb1aa6e..00000000 --- a/test/test_time_series/test_time_series.cpp +++ /dev/null @@ -1,138 +0,0 @@ -#include <Arduino.h> -#include <MeshCore.h> -#include <cmath> -#include <gtest/gtest.h> -#include <helpers/TimeSeriesData.h> -#include <utility> - -static MinMaxAvg query(const TimeSeriesData &series, uint32_t now, uint32_t start, uint32_t end) { - MinMaxAvg result; - series.calcMinMaxAvg(now, start, end, &result, 200, 116); - return result; -} - -TEST(TimeSeriesData, RingWrapKeepsNewestSamples) { - TimeSeriesData series(3, 10); - for (uint32_t i = 1; i <= 5; i++) - series.recordData(i * 10, float(i)); - auto result = query(series, 50, 100, 0); - EXPECT_FLOAT_EQ(result._min, 3); - EXPECT_FLOAT_EQ(result._max, 5); - EXPECT_FLOAT_EQ(result._avg, 4); - EXPECT_EQ(result._channel, 200); - EXPECT_EQ(result._lpp_type, 116); -} - -TEST(TimeSeriesData, RangeIncludesEndAndExcludesStart) { - TimeSeriesData series(4, 10); - series.recordData(10, -5); - series.recordData(20, -3); - series.recordData(30, -1); - series.recordData(40, 7); - auto result = query(series, 40, 30, 10); - EXPECT_FLOAT_EQ(result._min, -3); - EXPECT_FLOAT_EQ(result._max, -1); - EXPECT_FLOAT_EQ(result._avg, -2); -} - -TEST(TimeSeriesData, EmptyAndUnwrittenRangesReturnNaN) { - TimeSeriesData series(4, 10); - EXPECT_TRUE(std::isnan(query(series, 0, 100, 0)._avg)); - series.recordData(10, 4); - for (auto range : { std::pair<uint32_t, uint32_t>(100, 1), { 0, 0 }, { 1, 10 } }) { - auto result = query(series, 10, range.first, range.second); - EXPECT_TRUE(std::isnan(result._min)); - EXPECT_TRUE(std::isnan(result._max)); - EXPECT_TRUE(std::isnan(result._avg)); - } -} - -TEST(TimeSeriesData, CadenceAndNaNSamples) { - float storage[3]; - TimeSeriesData series(storage, 3, 10); - series.recordData(uint32_t(0), 2); // uptime zero is a valid first sample - series.recordData(9, 100); - EXPECT_FLOAT_EQ(query(series, 9, 100, 0)._avg, 2); - series.recordData(10, 4); - series.recordData(19, 100); - series.recordData(20, NAN); - series.recordData(20, 6); - EXPECT_FLOAT_EQ(query(series, 20, 100, 0)._avg, 4); -} - -TEST(TimeSeriesData, LargeGapsExpireOldSamplesAndDoNotStall) { - TimeSeriesData series(4, 300); - series.recordData(300, 1); - const uint32_t later = UINT32_MAX / 300 * 300; - series.recordData(later, 3); - EXPECT_FLOAT_EQ(query(series, later, 301, 0)._avg, 3); - EXPECT_FLOAT_EQ(query(series, later, UINT32_MAX, 0)._avg, 3); - series.recordData(later + uint32_t(300), 5); // seconds counter wrap - auto result = query(series, later + uint32_t(300), 301, 0); - EXPECT_FLOAT_EQ(result._min, 3); - EXPECT_FLOAT_EQ(result._max, 5); - EXPECT_FLOAT_EQ(result._avg, 4); -} - -TEST(TimeSeriesData, MissingIntervalsAreEmptyInsteadOfMovingOldSamplesForward) { - TimeSeriesData series(5, 10); - series.recordData(10, 2); - series.recordData(40, 8); - EXPECT_TRUE(std::isnan(query(series, 40, 30, 1)._avg)); - EXPECT_FLOAT_EQ(query(series, 40, 31, 0)._avg, 5); - series.recordData(52, 10); // late read belongs to the fixed slot at 50 - EXPECT_FLOAT_EQ(query(series, 52, 3, 0)._avg, 10); - EXPECT_TRUE(std::isnan(query(series, 52, 2, 0)._avg)); -} - -TEST(TimeSeriesData, QueryAgeDoesNotOverflowWhileWalkingTheRing) { - TimeSeriesData series(3, 10); - series.recordData(10, 1); - series.recordData(20, 2); - EXPECT_TRUE(std::isnan(query(series, uint32_t(20 + (UINT32_MAX - 5)), 100, 0)._avg)); -} - -TEST(TimeSeriesData, LegacyClockAPIUsesMonotonicTimeAcrossRTCAndMillisWrap) { - class Clock : public mesh::RTCClock { - public: - uint32_t time = 100000; - int reads = 0; - uint32_t getCurrentTime() override { - reads++; - return time; - } - void setCurrentTime(uint32_t value) override { time = value; } - } clock; - TimeSeriesData series(3, 1); - g_mock_millis = UINT32_MAX - 499; - series.recordData(&clock, 2); - clock.setCurrentTime(0); - g_mock_millis = 500; - series.recordData(&clock, 4); - MinMaxAvg result; - series.calcMinMaxAvg(&clock, 2, 0, &result, 1, 116); - EXPECT_FLOAT_EQ(result._avg, 3); - EXPECT_EQ(clock.reads, 0); -} - -TEST(TimeSeriesData, MillisecondCounterWrapDoesNotResetSeconds) { - TimeSeriesData series(3, 1); - uint32_t last_millis = UINT32_MAX - 499; - uint64_t uptime_millis = last_millis; - series.recordData(uint32_t(uptime_millis / 1000), 1); - uint32_t now = 500; - uptime_millis += uint32_t(now - last_millis); - series.recordData(uint32_t(uptime_millis / 1000), 3); - EXPECT_FLOAT_EQ(query(series, uint32_t(uptime_millis / 1000), 2, 0)._avg, 2); -} - -TEST(TimeSeriesData, ZeroCapacityIsEmpty) { - TimeSeriesData series(0, 10); - series.recordData(100, 1); - EXPECT_TRUE(std::isnan(query(series, 100, 1000, 0)._avg)); -} - -int main(int argc, char **argv) { - ::testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} From 7de440c0d38abc22f9067e35c3a758ad49f24ef0 Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Wed, 11 Nov 2026 07:58:39 -0400 Subject: [PATCH 377/381] gps_guard: remove time alert telemetry --- src/helpers/sensors/EnvironmentSensorManager.cpp | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/helpers/sensors/EnvironmentSensorManager.cpp b/src/helpers/sensors/EnvironmentSensorManager.cpp index 278677de..d038031b 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.cpp +++ b/src/helpers/sensors/EnvironmentSensorManager.cpp @@ -1,9 +1,6 @@ #include "EnvironmentSensorManager.h" #include <Wire.h> -#if ENV_INCLUDE_GPS && defined(GPS_GUARD) -#include <helpers/sensors/GpsGuard.h> -#endif #if ENV_PIN_SDA && ENV_PIN_SCL #define TELEM_WIRE &Wire1 // Use Wire1 as the I2C bus for Environment Sensors @@ -650,13 +647,6 @@ bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, Cayen _active_sensors[i].query(next_available_channel, _active_sensors[i].sub_channel, telemetry); next_available_channel++; } - #if ENV_INCLUDE_GPS && defined(GPS_GUARD) - // GPS-vs-clock offset in hours on its own channel while the guard's time alert is active - GpsGuard* guard = _location->getGuard(); - if (guard != nullptr && guard->isTimeAlert()) { - telemetry.addAnalogInput(next_available_channel++, guard->getAlertOffset() / 3600.0f); - } - #endif } return true; From 798b719caf9ebdee7a655de8cf58b5d58ecdb54e Mon Sep 17 00:00:00 2001 From: Florent <florent@frizoncorrea.fr> Date: Wed, 11 Nov 2026 09:52:03 -0400 Subject: [PATCH 378/381] CommonCLI: get/set loc to replace gps advert command --- docs/cli_commands.md | 6 +++++- src/helpers/CommonCLI.cpp | 30 ++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 754f5120..0a446e9c 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1101,6 +1101,8 @@ Covers serial NMEA receivers (`MicroNMEALocationProvider`). #### View or change the GPS advert policy **Usage:** +- `get advert.loc` +- `set advert.loc <policy>` - `gps advert` - `gps advert <policy>` @@ -1108,10 +1110,12 @@ Covers serial NMEA receivers (`MicroNMEALocationProvider`). - `policy`: `none`|`share`|`prefs` - `none`: don't include location in adverts - `share`: share gps location (from SensorManager) - - `prefs`: location stored in node's lat and lon settings + - `prefs`: location stored in node's lat and lon settings (can be different from gps value) **Default:** `prefs` +**Note:** `gps advert` command is the old format but is only accessible when a gps is attached to the unit. It has been kept for compatibility but one should prefer using `get/set` commands instead. + --- ### Sensors (When sensor support is compiled in) diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index 2c79bae1..64fed99b 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -467,6 +467,22 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep savePrefs(); strcpy(reply, "OK"); } + } else if (memcmp(config, "advert.loc ", 11) == 0) { + if (memcmp(config+11, "none", 4) == 0) { + _prefs->advert_loc_policy = ADVERT_LOC_NONE; + savePrefs(); + strcpy(reply, "OK"); + } else if (memcmp(config+11, "share", 5) == 0) { + _prefs->advert_loc_policy = ADVERT_LOC_SHARE; + savePrefs(); + strcpy(reply, "OK"); + } else if (memcmp(config+11, "prefs", 5) == 0) { + _prefs->advert_loc_policy = ADVERT_LOC_PREFS; + savePrefs(); + strcpy(reply, "OK"); + } else { + strcpy(reply, "Error, invalid policy"); + } } else if (memcmp(config, "guest.password ", 15) == 0) { StrHelper::strncpy(_prefs->guest_password, &config[15], sizeof(_prefs->guest_password)); savePrefs(); @@ -665,6 +681,20 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep sprintf(reply, "> %d", ((uint32_t) _prefs->flood_advert_interval)); } else if (memcmp(config, "advert.interval", 15) == 0) { sprintf(reply, "> %d", ((uint32_t) _prefs->advert_interval) * 2); + } else if (memcmp(config, "advert.loc", 10) == 0) { + switch (_prefs->advert_loc_policy) { + case ADVERT_LOC_NONE: + strcpy(reply, "> none"); + break; + case ADVERT_LOC_PREFS: + strcpy(reply, "> prefs"); + break; + case ADVERT_LOC_SHARE: + strcpy(reply, "> share"); + break; + default: + strcpy(reply, "Error, invalid policy"); + } } else if (memcmp(config, "guest.password", 14) == 0) { sprintf(reply, "> %s", _prefs->guest_password); } else if (sender_timestamp == 0 && memcmp(config, "prv.key", 7) == 0) { // from serial command line only From ace5230ff0767898d4643269c1e72a913f87e9c8 Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko <tishenko.alexandr@gmail.com> Date: Wed, 11 Nov 2026 16:18:58 +0200 Subject: [PATCH 379/381] GPS guard: drop leftovers of the alert telemetry channel #3813 removed the telemetry channel for the GPS time alert. Remove the docs sentence that still described it and the now unused GpsGuard::getAlertOffset(). --- docs/cli_commands.md | 2 +- src/helpers/sensors/GpsGuard.h | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 469de260..bc30adbd 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1085,7 +1085,7 @@ GPS time is written to the clock only while such a fix is current, never earlier Covers serial NMEA receivers (`MicroNMEALocationProvider`). **Usage:** -- `gps guard`: status, e.g. `> ok 7sat time ok +1s`, `> rej region time rej nofix`, `> ok 7sat time wait` (last check passed, no current trusted fix to check again, e.g. GPS asleep between periodic fixes), or `... ALERT gps-clk +3600s 75m` when a trusted fix has disagreed with the clock by the same offset for `GPS_GUARD_ALERT_MIN` minutes. While the alert is active, the offset in hours is also reported in telemetry on the next free channel. +- `gps guard`: status, e.g. `> ok 7sat time ok +1s`, `> rej region time rej nofix`, `> ok 7sat time wait` (last check passed, no current trusted fix to check again, e.g. GPS asleep between periodic fixes), or `... ALERT gps-clk +3600s 75m` when a trusted fix has disagreed with the clock by the same offset for `GPS_GUARD_ALERT_MIN` minutes. - `gps guard on`, `gps guard off`: turn the guard on or off (saved, default on). While off, every fix and GPS time is accepted and `gps guard` shows `off`. - `gps guard accept`: while an alert is active, confirm that the GPS time is right and apply it to the clock. - `gps fence`, `gps fence <metres>`: fence radius around the configured `lat`/`lon` (`0` = off). Default `GPS_GUARD_FENCE_M` (1000); a value set here is saved. diff --git a/src/helpers/sensors/GpsGuard.h b/src/helpers/sensors/GpsGuard.h index 66f4b92f..46b1936c 100644 --- a/src/helpers/sensors/GpsGuard.h +++ b/src/helpers/sensors/GpsGuard.h @@ -133,7 +133,6 @@ public: strcpy(_time_status, "-"); } bool isTimeAlert() const { return _time_alert; } - long getAlertOffset() const { return _time_disagree_offset; } // Fix as reported by the receiver: lat/lon in micro-degrees, HDOP in tenths (255 = unknown), // gps_time = UTC epoch of the fix. Returns true if the fix can be stored as trusted. From d1be1cbef0a525d6c4f86cf05a0068d20f54180d Mon Sep 17 00:00:00 2001 From: nullrouten0 <201262769+nullrouten0@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:58:36 +0000 Subject: [PATCH 380/381] GPS: stop MicroNMEA reading past the NMEA buffer Add a 16-byte zeroed tail behind the 100-byte NMEA buffer. MicroNMEA's fixed-width field skips can read a few bytes past the end of a malformed sentence; with the tail those reads land on NUL bytes. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- src/helpers/sensors/MicroNMEALocationProvider.h | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index bc9f5efa..09b4d955 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -23,7 +23,12 @@ #endif class MicroNMEALocationProvider : public LocationProvider { - char _nmeaBuffer[100]; + // MicroNMEA never writes past the length it is given, but its fixed-width field + // skips can read a few bytes past the end of a malformed sentence. The zeroed tail + // lets those reads stop on NUL bytes instead of reading the members that follow. + static constexpr size_t NMEA_BUFFER_LEN = 100; + static constexpr size_t NMEA_BUFFER_TAIL = 16; + char _nmeaBuffer[NMEA_BUFFER_LEN + NMEA_BUFFER_TAIL] = {}; MicroNMEA nmea; mesh::RTCClock* _clock; NmeaGpsDriver* _driver; @@ -135,7 +140,7 @@ class MicroNMEALocationProvider : public LocationProvider { public: MicroNMEALocationProvider(NmeaGpsDriver& driver, mesh::RTCClock* clock = nullptr) - : nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), _driver(&driver) {} + : nmea(_nmeaBuffer, NMEA_BUFFER_LEN), _clock(clock), _driver(&driver) {} void begin() override { _begin_calls++; From 8c06b34156a8da5582e8f77bc02715f35fc6c61e Mon Sep 17 00:00:00 2001 From: liamcottle <liam@liamcottle.com> Date: Thu, 12 Nov 2026 16:08:30 +1300 Subject: [PATCH 381/381] fix for mdns string not compiling due to ambiguous overload --- examples/companion_radio/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index 367d7bfa..b6d6643d 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -299,7 +299,7 @@ void setup() { MDNS.addServiceTxt("meshcore", "tcp", "firmware-version", FIRMWARE_VERSION); char protocol[12]; snprintf(protocol, sizeof(protocol), "%d", (int)FIRMWARE_VER_CODE); - MDNS.addServiceTxt("meshcore", "tcp", "protocol-version", protocol); + MDNS.addServiceTxt("meshcore", "tcp", "protocol-version", (const char*)protocol); MDNS.addServiceTxt("meshcore", "tcp", "build-date", __DATE__); MDNS.addServiceTxt("meshcore", "tcp", "build-time", __TIME__); }