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
39namespace esp32_ble_tracker {
41static const char *
const TAG =
"esp32_ble_tracker";
48 if (this->
parent_->is_failed()) {
50 ESP_LOGE(TAG,
"BLE Tracker was marked failed by ESP32BLE");
58 ESP_LOGE(TAG,
"Could not allocate buffer for BLE Tracker!");
62 global_esp32_ble_tracker =
this;
70 for (
auto *client : this->
clients_) {
79 if (!this->
parent_->is_active()) {
92 int disconnecting = 0;
93 for (
auto *client : this->
clients_) {
94 switch (client->state()) {
118 ESP_LOGD(TAG,
"connecting: %d, discovered: %d, searching: %d, disconnecting: %d",
connecting_,
discovered_,
121 bool promote_to_connecting = discovered && !searching && !connecting;
128 ESP_LOGW(TAG,
"Too many BLE events to process. Some devices may not show up.");
135 for (
auto *client : this->clients_) {
141 for (
size_t i = 0; i < index; i++) {
147 if (listener->parse_device(device))
151 for (
auto *client : this->clients_) {
152 if (client->parse_device(device)) {
155 promote_to_connecting =
true;
175 ESP_LOGE(TAG,
"ESP-IDF BLE scan could not restart after %d attempts, rebooting to restore BLE stack...",
176 std::numeric_limits<uint8_t>::max());
202#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
205 ESP_LOGD(TAG,
"Setting coexistence preference to balanced.");
206 esp_coex_preference_set(ESP_COEX_PREFER_BALANCE);
217 if (promote_to_connecting &&
219 for (
auto *client : this->clients_) {
222 ESP_LOGD(TAG,
"Stopping scan to make connection...");
225 ESP_LOGD(TAG,
"Promoting client to connect...");
228#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
229 ESP_LOGD(TAG,
"Setting coexistence to Bluetooth to make connection.");
232 esp_coex_preference_set(ESP_COEX_PREFER_BT);
246 ESP_LOGD(TAG,
"Stopping scan.");
256 ESP_LOGE(TAG,
"Scan is already stopped while trying to stop.");
258 ESP_LOGE(TAG,
"Scan is starting while trying to stop.");
260 ESP_LOGE(TAG,
"Scan is already stopping while trying to stop.");
262 ESP_LOGE(TAG,
"Scan is already stopped while trying to stop.");
268 esp_err_t err = esp_ble_gap_stop_scanning();
270 ESP_LOGE(TAG,
"esp_ble_gap_stop_scanning failed: %d", err);
276 if (!this->
parent_->is_active()) {
277 ESP_LOGW(TAG,
"Cannot start scan while ESP32BLE is disabled.");
282 ESP_LOGE(TAG,
"Cannot start scan while already starting.");
284 ESP_LOGE(TAG,
"Cannot start scan while already running.");
286 ESP_LOGE(TAG,
"Cannot start scan while already stopping.");
288 ESP_LOGE(TAG,
"Cannot start scan while already failed.");
290 ESP_LOGE(TAG,
"Cannot start scan while already stopped.");
295 ESP_LOGD(TAG,
"Starting scan, set scanner state to STARTING.");
298 listener->on_scan_end();
302 this->
scan_params_.own_addr_type = BLE_ADDR_TYPE_PUBLIC;
303 this->
scan_params_.scan_filter_policy = BLE_SCAN_FILTER_ALLOW_ALL;
309 ESP_LOGE(TAG,
"ESP-IDF BLE scan never terminated, rebooting to restore BLE stack...");
313 esp_err_t err = esp_ble_gap_set_scan_params(&this->
scan_params_);
315 ESP_LOGE(TAG,
"esp_ble_gap_set_scan_params failed: %d", err);
320 ESP_LOGE(TAG,
"esp_ble_gap_start_scanning failed: %d", err);
328 ESP_LOGE(TAG,
"end_of_scan_ called while scanner is not stopped.");
331 ESP_LOGD(TAG,
"End of scan, set scanner state to IDLE.");
336 listener->on_scan_end();
362 for (
auto *client : this->
clients_) {
373 case ESP_GAP_BLE_SCAN_RESULT_EVT:
376 case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT:
379 case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT:
382 case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT:
388 for (
auto *client : this->
clients_) {
389 client->gap_event_handler(event, param);
394 ESP_LOGV(TAG,
"gap_scan_set_param_complete - status %d", param.status);
395 if (param.status == ESP_BT_STATUS_DONE) {
403 ESP_LOGV(TAG,
"gap_scan_start_complete - status %d", param.status);
407 ESP_LOGE(TAG,
"Scan was already running when start complete.");
409 ESP_LOGE(TAG,
"Scan was stopping when start complete.");
411 ESP_LOGE(TAG,
"Scan was in failed state when start complete.");
413 ESP_LOGE(TAG,
"Scan was idle when start complete.");
415 ESP_LOGE(TAG,
"Scan was stopped when start complete.");
418 if (param.status == ESP_BT_STATUS_SUCCESS) {
430 ESP_LOGV(TAG,
"gap_scan_stop_complete - status %d", param.status);
433 ESP_LOGE(TAG,
"Scan was not running when stop complete.");
435 ESP_LOGE(TAG,
"Scan was not started when stop complete.");
437 ESP_LOGE(TAG,
"Scan was in failed state when stop complete.");
439 ESP_LOGE(TAG,
"Scan was idle when stop complete.");
441 ESP_LOGE(TAG,
"Scan was stopped when stop complete.");
448 ESP_LOGV(TAG,
"gap_scan_result - event %d", param.search_evt);
449 if (param.search_evt == ESP_GAP_SEARCH_INQ_RES_EVT) {
456 }
else if (param.search_evt == ESP_GAP_SEARCH_INQ_CMPL_EVT) {
460 ESP_LOGE(TAG,
"Scan was not running when scan completed.");
462 ESP_LOGE(TAG,
"Scan was not started when scan completed.");
464 ESP_LOGE(TAG,
"Scan was in failed state when scan completed.");
466 ESP_LOGE(TAG,
"Scan was idle when scan completed.");
468 ESP_LOGE(TAG,
"Scan was stopped when scan completed.");
476 esp_ble_gattc_cb_param_t *param) {
477 for (
auto *client : this->
clients_) {
478 client->gattc_event_handler(event, gattc_if, param);
492 if (data.
data.size() != 23)
499 for (uint8_t i = 0; i < ESP_BD_ADDR_LEN; i++)
502 this->
rssi_ = param.rssi;
505#ifdef ESPHOME_LOG_HAS_VERY_VERBOSE
506 ESP_LOGVV(TAG,
"Parse Result:");
507 const char *address_type;
509 case BLE_ADDR_TYPE_PUBLIC:
510 address_type =
"PUBLIC";
512 case BLE_ADDR_TYPE_RANDOM:
513 address_type =
"RANDOM";
515 case BLE_ADDR_TYPE_RPA_PUBLIC:
516 address_type =
"RPA_PUBLIC";
518 case BLE_ADDR_TYPE_RPA_RANDOM:
519 address_type =
"RPA_RANDOM";
522 address_type =
"UNKNOWN";
525 ESP_LOGVV(TAG,
" Address: %02X:%02X:%02X:%02X:%02X:%02X (%s)", this->
address_[0], this->
address_[1],
528 ESP_LOGVV(TAG,
" RSSI: %d", this->
rssi_);
529 ESP_LOGVV(TAG,
" Name: '%s'", this->
name_.c_str());
531 ESP_LOGVV(TAG,
" TX Power: %d", it);
534 ESP_LOGVV(TAG,
" Appearance: %u", *this->
appearance_);
537 ESP_LOGVV(TAG,
" Ad Flag: %u", *this->
ad_flag_);
540 ESP_LOGVV(TAG,
" Service UUID: %s", uuid.to_string().c_str());
544 if (ibeacon.has_value()) {
545 ESP_LOGVV(TAG,
" Manufacturer iBeacon:");
546 ESP_LOGVV(TAG,
" UUID: %s", ibeacon.value().get_uuid().to_string().c_str());
547 ESP_LOGVV(TAG,
" Major: %u", ibeacon.value().get_major());
548 ESP_LOGVV(TAG,
" Minor: %u", ibeacon.value().get_minor());
549 ESP_LOGVV(TAG,
" TXPower: %d", ibeacon.value().get_signal_power());
551 ESP_LOGVV(TAG,
" Manufacturer ID: %s, data: %s", data.uuid.to_string().c_str(),
556 ESP_LOGVV(TAG,
" Service data:");
557 ESP_LOGVV(TAG,
" UUID: %s", data.uuid.to_string().c_str());
561 ESP_LOGVV(TAG,
" Adv data: %s",
format_hex_pretty(param.ble_adv, param.adv_data_len + param.scan_rsp_len).c_str());
566 const uint8_t *payload = param.ble_adv;
567 uint8_t
len = param.adv_data_len + param.scan_rsp_len;
569 while (offset + 2 <
len) {
570 const uint8_t field_length = payload[offset++];
571 if (field_length == 0) {
576 const uint8_t record_type = payload[offset++];
577 const uint8_t *record = &payload[offset];
578 const uint8_t record_length = field_length - 1;
579 offset += record_length;
587 switch (record_type) {
588 case ESP_BLE_AD_TYPE_NAME_SHORT:
589 case ESP_BLE_AD_TYPE_NAME_CMPL: {
596 if (record_length > this->
name_.length()) {
597 this->
name_ = std::string(
reinterpret_cast<const char *
>(record), record_length);
601 case ESP_BLE_AD_TYPE_TX_PWR: {
608 case ESP_BLE_AD_TYPE_APPEARANCE: {
614 this->
appearance_ = *
reinterpret_cast<const uint16_t *
>(record);
617 case ESP_BLE_AD_TYPE_FLAG: {
630 case ESP_BLE_AD_TYPE_16SRV_CMPL:
631 case ESP_BLE_AD_TYPE_16SRV_PART: {
633 for (uint8_t i = 0; i < record_length / 2; i++) {
638 case ESP_BLE_AD_TYPE_32SRV_CMPL:
639 case ESP_BLE_AD_TYPE_32SRV_PART: {
641 for (uint8_t i = 0; i < record_length / 4; i++) {
646 case ESP_BLE_AD_TYPE_128SRV_CMPL:
647 case ESP_BLE_AD_TYPE_128SRV_PART: {
652 case ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE: {
658 if (record_length < 2) {
659 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE");
664 data.data.assign(record + 2UL, record + record_length);
672 case ESP_BLE_AD_TYPE_SERVICE_DATA: {
676 if (record_length < 2) {
677 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_TYPE_SERVICE_DATA");
682 data.data.assign(record + 2UL, record + record_length);
686 case ESP_BLE_AD_TYPE_32SERVICE_DATA: {
690 if (record_length < 4) {
691 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_TYPE_32SERVICE_DATA");
696 data.data.assign(record + 4UL, record + record_length);
700 case ESP_BLE_AD_TYPE_128SERVICE_DATA: {
704 if (record_length < 16) {
705 ESP_LOGV(TAG,
"Record length too small for ESP_BLE_AD_TYPE_128SERVICE_DATA");
710 data.data.assign(record + 16UL, record + record_length);
714 case ESP_BLE_AD_TYPE_INT_RANGE:
718 ESP_LOGV(TAG,
"Unhandled type: advType: 0x%02x", record_type);
726 snprintf(mac,
sizeof(mac),
"%02X:%02X:%02X:%02X:%02X:%02X", this->
address_[0], this->
address_[1], this->
address_[2],
733 ESP_LOGCONFIG(TAG,
"BLE Tracker:");
734 ESP_LOGCONFIG(TAG,
" Scan Duration: %" PRIu32
" s", this->
scan_duration_);
735 ESP_LOGCONFIG(TAG,
" Scan Interval: %.1f ms", this->
scan_interval_ * 0.625f);
736 ESP_LOGCONFIG(TAG,
" Scan Window: %.1f ms", this->
scan_window_ * 0.625f);
737 ESP_LOGCONFIG(TAG,
" Scan Type: %s", this->
scan_active_ ?
"ACTIVE" :
"PASSIVE");
738 ESP_LOGCONFIG(TAG,
" Continuous Scanning: %s", YESNO(this->
scan_continuous_));
741 ESP_LOGCONFIG(TAG,
" Scanner State: IDLE");
744 ESP_LOGCONFIG(TAG,
" Scanner State: STARTING");
747 ESP_LOGCONFIG(TAG,
" Scanner State: RUNNING");
750 ESP_LOGCONFIG(TAG,
" Scanner State: STOPPING");
753 ESP_LOGCONFIG(TAG,
" Scanner State: STOPPED");
756 ESP_LOGCONFIG(TAG,
" Scanner State: FAILED");
759 ESP_LOGCONFIG(TAG,
" Connecting: %d, discovered: %d, searching: %d, disconnecting: %d",
connecting_,
discovered_,
772 this->already_discovered_.push_back(
address);
776 const char *address_type_s;
778 case BLE_ADDR_TYPE_PUBLIC:
779 address_type_s =
"PUBLIC";
781 case BLE_ADDR_TYPE_RANDOM:
782 address_type_s =
"RANDOM";
784 case BLE_ADDR_TYPE_RPA_PUBLIC:
785 address_type_s =
"RPA_PUBLIC";
787 case BLE_ADDR_TYPE_RPA_RANDOM:
788 address_type_s =
"RPA_RANDOM";
791 address_type_s =
"UNKNOWN";
795 ESP_LOGD(TAG,
" Address Type: %s", address_type_s);
797 ESP_LOGD(TAG,
" Name: '%s'", device.
get_name().c_str());
800 ESP_LOGD(TAG,
" TX Power: %d", tx_power);
806 uint8_t ecb_plaintext[16];
807 uint8_t ecb_ciphertext[16];
811 memcpy(&ecb_key, irk, 16);
812 memset(&ecb_plaintext, 0, 16);
814 ecb_plaintext[13] = (addr64 >> 40) & 0xff;
815 ecb_plaintext[14] = (addr64 >> 32) & 0xff;
816 ecb_plaintext[15] = (addr64 >> 24) & 0xff;
818 mbedtls_aes_context ctx = {0, 0, {0}};
819 mbedtls_aes_init(&ctx);
821 if (mbedtls_aes_setkey_enc(&ctx, ecb_key, 128) != 0) {
822 mbedtls_aes_free(&ctx);
826 if (mbedtls_aes_crypt_ecb(&ctx, ESP_AES_ENCRYPT, ecb_plaintext, ecb_ciphertext) != 0) {
827 mbedtls_aes_free(&ctx);
831 mbedtls_aes_free(&ctx);
833 return ecb_ciphertext[15] == (addr64 & 0xff) && ecb_ciphertext[14] == ((addr64 >> 8) & 0xff) &&
834 ecb_ciphertext[13] == ((addr64 >> 16) & 0xff);
virtual void mark_failed()
Mark this component as failed.
bool cancel_timeout(const std::string &name)
Cancel a timeout function.
void set_timeout(const std::string &name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
An STL allocator that uses SPI or internal RAM.
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
std::vector< uint64_t > already_discovered_
Vector of addresses that have already been printed in print_bt_device_info.
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
static const u_int8_t SCAN_RESULT_BUFFER_SIZE
float get_setup_priority() const override
void register_client(ESPBTClient *client)
bool parse_advertisements_
void dump_config() override
void recalculate_advertisement_parser_types()
esp_ble_gap_cb_param_t::ble_scan_result_evt_param * scan_result_buffer_
ScannerState scanner_state_
esp_ble_scan_params_t scan_params_
A structure holding the ESP BLE scan parameters.
void register_listener(ESPBTDeviceListener *listener)
void end_of_scan_()
Called when a scan ends.
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_
esp_bt_status_t scan_set_param_failed_
void ble_before_disabled_event_handler() override
size_t scan_result_index_
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_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.
SemaphoreHandle_t scan_result_lock_
std::vector< ESPBTClient * > clients_
Client parameters.
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.
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
void parse_scan_rst(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param ¶m)
esp_ble_addr_type_t address_type_
optional< uint16_t > appearance_
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
esp_ble_gap_cb_param_t::ble_scan_result_evt_param scan_result_
std::string address_str() const
bool resolve_irk(const uint8_t *irk) const
void parse_adv_(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param ¶m)
std::vector< int8_t > tx_powers_
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
uint64_t ble_addr_to_uint64(const esp_bd_addr_t address)
OTAGlobalCallback * get_global_ota_callback()
const float AFTER_BLUETOOTH
Providing packet encoding functions for exchanging data with a remote host.
Application App
Global storage of Application pointer - only one Application can exist.
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.