Fix WisBlock GPS power policy and preserve shared peripherals

This commit is contained in:
mikecarper committed 2026-10-13 09:55:32 -07:00
1 parent af08c02a00
commit a2f51253d8
26 files changed
+1830 -107

No files matched your search

+50 -1
View File
@@ -7,6 +7,9 @@
#include <helpers/BatteryChargeCLI.h>
#include <helpers/MorseCLI.h>
#include <helpers/MorseLoopPolicy.h>
#if defined(RAK_4631)
#include <helpers/PeripheralModePrefs.h>
#endif
#include "CLICommandUtils.h"
#ifdef WITH_RS232_BRIDGE
#include "bridges/RS232PowerSettings.h"
@@ -811,6 +814,9 @@ void CommonCLI::loadPrefs(FILESYSTEM* fs) {
#endif
_prefs->bridge_format = mesh::bridge::ESPNOW_FORMAT_WRAPPED;
_prefs->gps_sync_interval_hours = 0;
#if defined(RAK_4631)
_prefs->peripherals_shared = 0;
#endif
#ifdef WITH_MQTT_BRIDGE
bool node_prefs_needs_migration = false;
@@ -1017,6 +1023,10 @@ void CommonCLI::loadPrefs(FILESYSTEM* fs) {
if (loaded) syncOtaConfigFromPrefs(); // persisted OTA policy/keys -> OtaContext (else keep safe defaults)
#endif
mesh::hilStartupTrace("prefs_apply_begin");
#if defined(RAK_4631)
// Boot-time only. Later CLI saves must not cut a live peripheral/flash rail.
_sensors->configureSharedPeripheralMode(_prefs->peripherals_shared != 0);
#endif
#if MESH_USB_LOGGING_AVAILABLE
mesh::setUsbDebugEnabled(_prefs->usb_debug_enabled != 0);
mesh::setUsbLoggingEnabled(_prefs->usb_logging_enabled != 0);
@@ -1057,6 +1067,10 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
_prefs->gps_sync_interval_hours = 0;
_prefs->ota_channel = 0;
_prefs->rs232_bridge_enabled = 0;
#if defined(RAK_4631)
// Failure to read an existing policy cannot authorize a shared-rail cut.
_prefs->peripherals_shared = 1;
#endif
#ifdef WITH_RS232_BRIDGE
_prefs->rs232_heartbeat = 1;
_prefs->rs232_autosleep = 1;
@@ -1753,6 +1767,10 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
&_prefs->rx_ps_rx_us,
&_prefs->rx_ps_sleep_us); // retune level-based timings to the loaded SF/BW
// Read the footer independently of optional legacy UART tails/profile.
#if defined(RAK_4631)
_prefs->peripherals_shared = mesh::peripherals::readCommonMode(file);
#endif
file.close();
}
}
@@ -1918,6 +1936,11 @@ static bool writeCommonPrefsImage(Writer& writer, NodePrefs* prefs) {
prefs->rs232_idle_seconds);
WRITE_COMMON_PREFS_BYTES(power_tail, sizeof(power_tail));
#endif
#if defined(RAK_4631)
uint8_t peripheral_footer[mesh::peripherals::FooterSize];
mesh::peripherals::encodeFooter(peripheral_footer, prefs->peripherals_shared);
WRITE_COMMON_PREFS_BYTES(peripheral_footer, sizeof(peripheral_footer));
#endif
#undef WRITE_COMMON_PREFS_BYTES
#undef WRITE_COMMON_PREFS
@@ -2110,6 +2133,11 @@ void CommonCLI::savePrefs(FILESYSTEM* fs, PrefsSaveRouting::Scope scope) {
_prefs->rs232_idle_seconds);
file.write(power_tail, sizeof(power_tail));
#endif
#if defined(RAK_4631)
uint8_t peripheral_footer[mesh::peripherals::FooterSize];
mesh::peripherals::encodeFooter(peripheral_footer, _prefs->peripherals_shared);
file.write(peripheral_footer, sizeof(peripheral_footer));
#endif
_common_save_succeeded = file.commit();
if (!_common_save_succeeded) {
@@ -3451,7 +3479,7 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
} else if (memcmp(command, "gps", 3) == 0) {
LocationProvider * l = _sensors->getLocationProvider();
if (l != NULL) {
bool enabled = l->isEnabled(); // is EN pin on ?
bool enabled = _sensors->isGpsPowered(); // physical rail/enable policy
bool fix = l->isValid(); // has fix ?
int sats = l->satellitesCount();
const char* gps_setting = _sensors->getSettingByKey("gps");
@@ -3737,6 +3765,17 @@ bool CommonCLI::handleSdCardGetCmd(const char* config, char* reply) {
void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* reply) {
const char* config = &command[4];
#if defined(RAK_4631)
if (mesh::peripherals::handleCommand(_prefs->peripherals_shared, command,
reply, 160, _sensors->supportsSharedPeripheralMode(),
[this]() { return trySavePrefs(); })) return;
#else
if (strncmp(config, "peripherals.mode", 16) == 0
&& (config[16] == 0 || config[16] == ' ' || config[16] == '\t')) {
strcpy(reply, "Error: unsupported");
return;
}
#endif
if (strncmp(config, "repeat.trace", 12) == 0
&& (config[12] == 0 || config[12] == ' ' || config[12] == '\t')) {
if (strcmp(_callbacks->getRole(), "repeater") != 0) {
@@ -5280,6 +5319,16 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* reply) {
const char* config = &command[4];
#if defined(RAK_4631)
if (mesh::peripherals::handleCommand(_prefs->peripherals_shared, command,
reply, 160, _sensors->supportsSharedPeripheralMode(),
[this]() { return trySavePrefs(); })) return;
#else
if (strcmp(config, "peripherals.mode") == 0) {
strcpy(reply, "Error: unsupported");
return;
}
#endif
if (strncmp(config, "repeat.trace", 12) == 0
&& (config[12] == 0 || config[12] == ' ' || config[12] == '\t')) {
if (strcmp(_callbacks->getRole(), "repeater") != 0) {
+4
View File
@@ -278,6 +278,10 @@ public:
uint8_t flood_retry_group_max_path = 0; // PAYLOAD_TYPE_GRP_DATA retry path gate; 0xFF = use only the general gate
uint8_t rx_watchdog_enabled = mesh::RepeaterRadioTiming::DEFAULT_RX_WATCHDOG_ENABLED;
uint8_t system_watchdog_enabled = 0; // nRF52 main-loop hardware watchdog (boolean; default on)
#if defined(RAK_4631)
// Checked append-only file footer; never shifts existing preference offsets.
uint8_t peripherals_shared = 0; // 0=GPS-only, 1=shared; applied only at boot
#endif
private:
class RadioPrefs : public CommonRadioPrefs {
+103
View File
@@ -0,0 +1,103 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
namespace mesh {
namespace peripherals {
// RAK4631 only: append this checked policy after every previously published
// preference byte. Missing historical policy means GPS-only; an unreadable or
// damaged new policy must retain the shared supply instead of removing power.
static constexpr size_t FooterSize = 8;
static constexpr size_t CommonLegacySize = 877;
static constexpr size_t LegacyRs232TailSize = 10;
inline uint16_t checksum(const uint8_t* bytes, size_t length) {
uint16_t crc = 0xFFFF;
for (size_t i = 0; i < length; ++i) {
crc ^= static_cast<uint16_t>(bytes[i]) << 8;
for (unsigned bit = 0; bit < 8; ++bit)
crc = (crc & 0x8000) ? static_cast<uint16_t>((crc << 1) ^ 0x1021)
: static_cast<uint16_t>(crc << 1);
}
return crc;
}
inline void encodeFooter(uint8_t out[FooterSize], uint8_t shared) {
out[0] = 'P'; out[1] = 'M'; out[2] = 'O'; out[3] = 1;
out[4] = shared == 0 ? 0 : 1;
out[5] = 0;
const uint16_t crc = checksum(out, 6);
out[6] = static_cast<uint8_t>(crc >> 8);
out[7] = static_cast<uint8_t>(crc);
}
inline bool decodeFooter(const uint8_t* in, size_t size, uint8_t& shared) {
if (!in || size != FooterSize || in[0] != 'P' || in[1] != 'M'
|| in[2] != 'O' || in[3] != 1 || in[4] > 1 || in[5] != 0
|| checksum(in, 6) != static_cast<uint16_t>((in[6] << 8) | in[7]))
return false;
shared = in[4];
return true;
}
template <typename File> uint8_t readCommonMode(File& file) {
const size_t size = file.size();
if (size <= CommonLegacySize) return 0;
// A historical RS232-only image has no peripheral policy. This check is
// independent of the current profile: UART -> no-UART upgrades must work.
if (size == CommonLegacySize + LegacyRs232TailSize) {
uint8_t header[4] = {};
if (!file.seek(CommonLegacySize) || file.read(header, sizeof(header)) != sizeof(header))
return 1;
if (header[0] == 'R' && header[1] == 'S' && header[2] == 'P' && header[3] == 1)
return 0;
}
uint8_t footer[FooterSize] = {};
uint8_t shared = 1;
if (size < FooterSize || !file.seek(size - FooterSize)
|| file.read(footer, sizeof(footer)) != sizeof(footer)
|| !decodeFooter(footer, sizeof(footer), shared)) return 1;
return shared;
}
template <typename Save>
bool handleCommand(uint8_t& shared, const char* command, char* reply,
size_t capacity, bool supported, Save save) {
if (!command || !reply || capacity == 0) return false;
const bool query = strcmp(command, "get peripherals.mode") == 0;
static const char prefix[] = "set peripherals.mode";
const bool setter = strncmp(command, prefix, sizeof(prefix) - 1) == 0
&& (command[sizeof(prefix) - 1] == 0 || command[sizeof(prefix) - 1] == ' '
|| command[sizeof(prefix) - 1] == '\t');
if (!query && !setter) return false;
if (!supported) {
snprintf(reply, capacity, "Error: peripheral mode unsupported");
return true;
}
if (query) {
snprintf(reply, capacity, "> %s (saved; applied at boot)", shared ? "shared" : "gps-only");
return true;
}
const char* value = command + sizeof(prefix) - 1;
while (*value == ' ' || *value == '\t') ++value;
if (strcmp(value, "gps-only") != 0 && strcmp(value, "shared") != 0) {
snprintf(reply, capacity, "Error: use set peripherals.mode gps-only|shared");
return true;
}
const uint8_t previous = shared;
shared = strcmp(value, "shared") == 0 ? 1 : 0;
if (!save()) {
shared = previous;
snprintf(reply, capacity, "Error: peripheral mode could not be saved");
} else {
snprintf(reply, capacity, "OK - %s saved; reboot to apply", value);
}
return true;
}
} // namespace peripherals
} // namespace mesh
+7
View File
@@ -162,6 +162,13 @@ public:
return false;
}
virtual LocationProvider* getLocationProvider() { return NULL; }
// WisBlock slot power is a boot-time choice, separate from logical GPS on/off.
virtual bool supportsSharedPeripheralMode() const { return false; }
virtual void configureSharedPeripheralMode(bool shared) { (void)shared; }
virtual bool isGpsPowered() const {
LocationProvider* location = const_cast<SensorManager*>(this)->getLocationProvider();
return location != NULL && location->isEnabled();
}
virtual void setPowerSavingEnabled(bool enabled) { powersaving_enabled = enabled; }
// Runtime bridges may temporarily own the UART used by a GPS receiver. A
// sensor manager that actually detected a GPS on that UART overrides these
+159 -74
View File
@@ -318,6 +318,16 @@ static bool serialGPSFlag = false;
#include <SparkFun_u-blox_GNSS_Arduino_Library.h>
static SFE_UBLOX_GNSS ublox_GNSS;
static bool configureRakUbloxReceiver() {
// Retain the receiver's supported constellation defaults/BBR selection.
// ZOE-M8Q cannot run GPS/Galileo/GLONASS/BeiDou all at once, and blindly
// enabling every constellation ignores CFG-GNSS constraints/errata. Only
// require the transport and cadence we actually consume after a cold wake.
// Do not repeatedly write receiver nonvolatile storage on wake.
return ublox_GNSS.setI2COutput(COM_TYPE_UBX)
&& ublox_GNSS.setMeasurementRate(1000);
}
#ifndef RAK_UART_GPS_PROBE_TIMEOUT_MS
#define RAK_UART_GPS_PROBE_TIMEOUT_MS 1200UL
#endif
@@ -334,8 +344,8 @@ static void setRakGpsControl(uint8_t pin, bool shared_power_rail,
bool enabled) {
pinMode(pin, OUTPUT);
if (shared_power_rail) {
// WB_IO2 controls every 3V3_S peripheral, not just the GPS. It must never
// be dropped as a GPS power-saving operation.
// Discovery cannot drop this shared rail. The manager's frozen ownership
// policy, not a provider's enable pin, handles later GPS-only shutdown.
digitalWrite(pin, HIGH);
return;
}
@@ -343,6 +353,14 @@ static void setRakGpsControl(uint8_t pin, bool shared_power_rail,
digitalWrite(pin, enabled ? active : static_cast<uint8_t>(!active));
}
static void stopRakGpsUart() {
Serial1.end();
// UARTE teardown disconnects PSEL but does not restore GPIO configuration.
// Remove output drive and pulls so serial pads cannot back-power an off GPS.
pinMode(PIN_GPS_TX, INPUT);
pinMode(PIN_GPS_RX, INPUT);
}
static bool serialHasValidGpsSentence(Stream& serial, uint32_t timeout_ms) {
mesh::NmeaSentenceProbe probe;
const uint32_t started = millis();
@@ -956,6 +974,10 @@ static const size_t SENSOR_TABLE_SIZE = (sizeof(SENSOR_TABLE) / sizeof(SENSOR_TA
bool EnvironmentSensorManager::begin() {
_active_sensor_count = 0;
#if defined(RAK_BOARD) && !defined(RAK_WISMESH_TAG)
_wisblock_power.setDiscoveryActive(true);
applyWisBlockRailPower();
#endif
#if ENV_INCLUDE_GPS
#ifdef RAK_WISBLOCK_GPS
@@ -973,7 +995,7 @@ bool EnvironmentSensorManager::begin() {
#ifdef NRF52_PLATFORM
if (!isValidNrfI2cPinPair(ENV_PIN_SDA, ENV_PIN_SCL)) {
MESH_DEBUG_PRINTLN("Second I2C skipped: invalid SDA/SCL pin pair");
return true;
return finishSensorDiscovery();
}
Wire1.setPins(static_cast<uint8_t>(ENV_PIN_SDA),
static_cast<uint8_t>(ENV_PIN_SCL));
@@ -987,13 +1009,13 @@ bool EnvironmentSensorManager::begin() {
// Avoid touching a shared I2C bus when no environmental drivers were built.
if (SENSOR_TABLE_SIZE == 0) {
return true;
return finishSensorDiscovery();
}
if (!ensureI2cBusReleased(TELEM_WIRE)) {
MESH_DEBUG_PRINTLN(
"I2C discovery skipped: bus pins unavailable or SDA/SCL remained low");
return true;
return finishSensorDiscovery();
}
// Probe only unique addresses compiled into this image before invoking any
@@ -1054,7 +1076,7 @@ bool EnvironmentSensorManager::begin() {
}
}
return true;
return finishSensorDiscovery();
}
// ============================================================
@@ -1070,6 +1092,10 @@ bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, Cayen
queryGpsTelemetry(requester_permissions, telemetry);
#endif
#if defined(RAK_BOARD) && !defined(RAK_WISMESH_TAG)
if (!_wisblock_power.railEnabled()) return true;
#endif
if (requester_permissions & TELEM_PERM_ENVIRONMENT) {
for (int i = 0; i < _active_sensor_count; i++) {
_active_sensors[i].query(next_available_channel, _active_sensors[i].sub_channel, telemetry);
@@ -1095,6 +1121,9 @@ uint8_t EnvironmentSensorManager::getVoltageSensorChannels(
uint8_t EnvironmentSensorManager::queryVoltageSensors(
VoltageSensorReading readings[], uint8_t capacity) {
#if defined(RAK_BOARD) && !defined(RAK_WISMESH_TAG)
if (!_wisblock_power.railEnabled()) return 0;
#endif
uint8_t count = 0;
for (int i = 0; i < _active_sensor_count && count < capacity; i++) {
const ActiveSensor& sensor = _active_sensors[i];
@@ -1149,17 +1178,6 @@ bool EnvironmentSensorManager::setSettingValue(const char* name, const char* val
gps_discovery_preference_known = true;
#endif
bool enabled = strcmp(value, "0") != 0;
#if defined(RAK_WISBLOCK_GPS) && defined(FORCE_GPS_ALIVE)
// A UART L76K cannot remove power from the shared 3V3_S rail. "Off" stops
// parsing and releases the MCU UART, but the still-powered receiver keeps
// driving its TX pin. It therefore does not make that pin safe for an
// external UART bridge.
if (serialGPSFlag) {
_location->setGPSPowerSaving(false);
setGpsTelemetryUserEnabled(enabled);
return true;
}
#endif
bool was_active = gps_active;
_location->setGPSPowerSaving(enabled && powersaving_enabled);
setGpsTelemetryUserEnabled(enabled);
@@ -1183,17 +1201,6 @@ void EnvironmentSensorManager::setPowerSavingEnabled(bool enabled) {
return;
}
bool gps_user_enabled = isGpsTelemetryUserEnabled();
#if defined(RAK_WISBLOCK_GPS) && defined(FORCE_GPS_ALIVE)
if (serialGPSFlag) {
_location->setGPSPowerSaving(false);
if (gps_user_enabled) {
if (!gps_active) start_gps();
} else if (gps_active) {
stop_gps();
}
return;
}
#endif
_location->setGPSPowerSaving(enabled && gps_user_enabled);
if (!gps_user_enabled) return;
@@ -1327,6 +1334,67 @@ void EnvironmentSensorManager::initBasicGPS() {
#endif
}
bool EnvironmentSensorManager::supportsSharedPeripheralMode() const {
#if defined(RAK_4631) && !defined(RAK_WISMESH_TAG)
return true;
#else
return false;
#endif
}
#if defined(RAK_BOARD) && !defined(RAK_WISMESH_TAG)
void EnvironmentSensorManager::applyWisBlockRailPower() {
pinMode(WB_IO2, OUTPUT);
digitalWrite(WB_IO2, _wisblock_power.railEnabled() ? HIGH : LOW);
}
uint8_t EnvironmentSensorManager::detectWisBlockStorageHolds() {
uint8_t holds = 0;
#if defined(OTA_RAK_AUTO_STORE)
uint32_t rak_id = 0, w25_id = 0;
const uint8_t selected = mesh::ota::OtaStoreQspiNrf52::autoDetect();
mesh::ota::OtaStoreQspiNrf52::autoProbeIds(rak_id, w25_id);
// Unsupported but responding NOR parts must not lose their supply either.
// All-zero/all-one reads are the probe's absent-chip values.
if (selected != 0 || (rak_id != 0 && rak_id != 0xFFFFFFUL)
|| (w25_id != 0 && w25_id != 0xFFFFFFUL)) {
holds |= mesh::gps::ExternalStorage;
}
#elif defined(OTA_QSPI_SHARED_WISBLOCK_SPI) || defined(OTA_SD_STORE)
holds |= mesh::gps::ExternalStorage;
#endif
return holds;
}
#endif
void EnvironmentSensorManager::configureSharedPeripheralMode(bool shared) {
#if defined(RAK_BOARD) && !defined(RAK_WISMESH_TAG)
// Called once after boot discovery and validated preference loading. Live
// setters only save the next-boot choice; they never revoke active owners.
if (!_wisblock_power.configure(shared ? mesh::gps::WisBlockPeripheralMode::Shared
: mesh::gps::WisBlockPeripheralMode::GpsOnly,
detectWisBlockStorageHolds())) return;
_wisblock_power.setGpsActive(gps_active);
// Companion loads preferences before sensor discovery, whereas repeaters
// load them afterwards. Only finishSensorDiscovery releases that interlock.
applyWisBlockRailPower();
#else
(void)shared;
#endif
}
bool EnvironmentSensorManager::isGpsPowered() const {
#ifdef RAK_WISBLOCK_GPS
#if defined(PIN_GPS_EN) && PIN_GPS_EN >= 0
return digitalRead(PIN_GPS_EN) == rakGpsControlActiveLevel();
#else
return digitalRead(WB_IO2) == HIGH;
#endif
#else
return SensorManager::isGpsPowered();
#endif
}
// gps code for rak might be moved to MicroNMEALoactionProvider
// or make a new location provider ...
#ifdef RAK_WISBLOCK_GPS
@@ -1382,27 +1450,21 @@ void EnvironmentSensorManager::rakGPSInit() {
#endif
if (gpsIsAwake(gps_control_pin, shared_power_rail)) {
_location->setPinEn(gps_control_pin);
// WB_IO2 is not an independently owned GPS pin. A provider must never
// lower it during reset/begin/stop behind the shared-power policy's back.
_location->setPinEn(shared_power_rail ? -1 : gps_control_pin);
if (i2cGPSFlag) stopRakGpsUart();
} else {
MESH_DEBUG_PRINTLN("No GPS found");
gps_active = false;
gps_detected = false;
Serial1.end();
stopRakGpsUart();
return;
}
#ifdef FORCE_GPS_ALIVE
if (i2cGPSFlag) {
// The u-blox receiver can sleep while the shared rail remains available.
stop_gps();
} else if (serialGPSFlag) {
// The UART L76K cannot be isolated from the RAK3401 radio power rail.
setGpsTelemetryUserEnabled(true);
}
#else
// Now that GPS is found and set up, set it to sleep for the initial state.
stop_gps();
#endif
// Keep discovery power available for the remaining slot probes. Loading the
// saved mode and GPS preference later performs the initial stop, without
// ever manufacturing a GPS-on preference from a successful UART probe.
}
bool EnvironmentSensorManager::gpsIsAwake(uint8_t ioPin,
@@ -1467,17 +1529,9 @@ bool EnvironmentSensorManager::gpsIsAwake(uint8_t ioPin,
// After two successful non-INA manufacturer reads, use the u-blox-specific
// probe. No software can make two physical devices at one address safe.
if (probe_i2c_gps
&& ublox_GNSS.begin(Wire, gps_i2c_address) == true) {
&& ublox_GNSS.begin(Wire, gps_i2c_address) == true
&& configureRakUbloxReceiver()) {
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;
@@ -1506,6 +1560,40 @@ void EnvironmentSensorManager::armGpsPowerSavingCycle() {
void EnvironmentSensorManager::start_gps() {
if (gps_active || gps_serial_transport_blocked) return;
#ifdef RAK_WISBLOCK_GPS
const bool was_powered = isGpsPowered();
_wisblock_power.setGpsActive(true);
applyWisBlockRailPower();
#if defined(PIN_GPS_EN) && PIN_GPS_EN >= 0
setRakGpsControl(PIN_GPS_EN, false, true);
#endif
// Supply first, UART second. A cold receiver must settle before its bus or
// serial transport is used, including a wake after full GPS-only shutdown.
if (!was_powered) delay(500);
if (i2cGPSFlag) {
if (!was_powered) {
if (!ensureI2cBusReleased(&Wire)
|| !ublox_GNSS.begin(Wire, TELEM_RAK12500_ADDRESS)
|| !configureRakUbloxReceiver()) {
// Do not spin on a failed cold wake on every mesh loop. Keep saved
// intent, fail this receiver closed, and allow rediscovery on reboot.
gps_detected = false;
_wisblock_power.setGpsActive(false);
applyWisBlockRailPower();
#if defined(PIN_GPS_EN) && PIN_GPS_EN >= 0
setRakGpsControl(PIN_GPS_EN, false, false);
#endif
_location->stopTimeSync();
MESH_DEBUG_PRINTLN("RAK12500 cold wake failed; GPS rediscovery needs reboot");
return;
}
} else {
// Shared mode retains the historical u-blox internal PSM. This is not
// a promise of full rail shutdown, nor does it silence a UART receiver.
ublox_GNSS.powerSaveMode(false);
}
}
#endif
if (gps_serial_transport) {
Serial1.setPins(PIN_GPS_TX, PIN_GPS_RX);
#ifdef GPS_BAUD_RATE
@@ -1516,13 +1604,7 @@ void EnvironmentSensorManager::start_gps() {
}
gps_active = true;
#ifdef RAK_WISBLOCK_GPS
#ifdef FORCE_GPS_ALIVE
// The UART L76K has no power-save command. Keep the shared rail enabled;
// an I2C u-blox receiver can also be explicitly returned to full power.
if (i2cGPSFlag) ublox_GNSS.powerSaveMode(false);
#else
setRakGpsControl(gpsResetPin, false, true);
#endif
_location->clearPositionFix();
#else
_location->begin();
_location->reset();
@@ -1546,18 +1628,17 @@ void EnvironmentSensorManager::stop_gps() {
}
#ifdef RAK_WISBLOCK_GPS
#ifdef FORCE_GPS_ALIVE
// Keep the shared rail alive for the RAK3401 radio FEM. The I2C u-blox can
// still enter its internal power-save mode. Ending Serial1 stops the MCU
// parser, but a UART L76K remains powered and continues driving its TX pin.
if (i2cGPSFlag) {
ublox_GNSS.powerSaveMode(true);
} else if (serialGPSFlag) {
Serial1.end();
}
// End the MCU UART before removing receiver power, never the reverse.
if (serialGPSFlag) stopRakGpsUart();
_wisblock_power.setGpsActive(false);
#if defined(PIN_GPS_EN) && PIN_GPS_EN >= 0
setRakGpsControl(PIN_GPS_EN, false, false);
#else
setRakGpsControl(gpsResetPin, false, false);
if (i2cGPSFlag && _wisblock_power.railEnabled()) {
ublox_GNSS.powerSaveMode(true);
}
#endif
applyWisBlockRailPower();
#else
_location->stop();
#endif
@@ -1603,11 +1684,10 @@ bool EnvironmentSensorManager::gpsSerialTransportMayConflict(
bool EnvironmentSensorManager::gpsSerialTransportCanYield(uint8_t uart) const {
#if ENV_INCLUDE_GPS
if (!gpsUsesSerialUart(uart)) return false;
#if defined(RAK_WISBLOCK_GPS) && defined(FORCE_GPS_ALIVE)
// RAK12501 exposes no independently controlled standby/power pin. WB_IO2 is
// the shared 3V3_S rail and must remain high, so its L76K keeps transmitting
// NMEA after Serial1.end(). Two TX drivers on UART1 would electrically
// contend; require UART2 or physical removal/isolation of this GPS instead.
#if defined(RAK_WISBLOCK_GPS) && !(defined(PIN_GPS_EN) && PIN_GPS_EN >= 0)
// WB_IO2 is not independent isolation even in GPS-only mode: a bridge or
// future GPS request can repower the same rail. Reserve UART1 to avoid two
// TX drivers; use UART2 or a physically independent GPS enable instead.
return false;
#elif defined(RAK_WISBLOCK_GPS)
// This profile is allowed to remove power with its validated GPS control.
@@ -1637,7 +1717,9 @@ bool EnvironmentSensorManager::setGpsSerialTransportBlocked(uint8_t uart,
if (gps_discovery_pending) _location->stop();
#endif
if (gps_active) stop_gps();
#ifndef RAK_WISBLOCK_GPS
Serial1.end();
#endif
} else {
gps_serial_transport_blocked = false;
#if (defined(ESP32_PLATFORM) || defined(NRF52_PLATFORM)) && !defined(RAK_WISBLOCK_GPS)
@@ -1722,6 +1804,9 @@ void EnvironmentSensorManager::loop() {
}
#endif
#if ENV_INCLUDE_BME680_BSEC
#if defined(RAK_BOARD) && !defined(RAK_WISMESH_TAG)
if (!_wisblock_power.railEnabled()) return;
#endif
if (bsec_active && bsec_iaq.run()) {
uint8_t prev_accuracy = bsec_accuracy;
bsec_temperature = bsec_iaq.temperature;
@@ -3,6 +3,9 @@
#include <Mesh.h>
#include <helpers/SensorManager.h>
#include <helpers/sensors/LocationProvider.h>
#if defined(RAK_BOARD) && !defined(RAK_WISMESH_TAG)
#include "WisBlockSharedPowerPolicy.h"
#endif
class EnvironmentSensorManager : public SensorManager {
protected:
@@ -24,6 +27,28 @@ protected:
bool gps_active = false;
bool gps_serial_transport = false;
bool gps_serial_transport_blocked = false;
#if defined(RAK_BOARD) && !defined(RAK_WISMESH_TAG)
mesh::gps::WisBlockSharedPowerPolicy _wisblock_power;
bool _wisblock_discovery_completed = false;
void applyWisBlockRailPower();
uint8_t detectWisBlockStorageHolds();
#endif
bool finishSensorDiscovery() {
#if defined(RAK_BOARD) && !defined(RAK_WISMESH_TAG)
#if ENV_INCLUDE_GPS
// A repeated probe must not override the loaded manual preference or an
// established telemetry demand. Initial boot waits for preference load.
if (_wisblock_discovery_completed && _wisblock_power.isConfigured() && gps_active
&& !isGpsTelemetryUserEnabled()
&& !gpsTelemetryReceiverRequired(millis())) stop_gps();
#endif
_wisblock_power.setGpsActive(gps_active);
_wisblock_discovery_completed = true;
_wisblock_power.setDiscoveryActive(false);
applyWisBlockRailPower();
#endif
return true;
}
#if ENV_INCLUDE_GPS
#if (defined(ESP32_PLATFORM) || defined(NRF52_PLATFORM)) \
@@ -75,6 +100,9 @@ public:
const char* getSettingValue(int i) const override;
bool setSettingValue(const char* name, const char* value) override;
void setPowerSavingEnabled(bool enabled) override;
bool supportsSharedPeripheralMode() const override;
void configureSharedPeripheralMode(bool shared) override;
bool isGpsPowered() const override;
bool gpsUsesSerialUart(uint8_t uart) const override;
bool gpsSerialTransportMayConflict(uint8_t uart) const override;
bool gpsSerialTransportCanYield(uint8_t uart) const override;
@@ -0,0 +1,108 @@
#pragma once
#include <stdint.h>
namespace mesh {
namespace gps {
enum class WisBlockPeripheralMode : uint8_t {
GpsOnly = 0,
Shared = 1,
SharedPeripherals = Shared,
};
enum WisBlockRailHold : uint8_t {
RadioPower = 1U << 0,
EthernetPower = 1U << 1,
ExternalStorage = 1U << 2,
};
// These are hardware dependencies, not whether the corresponding service is
// enabled at runtime. In particular, removing Ethernet power can brown out a
// PoE-powered core even when its network service is disabled.
constexpr uint8_t wisBlockCompileRailHolds() {
return 0
#if defined(RAK_3401)
| RadioPower
#endif
#if defined(ETHERNET_ENABLED) || defined(ETHERNET_USE_RAK13800) \
|| defined(RAK4631_COMBINED_ETHERNET)
| EthernetPower
#endif
;
}
// No GPIO, bus probes, allocation, or persistence belongs in this policy.
// Integrators must finish their read-only external-storage probe while the
// discovery hold is set, then freeze its result together with the saved mode.
// A powered/shared GNSS UART still cannot be safely handed to another driver.
class WisBlockSharedPowerPolicy {
public:
explicit WisBlockSharedPowerPolicy(uint8_t initial_holds = 0)
: _holds(static_cast<uint8_t>(initial_holds | wisBlockCompileRailHolds())),
_state(DiscoveryActive) {}
// Configuration is boot-only. Reject repeated or invalid configuration
// without changing the established owners; changing mode requires reboot.
bool configure(WisBlockPeripheralMode mode, uint8_t detected_holds = 0) {
if (isConfigured()
|| (mode != WisBlockPeripheralMode::GpsOnly
&& mode != WisBlockPeripheralMode::Shared)
|| (detected_holds & static_cast<uint8_t>(~KnownHolds)) != 0) {
return false;
}
_holds = static_cast<uint8_t>(_holds | detected_holds);
_state = static_cast<uint8_t>(_state | Configured);
if (mode == WisBlockPeripheralMode::Shared) _state |= SharedMode;
return true;
}
void setDiscoveryActive(bool active) { setFlag(DiscoveryActive, active); }
void setGpsActive(bool active) { setFlag(GpsActive, active); }
bool isConfigured() const { return (_state & Configured) != 0; }
bool discoveryActive() const { return (_state & DiscoveryActive) != 0; }
bool gpsActive() const { return (_state & GpsActive) != 0; }
WisBlockPeripheralMode mode() const {
return (_state & SharedMode) != 0 ? WisBlockPeripheralMode::Shared
: WisBlockPeripheralMode::GpsOnly;
}
uint8_t holds() const { return _holds; }
// Permission to remove GPS power, independent of its current requested
// state. This is not proof that a GNSS TX pin has already become isolated.
bool gpsPowerIndependentlyControllable() const {
return isConfigured() && !discoveryActive()
&& mode() == WisBlockPeripheralMode::GpsOnly && _holds == 0;
}
bool canPowerDown() const {
return gpsPowerIndependentlyControllable() && !gpsActive();
}
bool railEnabled() const { return !canPowerDown(); }
private:
enum State : uint8_t {
Configured = 1U << 0,
SharedMode = 1U << 1,
GpsActive = 1U << 2,
DiscoveryActive = 1U << 3,
};
static constexpr uint8_t KnownHolds =
RadioPower | EthernetPower | ExternalStorage;
// Retain unknown constructor hold bits fail-closed. They must never become
// permission to cut power merely because a future owner is not recognized.
uint8_t _holds;
uint8_t _state;
void setFlag(uint8_t flag, bool enabled) {
if (enabled) _state |= flag;
else _state &= static_cast<uint8_t>(~flag);
}
};
static_assert(sizeof(WisBlockSharedPowerPolicy) == 2,
"WisBlock rail ownership must stay allocation-free and compact");
} // namespace gps
} // namespace mesh