ESPHome 2025.10.1
Loading...
Searching...
No Matches
esp32_ble_tracker.cpp
Go to the documentation of this file.
1#ifdef USE_ESP32
2
3#include "esp32_ble_tracker.h"
6#include "esphome/core/hal.h"
8#include "esphome/core/log.h"
9
10#include <esp_bt.h>
11#include <esp_bt_defs.h>
12#include <esp_bt_main.h>
13#include <esp_gap_ble_api.h>
14#include <freertos/FreeRTOS.h>
15#include <freertos/FreeRTOSConfig.h>
16#include <freertos/task.h>
17#include <nvs_flash.h>
18#include <cinttypes>
19
20#ifdef USE_OTA
22#endif
23
24#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
25#include <esp_coexist.h>
26#endif
27
28#define MBEDTLS_AES_ALT
29#include <aes_alt.h>
30
31// bt_trace.h
32#undef TAG
33
35
36static const char *const TAG = "esp32_ble_tracker";
37
38ESP32BLETracker *global_esp32_ble_tracker = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
39
41 switch (state) {
43 return "INIT";
45 return "DISCONNECTING";
47 return "IDLE";
49 return "DISCOVERED";
51 return "CONNECTING";
53 return "CONNECTED";
55 return "ESTABLISHED";
56 default:
57 return "UNKNOWN";
58 }
59}
60
62
64 if (this->parent_->is_failed()) {
65 this->mark_failed();
66 ESP_LOGE(TAG, "BLE Tracker was marked failed by ESP32BLE");
67 return;
68 }
69
71
72#ifdef USE_OTA
74 [this](ota::OTAState state, float progress, uint8_t error, ota::OTAComponent *comp) {
75 if (state == ota::OTA_STARTED) {
76 this->stop_scan();
77 for (auto *client : this->clients_) {
78 client->disconnect();
79 }
80 }
81 });
82#endif
83}
84
86 if (!this->parent_->is_active()) {
87 this->ble_was_disabled_ = true;
88 return;
89 } else if (this->ble_was_disabled_) {
90 this->ble_was_disabled_ = false;
91 // If the BLE stack was disabled, we need to start the scan again.
92 if (this->scan_continuous_) {
93 this->start_scan();
94 }
95 }
96
97 // Check for scan timeout - moved here from scheduler to avoid false reboots
98 // when the loop is blocked
100 switch (this->scan_timeout_state_) {
102 uint32_t now = App.get_loop_component_start_time();
103 uint32_t timeout_ms = this->scan_duration_ * 2000;
104 // Robust time comparison that handles rollover correctly
105 // This works because unsigned arithmetic wraps around predictably
106 if ((now - this->scan_start_time_) > timeout_ms) {
107 // First time we've seen the timeout exceeded - wait one more loop iteration
108 // This ensures all components have had a chance to process pending events
109 // This is because esp32_ble may not have run yet and called
110 // gap_scan_event_handler yet when the loop unblocks
111 ESP_LOGW(TAG, "Scan timeout exceeded");
113 }
114 break;
115 }
117 // We've waited at least one full loop iteration, and scan is still running
118 ESP_LOGE(TAG, "Scan never terminated, rebooting");
119 App.reboot();
120 break;
121
123 // This case should be unreachable - scanner and timeout states are always synchronized
124 break;
125 }
126 }
127
129 if (counts != this->client_state_counts_) {
130 this->client_state_counts_ = counts;
131 ESP_LOGD(TAG, "connecting: %d, discovered: %d, disconnecting: %d", this->client_state_counts_.connecting,
132 this->client_state_counts_.discovered, this->client_state_counts_.disconnecting);
133 }
134
138 }
139 /*
140
141 Avoid starting the scanner if:
142 - we are already scanning
143 - we are connecting to a device
144 - we are disconnecting from a device
145
146 Otherwise the scanner could fail to ever start again
147 and our only way to recover is to reboot.
148
149 https://github.com/espressif/esp-idf/issues/6688
150
151 */
152
153 if (this->scanner_state_ == ScannerState::IDLE && !counts.connecting && !counts.disconnecting && !counts.discovered) {
154#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
155 this->update_coex_preference_(false);
156#endif
157 if (this->scan_continuous_) {
158 this->start_scan_(false); // first = false
159 }
160 }
161 // If there is a discovered client and no connecting
162 // clients, then promote the discovered client to ready to connect.
163 // We check both RUNNING and IDLE states because:
164 // - RUNNING: gap_scan_event_handler initiates stop_scan_() but promotion can happen immediately
165 // - IDLE: Scanner has already stopped (naturally or by gap_scan_event_handler)
166 if (counts.discovered && !counts.connecting &&
167 (this->scanner_state_ == ScannerState::RUNNING || this->scanner_state_ == ScannerState::IDLE)) {
169 }
170}
171
173
175 ESP_LOGD(TAG, "Stopping scan.");
176 this->scan_continuous_ = false;
177 this->stop_scan_();
178}
179
181
184 ESP_LOGE(TAG, "Cannot stop scan: %s", this->scanner_state_to_string_(this->scanner_state_));
185 return;
186 }
187 // Reset timeout state machine when stopping scan
190 esp_err_t err = esp_ble_gap_stop_scanning();
191 if (err != ESP_OK) {
192 ESP_LOGE(TAG, "esp_ble_gap_stop_scanning failed: %d", err);
193 return;
194 }
195}
196
198 if (!this->parent_->is_active()) {
199 ESP_LOGW(TAG, "Cannot start scan while ESP32BLE is disabled.");
200 return;
201 }
202 if (this->scanner_state_ != ScannerState::IDLE) {
203 this->log_unexpected_state_("start scan", ScannerState::IDLE);
204 return;
205 }
207 ESP_LOGD(TAG, "Starting scan, set scanner state to STARTING.");
208 if (!first) {
209 for (auto *listener : this->listeners_)
210 listener->on_scan_end();
211 }
212#ifdef USE_ESP32_BLE_DEVICE
213 this->already_discovered_.clear();
214#endif
215 this->scan_params_.scan_type = this->scan_active_ ? BLE_SCAN_TYPE_ACTIVE : BLE_SCAN_TYPE_PASSIVE;
216 this->scan_params_.own_addr_type = BLE_ADDR_TYPE_PUBLIC;
217 this->scan_params_.scan_filter_policy = BLE_SCAN_FILTER_ALLOW_ALL;
218 this->scan_params_.scan_interval = this->scan_interval_;
219 this->scan_params_.scan_window = this->scan_window_;
220
221 // Start timeout monitoring in loop() instead of using scheduler
222 // This prevents false reboots when the loop is blocked
225
226 esp_err_t err = esp_ble_gap_set_scan_params(&this->scan_params_);
227 if (err != ESP_OK) {
228 ESP_LOGE(TAG, "esp_ble_gap_set_scan_params failed: %d", err);
229 return;
230 }
231 err = esp_ble_gap_start_scanning(this->scan_duration_);
232 if (err != ESP_OK) {
233 ESP_LOGE(TAG, "esp_ble_gap_start_scanning failed: %d", err);
234 return;
235 }
236}
237
239 client->app_id = ++this->app_id_;
240 this->clients_.push_back(client);
242}
243
245 listener->set_parent(this);
246 this->listeners_.push_back(listener);
248}
249
251 this->raw_advertisements_ = false;
252 this->parse_advertisements_ = false;
253 for (auto *listener : this->listeners_) {
254 if (listener->get_advertisement_parser_type() == AdvertisementParserType::PARSED_ADVERTISEMENTS) {
255 this->parse_advertisements_ = true;
256 } else {
257 this->raw_advertisements_ = true;
258 }
259 }
260 for (auto *client : this->clients_) {
261 if (client->get_advertisement_parser_type() == AdvertisementParserType::PARSED_ADVERTISEMENTS) {
262 this->parse_advertisements_ = true;
263 } else {
264 this->raw_advertisements_ = true;
265 }
266 }
267}
268
269void ESP32BLETracker::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
270 // Note: This handler is called from the main loop context, not directly from the BT task.
271 // The esp32_ble component queues events via enqueue_ble_event() and processes them in loop().
272 switch (event) {
273 case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT:
274 this->gap_scan_set_param_complete_(param->scan_param_cmpl);
275 break;
276 case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT:
277 this->gap_scan_start_complete_(param->scan_start_cmpl);
278 break;
279 case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT:
280 this->gap_scan_stop_complete_(param->scan_stop_cmpl);
281 break;
282 default:
283 break;
284 }
285 // Forward all events to clients (scan results are handled separately via gap_scan_event_handler)
286 for (auto *client : this->clients_) {
287 client->gap_event_handler(event, param);
288 }
289}
290
291void ESP32BLETracker::gap_scan_event_handler(const BLEScanResult &scan_result) {
292 // Note: This handler is called from the main loop context via esp32_ble's event queue.
293 // We process advertisements immediately instead of buffering them.
294 ESP_LOGVV(TAG, "gap_scan_result - event %d", scan_result.search_evt);
295
296 if (scan_result.search_evt == ESP_GAP_SEARCH_INQ_RES_EVT) {
297 // Process the scan result immediately
298 this->process_scan_result_(scan_result);
299 } else if (scan_result.search_evt == ESP_GAP_SEARCH_INQ_CMPL_EVT) {
300 // Scan finished on its own
302 this->log_unexpected_state_("scan complete", ScannerState::RUNNING);
303 }
304 // Scan completed naturally, perform cleanup and transition to IDLE
305 this->cleanup_scan_state_(false);
306 }
307}
308
309void ESP32BLETracker::gap_scan_set_param_complete_(const esp_ble_gap_cb_param_t::ble_scan_param_cmpl_evt_param &param) {
310 // Called from main loop context via gap_event_handler after being queued from BT task
311 ESP_LOGV(TAG, "gap_scan_set_param_complete - status %d", param.status);
312 if (param.status == ESP_BT_STATUS_DONE) {
313 this->scan_set_param_failed_ = ESP_BT_STATUS_SUCCESS;
314 } else {
315 this->scan_set_param_failed_ = param.status;
316 }
317}
318
319void ESP32BLETracker::gap_scan_start_complete_(const esp_ble_gap_cb_param_t::ble_scan_start_cmpl_evt_param &param) {
320 // Called from main loop context via gap_event_handler after being queued from BT task
321 ESP_LOGV(TAG, "gap_scan_start_complete - status %d", param.status);
322 this->scan_start_failed_ = param.status;
324 this->log_unexpected_state_("start complete", ScannerState::STARTING);
325 }
326 if (param.status == ESP_BT_STATUS_SUCCESS) {
327 this->scan_start_fail_count_ = 0;
329 } else {
331 if (this->scan_start_fail_count_ != std::numeric_limits<uint8_t>::max()) {
333 }
334 }
335}
336
337void ESP32BLETracker::gap_scan_stop_complete_(const esp_ble_gap_cb_param_t::ble_scan_stop_cmpl_evt_param &param) {
338 // Called from main loop context via gap_event_handler after being queued from BT task
339 // This allows us to safely transition to IDLE state and perform cleanup without race conditions
340 ESP_LOGV(TAG, "gap_scan_stop_complete - status %d", param.status);
342 this->log_unexpected_state_("stop complete", ScannerState::STOPPING);
343 }
344
345 // Perform cleanup and transition to IDLE
346 this->cleanup_scan_state_(true);
347}
348
349void ESP32BLETracker::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
350 esp_ble_gattc_cb_param_t *param) {
351 for (auto *client : this->clients_) {
352 client->gattc_event_handler(event, gattc_if, param);
353 }
354}
355
360
361#ifdef USE_ESP32_BLE_DEVICE
362ESPBLEiBeacon::ESPBLEiBeacon(const uint8_t *data) { memcpy(&this->beacon_data_, data, sizeof(beacon_data_)); }
364 if (!data.uuid.contains(0x4C, 0x00))
365 return {};
366
367 if (data.data.size() != 23)
368 return {};
369 return ESPBLEiBeacon(data.data.data());
370}
371
372void ESPBTDevice::parse_scan_rst(const BLEScanResult &scan_result) {
373 this->scan_result_ = &scan_result;
374 for (uint8_t i = 0; i < ESP_BD_ADDR_LEN; i++)
375 this->address_[i] = scan_result.bda[i];
376 this->address_type_ = static_cast<esp_ble_addr_type_t>(scan_result.ble_addr_type);
377 this->rssi_ = scan_result.rssi;
378
379 // Parse advertisement data directly
380 uint8_t total_len = scan_result.adv_data_len + scan_result.scan_rsp_len;
381 this->parse_adv_(scan_result.ble_adv, total_len);
382
383#ifdef ESPHOME_LOG_HAS_VERY_VERBOSE
384 ESP_LOGVV(TAG, "Parse Result:");
385 const char *address_type;
386 switch (this->address_type_) {
387 case BLE_ADDR_TYPE_PUBLIC:
388 address_type = "PUBLIC";
389 break;
390 case BLE_ADDR_TYPE_RANDOM:
391 address_type = "RANDOM";
392 break;
393 case BLE_ADDR_TYPE_RPA_PUBLIC:
394 address_type = "RPA_PUBLIC";
395 break;
396 case BLE_ADDR_TYPE_RPA_RANDOM:
397 address_type = "RPA_RANDOM";
398 break;
399 default:
400 address_type = "UNKNOWN";
401 break;
402 }
403 ESP_LOGVV(TAG, " Address: %02X:%02X:%02X:%02X:%02X:%02X (%s)", this->address_[0], this->address_[1],
404 this->address_[2], this->address_[3], this->address_[4], this->address_[5], address_type);
405
406 ESP_LOGVV(TAG, " RSSI: %d", this->rssi_);
407 ESP_LOGVV(TAG, " Name: '%s'", this->name_.c_str());
408 for (auto &it : this->tx_powers_) {
409 ESP_LOGVV(TAG, " TX Power: %d", it);
410 }
411 if (this->appearance_.has_value()) {
412 ESP_LOGVV(TAG, " Appearance: %u", *this->appearance_);
413 }
414 if (this->ad_flag_.has_value()) {
415 ESP_LOGVV(TAG, " Ad Flag: %u", *this->ad_flag_);
416 }
417 for (auto &uuid : this->service_uuids_) {
418 ESP_LOGVV(TAG, " Service UUID: %s", uuid.to_string().c_str());
419 }
420 for (auto &data : this->manufacturer_datas_) {
421 auto ibeacon = ESPBLEiBeacon::from_manufacturer_data(data);
422 if (ibeacon.has_value()) {
423 ESP_LOGVV(TAG, " Manufacturer iBeacon:");
424 ESP_LOGVV(TAG, " UUID: %s", ibeacon.value().get_uuid().to_string().c_str());
425 ESP_LOGVV(TAG, " Major: %u", ibeacon.value().get_major());
426 ESP_LOGVV(TAG, " Minor: %u", ibeacon.value().get_minor());
427 ESP_LOGVV(TAG, " TXPower: %d", ibeacon.value().get_signal_power());
428 } else {
429 ESP_LOGVV(TAG, " Manufacturer ID: %s, data: %s", data.uuid.to_string().c_str(),
430 format_hex_pretty(data.data).c_str());
431 }
432 }
433 for (auto &data : this->service_datas_) {
434 ESP_LOGVV(TAG, " Service data:");
435 ESP_LOGVV(TAG, " UUID: %s", data.uuid.to_string().c_str());
436 ESP_LOGVV(TAG, " Data: %s", format_hex_pretty(data.data).c_str());
437 }
438
439 ESP_LOGVV(TAG, " Adv data: %s",
440 format_hex_pretty(scan_result.ble_adv, scan_result.adv_data_len + scan_result.scan_rsp_len).c_str());
441#endif
442}
443
444void ESPBTDevice::parse_adv_(const uint8_t *payload, uint8_t len) {
445 size_t offset = 0;
446
447 while (offset + 2 < len) {
448 const uint8_t field_length = payload[offset++]; // First byte is length of adv record
449 if (field_length == 0) {
450 continue; // Possible zero padded advertisement data
451 }
452
453 // first byte of adv record is adv record type
454 const uint8_t record_type = payload[offset++];
455 const uint8_t *record = &payload[offset];
456 const uint8_t record_length = field_length - 1;
457 offset += record_length;
458
459 // See also Generic Access Profile Assigned Numbers:
460 // https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile/ See also ADVERTISING AND SCAN
461 // RESPONSE DATA FORMAT: https://www.bluetooth.com/specifications/bluetooth-core-specification/ (vol 3, part C, 11)
462 // See also Core Specification Supplement: https://www.bluetooth.com/specifications/bluetooth-core-specification/
463 // (called CSS here)
464
465 switch (record_type) {
466 case ESP_BLE_AD_TYPE_NAME_SHORT:
467 case ESP_BLE_AD_TYPE_NAME_CMPL: {
468 // CSS 1.2 LOCAL NAME
469 // "The Local Name data type shall be the same as, or a shortened version of, the local name assigned to the
470 // device." CSS 1: Optional in this context; shall not appear more than once in a block.
471 // SHORTENED LOCAL NAME
472 // "The Shortened Local Name data type defines a shortened version of the Local Name data type. The Shortened
473 // Local Name data type shall not be used to advertise a name that is longer than the Local Name data type."
474 if (record_length > this->name_.length()) {
475 this->name_ = std::string(reinterpret_cast<const char *>(record), record_length);
476 }
477 break;
478 }
479 case ESP_BLE_AD_TYPE_TX_PWR: {
480 // CSS 1.5 TX POWER LEVEL
481 // "The TX Power Level data type indicates the transmitted power level of the packet containing the data type."
482 // CSS 1: Optional in this context (may appear more than once in a block).
483 this->tx_powers_.push_back(*payload);
484 break;
485 }
486 case ESP_BLE_AD_TYPE_APPEARANCE: {
487 // CSS 1.12 APPEARANCE
488 // "The Appearance data type defines the external appearance of the device."
489 // See also https://www.bluetooth.com/specifications/gatt/characteristics/
490 // CSS 1: Optional in this context; shall not appear more than once in a block and shall not appear in both
491 // the AD and SRD of the same extended advertising interval.
492 this->appearance_ = *reinterpret_cast<const uint16_t *>(record);
493 break;
494 }
495 case ESP_BLE_AD_TYPE_FLAG: {
496 // CSS 1.3 FLAGS
497 // "The Flags data type contains one bit Boolean flags. The Flags data type shall be included when any of the
498 // Flag bits are non-zero and the advertising packet is connectable, otherwise the Flags data type may be
499 // omitted."
500 // CSS 1: Optional in this context; shall not appear more than once in a block.
501 this->ad_flag_ = *record;
502 break;
503 }
504 // CSS 1.1 SERVICE UUID
505 // The Service UUID data type is used to include a list of Service or Service Class UUIDs.
506 // There are six data types defined for the three sizes of Service UUIDs that may be returned:
507 // CSS 1: Optional in this context (may appear more than once in a block).
508 case ESP_BLE_AD_TYPE_16SRV_CMPL:
509 case ESP_BLE_AD_TYPE_16SRV_PART: {
510 // • 16-bit Bluetooth Service UUIDs
511 for (uint8_t i = 0; i < record_length / 2; i++) {
512 this->service_uuids_.push_back(ESPBTUUID::from_uint16(*reinterpret_cast<const uint16_t *>(record + 2 * i)));
513 }
514 break;
515 }
516 case ESP_BLE_AD_TYPE_32SRV_CMPL:
517 case ESP_BLE_AD_TYPE_32SRV_PART: {
518 // • 32-bit Bluetooth Service UUIDs
519 for (uint8_t i = 0; i < record_length / 4; i++) {
520 this->service_uuids_.push_back(ESPBTUUID::from_uint32(*reinterpret_cast<const uint32_t *>(record + 4 * i)));
521 }
522 break;
523 }
524 case ESP_BLE_AD_TYPE_128SRV_CMPL:
525 case ESP_BLE_AD_TYPE_128SRV_PART: {
526 // • Global 128-bit Service UUIDs
527 this->service_uuids_.push_back(ESPBTUUID::from_raw(record));
528 break;
529 }
530 case ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE: {
531 // CSS 1.4 MANUFACTURER SPECIFIC DATA
532 // "The Manufacturer Specific data type is used for manufacturer specific data. The first two data octets shall
533 // contain a company identifier from Assigned Numbers. The interpretation of any other octets within the data
534 // shall be defined by the manufacturer specified by the company identifier."
535 // CSS 1: Optional in this context (may appear more than once in a block).
536 if (record_length < 2) {
537 ESP_LOGV(TAG, "Record length too small for ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE");
538 break;
539 }
540 ServiceData data{};
541 data.uuid = ESPBTUUID::from_uint16(*reinterpret_cast<const uint16_t *>(record));
542 data.data.assign(record + 2UL, record + record_length);
543 this->manufacturer_datas_.push_back(data);
544 break;
545 }
546
547 // CSS 1.11 SERVICE DATA
548 // "The Service Data data type consists of a service UUID with the data associated with that service."
549 // CSS 1: Optional in this context (may appear more than once in a block).
550 case ESP_BLE_AD_TYPE_SERVICE_DATA: {
551 // «Service Data - 16 bit UUID»
552 // Size: 2 or more octets
553 // The first 2 octets contain the 16 bit Service UUID fol- lowed by additional service data
554 if (record_length < 2) {
555 ESP_LOGV(TAG, "Record length too small for ESP_BLE_AD_TYPE_SERVICE_DATA");
556 break;
557 }
558 ServiceData data{};
559 data.uuid = ESPBTUUID::from_uint16(*reinterpret_cast<const uint16_t *>(record));
560 data.data.assign(record + 2UL, record + record_length);
561 this->service_datas_.push_back(data);
562 break;
563 }
564 case ESP_BLE_AD_TYPE_32SERVICE_DATA: {
565 // «Service Data - 32 bit UUID»
566 // Size: 4 or more octets
567 // The first 4 octets contain the 32 bit Service UUID fol- lowed by additional service data
568 if (record_length < 4) {
569 ESP_LOGV(TAG, "Record length too small for ESP_BLE_AD_TYPE_32SERVICE_DATA");
570 break;
571 }
572 ServiceData data{};
573 data.uuid = ESPBTUUID::from_uint32(*reinterpret_cast<const uint32_t *>(record));
574 data.data.assign(record + 4UL, record + record_length);
575 this->service_datas_.push_back(data);
576 break;
577 }
578 case ESP_BLE_AD_TYPE_128SERVICE_DATA: {
579 // «Service Data - 128 bit UUID»
580 // Size: 16 or more octets
581 // The first 16 octets contain the 128 bit Service UUID followed by additional service data
582 if (record_length < 16) {
583 ESP_LOGV(TAG, "Record length too small for ESP_BLE_AD_TYPE_128SERVICE_DATA");
584 break;
585 }
586 ServiceData data{};
587 data.uuid = ESPBTUUID::from_raw(record);
588 data.data.assign(record + 16UL, record + record_length);
589 this->service_datas_.push_back(data);
590 break;
591 }
592 case ESP_BLE_AD_TYPE_INT_RANGE:
593 // Avoid logging this as it's very verbose
594 break;
595 default: {
596 ESP_LOGV(TAG, "Unhandled type: advType: 0x%02x", record_type);
597 break;
598 }
599 }
600 }
601}
602
603std::string ESPBTDevice::address_str() const {
604 char mac[18];
606 return mac;
607}
608
610#endif // USE_ESP32_BLE_DEVICE
611
613 ESP_LOGCONFIG(TAG, "BLE Tracker:");
614 ESP_LOGCONFIG(TAG,
615 " Scan Duration: %" PRIu32 " s\n"
616 " Scan Interval: %.1f ms\n"
617 " Scan Window: %.1f ms\n"
618 " Scan Type: %s\n"
619 " Continuous Scanning: %s",
620 this->scan_duration_, this->scan_interval_ * 0.625f, this->scan_window_ * 0.625f,
621 this->scan_active_ ? "ACTIVE" : "PASSIVE", YESNO(this->scan_continuous_));
622 ESP_LOGCONFIG(TAG, " Scanner State: %s", this->scanner_state_to_string_(this->scanner_state_));
623 ESP_LOGCONFIG(TAG, " Connecting: %d, discovered: %d, disconnecting: %d", this->client_state_counts_.connecting,
624 this->client_state_counts_.discovered, this->client_state_counts_.disconnecting);
625 if (this->scan_start_fail_count_) {
626 ESP_LOGCONFIG(TAG, " Scan Start Fail Count: %d", this->scan_start_fail_count_);
627 }
628}
629
630#ifdef USE_ESP32_BLE_DEVICE
632 const uint64_t address = device.address_uint64();
633 for (auto &disc : this->already_discovered_) {
634 if (disc == address)
635 return;
636 }
637 this->already_discovered_.push_back(address);
638
639 ESP_LOGD(TAG, "Found device %s RSSI=%d", device.address_str().c_str(), device.get_rssi());
640
641 const char *address_type_s;
642 switch (device.get_address_type()) {
643 case BLE_ADDR_TYPE_PUBLIC:
644 address_type_s = "PUBLIC";
645 break;
646 case BLE_ADDR_TYPE_RANDOM:
647 address_type_s = "RANDOM";
648 break;
649 case BLE_ADDR_TYPE_RPA_PUBLIC:
650 address_type_s = "RPA_PUBLIC";
651 break;
652 case BLE_ADDR_TYPE_RPA_RANDOM:
653 address_type_s = "RPA_RANDOM";
654 break;
655 default:
656 address_type_s = "UNKNOWN";
657 break;
658 }
659
660 ESP_LOGD(TAG, " Address Type: %s", address_type_s);
661 if (!device.get_name().empty()) {
662 ESP_LOGD(TAG, " Name: '%s'", device.get_name().c_str());
663 }
664 for (auto &tx_power : device.get_tx_powers()) {
665 ESP_LOGD(TAG, " TX Power: %d", tx_power);
666 }
667}
668
669bool ESPBTDevice::resolve_irk(const uint8_t *irk) const {
670 uint8_t ecb_key[16];
671 uint8_t ecb_plaintext[16];
672 uint8_t ecb_ciphertext[16];
673
674 uint64_t addr64 = esp32_ble::ble_addr_to_uint64(this->address_);
675
676 memcpy(&ecb_key, irk, 16);
677 memset(&ecb_plaintext, 0, 16);
678
679 ecb_plaintext[13] = (addr64 >> 40) & 0xff;
680 ecb_plaintext[14] = (addr64 >> 32) & 0xff;
681 ecb_plaintext[15] = (addr64 >> 24) & 0xff;
682
683 mbedtls_aes_context ctx = {0, 0, {0}};
684 mbedtls_aes_init(&ctx);
685
686 if (mbedtls_aes_setkey_enc(&ctx, ecb_key, 128) != 0) {
687 mbedtls_aes_free(&ctx);
688 return false;
689 }
690
691 if (mbedtls_aes_crypt_ecb(&ctx, ESP_AES_ENCRYPT, ecb_plaintext, ecb_ciphertext) != 0) {
692 mbedtls_aes_free(&ctx);
693 return false;
694 }
695
696 mbedtls_aes_free(&ctx);
697
698 return ecb_ciphertext[15] == (addr64 & 0xff) && ecb_ciphertext[14] == ((addr64 >> 8) & 0xff) &&
699 ecb_ciphertext[13] == ((addr64 >> 16) & 0xff);
700}
701
702#endif // USE_ESP32_BLE_DEVICE
703
704void ESP32BLETracker::process_scan_result_(const BLEScanResult &scan_result) {
705 // Process raw advertisements
706 if (this->raw_advertisements_) {
707 for (auto *listener : this->listeners_) {
708 listener->parse_devices(&scan_result, 1);
709 }
710 for (auto *client : this->clients_) {
711 client->parse_devices(&scan_result, 1);
712 }
713 }
714
715 // Process parsed advertisements
716 if (this->parse_advertisements_) {
717#ifdef USE_ESP32_BLE_DEVICE
718 ESPBTDevice device;
719 device.parse_scan_rst(scan_result);
720
721 bool found = false;
722 for (auto *listener : this->listeners_) {
723 if (listener->parse_device(device))
724 found = true;
725 }
726
727 for (auto *client : this->clients_) {
728 if (client->parse_device(device)) {
729 found = true;
730 }
731 }
732
733 if (!found && !this->scan_continuous_) {
734 this->print_bt_device_info(device);
735 }
736#endif // USE_ESP32_BLE_DEVICE
737 }
738}
739
740void ESP32BLETracker::cleanup_scan_state_(bool is_stop_complete) {
741 ESP_LOGD(TAG, "Scan %scomplete, set scanner state to IDLE.", is_stop_complete ? "stop " : "");
742#ifdef USE_ESP32_BLE_DEVICE
743 this->already_discovered_.clear();
744#endif
745 // Reset timeout state machine instead of cancelling scheduler timeout
747
748 for (auto *listener : this->listeners_)
749 listener->on_scan_end();
750
752}
753
755 this->stop_scan_();
756 if (this->scan_start_fail_count_ == std::numeric_limits<uint8_t>::max()) {
757 ESP_LOGE(TAG, "Scan could not restart after %d attempts, rebooting to restore stack (IDF)",
758 std::numeric_limits<uint8_t>::max());
759 App.reboot();
760 }
761 if (this->scan_start_failed_) {
762 ESP_LOGE(TAG, "Scan start failed: %d", this->scan_start_failed_);
763 this->scan_start_failed_ = ESP_BT_STATUS_SUCCESS;
764 }
765 if (this->scan_set_param_failed_) {
766 ESP_LOGE(TAG, "Scan set param failed: %d", this->scan_set_param_failed_);
767 this->scan_set_param_failed_ = ESP_BT_STATUS_SUCCESS;
768 }
769}
770
772 // Only promote the first discovered client to avoid multiple simultaneous connections
773 for (auto *client : this->clients_) {
774 if (client->state() != ClientState::DISCOVERED) {
775 continue;
776 }
777
779 ESP_LOGD(TAG, "Stopping scan to make connection");
780 this->stop_scan_();
781 // Don't wait for scan stop complete - promote immediately.
782 // This is safe because ESP-IDF processes BLE commands sequentially through its internal mailbox queue.
783 // This guarantees that the stop scan command will be fully processed before any subsequent connect command,
784 // preventing race conditions or overlapping operations.
785 }
786
787 ESP_LOGD(TAG, "Promoting client to connect");
788#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
789 this->update_coex_preference_(true);
790#endif
791 client->connect();
792 break;
793 }
794}
795
797 switch (state) {
799 return "IDLE";
801 return "STARTING";
803 return "RUNNING";
805 return "STOPPING";
807 return "FAILED";
808 default:
809 return "UNKNOWN";
810 }
811}
812
813void ESP32BLETracker::log_unexpected_state_(const char *operation, ScannerState expected_state) const {
814 ESP_LOGE(TAG, "Unexpected state: %s on %s, expected: %s", this->scanner_state_to_string_(this->scanner_state_),
815 operation, this->scanner_state_to_string_(expected_state));
816}
817
818#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
820 if (force_ble && !this->coex_prefer_ble_) {
821 ESP_LOGD(TAG, "Setting coexistence to Bluetooth to make connection.");
822 this->coex_prefer_ble_ = true;
823 esp_coex_preference_set(ESP_COEX_PREFER_BT); // Prioritize Bluetooth
824 } else if (!force_ble && this->coex_prefer_ble_) {
825 ESP_LOGD(TAG, "Setting coexistence preference to balanced.");
826 this->coex_prefer_ble_ = false;
827 esp_coex_preference_set(ESP_COEX_PREFER_BALANCE); // Reset to default
828 }
829}
830#endif
831
832} // namespace esphome::esp32_ble_tracker
833
834#endif // USE_ESP32
uint8_t address
Definition bl0906.h:4
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
virtual void mark_failed()
Mark this component as failed.
static ESPBTUUID from_uint32(uint32_t uuid)
Definition ble_uuid.cpp:23
static ESPBTUUID from_uint16(uint16_t uuid)
Definition ble_uuid.cpp:17
static ESPBTUUID from_raw(const uint8_t *data)
Definition ble_uuid.cpp:29
bool contains(uint8_t data1, uint8_t data2) const
Definition ble_uuid.cpp:112
void try_promote_discovered_clients_()
Try to promote discovered clients to ready to connect.
std::vector< uint64_t > already_discovered_
Vector of addresses that have already been printed in print_bt_device_info.
void gap_scan_stop_complete_(const esp_ble_gap_cb_param_t::ble_scan_stop_cmpl_evt_param &param)
Called when a ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT event is received.
void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) override
ClientStateCounts count_client_states_() const
Count clients in each state.
esp_ble_scan_params_t scan_params_
A structure holding the ESP BLE scan parameters.
void register_listener(ESPBTDeviceListener *listener)
void update_coex_preference_(bool force_ble)
Update BLE coexistence preference.
const char * scanner_state_to_string_(ScannerState state) const
Convert scanner state enum to string for logging.
CallbackManager< void(ScannerState)> scanner_state_callbacks_
void gap_scan_set_param_complete_(const esp_ble_gap_cb_param_t::ble_scan_param_cmpl_evt_param &param)
Called when a ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT event is received.
uint32_t scan_duration_
The interval in seconds to perform scans.
void setup() override
Setup the FreeRTOS task and the Bluetooth stack.
void handle_scanner_failure_()
Handle scanner failure states.
void cleanup_scan_state_(bool is_stop_complete)
Common cleanup logic when transitioning scanner to IDLE state.
void set_scanner_state_(ScannerState state)
Called to set the scanner state. Will also call callbacks to let listeners know when state is changed...
void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) override
void print_bt_device_info(const ESPBTDevice &device)
void gap_scan_event_handler(const BLEScanResult &scan_result) override
void process_scan_result_(const BLEScanResult &scan_result)
Process a single scan result immediately.
void gap_scan_start_complete_(const esp_ble_gap_cb_param_t::ble_scan_start_cmpl_evt_param &param)
Called when a ESP_GAP_BLE_SCAN_START_COMPLETE_EVT event is received.
void log_unexpected_state_(const char *operation, ScannerState expected_state) const
Log an unexpected scanner state.
std::vector< ESPBTDeviceListener * > listeners_
void start_scan_(bool first)
Start a single scan by setting up the parameters and doing some esp-idf calls.
struct esphome::esp32_ble_tracker::ESPBLEiBeacon::@78 beacon_data_
static optional< ESPBLEiBeacon > from_manufacturer_data(const ServiceData &data)
esp_ble_addr_type_t get_address_type() const
void parse_adv_(const uint8_t *payload, uint8_t len)
void parse_scan_rst(const BLEScanResult &scan_result)
std::vector< ServiceData > manufacturer_datas_
const std::vector< int8_t > & get_tx_powers() const
bool resolve_irk(const uint8_t *irk) const
std::vector< ServiceData > service_datas_
bool has_value() const
Definition optional.h:92
void add_on_state_callback(std::function< void(OTAState, float, uint8_t, OTAComponent *)> &&callback)
bool state
Definition fan.h:0
ESP32BLETracker * global_esp32_ble_tracker
const char * client_state_to_string(ClientState state)
uint64_t ble_addr_to_uint64(const esp_bd_addr_t address)
Definition ble.cpp:577
OTAGlobalCallback * get_global_ota_callback()
const float AFTER_BLUETOOTH
Definition component.cpp:62
void format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase)
Definition helpers.h:415
std::string size_t len
Definition helpers.h:304
std::string format_hex_pretty(const uint8_t *data, size_t length, char separator, bool show_length)
Format a byte array in pretty-printed, human-readable hex format.
Definition helpers.cpp:293
Application App
Global storage of Application pointer - only one Application can exist.