Add an hourly emergency battery sleep schedule for infrastructure nodes

This commit is contained in:
mikecarper committed 2026-10-28 02:06:58 -07:00
1 parent 744692fb93
commit 0c7dec9f19
30 files changed
+2020 -33

No files matched your search

+10
View File
@@ -6,6 +6,7 @@
#include "helpers/UsbLogging.h"
#include "helpers/BatteryChargeSupport.h"
#include "helpers/BatteryCalibration.h"
#include "helpers/EmergencyPowerConfig.h"
#include "helpers/RegulatorMode.h"
#include "helpers/PowerSavingDiagnostics.h"
#include "helpers/LedPolicy.h"
@@ -202,6 +203,15 @@ public:
return false;
}
virtual void enterDeepSleep(uint32_t secs) { (void)secs; }
#if MESH_ENABLE_EMERGENCY_POWER
// Resumable CPU sleep after the caller has suspended RF and drained owners.
// Capability describes the backend, not whether this attempt can sleep.
virtual bool supportsEmergencySleep() const { return false; }
virtual bool emergencySleepMilliseconds(uint32_t millisecs) {
(void)millisecs;
return false;
}
#endif
// Called by example setup() functions to signal that boot is complete.
// Boards may override to stop a boot-indicator LED sequence or similar.
// Default no-op: boards that don't care need not implement anything.
+9 -4
View File
@@ -24,8 +24,8 @@ static constexpr size_t RecordSize = 16;
struct Settings {
uint8_t enabled = 0;
uint8_t repeatBelow = 10;
uint8_t floodBelow = 20;
uint8_t repeatBelow = 15;
uint8_t floodBelow = 25;
// Zero keeps the board's compiled endpoints. nRF52 uses its voltage policy.
uint16_t emptyMv = 0;
uint16_t fullMv = 0;
@@ -54,7 +54,7 @@ inline uint16_t checksum(const uint8_t* data, size_t size) {
inline void encode(uint8_t* out, const Settings& s) {
memset(out, 0, RecordSize);
out[0] = 'B'; out[1] = 'F'; out[2] = 'R'; out[3] = 1;
out[0] = 'B'; out[1] = 'F'; out[2] = 'R'; out[3] = 2;
out[4] = s.enabled; out[5] = s.repeatBelow; out[6] = s.floodBelow;
out[8] = uint8_t(s.emptyMv); out[9] = uint8_t(s.emptyMv >> 8);
out[10] = uint8_t(s.fullMv); out[11] = uint8_t(s.fullMv >> 8);
@@ -65,13 +65,18 @@ inline void encode(uint8_t* out, const Settings& s) {
inline bool decode(const uint8_t* in, size_t size, Settings& s) {
s = Settings{};
if (!in || size != RecordSize || in[0] != 'B' || in[1] != 'F'
|| in[2] != 'R' || in[3] != 1 || in[7] || in[12] || in[13]
|| in[2] != 'R' || (in[3] != 1 && in[3] != 2) || in[7] || in[12] || in[13]
|| checksum(in, 14) != uint16_t(in[14] | (uint16_t(in[15]) << 8))) return false;
Settings candidate;
candidate.enabled = in[4]; candidate.repeatBelow = in[5]; candidate.floodBelow = in[6];
candidate.emptyMv = uint16_t(in[8] | (uint16_t(in[9]) << 8));
candidate.fullMv = uint16_t(in[10] | (uint16_t(in[11]) << 8));
if (!validSettings(candidate)) return false;
// Upgrade the old default pair once; v2 preserves an explicit 10/20 choice.
if (in[3] == 1 && candidate.repeatBelow == 10 && candidate.floodBelow == 20) {
candidate.repeatBelow = 15;
candidate.floodBelow = 25;
}
s = candidate;
return true;
}
+9
View File
@@ -222,6 +222,9 @@ void CommonCLI::loop() {
#if MESH_ENABLE_BATTERY_FORWARDING
loopBatteryForwarding();
#endif
#if MESH_ENABLE_EMERGENCY_POWER
loopEmergencyPower();
#endif
#if MESH_ENABLE_MORSE_RX
if (_morse_reply.pending()) {
const ClientInfo* actor = _acl->getClient(_morse_reply.actor(), PUB_KEY_SIZE);
@@ -1012,6 +1015,9 @@ static void formatSnrDbX4Short(char* dest, size_t dest_len, int16_t snr_x4) {
void CommonCLI::loadPrefs(FILESYSTEM* fs) {
#if MESH_ENABLE_BATTERY_FORWARDING
loadBatteryForwarding(fs);
#endif
#if MESH_ENABLE_EMERGENCY_POWER
loadEmergencyPower(fs);
#endif
mesh::hilStartupTrace("prefs_profiles_begin");
_radio_profiles.begin(fs, _callbacks->getProfileRadio(), _rtc, true);
@@ -3563,6 +3569,9 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
#if MESH_ENABLE_BATTERY_FORWARDING
if (handleBatteryForwardingCommand(command, reply)) return;
#endif
#if MESH_ENABLE_EMERGENCY_POWER
if (handleEmergencyPowerCommand(command, reply)) return;
#endif
#if defined(WITH_UDP_BRIDGE)
if (handleUDPBridgeCommand(sender_timestamp, command, reply)) return;
#endif
+22 -2
View File
@@ -19,6 +19,8 @@
#include <helpers/WirelessControl.h>
#include <helpers/FleetCommand.h>
#include <helpers/BatteryForwarding.h>
#include <helpers/EmergencyPowerConfig.h>
#include <helpers/EmergencyPowerPolicy.h>
#if defined(NRF52_PLATFORM) && defined(OTA_SD_STORE)
#include <helpers/SdCardCLI.h>
#endif
@@ -91,8 +93,8 @@ static constexpr uint8_t DEFAULT_ADVERT_LOC_POLICY = ADVERT_LOC_PREFS;
#define FLOOD_RETRY_ADVERT_DEFAULT 0
#define FLOOD_RETRY_GROUP_MAX_PATH_DEFAULT 1
#define BATTERY_ALERT_LOW_PERCENT_DEFAULT 20
#define BATTERY_ALERT_CRITICAL_PERCENT_DEFAULT 10
#define BATTERY_ALERT_LOW_PERCENT_DEFAULT 25
#define BATTERY_ALERT_CRITICAL_PERCENT_DEFAULT 15
#ifndef FLOOD_RETRY_PREFIX_SLOTS
#define FLOOD_RETRY_PREFIX_SLOTS 8
@@ -938,6 +940,15 @@ class CommonCLI {
void loadBatteryForwarding(FILESYSTEM*) {}
void loopBatteryForwarding(bool = false) const {}
bool handleBatteryForwardingCommand(const char*, char*) { return false; }
#endif
#if MESH_ENABLE_EMERGENCY_POWER
FILESYSTEM* _emergency_power_fs = nullptr;
mesh::emergencypower::State _emergency_power;
bool _emergency_radio_sleeping = false;
void loadEmergencyPower(FILESYSTEM* fs);
bool saveEmergencyPower(const mesh::emergencypower::Settings& settings);
void loopEmergencyPower();
bool handleEmergencyPowerCommand(const char* command, char* reply);
#endif
uint16_t batteryEmptyMv() const;
uint16_t batteryFullMv() const;
@@ -1110,6 +1121,15 @@ public:
#else
bool batteryAllowsForward(bool) const { return true; }
bool batteryAllowsTransmit(const mesh::Packet*) const { return true; }
#endif
#if MESH_ENABLE_EMERGENCY_POWER
uint32_t emergencySleepMilliseconds();
bool emergencyActive() const { return _emergency_power.active(); }
void setEmergencyRadioSleeping(bool sleeping) { _emergency_radio_sleeping = sleeping; }
#else
uint32_t emergencySleepMilliseconds() { return 0; }
bool emergencyActive() const { return false; }
void setEmergencyRadioSleeping(bool) {}
#endif
uint8_t batteryPercent(uint16_t mv) const;
bool hasActiveUserGpioTimer() const;
+146
View File
@@ -0,0 +1,146 @@
#include "CommonCLI.h"
#if MESH_ENABLE_EMERGENCY_POWER
#include "CheckedSettingsFile.h"
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
#include "AtomicFileWriter.h"
#else
#include "ContactFileTransaction.h"
#endif
namespace {
const char* const EMERGENCY_POWER_PATH = "/power_emergency";
bool readEmergencyPower(FILESYSTEM* fs, const char* path,
mesh::emergencypower::Settings& settings) {
uint8_t bytes[mesh::emergencypower::RecordSize];
return mesh::storage::readFixedSettingsFile(fs, path, bytes, sizeof(bytes))
&& mesh::emergencypower::decode(bytes, sizeof(bytes), settings);
}
bool emergencyCommand(const char* command, const char* prefix, const char*& value) {
const size_t length = strlen(prefix);
if (strncmp(command, prefix, length) != 0
|| (command[length] && command[length] != ' ' && command[length] != '\t')) return false;
value = command + length;
while (*value == ' ' || *value == '\t') ++value;
return true;
}
bool emergencyValue(const char* value, const char* expected) {
const size_t length = strlen(expected);
if (strncmp(value, expected, length) != 0) return false;
value += length;
while (*value == ' ' || *value == '\t') ++value;
return !*value;
}
}
void CommonCLI::loadEmergencyPower(FILESYSTEM* fs) {
_emergency_power_fs = fs;
mesh::emergencypower::Settings loaded;
#if defined(ESP32_PLATFORM) || defined(RP2040_PLATFORM)
if (!mesh::ContactFileTransaction::recover(fs, EMERGENCY_POWER_PATH))
_emergency_power_fs = nullptr;
else
#endif
if (!readEmergencyPower(fs, EMERGENCY_POWER_PATH, loaded))
readEmergencyPower(fs, "/power_emergency.bak", loaded);
_emergency_power.begin(loaded, millis());
_emergency_radio_sleeping = false;
}
bool CommonCLI::saveEmergencyPower(const mesh::emergencypower::Settings& settings) {
if (!_emergency_power_fs) return false;
uint8_t bytes[mesh::emergencypower::RecordSize];
mesh::emergencypower::encode(bytes, settings);
#if defined(NRF52_PLATFORM)
return mesh::storage::writeCheckedSettingsFile(_emergency_power_fs, EMERGENCY_POWER_PATH,
bytes, sizeof(bytes)) == mesh::AtomicFileWriter::Outcome::Committed;
#else
#if defined(STM32_PLATFORM)
mesh::AtomicFileWriter writer(_emergency_power_fs, EMERGENCY_POWER_PATH);
#else
mesh::ContactFileTransaction writer(_emergency_power_fs, EMERGENCY_POWER_PATH);
#endif
if (!writer || writer.write(bytes, sizeof(bytes)) != sizeof(bytes) || !writer.commit()) return false;
uint8_t verified[sizeof(bytes)];
return mesh::storage::readFixedSettingsFile(_emergency_power_fs, EMERGENCY_POWER_PATH,
verified, sizeof(verified)) && memcmp(bytes, verified, sizeof(bytes)) == 0;
#endif
}
void CommonCLI::loopEmergencyPower() {
const uint32_t now = millis();
if (!_emergency_power.due(now)) return;
const uint16_t mv = _board->getBattMilliVolts();
_emergency_power.sample(now, mv, batteryPercent(mv),
mesh::batteryforward::validEndpoints(batteryEmptyMv(), batteryFullMv()));
}
uint32_t CommonCLI::emergencySleepMilliseconds() {
loopEmergencyPower();
return _emergency_power.sleepMilliseconds(millis(), _rtc->getCurrentTime());
}
bool CommonCLI::handleEmergencyPowerCommand(const char* command, char* reply) {
if (!command || !reply) return false;
const char* value;
if (emergencyCommand(command, "get power.emergency", value)) {
if (*value) snprintf(reply, 157, "Error: use get power.emergency");
else {
const uint32_t sleep_ms = emergencySleepMilliseconds();
char battery[12] = "unknown";
if (_emergency_power.valid)
snprintf(battery, sizeof(battery), "%u%%", unsigned(_emergency_power.percentage));
snprintf(reply, 157, "> mode=%s active=%s battery=%s clock=%s window=%s radio=%s wake=%lus hold=%lus",
_emergency_power.settings.manual ? "manual" : "auto", emergencyActive() ? "on" : "off",
battery, mesh::emergencypower::State::usesRtc(_rtc->getCurrentTime()) ? "rtc" : "uptime",
sleep_ms ? "sleep" : "awake", _emergency_radio_sleeping ? "sleep" : "awake",
static_cast<unsigned long>((sleep_ms + 999UL) / 1000UL),
static_cast<unsigned long>((_emergency_power.holdRemaining(millis()) + 999UL) / 1000UL));
}
return true;
}
if (emergencyCommand(command, "set power.emergency", value)) {
const bool manual = emergencyValue(value, "on");
if (!manual && !emergencyValue(value, "auto")) {
snprintf(reply, 157, "Error: use set power.emergency on|auto");
return true;
}
if (manual && !_board->supportsEmergencySleep()) {
snprintf(reply, 157, "Error: emergency sleep unsupported on this board");
return true;
}
mesh::emergencypower::Settings candidate;
candidate.manual = manual;
if (candidate.manual != _emergency_power.settings.manual && !saveEmergencyPower(candidate))
snprintf(reply, 157, "Error: emergency settings save unconfirmed; active policy unchanged");
else {
_emergency_power.setManual(manual, millis());
snprintf(reply, 157, "OK - emergency %s", manual ? "on" : "auto");
}
return true;
}
if (!emergencyCommand(command, "set power.awake", value)) return false;
uint16_t minutes = 0;
const char* p = value;
bool digits = false;
while (*p >= '0' && *p <= '9') {
digits = true;
const unsigned number = unsigned(minutes) * 10U + unsigned(*p++ - '0');
if (number > mesh::emergencypower::MaximumAwakeMinutes) {
snprintf(reply, 157, "Error: use set power.awake 0-10080 (minutes)");
return true;
}
minutes = uint16_t(number);
}
while (*p == ' ' || *p == '\t') ++p;
if (!digits || *p) snprintf(reply, 157, "Error: use set power.awake 0-10080 (minutes)");
else {
_emergency_power.stayAwake(minutes, millis());
snprintf(reply, 157, "OK - awake for %u minutes", unsigned(minutes));
}
return true;
}
#endif // MESH_ENABLE_EMERGENCY_POWER
+31
View File
@@ -8,6 +8,9 @@
#include "FileRead.h"
#include "UserGpioPinPolicy.h"
#include <helpers/esp32/ManagementPassword.h>
#if MESH_ENABLE_EMERGENCY_POWER
#include <esp_task_wdt.h>
#endif
namespace mesh {
namespace esp32_clock {
@@ -1408,6 +1411,34 @@ void ESP32Board::powerOff() {
enterDeepSleep(0); // Do not wakeup
}
#if MESH_ENABLE_EMERGENCY_POWER
bool ESP32Board::emergencySleepMilliseconds(uint32_t millisecs) {
// The caller owns radio suspension and reversible wireless shutdown. Never
// force a live WiFi/Bluetooth stack through explicit light sleep.
if (millisecs == 0 || isRadioTestActive() || xPortInIsrContext()
|| xTaskGetSchedulerState() != taskSCHEDULER_RUNNING
|| !mesh::esp32::manualLightSleepReady()) return false;
if (millisecs > 10000UL) millisecs = 10000UL;
const esp_err_t watchdog_status = esp_task_wdt_status(nullptr);
const bool watched = watchdog_status == ESP_OK;
if (!watched && watchdog_status != ESP_ERR_NOT_FOUND
&& watchdog_status != ESP_ERR_INVALID_STATE) return false;
#if defined(CONFIG_ESP_TASK_WDT_TIMEOUT_S) && CONFIG_ESP_TASK_WDT_TIMEOUT_S > 0
if (watched && millisecs > uint32_t(CONFIG_ESP_TASK_WDT_TIMEOUT_S) * 500UL)
millisecs = uint32_t(CONFIG_ESP_TASK_WDT_TIMEOUT_S) * 500UL;
#endif
if (watched && esp_task_wdt_reset() != ESP_OK) return false;
if (esp_sleep_enable_timer_wakeup(uint64_t(millisecs) * 1000ULL) != ESP_OK)
return false;
// Add no radio/GPIO wake. Existing button sources remain untouched. The
// normal sleep path installs its own next timer; never leave ours armed.
const esp_err_t slept = esp_light_sleep_start();
const esp_err_t cleared = esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_TIMER);
const bool watchdog_ok = !watched || esp_task_wdt_reset() == ESP_OK;
return slept == ESP_OK && cleared == ESP_OK && watchdog_ok;
}
#endif
void ESP32Board::enterDeepSleep(uint32_t secs) {
shutdownPeripherals();
+4
View File
@@ -349,6 +349,10 @@ public:
virtual void shutdownPeripherals();
virtual void powerOff() override;
virtual void enterDeepSleep(uint32_t secs) override;
#if MESH_ENABLE_EMERGENCY_POWER
bool supportsEmergencySleep() const override { return true; }
bool emergencySleepMilliseconds(uint32_t millisecs) override;
#endif
uint32_t getIRQGpio() override {
#ifdef P_LORA_DIO_1
+38
View File
@@ -0,0 +1,38 @@
#pragma once
#include "EmergencyPowerConfig.h"
#include <stdint.h>
#if MESH_ENABLE_EMERGENCY_POWER
namespace mesh { namespace power {
class EmergencyOtaWork {
mutable uint32_t served_at_ = 0, serve_hold_ms_ = 0;
public:
template <typename Context>
bool busy(const Context* context, uint32_t now) const {
bool receiving = false, cleanup = false;
if (context) {
const auto& manager = context->manager;
using Manager = decltype(context->manager);
const auto state = manager.fetchState();
receiving = state == Manager::WANT_MANIFEST || state == Manager::WANT_LEAVES
|| state == Manager::VERIFYING_STAGED || state == Manager::FETCHING;
if (manager.pendingServeJobs() || manager.pendingManifestJobs()) {
// Keep listening between a proof and the peer's next block request.
// Idle self-serving/catalog adverts never renew this bounded hold.
const uint32_t retry = manager.fetchRetryTimeoutMs();
serve_hold_ms_ = retry < 30000UL ? 30000UL : retry;
served_at_ = now;
}
#if defined(OTA_SD_STORE)
cleanup = context->sdCacheFetching();
#endif
}
if (serve_hold_ms_ && uint32_t(now - served_at_) >= serve_hold_ms_) serve_hold_ms_ = 0;
return receiving || cleanup || serve_hold_ms_ != 0;
}
};
}} // namespace mesh::power
#endif
+11
View File
@@ -0,0 +1,11 @@
#pragma once
// The source-role build policy enables this for supported infrastructure
// images. Companion and constrained profiles retain their existing footprint.
#ifndef MESH_ENABLE_EMERGENCY_POWER
#define MESH_ENABLE_EMERGENCY_POWER 0
#endif
#if MESH_ENABLE_EMERGENCY_POWER != 0 && MESH_ENABLE_EMERGENCY_POWER != 1
#error "MESH_ENABLE_EMERGENCY_POWER must be 0 or 1"
#endif
+122
View File
@@ -0,0 +1,122 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
namespace mesh { namespace emergencypower {
static constexpr uint32_t SampleIntervalMs = 30000;
static constexpr uint32_t HourMs = 3600000;
static constexpr uint32_t AwakeWindowMs = 900000;
static constexpr uint32_t ReplyHoldMs = 5000;
static constexpr uint32_t PlausibleEpoch = 1577836800; // 2020-01-01 UTC
static constexpr uint16_t MaximumAwakeMinutes = 10080;
static constexpr size_t RecordSize = 8;
struct Settings {
bool manual = false;
};
inline uint16_t checksum(const uint8_t* data, size_t size) {
uint16_t crc = 0xffff;
while (size--) {
crc ^= uint16_t(*data++) << 8;
for (unsigned bit = 0; bit < 8; ++bit)
crc = (crc & 0x8000) ? uint16_t((crc << 1) ^ 0x1021) : uint16_t(crc << 1);
}
return crc;
}
inline void encode(uint8_t* out, const Settings& settings) {
out[0] = 'P'; out[1] = 'E'; out[2] = 'M'; out[3] = 1;
out[4] = settings.manual ? 1 : 0; out[5] = 0;
const uint16_t crc = checksum(out, 6);
out[6] = uint8_t(crc); out[7] = uint8_t(crc >> 8);
}
inline bool decode(const uint8_t* in, size_t size, Settings& settings) {
settings = Settings{};
if (!in || size != RecordSize || in[0] != 'P' || in[1] != 'E'
|| in[2] != 'M' || in[3] != 1 || in[4] > 1 || in[5]
|| checksum(in, 6) != uint16_t(in[6] | uint16_t(in[7]) << 8)) return false;
settings.manual = in[4] != 0;
return true;
}
struct State {
Settings settings;
uint32_t sampledAt = 0;
uint16_t millivolts = 0;
uint8_t percentage = 0;
bool sampled = false;
bool valid = false;
bool lowBattery = false;
uint32_t phaseMs = 0;
uint32_t lastTick = 0;
uint32_t activationStarted = 0;
uint32_t awakeStarted = 0;
uint32_t awakeDuration = 0;
bool activationHold = false;
void begin(const Settings& loaded, uint32_t now) {
*this = State{};
settings = loaded;
phaseMs = now % HourMs;
lastTick = now;
if (active()) holdReplies(now);
}
bool active() const { return settings.manual || lowBattery; }
bool due(uint32_t now) const {
return !sampled || uint32_t(now - sampledAt) >= SampleIntervalMs;
}
void holdReplies(uint32_t now) {
activationStarted = now;
activationHold = true;
}
void setManual(bool manual, uint32_t now) {
if (settings.manual == manual) return;
settings.manual = manual;
if (active()) holdReplies(now);
}
void sample(uint32_t now, uint16_t mv, uint8_t pct, bool known) {
const bool was_active = active();
sampled = true; sampledAt = now; millivolts = mv; percentage = pct;
valid = known && pct <= 100 && mv >= 2000 && mv <= 20000;
// A failed reading cannot wake a node already protecting its battery.
if (valid) lowBattery = lowBattery ? pct < 7 : pct <= 5;
if (!was_active && active()) holdReplies(now);
}
bool stayAwake(uint16_t minutes, uint32_t now) {
if (minutes > MaximumAwakeMinutes) return false;
awakeStarted = now;
awakeDuration = uint32_t(minutes) * 60000UL;
return true;
}
uint32_t holdRemaining(uint32_t now) {
uint32_t remaining = 0;
if (activationHold) {
const uint32_t elapsed = uint32_t(now - activationStarted);
if (elapsed >= ReplyHoldMs) activationHold = false;
else remaining = ReplyHoldMs - elapsed;
}
if (awakeDuration) {
const uint32_t elapsed = uint32_t(now - awakeStarted);
if (elapsed >= awakeDuration) awakeDuration = 0;
else if (awakeDuration - elapsed > remaining) remaining = awakeDuration - elapsed;
}
return remaining;
}
static bool usesRtc(uint32_t epoch) { return epoch >= PlausibleEpoch; }
uint32_t sleepMilliseconds(uint32_t now, uint32_t epoch) {
// Accumulate the boot-relative phase across millis() wrap. RTC corrections
// change only the hourly window, never the duration of an awake lease.
phaseMs = (phaseMs + uint32_t(now - lastTick) % HourMs) % HourMs;
lastTick = now;
const uint32_t hold = holdRemaining(now);
if (!active() || hold) return 0;
const uint32_t phase = usesRtc(epoch) ? (epoch % 3600UL) * 1000UL : phaseMs;
return phase < AwakeWindowMs ? 0 : HourMs - phase;
}
};
}} // namespace mesh::emergencypower
+59
View File
@@ -0,0 +1,59 @@
#pragma once
#include "EmergencyPowerConfig.h"
#if MESH_ENABLE_EMERGENCY_POWER
#include <Arduino.h>
#include "WirelessControl.h"
namespace mesh { namespace power {
class EmergencyPowerRuntime {
bool radio_asleep_ = false;
bool radio_was_available_ = false;
public:
template <typename Mesh, typename Radio, typename Board, typename CLI>
bool service(Mesh& mesh, Radio& radio, Board& board, CLI& cli,
bool entry_busy, bool work_required = false) {
const uint32_t budget = cli.emergencySleepMilliseconds();
if (!board.supportsEmergencySleep()) return false;
const bool active_operation = work_required || board.isOTAUpdateRunning()
|| board.isRadioTestActive() || radio.isMorseTxActive() || radio.isMorseRxActive();
if (budget == 0 || active_operation) {
if (radio_asleep_) {
if (radio_was_available_) {
if (!radio.setTrackerSleep(false)) radio.recoverRadio(true);
mesh.setRadioAvailable(true);
}
radio_asleep_ = false;
cli.setEmergencyRadioSleeping(false);
}
wireless::control().resumeAfterEmergency();
return false;
}
if (!radio_asleep_) {
// Complete live operations and command replies before taking ownership.
// Queued future traffic cannot keep a critically low node awake forever.
if (entry_busy || mesh.hasOutbound()) return false;
if (!wireless::control().suspendForEmergency()) return false;
radio_was_available_ = mesh.isRadioAvailable();
if (radio_was_available_) {
if (!radio.setTrackerSleep(true)) return false;
mesh.setRadioAvailable(false);
}
radio_asleep_ = true;
cli.setEmergencyRadioSleeping(true);
}
// Brief maintenance wakes retain voltage protection and watchdogs. Normal
// radio/mesh/sensor/UI work remains suspended throughout the off window.
if (!board.emergencySleepMilliseconds(budget > 10000 ? 10000 : budget)) {
// A transient SDK/driver refusal must not turn battery protection into
// a busy loop. Keep RF ownership and retry after yielding the CPU.
delay(10);
}
return true;
}
};
}} // namespace mesh::power
#endif
+27 -1
View File
@@ -312,7 +312,7 @@ float NRF52Board::getAdcMultiplier() const {
return mesh::MainBoard::getAdcMultiplier();
}
#if NRF52_WATCHDOG_TIMEOUT_SECONDS > 0
#if NRF52_WATCHDOG_TIMEOUT_SECONDS > 0 || MESH_ENABLE_EMERGENCY_POWER
static void reloadWatchdogChannels() {
// Ordinarily only RR0 is enabled. If a bootloader left the watchdog running
// with a different reload channel, service every enabled channel.
@@ -927,6 +927,32 @@ void NRF52Board::powerOff() {
}
}
#if MESH_ENABLE_EMERGENCY_POWER
bool NRF52Board::emergencySleepMilliseconds(uint32_t millisecs) {
// Blocking the sketch lets the existing RTOS idle/RTC machinery sleep the
// CPU. SYSTEMOFF cannot provide a timed wake on every supported nRF52 board.
if (millisecs == 0 || watchdog_disable_reset_pending || isRadioTestActive()
|| __get_IPSR() != 0 || __get_PRIMASK() != 0 || __get_BASEPRI() != 0
|| __get_FAULTMASK() != 0 || nrf_nvic_state.__cr_flag != 0
|| xTaskGetSchedulerState() != taskSCHEDULER_RUNNING) return false;
if (millisecs > 10000UL) millisecs = 10000UL;
if (NRF_WDT->RUNSTATUS != 0) {
// A bootloader may have left a shorter watchdog than this build's default.
// Half its actual timeout leaves room for scheduling and wake processing.
const uint32_t watchdog_budget_ms = (NRF_WDT->CRV / 32768UL) * 500UL;
if (watchdog_budget_ms == 0) return false;
if (millisecs > watchdog_budget_ms) millisecs = watchdog_budget_ms;
}
const TickType_t ticks = pdMS_TO_TICKS(millisecs);
if (ticks == 0) return false;
// Service inherited watchdogs even when this build does not start one.
if (NRF_WDT->RUNSTATUS != 0) reloadWatchdogChannels();
vTaskDelay(ticks);
if (NRF_WDT->RUNSTATUS != 0) reloadWatchdogChannels();
return true;
}
#endif
void NRF52Board::enterDeepSleep(uint32_t secs) {
if (secs == 0) {
powerOff(); // Not wake up
+4
View File
@@ -80,6 +80,10 @@ public:
virtual void shutdownPeripherals();
virtual void powerOff() override;
virtual void enterDeepSleep(uint32_t secs) override;
#if MESH_ENABLE_EMERGENCY_POWER
bool supportsEmergencySleep() const override { return true; }
bool emergencySleepMilliseconds(uint32_t millisecs) override;
#endif
virtual bool getBootloaderVersion(char* version, size_t max_len) override;
virtual bool startOTAUpdate(const char *id, char reply[], bool force_ap = false) override;
virtual bool stopOTAUpdate(char reply[]) override;
+51
View File
@@ -4,6 +4,7 @@
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "EmergencyPowerConfig.h"
namespace mesh {
namespace wireless {
@@ -59,6 +60,10 @@ class Control {
uint8_t scope_ = 0, target_ = 0, saved_ = 0;
bool pending_ = false, started_ = false, force_ = false, independent_requester_ = false;
bool saved_valid_ = false, master_off_ = false;
#if MESH_ENABLE_EMERGENCY_POWER
bool emergency_suspended_ = false;
uint8_t emergency_enabled_ = 0, emergency_blocked_ = 0;
#endif
uint32_t due_ = 0;
const char* error_ = nullptr;
@@ -73,6 +78,9 @@ public:
}
bool masterOff() const { return master_off_; }
bool allowService(uint8_t service) {
#if MESH_ENABLE_EMERGENCY_POWER
if (emergency_suspended_) return false;
#endif
if (master_off_ || pending_) return false;
blocked_.store(blocked_.load() & ~service);
return true;
@@ -81,6 +89,9 @@ public:
// disabled 2.4 GHz for this boot. Leave the other services disabled. Do not
// race a pending shutdown, which could otherwise turn OTA off afterwards.
bool allowWiFiForOTA() {
#if MESH_ENABLE_EMERGENCY_POWER
if (emergency_suspended_) return false;
#endif
if (pending_) return false;
blocked_.store(blocked_.load() & ~WiFi);
master_off_ = false;
@@ -90,6 +101,40 @@ public:
}
uint8_t enabled() const { return backend_ ? backend_->enabled() : 0; }
#if MESH_ENABLE_EMERGENCY_POWER
// A scheduled battery sleep borrows the live services without changing the
// user's saved wireless policy or the ordinary off/on restore snapshot.
bool suspendForEmergency() {
if (!backend_) return true;
if (pending_) return false;
if (!emergency_suspended_) {
emergency_enabled_ = enabled();
emergency_blocked_ = blocked_.load();
emergency_suspended_ = true;
blocked_.store(emergency_blocked_ | All);
}
const uint8_t order[] = {WiFi, EspNow, Bluetooth};
for (uint8_t service : order) {
if ((emergency_enabled_ & service) && backend_->set(service, false) != Result::Done)
return false;
}
return enabled() == 0;
}
bool resumeAfterEmergency() {
if (!emergency_suspended_) return true;
const uint8_t order[] = {EspNow, WiFi, Bluetooth};
for (uint8_t service : order) {
if (!(emergency_enabled_ & service)) continue;
blocked_.store(blocked_.load() & ~service);
if (backend_->set(service, true) != Result::Done) return false;
}
blocked_.store(emergency_blocked_);
emergency_suspended_ = false;
return true;
}
#endif
bool handle(const char* text, char* reply, size_t size, uint32_t now, uint8_t requester) {
const auto command = parse(text);
if (command.action == Action::None || !reply || !size) return false;
@@ -106,6 +151,12 @@ public:
else snprintf(reply, size, "wifi=%s, bluetooth=%s, espnow=%s%s%s", state(WiFi), state(Bluetooth), state(EspNow), pending_ ? " (pending)" : "", error_ ? error_ : "");
return true;
}
#if MESH_ENABLE_EMERGENCY_POWER
if (emergency_suspended_) {
snprintf(reply, size, "Error: emergency sleep; use set power.awake <minutes> first");
return true;
}
#endif
if (!(available & command.scope)) {
snprintf(reply, size, "Error: requested wireless service unavailable in this build/boot");
return true;