ESPHome 2025.6.2
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 // Exposed through a function for use in lambdas
89 const BLEScanResult &get_scan_result() const { return *scan_result_; }
90
91 bool resolve_irk(const uint8_t *irk) const;
92
94 for (auto &it : this->manufacturer_datas_) {
96 if (res.has_value())
97 return *res;
98 }
99 return {};
100 }
101
102 protected:
103 void parse_adv_(const uint8_t *payload, uint8_t len);
104
105 esp_bd_addr_t address_{
106 0,
107 };
108 esp_ble_addr_type_t address_type_{BLE_ADDR_TYPE_PUBLIC};
109 int rssi_{0};
110 std::string name_{};
111 std::vector<int8_t> tx_powers_{};
114 std::vector<ESPBTUUID> service_uuids_{};
115 std::vector<ServiceData> manufacturer_datas_{};
116 std::vector<ServiceData> service_datas_{};
117 const BLEScanResult *scan_result_{nullptr};
118};
119
120class ESP32BLETracker;
121
123 public:
124 virtual void on_scan_end() {}
125 virtual bool parse_device(const ESPBTDevice &device) = 0;
126 virtual bool parse_devices(const BLEScanResult *scan_results, size_t count) { return false; };
130 void set_parent(ESP32BLETracker *parent) { parent_ = parent; }
131
132 protected:
134};
135
136enum class ClientState {
137 // Connection is allocated
138 INIT,
139 // Client is disconnecting
141 // Connection is idle, no device detected.
142 IDLE,
143 // Searching for device.
144 SEARCHING,
145 // Device advertisement found.
147 // Device is discovered and the scanner is stopped
149 // Connection in progress.
151 // Initial connection established.
152 CONNECTED,
153 // The client and sub-clients have completed setup.
155};
156
157enum class ScannerState {
158 // Scanner is idle, init state, set from the main loop when processing STOPPED
159 IDLE,
160 // Scanner is starting, set from the main loop only
161 STARTING,
162 // Scanner is running, set from the ESP callback only
163 RUNNING,
164 // Scanner failed to start, set from the ESP callback only
165 FAILED,
166 // Scanner is stopping, set from the main loop only
167 STOPPING,
168 // Scanner is stopped, set from the ESP callback only
169 STOPPED,
170};
171
172enum class ConnectionType {
173 // The default connection type, we hold all the services in ram
174 // for the duration of the connection.
175 V1,
176 // The client has a cache of the services and mtu so we should not
177 // fetch them again
179 // The client does not need the services and mtu once we send them
180 // so we should wipe them from memory as soon as we send them
182};
183
185 public:
186 virtual bool gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
187 esp_ble_gattc_cb_param_t *param) = 0;
188 virtual void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) = 0;
189 virtual void connect() = 0;
190 virtual void disconnect() = 0;
191 bool disconnect_pending() const { return this->want_disconnect_; }
193 virtual void set_state(ClientState st) {
194 this->state_ = st;
195 if (st == ClientState::IDLE) {
196 this->want_disconnect_ = false;
197 }
198 }
199 ClientState state() const { return state_; }
201
202 protected:
204 // want_disconnect_ is set to true when a disconnect is requested
205 // while the client is connecting. This is used to disconnect the
206 // client as soon as we get the connection id (conn_id_) from the
207 // ESP_GATTC_OPEN_EVT event.
208 bool want_disconnect_{false};
209};
210
212 public GAPEventHandler,
213 public GAPScanEventHandler,
214 public GATTcEventHandler,
216 public Parented<ESP32BLE> {
217 public:
218 void set_scan_duration(uint32_t scan_duration) { scan_duration_ = scan_duration; }
219 void set_scan_interval(uint32_t scan_interval) { scan_interval_ = scan_interval; }
220 void set_scan_window(uint32_t scan_window) { scan_window_ = scan_window; }
221 void set_scan_active(bool scan_active) { scan_active_ = scan_active; }
222 bool get_scan_active() const { return scan_active_; }
223 void set_scan_continuous(bool scan_continuous) { scan_continuous_ = scan_continuous; }
224
226 void setup() override;
227 void dump_config() override;
228 float get_setup_priority() const override;
229
230 void loop() override;
231
233 void register_client(ESPBTClient *client);
235
236 void print_bt_device_info(const ESPBTDevice &device);
237
238 void start_scan();
239 void stop_scan();
240
241 void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
242 esp_ble_gattc_cb_param_t *param) override;
243 void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) override;
244 void gap_scan_event_handler(const BLEScanResult &scan_result) override;
245 void ble_before_disabled_event_handler() override;
246
247 void add_scanner_state_callback(std::function<void(ScannerState)> &&callback) {
248 this->scanner_state_callbacks_.add(std::move(callback));
249 }
251
252 protected:
253 void stop_scan_();
255 void start_scan_(bool first);
257 void end_of_scan_();
259 void gap_scan_result_(const esp_ble_gap_cb_param_t::ble_scan_result_evt_param &param);
261 void gap_scan_set_param_complete_(const esp_ble_gap_cb_param_t::ble_scan_param_cmpl_evt_param &param);
263 void gap_scan_start_complete_(const esp_ble_gap_cb_param_t::ble_scan_start_cmpl_evt_param &param);
265 void gap_scan_stop_complete_(const esp_ble_gap_cb_param_t::ble_scan_stop_cmpl_evt_param &param);
268
269 int app_id_{0};
270
272 std::vector<uint64_t> already_discovered_;
273 std::vector<ESPBTDeviceListener *> listeners_;
275 std::vector<ESPBTClient *> clients_;
277 esp_ble_scan_params_t scan_params_;
281 uint32_t scan_window_;
290
291 // Lock-free Single-Producer Single-Consumer (SPSC) ring buffer for scan results
292 // Producer: ESP-IDF Bluetooth stack callback (gap_scan_event_handler)
293 // Consumer: ESPHome main loop (loop() method)
294 // This design ensures zero blocking in the BT callback and prevents scan result loss
295 BLEScanResult *scan_ring_buffer_;
296 std::atomic<size_t> ring_write_index_{0}; // Written only by BT callback (producer)
297 std::atomic<size_t> ring_read_index_{0}; // Written only by main loop (consumer)
298 std::atomic<size_t> scan_results_dropped_{0}; // Tracks buffer overflow events
299
300 esp_bt_status_t scan_start_failed_{ESP_BT_STATUS_SUCCESS};
301 esp_bt_status_t scan_set_param_failed_{ESP_BT_STATUS_SUCCESS};
306#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
307 bool coex_prefer_ble_{false};
308#endif
309};
310
311// NOLINTNEXTLINE
312extern ESP32BLETracker *global_esp32_ble_tracker;
313
314} // namespace esp32_ble_tracker
315} // namespace esphome
316
317#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.
struct esphome::esp32_ble_tracker::ESPBLEiBeacon::@80 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
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()