From 8c0d5aee925e456b627ca1c9991c5103d67c8ea7 Mon Sep 17 00:00:00 2001 From: me Date: Sat, 1 Aug 2026 23:48:20 -0700 Subject: [PATCH 01/79] Add USB CDC flags to M5Stack Unit C6L kiss_modem env M5Stack_Unit_C6L_kiss_modem env was missing ARDUINO_USB_CDC_ON_BOOT, ARDUINO_USB_MODE, and ENABLE_USB_INTERFACE build flags, present in the companion_radio_usb env for the same board. Without these, ESP32-C6 native USB serial output goes to UART0 (unconnected on this board), making the KISS modem unresponsive over USB. Hardware-verified: M5Stack Unit C6L, KISS modem confirmed operational via /dev/ttyACM0 with openhop_repeater. --- variants/m5stack_unit_c6l/platformio.ini | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/variants/m5stack_unit_c6l/platformio.ini b/variants/m5stack_unit_c6l/platformio.ini index 190add04..388532e0 100644 --- a/variants/m5stack_unit_c6l/platformio.ini +++ b/variants/m5stack_unit_c6l/platformio.ini @@ -109,5 +109,9 @@ lib_deps = [env:M5Stack_Unit_C6L_kiss_modem] extends = M5Stack_Unit_C6L +build_flags = ${M5Stack_Unit_C6L.build_flags} + -D ARDUINO_USB_CDC_ON_BOOT=1 + -D ARDUINO_USB_MODE=1 + -D ENABLE_USB_INTERFACE build_src_filter = ${M5Stack_Unit_C6L.build_src_filter} +<../examples/kiss_modem/> From fa18757f2c8a4fd160b903d8ecc982f69e7e018c Mon Sep 17 00:00:00 2001 From: agessaman Date: Wed, 23 Sep 2026 15:43:01 -0700 Subject: [PATCH 02/79] kiss_modem: add AGC reset interval and FEM gain control (protocol v2) Add SetHardware sub-commands so a host can probe and configure per-board RF front-end settings: - GetCapabilities (0x1B): uint32 feature bits (AGC, FEM RX, FEM TX) - Set/GetAgcResetInterval (0x1C/0x1D): 0-1020 s, 4 s resolution, 0 disables; default stays 30 s - Set/GetFemState (0x1E/0x1F): apply/value masks for FEM RX (LNA) and TX (PA) gain; all-or-nothing, Unsupported (0x08) if any requested bit is not controllable on this board The AGC scheduler moves from main.cpp into KissModem so it is configurable and unit-tested. FEM changes that arrive mid-TX are deferred until the packet ends, since board setters drive FEM pins directly. MainBoard gains virtual FEM hooks (canControl/set/is for LNA and PA gain). Boards that already implemented these methods privately now expose them as overrides: Heltec V4, V4 R8, T096, Tracker V2, Station G3 and Wio Tracker L1 1W. KISS_FIRMWARE_VERSION bumped to 2. --- docs/kiss_modem_protocol.md | 70 ++++- examples/kiss_modem/KissModem.cpp | 134 +++++++++ examples/kiss_modem/KissModem.h | 37 ++- examples/kiss_modem/main.cpp | 9 - src/MeshCore.h | 8 + test/mocks/Mesh.h | 7 + test/test_kiss_modem/test_hw_controls.cpp | 278 ++++++++++++++++++ variants/heltec_t096/T096Board.h | 6 +- .../heltec_tracker_v2/HeltecTrackerV2Board.h | 6 +- variants/heltec_v4/HeltecV4Board.h | 6 +- variants/heltec_v4_r8/HeltecV4R8Board.h | 5 +- variants/heltec_v4_r8/LoRaFEMControl.h | 2 +- variants/station_g3_esp32/StationG3Board.h | 10 +- .../wio-tracker-l1-1w/WioTrackerL1Board.h | 6 +- 14 files changed, 553 insertions(+), 31 deletions(-) create mode 100644 test/test_kiss_modem/test_hw_controls.cpp diff --git a/docs/kiss_modem_protocol.md b/docs/kiss_modem_protocol.md index 3f4dbf9c..9b8aaa4b 100644 --- a/docs/kiss_modem_protocol.md +++ b/docs/kiss_modem_protocol.md @@ -118,10 +118,15 @@ MeshCore-specific functionality uses the standard KISS SetHardware command. The | Reboot | `0x18` | - | | SetSignalReport | `0x19` | Enable (1): 0x00=disable, nonzero=enable | | GetSignalReport | `0x1A` | - | +| GetCapabilities | `0x1B` | - | +| SetAgcResetInterval | `0x1C` | Seconds (2): 0=disable, 0-1020 | +| GetAgcResetInterval | `0x1D` | - | +| SetFemState | `0x1E` | Apply mask (1) + Value mask (1) | +| GetFemState | `0x1F` | - | ### Response Sub-commands (TNC to Host) -Response codes use the high-bit convention: `response = command | 0x80`. Generic and unsolicited responses use the `0xF0`+ range. +Response codes use the high-bit convention: `response = command | 0x80`. Generic and unsolicited responses use the `0xF0`+ range. Set commands that report state (SetSignalReport, SetAgcResetInterval, SetFemState) reply with the matching Get response, so `0x9C` and `0x9E` are never sent. | Sub-command | Value | Data | |--------------|--------|-----------------------------------------| @@ -147,6 +152,9 @@ Response codes use the high-bit convention: `response = command | 0x80`. Generic | DeviceName | `0x96` | Name (variable, UTF-8) | | Pong | `0x97` | - | | SignalReport | `0x9A` | Status (1): 0x00=disabled, 0x01=enabled | +| Capabilities | `0x9B` | Feature bits (4) | +| AgcResetInterval | `0x9D` | Effective seconds (2) | +| FemState | `0x9F` | Capability mask (1) + Value mask (1) | | OK | `0xF0` | - | | Error | `0xF1` | Error code (1) | | TxDone | `0xF8` | Result (1): 0x00=failed, 0x01=success | @@ -163,6 +171,7 @@ Response codes use the high-bit convention: `response = command | 0x80`. Generic | UnknownCmd | `0x05` | Unknown sub-command | | EncryptFailed | `0x06` | Encryption failed | | TxBusy | `0x07` | Radio TX busy, or host output queue full | +| Unsupported | `0x08` | Command known, but not supported by this board | ### Unsolicited Events @@ -215,7 +224,64 @@ All values little-endian. |-------------|---------|-----------------------| | Noise floor | 2 bytes | int16_t, dBm (signed) | -The modem recalibrates the noise floor every 2 seconds with an AGC reset every 30 seconds. +The modem recalibrates the noise floor every 2 seconds. AGC resets follow the configured AGC reset interval (default 30 seconds). + +### Capabilities (Capabilities response) + +All values little-endian. Hosts should probe capabilities rather than infer them from the firmware version: boards running the same version expose different hardware controls. Firmware older than version 2 answers GetCapabilities with `UnknownCmd`; treat that as no capabilities. + +| Field | Size | Description | +|--------------|---------|--------------------| +| Feature bits | 4 bytes | uint32_t, see below | + +| Bit | Value | Description | +|-----|--------|-------------------------------------------| +| 0 | `0x01` | AGC reset interval control (always set) | +| 1 | `0x02` | External FEM RX (LNA) gain control | +| 2 | `0x04` | External FEM TX (PA) gain control | + +Remaining bits are reserved and sent as 0. + +### AGC Reset Interval (SetAgcResetInterval / AgcResetInterval response) + +All values little-endian. + +| Field | Size | Description | +|---------|---------|-------------------------------------------| +| Seconds | 2 bytes | uint16_t, 0 = disabled, maximum 1020 | + +The modem periodically resets the radio's AGC while idle (no transmission in progress and host output not backed up). The interval has 4-second resolution, matching the MeshCore `agc.reset.interval` setting: requested values are rounded down to a multiple of 4, so 1-3 disable the reset. Values above 1020 return `InvalidParam`. SetAgcResetInterval replies with the AgcResetInterval response carrying the effective value, and restarts the countdown from the time of the request. + +The default is 30 seconds. The setting is not persisted; hosts should re-send it after reconnecting or rebooting the modem. + +### FEM State (SetFemState / FemState response) + +Controls the board's external LoRa front-end module gain. This is separate from the radio chip's own RX boosted gain. TX/RX switching of the FEM is handled by the board and is not affected by these settings. + +| Bit | Value | Description | +|-----|--------|---------------------------------| +| 0 | `0x01` | RX gain (LNA enabled) | +| 1 | `0x02` | TX gain (PA high gain enabled) | + +SetFemState data: + +| Field | Size | Description | +|------------|--------|------------------------------------------------| +| Apply mask | 1 byte | Bits to change; bits not set are left as-is | +| Value mask | 1 byte | New value for each bit in the apply mask | + +FemState response data: + +| Field | Size | Description | +|-----------------|--------|---------------------------------------------------| +| Capability mask | 1 byte | Bits this board can control | +| Value mask | 1 byte | Current state; always 0 for uncontrollable bits | + +Example: enable RX gain without changing TX gain: apply `0x01`, value `0x01`. + +If any bit in the apply mask is not in the board's capability mask (including reserved bits), the modem replies `Unsupported` and changes nothing. On success, SetFemState replies with the FemState response carrying the new state. A request received while a packet is on air is applied as soon as that transmission ends, and the FemState response is sent then; a second request during the same transmission returns `TxBusy`. Capabilities come from the board, so a board with a fixed, board-managed FEM (for example RAK3401) reports none. + +The setting is not persisted; the board's power-on default applies after reboot. ### Stats (Stats response) diff --git a/examples/kiss_modem/KissModem.cpp b/examples/kiss_modem/KissModem.cpp index 7dcfc8d7..5b61e83c 100644 --- a/examples/kiss_modem/KissModem.cpp +++ b/examples/kiss_modem/KissModem.cpp @@ -22,6 +22,11 @@ KissModem::KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& r _getStatsCallback = nullptr; _config = {0, 0, 0, 0, 0}; _signal_report_enabled = true; + _agc_reset_interval_sec = KISS_AGC_RESET_DEFAULT_SEC; + _next_agc_reset_ms = 0; + _fem_deferred = false; + _fem_deferred_apply = 0; + _fem_deferred_value = 0; resetOutputQueue(); } @@ -31,6 +36,8 @@ void KissModem::begin() { _rx_active = false; _has_pending_tx = false; _tx_state = TX_IDLE; + _fem_deferred = false; + _next_agc_reset_ms = millis() + (uint32_t)_agc_reset_interval_sec * 1000; resetOutputQueue(); } @@ -240,10 +247,24 @@ void KissModem::loop() { } processTx(); + processDeferredFem(); + maybeResetAgc(); tryFlushFrames(); queuePendingBusyError(); } +void KissModem::maybeResetAgc() { + if (_agc_reset_interval_sec == 0) return; + // same guard as the RX path in main.cpp, so receive is restarted right after the reset + if (_tx_state != TX_IDLE || isHostOutputBackedUp()) return; + + uint32_t now = millis(); + if ((int32_t)(now - _next_agc_reset_ms) >= 0) { + _radio.resetAGC(); + _next_agc_reset_ms = now + (uint32_t)_agc_reset_interval_sec * 1000; + } +} + void KissModem::processFrame() { if (_rx_len < 1) return; @@ -381,6 +402,21 @@ void KissModem::handleHardwareCommand(uint8_t sub_cmd, const uint8_t* data, uint case HW_CMD_GET_SIGNAL_REPORT: handleGetSignalReport(); break; + case HW_CMD_GET_CAPABILITIES: + handleGetCapabilities(); + break; + case HW_CMD_SET_AGC_RESET_INTERVAL: + handleSetAgcResetInterval(data, len); + break; + case HW_CMD_GET_AGC_RESET_INTERVAL: + handleGetAgcResetInterval(); + break; + case HW_CMD_SET_FEM_STATE: + handleSetFemState(data, len); + break; + case HW_CMD_GET_FEM_STATE: + handleGetFemState(); + break; default: writeHardwareError(HW_ERR_UNKNOWN_CMD); break; @@ -732,3 +768,101 @@ void KissModem::handleGetSignalReport() { uint8_t val = _signal_report_enabled ? 0x01 : 0x00; writeHardwareFrame(HW_RESP(HW_CMD_GET_SIGNAL_REPORT), &val, 1); } + +void KissModem::handleGetCapabilities() { + uint32_t caps = HW_CAP_AGC_RESET; + if (_board.canControlLoRaFemLna()) caps |= HW_CAP_FEM_RX_GAIN; + if (_board.canControlLoRaFemPaGain()) caps |= HW_CAP_FEM_TX_GAIN; + uint8_t buf[4] = { (uint8_t)caps, (uint8_t)(caps >> 8), (uint8_t)(caps >> 16), (uint8_t)(caps >> 24) }; + writeHardwareFrame(HW_RESP(HW_CMD_GET_CAPABILITIES), buf, 4); +} + +void KissModem::handleSetAgcResetInterval(const uint8_t* data, uint16_t len) { + if (len < 2) { + writeHardwareError(HW_ERR_INVALID_LENGTH); + return; + } + uint16_t secs = (uint16_t)(data[0] | (data[1] << 8)); + if (secs > KISS_AGC_RESET_MAX_SEC) { + writeHardwareError(HW_ERR_INVALID_PARAM); + return; + } + _agc_reset_interval_sec = secs - (secs % KISS_AGC_RESET_STEP_SEC); + _next_agc_reset_ms = millis() + (uint32_t)_agc_reset_interval_sec * 1000; + handleGetAgcResetInterval(); +} + +void KissModem::handleGetAgcResetInterval() { + uint8_t buf[2] = { (uint8_t)_agc_reset_interval_sec, (uint8_t)(_agc_reset_interval_sec >> 8) }; + writeHardwareFrame(HW_RESP(HW_CMD_GET_AGC_RESET_INTERVAL), buf, 2); +} + +uint8_t KissModem::femCapabilityMask() const { + uint8_t mask = 0; + if (_board.canControlLoRaFemLna()) mask |= HW_FEM_RX_GAIN; + if (_board.canControlLoRaFemPaGain()) mask |= HW_FEM_TX_GAIN; + return mask; +} + +uint8_t KissModem::femValueMask() const { + uint8_t mask = 0; + if (_board.canControlLoRaFemLna() && _board.isLoRaFemLnaEnabled()) mask |= HW_FEM_RX_GAIN; + if (_board.canControlLoRaFemPaGain() && _board.isLoRaFemPaGainEnabled()) mask |= HW_FEM_TX_GAIN; + return mask; +} + +void KissModem::writeFemState() { + uint8_t buf[2] = { femCapabilityMask(), femValueMask() }; + writeHardwareFrame(HW_RESP(HW_CMD_GET_FEM_STATE), buf, 2); +} + +void KissModem::applyFemState(uint8_t apply_mask, uint8_t value_mask) { + bool ok = true; + if (apply_mask & HW_FEM_RX_GAIN) { + ok &= _board.setLoRaFemLnaEnabled((value_mask & HW_FEM_RX_GAIN) != 0); + } + if (apply_mask & HW_FEM_TX_GAIN) { + ok &= _board.setLoRaFemPaGainEnabled((value_mask & HW_FEM_TX_GAIN) != 0); + } + if (ok) { + writeFemState(); + } else { + writeHardwareError(HW_ERR_UNSUPPORTED); + } +} + +void KissModem::processDeferredFem() { + if (!_fem_deferred || _tx_state == TX_SENDING) return; + _fem_deferred = false; + applyFemState(_fem_deferred_apply, _fem_deferred_value); +} + +void KissModem::handleSetFemState(const uint8_t* data, uint16_t len) { + if (len < 2) { + writeHardwareError(HW_ERR_INVALID_LENGTH); + return; + } + uint8_t apply_mask = data[0]; + uint8_t value_mask = data[1]; + // validate every requested bit before touching hardware so a request is all-or-nothing + if (apply_mask & ~femCapabilityMask()) { + writeHardwareError(HW_ERR_UNSUPPORTED); + return; + } + if (_tx_state == TX_SENDING) { + // board setters drive FEM pins directly; changing them mid-packet would corrupt the TX + if (_fem_deferred) { + writeHardwareError(HW_ERR_TX_BUSY); + return; + } + _fem_deferred = true; + _fem_deferred_apply = apply_mask; + _fem_deferred_value = value_mask; + return; + } + applyFemState(apply_mask, value_mask); +} + +void KissModem::handleGetFemState() { + writeFemState(); +} diff --git a/examples/kiss_modem/KissModem.h b/examples/kiss_modem/KissModem.h index a23e459b..751fb336 100644 --- a/examples/kiss_modem/KissModem.h +++ b/examples/kiss_modem/KissModem.h @@ -62,6 +62,11 @@ #define HW_CMD_REBOOT 0x18 #define HW_CMD_SET_SIGNAL_REPORT 0x19 #define HW_CMD_GET_SIGNAL_REPORT 0x1A +#define HW_CMD_GET_CAPABILITIES 0x1B +#define HW_CMD_SET_AGC_RESET_INTERVAL 0x1C +#define HW_CMD_GET_AGC_RESET_INTERVAL 0x1D +#define HW_CMD_SET_FEM_STATE 0x1E +#define HW_CMD_GET_FEM_STATE 0x1F /* Response code = command code | 0x80. Generic / unsolicited use 0xF0+. */ #define HW_RESP(cmd) ((cmd) | 0x80) @@ -81,8 +86,22 @@ #define HW_ERR_UNKNOWN_CMD 0x05 #define HW_ERR_ENCRYPT_FAILED 0x06 #define HW_ERR_TX_BUSY 0x07 +#define HW_ERR_UNSUPPORTED 0x08 -#define KISS_FIRMWARE_VERSION 1 +/* GetCapabilities feature bits */ +#define HW_CAP_AGC_RESET (1UL << 0) +#define HW_CAP_FEM_RX_GAIN (1UL << 1) +#define HW_CAP_FEM_TX_GAIN (1UL << 2) + +/* SetFemState / GetFemState mask bits */ +#define HW_FEM_RX_GAIN (1 << 0) +#define HW_FEM_TX_GAIN (1 << 1) + +#define KISS_AGC_RESET_DEFAULT_SEC 30 +#define KISS_AGC_RESET_MAX_SEC 1020 +#define KISS_AGC_RESET_STEP_SEC 4 + +#define KISS_FIRMWARE_VERSION 2 typedef void (*SetRadioCallback)(float freq, float bw, uint8_t sf, uint8_t cr); typedef void (*SetTxPowerCallback)(uint8_t power); @@ -139,6 +158,11 @@ class KissModem { RadioConfig _config; bool _signal_report_enabled; + uint16_t _agc_reset_interval_sec; + uint32_t _next_agc_reset_ms; + bool _fem_deferred; + uint8_t _fem_deferred_apply; + uint8_t _fem_deferred_value; uint8_t _tx_frame_buf[KISS_TX_FRAME_QUEUE_DEPTH][KISS_MAX_ENCODED_FRAME_SIZE]; uint16_t _tx_frame_len[KISS_TX_FRAME_QUEUE_DEPTH]; uint16_t _tx_frame_written[KISS_TX_FRAME_QUEUE_DEPTH]; @@ -165,6 +189,12 @@ class KissModem { void processFrame(); void handleHardwareCommand(uint8_t sub_cmd, const uint8_t* data, uint16_t len); void processTx(); + void maybeResetAgc(); + uint8_t femCapabilityMask() const; + uint8_t femValueMask() const; + void writeFemState(); + void applyFemState(uint8_t apply_mask, uint8_t value_mask); + void processDeferredFem(); void handleGetIdentity(); void handleGetRandom(const uint8_t* data, uint16_t len); @@ -192,6 +222,11 @@ class KissModem { void handleGetDeviceName(); void handleSetSignalReport(const uint8_t* data, uint16_t len); void handleGetSignalReport(); + void handleGetCapabilities(); + void handleSetAgcResetInterval(const uint8_t* data, uint16_t len); + void handleGetAgcResetInterval(); + void handleSetFemState(const uint8_t* data, uint16_t len); + void handleGetFemState(); public: KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& rng, diff --git a/examples/kiss_modem/main.cpp b/examples/kiss_modem/main.cpp index 44b2a3df..8835418d 100644 --- a/examples/kiss_modem/main.cpp +++ b/examples/kiss_modem/main.cpp @@ -19,7 +19,6 @@ #endif #define NOISE_FLOOR_CALIB_INTERVAL_MS 2000 -#define AGC_RESET_INTERVAL_MS 30000 #define USB_TX_TIMEOUT_MS 50 #define USB_TX_BUFFER_SIZE 1024 @@ -27,7 +26,6 @@ StdRNG rng; mesh::LocalIdentity identity; KissModem* modem; static uint32_t next_noise_floor_calib_ms = 0; -static uint32_t next_agc_reset_ms = 0; void halt() { while (1) ; @@ -133,13 +131,6 @@ void loop() { modem->loop(); if (!modem->isActuallyTransmitting() && !modem->isHostOutputBackedUp()) { - if (!modem->isTxBusy()) { - if ((uint32_t)(millis() - next_agc_reset_ms) >= AGC_RESET_INTERVAL_MS) { - radio_driver.resetAGC(); - next_agc_reset_ms = millis(); - } - } - uint8_t rx_buf[256]; int rx_len = radio_driver.recvRaw(rx_buf, sizeof(rx_buf)); if (rx_len > 0) { diff --git a/src/MeshCore.h b/src/MeshCore.h index 2a3582de..5fdb064c 100644 --- a/src/MeshCore.h +++ b/src/MeshCore.h @@ -77,6 +77,14 @@ public: virtual bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { return false; } + // External LoRa front-end (FEM) gain control. Boards without a controllable FEM keep these defaults. + virtual bool canControlLoRaFemLna() const { return false; } + virtual bool setLoRaFemLnaEnabled(bool enable) { return false; } + virtual bool isLoRaFemLnaEnabled() const { return false; } + virtual bool canControlLoRaFemPaGain() const { return false; } + virtual bool setLoRaFemPaGainEnabled(bool enable) { return false; } + virtual bool isLoRaFemPaGainEnabled() const { return false; } + // Called from the example main loops. Lets a board feed its watchdog and // run periodic housekeeping. Default no-op. virtual void loop() { /* no op */ } diff --git a/test/mocks/Mesh.h b/test/mocks/Mesh.h index b6c263c1..29a29b82 100644 --- a/test/mocks/Mesh.h +++ b/test/mocks/Mesh.h @@ -13,6 +13,7 @@ public: virtual bool isSendComplete() { return true; } virtual void onSendFinished() {} virtual int16_t getNoiseFloor() { return -120; } + virtual void resetAGC() {} }; class MainBoard { @@ -22,6 +23,12 @@ public: virtual float getMCUTemperature() { return 25.0f; } virtual const char* getManufacturerName() { return "mock-board"; } virtual void reboot() {} + virtual bool canControlLoRaFemLna() const { return false; } + virtual bool setLoRaFemLnaEnabled(bool) { return false; } + virtual bool isLoRaFemLnaEnabled() const { return false; } + virtual bool canControlLoRaFemPaGain() const { return false; } + virtual bool setLoRaFemPaGainEnabled(bool) { return false; } + virtual bool isLoRaFemPaGainEnabled() const { return false; } }; } diff --git a/test/test_kiss_modem/test_hw_controls.cpp b/test/test_kiss_modem/test_hw_controls.cpp new file mode 100644 index 00000000..ad6f1e36 --- /dev/null +++ b/test/test_kiss_modem/test_hw_controls.cpp @@ -0,0 +1,278 @@ +#include + +#include +#include + +#include "KissModem.h" + +namespace { + +class RecordingStream : public Stream { +public: + void pushRx(const std::vector& bytes) { + for (uint8_t b : bytes) _rx.push(b); + } + + int availableForWrite() override { return 4096; } + size_t write(const uint8_t* buffer, size_t size) override { + _writes.insert(_writes.end(), buffer, buffer + size); + return size; + } + size_t write(uint8_t b) override { return write(&b, 1); } + int available() override { return (int)_rx.size(); } + int read() override { + if (_rx.empty()) return -1; + int b = _rx.front(); + _rx.pop(); + return b; + } + + // Decoded SetHardware payloads (sub-command + data), consumed on read. + std::vector> takeHardwareFrames() { + std::vector> frames; + std::vector cur; + bool in_frame = false, esc = false; + for (uint8_t b : _writes) { + if (b == KISS_FEND) { + if (in_frame && cur.size() > 1 && cur[0] == KISS_CMD_SETHARDWARE) { + frames.emplace_back(cur.begin() + 1, cur.end()); + } + cur.clear(); + in_frame = true; + continue; + } + if (b == KISS_FESC) { esc = true; continue; } + if (esc) { b = (b == KISS_TFEND) ? KISS_FEND : KISS_FESC; esc = false; } + cur.push_back(b); + } + _writes.clear(); + return frames; + } + +private: + std::queue _rx; + std::vector _writes; +}; + +class ZeroRNG : public mesh::RNG { +public: + void random(uint8_t* dest, size_t sz) override { memset(dest, 0, sz); } +}; + +class AgcRadio : public mesh::Radio { +public: + bool startSendRaw(const uint8_t*, uint16_t) override { return true; } + bool isSendComplete() override { return send_complete; } + void resetAGC() override { agc_resets++; } + + bool send_complete = true; + int agc_resets = 0; +}; + +class FemBoard : public mesh::MainBoard { +public: + const char* getManufacturerName() override { return "fem-board"; } + + bool canControlLoRaFemLna() const override { return has_lna; } + bool setLoRaFemLnaEnabled(bool enable) override { + if (!has_lna) return false; + lna = enable; + lna_sets++; + return true; + } + bool isLoRaFemLnaEnabled() const override { return lna; } + + bool canControlLoRaFemPaGain() const override { return has_pa; } + bool setLoRaFemPaGainEnabled(bool enable) override { + if (!has_pa) return false; + pa = enable; + pa_sets++; + return true; + } + bool isLoRaFemPaGainEnabled() const override { return pa; } + + bool has_lna = false, has_pa = false; + bool lna = false, pa = false; + int lna_sets = 0, pa_sets = 0; +}; + +class NoSensors : public SensorManager { +public: + bool querySensors(uint8_t, CayenneLPP&) override { return false; } +}; + +class KissHwControlTest : public ::testing::Test { +protected: + RecordingStream serial; + mesh::LocalIdentity identity; + ZeroRNG rng; + AgcRadio radio; + FemBoard board; + NoSensors sensors; + KissModem modem; + + KissHwControlTest() : modem(serial, identity, rng, radio, board, sensors) { + g_mock_millis = 1000; + modem.begin(); + } + + std::vector> hw(const std::vector& payload) { + std::vector frame = {KISS_FEND, KISS_CMD_SETHARDWARE}; + frame.insert(frame.end(), payload.begin(), payload.end()); + frame.push_back(KISS_FEND); + serial.pushRx(frame); + modem.loop(); + return serial.takeHardwareFrames(); + } + + std::vector hw1(const std::vector& payload) { + auto frames = hw(payload); + EXPECT_EQ(frames.size(), 1U); + return frames.empty() ? std::vector{} : frames[0]; + } + + void advance(uint32_t ms) { + g_mock_millis += ms; + modem.loop(); + } + + void startTxAndHold() { + radio.send_complete = false; + serial.pushRx({KISS_FEND, KISS_CMD_DATA, 0x42, KISS_FEND}); + modem.loop(); + modem.loop(); + advance((uint32_t)KISS_DEFAULT_TXDELAY * 10); + ASSERT_TRUE(modem.isActuallyTransmitting()); + } +}; + +const std::vector ERR_UNSUPPORTED = {HW_RESP_ERROR, HW_ERR_UNSUPPORTED}; + +TEST_F(KissHwControlTest, VersionIsTwo) { + EXPECT_EQ(hw1({HW_CMD_GET_VERSION}), (std::vector{HW_RESP(HW_CMD_GET_VERSION), 2, 0})); +} + +TEST_F(KissHwControlTest, CapabilitiesOnBareBoardAreAgcOnly) { + EXPECT_EQ(hw1({HW_CMD_GET_CAPABILITIES}), (std::vector{0x9B, 0x01, 0x00, 0x00, 0x00})); +} + +TEST_F(KissHwControlTest, CapabilitiesReflectBoardFem) { + board.has_lna = true; + EXPECT_EQ(hw1({HW_CMD_GET_CAPABILITIES}), (std::vector{0x9B, 0x03, 0x00, 0x00, 0x00})); + board.has_pa = true; + EXPECT_EQ(hw1({HW_CMD_GET_CAPABILITIES}), (std::vector{0x9B, 0x07, 0x00, 0x00, 0x00})); +} + +TEST_F(KissHwControlTest, AgcIntervalDefaultsToThirtySeconds) { + EXPECT_EQ(hw1({HW_CMD_GET_AGC_RESET_INTERVAL}), (std::vector{0x9D, 30, 0})); +} + +TEST_F(KissHwControlTest, AgcIntervalSetReturnsEffectiveRoundedValue) { + EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 10, 0}), (std::vector{0x9D, 8, 0})); + EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 4, 0}), (std::vector{0x9D, 4, 0})); + EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 0xFC, 0x03}), (std::vector{0x9D, 0xFC, 0x03})); + EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 0, 0}), (std::vector{0x9D, 0, 0})); + EXPECT_EQ(hw1({HW_CMD_GET_AGC_RESET_INTERVAL}), (std::vector{0x9D, 0, 0})); +} + +TEST_F(KissHwControlTest, AgcIntervalRejectsOutOfRangeAndShortPayload) { + EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 0xFD, 0x03}), (std::vector{HW_RESP_ERROR, HW_ERR_INVALID_PARAM})); + EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 4}), (std::vector{HW_RESP_ERROR, HW_ERR_INVALID_LENGTH})); + EXPECT_EQ(hw1({HW_CMD_GET_AGC_RESET_INTERVAL}), (std::vector{0x9D, 30, 0})); +} + +TEST_F(KissHwControlTest, AgcResetsOnDefaultSchedule) { + advance(29999); + EXPECT_EQ(radio.agc_resets, 0); + advance(1); + EXPECT_EQ(radio.agc_resets, 1); + advance(29999); + EXPECT_EQ(radio.agc_resets, 1); + advance(1); + EXPECT_EQ(radio.agc_resets, 2); +} + +TEST_F(KissHwControlTest, AgcZeroDisablesResets) { + hw({HW_CMD_SET_AGC_RESET_INTERVAL, 0, 0}); + for (int i = 0; i < 10; i++) advance(60000); + EXPECT_EQ(radio.agc_resets, 0); +} + +TEST_F(KissHwControlTest, AgcIntervalChangeRestartsDeadline) { + hw({HW_CMD_SET_AGC_RESET_INTERVAL, 0x2C, 0x01}); // 300 s + advance(100000); + hw({HW_CMD_SET_AGC_RESET_INTERVAL, 4, 0}); + EXPECT_EQ(radio.agc_resets, 0); + advance(3999); + EXPECT_EQ(radio.agc_resets, 0); + advance(1); + EXPECT_EQ(radio.agc_resets, 1); +} + +TEST_F(KissHwControlTest, AgcResetWaitsForTxToFinish) { + hw({HW_CMD_SET_AGC_RESET_INTERVAL, 4, 0}); + startTxAndHold(); + advance(10000); + EXPECT_EQ(radio.agc_resets, 0); + radio.send_complete = true; + modem.loop(); // TX done -> TX_DONE_PENDING + modem.loop(); // TxDone flushed -> idle, overdue reset runs + EXPECT_EQ(radio.agc_resets, 1); +} + +TEST_F(KissHwControlTest, FemUnsupportedOnBareBoard) { + EXPECT_EQ(hw1({HW_CMD_GET_FEM_STATE}), (std::vector{0x9F, 0x00, 0x00})); + EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}), ERR_UNSUPPORTED); + EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_TX_GAIN, 0}), ERR_UNSUPPORTED); +} + +TEST_F(KissHwControlTest, FemSetRxLeavesTxUntouched) { + board.has_lna = board.has_pa = true; + board.pa = true; + EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}), (std::vector{0x9F, 0x03, 0x03})); + EXPECT_TRUE(board.lna); + EXPECT_EQ(board.pa_sets, 0); + + EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_TX_GAIN, 0}), (std::vector{0x9F, 0x03, 0x01})); + EXPECT_FALSE(board.pa); + EXPECT_EQ(board.lna_sets, 1); +} + +TEST_F(KissHwControlTest, FemPartialCapabilityRejectsWholeRequest) { + board.has_lna = true; + EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN | HW_FEM_TX_GAIN, HW_FEM_RX_GAIN | HW_FEM_TX_GAIN}), ERR_UNSUPPORTED); + EXPECT_EQ(board.lna_sets, 0); + EXPECT_EQ(hw1({HW_CMD_GET_FEM_STATE}), (std::vector{0x9F, 0x01, 0x00})); +} + +TEST_F(KissHwControlTest, FemUnknownBitsAreUnsupported) { + board.has_lna = board.has_pa = true; + EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, 0x04, 0x04}), ERR_UNSUPPORTED); +} + +TEST_F(KissHwControlTest, FemShortPayloadIsInvalidLength) { + EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN}), (std::vector{HW_RESP_ERROR, HW_ERR_INVALID_LENGTH})); +} + +TEST_F(KissHwControlTest, FemSetDuringTxIsDeferredUntilTxCompletes) { + board.has_lna = true; + startTxAndHold(); + serial.takeHardwareFrames(); + + EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}).empty()); + EXPECT_EQ(board.lna_sets, 0); + EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, 0}), (std::vector{HW_RESP_ERROR, HW_ERR_TX_BUSY})); + + radio.send_complete = true; + modem.loop(); + auto frames = serial.takeHardwareFrames(); + ASSERT_EQ(frames.size(), 1U); + EXPECT_EQ(frames[0], (std::vector{0x9F, 0x01, 0x01})); + EXPECT_TRUE(board.lna); + modem.loop(); + frames = serial.takeHardwareFrames(); + ASSERT_EQ(frames.size(), 1U); + EXPECT_EQ(frames[0], (std::vector{HW_RESP_TX_DONE, 0x01})); +} + +} // namespace diff --git a/variants/heltec_t096/T096Board.h b/variants/heltec_t096/T096Board.h index e926c8a6..66fa5047 100644 --- a/variants/heltec_t096/T096Board.h +++ b/variants/heltec_t096/T096Board.h @@ -16,9 +16,6 @@ protected: #endif void variant_shutdown(); - bool setLoRaFemLnaEnabled(bool enable); - bool isLoRaFemLnaEnabled() const; - public: RefCountedDigitalPin periph_power; LoRaFEMControl loRaFEMControl; @@ -27,6 +24,9 @@ public: void begin(); void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; + bool canControlLoRaFemLna() const override { return loRaFEMControl.isLnaCanControl(); } + bool setLoRaFemLnaEnabled(bool enable) override; + bool isLoRaFemLnaEnabled() const override; void onBeforeTransmit(void) override; void onAfterTransmit(void) override; diff --git a/variants/heltec_tracker_v2/HeltecTrackerV2Board.h b/variants/heltec_tracker_v2/HeltecTrackerV2Board.h index 5fed2b65..34454cac 100644 --- a/variants/heltec_tracker_v2/HeltecTrackerV2Board.h +++ b/variants/heltec_tracker_v2/HeltecTrackerV2Board.h @@ -8,9 +8,6 @@ class HeltecTrackerV2Board : public ESP32Board { KeyValueStore* _prefs = NULL; - bool setLoRaFemLnaEnabled(bool enable); - bool isLoRaFemLnaEnabled() const; - public: RefCountedDigitalPin periph_power; LoRaFEMControl loRaFEMControl; @@ -20,6 +17,9 @@ public: void begin(); void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; + bool canControlLoRaFemLna() const override { return loRaFEMControl.isLnaCanControl(); } + bool setLoRaFemLnaEnabled(bool enable) override; + bool isLoRaFemLnaEnabled() const override; void onBeforeTransmit(void) override; void onAfterTransmit(void) override; diff --git a/variants/heltec_v4/HeltecV4Board.h b/variants/heltec_v4/HeltecV4Board.h index 79a690e8..bd3bdb25 100644 --- a/variants/heltec_v4/HeltecV4Board.h +++ b/variants/heltec_v4/HeltecV4Board.h @@ -12,9 +12,6 @@ class HeltecV4Board : public ESP32Board { KeyValueStore* _prefs = NULL; - bool setLoRaFemLnaEnabled(bool enable); - bool isLoRaFemLnaEnabled() const; - protected: float adc_mult = ADC_MULTIPLIER; @@ -26,6 +23,9 @@ public: void begin(); void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; + bool canControlLoRaFemLna() const override { return loRaFEMControl.isLnaCanControl(); } + bool setLoRaFemLnaEnabled(bool enable) override; + bool isLoRaFemLnaEnabled() const override; void onBeforeTransmit(void) override; void onAfterTransmit(void) override; diff --git a/variants/heltec_v4_r8/HeltecV4R8Board.h b/variants/heltec_v4_r8/HeltecV4R8Board.h index 7ab29f96..c34ee449 100644 --- a/variants/heltec_v4_r8/HeltecV4R8Board.h +++ b/variants/heltec_v4_r8/HeltecV4R8Board.h @@ -13,8 +13,6 @@ class HeltecV4R8Board : public ESP32Board { KeyValueStore* _prefs = NULL; - bool setLoRaFemLnaEnabled(bool enable); - bool isLoRaFemLnaEnabled() const; protected: float adc_mult = ADC_MULTIPLIER; @@ -27,6 +25,9 @@ public: void begin(); void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; + bool canControlLoRaFemLna() const override { return loRaFEMControl.isLnaCanControl(); } + bool setLoRaFemLnaEnabled(bool enable) override; + bool isLoRaFemLnaEnabled() const override; void onBeforeTransmit(void) override; void onAfterTransmit(void) override; diff --git a/variants/heltec_v4_r8/LoRaFEMControl.h b/variants/heltec_v4_r8/LoRaFEMControl.h index 4b74c2e2..52d7a0f8 100644 --- a/variants/heltec_v4_r8/LoRaFEMControl.h +++ b/variants/heltec_v4_r8/LoRaFEMControl.h @@ -15,7 +15,7 @@ public: void setRxModeEnable(void); void setRxModeEnableWhenMCUSleep(void); void setLNAEnable(bool enabled); - bool isLnaCanControl(void) { return true; } + bool isLnaCanControl(void) const { return true; } void setLnaCanControl(bool can_control) { } bool isLNAEnabled(void) const { return lna_enabled; } LoRaFEMType getFEMType(void) const { return KCT8103L_PA; } diff --git a/variants/station_g3_esp32/StationG3Board.h b/variants/station_g3_esp32/StationG3Board.h index b4c5838c..f8cb75cb 100644 --- a/variants/station_g3_esp32/StationG3Board.h +++ b/variants/station_g3_esp32/StationG3Board.h @@ -8,10 +8,6 @@ class StationG3Board : public ESP32Board { KeyValueStore* _prefs = NULL; - bool setLoRaFemLnaEnabled(bool enable); - bool isLoRaFemLnaEnabled() const; - bool setLoRaFemPaGainEnabled(bool enable); - bool isLoRaFemPaGainEnabled() const; public: LoRaFEMControl loRaFEMControl; @@ -34,6 +30,12 @@ public: void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; + bool canControlLoRaFemLna() const override { return loRaFEMControl.canControlLNA(); } + bool setLoRaFemLnaEnabled(bool enable) override; + bool isLoRaFemLnaEnabled() const override; + bool canControlLoRaFemPaGain() const override { return loRaFEMControl.canControlPAGain(); } + bool setLoRaFemPaGainEnabled(bool enable) override; + bool isLoRaFemPaGainEnabled() const override; void setPrimaryLNAEnable(bool enabled) { loRaFEMControl.setLNAEnable(enabled); diff --git a/variants/wio-tracker-l1-1w/WioTrackerL1Board.h b/variants/wio-tracker-l1-1w/WioTrackerL1Board.h index 798145db..7dde409d 100644 --- a/variants/wio-tracker-l1-1w/WioTrackerL1Board.h +++ b/variants/wio-tracker-l1-1w/WioTrackerL1Board.h @@ -10,14 +10,14 @@ protected: bool _is_pa_enabled = false; KeyValueStore* _prefs = NULL; - bool setLoRaFemPaGainEnabled(bool enable); - bool isLoRaFemPaGainEnabled() const { return _is_pa_enabled; } - public: WioTrackerL1Board() : NRF52Board("WioTrackerL1 OTA") {} void begin(); void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; + bool canControlLoRaFemPaGain() const override { return true; } + bool setLoRaFemPaGainEnabled(bool enable) override; + bool isLoRaFemPaGainEnabled() const override { return _is_pa_enabled; } #if defined(P_LORA_TX_LED) void onBeforeTransmit() override { From a087a5198fd11b68f69dba075fe7d6fd0d72109a Mon Sep 17 00:00:00 2001 From: agessaman Date: Wed, 23 Sep 2026 15:51:05 -0700 Subject: [PATCH 03/79] kiss_modem: only set USB TX buffer size on HWCDC builds USBCDC (ARDUINO_USB_MODE=0, TinyUSB) has no setTxBufferSize, which broke the Station G3 and Heltec Tracker V2 KISS builds. --- examples/kiss_modem/main.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/examples/kiss_modem/main.cpp b/examples/kiss_modem/main.cpp index 8835418d..3d815d96 100644 --- a/examples/kiss_modem/main.cpp +++ b/examples/kiss_modem/main.cpp @@ -113,7 +113,10 @@ void setup() { delay(100); #if defined(ESP32) && defined(ARDUINO_USB_CDC_ON_BOOT) && ARDUINO_USB_CDC_ON_BOOT Serial.setTxTimeoutMs(USB_TX_TIMEOUT_MS); +#if defined(ARDUINO_USB_MODE) && ARDUINO_USB_MODE + // HWCDC only; TinyUSB's USBCDC TX buffer is fixed at build time Serial.setTxBufferSize(USB_TX_BUFFER_SIZE); +#endif #endif modem = new KissModem(Serial, identity, rng, radio_driver, board, sensors); #endif From 0d648e4a18a692adf6c84fe3d8bb4737fb8e1551 Mon Sep 17 00:00:00 2001 From: agessaman Date: Wed, 23 Sep 2026 16:11:29 -0700 Subject: [PATCH 04/79] kiss_modem: keep FEM replies ordered and deliverable; drop Wio FEM control - Wio Tracker L1 1W no longer advertises TX gain control: its setter drives LORA_PWR_EN, the shared LDO for the SX1262 and the PA, so "gain off" would power down the radio. - A SetFemState that arrives mid-TX is now applied after TxDone is queued, so its reply follows TxDone. - SetFemState replies (immediate or deferred) are retained until they fit in the host output queue instead of being dropped, so a change that took effect is always acknowledged. - GetFemState replies queue behind an outstanding SetFemState reply; a further SetFemState returns TxBusy until it clears. --- docs/kiss_modem_protocol.md | 2 +- examples/kiss_modem/KissModem.cpp | 64 ++++++++++---- examples/kiss_modem/KissModem.h | 8 +- test/test_kiss_modem/test_hw_controls.cpp | 83 +++++++++++++++++-- .../wio-tracker-l1-1w/WioTrackerL1Board.h | 6 +- 5 files changed, 131 insertions(+), 32 deletions(-) diff --git a/docs/kiss_modem_protocol.md b/docs/kiss_modem_protocol.md index 9b8aaa4b..1a668cc4 100644 --- a/docs/kiss_modem_protocol.md +++ b/docs/kiss_modem_protocol.md @@ -279,7 +279,7 @@ FemState response data: Example: enable RX gain without changing TX gain: apply `0x01`, value `0x01`. -If any bit in the apply mask is not in the board's capability mask (including reserved bits), the modem replies `Unsupported` and changes nothing. On success, SetFemState replies with the FemState response carrying the new state. A request received while a packet is on air is applied as soon as that transmission ends, and the FemState response is sent then; a second request during the same transmission returns `TxBusy`. Capabilities come from the board, so a board with a fixed, board-managed FEM (for example RAK3401) reports none. +If any bit in the apply mask is not in the board's capability mask (including reserved bits), the modem replies `Unsupported` and changes nothing. On success, SetFemState replies with the FemState response carrying the new state. A SetFemState received while a packet is on air (before its TxDone is queued) is held and applied after TxDone, so its FemState response follows TxDone. While a SetFemState is held or its response is still waiting for output space, GetFemState responses are queued behind it in order, and a further SetFemState returns `TxBusy`. Capabilities come from the board, so a board with a fixed, board-managed FEM (for example RAK3401) reports none. The setting is not persisted; the board's power-on default applies after reboot. diff --git a/examples/kiss_modem/KissModem.cpp b/examples/kiss_modem/KissModem.cpp index 5b61e83c..af678bbe 100644 --- a/examples/kiss_modem/KissModem.cpp +++ b/examples/kiss_modem/KissModem.cpp @@ -27,6 +27,9 @@ KissModem::KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& r _fem_deferred = false; _fem_deferred_apply = 0; _fem_deferred_value = 0; + _fem_reply_pending = false; + _fem_reply_ok = false; + _fem_deferred_gets = 0; resetOutputQueue(); } @@ -37,6 +40,8 @@ void KissModem::begin() { _has_pending_tx = false; _tx_state = TX_IDLE; _fem_deferred = false; + _fem_reply_pending = false; + _fem_deferred_gets = 0; _next_agc_reset_ms = millis() + (uint32_t)_agc_reset_interval_sec * 1000; resetOutputQueue(); } @@ -811,12 +816,16 @@ uint8_t KissModem::femValueMask() const { return mask; } -void KissModem::writeFemState() { +bool KissModem::queueFemReply(bool ok, bool mark_busy_error) { + if (!ok) { + const uint8_t err = HW_ERR_UNSUPPORTED; + return queueHardwareFrame(HW_RESP_ERROR, &err, 1, mark_busy_error); + } uint8_t buf[2] = { femCapabilityMask(), femValueMask() }; - writeHardwareFrame(HW_RESP(HW_CMD_GET_FEM_STATE), buf, 2); + return queueHardwareFrame(HW_RESP(HW_CMD_GET_FEM_STATE), buf, 2, mark_busy_error); } -void KissModem::applyFemState(uint8_t apply_mask, uint8_t value_mask) { +bool KissModem::applyFemState(uint8_t apply_mask, uint8_t value_mask) { bool ok = true; if (apply_mask & HW_FEM_RX_GAIN) { ok &= _board.setLoRaFemLnaEnabled((value_mask & HW_FEM_RX_GAIN) != 0); @@ -824,17 +833,26 @@ void KissModem::applyFemState(uint8_t apply_mask, uint8_t value_mask) { if (apply_mask & HW_FEM_TX_GAIN) { ok &= _board.setLoRaFemPaGainEnabled((value_mask & HW_FEM_TX_GAIN) != 0); } - if (ok) { - writeFemState(); - } else { - writeHardwareError(HW_ERR_UNSUPPORTED); - } + return ok; } void KissModem::processDeferredFem() { - if (!_fem_deferred || _tx_state == TX_SENDING) return; - _fem_deferred = false; - applyFemState(_fem_deferred_apply, _fem_deferred_value); + // wait for TxDone to be queued so the host sees the TX result before the FEM change + if (_fem_deferred && _tx_state != TX_SENDING && _tx_state != TX_DONE_PENDING) { + _fem_reply_ok = applyFemState(_fem_deferred_apply, _fem_deferred_value); + _fem_deferred = false; + _fem_reply_pending = true; + } + if (_fem_deferred) return; + // replies are retained until queued, and GetFemState replies stay behind the Set reply + if (_fem_reply_pending) { + if (!queueFemReply(_fem_reply_ok, false)) return; + _fem_reply_pending = false; + } + while (_fem_deferred_gets > 0) { + if (!queueFemReply(true, false)) return; + _fem_deferred_gets--; + } } void KissModem::handleSetFemState(const uint8_t* data, uint16_t len) { @@ -849,20 +867,30 @@ void KissModem::handleSetFemState(const uint8_t* data, uint16_t len) { writeHardwareError(HW_ERR_UNSUPPORTED); return; } - if (_tx_state == TX_SENDING) { + if (isFemReplyQueued()) { + writeHardwareError(HW_ERR_TX_BUSY); + return; + } + if (_tx_state == TX_SENDING || _tx_state == TX_DONE_PENDING) { // board setters drive FEM pins directly; changing them mid-packet would corrupt the TX - if (_fem_deferred) { - writeHardwareError(HW_ERR_TX_BUSY); - return; - } _fem_deferred = true; _fem_deferred_apply = apply_mask; _fem_deferred_value = value_mask; return; } - applyFemState(apply_mask, value_mask); + _fem_reply_ok = applyFemState(apply_mask, value_mask); + _fem_reply_pending = true; + processDeferredFem(); } void KissModem::handleGetFemState() { - writeFemState(); + if (isFemReplyQueued()) { + if (_fem_deferred_gets == UINT8_MAX) { + writeHardwareError(HW_ERR_TX_BUSY); + return; + } + _fem_deferred_gets++; + return; + } + queueFemReply(true, true); } diff --git a/examples/kiss_modem/KissModem.h b/examples/kiss_modem/KissModem.h index 751fb336..25184217 100644 --- a/examples/kiss_modem/KissModem.h +++ b/examples/kiss_modem/KissModem.h @@ -163,6 +163,9 @@ class KissModem { bool _fem_deferred; uint8_t _fem_deferred_apply; uint8_t _fem_deferred_value; + bool _fem_reply_pending; + bool _fem_reply_ok; + uint8_t _fem_deferred_gets; uint8_t _tx_frame_buf[KISS_TX_FRAME_QUEUE_DEPTH][KISS_MAX_ENCODED_FRAME_SIZE]; uint16_t _tx_frame_len[KISS_TX_FRAME_QUEUE_DEPTH]; uint16_t _tx_frame_written[KISS_TX_FRAME_QUEUE_DEPTH]; @@ -192,8 +195,9 @@ class KissModem { void maybeResetAgc(); uint8_t femCapabilityMask() const; uint8_t femValueMask() const; - void writeFemState(); - void applyFemState(uint8_t apply_mask, uint8_t value_mask); + bool queueFemReply(bool ok, bool mark_busy_error); + bool applyFemState(uint8_t apply_mask, uint8_t value_mask); + bool isFemReplyQueued() const { return _fem_deferred || _fem_reply_pending || _fem_deferred_gets > 0; } void processDeferredFem(); void handleGetIdentity(); diff --git a/test/test_kiss_modem/test_hw_controls.cpp b/test/test_kiss_modem/test_hw_controls.cpp index ad6f1e36..614ccc24 100644 --- a/test/test_kiss_modem/test_hw_controls.cpp +++ b/test/test_kiss_modem/test_hw_controls.cpp @@ -13,8 +13,9 @@ public: for (uint8_t b : bytes) _rx.push(b); } - int availableForWrite() override { return 4096; } + int availableForWrite() override { return blocked ? 0 : 4096; } size_t write(const uint8_t* buffer, size_t size) override { + if (blocked) return 0; _writes.insert(_writes.end(), buffer, buffer + size); return size; } @@ -49,6 +50,8 @@ public: return frames; } + bool blocked = false; + private: std::queue _rx; std::vector _writes; @@ -254,7 +257,7 @@ TEST_F(KissHwControlTest, FemShortPayloadIsInvalidLength) { EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN}), (std::vector{HW_RESP_ERROR, HW_ERR_INVALID_LENGTH})); } -TEST_F(KissHwControlTest, FemSetDuringTxIsDeferredUntilTxCompletes) { +TEST_F(KissHwControlTest, FemSetDuringTxIsDeferredUntilAfterTxDone) { board.has_lna = true; startTxAndHold(); serial.takeHardwareFrames(); @@ -264,15 +267,79 @@ TEST_F(KissHwControlTest, FemSetDuringTxIsDeferredUntilTxCompletes) { EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, 0}), (std::vector{HW_RESP_ERROR, HW_ERR_TX_BUSY})); radio.send_complete = true; + modem.loop(); // TX done -> TX_DONE_PENDING; FEM still held + modem.loop(); // TxDone queued -> idle; FEM applied + auto frames = serial.takeHardwareFrames(); + ASSERT_EQ(frames.size(), 2U); + EXPECT_EQ(frames[0], (std::vector{HW_RESP_TX_DONE, 0x01})); + EXPECT_EQ(frames[1], (std::vector{0x9F, 0x01, 0x01})); + EXPECT_TRUE(board.lna); + EXPECT_EQ(board.lna_sets, 1); +} + +TEST_F(KissHwControlTest, FemGetDuringDeferredSetIsAnsweredAfterSet) { + board.has_lna = true; + startTxAndHold(); + serial.takeHardwareFrames(); + + EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}).empty()); + EXPECT_TRUE(hw({HW_CMD_GET_FEM_STATE}).empty()); + + radio.send_complete = true; + modem.loop(); modem.loop(); auto frames = serial.takeHardwareFrames(); - ASSERT_EQ(frames.size(), 1U); - EXPECT_EQ(frames[0], (std::vector{0x9F, 0x01, 0x01})); - EXPECT_TRUE(board.lna); - modem.loop(); - frames = serial.takeHardwareFrames(); - ASSERT_EQ(frames.size(), 1U); + ASSERT_EQ(frames.size(), 3U); EXPECT_EQ(frames[0], (std::vector{HW_RESP_TX_DONE, 0x01})); + EXPECT_EQ(frames[1], (std::vector{0x9F, 0x01, 0x01})); + EXPECT_EQ(frames[2], (std::vector{0x9F, 0x01, 0x01})); +} + +TEST_F(KissHwControlTest, DeferredFemRepliesSurviveHostBackpressure) { + board.has_lna = true; + hw({HW_CMD_SET_SIGNAL_REPORT, 0}); // one output frame per RX packet + startTxAndHold(); + serial.takeHardwareFrames(); + EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}).empty()); + EXPECT_TRUE(hw({HW_CMD_GET_FEM_STATE}).empty()); + + // with writes blocked: RX packet takes slot 1, TxDone slot 2, so the Set reply cannot be queued + serial.blocked = true; + static constexpr uint8_t PKT[] = {0x01}; + modem.onPacketReceived(0, 0, PKT, sizeof(PKT)); + radio.send_complete = true; + for (int i = 0; i < 5; i++) modem.loop(); + EXPECT_TRUE(board.lna); // applied once TxDone was queued, reply still held + + serial.blocked = false; + for (int i = 0; i < 5; i++) modem.loop(); + EXPECT_EQ(board.lna_sets, 1); + + auto frames = serial.takeHardwareFrames(); + ASSERT_EQ(frames.size(), 3U); + EXPECT_EQ(frames[0], (std::vector{HW_RESP_TX_DONE, 0x01})); + EXPECT_EQ(frames[1], (std::vector{0x9F, 0x01, 0x01})); + EXPECT_EQ(frames[2], (std::vector{0x9F, 0x01, 0x01})); +} + +TEST_F(KissHwControlTest, ImmediateFemReplySurvivesHostBackpressure) { + board.has_lna = true; + hw({HW_CMD_SET_SIGNAL_REPORT, 0}); + + serial.blocked = true; + static constexpr uint8_t PKT[] = {0x01}; + modem.onPacketReceived(0, 0, PKT, sizeof(PKT)); + modem.onPacketReceived(0, 0, PKT, sizeof(PKT)); // output queue now full + serial.pushRx({KISS_FEND, KISS_CMD_SETHARDWARE, HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN, KISS_FEND}); + modem.loop(); + EXPECT_TRUE(board.lna); + + serial.blocked = false; + for (int i = 0; i < 5; i++) modem.loop(); + auto frames = serial.takeHardwareFrames(); + ASSERT_EQ(frames.size(), 1U); // FemState, not TxBusy + EXPECT_EQ(frames[0], (std::vector{0x9F, 0x01, 0x01})); + EXPECT_EQ(board.lna_sets, 1); } } // namespace diff --git a/variants/wio-tracker-l1-1w/WioTrackerL1Board.h b/variants/wio-tracker-l1-1w/WioTrackerL1Board.h index 7dde409d..798145db 100644 --- a/variants/wio-tracker-l1-1w/WioTrackerL1Board.h +++ b/variants/wio-tracker-l1-1w/WioTrackerL1Board.h @@ -10,14 +10,14 @@ protected: bool _is_pa_enabled = false; KeyValueStore* _prefs = NULL; + bool setLoRaFemPaGainEnabled(bool enable); + bool isLoRaFemPaGainEnabled() const { return _is_pa_enabled; } + public: WioTrackerL1Board() : NRF52Board("WioTrackerL1 OTA") {} void begin(); void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; - bool canControlLoRaFemPaGain() const override { return true; } - bool setLoRaFemPaGainEnabled(bool enable) override; - bool isLoRaFemPaGainEnabled() const override { return _is_pa_enabled; } #if defined(P_LORA_TX_LED) void onBeforeTransmit() override { From 8cefda9612011bd35b592cd610c40953c8e7815a Mon Sep 17 00:00:00 2001 From: agessaman Date: Wed, 23 Sep 2026 16:59:39 -0700 Subject: [PATCH 05/79] kiss_modem: add radio chip boosted RX gain control Add SetRxBoostedGain (0x20) / GetRxBoostedGain (0x21, reply 0xA1) and capability bit 3, the KISS equivalent of the radio.rxgain CLI setting. It is separate from FEM RX gain; a board may support either or both. - Support is declared by the driver via a new RadioLibWrapper::supportsRxBoostedGain() (SX1262, SX1268, LLCC68, LR1110, LR1121, LR2021), so nothing is written to the radio at boot. - The set is refused with TxBusy during TX or while host output is backed up. Otherwise any completed RX packet is delivered first, because some drivers (LR2021) drop to standby to apply the gain. - The reply always carries the state read back from the radio. Driver fixes found along the way, which also affect the radio.rxgain CLI in regular firmware: - CustomLR2021 never updated its cached gain state, so the getter always reported off. It now tracks the applied level per RX path and rolls RadioLib's cached level back if a write fails. - CustomLR1110/LR1121 cached the requested state even when the write failed. - lr11x0ResetAGC only reapplied the gain when RX_BOOSTED_GAIN was defined, so a runtime setting was lost on the next AGC reset. --- docs/kiss_modem_protocol.md | 16 ++- examples/kiss_modem/KissModem.cpp | 45 +++++++++ examples/kiss_modem/KissModem.h | 18 ++++ examples/kiss_modem/main.cpp | 30 ++++-- src/helpers/radiolib/CustomLLCC68Wrapper.h | 1 + src/helpers/radiolib/CustomLR1110.h | 5 +- src/helpers/radiolib/CustomLR1110Wrapper.h | 1 + src/helpers/radiolib/CustomLR1121.h | 5 +- src/helpers/radiolib/CustomLR1121Wrapper.h | 1 + src/helpers/radiolib/CustomLR2021.h | 20 +++- src/helpers/radiolib/CustomLR2021Wrapper.h | 1 + src/helpers/radiolib/CustomSX1262Wrapper.h | 1 + src/helpers/radiolib/CustomSX1268Wrapper.h | 1 + src/helpers/radiolib/LR11x0Reset.h | 3 +- src/helpers/radiolib/RadioLibWrappers.h | 1 + test/test_kiss_modem/test_hw_controls.cpp | 112 +++++++++++++++++++++ 16 files changed, 245 insertions(+), 16 deletions(-) diff --git a/docs/kiss_modem_protocol.md b/docs/kiss_modem_protocol.md index 1a668cc4..cb7be8b3 100644 --- a/docs/kiss_modem_protocol.md +++ b/docs/kiss_modem_protocol.md @@ -123,10 +123,12 @@ MeshCore-specific functionality uses the standard KISS SetHardware command. The | GetAgcResetInterval | `0x1D` | - | | SetFemState | `0x1E` | Apply mask (1) + Value mask (1) | | GetFemState | `0x1F` | - | +| SetRxBoostedGain | `0x20` | Enable (1): 0x00=disable, nonzero=enable | +| GetRxBoostedGain | `0x21` | - | ### Response Sub-commands (TNC to Host) -Response codes use the high-bit convention: `response = command | 0x80`. Generic and unsolicited responses use the `0xF0`+ range. Set commands that report state (SetSignalReport, SetAgcResetInterval, SetFemState) reply with the matching Get response, so `0x9C` and `0x9E` are never sent. +Response codes use the high-bit convention: `response = command | 0x80`. Generic and unsolicited responses use the `0xF0`+ range. Set commands that report state (SetSignalReport, SetAgcResetInterval, SetFemState, SetRxBoostedGain) reply with the matching Get response, so `0x9C`, `0x9E` and `0xA0` are never sent. | Sub-command | Value | Data | |--------------|--------|-----------------------------------------| @@ -155,6 +157,7 @@ Response codes use the high-bit convention: `response = command | 0x80`. Generic | Capabilities | `0x9B` | Feature bits (4) | | AgcResetInterval | `0x9D` | Effective seconds (2) | | FemState | `0x9F` | Capability mask (1) + Value mask (1) | +| RxBoostedGain | `0xA1` | Status (1): 0x00=disabled, 0x01=enabled | | OK | `0xF0` | - | | Error | `0xF1` | Error code (1) | | TxDone | `0xF8` | Result (1): 0x00=failed, 0x01=success | @@ -239,6 +242,7 @@ All values little-endian. Hosts should probe capabilities rather than infer them | 0 | `0x01` | AGC reset interval control (always set) | | 1 | `0x02` | External FEM RX (LNA) gain control | | 2 | `0x04` | External FEM TX (PA) gain control | +| 3 | `0x08` | Radio chip boosted RX gain control | Remaining bits are reserved and sent as 0. @@ -283,6 +287,16 @@ If any bit in the apply mask is not in the board's capability mask (including re The setting is not persisted; the board's power-on default applies after reboot. +### RX Boosted Gain (SetRxBoostedGain / RxBoostedGain response) + +Controls the radio chip's own boosted RX gain mode (SX1262, SX1268, LLCC68, LR11x0, LR2021), the equivalent of the MeshCore `radio.rxgain` setting. This is independent of the external FEM RX gain controlled by SetFemState; a board can support either, both or neither. + +| Field | Size | Description | +|--------|--------|------------------------------------| +| Status | 1 byte | 0x00 = power-saving, 0x01 = boosted | + +SetRxBoostedGain always replies with the RxBoostedGain response carrying the effective state read back from the radio; if it differs from the requested value, the change did not take effect. Some radios must drop to standby to apply it, so the modem replies `TxBusy` and changes nothing while a packet is on air or host output is backed up; retry later. Before applying, any completed received packet is delivered to the host first. A packet still being received at that moment can be lost. Radios whose driver has no boosted RX gain control (for example SX127x and STM32WLx) do not set capability bit 3 and reply `Unsupported` to both commands. The power-on default is the build's `SX126X_RX_BOOSTED_GAIN` setting; the value is not persisted, and periodic AGC resets preserve it. + ### Stats (Stats response) All values little-endian. diff --git a/examples/kiss_modem/KissModem.cpp b/examples/kiss_modem/KissModem.cpp index af678bbe..221c40b1 100644 --- a/examples/kiss_modem/KissModem.cpp +++ b/examples/kiss_modem/KissModem.cpp @@ -20,6 +20,9 @@ KissModem::KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& r _setTxPowerCallback = nullptr; _getCurrentRssiCallback = nullptr; _getStatsCallback = nullptr; + _setRxBoostedGainCallback = nullptr; + _getRxBoostedGainCallback = nullptr; + _pollRxCallback = nullptr; _config = {0, 0, 0, 0, 0}; _signal_report_enabled = true; _agc_reset_interval_sec = KISS_AGC_RESET_DEFAULT_SEC; @@ -422,6 +425,12 @@ void KissModem::handleHardwareCommand(uint8_t sub_cmd, const uint8_t* data, uint case HW_CMD_GET_FEM_STATE: handleGetFemState(); break; + case HW_CMD_SET_RX_BOOSTED_GAIN: + handleSetRxBoostedGain(data, len); + break; + case HW_CMD_GET_RX_BOOSTED_GAIN: + handleGetRxBoostedGain(); + break; default: writeHardwareError(HW_ERR_UNKNOWN_CMD); break; @@ -778,6 +787,7 @@ void KissModem::handleGetCapabilities() { uint32_t caps = HW_CAP_AGC_RESET; if (_board.canControlLoRaFemLna()) caps |= HW_CAP_FEM_RX_GAIN; if (_board.canControlLoRaFemPaGain()) caps |= HW_CAP_FEM_TX_GAIN; + if (_setRxBoostedGainCallback && _getRxBoostedGainCallback) caps |= HW_CAP_RX_BOOSTED_GAIN; uint8_t buf[4] = { (uint8_t)caps, (uint8_t)(caps >> 8), (uint8_t)(caps >> 16), (uint8_t)(caps >> 24) }; writeHardwareFrame(HW_RESP(HW_CMD_GET_CAPABILITIES), buf, 4); } @@ -894,3 +904,38 @@ void KissModem::handleGetFemState() { } queueFemReply(true, true); } + +void KissModem::handleSetRxBoostedGain(const uint8_t* data, uint16_t len) { + if (len < 1) { + writeHardwareError(HW_ERR_INVALID_LENGTH); + return; + } + if (!_setRxBoostedGainCallback || !_getRxBoostedGainCallback) { + writeHardwareError(HW_ERR_UNSUPPORTED); + return; + } + // some drivers (LR2021) drop to standby to apply the gain, which would abort a TX and + // discard a completed RX packet; so never during TX, and only after draining RX + if (_tx_state == TX_SENDING || isHostOutputBackedUp()) { + writeHardwareError(HW_ERR_TX_BUSY); + return; + } + if (_pollRxCallback) _pollRxCallback(); + tryFlushFrames(); + if (_tx_frame_count >= KISS_TX_FRAME_QUEUE_DEPTH) { + writeHardwareError(HW_ERR_TX_BUSY); // no room left for the reply; change nothing + return; + } + // always reply with the state read back, so a failed or partial write is never misreported + _setRxBoostedGainCallback(data[0] != 0x00); + handleGetRxBoostedGain(); +} + +void KissModem::handleGetRxBoostedGain() { + if (!_getRxBoostedGainCallback) { + writeHardwareError(HW_ERR_UNSUPPORTED); + return; + } + uint8_t val = _getRxBoostedGainCallback() ? 0x01 : 0x00; + writeHardwareFrame(HW_RESP(HW_CMD_GET_RX_BOOSTED_GAIN), &val, 1); +} diff --git a/examples/kiss_modem/KissModem.h b/examples/kiss_modem/KissModem.h index 25184217..ffe89191 100644 --- a/examples/kiss_modem/KissModem.h +++ b/examples/kiss_modem/KissModem.h @@ -67,6 +67,8 @@ #define HW_CMD_GET_AGC_RESET_INTERVAL 0x1D #define HW_CMD_SET_FEM_STATE 0x1E #define HW_CMD_GET_FEM_STATE 0x1F +#define HW_CMD_SET_RX_BOOSTED_GAIN 0x20 +#define HW_CMD_GET_RX_BOOSTED_GAIN 0x21 /* Response code = command code | 0x80. Generic / unsolicited use 0xF0+. */ #define HW_RESP(cmd) ((cmd) | 0x80) @@ -92,6 +94,7 @@ #define HW_CAP_AGC_RESET (1UL << 0) #define HW_CAP_FEM_RX_GAIN (1UL << 1) #define HW_CAP_FEM_TX_GAIN (1UL << 2) +#define HW_CAP_RX_BOOSTED_GAIN (1UL << 3) /* SetFemState / GetFemState mask bits */ #define HW_FEM_RX_GAIN (1 << 0) @@ -107,6 +110,9 @@ typedef void (*SetRadioCallback)(float freq, float bw, uint8_t sf, uint8_t cr); typedef void (*SetTxPowerCallback)(uint8_t power); typedef float (*GetCurrentRssiCallback)(); typedef void (*GetStatsCallback)(uint32_t* rx, uint32_t* tx, uint32_t* errors); +typedef bool (*SetRxBoostedGainCallback)(bool enable); +typedef bool (*GetRxBoostedGainCallback)(); +typedef void (*PollRxCallback)(); struct RadioConfig { uint32_t freq_hz; @@ -155,6 +161,9 @@ class KissModem { SetTxPowerCallback _setTxPowerCallback; GetCurrentRssiCallback _getCurrentRssiCallback; GetStatsCallback _getStatsCallback; + SetRxBoostedGainCallback _setRxBoostedGainCallback; + GetRxBoostedGainCallback _getRxBoostedGainCallback; + PollRxCallback _pollRxCallback; RadioConfig _config; bool _signal_report_enabled; @@ -231,6 +240,8 @@ class KissModem { void handleGetAgcResetInterval(); void handleSetFemState(const uint8_t* data, uint16_t len); void handleGetFemState(); + void handleSetRxBoostedGain(const uint8_t* data, uint16_t len); + void handleGetRxBoostedGain(); public: KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& rng, @@ -243,6 +254,13 @@ public: void setTxPowerCallback(SetTxPowerCallback cb) { _setTxPowerCallback = cb; } void setGetCurrentRssiCallback(GetCurrentRssiCallback cb) { _getCurrentRssiCallback = cb; } void setGetStatsCallback(GetStatsCallback cb) { _getStatsCallback = cb; } + // Only register these when the radio supports boosted RX gain; they define the capability. + // Delivers any completed RX packet to the host; called before settings that restart the receiver. + void setPollRxCallback(PollRxCallback cb) { _pollRxCallback = cb; } + void setRxBoostedGainCallbacks(SetRxBoostedGainCallback set_cb, GetRxBoostedGainCallback get_cb) { + _setRxBoostedGainCallback = set_cb; + _getRxBoostedGainCallback = get_cb; + } void onPacketReceived(int8_t snr, int8_t rssi, const uint8_t* packet, uint16_t len); bool isTxBusy() const { return _tx_state != TX_IDLE; } diff --git a/examples/kiss_modem/main.cpp b/examples/kiss_modem/main.cpp index 3d815d96..dd1ee14f 100644 --- a/examples/kiss_modem/main.cpp +++ b/examples/kiss_modem/main.cpp @@ -73,6 +73,24 @@ void onGetStats(uint32_t* rx, uint32_t* tx, uint32_t* errors) { *errors = radio_driver.getPacketsRecvErrors(); } +void pollRadioRx() { + uint8_t rx_buf[256]; + int rx_len = radio_driver.recvRaw(rx_buf, sizeof(rx_buf)); + if (rx_len > 0) { + int8_t snr = (int8_t)(radio_driver.getLastSNR() * 4); + int8_t rssi = (int8_t)radio_driver.getLastRSSI(); + modem->onPacketReceived(snr, rssi, rx_buf, rx_len); + } +} + +bool onSetRxBoostedGain(bool enable) { + return radio_driver.setRxBoostedGainMode(enable); +} + +bool onGetRxBoostedGain() { + return radio_driver.getRxBoostedGainMode(); +} + void setup() { board.begin(); @@ -125,6 +143,10 @@ void setup() { modem->setTxPowerCallback(onSetTxPower); modem->setGetCurrentRssiCallback(onGetCurrentRssi); modem->setGetStatsCallback(onGetStats); + modem->setPollRxCallback(pollRadioRx); + if (radio_driver.supportsRxBoostedGain()) { + modem->setRxBoostedGainCallbacks(onSetRxBoostedGain, onGetRxBoostedGain); + } modem->begin(); board.onBootComplete(); @@ -134,13 +156,7 @@ void loop() { modem->loop(); if (!modem->isActuallyTransmitting() && !modem->isHostOutputBackedUp()) { - uint8_t rx_buf[256]; - int rx_len = radio_driver.recvRaw(rx_buf, sizeof(rx_buf)); - if (rx_len > 0) { - int8_t snr = (int8_t)(radio_driver.getLastSNR() * 4); - int8_t rssi = (int8_t)radio_driver.getLastRSSI(); - modem->onPacketReceived(snr, rssi, rx_buf, rx_len); - } + pollRadioRx(); } board.loop(); diff --git a/src/helpers/radiolib/CustomLLCC68Wrapper.h b/src/helpers/radiolib/CustomLLCC68Wrapper.h index ae0fe0a2..89d5e1bc 100644 --- a/src/helpers/radiolib/CustomLLCC68Wrapper.h +++ b/src/helpers/radiolib/CustomLLCC68Wrapper.h @@ -37,6 +37,7 @@ public: void doResetAGC() override { sx126xResetAGC((SX126x *)_radio); } + bool supportsRxBoostedGain() const override { return true; } bool setRxBoostedGainMode(bool en) override { return ((CustomLLCC68 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE; } diff --git a/src/helpers/radiolib/CustomLR1110.h b/src/helpers/radiolib/CustomLR1110.h index f0fde435..0d430c1d 100644 --- a/src/helpers/radiolib/CustomLR1110.h +++ b/src/helpers/radiolib/CustomLR1110.h @@ -39,8 +39,9 @@ class CustomLR1110 : public LR1110 { float getFreqMHz() const { return freqMHz; } int16_t setRxBoostedGainMode(bool en) { - _rx_boosted = en; - return LR1110::setRxBoostedGainMode(en); + int16_t status = LR1110::setRxBoostedGainMode(en); + if (status == RADIOLIB_ERR_NONE) _rx_boosted = en; + return status; } bool getRxBoostedGainMode() const { return _rx_boosted; } diff --git a/src/helpers/radiolib/CustomLR1110Wrapper.h b/src/helpers/radiolib/CustomLR1110Wrapper.h index e7aaeb93..bf2e8370 100644 --- a/src/helpers/radiolib/CustomLR1110Wrapper.h +++ b/src/helpers/radiolib/CustomLR1110Wrapper.h @@ -43,6 +43,7 @@ public: uint8_t getSpreadingFactor() const override { return ((CustomLR1110 *)_radio)->getSpreadingFactor(); } + bool supportsRxBoostedGain() const override { return true; } bool setRxBoostedGainMode(bool en) override { return ((CustomLR1110 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE; } diff --git a/src/helpers/radiolib/CustomLR1121.h b/src/helpers/radiolib/CustomLR1121.h index 67e3b52a..eaa55be8 100644 --- a/src/helpers/radiolib/CustomLR1121.h +++ b/src/helpers/radiolib/CustomLR1121.h @@ -39,8 +39,9 @@ class CustomLR1121 : public LR1121 { float getFreqMHz() const { return freqMHz; } int16_t setRxBoostedGainMode(bool en) { - _rx_boosted = en; - return LR1121::setRxBoostedGainMode(en); + int16_t status = LR1121::setRxBoostedGainMode(en); + if (status == RADIOLIB_ERR_NONE) _rx_boosted = en; + return status; } bool getRxBoostedGainMode() const { return _rx_boosted; } diff --git a/src/helpers/radiolib/CustomLR1121Wrapper.h b/src/helpers/radiolib/CustomLR1121Wrapper.h index 5a754cee..d5620b45 100644 --- a/src/helpers/radiolib/CustomLR1121Wrapper.h +++ b/src/helpers/radiolib/CustomLR1121Wrapper.h @@ -44,6 +44,7 @@ public: uint8_t getSpreadingFactor() const override { return ((CustomLR1121 *)_radio)->getSpreadingFactor(); } + bool supportsRxBoostedGain() const override { return true; } bool setRxBoostedGainMode(bool en) override { return ((CustomLR1121 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE; } diff --git a/src/helpers/radiolib/CustomLR2021.h b/src/helpers/radiolib/CustomLR2021.h index 0255b93c..d08d3dc7 100644 --- a/src/helpers/radiolib/CustomLR2021.h +++ b/src/helpers/radiolib/CustomLR2021.h @@ -8,7 +8,9 @@ class CustomLR2021 : public LR2021 { uint32_t _maxPayloadMillis = 3934; uint32_t _activityAt = 0; bool _headerSeen = false; - bool _rx_boosted = false; + // last applied gain level per RX path, mirroring RadioLib's gainModeLf/gainModeHf defaults + uint8_t _rx_gain_lf = RADIOLIB_LR2021_RX_BOOST_LF; + uint8_t _rx_gain_hf = RADIOLIB_LR2021_RX_BOOST_HF; public: CustomLR2021(Module *mod) : LR2021(mod) { irqDioNum = LR2021_IRQ_DIO; } @@ -68,7 +70,21 @@ class CustomLR2021 : public LR2021 { float getFreqMHz() const { return freqMHz; } - bool getRxBoostedGainMode() const { return _rx_boosted; } + bool isHighFreqPath() const { return freqMHz > RADIOLIB_LR2021_LF_CUTOFF_FREQ; } + + int16_t setRxBoostedGainMode(uint8_t level) { + uint8_t& applied = isHighFreqPath() ? _rx_gain_hf : _rx_gain_lf; + int16_t status = LR2021::setRxBoostedGainMode(level); + if (status == RADIOLIB_ERR_NONE) { + applied = level; + } else { + // RadioLib caches the level before sending it; restore it so the next startReceive keeps the old gain + LR2021::setRxBoostedGainMode(applied); + } + return status; + } + + bool getRxBoostedGainMode() const { return (isHighFreqPath() ? _rx_gain_hf : _rx_gain_lf) != 0; } int16_t startReceive() override { // include the PREAMBLE_DETECTED irq bit in reported flags diff --git a/src/helpers/radiolib/CustomLR2021Wrapper.h b/src/helpers/radiolib/CustomLR2021Wrapper.h index 8299e2bf..ca0affb6 100644 --- a/src/helpers/radiolib/CustomLR2021Wrapper.h +++ b/src/helpers/radiolib/CustomLR2021Wrapper.h @@ -93,6 +93,7 @@ public: uint8_t getSpreadingFactor() const override { return ((CustomLR2021 *)_radio)->getSpreadingFactor(); } + bool supportsRxBoostedGain() const override { return true; } bool setRxBoostedGainMode(bool en) override { ((CustomLR2021 *)_radio)->standby(); // LR2021 must be in standby to accept setRxBoostedGainMode int16_t status = ((CustomLR2021 *)_radio)->setRxBoostedGainMode(en ? LR2021_RX_BOOST_LEVEL: 0); diff --git a/src/helpers/radiolib/CustomSX1262Wrapper.h b/src/helpers/radiolib/CustomSX1262Wrapper.h index be314471..0caf0f1f 100644 --- a/src/helpers/radiolib/CustomSX1262Wrapper.h +++ b/src/helpers/radiolib/CustomSX1262Wrapper.h @@ -41,6 +41,7 @@ public: ((CustomSX1262 *)_radio)->sleep(false); } + bool supportsRxBoostedGain() const override { return true; } bool setRxBoostedGainMode(bool en) override { return ((CustomSX1262 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE; } diff --git a/src/helpers/radiolib/CustomSX1268Wrapper.h b/src/helpers/radiolib/CustomSX1268Wrapper.h index 70f5dabd..9fef1184 100644 --- a/src/helpers/radiolib/CustomSX1268Wrapper.h +++ b/src/helpers/radiolib/CustomSX1268Wrapper.h @@ -38,6 +38,7 @@ public: } uint8_t getSpreadingFactor() const override { return ((CustomSX1268 *)_radio)->spreadingFactor; } + bool supportsRxBoostedGain() const override { return true; } bool setRxBoostedGainMode(bool en) override { return ((CustomSX1268 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE; } diff --git a/src/helpers/radiolib/LR11x0Reset.h b/src/helpers/radiolib/LR11x0Reset.h index cdfc1f9f..3a10ff00 100644 --- a/src/helpers/radiolib/LR11x0Reset.h +++ b/src/helpers/radiolib/LR11x0Reset.h @@ -15,7 +15,6 @@ inline void lr11x0ResetAGC(LR11x0* radio, float freqMHz, bool rx_boost_gain) { // Re-calibrate for the actual operating frequency (band=4MHz matches RadioLib default). radio->calibrateImageRejection(freqMHz - 4.0f, freqMHz + 4.0f); -#ifdef RX_BOOSTED_GAIN + // always reapply: the gain may have been changed at runtime even when no build default is set radio->setRxBoostedGainMode(rx_boost_gain); -#endif } diff --git a/src/helpers/radiolib/RadioLibWrappers.h b/src/helpers/radiolib/RadioLibWrappers.h index 77dd9311..9b367ee4 100644 --- a/src/helpers/radiolib/RadioLibWrappers.h +++ b/src/helpers/radiolib/RadioLibWrappers.h @@ -75,6 +75,7 @@ public: float packetScore(float snr, int packet_len) override { return packetScoreInt(snr, 10, packet_len); } // assume sf=10 + virtual bool supportsRxBoostedGain() const { return false; } virtual bool setRxBoostedGainMode(bool) { return false; } virtual bool getRxBoostedGainMode() const { return false; } diff --git a/test/test_kiss_modem/test_hw_controls.cpp b/test/test_kiss_modem/test_hw_controls.cpp index 614ccc24..37b1b929 100644 --- a/test/test_kiss_modem/test_hw_controls.cpp +++ b/test/test_kiss_modem/test_hw_controls.cpp @@ -149,6 +149,29 @@ protected: } }; +bool g_rx_boost = false; +bool g_rx_boost_set_ok = true; +int g_rx_boost_sets = 0; +bool fakeSetRxBoost(bool en) { + g_rx_boost_sets++; + if (!g_rx_boost_set_ok) return false; + g_rx_boost = en; + return true; +} +bool fakeGetRxBoost() { return g_rx_boost; } + +KissModem* g_poll_modem = nullptr; +bool g_poll_has_packet = false; +int g_polls = 0; +void fakePollRx() { + g_polls++; + if (g_poll_has_packet && g_poll_modem) { + static constexpr uint8_t PKT[] = {0x55}; + g_poll_has_packet = false; + g_poll_modem->onPacketReceived(4, -80, PKT, sizeof(PKT)); + } +} + const std::vector ERR_UNSUPPORTED = {HW_RESP_ERROR, HW_ERR_UNSUPPORTED}; TEST_F(KissHwControlTest, VersionIsTwo) { @@ -342,4 +365,93 @@ TEST_F(KissHwControlTest, ImmediateFemReplySurvivesHostBackpressure) { EXPECT_EQ(board.lna_sets, 1); } +class KissRxBoostTest : public KissHwControlTest { +protected: + KissRxBoostTest() { + g_rx_boost = true; + g_rx_boost_set_ok = true; + g_rx_boost_sets = 0; + modem.setRxBoostedGainCallbacks(fakeSetRxBoost, fakeGetRxBoost); + g_poll_modem = &modem; + g_poll_has_packet = false; + g_polls = 0; + modem.setPollRxCallback(fakePollRx); + } +}; + +TEST_F(KissHwControlTest, RxBoostedGainUnsupportedWithoutCallbacks) { + EXPECT_EQ(hw1({HW_CMD_GET_RX_BOOSTED_GAIN}), ERR_UNSUPPORTED); + EXPECT_EQ(hw1({HW_CMD_SET_RX_BOOSTED_GAIN, 1}), ERR_UNSUPPORTED); +} + +TEST_F(KissRxBoostTest, CapabilityAdvertised) { + EXPECT_EQ(hw1({HW_CMD_GET_CAPABILITIES}), (std::vector{0x9B, 0x09, 0x00, 0x00, 0x00})); +} + +TEST_F(KissRxBoostTest, GetReportsCurrentState) { + EXPECT_EQ(hw1({HW_CMD_GET_RX_BOOSTED_GAIN}), (std::vector{0xA1, 0x01})); +} + +TEST_F(KissRxBoostTest, SetRepliesWithEffectiveState) { + EXPECT_EQ(hw1({HW_CMD_SET_RX_BOOSTED_GAIN, 0}), (std::vector{0xA1, 0x00})); + EXPECT_FALSE(g_rx_boost); + EXPECT_EQ(hw1({HW_CMD_SET_RX_BOOSTED_GAIN, 0x7F}), (std::vector{0xA1, 0x01})); + EXPECT_TRUE(g_rx_boost); +} + +TEST_F(KissRxBoostTest, SetFailureRepliesWithUnchangedState) { + g_rx_boost_set_ok = false; + EXPECT_EQ(hw1({HW_CMD_SET_RX_BOOSTED_GAIN, 0}), (std::vector{0xA1, 0x01})); + EXPECT_TRUE(g_rx_boost); +} + +TEST_F(KissRxBoostTest, SetDuringTxIsRejectedWithoutTouchingRadio) { + startTxAndHold(); + serial.takeHardwareFrames(); + EXPECT_EQ(hw1({HW_CMD_SET_RX_BOOSTED_GAIN, 0}), (std::vector{HW_RESP_ERROR, HW_ERR_TX_BUSY})); + EXPECT_EQ(g_rx_boost_sets, 0); + EXPECT_EQ(hw1({HW_CMD_GET_RX_BOOSTED_GAIN}), (std::vector{0xA1, 0x01})); +} + +TEST_F(KissRxBoostTest, SetShortPayloadIsInvalidLength) { + EXPECT_EQ(hw1({HW_CMD_SET_RX_BOOSTED_GAIN}), (std::vector{HW_RESP_ERROR, HW_ERR_INVALID_LENGTH})); + EXPECT_EQ(g_rx_boost_sets, 0); +} + +TEST_F(KissRxBoostTest, CompletedRxPacketIsDeliveredBeforeGainChange) { + g_poll_has_packet = true; + auto frames = hw({HW_CMD_SET_RX_BOOSTED_GAIN, 0}); + EXPECT_EQ(g_polls, 1); + EXPECT_FALSE(g_rx_boost); + ASSERT_EQ(frames.size(), 2U); // RxMeta for the drained packet, then the gain reply + EXPECT_EQ(frames[0][0], HW_RESP_RX_META); + EXPECT_EQ(frames[1], (std::vector{0xA1, 0x00})); +} + +TEST_F(KissRxBoostTest, NoRoomForReplyAfterDrainChangesNothing) { + serial.blocked = true; + g_poll_has_packet = true; // data + meta fill both output slots + serial.pushRx({KISS_FEND, KISS_CMD_SETHARDWARE, HW_CMD_SET_RX_BOOSTED_GAIN, 0, KISS_FEND}); + modem.loop(); + EXPECT_EQ(g_rx_boost_sets, 0); + EXPECT_TRUE(g_rx_boost); + + serial.blocked = false; + for (int i = 0; i < 5; i++) modem.loop(); + auto frames = serial.takeHardwareFrames(); + ASSERT_EQ(frames.size(), 2U); + EXPECT_EQ(frames[0][0], HW_RESP_RX_META); + EXPECT_EQ(frames[1], (std::vector{HW_RESP_ERROR, HW_ERR_TX_BUSY})); +} + +TEST_F(KissRxBoostTest, SetWhileHostOutputBackedUpIsRejected) { + serial.blocked = true; + static constexpr uint8_t PKT[] = {0x01}; + modem.onPacketReceived(0, 0, PKT, sizeof(PKT)); + serial.pushRx({KISS_FEND, KISS_CMD_SETHARDWARE, HW_CMD_SET_RX_BOOSTED_GAIN, 0, KISS_FEND}); + modem.loop(); + EXPECT_EQ(g_polls, 0); + EXPECT_EQ(g_rx_boost_sets, 0); +} + } // namespace From 7652ec5c267a6780adda6767bd260edc1c58653c Mon Sep 17 00:00:00 2001 From: agessaman Date: Wed, 23 Sep 2026 17:31:20 -0700 Subject: [PATCH 06/79] kiss_modem: reach FEM gain through the board's radio.fem CLI commands Boards own their FEM control through handleCommand() ("get/set radio.fem.rxgain|txgain"). Use that instead of a parallel set of FEM virtuals on MainBoard, so any board that implements the commands works in KISS with no extra code. - Remove the six FEM virtuals from MainBoard and the board overrides. - KissModem talks to the board in one adapter. A gain counts as controllable only if "get" replies exactly "> on" or "> off". "set" is checked by reading the state back, never by its reply wording. - SetFemState always replies with the read-back state once the requested bits pass the capability check. - Guard the boards' prefs writes against a NULL store. KISS attaches no prefs, so "set radio.fem.*" would dereference NULL. - Wio Tracker L1 1W TX gain is exposed again, matching its CLI. --- docs/kiss_modem_protocol.md | 2 +- examples/kiss_modem/KissModem.cpp | 92 ++++++++++++------- examples/kiss_modem/KissModem.h | 13 ++- src/MeshCore.h | 8 -- test/mocks/Mesh.h | 7 +- test/test_kiss_modem/test_hw_controls.cpp | 76 +++++++++++---- variants/heltec_t096/T096Board.cpp | 4 +- variants/heltec_t096/T096Board.h | 6 +- .../HeltecTrackerV2Board.cpp | 4 +- .../heltec_tracker_v2/HeltecTrackerV2Board.h | 6 +- variants/heltec_v4/HeltecV4Board.cpp | 4 +- variants/heltec_v4/HeltecV4Board.h | 6 +- variants/heltec_v4_r8/HeltecV4R8Board.cpp | 4 +- variants/heltec_v4_r8/HeltecV4R8Board.h | 5 +- variants/heltec_v4_r8/LoRaFEMControl.h | 2 +- variants/station_g3_esp32/StationG3Board.cpp | 8 +- variants/station_g3_esp32/StationG3Board.h | 10 +- .../wio-tracker-l1-1w/WioTrackerL1Board.cpp | 4 +- 18 files changed, 161 insertions(+), 100 deletions(-) diff --git a/docs/kiss_modem_protocol.md b/docs/kiss_modem_protocol.md index cb7be8b3..a37c4561 100644 --- a/docs/kiss_modem_protocol.md +++ b/docs/kiss_modem_protocol.md @@ -283,7 +283,7 @@ FemState response data: Example: enable RX gain without changing TX gain: apply `0x01`, value `0x01`. -If any bit in the apply mask is not in the board's capability mask (including reserved bits), the modem replies `Unsupported` and changes nothing. On success, SetFemState replies with the FemState response carrying the new state. A SetFemState received while a packet is on air (before its TxDone is queued) is held and applied after TxDone, so its FemState response follows TxDone. While a SetFemState is held or its response is still waiting for output space, GetFemState responses are queued behind it in order, and a further SetFemState returns `TxBusy`. Capabilities come from the board, so a board with a fixed, board-managed FEM (for example RAK3401) reports none. +If any bit in the apply mask is not in the board's capability mask (including reserved bits), the modem replies `Unsupported` and changes nothing. Otherwise SetFemState replies with the FemState response carrying the state read back from the board; if a bit differs from the request, that change did not take effect. A SetFemState received while a packet is on air (before its TxDone is queued) is held and applied after TxDone, so its FemState response follows TxDone. While a SetFemState is held or its response is still waiting for output space, GetFemState responses are queued behind it in order, and a further SetFemState returns `TxBusy`. Capabilities come from the board's own `get/set radio.fem.rxgain` and `radio.fem.txgain` CLI commands (see [cli_commands.md](./cli_commands.md)): a gain is controllable when the board answers `get` with `> on` or `> off`. Any board that implements those commands is supported without KISS changes, and a board with a fixed, board-managed FEM (for example RAK3401) reports none. Changes made over KISS are not saved to the board's preferences. The setting is not persisted; the board's power-on default applies after reboot. diff --git a/examples/kiss_modem/KissModem.cpp b/examples/kiss_modem/KissModem.cpp index 221c40b1..a6950bff 100644 --- a/examples/kiss_modem/KissModem.cpp +++ b/examples/kiss_modem/KissModem.cpp @@ -1,5 +1,6 @@ #include "KissModem.h" #include +#include KissModem::KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& rng, mesh::Radio& radio, mesh::MainBoard& board, SensorManager& sensors) @@ -31,7 +32,6 @@ KissModem::KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& r _fem_deferred_apply = 0; _fem_deferred_value = 0; _fem_reply_pending = false; - _fem_reply_ok = false; _fem_deferred_gets = 0; resetOutputQueue(); } @@ -785,8 +785,10 @@ void KissModem::handleGetSignalReport() { void KissModem::handleGetCapabilities() { uint32_t caps = HW_CAP_AGC_RESET; - if (_board.canControlLoRaFemLna()) caps |= HW_CAP_FEM_RX_GAIN; - if (_board.canControlLoRaFemPaGain()) caps |= HW_CAP_FEM_TX_GAIN; + uint8_t fem_caps, fem_values; + readFemState(&fem_caps, &fem_values); + if (fem_caps & HW_FEM_RX_GAIN) caps |= HW_CAP_FEM_RX_GAIN; + if (fem_caps & HW_FEM_TX_GAIN) caps |= HW_CAP_FEM_TX_GAIN; if (_setRxBoostedGainCallback && _getRxBoostedGainCallback) caps |= HW_CAP_RX_BOOSTED_GAIN; uint8_t buf[4] = { (uint8_t)caps, (uint8_t)(caps >> 8), (uint8_t)(caps >> 16), (uint8_t)(caps >> 24) }; writeHardwareFrame(HW_RESP(HW_CMD_GET_CAPABILITIES), buf, 4); @@ -812,55 +814,81 @@ void KissModem::handleGetAgcResetInterval() { writeHardwareFrame(HW_RESP(HW_CMD_GET_AGC_RESET_INTERVAL), buf, 2); } -uint8_t KissModem::femCapabilityMask() const { - uint8_t mask = 0; - if (_board.canControlLoRaFemLna()) mask |= HW_FEM_RX_GAIN; - if (_board.canControlLoRaFemPaGain()) mask |= HW_FEM_TX_GAIN; - return mask; +// FEM gain is reached through the board's own "radio.fem.*" CLI commands, the same ones users run. +static const char* femGainName(uint8_t bit) { + return bit == HW_FEM_RX_GAIN ? "rxgain" : "txgain"; } -uint8_t KissModem::femValueMask() const { - uint8_t mask = 0; - if (_board.canControlLoRaFemLna() && _board.isLoRaFemLnaEnabled()) mask |= HW_FEM_RX_GAIN; - if (_board.canControlLoRaFemPaGain() && _board.isLoRaFemPaGainEnabled()) mask |= HW_FEM_TX_GAIN; - return mask; -} - -bool KissModem::queueFemReply(bool ok, bool mark_busy_error) { - if (!ok) { - const uint8_t err = HW_ERR_UNSUPPORTED; - return queueHardwareFrame(HW_RESP_ERROR, &err, 1, mark_busy_error); +// Anything but an exact "> on" / "> off" (not handled, "Error: ...", unexpected text) means unsupported. +bool KissModem::queryFemGain(uint8_t bit, bool* enabled) { + char cmd[32]; + char reply[KISS_BOARD_REPLY_SIZE] = { 0 }; + snprintf(cmd, sizeof(cmd), "get radio.fem.%s", femGainName(bit)); + if (!_board.handleCommand(cmd, 0, reply)) return false; + if (strcmp(reply, "> on") == 0) { + *enabled = true; + } else if (strcmp(reply, "> off") == 0) { + *enabled = false; + } else { + return false; } - uint8_t buf[2] = { femCapabilityMask(), femValueMask() }; + return true; +} + +// Success is judged by reading the state back, not by the wording of the set reply. +bool KissModem::setFemGain(uint8_t bit, bool enable) { + char cmd[32]; + char reply[KISS_BOARD_REPLY_SIZE] = { 0 }; + snprintf(cmd, sizeof(cmd), "set radio.fem.%s %s", femGainName(bit), enable ? "on" : "off"); + _board.handleCommand(cmd, 0, reply); + bool now; + return queryFemGain(bit, &now) && now == enable; +} + +void KissModem::readFemState(uint8_t* caps, uint8_t* values) { + *caps = 0; + *values = 0; + const uint8_t bits[] = { HW_FEM_RX_GAIN, HW_FEM_TX_GAIN }; + for (uint8_t bit : bits) { + bool enabled; + if (queryFemGain(bit, &enabled)) { + *caps |= bit; + if (enabled) *values |= bit; + } + } +} + +bool KissModem::queueFemReply(bool mark_busy_error) { + uint8_t buf[2]; + readFemState(&buf[0], &buf[1]); return queueHardwareFrame(HW_RESP(HW_CMD_GET_FEM_STATE), buf, 2, mark_busy_error); } -bool KissModem::applyFemState(uint8_t apply_mask, uint8_t value_mask) { - bool ok = true; +// The reply always carries the read-back state, so a bit that failed to apply shows its real value. +void KissModem::applyFemState(uint8_t apply_mask, uint8_t value_mask) { if (apply_mask & HW_FEM_RX_GAIN) { - ok &= _board.setLoRaFemLnaEnabled((value_mask & HW_FEM_RX_GAIN) != 0); + setFemGain(HW_FEM_RX_GAIN, (value_mask & HW_FEM_RX_GAIN) != 0); } if (apply_mask & HW_FEM_TX_GAIN) { - ok &= _board.setLoRaFemPaGainEnabled((value_mask & HW_FEM_TX_GAIN) != 0); + setFemGain(HW_FEM_TX_GAIN, (value_mask & HW_FEM_TX_GAIN) != 0); } - return ok; } void KissModem::processDeferredFem() { // wait for TxDone to be queued so the host sees the TX result before the FEM change if (_fem_deferred && _tx_state != TX_SENDING && _tx_state != TX_DONE_PENDING) { - _fem_reply_ok = applyFemState(_fem_deferred_apply, _fem_deferred_value); + applyFemState(_fem_deferred_apply, _fem_deferred_value); _fem_deferred = false; _fem_reply_pending = true; } if (_fem_deferred) return; // replies are retained until queued, and GetFemState replies stay behind the Set reply if (_fem_reply_pending) { - if (!queueFemReply(_fem_reply_ok, false)) return; + if (!queueFemReply(false)) return; _fem_reply_pending = false; } while (_fem_deferred_gets > 0) { - if (!queueFemReply(true, false)) return; + if (!queueFemReply(false)) return; _fem_deferred_gets--; } } @@ -873,7 +901,9 @@ void KissModem::handleSetFemState(const uint8_t* data, uint16_t len) { uint8_t apply_mask = data[0]; uint8_t value_mask = data[1]; // validate every requested bit before touching hardware so a request is all-or-nothing - if (apply_mask & ~femCapabilityMask()) { + uint8_t fem_caps, fem_values; + readFemState(&fem_caps, &fem_values); + if (apply_mask & ~fem_caps) { writeHardwareError(HW_ERR_UNSUPPORTED); return; } @@ -888,7 +918,7 @@ void KissModem::handleSetFemState(const uint8_t* data, uint16_t len) { _fem_deferred_value = value_mask; return; } - _fem_reply_ok = applyFemState(apply_mask, value_mask); + applyFemState(apply_mask, value_mask); _fem_reply_pending = true; processDeferredFem(); } @@ -902,7 +932,7 @@ void KissModem::handleGetFemState() { _fem_deferred_gets++; return; } - queueFemReply(true, true); + queueFemReply(true); } void KissModem::handleSetRxBoostedGain(const uint8_t* data, uint16_t len) { diff --git a/examples/kiss_modem/KissModem.h b/examples/kiss_modem/KissModem.h index ffe89191..572999c4 100644 --- a/examples/kiss_modem/KissModem.h +++ b/examples/kiss_modem/KissModem.h @@ -100,6 +100,9 @@ #define HW_FEM_RX_GAIN (1 << 0) #define HW_FEM_TX_GAIN (1 << 1) +/* Matches the CLI reply buffer boards write into from handleCommand() */ +#define KISS_BOARD_REPLY_SIZE 160 + #define KISS_AGC_RESET_DEFAULT_SEC 30 #define KISS_AGC_RESET_MAX_SEC 1020 #define KISS_AGC_RESET_STEP_SEC 4 @@ -173,7 +176,6 @@ class KissModem { uint8_t _fem_deferred_apply; uint8_t _fem_deferred_value; bool _fem_reply_pending; - bool _fem_reply_ok; uint8_t _fem_deferred_gets; uint8_t _tx_frame_buf[KISS_TX_FRAME_QUEUE_DEPTH][KISS_MAX_ENCODED_FRAME_SIZE]; uint16_t _tx_frame_len[KISS_TX_FRAME_QUEUE_DEPTH]; @@ -202,10 +204,11 @@ class KissModem { void handleHardwareCommand(uint8_t sub_cmd, const uint8_t* data, uint16_t len); void processTx(); void maybeResetAgc(); - uint8_t femCapabilityMask() const; - uint8_t femValueMask() const; - bool queueFemReply(bool ok, bool mark_busy_error); - bool applyFemState(uint8_t apply_mask, uint8_t value_mask); + bool queryFemGain(uint8_t bit, bool* enabled); + bool setFemGain(uint8_t bit, bool enable); + void readFemState(uint8_t* caps, uint8_t* values); + bool queueFemReply(bool mark_busy_error); + void applyFemState(uint8_t apply_mask, uint8_t value_mask); bool isFemReplyQueued() const { return _fem_deferred || _fem_reply_pending || _fem_deferred_gets > 0; } void processDeferredFem(); diff --git a/src/MeshCore.h b/src/MeshCore.h index 5fdb064c..2a3582de 100644 --- a/src/MeshCore.h +++ b/src/MeshCore.h @@ -77,14 +77,6 @@ public: virtual bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { return false; } - // External LoRa front-end (FEM) gain control. Boards without a controllable FEM keep these defaults. - virtual bool canControlLoRaFemLna() const { return false; } - virtual bool setLoRaFemLnaEnabled(bool enable) { return false; } - virtual bool isLoRaFemLnaEnabled() const { return false; } - virtual bool canControlLoRaFemPaGain() const { return false; } - virtual bool setLoRaFemPaGainEnabled(bool enable) { return false; } - virtual bool isLoRaFemPaGainEnabled() const { return false; } - // Called from the example main loops. Lets a board feed its watchdog and // run periodic housekeeping. Default no-op. virtual void loop() { /* no op */ } diff --git a/test/mocks/Mesh.h b/test/mocks/Mesh.h index 29a29b82..33c437f2 100644 --- a/test/mocks/Mesh.h +++ b/test/mocks/Mesh.h @@ -23,12 +23,7 @@ public: virtual float getMCUTemperature() { return 25.0f; } virtual const char* getManufacturerName() { return "mock-board"; } virtual void reboot() {} - virtual bool canControlLoRaFemLna() const { return false; } - virtual bool setLoRaFemLnaEnabled(bool) { return false; } - virtual bool isLoRaFemLnaEnabled() const { return false; } - virtual bool canControlLoRaFemPaGain() const { return false; } - virtual bool setLoRaFemPaGainEnabled(bool) { return false; } - virtual bool isLoRaFemPaGainEnabled() const { return false; } + virtual bool handleCommand(const char*, uint32_t, char*) { return false; } }; } diff --git a/test/test_kiss_modem/test_hw_controls.cpp b/test/test_kiss_modem/test_hw_controls.cpp index 37b1b929..16ef50df 100644 --- a/test/test_kiss_modem/test_hw_controls.cpp +++ b/test/test_kiss_modem/test_hw_controls.cpp @@ -72,31 +72,50 @@ public: int agc_resets = 0; }; +// Implements FEM through the "radio.fem.*" CLI text, worded like the Heltec / Station G3 boards. class FemBoard : public mesh::MainBoard { public: const char* getManufacturerName() override { return "fem-board"; } - bool canControlLoRaFemLna() const override { return has_lna; } - bool setLoRaFemLnaEnabled(bool enable) override { - if (!has_lna) return false; - lna = enable; - lna_sets++; - return true; + bool handleCommand(const char* command, uint32_t, char* reply) override { + commands++; + if (handleGain(command, reply, "rxgain", has_lna, lna, lna_sets, lna_sticks)) return true; + if (handleGain(command, reply, "txgain", has_pa, pa, pa_sets, pa_sticks)) return true; + return false; } - bool isLoRaFemLnaEnabled() const override { return lna; } - - bool canControlLoRaFemPaGain() const override { return has_pa; } - bool setLoRaFemPaGainEnabled(bool enable) override { - if (!has_pa) return false; - pa = enable; - pa_sets++; - return true; - } - bool isLoRaFemPaGainEnabled() const override { return pa; } bool has_lna = false, has_pa = false; bool lna = false, pa = false; int lna_sets = 0, pa_sets = 0; + bool lna_sticks = false, pa_sticks = false; // set reports OK but the state does not change + bool unhandled = false; // board does not implement radio.fem.* at all + const char* odd_get_reply = nullptr; // unexpected get wording + int commands = 0; + +private: + bool handleGain(const char* command, char* reply, const char* name, bool has, bool& state, int& sets, bool sticks) { + if (unhandled) return false; + char get_cmd[32], set_cmd[32]; + snprintf(get_cmd, sizeof(get_cmd), "get radio.fem.%s", name); + snprintf(set_cmd, sizeof(set_cmd), "set radio.fem.%s ", name); + if (strcmp(command, get_cmd) == 0) { + if (!has) strcpy(reply, "Error: unsupported"); + else if (odd_get_reply) strcpy(reply, odd_get_reply); + else sprintf(reply, "> %s", state ? "on" : "off"); + return true; + } + if (strncmp(command, set_cmd, strlen(set_cmd)) == 0) { + if (!has) { + strcpy(reply, "Error: unsupported"); + } else { + sets++; + if (!sticks) state = strcmp(command + strlen(set_cmd), "on") == 0; + strcpy(reply, "OK - LoRa FEM gain changed"); + } + return true; + } + return false; + } }; class NoSensors : public SensorManager { @@ -276,6 +295,31 @@ TEST_F(KissHwControlTest, FemUnknownBitsAreUnsupported) { EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, 0x04, 0x04}), ERR_UNSUPPORTED); } +TEST_F(KissHwControlTest, FemUnhandledCommandsMeanUnsupported) { + board.has_lna = board.has_pa = true; + board.unhandled = true; + EXPECT_EQ(hw1({HW_CMD_GET_FEM_STATE}), (std::vector{0x9F, 0x00, 0x00})); + EXPECT_EQ(hw1({HW_CMD_GET_CAPABILITIES}), (std::vector{0x9B, 0x01, 0x00, 0x00, 0x00})); + EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}), ERR_UNSUPPORTED); +} + +TEST_F(KissHwControlTest, FemUnexpectedGetWordingMeansUnsupported) { + board.has_lna = true; + board.odd_get_reply = "> enabled"; + EXPECT_EQ(hw1({HW_CMD_GET_FEM_STATE}), (std::vector{0x9F, 0x00, 0x00})); + EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}), ERR_UNSUPPORTED); + EXPECT_EQ(board.lna_sets, 0); +} + +TEST_F(KissHwControlTest, FemSetThatDoesNotTakeRepliesWithReadBackState) { + board.has_lna = board.has_pa = true; + board.lna_sticks = true; // board says OK but LNA stays off + EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN | HW_FEM_TX_GAIN, HW_FEM_RX_GAIN | HW_FEM_TX_GAIN}), + (std::vector{0x9F, 0x03, 0x02})); + EXPECT_FALSE(board.lna); + EXPECT_TRUE(board.pa); +} + TEST_F(KissHwControlTest, FemShortPayloadIsInvalidLength) { EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN}), (std::vector{HW_RESP_ERROR, HW_ERR_INVALID_LENGTH})); } diff --git a/variants/heltec_t096/T096Board.cpp b/variants/heltec_t096/T096Board.cpp index ea26d2cc..47ad8d96 100644 --- a/variants/heltec_t096/T096Board.cpp +++ b/variants/heltec_t096/T096Board.cpp @@ -158,14 +158,14 @@ bool T096Board::handleCommand(const char* command, uint32_t sender_timestamp, ch strcpy(reply, "Error: unsupported"); } else if (memcmp(&command[21], "on", 2) == 0) { if (setLoRaFemLnaEnabled(true)) { - _prefs->setByKey("fem_rxgain", "1"); + if (_prefs) _prefs->setByKey("fem_rxgain", "1"); strcpy(reply, "OK - LoRa FEM RX gain on"); } else { strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); } } else if (memcmp(&command[21], "off", 3) == 0) { if (setLoRaFemLnaEnabled(false)) { - _prefs->setByKey("fem_rxgain", "0"); + if (_prefs) _prefs->setByKey("fem_rxgain", "0"); strcpy(reply, "OK - LoRa FEM RX gain off"); } else { strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); diff --git a/variants/heltec_t096/T096Board.h b/variants/heltec_t096/T096Board.h index 66fa5047..e926c8a6 100644 --- a/variants/heltec_t096/T096Board.h +++ b/variants/heltec_t096/T096Board.h @@ -16,6 +16,9 @@ protected: #endif void variant_shutdown(); + bool setLoRaFemLnaEnabled(bool enable); + bool isLoRaFemLnaEnabled() const; + public: RefCountedDigitalPin periph_power; LoRaFEMControl loRaFEMControl; @@ -24,9 +27,6 @@ public: void begin(); void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; - bool canControlLoRaFemLna() const override { return loRaFEMControl.isLnaCanControl(); } - bool setLoRaFemLnaEnabled(bool enable) override; - bool isLoRaFemLnaEnabled() const override; void onBeforeTransmit(void) override; void onAfterTransmit(void) override; diff --git a/variants/heltec_tracker_v2/HeltecTrackerV2Board.cpp b/variants/heltec_tracker_v2/HeltecTrackerV2Board.cpp index 753824a0..95d56699 100644 --- a/variants/heltec_tracker_v2/HeltecTrackerV2Board.cpp +++ b/variants/heltec_tracker_v2/HeltecTrackerV2Board.cpp @@ -99,14 +99,14 @@ bool HeltecTrackerV2Board::handleCommand(const char* command, uint32_t sender_ti strcpy(reply, "Error: unsupported"); } else if (memcmp(&command[21], "on", 2) == 0) { if (setLoRaFemLnaEnabled(true)) { - _prefs->setByKey("fem_rxgain", "1"); + if (_prefs) _prefs->setByKey("fem_rxgain", "1"); strcpy(reply, "OK - LoRa FEM RX gain on"); } else { strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); } } else if (memcmp(&command[21], "off", 3) == 0) { if (setLoRaFemLnaEnabled(false)) { - _prefs->setByKey("fem_rxgain", "0"); + if (_prefs) _prefs->setByKey("fem_rxgain", "0"); strcpy(reply, "OK - LoRa FEM RX gain off"); } else { strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); diff --git a/variants/heltec_tracker_v2/HeltecTrackerV2Board.h b/variants/heltec_tracker_v2/HeltecTrackerV2Board.h index 34454cac..5fed2b65 100644 --- a/variants/heltec_tracker_v2/HeltecTrackerV2Board.h +++ b/variants/heltec_tracker_v2/HeltecTrackerV2Board.h @@ -8,6 +8,9 @@ class HeltecTrackerV2Board : public ESP32Board { KeyValueStore* _prefs = NULL; + bool setLoRaFemLnaEnabled(bool enable); + bool isLoRaFemLnaEnabled() const; + public: RefCountedDigitalPin periph_power; LoRaFEMControl loRaFEMControl; @@ -17,9 +20,6 @@ public: void begin(); void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; - bool canControlLoRaFemLna() const override { return loRaFEMControl.isLnaCanControl(); } - bool setLoRaFemLnaEnabled(bool enable) override; - bool isLoRaFemLnaEnabled() const override; void onBeforeTransmit(void) override; void onAfterTransmit(void) override; diff --git a/variants/heltec_v4/HeltecV4Board.cpp b/variants/heltec_v4/HeltecV4Board.cpp index 794257d7..2d941bd8 100644 --- a/variants/heltec_v4/HeltecV4Board.cpp +++ b/variants/heltec_v4/HeltecV4Board.cpp @@ -100,14 +100,14 @@ bool HeltecV4Board::handleCommand(const char* command, uint32_t sender_timestamp strcpy(reply, "Error: unsupported"); } else if (memcmp(&command[21], "on", 2) == 0) { if (setLoRaFemLnaEnabled(true)) { - _prefs->setByKey("fem_rxgain", "1"); + if (_prefs) _prefs->setByKey("fem_rxgain", "1"); strcpy(reply, "OK - LoRa FEM RX gain on"); } else { strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); } } else if (memcmp(&command[21], "off", 3) == 0) { if (setLoRaFemLnaEnabled(false)) { - _prefs->setByKey("fem_rxgain", "0"); + if (_prefs) _prefs->setByKey("fem_rxgain", "0"); strcpy(reply, "OK - LoRa FEM RX gain off"); } else { strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); diff --git a/variants/heltec_v4/HeltecV4Board.h b/variants/heltec_v4/HeltecV4Board.h index bd3bdb25..79a690e8 100644 --- a/variants/heltec_v4/HeltecV4Board.h +++ b/variants/heltec_v4/HeltecV4Board.h @@ -12,6 +12,9 @@ class HeltecV4Board : public ESP32Board { KeyValueStore* _prefs = NULL; + bool setLoRaFemLnaEnabled(bool enable); + bool isLoRaFemLnaEnabled() const; + protected: float adc_mult = ADC_MULTIPLIER; @@ -23,9 +26,6 @@ public: void begin(); void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; - bool canControlLoRaFemLna() const override { return loRaFEMControl.isLnaCanControl(); } - bool setLoRaFemLnaEnabled(bool enable) override; - bool isLoRaFemLnaEnabled() const override; void onBeforeTransmit(void) override; void onAfterTransmit(void) override; diff --git a/variants/heltec_v4_r8/HeltecV4R8Board.cpp b/variants/heltec_v4_r8/HeltecV4R8Board.cpp index ea2cfbed..d4860ab4 100644 --- a/variants/heltec_v4_r8/HeltecV4R8Board.cpp +++ b/variants/heltec_v4_r8/HeltecV4R8Board.cpp @@ -122,14 +122,14 @@ bool HeltecV4R8Board::handleCommand(const char* command, uint32_t sender_timesta strcpy(reply, "Error: unsupported"); } else if (memcmp(&command[21], "on", 2) == 0) { if (setLoRaFemLnaEnabled(true)) { - _prefs->setByKey("fem_rxgain", "1"); + if (_prefs) _prefs->setByKey("fem_rxgain", "1"); strcpy(reply, "OK - LoRa FEM RX gain on"); } else { strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); } } else if (memcmp(&command[21], "off", 3) == 0) { if (setLoRaFemLnaEnabled(false)) { - _prefs->setByKey("fem_rxgain", "0"); + if (_prefs) _prefs->setByKey("fem_rxgain", "0"); strcpy(reply, "OK - LoRa FEM RX gain off"); } else { strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); diff --git a/variants/heltec_v4_r8/HeltecV4R8Board.h b/variants/heltec_v4_r8/HeltecV4R8Board.h index c34ee449..7ab29f96 100644 --- a/variants/heltec_v4_r8/HeltecV4R8Board.h +++ b/variants/heltec_v4_r8/HeltecV4R8Board.h @@ -13,6 +13,8 @@ class HeltecV4R8Board : public ESP32Board { KeyValueStore* _prefs = NULL; + bool setLoRaFemLnaEnabled(bool enable); + bool isLoRaFemLnaEnabled() const; protected: float adc_mult = ADC_MULTIPLIER; @@ -25,9 +27,6 @@ public: void begin(); void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; - bool canControlLoRaFemLna() const override { return loRaFEMControl.isLnaCanControl(); } - bool setLoRaFemLnaEnabled(bool enable) override; - bool isLoRaFemLnaEnabled() const override; void onBeforeTransmit(void) override; void onAfterTransmit(void) override; diff --git a/variants/heltec_v4_r8/LoRaFEMControl.h b/variants/heltec_v4_r8/LoRaFEMControl.h index 52d7a0f8..4b74c2e2 100644 --- a/variants/heltec_v4_r8/LoRaFEMControl.h +++ b/variants/heltec_v4_r8/LoRaFEMControl.h @@ -15,7 +15,7 @@ public: void setRxModeEnable(void); void setRxModeEnableWhenMCUSleep(void); void setLNAEnable(bool enabled); - bool isLnaCanControl(void) const { return true; } + bool isLnaCanControl(void) { return true; } void setLnaCanControl(bool can_control) { } bool isLNAEnabled(void) const { return lna_enabled; } LoRaFEMType getFEMType(void) const { return KCT8103L_PA; } diff --git a/variants/station_g3_esp32/StationG3Board.cpp b/variants/station_g3_esp32/StationG3Board.cpp index 277c2b8b..9e8ef112 100644 --- a/variants/station_g3_esp32/StationG3Board.cpp +++ b/variants/station_g3_esp32/StationG3Board.cpp @@ -65,14 +65,14 @@ bool StationG3Board::handleCommand(const char* command, uint32_t sender_timestam strcpy(reply, "Error: unsupported"); } else if (memcmp(&command[21], "on", 2) == 0) { if (setLoRaFemLnaEnabled(true)) { - _prefs->setByKey("fem_rxgain", "1"); + if (_prefs) _prefs->setByKey("fem_rxgain", "1"); strcpy(reply, "OK - LoRa FEM RX gain on"); } else { strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); } } else if (memcmp(&command[21], "off", 3) == 0) { if (setLoRaFemLnaEnabled(false)) { - _prefs->setByKey("fem_rxgain", "0"); + if (_prefs) _prefs->setByKey("fem_rxgain", "0"); strcpy(reply, "OK - LoRa FEM RX gain off"); } else { strcpy(reply, "Error: failed to apply LoRa FEM RX gain"); @@ -96,14 +96,14 @@ bool StationG3Board::handleCommand(const char* command, uint32_t sender_timestam strcpy(reply, "Error: unsupported"); } else if (memcmp(&command[21], "on", 2) == 0) { if (setLoRaFemPaGainEnabled(true)) { - _prefs->setByKey("fem_txgain", "1"); + if (_prefs) _prefs->setByKey("fem_txgain", "1"); strcpy(reply, "OK - LoRa FEM TX gain on"); } else { strcpy(reply, "Error: failed to apply LoRa FEM TX gain"); } } else if (memcmp(&command[21], "off", 3) == 0) { if (setLoRaFemPaGainEnabled(false)) { - _prefs->setByKey("fem_txgain", "0"); + if (_prefs) _prefs->setByKey("fem_txgain", "0"); strcpy(reply, "OK - LoRa FEM TX gain off"); } else { strcpy(reply, "Error: failed to apply LoRa FEM TX gain"); diff --git a/variants/station_g3_esp32/StationG3Board.h b/variants/station_g3_esp32/StationG3Board.h index f8cb75cb..b4c5838c 100644 --- a/variants/station_g3_esp32/StationG3Board.h +++ b/variants/station_g3_esp32/StationG3Board.h @@ -8,6 +8,10 @@ class StationG3Board : public ESP32Board { KeyValueStore* _prefs = NULL; + bool setLoRaFemLnaEnabled(bool enable); + bool isLoRaFemLnaEnabled() const; + bool setLoRaFemPaGainEnabled(bool enable); + bool isLoRaFemPaGainEnabled() const; public: LoRaFEMControl loRaFEMControl; @@ -30,12 +34,6 @@ public: void attachDynamicPrefs(KeyValueStore* prefs); bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; - bool canControlLoRaFemLna() const override { return loRaFEMControl.canControlLNA(); } - bool setLoRaFemLnaEnabled(bool enable) override; - bool isLoRaFemLnaEnabled() const override; - bool canControlLoRaFemPaGain() const override { return loRaFEMControl.canControlPAGain(); } - bool setLoRaFemPaGainEnabled(bool enable) override; - bool isLoRaFemPaGainEnabled() const override; void setPrimaryLNAEnable(bool enabled) { loRaFEMControl.setLNAEnable(enabled); diff --git a/variants/wio-tracker-l1-1w/WioTrackerL1Board.cpp b/variants/wio-tracker-l1-1w/WioTrackerL1Board.cpp index c6dbdbf5..69b33f75 100644 --- a/variants/wio-tracker-l1-1w/WioTrackerL1Board.cpp +++ b/variants/wio-tracker-l1-1w/WioTrackerL1Board.cpp @@ -65,14 +65,14 @@ bool WioTrackerL1Board::handleCommand(const char* command, uint32_t sender_times if (memcmp(command, "set radio.fem.txgain ", 21) == 0) { if (memcmp(&command[21], "on", 2) == 0) { if (setLoRaFemPaGainEnabled(true)) { - _prefs->setByKey("fem_txgain", "1"); + if (_prefs) _prefs->setByKey("fem_txgain", "1"); strcpy(reply, "OK - LoRa FEM TX gain on"); } else { strcpy(reply, "Error: failed to apply LoRa FEM TX gain"); } } else if (memcmp(&command[21], "off", 3) == 0) { if (setLoRaFemPaGainEnabled(false)) { - _prefs->setByKey("fem_txgain", "0"); + if (_prefs) _prefs->setByKey("fem_txgain", "0"); strcpy(reply, "OK - LoRa FEM TX gain off"); } else { strcpy(reply, "Error: failed to apply LoRa FEM TX gain"); From 09ee2e1223eb4478e7421077f08fc218d9461fa2 Mon Sep 17 00:00:00 2001 From: agessaman Date: Wed, 23 Sep 2026 17:41:14 -0700 Subject: [PATCH 07/79] kiss_modem: answer FEM requests strictly in arrival order A second SetFemState sent while the first was held for a TX got an immediate TxBusy, which reached the host before the first request's reply. With no request IDs, the host could not tell which Set failed. FEM requests now go through a small ordered queue (Set, Get and their error replies). Sets still wait for TxDone to be queued and apply once. Each reply is kept until it can be queued. Capability checks happen in order at processing time. Only an overflow (more than 4 waiting) replies TxBusy immediately. --- docs/kiss_modem_protocol.md | 2 +- examples/kiss_modem/KissModem.cpp | 107 ++++++++++------------ examples/kiss_modem/KissModem.h | 30 ++++-- test/test_kiss_modem/test_hw_controls.cpp | 50 +++++++++- 4 files changed, 117 insertions(+), 72 deletions(-) diff --git a/docs/kiss_modem_protocol.md b/docs/kiss_modem_protocol.md index a37c4561..5eb09738 100644 --- a/docs/kiss_modem_protocol.md +++ b/docs/kiss_modem_protocol.md @@ -283,7 +283,7 @@ FemState response data: Example: enable RX gain without changing TX gain: apply `0x01`, value `0x01`. -If any bit in the apply mask is not in the board's capability mask (including reserved bits), the modem replies `Unsupported` and changes nothing. Otherwise SetFemState replies with the FemState response carrying the state read back from the board; if a bit differs from the request, that change did not take effect. A SetFemState received while a packet is on air (before its TxDone is queued) is held and applied after TxDone, so its FemState response follows TxDone. While a SetFemState is held or its response is still waiting for output space, GetFemState responses are queued behind it in order, and a further SetFemState returns `TxBusy`. Capabilities come from the board's own `get/set radio.fem.rxgain` and `radio.fem.txgain` CLI commands (see [cli_commands.md](./cli_commands.md)): a gain is controllable when the board answers `get` with `> on` or `> off`. Any board that implements those commands is supported without KISS changes, and a board with a fixed, board-managed FEM (for example RAK3401) reports none. Changes made over KISS are not saved to the board's preferences. +If any bit in the apply mask is not in the board's capability mask (including reserved bits), the modem replies `Unsupported` and changes nothing. Otherwise SetFemState replies with the FemState response carrying the state read back from the board; if a bit differs from the request, that change did not take effect. SetFemState and GetFemState requests, including their error replies, are answered strictly in the order received. A SetFemState received while a packet is on air (before its TxDone is queued) is held and applied after TxDone, so its reply follows TxDone, and FEM requests that arrive after it wait behind it. Up to 4 FEM requests can wait; beyond that the modem replies `TxBusy` immediately. Capabilities come from the board's own `get/set radio.fem.rxgain` and `radio.fem.txgain` CLI commands (see [cli_commands.md](./cli_commands.md)): a gain is controllable when the board answers `get` with `> on` or `> off`. Any board that implements those commands is supported without KISS changes, and a board with a fixed, board-managed FEM (for example RAK3401) reports none. Changes made over KISS are not saved to the board's preferences. The setting is not persisted; the board's power-on default applies after reboot. diff --git a/examples/kiss_modem/KissModem.cpp b/examples/kiss_modem/KissModem.cpp index a6950bff..4d9cdbdb 100644 --- a/examples/kiss_modem/KissModem.cpp +++ b/examples/kiss_modem/KissModem.cpp @@ -28,11 +28,8 @@ KissModem::KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& r _signal_report_enabled = true; _agc_reset_interval_sec = KISS_AGC_RESET_DEFAULT_SEC; _next_agc_reset_ms = 0; - _fem_deferred = false; - _fem_deferred_apply = 0; - _fem_deferred_value = 0; - _fem_reply_pending = false; - _fem_deferred_gets = 0; + _fem_op_head = 0; + _fem_op_count = 0; resetOutputQueue(); } @@ -42,9 +39,8 @@ void KissModem::begin() { _rx_active = false; _has_pending_tx = false; _tx_state = TX_IDLE; - _fem_deferred = false; - _fem_reply_pending = false; - _fem_deferred_gets = 0; + _fem_op_head = 0; + _fem_op_count = 0; _next_agc_reset_ms = millis() + (uint32_t)_agc_reset_interval_sec * 1000; resetOutputQueue(); } @@ -255,7 +251,7 @@ void KissModem::loop() { } processTx(); - processDeferredFem(); + processFemOps(); maybeResetAgc(); tryFlushFrames(); queuePendingBusyError(); @@ -858,10 +854,10 @@ void KissModem::readFemState(uint8_t* caps, uint8_t* values) { } } -bool KissModem::queueFemReply(bool mark_busy_error) { +bool KissModem::queueFemReply() { uint8_t buf[2]; readFemState(&buf[0], &buf[1]); - return queueHardwareFrame(HW_RESP(HW_CMD_GET_FEM_STATE), buf, 2, mark_busy_error); + return queueHardwareFrame(HW_RESP(HW_CMD_GET_FEM_STATE), buf, 2, false); } // The reply always carries the read-back state, so a bit that failed to apply shows its real value. @@ -874,65 +870,58 @@ void KissModem::applyFemState(uint8_t apply_mask, uint8_t value_mask) { } } -void KissModem::processDeferredFem() { - // wait for TxDone to be queued so the host sees the TX result before the FEM change - if (_fem_deferred && _tx_state != TX_SENDING && _tx_state != TX_DONE_PENDING) { - applyFemState(_fem_deferred_apply, _fem_deferred_value); - _fem_deferred = false; - _fem_reply_pending = true; +void KissModem::enqueueFemOp(FemOpKind kind, uint8_t apply_mask, uint8_t value_mask) { + if (_fem_op_count >= KISS_FEM_OP_QUEUE_DEPTH) { + writeHardwareError(HW_ERR_TX_BUSY); // too many FEM requests waiting + return; } - if (_fem_deferred) return; - // replies are retained until queued, and GetFemState replies stay behind the Set reply - if (_fem_reply_pending) { - if (!queueFemReply(false)) return; - _fem_reply_pending = false; - } - while (_fem_deferred_gets > 0) { - if (!queueFemReply(false)) return; - _fem_deferred_gets--; + FemOp& op = _fem_ops[(_fem_op_head + _fem_op_count) % KISS_FEM_OP_QUEUE_DEPTH]; + op.kind = kind; + op.apply_mask = apply_mask; + op.value_mask = value_mask; + op.applied = false; + _fem_op_count++; + processFemOps(); +} + +// Every FEM reply goes out in request order. A Set waits until TxDone is queued, since board +// setters drive FEM pins directly; each reply is retained until there is room to queue it. +void KissModem::processFemOps() { + while (_fem_op_count > 0) { + FemOp& op = _fem_ops[_fem_op_head]; + if (op.kind == FEM_OP_ERROR) { + if (!queueHardwareFrame(HW_RESP_ERROR, &op.value_mask, 1, false)) return; + } else { + if (op.kind == FEM_OP_SET && !op.applied) { + if (_tx_state == TX_SENDING || _tx_state == TX_DONE_PENDING) return; + uint8_t caps, values; + readFemState(&caps, &values); + if (op.apply_mask & ~caps) { + // all-or-nothing: any bit the board cannot control rejects the whole request + op.kind = FEM_OP_ERROR; + op.value_mask = HW_ERR_UNSUPPORTED; + continue; + } + applyFemState(op.apply_mask, op.value_mask); + op.applied = true; + } + if (!queueFemReply()) return; + } + _fem_op_head = (uint8_t)((_fem_op_head + 1) % KISS_FEM_OP_QUEUE_DEPTH); + _fem_op_count--; } } void KissModem::handleSetFemState(const uint8_t* data, uint16_t len) { if (len < 2) { - writeHardwareError(HW_ERR_INVALID_LENGTH); + enqueueFemOp(FEM_OP_ERROR, 0, HW_ERR_INVALID_LENGTH); return; } - uint8_t apply_mask = data[0]; - uint8_t value_mask = data[1]; - // validate every requested bit before touching hardware so a request is all-or-nothing - uint8_t fem_caps, fem_values; - readFemState(&fem_caps, &fem_values); - if (apply_mask & ~fem_caps) { - writeHardwareError(HW_ERR_UNSUPPORTED); - return; - } - if (isFemReplyQueued()) { - writeHardwareError(HW_ERR_TX_BUSY); - return; - } - if (_tx_state == TX_SENDING || _tx_state == TX_DONE_PENDING) { - // board setters drive FEM pins directly; changing them mid-packet would corrupt the TX - _fem_deferred = true; - _fem_deferred_apply = apply_mask; - _fem_deferred_value = value_mask; - return; - } - applyFemState(apply_mask, value_mask); - _fem_reply_pending = true; - processDeferredFem(); + enqueueFemOp(FEM_OP_SET, data[0], data[1]); } void KissModem::handleGetFemState() { - if (isFemReplyQueued()) { - if (_fem_deferred_gets == UINT8_MAX) { - writeHardwareError(HW_ERR_TX_BUSY); - return; - } - _fem_deferred_gets++; - return; - } - queueFemReply(true); + enqueueFemOp(FEM_OP_GET, 0, 0); } void KissModem::handleSetRxBoostedGain(const uint8_t* data, uint16_t len) { diff --git a/examples/kiss_modem/KissModem.h b/examples/kiss_modem/KissModem.h index 572999c4..24021bdb 100644 --- a/examples/kiss_modem/KissModem.h +++ b/examples/kiss_modem/KissModem.h @@ -103,6 +103,9 @@ /* Matches the CLI reply buffer boards write into from handleCommand() */ #define KISS_BOARD_REPLY_SIZE 160 +/* FEM requests are answered strictly in arrival order; this many may wait (e.g. during a TX) */ +#define KISS_FEM_OP_QUEUE_DEPTH 4 + #define KISS_AGC_RESET_DEFAULT_SEC 30 #define KISS_AGC_RESET_MAX_SEC 1020 #define KISS_AGC_RESET_STEP_SEC 4 @@ -125,6 +128,19 @@ struct RadioConfig { uint8_t tx_power; }; +enum FemOpKind : uint8_t { + FEM_OP_SET, + FEM_OP_GET, + FEM_OP_ERROR +}; + +struct FemOp { + FemOpKind kind; + uint8_t apply_mask; // FEM_OP_SET + uint8_t value_mask; // FEM_OP_SET; error code for FEM_OP_ERROR + bool applied; // FEM_OP_SET: hardware changed, reply still to be queued +}; + enum TxState { TX_IDLE, TX_WAIT_CLEAR, @@ -172,11 +188,9 @@ class KissModem { bool _signal_report_enabled; uint16_t _agc_reset_interval_sec; uint32_t _next_agc_reset_ms; - bool _fem_deferred; - uint8_t _fem_deferred_apply; - uint8_t _fem_deferred_value; - bool _fem_reply_pending; - uint8_t _fem_deferred_gets; + FemOp _fem_ops[KISS_FEM_OP_QUEUE_DEPTH]; + uint8_t _fem_op_head; + uint8_t _fem_op_count; uint8_t _tx_frame_buf[KISS_TX_FRAME_QUEUE_DEPTH][KISS_MAX_ENCODED_FRAME_SIZE]; uint16_t _tx_frame_len[KISS_TX_FRAME_QUEUE_DEPTH]; uint16_t _tx_frame_written[KISS_TX_FRAME_QUEUE_DEPTH]; @@ -207,10 +221,10 @@ class KissModem { bool queryFemGain(uint8_t bit, bool* enabled); bool setFemGain(uint8_t bit, bool enable); void readFemState(uint8_t* caps, uint8_t* values); - bool queueFemReply(bool mark_busy_error); + bool queueFemReply(); void applyFemState(uint8_t apply_mask, uint8_t value_mask); - bool isFemReplyQueued() const { return _fem_deferred || _fem_reply_pending || _fem_deferred_gets > 0; } - void processDeferredFem(); + void enqueueFemOp(FemOpKind kind, uint8_t apply_mask, uint8_t value_mask); + void processFemOps(); void handleGetIdentity(); void handleGetRandom(const uint8_t* data, uint16_t len); diff --git a/test/test_kiss_modem/test_hw_controls.cpp b/test/test_kiss_modem/test_hw_controls.cpp index 16ef50df..e0fdd729 100644 --- a/test/test_kiss_modem/test_hw_controls.cpp +++ b/test/test_kiss_modem/test_hw_controls.cpp @@ -330,20 +330,62 @@ TEST_F(KissHwControlTest, FemSetDuringTxIsDeferredUntilAfterTxDone) { serial.takeHardwareFrames(); EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}).empty()); + EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, 0}).empty()); // queued behind the first EXPECT_EQ(board.lna_sets, 0); - EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, 0}), (std::vector{HW_RESP_ERROR, HW_ERR_TX_BUSY})); radio.send_complete = true; modem.loop(); // TX done -> TX_DONE_PENDING; FEM still held - modem.loop(); // TxDone queued -> idle; FEM applied + modem.loop(); // TxDone queued -> idle; FEM applied in order + for (int i = 0; i < 3; i++) modem.loop(); auto frames = serial.takeHardwareFrames(); - ASSERT_EQ(frames.size(), 2U); + ASSERT_EQ(frames.size(), 3U); EXPECT_EQ(frames[0], (std::vector{HW_RESP_TX_DONE, 0x01})); EXPECT_EQ(frames[1], (std::vector{0x9F, 0x01, 0x01})); - EXPECT_TRUE(board.lna); + EXPECT_EQ(frames[2], (std::vector{0x9F, 0x01, 0x00})); + EXPECT_FALSE(board.lna); + EXPECT_EQ(board.lna_sets, 2); +} + +TEST_F(KissHwControlTest, PipelinedFemRequestsAreAnsweredInArrivalOrder) { + board.has_lna = true; + startTxAndHold(); + serial.takeHardwareFrames(); + + EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}).empty()); + EXPECT_TRUE(hw({HW_CMD_GET_FEM_STATE}).empty()); + EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_TX_GAIN, HW_FEM_TX_GAIN}).empty()); // unsupported bit + EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN}).empty()); // short payload + + radio.send_complete = true; + for (int i = 0; i < 6; i++) modem.loop(); + auto frames = serial.takeHardwareFrames(); + ASSERT_EQ(frames.size(), 5U); + EXPECT_EQ(frames[0], (std::vector{HW_RESP_TX_DONE, 0x01})); + EXPECT_EQ(frames[1], (std::vector{0x9F, 0x01, 0x01})); + EXPECT_EQ(frames[2], (std::vector{0x9F, 0x01, 0x01})); + EXPECT_EQ(frames[3], ERR_UNSUPPORTED); + EXPECT_EQ(frames[4], (std::vector{HW_RESP_ERROR, HW_ERR_INVALID_LENGTH})); EXPECT_EQ(board.lna_sets, 1); } +TEST_F(KissHwControlTest, FemQueueOverflowRepliesTxBusyImmediately) { + board.has_lna = true; + startTxAndHold(); + serial.takeHardwareFrames(); + for (int i = 0; i < KISS_FEM_OP_QUEUE_DEPTH; i++) { + EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}).empty()); + } + EXPECT_EQ(hw1({HW_CMD_GET_FEM_STATE}), (std::vector{HW_RESP_ERROR, HW_ERR_TX_BUSY})); + EXPECT_EQ(board.lna_sets, 0); +} + +TEST_F(KissHwControlTest, FemGetWithNothingQueuedIsAnsweredDuringTx) { + board.has_lna = true; + startTxAndHold(); + serial.takeHardwareFrames(); + EXPECT_EQ(hw1({HW_CMD_GET_FEM_STATE}), (std::vector{0x9F, 0x01, 0x00})); +} + TEST_F(KissHwControlTest, FemGetDuringDeferredSetIsAnsweredAfterSet) { board.has_lna = true; startTxAndHold(); From bc4d0227fe08b89f289f2a5a3226b2fab61ca74b Mon Sep 17 00:00:00 2001 From: agessaman Date: Wed, 23 Sep 2026 18:51:03 -0700 Subject: [PATCH 08/79] kiss_modem: default AGC reset interval to 32 s The AGC interval is set in 4 s steps, matching MeshCore's agc.reset.interval, so the old 30 s default could not be restored by a host: setting 30 gives 28. Found on hardware. Use 32 s, the nearest multiple of 4 above it. --- docs/kiss_modem_protocol.md | 4 ++-- examples/kiss_modem/KissModem.h | 2 +- test/test_kiss_modem/test_hw_controls.cpp | 13 ++++++++----- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/docs/kiss_modem_protocol.md b/docs/kiss_modem_protocol.md index 5eb09738..5075cf4c 100644 --- a/docs/kiss_modem_protocol.md +++ b/docs/kiss_modem_protocol.md @@ -227,7 +227,7 @@ All values little-endian. |-------------|---------|-----------------------| | Noise floor | 2 bytes | int16_t, dBm (signed) | -The modem recalibrates the noise floor every 2 seconds. AGC resets follow the configured AGC reset interval (default 30 seconds). +The modem recalibrates the noise floor every 2 seconds. AGC resets follow the configured AGC reset interval (default 32 seconds). ### Capabilities (Capabilities response) @@ -256,7 +256,7 @@ All values little-endian. The modem periodically resets the radio's AGC while idle (no transmission in progress and host output not backed up). The interval has 4-second resolution, matching the MeshCore `agc.reset.interval` setting: requested values are rounded down to a multiple of 4, so 1-3 disable the reset. Values above 1020 return `InvalidParam`. SetAgcResetInterval replies with the AgcResetInterval response carrying the effective value, and restarts the countdown from the time of the request. -The default is 30 seconds. The setting is not persisted; hosts should re-send it after reconnecting or rebooting the modem. +The default is 32 seconds (previously a fixed 30; changed so the default is a settable 4-second multiple). The setting is not persisted; hosts should re-send it after reconnecting or rebooting the modem. ### FEM State (SetFemState / FemState response) diff --git a/examples/kiss_modem/KissModem.h b/examples/kiss_modem/KissModem.h index 24021bdb..bee41634 100644 --- a/examples/kiss_modem/KissModem.h +++ b/examples/kiss_modem/KissModem.h @@ -106,7 +106,7 @@ /* FEM requests are answered strictly in arrival order; this many may wait (e.g. during a TX) */ #define KISS_FEM_OP_QUEUE_DEPTH 4 -#define KISS_AGC_RESET_DEFAULT_SEC 30 +#define KISS_AGC_RESET_DEFAULT_SEC 32 // a multiple of the 4 s step, so hosts can set it back #define KISS_AGC_RESET_MAX_SEC 1020 #define KISS_AGC_RESET_STEP_SEC 4 diff --git a/test/test_kiss_modem/test_hw_controls.cpp b/test/test_kiss_modem/test_hw_controls.cpp index e0fdd729..2b0b779e 100644 --- a/test/test_kiss_modem/test_hw_controls.cpp +++ b/test/test_kiss_modem/test_hw_controls.cpp @@ -208,8 +208,11 @@ TEST_F(KissHwControlTest, CapabilitiesReflectBoardFem) { EXPECT_EQ(hw1({HW_CMD_GET_CAPABILITIES}), (std::vector{0x9B, 0x07, 0x00, 0x00, 0x00})); } -TEST_F(KissHwControlTest, AgcIntervalDefaultsToThirtySeconds) { - EXPECT_EQ(hw1({HW_CMD_GET_AGC_RESET_INTERVAL}), (std::vector{0x9D, 30, 0})); +TEST_F(KissHwControlTest, AgcIntervalDefaultsToThirtyTwoSeconds) { + EXPECT_EQ(hw1({HW_CMD_GET_AGC_RESET_INTERVAL}), (std::vector{0x9D, 32, 0})); + // the default must be restorable, i.e. a multiple of the 4 s step + EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 4, 0}), (std::vector{0x9D, 4, 0})); + EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, KISS_AGC_RESET_DEFAULT_SEC, 0}), (std::vector{0x9D, KISS_AGC_RESET_DEFAULT_SEC, 0})); } TEST_F(KissHwControlTest, AgcIntervalSetReturnsEffectiveRoundedValue) { @@ -223,15 +226,15 @@ TEST_F(KissHwControlTest, AgcIntervalSetReturnsEffectiveRoundedValue) { TEST_F(KissHwControlTest, AgcIntervalRejectsOutOfRangeAndShortPayload) { EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 0xFD, 0x03}), (std::vector{HW_RESP_ERROR, HW_ERR_INVALID_PARAM})); EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 4}), (std::vector{HW_RESP_ERROR, HW_ERR_INVALID_LENGTH})); - EXPECT_EQ(hw1({HW_CMD_GET_AGC_RESET_INTERVAL}), (std::vector{0x9D, 30, 0})); + EXPECT_EQ(hw1({HW_CMD_GET_AGC_RESET_INTERVAL}), (std::vector{0x9D, 32, 0})); } TEST_F(KissHwControlTest, AgcResetsOnDefaultSchedule) { - advance(29999); + advance(31999); EXPECT_EQ(radio.agc_resets, 0); advance(1); EXPECT_EQ(radio.agc_resets, 1); - advance(29999); + advance(31999); EXPECT_EQ(radio.agc_resets, 1); advance(1); EXPECT_EQ(radio.agc_resets, 2); From 990ea55e2d664140a7f4a913efe3fac1add95859 Mon Sep 17 00:00:00 2001 From: agessaman Date: Wed, 23 Sep 2026 21:56:27 -0700 Subject: [PATCH 09/79] radiolib: reapply runtime RX boosted gain on SX126x AGC reset sx126xResetAGC only restored the gain when the build defined SX126X_RX_BOOSTED_GAIN, so a gain set at runtime was lost on reset. Match lr11x0ResetAGC and always reapply. Also pass the gain state from the LLCC68 wrapper, whose call did not match the helper's signature. --- src/helpers/radiolib/CustomLLCC68Wrapper.h | 2 +- src/helpers/radiolib/SX126xReset.h | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/helpers/radiolib/CustomLLCC68Wrapper.h b/src/helpers/radiolib/CustomLLCC68Wrapper.h index 89d5e1bc..e96ae663 100644 --- a/src/helpers/radiolib/CustomLLCC68Wrapper.h +++ b/src/helpers/radiolib/CustomLLCC68Wrapper.h @@ -35,7 +35,7 @@ public: } uint8_t getSpreadingFactor() const override { return ((CustomLLCC68 *)_radio)->spreadingFactor; } - void doResetAGC() override { sx126xResetAGC((SX126x *)_radio); } + void doResetAGC() override { sx126xResetAGC((SX126x *)_radio, getRxBoostedGainMode()); } bool supportsRxBoostedGain() const override { return true; } bool setRxBoostedGainMode(bool en) override { diff --git a/src/helpers/radiolib/SX126xReset.h b/src/helpers/radiolib/SX126xReset.h index 472eb33b..bce84191 100644 --- a/src/helpers/radiolib/SX126xReset.h +++ b/src/helpers/radiolib/SX126xReset.h @@ -25,9 +25,8 @@ inline void sx126xResetAGC(SX126x* radio, bool rx_boost_gain) { #ifdef SX126X_DIO2_AS_RF_SWITCH radio->setDio2AsRfSwitch(SX126X_DIO2_AS_RF_SWITCH); #endif -#ifdef SX126X_RX_BOOSTED_GAIN + // always reapply: the gain may have been changed at runtime even when no build default is set radio->setRxBoostedGainMode(rx_boost_gain); -#endif #ifdef SX126X_REGISTER_PATCH uint8_t r_data = 0; radio->readRegister(0x8B5, &r_data, 1); From a1b5655af190b75ded7282c32800119202b60d78 Mon Sep 17 00:00:00 2001 From: Marcel Verdult Date: Sat, 26 Sep 2026 20:39:23 +0200 Subject: [PATCH 10/79] Fix ThinkNode M8 repeater/room server build: compile sensor helpers for all envs --- variants/thinknode_m8/platformio.ini | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/variants/thinknode_m8/platformio.ini b/variants/thinknode_m8/platformio.ini index db19e446..57f2a938 100644 --- a/variants/thinknode_m8/platformio.ini +++ b/variants/thinknode_m8/platformio.ini @@ -40,6 +40,7 @@ build_flags = ${nrf52_base.build_flags} -D LORA_TX_POWER=22 build_src_filter = ${nrf52_base.build_src_filter} + + + + +<../variants/thinknode_m8> lib_deps = @@ -110,7 +111,6 @@ build_src_filter = ${ThinkNode_M8.build_src_filter} + + + - + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = @@ -144,7 +144,6 @@ build_src_filter = ${ThinkNode_M8.build_src_filter} + + + - + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = From 05cd36d2ec884a999db1551ee930c741b562098d Mon Sep 17 00:00:00 2001 From: R0ck Date: Thu, 15 Oct 2026 19:33:35 +0100 Subject: [PATCH 11/79] Add T1000-E custom CLI command to toggle the buzzer --- variants/t1000-e/T1000eBoard.cpp | 70 +++++++++++++++++++++++++++++++- variants/t1000-e/T1000eBoard.h | 8 ++++ 2 files changed, 77 insertions(+), 1 deletion(-) diff --git a/variants/t1000-e/T1000eBoard.cpp b/variants/t1000-e/T1000eBoard.cpp index 0d390f79..a4713017 100644 --- a/variants/t1000-e/T1000eBoard.cpp +++ b/variants/t1000-e/T1000eBoard.cpp @@ -3,6 +3,10 @@ #include "T1000eBoard.h" +#ifdef PIN_BUZZER_EN + #include +#endif + void T1000eBoard::begin() { NRF52BoardDCDC::begin(); btn_prev_state = HIGH; @@ -20,4 +24,68 @@ void T1000eBoard::begin() { Wire.begin(); delay(10); // give sx1262 some time to power up -} \ No newline at end of file +} + +void T1000eBoard::attachDynamicPrefs(KeyValueStore* prefs) { + _prefs = prefs; +#ifdef PIN_BUZZER_EN + char val[8]; + val[0] = 0; + _prefs->getByKey("buzzer", val, sizeof(val)); + _buzzer_muted = strcmp(val, "0") == 0; +#endif +} + +#ifdef PIN_BUZZER_EN +static void playTune(const char* tune) { + if (rtttl::isPlaying()) rtttl::stop(); + rtttl::begin(PIN_BUZZER, tune); +} +#endif + +void T1000eBoard::setBuzzerEnabled(bool enable) { +#ifdef PIN_BUZZER_EN + _buzzer_muted = !enable; + digitalWrite(PIN_BUZZER_EN, enable ? HIGH : LOW); +#endif +} + +void T1000eBoard::loop() { + NRF52BoardDCDC::loop(); +#ifdef PIN_BUZZER_EN + if (!rtttl::done()) rtttl::play(); + if (_buzzer_mute_pending && rtttl::done()) { // mute once the confirmation beep has finished + _buzzer_mute_pending = false; + setBuzzerEnabled(false); + } + if (_buzzer_muted) digitalWrite(PIN_BUZZER_EN, LOW); // keep it off even if the UI re-enables it +#endif +} + +bool T1000eBoard::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { +#ifdef PIN_BUZZER_EN + if (strcmp(command, "get buzzer") == 0) { + sprintf(reply, "> %s", (_buzzer_muted || _buzzer_mute_pending) ? "off" : "on"); + return true; + } + if (memcmp(command, "set buzzer ", 11) == 0) { + if (strcmp(&command[11], "on") == 0) { + _buzzer_mute_pending = false; + setBuzzerEnabled(true); + if (_prefs) _prefs->setByKey("buzzer", "1"); + playTune("MsgRcv3:d=4,o=6,b=200:32e,32g,32b,16c7"); // same tune as a new message + strcpy(reply, "OK - buzzer on"); + } else if (strcmp(&command[11], "off") == 0) { + setBuzzerEnabled(true); + _buzzer_mute_pending = true; + if (_prefs) _prefs->setByKey("buzzer", "0"); + playTune("ack:d=32,o=8,b=120:c"); // same beep as an ack, before going quiet + strcpy(reply, "OK - buzzer off"); + } else { + strcpy(reply, "Error: state must be on or off"); + } + return true; + } +#endif + return false; // not handled +} diff --git a/variants/t1000-e/T1000eBoard.h b/variants/t1000-e/T1000eBoard.h index ba8bf0c1..846c7df2 100644 --- a/variants/t1000-e/T1000eBoard.h +++ b/variants/t1000-e/T1000eBoard.h @@ -7,10 +7,18 @@ class T1000eBoard : public NRF52BoardDCDC { protected: uint8_t btn_prev_state; + KeyValueStore* _prefs = NULL; + bool _buzzer_muted = false; + bool _buzzer_mute_pending = false; + + void setBuzzerEnabled(bool enable); public: T1000eBoard() : NRF52Board("T1000E_OTA") {} void begin(); + void attachDynamicPrefs(KeyValueStore* prefs); + bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; + void loop() override; uint16_t getBattMilliVolts() override { #ifdef BATTERY_PIN From bb84f293b79885dbaedaa83b2eaba10519b078fb Mon Sep 17 00:00:00 2001 From: R0ck Date: Thu, 15 Oct 2026 20:12:13 +0100 Subject: [PATCH 12/79] Fix off-by-one when loading the T1000-E buzzer setting --- variants/t1000-e/T1000eBoard.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/variants/t1000-e/T1000eBoard.cpp b/variants/t1000-e/T1000eBoard.cpp index a4713017..ff42f5e4 100644 --- a/variants/t1000-e/T1000eBoard.cpp +++ b/variants/t1000-e/T1000eBoard.cpp @@ -31,7 +31,7 @@ void T1000eBoard::attachDynamicPrefs(KeyValueStore* prefs) { #ifdef PIN_BUZZER_EN char val[8]; val[0] = 0; - _prefs->getByKey("buzzer", val, sizeof(val)); + _prefs->getByKey("buzzer", val, sizeof(val) - 1); _buzzer_muted = strcmp(val, "0") == 0; #endif } From 0769d68ed628c9cf346057f33df3c94ef5f82f60 Mon Sep 17 00:00:00 2001 From: R0ck Date: Thu, 15 Oct 2026 20:12:23 +0100 Subject: [PATCH 13/79] Report an error when the buzzer setting fails to save --- variants/t1000-e/T1000eBoard.cpp | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/variants/t1000-e/T1000eBoard.cpp b/variants/t1000-e/T1000eBoard.cpp index ff42f5e4..9bdeff89 100644 --- a/variants/t1000-e/T1000eBoard.cpp +++ b/variants/t1000-e/T1000eBoard.cpp @@ -70,17 +70,23 @@ bool T1000eBoard::handleCommand(const char* command, uint32_t sender_timestamp, } if (memcmp(command, "set buzzer ", 11) == 0) { if (strcmp(&command[11], "on") == 0) { - _buzzer_mute_pending = false; - setBuzzerEnabled(true); - if (_prefs) _prefs->setByKey("buzzer", "1"); - playTune("MsgRcv3:d=4,o=6,b=200:32e,32g,32b,16c7"); // same tune as a new message - strcpy(reply, "OK - buzzer on"); + if (_prefs && !_prefs->setByKey("buzzer", "1")) { + strcpy(reply, "Error: failed to save buzzer setting"); + } else { + _buzzer_mute_pending = false; + setBuzzerEnabled(true); + playTune("MsgRcv3:d=4,o=6,b=200:32e,32g,32b,16c7"); // same tune as a new message + strcpy(reply, "OK - buzzer on"); + } } else if (strcmp(&command[11], "off") == 0) { - setBuzzerEnabled(true); - _buzzer_mute_pending = true; - if (_prefs) _prefs->setByKey("buzzer", "0"); - playTune("ack:d=32,o=8,b=120:c"); // same beep as an ack, before going quiet - strcpy(reply, "OK - buzzer off"); + if (_prefs && !_prefs->setByKey("buzzer", "0")) { + strcpy(reply, "Error: failed to save buzzer setting"); + } else { + setBuzzerEnabled(true); + _buzzer_mute_pending = true; + playTune("ack:d=32,o=8,b=120:c"); // same beep as an ack, before going quiet + strcpy(reply, "OK - buzzer off"); + } } else { strcpy(reply, "Error: state must be on or off"); } From 757e84647ce1483ce775fc5abd4c459f2d8a95ef Mon Sep 17 00:00:00 2001 From: amdoolittle Date: Fri, 16 Oct 2026 22:39:26 -0700 Subject: [PATCH 14/79] Added WiFi to TFT BLE version of Heltec V4 --- variants/heltec_v4/platformio.ini | 2 ++ 1 file changed, 2 insertions(+) diff --git a/variants/heltec_v4/platformio.ini b/variants/heltec_v4/platformio.ini index 76e8e714..c91e31a8 100644 --- a/variants/heltec_v4/platformio.ini +++ b/variants/heltec_v4/platformio.ini @@ -380,12 +380,14 @@ build_flags = -D AUTO_SHUTDOWN_MILLIVOLTS=3400 -D BLE_DEBUG_LOGGING=1 -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_WIFI_INTERFACE ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${heltec_v4_tft.build_src_filter} + + + + + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> lib_deps = From b2bde37fe4e9d58e02e97d30982809792c0f57f3 Mon Sep 17 00:00:00 2001 From: rado <6479266+rbrus@users.noreply.github.com> Date: Sat, 17 Oct 2026 09:36:33 +0200 Subject: [PATCH 15/79] Fix unsigned conversion of negative TX power in CommonRadioPrefs --- examples/companion_radio/NodePrefs.h | 4 +- src/helpers/CommonCLI.h | 4 +- src/helpers/CommonRadioPrefs.h | 4 +- .../test_companion_node_prefs.cpp | 57 +++++++++++++++++++ 4 files changed, 63 insertions(+), 6 deletions(-) diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index 3cceed56..1cc5b501 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -102,8 +102,8 @@ private: void setIntThresh(uint8_t t) override { _parent->interference_threshold = t; markDirty(); } uint8_t getRxGain() const override { return _parent->rx_boosted_gain; } void setRxGain(uint8_t g) override { _parent->rx_boosted_gain = g; markDirty(); } - uint8_t getTxPower() const override { return _parent->tx_power_dbm; } - void setTxPower(uint8_t dbm) override { _parent->tx_power_dbm = dbm; markDirty(); } + int8_t getTxPower() const override { return _parent->tx_power_dbm; } + void setTxPower(int8_t dbm) override { _parent->tx_power_dbm = dbm; markDirty(); } float getRxDelay() const override { return _parent->rx_delay_base; } void setRxDelay(float d) override { _parent->rx_delay_base = d; markDirty(); } uint16_t getAgcResetInt() const override { return _parent->agc_reset_interval * 4; } diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 2759b0c4..675df7a4 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -115,8 +115,8 @@ private: void setIntThresh(uint8_t t) override { _parent->interference_threshold = t; markDirty(); } uint8_t getRxGain() const override { return _parent->rx_boosted_gain; } void setRxGain(uint8_t g) override { _parent->rx_boosted_gain = g; markDirty(); } - uint8_t getTxPower() const override { return _parent->tx_power_dbm; } - void setTxPower(uint8_t dbm) override { _parent->tx_power_dbm = dbm; markDirty(); } + int8_t getTxPower() const override { return _parent->tx_power_dbm; } + void setTxPower(int8_t dbm) override { _parent->tx_power_dbm = dbm; markDirty(); } float getRxDelay() const override { return _parent->rx_delay_base; } void setRxDelay(float d) override { _parent->rx_delay_base = d; markDirty(); } uint16_t getAgcResetInt() const override { return _parent->agc_reset_interval * 4; } diff --git a/src/helpers/CommonRadioPrefs.h b/src/helpers/CommonRadioPrefs.h index 0e83ca9d..d0083b8c 100644 --- a/src/helpers/CommonRadioPrefs.h +++ b/src/helpers/CommonRadioPrefs.h @@ -35,8 +35,8 @@ public: virtual uint8_t getRxGain() const = 0; virtual void setRxGain(uint8_t g) = 0; - virtual uint8_t getTxPower() const = 0; - virtual void setTxPower(uint8_t dbm) = 0; + virtual int8_t getTxPower() const = 0; + virtual void setTxPower(int8_t dbm) = 0; virtual float getRxDelay() const = 0; virtual void setRxDelay(float d) = 0; diff --git a/test/test_companion_node_prefs/test_companion_node_prefs.cpp b/test/test_companion_node_prefs/test_companion_node_prefs.cpp index 433c9710..ab5e0f90 100644 --- a/test/test_companion_node_prefs/test_companion_node_prefs.cpp +++ b/test/test_companion_node_prefs/test_companion_node_prefs.cpp @@ -6,6 +6,32 @@ #include "../../examples/companion_radio/NodePrefs.h" +bool CommonRadioPrefs::getByKey(const char* key, char* value, size_t max_len) { + if (strcmp(key, "fem_rxgain") == 0) { + snprintf(value, max_len, "%d", (uint32_t)getFEMRxGain()); + return true; + } + if (strcmp(key, "fem_txgain") == 0) { + snprintf(value, max_len, "%d", (uint32_t)getFEMTxGain()); + return true; + } + return false; +} + +bool CommonRadioPrefs::setByKey(const char* key, const char* value) { + if (strcmp(key, "fem_rxgain") == 0) { + setFEMRxGain(atoi(value)); + markDirty(); + return true; + } + if (strcmp(key, "fem_txgain") == 0) { + setFEMTxGain(atoi(value)); + markDirty(); + return true; + } + return false; +} + class ReplayStream : public Stream { const char* _text; int _pos = 0; @@ -77,6 +103,37 @@ TEST(CompanionNodePrefs, RxGainSettingsRoundTripIndependently) { } #endif +TEST(CompanionNodePrefs, NegativeTxPowerPreservedAsSigned) { + NodePrefs prefs; + CommonRadioPrefs* radio = prefs.getRadioPrefs(); + + radio->setTxPower(-9); + EXPECT_EQ(-9, prefs.tx_power_dbm); + EXPECT_EQ(-9, radio->getTxPower()); + EXPECT_EQ(-9, static_cast(radio->getTxPower())); + + char reply[32]; + snprintf(reply, sizeof(reply), "> %d", static_cast(radio->getTxPower())); + EXPECT_STREQ("> -9", reply); +} + +TEST(CompanionNodePrefs, NegativeTxPowerRoundTripsSerial) { + NodePrefs saved; + saved.getRadioPrefs()->setTxPower(-9); + + CaptureStream output; + ASSERT_TRUE(saved.saveSerial(output)); + EXPECT_NE(std::string::npos, output.text().find("tx:-9")); + + ReplayStream input("{radio:{tx:-9}}"); + NodePrefs loaded; + loaded.tx_power_dbm = 22; + + ASSERT_TRUE(loaded.loadSerial(input)); + EXPECT_EQ(-9, loaded.tx_power_dbm); + EXPECT_EQ(-9, loaded.getRadioPrefs()->getTxPower()); +} + int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); From 5f967d818a660c6a650b4a67d2510937a9b86497 Mon Sep 17 00:00:00 2001 From: Confituurke <9595028+Confituurke@users.noreply.github.com> Date: Sat, 17 Oct 2026 13:03:06 +0200 Subject: [PATCH 16/79] Show quarter-hour timezone offsets with two decimals 'get tz.offset' printed one decimal, so a UTC+5:45 offset (5.75) read back as 5.8. Print two decimals when the offset is on a quarter hour (x.25 / x.75); everything else keeps one decimal. --- examples/companion_radio/MyMesh.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 99a9aa30..2ea539db 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2192,7 +2192,7 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* } if (strcmp(command, "get tz.offset") == 0) { - sprintf(reply, "> %.1f", _prefs.tz_offset); + sprintf(reply, ((int)(_prefs.tz_offset * 4) % 2) ? "> %.2f" : "> %.1f", _prefs.tz_offset); return true; } if (memcmp(command, "set tz.offset ", 14) == 0) { From 36f2b1d163ed158688e0a50e681b57e5123503a1 Mon Sep 17 00:00:00 2001 From: R0ck Date: Sat, 17 Oct 2026 23:27:43 +0100 Subject: [PATCH 17/79] Remove the acknowledgement tones --- variants/t1000-e/T1000eBoard.cpp | 24 ++---------------------- variants/t1000-e/T1000eBoard.h | 1 - 2 files changed, 2 insertions(+), 23 deletions(-) diff --git a/variants/t1000-e/T1000eBoard.cpp b/variants/t1000-e/T1000eBoard.cpp index 9bdeff89..649ae9d6 100644 --- a/variants/t1000-e/T1000eBoard.cpp +++ b/variants/t1000-e/T1000eBoard.cpp @@ -3,10 +3,6 @@ #include "T1000eBoard.h" -#ifdef PIN_BUZZER_EN - #include -#endif - void T1000eBoard::begin() { NRF52BoardDCDC::begin(); btn_prev_state = HIGH; @@ -36,13 +32,6 @@ void T1000eBoard::attachDynamicPrefs(KeyValueStore* prefs) { #endif } -#ifdef PIN_BUZZER_EN -static void playTune(const char* tune) { - if (rtttl::isPlaying()) rtttl::stop(); - rtttl::begin(PIN_BUZZER, tune); -} -#endif - void T1000eBoard::setBuzzerEnabled(bool enable) { #ifdef PIN_BUZZER_EN _buzzer_muted = !enable; @@ -53,11 +42,6 @@ void T1000eBoard::setBuzzerEnabled(bool enable) { void T1000eBoard::loop() { NRF52BoardDCDC::loop(); #ifdef PIN_BUZZER_EN - if (!rtttl::done()) rtttl::play(); - if (_buzzer_mute_pending && rtttl::done()) { // mute once the confirmation beep has finished - _buzzer_mute_pending = false; - setBuzzerEnabled(false); - } if (_buzzer_muted) digitalWrite(PIN_BUZZER_EN, LOW); // keep it off even if the UI re-enables it #endif } @@ -65,7 +49,7 @@ void T1000eBoard::loop() { bool T1000eBoard::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { #ifdef PIN_BUZZER_EN if (strcmp(command, "get buzzer") == 0) { - sprintf(reply, "> %s", (_buzzer_muted || _buzzer_mute_pending) ? "off" : "on"); + sprintf(reply, "> %s", _buzzer_muted ? "off" : "on"); return true; } if (memcmp(command, "set buzzer ", 11) == 0) { @@ -73,18 +57,14 @@ bool T1000eBoard::handleCommand(const char* command, uint32_t sender_timestamp, if (_prefs && !_prefs->setByKey("buzzer", "1")) { strcpy(reply, "Error: failed to save buzzer setting"); } else { - _buzzer_mute_pending = false; setBuzzerEnabled(true); - playTune("MsgRcv3:d=4,o=6,b=200:32e,32g,32b,16c7"); // same tune as a new message strcpy(reply, "OK - buzzer on"); } } else if (strcmp(&command[11], "off") == 0) { if (_prefs && !_prefs->setByKey("buzzer", "0")) { strcpy(reply, "Error: failed to save buzzer setting"); } else { - setBuzzerEnabled(true); - _buzzer_mute_pending = true; - playTune("ack:d=32,o=8,b=120:c"); // same beep as an ack, before going quiet + setBuzzerEnabled(false); strcpy(reply, "OK - buzzer off"); } } else { diff --git a/variants/t1000-e/T1000eBoard.h b/variants/t1000-e/T1000eBoard.h index 846c7df2..e6ceb4fe 100644 --- a/variants/t1000-e/T1000eBoard.h +++ b/variants/t1000-e/T1000eBoard.h @@ -9,7 +9,6 @@ protected: uint8_t btn_prev_state; KeyValueStore* _prefs = NULL; bool _buzzer_muted = false; - bool _buzzer_mute_pending = false; void setBuzzerEnabled(bool enable); From b9fa77ed69cdb03229801f086eae79e02305f937 Mon Sep 17 00:00:00 2001 From: R0ck Date: Sat, 17 Oct 2026 23:37:14 +0100 Subject: [PATCH 18/79] Move to companion firmware, remove from varient --- examples/companion_radio/MyMesh.cpp | 17 +++++++++ variants/t1000-e/T1000eBoard.cpp | 56 +---------------------------- variants/t1000-e/T1000eBoard.h | 7 ---- 3 files changed, 18 insertions(+), 62 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index f32ea67a..ebe0636a 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2122,6 +2122,23 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* return true; } +#ifdef PIN_BUZZER + if (strcmp(command, "get buzzer") == 0) { + sprintf(reply, "> %s", _prefs.buzzer_quiet ? "off" : "on"); + return true; + } + if (memcmp(command, "set buzzer ", 11) == 0) { + if (strcmp(&command[11], "on") == 0 || strcmp(&command[11], "off") == 0) { + _prefs.buzzer_quiet = strcmp(&command[11], "off") == 0; + savePrefs(); + strcpy(reply, "OK"); + } else { + strcpy(reply, "Error: state must be on or off"); + } + return true; + } +#endif + if (memcmp(command, "set pin ", 8) == 0) { _prefs.ble_pin = atoi(&command[8]); savePrefs(); diff --git a/variants/t1000-e/T1000eBoard.cpp b/variants/t1000-e/T1000eBoard.cpp index 649ae9d6..0d390f79 100644 --- a/variants/t1000-e/T1000eBoard.cpp +++ b/variants/t1000-e/T1000eBoard.cpp @@ -20,58 +20,4 @@ void T1000eBoard::begin() { Wire.begin(); delay(10); // give sx1262 some time to power up -} - -void T1000eBoard::attachDynamicPrefs(KeyValueStore* prefs) { - _prefs = prefs; -#ifdef PIN_BUZZER_EN - char val[8]; - val[0] = 0; - _prefs->getByKey("buzzer", val, sizeof(val) - 1); - _buzzer_muted = strcmp(val, "0") == 0; -#endif -} - -void T1000eBoard::setBuzzerEnabled(bool enable) { -#ifdef PIN_BUZZER_EN - _buzzer_muted = !enable; - digitalWrite(PIN_BUZZER_EN, enable ? HIGH : LOW); -#endif -} - -void T1000eBoard::loop() { - NRF52BoardDCDC::loop(); -#ifdef PIN_BUZZER_EN - if (_buzzer_muted) digitalWrite(PIN_BUZZER_EN, LOW); // keep it off even if the UI re-enables it -#endif -} - -bool T1000eBoard::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { -#ifdef PIN_BUZZER_EN - if (strcmp(command, "get buzzer") == 0) { - sprintf(reply, "> %s", _buzzer_muted ? "off" : "on"); - return true; - } - if (memcmp(command, "set buzzer ", 11) == 0) { - if (strcmp(&command[11], "on") == 0) { - if (_prefs && !_prefs->setByKey("buzzer", "1")) { - strcpy(reply, "Error: failed to save buzzer setting"); - } else { - setBuzzerEnabled(true); - strcpy(reply, "OK - buzzer on"); - } - } else if (strcmp(&command[11], "off") == 0) { - if (_prefs && !_prefs->setByKey("buzzer", "0")) { - strcpy(reply, "Error: failed to save buzzer setting"); - } else { - setBuzzerEnabled(false); - strcpy(reply, "OK - buzzer off"); - } - } else { - strcpy(reply, "Error: state must be on or off"); - } - return true; - } -#endif - return false; // not handled -} +} \ No newline at end of file diff --git a/variants/t1000-e/T1000eBoard.h b/variants/t1000-e/T1000eBoard.h index e6ceb4fe..ba8bf0c1 100644 --- a/variants/t1000-e/T1000eBoard.h +++ b/variants/t1000-e/T1000eBoard.h @@ -7,17 +7,10 @@ class T1000eBoard : public NRF52BoardDCDC { protected: uint8_t btn_prev_state; - KeyValueStore* _prefs = NULL; - bool _buzzer_muted = false; - - void setBuzzerEnabled(bool enable); public: T1000eBoard() : NRF52Board("T1000E_OTA") {} void begin(); - void attachDynamicPrefs(KeyValueStore* prefs); - bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) override; - void loop() override; uint16_t getBattMilliVolts() override { #ifdef BATTERY_PIN From edb94d3fdcd0fb91397fa37720e39e132bf4865d Mon Sep 17 00:00:00 2001 From: R0ck Date: Sat, 17 Oct 2026 23:53:27 +0100 Subject: [PATCH 19/79] Apply buzzer setting changes in the UI so no reboot needed. --- examples/companion_radio/ui-new/UITask.cpp | 1 + examples/companion_radio/ui-orig/UITask.cpp | 1 + examples/companion_radio/ui-tiny/UITask.cpp | 1 + 3 files changed, 3 insertions(+) diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index bc25de79..e43fc5ea 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -1015,6 +1015,7 @@ void UITask::loop() { userLedHandler(); #ifdef PIN_BUZZER + if (buzzer.isQuiet() != (bool)_node_prefs->buzzer_quiet) buzzer.quiet(_node_prefs->buzzer_quiet); if (buzzer.isPlaying()) buzzer.loop(); #endif diff --git a/examples/companion_radio/ui-orig/UITask.cpp b/examples/companion_radio/ui-orig/UITask.cpp index db8772f4..8ae57c7a 100644 --- a/examples/companion_radio/ui-orig/UITask.cpp +++ b/examples/companion_radio/ui-orig/UITask.cpp @@ -485,6 +485,7 @@ void UITask::loop() { userLedHandler(); #ifdef PIN_BUZZER + if (buzzer.isQuiet() != (bool)_node_prefs->buzzer_quiet) buzzer.quiet(_node_prefs->buzzer_quiet); if (buzzer.isPlaying()) buzzer.loop(); #endif diff --git a/examples/companion_radio/ui-tiny/UITask.cpp b/examples/companion_radio/ui-tiny/UITask.cpp index 7b70f836..6bf33849 100644 --- a/examples/companion_radio/ui-tiny/UITask.cpp +++ b/examples/companion_radio/ui-tiny/UITask.cpp @@ -691,6 +691,7 @@ void UITask::loop() { userLedHandler(); #ifdef PIN_BUZZER + if (buzzer.isQuiet() != (bool)_node_prefs->buzzer_quiet) buzzer.quiet(_node_prefs->buzzer_quiet); if (buzzer.isPlaying()) buzzer.loop(); #endif From ad0324d354fa9238095956c3d0fb2d701a843e37 Mon Sep 17 00:00:00 2001 From: Radek <“6479266+rbrus@users.noreply.github.com”> Date: Sun, 18 Oct 2026 09:21:53 +0200 Subject: [PATCH 20/79] added dynamic wifi to: lilygo t-beam supreme sx1262 ble companion --- variants/lilygo_tbeam_supreme_SX1262/platformio.ini | 2 ++ 1 file changed, 2 insertions(+) diff --git a/variants/lilygo_tbeam_supreme_SX1262/platformio.ini b/variants/lilygo_tbeam_supreme_SX1262/platformio.ini index af4a8eaf..18a82802 100644 --- a/variants/lilygo_tbeam_supreme_SX1262/platformio.ini +++ b/variants/lilygo_tbeam_supreme_SX1262/platformio.ini @@ -131,11 +131,13 @@ build_flags = -D MAX_GROUP_CHANNELS=40 -D BLE_PIN_CODE=123456 -D OFFLINE_QUEUE_SIZE=256 + -D ENABLE_WIFI_INTERFACE ; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=8 ; -D MESH_DEBUG=1 build_src_filter = ${T_Beam_S3_Supreme_SX1262.build_src_filter} + + + + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> From c2d01f3c416c59107d24e01d138bf0ae18a44829 Mon Sep 17 00:00:00 2001 From: Marcel Verdult Date: Mon, 19 Oct 2026 23:19:42 +0200 Subject: [PATCH 21/79] fix(meshtracker_x1): inherit MicroNMEA in every environment of the variant What changes - variants/meshtracker_x1/platformio.ini moves stevemarple/MicroNMEA from the four environments that listed it into the [MeshTracker_X1] base section, the way nano_g2_ultra already keeps it, and drops the four copies. Why - MeshTracker_X1_kiss_modem was the one environment of this variant that did not list the library, so it did not build: src/helpers/sensors/MicroNMEALocationProvider.h:4: fatal error: MicroNMEA.h: No such file or directory variants/meshtracker_x1/target.cpp includes the location provider unconditionally and every environment of this variant compiles target.cpp, so every one of them needs the library. Putting it in the base section makes that true by construction rather than by repeating the line and hoping none is forgotten, which is exactly what happened here. Compatibility - All five environments of the variant were built, which is the whole reach of this change. MeshTracker_X1_kiss_modem now builds (text 240180, bss 18236; on unchanged dev it does not build at all). For the four that already built, text and bss are byte for byte identical to a build from unchanged dev c9fa617c with the same toolchain, so inheriting the library instead of listing it changes nothing for them: MeshTracker_X1_repeater text 299524 bss 32024, _room_server 292020 / 35740, _companion_radio_usb 316356 / 141000, _companion_radio_ble 322036 / 145432, each text +0 and bss +0 against dev. --- variants/meshtracker_x1/platformio.ini | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/variants/meshtracker_x1/platformio.ini b/variants/meshtracker_x1/platformio.ini index 2194d48d..80286460 100644 --- a/variants/meshtracker_x1/platformio.ini +++ b/variants/meshtracker_x1/platformio.ini @@ -34,6 +34,7 @@ build_src_filter = ${nrf52_base.build_src_filter} +<../variants/meshtracker_x1> lib_deps = ${nrf52_base.lib_deps} https://github.com/adafruit/Adafruit_SPA06_003/archive/refs/tags/1.0.2.zip + stevemarple/MicroNMEA @ ^2.0.6 debug_tool = jlink upload_protocol = nrfutil @@ -51,7 +52,6 @@ build_flags = ${MeshTracker_X1.build_flags} build_src_filter = ${MeshTracker_X1.build_src_filter} +<../examples/simple_repeater> lib_deps = ${MeshTracker_X1.lib_deps} - stevemarple/MicroNMEA @ ^2.0.6 [env:MeshTracker_X1_room_server] extends = MeshTracker_X1 @@ -67,7 +67,6 @@ build_flags = ${MeshTracker_X1.build_flags} build_src_filter = ${MeshTracker_X1.build_src_filter} +<../examples/simple_room_server> lib_deps = ${MeshTracker_X1.lib_deps} - stevemarple/MicroNMEA @ ^2.0.6 [env:MeshTracker_X1_companion_radio_usb] extends = MeshTracker_X1 @@ -94,7 +93,6 @@ build_src_filter = ${MeshTracker_X1.build_src_filter} +<../examples/companion_radio/ui-orig/*.cpp> lib_deps = ${MeshTracker_X1.lib_deps} densaugeo/base64 @ ~1.4.0 - stevemarple/MicroNMEA @ ^2.0.6 end2endzone/NonBlockingRTTTL@^1.3.0 adafruit/Adafruit DRV2605 Library @ ^1.2.4 @@ -127,7 +125,6 @@ build_src_filter = ${MeshTracker_X1.build_src_filter} +<../examples/companion_radio/ui-orig/*.cpp> lib_deps = ${MeshTracker_X1.lib_deps} densaugeo/base64 @ ~1.4.0 - stevemarple/MicroNMEA @ ^2.0.6 end2endzone/NonBlockingRTTTL@^1.3.0 adafruit/Adafruit DRV2605 Library @ ^1.2.4 From adb01c473e966f0cf8b19960906357d79bb70853 Mon Sep 17 00:00:00 2001 From: rado <6479266+rbrus@users.noreply.github.com> Date: Tue, 20 Oct 2026 05:56:02 +0200 Subject: [PATCH 22/79] Skip empty anon contact slots in peer/contact lookups (prevent null-key ECDH sink) --- src/helpers/BaseChatMesh.cpp | 10 +- src/helpers/ContactInfo.h | 6 + .../test_empty_contact_slots.cpp | 230 ++++++++++++++++++ 3 files changed, 245 insertions(+), 1 deletion(-) create mode 100644 test/test_empty_contact_slots/test_empty_contact_slots.cpp diff --git a/src/helpers/BaseChatMesh.cpp b/src/helpers/BaseChatMesh.cpp index 28592415..2c9ad745 100644 --- a/src/helpers/BaseChatMesh.cpp +++ b/src/helpers/BaseChatMesh.cpp @@ -128,6 +128,7 @@ void BaseChatMesh::onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, ContactInfo* from = NULL; for (int i = 0; i < num_contacts; i++) { + if (contacts[i].isEmptySlot()) continue; if (id.matches(contacts[i].id)) { // is from one of our contacts from = &contacts[i]; if (timestamp <= from->last_advert_timestamp) { // check for replay attacks!! @@ -203,6 +204,11 @@ void BaseChatMesh::onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, int BaseChatMesh::searchPeersByHash(const uint8_t* hash) { int n = 0; for (int i = 0; i < num_contacts && n < MAX_SEARCH_RESULTS; i++) { + // Skip empty/unconfigured anon slots. An empty slot has an all-zero pub_key + // (an order-4 Edwards25519 point whose clamped X25519 key exchange yields an + // all-zero shared secret for any private key) and would otherwise match + // src_hash == 0x00 as a null-key peer sink while consuming search slots. + if (contacts[i].isEmptySlot()) continue; if (contacts[i].id.isHashMatch(hash)) { matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods) } @@ -866,6 +872,7 @@ ContactInfo* BaseChatMesh::searchContactsByPrefix(const char* name_prefix) { int len = strlen(name_prefix); for (int i = 0; i < num_contacts; i++) { auto c = &contacts[i]; + if (c->isEmptySlot() || c->name[0] == 0) continue; if (memcmp(c->name, name_prefix, len) == 0) return c; } return NULL; // not found @@ -874,6 +881,7 @@ ContactInfo* BaseChatMesh::searchContactsByPrefix(const char* name_prefix) { ContactInfo* BaseChatMesh::lookupContactByPubKey(const uint8_t* pub_key, int prefix_len) { for (int i = 0; i < num_contacts; i++) { auto c = &contacts[i]; + if (c->isEmptySlot()) continue; if (memcmp(c->id.pub_key, pub_key, prefix_len) == 0) return c; } return NULL; // not found @@ -891,7 +899,7 @@ bool BaseChatMesh::addContact(const ContactInfo& contact) { bool BaseChatMesh::removeContact(ContactInfo& contact) { int idx = 0; - while (idx < num_contacts && !contacts[idx].id.matches(contact.id)) { + while (idx < num_contacts && (contacts[idx].isEmptySlot() || !contacts[idx].id.matches(contact.id))) { idx++; } if (idx >= num_contacts) return false; // not found diff --git a/src/helpers/ContactInfo.h b/src/helpers/ContactInfo.h index 5a156c82..a401117e 100644 --- a/src/helpers/ContactInfo.h +++ b/src/helpers/ContactInfo.h @@ -31,6 +31,12 @@ struct ContactInfo { bool isTelemLocAllowed() const { return flags & 0x04; } bool isTelemEnvAllowed() const { return flags & 0x08; } bool isRemoteCLIAllowed() const { return flags & 0x10; } + bool isEmptySlot() const { + for (int i = 0; i < PUB_KEY_SIZE; i++) { + if (id.pub_key[i] != 0) return false; + } + return true; + } private: mutable uint8_t shared_secret[PUB_KEY_SIZE]; diff --git a/test/test_empty_contact_slots/test_empty_contact_slots.cpp b/test/test_empty_contact_slots/test_empty_contact_slots.cpp new file mode 100644 index 00000000..cb4d5912 --- /dev/null +++ b/test/test_empty_contact_slots/test_empty_contact_slots.cpp @@ -0,0 +1,230 @@ +#include +#include +#include + +#include "Dispatcher.cpp" +#include "Mesh.cpp" +#include "helpers/AdvertDataHelpers.cpp" +#include "helpers/BaseChatMesh.cpp" + +void StrHelper::strncpy(char* dest, const char* src, size_t buf_sz) { + if (buf_sz == 0) return; + std::strncpy(dest, src, buf_sz - 1); + dest[buf_sz - 1] = 0; +} + +namespace mesh { + +Identity::Identity() { + memset(pub_key, 0, sizeof(pub_key)); +} + +bool Identity::verify(const uint8_t*, const uint8_t*, int) const { + return true; +} + +LocalIdentity::LocalIdentity() : Identity() { + memset(prv_key, 0, sizeof(prv_key)); +} + +void LocalIdentity::sign(uint8_t* sig, const uint8_t*, int) const { + memset(sig, 0, SIGNATURE_SIZE); +} + +void LocalIdentity::calcSharedSecret(uint8_t* secret, const uint8_t* other_pub_key) const { + ed25519_key_exchange(secret, other_pub_key, prv_key); +} + +} // namespace mesh + +namespace { + +class DummyRadio : public mesh::Radio { +public: + int recvRaw(uint8_t*, int) override { return 0; } + uint32_t getEstAirtimeFor(int) override { return 10; } + float packetScore(float, int) override { return 1.0f; } + bool startSendRaw(const uint8_t*, int) override { return true; } + bool isSendComplete() override { return true; } + void onSendFinished() override {} + bool isInRecvMode() const override { return true; } +}; + +class DummyMillisecondClock : public mesh::MillisecondClock { +public: + unsigned long getMillis() override { return 1000; } +}; + +class DummyRNG : public mesh::RNG { +public: + void random(uint8_t* dest, size_t len) override { memset(dest, 0x42, len); } +}; + +class DummyRTCClock : public mesh::RTCClock { + uint32_t _now = 1700000000; +public: + uint32_t getCurrentTime() override { return _now; } + void setCurrentTime(uint32_t time) override { _now = time; } +}; + +class DummyPacketManager : public mesh::PacketManager { +public: + mesh::Packet* allocNew() override { return nullptr; } + void free(mesh::Packet*) override {} + void queueOutbound(mesh::Packet*, uint8_t, uint32_t) override {} + mesh::Packet* getNextOutbound(uint32_t) override { return nullptr; } + int getOutboundCount(uint32_t) const override { return 0; } + int getOutboundTotal() const override { return 0; } + int getFreeCount() const override { return 16; } + mesh::Packet* getOutboundByIdx(int) override { return nullptr; } + mesh::Packet* removeOutboundByIdx(int) override { return nullptr; } + void queueInbound(mesh::Packet*, uint32_t) override {} + mesh::Packet* getNextInbound(uint32_t) override { return nullptr; } +}; + +class DummyMeshTables : public mesh::MeshTables { +public: + bool wasSeen(const mesh::Packet*) override { return false; } + void markSeen(const mesh::Packet*) override {} + void clear(const mesh::Packet*) override {} +}; + +class TestChatMesh : public BaseChatMesh { +public: + int messages_received = 0; + + TestChatMesh(mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, + mesh::RTCClock& rtc, mesh::PacketManager& mgr, mesh::MeshTables& tables) + : BaseChatMesh(radio, ms, rng, rtc, mgr, tables) {} + + void onDiscoveredContact(ContactInfo&, bool, uint8_t, const uint8_t*) override {} + ContactInfo* processAck(const uint8_t*) override { return nullptr; } + void onContactPathUpdated(const ContactInfo&) override {} + void onMessageRecv(const ContactInfo&, mesh::Packet*, uint32_t, const char*) override { + messages_received++; + } + void onCommandDataRecv(const ContactInfo&, mesh::Packet*, uint32_t, const char*) override {} + void onCLICommandRecv(const ContactInfo&, mesh::Packet*, uint32_t, const char*, char*) override {} + void onSignedMessageRecv(const ContactInfo&, mesh::Packet*, uint32_t, const uint8_t*, const char*) override {} + void onChannelMessageRecv(const mesh::GroupChannel&, mesh::Packet*, uint32_t, const char*) override {} + uint8_t onContactRequest(const ContactInfo&, uint32_t, const uint8_t*, uint8_t, uint8_t*) override { return 0; } + void onContactResponse(const ContactInfo&, const uint8_t*, uint8_t) override {} + uint32_t calcFloodTimeoutMillisFor(uint32_t) const override { return 1000; } + uint32_t calcDirectTimeoutMillisFor(uint32_t, uint8_t) const override { return 1000; } + void onSendTimeout() override {} + + using BaseChatMesh::resetContacts; + using BaseChatMesh::searchPeersByHash; + using BaseChatMesh::getPeerSharedSecret; + using mesh::Mesh::onRecvPacket; +}; + +struct MeshFixture { + DummyRadio radio; + DummyMillisecondClock ms; + DummyRNG rng; + DummyRTCClock rtc; + DummyPacketManager mgr; + DummyMeshTables tables; + TestChatMesh chat{radio, ms, rng, rtc, mgr, tables}; +}; + +} // namespace + +TEST(EmptyContactSlots, ZeroPubKeyProducesAllZeroSharedSecretForAnyPrivateKey) { + ContactInfo empty_slot; + memset(&empty_slot, 0, sizeof(empty_slot)); + EXPECT_TRUE(empty_slot.isEmptySlot()); + + uint8_t raw_prv[PRV_KEY_SIZE]; + for (int i = 0; i < PRV_KEY_SIZE; i++) { + raw_prv[i] = static_cast(0xA5 ^ (i * 13 + 7)); + } + uint8_t secret[PUB_KEY_SIZE]; + ed25519_key_exchange(secret, empty_slot.id.pub_key, raw_prv); + + uint8_t expected_zeroes[PUB_KEY_SIZE] = { 0 }; + EXPECT_EQ(0, memcmp(secret, expected_zeroes, PUB_KEY_SIZE)); +} + +TEST(EmptyContactSlots, NullKeyPeerPacketIsRejectedWhenAnonSlotsAreEmpty) { + MeshFixture fx; + fx.chat.self_id.pub_key[0] = 0x42; + + // Craft a PAYLOAD_TYPE_TXT_MSG addressed to self_id (dest_hash=0x42) with src_hash=0x00, + // encrypted and MAC'd under the all-zero 32-byte key that an empty ContactInfo slot derives. + uint8_t zero_secret[PUB_KEY_SIZE] = { 0 }; + uint8_t plaintext[16] = { 0 }; + uint32_t ts = 1700000001; + memcpy(plaintext, &ts, 4); + plaintext[4] = (TXT_TYPE_PLAIN << 2); + strcpy(reinterpret_cast(&plaintext[5]), "forged"); + + mesh::Packet pkt; + pkt.header = ROUTE_TYPE_FLOOD | (PAYLOAD_TYPE_TXT_MSG << PH_TYPE_SHIFT); + pkt.path_len = 0; + pkt.payload[0] = 0x42; // dest_hash (matches fx.chat.self_id) + pkt.payload[1] = 0x00; // src_hash (matches all-zero pub_key if empty slots are not skipped) + int enc_len = mesh::Utils::encryptThenMAC(zero_secret, &pkt.payload[2], plaintext, 12); + pkt.payload_len = static_cast(2 + enc_len); + + fx.chat.onRecvPacket(&pkt); + EXPECT_EQ(0, fx.chat.messages_received); +} + +TEST(EmptyContactSlots, SearchPeersByHashSkipsEmptyAnonSlotsAndFindsRealZeroPrefixPeer) { + MeshFixture fx; + const uint8_t zero_hash = 0x00; + + // Freshly reset contacts has MAX_ANON_CONTACTS (8) zeroed transient slots. + EXPECT_EQ(0, fx.chat.searchPeersByHash(&zero_hash)); + + // Add a legitimate permanent contact whose public key starts with 0x00. + ContactInfo peer; + memset(&peer, 0, sizeof(peer)); + peer.type = ADV_TYPE_CHAT; + peer.lastmod = 1700000100; + strcpy(peer.name, "Alice"); + peer.id.pub_key[0] = 0x00; + for (int i = 1; i < PUB_KEY_SIZE; i++) { + peer.id.pub_key[i] = static_cast(i); + } + ASSERT_TRUE(fx.chat.addContact(peer)); + + // Only the populated contact at index MAX_ANON_CONTACTS should match. + EXPECT_EQ(1, fx.chat.searchPeersByHash(&zero_hash)); + + // Lookup by pubkey and name prefix must also skip the empty transient slots. + uint8_t zero_prefix[6] = { 0 }; + EXPECT_EQ(nullptr, fx.chat.lookupContactByPubKey(zero_prefix, sizeof(zero_prefix))); + + ContactInfo* found = fx.chat.lookupContactByPubKey(peer.id.pub_key, 6); + ASSERT_NE(nullptr, found); + EXPECT_STREQ("Alice", found->name); + + ContactInfo* by_name = fx.chat.searchContactsByPrefix(""); + ASSERT_NE(nullptr, by_name); + EXPECT_STREQ("Alice", by_name->name); +} + +TEST(EmptyContactSlots, PopulatedTransientAnonSlotStillMatchesEvenWhenLastmodIsZero) { + MeshFixture fx; + const uint8_t zero_hash = 0x00; + + ContactInfo anon; + memset(&anon, 0, sizeof(anon)); + anon.type = ADV_TYPE_NONE; + anon.lastmod = 0; // e.g. RTC not yet initialised on nRF52 + anon.id.pub_key[0] = 0x00; + anon.id.pub_key[1] = 0x7F; + ASSERT_TRUE(fx.chat.addContact(anon)); + + EXPECT_FALSE(anon.isEmptySlot()); + EXPECT_EQ(1, fx.chat.searchPeersByHash(&zero_hash)); + EXPECT_NE(nullptr, fx.chat.lookupContactByPubKey(anon.id.pub_key, PUB_KEY_SIZE)); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} From 75ea17ea46be98e40fda8a99b64d9d2cd2fc8cfe Mon Sep 17 00:00:00 2001 From: liamcottle Date: Wed, 21 Oct 2026 15:41:11 +1300 Subject: [PATCH 23/79] implement new auto detect display for sh1106 and ssd1306 --- src/helpers/ui/AutoDetectDisplay.cpp | 45 ++++++++++++++++++++++++++++ src/helpers/ui/AutoDetectDisplay.h | 32 ++++++++++++++++++++ src/helpers/ui/SH1106Display.cpp | 18 +++++------ variants/rak4631/platformio.ini | 23 +++++++------- variants/rak4631/target.h | 2 +- 5 files changed, 100 insertions(+), 20 deletions(-) create mode 100644 src/helpers/ui/AutoDetectDisplay.cpp create mode 100644 src/helpers/ui/AutoDetectDisplay.h diff --git a/src/helpers/ui/AutoDetectDisplay.cpp b/src/helpers/ui/AutoDetectDisplay.cpp new file mode 100644 index 00000000..e3537ab2 --- /dev/null +++ b/src/helpers/ui/AutoDetectDisplay.cpp @@ -0,0 +1,45 @@ +#include "AutoDetectDisplay.h" +#include + +int AutoDetectDisplay::getDisplayStatus(TwoWire& wire, uint8_t addr) { + int status = -1; + for(int i = 0; i < 4; i++){ + + // request display status + wire.beginTransmission(addr); + wire.write((uint8_t)0x00); + + // ensure response received + if (wire.endTransmission() != 0) return -1; // expect success + if (wire.requestFrom((int)addr, 1) == 0) return -1; // expect at least 1 byte + + // ensure two consecutive reads are the same + int previous = status; + status = wire.read() & 0x0F; + if(status == previous){ + break; + } + + } + return status; +} + +bool AutoDetectDisplay::begin() { + + // request status from display address + int status = getDisplayStatus(Wire, DISPLAY_ADDRESS); + MESH_DEBUG_PRINTLN("AutoDetectDisplay: status=0x%02X", status); + + // detect SH1106 + if(status == 0x00 || status == 0x08){ + MESH_DEBUG_PRINTLN("AutoDetectDisplay: SH1106 detected"); + _impl = &_sh1106; + return _sh1106.begin(); + } + + // fallback to SSD1306 + MESH_DEBUG_PRINTLN("AutoDetectDisplay: falling back to SSD1306"); + _impl = &_ssd1306; + return _ssd1306.begin(); + +} diff --git a/src/helpers/ui/AutoDetectDisplay.h b/src/helpers/ui/AutoDetectDisplay.h new file mode 100644 index 00000000..7208d4f5 --- /dev/null +++ b/src/helpers/ui/AutoDetectDisplay.h @@ -0,0 +1,32 @@ +#pragma once + +#include "DisplayDriver.h" +#include "SSD1306Display.h" +#include "SH1106Display.h" + +// Auto detects SH1106 display at runtime, otherwise falls back to using SSD1306 +class AutoDetectDisplay : public DisplayDriver { + DisplayDriver* _impl; + SSD1306Display _ssd1306; + SH1106Display _sh1106; + + int getDisplayStatus(TwoWire& wire, uint8_t addr); +public: + AutoDetectDisplay() : DisplayDriver(128, 64), _impl(&_ssd1306) { } + bool begin(); + + bool isOn() override { return _impl->isOn(); } + void turnOn() override { _impl->turnOn(); } + void turnOff() override { _impl->turnOff(); } + void clear() override { _impl->clear(); } + void startFrame(ColorVal bkg = UIColor::window_bkg) override { _impl->startFrame(bkg); } + void setTextSize(int sz) override { _impl->setTextSize(sz); } + void setColor(ColorVal c) override { _impl->setColor(c); } + void setCursor(int x, int y) override { _impl->setCursor(x, y); } + void print(const char* str) override { _impl->print(str); } + void fillRect(int x, int y, int w, int h) override { _impl->fillRect(x, y, w, h); } + void drawRect(int x, int y, int w, int h) override { _impl->drawRect(x, y, w, h); } + void drawXbm(int x, int y, const uint8_t* bits, int w, int h) override { _impl->drawXbm(x, y, bits, w, h); } + uint16_t getTextWidth(const char* str) override { return _impl->getTextWidth(str); } + void endFrame() override { _impl->endFrame(); } +}; diff --git a/src/helpers/ui/SH1106Display.cpp b/src/helpers/ui/SH1106Display.cpp index 8b91d857..e290b355 100644 --- a/src/helpers/ui/SH1106Display.cpp +++ b/src/helpers/ui/SH1106Display.cpp @@ -10,15 +10,15 @@ bool SH1106Display::i2c_probe(TwoWire &wire, uint8_t addr) } // Color scheme -ColorVal UIColor::window_bkg = SH110X_BLACK; -ColorVal UIColor::title_bkg = SH110X_BLACK; -ColorVal UIColor::title_txt = SH110X_WHITE; -ColorVal UIColor::primary_txt = SH110X_WHITE; -ColorVal UIColor::secondary_txt = SH110X_WHITE; -ColorVal UIColor::warning_txt = SH110X_WHITE; -ColorVal UIColor::popup_bkg = SH110X_BLACK; -ColorVal UIColor::popup_txt = SH110X_WHITE; -ColorVal UIColor::corp_blue = SH110X_WHITE; +__attribute__((weak)) ColorVal UIColor::window_bkg = SH110X_BLACK; +__attribute__((weak)) ColorVal UIColor::title_bkg = SH110X_BLACK; +__attribute__((weak)) ColorVal UIColor::title_txt = SH110X_WHITE; +__attribute__((weak)) ColorVal UIColor::primary_txt = SH110X_WHITE; +__attribute__((weak)) ColorVal UIColor::secondary_txt = SH110X_WHITE; +__attribute__((weak)) ColorVal UIColor::warning_txt = SH110X_WHITE; +__attribute__((weak)) ColorVal UIColor::popup_bkg = SH110X_BLACK; +__attribute__((weak)) ColorVal UIColor::popup_txt = SH110X_WHITE; +__attribute__((weak)) ColorVal UIColor::corp_blue = SH110X_WHITE; bool SH1106Display::begin() { diff --git a/variants/rak4631/platformio.ini b/variants/rak4631/platformio.ini index d2781d9f..4c13b0d7 100644 --- a/variants/rak4631/platformio.ini +++ b/variants/rak4631/platformio.ini @@ -28,11 +28,14 @@ build_src_filter = ${nrf52_base.build_src_filter} +<../variants/rak4631> + + + + + + + lib_deps = ${nrf52_base.lib_deps} ${sensor_base.lib_deps} adafruit/Adafruit SSD1306 @ ^2.5.13 + adafruit/Adafruit SH110X @ ^2.1.13 sparkfun/SparkFun u-blox GNSS Arduino Library@^2.2.27 boschsensortec/BSEC Software Library @ ^1.8.1492 @@ -40,7 +43,7 @@ lib_deps = extends = rak4631 build_flags = ${rak4631.build_flags} - -D DISPLAY_CLASS=SSD1306Display + -D DISPLAY_CLASS=AutoDetectDisplay -D ADVERT_NAME='"RAK4631 Repeater"' -D ADVERT_LAT=0.0 -D ADVERT_LON=0.0 @@ -56,7 +59,7 @@ build_src_filter = ${rak4631.build_src_filter} extends = rak4631 build_flags = ${rak4631.build_flags} - -D DISPLAY_CLASS=SSD1306Display + -D DISPLAY_CLASS=AutoDetectDisplay -D ADVERT_NAME='"RAK4631 Repeater"' -D ADVERT_LAT=0.0 -D ADVERT_LON=0.0 @@ -75,7 +78,7 @@ lib_deps = extends = rak4631 build_flags = ${rak4631.build_flags} - -D DISPLAY_CLASS=SSD1306Display + -D DISPLAY_CLASS=AutoDetectDisplay -D ADVERT_NAME='"RS232 Bridge"' -D ADVERT_LAT=0.0 -D ADVERT_LON=0.0 @@ -98,7 +101,7 @@ build_src_filter = ${rak4631.build_src_filter} extends = rak4631 build_flags = ${rak4631.build_flags} - -D DISPLAY_CLASS=SSD1306Display + -D DISPLAY_CLASS=AutoDetectDisplay -D ADVERT_NAME='"RS232 Bridge"' -D ADVERT_LAT=0.0 -D ADVERT_LON=0.0 @@ -121,7 +124,7 @@ build_src_filter = ${rak4631.build_src_filter} extends = rak4631 build_flags = ${rak4631.build_flags} - -D DISPLAY_CLASS=SSD1306Display + -D DISPLAY_CLASS=AutoDetectDisplay -D ADVERT_NAME='"Test Room"' -D ADVERT_LAT=0.0 -D ADVERT_LON=0.0 @@ -137,7 +140,7 @@ build_src_filter = ${rak4631.build_src_filter} extends = rak4631 build_flags = ${rak4631.build_flags} - -D DISPLAY_CLASS=SSD1306Display + -D DISPLAY_CLASS=AutoDetectDisplay -D ADVERT_NAME='"RAK4631 Room Server"' -D ADVERT_LAT=0.0 -D ADVERT_LON=0.0 @@ -161,7 +164,7 @@ build_flags = -I examples/companion_radio/ui-new -D PIN_USER_BTN=9 -D PIN_USER_BTN_ANA=31 - -D DISPLAY_CLASS=SSD1306Display + -D DISPLAY_CLASS=AutoDetectDisplay -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D ENABLE_USB_INTERFACE @@ -186,7 +189,7 @@ build_flags = -I examples/companion_radio/ui-new -D PIN_USER_BTN=9 -D PIN_USER_BTN_ANA=31 - -D DISPLAY_CLASS=SSD1306Display + -D DISPLAY_CLASS=AutoDetectDisplay -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D ETHERNET_ENABLED=1 @@ -215,7 +218,7 @@ build_flags = -I examples/companion_radio/ui-new -D PIN_USER_BTN=9 -D PIN_USER_BTN_ANA=31 - -D DISPLAY_CLASS=SSD1306Display + -D DISPLAY_CLASS=AutoDetectDisplay -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D BLE_PIN_CODE=123456 @@ -251,7 +254,7 @@ lib_deps = extends = rak4631 build_flags = ${rak4631.build_flags} - -D DISPLAY_CLASS=SSD1306Display + -D DISPLAY_CLASS=AutoDetectDisplay -D ADVERT_NAME='"RAK4631 Sensor"' -D ADVERT_LAT=0.0 -D ADVERT_LON=0.0 diff --git a/variants/rak4631/target.h b/variants/rak4631/target.h index 1529f904..c04cd4e4 100644 --- a/variants/rak4631/target.h +++ b/variants/rak4631/target.h @@ -9,7 +9,7 @@ #include #ifdef DISPLAY_CLASS - #include + #include extern DISPLAY_CLASS display; #include extern MomentaryButton user_btn; From 8c4769d1ed7ccd8690eb228d732150b9a3fb1c5f Mon Sep 17 00:00:00 2001 From: Confituurke <9595028+Confituurke@users.noreply.github.com> Date: Wed, 21 Oct 2026 11:24:34 +0200 Subject: [PATCH 24/79] Use two decimals only for exact quarter-hour offsets --- examples/companion_radio/MyMesh.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 2ea539db..cc6340bb 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2192,7 +2192,8 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* } if (strcmp(command, "get tz.offset") == 0) { - sprintf(reply, ((int)(_prefs.tz_offset * 4) % 2) ? "> %.2f" : "> %.1f", _prefs.tz_offset); + float q = _prefs.tz_offset * 4; + sprintf(reply, (q == (int)q && ((int)q & 1)) ? "> %.2f" : "> %.1f", _prefs.tz_offset); return true; } if (memcmp(command, "set tz.offset ", 14) == 0) { From d1d06b92ab6b8879e0eed909df237bb224136ae3 Mon Sep 17 00:00:00 2001 From: Florent Date: Wed, 21 Oct 2026 14:08:56 -0400 Subject: [PATCH 25/79] refactoring eink devices behaviour --- examples/companion_radio/ui-new/UITask.cpp | 44 ++++++++++++++++------ examples/companion_radio/ui-new/UITask.h | 3 +- src/helpers/ui/DisplayDriver.h | 1 + src/helpers/ui/GxEPDDisplay.cpp | 6 ++- src/helpers/ui/GxEPDDisplay.h | 1 + variants/lilygo_techo/platformio.ini | 8 ++-- variants/lilygo_techo/target.cpp | 1 + variants/lilygo_techo/target.h | 1 + variants/thinknode_m1/platformio.ini | 7 ++++ variants/thinknode_m1/target.cpp | 1 + variants/thinknode_m1/target.h | 1 + variants/thinknode_m5/platformio.ini | 7 +++- variants/thinknode_m5/target.cpp | 1 + variants/thinknode_m5/target.h | 1 + variants/thinknode_m8/platformio.ini | 11 +++--- variants/thinknode_m8/target.cpp | 1 + variants/thinknode_m8/target.h | 1 + 17 files changed, 71 insertions(+), 25 deletions(-) diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index d48647b3..de9e8f58 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -197,11 +197,10 @@ class HomeScreen : public UIScreen { sensors_nb ++; } sensors_scroll = sensors_nb > UI_RECENT_LIST_SIZE; -#if AUTO_OFF_MILLIS > 0 - next_sensors_refresh = millis() + 5000; // refresh sensor values every 5 sec -#else - next_sensors_refresh = millis() + 60000; // refresh sensor values every 1 min -#endif + if (display.isEink()) // preserve eink displays + next_sensors_refresh = millis() + 60000; // refresh sensor values every 1 min + else + next_sensors_refresh = millis() + 5000; // refresh sensor values every 5 sec } } @@ -703,11 +702,7 @@ public: display.translateUTF8ToBlocks(filtered_msg, p->msg, sizeof(filtered_msg)); display.printWordWrap(filtered_msg, display.width()); -#if AUTO_OFF_MILLIS==0 // probably e-ink - return 10000; // 10 s -#else - return 1000; // next render after 1000 ms -#endif + return display.isEink() ? 10000 : 1000; // 10 s for eink } bool handleInput(char c) override { @@ -739,6 +734,9 @@ void UITask::begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* no #if defined(PIN_USER_BTN_ANA) analog_btn.begin(); #endif +#if defined(BACKLIGHT_BTN) + backlight_btn.begin(); +#endif _node_prefs = node_prefs; @@ -1002,13 +1000,30 @@ void UITask::loop() { #endif #if defined(BACKLIGHT_BTN) if (millis() > next_backlight_btn_check) { - bool touch_state = digitalRead(PIN_BUTTON2); + if (backlight_btn.isPressed()) { + if (!_display->isOn()) { + _display->turnOn(); + _next_refresh = 0; + } + _auto_off = millis() + AUTO_OFF_MILLIS; // extend auto-off timer + backlight_btn_pressed_at = millis(); // still pressed + } + bool touch_state = (millis() - backlight_btn_pressed_at > 5000); + // Backlight button events + int bev = backlight_btn.check(); + if (bev == BUTTON_EVENT_DOUBLE_CLICK) { + _display->forceFullRefresh(); + } else if (bev == BUTTON_EVENT_TRIPLE_CLICK) { + _display->blankScreen(); + _display->turnOff(); + backlight_btn_pressed_at = 0; + } #if defined(DISP_BACKLIGHT) digitalWrite(DISP_BACKLIGHT, !touch_state); #elif defined(EXP_PIN_BACKLIGHT) expander.digitalWrite(EXP_PIN_BACKLIGHT, !touch_state); #endif - next_backlight_btn_check = millis() + 300; + next_backlight_btn_check = millis() + 100; } #endif @@ -1056,6 +1071,11 @@ void UITask::loop() { } #endif if (millis() > _auto_off) { + #ifdef EINK_SCREENOFF_BLANK + if (curr != msg_preview) { // don't blank if messages are waiting + display.blankScreen(); + } + #endif _display->turnOff(); } #endif diff --git a/examples/companion_radio/ui-new/UITask.h b/examples/companion_radio/ui-new/UITask.h index 361b04d0..4d44bfe1 100644 --- a/examples/companion_radio/ui-new/UITask.h +++ b/examples/companion_radio/ui-new/UITask.h @@ -61,7 +61,8 @@ class UITask : public AbstractUITask { unsigned long _alert_expiry; int _msgcount; unsigned long ui_started_at, next_batt_chck; - int next_backlight_btn_check = 0; + unsigned long next_backlight_btn_check = 0; + unsigned long backlight_btn_pressed_at = 0; #ifdef PIN_STATUS_LED int led_state = 0; int next_led_change = 0; diff --git a/src/helpers/ui/DisplayDriver.h b/src/helpers/ui/DisplayDriver.h index 3e9e2dde..cbef3f98 100644 --- a/src/helpers/ui/DisplayDriver.h +++ b/src/helpers/ui/DisplayDriver.h @@ -27,6 +27,7 @@ public: virtual void turnOn() = 0; virtual void turnOff() = 0; virtual void clear() = 0; + virtual void blankScreen() {} // to cleanly erase screen before turning off virtual void startFrame(ColorVal bkg = UIColor::window_bkg) = 0; virtual void setTextSize(int sz) = 0; virtual void setColor(ColorVal c) = 0; diff --git a/src/helpers/ui/GxEPDDisplay.cpp b/src/helpers/ui/GxEPDDisplay.cpp index 332157eb..21b00afc 100644 --- a/src/helpers/ui/GxEPDDisplay.cpp +++ b/src/helpers/ui/GxEPDDisplay.cpp @@ -82,13 +82,17 @@ void GxEPDDisplay::turnOff() { expander.digitalWrite(EXP_PIN_BACKLIGHT, LOW); #endif _isOn = false; + last_display_crc_value=0; + display.hibernate(); +} + +void GxEPDDisplay::blankScreen() { // do full refresh before powering off to clear screen // no full refresh needed at wakeup display.clearScreen(0xFF); // Clears microcontroller side RAM display.writeScreenBuffer(0xFF); // Forces 0xFF (White) into the display controller's history registers resetPartialRefreshCounter(); last_display_crc_value=0; - display.hibernate(); } void GxEPDDisplay::clear() { diff --git a/src/helpers/ui/GxEPDDisplay.h b/src/helpers/ui/GxEPDDisplay.h index 8a37b72c..99b25d15 100644 --- a/src/helpers/ui/GxEPDDisplay.h +++ b/src/helpers/ui/GxEPDDisplay.h @@ -61,6 +61,7 @@ public: void turnOn() override; void turnOff() override; void clear() override; + void blankScreen() override; void startFrame(ColorVal bkg = UIColor::window_bkg) override; void setTextSize(int sz) override; void setColor(ColorVal c) override; diff --git a/variants/lilygo_techo/platformio.ini b/variants/lilygo_techo/platformio.ini index 81da2e48..14040622 100644 --- a/variants/lilygo_techo/platformio.ini +++ b/variants/lilygo_techo/platformio.ini @@ -32,8 +32,12 @@ build_flags = ${nrf52_base.build_flags} -D PIN_GPS_RESET_ACTIVE=LOW -D TELEM_BME280_ADDRESS=0x77 -D DISPLAY_CLASS=GxEPDDisplay + -D EINK_SCREENOFF_BLANK + -D UI_RECENT_LIST_SIZE=9 + -D UI_MSG_PREVIEW_SIZE=165 + -D EINK_MAX_PARTIAL_REFRESH=60 + -D AUTO_OFF_MILLIS=1800000 -D BACKLIGHT_BTN=PIN_BUTTON2 - -D AUTO_OFF_MILLIS=0 build_src_filter = ${nrf52_base.build_src_filter} + + @@ -91,7 +95,6 @@ build_flags = -D BLE_PIN_CODE=123456 ; -D BLE_DEBUG_LOGGING=1 -D OFFLINE_QUEUE_SIZE=256 - -D UI_RECENT_LIST_SIZE=9 -D UI_SENSORS_PAGE=1 -D UI_GPS_PAGE=1 ; -D MESH_PACKET_LOGGING=1 @@ -116,7 +119,6 @@ build_flags = -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 - -D UI_RECENT_LIST_SIZE=9 -D UI_SENSORS_PAGE=1 -D AUTO_SHUTDOWN_MILLIVOLTS=3300 -D QSPIFLASH=1 diff --git a/variants/lilygo_techo/target.cpp b/variants/lilygo_techo/target.cpp index 278fc76d..12b40d7e 100644 --- a/variants/lilygo_techo/target.cpp +++ b/variants/lilygo_techo/target.cpp @@ -23,6 +23,7 @@ EnvironmentSensorManager sensors = EnvironmentSensorManager(); #ifdef DISPLAY_CLASS DISPLAY_CLASS display; MomentaryButton user_btn(PIN_USER_BTN, 1000, true); + MomentaryButton backlight_btn(BACKLIGHT_BTN, 1000, true); #endif bool radio_init() { diff --git a/variants/lilygo_techo/target.h b/variants/lilygo_techo/target.h index 2b8a1783..a1668f03 100644 --- a/variants/lilygo_techo/target.h +++ b/variants/lilygo_techo/target.h @@ -22,6 +22,7 @@ extern EnvironmentSensorManager sensors; #ifdef DISPLAY_CLASS extern DISPLAY_CLASS display; extern MomentaryButton user_btn; + extern MomentaryButton backlight_btn; #endif bool radio_init(); diff --git a/variants/thinknode_m1/platformio.ini b/variants/thinknode_m1/platformio.ini index 89c48403..2e1aa48f 100644 --- a/variants/thinknode_m1/platformio.ini +++ b/variants/thinknode_m1/platformio.ini @@ -24,6 +24,13 @@ build_flags = ${nrf52_base.build_flags} -D SX126X_RX_BOOSTED_GAIN=1 -D LORA_TX_POWER=22 -D P_LORA_TX_LED=13 + -D UI_RECENT_LIST_SIZE=9 + -D UI_MSG_PREVIEW_SIZE=165 + -D EINK_MAX_PARTIAL_REFRESH=60 + -D BACKLIGHT_BTN=PIN_BUTTON2 + -D AUTO_OFF_MILLIS=1800000 + -D UI_NO_HIBERNATE + -D DISABLE_DIAGNOSTIC_OUTPUT build_src_filter = ${nrf52_base.build_src_filter} + + diff --git a/variants/thinknode_m1/target.cpp b/variants/thinknode_m1/target.cpp index 69306fc0..c430cee0 100644 --- a/variants/thinknode_m1/target.cpp +++ b/variants/thinknode_m1/target.cpp @@ -17,6 +17,7 @@ ThinkNodeM1SensorManager sensors = ThinkNodeM1SensorManager(nmea); #ifdef DISPLAY_CLASS DISPLAY_CLASS display; MomentaryButton user_btn(PIN_USER_BTN, 1000, true); + MomentaryButton backlight_btn(BACKLIGHT_BTN, 1000, true); #endif bool radio_init() { diff --git a/variants/thinknode_m1/target.h b/variants/thinknode_m1/target.h index ec1297be..d2d6aed1 100644 --- a/variants/thinknode_m1/target.h +++ b/variants/thinknode_m1/target.h @@ -40,6 +40,7 @@ extern ThinkNodeM1SensorManager sensors; #ifdef DISPLAY_CLASS extern DISPLAY_CLASS display; extern MomentaryButton user_btn; + extern MomentaryButton backlight_btn; #endif bool radio_init(); diff --git a/variants/thinknode_m5/platformio.ini b/variants/thinknode_m5/platformio.ini index a3f348b3..ed187dd2 100644 --- a/variants/thinknode_m5/platformio.ini +++ b/variants/thinknode_m5/platformio.ini @@ -26,8 +26,12 @@ build_flags = ${esp32_base.build_flags} -D EINK_SCALE_Y=1.5625f -D EINK_X_OFFSET=0 -D EINK_Y_OFFSET=10 + -D UI_RECENT_LIST_SIZE=9 + -D UI_MSG_PREVIEW_SIZE=165 + -D EINK_MAX_PARTIAL_REFRESH=60 -D BACKLIGHT_BTN=PIN_BUTTON2 - -D AUTO_OFF_MILLIS=0 + -D AUTO_OFF_MILLIS=1800000 + -D UI_NO_HIBERNATE -D DISABLE_DIAGNOSTIC_OUTPUT -D SX126X_DIO2_AS_RF_SWITCH=true -D SX126X_DIO3_TCXO_VOLTAGE=3.3 @@ -150,7 +154,6 @@ build_flags = -D MAX_GROUP_CHANNELS=40 -D BLE_PIN_CODE=123456 -D OFFLINE_QUEUE_SIZE=256 - -D UI_RECENT_LIST_SIZE=9 ; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 ; -D GPS_NMEA_DEBUG diff --git a/variants/thinknode_m5/target.cpp b/variants/thinknode_m5/target.cpp index be534f67..ec524df7 100644 --- a/variants/thinknode_m5/target.cpp +++ b/variants/thinknode_m5/target.cpp @@ -26,6 +26,7 @@ EnvironmentSensorManager sensors = EnvironmentSensorManager(); #ifdef DISPLAY_CLASS DISPLAY_CLASS display; MomentaryButton user_btn(PIN_USER_BTN, 1000, true); + MomentaryButton backlight_btn(BACKLIGHT_BTN, 1000, true); #endif bool radio_init() { diff --git a/variants/thinknode_m5/target.h b/variants/thinknode_m5/target.h index a613e390..7cce1edb 100644 --- a/variants/thinknode_m5/target.h +++ b/variants/thinknode_m5/target.h @@ -24,6 +24,7 @@ extern PCA9557 expander; #ifdef DISPLAY_CLASS extern DISPLAY_CLASS display; extern MomentaryButton user_btn; + extern MomentaryButton backlight_btn; #endif bool radio_init(); diff --git a/variants/thinknode_m8/platformio.ini b/variants/thinknode_m8/platformio.ini index db19e446..2c07038f 100644 --- a/variants/thinknode_m8/platformio.ini +++ b/variants/thinknode_m8/platformio.ini @@ -18,12 +18,16 @@ build_flags = ${nrf52_base.build_flags} -D P_LORA_SCLK=19 -D P_LORA_MISO=22 -D P_LORA_MOSI=20 - -D UI_SHOW_CLOCK=1 + -D DISPLAY_ROTATION=4 -D UI_HAS_ROTARY_INPUT=1 -D UI_HAS_NAV_INPUT=1 -D UI_RECENT_LIST_SIZE=9 -D UI_MSG_PREVIEW_SIZE=165 -D EINK_MAX_PARTIAL_REFRESH=60 + -D AUTO_OFF_MILLIS=1800000 + -D BACKLIGHT_BTN=PIN_BUTTON2 + -D UI_SHOW_CLOCK=1 + -D EINK_SCREENOFF_BLANK -D EINK_DISPLAY_MODEL=GxEPD2_154_D67 ; -D EINK_DISPLAY_MODEL=GxEPD2_154_GDEY0154D67 ; -D EINK_DISPLAY_MODEL=GxEPD2_150_BN @@ -92,10 +96,7 @@ build_flags = -D MAX_GROUP_CHANNELS=40 -D BLE_PIN_CODE=123456 # -D BLE_DEBUG_LOGGING=1 - -D DISPLAY_ROTATION=4 -D DISPLAY_CLASS=GxEPDDisplay - -D BACKLIGHT_BTN=PIN_BUTTON2 - -D AUTO_OFF_MILLIS=0 -D OFFLINE_QUEUE_SIZE=256 -D PIN_BUZZER=33 -D AUTO_SHUTDOWN_MILLIVOLTS=3300 @@ -133,8 +134,6 @@ build_flags = -D DISPLAY_ROTATION=4 -D QSPIFLASH=1 -D DISPLAY_CLASS=GxEPDDisplay - -D BACKLIGHT_BTN=PIN_BUTTON2 - -D AUTO_OFF_MILLIS=0 -D OFFLINE_QUEUE_SIZE=256 -D PIN_BUZZER=6 -D AUTO_SHUTDOWN_MILLIVOLTS=3300 diff --git a/variants/thinknode_m8/target.cpp b/variants/thinknode_m8/target.cpp index ac4ac100..69f3cc52 100644 --- a/variants/thinknode_m8/target.cpp +++ b/variants/thinknode_m8/target.cpp @@ -23,6 +23,7 @@ EnvironmentSensorManager sensors = EnvironmentSensorManager(); DISPLAY_CLASS display; MomentaryButton user_btn(PIN_USER_BTN, 1000, true); RotaryInputGPIO rotary_input(PIN_BUTTON1_A, PIN_BUTTON1_B); + MomentaryButton backlight_btn(BACKLIGHT_BTN, 1000, true); #endif bool radio_init() { diff --git a/variants/thinknode_m8/target.h b/variants/thinknode_m8/target.h index c3402a01..39928506 100644 --- a/variants/thinknode_m8/target.h +++ b/variants/thinknode_m8/target.h @@ -23,6 +23,7 @@ extern EnvironmentSensorManager sensors; #ifdef DISPLAY_CLASS extern DISPLAY_CLASS display; extern MomentaryButton user_btn; + extern MomentaryButton backlight_btn; extern RotaryInputGPIO rotary_input; #endif From afbab2de1652f35dca0aa010db3d7f3925de2f66 Mon Sep 17 00:00:00 2001 From: Florent Date: Wed, 21 Oct 2026 17:13:27 -0400 Subject: [PATCH 26/79] DisplayDriver: fixing alignment issue in vtable for nrf52 and epd display --- examples/companion_radio/ui-new/UITask.cpp | 6 +++++- src/helpers/ui/DisplayDriver.h | 3 ++- src/helpers/ui/GxEPDDisplay.cpp | 7 +++++-- src/helpers/ui/GxEPDDisplay.h | 3 ++- variants/lilygo_techo/platformio.ini | 2 +- variants/thinknode_m1/platformio.ini | 2 +- variants/thinknode_m5/platformio.ini | 2 +- variants/thinknode_m8/platformio.ini | 2 +- 8 files changed, 18 insertions(+), 9 deletions(-) diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index de9e8f58..6e987f87 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -955,7 +955,9 @@ void UITask::loop() { if (ev == BUTTON_EVENT_CLICK) { c = checkDisplayOn(KEY_ENTER); } else if (ev == BUTTON_EVENT_LONG_PRESS) { + display.blankScreen(); display.turnOff(); + display.powerOff(); } else if (ev == BUTTON_EVENT_DOUBLE_CLICK) { c = handleDoubleClick(KEY_SELECT); } else if (ev == BUTTON_EVENT_TRIPLE_CLICK) { @@ -1016,6 +1018,7 @@ void UITask::loop() { } else if (bev == BUTTON_EVENT_TRIPLE_CLICK) { _display->blankScreen(); _display->turnOff(); + _display->powerOff(); backlight_btn_pressed_at = 0; } #if defined(DISP_BACKLIGHT) @@ -1073,7 +1076,8 @@ void UITask::loop() { if (millis() > _auto_off) { #ifdef EINK_SCREENOFF_BLANK if (curr != msg_preview) { // don't blank if messages are waiting - display.blankScreen(); + _display->blankScreen(); + _display->powerOff(); } #endif _display->turnOff(); diff --git a/src/helpers/ui/DisplayDriver.h b/src/helpers/ui/DisplayDriver.h index cbef3f98..58147aa0 100644 --- a/src/helpers/ui/DisplayDriver.h +++ b/src/helpers/ui/DisplayDriver.h @@ -26,8 +26,9 @@ public: virtual void forceFullRefresh() {} // next refresh will be full for eink virtual void turnOn() = 0; virtual void turnOff() = 0; - virtual void clear() = 0; virtual void blankScreen() {} // to cleanly erase screen before turning off + virtual void powerOff() {} + virtual void clear() = 0; virtual void startFrame(ColorVal bkg = UIColor::window_bkg) = 0; virtual void setTextSize(int sz) = 0; virtual void setColor(ColorVal c) = 0; diff --git a/src/helpers/ui/GxEPDDisplay.cpp b/src/helpers/ui/GxEPDDisplay.cpp index 21b00afc..ce09423e 100644 --- a/src/helpers/ui/GxEPDDisplay.cpp +++ b/src/helpers/ui/GxEPDDisplay.cpp @@ -75,7 +75,11 @@ void GxEPDDisplay::turnOn() { } } -void GxEPDDisplay::turnOff() { +void GxEPDDisplay::powerOff() { + display.hibernate(); +} + +void GxEPDDisplay::turnOff() { // Only stops refresh #if defined(DISP_BACKLIGHT) && !defined(BACKLIGHT_BTN) digitalWrite(DISP_BACKLIGHT, LOW); #elif defined(EXP_PIN_BACKLIGHT) && !defined(BACKLIGHT_BTN) @@ -83,7 +87,6 @@ void GxEPDDisplay::turnOff() { #endif _isOn = false; last_display_crc_value=0; - display.hibernate(); } void GxEPDDisplay::blankScreen() { diff --git a/src/helpers/ui/GxEPDDisplay.h b/src/helpers/ui/GxEPDDisplay.h index 99b25d15..46274402 100644 --- a/src/helpers/ui/GxEPDDisplay.h +++ b/src/helpers/ui/GxEPDDisplay.h @@ -60,8 +60,9 @@ public: void resetPartialRefreshCounter() { _cycles_before_full_refresh = max_partial_refresh; }; void turnOn() override; void turnOff() override; - void clear() override; void blankScreen() override; + void powerOff() override; + void clear() override; void startFrame(ColorVal bkg = UIColor::window_bkg) override; void setTextSize(int sz) override; void setColor(ColorVal c) override; diff --git a/variants/lilygo_techo/platformio.ini b/variants/lilygo_techo/platformio.ini index 14040622..eb4a69e2 100644 --- a/variants/lilygo_techo/platformio.ini +++ b/variants/lilygo_techo/platformio.ini @@ -36,7 +36,7 @@ build_flags = ${nrf52_base.build_flags} -D UI_RECENT_LIST_SIZE=9 -D UI_MSG_PREVIEW_SIZE=165 -D EINK_MAX_PARTIAL_REFRESH=60 - -D AUTO_OFF_MILLIS=1800000 + -D AUTO_OFF_MILLIS=900000 -D BACKLIGHT_BTN=PIN_BUTTON2 build_src_filter = ${nrf52_base.build_src_filter} + diff --git a/variants/thinknode_m1/platformio.ini b/variants/thinknode_m1/platformio.ini index 2e1aa48f..c775ae3f 100644 --- a/variants/thinknode_m1/platformio.ini +++ b/variants/thinknode_m1/platformio.ini @@ -28,7 +28,7 @@ build_flags = ${nrf52_base.build_flags} -D UI_MSG_PREVIEW_SIZE=165 -D EINK_MAX_PARTIAL_REFRESH=60 -D BACKLIGHT_BTN=PIN_BUTTON2 - -D AUTO_OFF_MILLIS=1800000 + -D AUTO_OFF_MILLIS=900000 -D UI_NO_HIBERNATE -D DISABLE_DIAGNOSTIC_OUTPUT build_src_filter = ${nrf52_base.build_src_filter} diff --git a/variants/thinknode_m5/platformio.ini b/variants/thinknode_m5/platformio.ini index ed187dd2..1980575e 100644 --- a/variants/thinknode_m5/platformio.ini +++ b/variants/thinknode_m5/platformio.ini @@ -30,7 +30,7 @@ build_flags = ${esp32_base.build_flags} -D UI_MSG_PREVIEW_SIZE=165 -D EINK_MAX_PARTIAL_REFRESH=60 -D BACKLIGHT_BTN=PIN_BUTTON2 - -D AUTO_OFF_MILLIS=1800000 + -D AUTO_OFF_MILLIS=900000 -D UI_NO_HIBERNATE -D DISABLE_DIAGNOSTIC_OUTPUT -D SX126X_DIO2_AS_RF_SWITCH=true diff --git a/variants/thinknode_m8/platformio.ini b/variants/thinknode_m8/platformio.ini index 2c07038f..47d3a3fc 100644 --- a/variants/thinknode_m8/platformio.ini +++ b/variants/thinknode_m8/platformio.ini @@ -24,7 +24,7 @@ build_flags = ${nrf52_base.build_flags} -D UI_RECENT_LIST_SIZE=9 -D UI_MSG_PREVIEW_SIZE=165 -D EINK_MAX_PARTIAL_REFRESH=60 - -D AUTO_OFF_MILLIS=1800000 + -D AUTO_OFF_MILLIS=900000 -D BACKLIGHT_BTN=PIN_BUTTON2 -D UI_SHOW_CLOCK=1 -D EINK_SCREENOFF_BLANK From 97a6ff714c8809c88fafc628b388f882082f7d38 Mon Sep 17 00:00:00 2001 From: Marcel Verdult Date: Thu, 22 Oct 2026 09:33:07 +0000 Subject: [PATCH 27/79] fix(chat): refuse a negative text length for a group message CMD_SEND_CHANNEL_TXT_MSG reads txt_type, channel_idx and a 4 byte timestamp, so the frame needs 7 bytes before the text starts, and the branch had no length guard. For a shorter frame "len - i" is computed in size_t, wraps, and reaches sendGroupMessage() as a negative int. The clamp there tests "text_len + prefix_len > MAX_TEXT_LEN", which a negative value passes, and the following memcpy() converts the length back to a size_t: a 3 byte frame asks for 4294967292 bytes into a 197 byte stack buffer. Two guards, because there are two mistakes. The branch now states its minimum like most other branches of handleCmdFrame do, so a frame below 7 bytes is answered through the existing path instead of being parsed. And sendGroupMessage() refuses a negative length the way sendGroupData() in the same file already does, which protects every other caller. A frame of exactly 7 bytes keeps working and sends an empty message, as before. Evidence. On a T-Echo running dev c9fa617c, built with FIRMWARE_BUILD_DATE "f1-dev" and confirmed by "ver => v1.18.0 (Build: f1-dev)": CH_TXT len=7 -> RESP_CODE_OK GET_STATS core -> uptime=78s CH_TXT len=3 -> NO REPLY DEVICE_QUERY -> NO REPLY (three times over 8 s, node never came back) --- examples/companion_radio/MyMesh.cpp | 4 +++- src/helpers/BaseChatMesh.cpp | 5 +++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 99a9aa30..d74050be 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -1175,7 +1175,9 @@ void MyMesh::handleCmdFrame(size_t len) { ? ERR_CODE_NOT_FOUND : ERR_CODE_UNSUPPORTED_CMD); // unknown recipient, or unsupported TXT_TYPE_* } - } else if (cmd_frame[0] == CMD_SEND_CHANNEL_TXT_MSG) { // send GroupChannel text msg + } else if (cmd_frame[0] == CMD_SEND_CHANNEL_TXT_MSG && len >= 7) { // send GroupChannel text msg + // 7 = code, txt_type, channel_idx and the 4 byte timestamp; the text may be empty. + // Without this the text length below is computed as len - 7 and turns negative. int i = 1; uint8_t txt_type = cmd_frame[i++]; // should be TXT_TYPE_PLAIN uint8_t channel_idx = cmd_frame[i++]; diff --git a/src/helpers/BaseChatMesh.cpp b/src/helpers/BaseChatMesh.cpp index 28592415..2637bc32 100644 --- a/src/helpers/BaseChatMesh.cpp +++ b/src/helpers/BaseChatMesh.cpp @@ -516,6 +516,11 @@ int BaseChatMesh::sendCommandData(const ContactInfo& recipient, uint32_t timest } bool BaseChatMesh::sendGroupMessage(uint32_t timestamp, mesh::GroupChannel& channel, const char* sender_name, const char* text, int text_len) { + if (text_len < 0) { // memcpy() below would read this as a size_t, so clamping cannot catch it + MESH_DEBUG_PRINTLN("sendGroupMessage: invalid negative text_len=%d", text_len); + return false; + } + uint8_t temp[5+MAX_TEXT_LEN+32]; memcpy(temp, ×tamp, 4); // mostly an extra blob to help make packet_hash unique temp[4] = 0; // TXT_TYPE_PLAIN From e97de59b57376a6428961296d093e4f9d29d970b Mon Sep 17 00:00:00 2001 From: Marcel Verdult Date: Thu, 22 Oct 2026 09:42:58 +0000 Subject: [PATCH 28/79] fix(radio): refuse "nan" for the airtime factor "set af nan" is accepted and stores a NaN in airtime_factor, the duty cycle budget the roles hand to their airtime accounting. strtof() consumes the token, so the parse guard does not fire, and no ordered comparison is true for a NaN, so "af < 0 || af > 9" cannot reject it. "set dutycycle" writes the same field and has the same hole. Both commands now check the text before it is parsed: after optional white space and sign, a number has to start with a digit or a '.'. That refuses "nan", "inf" and their variants, and keeps every spelling that was accepted before (signs, leading white space, ".5"). The ranges and both reply strings are unchanged. The check is on the text rather than on the parsed float on purpose. nRF52 builds use -Ofast, and under -ffast-math the compiler may assume a float is never NaN or infinite. A test on the value, even one that reads its bits, can then be folded away: clang does exactly that with a bit test at -Ofast, while arm-none-eabi-gcc keeps it. A character test does not depend on that. --- src/helpers/CommonRadioPrefs.cpp | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/helpers/CommonRadioPrefs.cpp b/src/helpers/CommonRadioPrefs.cpp index 41b17993..44e0eba3 100644 --- a/src/helpers/CommonRadioPrefs.cpp +++ b/src/helpers/CommonRadioPrefs.cpp @@ -2,6 +2,22 @@ #include "TxtDataHelpers.h" #include "Utils.h" #include "target.h" +#include + +namespace { + +// strtof() and atof() also read "nan" and "inf". A NaN cannot be refused by a +// range check: no ordered comparison is true for it, and under -ffast-math, +// which nRF52 builds use, the compiler may assume it never occurs and fold any +// test on the parsed value away. So the text is checked before it is parsed: +// after optional white space and sign, a number starts with a digit or a '.'. +bool looksLikeANumber(const char* s) { + while (isspace((unsigned char)*s)) s++; + if (*s == '+' || *s == '-') s++; + return isdigit((unsigned char)*s) || *s == '.'; +} + +} // namespace bool CommonRadioPrefs::getByKey(const char* key, char* value, size_t max_len) { if (strcmp(key, "fem_rxgain") == 0) { @@ -69,7 +85,7 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest if (memcmp(command, "set af ", 7) == 0) { char* end; float af = strtof(&command[7], &end); - if (end == &command[7] || af < 0 || af > 9) { + if (end == &command[7] || !looksLikeANumber(&command[7]) || af < 0 || af > 9) { strcpy(reply, "ERROR: af must be 0-9"); } else { setAirtimeFactor(af); @@ -87,7 +103,7 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest } if (memcmp(command, "set dutycycle ", 14) == 0) { float dc = atof(&command[14]); - if (dc < 1 || dc > 100) { + if (!looksLikeANumber(&command[14]) || dc < 1 || dc > 100) { strcpy(reply, "ERROR: dutycycle must be 1-100"); } else { setAirtimeFactor((100.0f / dc) - 1.0f); From fded88ac6a97008a1e8d87bb150f85ac0f898fa8 Mon Sep 17 00:00:00 2001 From: Blake Latchford Date: Thu, 22 Oct 2026 17:57:33 -0400 Subject: [PATCH 29/79] Fix broken KISS modem build on 6 ESP32-S3 platforms Broken out from PR #3496 which has been open for a month. --- examples/kiss_modem/main.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/examples/kiss_modem/main.cpp b/examples/kiss_modem/main.cpp index 44b2a3df..bb77c23d 100644 --- a/examples/kiss_modem/main.cpp +++ b/examples/kiss_modem/main.cpp @@ -115,7 +115,10 @@ void setup() { delay(100); #if defined(ESP32) && defined(ARDUINO_USB_CDC_ON_BOOT) && ARDUINO_USB_CDC_ON_BOOT Serial.setTxTimeoutMs(USB_TX_TIMEOUT_MS); +#if defined(ARDUINO_USB_MODE) && ARDUINO_USB_MODE + // HWCDC only; TinyUSB's USBCDC TX buffer is fixed at build time Serial.setTxBufferSize(USB_TX_BUFFER_SIZE); +#endif #endif modem = new KissModem(Serial, identity, rng, radio_driver, board, sensors); #endif From e8be1ad6b21e5957ec6048f9ab0d27c39913470b Mon Sep 17 00:00:00 2001 From: Florent Date: Sat, 24 Oct 2026 10:16:56 -0400 Subject: [PATCH 30/79] UiTask: better cleaning of eink screens when hibernating --- examples/companion_radio/ui-new/UITask.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index 6e987f87..aced739d 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -908,9 +908,11 @@ void UITask::shutdown(bool restart){ if (restart) { _board->reboot(); } else { - display.forceFullRefresh(); - display.clear(); - display.endFrame(); + if (_display->isEink()) { + _display->blankScreen(); + _display->turnOff(); + _display->powerOff(); + } // Power off board including radio, display, GPS and components _board->powerOff(); } From f0ea4620caac782a5be3ab2ed555daa5ce2aa872 Mon Sep 17 00:00:00 2001 From: Florent Date: Sat, 24 Oct 2026 11:15:28 -0400 Subject: [PATCH 31/79] thinknode_m1: fix button2 definition --- variants/thinknode_m1/variant.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/variants/thinknode_m1/variant.h b/variants/thinknode_m1/variant.h index f7f52a6a..e096f3ca 100644 --- a/variants/thinknode_m1/variant.h +++ b/variants/thinknode_m1/variant.h @@ -81,7 +81,7 @@ #define BUTTON_PIN PIN_BUTTON1 #define PIN_USER_BTN BUTTON_PIN -#define PIN_BUTTON2 (11) +#define PIN_BUTTON2 (39) #define BUTTON_PIN2 PIN_BUTTON2 #define EXTERNAL_FLASH_DEVICES MX25R1635F From 81fa5d7f5a944b413abaa891f4858b9844620cdc Mon Sep 17 00:00:00 2001 From: Florent Date: Sat, 24 Oct 2026 13:26:06 -0400 Subject: [PATCH 32/79] ThinknodeM1: update eink driver --- variants/thinknode_m1/platformio.ini | 5 +++++ variants/thinknode_m1/variant.h | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/variants/thinknode_m1/platformio.ini b/variants/thinknode_m1/platformio.ini index c775ae3f..7c620e2e 100644 --- a/variants/thinknode_m1/platformio.ini +++ b/variants/thinknode_m1/platformio.ini @@ -27,6 +27,11 @@ build_flags = ${nrf52_base.build_flags} -D UI_RECENT_LIST_SIZE=9 -D UI_MSG_PREVIEW_SIZE=165 -D EINK_MAX_PARTIAL_REFRESH=60 + -D EINK_DISPLAY_MODEL=GxEPD2_154_D67 + -D EINK_SCALE_X=1.5625f + -D EINK_SCALE_Y=1.5625f + -D EINK_X_OFFSET=0 + -D EINK_Y_OFFSET=10 -D BACKLIGHT_BTN=PIN_BUTTON2 -D AUTO_OFF_MILLIS=900000 -D UI_NO_HIBERNATE diff --git a/variants/thinknode_m1/variant.h b/variants/thinknode_m1/variant.h index e096f3ca..aecf197e 100644 --- a/variants/thinknode_m1/variant.h +++ b/variants/thinknode_m1/variant.h @@ -131,6 +131,11 @@ extern const int SCK; #define DISP_BUSY (3) #define DISP_BACKLIGHT (43) +#define PIN_DISPLAY_CS DISP_CS +#define PIN_DISPLAY_DC DISP_DC +#define PIN_DISPLAY_RST DISP_RST +#define PIN_DISPLAY_BUSY DISP_BUSY + //////////////////////////////////////////////////////////////////////////////// // GPS From 6f9b3ba15515909bb051141edea79178a8c28b9b Mon Sep 17 00:00:00 2001 From: Florent Date: Sun, 25 Oct 2026 17:49:16 -0400 Subject: [PATCH 33/79] ThinknodeM5: enable wifi in usb companion --- variants/thinknode_m5/platformio.ini | 2 ++ 1 file changed, 2 insertions(+) diff --git a/variants/thinknode_m5/platformio.ini b/variants/thinknode_m5/platformio.ini index 1980575e..a9761597 100644 --- a/variants/thinknode_m5/platformio.ini +++ b/variants/thinknode_m5/platformio.ini @@ -177,12 +177,14 @@ build_flags = -D MAX_GROUP_CHANNELS=40 -D OFFLINE_QUEUE_SIZE=256 -D ENABLE_USB_INTERFACE + -D ENABLE_WIFI_INTERFACE build_src_filter = ${ThinkNode_M5.build_src_filter} + + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> + + + lib_deps = ${ThinkNode_M5.lib_deps} densaugeo/base64 @ ~1.4.0 From 8e0e5b81104dcdc971a195d506896f8b9140cac3 Mon Sep 17 00:00:00 2001 From: Blake Latchford Date: Sun, 25 Oct 2026 21:45:10 -0400 Subject: [PATCH 34/79] Saturate duplicate packet stats instead of wrapping Tested on a Heltec V4 repeater with the counter seeded at 65530. Fixes #3255 Co-Authored-By: Claude Opus 5.5 --- examples/simple_repeater/MyMesh.cpp | 4 ++-- examples/simple_room_server/MyMesh.cpp | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index 61b6c149..b50d19d0 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -229,8 +229,8 @@ int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t stats.n_recv_direct = getNumRecvDirect(); stats.err_events = _err_flags; stats.last_snr = (int16_t)(radio_driver.getLastSNR() * 4); - stats.n_direct_dups = ((SimpleMeshTables *)getTables())->getNumDirectDups(); - stats.n_flood_dups = ((SimpleMeshTables *)getTables())->getNumFloodDups(); + stats.n_direct_dups = std::min(((SimpleMeshTables *)getTables())->getNumDirectDups(), 0xFFFF); + stats.n_flood_dups = std::min(((SimpleMeshTables *)getTables())->getNumFloodDups(), 0xFFFF); stats.total_rx_air_time_secs = getReceiveAirTime() / 1000; stats.n_recv_errors = radio_driver.getPacketsRecvErrors(); memcpy(&reply_data[4], &stats, sizeof(stats)); diff --git a/examples/simple_room_server/MyMesh.cpp b/examples/simple_room_server/MyMesh.cpp index da4c776c..935fd7f9 100644 --- a/examples/simple_room_server/MyMesh.cpp +++ b/examples/simple_room_server/MyMesh.cpp @@ -1,4 +1,5 @@ #include "MyMesh.h" +#include #define REPLY_DELAY_MILLIS 1500 #define PUSH_NOTIFY_DELAY_MILLIS 2000 @@ -170,8 +171,8 @@ int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t stats.n_recv_direct = getNumRecvDirect(); stats.err_events = _err_flags; stats.last_snr = (int16_t)(radio_driver.getLastSNR() * 4); - stats.n_direct_dups = ((SimpleMeshTables *)getTables())->getNumDirectDups(); - stats.n_flood_dups = ((SimpleMeshTables *)getTables())->getNumFloodDups(); + stats.n_direct_dups = std::min(((SimpleMeshTables *)getTables())->getNumDirectDups(), 0xFFFF); + stats.n_flood_dups = std::min(((SimpleMeshTables *)getTables())->getNumFloodDups(), 0xFFFF); stats.n_posted = _num_posted; stats.n_post_push = _num_post_pushes; From ab64c87c384b11c283f6078c29304c2507ddd26e Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Mon, 26 Oct 2026 20:29:39 +1100 Subject: [PATCH 35/79] * scope 0 rule fixes --- src/helpers/RegionMap.cpp | 2 +- src/helpers/RoutingPolicy.h | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/helpers/RegionMap.cpp b/src/helpers/RegionMap.cpp index d8d77380..16a8e1ff 100644 --- a/src/helpers/RegionMap.cpp +++ b/src/helpers/RegionMap.cpp @@ -188,7 +188,7 @@ int RegionMap::getTransportKeysFor(const RegionEntry& src, TransportKey dest[], } RegionEntry* RegionMap::findMatch(mesh::Packet* packet, uint8_t mask) { - if (packet->transport_codes[0] == 0) return &wildcard; + if (packet->transport_codes[0] == 0) return (wildcard.flags & mask) == 0 ? &wildcard : NULL; for (int i = 0; i < num_regions; i++) { auto region = ®ions[i]; if ((region->flags & mask) == 0) { // does region allow this? (per 'mask' param) diff --git a/src/helpers/RoutingPolicy.h b/src/helpers/RoutingPolicy.h index 5251a590..225e5cd4 100644 --- a/src/helpers/RoutingPolicy.h +++ b/src/helpers/RoutingPolicy.h @@ -17,6 +17,7 @@ inline bool isFloodHopLimitExceeded(const Packet* packet, uint8_t flood_max, uint8_t hops = packet->getPathHashCount(); if (hops >= flood_max) return true; if (packet->getRouteType() == ROUTE_TYPE_FLOOD && hops >= flood_max_unscoped) return true; + if (packet->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD && packet->transport_codes[0] == 0 && hops >= flood_max_unscoped) return true; // scope 0, treat as unscoped if (packet->getPayloadType() == PAYLOAD_TYPE_ADVERT && hops >= flood_max_advert) return true; return false; } From f889b7d8a21a0a011d146b3bc11bb1ef161363d0 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Mon, 26 Oct 2026 20:39:46 +1100 Subject: [PATCH 36/79] * unit test fix --- test/test_routing_policy/test_routing_policy.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/test_routing_policy/test_routing_policy.cpp b/test/test_routing_policy/test_routing_policy.cpp index bba9ec79..3f7faf30 100644 --- a/test/test_routing_policy/test_routing_policy.cpp +++ b/test/test_routing_policy/test_routing_policy.cpp @@ -8,6 +8,9 @@ static Packet makeFlood(uint8_t route_type, uint8_t payload_type, uint8_t hops) p.header = route_type | (payload_type << PH_TYPE_SHIFT); p.setPathHashSizeAndCount(1, hops); p.payload_len = 1; + if (route_type == ROUTE_TYPE_TRANSPORT_FLOOD) { + p.transport_codes[0] = 1; // has to be non-zero + } return p; } From 2270b931fa404475364387e6135554e609e3b416 Mon Sep 17 00:00:00 2001 From: Marcel Verdult Date: Fri, 23 Oct 2026 01:30:57 +0200 Subject: [PATCH 37/79] fix(esp32): define the RTC backup of ESP32RTCClock once ESP32Board.h defined _rtc_backup_time and _rtc_backup_magic as static in the header, so every translation unit that includes it has its own copy, and the inline members of ESP32RTCClock read and write the copy of the unit they are compiled in. Today one unit per image uses them; a second one could restore a copy that setCurrentTime() never wrote. The header now declares them, and ESP32Board.cpp defines them once. --- src/helpers/ESP32Board.cpp | 4 ++++ src/helpers/ESP32Board.h | 7 +++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/helpers/ESP32Board.cpp b/src/helpers/ESP32Board.cpp index a55abb26..d190fca1 100644 --- a/src/helpers/ESP32Board.cpp +++ b/src/helpers/ESP32Board.cpp @@ -3,6 +3,10 @@ #include "ESP32Board.h" #include +// The RTC backup of ESP32RTCClock, declared in ESP32Board.h. +RTC_NOINIT_ATTR uint32_t _rtc_backup_time; +RTC_NOINIT_ATTR uint32_t _rtc_backup_magic; + #if defined(ADMIN_PASSWORD) && !defined(DISABLE_WIFI_OTA) // Repeater or Room Server only #include #include diff --git a/src/helpers/ESP32Board.h b/src/helpers/ESP32Board.h index 3f95e692..cd274cd9 100644 --- a/src/helpers/ESP32Board.h +++ b/src/helpers/ESP32Board.h @@ -200,8 +200,11 @@ public: } }; -static RTC_NOINIT_ATTR uint32_t _rtc_backup_time; -static RTC_NOINIT_ATTR uint32_t _rtc_backup_magic; +// The time ESP32RTCClock restores after a reset, in RTC memory that a reset does +// not clear. Defined once, in ESP32Board.cpp: the inline members below run in +// every translation unit that uses them and must all see the same backup. +extern uint32_t _rtc_backup_time; +extern uint32_t _rtc_backup_magic; #define RTC_BACKUP_MAGIC 0xAA55CC33 #define RTC_TIME_MIN 1772323200 // 1 Mar 2026 From 8a33082b59d1f0da9758d1f0437d602900da87fc Mon Sep 17 00:00:00 2001 From: WayenWeng Date: Tue, 27 Oct 2026 10:44:36 +0800 Subject: [PATCH 38/79] fix(radio): put LR2021 in standby before re-config in setParams --- src/helpers/radiolib/CustomLR2021Wrapper.h | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/src/helpers/radiolib/CustomLR2021Wrapper.h b/src/helpers/radiolib/CustomLR2021Wrapper.h index 8299e2bf..c60bfda3 100644 --- a/src/helpers/radiolib/CustomLR2021Wrapper.h +++ b/src/helpers/radiolib/CustomLR2021Wrapper.h @@ -16,15 +16,23 @@ public: CustomLR2021Wrapper(CustomLR2021& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { } void setParams(float freq, float bw, uint8_t sf, uint8_t cr) override { - ((CustomLR2021 *)_radio)->setFrequency(freq); - ((CustomLR2021 *)_radio)->setSpreadingFactor(sf); - ((CustomLR2021 *)_radio)->setBandwidth(bw); - ((CustomLR2021 *)_radio)->setCodingRate(cr); + auto r = (CustomLR2021 *)_radio; + // LR2021 only accepts RF/modulation config commands while in STANDBY mode. + // Re-configuring while in continuous RX gets silently rejected (-706), + // which broke hot frequency changes over BLE. + int16_t status = r->standby(); + if (status != RADIOLIB_ERR_NONE) { MESH_DEBUG_PRINTLN("CustomLR2021Wrapper: standby() -> %d", status); } + if ((status = r->setFrequency(freq)) != RADIOLIB_ERR_NONE) { MESH_DEBUG_PRINTLN("CustomLR2021Wrapper: setFrequency() -> %d", status); } + if ((status = r->setSpreadingFactor(sf)) != RADIOLIB_ERR_NONE) { MESH_DEBUG_PRINTLN("CustomLR2021Wrapper: setSpreadingFactor() -> %d", status); } + if ((status = r->setBandwidth(bw)) != RADIOLIB_ERR_NONE) { MESH_DEBUG_PRINTLN("CustomLR2021Wrapper: setBandwidth() -> %d", status); } + if ((status = r->setCodingRate(cr)) != RADIOLIB_ERR_NONE) { MESH_DEBUG_PRINTLN("CustomLR2021Wrapper: setCodingRate() -> %d", status); } updatePreamble(sf); - applySideDetectorConfig(); + // internal idle() sets STATE_IDLE, which triggers a startReceive() on the next loop + status = applySideDetectorConfig(); + if (status != RADIOLIB_ERR_NONE) { MESH_DEBUG_PRINTLN("CustomLR2021Wrapper: applySideDetectorConfig() -> %d", status); } PacketMillis pm = calcMaxPacketMillis(sf, bw, cr, preambleLengthForSF(sf)); - ((CustomLR2021 *)_radio)->setPreambleMillis(pm.preambleMillis); - ((CustomLR2021 *)_radio)->setMaxPayloadMillis(pm.payloadMillis); + r->setPreambleMillis(pm.preambleMillis); // pure in-memory setters, no standby needed + r->setMaxPayloadMillis(pm.payloadMillis); } From 4d93dfbc04645162697aec26618e7b73ebee69bf Mon Sep 17 00:00:00 2001 From: rado <6479266+rbrus@users.noreply.github.com> Date: Tue, 27 Oct 2026 07:21:24 +0100 Subject: [PATCH 39/79] Drop unit tests per review feedback --- .../test_companion_node_prefs.cpp | 57 ------------------- 1 file changed, 57 deletions(-) diff --git a/test/test_companion_node_prefs/test_companion_node_prefs.cpp b/test/test_companion_node_prefs/test_companion_node_prefs.cpp index ab5e0f90..433c9710 100644 --- a/test/test_companion_node_prefs/test_companion_node_prefs.cpp +++ b/test/test_companion_node_prefs/test_companion_node_prefs.cpp @@ -6,32 +6,6 @@ #include "../../examples/companion_radio/NodePrefs.h" -bool CommonRadioPrefs::getByKey(const char* key, char* value, size_t max_len) { - if (strcmp(key, "fem_rxgain") == 0) { - snprintf(value, max_len, "%d", (uint32_t)getFEMRxGain()); - return true; - } - if (strcmp(key, "fem_txgain") == 0) { - snprintf(value, max_len, "%d", (uint32_t)getFEMTxGain()); - return true; - } - return false; -} - -bool CommonRadioPrefs::setByKey(const char* key, const char* value) { - if (strcmp(key, "fem_rxgain") == 0) { - setFEMRxGain(atoi(value)); - markDirty(); - return true; - } - if (strcmp(key, "fem_txgain") == 0) { - setFEMTxGain(atoi(value)); - markDirty(); - return true; - } - return false; -} - class ReplayStream : public Stream { const char* _text; int _pos = 0; @@ -103,37 +77,6 @@ TEST(CompanionNodePrefs, RxGainSettingsRoundTripIndependently) { } #endif -TEST(CompanionNodePrefs, NegativeTxPowerPreservedAsSigned) { - NodePrefs prefs; - CommonRadioPrefs* radio = prefs.getRadioPrefs(); - - radio->setTxPower(-9); - EXPECT_EQ(-9, prefs.tx_power_dbm); - EXPECT_EQ(-9, radio->getTxPower()); - EXPECT_EQ(-9, static_cast(radio->getTxPower())); - - char reply[32]; - snprintf(reply, sizeof(reply), "> %d", static_cast(radio->getTxPower())); - EXPECT_STREQ("> -9", reply); -} - -TEST(CompanionNodePrefs, NegativeTxPowerRoundTripsSerial) { - NodePrefs saved; - saved.getRadioPrefs()->setTxPower(-9); - - CaptureStream output; - ASSERT_TRUE(saved.saveSerial(output)); - EXPECT_NE(std::string::npos, output.text().find("tx:-9")); - - ReplayStream input("{radio:{tx:-9}}"); - NodePrefs loaded; - loaded.tx_power_dbm = 22; - - ASSERT_TRUE(loaded.loadSerial(input)); - EXPECT_EQ(-9, loaded.tx_power_dbm); - EXPECT_EQ(-9, loaded.getRadioPrefs()->getTxPower()); -} - int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); From 15c58df0d99c1e0999e473a9a08d8ebc57ce2f72 Mon Sep 17 00:00:00 2001 From: Rastislav Vysoky Date: Tue, 27 Oct 2026 07:42:32 +0100 Subject: [PATCH 40/79] bump RadioLib to 7.8.1 --- platformio.ini | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/platformio.ini b/platformio.ini index f296f838..92c94204 100644 --- a/platformio.ini +++ b/platformio.ini @@ -19,8 +19,7 @@ monitor_speed = 115200 lib_deps = SPI Wire - ;jgromes/RadioLib @ ^7.7.1 - https://github.com/jgromes/RadioLib.git#6d8934836678d8894e3d556550475b37dce3e2b6 + jgromes/RadioLib @ 7.8.1 rweather/Crypto @ ^0.4.0 adafruit/RTClib @ ^2.1.3 melopero/Melopero RV3028 @ ^1.1.0 From b2997ef0d373203a6a5287f1ce3a90c2750e8234 Mon Sep 17 00:00:00 2001 From: akalinin-softvelum <142931037+akalinin-softvelum@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:20:36 +0000 Subject: [PATCH 41/79] T-Echo: use GxEPD2_154_D67 e-ink driver T-Echo used the fallback GxEPD2_150_BN; on my unit every refresh hit the 10 s busy timeout. Switch to GxEPD2_154_D67 like Meshtastic. --- variants/lilygo_techo/platformio.ini | 5 +++++ variants/lilygo_techo/variant.h | 6 ++++++ 2 files changed, 11 insertions(+) diff --git a/variants/lilygo_techo/platformio.ini b/variants/lilygo_techo/platformio.ini index eb4a69e2..ba39549e 100644 --- a/variants/lilygo_techo/platformio.ini +++ b/variants/lilygo_techo/platformio.ini @@ -32,6 +32,11 @@ build_flags = ${nrf52_base.build_flags} -D PIN_GPS_RESET_ACTIVE=LOW -D TELEM_BME280_ADDRESS=0x77 -D DISPLAY_CLASS=GxEPDDisplay + -D EINK_DISPLAY_MODEL=GxEPD2_154_D67 + -D EINK_SCALE_X=1.5625f + -D EINK_SCALE_Y=1.5625f + -D EINK_X_OFFSET=0 + -D EINK_Y_OFFSET=10 -D EINK_SCREENOFF_BLANK -D UI_RECENT_LIST_SIZE=9 -D UI_MSG_PREVIEW_SIZE=165 diff --git a/variants/lilygo_techo/variant.h b/variants/lilygo_techo/variant.h index 1de62d91..d11aac58 100644 --- a/variants/lilygo_techo/variant.h +++ b/variants/lilygo_techo/variant.h @@ -131,6 +131,12 @@ extern const int SCK; #define DISP_BUSY (3) #define DISP_BACKLIGHT (43) +// used by GxEPDDisplay when EINK_DISPLAY_MODEL is set +#define PIN_DISPLAY_CS DISP_CS +#define PIN_DISPLAY_DC DISP_DC +#define PIN_DISPLAY_RST DISP_RST +#define PIN_DISPLAY_BUSY DISP_BUSY + //////////////////////////////////////////////////////////////////////////////// // GPS From a1528cc36f02ecb770c2f677dd6a0d235d57b2c6 Mon Sep 17 00:00:00 2001 From: Florent Date: Tue, 27 Oct 2026 15:41:36 -0400 Subject: [PATCH 42/79] Remove unused buttonStateChanged from some variants --- variants/meshtracker_x1/MeshTrackerX1Board.cpp | 1 - variants/meshtracker_x1/MeshTrackerX1Board.h | 14 -------------- variants/promicro/PromicroBoard.cpp | 1 - variants/promicro/PromicroBoard.h | 12 ------------ variants/t1000-e/T1000eBoard.cpp | 1 - variants/t1000-e/T1000eBoard.h | 14 -------------- variants/thinknode_m3/ThinkNodeM3Board.cpp | 1 - variants/thinknode_m3/ThinkNodeM3Board.h | 12 ------------ variants/thinknode_m4/ThinkNodeM4Board.cpp | 1 - variants/thinknode_m4/ThinkNodeM4Board.h | 12 ------------ 10 files changed, 69 deletions(-) diff --git a/variants/meshtracker_x1/MeshTrackerX1Board.cpp b/variants/meshtracker_x1/MeshTrackerX1Board.cpp index 56e537a2..94c20a63 100644 --- a/variants/meshtracker_x1/MeshTrackerX1Board.cpp +++ b/variants/meshtracker_x1/MeshTrackerX1Board.cpp @@ -5,7 +5,6 @@ void MeshTrackerX1Board::begin() { NRF52BoardDCDC::begin(); - btn_prev_state = LOW; // button is active HIGH #ifdef BUTTON_PIN pinMode(BATTERY_PIN, INPUT); diff --git a/variants/meshtracker_x1/MeshTrackerX1Board.h b/variants/meshtracker_x1/MeshTrackerX1Board.h index 51f022e0..d332244f 100644 --- a/variants/meshtracker_x1/MeshTrackerX1Board.h +++ b/variants/meshtracker_x1/MeshTrackerX1Board.h @@ -5,9 +5,6 @@ #include class MeshTrackerX1Board : public NRF52BoardDCDC { -protected: - uint8_t btn_prev_state; - public: MeshTrackerX1Board() : NRF52Board("X1_OTA") {} void begin(); @@ -35,17 +32,6 @@ public: return "Seeed SenseCAP MeshTracker X1"; } - int buttonStateChanged() { - #ifdef BUTTON_PIN - uint8_t v = digitalRead(BUTTON_PIN); - if (v != btn_prev_state) { - btn_prev_state = v; - return (v == USER_BTN_PRESSED) ? 1 : -1; - } - #endif - return 0; - } - void powerOff() override { #ifdef HAS_GPS digitalWrite(GPS_VRTC_EN, LOW); diff --git a/variants/promicro/PromicroBoard.cpp b/variants/promicro/PromicroBoard.cpp index 7011521b..aba80878 100644 --- a/variants/promicro/PromicroBoard.cpp +++ b/variants/promicro/PromicroBoard.cpp @@ -5,7 +5,6 @@ void PromicroBoard::begin() { NRF52Board::begin(); - btn_prev_state = HIGH; pinMode(PIN_VBAT_READ, INPUT); diff --git a/variants/promicro/PromicroBoard.h b/variants/promicro/PromicroBoard.h index ee16c965..605b0365 100644 --- a/variants/promicro/PromicroBoard.h +++ b/variants/promicro/PromicroBoard.h @@ -9,7 +9,6 @@ class PromicroBoard : public NRF52BoardDCDC { protected: - uint8_t btn_prev_state; float adc_mult = ADC_MULTIPLIER; public: @@ -48,15 +47,4 @@ public: const char* getManufacturerName() const override { return "ProMicro DIY"; } - - int buttonStateChanged() { - #ifdef BUTTON_PIN - uint8_t v = digitalRead(BUTTON_PIN); - if (v != btn_prev_state) { - btn_prev_state = v; - return (v == LOW) ? 1 : -1; - } - #endif - return 0; - } }; diff --git a/variants/t1000-e/T1000eBoard.cpp b/variants/t1000-e/T1000eBoard.cpp index 0d390f79..1d3ce423 100644 --- a/variants/t1000-e/T1000eBoard.cpp +++ b/variants/t1000-e/T1000eBoard.cpp @@ -5,7 +5,6 @@ void T1000eBoard::begin() { NRF52BoardDCDC::begin(); - btn_prev_state = HIGH; #ifdef BUTTON_PIN pinMode(BATTERY_PIN, INPUT); diff --git a/variants/t1000-e/T1000eBoard.h b/variants/t1000-e/T1000eBoard.h index ba8bf0c1..653bea61 100644 --- a/variants/t1000-e/T1000eBoard.h +++ b/variants/t1000-e/T1000eBoard.h @@ -5,9 +5,6 @@ #include class T1000eBoard : public NRF52BoardDCDC { -protected: - uint8_t btn_prev_state; - public: T1000eBoard() : NRF52Board("T1000E_OTA") {} void begin(); @@ -38,17 +35,6 @@ public: return "Seeed Tracker T1000-E"; } - int buttonStateChanged() { - #ifdef BUTTON_PIN - uint8_t v = digitalRead(BUTTON_PIN); - if (v != btn_prev_state) { - btn_prev_state = v; - return (v == USER_BTN_PRESSED) ? 1 : -1; - } - #endif - return 0; - } - void powerOff() override { #ifdef HAS_GPS digitalWrite(GPS_VRTC_EN, LOW); diff --git a/variants/thinknode_m3/ThinkNodeM3Board.cpp b/variants/thinknode_m3/ThinkNodeM3Board.cpp index ac513ade..518d15bd 100644 --- a/variants/thinknode_m3/ThinkNodeM3Board.cpp +++ b/variants/thinknode_m3/ThinkNodeM3Board.cpp @@ -6,7 +6,6 @@ void ThinkNodeM3Board::begin() { NRF52Board::begin(); - btn_prev_state = HIGH; Wire.begin(); diff --git a/variants/thinknode_m3/ThinkNodeM3Board.h b/variants/thinknode_m3/ThinkNodeM3Board.h index 9e8f4989..bbd69d26 100644 --- a/variants/thinknode_m3/ThinkNodeM3Board.h +++ b/variants/thinknode_m3/ThinkNodeM3Board.h @@ -11,7 +11,6 @@ protected: #if NRF52_POWER_MANAGEMENT void initiateShutdown(uint8_t reason) override; #endif - uint8_t btn_prev_state; public: ThinkNodeM3Board() : NRF52Board("THINKNODE_M3_OTA") {} @@ -31,17 +30,6 @@ public: return "Elecrow ThinkNode M3"; } - int buttonStateChanged() { - #ifdef BUTTON_PIN - uint8_t v = digitalRead(BUTTON_PIN); - if (v != btn_prev_state) { - btn_prev_state = v; - return (v == LOW) ? 1 : -1; - } - #endif - return 0; - } - void powerOff() override { // turn off all leds, sd_power_system_off will not do this for us digitalWrite(PIN_LED_BLUE, !LED_STATE_ON); diff --git a/variants/thinknode_m4/ThinkNodeM4Board.cpp b/variants/thinknode_m4/ThinkNodeM4Board.cpp index 4a144a3a..281983ae 100644 --- a/variants/thinknode_m4/ThinkNodeM4Board.cpp +++ b/variants/thinknode_m4/ThinkNodeM4Board.cpp @@ -6,7 +6,6 @@ void ThinkNodeM4Board::begin() { NRF52Board::begin(); - btn_prev_state = HIGH; Wire.begin(); battery_serial->begin(4800); diff --git a/variants/thinknode_m4/ThinkNodeM4Board.h b/variants/thinknode_m4/ThinkNodeM4Board.h index c2cae54b..63de1ff2 100644 --- a/variants/thinknode_m4/ThinkNodeM4Board.h +++ b/variants/thinknode_m4/ThinkNodeM4Board.h @@ -9,7 +9,6 @@ protected: #if NRF52_POWER_MANAGEMENT void initiateShutdown(uint8_t reason) override; #endif - uint8_t btn_prev_state; HardwareSerial * battery_serial; uint16_t bat_level_mv = 0; uint8_t bat_level_percent =0; @@ -32,17 +31,6 @@ public: return "Elecrow ThinkNode M4"; } - int buttonStateChanged() { - #ifdef BUTTON_PIN - uint8_t v = digitalRead(BUTTON_PIN); - if (v != btn_prev_state) { - btn_prev_state = v; - return (v == USER_BTN_PRESSED) ? 1 : -1; - } - #endif - return 0; - } - void shutdownPeripherals() override { // shutdown common peripherals NRF52Board::shutdownPeripherals(); From 33eb7434f973ff908927ea22ffead0845739e9b7 Mon Sep 17 00:00:00 2001 From: Amoulier <19624653+Amoulier@users.noreply.github.com> Date: Wed, 28 Oct 2026 18:56:16 -0400 Subject: [PATCH 43/79] Initialize the RadioLib receive error counter --- src/helpers/radiolib/RadioLibWrappers.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/helpers/radiolib/RadioLibWrappers.h b/src/helpers/radiolib/RadioLibWrappers.h index 77dd9311..4b842f3d 100644 --- a/src/helpers/radiolib/RadioLibWrappers.h +++ b/src/helpers/radiolib/RadioLibWrappers.h @@ -29,7 +29,10 @@ protected: virtual void doResetAGC(); public: - RadioLibWrapper(PhysicalLayer& radio, mesh::MainBoard& board) : _radio(&radio), _board(&board), _preamble_sf(0) { n_recv = n_sent = 0; } + RadioLibWrapper(PhysicalLayer& radio, mesh::MainBoard& board) + : _radio(&radio), _board(&board), _preamble_sf(0) { + n_recv = n_sent = n_recv_errors = 0; + } void begin() override; virtual void powerOff() { _radio->sleep(); } From 1d88a709bd0853794eebcb4c92862010290042c7 Mon Sep 17 00:00:00 2001 From: Florent Date: Mon, 26 Oct 2026 15:04:08 -0400 Subject: [PATCH 44/79] ui: add some parameters to the cli (mostly regarding eink behaviour) --- docs/companion_cli.md | 472 +++++++++++++++++++++ examples/companion_radio/MyMesh.cpp | 102 +++++ examples/companion_radio/NodePrefs.h | 55 +++ examples/companion_radio/ui-new/UITask.cpp | 175 ++++---- examples/companion_radio/ui-new/UITask.h | 2 +- src/helpers/ui/DisplayDriver.h | 4 +- src/helpers/ui/GxEPDDisplay.cpp | 71 ++-- src/helpers/ui/GxEPDDisplay.h | 23 +- variants/lilygo_techo/platformio.ini | 3 +- variants/thinknode_m1/platformio.ini | 3 +- variants/thinknode_m5/platformio.ini | 3 +- variants/thinknode_m8/platformio.ini | 4 +- 12 files changed, 784 insertions(+), 133 deletions(-) create mode 100644 docs/companion_cli.md diff --git a/docs/companion_cli.md b/docs/companion_cli.md new file mode 100644 index 00000000..31a05584 --- /dev/null +++ b/docs/companion_cli.md @@ -0,0 +1,472 @@ +# Companion CLI + +Since version 1.18 meshcore companion radio firmware has a CLI interface, which can be accessed locally (through companion radio protocol) or remotely via the network. + +## Navigation +- [Operational](#operational) +- [Configuration](#configuration) + - [System](#system) + - [Radio](#radio) + - [BLE](#ble) + - [Wifi](#wifi) + - [UI](#ui) + +## Operational + +### Reboot the node +**Usage:** +- `reboot` + +**Note:** No reply is sent. + +--- + +### Power-off the node +**Usage:** +- `poweroff`, or +- `shutdown` + +**Note:** No reply is sent. + +--- + +## Configuration + +### System + +#### View or change this node's name +**Usage:** +- `get name` +- `set name ` + +**Parameters:** +- `name`: Node name + +**Set by build flag:** `ADVERT_NAME` + +**Default:** Varies by board + +**Note:** Advertised names can use up to 23 bytes when location is included and 31 bytes otherwise. Emoji and Unicode characters may take more than one byte. Names that exceed the available advert space are truncated at a valid UTF-8 code point boundary. + +--- + +#### View this node's firmware version +**Usage:** `ver` + +--- + +#### Configure this node's timezone +**Usage:** +- `set tz.offset ` +- `get tz.offset` + +**Parameters:** +- `offset`: float value of the offset in hours + +--- + +### Radio + +Radio parameters are common to all roles and handled by `CommonRadioPrefs`. + +#### View or change this node's radio parameters +**Usage:** +- `get radio` +- `set radio ,,,` + +**Parameters:** +- `freq`: Frequency in MHz +- `bw`: Bandwidth in kHz +- `sf`: Spreading factor (5-12) +- `cr`: Coding rate (5-8) + +**Set by build flag:** `LORA_FREQ`, `LORA_BW`, `LORA_SF`, `LORA_CR` + +**Default:** `869.618,62.5,8,5` + +**Note:** Requires reboot to apply + +--- + +#### View or change this node's transmit power +**Usage:** +- `get tx` +- `set tx ` + +**Parameters:** +- `dbm`: Power level in dBm (1-22) + +**Set by build flag:** `LORA_TX_POWER` + +**Default:** Varies by board + +**Notes:** This setting only controls the power level of the LoRa chip. Some nodes have an additional power amplifier stage which increases the total output. Refer to the node's manual for the correct setting to use. **Setting a value too high may violate the laws in your country.** + +--- + +#### View or change this node's frequency +**Usage:** +- `get freq` +- `set freq ` + +**Parameters:** +- `frequency`: Frequency in MHz + +**Default:** `869.618` + +**Note:** Requires reboot to apply +**Serial Only:** `set freq ` + +--- + +#### View or change this node's rx boosted gain mode (SX12xx and LR1110) +**Usage:** +- `get radio.rxgain` +- `set radio.rxgain ` + +**Parameters:** + - `state`: `on`|`off` + +**Default:** `on` + +--- + +#### View or change the LoRa FEM receive-path gain state on supported boards +**Usage:** +- `get radio.fem.rxgain` +- `set radio.fem.rxgain ` + +**Parameters:** +- `state`: `on`|`off` + +**Notes:** +- This controls the external LoRa FEM receive-path LNA where the board supports it. +- This is separate from `radio.rxgain`, which controls the radio chip receive gain mode. + +--- + +#### View or change the LoRa FEM transmit-path gain state on supported boards +**Usage:** +- `get radio.fem.txgain` +- `set radio.fem.txgain ` + +**Parameters:** +- `state`: `on`|`off` + +**Notes:** +- This controls a software-selectable external LoRa FEM transmit gain where the board supports it. +- On Station G3, remove the PA PL1 jumper to allow software control. `on` selects PA PL1 high/short and `off` selects PA PL1 low/open. The PA PL2 hardware jumper determines whether this switches between power levels 1/3 or 2/4. +- Select an operating level and SX1262 transmit power that comply with local RF limits and the Station G3 power-supply requirements. +- The setting is saved immediately, but on Station G3 the level is applied to the hardware at the start of the next transmit, so that the PA supply rail is never re-targeted while the PA is being driven. `get` reports the configured state, which may lead the hardware until the node next transmits. + +--- + +#### View or change the duty cycle limit +**Usage:** +- `get dutycycle` +- `set dutycycle ` + +**Parameters:** +- `value`: Duty cycle percentage (1-100) + +**Default:** `50%` (equivalent to airtime factor 1.0) + +**Examples:** +- `set dutycycle 100` — no duty cycle limit +- `set dutycycle 50` — 50% duty cycle (default) +- `set dutycycle 10` — 10% duty cycle +- `set dutycycle 1` — 1% duty cycle (strictest EU requirement) + +> **Note:** Added in firmware v1.15.0 + +--- + +#### View or change the airtime factor (duty cycle limit) +> **Deprecated** as of firmware v1.15.0. Use [`get/set dutycycle`](#view-or-change-the-duty-cycle-limit) instead. + +**Usage:** +- `get af` +- `set af ` + +**Parameters:** +- `value`: Airtime factor (0-9). After each transmission, the repeater enforces a silent period of approximately the on-air transmission time multiplied by the value. This results in a long-term duty cycle of roughly 1 divided by (1 plus the value). For example: + - `af = 1` → ~50% duty + - `af = 2` → ~33% duty + - `af = 3` → ~25% duty + - `af = 9` → ~10% duty + You are responsible for choosing a value that is appropriate for your jurisdiction and channel plan (for example EU 868 Mhz 10% duty cycle regulation). + +**Default:** `1.0` + +--- + +#### View or change the local interference threshold +**Usage:** +- `get int.thresh` +- `set int.thresh ` + +**Parameters:** +- `value`: Interference threshold value + +**Default:** `0.0` + +--- + +#### Enable or disable hardware Channel Activity Detection (CAD) +**Usage:** +- `get cad` +- `set cad ` + +**Description:** When enabled, the radio performs a hardware Channel Activity Detection scan before transmitting and defers if the channel is busy. Runs independently of `int.thresh` — either, both, or none may be active. + +**Parameters:** +- `on|off`: Enable or disable hardware CAD + +**Default:** `off` + +--- + +#### View or change the AGC Reset Interval +**Usage:** +- `get agc.reset.interval` +- `set agc.reset.interval ` + +**Parameters:** +- `value`: Interval in seconds, 0-1020, rounded down to a multiple of 4 (17 becomes 16). 0 to disable. + +**Default:** `0.0` + +--- + +#### Enable or disable Multi-Acks support +**Usage:** +- `get multi.acks` +- `set multi.acks ` + +**Parameters:** +- `state`: `0` (disable) or `1` (enable) + +**Default:** `0` + +--- + +#### View or change this node's advert path hash size +**Usage:** +- `get path.hash.mode` +- `set path.hash.mode ` + +**Parameters:** +- `value`: Path hash size (0-2) + - `0`: 1 Byte hash size (256 unique ids)[64 max flood] + - `1`: 2 Byte hash size (65,536 unique ids)[32 max flood] + - `2`: 3 Byte hash size (16,777,216 unique ids)[21 max flood] + - `3`: DO NOT USE (Reserved) + +**Default:** `0` + +**Note:** the 'path.hash.mode' sets the low-level ID/hash encoding size used when the repeater adverts. This setting has no impact on what packet ID/hash size this repeater forwards, all sizes should be forwarded on firmware >= 1.14. This feature was added in firmware 1.14 +#### View or change the retransmit delay factor for flood traffic +**Usage:** +- `get txdelay` +- `set txdelay ` + +**Parameters:** +- `value`: Transmit delay factor (0-2) + +**Default:** `0.5` + +**Note:** When multiple nearby repeaters all hear the same flood packet, each waits a random amount of time before retransmitting to avoid simultaneous collisions. This factor scales the size of that random window. Higher values reduce collision risk at the cost of added latency. `0` disables the window entirely. + +--- + +#### View or change the retransmit delay factor for direct traffic +**Usage:** +- `get direct.txdelay` +- `set direct.txdelay ` + +**Parameters:** +- `value`: Direct transmit delay factor (0-2) + +**Default:** `0.3` (Repeater) - `0.2` (Room Server, Sensor) + +**Note:** Same collision-avoidance random window as `txdelay`, but applied to direct (non-flood, routed) traffic. The default is lower because direct packets are addressed to a specific next hop, so far fewer nodes compete to retransmit them. + +--- + +#### [Experimental] View or change the processing delay for received traffic +**Usage:** +- `get rxdelay` +- `set rxdelay ` + +**Parameters:** +- `value`: Receive delay base (0-20) + +**Default:** `0.0` + +**Note:** When enabled, repeaters that received a flood packet with a weak signal are held in a delay queue before processing, while those that received it with a strong signal process it immediately. This gives strong-signal paths forwarding priority. By the time weak-signal nodes process their copy, the packet may have already propagated and will be suppressed as a duplicate, reducing redundant retransmissions. + +--- + +### BLE + +#### Change BLE PIN +**Usage:** +- `set pin ` + +**Parameters:** +- `pin`: New BLE PIN + +**Set by build flag:** `BLE_PIN_CODE` + +--- + +### Wifi + +#### Get status +**Usage:** +- `get wifi.status` +- `get wifi.ip` + +--- + +#### Toggle +**Usage:** +- `set wifi.enabled ` +- `get wifi.enabled` + +**Parameters:** +- `value`: `0` (disable) or `1` (enable) + +--- + +#### Set SSID +**Usage:** +- `set wifi.ssid ` +- `get wifi.ssid` + +**Parameters:** +- `value`: ssid as a string + +--- + +#### Set password +**Usage:** +- `set wifi.pwd ` +- `get wifi.pwd` + +**Parameters:** +- `value`: password string + +--- + +### UI + +#### Show clock +**Usage:** +- `set ui.show_clock ` +- `get ui.show_clock` + +**Parameters:** +- `state`: `0` (disable) or `1` (enable) + +**Default:** `0` (or `UI_SHOW_CLOCK` build flag) + +--- + +#### Node discovery screen shows nodes names +**Usage:** +- `set ui.nd_name ` +- `get ui.nd_name` + +**Parameters:** +- `state`: `1` (show name) or `0` (show pubkey_prefix) + +**Default:** `1` + +**Note:** When showing name, there is not always enough space to draw both incoming and outgoing snr values. + +--- + +#### Auto-off screen +**Usage:** +- `set ui.auto_off_delay ` +- `get ui.auto_off_delay` + +**Parameters:** +- `delay`: in seconds (`0` means always on) + +**Default:** `15` (or set by `AUTO_OFF_MILLIS` build flag (in ms)) + +**Note:** +On e-ink displays, when turned off, the screen is not necessarily blanked, see `ui.auto_off_blank` and `ui.backlight_delay`. + +When screen is not blanked, it is not refreshed any more. To let the user aware of that, a sleep icon is shown. + +--- + +#### Display backlight timeout +**Usage:** +- `set ui.backlight_delay ` +- `get ui.backlight_delay` + +**Parameters:** +- `delay`: in seconds + - `0` means no timeout + - `-2` means always off + - `-1` means always on + +**Note:** +When set to `0`, backlight can only be triggered using backlight btn. + +--- + +#### When to turn backlight on +**Usage:** +- `set ui.backlight_on_keys ` +- `get ui.backlight_on_keys` +- `set ui.backlight_on_msgs ` +- `get ui.backlight_on_msgs` + +**Parameters:** +- `state`: `0` (disable) or `1` (enable) + +**Default:** +- `ui.backlight_on_msgs = 0` +- `ui.backlight_on_keys = 0` if there is a backlight button on the board, else `1` + +**Note:** +By default backlight is triggered by backlight button if present (as long as the button is pressed backlight is on, and is turned off after a delay). +These toggles permits to toggle backlight when keys are pressed or when a message arrives (it acts as a notification signal). +If `backlight_delay` is set to `0` then this setting has no effect, backlight won't be turned on. + +--- + +#### Control if eink screen should be blanked +**Usage:** +- `set ui.auto_off_blank ` +- `get ui.auto_off_blank` + +**Parameters:** +- `state`: `0` (disable) or `1` (enable) + +**Default:** `0` (or set by `UI_SCREENOFF_BLANK` build flag) + +**Note:** +If disabled, when screen is shut the displays stays on screen and is not updated (an sleep icons covers battery to show the screen is sleeping). + +When screen is blanked, the controller is also put into hibernation, which should preserve the screen a little and some battery ... + +--- + +#### Maximum number of partial refreshes +**Usage:** +- `set ui.max_partial ` +- `get ui.max_partial` + +**Parmeters:** +- `value`: max partial refreshes before doing a full refresh + +**Default:** 0 (no partial refresh or set by `EINK_MAX_PARTIAL_REFRESH` build flag) + +**Note:** +Forcing full refresh helps revives the screen when some tearing appears (under certain environmental conditions). If you see some tearing appearing, you can force full refresh on your screen manually by double clicking the backlight button. If tearing reappears often, use this setting to force full refresh every `value` partial refreshes. \ No newline at end of file diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 6112b2db..8a8f7f1d 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2209,6 +2209,108 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* } return true; } +#ifdef DISPLAY_CLASS + if (memcmp(command, "set ui.show_clock", 17) == 0) { + _prefs.ui_show_clock = atoi(&command[17]) ? 1 : 0; + savePrefs(); + sprintf(reply, "> now %d", _prefs.ui_show_clock); + return true; + } + if (memcmp(command, "set ui.auto_off_delay", 21) == 0) { + _prefs.ui_auto_off_delay = atoi(&command[21]); + savePrefs(); + sprintf(reply, "> now %d seconds", _prefs.ui_auto_off_delay); + return true; + } + if (memcmp(command, "set ui.backlight_delay", 22) == 0) { + _prefs.ui_backlight_delay = atoi(&command[22]); + savePrefs(); + if (_prefs.ui_backlight_delay >= 0) + sprintf(reply, "> now %d seconds", _prefs.ui_backlight_delay); + else if (_prefs.ui_backlight_delay == -1) + sprintf(reply, "> now always on (-1)"); + else + sprintf(reply, "> now disabled (<-1)"); + return true; + } + if (memcmp(command, "set ui.backlight_on_keys", 24) == 0) { + _prefs.ui_backlight_on_keys = atoi(&command[24]); + savePrefs(); + sprintf(reply, "> now %d", _prefs.ui_backlight_on_keys); + return true; + } + if (memcmp(command, "set ui.backlight_on_msgs", 24) == 0) { + _prefs.ui_backlight_on_msgs = atoi(&command[24]); + savePrefs(); + sprintf(reply, "> now %d", _prefs.ui_backlight_on_msgs); + return true; + } + if (memcmp(command, "set ui.auto_off_blank", 21) == 0) { + _prefs.ui_auto_off_blank = atoi(&command[21]); + savePrefs(); + sprintf(reply, "> now %d", _prefs.ui_auto_off_blank); + return true; + } + if (memcmp(command, "set ui.auto_off_keep_msgs", 25) == 0) { + _prefs.ui_auto_off_keep_msgs = atoi(&command[25]); + savePrefs(); + sprintf(reply, "> now %d", _prefs.ui_auto_off_keep_msgs); + return true; + } + if (memcmp(command, "set ui.max_partial", 18) == 0) { + _prefs.ui_max_partial = atoi(&command[18]); + savePrefs(); + sprintf(reply, "> now %d (applied at next screen wakeup)", _prefs.ui_max_partial); + return true; + } + if (memcmp(command, "set ui.nd_name", 14) == 0) { + _prefs.ui_nd_name = atoi(&command[14]); + savePrefs(); + sprintf(reply, "> ui.nd_name is now %d", _prefs.ui_nd_name); + return true; + } + if (memcmp(command, "get ui.show_clock", 17) == 0) { + sprintf(reply, "> %d", _prefs.ui_show_clock); + return true; + } + if (memcmp(command, "get ui.auto_off_delay", 21) == 0) { + sprintf(reply, "> %d seconds", _prefs.ui_auto_off_delay); + return true; + } + if (memcmp(command, "get ui.backlight_delay", 22) == 0) { + if (_prefs.ui_backlight_delay >= 0) + sprintf(reply, "> %d seconds", _prefs.ui_backlight_delay); + else if (_prefs.ui_backlight_delay == -1) + sprintf(reply, "> always on (-1)"); + else + sprintf(reply, "> disabled (<-1)"); + return true; + } + if (memcmp(command, "get ui.backlight_on_keys", 24) == 0) { + sprintf(reply, "> %d", _prefs.ui_backlight_on_keys); + return true; + } + if (memcmp(command, "get ui.backlight_on_msgs", 24) == 0) { + sprintf(reply, "> %d", _prefs.ui_backlight_on_msgs); + return true; + } + if (memcmp(command, "get ui.auto_off_blank", 21) == 0) { + sprintf(reply, "> %d", _prefs.ui_auto_off_blank); + return true; + } + if (memcmp(command, "get ui.auto_off_keep_msgs", 25) == 0) { + sprintf(reply, "> %d", _prefs.ui_auto_off_keep_msgs); + return true; + } + if (memcmp(command, "get ui.max_partial", 18) == 0) { + sprintf(reply, "> %d", _prefs.ui_max_partial); + return true; + } + if (memcmp(command, "get ui.nd_name", 14) == 0) { + sprintf(reply, "> %d", _prefs.ui_nd_name); + return true; + } +#endif return false; // not handled } diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index 1cc5b501..c5d1df04 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -58,6 +58,34 @@ public: // use ssid from prefs, or fallback to ssid from build flags const char* getWifiSSID() const { return wifi_ssid[0] ? wifi_ssid : WIFI_SSID; } #endif +#ifdef DISPLAY_CLASS + #ifndef UI_SHOW_CLOCK + #define UI_SHOW_CLOCK 0 + #endif + #ifndef AUTO_OFF_MILLIS + #define AUTO_OFF_MILLIS 15000 + #endif + #ifndef EINK_MAX_PARTIAL_REFRESH + #define EINK_MAX_PARTIAL_REFRESH 0 + #endif + uint8_t ui_show_clock = UI_SHOW_CLOCK; + uint32_t ui_auto_off_delay = AUTO_OFF_MILLIS / 1000; + int32_t ui_backlight_delay = 5; + #if defined(BACKLIGHT_BTN) + uint8_t ui_backlight_on_keys = 0; + #else + uint8_t ui_backlight_on_keys = 1; + #endif + uint8_t ui_backlight_on_msgs = 0; +#ifdef UI_SCREENOFF_BLANK + uint8_t ui_auto_off_blank = 1; +#else + uint8_t ui_auto_off_blank = 0; +#endif + uint8_t ui_auto_off_keep_msgs = 1; + uint8_t ui_max_partial = EINK_MAX_PARTIAL_REFRESH; + uint8_t ui_nd_name = 1; +#endif private: class RadioPrefs : public CommonRadioPrefs { @@ -189,6 +217,27 @@ private: WiFiPrefs wifi; #endif +#ifdef DISPLAY_CLASS + class UI_Prefs : public ConfigSerializer { + NodePrefs* _parent; + protected: + void structure() override { + def("show_clock", _parent->ui_show_clock); + def("auto_off", _parent->ui_auto_off_delay); + def("bl_dly", _parent->ui_backlight_delay); + def("bl_keys", _parent->ui_backlight_on_keys); + def("bl_msgs", _parent->ui_backlight_on_msgs); + def("max_partial", _parent->ui_max_partial); + def("off_blank", _parent->ui_auto_off_blank); + def("off_keep_msgs", _parent->ui_auto_off_keep_msgs); + def("nd_name", _parent->ui_nd_name); + } + public: + UI_Prefs(NodePrefs* parent) : _parent(parent) {} + }; + UI_Prefs ui; +#endif + protected: void structure() override { def("name", node_name, sizeof(node_name)); @@ -203,12 +252,18 @@ protected: def("custom", custom); #ifdef ENABLE_WIFI_INTERFACE def("wifi", wifi); +#endif +#ifdef DISPLAY_CLASS + def("ui", ui); #endif } public: NodePrefs() : radio(this), gps(this), companion(this), custom(&radio) #ifdef ENABLE_WIFI_INTERFACE , wifi(this) +#endif +#ifdef DISPLAY_CLASS + , ui(this) #endif { node_name[0] = 0; diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index aced739d..89008d7a 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -122,7 +122,6 @@ class HomeScreen : public UIScreen { uint32_t disc_node_req_tag = 0; uint32_t disc_nodes_count = 0; uint32_t discovery_req_time = 0; - bool discovery_disp_names = true; // by default desplay names if available (removes SNR_O) #endif void renderBatteryIndicator(DisplayDriver& display, uint16_t batteryMilliVolts) { @@ -293,17 +292,17 @@ public: sprintf(tmp, "MSG: %d", _task->getMsgCount()); display.drawTextCentered(display.width() / 2, 22, tmp); #endif - #ifdef UI_SHOW_CLOCK - display.setTextSize(3); - uint32_t now = _rtc->getCurrentTime(); - now += (int32_t)(_node_prefs->tz_offset * 3600); - DateTime dt (now); - sprintf(tmp, "%02d:%02d", dt.hour(), dt.minute()); - display.drawTextCentered(display.width() / 2, 60, tmp); - display.setTextSize(1); - sprintf(tmp, "%02d/%02d/%d", dt.day(), dt.month(), dt.year()); - display.drawTextCentered(display.width() / 2, 80, tmp); - #endif + if (_node_prefs->ui_show_clock) { + display.setTextSize(3); + uint32_t now = _rtc->getCurrentTime(); + now += (int32_t)(_node_prefs->tz_offset * 3600); + DateTime dt (now); + sprintf(tmp, "%02d:%02d", dt.hour(), dt.minute()); + display.drawTextCentered(display.width() / 2, 60, tmp); + display.setTextSize(1); + sprintf(tmp, "%02d/%02d/%d", dt.day(), dt.month(), dt.year()); + display.drawTextCentered(display.width() / 2, 80, tmp); + } #ifdef ENABLE_WIFI_INTERFACE IPAddress ip = WiFi.localIP(); snprintf(tmp, sizeof(tmp), "IP: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); @@ -313,21 +312,20 @@ public: if (_task->hasConnection()) { display.setColor(UIColor::warning_txt); display.setTextSize(1); - #ifdef UI_SHOW_CLOCK - display.drawTextCentered(display.width() / 2, 110, "< Connected >"); - #else - display.drawTextCentered(display.width() / 2, 43, "< Connected >"); - #endif + if (_node_prefs->ui_show_clock) + display.drawTextCentered(display.width() / 2, 110, "< Connected >"); + else + display.drawTextCentered(display.width() / 2, 43, "< Connected >"); } else if (the_mesh.getBLEPin() != 0) { // BT pin display.setColor(UIColor::warning_txt); sprintf(tmp, "Pin:%d", the_mesh.getBLEPin()); - #ifdef UI_SHOW_CLOCK - display.setTextSize(1); - display.drawTextCentered(display.width() / 2, 110, tmp); - #else - display.setTextSize(2); - display.drawTextCentered(display.width() / 2, 43, tmp); - #endif + if (_node_prefs->ui_show_clock) { + display.setTextSize(1); + display.drawTextCentered(display.width() / 2, 110, tmp); + } else { + display.setTextSize(2); + display.drawTextCentered(display.width() / 2, 43, tmp); + } } } else if (_page == HomePage::RECENT) { the_mesh.getRecentlyHeard(recent, UI_RECENT_LIST_SIZE); @@ -518,7 +516,7 @@ public: for (int i = 0; i < count; i++, y += 11) { char name[32]; auto a = &discovered[i]; - if ((a->name[0] == 0) || !discovery_disp_names) { + if ((a->name[0] == 0) || !_node_prefs->ui_nd_name) { mesh::Utils::toHex(name, a->pubkey_prefix, 4); } else { strncpy(name, a->name, 32); @@ -618,7 +616,7 @@ public: return true; } if (c == KEY_SELECT && _page == HomePage::DISCOVERY) { - discovery_disp_names = !discovery_disp_names; + _node_prefs->ui_nd_name = !_node_prefs->ui_nd_name; return true; } #endif @@ -726,7 +724,6 @@ public: void UITask::begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* node_prefs) { _display = display; _sensors = sensors; - _auto_off = millis() + AUTO_OFF_MILLIS; #if defined(PIN_USER_BTN) user_btn.begin(); @@ -739,9 +736,11 @@ void UITask::begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* no #endif _node_prefs = node_prefs; + _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; + _backlight_off = millis() + _node_prefs->ui_backlight_delay * 1000; if (_display != NULL) { - _display->turnOn(); + _display->turnOn(_node_prefs->ui_max_partial); } #ifdef PIN_BUZZER @@ -807,11 +806,14 @@ void UITask::onMessageRecv(mesh::Packet *pkt, const ContactInfo &from, uint8_t t if (_display != NULL) { if (!_display->isOn() && !hasConnection()) { - _display->turnOn(); + _display->turnOn(_node_prefs->ui_max_partial); } if (_display->isOn()) { - _auto_off = millis() + AUTO_OFF_MILLIS; // extend the auto-off timer - _next_refresh = 100; // trigger refresh + _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; // extend the auto-off timer + _next_refresh = 100; // trigger refresh + if (_node_prefs->ui_backlight_on_msgs) { + _backlight_off = millis() + _node_prefs->ui_backlight_delay * 1000; + } } } @@ -827,10 +829,10 @@ void UITask::onChannelMessageRecv(mesh::Packet *pkt, ChannelDetails& channel_det if (_display != NULL) { if (!_display->isOn() && !hasConnection()) { - _display->turnOn(); + _display->turnOn(_node_prefs->ui_max_partial); } if (_display->isOn()) { - _auto_off = millis() + AUTO_OFF_MILLIS; // extend the auto-off timer + _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; // extend the auto-off timer _next_refresh = 100; // trigger refresh } } @@ -909,9 +911,7 @@ void UITask::shutdown(bool restart){ _board->reboot(); } else { if (_display->isEink()) { - _display->blankScreen(); - _display->turnOff(); - _display->powerOff(); + _display->turnOff(true); } // Power off board including radio, display, GPS and components _board->powerOff(); @@ -957,9 +957,7 @@ void UITask::loop() { if (ev == BUTTON_EVENT_CLICK) { c = checkDisplayOn(KEY_ENTER); } else if (ev == BUTTON_EVENT_LONG_PRESS) { - display.blankScreen(); - display.turnOff(); - display.powerOff(); + display.turnOff(true); } else if (ev == BUTTON_EVENT_DOUBLE_CLICK) { c = handleDoubleClick(KEY_SELECT); } else if (ev == BUTTON_EVENT_TRIPLE_CLICK) { @@ -979,11 +977,11 @@ void UITask::loop() { #endif #if defined(UI_HAS_ROTARY_INPUT) RotaryInputEvent rotaryEv = rotary_input.poll(); - if (c == 0 && _display != NULL && _display->isOn()) { + if (c == 0 && _display != NULL) { if (rotaryEv == RotaryInputEvent::Next) { - c = KEY_NEXT; + c = checkDisplayOn(KEY_NEXT); } else if (rotaryEv == RotaryInputEvent::Prev) { - c = KEY_PREV; + c = checkDisplayOn(KEY_PREV); } } #endif @@ -1002,39 +1000,52 @@ void UITask::loop() { _analogue_pin_read_millis = millis(); } #endif +#if defined(DISP_BACKLIGHT) || defined(EXP_PIN_BACKLIGHT) #if defined(BACKLIGHT_BTN) if (millis() > next_backlight_btn_check) { if (backlight_btn.isPressed()) { if (!_display->isOn()) { - _display->turnOn(); + _display->turnOn(_node_prefs->ui_max_partial); _next_refresh = 0; } - _auto_off = millis() + AUTO_OFF_MILLIS; // extend auto-off timer - backlight_btn_pressed_at = millis(); // still pressed + _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; // extend auto-off timer + _backlight_off = millis() + _node_prefs->ui_backlight_delay * 1000; // extend auto_off for backlight } - bool touch_state = (millis() - backlight_btn_pressed_at > 5000); - // Backlight button events - int bev = backlight_btn.check(); - if (bev == BUTTON_EVENT_DOUBLE_CLICK) { - _display->forceFullRefresh(); - } else if (bev == BUTTON_EVENT_TRIPLE_CLICK) { - _display->blankScreen(); - _display->turnOff(); - _display->powerOff(); - backlight_btn_pressed_at = 0; - } -#if defined(DISP_BACKLIGHT) - digitalWrite(DISP_BACKLIGHT, !touch_state); -#elif defined(EXP_PIN_BACKLIGHT) - expander.digitalWrite(EXP_PIN_BACKLIGHT, !touch_state); -#endif next_backlight_btn_check = millis() + 100; } + int bev = backlight_btn.check(); + if (bev == BUTTON_EVENT_DOUBLE_CLICK) { + _display->forceFullRefresh(); + } else if (bev == BUTTON_EVENT_TRIPLE_CLICK) { + _display->turnOff(true); + _backlight_off = 0; + } +#endif + + bool backlight_state; + if (_node_prefs->ui_backlight_delay == -1) { + backlight_state = true; + } else if (_node_prefs->ui_backlight_delay < -1) { + backlight_state = false; + } else if (_node_prefs->ui_backlight_delay == 0) { + backlight_state = false; + #ifdef BACKLIGHT_BTN + backlight_state = backlight_btn.isPressed(); + #endif + } else { + backlight_state = (millis() < _backlight_off); + } + +#if defined(DISP_BACKLIGHT) + digitalWrite(DISP_BACKLIGHT, backlight_state); +#elif defined(EXP_PIN_BACKLIGHT) + expander.digitalWrite(EXP_PIN_BACKLIGHT, backlight_state); +#endif #endif if (c != 0 && curr) { curr->handleInput(c); - _auto_off = millis() + AUTO_OFF_MILLIS; // extend auto-off timer + _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; // extend auto-off timer _next_refresh = 100; // trigger refresh } @@ -1065,26 +1076,27 @@ void UITask::loop() { } _display->endFrame(); } -#if AUTO_OFF_MILLIS > 0 + if (_node_prefs->ui_auto_off_delay > 0) { #ifdef KEEP_DISPLAY_ON_USB - // Opt-in: refresh the auto-off deadline while externally powered, so the - // timer counts from the moment external power is removed. Off by default - // because OLED panels burn in quickly; only enable for LCD targets or - // where the display is replaceable. - if (board.isExternalPowered()) { - _auto_off = millis() + AUTO_OFF_MILLIS; - } + // Opt-in: refresh the auto-off deadline while externally powered, so the + // timer counts from the moment external power is removed. Off by default + // because OLED panels burn in quickly; only enable for LCD targets or + // where the display is replaceable. + if (board.isExternalPowered()) { + _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; + } #endif - if (millis() > _auto_off) { - #ifdef EINK_SCREENOFF_BLANK - if (curr != msg_preview) { // don't blank if messages are waiting - _display->blankScreen(); - _display->powerOff(); + if (millis() > _auto_off) { + if (_node_prefs->ui_auto_off_blank && + !(_node_prefs->ui_auto_off_keep_msgs + && curr == msg_preview)) { + // don't blank if messages are waiting + _display->turnOff(true); + } else { + _display->turnOff(); } - #endif - _display->turnOff(); + } } -#endif } #ifdef PIN_VIBRATION @@ -1116,10 +1128,13 @@ void UITask::loop() { char UITask::checkDisplayOn(char c) { if (_display != NULL) { if (!_display->isOn()) { - _display->turnOn(); // turn display on and consume event + _display->turnOn(_node_prefs->ui_max_partial); // turn display on and consume event c = 0; } - _auto_off = millis() + AUTO_OFF_MILLIS; // extend auto-off timer + _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; // extend auto-off timer + if (_node_prefs->ui_backlight_on_keys) { + _backlight_off = millis() + _node_prefs->ui_backlight_delay * 1000; + } _next_refresh = 0; // trigger refresh } return c; diff --git a/examples/companion_radio/ui-new/UITask.h b/examples/companion_radio/ui-new/UITask.h index 4d44bfe1..61831488 100644 --- a/examples/companion_radio/ui-new/UITask.h +++ b/examples/companion_radio/ui-new/UITask.h @@ -62,7 +62,7 @@ class UITask : public AbstractUITask { int _msgcount; unsigned long ui_started_at, next_batt_chck; unsigned long next_backlight_btn_check = 0; - unsigned long backlight_btn_pressed_at = 0; + unsigned long _backlight_off = 0; #ifdef PIN_STATUS_LED int led_state = 0; int next_led_change = 0; diff --git a/src/helpers/ui/DisplayDriver.h b/src/helpers/ui/DisplayDriver.h index 58147aa0..0e41dab5 100644 --- a/src/helpers/ui/DisplayDriver.h +++ b/src/helpers/ui/DisplayDriver.h @@ -25,9 +25,9 @@ public: virtual bool isEink() { return false; } // default to non-eink, override in eink drivers virtual void forceFullRefresh() {} // next refresh will be full for eink virtual void turnOn() = 0; + virtual void turnOn(int max_partial) { turnOn(); } virtual void turnOff() = 0; - virtual void blankScreen() {} // to cleanly erase screen before turning off - virtual void powerOff() {} + virtual void turnOff(bool blank) { turnOff(); } virtual void clear() = 0; virtual void startFrame(ColorVal bkg = UIColor::window_bkg) = 0; virtual void setTextSize(int sz) = 0; diff --git a/src/helpers/ui/GxEPDDisplay.cpp b/src/helpers/ui/GxEPDDisplay.cpp index ce09423e..d7f9562b 100644 --- a/src/helpers/ui/GxEPDDisplay.cpp +++ b/src/helpers/ui/GxEPDDisplay.cpp @@ -1,11 +1,6 @@ #include "GxEPDDisplay.h" -#ifdef EXP_PIN_BACKLIGHT - #include - extern PCA9557 expander; -#endif - #ifndef DISPLAY_ROTATION #define DISPLAY_ROTATION 3 #endif @@ -52,7 +47,7 @@ bool GxEPDDisplay::begin() { } display.setPartialWindow(0, 0, display.width(), display.height()); - resetPartialRefreshCounter(); + _partial_refresh_count = 0; #if DISP_BACKLIGHT digitalWrite(DISP_BACKLIGHT, LOW); @@ -65,26 +60,43 @@ bool GxEPDDisplay::begin() { void GxEPDDisplay::turnOn() { if (!_init) begin(); -#if defined(DISP_BACKLIGHT) && !defined(BACKLIGHT_BTN) - digitalWrite(DISP_BACKLIGHT, HIGH); -#elif defined(EXP_PIN_BACKLIGHT) && !defined(BACKLIGHT_BTN) - expander.digitalWrite(EXP_PIN_BACKLIGHT, HIGH); -#endif if (!_isOn) { _isOn = true; } } -void GxEPDDisplay::powerOff() { - display.hibernate(); +void GxEPDDisplay::turnOn(int max_partial) { + setMaxPartialRefresh(max_partial); + turnOn(); } -void GxEPDDisplay::turnOff() { // Only stops refresh -#if defined(DISP_BACKLIGHT) && !defined(BACKLIGHT_BTN) - digitalWrite(DISP_BACKLIGHT, LOW); -#elif defined(EXP_PIN_BACKLIGHT) && !defined(BACKLIGHT_BTN) - expander.digitalWrite(EXP_PIN_BACKLIGHT, LOW); -#endif +// 24x24 sleep icon, MSB-first (matches GxEPDDisplay::drawXbm) +static const uint8_t sleep_icon_24x24[] = { + 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00, 0xe0, 0x0e, 0x03, 0xc0, 0x18, + 0x0f, 0x80, 0x70, 0x1f, 0x80, 0xff, 0x3f, 0x80, 0xff, 0x3f, 0x00, 0x00, + 0x7f, 0x3f, 0x00, 0x7f, 0x3f, 0x00, 0xff, 0x0e, 0x00, 0xff, 0x1c, 0x7c, + 0xff, 0xbf, 0x7c, 0xff, 0xbf, 0x38, 0xff, 0xc0, 0x7c, 0xff, 0xe0, 0x7c, + 0xff, 0xf0, 0x00, 0x7f, 0xfc, 0x00, 0x7f, 0xff, 0xf8, 0x3f, 0xff, 0xf0, + 0x1f, 0xff, 0xf0, 0x0f, 0xff, 0xe0, 0x07, 0xff, 0x80, 0x01, 0xff, 0x00 +}; + +void GxEPDDisplay::drawSleepIcon() { + const int W = 24, H = 24; + int x = (int)(display.width() / scale_x) - W; // top-right, logical coordinates + int y = 0; + + display.fillRect((x - 5) * scale_x - 1, y * scale_y, (W+5) * scale_x + 2, (H-2) * scale_y + 1, GxEPD_WHITE); + _curr_color = GxEPD_BLACK; + drawXbm(x, y, sleep_icon_24x24, W, H); + display.display(true); +} + +void GxEPDDisplay::turnOff(bool blank) { + if (blank) { + blankScreen(); + } else { + drawSleepIcon(); + } _isOn = false; last_display_crc_value=0; } @@ -94,8 +106,10 @@ void GxEPDDisplay::blankScreen() { // no full refresh needed at wakeup display.clearScreen(0xFF); // Clears microcontroller side RAM display.writeScreenBuffer(0xFF); // Forces 0xFF (White) into the display controller's history registers - resetPartialRefreshCounter(); - last_display_crc_value=0; + _partial_refresh_count = 0; + last_display_crc_value = 0; + // we can hibernate as screen has been cleaned + display.hibernate(); } void GxEPDDisplay::clear() { @@ -108,15 +122,18 @@ void GxEPDDisplay::startFrame(ColorVal bkg) { display.fillScreen(bkg); display.setTextColor(_curr_color = UIColor::primary_txt); display_crc.reset(); - if (_cycles_before_full_refresh != 0) { - display.setPartialWindow(0, 0, display.width(), display.height()); - } else { + if (_force_full_refresh + || (_max_partial_refresh > 0 + && _partial_refresh_count >= _max_partial_refresh)) { // forces a full wipe of the screen ... display.clearScreen(0xFF); // Clears microcontroller side RAM display.writeScreenBuffer(0xFF); // Forces 0xFF (White) into the display controller's history registers // we'll need a partial refresh after that (whatever crc value is) last_display_crc_value = 0; - resetPartialRefreshCounter(); + _partial_refresh_count = 0; + _force_full_refresh = false; + } else { + display.setPartialWindow(0, 0, display.width(), display.height()); } } @@ -223,9 +240,7 @@ void GxEPDDisplay::endFrame() { uint32_t crc = display_crc.finalize(); if (crc != last_display_crc_value) { display.display(true); - if (_cycles_before_full_refresh > 0) { - _cycles_before_full_refresh--; - } + _partial_refresh_count++; } last_display_crc_value = crc; } diff --git a/src/helpers/ui/GxEPDDisplay.h b/src/helpers/ui/GxEPDDisplay.h index 46274402..9d918443 100644 --- a/src/helpers/ui/GxEPDDisplay.h +++ b/src/helpers/ui/GxEPDDisplay.h @@ -16,12 +16,6 @@ #include "DisplayDriver.h" -#ifndef EINK_MAX_PARTIAL_REFRESH - // 60 to prevent ghosting when refreshing every minute ... - // set to -1 to disable the counter - #define EINK_MAX_PARTIAL_REFRESH -1 -#endif - class GxEPDDisplay : public DisplayDriver { #if defined(EINK_DISPLAY_MODEL) @@ -42,8 +36,9 @@ class GxEPDDisplay : public DisplayDriver { uint16_t _curr_color; CRC32 display_crc; int last_display_crc_value = 0; - int _cycles_before_full_refresh; - int max_partial_refresh = EINK_MAX_PARTIAL_REFRESH; // so this can be changed by an option after + bool _force_full_refresh = false; + int _partial_refresh_count = 0; + int _max_partial_refresh = 0; public: #if defined(EINK_DISPLAY_MODEL) @@ -56,12 +51,13 @@ public: bool isOn() override { return _isOn; } bool isEink() override { return true; } - void forceFullRefresh() override { _cycles_before_full_refresh = 0; }; - void resetPartialRefreshCounter() { _cycles_before_full_refresh = max_partial_refresh; }; + void forceFullRefresh() override { _force_full_refresh = true; } + void turnOn(int max_partial) override; void turnOn() override; - void turnOff() override; - void blankScreen() override; - void powerOff() override; + void turnOff(bool blank) override; + void turnOff() override { turnOff(false); } + virtual void blankScreen(); + virtual void setMaxPartialRefresh(int count) {_max_partial_refresh = count; } void clear() override; void startFrame(ColorVal bkg = UIColor::window_bkg) override; void setTextSize(int sz) override; @@ -71,6 +67,7 @@ public: void fillRect(int x, int y, int w, int h) override; void drawRect(int x, int y, int w, int h) override; void drawXbm(int x, int y, const uint8_t* bits, int w, int h) override; + void drawSleepIcon(); uint16_t getTextWidth(const char* str) override; void endFrame() override; }; diff --git a/variants/lilygo_techo/platformio.ini b/variants/lilygo_techo/platformio.ini index ba39549e..896e42a6 100644 --- a/variants/lilygo_techo/platformio.ini +++ b/variants/lilygo_techo/platformio.ini @@ -40,8 +40,7 @@ build_flags = ${nrf52_base.build_flags} -D EINK_SCREENOFF_BLANK -D UI_RECENT_LIST_SIZE=9 -D UI_MSG_PREVIEW_SIZE=165 - -D EINK_MAX_PARTIAL_REFRESH=60 - -D AUTO_OFF_MILLIS=900000 + -D AUTO_OFF_MILLIS=300000 -D BACKLIGHT_BTN=PIN_BUTTON2 build_src_filter = ${nrf52_base.build_src_filter} + diff --git a/variants/thinknode_m1/platformio.ini b/variants/thinknode_m1/platformio.ini index 7c620e2e..03b0eb4e 100644 --- a/variants/thinknode_m1/platformio.ini +++ b/variants/thinknode_m1/platformio.ini @@ -26,14 +26,13 @@ build_flags = ${nrf52_base.build_flags} -D P_LORA_TX_LED=13 -D UI_RECENT_LIST_SIZE=9 -D UI_MSG_PREVIEW_SIZE=165 - -D EINK_MAX_PARTIAL_REFRESH=60 -D EINK_DISPLAY_MODEL=GxEPD2_154_D67 -D EINK_SCALE_X=1.5625f -D EINK_SCALE_Y=1.5625f -D EINK_X_OFFSET=0 -D EINK_Y_OFFSET=10 -D BACKLIGHT_BTN=PIN_BUTTON2 - -D AUTO_OFF_MILLIS=900000 + -D AUTO_OFF_MILLIS=300000 ; 5 minutes -D UI_NO_HIBERNATE -D DISABLE_DIAGNOSTIC_OUTPUT build_src_filter = ${nrf52_base.build_src_filter} diff --git a/variants/thinknode_m5/platformio.ini b/variants/thinknode_m5/platformio.ini index a9761597..d2b791a3 100644 --- a/variants/thinknode_m5/platformio.ini +++ b/variants/thinknode_m5/platformio.ini @@ -28,9 +28,8 @@ build_flags = ${esp32_base.build_flags} -D EINK_Y_OFFSET=10 -D UI_RECENT_LIST_SIZE=9 -D UI_MSG_PREVIEW_SIZE=165 - -D EINK_MAX_PARTIAL_REFRESH=60 -D BACKLIGHT_BTN=PIN_BUTTON2 - -D AUTO_OFF_MILLIS=900000 + -D AUTO_OFF_MILLIS=300000 -D UI_NO_HIBERNATE -D DISABLE_DIAGNOSTIC_OUTPUT -D SX126X_DIO2_AS_RF_SWITCH=true diff --git a/variants/thinknode_m8/platformio.ini b/variants/thinknode_m8/platformio.ini index 5282f280..fdbaea1f 100644 --- a/variants/thinknode_m8/platformio.ini +++ b/variants/thinknode_m8/platformio.ini @@ -23,11 +23,9 @@ build_flags = ${nrf52_base.build_flags} -D UI_HAS_NAV_INPUT=1 -D UI_RECENT_LIST_SIZE=9 -D UI_MSG_PREVIEW_SIZE=165 - -D EINK_MAX_PARTIAL_REFRESH=60 - -D AUTO_OFF_MILLIS=900000 + -D AUTO_OFF_MILLIS=300000 -D BACKLIGHT_BTN=PIN_BUTTON2 -D UI_SHOW_CLOCK=1 - -D EINK_SCREENOFF_BLANK -D EINK_DISPLAY_MODEL=GxEPD2_154_D67 ; -D EINK_DISPLAY_MODEL=GxEPD2_154_GDEY0154D67 ; -D EINK_DISPLAY_MODEL=GxEPD2_150_BN From 54b90cbdfa459830eebdd0c46207341b065cbbbf Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko Date: Thu, 29 Oct 2026 23:49:49 +0200 Subject: [PATCH 45/79] Fix possible reply buffer overflow in 'sensor list' 'sensor list' appended 'name=value' lines into the 160-byte CLI reply with unbounded sprintf, only checking the position before each write (< 134). A single long value (or several medium ones) could write past the end of the buffer. Write each entry with snprintf against the remaining space, keep room for the '... next:N' paging hint, and move entries that do not fit to the next page. Also guard against NULL names/values from a sensor manager. --- src/helpers/CommonCLI.cpp | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index 04199e24..5d7501d9 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -326,18 +326,26 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re if (start >= end) { strcpy(reply, "no custom var"); } else { + const int reply_max = 160; // callers pass a 160-byte reply buffer + const int next_reserve = 16; // room for "... next:NNN" sprintf(dp, "%d vars\n", end); dp = strchr(dp, 0); int i; - for (i = start; i < end && (dp-reply < 134); i++) { - sprintf(dp, "%s=%s\n", - _sensors->getSettingName(i), - _sensors->getSettingValue(i)); + for (i = start; i < end; i++) { + const char* name = _sensors->getSettingName(i); + const char* value = _sensors->getSettingValue(i); + if (name == NULL) name = "?"; + if (value == NULL) value = ""; + int room = reply_max - next_reserve - (int)(dp - reply); + int need = snprintf(NULL, 0, "%s=%s\n", name, value); + if (need >= room && i > start) break; // continue on the next page + snprintf(dp, room, "%s=%s\n", name, value); // a single oversized entry is truncated dp = strchr(dp, 0); + if (need >= room) { i++; break; } } if (i < end) { - sprintf(dp, "... next:%d", i); - } else { + snprintf(dp, reply_max - (int)(dp - reply), "... next:%d", i); + } else if (dp > reply && *(dp-1) == '\n') { *(dp-1) = 0; // remove last CR } } From fee7a5a4c10a6e0d330ccb2a57592aabb557c64e Mon Sep 17 00:00:00 2001 From: zxw <2680562856@qq.com> Date: Thu, 15 Oct 2026 17:37:39 +0800 Subject: [PATCH 46/79] feat: Add low-power white status LED for SenseCAP Solar P1 Pro Add a dimmed heartbeat for the SenseCAP Solar (P1 Pro) white LED in the repeater firmware, implemented entirely as a SenseCapSolarBoard::loop() override so no example main.cpp needs to be touched: - 100 ms pulse every 5 s, dimmed to 10% brightness via hardware PWM (NRF_PWM0 / HwPWM0, 1 kHz, COUNTERTOP 16000, compare 1600) - during the 4.9 s off phase the PWM peripheral is stopped (ENABLE=0), the pin is released (PSEL disconnect) and GPIO 11 is held LOW, so no HFCLK is demanded between pulses - on successful application-level "start ota" the PWM is stopped and the white LED goes steady full-brightness while BLE OTA is advertised; on failed start the heartbeat keeps blinking - powerOff() stops/releases the heartbeat PWM before shutting the LED off - non-blocking millis() timing with wrap-safe unsigned arithmetic - gated by SENSECAP_SOLAR_WHITE_LED, defined only in the SenseCap_Solar_repeater PlatformIO env, so the room-server and companion firmwares sharing this board class are unaffected No changes to LoRa/repeater forwarding, the blue TX LED, charging LEDs, GPS, power management, config storage or the bootloader. --- .../sensecap_solar/SenseCapSolarBoard.cpp | 77 +++++++++++++++++++ variants/sensecap_solar/SenseCapSolarBoard.h | 23 ++++++ variants/sensecap_solar/platformio.ini | 2 + 3 files changed, 102 insertions(+) diff --git a/variants/sensecap_solar/SenseCapSolarBoard.cpp b/variants/sensecap_solar/SenseCapSolarBoard.cpp index da7964c9..058c1620 100644 --- a/variants/sensecap_solar/SenseCapSolarBoard.cpp +++ b/variants/sensecap_solar/SenseCapSolarBoard.cpp @@ -1,5 +1,6 @@ #include #include +#include #include "SenseCapSolarBoard.h" @@ -50,6 +51,9 @@ void SenseCapSolarBoard::begin() { #ifdef LED_WHITE pinMode(LED_WHITE, OUTPUT); digitalWrite(LED_WHITE, LOW); +#ifdef SENSECAP_SOLAR_WHITE_LED + white_led_last_pulse_at_ = millis(); // first heartbeat pulse 5 s after boot +#endif #endif #ifdef LED_BLUE pinMode(LED_BLUE, OUTPUT); @@ -67,3 +71,76 @@ void SenseCapSolarBoard::begin() { delay(10); // give sx1262 some time to power up } + +#ifdef SENSECAP_SOLAR_WHITE_LED +// Dimmed WHITE heartbeat using hardware PWM (repeater builds only). +// +// Peripheral audit for this firmware: no analogWrite()/tone() callers, no +// NeoPixel/Servo, Bluefruit52Lib uses no PWM, SoftDevice S140 does not own +// any PWM instance -> NRF_PWM0 (HwPWM0) is free. takeOwnership() fences the +// instance so a future analogWrite() caller cannot claim it. +// +// Timing: base clock 16 MHz (DIV_1), COUNTERTOP 16000 -> exactly 1 kHz. +// Duty: HardwarePWM non-inverted values place bit15 (active-HIGH polarity), +// so compare 1600 => HIGH for [0,1600)/16000 => 10% duty, active-high. +static const uint32_t WHITE_LED_PWM_TOKEN = 0x5031574C; // 'P1WL' +static const uint16_t WHITE_LED_PWM_TOP = 16000; // 16 MHz / 16000 = 1 kHz +static const uint16_t WHITE_LED_PWM_DUTY = 1600; // 1600 / 16000 = 10 % +static_assert(WHITE_LED_PWM_TOP <= 0x7FFF, "PWM compare values are 15-bit"); +static_assert(WHITE_LED_PWM_DUTY < WHITE_LED_PWM_TOP, "duty must stay below COUNTERTOP"); + +void SenseCapSolarBoard::whiteLedHeartbeatOn() { + HwPWM0.takeOwnership(WHITE_LED_PWM_TOKEN); // no-op once owned; keeps analogWrite away + HwPWM0.setClockDiv(PWM_PRESCALER_PRESCALER_DIV_1); // 16 MHz base clock + HwPWM0.setMaxValue(WHITE_LED_PWM_TOP); // 1 kHz period + HwPWM0.addPin(LED_WHITE); // drives pin LOW, connects PSEL + HwPWM0.writePin(LED_WHITE, WHITE_LED_PWM_DUTY); // enables + starts 10% PWM +} + +void SenseCapSolarBoard::whiteLedHeartbeatOff() { + HwPWM0.stop(); // ENABLE=0: waveform and its HFCLK demand stop + if (HwPWM0.checkPin(LED_WHITE)) { + HwPWM0.removePin(LED_WHITE); // disconnect PSEL; GPIO block drives again + } + pinMode(LED_WHITE, OUTPUT); + digitalWrite(LED_WHITE, LOW); // deterministic LOW during the 4900 ms off phase +} + +// 100 ms pulse every 5000 ms, non-blocking millis() with wrap-safe unsigned +// arithmetic. Called from loop(); frozen while the OTA steady-on owns the LED. +void SenseCapSolarBoard::updateWhiteStatusLed() { + if (white_led_ota_active_) return; + + const uint32_t now = millis(); + const uint32_t elapsed = (uint32_t)(now - white_led_last_pulse_at_); + if (white_led_pulse_active_ && elapsed >= 100U) { + whiteLedHeartbeatOff(); // stop PWM, pin LOW + white_led_pulse_active_ = false; + } + if (!white_led_pulse_active_ && elapsed >= 5000U) { + whiteLedHeartbeatOn(); // 1 kHz hardware PWM, 10% duty + white_led_pulse_active_ = true; + white_led_last_pulse_at_ = now; + } +} + +void SenseCapSolarBoard::loop() { + mesh::MainBoard::loop(); // keep base housekeeping (watchdog etc.) if it ever gains any + updateWhiteStatusLed(); +} + +// `start ota` keeps WHITE on for as long as the application is advertising +// its BLE OTA service. The heartbeat PWM is stopped and the pin released +// first, so steady-on is a plain full-brightness GPIO drive (no PWM vs +// digitalWrite conflict). On a failed start nothing changes: the heartbeat +// keeps its normal blinking. +bool SenseCapSolarBoard::startOTAUpdate(const char *id, char reply[]) { + const bool started = NRF52Board::startOTAUpdate(id, reply); + if (started) { + white_led_ota_active_ = true; + whiteLedHeartbeatOff(); + digitalWrite(LED_WHITE, LED_STATE_ON); + } + return started; +} +#endif // SENSECAP_SOLAR_WHITE_LED diff --git a/variants/sensecap_solar/SenseCapSolarBoard.h b/variants/sensecap_solar/SenseCapSolarBoard.h index 5a8861c2..1b4b5711 100644 --- a/variants/sensecap_solar/SenseCapSolarBoard.h +++ b/variants/sensecap_solar/SenseCapSolarBoard.h @@ -5,6 +5,19 @@ #include class SenseCapSolarBoard : public NRF52BoardDCDC { +#ifdef SENSECAP_SOLAR_WHITE_LED + // Dimmed white-LED heartbeat state (repeater builds only; enabled with + // -D SENSECAP_SOLAR_WHITE_LED in the PlatformIO env, so room-server and + // companion firmwares sharing this board class are unaffected). + bool white_led_ota_active_ = false; + bool white_led_pulse_active_ = false; + uint32_t white_led_last_pulse_at_ = 0; + + void whiteLedHeartbeatOn(); // start 1 kHz PWM at 10% duty on LED_WHITE + void whiteLedHeartbeatOff(); // stop/release PWM, hold LED_WHITE LOW + void updateWhiteStatusLed(); // non-blocking 100 ms pulse every 5000 ms +#endif + protected: #ifdef NRF52_POWER_MANAGEMENT void initiateShutdown(uint8_t reason) override; @@ -14,6 +27,13 @@ public: SenseCapSolarBoard() : NRF52Board("SENSECAP_SOLAR_OTA") {} void begin(); +#ifdef SENSECAP_SOLAR_WHITE_LED + // Runs the white-LED heartbeat; invoked by the example main loops via the + // existing board.loop() call (mesh::MainBoard::loop() is a no-op by default). + void loop() override; + bool startOTAUpdate(const char *id, char reply[]) override; +#endif + #if defined(P_LORA_TX_LED) void onBeforeTransmit() override { digitalWrite(P_LORA_TX_LED, HIGH); // turn TX LED on @@ -38,6 +58,9 @@ public: } void powerOff() override { +#ifdef SENSECAP_SOLAR_WHITE_LED + whiteLedHeartbeatOff(); // stop/release the heartbeat PWM before shutdown +#endif digitalWrite(LED_WHITE, LOW); digitalWrite(LED_BLUE, LOW); diff --git a/variants/sensecap_solar/platformio.ini b/variants/sensecap_solar/platformio.ini index a2a9c85a..60e11e9f 100644 --- a/variants/sensecap_solar/platformio.ini +++ b/variants/sensecap_solar/platformio.ini @@ -45,6 +45,8 @@ build_flags = -D ADVERT_LON=0.0 -D ADMIN_PASSWORD='"password"' -D MAX_NEIGHBOURS=50 +; dimmed white-LED heartbeat + OTA steady-on (repeater builds only) + -D SENSECAP_SOLAR_WHITE_LED=1 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${SenseCap_Solar.build_src_filter} From 93254adbca827a768bdbf8ad35b6221ecc44ee2f Mon Sep 17 00:00:00 2001 From: R0ck Date: Fri, 30 Oct 2026 14:05:25 +0000 Subject: [PATCH 47/79] radiolib: drop received packets whose LoRa header says no CRC. --- src/helpers/radiolib/CustomLLCC68Wrapper.h | 5 +++++ src/helpers/radiolib/CustomLR1110Wrapper.h | 5 +++++ src/helpers/radiolib/CustomLR1121Wrapper.h | 5 +++++ src/helpers/radiolib/CustomLR2021Wrapper.h | 5 +++++ src/helpers/radiolib/CustomSTM32WLxWrapper.h | 5 +++++ src/helpers/radiolib/CustomSX1262Wrapper.h | 5 +++++ src/helpers/radiolib/CustomSX1268Wrapper.h | 5 +++++ src/helpers/radiolib/RadioLibWrappers.cpp | 3 +++ src/helpers/radiolib/RadioLibWrappers.h | 1 + 9 files changed, 39 insertions(+) diff --git a/src/helpers/radiolib/CustomLLCC68Wrapper.h b/src/helpers/radiolib/CustomLLCC68Wrapper.h index ae0fe0a2..36cde0f6 100644 --- a/src/helpers/radiolib/CustomLLCC68Wrapper.h +++ b/src/helpers/radiolib/CustomLLCC68Wrapper.h @@ -20,6 +20,11 @@ public: } + bool lastRxHadCRC() override { + bool crc = true; + ((CustomLLCC68 *)_radio)->getLoRaRxHeaderInfo(NULL, &crc); + return crc; + } bool isReceivingPacket() override { return ((CustomLLCC68 *)_radio)->isReceiving(); } diff --git a/src/helpers/radiolib/CustomLR1110Wrapper.h b/src/helpers/radiolib/CustomLR1110Wrapper.h index e7aaeb93..66bcb3b4 100644 --- a/src/helpers/radiolib/CustomLR1110Wrapper.h +++ b/src/helpers/radiolib/CustomLR1110Wrapper.h @@ -19,6 +19,11 @@ public: ((CustomLR1110 *)_radio)->setMaxPayloadMillis(pm.payloadMillis); } + bool lastRxHadCRC() override { + bool crc = true; + ((CustomLR1110 *)_radio)->getLoRaRxHeaderInfo(NULL, &crc); + return crc; + } bool isReceivingPacket() override { return ((CustomLR1110 *)_radio)->isReceiving(); } diff --git a/src/helpers/radiolib/CustomLR1121Wrapper.h b/src/helpers/radiolib/CustomLR1121Wrapper.h index 5a754cee..70912f1e 100644 --- a/src/helpers/radiolib/CustomLR1121Wrapper.h +++ b/src/helpers/radiolib/CustomLR1121Wrapper.h @@ -20,6 +20,11 @@ public: } void doResetAGC() override { lr11x0ResetAGC((LR11x0 *)_radio, ((CustomLR1121 *)_radio)->getFreqMHz(), getRxBoostedGainMode()); } + bool lastRxHadCRC() override { + bool crc = true; + ((CustomLR1121 *)_radio)->getLoRaRxHeaderInfo(NULL, &crc); + return crc; + } bool isReceivingPacket() override { return ((CustomLR1121 *)_radio)->isReceiving(); } diff --git a/src/helpers/radiolib/CustomLR2021Wrapper.h b/src/helpers/radiolib/CustomLR2021Wrapper.h index c60bfda3..81c2feac 100644 --- a/src/helpers/radiolib/CustomLR2021Wrapper.h +++ b/src/helpers/radiolib/CustomLR2021Wrapper.h @@ -81,6 +81,11 @@ public: return tSym; } + bool lastRxHadCRC() override { + bool crc = true; + ((CustomLR2021 *)_radio)->getLoRaRxHeaderInfo(NULL, &crc); + return crc; + } bool isReceivingPacket() override { return ((CustomLR2021 *)_radio)->isReceiving(); } diff --git a/src/helpers/radiolib/CustomSTM32WLxWrapper.h b/src/helpers/radiolib/CustomSTM32WLxWrapper.h index a4ba4971..bc93de75 100644 --- a/src/helpers/radiolib/CustomSTM32WLxWrapper.h +++ b/src/helpers/radiolib/CustomSTM32WLxWrapper.h @@ -20,6 +20,11 @@ public: ((CustomSTM32WLx *)_radio)->setMaxPayloadMillis(pm.payloadMillis); } + bool lastRxHadCRC() override { + bool crc = true; + ((CustomSTM32WLx *)_radio)->getLoRaRxHeaderInfo(NULL, &crc); + return crc; + } bool isReceivingPacket() override { return ((CustomSTM32WLx *)_radio)->isReceiving(); } diff --git a/src/helpers/radiolib/CustomSX1262Wrapper.h b/src/helpers/radiolib/CustomSX1262Wrapper.h index be314471..cdd195fb 100644 --- a/src/helpers/radiolib/CustomSX1262Wrapper.h +++ b/src/helpers/radiolib/CustomSX1262Wrapper.h @@ -23,6 +23,11 @@ public: ((CustomSX1262 *)_radio)->setMaxPayloadMillis(pm.payloadMillis); } + bool lastRxHadCRC() override { + bool crc = true; + ((CustomSX1262 *)_radio)->getLoRaRxHeaderInfo(NULL, &crc); + return crc; + } bool isReceivingPacket() override { return ((CustomSX1262 *)_radio)->isReceiving(); } diff --git a/src/helpers/radiolib/CustomSX1268Wrapper.h b/src/helpers/radiolib/CustomSX1268Wrapper.h index 70f5dabd..ec11f147 100644 --- a/src/helpers/radiolib/CustomSX1268Wrapper.h +++ b/src/helpers/radiolib/CustomSX1268Wrapper.h @@ -23,6 +23,11 @@ public: ((CustomSX1268 *)_radio)->setMaxPayloadMillis(pm.payloadMillis); } + bool lastRxHadCRC() override { + bool crc = true; + ((CustomSX1268 *)_radio)->getLoRaRxHeaderInfo(NULL, &crc); + return crc; + } bool isReceivingPacket() override { return ((CustomSX1268 *)_radio)->isReceiving(); } diff --git a/src/helpers/radiolib/RadioLibWrappers.cpp b/src/helpers/radiolib/RadioLibWrappers.cpp index e4d2ba1c..0faeebac 100644 --- a/src/helpers/radiolib/RadioLibWrappers.cpp +++ b/src/helpers/radiolib/RadioLibWrappers.cpp @@ -132,6 +132,9 @@ int RadioLibWrapper::recvRaw(uint8_t* bytes, int sz) { if (len > 0) { if (len > sz) { len = sz; } int err = _radio->readData(bytes, len); + if (err == RADIOLIB_ERR_NONE && !lastRxHadCRC()) { + err = RADIOLIB_ERR_LORA_HEADER_DAMAGED; // header says no CRC, so the payload was never checked + } if (err != RADIOLIB_ERR_NONE) { MESH_DEBUG_PRINTLN("RadioLibWrapper: error: readData(%d)", err); len = 0; diff --git a/src/helpers/radiolib/RadioLibWrappers.h b/src/helpers/radiolib/RadioLibWrappers.h index 77dd9311..9f572572 100644 --- a/src/helpers/radiolib/RadioLibWrappers.h +++ b/src/helpers/radiolib/RadioLibWrappers.h @@ -26,6 +26,7 @@ protected: void startRecv(); float packetScoreInt(float snr, int sf, int packet_len); virtual bool isReceivingPacket() =0; + virtual bool lastRxHadCRC() { return true; } virtual void doResetAGC(); public: From 90ffa57c5f999f109f698090e3c270987b2524f1 Mon Sep 17 00:00:00 2001 From: Juraj Bednar Date: Sun, 1 Nov 2026 13:32:38 +0100 Subject: [PATCH 48/79] Add Road Events allocation for GroupData --- docs/number_allocations.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/number_allocations.md b/docs/number_allocations.md index 79cc90b8..44cd25bf 100644 --- a/docs/number_allocations.md +++ b/docs/number_allocations.md @@ -20,6 +20,7 @@ Once you have a working app/project, you need to be able to demonstrate it exist | 0120 | MCO Advanced | most.original.address@gmail.com — https://hdden.ru/MCOa/ | | 0130 - 013F | StreamSensor | william@housedillon.com - https://housedillon.com/blog/lora-e5-with-seeed-fusion | | 0140 | Nelos | support@nelos.app — https://nelos.app | +| 0150 | Road Events | juraj@bednar.io — https://github.com/jooray/roadbeacon/blob/main/nips/road-events.md | | FF00 - FFFF | -reserved for testing/dev- | | (add rows, inside the range 0100 - FEFF for custom apps) From 287c5e21cf2867477cfe94fd6c5afc905fd11526 Mon Sep 17 00:00:00 2001 From: Will MacGregor Date: Wed, 4 Nov 2026 09:46:27 -0500 Subject: [PATCH 49/79] Enable simple_room_server on the STM32 platform The room server gated its filesystem paths on NRF52_PLATFORM only, so an STM32 build fell through to the ESP32 branch and failed to compile: MyMesh.cpp:147: no matching function for call to 'Adafruit_LittleFS::open(const char*&, const char [2], bool)' main.cpp:69: 'store' was not declared in this scope STM32 uses the same InternalFS / Adafruit_LittleFS API as nRF52, including append semantics (FILE_O_WRITE opens LFS_O_RDWR|LFS_O_CREAT and then seeks to the end), so the nRF52 branch is already correct for it. Add STM32_PLATFORM alongside NRF52_PLATFORM in the four remaining gates; saveIdentity() already did this. This unblocks the room_server example on the existing STM32WL boards (wio-e5-mini, wio-e5-dev, rak3x72, tiny_relay) as well as new ones. Co-Authored-By: Claude Opus 5 (1M context) --- examples/simple_room_server/MyMesh.cpp | 4 ++-- examples/simple_room_server/MyMesh.h | 2 +- examples/simple_room_server/main.cpp | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/simple_room_server/MyMesh.cpp b/examples/simple_room_server/MyMesh.cpp index 935fd7f9..b1a88dd8 100644 --- a/examples/simple_room_server/MyMesh.cpp +++ b/examples/simple_room_server/MyMesh.cpp @@ -140,7 +140,7 @@ mesh::Packet *MyMesh::createSelfAdvert() { } File MyMesh::openAppend(const char *fname) { -#if defined(NRF52_PLATFORM) +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) return _fs->open(fname, FILE_O_WRITE); #elif defined(RP2040_PLATFORM) return _fs->open(fname, "a"); @@ -782,7 +782,7 @@ void MyMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, } bool MyMesh::formatFileSystem() { -#if defined(NRF52_PLATFORM) +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) return InternalFS.format(); #elif defined(RP2040_PLATFORM) return LittleFS.format(); diff --git a/examples/simple_room_server/MyMesh.h b/examples/simple_room_server/MyMesh.h index 4dee8bdb..974e633a 100644 --- a/examples/simple_room_server/MyMesh.h +++ b/examples/simple_room_server/MyMesh.h @@ -3,7 +3,7 @@ #include // needed for PlatformIO #include -#if defined(NRF52_PLATFORM) +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) #include #elif defined(RP2040_PLATFORM) #include diff --git a/examples/simple_room_server/main.cpp b/examples/simple_room_server/main.cpp index 65fc55ef..4bfad4e5 100644 --- a/examples/simple_room_server/main.cpp +++ b/examples/simple_room_server/main.cpp @@ -50,7 +50,7 @@ void setup() { fast_rng.begin(radio_driver.getRngSeed()); FILESYSTEM* fs; -#if defined(NRF52_PLATFORM) +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) InternalFS.begin(); fs = &InternalFS; IdentityStore store(InternalFS, ""); From afb56bb976bccb9cf95d44fe8aff2f6dca13b47d Mon Sep 17 00:00:00 2001 From: Will MacGregor Date: Wed, 4 Nov 2026 09:46:40 -0500 Subject: [PATCH 50/79] Add variant for ST Nucleo-WL55JC1 Adds repeater, room_server, companion_radio_usb and kiss_modem environments for the NUCLEO-WL55JC1 (STM32WL55JC, integrated SubGHz radio). Notes on the board setup: - Uses the upstream nucleo_wl55jc board. PlatformIO's boards_remap maps it to the core's NUCLEO_WL55JC1 variant, so the LEDs, user buttons and the LPUART1 -> ST-LINK VCP serial mapping all come from the core rather than being redefined here. - The RF switch table is built from the core's LORAWAN_RFSWITCH_* macros (SP3T front end on PC3/PC4/PC5) so it tracks upstream if those are ever revised. Both RFO_LP and RFO_HP are registered, so RadioLib selects HP above 14 dBm and LP below it. - board_build.extra_flags pins the device to STM32WL55xx. The stock board manifest declares product_line STM32WL55xx but extra_flags -DSTM32WLE5xx; that only works because every #elif chain happens to test WL55xx first. - The Nucleo's LD1..LD3 are driven active HIGH, so the TX LED hooks are inverted relative to STM32Board's active-LOW default. - 32 KB reserved at the top of flash for LittleFS, as on the other STM32WL variants. Verified on hardware: all four environments build; repeater and room_server flash and run over ST-LINK; identity and prefs persist across reboot and across a firmware swap; and GPIOC reads back the documented RX levels at idle, confirming the front-end switch is driven correctly. Co-Authored-By: Claude Opus 5 (1M context) --- variants/nucleo_wl55jc/platformio.ini | 57 +++++++++++++++++++++++ variants/nucleo_wl55jc/target.cpp | 65 +++++++++++++++++++++++++++ variants/nucleo_wl55jc/target.h | 47 +++++++++++++++++++ variants/nucleo_wl55jc/variant.h | 5 +++ 4 files changed, 174 insertions(+) create mode 100644 variants/nucleo_wl55jc/platformio.ini create mode 100644 variants/nucleo_wl55jc/target.cpp create mode 100644 variants/nucleo_wl55jc/target.h create mode 100644 variants/nucleo_wl55jc/variant.h diff --git a/variants/nucleo_wl55jc/platformio.ini b/variants/nucleo_wl55jc/platformio.ini new file mode 100644 index 00000000..0de5ba6f --- /dev/null +++ b/variants/nucleo_wl55jc/platformio.ini @@ -0,0 +1,57 @@ +[nucleo_wl55jc] +extends = stm32_base +board = nucleo_wl55jc +; The upstream board manifest tags the part as STM32WLE5xx even though its +; product_line is STM32WL55xx. Pin both to WL55 so a single device header and +; startup file (startup_stm32wl55xx_cm4.s) are in play. +board_build.extra_flags = -DSTM32WL -DSTM32WLxx -DSTM32WL55xx +board_upload.maximum_size = 229376 ; 32kb at the top of flash reserved for LittleFS +build_flags = ${stm32_base.build_flags} + -D RADIO_CLASS=CustomSTM32WLx + -D WRAPPER_CLASS=CustomSTM32WLxWrapper + -D LORA_TX_POWER=22 + -D SPI_INTERFACES_COUNT=0 + -D RX_BOOSTED_GAIN=true + -D STM32WL_TCXO_VOLTAGE=1.7 + -D P_LORA_TX_LED=LED_BLUE + -D PIN_USER_BTN=USER_BTN + -D USER_BTN_PRESSED=LOW + -I variants/nucleo_wl55jc +build_src_filter = ${stm32_base.build_src_filter} + +<../variants/nucleo_wl55jc> + +[env:nucleo_wl55jc_repeater] +extends = nucleo_wl55jc +build_flags = ${nucleo_wl55jc.build_flags} + -D ADVERT_NAME='"Nucleo WL55JC Repeater"' + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=50 +build_src_filter = ${nucleo_wl55jc.build_src_filter} + +<../examples/simple_repeater/*.cpp> + +[env:nucleo_wl55jc_companion_radio_usb] +extends = nucleo_wl55jc +build_flags = ${nucleo_wl55jc.build_flags} + -D MAX_CONTACTS=100 + -D MAX_GROUP_CHANNELS=8 + -D ENABLE_USB_INTERFACE ; binds to Serial, i.e. the ST-LINK virtual COM port +build_src_filter = ${nucleo_wl55jc.build_src_filter} + +<../examples/companion_radio/*.cpp> +lib_deps = ${nucleo_wl55jc.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[env:nucleo_wl55jc_kiss_modem] +extends = nucleo_wl55jc +build_src_filter = ${nucleo_wl55jc.build_src_filter} + +<../examples/kiss_modem/> + +[env:nucleo_wl55jc_room_server] +extends = nucleo_wl55jc +build_flags = ${nucleo_wl55jc.build_flags} + -D ADVERT_NAME='"Nucleo WL55JC Room"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D ROOM_PASSWORD='"hello"' +build_src_filter = ${nucleo_wl55jc.build_src_filter} + +<../examples/simple_room_server> diff --git a/variants/nucleo_wl55jc/target.cpp b/variants/nucleo_wl55jc/target.cpp new file mode 100644 index 00000000..8e773adf --- /dev/null +++ b/variants/nucleo_wl55jc/target.cpp @@ -0,0 +1,65 @@ +#include +#include "target.h" +#include + +NucleoWL55JCBoard board; + +RADIO_CLASS radio = new STM32WLx_Module(); + +WRAPPER_CLASS radio_driver(radio, board); + +// The NUCLEO-WL55JC1 drives an SP3T front-end switch from FE_CTRL1..3 (PC4, PC5, PC3), +// routing the single SMA between RX, RFO_LP and RFO_HP. Pin order and levels are taken +// straight from the core's board definition (variant_NUCLEO_WL55JC1.h) so they stay in +// sync with upstream. +static const uint32_t rfswitch_pins[] = {LORAWAN_RFSWITCH_PINS, RADIOLIB_NC, RADIOLIB_NC}; +static const Module::RfSwitchMode_t rfswitch_table[] = { + {STM32WLx::MODE_IDLE, {LORAWAN_RFSWITCH_OFF_VALUES}}, + {STM32WLx::MODE_RX, {LORAWAN_RFSWITCH_RX_VALUES}}, + {STM32WLx::MODE_TX_LP, {LORAWAN_RFSWITCH_RFO_LP_VALUES}}, + {STM32WLx::MODE_TX_HP, {LORAWAN_RFSWITCH_RFO_HP_VALUES}}, + END_OF_MODE_TABLE, +}; + +VolatileRTCClock rtc_clock; +SensorManager sensors; + +#ifndef LORA_CR + #define LORA_CR 5 +#endif + +#ifndef STM32WL_TCXO_VOLTAGE + // The board is fitted with a 32MHz TCXO powered from the radio's DIO3 at 1.7V + #define STM32WL_TCXO_VOLTAGE 1.7 +#endif + +#ifndef LORA_TX_POWER + #define LORA_TX_POWER 22 +#endif + +bool radio_init() { + radio.setRfSwitchTable(rfswitch_pins, rfswitch_table); + + // Both PA paths are registered above, so RadioLib picks RFO_HP whenever the + // requested power is above 14dBm, and RFO_LP below that. + int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, LORA_TX_POWER, 16, STM32WL_TCXO_VOLTAGE, 0); + + if (status != RADIOLIB_ERR_NONE) { + Serial.print("ERROR: radio init failed: "); + Serial.println(status); + return false; // fail + } + + #ifdef RX_BOOSTED_GAIN + radio.setRxBoostedGainMode(RX_BOOSTED_GAIN); + #endif + + radio.setCRC(1); + + return true; // success +} + +mesh::LocalIdentity radio_new_identity() { + RadioNoiseListener rng(radio); + return mesh::LocalIdentity(&rng); // create new random identity +} diff --git a/variants/nucleo_wl55jc/target.h b/variants/nucleo_wl55jc/target.h new file mode 100644 index 00000000..4b1c3ada --- /dev/null +++ b/variants/nucleo_wl55jc/target.h @@ -0,0 +1,47 @@ +#pragma once + +#define RADIOLIB_STATIC_ONLY 1 +#include +#include +#include +#include +#include +#include + +class NucleoWL55JCBoard : public STM32Board { +public: + void begin() override { + STM32Board::begin(); + + pinMode(P_LORA_TX_LED, OUTPUT); + digitalWrite(P_LORA_TX_LED, LOW); // see note on LED polarity below + pinMode(PIN_USER_BTN, INPUT_PULLUP); + } + + const char* getManufacturerName() const override { + return "ST Nucleo WL55JC1"; + } + + // LD1..LD3 on the Nucleo are driven active HIGH, whereas STM32Board's + // default TX-LED handling assumes the active LOW wiring used by the + // Wio-E5 boards. Invert both halves here. + void onBeforeTransmit() override { + digitalWrite(P_LORA_TX_LED, HIGH); // turn TX LED on + } + void onAfterTransmit() override { + digitalWrite(P_LORA_TX_LED, LOW); // turn TX LED off + } + + // No battery on this dev board, it is USB/ST-LINK powered. + uint16_t getBattMilliVolts() override { + return 0; + } +}; + +extern NucleoWL55JCBoard board; +extern WRAPPER_CLASS radio_driver; +extern VolatileRTCClock rtc_clock; +extern SensorManager sensors; + +bool radio_init(); +mesh::LocalIdentity radio_new_identity(); diff --git a/variants/nucleo_wl55jc/variant.h b/variants/nucleo_wl55jc/variant.h new file mode 100644 index 00000000..a006d1f1 --- /dev/null +++ b/variants/nucleo_wl55jc/variant.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +#undef RNG From 9af19c870c6236d0aa310137badd7616c5116cd0 Mon Sep 17 00:00:00 2001 From: Will MacGregor Date: Wed, 4 Nov 2026 09:51:33 -0500 Subject: [PATCH 51/79] Build nucleo_wl55jc_repeater in PR build check Adds the new variant to the PR build matrix, next to the existing STM32 entry, so it is covered by CI going forward. Co-Authored-By: Claude Opus 5 (1M context) --- .github/workflows/pr-build-check.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/pr-build-check.yml b/.github/workflows/pr-build-check.yml index cebf0cfe..1d431451 100644 --- a/.github/workflows/pr-build-check.yml +++ b/.github/workflows/pr-build-check.yml @@ -40,6 +40,7 @@ jobs: - PicoW_repeater # STM32 - wio-e5-mini_repeater + - nucleo_wl55jc_repeater # ESP32-C6 - LilyGo_Tlora_C6_repeater_ # LR1110 (nRF52) From c5a0673d678512acb261625c9977dd7d5607d342 Mon Sep 17 00:00:00 2001 From: Rastislav Vysoky Date: Sat, 7 Nov 2026 00:35:47 +0100 Subject: [PATCH 52/79] added rp2350 support, harmonized companions with other variants --- platformio.ini | 3 +- variants/rpi_picow/PicoWBoard.h | 4 + variants/rpi_picow/platformio.ini | 135 ++++++++++++++++++++---------- 3 files changed, 97 insertions(+), 45 deletions(-) diff --git a/platformio.ini b/platformio.ini index 92c94204..9ad9c890 100644 --- a/platformio.ini +++ b/platformio.ini @@ -101,7 +101,8 @@ lib_deps = extends = arduino_base upload_protocol = picotool board_build.core = earlephilhower -platform = https://github.com/maxgerhardt/platform-raspberrypi.git ; framework-arduinopico @ 1.50600.0+sha.6a1d13e9 +platform = https://github.com/maxgerhardt/platform-raspberrypi.git +platform_packages = framework-arduinopico @ https://github.com/earlephilhower/arduino-pico.git#6a1d13e960e0854da2bf328b1a5fc05481d89aba build_flags = ${arduino_base.build_flags} -D RP2040_PLATFORM diff --git a/variants/rpi_picow/PicoWBoard.h b/variants/rpi_picow/PicoWBoard.h index e64590f2..1660fe91 100644 --- a/variants/rpi_picow/PicoWBoard.h +++ b/variants/rpi_picow/PicoWBoard.h @@ -42,7 +42,11 @@ public: } const char* getManufacturerName() const override { + #if defined(PICO_RP2350) + return "Pico 2 W"; + #else return "Pico W"; + #endif } void reboot() override { diff --git a/variants/rpi_picow/platformio.ini b/variants/rpi_picow/platformio.ini index 9814f397..94fc40aa 100644 --- a/variants/rpi_picow/platformio.ini +++ b/variants/rpi_picow/platformio.ini @@ -56,8 +56,8 @@ build_src_filter = ${rpi_picow.build_src_filter} [env:PicoW_companion_radio_usb] extends = rpi_picow build_flags = ${rpi_picow.build_flags} - -D MAX_CONTACTS=100 - -D MAX_GROUP_CHANNELS=8 + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 -D ENABLE_USB_INTERFACE ; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 ; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 @@ -70,33 +70,14 @@ lib_ignore = BLE [env:PicoW_companion_radio_ble] extends = rpi_picow build_flags = ${rpi_picow.build_flags} - -D MAX_CONTACTS=100 - -D MAX_GROUP_CHANNELS=8 + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 -D PIO_FRAMEWORK_ARDUINO_ENABLE_BLUETOOTH + -D ENABLE_WIFI_INTERFACE -D BLE_PIN_CODE=123456 -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 -build_src_filter = ${rpi_picow.build_src_filter} - + - +<../examples/companion_radio/*.cpp> -lib_deps = ${rpi_picow.lib_deps} - densaugeo/base64 @ ~1.4.0 - -; USB + WiFi + BLE together; the interface manager fans frames out to all of them -[env:PicoW_companion_radio] -extends = rpi_picow -build_flags = ${rpi_picow.build_flags} - -D MAX_CONTACTS=100 - -D MAX_GROUP_CHANNELS=8 - -D ENABLE_USB_INTERFACE - -D ENABLE_WIFI_INTERFACE - -D PIO_FRAMEWORK_ARDUINO_ENABLE_BLUETOOTH - -D BLE_PIN_CODE=123456 -; NOTE: DO NOT ENABLE --> -D BLE_DEBUG_LOGGING=1 (shares Serial with the USB interface) -; NOTE: DO NOT ENABLE --> -D WIFI_DEBUG_LOGGING=1 -; -D MESH_PACKET_LOGGING=1 -; -D MESH_DEBUG=1 build_src_filter = ${rpi_picow.build_src_filter} + + @@ -104,29 +85,11 @@ build_src_filter = ${rpi_picow.build_src_filter} lib_deps = ${rpi_picow.lib_deps} densaugeo/base64 @ ~1.4.0 -[env:PicoW_companion_radio_wifi] -extends = rpi_picow -build_flags = ${rpi_picow.build_flags} - -D ENABLE_WIFI_INTERFACE - -D MAX_CONTACTS=100 - -D MAX_GROUP_CHANNELS=8 - -D WIFI_DEBUG_LOGGING=1 - -D WIFI_SSID='""' ; no default network, configure with 'set wifi.ssid' / 'set wifi.pwd' - -D WIFI_PWD='""' -; -D MESH_PACKET_LOGGING=1 -; -D MESH_DEBUG=1 -build_src_filter = ${rpi_picow.build_src_filter} - + - +<../examples/companion_radio/*.cpp> -lib_deps = ${rpi_picow.lib_deps} - densaugeo/base64 @ ~1.4.0 -lib_ignore = BLE - [env:PicoW_terminal_chat] extends = rpi_picow build_flags = ${rpi_picow.build_flags} - -D MAX_CONTACTS=100 - -D MAX_GROUP_CHANNELS=1 + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${rpi_picow.build_src_filter} @@ -138,3 +101,87 @@ lib_deps = ${rpi_picow.lib_deps} extends = rpi_picow build_src_filter = ${rpi_picow.build_src_filter} +<../examples/kiss_modem/> + +[rpi_pico2w] +extends = rp2040_base +board = rpipico2w +board_build.core = earlephilhower +board_build.filesystem_size = 0.5m +build_flags = ${rpi_picow.build_flags} +build_src_filter = ${rpi_picow.build_src_filter} +lib_deps = ${rpi_picow.lib_deps} + +[env:Pico2W_repeater] +extends = rpi_pico2w +build_flags = ${rpi_pico2w.build_flags} + -D ADVERT_NAME='"Pico2W Repeater"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=50 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${rpi_pico2w.build_src_filter} + +<../examples/simple_repeater> + +[env:Pico2W_room_server] +extends = rpi_pico2w +build_flags = ${rpi_pico2w.build_flags} + -D ADVERT_NAME='"Test Room"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D ROOM_PASSWORD='"hello"' +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${rpi_pico2w.build_src_filter} + +<../examples/simple_room_server> + +[env:Pico2W_companion_radio_usb] +extends = rpi_pico2w +build_flags = ${rpi_pico2w.build_flags} + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D ENABLE_USB_INTERFACE +; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1 +; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1 +build_src_filter = ${rpi_pico2w.build_src_filter} + +<../examples/companion_radio/*.cpp> +lib_deps = ${rpi_pico2w.lib_deps} + densaugeo/base64 @ ~1.4.0 +lib_ignore = BLE + +[env:Pico2W_companion_radio_ble] +extends = rpi_pico2w +build_flags = ${rpi_pico2w.build_flags} + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D PIO_FRAMEWORK_ARDUINO_ENABLE_BLUETOOTH + -D ENABLE_WIFI_INTERFACE + -D BLE_PIN_CODE=123456 + -D BLE_DEBUG_LOGGING=1 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${rpi_pico2w.build_src_filter} + + + + + +<../examples/companion_radio/*.cpp> +lib_deps = ${rpi_pico2w.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[env:Pico2W_terminal_chat] +extends = rpi_pico2w +build_flags = ${rpi_pico2w.build_flags} + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${rpi_pico2w.build_src_filter} + +<../examples/simple_secure_chat/main.cpp> +lib_deps = ${rpi_pico2w.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[env:Pico2W_kiss_modem] +extends = rpi_pico2w +build_src_filter = ${rpi_pico2w.build_src_filter} + +<../examples/kiss_modem/> From 683680d83b0f475db1cc2a5bac4f58ff10e69687 Mon Sep 17 00:00:00 2001 From: Rastislav Vysoky Date: Sat, 7 Nov 2026 00:49:21 +0100 Subject: [PATCH 53/79] fix: pin to 5.6.0 --- platformio.ini | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/platformio.ini b/platformio.ini index 9ad9c890..f66fbf2e 100644 --- a/platformio.ini +++ b/platformio.ini @@ -101,8 +101,8 @@ lib_deps = extends = arduino_base upload_protocol = picotool board_build.core = earlephilhower -platform = https://github.com/maxgerhardt/platform-raspberrypi.git -platform_packages = framework-arduinopico @ https://github.com/earlephilhower/arduino-pico.git#6a1d13e960e0854da2bf328b1a5fc05481d89aba +; commit points to framework-arduinopico 5.6.0 +platform = https://github.com/maxgerhardt/platform-raspberrypi.git#4e22a0dcdd94eead72fdf56ea59a3d7c8aa2f379 build_flags = ${arduino_base.build_flags} -D RP2040_PLATFORM From 02081ba500c3cc4d3c3410a4fb6feae30e1b3501 Mon Sep 17 00:00:00 2001 From: Blake Latchford Date: Sat, 7 Nov 2026 10:21:01 -0500 Subject: [PATCH 54/79] Incorporate PR Backtesting into CONTRIBUTING.md I used an LLM to review what changes the likelihood of a PR getting merged. I then asked it to select potential changes based on its findings. I selected from those options and carefully guided the LLM to produce several pull requests. I fed the subset of PRs that failed back into the skill and discovered additional missing factors. --- CONTRIBUTING.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b998610e..da30c3ae 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -18,6 +18,15 @@ Thanks for considering contributing to this project! ### 3. Submitting Code Changes (Pull Requests) +The project receives far more code than it is able to process. +To increase the likelihood of your PR being accepted, please consider +the following: + +- **Keep it small.** Changes of about 10 lines or fewer were merged 64% of the time; changes over 1000 lines, 10%. +- **Keep the description short.** A few sentences on what changed and why is enough. Longer descriptions were merged less often. +- **Build a track record with small fixes first.** First-time contributors were merged 31% of the time, rising to 74% after 10 merged PRs. +- **Open the PR when it is ready for review, not as a draft.** + #### Small fixes (typos, comments, examples, small bug fixes) → Just open a pull request — no prior issue needed @@ -52,6 +61,15 @@ Please follow the existing C++ style (per the .clang-format) (But consistency with existing code is more important than strict rules) +## LLM Agent Specific Advice + +- **Have a human read and understand every line before opening the PR.** Check every claim in the description against the code. +- **Search open PRs first** so you don't duplicate one that's already waiting. +- **Pick a subsystem maintainers are actively merging in.** If several PRs for the same board or feature have sat for weeks with no response, a new one will likely sit too. +- **Prefer low-risk changes.** Build fixes and documentation fixes merge most often (about 61% and 64%). Changes to protocol or behavior, and crash or overflow fixes, get much more scrutiny. +- **Make a minimal diff in the existing style.** Don't reformat, rename, or "tidy" code next to your change. +- **Don't use a templated description.** Lots of headings and boilerplate on a small change reads as generated. Just say what changed, why, and what hardware you tested on. + ## Thank You! > [!NOTE] From 2f00b0e83a8434bbbab14d20328826e5fc146233 Mon Sep 17 00:00:00 2001 From: anders-dc Date: Sun, 8 Nov 2026 11:01:05 +0100 Subject: [PATCH 55/79] fix(companion): guard null _serial in contact overwrite and full callbacks --- examples/companion_radio/MyMesh.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 755c56d1..28e5c3ec 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -341,7 +341,7 @@ uint8_t MyMesh::getAutoAddMaxHops() const { void MyMesh::onContactOverwrite(const uint8_t* pub_key) { _store->deleteBlobByKey(pub_key, PUB_KEY_SIZE); // delete from storage - if (_serial->isConnected()) { + if (_serial && _serial->isConnected()) { out_frame[0] = PUSH_CODE_CONTACT_DELETED; memcpy(&out_frame[1], pub_key, PUB_KEY_SIZE); _serial->writeFrame(out_frame, 1 + PUB_KEY_SIZE); @@ -349,7 +349,7 @@ void MyMesh::onContactOverwrite(const uint8_t* pub_key) { } void MyMesh::onContactsFull() { - if (_serial->isConnected()) { + if (_serial && _serial->isConnected()) { out_frame[0] = PUSH_CODE_CONTACTS_FULL; _serial->writeFrame(out_frame, 1); } From 81afafcb357e832d46aef4f4a79540044ee7158d Mon Sep 17 00:00:00 2001 From: Florent Date: Sun, 1 Nov 2026 20:08:16 -0400 Subject: [PATCH 56/79] gps: add GpsDriver, handle the hardware and software switches in the drivers --- examples/companion_radio/ui-new/UITask.cpp | 8 +- examples/companion_radio/ui-tiny/UITask.cpp | 8 +- examples/simple_repeater/MyMesh.h | 3 + examples/simple_room_server/MyMesh.h | 3 + examples/simple_sensor/SensorMesh.h | 3 + src/helpers/CommonCLI.cpp | 18 ++ src/helpers/CommonCLI.h | 2 + src/helpers/sensors/AirohaGpsDriver.h | 83 +++++ .../sensors/EnvironmentSensorManager.cpp | 249 ++------------- .../sensors/EnvironmentSensorManager.h | 5 - src/helpers/sensors/GpsDriver.h | 18 ++ src/helpers/sensors/LocationProvider.h | 19 ++ .../sensors/MicroNMEALocationProvider.h | 293 +++++++++--------- src/helpers/sensors/NmeaGpsDriver.h | 262 ++++++++++++++++ src/helpers/sensors/RakGpsDriver.h | 112 +++++++ src/helpers/sensors/RakLocationProvider.h | 144 +++++++++ variants/gat562_30s_mesh_kit/target.cpp | 7 +- variants/lilygo_techo/target.cpp | 5 +- variants/rak3401/target.cpp | 8 +- variants/rak4631/target.cpp | 7 +- variants/t1000-e/platformio.ini | 1 + variants/t1000-e/target.cpp | 24 +- variants/t1000-e/target.h | 6 +- variants/thinknode_m1/target.cpp | 59 +--- variants/thinknode_m1/target.h | 3 - variants/thinknode_m1/variant.h | 2 + variants/thinknode_m5/target.cpp | 5 +- variants/thinknode_m5/variant.h | 3 +- 28 files changed, 892 insertions(+), 468 deletions(-) create mode 100644 src/helpers/sensors/AirohaGpsDriver.h create mode 100644 src/helpers/sensors/GpsDriver.h create mode 100644 src/helpers/sensors/NmeaGpsDriver.h create mode 100644 src/helpers/sensors/RakGpsDriver.h create mode 100644 src/helpers/sensors/RakLocationProvider.h diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index 55cae1fe..cfe34cf2 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -392,16 +392,16 @@ public: char buf[50]; int y = 18; bool gps_state = _task->getGPSState(); -#ifdef PIN_GPS_SWITCH - bool hw_gps_state = digitalRead(PIN_GPS_SWITCH); + bool hw_gps_state = nmea != NULL && nmea->isHardwareEnabled(); + if (nmea != NULL && nmea->hasHardwareEnableState()) { if (gps_state != hw_gps_state) { strcpy(buf, gps_state ? "gps off(hw)" : "gps off(sw)"); } else { strcpy(buf, gps_state ? "gps on" : "gps off"); } -#else + } else { strcpy(buf, gps_state ? "gps on" : "gps off"); -#endif + } display.setColor(UIColor::primary_txt); display.drawTextLeftAlign(0, y, buf); if (nmea == NULL) { diff --git a/examples/companion_radio/ui-tiny/UITask.cpp b/examples/companion_radio/ui-tiny/UITask.cpp index 6bf33849..035340a8 100644 --- a/examples/companion_radio/ui-tiny/UITask.cpp +++ b/examples/companion_radio/ui-tiny/UITask.cpp @@ -254,16 +254,16 @@ public: char buf[50]; int y = 8; bool gps_state = _task->getGPSState(); -#ifdef PIN_GPS_SWITCH - bool hw_gps_state = digitalRead(PIN_GPS_SWITCH); + bool hw_gps_state = nmea != NULL && nmea->isHardwareEnabled(); + if (nmea != NULL && nmea->hasHardwareEnableState()) { if (gps_state != hw_gps_state) { strcpy(buf, gps_state ? "gps off(hw)" : "gps off(sw)"); } else { strcpy(buf, gps_state ? "gps on" : "gps off"); } -#else + } else { strcpy(buf, gps_state ? "gps on" : "gps off"); -#endif + } display.setColor(UIColor::primary_txt); display.drawTextLeftAlign(0, y, buf); if (nmea == NULL) { diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index dc893258..1d975a94 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -159,6 +159,9 @@ protected: #if ENV_INCLUDE_GPS == 1 void applyGpsPrefs() { + char period[11]; + snprintf(period, sizeof(period), "%lu", (unsigned long)_prefs.gps_period); + sensors.setSettingValue("gps_period", period); sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0"); } #endif diff --git a/examples/simple_room_server/MyMesh.h b/examples/simple_room_server/MyMesh.h index 4dee8bdb..5f8de73a 100644 --- a/examples/simple_room_server/MyMesh.h +++ b/examples/simple_room_server/MyMesh.h @@ -168,6 +168,9 @@ protected: #if ENV_INCLUDE_GPS == 1 void applyGpsPrefs() { + char period[11]; + snprintf(period, sizeof(period), "%lu", (unsigned long)_prefs.gps_period); + sensors.setSettingValue("gps_period", period); sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0"); } #endif diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index 590ca0c7..b93939de 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -173,6 +173,9 @@ private: #if ENV_INCLUDE_GPS == 1 void applyGpsPrefs() { + char period[11]; + snprintf(period, sizeof(period), "%lu", (unsigned long)_prefs.gps_period); + sensors.setSettingValue("gps_period", period); sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0"); } #endif diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index 5d7501d9..613f2578 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -368,6 +368,24 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re } else { strcpy(reply, "gps toggle not found"); } + } else if (memcmp(command, "gps period ", 11) == 0) { + char* end = nullptr; + unsigned long period = strtoul(command + 11, &end, 10); + if (command[11] == '\0' || *end != '\0' || period > 86400) { + strcpy(reply, "gps period must be 0-86400 seconds"); + } else { + char period_value[11]; + snprintf(period_value, sizeof(period_value), "%lu", period); + if (_sensors->setSettingValue("gps_period", period_value) && + _sensors->setSettingValue("gps", "1")) { + _prefs->gps_period = (uint32_t)period; + _prefs->gps_enabled = 1; + savePrefs(); + strcpy(reply, "ok"); + } else { + strcpy(reply, "gps provider not found"); + } + } } else if (memcmp(command, "gps sync", 8) == 0) { LocationProvider * l = _sensors->getLocationProvider(); if (l != NULL) { diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 675df7a4..06778a60 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -61,6 +61,7 @@ public: // Gps settings uint8_t gps_enabled = 0; uint32_t gps_interval = 0; // in seconds + uint32_t gps_period = 0; // periodic acquisition interval in seconds uint8_t advert_loc_policy = 0; uint32_t discovery_mod_timestamp = 0; float adc_multiplier = 0; @@ -158,6 +159,7 @@ private: void structure() override { def("en", _parent->gps_enabled); // boolean def("int", _parent->gps_interval); // interval in seconds + def("period", _parent->gps_period); // periodic acquisition interval in seconds def("adv_loc", _parent->advert_loc_policy); } public: diff --git a/src/helpers/sensors/AirohaGpsDriver.h b/src/helpers/sensors/AirohaGpsDriver.h new file mode 100644 index 00000000..36d5eb6b --- /dev/null +++ b/src/helpers/sensors/AirohaGpsDriver.h @@ -0,0 +1,83 @@ +#pragma once + +#include "NmeaGpsDriver.h" + +class AirohaGpsDriver : public NmeaGpsDriver { + bool waitFor(const char* prefix, uint32_t timeout_ms) { // TODO: Refactor so it doesn't block the loop ! + char sentence[100]; + size_t length = 0; + const size_t prefixLength = strlen(prefix); + const uint32_t deadline = millis() + timeout_ms; + + while ((int32_t)(millis() - deadline) < 0) { + if (available() <= 0) { + yield(); + continue; + } + + const char c = (char)read(); +#ifdef GPS_NMEA_DEBUG + Serial.print(c); +#endif + if (c == '$') length = 0; + if (length < sizeof(sentence) - 1) { + sentence[length++] = c; + sentence[length] = '\0'; + if (length >= prefixLength && strncmp(sentence, prefix, prefixLength) == 0) { + return true; + } + } + } + return false; + } + + void enterBackupSleep() { + for (uint8_t attempt = 0; attempt < 3; attempt++) { + drain(); + sendNmeaSentence("$PAIR650,0"); + if (waitFor("$PAIR001,650,0", 50)) { +#ifdef GPS_NMEA_DEBUG + Serial.printf("Airoha RTC backup sleep accepted after %u attempts\r\n", attempt + 1); +#endif + waitFor("$PAIR650,0", 50); + return; + } + } + } + +public: + AirohaGpsDriver(HardwareSerial& serial) + : NmeaGpsDriver(serial, -1, -1, -1, -1, nullptr, HIGH, LOW, 115200) {} + + void initialize() { + NmeaGpsDriver::begin(); + reset(); + } + + void begin() override { + NmeaGpsDriver::begin(); + digitalWrite(GPS_EN, HIGH); + delay(10); + digitalWrite(GPS_RTC_INT, HIGH); + delay(5); + digitalWrite(GPS_RTC_INT, LOW); + } + + void reset() override { + digitalWrite(GPS_RESET, HIGH); + delay(10); + digitalWrite(GPS_RESET, LOW); + } + + void stop() override { + digitalWrite(GPS_VRTC_EN, HIGH); + digitalWrite(GPS_RTC_INT, LOW); + enterBackupSleep(); + digitalWrite(GPS_EN, LOW); + NmeaGpsDriver::stop(); + } + + bool isEnabled() const override { + return digitalRead(GPS_EN) == HIGH; + } +}; diff --git a/src/helpers/sensors/EnvironmentSensorManager.cpp b/src/helpers/sensors/EnvironmentSensorManager.cpp index 0dc892c3..2861fac2 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.cpp +++ b/src/helpers/sensors/EnvironmentSensorManager.cpp @@ -160,56 +160,6 @@ static Adafruit_VL53L0X VL53L0X; static RAK12035_SoilMoisture RAK12035; #endif -#if ENV_INCLUDE_GPS && defined(RAK_BOARD) && !defined(RAK_WISMESH_TAG) -#define RAK_WISBLOCK_GPS -#endif - -#ifdef RAK_WISBLOCK_GPS -static uint32_t gpsResetPin = 0; -static bool i2cGPSFlag = false; -static bool serialGPSFlag = false; -#ifndef TELEM_RAK12500_ADDRESS -#define TELEM_RAK12500_ADDRESS 0x42 //RAK12500 Ublox GPS via i2c -#endif -#include -static SFE_UBLOX_GNSS ublox_GNSS; - -class RAK12500LocationProvider : public LocationProvider { - long _lat = 0; - long _lng = 0; - long _alt = 0; - int _sats = 0; - long _epoch = 0; - bool _fix = false; -public: - long getLatitude() override { return _lat; } - long getLongitude() override { return _lng; } - long getAltitude() override { return _alt; } - long satellitesCount() override { return _sats; } - bool isValid() override { return _fix; } - long getTimestamp() override { return _epoch; } - void sendSentence(const char * sentence) override { } - void reset() override { } - void begin() override { } - void stop() override { } - void loop() override { - if (ublox_GNSS.getGnssFixOk(8)) { - _fix = true; - _lat = ublox_GNSS.getLatitude(2) / 10; - _lng = ublox_GNSS.getLongitude(2) / 10; - _alt = ublox_GNSS.getAltitude(2); - _sats = ublox_GNSS.getSIV(2); - } else { - _fix = false; - } - _epoch = ublox_GNSS.getUnixEpoch(2); - } - bool isEnabled() override { return true; } -}; - -static RAK12500LocationProvider RAK12500_provider; -#endif - // ============================================================ // I2C bus scanner // Probes every valid address and records which ones ACK. @@ -624,12 +574,8 @@ static const size_t SENSOR_TABLE_SIZE = (sizeof(SENSOR_TABLE) / sizeof(SENSOR_TA bool EnvironmentSensorManager::begin() { #if ENV_INCLUDE_GPS - #ifdef RAK_WISBLOCK_GPS - rakGPSInit(); - #else initBasicGPS(); #endif - #endif #if ENV_PIN_SDA && ENV_PIN_SCL #ifdef NRF52_PLATFORM @@ -684,9 +630,11 @@ bool EnvironmentSensorManager::begin() { bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, CayenneLPP& telemetry) { next_available_channel = TELEM_CHANNEL_SELF + 1; - if (requester_permissions & TELEM_PERM_LOCATION && gps_active) { + #if ENV_INCLUDE_GPS + if (requester_permissions & TELEM_PERM_LOCATION && _location->isEnabled()) { telemetry.addGPS(TELEM_CHANNEL_SELF, node_lat, node_lon, node_altitude); } + #endif if (requester_permissions & TELEM_PERM_ENVIRONMENT) { for (int i = 0; i < _active_sensor_count; i++) { @@ -702,7 +650,7 @@ bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, Cayen int EnvironmentSensorManager::getNumSettings() const { int settings = 0; #if ENV_INCLUDE_GPS - if (gps_detected) settings++; // only show GPS setting if GPS is detected + if (gps_detected) settings += 2; // GPS enablement and periodic acquisition #endif return settings; } @@ -713,6 +661,9 @@ const char* EnvironmentSensorManager::getSettingName(int i) const { if (gps_detected && i == settings++) { return "gps"; } + if (gps_detected && i == settings++) { + return "gps_period"; + } #endif return NULL; } @@ -721,7 +672,13 @@ const char* EnvironmentSensorManager::getSettingValue(int i) const { int settings = 0; #if ENV_INCLUDE_GPS if (gps_detected && i == settings++) { - return gps_active ? "1" : "0"; + return _location->isGpsOn() ? "1" : "0"; + } + if (gps_detected && i == settings++) { + static char period[11]; + snprintf(period, sizeof(period), "%lu", + (unsigned long)_location->getGpsPeriod()); + return period; } #endif return NULL; @@ -737,6 +694,13 @@ bool EnvironmentSensorManager::setSettingValue(const char* name, const char* val } return true; } + if (gps_detected && strcmp(name, "gps_period") == 0) { + char* end = nullptr; + unsigned long period = strtoul(value, &end, 10); + if (*value == '\0' || *end != '\0' || period > 86400) return false; + _location->setGpsPeriod((uint32_t)period); + return true; + } if (strcmp(name, "gps_interval") == 0) { uint32_t interval_seconds = atoi(value); gps_update_interval_sec = interval_seconds > 0 ? interval_seconds : 1; @@ -748,157 +712,35 @@ bool EnvironmentSensorManager::setSettingValue(const char* name, const char* val #if ENV_INCLUDE_GPS void EnvironmentSensorManager::initBasicGPS() { - - Serial1.setPins(PIN_GPS_TX, PIN_GPS_RX); - - #ifdef GPS_BAUD_RATE - Serial1.begin(GPS_BAUD_RATE); - #else - Serial1.begin(9600); - #endif - - // Try to detect if GPS is physically connected to determine if we should expose the setting - _location->begin(); - _location->reset(); + start_gps(); #ifndef PIN_GPS_EN MESH_DEBUG_PRINTLN("No GPS wake/reset pin found for this board. Continuing on..."); #endif - // Give the GPS time to power up and emit its first NMEA sentence. Cold-start - // modules can take several seconds, so poll for up to ~5s instead of checking - // once after a fixed 1s delay -- returning as soon as any data appears, so - // fast modules add no boot delay (issue #2258). #ifdef ENV_SKIP_GPS_DETECT gps_detected = true; #else - gps_detected = false; - for (int i = 0; i < 20 && !gps_detected; i++) { - delay(250); - gps_detected = (Serial1.available() > 0); - } + gps_detected = _location->detect(5000); #endif if (gps_detected) { MESH_DEBUG_PRINTLN("GPS detected"); - #ifdef PERSISTANT_GPS - gps_active = true; + #if defined(PERSISTANT_GPS) return; + #else + if (_location->keepEnabledAfterDetection()) { + return; + } #endif } else { MESH_DEBUG_PRINTLN("No GPS detected"); } - _location->stop(); - gps_active = false; //Set GPS visibility off until setting is changed -} - -// gps code for rak might be moved to MicroNMEALoactionProvider -// or make a new location provider ... -#ifdef RAK_WISBLOCK_GPS -void EnvironmentSensorManager::rakGPSInit(){ - - Serial1.setPins(PIN_GPS_TX, PIN_GPS_RX); - - #ifdef GPS_BAUD_RATE - Serial1.begin(GPS_BAUD_RATE); - #else - Serial1.begin(9600); - #endif - - //search for the correct IO standby pin depending on socket used - if(gpsIsAwake(WB_IO2)){ - } - else if(gpsIsAwake(WB_IO4)){ - } - else if(gpsIsAwake(WB_IO5)){ - } - else{ - MESH_DEBUG_PRINTLN("No GPS found"); - gps_active = false; - gps_detected = false; - Serial1.end(); - return; - } - - #ifndef FORCE_GPS_ALIVE // for use with repeaters, until GPS toggle is implimented - //Now that GPS is found and set up, set to sleep for initial state stop_gps(); - #endif } -bool EnvironmentSensorManager::gpsIsAwake(uint8_t ioPin){ - - #if defined(ETHERNET_ENABLED) && defined(RAK_BOARD) - if (ioPin == WB_IO2) { - // WB_IO2 powers the Ethernet module on RAK baseboards. - return false; - } - #endif - - #ifndef RAK_3401 - //set initial waking state - pinMode(ioPin,OUTPUT); - digitalWrite(ioPin,LOW); - delay(500); - digitalWrite(ioPin,HIGH); - #endif - - // give gps time to power up - delay(500); - - //Try to init RAK12500 on I2C - if (ublox_GNSS.begin(Wire) == true){ - MESH_DEBUG_PRINTLN("RAK12500 GPS init correctly with pin %i",ioPin); - ublox_GNSS.setI2COutput(COM_TYPE_UBX); - ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_GPS); - ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_GALILEO); - ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_GLONASS); - ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_SBAS); - ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_BEIDOU); - ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_IMES); - ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_QZSS); - ublox_GNSS.setMeasurementRate(1000); - ublox_GNSS.saveConfigSelective(VAL_CFG_SUBSEC_IOPORT); - gpsResetPin = ioPin; - i2cGPSFlag = true; - gps_active = true; - gps_detected = true; - - _location = &RAK12500_provider; - return true; - } else if (Serial1.available()) { - MESH_DEBUG_PRINTLN("Serial GPS init correctly and is turned on"); -#ifdef PIN_GPS_EN - if(PIN_GPS_EN){ - gpsResetPin = PIN_GPS_EN; - } -#endif - serialGPSFlag = true; - gps_active = true; - gps_detected = true; - return true; - } - - #ifndef RAK_3401 - pinMode(ioPin, INPUT); - #endif - MESH_DEBUG_PRINTLN("GPS did not init with this IO pin... try the next"); - return false; -} -#endif - void EnvironmentSensorManager::start_gps() { - gps_active = true; - #ifdef RAK_WISBLOCK_GPS - #ifndef RAK_3401 - pinMode(gpsResetPin, OUTPUT); - digitalWrite(gpsResetPin, HIGH); - #endif - return; - #endif - - _location->begin(); - _location->reset(); + _location->setGpsOn(true); #ifndef PIN_GPS_EN MESH_DEBUG_PRINTLN("Start GPS is N/A on this board. Actual GPS state unchanged"); @@ -906,20 +748,11 @@ void EnvironmentSensorManager::start_gps() { } void EnvironmentSensorManager::stop_gps() { - gps_active = false; - #ifdef RAK_WISBLOCK_GPS - #ifndef RAK_3401 // rak3401 shouldn't turn off WB_IO2 as it powers the PA - pinMode(gpsResetPin, OUTPUT); - digitalWrite(gpsResetPin, LOW); - #endif - return; - #endif + _location->setGpsOn(false); - _location->stop(); - - #ifndef PIN_GPS_EN +#ifndef PIN_GPS_EN MESH_DEBUG_PRINTLN("Stop GPS is N/A on this board. Actual GPS state unchanged"); - #endif +#endif } #endif // ENV_INCLUDE_GPS @@ -928,30 +761,16 @@ void EnvironmentSensorManager::loop() { #if ENV_INCLUDE_GPS static unsigned long next_gps_update = 0; - if (gps_active) { - _location->loop(); - } + _location->loop(); if ((long)(millis() - next_gps_update) > 0) { - if(gps_active){ - #ifdef RAK_WISBLOCK_GPS - if ((i2cGPSFlag || serialGPSFlag) && _location->isValid()) { + if (_location->isEnabled() && _location->isValid()) { node_lat = ((double)_location->getLatitude())/1000000.; node_lon = ((double)_location->getLongitude())/1000000.; MESH_DEBUG_PRINTLN("lat %f lon %f", node_lat, node_lon); node_altitude = ((double)_location->getAltitude()) / 1000.0; MESH_DEBUG_PRINTLN("lat %f lon %f alt %f", node_lat, node_lon, node_altitude); } - #else - if (_location->isValid()) { - node_lat = ((double)_location->getLatitude())/1000000.; - node_lon = ((double)_location->getLongitude())/1000000.; - MESH_DEBUG_PRINTLN("lat %f lon %f", node_lat, node_lon); - node_altitude = ((double)_location->getAltitude()) / 1000.0; - MESH_DEBUG_PRINTLN("lat %f lon %f alt %f", node_lat, node_lon, node_altitude); - } - #endif - } next_gps_update = millis() + (gps_update_interval_sec * 1000); } #endif diff --git a/src/helpers/sensors/EnvironmentSensorManager.h b/src/helpers/sensors/EnvironmentSensorManager.h index 17706cbc..425415a1 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.h +++ b/src/helpers/sensors/EnvironmentSensorManager.h @@ -20,7 +20,6 @@ protected: uint8_t next_available_channel = TELEM_CHANNEL_SELF + 1; bool gps_detected = false; - bool gps_active = false; uint32_t gps_update_interval_sec = 1; #if ENV_INCLUDE_GPS @@ -28,10 +27,6 @@ protected: void start_gps(); void stop_gps(); void initBasicGPS(); - #ifdef RAK_BOARD - void rakGPSInit(); - bool gpsIsAwake(uint8_t ioPin); - #endif #endif public: diff --git a/src/helpers/sensors/GpsDriver.h b/src/helpers/sensors/GpsDriver.h new file mode 100644 index 00000000..b8cf4a5d --- /dev/null +++ b/src/helpers/sensors/GpsDriver.h @@ -0,0 +1,18 @@ +#pragma once + +#include + +class GpsDriver { +public: + virtual ~GpsDriver() = default; + + virtual void begin() = 0; + virtual void reset() = 0; + virtual void stop() = 0; + virtual bool isEnabled() const = 0; + virtual bool hasHardwareEnableState() const { return false; } + virtual bool isHardwareEnabled() const { return true; } + // Returns true when the switch explicitly enables GPS in software. + virtual bool pollGpsSwitch() { return false; } + virtual bool detect(uint32_t timeout_ms) = 0; +}; diff --git a/src/helpers/sensors/LocationProvider.h b/src/helpers/sensors/LocationProvider.h index bc4f1fe7..93cecf5b 100644 --- a/src/helpers/sensors/LocationProvider.h +++ b/src/helpers/sensors/LocationProvider.h @@ -8,8 +8,11 @@ class LocationProvider { protected: bool _time_sync_needed = true; + bool _gpsOn = false; public: + virtual ~LocationProvider() = default; + virtual void syncTime() { _time_sync_needed = true; } virtual bool waitingTimeSync() { return _time_sync_needed; } virtual long getLatitude() = 0; @@ -21,6 +24,22 @@ public: virtual void sendSentence(const char * sentence); virtual bool waitFor(const char* prefix, uint32_t timeout_ms) { return false; } virtual void drain() { } + virtual bool detect(uint32_t timeout_ms) { return false; } + virtual bool keepEnabledAfterDetection() const { return false; } + virtual void setGpsPeriod(uint32_t seconds) { } + virtual uint32_t getGpsPeriod() const { return 0; } + virtual bool hasHardwareEnableState() const { return false; } + virtual bool isHardwareEnabled() const { return true; } + virtual bool isGpsOn() const { return _gpsOn; } + virtual void setGpsOn(bool on) { + _gpsOn = on; + if (on) { + begin(); + reset(); + } else { + stop(); + } + } virtual void reset() = 0; virtual void begin() = 0; virtual void stop() = 0; diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index 37ef5762..2e9ff9cc 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -1,69 +1,30 @@ #pragma once +#include "NmeaGpsDriver.h" #include "LocationProvider.h" #include #include -#include #include -#ifndef GPS_EN - #ifdef PIN_GPS_EN - #define GPS_EN PIN_GPS_EN - #else - #define GPS_EN (-1) - #endif -#endif - -#ifndef GPS_EN_ACTIVE - #ifdef PIN_GPS_EN_ACTIVE - #define GPS_EN_ACTIVE PIN_GPS_EN_ACTIVE - #else - #define GPS_EN_ACTIVE HIGH - #endif -#endif - -#ifndef GPS_RESET - #ifdef PIN_GPS_RESET - #define GPS_RESET PIN_GPS_RESET - #else - #define GPS_RESET (-1) - #endif -#endif - -#ifndef GPS_RESET_ACTIVE - #ifdef PIN_GPS_RESET_ACTIVE - #define GPS_RESET_ACTIVE PIN_GPS_RESET_ACTIVE - #else - #define GPS_RESET_ACTIVE LOW - #endif +#ifndef GPS_PERIODIC_ACQUISITION_TIMEOUT_MS + #define GPS_PERIODIC_ACQUISITION_TIMEOUT_MS 120000UL #endif class MicroNMEALocationProvider : public LocationProvider { char _nmeaBuffer[100]; MicroNMEA nmea; mesh::RTCClock* _clock; - Stream* _gps_serial; - RefCountedDigitalPin* _peripher_power; - int8_t _claims = 0; - int _pin_reset; - int _pin_en; + NmeaGpsDriver* _driver; + bool _ownsDriver = false; unsigned long next_check = 0; long time_valid = 0; unsigned long _last_time_sync = 0; - static const unsigned long TIME_SYNC_INTERVAL = 1800000; // Re-sync every 30 minutes + uint32_t _gpsPeriodSeconds = 0; + unsigned long _nextAcquisition = 0; + unsigned long _acquisitionStarted = 0; + bool _acquiringPeriodically = false; + static const unsigned long TIME_SYNC_INTERVAL = 1800000; -#ifdef GPS_L76K - void configureL76K() { - // Reapply the constellation mode at each provider start instead of - // assuming it survives a receiver power cycle. - // Mode 7 enables GPS + BeiDou + GLONASS. - delay(250); - MicroNMEA::sendSentence(*_gps_serial, "$PCAS04,7"); - delay(250); - } -#endif - // Observation-only diagnostics. These fields do not change GPS power, - // timing, reset behaviour, or parser input. uint32_t _uart_bytes = 0; uint32_t _nmea_checksum_ok = 0; uint32_t _nmea_checksum_bad = 0; @@ -88,79 +49,121 @@ class MicroNMEALocationProvider : public LocationProvider { } } -public : - MicroNMEALocationProvider(Stream& ser, mesh::RTCClock* clock = NULL, int pin_reset = GPS_RESET, int pin_en = GPS_EN,RefCountedDigitalPin* peripher_power=NULL) : - nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), _gps_serial(&ser), _peripher_power(peripher_power), _pin_reset(pin_reset), _pin_en(pin_en) { - if (_pin_reset != -1) { - pinMode(_pin_reset, OUTPUT); - digitalWrite(_pin_reset, GPS_RESET_ACTIVE); - } - if (_pin_en != -1) { - pinMode(_pin_en, OUTPUT); - digitalWrite(_pin_en, !GPS_EN_ACTIVE); - } + void startPeriodicAcquisition() { + nmea.clear(); + time_valid = 0; + _driver->begin(); + _driver->reset(); + _acquiringPeriodically = true; + _acquisitionStarted = millis(); } - void claim() { - _claims++; - if (_peripher_power) _peripher_power->claim(); + void finishPeriodicAcquisition() { + _driver->stop(); + _acquiringPeriodically = false; + _nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL; } - void release() { - if (_claims == 0) return; // avoid negative _claims - _claims--; - if (_peripher_power) _peripher_power->release(); + void updateTime() { + if (!isValid()) time_valid = 0; + + if ((long)(millis() - next_check) <= 0) return; + next_check = millis() + 1000; + + if (!_time_sync_needed && _clock != nullptr && + (millis() - _last_time_sync) > TIME_SYNC_INTERVAL) { + _time_sync_needed = true; + } + if (_time_sync_needed && time_valid > 2 && _clock != nullptr) { + _clock->setCurrentTime(getTimestamp()); + _time_sync_needed = false; + _last_time_sync = millis(); + } + if (isValid()) time_valid++; + } + +public: + MicroNMEALocationProvider(NmeaGpsDriver& driver, mesh::RTCClock* clock = nullptr) + : nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), _driver(&driver) {} + + // Temporary migration adapter for targets and downstream boards. New code + // should inject a GpsDriver; this constructor will be removed once targets + // have been migrated. + MicroNMEALocationProvider(HardwareSerial& serial, mesh::RTCClock* clock = nullptr, + int pin_reset = GPS_RESET, int pin_en = GPS_EN, + RefCountedDigitalPin* peripher_power = nullptr) + : nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), + _driver(new NmeaGpsDriver(serial, PIN_GPS_TX, PIN_GPS_RX, pin_reset, pin_en, + peripher_power)), + _ownsDriver(true) {} + + MicroNMEALocationProvider(Stream& serial, mesh::RTCClock* clock = nullptr, + int pin_reset = GPS_RESET, int pin_en = GPS_EN, + RefCountedDigitalPin* peripher_power = nullptr) + : nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), + _driver(new NmeaGpsDriver(serial, PIN_GPS_TX, PIN_GPS_RX, pin_reset, pin_en, + peripher_power)), + _ownsDriver(true) {} + + ~MicroNMEALocationProvider() override { + if (_ownsDriver) delete _driver; } void begin() override { _begin_calls++; - claim(); - if (_pin_en != -1) { - digitalWrite(_pin_en, GPS_EN_ACTIVE); - } - if (_pin_reset != -1) { - digitalWrite(_pin_reset, !GPS_RESET_ACTIVE); + _driver->begin(); + if (_gpsPeriodSeconds > 0 && _driver->isEnabled()) { + nmea.clear(); + time_valid = 0; + _acquiringPeriodically = true; + _acquisitionStarted = millis(); } } void reset() override { - if (_pin_reset != -1) { - digitalWrite(_pin_reset, GPS_RESET_ACTIVE); - delay(10); - digitalWrite(_pin_reset, !GPS_RESET_ACTIVE); - } -#ifdef GPS_L76K - // EnvironmentSensorManager calls reset() immediately after begin(). - // Configure only after that reset so the setting is not discarded. - configureL76K(); -#endif + _driver->reset(); } void stop() override { _stop_calls++; - if (_pin_en != -1) { - digitalWrite(_pin_en, !GPS_EN_ACTIVE); - } - if (_pin_reset != -1) { - digitalWrite(_pin_reset, GPS_RESET_ACTIVE); - } - release(); + _acquiringPeriodically = false; + _driver->stop(); } bool isEnabled() override { - // directly read the enable pin if present as gps can be - // activated/deactivated outside of here ... - if (_pin_en != -1) { - return digitalRead(_pin_en) == GPS_EN_ACTIVE; - } else { - return true; // no enable so must be active - } + return _driver->isEnabled(); + } + + bool hasHardwareEnableState() const override { + return _driver->hasHardwareEnableState(); + } + + bool isHardwareEnabled() const override { + return _driver->isHardwareEnabled(); + } + + bool detect(uint32_t timeout_ms) override { + return _driver->detect(timeout_ms); + } + + void setGpsPeriod(uint32_t seconds) override { + _gpsPeriodSeconds = seconds; + _nextAcquisition = millis(); + _acquiringPeriodically = false; + } + + uint32_t getGpsPeriod() const override { + return _gpsPeriodSeconds; + } + + void syncTime() override { + nmea.clear(); + LocationProvider::syncTime(); } - void syncTime() override { nmea.clear(); LocationProvider::syncTime(); } long getLatitude() override { return nmea.getLatitude(); } long getLongitude() override { return nmea.getLongitude(); } - long getAltitude() override { + long getAltitude() override { long alt = 0; nmea.getAltitude(alt); return alt; @@ -168,29 +171,31 @@ public : long satellitesCount() override { return nmea.getNumSatellites(); } bool isValid() override { return nmea.isValid(); } - long getTimestamp() override { - DateTime dt(nmea.getYear(), nmea.getMonth(),nmea.getDay(),nmea.getHour(),nmea.getMinute(),nmea.getSecond()); + long getTimestamp() override { + DateTime dt(nmea.getYear(), nmea.getMonth(), nmea.getDay(), + nmea.getHour(), nmea.getMinute(), nmea.getSecond()); return dt.unixtime(); - } - - void drain() { while (_gps_serial->available()) _gps_serial->read(); } - - const char* getSentence() const { return nmea.getSentence(); } - - void sendSentence(const char *sentence) override { - nmea.sendSentence(*_gps_serial, sentence); } - bool waitFor(const char* prefix, uint32_t timeout_ms) { - size_t plen = strlen(prefix); - uint32_t timeout = millis() + timeout_ms; - while ((int32_t)(millis() - timeout) < 0) { - if (_gps_serial->available()) { - char c = _gps_serial->read(); - #ifdef GPS_NMEA_DEBUG + void drain() override { _driver->drain(); } + const char* getSentence() const { return nmea.getSentence(); } + + void sendSentence(const char* sentence) override { + _driver->sendNmeaSentence(sentence); + } + + bool waitFor(const char* prefix, uint32_t timeout_ms) override { + const size_t prefixLength = strlen(prefix); + const uint32_t deadline = millis() + timeout_ms; + while ((int32_t)(millis() - deadline) < 0) { + if (_driver->available() > 0) { + const char c = (char)_driver->read(); +#ifdef GPS_NMEA_DEBUG Serial.print(c); - #endif - if (nmea.process(c) && strncmp(nmea.getSentence(), prefix, plen) == 0) return true; +#endif + if (nmea.process(c) && strncmp(nmea.getSentence(), prefix, prefixLength) == 0) { + return true; + } } else { yield(); } @@ -199,34 +204,35 @@ public : } void loop() override { + if (_driver->pollGpsSwitch()) _gpsOn = true; - while (_gps_serial->available()) { - char c = _gps_serial->read(); + if (_gpsOn && _gpsPeriodSeconds > 0 && !_acquiringPeriodically && + (long)(millis() - _nextAcquisition) >= 0) { + startPeriodicAcquisition(); + } + + while (_driver->available() > 0) { + const char c = (char)_driver->read(); _uart_bytes++; _last_uart_ms = millis(); _uart_seen = true; - #ifdef GPS_NMEA_DEBUG +#ifdef GPS_NMEA_DEBUG Serial.print(c); - #endif - bool parsed = nmea.process(c); +#endif + const bool parsed = nmea.process(c); - // MicroNMEA leaves the completed sentence in its buffer after the - // first line terminator. CRLF therefore counts once: CR observes the - // sentence, then LF clears the now-empty buffer. if ((c == '\0' || c == '\r' || c == '\n') && nmea.getSentence()[0] != '\0') { if (MicroNMEA::testChecksum(nmea.getSentence())) { _nmea_checksum_ok++; _last_nmea_ms = millis(); _nmea_seen = true; - // Refresh fix age only when a newly parsed GGA/RMC sentence - // carries a valid fix. Other valid NMEA sentences must not - // make an old position look fresh. - const char* message_id = nmea.getMessageID(); + const char* messageId = nmea.getMessageID(); if (parsed && isValid() && - (strcmp(message_id, "GGA") == 0 || strcmp(message_id, "RMC") == 0)) { + (strcmp(messageId, "GGA") == 0 || strcmp(messageId, "RMC") == 0)) { _last_fix_ms = millis(); _fix_seen = true; + if (_acquiringPeriodically) finishPeriodicAcquisition(); } } else { _nmea_checksum_bad++; @@ -234,25 +240,12 @@ public : } } - if (!isValid()) time_valid = 0; - - if ((long)(millis() - next_check) > 0) { - next_check = millis() + 1000; - // Re-enable time sync periodically when GPS has valid fix - if (!_time_sync_needed && _clock != NULL && (millis() - _last_time_sync) > TIME_SYNC_INTERVAL) { - _time_sync_needed = true; - } - if (_time_sync_needed && time_valid > 2) { - if (_clock != NULL) { - _clock->setCurrentTime(getTimestamp()); - _time_sync_needed = false; - _last_time_sync = millis(); - } - } - if (isValid()) { - time_valid ++; - } + if (_acquiringPeriodically && + (uint32_t)(millis() - _acquisitionStarted) >= GPS_PERIODIC_ACQUISITION_TIMEOUT_MS) { + finishPeriodicAcquisition(); } + + updateTime(); } void formatDiagnostics(char* out, size_t out_size) override { @@ -265,8 +258,6 @@ public : formatAge(nmea_age, sizeof(nmea_age), _nmea_seen, _last_nmea_ms); formatAge(fix_age, sizeof(fix_age), _fix_seen, _last_fix_ms); - // Compact enough for CommonCLI's 160-byte reply buffer, including the - // "req:" prefix added by CommonCLI. snprintf(out, out_size, "en:%u ub:%lu ua:%s ok:%lu bad:%lu na:%s sat:%ld fix:%u fa:%s bc:%lu sc:%lu", isEnabled() ? 1U : 0U, diff --git a/src/helpers/sensors/NmeaGpsDriver.h b/src/helpers/sensors/NmeaGpsDriver.h new file mode 100644 index 00000000..f9ea5124 --- /dev/null +++ b/src/helpers/sensors/NmeaGpsDriver.h @@ -0,0 +1,262 @@ +#pragma once + +#include "GpsDriver.h" + +#include +#include + +#ifndef PIN_GPS_TX + #define PIN_GPS_TX (-1) +#endif + +#ifndef PIN_GPS_RX + #define PIN_GPS_RX (-1) +#endif + +#ifndef GPS_EN + #ifdef PIN_GPS_EN + #define GPS_EN PIN_GPS_EN + #else + #define GPS_EN (-1) + #endif +#endif + +#ifndef GPS_EN_ACTIVE + #ifdef PIN_GPS_EN_ACTIVE + #define GPS_EN_ACTIVE PIN_GPS_EN_ACTIVE + #else + #define GPS_EN_ACTIVE HIGH + #endif +#endif + +#ifndef GPS_RESET + #ifdef PIN_GPS_RESET + #define GPS_RESET PIN_GPS_RESET + #else + #define GPS_RESET (-1) + #endif +#endif + +#ifndef GPS_RESET_ACTIVE + #ifdef PIN_GPS_RESET_ACTIVE + #define GPS_RESET_ACTIVE PIN_GPS_RESET_ACTIVE + #else + #define GPS_RESET_ACTIVE LOW + #endif +#endif + +#ifndef GPS_BAUD_RATE + #define GPS_BAUD_RATE 9600 +#endif + +#ifndef PIN_GPS_SWITCH + #define PIN_GPS_SWITCH (-1) +#endif + +#ifndef GPS_SWITCH_ACTIVE + #define GPS_SWITCH_ACTIVE HIGH +#endif + +#ifndef GPS_SWITCH_IS_HARDWARE + #define GPS_SWITCH_IS_HARDWARE 1 +#endif + +#ifndef GPS_SWITCH_TURNS_GPS_ON + #define GPS_SWITCH_TURNS_GPS_ON 0 +#endif + +class NmeaGpsDriver : public GpsDriver { + Stream* _stream = nullptr; + HardwareSerial* _hardwareSerial = nullptr; + RefCountedDigitalPin* _peripheralPower = nullptr; + int _txPin = -1; + int _rxPin = -1; + int _resetPin = -1; + int _enablePin = -1; + int _enableActive = HIGH; + int _resetActive = LOW; + uint32_t _baudRate = 9600; + int _hardwareEnablePin = -1; + int _hardwareEnableActive = HIGH; + bool _started = false; +#if !GPS_SWITCH_IS_HARDWARE + bool _requestedOn = false; + bool _switchStateKnown = false; + bool _lastSwitchEnabled = false; + unsigned long _nextSwitchPoll = 0; +#endif + + void startHardware() { + if (_stream == nullptr || _started) return; + + if (_hardwareSerial != nullptr) { +#ifdef ESP32_PLATFORM + _hardwareSerial->setPins(_txPin, _rxPin); +#endif + _hardwareSerial->begin(_baudRate); + } + + if (_peripheralPower != nullptr) _peripheralPower->claim(); + + if (_enablePin != -1) digitalWrite(_enablePin, _enableActive); + if (_resetPin != -1) digitalWrite(_resetPin, !_resetActive); + _started = true; + } + + void stopHardware() { + if (!_started) return; + + if (_enablePin != -1) digitalWrite(_enablePin, !_enableActive); + if (_resetPin != -1) digitalWrite(_resetPin, _resetActive); + + if (_peripheralPower != nullptr) _peripheralPower->release(); + _started = false; + } + +public: + NmeaGpsDriver() = default; + + NmeaGpsDriver(Stream& stream, int txPin = PIN_GPS_TX, int rxPin = PIN_GPS_RX, + int resetPin = GPS_RESET, int enablePin = GPS_EN, + RefCountedDigitalPin* peripheralPower = nullptr, + int enableActive = GPS_EN_ACTIVE, int resetActive = GPS_RESET_ACTIVE, + uint32_t baudRate = GPS_BAUD_RATE, + int hardwareEnablePin = PIN_GPS_SWITCH, + int hardwareEnableActive = GPS_SWITCH_ACTIVE) + : _stream(&stream), _peripheralPower(peripheralPower), _txPin(txPin), _rxPin(rxPin), + _resetPin(resetPin), _enablePin(enablePin), _enableActive(enableActive), + _resetActive(resetActive), _baudRate(baudRate), + _hardwareEnablePin(hardwareEnablePin), _hardwareEnableActive(hardwareEnableActive) { + if (_resetPin != -1) { + pinMode(_resetPin, OUTPUT); + digitalWrite(_resetPin, _resetActive); + } + if (_enablePin != -1) { + pinMode(_enablePin, OUTPUT); + digitalWrite(_enablePin, !_enableActive); + } + if (_hardwareEnablePin != -1) { + pinMode(_hardwareEnablePin, INPUT); + } + } + + NmeaGpsDriver(HardwareSerial& serial, int txPin = PIN_GPS_TX, int rxPin = PIN_GPS_RX, + int resetPin = GPS_RESET, int enablePin = GPS_EN, + RefCountedDigitalPin* peripheralPower = nullptr, + int enableActive = GPS_EN_ACTIVE, int resetActive = GPS_RESET_ACTIVE, + uint32_t baudRate = GPS_BAUD_RATE, + int hardwareEnablePin = PIN_GPS_SWITCH, + int hardwareEnableActive = GPS_SWITCH_ACTIVE) + : NmeaGpsDriver(static_cast(serial), txPin, rxPin, resetPin, enablePin, + peripheralPower, enableActive, resetActive, baudRate, + hardwareEnablePin, hardwareEnableActive) { + _hardwareSerial = &serial; + } + + void begin() override { +#if !GPS_SWITCH_IS_HARDWARE + _requestedOn = true; + if (!isHardwareEnabled()) return; +#endif + startHardware(); + } + + void reset() override { + if (!_started) return; + if (_resetPin != -1) { + digitalWrite(_resetPin, _resetActive); + delay(10); + digitalWrite(_resetPin, !_resetActive); + } + +#ifdef GPS_L76K + delay(250); + sendNmeaSentence("$PCAS04,7"); + delay(250); +#endif + } + + void stop() override { +#if !GPS_SWITCH_IS_HARDWARE + _requestedOn = false; +#endif + stopHardware(); + } + + bool isEnabled() const override { + return _started && isHardwareEnabled(); + } + + bool hasHardwareEnableState() const override { + return _hardwareEnablePin != -1; + } + + bool isHardwareEnabled() const override { + return _hardwareEnablePin == -1 || + digitalRead(_hardwareEnablePin) == _hardwareEnableActive; + } + + bool pollGpsSwitch() override { +#if !GPS_SWITCH_IS_HARDWARE + if (_hardwareEnablePin == -1 || + (long)(millis() - _nextSwitchPoll) < 0) return false; + + _nextSwitchPoll = millis() + 1000; + const bool switchEnabled = isHardwareEnabled(); + const bool enablesGps = GPS_SWITCH_TURNS_GPS_ON && _switchStateKnown && + !_lastSwitchEnabled && switchEnabled; + _switchStateKnown = true; + _lastSwitchEnabled = switchEnabled; + + if (enablesGps) _requestedOn = true; + if (_requestedOn && switchEnabled) { + startHardware(); + } else { + stopHardware(); + } + return enablesGps; +#else + return false; +#endif + } + + bool detect(uint32_t timeout_ms) override { + if (available() > 0) return true; + + const uint32_t deadline = millis() + timeout_ms; + while ((int32_t)(millis() - deadline) < 0) { + if (available() > 0) return true; + delay(10); + } + return false; + } + + int available() { + return _stream == nullptr ? 0 : _stream->available(); + } + + int read() { + return _stream == nullptr ? -1 : _stream->read(); + } + + void drain() { + while (available() > 0) read(); + } + + void sendNmeaSentence(const char* sentence) { + if (_stream == nullptr || sentence == nullptr || sentence[0] != '$') return; + + uint8_t checksum = 0; + const char* p = sentence + 1; + while (*p != '\0' && *p != '*') checksum ^= (uint8_t)*p++; + + _stream->print(sentence); + if (*p == '\0') { + char checksumSuffix[6]; + snprintf(checksumSuffix, sizeof(checksumSuffix), "*%02X\r\n", checksum); + _stream->print(checksumSuffix); + } else { + _stream->print("\r\n"); + } + } +}; diff --git a/src/helpers/sensors/RakGpsDriver.h b/src/helpers/sensors/RakGpsDriver.h new file mode 100644 index 00000000..fb4b772b --- /dev/null +++ b/src/helpers/sensors/RakGpsDriver.h @@ -0,0 +1,112 @@ +#pragma once + +#include "NmeaGpsDriver.h" + +#include + +class RakGpsDriver : public GpsDriver { + NmeaGpsDriver _serialDriver; + TwoWire& _wire; + SFE_UBLOX_GNSS _gnss; + uint8_t _powerPin = 0; + bool _usingRak12500 = false; + bool _detected = false; + + bool probeRak12500(uint8_t powerPin) { +#if defined(ETHERNET_ENABLED) && defined(RAK_BOARD) + if (powerPin == WB_IO2) return false; +#endif + +#ifndef RAK_3401 + pinMode(powerPin, OUTPUT); + digitalWrite(powerPin, LOW); + delay(500); + digitalWrite(powerPin, HIGH); +#endif + delay(500); + + if (_gnss.begin(_wire)) { + _gnss.setI2COutput(COM_TYPE_UBX); + _gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_GPS); + _gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_GALILEO); + _gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_GLONASS); + _gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_SBAS); + _gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_BEIDOU); + _gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_IMES); + _gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_QZSS); + _gnss.setMeasurementRate(1000); + _gnss.saveConfigSelective(VAL_CFG_SUBSEC_IOPORT); + _powerPin = powerPin; + _usingRak12500 = true; + return true; + } + +#ifndef RAK_3401 + pinMode(powerPin, INPUT); +#endif + return false; + } + +public: + RakGpsDriver(HardwareSerial& serial = Serial1, TwoWire& wire = Wire) + : _serialDriver(serial), _wire(wire) {} + + void begin() override { + if (_usingRak12500) { +#ifndef RAK_3401 + pinMode(_powerPin, OUTPUT); + digitalWrite(_powerPin, HIGH); +#endif + return; + } + _serialDriver.begin(); + } + + void reset() override { + if (!_usingRak12500) _serialDriver.reset(); + } + + void stop() override { + if (_usingRak12500) { +#ifndef RAK_3401 + pinMode(_powerPin, OUTPUT); + digitalWrite(_powerPin, LOW); +#endif + return; + } + _serialDriver.stop(); + } + + bool isEnabled() const override { + return _usingRak12500 ? true : _serialDriver.isEnabled(); + } + + bool detect(uint32_t) override { + if (_detected) return true; + + _serialDriver.begin(); + if (probeRak12500(WB_IO2) || probeRak12500(WB_IO4) || probeRak12500(WB_IO5)) { + _detected = true; + return true; + } + + if (_serialDriver.detect(0)) { + _detected = true; + return true; + } + + _serialDriver.stop(); + return false; + } + + bool usesRak12500() const { return _usingRak12500; } + bool isDetected() const { return _detected; } + NmeaGpsDriver& nmeaDriver() { return _serialDriver; } + + bool hasFix() { return _usingRak12500 && _gnss.getGnssFixOk(8); } + long getLatitude() { return _gnss.getLatitude(2) / 10; } + long getLongitude() { return _gnss.getLongitude(2) / 10; } + long getAltitude() { return _gnss.getAltitude(2); } + long getSatellites() { return _gnss.getSIV(2); } + long getTimestamp() { return _gnss.getUnixEpoch(2); } +}; diff --git a/src/helpers/sensors/RakLocationProvider.h b/src/helpers/sensors/RakLocationProvider.h new file mode 100644 index 00000000..c909b7c4 --- /dev/null +++ b/src/helpers/sensors/RakLocationProvider.h @@ -0,0 +1,144 @@ +#pragma once + +#include "MicroNMEALocationProvider.h" +#include "RakGpsDriver.h" + +class RakLocationProvider : public LocationProvider { + RakGpsDriver& _driver; + MicroNMEALocationProvider _nmea; + uint32_t _gpsPeriodSeconds = 0; + unsigned long _nextAcquisition = 0; + unsigned long _acquisitionStarted = 0; + bool _acquiringPeriodically = false; + +public: + RakLocationProvider(RakGpsDriver& driver, mesh::RTCClock* clock = nullptr) + : _driver(driver), _nmea(driver.nmeaDriver(), clock) {} + + void syncTime() override { + LocationProvider::syncTime(); + if (!_driver.usesRak12500()) _nmea.syncTime(); + } + + long getLatitude() override { + return _driver.usesRak12500() ? _driver.getLatitude() : _nmea.getLatitude(); + } + + long getLongitude() override { + return _driver.usesRak12500() ? _driver.getLongitude() : _nmea.getLongitude(); + } + + long getAltitude() override { + return _driver.usesRak12500() ? _driver.getAltitude() : _nmea.getAltitude(); + } + + long satellitesCount() override { + return _driver.usesRak12500() ? _driver.getSatellites() : _nmea.satellitesCount(); + } + + bool isValid() override { + return _driver.usesRak12500() ? _driver.hasFix() : _nmea.isValid(); + } + + long getTimestamp() override { + return _driver.usesRak12500() ? _driver.getTimestamp() : _nmea.getTimestamp(); + } + + void sendSentence(const char* sentence) override { + if (!_driver.usesRak12500()) _nmea.sendSentence(sentence); + } + + bool waitFor(const char* prefix, uint32_t timeout_ms) override { + return _driver.usesRak12500() ? false : _nmea.waitFor(prefix, timeout_ms); + } + + void drain() override { + if (!_driver.usesRak12500()) _nmea.drain(); + } + + void reset() override { + _driver.reset(); + } + + void begin() override { + if (_driver.isDetected() && _driver.usesRak12500()) { + _driver.begin(); + _acquiringPeriodically = _gpsPeriodSeconds > 0; + _acquisitionStarted = millis(); + } else if (_driver.isDetected()) { + _nmea.begin(); + } else { + _driver.begin(); + } + } + + void stop() override { + _acquiringPeriodically = false; + if (_driver.usesRak12500()) { + _driver.stop(); + } else { + _nmea.stop(); + } + } + + bool detect(uint32_t timeout_ms) override { + if (!_driver.detect(timeout_ms)) return false; + + if (_driver.usesRak12500()) { + _acquiringPeriodically = _gpsPeriodSeconds > 0; + _acquisitionStarted = millis(); + } else { + _nmea.setGpsPeriod(_gpsPeriodSeconds); + _nmea.begin(); + } + return true; + } + + bool keepEnabledAfterDetection() const override { +#ifdef FORCE_GPS_ALIVE + return true; +#else + return false; +#endif + } + + void loop() override { + if (_driver.usesRak12500()) { + if (_gpsOn && _gpsPeriodSeconds > 0) { + if (!_acquiringPeriodically && + (long)(millis() - _nextAcquisition) >= 0) { + _driver.begin(); + _acquiringPeriodically = true; + _acquisitionStarted = millis(); + } + if (_acquiringPeriodically && isValid()) { + _driver.stop(); + _acquiringPeriodically = false; + _nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL; + } else if (_acquiringPeriodically && + (uint32_t)(millis() - _acquisitionStarted) >= + GPS_PERIODIC_ACQUISITION_TIMEOUT_MS) { + _driver.stop(); + _acquiringPeriodically = false; + _nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL; + } + } + } else { + _nmea.loop(); + } + } + + bool isEnabled() override { + return _driver.isEnabled(); + } + + void setGpsPeriod(uint32_t seconds) override { + _gpsPeriodSeconds = seconds; + _nextAcquisition = millis(); + if (!_driver.usesRak12500()) _nmea.setGpsPeriod(seconds); + } + + uint32_t getGpsPeriod() const override { + return _gpsPeriodSeconds; + } +}; diff --git a/variants/gat562_30s_mesh_kit/target.cpp b/variants/gat562_30s_mesh_kit/target.cpp index 8f84a7a1..ba81a690 100644 --- a/variants/gat562_30s_mesh_kit/target.cpp +++ b/variants/gat562_30s_mesh_kit/target.cpp @@ -26,9 +26,10 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS - #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); - EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); + #include + RakGpsDriver gps_driver; + RakLocationProvider location(gps_driver, &rtc_clock); + EnvironmentSensorManager sensors(location); #else EnvironmentSensorManager sensors; #endif diff --git a/variants/lilygo_techo/target.cpp b/variants/lilygo_techo/target.cpp index 12b40d7e..394d79c5 100644 --- a/variants/lilygo_techo/target.cpp +++ b/variants/lilygo_techo/target.cpp @@ -13,7 +13,8 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea = MicroNMEALocationProvider(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); @@ -36,5 +37,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - - diff --git a/variants/rak3401/target.cpp b/variants/rak3401/target.cpp index 5309e6b2..26501977 100644 --- a/variants/rak3401/target.cpp +++ b/variants/rak3401/target.cpp @@ -25,9 +25,10 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS - #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); - EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); + #include + RakGpsDriver gps_driver; + RakLocationProvider location(gps_driver, &rtc_clock); + EnvironmentSensorManager sensors(location); #else EnvironmentSensorManager sensors; #endif @@ -41,4 +42,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/rak4631/target.cpp b/variants/rak4631/target.cpp index a41ba720..06ccd23d 100644 --- a/variants/rak4631/target.cpp +++ b/variants/rak4631/target.cpp @@ -25,9 +25,10 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS - #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); - EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); + #include + RakGpsDriver gps_driver; + RakLocationProvider location(gps_driver, &rtc_clock); + EnvironmentSensorManager sensors(location); #else EnvironmentSensorManager sensors; #endif diff --git a/variants/t1000-e/platformio.ini b/variants/t1000-e/platformio.ini index 8456dc91..ab8b0de0 100644 --- a/variants/t1000-e/platformio.ini +++ b/variants/t1000-e/platformio.ini @@ -106,6 +106,7 @@ build_flags = ${t1000-e.build_flags} ; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 +; -D GPS_NMEA_DEBUG -D OFFLINE_QUEUE_SIZE=256 -D DISPLAY_CLASS=NullDisplayDriver -D PIN_BUZZER=25 diff --git a/variants/t1000-e/target.cpp b/variants/t1000-e/target.cpp index 70a64359..0d7710b3 100644 --- a/variants/t1000-e/target.cpp +++ b/variants/t1000-e/target.cpp @@ -1,8 +1,8 @@ #include #include "t1000e_sensors.h" #include "target.h" +#include #include -#include T1000eBoard board; @@ -11,8 +11,9 @@ RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BU WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock rtc_clock; -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); -T1000SensorManager sensors = T1000SensorManager(nmea); +AirohaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); +T1000SensorManager sensors(nmea, gps_driver); #ifdef DISPLAY_CLASS NullDisplayDriver display; @@ -82,28 +83,17 @@ mesh::LocalIdentity radio_new_identity() { void T1000SensorManager::start_gps() { gps_active = true; - digitalWrite(GPS_EN, HIGH); - delay(10); - digitalWrite(GPS_RTC_INT, HIGH); - delay(5); - digitalWrite(GPS_RTC_INT, LOW); + _nmea->begin(); } void T1000SensorManager::stop_gps() { gps_active = false; - digitalWrite(GPS_VRTC_EN, HIGH); // keep GPS RTC alive for faster fix on wake - digitalWrite(GPS_RTC_INT, LOW); // make sure this is LOW so we can pulse it to wake - airohaEnterSleep(_nmea); // send command to put the GPS into RTC backup sleep - digitalWrite(GPS_EN, LOW); + _nmea->stop(); } bool T1000SensorManager::begin() { - // init GPS - Serial1.begin(115200); - digitalWrite(GPS_RESET, HIGH); - delay(10); - digitalWrite(GPS_RESET, LOW); + _gps_driver->initialize(); return true; } diff --git a/variants/t1000-e/target.h b/variants/t1000-e/target.h index db003cc5..4a1a2bb7 100644 --- a/variants/t1000-e/target.h +++ b/variants/t1000-e/target.h @@ -12,15 +12,19 @@ #include "NullDisplayDriver.h" #endif +class AirohaGpsDriver; + class T1000SensorManager: public SensorManager { bool gps_active = false; LocationProvider * _nmea; + AirohaGpsDriver* _gps_driver; void start_gps(); void sleep_gps(); void stop_gps(); public: - T1000SensorManager(LocationProvider &nmea): _nmea(&nmea) { } + T1000SensorManager(LocationProvider &nmea, AirohaGpsDriver& gps_driver) + : _nmea(&nmea), _gps_driver(&gps_driver) { } bool begin() override; bool querySensors(uint8_t requester_permissions, CayenneLPP& telemetry) override; void loop() override; diff --git a/variants/thinknode_m1/target.cpp b/variants/thinknode_m1/target.cpp index c430cee0..78f5a88e 100644 --- a/variants/thinknode_m1/target.cpp +++ b/variants/thinknode_m1/target.cpp @@ -2,6 +2,7 @@ #include "target.h" #include #include +#include ThinkNodeM1Board board; @@ -11,7 +12,8 @@ WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea = MicroNMEALocationProvider(gps_driver, &rtc_clock); ThinkNodeM1SensorManager sensors = ThinkNodeM1SensorManager(nmea); #ifdef DISPLAY_CLASS @@ -31,34 +33,15 @@ mesh::LocalIdentity radio_new_identity() { } void ThinkNodeM1SensorManager::start_gps() { - if (!gps_active) { - gps_active = true; - _location->begin(); - } + _location->setGpsOn(true); } void ThinkNodeM1SensorManager::stop_gps() { - if (gps_active) { - gps_active = false; - _location->stop(); - } + _location->setGpsOn(false); } bool ThinkNodeM1SensorManager::begin() { - Serial1.begin(9600); - - // Initialize GPS switch pin - pinMode(PIN_GPS_SWITCH, INPUT); - last_gps_switch_state = digitalRead(PIN_GPS_SWITCH); - - // Initialize GPS power pin - pinMode(GPS_EN, OUTPUT); - - // Check initial switch state to determine if GPS should be active - if (last_gps_switch_state == HIGH) { // Switch is HIGH when ON - start_gps(); - } - + start_gps(); return true; } @@ -71,36 +54,11 @@ bool ThinkNodeM1SensorManager::querySensors(uint8_t requester_permissions, Cayen void ThinkNodeM1SensorManager::loop() { static long next_gps_update = 0; - static long last_switch_check = 0; - - // Check GPS switch state every second - if (millis() - last_switch_check > 1000) { - bool current_switch_state = digitalRead(PIN_GPS_SWITCH); - - // Detect switch state change - if (current_switch_state != last_gps_switch_state) { - last_gps_switch_state = current_switch_state; - - if (current_switch_state == HIGH) { // Switch is ON - MESH_DEBUG_PRINTLN("GPS switch ON"); - start_gps(); - } else { // Switch is OFF - MESH_DEBUG_PRINTLN("GPS switch OFF"); - stop_gps(); - } - } - - last_switch_check = millis(); - } - - if (!gps_active) { - return; // GPS is not active, skip further processing - } _location->loop(); if (millis() > next_gps_update) { - if (_location->isValid()) { + if (_location->isEnabled() && _location->isValid()) { node_lat = ((double)_location->getLatitude())/1000000.; node_lon = ((double)_location->getLongitude())/1000000.; node_altitude = ((double)_location->getAltitude()) / 1000.0; @@ -120,7 +78,7 @@ const char* ThinkNodeM1SensorManager::getSettingName(int i) const { const char* ThinkNodeM1SensorManager::getSettingValue(int i) const { if (i == 0) { - return gps_active ? "1" : "0"; + return _location->isGpsOn() ? "1" : "0"; } return NULL; } @@ -136,4 +94,3 @@ bool ThinkNodeM1SensorManager::setSettingValue(const char* name, const char* val } return false; // not supported } - diff --git a/variants/thinknode_m1/target.h b/variants/thinknode_m1/target.h index d2d6aed1..9c8a6e80 100644 --- a/variants/thinknode_m1/target.h +++ b/variants/thinknode_m1/target.h @@ -14,8 +14,6 @@ #endif class ThinkNodeM1SensorManager : public SensorManager { - bool gps_active = false; - bool last_gps_switch_state = false; LocationProvider* _location; void start_gps(); @@ -45,4 +43,3 @@ extern ThinkNodeM1SensorManager sensors; bool radio_init(); mesh::LocalIdentity radio_new_identity(); - diff --git a/variants/thinknode_m1/variant.h b/variants/thinknode_m1/variant.h index aecf197e..3e3f03a7 100644 --- a/variants/thinknode_m1/variant.h +++ b/variants/thinknode_m1/variant.h @@ -146,3 +146,5 @@ extern const int SCK; #define PIN_GPS_PPS (36) #define PIN_GPS_STANDBY (34) #define PIN_GPS_SWITCH (33) +#define GPS_SWITCH_IS_HARDWARE (0) +#define GPS_SWITCH_TURNS_GPS_ON (1) diff --git a/variants/thinknode_m5/target.cpp b/variants/thinknode_m5/target.cpp index ec524df7..0ed9a0d0 100644 --- a/variants/thinknode_m5/target.cpp +++ b/variants/thinknode_m5/target.cpp @@ -17,7 +17,8 @@ ESP32RTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea = MicroNMEALocationProvider(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); @@ -46,5 +47,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - - diff --git a/variants/thinknode_m5/variant.h b/variants/thinknode_m5/variant.h index 9b82416b..fefb45d1 100644 --- a/variants/thinknode_m5/variant.h +++ b/variants/thinknode_m5/variant.h @@ -25,4 +25,5 @@ #define PIN_GPS_RESET (13) #define PIN_GPS_RX (20) #define PIN_GPS_TX (19) -#define PIN_GPS_SWITCH (10) \ No newline at end of file +#define PIN_GPS_SWITCH (10) +#define GPS_SWITCH_IS_HARDWARE (1) \ No newline at end of file From dea38936d7c24a3680044ca9871bf6bcf775cd29 Mon Sep 17 00:00:00 2001 From: Florent Date: Mon, 2 Nov 2026 11:09:16 -0400 Subject: [PATCH 57/79] gps: move the gps CLI to GpsPrefs and convert all targets --- examples/companion_radio/MyMesh.cpp | 5 + examples/companion_radio/MyMesh.h | 11 +- examples/companion_radio/NodePrefs.h | 14 ++- examples/companion_radio/ui-new/UITask.cpp | 8 +- examples/companion_radio/ui-orig/UITask.cpp | 5 +- examples/companion_radio/ui-tiny/UITask.cpp | 8 +- examples/simple_repeater/MyMesh.h | 12 +- examples/simple_room_server/MyMesh.h | 12 +- examples/simple_sensor/SensorMesh.h | 10 +- src/helpers/CommonCLI.cpp | 76 +----------- src/helpers/CommonCLI.h | 12 +- src/helpers/CommonGpsPrefs.cpp | 110 ++++++++++++++++++ src/helpers/CommonGpsPrefs.h | 26 +++++ .../sensors/EnvironmentSensorManager.cpp | 18 +-- variants/gat562_mesh_evb_pro/target.cpp | 3 +- variants/gat562_mesh_tracker_pro/target.cpp | 3 +- variants/heltec_mesh_solar/target.cpp | 15 +-- variants/heltec_mesh_solar/target.h | 1 - variants/heltec_rc32/target.cpp | 4 +- variants/heltec_t096/target.cpp | 4 +- variants/heltec_t1/target.cpp | 4 +- variants/heltec_t114/target.cpp | 3 +- variants/heltec_tower_v2/target.cpp | 3 +- variants/heltec_tracker/target.cpp | 30 +++-- variants/heltec_tracker/target.h | 1 - variants/heltec_tracker_v2/target.cpp | 5 +- variants/heltec_v3/target.cpp | 4 +- variants/heltec_v4/target.cpp | 4 +- variants/heltec_v4_r8/target.cpp | 4 +- variants/keepteen_lt1/target.cpp | 4 +- variants/lilygo_t_impulse_plus/target.cpp | 4 +- variants/lilygo_tbeam_1w/target.cpp | 4 +- variants/lilygo_tbeam_SX1262/target.cpp | 4 +- variants/lilygo_tbeam_SX1276/target.cpp | 3 +- .../lilygo_tbeam_supreme_SX1262/target.cpp | 4 +- variants/lilygo_tdeck/target.cpp | 3 +- variants/lilygo_techo_card/target.cpp | 3 +- variants/lilygo_techo_lite/target.cpp | 4 +- variants/meshadventurer/target.cpp | 19 ++- variants/meshadventurer/target.h | 3 +- variants/meshnology_w12/target.cpp | 4 +- variants/meshtracker_x1/target.cpp | 27 ++--- variants/meshtracker_x1/target.h | 2 - variants/minewsemi_me25ls01/target.cpp | 3 +- variants/muzi_base/target.cpp | 22 +--- variants/muzi_base/target.h | 6 +- variants/muzi_base/variant.h | 2 + variants/muziworks_r1_neo/target.cpp | 3 +- variants/nano_g2_ultra/NanoG2UltraGpsDriver.h | 31 +++++ variants/nano_g2_ultra/target.cpp | 35 ++---- variants/nano_g2_ultra/target.h | 8 +- variants/promicro/target.cpp | 4 +- variants/rak3112/target.cpp | 4 +- variants/rak_wismesh_tag/target.cpp | 4 +- variants/sensecap_indicator-espnow/target.cpp | 3 +- variants/sensecap_solar/target.cpp | 4 +- variants/station_g2/target.cpp | 4 +- variants/station_g3_esp32/target.cpp | 3 +- variants/t1000-e/target.cpp | 10 +- variants/t1000-e/target.h | 1 - variants/thinknode_m3/target.cpp | 3 +- variants/thinknode_m4/target.cpp | 3 +- variants/thinknode_m6/target.cpp | 4 +- variants/thinknode_m7/target.cpp | 4 +- variants/thinknode_m8/target.cpp | 3 +- variants/thinknode_m9/target.cpp | 3 +- variants/wio-tracker-l1-1w/target.cpp | 4 +- variants/wio-tracker-l1/target.cpp | 4 +- variants/xiao_c3/target.cpp | 4 +- 69 files changed, 381 insertions(+), 301 deletions(-) create mode 100644 src/helpers/CommonGpsPrefs.cpp create mode 100644 src/helpers/CommonGpsPrefs.h create mode 100644 variants/nano_g2_ultra/NanoG2UltraGpsDriver.h diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 755c56d1..d12c7b8a 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2093,6 +2093,11 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* return true; } + if (_prefs.getGpsPrefs()->handleCommand(command, sensors, reply)) { + if (_prefs.getGpsPrefs()->isDirty()) { savePrefs(); } + return true; + } + // hook for variant-specific CLI processing if (board.handleCommand(command, sender_timestamp, reply)) { if (_prefs.isDirty()) { savePrefs(); } diff --git a/examples/companion_radio/MyMesh.h b/examples/companion_radio/MyMesh.h index 944790df..846708b5 100644 --- a/examples/companion_radio/MyMesh.h +++ b/examples/companion_radio/MyMesh.h @@ -203,12 +203,13 @@ public: #if ENV_INCLUDE_GPS == 1 void applyGpsPrefs() { - sensors.setSettingValue("gps", _prefs.gps_enabled ? "1" : "0"); - if (_prefs.gps_interval > 0) { - char interval_str[12]; // Max: 24 hours = 86400 seconds (5 digits + null) - sprintf(interval_str, "%u", _prefs.gps_interval); - sensors.setSettingValue("gps_interval", interval_str); + if (_prefs.gps_interval > 0 && + sensors.getSettingByKey("gps_interval") != nullptr) { + char interval[11]; + snprintf(interval, sizeof(interval), "%lu", (unsigned long)_prefs.gps_interval); + sensors.setSettingValue("gps_interval", interval); } + _prefs.getGpsPrefs()->apply(sensors); } #endif diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index c5d1df04..a54eca75 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -2,6 +2,7 @@ #include // For uint8_t, uint32_t #include #include +#include #include #define TELEM_MODE_DENY 0 @@ -35,6 +36,7 @@ public: uint8_t vibe_quiet = 0; uint8_t gps_enabled = 0; // GPS enabled flag (0=disabled, 1=enabled) uint32_t gps_interval = 0; // GPS read interval in seconds + uint32_t gps_period = 0; // periodic acquisition interval in seconds uint8_t autoadd_config = 0; // bitmask for auto-add contacts config uint8_t rx_boosted_gain = 0; // SX126x RX boosted gain mode (0=power saving, 1=boosted) uint8_t radio_fem_rxgain = 0; // external LoRa FEM RX gain (LNA) @@ -151,16 +153,21 @@ private: }; RadioPrefs radio; - class GPSPrefs : public ConfigSerializer { // COPIED from CommonCLI (for now) + class GPSPrefs : public CommonGpsPrefs { NodePrefs* _parent; protected: void structure() override { def("en", _parent->gps_enabled); // boolean def("int", _parent->gps_interval); // interval in seconds + def("period", _parent->gps_period); // periodic acquisition interval in seconds def("adv_loc", _parent->advert_loc_policy); } public: GPSPrefs(NodePrefs* parent) : _parent(parent) { } + bool isGpsEnabled() const override { return _parent->gps_enabled; } + void setGpsEnabled(bool enabled) override { _parent->gps_enabled = enabled; markDirty(); } + uint32_t getGpsPeriod() const override { return _parent->gps_period; } + void setGpsPeriod(uint32_t seconds) override { _parent->gps_period = seconds; markDirty(); } }; GPSPrefs gps; @@ -275,8 +282,9 @@ public: void setRepeatEn(bool en) { repeat.disable_fwd = en ? 0 : 1; } CommonRadioPrefs* getRadioPrefs() { return &radio; } + CommonGpsPrefs* getGpsPrefs() { return &gps; } KeyValueStore* getCustom() { return &custom; } - bool isDirty() const override { return ConfigSerializer::isDirty() || radio.isDirty() || custom.isDirty(); } - void clearDirty() override { ConfigSerializer::clearDirty(); radio.clearDirty(); custom.clearDirty(); } + bool isDirty() const override { return ConfigSerializer::isDirty() || radio.isDirty() || gps.isDirty() || custom.isDirty(); } + void clearDirty() override { ConfigSerializer::clearDirty(); radio.clearDirty(); gps.clearDirty(); custom.clearDirty(); } }; diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index cfe34cf2..a1400669 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -1182,16 +1182,14 @@ void UITask::toggleGPS() { for (int i = 0; i < num; i++) { if (strcmp(_sensors->getSettingName(i), "gps") == 0) { if (strcmp(_sensors->getSettingValue(i), "1") == 0) { - _sensors->setSettingValue("gps", "0"); - _node_prefs->gps_enabled = 0; + _node_prefs->getGpsPrefs()->setGpsEnabled(*_sensors, false); notify(UIEventType::ack); } else { - _sensors->setSettingValue("gps", "1"); - _node_prefs->gps_enabled = 1; + _node_prefs->getGpsPrefs()->setGpsEnabled(*_sensors, true); notify(UIEventType::ack); } the_mesh.savePrefs(); - showAlert(_node_prefs->gps_enabled ? "GPS: Enabled" : "GPS: Disabled", 800); + showAlert(_node_prefs->getGpsPrefs()->isGpsEnabled() ? "GPS: Enabled" : "GPS: Disabled", 800); _next_refresh = 0; break; } diff --git a/examples/companion_radio/ui-orig/UITask.cpp b/examples/companion_radio/ui-orig/UITask.cpp index 8ae57c7a..c2fd80fb 100644 --- a/examples/companion_radio/ui-orig/UITask.cpp +++ b/examples/companion_radio/ui-orig/UITask.cpp @@ -609,14 +609,15 @@ void UITask::handleButtonQuadruplePress() { for (int i = 0; i < num; i++) { if (strcmp(_sensors->getSettingName(i), "gps") == 0) { if (strcmp(_sensors->getSettingValue(i), "1") == 0) { - _sensors->setSettingValue("gps", "0"); + _node_prefs->getGpsPrefs()->setGpsEnabled(*_sensors, false); notify(UIEventType::ack); sprintf(_alert, "GPS: Disabled"); } else { - _sensors->setSettingValue("gps", "1"); + _node_prefs->getGpsPrefs()->setGpsEnabled(*_sensors, true); notify(UIEventType::ack); sprintf(_alert, "GPS: Enabled"); } + the_mesh.savePrefs(); break; } } diff --git a/examples/companion_radio/ui-tiny/UITask.cpp b/examples/companion_radio/ui-tiny/UITask.cpp index 035340a8..1b48cca8 100644 --- a/examples/companion_radio/ui-tiny/UITask.cpp +++ b/examples/companion_radio/ui-tiny/UITask.cpp @@ -833,16 +833,14 @@ void UITask::toggleGPS() { for (int i = 0; i < num; i++) { if (strcmp(_sensors->getSettingName(i), "gps") == 0) { if (strcmp(_sensors->getSettingValue(i), "1") == 0) { - _sensors->setSettingValue("gps", "0"); - _node_prefs->gps_enabled = 0; + _node_prefs->getGpsPrefs()->setGpsEnabled(*_sensors, false); notify(UIEventType::ack); } else { - _sensors->setSettingValue("gps", "1"); - _node_prefs->gps_enabled = 1; + _node_prefs->getGpsPrefs()->setGpsEnabled(*_sensors, true); notify(UIEventType::ack); } the_mesh.savePrefs(); - showAlert(_node_prefs->gps_enabled ? "GPS: Enabled" : "GPS: Disabled", 800); + showAlert(_node_prefs->getGpsPrefs()->isGpsEnabled() ? "GPS: Enabled" : "GPS: Disabled", 800); _next_refresh = 0; break; } diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index 1d975a94..7e4cfd4f 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -159,10 +159,14 @@ protected: #if ENV_INCLUDE_GPS == 1 void applyGpsPrefs() { - char period[11]; - snprintf(period, sizeof(period), "%lu", (unsigned long)_prefs.gps_period); - sensors.setSettingValue("gps_period", period); - sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0"); + if (sensors.getSettingByKey("gps_interval") != nullptr) { + // gps_interval was introduced only for EnvironmentSensorManager + // and has little interest ... kept only as a legacy + char interval[11]; + snprintf(interval, sizeof(interval), "%lu", (unsigned long)_prefs.gps_interval); + sensors.setSettingValue("gps_interval", interval); + } + _prefs.getGpsPrefs()->apply(sensors); } #endif diff --git a/examples/simple_room_server/MyMesh.h b/examples/simple_room_server/MyMesh.h index 5f8de73a..11367b12 100644 --- a/examples/simple_room_server/MyMesh.h +++ b/examples/simple_room_server/MyMesh.h @@ -168,10 +168,14 @@ protected: #if ENV_INCLUDE_GPS == 1 void applyGpsPrefs() { - char period[11]; - snprintf(period, sizeof(period), "%lu", (unsigned long)_prefs.gps_period); - sensors.setSettingValue("gps_period", period); - sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0"); + if (sensors.getSettingByKey("gps_interval") != nullptr) { + // gps_interval was introduced only for EnvironmentSensorManager + // and has little interest ... kept only as a legacy + char interval[11]; + snprintf(interval, sizeof(interval), "%lu", (unsigned long)_prefs.gps_interval); + sensors.setSettingValue("gps_interval", interval); + } + _prefs.getGpsPrefs()->apply(sensors); } #endif diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index b93939de..e6746d47 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -173,10 +173,12 @@ private: #if ENV_INCLUDE_GPS == 1 void applyGpsPrefs() { - char period[11]; - snprintf(period, sizeof(period), "%lu", (unsigned long)_prefs.gps_period); - sensors.setSettingValue("gps_period", period); - sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0"); + if (sensors.getSettingByKey("gps_interval") != nullptr) { + char interval[11]; + snprintf(interval, sizeof(interval), "%lu", (unsigned long)_prefs.gps_interval); + sensors.setSettingValue("gps_interval", interval); + } + _prefs.getGpsPrefs()->apply(sensors); } #endif }; diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index 613f2578..ed1b5199 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -349,65 +349,11 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re *(dp-1) = 0; // remove last CR } } + } else if (_prefs->getGpsPrefs()->handleCommand(command, *_sensors, reply)) { + if (_prefs->getGpsPrefs()->isDirty()) savePrefs(); } else if (memcmp(command, "region", 6) == 0) { handleRegionCmd(command, reply); #if ENV_INCLUDE_GPS == 1 - } else if (memcmp(command, "gps on", 6) == 0) { - if (_sensors->setSettingValue("gps", "1")) { - _prefs->gps_enabled = 1; - savePrefs(); - strcpy(reply, "ok"); - } else { - strcpy(reply, "gps toggle not found"); - } - } else if (memcmp(command, "gps off", 7) == 0) { - if (_sensors->setSettingValue("gps", "0")) { - _prefs->gps_enabled = 0; - savePrefs(); - strcpy(reply, "ok"); - } else { - strcpy(reply, "gps toggle not found"); - } - } else if (memcmp(command, "gps period ", 11) == 0) { - char* end = nullptr; - unsigned long period = strtoul(command + 11, &end, 10); - if (command[11] == '\0' || *end != '\0' || period > 86400) { - strcpy(reply, "gps period must be 0-86400 seconds"); - } else { - char period_value[11]; - snprintf(period_value, sizeof(period_value), "%lu", period); - if (_sensors->setSettingValue("gps_period", period_value) && - _sensors->setSettingValue("gps", "1")) { - _prefs->gps_period = (uint32_t)period; - _prefs->gps_enabled = 1; - savePrefs(); - strcpy(reply, "ok"); - } else { - strcpy(reply, "gps provider not found"); - } - } - } else if (memcmp(command, "gps sync", 8) == 0) { - LocationProvider * l = _sensors->getLocationProvider(); - if (l != NULL) { - l->syncTime(); - strcpy(reply, "ok"); - } else { - strcpy(reply, "gps provider not found"); - } - } else if (strcmp(command, "gps diag") == 0) { - LocationProvider * l = _sensors->getLocationProvider(); - if (l != NULL) { - const char* setting = _sensors->getSettingByKey("gps"); - bool requested = setting != NULL && strcmp(setting, "1") == 0; - int prefix_len = snprintf(reply, 160, "req:%u ", requested ? 1U : 0U); - if (prefix_len < 0 || prefix_len >= 160) { - reply[159] = 0; - } else { - l->formatDiagnostics(reply + prefix_len, 160 - prefix_len); - } - } else { - strcpy(reply, "gps provider not found"); - } } else if (memcmp(command, "gps setloc", 10) == 0) { _prefs->node_lat = _sensors->node_lat; _prefs->node_lon = _sensors->node_lon; @@ -443,24 +389,6 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re } else { strcpy(reply, "error"); } - } else if (memcmp(command, "gps", 3) == 0) { - LocationProvider * l = _sensors->getLocationProvider(); - if (l != NULL) { - bool enabled = l->isEnabled(); // is EN pin on ? - bool fix = l->isValid(); // has fix ? - int sats = l->satellitesCount(); - bool active = !strcmp(_sensors->getSettingByKey("gps"), "1"); - if (enabled) { - sprintf(reply, "on, %s, %s, %d sats", - active?"active":"deactivated", - fix?"fix":"no fix", - sats); - } else { - strcpy(reply, "off"); - } - } else { - strcpy(reply, "Can't find GPS"); - } #endif } else if (memcmp(command, "powersaving on", 14) == 0) { #if defined(NRF52_PLATFORM) diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 06778a60..33e27d2d 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -7,6 +7,7 @@ #include #include #include +#include #include #if defined(WITH_RS232_BRIDGE) || defined(WITH_ESPNOW_BRIDGE) @@ -153,7 +154,7 @@ private: }; BridgePrefs bridge; - class GPSPrefs : public ConfigSerializer { + class GPSPrefs : public CommonGpsPrefs { NodePrefs* _parent; protected: void structure() override { @@ -164,6 +165,10 @@ private: } public: GPSPrefs(NodePrefs* parent) : _parent(parent) { } + bool isGpsEnabled() const override { return _parent->gps_enabled; } + void setGpsEnabled(bool enabled) override { _parent->gps_enabled = enabled; markDirty(); } + uint32_t getGpsPeriod() const override { return _parent->gps_period; } + void setGpsPeriod(uint32_t seconds) override { _parent->gps_period = seconds; markDirty(); } }; GPSPrefs gps; @@ -236,10 +241,11 @@ public: } CommonRadioPrefs* getRadioPrefs() { return &radio; } + CommonGpsPrefs* getGpsPrefs() { return &gps; } KeyValueStore* getCustom() { return &custom; } - bool isDirty() const override { return ConfigSerializer::isDirty() || radio.isDirty() || custom.isDirty(); } - void clearDirty() override { ConfigSerializer::clearDirty(); radio.clearDirty(); custom.clearDirty(); } + bool isDirty() const override { return ConfigSerializer::isDirty() || radio.isDirty() || gps.isDirty() || custom.isDirty(); } + void clearDirty() override { ConfigSerializer::clearDirty(); radio.clearDirty(); gps.clearDirty(); custom.clearDirty(); } }; class CommonCLICallbacks { diff --git a/src/helpers/CommonGpsPrefs.cpp b/src/helpers/CommonGpsPrefs.cpp new file mode 100644 index 00000000..fe29c0c0 --- /dev/null +++ b/src/helpers/CommonGpsPrefs.cpp @@ -0,0 +1,110 @@ +#include "CommonGpsPrefs.h" +#include + +bool CommonGpsPrefs::setGpsEnabled(SensorManager& sensors, bool enabled) { + LocationProvider* location = sensors.getLocationProvider(); + if (location == nullptr) return false; + location->setGpsOn(enabled); + setGpsEnabled(enabled); + return true; +} + +bool CommonGpsPrefs::setGpsPeriod(SensorManager& sensors, uint32_t seconds) { + LocationProvider* location = sensors.getLocationProvider(); + if (location == nullptr) return false; + location->setGpsPeriod(seconds); + setGpsPeriod(seconds); + return true; +} + +bool CommonGpsPrefs::apply(SensorManager& sensors) const { + LocationProvider* location = sensors.getLocationProvider(); + if (location == nullptr) return false; + location->setGpsPeriod(getGpsPeriod()); + location->setGpsOn(isGpsEnabled()); + return true; +} + +bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, char* reply) { + if (strcmp(command, "gps") == 0) { + LocationProvider* location = sensors.getLocationProvider(); + char mode[32]; + if (getGpsPeriod() == 0) { + strcpy(mode, "tracking"); + } else { + snprintf(mode, sizeof(mode), "periodic (%lus)", + (unsigned long)getGpsPeriod()); + } + if (location == nullptr) { + strcpy(reply, "gps provider not found"); + } else if (location->isEnabled()) { + sprintf(reply, "on, %s, %s, %d sats, mode: %s", + isGpsEnabled() ? "active" : "deactivated", + location->isValid() ? "fix" : "no fix", + location->satellitesCount(), mode); + } else { + snprintf(reply, 160, "off, mode: %s", mode); + } + return true; + } + if (memcmp(command, "gps on", 6) == 0) { + if (!setGpsEnabled(sensors, true)) { + strcpy(reply, "gps toggle not found"); + } else { + strcpy(reply, "ok"); + } + return true; + } + if (memcmp(command, "gps off", 7) == 0) { + if (!setGpsEnabled(sensors, false)) { + strcpy(reply, "gps toggle not found"); + } else { + strcpy(reply, "ok"); + } + return true; + } + if (strcmp(command, "gps period") == 0) { + if (getGpsPeriod() == 0) { + strcpy(reply, "> 0 (continuous)"); + } else { + sprintf(reply, "> %lu", (unsigned long)getGpsPeriod()); + } + return true; + } + if (memcmp(command, "gps period ", 11) == 0) { + char* end = nullptr; + unsigned long period = strtoul(command + 11, &end, 10); + if (command[11] == '\0' || *end != '\0' || period > 86400) { + strcpy(reply, "gps period must be 0-86400 seconds"); + } else { + if (!setGpsPeriod(sensors, (uint32_t)period) || + !setGpsEnabled(sensors, true)) { + strcpy(reply, "gps provider not found"); + } else { + strcpy(reply, "ok"); + } + } + return true; + } + if (memcmp(command, "gps sync", 8) == 0) { + LocationProvider* location = sensors.getLocationProvider(); + if (location == nullptr) { + strcpy(reply, "gps provider not found"); + } else { + location->syncTime(); + strcpy(reply, "ok"); + } + return true; + } + if (strcmp(command, "gps diag") == 0) { + LocationProvider* location = sensors.getLocationProvider(); + if (location == nullptr) { + strcpy(reply, "gps provider not found"); + } else { + int prefix = snprintf(reply, 160, "req:%u ", isGpsEnabled() ? 1U : 0U); + if (prefix >= 0 && prefix < 160) location->formatDiagnostics(reply + prefix, 160 - prefix); + } + return true; + } + return false; +} diff --git a/src/helpers/CommonGpsPrefs.h b/src/helpers/CommonGpsPrefs.h new file mode 100644 index 00000000..25cce1b1 --- /dev/null +++ b/src/helpers/CommonGpsPrefs.h @@ -0,0 +1,26 @@ +#pragma once + +#include "ConfigSerializer.h" +#include "SensorManager.h" + +class CommonGpsPrefs : public ConfigSerializer { + bool _is_dirty = false; + +protected: + CommonGpsPrefs() = default; + +public: + void markDirty() { _is_dirty = true; } + void clearDirty() { _is_dirty = false; } + bool isDirty() const { return _is_dirty; } + + virtual bool isGpsEnabled() const = 0; + virtual void setGpsEnabled(bool enabled) = 0; + virtual uint32_t getGpsPeriod() const = 0; + virtual void setGpsPeriod(uint32_t seconds) = 0; + + bool setGpsEnabled(SensorManager& sensors, bool enabled); + bool setGpsPeriod(SensorManager& sensors, uint32_t seconds); + bool apply(SensorManager& sensors) const; + bool handleCommand(const char* command, SensorManager& sensors, char* reply); +}; diff --git a/src/helpers/sensors/EnvironmentSensorManager.cpp b/src/helpers/sensors/EnvironmentSensorManager.cpp index 2861fac2..2cf8b66b 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.cpp +++ b/src/helpers/sensors/EnvironmentSensorManager.cpp @@ -650,7 +650,7 @@ bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, Cayen int EnvironmentSensorManager::getNumSettings() const { int settings = 0; #if ENV_INCLUDE_GPS - if (gps_detected) settings += 2; // GPS enablement and periodic acquisition + if (gps_detected) settings += 1; // GPS enablement #endif return settings; } @@ -661,9 +661,6 @@ const char* EnvironmentSensorManager::getSettingName(int i) const { if (gps_detected && i == settings++) { return "gps"; } - if (gps_detected && i == settings++) { - return "gps_period"; - } #endif return NULL; } @@ -674,12 +671,6 @@ const char* EnvironmentSensorManager::getSettingValue(int i) const { if (gps_detected && i == settings++) { return _location->isGpsOn() ? "1" : "0"; } - if (gps_detected && i == settings++) { - static char period[11]; - snprintf(period, sizeof(period), "%lu", - (unsigned long)_location->getGpsPeriod()); - return period; - } #endif return NULL; } @@ -694,13 +685,6 @@ bool EnvironmentSensorManager::setSettingValue(const char* name, const char* val } return true; } - if (gps_detected && strcmp(name, "gps_period") == 0) { - char* end = nullptr; - unsigned long period = strtoul(value, &end, 10); - if (*value == '\0' || *end != '\0' || period > 86400) return false; - _location->setGpsPeriod((uint32_t)period); - return true; - } if (strcmp(name, "gps_interval") == 0) { uint32_t interval_seconds = atoi(value); gps_update_interval_sec = interval_seconds > 0 ? interval_seconds : 1; diff --git a/variants/gat562_mesh_evb_pro/target.cpp b/variants/gat562_mesh_evb_pro/target.cpp index 8dc203de..0aac297a 100644 --- a/variants/gat562_mesh_evb_pro/target.cpp +++ b/variants/gat562_mesh_evb_pro/target.cpp @@ -26,7 +26,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; diff --git a/variants/gat562_mesh_tracker_pro/target.cpp b/variants/gat562_mesh_tracker_pro/target.cpp index d16b4538..225aa161 100644 --- a/variants/gat562_mesh_tracker_pro/target.cpp +++ b/variants/gat562_mesh_tracker_pro/target.cpp @@ -27,7 +27,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; diff --git a/variants/heltec_mesh_solar/target.cpp b/variants/heltec_mesh_solar/target.cpp index 94e2684c..9468f8fc 100644 --- a/variants/heltec_mesh_solar/target.cpp +++ b/variants/heltec_mesh_solar/target.cpp @@ -11,7 +11,8 @@ WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); SolarSensorManager sensors = SolarSensorManager(nmea); SolarExternalWatchdog external_watchdog; @@ -30,17 +31,11 @@ mesh::LocalIdentity radio_new_identity() { } void SolarSensorManager::start_gps() { - if (!gps_active) { - gps_active = true; - _location->begin(); - } + _location->setGpsOn(true); } void SolarSensorManager::stop_gps() { - if (gps_active) { - gps_active = false; - _location->stop(); - } + _location->setGpsOn(false); } bool SolarSensorManager::begin() { @@ -91,7 +86,7 @@ const char* SolarSensorManager::getSettingName(int i) const { const char* SolarSensorManager::getSettingValue(int i) const { if (gps_detected && i == 0) { - return gps_active ? "1" : "0"; + return _location->isGpsOn() ? "1" : "0"; } return NULL; } diff --git a/variants/heltec_mesh_solar/target.h b/variants/heltec_mesh_solar/target.h index 8e13a960..97550a00 100644 --- a/variants/heltec_mesh_solar/target.h +++ b/variants/heltec_mesh_solar/target.h @@ -14,7 +14,6 @@ #endif class SolarSensorManager : public SensorManager { - bool gps_active = false; bool gps_detected = false; LocationProvider* _location; diff --git a/variants/heltec_rc32/target.cpp b/variants/heltec_rc32/target.cpp index cc7e4deb..e095baab 100644 --- a/variants/heltec_rc32/target.cpp +++ b/variants/heltec_rc32/target.cpp @@ -20,7 +20,9 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, PIN_GPS_RESET, PIN_GPS_EN); + NmeaGpsDriver gps_driver(Serial1, PIN_GPS_TX, PIN_GPS_RX, PIN_GPS_RESET, + PIN_GPS_EN); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; diff --git a/variants/heltec_t096/target.cpp b/variants/heltec_t096/target.cpp index 30509977..d0c2c07e 100644 --- a/variants/heltec_t096/target.cpp +++ b/variants/heltec_t096/target.cpp @@ -22,7 +22,9 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, GPS_RESET, GPS_EN, &board.periph_power); +NmeaGpsDriver gps_driver(Serial1, PIN_GPS_TX, PIN_GPS_RX, GPS_RESET, GPS_EN, + &board.periph_power); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; diff --git a/variants/heltec_t1/target.cpp b/variants/heltec_t1/target.cpp index af771582..1d9c8baa 100644 --- a/variants/heltec_t1/target.cpp +++ b/variants/heltec_t1/target.cpp @@ -21,7 +21,9 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, GPS_RESET, GPS_EN, &board.periph_power); +NmeaGpsDriver gps_driver(Serial1, PIN_GPS_TX, PIN_GPS_RX, GPS_RESET, GPS_EN, + &board.periph_power); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; diff --git a/variants/heltec_t114/target.cpp b/variants/heltec_t114/target.cpp index 90a902f8..dc62f83b 100644 --- a/variants/heltec_t114/target.cpp +++ b/variants/heltec_t114/target.cpp @@ -22,7 +22,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; diff --git a/variants/heltec_tower_v2/target.cpp b/variants/heltec_tower_v2/target.cpp index ec8e7a17..ae627a0b 100644 --- a/variants/heltec_tower_v2/target.cpp +++ b/variants/heltec_tower_v2/target.cpp @@ -12,7 +12,8 @@ WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); TowerV2ExternalWatchdog external_watchdog; diff --git a/variants/heltec_tracker/target.cpp b/variants/heltec_tracker/target.cpp index f32c41ff..5903f659 100644 --- a/variants/heltec_tracker/target.cpp +++ b/variants/heltec_tracker/target.cpp @@ -17,7 +17,20 @@ WRAPPER_CLASS radio_driver(radio, board); ESP32RTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); // GPS_EN (GPIO35) drives N-ch MOSFET → P-ch high-side switch; GPS_RESET (GPIO36) active LOW -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, GPS_RESET, GPS_EN, &board.periph_power); +class HeltecTrackerGpsDriver : public NmeaGpsDriver { +public: + HeltecTrackerGpsDriver() + : NmeaGpsDriver(Serial1, PIN_GPS_TX, PIN_GPS_RX, GPS_RESET, GPS_EN, + &board.periph_power) {} + + void begin() override { + NmeaGpsDriver::begin(); + sendNmeaSentence("$CFGSYS,h35155*68"); + } +}; + +HeltecTrackerGpsDriver gps_driver; +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); HWTSensorManager sensors = HWTSensorManager(nmea); #ifdef DISPLAY_CLASS @@ -43,18 +56,11 @@ mesh::LocalIdentity radio_new_identity() { } void HWTSensorManager::start_gps() { - if (!gps_active) { - _location->begin(); // Claims periph_power via RefCountedDigitalPin - gps_active = true; - Serial1.println("$CFGSYS,h35155*68"); // Configure GPS for all constellations - } + _location->setGpsOn(true); } void HWTSensorManager::stop_gps() { - if (gps_active) { - gps_active = false; - _location->stop(); // Releases periph_power via RefCountedDigitalPin - } + _location->setGpsOn(false); } bool HWTSensorManager::begin() { @@ -76,7 +82,7 @@ void HWTSensorManager::loop() { _location->loop(); if (millis() > next_gps_update) { - if (gps_active && _location->isValid()) { + if (_location->isEnabled() && _location->isValid()) { node_lat = ((double)_location->getLatitude())/1000000.; node_lon = ((double)_location->getLongitude())/1000000.; node_altitude = ((double)_location->getAltitude()) / 1000.0; @@ -93,7 +99,7 @@ const char* HWTSensorManager::getSettingName(int i) const { } const char* HWTSensorManager::getSettingValue(int i) const { if (i == 0) { - return gps_active ? "1" : "0"; + return _location->isGpsOn() ? "1" : "0"; } return NULL; } diff --git a/variants/heltec_tracker/target.h b/variants/heltec_tracker/target.h index 2931eda8..f6fea637 100644 --- a/variants/heltec_tracker/target.h +++ b/variants/heltec_tracker/target.h @@ -14,7 +14,6 @@ #endif class HWTSensorManager : public SensorManager { - bool gps_active = false; LocationProvider * _location; void start_gps(); diff --git a/variants/heltec_tracker_v2/target.cpp b/variants/heltec_tracker_v2/target.cpp index c48a29f6..12b01bcc 100644 --- a/variants/heltec_tracker_v2/target.cpp +++ b/variants/heltec_tracker_v2/target.cpp @@ -17,7 +17,9 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, GPS_RESET, GPS_EN, &board.periph_power); + NmeaGpsDriver gps_driver(Serial1, PIN_GPS_TX, PIN_GPS_RX, GPS_RESET, GPS_EN, + &board.periph_power); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -43,4 +45,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/heltec_v3/target.cpp b/variants/heltec_v3/target.cpp index e6af466a..f2f712eb 100644 --- a/variants/heltec_v3/target.cpp +++ b/variants/heltec_v3/target.cpp @@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -43,4 +44,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/heltec_v4/target.cpp b/variants/heltec_v4/target.cpp index 8483f276..0f87c6b3 100644 --- a/variants/heltec_v4/target.cpp +++ b/variants/heltec_v4/target.cpp @@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -43,4 +44,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/heltec_v4_r8/target.cpp b/variants/heltec_v4_r8/target.cpp index 0b38531e..27e9f468 100644 --- a/variants/heltec_v4_r8/target.cpp +++ b/variants/heltec_v4_r8/target.cpp @@ -17,7 +17,9 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, GPS_RESET, GPS_EN, &board.periph_power); + NmeaGpsDriver gps_driver(Serial1, PIN_GPS_TX, PIN_GPS_RX, GPS_RESET, GPS_EN, + &board.periph_power); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; diff --git a/variants/keepteen_lt1/target.cpp b/variants/keepteen_lt1/target.cpp index f1879ac5..dd7c6741 100644 --- a/variants/keepteen_lt1/target.cpp +++ b/variants/keepteen_lt1/target.cpp @@ -12,7 +12,8 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -34,4 +35,3 @@ mesh::LocalIdentity radio_new_identity() { return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/lilygo_t_impulse_plus/target.cpp b/variants/lilygo_t_impulse_plus/target.cpp index 87b3dbfe..b6b0c82c 100644 --- a/variants/lilygo_t_impulse_plus/target.cpp +++ b/variants/lilygo_t_impulse_plus/target.cpp @@ -13,7 +13,8 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); @@ -34,4 +35,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/lilygo_tbeam_1w/target.cpp b/variants/lilygo_tbeam_1w/target.cpp index 6755df09..db11747f 100644 --- a/variants/lilygo_tbeam_1w/target.cpp +++ b/variants/lilygo_tbeam_1w/target.cpp @@ -19,7 +19,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -47,4 +48,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); } - diff --git a/variants/lilygo_tbeam_SX1262/target.cpp b/variants/lilygo_tbeam_SX1262/target.cpp index 6e5292a7..b97dda41 100644 --- a/variants/lilygo_tbeam_SX1262/target.cpp +++ b/variants/lilygo_tbeam_SX1262/target.cpp @@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -38,4 +39,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/lilygo_tbeam_SX1276/target.cpp b/variants/lilygo_tbeam_SX1276/target.cpp index 30f23dab..be7c8287 100644 --- a/variants/lilygo_tbeam_SX1276/target.cpp +++ b/variants/lilygo_tbeam_SX1276/target.cpp @@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; diff --git a/variants/lilygo_tbeam_supreme_SX1262/target.cpp b/variants/lilygo_tbeam_supreme_SX1262/target.cpp index a0b765bf..86b9116c 100644 --- a/variants/lilygo_tbeam_supreme_SX1262/target.cpp +++ b/variants/lilygo_tbeam_supreme_SX1262/target.cpp @@ -19,7 +19,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -35,4 +36,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/lilygo_tdeck/target.cpp b/variants/lilygo_tdeck/target.cpp index d20c56a3..4084a73b 100644 --- a/variants/lilygo_tdeck/target.cpp +++ b/variants/lilygo_tdeck/target.cpp @@ -14,7 +14,8 @@ WRAPPER_CLASS radio_driver(radio, board); ESP32RTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); -MicroNMEALocationProvider gps(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider gps(gps_driver, &rtc_clock); EnvironmentSensorManager sensors(gps); #ifdef DISPLAY_CLASS diff --git a/variants/lilygo_techo_card/target.cpp b/variants/lilygo_techo_card/target.cpp index 8bbe0363..ea74bd0c 100644 --- a/variants/lilygo_techo_card/target.cpp +++ b/variants/lilygo_techo_card/target.cpp @@ -13,7 +13,8 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); diff --git a/variants/lilygo_techo_lite/target.cpp b/variants/lilygo_techo_lite/target.cpp index 95a62fcd..6d199fff 100644 --- a/variants/lilygo_techo_lite/target.cpp +++ b/variants/lilygo_techo_lite/target.cpp @@ -13,7 +13,8 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); @@ -35,4 +36,3 @@ mesh::LocalIdentity radio_new_identity() { return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/meshadventurer/target.cpp b/variants/meshadventurer/target.cpp index 8795a4cb..faf2e30e 100644 --- a/variants/meshadventurer/target.cpp +++ b/variants/meshadventurer/target.cpp @@ -11,7 +11,8 @@ WRAPPER_CLASS radio_driver(radio, board); ESP32RTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); MASensorManager sensors = MASensorManager(nmea); #ifdef DISPLAY_CLASS @@ -37,17 +38,13 @@ mesh::LocalIdentity radio_new_identity() { void MASensorManager::start_gps() { - if(!gps_active) { - MESH_DEBUG_PRINTLN("starting GPS"); - gps_active = true; - } + MESH_DEBUG_PRINTLN("starting GPS"); + _location->setGpsOn(true); } void MASensorManager::stop_gps() { - if(gps_active) { - MESH_DEBUG_PRINTLN("stopping GPS"); - gps_active = false; - } + MESH_DEBUG_PRINTLN("stopping GPS"); + _location->setGpsOn(false); } bool MASensorManager::begin() { @@ -67,7 +64,7 @@ bool MASensorManager::querySensors(uint8_t requester_permissions, CayenneLPP& te void MASensorManager::loop() { static long next_gps_update = 0; _location->loop(); - if(millis() > next_gps_update && gps_active) { + if(millis() > next_gps_update && _location->isEnabled()) { if(_location->isValid()) { node_lat = ((double)_location->getLatitude()) / 1000000.; node_lon = ((double)_location->getLongitude()) / 1000000.; @@ -85,7 +82,7 @@ const char* MASensorManager::getSettingName(int i) const { } const char* MASensorManager::getSettingValue(int i) const { if(i == 0) { - return gps_active ? "1" : "0"; + return _location->isGpsOn() ? "1" : "0"; } return NULL; } diff --git a/variants/meshadventurer/target.h b/variants/meshadventurer/target.h index 0749565d..9581d422 100644 --- a/variants/meshadventurer/target.h +++ b/variants/meshadventurer/target.h @@ -15,8 +15,7 @@ #endif class MASensorManager : public SensorManager { - bool gps_active = false; - LocationProvider * _location; + LocationProvider* _location; void start_gps(); void stop_gps(); diff --git a/variants/meshnology_w12/target.cpp b/variants/meshnology_w12/target.cpp index bf04ba36..a3d6089f 100644 --- a/variants/meshnology_w12/target.cpp +++ b/variants/meshnology_w12/target.cpp @@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -70,4 +71,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/meshtracker_x1/target.cpp b/variants/meshtracker_x1/target.cpp index 5b90d660..2dee0ebd 100644 --- a/variants/meshtracker_x1/target.cpp +++ b/variants/meshtracker_x1/target.cpp @@ -1,7 +1,7 @@ #include #include "target.h" +#include #include -#include MeshTrackerX1Board board; @@ -10,7 +10,8 @@ RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BU WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock rtc_clock; -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +AirohaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); MeshTrackerX1SensorManager sensors = MeshTrackerX1SensorManager(nmea); #ifdef DISPLAY_CLASS @@ -27,28 +28,16 @@ mesh::LocalIdentity radio_new_identity() { } void MeshTrackerX1SensorManager::start_gps() { - gps_active = true; - digitalWrite(GPS_EN, HIGH); - delay(10); - digitalWrite(GPS_RTC_INT, HIGH); - delay(5); - digitalWrite(GPS_RTC_INT, LOW); + _nmea->setGpsOn(true); } void MeshTrackerX1SensorManager::stop_gps() { - gps_active = false; - digitalWrite(GPS_VRTC_EN, HIGH); // keep GPS RTC alive for faster fix on wake - digitalWrite(GPS_RTC_INT, LOW); // make sure this is LOW so we can pulse it to wake - airohaEnterSleep(_nmea); - digitalWrite(GPS_EN, LOW); + _nmea->setGpsOn(false); } bool MeshTrackerX1SensorManager::begin() { // init GPS - Serial1.begin(GPS_BAUD_RATE); - digitalWrite(GPS_RESET, HIGH); - delay(10); - digitalWrite(GPS_RESET, LOW); + gps_driver.initialize(); // init SPA06-003 barometer baro_ok = spa06.begin(SPA06_003_DEFAULT_ADDR, &Wire) || spa06.begin(0x76, &Wire); @@ -81,7 +70,7 @@ void MeshTrackerX1SensorManager::loop() { _nmea->loop(); if (millis() > next_gps_update) { - if (gps_active && _nmea->isValid()) { + if (_nmea->isEnabled() && _nmea->isValid()) { node_lat = ((double)_nmea->getLatitude())/1000000.; node_lon = ((double)_nmea->getLongitude())/1000000.; node_altitude = ((double)_nmea->getAltitude()) / 1000.0; @@ -97,7 +86,7 @@ const char* MeshTrackerX1SensorManager::getSettingName(int i) const { } const char* MeshTrackerX1SensorManager::getSettingValue(int i) const { if (i == 0) { - return gps_active ? "1" : "0"; + return _nmea->isGpsOn() ? "1" : "0"; } return NULL; } diff --git a/variants/meshtracker_x1/target.h b/variants/meshtracker_x1/target.h index 9741efb6..e678e29c 100644 --- a/variants/meshtracker_x1/target.h +++ b/variants/meshtracker_x1/target.h @@ -14,13 +14,11 @@ #endif class MeshTrackerX1SensorManager: public SensorManager { - bool gps_active = false; bool baro_ok = false; Adafruit_SPA06_003 spa06; LocationProvider * _nmea; void start_gps(); - void sleep_gps(); void stop_gps(); public: MeshTrackerX1SensorManager(LocationProvider &nmea): _nmea(&nmea) { } diff --git a/variants/minewsemi_me25ls01/target.cpp b/variants/minewsemi_me25ls01/target.cpp index 41fc71a7..8d9a6e07 100644 --- a/variants/minewsemi_me25ls01/target.cpp +++ b/variants/minewsemi_me25ls01/target.cpp @@ -10,7 +10,8 @@ VolatileRTCClock rtc_clock; extern EnvironmentSensorManager sensors; #if ENV_INCLUDE_GPS #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; diff --git a/variants/muzi_base/target.cpp b/variants/muzi_base/target.cpp index 5bd846c9..b65bafa1 100644 --- a/variants/muzi_base/target.cpp +++ b/variants/muzi_base/target.cpp @@ -13,7 +13,8 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); MuziBaseSensorManager sensors = MuziBaseSensorManager(nmea); #else MuziBaseSensorManager sensors; @@ -38,13 +39,7 @@ static void muziPowerOff() { bool MuziBaseSensorManager::begin() { pwr_btn.begin(); - bool ok = EnvironmentSensorManager::begin(); -#if ENV_INCLUDE_GPS - pinMode(PIN_GPS_SWITCH, INPUT); - _last_gps_sw = digitalRead(PIN_GPS_SWITCH); // initial gps state from the switch - if (_last_gps_sw == HIGH) start_gps(); else stop_gps(); -#endif - return ok; + return EnvironmentSensorManager::begin(); } void MuziBaseSensorManager::loop() { @@ -55,17 +50,6 @@ void MuziBaseSensorManager::loop() { _pwr_last_click = t; if (++_pwr_clicks >= USER_BTN_POWER_OFF_CLICKS) muziPowerOff(); } -#if ENV_INCLUDE_GPS - unsigned long now = millis(); - if (now > _next_sw_check) { // check the mode switch ~once a sec - _next_sw_check = now + 1000; - int sw = digitalRead(PIN_GPS_SWITCH); - if (sw != _last_gps_sw) { - _last_gps_sw = sw; - if (sw == HIGH) start_gps(); else stop_gps(); - } - } -#endif EnvironmentSensorManager::loop(); } diff --git a/variants/muzi_base/target.h b/variants/muzi_base/target.h index 45cd595f..3f7dcbf5 100644 --- a/variants/muzi_base/target.h +++ b/variants/muzi_base/target.h @@ -38,14 +38,10 @@ extern AutoDiscoverRTCClock rtc_clock; // muzi sensor manager, polled from main loop via sensors.loop(): // - user button: USER_BTN_POWER_OFF_CLICKS quick presses -> power off (all builds) -// - gps mode switch on/off (superIO only, see thinknode_m1) +// gps mode is now handled by GpsDriver on superIO class MuziBaseSensorManager : public EnvironmentSensorManager { unsigned long _pwr_last_click = 0; uint8_t _pwr_clicks = 0; -#if ENV_INCLUDE_GPS - int _last_gps_sw = -1; - unsigned long _next_sw_check = 0; -#endif public: #if ENV_INCLUDE_GPS MuziBaseSensorManager(LocationProvider& location) : EnvironmentSensorManager(location) {} diff --git a/variants/muzi_base/variant.h b/variants/muzi_base/variant.h index b007c1f8..0c1245a8 100644 --- a/variants/muzi_base/variant.h +++ b/variants/muzi_base/variant.h @@ -162,6 +162,8 @@ static const uint8_t AREF = (PIN_AREF); // not used #define SWITCH_MODE1 (32+9) // P1.09 #define SWITCH_MODE2 (12) // P0.12 #define PIN_GPS_SWITCH SWITCH_MODE2 +#define GPS_SWITCH_IS_HARDWARE (0) +#define GPS_SWITCH_TURNS_GPS_ON (1) //////////////////////////////////////////////////////////////////////////////// // Buzzer diff --git a/variants/muziworks_r1_neo/target.cpp b/variants/muziworks_r1_neo/target.cpp index f667a282..3081de2c 100644 --- a/variants/muziworks_r1_neo/target.cpp +++ b/variants/muziworks_r1_neo/target.cpp @@ -20,7 +20,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; diff --git a/variants/nano_g2_ultra/NanoG2UltraGpsDriver.h b/variants/nano_g2_ultra/NanoG2UltraGpsDriver.h new file mode 100644 index 00000000..3772084b --- /dev/null +++ b/variants/nano_g2_ultra/NanoG2UltraGpsDriver.h @@ -0,0 +1,31 @@ +#pragma once + +#include + +class NanoG2UltraGpsDriver : public NmeaGpsDriver { +public: + NanoG2UltraGpsDriver(HardwareSerial& serial) : NmeaGpsDriver(serial) { + pinMode(PIN_GPS_STANDBY, OUTPUT); + digitalWrite(PIN_GPS_STANDBY, LOW); + } + + void begin() override { + if (isEnabled()) return; + + digitalWrite(PIN_GPS_STANDBY, HIGH); + NmeaGpsDriver::begin(); + delay(1000); + } + + void stop() override { + NmeaGpsDriver::stop(); + digitalWrite(PIN_GPS_STANDBY, LOW); + } + + bool detectAtBoot() { + begin(); + const bool wasActive = detect(0); + if (!wasActive) stop(); + return wasActive; + } +}; diff --git a/variants/nano_g2_ultra/target.cpp b/variants/nano_g2_ultra/target.cpp index 69a2772c..ee258f2d 100644 --- a/variants/nano_g2_ultra/target.cpp +++ b/variants/nano_g2_ultra/target.cpp @@ -3,6 +3,7 @@ #include #include #include +#include "NanoG2UltraGpsDriver.h" NanoG2Ultra board; @@ -12,8 +13,10 @@ WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); -NanoG2UltraSensorManager sensors = NanoG2UltraSensorManager(nmea); +// NanoG2UltraGpsDriver now handles the special init needed for NanoG2 +NanoG2UltraGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); +NanoG2UltraSensorManager sensors = NanoG2UltraSensorManager(nmea, gps_driver); #ifdef DISPLAY_CLASS DISPLAY_CLASS display; @@ -27,35 +30,19 @@ bool radio_init() { void NanoG2UltraSensorManager::start_gps() { MESH_DEBUG_PRINTLN("Starting GPS"); - if (!gps_active) { - digitalWrite(PIN_GPS_STANDBY, HIGH); // Wake GPS from standby - Serial1.setPins(PIN_GPS_TX, PIN_GPS_RX); - Serial1.begin(9600); - MESH_DEBUG_PRINTLN("Waiting for gps to power up"); - delay(1000); - gps_active = true; - } - _location->begin(); + _location->setGpsOn(true); } void NanoG2UltraSensorManager::stop_gps() { MESH_DEBUG_PRINTLN("Stopping GPS"); - if (gps_active) { - digitalWrite(PIN_GPS_STANDBY, LOW); // sleep GPS - gps_active = false; - } - _location->stop(); + _location->setGpsOn(false); } bool NanoG2UltraSensorManager::begin() { - digitalWrite(PIN_GPS_STANDBY, HIGH); // Wake GPS from standby - Serial1.setPins(PIN_GPS_TX, PIN_GPS_RX); - Serial1.begin(9600); MESH_DEBUG_PRINTLN("Checking GPS switch state"); - delay(1000); // Check initial switch state to determine if GPS should be active - if (Serial1.available() > 0) { + if (_gps_driver->detectAtBoot()) { MESH_DEBUG_PRINTLN("GPS was on at boot, GPS enabled"); start_gps(); } else { @@ -75,14 +62,14 @@ bool NanoG2UltraSensorManager::querySensors(uint8_t requester_permissions, Cayen void NanoG2UltraSensorManager::loop() { static long next_gps_update = 0; - if (!gps_active) { + if (!_location->isEnabled()) { return; // GPS is not active, skip further processing } _location->loop(); if (millis() > next_gps_update) { - if (_location->isValid()) { + if (_location->isEnabled() && _location->isValid()) { node_lat = ((double)_location->getLatitude()) / 1000000.; node_lon = ((double)_location->getLongitude()) / 1000000.; node_altitude = ((double)_location->getAltitude()) / 1000.0; @@ -105,7 +92,7 @@ const char *NanoG2UltraSensorManager::getSettingName(int i) const { const char *NanoG2UltraSensorManager::getSettingValue(int i) const { if (i == 0) { - return gps_active ? "1" : "0"; + return _location->isGpsOn() ? "1" : "0"; } return NULL; } diff --git a/variants/nano_g2_ultra/target.h b/variants/nano_g2_ultra/target.h index 5c6ebee1..d540b9ec 100644 --- a/variants/nano_g2_ultra/target.h +++ b/variants/nano_g2_ultra/target.h @@ -14,15 +14,18 @@ #endif #include +class NanoG2UltraGpsDriver; + class NanoG2UltraSensorManager : public SensorManager { - bool gps_active = false; LocationProvider *_location; + NanoG2UltraGpsDriver *_gps_driver; void start_gps(); void stop_gps(); public: - NanoG2UltraSensorManager(LocationProvider &location) : _location(&location) {} + NanoG2UltraSensorManager(LocationProvider &location, NanoG2UltraGpsDriver &gps_driver) + : _location(&location), _gps_driver(&gps_driver) {} bool begin() override; bool querySensors(uint8_t requester_permissions, CayenneLPP &telemetry) override; void loop() override; @@ -44,4 +47,3 @@ extern MomentaryButton user_btn; bool radio_init(); mesh::LocalIdentity radio_new_identity(); - diff --git a/variants/promicro/target.cpp b/variants/promicro/target.cpp index b5a74c90..5758d9cd 100644 --- a/variants/promicro/target.cpp +++ b/variants/promicro/target.cpp @@ -12,7 +12,8 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -34,4 +35,3 @@ mesh::LocalIdentity radio_new_identity() { return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/rak3112/target.cpp b/variants/rak3112/target.cpp index 9df1bf8f..9b1d11a0 100644 --- a/variants/rak3112/target.cpp +++ b/variants/rak3112/target.cpp @@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -43,4 +44,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/rak_wismesh_tag/target.cpp b/variants/rak_wismesh_tag/target.cpp index cdf81f4f..3e80ae63 100644 --- a/variants/rak_wismesh_tag/target.cpp +++ b/variants/rak_wismesh_tag/target.cpp @@ -22,7 +22,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -37,4 +38,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/sensecap_indicator-espnow/target.cpp b/variants/sensecap_indicator-espnow/target.cpp index c84d1883..4895447c 100644 --- a/variants/sensecap_indicator-espnow/target.cpp +++ b/variants/sensecap_indicator-espnow/target.cpp @@ -8,7 +8,8 @@ ESPNOWRadio radio_driver; ESP32RTCClock rtc_clock; #if defined(ENV_INCLUDE_GPS) -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, (mesh::RTCClock*)&rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, (mesh::RTCClock*)&rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); diff --git a/variants/sensecap_solar/target.cpp b/variants/sensecap_solar/target.cpp index 46641517..11586ecd 100644 --- a/variants/sensecap_solar/target.cpp +++ b/variants/sensecap_solar/target.cpp @@ -13,7 +13,8 @@ WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); @@ -29,4 +30,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/station_g2/target.cpp b/variants/station_g2/target.cpp index 8018c20e..f5365eb5 100644 --- a/variants/station_g2/target.cpp +++ b/variants/station_g2/target.cpp @@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -44,4 +45,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/station_g3_esp32/target.cpp b/variants/station_g3_esp32/target.cpp index d3de074b..189169d2 100644 --- a/variants/station_g3_esp32/target.cpp +++ b/variants/station_g3_esp32/target.cpp @@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; diff --git a/variants/t1000-e/target.cpp b/variants/t1000-e/target.cpp index 0d7710b3..b96d01f8 100644 --- a/variants/t1000-e/target.cpp +++ b/variants/t1000-e/target.cpp @@ -82,13 +82,11 @@ mesh::LocalIdentity radio_new_identity() { } void T1000SensorManager::start_gps() { - gps_active = true; - _nmea->begin(); + _nmea->setGpsOn(true); } void T1000SensorManager::stop_gps() { - gps_active = false; - _nmea->stop(); + _nmea->setGpsOn(false); } @@ -115,7 +113,7 @@ void T1000SensorManager::loop() { _nmea->loop(); if (millis() > next_gps_update) { - if (gps_active && _nmea->isValid()) { + if (_nmea->isEnabled() && _nmea->isValid()) { node_lat = ((double)_nmea->getLatitude())/1000000.; node_lon = ((double)_nmea->getLongitude())/1000000.; node_altitude = ((double)_nmea->getAltitude()) / 1000.0; @@ -131,7 +129,7 @@ const char* T1000SensorManager::getSettingName(int i) const { } const char* T1000SensorManager::getSettingValue(int i) const { if (i == 0) { - return gps_active ? "1" : "0"; + return _nmea->isGpsOn() ? "1" : "0"; } return NULL; } diff --git a/variants/t1000-e/target.h b/variants/t1000-e/target.h index 4a1a2bb7..68508bcb 100644 --- a/variants/t1000-e/target.h +++ b/variants/t1000-e/target.h @@ -15,7 +15,6 @@ class AirohaGpsDriver; class T1000SensorManager: public SensorManager { - bool gps_active = false; LocationProvider * _nmea; AirohaGpsDriver* _gps_driver; diff --git a/variants/thinknode_m3/target.cpp b/variants/thinknode_m3/target.cpp index 1e6c2ad1..bb5746ca 100644 --- a/variants/thinknode_m3/target.cpp +++ b/variants/thinknode_m3/target.cpp @@ -11,7 +11,8 @@ WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); diff --git a/variants/thinknode_m4/target.cpp b/variants/thinknode_m4/target.cpp index 7da3f400..59a898f5 100644 --- a/variants/thinknode_m4/target.cpp +++ b/variants/thinknode_m4/target.cpp @@ -11,7 +11,8 @@ WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); diff --git a/variants/thinknode_m6/target.cpp b/variants/thinknode_m6/target.cpp index de167194..061f7ad4 100644 --- a/variants/thinknode_m6/target.cpp +++ b/variants/thinknode_m6/target.cpp @@ -12,7 +12,8 @@ WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); @@ -32,4 +33,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/thinknode_m7/target.cpp b/variants/thinknode_m7/target.cpp index f4b898d8..8e7e8a05 100644 --- a/variants/thinknode_m7/target.cpp +++ b/variants/thinknode_m7/target.cpp @@ -12,7 +12,8 @@ ESP32RTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); @@ -81,4 +82,3 @@ mesh::LocalIdentity radio_new_identity() { return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/thinknode_m8/target.cpp b/variants/thinknode_m8/target.cpp index 69f3cc52..04496d3f 100644 --- a/variants/thinknode_m8/target.cpp +++ b/variants/thinknode_m8/target.cpp @@ -13,7 +13,8 @@ WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); diff --git a/variants/thinknode_m9/target.cpp b/variants/thinknode_m9/target.cpp index 3cbd7d75..990f0388 100644 --- a/variants/thinknode_m9/target.cpp +++ b/variants/thinknode_m9/target.cpp @@ -11,7 +11,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS #include -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); diff --git a/variants/wio-tracker-l1-1w/target.cpp b/variants/wio-tracker-l1-1w/target.cpp index 7a573258..cd4b8dac 100644 --- a/variants/wio-tracker-l1-1w/target.cpp +++ b/variants/wio-tracker-l1-1w/target.cpp @@ -13,7 +13,8 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); @@ -37,4 +38,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/wio-tracker-l1/target.cpp b/variants/wio-tracker-l1/target.cpp index 7a573258..cd4b8dac 100644 --- a/variants/wio-tracker-l1/target.cpp +++ b/variants/wio-tracker-l1/target.cpp @@ -13,7 +13,8 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); @@ -37,4 +38,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/xiao_c3/target.cpp b/variants/xiao_c3/target.cpp index 7f30dc8b..d3bbdf1c 100644 --- a/variants/xiao_c3/target.cpp +++ b/variants/xiao_c3/target.cpp @@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); + NmeaGpsDriver gps_driver(Serial1); + MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors; @@ -39,4 +40,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - From e58be9ab11b8c7a22b08c19dbb78d7bc895a1cef Mon Sep 17 00:00:00 2001 From: Florent Date: Mon, 2 Nov 2026 12:45:05 -0400 Subject: [PATCH 58/79] gps: cache the last fix in LocationProvider (isValid vs hasValidFix), fix and status commands --- docs/cli_commands.md | 37 +++++++++++-- docs/companion_cli.md | 52 +++++++++++++++++++ src/helpers/CommonGpsPrefs.cpp | 48 ++++++++++++++--- src/helpers/sensors/LocationProvider.h | 21 +++++++- .../sensors/MicroNMEALocationProvider.h | 35 +++++++++---- src/helpers/sensors/RakLocationProvider.h | 48 ++++++++++++----- 6 files changed, 208 insertions(+), 33 deletions(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 9fde4d43..eb8c6b20 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -999,9 +999,16 @@ region save --- ### GPS (When GPS support is compiled in) -#### View or change GPS state +#### View GPS state **Usage:** - `gps` + +**Note:** Reports the requested state, receiver activity, last-fix status (last fix gives number of sats and how long ago was the fix), and mode. In periodic mode, `waiting` means the receiver is off between acquisitions; the last fix remains available. `off(hw)` means a hardware GPS switch is off. + +--- + +#### Change GPS state +**Usage:** - `gps ` **Parameters:** @@ -1009,9 +1016,25 @@ region save **Default:** `off` -**Note:** Output format: -- `off` when the GPS hardware is disabled -- `on, {active|deactivated}, {fix|no fix}, {sat count} sats` when the GPS hardware is enabled +--- + +#### View or change the GPS acquisition period +**Usage:** +- `gps period` +- `gps period ` + +**Parameters:** +- `seconds`: `0` for continuous tracking, or `1`-`86400` for periodic acquisition + +**Note:** A periodic acquisition stops after receiving a valid fix, then resumes after the configured period. + +--- + +#### View the last GPS fix +**Usage:** +- `gps fix` + +**Note:** Returns the last valid latitude, longitude, altitude, and elapsed time since the fix. Returns `no fix` until a valid fix is received. --- @@ -1021,6 +1044,12 @@ region save --- +#### View GPS diagnostics +**Usage:** +- `gps diag` + +--- + #### Set this node's location based on the GPS coordinates **Usage:** - `gps setloc` diff --git a/docs/companion_cli.md b/docs/companion_cli.md index 31a05584..24843269 100644 --- a/docs/companion_cli.md +++ b/docs/companion_cli.md @@ -7,6 +7,7 @@ Since version 1.18 meshcore companion radio firmware has a CLI interface, which - [Configuration](#configuration) - [System](#system) - [Radio](#radio) + - [GPS](#gps) - [BLE](#ble) - [Wifi](#wifi) - [UI](#ui) @@ -119,6 +120,57 @@ Radio parameters are common to all roles and handled by `CommonRadioPrefs`. --- +### GPS + +#### View GPS state +**Usage:** +- `gps` + +**Note:** Reports the requested state, receiver activity, last-fix status (last fix gives number of sats and how long ago was the fix), and mode. In periodic mode, `waiting` means the receiver is off between acquisitions; the last fix remains available. `off(hw)` means a hardware GPS switch is off. + +--- + +#### Change GPS state +**Usage:** +- `gps ` + +**Parameters:** +- `state`: `on`|`off` + +--- + +#### View or change the GPS acquisition period +**Usage:** +- `gps period` +- `gps period ` + +**Parameters:** +- `seconds`: `0` for continuous tracking, or `1`-`86400` for periodic acquisition + +**Note:** A periodic acquisition stops after receiving a valid fix, then resumes after the configured period. + +--- + +#### View the last GPS fix +**Usage:** +- `gps fix` + +**Note:** Returns the last valid latitude, longitude, altitude, and elapsed time since the fix. Returns `no fix` until a valid fix is received. + +--- + +#### Sync this node's clock with GPS time +**Usage:** +- `gps sync` + +--- + +#### View GPS diagnostics +**Usage:** +- `gps diag` + +--- + #### View or change this node's rx boosted gain mode (SX12xx and LR1110) **Usage:** - `get radio.rxgain` diff --git a/src/helpers/CommonGpsPrefs.cpp b/src/helpers/CommonGpsPrefs.cpp index fe29c0c0..248ae540 100644 --- a/src/helpers/CommonGpsPrefs.cpp +++ b/src/helpers/CommonGpsPrefs.cpp @@ -37,13 +37,49 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, } if (location == nullptr) { strcpy(reply, "gps provider not found"); - } else if (location->isEnabled()) { - sprintf(reply, "on, %s, %s, %d sats, mode: %s", - isGpsEnabled() ? "active" : "deactivated", - location->isValid() ? "fix" : "no fix", - location->satellitesCount(), mode); + } else if (location->isGpsOn()) { + const char* activity = "active"; + if (!location->isEnabled()) { + if (location->hasHardwareEnableState() && !location->isHardwareEnabled()) { + activity = "off(hw)"; + } else if (getGpsPeriod() > 0) { + activity = "waiting"; + } else { + activity = "inactive"; + } + } + char fix[32]; + if (location->hasValidFix()) { + snprintf(fix, sizeof(fix), "%ld sats %lus ago", + location->satellitesCount(), (unsigned long)location->getLastFixAge()); + } else { + strcpy(fix, "no fix"); + } + snprintf(reply, 160, "on, %s, %s, mode: %s", activity, fix, mode); + } + return true; + } + if (strcmp(command, "gps fix") == 0) { + LocationProvider* location = sensors.getLocationProvider(); + if (location == nullptr) { + strcpy(reply, "gps provider not found"); + } else if (!location->hasValidFix()) { + strcpy(reply, "no fix"); } else { - snprintf(reply, 160, "off, mode: %s", mode); + const long latitude = location->getLatitude(); + const long longitude = location->getLongitude(); + const uint32_t fixAge = location->getLastFixAge(); + char age[24]; + if (fixAge == UINT32_MAX) { + strcpy(age, "age unavailable"); + } else { + snprintf(age, sizeof(age), "%lus ago", (unsigned long)fixAge); + } + snprintf(reply, 160, "%s%ld.%06ld, %s%ld.%06ld, %ldm, %s", + latitude < 0 ? "-" : "", labs(latitude) / 1000000L, + labs(latitude) % 1000000L, + longitude < 0 ? "-" : "", labs(longitude) / 1000000L, + labs(longitude) % 1000000L, location->getAltitude() / 1000L, age); } return true; } diff --git a/src/helpers/sensors/LocationProvider.h b/src/helpers/sensors/LocationProvider.h index 93cecf5b..dc316e1d 100644 --- a/src/helpers/sensors/LocationProvider.h +++ b/src/helpers/sensors/LocationProvider.h @@ -6,9 +6,22 @@ class LocationProvider { +public: + // Last valid fix, always filled in one go so readers get a consistent snapshot. + struct LastFix { + bool valid = false; + long latitude = 0; + long longitude = 0; + long altitude = 0; + long satellites = 0; + long timestamp = 0; + unsigned long acquiredAt = 0; // millis() when the fix was stored + }; + protected: bool _time_sync_needed = true; bool _gpsOn = false; + LastFix _lastFix; public: virtual ~LocationProvider() = default; @@ -19,7 +32,9 @@ public: virtual long getLongitude() = 0; virtual long getAltitude() = 0; virtual long satellitesCount() = 0; - virtual bool isValid() = 0; + virtual bool isValid() = 0; // current fix is valid + virtual bool hasValidFix() { return getLastFix().valid || isValid(); } // a valid fix was obtained at some point + virtual LastFix getLastFix() const { return _lastFix; } // snapshot of the last valid fix virtual long getTimestamp() = 0; virtual void sendSentence(const char * sentence); virtual bool waitFor(const char* prefix, uint32_t timeout_ms) { return false; } @@ -28,6 +43,10 @@ public: virtual bool keepEnabledAfterDetection() const { return false; } virtual void setGpsPeriod(uint32_t seconds) { } virtual uint32_t getGpsPeriod() const { return 0; } + virtual uint32_t getLastFixAge() const { // in seconds, UINT32_MAX if never + const LastFix f = getLastFix(); + return f.valid ? (uint32_t)(millis() - f.acquiredAt) / 1000UL : UINT32_MAX; + } virtual bool hasHardwareEnableState() const { return false; } virtual bool isHardwareEnabled() const { return true; } virtual bool isGpsOn() const { return _gpsOn; } diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index 2e9ff9cc..cceffd8c 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -32,10 +32,8 @@ class MicroNMEALocationProvider : public LocationProvider { uint32_t _stop_calls = 0; unsigned long _last_uart_ms = 0; unsigned long _last_nmea_ms = 0; - unsigned long _last_fix_ms = 0; bool _uart_seen = false; bool _nmea_seen = false; - bool _fix_seen = false; static uint32_t ageMs(unsigned long timestamp) { return (uint32_t)(millis() - timestamp); @@ -64,6 +62,18 @@ class MicroNMEALocationProvider : public LocationProvider { _nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL; } + void saveFix() { + LastFix fix; + fix.latitude = nmea.getLatitude(); + fix.longitude = nmea.getLongitude(); + nmea.getAltitude(fix.altitude); + fix.satellites = nmea.getNumSatellites(); + fix.timestamp = getTimestamp(); + fix.acquiredAt = millis(); + fix.valid = true; + _lastFix = fix; + } + void updateTime() { if (!isValid()) time_valid = 0; @@ -161,17 +171,25 @@ public: LocationProvider::syncTime(); } - long getLatitude() override { return nmea.getLatitude(); } - long getLongitude() override { return nmea.getLongitude(); } + long getLatitude() override { + return nmea.isValid() ? nmea.getLatitude() : _lastFix.latitude; + } + long getLongitude() override { + return nmea.isValid() ? nmea.getLongitude() : _lastFix.longitude; + } long getAltitude() override { + if (!nmea.isValid()) return _lastFix.altitude; long alt = 0; nmea.getAltitude(alt); return alt; } - long satellitesCount() override { return nmea.getNumSatellites(); } + long satellitesCount() override { + return nmea.isValid() ? nmea.getNumSatellites() : _lastFix.satellites; + } bool isValid() override { return nmea.isValid(); } long getTimestamp() override { + if (!nmea.isValid()) return _lastFix.timestamp; DateTime dt(nmea.getYear(), nmea.getMonth(), nmea.getDay(), nmea.getHour(), nmea.getMinute(), nmea.getSecond()); return dt.unixtime(); @@ -228,10 +246,9 @@ public: _nmea_seen = true; const char* messageId = nmea.getMessageID(); - if (parsed && isValid() && + if (parsed && nmea.isValid() && (strcmp(messageId, "GGA") == 0 || strcmp(messageId, "RMC") == 0)) { - _last_fix_ms = millis(); - _fix_seen = true; + saveFix(); if (_acquiringPeriodically) finishPeriodicAcquisition(); } } else { @@ -256,7 +273,7 @@ public: char fix_age[11]; formatAge(uart_age, sizeof(uart_age), _uart_seen, _last_uart_ms); formatAge(nmea_age, sizeof(nmea_age), _nmea_seen, _last_nmea_ms); - formatAge(fix_age, sizeof(fix_age), _fix_seen, _last_fix_ms); + formatAge(fix_age, sizeof(fix_age), _lastFix.valid, _lastFix.acquiredAt); snprintf(out, out_size, "en:%u ub:%lu ua:%s ok:%lu bad:%lu na:%s sat:%ld fix:%u fa:%s bc:%lu sc:%lu", diff --git a/src/helpers/sensors/RakLocationProvider.h b/src/helpers/sensors/RakLocationProvider.h index c909b7c4..db0b957b 100644 --- a/src/helpers/sensors/RakLocationProvider.h +++ b/src/helpers/sensors/RakLocationProvider.h @@ -11,6 +11,18 @@ class RakLocationProvider : public LocationProvider { unsigned long _acquisitionStarted = 0; bool _acquiringPeriodically = false; + void saveRak12500Fix() { + LastFix fix; + fix.latitude = _driver.getLatitude(); + fix.longitude = _driver.getLongitude(); + fix.altitude = _driver.getAltitude(); + fix.satellites = _driver.getSatellites(); + fix.timestamp = _driver.getTimestamp(); + fix.acquiredAt = millis(); + fix.valid = true; + _lastFix = fix; + } + public: RakLocationProvider(RakGpsDriver& driver, mesh::RTCClock* clock = nullptr) : _driver(driver), _nmea(driver.nmeaDriver(), clock) {} @@ -21,27 +33,31 @@ public: } long getLatitude() override { - return _driver.usesRak12500() ? _driver.getLatitude() : _nmea.getLatitude(); + return _driver.usesRak12500() ? _lastFix.latitude : _nmea.getLatitude(); } long getLongitude() override { - return _driver.usesRak12500() ? _driver.getLongitude() : _nmea.getLongitude(); + return _driver.usesRak12500() ? _lastFix.longitude : _nmea.getLongitude(); } long getAltitude() override { - return _driver.usesRak12500() ? _driver.getAltitude() : _nmea.getAltitude(); + return _driver.usesRak12500() ? _lastFix.altitude : _nmea.getAltitude(); } long satellitesCount() override { - return _driver.usesRak12500() ? _driver.getSatellites() : _nmea.satellitesCount(); + return _driver.usesRak12500() ? _lastFix.satellites : _nmea.satellitesCount(); } bool isValid() override { return _driver.usesRak12500() ? _driver.hasFix() : _nmea.isValid(); } + LastFix getLastFix() const override { + return _driver.usesRak12500() ? _lastFix : _nmea.getLastFix(); + } + long getTimestamp() override { - return _driver.usesRak12500() ? _driver.getTimestamp() : _nmea.getTimestamp(); + return _driver.usesRak12500() ? _lastFix.timestamp : _nmea.getTimestamp(); } void sendSentence(const char* sentence) override { @@ -104,18 +120,24 @@ public: void loop() override { if (_driver.usesRak12500()) { - if (_gpsOn && _gpsPeriodSeconds > 0) { - if (!_acquiringPeriodically && - (long)(millis() - _nextAcquisition) >= 0) { - _driver.begin(); - _acquiringPeriodically = true; - _acquisitionStarted = millis(); + if (_gpsOn) { + if (_gpsPeriodSeconds > 0) { + if (!_acquiringPeriodically && + (long)(millis() - _nextAcquisition) >= 0) { + _driver.begin(); + _acquiringPeriodically = true; + _acquisitionStarted = millis(); + } } - if (_acquiringPeriodically && isValid()) { + + const bool hasCurrentFix = _driver.hasFix(); + if (hasCurrentFix) saveRak12500Fix(); + + if (_gpsPeriodSeconds > 0 && _acquiringPeriodically && hasCurrentFix) { _driver.stop(); _acquiringPeriodically = false; _nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL; - } else if (_acquiringPeriodically && + } else if (_gpsPeriodSeconds > 0 && _acquiringPeriodically && (uint32_t)(millis() - _acquisitionStarted) >= GPS_PERIODIC_ACQUISITION_TIMEOUT_MS) { _driver.stop(); From e9d197cf795d8414841e5f7586cc57b0b94dd16e Mon Sep 17 00:00:00 2001 From: Florent Date: Tue, 3 Nov 2026 15:52:59 -0400 Subject: [PATCH 59/79] gps: periodic acquisition rules (timeout, sats and settle time), isEnabled renamed isActive --- src/helpers/CommonGpsPrefs.cpp | 4 ++- src/helpers/sensors/AirohaGpsDriver.h | 2 +- .../sensors/EnvironmentSensorManager.cpp | 4 +-- src/helpers/sensors/GpsDriver.h | 2 +- src/helpers/sensors/LocationProvider.h | 4 +-- .../sensors/MicroNMEALocationProvider.h | 33 +++++++++++++++---- src/helpers/sensors/NmeaGpsDriver.h | 2 +- src/helpers/sensors/RakGpsDriver.h | 4 +-- src/helpers/sensors/RakLocationProvider.h | 11 +++++-- 9 files changed, 46 insertions(+), 20 deletions(-) diff --git a/src/helpers/CommonGpsPrefs.cpp b/src/helpers/CommonGpsPrefs.cpp index 248ae540..e08878a6 100644 --- a/src/helpers/CommonGpsPrefs.cpp +++ b/src/helpers/CommonGpsPrefs.cpp @@ -39,7 +39,7 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, strcpy(reply, "gps provider not found"); } else if (location->isGpsOn()) { const char* activity = "active"; - if (!location->isEnabled()) { + if (!location->isActive()) { if (location->hasHardwareEnableState() && !location->isHardwareEnabled()) { activity = "off(hw)"; } else if (getGpsPeriod() > 0) { @@ -56,6 +56,8 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, strcpy(fix, "no fix"); } snprintf(reply, 160, "on, %s, %s, mode: %s", activity, fix, mode); + } else { + snprintf(reply, 160, "off, mode: %s", mode); } return true; } diff --git a/src/helpers/sensors/AirohaGpsDriver.h b/src/helpers/sensors/AirohaGpsDriver.h index 36d5eb6b..cd94d419 100644 --- a/src/helpers/sensors/AirohaGpsDriver.h +++ b/src/helpers/sensors/AirohaGpsDriver.h @@ -77,7 +77,7 @@ public: NmeaGpsDriver::stop(); } - bool isEnabled() const override { + bool isActive() const override { return digitalRead(GPS_EN) == HIGH; } }; diff --git a/src/helpers/sensors/EnvironmentSensorManager.cpp b/src/helpers/sensors/EnvironmentSensorManager.cpp index 2cf8b66b..ee942df1 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.cpp +++ b/src/helpers/sensors/EnvironmentSensorManager.cpp @@ -631,7 +631,7 @@ bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, Cayen next_available_channel = TELEM_CHANNEL_SELF + 1; #if ENV_INCLUDE_GPS - if (requester_permissions & TELEM_PERM_LOCATION && _location->isEnabled()) { + if (requester_permissions & TELEM_PERM_LOCATION && _location->isGpsOn()) { telemetry.addGPS(TELEM_CHANNEL_SELF, node_lat, node_lon, node_altitude); } #endif @@ -748,7 +748,7 @@ void EnvironmentSensorManager::loop() { _location->loop(); if ((long)(millis() - next_gps_update) > 0) { - if (_location->isEnabled() && _location->isValid()) { + if (_location->isGpsOn() && _location->hasValidFix()) { node_lat = ((double)_location->getLatitude())/1000000.; node_lon = ((double)_location->getLongitude())/1000000.; MESH_DEBUG_PRINTLN("lat %f lon %f", node_lat, node_lon); diff --git a/src/helpers/sensors/GpsDriver.h b/src/helpers/sensors/GpsDriver.h index b8cf4a5d..b17a6b27 100644 --- a/src/helpers/sensors/GpsDriver.h +++ b/src/helpers/sensors/GpsDriver.h @@ -9,7 +9,7 @@ public: virtual void begin() = 0; virtual void reset() = 0; virtual void stop() = 0; - virtual bool isEnabled() const = 0; + virtual bool isActive() const = 0; virtual bool hasHardwareEnableState() const { return false; } virtual bool isHardwareEnabled() const { return true; } // Returns true when the switch explicitly enables GPS in software. diff --git a/src/helpers/sensors/LocationProvider.h b/src/helpers/sensors/LocationProvider.h index dc316e1d..5bb6ec6a 100644 --- a/src/helpers/sensors/LocationProvider.h +++ b/src/helpers/sensors/LocationProvider.h @@ -63,14 +63,14 @@ public: virtual void begin() = 0; virtual void stop() = 0; virtual void loop() = 0; - virtual bool isEnabled() = 0; + virtual bool isActive() = 0; // Format compact diagnostics in the caller-provided buffer. Providers that // have more information (for example UART counters) can override this. virtual void formatDiagnostics(char* out, size_t out_size) { if (out_size == 0) return; snprintf(out, out_size, "en:%u sat:%ld fix:%u", - isEnabled() ? 1U : 0U, + isActive() ? 1U : 0U, satellitesCount(), isValid() ? 1U : 0U); } diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index cceffd8c..b07f486b 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -7,7 +7,16 @@ #include #ifndef GPS_PERIODIC_ACQUISITION_TIMEOUT_MS - #define GPS_PERIODIC_ACQUISITION_TIMEOUT_MS 120000UL + #define GPS_PERIODIC_ACQUISITION_TIMEOUT_MS 300000UL +#endif + +// in periodic mode, keep reading after the first valid fix until enough satellites +// are used or the settle time has elapsed +#ifndef GPS_MIN_SATS_FOR_FIX + #define GPS_MIN_SATS_FOR_FIX 5 +#endif +#ifndef GPS_FIX_SETTLE_MS + #define GPS_FIX_SETTLE_MS 10000UL #endif class MicroNMEALocationProvider : public LocationProvider { @@ -22,6 +31,7 @@ class MicroNMEALocationProvider : public LocationProvider { uint32_t _gpsPeriodSeconds = 0; unsigned long _nextAcquisition = 0; unsigned long _acquisitionStarted = 0; + unsigned long _firstFixInWindow = 0; bool _acquiringPeriodically = false; static const unsigned long TIME_SYNC_INTERVAL = 1800000; @@ -54,6 +64,7 @@ class MicroNMEALocationProvider : public LocationProvider { _driver->reset(); _acquiringPeriodically = true; _acquisitionStarted = millis(); + _firstFixInWindow = 0; } void finishPeriodicAcquisition() { @@ -122,11 +133,12 @@ public: void begin() override { _begin_calls++; _driver->begin(); - if (_gpsPeriodSeconds > 0 && _driver->isEnabled()) { + if (_gpsPeriodSeconds > 0 && _driver->isActive()) { nmea.clear(); time_valid = 0; _acquiringPeriodically = true; _acquisitionStarted = millis(); + _firstFixInWindow = 0; } } @@ -140,8 +152,8 @@ public: _driver->stop(); } - bool isEnabled() override { - return _driver->isEnabled(); + bool isActive() override { + return _driver->isActive(); } bool hasHardwareEnableState() const override { @@ -249,7 +261,13 @@ public: if (parsed && nmea.isValid() && (strcmp(messageId, "GGA") == 0 || strcmp(messageId, "RMC") == 0)) { saveFix(); - if (_acquiringPeriodically) finishPeriodicAcquisition(); + if (_acquiringPeriodically) { + if (_firstFixInWindow == 0) _firstFixInWindow = millis(); + if (nmea.getNumSatellites() >= GPS_MIN_SATS_FOR_FIX || + (uint32_t)(millis() - _firstFixInWindow) >= GPS_FIX_SETTLE_MS) { + finishPeriodicAcquisition(); + } + } } } else { _nmea_checksum_bad++; @@ -257,7 +275,8 @@ public: } } - if (_acquiringPeriodically && + // no timeout until a first fix has been obtained (cold start can be long) + if (_acquiringPeriodically && _lastFix.valid && (uint32_t)(millis() - _acquisitionStarted) >= GPS_PERIODIC_ACQUISITION_TIMEOUT_MS) { finishPeriodicAcquisition(); } @@ -277,7 +296,7 @@ public: snprintf(out, out_size, "en:%u ub:%lu ua:%s ok:%lu bad:%lu na:%s sat:%ld fix:%u fa:%s bc:%lu sc:%lu", - isEnabled() ? 1U : 0U, + isActive() ? 1U : 0U, (unsigned long)_uart_bytes, uart_age, (unsigned long)_nmea_checksum_ok, diff --git a/src/helpers/sensors/NmeaGpsDriver.h b/src/helpers/sensors/NmeaGpsDriver.h index f9ea5124..abecb817 100644 --- a/src/helpers/sensors/NmeaGpsDriver.h +++ b/src/helpers/sensors/NmeaGpsDriver.h @@ -183,7 +183,7 @@ public: stopHardware(); } - bool isEnabled() const override { + bool isActive() const override { return _started && isHardwareEnabled(); } diff --git a/src/helpers/sensors/RakGpsDriver.h b/src/helpers/sensors/RakGpsDriver.h index fb4b772b..b3754852 100644 --- a/src/helpers/sensors/RakGpsDriver.h +++ b/src/helpers/sensors/RakGpsDriver.h @@ -77,8 +77,8 @@ public: _serialDriver.stop(); } - bool isEnabled() const override { - return _usingRak12500 ? true : _serialDriver.isEnabled(); + bool isActive() const override { + return _usingRak12500 ? true : _serialDriver.isActive(); } bool detect(uint32_t) override { diff --git a/src/helpers/sensors/RakLocationProvider.h b/src/helpers/sensors/RakLocationProvider.h index db0b957b..57ceb5e9 100644 --- a/src/helpers/sensors/RakLocationProvider.h +++ b/src/helpers/sensors/RakLocationProvider.h @@ -137,7 +137,7 @@ public: _driver.stop(); _acquiringPeriodically = false; _nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL; - } else if (_gpsPeriodSeconds > 0 && _acquiringPeriodically && + } else if (_gpsPeriodSeconds > 0 && _acquiringPeriodically && _lastFix.valid && (uint32_t)(millis() - _acquisitionStarted) >= GPS_PERIODIC_ACQUISITION_TIMEOUT_MS) { _driver.stop(); @@ -150,8 +150,8 @@ public: } } - bool isEnabled() override { - return _driver.isEnabled(); + bool isActive() override { + return _driver.isActive(); } void setGpsPeriod(uint32_t seconds) override { @@ -163,4 +163,9 @@ public: uint32_t getGpsPeriod() const override { return _gpsPeriodSeconds; } + + void setGpsOn(bool on) override { + if (_driver.usesRak12500()) LocationProvider::setGpsOn(on); + else { _gpsOn = on; _nmea.setGpsOn(on); } + } }; From a0c5854b591ccef21061009c05932aa334722978 Mon Sep 17 00:00:00 2001 From: Florent Date: Tue, 3 Nov 2026 21:10:01 -0400 Subject: [PATCH 60/79] rak_gps: simplify the rak driver, which now only handles i2c, for nmea use nmea driver directly --- .../{RakGpsDriver.h => RakI2cGpsDriver.h} | 50 +++++--------- src/helpers/sensors/RakLocationProvider.h | 67 ++++++++++++------- variants/gat562_30s_mesh_kit/target.cpp | 2 +- variants/rak3401/target.cpp | 2 +- variants/rak4631/target.cpp | 2 +- 5 files changed, 61 insertions(+), 62 deletions(-) rename src/helpers/sensors/{RakGpsDriver.h => RakI2cGpsDriver.h} (65%) diff --git a/src/helpers/sensors/RakGpsDriver.h b/src/helpers/sensors/RakI2cGpsDriver.h similarity index 65% rename from src/helpers/sensors/RakGpsDriver.h rename to src/helpers/sensors/RakI2cGpsDriver.h index b3754852..ac76e069 100644 --- a/src/helpers/sensors/RakGpsDriver.h +++ b/src/helpers/sensors/RakI2cGpsDriver.h @@ -1,16 +1,16 @@ #pragma once -#include "NmeaGpsDriver.h" +#include "GpsDriver.h" #include -class RakGpsDriver : public GpsDriver { - NmeaGpsDriver _serialDriver; +// Driver for the RAK12500 (u-blox, I2C). Serial NMEA modules are handled by NmeaGpsDriver. +class RakI2cGpsDriver : public GpsDriver { TwoWire& _wire; SFE_UBLOX_GNSS _gnss; uint8_t _powerPin = 0; - bool _usingRak12500 = false; bool _detected = false; + bool _started = false; bool probeRak12500(uint8_t powerPin) { #if defined(ETHERNET_ENABLED) && defined(RAK_BOARD) @@ -37,7 +37,6 @@ class RakGpsDriver : public GpsDriver { _gnss.setMeasurementRate(1000); _gnss.saveConfigSelective(VAL_CFG_SUBSEC_IOPORT); _powerPin = powerPin; - _usingRak12500 = true; return true; } @@ -48,62 +47,47 @@ class RakGpsDriver : public GpsDriver { } public: - RakGpsDriver(HardwareSerial& serial = Serial1, TwoWire& wire = Wire) - : _serialDriver(serial), _wire(wire) {} + RakI2cGpsDriver(TwoWire& wire = Wire) : _wire(wire) {} void begin() override { - if (_usingRak12500) { + if (!_detected) return; #ifndef RAK_3401 - pinMode(_powerPin, OUTPUT); - digitalWrite(_powerPin, HIGH); + pinMode(_powerPin, OUTPUT); + digitalWrite(_powerPin, HIGH); #endif - return; - } - _serialDriver.begin(); + _started = true; } - void reset() override { - if (!_usingRak12500) _serialDriver.reset(); - } + void reset() override {} void stop() override { - if (_usingRak12500) { + if (_detected) { #ifndef RAK_3401 pinMode(_powerPin, OUTPUT); digitalWrite(_powerPin, LOW); #endif - return; } - _serialDriver.stop(); + _started = false; } bool isActive() const override { - return _usingRak12500 ? true : _serialDriver.isActive(); + return _started; } + // Probes the I2C module on the possible power pins; the module is left powered. bool detect(uint32_t) override { if (_detected) return true; - _serialDriver.begin(); if (probeRak12500(WB_IO2) || probeRak12500(WB_IO4) || probeRak12500(WB_IO5)) { _detected = true; - return true; + _started = true; } - - if (_serialDriver.detect(0)) { - _detected = true; - return true; - } - - _serialDriver.stop(); - return false; + return _detected; } - bool usesRak12500() const { return _usingRak12500; } bool isDetected() const { return _detected; } - NmeaGpsDriver& nmeaDriver() { return _serialDriver; } - bool hasFix() { return _usingRak12500 && _gnss.getGnssFixOk(8); } + bool hasFix() { return _started && _gnss.getGnssFixOk(8); } long getLatitude() { return _gnss.getLatitude(2) / 10; } long getLongitude() { return _gnss.getLongitude(2) / 10; } long getAltitude() { return _gnss.getAltitude(2); } diff --git a/src/helpers/sensors/RakLocationProvider.h b/src/helpers/sensors/RakLocationProvider.h index 57ceb5e9..d2c755e6 100644 --- a/src/helpers/sensors/RakLocationProvider.h +++ b/src/helpers/sensors/RakLocationProvider.h @@ -1,11 +1,15 @@ #pragma once #include "MicroNMEALocationProvider.h" -#include "RakGpsDriver.h" +#include "NmeaGpsDriver.h" +#include "RakI2cGpsDriver.h" class RakLocationProvider : public LocationProvider { - RakGpsDriver& _driver; + RakI2cGpsDriver& _driver; // RAK12500 (I2C) + NmeaGpsDriver _nmeaDriver; // serial NMEA module MicroNMEALocationProvider _nmea; + bool _detected = false; + bool _useI2c = false; uint32_t _gpsPeriodSeconds = 0; unsigned long _nextAcquisition = 0; unsigned long _acquisitionStarted = 0; @@ -24,73 +28,74 @@ class RakLocationProvider : public LocationProvider { } public: - RakLocationProvider(RakGpsDriver& driver, mesh::RTCClock* clock = nullptr) - : _driver(driver), _nmea(driver.nmeaDriver(), clock) {} + RakLocationProvider(RakI2cGpsDriver& driver, mesh::RTCClock* clock = nullptr, + HardwareSerial& serial = Serial1) + : _driver(driver), _nmeaDriver(serial), _nmea(_nmeaDriver, clock) {} void syncTime() override { LocationProvider::syncTime(); - if (!_driver.usesRak12500()) _nmea.syncTime(); + if (!_useI2c) _nmea.syncTime(); } long getLatitude() override { - return _driver.usesRak12500() ? _lastFix.latitude : _nmea.getLatitude(); + return _useI2c ? _lastFix.latitude : _nmea.getLatitude(); } long getLongitude() override { - return _driver.usesRak12500() ? _lastFix.longitude : _nmea.getLongitude(); + return _useI2c ? _lastFix.longitude : _nmea.getLongitude(); } long getAltitude() override { - return _driver.usesRak12500() ? _lastFix.altitude : _nmea.getAltitude(); + return _useI2c ? _lastFix.altitude : _nmea.getAltitude(); } long satellitesCount() override { - return _driver.usesRak12500() ? _lastFix.satellites : _nmea.satellitesCount(); + return _useI2c ? _lastFix.satellites : _nmea.satellitesCount(); } bool isValid() override { - return _driver.usesRak12500() ? _driver.hasFix() : _nmea.isValid(); + return _useI2c ? _driver.hasFix() : _nmea.isValid(); } LastFix getLastFix() const override { - return _driver.usesRak12500() ? _lastFix : _nmea.getLastFix(); + return _useI2c ? _lastFix : _nmea.getLastFix(); } long getTimestamp() override { - return _driver.usesRak12500() ? _lastFix.timestamp : _nmea.getTimestamp(); + return _useI2c ? _lastFix.timestamp : _nmea.getTimestamp(); } void sendSentence(const char* sentence) override { - if (!_driver.usesRak12500()) _nmea.sendSentence(sentence); + if (!_useI2c) _nmea.sendSentence(sentence); } bool waitFor(const char* prefix, uint32_t timeout_ms) override { - return _driver.usesRak12500() ? false : _nmea.waitFor(prefix, timeout_ms); + return _useI2c ? false : _nmea.waitFor(prefix, timeout_ms); } void drain() override { - if (!_driver.usesRak12500()) _nmea.drain(); + if (!_useI2c) _nmea.drain(); } void reset() override { - _driver.reset(); + if (!_useI2c) _nmea.reset(); } void begin() override { - if (_driver.isDetected() && _driver.usesRak12500()) { + if (_detected && _useI2c) { _driver.begin(); _acquiringPeriodically = _gpsPeriodSeconds > 0; _acquisitionStarted = millis(); - } else if (_driver.isDetected()) { + } else if (_detected) { _nmea.begin(); } else { - _driver.begin(); + _nmeaDriver.begin(); } } void stop() override { _acquiringPeriodically = false; - if (_driver.usesRak12500()) { + if (_useI2c) { _driver.stop(); } else { _nmea.stop(); @@ -98,9 +103,19 @@ public: } bool detect(uint32_t timeout_ms) override { - if (!_driver.detect(timeout_ms)) return false; + if (_detected) return true; - if (_driver.usesRak12500()) { + // the serial module is started first, then the I2C module is probed + _nmeaDriver.begin(); + if (_driver.detect(timeout_ms)) { + _useI2c = true; + } else if (!_nmeaDriver.detect(0)) { + _nmeaDriver.stop(); + return false; + } + _detected = true; + + if (_useI2c) { _acquiringPeriodically = _gpsPeriodSeconds > 0; _acquisitionStarted = millis(); } else { @@ -119,7 +134,7 @@ public: } void loop() override { - if (_driver.usesRak12500()) { + if (_useI2c) { if (_gpsOn) { if (_gpsPeriodSeconds > 0) { if (!_acquiringPeriodically && @@ -151,13 +166,13 @@ public: } bool isActive() override { - return _driver.isActive(); + return _useI2c ? _driver.isActive() : _nmea.isActive(); } void setGpsPeriod(uint32_t seconds) override { _gpsPeriodSeconds = seconds; _nextAcquisition = millis(); - if (!_driver.usesRak12500()) _nmea.setGpsPeriod(seconds); + if (!_useI2c) _nmea.setGpsPeriod(seconds); } uint32_t getGpsPeriod() const override { @@ -165,7 +180,7 @@ public: } void setGpsOn(bool on) override { - if (_driver.usesRak12500()) LocationProvider::setGpsOn(on); + if (_useI2c) LocationProvider::setGpsOn(on); else { _gpsOn = on; _nmea.setGpsOn(on); } } }; diff --git a/variants/gat562_30s_mesh_kit/target.cpp b/variants/gat562_30s_mesh_kit/target.cpp index ba81a690..96e38a79 100644 --- a/variants/gat562_30s_mesh_kit/target.cpp +++ b/variants/gat562_30s_mesh_kit/target.cpp @@ -27,7 +27,7 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - RakGpsDriver gps_driver; + RakI2cGpsDriver gps_driver; RakLocationProvider location(gps_driver, &rtc_clock); EnvironmentSensorManager sensors(location); #else diff --git a/variants/rak3401/target.cpp b/variants/rak3401/target.cpp index 26501977..58c0e1d7 100644 --- a/variants/rak3401/target.cpp +++ b/variants/rak3401/target.cpp @@ -26,7 +26,7 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - RakGpsDriver gps_driver; + RakI2cGpsDriver gps_driver; RakLocationProvider location(gps_driver, &rtc_clock); EnvironmentSensorManager sensors(location); #else diff --git a/variants/rak4631/target.cpp b/variants/rak4631/target.cpp index 06ccd23d..158de2b5 100644 --- a/variants/rak4631/target.cpp +++ b/variants/rak4631/target.cpp @@ -26,7 +26,7 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - RakGpsDriver gps_driver; + RakI2cGpsDriver gps_driver; RakLocationProvider location(gps_driver, &rtc_clock); EnvironmentSensorManager sensors(location); #else From 53037037507c64c72b02c74d75a85a2219166f0b Mon Sep 17 00:00:00 2001 From: Florent Date: Tue, 3 Nov 2026 21:29:21 -0400 Subject: [PATCH 61/79] gps: adapt ui-new and the sensor managers --- examples/companion_radio/ui-new/UITask.cpp | 51 ++++++++++++++++--- variants/heltec_mesh_solar/target.cpp | 2 +- variants/heltec_tracker/target.cpp | 2 +- variants/meshadventurer/target.cpp | 4 +- variants/meshtracker_x1/target.cpp | 2 +- variants/nano_g2_ultra/NanoG2UltraGpsDriver.h | 2 +- variants/nano_g2_ultra/target.cpp | 4 +- variants/t1000-e/target.cpp | 2 +- variants/thinknode_m1/target.cpp | 2 +- 9 files changed, 53 insertions(+), 18 deletions(-) diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index a1400669..6b6af33e 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -86,6 +86,30 @@ public: } }; +#if ENV_INCLUDE_GPS == 1 +// exact period with the largest unit that divides it: "30s", "5m", "2h" +static void formatGpsPeriod(char* buf, size_t size, uint32_t seconds) { + if (seconds % 3600 == 0) { + snprintf(buf, size, "%luh", (unsigned long)(seconds / 3600)); + } else if (seconds % 60 == 0) { + snprintf(buf, size, "%lum", (unsigned long)(seconds / 60)); + } else { + snprintf(buf, size, "%lus", (unsigned long)seconds); + } +} + +// age of the last fix, rounded down to a single unit: "45s", "12m", "3h" +static void formatFixAge(char* buf, size_t size, uint32_t seconds) { + if (seconds < 60) { + snprintf(buf, size, "%lus", (unsigned long)seconds); + } else if (seconds < 3600) { + snprintf(buf, size, "%lum", (unsigned long)(seconds / 60)); + } else { + snprintf(buf, size, "%luh", (unsigned long)(seconds / 3600)); + } +} +#endif + class HomeScreen : public UIScreen { enum HomePage { FIRST, @@ -393,14 +417,26 @@ public: int y = 18; bool gps_state = _task->getGPSState(); bool hw_gps_state = nmea != NULL && nmea->isHardwareEnabled(); - if (nmea != NULL && nmea->hasHardwareEnableState()) { - if (gps_state != hw_gps_state) { - strcpy(buf, gps_state ? "gps off(hw)" : "gps off(sw)"); - } else { - strcpy(buf, gps_state ? "gps on" : "gps off"); + uint32_t period = nmea != NULL ? nmea->getGpsPeriod() : 0; + char fix_buf[12] = ""; + if (nmea != NULL) { + uint32_t fix_age = nmea->getLastFixAge(); + if (fix_age == UINT32_MAX) { + strcpy(fix_buf, "no fix"); + } else { + formatFixAge(fix_buf, sizeof(fix_buf), fix_age); + } } + if (nmea != NULL && nmea->hasHardwareEnableState() && gps_state != hw_gps_state) { + strcpy(buf, gps_state ? "gps off(hw)" : "gps off(sw)"); + } else if (!gps_state) { + strcpy(buf, "gps off"); + } else if (period == 0) { + strcpy(buf, "gps on"); } else { - strcpy(buf, gps_state ? "gps on" : "gps off"); + char per[12]; + formatGpsPeriod(per, sizeof(per), period); + snprintf(buf, sizeof(buf), "%s (%s)", nmea != NULL && nmea->isActive() ? "active" : "sleep", per); } display.setColor(UIColor::primary_txt); display.drawTextLeftAlign(0, y, buf); @@ -410,8 +446,7 @@ public: display.drawTextLeftAlign(0, y, "Can't access GPS"); } else { display.setColor(UIColor::primary_txt); - strcpy(buf, nmea->isValid()?"fix":"no fix"); - display.drawTextRightAlign(display.width()-1, y, buf); + display.drawTextRightAlign(display.width()-1, y, fix_buf); y = y + 12; display.setColor(UIColor::secondary_txt); display.drawTextLeftAlign(0, y, "sat"); diff --git a/variants/heltec_mesh_solar/target.cpp b/variants/heltec_mesh_solar/target.cpp index 9468f8fc..9e7fb04d 100644 --- a/variants/heltec_mesh_solar/target.cpp +++ b/variants/heltec_mesh_solar/target.cpp @@ -66,7 +66,7 @@ void SolarSensorManager::loop() { _location->loop(); if (millis() > next_gps_update) { - if (_location->isValid()) { + if (_location->isGpsOn() && _location->hasValidFix()) { node_lat = ((double)_location->getLatitude())/1000000.; node_lon = ((double)_location->getLongitude())/1000000.; node_altitude = ((double)_location->getAltitude()) / 1000.0; diff --git a/variants/heltec_tracker/target.cpp b/variants/heltec_tracker/target.cpp index 5903f659..041cb2b8 100644 --- a/variants/heltec_tracker/target.cpp +++ b/variants/heltec_tracker/target.cpp @@ -82,7 +82,7 @@ void HWTSensorManager::loop() { _location->loop(); if (millis() > next_gps_update) { - if (_location->isEnabled() && _location->isValid()) { + if (_location->isGpsOn() && _location->hasValidFix()) { node_lat = ((double)_location->getLatitude())/1000000.; node_lon = ((double)_location->getLongitude())/1000000.; node_altitude = ((double)_location->getAltitude()) / 1000.0; diff --git a/variants/meshadventurer/target.cpp b/variants/meshadventurer/target.cpp index faf2e30e..827e23b7 100644 --- a/variants/meshadventurer/target.cpp +++ b/variants/meshadventurer/target.cpp @@ -64,8 +64,8 @@ bool MASensorManager::querySensors(uint8_t requester_permissions, CayenneLPP& te void MASensorManager::loop() { static long next_gps_update = 0; _location->loop(); - if(millis() > next_gps_update && _location->isEnabled()) { - if(_location->isValid()) { + if(millis() > next_gps_update && _location->isGpsOn()) { + if(_location->hasValidFix()) { node_lat = ((double)_location->getLatitude()) / 1000000.; node_lon = ((double)_location->getLongitude()) / 1000000.; node_altitude = ((double)_location->getAltitude()) / 1000.0; diff --git a/variants/meshtracker_x1/target.cpp b/variants/meshtracker_x1/target.cpp index 2dee0ebd..84e0870e 100644 --- a/variants/meshtracker_x1/target.cpp +++ b/variants/meshtracker_x1/target.cpp @@ -70,7 +70,7 @@ void MeshTrackerX1SensorManager::loop() { _nmea->loop(); if (millis() > next_gps_update) { - if (_nmea->isEnabled() && _nmea->isValid()) { + if (_nmea->isGpsOn() && _nmea->hasValidFix()) { node_lat = ((double)_nmea->getLatitude())/1000000.; node_lon = ((double)_nmea->getLongitude())/1000000.; node_altitude = ((double)_nmea->getAltitude()) / 1000.0; diff --git a/variants/nano_g2_ultra/NanoG2UltraGpsDriver.h b/variants/nano_g2_ultra/NanoG2UltraGpsDriver.h index 3772084b..7e3bd109 100644 --- a/variants/nano_g2_ultra/NanoG2UltraGpsDriver.h +++ b/variants/nano_g2_ultra/NanoG2UltraGpsDriver.h @@ -10,7 +10,7 @@ public: } void begin() override { - if (isEnabled()) return; + if (isActive()) return; digitalWrite(PIN_GPS_STANDBY, HIGH); NmeaGpsDriver::begin(); diff --git a/variants/nano_g2_ultra/target.cpp b/variants/nano_g2_ultra/target.cpp index ee258f2d..fedc48e7 100644 --- a/variants/nano_g2_ultra/target.cpp +++ b/variants/nano_g2_ultra/target.cpp @@ -62,14 +62,14 @@ bool NanoG2UltraSensorManager::querySensors(uint8_t requester_permissions, Cayen void NanoG2UltraSensorManager::loop() { static long next_gps_update = 0; - if (!_location->isEnabled()) { + if (!_location->isGpsOn()) { return; // GPS is not active, skip further processing } _location->loop(); if (millis() > next_gps_update) { - if (_location->isEnabled() && _location->isValid()) { + if (_location->isGpsOn() && _location->hasValidFix()) { node_lat = ((double)_location->getLatitude()) / 1000000.; node_lon = ((double)_location->getLongitude()) / 1000000.; node_altitude = ((double)_location->getAltitude()) / 1000.0; diff --git a/variants/t1000-e/target.cpp b/variants/t1000-e/target.cpp index b96d01f8..609c32bc 100644 --- a/variants/t1000-e/target.cpp +++ b/variants/t1000-e/target.cpp @@ -113,7 +113,7 @@ void T1000SensorManager::loop() { _nmea->loop(); if (millis() > next_gps_update) { - if (_nmea->isEnabled() && _nmea->isValid()) { + if (_nmea->isGpsOn() && _nmea->hasValidFix()) { node_lat = ((double)_nmea->getLatitude())/1000000.; node_lon = ((double)_nmea->getLongitude())/1000000.; node_altitude = ((double)_nmea->getAltitude()) / 1000.0; diff --git a/variants/thinknode_m1/target.cpp b/variants/thinknode_m1/target.cpp index 78f5a88e..4183c514 100644 --- a/variants/thinknode_m1/target.cpp +++ b/variants/thinknode_m1/target.cpp @@ -58,7 +58,7 @@ void ThinkNodeM1SensorManager::loop() { _location->loop(); if (millis() > next_gps_update) { - if (_location->isEnabled() && _location->isValid()) { + if (_location->isGpsOn() && _location->hasValidFix()) { node_lat = ((double)_location->getLatitude())/1000000.; node_lon = ((double)_location->getLongitude())/1000000.; node_altitude = ((double)_location->getAltitude()) / 1000.0; From 47959b8960701209bf5012f77c43444eb93f9821 Mon Sep 17 00:00:00 2001 From: Florent Date: Wed, 4 Nov 2026 09:02:38 -0400 Subject: [PATCH 62/79] gps: fix_stats command --- docs/cli_commands.md | 8 +++++ docs/companion_cli.md | 8 +++++ src/helpers/CommonGpsPrefs.cpp | 32 +++++++++++++++-- src/helpers/sensors/LocationProvider.h | 20 +++++++++++ .../sensors/MicroNMEALocationProvider.h | 35 ++++++++++++++----- src/helpers/sensors/RakLocationProvider.h | 13 ++++++- 6 files changed, 105 insertions(+), 11 deletions(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index eb8c6b20..d7b8d5d0 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1044,6 +1044,14 @@ region save --- +#### View GPS time to first fix statistics +**Usage:** +- `gps fix_stats` + +**Output:** `ttf:/ ok: miss:`: last and maximum time between a start of the GPS and its first valid fix, then the last count of consecutive starts with a fix (`ok`) or without one (`miss`). + +--- + #### View GPS diagnostics **Usage:** - `gps diag` diff --git a/docs/companion_cli.md b/docs/companion_cli.md index 24843269..0b3a27df 100644 --- a/docs/companion_cli.md +++ b/docs/companion_cli.md @@ -165,6 +165,14 @@ Radio parameters are common to all roles and handled by `CommonRadioPrefs`. --- +#### View GPS time to first fix statistics +**Usage:** +- `gps fix_stats` + +**Output:** `ttf:/ ok: miss:`: last and maximum time between a start of the GPS and its first valid fix, then the last count of consecutive starts with a fix (`ok`) or without one (`miss`). + +--- + #### View GPS diagnostics **Usage:** - `gps diag` diff --git a/src/helpers/CommonGpsPrefs.cpp b/src/helpers/CommonGpsPrefs.cpp index e08878a6..c4936d4f 100644 --- a/src/helpers/CommonGpsPrefs.cpp +++ b/src/helpers/CommonGpsPrefs.cpp @@ -25,6 +25,17 @@ bool CommonGpsPrefs::apply(SensorManager& sensors) const { return true; } +// single unit, rounded down: "45s", "12m", "3h" +static void formatDuration(char* buf, size_t size, uint32_t seconds) { + if (seconds < 60) { + snprintf(buf, size, "%lus", (unsigned long)seconds); + } else if (seconds < 3600) { + snprintf(buf, size, "%lum", (unsigned long)(seconds / 60)); + } else { + snprintf(buf, size, "%luh", (unsigned long)(seconds / 3600)); + } +} + bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, char* reply) { if (strcmp(command, "gps") == 0) { LocationProvider* location = sensors.getLocationProvider(); @@ -50,8 +61,9 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, } char fix[32]; if (location->hasValidFix()) { - snprintf(fix, sizeof(fix), "%ld sats %lus ago", - location->satellitesCount(), (unsigned long)location->getLastFixAge()); + char age[12]; + formatDuration(age, sizeof(age), location->getLastFixAge()); + snprintf(fix, sizeof(fix), "%ld sats %s ago", location->satellitesCount(), age); } else { strcpy(fix, "no fix"); } @@ -134,6 +146,22 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, } return true; } + if (strcmp(command, "gps fix_stats") == 0) { + LocationProvider* location = sensors.getLocationProvider(); + if (location == nullptr) { + strcpy(reply, "gps provider not found"); + } else { + const LocationProvider::FixStats s = location->getFixStats(); + char last[12] = "-", max[12] = "-"; + if (s.maxTtffMs > 0) { + formatDuration(last, sizeof(last), (s.lastTtffMs + 500) / 1000); + formatDuration(max, sizeof(max), (s.maxTtffMs + 500) / 1000); + } + snprintf(reply, 160, "ttf:%s/%s ok:%lu miss:%lu", last, max, + (unsigned long)s.consecutiveFixes, (unsigned long)s.consecutiveMisses); + } + return true; + } if (strcmp(command, "gps diag") == 0) { LocationProvider* location = sensors.getLocationProvider(); if (location == nullptr) { diff --git a/src/helpers/sensors/LocationProvider.h b/src/helpers/sensors/LocationProvider.h index 5bb6ec6a..3d7abd7a 100644 --- a/src/helpers/sensors/LocationProvider.h +++ b/src/helpers/sensors/LocationProvider.h @@ -18,10 +18,29 @@ public: unsigned long acquiredAt = 0; // millis() when the fix was stored }; + struct FixStats { + uint32_t lastTtffMs = 0; //time to first fix in ms + uint32_t maxTtffMs = 0; + uint32_t consecutiveFixes = 0; + uint32_t consecutiveMisses = 0; + }; + protected: bool _time_sync_needed = true; bool _gpsOn = false; LastFix _lastFix; + FixStats _fixStats; + + void fixStatsFix(uint32_t ttffMs) { + _fixStats.lastTtffMs = ttffMs; + if (ttffMs > _fixStats.maxTtffMs) _fixStats.maxTtffMs = ttffMs; + _fixStats.consecutiveFixes++; + _fixStats.consecutiveMisses = 0; + } + void fixStatsMiss() { + _fixStats.consecutiveMisses++; + _fixStats.consecutiveFixes = 0; + } public: virtual ~LocationProvider() = default; @@ -35,6 +54,7 @@ public: virtual bool isValid() = 0; // current fix is valid virtual bool hasValidFix() { return getLastFix().valid || isValid(); } // a valid fix was obtained at some point virtual LastFix getLastFix() const { return _lastFix; } // snapshot of the last valid fix + virtual FixStats getFixStats() const { return _fixStats; } virtual long getTimestamp() = 0; virtual void sendSentence(const char * sentence); virtual bool waitFor(const char* prefix, uint32_t timeout_ms) { return false; } diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index b07f486b..3c2adc6e 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -68,21 +68,30 @@ class MicroNMEALocationProvider : public LocationProvider { } void finishPeriodicAcquisition() { + if (_firstFixInWindow == 0) fixStatsMiss(); _driver->stop(); _acquiringPeriodically = false; _nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL; } - void saveFix() { + bool saveFix() { + // only store a fix when the snapshot is coherent (sats > 0). + // Returns true if the fix was stored. + if (nmea.getNumSatellites() == 0) return false; + LastFix fix; fix.latitude = nmea.getLatitude(); fix.longitude = nmea.getLongitude(); - nmea.getAltitude(fix.altitude); + // altitude comes from GGA only: keep the previous one if not available + if (!nmea.getAltitude(fix.altitude)) { + fix.altitude = _lastFix.valid ? _lastFix.altitude : 0; + } fix.satellites = nmea.getNumSatellites(); fix.timestamp = getTimestamp(); fix.acquiredAt = millis(); fix.valid = true; _lastFix = fix; + return true; } void updateTime() { @@ -132,7 +141,12 @@ public: void begin() override { _begin_calls++; + const bool wasActive = _driver->isActive(); _driver->begin(); + if (!wasActive) { + _acquisitionStarted = millis(); + _firstFixInWindow = 0; + } if (_gpsPeriodSeconds > 0 && _driver->isActive()) { nmea.clear(); time_valid = 0; @@ -183,20 +197,22 @@ public: LocationProvider::syncTime(); } + // Position, altitude and satellite count describe the last saved fix + // Before the first saved fix, fall back to the live parser state. long getLatitude() override { - return nmea.isValid() ? nmea.getLatitude() : _lastFix.latitude; + return _lastFix.valid ? _lastFix.latitude : nmea.getLatitude(); } long getLongitude() override { - return nmea.isValid() ? nmea.getLongitude() : _lastFix.longitude; + return _lastFix.valid ? _lastFix.longitude : nmea.getLongitude(); } long getAltitude() override { - if (!nmea.isValid()) return _lastFix.altitude; + if (_lastFix.valid) return _lastFix.altitude; long alt = 0; nmea.getAltitude(alt); return alt; } long satellitesCount() override { - return nmea.isValid() ? nmea.getNumSatellites() : _lastFix.satellites; + return _lastFix.valid ? _lastFix.satellites : nmea.getNumSatellites(); } bool isValid() override { return nmea.isValid(); } @@ -260,9 +276,12 @@ public: const char* messageId = nmea.getMessageID(); if (parsed && nmea.isValid() && (strcmp(messageId, "GGA") == 0 || strcmp(messageId, "RMC") == 0)) { - saveFix(); + if (!saveFix()) continue; // incoherent snapshot + if (_firstFixInWindow == 0) { + _firstFixInWindow = millis(); + fixStatsFix((uint32_t)(_firstFixInWindow - _acquisitionStarted)); + } if (_acquiringPeriodically) { - if (_firstFixInWindow == 0) _firstFixInWindow = millis(); if (nmea.getNumSatellites() >= GPS_MIN_SATS_FOR_FIX || (uint32_t)(millis() - _firstFixInWindow) >= GPS_FIX_SETTLE_MS) { finishPeriodicAcquisition(); diff --git a/src/helpers/sensors/RakLocationProvider.h b/src/helpers/sensors/RakLocationProvider.h index d2c755e6..7deddf43 100644 --- a/src/helpers/sensors/RakLocationProvider.h +++ b/src/helpers/sensors/RakLocationProvider.h @@ -57,6 +57,10 @@ public: return _useI2c ? _driver.hasFix() : _nmea.isValid(); } + FixStats getFixStats() const override { + return _useI2c ? _fixStats : _nmea.getFixStats(); + } + LastFix getLastFix() const override { return _useI2c ? _lastFix : _nmea.getLastFix(); } @@ -146,7 +150,13 @@ public: } const bool hasCurrentFix = _driver.hasFix(); - if (hasCurrentFix) saveRak12500Fix(); + if (hasCurrentFix) { + // first fix since the start + if (!_lastFix.valid || (long)(_lastFix.acquiredAt - _acquisitionStarted) < 0) { + fixStatsFix((uint32_t)(millis() - _acquisitionStarted)); + } + saveRak12500Fix(); + } if (_gpsPeriodSeconds > 0 && _acquiringPeriodically && hasCurrentFix) { _driver.stop(); @@ -155,6 +165,7 @@ public: } else if (_gpsPeriodSeconds > 0 && _acquiringPeriodically && _lastFix.valid && (uint32_t)(millis() - _acquisitionStarted) >= GPS_PERIODIC_ACQUISITION_TIMEOUT_MS) { + fixStatsMiss(); _driver.stop(); _acquiringPeriodically = false; _nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL; From bd21096ce0282851958dcef6d4422d56094df373 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?N=C3=ADckolas=20Goline?= Date: Wed, 4 Nov 2026 13:36:33 -0300 Subject: [PATCH 63/79] muzi_base: fix GPS UART pins and re-enable ATGM336H NMEA output The refactor no longer calls Serial1.setPins() on nRF52, so Serial1 uses PIN_SERIAL1_RX/TX directly. Those were swapped (the GPS transmits on P0.20), so no data was received. Fix them and define PIN_GPS_TX/RX by the gps module's side, as other variants do. The ATGM336H keeps its NMEA output config across power cycles, and other firmware may leave every sentence disabled. Re-enable GGA + RMC after each power-up. --- variants/muzi_base/target.cpp | 12 ++++++++++++ variants/muzi_base/target.h | 4 ++++ variants/muzi_base/variant.h | 8 ++++---- 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/variants/muzi_base/target.cpp b/variants/muzi_base/target.cpp index b65bafa1..6653ada1 100644 --- a/variants/muzi_base/target.cpp +++ b/variants/muzi_base/target.cpp @@ -50,6 +50,18 @@ void MuziBaseSensorManager::loop() { _pwr_last_click = t; if (++_pwr_clicks >= USER_BTN_POWER_OFF_CLICKS) muziPowerOff(); } +#if ENV_INCLUDE_GPS + // the ATGM336H keeps its nmea output config across power cycles (backup + // supply), and other firmware may have turned every sentence off. re-enable + // GGA + RMC after each power-up, once the module has booted. + bool gps_on = _location->isActive(); + if (gps_on && !_gps_was_active) _gps_cfg_at = millis() + 1000; + _gps_was_active = gps_on; + if (_gps_cfg_at && gps_on && (long)(millis() - _gps_cfg_at) > 0) { + _gps_cfg_at = 0; + _location->sendSentence("$PCAS03,1,0,0,0,1,0,0,0,0,0,,,0,0"); + } +#endif EnvironmentSensorManager::loop(); } diff --git a/variants/muzi_base/target.h b/variants/muzi_base/target.h index 3f7dcbf5..0c143e1b 100644 --- a/variants/muzi_base/target.h +++ b/variants/muzi_base/target.h @@ -42,6 +42,10 @@ extern AutoDiscoverRTCClock rtc_clock; class MuziBaseSensorManager : public EnvironmentSensorManager { unsigned long _pwr_last_click = 0; uint8_t _pwr_clicks = 0; +#if ENV_INCLUDE_GPS + unsigned long _gps_cfg_at = 0; + bool _gps_was_active = false; +#endif public: #if ENV_INCLUDE_GPS MuziBaseSensorManager(LocationProvider& location) : EnvironmentSensorManager(location) {} diff --git a/variants/muzi_base/variant.h b/variants/muzi_base/variant.h index 0c1245a8..d42804f6 100644 --- a/variants/muzi_base/variant.h +++ b/variants/muzi_base/variant.h @@ -54,8 +54,8 @@ static const uint8_t AREF = (PIN_AREF); // not used //////////////////////////////////////////////////////////////////////////////// // UART pin definition -#define PIN_SERIAL1_RX (19) // P0.19 used for GPS RX -#define PIN_SERIAL1_TX (20) // P0.20 used for GPS TX +#define PIN_SERIAL1_RX (20) // P0.20, data from the gps +#define PIN_SERIAL1_TX (19) // P0.19, data to the gps //////////////////////////////////////////////////////////////////////////////// // I2C pin definition @@ -153,8 +153,8 @@ static const uint8_t AREF = (PIN_AREF); // not used //////////////////////////////////////////////////////////////////////////////// // GPS #define HAS_GPS 1 -#define PIN_GPS_RX PIN_SERIAL1_RX -#define PIN_GPS_TX PIN_SERIAL1_TX +#define PIN_GPS_TX PIN_SERIAL1_RX // gps module's TX pin +#define PIN_GPS_RX PIN_SERIAL1_TX // gps module's RX pin #define PIN_GPS_EN (32+1) // P1.01 PWR_IO2 on schematic. gps power, driven by the sensor manager. // superIO 3-position mode switch (pins from the meshtastic muzi_base variant). From a134188c62a7f7bdfaa1bd429fc2a2dad44ebe75 Mon Sep 17 00:00:00 2001 From: Florent Date: Wed, 4 Nov 2026 16:30:44 -0400 Subject: [PATCH 64/79] gps: serial pin and configuration fixes (nrf52, meshadventurer, tracker_v1, heltec_tracker) --- src/helpers/sensors/AirohaGpsDriver.h | 4 +- src/helpers/sensors/AirohaSleep.h | 19 ------- .../sensors/MicroNMEALocationProvider.h | 10 +--- src/helpers/sensors/NmeaGpsDriver.h | 55 +++++++++---------- src/helpers/sensors/RakLocationProvider.h | 2 +- variants/heltec_tracker/platformio.ini | 4 +- variants/heltec_tracker/target.cpp | 14 +++-- variants/meshadventurer/platformio.ini | 4 +- variants/meshadventurer/target.cpp | 4 +- variants/nano_g2_ultra/NanoG2UltraGpsDriver.h | 2 +- variants/t1000-e/variant.h | 2 + 11 files changed, 48 insertions(+), 72 deletions(-) delete mode 100644 src/helpers/sensors/AirohaSleep.h diff --git a/src/helpers/sensors/AirohaGpsDriver.h b/src/helpers/sensors/AirohaGpsDriver.h index cd94d419..9ba8a55d 100644 --- a/src/helpers/sensors/AirohaGpsDriver.h +++ b/src/helpers/sensors/AirohaGpsDriver.h @@ -46,8 +46,8 @@ class AirohaGpsDriver : public NmeaGpsDriver { } public: - AirohaGpsDriver(HardwareSerial& serial) - : NmeaGpsDriver(serial, -1, -1, -1, -1, nullptr, HIGH, LOW, 115200) {} + AirohaGpsDriver(UART_TYPE& serial) + : NmeaGpsDriver(serial, -1, -1, -1, -1, nullptr, HIGH, LOW, GPS_BAUD_RATE) {} void initialize() { NmeaGpsDriver::begin(); diff --git a/src/helpers/sensors/AirohaSleep.h b/src/helpers/sensors/AirohaSleep.h deleted file mode 100644 index 6637d0fb..00000000 --- a/src/helpers/sensors/AirohaSleep.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once -#include - -// Board must keep the GPS RTC backup pin powered and can cut GPS power once we return. -// Returns true if the command was acked within 3 attempts, otherwise returns false. -static inline bool airohaEnterSleep(LocationProvider* nmea) { - for (uint8_t attempt = 0; attempt < 3; attempt++) { - nmea->drain(); - nmea->sendSentence("$PAIR650,0"); - if (nmea->waitFor("$PAIR001,650,0", 50)) { // wait for the command received signal - #ifdef GPS_NMEA_DEBUG - Serial.printf("Airoha RTC Backup sleep command accepted by GPS after %u attempts\r\n", attempt + 1); - #endif - nmea->waitFor("$PAIR650,0", 50); // give the GPS 50ms grace to signal it is ready for sleep - return true; - } - } - return false; -} \ No newline at end of file diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index 3c2adc6e..db279acb 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -119,15 +119,7 @@ public: // Temporary migration adapter for targets and downstream boards. New code // should inject a GpsDriver; this constructor will be removed once targets // have been migrated. - MicroNMEALocationProvider(HardwareSerial& serial, mesh::RTCClock* clock = nullptr, - int pin_reset = GPS_RESET, int pin_en = GPS_EN, - RefCountedDigitalPin* peripher_power = nullptr) - : nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), - _driver(new NmeaGpsDriver(serial, PIN_GPS_TX, PIN_GPS_RX, pin_reset, pin_en, - peripher_power)), - _ownsDriver(true) {} - - MicroNMEALocationProvider(Stream& serial, mesh::RTCClock* clock = nullptr, + MicroNMEALocationProvider(UART_TYPE& serial, mesh::RTCClock* clock = nullptr, int pin_reset = GPS_RESET, int pin_en = GPS_EN, RefCountedDigitalPin* peripher_power = nullptr) : nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), diff --git a/src/helpers/sensors/NmeaGpsDriver.h b/src/helpers/sensors/NmeaGpsDriver.h index abecb817..25acff45 100644 --- a/src/helpers/sensors/NmeaGpsDriver.h +++ b/src/helpers/sensors/NmeaGpsDriver.h @@ -5,6 +5,14 @@ #include #include +#ifndef UART_TYPE +#ifdef NRF52_PLATFORM + #define UART_TYPE Uart +#else + #define UART_TYPE HardwareSerial +#endif +#endif + #ifndef PIN_GPS_TX #define PIN_GPS_TX (-1) #endif @@ -46,7 +54,11 @@ #endif #ifndef GPS_BAUD_RATE - #define GPS_BAUD_RATE 9600 + #ifdef GPS_BAUDRATE + #define GPS_BAUD_RATE GPS_BAUDRATE + #else + #define GPS_BAUD_RATE 9600 + #endif #endif #ifndef PIN_GPS_SWITCH @@ -66,8 +78,8 @@ #endif class NmeaGpsDriver : public GpsDriver { - Stream* _stream = nullptr; - HardwareSerial* _hardwareSerial = nullptr; + UART_TYPE* _hardwareSerial = nullptr; + RefCountedDigitalPin* _peripheralPower = nullptr; int _txPin = -1; int _rxPin = -1; @@ -87,12 +99,12 @@ class NmeaGpsDriver : public GpsDriver { #endif void startHardware() { - if (_stream == nullptr || _started) return; + if (_hardwareSerial == nullptr || _started) return; if (_hardwareSerial != nullptr) { -#ifdef ESP32_PLATFORM - _hardwareSerial->setPins(_txPin, _rxPin); -#endif + if (_txPin != -1 && _rxPin != -1) { + _hardwareSerial->setPins(_txPin, _rxPin); + } _hardwareSerial->begin(_baudRate); } @@ -116,14 +128,14 @@ class NmeaGpsDriver : public GpsDriver { public: NmeaGpsDriver() = default; - NmeaGpsDriver(Stream& stream, int txPin = PIN_GPS_TX, int rxPin = PIN_GPS_RX, + NmeaGpsDriver(UART_TYPE& serial, int txPin = PIN_GPS_TX, int rxPin = PIN_GPS_RX, int resetPin = GPS_RESET, int enablePin = GPS_EN, RefCountedDigitalPin* peripheralPower = nullptr, int enableActive = GPS_EN_ACTIVE, int resetActive = GPS_RESET_ACTIVE, uint32_t baudRate = GPS_BAUD_RATE, int hardwareEnablePin = PIN_GPS_SWITCH, int hardwareEnableActive = GPS_SWITCH_ACTIVE) - : _stream(&stream), _peripheralPower(peripheralPower), _txPin(txPin), _rxPin(rxPin), + : _hardwareSerial(&serial), _peripheralPower(peripheralPower), _txPin(txPin), _rxPin(rxPin), _resetPin(resetPin), _enablePin(enablePin), _enableActive(enableActive), _resetActive(resetActive), _baudRate(baudRate), _hardwareEnablePin(hardwareEnablePin), _hardwareEnableActive(hardwareEnableActive) { @@ -140,19 +152,6 @@ public: } } - NmeaGpsDriver(HardwareSerial& serial, int txPin = PIN_GPS_TX, int rxPin = PIN_GPS_RX, - int resetPin = GPS_RESET, int enablePin = GPS_EN, - RefCountedDigitalPin* peripheralPower = nullptr, - int enableActive = GPS_EN_ACTIVE, int resetActive = GPS_RESET_ACTIVE, - uint32_t baudRate = GPS_BAUD_RATE, - int hardwareEnablePin = PIN_GPS_SWITCH, - int hardwareEnableActive = GPS_SWITCH_ACTIVE) - : NmeaGpsDriver(static_cast(serial), txPin, rxPin, resetPin, enablePin, - peripheralPower, enableActive, resetActive, baudRate, - hardwareEnablePin, hardwareEnableActive) { - _hardwareSerial = &serial; - } - void begin() override { #if !GPS_SWITCH_IS_HARDWARE _requestedOn = true; @@ -232,11 +231,11 @@ public: } int available() { - return _stream == nullptr ? 0 : _stream->available(); + return _hardwareSerial == nullptr ? 0 : _hardwareSerial->available(); } int read() { - return _stream == nullptr ? -1 : _stream->read(); + return _hardwareSerial == nullptr ? -1 : _hardwareSerial->read(); } void drain() { @@ -244,19 +243,19 @@ public: } void sendNmeaSentence(const char* sentence) { - if (_stream == nullptr || sentence == nullptr || sentence[0] != '$') return; + if (_hardwareSerial == nullptr || sentence == nullptr || sentence[0] != '$') return; uint8_t checksum = 0; const char* p = sentence + 1; while (*p != '\0' && *p != '*') checksum ^= (uint8_t)*p++; - _stream->print(sentence); + _hardwareSerial->print(sentence); if (*p == '\0') { char checksumSuffix[6]; snprintf(checksumSuffix, sizeof(checksumSuffix), "*%02X\r\n", checksum); - _stream->print(checksumSuffix); + _hardwareSerial->print(checksumSuffix); } else { - _stream->print("\r\n"); + _hardwareSerial->print("\r\n"); } } }; diff --git a/src/helpers/sensors/RakLocationProvider.h b/src/helpers/sensors/RakLocationProvider.h index 7deddf43..094e70ec 100644 --- a/src/helpers/sensors/RakLocationProvider.h +++ b/src/helpers/sensors/RakLocationProvider.h @@ -29,7 +29,7 @@ class RakLocationProvider : public LocationProvider { public: RakLocationProvider(RakI2cGpsDriver& driver, mesh::RTCClock* clock = nullptr, - HardwareSerial& serial = Serial1) + UART_TYPE& serial = Serial1) : _driver(driver), _nmeaDriver(serial), _nmea(_nmeaDriver, clock) {} void syncTime() override { diff --git a/variants/heltec_tracker/platformio.ini b/variants/heltec_tracker/platformio.ini index 75d1cadf..3affd8ae 100644 --- a/variants/heltec_tracker/platformio.ini +++ b/variants/heltec_tracker/platformio.ini @@ -31,8 +31,8 @@ build_flags = -D USE_PIN_TFT=1 -D PIN_VEXT_EN=3 ; Vext is connected to VDD which is also connected to OLED & GPS -D PIN_TFT_LEDA_CTL=21 ; LEDK (switches on/off via mosfet to create the ground) - -D PIN_GPS_RX=33 - -D PIN_GPS_TX=34 + -D PIN_GPS_TX=33 ; GPS module TX -> MCU RX (GPIO33) + -D PIN_GPS_RX=34 ; GPS module RX <- MCU TX (GPIO34) -D PIN_GPS_EN=35 ; N-ch MOSFET Q2 drives P-ch high-side switch → active HIGH (default) -D PIN_GPS_RESET=36 -D PIN_GPS_RESET_ACTIVE=LOW diff --git a/variants/heltec_tracker/target.cpp b/variants/heltec_tracker/target.cpp index 041cb2b8..67f98306 100644 --- a/variants/heltec_tracker/target.cpp +++ b/variants/heltec_tracker/target.cpp @@ -23,9 +23,14 @@ public: : NmeaGpsDriver(Serial1, PIN_GPS_TX, PIN_GPS_RX, GPS_RESET, GPS_EN, &board.periph_power) {} - void begin() override { - NmeaGpsDriver::begin(); - sendNmeaSentence("$CFGSYS,h35155*68"); + void reset() override { + NmeaGpsDriver::reset(); + // Send configuration after reset + if (isActive()) { + delay(250); + sendNmeaSentence("$CFGSYS,h35155*68"); + // TODO: remove active wait (250ms is a lot) + } } }; @@ -64,8 +69,7 @@ void HWTSensorManager::stop_gps() { } bool HWTSensorManager::begin() { - // init GPS port - Serial1.begin(115200, SERIAL_8N1, PIN_GPS_RX, PIN_GPS_TX); + // the GPS UART (pins, baud rate) is now configured by gps_driver when the GPS is started return true; } diff --git a/variants/meshadventurer/platformio.ini b/variants/meshadventurer/platformio.ini index 4af0f7f7..5e35251c 100644 --- a/variants/meshadventurer/platformio.ini +++ b/variants/meshadventurer/platformio.ini @@ -23,8 +23,8 @@ build_flags = -D SX126X_DIO2_AS_RF_SWITCH=false -D SX126X_DIO3_TCXO_VOLTAGE=1.8 -D SX126X_RX_BOOSTED_GAIN=1 - -D PIN_GPS_RX=12 - -D PIN_GPS_TX=15 + -D PIN_GPS_TX=12 ; GPS module TX -> MCU RX (GPIO12) + -D PIN_GPS_RX=15 ; GPS module RX <- MCU TX (GPIO15) -D DISPLAY_CLASS=SSD1306Display build_src_filter = ${esp32_base.build_src_filter} +<../variants/meshadventurer> diff --git a/variants/meshadventurer/target.cpp b/variants/meshadventurer/target.cpp index 827e23b7..1ccfe151 100644 --- a/variants/meshadventurer/target.cpp +++ b/variants/meshadventurer/target.cpp @@ -48,9 +48,7 @@ void MASensorManager::stop_gps() { } bool MASensorManager::begin() { - Serial1.setPins(PIN_GPS_RX, PIN_GPS_TX); - Serial1.begin(9600); - delay(500); + // the GPS UART (pins, baud rate) is now configured by gps_driver when the GPS is started return true; } diff --git a/variants/nano_g2_ultra/NanoG2UltraGpsDriver.h b/variants/nano_g2_ultra/NanoG2UltraGpsDriver.h index 7e3bd109..76270d32 100644 --- a/variants/nano_g2_ultra/NanoG2UltraGpsDriver.h +++ b/variants/nano_g2_ultra/NanoG2UltraGpsDriver.h @@ -4,7 +4,7 @@ class NanoG2UltraGpsDriver : public NmeaGpsDriver { public: - NanoG2UltraGpsDriver(HardwareSerial& serial) : NmeaGpsDriver(serial) { + NanoG2UltraGpsDriver(UART_TYPE& serial) : NmeaGpsDriver(serial) { pinMode(PIN_GPS_STANDBY, OUTPUT); digitalWrite(PIN_GPS_STANDBY, LOW); } diff --git a/variants/t1000-e/variant.h b/variants/t1000-e/variant.h index bd509073..17a5538c 100644 --- a/variants/t1000-e/variant.h +++ b/variants/t1000-e/variant.h @@ -117,6 +117,8 @@ #define GPS_RTC_INT (15) // P0.15 #define GPS_RESETB (46) // P1.14 +#define GPS_BAUDRATE 115200 + //////////////////////////////////////////////////////////////////////////////// // Temp+Lux Sensor From d41aee832e4252ebe2ab87899ee55f1217b798fe Mon Sep 17 00:00:00 2001 From: Florent Date: Wed, 4 Nov 2026 20:34:28 -0400 Subject: [PATCH 65/79] gps: guard the clock sync against stalled and too old fixes --- src/helpers/sensors/MicroNMEALocationProvider.h | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index db279acb..dddcce19 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -70,6 +70,8 @@ class MicroNMEALocationProvider : public LocationProvider { void finishPeriodicAcquisition() { if (_firstFixInWindow == 0) fixStatsMiss(); _driver->stop(); + nmea.clear(); // the parser keeps the last time as valid otherwise + time_valid = 0; _acquiringPeriodically = false; _nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL; } @@ -95,7 +97,7 @@ class MicroNMEALocationProvider : public LocationProvider { } void updateTime() { - if (!isValid()) time_valid = 0; + if (!isValid() || (millis() - _last_nmea_ms) > 2000) time_valid = 0; // no stale time if ((long)(millis() - next_check) <= 0) return; next_check = millis() + 1000; @@ -156,6 +158,8 @@ public: _stop_calls++; _acquiringPeriodically = false; _driver->stop(); + nmea.clear(); + time_valid = 0; } bool isActive() override { @@ -274,7 +278,9 @@ public: fixStatsFix((uint32_t)(_firstFixInWindow - _acquisitionStarted)); } if (_acquiringPeriodically) { - if (nmea.getNumSatellites() >= GPS_MIN_SATS_FOR_FIX || + // stay on until a pending time sync is done (or the settle time is over) + const bool synced = _clock == nullptr || !_time_sync_needed; + if ((nmea.getNumSatellites() >= GPS_MIN_SATS_FOR_FIX && synced) || (uint32_t)(millis() - _firstFixInWindow) >= GPS_FIX_SETTLE_MS) { finishPeriodicAcquisition(); } From 539b55b7724fd56ccf1880fd9081b9151e0155d5 Mon Sep 17 00:00:00 2001 From: Florent Date: Thu, 5 Nov 2026 10:16:28 -0400 Subject: [PATCH 66/79] gps: move detection into LocationProvider, remove the legacy constructor --- .../sensors/EnvironmentSensorManager.cpp | 23 ++----------------- src/helpers/sensors/LocationProvider.h | 16 +++++++++++++ .../sensors/MicroNMEALocationProvider.h | 16 ------------- 3 files changed, 18 insertions(+), 37 deletions(-) diff --git a/src/helpers/sensors/EnvironmentSensorManager.cpp b/src/helpers/sensors/EnvironmentSensorManager.cpp index ee942df1..eafa11a3 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.cpp +++ b/src/helpers/sensors/EnvironmentSensorManager.cpp @@ -696,31 +696,12 @@ bool EnvironmentSensorManager::setSettingValue(const char* name, const char* val #if ENV_INCLUDE_GPS void EnvironmentSensorManager::initBasicGPS() { - start_gps(); - #ifndef PIN_GPS_EN MESH_DEBUG_PRINTLN("No GPS wake/reset pin found for this board. Continuing on..."); #endif -#ifdef ENV_SKIP_GPS_DETECT - gps_detected = true; -#else - gps_detected = _location->detect(5000); -#endif - - if (gps_detected) { - MESH_DEBUG_PRINTLN("GPS detected"); - #if defined(PERSISTANT_GPS) - return; - #else - if (_location->keepEnabledAfterDetection()) { - return; - } - #endif - } else { - MESH_DEBUG_PRINTLN("No GPS detected"); - } - stop_gps(); + gps_detected = _location->autoDetect(); + MESH_DEBUG_PRINTLN("%s", gps_detected ? "GPS detected" : "No GPS detected"); } void EnvironmentSensorManager::start_gps() { diff --git a/src/helpers/sensors/LocationProvider.h b/src/helpers/sensors/LocationProvider.h index 3d7abd7a..ad2bba1d 100644 --- a/src/helpers/sensors/LocationProvider.h +++ b/src/helpers/sensors/LocationProvider.h @@ -61,6 +61,22 @@ public: virtual void drain() { } virtual bool detect(uint32_t timeout_ms) { return false; } virtual bool keepEnabledAfterDetection() const { return false; } + // Power on, detect, then leave the GPS on or off as the board wants. + // Returns true if a GPS is present. + virtual bool autoDetect() { + setGpsOn(true); + #ifdef ENV_SKIP_GPS_DETECT + bool found = true; + #else + bool found = detect(5000); + #endif + #ifdef PERSISTANT_GPS + if (found) return true; + #endif + if (found && keepEnabledAfterDetection()) return true; + setGpsOn(false); + return found; + } virtual void setGpsPeriod(uint32_t seconds) { } virtual uint32_t getGpsPeriod() const { return 0; } virtual uint32_t getLastFixAge() const { // in seconds, UINT32_MAX if never diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index dddcce19..ea87ad19 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -24,7 +24,6 @@ class MicroNMEALocationProvider : public LocationProvider { MicroNMEA nmea; mesh::RTCClock* _clock; NmeaGpsDriver* _driver; - bool _ownsDriver = false; unsigned long next_check = 0; long time_valid = 0; unsigned long _last_time_sync = 0; @@ -118,21 +117,6 @@ public: MicroNMEALocationProvider(NmeaGpsDriver& driver, mesh::RTCClock* clock = nullptr) : nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), _driver(&driver) {} - // Temporary migration adapter for targets and downstream boards. New code - // should inject a GpsDriver; this constructor will be removed once targets - // have been migrated. - MicroNMEALocationProvider(UART_TYPE& serial, mesh::RTCClock* clock = nullptr, - int pin_reset = GPS_RESET, int pin_en = GPS_EN, - RefCountedDigitalPin* peripher_power = nullptr) - : nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), - _driver(new NmeaGpsDriver(serial, PIN_GPS_TX, PIN_GPS_RX, pin_reset, pin_en, - peripher_power)), - _ownsDriver(true) {} - - ~MicroNMEALocationProvider() override { - if (_ownsDriver) delete _driver; - } - void begin() override { _begin_calls++; const bool wasActive = _driver->isActive(); From 93d165dd8cdc72301870ec1e8a83fd64f69ef899 Mon Sep 17 00:00:00 2001 From: Florent Date: Sat, 7 Nov 2026 09:05:11 -0400 Subject: [PATCH 67/79] gps: once command --- src/helpers/CommonGpsPrefs.cpp | 27 ++++++++++++++++++ src/helpers/sensors/LocationProvider.h | 1 + .../sensors/MicroNMEALocationProvider.h | 28 +++++++++++++++++++ src/helpers/sensors/RakLocationProvider.h | 8 ++++++ 4 files changed, 64 insertions(+) diff --git a/src/helpers/CommonGpsPrefs.cpp b/src/helpers/CommonGpsPrefs.cpp index c4936d4f..926efe71 100644 --- a/src/helpers/CommonGpsPrefs.cpp +++ b/src/helpers/CommonGpsPrefs.cpp @@ -97,6 +97,33 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, } return true; } + if (memcmp(command, "gps once", 8) == 0) { // before "gps on" + LocationProvider* location = sensors.getLocationProvider(); + + if (location == nullptr) { + strcpy(reply, "gps provider not found"); + return true; + } + + if (location->hasHardwareEnableState() && !location->isHardwareEnabled()) { + strcpy(reply, "gps hw switch off"); + return true; + } + + if (strstr(command, " -s") != nullptr) location->syncTime(); + + const char* state = !location->isGpsOn() ? "turning on and acquiring" + : (location->getGpsPeriod() > 0 && !location->isActive()) ? "waking gps" + : "gps already on"; + + if (location->startOnce()) { + snprintf(reply, 160, "ok (%s)", state); + } else { + strcpy(reply, "gps once not supported"); + } + + return true; + } if (memcmp(command, "gps on", 6) == 0) { if (!setGpsEnabled(sensors, true)) { strcpy(reply, "gps toggle not found"); diff --git a/src/helpers/sensors/LocationProvider.h b/src/helpers/sensors/LocationProvider.h index ad2bba1d..b15c0ed2 100644 --- a/src/helpers/sensors/LocationProvider.h +++ b/src/helpers/sensors/LocationProvider.h @@ -86,6 +86,7 @@ public: virtual bool hasHardwareEnableState() const { return false; } virtual bool isHardwareEnabled() const { return true; } virtual bool isGpsOn() const { return _gpsOn; } + virtual bool startOnce() { return false; } virtual void setGpsOn(bool on) { _gpsOn = on; if (on) { diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index ea87ad19..9a6d8006 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -32,6 +32,7 @@ class MicroNMEALocationProvider : public LocationProvider { unsigned long _acquisitionStarted = 0; unsigned long _firstFixInWindow = 0; bool _acquiringPeriodically = false; + unsigned long _onceDeadline = 0; static const unsigned long TIME_SYNC_INTERVAL = 1800000; uint32_t _uart_bytes = 0; @@ -119,6 +120,7 @@ public: void begin() override { _begin_calls++; + _onceDeadline = 0; const bool wasActive = _driver->isActive(); _driver->begin(); if (!wasActive) { @@ -140,6 +142,7 @@ public: void stop() override { _stop_calls++; + _onceDeadline = 0; _acquiringPeriodically = false; _driver->stop(); nmea.clear(); @@ -172,6 +175,16 @@ public: return _gpsPeriodSeconds; } + bool startOnce() override { + if (_gpsOn) { // already on, acquire now + _nextAcquisition = millis(); + return true; + } + setGpsOn(true); + _onceDeadline = millis() + GPS_PERIODIC_ACQUISITION_TIMEOUT_MS; + return true; + } + void syncTime() override { nmea.clear(); LocationProvider::syncTime(); @@ -232,6 +245,21 @@ public: void loop() override { if (_driver->pollGpsSwitch()) _gpsOn = true; + if (_onceDeadline != 0) { + if (_firstFixInWindow != 0 && (long)(_onceDeadline - (millis() + GPS_FIX_SETTLE_MS)) > 0) { + _onceDeadline = millis() + GPS_FIX_SETTLE_MS; + } + if ((long)(millis() - _onceDeadline) >= 0) { + if (_driver->isActive()) { + setGpsOn(false); + } else { // do not stop twice + _gpsOn = false; + _onceDeadline = 0; + _acquiringPeriodically = false; + } + } + } + if (_gpsOn && _gpsPeriodSeconds > 0 && !_acquiringPeriodically && (long)(millis() - _nextAcquisition) >= 0) { startPeriodicAcquisition(); diff --git a/src/helpers/sensors/RakLocationProvider.h b/src/helpers/sensors/RakLocationProvider.h index 094e70ec..6ad05125 100644 --- a/src/helpers/sensors/RakLocationProvider.h +++ b/src/helpers/sensors/RakLocationProvider.h @@ -190,6 +190,14 @@ public: return _gpsPeriodSeconds; } + bool isGpsOn() const override { + return _useI2c ? _gpsOn : _nmea.isGpsOn(); + } + + bool startOnce() override { + return _useI2c ? false : _nmea.startOnce(); // not supported on the RAK12500 + } + void setGpsOn(bool on) override { if (_useI2c) LocationProvider::setGpsOn(on); else { _gpsOn = on; _nmea.setGpsOn(on); } From 6b34ae96dfd7df221911705e10077fd82d83269b Mon Sep 17 00:00:00 2001 From: Florent Date: Sat, 7 Nov 2026 13:45:40 -0400 Subject: [PATCH 68/79] gps: Rework the CLI - more consistency with other cli commands - new format for gps fix - gps format accepts postfix (s/m/d/h) - documentation --- docs/cli_commands.md | 27 +++++- docs/companion_cli.md | 27 +++++- src/helpers/CommonCLI.cpp | 12 +-- src/helpers/CommonGpsPrefs.cpp | 89 ++++++++++--------- src/helpers/sensors/LocationProvider.h | 1 + .../sensors/MicroNMEALocationProvider.h | 4 + src/helpers/sensors/RakLocationProvider.h | 4 + 7 files changed, 110 insertions(+), 54 deletions(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index d7b8d5d0..44ff3a25 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1021,10 +1021,10 @@ region save #### View or change the GPS acquisition period **Usage:** - `gps period` -- `gps period ` +- `gps period ` **Parameters:** -- `seconds`: `0` for continuous tracking, or `1`-`86400` for periodic acquisition +- `value`: `0` for continuous tracking, or a period. The value can be postfixed with `s`, `m`, `h` or `d` to specify the unit (seconds by default). **Note:** A periodic acquisition stops after receiving a valid fix, then resumes after the configured period. @@ -1034,7 +1034,12 @@ region save **Usage:** - `gps fix` -**Note:** Returns the last valid latitude, longitude, altitude, and elapsed time since the fix. Returns `no fix` until a valid fix is received. +**Output:** +- `> Fix (n sat): , `: the GPS currently has a fix. +- `> Last fix ago (n sat)[, acq