Compare commits

...
Author SHA1 Message Date
J. Nick Koston d994465cbb Merge remote-tracking branch 'upstream/ble-adv-uuid-leak' into ble-adv-priority-uuid 2026-11-09 13:49:23 -08:00
J. Nick Koston 47644620ba Merge remote-tracking branch 'upstream/esp32-ble-adv-config-serialize' into ble-adv-uuid-leak 2026-11-09 13:49:07 -08:00
J. Nick Koston a401b13317 Time the config send with millis() and keep a deferred refresh after a central link 2026-11-09 13:48:32 -08:00
J. Nick Koston 8a00a46bc5 Clear the data pointer with its length 2026-11-09 13:01:34 -08:00
J. Nick Koston 35f82ddfa4 clang-format 2026-11-09 12:45:37 -08:00
J. Nick Koston 35941340ec Merge branch 'ble-adv-uuid-leak' into ble-adv-priority-uuid
# Conflicts:
#	esphome/components/esp32_ble/ble_advertising.h
2026-11-09 12:45:28 -08:00
J. Nick Koston a21824d7dc Note that p_service_uuid only lives during services_advertisement_() 2026-11-09 12:44:57 -08:00
J. Nick Koston 3a1f88fb09 Document the 8 byte service data limit of the priority UUID 2026-11-09 12:19:22 -08:00
J. Nick Koston 0b6b4ea1fb Merge ble-adv-uuid-leak; shorten comments 2026-11-09 12:16:57 -08:00
J. Nick Koston 1e904175f5 Shorten comments 2026-11-09 12:16:21 -08:00
J. Nick Koston c0fa18cce0 Merge branch 'ble-adv-uuid-leak' into ble-adv-priority-uuid
# Conflicts:
#	esphome/components/esp32_ble/ble_advertising.h
2026-11-09 12:12:02 -08:00
J. Nick Koston 61c20a631c Merge remote-tracking branch 'upstream/esp32-ble-adv-config-serialize' into ble-adv-uuid-leak 2026-11-09 12:11:28 -08:00
J. Nick Koston 97d061261f Mark the GAP advertising completion fallthrough and note the 16-bit time aliasing 2026-11-09 12:10:50 -08:00
J. Nick Koston 0f8b35e038 Merge branch 'ble-adv-uuid-leak' into ble-adv-priority-uuid
# Conflicts:
#	esphome/components/esp32_ble/ble_advertising.h
2026-11-09 11:53:39 -08:00
J. Nick Koston 12fdae5358 Merge remote-tracking branch 'upstream/esp32-ble-adv-config-serialize' into ble-adv-uuid-leak 2026-11-09 11:52:58 -08:00
J. Nick Koston 4942918ff6 Keep the config send time in 16 bits inside existing padding 2026-11-09 11:52:26 -08:00
J. Nick Koston bc96d6ea98 Merge branch 'ble-adv-uuid-leak' into ble-adv-priority-uuid 2026-11-09 11:44:09 -08:00
J. Nick Koston 600007c10e Merge remote-tracking branch 'upstream/esp32-ble-adv-config-serialize' into ble-adv-uuid-leak 2026-11-09 11:43:54 -08:00
J. Nick Koston 1222c9f827 Force advertising_loop_() inline, as it runs on every loop pass 2026-11-09 11:43:09 -08:00
J. Nick Koston ec267b59a8 Merge branch 'ble-adv-uuid-leak' into ble-adv-priority-uuid 2026-11-09 10:35:46 -08:00
J. Nick Koston e932f43f0c Merge remote-tracking branch 'upstream/esp32-ble-adv-config-serialize' into ble-adv-uuid-leak 2026-11-09 10:35:28 -08:00
J. Nick Koston 926adb62d7 Send advertising configs only from BLEAdvertising::loop() and wake the loop for them
advertising_refresh() now only marks the services advertising pending (or stops
it) and wakes the loop; BLEAdvertising::loop(), which runs after the BLE event
queue is drained, is the only sender. Late completions from a timed-out batch are
therefore always counted before the next send, and several refreshes in one pass
become one config pair. The two config completion events also wake the loop.
2026-11-09 09:57:03 -08:00
J. Nick Koston b8ad998d27 Merge branch 'ble-adv-uuid-leak' into ble-adv-priority-uuid 2026-11-09 09:50:15 -08:00
J. Nick Koston 92f89a206d Merge remote-tracking branch 'upstream/esp32-ble-adv-config-serialize' into ble-adv-uuid-leak 2026-11-09 09:49:58 -08:00
J. Nick Koston 76911fc276 Register the GAP callback for advertising, count queued completions first, and drop a deferred restart when the server is full
Without a GAP event consumer (Improv only, a server without security) the GAP
callback was never registered, so the config completions never arrived and
every refresh waited out the 1 s timeout. advertising_->loop() now runs after
the event queue is drained, so completions that arrived during a long loop
pause are counted before the timeout check. A client filling the last server
slot stops advertising, so a restart deferred before it is dropped.
2026-11-09 09:27:37 -08:00
J. Nick Koston 6c34c2284c Remove conflict markers left by the previous merge 2026-11-09 09:14:01 -08:00
J. Nick Koston d2a5490b6e Say Bluedroid copies the UUIDs, not the stack 2026-11-09 09:13:37 -08:00
J. Nick Koston 63faae0212 Say Bluedroid copies the UUIDs, not the stack 2026-11-09 09:13:34 -08:00
J. Nick Koston e86d35662b Merge the stack UUID buffer; size it one larger for the priority UUID 2026-11-09 09:11:30 -08:00
J. Nick Koston f0d94b89e2 Build the UUID list on the stack instead of the heap 2026-11-09 09:10:44 -08:00
J. Nick Koston 8bc0eec00d [esp32_ble][improv_ble] Keep the Improv UUID and state in the advertising packet for passive scanners 2026-11-09 09:09:15 -08:00
J. Nick Koston d62efd063c [esp32_ble] Free the advertised service UUID buffer on every return 2026-11-09 09:04:38 -08:00
J. Nick Koston 180d5dc3f0 Warn when an advertising config is not confirmed in time and reset the count on disable
Completion events carry no id, so a late one after the timeout can count down
the next configs; the warning makes that degraded path visible. Disabling BLE
drops pending completion events, so the count is reset with them.
2026-11-09 08:44:49 -08:00
J. Nick Koston 14d5a88a32 Apply a deferred advertising restart only from loop() 2026-11-09 08:08:41 -08:00
J. Nick Koston 684a9cef41 [esp32_ble] Wait for the stack to take an advertising config before sending the next
Bluedroid converts each advertising and scan response config into one static
buffer and hands the BTU task only a pointer to it; the next config frees that
buffer, so two configs back to back let the BTU task read freed memory and
crash in btm_ble_build_adv_data. Count the configs in flight, defer a restart
until their completion events arrive, and give up waiting after 1 s.
2026-11-09 07:43:42 -08:00
6 changed files with 155 additions and 30 deletions

