From 5453835963c1df898c31f38207d7c52d70d730f4 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Tue, 17 Jun 2025 18:09:53 +0200 Subject: [PATCH] make ble client disable/enable smarter --- .../esp32_ble_client/ble_client_base.cpp | 19 +++++++++++++------ .../esp32_ble_client/ble_client_base.h | 6 ++---- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/esphome/components/esp32_ble_client/ble_client_base.cpp b/esphome/components/esp32_ble_client/ble_client_base.cpp index 115d785eae..ef1d427113 100644 --- a/esphome/components/esp32_ble_client/ble_client_base.cpp +++ b/esphome/components/esp32_ble_client/ble_client_base.cpp @@ -22,6 +22,19 @@ void BLEClientBase::setup() { this->connection_index_ = connection_index++; } +void BLEClientBase::set_state(espbt::ClientState st) { + ESP_LOGV(TAG, "[%d] [%s] Set state %d", this->connection_index_, this->address_str_.c_str(), (int) st); + ESPBTClient::set_state(st); + + // Disable loop when idle AND address is not set (unused connection slot) + if (st == espbt::ClientState::IDLE && this->address_ == 0) { + this->disable_loop(); + } else if (st == espbt::ClientState::READY_TO_CONNECT || st == espbt::ClientState::INIT) { + // Enable loop when we need to initialize or connect + this->enable_loop(); + } +} + void BLEClientBase::loop() { if (!esp32_ble::global_ble->is_active()) { this->set_state(espbt::ClientState::INIT); @@ -36,12 +49,6 @@ void BLEClientBase::loop() { this->set_state(espbt::ClientState::IDLE); } - // If address is 0, this connection is not in use - if (this->address_ == 0) { - this->disable_loop(); - return; - } - // READY_TO_CONNECT means we have discovered the device // and the scanner has been stopped by the tracker. if (this->state_ == espbt::ClientState::READY_TO_CONNECT) { diff --git a/esphome/components/esp32_ble_client/ble_client_base.h b/esphome/components/esp32_ble_client/ble_client_base.h index 69c7c31ad8..814a9664d9 100644 --- a/esphome/components/esp32_ble_client/ble_client_base.h +++ b/esphome/components/esp32_ble_client/ble_client_base.h @@ -63,10 +63,6 @@ class BLEClientBase : public espbt::ESPBTClient, public Component { (uint8_t) (this->address_ >> 16) & 0xff, (uint8_t) (this->address_ >> 8) & 0xff, (uint8_t) (this->address_ >> 0) & 0xff); } - // Re-enable loop() when a non-zero address is assigned - if (address != 0) { - this->enable_loop(); - } } std::string address_str() const { return this->address_str_; } @@ -97,6 +93,8 @@ class BLEClientBase : public espbt::ESPBTClient, public Component { bool check_addr(esp_bd_addr_t &addr) { return memcmp(addr, this->remote_bda_, sizeof(esp_bd_addr_t)) == 0; } + void set_state(espbt::ClientState st) override; + protected: int gattc_if_; esp_bd_addr_t remote_bda_;