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