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