ESPHome 2025.6.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 <atomic>
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
24
25namespace esphome {
26namespace esp32_ble_tracker {
27
28using namespace esp32_ble;
29
30using adv_data_t = std::vector<uint8_t>;
31
36
41
43 public:
44 ESPBLEiBeacon() { memset(&this->beacon_data_, 0, sizeof(this->beacon_data_)); }
45 ESPBLEiBeacon(const uint8_t *data);
47
48 uint16_t get_major() { return byteswap(this->beacon_data_.major); }
49 uint16_t get_minor() { return byteswap(this->beacon_data_.minor); }
50 int8_t get_signal_power() { return this->beacon_data_.signal_power; }
51 ESPBTUUID get_uuid() { return ESPBTUUID::from_raw_reversed(this->beacon_data_.proximity_uuid); }
52
53 protected:
54 struct {
55 uint8_t sub_type;
56 uint8_t length;
57 uint8_t proximity_uuid[16];
58 uint16_t major;
59 uint16_t minor;
61 } PACKED beacon_data_;
62};
63
65 public:
66 void parse_scan_rst(const BLEScanResult &scan_result);
67
68 std::string address_str() const;
69
70 uint64_t address_uint64() const;
71
72 const uint8_t *address() const { return address_; }
73
74 esp_ble_addr_type_t get_address_type() const { return this->address_type_; }
75 int get_rssi() const { return rssi_; }
76 const std::string &get_name() const { return this->name_; }
77
78 const std::vector<int8_t> &get_tx_powers() const { return tx_powers_; }
79
81 const optional<uint8_t> &get_ad_flag() const { return ad_flag_; }
82 const std::vector<ESPBTUUID> &get_service_uuids() const { return service_uuids_; }
83
84 const std::vector<ServiceData> &get_manufacturer_datas() const { return manufacturer_datas_; }
85
86 const std::vector<ServiceData> &get_service_datas() const { return service_datas_; }
87
88 bool resolve_irk(const uint8_t *irk) const;
89
91 for (auto &it : this->manufacturer_datas_) {
93 if (res.has_value())
94 return *res;
95 }
96 return {};
97 }
98
99 protected:
100 void parse_adv_(const uint8_t *payload, uint8_t len);
101
102 esp_bd_addr_t address_{
103 0,
104 };
105 esp_ble_addr_type_t address_type_{BLE_ADDR_TYPE_PUBLIC};
106 int rssi_{0};
107 std::string name_{};
108 std::vector<int8_t> tx_powers_{};
111 std::vector<ESPBTUUID> service_uuids_{};
112 std::vector<ServiceData> manufacturer_datas_{};
113 std::vector<ServiceData> service_datas_{};
114};
115
116class ESP32BLETracker;
117
119 public:
120 virtual void on_scan_end() {}
121 virtual bool parse_device(const ESPBTDevice &device) = 0;
122 virtual bool parse_devices(const BLEScanResult *scan_results, size_t count) { return false; };
126 void set_parent(ESP32BLETracker *parent) { parent_ = parent; }
127
128 protected:
130};
131
132enum class ClientState {
133 // Connection is allocated
134 INIT,
135 // Client is disconnecting
137 // Connection is idle, no device detected.
138 IDLE,
139 // Searching for device.
140 SEARCHING,
141 // Device advertisement found.
143 // Device is discovered and the scanner is stopped
145 // Connection in progress.
147 // Initial connection established.
148 CONNECTED,
149 // The client and sub-clients have completed setup.
151};
152
153enum class ScannerState {
154 // Scanner is idle, init state, set from the main loop when processing STOPPED
155 IDLE,
156 // Scanner is starting, set from the main loop only
157 STARTING,
158 // Scanner is running, set from the ESP callback only
159 RUNNING,
160 // Scanner failed to start, set from the ESP callback only
161 FAILED,
162 // Scanner is stopping, set from the main loop only
163 STOPPING,
164 // Scanner is stopped, set from the ESP callback only
165 STOPPED,
166};
167
168enum class ConnectionType {
169 // The default connection type, we hold all the services in ram
170 // for the duration of the connection.
171 V1,
172 // The client has a cache of the services and mtu so we should not
173 // fetch them again
175 // The client does not need the services and mtu once we send them
176 // so we should wipe them from memory as soon as we send them
178};
179
181 public:
182 virtual bool gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
183 esp_ble_gattc_cb_param_t *param) = 0;
184 virtual void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) = 0;
185 virtual void connect() = 0;
186 virtual void disconnect() = 0;
187 bool disconnect_pending() const { return this->want_disconnect_; }
189 virtual void set_state(ClientState st) {
190 this->state_ = st;
191 if (st == ClientState::IDLE) {
192 this->want_disconnect_ = false;
193 }
194 }
195 ClientState state() const { return state_; }
197
198 protected:
200 // want_disconnect_ is set to true when a disconnect is requested
201 // while the client is connecting. This is used to disconnect the
202 // client as soon as we get the connection id (conn_id_) from the
203 // ESP_GATTC_OPEN_EVT event.
204 bool want_disconnect_{false};
205};
206
208 public GAPEventHandler,
209 public GAPScanEventHandler,
210 public GATTcEventHandler,
212 public Parented<ESP32BLE> {
213 public:
214 void set_scan_duration(uint32_t scan_duration) { scan_duration_ = scan_duration; }
215 void set_scan_interval(uint32_t scan_interval) { scan_interval_ = scan_interval; }
216 void set_scan_window(uint32_t scan_window) { scan_window_ = scan_window; }
217 void set_scan_active(bool scan_active) { scan_active_ = scan_active; }
218 bool get_scan_active() const { return scan_active_; }
219 void set_scan_continuous(bool scan_continuous) { scan_continuous_ = scan_continuous; }
220
222 void setup() override;
223 void dump_config() override;
224 float get_setup_priority() const override;
225
226 void loop() override;
227
229 void register_client(ESPBTClient *client);
231
232 void print_bt_device_info(const ESPBTDevice &device);
233
234 void start_scan();
235 void stop_scan();
236
237 void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
238 esp_ble_gattc_cb_param_t *param) override;
239 void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) override;
240 void gap_scan_event_handler(const BLEScanResult &scan_result) override;
241 void ble_before_disabled_event_handler() override;
242
243 void add_scanner_state_callback(std::function<void(ScannerState)> &&callback) {
244 this->scanner_state_callbacks_.add(std::move(callback));
245 }
247
248 protected:
249 void stop_scan_();
251 void start_scan_(bool first);
253 void end_of_scan_();
255 void gap_scan_result_(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param &param);
257 void gap_scan_set_param_complete_(const esp_ble_gap_cb_param_t::ble_scan_param_cmpl_evt_param &param);
259 void gap_scan_start_complete_(const esp_ble_gap_cb_param_t::ble_scan_start_cmpl_evt_param &param);
261 void gap_scan_stop_complete_(const esp_ble_gap_cb_param_t::ble_scan_stop_cmpl_evt_param &param);
264
265 int app_id_{0};
266
268 std::vector<uint64_t> already_discovered_;
269 std::vector<ESPBTDeviceListener *> listeners_;
271 std::vector<ESPBTClient *> clients_;
273 esp_ble_scan_params_t scan_params_;
277 uint32_t scan_window_;
286
287 // Lock-free Single-Producer Single-Consumer (SPSC) ring buffer for scan results
288 // Producer: ESP-IDF Bluetooth stack callback (gap_scan_event_handler)
289 // Consumer: ESPHome main loop (loop() method)
290 // This design ensures zero blocking in the BT callback and prevents scan result loss
291 BLEScanResult *scan_ring_buffer_;
292 std::atomic<size_t> ring_write_index_{0}; // Written only by BT callback (producer)
293 std::atomic<size_t> ring_read_index_{0}; // Written only by main loop (consumer)
294 std::atomic<size_t> scan_results_dropped_{0}; // Tracks buffer overflow events
295
296 esp_bt_status_t scan_start_failed_{ESP_BT_STATUS_SUCCESS};
297 esp_bt_status_t scan_set_param_failed_{ESP_BT_STATUS_SUCCESS};
302#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
303 bool coex_prefer_ble_{false};
304#endif
305};
306
307// NOLINTNEXTLINE
308extern ESP32BLETracker *global_esp32_ble_tracker;
309
310} // namespace esp32_ble_tracker
311} // namespace esphome
312
313#endif
Helper class to easily give an object a parent of type T.
Definition helpers.h:539
static ESPBTUUID from_raw_reversed(const uint8_t *data)
Definition ble_uuid.cpp:34
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
esp_ble_scan_params_t scan_params_
A structure holding the ESP BLE scan parameters.
void register_listener(ESPBTDeviceListener *listener)
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 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 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.
std::vector< ESPBTClient * > clients_
Client parameters.
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.
static optional< ESPBLEiBeacon > from_manufacturer_data(const ServiceData &data)
struct esphome::esp32_ble_tracker::ESPBLEiBeacon::@81 beacon_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
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
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
std::string size_t len
Definition helpers.h:302
void byteswap()