ESPHome 2026.10.0-dev
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"
8
9#ifndef CONFIG_ESP_HOSTED_ENABLE_BT_BLUEDROID
10#include <esp_bt.h>
11#else
13#include <cinttypes>
14extern "C" {
15#include <esp_hosted.h>
16#include <esp_hosted_misc.h>
17#include <esp_hosted_bluedroid.h>
18}
19#endif
20#include <esp_bt_device.h>
21#include <esp_bt_main.h>
22#include <esp_gap_ble_api.h>
23#include <freertos/FreeRTOS.h>
24#include <freertos/FreeRTOSConfig.h>
25#include <freertos/task.h>
26#include <nvs_flash.h>
27
28#ifdef USE_ARDUINO
29// Prevent Arduino from releasing BT memory at startup (esp32-hal-misc.c).
30// Without this, esp_bt_controller_init() fails with ESP_ERR_INVALID_STATE.
31extern "C" bool btInUse() { return true; } // NOLINT(readability-identifier-naming)
32#endif
33
35
36static const char *const TAG = "esp32_ble";
37
38#ifdef CONFIG_ESP_HOSTED_ENABLE_BT_BLUEDROID
39// Bringing up the remote BT controller issues synchronous RPCs to the
40// co-processor with 5 second response timeouts, and the default task watchdog
41// is also 5 seconds. If the co-processor firmware does not answer (for example
42// factory firmware without Bluetooth support), the watchdog would reboot the
43// device before the RPC could return an error, causing a boot loop. Raise the
44// watchdog for the duration of the bring-up so failures surface as error
45// returns instead. 60 seconds covers the worst case: transport reconnect
46// (up to ~20s), version preflight (1s), controller init/enable (5s each) and
47// the bluedroid host bring-up over the hosted HCI transport.
48static constexpr uint32_t HOSTED_BT_WDT_TIMEOUT_MS = 60000;
49#endif
50
51// GAP event groups for deduplication across gap_event_handler and dispatch_gap_event_
52#define GAP_SCAN_COMPLETE_EVENTS \
53 case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT: \
54 case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT: \
55 case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT
56
57#define GAP_ADV_COMPLETE_EVENTS \
58 case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: \
59 case ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT: \
60 case ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT: \
61 case ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT: \
62 case ESP_GAP_BLE_ADV_START_COMPLETE_EVT: \
63 case ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT
64
65#define GAP_SECURITY_EVENTS \
66 case ESP_GAP_BLE_AUTH_CMPL_EVT: \
67 case ESP_GAP_BLE_SEC_REQ_EVT: \
68 case ESP_GAP_BLE_PASSKEY_NOTIF_EVT: \
69 case ESP_GAP_BLE_PASSKEY_REQ_EVT: \
70 case ESP_GAP_BLE_NC_REQ_EVT
71
73 global_ble = this;
74 if (!ble_pre_setup_()) {
75 ESP_LOGE(TAG, "BLE could not be prepared for configuration");
76 this->mark_failed();
77 return;
78 }
79
80 this->state_ = BLE_COMPONENT_STATE_DISABLED;
81 if (this->enable_on_boot_) {
82 this->enable();
83 }
84}
85
87 if (this->state_ != BLE_COMPONENT_STATE_DISABLED)
88 return;
89
90 this->state_ = BLE_COMPONENT_STATE_ENABLE;
91}
92
94 if (this->state_ == BLE_COMPONENT_STATE_DISABLED)
95 return;
96
97 this->state_ = BLE_COMPONENT_STATE_DISABLE;
98}
99
100#ifdef USE_ESP32_BLE_ADVERTISING
102 this->advertising_init_();
103 this->advertising_ref_count_++;
104 this->advertising_refresh();
105}
106
108 if (this->advertising_ref_count_ == 0)
109 return;
110 this->advertising_ref_count_--;
111 this->advertising_refresh();
112}
113
115 if (this->advertising_ == nullptr || !this->is_active())
116 return;
117 // Advertise while any component still needs it, otherwise stop
118 if (this->advertising_ref_count_ == 0) {
119 this->advertising_->stop();
120 } else {
121 this->advertising_->start();
122 }
123}
124
125void ESP32BLE::advertising_set_service_data(const std::vector<uint8_t> &data) {
126 this->advertising_init_();
127 this->advertising_->set_service_data(data);
128 this->advertising_refresh();
129}
130
131void ESP32BLE::advertising_set_manufacturer_data(const std::vector<uint8_t> &data) {
132 this->advertising_init_();
133 this->advertising_->set_manufacturer_data(data);
134 this->advertising_refresh();
135}
136
137void ESP32BLE::advertising_set_service_data_and_name(std::span<const uint8_t> data, bool include_name) {
138 // This method atomically updates both service data and device name inclusion in BLE advertising.
139 // When include_name is true, the device name is included in the advertising packet making it
140 // visible to passive BLE scanners. When false, the name is only visible in scan response
141 // (requires active scanning). This atomic operation ensures we only restart advertising once
142 // when changing both properties, avoiding the brief gap that would occur with separate calls.
143
144 this->advertising_init_();
145
146 if (include_name) {
147 // When including name, clear service data first to avoid packet overflow
148 this->advertising_->set_service_data(std::span<const uint8_t>{});
149 this->advertising_->set_include_name(true);
150 } else {
151 // When including service data, clear name first to avoid packet overflow
152 this->advertising_->set_include_name(false);
153 this->advertising_->set_service_data(data);
154 }
155
156 this->advertising_refresh();
157}
158
159void ESP32BLE::advertising_register_raw_advertisement_callback(std::function<void(bool)> &&callback) {
160 this->advertising_init_();
161 this->advertising_->register_raw_advertisement_callback(std::move(callback));
162}
163
165 this->advertising_init_();
166 this->advertising_->add_service_uuid(uuid);
167 this->advertising_refresh();
168}
169
171 this->advertising_init_();
172 this->advertising_->remove_service_uuid(uuid);
173 this->advertising_refresh();
174}
175#endif
176
178 esp_err_t err = nvs_flash_init();
179 if (err != ESP_OK) {
180 ESP_LOGE(TAG, "nvs_flash_init failed: %d", err);
181 return false;
182 }
183 return true;
184}
185
186#ifdef USE_ESP32_BLE_ADVERTISING
188 if (this->advertising_ != nullptr)
189 return;
190 this->advertising_ = new BLEAdvertising(this->advertising_cycle_time_); // NOLINT(cppcoreguidelines-owning-memory)
191
192 this->advertising_->set_scan_response(true);
193 this->advertising_->set_min_preferred_interval(0x06);
194 this->advertising_->set_appearance(this->appearance_);
195}
196#endif
197
199 esp_err_t err;
200#ifdef CONFIG_ESP_HOSTED_ENABLE_BT_BLUEDROID
201 watchdog::WatchdogManager wdt(HOSTED_BT_WDT_TIMEOUT_MS);
202#endif
203#ifndef CONFIG_ESP_HOSTED_ENABLE_BT_BLUEDROID
204 if (esp_bt_controller_get_status() != ESP_BT_CONTROLLER_STATUS_ENABLED) {
205 // start bt controller
206 if (esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_IDLE) {
207 esp_bt_controller_config_t cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
208 err = esp_bt_controller_init(&cfg);
209 if (err != ESP_OK) {
210 ESP_LOGE(TAG, "esp_bt_controller_init failed: %s", esp_err_to_name(err));
211 return false;
212 }
213 while (esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_IDLE)
214 ;
215 }
216 if (esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_INITED) {
217 err = esp_bt_controller_enable(ESP_BT_MODE_BLE);
218 if (err != ESP_OK) {
219 ESP_LOGE(TAG, "esp_bt_controller_enable failed: %s", esp_err_to_name(err));
220 return false;
221 }
222 }
223 if (esp_bt_controller_get_status() != ESP_BT_CONTROLLER_STATUS_ENABLED) {
224 ESP_LOGE(TAG, "esp bt controller enable failed");
225 return false;
226 }
227 }
228
229 esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT);
230#else
231 if (esp_hosted_connect_to_slave() != ESP_OK) { // NOLINT
232 ESP_LOGE(TAG, "Co-processor transport failed; BLE disabled");
233 return false;
234 }
235
236 // Fast preflight (1 second RPC timeout): verifies the co-processor answers
237 // RPCs at all before the 5 second timeout BT controller RPCs below, and
238 // before hosted_hci_bluedroid_open(), which aborts if the transport is down.
239 esp_hosted_coprocessor_fwver_t fw_ver{};
240 if (esp_hosted_get_coprocessor_fwversion(&fw_ver) != ESP_OK) {
241 ESP_LOGE(TAG, "Co-processor not responding; BLE disabled. Update its firmware with the esp32_hosted "
242 "update component");
243 return false;
244 }
245 ESP_LOGD(TAG, "Co-processor firmware %" PRIu32 ".%" PRIu32 ".%" PRIu32, fw_ver.major1, fw_ver.minor1, fw_ver.patch1);
246
247 if (esp_hosted_bt_controller_init() != ESP_OK) {
248 ESP_LOGE(TAG,
249 "BT controller init failed; co-processor firmware %" PRIu32 ".%" PRIu32 ".%" PRIu32
250 " may lack BT support. Update it with the esp32_hosted update component; BLE disabled",
251 fw_ver.major1, fw_ver.minor1, fw_ver.patch1);
252 return false;
253 }
254
255 if (esp_hosted_bt_controller_enable() != ESP_OK) {
256 ESP_LOGE(TAG,
257 "BT controller enable failed; co-processor firmware %" PRIu32 ".%" PRIu32 ".%" PRIu32
258 " may lack BT support. Update it with the esp32_hosted update component; BLE disabled",
259 fw_ver.major1, fw_ver.minor1, fw_ver.patch1);
260 return false;
261 }
262
263 hosted_hci_bluedroid_open();
264
265 esp_bluedroid_hci_driver_operations_t operations = {
266 .send = hosted_hci_bluedroid_send,
267 .check_send_available = hosted_hci_bluedroid_check_send_available,
268 .register_host_callback = hosted_hci_bluedroid_register_host_callback,
269 };
270 esp_bluedroid_attach_hci_driver(&operations);
271#endif
272
273 err = esp_bluedroid_init();
274 if (err != ESP_OK) {
275 ESP_LOGE(TAG, "esp_bluedroid_init failed: %d", err);
276 return false;
277 }
278 err = esp_bluedroid_enable();
279 if (err != ESP_OK) {
280 ESP_LOGE(TAG, "esp_bluedroid_enable failed: %d", err);
281 return false;
282 }
283
284#ifdef ESPHOME_ESP32_BLE_GAP_EVENT_HANDLER_COUNT
285 err = esp_ble_gap_register_callback(ESP32BLE::gap_event_handler);
286 if (err != ESP_OK) {
287 ESP_LOGE(TAG, "esp_ble_gap_register_callback failed: %d", err);
288 return false;
289 }
290#endif
291
292#if defined(USE_ESP32_BLE_SERVER) && defined(ESPHOME_ESP32_BLE_GATTS_EVENT_HANDLER_COUNT)
293 err = esp_ble_gatts_register_callback(ESP32BLE::gatts_event_handler);
294 if (err != ESP_OK) {
295 ESP_LOGE(TAG, "esp_ble_gatts_register_callback failed: %d", err);
296 return false;
297 }
298#endif
299
300#if defined(USE_ESP32_BLE_CLIENT) && defined(ESPHOME_ESP32_BLE_GATTC_EVENT_HANDLER_COUNT)
301 err = esp_ble_gattc_register_callback(ESP32BLE::gattc_event_handler);
302 if (err != ESP_OK) {
303 ESP_LOGE(TAG, "esp_ble_gattc_register_callback failed: %d", err);
304 return false;
305 }
306#endif
307
308 // BLE device names are limited to 20 characters
309 // Buffer: 20 chars + null terminator
310 constexpr size_t ble_name_max_len = 21;
311 char name_buffer[ble_name_max_len];
312 const char *device_name;
313
314 if (this->name_ != nullptr) {
316 // MAC address suffix length (last 6 characters of 12-char MAC address string)
317 constexpr size_t mac_address_suffix_len = 6;
318 char mac_addr[MAC_ADDRESS_BUFFER_SIZE];
320 const char *mac_suffix_ptr = mac_addr + mac_address_suffix_len;
321 make_name_with_suffix_to(name_buffer, sizeof(name_buffer), this->name_, strlen(this->name_), '-', mac_suffix_ptr,
322 mac_address_suffix_len);
323 device_name = name_buffer;
324 } else {
325 device_name = this->name_;
326 }
327 } else {
328 const auto &app_name = App.get_name();
329 size_t name_len = app_name.length();
330 if (name_len > 20) {
332 // Keep first 13 chars and last 7 chars (MAC suffix), remove middle
333 memcpy(name_buffer, app_name.c_str(), 13);
334 memcpy(name_buffer + 13, app_name.c_str() + name_len - 7, 7);
335 } else {
336 memcpy(name_buffer, app_name.c_str(), 20);
337 }
338 name_buffer[20] = '\0';
339 } else {
340 memcpy(name_buffer, app_name.c_str(), name_len + 1); // Include null terminator
341 }
342 device_name = name_buffer;
343 }
344
345 err = esp_ble_gap_set_device_name(device_name);
346 if (err != ESP_OK) {
347 ESP_LOGE(TAG, "esp_ble_gap_set_device_name failed: %d", err);
348 return false;
349 }
350
351 err = esp_ble_gap_set_security_param(ESP_BLE_SM_IOCAP_MODE, &(this->io_cap_), sizeof(esp_ble_io_cap_t));
352 if (err != ESP_OK) {
353 ESP_LOGE(TAG, "esp_ble_gap_set_security_param iocap_mode failed: %d", err);
354 return false;
355 }
356
357#ifdef ESPHOME_ESP32_BLE_EXTENDED_AUTH_PARAMS
358 if (this->max_key_size_) {
359 err = esp_ble_gap_set_security_param(ESP_BLE_SM_MAX_KEY_SIZE, &(this->max_key_size_), sizeof(uint8_t));
360 if (err != ESP_OK) {
361 ESP_LOGE(TAG, "esp_ble_gap_set_security_param max_key_size failed: %d", err);
362 return false;
363 }
364 }
365
366 if (this->min_key_size_) {
367 err = esp_ble_gap_set_security_param(ESP_BLE_SM_MIN_KEY_SIZE, &(this->min_key_size_), sizeof(uint8_t));
368 if (err != ESP_OK) {
369 ESP_LOGE(TAG, "esp_ble_gap_set_security_param min_key_size failed: %d", err);
370 return false;
371 }
372 }
373
374 if (this->auth_req_mode_) {
375 err = esp_ble_gap_set_security_param(ESP_BLE_SM_AUTHEN_REQ_MODE, &(this->auth_req_mode_.value()),
376 sizeof(esp_ble_auth_req_t));
377 if (err != ESP_OK) {
378 ESP_LOGE(TAG, "esp_ble_gap_set_security_param authen_req_mode failed: %d", err);
379 return false;
380 }
381 }
382#endif // ESPHOME_ESP32_BLE_EXTENDED_AUTH_PARAMS
383
384 // BLE takes some time to be fully set up, 200ms should be more than enough
385 delay(200); // NOLINT
386
387 return true;
388}
389
391#ifdef CONFIG_ESP_HOSTED_ENABLE_BT_BLUEDROID
392 // Same 5 second RPCs as the bring-up path; see HOSTED_BT_WDT_TIMEOUT_MS
393 watchdog::WatchdogManager wdt(HOSTED_BT_WDT_TIMEOUT_MS);
394#endif
395 esp_err_t err = esp_bluedroid_disable();
396 if (err != ESP_OK) {
397 // ESP_ERR_INVALID_STATE means Bluedroid is already disabled, which is fine
398 if (err != ESP_ERR_INVALID_STATE) {
399 ESP_LOGE(TAG, "esp_bluedroid_disable failed: %d", err);
400 return false;
401 }
402 ESP_LOGD(TAG, "Already disabled");
403 }
404 err = esp_bluedroid_deinit();
405 if (err != ESP_OK) {
406 // ESP_ERR_INVALID_STATE means Bluedroid is already deinitialized, which is fine
407 if (err != ESP_ERR_INVALID_STATE) {
408 ESP_LOGE(TAG, "esp_bluedroid_deinit failed: %d", err);
409 return false;
410 }
411 ESP_LOGD(TAG, "Already deinitialized");
412 }
413
414#ifndef CONFIG_ESP_HOSTED_ENABLE_BT_BLUEDROID
415 if (esp_bt_controller_get_status() != ESP_BT_CONTROLLER_STATUS_IDLE) {
416 // stop bt controller
417 if (esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_ENABLED) {
418 err = esp_bt_controller_disable();
419 if (err != ESP_OK) {
420 ESP_LOGE(TAG, "esp_bt_controller_disable failed: %s", esp_err_to_name(err));
421 return false;
422 }
423 while (esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_ENABLED)
424 ;
425 }
426 if (esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_INITED) {
427 err = esp_bt_controller_deinit();
428 if (err != ESP_OK) {
429 ESP_LOGE(TAG, "esp_bt_controller_deinit failed: %s", esp_err_to_name(err));
430 return false;
431 }
432 }
433 if (esp_bt_controller_get_status() != ESP_BT_CONTROLLER_STATUS_IDLE) {
434 ESP_LOGE(TAG, "esp bt controller disable failed");
435 return false;
436 }
437 }
438#else
439 if (esp_hosted_bt_controller_disable() != ESP_OK) {
440 ESP_LOGE(TAG, "esp_hosted_bt_controller_disable failed");
441 return false;
442 }
443
444 if (esp_hosted_bt_controller_deinit(false) != ESP_OK) {
445 ESP_LOGE(TAG, "esp_hosted_bt_controller_deinit failed");
446 return false;
447 }
448
449 hosted_hci_bluedroid_close();
450#endif
451 return true;
452}
453
455 if (this->state_ != BLE_COMPONENT_STATE_ACTIVE) {
456 this->loop_handle_state_transition_not_active_();
457 return;
458 }
459
460#ifdef USE_ESP32_BLE_ADVERTISING
461 if (this->advertising_ != nullptr) {
462 this->advertising_->loop();
463 }
464#endif
465
466 BLEEvent *ble_event = this->ble_events_.pop();
467 if (ble_event == nullptr)
468 return;
469
470 do {
471 switch (ble_event->type_) {
472#if defined(USE_ESP32_BLE_SERVER) && defined(ESPHOME_ESP32_BLE_GATTS_EVENT_HANDLER_COUNT)
473 case BLEEvent::GATTS: {
474 esp_gatts_cb_event_t event = ble_event->event_.gatts.gatts_event;
475 esp_gatt_if_t gatts_if = ble_event->event_.gatts.gatts_if;
476 esp_ble_gatts_cb_param_t *param = &ble_event->event_.gatts.gatts_param;
477 ESP_LOGV(TAG, "gatts_event [esp_gatt_if: %d] - %d", gatts_if, event);
478 this->gatts_event_callbacks_.call(event, gatts_if, param);
479 break;
480 }
481#endif
482#if defined(USE_ESP32_BLE_CLIENT) && defined(ESPHOME_ESP32_BLE_GATTC_EVENT_HANDLER_COUNT)
483 case BLEEvent::GATTC: {
484 esp_gattc_cb_event_t event = ble_event->event_.gattc.gattc_event;
485 esp_gatt_if_t gattc_if = ble_event->event_.gattc.gattc_if;
486 esp_ble_gattc_cb_param_t *param = &ble_event->event_.gattc.gattc_param;
487 ESP_LOGV(TAG, "gattc_event [esp_gatt_if: %d] - %d", gattc_if, event);
488 this->gattc_event_callbacks_.call(event, gattc_if, param);
489 break;
490 }
491#endif
492 case BLEEvent::GAP: {
493 esp_gap_ble_cb_event_t gap_event = ble_event->event_.gap.gap_event;
494 switch (gap_event) {
495 case ESP_GAP_BLE_SCAN_RESULT_EVT:
496#ifdef ESPHOME_ESP32_BLE_GAP_SCAN_EVENT_HANDLER_COUNT
497 this->gap_scan_event_callbacks_.call(ble_event->scan_result());
498#endif
499 break;
500
501 // Scan complete events
502 GAP_SCAN_COMPLETE_EVENTS:
503 // Advertising complete events
504 GAP_ADV_COMPLETE_EVENTS:
505 // RSSI complete event
506 case ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT:
507 // Security events
508 GAP_SECURITY_EVENTS:
509 ESP_LOGV(TAG, "gap_event_handler - %d", gap_event);
510#ifdef ESPHOME_ESP32_BLE_GAP_EVENT_HANDLER_COUNT
511 {
512 esp_ble_gap_cb_param_t *param = NULL;
513 // clang-format off
514 switch (gap_event) {
515 // All three scan complete events have the same structure with just status
516 // The scan_complete struct matches ESP-IDF's layout exactly, so this reinterpret_cast is safe
517 // This is verified at compile-time by static_assert checks in ble_event.h
518 // The struct already contains our copy of the status (copied in BLEEvent constructor)
519 GAP_SCAN_COMPLETE_EVENTS:
520 param = reinterpret_cast<esp_ble_gap_cb_param_t *>(&ble_event->event_.gap.scan_complete);
521 break;
522
523 // All advertising complete events have the same structure with just status
524 GAP_ADV_COMPLETE_EVENTS:
525 param = reinterpret_cast<esp_ble_gap_cb_param_t *>(&ble_event->event_.gap.adv_complete);
526 break;
527
528 case ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT:
529 param = reinterpret_cast<esp_ble_gap_cb_param_t *>(&ble_event->event_.gap.read_rssi_complete);
530 break;
531
532 GAP_SECURITY_EVENTS:
533 param = reinterpret_cast<esp_ble_gap_cb_param_t *>(&ble_event->event_.gap.security);
534 break;
535
536 default:
537 break;
538 }
539 // clang-format on
540 // Dispatch to all registered handlers
541 this->gap_event_callbacks_.call(gap_event, param);
542 }
543#endif
544 break;
545
546 default:
547 // Unknown/unhandled event
548 ESP_LOGW(TAG, "Unhandled GAP event type in loop: %d", gap_event);
549 break;
550 }
551 break;
552 }
553 default:
554 break;
555 }
556 // Return the event to the pool
557 this->ble_event_pool_.release(ble_event);
558 } while ((ble_event = this->ble_events_.pop()) != nullptr);
559
560 // Log dropped events - only reachable when events were processed.
561 // Drops only occur when the queue is full, and only this loop drains it,
562 // so if pop() returned nullptr above we can skip this check (saves a memw).
563 uint16_t dropped = this->ble_events_.get_and_reset_dropped_count();
564 if (dropped > 0) {
565 ESP_LOGW(TAG, "Dropped %u BLE events due to buffer overflow", dropped);
566 }
567}
568
569void ESP32BLE::loop_handle_state_transition_not_active_() {
570 // Caller ensures state_ != ACTIVE
571 if (this->state_ == BLE_COMPONENT_STATE_DISABLE) {
572 ESP_LOGD(TAG, "Disabling");
573
574#ifdef ESPHOME_ESP32_BLE_BLE_STATUS_EVENT_HANDLER_COUNT
575 this->ble_status_event_callbacks_.call();
576#endif
577
578 if (!ble_dismantle_()) {
579 ESP_LOGE(TAG, "Could not be dismantled");
580 this->mark_failed();
581 return;
582 }
583 this->state_ = BLE_COMPONENT_STATE_DISABLED;
584 } else if (this->state_ == BLE_COMPONENT_STATE_ENABLE) {
585 ESP_LOGD(TAG, "Enabling");
586 this->state_ = BLE_COMPONENT_STATE_OFF;
587
588 if (!ble_setup_()) {
589 ESP_LOGE(TAG, "Could not be set up");
590 this->mark_failed();
591 return;
592 }
593
594 this->state_ = BLE_COMPONENT_STATE_ACTIVE;
595#ifdef USE_ESP32_BLE_ADVERTISING
596 // Requests made before the stack was up (or before it was re-enabled) take effect now
597 this->advertising_refresh();
598#endif
599 }
600}
601
602// Helper function to load new event data based on type
603void load_ble_event(BLEEvent *event, esp_gap_ble_cb_event_t e, esp_ble_gap_cb_param_t *p) {
604 event->load_gap_event(e, p);
605}
606
607#ifdef USE_ESP32_BLE_CLIENT
608void load_ble_event(BLEEvent *event, esp_gattc_cb_event_t e, esp_gatt_if_t i, esp_ble_gattc_cb_param_t *p) {
609 event->load_gattc_event(e, i, p);
610}
611#endif
612
613#ifdef USE_ESP32_BLE_SERVER
614void load_ble_event(BLEEvent *event, esp_gatts_cb_event_t e, esp_gatt_if_t i, esp_ble_gatts_cb_param_t *p) {
615 event->load_gatts_event(e, i, p);
616}
617#endif
618
619template<typename... Args> void enqueue_ble_event(Args... args) {
620 // Allocate an event from the pool
621 BLEEvent *event = global_ble->ble_event_pool_.allocate();
622 if (event == nullptr) {
623 // No events available - queue is full or we're out of memory
624 global_ble->ble_events_.increment_dropped_count();
625 return;
626 }
627
628 // Load new event data (replaces previous event)
629 load_ble_event(event, args...);
630
631 // Push the event to the queue
632 // Push always succeeds: pool is sized to queue capacity (N-1), so if
633 // allocate() returned non-null, the queue is guaranteed to have room.
634 global_ble->ble_events_.push(event);
635}
636
637// Explicit template instantiations for the friend function
638template void enqueue_ble_event(esp_gap_ble_cb_event_t, esp_ble_gap_cb_param_t *);
639#ifdef USE_ESP32_BLE_SERVER
640template void enqueue_ble_event(esp_gatts_cb_event_t, esp_gatt_if_t, esp_ble_gatts_cb_param_t *);
641#endif
642#ifdef USE_ESP32_BLE_CLIENT
643template void enqueue_ble_event(esp_gattc_cb_event_t, esp_gatt_if_t, esp_ble_gattc_cb_param_t *);
644#endif
645
646void ESP32BLE::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
647 switch (event) {
648 // Queue GAP events that components need to handle
649 // Scanning events - used by esp32_ble_tracker
650 case ESP_GAP_BLE_SCAN_RESULT_EVT:
651 GAP_SCAN_COMPLETE_EVENTS:
652 // Advertising events - used by esp32_ble_beacon and esp32_ble server
653 GAP_ADV_COMPLETE_EVENTS:
654 // Connection events - used by ble_client
655 case ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT:
656 enqueue_ble_event(event, param);
657 return;
658
659 // Security events - used by ble_client and bluetooth_proxy
660 // These are rare but interactive (pairing/bonding), so notify immediately
661 GAP_SECURITY_EVENTS:
662 enqueue_ble_event(event, param);
663 // Wake up main loop to process security event immediately
665 return;
666
667 // Log the result of connection parameter updates: a peer can reject or
668 // never answer an update, and without this the link silently stays on the
669 // old parameters (visible only as unexplained supervision timeouts).
670 case ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT: {
671 if (param->update_conn_params.status != ESP_BT_STATUS_SUCCESS) {
672 char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
673 format_mac_addr_upper(param->update_conn_params.bda, mac_s);
674 ESP_LOGW(TAG, "[%s] Conn param update failed, status=%d", mac_s, param->update_conn_params.status);
675 }
676#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
677 else {
678 char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
679 format_mac_addr_upper(param->update_conn_params.bda, mac_s);
680 ESP_LOGV(TAG, "[%s] Conn params updated: interval=%u (x1.25ms) latency=%u timeout=%u (x10ms)", mac_s,
681 param->update_conn_params.conn_int, param->update_conn_params.latency,
682 param->update_conn_params.timeout);
683 }
684#endif
685 return;
686 }
687
688 // Ignore these GAP events as they are not relevant for our use case
689 case ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT:
690 case ESP_GAP_BLE_PHY_UPDATE_COMPLETE_EVT: // BLE 5.0 PHY update complete
691 case ESP_GAP_BLE_CHANNEL_SELECT_ALGORITHM_EVT: // BLE 5.0 channel selection algorithm
692 case ESP_GAP_BLE_LOCAL_IR_EVT: // Local identity root key generated at security init
693 case ESP_GAP_BLE_LOCAL_ER_EVT: // Local encryption root key generated at security init
694 return;
695
696 default:
697 break;
698 }
699 ESP_LOGW(TAG, "Ignoring unexpected GAP event type: %d", event);
700}
701
702#ifdef USE_ESP32_BLE_SERVER
703void ESP32BLE::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if,
704 esp_ble_gatts_cb_param_t *param) {
705 enqueue_ble_event(event, gatts_if, param);
706 // Wake up main loop to process GATT event immediately
708}
709#endif
710
711#ifdef USE_ESP32_BLE_CLIENT
712void ESP32BLE::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
713 esp_ble_gattc_cb_param_t *param) {
714 enqueue_ble_event(event, gattc_if, param);
715 // Wake up main loop to process GATT event immediately
717}
718#endif
719
720void ESP32BLE::get_mac_msb_first(uint8_t out[MAC_ADDRESS_SIZE]) const {
721 // The running stack owns the address (on hosted controllers it lives in
722 // the remote chip's efuse); null before init becomes all-zero.
723 const uint8_t *mac = esp_bt_dev_get_address();
724 if (mac != nullptr) {
725 memcpy(out, mac, MAC_ADDRESS_SIZE);
726 } else {
727 memset(out, 0, MAC_ADDRESS_SIZE);
728 }
729}
730
732
734 uint8_t mac_address[MAC_ADDRESS_SIZE];
735 this->get_mac_msb_first(mac_address);
736 if (mac_address_is_valid(mac_address)) {
737 const char *io_capability_s;
738 switch (this->io_cap_) {
739 case ESP_IO_CAP_OUT:
740 io_capability_s = "display_only";
741 break;
742 case ESP_IO_CAP_IO:
743 io_capability_s = "display_yes_no";
744 break;
745 case ESP_IO_CAP_IN:
746 io_capability_s = "keyboard_only";
747 break;
748 case ESP_IO_CAP_NONE:
749 io_capability_s = "none";
750 break;
751 case ESP_IO_CAP_KBDISP:
752 io_capability_s = "keyboard_display";
753 break;
754 default:
755 io_capability_s = "invalid";
756 break;
757 }
758
759 char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
760 format_mac_addr_upper(mac_address, mac_s);
761 ESP_LOGCONFIG(TAG,
762 "BLE:\n"
763 " MAC address: %s\n"
764 " IO Capability: %s",
765 mac_s, io_capability_s);
766#ifdef USE_ESP32_BLE_PSRAM
767 ESP_LOGCONFIG(TAG, " PSRAM BLE allocation: enabled");
768#endif
769
770#ifdef ESPHOME_ESP32_BLE_EXTENDED_AUTH_PARAMS
771 const char *auth_req_mode_s = "<default>";
772 if (this->auth_req_mode_) {
773 switch (this->auth_req_mode_.value()) {
774 case AUTH_REQ_NO_BOND:
775 auth_req_mode_s = "no_bond";
776 break;
777 case AUTH_REQ_BOND:
778 auth_req_mode_s = "bond";
779 break;
780 case AUTH_REQ_MITM:
781 auth_req_mode_s = "mitm";
782 break;
784 auth_req_mode_s = "bond_mitm";
785 break;
786 case AUTH_REQ_SC_ONLY:
787 auth_req_mode_s = "sc_only";
788 break;
789 case AUTH_REQ_SC_BOND:
790 auth_req_mode_s = "sc_bond";
791 break;
792 case AUTH_REQ_SC_MITM:
793 auth_req_mode_s = "sc_mitm";
794 break;
796 auth_req_mode_s = "sc_mitm_bond";
797 break;
798 }
799 }
800
801 ESP_LOGCONFIG(TAG, " Auth Req Mode: %s", auth_req_mode_s);
802 if (this->max_key_size_ && this->min_key_size_) {
803 ESP_LOGCONFIG(TAG, " Key Size: %u - %u", this->min_key_size_, this->max_key_size_);
804 } else if (this->max_key_size_) {
805 ESP_LOGCONFIG(TAG, " Key Size: <default> - %u", this->max_key_size_);
806 } else if (this->min_key_size_) {
807 ESP_LOGCONFIG(TAG, " Key Size: %u - <default>", this->min_key_size_);
808 }
809#endif // ESPHOME_ESP32_BLE_EXTENDED_AUTH_PARAMS
810
811 } else {
812 ESP_LOGCONFIG(TAG, "Bluetooth stack is not enabled");
813 }
814}
815
816ESP32BLE *global_ble = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
817
818} // namespace esphome::esp32_ble
819
820#endif
bool btInUse()
Definition ble.cpp:31
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.
constexpr size_type length() const
Definition string_ref.h:75
void set_manufacturer_data(const std::vector< uint8_t > &data)
void set_scan_response(bool scan_response)
void set_include_name(bool include_name)
void set_min_preferred_interval(uint16_t interval)
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)
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:131
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:720
static void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
Definition ble.cpp:646
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:712
void advertising_start()
Request advertising on behalf of a component.
Definition ble.cpp:101
void advertising_refresh()
Apply the current payload and request count: advertise while requested, otherwise stop.
Definition ble.cpp:114
friend void enqueue_ble_event(Args... args)
Definition ble.cpp:619
void advertising_register_raw_advertisement_callback(std::function< void(bool)> &&callback)
Definition ble.cpp:159
void advertising_set_service_data_and_name(std::span< const uint8_t > data, bool include_name)
Definition ble.cpp:137
void advertising_add_service_uuid(ESPBTUUID uuid)
Definition ble.cpp:164
void dump_config() override
Definition ble.cpp:733
void loop() override
Definition ble.cpp:454
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:703
void advertising_set_service_data(const std::vector< uint8_t > &data)
Definition ble.cpp:125
ESPHOME_ALWAYS_INLINE bool is_active()
Definition ble.h:107
float get_setup_priority() const override
Definition ble.cpp:731
void setup() override
Definition ble.cpp:72
void advertising_stop()
Release a request made with advertising_start(); advertising stops at the last release.
Definition ble.cpp:107
void advertising_remove_service_uuid(ESPBTUUID uuid)
Definition ble.cpp:170
ESP32BLE * global_ble
Definition ble.cpp:816
void load_ble_event(BLEEvent *event, esp_gap_ble_cb_event_t e, esp_ble_gap_cb_param_t *p)
Definition ble.cpp:603
@ 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:619
constexpr float BLUETOOTH
Definition component.h:48
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:271
bool mac_address_is_valid(const uint8_t *mac)
Check if the MAC address is not all zeros or all ones.
Definition helpers.cpp:843
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:826
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:1505
static void uint32_t