From df5a768c5d2d5b9a47a513092c4193ccbc3f14d1 Mon Sep 17 00:00:00 2001 From: Florent Date: Sun, 1 Nov 2026 20:08:16 -0400 Subject: [PATCH] gps: add GpsDriver, handle the hardware and software switches in the drivers --- examples/companion_radio/ui-new/UITask.cpp | 8 +- examples/companion_radio/ui-tiny/UITask.cpp | 8 +- examples/simple_repeater/MyMesh.h | 3 + examples/simple_room_server/MyMesh.h | 3 + examples/simple_sensor/SensorMesh.h | 3 + src/helpers/CommonCLI.cpp | 18 ++ src/helpers/CommonCLI.h | 2 + src/helpers/sensors/AirohaGpsDriver.h | 83 +++++ .../sensors/EnvironmentSensorManager.cpp | 249 ++------------- .../sensors/EnvironmentSensorManager.h | 5 - src/helpers/sensors/GpsDriver.h | 18 ++ src/helpers/sensors/LocationProvider.h | 19 ++ .../sensors/MicroNMEALocationProvider.h | 293 +++++++++--------- src/helpers/sensors/NmeaGpsDriver.h | 262 ++++++++++++++++ src/helpers/sensors/RakGpsDriver.h | 112 +++++++ src/helpers/sensors/RakLocationProvider.h | 144 +++++++++ variants/gat562_30s_mesh_kit/target.cpp | 7 +- variants/lilygo_techo/target.cpp | 5 +- variants/rak3401/target.cpp | 8 +- variants/rak4631/target.cpp | 7 +- variants/t1000-e/platformio.ini | 1 + variants/t1000-e/target.cpp | 24 +- variants/t1000-e/target.h | 6 +- variants/thinknode_m1/target.cpp | 59 +--- variants/thinknode_m1/target.h | 3 - variants/thinknode_m1/variant.h | 2 + variants/thinknode_m5/target.cpp | 5 +- variants/thinknode_m5/variant.h | 3 +- 28 files changed, 892 insertions(+), 468 deletions(-) create mode 100644 src/helpers/sensors/AirohaGpsDriver.h create mode 100644 src/helpers/sensors/GpsDriver.h create mode 100644 src/helpers/sensors/NmeaGpsDriver.h create mode 100644 src/helpers/sensors/RakGpsDriver.h create mode 100644 src/helpers/sensors/RakLocationProvider.h diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index 55cae1fe3..cfe34cf2a 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -392,16 +392,16 @@ public: char buf[50]; int y = 18; bool gps_state = _task->getGPSState(); -#ifdef PIN_GPS_SWITCH - bool hw_gps_state = digitalRead(PIN_GPS_SWITCH); + bool hw_gps_state = nmea != NULL && nmea->isHardwareEnabled(); + if (nmea != NULL && nmea->hasHardwareEnableState()) { if (gps_state != hw_gps_state) { strcpy(buf, gps_state ? "gps off(hw)" : "gps off(sw)"); } else { strcpy(buf, gps_state ? "gps on" : "gps off"); } -#else + } else { strcpy(buf, gps_state ? "gps on" : "gps off"); -#endif + } display.setColor(UIColor::primary_txt); display.drawTextLeftAlign(0, y, buf); if (nmea == NULL) { diff --git a/examples/companion_radio/ui-tiny/UITask.cpp b/examples/companion_radio/ui-tiny/UITask.cpp index 6bf338497..035340a8f 100644 --- a/examples/companion_radio/ui-tiny/UITask.cpp +++ b/examples/companion_radio/ui-tiny/UITask.cpp @@ -254,16 +254,16 @@ public: char buf[50]; int y = 8; bool gps_state = _task->getGPSState(); -#ifdef PIN_GPS_SWITCH - bool hw_gps_state = digitalRead(PIN_GPS_SWITCH); + bool hw_gps_state = nmea != NULL && nmea->isHardwareEnabled(); + if (nmea != NULL && nmea->hasHardwareEnableState()) { if (gps_state != hw_gps_state) { strcpy(buf, gps_state ? "gps off(hw)" : "gps off(sw)"); } else { strcpy(buf, gps_state ? "gps on" : "gps off"); } -#else + } else { strcpy(buf, gps_state ? "gps on" : "gps off"); -#endif + } display.setColor(UIColor::primary_txt); display.drawTextLeftAlign(0, y, buf); if (nmea == NULL) { diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index dc8932586..1d975a94d 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -159,6 +159,9 @@ protected: #if ENV_INCLUDE_GPS == 1 void applyGpsPrefs() { + char period[11]; + snprintf(period, sizeof(period), "%lu", (unsigned long)_prefs.gps_period); + sensors.setSettingValue("gps_period", period); sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0"); } #endif diff --git a/examples/simple_room_server/MyMesh.h b/examples/simple_room_server/MyMesh.h index 4dee8bdbf..5f8de73a3 100644 --- a/examples/simple_room_server/MyMesh.h +++ b/examples/simple_room_server/MyMesh.h @@ -168,6 +168,9 @@ protected: #if ENV_INCLUDE_GPS == 1 void applyGpsPrefs() { + char period[11]; + snprintf(period, sizeof(period), "%lu", (unsigned long)_prefs.gps_period); + sensors.setSettingValue("gps_period", period); sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0"); } #endif diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index 590ca0c76..b93939de3 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -173,6 +173,9 @@ private: #if ENV_INCLUDE_GPS == 1 void applyGpsPrefs() { + char period[11]; + snprintf(period, sizeof(period), "%lu", (unsigned long)_prefs.gps_period); + sensors.setSettingValue("gps_period", period); sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0"); } #endif diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index 5d7501d99..613f2578c 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -368,6 +368,24 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re } else { strcpy(reply, "gps toggle not found"); } + } else if (memcmp(command, "gps period ", 11) == 0) { + char* end = nullptr; + unsigned long period = strtoul(command + 11, &end, 10); + if (command[11] == '\0' || *end != '\0' || period > 86400) { + strcpy(reply, "gps period must be 0-86400 seconds"); + } else { + char period_value[11]; + snprintf(period_value, sizeof(period_value), "%lu", period); + if (_sensors->setSettingValue("gps_period", period_value) && + _sensors->setSettingValue("gps", "1")) { + _prefs->gps_period = (uint32_t)period; + _prefs->gps_enabled = 1; + savePrefs(); + strcpy(reply, "ok"); + } else { + strcpy(reply, "gps provider not found"); + } + } } else if (memcmp(command, "gps sync", 8) == 0) { LocationProvider * l = _sensors->getLocationProvider(); if (l != NULL) { diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 675df7a4b..06778a602 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -61,6 +61,7 @@ public: // Gps settings uint8_t gps_enabled = 0; uint32_t gps_interval = 0; // in seconds + uint32_t gps_period = 0; // periodic acquisition interval in seconds uint8_t advert_loc_policy = 0; uint32_t discovery_mod_timestamp = 0; float adc_multiplier = 0; @@ -158,6 +159,7 @@ private: void structure() override { def("en", _parent->gps_enabled); // boolean def("int", _parent->gps_interval); // interval in seconds + def("period", _parent->gps_period); // periodic acquisition interval in seconds def("adv_loc", _parent->advert_loc_policy); } public: diff --git a/src/helpers/sensors/AirohaGpsDriver.h b/src/helpers/sensors/AirohaGpsDriver.h new file mode 100644 index 000000000..36d5eb6b5 --- /dev/null +++ b/src/helpers/sensors/AirohaGpsDriver.h @@ -0,0 +1,83 @@ +#pragma once + +#include "NmeaGpsDriver.h" + +class AirohaGpsDriver : public NmeaGpsDriver { + bool waitFor(const char* prefix, uint32_t timeout_ms) { // TODO: Refactor so it doesn't block the loop ! + char sentence[100]; + size_t length = 0; + const size_t prefixLength = strlen(prefix); + const uint32_t deadline = millis() + timeout_ms; + + while ((int32_t)(millis() - deadline) < 0) { + if (available() <= 0) { + yield(); + continue; + } + + const char c = (char)read(); +#ifdef GPS_NMEA_DEBUG + Serial.print(c); +#endif + if (c == '$') length = 0; + if (length < sizeof(sentence) - 1) { + sentence[length++] = c; + sentence[length] = '\0'; + if (length >= prefixLength && strncmp(sentence, prefix, prefixLength) == 0) { + return true; + } + } + } + return false; + } + + void enterBackupSleep() { + for (uint8_t attempt = 0; attempt < 3; attempt++) { + drain(); + sendNmeaSentence("$PAIR650,0"); + if (waitFor("$PAIR001,650,0", 50)) { +#ifdef GPS_NMEA_DEBUG + Serial.printf("Airoha RTC backup sleep accepted after %u attempts\r\n", attempt + 1); +#endif + waitFor("$PAIR650,0", 50); + return; + } + } + } + +public: + AirohaGpsDriver(HardwareSerial& serial) + : NmeaGpsDriver(serial, -1, -1, -1, -1, nullptr, HIGH, LOW, 115200) {} + + void initialize() { + NmeaGpsDriver::begin(); + reset(); + } + + void begin() override { + NmeaGpsDriver::begin(); + digitalWrite(GPS_EN, HIGH); + delay(10); + digitalWrite(GPS_RTC_INT, HIGH); + delay(5); + digitalWrite(GPS_RTC_INT, LOW); + } + + void reset() override { + digitalWrite(GPS_RESET, HIGH); + delay(10); + digitalWrite(GPS_RESET, LOW); + } + + void stop() override { + digitalWrite(GPS_VRTC_EN, HIGH); + digitalWrite(GPS_RTC_INT, LOW); + enterBackupSleep(); + digitalWrite(GPS_EN, LOW); + NmeaGpsDriver::stop(); + } + + bool isEnabled() const override { + return digitalRead(GPS_EN) == HIGH; + } +}; diff --git a/src/helpers/sensors/EnvironmentSensorManager.cpp b/src/helpers/sensors/EnvironmentSensorManager.cpp index 0dc892c3a..2861fac2f 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.cpp +++ b/src/helpers/sensors/EnvironmentSensorManager.cpp @@ -160,56 +160,6 @@ static Adafruit_VL53L0X VL53L0X; static RAK12035_SoilMoisture RAK12035; #endif -#if ENV_INCLUDE_GPS && defined(RAK_BOARD) && !defined(RAK_WISMESH_TAG) -#define RAK_WISBLOCK_GPS -#endif - -#ifdef RAK_WISBLOCK_GPS -static uint32_t gpsResetPin = 0; -static bool i2cGPSFlag = false; -static bool serialGPSFlag = false; -#ifndef TELEM_RAK12500_ADDRESS -#define TELEM_RAK12500_ADDRESS 0x42 //RAK12500 Ublox GPS via i2c -#endif -#include -static SFE_UBLOX_GNSS ublox_GNSS; - -class RAK12500LocationProvider : public LocationProvider { - long _lat = 0; - long _lng = 0; - long _alt = 0; - int _sats = 0; - long _epoch = 0; - bool _fix = false; -public: - long getLatitude() override { return _lat; } - long getLongitude() override { return _lng; } - long getAltitude() override { return _alt; } - long satellitesCount() override { return _sats; } - bool isValid() override { return _fix; } - long getTimestamp() override { return _epoch; } - void sendSentence(const char * sentence) override { } - void reset() override { } - void begin() override { } - void stop() override { } - void loop() override { - if (ublox_GNSS.getGnssFixOk(8)) { - _fix = true; - _lat = ublox_GNSS.getLatitude(2) / 10; - _lng = ublox_GNSS.getLongitude(2) / 10; - _alt = ublox_GNSS.getAltitude(2); - _sats = ublox_GNSS.getSIV(2); - } else { - _fix = false; - } - _epoch = ublox_GNSS.getUnixEpoch(2); - } - bool isEnabled() override { return true; } -}; - -static RAK12500LocationProvider RAK12500_provider; -#endif - // ============================================================ // I2C bus scanner // Probes every valid address and records which ones ACK. @@ -624,12 +574,8 @@ static const size_t SENSOR_TABLE_SIZE = (sizeof(SENSOR_TABLE) / sizeof(SENSOR_TA bool EnvironmentSensorManager::begin() { #if ENV_INCLUDE_GPS - #ifdef RAK_WISBLOCK_GPS - rakGPSInit(); - #else initBasicGPS(); #endif - #endif #if ENV_PIN_SDA && ENV_PIN_SCL #ifdef NRF52_PLATFORM @@ -684,9 +630,11 @@ bool EnvironmentSensorManager::begin() { bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, CayenneLPP& telemetry) { next_available_channel = TELEM_CHANNEL_SELF + 1; - if (requester_permissions & TELEM_PERM_LOCATION && gps_active) { + #if ENV_INCLUDE_GPS + if (requester_permissions & TELEM_PERM_LOCATION && _location->isEnabled()) { telemetry.addGPS(TELEM_CHANNEL_SELF, node_lat, node_lon, node_altitude); } + #endif if (requester_permissions & TELEM_PERM_ENVIRONMENT) { for (int i = 0; i < _active_sensor_count; i++) { @@ -702,7 +650,7 @@ bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, Cayen int EnvironmentSensorManager::getNumSettings() const { int settings = 0; #if ENV_INCLUDE_GPS - if (gps_detected) settings++; // only show GPS setting if GPS is detected + if (gps_detected) settings += 2; // GPS enablement and periodic acquisition #endif return settings; } @@ -713,6 +661,9 @@ const char* EnvironmentSensorManager::getSettingName(int i) const { if (gps_detected && i == settings++) { return "gps"; } + if (gps_detected && i == settings++) { + return "gps_period"; + } #endif return NULL; } @@ -721,7 +672,13 @@ const char* EnvironmentSensorManager::getSettingValue(int i) const { int settings = 0; #if ENV_INCLUDE_GPS if (gps_detected && i == settings++) { - return gps_active ? "1" : "0"; + return _location->isGpsOn() ? "1" : "0"; + } + if (gps_detected && i == settings++) { + static char period[11]; + snprintf(period, sizeof(period), "%lu", + (unsigned long)_location->getGpsPeriod()); + return period; } #endif return NULL; @@ -737,6 +694,13 @@ bool EnvironmentSensorManager::setSettingValue(const char* name, const char* val } return true; } + if (gps_detected && strcmp(name, "gps_period") == 0) { + char* end = nullptr; + unsigned long period = strtoul(value, &end, 10); + if (*value == '\0' || *end != '\0' || period > 86400) return false; + _location->setGpsPeriod((uint32_t)period); + return true; + } if (strcmp(name, "gps_interval") == 0) { uint32_t interval_seconds = atoi(value); gps_update_interval_sec = interval_seconds > 0 ? interval_seconds : 1; @@ -748,157 +712,35 @@ bool EnvironmentSensorManager::setSettingValue(const char* name, const char* val #if ENV_INCLUDE_GPS void EnvironmentSensorManager::initBasicGPS() { - - Serial1.setPins(PIN_GPS_TX, PIN_GPS_RX); - - #ifdef GPS_BAUD_RATE - Serial1.begin(GPS_BAUD_RATE); - #else - Serial1.begin(9600); - #endif - - // Try to detect if GPS is physically connected to determine if we should expose the setting - _location->begin(); - _location->reset(); + start_gps(); #ifndef PIN_GPS_EN MESH_DEBUG_PRINTLN("No GPS wake/reset pin found for this board. Continuing on..."); #endif - // Give the GPS time to power up and emit its first NMEA sentence. Cold-start - // modules can take several seconds, so poll for up to ~5s instead of checking - // once after a fixed 1s delay -- returning as soon as any data appears, so - // fast modules add no boot delay (issue #2258). #ifdef ENV_SKIP_GPS_DETECT gps_detected = true; #else - gps_detected = false; - for (int i = 0; i < 20 && !gps_detected; i++) { - delay(250); - gps_detected = (Serial1.available() > 0); - } + gps_detected = _location->detect(5000); #endif if (gps_detected) { MESH_DEBUG_PRINTLN("GPS detected"); - #ifdef PERSISTANT_GPS - gps_active = true; + #if defined(PERSISTANT_GPS) return; + #else + if (_location->keepEnabledAfterDetection()) { + return; + } #endif } else { MESH_DEBUG_PRINTLN("No GPS detected"); } - _location->stop(); - gps_active = false; //Set GPS visibility off until setting is changed -} - -// gps code for rak might be moved to MicroNMEALoactionProvider -// or make a new location provider ... -#ifdef RAK_WISBLOCK_GPS -void EnvironmentSensorManager::rakGPSInit(){ - - Serial1.setPins(PIN_GPS_TX, PIN_GPS_RX); - - #ifdef GPS_BAUD_RATE - Serial1.begin(GPS_BAUD_RATE); - #else - Serial1.begin(9600); - #endif - - //search for the correct IO standby pin depending on socket used - if(gpsIsAwake(WB_IO2)){ - } - else if(gpsIsAwake(WB_IO4)){ - } - else if(gpsIsAwake(WB_IO5)){ - } - else{ - MESH_DEBUG_PRINTLN("No GPS found"); - gps_active = false; - gps_detected = false; - Serial1.end(); - return; - } - - #ifndef FORCE_GPS_ALIVE // for use with repeaters, until GPS toggle is implimented - //Now that GPS is found and set up, set to sleep for initial state stop_gps(); - #endif } -bool EnvironmentSensorManager::gpsIsAwake(uint8_t ioPin){ - - #if defined(ETHERNET_ENABLED) && defined(RAK_BOARD) - if (ioPin == WB_IO2) { - // WB_IO2 powers the Ethernet module on RAK baseboards. - return false; - } - #endif - - #ifndef RAK_3401 - //set initial waking state - pinMode(ioPin,OUTPUT); - digitalWrite(ioPin,LOW); - delay(500); - digitalWrite(ioPin,HIGH); - #endif - - // give gps time to power up - delay(500); - - //Try to init RAK12500 on I2C - if (ublox_GNSS.begin(Wire) == true){ - MESH_DEBUG_PRINTLN("RAK12500 GPS init correctly with pin %i",ioPin); - ublox_GNSS.setI2COutput(COM_TYPE_UBX); - ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_GPS); - ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_GALILEO); - ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_GLONASS); - ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_SBAS); - ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_BEIDOU); - ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_IMES); - ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_QZSS); - ublox_GNSS.setMeasurementRate(1000); - ublox_GNSS.saveConfigSelective(VAL_CFG_SUBSEC_IOPORT); - gpsResetPin = ioPin; - i2cGPSFlag = true; - gps_active = true; - gps_detected = true; - - _location = &RAK12500_provider; - return true; - } else if (Serial1.available()) { - MESH_DEBUG_PRINTLN("Serial GPS init correctly and is turned on"); -#ifdef PIN_GPS_EN - if(PIN_GPS_EN){ - gpsResetPin = PIN_GPS_EN; - } -#endif - serialGPSFlag = true; - gps_active = true; - gps_detected = true; - return true; - } - - #ifndef RAK_3401 - pinMode(ioPin, INPUT); - #endif - MESH_DEBUG_PRINTLN("GPS did not init with this IO pin... try the next"); - return false; -} -#endif - void EnvironmentSensorManager::start_gps() { - gps_active = true; - #ifdef RAK_WISBLOCK_GPS - #ifndef RAK_3401 - pinMode(gpsResetPin, OUTPUT); - digitalWrite(gpsResetPin, HIGH); - #endif - return; - #endif - - _location->begin(); - _location->reset(); + _location->setGpsOn(true); #ifndef PIN_GPS_EN MESH_DEBUG_PRINTLN("Start GPS is N/A on this board. Actual GPS state unchanged"); @@ -906,20 +748,11 @@ void EnvironmentSensorManager::start_gps() { } void EnvironmentSensorManager::stop_gps() { - gps_active = false; - #ifdef RAK_WISBLOCK_GPS - #ifndef RAK_3401 // rak3401 shouldn't turn off WB_IO2 as it powers the PA - pinMode(gpsResetPin, OUTPUT); - digitalWrite(gpsResetPin, LOW); - #endif - return; - #endif + _location->setGpsOn(false); - _location->stop(); - - #ifndef PIN_GPS_EN +#ifndef PIN_GPS_EN MESH_DEBUG_PRINTLN("Stop GPS is N/A on this board. Actual GPS state unchanged"); - #endif +#endif } #endif // ENV_INCLUDE_GPS @@ -928,30 +761,16 @@ void EnvironmentSensorManager::loop() { #if ENV_INCLUDE_GPS static unsigned long next_gps_update = 0; - if (gps_active) { - _location->loop(); - } + _location->loop(); if ((long)(millis() - next_gps_update) > 0) { - if(gps_active){ - #ifdef RAK_WISBLOCK_GPS - if ((i2cGPSFlag || serialGPSFlag) && _location->isValid()) { + if (_location->isEnabled() && _location->isValid()) { node_lat = ((double)_location->getLatitude())/1000000.; node_lon = ((double)_location->getLongitude())/1000000.; MESH_DEBUG_PRINTLN("lat %f lon %f", node_lat, node_lon); node_altitude = ((double)_location->getAltitude()) / 1000.0; MESH_DEBUG_PRINTLN("lat %f lon %f alt %f", node_lat, node_lon, node_altitude); } - #else - if (_location->isValid()) { - node_lat = ((double)_location->getLatitude())/1000000.; - node_lon = ((double)_location->getLongitude())/1000000.; - MESH_DEBUG_PRINTLN("lat %f lon %f", node_lat, node_lon); - node_altitude = ((double)_location->getAltitude()) / 1000.0; - MESH_DEBUG_PRINTLN("lat %f lon %f alt %f", node_lat, node_lon, node_altitude); - } - #endif - } next_gps_update = millis() + (gps_update_interval_sec * 1000); } #endif diff --git a/src/helpers/sensors/EnvironmentSensorManager.h b/src/helpers/sensors/EnvironmentSensorManager.h index 17706cbc4..425415a17 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.h +++ b/src/helpers/sensors/EnvironmentSensorManager.h @@ -20,7 +20,6 @@ protected: uint8_t next_available_channel = TELEM_CHANNEL_SELF + 1; bool gps_detected = false; - bool gps_active = false; uint32_t gps_update_interval_sec = 1; #if ENV_INCLUDE_GPS @@ -28,10 +27,6 @@ protected: void start_gps(); void stop_gps(); void initBasicGPS(); - #ifdef RAK_BOARD - void rakGPSInit(); - bool gpsIsAwake(uint8_t ioPin); - #endif #endif public: diff --git a/src/helpers/sensors/GpsDriver.h b/src/helpers/sensors/GpsDriver.h new file mode 100644 index 000000000..b8cf4a5d5 --- /dev/null +++ b/src/helpers/sensors/GpsDriver.h @@ -0,0 +1,18 @@ +#pragma once + +#include + +class GpsDriver { +public: + virtual ~GpsDriver() = default; + + virtual void begin() = 0; + virtual void reset() = 0; + virtual void stop() = 0; + virtual bool isEnabled() const = 0; + virtual bool hasHardwareEnableState() const { return false; } + virtual bool isHardwareEnabled() const { return true; } + // Returns true when the switch explicitly enables GPS in software. + virtual bool pollGpsSwitch() { return false; } + virtual bool detect(uint32_t timeout_ms) = 0; +}; diff --git a/src/helpers/sensors/LocationProvider.h b/src/helpers/sensors/LocationProvider.h index bc4f1fe76..93cecf5be 100644 --- a/src/helpers/sensors/LocationProvider.h +++ b/src/helpers/sensors/LocationProvider.h @@ -8,8 +8,11 @@ class LocationProvider { protected: bool _time_sync_needed = true; + bool _gpsOn = false; public: + virtual ~LocationProvider() = default; + virtual void syncTime() { _time_sync_needed = true; } virtual bool waitingTimeSync() { return _time_sync_needed; } virtual long getLatitude() = 0; @@ -21,6 +24,22 @@ public: virtual void sendSentence(const char * sentence); virtual bool waitFor(const char* prefix, uint32_t timeout_ms) { return false; } virtual void drain() { } + virtual bool detect(uint32_t timeout_ms) { return false; } + virtual bool keepEnabledAfterDetection() const { return false; } + virtual void setGpsPeriod(uint32_t seconds) { } + virtual uint32_t getGpsPeriod() const { return 0; } + virtual bool hasHardwareEnableState() const { return false; } + virtual bool isHardwareEnabled() const { return true; } + virtual bool isGpsOn() const { return _gpsOn; } + virtual void setGpsOn(bool on) { + _gpsOn = on; + if (on) { + begin(); + reset(); + } else { + stop(); + } + } virtual void reset() = 0; virtual void begin() = 0; virtual void stop() = 0; diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index 37ef5762c..2e9ff9cc4 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -1,69 +1,30 @@ #pragma once +#include "NmeaGpsDriver.h" #include "LocationProvider.h" #include #include -#include #include -#ifndef GPS_EN - #ifdef PIN_GPS_EN - #define GPS_EN PIN_GPS_EN - #else - #define GPS_EN (-1) - #endif -#endif - -#ifndef GPS_EN_ACTIVE - #ifdef PIN_GPS_EN_ACTIVE - #define GPS_EN_ACTIVE PIN_GPS_EN_ACTIVE - #else - #define GPS_EN_ACTIVE HIGH - #endif -#endif - -#ifndef GPS_RESET - #ifdef PIN_GPS_RESET - #define GPS_RESET PIN_GPS_RESET - #else - #define GPS_RESET (-1) - #endif -#endif - -#ifndef GPS_RESET_ACTIVE - #ifdef PIN_GPS_RESET_ACTIVE - #define GPS_RESET_ACTIVE PIN_GPS_RESET_ACTIVE - #else - #define GPS_RESET_ACTIVE LOW - #endif +#ifndef GPS_PERIODIC_ACQUISITION_TIMEOUT_MS + #define GPS_PERIODIC_ACQUISITION_TIMEOUT_MS 120000UL #endif class MicroNMEALocationProvider : public LocationProvider { char _nmeaBuffer[100]; MicroNMEA nmea; mesh::RTCClock* _clock; - Stream* _gps_serial; - RefCountedDigitalPin* _peripher_power; - int8_t _claims = 0; - int _pin_reset; - int _pin_en; + NmeaGpsDriver* _driver; + bool _ownsDriver = false; unsigned long next_check = 0; long time_valid = 0; unsigned long _last_time_sync = 0; - static const unsigned long TIME_SYNC_INTERVAL = 1800000; // Re-sync every 30 minutes + uint32_t _gpsPeriodSeconds = 0; + unsigned long _nextAcquisition = 0; + unsigned long _acquisitionStarted = 0; + bool _acquiringPeriodically = false; + static const unsigned long TIME_SYNC_INTERVAL = 1800000; -#ifdef GPS_L76K - void configureL76K() { - // Reapply the constellation mode at each provider start instead of - // assuming it survives a receiver power cycle. - // Mode 7 enables GPS + BeiDou + GLONASS. - delay(250); - MicroNMEA::sendSentence(*_gps_serial, "$PCAS04,7"); - delay(250); - } -#endif - // Observation-only diagnostics. These fields do not change GPS power, - // timing, reset behaviour, or parser input. uint32_t _uart_bytes = 0; uint32_t _nmea_checksum_ok = 0; uint32_t _nmea_checksum_bad = 0; @@ -88,79 +49,121 @@ class MicroNMEALocationProvider : public LocationProvider { } } -public : - MicroNMEALocationProvider(Stream& ser, mesh::RTCClock* clock = NULL, int pin_reset = GPS_RESET, int pin_en = GPS_EN,RefCountedDigitalPin* peripher_power=NULL) : - nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), _gps_serial(&ser), _peripher_power(peripher_power), _pin_reset(pin_reset), _pin_en(pin_en) { - if (_pin_reset != -1) { - pinMode(_pin_reset, OUTPUT); - digitalWrite(_pin_reset, GPS_RESET_ACTIVE); - } - if (_pin_en != -1) { - pinMode(_pin_en, OUTPUT); - digitalWrite(_pin_en, !GPS_EN_ACTIVE); - } + void startPeriodicAcquisition() { + nmea.clear(); + time_valid = 0; + _driver->begin(); + _driver->reset(); + _acquiringPeriodically = true; + _acquisitionStarted = millis(); } - void claim() { - _claims++; - if (_peripher_power) _peripher_power->claim(); + void finishPeriodicAcquisition() { + _driver->stop(); + _acquiringPeriodically = false; + _nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL; } - void release() { - if (_claims == 0) return; // avoid negative _claims - _claims--; - if (_peripher_power) _peripher_power->release(); + void updateTime() { + if (!isValid()) time_valid = 0; + + if ((long)(millis() - next_check) <= 0) return; + next_check = millis() + 1000; + + if (!_time_sync_needed && _clock != nullptr && + (millis() - _last_time_sync) > TIME_SYNC_INTERVAL) { + _time_sync_needed = true; + } + if (_time_sync_needed && time_valid > 2 && _clock != nullptr) { + _clock->setCurrentTime(getTimestamp()); + _time_sync_needed = false; + _last_time_sync = millis(); + } + if (isValid()) time_valid++; + } + +public: + MicroNMEALocationProvider(NmeaGpsDriver& driver, mesh::RTCClock* clock = nullptr) + : nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), _driver(&driver) {} + + // Temporary migration adapter for targets and downstream boards. New code + // should inject a GpsDriver; this constructor will be removed once targets + // have been migrated. + MicroNMEALocationProvider(HardwareSerial& serial, mesh::RTCClock* clock = nullptr, + int pin_reset = GPS_RESET, int pin_en = GPS_EN, + RefCountedDigitalPin* peripher_power = nullptr) + : nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), + _driver(new NmeaGpsDriver(serial, PIN_GPS_TX, PIN_GPS_RX, pin_reset, pin_en, + peripher_power)), + _ownsDriver(true) {} + + MicroNMEALocationProvider(Stream& serial, mesh::RTCClock* clock = nullptr, + int pin_reset = GPS_RESET, int pin_en = GPS_EN, + RefCountedDigitalPin* peripher_power = nullptr) + : nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), + _driver(new NmeaGpsDriver(serial, PIN_GPS_TX, PIN_GPS_RX, pin_reset, pin_en, + peripher_power)), + _ownsDriver(true) {} + + ~MicroNMEALocationProvider() override { + if (_ownsDriver) delete _driver; } void begin() override { _begin_calls++; - claim(); - if (_pin_en != -1) { - digitalWrite(_pin_en, GPS_EN_ACTIVE); - } - if (_pin_reset != -1) { - digitalWrite(_pin_reset, !GPS_RESET_ACTIVE); + _driver->begin(); + if (_gpsPeriodSeconds > 0 && _driver->isEnabled()) { + nmea.clear(); + time_valid = 0; + _acquiringPeriodically = true; + _acquisitionStarted = millis(); } } void reset() override { - if (_pin_reset != -1) { - digitalWrite(_pin_reset, GPS_RESET_ACTIVE); - delay(10); - digitalWrite(_pin_reset, !GPS_RESET_ACTIVE); - } -#ifdef GPS_L76K - // EnvironmentSensorManager calls reset() immediately after begin(). - // Configure only after that reset so the setting is not discarded. - configureL76K(); -#endif + _driver->reset(); } void stop() override { _stop_calls++; - if (_pin_en != -1) { - digitalWrite(_pin_en, !GPS_EN_ACTIVE); - } - if (_pin_reset != -1) { - digitalWrite(_pin_reset, GPS_RESET_ACTIVE); - } - release(); + _acquiringPeriodically = false; + _driver->stop(); } bool isEnabled() override { - // directly read the enable pin if present as gps can be - // activated/deactivated outside of here ... - if (_pin_en != -1) { - return digitalRead(_pin_en) == GPS_EN_ACTIVE; - } else { - return true; // no enable so must be active - } + return _driver->isEnabled(); + } + + bool hasHardwareEnableState() const override { + return _driver->hasHardwareEnableState(); + } + + bool isHardwareEnabled() const override { + return _driver->isHardwareEnabled(); + } + + bool detect(uint32_t timeout_ms) override { + return _driver->detect(timeout_ms); + } + + void setGpsPeriod(uint32_t seconds) override { + _gpsPeriodSeconds = seconds; + _nextAcquisition = millis(); + _acquiringPeriodically = false; + } + + uint32_t getGpsPeriod() const override { + return _gpsPeriodSeconds; + } + + void syncTime() override { + nmea.clear(); + LocationProvider::syncTime(); } - void syncTime() override { nmea.clear(); LocationProvider::syncTime(); } long getLatitude() override { return nmea.getLatitude(); } long getLongitude() override { return nmea.getLongitude(); } - long getAltitude() override { + long getAltitude() override { long alt = 0; nmea.getAltitude(alt); return alt; @@ -168,29 +171,31 @@ public : long satellitesCount() override { return nmea.getNumSatellites(); } bool isValid() override { return nmea.isValid(); } - long getTimestamp() override { - DateTime dt(nmea.getYear(), nmea.getMonth(),nmea.getDay(),nmea.getHour(),nmea.getMinute(),nmea.getSecond()); + long getTimestamp() override { + DateTime dt(nmea.getYear(), nmea.getMonth(), nmea.getDay(), + nmea.getHour(), nmea.getMinute(), nmea.getSecond()); return dt.unixtime(); - } - - void drain() { while (_gps_serial->available()) _gps_serial->read(); } - - const char* getSentence() const { return nmea.getSentence(); } - - void sendSentence(const char *sentence) override { - nmea.sendSentence(*_gps_serial, sentence); } - bool waitFor(const char* prefix, uint32_t timeout_ms) { - size_t plen = strlen(prefix); - uint32_t timeout = millis() + timeout_ms; - while ((int32_t)(millis() - timeout) < 0) { - if (_gps_serial->available()) { - char c = _gps_serial->read(); - #ifdef GPS_NMEA_DEBUG + void drain() override { _driver->drain(); } + const char* getSentence() const { return nmea.getSentence(); } + + void sendSentence(const char* sentence) override { + _driver->sendNmeaSentence(sentence); + } + + bool waitFor(const char* prefix, uint32_t timeout_ms) override { + const size_t prefixLength = strlen(prefix); + const uint32_t deadline = millis() + timeout_ms; + while ((int32_t)(millis() - deadline) < 0) { + if (_driver->available() > 0) { + const char c = (char)_driver->read(); +#ifdef GPS_NMEA_DEBUG Serial.print(c); - #endif - if (nmea.process(c) && strncmp(nmea.getSentence(), prefix, plen) == 0) return true; +#endif + if (nmea.process(c) && strncmp(nmea.getSentence(), prefix, prefixLength) == 0) { + return true; + } } else { yield(); } @@ -199,34 +204,35 @@ public : } void loop() override { + if (_driver->pollGpsSwitch()) _gpsOn = true; - while (_gps_serial->available()) { - char c = _gps_serial->read(); + if (_gpsOn && _gpsPeriodSeconds > 0 && !_acquiringPeriodically && + (long)(millis() - _nextAcquisition) >= 0) { + startPeriodicAcquisition(); + } + + while (_driver->available() > 0) { + const char c = (char)_driver->read(); _uart_bytes++; _last_uart_ms = millis(); _uart_seen = true; - #ifdef GPS_NMEA_DEBUG +#ifdef GPS_NMEA_DEBUG Serial.print(c); - #endif - bool parsed = nmea.process(c); +#endif + const bool parsed = nmea.process(c); - // MicroNMEA leaves the completed sentence in its buffer after the - // first line terminator. CRLF therefore counts once: CR observes the - // sentence, then LF clears the now-empty buffer. if ((c == '\0' || c == '\r' || c == '\n') && nmea.getSentence()[0] != '\0') { if (MicroNMEA::testChecksum(nmea.getSentence())) { _nmea_checksum_ok++; _last_nmea_ms = millis(); _nmea_seen = true; - // Refresh fix age only when a newly parsed GGA/RMC sentence - // carries a valid fix. Other valid NMEA sentences must not - // make an old position look fresh. - const char* message_id = nmea.getMessageID(); + const char* messageId = nmea.getMessageID(); if (parsed && isValid() && - (strcmp(message_id, "GGA") == 0 || strcmp(message_id, "RMC") == 0)) { + (strcmp(messageId, "GGA") == 0 || strcmp(messageId, "RMC") == 0)) { _last_fix_ms = millis(); _fix_seen = true; + if (_acquiringPeriodically) finishPeriodicAcquisition(); } } else { _nmea_checksum_bad++; @@ -234,25 +240,12 @@ public : } } - if (!isValid()) time_valid = 0; - - if ((long)(millis() - next_check) > 0) { - next_check = millis() + 1000; - // Re-enable time sync periodically when GPS has valid fix - if (!_time_sync_needed && _clock != NULL && (millis() - _last_time_sync) > TIME_SYNC_INTERVAL) { - _time_sync_needed = true; - } - if (_time_sync_needed && time_valid > 2) { - if (_clock != NULL) { - _clock->setCurrentTime(getTimestamp()); - _time_sync_needed = false; - _last_time_sync = millis(); - } - } - if (isValid()) { - time_valid ++; - } + if (_acquiringPeriodically && + (uint32_t)(millis() - _acquisitionStarted) >= GPS_PERIODIC_ACQUISITION_TIMEOUT_MS) { + finishPeriodicAcquisition(); } + + updateTime(); } void formatDiagnostics(char* out, size_t out_size) override { @@ -265,8 +258,6 @@ public : formatAge(nmea_age, sizeof(nmea_age), _nmea_seen, _last_nmea_ms); formatAge(fix_age, sizeof(fix_age), _fix_seen, _last_fix_ms); - // Compact enough for CommonCLI's 160-byte reply buffer, including the - // "req:" prefix added by CommonCLI. snprintf(out, out_size, "en:%u ub:%lu ua:%s ok:%lu bad:%lu na:%s sat:%ld fix:%u fa:%s bc:%lu sc:%lu", isEnabled() ? 1U : 0U, diff --git a/src/helpers/sensors/NmeaGpsDriver.h b/src/helpers/sensors/NmeaGpsDriver.h new file mode 100644 index 000000000..f9ea5124a --- /dev/null +++ b/src/helpers/sensors/NmeaGpsDriver.h @@ -0,0 +1,262 @@ +#pragma once + +#include "GpsDriver.h" + +#include +#include + +#ifndef PIN_GPS_TX + #define PIN_GPS_TX (-1) +#endif + +#ifndef PIN_GPS_RX + #define PIN_GPS_RX (-1) +#endif + +#ifndef GPS_EN + #ifdef PIN_GPS_EN + #define GPS_EN PIN_GPS_EN + #else + #define GPS_EN (-1) + #endif +#endif + +#ifndef GPS_EN_ACTIVE + #ifdef PIN_GPS_EN_ACTIVE + #define GPS_EN_ACTIVE PIN_GPS_EN_ACTIVE + #else + #define GPS_EN_ACTIVE HIGH + #endif +#endif + +#ifndef GPS_RESET + #ifdef PIN_GPS_RESET + #define GPS_RESET PIN_GPS_RESET + #else + #define GPS_RESET (-1) + #endif +#endif + +#ifndef GPS_RESET_ACTIVE + #ifdef PIN_GPS_RESET_ACTIVE + #define GPS_RESET_ACTIVE PIN_GPS_RESET_ACTIVE + #else + #define GPS_RESET_ACTIVE LOW + #endif +#endif + +#ifndef GPS_BAUD_RATE + #define GPS_BAUD_RATE 9600 +#endif + +#ifndef PIN_GPS_SWITCH + #define PIN_GPS_SWITCH (-1) +#endif + +#ifndef GPS_SWITCH_ACTIVE + #define GPS_SWITCH_ACTIVE HIGH +#endif + +#ifndef GPS_SWITCH_IS_HARDWARE + #define GPS_SWITCH_IS_HARDWARE 1 +#endif + +#ifndef GPS_SWITCH_TURNS_GPS_ON + #define GPS_SWITCH_TURNS_GPS_ON 0 +#endif + +class NmeaGpsDriver : public GpsDriver { + Stream* _stream = nullptr; + HardwareSerial* _hardwareSerial = nullptr; + RefCountedDigitalPin* _peripheralPower = nullptr; + int _txPin = -1; + int _rxPin = -1; + int _resetPin = -1; + int _enablePin = -1; + int _enableActive = HIGH; + int _resetActive = LOW; + uint32_t _baudRate = 9600; + int _hardwareEnablePin = -1; + int _hardwareEnableActive = HIGH; + bool _started = false; +#if !GPS_SWITCH_IS_HARDWARE + bool _requestedOn = false; + bool _switchStateKnown = false; + bool _lastSwitchEnabled = false; + unsigned long _nextSwitchPoll = 0; +#endif + + void startHardware() { + if (_stream == nullptr || _started) return; + + if (_hardwareSerial != nullptr) { +#ifdef ESP32_PLATFORM + _hardwareSerial->setPins(_txPin, _rxPin); +#endif + _hardwareSerial->begin(_baudRate); + } + + if (_peripheralPower != nullptr) _peripheralPower->claim(); + + if (_enablePin != -1) digitalWrite(_enablePin, _enableActive); + if (_resetPin != -1) digitalWrite(_resetPin, !_resetActive); + _started = true; + } + + void stopHardware() { + if (!_started) return; + + if (_enablePin != -1) digitalWrite(_enablePin, !_enableActive); + if (_resetPin != -1) digitalWrite(_resetPin, _resetActive); + + if (_peripheralPower != nullptr) _peripheralPower->release(); + _started = false; + } + +public: + NmeaGpsDriver() = default; + + NmeaGpsDriver(Stream& stream, int txPin = PIN_GPS_TX, int rxPin = PIN_GPS_RX, + int resetPin = GPS_RESET, int enablePin = GPS_EN, + RefCountedDigitalPin* peripheralPower = nullptr, + int enableActive = GPS_EN_ACTIVE, int resetActive = GPS_RESET_ACTIVE, + uint32_t baudRate = GPS_BAUD_RATE, + int hardwareEnablePin = PIN_GPS_SWITCH, + int hardwareEnableActive = GPS_SWITCH_ACTIVE) + : _stream(&stream), _peripheralPower(peripheralPower), _txPin(txPin), _rxPin(rxPin), + _resetPin(resetPin), _enablePin(enablePin), _enableActive(enableActive), + _resetActive(resetActive), _baudRate(baudRate), + _hardwareEnablePin(hardwareEnablePin), _hardwareEnableActive(hardwareEnableActive) { + if (_resetPin != -1) { + pinMode(_resetPin, OUTPUT); + digitalWrite(_resetPin, _resetActive); + } + if (_enablePin != -1) { + pinMode(_enablePin, OUTPUT); + digitalWrite(_enablePin, !_enableActive); + } + if (_hardwareEnablePin != -1) { + pinMode(_hardwareEnablePin, INPUT); + } + } + + NmeaGpsDriver(HardwareSerial& serial, int txPin = PIN_GPS_TX, int rxPin = PIN_GPS_RX, + int resetPin = GPS_RESET, int enablePin = GPS_EN, + RefCountedDigitalPin* peripheralPower = nullptr, + int enableActive = GPS_EN_ACTIVE, int resetActive = GPS_RESET_ACTIVE, + uint32_t baudRate = GPS_BAUD_RATE, + int hardwareEnablePin = PIN_GPS_SWITCH, + int hardwareEnableActive = GPS_SWITCH_ACTIVE) + : NmeaGpsDriver(static_cast(serial), txPin, rxPin, resetPin, enablePin, + peripheralPower, enableActive, resetActive, baudRate, + hardwareEnablePin, hardwareEnableActive) { + _hardwareSerial = &serial; + } + + void begin() override { +#if !GPS_SWITCH_IS_HARDWARE + _requestedOn = true; + if (!isHardwareEnabled()) return; +#endif + startHardware(); + } + + void reset() override { + if (!_started) return; + if (_resetPin != -1) { + digitalWrite(_resetPin, _resetActive); + delay(10); + digitalWrite(_resetPin, !_resetActive); + } + +#ifdef GPS_L76K + delay(250); + sendNmeaSentence("$PCAS04,7"); + delay(250); +#endif + } + + void stop() override { +#if !GPS_SWITCH_IS_HARDWARE + _requestedOn = false; +#endif + stopHardware(); + } + + bool isEnabled() const override { + return _started && isHardwareEnabled(); + } + + bool hasHardwareEnableState() const override { + return _hardwareEnablePin != -1; + } + + bool isHardwareEnabled() const override { + return _hardwareEnablePin == -1 || + digitalRead(_hardwareEnablePin) == _hardwareEnableActive; + } + + bool pollGpsSwitch() override { +#if !GPS_SWITCH_IS_HARDWARE + if (_hardwareEnablePin == -1 || + (long)(millis() - _nextSwitchPoll) < 0) return false; + + _nextSwitchPoll = millis() + 1000; + const bool switchEnabled = isHardwareEnabled(); + const bool enablesGps = GPS_SWITCH_TURNS_GPS_ON && _switchStateKnown && + !_lastSwitchEnabled && switchEnabled; + _switchStateKnown = true; + _lastSwitchEnabled = switchEnabled; + + if (enablesGps) _requestedOn = true; + if (_requestedOn && switchEnabled) { + startHardware(); + } else { + stopHardware(); + } + return enablesGps; +#else + return false; +#endif + } + + bool detect(uint32_t timeout_ms) override { + if (available() > 0) return true; + + const uint32_t deadline = millis() + timeout_ms; + while ((int32_t)(millis() - deadline) < 0) { + if (available() > 0) return true; + delay(10); + } + return false; + } + + int available() { + return _stream == nullptr ? 0 : _stream->available(); + } + + int read() { + return _stream == nullptr ? -1 : _stream->read(); + } + + void drain() { + while (available() > 0) read(); + } + + void sendNmeaSentence(const char* sentence) { + if (_stream == nullptr || sentence == nullptr || sentence[0] != '$') return; + + uint8_t checksum = 0; + const char* p = sentence + 1; + while (*p != '\0' && *p != '*') checksum ^= (uint8_t)*p++; + + _stream->print(sentence); + if (*p == '\0') { + char checksumSuffix[6]; + snprintf(checksumSuffix, sizeof(checksumSuffix), "*%02X\r\n", checksum); + _stream->print(checksumSuffix); + } else { + _stream->print("\r\n"); + } + } +}; diff --git a/src/helpers/sensors/RakGpsDriver.h b/src/helpers/sensors/RakGpsDriver.h new file mode 100644 index 000000000..fb4b772bf --- /dev/null +++ b/src/helpers/sensors/RakGpsDriver.h @@ -0,0 +1,112 @@ +#pragma once + +#include "NmeaGpsDriver.h" + +#include + +class RakGpsDriver : public GpsDriver { + NmeaGpsDriver _serialDriver; + TwoWire& _wire; + SFE_UBLOX_GNSS _gnss; + uint8_t _powerPin = 0; + bool _usingRak12500 = false; + bool _detected = false; + + bool probeRak12500(uint8_t powerPin) { +#if defined(ETHERNET_ENABLED) && defined(RAK_BOARD) + if (powerPin == WB_IO2) return false; +#endif + +#ifndef RAK_3401 + pinMode(powerPin, OUTPUT); + digitalWrite(powerPin, LOW); + delay(500); + digitalWrite(powerPin, HIGH); +#endif + delay(500); + + if (_gnss.begin(_wire)) { + _gnss.setI2COutput(COM_TYPE_UBX); + _gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_GPS); + _gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_GALILEO); + _gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_GLONASS); + _gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_SBAS); + _gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_BEIDOU); + _gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_IMES); + _gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_QZSS); + _gnss.setMeasurementRate(1000); + _gnss.saveConfigSelective(VAL_CFG_SUBSEC_IOPORT); + _powerPin = powerPin; + _usingRak12500 = true; + return true; + } + +#ifndef RAK_3401 + pinMode(powerPin, INPUT); +#endif + return false; + } + +public: + RakGpsDriver(HardwareSerial& serial = Serial1, TwoWire& wire = Wire) + : _serialDriver(serial), _wire(wire) {} + + void begin() override { + if (_usingRak12500) { +#ifndef RAK_3401 + pinMode(_powerPin, OUTPUT); + digitalWrite(_powerPin, HIGH); +#endif + return; + } + _serialDriver.begin(); + } + + void reset() override { + if (!_usingRak12500) _serialDriver.reset(); + } + + void stop() override { + if (_usingRak12500) { +#ifndef RAK_3401 + pinMode(_powerPin, OUTPUT); + digitalWrite(_powerPin, LOW); +#endif + return; + } + _serialDriver.stop(); + } + + bool isEnabled() const override { + return _usingRak12500 ? true : _serialDriver.isEnabled(); + } + + bool detect(uint32_t) override { + if (_detected) return true; + + _serialDriver.begin(); + if (probeRak12500(WB_IO2) || probeRak12500(WB_IO4) || probeRak12500(WB_IO5)) { + _detected = true; + return true; + } + + if (_serialDriver.detect(0)) { + _detected = true; + return true; + } + + _serialDriver.stop(); + return false; + } + + bool usesRak12500() const { return _usingRak12500; } + bool isDetected() const { return _detected; } + NmeaGpsDriver& nmeaDriver() { return _serialDriver; } + + bool hasFix() { return _usingRak12500 && _gnss.getGnssFixOk(8); } + long getLatitude() { return _gnss.getLatitude(2) / 10; } + long getLongitude() { return _gnss.getLongitude(2) / 10; } + long getAltitude() { return _gnss.getAltitude(2); } + long getSatellites() { return _gnss.getSIV(2); } + long getTimestamp() { return _gnss.getUnixEpoch(2); } +}; diff --git a/src/helpers/sensors/RakLocationProvider.h b/src/helpers/sensors/RakLocationProvider.h new file mode 100644 index 000000000..c909b7c42 --- /dev/null +++ b/src/helpers/sensors/RakLocationProvider.h @@ -0,0 +1,144 @@ +#pragma once + +#include "MicroNMEALocationProvider.h" +#include "RakGpsDriver.h" + +class RakLocationProvider : public LocationProvider { + RakGpsDriver& _driver; + MicroNMEALocationProvider _nmea; + uint32_t _gpsPeriodSeconds = 0; + unsigned long _nextAcquisition = 0; + unsigned long _acquisitionStarted = 0; + bool _acquiringPeriodically = false; + +public: + RakLocationProvider(RakGpsDriver& driver, mesh::RTCClock* clock = nullptr) + : _driver(driver), _nmea(driver.nmeaDriver(), clock) {} + + void syncTime() override { + LocationProvider::syncTime(); + if (!_driver.usesRak12500()) _nmea.syncTime(); + } + + long getLatitude() override { + return _driver.usesRak12500() ? _driver.getLatitude() : _nmea.getLatitude(); + } + + long getLongitude() override { + return _driver.usesRak12500() ? _driver.getLongitude() : _nmea.getLongitude(); + } + + long getAltitude() override { + return _driver.usesRak12500() ? _driver.getAltitude() : _nmea.getAltitude(); + } + + long satellitesCount() override { + return _driver.usesRak12500() ? _driver.getSatellites() : _nmea.satellitesCount(); + } + + bool isValid() override { + return _driver.usesRak12500() ? _driver.hasFix() : _nmea.isValid(); + } + + long getTimestamp() override { + return _driver.usesRak12500() ? _driver.getTimestamp() : _nmea.getTimestamp(); + } + + void sendSentence(const char* sentence) override { + if (!_driver.usesRak12500()) _nmea.sendSentence(sentence); + } + + bool waitFor(const char* prefix, uint32_t timeout_ms) override { + return _driver.usesRak12500() ? false : _nmea.waitFor(prefix, timeout_ms); + } + + void drain() override { + if (!_driver.usesRak12500()) _nmea.drain(); + } + + void reset() override { + _driver.reset(); + } + + void begin() override { + if (_driver.isDetected() && _driver.usesRak12500()) { + _driver.begin(); + _acquiringPeriodically = _gpsPeriodSeconds > 0; + _acquisitionStarted = millis(); + } else if (_driver.isDetected()) { + _nmea.begin(); + } else { + _driver.begin(); + } + } + + void stop() override { + _acquiringPeriodically = false; + if (_driver.usesRak12500()) { + _driver.stop(); + } else { + _nmea.stop(); + } + } + + bool detect(uint32_t timeout_ms) override { + if (!_driver.detect(timeout_ms)) return false; + + if (_driver.usesRak12500()) { + _acquiringPeriodically = _gpsPeriodSeconds > 0; + _acquisitionStarted = millis(); + } else { + _nmea.setGpsPeriod(_gpsPeriodSeconds); + _nmea.begin(); + } + return true; + } + + bool keepEnabledAfterDetection() const override { +#ifdef FORCE_GPS_ALIVE + return true; +#else + return false; +#endif + } + + void loop() override { + if (_driver.usesRak12500()) { + if (_gpsOn && _gpsPeriodSeconds > 0) { + if (!_acquiringPeriodically && + (long)(millis() - _nextAcquisition) >= 0) { + _driver.begin(); + _acquiringPeriodically = true; + _acquisitionStarted = millis(); + } + if (_acquiringPeriodically && isValid()) { + _driver.stop(); + _acquiringPeriodically = false; + _nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL; + } else if (_acquiringPeriodically && + (uint32_t)(millis() - _acquisitionStarted) >= + GPS_PERIODIC_ACQUISITION_TIMEOUT_MS) { + _driver.stop(); + _acquiringPeriodically = false; + _nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL; + } + } + } else { + _nmea.loop(); + } + } + + bool isEnabled() override { + return _driver.isEnabled(); + } + + void setGpsPeriod(uint32_t seconds) override { + _gpsPeriodSeconds = seconds; + _nextAcquisition = millis(); + if (!_driver.usesRak12500()) _nmea.setGpsPeriod(seconds); + } + + uint32_t getGpsPeriod() const override { + return _gpsPeriodSeconds; + } +}; diff --git a/variants/gat562_30s_mesh_kit/target.cpp b/variants/gat562_30s_mesh_kit/target.cpp index 8f84a7a19..ba81a690d 100644 --- a/variants/gat562_30s_mesh_kit/target.cpp +++ b/variants/gat562_30s_mesh_kit/target.cpp @@ -26,9 +26,10 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS - #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); - EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); + #include + RakGpsDriver gps_driver; + RakLocationProvider location(gps_driver, &rtc_clock); + EnvironmentSensorManager sensors(location); #else EnvironmentSensorManager sensors; #endif diff --git a/variants/lilygo_techo/target.cpp b/variants/lilygo_techo/target.cpp index 12b40d7ee..394d79c5c 100644 --- a/variants/lilygo_techo/target.cpp +++ b/variants/lilygo_techo/target.cpp @@ -13,7 +13,8 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea = MicroNMEALocationProvider(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); @@ -36,5 +37,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - - diff --git a/variants/rak3401/target.cpp b/variants/rak3401/target.cpp index 5309e6b22..265019770 100644 --- a/variants/rak3401/target.cpp +++ b/variants/rak3401/target.cpp @@ -25,9 +25,10 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS - #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); - EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); + #include + RakGpsDriver gps_driver; + RakLocationProvider location(gps_driver, &rtc_clock); + EnvironmentSensorManager sensors(location); #else EnvironmentSensorManager sensors; #endif @@ -41,4 +42,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - diff --git a/variants/rak4631/target.cpp b/variants/rak4631/target.cpp index a41ba7207..06ccd23db 100644 --- a/variants/rak4631/target.cpp +++ b/variants/rak4631/target.cpp @@ -25,9 +25,10 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS - #include - MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); - EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); + #include + RakGpsDriver gps_driver; + RakLocationProvider location(gps_driver, &rtc_clock); + EnvironmentSensorManager sensors(location); #else EnvironmentSensorManager sensors; #endif diff --git a/variants/t1000-e/platformio.ini b/variants/t1000-e/platformio.ini index 8456dc915..ab8b0de0b 100644 --- a/variants/t1000-e/platformio.ini +++ b/variants/t1000-e/platformio.ini @@ -106,6 +106,7 @@ build_flags = ${t1000-e.build_flags} ; -D BLE_DEBUG_LOGGING=1 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 +; -D GPS_NMEA_DEBUG -D OFFLINE_QUEUE_SIZE=256 -D DISPLAY_CLASS=NullDisplayDriver -D PIN_BUZZER=25 diff --git a/variants/t1000-e/target.cpp b/variants/t1000-e/target.cpp index 70a64359f..0d7710b3a 100644 --- a/variants/t1000-e/target.cpp +++ b/variants/t1000-e/target.cpp @@ -1,8 +1,8 @@ #include #include "t1000e_sensors.h" #include "target.h" +#include #include -#include T1000eBoard board; @@ -11,8 +11,9 @@ RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BU WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock rtc_clock; -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); -T1000SensorManager sensors = T1000SensorManager(nmea); +AirohaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); +T1000SensorManager sensors(nmea, gps_driver); #ifdef DISPLAY_CLASS NullDisplayDriver display; @@ -82,28 +83,17 @@ mesh::LocalIdentity radio_new_identity() { void T1000SensorManager::start_gps() { gps_active = true; - digitalWrite(GPS_EN, HIGH); - delay(10); - digitalWrite(GPS_RTC_INT, HIGH); - delay(5); - digitalWrite(GPS_RTC_INT, LOW); + _nmea->begin(); } void T1000SensorManager::stop_gps() { gps_active = false; - digitalWrite(GPS_VRTC_EN, HIGH); // keep GPS RTC alive for faster fix on wake - digitalWrite(GPS_RTC_INT, LOW); // make sure this is LOW so we can pulse it to wake - airohaEnterSleep(_nmea); // send command to put the GPS into RTC backup sleep - digitalWrite(GPS_EN, LOW); + _nmea->stop(); } bool T1000SensorManager::begin() { - // init GPS - Serial1.begin(115200); - digitalWrite(GPS_RESET, HIGH); - delay(10); - digitalWrite(GPS_RESET, LOW); + _gps_driver->initialize(); return true; } diff --git a/variants/t1000-e/target.h b/variants/t1000-e/target.h index db003cc5f..4a1a2bb73 100644 --- a/variants/t1000-e/target.h +++ b/variants/t1000-e/target.h @@ -12,15 +12,19 @@ #include "NullDisplayDriver.h" #endif +class AirohaGpsDriver; + class T1000SensorManager: public SensorManager { bool gps_active = false; LocationProvider * _nmea; + AirohaGpsDriver* _gps_driver; void start_gps(); void sleep_gps(); void stop_gps(); public: - T1000SensorManager(LocationProvider &nmea): _nmea(&nmea) { } + T1000SensorManager(LocationProvider &nmea, AirohaGpsDriver& gps_driver) + : _nmea(&nmea), _gps_driver(&gps_driver) { } bool begin() override; bool querySensors(uint8_t requester_permissions, CayenneLPP& telemetry) override; void loop() override; diff --git a/variants/thinknode_m1/target.cpp b/variants/thinknode_m1/target.cpp index c430cee00..78f5a88e6 100644 --- a/variants/thinknode_m1/target.cpp +++ b/variants/thinknode_m1/target.cpp @@ -2,6 +2,7 @@ #include "target.h" #include #include +#include ThinkNodeM1Board board; @@ -11,7 +12,8 @@ WRAPPER_CLASS radio_driver(radio, board); VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea = MicroNMEALocationProvider(gps_driver, &rtc_clock); ThinkNodeM1SensorManager sensors = ThinkNodeM1SensorManager(nmea); #ifdef DISPLAY_CLASS @@ -31,34 +33,15 @@ mesh::LocalIdentity radio_new_identity() { } void ThinkNodeM1SensorManager::start_gps() { - if (!gps_active) { - gps_active = true; - _location->begin(); - } + _location->setGpsOn(true); } void ThinkNodeM1SensorManager::stop_gps() { - if (gps_active) { - gps_active = false; - _location->stop(); - } + _location->setGpsOn(false); } bool ThinkNodeM1SensorManager::begin() { - Serial1.begin(9600); - - // Initialize GPS switch pin - pinMode(PIN_GPS_SWITCH, INPUT); - last_gps_switch_state = digitalRead(PIN_GPS_SWITCH); - - // Initialize GPS power pin - pinMode(GPS_EN, OUTPUT); - - // Check initial switch state to determine if GPS should be active - if (last_gps_switch_state == HIGH) { // Switch is HIGH when ON - start_gps(); - } - + start_gps(); return true; } @@ -71,36 +54,11 @@ bool ThinkNodeM1SensorManager::querySensors(uint8_t requester_permissions, Cayen void ThinkNodeM1SensorManager::loop() { static long next_gps_update = 0; - static long last_switch_check = 0; - - // Check GPS switch state every second - if (millis() - last_switch_check > 1000) { - bool current_switch_state = digitalRead(PIN_GPS_SWITCH); - - // Detect switch state change - if (current_switch_state != last_gps_switch_state) { - last_gps_switch_state = current_switch_state; - - if (current_switch_state == HIGH) { // Switch is ON - MESH_DEBUG_PRINTLN("GPS switch ON"); - start_gps(); - } else { // Switch is OFF - MESH_DEBUG_PRINTLN("GPS switch OFF"); - stop_gps(); - } - } - - last_switch_check = millis(); - } - - if (!gps_active) { - return; // GPS is not active, skip further processing - } _location->loop(); if (millis() > next_gps_update) { - if (_location->isValid()) { + if (_location->isEnabled() && _location->isValid()) { node_lat = ((double)_location->getLatitude())/1000000.; node_lon = ((double)_location->getLongitude())/1000000.; node_altitude = ((double)_location->getAltitude()) / 1000.0; @@ -120,7 +78,7 @@ const char* ThinkNodeM1SensorManager::getSettingName(int i) const { const char* ThinkNodeM1SensorManager::getSettingValue(int i) const { if (i == 0) { - return gps_active ? "1" : "0"; + return _location->isGpsOn() ? "1" : "0"; } return NULL; } @@ -136,4 +94,3 @@ bool ThinkNodeM1SensorManager::setSettingValue(const char* name, const char* val } return false; // not supported } - diff --git a/variants/thinknode_m1/target.h b/variants/thinknode_m1/target.h index d2d6aed1d..9c8a6e80f 100644 --- a/variants/thinknode_m1/target.h +++ b/variants/thinknode_m1/target.h @@ -14,8 +14,6 @@ #endif class ThinkNodeM1SensorManager : public SensorManager { - bool gps_active = false; - bool last_gps_switch_state = false; LocationProvider* _location; void start_gps(); @@ -45,4 +43,3 @@ extern ThinkNodeM1SensorManager sensors; bool radio_init(); mesh::LocalIdentity radio_new_identity(); - diff --git a/variants/thinknode_m1/variant.h b/variants/thinknode_m1/variant.h index aecf197e6..3e3f03a74 100644 --- a/variants/thinknode_m1/variant.h +++ b/variants/thinknode_m1/variant.h @@ -146,3 +146,5 @@ extern const int SCK; #define PIN_GPS_PPS (36) #define PIN_GPS_STANDBY (34) #define PIN_GPS_SWITCH (33) +#define GPS_SWITCH_IS_HARDWARE (0) +#define GPS_SWITCH_TURNS_GPS_ON (1) diff --git a/variants/thinknode_m5/target.cpp b/variants/thinknode_m5/target.cpp index ec524df74..0ed9a0d0c 100644 --- a/variants/thinknode_m5/target.cpp +++ b/variants/thinknode_m5/target.cpp @@ -17,7 +17,8 @@ ESP32RTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #ifdef ENV_INCLUDE_GPS -MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock); +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider nmea = MicroNMEALocationProvider(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else EnvironmentSensorManager sensors = EnvironmentSensorManager(); @@ -46,5 +47,3 @@ mesh::LocalIdentity radio_new_identity() { RadioNoiseListener rng(radio); return mesh::LocalIdentity(&rng); // create new random identity } - - diff --git a/variants/thinknode_m5/variant.h b/variants/thinknode_m5/variant.h index 9b82416b0..fefb45d1d 100644 --- a/variants/thinknode_m5/variant.h +++ b/variants/thinknode_m5/variant.h @@ -25,4 +25,5 @@ #define PIN_GPS_RESET (13) #define PIN_GPS_RX (20) #define PIN_GPS_TX (19) -#define PIN_GPS_SWITCH (10) \ No newline at end of file +#define PIN_GPS_SWITCH (10) +#define GPS_SWITCH_IS_HARDWARE (1) \ No newline at end of file