ESPHome 2025.12.0-dev
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 ESP_LOGE(TAG, "Cannot stop scan: %s", this->scanner_state_to_string_(this->scanner_state_));
189 return;
190 }
191 // Reset timeout state machine when stopping scan
194 esp_err_t err = esp_ble_gap_stop_scanning();
195 if (err != ESP_OK) {
196 ESP_LOGE(TAG, "esp_ble_gap_stop_scanning failed: %d", err);
197 return;
198 }
199}
200
202 if (!this->parent_->is_active()) {
203 ESP_LOGW(TAG, "Cannot start scan while ESP32BLE is disabled.");
204 return;
205 }
206 if (this->scanner_state_ != ScannerState::IDLE) {
207 this->log_unexpected_state_("start scan", ScannerState::IDLE);
208 return;
209 }
211 ESP_LOGD(TAG, "Starting scan, set scanner state to STARTING.");
212 if (!first) {
213#ifdef ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT
214 for (auto *listener : this->listeners_)
215 listener->on_scan_end();
216#endif
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#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
246 client->app_id = ++this->app_id_;
247 this->clients_.push_back(client);
249#endif
250}
251
253#ifdef ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT
254 listener->set_parent(this);
255 this->listeners_.push_back(listener);
257#endif
258}
259
261 this->raw_advertisements_ = false;
262 this->parse_advertisements_ = false;
263#ifdef ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT
264 for (auto *listener : this->listeners_) {
265 if (listener->get_advertisement_parser_type() == AdvertisementParserType::PARSED_ADVERTISEMENTS) {
266 this->parse_advertisements_ = true;
267 } else {
268 this->raw_advertisements_ = true;
269 }
270 }
271#endif
272#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
273 for (auto *client : this->clients_) {
274 if (client->get_advertisement_parser_type() == AdvertisementParserType::PARSED_ADVERTISEMENTS) {
275 this->parse_advertisements_ = true;
276 } else {
277 this->raw_advertisements_ = true;
278 }
279 }
280#endif
281}
282
283void ESP32BLETracker::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
284 // Note: This handler is called from the main loop context, not directly from the BT task.
285 // The esp32_ble component queues events via enqueue_ble_event() and processes them in loop().
286 switch (event) {
287 case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT:
288 this->gap_scan_set_param_complete_(param->scan_param_cmpl);
289 break;
290 case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT:
291 this->gap_scan_start_complete_(param->scan_start_cmpl);
292 break;
293 case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT:
294 this->gap_scan_stop_complete_(param->scan_stop_cmpl);
295 break;
296 default:
297 break;
298 }
299 // Forward all events to clients (scan results are handled separately via gap_scan_event_handler)
300#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
301 for (auto *client : this->clients_) {
302 client->gap_event_handler(event, param);
303 }
304#endif
305}
306
307void ESP32BLETracker::gap_scan_event_handler(const BLEScanResult &scan_result) {
308 // Note: This handler is called from the main loop context via esp32_ble's event queue.
309 // We process advertisements immediately instead of buffering them.
310 ESP_LOGVV(TAG, "gap_scan_result - event %d", scan_result.search_evt);
311
312 if (scan_result.search_evt == ESP_GAP_SEARCH_INQ_RES_EVT) {
313 // Process the scan result immediately
314 this->process_scan_result_(scan_result);
315 } else if (scan_result.search_evt == ESP_GAP_SEARCH_INQ_CMPL_EVT) {
316 // Scan finished on its own
318 this->log_unexpected_state_("scan complete", ScannerState::RUNNING);
319 }
320 // Scan completed naturally, perform cleanup and transition to IDLE
321 this->cleanup_scan_state_(false);
322 }
323}
324
325void ESP32BLETracker::gap_scan_set_param_complete_(const esp_ble_gap_cb_param_t::ble_scan_param_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_set_param_complete - status %d", param.status);
328 if (param.status == ESP_BT_STATUS_DONE) {
329 this->scan_set_param_failed_ = ESP_BT_STATUS_SUCCESS;
330 } else {
331 this->scan_set_param_failed_ = param.status;
332 }
333}
334
335void ESP32BLETracker::gap_scan_start_complete_(const esp_ble_gap_cb_param_t::ble_scan_start_cmpl_evt_param &param) {
336 // Called from main loop context via gap_event_handler after being queued from BT task
337 ESP_LOGV(TAG, "gap_scan_start_complete - status %d", param.status);
338 this->scan_start_failed_ = param.status;
340 this->log_unexpected_state_("start complete", ScannerState::STARTING);
341 }
342 if (param.status == ESP_BT_STATUS_SUCCESS) {
343 this->scan_start_fail_count_ = 0;
345 } else {
347 if (this->scan_start_fail_count_ != std::numeric_limits<uint8_t>::max()) {
349 }
350 }
351}
352
353void ESP32BLETracker::gap_scan_stop_complete_(const esp_ble_gap_cb_param_t::ble_scan_stop_cmpl_evt_param &param) {
354 // Called from main loop context via gap_event_handler after being queued from BT task
355 // This allows us to safely transition to IDLE state and perform cleanup without race conditions
356 ESP_LOGV(TAG, "gap_scan_stop_complete - status %d", param.status);
358 this->log_unexpected_state_("stop complete", ScannerState::STOPPING);
359 }
360
361 // Perform cleanup and transition to IDLE
362 this->cleanup_scan_state_(true);
363}
364
365void ESP32BLETracker::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
366 esp_ble_gattc_cb_param_t *param) {
367#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
368 for (auto *client : this->clients_) {
369 client->gattc_event_handler(event, gattc_if, param);
370 }
371#endif
372}
373
378
379#ifdef USE_ESP32_BLE_DEVICE
380ESPBLEiBeacon::ESPBLEiBeacon(const uint8_t *data) { memcpy(&this->beacon_data_, data, sizeof(beacon_data_)); }
382 if (!data.uuid.contains(0x4C, 0x00))
383 return {};
384
385 if (data.data.size() != 23)
386 return {};
387 return ESPBLEiBeacon(data.data.data());
388}
389
390void ESPBTDevice::parse_scan_rst(const BLEScanResult &scan_result) {
391 this->scan_result_ = &scan_result;
392 for (uint8_t i = 0; i < ESP_BD_ADDR_LEN; i++)
393 this->address_[i] = scan_result.bda[i];
394 this->address_type_ = static_cast<esp_ble_addr_type_t>(scan_result.ble_addr_type);
395 this->rssi_ = scan_result.rssi;
396
397 // Parse advertisement data directly
398 uint8_t total_len = scan_result.adv_data_len + scan_result.scan_rsp_len;
399 this->parse_adv_(scan_result.ble_adv, total_len);
400
401#ifdef ESPHOME_LOG_HAS_VERY_VERBOSE
402 ESP_LOGVV(TAG, "Parse Result:");
403 const char *address_type;
404 switch (this->address_type_) {
405 case BLE_ADDR_TYPE_PUBLIC:
406 address_type = "PUBLIC";
407 break;
408 case BLE_ADDR_TYPE_RANDOM:
409 address_type = "RANDOM";
410 break;
411 case BLE_ADDR_TYPE_RPA_PUBLIC:
412 address_type = "RPA_PUBLIC";
413 break;
414 case BLE_ADDR_TYPE_RPA_RANDOM:
415 address_type = "RPA_RANDOM";
416 break;
417 default:
418 address_type = "UNKNOWN";
419 break;
420 }
421 ESP_LOGVV(TAG, " Address: %02X:%02X:%02X:%02X:%02X:%02X (%s)", this->address_[0], this->address_[1],
422 this->address_[2], this->address_[3], this->address_[4], this->address_[5], address_type);
423
424 ESP_LOGVV(TAG, " RSSI: %d", this->rssi_);
425 ESP_LOGVV(TAG, " Name: '%s'", this->name_.c_str());
426 for (auto &it : this->tx_powers_) {
427 ESP_LOGVV(TAG, " TX Power: %d", it);
428 }
429 if (this->appearance_.has_value()) {
430 ESP_LOGVV(TAG, " Appearance: %u", *this->appearance_);
431 }
432 if (this->ad_flag_.has_value()) {
433 ESP_LOGVV(TAG, " Ad Flag: %u", *this->ad_flag_);
434 }
435 for (auto &uuid : this->service_uuids_) {
436 ESP_LOGVV(TAG, " Service UUID: %s", uuid.to_string().c_str());
437 }
438 for (auto &data : this->manufacturer_datas_) {
439 auto ibeacon = ESPBLEiBeacon::from_manufacturer_data(data);
440 if (ibeacon.has_value()) {
441 ESP_LOGVV(TAG, " Manufacturer iBeacon:");
442 ESP_LOGVV(TAG, " UUID: %s", ibeacon.value().get_uuid().to_string().c_str());
443 ESP_LOGVV(TAG, " Major: %u", ibeacon.value().get_major());
444 ESP_LOGVV(TAG, " Minor: %u", ibeacon.value().get_minor());
445 ESP_LOGVV(TAG, " TXPower: %d", ibeacon.value().get_signal_power());
446 } else {
447 ESP_LOGVV(TAG, " Manufacturer ID: %s, data: %s", data.uuid.to_string().c_str(),
448 format_hex_pretty(data.data).c_str());
449 }
450 }
451 for (auto &data : this->service_datas_) {
452 ESP_LOGVV(TAG, " Service data:");
453 ESP_LOGVV(TAG, " UUID: %s", data.uuid.to_string().c_str());
454 ESP_LOGVV(TAG, " Data: %s", format_hex_pretty(data.data).c_str());
455 }
456
457 ESP_LOGVV(TAG, " Adv data: %s",
458 format_hex_pretty(scan_result.ble_adv, scan_result.adv_data_len + scan_result.scan_rsp_len).c_str());
459#endif
460}
461
462void ESPBTDevice::parse_adv_(const uint8_t *payload, uint8_t len) {
463 size_t offset = 0;
464
465 while (offset + 2 < len) {
466 const uint8_t field_length = payload[offset++]; // First byte is length of adv record
467 if (field_length == 0) {
468 continue; // Possible zero padded advertisement data
469 }
470
471 // first byte of adv record is adv record type
472 const uint8_t record_type = payload[offset++];
473 const uint8_t *record = &payload[offset];
474 const uint8_t record_length = field_length - 1;
475 offset += record_length;
476
477 // See also Generic Access Profile Assigned Numbers:
478 // https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile/ See also ADVERTISING AND SCAN
479 // RESPONSE DATA FORMAT: https://www.bluetooth.com/specifications/bluetooth-core-specification/ (vol 3, part C, 11)
480 // See also Core Specification Supplement: https://www.bluetooth.com/specifications/bluetooth-core-specification/
481 // (called CSS here)
482
483 switch (record_type) {
484 case ESP_BLE_AD_TYPE_NAME_SHORT:
485 case ESP_BLE_AD_TYPE_NAME_CMPL: {
486 // CSS 1.2 LOCAL NAME
487 // "The Local Name data type shall be the same as, or a shortened version of, the local name assigned to the
488 // device." CSS 1: Optional in this context; shall not appear more than once in a block.
489 // SHORTENED LOCAL NAME
490 // "The Shortened Local Name data type defines a shortened version of the Local Name data type. The Shortened
491 // Local Name data type shall not be used to advertise a name that is longer than the Local Name data type."
492 if (record_length > this->name_.length()) {
493 this->name_ = std::string(reinterpret_cast<const char *>(record), record_length);
494 }
495 break;
496 }
497 case ESP_BLE_AD_TYPE_TX_PWR: {
498 // CSS 1.5 TX POWER LEVEL
499 // "The TX Power Level data type indicates the transmitted power level of the packet containing the data type."
500 // CSS 1: Optional in this context (may appear more than once in a block).
501 this->tx_powers_.push_back(*payload);
502 break;
503 }
504 case ESP_BLE_AD_TYPE_APPEARANCE: {
505 // CSS 1.12 APPEARANCE
506 // "The Appearance data type defines the external appearance of the device."
507 // See also https://www.bluetooth.com/specifications/gatt/characteristics/
508 // CSS 1: Optional in this context; shall not appear more than once in a block and shall not appear in both
509 // the AD and SRD of the same extended advertising interval.
510 this->appearance_ = *reinterpret_cast<const uint16_t *>(record);
511 break;
512 }
513 case ESP_BLE_AD_TYPE_FLAG: {
514 // CSS 1.3 FLAGS
515 // "The Flags data type contains one bit Boolean flags. The Flags data type shall be included when any of the
516 // Flag bits are non-zero and the advertising packet is connectable, otherwise the Flags data type may be
517 // omitted."
518 // CSS 1: Optional in this context; shall not appear more than once in a block.
519 this->ad_flag_ = *record;
520 break;
521 }
522 // CSS 1.1 SERVICE UUID
523 // The Service UUID data type is used to include a list of Service or Service Class UUIDs.
524 // There are six data types defined for the three sizes of Service UUIDs that may be returned:
525 // CSS 1: Optional in this context (may appear more than once in a block).
526 case ESP_BLE_AD_TYPE_16SRV_CMPL:
527 case ESP_BLE_AD_TYPE_16SRV_PART: {
528 // • 16-bit Bluetooth Service UUIDs
529 for (uint8_t i = 0; i < record_length / 2; i++) {
530 this->service_uuids_.push_back(ESPBTUUID::from_uint16(*reinterpret_cast<const uint16_t *>(record + 2 * i)));
531 }
532 break;
533 }
534 case ESP_BLE_AD_TYPE_32SRV_CMPL:
535 case ESP_BLE_AD_TYPE_32SRV_PART: {
536 // • 32-bit Bluetooth Service UUIDs
537 for (uint8_t i = 0; i < record_length / 4; i++) {
538 this->service_uuids_.push_back(ESPBTUUID::from_uint32(*reinterpret_cast<const uint32_t *>(record + 4 * i)));
539 }
540 break;
541 }
542 case ESP_BLE_AD_TYPE_128SRV_CMPL:
543 case ESP_BLE_AD_TYPE_128SRV_PART: {
544 // • Global 128-bit Service UUIDs
545 this->service_uuids_.push_back(ESPBTUUID::from_raw(record));
546 break;
547 }
548 case ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE: {
549 // CSS 1.4 MANUFACTURER SPECIFIC DATA
550 // "The Manufacturer Specific data type is used for manufacturer specific data. The first two data octets shall
551 // contain a company identifier from Assigned Numbers. The interpretation of any other octets within the data
552 // shall be defined by the manufacturer specified by the company identifier."
553 // CSS 1: Optional in this context (may appear more than once in a block).
554 if (record_length < 2) {
555 ESP_LOGV(TAG, "Record length too small for ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE");
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->manufacturer_datas_.push_back(data);
562 break;
563 }
564
565 // CSS 1.11 SERVICE DATA
566 // "The Service Data data type consists of a service UUID with the data associated with that service."
567 // CSS 1: Optional in this context (may appear more than once in a block).
568 case ESP_BLE_AD_TYPE_SERVICE_DATA: {
569 // «Service Data - 16 bit UUID»
570 // Size: 2 or more octets
571 // The first 2 octets contain the 16 bit Service UUID fol- lowed by additional service data
572 if (record_length < 2) {
573 ESP_LOGV(TAG, "Record length too small for ESP_BLE_AD_TYPE_SERVICE_DATA");
574 break;
575 }
576 ServiceData data{};
577 data.uuid = ESPBTUUID::from_uint16(*reinterpret_cast<const uint16_t *>(record));
578 data.data.assign(record + 2UL, record + record_length);
579 this->service_datas_.push_back(data);
580 break;
581 }
582 case ESP_BLE_AD_TYPE_32SERVICE_DATA: {
583 // «Service Data - 32 bit UUID»
584 // Size: 4 or more octets
585 // The first 4 octets contain the 32 bit Service UUID fol- lowed by additional service data
586 if (record_length < 4) {
587 ESP_LOGV(TAG, "Record length too small for ESP_BLE_AD_TYPE_32SERVICE_DATA");
588 break;
589 }
590 ServiceData data{};
591 data.uuid = ESPBTUUID::from_uint32(*reinterpret_cast<const uint32_t *>(record));
592 data.data.assign(record + 4UL, record + record_length);
593 this->service_datas_.push_back(data);
594 break;
595 }
596 case ESP_BLE_AD_TYPE_128SERVICE_DATA: {
597 // «Service Data - 128 bit UUID»
598 // Size: 16 or more octets
599 // The first 16 octets contain the 128 bit Service UUID followed by additional service data
600 if (record_length < 16) {
601 ESP_LOGV(TAG, "Record length too small for ESP_BLE_AD_TYPE_128SERVICE_DATA");
602 break;
603 }
604 ServiceData data{};
605 data.uuid = ESPBTUUID::from_raw(record);
606 data.data.assign(record + 16UL, record + record_length);
607 this->service_datas_.push_back(data);
608 break;
609 }
610 case ESP_BLE_AD_TYPE_INT_RANGE:
611 // Avoid logging this as it's very verbose
612 break;
613 default: {
614 ESP_LOGV(TAG, "Unhandled type: advType: 0x%02x", record_type);
615 break;
616 }
617 }
618 }
619}
620
621std::string ESPBTDevice::address_str() const {
622 char mac[18];
624 return mac;
625}
626
628#endif // USE_ESP32_BLE_DEVICE
629
631 ESP_LOGCONFIG(TAG, "BLE Tracker:");
632 ESP_LOGCONFIG(TAG,
633 " Scan Duration: %" PRIu32 " s\n"
634 " Scan Interval: %.1f ms\n"
635 " Scan Window: %.1f ms\n"
636 " Scan Type: %s\n"
637 " Continuous Scanning: %s",
638 this->scan_duration_, this->scan_interval_ * 0.625f, this->scan_window_ * 0.625f,
639 this->scan_active_ ? "ACTIVE" : "PASSIVE", YESNO(this->scan_continuous_));
640 ESP_LOGCONFIG(TAG, " Scanner State: %s", this->scanner_state_to_string_(this->scanner_state_));
641 ESP_LOGCONFIG(TAG, " Connecting: %d, discovered: %d, disconnecting: %d", this->client_state_counts_.connecting,
642 this->client_state_counts_.discovered, this->client_state_counts_.disconnecting);
643 if (this->scan_start_fail_count_) {
644 ESP_LOGCONFIG(TAG, " Scan Start Fail Count: %d", this->scan_start_fail_count_);
645 }
646}
647
648#ifdef USE_ESP32_BLE_DEVICE
650 const uint64_t address = device.address_uint64();
651 for (auto &disc : this->already_discovered_) {
652 if (disc == address)
653 return;
654 }
655 this->already_discovered_.push_back(address);
656
657 ESP_LOGD(TAG, "Found device %s RSSI=%d", device.address_str().c_str(), device.get_rssi());
658
659 const char *address_type_s;
660 switch (device.get_address_type()) {
661 case BLE_ADDR_TYPE_PUBLIC:
662 address_type_s = "PUBLIC";
663 break;
664 case BLE_ADDR_TYPE_RANDOM:
665 address_type_s = "RANDOM";
666 break;
667 case BLE_ADDR_TYPE_RPA_PUBLIC:
668 address_type_s = "RPA_PUBLIC";
669 break;
670 case BLE_ADDR_TYPE_RPA_RANDOM:
671 address_type_s = "RPA_RANDOM";
672 break;
673 default:
674 address_type_s = "UNKNOWN";
675 break;
676 }
677
678 ESP_LOGD(TAG, " Address Type: %s", address_type_s);
679 if (!device.get_name().empty()) {
680 ESP_LOGD(TAG, " Name: '%s'", device.get_name().c_str());
681 }
682 for (auto &tx_power : device.get_tx_powers()) {
683 ESP_LOGD(TAG, " TX Power: %d", tx_power);
684 }
685}
686
687bool ESPBTDevice::resolve_irk(const uint8_t *irk) const {
688 uint8_t ecb_key[16];
689 uint8_t ecb_plaintext[16];
690 uint8_t ecb_ciphertext[16];
691
692 uint64_t addr64 = esp32_ble::ble_addr_to_uint64(this->address_);
693
694 memcpy(&ecb_key, irk, 16);
695 memset(&ecb_plaintext, 0, 16);
696
697 ecb_plaintext[13] = (addr64 >> 40) & 0xff;
698 ecb_plaintext[14] = (addr64 >> 32) & 0xff;
699 ecb_plaintext[15] = (addr64 >> 24) & 0xff;
700
701 mbedtls_aes_context ctx = {0, 0, {0}};
702 mbedtls_aes_init(&ctx);
703
704 if (mbedtls_aes_setkey_enc(&ctx, ecb_key, 128) != 0) {
705 mbedtls_aes_free(&ctx);
706 return false;
707 }
708
709 if (mbedtls_aes_crypt_ecb(&ctx, ESP_AES_ENCRYPT, ecb_plaintext, ecb_ciphertext) != 0) {
710 mbedtls_aes_free(&ctx);
711 return false;
712 }
713
714 mbedtls_aes_free(&ctx);
715
716 return ecb_ciphertext[15] == (addr64 & 0xff) && ecb_ciphertext[14] == ((addr64 >> 8) & 0xff) &&
717 ecb_ciphertext[13] == ((addr64 >> 16) & 0xff);
718}
719
720#endif // USE_ESP32_BLE_DEVICE
721
722void ESP32BLETracker::process_scan_result_(const BLEScanResult &scan_result) {
723 // Process raw advertisements
724 if (this->raw_advertisements_) {
725#ifdef ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT
726 for (auto *listener : this->listeners_) {
727 listener->parse_devices(&scan_result, 1);
728 }
729#endif
730#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
731 for (auto *client : this->clients_) {
732 client->parse_devices(&scan_result, 1);
733 }
734#endif
735 }
736
737 // Process parsed advertisements
738 if (this->parse_advertisements_) {
739#ifdef USE_ESP32_BLE_DEVICE
740 ESPBTDevice device;
741 device.parse_scan_rst(scan_result);
742
743 bool found = false;
744#ifdef ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT
745 for (auto *listener : this->listeners_) {
746 if (listener->parse_device(device))
747 found = true;
748 }
749#endif
750
751#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
752 for (auto *client : this->clients_) {
753 if (client->parse_device(device)) {
754 found = true;
755 }
756 }
757#endif
758
759 if (!found && !this->scan_continuous_) {
760 this->print_bt_device_info(device);
761 }
762#endif // USE_ESP32_BLE_DEVICE
763 }
764}
765
766void ESP32BLETracker::cleanup_scan_state_(bool is_stop_complete) {
767 ESP_LOGD(TAG, "Scan %scomplete, set scanner state to IDLE.", is_stop_complete ? "stop " : "");
768#ifdef USE_ESP32_BLE_DEVICE
769 this->already_discovered_.clear();
770#endif
771 // Reset timeout state machine instead of cancelling scheduler timeout
773
774#ifdef ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT
775 for (auto *listener : this->listeners_)
776 listener->on_scan_end();
777#endif
778
780}
781
783 this->stop_scan_();
784 if (this->scan_start_fail_count_ == std::numeric_limits<uint8_t>::max()) {
785 ESP_LOGE(TAG, "Scan could not restart after %d attempts, rebooting to restore stack (IDF)",
786 std::numeric_limits<uint8_t>::max());
787 App.reboot();
788 }
789 if (this->scan_start_failed_) {
790 ESP_LOGE(TAG, "Scan start failed: %d", this->scan_start_failed_);
791 this->scan_start_failed_ = ESP_BT_STATUS_SUCCESS;
792 }
793 if (this->scan_set_param_failed_) {
794 ESP_LOGE(TAG, "Scan set param failed: %d", this->scan_set_param_failed_);
795 this->scan_set_param_failed_ = ESP_BT_STATUS_SUCCESS;
796 }
797}
798
800 // Only promote the first discovered client to avoid multiple simultaneous connections
801#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
802 for (auto *client : this->clients_) {
803 if (client->state() != ClientState::DISCOVERED) {
804 continue;
805 }
806
808 ESP_LOGD(TAG, "Stopping scan to make connection");
809 this->stop_scan_();
810 // Don't wait for scan stop complete - promote immediately.
811 // This is safe because ESP-IDF processes BLE commands sequentially through its internal mailbox queue.
812 // This guarantees that the stop scan command will be fully processed before any subsequent connect command,
813 // preventing race conditions or overlapping operations.
814 }
815
816 ESP_LOGD(TAG, "Promoting client to connect");
817#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
818 this->update_coex_preference_(true);
819#endif
820 client->connect();
821 break;
822 }
823#endif
824}
825
827 switch (state) {
829 return "IDLE";
831 return "STARTING";
833 return "RUNNING";
835 return "STOPPING";
837 return "FAILED";
838 default:
839 return "UNKNOWN";
840 }
841}
842
843void ESP32BLETracker::log_unexpected_state_(const char *operation, ScannerState expected_state) const {
844 ESP_LOGE(TAG, "Unexpected state: %s on %s, expected: %s", this->scanner_state_to_string_(this->scanner_state_),
845 operation, this->scanner_state_to_string_(expected_state));
846}
847
848#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
850#ifndef CONFIG_ESP_HOSTED_ENABLE_BT_BLUEDROID
851 if (force_ble && !this->coex_prefer_ble_) {
852 ESP_LOGD(TAG, "Setting coexistence to Bluetooth to make connection.");
853 this->coex_prefer_ble_ = true;
854 esp_coex_preference_set(ESP_COEX_PREFER_BT); // Prioritize Bluetooth
855 } else if (!force_ble && this->coex_prefer_ble_) {
856 ESP_LOGD(TAG, "Setting coexistence preference to balanced.");
857 this->coex_prefer_ble_ = false;
858 esp_coex_preference_set(ESP_COEX_PREFER_BALANCE); // Reset to default
859 }
860#endif // CONFIG_ESP_HOSTED_ENABLE_BT_BLUEDROID
861}
862#endif
863
864} // namespace esphome::esp32_ble_tracker
865
866#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.
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.
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.
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:649
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:604
std::string size_t len
Definition helpers.h:483
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:317
Application App
Global storage of Application pointer - only one Application can exist.