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>
28#define MBEDTLS_AES_ALT
36static const char *
const TAG =
"esp32_ble_tracker";
45 return "DISCONNECTING";
64 if (this->
parent_->is_failed()) {
66 ESP_LOGE(TAG,
"BLE Tracker was marked failed by ESP32BLE");
77 for (
auto *client : this->
clients_) {
86 if (!this->
parent_->is_active()) {
111 ESP_LOGW(TAG,
"Scan timeout exceeded");
118 ESP_LOGE(TAG,
"Scan never terminated, rebooting");
132 this->client_state_counts_.discovered, this->client_state_counts_.disconnecting);
154#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
175 ESP_LOGD(TAG,
"Stopping scan.");
190 esp_err_t err = esp_ble_gap_stop_scanning();
192 ESP_LOGE(TAG,
"esp_ble_gap_stop_scanning failed: %d", err);
198 if (!this->
parent_->is_active()) {
199 ESP_LOGW(TAG,
"Cannot start scan while ESP32BLE is disabled.");
207 ESP_LOGD(TAG,
"Starting scan, set scanner state to STARTING.");
210 listener->on_scan_end();
212#ifdef USE_ESP32_BLE_DEVICE
216 this->
scan_params_.own_addr_type = BLE_ADDR_TYPE_PUBLIC;
217 this->
scan_params_.scan_filter_policy = BLE_SCAN_FILTER_ALLOW_ALL;
226 esp_err_t err = esp_ble_gap_set_scan_params(&this->
scan_params_);
228 ESP_LOGE(TAG,
"esp_ble_gap_set_scan_params failed: %d", err);
233 ESP_LOGE(TAG,
"esp_ble_gap_start_scanning failed: %d", err);
260 for (
auto *client : this->
clients_) {
273 case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT:
276 case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT:
279 case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT:
286 for (
auto *client : this->
clients_) {
287 client->gap_event_handler(event, param);
294 ESP_LOGVV(TAG,
"gap_scan_result - event %d", scan_result.search_evt);
296 if (scan_result.search_evt == ESP_GAP_SEARCH_INQ_RES_EVT) {
299 }
else if (scan_result.search_evt == ESP_GAP_SEARCH_INQ_CMPL_EVT) {
311 ESP_LOGV(TAG,
"gap_scan_set_param_complete - status %d", param.status);
312 if (param.status == ESP_BT_STATUS_DONE) {
321 ESP_LOGV(TAG,
"gap_scan_start_complete - status %d", param.status);
326 if (param.status == ESP_BT_STATUS_SUCCESS) {
340 ESP_LOGV(TAG,
"gap_scan_stop_complete - status %d", param.status);
350 esp_ble_gattc_cb_param_t *param) {
351 for (
auto *client : this->
clients_) {
352 client->gattc_event_handler(event, gattc_if, param);
361#ifdef USE_ESP32_BLE_DEVICE
367 if (data.
data.size() != 23)
374 for (uint8_t i = 0; i < ESP_BD_ADDR_LEN; i++)
375 this->
address_[i] = scan_result.bda[i];
376 this->
address_type_ =
static_cast<esp_ble_addr_type_t
>(scan_result.ble_addr_type);
377 this->
rssi_ = scan_result.rssi;
380 uint8_t total_len = scan_result.adv_data_len + scan_result.scan_rsp_len;
381 this->
parse_adv_(scan_result.ble_adv, total_len);
383#ifdef ESPHOME_LOG_HAS_VERY_VERBOSE
384 ESP_LOGVV(TAG,
"Parse Result:");
385 const char *address_type;
387 case BLE_ADDR_TYPE_PUBLIC:
388 address_type =
"PUBLIC";
390 case BLE_ADDR_TYPE_RANDOM:
391 address_type =
"RANDOM";
393 case BLE_ADDR_TYPE_RPA_PUBLIC:
394 address_type =
"RPA_PUBLIC";
396 case BLE_ADDR_TYPE_RPA_RANDOM:
397 address_type =
"RPA_RANDOM";
400 address_type =
"UNKNOWN";
403 ESP_LOGVV(TAG,
" Address: %02X:%02X:%02X:%02X:%02X:%02X (%s)", this->
address_[0], this->
address_[1],
406 ESP_LOGVV(TAG,
" RSSI: %d", this->
rssi_);
407 ESP_LOGVV(TAG,
" Name: '%s'", this->
name_.c_str());
409 ESP_LOGVV(TAG,
" TX Power: %d", it);
412 ESP_LOGVV(TAG,
" Appearance: %u", *this->
appearance_);
415 ESP_LOGVV(TAG,
" Ad Flag: %u", *this->
ad_flag_);
418 ESP_LOGVV(TAG,
" Service UUID: %s", uuid.to_string().c_str());
422 if (ibeacon.has_value()) {
423 ESP_LOGVV(TAG,
" Manufacturer iBeacon:");
424 ESP_LOGVV(TAG,
" UUID: %s", ibeacon.value().get_uuid().to_string().c_str());
425 ESP_LOGVV(TAG,
" Major: %u", ibeacon.value().get_major());
426 ESP_LOGVV(TAG,
" Minor: %u", ibeacon.value().get_minor());
427 ESP_LOGVV(TAG,
" TXPower: %d", ibeacon.value().get_signal_power());
429 ESP_LOGVV(TAG,
" Manufacturer ID: %s, data: %s", data.uuid.to_string().c_str(),
434 ESP_LOGVV(TAG,
" Service data:");
435 ESP_LOGVV(TAG,
" UUID: %s", data.uuid.to_string().c_str());
439 ESP_LOGVV(TAG,
" Adv data: %s",
440 format_hex_pretty(scan_result.ble_adv, scan_result.adv_data_len + scan_result.scan_rsp_len).c_str());
447 while (offset + 2 <
len) {
448 const uint8_t field_length = payload[offset++];
449 if (field_length == 0) {
454 const uint8_t record_type = payload[offset++];
455 const uint8_t *record = &payload[offset];
456 const uint8_t record_length = field_length - 1;
457 offset += record_length;
465 switch (record_type) {
466 case ESP_BLE_AD_TYPE_NAME_SHORT:
467 case ESP_BLE_AD_TYPE_NAME_CMPL: {
474 if (record_length > this->
name_.length()) {
475 this->
name_ = std::string(
reinterpret_cast<const char *
>(record), record_length);
479 case ESP_BLE_AD_TYPE_TX_PWR: {
486 case ESP_BLE_AD_TYPE_APPEARANCE: {
492 this->
appearance_ = *
reinterpret_cast<const uint16_t *
>(record);
495 case ESP_BLE_AD_TYPE_FLAG: {
508 case ESP_BLE_AD_TYPE_16SRV_CMPL:
509 case ESP_BLE_AD_TYPE_16SRV_PART: {
511 for (uint8_t i = 0; i < record_length / 2; i++) {
516 case ESP_BLE_AD_TYPE_32SRV_CMPL:
517 case ESP_BLE_AD_TYPE_32SRV_PART: {
519 for (uint8_t i = 0; i < record_length / 4; i++) {
524 case ESP_BLE_AD_TYPE_128SRV_CMPL:
525 case ESP_BLE_AD_TYPE_128SRV_PART: {
530 case ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE: {
536 if (record_length < 2) {
537 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE");
542 data.data.assign(record + 2UL, record + record_length);
550 case ESP_BLE_AD_TYPE_SERVICE_DATA: {
554 if (record_length < 2) {
555 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_TYPE_SERVICE_DATA");
560 data.data.assign(record + 2UL, record + record_length);
564 case ESP_BLE_AD_TYPE_32SERVICE_DATA: {
568 if (record_length < 4) {
569 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_TYPE_32SERVICE_DATA");
574 data.data.assign(record + 4UL, record + record_length);
578 case ESP_BLE_AD_TYPE_128SERVICE_DATA: {
582 if (record_length < 16) {
583 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_TYPE_128SERVICE_DATA");
588 data.data.assign(record + 16UL, record + record_length);
592 case ESP_BLE_AD_TYPE_INT_RANGE:
596 ESP_LOGV(TAG,
"Unhandled type: advType: 0x%02x", record_type);
613 ESP_LOGCONFIG(TAG,
"BLE Tracker:");
615 " Scan Duration: %" PRIu32
" s\n"
616 " Scan Interval: %.1f ms\n"
617 " Scan Window: %.1f ms\n"
619 " Continuous Scanning: %s",
624 this->client_state_counts_.discovered, this->client_state_counts_.disconnecting);
630#ifdef USE_ESP32_BLE_DEVICE
637 this->already_discovered_.push_back(
address);
641 const char *address_type_s;
643 case BLE_ADDR_TYPE_PUBLIC:
644 address_type_s =
"PUBLIC";
646 case BLE_ADDR_TYPE_RANDOM:
647 address_type_s =
"RANDOM";
649 case BLE_ADDR_TYPE_RPA_PUBLIC:
650 address_type_s =
"RPA_PUBLIC";
652 case BLE_ADDR_TYPE_RPA_RANDOM:
653 address_type_s =
"RPA_RANDOM";
656 address_type_s =
"UNKNOWN";
660 ESP_LOGD(TAG,
" Address Type: %s", address_type_s);
662 ESP_LOGD(TAG,
" Name: '%s'", device.
get_name().c_str());
665 ESP_LOGD(TAG,
" TX Power: %d", tx_power);
671 uint8_t ecb_plaintext[16];
672 uint8_t ecb_ciphertext[16];
676 memcpy(&ecb_key, irk, 16);
677 memset(&ecb_plaintext, 0, 16);
679 ecb_plaintext[13] = (addr64 >> 40) & 0xff;
680 ecb_plaintext[14] = (addr64 >> 32) & 0xff;
681 ecb_plaintext[15] = (addr64 >> 24) & 0xff;
683 mbedtls_aes_context ctx = {0, 0, {0}};
684 mbedtls_aes_init(&ctx);
686 if (mbedtls_aes_setkey_enc(&ctx, ecb_key, 128) != 0) {
687 mbedtls_aes_free(&ctx);
691 if (mbedtls_aes_crypt_ecb(&ctx, ESP_AES_ENCRYPT, ecb_plaintext, ecb_ciphertext) != 0) {
692 mbedtls_aes_free(&ctx);
696 mbedtls_aes_free(&ctx);
698 return ecb_ciphertext[15] == (addr64 & 0xff) && ecb_ciphertext[14] == ((addr64 >> 8) & 0xff) &&
699 ecb_ciphertext[13] == ((addr64 >> 16) & 0xff);
708 listener->parse_devices(&scan_result, 1);
710 for (
auto *client : this->
clients_) {
711 client->parse_devices(&scan_result, 1);
717#ifdef USE_ESP32_BLE_DEVICE
723 if (listener->parse_device(device))
727 for (
auto *client : this->
clients_) {
728 if (client->parse_device(device)) {
741 ESP_LOGD(TAG,
"Scan %scomplete, set scanner state to IDLE.", is_stop_complete ?
"stop " :
"");
742#ifdef USE_ESP32_BLE_DEVICE
749 listener->on_scan_end();
757 ESP_LOGE(TAG,
"Scan could not restart after %d attempts, rebooting to restore stack (IDF)",
758 std::numeric_limits<uint8_t>::max());
773 for (
auto *client : this->
clients_) {
779 ESP_LOGD(TAG,
"Stopping scan to make connection");
787 ESP_LOGD(TAG,
"Promoting client to connect");
788#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
818#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
821 ESP_LOGD(TAG,
"Setting coexistence to Bluetooth to make connection.");
823 esp_coex_preference_set(ESP_COEX_PREFER_BT);
825 ESP_LOGD(TAG,
"Setting coexistence preference to balanced.");
827 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.