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