ESPHome  2022.9.1
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 <nvs_flash.h>
11 #include <freertos/FreeRTOSConfig.h>
12 #include <esp_bt_main.h>
13 #include <esp_bt.h>
14 #include <freertos/FreeRTOS.h>
15 #include <freertos/task.h>
16 #include <esp_gap_ble_api.h>
17 #include <esp_bt_defs.h>
18 
19 #ifdef USE_OTA
21 #endif
22 
23 #ifdef USE_ARDUINO
24 #include <esp32-hal-bt.h>
25 #endif
26 
27 // bt_trace.h
28 #undef TAG
29 
30 namespace esphome {
31 namespace esp32_ble_tracker {
32 
33 static const char *const TAG = "esp32_ble_tracker";
34 
35 ESP32BLETracker *global_esp32_ble_tracker = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
36 
37 uint64_t ble_addr_to_uint64(const esp_bd_addr_t address) {
38  uint64_t u = 0;
39  u |= uint64_t(address[0] & 0xFF) << 40;
40  u |= uint64_t(address[1] & 0xFF) << 32;
41  u |= uint64_t(address[2] & 0xFF) << 24;
42  u |= uint64_t(address[3] & 0xFF) << 16;
43  u |= uint64_t(address[4] & 0xFF) << 8;
44  u |= uint64_t(address[5] & 0xFF) << 0;
45  return u;
46 }
47 
49 
51  global_esp32_ble_tracker = this;
52  this->scan_result_lock_ = xSemaphoreCreateMutex();
53  this->scan_end_lock_ = xSemaphoreCreateMutex();
54  this->scanner_idle_ = true;
56  this->mark_failed();
57  return;
58  }
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  this->start_scan_(true);
70  }
71 }
72 
74  BLEEvent *ble_event = this->ble_events_.pop();
75  while (ble_event != nullptr) {
76  if (ble_event->type_) {
77  this->real_gattc_event_handler_(ble_event->event_.gattc.gattc_event, ble_event->event_.gattc.gattc_if,
78  &ble_event->event_.gattc.gattc_param);
79  } else {
80  this->real_gap_event_handler_(ble_event->event_.gap.gap_event, &ble_event->event_.gap.gap_param);
81  }
82  delete ble_event; // NOLINT(cppcoreguidelines-owning-memory)
83  ble_event = this->ble_events_.pop();
84  }
85 
86  if (this->scanner_idle_) {
87  return;
88  }
89 
90  bool connecting = false;
91  for (auto *client : this->clients_) {
92  if (client->state() == ClientState::CONNECTING || client->state() == ClientState::DISCOVERED)
93  connecting = true;
94  }
95 
96  if (!connecting && xSemaphoreTake(this->scan_end_lock_, 0L)) {
97  xSemaphoreGive(this->scan_end_lock_);
98  if (this->scan_continuous_) {
99  this->start_scan_(false);
100  } else if (xSemaphoreTake(this->scan_end_lock_, 0L) && !this->scanner_idle_) {
101  xSemaphoreGive(this->scan_end_lock_);
102  this->end_of_scan_();
103  return;
104  }
105  }
106 
107  if (xSemaphoreTake(this->scan_result_lock_, 5L / portTICK_PERIOD_MS)) {
108  uint32_t index = this->scan_result_index_;
109  xSemaphoreGive(this->scan_result_lock_);
110 
111  if (index >= 16) {
112  ESP_LOGW(TAG, "Too many BLE events to process. Some devices may not show up.");
113  }
114  for (size_t i = 0; i < index; i++) {
115  ESPBTDevice device;
116  device.parse_scan_rst(this->scan_result_buffer_[i]);
117 
118  bool found = false;
119  for (auto *listener : this->listeners_) {
120  if (listener->parse_device(device))
121  found = true;
122  }
123 
124  for (auto *client : this->clients_) {
125  if (client->parse_device(device)) {
126  found = true;
127  if (client->state() == ClientState::DISCOVERED) {
128  esp_ble_gap_stop_scanning();
129 #ifdef USE_ARDUINO
130  constexpr TickType_t block_time = 10L / portTICK_PERIOD_MS;
131 #else
132  constexpr TickType_t block_time = 0L; // PR #3594
133 #endif
134  if (xSemaphoreTake(this->scan_end_lock_, block_time)) {
135  xSemaphoreGive(this->scan_end_lock_);
136  }
137  }
138  }
139  }
140 
141  if (!found) {
142  this->print_bt_device_info(device);
143  }
144  }
145 
146  if (xSemaphoreTake(this->scan_result_lock_, 10L / portTICK_PERIOD_MS)) {
147  this->scan_result_index_ = 0;
148  xSemaphoreGive(this->scan_result_lock_);
149  }
150  }
151 
152  if (this->scan_set_param_failed_) {
153  ESP_LOGE(TAG, "Scan set param failed: %d", this->scan_set_param_failed_);
154  this->scan_set_param_failed_ = ESP_BT_STATUS_SUCCESS;
155  }
156 
157  if (this->scan_start_failed_) {
158  ESP_LOGE(TAG, "Scan start failed: %d", this->scan_start_failed_);
159  this->scan_start_failed_ = ESP_BT_STATUS_SUCCESS;
160  }
161 }
162 
164  if (xSemaphoreTake(this->scan_end_lock_, 0L)) {
165  xSemaphoreGive(this->scan_end_lock_);
166  this->start_scan_(true);
167  } else {
168  ESP_LOGW(TAG, "Scan requested when a scan is already in progress. Ignoring.");
169  }
170 }
171 
173  ESP_LOGD(TAG, "Stopping scan.");
174  this->scan_continuous_ = false;
175  esp_ble_gap_stop_scanning();
176  this->cancel_timeout("scan");
177 }
178 
180  // Initialize non-volatile storage for the bluetooth controller
181  esp_err_t err = nvs_flash_init();
182  if (err != ESP_OK) {
183  ESP_LOGE(TAG, "nvs_flash_init failed: %d", err);
184  return false;
185  }
186 
187 #ifdef USE_ARDUINO
188  if (!btStart()) {
189  ESP_LOGE(TAG, "btStart failed: %d", esp_bt_controller_get_status());
190  return false;
191  }
192 #else
193  if (esp_bt_controller_get_status() != ESP_BT_CONTROLLER_STATUS_ENABLED) {
194  // start bt controller
195  if (esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_IDLE) {
196  esp_bt_controller_config_t cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
197  err = esp_bt_controller_init(&cfg);
198  if (err != ESP_OK) {
199  ESP_LOGE(TAG, "esp_bt_controller_init failed: %s", esp_err_to_name(err));
200  return false;
201  }
202  while (esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_IDLE)
203  ;
204  }
205  if (esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_INITED) {
206  err = esp_bt_controller_enable(ESP_BT_MODE_BLE);
207  if (err != ESP_OK) {
208  ESP_LOGE(TAG, "esp_bt_controller_enable failed: %s", esp_err_to_name(err));
209  return false;
210  }
211  }
212  if (esp_bt_controller_get_status() != ESP_BT_CONTROLLER_STATUS_ENABLED) {
213  ESP_LOGE(TAG, "esp bt controller enable failed");
214  return false;
215  }
216  }
217 #endif
218 
219  esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT);
220 
221  err = esp_bluedroid_init();
222  if (err != ESP_OK) {
223  ESP_LOGE(TAG, "esp_bluedroid_init failed: %d", err);
224  return false;
225  }
226  err = esp_bluedroid_enable();
227  if (err != ESP_OK) {
228  ESP_LOGE(TAG, "esp_bluedroid_enable failed: %d", err);
229  return false;
230  }
231  err = esp_ble_gap_register_callback(ESP32BLETracker::gap_event_handler);
232  if (err != ESP_OK) {
233  ESP_LOGE(TAG, "esp_ble_gap_register_callback failed: %d", err);
234  return false;
235  }
236  err = esp_ble_gattc_register_callback(ESP32BLETracker::gattc_event_handler);
237  if (err != ESP_OK) {
238  ESP_LOGE(TAG, "esp_ble_gattc_register_callback failed: %d", err);
239  return false;
240  }
241 
242  // Empty name
243  esp_ble_gap_set_device_name("");
244 
245  esp_ble_io_cap_t iocap = ESP_IO_CAP_NONE;
246  err = esp_ble_gap_set_security_param(ESP_BLE_SM_IOCAP_MODE, &iocap, sizeof(uint8_t));
247  if (err != ESP_OK) {
248  ESP_LOGE(TAG, "esp_ble_gap_set_security_param failed: %d", err);
249  return false;
250  }
251 
252  // BLE takes some time to be fully set up, 200ms should be more than enough
253  delay(200); // NOLINT
254 
255  return true;
256 }
257 
259  if (!xSemaphoreTake(this->scan_end_lock_, 0L)) {
260  ESP_LOGW(TAG, "Cannot start scan!");
261  return;
262  }
263 
264  ESP_LOGD(TAG, "Starting scan...");
265  if (!first) {
266  for (auto *listener : this->listeners_)
267  listener->on_scan_end();
268  }
269  this->already_discovered_.clear();
270  this->scanner_idle_ = false;
271  this->scan_params_.scan_type = this->scan_active_ ? BLE_SCAN_TYPE_ACTIVE : BLE_SCAN_TYPE_PASSIVE;
272  this->scan_params_.own_addr_type = BLE_ADDR_TYPE_PUBLIC;
273  this->scan_params_.scan_filter_policy = BLE_SCAN_FILTER_ALLOW_ALL;
274  this->scan_params_.scan_interval = this->scan_interval_;
275  this->scan_params_.scan_window = this->scan_window_;
276 
277  esp_ble_gap_set_scan_params(&this->scan_params_);
278  esp_ble_gap_start_scanning(this->scan_duration_);
279 
280  this->set_timeout("scan", this->scan_duration_ * 2000, []() {
281  ESP_LOGW(TAG, "ESP-IDF BLE scan never terminated, rebooting to restore BLE stack...");
282  App.reboot();
283  });
284 }
285 
287  if (!xSemaphoreTake(this->scan_end_lock_, 0L)) {
288  ESP_LOGW(TAG, "Cannot clean up end of scan!");
289  return;
290  }
291 
292  ESP_LOGD(TAG, "End of scan.");
293  this->scanner_idle_ = true;
294  this->already_discovered_.clear();
295  xSemaphoreGive(this->scan_end_lock_);
296  this->cancel_timeout("scan");
297 
298  for (auto *listener : this->listeners_)
299  listener->on_scan_end();
300 }
301 
303  client->app_id = ++this->app_id_;
304  this->clients_.push_back(client);
305 }
306 
307 void ESP32BLETracker::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
308  BLEEvent *gap_event = new BLEEvent(event, param); // NOLINT(cppcoreguidelines-owning-memory)
309  global_esp32_ble_tracker->ble_events_.push(gap_event);
310 } // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks)
311 
312 void ESP32BLETracker::real_gap_event_handler_(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
313  switch (event) {
314  case ESP_GAP_BLE_SCAN_RESULT_EVT:
315  this->gap_scan_result_(param->scan_rst);
316  break;
317  case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT:
318  this->gap_scan_set_param_complete_(param->scan_param_cmpl);
319  break;
320  case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT:
321  this->gap_scan_start_complete_(param->scan_start_cmpl);
322  break;
323  case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT:
324  this->gap_scan_stop_complete_(param->scan_stop_cmpl);
325  break;
326  default:
327  break;
328  }
329  for (auto *client : this->clients_) {
330  client->gap_event_handler(event, param);
331  }
332 }
333 
334 void ESP32BLETracker::gap_scan_set_param_complete_(const esp_ble_gap_cb_param_t::ble_scan_param_cmpl_evt_param &param) {
335  this->scan_set_param_failed_ = param.status;
336 }
337 
338 void ESP32BLETracker::gap_scan_start_complete_(const esp_ble_gap_cb_param_t::ble_scan_start_cmpl_evt_param &param) {
339  this->scan_start_failed_ = param.status;
340 }
341 
342 void ESP32BLETracker::gap_scan_stop_complete_(const esp_ble_gap_cb_param_t::ble_scan_stop_cmpl_evt_param &param) {
343  xSemaphoreGive(this->scan_end_lock_);
344 }
345 
346 void ESP32BLETracker::gap_scan_result_(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param &param) {
347  if (param.search_evt == ESP_GAP_SEARCH_INQ_RES_EVT) {
348  if (xSemaphoreTake(this->scan_result_lock_, 0L)) {
349  if (this->scan_result_index_ < 16) {
350  this->scan_result_buffer_[this->scan_result_index_++] = param;
351  }
352  xSemaphoreGive(this->scan_result_lock_);
353  }
354  } else if (param.search_evt == ESP_GAP_SEARCH_INQ_CMPL_EVT) {
355  xSemaphoreGive(this->scan_end_lock_);
356  }
357 }
358 
359 void ESP32BLETracker::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
360  esp_ble_gattc_cb_param_t *param) {
361  BLEEvent *gattc_event = new BLEEvent(event, gattc_if, param); // NOLINT(cppcoreguidelines-owning-memory)
362  global_esp32_ble_tracker->ble_events_.push(gattc_event);
363 } // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks)
364 
365 void ESP32BLETracker::real_gattc_event_handler_(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
366  esp_ble_gattc_cb_param_t *param) {
367  for (auto *client : this->clients_) {
368  client->gattc_event_handler(event, gattc_if, param);
369  }
370 }
371 
372 ESPBTUUID::ESPBTUUID() : uuid_() {}
374  ESPBTUUID ret;
375  ret.uuid_.len = ESP_UUID_LEN_16;
376  ret.uuid_.uuid.uuid16 = uuid;
377  return ret;
378 }
380  ESPBTUUID ret;
381  ret.uuid_.len = ESP_UUID_LEN_32;
382  ret.uuid_.uuid.uuid32 = uuid;
383  return ret;
384 }
385 ESPBTUUID ESPBTUUID::from_raw(const uint8_t *data) {
386  ESPBTUUID ret;
387  ret.uuid_.len = ESP_UUID_LEN_128;
388  for (size_t i = 0; i < ESP_UUID_LEN_128; i++)
389  ret.uuid_.uuid.uuid128[i] = data[i];
390  return ret;
391 }
392 ESPBTUUID ESPBTUUID::from_raw(const std::string &data) {
393  ESPBTUUID ret;
394  if (data.length() == 4) {
395  ret.uuid_.len = ESP_UUID_LEN_16;
396  ret.uuid_.uuid.uuid16 = 0;
397  for (int i = 0; i < data.length();) {
398  uint8_t msb = data.c_str()[i];
399  uint8_t lsb = data.c_str()[i + 1];
400 
401  if (msb > '9')
402  msb -= 7;
403  if (lsb > '9')
404  lsb -= 7;
405  ret.uuid_.uuid.uuid16 += (((msb & 0x0F) << 4) | (lsb & 0x0F)) << (2 - i) * 4;
406  i += 2;
407  }
408  } else if (data.length() == 8) {
409  ret.uuid_.len = ESP_UUID_LEN_32;
410  ret.uuid_.uuid.uuid32 = 0;
411  for (int i = 0; i < data.length();) {
412  uint8_t msb = data.c_str()[i];
413  uint8_t lsb = data.c_str()[i + 1];
414 
415  if (msb > '9')
416  msb -= 7;
417  if (lsb > '9')
418  lsb -= 7;
419  ret.uuid_.uuid.uuid32 += (((msb & 0x0F) << 4) | (lsb & 0x0F)) << (6 - i) * 4;
420  i += 2;
421  }
422  } else if (data.length() == 16) { // how we can have 16 byte length string reprezenting 128 bit uuid??? needs to be
423  // investigated (lack of time)
424  ret.uuid_.len = ESP_UUID_LEN_128;
425  memcpy(ret.uuid_.uuid.uuid128, (uint8_t *) data.data(), 16);
426  } else if (data.length() == 36) {
427  // If the length of the string is 36 bytes then we will assume it is a long hex string in
428  // UUID format.
429  ret.uuid_.len = ESP_UUID_LEN_128;
430  int n = 0;
431  for (int i = 0; i < data.length();) {
432  if (data.c_str()[i] == '-')
433  i++;
434  uint8_t msb = data.c_str()[i];
435  uint8_t lsb = data.c_str()[i + 1];
436 
437  if (msb > '9')
438  msb -= 7;
439  if (lsb > '9')
440  lsb -= 7;
441  ret.uuid_.uuid.uuid128[15 - n++] = ((msb & 0x0F) << 4) | (lsb & 0x0F);
442  i += 2;
443  }
444  } else {
445  ESP_LOGE(TAG, "ERROR: UUID value not 2, 4, 16 or 36 bytes - %s", data.c_str());
446  }
447  return ret;
448 }
449 ESPBTUUID ESPBTUUID::from_uuid(esp_bt_uuid_t uuid) {
450  ESPBTUUID ret;
451  ret.uuid_.len = uuid.len;
452  ret.uuid_.uuid.uuid16 = uuid.uuid.uuid16;
453  ret.uuid_.uuid.uuid32 = uuid.uuid.uuid32;
454  for (size_t i = 0; i < ESP_UUID_LEN_128; i++)
455  ret.uuid_.uuid.uuid128[i] = uuid.uuid.uuid128[i];
456  return ret;
457 }
459  if (this->uuid_.len == ESP_UUID_LEN_128) {
460  return *this;
461  }
462  uint8_t data[] = {0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
463  uint32_t uuid32;
464  if (this->uuid_.len == ESP_UUID_LEN_32) {
465  uuid32 = this->uuid_.uuid.uuid32;
466  } else {
467  uuid32 = this->uuid_.uuid.uuid16;
468  }
469  for (uint8_t i = 0; i < this->uuid_.len; i++) {
470  data[12 + i] = ((uuid32 >> i * 8) & 0xFF);
471  }
472  return ESPBTUUID::from_raw(data);
473 }
474 bool ESPBTUUID::contains(uint8_t data1, uint8_t data2) const {
475  if (this->uuid_.len == ESP_UUID_LEN_16) {
476  return (this->uuid_.uuid.uuid16 >> 8) == data2 && (this->uuid_.uuid.uuid16 & 0xFF) == data1;
477  } else if (this->uuid_.len == ESP_UUID_LEN_32) {
478  for (uint8_t i = 0; i < 3; i++) {
479  bool a = ((this->uuid_.uuid.uuid32 >> i * 8) & 0xFF) == data1;
480  bool b = ((this->uuid_.uuid.uuid32 >> (i + 1) * 8) & 0xFF) == data2;
481  if (a && b)
482  return true;
483  }
484  } else {
485  for (uint8_t i = 0; i < 15; i++) {
486  if (this->uuid_.uuid.uuid128[i] == data1 && this->uuid_.uuid.uuid128[i + 1] == data2)
487  return true;
488  }
489  }
490  return false;
491 }
492 bool ESPBTUUID::operator==(const ESPBTUUID &uuid) const {
493  if (this->uuid_.len == uuid.uuid_.len) {
494  switch (this->uuid_.len) {
495  case ESP_UUID_LEN_16:
496  if (uuid.uuid_.uuid.uuid16 == this->uuid_.uuid.uuid16) {
497  return true;
498  }
499  break;
500  case ESP_UUID_LEN_32:
501  if (uuid.uuid_.uuid.uuid32 == this->uuid_.uuid.uuid32) {
502  return true;
503  }
504  break;
505  case ESP_UUID_LEN_128:
506  for (int i = 0; i < ESP_UUID_LEN_128; i++) {
507  if (uuid.uuid_.uuid.uuid128[i] != this->uuid_.uuid.uuid128[i]) {
508  return false;
509  }
510  }
511  return true;
512  break;
513  }
514  } else {
515  return this->as_128bit() == uuid.as_128bit();
516  }
517  return false;
518 }
519 esp_bt_uuid_t ESPBTUUID::get_uuid() const { return this->uuid_; }
520 std::string ESPBTUUID::to_string() const {
521  char sbuf[64];
522  switch (this->uuid_.len) {
523  case ESP_UUID_LEN_16:
524  sprintf(sbuf, "0x%02X%02X", this->uuid_.uuid.uuid16 >> 8, this->uuid_.uuid.uuid16 & 0xff);
525  break;
526  case ESP_UUID_LEN_32:
527  sprintf(sbuf, "0x%02X%02X%02X%02X", this->uuid_.uuid.uuid32 >> 24, (this->uuid_.uuid.uuid32 >> 16 & 0xff),
528  (this->uuid_.uuid.uuid32 >> 8 & 0xff), this->uuid_.uuid.uuid32 & 0xff);
529  break;
530  default:
531  case ESP_UUID_LEN_128:
532  char *bpos = sbuf;
533  for (int8_t i = 15; i >= 0; i--) {
534  sprintf(bpos, "%02X", this->uuid_.uuid.uuid128[i]);
535  bpos += 2;
536  if (i == 6 || i == 8 || i == 10 || i == 12)
537  sprintf(bpos++, "-");
538  }
539  sbuf[47] = '\0';
540  break;
541  }
542  return sbuf;
543 }
544 
545 ESPBLEiBeacon::ESPBLEiBeacon(const uint8_t *data) { memcpy(&this->beacon_data_, data, sizeof(beacon_data_)); }
547  if (!data.uuid.contains(0x4C, 0x00))
548  return {};
549 
550  if (data.data.size() != 23)
551  return {};
552  return ESPBLEiBeacon(data.data.data());
553 }
554 
555 void ESPBTDevice::parse_scan_rst(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param &param) {
556  this->scan_result_ = param;
557  for (uint8_t i = 0; i < ESP_BD_ADDR_LEN; i++)
558  this->address_[i] = param.bda[i];
559  this->address_type_ = param.ble_addr_type;
560  this->rssi_ = param.rssi;
561  this->parse_adv_(param);
562 
563 #ifdef ESPHOME_LOG_HAS_VERY_VERBOSE
564  ESP_LOGVV(TAG, "Parse Result:");
565  const char *address_type = "";
566  switch (this->address_type_) {
567  case BLE_ADDR_TYPE_PUBLIC:
568  address_type = "PUBLIC";
569  break;
570  case BLE_ADDR_TYPE_RANDOM:
571  address_type = "RANDOM";
572  break;
573  case BLE_ADDR_TYPE_RPA_PUBLIC:
574  address_type = "RPA_PUBLIC";
575  break;
576  case BLE_ADDR_TYPE_RPA_RANDOM:
577  address_type = "RPA_RANDOM";
578  break;
579  }
580  ESP_LOGVV(TAG, " Address: %02X:%02X:%02X:%02X:%02X:%02X (%s)", this->address_[0], this->address_[1],
581  this->address_[2], this->address_[3], this->address_[4], this->address_[5], address_type);
582 
583  ESP_LOGVV(TAG, " RSSI: %d", this->rssi_);
584  ESP_LOGVV(TAG, " Name: '%s'", this->name_.c_str());
585  for (auto &it : this->tx_powers_) {
586  ESP_LOGVV(TAG, " TX Power: %d", it);
587  }
588  if (this->appearance_.has_value()) {
589  ESP_LOGVV(TAG, " Appearance: %u", *this->appearance_);
590  }
591  if (this->ad_flag_.has_value()) {
592  ESP_LOGVV(TAG, " Ad Flag: %u", *this->ad_flag_);
593  }
594  for (auto &uuid : this->service_uuids_) {
595  ESP_LOGVV(TAG, " Service UUID: %s", uuid.to_string().c_str());
596  }
597  for (auto &data : this->manufacturer_datas_) {
598  ESP_LOGVV(TAG, " Manufacturer data: %s", format_hex_pretty(data.data).c_str());
599  if (this->get_ibeacon().has_value()) {
600  auto ibeacon = this->get_ibeacon().value();
601  ESP_LOGVV(TAG, " iBeacon data:");
602  ESP_LOGVV(TAG, " UUID: %s", ibeacon.get_uuid().to_string().c_str());
603  ESP_LOGVV(TAG, " Major: %u", ibeacon.get_major());
604  ESP_LOGVV(TAG, " Minor: %u", ibeacon.get_minor());
605  ESP_LOGVV(TAG, " TXPower: %d", ibeacon.get_signal_power());
606  }
607  }
608  for (auto &data : this->service_datas_) {
609  ESP_LOGVV(TAG, " Service data:");
610  ESP_LOGVV(TAG, " UUID: %s", data.uuid.to_string().c_str());
611  ESP_LOGVV(TAG, " Data: %s", format_hex_pretty(data.data).c_str());
612  }
613 
614  ESP_LOGVV(TAG, "Adv data: %s", format_hex_pretty(param.ble_adv, param.adv_data_len + param.scan_rsp_len).c_str());
615 #endif
616 }
617 void ESPBTDevice::parse_adv_(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param &param) {
618  size_t offset = 0;
619  const uint8_t *payload = param.ble_adv;
620  uint8_t len = param.adv_data_len + param.scan_rsp_len;
621 
622  while (offset + 2 < len) {
623  const uint8_t field_length = payload[offset++]; // First byte is length of adv record
624  if (field_length == 0)
625  break;
626 
627  // first byte of adv record is adv record type
628  const uint8_t record_type = payload[offset++];
629  const uint8_t *record = &payload[offset];
630  const uint8_t record_length = field_length - 1;
631  offset += record_length;
632 
633  // See also Generic Access Profile Assigned Numbers:
634  // https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile/ See also ADVERTISING AND SCAN
635  // RESPONSE DATA FORMAT: https://www.bluetooth.com/specifications/bluetooth-core-specification/ (vol 3, part C, 11)
636  // See also Core Specification Supplement: https://www.bluetooth.com/specifications/bluetooth-core-specification/
637  // (called CSS here)
638 
639  switch (record_type) {
640  case ESP_BLE_AD_TYPE_NAME_CMPL: {
641  // CSS 1.2 LOCAL NAME
642  // "The Local Name data type shall be the same as, or a shortened version of, the local name assigned to the
643  // device." CSS 1: Optional in this context; shall not appear more than once in a block.
644  this->name_ = std::string(reinterpret_cast<const char *>(record), record_length);
645  break;
646  }
647  case ESP_BLE_AD_TYPE_TX_PWR: {
648  // CSS 1.5 TX POWER LEVEL
649  // "The TX Power Level data type indicates the transmitted power level of the packet containing the data type."
650  // CSS 1: Optional in this context (may appear more than once in a block).
651  this->tx_powers_.push_back(*payload);
652  break;
653  }
654  case ESP_BLE_AD_TYPE_APPEARANCE: {
655  // CSS 1.12 APPEARANCE
656  // "The Appearance data type defines the external appearance of the device."
657  // See also https://www.bluetooth.com/specifications/gatt/characteristics/
658  // CSS 1: Optional in this context; shall not appear more than once in a block and shall not appear in both
659  // the AD and SRD of the same extended advertising interval.
660  this->appearance_ = *reinterpret_cast<const uint16_t *>(record);
661  break;
662  }
663  case ESP_BLE_AD_TYPE_FLAG: {
664  // CSS 1.3 FLAGS
665  // "The Flags data type contains one bit Boolean flags. The Flags data type shall be included when any of the
666  // Flag bits are non-zero and the advertising packet is connectable, otherwise the Flags data type may be
667  // omitted."
668  // CSS 1: Optional in this context; shall not appear more than once in a block.
669  this->ad_flag_ = *record;
670  break;
671  }
672  // CSS 1.1 SERVICE UUID
673  // The Service UUID data type is used to include a list of Service or Service Class UUIDs.
674  // There are six data types defined for the three sizes of Service UUIDs that may be returned:
675  // CSS 1: Optional in this context (may appear more than once in a block).
676  case ESP_BLE_AD_TYPE_16SRV_CMPL:
677  case ESP_BLE_AD_TYPE_16SRV_PART: {
678  // • 16-bit Bluetooth Service UUIDs
679  for (uint8_t i = 0; i < record_length / 2; i++) {
680  this->service_uuids_.push_back(ESPBTUUID::from_uint16(*reinterpret_cast<const uint16_t *>(record + 2 * i)));
681  }
682  break;
683  }
684  case ESP_BLE_AD_TYPE_32SRV_CMPL:
685  case ESP_BLE_AD_TYPE_32SRV_PART: {
686  // • 32-bit Bluetooth Service UUIDs
687  for (uint8_t i = 0; i < record_length / 4; i++) {
688  this->service_uuids_.push_back(ESPBTUUID::from_uint32(*reinterpret_cast<const uint32_t *>(record + 4 * i)));
689  }
690  break;
691  }
692  case ESP_BLE_AD_TYPE_128SRV_CMPL:
693  case ESP_BLE_AD_TYPE_128SRV_PART: {
694  // • Global 128-bit Service UUIDs
695  this->service_uuids_.push_back(ESPBTUUID::from_raw(record));
696  break;
697  }
698  case ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE: {
699  // CSS 1.4 MANUFACTURER SPECIFIC DATA
700  // "The Manufacturer Specific data type is used for manufacturer specific data. The first two data octets shall
701  // contain a company identifier from Assigned Numbers. The interpretation of any other octets within the data
702  // shall be defined by the manufacturer specified by the company identifier."
703  // CSS 1: Optional in this context (may appear more than once in a block).
704  if (record_length < 2) {
705  ESP_LOGV(TAG, "Record length too small for ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE");
706  break;
707  }
708  ServiceData data{};
709  data.uuid = ESPBTUUID::from_uint16(*reinterpret_cast<const uint16_t *>(record));
710  data.data.assign(record + 2UL, record + record_length);
711  this->manufacturer_datas_.push_back(data);
712  break;
713  }
714 
715  // CSS 1.11 SERVICE DATA
716  // "The Service Data data type consists of a service UUID with the data associated with that service."
717  // CSS 1: Optional in this context (may appear more than once in a block).
718  case ESP_BLE_AD_TYPE_SERVICE_DATA: {
719  // «Service Data - 16 bit UUID»
720  // Size: 2 or more octets
721  // The first 2 octets contain the 16 bit Service UUID fol- lowed by additional service data
722  if (record_length < 2) {
723  ESP_LOGV(TAG, "Record length too small for ESP_BLE_AD_TYPE_SERVICE_DATA");
724  break;
725  }
726  ServiceData data{};
727  data.uuid = ESPBTUUID::from_uint16(*reinterpret_cast<const uint16_t *>(record));
728  data.data.assign(record + 2UL, record + record_length);
729  this->service_datas_.push_back(data);
730  break;
731  }
732  case ESP_BLE_AD_TYPE_32SERVICE_DATA: {
733  // «Service Data - 32 bit UUID»
734  // Size: 4 or more octets
735  // The first 4 octets contain the 32 bit Service UUID fol- lowed by additional service data
736  if (record_length < 4) {
737  ESP_LOGV(TAG, "Record length too small for ESP_BLE_AD_TYPE_32SERVICE_DATA");
738  break;
739  }
740  ServiceData data{};
741  data.uuid = ESPBTUUID::from_uint32(*reinterpret_cast<const uint32_t *>(record));
742  data.data.assign(record + 4UL, record + record_length);
743  this->service_datas_.push_back(data);
744  break;
745  }
746  case ESP_BLE_AD_TYPE_128SERVICE_DATA: {
747  // «Service Data - 128 bit UUID»
748  // Size: 16 or more octets
749  // The first 16 octets contain the 128 bit Service UUID followed by additional service data
750  if (record_length < 16) {
751  ESP_LOGV(TAG, "Record length too small for ESP_BLE_AD_TYPE_128SERVICE_DATA");
752  break;
753  }
754  ServiceData data{};
755  data.uuid = ESPBTUUID::from_raw(record);
756  data.data.assign(record + 16UL, record + record_length);
757  this->service_datas_.push_back(data);
758  break;
759  }
760  default: {
761  ESP_LOGV(TAG, "Unhandled type: advType: 0x%02x", record_type);
762  break;
763  }
764  }
765  }
766 }
767 std::string ESPBTDevice::address_str() const {
768  char mac[24];
769  snprintf(mac, sizeof(mac), "%02X:%02X:%02X:%02X:%02X:%02X", this->address_[0], this->address_[1], this->address_[2],
770  this->address_[3], this->address_[4], this->address_[5]);
771  return mac;
772 }
773 uint64_t ESPBTDevice::address_uint64() const { return ble_addr_to_uint64(this->address_); }
774 
776  ESP_LOGCONFIG(TAG, "BLE Tracker:");
777  ESP_LOGCONFIG(TAG, " Scan Duration: %u s", this->scan_duration_);
778  ESP_LOGCONFIG(TAG, " Scan Interval: %.1f ms", this->scan_interval_ * 0.625f);
779  ESP_LOGCONFIG(TAG, " Scan Window: %.1f ms", this->scan_window_ * 0.625f);
780  ESP_LOGCONFIG(TAG, " Scan Type: %s", this->scan_active_ ? "ACTIVE" : "PASSIVE");
781  ESP_LOGCONFIG(TAG, " Continuous Scanning: %s", this->scan_continuous_ ? "True" : "False");
782 }
783 
785  const uint64_t address = device.address_uint64();
786  for (auto &disc : this->already_discovered_) {
787  if (disc == address)
788  return;
789  }
790  this->already_discovered_.push_back(address);
791 
792  ESP_LOGD(TAG, "Found device %s RSSI=%d", device.address_str().c_str(), device.get_rssi());
793 
794  const char *address_type_s;
795  switch (device.get_address_type()) {
796  case BLE_ADDR_TYPE_PUBLIC:
797  address_type_s = "PUBLIC";
798  break;
799  case BLE_ADDR_TYPE_RANDOM:
800  address_type_s = "RANDOM";
801  break;
802  case BLE_ADDR_TYPE_RPA_PUBLIC:
803  address_type_s = "RPA_PUBLIC";
804  break;
805  case BLE_ADDR_TYPE_RPA_RANDOM:
806  address_type_s = "RPA_RANDOM";
807  break;
808  default:
809  address_type_s = "UNKNOWN";
810  break;
811  }
812 
813  ESP_LOGD(TAG, " Address Type: %s", address_type_s);
814  if (!device.get_name().empty())
815  ESP_LOGD(TAG, " Name: '%s'", device.get_name().c_str());
816  for (auto &tx_power : device.get_tx_powers()) {
817  ESP_LOGD(TAG, " TX Power: %d", tx_power);
818  }
819 }
820 
821 } // namespace esp32_ble_tracker
822 } // namespace esphome
823 
824 #endif
void real_gattc_event_handler_(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param)
void end_of_scan_()
Called when a scan ends.
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:214
bool cancel_timeout(const std::string &name)
Cancel a timeout function.
Definition: component.cpp:71
void setup() override
Setup the FreeRTOS task and the Bluetooth stack.
void start_scan_(bool first)
Start a single scan by setting up the parameters and doing some esp-idf calls.
esp_ble_gap_cb_param_t::ble_scan_result_evt_param scan_result_buffer_[16]
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:67
void parse_scan_rst(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param &param)
void add_on_state_callback(std::function< void(OTAState, float, uint8_t)> &&callback)
const std::vector< int8_t > & get_tx_powers() const
esp_ble_scan_params_t scan_params_
A structure holding the ESP BLE scan parameters.
static ESPBTUUID from_raw(const uint8_t *data)
void real_gap_event_handler_(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
ESP32BLETracker * global_esp32_ble_tracker
static void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
Callback that will handle all GAP events and redistribute them to other callbacks.
struct esphome::esp32_ble_tracker::BLEEvent::@61::gattc_event gattc
Application App
Global storage of Application pointer - only one Application can exist.
esp_ble_addr_type_t get_address_type() const
union esphome::esp32_ble_tracker::BLEEvent::@61 event_
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
bool contains(uint8_t data1, uint8_t data2) const
struct esphome::esp32_ble_tracker::BLEEvent::@61::gap_event gap
static void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param)
Callback that will handle all GATTC events and redistribute them to other callbacks.
uint32_t scan_duration_
The interval in seconds to perform scans.
std::string size_t len
Definition: helpers.h:281
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:111
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.
uint64_t ble_addr_to_uint64(const esp_bd_addr_t address)
static ESPBTUUID from_uint16(uint16_t uuid)
static ESPBTUUID from_uint32(uint32_t uuid)
Definition: a4988.cpp:4
void print_bt_device_info(const ESPBTDevice &device)
const std::string & get_name() const
static bool ble_setup()
The FreeRTOS task managing the bluetooth interface.
bool operator==(const ESPBTUUID &uuid) 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)
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
void IRAM_ATTR HOT delay(uint32_t ms)
Definition: core.cpp:27
static ESPBTUUID from_uuid(esp_bt_uuid_t uuid)