diff --git a/esphome/components/esp32_ble/ble.cpp b/esphome/components/esp32_ble/ble.cpp index 4b5505f5ad..0e723855c3 100644 --- a/esphome/components/esp32_ble/ble.cpp +++ b/esphome/components/esp32_ble/ble.cpp @@ -84,11 +84,8 @@ void ESP32BLE::setup() { } void ESP32BLE::enable() { - if (this->state_ == BLE_COMPONENT_STATE_DISABLE) { - // The teardown has not run yet; the stack is still up. - this->state_ = BLE_COMPONENT_STATE_ACTIVE; + if (this->cancel_pending_(BLE_COMPONENT_STATE_DISABLE, BLE_COMPONENT_STATE_ACTIVE)) return; - } if (this->state_ != BLE_COMPONENT_STATE_DISABLED) return; @@ -96,11 +93,8 @@ void ESP32BLE::enable() { } void ESP32BLE::disable() { - if (this->state_ == BLE_COMPONENT_STATE_ENABLE) { - // The bring-up has not run yet; the stack is still down. - this->state_ = BLE_COMPONENT_STATE_DISABLED; + if (this->cancel_pending_(BLE_COMPONENT_STATE_ENABLE, BLE_COMPONENT_STATE_DISABLED)) return; - } if (this->state_ == BLE_COMPONENT_STATE_DISABLED) return; diff --git a/esphome/components/esp32_ble/ble.h b/esphome/components/esp32_ble/ble.h index 35bf4b5b9f..4de5f8e0e0 100644 --- a/esphome/components/esp32_ble/ble.h +++ b/esphome/components/esp32_ble/ble.h @@ -176,6 +176,14 @@ 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; + } // Drop what the old stack queued; the next stack reuses the same interface ids. void drain_ble_events_() { BLEEvent *ble_event;