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