From 8b273cc912c8c7e6e67439eab76488d3abe87327 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 10 Sep 2026 08:34:25 -0500 Subject: [PATCH] [esp32_ble] Fold enable and disable into one request table --- esphome/components/esp32_ble/ble.cpp | 41 ++++++++++++++++++---------- esphome/components/esp32_ble/ble.h | 9 +----- 2 files changed, 27 insertions(+), 23 deletions(-) diff --git a/esphome/components/esp32_ble/ble.cpp b/esphome/components/esp32_ble/ble.cpp index 0e723855c3..e414f32580 100644 --- a/esphome/components/esp32_ble/ble.cpp +++ b/esphome/components/esp32_ble/ble.cpp @@ -83,22 +83,33 @@ void ESP32BLE::setup() { } } -void ESP32BLE::enable() { - if (this->cancel_pending_(BLE_COMPONENT_STATE_DISABLE, BLE_COMPONENT_STATE_ACTIVE)) - return; - if (this->state_ != BLE_COMPONENT_STATE_DISABLED) - return; +void ESP32BLE::enable() { this->request_state_(true); } +void ESP32BLE::disable() { this->request_state_(false); } - this->state_ = BLE_COMPONENT_STATE_ENABLE; -} - -void ESP32BLE::disable() { - if (this->cancel_pending_(BLE_COMPONENT_STATE_ENABLE, BLE_COMPONENT_STATE_DISABLED)) - return; - if (this->state_ == BLE_COMPONENT_STATE_DISABLED) - return; - - this->state_ = BLE_COMPONENT_STATE_DISABLE; +// Queue the transition for loop(). A pending transition the other way is +// cancelled instead, since nothing was torn down or brought up yet; any other +// state is already there or on its way. +void ESP32BLE::request_state_(bool enable) { + switch (this->state_) { + case BLE_COMPONENT_STATE_DISABLE: + if (enable) + this->state_ = BLE_COMPONENT_STATE_ACTIVE; + break; + case BLE_COMPONENT_STATE_ENABLE: + if (!enable) + this->state_ = BLE_COMPONENT_STATE_DISABLED; + break; + case BLE_COMPONENT_STATE_DISABLED: + if (enable) + this->state_ = BLE_COMPONENT_STATE_ENABLE; + break; + case BLE_COMPONENT_STATE_ACTIVE: + if (!enable) + this->state_ = BLE_COMPONENT_STATE_DISABLE; + break; + default: + break; + } } #ifdef USE_ESP32_BLE_ADVERTISING diff --git a/esphome/components/esp32_ble/ble.h b/esphome/components/esp32_ble/ble.h index 4de5f8e0e0..2b889c5a3c 100644 --- a/esphome/components/esp32_ble/ble.h +++ b/esphome/components/esp32_ble/ble.h @@ -176,14 +176,7 @@ class ESP32BLE final : public Component { bool ble_setup_(); bool ble_dismantle_(); - // A request that arrives while the opposite transition is still pending just - // cancels it: loop() has not run, so nothing was torn down or brought up. - bool cancel_pending_(BLEComponentState pending, BLEComponentState restored) { - if (this->state_ != pending) - return false; - this->state_ = restored; - return true; - } + void request_state_(bool enable); // Drop what the old stack queued; the next stack reuses the same interface ids. void drain_ble_events_() { BLEEvent *ble_event;