From e8ace69fc05ce5a195fdcb3d4cd2d05ebbdfa271 Mon Sep 17 00:00:00 2001 From: Quency-D Date: Wed, 22 Jul 2026 16:33:05 +0800 Subject: [PATCH 01/11] 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/11] 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/11] 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/11] 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/11] 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 87679ba526cffba46cf619c0b20f80afad7ed738 Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko Date: Thu, 12 Nov 2026 00:34:05 +0200 Subject: [PATCH 06/11] 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 bf0ccfe2eb7b08efab625169aaeda3b4a96a4dbc Mon Sep 17 00:00:00 2001 From: Quency-D Date: Thu, 12 Nov 2026 14:20:08 +0800 Subject: [PATCH 07/11] 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 08/11] 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 09/11] 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 407cb9abacf5557951eb12b8231e6f7bbf8b9d4b Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko Date: Fri, 13 Nov 2026 14:29:02 +0200 Subject: [PATCH 10/11] 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 11/11] 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 } };