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_) {
76 if (!this->parent_->is_active()) {
99 ESP_LOGW(TAG,
"Scan timeout exceeded");
106 ESP_LOGE(TAG,
"Scan never terminated, rebooting");
140 ESP_LOGD(TAG,
"connecting: %d, discovered: %d, disconnecting: %d, active: %d",
142 this->client_state_counts_.disconnecting, this->client_state_counts_.active);
151#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
157 this->scan_params_.scan_window != this->desired_scan_window_(counts.
active)) {
182#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
202 (this->scanner_state_ == ScannerState::RUNNING || this->scanner_state_ == ScannerState::IDLE)) {
212 ESP_LOGV(TAG,
"Stopping scan.");
214#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
235 esp_err_t err = esp_ble_gap_stop_scanning();
237 ESP_LOGE(TAG,
"esp_ble_gap_stop_scanning failed: %d", err);
244 if (!this->parent_->is_active()) {
245 ESP_LOGW(TAG,
"Cannot start scan while ESP32BLE is disabled.");
253 ESP_LOGV(TAG,
"Starting scan, set scanner state to STARTING.");
256#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
259#ifdef USE_ESP32_BLE_DEVICE
263 this->
scan_params_.own_addr_type = BLE_ADDR_TYPE_PUBLIC;
264 this->
scan_params_.scan_filter_policy = BLE_SCAN_FILTER_ALLOW_ALL;
266#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
271 ESP_LOGV(TAG,
"Connection active, using %" PRIu32
" unit scan window", window);
284 esp_err_t err = esp_ble_gap_set_scan_params(&this->
scan_params_);
286 ESP_LOGE(TAG,
"esp_ble_gap_set_scan_params failed: %d", err);
291 ESP_LOGE(TAG,
"esp_ble_gap_start_scanning failed: %d", err);
297#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
311#ifdef ESPHOME_BLE_DEVICE_BASE_LISTENER_COUNT
319#ifdef ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT
330 case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT:
333 case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT:
336 case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT:
343#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
344 for (
auto *client : this->
clients_) {
345 client->gap_event_handler(event, param);
353 ESP_LOGVV(TAG,
"gap_scan_result - event %d", scan_result.search_evt);
355 if (scan_result.search_evt == ESP_GAP_SEARCH_INQ_RES_EVT) {
358 }
else if (scan_result.search_evt == ESP_GAP_SEARCH_INQ_CMPL_EVT) {
370 ESP_LOGV(TAG,
"gap_scan_set_param_complete - status %d", param.status);
371 if (param.status == ESP_BT_STATUS_DONE) {
380 ESP_LOGV(TAG,
"gap_scan_start_complete - status %d", param.status);
385 if (param.status == ESP_BT_STATUS_SUCCESS) {
399 ESP_LOGV(TAG,
"gap_scan_stop_complete - status %d", param.status);
409 esp_ble_gattc_cb_param_t *param) {
410#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
411 for (
auto *client : this->
clients_) {
412 client->gattc_event_handler(event, gattc_if, param);
420#ifdef USE_BLE_SCANNER_STATE_CALLBACK
428 ESP_LOGCONFIG(TAG,
"BLE Tracker:");
430 " Scan Duration: %" PRIu32
" s\n"
431 " Scan Interval: %.1f ms\n"
432 " Scan Window: %.1f ms\n"
434 " Continuous Scanning: %s",
437#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
443 " Scanner State: %s\n"
444 " Connecting: %d, discovered: %d, disconnecting: %d, active: %d",
446 this->client_state_counts_.discovered, this->client_state_counts_.disconnecting,
447 this->client_state_counts_.active);
453#ifdef USE_ESP32_BLE_DEVICE
469 adv.
data = scan_result.ble_adv;
470 adv.
data_len =
static_cast<uint16_t
>(scan_result.adv_data_len) + scan_result.scan_rsp_len;
471 adv.
rssi = scan_result.rssi;
472 adv.
addr_type = scan_result.ble_addr_type;
478#ifdef USE_ESP32_BLE_DEVICE
485#ifdef ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT
487 if (listener->parse_device(device))
491#ifdef ESPHOME_BLE_DEVICE_BASE_LISTENER_COUNT
493 if (listener->parse_device(device))
498#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
499 for (
auto *client : this->
clients_) {
500 if (client->parse_device(device)) {
514 ESP_LOGV(TAG,
"Scan %scomplete, set scanner state to IDLE.", is_stop_complete ?
"stop " :
"");
515#ifdef USE_ESP32_BLE_DEVICE
527#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
533#ifdef ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT
535 listener->on_scan_end();
537#ifdef ESPHOME_BLE_DEVICE_BASE_LISTENER_COUNT
539 listener->on_scan_end();
546 ESP_LOGE(TAG,
"Scan could not restart after %d attempts, rebooting to restore stack (IDF)",
547 std::numeric_limits<uint8_t>::max());
562#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
563 for (
auto *client : this->
clients_) {
564 if (client->state() != ClientState::DISCOVERED) {
569 ESP_LOGD(TAG,
"Stopping scan to make connection");
577 ESP_LOGD(TAG,
"Promoting client to connect");
580#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
591 case ScannerState::IDLE:
593 case ScannerState::STARTING:
595 case ScannerState::RUNNING:
597 case ScannerState::STOPPING:
599 case ScannerState::FAILED:
611#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
613#ifndef CONFIG_ESP_HOSTED_ENABLE_BT_BLUEDROID
615 ESP_LOGD(TAG,
"Setting coexistence to Bluetooth to make connection.");
617 esp_coex_preference_set(ESP_COEX_PREFER_BT);
619 ESP_LOGD(TAG,
"Setting coexistence preference to balanced.");
621 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