ESPHome 2026.2.1
Loading...
Searching...
No Matches
esp32_ble_tracker.h
Go to the documentation of this file.
1#pragma once
2
7
8#include <array>
9#include <span>
10#include <string>
11#include <vector>
12
13#ifdef USE_ESP32
14
15#include <esp_bt_defs.h>
16#include <esp_gap_ble_api.h>
17#include <esp_gattc_api.h>
18
19#include <freertos/FreeRTOS.h>
20#include <freertos/semphr.h>
21
25
26#ifdef USE_OTA_STATE_LISTENER
28#endif
29
31
32using namespace esp32_ble;
33
34using adv_data_t = std::vector<uint8_t>;
35
40
41#ifdef USE_ESP32_BLE_UUID
46#endif
47
48#ifdef USE_ESP32_BLE_DEVICE
50 public:
51 ESPBLEiBeacon() { memset(&this->beacon_data_, 0, sizeof(this->beacon_data_)); }
52 ESPBLEiBeacon(const uint8_t *data);
54
55 uint16_t get_major() { return byteswap(this->beacon_data_.major); }
56 uint16_t get_minor() { return byteswap(this->beacon_data_.minor); }
57 int8_t get_signal_power() { return this->beacon_data_.signal_power; }
58 ESPBTUUID get_uuid() { return ESPBTUUID::from_raw_reversed(this->beacon_data_.proximity_uuid); }
59
60 protected:
61 struct {
62 uint8_t sub_type;
63 uint8_t length;
64 uint8_t proximity_uuid[16];
65 uint16_t major;
66 uint16_t minor;
68 } PACKED beacon_data_;
69};
70
72 public:
73 void parse_scan_rst(const BLEScanResult &scan_result);
74
75 std::string address_str() const;
76
78 const char *address_str_to(std::span<char, MAC_ADDRESS_PRETTY_BUFFER_SIZE> buf) const {
79 format_mac_addr_upper(this->address_, buf.data());
80 return buf.data();
81 }
82
83 uint64_t address_uint64() const;
84
85 const uint8_t *address() const { return address_; }
86
87 esp_ble_addr_type_t get_address_type() const { return this->address_type_; }
88 int get_rssi() const { return rssi_; }
89 const std::string &get_name() const { return this->name_; }
90
91 const std::vector<int8_t> &get_tx_powers() const { return tx_powers_; }
92
94 const optional<uint8_t> &get_ad_flag() const { return ad_flag_; }
95 const std::vector<ESPBTUUID> &get_service_uuids() const { return service_uuids_; }
96
97 const std::vector<ServiceData> &get_manufacturer_datas() const { return manufacturer_datas_; }
98
99 const std::vector<ServiceData> &get_service_datas() const { return service_datas_; }
100
101 // Exposed through a function for use in lambdas
102 const BLEScanResult &get_scan_result() const { return *scan_result_; }
103
104 bool resolve_irk(const uint8_t *irk) const;
105
107 for (auto &it : this->manufacturer_datas_) {
109 if (res.has_value())
110 return *res;
111 }
112 return {};
113 }
114
115 protected:
116 void parse_adv_(const uint8_t *payload, uint8_t len);
117
118 esp_bd_addr_t address_{
119 0,
120 };
121 esp_ble_addr_type_t address_type_{BLE_ADDR_TYPE_PUBLIC};
122 int rssi_{0};
123 std::string name_{};
124 std::vector<int8_t> tx_powers_{};
127 std::vector<ESPBTUUID> service_uuids_{};
128 std::vector<ServiceData> manufacturer_datas_{};
129 std::vector<ServiceData> service_datas_{};
130 const BLEScanResult *scan_result_{nullptr};
131};
132#endif // USE_ESP32_BLE_DEVICE
133
134class ESP32BLETracker;
135
137 public:
138 virtual void on_scan_end() {}
139#ifdef USE_ESP32_BLE_DEVICE
140 virtual bool parse_device(const ESPBTDevice &device) = 0;
141#endif
142 virtual bool parse_devices(const BLEScanResult *scan_results, size_t count) { return false; };
146 void set_parent(ESP32BLETracker *parent) { parent_ = parent; }
147
148 protected:
150};
151
153 uint8_t connecting = 0;
154 uint8_t discovered = 0;
155 uint8_t disconnecting = 0;
156
157 bool operator==(const ClientStateCounts &other) const {
158 return connecting == other.connecting && discovered == other.discovered && disconnecting == other.disconnecting;
159 }
160
161 bool operator!=(const ClientStateCounts &other) const { return !(*this == other); }
162};
163
164enum class ClientState : uint8_t {
165 // Connection is allocated
166 INIT,
167 // Client is disconnecting
169 // Connection is idle, no device detected.
170 IDLE,
171 // Device advertisement found.
173 // Connection in progress.
175 // Initial connection established.
176 CONNECTED,
177 // The client and sub-clients have completed setup.
179};
180
181enum class ScannerState {
182 // Scanner is idle, init state
183 IDLE,
184 // Scanner is starting
185 STARTING,
186 // Scanner is running
187 RUNNING,
188 // Scanner failed to start
189 FAILED,
190 // Scanner is stopping
191 STOPPING,
192};
193
200 public:
202};
203
204// Helper function to convert ClientState to string
206
207enum class ConnectionType : uint8_t {
208 // The default connection type, we hold all the services in ram
209 // for the duration of the connection.
210 V1,
211 // The client has a cache of the services and mtu so we should not
212 // fetch them again
214 // The client does not need the services and mtu once we send them
215 // so we should wipe them from memory as soon as we send them
217};
218
233 public:
234 virtual bool gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
235 esp_ble_gattc_cb_param_t *param) = 0;
236 virtual void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) = 0;
237 virtual void connect() = 0;
238 virtual void disconnect() = 0;
239 bool disconnect_pending() const { return this->want_disconnect_; }
241
244 virtual void set_state(ClientState st) {
245 this->set_state_internal_(st);
246 if (st == ClientState::IDLE) {
247 this->want_disconnect_ = false;
248 }
249 }
250 ClientState state() const { return this->state_; }
251
255 void set_tracker_state_version(uint8_t *version) { this->tracker_state_version_ = version; }
256
257 // Memory optimized layout
258 uint8_t app_id; // App IDs are small integers assigned sequentially
259
260 protected:
265 this->state_ = st;
266 // Notify tracker that state changed (tracker_state_version_ is owned by ESP32BLETracker)
267 if (this->tracker_state_version_ != nullptr) {
268 (*this->tracker_state_version_)++;
269 }
270 }
271
272 // want_disconnect_ is set to true when a disconnect is requested
273 // while the client is connecting. This is used to disconnect the
274 // client as soon as we get the connection id (conn_id_) from the
275 // ESP_GATTC_OPEN_EVT event.
276 bool want_disconnect_{false};
277
278 private:
283 uint8_t *tracker_state_version_{nullptr};
284};
285
287 public GAPEventHandler,
288 public GAPScanEventHandler,
289 public GATTcEventHandler,
291#ifdef USE_OTA_STATE_LISTENER
293#endif
294 public Parented<ESP32BLE> {
295 public:
296 void set_scan_duration(uint32_t scan_duration) { scan_duration_ = scan_duration; }
297 void set_scan_interval(uint32_t scan_interval) { scan_interval_ = scan_interval; }
298 void set_scan_window(uint32_t scan_window) { scan_window_ = scan_window; }
299 void set_scan_active(bool scan_active) { scan_active_ = scan_active; }
300 bool get_scan_active() const { return scan_active_; }
301 void set_scan_continuous(bool scan_continuous) { scan_continuous_ = scan_continuous; }
302
304 void setup() override;
305 void dump_config() override;
306 float get_setup_priority() const override;
307
308 void loop() override;
309
311 void register_client(ESPBTClient *client);
313
314#ifdef USE_ESP32_BLE_DEVICE
315 void print_bt_device_info(const ESPBTDevice &device);
316#endif
317
318 void start_scan();
319 void stop_scan();
320
321 void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
322 esp_ble_gattc_cb_param_t *param) override;
323 void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) override;
324 void gap_scan_event_handler(const BLEScanResult &scan_result) override;
325 void ble_before_disabled_event_handler() override;
326
327#ifdef USE_OTA_STATE_LISTENER
328 void on_ota_global_state(ota::OTAState state, float progress, uint8_t error, ota::OTAComponent *comp) override;
329#endif
330
333 this->scanner_state_listeners_.push_back(listener);
334 }
336
337 protected:
338 void stop_scan_();
340 void start_scan_(bool first);
342 void gap_scan_result_(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param &param);
344 void gap_scan_set_param_complete_(const esp_ble_gap_cb_param_t::ble_scan_param_cmpl_evt_param &param);
346 void gap_scan_start_complete_(const esp_ble_gap_cb_param_t::ble_scan_start_cmpl_evt_param &param);
348 void gap_scan_stop_complete_(const esp_ble_gap_cb_param_t::ble_scan_stop_cmpl_evt_param &param);
352 void cleanup_scan_state_(bool is_stop_complete);
354 void process_scan_result_(const BLEScanResult &scan_result);
362 void log_unexpected_state_(const char *operation, ScannerState expected_state) const;
363#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
365 void update_coex_preference_(bool force_ble);
366#endif
369 ClientStateCounts counts;
370#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
371 for (auto *client : this->clients_) {
372 switch (client->state()) {
374 counts.disconnecting++;
375 break;
377 counts.discovered++;
378 break;
380 counts.connecting++;
381 break;
382 default:
383 break;
384 }
385 }
386#endif
387 return counts;
388 }
389
390 // Group 1: Large objects (12+ bytes) - vectors
391#ifdef ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT
393#endif
394#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
396#endif
397 std::vector<BLEScannerStateListener *> scanner_state_listeners_;
398#ifdef USE_ESP32_BLE_DEVICE
400 std::vector<uint64_t> already_discovered_;
401#endif
402
403 // Group 2: Structs (aligned to 4 bytes)
405 esp_ble_scan_params_t scan_params_;
407
408 // Group 3: 4-byte types
412 uint32_t scan_window_;
413 esp_bt_status_t scan_start_failed_{ESP_BT_STATUS_SUCCESS};
414 esp_bt_status_t scan_set_param_failed_{ESP_BT_STATUS_SUCCESS};
415
416 // Group 4: 1-byte types (enums, uint8_t, bool)
417 uint8_t app_id_{0};
425 uint8_t state_version_{0};
435#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
436 bool coex_prefer_ble_{false};
437#endif
438 // Scan timeout state machine
439 enum class ScanTimeoutState : uint8_t {
440 INACTIVE, // No timeout monitoring
441 MONITORING, // Actively monitoring for timeout
442 EXCEEDED_WAIT, // Timeout exceeded, waiting one loop before reboot
443 };
444 uint32_t scan_start_time_{0};
446 uint32_t scan_timeout_ms_{0};
448};
449
450// NOLINTNEXTLINE
451extern ESP32BLETracker *global_esp32_ble_tracker;
452
453} // namespace esphome::esp32_ble_tracker
454
455#endif
Helper class to easily give an object a parent of type T.
Definition helpers.h:1471
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:137
static ESPBTUUID from_raw_reversed(const uint8_t *data)
Definition ble_uuid.cpp:35
Listener interface for BLE scanner state changes.
virtual void on_scanner_state(ScannerState state)=0
void try_promote_discovered_clients_()
Try to promote discovered clients to ready to connect.
std::vector< uint64_t > already_discovered_
Vector of addresses that have already been printed in print_bt_device_info.
uint8_t state_version_
Version counter for loop() fast-path optimization.
StaticVector< ESPBTClient *, ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT > clients_
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.
void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) override
ClientStateCounts count_client_states_() const
Count clients in each state.
uint8_t last_processed_version_
Last state_version_ value when loop() did full processing.
std::vector< BLEScannerStateListener * > scanner_state_listeners_
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.
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.
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 set_scan_duration(uint32_t scan_duration)
void gap_scan_event_handler(const BLEScanResult &scan_result) override
void set_scan_interval(uint32_t scan_interval)
void add_scanner_state_listener(BLEScannerStateListener *listener)
Add a listener for scanner state changes.
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.
void on_ota_global_state(ota::OTAState state, float progress, uint8_t error, ota::OTAComponent *comp) override
void gap_scan_result_(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param &param)
Called when a ESP_GAP_BLE_SCAN_RESULT_EVT event is received.
void start_scan_(bool first)
Start a single scan by setting up the parameters and doing some esp-idf calls.
static optional< ESPBLEiBeacon > from_manufacturer_data(const ServiceData &data)
struct esphome::esp32_ble_tracker::ESPBLEiBeacon::@83 beacon_data_
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 void set_state(ClientState st)
Set the client state with IDLE handling (clears want_disconnect_).
virtual void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)=0
virtual bool gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param)=0
void set_state_internal_(ClientState st)
Set state without IDLE handling - use for direct state transitions.
const BLEScanResult & get_scan_result() const
esp_ble_addr_type_t get_address_type() const
void parse_adv_(const uint8_t *payload, uint8_t len)
void parse_scan_rst(const BLEScanResult &scan_result)
std::vector< ServiceData > manufacturer_datas_
const char * address_str_to(std::span< char, MAC_ADDRESS_PRETTY_BUFFER_SIZE > buf) const
Format MAC address into provided buffer, returns pointer to buffer for convenience.
const optional< uint8_t > & get_ad_flag() const
const std::vector< int8_t > & get_tx_powers() const
const std::vector< ServiceData > & get_service_datas() const
const optional< uint16_t > & get_appearance() const
const std::vector< ServiceData > & get_manufacturer_datas() const
bool resolve_irk(const uint8_t *irk) const
const std::vector< ESPBTUUID > & get_service_uuids() const
std::vector< ServiceData > service_datas_
optional< ESPBLEiBeacon > get_ibeacon() const
virtual AdvertisementParserType get_advertisement_parser_type()
virtual bool parse_device(const ESPBTDevice &device)=0
virtual bool parse_devices(const BLEScanResult *scan_results, size_t count)
Listener interface for global OTA state changes (includes OTA component pointer).
bool state
Definition fan.h:2
ESP32BLETracker * global_esp32_ble_tracker
std::vector< uint8_t > adv_data_t
const char * client_state_to_string(ClientState state)
std::string size_t len
Definition helpers.h:692
char * format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase, colon separators)
Definition helpers.h:1045
bool operator==(const ClientStateCounts &other) const
bool operator!=(const ClientStateCounts &other) const
void byteswap()