commit
822bea7b7c
97 files changed
+2404
-795
No files matched your search
+13
-62
@@ -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
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
};
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -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;
|
||||
}
|
||||
};
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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:
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -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); }
|
||||
};
|
||||
@@ -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); }
|
||||
}
|
||||
};
|
||||
Reference in new issue
Block a user