Merge upstream/dev (80 commits) [upstream-sync]

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tthandClaude Opus 5.5 committed 2026-11-12 09:22:19 +01:00
commit 8d0b0dd164
140 files changed
+3573 -853

No files matched your search

+5
View File
@@ -40,6 +40,11 @@ jobs:
- PicoW_repeater
# STM32
- wio-e5-mini_repeater
- LilyGo_T3_STM32_repeater
- LilyGo_T3_STM32_companion_radio_usb
- LilyGo_T3_STM32_repeater_ina219
- LilyGo_T3_STM32_companion_radio_usb_ina219
- nucleo_wl55jc_repeater
# ESP32-C6
- LilyGo_Tlora_C6_repeater_
# LR1110 (nRF52)
+1
View File
@@ -196,6 +196,7 @@ For developers:
- Install [PlatformIO](https://docs.platformio.org) in [Visual Studio Code](https://code.visualstudio.com).
- Clone and open the MeshCore repository in Visual Studio Code.
- For the LilyGO T3 STM32, see the [board build and flashing guide](./variants/lilygo_t3_stm32/README.md).
- See the example applications you can modify and run:
- [Companion Radio](./examples/companion_radio) - For use with an external chat app, over BLE, USB or Wi-Fi.
- [KISS Modem](./examples/kiss_modem) - Serial KISS protocol bridge for host applications. ([protocol docs](./docs/kiss_modem_protocol.md))
+39
View File
@@ -0,0 +1,39 @@
{
"build": {
"arduino": {
"ldscript": "esp32s3_out.ld"
},
"core": "esp32",
"extra_flags": [
"-D ARDUINO_USB_CDC_ON_BOOT=0",
"-D ARDUINO_USB_MSC_ON_BOOT=0",
"-D ARDUINO_USB_DFU_ON_BOOT=0",
"-D ARDUINO_USB_MODE=0",
"-D ARDUINO_RUNNING_CORE=1",
"-D ARDUINO_EVENT_RUNNING_CORE=1"
],
"f_cpu": "240000000L",
"f_flash": "80000000L",
"flash_mode": "qio",
"hwids": [["0x303A", "0x1001"]],
"mcu": "esp32s3",
"variant": "esp32s3"
},
"connectivity": ["wifi", "bluetooth", "lora"],
"debug": {
"default_tool": "esp-builtin",
"onboard_tools": ["esp-builtin"],
"openocd_target": "esp32s3.cfg"
},
"frameworks": ["arduino", "espidf"],
"name": "DFRobot LoRaWAN ESP32-S3 (4 MB Flash, No PSRAM)",
"upload": {
"flash_size": "4MB",
"maximum_ram_size": 524288,
"maximum_size": 4194304,
"require_upload_port": true,
"speed": 921600
},
"url": "https://www.dfrobot.com",
"vendor": "DFRobot"
}
+32
View File
@@ -0,0 +1,32 @@
{
"build": {
"arduino": {
"variant_h": "variant_generic.h"
},
"core": "stm32",
"cpu": "cortex-m4",
"extra_flags": "-DSTM32WL -DSTM32WLxx -DSTM32WL55xx",
"f_cpu": "48000000L",
"framework_extra_flags": {
"arduino": "-DUSE_CM4_STARTUP_FILE -DARDUINO_GENERIC_WL55CCUX"
},
"mcu": "stm32wl55ccu6",
"product_line": "STM32WL55xx",
"variant": "STM32WLxx/WL54CCU_WL55CCU_WLE4C(8-B-C)U_WLE5C(8-B-C)U"
},
"debug": {
"jlink_device": "STM32WL55CC",
"openocd_target": "stm32wlx",
"svd_path": "STM32WL5x_CM4.svd"
},
"frameworks": ["arduino"],
"name": "LilyGO T3 STM32 V1.0 (STM32WL55CCU6)",
"upload": {
"maximum_ram_size": 65536,
"maximum_size": 262144,
"protocol": "serial",
"protocols": ["serial", "stlink", "jlink"]
},
"url": "https://github.com/Xinyuan-LilyGO/T3-STM32",
"vendor": "LilyGO"
}
+90 -12
View File
@@ -1116,9 +1116,16 @@ region save
---
### GPS (When GPS support is compiled in)
#### View or change GPS state
#### View GPS state
**Usage:**
- `gps`
**Note:** Reports the requested state, receiver activity, last-fix status (last fix gives number of sats and how long ago was the fix), and mode. In periodic mode, `waiting` means the receiver is off between acquisitions; the last fix remains available. `off(hw)` means a hardware GPS switch is off.
---
#### Change GPS state
**Usage:**
- `gps <state>`
**Parameters:**
@@ -1126,20 +1133,43 @@ 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
- `duty, {awake|asleep}, {fix|no fix}, {sat count} sats` in duty-cycle mode
**Note:** In duty-cycle mode `gps` answers `duty, {awake|asleep}, {fix|no fix}, {sat count} sats`.
`gps duty` powers the receiver only around a clock sync and cuts it in between.
It is meant for a node that runs GPS purely to keep its (volatile) RTC set — a
mast or solar repeater — where a receiver drawing tens of mA continuously
dwarfs the rest of the power budget. Clock accuracy is unchanged: the sync
cadence matches the periodic re-sync that `gps on` already does. The position
still comes from prefs (see `gps advert`), so duty mode does not affect what a
repeater advertises. Build-time knobs: `GPS_DUTY_SYNC_INTERVAL_SECS` (1800),
`GPS_DUTY_MAX_AWAKE_SECS` (300, the cap on one attempt) and
`GPS_DUTY_RETRY_SECS` (3600, backoff after a window with no fix).
dwarfs the rest of the power budget. Unlike `gps period`, every attempt is
capped even before the first fix ever, so a node that never sees the sky does
not keep the receiver powered. It sets `gps period` to 0. The position still
comes from prefs (see `set loc`), so duty mode does not affect what a repeater
advertises. `gps on` / `gps off` leave duty mode. Build-time knobs:
`GPS_DUTY_SYNC_INTERVAL_SECS` (1800), `GPS_DUTY_MAX_AWAKE_SECS` (300, the cap on
one attempt) and `GPS_DUTY_RETRY_SECS` (3600, backoff after a window with no fix).
---
#### View or change the GPS acquisition period
**Usage:**
- `gps period`
- `gps period <value>`
**Parameters:**
- `value`: `0` for continuous tracking, or a period. The value can be postfixed with `s`, `m`, `h` or `d` to specify the unit (seconds by default).
**Note:** A periodic acquisition stops after receiving a valid fix, then resumes after the configured period.
---
#### View the last GPS fix
**Usage:**
- `gps fix`
**Output:**
- `> Fix (n sat): <lat>, <lon>`: the GPS currently has a fix.
- `> Last fix <age> ago (n sat)[, acq <time>]: <lat>, <lon>`: position of the last valid fix; `acq` is shown only while the receiver is running and shows how for how long the gps has been trying to get a fix.
- `> No fix[, acq <time>]`: no valid fix since the node started.
**Note:** Ages and durations are given in `s`, `m` or `h`.
---
@@ -1149,6 +1179,50 @@ repeater advertises. Build-time knobs: `GPS_DUTY_SYNC_INTERVAL_SECS` (1800),
---
#### On demand GPS fix
**Usage:**
- `gps once`
- `gps once -s`
**Parameters:**
- `-s`: also sync this node's clock with GPS time (as `gps sync`)
**Note:** Starts an acquisition now. If the GPS is off, it is switched and kept on until a valid fix and then turned off.
**Reply:** `OK - turning on and acquiring` (GPS was off), `OK - waking gps` (periodic mode, receiver off between acquisitions) or `OK - gps already on`. `Error, gps hw switch off` if a hardware GPS switch is off, `Error, gps once not supported`.
---
#### View GPS time to first fix statistics
**Usage:**
- `gps fix_stats`
**Output:** `> ttf:<last>/<max> ok:<n> miss:<n>`: last and maximum time between a start of the GPS and its first valid fix, then the last count of consecutive starts with a fix (`ok`) or without one (`miss`).
---
#### View GPS diagnostics
**Usage:**
- `gps diag`
---
#### GPS anti-spoofing guard (When built with `GPS_GUARD`)
With `GPS_GUARD`, a fix becomes the node's last fix (position, telemetry, adverts) only after it passes plausibility checks: at least `GPS_GUARD_MIN_SATS` satellites, HDOP ≤ `GPS_GUARD_MAX_HDOP10`/10, inside the optional build-time region (`GPS_GUARD_LAT_MIN/MAX`, `GPS_GUARD_LON_MIN/MAX`), within the fence around the node's configured `lat`/`lon` (if set), no jump faster than `GPS_GUARD_MAX_SPEED_KMH`, and `GPS_GUARD_STABLE_FIXES` consistent fixes in a row. An unverified position is never reported.
GPS time is written to the clock only while such a fix is current, never earlier than the firmware build date, and, once the clock holds a plausible time (from the build date to 10 years after it), only within `GPS_GUARD_TIME_MAX_STEP` seconds for the first sync and within clock drift (`GPS_GUARD_TIME_DRIFT_BASE` s + `GPS_GUARD_TIME_DRIFT_PPM`) afterwards. Setting the clock manually (`time`, `clock sync`) resets that anchor. A clock outside that window (e.g. a bogus date in 2080) is corrected by the first trusted fix.
Covers serial NMEA receivers (`MicroNMEALocationProvider`).
**Usage:**
- `gps guard`: status, e.g. `> ok 7sat time ok +1s`, `> rej region time rej nofix`, `> ok 7sat time wait` (last check passed, no current trusted fix to check again, e.g. GPS asleep between periodic fixes), or `... ALERT gps-clk +3600s 75m` when a trusted fix has disagreed with the clock by the same offset for `GPS_GUARD_ALERT_MIN` minutes.
- `gps guard on`, `gps guard off`: turn the guard on or off (saved, default on). While off, every fix and GPS time is accepted and `gps guard` shows `off`.
- `gps guard accept`: while an alert is active, confirm that the GPS time is right and apply it to the clock.
- `gps fence`, `gps fence <metres>`: fence radius around the configured `lat`/`lon` (`0` = off). Default `GPS_GUARD_FENCE_M` (1000); a value set here is saved.
- `gps ref`: the reference position; follows `set lat`, `set lon` and `gps setloc`.
---
#### Set this node's location based on the GPS coordinates
**Usage:**
- `gps setloc`
@@ -1157,6 +1231,8 @@ repeater advertises. Build-time knobs: `GPS_DUTY_SYNC_INTERVAL_SECS` (1800),
#### View or change the GPS advert policy
**Usage:**
- `get advert.loc`
- `set advert.loc <policy>`
- `gps advert`
- `gps advert <policy>`
@@ -1164,10 +1240,12 @@ repeater advertises. Build-time knobs: `GPS_DUTY_SYNC_INTERVAL_SECS` (1800),
- `policy`: `none`|`share`|`prefs`
- `none`: don't include location in adverts
- `share`: share gps location (from SensorManager)
- `prefs`: location stored in node's lat and lon settings
- `prefs`: location stored in node's lat and lon settings (can be different from gps value)
**Default:** `prefs`
**Note:** `gps advert` command is the old format but is only accessible when a gps is attached to the unit. It has been kept for compatibility but one should prefer using `get/set` commands instead.
---
### Sensors (When sensor support is compiled in)
+107
View File
@@ -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)
@@ -65,6 +66,20 @@ Since version 1.18 meshcore companion radio firmware has a CLI interface, which
---
#### Fine-tune the battery reading
**Usage:**
- `get adc.multiplier`
- `set adc.multiplier <value>`
**Parameters:**
- `value`: ADC multiplier (0.0-10.0)
**Default:** `0.0` (value defined by board)
**Note:** Returns "Error: unsupported" if the board doesn't support it. Same command as on repeaters, for boards whose battery divider resistors vary (e.g. DIY ProMicro / Faketec).
---
### Radio
Radio parameters are common to all roles and handled by `CommonRadioPrefs`.
@@ -119,6 +134,84 @@ Radio parameters are common to all roles and handled by `CommonRadioPrefs`.
---
### GPS
#### View GPS state
**Usage:**
- `gps`
**Note:** Reports the requested state, receiver activity, last-fix status (last fix gives number of sats and how long ago was the fix), and mode. In periodic mode, `waiting` means the receiver is off between acquisitions; the last fix remains available. `off(hw)` means a hardware GPS switch is off.
---
#### Change GPS state
**Usage:**
- `gps <state>`
**Parameters:**
- `state`: `on`|`off`
---
#### View or change the GPS acquisition period
**Usage:**
- `gps period`
- `gps period <value>`
**Parameters:**
- `value`: `0` for continuous tracking, or a period. The value can be postfixed with `s`, `m`, `h` or `d` to specify the unit (seconds by default).
**Note:** A periodic acquisition stops after receiving a valid fix, then resumes after the configured period.
---
#### View the last GPS fix
**Usage:**
- `gps fix`
**Output:**
- `> Fix (n sat): <lat>, <lon>`: the GPS currently has a fix.
- `> Last fix <age> ago (n sat)[, acq <time>]: <lat>, <lon>`: position of the last valid fix; `acq` is shown only while the receiver is running and shows how for how long the gps has been trying to get a fix.
- `> No fix[, acq <time>]`: no valid fix since the node started.
**Note:** Ages and durations are given in `s`, `m` or `h`.
---
#### Sync this node's clock with GPS time
**Usage:**
- `gps sync`
---
#### On demand GPS fix
**Usage:**
- `gps once`
- `gps once -s`
**Parameters:**
- `-s`: also sync this node's clock with GPS time (as `gps sync`)
**Note:** Starts an acquisition now. If the GPS is off, it is switched and kept on until a valid fix and then turned off.
**Reply:** `OK - turning on and acquiring` (GPS was off), `OK - waking gps` (periodic mode, receiver off between acquisitions) or `OK - gps already on`. `Error, gps hw switch off` if a hardware GPS switch is off, `Error, gps once not supported`.
---
#### View GPS time to first fix statistics
**Usage:**
- `gps fix_stats`
**Output:** `> ttf:<last>/<max> ok:<n> miss:<n>`: last and maximum time between a start of the GPS and its first valid fix, then the last count of consecutive starts with a fix (`ok`) or without one (`miss`).
---
#### View GPS diagnostics
**Usage:**
- `gps diag`
---
#### View or change this node's rx boosted gain mode (SX12xx and LR1110)
**Usage:**
- `get radio.rxgain`
@@ -373,6 +466,20 @@ Radio parameters are common to all roles and handled by `CommonRadioPrefs`.
---
#### GPS key action
**Usage:**
- `set ui.gps_action <action>`
- `get ui.gps_action`
**Parameters:**
- `action`: `toggle` (or `0`) to switch the GPS on and off, `once` (or `trigger`, `1`) to acquire a fix on demand, as `gps once`
**Default:** `toggle`, or `once` on boards with a GPS switch
**Note:** Only used by the `ui-new` screens for now.
---
#### Node discovery screen shows nodes names
**Usage:**
- `set ui.nd_name <state>`
+46
View File
@@ -1008,6 +1008,8 @@ void MyMesh::begin() {
_prefs.tx_power_dbm = constrain(_prefs.tx_power_dbm, -9, MAX_LORA_TX_POWER);
_prefs.gps_enabled = constrain(_prefs.gps_enabled, 0, 2); // 0 off, 1 on, 2 duty cycle
_prefs.gps_interval = constrain(_prefs.gps_interval, 0, 86400); // Max 24 hours
_prefs.adc_multiplier = constrain(_prefs.adc_multiplier, 0.0f, 10.0f);
if (!board.setAdcMultiplier(_prefs.adc_multiplier)) _prefs.adc_multiplier = 0.0f;
_active_ble_pin = _prefs.ble_pin;
@@ -2136,6 +2138,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(); }
@@ -2266,6 +2273,33 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char*
return true;
}
if (memcmp(command, "set adc.multiplier ", 19) == 0) { // same as CommonCLI
float mult = atof(&command[19]);
if (mult < 0.0f || mult > 10.0f) {
strcpy(reply, "Error, must be from 0 to 10");
} else if (board.setAdcMultiplier(mult)) {
_prefs.adc_multiplier = mult;
savePrefs();
if (mult == 0.0f) {
strcpy(reply, "OK - using default board multiplier");
} else {
sprintf(reply, "OK - multiplier set to %.3f", mult);
}
} else {
strcpy(reply, "Error: unsupported");
}
return true;
}
if (strcmp(command, "get adc.multiplier") == 0) {
float mult = board.getAdcMultiplier();
if (mult == 0.0f) {
strcpy(reply, "Error: unsupported");
} else {
sprintf(reply, "> %.3f", mult);
}
return true;
}
if (strcmp(command, "get tz.offset") == 0) {
float q = _prefs.tz_offset * 4;
sprintf(reply, (q == (int)q && ((int)q & 1)) ? "> %.2f" : "> %.1f", _prefs.tz_offset);
@@ -2342,6 +2376,18 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char*
sprintf(reply, "> ui.nd_name is now %d", _prefs.ui_nd_name);
return true;
}
if (memcmp(command, "set ui.gps_action", 17) == 0) {
const char* v = &command[17];
while (*v == ' ') v++;
_prefs.ui_gps_action = (memcmp(v, "once", 4) == 0 || memcmp(v, "trigger", 7) == 0 || *v == '1') ? 1 : 0; // anything else: toggle
savePrefs();
sprintf(reply, "> now %s", _prefs.ui_gps_action ? "once" : "toggle");
return true;
}
if (memcmp(command, "get ui.gps_action", 17) == 0) {
sprintf(reply, "> %s", _prefs.ui_gps_action ? "once" : "toggle");
return true;
}
if (memcmp(command, "get ui.show_clock", 17) == 0) {
sprintf(reply, "> %d", _prefs.ui_show_clock);
return true;
+9 -6
View File
@@ -208,13 +208,16 @@ public:
#if ENV_INCLUDE_GPS == 1
void applyGpsPrefs() {
// 0 off / 1 on / 2 duty cycle (see EnvironmentSensorManager::gpsDutyLoop)
sensors.setSettingValue("gps", _prefs.gps_enabled == 2 ? "2" : (_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);
// 2 = duty cycle (see EnvironmentSensorManager::gpsDutyLoop); apply() only
// knows on/off, so switch the sensor manager into duty after it
if (_prefs.gps_enabled == 2) sensors.setSettingValue("gps", "2");
}
#endif
+36 -3
View File
@@ -2,6 +2,7 @@
#include <cstdint> // For uint8_t, uint32_t
#include <helpers/ConfigSerializer.h>
#include <helpers/CommonRadioPrefs.h>
#include <helpers/CommonGpsPrefs.h>
#include <helpers/DynamicConfigSerializer.h>
#define TELEM_MODE_DENY 0
@@ -35,6 +36,9 @@ 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
int32_t gps_fence = -1; // GPS_GUARD fence in metres, 0 = off, -1 = build default
uint8_t gps_guard = 1; // GPS_GUARD on/off
uint8_t autoadd_config = 0; // bitmask for auto-add contacts config
uint8_t rx_boosted_gain = 0; // SX126x RX boosted gain mode (0=power saving, 1=boosted)
uint8_t radio_fem_rxgain = 0; // external LoRa FEM RX gain (LNA)
@@ -48,6 +52,7 @@ public:
char default_scope_name[31];
uint8_t default_scope_key[16];
float tz_offset = 0;
float adc_multiplier = 0; // battery ADC multiplier, 0 = board default
#ifdef ENABLE_WIFI_INTERFACE
#ifndef WIFI_SSID
#define WIFI_SSID ""
@@ -85,6 +90,11 @@ public:
uint8_t ui_auto_off_keep_msgs = 1;
uint8_t ui_max_partial = EINK_MAX_PARTIAL_REFRESH;
uint8_t ui_nd_name = 1;
#ifdef PIN_GPS_SWITCH
uint8_t ui_gps_action = 1;
#else
uint8_t ui_gps_action = 0;
#endif
#endif
private:
@@ -151,16 +161,36 @@ 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);
#ifdef GPS_GUARD
def("fence", _parent->gps_fence);
def("guard", _parent->gps_guard);
#endif
}
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(); }
bool getGuardFence(uint32_t& metres) const override {
if (_parent->gps_fence < 0) return false;
metres = (uint32_t)_parent->gps_fence;
return true;
}
void setGuardFence(uint32_t metres) override { _parent->gps_fence = (int32_t)metres; markDirty(); }
bool getGuardEnabled(bool& enabled) const override {
enabled = _parent->gps_guard != 0;
return true;
}
void setGuardEnabled(bool enabled) override { _parent->gps_guard = enabled ? 1 : 0; markDirty(); }
};
GPSPrefs gps;
@@ -194,6 +224,7 @@ private:
def("tel_loc", _parent->telemetry_mode_loc);
def("tel_env", _parent->telemetry_mode_env);
def("tz_offset", _parent->tz_offset);
def("adc_mult", _parent->adc_multiplier);
}
public:
CompanionPrefs(NodePrefs* parent) : _parent(parent) { }
@@ -231,6 +262,7 @@ private:
def("off_blank", _parent->ui_auto_off_blank);
def("off_keep_msgs", _parent->ui_auto_off_keep_msgs);
def("nd_name", _parent->ui_nd_name);
def("gps_act", _parent->ui_gps_action);
}
public:
UI_Prefs(NodePrefs* parent) : _parent(parent) {}
@@ -275,8 +307,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(); }
};
+61 -1
View File
@@ -2,6 +2,11 @@
#include <Mesh.h>
#include "MyMesh.h"
#if defined(ENABLE_WIFI_INTERFACE) && defined(ENABLE_ESP_MDNS)
#define HAS_ESP_MDNS
#include <ESPmDNS.h>
#endif
// Believe it or not, this std C function is busted on some platforms!
static uint32_t _atoi(const char* sp) {
uint32_t n = 0;
@@ -132,6 +137,10 @@ void halt() {
bool wifi_enabled = false; // set at boot from prefs; false also when the effective SSID is blank
#endif
#if defined(DISPLAY_CLASS) && defined(EINK_REFRESH_LOOP)
static void loopDuringDisplayRefresh();
#endif
void setup() {
Serial.begin(115200);
board.begin();
@@ -266,6 +275,36 @@ void setup() {
interface_manager.addInterface(InterfaceType::Ethernet, &ethernet_interface);
#endif
#ifdef HAS_ESP_MDNS
const char* nodeName = the_mesh.getNodeName();
// "meshcore_" prefix + sanitized node name, capped at 63 chars (max DNS label length)
char mdnsName[64];
const size_t prefixLen = snprintf(mdnsName, sizeof(mdnsName), "meshcore_");
size_t pos = prefixLen;
for (size_t i = 0; nodeName[i] != '\0' && pos < sizeof(mdnsName) - 1; ++i) {
const char c = nodeName[i];
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '-' || c == '_') {
mdnsName[pos++] = c;
}
}
mdnsName[pos] = '\0';
if (!MDNS.begin(mdnsName)) {
WIFI_DEBUG_PRINTLN("mDNS failed to start!");
} else {
MDNS.addService("meshcore", "tcp", TCP_PORT);
MDNS.addServiceTxt("meshcore", "tcp", "node-name", nodeName);
MDNS.addServiceTxt("meshcore", "tcp", "firmware-version", FIRMWARE_VERSION);
char protocol[12];
snprintf(protocol, sizeof(protocol), "%d", (int)FIRMWARE_VER_CODE);
MDNS.addServiceTxt("meshcore", "tcp", "protocol-version", (const char*)protocol);
MDNS.addServiceTxt("meshcore", "tcp", "build-date", __DATE__);
MDNS.addServiceTxt("meshcore", "tcp", "build-time", __TIME__);
}
#endif
// add hardware serial interface
#if defined(SERIAL_RX)
companion_serial.setPins(SERIAL_RX, SERIAL_TX);
@@ -284,15 +323,36 @@ void setup() {
#ifdef DISPLAY_CLASS
ui_task.begin(disp, &sensors, the_mesh.getNodePrefs()); // still want to pass this in as dependency, as prefs might be moved
the_mesh.setListener(&ui_task);
#ifdef EINK_REFRESH_LOOP
if (disp != NULL) disp->setBusyHook(loopDuringDisplayRefresh);
#endif
#endif
board.onBootComplete();
}
void loop() {
// Work that must keep running even while the UI is blocked (e.g. by an e-ink refresh).
// Called from loop() and from the display busy hook, so both always run the same set.
static void loopCore() {
the_mesh.loop();
interface_manager.loop();
sensors.loop();
}
#if defined(DISPLAY_CLASS) && defined(EINK_REFRESH_LOOP)
// Runs from inside the e-ink busy wait, so radio/BLE/sensors keep going during a panel refresh.
// Must not touch the display: UI listener callbacks only update state and schedule the next frame.
static void loopDuringDisplayRefresh() {
static bool active = false;
if (active) return;
active = true;
loopCore();
active = false;
}
#endif
void loop() {
loopCore();
#ifdef DISPLAY_CLASS
ui_task.loop();
#endif
+59 -17
View File
@@ -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,
@@ -394,16 +418,28 @@ public:
char buf[50];
int y = 18;
bool gps_state = _task->getGPSState();
#ifdef PIN_GPS_SWITCH
bool hw_gps_state = digitalRead(PIN_GPS_SWITCH);
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");
bool hw_gps_state = nmea != NULL && nmea->isHardwareEnabled();
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 {
char per[12];
formatGpsPeriod(per, sizeof(per), period);
snprintf(buf, sizeof(buf), "%s (%s)", nmea != NULL && nmea->isActive() ? "active" : "sleep", per);
}
#else
strcpy(buf, gps_state ? "gps on" : "gps off");
#endif
display.setColor(UIColor::primary_txt);
display.drawTextLeftAlign(0, y, buf);
if (nmea == NULL) {
@@ -412,8 +448,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");
@@ -599,7 +634,7 @@ public:
}
#if ENV_INCLUDE_GPS == 1
if (c == KEY_ENTER && _page == HomePage::GPS) {
_task->toggleGPS();
if (_node_prefs->ui_gps_action == 1) _task->triggerGPS(); else _task->toggleGPS();
return true;
}
#endif
@@ -1184,16 +1219,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;
}
@@ -1201,6 +1234,15 @@ void UITask::toggleGPS() {
}
}
void UITask::triggerGPS() {
LocationProvider* location = _sensors != NULL ? _sensors->getLocationProvider() : NULL;
if (location != NULL && !(location->hasHardwareEnableState() && !location->isHardwareEnabled())
&& location->startOnce()) {
notify(UIEventType::ack);
}
_next_refresh = 0;
}
void UITask::toggleBuzzer() {
// Toggle buzzer quiet mode
#ifdef PIN_BUZZER
+1
View File
@@ -114,6 +114,7 @@ public:
void toggleBuzzer();
bool getGPSState();
void toggleGPS();
void triggerGPS();
// MyMesh::Listener
void onMessageRecv(mesh::Packet *pkt, const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, const char* text) override;
+3 -2
View File
@@ -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;
}
}
+7 -9
View File
@@ -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) {
@@ -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;
}
+2 -1
View File
@@ -1167,7 +1167,8 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx,
}
}
uint8_t temp[166];
// 5-byte datagram header + 3-byte reflected CLI prefix + 160-byte reply text + NUL
uint8_t temp[169];
char *command = (char *)&data[5];
char *reply = (char *)&temp[5];
if (is_retry) {
+11 -4
View File
@@ -415,10 +415,17 @@ protected:
#if ENV_INCLUDE_GPS == 1
void applyGpsPrefs() {
// 0 off / 1 on / 2 duty cycle -- pass the mode through, not a boolean, or
// a duty-cycled node comes back from a reboot with GPS powered forever.
const char* mode = _prefs.gps_enabled == 2 ? "2" : (_prefs.gps_enabled ? "1" : "0");
sensors.setSettingValue("gps", mode);
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);
// 2 = duty cycle -- apply() only knows on/off, and a duty-cycled node must
// not come back from a reboot with GPS powered forever
if (_prefs.gps_enabled == 2) sensors.setSettingValue("gps", "2");
}
#endif
+4 -3
View File
@@ -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");
@@ -462,7 +462,8 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx,
mesh::Utils::sha256((uint8_t *)&ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key,
PUB_KEY_SIZE);
uint8_t temp[166];
// 5-byte datagram header + 3-byte reflected CLI prefix + 160-byte reply text + NUL
uint8_t temp[169];
bool send_ack;
if (flags == TXT_TYPE_CLI_DATA || flags == TXT_TYPE_CLI_COMMAND) {
if (client->isAdmin()) {
@@ -791,7 +792,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();
+9 -2
View File
@@ -3,7 +3,7 @@
#include <Arduino.h> // needed for PlatformIO
#include <Mesh.h>
#if defined(NRF52_PLATFORM)
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
#include <InternalFileSystem.h>
#elif defined(RP2040_PLATFORM)
#include <LittleFS.h>
@@ -173,7 +173,14 @@ protected:
#if ENV_INCLUDE_GPS == 1
void applyGpsPrefs() {
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
+1 -1
View File
@@ -58,7 +58,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, "");
+2 -1
View File
@@ -671,7 +671,8 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i
// len can be > original length, but 'text' will be padded with zeroes
data[len] = 0; // need to make a C string again, with null terminator
uint8_t temp[166];
// 5-byte datagram header + 3-byte reflected CLI prefix + 160-byte reply text + NUL
uint8_t temp[169];
char *command = (char *) &data[5];
char *reply = (char *) &temp[5];
handleCommand(from, sender_timestamp, command, reply);
+6 -1
View File
@@ -178,7 +178,12 @@ private:
#if ENV_INCLUDE_GPS == 1
void applyGpsPrefs() {
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
};
+2 -1
View File
@@ -271,7 +271,8 @@ void BaseChatMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender
onCommandDataRecv(from, packet, sender_timestamp, text); // let UI know
// NOTE: no ack expected for CLI_DATA replies
} else if (flags == TXT_TYPE_CLI_COMMAND) {
uint8_t temp[166];
// 5-byte datagram header + 3-byte reflected CLI prefix + 160-byte reply text + NUL
uint8_t temp[169];
char *command = (char *)&data[5];
char *reply = (char *)&temp[5];
*reply = 0;
+60 -70
View File
@@ -303,6 +303,7 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
uint32_t curr = getRTCClock()->getCurrentTime();
if (sender_timestamp > curr) {
getRTCClock()->setCurrentTime(sender_timestamp + 1);
CommonGpsPrefs::onClockSetManually(*_sensors);
uint32_t now = getRTCClock()->getCurrentTime();
DateTime dt = DateTime(now);
sprintf(reply, "OK - clock set: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
@@ -329,6 +330,7 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
uint32_t curr = getRTCClock()->getCurrentTime();
if (secs > curr) {
getRTCClock()->setCurrentTime(secs);
CommonGpsPrefs::onClockSetManually(*_sensors);
uint32_t now = getRTCClock()->getCurrentTime();
DateTime dt = DateTime(now);
sprintf(reply, "OK - clock set: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
@@ -529,63 +531,44 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
} else if (*(dp-1) == ' ') {
*(dp-1) = 0; // trim trailing space
}
} 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 duty", 8) == 0) {
// Power GPS only around a clock sync. For a node that runs GPS purely for
// the (volatile) RTC this is the same service at a fraction of the power;
// position keeps coming from prefs, see `gps advert`.
// position keeps coming from prefs, see `set loc`. Duty owns the cadence,
// so a `gps period` left over would fight it.
if (_sensors->setSettingValue("gps", "2")) {
_prefs->getGpsPrefs()->setGpsPeriod(*_sensors, 0);
_prefs->gps_enabled = 2;
savePrefs();
strcpy(reply, "ok");
strcpy(reply, "OK");
} else {
strcpy(reply, "gps toggle not found");
strcpy(reply, "Error, gps toggle not found");
}
} else if (memcmp(command, "gps sync", 8) == 0) {
} else if (strcmp(command, "gps") == 0 && _prefs->gps_enabled == 2) {
// Duty cycle: the receiver is off most of the time BY DESIGN, so the
// generic "on, inactive" would read as a dead GPS. Say which.
LocationProvider * l = _sensors->getLocationProvider();
if (l != NULL) {
l->syncTime();
strcpy(reply, "ok");
sprintf(reply, "> duty, %s, %s, %ld sats",
l->isActive() ? "awake" : "asleep",
l->hasValidFix() ? "fix" : "no fix",
l->satellitesCount());
} 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");
strcpy(reply, "Error, gps provider not found");
}
#endif
} 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 setloc", 10) == 0) {
_prefs->node_lat = _sensors->node_lat;
_prefs->node_lon = _sensors->node_lon;
_prefs->getGpsPrefs()->applyGuardReference(*_sensors);
savePrefs();
strcpy(reply, "ok");
strcpy(reply, "OK");
} else if (memcmp(command, "gps advert", 10) == 0) {
if (strlen(command) == 10) {
switch (_prefs->advert_loc_policy) {
@@ -599,47 +582,22 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
strcpy(reply, "> share");
break;
default:
strcpy(reply, "error");
strcpy(reply, "Error, invalid policy");
}
} else if (memcmp(command+11, "none", 4) == 0) {
_prefs->advert_loc_policy = ADVERT_LOC_NONE;
savePrefs();
strcpy(reply, "ok");
strcpy(reply, "OK");
} else if (memcmp(command+11, "share", 5) == 0) {
_prefs->advert_loc_policy = ADVERT_LOC_SHARE;
savePrefs();
strcpy(reply, "ok");
strcpy(reply, "OK");
} else if (memcmp(command+11, "prefs", 5) == 0) {
_prefs->advert_loc_policy = ADVERT_LOC_PREFS;
savePrefs();
strcpy(reply, "ok");
strcpy(reply, "OK");
} else {
strcpy(reply, "error");
}
} 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 (_prefs->gps_enabled == 2) {
// Duty cycle: the EN pin is off most of the time BY DESIGN, so
// reporting plain "off" here would read as a dead GPS. Say which.
sprintf(reply, "duty, %s, %s, %d sats",
enabled?"awake":"asleep",
fix?"fix":"no fix",
sats);
} else 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");
strcpy(reply, "Error, invalid policy");
}
#endif
} else if (memcmp(command, "powersaving on", 14) == 0) {
@@ -716,6 +674,22 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
savePrefs();
strcpy(reply, "OK");
}
} else if (memcmp(config, "advert.loc ", 11) == 0) {
if (memcmp(config+11, "none", 4) == 0) {
_prefs->advert_loc_policy = ADVERT_LOC_NONE;
savePrefs();
strcpy(reply, "OK");
} else if (memcmp(config+11, "share", 5) == 0) {
_prefs->advert_loc_policy = ADVERT_LOC_SHARE;
savePrefs();
strcpy(reply, "OK");
} else if (memcmp(config+11, "prefs", 5) == 0) {
_prefs->advert_loc_policy = ADVERT_LOC_PREFS;
savePrefs();
strcpy(reply, "OK");
} else {
strcpy(reply, "Error, invalid policy");
}
} else if (memcmp(config, "guest.password ", 15) == 0) {
StrHelper::strncpy(_prefs->guest_password, &config[15], sizeof(_prefs->guest_password));
savePrefs();
@@ -756,10 +730,12 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
strcpy(reply, _prefs->disable_fwd ? "OK - repeat is now OFF" : "OK - repeat is now ON");
} else if (memcmp(config, "lat ", 4) == 0) {
_prefs->node_lat = atof(&config[4]);
_prefs->getGpsPrefs()->applyGuardReference(*_sensors);
savePrefs();
strcpy(reply, "OK");
} else if (memcmp(config, "lon ", 4) == 0) {
_prefs->node_lon = atof(&config[4]);
_prefs->getGpsPrefs()->applyGuardReference(*_sensors);
savePrefs();
strcpy(reply, "OK");
} else if (memcmp(config, "flood.max.unscoped ", 19) == 0) {
@@ -953,6 +929,20 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep
sprintf(reply, "> %d", ((uint32_t) _prefs->flood_advert_interval));
} else if (memcmp(config, "advert.interval", 15) == 0) {
sprintf(reply, "> %d", ((uint32_t) _prefs->advert_interval) * 2);
} else if (memcmp(config, "advert.loc", 10) == 0) {
switch (_prefs->advert_loc_policy) {
case ADVERT_LOC_NONE:
strcpy(reply, "> none");
break;
case ADVERT_LOC_PREFS:
strcpy(reply, "> prefs");
break;
case ADVERT_LOC_SHARE:
strcpy(reply, "> share");
break;
default:
strcpy(reply, "Error, invalid policy");
}
} else if (memcmp(config, "guest.password", 14) == 0) {
sprintf(reply, "> %s", _prefs->guest_password);
} else if (sender_timestamp == 0 && memcmp(config, "prv.key", 7) == 0) { // from serial command line only
+33 -3
View File
@@ -7,6 +7,7 @@
#include <helpers/RegionMap.h>
#include <helpers/ConfigSerializer.h>
#include <helpers/CommonRadioPrefs.h>
#include <helpers/CommonGpsPrefs.h>
#include <helpers/DynamicConfigSerializer.h>
#if defined(WITH_RS232_BRIDGE) || defined(WITH_ESPNOW_BRIDGE)
@@ -61,6 +62,9 @@ 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
int32_t gps_fence = -1; // GPS_GUARD fence in metres, 0 = off, -1 = build default
uint8_t gps_guard = 1; // GPS_GUARD on/off
uint8_t advert_loc_policy = 0;
uint32_t discovery_mod_timestamp = 0;
float adc_multiplier = 0;
@@ -178,16 +182,41 @@ private:
};
BridgePrefs bridge;
class GPSPrefs : public ConfigSerializer {
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);
#ifdef GPS_GUARD
def("fence", _parent->gps_fence);
def("guard", _parent->gps_guard);
#endif
}
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(); }
bool getGuardFence(uint32_t& metres) const override {
if (_parent->gps_fence < 0) return false;
metres = (uint32_t)_parent->gps_fence;
return true;
}
void setGuardFence(uint32_t metres) override { _parent->gps_fence = (int32_t)metres; markDirty(); }
bool getGuardEnabled(bool& enabled) const override {
enabled = _parent->gps_guard != 0;
return true;
}
void setGuardEnabled(bool enabled) override { _parent->gps_guard = enabled ? 1 : 0; markDirty(); }
bool getGuardReference(double& lat, double& lon) const override {
lat = _parent->node_lat;
lon = _parent->node_lon;
return true;
}
};
GPSPrefs gps;
@@ -281,10 +310,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 {
+289
View File
@@ -0,0 +1,289 @@
#include "CommonGpsPrefs.h"
#include <helpers/sensors/LocationProvider.h>
#ifdef GPS_GUARD
#include <helpers/sensors/GpsGuard.h>
#endif
bool CommonGpsPrefs::setGpsEnabled(SensorManager& sensors, bool enabled) {
LocationProvider* location = sensors.getLocationProvider();
if (location == nullptr) return false;
// `gps duty` (setting "2") runs in the sensor manager, above the provider:
// on/off has to leave it there too, or its loop keeps cycling the receiver
const char* mode = sensors.getSettingByKey("gps");
if (mode != nullptr && strcmp(mode, "2") == 0) sensors.setSettingValue("gps", enabled ? "1" : "0");
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;
}
void CommonGpsPrefs::applyGuardReference(SensorManager& sensors) const {
#ifdef GPS_GUARD
LocationProvider* location = sensors.getLocationProvider();
GpsGuard* guard = location != nullptr ? location->getGuard() : nullptr;
double lat, lon;
if (guard != nullptr && getGuardReference(lat, lon)) guard->setReference(lat, lon);
uint32_t fence;
if (guard != nullptr && getGuardFence(fence)) guard->setFence(fence);
bool enabled;
if (guard != nullptr && getGuardEnabled(enabled)) guard->setEnabled(enabled);
#endif
}
// The clock was set by hand: the guard drops its GPS time anchor and any alert.
void CommonGpsPrefs::onClockSetManually(SensorManager& sensors) {
#ifdef GPS_GUARD
LocationProvider* location = sensors.getLocationProvider();
GpsGuard* guard = location != nullptr ? location->getGuard() : nullptr;
if (guard != nullptr) guard->clockSetManually();
#endif
}
bool CommonGpsPrefs::apply(SensorManager& sensors) const {
LocationProvider* location = sensors.getLocationProvider();
if (location == nullptr) return false;
applyGuardReference(sensors);
location->setGpsPeriod(getGpsPeriod());
location->setGpsOn(isGpsEnabled());
return true;
}
// 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();
char mode[32];
if (getGpsPeriod() == 0) {
strcpy(mode, "continuous");
} else {
snprintf(mode, sizeof(mode), "periodic (%lus)",
(unsigned long)getGpsPeriod());
}
if (location == nullptr) {
strcpy(reply, "Error, gps provider not found");
} else if (location->isGpsOn()) {
const char* activity = "active";
if (!location->isActive()) {
if (location->hasHardwareEnableState() && !location->isHardwareEnabled()) {
activity = "off(hw)";
} else if (getGpsPeriod() > 0) {
activity = "waiting";
} else {
activity = "inactive";
}
}
char fix[32];
if (location->hasValidFix()) {
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");
}
snprintf(reply, 160, "> on, %s, %s, %s", activity, fix, mode);
} else {
snprintf(reply, 160, "> off, %s", mode);
}
return true;
}
if (strcmp(command, "gps fix") == 0) {
LocationProvider* location = sensors.getLocationProvider();
char acq[16] = "";
if (location == nullptr) {
strcpy(reply, "Error, gps provider not found");
return true;
}
if (location->isActive()) {
char t[12];
formatDuration(t, sizeof(t), location->getAcquisitionAge());
snprintf(acq, sizeof(acq), "acq %s", t);
}
if (!location->hasValidFix()) {
snprintf(reply, 160, "> No fix%s%s", acq[0] ? ", " : "", acq);
} else {
const long latitude = location->getLatitude();
const long longitude = location->getLongitude();
char pos[40];
snprintf(pos, sizeof(pos), "%.6f, %.6f", latitude / 1e6, longitude / 1e6);
if (location->isValid()) {
snprintf(reply, 160, "> Fix (%d sat): %s", location->satellitesCount(), pos);
} else {
char age[12];
formatDuration(age, sizeof(age), location->getLastFixAge());
snprintf(reply, 160, "> Fix %s ago (%d sat)%s%s: %s", age, location->satellitesCount(),acq[0] ? ", " : "", acq, pos);
}
}
return true;
}
if (memcmp(command, "gps once", 8) == 0) { // before "gps on"
LocationProvider* location = sensors.getLocationProvider();
if (location == nullptr) {
strcpy(reply, "Error, gps provider not found");
return true;
}
if (location->hasHardwareEnableState() && !location->isHardwareEnabled()) {
strcpy(reply, "Error, 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, "Error, gps once not supported");
}
return true;
}
if (memcmp(command, "gps on", 6) == 0) {
if (!setGpsEnabled(sensors, true)) {
strcpy(reply, "Error, gps toggle not found");
} else {
strcpy(reply, "OK");
}
return true;
}
if (memcmp(command, "gps off", 7) == 0) {
if (!setGpsEnabled(sensors, false)) {
strcpy(reply, "Error, 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;
unsigned long period = strtoul(command + 11, &end, 10);
unsigned long mult = 1;
if (*end == 'm') mult = 60;
else if (*end == 'h') mult = 3600;
else if (*end == 'd') mult = 86400;
if (mult > 1 || *end == 's') end++; // skip the suffix char
if (command[11] == '\0' || *end != '\0') {
strcpy(reply, "Error, invalid gps period");
} else if (!setGpsPeriod(sensors, (uint32_t)(period * mult)) ||
!setGpsEnabled(sensors, true)) {
strcpy(reply, "Error, gps provider not found");
} else {
strcpy(reply, "OK");
}
return true;
}
if (memcmp(command, "gps sync", 8) == 0) {
LocationProvider* location = sensors.getLocationProvider();
if (location == nullptr) {
strcpy(reply, "Error, gps provider not found");
} else {
location->syncTime();
strcpy(reply, "OK");
}
return true;
}
if (strcmp(command, "gps fix_stats") == 0) {
LocationProvider* location = sensors.getLocationProvider();
if (location == nullptr) {
strcpy(reply, "Error, 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;
}
#ifdef GPS_GUARD
if (memcmp(command, "gps guard", 9) == 0 || memcmp(command, "gps fence", 9) == 0 ||
strcmp(command, "gps ref") == 0) {
LocationProvider* location = sensors.getLocationProvider();
GpsGuard* guard = location != nullptr ? location->getGuard() : nullptr;
if (guard == nullptr) {
strcpy(reply, "Error, gps guard not supported");
} else if (strcmp(command, "gps guard") == 0) {
reply[0] = '>'; reply[1] = ' ';
guard->formatStatus(reply + 2, 158);
} else if (strcmp(command, "gps guard on") == 0 || strcmp(command, "gps guard off") == 0) {
const bool enabled = command[11] == 'n';
guard->setEnabled(enabled);
setGuardEnabled(enabled); // saved by the caller (isDirty)
strcpy(reply, "OK");
} else if (strcmp(command, "gps guard accept") == 0) {
// operator confirms that the alerted GPS time is right: apply it to the clock
long offset;
if (!guard->isTimeAlert()) {
strcpy(reply, "Error, no time alert");
} else if (!location->getClockOffset(offset) ||
!guard->acceptAlertedTime(offset, (uint32_t)location->getTimestamp()) ||
!location->applyTimeNow()) {
strcpy(reply, "Error, no current trusted fix with the alerted time");
} else {
strcpy(reply, "OK - clock set from GPS");
}
} else if (strcmp(command, "gps fence") == 0) {
sprintf(reply, "> %lu", (unsigned long)guard->getFence());
} else if (memcmp(command, "gps fence ", 10) == 0) {
char* end;
unsigned long metres = strtoul(command + 10, &end, 10);
if (command[10] == '\0' || *end != '\0' || metres > 20000000UL) { // at most half the Earth
strcpy(reply, "Error, invalid fence");
} else {
guard->setFence((uint32_t)metres);
setGuardFence((uint32_t)metres); // saved by the caller (isDirty)
strcpy(reply, "OK");
}
} else if (strcmp(command, "gps ref") == 0) {
snprintf(reply, 160, "> %.6f, %.6f", guard->getRefLat(), guard->getRefLon());
} else {
return false;
}
return true;
}
#endif
if (strcmp(command, "gps diag") == 0) {
LocationProvider* location = sensors.getLocationProvider();
if (location == nullptr) {
strcpy(reply, "Error, 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;
}
+37
View File
@@ -0,0 +1,37 @@
#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;
// Reference position for the anti-spoofing guard (GPS_GUARD), e.g. the configured node position.
virtual bool getGuardReference(double& lat, double& lon) const { return false; }
// Saved fence radius for the guard; false = not set, use the build default.
virtual bool getGuardFence(uint32_t& metres) const { return false; }
virtual void setGuardFence(uint32_t metres) { }
// Saved on/off state of the guard; false = not set, guard on.
virtual bool getGuardEnabled(bool& enabled) const { return false; }
virtual void setGuardEnabled(bool enabled) { }
bool setGpsEnabled(SensorManager& sensors, bool enabled);
void applyGuardReference(SensorManager& sensors) const;
static void onClockSetManually(SensorManager& sensors);
bool setGpsPeriod(SensorManager& sensors, uint32_t seconds);
bool apply(SensorManager& sensors) const;
bool handleCommand(const char* command, SensorManager& sensors, char* reply);
};
+2
View File
@@ -63,11 +63,13 @@ void ESP32Board::enterDeepSleep(uint32_t secs) {
radio_driver.powerOff();
// Keep LoRa inactive during deepsleep
#ifdef P_LORA_NSS
digitalWrite(P_LORA_NSS, HIGH);
#if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6)
gpio_hold_en((gpio_num_t)P_LORA_NSS);
#else
rtc_gpio_hold_en((gpio_num_t)P_LORA_NSS);
#endif
#endif
// Power off GPS if any
+6
View File
@@ -69,9 +69,11 @@ public:
virtual void powerOff() override;
void enterDeepSleep(uint32_t secs);
#ifdef P_LORA_DIO_1
uint32_t getIRQGpio() override {
return P_LORA_DIO_1; // default for SX1262
}
#endif
void sleep(uint32_t secs) override {
// Skip if not allow to sleep
@@ -82,6 +84,10 @@ public:
// Set GPIO wakeup
gpio_num_t wakeupPin = (gpio_num_t)getIRQGpio();
if (wakeupPin == GPIO_NUM_NC) { // no radio IRQ pin to wake on
delay(1);
return;
}
// Configure timer wakeup
if (secs > 0) {
+4
View File
@@ -14,10 +14,13 @@ public:
digitalWrite(_pin, !_active); // initial state
}
// Both set the level, then make the pin an output again, since other code may have left it
// an input. On a RAK19007 with a RAK12501, WB_IO2 left as an input keeps 3V3_S in its last state.
void claim() {
_claims++;
if (_claims > 0) {
digitalWrite(_pin, _active);
pinMode(_pin, OUTPUT);
}
}
@@ -27,6 +30,7 @@ public:
_claims--;
if (_claims == 0) {
digitalWrite(_pin, !_active);
pinMode(_pin, OUTPUT);
}
}
};
+83
View File
@@ -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(UART_TYPE& serial)
: NmeaGpsDriver(serial, -1, -1, -1, -1, nullptr, HIGH, LOW, GPS_BAUD_RATE) {}
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 isActive() const override {
return digitalRead(GPS_EN) == HIGH;
}
};
-19
View File
@@ -1,19 +0,0 @@
#pragma once
#include <helpers/sensors/LocationProvider.h>
// Board must keep the GPS RTC backup pin powered and can cut GPS power once we return.
// Returns true if the command was acked within 3 attempts, otherwise returns false.
static inline bool airohaEnterSleep(LocationProvider* nmea) {
for (uint8_t attempt = 0; attempt < 3; attempt++) {
nmea->drain();
nmea->sendSentence("$PAIR650,0");
if (nmea->waitFor("$PAIR001,650,0", 50)) { // wait for the command received signal
#ifdef GPS_NMEA_DEBUG
Serial.printf("Airoha RTC Backup sleep command accepted by GPS after %u attempts\r\n", attempt + 1);
#endif
nmea->waitFor("$PAIR650,0", 50); // give the GPS 50ms grace to signal it is ready for sleep
return true;
}
}
return false;
}
+33 -243
View File
@@ -160,56 +160,6 @@ static Adafruit_VL53L0X VL53L0X;
static RAK12035_SoilMoisture RAK12035;
#endif
#if ENV_INCLUDE_GPS && defined(RAK_BOARD) && !defined(RAK_WISMESH_TAG)
#define RAK_WISBLOCK_GPS
#endif
#ifdef RAK_WISBLOCK_GPS
static uint32_t gpsResetPin = 0;
static bool i2cGPSFlag = false;
static bool serialGPSFlag = false;
#ifndef TELEM_RAK12500_ADDRESS
#define TELEM_RAK12500_ADDRESS 0x42 //RAK12500 Ublox GPS via i2c
#endif
#include <SparkFun_u-blox_GNSS_Arduino_Library.h>
static SFE_UBLOX_GNSS ublox_GNSS;
class RAK12500LocationProvider : public LocationProvider {
long _lat = 0;
long _lng = 0;
long _alt = 0;
int _sats = 0;
long _epoch = 0;
bool _fix = false;
public:
long getLatitude() override { return _lat; }
long getLongitude() override { return _lng; }
long getAltitude() override { return _alt; }
long satellitesCount() override { return _sats; }
bool isValid() override { return _fix; }
long getTimestamp() override { return _epoch; }
void sendSentence(const char * sentence) override { }
void reset() override { }
void begin() override { }
void stop() override { }
void loop() override {
if (ublox_GNSS.getGnssFixOk(8)) {
_fix = true;
_lat = ublox_GNSS.getLatitude(2) / 10;
_lng = ublox_GNSS.getLongitude(2) / 10;
_alt = ublox_GNSS.getAltitude(2);
_sats = ublox_GNSS.getSIV(2);
} else {
_fix = false;
}
_epoch = ublox_GNSS.getUnixEpoch(2);
}
bool isEnabled() override { return true; }
};
static RAK12500LocationProvider RAK12500_provider;
#endif
// ============================================================
// I2C bus scanner
// Probes every valid address and records which ones ACK.
@@ -375,14 +325,17 @@ static void query_ina3221(uint8_t ch, uint8_t sub_ch, CayenneLPP& lpp) {
#endif
#if ENV_INCLUDE_INA219
static uint8_t init_ina219(TwoWire* wire, uint8_t) {
// INA219 static instance was constructed with the address; begin() uses it.
return INA219.begin(wire) ? 1 : 0;
static Adafruit_INA219 INA219_ALT((TELEM_INA219_ADDRESS == 0x40) ? 0x41 : 0x40);
static Adafruit_INA219* active_ina219 = &INA219;
static uint8_t init_ina219(TwoWire* wire, uint8_t addr) {
active_ina219 = (addr == TELEM_INA219_ADDRESS) ? &INA219 : &INA219_ALT;
return active_ina219->begin(wire) ? 1 : 0;
}
static void query_ina219(uint8_t ch, uint8_t, CayenneLPP& lpp) {
lpp.addVoltage(ch, INA219.getBusVoltage_V());
lpp.addCurrent(ch, INA219.getCurrent_mA() / 1000.0f);
lpp.addPower(ch, INA219.getPower_mW() / 1000.0f);
lpp.addVoltage(ch, active_ina219->getBusVoltage_V());
lpp.addCurrent(ch, active_ina219->getCurrent_mA() / 1000.0f);
lpp.addPower(ch, active_ina219->getPower_mW() / 1000.0f);
}
#endif
@@ -554,6 +507,7 @@ struct SensorDef {
};
#define TELEM_BOSCH_ALT_ADDR(addr) ((uint8_t)((addr) == 0x76 ? 0x77 : 0x76))
#define TELEM_INA219_ALT_ADDR(addr) ((uint8_t)((addr) == 0x40 ? 0x41 : 0x40))
static const SensorDef SENSOR_TABLE[] = {
#if ENV_INCLUDE_AHTX0
@@ -589,6 +543,7 @@ static const SensorDef SENSOR_TABLE[] = {
#endif
#if ENV_INCLUDE_INA219
{ TELEM_INA219_ADDRESS, "INA219", init_ina219, query_ina219 },
{ TELEM_INA219_ALT_ADDR(TELEM_INA219_ADDRESS), "INA219", init_ina219, query_ina219 },
#endif
#if ENV_INCLUDE_INA260
{ TELEM_INA260_ADDRESS, "INA260", init_ina260, query_ina260 },
@@ -612,6 +567,7 @@ static const SensorDef SENSOR_TABLE[] = {
};
#undef TELEM_BOSCH_ALT_ADDR
#undef TELEM_INA219_ALT_ADDR
static const size_t SENSOR_TABLE_SIZE = (sizeof(SENSOR_TABLE) / sizeof(SENSOR_TABLE[0])) - 1;
@@ -624,12 +580,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
@@ -747,9 +699,11 @@ int EnvironmentSensorManager::scanI2C(char* dest, size_t max_len) {
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->isGpsOn()) {
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++) {
@@ -765,7 +719,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 += 1; // GPS enablement
#endif
return settings;
}
@@ -788,7 +742,7 @@ const char* EnvironmentSensorManager::getSettingValue(int i) const {
// between syncs is not the same thing as `gps off`, and something that
// round-trips this value must not silently downgrade the mode.
if (gps_duty) return "2";
return gps_active ? "1" : "0";
return _location->isGpsOn() ? "1" : "0";
}
#endif
return NULL;
@@ -827,157 +781,16 @@ 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();
#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);
}
#endif
if (gps_detected) {
MESH_DEBUG_PRINTLN("GPS detected");
#ifdef PERSISTANT_GPS
gps_active = true;
return;
#endif
} else {
MESH_DEBUG_PRINTLN("No GPS detected");
}
_location->stop();
gps_active = false; //Set GPS visibility off until setting is changed
gps_detected = _location->autoDetect();
MESH_DEBUG_PRINTLN("%s", gps_detected ? "GPS detected" : "No GPS detected");
}
// 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");
@@ -986,16 +799,16 @@ void EnvironmentSensorManager::start_gps() {
// Powers the receiver only around a clock sync (see gps_duty in the header).
//
// The cadence is owned here, not by MicroNMEALocationProvider's 30-minute
// re-arm, for one concrete reason: while the receiver is off its loop() is not
// called, so nothing feeds the parser -- and MicroNMEA keeps reporting the LAST
// fix as valid. A provider-driven re-arm would therefore sync the RTC to a
// half-hour-old timestamp. Hence syncTime() (which clears the parser) on every
// wake, and our own timer for when the next wake is due.
// The cadence is owned here, not by the provider's `gps period`, because that
// one has no timeout until the first fix ever: a node that never sees the sky
// would keep the receiver (46 mA) powered forever, which is exactly what duty
// exists to avoid. syncTime() (which clears the parser) on every wake, and our
// own timer for when the next wake is due.
// Pull the next duty window forward to now -- see SensorManager::requestLocationRefresh.
void EnvironmentSensorManager::requestLocationRefresh() {
#if ENV_INCLUDE_GPS
if (gps_duty && !gps_active) {
if (gps_duty && !_location->isGpsOn()) {
gps_wake_at = millis();
}
#endif
@@ -1006,7 +819,7 @@ void EnvironmentSensorManager::gpsDutyLoop() {
// int32_t deltas, so the 49-day millis() wrap does not park GPS on (or off)
// forever -- these repeaters run for months between reboots.
if (!gps_active) {
if (!_location->isGpsOn()) {
if ((int32_t)(millis() - gps_wake_at) >= 0) {
start_gps();
_location->syncTime(); // clears the parser + arms the sync request
@@ -1028,20 +841,11 @@ void EnvironmentSensorManager::gpsDutyLoop() {
}
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
@@ -1050,31 +854,17 @@ void EnvironmentSensorManager::loop() {
#if ENV_INCLUDE_GPS
static unsigned long next_gps_update = 0;
if (gps_active) {
_location->loop();
}
_location->loop();
gpsDutyLoop();
if ((long)(millis() - next_gps_update) > 0) {
if(gps_active){
#ifdef RAK_WISBLOCK_GPS
if ((i2cGPSFlag || serialGPSFlag) && _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);
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
@@ -20,13 +20,12 @@ 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
// Duty-cycle state. `gps_duty` is the mode; `gps_active` stays the truth
// about the receiver being powered, so everything that already reads it
// (telemetry, settings) keeps working unchanged.
// Duty-cycle state. `gps_duty` is the mode; the provider's isGpsOn() stays
// the truth about the receiver being powered, so everything that already
// reads it (telemetry, settings) keeps working unchanged.
bool gps_duty = false;
uint32_t gps_wake_at = 0; // millis of the next sync attempt
uint32_t gps_awake_until = 0; // millis the current attempt gives up at
@@ -36,10 +35,6 @@ protected:
void stop_gps();
void gpsDutyLoop();
void initBasicGPS();
#ifdef RAK_BOARD
void rakGPSInit();
bool gpsIsAwake(uint8_t ioPin);
#endif
#endif
public:
+18
View File
@@ -0,0 +1,18 @@
#pragma once
#include <stdint.h>
class GpsDriver {
public:
virtual ~GpsDriver() = default;
virtual void begin() = 0;
virtual void reset() = 0;
virtual void stop() = 0;
virtual bool 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.
virtual bool pollGpsSwitch() { return false; }
virtual bool detect(uint32_t timeout_ms) = 0;
};
+300
View File
@@ -0,0 +1,300 @@
#pragma once
// GPS anti-spoofing guard (opt-in with GPS_GUARD).
//
// A location provider asks the guard before it stores a fix as its last fix and before it
// writes GPS time to the clock:
// - acceptFix(): plausibility checks (satellites, HDOP, optional build-time region, distance
// from a reference position, jump speed) and N consecutive consistent fixes;
// - acceptTime(): GPS time only while a trusted fix is current, not before this firmware
// was built, and once the clock is valid only small corrections (clock drift after the
// first accepted sync), so a spoofer cannot walk the clock away.
// A trusted fix that keeps disagreeing with the clock by the same offset raises an alert;
// the operator can then accept that GPS time (acceptAlertedTime()).
#include <Arduino.h>
#include <MeshCore.h>
#include <RTClib.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#ifndef GPS_GUARD_MIN_SATS
#define GPS_GUARD_MIN_SATS 4
#endif
#ifndef GPS_GUARD_MAX_HDOP10
#define GPS_GUARD_MAX_HDOP10 40 // HDOP 4.0
#endif
#ifndef GPS_GUARD_FENCE_M
#define GPS_GUARD_FENCE_M 1000 // max distance from the reference position (0 = off)
#endif
#ifndef GPS_GUARD_STABLE_FIXES
#define GPS_GUARD_STABLE_FIXES 5 // consecutive consistent fixes (one per GPS second)
#endif
#ifndef GPS_GUARD_STABLE_M
#define GPS_GUARD_STABLE_M 100
#endif
#ifndef GPS_GUARD_MAX_SPEED_KMH
#define GPS_GUARD_MAX_SPEED_KMH 250 // jump limit relative to the last trusted fix
#endif
#ifndef GPS_GUARD_TIME_MAX_STEP
#define GPS_GUARD_TIME_MAX_STEP 600 // max GPS-vs-clock correction (s) once the clock is valid
#endif
#ifndef GPS_GUARD_TIME_DRIFT_BASE
#define GPS_GUARD_TIME_DRIFT_BASE 5 // after the first sync: fixed allowance (s) ...
#endif
#ifndef GPS_GUARD_TIME_DRIFT_PPM
#define GPS_GUARD_TIME_DRIFT_PPM 100 // ... plus clock drift since that sync (~8.6 s/day)
#endif
#ifndef GPS_GUARD_ALERT_MIN
#define GPS_GUARD_ALERT_MIN 60 // alert after GPS disagrees with the clock this long ...
#endif
#ifndef GPS_GUARD_ALERT_TOLERANCE
#define GPS_GUARD_ALERT_TOLERANCE 60 // ... by an offset that stays within this many seconds
#endif
#ifndef GPS_GUARD_TRUSTED_MS
#define GPS_GUARD_TRUSTED_MS 5000 // a trusted fix is "current" for this long
#endif
class GpsGuard {
bool _enabled = true; // off: every fix and GPS time passes, as without GPS_GUARD
double _ref_lat = 0, _ref_lon = 0; // 0,0 = no reference position
uint32_t _fence_m = GPS_GUARD_FENCE_M;
bool _have_trusted = false;
unsigned long _last_trusted_ms = 0;
double _last_trusted_lat = 0, _last_trusted_lon = 0;
double _cand_lat = 0, _cand_lon = 0;
uint32_t _cand_time = 0; // GPS second of the last counted candidate
uint32_t _rej_log_time = 0; // GPS second of the last logged rejection
uint8_t _stable_count = 0;
char _fix_status[24] = "no fix";
char _time_status[24] = "-";
bool _time_accepted = false; // a GPS time sync was accepted (drift budget anchor)
unsigned long _last_time_accept_ms = 0;
bool _time_disagree = false;
long _time_disagree_offset = 0; // GPS minus clock, seconds
unsigned long _time_disagree_since_ms = 0;
bool _time_alert = false;
static double distanceM(double lat1, double lon1, double lat2, double lon2) {
const double R = 6371000.0, D2R = 0.017453292519943295;
double dlat = (lat2 - lat1) * D2R, dlon = (lon2 - lon1) * D2R;
double a = sin(dlat / 2) * sin(dlat / 2) +
cos(lat1 * D2R) * cos(lat2 * D2R) * sin(dlon / 2) * sin(dlon / 2);
return 2 * R * atan2(sqrt(a), sqrt(1 - a));
}
bool trustedFixIsCurrent() const {
return _have_trusted && (uint32_t)(millis() - _last_trusted_ms) <= GPS_GUARD_TRUSTED_MS;
}
void trackTimeDisagreement(long offset) {
const unsigned long now = millis();
if (!_time_disagree || labs(offset - _time_disagree_offset) > GPS_GUARD_ALERT_TOLERANCE) {
_time_disagree = true;
_time_disagree_offset = offset;
_time_disagree_since_ms = now;
_time_alert = false;
return;
}
if (!_time_alert && (uint32_t)(now - _time_disagree_since_ms) >= GPS_GUARD_ALERT_MIN * 60000UL) {
_time_alert = true;
MESH_DEBUG_PRINTLN("GPS TIME ALERT: GPS differs from clock by %lds for %u min", offset, GPS_GUARD_ALERT_MIN);
}
}
public:
// Plausible GPS time window: not before this firmware was built, at most 10 years after.
static uint32_t minEpoch() {
static const uint32_t min_epoch = DateTime(__DATE__, __TIME__).unixtime() - 86400;
return min_epoch;
}
static uint32_t maxEpoch() { return minEpoch() + 10UL * 365 * 86400; }
void setReference(double lat, double lon) { _ref_lat = lat; _ref_lon = lon; }
double getRefLat() const { return _ref_lat; }
double getRefLon() const { return _ref_lon; }
void setFence(uint32_t metres) { _fence_m = metres; }
uint32_t getFence() const { return _fence_m; }
bool hasTrustedFix() const { return _have_trusted; }
bool isEnabled() const { return _enabled; }
void setEnabled(bool enabled) {
if (enabled == _enabled) return;
_enabled = enabled;
// start over: a re-enabled guard needs fresh stable fixes, and no alert survives
_have_trusted = false;
_stable_count = 0;
_time_accepted = false;
_time_disagree = false;
_time_alert = false;
strcpy(_fix_status, "no fix");
strcpy(_time_status, "-");
}
bool isTimeAlert() const { return _time_alert; }
// Fix as reported by the receiver: lat/lon in micro-degrees, HDOP in tenths (255 = unknown),
// gps_time = UTC epoch of the fix. Returns true if the fix can be stored as trusted.
bool acceptFix(long lat_e6, long lon_e6, long sats, uint8_t hdop10, uint32_t gps_time) {
const double lat = lat_e6 / 1000000.0;
const double lon = lon_e6 / 1000000.0;
const unsigned long now = millis();
if (!_enabled) return true;
const char* why = NULL;
double dist = 0;
if (sats < GPS_GUARD_MIN_SATS) {
why = "sats";
} else if (hdop10 == 255 || hdop10 > GPS_GUARD_MAX_HDOP10) {
why = "hdop";
}
#if defined(GPS_GUARD_LAT_MIN) && defined(GPS_GUARD_LAT_MAX) && defined(GPS_GUARD_LON_MIN) && defined(GPS_GUARD_LON_MAX)
else if (lat < GPS_GUARD_LAT_MIN || lat > GPS_GUARD_LAT_MAX || lon < GPS_GUARD_LON_MIN || lon > GPS_GUARD_LON_MAX) {
why = "region";
}
#endif
else if (_fence_m > 0 && (_ref_lat != 0 || _ref_lon != 0) &&
(dist = distanceM(_ref_lat, _ref_lon, lat, lon)) > _fence_m) {
why = "fence";
} else if (_have_trusted) {
dist = distanceM(_last_trusted_lat, _last_trusted_lon, lat, lon);
double secs = (uint32_t)(now - _last_trusted_ms) / 1000.0;
if (secs < 1) secs = 1;
if (dist / secs > GPS_GUARD_MAX_SPEED_KMH / 3.6) why = "jump";
}
if (why) {
_stable_count = 0;
if (dist > 0) {
snprintf(_fix_status, sizeof(_fix_status), "rej %s %.1fkm", why, dist / 1000.0);
} else {
snprintf(_fix_status, sizeof(_fix_status), "rej %s", why);
}
if (gps_time == 0 || gps_time != _rej_log_time) { // GGA and RMC report the same second: log it once
_rej_log_time = gps_time;
MESH_DEBUG_PRINTLN("GPS fix rejected (%s): %f,%f sats=%ld hdop=%u", why, lat, lon, sats, hdop10);
}
return false;
}
if (!_have_trusted || _stable_count < GPS_GUARD_STABLE_FIXES) {
// Require several consecutive, mutually consistent fixes. GGA and RMC report the
// same GPS second: count each second once.
if (_stable_count > 0 && distanceM(_cand_lat, _cand_lon, lat, lon) > GPS_GUARD_STABLE_M) {
_stable_count = 0;
}
if (_stable_count == 0 || gps_time != _cand_time) {
if (_stable_count < 255) _stable_count++;
}
_cand_lat = lat;
_cand_lon = lon;
_cand_time = gps_time;
if (_stable_count < GPS_GUARD_STABLE_FIXES) {
snprintf(_fix_status, sizeof(_fix_status), "settle %u/%u", _stable_count, GPS_GUARD_STABLE_FIXES);
return false;
}
}
if (!_have_trusted) {
MESH_DEBUG_PRINTLN("GPS fix trusted: %f,%f sats=%ld hdop=%u", lat, lon, sats, hdop10);
}
_have_trusted = true;
_last_trusted_ms = now;
_last_trusted_lat = lat;
_last_trusted_lon = lon;
snprintf(_fix_status, sizeof(_fix_status), "ok %ldsat", sats);
return true;
}
// No usable fix right now (e.g. receiver lost the fix): restart the consistency count.
void noFix(long sats) {
_stable_count = 0;
snprintf(_fix_status, sizeof(_fix_status), "no fix %ldsat", sats);
}
// GPS time is only written to the clock while a trusted fix is current, it is not
// older than this firmware, and (once the clock is plausible) it only nudges the clock.
bool acceptTime(uint32_t gps_time, uint32_t clock_time) {
if (!_enabled) return true;
const char* why = NULL;
long step = 0;
if (!trustedFixIsCurrent()) {
why = "nofix";
} else if (gps_time < minEpoch() || gps_time > maxEpoch()) {
why = "range";
} else if (clock_time >= minEpoch() && clock_time <= maxEpoch()) {
// The clock already holds a plausible time. A clock outside that window (e.g. a
// bogus 2080 date at boot) is treated like an unset one, so GPS can correct it.
step = (long)gps_time - (long)clock_time;
long limit = GPS_GUARD_TIME_MAX_STEP;
if (_time_accepted) {
// After the first accepted sync only allow corrections the size of real clock
// drift, so a spoofer cannot walk the clock away in many small steps.
uint32_t elapsed_s = (uint32_t)(millis() - _last_time_accept_ms) / 1000;
limit = GPS_GUARD_TIME_DRIFT_BASE + (long)((uint64_t)elapsed_s * GPS_GUARD_TIME_DRIFT_PPM / 1000000UL);
if (limit > GPS_GUARD_TIME_MAX_STEP) limit = GPS_GUARD_TIME_MAX_STEP;
}
if (labs(step) > limit) why = "step";
}
if (why) {
if (step != 0) {
snprintf(_time_status, sizeof(_time_status), "rej %s %lds", why, step);
trackTimeDisagreement(step);
} else {
snprintf(_time_status, sizeof(_time_status), "rej %s", why);
}
return false;
}
snprintf(_time_status, sizeof(_time_status), "ok %+lds", (long)gps_time - (long)clock_time);
// Every accepted sync anchors the drift budget (fail closed: no walking the clock in
// repeated MAX_STEP jumps). A wrongly anchored time is recovered with a manual clock
// set, which resets the anchor (clockSetManually()).
_time_disagree = false;
_time_alert = false;
_time_accepted = true;
_last_time_accept_ms = millis();
return true;
}
// The clock was set by hand: drop the drift anchor and any alert.
void clockSetManually() {
_time_accepted = false;
_time_disagree = false;
_time_alert = false;
}
// Operator confirms that the alerted GPS time is right. offset = current GPS minus clock.
// Returns true if the caller may write the GPS time to the clock now.
bool acceptAlertedTime(long offset, uint32_t gps_time) {
if (!_time_alert || !trustedFixIsCurrent()) return false;
if (labs(offset - _time_disagree_offset) > GPS_GUARD_ALERT_TOLERANCE) return false; // not the alerted offset
if (gps_time < minEpoch() || gps_time > maxEpoch()) return false;
_time_accepted = true;
_last_time_accept_ms = millis();
_time_disagree = false;
_time_alert = false;
snprintf(_time_status, sizeof(_time_status), "ok manual");
return true;
}
// e.g. "ok 7sat time ok +1s", "ok 7sat time wait", "rej region time rej nofix",
// "ok 9sat time rej step 3600s ALERT gps-clk +3600s 75m"
void formatStatus(char* out, size_t out_size) const {
if (!_enabled) {
snprintf(out, out_size, "off");
return;
}
// The time status is only refreshed when a sync is due. Without a current trusted fix
// (e.g. GPS asleep between periodic fixes) an old "ok" is not shown as current: the last
// check passed and the next one waits for a trusted fix.
const char* time_status = (_time_status[0] == 'o' && !trustedFixIsCurrent()) ? "wait" : _time_status;
if (_time_alert) {
snprintf(out, out_size, "%s time %s ALERT gps-clk %+lds %lum", _fix_status, time_status,
_time_disagree_offset, (unsigned long)((uint32_t)(millis() - _time_disagree_since_ms) / 60000));
} else {
snprintf(out, out_size, "%s time %s", _fix_status, time_status);
}
}
};
+86 -3
View File
@@ -5,34 +5,117 @@
#include <stdio.h>
class GpsGuard;
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
};
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;
virtual void syncTime() { _time_sync_needed = true; }
virtual bool waitingTimeSync() { return _time_sync_needed; }
virtual long getLatitude() = 0;
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 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; }
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
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; }
virtual uint32_t getAcquisitionAge() const { return 0; }
virtual bool startOnce() { return false; }
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;
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.
// Anti-spoofing guard (GPS_GUARD), nullptr if this provider has none
virtual GpsGuard* getGuard() { return nullptr; }
virtual bool getClockOffset(long& offset) { return false; } // GPS time minus clock time
virtual bool applyTimeNow() { return false; } // write GPS time to the clock now
virtual void formatDiagnostics(char* out, size_t out_size) {
if (out_size == 0) return;
snprintf(out, out_size, "en:%u sat:%ld fix:%u",
isEnabled() ? 1U : 0U,
isActive() ? 1U : 0U,
satellitesCount(),
isValid() ? 1U : 0U);
}
+275 -160
View File
@@ -1,69 +1,48 @@
#pragma once
#include "NmeaGpsDriver.h"
#include "LocationProvider.h"
#include <MicroNMEA.h>
#include <RTClib.h>
#include <helpers/RefCountedDigitalPin.h>
#include <string.h>
#ifndef GPS_EN
#ifdef PIN_GPS_EN
#define GPS_EN PIN_GPS_EN
#else
#define GPS_EN (-1)
#endif
#ifdef GPS_GUARD
#include "GpsGuard.h"
#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
#ifndef GPS_PERIODIC_ACQUISITION_TIMEOUT_MS
#define GPS_PERIODIC_ACQUISITION_TIMEOUT_MS 300000UL
#endif
#ifndef GPS_RESET
#ifdef PIN_GPS_RESET
#define GPS_RESET PIN_GPS_RESET
#else
#define GPS_RESET (-1)
#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_RESET_ACTIVE
#ifdef PIN_GPS_RESET_ACTIVE
#define GPS_RESET_ACTIVE PIN_GPS_RESET_ACTIVE
#else
#define GPS_RESET_ACTIVE LOW
#endif
#ifndef GPS_FIX_SETTLE_MS
#define GPS_FIX_SETTLE_MS 10000UL
#endif
class MicroNMEALocationProvider : public LocationProvider {
char _nmeaBuffer[100];
// MicroNMEA never writes past the length it is given, but its fixed-width field
// skips can read a few bytes past the end of a malformed sentence. The zeroed tail
// lets those reads stop on NUL bytes instead of reading the members that follow.
static constexpr size_t NMEA_BUFFER_LEN = 100;
static constexpr size_t NMEA_BUFFER_TAIL = 16;
char _nmeaBuffer[NMEA_BUFFER_LEN + NMEA_BUFFER_TAIL] = {};
MicroNMEA nmea;
mesh::RTCClock* _clock;
Stream* _gps_serial;
RefCountedDigitalPin* _peripher_power;
int8_t _claims = 0;
int _pin_reset;
int _pin_en;
NmeaGpsDriver* _driver;
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;
unsigned long _firstFixInWindow = 0;
bool _acquiringPeriodically = false;
unsigned long _onceDeadline = 0;
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;
@@ -71,10 +50,11 @@ 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;
#ifdef GPS_GUARD
GpsGuard _guard;
#endif
static uint32_t ageMs(unsigned long timestamp) {
return (uint32_t)(millis() - timestamp);
@@ -88,109 +68,226 @@ 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();
_firstFixInWindow = 0;
}
void claim() {
_claims++;
if (_peripher_power) _peripher_power->claim();
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;
}
void release() {
if (_claims == 0) return; // avoid negative _claims
_claims--;
if (_peripher_power) _peripher_power->release();
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;
#ifdef GPS_GUARD
// only plausible, stable fixes become the last fix (position, telemetry, time sync)
if (!_guard.acceptFix(nmea.getLatitude(), nmea.getLongitude(), nmea.getNumSatellites(),
nmea.getHDOP(), getTimestamp())) return false;
#endif
LastFix fix;
fix.latitude = nmea.getLatitude();
fix.longitude = nmea.getLongitude();
// 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() {
if (!isValid() || (millis() - _last_nmea_ms) > 2000) time_valid = 0; // no stale time
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 && timeSyncAllowed()) {
_clock->setCurrentTime(getTimestamp());
_time_sync_needed = false;
_last_time_sync = millis();
}
if (isValid()) time_valid++;
}
bool timeSyncAllowed() {
#ifdef GPS_GUARD
return _guard.acceptTime(getTimestamp(), _clock->getCurrentTime());
#else
return true;
#endif
}
public:
MicroNMEALocationProvider(NmeaGpsDriver& driver, mesh::RTCClock* clock = nullptr)
: nmea(_nmeaBuffer, NMEA_BUFFER_LEN), _clock(clock), _driver(&driver) {}
void begin() override {
_begin_calls++;
claim();
if (_pin_en != -1) {
digitalWrite(_pin_en, GPS_EN_ACTIVE);
_onceDeadline = 0;
const bool wasActive = _driver->isActive();
_driver->begin();
if (!wasActive) {
_acquisitionStarted = millis();
_firstFixInWindow = 0;
}
if (_pin_reset != -1) {
digitalWrite(_pin_reset, !GPS_RESET_ACTIVE);
if (_gpsPeriodSeconds > 0 && _driver->isActive()) {
nmea.clear();
time_valid = 0;
_acquiringPeriodically = true;
_acquisitionStarted = millis();
_firstFixInWindow = 0;
}
}
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();
_onceDeadline = 0;
_acquiringPeriodically = false;
_driver->stop();
nmea.clear();
time_valid = 0;
}
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
}
bool isActive() override {
return _driver->isActive();
}
void syncTime() override { nmea.clear(); LocationProvider::syncTime(); }
long getLatitude() override { return nmea.getLatitude(); }
long getLongitude() override { return nmea.getLongitude(); }
long getAltitude() override {
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;
}
uint32_t getAcquisitionAge() const override {
return (uint32_t)(millis() - _acquisitionStarted) / 1000UL;
}
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();
}
// Position, altitude and satellite count describe the last saved fix
// Before the first saved fix, fall back to the live parser state
// (not with GPS_GUARD: an unverified position is never reported).
#ifdef GPS_GUARD
GpsGuard* getGuard() override { return &_guard; }
bool hasValidFix() override { return _lastFix.valid; }
long getLatitude() override { return _lastFix.latitude; }
long getLongitude() override { return _lastFix.longitude; }
long getAltitude() override { return _lastFix.altitude; }
#else
long getLatitude() override {
return _lastFix.valid ? _lastFix.latitude : nmea.getLatitude();
}
long getLongitude() override {
return _lastFix.valid ? _lastFix.longitude : nmea.getLongitude();
}
long getAltitude() override {
if (_lastFix.valid) return _lastFix.altitude;
long alt = 0;
nmea.getAltitude(alt);
return alt;
}
long satellitesCount() override { return nmea.getNumSatellites(); }
bool isValid() override { return nmea.isValid(); }
#endif
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);
// GPS time minus clock time, from a current fix with a settled time
bool getClockOffset(long& offset) override {
if (_clock == nullptr || !isValid() || time_valid < 3) return false;
offset = (long)getTimestamp() - (long)_clock->getCurrentTime();
return true;
}
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
// write the current GPS time to the clock now (caller has done its own checks)
bool applyTimeNow() override {
if (_clock == nullptr || !isValid() || time_valid < 3) return false;
_clock->setCurrentTime(getTimestamp());
_time_sync_needed = false;
_last_time_sync = millis();
return true;
}
long satellitesCount() override {
return _lastFix.valid ? _lastFix.satellites : nmea.getNumSatellites();
}
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();
}
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 +296,66 @@ public :
}
void loop() override {
if (_driver->pollGpsSwitch()) _gpsOn = true;
while (_gps_serial->available()) {
char c = _gps_serial->read();
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();
}
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();
if (parsed && isValid() &&
(strcmp(message_id, "GGA") == 0 || strcmp(message_id, "RMC") == 0)) {
_last_fix_ms = millis();
_fix_seen = true;
const char* messageId = nmea.getMessageID();
#ifdef GPS_GUARD
if (parsed && !nmea.isValid() &&
(strcmp(messageId, "GGA") == 0 || strcmp(messageId, "RMC") == 0)) {
_guard.noFix(nmea.getNumSatellites());
}
#endif
if (parsed && nmea.isValid() &&
(strcmp(messageId, "GGA") == 0 || strcmp(messageId, "RMC") == 0)) {
if (!saveFix()) continue; // incoherent snapshot
if (_firstFixInWindow == 0) {
_firstFixInWindow = millis();
fixStatsFix((uint32_t)(_firstFixInWindow - _acquisitionStarted));
}
if (_acquiringPeriodically) {
// 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();
}
}
}
} else {
_nmea_checksum_bad++;
@@ -234,25 +363,13 @@ 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 ++;
}
// 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();
}
updateTime();
}
void formatDiagnostics(char* out, size_t out_size) override {
@@ -263,13 +380,11 @@ 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);
// 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,
isActive() ? 1U : 0U,
(unsigned long)_uart_bytes,
uart_age,
(unsigned long)_nmea_checksum_ok,
+350
View File
@@ -0,0 +1,350 @@
#pragma once
#include "GpsDriver.h"
#include <Arduino.h>
#include <helpers/RefCountedDigitalPin.h>
#include <MeshCore.h>
#include <stdlib.h>
#include <string.h>
#ifndef UART_TYPE
#ifdef NRF52_PLATFORM
#define UART_TYPE Uart
#else
#define UART_TYPE HardwareSerial
#endif
#endif
#ifndef PIN_GPS_TX
#define PIN_GPS_TX (-1)
#endif
#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
#ifdef GPS_BAUDRATE
#define GPS_BAUD_RATE GPS_BAUDRATE
#else
#define GPS_BAUD_RATE 9600
#endif
#endif
// Optional rates detect() tries after GPS_BAUD_RATE, for GPS modules whose baud rate is
// not known in advance (e.g. -D GPS_BAUD_PROBE_LIST=9600,115200,38400). Used by every
// NmeaGpsDriver that does not pass its own list.
#ifdef GPS_BAUD_PROBE_LIST
static const uint32_t NMEA_GPS_PROBE_BAUDS[] = { GPS_BAUD_PROBE_LIST };
#define GPS_PROBE_BAUDS NMEA_GPS_PROBE_BAUDS
#define GPS_PROBE_COUNT ((uint8_t)(sizeof(NMEA_GPS_PROBE_BAUDS) / sizeof(NMEA_GPS_PROBE_BAUDS[0])))
#else
#define GPS_PROBE_BAUDS nullptr
#define GPS_PROBE_COUNT 0
#endif
#ifndef PIN_GPS_SWITCH
#define PIN_GPS_SWITCH (-1)
#endif
#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 {
UART_TYPE* _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;
const uint32_t* _probeBauds = nullptr; // optional rates to try in detect(), set by the board
uint8_t _probeCount = 0;
int _hardwareEnablePin = -1;
int _hardwareEnableActive = HIGH;
bool _started = false;
#if !GPS_SWITCH_IS_HARDWARE
bool _requestedOn = false;
bool _switchStateKnown = false;
bool _lastSwitchEnabled = false;
unsigned long _nextSwitchPoll = 0;
#endif
void startHardware() {
if (_hardwareSerial == nullptr || _started) return;
if (_hardwareSerial != nullptr) {
if (_txPin != -1 && _rxPin != -1) {
_hardwareSerial->setPins(_txPin, _rxPin);
}
_hardwareSerial->begin(_baudRate);
}
if (_peripheralPower != nullptr) _peripheralPower->claim();
if (_enablePin != -1) digitalWrite(_enablePin, _enableActive);
if (_resetPin != -1) digitalWrite(_resetPin, !_resetActive);
_started = true;
}
void reopenSerial(uint32_t baud) {
_hardwareSerial->end();
if (_txPin != -1 && _rxPin != -1) {
_hardwareSerial->setPins(_txPin, _rxPin);
}
_hardwareSerial->begin(baud);
drain();
}
// True if a complete NMEA sentence with a valid checksum arrives within timeout_ms.
bool seesValidNmea(uint32_t timeout_ms) {
char line[100];
int len = -1; // -1 = waiting for '$'
const uint32_t start = millis();
while ((uint32_t)(millis() - start) < timeout_ms) {
if (available() <= 0) { delay(2); continue; }
const char c = (char)read();
if (c == '$') { len = 0; continue; }
if (len < 0) continue;
if (c == '\r' || c == '\n') {
line[len] = '\0';
const char* star = strchr(line, '*');
if (star != nullptr && strlen(star) >= 3) {
uint8_t sum = 0;
for (const char* p = line; p < star; p++) sum ^= (uint8_t)*p;
if (sum == (uint8_t)strtoul(star + 1, nullptr, 16)) return true;
}
len = -1;
} else if (len < (int)sizeof(line) - 1) {
line[len++] = c;
} else {
len = -1; // longer than any NMEA sentence: wrong baud rate
}
}
return false;
}
// Bytes arriving does not mean the baud rate is right: at the wrong rate the
// parser only sees garbage and never gets a fix. Try the configured rate, then the
// board's list, and keep the first that yields valid NMEA. The rate is kept in
// _baudRate, so later power cycles reopen the UART with it.
bool tryBaudRate(uint32_t baud) {
reopenSerial(baud);
if (!seesValidNmea(2000)) return false;
_baudRate = baud;
MESH_DEBUG_PRINTLN("GPS baud rate: %lu", (unsigned long)_baudRate);
return true;
}
void detectBaudRate() {
const uint32_t configured = _baudRate;
if (tryBaudRate(configured)) return;
for (uint8_t i = 0; i < _probeCount; i++) {
if (_probeBauds[i] != configured && tryBaudRate(_probeBauds[i])) return;
}
reopenSerial(configured);
MESH_DEBUG_PRINTLN("GPS baud rate not detected, using %lu", (unsigned long)configured);
}
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(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,
const uint32_t* probeBauds = GPS_PROBE_BAUDS, uint8_t probeCount = GPS_PROBE_COUNT)
: _hardwareSerial(&serial), _peripheralPower(peripheralPower), _txPin(txPin), _rxPin(rxPin),
_resetPin(resetPin), _enablePin(enablePin), _enableActive(enableActive),
_resetActive(resetActive), _baudRate(baudRate),
_probeBauds(probeBauds), _probeCount(probeBauds != nullptr ? probeCount : 0),
_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);
}
}
// Board with a GPS whose baud rate is not known in advance: detect() also tries the
// rates in probeBauds (after the configured one). The array must stay valid (static).
NmeaGpsDriver(UART_TYPE& serial, const uint32_t* probeBauds, uint8_t probeCount)
: NmeaGpsDriver(serial, PIN_GPS_TX, PIN_GPS_RX, GPS_RESET, GPS_EN, nullptr,
GPS_EN_ACTIVE, GPS_RESET_ACTIVE, GPS_BAUD_RATE, PIN_GPS_SWITCH,
GPS_SWITCH_ACTIVE, probeBauds, probeCount) {}
void begin() override {
#if !GPS_SWITCH_IS_HARDWARE
_requestedOn = true;
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 isActive() 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 {
bool found = available() > 0;
const uint32_t deadline = millis() + timeout_ms;
while (!found && (int32_t)(millis() - deadline) < 0) {
found = available() > 0;
if (!found) delay(10);
}
// only on a real detection (timeout > 0), not on the quick "still active?" polls
if (found && timeout_ms > 0 && _probeCount > 0 && _started && _hardwareSerial != nullptr) {
detectBaudRate();
}
return found;
}
int available() {
return _hardwareSerial == nullptr ? 0 : _hardwareSerial->available();
}
int read() {
return _hardwareSerial == nullptr ? -1 : _hardwareSerial->read();
}
void drain() {
while (available() > 0) read();
}
void sendNmeaSentence(const char* sentence) {
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++;
_hardwareSerial->print(sentence);
if (*p == '\0') {
char checksumSuffix[6];
snprintf(checksumSuffix, sizeof(checksumSuffix), "*%02X\r\n", checksum);
_hardwareSerial->print(checksumSuffix);
} else {
_hardwareSerial->print("\r\n");
}
}
};
+96
View File
@@ -0,0 +1,96 @@
#pragma once
#include "GpsDriver.h"
#include <SparkFun_u-blox_GNSS_Arduino_Library.h>
// 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 _detected = false;
bool _started = 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;
return true;
}
#ifndef RAK_3401
pinMode(powerPin, INPUT);
#endif
return false;
}
public:
RakI2cGpsDriver(TwoWire& wire = Wire) : _wire(wire) {}
void begin() override {
if (!_detected) return;
#ifndef RAK_3401
pinMode(_powerPin, OUTPUT);
digitalWrite(_powerPin, HIGH);
#endif
_started = true;
}
void reset() override {}
void stop() override {
if (_detected) {
#ifndef RAK_3401
pinMode(_powerPin, OUTPUT);
digitalWrite(_powerPin, LOW);
#endif
}
_started = false;
}
bool isActive() const override {
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;
if (probeRak12500(WB_IO2) || probeRak12500(WB_IO4) || probeRak12500(WB_IO5)) {
_detected = true;
_started = true;
}
return _detected;
}
bool isDetected() const { return _detected; }
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); }
long getSatellites() { return _gnss.getSIV(2); }
long getTimestamp() { return _gnss.getUnixEpoch(2); }
};
+230
View File
@@ -0,0 +1,230 @@
#pragma once
#include "MicroNMEALocationProvider.h"
#include "NmeaGpsDriver.h"
#include "RakI2cGpsDriver.h"
class RakLocationProvider : public LocationProvider {
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;
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:
// serialPower, if given, switches the serial module's supply (WB_IO2 on WisBlock bases).
RakLocationProvider(RakI2cGpsDriver& driver, mesh::RTCClock* clock = nullptr,
UART_TYPE& serial = Serial1, RefCountedDigitalPin* serialPower = nullptr)
: _driver(driver), _nmeaDriver(serial, PIN_GPS_TX, PIN_GPS_RX, GPS_RESET, GPS_EN, serialPower),
_nmea(_nmeaDriver, clock) {}
void syncTime() override {
LocationProvider::syncTime();
if (!_useI2c) _nmea.syncTime();
}
long getLatitude() override {
return _useI2c ? _lastFix.latitude : _nmea.getLatitude();
}
long getLongitude() override {
return _useI2c ? _lastFix.longitude : _nmea.getLongitude();
}
long getAltitude() override {
return _useI2c ? _lastFix.altitude : _nmea.getAltitude();
}
long satellitesCount() override {
return _useI2c ? _lastFix.satellites : _nmea.satellitesCount();
}
bool isValid() override {
return _useI2c ? _driver.hasFix() : _nmea.isValid();
}
FixStats getFixStats() const override {
return _useI2c ? _fixStats : _nmea.getFixStats();
}
LastFix getLastFix() const override {
return _useI2c ? _lastFix : _nmea.getLastFix();
}
long getTimestamp() override {
return _useI2c ? _lastFix.timestamp : _nmea.getTimestamp();
}
// the anti-spoofing guard (GPS_GUARD) only covers the serial NMEA path
GpsGuard* getGuard() override {
return _useI2c ? nullptr : _nmea.getGuard();
}
bool hasValidFix() override {
return _useI2c ? LocationProvider::hasValidFix() : _nmea.hasValidFix();
}
bool getClockOffset(long& offset) override {
return _useI2c ? false : _nmea.getClockOffset(offset);
}
bool applyTimeNow() override {
return _useI2c ? false : _nmea.applyTimeNow();
}
void sendSentence(const char* sentence) override {
if (!_useI2c) _nmea.sendSentence(sentence);
}
bool waitFor(const char* prefix, uint32_t timeout_ms) override {
return _useI2c ? false : _nmea.waitFor(prefix, timeout_ms);
}
void drain() override {
if (!_useI2c) _nmea.drain();
}
void reset() override {
if (!_useI2c) _nmea.reset();
}
void begin() override {
if (_detected && _useI2c) {
_driver.begin();
_acquiringPeriodically = _gpsPeriodSeconds > 0;
_acquisitionStarted = millis();
} else if (_detected) {
_nmea.begin();
} else {
_nmeaDriver.begin();
}
}
void stop() override {
_acquiringPeriodically = false;
if (_useI2c) {
_driver.stop();
} else {
_nmea.stop();
}
}
bool detect(uint32_t timeout_ms) override {
if (_detected) return true;
// the serial module is started first, then the I2C module is probed
_nmeaDriver.begin();
if (_driver.detect(timeout_ms)) {
// The serial driver keeps its claim on serialPower, so the rail stays as it is without one.
// The RAK12500 driver switches its own power pin, and serialPower is only used on the serial path.
_useI2c = true;
} else if (!_nmeaDriver.detect(0)) {
_nmeaDriver.stop();
return false;
}
_detected = true;
if (_useI2c) {
_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 (_useI2c) {
if (_gpsOn) {
if (_gpsPeriodSeconds > 0) {
if (!_acquiringPeriodically &&
(long)(millis() - _nextAcquisition) >= 0) {
_driver.begin();
_acquiringPeriodically = true;
_acquisitionStarted = millis();
}
}
const bool hasCurrentFix = _driver.hasFix();
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();
_acquiringPeriodically = false;
_nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL;
} 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;
}
}
} else {
_nmea.loop();
}
}
bool isActive() override {
return _useI2c ? _driver.isActive() : _nmea.isActive();
}
void setGpsPeriod(uint32_t seconds) override {
_gpsPeriodSeconds = seconds;
_nextAcquisition = millis();
if (!_useI2c) _nmea.setGpsPeriod(seconds);
}
uint32_t getGpsPeriod() const override {
return _gpsPeriodSeconds;
}
bool isGpsOn() const override {
return _useI2c ? _gpsOn : _nmea.isGpsOn();
}
uint32_t getAcquisitionAge() const override {
return _useI2c ? (uint32_t)(millis() - _acquisitionStarted) / 1000UL : _nmea.getAcquisitionAge();
}
bool startOnce() override {
return _useI2c ? false : _nmea.startOnce(); // not supported on the RAK12500
}
void setGpsOn(bool on) override {
if (_useI2c) LocationProvider::setGpsOn(on);
else { _gpsOn = on; _nmea.setGpsOn(on); }
}
};
+1
View File
@@ -24,6 +24,7 @@ public:
virtual bool isOn() = 0;
virtual bool isEink() { return false; } // default to non-eink, override in eink drivers
virtual void forceFullRefresh() {} // next refresh will be full for eink
virtual void setBusyHook(void (*hook)()) {} // eink: hook is called repeatedly while waiting for panel refresh
virtual void turnOn() = 0;
virtual void turnOn(int max_partial) { turnOn(); }
virtual void turnOff() = 0;
+10 -2
View File
@@ -88,7 +88,9 @@ void GxEPDDisplay::drawSleepIcon() {
display.fillRect((x - 5) * scale_x - 1, y * scale_y, (W+5) * scale_x + 2, (H-2) * scale_y + 1, GxEPD_WHITE);
_curr_color = GxEPD_BLACK;
drawXbm(x, y, sleep_icon_24x24, W, H);
if (_busy_hook) display.epd2.setBusyCallback(busyCallback, this);
display.display(true);
display.epd2.setBusyCallback(NULL);
}
void GxEPDDisplay::turnOff(bool blank) {
@@ -99,17 +101,18 @@ void GxEPDDisplay::turnOff(bool blank) {
}
_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
if (_busy_hook) display.epd2.setBusyCallback(busyCallback, this);
display.clearScreen(0xFF); // Clears microcontroller side RAM
display.writeScreenBuffer(0xFF); // Forces 0xFF (White) into the display controller's history registers
display.epd2.setBusyCallback(NULL);
_partial_refresh_count = 0;
last_display_crc_value = 0;
// we can hibernate as screen has been cleaned
display.hibernate();
}
void GxEPDDisplay::clear() {
@@ -126,8 +129,10 @@ void GxEPDDisplay::startFrame(ColorVal bkg) {
|| (_max_partial_refresh > 0
&& _partial_refresh_count >= _max_partial_refresh)) {
// forces a full wipe of the screen ...
if (_busy_hook) display.epd2.setBusyCallback(busyCallback, this);
display.clearScreen(0xFF); // Clears microcontroller side RAM
display.writeScreenBuffer(0xFF); // Forces 0xFF (White) into the display controller's history registers
display.epd2.setBusyCallback(NULL);
// we'll need a partial refresh after that (whatever crc value is)
last_display_crc_value = 0;
_partial_refresh_count = 0;
@@ -239,7 +244,10 @@ void GxEPDDisplay::endFrame() {
if (_isOn == false) return;
uint32_t crc = display_crc.finalize();
if (crc != last_display_crc_value) {
// keep the rest of the firmware running while the panel refreshes (~0.5s partial)
if (_busy_hook) display.epd2.setBusyCallback(busyCallback, this);
display.display(true);
display.epd2.setBusyCallback(NULL);
_partial_refresh_count++;
}
last_display_crc_value = crc;
+7
View File
@@ -39,6 +39,12 @@ class GxEPDDisplay : public DisplayDriver {
bool _force_full_refresh = false;
int _partial_refresh_count = 0;
int _max_partial_refresh = 0;
void (*_busy_hook)() = NULL;
static void busyCallback(const void* self) {
((const GxEPDDisplay*)self)->_busy_hook();
delay(1); // same as GxEPD2 does without a callback
}
public:
#if defined(EINK_DISPLAY_MODEL)
@@ -53,6 +59,7 @@ public:
bool isEink() override { return true; }
void forceFullRefresh() override { _force_full_refresh = true; }
void turnOn(int max_partial) override;
void setBusyHook(void (*hook)()) override { _busy_hook = hook; }
void turnOn() override;
void turnOff(bool blank) override;
void turnOff() override { turnOff(false); }
+6 -1
View File
@@ -25,7 +25,12 @@ bool SSD1306Display::begin() {
#ifdef DISPLAY_ROTATION
display.setRotation(DISPLAY_ROTATION);
#endif
return display.begin(SSD1306_SWITCHCAPVCC, DISPLAY_ADDRESS, true, false) && i2c_probe(Wire, DISPLAY_ADDRESS);
bool success = display.begin(SSD1306_SWITCHCAPVCC, DISPLAY_ADDRESS, true, false);
#if defined(PIN_OLED_CS) && defined(PIN_OLED_DC)
return success;
#else
return success && i2c_probe(Wire, DISPLAY_ADDRESS);
#endif
}
void SSD1306Display::turnOn() {
+8
View File
@@ -15,6 +15,10 @@
#define DISPLAY_ADDRESS 0x3C
#endif
#if defined(PIN_OLED_CS) != defined(PIN_OLED_DC)
#error "SPI OLED requires both PIN_OLED_CS and PIN_OLED_DC"
#endif
class SSD1306Display : public DisplayDriver {
Adafruit_SSD1306 display;
bool _isOn;
@@ -24,7 +28,11 @@ class SSD1306Display : public DisplayDriver {
bool i2c_probe(TwoWire& wire, uint8_t addr);
public:
SSD1306Display(RefCountedDigitalPin* peripher_power=NULL) : DisplayDriver(128, 64),
#if defined(PIN_OLED_CS) && defined(PIN_OLED_DC)
display(128, 64, &SPI, PIN_OLED_DC, PIN_OLED_RESET, PIN_OLED_CS),
#else
display(128, 64, &Wire, PIN_OLED_RESET),
#endif
_peripher_power(peripher_power)
{
_isOn = false;
+3 -2
View File
@@ -102,7 +102,8 @@
static TFT_eSPI lcd = TFT_eSPI(160, 80);
static uint32_t curr_color;
#if defined(HELTEC_LORA_V3) || defined(HELTEC_TRACKER_V2)
#if defined(HELTEC_LORA_V3) || defined(HELTEC_TRACKER_V2) || defined(DFROBOT_LORAWAN_ESP32S3)
// ESP32-S3: HSPI is SPI3. The SX1262 uses FSPI (SPI2) so the two buses do not share a controller.
static SPIClass tft_spi(HSPI);
#define _spi (&tft_spi)
#else
@@ -490,7 +491,7 @@ void ST7735Display::_resetAndInit() {
// run init commands
displayInit(Rcmd1);
#if defined(HELTEC_TRACKER_V2) || defined(HELTEC_T096)
#if defined(HELTEC_TRACKER_V2) || defined(HELTEC_T096) || defined(DFROBOT_LORAWAN_ESP32S3)
displayInit(Rcmd2green160x80);
//uint8_t madctl = ST77XX_MADCTL_MY | ST77XX_MADCTL_MV |ST7735_MADCTL_BGR;//Adjust color to BGR
//display.sendCommand(ST77XX_MADCTL, &madctl, 1);
@@ -0,0 +1,20 @@
#include "DFRobotLoRaBoard.h"
void DFRobotLoRaBoard::begin() {
// SX1262 module power. Held high for the whole boot; Companion does not
// drop into deep sleep, so the pin does not need an RTC hold.
pinMode(LORA_POWER_EN, OUTPUT);
digitalWrite(LORA_POWER_EN, HIGH);
delay(10);
periph_power.begin();
pinMode(PIN_LED, OUTPUT);
digitalWrite(PIN_LED, HIGH);
ESP32Board::begin();
}
const char* DFRobotLoRaBoard::getManufacturerName() const {
return "DFRobot LoRaWAN ESP32-S3";
}
@@ -0,0 +1,15 @@
#pragma once
#include <Arduino.h>
#include <helpers/RefCountedDigitalPin.h>
#include <helpers/ESP32Board.h>
class DFRobotLoRaBoard : public ESP32Board {
public:
RefCountedDigitalPin periph_power;
DFRobotLoRaBoard() : periph_power(PIN_VEXT_EN, PIN_VEXT_EN_ACTIVE) { }
void begin();
const char* getManufacturerName() const override;
};
@@ -0,0 +1,73 @@
; DFRobot LoRaWAN ESP32-S3 (DFR1195)
; ESP32-S3-WROOM-1-N4 (4 MB flash, no PSRAM), SX1262, SPI ST7735S 80x160.
; Pin map follows variants/esp32s3/DFRobot_LoRaWAN_ESP32-S3 in the Meshtastic tree.
; LoRa is on FSPI. The display is on HSPI (SPI3), matching ST7735_SPI_HOST.
[DFRobot_LoRaWAN_ESP32S3]
extends = esp32_base
board = dfrobot_lorawan_esp32s3
; 4 MB module: app slots are 1.9 MB. The default 4 MB table only leaves 1.25 MB.
board_build.partitions = min_spiffs.csv
build_flags =
${esp32_base.build_flags}
-I variants/dfrobot_lorawan_esp32s3
-D DFROBOT_LORAWAN_ESP32S3
-D ESP32_CPU_FREQ=80
-D RADIO_CLASS=CustomSX1262
-D WRAPPER_CLASS=CustomSX1262Wrapper
-D LORA_TX_POWER=22
-D P_LORA_NSS=10
-D P_LORA_DIO_1=4
-D P_LORA_RESET=41
-D P_LORA_BUSY=40
-D P_LORA_SCLK=7
-D P_LORA_MISO=5
-D P_LORA_MOSI=6
-D LORA_POWER_EN=42
-D SX126X_DIO2_AS_RF_SWITCH=true
-D SX126X_DIO3_TCXO_VOLTAGE=3.3
-D SX126X_CURRENT_LIMIT=140
-D SX126X_RX_BOOSTED_GAIN=1
-D PIN_USER_BTN=18
-D PIN_LED=21
-D PIN_VEXT_EN=48
-D PIN_VEXT_EN_ACTIVE=LOW
-D PIN_BOARD_SDA=8
-D PIN_BOARD_SCL=9
-D PIN_TFT_CS=17
-D PIN_TFT_DC=14
-D PIN_TFT_RST=15
-D PIN_TFT_SDA=11
-D PIN_TFT_SCL=12
-D PIN_TFT_LEDA_CTL=16
-D PIN_TFT_LEDA_CTL_ACTIVE=HIGH
build_src_filter = ${esp32_base.build_src_filter}
+<../variants/dfrobot_lorawan_esp32s3>
lib_deps =
${esp32_base.lib_deps}
bodmer/TFT_eSPI @ ^2.4.31
; Landscape UI on the 80x160 panel. Use 3 if the picture is upside down.
[env:DFRobot_LoRaWAN_ESP32S3_companion_radio_ble]
extends = DFRobot_LoRaWAN_ESP32S3
build_flags =
${DFRobot_LoRaWAN_ESP32S3.build_flags}
-I src/helpers/ui
-I examples/companion_radio/ui-new
-D DISPLAY_ROTATION=3
-D DISPLAY_CLASS=ST7735Display
-D MAX_CONTACTS=350
-D MAX_GROUP_CHANNELS=40
-D BLE_PIN_CODE=123456
-D OFFLINE_QUEUE_SIZE=256
; -D BLE_DEBUG_LOGGING=1
; -D MESH_PACKET_LOGGING=1
; -D MESH_DEBUG=1
build_src_filter = ${DFRobot_LoRaWAN_ESP32S3.build_src_filter}
+<helpers/esp32/SerialBLEInterface.cpp>
+<helpers/ui/MomentaryButton.cpp>
+<helpers/ui/ST7735Display.cpp>
+<../examples/companion_radio/*.cpp>
+<../examples/companion_radio/ui-new/*.cpp>
lib_deps =
${DFRobot_LoRaWAN_ESP32S3.lib_deps}
densaugeo/base64 @ ~1.4.0
@@ -0,0 +1,34 @@
#include <Arduino.h>
#include <SPI.h>
#include "target.h"
DFRobotLoRaBoard board;
// FSPI is SPI2. The ST7735 driver takes HSPI (SPI3); the default SPIClass
// constructor on ESP32-S3 is HSPI and would collide with the display.
static SPIClass spi(FSPI);
RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi);
WRAPPER_CLASS radio_driver(radio, board);
ESP32RTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
SensorManager sensors;
#ifdef DISPLAY_CLASS
DISPLAY_CLASS display(&board.periph_power);
// Active-low button, internal pull-up.
MomentaryButton user_btn(PIN_USER_BTN, 1000, true, true);
#endif
bool radio_init() {
fallback_clock.begin();
rtc_clock.begin(Wire);
return radio.std_init(&spi);
}
mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity
}
+26
View File
@@ -0,0 +1,26 @@
#pragma once
#define RADIOLIB_STATIC_ONLY 1
#include <RadioLib.h>
#include <helpers/radiolib/RadioLibWrappers.h>
#include <DFRobotLoRaBoard.h>
#include <helpers/radiolib/CustomSX1262Wrapper.h>
#include <helpers/AutoDiscoverRTCClock.h>
#include <helpers/SensorManager.h>
#ifdef DISPLAY_CLASS
#include <helpers/ui/ST7735Display.h>
#include <helpers/ui/MomentaryButton.h>
#endif
extern DFRobotLoRaBoard board;
extern WRAPPER_CLASS radio_driver;
extern AutoDiscoverRTCClock rtc_clock;
extern SensorManager sensors;
#ifdef DISPLAY_CLASS
extern DISPLAY_CLASS display;
extern MomentaryButton user_btn;
#endif
bool radio_init();
mesh::LocalIdentity radio_new_identity();
+4 -3
View File
@@ -26,9 +26,10 @@ VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#include <helpers/sensors/RakLocationProvider.h>
RakI2cGpsDriver gps_driver;
RakLocationProvider location(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors(location);
#else
EnvironmentSensorManager sensors;
#endif
+2 -1
View File
@@ -26,7 +26,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
+2 -1
View File
@@ -27,7 +27,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
+6 -11
View File
@@ -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() {
@@ -71,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;
@@ -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;
}
-1
View File
@@ -14,7 +14,6 @@
#endif
class SolarSensorManager : public SensorManager {
bool gps_active = false;
bool gps_detected = false;
LocationProvider* _location;
+3 -1
View File
@@ -20,7 +20,9 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, PIN_GPS_RESET, PIN_GPS_EN);
NmeaGpsDriver gps_driver(Serial1, PIN_GPS_TX, PIN_GPS_RX, PIN_GPS_RESET,
PIN_GPS_EN);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
+3 -1
View File
@@ -22,7 +22,9 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, GPS_RESET, GPS_EN, &board.periph_power);
NmeaGpsDriver gps_driver(Serial1, PIN_GPS_TX, PIN_GPS_RX, GPS_RESET, GPS_EN,
&board.periph_power);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
+3 -1
View File
@@ -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;
+2 -1
View File
@@ -22,7 +22,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
+2 -1
View File
@@ -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;
+2 -2
View File
@@ -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
+24 -14
View File
@@ -17,7 +17,25 @@ 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 reset() override {
NmeaGpsDriver::reset();
// Send configuration after reset
if (isActive()) {
delay(250);
sendNmeaSentence("$CFGSYS,h35155*68");
// TODO: remove active wait (250ms is a lot)
}
}
};
HeltecTrackerGpsDriver gps_driver;
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
HWTSensorManager sensors = HWTSensorManager(nmea);
#ifdef DISPLAY_CLASS
@@ -43,23 +61,15 @@ 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() {
// 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;
}
@@ -76,7 +86,7 @@ void HWTSensorManager::loop() {
_location->loop();
if (millis() > next_gps_update) {
if (gps_active && _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;
@@ -93,7 +103,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;
}
-1
View File
@@ -14,7 +14,6 @@
#endif
class HWTSensorManager : public SensorManager {
bool gps_active = false;
LocationProvider * _location;
void start_gps();
+3 -2
View File
@@ -17,7 +17,9 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, GPS_RESET, GPS_EN, &board.periph_power);
NmeaGpsDriver gps_driver(Serial1, PIN_GPS_TX, PIN_GPS_RX, GPS_RESET, GPS_EN,
&board.periph_power);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
@@ -43,4 +45,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity
}
+2 -2
View File
@@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
@@ -43,4 +44,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity
}
+2
View File
@@ -212,6 +212,7 @@ build_flags =
-D BLE_DEBUG_LOGGING=1
-D OFFLINE_QUEUE_SIZE=256
-D ENABLE_WIFI_INTERFACE
-D ENABLE_ESP_MDNS
; -D MESH_PACKET_LOGGING=1
; -D MESH_DEBUG=1
build_src_filter = ${heltec_v4_oled.build_src_filter}
@@ -231,6 +232,7 @@ build_flags =
${heltec_v4_oled.build_flags}
-I examples/companion_radio/ui-new
-D ENABLE_WIFI_INTERFACE
-D ENABLE_ESP_MDNS
-D MAX_CONTACTS=350
-D MAX_GROUP_CHANNELS=40
-D OFFLINE_QUEUE_SIZE=256
+2 -2
View File
@@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
@@ -43,4 +44,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity
}
+3 -1
View File
@@ -17,7 +17,9 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, GPS_RESET, GPS_EN, &board.periph_power);
NmeaGpsDriver gps_driver(Serial1, PIN_GPS_TX, PIN_GPS_RX, GPS_RESET, GPS_EN,
&board.periph_power);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
+2 -2
View File
@@ -12,7 +12,8 @@ VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
@@ -34,4 +35,3 @@ mesh::LocalIdentity radio_new_identity() {
return mesh::LocalIdentity(&rng); // create new random identity
}
+101
View File
@@ -0,0 +1,101 @@
# LilyGO T3 STM32 V1.0
MVP support for the STM32WL55CCU6 board with its integrated Sub-GHz radio and
128×64 SSD1315 SPI OLED. Supports a USB companion and a repeater, with a default
transmit power of **20 dBm**. The companion uses USB serial; the board has no BLE.
## Build
```sh
pio run -e LilyGo_T3_STM32_companion_radio_usb
pio run -e LilyGo_T3_STM32_repeater
```
The companion supports 100 contacts and eight channels. Radio settings inherit
the repository defaults; select settings appropriate to the board's RF band.
Existing saved preferences override build defaults.
## Optional INA219 telemetry
The INA219 builds use MeshCore's existing environment sensor driver to report
voltage, current, and power. Build either role with:
```sh
pio run -e LilyGo_T3_STM32_repeater_ina219
pio run -e LilyGo_T3_STM32_companion_radio_usb_ina219
```
Connect the sensor's logic supply to **3.3 V** and use a common ground:
| INA219 connection | T3 STM32 connection |
| --- | --- |
| VCC / logic supply | 3.3 V |
| GND | GND |
| SDA | PB7 (JP2 pin 9) |
| SCL | PB8 (JP2 pin 10) |
PB7/PB8 are the alternate I2C1 pins exposed on the board headers. The default
STM32 I2C pins, PA9/PA10, are reserved for USB serial. The OLED uses SPI.
The sensor is detected at startup at address **0x40**; to use another address,
override `TELEM_INA219_ADDRESS` in the build flags. An absent sensor produces no
additional telemetry. The base builds do not initialize I2C or include the driver.
The measurement terminals (VIN+ and VIN-) go in series with the positive supply
of the circuit being measured; these are separate from the sensor's logic supply.
See the [INA219 wiring guide](https://learn.adafruit.com/adafruit-ina219-current-sensor-breakout/wiring).
USB power can bypass a sensor placed only in the battery lead.
Readings use environment telemetry permissions. Existing telemetry encodes current
in 1 mA steps and power in whole watts; it does not provide accumulated mAh or
battery percentage. INA219 telemetry has been confirmed on hardware with the
repeater build; the USB companion sensor build has been compile-tested only.
## Flash and connect
Connect the USB serial port. Hold BOOT, press and release RST, then release BOOT:
```sh
pio run -e LilyGo_T3_STM32_companion_radio_usb -t upload --upload-port /dev/ttyACM0
```
Choose your actual serial port, then press RST after programming. The repeater
CLI and USB companion protocol both use USART1 at **115200 baud**.
The bundled `stm32flash` 0.7 may reject device ID `0x497` due to an
[upstream packaging issue](https://github.com/platformio/platform-ststm32/issues/899).
Use an updated [stm32flash](https://sourceforge.net/p/stm32flash/code/ci/master/tree/)
with STM32WL support, or STM32CubeProgrammer in UART mode. For CubeProgrammer,
use `.pio/build/<environment>/firmware.hex`, or `firmware.bin` at `0x08000000`.
ST-Link and J-Link uploads are also available through the board's SWD connector.
Application flash is limited to **224 KiB**. InternalFS occupies the final
32 KiB at `0x08038000`–`0x0803FFFF`; preserve it when updating to retain the
identity and settings.
## Hardware mapping
| Function | Pins / setting |
| --- | --- |
| USART1 | TX PA9, RX PA10 |
| Radio RF switch | PB2/PB6: idle 0/0, RX 1/0, HP TX 0/1 |
| Radio oscillator | 32 MHz crystal; TCXO mode disabled |
| SPI1 | SCK PA5, MISO PA6, MOSI PA7 |
| OLED | CS PB12, DC PA8, no software reset pin |
| SD card | CS PA4, held high |
| User button | PH3/BOOT, active high |
| LEDs | PA0/PA1, left off |
Initialization follows the manufacturer's
[hardware files](https://github.com/Xinyuan-LilyGO/T3-STM32/tree/master/hardware)
and [reference firmware](https://github.com/Xinyuan-LilyGO/T3-STM32/tree/master/examples/6_SubGHz_TXRX).
## MVP validation and limitations
Hardware checks covered OLED startup, USB companion communication, advertisement
reception, Public message transmission, and matching repeater trace replies at
20 dBm. Public packets were captured and decrypted independently. Some repeater
pings timed out; long-term reliability has not been established. Higher transmit
powers are outside the validated MVP setting.
The repeater builds successfully; forwarding has not been hardware-tested.
Built-in battery telemetry, SD storage, and low-power optimization are not implemented.
@@ -0,0 +1,11 @@
#pragma once
#ifdef __cplusplus
// Include the device headers first so subsequent Arduino includes cannot
// reintroduce the peripheral macro. It conflicts with both mesh::RNG and
// Crypto's global RNG object. Leave C HAL sources' register macros intact.
#include <Arduino.h>
#ifdef RNG
#undef RNG
#endif
#endif
+81
View File
@@ -0,0 +1,81 @@
[lilygo_t3_stm32]
extends = stm32_base
board = lilygo_t3_stm32
board_upload.maximum_size = 229376 ; final 32 KiB reserved for InternalFS
build_flags = ${stm32_base.build_flags}
-include variants/lilygo_t3_stm32/STM32ArduinoCompat.h
-I variants/lilygo_t3_stm32
-D RADIO_CLASS=CustomSTM32WLx
-D WRAPPER_CLASS=CustomSTM32WLxWrapper
-D LORA_TX_POWER=20
-D SX126X_CURRENT_LIMIT=140
-D RX_BOOSTED_GAIN=true
-D STM32WL_TCXO_VOLTAGE=0 ; crystal oscillator; manufacturer sets IS_TCXO_SUPPORTED=0
-D PIN_SERIAL_TX=PA9
-D PIN_SERIAL_RX=PA10
-D SERIAL_UART_INSTANCE=1
-D PIN_SPI_SCK=PA5
-D PIN_SPI_MISO=PA6
-D PIN_SPI_MOSI=PA7
-D PIN_OLED_CS=PB12
-D PIN_OLED_DC=PA8
-D PIN_OLED_RESET=-1
-D PIN_USER_BTN=PH3
-D USER_BTN_PRESSED=HIGH
-D DISPLAY_CLASS=SSD1306Display
build_src_filter = ${stm32_base.build_src_filter}
+<../variants/lilygo_t3_stm32>
+<helpers/ui/SSD1306Display.cpp>
lib_deps = ${stm32_base.lib_deps}
adafruit/Adafruit SSD1306 @ ^2.5.13
[env:LilyGo_T3_STM32_repeater]
extends = lilygo_t3_stm32
build_flags = ${lilygo_t3_stm32.build_flags}
-D ADVERT_NAME='"T3 STM32 Repeater"'
-D ADMIN_PASSWORD='"password"'
-D MAX_NEIGHBOURS=50
build_src_filter = ${lilygo_t3_stm32.build_src_filter}
+<../examples/simple_repeater/*.cpp>
[env:LilyGo_T3_STM32_companion_radio_usb]
extends = lilygo_t3_stm32
build_flags = ${lilygo_t3_stm32.build_flags}
-I examples/companion_radio/ui-orig
-D MAX_CONTACTS=100
-D MAX_GROUP_CHANNELS=8
-D ENABLE_USB_INTERFACE
build_src_filter = ${lilygo_t3_stm32.build_src_filter}
+<../examples/companion_radio/*.cpp>
+<../examples/companion_radio/ui-orig/*.cpp>
lib_deps = ${lilygo_t3_stm32.lib_deps}
densaugeo/base64 @ ~1.4.0
; Optional INA219 telemetry on I2C1. Keep the base builds sensor-free.
[lilygo_t3_stm32_ina219]
build_flags =
-D ENV_INCLUDE_INA219=1
-D PIN_WIRE_SDA=PB7
-D PIN_WIRE_SCL=PB8
build_src_filter =
+<helpers/sensors/EnvironmentSensorManager.cpp>
lib_deps =
adafruit/Adafruit INA219 @ ^1.2.3
[env:LilyGo_T3_STM32_repeater_ina219]
extends = env:LilyGo_T3_STM32_repeater
build_flags = ${env:LilyGo_T3_STM32_repeater.build_flags}
${lilygo_t3_stm32_ina219.build_flags}
build_src_filter = ${env:LilyGo_T3_STM32_repeater.build_src_filter}
${lilygo_t3_stm32_ina219.build_src_filter}
lib_deps = ${lilygo_t3_stm32.lib_deps}
${lilygo_t3_stm32_ina219.lib_deps}
[env:LilyGo_T3_STM32_companion_radio_usb_ina219]
extends = env:LilyGo_T3_STM32_companion_radio_usb
build_flags = ${env:LilyGo_T3_STM32_companion_radio_usb.build_flags}
${lilygo_t3_stm32_ina219.build_flags}
build_src_filter = ${env:LilyGo_T3_STM32_companion_radio_usb.build_src_filter}
${lilygo_t3_stm32_ina219.build_src_filter}
lib_deps = ${env:LilyGo_T3_STM32_companion_radio_usb.lib_deps}
${lilygo_t3_stm32_ina219.lib_deps}
+94
View File
@@ -0,0 +1,94 @@
#include <Arduino.h>
#include <SPI.h>
#if ENV_INCLUDE_INA219
#include <Wire.h>
#endif
#include "target.h"
LilyGoT3STM32Board board;
RADIO_CLASS radio = new STM32WLx_Module();
WRAPPER_CLASS radio_driver(radio, board);
VolatileRTCClock rtc_clock;
#if ENV_INCLUDE_INA219
EnvironmentSensorManager sensors;
#else
SensorManager sensors;
#endif
DISPLAY_CLASS display;
// PH3 is also BOOT0: the board's button is active high with an external pull-down.
MomentaryButton user_btn(PIN_USER_BTN, 1000, false);
static const uint32_t rfswitch_pins[] = {
PB2, PB6, RADIOLIB_NC, RADIOLIB_NC, RADIOLIB_NC
};
static const Module::RfSwitchMode_t rfswitch_table[] = {
{STM32WLx::MODE_IDLE, {LOW, LOW}},
{STM32WLx::MODE_RX, {HIGH, LOW}},
{STM32WLx::MODE_TX_HP, {LOW, HIGH}},
END_OF_MODE_TABLE,
};
void LilyGoT3STM32Board::begin() {
STM32Board::begin();
#if ENV_INCLUDE_INA219
// These builds remap Wire to PB7/PB8; PA9/PA10 are used by USART1.
Wire.begin();
#endif
// The SD card shares SPI1 with the OLED; keep it deselected.
digitalWrite(PA4, HIGH);
pinMode(PA4, OUTPUT);
digitalWrite(PIN_OLED_CS, HIGH);
pinMode(PIN_OLED_CS, OUTPUT);
pinMode(PIN_USER_BTN, INPUT);
// Both onboard LEDs are active high. Leave them off until explicitly needed.
digitalWrite(PA0, LOW);
pinMode(PA0, OUTPUT);
digitalWrite(PA1, LOW);
pinMode(PA1, OUTPUT);
SPI.setSCLK(PIN_SPI_SCK);
SPI.setMISO(PIN_SPI_MISO);
SPI.setMOSI(PIN_SPI_MOSI);
SPI.begin();
delay(200); // OLED power-on settling time used by the manufacturer's example.
}
#ifndef LORA_CR
#define LORA_CR 5
#endif
static bool check_radio_status(int status, const char* stage) {
if (status == RADIOLIB_ERR_NONE) return true;
Serial.print("ERROR: ");
Serial.print(stage);
Serial.print(": ");
Serial.println(status);
return false;
}
bool radio_init() {
radio.setRfSwitchTable(rfswitch_pins, rfswitch_table);
int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR,
RADIOLIB_SX126X_SYNC_WORD_PRIVATE, LORA_TX_POWER,
16, STM32WL_TCXO_VOLTAGE, 0);
if (!check_radio_status(status, "radio.begin")) return false;
// Match the manufacturer's 3.3 V power-LDO trim (REG_DRV_CTRL).
const uint8_t power_ldo_3v3 = 0x0E;
status = radio.writeRegister(0x091F, &power_ldo_3v3, 1);
if (!check_radio_status(status, "power LDO trim")) return false;
status = radio.setCurrentLimit(SX126X_CURRENT_LIMIT);
if (!check_radio_status(status, "current limit")) return false;
status = radio.setRxBoostedGainMode(RX_BOOSTED_GAIN);
if (!check_radio_status(status, "RX gain")) return false;
return check_radio_status(radio.setCRC(1), "CRC");
}
mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng);
}
+36
View File
@@ -0,0 +1,36 @@
#pragma once
#include <RadioLib.h>
#include <helpers/stm32/STM32Board.h>
#include <helpers/radiolib/CustomSTM32WLxWrapper.h>
#include <helpers/ArduinoHelpers.h>
#if ENV_INCLUDE_INA219
#include <helpers/sensors/EnvironmentSensorManager.h>
#else
#include <helpers/SensorManager.h>
#endif
#include <helpers/ui/SSD1306Display.h>
#include <helpers/ui/MomentaryButton.h>
class LilyGoT3STM32Board : public STM32Board {
public:
void begin() override;
const char* getManufacturerName() const override {
return "LilyGO T3 STM32";
}
};
extern LilyGoT3STM32Board board;
extern WRAPPER_CLASS radio_driver;
extern VolatileRTCClock rtc_clock;
#if ENV_INCLUDE_INA219
extern EnvironmentSensorManager sensors;
#else
extern SensorManager sensors;
#endif
extern DISPLAY_CLASS display;
extern MomentaryButton user_btn;
bool radio_init();
mesh::LocalIdentity radio_new_identity();
+2 -2
View File
@@ -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
}
+2 -2
View File
@@ -19,7 +19,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
@@ -47,4 +48,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng);
}
+2 -2
View File
@@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
@@ -38,4 +39,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity
}
+2 -1
View File
@@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
@@ -19,7 +19,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
@@ -35,4 +36,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity
}
+2 -1
View File
@@ -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
+2
View File
@@ -93,6 +93,7 @@ build_flags =
${LilyGo_T-Echo.build_flags}
-I src/helpers/ui
-I examples/companion_radio/ui-new
-D EINK_REFRESH_LOOP
-D MAX_CONTACTS=350
-D MAX_GROUP_CHANNELS=40
-D QSPIFLASH=1
@@ -120,6 +121,7 @@ build_flags =
${LilyGo_T-Echo.build_flags}
-I src/helpers/ui
-I examples/companion_radio/ui-new
-D EINK_REFRESH_LOOP
-D MAX_CONTACTS=350
-D MAX_GROUP_CHANNELS=40
-D OFFLINE_QUEUE_SIZE=256
+2 -3
View File
@@ -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
}
+2 -1
View File
@@ -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();
+2 -2
View File
@@ -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
}
+2 -2
View File
@@ -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>
+10 -15
View File
@@ -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,23 +38,17 @@ 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() {
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;
}
@@ -67,8 +62,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 && gps_active) {
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;
@@ -85,7 +80,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;
}
+1 -2
View File
@@ -15,8 +15,7 @@
#endif
class MASensorManager : public SensorManager {
bool gps_active = false;
LocationProvider * _location;
LocationProvider* _location;
void start_gps();
void stop_gps();
+2 -2
View File
@@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
@@ -70,4 +71,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity
}
+8 -19
View File
@@ -1,7 +1,7 @@
#include <Arduino.h>
#include "target.h"
#include <helpers/sensors/AirohaGpsDriver.h>
#include <helpers/sensors/MicroNMEALocationProvider.h>
#include <helpers/sensors/AirohaSleep.h>
MeshTrackerX1Board board;
@@ -10,7 +10,8 @@ RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BU
WRAPPER_CLASS radio_driver(radio, board);
VolatileRTCClock rtc_clock;
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
AirohaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
MeshTrackerX1SensorManager sensors = MeshTrackerX1SensorManager(nmea);
#ifdef DISPLAY_CLASS
@@ -27,28 +28,16 @@ mesh::LocalIdentity radio_new_identity() {
}
void MeshTrackerX1SensorManager::start_gps() {
gps_active = true;
digitalWrite(GPS_EN, HIGH);
delay(10);
digitalWrite(GPS_RTC_INT, HIGH);
delay(5);
digitalWrite(GPS_RTC_INT, LOW);
_nmea->setGpsOn(true);
}
void MeshTrackerX1SensorManager::stop_gps() {
gps_active = false;
digitalWrite(GPS_VRTC_EN, HIGH); // keep GPS RTC alive for faster fix on wake
digitalWrite(GPS_RTC_INT, LOW); // make sure this is LOW so we can pulse it to wake
airohaEnterSleep(_nmea);
digitalWrite(GPS_EN, LOW);
_nmea->setGpsOn(false);
}
bool MeshTrackerX1SensorManager::begin() {
// init GPS
Serial1.begin(GPS_BAUD_RATE);
digitalWrite(GPS_RESET, HIGH);
delay(10);
digitalWrite(GPS_RESET, LOW);
gps_driver.initialize();
// init SPA06-003 barometer
baro_ok = spa06.begin(SPA06_003_DEFAULT_ADDR, &Wire) || spa06.begin(0x76, &Wire);
@@ -81,7 +70,7 @@ void MeshTrackerX1SensorManager::loop() {
_nmea->loop();
if (millis() > next_gps_update) {
if (gps_active && _nmea->isValid()) {
if (_nmea->isGpsOn() && _nmea->hasValidFix()) {
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;
}
-2
View File
@@ -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) { }
+2 -1
View File
@@ -10,7 +10,8 @@ VolatileRTCClock rtc_clock;
extern EnvironmentSensorManager sensors;
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
+12 -16
View File
@@ -13,7 +13,8 @@ VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
MuziBaseSensorManager sensors = MuziBaseSensorManager(nmea);
#else
MuziBaseSensorManager sensors;
@@ -38,13 +39,7 @@ static void muziPowerOff() {
bool MuziBaseSensorManager::begin() {
pwr_btn.begin();
bool ok = EnvironmentSensorManager::begin();
#if ENV_INCLUDE_GPS
pinMode(PIN_GPS_SWITCH, INPUT);
_last_gps_sw = digitalRead(PIN_GPS_SWITCH); // initial gps state from the switch
if (_last_gps_sw == HIGH) start_gps(); else stop_gps();
#endif
return ok;
return EnvironmentSensorManager::begin();
}
void MuziBaseSensorManager::loop() {
@@ -56,14 +51,15 @@ void MuziBaseSensorManager::loop() {
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();
}
// 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();
+3 -3
View File
@@ -38,13 +38,13 @@ 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;
unsigned long _gps_cfg_at = 0;
bool _gps_was_active = false;
#endif
public:
#if ENV_INCLUDE_GPS
+6 -4
View File
@@ -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).
@@ -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
+2 -1
View File
@@ -20,7 +20,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
@@ -0,0 +1,31 @@
#pragma once
#include <helpers/sensors/NmeaGpsDriver.h>
class NanoG2UltraGpsDriver : public NmeaGpsDriver {
public:
NanoG2UltraGpsDriver(UART_TYPE& serial) : NmeaGpsDriver(serial) {
pinMode(PIN_GPS_STANDBY, OUTPUT);
digitalWrite(PIN_GPS_STANDBY, LOW);
}
void begin() override {
if (isActive()) 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;
}
};
+11 -24
View File
@@ -3,6 +3,7 @@
#include <Arduino.h>
#include <helpers/ArduinoHelpers.h>
#include <helpers/sensors/MicroNMEALocationProvider.h>
#include "NanoG2UltraGpsDriver.h"
NanoG2Ultra board;
@@ -12,8 +13,10 @@ WRAPPER_CLASS radio_driver(radio, board);
VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NanoG2UltraSensorManager sensors = NanoG2UltraSensorManager(nmea);
// NanoG2UltraGpsDriver now handles the special init needed for NanoG2
NanoG2UltraGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
NanoG2UltraSensorManager sensors = NanoG2UltraSensorManager(nmea, gps_driver);
#ifdef DISPLAY_CLASS
DISPLAY_CLASS display;
@@ -27,35 +30,19 @@ bool radio_init() {
void NanoG2UltraSensorManager::start_gps() {
MESH_DEBUG_PRINTLN("Starting GPS");
if (!gps_active) {
digitalWrite(PIN_GPS_STANDBY, HIGH); // Wake GPS from standby
Serial1.setPins(PIN_GPS_TX, PIN_GPS_RX);
Serial1.begin(9600);
MESH_DEBUG_PRINTLN("Waiting for gps to power up");
delay(1000);
gps_active = true;
}
_location->begin();
_location->setGpsOn(true);
}
void NanoG2UltraSensorManager::stop_gps() {
MESH_DEBUG_PRINTLN("Stopping GPS");
if (gps_active) {
digitalWrite(PIN_GPS_STANDBY, LOW); // sleep GPS
gps_active = false;
}
_location->stop();
_location->setGpsOn(false);
}
bool NanoG2UltraSensorManager::begin() {
digitalWrite(PIN_GPS_STANDBY, HIGH); // Wake GPS from standby
Serial1.setPins(PIN_GPS_TX, PIN_GPS_RX);
Serial1.begin(9600);
MESH_DEBUG_PRINTLN("Checking GPS switch state");
delay(1000);
// Check initial switch state to determine if GPS should be active
if (Serial1.available() > 0) {
if (_gps_driver->detectAtBoot()) {
MESH_DEBUG_PRINTLN("GPS was on at boot, GPS enabled");
start_gps();
} else {
@@ -75,14 +62,14 @@ bool NanoG2UltraSensorManager::querySensors(uint8_t requester_permissions, Cayen
void NanoG2UltraSensorManager::loop() {
static long next_gps_update = 0;
if (!gps_active) {
if (!_location->isGpsOn()) {
return; // GPS is not active, skip further processing
}
_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;
@@ -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;
}
+5 -3
View File
@@ -14,15 +14,18 @@
#endif
#include <helpers/sensors/LocationProvider.h>
class NanoG2UltraGpsDriver;
class NanoG2UltraSensorManager : public SensorManager {
bool gps_active = false;
LocationProvider *_location;
NanoG2UltraGpsDriver *_gps_driver;
void start_gps();
void stop_gps();
public:
NanoG2UltraSensorManager(LocationProvider &location) : _location(&location) {}
NanoG2UltraSensorManager(LocationProvider &location, NanoG2UltraGpsDriver &gps_driver)
: _location(&location), _gps_driver(&gps_driver) {}
bool begin() override;
bool querySensors(uint8_t requester_permissions, CayenneLPP &telemetry) override;
void loop() override;
@@ -44,4 +47,3 @@ extern MomentaryButton user_btn;
bool radio_init();
mesh::LocalIdentity radio_new_identity();
+57
View File
@@ -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>
Loaded 100 of 140 files, more files were not shown because too many files have changed in this diff. Show more