Merge pull request #3753 from fdlamotte/gps_refactor

Big GPS refactor
This commit is contained in:
fdlamotte authored and GitHub committed 2026-11-10 07:44:00 -04:00
commit 822bea7b7c
97 files changed
+2404 -795

No files matched your search

+76 -4
View File
@@ -999,9 +999,16 @@ region save
---
### GPS (When GPS support is compiled in)
#### View or change GPS state
#### View GPS state
**Usage:**
- `gps`
**Note:** Reports the requested state, receiver activity, last-fix status (last fix gives number of sats and how long ago was the fix), and mode. In periodic mode, `waiting` means the receiver is off between acquisitions; the last fix remains available. `off(hw)` means a hardware GPS switch is off.
---
#### Change GPS state
**Usage:**
- `gps <state>`
**Parameters:**
@@ -1009,9 +1016,30 @@ region save
**Default:** `off`
**Note:** Output format:
- `off` when the GPS hardware is disabled
- `on, {active|deactivated}, {fix|no fix}, {sat count} sats` when the GPS hardware is enabled
---
#### View or change the GPS acquisition period
**Usage:**
- `gps period`
- `gps period <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`.
---
@@ -1021,6 +1049,50 @@ region save
---
#### On demand GPS fix
**Usage:**
- `gps once`
- `gps once -s`
**Parameters:**
- `-s`: also sync this node's clock with GPS time (as `gps sync`)
**Note:** Starts an acquisition now. If the GPS is off, it is switched and kept on until a valid fix and then turned off.
**Reply:** `OK - turning on and acquiring` (GPS was off), `OK - waking gps` (periodic mode, receiver off between acquisitions) or `OK - gps already on`. `Error, gps hw switch off` if a hardware GPS switch is off, `Error, gps once not supported`.
---
#### View GPS time to first fix statistics
**Usage:**
- `gps fix_stats`
**Output:** `> ttf:<last>/<max> ok:<n> miss:<n>`: last and maximum time between a start of the GPS and its first valid fix, then the last count of consecutive starts with a fix (`ok`) or without one (`miss`).
---
#### 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`, or `... ALERT gps-clk +3600s 75m` when a trusted fix has disagreed with the clock by the same offset for `GPS_GUARD_ALERT_MIN` minutes. While the alert is active, the offset in hours is also reported in telemetry on the next free channel.
- `gps guard on`, `gps guard off`: turn the guard on or off (saved, default on). While off, every fix and GPS time is accepted and `gps guard` shows `off`.
- `gps guard accept`: while an alert is active, confirm that the GPS time is right and apply it to the clock.
- `gps fence`, `gps fence <metres>`: fence radius around the configured `lat`/`lon` (`0` = off). Default `GPS_GUARD_FENCE_M` (1000); a value set here is saved.
- `gps ref`: the reference position; follows `set lat`, `set lon` and `gps setloc`.
---
#### Set this node's location based on the GPS coordinates
**Usage:**
- `gps setloc`
+93
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)
@@ -119,6 +120,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 +452,20 @@ Radio parameters are common to all roles and handled by `CommonRadioPrefs`.
---
#### GPS key action
**Usage:**
- `set ui.gps_action <action>`
- `get ui.gps_action`
**Parameters:**
- `action`: `toggle` (or `0`) to switch the GPS on and off, `once` (or `trigger`, `1`) to acquire a fix on demand, as `gps once`
**Default:** `toggle`, or `once` on boards with a GPS switch
**Note:** Only used by the `ui-new` screens for now.
---
#### Node discovery screen shows nodes names
**Usage:**
- `set ui.nd_name <state>`
+17
View File
@@ -2093,6 +2093,11 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char*
return true;
}
if (_prefs.getGpsPrefs()->handleCommand(command, sensors, reply)) {
if (_prefs.getGpsPrefs()->isDirty()) { savePrefs(); }
return true;
}
// hook for variant-specific CLI processing
if (board.handleCommand(command, sender_timestamp, reply)) {
if (_prefs.isDirty()) { savePrefs(); }
@@ -2286,6 +2291,18 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char*
sprintf(reply, "> ui.nd_name is now %d", _prefs.ui_nd_name);
return true;
}
if (memcmp(command, "set ui.gps_action", 17) == 0) {
const char* v = &command[17];
while (*v == ' ') v++;
_prefs.ui_gps_action = (memcmp(v, "once", 4) == 0 || memcmp(v, "trigger", 7) == 0 || *v == '1') ? 1 : 0; // anything else: toggle
savePrefs();
sprintf(reply, "> now %s", _prefs.ui_gps_action ? "once" : "toggle");
return true;
}
if (memcmp(command, "get ui.gps_action", 17) == 0) {
sprintf(reply, "> %s", _prefs.ui_gps_action ? "once" : "toggle");
return true;
}
if (memcmp(command, "get ui.show_clock", 17) == 0) {
sprintf(reply, "> %d", _prefs.ui_show_clock);
return true;
+6 -5
View File
@@ -203,12 +203,13 @@ public:
#if ENV_INCLUDE_GPS == 1
void applyGpsPrefs() {
sensors.setSettingValue("gps", _prefs.gps_enabled ? "1" : "0");
if (_prefs.gps_interval > 0) {
char interval_str[12]; // Max: 24 hours = 86400 seconds (5 digits + null)
sprintf(interval_str, "%u", _prefs.gps_interval);
sensors.setSettingValue("gps_interval", interval_str);
if (_prefs.gps_interval > 0 &&
sensors.getSettingByKey("gps_interval") != nullptr) {
char interval[11];
snprintf(interval, sizeof(interval), "%lu", (unsigned long)_prefs.gps_interval);
sensors.setSettingValue("gps_interval", interval);
}
_prefs.getGpsPrefs()->apply(sensors);
}
#endif
+34 -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)
@@ -85,6 +89,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 +160,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;
@@ -231,6 +260,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 +305,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(); }
};
+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,
@@ -392,16 +416,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) {
@@ -410,8 +446,7 @@ public:
display.drawTextLeftAlign(0, y, "Can't access GPS");
} else {
display.setColor(UIColor::primary_txt);
strcpy(buf, nmea->isValid()?"fix":"no fix");
display.drawTextRightAlign(display.width()-1, y, buf);
display.drawTextRightAlign(display.width()-1, y, fix_buf);
y = y + 12;
display.setColor(UIColor::secondary_txt);
display.drawTextLeftAlign(0, y, "sat");
@@ -597,7 +632,7 @@ public:
}
#if ENV_INCLUDE_GPS == 1
if (c == KEY_ENTER && _page == HomePage::GPS) {
_task->toggleGPS();
if (_node_prefs->ui_gps_action == 1) _task->triggerGPS(); else _task->toggleGPS();
return true;
}
#endif
@@ -1182,16 +1217,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;
}
@@ -1199,6 +1232,15 @@ void UITask::toggleGPS() {
}
}
void UITask::triggerGPS() {
LocationProvider* location = _sensors != NULL ? _sensors->getLocationProvider() : NULL;
if (location != NULL && !(location->hasHardwareEnableState() && !location->isHardwareEnabled())
&& location->startOnce()) {
notify(UIEventType::ack);
}
_next_refresh = 0;
}
void UITask::toggleBuzzer() {
// Toggle buzzer quiet mode
#ifdef PIN_BUZZER
+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;
}
+8 -1
View File
@@ -159,7 +159,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
+8 -1
View File
@@ -168,7 +168,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
+6 -1
View File
@@ -173,7 +173,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
};
+13 -62
View File
@@ -211,6 +211,7 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
uint32_t curr = getRTCClock()->getCurrentTime();
if (sender_timestamp > curr) {
getRTCClock()->setCurrentTime(sender_timestamp + 1);
CommonGpsPrefs::onClockSetManually(*_sensors);
uint32_t now = getRTCClock()->getCurrentTime();
DateTime dt = DateTime(now);
sprintf(reply, "OK - clock set: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
@@ -230,6 +231,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());
@@ -349,52 +351,17 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
*(dp-1) = 0; // remove last CR
}
}
} else if (_prefs->getGpsPrefs()->handleCommand(command, *_sensors, reply)) {
if (_prefs->getGpsPrefs()->isDirty()) savePrefs();
} else if (memcmp(command, "region", 6) == 0) {
handleRegionCmd(command, reply);
#if ENV_INCLUDE_GPS == 1
} else if (memcmp(command, "gps on", 6) == 0) {
if (_sensors->setSettingValue("gps", "1")) {
_prefs->gps_enabled = 1;
savePrefs();
strcpy(reply, "ok");
} else {
strcpy(reply, "gps toggle not found");
}
} else if (memcmp(command, "gps off", 7) == 0) {
if (_sensors->setSettingValue("gps", "0")) {
_prefs->gps_enabled = 0;
savePrefs();
strcpy(reply, "ok");
} else {
strcpy(reply, "gps toggle not found");
}
} else if (memcmp(command, "gps sync", 8) == 0) {
LocationProvider * l = _sensors->getLocationProvider();
if (l != NULL) {
l->syncTime();
strcpy(reply, "ok");
} else {
strcpy(reply, "gps provider not found");
}
} else if (strcmp(command, "gps diag") == 0) {
LocationProvider * l = _sensors->getLocationProvider();
if (l != NULL) {
const char* setting = _sensors->getSettingByKey("gps");
bool requested = setting != NULL && strcmp(setting, "1") == 0;
int prefix_len = snprintf(reply, 160, "req:%u ", requested ? 1U : 0U);
if (prefix_len < 0 || prefix_len >= 160) {
reply[159] = 0;
} else {
l->formatDiagnostics(reply + prefix_len, 160 - prefix_len);
}
} else {
strcpy(reply, "gps provider not found");
}
} else if (memcmp(command, "gps setloc", 10) == 0) {
_prefs->node_lat = _sensors->node_lat;
_prefs->node_lon = _sensors->node_lon;
_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) {
@@ -408,40 +375,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 (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) {
@@ -549,10 +498,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) {
+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;
@@ -152,16 +156,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;
@@ -234,10 +263,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 {
+285
View File
@@ -0,0 +1,285 @@
#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;
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);
};
+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;
}
+23 -229
View File
@@ -1,6 +1,9 @@
#include "EnvironmentSensorManager.h"
#include <Wire.h>
#if ENV_INCLUDE_GPS && defined(GPS_GUARD)
#include <helpers/sensors/GpsGuard.h>
#endif
#if ENV_PIN_SDA && ENV_PIN_SCL
#define TELEM_WIRE &Wire1 // Use Wire1 as the I2C bus for Environment Sensors
@@ -160,56 +163,6 @@ static Adafruit_VL53L0X VL53L0X;
static RAK12035_SoilMoisture RAK12035;
#endif
#if ENV_INCLUDE_GPS && defined(RAK_BOARD) && !defined(RAK_WISMESH_TAG)
#define RAK_WISBLOCK_GPS
#endif
#ifdef RAK_WISBLOCK_GPS
static uint32_t gpsResetPin = 0;
static bool i2cGPSFlag = false;
static bool serialGPSFlag = false;
#ifndef TELEM_RAK12500_ADDRESS
#define TELEM_RAK12500_ADDRESS 0x42 //RAK12500 Ublox GPS via i2c
#endif
#include <SparkFun_u-blox_GNSS_Arduino_Library.h>
static SFE_UBLOX_GNSS ublox_GNSS;
class RAK12500LocationProvider : public LocationProvider {
long _lat = 0;
long _lng = 0;
long _alt = 0;
int _sats = 0;
long _epoch = 0;
bool _fix = false;
public:
long getLatitude() override { return _lat; }
long getLongitude() override { return _lng; }
long getAltitude() override { return _alt; }
long satellitesCount() override { return _sats; }
bool isValid() override { return _fix; }
long getTimestamp() override { return _epoch; }
void sendSentence(const char * sentence) override { }
void reset() override { }
void begin() override { }
void stop() override { }
void loop() override {
if (ublox_GNSS.getGnssFixOk(8)) {
_fix = true;
_lat = ublox_GNSS.getLatitude(2) / 10;
_lng = ublox_GNSS.getLongitude(2) / 10;
_alt = ublox_GNSS.getAltitude(2);
_sats = ublox_GNSS.getSIV(2);
} else {
_fix = false;
}
_epoch = ublox_GNSS.getUnixEpoch(2);
}
bool isEnabled() override { return true; }
};
static RAK12500LocationProvider RAK12500_provider;
#endif
// ============================================================
// I2C bus scanner
// Probes every valid address and records which ones ACK.
@@ -624,12 +577,8 @@ static const size_t SENSOR_TABLE_SIZE = (sizeof(SENSOR_TABLE) / sizeof(SENSOR_TA
bool EnvironmentSensorManager::begin() {
#if ENV_INCLUDE_GPS
#ifdef RAK_WISBLOCK_GPS
rakGPSInit();
#else
initBasicGPS();
#endif
#endif
#if ENV_PIN_SDA && ENV_PIN_SCL
#ifdef NRF52_PLATFORM
@@ -684,15 +633,24 @@ bool EnvironmentSensorManager::begin() {
bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, CayenneLPP& telemetry) {
next_available_channel = TELEM_CHANNEL_SELF + 1;
if (requester_permissions & TELEM_PERM_LOCATION && gps_active) {
#if ENV_INCLUDE_GPS
if (requester_permissions & TELEM_PERM_LOCATION && _location->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++) {
_active_sensors[i].query(next_available_channel, _active_sensors[i].sub_channel, telemetry);
next_available_channel++;
}
#if ENV_INCLUDE_GPS && defined(GPS_GUARD)
// GPS-vs-clock offset in hours on its own channel while the guard's time alert is active
GpsGuard* guard = _location->getGuard();
if (guard != nullptr && guard->isTimeAlert()) {
telemetry.addAnalogInput(next_available_channel++, guard->getAlertOffset() / 3600.0f);
}
#endif
}
return true;
@@ -702,7 +660,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;
}
@@ -721,7 +679,7 @@ const char* EnvironmentSensorManager::getSettingValue(int i) const {
int settings = 0;
#if ENV_INCLUDE_GPS
if (gps_detected && i == settings++) {
return gps_active ? "1" : "0";
return _location->isGpsOn() ? "1" : "0";
}
#endif
return NULL;
@@ -748,157 +706,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");
@@ -906,20 +723,11 @@ void EnvironmentSensorManager::start_gps() {
}
void EnvironmentSensorManager::stop_gps() {
gps_active = false;
#ifdef RAK_WISBLOCK_GPS
#ifndef RAK_3401 // rak3401 shouldn't turn off WB_IO2 as it powers the PA
pinMode(gpsResetPin, OUTPUT);
digitalWrite(gpsResetPin, LOW);
#endif
return;
#endif
_location->setGpsOn(false);
_location->stop();
#ifndef PIN_GPS_EN
#ifndef PIN_GPS_EN
MESH_DEBUG_PRINTLN("Stop GPS is N/A on this board. Actual GPS state unchanged");
#endif
#endif
}
#endif // ENV_INCLUDE_GPS
@@ -928,30 +736,16 @@ void EnvironmentSensorManager::loop() {
#if ENV_INCLUDE_GPS
static unsigned long next_gps_update = 0;
if (gps_active) {
_location->loop();
}
_location->loop();
if ((long)(millis() - next_gps_update) > 0) {
if(gps_active){
#ifdef RAK_WISBLOCK_GPS
if ((i2cGPSFlag || serialGPSFlag) && _location->isValid()) {
if (_location->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,7 +20,6 @@ protected:
uint8_t next_available_channel = TELEM_CHANNEL_SELF + 1;
bool gps_detected = false;
bool gps_active = false;
uint32_t gps_update_interval_sec = 1;
#if ENV_INCLUDE_GPS
@@ -28,10 +27,6 @@ protected:
void start_gps();
void stop_gps();
void initBasicGPS();
#ifdef RAK_BOARD
void rakGPSInit();
bool gpsIsAwake(uint8_t ioPin);
#endif
#endif
public:
+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; }
long getAlertOffset() const { return _time_disagree_offset; }
// Fix as reported by the receiver: lat/lon in micro-degrees, HDOP in tenths (255 = unknown),
// gps_time = UTC epoch of the fix. Returns true if the fix can be stored as trusted.
bool acceptFix(long lat_e6, long lon_e6, long sats, uint8_t hdop10, uint32_t gps_time) {
const double lat = lat_e6 / 1000000.0;
const double lon = lon_e6 / 1000000.0;
const unsigned long now = millis();
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", "rej region time rej nofix",
// "ok 9sat time rej step 3600s ALERT gps-clk +3600s 75m"
void formatStatus(char* out, size_t out_size) const {
if (!_enabled) {
snprintf(out, out_size, "off");
return;
}
// The time status is only refreshed when a sync is due: without a current trusted fix,
// do not keep showing an old "ok" as if GPS time were usable now.
const char* time_status = (_time_status[0] == 'o' && !trustedFixIsCurrent()) ? "rej nofix" : _time_status;
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);
}
+269 -159
View File
@@ -1,69 +1,43 @@
#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 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 +45,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 +63,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, sizeof(_nmeaBuffer)), _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 +291,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 +358,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 +375,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,
+338
View File
@@ -0,0 +1,338 @@
#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
#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 = nullptr, uint8_t probeCount = 0)
: _hardwareSerial(&serial), _peripheralPower(peripheralPower), _txPin(txPin), _rxPin(rxPin),
_resetPin(resetPin), _enablePin(enablePin), _enableActive(enableActive),
_resetActive(resetActive), _baudRate(baudRate),
_probeBauds(probeBauds), _probeCount(probeBauds != nullptr ? probeCount : 0),
_hardwareEnablePin(hardwareEnablePin), _hardwareEnableActive(hardwareEnableActive) {
if (_resetPin != -1) {
pinMode(_resetPin, OUTPUT);
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); }
}
};
+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 -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
}
+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 -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();
+7 -2
View File
@@ -12,7 +12,13 @@ VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
#ifdef GPS_BAUD_PROBE_LIST // e.g. -D GPS_BAUD_PROBE_LIST=9600,38400,115200
static const uint32_t gps_probe_bauds[] = { GPS_BAUD_PROBE_LIST };
NmeaGpsDriver gps_driver(Serial1, gps_probe_bauds, sizeof(gps_probe_bauds) / sizeof(gps_probe_bauds[0]));
#else
NmeaGpsDriver gps_driver(Serial1);
#endif
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
@@ -34,4 +40,3 @@ mesh::LocalIdentity radio_new_identity() {
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
}
+4 -4
View File
@@ -25,9 +25,10 @@ VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#include <helpers/sensors/RakLocationProvider.h>
RakI2cGpsDriver gps_driver;
RakLocationProvider location(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors(location);
#else
EnvironmentSensorManager sensors;
#endif
@@ -41,4 +42,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity
}
+8
View File
@@ -55,6 +55,14 @@ build_src_filter = ${rak4631.build_src_filter}
+<helpers/ui/SSD1306Display.cpp>
+<../examples/simple_repeater>
; Lets `gps off`, periodic mode and shutdown cut the power to a serial GPS (RAK12501).
; WB_IO2 switches the shared 3V3_S slot rail, so this also powers down any other slot module.
[env:RAK_4631_repeater_gps_power]
extends = env:RAK_4631_repeater
build_flags =
${env:RAK_4631_repeater.build_flags}
-D GPS_RAIL_POWER_CONTROL
[env:RAK_4631_repeater_ethernet]
extends = rak4631
build_flags =
+13 -3
View File
@@ -25,9 +25,19 @@ 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;
#ifdef GPS_RAIL_POWER_CONTROL
#ifdef ETHERNET_ENABLED
#error "GPS_RAIL_POWER_CONTROL would cut the RAK13800's power, which also comes from WB_IO2"
#endif
// WB_IO2 switches 3V3_S, which powers the serial GPS and every other slot module.
RefCountedDigitalPin gps_rail(WB_IO2);
RakLocationProvider location(gps_driver, &rtc_clock, Serial1, &gps_rail);
#else
RakLocationProvider location(gps_driver, &rtc_clock);
#endif
EnvironmentSensorManager sensors(location);
#else
EnvironmentSensorManager sensors;
#endif
+2 -2
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;
@@ -37,4 +38,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity
}
@@ -8,7 +8,8 @@ ESPNOWRadio radio_driver;
ESP32RTCClock rtc_clock;
#if defined(ENV_INCLUDE_GPS)
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, (mesh::RTCClock*)&rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, (mesh::RTCClock*)&rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors = EnvironmentSensorManager();
+2 -2
View File
@@ -13,7 +13,8 @@ WRAPPER_CLASS radio_driver(radio, board);
VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
#ifdef ENV_INCLUDE_GPS
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors = EnvironmentSensorManager();
@@ -29,4 +30,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity
}
+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;
@@ -44,4 +45,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;
+1
View File
@@ -106,6 +106,7 @@ build_flags = ${t1000-e.build_flags}
; -D BLE_DEBUG_LOGGING=1
; -D MESH_PACKET_LOGGING=1
; -D MESH_DEBUG=1
; -D GPS_NMEA_DEBUG
-D OFFLINE_QUEUE_SIZE=256
-D DISPLAY_CLASS=NullDisplayDriver
-D PIN_BUZZER=25
+9 -21
View File
@@ -1,8 +1,8 @@
#include <Arduino.h>
#include "t1000e_sensors.h"
#include "target.h"
#include <helpers/sensors/AirohaGpsDriver.h>
#include <helpers/sensors/MicroNMEALocationProvider.h>
#include <helpers/sensors/AirohaSleep.h>
T1000eBoard board;
@@ -11,8 +11,9 @@ RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BU
WRAPPER_CLASS radio_driver(radio, board);
VolatileRTCClock rtc_clock;
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
T1000SensorManager sensors = T1000SensorManager(nmea);
AirohaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
T1000SensorManager sensors(nmea, gps_driver);
#ifdef DISPLAY_CLASS
NullDisplayDriver display;
@@ -81,29 +82,16 @@ mesh::LocalIdentity radio_new_identity() {
}
void T1000SensorManager::start_gps() {
gps_active = true;
digitalWrite(GPS_EN, HIGH);
delay(10);
digitalWrite(GPS_RTC_INT, HIGH);
delay(5);
digitalWrite(GPS_RTC_INT, LOW);
_nmea->setGpsOn(true);
}
void T1000SensorManager::stop_gps() {
gps_active = false;
digitalWrite(GPS_VRTC_EN, HIGH); // keep GPS RTC alive for faster fix on wake
digitalWrite(GPS_RTC_INT, LOW); // make sure this is LOW so we can pulse it to wake
airohaEnterSleep(_nmea); // send command to put the GPS into RTC backup sleep
digitalWrite(GPS_EN, LOW);
_nmea->setGpsOn(false);
}
bool T1000SensorManager::begin() {
// init GPS
Serial1.begin(115200);
digitalWrite(GPS_RESET, HIGH);
delay(10);
digitalWrite(GPS_RESET, LOW);
_gps_driver->initialize();
return true;
}
@@ -125,7 +113,7 @@ void T1000SensorManager::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;
@@ -141,7 +129,7 @@ const char* T1000SensorManager::getSettingName(int i) const {
}
const char* T1000SensorManager::getSettingValue(int i) const {
if (i == 0) {
return gps_active ? "1" : "0";
return _nmea->isGpsOn() ? "1" : "0";
}
return NULL;
}
+5 -2
View File
@@ -12,15 +12,18 @@
#include "NullDisplayDriver.h"
#endif
class AirohaGpsDriver;
class T1000SensorManager: public SensorManager {
bool gps_active = false;
LocationProvider * _nmea;
AirohaGpsDriver* _gps_driver;
void start_gps();
void sleep_gps();
void stop_gps();
public:
T1000SensorManager(LocationProvider &nmea): _nmea(&nmea) { }
T1000SensorManager(LocationProvider &nmea, AirohaGpsDriver& gps_driver)
: _nmea(&nmea), _gps_driver(&gps_driver) { }
bool begin() override;
bool querySensors(uint8_t requester_permissions, CayenneLPP& telemetry) override;
void loop() override;
+2
View File
@@ -117,6 +117,8 @@
#define GPS_RTC_INT (15) // P0.15
#define GPS_RESETB (46) // P1.14
#define GPS_BAUDRATE 115200
////////////////////////////////////////////////////////////////////////////////
// Temp+Lux Sensor
+8 -51
View File
@@ -2,6 +2,7 @@
#include "target.h"
#include <helpers/ArduinoHelpers.h>
#include <helpers/sensors/MicroNMEALocationProvider.h>
#include <helpers/sensors/NmeaGpsDriver.h>
ThinkNodeM1Board board;
@@ -11,7 +12,8 @@ WRAPPER_CLASS radio_driver(radio, board);
VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(gps_driver, &rtc_clock);
ThinkNodeM1SensorManager sensors = ThinkNodeM1SensorManager(nmea);
#ifdef DISPLAY_CLASS
@@ -31,34 +33,15 @@ mesh::LocalIdentity radio_new_identity() {
}
void ThinkNodeM1SensorManager::start_gps() {
if (!gps_active) {
gps_active = true;
_location->begin();
}
_location->setGpsOn(true);
}
void ThinkNodeM1SensorManager::stop_gps() {
if (gps_active) {
gps_active = false;
_location->stop();
}
_location->setGpsOn(false);
}
bool ThinkNodeM1SensorManager::begin() {
Serial1.begin(9600);
// Initialize GPS switch pin
pinMode(PIN_GPS_SWITCH, INPUT);
last_gps_switch_state = digitalRead(PIN_GPS_SWITCH);
// Initialize GPS power pin
pinMode(GPS_EN, OUTPUT);
// Check initial switch state to determine if GPS should be active
if (last_gps_switch_state == HIGH) { // Switch is HIGH when ON
start_gps();
}
start_gps();
return true;
}
@@ -71,36 +54,11 @@ bool ThinkNodeM1SensorManager::querySensors(uint8_t requester_permissions, Cayen
void ThinkNodeM1SensorManager::loop() {
static long next_gps_update = 0;
static long last_switch_check = 0;
// Check GPS switch state every second
if (millis() - last_switch_check > 1000) {
bool current_switch_state = digitalRead(PIN_GPS_SWITCH);
// Detect switch state change
if (current_switch_state != last_gps_switch_state) {
last_gps_switch_state = current_switch_state;
if (current_switch_state == HIGH) { // Switch is ON
MESH_DEBUG_PRINTLN("GPS switch ON");
start_gps();
} else { // Switch is OFF
MESH_DEBUG_PRINTLN("GPS switch OFF");
stop_gps();
}
}
last_switch_check = millis();
}
if (!gps_active) {
return; // GPS is not active, skip further processing
}
_location->loop();
if (millis() > next_gps_update) {
if (_location->isValid()) {
if (_location->isGpsOn() && _location->hasValidFix()) {
node_lat = ((double)_location->getLatitude())/1000000.;
node_lon = ((double)_location->getLongitude())/1000000.;
node_altitude = ((double)_location->getAltitude()) / 1000.0;
@@ -120,7 +78,7 @@ const char* ThinkNodeM1SensorManager::getSettingName(int i) const {
const char* ThinkNodeM1SensorManager::getSettingValue(int i) const {
if (i == 0) {
return gps_active ? "1" : "0";
return _location->isGpsOn() ? "1" : "0";
}
return NULL;
}
@@ -136,4 +94,3 @@ bool ThinkNodeM1SensorManager::setSettingValue(const char* name, const char* val
}
return false; // not supported
}
-3
View File
@@ -14,8 +14,6 @@
#endif
class ThinkNodeM1SensorManager : public SensorManager {
bool gps_active = false;
bool last_gps_switch_state = false;
LocationProvider* _location;
void start_gps();
@@ -45,4 +43,3 @@ extern ThinkNodeM1SensorManager sensors;
bool radio_init();
mesh::LocalIdentity radio_new_identity();
+2
View File
@@ -146,3 +146,5 @@ extern const int SCK;
#define PIN_GPS_PPS (36)
#define PIN_GPS_STANDBY (34)
#define PIN_GPS_SWITCH (33)
#define GPS_SWITCH_IS_HARDWARE (0)
#define GPS_SWITCH_TURNS_GPS_ON (1)
+2 -1
View File
@@ -11,7 +11,8 @@ WRAPPER_CLASS radio_driver(radio, board);
VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
#ifdef ENV_INCLUDE_GPS
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors = EnvironmentSensorManager();
+2 -1
View File
@@ -11,7 +11,8 @@ WRAPPER_CLASS radio_driver(radio, board);
VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
#ifdef ENV_INCLUDE_GPS
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors = EnvironmentSensorManager();
+2 -3
View File
@@ -17,7 +17,8 @@ ESP32RTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
#ifdef ENV_INCLUDE_GPS
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors = EnvironmentSensorManager();
@@ -46,5 +47,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity
}
+2 -1
View File
@@ -25,4 +25,5 @@
#define PIN_GPS_RESET (13)
#define PIN_GPS_RX (20)
#define PIN_GPS_TX (19)
#define PIN_GPS_SWITCH (10)
#define PIN_GPS_SWITCH (10)
#define GPS_SWITCH_IS_HARDWARE (1)
+2 -2
View File
@@ -12,7 +12,8 @@ WRAPPER_CLASS radio_driver(radio, board);
VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
#ifdef ENV_INCLUDE_GPS
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors = EnvironmentSensorManager();
@@ -32,4 +33,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity
}
+2 -2
View File
@@ -12,7 +12,8 @@ ESP32RTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
#ifdef ENV_INCLUDE_GPS
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors = EnvironmentSensorManager();
@@ -81,4 +82,3 @@ mesh::LocalIdentity radio_new_identity() {
return mesh::LocalIdentity(&rng); // create new random identity
}
+2 -1
View File
@@ -13,7 +13,8 @@ WRAPPER_CLASS radio_driver(radio, board);
VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
#ifdef ENV_INCLUDE_GPS
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors = EnvironmentSensorManager();
+2 -1
View File
@@ -11,7 +11,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#ifdef ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors = EnvironmentSensorManager();
+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();
@@ -37,4 +38,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random 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();
@@ -37,4 +38,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;
@@ -39,4 +40,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity
}