ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
ble.cpp
Go to the documentation of this file.
1#include "ble.h"
2
3#ifdef USE_ESP32
4
7#include "esphome/core/log.h"
9
10#ifndef CONFIG_BT_CONTROLLER_DISABLED
11#include <esp_bt.h>
12#else
14#include <cinttypes>
15extern "C" {
16#include <esp_hosted.h>
17}
18#include <eh_host_bt.h>
19#include <esp_hosted_bt_host_stack.h>
20#endif
21#include <esp_bt_device.h>
22#include <esp_bt_main.h>
23#include <esp_gap_ble_api.h>
24#include <freertos/FreeRTOS.h>
25#include <freertos/FreeRTOSConfig.h>
26#include <freertos/task.h>
27
28#include <cstring>
29
30#ifdef USE_ARDUINO
31// Prevent Arduino from releasing BT memory at startup (esp32-hal-misc.c).
32// Without this, esp_bt_controller_init() fails with ESP_ERR_INVALID_STATE.
33extern "C" bool btInUse() { return true; } // NOLINT(readability-identifier-naming)
34#endif
35
36#if !defined(CONFIG_BT_CONTROLLER_DISABLED) && \
37 (defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32S3))
38// The ESP32-C3 and ESP32-S3 share one controller (lib_esp32c3_family, RivieraWaves link layer).
39#define USE_ESP32_BLE_TERMINATE_PATCH
40// Controller internals, reached through r_ip_funcs_p: a table btdm_controller_init() copies into RAM.
41extern "C" {
42extern void *r_ip_funcs_p;
44uint8_t r_lld_con_terminate_max_evt_update(uint8_t link_id, uint8_t acked);
46}
47#endif
48
50
51ESPHOME_LOG_TAG(TAG, "esp32_ble");
52
53#ifdef USE_ESP32_BLE_TERMINATE_PATCH
54// The controller ends its terminate procedure after 6 connection events without an acknowledgement and reports
55// the link closed. A peer using peripheral latency listens only every (latency + 1) events, so it can miss all
56// six LL_TERMINATE_IND: it keeps the link and searches for the central at full receive current until its own
57// supervision timeout. The Core spec keeps the procedure going until the acknowledgement or the supervision
58// timeout; this does that, by holding the controller's no-acknowledgement count below its limit. A peer that
59// never answers still ends the link at the supervision timeout.
60static constexpr size_t TERMINATE_MAX_EVT_SLOT = 0x7dc / sizeof(void *);
61static constexpr uint8_t TERMINATE_MAX_EVT = 5; // the controller gives up once its count exceeds this
62
63static uint8_t IRAM_ATTR terminate_until_acked(uint8_t link_id, uint8_t acked) {
64 // Per link: [2] terminate in progress, [3] connection events without an acknowledgement.
65 uint8_t *info = r_lld_con_cntl_pkt_info_get() + link_id * 4;
66 if (!acked && info[2] != 0 && info[3] >= TERMINATE_MAX_EVT)
67 info[3] = TERMINATE_MAX_EVT - 1;
68 return r_lld_con_terminate_max_evt_update(link_id, acked);
69}
70
71// The controller builds whose r_lld_con_terminate_max_evt_update and r_lld_con_cntl_pkt_info_get the wrapper was
72// checked against. The table slot alone does not prove the pkt_info layout, so an unknown build is left alone.
73// btdm_controller_get_compile_version() is what ESP-IDF logs at init as "BT controller compile version [...]".
74// Recheck on every ESP-IDF bump: add the new build once both functions are confirmed unchanged, or drop the patch once
75// espressif/esp-idf#19189 is fixed.
76static const char *const TERMINATE_PATCH_CONTROLLER_BUILDS[] = {
77 "51d9dfd", // ESP-IDF 5.5.5-5.5.6, Arduino 3.3.10-3.3.12
78 "b7de11e", // ESP-IDF 5.5.4, Arduino 3.3.8-3.3.9: both functions identical to 51d9dfd's
79};
80
81static void patch_terminate_until_acked() {
82 auto **table = static_cast<void **>(r_ip_funcs_p);
83 if (table == nullptr) {
84 ESP_LOGW(TAG, "Controller layout not recognised; disconnects keep the controller's 6-event limit");
85 return;
86 }
87 const char *build = btdm_controller_get_compile_version();
88 bool known_build = false;
89 for (const char *known : TERMINATE_PATCH_CONTROLLER_BUILDS)
90 known_build = known_build || strcmp(build, known) == 0;
91 if (!known_build) {
92 // Expected after an ESP-IDF bump, and nothing a user can act on
93 ESP_LOGD(TAG,
94 "Controller build %s not checked for the terminate patch; disconnects keep the controller's 6-event limit",
95 build);
96 return;
97 }
98 if (table[TERMINATE_MAX_EVT_SLOT] == reinterpret_cast<void *>(&terminate_until_acked))
99 return; // already patched: the controller stayed enabled across a setup
100 if (table[TERMINATE_MAX_EVT_SLOT] != reinterpret_cast<void *>(&r_lld_con_terminate_max_evt_update)) {
101 ESP_LOGW(TAG, "Controller build %s has an unexpected terminate handler; terminate patch skipped", build);
102 return;
103 }
104 table[TERMINATE_MAX_EVT_SLOT] = reinterpret_cast<void *>(&terminate_until_acked);
105}
106#endif
107
108#ifdef CONFIG_BT_CONTROLLER_DISABLED
109// Bringing up the remote BT controller issues synchronous RPCs to the
110// co-processor with 5 second response timeouts, and the default task watchdog
111// is also 5 seconds. If the co-processor firmware does not answer (for example
112// factory firmware without Bluetooth support), the watchdog would reboot the
113// device before the RPC could return an error, causing a boot loop. Raise the
114// watchdog for the duration of the bring-up so failures surface as error
115// returns instead. 60 seconds covers the worst case: transport reconnect
116// (up to ~20s), version preflight (1s), the controller init retry window
117// (5s of 5s RPCs), controller enable (5s) and the bluedroid host bring-up
118// over the hosted HCI transport.
119static constexpr uint32_t HOSTED_BT_WDT_TIMEOUT_MS = 60000;
120#endif
121
122// GAP event groups for deduplication across gap_event_handler and dispatch_gap_event_
123#define GAP_SCAN_COMPLETE_EVENTS \
124 case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT: \
125 case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT: \
126 case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT
127
128#define GAP_ADV_COMPLETE_EVENTS \
129 case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: \
130 case ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT: \
131 case ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT: \
132 case ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT: \
133 case ESP_GAP_BLE_ADV_START_COMPLETE_EVT: \
134 case ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT
135
136#define GAP_SECURITY_EVENTS \
137 case ESP_GAP_BLE_AUTH_CMPL_EVT: \
138 case ESP_GAP_BLE_SEC_REQ_EVT: \
139 case ESP_GAP_BLE_PASSKEY_NOTIF_EVT: \
140 case ESP_GAP_BLE_PASSKEY_REQ_EVT: \
141 case ESP_GAP_BLE_NC_REQ_EVT
142
144 global_ble = this;
145 // Preferences opens NVS in app_main(); a zero handle means it could not be opened, even after an erase
146 if (global_preferences->nvs_handle == 0) {
147 ESP_LOGE(TAG, "NVS unavailable");
148 this->mark_failed();
149 return;
150 }
151
152 this->state_ = BLE_COMPONENT_STATE_DISABLED;
153 if (this->enable_on_boot_) {
154 this->enable();
155 }
156}
157
158// Queue the transition for loop(). A pending transition the other way is
159// cancelled instead, since nothing was torn down or brought up yet; any other
160// state is already there or on its way.
161void ESP32BLE::request_state_(bool enable) {
162 if (enable) {
163 if (this->state_ == BLE_COMPONENT_STATE_DISABLED) {
164 this->state_ = BLE_COMPONENT_STATE_ENABLE;
165 } else if (this->state_ == BLE_COMPONENT_STATE_DISABLE) {
166 this->state_ = BLE_COMPONENT_STATE_ACTIVE;
167 }
168 } else {
169 if (this->state_ == BLE_COMPONENT_STATE_ACTIVE) {
170 this->state_ = BLE_COMPONENT_STATE_DISABLE;
171 } else if (this->state_ == BLE_COMPONENT_STATE_ENABLE) {
172 this->state_ = BLE_COMPONENT_STATE_DISABLED;
173 }
174 }
175}
176
177#ifdef USE_ESP32_BLE_ADVERTISING
179 this->advertising_init_();
180 this->advertising_ref_count_++;
181 this->advertising_refresh();
182}
183
185 if (this->advertising_ref_count_ == 0)
186 return;
187 this->advertising_ref_count_--;
188 this->advertising_refresh();
189}
190
192 if (this->advertising_ == nullptr || !this->is_active())
193 return;
194 // Advertise while any component still needs it, otherwise stop
195 if (this->advertising_ref_count_ == 0) {
196 this->advertising_->stop();
197 } else {
198 this->advertising_->request_start();
200 }
201}
202
203void ESP32BLE::advertising_set_service_data(const std::vector<uint8_t> &data) {
204 this->advertising_init_();
205 this->advertising_->set_service_data(data);
206 this->advertising_refresh();
207}
208
209void ESP32BLE::advertising_set_manufacturer_data(const std::vector<uint8_t> &data) {
210 this->advertising_init_();
211 this->advertising_->set_manufacturer_data(data);
212 this->advertising_refresh();
213}
214
215void ESP32BLE::advertising_set_service_data_and_name(std::span<const uint8_t> data, bool include_name) {
216 // This method atomically updates both service data and device name inclusion in BLE advertising.
217 // When include_name is true, the device name is included in the advertising packet making it
218 // visible to passive BLE scanners. When false, the name is only visible in scan response
219 // (requires active scanning). This atomic operation ensures we only restart advertising once
220 // when changing both properties, avoiding the brief gap that would occur with separate calls.
221
222 this->advertising_init_();
223
224 if (include_name) {
225 // When including name, clear service data first to avoid packet overflow
226 this->advertising_->set_service_data(std::span<const uint8_t>{});
227 this->advertising_->set_include_name(true);
228 } else {
229 // When including service data, clear name first to avoid packet overflow
230 this->advertising_->set_include_name(false);
231 this->advertising_->set_service_data(data);
232 }
233
234 this->advertising_refresh();
235}
236
237void ESP32BLE::advertising_register_raw_advertisement_callback(std::function<void(bool)> &&callback) {
238 this->advertising_init_();
239 this->advertising_->register_raw_advertisement_callback(std::move(callback));
240}
241
243 this->advertising_init_();
244 this->advertising_->add_service_uuid(uuid);
245 this->advertising_refresh();
246}
247
249 this->advertising_init_();
250 this->advertising_->set_priority_uuid(uuid);
251}
252
254 if (this->advertising_ != nullptr)
255 this->advertising_->clear_priority_uuid();
256}
257
259 this->advertising_init_();
260 this->advertising_->remove_service_uuid(uuid);
261 this->advertising_refresh();
262}
263#endif
264
265#ifdef USE_ESP32_BLE_ADVERTISING
267 if (this->advertising_ != nullptr)
268 return;
269 this->advertising_ = new BLEAdvertising(this->advertising_cycle_time_); // NOLINT(cppcoreguidelines-owning-memory)
270
271 this->advertising_->set_appearance(this->appearance_);
272}
273#endif
274
275const char *ESP32BLE::device_name(char *buffer) const {
276 if (this->name_ != nullptr) {
278 return this->name_;
279 // Last 6 characters of the 12 character MAC address string
280 constexpr size_t mac_address_suffix_len = 6;
281 char mac_addr[MAC_ADDRESS_BUFFER_SIZE];
283 make_name_with_suffix_to(buffer, DEVICE_NAME_BUFFER_SIZE, this->name_, strlen(this->name_), '-',
284 mac_addr + mac_address_suffix_len, mac_address_suffix_len);
285 return buffer;
286 }
287 const auto &app_name = App.get_name();
288 truncate_name_to(buffer, DEVICE_NAME_BUFFER_SIZE, app_name.c_str(), app_name.length(),
289 App.is_name_add_mac_suffix_enabled() ? MAC_ADDRESS_SUFFIX_WITH_SEPARATOR_LEN : 0);
290 return buffer;
291}
292
294 esp_err_t err;
295#ifdef CONFIG_BT_CONTROLLER_DISABLED
296 watchdog::WatchdogManager wdt(HOSTED_BT_WDT_TIMEOUT_MS);
297#endif
298#ifndef CONFIG_BT_CONTROLLER_DISABLED
299 if (esp_bt_controller_get_status() != ESP_BT_CONTROLLER_STATUS_ENABLED) {
300 // start bt controller
301 if (esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_IDLE) {
302 esp_bt_controller_config_t cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
303 err = esp_bt_controller_init(&cfg);
304 if (err != ESP_OK) {
305 ESP_LOGE(TAG, "esp_bt_controller_init failed: %s", esp_err_to_name(err));
306 return false;
307 }
308 while (esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_IDLE)
309 ;
310 }
311 if (esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_INITED) {
312 err = esp_bt_controller_enable(ESP_BT_MODE_BLE);
313 if (err != ESP_OK) {
314 ESP_LOGE(TAG, "esp_bt_controller_enable failed: %s", esp_err_to_name(err));
315 return false;
316 }
317 }
318 if (esp_bt_controller_get_status() != ESP_BT_CONTROLLER_STATUS_ENABLED) {
319 ESP_LOGE(TAG, "esp bt controller enable failed");
320 return false;
321 }
322 }
323#ifdef USE_ESP32_BLE_TERMINATE_PATCH
324 patch_terminate_until_acked();
325#endif
326
327 esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT);
328#else
329 if (esp_hosted_connect_to_slave() != ESP_OK) { // NOLINT
330 ESP_LOGE(TAG, "Co-processor transport failed; BLE disabled");
331 return false;
332 }
333
334 // Fast preflight (1 second RPC timeout): verifies the co-processor answers
335 // RPCs at all before the 5 second timeout BT controller RPCs below.
336 esp_hosted_coprocessor_fwver_t fw_ver{};
337 if (esp_hosted_get_coprocessor_fwversion(&fw_ver) != ESP_OK) {
338 ESP_LOGE(TAG, "Co-processor not responding; BLE disabled. Update its firmware with the esp32_hosted "
339 "update component");
340 return false;
341 }
342 ESP_LOGD(TAG, "Co-processor firmware %" PRIu32 ".%" PRIu32 ".%" PRIu32, fw_ver.major1, fw_ver.minor1, fw_ver.patch1);
343
344 // Not the library's bring-up: its retry loop can block for minutes on a silent co-processor
345 err = eh_host_bt_controller_init();
346 if (err != ESP_OK && err != ESP_ERR_INVALID_STATE) {
347 ESP_LOGE(TAG,
348 "BT controller init failed; co-processor firmware %" PRIu32 ".%" PRIu32 ".%" PRIu32
349 " may lack BT support. Update it with the esp32_hosted update component; BLE disabled",
350 fw_ver.major1, fw_ver.minor1, fw_ver.patch1);
351 return false;
352 }
353 err = eh_host_bt_controller_enable();
354 if (err != ESP_OK && err != ESP_ERR_INVALID_STATE) {
355 ESP_LOGE(TAG, "BT controller enable failed: %s; BLE disabled", esp_err_to_name(err));
356 return false;
357 }
358
359 esp_hosted_bt_host_stack_cfg_t bt_cfg{};
360 bt_cfg.stack = ESP_HOSTED_BT_HOST_STACK_BLUEDROID;
361 bt_cfg.bring_up_controller = false;
362 if (esp_hosted_bt_host_stack_setup(&bt_cfg) != ESP_OK) {
363 ESP_LOGE(TAG, "BT host stack setup failed; BLE disabled");
364 return false;
365 }
366#endif
367
368 err = esp_bluedroid_init();
369 if (err != ESP_OK) {
370 ESP_LOGE(TAG, "esp_bluedroid_init failed: %d", err);
371 return false;
372 }
373 err = esp_bluedroid_enable();
374 if (err != ESP_OK) {
375 ESP_LOGE(TAG, "esp_bluedroid_enable failed: %d", err);
376 return false;
377 }
378
379#ifdef ESPHOME_ESP32_BLE_GAP_EVENT_HANDLER_COUNT
380 err = esp_ble_gap_register_callback(ESP32BLE::gap_event_handler);
381 if (err != ESP_OK) {
382 ESP_LOGE(TAG, "esp_ble_gap_register_callback failed: %d", err);
383 return false;
384 }
385#endif
386
387#if defined(USE_ESP32_BLE_SERVER) && defined(ESPHOME_ESP32_BLE_GATTS_EVENT_HANDLER_COUNT)
388 err = esp_ble_gatts_register_callback(ESP32BLE::gatts_event_handler);
389 if (err != ESP_OK) {
390 ESP_LOGE(TAG, "esp_ble_gatts_register_callback failed: %d", err);
391 return false;
392 }
393#endif
394
395#if defined(USE_ESP32_BLE_CLIENT) && defined(ESPHOME_ESP32_BLE_GATTC_EVENT_HANDLER_COUNT)
396 err = esp_ble_gattc_register_callback(ESP32BLE::gattc_event_handler);
397 if (err != ESP_OK) {
398 ESP_LOGE(TAG, "esp_ble_gattc_register_callback failed: %d", err);
399 return false;
400 }
401#endif
402
403 char name_buffer[DEVICE_NAME_BUFFER_SIZE];
404 const char *device_name = this->device_name(name_buffer);
405 err = esp_ble_gap_set_device_name(device_name);
406 if (err != ESP_OK) {
407 ESP_LOGE(TAG, "esp_ble_gap_set_device_name failed: %d", err);
408 return false;
409 }
410
411 err = esp_ble_gap_set_security_param(ESP_BLE_SM_IOCAP_MODE, &(this->io_cap_), sizeof(esp_ble_io_cap_t));
412 if (err != ESP_OK) {
413 ESP_LOGE(TAG, "esp_ble_gap_set_security_param iocap_mode failed: %d", err);
414 return false;
415 }
416
417#ifdef ESPHOME_ESP32_BLE_EXTENDED_AUTH_PARAMS
418 if (this->max_key_size_) {
419 err = esp_ble_gap_set_security_param(ESP_BLE_SM_MAX_KEY_SIZE, &(this->max_key_size_), sizeof(uint8_t));
420 if (err != ESP_OK) {
421 ESP_LOGE(TAG, "esp_ble_gap_set_security_param max_key_size failed: %d", err);
422 return false;
423 }
424 }
425
426 if (this->min_key_size_) {
427 err = esp_ble_gap_set_security_param(ESP_BLE_SM_MIN_KEY_SIZE, &(this->min_key_size_), sizeof(uint8_t));
428 if (err != ESP_OK) {
429 ESP_LOGE(TAG, "esp_ble_gap_set_security_param min_key_size failed: %d", err);
430 return false;
431 }
432 }
433
434 if (this->auth_req_mode_) {
435 err = esp_ble_gap_set_security_param(ESP_BLE_SM_AUTHEN_REQ_MODE, &(this->auth_req_mode_.value()),
436 sizeof(esp_ble_auth_req_t));
437 if (err != ESP_OK) {
438 ESP_LOGE(TAG, "esp_ble_gap_set_security_param authen_req_mode failed: %d", err);
439 return false;
440 }
441 }
442#endif // ESPHOME_ESP32_BLE_EXTENDED_AUTH_PARAMS
443
444 // BLE takes some time to be fully set up, 200ms should be more than enough
445 delay(200); // NOLINT
446
447 return true;
448}
449
451#ifdef CONFIG_BT_CONTROLLER_DISABLED
452 // Same 5 second RPCs as the bring-up path; see HOSTED_BT_WDT_TIMEOUT_MS
453 watchdog::WatchdogManager wdt(HOSTED_BT_WDT_TIMEOUT_MS);
454#endif
455 esp_err_t err = esp_bluedroid_disable();
456 if (err != ESP_OK) {
457 // ESP_ERR_INVALID_STATE means Bluedroid is already disabled, which is fine
458 if (err != ESP_ERR_INVALID_STATE) {
459 ESP_LOGE(TAG, "esp_bluedroid_disable failed: %d", err);
460 return false;
461 }
462 ESP_LOGD(TAG, "Already disabled");
463 }
464 err = esp_bluedroid_deinit();
465 if (err != ESP_OK) {
466 // ESP_ERR_INVALID_STATE means Bluedroid is already deinitialized, which is fine
467 if (err != ESP_ERR_INVALID_STATE) {
468 ESP_LOGE(TAG, "esp_bluedroid_deinit failed: %d", err);
469 return false;
470 }
471 ESP_LOGD(TAG, "Already deinitialized");
472 }
473
474#ifndef CONFIG_BT_CONTROLLER_DISABLED
475 if (esp_bt_controller_get_status() != ESP_BT_CONTROLLER_STATUS_IDLE) {
476 // stop bt controller
477 if (esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_ENABLED) {
478 err = esp_bt_controller_disable();
479 if (err != ESP_OK) {
480 ESP_LOGE(TAG, "esp_bt_controller_disable failed: %s", esp_err_to_name(err));
481 return false;
482 }
483 while (esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_ENABLED)
484 ;
485 }
486 if (esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_INITED) {
487 err = esp_bt_controller_deinit();
488 if (err != ESP_OK) {
489 ESP_LOGE(TAG, "esp_bt_controller_deinit failed: %s", esp_err_to_name(err));
490 return false;
491 }
492 }
493 if (esp_bt_controller_get_status() != ESP_BT_CONTROLLER_STATUS_IDLE) {
494 ESP_LOGE(TAG, "esp bt controller disable failed");
495 return false;
496 }
497 }
498#else
499 if (esp_hosted_bt_host_stack_teardown() != ESP_OK) {
500 ESP_LOGE(TAG, "esp_hosted_bt_host_stack_teardown failed");
501 return false;
502 }
503#endif
504 return true;
505}
506
508 if (this->state_ != BLE_COMPONENT_STATE_ACTIVE) {
509 this->loop_handle_state_transition_not_active_();
510 return;
511 }
512
513 BLEEvent *ble_event = this->ble_events_.pop();
514 if (ble_event == nullptr) {
515 this->advertising_loop_();
516 return;
517 }
518
519 do {
520 switch (ble_event->type_) {
521#if defined(USE_ESP32_BLE_SERVER) && defined(ESPHOME_ESP32_BLE_GATTS_EVENT_HANDLER_COUNT)
522 case BLEEvent::GATTS: {
523 esp_gatts_cb_event_t event = ble_event->event_.gatts.gatts_event;
524 esp_gatt_if_t gatts_if = ble_event->event_.gatts.gatts_if;
525 esp_ble_gatts_cb_param_t *param = &ble_event->event_.gatts.gatts_param;
526 ESP_LOGV(TAG, "gatts_event [esp_gatt_if: %d] - %d", gatts_if, event);
527#ifdef USE_ESP32_BLE_ADVERTISING
528 // A peripheral connect stops advertising, so drop a queued send; a handler that wants more refreshes again
529 if (event == ESP_GATTS_CONNECT_EVT && param->connect.link_role == 1)
531#endif
532 this->gatts_event_callbacks_.call(event, gatts_if, param);
533 break;
534 }
535#endif
536#if defined(USE_ESP32_BLE_CLIENT) && defined(ESPHOME_ESP32_BLE_GATTC_EVENT_HANDLER_COUNT)
537 case BLEEvent::GATTC: {
538 esp_gattc_cb_event_t event = ble_event->event_.gattc.gattc_event;
539 esp_gatt_if_t gattc_if = ble_event->event_.gattc.gattc_if;
540 esp_ble_gattc_cb_param_t *param = &ble_event->event_.gattc.gattc_param;
541 ESP_LOGV(TAG, "gattc_event [esp_gatt_if: %d] - %d", gattc_if, event);
542 this->gattc_event_callbacks_.call(event, gattc_if, param);
543 break;
544 }
545#endif
546 case BLEEvent::GAP: {
547 esp_gap_ble_cb_event_t gap_event = ble_event->event_.gap.gap_event;
548 switch (gap_event) {
549 case ESP_GAP_BLE_SCAN_RESULT_EVT:
550#ifdef ESPHOME_ESP32_BLE_GAP_SCAN_EVENT_HANDLER_COUNT
551 this->gap_scan_event_callbacks_.call(ble_event->scan_result());
552#endif
553 break;
554
555 // Scan complete events
556 GAP_SCAN_COMPLETE_EVENTS:
557 // Advertising complete events
558 GAP_ADV_COMPLETE_EVENTS:
559 // RSSI complete event
560 case ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT:
561 // Security events
562 GAP_SECURITY_EVENTS:
563 ESP_LOGV(TAG, "gap_event_handler - %d", gap_event);
564#ifdef ESPHOME_ESP32_BLE_GAP_EVENT_HANDLER_COUNT
565 {
566 esp_ble_gap_cb_param_t *param = NULL;
567 // clang-format off
568 switch (gap_event) {
569 // All three scan complete events have the same structure with just status
570 // The scan_complete struct matches ESP-IDF's layout exactly, so this reinterpret_cast is safe
571 // This is verified at compile-time by static_assert checks in ble_event.h
572 // The struct already contains our copy of the status (copied in BLEEvent constructor)
573 GAP_SCAN_COMPLETE_EVENTS:
574 param = reinterpret_cast<esp_ble_gap_cb_param_t *>(&ble_event->event_.gap.scan_complete);
575 break;
576
577 // All advertising complete events have the same structure with just status
578 GAP_ADV_COMPLETE_EVENTS:
579 param = reinterpret_cast<esp_ble_gap_cb_param_t *>(&ble_event->event_.gap.adv_complete);
580 break;
581
582 case ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT:
583 param = reinterpret_cast<esp_ble_gap_cb_param_t *>(&ble_event->event_.gap.read_rssi_complete);
584 break;
585
586 GAP_SECURITY_EVENTS:
587 param = reinterpret_cast<esp_ble_gap_cb_param_t *>(&ble_event->event_.gap.security);
588 break;
589
590 default:
591 break;
592 }
593 // clang-format on
594 // Dispatch to all registered handlers
595 this->gap_event_callbacks_.call(gap_event, param);
596 }
597#endif
598 break;
599
600 default:
601 // Unknown/unhandled event
602 ESP_LOGW(TAG, "Unhandled GAP event type in loop: %d", gap_event);
603 break;
604 }
605 break;
606 }
607 default:
608 break;
609 }
610 // Return the event to the pool
611 this->ble_event_pool_.release(ble_event);
612 } while ((ble_event = this->ble_events_.pop()) != nullptr);
613
614 // Log dropped events - only reachable when events were processed.
615 // Drops only occur when the queue is full, and only this loop drains it,
616 // so if pop() returned nullptr above we can skip this check (saves a memw).
617 uint16_t dropped = this->ble_events_.get_and_reset_dropped_count();
618 if (dropped > 0) {
619 ESP_LOGW(TAG, "Dropped %u BLE events due to buffer overflow", dropped);
620 }
621 // After the events, so refreshes they trigger go out in this pass
622 this->advertising_loop_();
623}
624
625void ESP32BLE::loop_handle_state_transition_not_active_() {
626 // Caller ensures state_ != ACTIVE
627 if (this->state_ == BLE_COMPONENT_STATE_DISABLE) {
628 ESP_LOGD(TAG, "Disabling");
629
630#ifdef ESPHOME_ESP32_BLE_BLE_STATUS_EVENT_HANDLER_COUNT
631 this->ble_status_event_callbacks_.call();
632#endif
633
634 if (!ble_dismantle_()) {
635 ESP_LOGE(TAG, "Could not be dismantled");
636 this->mark_failed();
637 return;
638 }
639 this->drain_ble_events_();
640#ifdef USE_ESP32_BLE_ADVERTISING
642#endif
643 // A status callback may have asked for BLE back; the stack is down now, so
644 // that request becomes a bring-up.
645 this->state_ =
647 } else if (this->state_ == BLE_COMPONENT_STATE_ENABLE) {
648 ESP_LOGD(TAG, "Enabling");
649 this->state_ = BLE_COMPONENT_STATE_OFF;
650
651 if (!ble_setup_()) {
652 ESP_LOGE(TAG, "Could not be set up");
653 this->mark_failed();
654 return;
655 }
656
657 this->state_ = BLE_COMPONENT_STATE_ACTIVE;
658#ifdef USE_ESP32_BLE_ADVERTISING
659 // Requests made before the stack was up (or before it was re-enabled) take effect now
660 this->advertising_refresh();
661#endif
662 }
663}
664
665// Helper function to load new event data based on type
666void load_ble_event(BLEEvent *event, esp_gap_ble_cb_event_t e, esp_ble_gap_cb_param_t *p) {
667 event->load_gap_event(e, p);
668}
669
670#ifdef USE_ESP32_BLE_CLIENT
671void load_ble_event(BLEEvent *event, esp_gattc_cb_event_t e, esp_gatt_if_t i, esp_ble_gattc_cb_param_t *p) {
672 event->load_gattc_event(e, i, p);
673}
674#endif
675
676#ifdef USE_ESP32_BLE_SERVER
677void load_ble_event(BLEEvent *event, esp_gatts_cb_event_t e, esp_gatt_if_t i, esp_ble_gatts_cb_param_t *p) {
678 event->load_gatts_event(e, i, p);
679}
680#endif
681
682template<typename... Args> void enqueue_ble_event(Args... args) {
683 // Allocate an event from the pool
684 BLEEvent *event = global_ble->ble_event_pool_.allocate();
685 if (event == nullptr) {
686 // No events available - queue is full or we're out of memory
687 global_ble->ble_events_.increment_dropped_count();
688 return;
689 }
690
691 // Load new event data (replaces previous event)
692 load_ble_event(event, args...);
693
694 // Push the event to the queue
695 // Push always succeeds: pool is sized to queue capacity (N-1), so if
696 // allocate() returned non-null, the queue is guaranteed to have room.
697 global_ble->ble_events_.push(event);
698}
699
700// Explicit template instantiations for the friend function
701template void enqueue_ble_event(esp_gap_ble_cb_event_t, esp_ble_gap_cb_param_t *);
702#ifdef USE_ESP32_BLE_SERVER
703template void enqueue_ble_event(esp_gatts_cb_event_t, esp_gatt_if_t, esp_ble_gatts_cb_param_t *);
704#endif
705#ifdef USE_ESP32_BLE_CLIENT
706template void enqueue_ble_event(esp_gattc_cb_event_t, esp_gatt_if_t, esp_ble_gattc_cb_param_t *);
707#endif
708
709void ESP32BLE::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
710 switch (event) {
711 // Queue GAP events that components need to handle
712 // Scanning events - used by esp32_ble_tracker
713 case ESP_GAP_BLE_SCAN_RESULT_EVT:
714 GAP_SCAN_COMPLETE_EVENTS:
715 // Advertising events - used by esp32_ble_beacon and esp32_ble server
716 GAP_ADV_COMPLETE_EVENTS:
717 // Connection events - used by ble_client
718 case ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT:
719 enqueue_ble_event(event, param);
720 return;
721
722 // Security events - used by ble_client and bluetooth_proxy
723 // These are rare but interactive (pairing/bonding), so notify immediately
724 GAP_SECURITY_EVENTS:
725 enqueue_ble_event(event, param);
726 // Wake up main loop to process security event immediately
728 return;
729
730 // Log the result of connection parameter updates: a peer can reject or
731 // never answer an update, and without this the link silently stays on the
732 // old parameters (visible only as unexplained supervision timeouts).
733 case ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT: {
734 // A peer can keep asking for parameters it then rejects: warn once per peer, repeats are
735 // verbose until an update succeeds or it disconnects.
736 if (param->update_conn_params.status != ESP_BT_STATUS_SUCCESS) {
737 char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
738 format_mac_addr_upper(param->update_conn_params.bda, mac_s);
739 if (global_ble->conn_param_failed_slot_(param->update_conn_params.bda) != nullptr) {
740 ESP_LOGV(TAG, "[%s] Conn param update failed again, status=%d", mac_s, param->update_conn_params.status);
741 } else {
742 ESP_LOGW(TAG, "[%s] Conn param update failed, status=%d", mac_s, param->update_conn_params.status);
743 static constexpr esp_bd_addr_t FREE{};
744 uint8_t *slot = global_ble->conn_param_failed_slot_(FREE);
745 if (slot != nullptr)
746 memcpy(slot, param->update_conn_params.bda, sizeof(esp_bd_addr_t));
747 }
748 } else {
749 global_ble->forget_conn_param_failure_(param->update_conn_params.bda);
750#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
751 char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
752 format_mac_addr_upper(param->update_conn_params.bda, mac_s);
753 ESP_LOGV(TAG, "[%s] Conn params updated: interval=%u (x1.25ms) latency=%u timeout=%u (x10ms)", mac_s,
754 param->update_conn_params.conn_int, param->update_conn_params.latency,
755 param->update_conn_params.timeout);
756#endif
757 }
758 return;
759 }
760
761 // Ignore these GAP events as they are not relevant for our use case
762 case ESP_GAP_BLE_KEY_EVT:
763 case ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT:
764 case ESP_GAP_BLE_PHY_UPDATE_COMPLETE_EVT: // BLE 5.0 PHY update complete
765 case ESP_GAP_BLE_CHANNEL_SELECT_ALGORITHM_EVT: // BLE 5.0 channel selection algorithm
766 case ESP_GAP_BLE_LOCAL_IR_EVT: // Local identity root key generated at security init
767 case ESP_GAP_BLE_LOCAL_ER_EVT: // Local encryption root key generated at security init
768 return;
769
770 default:
771 break;
772 }
773 ESP_LOGW(TAG, "Ignoring unexpected GAP event type: %d", event);
774}
775
776#ifdef USE_ESP32_BLE_SERVER
777void ESP32BLE::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if,
778 esp_ble_gatts_cb_param_t *param) {
779 if (event == ESP_GATTS_DISCONNECT_EVT)
780 global_ble->forget_conn_param_failure_(param->disconnect.remote_bda);
781 enqueue_ble_event(event, gatts_if, param);
782 // Wake up main loop to process GATT event immediately
784}
785#endif
786
787#ifdef USE_ESP32_BLE_CLIENT
788void ESP32BLE::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
789 esp_ble_gattc_cb_param_t *param) {
790 if (event == ESP_GATTC_DISCONNECT_EVT)
791 global_ble->forget_conn_param_failure_(param->disconnect.remote_bda);
792 enqueue_ble_event(event, gattc_if, param);
793 // Wake up main loop to process GATT event immediately
795}
796#endif
797
798uint8_t *ESP32BLE::conn_param_failed_slot_(const uint8_t *bda) {
799 for (auto &slot : this->conn_param_failed_bdas_) {
800 if (memcmp(slot, bda, sizeof(esp_bd_addr_t)) == 0)
801 return slot;
802 }
803 return nullptr;
804}
805
806void ESP32BLE::forget_conn_param_failure_(const uint8_t *bda) {
807 uint8_t *slot = this->conn_param_failed_slot_(bda);
808 if (slot != nullptr)
809 memset(slot, 0, sizeof(esp_bd_addr_t));
810}
811
812void ESP32BLE::get_mac_msb_first(uint8_t out[MAC_ADDRESS_SIZE]) const {
813 // The running stack owns the address (on hosted controllers it lives in
814 // the remote chip's efuse); null before init becomes all-zero.
815 const uint8_t *mac = esp_bt_dev_get_address();
816 if (mac != nullptr) {
817 memcpy(out, mac, MAC_ADDRESS_SIZE);
818 } else {
819 memset(out, 0, MAC_ADDRESS_SIZE);
820 }
821}
822
824
826 uint8_t mac_address[MAC_ADDRESS_SIZE];
827 this->get_mac_msb_first(mac_address);
828 if (mac_address_is_valid(mac_address)) {
829 const char *io_capability_s;
830 switch (this->io_cap_) {
831 case ESP_IO_CAP_OUT:
832 io_capability_s = "display_only";
833 break;
834 case ESP_IO_CAP_IO:
835 io_capability_s = "display_yes_no";
836 break;
837 case ESP_IO_CAP_IN:
838 io_capability_s = "keyboard_only";
839 break;
840 case ESP_IO_CAP_NONE:
841 io_capability_s = "none";
842 break;
843 case ESP_IO_CAP_KBDISP:
844 io_capability_s = "keyboard_display";
845 break;
846 default:
847 io_capability_s = "invalid";
848 break;
849 }
850
851 char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
852 format_mac_addr_upper(mac_address, mac_s);
853 ESP_LOGCONFIG(TAG,
854 "BLE:\n"
855 " MAC address: %s\n"
856 " IO Capability: %s",
857 mac_s, io_capability_s);
858#ifdef USE_ESP32_BLE_PSRAM
859 ESP_LOGCONFIG(TAG, " PSRAM BLE allocation: enabled");
860#endif
861
862#ifdef ESPHOME_ESP32_BLE_EXTENDED_AUTH_PARAMS
863 const char *auth_req_mode_s = "<default>";
864 if (this->auth_req_mode_) {
865 switch (this->auth_req_mode_.value()) {
866 case AUTH_REQ_NO_BOND:
867 auth_req_mode_s = "no_bond";
868 break;
869 case AUTH_REQ_BOND:
870 auth_req_mode_s = "bond";
871 break;
872 case AUTH_REQ_MITM:
873 auth_req_mode_s = "mitm";
874 break;
876 auth_req_mode_s = "bond_mitm";
877 break;
878 case AUTH_REQ_SC_ONLY:
879 auth_req_mode_s = "sc_only";
880 break;
881 case AUTH_REQ_SC_BOND:
882 auth_req_mode_s = "sc_bond";
883 break;
884 case AUTH_REQ_SC_MITM:
885 auth_req_mode_s = "sc_mitm";
886 break;
888 auth_req_mode_s = "sc_mitm_bond";
889 break;
890 }
891 }
892
893 ESP_LOGCONFIG(TAG, " Auth Req Mode: %s", auth_req_mode_s);
894 if (this->max_key_size_ && this->min_key_size_) {
895 ESP_LOGCONFIG(TAG, " Key Size: %u - %u", this->min_key_size_, this->max_key_size_);
896 } else if (this->max_key_size_) {
897 ESP_LOGCONFIG(TAG, " Key Size: <default> - %u", this->max_key_size_);
898 } else if (this->min_key_size_) {
899 ESP_LOGCONFIG(TAG, " Key Size: %u - <default>", this->min_key_size_);
900 }
901#endif // ESPHOME_ESP32_BLE_EXTENDED_AUTH_PARAMS
902
903 } else {
904 ESP_LOGCONFIG(TAG, "Bluetooth stack is not enabled");
905 }
906}
907
908ESP32BLE *global_ble = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
909
910} // namespace esphome::esp32_ble
911
912#endif
void * r_ip_funcs_p
const char * btdm_controller_get_compile_version()
uint8_t r_lld_con_terminate_max_evt_update(uint8_t link_id, uint8_t acked)
uint8_t * r_lld_con_cntl_pkt_info_get()
bool btInUse()
Definition ble.cpp:33
const StringRef & get_name() const
Get the name of this Application set by pre_setup().
void wake_loop_threadsafe()
Wake the main event loop from another thread or callback.
bool is_name_add_mac_suffix_enabled() const
void mark_failed()
Mark this component as failed.
void set_manufacturer_data(const std::vector< uint8_t > &data)
void set_include_name(bool include_name)
void set_priority_uuid(ESPBTUUID uuid)
Give uuid and the service data the advertising packet; the rest moves to the scan response.
void set_service_data(const std::vector< uint8_t > &data)
void register_raw_advertisement_callback(std::function< void(bool)> &&callback)
void set_appearance(uint16_t appearance)
void request_start()
Send from the next loop(): a burst of refreshes becomes one send instead of flooding the Bluetooth ta...
struct esphome::esp32_ble::BLEEvent::@79::gap_event gap
struct esphome::esp32_ble::BLEEvent::@79::gatts_event gatts
union esphome::esp32_ble::BLEEvent::@79 event_
struct esphome::esp32_ble::BLEEvent::@79::gattc_event gattc
void advertising_set_manufacturer_data(const std::vector< uint8_t > &data)
Definition ble.cpp:209
void get_mac_msb_first(uint8_t out[MAC_ADDRESS_SIZE]) const
Adapter MAC in printable (MSB-first) order; all-zero until the stack is up.
Definition ble.cpp:812
ESPHOME_ALWAYS_INLINE void advertising_loop_()
Definition ble.h:198
static void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
Definition ble.cpp:709
static constexpr size_t DEVICE_NAME_BUFFER_SIZE
Definition ble.h:116
const char * device_name(char *buffer) const
The device name; written to buffer unless the configured name is used as is.
Definition ble.cpp:275
static void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param)
Definition ble.cpp:788
void advertising_start()
Request advertising on behalf of a component.
Definition ble.cpp:178
void advertising_refresh()
Apply the current payload and request count: advertise while requested, otherwise stop.
Definition ble.cpp:191
friend void enqueue_ble_event(Args... args)
Definition ble.cpp:682
void forget_conn_param_failure_(const uint8_t *bda)
Definition ble.cpp:806
uint8_t * conn_param_failed_slot_(const uint8_t *bda)
Definition ble.cpp:798
void advertising_register_raw_advertisement_callback(std::function< void(bool)> &&callback)
Definition ble.cpp:237
void advertising_set_service_data_and_name(std::span< const uint8_t > data, bool include_name)
Definition ble.cpp:215
void advertising_add_service_uuid(ESPBTUUID uuid)
Definition ble.cpp:242
void advertising_cancel_start_()
Definition ble.h:206
void advertising_clear_priority_uuid()
Definition ble.cpp:253
void dump_config() override
Definition ble.cpp:825
void request_state_(bool enable)
Definition ble.cpp:161
void loop() override
Definition ble.cpp:507
static void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param)
Definition ble.cpp:777
void advertising_set_priority_uuid(ESPBTUUID uuid)
Keep uuid and the service data alone in the advertising packet; applies on the next refresh.
Definition ble.cpp:248
void advertising_set_service_data(const std::vector< uint8_t > &data)
Definition ble.cpp:203
ESPHOME_ALWAYS_INLINE bool is_active()
Definition ble.h:107
float get_setup_priority() const override
Definition ble.cpp:823
void setup() override
Definition ble.cpp:143
void advertising_stop()
Release a request made with advertising_start(); advertising stops at the last release.
Definition ble.cpp:184
void advertising_remove_service_uuid(ESPBTUUID uuid)
Definition ble.cpp:258
std::vector< uint8_t > & out
Definition gif.cpp:49
uint32_t buffer
Definition gif.cpp:50
ESP32BLE * global_ble
Definition ble.cpp:908
void load_ble_event(BLEEvent *event, esp_gap_ble_cb_event_t e, esp_ble_gap_cb_param_t *p)
Definition ble.cpp:666
@ BLE_COMPONENT_STATE_DISABLE
BLE should be disabled on next loop.
Definition ble.h:81
@ BLE_COMPONENT_STATE_OFF
Nothing has been initialized yet.
Definition ble.h:79
@ BLE_COMPONENT_STATE_ENABLE
BLE should be enabled on next loop.
Definition ble.h:85
@ BLE_COMPONENT_STATE_DISABLED
BLE is disabled.
Definition ble.h:83
@ BLE_COMPONENT_STATE_ACTIVE
BLE is active.
Definition ble.h:87
@ AUTH_REQ_SC_MITM_BOND
Definition ble.h:73
@ AUTH_REQ_BOND_MITM
Definition ble.h:69
void enqueue_ble_event(Args... args)
Definition ble.cpp:682
ESPHOME_LOG_TAG(TAG, "esp32_ble")
constexpr float BLUETOOTH
Definition component.h:48
static uint64_t const uint8_t * table
Definition vnc_des.cpp:92
size_t make_name_with_suffix_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, char sep, const char *suffix_ptr, size_t suffix_len)
Format name + separator + suffix directly into buffer without heap allocation.
Definition helpers.cpp:277
size_t truncate_name_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, size_t keep_suffix_len)
Copy a name into a buffer, cutting it when it does not fit.
Definition helpers.cpp:297
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Definition helpers.cpp:865
ESPPreferences * global_preferences
void get_mac_address_into_buffer(std::span< char, MAC_ADDRESS_BUFFER_SIZE > buf)
Get the device MAC address into the given buffer, in lowercase hex notation.
Definition helpers.cpp:848
void HOT delay(uint32_t ms)
Definition hal.cpp:85
Application App
Global storage of Application pointer - only one Application can exist.
char * format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase, colon separators)
Definition helpers.h:1754
static void uint32_t