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