10#ifndef CONFIG_BT_CONTROLLER_DISABLED
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>
25#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
26#include <esp_coexist.h>
29#if defined(USE_WIFI_AP) && defined(USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW)
45 if (this->parent_->is_failed()) {
47 ESP_LOGE(TAG,
"BLE Tracker was marked failed by ESP32BLE");
53#ifdef USE_OTA_STATE_LISTENER
58#ifdef USE_OTA_STATE_LISTENER
61 ESP_LOGD(TAG,
"Stopping scan for OTA");
64#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
65 for (
auto *client : this->
clients_) {
68#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
84 if (!this->parent_->is_active()) {
87#if defined(USE_WIFI_AP) && defined(USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW)
116 ESP_LOGW(TAG,
"Scan timeout exceeded");
123 ESP_LOGE(TAG,
"Scan never terminated, rebooting");
158 ESP_LOGD(TAG,
"connecting: %d, discovered: %d, disconnecting: %d, active: %d",
160 this->client_state_counts_.disconnecting, this->client_state_counts_.active);
169#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
176 this->scan_params_.scan_window != this->desired_scan_window_(counts.
active)) {
201#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
231 ESP_LOGV(TAG,
"Stopping scan.");
233#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
245#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
246 for (
auto *client : this->
clients_) {
247 client->ble_before_disabled_event_handler();
250#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
276 esp_err_t err = esp_ble_gap_stop_scanning();
278 ESP_LOGE(TAG,
"esp_ble_gap_stop_scanning failed: %d", err);
285 if (!this->parent_->is_active()) {
286 ESP_LOGW(TAG,
"Cannot start scan while ESP32BLE is disabled.");
294 ESP_LOGV(TAG,
"Starting scan, set scanner state to STARTING.");
297#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
300#ifdef USE_ESP32_BLE_DEVICE
304 this->
scan_params_.own_addr_type = BLE_ADDR_TYPE_PUBLIC;
305 this->
scan_params_.scan_filter_policy = BLE_SCAN_FILTER_ALLOW_ALL;
307#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
312 ESP_LOGV(TAG,
"Connection or AP active, using %" PRIu32
" unit scan window", window);
325 esp_err_t err = esp_ble_gap_set_scan_params(&this->
scan_params_);
327 ESP_LOGE(TAG,
"esp_ble_gap_set_scan_params failed: %d", err);
332 ESP_LOGE(TAG,
"esp_ble_gap_start_scanning failed: %d", err);
338#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
352#ifdef ESPHOME_BLE_DEVICE_BASE_LISTENER_COUNT
360#ifdef ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT
371 case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT:
374 case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT:
377 case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT:
384#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
385 for (
auto *client : this->
clients_) {
386 client->gap_event_handler(event, param);
394 ESP_LOGVV(TAG,
"gap_scan_result - event %d", scan_result.search_evt);
396 if (scan_result.search_evt == ESP_GAP_SEARCH_INQ_RES_EVT) {
399 }
else if (scan_result.search_evt == ESP_GAP_SEARCH_INQ_CMPL_EVT) {
411 ESP_LOGV(TAG,
"gap_scan_set_param_complete - status %d", param.status);
412 if (param.status == ESP_BT_STATUS_DONE) {
421 ESP_LOGV(TAG,
"gap_scan_start_complete - status %d", param.status);
426 if (param.status == ESP_BT_STATUS_SUCCESS) {
440 ESP_LOGV(TAG,
"gap_scan_stop_complete - status %d", param.status);
450 esp_ble_gattc_cb_param_t *param) {
451#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
452 for (
auto *client : this->
clients_) {
453 client->gattc_event_handler(event, gattc_if, param);
461#ifdef USE_BLE_SCANNER_STATE_CALLBACK
469 ESP_LOGCONFIG(TAG,
"BLE Tracker:");
471 " Scan Duration: %" PRIu32
" s\n"
472 " Scan Interval: %.1f ms\n"
473 " Scan Window: %.1f ms\n"
475 " Continuous Scanning: %s",
478#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
484 " Scanner State: %s\n"
485 " Connecting: %d, discovered: %d, disconnecting: %d, active: %d",
487 this->client_state_counts_.discovered, this->client_state_counts_.disconnecting,
488 this->client_state_counts_.active);
494#ifdef USE_ESP32_BLE_DEVICE
510 adv.
data = scan_result.ble_adv;
511 adv.
data_len =
static_cast<uint16_t
>(scan_result.adv_data_len) + scan_result.scan_rsp_len;
512 adv.
rssi = scan_result.rssi;
513 adv.
addr_type = scan_result.ble_addr_type;
519#ifdef USE_ESP32_BLE_DEVICE
526#ifdef ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT
528 if (listener->parse_device(device))
532#ifdef ESPHOME_BLE_DEVICE_BASE_LISTENER_COUNT
534 if (listener->parse_device(device))
539#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
540 for (
auto *client : this->
clients_) {
541 if (client->parse_device(device)) {
555 ESP_LOGV(TAG,
"Scan %scomplete, set scanner state to IDLE.", is_stop_complete ?
"stop " :
"");
556#ifdef USE_ESP32_BLE_DEVICE
568#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
574#ifdef ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT
576 listener->on_scan_end();
578#ifdef ESPHOME_BLE_DEVICE_BASE_LISTENER_COUNT
580 listener->on_scan_end();
587 ESP_LOGE(TAG,
"Scan could not restart after %d attempts, rebooting to restore stack (IDF)",
588 std::numeric_limits<uint8_t>::max());
603#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
604 for (
auto *client : this->
clients_) {
610 ESP_LOGD(TAG,
"Stopping scan to make connection");
618 ESP_LOGD(TAG,
"Promoting client to connect");
619#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
623#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
654#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
656#ifndef CONFIG_BT_CONTROLLER_DISABLED
658 ESP_LOGD(TAG,
"Setting coexistence to Bluetooth to make connection.");
660 esp_coex_preference_set(ESP_COEX_PREFER_BT);
662 ESP_LOGD(TAG,
"Setting coexistence preference to balanced.");
664 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 and the last seen AP state.
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 or the wifi AP is active; set by the user, or defaulted when the ...
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.
bool ap_active_
Last seen wifi AP state, polled by loop(); stays false without an AP.
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)
bool is_ap_active() const
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)
ESPHOME_LOG_TAG(TAG, "esp32_ble")
OTAGlobalCallback * get_global_ota_callback()
constexpr float AFTER_BLUETOOTH
WiFiComponent * global_wifi_component
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