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