Enable reversible ESP32 BLE shutdown and bounded radio2 CPU sleep

This commit is contained in:
mikecarper committed 2026-10-21 17:53:57 -07:00
1 parent a3d77a9a76
commit 61eecbd971
38 files changed
+1829 -117

No files matched your search

+12
View File
@@ -663,6 +663,18 @@ public:
return radio_available && _radio->getProfileIdleDelay(delay_millis)
&& delay_millis > 0;
}
// A timed-sleep caller must use the remaining visit budget, not just the
// boolean admission. Single-profile radios retain their existing policy.
// Read the sleep clock before calling, cap the caller's absolute deadline,
// and fail closed if setup/preemption consumes that budget before sleeping.
bool getDualRadioIdleDelay(uint32_t& delay_millis) const {
delay_millis = 0;
uint32_t profile_millis = 0;
if (!isDualRadioActive() || !radio_available
|| !_radio->getProfileIdleDelay(profile_millis) || !profile_millis) return false;
delay_millis = profile_millis;
return true;
}
Packet* obtainNewPacket();
void releasePacket(Packet* packet);
+55 -13
View File
@@ -20,6 +20,7 @@
#include "UsbLogging.h"
#include "UsbHostSleepPolicy.h"
#include "PowerSavingDiagnostics.h"
#include "esp32/LightSleepPolicy.h"
#if defined(STATION_G3_ESP32)
#include <StationG3RadioSlot.h>
#endif
@@ -137,6 +138,18 @@ public:
}
void sleepMicroseconds(uint64_t wake_us, bool require_timer = false) {
sleepMicrosecondsImpl(wake_us, require_timer, false, 0);
}
// Radio-profile visits use the low 32 bits of esp_timer_get_time()/micros().
// An absolute deadline prevents setup work or a task preemption from making
// the sleep slice outlast the visit which the scanner proved safe.
void sleepUntilMicroseconds(uint32_t deadline_us) {
sleepMicrosecondsImpl(0, true, true, deadline_us);
}
void sleepMicrosecondsImpl(uint64_t wake_us, bool require_timer,
bool has_deadline, uint32_t deadline_us) {
using mesh::powerdiag::Reason;
const bool diagnostics = mesh::powerdiag::enabled();
// Native USB loses its connection in light sleep. An enumerated host
@@ -166,9 +179,13 @@ public:
// it and across host disconnects. Compiled-out logging is not a blocker.
keep_awake = keep_awake || hold(mesh::isUsbLoggingEnabled(), Reason::UsbLogging);
#endif
if (!keep_awake) {
const Reason wireless = mesh::esp32::manualLightSleepBlocker();
keep_awake = hold(wireless != Reason::Count, wireless);
}
if (keep_awake) {
if (diagnostics) mesh::powerdiag::boardVeto(veto_reason, millis(), veto_detail);
delay(1); // Keep USB and OTA tasks running.
if (!has_deadline) delay(1); // A bounded profile visit must retain polling.
return;
}
@@ -176,7 +193,7 @@ public:
// Otherwise its real elapsed time would be mislabelled as blocked time.
esp_err_t setup_error = ESP_OK;
// Configure timer wakeup
if (wake_us > 0) {
if (!has_deadline && wake_us > 0) {
const esp_err_t error = esp_sleep_enable_timer_wakeup(wake_us);
// A calibration slice must not inherit an old, longer timer after a
// setup failure. Keep the legacy seconds API's policy unchanged.
@@ -189,6 +206,11 @@ public:
const uint32_t irqGpio = getIRQGpio();
const bool radio_wakeup = irqGpio != static_cast<uint32_t>(-1);
if (has_deadline && !radio_wakeup) {
// A timer-only wake cannot service a newly arrived profile packet.
if (diagnostics) mesh::powerdiag::boardVeto(Reason::NoWake, millis());
return;
}
#if defined(MOMENTARY_BUTTON_WAKE_FROM_SLEEP) \
&& MOMENTARY_BUTTON_WAKE_FROM_SLEEP && defined(PIN_USER_BTN)
const int button_gpio = PIN_USER_BTN;
@@ -225,28 +247,43 @@ public:
if (diagnostics) mesh::powerdiag::boardVeto(
radio_pending ? Reason::Mesh : Reason::Button, millis(),
radio_pending ? static_cast<int32_t>(irqGpio) : button_gpio);
delay(1);
if (!has_deadline) delay(1);
return;
}
// Configure GPIO wakeup
const esp_err_t gpio_error = esp_sleep_enable_gpio_wakeup();
if (diagnostics && setup_error == ESP_OK && gpio_error != ESP_OK) setup_error = gpio_error;
// Configure each level source before enabling global GPIO wake. Setup
// errors must veto sleep even with diagnostics off: a timer alone cannot
// replace the pending radio/button event which this caller must service.
esp_err_t gpio_error = ESP_OK;
if (radio_wakeup) {
const esp_err_t error = gpio_wakeup_enable(wakeupPin, GPIO_INTR_HIGH_LEVEL);
if (diagnostics && setup_error == ESP_OK && error != ESP_OK) setup_error = error;
if (error != ESP_OK) gpio_error = error;
}
if (button_gpio >= 0) {
const esp_err_t error = gpio_wakeup_enable((gpio_num_t)button_gpio,
USER_BTN_PRESSED == LOW ? GPIO_INTR_LOW_LEVEL : GPIO_INTR_HIGH_LEVEL);
if (diagnostics && setup_error == ESP_OK && error != ESP_OK) setup_error = error;
if (gpio_error == ESP_OK && error != ESP_OK) gpio_error = error;
}
if (gpio_error == ESP_OK) gpio_error = esp_sleep_enable_gpio_wakeup();
// MCU enters light sleep
if (diagnostics) mesh::powerdiag::sleepBegin(micros());
const esp_err_t sleep_error = esp_light_sleep_start();
if (diagnostics) {
mesh::powerdiag::sleepEnd(micros());
// The level source also catches an IRQ asserted while configuring wake.
// Avoid entering the SDK at all if its pending state is already visible.
const bool pending_after_setup = (radio_wakeup && gpio_get_level(wakeupPin) == HIGH)
|| (button_gpio >= 0
&& gpio_get_level((gpio_num_t)button_gpio) == USER_BTN_PRESSED);
bool deadline_expired = false;
if (has_deadline && gpio_error == ESP_OK && !pending_after_setup) {
// 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;
else gpio_error = esp_sleep_enable_timer_wakeup(static_cast<uint32_t>(remaining_us));
}
esp_err_t sleep_error = ESP_OK;
if (gpio_error == ESP_OK && !pending_after_setup && !deadline_expired) {
if (diagnostics) mesh::powerdiag::sleepBegin(micros());
sleep_error = esp_light_sleep_start();
if (diagnostics) mesh::powerdiag::sleepEnd(micros());
}
// Avoid ISR flood during wakeup due to HIGH LEVEL interrupt
@@ -264,7 +301,12 @@ public:
portEXIT_CRITICAL(&sleepMux);
if (diagnostics) {
if (setup_error != ESP_OK) mesh::powerdiag::boardError(setup_error, millis());
if (gpio_error != ESP_OK) mesh::powerdiag::boardError(gpio_error, millis());
if (sleep_error != ESP_OK) mesh::powerdiag::boardError(sleep_error, millis());
if (pending_after_setup) mesh::powerdiag::boardVeto(
radio_wakeup && gpio_get_level(wakeupPin) == HIGH ? Reason::Mesh : Reason::Button,
millis());
if (deadline_expired) mesh::powerdiag::boardVeto(Reason::Scheduled, millis());
}
}
+50
View File
@@ -0,0 +1,50 @@
#pragma once
#include <esp_wifi.h>
#include <helpers/PowerSavingDiagnostics.h>
#if defined(CONFIG_BT_ENABLED) && CONFIG_BT_ENABLED
#include <esp_bt.h>
#if defined(CONFIG_BLUEDROID_ENABLED) && CONFIG_BLUEDROID_ENABLED \
&& !defined(MESH_USE_NIMBLE_ARDUINO)
#include <esp_bt_main.h>
#endif
#endif
namespace mesh {
namespace esp32 {
// Explicit light sleep powers down the WiFi/Bluetooth peripheral, even when
// its connections are idle. Only automatic SDK sleep can preserve an active
// driver. Read the physical drivers: a logical service-off flag can precede
// asynchronous teardown, and ESP-NOW may own WiFi without Arduino's facade.
inline powerdiag::Reason manualLightSleepBlocker() {
#if defined(CONFIG_BT_ENABLED) && CONFIG_BT_ENABLED
const esp_bt_controller_status_t controller = esp_bt_controller_get_status();
if (controller != ESP_BT_CONTROLLER_STATUS_IDLE
&& controller != ESP_BT_CONTROLLER_STATUS_INITED)
return powerdiag::Reason::Wireless;
#if defined(CONFIG_BLUEDROID_ENABLED) && CONFIG_BLUEDROID_ENABLED \
&& !defined(MESH_USE_NIMBLE_ARDUINO)
const esp_bluedroid_status_t host = esp_bluedroid_get_status();
if (host != ESP_BLUEDROID_STATUS_UNINITIALIZED
&& host != ESP_BLUEDROID_STATUS_INITIALIZED)
return powerdiag::Reason::Wireless;
#endif
#endif
wifi_mode_t mode = WIFI_MODE_NULL;
const esp_err_t result = esp_wifi_get_mode(&mode);
if (result == ESP_OK)
return mode == WIFI_MODE_NULL ? powerdiag::Reason::Count
: powerdiag::Reason::Network;
if (result == ESP_ERR_WIFI_NOT_INIT || result == ESP_ERR_WIFI_NOT_STARTED)
return powerdiag::Reason::Count;
return powerdiag::Reason::Network; // An unknown driver state is not off.
}
inline bool manualLightSleepReady() {
return manualLightSleepBlocker() == powerdiag::Reason::Count;
}
} // namespace esp32
} // namespace mesh
+35
View File
@@ -0,0 +1,35 @@
#pragma once
#include <stdint.h>
#include <esp_timer.h>
namespace mesh {
namespace esp32 {
// Preserve both the role's original wake deadline and the scanner's late
// admission. The board checks this absolute deadline again after configuring
// wake sources, so preemption cannot turn a short visit into a longer sleep.
// True means a board sleep was attempted, not proof that the SDK slept.
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;
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)
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;
const uint32_t profile_us = profile_ms * 1000UL;
const uint32_t remaining_us = static_cast<uint32_t>(role_remaining_us) < profile_us
? static_cast<uint32_t>(role_remaining_us) : profile_us;
board.sleepUntilMicroseconds(observed_us + remaining_us);
return true;
}
} // namespace esp32
} // namespace mesh
+247 -51
View File
@@ -2,12 +2,15 @@
#include "../BluetoothMac.h"
#include "../CompanionFrameQueue.h"
#include "esp_mac.h"
#include "esp_bt.h"
#include <stdlib.h>
#if defined(CONFIG_BLUEDROID_ENABLED) && !defined(MESH_USE_NIMBLE_ARDUINO)
#include "esp_gap_ble_api.h"
#include "esp_bt_main.h"
#endif
#if MESH_BLE_USES_NIMBLE && !defined(MESH_USE_NIMBLE_ARDUINO)
#include <host/ble_store.h>
#include <nimble/nimble_port.h>
#endif
// Arduino 3.x relies on a library constructor to mark BLE as used before
@@ -29,12 +32,83 @@ extern "C" bool bleInUse(void) {
#define ADVERT_RESTART_DELAY 1000 // millis
#define BLE_BOND_PERSIST_TIMEOUT_MS 15000
static void cleanupFailedBluetoothStart() {
#if defined(MESH_USE_NIMBLE_ARDUINO)
BLEDevice::deinit(true);
#else
BLEDevice::deinit(false);
#define BLE_POWER_RETRY_MS 1000
static bool stopBluetoothController() {
if (esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_ENABLED
&& esp_bt_controller_disable() != ESP_OK) return false;
if (esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_INITED
&& esp_bt_controller_deinit() != ESP_OK) return false;
return esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_IDLE;
}
#if !defined(MESH_USE_NIMBLE_ARDUINO)
// The pinned 2.0.17/3.1.3 wrappers leave their static server/advertiser alive
// on deinit(false). The newer wrapper exposing getServer() deletes them.
// Keep that ownership distinction independent of the processor model.
template <typename Device>
static auto bluetoothLibraryOwnsServer(int)
-> decltype(Device::getServer(), bool()) { return true; }
template <typename Device>
static bool bluetoothLibraryOwnsServer(...) { return false; }
#endif
void SerialBLEInterface::forgetGattPointers() {
pServer = NULL;
pService = NULL;
pTxCharacteristic = NULL;
pRxCharacteristic = NULL;
#if !defined(MESH_USE_NIMBLE_ARDUINO)
pTxDescriptor = NULL;
#endif
}
bool SerialBLEInterface::stopBluetoothStack() {
_callbacksEnabled.store(false, std::memory_order_release);
#if defined(MESH_USE_NIMBLE_ARDUINO)
// clearAll is OBJECT ownership, not bond storage. Stop first without
// deleting objects: a failed stop must leave callback targets valid.
if (!BLEDevice::deinit(false)) return false;
if (!stopBluetoothController()) return false;
BLEDevice::deinit(true);
forgetGattPointers();
_advertisingConfigured = false;
#else
#if defined(CONFIG_BLUEDROID_ENABLED)
// Stop callback dispatch before the newer wrapper deletes its server.
// Never release controller memory: Bluetooth on must work in this boot.
if (esp_bluedroid_get_status() == ESP_BLUEDROID_STATUS_ENABLED
&& esp_bluedroid_disable() != ESP_OK) return false;
if (esp_bluedroid_get_status() == ESP_BLUEDROID_STATUS_INITIALIZED
&& esp_bluedroid_deinit() != ESP_OK) return false;
#elif defined(CONFIG_NIMBLE_ENABLED)
if (!_nativeHostStopped) {
if (nimble_port_stop() != 0) return false;
_nativeHostStopped = true;
}
#endif
#if defined(CONFIG_BLUEDROID_ENABLED)
if (!stopBluetoothController()) return false;
#endif
const bool owns_server = bluetoothLibraryOwnsServer<BLEDevice>(0);
BLEDevice::deinit(false);
// Neither pinned Arduino wrapper owns our characteristics/service. The
// legacy server is retained until createServer() replaces its static
// pointer; deleting it sooner would leave a dangling callback target.
delete pTxDescriptor;
delete pRxCharacteristic;
delete pTxCharacteristic;
delete pService;
pTxDescriptor = NULL;
pRxCharacteristic = pTxCharacteristic = NULL;
pService = NULL;
if (owns_server) {
pServer = NULL;
_advertisingConfigured = false;
}
if (!stopBluetoothController()) return false;
#endif
return true;
}
#if !defined(MESH_USE_NIMBLE_ARDUINO)
@@ -276,6 +350,8 @@ bool SerialBLEInterface::configureBondedOnlyAdvertising(
advertising->setAdvertisementData(minimal_advertisement);
_bonded_only = true;
_bondedPeer = peer;
_hasBondedPeer = true;
_stealth_pair_once = false;
_advertisingSuppressed.store(false, std::memory_order_release);
_adv_restart_pending = false;
@@ -310,7 +386,9 @@ bool SerialBLEInterface::begin(const char* prefix, const char* name,
bool clear_bonds, bool stealth_pair_once,
const mesh::companion::BluetoothPeerIdentity*
bonded_only_peer) {
if (_stackActive || _shutdownPending) return false;
_pin_code = pin_code;
_hasBondedPeer = false;
_successfulConnectionPending.store(false, std::memory_order_release);
_successfulConnectionStarted.store(0, std::memory_order_relaxed);
_bondedOnlyRecoveryPending.store(false, std::memory_order_release);
@@ -344,22 +422,58 @@ bool SerialBLEInterface::begin(const char* prefix, const char* name,
return false;
}
memcpy(_deviceName, dev_name, dev_name_len + 1);
_hasCustomAddress = custom_address != nullptr;
if (_hasCustomAddress) {
memcpy(_customAddress, custom_address, sizeof(_customAddress));
}
if (bonded_only_peer != nullptr) {
_bondedPeer = *bonded_only_peer;
_hasBondedPeer = true;
_bonded_only = true;
}
_configured = true;
if (startBluetoothStack(clear_bonds)) return true;
servicePowerState();
return false;
}
bool SerialBLEInterface::startBluetoothStack(bool clear_bonds) {
const char* dev_name = _deviceName;
const uint8_t* custom_address = _hasCustomAddress ? _customAddress : nullptr;
const uint32_t pin_code = _pin_code;
// A failed start can have partially initialized the controller. Keep the
// shutdown gate closed until servicePowerState() has cleaned it up.
_stackActive = true;
_nativeHostStopped = false;
_callbacksEnabled.store(false, std::memory_order_release);
// Create the BLE Device
#if MESH_BLE_USES_NIMBLE
if (!BLEDevice::init(dev_name)) {
BLE_DEBUG_PRINTLN("BLEDevice::init failed");
_isEnabled = _enableRequested = false;
_shutdownPending = true;
return false;
}
#else
// Arduino-ESP32 2.x Bluedroid exposes a void init(). Its first observable
// failure is a null server below, which is handled without dereferencing it.
BLEDevice::init(dev_name);
#if defined(CONFIG_BLUEDROID_ENABLED)
if (esp_bt_controller_get_status() != ESP_BT_CONTROLLER_STATUS_ENABLED
|| esp_bluedroid_get_status() != ESP_BLUEDROID_STATUS_ENABLED) {
_isEnabled = _enableRequested = false;
_shutdownPending = true;
return false;
}
#endif
#endif
#if defined(MESH_USE_NIMBLE_ARDUINO)
if (clear_bonds && !BLEDevice::deleteAllBonds()) {
BLE_DEBUG_PRINTLN("Could not clear NimBLE bonds for the new identity");
cleanupFailedBluetoothStart();
_isEnabled = _enableRequested = false;
_shutdownPending = true;
return false;
}
#else
@@ -376,13 +490,15 @@ bool SerialBLEInterface::begin(const char* prefix, const char* name,
if (!BLEDevice::setOwnAddr(native_address)
|| !BLEDevice::setOwnAddrType(BLE_OWN_ADDR_RANDOM)) {
BLE_DEBUG_PRINTLN("Custom Bluetooth MAC setup failed");
cleanupFailedBluetoothStart();
_isEnabled = _enableRequested = false;
_shutdownPending = true;
return false;
}
}
#if defined(MESH_USE_NIMBLE_ARDUINO)
else if (!BLEDevice::setOwnAddrType(BLE_OWN_ADDR_PUBLIC)) {
cleanupFailedBluetoothStart();
_isEnabled = _enableRequested = false;
_shutdownPending = true;
return false;
}
#endif
@@ -424,10 +540,19 @@ bool SerialBLEInterface::begin(const char* prefix, const char* name,
//BLEDevice::setPower(ESP_PWR_LVL_N8);
// Create the BLE Server
#if !defined(MESH_USE_NIMBLE_ARDUINO)
BLEServer* retired_server = pServer;
#endif
pServer = BLEDevice::createServer();
#if !defined(MESH_USE_NIMBLE_ARDUINO)
// createServer has replaced the legacy library's static callback pointer.
// Its old server can now be freed, without ever exposing a dangling one.
delete retired_server;
#endif
if (pServer == NULL) {
BLE_DEBUG_PRINTLN("BLEDevice::createServer failed");
cleanupFailedBluetoothStart();
_isEnabled = _enableRequested = false;
_shutdownPending = true;
return false;
}
#if defined(MESH_USE_NIMBLE_ARDUINO)
@@ -454,8 +579,8 @@ bool SerialBLEInterface::begin(const char* prefix, const char* name,
pService = pServer->createService(SERVICE_UUID);
if (pService == NULL) {
BLE_DEBUG_PRINTLN("BLEServer::createService failed");
cleanupFailedBluetoothStart();
pServer = NULL;
_isEnabled = _enableRequested = false;
_shutdownPending = true;
return false;
}
@@ -479,9 +604,8 @@ bool SerialBLEInterface::begin(const char* prefix, const char* name,
CHARACTERISTIC_UUID_TX, tx_properties);
if (pTxCharacteristic == NULL) {
BLE_DEBUG_PRINTLN("BLEService::createCharacteristic(TX) failed");
cleanupFailedBluetoothStart();
pServer = NULL;
pService = NULL;
_isEnabled = _enableRequested = false;
_shutdownPending = true;
return false;
}
#if !defined(MESH_USE_NIMBLE_ARDUINO)
@@ -500,17 +624,12 @@ bool SerialBLEInterface::begin(const char* prefix, const char* name,
pTxCharacteristic->addDescriptor(pTxDescriptor);
#endif
BLECharacteristic * pRxCharacteristic = pService->createCharacteristic(
pRxCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID_RX, rx_properties);
if (pRxCharacteristic == NULL) {
BLE_DEBUG_PRINTLN("BLEService::createCharacteristic(RX) failed");
cleanupFailedBluetoothStart();
pServer = NULL;
pService = NULL;
pTxCharacteristic = NULL;
#if !defined(MESH_USE_NIMBLE_ARDUINO)
pTxDescriptor = NULL;
#endif
_isEnabled = _enableRequested = false;
_shutdownPending = true;
return false;
}
#if !defined(MESH_USE_NIMBLE_ARDUINO)
@@ -522,10 +641,16 @@ bool SerialBLEInterface::begin(const char* prefix, const char* name,
pServer->getAdvertising()->setName(dev_name);
pServer->getAdvertising()->enableScanResponse(true);
#endif
pServer->getAdvertising()->addServiceUUID(SERVICE_UUID);
if (bonded_only_peer != nullptr) {
configureBondedOnlyAdvertising(*bonded_only_peer, true);
if (!_advertisingConfigured) {
pServer->getAdvertising()->addServiceUUID(SERVICE_UUID);
_advertisingConfigured = true;
}
if (_bonded_only && _hasBondedPeer) {
const bool suppressed = _advertisingSuppressed.load(std::memory_order_acquire);
configureBondedOnlyAdvertising(_bondedPeer, true);
if (suppressed) _advertisingSuppressed.store(true, std::memory_order_release);
}
_callbacksEnabled.store(true, std::memory_order_release);
return true;
}
@@ -533,11 +658,13 @@ bool SerialBLEInterface::begin(const char* prefix, const char* name,
#if defined(MESH_USE_NIMBLE_ARDUINO)
uint32_t SerialBLEInterface::onPassKeyDisplay() {
if (!_callbacksEnabled.load(std::memory_order_acquire)) return _pin_code;
_pairingRequestPending.store(true, std::memory_order_release);
return _pin_code;
}
void SerialBLEInterface::onAuthenticationComplete(NimBLEConnInfo& info) {
if (!_callbacksEnabled.load(std::memory_order_acquire)) return;
if (pServer == NULL || pServer->getConnectedCount() == 0
|| info.getConnHandle() != last_conn_id) return;
if (info.isEncrypted() && info.isAuthenticated() && info.isBonded()) {
@@ -562,17 +689,20 @@ void SerialBLEInterface::onAuthenticationComplete(NimBLEConnInfo& info) {
}
#else
uint32_t SerialBLEInterface::onPassKeyRequest() {
if (!_callbacksEnabled.load(std::memory_order_acquire)) return _pin_code;
BLE_DEBUG_PRINTLN("onPassKeyRequest()");
_pairingRequestPending.store(true, std::memory_order_release);
return _pin_code;
}
void SerialBLEInterface::onPassKeyNotify(uint32_t pass_key) {
if (!_callbacksEnabled.load(std::memory_order_acquire)) return;
BLE_DEBUG_PRINTLN("onPassKeyNotify(%u)", pass_key);
_pairingRequestPending.store(true, std::memory_order_release);
}
bool SerialBLEInterface::onConfirmPIN(uint32_t pass_key) {
if (!_callbacksEnabled.load(std::memory_order_acquire)) return false;
BLE_DEBUG_PRINTLN("onConfirmPIN(%u)", pass_key);
_pairingRequestPending.store(true, std::memory_order_release);
return true;
@@ -580,11 +710,12 @@ bool SerialBLEInterface::onConfirmPIN(uint32_t pass_key) {
bool SerialBLEInterface::onSecurityRequest() {
BLE_DEBUG_PRINTLN("onSecurityRequest()");
return true; // allow
return _callbacksEnabled.load(std::memory_order_acquire);
}
#if MESH_BLE_USES_NIMBLE
void SerialBLEInterface::onAuthenticationComplete(ble_gap_conn_desc* desc) {
if (!_callbacksEnabled.load(std::memory_order_acquire)) return;
const bool success = desc != NULL && desc->sec_state.encrypted &&
desc->sec_state.authenticated
&& desc->sec_state.bonded;
@@ -621,6 +752,7 @@ void SerialBLEInterface::onAuthenticationComplete(ble_gap_conn_desc* desc) {
}
#else
void SerialBLEInterface::onAuthenticationComplete(esp_ble_auth_cmpl_t cmpl) {
if (!_callbacksEnabled.load(std::memory_order_acquire)) return;
if (cmpl.success) {
BLE_DEBUG_PRINTLN(" - SecurityCallback - Authentication Success");
deviceConnected = true;
@@ -662,6 +794,11 @@ void SerialBLEInterface::onAuthenticationComplete(esp_ble_auth_cmpl_t cmpl) {
#if defined(MESH_USE_NIMBLE_ARDUINO)
void SerialBLEInterface::onConnect(BLEServer* pServer, NimBLEConnInfo& info) {
if (!_callbacksEnabled.load(std::memory_order_acquire)) {
last_conn_id = info.getConnHandle();
pServer->disconnect(last_conn_id);
return;
}
last_conn_id = info.getConnHandle();
deviceConnected = false;
oldDeviceConnected = false;
@@ -682,6 +819,11 @@ void SerialBLEInterface::onConnect(BLEServer* pServer) {
#if MESH_BLE_USES_NIMBLE
void SerialBLEInterface::onConnect(BLEServer* pServer, ble_gap_conn_desc* desc) {
if (!_callbacksEnabled.load(std::memory_order_acquire)) {
last_conn_id = desc->conn_handle;
pServer->disconnect(last_conn_id);
return;
}
BLE_DEBUG_PRINTLN("onConnect(), conn_id=%d, mtu=%d", desc->conn_handle,
pServer->getPeerMTU(desc->conn_handle));
last_conn_id = desc->conn_handle;
@@ -703,6 +845,11 @@ void SerialBLEInterface::onMtuChanged(BLEServer* pServer,
}
#else
void SerialBLEInterface::onConnect(BLEServer* pServer, esp_ble_gatts_cb_param_t *param) {
if (!_callbacksEnabled.load(std::memory_order_acquire)) {
last_conn_id = param->connect.conn_id;
pServer->disconnect(last_conn_id);
return;
}
BLE_DEBUG_PRINTLN("onConnect(), conn_id=%d, mtu=%d", param->connect.conn_id, pServer->getPeerMTU(param->connect.conn_id));
last_conn_id = param->connect.conn_id;
deviceConnected = false; // becomes usable only after authentication completes
@@ -734,6 +881,7 @@ void SerialBLEInterface::onDisconnect(BLEServer* pServer, NimBLEConnInfo& info,
#else
void SerialBLEInterface::onDisconnect(BLEServer* pServer) {
#endif
if (!_callbacksEnabled.load(std::memory_order_acquire)) return;
BLE_DEBUG_PRINTLN("onDisconnect()");
deviceConnected = false;
notifySucceeded = false;
@@ -763,6 +911,7 @@ void SerialBLEInterface::onWrite(BLECharacteristic* pCharacteristic,
esp_ble_gatts_cb_param_t* param) {
(void)param;
#endif
if (!_callbacksEnabled.load(std::memory_order_acquire)) return;
if (_tx_disconnect_recovery.pending()) {
BLE_DEBUG_PRINTLN("onWrite(): dropping frame while BLE reconnect is pending");
return;
@@ -801,6 +950,7 @@ void SerialBLEInterface::onSubscribe(BLECharacteristic* pCharacteristic,
(void)desc;
#endif
#if MESH_BLE_USES_NIMBLE
if (!_callbacksEnabled.load(std::memory_order_acquire)) return;
if (pCharacteristic == pTxCharacteristic) {
// NimBLE uses bit 0 for notification subscriptions.
notificationsEnabled.store((subValue & 0x0001u) != 0,
@@ -812,6 +962,7 @@ void SerialBLEInterface::onSubscribe(BLECharacteristic* pCharacteristic,
#if !defined(MESH_USE_NIMBLE_ARDUINO)
void SerialBLEInterface::onStatus(BLECharacteristic* pCharacteristic, Status status, uint32_t code) {
(void)pCharacteristic;
if (!_callbacksEnabled.load(std::memory_order_acquire)) return;
notifySucceeded = status == SUCCESS_NOTIFY;
if (!notifySucceeded) {
BLE_DEBUG_PRINTLN("notify failed, status=%d, code=%u; retaining frame",
@@ -926,46 +1077,89 @@ void SerialBLEInterface::recoverStalledTx(const char* cause) {
serviceTxRecovery((uint32_t)millis());
}
void SerialBLEInterface::enable() {
if (_isEnabled) return;
_isEnabled = true;
void SerialBLEInterface::startServiceAndAdvertising() {
if (pServer == NULL || pService == NULL) return;
clearBuffers();
// Start the service
#if defined(MESH_USE_NIMBLE_ARDUINO)
if (!pServer->start()) {
_isEnabled = false;
_isEnabled = _enableRequested = false;
_shutdownPending = true;
_callbacksEnabled.store(false, std::memory_order_release);
return;
}
#else
pService->start();
#endif
// Start advertising
//pServer->getAdvertising()->setMinInterval(500);
//pServer->getAdvertising()->setMaxInterval(1000);
_isEnabled = true;
if (advertisingAllowed()) {
#if defined(MESH_USE_NIMBLE_ARDUINO)
if (!pServer->getAdvertising()->start()) {
_isEnabled = _enableRequested = false;
_shutdownPending = true;
_callbacksEnabled.store(false, std::memory_order_release);
pServer->getAdvertising()->stop();
}
#else
pServer->getAdvertising()->start();
#endif
}
_adv_restart_pending = false;
}
void SerialBLEInterface::enable() {
if (_isEnabled || !_configured) return;
_enableRequested = true;
if (_shutdownPending) {
// Finish a previously requested disconnect/stop before rebuilding. A
// second toggle must never revive half of a stopped host.
servicePowerState();
return;
}
if (!_stackActive && !startBluetoothStack(false)) {
servicePowerState();
return;
}
startServiceAndAdvertising();
}
void SerialBLEInterface::disable() {
_isEnabled = false;
BLE_DEBUG_PRINTLN("SerialBLEInterface::disable");
pServer->getAdvertising()->stop();
pServer->disconnect(last_conn_id);
#if !defined(MESH_USE_NIMBLE_ARDUINO)
pService->stop();
#endif
oldDeviceConnected = deviceConnected = false;
clearBuffers();
_isEnabled = _enableRequested = false;
_adv_restart_pending = false;
// The caller drains its command reply before this point. Only stop
// advertising/disconnect here; the host is stopped in the loop task after
// its asynchronous disconnect has completed.
servicePowerState();
}
void SerialBLEInterface::servicePowerState() {
const uint32_t now = (uint32_t)millis();
if (!_enableRequested && _stackActive && !_shutdownPending) {
_shutdownPending = true;
_powerAttempted = false;
_callbacksEnabled.store(false, std::memory_order_release);
_adv_restart_pending = false;
if (pServer != NULL) pServer->getAdvertising()->stop();
oldDeviceConnected = deviceConnected = false;
}
if (!_shutdownPending) return;
if (_powerAttempted
&& !mesh::bleElapsedAtLeast(now, _lastPowerAttempt, BLE_POWER_RETRY_MS))
return;
_powerAttempted = true;
_lastPowerAttempt = now;
if (pServer != NULL && pServer->getConnectedCount() != 0) {
pServer->disconnect(last_conn_id);
return;
}
if (!stopBluetoothStack()) return;
_stackActive = false;
_shutdownPending = false;
_powerAttempted = false;
clearBuffers();
_pairingRequestPending.store(false, std::memory_order_release);
_successfulConnectionPending.store(false, std::memory_order_release);
_successfulConnectionStarted.store(0, std::memory_order_relaxed);
if (_enableRequested && startBluetoothStack(false)) startServiceAndAdvertising();
}
size_t SerialBLEInterface::writeFrame(const uint8_t src[], size_t len) {
@@ -1026,6 +1220,7 @@ bool SerialBLEInterface::isWriteBusy() const {
size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) {
const uint32_t now = (uint32_t)millis();
if (!_isEnabled || !_stackActive || _shutdownPending) return 0;
servicePendingTxReset();
if (_tx_disconnect_recovery.pending()) {
serviceTxRecovery(now);
@@ -1137,5 +1332,6 @@ size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) {
}
bool SerialBLEInterface::isConnected() const {
return !_tx_disconnect_recovery.pending() && deviceConnected;
return _isEnabled && _stackActive && !_shutdownPending
&& !_tx_disconnect_recovery.pending() && deviceConnected;
}
+28
View File
@@ -29,6 +29,7 @@ class SerialBLEInterface : public BaseSerialInterface,
BLEServer *pServer;
BLEService *pService;
BLECharacteristic * pTxCharacteristic;
BLECharacteristic *pRxCharacteristic;
#if !defined(MESH_USE_NIMBLE_ARDUINO)
BLE2902 *pTxDescriptor;
#endif
@@ -37,6 +38,22 @@ class SerialBLEInterface : public BaseSerialInterface,
bool notifySucceeded;
std::atomic<bool> notificationsEnabled{false};
bool _isEnabled;
bool _enableRequested = false;
// This interface outlives each host/controller session. Disable callbacks
// before stopping the host, and only then destroy its GATT objects.
std::atomic<bool> _callbacksEnabled{false};
bool _stackActive = false;
bool _shutdownPending = false;
bool _nativeHostStopped = false;
bool _configured = false;
bool _powerAttempted = false;
uint32_t _lastPowerAttempt = 0;
char _deviceName[48] = {};
uint8_t _customAddress[mesh::companion::BLUETOOTH_MAC_BYTES] = {};
bool _hasCustomAddress = false;
bool _advertisingConfigured = false;
bool _hasBondedPeer = false;
mesh::companion::BluetoothPeerIdentity _bondedPeer;
uint16_t last_conn_id;
uint32_t _pin_code;
uint32_t _last_write;
@@ -67,6 +84,10 @@ class SerialBLEInterface : public BaseSerialInterface,
Frame send_queue[FRAME_QUEUE_SIZE];
void clearBuffers();
bool startBluetoothStack(bool clear_bonds);
bool stopBluetoothStack();
void forgetGattPointers();
void startServiceAndAdvertising();
bool hasRequiredReplyCapacity() const;
void servicePendingTxReset();
void scheduleAdvertisingRestart(uint32_t now);
@@ -131,6 +152,7 @@ public:
pServer = NULL;
pService = NULL;
pTxCharacteristic = NULL;
pRxCharacteristic = NULL;
#if !defined(MESH_USE_NIMBLE_ARDUINO)
pTxDescriptor = NULL;
#endif
@@ -171,6 +193,12 @@ public:
void enable() override;
void disable() override;
bool isEnabled() const override { return _isEnabled; }
// Call from the application task even while the logical interface is off.
// Disconnects are asynchronous; never stop a host from its own callback.
void servicePowerState();
bool isPowerTransitionPending() const {
return _shutdownPending || (_stackActive != _enableRequested);
}
bool isConnected() const override;
+92 -1
View File
@@ -9,6 +9,7 @@
#include <new>
#if defined(ESP32_PLATFORM)
#include <esp_heap_caps.h>
#include <esp_timer.h>
#elif defined(NRF52_PLATFORM)
#include <utility/debug.h>
#include "../NRF52Board.h"
@@ -94,7 +95,12 @@ static uint32_t profileTimestamp(bool dual_profile) {
return profile_clock_ticks;
}
#endif
#if defined(ESP32_PLATFORM)
// Unlike a cycle counter, this domain includes elapsed light-sleep time.
return static_cast<uint32_t>(esp_timer_get_time());
#else
return micros();
#endif
}
static uint32_t profileElapsedUs(uint32_t since, uint32_t now, bool dual_profile) {
@@ -486,7 +492,12 @@ mesh::RadioParamApplyResult RadioLibWrapper::trySetParams(float freq, float bw,
}
}
#if defined(ESP32_PLATFORM)
_esp32_profile_visit_started_us = static_cast<uint64_t>(esp_timer_get_time());
_profile_visit_stamp = static_cast<uint32_t>(_esp32_profile_visit_started_us);
#else
_profile_visit_stamp = profileTimestamp(_profiles.enabled());
#endif
return success ? mesh::RadioParamApplyResult::APPLIED : mesh::RadioParamApplyResult::FAILED;
}
@@ -610,7 +621,12 @@ mesh::RadioParamApplyResult RadioLibWrapper::tuneProfile(uint8_t profile) {
if (!restored || (resume && !isInRecvMode()))
_profile_refresh_required = _profile_repair_required = true;
}
#if defined(ESP32_PLATFORM)
_esp32_profile_visit_started_us = static_cast<uint64_t>(esp_timer_get_time());
_profile_visit_stamp = static_cast<uint32_t>(_esp32_profile_visit_started_us);
#else
_profile_visit_stamp = profileTimestamp(dual_profile);
#endif
// A profile retune re-enters RX on a different tuple. Do not read its
// instantaneous RSSI until the chip family's settle interval has elapsed.
if (applied && _nf_refresh_requested) {
@@ -837,6 +853,9 @@ mesh::RadioParamApplyResult RadioLibWrapper::tryRestoreCodingRate(uint8_t cr) {
void RadioLibWrapper::serviceProfileScan() {
#if defined(NRF52_PLATFORM)
_profile_idle_visit_ticks = 0; // Every deferred/restarted scan fails closed.
#endif
#if defined(ESP32_PLATFORM)
_esp32_profile_idle_visit_us = 0;
#endif
(void)profileTimestamp(_profiles.enabled());
if (_cw_active) return;
@@ -886,7 +905,7 @@ void RadioLibWrapper::serviceProfileScan() {
if (!_profiles.switchTestReady()) return;
}
uint8_t target = _active_profile;
#if defined(NRF52_PLATFORM)
#if defined(NRF52_PLATFORM) || defined(ESP32_PLATFORM)
const uint8_t visited_profile = _active_profile;
#endif
uint32_t visit_us = 0;
@@ -919,13 +938,25 @@ void RadioLibWrapper::serviceProfileScan() {
&& visit_us < NF_CALIB_SETTLE_MS * 1000UL) {
visit_us = NF_CALIB_SETTLE_MS * 1000UL;
}
#if defined(ESP32_PLATFORM)
// Keep long visits and light-sleep elapsed time in the same 64-bit domain.
const uint64_t now_us = static_cast<uint64_t>(esp_timer_get_time());
if (now_us < _esp32_profile_visit_started_us
|| now_us - _esp32_profile_visit_started_us >= visit_us) target ^= 1;
#else
if (profileElapsedUs(_profile_visit_stamp, profileTimestamp(true), true) >= visit_us) target ^= 1;
#endif
}
const auto result = tuneProfile(target);
if (restart_scan && result == mesh::RadioParamApplyResult::APPLIED) {
_profile_scan_generation[0] = _profiles.generation[0];
_profile_scan_generation[1] = _profiles.generation[1];
#if defined(ESP32_PLATFORM)
_esp32_profile_visit_started_us = static_cast<uint64_t>(esp_timer_get_time());
_profile_visit_stamp = static_cast<uint32_t>(_esp32_profile_visit_started_us);
#else
_profile_visit_stamp = profileTimestamp(true);
#endif
}
if (result == mesh::RadioParamApplyResult::FAILED) {
// Retry a rejected or failing profile at a bounded rate; retain primary RX.
@@ -955,6 +986,19 @@ void RadioLibWrapper::serviceProfileScan() {
_profile_idle_preamble = _physical_preamble;
}
#endif
#if defined(ESP32_PLATFORM)
if (_profiles.enabled() && !restart_scan && _active_profile == visited_profile
&& result == mesh::RadioParamApplyResult::APPLIED
&& !isChipBusy() && !isPacketPendingOrReceiving()) {
_esp32_profile_idle_visit_us = visit_us;
_esp32_profile_idle_stamp_us = _esp32_profile_visit_started_us;
_esp32_profile_idle_switch_us = _profiles.switchBudgetUs();
_esp32_profile_idle_preamble = _physical_preamble;
_esp32_profile_idle_profile = _active_profile;
_esp32_profile_idle_generation[0] = _profiles.generation[0];
_esp32_profile_idle_generation[1] = _profiles.generation[1];
}
#endif
}
bool RadioLibWrapper::getProfileIdleDelay(uint32_t& delay_ms) const {
@@ -993,6 +1037,48 @@ bool RadioLibWrapper::getProfileIdleDelay(uint32_t& delay_ms) const {
|| _profile_idle_visit_ticks - elapsed <= 32 + guard_ticks) return false;
delay_ms = uint64_t(_profile_idle_visit_ticks - elapsed - guard_ticks) * 15625 / 512000;
return delay_ms != 0;
#elif defined(ESP32_PLATFORM)
if (!_profiles.enabled() || !_esp32_profile_idle_visit_us
|| !_params_valid || state != STATE_RX || !_profile_rxps_suspended
|| _rx_ps_enabled || _rx_ps_armed || _rx_hold_continuous
|| _rx_retry_pending || _profile_retry_at || _profile_refresh_required
|| _profile_repair_required || _nf_refresh_requested || _nf_calib_active
|| !_noise_floor_valid || !_noise_floor_secondary_valid
|| _wd_observe_until || _cw_active || _morse_owned || hasPendingRadioInterrupt()
|| !_profiles.switchTestReady() || _active_profile > 1
|| _esp32_profile_idle_profile != _active_profile
|| _profile_generation != _profiles.generation[_active_profile]
|| _profile_scan_generation[0] != _profiles.generation[0]
|| _profile_scan_generation[1] != _profiles.generation[1]
|| _esp32_profile_idle_generation[0] != _profiles.generation[0]
|| _esp32_profile_idle_generation[1] != _profiles.generation[1]
|| _esp32_profile_idle_stamp_us != _esp32_profile_visit_started_us
|| _esp32_profile_idle_preamble != _physical_preamble
|| _esp32_profile_idle_switch_us != _profiles.switchBudgetUs()) return false;
#if MESH_ENABLE_TX_BEACONS
if (_beacon_owned) return false;
#endif
#if MESH_ENABLE_MORSE_RX
if (_morse_rx_owned) return false;
#endif
const uint64_t now_us = static_cast<uint64_t>(esp_timer_get_time());
if (now_us < _esp32_profile_idle_stamp_us) return false;
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
|| 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;
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;
return true;
#else
return false; // Other platforms retain polling until their wake path is validated.
#endif
@@ -2070,7 +2156,12 @@ void RadioLibWrapper::startRecv() {
int err = startReceiveMode();
if (err == RADIOLIB_ERR_NONE) {
// A very short frame may complete while startReceiveMode() returns.
#if defined(ESP32_PLATFORM)
_esp32_profile_visit_started_us = static_cast<uint64_t>(esp_timer_get_time());
_profile_visit_stamp = static_cast<uint32_t>(_esp32_profile_visit_started_us);
#else
_profile_visit_stamp = profileTimestamp(_profiles.enabled());
#endif
// Retain that RX interrupt instead of overwriting it with software state.
state = STATE_RX;
// RSSI is unsettled after every RX entry, including CAD/TX completion.
+12
View File
@@ -125,6 +125,18 @@ protected:
uint32_t _profile_idle_switch_us = 0;
uint16_t _profile_idle_preamble = 0;
#endif
#if defined(ESP32_PLATFORM)
// ESP Timer advances by the RTC interval after light sleep. Retain its
// full domain as well as the legacy scanner timestamp: a long RX hold or
// delayed loop must not resurrect a visit after micros() wraps.
uint64_t _esp32_profile_visit_started_us = 0;
uint64_t _esp32_profile_idle_stamp_us = 0;
uint32_t _esp32_profile_idle_visit_us = 0;
uint32_t _esp32_profile_idle_switch_us = 0;
uint32_t _esp32_profile_idle_generation[2] = {};
uint16_t _esp32_profile_idle_preamble = 0;
uint8_t _esp32_profile_idle_profile = 0;
#endif
#if defined(MESH_HIL_TX_FREQ_MHZ)
bool hilPacketTransmitAllowed() const;
#endif