ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
esp32_ble_tracker.cpp
Go to the documentation of this file.
1#ifdef USE_ESP32
2
3#include "esp32_ble_tracker.h"
6#include "esphome/core/hal.h"
8#include "esphome/core/log.h"
9
10#ifndef CONFIG_BT_CONTROLLER_DISABLED
11#include <esp_bt.h>
12#endif
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>
19#include <cinttypes>
20
21#ifdef USE_OTA
23#endif
24
25#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
26#include <esp_coexist.h>
27#endif
28
29#if defined(USE_WIFI_AP) && defined(USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW)
31#endif
32
33// bt_trace.h
34#undef TAG
35
37
38ESPHOME_LOG_TAG(TAG, "esp32_ble_tracker");
39
40ESP32BLETracker *global_esp32_ble_tracker = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
41
43
45 if (this->parent_->is_failed()) {
46 this->mark_failed();
47 ESP_LOGE(TAG, "BLE Tracker was marked failed by ESP32BLE");
48 return;
49 }
50
52
53#ifdef USE_OTA_STATE_LISTENER
55#endif
56}
57
58#ifdef USE_OTA_STATE_LISTENER
60 if (state == ota::OTA_STARTED) {
61 ESP_LOGD(TAG, "Stopping scan for OTA");
63 this->stop_scan();
64#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
65 for (auto *client : this->clients_) {
66 client->disconnect();
67 }
68#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
69 // The OTA transfer blocks the main loop, so the revert in loop() cannot run. No
70 // active-connection gate here: every client was just told to disconnect.
71 this->update_coex_preference_(false);
72#endif
73#endif
74 } else if ((state == ota::OTA_ERROR || state == ota::OTA_ABORT) && this->scan_continuous_before_ota_) {
75 this->scan_continuous_before_ota_ = false;
76 this->scan_continuous_ = true;
77 // Do not restart scanning immediately here; allow loop() to
78 // safely restart scanning once the scanner and all clients are idle.
79 }
80}
81#endif
82
84 if (!this->parent_->is_active()) {
85 return;
86 }
87#if defined(USE_WIFI_AP) && defined(USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW)
88 // The AP state is not versioned; fold its changes in so the window restart runs.
89 const bool ap_active = wifi::global_wifi_component->is_ap_active();
90 if (ap_active != this->ap_active_) {
91 this->ap_active_ = ap_active;
92 this->state_version_++;
93 }
94#endif
95
96 if (this->ble_was_disabled_) {
97 this->ble_was_disabled_ = false;
98 // First start after boot or after the stack came back.
99 if (this->scan_continuous_) {
100 this->start_scan();
101 }
102 }
103
104 // Check for scan timeout - moved here from scheduler to avoid false reboots
105 // when the loop is blocked. This must run every iteration for safety.
107 switch (this->scan_timeout_state_) {
109 // Robust time comparison that handles rollover correctly
110 // This works because unsigned arithmetic wraps around predictably
111 if ((App.get_loop_component_start_time() - this->scan_start_time_) > this->scan_timeout_ms_) {
112 // First time we've seen the timeout exceeded - wait one more loop iteration
113 // This ensures all components have had a chance to process pending events
114 // This is because esp32_ble may not have run yet and called
115 // gap_scan_event_handler yet when the loop unblocks
116 ESP_LOGW(TAG, "Scan timeout exceeded");
118 }
119 break;
120 }
122 // We've waited at least one full loop iteration, and scan is still running
123 ESP_LOGE(TAG, "Scan never terminated, rebooting");
124 App.reboot();
125 break;
127 break;
128 }
129 }
130
131 // Fast path: skip expensive client state counting and processing
132 // if no state has changed since last loop iteration.
133 //
134 // How state changes ensure we reach the code below:
135 // - handle_scanner_failure_(): scanner_state_ becomes FAILED via set_scanner_state_(), or
136 // scan_set_param_failed_ requires scanner_state_==RUNNING which can only be reached via
137 // set_scanner_state_(RUNNING) in gap_scan_start_complete_() (scan params are set during
138 // STARTING, not RUNNING, so version is always incremented before this condition is true)
139 // - start_scan_(): scanner_state_ becomes IDLE via set_scanner_state_() in cleanup_scan_state_()
140 // - try_promote_discovered_clients_(): client enters DISCOVERED via set_state(), or
141 // connecting client finishes (state change), or scanner reaches RUNNING/IDLE
142 // - short-window restart: scan_params_ is only written in start_scan_()
143 // (which changes scanner state via set_scanner_state_()),
144 // counts.active/disconnecting only change on client state changes, and
145 // ap_active_ changes bump state_version_ at the top of loop()
146 //
147 // All conditions that affect the logic below are tied to state changes that increment
148 // state_version_, so the fast path is safe.
149 if (this->state_version_ == this->last_processed_version_) {
150 return;
151 }
153
154 // State changed - do full processing
156 if (counts != this->client_state_counts_) {
157 this->client_state_counts_ = counts;
158 ESP_LOGD(TAG, "connecting: %d, discovered: %d, disconnecting: %d, active: %d",
159 this->client_state_counts_.connecting, this->client_state_counts_.discovered,
160 this->client_state_counts_.disconnecting, this->client_state_counts_.active);
161 }
162
163 // Scanner failure: reached when set_scanner_state_(FAILED) or scan_set_param_failed_ set
167 }
168
169#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
170 // The programmed window no longer matches the connection or AP state
171 // (typically the last connection dropped, or the AP started or stopped):
172 // restart so the right window applies now instead of at the end of the scan
173 // period. Continuous only (a user-started scan would not restart);
174 // !disconnecting matches the restart gate below.
175 if (this->scanner_state_ == ScannerState::RUNNING && this->scan_continuous_ && !counts.disconnecting &&
176 this->scan_params_.scan_window != this->desired_scan_window_(counts.active)) {
177 // Same logical scan period continues: no on_scan_end sweeps for this
178 // restart. Only armed when the stop was issued.
179 this->skip_next_scan_end_ = this->stop_scan_();
180 }
181#endif
182 /*
183
184 Avoid starting the scanner if:
185 - we are already scanning
186 - we are connecting to a device
187 - we are disconnecting from a device
188
189 Otherwise the scanner could fail to ever start again
190 and our only way to recover is to reboot.
191
192 https://github.com/espressif/esp-idf/issues/6688
193
194 */
195
196 // Start scan: reached when scanner_state_ becomes IDLE (via set_scanner_state_()) and
197 // no clients are in the transient CONNECTING / DISCOVERED / DISCONNECTING states
198 // (their state changes increment version when they finish). CONNECTED / ESTABLISHED
199 // clients do NOT block this branch — the coex revert below has its own active-count gate.
200 if (this->scanner_state_ == ScannerState::IDLE && !counts.connecting && !counts.disconnecting && !counts.discovered) {
201#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
202 // Only revert to BALANCE when no connections are active. Established connections
203 // continue to need PREFER_BT so peer GATT responses can reach us while WiFi traffic
204 // (advertisement upload, log streaming) competes for the shared radio. Reverting too
205 // early causes Bluedroid to time out at ~20s and synthesize status=133.
206 if (!counts.active) {
207 this->update_coex_preference_(false);
208 }
209#endif
210 if (this->scan_continuous_) {
211 this->start_scan_(false); // first = false
212 }
213 }
214 // Promote discovered clients: reached when a client's state becomes DISCOVERED (via set_state()),
215 // or when a blocking condition clears (connecting client finishes, scanner reaches RUNNING/IDLE).
216 // All these trigger state_version_ increment, so we'll process and check promotion eligibility.
217 // We check both RUNNING and IDLE states because:
218 // - RUNNING: gap_scan_event_handler initiates stop_scan_() but promotion can happen immediately
219 // - IDLE: Scanner has already stopped (naturally or by gap_scan_event_handler)
220 if (counts.discovered && !counts.connecting &&
221 (this->scanner_state_ == ScannerState::RUNNING || this->scanner_state_ == ScannerState::IDLE)) {
223 }
224}
225
227
229 // V to match the start log: the mode-switch and OTA callers narrate their
230 // reason at D themselves, and the user-facing stop action is deliberate.
231 ESP_LOGV(TAG, "Stopping scan.");
232 this->scan_continuous_ = false;
233#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
234 // The window-change restart is abandoned with continuous scanning.
235 this->skip_next_scan_end_ = false;
236#endif
237 this->stop_scan_();
238}
239
241 // Tell the controller to stop; a scan still starting has nothing to stop yet.
243 this->stop_scan_();
244 }
245#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
246 for (auto *client : this->clients_) {
247 client->ble_before_disabled_event_handler();
248 }
249#endif
250#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
251 this->skip_next_scan_end_ = false;
252#endif
253 // The stop above never completes (stack torn down, events dropped); settle
254 // here so start_scan_() sees IDLE once the stack is back.
255 if (this->scanner_state_ != ScannerState::IDLE) {
256 this->cleanup_scan_state_(true);
257 }
258 // A failure latched by the old stack must not be handled against the next.
259 this->scan_start_failed_ = ESP_BT_STATUS_SUCCESS;
260 this->scan_set_param_failed_ = ESP_BT_STATUS_SUCCESS;
261 this->ble_was_disabled_ = true;
262}
263
266 // IDLE means there is nothing to stop; STOPPING means a stop is already in
267 // flight and will finish on its own. Neither is an error.
269 ESP_LOGE(TAG, "Cannot stop scan: %s", this->scanner_state_to_string_(this->scanner_state_));
270 }
271 return false;
272 }
273 // Reset timeout state machine when stopping scan
276 esp_err_t err = esp_ble_gap_stop_scanning();
277 if (err != ESP_OK) {
278 ESP_LOGE(TAG, "esp_ble_gap_stop_scanning failed: %d", err);
279 return false;
280 }
281 return true;
282}
283
285 if (!this->parent_->is_active()) {
286 ESP_LOGW(TAG, "Cannot start scan while ESP32BLE is disabled.");
287 return;
288 }
289 if (this->scanner_state_ != ScannerState::IDLE) {
290 this->log_unexpected_state_("start scan", ScannerState::IDLE);
291 return;
292 }
294 ESP_LOGV(TAG, "Starting scan, set scanner state to STARTING.");
295 if (!first)
296 this->notify_scan_end_();
297#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
298 this->skip_next_scan_end_ = false;
299#endif
300#ifdef USE_ESP32_BLE_DEVICE
301 this->discovered_log_.clear();
302#endif
303 this->scan_params_.scan_type = this->scan_active_ ? BLE_SCAN_TYPE_ACTIVE : BLE_SCAN_TYPE_PASSIVE;
304 this->scan_params_.own_addr_type = BLE_ADDR_TYPE_PUBLIC;
305 this->scan_params_.scan_filter_policy = BLE_SCAN_FILTER_ALLOW_ALL;
306 this->scan_params_.scan_interval = this->scan_interval_;
307#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
308 // Count fresh: an automation can start a scan before loop() refreshes the counts.
309 const uint32_t window = this->desired_scan_window_(this->count_client_states_().active);
310 if (window != this->scan_window_) {
311 // Leave airtime for the connection or the AP instead of scanning wall to wall.
312 ESP_LOGV(TAG, "Connection or AP active, using %" PRIu32 " unit scan window", window);
313 }
314#else
315 const uint32_t window = this->scan_window_;
316#endif
317 this->scan_params_.scan_window = window;
318
319 // Start timeout monitoring in loop() instead of using scheduler
320 // This prevents false reboots when the loop is blocked
322 this->scan_timeout_ms_ = this->scan_duration_ * 2000;
324
325 esp_err_t err = esp_ble_gap_set_scan_params(&this->scan_params_);
326 if (err != ESP_OK) {
327 ESP_LOGE(TAG, "esp_ble_gap_set_scan_params failed: %d", err);
328 return;
329 }
330 err = esp_ble_gap_start_scanning(this->scan_duration_);
331 if (err != ESP_OK) {
332 ESP_LOGE(TAG, "esp_ble_gap_start_scanning failed: %d", err);
333 return;
334 }
335}
336
338#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
339 client->app_id = ++this->app_id_;
340 // Give client a pointer to our state_version_ so it can notify us of state changes.
341 // This enables loop() fast-path optimization - we skip expensive work when no state changed.
342 // Safe because ESP32BLETracker (singleton) outlives all registered clients.
344 this->clients_.push_back(client);
345 // Registration is add-only, so the flag is a monotonic OR.
346 if (client->wants_parsed_advertisements())
347 this->parse_advertisements_ = true;
348#endif
349}
350
352#ifdef ESPHOME_BLE_DEVICE_BASE_LISTENER_COUNT
353 // Neutral BLEHub path (migrated sensors): parsed-advertisement consumers only.
354 this->neutral_listeners_.push_back(listener);
355 this->parse_advertisements_ = true;
356#endif
357}
358
360#ifdef ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT
361 listener->set_parent(this);
362 this->listeners_.push_back(listener);
363 this->parse_advertisements_ = true;
364#endif
365}
366
367void ESP32BLETracker::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
368 // Note: This handler is called from the main loop context, not directly from the BT task.
369 // The esp32_ble component queues events via enqueue_ble_event() and processes them in loop().
370 switch (event) {
371 case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT:
372 this->gap_scan_set_param_complete_(param->scan_param_cmpl);
373 break;
374 case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT:
375 this->gap_scan_start_complete_(param->scan_start_cmpl);
376 break;
377 case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT:
378 this->gap_scan_stop_complete_(param->scan_stop_cmpl);
379 break;
380 default:
381 break;
382 }
383 // Forward all events to clients (scan results are handled separately via gap_scan_event_handler)
384#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
385 for (auto *client : this->clients_) {
386 client->gap_event_handler(event, param);
387 }
388#endif
389}
390
391void ESP32BLETracker::gap_scan_event_handler(const BLEScanResult &scan_result) {
392 // Note: This handler is called from the main loop context via esp32_ble's event queue.
393 // We process advertisements immediately instead of buffering them.
394 ESP_LOGVV(TAG, "gap_scan_result - event %d", scan_result.search_evt);
395
396 if (scan_result.search_evt == ESP_GAP_SEARCH_INQ_RES_EVT) {
397 // Process the scan result immediately
398 this->process_scan_result_(scan_result);
399 } else if (scan_result.search_evt == ESP_GAP_SEARCH_INQ_CMPL_EVT) {
400 // Scan finished on its own
402 this->log_unexpected_state_("scan complete", ScannerState::RUNNING);
403 }
404 // Scan completed naturally, perform cleanup and transition to IDLE
405 this->cleanup_scan_state_(false);
406 }
407}
408
409void ESP32BLETracker::gap_scan_set_param_complete_(const esp_ble_gap_cb_param_t::ble_scan_param_cmpl_evt_param &param) {
410 // Called from main loop context via gap_event_handler after being queued from BT task
411 ESP_LOGV(TAG, "gap_scan_set_param_complete - status %d", param.status);
412 if (param.status == ESP_BT_STATUS_DONE) {
413 this->scan_set_param_failed_ = ESP_BT_STATUS_SUCCESS;
414 } else {
415 this->scan_set_param_failed_ = param.status;
416 }
417}
418
419void ESP32BLETracker::gap_scan_start_complete_(const esp_ble_gap_cb_param_t::ble_scan_start_cmpl_evt_param &param) {
420 // Called from main loop context via gap_event_handler after being queued from BT task
421 ESP_LOGV(TAG, "gap_scan_start_complete - status %d", param.status);
422 this->scan_start_failed_ = param.status;
424 this->log_unexpected_state_("start complete", ScannerState::STARTING);
425 }
426 if (param.status == ESP_BT_STATUS_SUCCESS) {
427 this->scan_start_fail_count_ = 0;
429 } else {
431 if (this->scan_start_fail_count_ != std::numeric_limits<uint8_t>::max()) {
433 }
434 }
435}
436
437void ESP32BLETracker::gap_scan_stop_complete_(const esp_ble_gap_cb_param_t::ble_scan_stop_cmpl_evt_param &param) {
438 // Called from main loop context via gap_event_handler after being queued from BT task
439 // This allows us to safely transition to IDLE state and perform cleanup without race conditions
440 ESP_LOGV(TAG, "gap_scan_stop_complete - status %d", param.status);
442 this->log_unexpected_state_("stop complete", ScannerState::STOPPING);
443 }
444
445 // Perform cleanup and transition to IDLE
446 this->cleanup_scan_state_(true);
447}
448
449void ESP32BLETracker::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
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);
454 }
455#endif
456}
457
459 this->scanner_state_ = state;
460 this->state_version_++;
461#ifdef USE_BLE_SCANNER_STATE_CALLBACK
462 if (this->scanner_state_callback_.is_set()) {
463 this->scanner_state_callback_.invoke(state);
464 }
465#endif
466}
467
469 ESP_LOGCONFIG(TAG, "BLE Tracker:");
470 ESP_LOGCONFIG(TAG,
471 " Scan Duration: %" PRIu32 " s\n"
472 " Scan Interval: %.1f ms\n"
473 " Scan Window: %.1f ms\n"
474 " Scan Type: %s\n"
475 " Continuous Scanning: %s",
476 this->scan_duration_, this->scan_interval_ * 0.625f, this->scan_window_ * 0.625f,
477 this->scan_active_ ? "ACTIVE" : "PASSIVE", YESNO(this->scan_continuous_));
478#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
479 if (this->connection_scan_window_ != 0) {
480 ESP_LOGCONFIG(TAG, " Connection Scan Window: %.1f ms", this->connection_scan_window_ * 0.625f);
481 }
482#endif
483 ESP_LOGCONFIG(TAG,
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);
489 if (this->scan_start_fail_count_) {
490 ESP_LOGCONFIG(TAG, " Scan Start Fail Count: %d", this->scan_start_fail_count_);
491 }
492}
493
494#ifdef USE_ESP32_BLE_DEVICE
496 // Shared implementation in ble_device_base — identical output and per-period
497 // MAC dedup on every tracker backend.
498 this->discovered_log_.log_device(TAG, device);
499}
500
501// resolve_irk() is provided by ble_device_base (portable software AES).
502
503#endif // USE_ESP32_BLE_DEVICE
504
505void ESP32BLETracker::process_scan_result_(const BLEScanResult &scan_result) {
506 // Neutral raw-advertisement subscriber (the bluetooth_proxy path).
509 adv.address = esp32_ble::ble_addr_to_uint64(scan_result.bda);
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;
515 }
516
517 // Process parsed advertisements
518 if (this->parse_advertisements_) {
519#ifdef USE_ESP32_BLE_DEVICE
520 ESPBTDevice device;
521 // The historical ingest keeps the raw scan-result fields populated for
522 // external components.
523 device.parse_scan_rst(scan_result);
524
525 bool found = false;
526#ifdef ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT
527 for (auto *listener : this->listeners_) {
528 if (listener->parse_device(device))
529 found = true;
530 }
531#endif
532#ifdef ESPHOME_BLE_DEVICE_BASE_LISTENER_COUNT
533 for (auto *listener : this->neutral_listeners_) {
534 if (listener->parse_device(device))
535 found = true;
536 }
537#endif
538
539#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
540 for (auto *client : this->clients_) {
541 if (client->parse_device(device)) {
542 found = true;
543 }
544 }
545#endif
546
547 if (!found && !this->scan_continuous_) {
548 this->print_bt_device_info(device);
549 }
550#endif // USE_ESP32_BLE_DEVICE
551 }
552}
553
554void ESP32BLETracker::cleanup_scan_state_(bool is_stop_complete) {
555 ESP_LOGV(TAG, "Scan %scomplete, set scanner state to IDLE.", is_stop_complete ? "stop " : "");
556#ifdef USE_ESP32_BLE_DEVICE
557 this->discovered_log_.clear();
558#endif
559 // Reset timeout state machine instead of cancelling scheduler timeout
561
562 this->notify_scan_end_();
563
565}
566
568#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
569 // Window-change restart continues the same scan period; the flag stays set
570 // across the stop and is cleared by the restart in start_scan_.
571 if (this->skip_next_scan_end_)
572 return;
573#endif
574#ifdef ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT
575 for (auto *listener : this->listeners_)
576 listener->on_scan_end();
577#endif
578#ifdef ESPHOME_BLE_DEVICE_BASE_LISTENER_COUNT
579 for (auto *listener : this->neutral_listeners_)
580 listener->on_scan_end();
581#endif
582}
583
585 this->stop_scan_();
586 if (this->scan_start_fail_count_ == std::numeric_limits<uint8_t>::max()) {
587 ESP_LOGE(TAG, "Scan could not restart after %d attempts, rebooting to restore stack (IDF)",
588 std::numeric_limits<uint8_t>::max());
589 App.reboot();
590 }
591 if (this->scan_start_failed_) {
592 ESP_LOGE(TAG, "Scan start failed: %d", this->scan_start_failed_);
593 this->scan_start_failed_ = ESP_BT_STATUS_SUCCESS;
594 }
595 if (this->scan_set_param_failed_) {
596 ESP_LOGE(TAG, "Scan set param failed: %d", this->scan_set_param_failed_);
597 this->scan_set_param_failed_ = ESP_BT_STATUS_SUCCESS;
598 }
599}
600
602 // Only promote the first discovered client to avoid multiple simultaneous connections
603#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
604 for (auto *client : this->clients_) {
605 if (client->state() != ClientState::DISCOVERED) {
606 continue;
607 }
608
610 ESP_LOGD(TAG, "Stopping scan to make connection");
611 this->stop_scan_();
612 // Don't wait for scan stop complete - promote immediately.
613 // This is safe because ESP-IDF processes BLE commands sequentially through its internal mailbox queue.
614 // This guarantees that the stop scan command will be fully processed before any subsequent connect command,
615 // preventing race conditions or overlapping operations.
616 }
617
618 ESP_LOGD(TAG, "Promoting client to connect");
619#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
620 // A connect ends the scan period a window-change restart was continuing.
621 this->skip_next_scan_end_ = false;
622#endif
623#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
624 this->update_coex_preference_(true);
625#endif
626 client->connect();
627 break;
628 }
629#endif
630}
631
633 switch (state) {
635 return "IDLE";
637 return "STARTING";
639 return "RUNNING";
641 return "STOPPING";
643 return "FAILED";
644 default:
645 return "UNKNOWN";
646 }
647}
648
649void ESP32BLETracker::log_unexpected_state_(const char *operation, ScannerState expected_state) const {
650 ESP_LOGE(TAG, "Unexpected state: %s on %s, expected: %s", this->scanner_state_to_string_(this->scanner_state_),
651 operation, this->scanner_state_to_string_(expected_state));
652}
653
654#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
656#ifndef CONFIG_BT_CONTROLLER_DISABLED
657 if (force_ble && !this->coex_prefer_ble_) {
658 ESP_LOGD(TAG, "Setting coexistence to Bluetooth to make connection.");
659 this->coex_prefer_ble_ = true;
660 esp_coex_preference_set(ESP_COEX_PREFER_BT); // Prioritize Bluetooth
661 } else if (!force_ble && this->coex_prefer_ble_) {
662 ESP_LOGD(TAG, "Setting coexistence preference to balanced.");
663 this->coex_prefer_ble_ = false;
664 esp_coex_preference_set(ESP_COEX_PREFER_BALANCE); // Reset to default
665 }
666#endif // CONFIG_BT_CONTROLLER_DISABLED
667}
668#endif
669
670} // namespace esphome::esp32_ble_tracker
671
672#endif // USE_ESP32
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).
Definition ble_device.h:274
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.
void gap_scan_stop_complete_(const esp_ble_gap_cb_param_t::ble_scan_stop_cmpl_evt_param &param)
Called when a ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT event is received.
ClientStateCounts count_client_states_() const
Count clients in each state.
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)
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)
ble_device_base::RawAdvertisementCallback raw_advertisement_callback_
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.
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 &param)
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.
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 handle_scanner_failure_()
Handle scanner failure states.
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 &param)
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 add_global_state_listener(OTAGlobalStateListener *listener)
bool state
Definition fan.h:2
ScannerState
Scanner lifecycle, wire-value aligned with the api enum so consumers cast directly (pinned by static_...
Definition ble_hub.h:53
ESP32BLETracker * global_esp32_ble_tracker
uint64_t ble_addr_to_uint64(const esp_bd_addr_t address)
Definition ble.h:38
ESPHOME_LOG_TAG(TAG, "esp32_ble")
OTAGlobalCallback * get_global_ota_callback()
constexpr float AFTER_BLUETOOTH
Definition component.h:49
WiFiComponent * global_wifi_component
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
bool is_set() const
A default-constructed slot is "no subscriber"; hubs must guard on this.
Definition ble_hub.h:47
void invoke(const RawAdvertisement &adv) const
Definition ble_hub.h:48
One raw advertisement as delivered by the controller — a borrowed view, valid only for the duration o...
Definition ble_hub.h:24
uint64_t address
Producers convert their native byte order at the emit site, so no byte-order convention crosses this ...
Definition ble_hub.h:27
void invoke(ScannerState state) const
Definition ble_hub.h:69