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";
55 return "READY_TO_CONNECT";
70 if (this->
parent_->is_failed()) {
72 ESP_LOGE(TAG,
"BLE Tracker was marked failed by ESP32BLE");
83 for (
auto *client : this->
clients_) {
92 if (!this->
parent_->is_active()) {
117 ESP_LOGW(TAG,
"Scan timeout exceeded");
124 ESP_LOGE(TAG,
"Scan never terminated, rebooting");
138 this->client_state_counts_.discovered, this->client_state_counts_.disconnecting);
160#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
181 ESP_LOGD(TAG,
"Stopping scan.");
196 esp_err_t err = esp_ble_gap_stop_scanning();
198 ESP_LOGE(TAG,
"esp_ble_gap_stop_scanning failed: %d", err);
204 if (!this->
parent_->is_active()) {
205 ESP_LOGW(TAG,
"Cannot start scan while ESP32BLE is disabled.");
213 ESP_LOGD(TAG,
"Starting scan, set scanner state to STARTING.");
216 listener->on_scan_end();
218#ifdef USE_ESP32_BLE_DEVICE
222 this->
scan_params_.own_addr_type = BLE_ADDR_TYPE_PUBLIC;
223 this->
scan_params_.scan_filter_policy = BLE_SCAN_FILTER_ALLOW_ALL;
232 esp_err_t err = esp_ble_gap_set_scan_params(&this->
scan_params_);
234 ESP_LOGE(TAG,
"esp_ble_gap_set_scan_params failed: %d", err);
239 ESP_LOGE(TAG,
"esp_ble_gap_start_scanning failed: %d", err);
266 for (
auto *client : this->
clients_) {
279 case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT:
282 case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT:
285 case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT:
292 for (
auto *client : this->
clients_) {
293 client->gap_event_handler(event, param);
300 ESP_LOGV(TAG,
"gap_scan_result - event %d", scan_result.search_evt);
302 if (scan_result.search_evt == ESP_GAP_SEARCH_INQ_RES_EVT) {
305 }
else if (scan_result.search_evt == ESP_GAP_SEARCH_INQ_CMPL_EVT) {
317 ESP_LOGV(TAG,
"gap_scan_set_param_complete - status %d", param.status);
318 if (param.status == ESP_BT_STATUS_DONE) {
327 ESP_LOGV(TAG,
"gap_scan_start_complete - status %d", param.status);
332 if (param.status == ESP_BT_STATUS_SUCCESS) {
346 ESP_LOGV(TAG,
"gap_scan_stop_complete - status %d", param.status);
356 esp_ble_gattc_cb_param_t *param) {
357 for (
auto *client : this->
clients_) {
358 client->gattc_event_handler(event, gattc_if, param);
367#ifdef USE_ESP32_BLE_DEVICE
373 if (data.
data.size() != 23)
380 for (uint8_t i = 0; i < ESP_BD_ADDR_LEN; i++)
381 this->
address_[i] = scan_result.bda[i];
382 this->
address_type_ =
static_cast<esp_ble_addr_type_t
>(scan_result.ble_addr_type);
383 this->
rssi_ = scan_result.rssi;
386 uint8_t total_len = scan_result.adv_data_len + scan_result.scan_rsp_len;
387 this->
parse_adv_(scan_result.ble_adv, total_len);
389#ifdef ESPHOME_LOG_HAS_VERY_VERBOSE
390 ESP_LOGVV(TAG,
"Parse Result:");
391 const char *address_type;
393 case BLE_ADDR_TYPE_PUBLIC:
394 address_type =
"PUBLIC";
396 case BLE_ADDR_TYPE_RANDOM:
397 address_type =
"RANDOM";
399 case BLE_ADDR_TYPE_RPA_PUBLIC:
400 address_type =
"RPA_PUBLIC";
402 case BLE_ADDR_TYPE_RPA_RANDOM:
403 address_type =
"RPA_RANDOM";
406 address_type =
"UNKNOWN";
409 ESP_LOGVV(TAG,
" Address: %02X:%02X:%02X:%02X:%02X:%02X (%s)", this->
address_[0], this->
address_[1],
412 ESP_LOGVV(TAG,
" RSSI: %d", this->
rssi_);
413 ESP_LOGVV(TAG,
" Name: '%s'", this->
name_.c_str());
415 ESP_LOGVV(TAG,
" TX Power: %d", it);
418 ESP_LOGVV(TAG,
" Appearance: %u", *this->
appearance_);
421 ESP_LOGVV(TAG,
" Ad Flag: %u", *this->
ad_flag_);
424 ESP_LOGVV(TAG,
" Service UUID: %s", uuid.to_string().c_str());
428 if (ibeacon.has_value()) {
429 ESP_LOGVV(TAG,
" Manufacturer iBeacon:");
430 ESP_LOGVV(TAG,
" UUID: %s", ibeacon.value().get_uuid().to_string().c_str());
431 ESP_LOGVV(TAG,
" Major: %u", ibeacon.value().get_major());
432 ESP_LOGVV(TAG,
" Minor: %u", ibeacon.value().get_minor());
433 ESP_LOGVV(TAG,
" TXPower: %d", ibeacon.value().get_signal_power());
435 ESP_LOGVV(TAG,
" Manufacturer ID: %s, data: %s", data.uuid.to_string().c_str(),
440 ESP_LOGVV(TAG,
" Service data:");
441 ESP_LOGVV(TAG,
" UUID: %s", data.uuid.to_string().c_str());
445 ESP_LOGVV(TAG,
" Adv data: %s",
446 format_hex_pretty(scan_result.ble_adv, scan_result.adv_data_len + scan_result.scan_rsp_len).c_str());
453 while (offset + 2 <
len) {
454 const uint8_t field_length = payload[offset++];
455 if (field_length == 0) {
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;
471 switch (record_type) {
472 case ESP_BLE_AD_TYPE_NAME_SHORT:
473 case ESP_BLE_AD_TYPE_NAME_CMPL: {
480 if (record_length > this->
name_.length()) {
481 this->
name_ = std::string(
reinterpret_cast<const char *
>(record), record_length);
485 case ESP_BLE_AD_TYPE_TX_PWR: {
492 case ESP_BLE_AD_TYPE_APPEARANCE: {
498 this->
appearance_ = *
reinterpret_cast<const uint16_t *
>(record);
501 case ESP_BLE_AD_TYPE_FLAG: {
514 case ESP_BLE_AD_TYPE_16SRV_CMPL:
515 case ESP_BLE_AD_TYPE_16SRV_PART: {
517 for (uint8_t i = 0; i < record_length / 2; i++) {
522 case ESP_BLE_AD_TYPE_32SRV_CMPL:
523 case ESP_BLE_AD_TYPE_32SRV_PART: {
525 for (uint8_t i = 0; i < record_length / 4; i++) {
530 case ESP_BLE_AD_TYPE_128SRV_CMPL:
531 case ESP_BLE_AD_TYPE_128SRV_PART: {
536 case ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE: {
542 if (record_length < 2) {
543 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE");
548 data.data.assign(record + 2UL, record + record_length);
556 case ESP_BLE_AD_TYPE_SERVICE_DATA: {
560 if (record_length < 2) {
561 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_TYPE_SERVICE_DATA");
566 data.data.assign(record + 2UL, record + record_length);
570 case ESP_BLE_AD_TYPE_32SERVICE_DATA: {
574 if (record_length < 4) {
575 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_TYPE_32SERVICE_DATA");
580 data.data.assign(record + 4UL, record + record_length);
584 case ESP_BLE_AD_TYPE_128SERVICE_DATA: {
588 if (record_length < 16) {
589 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_TYPE_128SERVICE_DATA");
594 data.data.assign(record + 16UL, record + record_length);
598 case ESP_BLE_AD_TYPE_INT_RANGE:
602 ESP_LOGV(TAG,
"Unhandled type: advType: 0x%02x", record_type);
619 ESP_LOGCONFIG(TAG,
"BLE Tracker:");
621 " Scan Duration: %" PRIu32
" s\n"
622 " Scan Interval: %.1f ms\n"
623 " Scan Window: %.1f ms\n"
625 " Continuous Scanning: %s",
630 this->client_state_counts_.discovered, this->client_state_counts_.disconnecting);
636#ifdef USE_ESP32_BLE_DEVICE
643 this->already_discovered_.push_back(
address);
647 const char *address_type_s;
649 case BLE_ADDR_TYPE_PUBLIC:
650 address_type_s =
"PUBLIC";
652 case BLE_ADDR_TYPE_RANDOM:
653 address_type_s =
"RANDOM";
655 case BLE_ADDR_TYPE_RPA_PUBLIC:
656 address_type_s =
"RPA_PUBLIC";
658 case BLE_ADDR_TYPE_RPA_RANDOM:
659 address_type_s =
"RPA_RANDOM";
662 address_type_s =
"UNKNOWN";
666 ESP_LOGD(TAG,
" Address Type: %s", address_type_s);
668 ESP_LOGD(TAG,
" Name: '%s'", device.
get_name().c_str());
671 ESP_LOGD(TAG,
" TX Power: %d", tx_power);
677 uint8_t ecb_plaintext[16];
678 uint8_t ecb_ciphertext[16];
682 memcpy(&ecb_key, irk, 16);
683 memset(&ecb_plaintext, 0, 16);
685 ecb_plaintext[13] = (addr64 >> 40) & 0xff;
686 ecb_plaintext[14] = (addr64 >> 32) & 0xff;
687 ecb_plaintext[15] = (addr64 >> 24) & 0xff;
689 mbedtls_aes_context ctx = {0, 0, {0}};
690 mbedtls_aes_init(&ctx);
692 if (mbedtls_aes_setkey_enc(&ctx, ecb_key, 128) != 0) {
693 mbedtls_aes_free(&ctx);
697 if (mbedtls_aes_crypt_ecb(&ctx, ESP_AES_ENCRYPT, ecb_plaintext, ecb_ciphertext) != 0) {
698 mbedtls_aes_free(&ctx);
702 mbedtls_aes_free(&ctx);
704 return ecb_ciphertext[15] == (addr64 & 0xff) && ecb_ciphertext[14] == ((addr64 >> 8) & 0xff) &&
705 ecb_ciphertext[13] == ((addr64 >> 16) & 0xff);
714 listener->parse_devices(&scan_result, 1);
716 for (
auto *client : this->
clients_) {
717 client->parse_devices(&scan_result, 1);
723#ifdef USE_ESP32_BLE_DEVICE
729 if (listener->parse_device(device))
733 for (
auto *client : this->
clients_) {
734 if (client->parse_device(device)) {
747 ESP_LOGD(TAG,
"Scan %scomplete, set scanner state to IDLE.", is_stop_complete ?
"stop " :
"");
748#ifdef USE_ESP32_BLE_DEVICE
755 listener->on_scan_end();
763 ESP_LOGE(TAG,
"Scan could not restart after %d attempts, rebooting to restore stack (IDF)",
764 std::numeric_limits<uint8_t>::max());
779 for (
auto *client : this->
clients_) {
785 ESP_LOGD(TAG,
"Stopping scan to make connection");
793 ESP_LOGD(TAG,
"Promoting client to connect");
794#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
824#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
827 ESP_LOGD(TAG,
"Setting coexistence to Bluetooth to make connection.");
829 esp_coex_preference_set(ESP_COEX_PREFER_BT);
831 ESP_LOGD(TAG,
"Setting coexistence preference to balanced.");
833 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.
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.
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 process_scan_result_(const BLEScanResult &scan_result)
Process a single scan result immediately.
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::@78 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
void format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase)
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.