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