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> 25 #include <esp32-hal-bt.h> 28 #define MBEDTLS_AES_ALT 35 namespace esp32_ble_tracker {
37 static const char *
const TAG =
"esp32_ble_tracker";
44 if (this->
parent_->is_failed()) {
46 ESP_LOGE(TAG,
"BLE Tracker was marked failed by ESP32BLE");
54 ESP_LOGE(TAG,
"Could not allocate buffer for BLE Tracker!");
58 global_esp32_ble_tracker =
this;
67 for (
auto *client : this->
clients_) {
76 if (!this->
parent_->is_active()) {
89 int disconnecting = 0;
90 for (
auto *client : this->
clients_) {
91 switch (client->state()) {
115 ESP_LOGD(TAG,
"connecting: %d, discovered: %d, searching: %d, disconnecting: %d",
connecting_,
discovered_,
118 bool promote_to_connecting = discovered && !searching && !connecting;
125 ESP_LOGW(TAG,
"Too many BLE events to process. Some devices may not show up.");
132 for (
auto *client : this->clients_) {
138 for (
size_t i = 0; i < index; i++) {
144 if (listener->parse_device(device))
148 for (
auto *client : this->clients_) {
149 if (client->parse_device(device)) {
152 promote_to_connecting =
true;
179 if (!connecting && !disconnecting && xSemaphoreTake(this->
scan_end_lock_, 0L)) {
195 ESP_LOGE(TAG,
"ESP-IDF BLE scan could not restart after %d attempts, rebooting to restore BLE stack...",
196 std::numeric_limits<uint8_t>::max());
202 ESP_LOGD(TAG,
"Stopping scan after failure...");
220 if (promote_to_connecting) {
221 for (
auto *client : this->clients_) {
231 ESP_LOGD(TAG,
"Pausing scan to make connection...");
244 ESP_LOGW(TAG,
"Scan requested when a scan is already in progress. Ignoring.");
249 ESP_LOGD(TAG,
"Stopping scan.");
264 esp_err_t err = esp_ble_gap_stop_scanning();
266 ESP_LOGE(TAG,
"esp_ble_gap_stop_scanning failed: %d", err);
272 if (!this->
parent_->is_active()) {
273 ESP_LOGW(TAG,
"Cannot start scan while ESP32BLE is disabled.");
278 ESP_LOGE(TAG,
"start_scan called without holding scan_end_lock_");
282 ESP_LOGD(TAG,
"Starting scan...");
285 listener->on_scan_end();
289 this->
scan_params_.own_addr_type = BLE_ADDR_TYPE_PUBLIC;
290 this->
scan_params_.scan_filter_policy = BLE_SCAN_FILTER_ALLOW_ALL;
296 ESP_LOGE(TAG,
"ESP-IDF BLE scan never terminated, rebooting to restore BLE stack...");
300 esp_err_t err = esp_ble_gap_set_scan_params(&this->
scan_params_);
302 ESP_LOGE(TAG,
"esp_ble_gap_set_scan_params failed: %d", err);
307 ESP_LOGE(TAG,
"esp_ble_gap_start_scanning failed: %d", err);
316 ESP_LOGE(TAG,
"end_of_scan_ called without holding the scan_end_lock_");
320 ESP_LOGD(TAG,
"End of scan.");
327 listener->on_scan_end();
352 for (
auto *client : this->
clients_) {
363 case ESP_GAP_BLE_SCAN_RESULT_EVT:
366 case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT:
369 case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT:
372 case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT:
378 for (
auto *client : this->
clients_) {
379 client->gap_event_handler(event, param);
384 ESP_LOGV(TAG,
"gap_scan_set_param_complete - status %d", param.status);
385 if (param.status == ESP_BT_STATUS_DONE) {
393 ESP_LOGV(TAG,
"gap_scan_start_complete - status %d", param.status);
395 if (param.status == ESP_BT_STATUS_SUCCESS) {
406 ESP_LOGV(TAG,
"gap_scan_stop_complete - status %d", param.status);
411 ESP_LOGV(TAG,
"gap_scan_result - event %d", param.search_evt);
412 if (param.search_evt == ESP_GAP_SEARCH_INQ_RES_EVT) {
419 }
else if (param.search_evt == ESP_GAP_SEARCH_INQ_CMPL_EVT) {
425 esp_ble_gattc_cb_param_t *param) {
426 for (
auto *client : this->
clients_) {
427 client->gattc_event_handler(event, gattc_if, param);
436 if (data.
data.size() != 23)
442 this->scan_result_ = param;
443 for (uint8_t i = 0; i < ESP_BD_ADDR_LEN; i++)
444 this->address_[i] = param.bda[i];
445 this->address_type_ = param.ble_addr_type;
446 this->rssi_ = param.rssi;
447 this->parse_adv_(param);
449 #ifdef ESPHOME_LOG_HAS_VERY_VERBOSE 450 ESP_LOGVV(TAG,
"Parse Result:");
451 const char *address_type;
452 switch (this->address_type_) {
453 case BLE_ADDR_TYPE_PUBLIC:
454 address_type =
"PUBLIC";
456 case BLE_ADDR_TYPE_RANDOM:
457 address_type =
"RANDOM";
459 case BLE_ADDR_TYPE_RPA_PUBLIC:
460 address_type =
"RPA_PUBLIC";
462 case BLE_ADDR_TYPE_RPA_RANDOM:
463 address_type =
"RPA_RANDOM";
466 address_type =
"UNKNOWN";
469 ESP_LOGVV(TAG,
" Address: %02X:%02X:%02X:%02X:%02X:%02X (%s)", this->address_[0], this->address_[1],
470 this->address_[2], this->address_[3], this->address_[4], this->address_[5], address_type);
472 ESP_LOGVV(TAG,
" RSSI: %d", this->rssi_);
473 ESP_LOGVV(TAG,
" Name: '%s'", this->name_.c_str());
474 for (
auto &it : this->tx_powers_) {
475 ESP_LOGVV(TAG,
" TX Power: %d", it);
477 if (this->appearance_.has_value()) {
478 ESP_LOGVV(TAG,
" Appearance: %u", *this->appearance_);
480 if (this->ad_flag_.has_value()) {
481 ESP_LOGVV(TAG,
" Ad Flag: %u", *this->ad_flag_);
483 for (
auto &uuid : this->service_uuids_) {
484 ESP_LOGVV(TAG,
" Service UUID: %s", uuid.to_string().c_str());
486 for (
auto &data : this->manufacturer_datas_) {
488 if (ibeacon.has_value()) {
489 ESP_LOGVV(TAG,
" Manufacturer iBeacon:");
490 ESP_LOGVV(TAG,
" UUID: %s", ibeacon.value().get_uuid().to_string().c_str());
491 ESP_LOGVV(TAG,
" Major: %u", ibeacon.value().get_major());
492 ESP_LOGVV(TAG,
" Minor: %u", ibeacon.value().get_minor());
493 ESP_LOGVV(TAG,
" TXPower: %d", ibeacon.value().get_signal_power());
495 ESP_LOGVV(TAG,
" Manufacturer ID: %s, data: %s", data.uuid.to_string().c_str(),
499 for (
auto &data : this->service_datas_) {
500 ESP_LOGVV(TAG,
" Service data:");
501 ESP_LOGVV(TAG,
" UUID: %s", data.uuid.to_string().c_str());
505 ESP_LOGVV(TAG,
" Adv data: %s",
format_hex_pretty(param.ble_adv, param.adv_data_len + param.scan_rsp_len).c_str());
510 const uint8_t *payload = param.ble_adv;
511 uint8_t
len = param.adv_data_len + param.scan_rsp_len;
513 while (offset + 2 < len) {
514 const uint8_t field_length = payload[offset++];
515 if (field_length == 0) {
520 const uint8_t record_type = payload[offset++];
521 const uint8_t *record = &payload[offset];
522 const uint8_t record_length = field_length - 1;
523 offset += record_length;
531 switch (record_type) {
532 case ESP_BLE_AD_TYPE_NAME_SHORT:
533 case ESP_BLE_AD_TYPE_NAME_CMPL: {
540 if (record_length > this->name_.length()) {
541 this->name_ = std::string(reinterpret_cast<const char *>(record), record_length);
545 case ESP_BLE_AD_TYPE_TX_PWR: {
549 this->tx_powers_.push_back(*payload);
552 case ESP_BLE_AD_TYPE_APPEARANCE: {
558 this->appearance_ = *
reinterpret_cast<const uint16_t *
>(record);
561 case ESP_BLE_AD_TYPE_FLAG: {
567 this->ad_flag_ = *record;
574 case ESP_BLE_AD_TYPE_16SRV_CMPL:
575 case ESP_BLE_AD_TYPE_16SRV_PART: {
577 for (uint8_t i = 0; i < record_length / 2; i++) {
578 this->service_uuids_.push_back(
ESPBTUUID::from_uint16(*reinterpret_cast<const uint16_t *>(record + 2 * i)));
582 case ESP_BLE_AD_TYPE_32SRV_CMPL:
583 case ESP_BLE_AD_TYPE_32SRV_PART: {
585 for (uint8_t i = 0; i < record_length / 4; i++) {
586 this->service_uuids_.push_back(
ESPBTUUID::from_uint32(*reinterpret_cast<const uint32_t *>(record + 4 * i)));
590 case ESP_BLE_AD_TYPE_128SRV_CMPL:
591 case ESP_BLE_AD_TYPE_128SRV_PART: {
596 case ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE: {
602 if (record_length < 2) {
603 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE");
608 data.data.assign(record + 2UL, record + record_length);
609 this->manufacturer_datas_.push_back(data);
616 case ESP_BLE_AD_TYPE_SERVICE_DATA: {
620 if (record_length < 2) {
621 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_TYPE_SERVICE_DATA");
626 data.data.assign(record + 2UL, record + record_length);
627 this->service_datas_.push_back(data);
630 case ESP_BLE_AD_TYPE_32SERVICE_DATA: {
634 if (record_length < 4) {
635 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_TYPE_32SERVICE_DATA");
640 data.data.assign(record + 4UL, record + record_length);
641 this->service_datas_.push_back(data);
644 case ESP_BLE_AD_TYPE_128SERVICE_DATA: {
648 if (record_length < 16) {
649 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_TYPE_128SERVICE_DATA");
654 data.data.assign(record + 16UL, record + record_length);
655 this->service_datas_.push_back(data);
658 case ESP_BLE_AD_TYPE_INT_RANGE:
662 ESP_LOGV(TAG,
"Unhandled type: advType: 0x%02x", record_type);
670 snprintf(mac,
sizeof(mac),
"%02X:%02X:%02X:%02X:%02X:%02X", this->address_[0], this->address_[1], this->address_[2],
671 this->address_[3], this->address_[4], this->address_[5]);
677 ESP_LOGCONFIG(TAG,
"BLE Tracker:");
678 ESP_LOGCONFIG(TAG,
" Scan Duration: %" PRIu32
" s", this->
scan_duration_);
679 ESP_LOGCONFIG(TAG,
" Scan Interval: %.1f ms", this->
scan_interval_ * 0.625f);
680 ESP_LOGCONFIG(TAG,
" Scan Window: %.1f ms", this->
scan_window_ * 0.625f);
681 ESP_LOGCONFIG(TAG,
" Scan Type: %s", this->
scan_active_ ?
"ACTIVE" :
"PASSIVE");
682 ESP_LOGCONFIG(TAG,
" Continuous Scanning: %s", YESNO(this->
scan_continuous_));
683 ESP_LOGCONFIG(TAG,
" Scanner Idle: %s", YESNO(this->
scanner_idle_));
684 ESP_LOGCONFIG(TAG,
" Scan End: %s", YESNO(xSemaphoreGetMutexHolder(this->
scan_end_lock_) ==
nullptr));
685 ESP_LOGCONFIG(TAG,
" Connecting: %d, discovered: %d, searching: %d, disconnecting: %d",
connecting_,
discovered_,
698 this->already_discovered_.push_back(address);
702 const char *address_type_s;
704 case BLE_ADDR_TYPE_PUBLIC:
705 address_type_s =
"PUBLIC";
707 case BLE_ADDR_TYPE_RANDOM:
708 address_type_s =
"RANDOM";
710 case BLE_ADDR_TYPE_RPA_PUBLIC:
711 address_type_s =
"RPA_PUBLIC";
713 case BLE_ADDR_TYPE_RPA_RANDOM:
714 address_type_s =
"RPA_RANDOM";
717 address_type_s =
"UNKNOWN";
721 ESP_LOGD(TAG,
" Address Type: %s", address_type_s);
723 ESP_LOGD(TAG,
" Name: '%s'", device.
get_name().c_str());
726 ESP_LOGD(TAG,
" TX Power: %d", tx_power);
732 uint8_t ecb_plaintext[16];
733 uint8_t ecb_ciphertext[16];
737 memcpy(&ecb_key, irk, 16);
738 memset(&ecb_plaintext, 0, 16);
740 ecb_plaintext[13] = (addr64 >> 40) & 0xff;
741 ecb_plaintext[14] = (addr64 >> 32) & 0xff;
742 ecb_plaintext[15] = (addr64 >> 24) & 0xff;
744 mbedtls_aes_context ctx = {0, 0, {0}};
745 mbedtls_aes_init(&ctx);
747 if (mbedtls_aes_setkey_enc(&ctx, ecb_key, 128) != 0) {
748 mbedtls_aes_free(&ctx);
752 if (mbedtls_aes_crypt_ecb(&ctx, ESP_AES_ENCRYPT, ecb_plaintext, ecb_ciphertext) != 0) {
753 mbedtls_aes_free(&ctx);
757 mbedtls_aes_free(&ctx);
759 return ecb_ciphertext[15] == (addr64 & 0xff) && ecb_ciphertext[14] == ((addr64 >> 8) & 0xff) &&
760 ecb_ciphertext[13] == ((addr64 >> 16) & 0xff);
static const u_int8_t SCAN_RESULT_BUFFER_SIZE
void end_of_scan_()
Called when a scan ends.
uint64_t ble_addr_to_uint64(const esp_bd_addr_t address)
esp_bt_status_t scan_start_failed_
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.
bool cancel_timeout(const std::string &name)
Cancel a timeout function.
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 ble_before_disabled_event_handler() override
void set_timeout(const std::string &name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
void parse_scan_rst(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param ¶m)
void recalculate_advertisement_parser_types()
const std::vector< int8_t > & get_tx_powers() const
std::string address_str() const
esp_bt_status_t scan_set_param_failed_
const float AFTER_BLUETOOTH
esp_ble_scan_params_t scan_params_
A structure holding the ESP BLE scan parameters.
SemaphoreHandle_t scan_end_lock_
void register_client(ESPBTClient *client)
ESP32BLETracker * global_esp32_ble_tracker
static ESPBTUUID from_uint32(uint32_t uuid)
void set_parent(ESP32BLETracker *parent)
void dump_config() override
esp_ble_gap_cb_param_t::ble_scan_result_evt_param * scan_result_buffer_
static ESPBTUUID from_uint16(uint16_t uuid)
Application App
Global storage of Application pointer - only one Application can exist.
bool parse_advertisements_
void add_on_state_callback(std::function< void(OTAState, float, uint8_t, OTAComponent *)> &&callback)
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 ¶m)
Called when a ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT event is received.
uint64_t address_uint64() const
uint8_t scan_start_fail_count_
SemaphoreHandle_t scan_result_lock_
uint32_t scan_duration_
The interval in seconds to perform scans.
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.
bool contains(uint8_t data1, uint8_t data2) const
void gap_scan_result_(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param ¶m)
Called when a ESP_GAP_BLE_SCAN_RESULT_EVT event is received.
Implementation of SPI Controller mode.
static ESPBTUUID from_raw(const uint8_t *data)
void print_bt_device_info(const ESPBTDevice &device)
const std::string & get_name() const
An STL allocator that uses SPI or internal RAM.
OTAGlobalCallback * get_global_ota_callback()
float get_setup_priority() const override
size_t scan_result_index_
void gap_scan_stop_complete_(const esp_ble_gap_cb_param_t::ble_scan_stop_cmpl_evt_param ¶m)
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 ¶m)
void gap_scan_start_complete_(const esp_ble_gap_cb_param_t::ble_scan_start_cmpl_evt_param ¶m)
Called when a ESP_GAP_BLE_SCAN_START_COMPLETE_EVT event is received.