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