gps: add GpsDriver, handle the hardware and software switches in the drivers

This commit is contained in:
Florent committed 2026-11-08 08:47:34 -04:00
1 parent 5533c24fde
commit df5a768c5d
28 files changed
+892 -468

No files matched your search

+4 -4
View File
@@ -392,16 +392,16 @@ public:
char buf[50]; char buf[50];
int y = 18; int y = 18;
bool gps_state = _task->getGPSState(); bool gps_state = _task->getGPSState();
#ifdef PIN_GPS_SWITCH bool hw_gps_state = nmea != NULL && nmea->isHardwareEnabled();
bool hw_gps_state = digitalRead(PIN_GPS_SWITCH); if (nmea != NULL && nmea->hasHardwareEnableState()) {
if (gps_state != hw_gps_state) { if (gps_state != hw_gps_state) {
strcpy(buf, gps_state ? "gps off(hw)" : "gps off(sw)"); strcpy(buf, gps_state ? "gps off(hw)" : "gps off(sw)");
} else { } else {
strcpy(buf, gps_state ? "gps on" : "gps off"); strcpy(buf, gps_state ? "gps on" : "gps off");
} }
#else } else {
strcpy(buf, gps_state ? "gps on" : "gps off"); strcpy(buf, gps_state ? "gps on" : "gps off");
#endif }
display.setColor(UIColor::primary_txt); display.setColor(UIColor::primary_txt);
display.drawTextLeftAlign(0, y, buf); display.drawTextLeftAlign(0, y, buf);
if (nmea == NULL) { if (nmea == NULL) {
+4 -4
View File
@@ -254,16 +254,16 @@ public:
char buf[50]; char buf[50];
int y = 8; int y = 8;
bool gps_state = _task->getGPSState(); bool gps_state = _task->getGPSState();
#ifdef PIN_GPS_SWITCH bool hw_gps_state = nmea != NULL && nmea->isHardwareEnabled();
bool hw_gps_state = digitalRead(PIN_GPS_SWITCH); if (nmea != NULL && nmea->hasHardwareEnableState()) {
if (gps_state != hw_gps_state) { if (gps_state != hw_gps_state) {
strcpy(buf, gps_state ? "gps off(hw)" : "gps off(sw)"); strcpy(buf, gps_state ? "gps off(hw)" : "gps off(sw)");
} else { } else {
strcpy(buf, gps_state ? "gps on" : "gps off"); strcpy(buf, gps_state ? "gps on" : "gps off");
} }
#else } else {
strcpy(buf, gps_state ? "gps on" : "gps off"); strcpy(buf, gps_state ? "gps on" : "gps off");
#endif }
display.setColor(UIColor::primary_txt); display.setColor(UIColor::primary_txt);
display.drawTextLeftAlign(0, y, buf); display.drawTextLeftAlign(0, y, buf);
if (nmea == NULL) { if (nmea == NULL) {
+3
View File
@@ -159,6 +159,9 @@ protected:
#if ENV_INCLUDE_GPS == 1 #if ENV_INCLUDE_GPS == 1
void applyGpsPrefs() { void applyGpsPrefs() {
char period[11];
snprintf(period, sizeof(period), "%lu", (unsigned long)_prefs.gps_period);
sensors.setSettingValue("gps_period", period);
sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0"); sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0");
} }
#endif #endif
+3
View File
@@ -168,6 +168,9 @@ protected:
#if ENV_INCLUDE_GPS == 1 #if ENV_INCLUDE_GPS == 1
void applyGpsPrefs() { void applyGpsPrefs() {
char period[11];
snprintf(period, sizeof(period), "%lu", (unsigned long)_prefs.gps_period);
sensors.setSettingValue("gps_period", period);
sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0"); sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0");
} }
#endif #endif
+3
View File
@@ -173,6 +173,9 @@ private:
#if ENV_INCLUDE_GPS == 1 #if ENV_INCLUDE_GPS == 1
void applyGpsPrefs() { void applyGpsPrefs() {
char period[11];
snprintf(period, sizeof(period), "%lu", (unsigned long)_prefs.gps_period);
sensors.setSettingValue("gps_period", period);
sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0"); sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0");
} }
#endif #endif
+18
View File
@@ -368,6 +368,24 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
} else { } else {
strcpy(reply, "gps toggle not found"); strcpy(reply, "gps toggle not found");
} }
} else if (memcmp(command, "gps period ", 11) == 0) {
char* end = nullptr;
unsigned long period = strtoul(command + 11, &end, 10);
if (command[11] == '\0' || *end != '\0' || period > 86400) {
strcpy(reply, "gps period must be 0-86400 seconds");
} else {
char period_value[11];
snprintf(period_value, sizeof(period_value), "%lu", period);
if (_sensors->setSettingValue("gps_period", period_value) &&
_sensors->setSettingValue("gps", "1")) {
_prefs->gps_period = (uint32_t)period;
_prefs->gps_enabled = 1;
savePrefs();
strcpy(reply, "ok");
} else {
strcpy(reply, "gps provider not found");
}
}
} else if (memcmp(command, "gps sync", 8) == 0) { } else if (memcmp(command, "gps sync", 8) == 0) {
LocationProvider * l = _sensors->getLocationProvider(); LocationProvider * l = _sensors->getLocationProvider();
if (l != NULL) { if (l != NULL) {
+2
View File
@@ -61,6 +61,7 @@ public:
// Gps settings // Gps settings
uint8_t gps_enabled = 0; uint8_t gps_enabled = 0;
uint32_t gps_interval = 0; // in seconds uint32_t gps_interval = 0; // in seconds
uint32_t gps_period = 0; // periodic acquisition interval in seconds
uint8_t advert_loc_policy = 0; uint8_t advert_loc_policy = 0;
uint32_t discovery_mod_timestamp = 0; uint32_t discovery_mod_timestamp = 0;
float adc_multiplier = 0; float adc_multiplier = 0;
@@ -158,6 +159,7 @@ private:
void structure() override { void structure() override {
def("en", _parent->gps_enabled); // boolean def("en", _parent->gps_enabled); // boolean
def("int", _parent->gps_interval); // interval in seconds def("int", _parent->gps_interval); // interval in seconds
def("period", _parent->gps_period); // periodic acquisition interval in seconds
def("adv_loc", _parent->advert_loc_policy); def("adv_loc", _parent->advert_loc_policy);
} }
public: public:
+83
View File
@@ -0,0 +1,83 @@
#pragma once
#include "NmeaGpsDriver.h"
class AirohaGpsDriver : public NmeaGpsDriver {
bool waitFor(const char* prefix, uint32_t timeout_ms) { // TODO: Refactor so it doesn't block the loop !
char sentence[100];
size_t length = 0;
const size_t prefixLength = strlen(prefix);
const uint32_t deadline = millis() + timeout_ms;
while ((int32_t)(millis() - deadline) < 0) {
if (available() <= 0) {
yield();
continue;
}
const char c = (char)read();
#ifdef GPS_NMEA_DEBUG
Serial.print(c);
#endif
if (c == '$') length = 0;
if (length < sizeof(sentence) - 1) {
sentence[length++] = c;
sentence[length] = '\0';
if (length >= prefixLength && strncmp(sentence, prefix, prefixLength) == 0) {
return true;
}
}
}
return false;
}
void enterBackupSleep() {
for (uint8_t attempt = 0; attempt < 3; attempt++) {
drain();
sendNmeaSentence("$PAIR650,0");
if (waitFor("$PAIR001,650,0", 50)) {
#ifdef GPS_NMEA_DEBUG
Serial.printf("Airoha RTC backup sleep accepted after %u attempts\r\n", attempt + 1);
#endif
waitFor("$PAIR650,0", 50);
return;
}
}
}
public:
AirohaGpsDriver(HardwareSerial& serial)
: NmeaGpsDriver(serial, -1, -1, -1, -1, nullptr, HIGH, LOW, 115200) {}
void initialize() {
NmeaGpsDriver::begin();
reset();
}
void begin() override {
NmeaGpsDriver::begin();
digitalWrite(GPS_EN, HIGH);
delay(10);
digitalWrite(GPS_RTC_INT, HIGH);
delay(5);
digitalWrite(GPS_RTC_INT, LOW);
}
void reset() override {
digitalWrite(GPS_RESET, HIGH);
delay(10);
digitalWrite(GPS_RESET, LOW);
}
void stop() override {
digitalWrite(GPS_VRTC_EN, HIGH);
digitalWrite(GPS_RTC_INT, LOW);
enterBackupSleep();
digitalWrite(GPS_EN, LOW);
NmeaGpsDriver::stop();
}
bool isEnabled() const override {
return digitalRead(GPS_EN) == HIGH;
}
};
+34 -215
View File
@@ -160,56 +160,6 @@ static Adafruit_VL53L0X VL53L0X;
static RAK12035_SoilMoisture RAK12035; static RAK12035_SoilMoisture RAK12035;
#endif #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 // I2C bus scanner
// Probes every valid address and records which ones ACK. // Probes every valid address and records which ones ACK.
@@ -624,12 +574,8 @@ static const size_t SENSOR_TABLE_SIZE = (sizeof(SENSOR_TABLE) / sizeof(SENSOR_TA
bool EnvironmentSensorManager::begin() { bool EnvironmentSensorManager::begin() {
#if ENV_INCLUDE_GPS #if ENV_INCLUDE_GPS
#ifdef RAK_WISBLOCK_GPS
rakGPSInit();
#else
initBasicGPS(); initBasicGPS();
#endif #endif
#endif
#if ENV_PIN_SDA && ENV_PIN_SCL #if ENV_PIN_SDA && ENV_PIN_SCL
#ifdef NRF52_PLATFORM #ifdef NRF52_PLATFORM
@@ -684,9 +630,11 @@ bool EnvironmentSensorManager::begin() {
bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, CayenneLPP& telemetry) { bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, CayenneLPP& telemetry) {
next_available_channel = TELEM_CHANNEL_SELF + 1; next_available_channel = TELEM_CHANNEL_SELF + 1;
if (requester_permissions & TELEM_PERM_LOCATION && gps_active) { #if ENV_INCLUDE_GPS
if (requester_permissions & TELEM_PERM_LOCATION && _location->isEnabled()) {
telemetry.addGPS(TELEM_CHANNEL_SELF, node_lat, node_lon, node_altitude); telemetry.addGPS(TELEM_CHANNEL_SELF, node_lat, node_lon, node_altitude);
} }
#endif
if (requester_permissions & TELEM_PERM_ENVIRONMENT) { if (requester_permissions & TELEM_PERM_ENVIRONMENT) {
for (int i = 0; i < _active_sensor_count; i++) { for (int i = 0; i < _active_sensor_count; i++) {
@@ -702,7 +650,7 @@ bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, Cayen
int EnvironmentSensorManager::getNumSettings() const { int EnvironmentSensorManager::getNumSettings() const {
int settings = 0; int settings = 0;
#if ENV_INCLUDE_GPS #if ENV_INCLUDE_GPS
if (gps_detected) settings++; // only show GPS setting if GPS is detected if (gps_detected) settings += 2; // GPS enablement and periodic acquisition
#endif #endif
return settings; return settings;
} }
@@ -713,6 +661,9 @@ const char* EnvironmentSensorManager::getSettingName(int i) const {
if (gps_detected && i == settings++) { if (gps_detected && i == settings++) {
return "gps"; return "gps";
} }
if (gps_detected && i == settings++) {
return "gps_period";
}
#endif #endif
return NULL; return NULL;
} }
@@ -721,7 +672,13 @@ const char* EnvironmentSensorManager::getSettingValue(int i) const {
int settings = 0; int settings = 0;
#if ENV_INCLUDE_GPS #if ENV_INCLUDE_GPS
if (gps_detected && i == settings++) { if (gps_detected && i == settings++) {
return gps_active ? "1" : "0"; return _location->isGpsOn() ? "1" : "0";
}
if (gps_detected && i == settings++) {
static char period[11];
snprintf(period, sizeof(period), "%lu",
(unsigned long)_location->getGpsPeriod());
return period;
} }
#endif #endif
return NULL; return NULL;
@@ -737,6 +694,13 @@ bool EnvironmentSensorManager::setSettingValue(const char* name, const char* val
} }
return true; return true;
} }
if (gps_detected && strcmp(name, "gps_period") == 0) {
char* end = nullptr;
unsigned long period = strtoul(value, &end, 10);
if (*value == '\0' || *end != '\0' || period > 86400) return false;
_location->setGpsPeriod((uint32_t)period);
return true;
}
if (strcmp(name, "gps_interval") == 0) { if (strcmp(name, "gps_interval") == 0) {
uint32_t interval_seconds = atoi(value); uint32_t interval_seconds = atoi(value);
gps_update_interval_sec = interval_seconds > 0 ? interval_seconds : 1; gps_update_interval_sec = interval_seconds > 0 ? interval_seconds : 1;
@@ -748,157 +712,35 @@ bool EnvironmentSensorManager::setSettingValue(const char* name, const char* val
#if ENV_INCLUDE_GPS #if ENV_INCLUDE_GPS
void EnvironmentSensorManager::initBasicGPS() { void EnvironmentSensorManager::initBasicGPS() {
start_gps();
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 #ifndef PIN_GPS_EN
MESH_DEBUG_PRINTLN("No GPS wake/reset pin found for this board. Continuing on..."); MESH_DEBUG_PRINTLN("No GPS wake/reset pin found for this board. Continuing on...");
#endif #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 #ifdef ENV_SKIP_GPS_DETECT
gps_detected = true; gps_detected = true;
#else #else
gps_detected = false; gps_detected = _location->detect(5000);
for (int i = 0; i < 20 && !gps_detected; i++) {
delay(250);
gps_detected = (Serial1.available() > 0);
}
#endif #endif
if (gps_detected) { if (gps_detected) {
MESH_DEBUG_PRINTLN("GPS detected"); MESH_DEBUG_PRINTLN("GPS detected");
#ifdef PERSISTANT_GPS #if defined(PERSISTANT_GPS)
gps_active = true;
return; return;
#else
if (_location->keepEnabledAfterDetection()) {
return;
}
#endif #endif
} else { } else {
MESH_DEBUG_PRINTLN("No GPS detected"); MESH_DEBUG_PRINTLN("No GPS detected");
} }
_location->stop();
gps_active = false; //Set GPS visibility off until setting is changed
}
// gps code for rak might be moved to MicroNMEALoactionProvider
// or make a new location provider ...
#ifdef RAK_WISBLOCK_GPS
void EnvironmentSensorManager::rakGPSInit(){
Serial1.setPins(PIN_GPS_TX, PIN_GPS_RX);
#ifdef GPS_BAUD_RATE
Serial1.begin(GPS_BAUD_RATE);
#else
Serial1.begin(9600);
#endif
//search for the correct IO standby pin depending on socket used
if(gpsIsAwake(WB_IO2)){
}
else if(gpsIsAwake(WB_IO4)){
}
else if(gpsIsAwake(WB_IO5)){
}
else{
MESH_DEBUG_PRINTLN("No GPS found");
gps_active = false;
gps_detected = false;
Serial1.end();
return;
}
#ifndef FORCE_GPS_ALIVE // for use with repeaters, until GPS toggle is implimented
//Now that GPS is found and set up, set to sleep for initial state
stop_gps(); 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() { void EnvironmentSensorManager::start_gps() {
gps_active = true; _location->setGpsOn(true);
#ifdef RAK_WISBLOCK_GPS
#ifndef RAK_3401
pinMode(gpsResetPin, OUTPUT);
digitalWrite(gpsResetPin, HIGH);
#endif
return;
#endif
_location->begin();
_location->reset();
#ifndef PIN_GPS_EN #ifndef PIN_GPS_EN
MESH_DEBUG_PRINTLN("Start GPS is N/A on this board. Actual GPS state unchanged"); MESH_DEBUG_PRINTLN("Start GPS is N/A on this board. Actual GPS state unchanged");
@@ -906,20 +748,11 @@ void EnvironmentSensorManager::start_gps() {
} }
void EnvironmentSensorManager::stop_gps() { void EnvironmentSensorManager::stop_gps() {
gps_active = false; _location->setGpsOn(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->stop(); #ifndef PIN_GPS_EN
#ifndef PIN_GPS_EN
MESH_DEBUG_PRINTLN("Stop GPS is N/A on this board. Actual GPS state unchanged"); MESH_DEBUG_PRINTLN("Stop GPS is N/A on this board. Actual GPS state unchanged");
#endif #endif
} }
#endif // ENV_INCLUDE_GPS #endif // ENV_INCLUDE_GPS
@@ -928,30 +761,16 @@ void EnvironmentSensorManager::loop() {
#if ENV_INCLUDE_GPS #if ENV_INCLUDE_GPS
static unsigned long next_gps_update = 0; static unsigned long next_gps_update = 0;
if (gps_active) { _location->loop();
_location->loop();
}
if ((long)(millis() - next_gps_update) > 0) { if ((long)(millis() - next_gps_update) > 0) {
if(gps_active){ if (_location->isEnabled() && _location->isValid()) {
#ifdef RAK_WISBLOCK_GPS
if ((i2cGPSFlag || serialGPSFlag) && _location->isValid()) {
node_lat = ((double)_location->getLatitude())/1000000.; node_lat = ((double)_location->getLatitude())/1000000.;
node_lon = ((double)_location->getLongitude())/1000000.; node_lon = ((double)_location->getLongitude())/1000000.;
MESH_DEBUG_PRINTLN("lat %f lon %f", node_lat, node_lon); MESH_DEBUG_PRINTLN("lat %f lon %f", node_lat, node_lon);
node_altitude = ((double)_location->getAltitude()) / 1000.0; node_altitude = ((double)_location->getAltitude()) / 1000.0;
MESH_DEBUG_PRINTLN("lat %f lon %f alt %f", node_lat, node_lon, node_altitude); 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); next_gps_update = millis() + (gps_update_interval_sec * 1000);
} }
#endif #endif
@@ -20,7 +20,6 @@ protected:
uint8_t next_available_channel = TELEM_CHANNEL_SELF + 1; uint8_t next_available_channel = TELEM_CHANNEL_SELF + 1;
bool gps_detected = false; bool gps_detected = false;
bool gps_active = false;
uint32_t gps_update_interval_sec = 1; uint32_t gps_update_interval_sec = 1;
#if ENV_INCLUDE_GPS #if ENV_INCLUDE_GPS
@@ -28,10 +27,6 @@ protected:
void start_gps(); void start_gps();
void stop_gps(); void stop_gps();
void initBasicGPS(); void initBasicGPS();
#ifdef RAK_BOARD
void rakGPSInit();
bool gpsIsAwake(uint8_t ioPin);
#endif
#endif #endif
public: public:
+18
View File
@@ -0,0 +1,18 @@
#pragma once
#include <stdint.h>
class GpsDriver {
public:
virtual ~GpsDriver() = default;
virtual void begin() = 0;
virtual void reset() = 0;
virtual void stop() = 0;
virtual bool isEnabled() const = 0;
virtual bool hasHardwareEnableState() const { return false; }
virtual bool isHardwareEnabled() const { return true; }
// Returns true when the switch explicitly enables GPS in software.
virtual bool pollGpsSwitch() { return false; }
virtual bool detect(uint32_t timeout_ms) = 0;
};
+19
View File
@@ -8,8 +8,11 @@
class LocationProvider { class LocationProvider {
protected: protected:
bool _time_sync_needed = true; bool _time_sync_needed = true;
bool _gpsOn = false;
public: public:
virtual ~LocationProvider() = default;
virtual void syncTime() { _time_sync_needed = true; } virtual void syncTime() { _time_sync_needed = true; }
virtual bool waitingTimeSync() { return _time_sync_needed; } virtual bool waitingTimeSync() { return _time_sync_needed; }
virtual long getLatitude() = 0; virtual long getLatitude() = 0;
@@ -21,6 +24,22 @@ public:
virtual void sendSentence(const char * sentence); virtual void sendSentence(const char * sentence);
virtual bool waitFor(const char* prefix, uint32_t timeout_ms) { return false; } virtual bool waitFor(const char* prefix, uint32_t timeout_ms) { return false; }
virtual void drain() { } virtual void drain() { }
virtual bool detect(uint32_t timeout_ms) { return false; }
virtual bool keepEnabledAfterDetection() const { return false; }
virtual void setGpsPeriod(uint32_t seconds) { }
virtual uint32_t getGpsPeriod() const { return 0; }
virtual bool hasHardwareEnableState() const { return false; }
virtual bool isHardwareEnabled() const { return true; }
virtual bool isGpsOn() const { return _gpsOn; }
virtual void setGpsOn(bool on) {
_gpsOn = on;
if (on) {
begin();
reset();
} else {
stop();
}
}
virtual void reset() = 0; virtual void reset() = 0;
virtual void begin() = 0; virtual void begin() = 0;
virtual void stop() = 0; virtual void stop() = 0;
+142 -151
View File
@@ -1,69 +1,30 @@
#pragma once #pragma once
#include "NmeaGpsDriver.h"
#include "LocationProvider.h" #include "LocationProvider.h"
#include <MicroNMEA.h> #include <MicroNMEA.h>
#include <RTClib.h> #include <RTClib.h>
#include <helpers/RefCountedDigitalPin.h>
#include <string.h> #include <string.h>
#ifndef GPS_EN #ifndef GPS_PERIODIC_ACQUISITION_TIMEOUT_MS
#ifdef PIN_GPS_EN #define GPS_PERIODIC_ACQUISITION_TIMEOUT_MS 120000UL
#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 #endif
class MicroNMEALocationProvider : public LocationProvider { class MicroNMEALocationProvider : public LocationProvider {
char _nmeaBuffer[100]; char _nmeaBuffer[100];
MicroNMEA nmea; MicroNMEA nmea;
mesh::RTCClock* _clock; mesh::RTCClock* _clock;
Stream* _gps_serial; NmeaGpsDriver* _driver;
RefCountedDigitalPin* _peripher_power; bool _ownsDriver = false;
int8_t _claims = 0;
int _pin_reset;
int _pin_en;
unsigned long next_check = 0; unsigned long next_check = 0;
long time_valid = 0; long time_valid = 0;
unsigned long _last_time_sync = 0; unsigned long _last_time_sync = 0;
static const unsigned long TIME_SYNC_INTERVAL = 1800000; // Re-sync every 30 minutes uint32_t _gpsPeriodSeconds = 0;
unsigned long _nextAcquisition = 0;
unsigned long _acquisitionStarted = 0;
bool _acquiringPeriodically = false;
static const unsigned long TIME_SYNC_INTERVAL = 1800000;
#ifdef GPS_L76K
void configureL76K() {
// Reapply the constellation mode at each provider start instead of
// assuming it survives a receiver power cycle.
// Mode 7 enables GPS + BeiDou + GLONASS.
delay(250);
MicroNMEA::sendSentence(*_gps_serial, "$PCAS04,7");
delay(250);
}
#endif
// Observation-only diagnostics. These fields do not change GPS power,
// timing, reset behaviour, or parser input.
uint32_t _uart_bytes = 0; uint32_t _uart_bytes = 0;
uint32_t _nmea_checksum_ok = 0; uint32_t _nmea_checksum_ok = 0;
uint32_t _nmea_checksum_bad = 0; uint32_t _nmea_checksum_bad = 0;
@@ -88,79 +49,121 @@ class MicroNMEALocationProvider : public LocationProvider {
} }
} }
public : void startPeriodicAcquisition() {
MicroNMEALocationProvider(Stream& ser, mesh::RTCClock* clock = NULL, int pin_reset = GPS_RESET, int pin_en = GPS_EN,RefCountedDigitalPin* peripher_power=NULL) : nmea.clear();
nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), _gps_serial(&ser), _peripher_power(peripher_power), _pin_reset(pin_reset), _pin_en(pin_en) { time_valid = 0;
if (_pin_reset != -1) { _driver->begin();
pinMode(_pin_reset, OUTPUT); _driver->reset();
digitalWrite(_pin_reset, GPS_RESET_ACTIVE); _acquiringPeriodically = true;
} _acquisitionStarted = millis();
if (_pin_en != -1) {
pinMode(_pin_en, OUTPUT);
digitalWrite(_pin_en, !GPS_EN_ACTIVE);
}
} }
void claim() { void finishPeriodicAcquisition() {
_claims++; _driver->stop();
if (_peripher_power) _peripher_power->claim(); _acquiringPeriodically = false;
_nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL;
} }
void release() { void updateTime() {
if (_claims == 0) return; // avoid negative _claims if (!isValid()) time_valid = 0;
_claims--;
if (_peripher_power) _peripher_power->release(); if ((long)(millis() - next_check) <= 0) return;
next_check = millis() + 1000;
if (!_time_sync_needed && _clock != nullptr &&
(millis() - _last_time_sync) > TIME_SYNC_INTERVAL) {
_time_sync_needed = true;
}
if (_time_sync_needed && time_valid > 2 && _clock != nullptr) {
_clock->setCurrentTime(getTimestamp());
_time_sync_needed = false;
_last_time_sync = millis();
}
if (isValid()) time_valid++;
}
public:
MicroNMEALocationProvider(NmeaGpsDriver& driver, mesh::RTCClock* clock = nullptr)
: nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), _driver(&driver) {}
// Temporary migration adapter for targets and downstream boards. New code
// should inject a GpsDriver; this constructor will be removed once targets
// have been migrated.
MicroNMEALocationProvider(HardwareSerial& serial, mesh::RTCClock* clock = nullptr,
int pin_reset = GPS_RESET, int pin_en = GPS_EN,
RefCountedDigitalPin* peripher_power = nullptr)
: nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock),
_driver(new NmeaGpsDriver(serial, PIN_GPS_TX, PIN_GPS_RX, pin_reset, pin_en,
peripher_power)),
_ownsDriver(true) {}
MicroNMEALocationProvider(Stream& serial, mesh::RTCClock* clock = nullptr,
int pin_reset = GPS_RESET, int pin_en = GPS_EN,
RefCountedDigitalPin* peripher_power = nullptr)
: nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock),
_driver(new NmeaGpsDriver(serial, PIN_GPS_TX, PIN_GPS_RX, pin_reset, pin_en,
peripher_power)),
_ownsDriver(true) {}
~MicroNMEALocationProvider() override {
if (_ownsDriver) delete _driver;
} }
void begin() override { void begin() override {
_begin_calls++; _begin_calls++;
claim(); _driver->begin();
if (_pin_en != -1) { if (_gpsPeriodSeconds > 0 && _driver->isEnabled()) {
digitalWrite(_pin_en, GPS_EN_ACTIVE); nmea.clear();
} time_valid = 0;
if (_pin_reset != -1) { _acquiringPeriodically = true;
digitalWrite(_pin_reset, !GPS_RESET_ACTIVE); _acquisitionStarted = millis();
} }
} }
void reset() override { void reset() override {
if (_pin_reset != -1) { _driver->reset();
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
} }
void stop() override { void stop() override {
_stop_calls++; _stop_calls++;
if (_pin_en != -1) { _acquiringPeriodically = false;
digitalWrite(_pin_en, !GPS_EN_ACTIVE); _driver->stop();
}
if (_pin_reset != -1) {
digitalWrite(_pin_reset, GPS_RESET_ACTIVE);
}
release();
} }
bool isEnabled() override { bool isEnabled() override {
// directly read the enable pin if present as gps can be return _driver->isEnabled();
// activated/deactivated outside of here ... }
if (_pin_en != -1) {
return digitalRead(_pin_en) == GPS_EN_ACTIVE; bool hasHardwareEnableState() const override {
} else { return _driver->hasHardwareEnableState();
return true; // no enable so must be active }
}
bool isHardwareEnabled() const override {
return _driver->isHardwareEnabled();
}
bool detect(uint32_t timeout_ms) override {
return _driver->detect(timeout_ms);
}
void setGpsPeriod(uint32_t seconds) override {
_gpsPeriodSeconds = seconds;
_nextAcquisition = millis();
_acquiringPeriodically = false;
}
uint32_t getGpsPeriod() const override {
return _gpsPeriodSeconds;
}
void syncTime() override {
nmea.clear();
LocationProvider::syncTime();
} }
void syncTime() override { nmea.clear(); LocationProvider::syncTime(); }
long getLatitude() override { return nmea.getLatitude(); } long getLatitude() override { return nmea.getLatitude(); }
long getLongitude() override { return nmea.getLongitude(); } long getLongitude() override { return nmea.getLongitude(); }
long getAltitude() override { long getAltitude() override {
long alt = 0; long alt = 0;
nmea.getAltitude(alt); nmea.getAltitude(alt);
return alt; return alt;
@@ -168,29 +171,31 @@ public :
long satellitesCount() override { return nmea.getNumSatellites(); } long satellitesCount() override { return nmea.getNumSatellites(); }
bool isValid() override { return nmea.isValid(); } bool isValid() override { return nmea.isValid(); }
long getTimestamp() override { long getTimestamp() override {
DateTime dt(nmea.getYear(), nmea.getMonth(),nmea.getDay(),nmea.getHour(),nmea.getMinute(),nmea.getSecond()); DateTime dt(nmea.getYear(), nmea.getMonth(), nmea.getDay(),
nmea.getHour(), nmea.getMinute(), nmea.getSecond());
return dt.unixtime(); return dt.unixtime();
}
void drain() { while (_gps_serial->available()) _gps_serial->read(); }
const char* getSentence() const { return nmea.getSentence(); }
void sendSentence(const char *sentence) override {
nmea.sendSentence(*_gps_serial, sentence);
} }
bool waitFor(const char* prefix, uint32_t timeout_ms) { void drain() override { _driver->drain(); }
size_t plen = strlen(prefix); const char* getSentence() const { return nmea.getSentence(); }
uint32_t timeout = millis() + timeout_ms;
while ((int32_t)(millis() - timeout) < 0) { void sendSentence(const char* sentence) override {
if (_gps_serial->available()) { _driver->sendNmeaSentence(sentence);
char c = _gps_serial->read(); }
#ifdef GPS_NMEA_DEBUG
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); Serial.print(c);
#endif #endif
if (nmea.process(c) && strncmp(nmea.getSentence(), prefix, plen) == 0) return true; if (nmea.process(c) && strncmp(nmea.getSentence(), prefix, prefixLength) == 0) {
return true;
}
} else { } else {
yield(); yield();
} }
@@ -199,34 +204,35 @@ public :
} }
void loop() override { void loop() override {
if (_driver->pollGpsSwitch()) _gpsOn = true;
while (_gps_serial->available()) { if (_gpsOn && _gpsPeriodSeconds > 0 && !_acquiringPeriodically &&
char c = _gps_serial->read(); (long)(millis() - _nextAcquisition) >= 0) {
startPeriodicAcquisition();
}
while (_driver->available() > 0) {
const char c = (char)_driver->read();
_uart_bytes++; _uart_bytes++;
_last_uart_ms = millis(); _last_uart_ms = millis();
_uart_seen = true; _uart_seen = true;
#ifdef GPS_NMEA_DEBUG #ifdef GPS_NMEA_DEBUG
Serial.print(c); Serial.print(c);
#endif #endif
bool parsed = nmea.process(c); 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 ((c == '\0' || c == '\r' || c == '\n') && nmea.getSentence()[0] != '\0') {
if (MicroNMEA::testChecksum(nmea.getSentence())) { if (MicroNMEA::testChecksum(nmea.getSentence())) {
_nmea_checksum_ok++; _nmea_checksum_ok++;
_last_nmea_ms = millis(); _last_nmea_ms = millis();
_nmea_seen = true; _nmea_seen = true;
// Refresh fix age only when a newly parsed GGA/RMC sentence const char* messageId = nmea.getMessageID();
// 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() && if (parsed && isValid() &&
(strcmp(message_id, "GGA") == 0 || strcmp(message_id, "RMC") == 0)) { (strcmp(messageId, "GGA") == 0 || strcmp(messageId, "RMC") == 0)) {
_last_fix_ms = millis(); _last_fix_ms = millis();
_fix_seen = true; _fix_seen = true;
if (_acquiringPeriodically) finishPeriodicAcquisition();
} }
} else { } else {
_nmea_checksum_bad++; _nmea_checksum_bad++;
@@ -234,25 +240,12 @@ public :
} }
} }
if (!isValid()) time_valid = 0; if (_acquiringPeriodically &&
(uint32_t)(millis() - _acquisitionStarted) >= GPS_PERIODIC_ACQUISITION_TIMEOUT_MS) {
if ((long)(millis() - next_check) > 0) { finishPeriodicAcquisition();
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 ++;
}
} }
updateTime();
} }
void formatDiagnostics(char* out, size_t out_size) override { void formatDiagnostics(char* out, size_t out_size) override {
@@ -265,8 +258,6 @@ public :
formatAge(nmea_age, sizeof(nmea_age), _nmea_seen, _last_nmea_ms); formatAge(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), _fix_seen, _last_fix_ms);
// Compact enough for CommonCLI's 160-byte reply buffer, including the
// "req:" prefix added by CommonCLI.
snprintf(out, out_size, 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", "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, isEnabled() ? 1U : 0U,
+262
View File
@@ -0,0 +1,262 @@
#pragma once
#include "GpsDriver.h"
#include <Arduino.h>
#include <helpers/RefCountedDigitalPin.h>
#ifndef PIN_GPS_TX
#define PIN_GPS_TX (-1)
#endif
#ifndef PIN_GPS_RX
#define PIN_GPS_RX (-1)
#endif
#ifndef GPS_EN
#ifdef PIN_GPS_EN
#define GPS_EN PIN_GPS_EN
#else
#define GPS_EN (-1)
#endif
#endif
#ifndef GPS_EN_ACTIVE
#ifdef PIN_GPS_EN_ACTIVE
#define GPS_EN_ACTIVE PIN_GPS_EN_ACTIVE
#else
#define GPS_EN_ACTIVE HIGH
#endif
#endif
#ifndef GPS_RESET
#ifdef PIN_GPS_RESET
#define GPS_RESET PIN_GPS_RESET
#else
#define GPS_RESET (-1)
#endif
#endif
#ifndef GPS_RESET_ACTIVE
#ifdef PIN_GPS_RESET_ACTIVE
#define GPS_RESET_ACTIVE PIN_GPS_RESET_ACTIVE
#else
#define GPS_RESET_ACTIVE LOW
#endif
#endif
#ifndef GPS_BAUD_RATE
#define GPS_BAUD_RATE 9600
#endif
#ifndef PIN_GPS_SWITCH
#define PIN_GPS_SWITCH (-1)
#endif
#ifndef GPS_SWITCH_ACTIVE
#define GPS_SWITCH_ACTIVE HIGH
#endif
#ifndef GPS_SWITCH_IS_HARDWARE
#define GPS_SWITCH_IS_HARDWARE 1
#endif
#ifndef GPS_SWITCH_TURNS_GPS_ON
#define GPS_SWITCH_TURNS_GPS_ON 0
#endif
class NmeaGpsDriver : public GpsDriver {
Stream* _stream = nullptr;
HardwareSerial* _hardwareSerial = nullptr;
RefCountedDigitalPin* _peripheralPower = nullptr;
int _txPin = -1;
int _rxPin = -1;
int _resetPin = -1;
int _enablePin = -1;
int _enableActive = HIGH;
int _resetActive = LOW;
uint32_t _baudRate = 9600;
int _hardwareEnablePin = -1;
int _hardwareEnableActive = HIGH;
bool _started = false;
#if !GPS_SWITCH_IS_HARDWARE
bool _requestedOn = false;
bool _switchStateKnown = false;
bool _lastSwitchEnabled = false;
unsigned long _nextSwitchPoll = 0;
#endif
void startHardware() {
if (_stream == nullptr || _started) return;
if (_hardwareSerial != nullptr) {
#ifdef ESP32_PLATFORM
_hardwareSerial->setPins(_txPin, _rxPin);
#endif
_hardwareSerial->begin(_baudRate);
}
if (_peripheralPower != nullptr) _peripheralPower->claim();
if (_enablePin != -1) digitalWrite(_enablePin, _enableActive);
if (_resetPin != -1) digitalWrite(_resetPin, !_resetActive);
_started = true;
}
void stopHardware() {
if (!_started) return;
if (_enablePin != -1) digitalWrite(_enablePin, !_enableActive);
if (_resetPin != -1) digitalWrite(_resetPin, _resetActive);
if (_peripheralPower != nullptr) _peripheralPower->release();
_started = false;
}
public:
NmeaGpsDriver() = default;
NmeaGpsDriver(Stream& stream, int txPin = PIN_GPS_TX, int rxPin = PIN_GPS_RX,
int resetPin = GPS_RESET, int enablePin = GPS_EN,
RefCountedDigitalPin* peripheralPower = nullptr,
int enableActive = GPS_EN_ACTIVE, int resetActive = GPS_RESET_ACTIVE,
uint32_t baudRate = GPS_BAUD_RATE,
int hardwareEnablePin = PIN_GPS_SWITCH,
int hardwareEnableActive = GPS_SWITCH_ACTIVE)
: _stream(&stream), _peripheralPower(peripheralPower), _txPin(txPin), _rxPin(rxPin),
_resetPin(resetPin), _enablePin(enablePin), _enableActive(enableActive),
_resetActive(resetActive), _baudRate(baudRate),
_hardwareEnablePin(hardwareEnablePin), _hardwareEnableActive(hardwareEnableActive) {
if (_resetPin != -1) {
pinMode(_resetPin, OUTPUT);
digitalWrite(_resetPin, _resetActive);
}
if (_enablePin != -1) {
pinMode(_enablePin, OUTPUT);
digitalWrite(_enablePin, !_enableActive);
}
if (_hardwareEnablePin != -1) {
pinMode(_hardwareEnablePin, INPUT);
}
}
NmeaGpsDriver(HardwareSerial& serial, int txPin = PIN_GPS_TX, int rxPin = PIN_GPS_RX,
int resetPin = GPS_RESET, int enablePin = GPS_EN,
RefCountedDigitalPin* peripheralPower = nullptr,
int enableActive = GPS_EN_ACTIVE, int resetActive = GPS_RESET_ACTIVE,
uint32_t baudRate = GPS_BAUD_RATE,
int hardwareEnablePin = PIN_GPS_SWITCH,
int hardwareEnableActive = GPS_SWITCH_ACTIVE)
: NmeaGpsDriver(static_cast<Stream&>(serial), txPin, rxPin, resetPin, enablePin,
peripheralPower, enableActive, resetActive, baudRate,
hardwareEnablePin, hardwareEnableActive) {
_hardwareSerial = &serial;
}
void begin() override {
#if !GPS_SWITCH_IS_HARDWARE
_requestedOn = true;
if (!isHardwareEnabled()) return;
#endif
startHardware();
}
void reset() override {
if (!_started) return;
if (_resetPin != -1) {
digitalWrite(_resetPin, _resetActive);
delay(10);
digitalWrite(_resetPin, !_resetActive);
}
#ifdef GPS_L76K
delay(250);
sendNmeaSentence("$PCAS04,7");
delay(250);
#endif
}
void stop() override {
#if !GPS_SWITCH_IS_HARDWARE
_requestedOn = false;
#endif
stopHardware();
}
bool isEnabled() const override {
return _started && isHardwareEnabled();
}
bool hasHardwareEnableState() const override {
return _hardwareEnablePin != -1;
}
bool isHardwareEnabled() const override {
return _hardwareEnablePin == -1 ||
digitalRead(_hardwareEnablePin) == _hardwareEnableActive;
}
bool pollGpsSwitch() override {
#if !GPS_SWITCH_IS_HARDWARE
if (_hardwareEnablePin == -1 ||
(long)(millis() - _nextSwitchPoll) < 0) return false;
_nextSwitchPoll = millis() + 1000;
const bool switchEnabled = isHardwareEnabled();
const bool enablesGps = GPS_SWITCH_TURNS_GPS_ON && _switchStateKnown &&
!_lastSwitchEnabled && switchEnabled;
_switchStateKnown = true;
_lastSwitchEnabled = switchEnabled;
if (enablesGps) _requestedOn = true;
if (_requestedOn && switchEnabled) {
startHardware();
} else {
stopHardware();
}
return enablesGps;
#else
return false;
#endif
}
bool detect(uint32_t timeout_ms) override {
if (available() > 0) return true;
const uint32_t deadline = millis() + timeout_ms;
while ((int32_t)(millis() - deadline) < 0) {
if (available() > 0) return true;
delay(10);
}
return false;
}
int available() {
return _stream == nullptr ? 0 : _stream->available();
}
int read() {
return _stream == nullptr ? -1 : _stream->read();
}
void drain() {
while (available() > 0) read();
}
void sendNmeaSentence(const char* sentence) {
if (_stream == nullptr || sentence == nullptr || sentence[0] != '$') return;
uint8_t checksum = 0;
const char* p = sentence + 1;
while (*p != '\0' && *p != '*') checksum ^= (uint8_t)*p++;
_stream->print(sentence);
if (*p == '\0') {
char checksumSuffix[6];
snprintf(checksumSuffix, sizeof(checksumSuffix), "*%02X\r\n", checksum);
_stream->print(checksumSuffix);
} else {
_stream->print("\r\n");
}
}
};
+112
View File
@@ -0,0 +1,112 @@
#pragma once
#include "NmeaGpsDriver.h"
#include <SparkFun_u-blox_GNSS_Arduino_Library.h>
class RakGpsDriver : public GpsDriver {
NmeaGpsDriver _serialDriver;
TwoWire& _wire;
SFE_UBLOX_GNSS _gnss;
uint8_t _powerPin = 0;
bool _usingRak12500 = false;
bool _detected = false;
bool probeRak12500(uint8_t powerPin) {
#if defined(ETHERNET_ENABLED) && defined(RAK_BOARD)
if (powerPin == WB_IO2) return false;
#endif
#ifndef RAK_3401
pinMode(powerPin, OUTPUT);
digitalWrite(powerPin, LOW);
delay(500);
digitalWrite(powerPin, HIGH);
#endif
delay(500);
if (_gnss.begin(_wire)) {
_gnss.setI2COutput(COM_TYPE_UBX);
_gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_GPS);
_gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_GALILEO);
_gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_GLONASS);
_gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_SBAS);
_gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_BEIDOU);
_gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_IMES);
_gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_QZSS);
_gnss.setMeasurementRate(1000);
_gnss.saveConfigSelective(VAL_CFG_SUBSEC_IOPORT);
_powerPin = powerPin;
_usingRak12500 = true;
return true;
}
#ifndef RAK_3401
pinMode(powerPin, INPUT);
#endif
return false;
}
public:
RakGpsDriver(HardwareSerial& serial = Serial1, TwoWire& wire = Wire)
: _serialDriver(serial), _wire(wire) {}
void begin() override {
if (_usingRak12500) {
#ifndef RAK_3401
pinMode(_powerPin, OUTPUT);
digitalWrite(_powerPin, HIGH);
#endif
return;
}
_serialDriver.begin();
}
void reset() override {
if (!_usingRak12500) _serialDriver.reset();
}
void stop() override {
if (_usingRak12500) {
#ifndef RAK_3401
pinMode(_powerPin, OUTPUT);
digitalWrite(_powerPin, LOW);
#endif
return;
}
_serialDriver.stop();
}
bool isEnabled() const override {
return _usingRak12500 ? true : _serialDriver.isEnabled();
}
bool detect(uint32_t) override {
if (_detected) return true;
_serialDriver.begin();
if (probeRak12500(WB_IO2) || probeRak12500(WB_IO4) || probeRak12500(WB_IO5)) {
_detected = true;
return true;
}
if (_serialDriver.detect(0)) {
_detected = true;
return true;
}
_serialDriver.stop();
return false;
}
bool usesRak12500() const { return _usingRak12500; }
bool isDetected() const { return _detected; }
NmeaGpsDriver& nmeaDriver() { return _serialDriver; }
bool hasFix() { return _usingRak12500 && _gnss.getGnssFixOk(8); }
long getLatitude() { return _gnss.getLatitude(2) / 10; }
long getLongitude() { return _gnss.getLongitude(2) / 10; }
long getAltitude() { return _gnss.getAltitude(2); }
long getSatellites() { return _gnss.getSIV(2); }
long getTimestamp() { return _gnss.getUnixEpoch(2); }
};
+144
View File
@@ -0,0 +1,144 @@
#pragma once
#include "MicroNMEALocationProvider.h"
#include "RakGpsDriver.h"
class RakLocationProvider : public LocationProvider {
RakGpsDriver& _driver;
MicroNMEALocationProvider _nmea;
uint32_t _gpsPeriodSeconds = 0;
unsigned long _nextAcquisition = 0;
unsigned long _acquisitionStarted = 0;
bool _acquiringPeriodically = false;
public:
RakLocationProvider(RakGpsDriver& driver, mesh::RTCClock* clock = nullptr)
: _driver(driver), _nmea(driver.nmeaDriver(), clock) {}
void syncTime() override {
LocationProvider::syncTime();
if (!_driver.usesRak12500()) _nmea.syncTime();
}
long getLatitude() override {
return _driver.usesRak12500() ? _driver.getLatitude() : _nmea.getLatitude();
}
long getLongitude() override {
return _driver.usesRak12500() ? _driver.getLongitude() : _nmea.getLongitude();
}
long getAltitude() override {
return _driver.usesRak12500() ? _driver.getAltitude() : _nmea.getAltitude();
}
long satellitesCount() override {
return _driver.usesRak12500() ? _driver.getSatellites() : _nmea.satellitesCount();
}
bool isValid() override {
return _driver.usesRak12500() ? _driver.hasFix() : _nmea.isValid();
}
long getTimestamp() override {
return _driver.usesRak12500() ? _driver.getTimestamp() : _nmea.getTimestamp();
}
void sendSentence(const char* sentence) override {
if (!_driver.usesRak12500()) _nmea.sendSentence(sentence);
}
bool waitFor(const char* prefix, uint32_t timeout_ms) override {
return _driver.usesRak12500() ? false : _nmea.waitFor(prefix, timeout_ms);
}
void drain() override {
if (!_driver.usesRak12500()) _nmea.drain();
}
void reset() override {
_driver.reset();
}
void begin() override {
if (_driver.isDetected() && _driver.usesRak12500()) {
_driver.begin();
_acquiringPeriodically = _gpsPeriodSeconds > 0;
_acquisitionStarted = millis();
} else if (_driver.isDetected()) {
_nmea.begin();
} else {
_driver.begin();
}
}
void stop() override {
_acquiringPeriodically = false;
if (_driver.usesRak12500()) {
_driver.stop();
} else {
_nmea.stop();
}
}
bool detect(uint32_t timeout_ms) override {
if (!_driver.detect(timeout_ms)) return false;
if (_driver.usesRak12500()) {
_acquiringPeriodically = _gpsPeriodSeconds > 0;
_acquisitionStarted = millis();
} else {
_nmea.setGpsPeriod(_gpsPeriodSeconds);
_nmea.begin();
}
return true;
}
bool keepEnabledAfterDetection() const override {
#ifdef FORCE_GPS_ALIVE
return true;
#else
return false;
#endif
}
void loop() override {
if (_driver.usesRak12500()) {
if (_gpsOn && _gpsPeriodSeconds > 0) {
if (!_acquiringPeriodically &&
(long)(millis() - _nextAcquisition) >= 0) {
_driver.begin();
_acquiringPeriodically = true;
_acquisitionStarted = millis();
}
if (_acquiringPeriodically && isValid()) {
_driver.stop();
_acquiringPeriodically = false;
_nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL;
} else if (_acquiringPeriodically &&
(uint32_t)(millis() - _acquisitionStarted) >=
GPS_PERIODIC_ACQUISITION_TIMEOUT_MS) {
_driver.stop();
_acquiringPeriodically = false;
_nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL;
}
}
} else {
_nmea.loop();
}
}
bool isEnabled() override {
return _driver.isEnabled();
}
void setGpsPeriod(uint32_t seconds) override {
_gpsPeriodSeconds = seconds;
_nextAcquisition = millis();
if (!_driver.usesRak12500()) _nmea.setGpsPeriod(seconds);
}
uint32_t getGpsPeriod() const override {
return _gpsPeriodSeconds;
}
};
+4 -3
View File
@@ -26,9 +26,10 @@ VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock); AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS #if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h> #include <helpers/sensors/RakLocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); RakGpsDriver gps_driver;
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); RakLocationProvider location(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors(location);
#else #else
EnvironmentSensorManager sensors; EnvironmentSensorManager sensors;
#endif #endif
+2 -3
View File
@@ -13,7 +13,8 @@ VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock); AutoDiscoverRTCClock rtc_clock(fallback_clock);
#ifdef ENV_INCLUDE_GPS #ifdef ENV_INCLUDE_GPS
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else #else
EnvironmentSensorManager sensors = EnvironmentSensorManager(); EnvironmentSensorManager sensors = EnvironmentSensorManager();
@@ -36,5 +37,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio); RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity return mesh::LocalIdentity(&rng); // create new random identity
} }
+4 -4
View File
@@ -25,9 +25,10 @@ VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock); AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS #if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h> #include <helpers/sensors/RakLocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); RakGpsDriver gps_driver;
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); RakLocationProvider location(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors(location);
#else #else
EnvironmentSensorManager sensors; EnvironmentSensorManager sensors;
#endif #endif
@@ -41,4 +42,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio); RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity return mesh::LocalIdentity(&rng); // create new random identity
} }
+4 -3
View File
@@ -25,9 +25,10 @@ VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock); AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS #if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h> #include <helpers/sensors/RakLocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); RakGpsDriver gps_driver;
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); RakLocationProvider location(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors(location);
#else #else
EnvironmentSensorManager sensors; EnvironmentSensorManager sensors;
#endif #endif
+1
View File
@@ -106,6 +106,7 @@ build_flags = ${t1000-e.build_flags}
; -D BLE_DEBUG_LOGGING=1 ; -D BLE_DEBUG_LOGGING=1
; -D MESH_PACKET_LOGGING=1 ; -D MESH_PACKET_LOGGING=1
; -D MESH_DEBUG=1 ; -D MESH_DEBUG=1
; -D GPS_NMEA_DEBUG
-D OFFLINE_QUEUE_SIZE=256 -D OFFLINE_QUEUE_SIZE=256
-D DISPLAY_CLASS=NullDisplayDriver -D DISPLAY_CLASS=NullDisplayDriver
-D PIN_BUZZER=25 -D PIN_BUZZER=25
+7 -17
View File
@@ -1,8 +1,8 @@
#include <Arduino.h> #include <Arduino.h>
#include "t1000e_sensors.h" #include "t1000e_sensors.h"
#include "target.h" #include "target.h"
#include <helpers/sensors/AirohaGpsDriver.h>
#include <helpers/sensors/MicroNMEALocationProvider.h> #include <helpers/sensors/MicroNMEALocationProvider.h>
#include <helpers/sensors/AirohaSleep.h>
T1000eBoard board; T1000eBoard board;
@@ -11,8 +11,9 @@ RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BU
WRAPPER_CLASS radio_driver(radio, board); WRAPPER_CLASS radio_driver(radio, board);
VolatileRTCClock rtc_clock; VolatileRTCClock rtc_clock;
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); AirohaGpsDriver gps_driver(Serial1);
T1000SensorManager sensors = T1000SensorManager(nmea); MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
T1000SensorManager sensors(nmea, gps_driver);
#ifdef DISPLAY_CLASS #ifdef DISPLAY_CLASS
NullDisplayDriver display; NullDisplayDriver display;
@@ -82,28 +83,17 @@ mesh::LocalIdentity radio_new_identity() {
void T1000SensorManager::start_gps() { void T1000SensorManager::start_gps() {
gps_active = true; gps_active = true;
digitalWrite(GPS_EN, HIGH); _nmea->begin();
delay(10);
digitalWrite(GPS_RTC_INT, HIGH);
delay(5);
digitalWrite(GPS_RTC_INT, LOW);
} }
void T1000SensorManager::stop_gps() { void T1000SensorManager::stop_gps() {
gps_active = false; gps_active = false;
digitalWrite(GPS_VRTC_EN, HIGH); // keep GPS RTC alive for faster fix on wake _nmea->stop();
digitalWrite(GPS_RTC_INT, LOW); // make sure this is LOW so we can pulse it to wake
airohaEnterSleep(_nmea); // send command to put the GPS into RTC backup sleep
digitalWrite(GPS_EN, LOW);
} }
bool T1000SensorManager::begin() { bool T1000SensorManager::begin() {
// init GPS _gps_driver->initialize();
Serial1.begin(115200);
digitalWrite(GPS_RESET, HIGH);
delay(10);
digitalWrite(GPS_RESET, LOW);
return true; return true;
} }
+5 -1
View File
@@ -12,15 +12,19 @@
#include "NullDisplayDriver.h" #include "NullDisplayDriver.h"
#endif #endif
class AirohaGpsDriver;
class T1000SensorManager: public SensorManager { class T1000SensorManager: public SensorManager {
bool gps_active = false; bool gps_active = false;
LocationProvider * _nmea; LocationProvider * _nmea;
AirohaGpsDriver* _gps_driver;
void start_gps(); void start_gps();
void sleep_gps(); void sleep_gps();
void stop_gps(); void stop_gps();
public: public:
T1000SensorManager(LocationProvider &nmea): _nmea(&nmea) { } T1000SensorManager(LocationProvider &nmea, AirohaGpsDriver& gps_driver)
: _nmea(&nmea), _gps_driver(&gps_driver) { }
bool begin() override; bool begin() override;
bool querySensors(uint8_t requester_permissions, CayenneLPP& telemetry) override; bool querySensors(uint8_t requester_permissions, CayenneLPP& telemetry) override;
void loop() override; void loop() override;
+8 -51
View File
@@ -2,6 +2,7 @@
#include "target.h" #include "target.h"
#include <helpers/ArduinoHelpers.h> #include <helpers/ArduinoHelpers.h>
#include <helpers/sensors/MicroNMEALocationProvider.h> #include <helpers/sensors/MicroNMEALocationProvider.h>
#include <helpers/sensors/NmeaGpsDriver.h>
ThinkNodeM1Board board; ThinkNodeM1Board board;
@@ -11,7 +12,8 @@ WRAPPER_CLASS radio_driver(radio, board);
VolatileRTCClock fallback_clock; VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock); AutoDiscoverRTCClock rtc_clock(fallback_clock);
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(gps_driver, &rtc_clock);
ThinkNodeM1SensorManager sensors = ThinkNodeM1SensorManager(nmea); ThinkNodeM1SensorManager sensors = ThinkNodeM1SensorManager(nmea);
#ifdef DISPLAY_CLASS #ifdef DISPLAY_CLASS
@@ -31,34 +33,15 @@ mesh::LocalIdentity radio_new_identity() {
} }
void ThinkNodeM1SensorManager::start_gps() { void ThinkNodeM1SensorManager::start_gps() {
if (!gps_active) { _location->setGpsOn(true);
gps_active = true;
_location->begin();
}
} }
void ThinkNodeM1SensorManager::stop_gps() { void ThinkNodeM1SensorManager::stop_gps() {
if (gps_active) { _location->setGpsOn(false);
gps_active = false;
_location->stop();
}
} }
bool ThinkNodeM1SensorManager::begin() { bool ThinkNodeM1SensorManager::begin() {
Serial1.begin(9600); start_gps();
// Initialize GPS switch pin
pinMode(PIN_GPS_SWITCH, INPUT);
last_gps_switch_state = digitalRead(PIN_GPS_SWITCH);
// Initialize GPS power pin
pinMode(GPS_EN, OUTPUT);
// Check initial switch state to determine if GPS should be active
if (last_gps_switch_state == HIGH) { // Switch is HIGH when ON
start_gps();
}
return true; return true;
} }
@@ -71,36 +54,11 @@ bool ThinkNodeM1SensorManager::querySensors(uint8_t requester_permissions, Cayen
void ThinkNodeM1SensorManager::loop() { void ThinkNodeM1SensorManager::loop() {
static long next_gps_update = 0; static long next_gps_update = 0;
static long last_switch_check = 0;
// Check GPS switch state every second
if (millis() - last_switch_check > 1000) {
bool current_switch_state = digitalRead(PIN_GPS_SWITCH);
// Detect switch state change
if (current_switch_state != last_gps_switch_state) {
last_gps_switch_state = current_switch_state;
if (current_switch_state == HIGH) { // Switch is ON
MESH_DEBUG_PRINTLN("GPS switch ON");
start_gps();
} else { // Switch is OFF
MESH_DEBUG_PRINTLN("GPS switch OFF");
stop_gps();
}
}
last_switch_check = millis();
}
if (!gps_active) {
return; // GPS is not active, skip further processing
}
_location->loop(); _location->loop();
if (millis() > next_gps_update) { if (millis() > next_gps_update) {
if (_location->isValid()) { if (_location->isEnabled() && _location->isValid()) {
node_lat = ((double)_location->getLatitude())/1000000.; node_lat = ((double)_location->getLatitude())/1000000.;
node_lon = ((double)_location->getLongitude())/1000000.; node_lon = ((double)_location->getLongitude())/1000000.;
node_altitude = ((double)_location->getAltitude()) / 1000.0; node_altitude = ((double)_location->getAltitude()) / 1000.0;
@@ -120,7 +78,7 @@ const char* ThinkNodeM1SensorManager::getSettingName(int i) const {
const char* ThinkNodeM1SensorManager::getSettingValue(int i) const { const char* ThinkNodeM1SensorManager::getSettingValue(int i) const {
if (i == 0) { if (i == 0) {
return gps_active ? "1" : "0"; return _location->isGpsOn() ? "1" : "0";
} }
return NULL; return NULL;
} }
@@ -136,4 +94,3 @@ bool ThinkNodeM1SensorManager::setSettingValue(const char* name, const char* val
} }
return false; // not supported return false; // not supported
} }
-3
View File
@@ -14,8 +14,6 @@
#endif #endif
class ThinkNodeM1SensorManager : public SensorManager { class ThinkNodeM1SensorManager : public SensorManager {
bool gps_active = false;
bool last_gps_switch_state = false;
LocationProvider* _location; LocationProvider* _location;
void start_gps(); void start_gps();
@@ -45,4 +43,3 @@ extern ThinkNodeM1SensorManager sensors;
bool radio_init(); bool radio_init();
mesh::LocalIdentity radio_new_identity(); mesh::LocalIdentity radio_new_identity();
+2
View File
@@ -146,3 +146,5 @@ extern const int SCK;
#define PIN_GPS_PPS (36) #define PIN_GPS_PPS (36)
#define PIN_GPS_STANDBY (34) #define PIN_GPS_STANDBY (34)
#define PIN_GPS_SWITCH (33) #define PIN_GPS_SWITCH (33)
#define GPS_SWITCH_IS_HARDWARE (0)
#define GPS_SWITCH_TURNS_GPS_ON (1)
+2 -3
View File
@@ -17,7 +17,8 @@ ESP32RTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock); AutoDiscoverRTCClock rtc_clock(fallback_clock);
#ifdef ENV_INCLUDE_GPS #ifdef ENV_INCLUDE_GPS
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else #else
EnvironmentSensorManager sensors = EnvironmentSensorManager(); EnvironmentSensorManager sensors = EnvironmentSensorManager();
@@ -46,5 +47,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio); RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity return mesh::LocalIdentity(&rng); // create new random identity
} }
+2 -1
View File
@@ -25,4 +25,5 @@
#define PIN_GPS_RESET (13) #define PIN_GPS_RESET (13)
#define PIN_GPS_RX (20) #define PIN_GPS_RX (20)
#define PIN_GPS_TX (19) #define PIN_GPS_TX (19)
#define PIN_GPS_SWITCH (10) #define PIN_GPS_SWITCH (10)
#define GPS_SWITCH_IS_HARDWARE (1)