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";
68 if (this->
parent_->is_failed()) {
70 ESP_LOGE(TAG,
"BLE Tracker was marked failed by ESP32BLE");
81 for (
auto *client : this->
clients_) {
90 if (!this->
parent_->is_active()) {
115 ESP_LOGW(TAG,
"Scan timeout exceeded");
122 ESP_LOGE(TAG,
"Scan never terminated, rebooting");
136 this->client_state_counts_.discovered, this->client_state_counts_.disconnecting);
158#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
179 ESP_LOGD(TAG,
"Stopping scan.");
194 esp_err_t err = esp_ble_gap_stop_scanning();
196 ESP_LOGE(TAG,
"esp_ble_gap_stop_scanning failed: %d", err);
202 if (!this->
parent_->is_active()) {
203 ESP_LOGW(TAG,
"Cannot start scan while ESP32BLE is disabled.");
211 ESP_LOGD(TAG,
"Starting scan, set scanner state to STARTING.");
214 listener->on_scan_end();
216#ifdef USE_ESP32_BLE_DEVICE
220 this->
scan_params_.own_addr_type = BLE_ADDR_TYPE_PUBLIC;
221 this->
scan_params_.scan_filter_policy = BLE_SCAN_FILTER_ALLOW_ALL;
230 esp_err_t err = esp_ble_gap_set_scan_params(&this->
scan_params_);
232 ESP_LOGE(TAG,
"esp_ble_gap_set_scan_params failed: %d", err);
237 ESP_LOGE(TAG,
"esp_ble_gap_start_scanning failed: %d", err);
264 for (
auto *client : this->
clients_) {
277 case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT:
280 case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT:
283 case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT:
290 for (
auto *client : this->
clients_) {
291 client->gap_event_handler(event, param);
298 ESP_LOGVV(TAG,
"gap_scan_result - event %d", scan_result.search_evt);
300 if (scan_result.search_evt == ESP_GAP_SEARCH_INQ_RES_EVT) {
303 }
else if (scan_result.search_evt == ESP_GAP_SEARCH_INQ_CMPL_EVT) {
315 ESP_LOGV(TAG,
"gap_scan_set_param_complete - status %d", param.status);
316 if (param.status == ESP_BT_STATUS_DONE) {
325 ESP_LOGV(TAG,
"gap_scan_start_complete - status %d", param.status);
330 if (param.status == ESP_BT_STATUS_SUCCESS) {
344 ESP_LOGV(TAG,
"gap_scan_stop_complete - status %d", param.status);
354 esp_ble_gattc_cb_param_t *param) {
355 for (
auto *client : this->
clients_) {
356 client->gattc_event_handler(event, gattc_if, param);
365#ifdef USE_ESP32_BLE_DEVICE
371 if (data.
data.size() != 23)
378 for (uint8_t i = 0; i < ESP_BD_ADDR_LEN; i++)
379 this->
address_[i] = scan_result.bda[i];
380 this->
address_type_ =
static_cast<esp_ble_addr_type_t
>(scan_result.ble_addr_type);
381 this->
rssi_ = scan_result.rssi;
384 uint8_t total_len = scan_result.adv_data_len + scan_result.scan_rsp_len;
385 this->
parse_adv_(scan_result.ble_adv, total_len);
387#ifdef ESPHOME_LOG_HAS_VERY_VERBOSE
388 ESP_LOGVV(TAG,
"Parse Result:");
389 const char *address_type;
391 case BLE_ADDR_TYPE_PUBLIC:
392 address_type =
"PUBLIC";
394 case BLE_ADDR_TYPE_RANDOM:
395 address_type =
"RANDOM";
397 case BLE_ADDR_TYPE_RPA_PUBLIC:
398 address_type =
"RPA_PUBLIC";
400 case BLE_ADDR_TYPE_RPA_RANDOM:
401 address_type =
"RPA_RANDOM";
404 address_type =
"UNKNOWN";
407 ESP_LOGVV(TAG,
" Address: %02X:%02X:%02X:%02X:%02X:%02X (%s)", this->
address_[0], this->
address_[1],
410 ESP_LOGVV(TAG,
" RSSI: %d", this->
rssi_);
411 ESP_LOGVV(TAG,
" Name: '%s'", this->
name_.c_str());
413 ESP_LOGVV(TAG,
" TX Power: %d", it);
416 ESP_LOGVV(TAG,
" Appearance: %u", *this->
appearance_);
419 ESP_LOGVV(TAG,
" Ad Flag: %u", *this->
ad_flag_);
422 ESP_LOGVV(TAG,
" Service UUID: %s", uuid.to_string().c_str());
426 if (ibeacon.has_value()) {
427 ESP_LOGVV(TAG,
" Manufacturer iBeacon:");
428 ESP_LOGVV(TAG,
" UUID: %s", ibeacon.value().get_uuid().to_string().c_str());
429 ESP_LOGVV(TAG,
" Major: %u", ibeacon.value().get_major());
430 ESP_LOGVV(TAG,
" Minor: %u", ibeacon.value().get_minor());
431 ESP_LOGVV(TAG,
" TXPower: %d", ibeacon.value().get_signal_power());
433 ESP_LOGVV(TAG,
" Manufacturer ID: %s, data: %s", data.uuid.to_string().c_str(),
438 ESP_LOGVV(TAG,
" Service data:");
439 ESP_LOGVV(TAG,
" UUID: %s", data.uuid.to_string().c_str());
443 ESP_LOGVV(TAG,
" Adv data: %s",
444 format_hex_pretty(scan_result.ble_adv, scan_result.adv_data_len + scan_result.scan_rsp_len).c_str());
451 while (offset + 2 <
len) {
452 const uint8_t field_length = payload[offset++];
453 if (field_length == 0) {
458 const uint8_t record_type = payload[offset++];
459 const uint8_t *record = &payload[offset];
460 const uint8_t record_length = field_length - 1;
461 offset += record_length;
469 switch (record_type) {
470 case ESP_BLE_AD_TYPE_NAME_SHORT:
471 case ESP_BLE_AD_TYPE_NAME_CMPL: {
478 if (record_length > this->
name_.length()) {
479 this->
name_ = std::string(
reinterpret_cast<const char *
>(record), record_length);
483 case ESP_BLE_AD_TYPE_TX_PWR: {
490 case ESP_BLE_AD_TYPE_APPEARANCE: {
496 this->
appearance_ = *
reinterpret_cast<const uint16_t *
>(record);
499 case ESP_BLE_AD_TYPE_FLAG: {
512 case ESP_BLE_AD_TYPE_16SRV_CMPL:
513 case ESP_BLE_AD_TYPE_16SRV_PART: {
515 for (uint8_t i = 0; i < record_length / 2; i++) {
520 case ESP_BLE_AD_TYPE_32SRV_CMPL:
521 case ESP_BLE_AD_TYPE_32SRV_PART: {
523 for (uint8_t i = 0; i < record_length / 4; i++) {
528 case ESP_BLE_AD_TYPE_128SRV_CMPL:
529 case ESP_BLE_AD_TYPE_128SRV_PART: {
534 case ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE: {
540 if (record_length < 2) {
541 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE");
546 data.data.assign(record + 2UL, record + record_length);
554 case ESP_BLE_AD_TYPE_SERVICE_DATA: {
558 if (record_length < 2) {
559 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_TYPE_SERVICE_DATA");
564 data.data.assign(record + 2UL, record + record_length);
568 case ESP_BLE_AD_TYPE_32SERVICE_DATA: {
572 if (record_length < 4) {
573 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_TYPE_32SERVICE_DATA");
578 data.data.assign(record + 4UL, record + record_length);
582 case ESP_BLE_AD_TYPE_128SERVICE_DATA: {
586 if (record_length < 16) {
587 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_TYPE_128SERVICE_DATA");
592 data.data.assign(record + 16UL, record + record_length);
596 case ESP_BLE_AD_TYPE_INT_RANGE:
600 ESP_LOGV(TAG,
"Unhandled type: advType: 0x%02x", record_type);
617 ESP_LOGCONFIG(TAG,
"BLE Tracker:");
619 " Scan Duration: %" PRIu32
" s\n"
620 " Scan Interval: %.1f ms\n"
621 " Scan Window: %.1f ms\n"
623 " Continuous Scanning: %s",
628 this->client_state_counts_.discovered, this->client_state_counts_.disconnecting);
634#ifdef USE_ESP32_BLE_DEVICE
641 this->already_discovered_.push_back(
address);
645 const char *address_type_s;
647 case BLE_ADDR_TYPE_PUBLIC:
648 address_type_s =
"PUBLIC";
650 case BLE_ADDR_TYPE_RANDOM:
651 address_type_s =
"RANDOM";
653 case BLE_ADDR_TYPE_RPA_PUBLIC:
654 address_type_s =
"RPA_PUBLIC";
656 case BLE_ADDR_TYPE_RPA_RANDOM:
657 address_type_s =
"RPA_RANDOM";
660 address_type_s =
"UNKNOWN";
664 ESP_LOGD(TAG,
" Address Type: %s", address_type_s);
666 ESP_LOGD(TAG,
" Name: '%s'", device.
get_name().c_str());
669 ESP_LOGD(TAG,
" TX Power: %d", tx_power);
675 uint8_t ecb_plaintext[16];
676 uint8_t ecb_ciphertext[16];
680 memcpy(&ecb_key, irk, 16);
681 memset(&ecb_plaintext, 0, 16);
683 ecb_plaintext[13] = (addr64 >> 40) & 0xff;
684 ecb_plaintext[14] = (addr64 >> 32) & 0xff;
685 ecb_plaintext[15] = (addr64 >> 24) & 0xff;
687 mbedtls_aes_context ctx = {0, 0, {0}};
688 mbedtls_aes_init(&ctx);
690 if (mbedtls_aes_setkey_enc(&ctx, ecb_key, 128) != 0) {
691 mbedtls_aes_free(&ctx);
695 if (mbedtls_aes_crypt_ecb(&ctx, ESP_AES_ENCRYPT, ecb_plaintext, ecb_ciphertext) != 0) {
696 mbedtls_aes_free(&ctx);
700 mbedtls_aes_free(&ctx);
702 return ecb_ciphertext[15] == (addr64 & 0xff) && ecb_ciphertext[14] == ((addr64 >> 8) & 0xff) &&
703 ecb_ciphertext[13] == ((addr64 >> 16) & 0xff);
712 listener->parse_devices(&scan_result, 1);
714 for (
auto *client : this->
clients_) {
715 client->parse_devices(&scan_result, 1);
721#ifdef USE_ESP32_BLE_DEVICE
727 if (listener->parse_device(device))
731 for (
auto *client : this->
clients_) {
732 if (client->parse_device(device)) {
745 ESP_LOGD(TAG,
"Scan %scomplete, set scanner state to IDLE.", is_stop_complete ?
"stop " :
"");
746#ifdef USE_ESP32_BLE_DEVICE
753 listener->on_scan_end();
761 ESP_LOGE(TAG,
"Scan could not restart after %d attempts, rebooting to restore stack (IDF)",
762 std::numeric_limits<uint8_t>::max());
777 for (
auto *client : this->
clients_) {
783 ESP_LOGD(TAG,
"Stopping scan to make connection");
791 ESP_LOGD(TAG,
"Promoting client to connect");
792#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
822#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
825 ESP_LOGD(TAG,
"Setting coexistence to Bluetooth to make connection.");
827 esp_coex_preference_set(ESP_COEX_PREFER_BT);
829 ESP_LOGD(TAG,
"Setting coexistence preference to balanced.");
831 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.