From e8ace69fc05ce5a195fdcb3d4cd2d05ebbdfa271 Mon Sep 17 00:00:00 2001 From: Quency-D Date: Wed, 22 Jul 2026 16:33:05 +0800 Subject: [PATCH 01/29] Add heltec-rc52 board --- boards/heltec-rc52.json | 61 ++++++ src/helpers/ui/NV3001BDisplay.cpp | 29 +-- src/helpers/ui/NV3001BDisplay.h | 20 +- variants/heltec_rc52/HeltecRC52Board.cpp | 88 +++++++++ variants/heltec_rc52/HeltecRC52Board.h | 23 +++ .../heltec_rc52/HeltecRC52RotaryInput.cpp | 128 ++++++++++++ variants/heltec_rc52/HeltecRC52RotaryInput.h | 26 +++ variants/heltec_rc52/platformio.ini | 187 ++++++++++++++++++ variants/heltec_rc52/target.cpp | 52 +++++ variants/heltec_rc52/target.h | 38 ++++ variants/heltec_rc52/variant.cpp | 92 +++++++++ variants/heltec_rc52/variant.h | 101 ++++++++++ 12 files changed, 830 insertions(+), 15 deletions(-) create mode 100644 boards/heltec-rc52.json create mode 100644 variants/heltec_rc52/HeltecRC52Board.cpp create mode 100644 variants/heltec_rc52/HeltecRC52Board.h create mode 100644 variants/heltec_rc52/HeltecRC52RotaryInput.cpp create mode 100644 variants/heltec_rc52/HeltecRC52RotaryInput.h create mode 100644 variants/heltec_rc52/platformio.ini create mode 100644 variants/heltec_rc52/target.cpp create mode 100644 variants/heltec_rc52/target.h create mode 100644 variants/heltec_rc52/variant.cpp create mode 100644 variants/heltec_rc52/variant.h diff --git a/boards/heltec-rc52.json b/boards/heltec-rc52.json new file mode 100644 index 00000000..404aac19 --- /dev/null +++ b/boards/heltec-rc52.json @@ -0,0 +1,61 @@ +{ + "build": { + "arduino": { + "ldscript": "nrf52840_s140_v6.ld" + }, + "core": "nRF5", + "cpu": "cortex-m4", + "extra_flags": "-DNRF52840_XXAA", + "f_cpu": "64000000L", + "hwids": [ + ["0x239A", "0x8071"], + ["0x239A", "0x0071"], + ["0x239A", "0x8072"] + ], + "usb_product": "HT-n5262", + "mcu": "nrf52840", + "variant": "heltec_rc52", + "bsp": { + "name": "adafruit" + }, + "softdevice": { + "sd_flags": "-DS140", + "sd_name": "s140", + "sd_version": "6.1.1", + "sd_fwid": "0x00B6" + }, + "bootloader": { + "settings_addr": "0xFF000" + } + }, + "connectivity": [ + "bluetooth", + "lora" + ], + "debug": { + "jlink_device": "nRF52840_xxAA", + "svd_path": "nrf52840.svd", + "openocd_target": "nrf52.cfg" + }, + "frameworks": [ + "arduino" + ], + "name": "Heltec RC52", + "upload": { + "maximum_ram_size": 237568, + "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": "https://heltec.org/", + "vendor": "Heltec" +} diff --git a/src/helpers/ui/NV3001BDisplay.cpp b/src/helpers/ui/NV3001BDisplay.cpp index 03825cc0..5440904f 100644 --- a/src/helpers/ui/NV3001BDisplay.cpp +++ b/src/helpers/ui/NV3001BDisplay.cpp @@ -203,25 +203,25 @@ static void writeOptionalPin(int pin, int level) { } void NV3001BDisplay::writeCommand(uint8_t cmd) { - spi.beginTransaction(SPISettings(SPI_FREQUENCY, MSBFIRST, SPI_MODE0)); + spi->beginTransaction(SPISettings(SPI_FREQUENCY, MSBFIRST, SPI_MODE0)); digitalWrite(PIN_TFT_DC, LOW); digitalWrite(PIN_TFT_CS, LOW); - spi.transfer(cmd); + spi->transfer(cmd); digitalWrite(PIN_TFT_CS, HIGH); - spi.endTransaction(); + spi->endTransaction(); } void NV3001BDisplay::writeBytes(const uint8_t* data, size_t len) { if (!data || len == 0) return; - spi.beginTransaction(SPISettings(SPI_FREQUENCY, MSBFIRST, SPI_MODE0)); + spi->beginTransaction(SPISettings(SPI_FREQUENCY, MSBFIRST, SPI_MODE0)); digitalWrite(PIN_TFT_DC, HIGH); digitalWrite(PIN_TFT_CS, LOW); for (size_t i = 0; i < len; i++) { - spi.transfer(data[i]); + spi->transfer(data[i]); } digitalWrite(PIN_TFT_CS, HIGH); - spi.endTransaction(); + spi->endTransaction(); } void NV3001BDisplay::writeCommandData(uint8_t cmd, const uint8_t* data, size_t len) { @@ -253,15 +253,15 @@ void NV3001BDisplay::writeColor(uint16_t rgb, uint32_t count) { uint8_t hi = rgb >> 8; uint8_t lo = rgb & 0xff; - spi.beginTransaction(SPISettings(SPI_FREQUENCY, MSBFIRST, SPI_MODE0)); + spi->beginTransaction(SPISettings(SPI_FREQUENCY, MSBFIRST, SPI_MODE0)); digitalWrite(PIN_TFT_DC, HIGH); digitalWrite(PIN_TFT_CS, LOW); while (count--) { - spi.transfer(hi); - spi.transfer(lo); + spi->transfer(hi); + spi->transfer(lo); } digitalWrite(PIN_TFT_CS, HIGH); - spi.endTransaction(); + spi->endTransaction(); } void NV3001BDisplay::initPanel() { @@ -416,6 +416,7 @@ void NV3001BDisplay::drawChar(int x, int y, char ch) { bool NV3001BDisplay::begin() { if (is_on) return true; + if (!spi) return false; if (periph_power) periph_power->claim(); @@ -427,7 +428,13 @@ bool NV3001BDisplay::begin() { digitalWrite(PIN_TFT_DC, HIGH); delay(20); - spi.begin(PIN_TFT_SCL, PIN_TFT_MISO, PIN_TFT_SDA, PIN_TFT_CS); +#if defined(NRF52_PLATFORM) + spi->begin(); +#elif defined(ESP_PLATFORM) || defined(ESP32_PLATFORM) + spi->begin(PIN_TFT_SCL, PIN_TFT_MISO, PIN_TFT_SDA, PIN_TFT_CS); +#else + spi->begin(); +#endif if (PIN_TFT_RST >= 0) { pinMode(PIN_TFT_RST, OUTPUT); digitalWrite(PIN_TFT_RST, HIGH); diff --git a/src/helpers/ui/NV3001BDisplay.h b/src/helpers/ui/NV3001BDisplay.h index 98cdaae8..de47c102 100644 --- a/src/helpers/ui/NV3001BDisplay.h +++ b/src/helpers/ui/NV3001BDisplay.h @@ -20,12 +20,14 @@ #define NV3001B_PANEL_HEIGHT 220 #endif +class NV3001BDisplay : public DisplayDriver { +#if defined(ESP_PLATFORM) || defined(ESP32_PLATFORM) #ifndef NV3001B_SPI_HOST #define NV3001B_SPI_HOST HSPI #endif - -class NV3001BDisplay : public DisplayDriver { - SPIClass spi; + SPIClass owned_spi; +#endif + SPIClass* spi; RefCountedDigitalPin* periph_power; bool is_on = false; uint16_t color = 0xffff; @@ -43,8 +45,18 @@ class NV3001BDisplay : public DisplayDriver { void drawChar(int x, int y, char ch); public: +#if defined(ESP_PLATFORM) || defined(ESP32_PLATFORM) NV3001BDisplay(RefCountedDigitalPin* power = nullptr) : - DisplayDriver(NV3001B_LOGICAL_WIDTH, NV3001B_LOGICAL_HEIGHT), spi(NV3001B_SPI_HOST), periph_power(power) { } + DisplayDriver(NV3001B_LOGICAL_WIDTH, NV3001B_LOGICAL_HEIGHT), + owned_spi(NV3001B_SPI_HOST), spi(&owned_spi), periph_power(power) { } + + NV3001BDisplay(SPIClass* displaySpi, RefCountedDigitalPin* power = nullptr) : + DisplayDriver(NV3001B_LOGICAL_WIDTH, NV3001B_LOGICAL_HEIGHT), + owned_spi(NV3001B_SPI_HOST), spi(displaySpi ? displaySpi : &owned_spi), periph_power(power) { } +#else + NV3001BDisplay(SPIClass* displaySpi = &SPI, RefCountedDigitalPin* power = nullptr) : + DisplayDriver(NV3001B_LOGICAL_WIDTH, NV3001B_LOGICAL_HEIGHT), spi(displaySpi), periph_power(power) { } +#endif bool begin(); static const char* driverName() { return "NV3001B"; } diff --git a/variants/heltec_rc52/HeltecRC52Board.cpp b/variants/heltec_rc52/HeltecRC52Board.cpp new file mode 100644 index 00000000..39fc6ddc --- /dev/null +++ b/variants/heltec_rc52/HeltecRC52Board.cpp @@ -0,0 +1,88 @@ +#include "HeltecRC52Board.h" + +#include +#include + +extern void variant_shutdown(); + +#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 HeltecRC52Board::initiateShutdown(uint8_t reason) +{ + shutdownPeripherals(); + + bool enable_lpcomp = (reason == SHUTDOWN_REASON_LOW_VOLTAGE || + reason == SHUTDOWN_REASON_BOOT_PROTECT); + pinMode(PIN_ADC_CTRL, OUTPUT); + digitalWrite(PIN_ADC_CTRL, enable_lpcomp ? ADC_CTRL_ENABLED : !ADC_CTRL_ENABLED); + + if (enable_lpcomp) { + configureVoltageWake(power_config.lpcomp_ain_channel, power_config.lpcomp_refsel); + } + + enterSystemOff(reason); +} +#endif + +void HeltecRC52Board::begin() +{ + NRF52BoardDCDC::begin(); + + pinMode(PIN_VBAT_READ, INPUT); + pinMode(PIN_ADC_CTRL, OUTPUT); + digitalWrite(PIN_ADC_CTRL, !ADC_CTRL_ENABLED); + +#if defined(PIN_BOARD_SDA) && defined(PIN_BOARD_SCL) + Wire.setPins(PIN_BOARD_SDA, PIN_BOARD_SCL); +#endif + Wire.begin(); + + pinMode(RADIOCORE_VFEM_CTRL, OUTPUT); + digitalWrite(RADIOCORE_VFEM_CTRL, HIGH); + pinMode(RADIOCORE_FEM_EN, OUTPUT); + digitalWrite(RADIOCORE_FEM_EN, HIGH); + + pinMode(SENSOR_RST_PIN, OUTPUT); + digitalWrite(SENSOR_RST_PIN, HIGH); + pinMode(SENSOR_INT, INPUT); + + periph_power.begin(); + +#ifdef NRF52_POWER_MANAGEMENT + checkBootVoltage(&power_config); +#endif +} + +void HeltecRC52Board::shutdownPeripherals() +{ + NRF52Board::shutdownPeripherals(); + variant_shutdown(); +} + +uint16_t HeltecRC52Board::getBattMilliVolts() +{ + analogReadResolution(12); + analogReference(AR_INTERNAL_3_0); + pinMode(PIN_VBAT_READ, INPUT); + pinMode(PIN_ADC_CTRL, OUTPUT); + digitalWrite(PIN_ADC_CTRL, ADC_CTRL_ENABLED); + + delay(10); + uint32_t raw = 0; + for (int i = 0; i < 8; i++) { + raw += analogRead(PIN_VBAT_READ); + } + raw /= 8; + digitalWrite(PIN_ADC_CTRL, !ADC_CTRL_ENABLED); + + return (uint16_t)((float)raw * MV_LSB * ADC_MULTIPLIER); +} + +const char* HeltecRC52Board::getManufacturerName() const +{ + return "Heltec RC52"; +} diff --git a/variants/heltec_rc52/HeltecRC52Board.h b/variants/heltec_rc52/HeltecRC52Board.h new file mode 100644 index 00000000..f9a96db9 --- /dev/null +++ b/variants/heltec_rc52/HeltecRC52Board.h @@ -0,0 +1,23 @@ +#pragma once + +#include +#include +#include +#include + +class HeltecRC52Board : public NRF52BoardDCDC { +protected: +#ifdef NRF52_POWER_MANAGEMENT + void initiateShutdown(uint8_t reason) override; +#endif + +public: + RefCountedDigitalPin periph_power; + + HeltecRC52Board() : NRF52Board("RC52_OTA"), periph_power(SENSOR_POWER_CTRL_PIN, SENSOR_POWER_ON) {} + + void begin() override; + void shutdownPeripherals() override; + uint16_t getBattMilliVolts() override; + const char* getManufacturerName() const override; +}; diff --git a/variants/heltec_rc52/HeltecRC52RotaryInput.cpp b/variants/heltec_rc52/HeltecRC52RotaryInput.cpp new file mode 100644 index 00000000..8baea9f3 --- /dev/null +++ b/variants/heltec_rc52/HeltecRC52RotaryInput.cpp @@ -0,0 +1,128 @@ +#include "HeltecRC52RotaryInput.h" + +#include +#include + +namespace { +constexpr uint8_t TCA6408_ADDR = 0x20; +constexpr uint8_t TCA6408_INPUT_REG = 0x00; +constexpr uint8_t TCA6408_POLARITY_REG = 0x02; +constexpr uint8_t TCA6408_CONFIG_REG = 0x03; +constexpr uint8_t TCA6408_ROTARY_A_MASK = 0x01; +constexpr uint8_t TCA6408_ROTARY_B_MASK = 0x02; +constexpr uint8_t TCA6408_ROTARY_MASK = TCA6408_ROTARY_A_MASK | TCA6408_ROTARY_B_MASK; +constexpr uint32_t TCA6408_DEBOUNCE_MS = 5; +} + +bool HeltecRC52RotaryInput::begin() +{ + initialized = true; + ready = false; + input_state = TCA6408_ROTARY_MASK; + active_low_phase = false; + + if (periph_power && !power_claimed) { + periph_power->claim(); + power_claimed = true; + delay(12); + } + + if (!writeRegister(TCA6408_POLARITY_REG, 0x00) || !writeRegister(TCA6408_CONFIG_REG, 0xFF)) { + return false; + } + + uint8_t state = 0; + if (!readInput(state)) { + return false; + } + + input_state = state & TCA6408_ROTARY_MASK; + ready = true; + return true; +} + +RotaryInputEvent HeltecRC52RotaryInput::poll() +{ + if (!initialized) { + begin(); + return RotaryInputEvent::None; + } + + if (!ready) { + return RotaryInputEvent::None; + } + + uint8_t new_state = 0; + if (!readInput(new_state)) { + return RotaryInputEvent::None; + } + + new_state &= TCA6408_ROTARY_MASK; + RotaryInputEvent event = handleTransition(new_state); + input_state = new_state; + return event; +} + +bool HeltecRC52RotaryInput::writeRegister(uint8_t reg, uint8_t value) +{ + Wire.beginTransmission(TCA6408_ADDR); + Wire.write(reg); + Wire.write(value); + return Wire.endTransmission() == 0; +} + +bool HeltecRC52RotaryInput::readInput(uint8_t& value) +{ + Wire.beginTransmission(TCA6408_ADDR); + Wire.write(TCA6408_INPUT_REG); + if (Wire.endTransmission(false) != 0) { + return false; + } + if (Wire.requestFrom(TCA6408_ADDR, static_cast(1)) != 1) { + return false; + } + + value = Wire.read(); + return true; +} + +RotaryInputEvent HeltecRC52RotaryInput::handleTransition(uint8_t newState) +{ + uint8_t changed = (input_state ^ newState) & TCA6408_ROTARY_MASK; + RotaryInputEvent event = RotaryInputEvent::None; + bool a_low = (newState & TCA6408_ROTARY_A_MASK) == 0; + bool b_low = (newState & TCA6408_ROTARY_B_MASK) == 0; + + if (!a_low && !b_low) { + active_low_phase = false; + } + + if (!active_low_phase && (changed & TCA6408_ROTARY_A_MASK) && a_low && !b_low) { + event = RotaryInputEvent::Prev; + active_low_phase = true; + } else if (!active_low_phase && (changed & TCA6408_ROTARY_B_MASK) && b_low && !a_low) { + event = RotaryInputEvent::Next; + active_low_phase = true; + } + + if (event == RotaryInputEvent::None && !active_low_phase && (changed & TCA6408_ROTARY_A_MASK)) { + bool a_rising = (newState & TCA6408_ROTARY_A_MASK) != 0; + if (a_rising && b_low) { + event = RotaryInputEvent::Prev; + } + } + + if (event == RotaryInputEvent::None && !active_low_phase && (changed & TCA6408_ROTARY_B_MASK)) { + bool b_rising = (newState & TCA6408_ROTARY_B_MASK) != 0; + if (b_rising && a_low) { + event = RotaryInputEvent::Next; + } + } + + if (event == RotaryInputEvent::None || (millis() - last_event_ms) < TCA6408_DEBOUNCE_MS) { + return RotaryInputEvent::None; + } + + last_event_ms = millis(); + return event; +} diff --git a/variants/heltec_rc52/HeltecRC52RotaryInput.h b/variants/heltec_rc52/HeltecRC52RotaryInput.h new file mode 100644 index 00000000..4aa6f823 --- /dev/null +++ b/variants/heltec_rc52/HeltecRC52RotaryInput.h @@ -0,0 +1,26 @@ +#pragma once + +#include +#include + +class HeltecRC52RotaryInput : public RotaryInput { +public: + explicit HeltecRC52RotaryInput(RefCountedDigitalPin* periphPower = nullptr) : periph_power(periphPower) { } + + bool begin() override; + RotaryInputEvent poll() override; + bool isReady() const override { return ready; } + +private: + bool writeRegister(uint8_t reg, uint8_t value); + bool readInput(uint8_t& value); + RotaryInputEvent handleTransition(uint8_t newState); + + uint8_t input_state = 0x03; + uint32_t last_event_ms = 0; + bool ready = false; + bool initialized = false; + bool power_claimed = false; + bool active_low_phase = false; + RefCountedDigitalPin* periph_power = nullptr; +}; diff --git a/variants/heltec_rc52/platformio.ini b/variants/heltec_rc52/platformio.ini new file mode 100644 index 00000000..99ec414f --- /dev/null +++ b/variants/heltec_rc52/platformio.ini @@ -0,0 +1,187 @@ +[heltec_rc52] +extends = nrf52_base +board = heltec-rc52 +board_build.ldscript = boards/nrf52840_s140_v6.ld +build_flags = ${nrf52_base.build_flags} + ${sensor_base.build_flags} + -I lib/nrf52/s140_nrf52_6.1.1_API/include + -I lib/nrf52/s140_nrf52_6.1.1_API/include/nrf52 + -I variants/heltec_rc52 + -I src/helpers/ui + -D HELTEC_RC52 + -D NRF52_POWER_MANAGEMENT + -D USE_SX1262 + -D RADIO_CLASS=CustomSX1262 + -D WRAPPER_CLASS=CustomSX1262Wrapper + -D P_LORA_DIO_1=11 + -D P_LORA_NSS=13 + -D P_LORA_RESET=32 + -D P_LORA_BUSY=24 + -D P_LORA_SCLK=25 + -D P_LORA_MISO=14 + -D P_LORA_MOSI=22 + -D LORA_TX_POWER=22 + -D SX126X_CURRENT_LIMIT=140 + -D SX126X_RX_BOOSTED_GAIN=1 +build_src_filter = ${nrf52_base.build_src_filter} + + + + + +<../variants/heltec_rc52> +lib_deps = + ${nrf52_base.lib_deps} + ${sensor_base.lib_deps} +debug_tool = jlink +upload_protocol = nrfutil + +[env:heltec_rc52_without_display_repeater] +extends = heltec_rc52 +build_src_filter = ${heltec_rc52.build_src_filter} + +<../examples/simple_repeater> +build_flags = + ${heltec_rc52.build_flags} + -D ADVERT_NAME='"Heltec RC52 Repeater"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=50 + +[env:heltec_rc52_without_display_room_server] +extends = heltec_rc52 +build_src_filter = ${heltec_rc52.build_src_filter} + +<../examples/simple_room_server> +build_flags = + ${heltec_rc52.build_flags} + -D ADVERT_NAME='"Heltec RC52 Room"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D ROOM_PASSWORD='"hello"' + +[env:heltec_rc52_without_display_companion_radio_ble] +extends = heltec_rc52 +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 712704 +build_flags = + ${heltec_rc52.build_flags} + -I examples/companion_radio/ui-new + -D DISPLAY_CLASS=NullDisplayDriver + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D BLE_PIN_CODE=123456 + -D OFFLINE_QUEUE_SIZE=256 +build_src_filter = ${heltec_rc52.build_src_filter} + + + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = + ${heltec_rc52.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[env:heltec_rc52_without_display_companion_radio_usb] +extends = heltec_rc52 +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 712704 +build_flags = + ${heltec_rc52.build_flags} + -I examples/companion_radio/ui-new + -D DISPLAY_CLASS=NullDisplayDriver + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 +build_src_filter = ${heltec_rc52.build_src_filter} + + + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = + ${heltec_rc52.lib_deps} + densaugeo/base64 @ ~1.4.0 + +; +; Heltec RC52 with NV3001B display +; +[heltec_rc52_with_display] +extends = heltec_rc52 +board_build.ldscript = boards/nrf52840_s140_v6.ld +build_flags = + ${heltec_rc52.build_flags} + -D HELTEC_RC52_WITH_DISPLAY + -D DISPLAY_CLASS=NV3001BDisplay +build_src_filter = ${heltec_rc52.build_src_filter} + + + + +lib_deps = + ${heltec_rc52.lib_deps} + +[env:heltec_rc52_repeater] +extends = heltec_rc52_with_display +build_src_filter = ${heltec_rc52_with_display.build_src_filter} + +<../examples/simple_repeater> +build_flags = + ${heltec_rc52_with_display.build_flags} + -D ADVERT_NAME='"Heltec RC52 Repeater"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=50 + +[env:heltec_rc52_room_server] +extends = heltec_rc52_with_display +build_src_filter = ${heltec_rc52_with_display.build_src_filter} + +<../examples/simple_room_server> +build_flags = + ${heltec_rc52_with_display.build_flags} + -D ADVERT_NAME='"Heltec RC52 Room"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D ROOM_PASSWORD='"hello"' + +[env:heltec_rc52_companion_radio_ble] +extends = heltec_rc52_with_display +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 712704 +build_flags = + ${heltec_rc52_with_display.build_flags} + -I examples/companion_radio/ui-new + -D PIN_BUZZER=5 + -D UI_HAS_ROTARY_INPUT + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D BLE_PIN_CODE=123456 + -D ENV_INCLUDE_GPS=1 + -D OFFLINE_QUEUE_SIZE=256 +build_src_filter = ${heltec_rc52_with_display.build_src_filter} + + + + + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = + ${heltec_rc52_with_display.lib_deps} + densaugeo/base64 @ ~1.4.0 + end2endzone/NonBlockingRTTTL@^1.3.0 + +[env:heltec_rc52_companion_radio_usb] +extends = heltec_rc52_with_display +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 712704 +build_flags = + ${heltec_rc52_with_display.build_flags} + -I examples/companion_radio/ui-new + -D PIN_BUZZER=5 + -D UI_HAS_ROTARY_INPUT + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D ENV_INCLUDE_GPS=1 +build_src_filter = ${heltec_rc52_with_display.build_src_filter} + + + + + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = + ${heltec_rc52_with_display.lib_deps} + densaugeo/base64 @ ~1.4.0 + end2endzone/NonBlockingRTTTL@^1.3.0 + +[env:heltec_rc52_kiss_modem] +extends = heltec_rc52 +build_src_filter = ${heltec_rc52.build_src_filter} + +<../examples/kiss_modem/> diff --git a/variants/heltec_rc52/target.cpp b/variants/heltec_rc52/target.cpp new file mode 100644 index 00000000..5b03951a --- /dev/null +++ b/variants/heltec_rc52/target.cpp @@ -0,0 +1,52 @@ +#include "target.h" + +#include +#include + +#if defined(UI_HAS_ROTARY_INPUT) +#include "HeltecRC52RotaryInput.h" +#endif + +#ifdef ENV_INCLUDE_GPS +#include +#endif + +HeltecRC52Board 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 +MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, PIN_GPS_RESET, PIN_GPS_EN); +EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); +#else +EnvironmentSensorManager sensors; +#endif + +#ifdef DISPLAY_CLASS +#ifdef HELTEC_RC52_WITH_DISPLAY +DISPLAY_CLASS display(&SPI1); +#else +DISPLAY_CLASS display; +#endif +MomentaryButton user_btn(PIN_USER_BTN, 1000, true); +#if defined(UI_HAS_ROTARY_INPUT) +static HeltecRC52RotaryInput rotaryInputImpl(&board.periph_power); +RotaryInput& rotary_input = rotaryInputImpl; +#endif +#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); +} diff --git a/variants/heltec_rc52/target.h b/variants/heltec_rc52/target.h new file mode 100644 index 00000000..efb7fdcb --- /dev/null +++ b/variants/heltec_rc52/target.h @@ -0,0 +1,38 @@ +#pragma once + +#define RADIOLIB_STATIC_ONLY 1 +#include +#include +#include +#include +#include +#include +#include + +#ifdef DISPLAY_CLASS +#include +#if defined(UI_HAS_ROTARY_INPUT) +#include +#endif +#ifdef HELTEC_RC52_WITH_DISPLAY +#include +#else +#include +#endif +#endif + +extern HeltecRC52Board board; +extern WRAPPER_CLASS radio_driver; +extern AutoDiscoverRTCClock rtc_clock; +extern EnvironmentSensorManager sensors; + +#ifdef DISPLAY_CLASS +extern DISPLAY_CLASS display; +extern MomentaryButton user_btn; +#if defined(UI_HAS_ROTARY_INPUT) +extern RotaryInput& rotary_input; +#endif +#endif + +bool radio_init(); +mesh::LocalIdentity radio_new_identity(); diff --git a/variants/heltec_rc52/variant.cpp b/variants/heltec_rc52/variant.cpp new file mode 100644 index 00000000..72b680d9 --- /dev/null +++ b/variants/heltec_rc52/variant.cpp @@ -0,0 +1,92 @@ +#include "variant.h" +#include "Arduino.h" +#include "nrf.h" +#include +#include "wiring_constants.h" +#include "wiring_digital.h" + +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}; + +static void resetOptionalPin(int pin) +{ + if (pin >= 0) nrf_gpio_cfg_default(pin); +} + +void initVariant() +{ + pinMode(PIN_BUTTON1, INPUT_PULLUP); + + pinMode(RADIOCORE_FEM_EN, OUTPUT); + digitalWrite(RADIOCORE_FEM_EN, HIGH); + + pinMode(RADIOCORE_VFEM_CTRL, OUTPUT); + digitalWrite(RADIOCORE_VFEM_CTRL, HIGH); + + pinMode(PIN_ADC_CTRL, OUTPUT); + digitalWrite(PIN_ADC_CTRL, !ADC_CTRL_ENABLED); + +#ifdef PIN_BUZZER + pinMode(PIN_BUZZER, OUTPUT); + digitalWrite(PIN_BUZZER, LOW); +#endif + + pinMode(PIN_TFT_EN, OUTPUT); + digitalWrite(PIN_TFT_EN, !PIN_TFT_EN_ACTIVE); + pinMode(PIN_TFT_BL, OUTPUT); + digitalWrite(PIN_TFT_BL, !PIN_TFT_BL_ACTIVE); + pinMode(PIN_TFT_CS, OUTPUT); + digitalWrite(PIN_TFT_CS, HIGH); +} + +void variant_shutdown() +{ + Wire.end(); + + digitalWrite(RADIOCORE_FEM_EN, LOW); + digitalWrite(RADIOCORE_VFEM_CTRL, LOW); + digitalWrite(PIN_ADC_CTRL, !ADC_CTRL_ENABLED); +#ifdef PIN_BUZZER + digitalWrite(PIN_BUZZER, LOW); +#endif + digitalWrite(PIN_TFT_BL, !PIN_TFT_BL_ACTIVE); + digitalWrite(PIN_TFT_EN, !PIN_TFT_EN_ACTIVE); + + nrf_gpio_cfg_default(PIN_BUTTON1); + nrf_gpio_cfg_default(PIN_ADC_CTRL); +#ifdef PIN_BUZZER + nrf_gpio_cfg_default(PIN_BUZZER); +#endif + + nrf_gpio_cfg_default(PIN_TFT_BL); + nrf_gpio_cfg_default(PIN_TFT_EN); + nrf_gpio_cfg_default(PIN_TFT_CS); + nrf_gpio_cfg_default(PIN_TFT_DC); + nrf_gpio_cfg_default(PIN_TFT_MOSI); + nrf_gpio_cfg_default(PIN_TFT_RST); + + nrf_gpio_cfg_default(PIN_SPI_MISO); + nrf_gpio_cfg_default(PIN_SPI_MOSI); + nrf_gpio_cfg_default(PIN_SPI_SCK); + + resetOptionalPin(PIN_SPI1_MISO); + nrf_gpio_cfg_default(PIN_SPI1_MOSI); + nrf_gpio_cfg_default(PIN_SPI1_SCK); + + nrf_gpio_cfg_default(PIN_GPS_EN); + nrf_gpio_cfg_default(PIN_GPS_RESET); + nrf_gpio_cfg_default(PIN_GPS_PPS); + nrf_gpio_cfg_default(PIN_GPS_RX); + nrf_gpio_cfg_default(PIN_GPS_TX); + + nrf_gpio_cfg_default(SENSOR_POWER_CTRL_PIN); + nrf_gpio_cfg_default(SENSOR_RST_PIN); + nrf_gpio_cfg_default(SENSOR_INT); + nrf_gpio_cfg_default(PIN_BOARD_SDA); + nrf_gpio_cfg_default(PIN_BOARD_SCL); + + nrf_gpio_cfg_default(RADIOCORE_FEM_EN); + nrf_gpio_cfg_default(RADIOCORE_VFEM_CTRL); +} diff --git a/variants/heltec_rc52/variant.h b/variants/heltec_rc52/variant.h new file mode 100644 index 00000000..3ecbc391 --- /dev/null +++ b/variants/heltec_rc52/variant.h @@ -0,0 +1,101 @@ +#ifndef _VARIANT_HELTEC_RC52_ +#define _VARIANT_HELTEC_RC52_ + +#define VARIANT_MCK (64000000ul) +#define USE_LFXO + +#include "WVariant.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define HARD_VERSION_ADDR (0xED000 + 7 * 4096 - 16 - 1) +#define HT_LICENSE_ADDR (0xED000 + 7 * 4096 - 16) +#define HT_LICENSE_ADDR_BASE (0xED000 + 6 * 4096) + +#define PINS_COUNT (48) +#define NUM_DIGITAL_PINS (48) +#define NUM_ANALOG_INPUTS (1) +#define NUM_ANALOG_OUTPUTS (0) + +#define PIN_LED1 (-1) +#define PIN_NEOPIXEL (-1) +#define NEOPIXEL_NUM 0 +#define LED_BUILTIN PIN_LED1 +#define LED_BLUE PIN_LED1 +#define LED_STATE_ON 1 + +#define PIN_BUTTON1 (32 + 10) // P1.10, external pull-up, active low +#define PIN_BUTTON_USER PIN_BUTTON1 +#define PIN_USER_BTN PIN_BUTTON1 + +#define ADC_RESOLUTION 14 +#define PIN_VBAT_READ (0 + 31) +#define PIN_ADC_CTRL (0 + 4) +#define ADC_CTRL_ENABLED HIGH +#define ADC_MULTIPLIER 4.9F +#define MV_LSB (3000.0F / 4096.0F) + +#define PWRMGT_VOLTAGE_BOOTLOCK 3300 +#define PWRMGT_LPCOMP_AIN 7 +#define PWRMGT_LPCOMP_REFSEL 1 + +#define WIRE_INTERFACES_COUNT 1 +// Default board-package I2C pins. +#define PIN_WIRE_SDA (0 + 6) +#define PIN_WIRE_SCL (0 + 29) + +// External connector I2C used by MeshCore sensors/rotary input. +#define PIN_BOARD_SDA (32 + 11) // P1.11 +#define PIN_BOARD_SCL (0 + 2) // P0.02 +#define SENSOR_POWER_CTRL_PIN (0 + 12) +#define SENSOR_POWER_ON HIGH +#define SENSOR_INT (0 + 20) +#define SENSOR_RST_PIN (32 + 15) + + +#define PIN_GPS_TX (0 + 8) // GPS TX toward MCU RX +#define PIN_GPS_RX (0 + 7) // MCU TX toward GPS RX +#define PIN_GPS_EN (32 + 9) +#define PIN_GPS_PPS (32 + 1) +#define PIN_GPS_RESET (32 + 6) +#define PIN_GPS_EN_ACTIVE HIGH +#define PIN_GPS_RESET_ACTIVE LOW +#define GPS_BAUD_RATE 9600 +#define GPS_THREAD_INTERVAL 50 +#define PERIPHERAL_WARMUP_MS 100 + +#define PIN_SERIAL1_RX PIN_GPS_RX +#define PIN_SERIAL1_TX PIN_GPS_TX + +#define PIN_TFT_CS (32 + 4) +#define PIN_TFT_RST (0 + 10) +#define PIN_TFT_DC (0 + 28) +#define PIN_TFT_SCL (0 + 30) +#define PIN_TFT_SDA (32 + 2) +#define PIN_TFT_EN (32 + 13) +#define PIN_TFT_EN_ACTIVE LOW +#define PIN_TFT_BL (0 + 9) +#define PIN_TFT_BL_ACTIVE HIGH +#define SPI_FREQUENCY 8000000 + +#define RADIOCORE_FEM_EN (0 + 26) +#define RADIOCORE_VFEM_CTRL (0 + 16) + +#define SPI_INTERFACES_COUNT 2 +#define SPI_32MHZ_INTERFACE 1 + +#define PIN_SPI_MISO (0 + 14) +#define PIN_SPI_MOSI (0 + 22) +#define PIN_SPI_SCK (0 + 25) + +#define PIN_SPI1_MISO (-1) +#define PIN_SPI1_MOSI PIN_TFT_SDA +#define PIN_SPI1_SCK PIN_TFT_SCL + +#ifdef __cplusplus +} +#endif + +#endif From a8dc73f368d40896c0f94c7c015df1cf5d2f2727 Mon Sep 17 00:00:00 2001 From: Quency-D Date: Wed, 22 Jul 2026 16:48:53 +0800 Subject: [PATCH 02/29] Modify the default I2C pin configuration --- variants/heltec_rc52/variant.cpp | 5 +---- variants/heltec_rc52/variant.h | 6 ++---- 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/variants/heltec_rc52/variant.cpp b/variants/heltec_rc52/variant.cpp index 72b680d9..b9c30863 100644 --- a/variants/heltec_rc52/variant.cpp +++ b/variants/heltec_rc52/variant.cpp @@ -48,9 +48,7 @@ void variant_shutdown() digitalWrite(RADIOCORE_FEM_EN, LOW); digitalWrite(RADIOCORE_VFEM_CTRL, LOW); digitalWrite(PIN_ADC_CTRL, !ADC_CTRL_ENABLED); -#ifdef PIN_BUZZER - digitalWrite(PIN_BUZZER, LOW); -#endif + digitalWrite(PIN_TFT_BL, !PIN_TFT_BL_ACTIVE); digitalWrite(PIN_TFT_EN, !PIN_TFT_EN_ACTIVE); @@ -64,7 +62,6 @@ void variant_shutdown() nrf_gpio_cfg_default(PIN_TFT_EN); nrf_gpio_cfg_default(PIN_TFT_CS); nrf_gpio_cfg_default(PIN_TFT_DC); - nrf_gpio_cfg_default(PIN_TFT_MOSI); nrf_gpio_cfg_default(PIN_TFT_RST); nrf_gpio_cfg_default(PIN_SPI_MISO); diff --git a/variants/heltec_rc52/variant.h b/variants/heltec_rc52/variant.h index 3ecbc391..a2225a2c 100644 --- a/variants/heltec_rc52/variant.h +++ b/variants/heltec_rc52/variant.h @@ -42,13 +42,11 @@ extern "C" { #define PWRMGT_LPCOMP_REFSEL 1 #define WIRE_INTERFACES_COUNT 1 -// Default board-package I2C pins. -#define PIN_WIRE_SDA (0 + 6) -#define PIN_WIRE_SCL (0 + 29) -// External connector I2C used by MeshCore sensors/rotary input. #define PIN_BOARD_SDA (32 + 11) // P1.11 #define PIN_BOARD_SCL (0 + 2) // P0.02 +#define PIN_WIRE_SDA PIN_BOARD_SDA +#define PIN_WIRE_SCL PIN_BOARD_SCL #define SENSOR_POWER_CTRL_PIN (0 + 12) #define SENSOR_POWER_ON HIGH #define SENSOR_INT (0 + 20) From b6f20133d26c07084c854db86a118f2349fd3f78 Mon Sep 17 00:00:00 2001 From: Quency-D Date: Thu, 23 Jul 2026 11:06:55 +0800 Subject: [PATCH 03/29] Adjust the sensor power-on sequence --- variants/heltec_rc52/HeltecRC52Board.cpp | 8 ++------ variants/heltec_rc52/platformio.ini | 2 ++ 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/variants/heltec_rc52/HeltecRC52Board.cpp b/variants/heltec_rc52/HeltecRC52Board.cpp index 39fc6ddc..299f0903 100644 --- a/variants/heltec_rc52/HeltecRC52Board.cpp +++ b/variants/heltec_rc52/HeltecRC52Board.cpp @@ -41,20 +41,16 @@ void HeltecRC52Board::begin() #endif Wire.begin(); - pinMode(RADIOCORE_VFEM_CTRL, OUTPUT); - digitalWrite(RADIOCORE_VFEM_CTRL, HIGH); - pinMode(RADIOCORE_FEM_EN, OUTPUT); - digitalWrite(RADIOCORE_FEM_EN, HIGH); - pinMode(SENSOR_RST_PIN, OUTPUT); digitalWrite(SENSOR_RST_PIN, HIGH); pinMode(SENSOR_INT, INPUT); - periph_power.begin(); #ifdef NRF52_POWER_MANAGEMENT checkBootVoltage(&power_config); #endif + periph_power.begin(); + periph_power.claim(); } void HeltecRC52Board::shutdownPeripherals() diff --git a/variants/heltec_rc52/platformio.ini b/variants/heltec_rc52/platformio.ini index 99ec414f..01bf48df 100644 --- a/variants/heltec_rc52/platformio.ini +++ b/variants/heltec_rc52/platformio.ini @@ -23,6 +23,8 @@ build_flags = ${nrf52_base.build_flags} -D LORA_TX_POWER=22 -D SX126X_CURRENT_LIMIT=140 -D SX126X_RX_BOOSTED_GAIN=1 + -D SX126X_DIO2_AS_RF_SWITCH=true + -D SX126X_DIO3_TCXO_VOLTAGE=1.8 build_src_filter = ${nrf52_base.build_src_filter} + + From 7e8aa9464729e5f8b7e27754394d9f174149d8a6 Mon Sep 17 00:00:00 2001 From: Quency-D Date: Thu, 23 Jul 2026 11:40:51 +0800 Subject: [PATCH 04/29] Change the screen display from pointer to reference --- src/helpers/ui/NV3001BDisplay.cpp | 27 +++++++++++++-------------- src/helpers/ui/NV3001BDisplay.h | 8 ++++---- variants/heltec_rc52/variant.h | 4 ++-- 3 files changed, 19 insertions(+), 20 deletions(-) diff --git a/src/helpers/ui/NV3001BDisplay.cpp b/src/helpers/ui/NV3001BDisplay.cpp index 5440904f..05dc968d 100644 --- a/src/helpers/ui/NV3001BDisplay.cpp +++ b/src/helpers/ui/NV3001BDisplay.cpp @@ -203,25 +203,25 @@ static void writeOptionalPin(int pin, int level) { } void NV3001BDisplay::writeCommand(uint8_t cmd) { - spi->beginTransaction(SPISettings(SPI_FREQUENCY, MSBFIRST, SPI_MODE0)); + spi.beginTransaction(SPISettings(SPI_FREQUENCY, MSBFIRST, SPI_MODE0)); digitalWrite(PIN_TFT_DC, LOW); digitalWrite(PIN_TFT_CS, LOW); - spi->transfer(cmd); + spi.transfer(cmd); digitalWrite(PIN_TFT_CS, HIGH); - spi->endTransaction(); + spi.endTransaction(); } void NV3001BDisplay::writeBytes(const uint8_t* data, size_t len) { if (!data || len == 0) return; - spi->beginTransaction(SPISettings(SPI_FREQUENCY, MSBFIRST, SPI_MODE0)); + spi.beginTransaction(SPISettings(SPI_FREQUENCY, MSBFIRST, SPI_MODE0)); digitalWrite(PIN_TFT_DC, HIGH); digitalWrite(PIN_TFT_CS, LOW); for (size_t i = 0; i < len; i++) { - spi->transfer(data[i]); + spi.transfer(data[i]); } digitalWrite(PIN_TFT_CS, HIGH); - spi->endTransaction(); + spi.endTransaction(); } void NV3001BDisplay::writeCommandData(uint8_t cmd, const uint8_t* data, size_t len) { @@ -253,15 +253,15 @@ void NV3001BDisplay::writeColor(uint16_t rgb, uint32_t count) { uint8_t hi = rgb >> 8; uint8_t lo = rgb & 0xff; - spi->beginTransaction(SPISettings(SPI_FREQUENCY, MSBFIRST, SPI_MODE0)); + spi.beginTransaction(SPISettings(SPI_FREQUENCY, MSBFIRST, SPI_MODE0)); digitalWrite(PIN_TFT_DC, HIGH); digitalWrite(PIN_TFT_CS, LOW); while (count--) { - spi->transfer(hi); - spi->transfer(lo); + spi.transfer(hi); + spi.transfer(lo); } digitalWrite(PIN_TFT_CS, HIGH); - spi->endTransaction(); + spi.endTransaction(); } void NV3001BDisplay::initPanel() { @@ -416,7 +416,6 @@ void NV3001BDisplay::drawChar(int x, int y, char ch) { bool NV3001BDisplay::begin() { if (is_on) return true; - if (!spi) return false; if (periph_power) periph_power->claim(); @@ -429,11 +428,11 @@ bool NV3001BDisplay::begin() { delay(20); #if defined(NRF52_PLATFORM) - spi->begin(); + spi.begin(); #elif defined(ESP_PLATFORM) || defined(ESP32_PLATFORM) - spi->begin(PIN_TFT_SCL, PIN_TFT_MISO, PIN_TFT_SDA, PIN_TFT_CS); + spi.begin(PIN_TFT_SCL, PIN_TFT_MISO, PIN_TFT_SDA, PIN_TFT_CS); #else - spi->begin(); + spi.begin(); #endif if (PIN_TFT_RST >= 0) { pinMode(PIN_TFT_RST, OUTPUT); diff --git a/src/helpers/ui/NV3001BDisplay.h b/src/helpers/ui/NV3001BDisplay.h index de47c102..52dd4a6e 100644 --- a/src/helpers/ui/NV3001BDisplay.h +++ b/src/helpers/ui/NV3001BDisplay.h @@ -27,7 +27,7 @@ class NV3001BDisplay : public DisplayDriver { #endif SPIClass owned_spi; #endif - SPIClass* spi; + SPIClass& spi; RefCountedDigitalPin* periph_power; bool is_on = false; uint16_t color = 0xffff; @@ -48,14 +48,14 @@ public: #if defined(ESP_PLATFORM) || defined(ESP32_PLATFORM) NV3001BDisplay(RefCountedDigitalPin* power = nullptr) : DisplayDriver(NV3001B_LOGICAL_WIDTH, NV3001B_LOGICAL_HEIGHT), - owned_spi(NV3001B_SPI_HOST), spi(&owned_spi), periph_power(power) { } + owned_spi(NV3001B_SPI_HOST), spi(owned_spi), periph_power(power) { } NV3001BDisplay(SPIClass* displaySpi, RefCountedDigitalPin* power = nullptr) : DisplayDriver(NV3001B_LOGICAL_WIDTH, NV3001B_LOGICAL_HEIGHT), - owned_spi(NV3001B_SPI_HOST), spi(displaySpi ? displaySpi : &owned_spi), periph_power(power) { } + owned_spi(NV3001B_SPI_HOST), spi(displaySpi ? *displaySpi : owned_spi), periph_power(power) { } #else NV3001BDisplay(SPIClass* displaySpi = &SPI, RefCountedDigitalPin* power = nullptr) : - DisplayDriver(NV3001B_LOGICAL_WIDTH, NV3001B_LOGICAL_HEIGHT), spi(displaySpi), periph_power(power) { } + DisplayDriver(NV3001B_LOGICAL_WIDTH, NV3001B_LOGICAL_HEIGHT), spi(displaySpi ? *displaySpi : SPI), periph_power(power) { } #endif bool begin(); diff --git a/variants/heltec_rc52/variant.h b/variants/heltec_rc52/variant.h index a2225a2c..58036abd 100644 --- a/variants/heltec_rc52/variant.h +++ b/variants/heltec_rc52/variant.h @@ -53,8 +53,8 @@ extern "C" { #define SENSOR_RST_PIN (32 + 15) -#define PIN_GPS_TX (0 + 8) // GPS TX toward MCU RX -#define PIN_GPS_RX (0 + 7) // MCU TX toward GPS RX +#define PIN_GPS_TX (0 + 8) +#define PIN_GPS_RX (0 + 7) #define PIN_GPS_EN (32 + 9) #define PIN_GPS_PPS (32 + 1) #define PIN_GPS_RESET (32 + 6) From 75bb7fd01ac44a71023209d6ee42d19838700bab Mon Sep 17 00:00:00 2001 From: Quency-D Date: Thu, 23 Jul 2026 15:53:18 +0800 Subject: [PATCH 05/29] Add LED --- variants/heltec_rc52/HeltecRC52Board.cpp | 11 +++++++++++ variants/heltec_rc52/HeltecRC52Board.h | 2 ++ variants/heltec_rc52/platformio.ini | 1 + 3 files changed, 14 insertions(+) diff --git a/variants/heltec_rc52/HeltecRC52Board.cpp b/variants/heltec_rc52/HeltecRC52Board.cpp index 299f0903..c1d4deea 100644 --- a/variants/heltec_rc52/HeltecRC52Board.cpp +++ b/variants/heltec_rc52/HeltecRC52Board.cpp @@ -49,6 +49,9 @@ void HeltecRC52Board::begin() #ifdef NRF52_POWER_MANAGEMENT checkBootVoltage(&power_config); #endif + pinMode(P_LORA_TX_LED, OUTPUT); + digitalWrite(P_LORA_TX_LED, LOW); // off by default, active high + periph_power.begin(); periph_power.claim(); } @@ -59,6 +62,14 @@ void HeltecRC52Board::shutdownPeripherals() variant_shutdown(); } +void HeltecRC52Board::onBeforeTransmit() { + digitalWrite(P_LORA_TX_LED, HIGH); +} + +void HeltecRC52Board::onAfterTransmit() { + digitalWrite(P_LORA_TX_LED, LOW); +} + uint16_t HeltecRC52Board::getBattMilliVolts() { analogReadResolution(12); diff --git a/variants/heltec_rc52/HeltecRC52Board.h b/variants/heltec_rc52/HeltecRC52Board.h index f9a96db9..548b1049 100644 --- a/variants/heltec_rc52/HeltecRC52Board.h +++ b/variants/heltec_rc52/HeltecRC52Board.h @@ -17,6 +17,8 @@ public: HeltecRC52Board() : NRF52Board("RC52_OTA"), periph_power(SENSOR_POWER_CTRL_PIN, SENSOR_POWER_ON) {} void begin() override; + void onBeforeTransmit() override; + void onAfterTransmit() override; void shutdownPeripherals() override; uint16_t getBattMilliVolts() override; const char* getManufacturerName() const override; diff --git a/variants/heltec_rc52/platformio.ini b/variants/heltec_rc52/platformio.ini index 01bf48df..f806127a 100644 --- a/variants/heltec_rc52/platformio.ini +++ b/variants/heltec_rc52/platformio.ini @@ -20,6 +20,7 @@ build_flags = ${nrf52_base.build_flags} -D P_LORA_SCLK=25 -D P_LORA_MISO=14 -D P_LORA_MOSI=22 + -D P_LORA_TX_LED=15 -D LORA_TX_POWER=22 -D SX126X_CURRENT_LIMIT=140 -D SX126X_RX_BOOSTED_GAIN=1 From e1a445b9678222e9818ed4a180b0fd99245c9d2e Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko Date: Wed, 11 Nov 2026 01:48:12 +0200 Subject: [PATCH 06/29] 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 `: 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 Date: Wed, 11 Nov 2026 05:23:22 +0100 Subject: [PATCH 07/29] 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 Date: Wed, 11 Nov 2026 07:26:01 -0400 Subject: [PATCH 08/29] 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 -#include -#include - -#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 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 -#include -// Exercise the real startup code with a power-management stub that stops at SYSTEMOFF. -#include "../../variants/rak3401/RAK3401Board.cpp" - -namespace startup_test { -std::vector events; -bool permitBoot; -std::array 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{"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{"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{"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 -#include -#include -#include "../../variants/rak3401/OnboardRadioSleep.h" - -namespace { -struct FakeRadioIO { - std::string version = "SX1261"; - std::array 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 Date: Wed, 11 Nov 2026 07:37:24 -0400 Subject: [PATCH 09/29] 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 Date: Wed, 11 Nov 2026 07:49:41 -0400 Subject: [PATCH 10/29] 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 -#if REPEATER_HISTORY_SLOTS > 0 -#include -#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 #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 -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 // needed for PlatformIO #include -#include +#include "TimeSeriesData.h" #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) #include @@ -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 +#include +#include + +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 -#include - -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 - -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 -#include -#include -#include -#include -#include - -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(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 Date: Wed, 11 Nov 2026 07:58:39 -0400 Subject: [PATCH 11/29] 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 -#if ENV_INCLUDE_GPS && defined(GPS_GUARD) -#include -#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 Date: Wed, 11 Nov 2026 09:52:03 -0400 Subject: [PATCH 12/29] 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 ` - `gps advert` - `gps advert ` @@ -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 Date: Wed, 11 Nov 2026 16:18:58 +0200 Subject: [PATCH 13/29] 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 `: 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 14/29] 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 --- 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 87679ba526cffba46cf619c0b20f80afad7ed738 Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko Date: Thu, 12 Nov 2026 00:34:05 +0200 Subject: [PATCH 15/29] GPS guard: reject a fix the receiver reports as 2D (GSA) The guard checked satellites and HDOP but not the fix type. When the receiver sends GSA, a fix it reports as 2D or no-fix is now rejected (`rej 2d`). Receivers without GSA are unchanged (fix mode unknown). GPS_GUARD_REQUIRE_3D=0 turns the check off. `gps diag` shows the fix mode as `fm`. --- docs/cli_commands.md | 2 +- src/helpers/sensors/GpsGuard.h | 17 +++++++++-- .../sensors/MicroNMEALocationProvider.h | 28 ++++++++++++++++++- 3 files changed, 42 insertions(+), 5 deletions(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index bc30adbd..01eed226 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1078,7 +1078,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. +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, a 3D fix if the receiver reports the fix mode in GSA (`GPS_GUARD_REQUIRE_3D`, default on; status `rej 2d`), 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 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. diff --git a/src/helpers/sensors/GpsGuard.h b/src/helpers/sensors/GpsGuard.h index 46b1936c..bcd949f4 100644 --- a/src/helpers/sensors/GpsGuard.h +++ b/src/helpers/sensors/GpsGuard.h @@ -4,7 +4,8 @@ // // 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 +// - acceptFix(): plausibility checks (satellites, HDOP, 3D fix if the receiver reports the fix +// mode, 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 @@ -25,6 +26,9 @@ #ifndef GPS_GUARD_MAX_HDOP10 #define GPS_GUARD_MAX_HDOP10 40 // HDOP 4.0 #endif +#ifndef GPS_GUARD_REQUIRE_3D + #define GPS_GUARD_REQUIRE_3D 1 // reject a fix the receiver reports as 2D (GSA); 0 = off +#endif #ifndef GPS_GUARD_FENCE_M #define GPS_GUARD_FENCE_M 1000 // max distance from the reference position (0 = off) #endif @@ -135,8 +139,10 @@ public: bool isTimeAlert() const { return _time_alert; } // 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) { + // gps_time = UTC epoch of the fix, fix_mode = receiver fix mode from GSA (1 = none, 2 = 2D, + // 3 = 3D, 0 = unknown: no recent GSA). 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, + uint8_t fix_mode = 0) { const double lat = lat_e6 / 1000000.0; const double lon = lon_e6 / 1000000.0; const unsigned long now = millis(); @@ -149,6 +155,11 @@ public: } else if (hdop10 == 255 || hdop10 > GPS_GUARD_MAX_HDOP10) { why = "hdop"; } +#if GPS_GUARD_REQUIRE_3D + else if (fix_mode == 1 || fix_mode == 2) { + why = "2d"; + } +#endif #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"; diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index 09b4d955..98f04e4b 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -54,6 +54,26 @@ class MicroNMEALocationProvider : public LocationProvider { bool _nmea_seen = false; #ifdef GPS_GUARD GpsGuard _guard; + uint8_t _gsa_fix_mode = 0; // fix mode from the last GSA: 1 = none, 2 = 2D, 3 = 3D + unsigned long _gsa_ms = 0; + + static bool isGsa(const char* id) { // GPGSA, GNGSA, BDGSA, ... + const size_t n = strlen(id); + return n >= 3 && strcmp(id + n - 3, "GSA") == 0; + } + // $--GSA,,,... + void parseGsa(const char* s) { + s = strchr(s, ','); + if (s != NULL) s = strchr(s + 1, ','); + if (s != NULL && s[1] >= '1' && s[1] <= '3') { + _gsa_fix_mode = s[1] - '0'; + _gsa_ms = millis(); + } + } + // 0 (unknown) if the receiver does not send GSA, or sent none recently + uint8_t currentFixMode() const { + return (_gsa_fix_mode != 0 && (uint32_t)(millis() - _gsa_ms) <= 2000) ? _gsa_fix_mode : 0; + } #endif static uint32_t ageMs(unsigned long timestamp) { @@ -94,7 +114,7 @@ class MicroNMEALocationProvider : public LocationProvider { #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; + nmea.getHDOP(), getTimestamp(), currentFixMode())) return false; #endif LastFix fix; @@ -336,6 +356,7 @@ public: const char* messageId = nmea.getMessageID(); #ifdef GPS_GUARD + if (isGsa(messageId)) parseGsa(nmea.getSentence()); if (parsed && !nmea.isValid() && (strcmp(messageId, "GGA") == 0 || strcmp(messageId, "RMC") == 0)) { _guard.noFix(nmea.getNumSatellites()); @@ -395,5 +416,10 @@ public: fix_age, (unsigned long)_begin_calls, (unsigned long)_stop_calls); +#ifdef GPS_GUARD + // fix mode from GSA (1 none, 2 2D, 3 3D, 0 no recent GSA) + const size_t len = strlen(out); + if (len < out_size) snprintf(out + len, out_size - len, " fm:%u", currentFixMode()); +#endif } }; From 8c06b34156a8da5582e8f77bc02715f35fc6c61e Mon Sep 17 00:00:00 2001 From: liamcottle Date: Thu, 12 Nov 2026 16:08:30 +1300 Subject: [PATCH 16/29] 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__); } From bf0ccfe2eb7b08efab625169aaeda3b4a96a4dbc Mon Sep 17 00:00:00 2001 From: Quency-D Date: Thu, 12 Nov 2026 14:20:08 +0800 Subject: [PATCH 17/29] Fix RC52 companion radio builds --- variants/heltec_rc52/platformio.ini | 2 ++ variants/heltec_rc52/target.cpp | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/variants/heltec_rc52/platformio.ini b/variants/heltec_rc52/platformio.ini index f806127a..d6526494 100644 --- a/variants/heltec_rc52/platformio.ini +++ b/variants/heltec_rc52/platformio.ini @@ -74,6 +74,7 @@ build_flags = -D OFFLINE_QUEUE_SIZE=256 build_src_filter = ${heltec_rc52.build_src_filter} + + + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = @@ -92,6 +93,7 @@ build_flags = -D MAX_GROUP_CHANNELS=40 build_src_filter = ${heltec_rc52.build_src_filter} + + + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = diff --git a/variants/heltec_rc52/target.cpp b/variants/heltec_rc52/target.cpp index 5b03951a..dc5652d8 100644 --- a/variants/heltec_rc52/target.cpp +++ b/variants/heltec_rc52/target.cpp @@ -20,7 +20,9 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, PIN_GPS_RESET, PIN_GPS_EN); +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; From 7762588e58acaf4a04dfc5f3a384f85628bf47eb Mon Sep 17 00:00:00 2001 From: Quency-D Date: Thu, 12 Nov 2026 15:54:21 +0800 Subject: [PATCH 18/29] Fix RC52 unused SPI1 MISO pin mapping Use pin index 0, which maps to NRFX_SPIM_PIN_NOT_USED, to avoid the nRF52 SPI constructor indexing g_ADigitalPinMap[255]. Remove the absent MISO shutdown reset so the sentinel cannot reset physical P0.00. Follows the variant-side fixes in #3188 and #3189. Validated heltec_rc52_repeater and heltec_rc52_companion_radio_ble builds. ELF disassembly confirms the MISO lookup uses map[0]=0xFF instead of the +1020-byte read and shutdown has no P0.00 reset. No hardware testing performed. --- variants/heltec_rc52/variant.cpp | 7 +------ variants/heltec_rc52/variant.h | 2 +- 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/variants/heltec_rc52/variant.cpp b/variants/heltec_rc52/variant.cpp index b9c30863..a4a090fa 100644 --- a/variants/heltec_rc52/variant.cpp +++ b/variants/heltec_rc52/variant.cpp @@ -10,11 +10,6 @@ const uint32_t g_ADigitalPinMap[] = { 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}; -static void resetOptionalPin(int pin) -{ - if (pin >= 0) nrf_gpio_cfg_default(pin); -} - void initVariant() { pinMode(PIN_BUTTON1, INPUT_PULLUP); @@ -68,7 +63,7 @@ void variant_shutdown() nrf_gpio_cfg_default(PIN_SPI_MOSI); nrf_gpio_cfg_default(PIN_SPI_SCK); - resetOptionalPin(PIN_SPI1_MISO); + // SPI1 MISO is not connected; its sentinel is not a physical GPIO. nrf_gpio_cfg_default(PIN_SPI1_MOSI); nrf_gpio_cfg_default(PIN_SPI1_SCK); diff --git a/variants/heltec_rc52/variant.h b/variants/heltec_rc52/variant.h index 58036abd..bd2662fb 100644 --- a/variants/heltec_rc52/variant.h +++ b/variants/heltec_rc52/variant.h @@ -88,7 +88,7 @@ extern "C" { #define PIN_SPI_MOSI (0 + 22) #define PIN_SPI_SCK (0 + 25) -#define PIN_SPI1_MISO (-1) +#define PIN_SPI1_MISO (0) // g_ADigitalPinMap[0] is 0xFF (NRFX_SPIM_PIN_NOT_USED). #define PIN_SPI1_MOSI PIN_TFT_SDA #define PIN_SPI1_SCK PIN_TFT_SCL From be9d278a968ed4dbd5b0fb9194b7e48b95da4797 Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko Date: Thu, 12 Nov 2026 10:48:10 +0200 Subject: [PATCH 19/29] Limit the first periodic GPS acquisition after boot Before the first fix since boot, a periodic acquisition had no timeout. If no fix is accepted (no sky view, no antenna, or a guard rejecting spoofed fixes), the receiver then stayed on until a fix was accepted. Give that window its own limit, GPS_FIRST_FIX_TIMEOUT_MS (15 min by default, enough for a full almanac; 0 keeps the old behaviour). It counts as a miss and the next acquisition starts after the configured period. --- docs/cli_commands.md | 2 +- src/helpers/sensors/MicroNMEALocationProvider.h | 16 ++++++++++++---- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index bc30adbd..f6c56ee3 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1026,7 +1026,7 @@ region save **Parameters:** - `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. +**Note:** A periodic acquisition stops after receiving a valid fix, then resumes after the configured period. Without a fix it stops after 5 minutes, or after 15 minutes until the first fix since boot (`GPS_PERIODIC_ACQUISITION_TIMEOUT_MS`, `GPS_FIRST_FIX_TIMEOUT_MS`). --- diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index 09b4d955..c44e1c47 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -12,6 +12,11 @@ #ifndef GPS_PERIODIC_ACQUISITION_TIMEOUT_MS #define GPS_PERIODIC_ACQUISITION_TIMEOUT_MS 300000UL #endif +// limit for the periodic window before the first fix since boot (cold start can be long, +// a full almanac takes 12.5 min); 0 = keep searching until a fix +#ifndef GPS_FIRST_FIX_TIMEOUT_MS + #define GPS_FIRST_FIX_TIMEOUT_MS 900000UL +#endif // in periodic mode, keep reading after the first valid fix until enough satellites // are used or the settle time has elapsed @@ -363,10 +368,13 @@ public: } } - // 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(); + // a longer limit until a first fix has been obtained (cold start can be long) + if (_acquiringPeriodically) { + const uint32_t limit = _lastFix.valid ? GPS_PERIODIC_ACQUISITION_TIMEOUT_MS + : GPS_FIRST_FIX_TIMEOUT_MS; + if (limit > 0 && (uint32_t)(millis() - _acquisitionStarted) >= limit) { + finishPeriodicAcquisition(); + } } updateTime(); From 9e70d32f792ca2e7876d8b482f4c39342fe54450 Mon Sep 17 00:00:00 2001 From: Eve <139727413+netrunnereve@users.noreply.github.com> Date: Mon, 2 Nov 2026 18:14:12 -0500 Subject: [PATCH 20/29] add cli option to set custom bluetooth name --- docs/companion_cli.md | 13 +++++++++++++ examples/companion_radio/MyMesh.cpp | 20 ++++++++++++++++++++ examples/companion_radio/NodePrefs.h | 2 ++ examples/companion_radio/main.cpp | 2 +- 4 files changed, 36 insertions(+), 1 deletion(-) diff --git a/docs/companion_cli.md b/docs/companion_cli.md index 87d94b55..4887d997 100644 --- a/docs/companion_cli.md +++ b/docs/companion_cli.md @@ -413,6 +413,19 @@ Radio parameters are common to all roles and handled by `CommonRadioPrefs`. --- +#### Change BLE name +**Usage:** +- `get ble_name` +- `set ble_name ` +- `set ble_name_default` + +**Parameters:** +- `name`: New BLE name + +**Note:** By default the node name will be used as the BLE name. These commands require a reboot to take effect. + +--- + ### Wifi #### Get status diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 1a1bcbe7..d1ba6e13 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2154,6 +2154,26 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* sprintf(reply, "> pin is now %06d", _prefs.ble_pin); return true; } + if (memcmp(command, "set ble_name ", 13) == 0) { + if (AdvertDataParser::isValidName(&command[13])) { + StrHelper::strncpy(_prefs.ble_name, &command[13], sizeof(_prefs.ble_name)); + savePrefs(); + sprintf(reply, "> BLE name is now %s (reboot to apply)", _prefs.ble_name); + } else { + strcpy(reply, "Error, bad chars"); + } + return true; + } + if (strcmp(command, "get ble_name") == 0) { + sprintf(reply, "> %s", _prefs.ble_name[0] ? _prefs.ble_name : _prefs.node_name); + return true; + } + if (strcmp(command, "set ble_name_default") == 0) { + _prefs.ble_name[0] = 0; + savePrefs(); + sprintf(reply, "> BLE name reset to %s (reboot to apply)", _prefs.node_name); + return true; + } #ifdef ENABLE_WIFI_INTERFACE if (memcmp(command, "set wifi.ssid ", 14) == 0) { diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index c5387976..b06ace7a 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -31,6 +31,7 @@ public: float tx_delay_factor = 0; float direct_tx_delay_factor = 0; uint32_t ble_pin = 0; + char ble_name[32] = {0}; uint8_t advert_loc_policy = 0; uint8_t buzzer_quiet = 0; uint8_t vibe_quiet = 0; @@ -216,6 +217,7 @@ private: 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("ble_name", _parent->ble_name, sizeof(_parent->ble_name)); def("buzz_q", _parent->buzzer_quiet); def("vibe_q", _parent->vibe_quiet); def("auto_add", _parent->autoadd_config); // bitmask for auto-add contacts config diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index b6d6643d..82f2b236 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -215,7 +215,7 @@ void setup() { // add bluetooth interface #if defined(BLE_PIN_CODE) - bluetooth_interface.begin(BLE_NAME_PREFIX, the_mesh.getNodePrefs()->node_name, the_mesh.getBLEPin()); + bluetooth_interface.begin(BLE_NAME_PREFIX, the_mesh.getNodePrefs()->ble_name[0] ? the_mesh.getNodePrefs()->ble_name : the_mesh.getNodePrefs()->node_name, the_mesh.getBLEPin()); interface_manager.addInterface(InterfaceType::Bluetooth, &bluetooth_interface); #endif From 407cb9abacf5557951eb12b8231e6f7bbf8b9d4b Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko Date: Fri, 13 Nov 2026 14:29:02 +0200 Subject: [PATCH 21/29] GPS: first fix timeout as a saved setting (gps firstfix), 1 h by default A cold start can take up to ~30 min with a weak sky view, so the default limit before the first fix since boot goes from 15 min to 1 h. The limit is now a GPS preference, set with `gps firstfix ` (0 = no limit, at most 1 day) and saved with the other GPS settings, so repeaters and companions can use different values without a rebuild. GPS_FIRST_FIX_TIMEOUT_MS stays as the build default. --- docs/cli_commands.md | 16 +++++- examples/companion_radio/NodePrefs.h | 8 +++ src/helpers/CommonCLI.h | 8 +++ src/helpers/CommonGpsPrefs.cpp | 54 +++++++++++++++---- src/helpers/CommonGpsPrefs.h | 3 ++ src/helpers/sensors/LocationProvider.h | 3 ++ .../sensors/MicroNMEALocationProvider.h | 18 +++++-- 7 files changed, 95 insertions(+), 15 deletions(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index f6c56ee3..7bd0e3ac 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1026,7 +1026,21 @@ region save **Parameters:** - `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. Without a fix it stops after 5 minutes, or after 15 minutes until the first fix since boot (`GPS_PERIODIC_ACQUISITION_TIMEOUT_MS`, `GPS_FIRST_FIX_TIMEOUT_MS`). +**Note:** A periodic acquisition stops after receiving a valid fix, then resumes after the configured period. Without a fix it stops after 5 minutes (`GPS_PERIODIC_ACQUISITION_TIMEOUT_MS`), or, until the first fix since boot, after the first fix timeout (see `gps firstfix`). + +--- + +#### View or change the first fix timeout +**Usage:** +- `gps firstfix` +- `gps firstfix ` + +**Parameters:** +- `value`: `0` for no limit, or a duration up to `1d`. The value can be postfixed with `s`, `m`, `h` or `d` to specify the unit (seconds by default). + +**Default:** `1h` (`GPS_FIRST_FIX_TIMEOUT_MS`) + +**Note:** In periodic mode, limits an acquisition until the first valid fix since boot. A cold start can take much longer than the usual 5 minutes with a weak sky view; after the limit the GPS sleeps for the period and tries again. Saved with the other GPS settings. --- diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index c5387976..09dbba0e 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 + int32_t gps_first_fix = -1; // first-fix timeout in seconds, 0 = no limit, -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) @@ -169,6 +170,7 @@ 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); + def("ffix", _parent->gps_first_fix); #ifdef GPS_GUARD def("fence", _parent->gps_fence); def("guard", _parent->gps_guard); @@ -180,6 +182,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 getFirstFixTimeout(uint32_t& seconds) const override { + if (_parent->gps_first_fix < 0) return false; + seconds = (uint32_t)_parent->gps_first_fix; + return true; + } + void setFirstFixTimeout(uint32_t seconds) override { _parent->gps_first_fix = (int32_t)seconds; markDirty(); } bool getGuardFence(uint32_t& metres) const override { if (_parent->gps_fence < 0) return false; metres = (uint32_t)_parent->gps_fence; diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index cb85f6f9..24b1fe26 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 + int32_t gps_first_fix = -1; // first-fix timeout in seconds, 0 = no limit, -1 = build default uint8_t gps_guard = 1; // GPS_GUARD on/off uint8_t advert_loc_policy = 0; uint32_t discovery_mod_timestamp = 0; @@ -164,6 +165,7 @@ 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); + def("ffix", _parent->gps_first_fix); #ifdef GPS_GUARD def("fence", _parent->gps_fence); def("guard", _parent->gps_guard); @@ -175,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 getFirstFixTimeout(uint32_t& seconds) const override { + if (_parent->gps_first_fix < 0) return false; + seconds = (uint32_t)_parent->gps_first_fix; + return true; + } + void setFirstFixTimeout(uint32_t seconds) override { _parent->gps_first_fix = (int32_t)seconds; markDirty(); } bool getGuardFence(uint32_t& metres) const override { if (_parent->gps_fence < 0) return false; metres = (uint32_t)_parent->gps_fence; diff --git a/src/helpers/CommonGpsPrefs.cpp b/src/helpers/CommonGpsPrefs.cpp index cdc889d0..d9768fe1 100644 --- a/src/helpers/CommonGpsPrefs.cpp +++ b/src/helpers/CommonGpsPrefs.cpp @@ -46,6 +46,8 @@ bool CommonGpsPrefs::apply(SensorManager& sensors) const { LocationProvider* location = sensors.getLocationProvider(); if (location == nullptr) return false; applyGuardReference(sensors); + uint32_t first_fix; + if (getFirstFixTimeout(first_fix)) location->setFirstFixTimeout(first_fix); location->setGpsPeriod(getGpsPeriod()); location->setGpsOn(isGpsEnabled()); return true; @@ -62,6 +64,20 @@ static void formatDuration(char* buf, size_t size, uint32_t seconds) { } } +// "[s|m|h|d]", seconds by default +static bool parseDuration(const char* text, uint32_t& seconds) { + char* end; + unsigned long value = strtoul(text, &end, 10); + 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 (text[0] == '\0' || *end != '\0') return false; + seconds = (uint32_t)(value * mult); + return true; +} + bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, char* reply) { if (strcmp(command, "gps") == 0) { LocationProvider* location = sensors.getLocationProvider(); @@ -180,17 +196,10 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, return true; } if (memcmp(command, "gps period ", 11) == 0) { - char* end; - unsigned long period = strtoul(command + 11, &end, 10); - 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') { + uint32_t period; + if (!parseDuration(command + 11, period)) { strcpy(reply, "Error, invalid gps period"); - } else if (!setGpsPeriod(sensors, (uint32_t)(period * mult)) || + } else if (!setGpsPeriod(sensors, period) || !setGpsEnabled(sensors, true)) { strcpy(reply, "Error, gps provider not found"); } else { @@ -198,6 +207,31 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, } return true; } + if (strcmp(command, "gps firstfix") == 0) { + LocationProvider* location = sensors.getLocationProvider(); + if (location == nullptr) { + strcpy(reply, "Error, gps provider not found"); + } else if (location->getFirstFixTimeout() == 0) { + strcpy(reply, "> 0 (no limit)"); + } else { + sprintf(reply, "> %lu", (unsigned long)location->getFirstFixTimeout()); + } + return true; + } + if (memcmp(command, "gps firstfix ", 13) == 0) { + LocationProvider* location = sensors.getLocationProvider(); + uint32_t seconds; + if (location == nullptr) { + strcpy(reply, "Error, gps provider not found"); + } else if (!parseDuration(command + 13, seconds) || seconds > 86400UL) { // at most a day + strcpy(reply, "Error, invalid first fix timeout"); + } else { + location->setFirstFixTimeout(seconds); + setFirstFixTimeout(seconds); // saved by the caller (isDirty) + strcpy(reply, "OK"); + } + return true; + } if (memcmp(command, "gps sync", 8) == 0) { LocationProvider* location = sensors.getLocationProvider(); if (location == nullptr) { diff --git a/src/helpers/CommonGpsPrefs.h b/src/helpers/CommonGpsPrefs.h index c1e30b8e..5502cba8 100644 --- a/src/helpers/CommonGpsPrefs.h +++ b/src/helpers/CommonGpsPrefs.h @@ -18,6 +18,9 @@ public: virtual void setGpsEnabled(bool enabled) = 0; virtual uint32_t getGpsPeriod() const = 0; virtual void setGpsPeriod(uint32_t seconds) = 0; + // Saved first-fix timeout in seconds; false = not set, use the build default. + virtual bool getFirstFixTimeout(uint32_t& seconds) const { return false; } + virtual void setFirstFixTimeout(uint32_t seconds) { } // 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; } diff --git a/src/helpers/sensors/LocationProvider.h b/src/helpers/sensors/LocationProvider.h index 5b5b69c0..2e730343 100644 --- a/src/helpers/sensors/LocationProvider.h +++ b/src/helpers/sensors/LocationProvider.h @@ -81,6 +81,9 @@ public: } virtual void setGpsPeriod(uint32_t seconds) { } virtual uint32_t getGpsPeriod() const { return 0; } + // periodic mode: limit of an acquisition before the first fix since boot, 0 = no limit + virtual void setFirstFixTimeout(uint32_t seconds) { } + virtual uint32_t getFirstFixTimeout() 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; diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index c44e1c47..93b2dbfc 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -12,10 +12,11 @@ #ifndef GPS_PERIODIC_ACQUISITION_TIMEOUT_MS #define GPS_PERIODIC_ACQUISITION_TIMEOUT_MS 300000UL #endif -// limit for the periodic window before the first fix since boot (cold start can be long, -// a full almanac takes 12.5 min); 0 = keep searching until a fix +// default limit for the periodic window before the first fix since boot (a cold start +// can take up to ~30 min with a weak sky view); 0 = keep searching until a fix. +// Can be changed at runtime with `gps firstfix`. #ifndef GPS_FIRST_FIX_TIMEOUT_MS - #define GPS_FIRST_FIX_TIMEOUT_MS 900000UL + #define GPS_FIRST_FIX_TIMEOUT_MS 3600000UL #endif // in periodic mode, keep reading after the first valid fix until enough satellites @@ -41,6 +42,7 @@ class MicroNMEALocationProvider : public LocationProvider { long time_valid = 0; unsigned long _last_time_sync = 0; uint32_t _gpsPeriodSeconds = 0; + uint32_t _firstFixTimeoutSeconds = GPS_FIRST_FIX_TIMEOUT_MS / 1000UL; unsigned long _nextAcquisition = 0; unsigned long _acquisitionStarted = 0; unsigned long _firstFixInWindow = 0; @@ -204,6 +206,14 @@ public: return _gpsPeriodSeconds; } + void setFirstFixTimeout(uint32_t seconds) override { + _firstFixTimeoutSeconds = seconds; + } + + uint32_t getFirstFixTimeout() const override { + return _firstFixTimeoutSeconds; + } + uint32_t getAcquisitionAge() const override { return (uint32_t)(millis() - _acquisitionStarted) / 1000UL; } @@ -371,7 +381,7 @@ public: // a longer limit until a first fix has been obtained (cold start can be long) if (_acquiringPeriodically) { const uint32_t limit = _lastFix.valid ? GPS_PERIODIC_ACQUISITION_TIMEOUT_MS - : GPS_FIRST_FIX_TIMEOUT_MS; + : _firstFixTimeoutSeconds * 1000UL; if (limit > 0 && (uint32_t)(millis() - _acquisitionStarted) >= limit) { finishPeriodicAcquisition(); } From fb210a8441d401f768e3f24c055b68f15197da4b Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko Date: Fri, 13 Nov 2026 14:30:24 +0200 Subject: [PATCH 22/29] GPS: accept a 2D fix, but keep the GPS on for a 3D fix Per review: a 2D fix is valid, only less precise, and in some places a receiver never gets a 3D fix. So the guard no longer rejects it; instead the fix mode decides when the GPS may sleep: - the fix mode is read from GSA for every NMEA receiver, not only with GPS_GUARD (`fm:` in `gps diag`), and stored with the last fix; - in periodic mode, and for `gps once`, the GPS sleeps only after a 3D fix (or a fix from a receiver that does not report the mode); after a 2D fix it stays on up to the acquisition timeout; - a 2D fix does not replace a 3D fix younger than 5 min (GPS_3D_FIX_PREFERRED_MS). --- docs/cli_commands.md | 4 +-- src/helpers/sensors/GpsGuard.h | 17 ++-------- src/helpers/sensors/LocationProvider.h | 1 + .../sensors/MicroNMEALocationProvider.h | 34 ++++++++++++++----- 4 files changed, 31 insertions(+), 25 deletions(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 01eed226..838ab81f 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1026,7 +1026,7 @@ region save **Parameters:** - `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. +**Note:** A periodic acquisition stops after receiving a valid fix, then resumes after the configured period. If the receiver reports the fix mode (GSA) and the fix is 2D, the GPS stays on up to the acquisition timeout to get a 3D fix; a 2D fix is used as the position, but does not replace a 3D fix younger than 5 minutes (`GPS_3D_FIX_PREFERRED_MS`). --- @@ -1078,7 +1078,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, a 3D fix if the receiver reports the fix mode in GSA (`GPS_GUARD_REQUIRE_3D`, default on; status `rej 2d`), 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. +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 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. diff --git a/src/helpers/sensors/GpsGuard.h b/src/helpers/sensors/GpsGuard.h index bcd949f4..46b1936c 100644 --- a/src/helpers/sensors/GpsGuard.h +++ b/src/helpers/sensors/GpsGuard.h @@ -4,8 +4,7 @@ // // 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, 3D fix if the receiver reports the fix -// mode, optional build-time region, distance +// - 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 @@ -26,9 +25,6 @@ #ifndef GPS_GUARD_MAX_HDOP10 #define GPS_GUARD_MAX_HDOP10 40 // HDOP 4.0 #endif -#ifndef GPS_GUARD_REQUIRE_3D - #define GPS_GUARD_REQUIRE_3D 1 // reject a fix the receiver reports as 2D (GSA); 0 = off -#endif #ifndef GPS_GUARD_FENCE_M #define GPS_GUARD_FENCE_M 1000 // max distance from the reference position (0 = off) #endif @@ -139,10 +135,8 @@ public: bool isTimeAlert() const { return _time_alert; } // Fix as reported by the receiver: lat/lon in micro-degrees, HDOP in tenths (255 = unknown), - // gps_time = UTC epoch of the fix, fix_mode = receiver fix mode from GSA (1 = none, 2 = 2D, - // 3 = 3D, 0 = unknown: no recent GSA). 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, - uint8_t fix_mode = 0) { + // 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(); @@ -155,11 +149,6 @@ public: } else if (hdop10 == 255 || hdop10 > GPS_GUARD_MAX_HDOP10) { why = "hdop"; } -#if GPS_GUARD_REQUIRE_3D - else if (fix_mode == 1 || fix_mode == 2) { - why = "2d"; - } -#endif #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"; diff --git a/src/helpers/sensors/LocationProvider.h b/src/helpers/sensors/LocationProvider.h index 5b5b69c0..8b0ed18f 100644 --- a/src/helpers/sensors/LocationProvider.h +++ b/src/helpers/sensors/LocationProvider.h @@ -18,6 +18,7 @@ public: long satellites = 0; long timestamp = 0; unsigned long acquiredAt = 0; // millis() when the fix was stored + uint8_t fixMode = 0; // from GSA: 2 = 2D, 3 = 3D, 0 = unknown }; struct FixStats { diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index 98f04e4b..b095d46e 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -22,6 +22,11 @@ #define GPS_FIX_SETTLE_MS 10000UL #endif +// a 2D fix does not replace a 3D fix younger than this (it is less precise) +#ifndef GPS_3D_FIX_PREFERRED_MS + #define GPS_3D_FIX_PREFERRED_MS 300000UL +#endif + class MicroNMEALocationProvider : public LocationProvider { // 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 @@ -39,6 +44,7 @@ class MicroNMEALocationProvider : public LocationProvider { unsigned long _nextAcquisition = 0; unsigned long _acquisitionStarted = 0; unsigned long _firstFixInWindow = 0; + bool _goodFixInWindow = false; // a fix that lets the GPS sleep (3D, or fix mode unknown) bool _acquiringPeriodically = false; unsigned long _onceDeadline = 0; static const unsigned long TIME_SYNC_INTERVAL = 1800000; @@ -52,8 +58,6 @@ class MicroNMEALocationProvider : public LocationProvider { unsigned long _last_nmea_ms = 0; bool _uart_seen = false; bool _nmea_seen = false; -#ifdef GPS_GUARD - GpsGuard _guard; uint8_t _gsa_fix_mode = 0; // fix mode from the last GSA: 1 = none, 2 = 2D, 3 = 3D unsigned long _gsa_ms = 0; @@ -74,6 +78,8 @@ class MicroNMEALocationProvider : public LocationProvider { uint8_t currentFixMode() const { return (_gsa_fix_mode != 0 && (uint32_t)(millis() - _gsa_ms) <= 2000) ? _gsa_fix_mode : 0; } +#ifdef GPS_GUARD + GpsGuard _guard; #endif static uint32_t ageMs(unsigned long timestamp) { @@ -96,6 +102,7 @@ class MicroNMEALocationProvider : public LocationProvider { _acquiringPeriodically = true; _acquisitionStarted = millis(); _firstFixInWindow = 0; + _goodFixInWindow = false; } void finishPeriodicAcquisition() { @@ -109,13 +116,17 @@ class MicroNMEALocationProvider : public LocationProvider { bool saveFix() { // only store a fix when the snapshot is coherent (sats > 0). - // Returns true if the fix was stored. + // Returns true if the fix was accepted (stored, or kept out by a recent 3D fix). 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(), currentFixMode())) return false; + nmea.getHDOP(), getTimestamp())) return false; #endif + const uint8_t mode = currentFixMode(); + // a 2D fix is valid but less precise: keep a recent 3D fix instead + if (mode == 2 && _lastFix.valid && _lastFix.fixMode == 3 && + (uint32_t)(millis() - _lastFix.acquiredAt) < GPS_3D_FIX_PREFERRED_MS) return true; LastFix fix; fix.latitude = nmea.getLatitude(); @@ -127,6 +138,7 @@ class MicroNMEALocationProvider : public LocationProvider { fix.satellites = nmea.getNumSatellites(); fix.timestamp = getTimestamp(); fix.acquiredAt = millis(); + fix.fixMode = mode; fix.valid = true; _lastFix = fix; return true; @@ -170,6 +182,7 @@ public: if (!wasActive) { _acquisitionStarted = millis(); _firstFixInWindow = 0; + _goodFixInWindow = false; } if (_gpsPeriodSeconds > 0 && _driver->isActive()) { nmea.clear(); @@ -177,6 +190,7 @@ public: _acquiringPeriodically = true; _acquisitionStarted = millis(); _firstFixInWindow = 0; + _goodFixInWindow = false; } } @@ -319,7 +333,7 @@ public: if (_driver->pollGpsSwitch()) _gpsOn = true; if (_onceDeadline != 0) { - if (_firstFixInWindow != 0 && (long)(_onceDeadline - (millis() + GPS_FIX_SETTLE_MS)) > 0) { + if (_goodFixInWindow && (long)(_onceDeadline - (millis() + GPS_FIX_SETTLE_MS)) > 0) { _onceDeadline = millis() + GPS_FIX_SETTLE_MS; } if ((long)(millis() - _onceDeadline) >= 0) { @@ -355,8 +369,8 @@ public: _nmea_seen = true; const char* messageId = nmea.getMessageID(); -#ifdef GPS_GUARD if (isGsa(messageId)) parseGsa(nmea.getSentence()); +#ifdef GPS_GUARD if (parsed && !nmea.isValid() && (strcmp(messageId, "GGA") == 0 || strcmp(messageId, "RMC") == 0)) { _guard.noFix(nmea.getNumSatellites()); @@ -369,7 +383,11 @@ public: _firstFixInWindow = millis(); fixStatsFix((uint32_t)(_firstFixInWindow - _acquisitionStarted)); } - if (_acquiringPeriodically) { + // after a 2D fix the GPS stays on (up to the acquisition timeout) + // to give the receiver a chance to get a 3D fix + const uint8_t mode = currentFixMode(); + if (mode == 0 || mode == 3) _goodFixInWindow = true; + if (_acquiringPeriodically && _goodFixInWindow) { // 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) || @@ -416,10 +434,8 @@ public: fix_age, (unsigned long)_begin_calls, (unsigned long)_stop_calls); -#ifdef GPS_GUARD // fix mode from GSA (1 none, 2 2D, 3 3D, 0 no recent GSA) const size_t len = strlen(out); if (len < out_size) snprintf(out + len, out_size - len, " fm:%u", currentFixMode()); -#endif } }; From de721bcb4b3ae041097807a30a2341c1ba8cdbd3 Mon Sep 17 00:00:00 2001 From: Eve <139727413+netrunnereve@users.noreply.github.com> Date: Fri, 13 Nov 2026 20:35:32 -0500 Subject: [PATCH 23/29] use ble.name --- docs/companion_cli.md | 7 +++---- examples/companion_radio/MyMesh.cpp | 16 ++++++++-------- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/docs/companion_cli.md b/docs/companion_cli.md index 4887d997..d861b81e 100644 --- a/docs/companion_cli.md +++ b/docs/companion_cli.md @@ -415,14 +415,13 @@ Radio parameters are common to all roles and handled by `CommonRadioPrefs`. #### Change BLE name **Usage:** -- `get ble_name` -- `set ble_name ` -- `set ble_name_default` +- `get ble.name` +- `set ble.name ` **Parameters:** - `name`: New BLE name -**Note:** By default the node name will be used as the BLE name. These commands require a reboot to take effect. +**Note:** By default the node name will be used as the BLE name. If `` is empty the BLE name will be reset to the aforementioned default. These commands require a reboot to take effect. --- diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index d1ba6e13..91a9c8ab 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2154,7 +2154,13 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* sprintf(reply, "> pin is now %06d", _prefs.ble_pin); return true; } - if (memcmp(command, "set ble_name ", 13) == 0) { + if (strcmp(command, "set ble.name") == 0) { + _prefs.ble_name[0] = 0; + savePrefs(); + sprintf(reply, "> BLE name reset to %s (reboot to apply)", _prefs.node_name); + return true; + } + if (memcmp(command, "set ble.name ", 13) == 0) { if (AdvertDataParser::isValidName(&command[13])) { StrHelper::strncpy(_prefs.ble_name, &command[13], sizeof(_prefs.ble_name)); savePrefs(); @@ -2164,16 +2170,10 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* } return true; } - if (strcmp(command, "get ble_name") == 0) { + if (strcmp(command, "get ble.name") == 0) { sprintf(reply, "> %s", _prefs.ble_name[0] ? _prefs.ble_name : _prefs.node_name); return true; } - if (strcmp(command, "set ble_name_default") == 0) { - _prefs.ble_name[0] = 0; - savePrefs(); - sprintf(reply, "> BLE name reset to %s (reboot to apply)", _prefs.node_name); - return true; - } #ifdef ENABLE_WIFI_INTERFACE if (memcmp(command, "set wifi.ssid ", 14) == 0) { From 166863f69038521341524206037fec3210efd42c Mon Sep 17 00:00:00 2001 From: Marcel Verdult <37555613+marcelverdult@users.noreply.github.com> Date: Sat, 14 Nov 2026 13:13:08 +0100 Subject: [PATCH 24/29] rak: keep WB_IO2 driven HIGH after a failed RAK12500 probe (#3834) The I2C probe left WB_IO2 as an input when no RAK12500 answered. WB_IO2 switches the 3V3_S slot rail, which also powers a serial GPS. On base boards that pull this line low, the serial GPS lost power right after detection and never got a fix (#3830). Before 81afafcb the pin stayed HIGH, so keep it driven HIGH again. WB_IO4 and WB_IO5 still go back to inputs. --- src/helpers/sensors/RakI2cGpsDriver.h | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/helpers/sensors/RakI2cGpsDriver.h b/src/helpers/sensors/RakI2cGpsDriver.h index ac76e069..74327c6a 100644 --- a/src/helpers/sensors/RakI2cGpsDriver.h +++ b/src/helpers/sensors/RakI2cGpsDriver.h @@ -41,7 +41,15 @@ class RakI2cGpsDriver : public GpsDriver { } #ifndef RAK_3401 - pinMode(powerPin, INPUT); + if (powerPin == WB_IO2) { + // WB_IO2 switches the 3V3_S slot rail, which also powers a serial GPS and the other + // slot modules. Left as an input, the rail follows whatever the base board pulls it + // to: some keep it on, others switch it off, and the serial GPS loses power (#3830). + // Keep it driven HIGH, as before the probe; a GPS power pin re-claims it later. + digitalWrite(powerPin, HIGH); + } else { + pinMode(powerPin, INPUT); + } #endif return false; } From 7416193a76d1417deef525ce9e59f6b78ce7b4b1 Mon Sep 17 00:00:00 2001 From: Eve <139727413+netrunnereve@users.noreply.github.com> Date: Fri, 13 Nov 2026 22:10:43 -0500 Subject: [PATCH 25/29] change prefix as well --- docs/companion_cli.md | 2 +- examples/companion_radio/MyMesh.cpp | 8 ++++++-- examples/companion_radio/main.cpp | 8 +++++++- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/docs/companion_cli.md b/docs/companion_cli.md index d861b81e..212eb905 100644 --- a/docs/companion_cli.md +++ b/docs/companion_cli.md @@ -421,7 +421,7 @@ Radio parameters are common to all roles and handled by `CommonRadioPrefs`. **Parameters:** - `name`: New BLE name -**Note:** By default the node name will be used as the BLE name. If `` is empty the BLE name will be reset to the aforementioned default. These commands require a reboot to take effect. +**Note:** By default the BLE name is `Meshcore-` followed by the node name. If `` is empty the BLE name will be reset to the aforementioned default. These commands require a reboot to take effect. --- diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 91a9c8ab..cd6966e8 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2157,7 +2157,7 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* if (strcmp(command, "set ble.name") == 0) { _prefs.ble_name[0] = 0; savePrefs(); - sprintf(reply, "> BLE name reset to %s (reboot to apply)", _prefs.node_name); + sprintf(reply, "> BLE name reset to %s%s (reboot to apply)", BLE_NAME_PREFIX, _prefs.node_name); return true; } if (memcmp(command, "set ble.name ", 13) == 0) { @@ -2171,7 +2171,11 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* return true; } if (strcmp(command, "get ble.name") == 0) { - sprintf(reply, "> %s", _prefs.ble_name[0] ? _prefs.ble_name : _prefs.node_name); + if (_prefs.ble_name[0]) { + sprintf(reply, "> %s", _prefs.ble_name); + } else { + sprintf(reply, "> %s%s", BLE_NAME_PREFIX, _prefs.node_name); + } return true; } diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index 82f2b236..3e7ec6dc 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -215,7 +215,13 @@ void setup() { // add bluetooth interface #if defined(BLE_PIN_CODE) - bluetooth_interface.begin(BLE_NAME_PREFIX, the_mesh.getNodePrefs()->ble_name[0] ? the_mesh.getNodePrefs()->ble_name : the_mesh.getNodePrefs()->node_name, the_mesh.getBLEPin()); + char *prefix = BLE_NAME_PREFIX; + char *ble_name = the_mesh.getNodePrefs()->node_name; + if (the_mesh.getNodePrefs()->ble_name[0]) { + prefix = ""; + ble_name = the_mesh.getNodePrefs()->ble_name; + } + bluetooth_interface.begin((const char *) prefix, ble_name, the_mesh.getBLEPin()); interface_manager.addInterface(InterfaceType::Bluetooth, &bluetooth_interface); #endif From 3a3f69fb5d5038ddfa8e6dfd0fce401c231cf9fc Mon Sep 17 00:00:00 2001 From: Martin Boissonneault <19229816+Ve2mrx@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:42:51 -0500 Subject: [PATCH 26/29] rak4631: forward the first-fix limit and gps diag to the serial GPS RakLocationProvider wraps a MicroNMEALocationProvider but did not override setFirstFixTimeout(), getFirstFixTimeout() or formatDiagnostics(), so on RAK4631 boards with a serial GPS: - `gps firstfix` always answered "0 (no limit)" (the LocationProvider default), while the limit in force was the build default (1 h); - `gps firstfix ` saved the value but never applied it, at once or at boot; - `gps diag` gave the short base form, without the UART/NMEA counters or fm:. Forward all three to the NMEA provider. The RAK12500 (I2C) path has no first-fix limit, so it keeps reporting 0 and the short diagnostics. Co-Authored-By: Claude Opus 5.5 --- src/helpers/sensors/RakLocationProvider.h | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/helpers/sensors/RakLocationProvider.h b/src/helpers/sensors/RakLocationProvider.h index 2dda12a5..f395530f 100644 --- a/src/helpers/sensors/RakLocationProvider.h +++ b/src/helpers/sensors/RakLocationProvider.h @@ -211,6 +211,20 @@ public: return _gpsPeriodSeconds; } + // the first-fix limit is only implemented on the serial NMEA path + void setFirstFixTimeout(uint32_t seconds) override { + _nmea.setFirstFixTimeout(seconds); + } + + uint32_t getFirstFixTimeout() const override { + return _useI2c ? 0 : _nmea.getFirstFixTimeout(); + } + + void formatDiagnostics(char* out, size_t out_size) override { + if (_useI2c) LocationProvider::formatDiagnostics(out, out_size); + else _nmea.formatDiagnostics(out, out_size); + } + bool isGpsOn() const override { return _useI2c ? _gpsOn : _nmea.isGpsOn(); } From d1c71522b811e1e3e63acd44a86b54c1af37afeb Mon Sep 17 00:00:00 2001 From: Martin Boissonneault <19229816+Ve2mrx@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:23:54 -0500 Subject: [PATCH 27/29] gps: don't let the settle time close a periodic window before the time sync In periodic mode a window closed after GPS_FIX_SETTLE_MS (10 s) from the first fix even if the clock sync was still pending. The sync needs about 4 s of continuous valid fixes (time_valid > 2, reset on any pass without a fix), so after a hot start, when the receiver reports a fix within seconds but not yet steadily, the window could close unsynced. On a board without an RTC the clock then stays at its default until the next window, a whole period later. Close the window only once the sync has been tried (done, not needed, or refused by GPS_GUARD); the settle time and the satellite count apply after that. The acquisition timeout still bounds the window. Co-Authored-By: Claude Opus 5.5 --- src/helpers/sensors/MicroNMEALocationProvider.h | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index 34480b45..85262ba4 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -169,6 +169,12 @@ class MicroNMEALocationProvider : public LocationProvider { if (isValid()) time_valid++; } + // the time sync has had its chance: done, not needed, or refused by GPS_GUARD. + // updateTime() tries it on the tick where time_valid goes from 3 to 4. + bool timeSyncSettled() const { + return _clock == nullptr || !_time_sync_needed || time_valid > 3; + } + bool timeSyncAllowed() { #ifdef GPS_GUARD return _guard.acceptTime(getTimestamp(), _clock->getCurrentTime()); @@ -403,10 +409,13 @@ public: const uint8_t mode = currentFixMode(); if (mode == 0 || mode == 3) _goodFixInWindow = true; if (_acquiringPeriodically && _goodFixInWindow) { - // 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) { + // stay on until a pending time sync has been tried, even past the settle + // time: after a hot start the fix can come before the time is steady, and + // the window would close unsynced until the next period. The acquisition + // timeout below still bounds it. + if (timeSyncSettled() && + (nmea.getNumSatellites() >= GPS_MIN_SATS_FOR_FIX || + (uint32_t)(millis() - _firstFixInWindow) >= GPS_FIX_SETTLE_MS)) { finishPeriodicAcquisition(); } } From fe520673ae992888486af84d01a6f90c69518391 Mon Sep 17 00:00:00 2001 From: Cyclic3 Date: Sat, 14 Nov 2026 12:01:14 +0000 Subject: [PATCH 28/29] Fix USB serial issue on Xiao ESP32-S3 Wio (#1416) (#3726) * Initial attempt at fixing serial issue on Xiao ESP32-S3 Wio (#1416) * restrict Xiao ESP32-S3 WIO fix to just that board --- variants/xiao_s3_wio/XiaoS3WIOBoard.h | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/variants/xiao_s3_wio/XiaoS3WIOBoard.h b/variants/xiao_s3_wio/XiaoS3WIOBoard.h index 7ae06a35..4a635334 100644 --- a/variants/xiao_s3_wio/XiaoS3WIOBoard.h +++ b/variants/xiao_s3_wio/XiaoS3WIOBoard.h @@ -7,6 +7,13 @@ class XiaoS3WIOBoard : public ESP32Board { public: XiaoS3WIOBoard() { } + void begin() { + while (!Serial.availableForWrite()) + delay(10); + + ESP32Board::begin(); + } + const char* getManufacturerName() const override { return "Xiao S3 WIO"; } From 6cba7681815d8ea627500e2f88502ea46178d6aa Mon Sep 17 00:00:00 2001 From: liamcottle Date: Sun, 15 Nov 2026 18:22:21 +1300 Subject: [PATCH 29/29] workaround for CC310 where mutex can still be locked after a failed verification --- src/Identity.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/Identity.cpp b/src/Identity.cpp index 51a01ae7..045fe097 100644 --- a/src/Identity.cpp +++ b/src/Identity.cpp @@ -7,6 +7,10 @@ #ifdef USE_CC310_HW_CRYPTO #include #include "nrf_cc310/include/crys_ec_edw_api.h" +#include "nrf_cc310/include/ssi_pal_mutex.h" +extern "C" { + extern SaSi_PalMutex sasiAsymCryptoMutex; +} #endif namespace mesh { @@ -30,6 +34,13 @@ bool Identity::verify(const uint8_t* sig, const uint8_t* message, int msg_len) c 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); + + // workaround for CC310 v0.9.13 where mutex can still be locked after a failed verification + if (rc != CRYS_OK && sasiAsymCryptoMutex != 0) { + MESH_DEBUG_PRINTLN("CRYS_ECEDW_Verify mutex still locked after error result, unlocking"); + SaSi_PalMutexUnlock(&sasiAsymCryptoMutex); + } + return rc == CRYS_OK; #elif 0 // NOTE: memory corruption bug was found in this function!!