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>
24#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
25#include <esp_coexist.h>
29#include <esp32-hal-bt.h>
32#define MBEDTLS_AES_ALT
40static const char *
const TAG =
"esp32_ble_tracker";
49 return "DISCONNECTING";
57 return "READY_TO_CONNECT";
72 if (this->
parent_->is_failed()) {
74 ESP_LOGE(TAG,
"BLE Tracker was marked failed by ESP32BLE");
85 for (
auto *client : this->
clients_) {
94 if (!this->
parent_->is_active()) {
119 ESP_LOGW(TAG,
"Scan timeout exceeded");
126 ESP_LOGE(TAG,
"Scan never terminated, rebooting");
139 ESP_LOGD(TAG,
"connecting: %d, discovered: %d, searching: %d, disconnecting: %d",
141 this->client_state_counts_.searching, this->client_state_counts_.disconnecting);
164 !promote_to_connecting) {
165#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
178 if (promote_to_connecting &&
187 ESP_LOGD(TAG,
"Stopping scan.");
202 esp_err_t err = esp_ble_gap_stop_scanning();
204 ESP_LOGE(TAG,
"esp_ble_gap_stop_scanning failed: %d", err);
210 if (!this->
parent_->is_active()) {
211 ESP_LOGW(TAG,
"Cannot start scan while ESP32BLE is disabled.");
219 ESP_LOGD(TAG,
"Starting scan, set scanner state to STARTING.");
222 listener->on_scan_end();
224#ifdef USE_ESP32_BLE_DEVICE
228 this->
scan_params_.own_addr_type = BLE_ADDR_TYPE_PUBLIC;
229 this->
scan_params_.scan_filter_policy = BLE_SCAN_FILTER_ALLOW_ALL;
238 esp_err_t err = esp_ble_gap_set_scan_params(&this->
scan_params_);
240 ESP_LOGE(TAG,
"esp_ble_gap_set_scan_params failed: %d", err);
245 ESP_LOGE(TAG,
"esp_ble_gap_start_scanning failed: %d", err);
272 for (
auto *client : this->
clients_) {
285 case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT:
288 case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT:
291 case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT:
298 for (
auto *client : this->
clients_) {
299 client->gap_event_handler(event, param);
306 ESP_LOGV(TAG,
"gap_scan_result - event %d", scan_result.search_evt);
308 if (scan_result.search_evt == ESP_GAP_SEARCH_INQ_RES_EVT) {
315 ESP_LOGD(TAG,
"Found discovered client, stopping scan for connection");
318 }
else if (scan_result.search_evt == ESP_GAP_SEARCH_INQ_CMPL_EVT) {
330 ESP_LOGV(TAG,
"gap_scan_set_param_complete - status %d", param.status);
331 if (param.status == ESP_BT_STATUS_DONE) {
340 ESP_LOGV(TAG,
"gap_scan_start_complete - status %d", param.status);
345 if (param.status == ESP_BT_STATUS_SUCCESS) {
359 ESP_LOGV(TAG,
"gap_scan_stop_complete - status %d", param.status);
369 esp_ble_gattc_cb_param_t *param) {
370 for (
auto *client : this->
clients_) {
371 client->gattc_event_handler(event, gattc_if, param);
380#ifdef USE_ESP32_BLE_DEVICE
386 if (data.
data.size() != 23)
393 for (uint8_t i = 0; i < ESP_BD_ADDR_LEN; i++)
394 this->
address_[i] = scan_result.bda[i];
395 this->
address_type_ =
static_cast<esp_ble_addr_type_t
>(scan_result.ble_addr_type);
396 this->
rssi_ = scan_result.rssi;
399 uint8_t total_len = scan_result.adv_data_len + scan_result.scan_rsp_len;
400 this->
parse_adv_(scan_result.ble_adv, total_len);
402#ifdef ESPHOME_LOG_HAS_VERY_VERBOSE
403 ESP_LOGVV(TAG,
"Parse Result:");
404 const char *address_type;
406 case BLE_ADDR_TYPE_PUBLIC:
407 address_type =
"PUBLIC";
409 case BLE_ADDR_TYPE_RANDOM:
410 address_type =
"RANDOM";
412 case BLE_ADDR_TYPE_RPA_PUBLIC:
413 address_type =
"RPA_PUBLIC";
415 case BLE_ADDR_TYPE_RPA_RANDOM:
416 address_type =
"RPA_RANDOM";
419 address_type =
"UNKNOWN";
422 ESP_LOGVV(TAG,
" Address: %02X:%02X:%02X:%02X:%02X:%02X (%s)", this->
address_[0], this->
address_[1],
425 ESP_LOGVV(TAG,
" RSSI: %d", this->
rssi_);
426 ESP_LOGVV(TAG,
" Name: '%s'", this->
name_.c_str());
428 ESP_LOGVV(TAG,
" TX Power: %d", it);
431 ESP_LOGVV(TAG,
" Appearance: %u", *this->
appearance_);
434 ESP_LOGVV(TAG,
" Ad Flag: %u", *this->
ad_flag_);
437 ESP_LOGVV(TAG,
" Service UUID: %s", uuid.to_string().c_str());
441 if (ibeacon.has_value()) {
442 ESP_LOGVV(TAG,
" Manufacturer iBeacon:");
443 ESP_LOGVV(TAG,
" UUID: %s", ibeacon.value().get_uuid().to_string().c_str());
444 ESP_LOGVV(TAG,
" Major: %u", ibeacon.value().get_major());
445 ESP_LOGVV(TAG,
" Minor: %u", ibeacon.value().get_minor());
446 ESP_LOGVV(TAG,
" TXPower: %d", ibeacon.value().get_signal_power());
448 ESP_LOGVV(TAG,
" Manufacturer ID: %s, data: %s", data.uuid.to_string().c_str(),
453 ESP_LOGVV(TAG,
" Service data:");
454 ESP_LOGVV(TAG,
" UUID: %s", data.uuid.to_string().c_str());
458 ESP_LOGVV(TAG,
" Adv data: %s",
459 format_hex_pretty(scan_result.ble_adv, scan_result.adv_data_len + scan_result.scan_rsp_len).c_str());
466 while (offset + 2 <
len) {
467 const uint8_t field_length = payload[offset++];
468 if (field_length == 0) {
473 const uint8_t record_type = payload[offset++];
474 const uint8_t *record = &payload[offset];
475 const uint8_t record_length = field_length - 1;
476 offset += record_length;
484 switch (record_type) {
485 case ESP_BLE_AD_TYPE_NAME_SHORT:
486 case ESP_BLE_AD_TYPE_NAME_CMPL: {
493 if (record_length > this->
name_.length()) {
494 this->
name_ = std::string(
reinterpret_cast<const char *
>(record), record_length);
498 case ESP_BLE_AD_TYPE_TX_PWR: {
505 case ESP_BLE_AD_TYPE_APPEARANCE: {
511 this->
appearance_ = *
reinterpret_cast<const uint16_t *
>(record);
514 case ESP_BLE_AD_TYPE_FLAG: {
527 case ESP_BLE_AD_TYPE_16SRV_CMPL:
528 case ESP_BLE_AD_TYPE_16SRV_PART: {
530 for (uint8_t i = 0; i < record_length / 2; i++) {
535 case ESP_BLE_AD_TYPE_32SRV_CMPL:
536 case ESP_BLE_AD_TYPE_32SRV_PART: {
538 for (uint8_t i = 0; i < record_length / 4; i++) {
543 case ESP_BLE_AD_TYPE_128SRV_CMPL:
544 case ESP_BLE_AD_TYPE_128SRV_PART: {
549 case ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE: {
555 if (record_length < 2) {
556 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE");
561 data.data.assign(record + 2UL, record + record_length);
569 case ESP_BLE_AD_TYPE_SERVICE_DATA: {
573 if (record_length < 2) {
574 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_TYPE_SERVICE_DATA");
579 data.data.assign(record + 2UL, record + record_length);
583 case ESP_BLE_AD_TYPE_32SERVICE_DATA: {
587 if (record_length < 4) {
588 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_TYPE_32SERVICE_DATA");
593 data.data.assign(record + 4UL, record + record_length);
597 case ESP_BLE_AD_TYPE_128SERVICE_DATA: {
601 if (record_length < 16) {
602 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_TYPE_128SERVICE_DATA");
607 data.data.assign(record + 16UL, record + record_length);
611 case ESP_BLE_AD_TYPE_INT_RANGE:
615 ESP_LOGV(TAG,
"Unhandled type: advType: 0x%02x", record_type);
624 snprintf(mac,
sizeof(mac),
"%02X:%02X:%02X:%02X:%02X:%02X", this->
address_[0], this->
address_[1], this->
address_[2],
633 ESP_LOGCONFIG(TAG,
"BLE Tracker:");
635 " Scan Duration: %" PRIu32
" s\n"
636 " Scan Interval: %.1f ms\n"
637 " Scan Window: %.1f ms\n"
639 " Continuous Scanning: %s",
643 ESP_LOGCONFIG(TAG,
" Connecting: %d, discovered: %d, searching: %d, disconnecting: %d",
645 this->client_state_counts_.searching, this->client_state_counts_.disconnecting);
651#ifdef USE_ESP32_BLE_DEVICE
658 this->already_discovered_.push_back(
address);
662 const char *address_type_s;
664 case BLE_ADDR_TYPE_PUBLIC:
665 address_type_s =
"PUBLIC";
667 case BLE_ADDR_TYPE_RANDOM:
668 address_type_s =
"RANDOM";
670 case BLE_ADDR_TYPE_RPA_PUBLIC:
671 address_type_s =
"RPA_PUBLIC";
673 case BLE_ADDR_TYPE_RPA_RANDOM:
674 address_type_s =
"RPA_RANDOM";
677 address_type_s =
"UNKNOWN";
681 ESP_LOGD(TAG,
" Address Type: %s", address_type_s);
683 ESP_LOGD(TAG,
" Name: '%s'", device.
get_name().c_str());
686 ESP_LOGD(TAG,
" TX Power: %d", tx_power);
692 uint8_t ecb_plaintext[16];
693 uint8_t ecb_ciphertext[16];
697 memcpy(&ecb_key, irk, 16);
698 memset(&ecb_plaintext, 0, 16);
700 ecb_plaintext[13] = (addr64 >> 40) & 0xff;
701 ecb_plaintext[14] = (addr64 >> 32) & 0xff;
702 ecb_plaintext[15] = (addr64 >> 24) & 0xff;
704 mbedtls_aes_context ctx = {0, 0, {0}};
705 mbedtls_aes_init(&ctx);
707 if (mbedtls_aes_setkey_enc(&ctx, ecb_key, 128) != 0) {
708 mbedtls_aes_free(&ctx);
712 if (mbedtls_aes_crypt_ecb(&ctx, ESP_AES_ENCRYPT, ecb_plaintext, ecb_ciphertext) != 0) {
713 mbedtls_aes_free(&ctx);
717 mbedtls_aes_free(&ctx);
719 return ecb_ciphertext[15] == (addr64 & 0xff) && ecb_ciphertext[14] == ((addr64 >> 8) & 0xff) &&
720 ecb_ciphertext[13] == ((addr64 >> 16) & 0xff);
724 for (
auto *client : this->
clients_) {
725 auto state = client->state();
735 bool found_discovered_client =
false;
740 listener->parse_devices(&scan_result, 1);
742 for (
auto *client : this->
clients_) {
743 client->parse_devices(&scan_result, 1);
749#ifdef USE_ESP32_BLE_DEVICE
755 if (listener->parse_device(device))
759 for (
auto *client : this->
clients_) {
760 if (client->parse_device(device)) {
767 found_discovered_client =
true;
779 return found_discovered_client;
783 ESP_LOGD(TAG,
"Scan %scomplete, set scanner state to IDLE.", is_stop_complete ?
"stop " :
"");
784#ifdef USE_ESP32_BLE_DEVICE
791 listener->on_scan_end();
799 ESP_LOGE(TAG,
"Scan could not restart after %d attempts, rebooting to restore stack (IDF)",
800 std::numeric_limits<uint8_t>::max());
815 for (
auto *client : this->
clients_) {
821 ESP_LOGD(TAG,
"Stopping scan to make connection");
829 ESP_LOGD(TAG,
"Promoting client to connect");
830#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
860#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
863 ESP_LOGD(TAG,
"Setting coexistence to Bluetooth to make connection.");
865 esp_coex_preference_set(ESP_COEX_PREFER_BT);
867 ESP_LOGD(TAG,
"Setting coexistence preference to balanced.");
869 esp_coex_preference_set(ESP_COEX_PREFER_BALANCE);
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
virtual void mark_failed()
Mark this component as failed.
static ESPBTUUID from_uint32(uint32_t uuid)
static ESPBTUUID from_uint16(uint16_t uuid)
static ESPBTUUID from_raw(const uint8_t *data)
bool contains(uint8_t data1, uint8_t data2) const
void try_promote_discovered_clients_()
Try to promote discovered clients to ready to connect.
std::vector< uint64_t > already_discovered_
Vector of addresses that have already been printed in print_bt_device_info.
bool process_scan_result_(const BLEScanResult &scan_result)
Process a single scan result immediately Returns true if a discovered client needs promotion to READY...
uint32_t scan_start_time_
uint8_t scan_start_fail_count_
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.
void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) override
ClientStateCounts count_client_states_() const
Count clients in each state.
ClientStateCounts client_state_counts_
float get_setup_priority() const override
void register_client(ESPBTClient *client)
bool parse_advertisements_
void dump_config() override
void recalculate_advertisement_parser_types()
ScanTimeoutState scan_timeout_state_
ScannerState scanner_state_
esp_ble_scan_params_t scan_params_
A structure holding the ESP BLE scan parameters.
void register_listener(ESPBTDeviceListener *listener)
void update_coex_preference_(bool force_ble)
Update BLE coexistence preference.
const char * scanner_state_to_string_(ScannerState state) const
Convert scanner state enum to string for logging.
CallbackManager< void(ScannerState)> scanner_state_callbacks_
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.
uint32_t scan_duration_
The interval in seconds to perform scans.
bool has_connecting_clients_() const
Check if any clients are in connecting or ready to connect state.
void setup() override
Setup the FreeRTOS task and the Bluetooth stack.
esp_bt_status_t scan_start_failed_
void handle_scanner_failure_()
Handle scanner failure states.
esp_bt_status_t scan_set_param_failed_
void cleanup_scan_state_(bool is_stop_complete)
Common cleanup logic when transitioning scanner to IDLE state.
void ble_before_disabled_event_handler() override
void set_scanner_state_(ScannerState state)
Called to set the scanner state. Will also call callbacks to let listeners know when state is changed...
void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) override
void print_bt_device_info(const ESPBTDevice &device)
void gap_scan_event_handler(const BLEScanResult &scan_result) override
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.
void log_unexpected_state_(const char *operation, ScannerState expected_state) const
Log an unexpected scanner state.
std::vector< ESPBTClient * > clients_
std::vector< ESPBTDeviceListener * > listeners_
void start_scan_(bool first)
Start a single scan by setting up the parameters and doing some esp-idf calls.
struct esphome::esp32_ble_tracker::ESPBLEiBeacon::@80 beacon_data_
static optional< ESPBLEiBeacon > from_manufacturer_data(const ServiceData &data)
uint64_t address_uint64() const
esp_ble_addr_type_t get_address_type() const
esp_ble_addr_type_t address_type_
optional< uint16_t > appearance_
void parse_adv_(const uint8_t *payload, uint8_t len)
void parse_scan_rst(const BLEScanResult &scan_result)
optional< uint8_t > ad_flag_
std::vector< ServiceData > manufacturer_datas_
std::vector< ESPBTUUID > service_uuids_
const std::vector< int8_t > & get_tx_powers() const
const std::string & get_name() const
std::string address_str() const
bool resolve_irk(const uint8_t *irk) const
std::vector< int8_t > tx_powers_
const BLEScanResult * scan_result_
std::vector< ServiceData > service_datas_
void set_parent(ESP32BLETracker *parent)
void add_on_state_callback(std::function< void(OTAState, float, uint8_t, OTAComponent *)> &&callback)
ESP32BLETracker * global_esp32_ble_tracker
const char * client_state_to_string(ClientState state)
uint64_t ble_addr_to_uint64(const esp_bd_addr_t address)
OTAGlobalCallback * get_global_ota_callback()
const float AFTER_BLUETOOTH
std::string format_hex_pretty(const uint8_t *data, size_t length, char separator, bool show_length)
Format a byte array in pretty-printed, human-readable hex format.
Application App
Global storage of Application pointer - only one Application can exist.