Add ESP32 clock selection and bounded power test controls

This commit is contained in:
mikecarper committed 2026-10-21 21:06:42 -07:00
1 parent 11dbca377c
commit 6e599d1709
33 files changed
+4028 -2430

No files matched your search

+7
View File
@@ -148,6 +148,13 @@ public:
virtual void onAfterTransmit() { }
// Update only indicator outputs; transmit hooks may also control RF hardware.
virtual void applyLedPolicy() { }
#if defined(ESP32_PLATFORM)
// CPU clock selection is ESP32-only; other platforms retain their current
// preference layout and board vtable. Zero selects the role's Auto policy.
virtual uint16_t getCpuFrequencyMHz() const { return 0; }
virtual bool supportsCpuFrequencyMHz(uint16_t) const { return false; }
virtual bool applyCpuFrequencyMHz(uint16_t, bool) { return false; }
#endif
virtual void reboot() = 0;
MESH_REGULATOR_VIRTUAL uint8_t mcuRegulatorModes() const { return 0; }
MESH_REGULATOR_VIRTUAL power::RegulatorMode defaultMcuRegulatorMode() const {
+38
View File
@@ -9,6 +9,10 @@
#include "UsbLoggingWatchdog.h"
#include "PowerSavingDiagnostics.h"
#include "HilStartupTrace.h"
#if defined(ESP32_PLATFORM)
#include <helpers/esp32/CpuClockPolicy.h>
#include <helpers/esp32/PowerTestControls.h>
#endif
#include <helpers/ui/DisplayPowerSettings.h>
#if defined(OLED_AUTO_DETECT) && OLED_AUTO_DETECT && defined(DISPLAY_CLASS)
#include <helpers/ui/OLEDControllerSettings.h>
@@ -1100,6 +1104,9 @@ 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(ESP32_PLATFORM)
_prefs->cpu_freq_mhz = 0;
#endif
#if defined(RAK_4631)
// Failure to read an existing policy cannot authorize a shared-rail cut.
_prefs->peripherals_shared = 1;
@@ -1803,6 +1810,11 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
// Read the footer independently of optional legacy UART tails/profile.
#if defined(RAK_4631)
_prefs->peripherals_shared = mesh::peripherals::readCommonMode(file);
#endif
#if defined(ESP32_PLATFORM)
_prefs->cpu_freq_mhz = mesh::esp32::cpuclock::readFooter(file);
if (_prefs->cpu_freq_mhz && !_board->supportsCpuFrequencyMHz(_prefs->cpu_freq_mhz))
_prefs->cpu_freq_mhz = 0;
#endif
file.close();
}
@@ -1974,6 +1986,13 @@ static bool writeCommonPrefsImage(Writer& writer, NodePrefs* prefs) {
mesh::peripherals::encodeFooter(peripheral_footer, prefs->peripherals_shared);
WRITE_COMMON_PREFS_BYTES(peripheral_footer, sizeof(peripheral_footer));
#endif
#if defined(ESP32_PLATFORM)
if (prefs->cpu_freq_mhz && mesh::esp32::cpuclock::validSelection(prefs->cpu_freq_mhz)) {
uint8_t cpu_footer[mesh::esp32::cpuclock::FooterSize];
mesh::esp32::cpuclock::encodeFooter(cpu_footer, prefs->cpu_freq_mhz);
WRITE_COMMON_PREFS_BYTES(cpu_footer, sizeof(cpu_footer));
}
#endif
#undef WRITE_COMMON_PREFS_BYTES
#undef WRITE_COMMON_PREFS
@@ -2057,6 +2076,11 @@ void CommonCLI::savePrefs(FILESYSTEM* fs, PrefsSaveRouting::Scope scope) {
_common_save_succeeded = false;
_prefs->usb_debug_enabled = _prefs->usb_debug_enabled == 1 ? 1 : 0;
_prefs->trace_when_repeat_off = _prefs->trace_when_repeat_off == 1 ? 1 : 0;
#if defined(ESP32_PLATFORM)
if (!mesh::esp32::cpuclock::validSelection(_prefs->cpu_freq_mhz)
|| (_prefs->cpu_freq_mhz && !_board->supportsCpuFrequencyMHz(_prefs->cpu_freq_mhz)))
_prefs->cpu_freq_mhz = 0;
#endif
#ifdef WITH_RS232_BRIDGE
mesh::bridge::rs232power::sanitize(_prefs->rs232_heartbeat,
_prefs->rs232_autosleep, _prefs->rs232_idle_seconds);
@@ -2213,6 +2237,13 @@ void CommonCLI::savePrefs(FILESYSTEM* fs, PrefsSaveRouting::Scope scope) {
mesh::peripherals::encodeFooter(peripheral_footer, _prefs->peripherals_shared);
file.write(peripheral_footer, sizeof(peripheral_footer));
#endif
#if defined(ESP32_PLATFORM)
if (_prefs->cpu_freq_mhz && mesh::esp32::cpuclock::validSelection(_prefs->cpu_freq_mhz)) {
uint8_t cpu_footer[mesh::esp32::cpuclock::FooterSize];
mesh::esp32::cpuclock::encodeFooter(cpu_footer, _prefs->cpu_freq_mhz);
file.write(cpu_footer, sizeof(cpu_footer));
}
#endif
_common_save_succeeded = file.commit();
if (!_common_save_succeeded) {
@@ -3033,6 +3064,13 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
if (mesh::leds::handleCommand(command, reply, 157)) return;
if (mesh::handleUsbLoggingWatchdogCommand(command, reply, 160)) return;
if (mesh::powerdiag::handleCommand(command, reply, 157, millis())) return;
#if defined(ESP32_PLATFORM)
if (mesh::esp32::cpuclock::handleCommand(*_board, _prefs->cpu_freq_mhz,
_prefs->powersaving_enabled != 0, command, reply, 157,
[this]() { return saveCommonPrefs(); })) return;
if (mesh::esp32::handlePowerTestCommand(command, reply, 157,
sender_timestamp == 0)) return;
#endif
if (handleManagementCommand(command, reply)) return;
#if MESH_ENABLE_TX_BEACONS
if (handleBeaconCommand(command, reply, 157)) return;
+6
View File
@@ -162,6 +162,9 @@ public:
char bridge_secret[16] = {}; // for XOR encryption of bridge packets (ESP-NOW only)
// Power setting
uint8_t powersaving_enabled = DEFAULT_POWERSAVING_ENABLED ? 1 : 0; // boolean
#if defined(ESP32_PLATFORM)
uint16_t cpu_freq_mhz = 0; // 0=Auto; checked ESP32-only append-only footer
#endif
uint8_t reboot_interval = 0; // hours, 0-255 (default 0=disable)
// Gps settings
uint8_t gps_enabled = 0;
@@ -398,6 +401,9 @@ private:
void structure() override {
def("adc_mult", _parent->adc_multiplier);
def("pwr_sav_en", _parent->powersaving_enabled);
#if defined(ESP32_PLATFORM)
def("cpu_freq", _parent->cpu_freq_mhz);
#endif
}
public:
+169 -2
View File
@@ -21,6 +21,12 @@
#include "UsbHostSleepPolicy.h"
#include "PowerSavingDiagnostics.h"
#include "esp32/LightSleepPolicy.h"
#include "esp32/PowerTestControls.h"
#include "esp32/CpuClockPolicy.h"
#include <esp_pm.h>
#if CONFIG_IDF_TARGET_ESP32
#include <soc/efuse_reg.h>
#endif
#if defined(STATION_G3_ESP32)
#include <StationG3RadioSlot.h>
#endif
@@ -47,6 +53,10 @@ protected:
bool inhibit_sleep = false;
bool ota_started_ap = false;
bool ota_started_radio = false;
bool companion_cpu_clock_policy = false;
uint32_t uart_quiet_start_at = 0;
uint32_t uart_quiet_restore_at = 0;
uint16_t uart_quiet_seconds = 0;
#if MESH_ESP32_USB_CONSOLE_COOPERATIVE
mesh::UsbHostSleepPolicy usb_host_sleep_policy;
#endif
@@ -76,6 +86,12 @@ public:
// for future use, sub-classes SHOULD call this from their begin()
startup_reason = BD_STARTUP_NORMAL;
mesh::esp32::registerUartQuietControl(this,
[](void* owner, mesh::esp32::UartQuietAction action, uint16_t seconds,
char* reply, size_t capacity) {
return static_cast<ESP32Board*>(owner)->handleUartQuiet(action, seconds, reply, capacity);
});
#ifdef ESP32_CPU_FREQ
setCpuFrequencyMhz(ESP32_CPU_FREQ);
#endif
@@ -104,6 +120,137 @@ public:
void attachDynamicPrefs(KeyValueStore* prefs) { (void)prefs; } // no-op
void setCompanionCpuClockPolicy(bool enabled) { companion_cpu_clock_policy = enabled; }
uint16_t getCpuFrequencyMHz() const override { return ::getCpuFrequencyMhz(); }
bool supportsCpuFrequencyMHz(uint16_t mhz) const override {
#if CONFIG_IDF_TARGET_ESP32H2
(void)mhz;
return false;
#else
if (mhz == 80) return true;
#if CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3 \
|| CONFIG_IDF_TARGET_ESP32C3 || CONFIG_IDF_TARGET_ESP32C6
if (mhz == 160) return true;
#endif
#if CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3
if (mhz == 240) {
#if CONFIG_IDF_TARGET_ESP32
if (REG_GET_BIT(EFUSE_BLK0_RDATA3_REG, EFUSE_RD_CHIP_CPU_FREQ_RATED)
&& REG_GET_BIT(EFUSE_BLK0_RDATA3_REG, EFUSE_RD_CHIP_CPU_FREQ_LOW)) return false;
#endif
return true;
}
#endif
return false;
#endif
}
bool applyCpuFrequencyMHz(uint16_t selected, bool powersaving) override {
if (!mesh::esp32::cpuclock::validSelection(selected)
|| (selected && !supportsCpuFrequencyMHz(selected))) return false;
uint16_t maximum = mesh::esp32::cpuclock::resolveMHz(
selected, powersaving, companion_cpu_clock_policy);
if (!selected && maximum == 240 && !supportsCpuFrequencyMHz(240)
&& supportsCpuFrequencyMHz(160)) maximum = 160;
#if defined(CONFIG_PM_ENABLE) && CONFIG_PM_ENABLE
const uint16_t minimum = !selected && companion_cpu_clock_policy && powersaving && maximum > 40
? 40 : maximum;
#if CONFIG_IDF_TARGET_ESP32C3
esp_pm_config_esp32c3_t config;
#elif CONFIG_IDF_TARGET_ESP32S3
esp_pm_config_esp32s3_t config;
#elif CONFIG_IDF_TARGET_ESP32
esp_pm_config_esp32_t config;
#else
esp_pm_config_t config;
#endif
config.max_freq_mhz = maximum;
config.min_freq_mhz = minimum;
#if (defined(ARDUINO_USB_CDC_ON_BOOT) && ARDUINO_USB_CDC_ON_BOOT) || defined(ENABLE_USB_INTERFACE)
config.light_sleep_enable = false;
#else
config.light_sleep_enable = companion_cpu_clock_policy && powersaving;
#endif
if (esp_pm_configure(&config) != ESP_OK) return false;
#else
if (!setCpuFrequencyMhz(maximum)) return false;
#endif
return !selected || getCpuFrequencyMHz() == selected;
}
bool handleUartQuiet(mesh::esp32::UartQuietAction action, uint16_t seconds,
char* reply, size_t capacity) {
#if (defined(ARDUINO_USB_CDC_ON_BOOT) && ARDUINO_USB_CDC_ON_BOOT) \
|| defined(SERIAL_RX) || defined(SERIAL_TX)
(void)seconds;
const bool harmless = action != mesh::esp32::UartQuietAction::Schedule;
snprintf(reply, capacity, harmless ? "uart=unsupported"
: "Error: UART quiet requires a default hardware UART console");
return harmless;
#else
if (action == mesh::esp32::UartQuietAction::Cancel) {
uart_quiet_start_at = 0;
if (uart_quiet_restore_at) {
Serial.begin(115200); // all four roles start this same default console
if (!Serial) {
uart_quiet_restore_at = millis() + 1000;
if (!uart_quiet_restore_at) uart_quiet_restore_at = 1;
snprintf(reply, capacity, "Error: UART restore failed; retrying automatically");
return false;
}
uart_quiet_restore_at = 0;
}
uart_quiet_seconds = 0;
} else if (action == mesh::esp32::UartQuietAction::Schedule) {
if (seconds < 5 || seconds > 300 || uart_quiet_start_at || uart_quiet_restore_at
|| !Serial || inhibit_sleep || isOTAUpdateRunning() || isRadioTestActive()
|| mesh::isUsbLoggingEnabled()) {
snprintf(reply, capacity, "Error: UART quiet needs an idle console, logging/OTA off, and 5..300 seconds");
return false;
}
uart_quiet_seconds = seconds;
uart_quiet_start_at = millis() + 100;
if (!uart_quiet_start_at) uart_quiet_start_at = 1;
snprintf(reply, capacity, "OK - UART quiet in 100ms after replies drain, for %us; automatic restore", unsigned(seconds));
return true;
}
const int32_t remaining = static_cast<int32_t>(uart_quiet_restore_at - millis());
snprintf(reply, capacity, "uart=%s remaining_s=%lu", uart_quiet_start_at ? "armed"
: uart_quiet_restore_at ? "quiet" : "active", static_cast<unsigned long>(
uart_quiet_start_at ? uart_quiet_seconds : uart_quiet_restore_at && remaining > 0
? (uint32_t(remaining) + 999) / 1000 : 0));
return true;
#endif
}
// Call after the role's reply pump, and regardless of its sleep decision.
// A quiet console is always restored by a timer; no permanent guard bypass.
void servicePowerTestControls(bool replies_drained = true) {
#if (!defined(ARDUINO_USB_CDC_ON_BOOT) || !ARDUINO_USB_CDC_ON_BOOT) \
&& !defined(SERIAL_RX) && !defined(SERIAL_TX)
char ignored[96];
const uint32_t now = millis();
if (uart_quiet_restore_at && (static_cast<int32_t>(now - uart_quiet_restore_at) >= 0
|| inhibit_sleep || isOTAUpdateRunning() || isRadioTestActive() || mesh::isUsbLoggingEnabled())) {
handleUartQuiet(mesh::esp32::UartQuietAction::Cancel, 0, ignored, sizeof(ignored));
}
if (!uart_quiet_start_at || static_cast<int32_t>(now - uart_quiet_start_at) < 0) return;
if (static_cast<int32_t>(now - uart_quiet_start_at) >= 1900
|| inhibit_sleep || isOTAUpdateRunning() || isRadioTestActive() || mesh::isUsbLoggingEnabled()) {
uart_quiet_start_at = 0; uart_quiet_seconds = 0;
return;
}
if (!replies_drained || mesh::hasPendingUsbTerminalOutput()) return;
Serial.flush(); // drain the hardware FIFO containing the acknowledgement
Serial.end();
uart_quiet_restore_at = millis() + uint32_t(uart_quiet_seconds) * 1000;
if (!uart_quiet_restore_at) uart_quiet_restore_at = 1;
uart_quiet_start_at = 0;
#else
(void)replies_drained;
#endif
}
// Temperature from ESP32 MCU
float getMCUTemperature() override {
uint32_t raw = 0;
@@ -152,12 +299,32 @@ public:
bool has_deadline, uint32_t deadline_us) {
using mesh::powerdiag::Reason;
const bool diagnostics = mesh::powerdiag::enabled();
// Preserve native-host signal history even while a test disables sleep.
const bool usb_sleep_held = isUsbSleepHeld();
if (!mesh::esp32::manualCpuSleepEnabled()) {
if (diagnostics) mesh::powerdiag::boardVeto(Reason::PolicyOff, millis());
return;
}
// A temporary UART quiet interval must not sleep past console recovery.
// This only shortens the request and leaves every normal wake guard live.
if (uart_quiet_restore_at) {
const int32_t remaining_ms = static_cast<int32_t>(uart_quiet_restore_at - millis());
if (remaining_ms <= 0) return;
const uint32_t quiet_us = uint32_t(remaining_ms) * 1000UL;
if (has_deadline) {
const uint32_t now_us = micros();
if (static_cast<int32_t>(deadline_us - now_us) > static_cast<int32_t>(quiet_us))
deadline_us = now_us + quiet_us;
} else {
if (!wake_us || wake_us > quiet_us) wake_us = quiet_us;
require_timer = true;
}
}
// Native USB loses its connection in light sleep. An enumerated host
// still needs USB serviced when no terminal asserts CDC DTR (for example,
// after a Pi closes its serial port). Guard every caller here.
// Sample even when another blocker is active, so an open console/OTA does
// not leave the last positive native USB host signal stale.
const bool usb_sleep_held = isUsbSleepHeld();
Reason veto_reason = Reason::Board;
int32_t veto_detail = 1; // Explicit inhibit_sleep.
const auto hold = [&veto_reason, &veto_detail](bool active, Reason reason, int32_t detail = 0) {
@@ -276,7 +443,7 @@ public:
// Keep this immediately before the SDK wait with local interrupts held.
// A short/rejected slice polls instead; it must not reuse an older timer.
const int32_t remaining_us = static_cast<int32_t>(deadline_us - micros());
if (remaining_us < 2000) deadline_expired = true;
if (remaining_us < static_cast<int32_t>(mesh::esp32::profileSleepMinimumMicros())) deadline_expired = true;
else gpio_error = esp_sleep_enable_timer_wakeup(static_cast<uint32_t>(remaining_us));
}
esp_err_t sleep_error = ESP_OK;
+1 -1
View File
@@ -20,7 +20,7 @@ static const char* const WC_ALLOWED_SET_KEYS[] = {
// NodePrefs (radio / node)
"name", "bluetooth.name", "bluetooth.mac", "bluetooth.stealth", "lost.reply",
"lat", "lon", "radio", "tx", "af", "rxdelay", "txdelay",
"cad", "radio.rxgain", "radio.fem.rxgain", "radio.fem.txgain", "radio.rxps", "powersaving",
"cad", "radio.rxgain", "radio.fem.rxgain", "radio.fem.txgain", "radio.rxps", "powersaving", "cpu.freq",
"mcu.regulator", "radio.regulator",
"repeat",
"display.mode", "display.timeout", "display.usb.mode", "display.usb.timeout",
+156
View File
@@ -0,0 +1,156 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
namespace mesh {
namespace esp32 {
namespace cpuclock {
// Zero retains each role's established automatic clock policy. Explicit
// selections are deliberately limited to PLL clocks supported by this UI;
// the board must additionally validate the actual chip/SDK capability.
inline bool validSelection(uint16_t mhz) {
return mhz == 0 || mhz == 80 || mhz == 160 || mhz == 240;
}
inline uint16_t nominalMHz() {
#if defined(ESP32_POST_BOOT_CPU_FREQ)
return ESP32_POST_BOOT_CPU_FREQ;
#elif defined(ESP32_CPU_FREQ)
return ESP32_CPU_FREQ;
#elif defined(F_CPU)
return F_CPU / 1000000UL;
#else
return 80;
#endif
}
inline uint16_t resolveMHz(uint16_t selected, bool powersaving, bool companion) {
if (selected && validSelection(selected)) return selected;
const uint16_t nominal = nominalMHz();
return companion && powersaving && nominal > 80 ? 80 : nominal;
}
static constexpr size_t FooterSize = 8;
inline uint16_t footerChecksum(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 = static_cast<uint16_t>((crc & 0x8000) ? (crc << 1) ^ 0x1021 : crc << 1);
}
return crc;
}
inline void encodeFooter(uint8_t* out, uint16_t selected) {
if (!validSelection(selected)) selected = 0;
out[0] = 'C'; out[1] = 'P'; out[2] = 'U'; out[3] = 1;
out[4] = static_cast<uint8_t>(selected >> 8);
out[5] = static_cast<uint8_t>(selected);
const uint16_t crc = footerChecksum(out, 6);
out[6] = static_cast<uint8_t>(crc >> 8);
out[7] = static_cast<uint8_t>(crc);
}
// A missing, truncated, foreign or corrupt footer always selects Auto, even
// when loading into an object which previously held an explicit selection.
inline bool decodeFooter(const uint8_t* in, size_t length, uint16_t& selected) {
selected = 0;
if (!in || length != FooterSize || in[0] != 'C' || in[1] != 'P'
|| in[2] != 'U' || in[3] != 1) return false;
const uint16_t value = static_cast<uint16_t>((in[4] << 8) | in[5]);
const uint16_t crc = static_cast<uint16_t>((in[6] << 8) | in[7]);
if (!validSelection(value) || footerChecksum(in, 6) != crc) return false;
selected = value;
return true;
}
template <typename File>
uint16_t readFooter(File& file) {
uint16_t selected = 0;
uint8_t bytes[FooterSize] = {};
if (file.size() >= FooterSize && file.seek(file.size() - FooterSize))
decodeFooter(bytes, file.read(bytes, sizeof(bytes)), selected);
return selected;
}
inline bool parseSelection(const char* value, uint16_t& selected) {
if (!value) return false;
while (*value == ' ' || *value == '\t') ++value;
const char* end = value + strlen(value);
while (end > value && (end[-1] == ' ' || end[-1] == '\t')) --end;
const size_t length = static_cast<size_t>(end - value);
if (length == 4 && memcmp(value, "auto", 4) == 0) selected = 0;
else if (length == 2 && memcmp(value, "80", 2) == 0) selected = 80;
else if (length == 3 && memcmp(value, "160", 3) == 0) selected = 160;
else if (length == 3 && memcmp(value, "240", 3) == 0) selected = 240;
else return false;
return true;
}
template <typename Board>
void formatStatus(Board& board, uint16_t selected, char* reply, size_t capacity,
const char* prefix = ">") {
char selection[8] = "auto";
if (selected) snprintf(selection, sizeof(selection), "%u", unsigned(selected));
char supported[24] = "auto";
const uint16_t choices[] = {80, 160, 240};
for (uint16_t mhz : choices) {
if (board.supportsCpuFrequencyMHz(mhz)) {
const size_t used = strlen(supported);
snprintf(supported + used, sizeof(supported) - used, ",%u", unsigned(mhz));
}
}
snprintf(reply, capacity, "%s selected=%s actual=%uMHz supported=%s", prefix,
selection, unsigned(board.getCpuFrequencyMHz()), supported);
}
template <typename Board, typename Save>
bool handleCommand(Board& board, uint16_t& selected, bool powersaving,
const char* command, char* reply, size_t capacity, Save save) {
if (!command || !reply || !capacity) return false;
const bool get = strncmp(command, "get cpu.freq", 12) == 0;
const bool set = strncmp(command, "set cpu.freq", 12) == 0;
if ((!get && !set) || (command[12] && command[12] != ' ' && command[12] != '\t'))
return false;
const char* value = command + 12;
while (*value == ' ' || *value == '\t') ++value;
if (get) {
if (*value) snprintf(reply, capacity, "Error: usage get cpu.freq");
else formatStatus(board, selected, reply, capacity);
return true;
}
uint16_t wanted = 0;
if (!parseSelection(value, wanted)) {
snprintf(reply, capacity, "Error: use set cpu.freq auto|80|160|240");
return true;
}
if (wanted && !board.supportsCpuFrequencyMHz(wanted)) {
snprintf(reply, capacity, "Error: unsupported CPU clock; use get cpu.freq");
return true;
}
const uint16_t previous = selected;
selected = wanted;
if (!board.applyCpuFrequencyMHz(wanted, powersaving)) {
selected = previous;
const bool restored = board.applyCpuFrequencyMHz(previous, powersaving);
snprintf(reply, capacity, restored ? "Error: CPU clock apply failed; unchanged"
: "Error: CPU clock apply and restore failed; check get cpu.freq");
} else if (!save()) {
selected = previous;
const bool restored = board.applyCpuFrequencyMHz(previous, powersaving);
snprintf(reply, capacity, restored ? "Error: CPU clock save failed; restored"
: "Error: CPU clock save and restore failed; check get cpu.freq");
} else {
formatStatus(board, selected, reply, capacity, "OK - saved");
}
return true;
}
} // namespace cpuclock
} // namespace esp32
} // namespace mesh
+146
View File
@@ -0,0 +1,146 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
namespace mesh {
namespace esp32 {
// Local experiments only. Nothing here is persisted; reboot restores the
// production policy. RF parameters and calibration settling are unchanged.
struct PowerTestControls {
bool sleep_enabled = true;
uint8_t slice_ms = 10;
uint8_t guard_ms = 4;
uint8_t minimum_ms = 2;
uint8_t settle_ms = 0; // zero selects the radio family's normal idle settle
};
inline PowerTestControls& powerTestControls() {
static PowerTestControls value;
return value;
}
enum class UartQuietAction : uint8_t { Status, Schedule, Cancel };
using UartQuietHandler = bool (*)(void*, UartQuietAction, uint16_t, char*, size_t);
struct UartQuietControl {
void* owner = nullptr;
UartQuietHandler handle = nullptr;
};
inline UartQuietControl& uartQuietControl() {
static UartQuietControl value;
return value;
}
inline void registerUartQuietControl(void* owner, UartQuietHandler handle) {
uartQuietControl().owner = owner;
uartQuietControl().handle = handle;
}
inline bool manualCpuSleepEnabled() { return powerTestControls().sleep_enabled; }
inline uint32_t profileSleepSliceMillis() { return powerTestControls().slice_ms; }
inline uint32_t profileSleepGuardMicros() { return uint32_t(powerTestControls().guard_ms) * 1000; }
inline uint32_t profileSleepMinimumMicros() { return uint32_t(powerTestControls().minimum_ms) * 1000; }
inline uint32_t profileSleepSettleMillis(uint32_t normal) {
return powerTestControls().settle_ms ? powerTestControls().settle_ms : normal;
}
// Infrastructure has no Bluetooth modem policy, but must honor a saved CPU
// choice at boot and after preference changes without reconfiguring each loop.
template <typename Board>
bool serviceCpuFrequencyPolicy(Board& board, uint16_t selected, bool powersaving,
uint32_t now_ms, bool force = false) {
struct State {
uint16_t selected = UINT16_MAX;
bool powersaving = false;
uint32_t retry_at = 0;
};
static State state;
if (!force && state.selected == selected && state.powersaving == powersaving) return true;
if (!force && state.retry_at && static_cast<int32_t>(now_ms - state.retry_at) < 0) return false;
if (!board.applyCpuFrequencyMHz(selected, powersaving)) {
state.retry_at = now_ms + 5000;
if (!state.retry_at) state.retry_at = 1;
return false;
}
state.selected = selected;
state.powersaving = powersaving;
state.retry_at = 0;
return true;
}
inline bool powerTestNumber(const char* text, uint16_t minimum, uint16_t maximum, uint16_t& output) {
if (!text || !*text) return false;
uint32_t value = 0;
for (const char* p = text; *p; ++p) {
if (*p < '0' || *p > '9') return false;
value = value * 10 + unsigned(*p - '0');
if (value > maximum) return false;
}
if (value < minimum) return false;
output = uint16_t(value);
return true;
}
inline void formatPowerTestControls(char* reply, size_t capacity) {
const auto& value = powerTestControls();
char settle[8], uart[48] = "uart=unsupported";
if (value.settle_ms) snprintf(settle, sizeof(settle), "%u", unsigned(value.settle_ms));
else strcpy(settle, "auto");
const auto& quiet = uartQuietControl();
if (quiet.handle) quiet.handle(quiet.owner, UartQuietAction::Status, 0, uart, sizeof(uart));
snprintf(reply, capacity, "sleep=%s slice_ms=%u guard_ms=%u min_ms=%u settle_ms=%s %s; RAM only",
value.sleep_enabled ? "on" : "off", unsigned(value.slice_ms), unsigned(value.guard_ms),
unsigned(value.minimum_ms), settle, uart);
}
inline bool handlePowerTestCommand(const char* command, char* reply, size_t capacity, bool local) {
const bool get = strcmp(command, "get powersaving.test") == 0;
const char* arguments = strncmp(command, "set powersaving.test ", 21) == 0 ? command + 21 : nullptr;
if (!get && !arguments && strcmp(command, "set powersaving.test") != 0) return false;
if (!local) {
snprintf(reply, capacity, "Error: powersaving.test is local only");
return true;
}
if (get) { formatPowerTestControls(reply, capacity); return true; }
auto& value = powerTestControls();
if (arguments && strcmp(arguments, "reset") == 0) {
const auto& quiet = uartQuietControl();
if (quiet.handle && !quiet.handle(quiet.owner, UartQuietAction::Cancel, 0, reply, capacity)) return true;
value = PowerTestControls();
} else if (arguments && (strcmp(arguments, "sleep on") == 0 || strcmp(arguments, "sleep off") == 0)) {
value.sleep_enabled = strcmp(arguments, "sleep on") == 0;
} else if (arguments && strncmp(arguments, "uart_quiet ", 11) == 0) {
const auto& quiet = uartQuietControl();
uint16_t seconds = 0;
const bool cancel = strcmp(arguments + 11, "off") == 0;
if (!cancel && !powerTestNumber(arguments + 11, 5, 300, seconds)) {
snprintf(reply, capacity, "Error: uart_quiet requires 5..300 seconds or off"); return true;
}
if (!quiet.handle) snprintf(reply, capacity, "Error: UART quiet is unsupported");
else quiet.handle(quiet.owner, cancel ? UartQuietAction::Cancel : UartQuietAction::Schedule,
seconds, reply, capacity);
return true;
} else {
uint16_t number = 0;
if (arguments && strncmp(arguments, "slice_ms ", 9) == 0
&& powerTestNumber(arguments + 9, 2, 20, number)) value.slice_ms = uint8_t(number);
else if (arguments && strncmp(arguments, "guard_ms ", 9) == 0
&& powerTestNumber(arguments + 9, 0, 20, number)) value.guard_ms = uint8_t(number);
else if (arguments && strncmp(arguments, "min_ms ", 7) == 0
&& powerTestNumber(arguments + 7, 1, 10, number)) value.minimum_ms = uint8_t(number);
else if (arguments && strcmp(arguments, "settle_ms auto") == 0) value.settle_ms = 0;
else if (arguments && strncmp(arguments, "settle_ms ", 10) == 0
&& powerTestNumber(arguments + 10, 1, 50, number)) value.settle_ms = uint8_t(number);
else {
snprintf(reply, capacity, "Error: use sleep on|off, slice_ms 2..20, guard_ms 0..20, min_ms 1..10, settle_ms auto|1..50, uart_quiet 5..300|off, reset");
return true;
}
}
formatPowerTestControls(reply, capacity);
return true;
}
} // namespace esp32
} // namespace mesh
+6 -3
View File
@@ -2,6 +2,7 @@
#include <stdint.h>
#include <esp_timer.h>
#include "PowerTestControls.h"
namespace mesh {
namespace esp32 {
@@ -13,16 +14,18 @@ namespace esp32 {
template <typename Mesh, typename Board>
bool tryProfileIdleSleep(Mesh& mesh, Board& board,
uint32_t budget_started_us, uint32_t budget_ms) {
if (budget_ms == 0 || budget_ms > 0x7fffffffUL / 1000UL) return false;
if (!manualCpuSleepEnabled() || budget_ms == 0 || budget_ms > 0x7fffffffUL / 1000UL) return false;
const uint32_t observed_us = static_cast<uint32_t>(esp_timer_get_time());
uint32_t profile_ms = 0;
if (!mesh.getDualRadioIdleDelay(profile_ms) || profile_ms < 2 || profile_ms > 10)
const uint32_t minimum_us = profileSleepMinimumMicros();
if (!mesh.getDualRadioIdleDelay(profile_ms) || profile_ms * 1000UL < minimum_us
|| profile_ms > profileSleepSliceMillis())
return false;
const uint32_t role_deadline = budget_started_us + budget_ms * 1000UL;
const int32_t role_remaining_us = static_cast<int32_t>(role_deadline - observed_us);
if (role_remaining_us < 2000) return false;
if (role_remaining_us < static_cast<int32_t>(minimum_us)) return false;
const uint32_t profile_us = profile_ms * 1000UL;
const uint32_t remaining_us = static_cast<uint32_t>(role_remaining_us) < profile_us
File diff suppressed because it is too large. Load diff
+10
View File
@@ -2374,6 +2374,16 @@ void WebConfigServer::handleConfigGet(AsyncWebServerRequest* req) {
radio["rxps_rx_us"] = node.rx_ps_rx_us;
radio["rxps_sleep_us"] = node.rx_ps_sleep_us;
radio["powersaving"] = (bool)node.power_saving;
if (node.cpu_supported_mask & 7U) {
JsonObject cpu = doc.createNestedObject("cpu");
cpu["selected_mhz"] = node.cpu_freq_mhz;
cpu["actual_mhz"] = node.cpu_actual_mhz;
JsonArray supported = cpu.createNestedArray("supported_mhz");
static const uint16_t frequencies[] = {80, 160, 240};
for (unsigned i = 0; i < 3; ++i) {
if (node.cpu_supported_mask & (1U << i)) supported.add(frequencies[i]);
}
}
#ifdef MESHCORE_HAS_REAL_DISPLAY
JsonObject screen = doc["display"].to<JsonObject>();
const auto& display_prefs = mesh::ui::displayPowerPrefs();
+3
View File
@@ -130,6 +130,9 @@ public:
uint32_t rx_ps_rx_us;
uint32_t rx_ps_sleep_us;
uint8_t power_saving;
uint16_t cpu_freq_mhz; // 0 = automatic device policy
uint16_t cpu_actual_mhz;
uint8_t cpu_supported_mask; // bits 0/1/2 = 80/160/240 MHz
bool display_rotation_supported;
uint16_t display_rotation_degrees;
bool mqtt_enabled;
+6 -4
View File
@@ -11,6 +11,7 @@
#include <esp_heap_caps.h>
#include <esp_timer.h>
#include <driver/gpio.h>
#include "../esp32/PowerTestControls.h"
#elif defined(NRF52_PLATFORM)
#include <utility/debug.h>
#include "../NRF52Board.h"
@@ -1089,18 +1090,19 @@ bool RadioLibWrapper::getProfileIdleDelay(uint32_t& delay_ms) const {
const uint64_t elapsed_us = now_us - _esp32_profile_idle_stamp_us;
// Keep frontend settling and short visits on their polling path. Only the
// MCU idles; the RF receiver stays in continuous RX on the current profile.
if (elapsed_us < NoiseFloorSettleMillis * 1000UL
if (elapsed_us < mesh::esp32::profileSleepSettleMillis(NoiseFloorSettleMillis) * 1000UL
|| elapsed_us >= _esp32_profile_idle_visit_us) return false;
const uint32_t remaining_us = _esp32_profile_idle_visit_us - static_cast<uint32_t>(elapsed_us);
// Reserve return-to-loop/wake latency and require a useful timer interval.
// These bounds are a conservative policy, not a measured latency guarantee.
// The caller anchors this budget to an absolute ESP Timer deadline before
// querying it and checks that deadline again immediately before sleeping.
constexpr uint32_t wake_guard_us = 4000;
constexpr uint32_t minimum_idle_us = 2000;
const uint32_t wake_guard_us = mesh::esp32::profileSleepGuardMicros();
const uint32_t minimum_idle_us = mesh::esp32::profileSleepMinimumMicros();
if (remaining_us < wake_guard_us + minimum_idle_us) return false;
delay_ms = (remaining_us - wake_guard_us) / 1000;
if (delay_ms > 10) delay_ms = 10;
if (delay_ms > mesh::esp32::profileSleepSliceMillis())
delay_ms = mesh::esp32::profileSleepSliceMillis();
return true;
#else
return false; // Other platforms retain polling until their wake path is validated.