ESPHome 2025.5.0
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
38namespace esphome {
39namespace esp32_ble_tracker {
40
41static const char *const TAG = "esp32_ble_tracker";
42
43ESP32BLETracker *global_esp32_ble_tracker = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
44
46
48 if (this->parent_->is_failed()) {
49 this->mark_failed();
50 ESP_LOGE(TAG, "BLE Tracker was marked failed by ESP32BLE");
51 return;
52 }
56
57 if (this->scan_result_buffer_ == nullptr) {
58 ESP_LOGE(TAG, "Could not allocate buffer for BLE Tracker!");
59 this->mark_failed();
60 }
61
62 global_esp32_ble_tracker = this;
63 this->scan_result_lock_ = xSemaphoreCreateMutex();
64
65#ifdef USE_OTA
67 [this](ota::OTAState state, float progress, uint8_t error, ota::OTAComponent *comp) {
68 if (state == ota::OTA_STARTED) {
69 this->stop_scan();
70 for (auto *client : this->clients_) {
71 client->disconnect();
72 }
73 }
74 });
75#endif
76}
77
79 if (!this->parent_->is_active()) {
80 this->ble_was_disabled_ = true;
81 return;
82 } else if (this->ble_was_disabled_) {
83 this->ble_was_disabled_ = false;
84 // If the BLE stack was disabled, we need to start the scan again.
85 if (this->scan_continuous_) {
86 this->start_scan();
87 }
88 }
89 int connecting = 0;
90 int discovered = 0;
91 int searching = 0;
92 int disconnecting = 0;
93 for (auto *client : this->clients_) {
94 switch (client->state()) {
96 disconnecting++;
97 break;
99 discovered++;
100 break;
102 searching++;
103 break;
106 connecting++;
107 break;
108 default:
109 break;
110 }
111 }
112 if (connecting != connecting_ || discovered != discovered_ || searching != searching_ ||
113 disconnecting != disconnecting_) {
114 connecting_ = connecting;
115 discovered_ = discovered;
116 searching_ = searching;
117 disconnecting_ = disconnecting;
118 ESP_LOGD(TAG, "connecting: %d, discovered: %d, searching: %d, disconnecting: %d", connecting_, discovered_,
120 }
121 bool promote_to_connecting = discovered && !searching && !connecting;
122
124 this->scan_result_index_ && // if it looks like we have a scan result we will take the lock
125 xSemaphoreTake(this->scan_result_lock_, 0)) {
126 uint32_t index = this->scan_result_index_;
128 ESP_LOGW(TAG, "Too many BLE events to process. Some devices may not show up.");
129 }
130
131 if (this->raw_advertisements_) {
132 for (auto *listener : this->listeners_) {
133 listener->parse_devices(this->scan_result_buffer_, this->scan_result_index_);
134 }
135 for (auto *client : this->clients_) {
136 client->parse_devices(this->scan_result_buffer_, this->scan_result_index_);
137 }
138 }
139
140 if (this->parse_advertisements_) {
141 for (size_t i = 0; i < index; i++) {
142 ESPBTDevice device;
143 device.parse_scan_rst(this->scan_result_buffer_[i]);
144
145 bool found = false;
146 for (auto *listener : this->listeners_) {
147 if (listener->parse_device(device))
148 found = true;
149 }
150
151 for (auto *client : this->clients_) {
152 if (client->parse_device(device)) {
153 found = true;
154 if (!connecting && client->state() == ClientState::DISCOVERED) {
155 promote_to_connecting = true;
156 }
157 }
158 }
159
160 if (!found && !this->scan_continuous_) {
161 this->print_bt_device_info(device);
162 }
163 }
164 }
165 this->scan_result_index_ = 0;
166 xSemaphoreGive(this->scan_result_lock_);
167 }
169 this->end_of_scan_(); // Change state to IDLE
170 }
173 this->stop_scan_();
174 if (this->scan_start_fail_count_ == std::numeric_limits<uint8_t>::max()) {
175 ESP_LOGE(TAG, "ESP-IDF BLE scan could not restart after %d attempts, rebooting to restore BLE stack...",
176 std::numeric_limits<uint8_t>::max());
177 App.reboot();
178 }
179 if (this->scan_start_failed_) {
180 ESP_LOGE(TAG, "Scan start failed: %d", this->scan_start_failed_);
181 this->scan_start_failed_ = ESP_BT_STATUS_SUCCESS;
182 }
183 if (this->scan_set_param_failed_) {
184 ESP_LOGE(TAG, "Scan set param failed: %d", this->scan_set_param_failed_);
185 this->scan_set_param_failed_ = ESP_BT_STATUS_SUCCESS;
186 }
187 }
188 /*
189
190 Avoid starting the scanner if:
191 - we are already scanning
192 - we are connecting to a device
193 - we are disconnecting from a device
194
195 Otherwise the scanner could fail to ever start again
196 and our only way to recover is to reboot.
197
198 https://github.com/espressif/esp-idf/issues/6688
199
200 */
201 if (this->scanner_state_ == ScannerState::IDLE && !connecting && !disconnecting && !promote_to_connecting) {
202#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
203 if (this->coex_prefer_ble_) {
204 this->coex_prefer_ble_ = false;
205 ESP_LOGD(TAG, "Setting coexistence preference to balanced.");
206 esp_coex_preference_set(ESP_COEX_PREFER_BALANCE); // Reset to default
207 }
208#endif
209 if (this->scan_continuous_) {
210 this->start_scan_(false); // first = false
211 }
212 }
213 // If there is a discovered client and no connecting
214 // clients and no clients using the scanner to search for
215 // devices, then stop scanning and promote the discovered
216 // client to ready to connect.
217 if (promote_to_connecting &&
219 for (auto *client : this->clients_) {
220 if (client->state() == ClientState::DISCOVERED) {
222 ESP_LOGD(TAG, "Stopping scan to make connection...");
223 this->stop_scan_();
224 } else if (this->scanner_state_ == ScannerState::IDLE) {
225 ESP_LOGD(TAG, "Promoting client to connect...");
226 // We only want to promote one client at a time.
227 // once the scanner is fully stopped.
228#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
229 ESP_LOGD(TAG, "Setting coexistence to Bluetooth to make connection.");
230 if (!this->coex_prefer_ble_) {
231 this->coex_prefer_ble_ = true;
232 esp_coex_preference_set(ESP_COEX_PREFER_BT); // Prioritize Bluetooth
233 }
234#endif
235 client->set_state(ClientState::READY_TO_CONNECT);
236 }
237 break;
238 }
239 }
240 }
241}
242
244
246 ESP_LOGD(TAG, "Stopping scan.");
247 this->scan_continuous_ = false;
248 this->stop_scan_();
249}
250
252
255 if (this->scanner_state_ == ScannerState::IDLE) {
256 ESP_LOGE(TAG, "Scan is already stopped while trying to stop.");
257 } else if (this->scanner_state_ == ScannerState::STARTING) {
258 ESP_LOGE(TAG, "Scan is starting while trying to stop.");
259 } else if (this->scanner_state_ == ScannerState::STOPPING) {
260 ESP_LOGE(TAG, "Scan is already stopping while trying to stop.");
261 } else if (this->scanner_state_ == ScannerState::STOPPED) {
262 ESP_LOGE(TAG, "Scan is already stopped while trying to stop.");
263 }
264 return;
265 }
266 this->cancel_timeout("scan");
268 esp_err_t err = esp_ble_gap_stop_scanning();
269 if (err != ESP_OK) {
270 ESP_LOGE(TAG, "esp_ble_gap_stop_scanning failed: %d", err);
271 return;
272 }
273}
274
276 if (!this->parent_->is_active()) {
277 ESP_LOGW(TAG, "Cannot start scan while ESP32BLE is disabled.");
278 return;
279 }
280 if (this->scanner_state_ != ScannerState::IDLE) {
282 ESP_LOGE(TAG, "Cannot start scan while already starting.");
283 } else if (this->scanner_state_ == ScannerState::RUNNING) {
284 ESP_LOGE(TAG, "Cannot start scan while already running.");
285 } else if (this->scanner_state_ == ScannerState::STOPPING) {
286 ESP_LOGE(TAG, "Cannot start scan while already stopping.");
287 } else if (this->scanner_state_ == ScannerState::FAILED) {
288 ESP_LOGE(TAG, "Cannot start scan while already failed.");
289 } else if (this->scanner_state_ == ScannerState::STOPPED) {
290 ESP_LOGE(TAG, "Cannot start scan while already stopped.");
291 }
292 return;
293 }
295 ESP_LOGD(TAG, "Starting scan, set scanner state to STARTING.");
296 if (!first) {
297 for (auto *listener : this->listeners_)
298 listener->on_scan_end();
299 }
300 this->already_discovered_.clear();
301 this->scan_params_.scan_type = this->scan_active_ ? BLE_SCAN_TYPE_ACTIVE : BLE_SCAN_TYPE_PASSIVE;
302 this->scan_params_.own_addr_type = BLE_ADDR_TYPE_PUBLIC;
303 this->scan_params_.scan_filter_policy = BLE_SCAN_FILTER_ALLOW_ALL;
304 this->scan_params_.scan_interval = this->scan_interval_;
305 this->scan_params_.scan_window = this->scan_window_;
306
307 // Start timeout before scan is started. Otherwise scan never starts if any error.
308 this->set_timeout("scan", this->scan_duration_ * 2000, []() {
309 ESP_LOGE(TAG, "ESP-IDF BLE scan never terminated, rebooting to restore BLE stack...");
310 App.reboot();
311 });
312
313 esp_err_t err = esp_ble_gap_set_scan_params(&this->scan_params_);
314 if (err != ESP_OK) {
315 ESP_LOGE(TAG, "esp_ble_gap_set_scan_params failed: %d", err);
316 return;
317 }
318 err = esp_ble_gap_start_scanning(this->scan_duration_);
319 if (err != ESP_OK) {
320 ESP_LOGE(TAG, "esp_ble_gap_start_scanning failed: %d", err);
321 return;
322 }
323}
324
326 // The lock must be held when calling this function.
328 ESP_LOGE(TAG, "end_of_scan_ called while scanner is not stopped.");
329 return;
330 }
331 ESP_LOGD(TAG, "End of scan, set scanner state to IDLE.");
332 this->already_discovered_.clear();
333 this->cancel_timeout("scan");
334
335 for (auto *listener : this->listeners_)
336 listener->on_scan_end();
338}
339
341 client->app_id = ++this->app_id_;
342 this->clients_.push_back(client);
344}
345
347 listener->set_parent(this);
348 this->listeners_.push_back(listener);
350}
351
353 this->raw_advertisements_ = false;
354 this->parse_advertisements_ = false;
355 for (auto *listener : this->listeners_) {
356 if (listener->get_advertisement_parser_type() == AdvertisementParserType::PARSED_ADVERTISEMENTS) {
357 this->parse_advertisements_ = true;
358 } else {
359 this->raw_advertisements_ = true;
360 }
361 }
362 for (auto *client : this->clients_) {
363 if (client->get_advertisement_parser_type() == AdvertisementParserType::PARSED_ADVERTISEMENTS) {
364 this->parse_advertisements_ = true;
365 } else {
366 this->raw_advertisements_ = true;
367 }
368 }
369}
370
371void ESP32BLETracker::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
372 switch (event) {
373 case ESP_GAP_BLE_SCAN_RESULT_EVT:
374 this->gap_scan_result_(param->scan_rst);
375 break;
376 case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT:
377 this->gap_scan_set_param_complete_(param->scan_param_cmpl);
378 break;
379 case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT:
380 this->gap_scan_start_complete_(param->scan_start_cmpl);
381 break;
382 case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT:
383 this->gap_scan_stop_complete_(param->scan_stop_cmpl);
384 break;
385 default:
386 break;
387 }
388 for (auto *client : this->clients_) {
389 client->gap_event_handler(event, param);
390 }
391}
392
393void ESP32BLETracker::gap_scan_set_param_complete_(const esp_ble_gap_cb_param_t::ble_scan_param_cmpl_evt_param &param) {
394 ESP_LOGV(TAG, "gap_scan_set_param_complete - status %d", param.status);
395 if (param.status == ESP_BT_STATUS_DONE) {
396 this->scan_set_param_failed_ = ESP_BT_STATUS_SUCCESS;
397 } else {
398 this->scan_set_param_failed_ = param.status;
399 }
400}
401
402void ESP32BLETracker::gap_scan_start_complete_(const esp_ble_gap_cb_param_t::ble_scan_start_cmpl_evt_param &param) {
403 ESP_LOGV(TAG, "gap_scan_start_complete - status %d", param.status);
404 this->scan_start_failed_ = param.status;
407 ESP_LOGE(TAG, "Scan was already running when start complete.");
408 } else if (this->scanner_state_ == ScannerState::STOPPING) {
409 ESP_LOGE(TAG, "Scan was stopping when start complete.");
410 } else if (this->scanner_state_ == ScannerState::FAILED) {
411 ESP_LOGE(TAG, "Scan was in failed state when start complete.");
412 } else if (this->scanner_state_ == ScannerState::IDLE) {
413 ESP_LOGE(TAG, "Scan was idle when start complete.");
414 } else if (this->scanner_state_ == ScannerState::STOPPED) {
415 ESP_LOGE(TAG, "Scan was stopped when start complete.");
416 }
417 }
418 if (param.status == ESP_BT_STATUS_SUCCESS) {
419 this->scan_start_fail_count_ = 0;
421 } else {
423 if (this->scan_start_fail_count_ != std::numeric_limits<uint8_t>::max()) {
425 }
426 }
427}
428
429void ESP32BLETracker::gap_scan_stop_complete_(const esp_ble_gap_cb_param_t::ble_scan_stop_cmpl_evt_param &param) {
430 ESP_LOGV(TAG, "gap_scan_stop_complete - status %d", param.status);
433 ESP_LOGE(TAG, "Scan was not running when stop complete.");
434 } else if (this->scanner_state_ == ScannerState::STARTING) {
435 ESP_LOGE(TAG, "Scan was not started when stop complete.");
436 } else if (this->scanner_state_ == ScannerState::FAILED) {
437 ESP_LOGE(TAG, "Scan was in failed state when stop complete.");
438 } else if (this->scanner_state_ == ScannerState::IDLE) {
439 ESP_LOGE(TAG, "Scan was idle when stop complete.");
440 } else if (this->scanner_state_ == ScannerState::STOPPED) {
441 ESP_LOGE(TAG, "Scan was stopped when stop complete.");
442 }
443 }
445}
446
447void ESP32BLETracker::gap_scan_result_(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param &param) {
448 ESP_LOGV(TAG, "gap_scan_result - event %d", param.search_evt);
449 if (param.search_evt == ESP_GAP_SEARCH_INQ_RES_EVT) {
450 if (xSemaphoreTake(this->scan_result_lock_, 0)) {
452 this->scan_result_buffer_[this->scan_result_index_++] = param;
453 }
454 xSemaphoreGive(this->scan_result_lock_);
455 }
456 } else if (param.search_evt == ESP_GAP_SEARCH_INQ_CMPL_EVT) {
457 // Scan finished on its own
460 ESP_LOGE(TAG, "Scan was not running when scan completed.");
461 } else if (this->scanner_state_ == ScannerState::STARTING) {
462 ESP_LOGE(TAG, "Scan was not started when scan completed.");
463 } else if (this->scanner_state_ == ScannerState::FAILED) {
464 ESP_LOGE(TAG, "Scan was in failed state when scan completed.");
465 } else if (this->scanner_state_ == ScannerState::IDLE) {
466 ESP_LOGE(TAG, "Scan was idle when scan completed.");
467 } else if (this->scanner_state_ == ScannerState::STOPPED) {
468 ESP_LOGE(TAG, "Scan was stopped when scan completed.");
469 }
470 }
472 }
473}
474
475void ESP32BLETracker::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
476 esp_ble_gattc_cb_param_t *param) {
477 for (auto *client : this->clients_) {
478 client->gattc_event_handler(event, gattc_if, param);
479 }
480}
481
486
487ESPBLEiBeacon::ESPBLEiBeacon(const uint8_t *data) { memcpy(&this->beacon_data_, data, sizeof(beacon_data_)); }
489 if (!data.uuid.contains(0x4C, 0x00))
490 return {};
491
492 if (data.data.size() != 23)
493 return {};
494 return ESPBLEiBeacon(data.data.data());
495}
496
497void ESPBTDevice::parse_scan_rst(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param &param) {
498 this->scan_result_ = param;
499 for (uint8_t i = 0; i < ESP_BD_ADDR_LEN; i++)
500 this->address_[i] = param.bda[i];
501 this->address_type_ = param.ble_addr_type;
502 this->rssi_ = param.rssi;
503 this->parse_adv_(param);
504
505#ifdef ESPHOME_LOG_HAS_VERY_VERBOSE
506 ESP_LOGVV(TAG, "Parse Result:");
507 const char *address_type;
508 switch (this->address_type_) {
509 case BLE_ADDR_TYPE_PUBLIC:
510 address_type = "PUBLIC";
511 break;
512 case BLE_ADDR_TYPE_RANDOM:
513 address_type = "RANDOM";
514 break;
515 case BLE_ADDR_TYPE_RPA_PUBLIC:
516 address_type = "RPA_PUBLIC";
517 break;
518 case BLE_ADDR_TYPE_RPA_RANDOM:
519 address_type = "RPA_RANDOM";
520 break;
521 default:
522 address_type = "UNKNOWN";
523 break;
524 }
525 ESP_LOGVV(TAG, " Address: %02X:%02X:%02X:%02X:%02X:%02X (%s)", this->address_[0], this->address_[1],
526 this->address_[2], this->address_[3], this->address_[4], this->address_[5], address_type);
527
528 ESP_LOGVV(TAG, " RSSI: %d", this->rssi_);
529 ESP_LOGVV(TAG, " Name: '%s'", this->name_.c_str());
530 for (auto &it : this->tx_powers_) {
531 ESP_LOGVV(TAG, " TX Power: %d", it);
532 }
533 if (this->appearance_.has_value()) {
534 ESP_LOGVV(TAG, " Appearance: %u", *this->appearance_);
535 }
536 if (this->ad_flag_.has_value()) {
537 ESP_LOGVV(TAG, " Ad Flag: %u", *this->ad_flag_);
538 }
539 for (auto &uuid : this->service_uuids_) {
540 ESP_LOGVV(TAG, " Service UUID: %s", uuid.to_string().c_str());
541 }
542 for (auto &data : this->manufacturer_datas_) {
543 auto ibeacon = ESPBLEiBeacon::from_manufacturer_data(data);
544 if (ibeacon.has_value()) {
545 ESP_LOGVV(TAG, " Manufacturer iBeacon:");
546 ESP_LOGVV(TAG, " UUID: %s", ibeacon.value().get_uuid().to_string().c_str());
547 ESP_LOGVV(TAG, " Major: %u", ibeacon.value().get_major());
548 ESP_LOGVV(TAG, " Minor: %u", ibeacon.value().get_minor());
549 ESP_LOGVV(TAG, " TXPower: %d", ibeacon.value().get_signal_power());
550 } else {
551 ESP_LOGVV(TAG, " Manufacturer ID: %s, data: %s", data.uuid.to_string().c_str(),
552 format_hex_pretty(data.data).c_str());
553 }
554 }
555 for (auto &data : this->service_datas_) {
556 ESP_LOGVV(TAG, " Service data:");
557 ESP_LOGVV(TAG, " UUID: %s", data.uuid.to_string().c_str());
558 ESP_LOGVV(TAG, " Data: %s", format_hex_pretty(data.data).c_str());
559 }
560
561 ESP_LOGVV(TAG, " Adv data: %s", format_hex_pretty(param.ble_adv, param.adv_data_len + param.scan_rsp_len).c_str());
562#endif
563}
564void ESPBTDevice::parse_adv_(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param &param) {
565 size_t offset = 0;
566 const uint8_t *payload = param.ble_adv;
567 uint8_t len = param.adv_data_len + param.scan_rsp_len;
568
569 while (offset + 2 < len) {
570 const uint8_t field_length = payload[offset++]; // First byte is length of adv record
571 if (field_length == 0) {
572 continue; // Possible zero padded advertisement data
573 }
574
575 // first byte of adv record is adv record type
576 const uint8_t record_type = payload[offset++];
577 const uint8_t *record = &payload[offset];
578 const uint8_t record_length = field_length - 1;
579 offset += record_length;
580
581 // See also Generic Access Profile Assigned Numbers:
582 // https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile/ See also ADVERTISING AND SCAN
583 // RESPONSE DATA FORMAT: https://www.bluetooth.com/specifications/bluetooth-core-specification/ (vol 3, part C, 11)
584 // See also Core Specification Supplement: https://www.bluetooth.com/specifications/bluetooth-core-specification/
585 // (called CSS here)
586
587 switch (record_type) {
588 case ESP_BLE_AD_TYPE_NAME_SHORT:
589 case ESP_BLE_AD_TYPE_NAME_CMPL: {
590 // CSS 1.2 LOCAL NAME
591 // "The Local Name data type shall be the same as, or a shortened version of, the local name assigned to the
592 // device." CSS 1: Optional in this context; shall not appear more than once in a block.
593 // SHORTENED LOCAL NAME
594 // "The Shortened Local Name data type defines a shortened version of the Local Name data type. The Shortened
595 // Local Name data type shall not be used to advertise a name that is longer than the Local Name data type."
596 if (record_length > this->name_.length()) {
597 this->name_ = std::string(reinterpret_cast<const char *>(record), record_length);
598 }
599 break;
600 }
601 case ESP_BLE_AD_TYPE_TX_PWR: {
602 // CSS 1.5 TX POWER LEVEL
603 // "The TX Power Level data type indicates the transmitted power level of the packet containing the data type."
604 // CSS 1: Optional in this context (may appear more than once in a block).
605 this->tx_powers_.push_back(*payload);
606 break;
607 }
608 case ESP_BLE_AD_TYPE_APPEARANCE: {
609 // CSS 1.12 APPEARANCE
610 // "The Appearance data type defines the external appearance of the device."
611 // See also https://www.bluetooth.com/specifications/gatt/characteristics/
612 // CSS 1: Optional in this context; shall not appear more than once in a block and shall not appear in both
613 // the AD and SRD of the same extended advertising interval.
614 this->appearance_ = *reinterpret_cast<const uint16_t *>(record);
615 break;
616 }
617 case ESP_BLE_AD_TYPE_FLAG: {
618 // CSS 1.3 FLAGS
619 // "The Flags data type contains one bit Boolean flags. The Flags data type shall be included when any of the
620 // Flag bits are non-zero and the advertising packet is connectable, otherwise the Flags data type may be
621 // omitted."
622 // CSS 1: Optional in this context; shall not appear more than once in a block.
623 this->ad_flag_ = *record;
624 break;
625 }
626 // CSS 1.1 SERVICE UUID
627 // The Service UUID data type is used to include a list of Service or Service Class UUIDs.
628 // There are six data types defined for the three sizes of Service UUIDs that may be returned:
629 // CSS 1: Optional in this context (may appear more than once in a block).
630 case ESP_BLE_AD_TYPE_16SRV_CMPL:
631 case ESP_BLE_AD_TYPE_16SRV_PART: {
632 // • 16-bit Bluetooth Service UUIDs
633 for (uint8_t i = 0; i < record_length / 2; i++) {
634 this->service_uuids_.push_back(ESPBTUUID::from_uint16(*reinterpret_cast<const uint16_t *>(record + 2 * i)));
635 }
636 break;
637 }
638 case ESP_BLE_AD_TYPE_32SRV_CMPL:
639 case ESP_BLE_AD_TYPE_32SRV_PART: {
640 // • 32-bit Bluetooth Service UUIDs
641 for (uint8_t i = 0; i < record_length / 4; i++) {
642 this->service_uuids_.push_back(ESPBTUUID::from_uint32(*reinterpret_cast<const uint32_t *>(record + 4 * i)));
643 }
644 break;
645 }
646 case ESP_BLE_AD_TYPE_128SRV_CMPL:
647 case ESP_BLE_AD_TYPE_128SRV_PART: {
648 // • Global 128-bit Service UUIDs
649 this->service_uuids_.push_back(ESPBTUUID::from_raw(record));
650 break;
651 }
652 case ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE: {
653 // CSS 1.4 MANUFACTURER SPECIFIC DATA
654 // "The Manufacturer Specific data type is used for manufacturer specific data. The first two data octets shall
655 // contain a company identifier from Assigned Numbers. The interpretation of any other octets within the data
656 // shall be defined by the manufacturer specified by the company identifier."
657 // CSS 1: Optional in this context (may appear more than once in a block).
658 if (record_length < 2) {
659 ESP_LOGV(TAG, "Record length too small for ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE");
660 break;
661 }
662 ServiceData data{};
663 data.uuid = ESPBTUUID::from_uint16(*reinterpret_cast<const uint16_t *>(record));
664 data.data.assign(record + 2UL, record + record_length);
665 this->manufacturer_datas_.push_back(data);
666 break;
667 }
668
669 // CSS 1.11 SERVICE DATA
670 // "The Service Data data type consists of a service UUID with the data associated with that service."
671 // CSS 1: Optional in this context (may appear more than once in a block).
672 case ESP_BLE_AD_TYPE_SERVICE_DATA: {
673 // «Service Data - 16 bit UUID»
674 // Size: 2 or more octets
675 // The first 2 octets contain the 16 bit Service UUID fol- lowed by additional service data
676 if (record_length < 2) {
677 ESP_LOGV(TAG, "Record length too small for ESP_BLE_AD_TYPE_SERVICE_DATA");
678 break;
679 }
680 ServiceData data{};
681 data.uuid = ESPBTUUID::from_uint16(*reinterpret_cast<const uint16_t *>(record));
682 data.data.assign(record + 2UL, record + record_length);
683 this->service_datas_.push_back(data);
684 break;
685 }
686 case ESP_BLE_AD_TYPE_32SERVICE_DATA: {
687 // «Service Data - 32 bit UUID»
688 // Size: 4 or more octets
689 // The first 4 octets contain the 32 bit Service UUID fol- lowed by additional service data
690 if (record_length < 4) {
691 ESP_LOGV(TAG, "Record length too small for ESP_BLE_AD_TYPE_32SERVICE_DATA");
692 break;
693 }
694 ServiceData data{};
695 data.uuid = ESPBTUUID::from_uint32(*reinterpret_cast<const uint32_t *>(record));
696 data.data.assign(record + 4UL, record + record_length);
697 this->service_datas_.push_back(data);
698 break;
699 }
700 case ESP_BLE_AD_TYPE_128SERVICE_DATA: {
701 // «Service Data - 128 bit UUID»
702 // Size: 16 or more octets
703 // The first 16 octets contain the 128 bit Service UUID followed by additional service data
704 if (record_length < 16) {
705 ESP_LOGV(TAG, "Record length too small for ESP_BLE_AD_TYPE_128SERVICE_DATA");
706 break;
707 }
708 ServiceData data{};
709 data.uuid = ESPBTUUID::from_raw(record);
710 data.data.assign(record + 16UL, record + record_length);
711 this->service_datas_.push_back(data);
712 break;
713 }
714 case ESP_BLE_AD_TYPE_INT_RANGE:
715 // Avoid logging this as it's very verbose
716 break;
717 default: {
718 ESP_LOGV(TAG, "Unhandled type: advType: 0x%02x", record_type);
719 break;
720 }
721 }
722 }
723}
724std::string ESPBTDevice::address_str() const {
725 char mac[24];
726 snprintf(mac, sizeof(mac), "%02X:%02X:%02X:%02X:%02X:%02X", this->address_[0], this->address_[1], this->address_[2],
727 this->address_[3], this->address_[4], this->address_[5]);
728 return mac;
729}
731
733 ESP_LOGCONFIG(TAG, "BLE Tracker:");
734 ESP_LOGCONFIG(TAG, " Scan Duration: %" PRIu32 " s", this->scan_duration_);
735 ESP_LOGCONFIG(TAG, " Scan Interval: %.1f ms", this->scan_interval_ * 0.625f);
736 ESP_LOGCONFIG(TAG, " Scan Window: %.1f ms", this->scan_window_ * 0.625f);
737 ESP_LOGCONFIG(TAG, " Scan Type: %s", this->scan_active_ ? "ACTIVE" : "PASSIVE");
738 ESP_LOGCONFIG(TAG, " Continuous Scanning: %s", YESNO(this->scan_continuous_));
739 switch (this->scanner_state_) {
741 ESP_LOGCONFIG(TAG, " Scanner State: IDLE");
742 break;
744 ESP_LOGCONFIG(TAG, " Scanner State: STARTING");
745 break;
747 ESP_LOGCONFIG(TAG, " Scanner State: RUNNING");
748 break;
750 ESP_LOGCONFIG(TAG, " Scanner State: STOPPING");
751 break;
753 ESP_LOGCONFIG(TAG, " Scanner State: STOPPED");
754 break;
756 ESP_LOGCONFIG(TAG, " Scanner State: FAILED");
757 break;
758 }
759 ESP_LOGCONFIG(TAG, " Connecting: %d, discovered: %d, searching: %d, disconnecting: %d", connecting_, discovered_,
761 if (this->scan_start_fail_count_) {
762 ESP_LOGCONFIG(TAG, " Scan Start Fail Count: %d", this->scan_start_fail_count_);
763 }
764}
765
767 const uint64_t address = device.address_uint64();
768 for (auto &disc : this->already_discovered_) {
769 if (disc == address)
770 return;
771 }
772 this->already_discovered_.push_back(address);
773
774 ESP_LOGD(TAG, "Found device %s RSSI=%d", device.address_str().c_str(), device.get_rssi());
775
776 const char *address_type_s;
777 switch (device.get_address_type()) {
778 case BLE_ADDR_TYPE_PUBLIC:
779 address_type_s = "PUBLIC";
780 break;
781 case BLE_ADDR_TYPE_RANDOM:
782 address_type_s = "RANDOM";
783 break;
784 case BLE_ADDR_TYPE_RPA_PUBLIC:
785 address_type_s = "RPA_PUBLIC";
786 break;
787 case BLE_ADDR_TYPE_RPA_RANDOM:
788 address_type_s = "RPA_RANDOM";
789 break;
790 default:
791 address_type_s = "UNKNOWN";
792 break;
793 }
794
795 ESP_LOGD(TAG, " Address Type: %s", address_type_s);
796 if (!device.get_name().empty()) {
797 ESP_LOGD(TAG, " Name: '%s'", device.get_name().c_str());
798 }
799 for (auto &tx_power : device.get_tx_powers()) {
800 ESP_LOGD(TAG, " TX Power: %d", tx_power);
801 }
802}
803
804bool ESPBTDevice::resolve_irk(const uint8_t *irk) const {
805 uint8_t ecb_key[16];
806 uint8_t ecb_plaintext[16];
807 uint8_t ecb_ciphertext[16];
808
809 uint64_t addr64 = esp32_ble::ble_addr_to_uint64(this->address_);
810
811 memcpy(&ecb_key, irk, 16);
812 memset(&ecb_plaintext, 0, 16);
813
814 ecb_plaintext[13] = (addr64 >> 40) & 0xff;
815 ecb_plaintext[14] = (addr64 >> 32) & 0xff;
816 ecb_plaintext[15] = (addr64 >> 24) & 0xff;
817
818 mbedtls_aes_context ctx = {0, 0, {0}};
819 mbedtls_aes_init(&ctx);
820
821 if (mbedtls_aes_setkey_enc(&ctx, ecb_key, 128) != 0) {
822 mbedtls_aes_free(&ctx);
823 return false;
824 }
825
826 if (mbedtls_aes_crypt_ecb(&ctx, ESP_AES_ENCRYPT, ecb_plaintext, ecb_ciphertext) != 0) {
827 mbedtls_aes_free(&ctx);
828 return false;
829 }
830
831 mbedtls_aes_free(&ctx);
832
833 return ecb_ciphertext[15] == (addr64 & 0xff) && ecb_ciphertext[14] == ((addr64 >> 8) & 0xff) &&
834 ecb_ciphertext[13] == ((addr64 >> 16) & 0xff);
835}
836
837} // namespace esp32_ble_tracker
838} // namespace esphome
839
840#endif
uint8_t address
Definition bl0906.h:4
virtual void mark_failed()
Mark this component as failed.
bool cancel_timeout(const std::string &name)
Cancel a timeout function.
Definition component.cpp:76
void set_timeout(const std::string &name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
Definition component.cpp:72
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:683
T * allocate(size_t n)
Definition helpers.h:703
static ESPBTUUID from_uint32(uint32_t uuid)
Definition ble_uuid.cpp:22
static ESPBTUUID from_uint16(uint16_t uuid)
Definition ble_uuid.cpp:16
static ESPBTUUID from_raw(const uint8_t *data)
Definition ble_uuid.cpp:28
bool contains(uint8_t data1, uint8_t data2) const
Definition ble_uuid.cpp:125
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
esp_ble_gap_cb_param_t::ble_scan_result_evt_param * scan_result_buffer_
esp_ble_scan_params_t scan_params_
A structure holding the ESP BLE scan parameters.
void register_listener(ESPBTDeviceListener *listener)
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 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_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.
std::vector< ESPBTClient * > clients_
Client parameters.
void gap_scan_result_(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param &param)
Called when a ESP_GAP_BLE_SCAN_RESULT_EVT event is received.
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_scan_rst(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param &param)
std::vector< ServiceData > manufacturer_datas_
const std::vector< int8_t > & get_tx_powers() const
esp_ble_gap_cb_param_t::ble_scan_result_evt_param scan_result_
bool resolve_irk(const uint8_t *irk) const
void parse_adv_(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param &param)
std::vector< ServiceData > service_datas_
bool has_value() const
Definition optional.h:87
void add_on_state_callback(std::function< void(OTAState, float, uint8_t, OTAComponent *)> &&callback)
Definition ota_backend.h:82
bool state
Definition fan.h:0
ESP32BLETracker * global_esp32_ble_tracker
uint64_t ble_addr_to_uint64(const esp_bd_addr_t address)
Definition ble.cpp:420
OTAGlobalCallback * get_global_ota_callback()
const float AFTER_BLUETOOTH
Definition component.cpp:22
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
std::string size_t len
Definition helpers.h:301
Application App
Global storage of Application pointer - only one Application can exist.
std::string format_hex_pretty(const uint8_t *data, size_t length)
Format the byte array data of length len in pretty-printed, human-readable hex.
Definition helpers.cpp:372