ESPHome 2025.9.0
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 <string>
10#include <vector>
11
12#ifdef USE_ESP32
13
14#include <esp_bt_defs.h>
15#include <esp_gap_ble_api.h>
16#include <esp_gattc_api.h>
17
18#include <freertos/FreeRTOS.h>
19#include <freertos/semphr.h>
20
24
26
27using namespace esp32_ble;
28
29using adv_data_t = std::vector<uint8_t>;
30
35
36#ifdef USE_ESP32_BLE_UUID
41#endif
42
43#ifdef USE_ESP32_BLE_DEVICE
45 public:
46 ESPBLEiBeacon() { memset(&this->beacon_data_, 0, sizeof(this->beacon_data_)); }
47 ESPBLEiBeacon(const uint8_t *data);
49
50 uint16_t get_major() { return byteswap(this->beacon_data_.major); }
51 uint16_t get_minor() { return byteswap(this->beacon_data_.minor); }
52 int8_t get_signal_power() { return this->beacon_data_.signal_power; }
53 ESPBTUUID get_uuid() { return ESPBTUUID::from_raw_reversed(this->beacon_data_.proximity_uuid); }
54
55 protected:
56 struct {
57 uint8_t sub_type;
58 uint8_t length;
59 uint8_t proximity_uuid[16];
60 uint16_t major;
61 uint16_t minor;
63 } PACKED beacon_data_;
64};
65
67 public:
68 void parse_scan_rst(const BLEScanResult &scan_result);
69
70 std::string address_str() const;
71
72 uint64_t address_uint64() const;
73
74 const uint8_t *address() const { return address_; }
75
76 esp_ble_addr_type_t get_address_type() const { return this->address_type_; }
77 int get_rssi() const { return rssi_; }
78 const std::string &get_name() const { return this->name_; }
79
80 const std::vector<int8_t> &get_tx_powers() const { return tx_powers_; }
81
83 const optional<uint8_t> &get_ad_flag() const { return ad_flag_; }
84 const std::vector<ESPBTUUID> &get_service_uuids() const { return service_uuids_; }
85
86 const std::vector<ServiceData> &get_manufacturer_datas() const { return manufacturer_datas_; }
87
88 const std::vector<ServiceData> &get_service_datas() const { return service_datas_; }
89
90 // Exposed through a function for use in lambdas
91 const BLEScanResult &get_scan_result() const { return *scan_result_; }
92
93 bool resolve_irk(const uint8_t *irk) const;
94
96 for (auto &it : this->manufacturer_datas_) {
98 if (res.has_value())
99 return *res;
100 }
101 return {};
102 }
103
104 protected:
105 void parse_adv_(const uint8_t *payload, uint8_t len);
106
107 esp_bd_addr_t address_{
108 0,
109 };
110 esp_ble_addr_type_t address_type_{BLE_ADDR_TYPE_PUBLIC};
111 int rssi_{0};
112 std::string name_{};
113 std::vector<int8_t> tx_powers_{};
116 std::vector<ESPBTUUID> service_uuids_{};
117 std::vector<ServiceData> manufacturer_datas_{};
118 std::vector<ServiceData> service_datas_{};
119 const BLEScanResult *scan_result_{nullptr};
120};
121#endif // USE_ESP32_BLE_DEVICE
122
123class ESP32BLETracker;
124
126 public:
127 virtual void on_scan_end() {}
128#ifdef USE_ESP32_BLE_DEVICE
129 virtual bool parse_device(const ESPBTDevice &device) = 0;
130#endif
131 virtual bool parse_devices(const BLEScanResult *scan_results, size_t count) { return false; };
135 void set_parent(ESP32BLETracker *parent) { parent_ = parent; }
136
137 protected:
139};
140
142 uint8_t connecting = 0;
143 uint8_t discovered = 0;
144 uint8_t disconnecting = 0;
145
146 bool operator==(const ClientStateCounts &other) const {
147 return connecting == other.connecting && discovered == other.discovered && disconnecting == other.disconnecting;
148 }
149
150 bool operator!=(const ClientStateCounts &other) const { return !(*this == other); }
151};
152
153enum class ClientState : uint8_t {
154 // Connection is allocated
155 INIT,
156 // Client is disconnecting
158 // Connection is idle, no device detected.
159 IDLE,
160 // Device advertisement found.
162 // Device is discovered and the scanner is stopped
164 // Connection in progress.
166 // Initial connection established.
167 CONNECTED,
168 // The client and sub-clients have completed setup.
170};
171
172enum class ScannerState {
173 // Scanner is idle, init state
174 IDLE,
175 // Scanner is starting
176 STARTING,
177 // Scanner is running
178 RUNNING,
179 // Scanner failed to start
180 FAILED,
181 // Scanner is stopping
182 STOPPING,
183};
184
185// Helper function to convert ClientState to string
187
188enum class ConnectionType : uint8_t {
189 // The default connection type, we hold all the services in ram
190 // for the duration of the connection.
191 V1,
192 // The client has a cache of the services and mtu so we should not
193 // fetch them again
195 // The client does not need the services and mtu once we send them
196 // so we should wipe them from memory as soon as we send them
198};
199
201 public:
202 virtual bool gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
203 esp_ble_gattc_cb_param_t *param) = 0;
204 virtual void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) = 0;
205 virtual void connect() = 0;
206 virtual void disconnect() = 0;
207 bool disconnect_pending() const { return this->want_disconnect_; }
209 virtual void set_state(ClientState st) {
210 this->state_ = st;
211 if (st == ClientState::IDLE) {
212 this->want_disconnect_ = false;
213 }
214 }
215 ClientState state() const { return state_; }
216
217 // Memory optimized layout
218 uint8_t app_id; // App IDs are small integers assigned sequentially
219
220 protected:
221 // Group 1: 1-byte types
223 // want_disconnect_ is set to true when a disconnect is requested
224 // while the client is connecting. This is used to disconnect the
225 // client as soon as we get the connection id (conn_id_) from the
226 // ESP_GATTC_OPEN_EVT event.
227 bool want_disconnect_{false};
228 // 2 bytes used, 2 bytes padding
229};
230
232 public GAPEventHandler,
233 public GAPScanEventHandler,
234 public GATTcEventHandler,
236 public Parented<ESP32BLE> {
237 public:
238 void set_scan_duration(uint32_t scan_duration) { scan_duration_ = scan_duration; }
239 void set_scan_interval(uint32_t scan_interval) { scan_interval_ = scan_interval; }
240 void set_scan_window(uint32_t scan_window) { scan_window_ = scan_window; }
241 void set_scan_active(bool scan_active) { scan_active_ = scan_active; }
242 bool get_scan_active() const { return scan_active_; }
243 void set_scan_continuous(bool scan_continuous) { scan_continuous_ = scan_continuous; }
244
246 void setup() override;
247 void dump_config() override;
248 float get_setup_priority() const override;
249
250 void loop() override;
251
253 void register_client(ESPBTClient *client);
255
256#ifdef USE_ESP32_BLE_DEVICE
257 void print_bt_device_info(const ESPBTDevice &device);
258#endif
259
260 void start_scan();
261 void stop_scan();
262
263 void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
264 esp_ble_gattc_cb_param_t *param) override;
265 void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) override;
266 void gap_scan_event_handler(const BLEScanResult &scan_result) override;
267 void ble_before_disabled_event_handler() override;
268
269 void add_scanner_state_callback(std::function<void(ScannerState)> &&callback) {
270 this->scanner_state_callbacks_.add(std::move(callback));
271 }
273
274 protected:
275 void stop_scan_();
277 void start_scan_(bool first);
279 void gap_scan_result_(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param &param);
281 void gap_scan_set_param_complete_(const esp_ble_gap_cb_param_t::ble_scan_param_cmpl_evt_param &param);
283 void gap_scan_start_complete_(const esp_ble_gap_cb_param_t::ble_scan_start_cmpl_evt_param &param);
285 void gap_scan_stop_complete_(const esp_ble_gap_cb_param_t::ble_scan_stop_cmpl_evt_param &param);
289 void cleanup_scan_state_(bool is_stop_complete);
291 void process_scan_result_(const BLEScanResult &scan_result);
299 void log_unexpected_state_(const char *operation, ScannerState expected_state) const;
300#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
302 void update_coex_preference_(bool force_ble);
303#endif
306 ClientStateCounts counts;
307 for (auto *client : this->clients_) {
308 switch (client->state()) {
310 counts.disconnecting++;
311 break;
313 counts.discovered++;
314 break;
317 counts.connecting++;
318 break;
319 default:
320 break;
321 }
322 }
323 return counts;
324 }
325
326 // Group 1: Large objects (12+ bytes) - vectors and callback manager
327 std::vector<ESPBTDeviceListener *> listeners_;
328 std::vector<ESPBTClient *> clients_;
330#ifdef USE_ESP32_BLE_DEVICE
332 std::vector<uint64_t> already_discovered_;
333#endif
334
335 // Group 2: Structs (aligned to 4 bytes)
337 esp_ble_scan_params_t scan_params_;
339
340 // Group 3: 4-byte types
344 uint32_t scan_window_;
345 esp_bt_status_t scan_start_failed_{ESP_BT_STATUS_SUCCESS};
346 esp_bt_status_t scan_set_param_failed_{ESP_BT_STATUS_SUCCESS};
347
348 // Group 4: 1-byte types (enums, uint8_t, bool)
349 uint8_t app_id_{0};
357#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
358 bool coex_prefer_ble_{false};
359#endif
360 // Scan timeout state machine
361 enum class ScanTimeoutState : uint8_t {
362 INACTIVE, // No timeout monitoring
363 MONITORING, // Actively monitoring for timeout
364 EXCEEDED_WAIT, // Timeout exceeded, waiting one loop before reboot
365 };
366 uint32_t scan_start_time_{0};
368};
369
370// NOLINTNEXTLINE
371extern ESP32BLETracker *global_esp32_ble_tracker;
372
373} // namespace esphome::esp32_ble_tracker
374
375#endif
Helper class to easily give an object a parent of type T.
Definition helpers.h:686
static ESPBTUUID from_raw_reversed(const uint8_t *data)
Definition ble_uuid.cpp:35
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.
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.
esp_ble_scan_params_t scan_params_
A structure holding the ESP BLE scan parameters.
void register_listener(ESPBTDeviceListener *listener)
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.
CallbackManager< void(ScannerState)> scanner_state_callbacks_
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 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 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 add_scanner_state_callback(std::function< void(ScannerState)> &&callback)
std::vector< ESPBTDeviceListener * > listeners_
void start_scan_(bool first)
Start a single scan by setting up the parameters and doing some esp-idf calls.
struct esphome::esp32_ble_tracker::ESPBLEiBeacon::@78 beacon_data_
static optional< ESPBLEiBeacon > from_manufacturer_data(const ServiceData &data)
virtual void set_state(ClientState st)
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
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 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)
bool state
Definition fan.h:0
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:280
bool operator==(const ClientStateCounts &other) const
bool operator!=(const ClientStateCounts &other) const
void byteswap()