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