From 4cb67d9054909f2652522359a1b97d1d7e9c0ed5 Mon Sep 17 00:00:00 2001 From: Kevin Le Date: Fri, 14 Aug 2026 22:34:50 +0700 Subject: [PATCH] GPS PowerSaving, outpath, sensor, reboot.interval, board_build.ldscript --- examples/simple_repeater/MyMesh.cpp | 160 ++++++++++++++- examples/simple_repeater/MyMesh.h | 10 +- examples/simple_repeater/UITask.cpp | 13 +- examples/simple_repeater/UITask.h | 4 +- examples/simple_repeater/main.cpp | 29 ++- src/helpers/ClientACL.h | 3 +- src/helpers/CommonCLI.cpp | 110 +++++++++-- src/helpers/CommonCLI.h | 2 + src/helpers/SensorManager.h | 3 +- .../sensors/EnvironmentSensorManager.cpp | 183 +++++++++++++----- .../sensors/EnvironmentSensorManager.h | 1 + src/helpers/sensors/LocationProvider.h | 24 +++ .../sensors/MicroNMEALocationProvider.h | 13 +- variants/heltec_mesh_solar/target.cpp | 74 ++++++- variants/heltec_mesh_solar/target.h | 1 + variants/heltec_tracker/target.cpp | 73 ++++++- variants/heltec_tracker/target.h | 1 + variants/rak3401/platformio.ini | 7 +- variants/rak3401/variant.h | 4 +- variants/rak4631/platformio.ini | 10 +- variants/rak4631/variant.h | 3 + variants/t1000-e/target.cpp | 84 +++++++- variants/t1000-e/target.h | 1 + 23 files changed, 694 insertions(+), 119 deletions(-) diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index 7d0179f3a..475e1dbfc 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -689,7 +689,8 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, mesh::Packet *reply = createDatagram(PAYLOAD_TYPE_RESPONSE, client->id, secret, reply_data, reply_len); if (reply) { - if (client->out_path_len != OUT_PATH_UNKNOWN) { // we have an out_path, so send DIRECT + // Outpath PR + if (mesh::Packet::isValidPathLen(client->out_path_len)) { // we have an out_path, so send DIRECT sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY); } else { sendFloodReply(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize()); @@ -722,10 +723,12 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, mesh::Packet *ack = createAck(ack_hash); if (ack) { - if (client->out_path_len == OUT_PATH_UNKNOWN) { - sendFloodReply(ack, TXT_ACK_DELAY, packet->getPathHashSize()); - } else { + // Outpath PR + if (mesh::Packet::isValidPathLen(client->out_path_len)) { sendDirect(ack, client->out_path, client->out_path_len, TXT_ACK_DELAY); + } else { + // Outpath PR + sendFloodReply(ack, TXT_ACK_DELAY, packet->getPathHashSize()); } } } @@ -736,7 +739,8 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, if (is_retry) { *reply = 0; } else { - handleCommand(sender_timestamp, command, reply); + // Outpath PR + handleCommand(sender_timestamp, client, command, reply); } int text_len = strlen(reply); if (text_len > 0) { @@ -750,10 +754,12 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret, temp, 5 + text_len); if (reply) { - if (client->out_path_len == OUT_PATH_UNKNOWN) { - sendFloodReply(reply, CLI_REPLY_DELAY_MILLIS, packet->getPathHashSize()); - } else { + // Outpath PR + if (mesh::Packet::isValidPathLen(client->out_path_len)) { sendDirect(reply, client->out_path, client->out_path_len, CLI_REPLY_DELAY_MILLIS); + } else { + // Outpath PR + sendFloodReply(reply, CLI_REPLY_DELAY_MILLIS, packet->getPathHashSize()); } } } @@ -772,8 +778,11 @@ bool MyMesh::onPeerPathRecv(mesh::Packet *packet, int sender_idx, const uint8_t MESH_DEBUG_PRINTLN("PATH to client, path_len=%d", (uint32_t)path_len); auto client = acl.getClientByIdx(i); + // Outpath PR // store a copy of path, for sendDirect() - client->out_path_len = mesh::Packet::copyPath(client->out_path, path, path_len); + if (client->out_path_len != OUT_PATH_FORCE_FLOOD) { + client->out_path_len = mesh::Packet::copyPath(client->out_path, path, path_len); + } client->last_activity = getRTCClock()->getCurrentTime(); } else { MESH_DEBUG_PRINTLN("onPeerPathRecv: invalid peer idx: %d", i); @@ -1193,7 +1202,110 @@ void MyMesh::clearStats() { ((SimpleMeshTables *)getTables())->resetStats(); } -void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply) { +// Outpath PR +static char* trimSpaces(char* s) { + while (*s == ' ') s++; + char* end = s + strlen(s); + while (end > s && end[-1] == ' ') end--; + *end = 0; + return s; +} + +static bool parsePathCommand(char* raw, uint8_t* out_path, uint8_t& out_path_len, const char*& err) { + if (raw == NULL || out_path == NULL) { + err = "Err - bad params"; + return false; + } + + char* spec = trimSpaces(raw); + if (*spec == 0) { + err = "Err - missing path"; + return false; + } + if (strcmp(spec, "clear") == 0 || strcmp(spec, "-") == 0 || strcmp(spec, "none") == 0) { + out_path_len = OUT_PATH_UNKNOWN; + return true; + } + if (strcmp(spec, "flood") == 0) { + out_path_len = OUT_PATH_FORCE_FLOOD; + return true; + } + if (strcmp(spec, "direct") == 0) { + out_path_len = 0; + return true; + } + + uint8_t hash_size = 0; + uint8_t hop_count = 0; + char* token = spec; + while (token && *token) { + char* comma = strchr(token, ','); + if (comma) *comma = 0; + token = trimSpaces(token); + + int hex_len = strlen(token); + if (!(hex_len == 2 || hex_len == 4 || hex_len == 6)) { + err = "Err - bad params"; + return false; + } + + uint8_t hop_hash_size = (uint8_t)(hex_len / 2); + if (hash_size == 0) { + hash_size = hop_hash_size; + } else if (hash_size != hop_hash_size) { + err = "Err - bad params"; + return false; + } + + if (hop_count >= 63 || (hop_count + 1) * hash_size > MAX_PATH_SIZE) { + err = "Err - bad params"; + return false; + } + if (!mesh::Utils::fromHex(&out_path[hop_count * hash_size], hash_size, token)) { + err = "Err - bad hex"; + return false; + } + + hop_count++; + token = comma ? comma + 1 : NULL; + } + + if (hash_size == 0 || hop_count == 0) { + err = "Err - missing path"; + return false; + } + out_path_len = ((hash_size - 1) << 6) | (hop_count & 63); + return true; +} + +static void formatPathReply(const uint8_t* path, uint8_t path_len, char* out, size_t out_len) { + if (path_len == OUT_PATH_FORCE_FLOOD) { + snprintf(out, out_len, "> flood"); + return; + } + if (path_len == OUT_PATH_UNKNOWN) { + snprintf(out, out_len, "> unknown"); + return; + } + if (!mesh::Packet::isValidPathLen(path_len)) { + snprintf(out, out_len, "> invalid"); + return; + } + if ((path_len & 63) == 0) { + snprintf(out, out_len, "> direct"); + return; + } + + uint8_t hash_size = (path_len >> 6) + 1; + uint8_t hop_count = path_len & 63; + uint8_t byte_len = hop_count * hash_size; + char hex[(MAX_PATH_SIZE * 2) + 1]; + mesh::Utils::toHex(hex, path, byte_len); + snprintf(out, out_len, "> hs=%u hops=%u hex=%s", (uint32_t)hash_size, (uint32_t)hop_count, hex); +} + +// Outpath PR +void MyMesh::handleCommand(uint32_t sender_timestamp, ClientInfo* sender, char *command, char *reply) { if (region_load_active) { if (StrHelper::isBlank(command)) { // empty/blank line, signal to terminate 'load' operation region_map = temp_map; // copy over the temp instance as new current map @@ -1270,6 +1382,34 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply Serial.printf("\n"); } reply[0] = 0; + } else if (strcmp(command, "get outpath") == 0 + || strcmp(command, "set outpath") == 0 + || strncmp(command, "set outpath ", 12) == 0) { + bool is_get = strncmp(command, "get ", 4) == 0; + if (sender == NULL) { + strcpy(reply, "Err - command needs remote client context"); + } else if (is_get) { + formatPathReply(sender->out_path, sender->out_path_len, reply, 160); + } else { + char* spec = command + 11; // length of "set outpath" + if (*spec == ' ') spec++; + + uint8_t path[MAX_PATH_SIZE]; + uint8_t path_len = OUT_PATH_UNKNOWN; + const char* err = NULL; + if (!parsePathCommand(spec, path, path_len, err)) { + strcpy(reply, err ? err : "Err - invalid path"); + } else { + if (path_len == OUT_PATH_UNKNOWN || path_len == OUT_PATH_FORCE_FLOOD) { + memset(sender->out_path, 0, sizeof(sender->out_path)); + sender->out_path_len = path_len; + } else { + sender->out_path_len = mesh::Packet::copyPath(sender->out_path, path, path_len); + } + dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); + formatPathReply(sender->out_path, sender->out_path_len, reply, 160); + } + } } else if (memcmp(command, "discover.neighbors", 18) == 0) { const char* sub = command + 18; while (*sub == ' ') sub++; diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index 04bd4fb92..f1cff542b 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -163,6 +163,13 @@ protected: #if ENV_INCLUDE_GPS == 1 void applyGpsPrefs() { + // If powersaving on, apply powersaving to sensors + if (_prefs.powersaving_enabled) { + sensors.powersaving_enabled = true; + } else { + sensors.powersaving_enabled = false; + } + sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0"); } #endif @@ -227,7 +234,8 @@ public: void saveIdentity(const mesh::LocalIdentity& new_id) override; void clearStats() override; - void handleCommand(uint32_t sender_timestamp, char* command, char* reply); + // Outpath PR + void handleCommand(uint32_t sender_timestamp, ClientInfo* sender, char* command, char* reply); void loop(); #if defined(WITH_BRIDGE) diff --git a/examples/simple_repeater/UITask.cpp b/examples/simple_repeater/UITask.cpp index e7225557d..89c833fa7 100644 --- a/examples/simple_repeater/UITask.cpp +++ b/examples/simple_repeater/UITask.cpp @@ -29,7 +29,8 @@ static const uint8_t meshcore_logo [] PROGMEM = { 0xe3, 0xe3, 0x8f, 0xff, 0x1f, 0xfc, 0x3c, 0x0e, 0x1f, 0xf8, 0xff, 0xf8, 0x70, 0x3c, 0x7f, 0xf8, }; -void UITask::begin(NodePrefs* node_prefs, const char* build_date, const char* firmware_version) { +// Added board for battery display +void UITask::begin(NodePrefs* node_prefs, const char* build_date, const char* firmware_version, mesh::MainBoard* board) { _prevBtnState = HIGH; _auto_off = millis() + AUTO_OFF_MILLIS; _started_at = millis(); @@ -106,6 +107,16 @@ void UITask::renderCurrScreen() { _display->setCursor(0, 30); sprintf(tmp, "BW: %03.2f CR: %d", _node_prefs->bw, _node_prefs->cr); _display->print(tmp); + + // Battery + _display->setCursor(0, 40); + sprintf(tmp, "BAT: %.2fV", _board->getBattMilliVolts() / 1000.0); + _display->print(tmp); + + // PowerSaving + _display->setCursor(0, 50); + sprintf(tmp, "PowerSaving: %s", _node_prefs->powersaving_enabled? "ON" : "off"); + _display->print(tmp); } } diff --git a/examples/simple_repeater/UITask.h b/examples/simple_repeater/UITask.h index d8e3ce1d2..93845fb63 100644 --- a/examples/simple_repeater/UITask.h +++ b/examples/simple_repeater/UITask.h @@ -16,7 +16,9 @@ class UITask { void renderCurrScreen(); public: UITask(mesh::MainBoard& board, DisplayDriver& display) : _board(&board), _display(&display) { _next_read = _next_refresh = 0; } - void begin(NodePrefs* node_prefs, const char* build_date, const char* firmware_version); + + // Added board for battery display + void begin(NodePrefs* node_prefs, const char* build_date, const char* firmware_version, mesh::MainBoard* board); void loop(); }; \ No newline at end of file diff --git a/examples/simple_repeater/main.cpp b/examples/simple_repeater/main.cpp index a714db68e..3a9c480a0 100644 --- a/examples/simple_repeater/main.cpp +++ b/examples/simple_repeater/main.cpp @@ -102,12 +102,25 @@ void setup() { ethernet_command[0] = 0; #endif +#if ENV_INCLUDE_GPS == 1 + // Apply PowerSaving profile for GPS + if (sensors.getLocationProvider() != NULL) { + // Let CLI "gps on" call setSettingValue to enable the PowerSaving mode + // sensors.powersaving_enabled = true; + // sensors.getLocationProvider()->enablePowerSaving(true); + + // GPS on and off duration in seconds + sensors.getLocationProvider()->setPowerSavingProfile(600, 86400); // Max 10 minutes, 1 day + } +#endif + sensors.begin(); the_mesh.begin(fs); #ifdef DISPLAY_CLASS - ui_task.begin(the_mesh.getNodePrefs(), FIRMWARE_BUILD_DATE, FIRMWARE_VERSION); + // Added board for battery display + ui_task.begin(the_mesh.getNodePrefs(), FIRMWARE_BUILD_DATE, FIRMWARE_VERSION, &board); #endif #ifdef ETHERNET_ENABLED @@ -145,10 +158,12 @@ void loop() { reply[0] = 0; #ifdef ETHERNET_ENABLED if (!ethernet_handle_command(command, reply)) { - the_mesh.handleCommand(0, command, reply); + // Outpath PR + the_mesh.handleCommand(0, NULL, command, reply); } #else - the_mesh.handleCommand(0, command, reply); // NOTE: there is no sender_timestamp via serial! + // Outpath PR + the_mesh.handleCommand(0, NULL, command, reply); // NOTE: there is no sender_timestamp via serial! #endif if (reply[0]) { Serial.print(" -> "); Serial.println(reply); @@ -163,7 +178,8 @@ void loop() { char reply[160]; reply[0] = 0; if (!ethernet_handle_command(ethernet_command, reply)) { - the_mesh.handleCommand(0, ethernet_command, reply); + // Outpath PR + the_mesh.handleCommand(0, NULL, ethernet_command, reply); } ethernet_send_reply(reply); ethernet_command[0] = 0; @@ -204,4 +220,9 @@ void loop() { } #endif } + + if (the_mesh.getNodePrefs()->reboot_interval > 0 && + the_mesh.millisHasNowPassed(the_mesh.getNodePrefs()->reboot_interval * 3600000)) { + board.reboot(); + } } diff --git a/src/helpers/ClientACL.h b/src/helpers/ClientACL.h index b758f7068..e0b8c5428 100644 --- a/src/helpers/ClientACL.h +++ b/src/helpers/ClientACL.h @@ -10,7 +10,8 @@ #define PERM_ACL_READ_WRITE 2 #define PERM_ACL_ADMIN 3 -#define OUT_PATH_UNKNOWN 0xFF +#define OUT_PATH_FORCE_FLOOD 0xFE +#define OUT_PATH_UNKNOWN 0xFF struct ClientInfo { mesh::Identity id; diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index b318bb58e..66130a7ea 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -4,6 +4,8 @@ #include "AdvertDataHelpers.h" #include "TxtDataHelpers.h" #include +#define STR_HELPER(x) #x +#define STR(x) STR_HELPER(x) #ifndef BRIDGE_MAX_BAUD #define BRIDGE_MAX_BAUD 115200 @@ -90,7 +92,8 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) { // Legacy file.read((uint8_t *)&_prefs->bridge_channel, sizeof(_prefs->bridge_channel)); // 135 file.read((uint8_t *)&_prefs->bridge_secret, sizeof(_prefs->bridge_secret)); // 136 file.read((uint8_t *)&_prefs->powersaving_enabled, sizeof(_prefs->powersaving_enabled)); // 152 - file.read(pad, 3); // 153 + file.read((uint8_t *)&_prefs->reboot_interval, sizeof(_prefs->reboot_interval)); // 153 + file.read(pad, 2); // 154 file.read((uint8_t *)&_prefs->gps_enabled, sizeof(_prefs->gps_enabled)); // 156 file.read((uint8_t *)&_prefs->gps_interval, sizeof(_prefs->gps_interval)); // 157 file.read((uint8_t *)&_prefs->advert_loc_policy, sizeof (_prefs->advert_loc_policy)); // 161 @@ -126,6 +129,7 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) { // Legacy _prefs->bridge_channel = constrain(_prefs->bridge_channel, 0, 14); _prefs->powersaving_enabled = constrain(_prefs->powersaving_enabled, 0, 1); + _prefs->reboot_interval = constrain(_prefs->reboot_interval, 0, 255); _prefs->gps_enabled = constrain(_prefs->gps_enabled, 0, 1); _prefs->advert_loc_policy = constrain(_prefs->advert_loc_policy, 0, 2); @@ -324,7 +328,12 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re if (_sensors->setSettingValue("gps", "1")) { _prefs->gps_enabled = 1; savePrefs(); - strcpy(reply, "ok"); + + if (_prefs->powersaving_enabled) { // Power Saving + strcpy(reply, "on (powersaving)"); + } else { // Normal mode + strcpy(reply, "ok"); + } } else { strcpy(reply, "gps toggle not found"); } @@ -340,7 +349,7 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re LocationProvider * l = _sensors->getLocationProvider(); if (l != NULL) { l->syncTime(); - strcpy(reply, "ok"); + strcpy(reply, "scheduled"); } else { strcpy(reply, "gps provider not found"); } @@ -386,13 +395,40 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re bool fix = l->isValid(); // has fix ? int sats = l->satellitesCount(); bool active = !strcmp(_sensors->getSettingByKey("gps"), "1"); - if (enabled) { - sprintf(reply, "on, %s, %s, %d sats", - active?"active":"deactivated", - fix?"fix":"no fix", - sats); - } else { - strcpy(reply, "off"); + + if (_prefs->powersaving_enabled && l->isPowerSavingEnabled()) { // GPS Power Saving + if (enabled) { + unsigned long mins = (l->getNextSleep() - millis()) / 60000UL; + sprintf(reply, "on (powersaving, sleep in %luh %lum), %s, %s, %d sats", + mins / 60UL, + mins % 60UL, + active ? "active" : "deactivated", + fix ? "fix" : "no fix", + sats); + } else { + unsigned long mins = (l->getNextWake() - millis()) / 60000UL; + sprintf(reply, "off (powersaving, wake in %luh %lum)", + mins / 60UL, + mins % 60UL); + } + + // "last sync" from GPS + DateTime dt = DateTime(l->getLastValidTimeSync()); + if (dt.unixtime() == 0) { + sprintf(reply + strlen(reply), ", last sync: none"); + } else { + sprintf(reply + strlen(reply), ", last sync: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), + dt.day(), dt.month(), dt.year()); + } + } else { // Normal mode + if (enabled) { + sprintf(reply, "on, %s, %s, %d sats", + active?"active":"deactivated", + fix?"fix":"no fix", + sats); + } else { + strcpy(reply, "off"); + } } } else { strcpy(reply, "Can't find GPS"); @@ -401,10 +437,12 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re } else if (memcmp(command, "powersaving on", 14) == 0) { #if defined(NRF52_PLATFORM) _prefs->powersaving_enabled = 1; + _sensors->powersaving_enabled = 1; savePrefs(); strcpy(reply, "on - Immediate effect"); #elif defined(ESP32) && !defined(WITH_BRIDGE) _prefs->powersaving_enabled = 1; + _sensors->powersaving_enabled = 1; savePrefs(); strcpy(reply, "on - After 2 minutes"); #elif defined(WITH_BRIDGE) @@ -414,6 +452,7 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re #endif } else if (memcmp(command, "powersaving off", 15) == 0) { _prefs->powersaving_enabled = 0; + _sensors->powersaving_enabled = 0; savePrefs(); strcpy(reply, "off"); } else if (memcmp(command, "powersaving", 11) == 0) { @@ -422,6 +461,36 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re } else { strcpy(reply, "off"); } + } else if (memcmp(command, "sensor", 6) == 0) { + // I2C +#if defined(ENV_PIN_SDA) && defined(ENV_PIN_SCL) + sprintf(reply, "I2C Wire1: SDA=%s,SCL=%s\r\n", STR(ENV_PIN_SDA), STR(ENV_PIN_SCL)); +#elif defined(PIN_BOARD_SDA) && defined(PIN_BOARD_SCL) + sprintf(reply, "I2C Wire: SDA=%s, SCL=%s\r\n", STR(PIN_BOARD_SDA), STR(PIN_BOARD_SCL)); +#elif defined(PIN_WIRE_SDA) && defined(PIN_WIRE_SCL) + sprintf(reply, "I2C Wire: SDA=%s, SCL=%s\r\n", STR(PIN_WIRE_SDA), STR(PIN_WIRE_SCL)); +#else + sprintf(reply, "I2C GPIOs not defined\r\n"); +#endif + + // GPS +#if defined(PIN_GPS_RX) && defined(PIN_GPS_TX) + sprintf(reply + strlen(reply), "GPS Serial: RX=%s, TX=%s", STR(PIN_GPS_RX), STR(PIN_GPS_TX)); +#ifdef ENV_INCLUDE_GPS> 0 + sprintf(reply + strlen(reply), ". Configured"); +#else + sprintf(reply + strlen(reply), ". Not configured"); +#endif +#else + sprintf(reply + strlen(reply), "GPS Serial not defined"); +#endif + } else if (memcmp(command, "powerlog", 8) == 0) { + sprintf(reply, "Last reset reason: %s", _board->getResetReasonString(_board->getResetReason())); +#if defined(NRF52_PLATFORM) + sprintf(reply + strlen(reply), "\r\nLast shutdown reason: %s", + _board->getShutdownReasonString(_board->getShutdownReason())); + sprintf(reply + strlen(reply), "\r\nLast boot voltage: %u mV", _board->getBootVoltage()); +#endif } else if (memcmp(command, "log start", 9) == 0) { _callbacks->setLoggingOn(true); strcpy(reply, " logging on"); @@ -798,6 +867,19 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep } } #endif + } else if (memcmp(config, "reboot.interval ", 16) == 0) { + int hours = _atoi(&config[16]); + if (hours == 0) { + _prefs->reboot_interval = 0; + savePrefs(); + strcpy(reply, "reboot.interval disabled"); + } else if (hours < 1 || 255 < hours) { + strcpy(reply, "Error: interval range is 1-255 hours"); + } else { + _prefs->reboot_interval = hours; + savePrefs(); + sprintf(reply, "OK - reboot.interval set to %d", _prefs->reboot_interval); + } } else { strcpy(reply, "unknown config: "); StrHelper::strncpy(&reply[16], config, 160-17); @@ -816,7 +898,7 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep } else if (memcmp(config, "int.thresh", 10) == 0) { sprintf(reply, "> %d", (uint32_t) _prefs->interference_threshold); } else if (memcmp(config, "cad", 3) == 0) { - sprintf(reply, "> %s", _prefs->cad_enabled ? "on" : "off"); + sprintf(reply, "> %s. # channel busy: %u", _prefs->cad_enabled ? "on" : "off", _board->n_cad_busy); } else if (memcmp(config, "agc.reset.interval", 18) == 0) { sprintf(reply, "> %d", ((uint32_t) _prefs->agc_reset_interval) * 4); } else if (memcmp(config, "multi.acks", 10) == 0) { @@ -981,6 +1063,12 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep if (tmp == reply) { sprintf(reply, "No extra SF configured"); } + } else if (memcmp(config, "reboot.interval", 15) == 0) { + if (_prefs->reboot_interval == 0) { + strcpy(reply, "disabled"); + } else { + sprintf(reply, "> %d", (uint8_t)_prefs->reboot_interval); + } } else { sprintf(reply, "??: %s", config); } diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 237c758e9..8b590b819 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -56,6 +56,7 @@ public: char bridge_secret[16]; // for XOR encryption of bridge packets (ESP-NOW only) // Power setting uint8_t powersaving_enabled = 0; // boolean + uint8_t reboot_interval = 0; // hours, 0-255 (default 0=disable) // Gps settings uint8_t gps_enabled = 0; uint32_t gps_interval = 0; // in seconds @@ -134,6 +135,7 @@ private: void structure() override { def("adc_mult", _parent->adc_multiplier); def("pwr_sav_en", _parent->powersaving_enabled); + def("pwr_reboot_int", _parent->reboot_interval); } public: PowerPrefs(NodePrefs* parent) : _parent(parent) { } diff --git a/src/helpers/SensorManager.h b/src/helpers/SensorManager.h index 89a174c22..2031bbc52 100644 --- a/src/helpers/SensorManager.h +++ b/src/helpers/SensorManager.h @@ -13,8 +13,9 @@ class SensorManager { public: double node_lat, node_lon; // modify these, if you want to affect Advert location double node_altitude; // altitude in meters + bool powersaving_enabled; // powersaving mode - SensorManager() { node_lat = 0; node_lon = 0; node_altitude = 0; } + SensorManager() { node_lat = 0; node_lon = 0; node_altitude = 0; powersaving_enabled = false; } virtual bool begin() { return false; } virtual bool querySensors(uint8_t requester_permissions, CayenneLPP& telemetry) { return false; } virtual void loop() { } diff --git a/src/helpers/sensors/EnvironmentSensorManager.cpp b/src/helpers/sensors/EnvironmentSensorManager.cpp index e2f0d33e7..d490b2a9f 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.cpp +++ b/src/helpers/sensors/EnvironmentSensorManager.cpp @@ -15,6 +15,7 @@ #if ENV_INCLUDE_BME680_BSEC #ifndef TELEM_BME680_ADDRESS #define TELEM_BME680_ADDRESS 0x76 +#define TELEM_BME680_ADDRESS_2 0x77 #endif #define TELEM_BME680_SEALEVELPRESSURE_HPA (1013.25) #include @@ -40,6 +41,7 @@ static uint32_t bsec_last_save_ms = 0; #ifdef ENV_INCLUDE_BME680 #ifndef TELEM_BME680_ADDRESS #define TELEM_BME680_ADDRESS 0x76 +#define TELEM_BME680_ADDRESS_2 0x77 #endif #define TELEM_BME680_SEALEVELPRESSURE_HPA (1013.25) #include @@ -63,6 +65,7 @@ static Adafruit_AHTX0 AHTX0; #if ENV_INCLUDE_BME280 #ifndef TELEM_BME280_ADDRESS #define TELEM_BME280_ADDRESS 0x76 // BME280 environmental sensor I2C address +#define TELEM_BME280_ADDRESS_2 0x77 #endif #define TELEM_BME280_SEALEVELPRESSURE_HPA (1013.25) // Atmospheric pressure at sea level #include @@ -72,6 +75,7 @@ static Adafruit_BME280 BME280; #if ENV_INCLUDE_BMP280 #ifndef TELEM_BMP280_ADDRESS #define TELEM_BMP280_ADDRESS 0x76 // BMP280 environmental sensor I2C address +#define TELEM_BMP280_ADDRESS_2 0x77 #endif #define TELEM_BMP280_SEALEVELPRESSURE_HPA (1013.25) // Atmospheric pressure at sea level #include @@ -165,7 +169,9 @@ static RAK12035_SoilMoisture RAK12035; #endif #ifdef RAK_WISBLOCK_GPS -static uint32_t gpsResetPin = 0; +// -1 = no enable pin; out-of-range values are no-ops in pinMode/digitalWrite, +// while 0 would be a real GPIO (P0.00 = LFXO crystal on nRF52) +static uint32_t gpsResetPin = -1; static bool i2cGPSFlag = false; static bool serialGPSFlag = false; #ifndef TELEM_RAK12500_ADDRESS @@ -181,6 +187,7 @@ class RAK12500LocationProvider : public LocationProvider { int _sats = 0; long _epoch = 0; bool _fix = false; + int _pin_en = -1; public: long getLatitude() override { return _lat; } long getLongitude() override { return _lng; } @@ -193,18 +200,25 @@ public: 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; + static long next_gps_update = 0; + if ((int32_t)(millis() - next_gps_update) >= 0) { + 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); + + next_gps_update = millis() + 1000; } - _epoch = ublox_GNSS.getUnixEpoch(2); } bool isEnabled() override { return true; } + void setPinEn(int pin_en) override { _pin_en = pin_en; } + int getPinEn() override { return _pin_en; } }; static RAK12500LocationProvider RAK12500_provider; @@ -557,15 +571,27 @@ static const SensorDef SENSOR_TABLE[] = { #endif #ifdef ENV_INCLUDE_BME680 { TELEM_BME680_ADDRESS, "BME680", init_bme680, query_bme680 }, + #ifdef TELEM_BME680_ADDRESS_2 + { TELEM_BME680_ADDRESS_2, "BME680", init_bme680, query_bme680 }, + #endif #endif #if ENV_INCLUDE_BME680_BSEC { TELEM_BME680_ADDRESS, "BME680+BSEC", init_bme680_bsec, query_bme680_bsec }, + #ifdef TELEM_BME680_ADDRESS_2 + { TELEM_BME680_ADDRESS_2, "BME680+BSEC", init_bme680_bsec, query_bme680_bsec }, + #endif #endif #if ENV_INCLUDE_BME280 { TELEM_BME280_ADDRESS, "BME280", init_bme280, query_bme280 }, + #ifdef TELEM_BME280_ADDRESS_2 + { TELEM_BME280_ADDRESS_2, "BME280", init_bme280, query_bme280 }, + #endif #endif #if ENV_INCLUDE_BMP280 { TELEM_BMP280_ADDRESS, "BMP280", init_bmp280, query_bmp280 }, + #ifdef TELEM_BMP280_ADDRESS_2 + { TELEM_BMP280_ADDRESS_2, "BMP280", init_bmp280, query_bmp280 }, + #endif #endif #if ENV_INCLUDE_SHTC3 { 0x70, "SHTC3", init_shtc3, query_shtc3 }, @@ -714,8 +740,16 @@ bool EnvironmentSensorManager::setSettingValue(const char* name, const char* val #if ENV_INCLUDE_GPS if (gps_detected && strcmp(name, "gps") == 0) { if (strcmp(value, "0") == 0) { + if (powersaving_enabled) { + _location->enablePowerSaving(false); + } + stop_gps(); } else { + if (powersaving_enabled) { + _location->enablePowerSaving(true); + } + start_gps(); } return true; @@ -774,24 +808,19 @@ void EnvironmentSensorManager::initBasicGPS() { // gps code for rak might be moved to MicroNMEALoactionProvider // or make a new location provider ... #ifdef RAK_WISBLOCK_GPS -void EnvironmentSensorManager::rakGPSInit(){ - +void EnvironmentSensorManager::rakGPSInit() { Serial1.setPins(PIN_GPS_TX, PIN_GPS_RX); - #ifdef GPS_BAUD_RATE +#ifdef GPS_BAUD_RATE Serial1.begin(GPS_BAUD_RATE); - #else +#else Serial1.begin(9600); - #endif +#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{ + // search for the correct IO standby pin depending on socket used + if (gpsIsAwake(WB_IO2)) { + _location->setPinEn(WB_IO2); // WB_IO2 is the power switch for all sensor and IO slots + } else { MESH_DEBUG_PRINTLN("No GPS found"); gps_active = false; gps_detected = false; @@ -799,13 +828,13 @@ void EnvironmentSensorManager::rakGPSInit(){ 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 +#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 +#endif } -bool EnvironmentSensorManager::gpsIsAwake(uint8_t ioPin){ +bool EnvironmentSensorManager::gpsIsAwake(uint8_t ioPin) { #if defined(ETHERNET_ENABLED) && defined(RAK_BOARD) if (ioPin == WB_IO2) { @@ -813,17 +842,16 @@ bool EnvironmentSensorManager::gpsIsAwake(uint8_t ioPin){ return false; } #endif - //set initial waking state - pinMode(ioPin,OUTPUT); - digitalWrite(ioPin,LOW); + pinMode(ioPin, OUTPUT); + digitalWrite(ioPin, LOW); delay(500); - digitalWrite(ioPin,HIGH); + digitalWrite(ioPin, HIGH); 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); + // 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); @@ -841,13 +869,9 @@ bool EnvironmentSensorManager::gpsIsAwake(uint8_t ioPin){ _location = &RAK12500_provider; return true; - } else if (Serial1.available()) { + } else if (Serial1.available()) { // RAK12501 (L76K) on UART MESH_DEBUG_PRINTLN("Serial GPS init correctly and is turned on"); -#ifdef PIN_GPS_EN - if(PIN_GPS_EN){ - gpsResetPin = PIN_GPS_EN; - } -#endif + gpsResetPin = ioPin; serialGPSFlag = true; gps_active = true; gps_detected = true; @@ -862,11 +886,23 @@ bool EnvironmentSensorManager::gpsIsAwake(uint8_t ioPin){ void EnvironmentSensorManager::start_gps() { gps_active = true; - #ifdef RAK_WISBLOCK_GPS - pinMode(gpsResetPin, OUTPUT); - digitalWrite(gpsResetPin, HIGH); - return; - #endif + + if (powersaving_enabled && _location->isPowerSavingEnabled()) { + gps_wake = true; // gps_active is true + _location->syncTime(); // Clear GPS data and force sync time + _location->setNextSleep(); // Next time to off + } + +#ifdef RAK_WISBLOCK_GPS +#ifdef FORCE_GPS_ALIVE + // There is no UART command to enter power save for L76K + if (i2cGPSFlag) ublox_GNSS.powerSaveMode(false); +#else + pinMode(gpsResetPin, OUTPUT); + digitalWrite(gpsResetPin, HIGH); // WB_IO2 +#endif + return; +#endif _location->begin(); _location->reset(); @@ -877,10 +913,23 @@ void EnvironmentSensorManager::start_gps() { } void EnvironmentSensorManager::stop_gps() { - gps_active = false; + if (powersaving_enabled && _location->isPowerSavingEnabled()) { + gps_wake = false; // gps_active is unchanged (true) even the GPS sleep (e.g: off) + _location->stopTimeSync(); // Stop time sync + _location->setNextWake(); // Next time to on + } else { + gps_active = false; + gps_wake = false; // When GPS is off, wake is false to be sure + } + #ifdef RAK_WISBLOCK_GPS + #ifdef FORCE_GPS_ALIVE + // There is no UART command to enter power save for L76K + if(i2cGPSFlag) ublox_GNSS.powerSaveMode(false); + #else pinMode(gpsResetPin, OUTPUT); - digitalWrite(gpsResetPin, LOW); + digitalWrite(gpsResetPin, LOW); // WB_IO2 + #endif return; #endif @@ -896,13 +945,39 @@ void EnvironmentSensorManager::stop_gps() { void EnvironmentSensorManager::loop() { #if ENV_INCLUDE_GPS - static unsigned long next_gps_update = 0; - if (gps_active) { + static long next_gps_update = 0; + + // PowerSaving + if (powersaving_enabled) { + if (gps_detected && _location->isPowerSavingEnabled()) { + if (gps_wake && ((int32_t)(millis() - _location->getNextSleep()) >= 0 || + !_location->waitingTimeSync())) { // Time to off or GPS set + if ((int32_t)(millis() - _location->getNextSleep()) >= 0) { + POWERSAVING_DEBUG_PRINTLN("GPS wake timeout. Enter sleep"); + } + else if (!_location->waitingTimeSync()) { + POWERSAVING_DEBUG_PRINTLN("GPS set. Enter sleep early"); + } + + stop_gps(); + } else if (!gps_wake && ((int32_t)(millis() - _location->getNextWake()) >= 0)) { // Time to on + POWERSAVING_DEBUG_PRINTLN("GPS sleep timeout. Wakeup."); + + start_gps(); + } else if (!gps_wake && _location->waitingTimeSync()) { // On for "gps sync" + POWERSAVING_DEBUG_PRINTLN("CLI gps sync. Wakeup"); + + start_gps(); + } + } + } + + if ((!powersaving_enabled && gps_active) || (powersaving_enabled && gps_wake)) { _location->loop(); } - if ((long)(millis() - next_gps_update) > 0) { - if(gps_active){ + if ((int32_t)(millis() - next_gps_update) >= 0) { + if((!powersaving_enabled && gps_active) || (powersaving_enabled && gps_wake)){ #ifdef RAK_WISBLOCK_GPS if ((i2cGPSFlag || serialGPSFlag) && _location->isValid()) { node_lat = ((double)_location->getLatitude())/1000000.; @@ -920,8 +995,12 @@ void EnvironmentSensorManager::loop() { MESH_DEBUG_PRINTLN("lat %f lon %f alt %f", node_lat, node_lon, node_altitude); } #endif + + // In powersaving mode, GPS is on and off. Only update data when GPS is on + if(powersaving_enabled) next_gps_update = millis() + (gps_update_interval_sec * 1000); } - next_gps_update = millis() + (gps_update_interval_sec * 1000); + + if(!powersaving_enabled) next_gps_update = millis() + (gps_update_interval_sec * 1000); } #endif #if ENV_INCLUDE_BME680_BSEC diff --git a/src/helpers/sensors/EnvironmentSensorManager.h b/src/helpers/sensors/EnvironmentSensorManager.h index 29147c896..40c44e908 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.h +++ b/src/helpers/sensors/EnvironmentSensorManager.h @@ -21,6 +21,7 @@ protected: bool gps_detected = false; bool gps_active = false; + bool gps_wake = false; // In PowerSaving, gps_active can have gps_wake true or false uint32_t gps_update_interval_sec = 1; #if ENV_INCLUDE_GPS diff --git a/src/helpers/sensors/LocationProvider.h b/src/helpers/sensors/LocationProvider.h index 81d08652e..c9204373e 100644 --- a/src/helpers/sensors/LocationProvider.h +++ b/src/helpers/sensors/LocationProvider.h @@ -7,9 +7,31 @@ class LocationProvider { protected: bool _time_sync_needed = true; + bool powersaving_enabled = false; + unsigned long _wake_duration_secs = 86400; // Full day + unsigned long _sleep_duration_secs = 0; // No off + unsigned long _next_wake = 0; + unsigned long _next_sleep = 0; + unsigned long _last_valid_time_sync = 0; + public: virtual void syncTime() { _time_sync_needed = true; } virtual bool waitingTimeSync() { return _time_sync_needed; } + virtual void stopTimeSync() { _time_sync_needed = false; } + + virtual void setPowerSavingProfile(unsigned long wake_duration_secs, unsigned long sleep_duration_secs) { + _wake_duration_secs = wake_duration_secs; + _sleep_duration_secs = sleep_duration_secs; + } + + virtual void enablePowerSaving(bool enabled) { powersaving_enabled = enabled; _next_wake = 0; _next_sleep = 0; } + virtual bool isPowerSavingEnabled() { return powersaving_enabled; } + virtual void setNextWake() { _next_wake = millis() + _sleep_duration_secs * 1000UL; } + virtual unsigned long getNextWake() { return _next_wake; } + virtual void setNextSleep() { _next_sleep = millis() + _wake_duration_secs * 1000UL; } + virtual unsigned long getNextSleep() { return _next_sleep; } + virtual unsigned long getLastValidTimeSync() { return _last_valid_time_sync; } + virtual long getLatitude() = 0; virtual long getLongitude() = 0; virtual long getAltitude() = 0; @@ -22,4 +44,6 @@ public: virtual void stop() = 0; virtual void loop() = 0; virtual bool isEnabled() = 0; + virtual void setPinEn(int pin_en) = 0; + virtual int getPinEn() = 0; }; diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index b66cb1145..b7d8d14ee 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -113,6 +113,14 @@ public : } } + void setPinEn(int pin_en) override { + _pin_en = pin_en; + } + + int getPinEn() override { + return _pin_en; + } + void syncTime() override { nmea.clear(); LocationProvider::syncTime(); } long getLatitude() override { return nmea.getLatitude(); } long getLongitude() override { return nmea.getLongitude(); } @@ -122,7 +130,7 @@ public : return alt; } long satellitesCount() override { return nmea.getNumSatellites(); } - bool isValid() override { return nmea.isValid(); } + bool isValid() override { return nmea.isValid() && nmea.getYear() < 2030; } // TODO: Pending better validation long getTimestamp() override { DateTime dt(nmea.getYear(), nmea.getMonth(),nmea.getDay(),nmea.getHour(),nmea.getMinute(),nmea.getSecond()); @@ -156,9 +164,10 @@ public : _clock->setCurrentTime(getTimestamp()); _time_sync_needed = false; _last_time_sync = millis(); + _last_valid_time_sync = _clock->getCurrentTime(); } } - if (isValid()) { + if (isValid() && satellitesCount() >= 5) { time_valid ++; } } diff --git a/variants/heltec_mesh_solar/target.cpp b/variants/heltec_mesh_solar/target.cpp index 94e2684c1..28442334d 100644 --- a/variants/heltec_mesh_solar/target.cpp +++ b/variants/heltec_mesh_solar/target.cpp @@ -32,13 +32,28 @@ mesh::LocalIdentity radio_new_identity() { void SolarSensorManager::start_gps() { if (!gps_active) { gps_active = true; + + if (powersaving_enabled && _location->isPowerSavingEnabled()) { + gps_wake = true; // gps_active is true + _location->syncTime(); // Clear GPS data and force sync time + _location->setNextSleep(); // Next time to off + } + _location->begin(); } } void SolarSensorManager::stop_gps() { if (gps_active) { - gps_active = false; + if (powersaving_enabled && _location->isPowerSavingEnabled()) { + gps_wake = false; // gps_active is unchanged (true) even the GPS sleep (e.g: off) + _location->stopTimeSync(); // Stop time sync + _location->setNextWake(); // Next time to on + } else { + gps_active = false; + gps_wake = false; // When GPS is off, wake is false to be sure + } + _location->stop(); } } @@ -68,16 +83,49 @@ bool SolarSensorManager::querySensors(uint8_t requester_permissions, CayenneLPP& void SolarSensorManager::loop() { static long next_gps_update = 0; - _location->loop(); + // PowerSaving + if (powersaving_enabled) { + if (gps_detected && _location->isPowerSavingEnabled()) { + if (gps_wake && ((int32_t)(millis() - _location->getNextSleep()) >= 0 || + !_location->waitingTimeSync())) { // Time to off or GPS set + if ((int32_t)(millis() - _location->getNextSleep()) >= 0) { + POWERSAVING_DEBUG_PRINTLN("GPS wake timeout. Enter sleep"); + } else if (!_location->waitingTimeSync()) { + POWERSAVING_DEBUG_PRINTLN("GPS set. Enter sleep early"); + } - if (millis() > next_gps_update) { - if (_location->isValid()) { - node_lat = ((double)_location->getLatitude())/1000000.; - node_lon = ((double)_location->getLongitude())/1000000.; - node_altitude = ((double)_location->getAltitude()) / 1000.0; - MESH_DEBUG_PRINTLN("lat %f lon %f", node_lat, node_lon); + stop_gps(); + } else if (!gps_wake && ((int32_t)(millis() - _location->getNextWake()) >= 0)) { // Time to on + POWERSAVING_DEBUG_PRINTLN("GPS sleep timeout. Wakeup."); + + start_gps(); + } else if (!gps_wake && _location->waitingTimeSync()) { // On for "gps sync" + POWERSAVING_DEBUG_PRINTLN("CLI gps sync. Wakeup"); + + start_gps(); + } } - next_gps_update = millis() + 1000; + } + + if ((!powersaving_enabled && gps_active) || (powersaving_enabled && gps_wake)) { + _location->loop(); + } + + if ((int32_t)(millis() - next_gps_update) >= 0) { + if ((!powersaving_enabled && gps_active) || (powersaving_enabled && gps_wake)) { + 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); + } + + // In powersaving mode, GPS is on and off. Only update data when GPS is on + if (powersaving_enabled) next_gps_update = millis() + 1000; + } + + if (!powersaving_enabled) next_gps_update = millis() + 1000; } } @@ -99,8 +147,16 @@ const char* SolarSensorManager::getSettingValue(int i) const { bool SolarSensorManager::setSettingValue(const char* name, const char* value) { if (gps_detected && strcmp(name, "gps") == 0) { if (strcmp(value, "0") == 0) { + if (powersaving_enabled) { + _location->enablePowerSaving(false); + } + stop_gps(); } else { + if (powersaving_enabled) { + _location->enablePowerSaving(true); + } + start_gps(); } return true; diff --git a/variants/heltec_mesh_solar/target.h b/variants/heltec_mesh_solar/target.h index 8e13a9601..f80d22473 100644 --- a/variants/heltec_mesh_solar/target.h +++ b/variants/heltec_mesh_solar/target.h @@ -16,6 +16,7 @@ class SolarSensorManager : public SensorManager { bool gps_active = false; bool gps_detected = false; + bool gps_wake = false; // In PowerSaving, gps_active can have gps_wake true or false LocationProvider* _location; void start_gps(); diff --git a/variants/heltec_tracker/target.cpp b/variants/heltec_tracker/target.cpp index f32c41ff4..9bc5ab7cd 100644 --- a/variants/heltec_tracker/target.cpp +++ b/variants/heltec_tracker/target.cpp @@ -46,13 +46,28 @@ void HWTSensorManager::start_gps() { if (!gps_active) { _location->begin(); // Claims periph_power via RefCountedDigitalPin gps_active = true; + + if (powersaving_enabled && _location->isPowerSavingEnabled()) { + gps_wake = true; // gps_active is true + _location->syncTime(); // Clear GPS data and force sync time + _location->setNextSleep(); // Next time to off + } + Serial1.println("$CFGSYS,h35155*68"); // Configure GPS for all constellations } } void HWTSensorManager::stop_gps() { if (gps_active) { - gps_active = false; + if (powersaving_enabled && _location->isPowerSavingEnabled()) { + gps_wake = false; // gps_active is unchanged (true) even the GPS sleep (e.g: off) + _location->stopTimeSync(); // Stop time sync + _location->setNextWake(); // Next time to on + } else { + gps_active = false; + gps_wake = false; // When GPS is off, wake is false to be sure + } + _location->stop(); // Releases periph_power via RefCountedDigitalPin } } @@ -73,16 +88,48 @@ bool HWTSensorManager::querySensors(uint8_t requester_permissions, CayenneLPP& t void HWTSensorManager::loop() { static long next_gps_update = 0; - _location->loop(); + // PowerSaving + if (powersaving_enabled) { + if (_location->isPowerSavingEnabled()) { + if (gps_wake && ((int32_t)(millis() - _location->getNextSleep()) >= 0 || + !_location->waitingTimeSync())) { // Time to off or GPS set + if ((int32_t)(millis() - _location->getNextSleep()) >= 0) { + POWERSAVING_DEBUG_PRINTLN("GPS wake timeout. Enter sleep"); + } else if (!_location->waitingTimeSync()) { + POWERSAVING_DEBUG_PRINTLN("GPS set. Enter sleep early"); + } - if (millis() > next_gps_update) { - if (gps_active && _location->isValid()) { - node_lat = ((double)_location->getLatitude())/1000000.; - node_lon = ((double)_location->getLongitude())/1000000.; - node_altitude = ((double)_location->getAltitude()) / 1000.0; - MESH_DEBUG_PRINTLN("lat %f lon %f", node_lat, node_lon); + stop_gps(); + } else if (!gps_wake && ((int32_t)(millis() - _location->getNextWake()) >= 0)) { // Time to on + POWERSAVING_DEBUG_PRINTLN("GPS sleep timeout. Wakeup."); + + start_gps(); + } else if (!gps_wake && _location->waitingTimeSync()) { // On for "gps sync" + POWERSAVING_DEBUG_PRINTLN("CLI gps sync. Wakeup"); + + start_gps(); + } } - next_gps_update = millis() + 1000; + } + + if ((!powersaving_enabled && gps_active) || (powersaving_enabled && gps_wake)) { + _location->loop(); + } + + if ((int32_t)(millis() - next_gps_update) >= 0) { + if ((!powersaving_enabled && gps_active) || (powersaving_enabled && gps_wake)) { + if (_location->isValid()) { + node_lat = ((double)_location->getLatitude()) / 1000000.; + node_lon = ((double)_location->getLongitude()) / 1000000.; + node_altitude = ((double)_location->getAltitude()) / 1000.0; + MESH_DEBUG_PRINTLN("lat %f lon %f alt %f", node_lat, node_lon, node_altitude); + } + + // In powersaving mode, GPS is on and off. Only update data when GPS is on + if (powersaving_enabled) next_gps_update = millis() + 1000; + } + + if (!powersaving_enabled) next_gps_update = millis() + 1000; } } @@ -100,8 +147,16 @@ const char* HWTSensorManager::getSettingValue(int i) const { bool HWTSensorManager::setSettingValue(const char* name, const char* value) { if (strcmp(name, "gps") == 0) { if (strcmp(value, "0") == 0) { + if (powersaving_enabled) { + _location->enablePowerSaving(false); + } + stop_gps(); } else { + if (powersaving_enabled) { + _location->enablePowerSaving(true); + } + start_gps(); } return true; diff --git a/variants/heltec_tracker/target.h b/variants/heltec_tracker/target.h index 2931eda81..0fe3d0251 100644 --- a/variants/heltec_tracker/target.h +++ b/variants/heltec_tracker/target.h @@ -15,6 +15,7 @@ class HWTSensorManager : public SensorManager { bool gps_active = false; + bool gps_wake = false; // In PowerSaving, gps_active can have gps_wake true or false LocationProvider * _location; void start_gps(); diff --git a/variants/rak3401/platformio.ini b/variants/rak3401/platformio.ini index 48e719226..a16c3e46f 100644 --- a/variants/rak3401/platformio.ini +++ b/variants/rak3401/platformio.ini @@ -2,17 +2,22 @@ extends = nrf52_base board = rak3401 board_check = true +board_build.ldscript = boards/nrf52840_s140_v6.ld build_flags = ${nrf52_base.build_flags} ${sensor_base.build_flags} -I variants/rak3401 -D RAK_3401 - -D NRF52_POWER_MANAGEMENT + -D RAK_BOARD +; -D NRF52_POWER_MANAGEMENT -D RADIO_CLASS=CustomSX1262 -D WRAPPER_CLASS=CustomSX1262Wrapper -D LORA_TX_POWER=22 -D SX126X_CURRENT_LIMIT=140 -D SX126X_RX_BOOSTED_GAIN=1 -D SX126X_REGISTER_PATCH=1 ; Patch register 0x8B5 for improved RX with SKY66122 FEM + -D FORCE_GPS_ALIVE ; on RAK3401, gpsResetPin ends up = WB_IO2 (kills 3V3_S rail) or + ; pin 4 (= SX126X_RESET, holds radio in reset). stop_gps() must not run. + -D PIN_GPS_EN=-1 ; -1 = no dedicated GPS enable pin (power is the shared 3V3_S rail), same as rak4631 build_src_filter = ${nrf52_base.build_src_filter} +<../variants/rak3401> + diff --git a/variants/rak3401/variant.h b/variants/rak3401/variant.h index 988278860..a2e32ae29 100644 --- a/variants/rak3401/variant.h +++ b/variants/rak3401/variant.h @@ -188,8 +188,8 @@ static const uint8_t AREF = PIN_AREF; // Power is on the controllable 3V3_S rail #define PIN_GPS_PPS (17) // Pulse per second input from the GPS -#define PIN_GPS_RX PIN_SERIAL1_RX -#define PIN_GPS_TX PIN_SERIAL1_TX +#define PIN_GPS_RX PIN_SERIAL1_TX +#define PIN_GPS_TX PIN_SERIAL1_RX #define PIN_GPS_1PPS PIN_GPS_PPS #define GPS_BAUD_RATE 9600 diff --git a/variants/rak4631/platformio.ini b/variants/rak4631/platformio.ini index 0dfbf7977..0ac5ec8b1 100644 --- a/variants/rak4631/platformio.ini +++ b/variants/rak4631/platformio.ini @@ -2,6 +2,7 @@ extends = nrf52_base board = rak4631 board_check = true +board_build.ldscript = boards/nrf52840_s140_v6.ld extra_scripts = ${nrf52_base.extra_scripts} post:variants/rak4631/fix_bsec_lib.py build_flags = ${nrf52_base.build_flags} @@ -9,11 +10,10 @@ build_flags = ${nrf52_base.build_flags} -I variants/rak4631 -D RAK_4631 -D RAK_BOARD - -D NRF52_POWER_MANAGEMENT +; -D NRF52_POWER_MANAGEMENT -D PIN_BOARD_SCL=14 -D PIN_BOARD_SDA=13 - -D PIN_GPS_TX=PIN_SERIAL1_RX - -D PIN_GPS_RX=PIN_SERIAL1_TX +; -D FORCE_GPS_ALIVE // Do not off WB_IO2 if we want to keep other sensor / IO slots on -D PIN_GPS_EN=-1 -D PIN_OLED_RESET=-1 -D USE_SX1262 @@ -49,6 +49,7 @@ build_flags = -D MAX_NEIGHBOURS=50 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 +; -D POWERSAVING_DEBUG=1 build_src_filter = ${rak4631.build_src_filter} + +<../examples/simple_repeater> @@ -220,10 +221,11 @@ build_flags = -D MAX_CONTACTS=350 -D MAX_GROUP_CHANNELS=40 -D BLE_PIN_CODE=123456 - -D BLE_DEBUG_LOGGING=1 +; -D BLE_DEBUG_LOGGING=1 -D OFFLINE_QUEUE_SIZE=256 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 +; -D POWERSAVING_DEBUG=1 build_src_filter = ${rak4631.build_src_filter} + +<../examples/companion_radio/*.cpp> diff --git a/variants/rak4631/variant.h b/variants/rak4631/variant.h index 38cc88685..42ca3b0c5 100644 --- a/variants/rak4631/variant.h +++ b/variants/rak4631/variant.h @@ -182,6 +182,9 @@ extern "C" #define EXTERNAL_FLASH_DEVICES IS25LP080D #define EXTERNAL_FLASH_USE_QSPI +#define PIN_GPS_RX PIN_SERIAL1_TX +#define PIN_GPS_TX PIN_SERIAL1_RX + #define PIN_GPS_1PPS 17 //GPS PPS pin #define GPS_BAUD_RATE 9600 #define GPS_ADDRESS 0x42 //i2c address for GPS diff --git a/variants/t1000-e/target.cpp b/variants/t1000-e/target.cpp index 425328270..99c9be29a 100644 --- a/variants/t1000-e/target.cpp +++ b/variants/t1000-e/target.cpp @@ -81,6 +81,13 @@ mesh::LocalIdentity radio_new_identity() { void T1000SensorManager::start_gps() { gps_active = true; + + if (powersaving_enabled && _nmea->isPowerSavingEnabled()) { + gps_wake = true; // gps_active is true + _nmea->syncTime(); // Clear GPS data and force sync time + _nmea->setNextSleep(); // Next time to off + } + //_nmea->begin(); // this init sequence should be better // comes from seeed examples and deals with all gps pins @@ -104,7 +111,15 @@ void T1000SensorManager::start_gps() { } void T1000SensorManager::sleep_gps() { - gps_active = false; + if (powersaving_enabled && _nmea->isPowerSavingEnabled()) { + gps_wake = false; // gps_active is unchanged (true) even the GPS sleep (e.g: off) + _nmea->stopTimeSync(); // Stop time sync + _nmea->setNextWake(); // Next time to on + } else { + gps_active = false; + gps_wake = false; // When GPS is off, wake is false to be sure + } + digitalWrite(GPS_VRTC_EN, HIGH); digitalWrite(GPS_EN, LOW); digitalWrite(GPS_RESET, HIGH); @@ -116,7 +131,15 @@ void T1000SensorManager::sleep_gps() { } void T1000SensorManager::stop_gps() { - gps_active = false; + if (powersaving_enabled && _nmea->isPowerSavingEnabled()) { + gps_wake = false; // gps_active is unchanged (true) even the GPS sleep (e.g: off) + _nmea->stopTimeSync(); // Stop time sync + _nmea->setNextWake(); // Next time to on + } else { + gps_active = false; + gps_wake = false; // When GPS is off, wake is false to be sure + } + digitalWrite(GPS_VRTC_EN, LOW); digitalWrite(GPS_EN, LOW); digitalWrite(GPS_RESET, HIGH); @@ -149,16 +172,49 @@ bool T1000SensorManager::querySensors(uint8_t requester_permissions, CayenneLPP& void T1000SensorManager::loop() { static long next_gps_update = 0; - _nmea->loop(); + // PowerSaving + if (powersaving_enabled) { + if (_nmea->isPowerSavingEnabled()) { + if (gps_wake && ((int32_t)(millis() - _nmea->getNextSleep()) >= 0 || + !_nmea->waitingTimeSync())) { // Time to off or GPS set + if ((int32_t)(millis() - _nmea->getNextSleep()) >= 0) { + POWERSAVING_DEBUG_PRINTLN("GPS wake timeout. Enter sleep"); + } else if (!_nmea->waitingTimeSync()) { + POWERSAVING_DEBUG_PRINTLN("GPS set. Enter sleep early"); + } - if (millis() > next_gps_update) { - if (gps_active && _nmea->isValid()) { - node_lat = ((double)_nmea->getLatitude())/1000000.; - node_lon = ((double)_nmea->getLongitude())/1000000.; - node_altitude = ((double)_nmea->getAltitude()) / 1000.0; - //Serial.printf("lat %f lon %f\r\n", _lat, _lon); + stop_gps(); + } else if (!gps_wake && ((int32_t)(millis() - _nmea->getNextWake()) >= 0)) { // Time to on + POWERSAVING_DEBUG_PRINTLN("GPS sleep timeout. Wakeup."); + + start_gps(); + } else if (!gps_wake && _nmea->waitingTimeSync()) { // On for "gps sync" + POWERSAVING_DEBUG_PRINTLN("CLI gps sync. Wakeup"); + + start_gps(); + } } - next_gps_update = millis() + 1000; + } + + if ((!powersaving_enabled && gps_active) || (powersaving_enabled && gps_wake)) { + _nmea->loop(); + } + + if ((int32_t)(millis() - next_gps_update) >= 0) { + if ((!powersaving_enabled && gps_active) || (powersaving_enabled && gps_wake)) { + if (_nmea->isValid()) { + node_lat = ((double)_nmea->getLatitude()) / 1000000.; + node_lon = ((double)_nmea->getLongitude()) / 1000000.; + MESH_DEBUG_PRINTLN("lat %f lon %f", node_lat, node_lon); + node_altitude = ((double)_nmea->getAltitude()) / 1000.0; + MESH_DEBUG_PRINTLN("lat %f lon %f alt %f", node_lat, node_lon, node_altitude); + } + + // In powersaving mode, GPS is on and off. Only update data when GPS is on + if (powersaving_enabled) next_gps_update = millis() + 1000; + } + + if (!powersaving_enabled) next_gps_update = millis() + 1000; } } @@ -176,8 +232,16 @@ const char* T1000SensorManager::getSettingValue(int i) const { bool T1000SensorManager::setSettingValue(const char* name, const char* value) { if (strcmp(name, "gps") == 0) { if (strcmp(value, "0") == 0) { + if (powersaving_enabled) { + _nmea->enablePowerSaving(false); + } + sleep_gps(); // sleep for faster fix ! } else { + if (powersaving_enabled) { + _nmea->enablePowerSaving(true); + } + start_gps(); } return true; diff --git a/variants/t1000-e/target.h b/variants/t1000-e/target.h index db003cc5f..cd91ceec9 100644 --- a/variants/t1000-e/target.h +++ b/variants/t1000-e/target.h @@ -14,6 +14,7 @@ class T1000SensorManager: public SensorManager { bool gps_active = false; + bool gps_wake = false; // In PowerSaving, gps_active can have gps_wake true or false LocationProvider * _nmea; void start_gps();