No files matched your search

+39 -9
View File
@@ -188,6 +188,11 @@ void ESP32BLE::advertising_stop() {
this->advertising_refresh();
}
void ESP32BLE::advertising_cancel_deferred() {
if (this->advertising_ != nullptr)
this->advertising_->cancel_deferred_restart();
}
void ESP32BLE::advertising_refresh() {
if (this->advertising_ == nullptr || !this->is_active())
return;
@@ -195,7 +200,8 @@ void ESP32BLE::advertising_refresh() {
if (this->advertising_ref_count_ == 0) {
this->advertising_->stop();
} else {
this->advertising_->start();
this->advertising_->request_start();
App.wake_loop_threadsafe();
}
}
@@ -244,6 +250,16 @@ void ESP32BLE::advertising_add_service_uuid(ESPBTUUID uuid) {
this->advertising_refresh();
}
void ESP32BLE::advertising_set_priority_uuid(ESPBTUUID uuid) {
this->advertising_init_();
this->advertising_->set_priority_uuid(uuid);
}
void ESP32BLE::advertising_clear_priority_uuid() {
if (this->advertising_ != nullptr)
this->advertising_->clear_priority_uuid();
}
void ESP32BLE::advertising_remove_service_uuid(ESPBTUUID uuid) {
this->advertising_init_();
this->advertising_->remove_service_uuid(uuid);
@@ -349,7 +365,8 @@ bool ESP32BLE::ble_setup_() {
return false;
}
#ifdef ESPHOME_ESP32_BLE_GAP_EVENT_HANDLER_COUNT
#if defined(ESPHOME_ESP32_BLE_GAP_EVENT_HANDLER_COUNT) || defined(USE_ESP32_BLE_ADVERTISING)
// Advertising needs its config completion events even when no component handles GAP events
err = esp_ble_gap_register_callback(ESP32BLE::gap_event_handler);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gap_register_callback failed: %d", err);
@@ -507,15 +524,11 @@ void ESP32BLE::loop() {
return;
}
#ifdef USE_ESP32_BLE_ADVERTISING
if (this->advertising_ != nullptr) {
this->advertising_->loop();
}
#endif
BLEEvent *ble_event = this->ble_events_.pop();
if (ble_event == nullptr)
if (ble_event == nullptr) {
this->advertising_loop_();
return;
}
do {
switch (ble_event->type_) {
@@ -552,6 +565,14 @@ void ESP32BLE::loop() {
GAP_SCAN_COMPLETE_EVENTS:
// Advertising complete events
GAP_ADV_COMPLETE_EVENTS:
#ifdef USE_ESP32_BLE_ADVERTISING
if ((gap_event == ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT ||
gap_event == ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT) &&
this->advertising_ != nullptr) {
this->advertising_->on_config_complete();
}
[[fallthrough]];
#endif
// RSSI complete event
case ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT:
// Security events
@@ -614,6 +635,8 @@ void ESP32BLE::loop() {
if (dropped > 0) {
ESP_LOGW(TAG, "Dropped %u BLE events due to buffer overflow", dropped);
}
// After the events, so config completions already queued are counted before the timeout check
this->advertising_loop_();
}
void ESP32BLE::loop_handle_state_transition_not_active_() {
@@ -631,6 +654,10 @@ void ESP32BLE::loop_handle_state_transition_not_active_() {
return;
}
this->drain_ble_events_();
#ifdef USE_ESP32_BLE_ADVERTISING
if (this->advertising_ != nullptr)
this->advertising_->reset_config_state();
#endif
// A status callback may have asked for BLE back; the stack is down now, so
// that request becomes a bring-up.
this->state_ =
@@ -708,6 +735,9 @@ void ESP32BLE::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_pa
// Connection events - used by ble_client
case ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT:
enqueue_ble_event(event, param);
// A deferred advertising send waits for these; this runs on the Bluetooth task
if (event == ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT || event == ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT)
App.wake_loop_threadsafe();
return;
// Security events - used by ble_client and bluetooth_proxy
+11
View File
@@ -125,12 +125,17 @@ class ESP32BLE final : public Component {
void advertising_stop();
/// Apply the current payload and request count: advertise while requested, otherwise stop.
void advertising_refresh();
/// Drop a restart deferred while advertising configs were in flight (the controller stopped advertising).
void advertising_cancel_deferred();
void advertising_set_service_data(const std::vector<uint8_t> &data);
void advertising_set_manufacturer_data(const std::vector<uint8_t> &data);
void advertising_set_appearance(uint16_t appearance) { this->appearance_ = appearance; }
void advertising_set_service_data_and_name(std::span<const uint8_t> data, bool include_name);
void advertising_add_service_uuid(ESPBTUUID uuid);
void advertising_remove_service_uuid(ESPBTUUID uuid);
/// Keep `uuid` and up to 8 bytes of service data in the advertising packet; applies on the next refresh.
void advertising_set_priority_uuid(ESPBTUUID uuid);
void advertising_clear_priority_uuid();
void advertising_register_raw_advertisement_callback(std::function<void(bool)> &&callback);
#endif
@@ -188,6 +193,12 @@ class ESP32BLE final : public Component {
}
this->ble_events_.get_and_reset_dropped_count();
}
ESPHOME_ALWAYS_INLINE void advertising_loop_() {
#ifdef USE_ESP32_BLE_ADVERTISING
if (this->advertising_ != nullptr)
this->advertising_->loop();
#endif
}
#ifdef USE_ESP32_BLE_ADVERTISING
void advertising_init_();
#endif
@@ -4,6 +4,7 @@
#ifdef USE_ESP32_BLE_ADVERTISING
#include <cstdio>
#include <algorithm>
#include <cstring>
#include "ble_uuid.h"
#include "esphome/core/log.h"
@@ -12,6 +13,10 @@
namespace esphome::esp32_ble {
ESPHOME_LOG_TAG(TAG, "esp32_ble.advertising");
// Give up on a completion event after this long, so a lost event cannot stop advertising updates for good
static constexpr uint32_t CONFIG_COMPLETE_TIMEOUT_MS = 1000;
// A 31 byte packet holds at most 14 16-bit UUIDs
static constexpr size_t MAX_ADVERTISED_UUIDS = 14;
BLEAdvertising::BLEAdvertising(uint32_t advertising_cycle_time) : advertising_cycle_time_(advertising_cycle_time) {
this->advertising_data_.set_scan_rsp = false;
@@ -69,51 +74,99 @@ void BLEAdvertising::set_manufacturer_data(const std::vector<uint8_t> &data) {
}
}
bool BLEAdvertising::config_pending_() const {
// millis(), not the loop start time: the send follows the BLE event drain, which can take longer than the timeout
return this->configs_pending_ != 0 &&
static_cast<uint16_t>(millis() - this->config_sent_time_) < CONFIG_COMPLETE_TIMEOUT_MS;
}
void BLEAdvertising::reset_config_state() {
this->configs_pending_ = 0;
this->restart_pending_ = false;
}
void BLEAdvertising::on_config_complete() {
if (this->configs_pending_ != 0)
this->configs_pending_--;
}
esp_err_t BLEAdvertising::services_advertisement_() {
int num_services = this->advertising_uuids_.size();
if (num_services == 0) {
this->advertising_data_.service_uuid_len = 0;
} else {
this->advertising_data_.service_uuid_len = 16 * num_services;
// NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
this->advertising_data_.p_service_uuid = new uint8_t[this->advertising_data_.service_uuid_len];
uint8_t *p = this->advertising_data_.p_service_uuid;
for (int i = 0; i < num_services; i++) {
ESPBTUUID uuid = this->advertising_uuids_[i];
memcpy(p, uuid.as_128bit().get_uuid().uuid.uuid128, 16);
p += 16;
}
if (this->config_pending_()) {
// Applied once the stack has taken the previous config
this->restart_pending_ = true;
return ESP_OK;
}
if (this->configs_pending_ != 0) {
// Completion events carry no id: one that is only late, not lost, can still count down the new configs
ESP_LOGW(TAG, "Advertising config not confirmed within %u ms", (unsigned) CONFIG_COMPLETE_TIMEOUT_MS);
this->configs_pending_ = 0;
}
this->config_sent_time_ = static_cast<uint16_t>(millis());
// Bluedroid copies these during each config call; a priority UUID goes first and alone in the advertising packet
const bool priority = this->priority_uuid_.is_set();
const size_t max_services = MAX_ADVERTISED_UUIDS + (priority ? 1 : 0);
uint8_t uuids[16 * (MAX_ADVERTISED_UUIDS + 1)];
size_t num_services = 0;
if (priority)
memcpy(uuids + 16 * num_services++, this->priority_uuid_.as_128bit().get_uuid().uuid.uuid128, 16);
for (const auto &uuid : this->advertising_uuids_) {
if (num_services == max_services)
break;
if (uuid != this->priority_uuid_) // an unset priority UUID matches nothing
memcpy(uuids + 16 * num_services++, uuid.as_128bit().get_uuid().uuid.uuid128, 16);
}
this->advertising_data_.service_uuid_len = 16 * (priority ? 1 : num_services);
this->advertising_data_.p_service_uuid = num_services > 0 ? uuids : nullptr;
esp_err_t err;
this->advertising_data_.set_scan_rsp = false;
this->advertising_data_.include_name = this->include_name_in_adv_ || !this->scan_response_;
this->advertising_data_.include_txpower = !this->scan_response_;
// No room for these next to a priority UUID; they go to the scan response. Bluedroid copies a non-null pointer
// even with a zero length, so clear both.
const uint16_t manufacturer_len = this->advertising_data_.manufacturer_len;
uint8_t *manufacturer_data = this->advertising_data_.p_manufacturer_data;
const uint16_t appearance = this->advertising_data_.appearance;
if (priority) {
this->advertising_data_.manufacturer_len = 0;
this->advertising_data_.p_manufacturer_data = nullptr;
this->advertising_data_.appearance = 0;
}
err = esp_ble_gap_config_adv_data(&this->advertising_data_);
this->advertising_data_.manufacturer_len = manufacturer_len;
this->advertising_data_.p_manufacturer_data = manufacturer_data;
this->advertising_data_.appearance = appearance;
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gap_config_adv_data failed (Advertising): %s", esp_err_to_name(err));
return err;
}
this->configs_pending_++;
if (this->scan_response_) {
memcpy(&this->scan_response_data_, &this->advertising_data_, sizeof(esp_ble_adv_data_t));
this->scan_response_data_.set_scan_rsp = true;
this->scan_response_data_.include_name = true;
this->scan_response_data_.include_txpower = true;
this->scan_response_data_.manufacturer_len = 0;
this->scan_response_data_.appearance = 0;
this->scan_response_data_.flag = 0;
if (priority) {
// The other UUIDs; the service data is already in the advertising packet
this->scan_response_data_.service_uuid_len = 16 * (num_services - 1);
this->scan_response_data_.p_service_uuid = num_services > 1 ? uuids + 16 : nullptr;
this->scan_response_data_.service_data_len = 0;
this->scan_response_data_.p_service_data = nullptr;
} else {
this->scan_response_data_.manufacturer_len = 0;
this->scan_response_data_.p_manufacturer_data = nullptr;
this->scan_response_data_.appearance = 0;
}
err = esp_ble_gap_config_adv_data(&this->scan_response_data_);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gap_config_adv_data failed (Scan response): %s", esp_err_to_name(err));
return err;
}
}
if (this->advertising_data_.service_uuid_len > 0) {
delete[] this->advertising_data_.p_service_uuid;
this->advertising_data_.p_service_uuid = nullptr;
this->configs_pending_++;
}
err = esp_ble_gap_start_advertising(&this->advertising_params_);
@@ -134,6 +187,7 @@ void BLEAdvertising::start() {
}
void BLEAdvertising::stop() {
this->restart_pending_ = false;
esp_err_t err = esp_ble_gap_stop_advertising();
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gap_stop_advertising failed: %d", err);
@@ -145,6 +199,11 @@ void BLEAdvertising::stop() {
}
void BLEAdvertising::loop() {
// The only sender of the services advertising: after the event drain, once no config is in flight
if (this->restart_pending_ && !this->config_pending_()) {
this->restart_pending_ = false;
this->start();
}
if (this->raw_advertisements_callbacks_.empty()) {
return;
}
+19 -1
View File
@@ -31,17 +31,31 @@ class BLEAdvertising {
void set_service_data(const std::vector<uint8_t> &data);
void set_service_data(std::span<const uint8_t> data);
void set_include_name(bool include_name) { this->include_name_in_adv_ = include_name; }
/// Give `uuid` and up to 8 bytes of service data the advertising packet; the rest moves to the scan response.
void set_priority_uuid(ESPBTUUID uuid) { this->priority_uuid_ = uuid; }
void clear_priority_uuid() { this->priority_uuid_ = {}; }
void register_raw_advertisement_callback(std::function<void(bool)> &&callback);
void start();
void stop();
/// Send the services advertising from the next loop() once no config is in flight; loop() is the only sender.
void request_start() { this->restart_pending_ = true; }
void on_config_complete();
/// The stack was torn down and its pending completion events dropped.
void reset_config_state();
void cancel_deferred_restart() { this->restart_pending_ = false; }
protected:
esp_err_t services_advertisement_();
bool config_pending_() const;
bool scan_response_;
bool include_name_in_adv_{false};
esp_ble_adv_data_t advertising_data_;
// Low 16 bits of the loop time, in the padding before the aligned members. A gap over 65.5 s (only after a lost
// completion) can alias and hold one send back by up to 1 s, which is harmless.
uint16_t config_sent_time_{0};
ESPBTUUID priority_uuid_; // unset when no service has priority
esp_ble_adv_data_t advertising_data_; // p_service_uuid is only valid inside services_advertisement_()
esp_ble_adv_data_t scan_response_data_;
esp_ble_adv_params_t advertising_params_;
std::vector<ESPBTUUID> advertising_uuids_;
@@ -51,6 +65,10 @@ class BLEAdvertising {
const uint32_t advertising_cycle_time_;
uint32_t last_advertisement_time_{0};
int8_t current_adv_index_{-1}; // -1 means standard scan response
// Bluedroid keeps the last advertising and scan response config in one static buffer and builds the packet from it
// later on another task; a new config before that frees it under the builder. Count the configs in flight.
uint8_t configs_pending_{0};
bool restart_pending_{false};
};
} // namespace esphome::esp32_ble
@@ -195,6 +195,10 @@ void BLEServer::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t ga
// Resume advertising so additional clients can discover and connect
if (this->client_count_ < this->max_clients_) {
this->parent_->advertising_refresh();
} else if (param->connect.link_role == 1) {
// Full: the controller stopped advertising; a restart deferred before this connect must not reopen it.
// A link opened as a central (link_role 0) does not stop advertising, so a pending refresh still applies.
this->parent_->advertising_cancel_deferred();
}
this->dispatch_callbacks_(CallbackType::ON_CONNECT, param->connect.conn_id);
break;
@@ -527,6 +527,8 @@ void ImprovBLEComponent::request_advertising_() {
if (this->advertising_requested_)
return;
this->advertising_requested_ = true;
// Passive scanners only see the advertising packet
esp32_ble::global_ble->advertising_set_priority_uuid(ESPBTUUID::from_raw(improv::SERVICE_UUID));
esp32_ble::global_ble->advertising_start();
}
@@ -534,6 +536,7 @@ void ImprovBLEComponent::release_advertising_() {
if (!this->advertising_requested_)
return;
this->advertising_requested_ = false;
esp32_ble::global_ble->advertising_clear_priority_uuid();
esp32_ble::global_ble->advertising_stop();
}