10#ifndef CONFIG_ESP_HOSTED_ENABLE_BT_BLUEDROID
13#include <esp_bt_defs.h>
14#include <esp_bt_main.h>
15#include <esp_gap_ble_api.h>
16#include <freertos/FreeRTOS.h>
17#include <freertos/FreeRTOSConfig.h>
18#include <freertos/task.h>
26#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
27#include <esp_coexist.h>
35static const char *
const TAG =
"esp32_ble_tracker";
42 if (this->parent_->is_failed()) {
44 ESP_LOGE(TAG,
"BLE Tracker was marked failed by ESP32BLE");
50#ifdef USE_OTA_STATE_LISTENER
55#ifdef USE_OTA_STATE_LISTENER
58 ESP_LOGD(TAG,
"Stopping scan for OTA");
61#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
62 for (
auto *client : this->
clients_) {
65#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
81 if (!this->parent_->is_active()) {
104 ESP_LOGW(TAG,
"Scan timeout exceeded");
111 ESP_LOGE(TAG,
"Scan never terminated, rebooting");
145 ESP_LOGD(TAG,
"connecting: %d, discovered: %d, disconnecting: %d, active: %d",
147 this->client_state_counts_.disconnecting, this->client_state_counts_.active);
156#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
162 this->scan_params_.scan_window != this->desired_scan_window_(counts.
active)) {
187#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
207 (this->scanner_state_ == ScannerState::RUNNING || this->scanner_state_ == ScannerState::IDLE)) {
217 ESP_LOGV(TAG,
"Stopping scan.");
219#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
231#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
232 for (
auto *client : this->
clients_) {
233 client->ble_before_disabled_event_handler();
260 esp_err_t err = esp_ble_gap_stop_scanning();
262 ESP_LOGE(TAG,
"esp_ble_gap_stop_scanning failed: %d", err);
269 if (!this->parent_->is_active()) {
270 ESP_LOGW(TAG,
"Cannot start scan while ESP32BLE is disabled.");
278 ESP_LOGV(TAG,
"Starting scan, set scanner state to STARTING.");
281#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
284#ifdef USE_ESP32_BLE_DEVICE
288 this->
scan_params_.own_addr_type = BLE_ADDR_TYPE_PUBLIC;
289 this->
scan_params_.scan_filter_policy = BLE_SCAN_FILTER_ALLOW_ALL;
291#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
296 ESP_LOGV(TAG,
"Connection active, using %" PRIu32
" unit scan window", window);
309 esp_err_t err = esp_ble_gap_set_scan_params(&this->
scan_params_);
311 ESP_LOGE(TAG,
"esp_ble_gap_set_scan_params failed: %d", err);
316 ESP_LOGE(TAG,
"esp_ble_gap_start_scanning failed: %d", err);
322#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
336#ifdef ESPHOME_BLE_DEVICE_BASE_LISTENER_COUNT
344#ifdef ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT
355 case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT:
358 case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT:
361 case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT:
368#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
369 for (
auto *client : this->
clients_) {
370 client->gap_event_handler(event, param);
378 ESP_LOGVV(TAG,
"gap_scan_result - event %d", scan_result.search_evt);
380 if (scan_result.search_evt == ESP_GAP_SEARCH_INQ_RES_EVT) {
383 }
else if (scan_result.search_evt == ESP_GAP_SEARCH_INQ_CMPL_EVT) {
395 ESP_LOGV(TAG,
"gap_scan_set_param_complete - status %d", param.status);
396 if (param.status == ESP_BT_STATUS_DONE) {
405 ESP_LOGV(TAG,
"gap_scan_start_complete - status %d", param.status);
410 if (param.status == ESP_BT_STATUS_SUCCESS) {
424 ESP_LOGV(TAG,
"gap_scan_stop_complete - status %d", param.status);
434 esp_ble_gattc_cb_param_t *param) {
435#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
436 for (
auto *client : this->
clients_) {
437 client->gattc_event_handler(event, gattc_if, param);
445#ifdef USE_BLE_SCANNER_STATE_CALLBACK
453 ESP_LOGCONFIG(TAG,
"BLE Tracker:");
455 " Scan Duration: %" PRIu32
" s\n"
456 " Scan Interval: %.1f ms\n"
457 " Scan Window: %.1f ms\n"
459 " Continuous Scanning: %s",
462#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
468 " Scanner State: %s\n"
469 " Connecting: %d, discovered: %d, disconnecting: %d, active: %d",
471 this->client_state_counts_.discovered, this->client_state_counts_.disconnecting,
472 this->client_state_counts_.active);
478#ifdef USE_ESP32_BLE_DEVICE
494 adv.
data = scan_result.ble_adv;
495 adv.
data_len =
static_cast<uint16_t
>(scan_result.adv_data_len) + scan_result.scan_rsp_len;
496 adv.
rssi = scan_result.rssi;
497 adv.
addr_type = scan_result.ble_addr_type;
503#ifdef USE_ESP32_BLE_DEVICE
510#ifdef ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT
512 if (listener->parse_device(device))
516#ifdef ESPHOME_BLE_DEVICE_BASE_LISTENER_COUNT
518 if (listener->parse_device(device))
523#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
524 for (
auto *client : this->
clients_) {
525 if (client->parse_device(device)) {
539 ESP_LOGV(TAG,
"Scan %scomplete, set scanner state to IDLE.", is_stop_complete ?
"stop " :
"");
540#ifdef USE_ESP32_BLE_DEVICE
552#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
558#ifdef ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT
560 listener->on_scan_end();
562#ifdef ESPHOME_BLE_DEVICE_BASE_LISTENER_COUNT
564 listener->on_scan_end();
571 ESP_LOGE(TAG,
"Scan could not restart after %d attempts, rebooting to restore stack (IDF)",
572 std::numeric_limits<uint8_t>::max());
587#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
588 for (
auto *client : this->
clients_) {
589 if (client->state() != ClientState::DISCOVERED) {
594 ESP_LOGD(TAG,
"Stopping scan to make connection");
602 ESP_LOGD(TAG,
"Promoting client to connect");
605#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
616 case ScannerState::IDLE:
618 case ScannerState::STARTING:
620 case ScannerState::RUNNING:
622 case ScannerState::STOPPING:
624 case ScannerState::FAILED:
636#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
638#ifndef CONFIG_ESP_HOSTED_ENABLE_BT_BLUEDROID
640 ESP_LOGD(TAG,
"Setting coexistence to Bluetooth to make connection.");
642 esp_coex_preference_set(ESP_COEX_PREFER_BT);
644 ESP_LOGD(TAG,
"Setting coexistence preference to balanced.");
646 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.
void mark_failed()
Mark this component as failed.
void clear()
Reset the per-period dedup list (call when a scan period ends).
void log_device(const char *tag, const ESPBTDevice &device)
Log the device at DEBUG the first time its MAC is seen this scan period.
void parse_scan_rst(const esp32_ble::BLEScanResult &scan_result)
Historical esp32 ingest (esp32 builds only): parse an ESP-IDF scan result.
void try_promote_discovered_clients_()
Try to promote discovered clients to ready to connect.
void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
uint8_t state_version_
Version counter for loop() fast-path optimization.
StaticVector< ESPBTClient *, ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT > clients_
void notify_scan_end_()
Fire on_scan_end on every listener unless a window-change restart suppressed it.
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.
ClientStateCounts count_client_states_() const
Count clients in each state.
ClientStateCounts client_state_counts_
ble_device_base::ScannerStateCallback scanner_state_callback_
uint8_t last_processed_version_
Last state_version_ value when loop() did full processing.
void gap_scan_event_handler(const BLEScanResult &scan_result)
float get_setup_priority() const override
void register_client(ESPBTClient *client)
bool parse_advertisements_
bool skip_next_scan_end_
Suppress the window-change restart's on_scan_end sweeps (stop and start).
void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param)
void dump_config() override
ble_device_base::RawAdvertisementCallback raw_advertisement_callback_
ScanTimeoutState scan_timeout_state_
uint32_t desired_scan_window_(uint8_t active) const
The window to scan at for the given number of active GATT connections.
ScannerState scanner_state_
esp_ble_scan_params_t scan_params_
A structure holding the ESP BLE scan parameters.
StaticVector< ESPBTDeviceListener *, ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT > listeners_
void register_listener(ESPBTDeviceListener *listener)
uint32_t scan_timeout_ms_
Precomputed timeout value: scan_duration_ * 2000.
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.
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.
bool scan_continuous_before_ota_
uint32_t scan_duration_
The interval in seconds to perform scans.
uint32_t connection_scan_window_
Window used while a GATT connection is active; set by the user, or defaulted when the window was rais...
void setup() override
Setup the FreeRTOS task and the Bluetooth stack.
void ble_before_disabled_event_handler()
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.
ble_device_base::DiscoveredDeviceLog discovered_log_
Per-period "Found device" DEBUG log with MAC dedup (shared ble_device_base impl)
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 print_bt_device_info(const ESPBTDevice &device)
StaticVector< ble_device_base::ESPBTDeviceListener *, ESPHOME_BLE_DEVICE_BASE_LISTENER_COUNT > neutral_listeners_
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.
bool stop_scan_()
Returns true when a stop was issued to the controller.
void on_ota_global_state(ota::OTAState state, float progress, uint8_t error, ota::OTAComponent *comp) override
void start_scan_(bool first)
Start a single scan by setting up the parameters and doing some esp-idf calls.
Base class for BLE GATT clients that connect to remote devices.
void set_tracker_state_version(uint8_t *version)
Called by ESP32BLETracker::register_client() to enable state change notifications.
virtual bool wants_parsed_advertisements()
False keeps the tracker from building parsed ESPBTDevice objects on this client's account (raw consum...
void set_parent(ESP32BLETracker *parent)
void add_global_state_listener(OTAGlobalStateListener *listener)
ScannerState
Scanner lifecycle, wire-value aligned with the api enum so consumers cast directly (pinned by static_...
ESP32BLETracker * global_esp32_ble_tracker
uint64_t ble_addr_to_uint64(const esp_bd_addr_t address)
OTAGlobalCallback * get_global_ota_callback()
constexpr float AFTER_BLUETOOTH
Application App
Global storage of Application pointer - only one Application can exist.
bool is_set() const
A default-constructed slot is "no subscriber"; hubs must guard on this.
void invoke(const RawAdvertisement &adv) const
One raw advertisement as delivered by the controller — a borrowed view, valid only for the duration o...
uint64_t address
Producers convert their native byte order at the emit site, so no byte-order convention crosses this ...
void invoke(ScannerState state) const