ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
ble.h
Go to the documentation of this file.
1#pragma once
2
3#include "esphome/core/defines.h" // Must be included before conditional includes
4
5#include "ble_uuid.h"
6#include "ble_scan_result.h"
7#ifdef USE_ESP32_BLE_ADVERTISING
8#include "ble_advertising.h"
9#endif
10
11#include <functional>
12#include <span>
13
17
18#include "ble_event.h"
21
22#ifdef USE_ESP32
23
24#include <esp_gap_ble_api.h>
25#include <esp_gattc_api.h>
26#include <esp_gatts_api.h>
27
28namespace esphome::esp32_ble {
29
30// Maximum size of the BLE event queue
31// Increased to absorb the ring buffer capacity from esp32_ble_tracker
32#ifdef USE_PSRAM
33static constexpr uint8_t MAX_BLE_QUEUE_SIZE = 100; // 64 + 36 (ring buffer size with PSRAM)
34#else
35static constexpr uint8_t MAX_BLE_QUEUE_SIZE = 88; // 64 + 24 (ring buffer size without PSRAM)
36#endif
37
38inline uint64_t ble_addr_to_uint64(const esp_bd_addr_t address) {
39 uint64_t u = 0;
40 u |= uint64_t(address[0] & 0xFF) << 40;
41 u |= uint64_t(address[1] & 0xFF) << 32;
42 u |= uint64_t(address[2] & 0xFF) << 24;
43 u |= uint64_t(address[3] & 0xFF) << 16;
44 u |= uint64_t(address[4] & 0xFF) << 8;
45 u |= uint64_t(address[5] & 0xFF) << 0;
46 return u;
47}
48
49// NOLINTNEXTLINE(modernize-use-using)
50typedef struct {
53 uint16_t mtu;
55
57 IO_CAP_OUT = ESP_IO_CAP_OUT,
58 IO_CAP_IO = ESP_IO_CAP_IO,
59 IO_CAP_IN = ESP_IO_CAP_IN,
60 IO_CAP_NONE = ESP_IO_CAP_NONE,
61 IO_CAP_KBDISP = ESP_IO_CAP_KBDISP,
62};
63
64#ifdef ESPHOME_ESP32_BLE_EXTENDED_AUTH_PARAMS
66 AUTH_REQ_NO_BOND = ESP_LE_AUTH_NO_BOND,
67 AUTH_REQ_BOND = ESP_LE_AUTH_BOND,
68 AUTH_REQ_MITM = ESP_LE_AUTH_REQ_MITM,
69 AUTH_REQ_BOND_MITM = ESP_LE_AUTH_REQ_BOND_MITM,
70 AUTH_REQ_SC_ONLY = ESP_LE_AUTH_REQ_SC_ONLY,
71 AUTH_REQ_SC_BOND = ESP_LE_AUTH_REQ_SC_BOND,
72 AUTH_REQ_SC_MITM = ESP_LE_AUTH_REQ_SC_MITM,
73 AUTH_REQ_SC_MITM_BOND = ESP_LE_AUTH_REQ_SC_MITM_BOND,
74};
75#endif
76
89
90class ESP32BLE final : public Component {
91 public:
92 void set_io_capability(IoCapability io_capability) { this->io_cap_ = (esp_ble_io_cap_t) io_capability; }
93
94#ifdef ESPHOME_ESP32_BLE_EXTENDED_AUTH_PARAMS
95 void set_max_key_size(uint8_t key_size) { this->max_key_size_ = key_size; }
96 void set_min_key_size(uint8_t key_size) { this->min_key_size_ = key_size; }
97 void set_auth_req(AuthReqMode req) { this->auth_req_mode_ = (esp_ble_auth_req_t) req; }
98#endif
99
100 void set_advertising_cycle_time(uint32_t advertising_cycle_time) {
101 this->advertising_cycle_time_ = advertising_cycle_time;
102 }
103 uint32_t get_advertising_cycle_time() const { return this->advertising_cycle_time_; }
104
105 void enable() { this->request_state_(true); }
106 void disable() { this->request_state_(false); }
107 ESPHOME_ALWAYS_INLINE bool is_active() { return this->state_ == BLE_COMPONENT_STATE_ACTIVE; }
108 void setup() override;
109 void loop() override;
110 void dump_config() override;
112 void get_mac_msb_first(uint8_t out[MAC_ADDRESS_SIZE]) const;
113 float get_setup_priority() const override;
114 void set_name(const char *name) { this->name_ = name; }
115 // BLE device names are limited to 20 characters
116 static constexpr size_t DEVICE_NAME_BUFFER_SIZE = 21;
118 const char *device_name(char *buffer) const;
119
120#ifdef USE_ESP32_BLE_ADVERTISING
127 void advertising_start();
129 void advertising_stop();
131 void advertising_refresh();
132 void advertising_set_service_data(const std::vector<uint8_t> &data);
133 void advertising_set_manufacturer_data(const std::vector<uint8_t> &data);
134 void advertising_set_appearance(uint16_t appearance) { this->appearance_ = appearance; }
135 void advertising_set_service_data_and_name(std::span<const uint8_t> data, bool include_name);
141 void advertising_register_raw_advertisement_callback(std::function<void(bool)> &&callback);
142#endif
143
144#ifdef ESPHOME_ESP32_BLE_GAP_EVENT_HANDLER_COUNT
145 template<typename F> void add_gap_event_callback(F &&callback) {
146 this->gap_event_callbacks_.add(std::forward<F>(callback));
147 }
148#endif
149#ifdef ESPHOME_ESP32_BLE_GAP_SCAN_EVENT_HANDLER_COUNT
150 template<typename F> void add_gap_scan_event_callback(F &&callback) {
151 this->gap_scan_event_callbacks_.add(std::forward<F>(callback));
152 }
153#endif
154#if defined(USE_ESP32_BLE_CLIENT) && defined(ESPHOME_ESP32_BLE_GATTC_EVENT_HANDLER_COUNT)
155 template<typename F> void add_gattc_event_callback(F &&callback) {
156 this->gattc_event_callbacks_.add(std::forward<F>(callback));
157 }
158#endif
159#if defined(USE_ESP32_BLE_SERVER) && defined(ESPHOME_ESP32_BLE_GATTS_EVENT_HANDLER_COUNT)
160 template<typename F> void add_gatts_event_callback(F &&callback) {
161 this->gatts_event_callbacks_.add(std::forward<F>(callback));
162 }
163#endif
164#ifdef ESPHOME_ESP32_BLE_BLE_STATUS_EVENT_HANDLER_COUNT
165 template<typename F> void add_ble_status_event_callback(F &&callback) {
166 this->ble_status_event_callbacks_.add(std::forward<F>(callback));
167 }
168#endif
169 void set_enable_on_boot(bool enable_on_boot) { this->enable_on_boot_ = enable_on_boot; }
170
171 protected:
172#ifdef USE_ESP32_BLE_SERVER
173 static void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
174#endif
175#ifdef USE_ESP32_BLE_CLIENT
176 static void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param);
177#endif
178 static void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param);
179
180 // Handle DISABLE and ENABLE transitions when not in the ACTIVE state.
181 // Other non-ACTIVE states (e.g. OFF, DISABLED) are currently treated as no-ops.
182 void __attribute__((noinline)) loop_handle_state_transition_not_active_();
183
184 uint8_t *conn_param_failed_slot_(const uint8_t *bda);
185 void forget_conn_param_failure_(const uint8_t *bda);
186
187 bool ble_setup_();
188 bool ble_dismantle_();
189 void request_state_(bool enable);
190 // Drop what the old stack queued; the next stack reuses the same interface ids.
192 BLEEvent *ble_event;
193 while ((ble_event = this->ble_events_.pop()) != nullptr) {
194 this->ble_event_pool_.release(ble_event);
195 }
196 this->ble_events_.get_and_reset_dropped_count();
197 }
198 ESPHOME_ALWAYS_INLINE void advertising_loop_() {
199#ifdef USE_ESP32_BLE_ADVERTISING
200 if (this->advertising_ != nullptr)
201 this->advertising_->loop();
202#endif
203 }
204#ifdef USE_ESP32_BLE_ADVERTISING
205 void advertising_init_();
207 if (this->advertising_ != nullptr)
208 this->advertising_->cancel_start();
209 }
210#endif
211
212 // BLE uses the core wake_loop_threadsafe() mechanism to wake the main event loop
213 // from BLE tasks. This enables low-latency (~12μs) event processing instead of
214 // waiting for select() timeout (0-16ms). The wake socket is shared with other
215 // components that need this functionality.
216
217 private:
218 template<typename... Args> friend void enqueue_ble_event(Args... args);
219
220#ifdef ESPHOME_ESP32_BLE_GAP_EVENT_HANDLER_COUNT
221 StaticCallbackManager<ESPHOME_ESP32_BLE_GAP_EVENT_HANDLER_COUNT,
222 void(esp_gap_ble_cb_event_t, esp_ble_gap_cb_param_t *)>
223 gap_event_callbacks_;
224#endif
225#ifdef ESPHOME_ESP32_BLE_GAP_SCAN_EVENT_HANDLER_COUNT
226 StaticCallbackManager<ESPHOME_ESP32_BLE_GAP_SCAN_EVENT_HANDLER_COUNT, void(const BLEScanResult &)>
227 gap_scan_event_callbacks_;
228#endif
229#if defined(USE_ESP32_BLE_CLIENT) && defined(ESPHOME_ESP32_BLE_GATTC_EVENT_HANDLER_COUNT)
230 StaticCallbackManager<ESPHOME_ESP32_BLE_GATTC_EVENT_HANDLER_COUNT,
231 void(esp_gattc_cb_event_t, esp_gatt_if_t, esp_ble_gattc_cb_param_t *)>
232 gattc_event_callbacks_;
233#endif
234#if defined(USE_ESP32_BLE_SERVER) && defined(ESPHOME_ESP32_BLE_GATTS_EVENT_HANDLER_COUNT)
235 StaticCallbackManager<ESPHOME_ESP32_BLE_GATTS_EVENT_HANDLER_COUNT,
236 void(esp_gatts_cb_event_t, esp_gatt_if_t, esp_ble_gatts_cb_param_t *)>
237 gatts_event_callbacks_;
238#endif
239#ifdef ESPHOME_ESP32_BLE_BLE_STATUS_EVENT_HANDLER_COUNT
240 StaticCallbackManager<ESPHOME_ESP32_BLE_BLE_STATUS_EVENT_HANDLER_COUNT, void()> ble_status_event_callbacks_;
241#endif
242
243 // Large objects (size depends on template parameters, but typically aligned to 4 bytes)
245 // Pool sized to queue capacity (SIZE-1) because LockFreeQueue<T,N> is a ring
246 // buffer that holds N-1 elements (one slot distinguishes full from empty).
247 // This guarantees allocate() returns nullptr before push() can fail, which:
248 // 1. Prevents leaking a pool slot (the Nth allocate succeeds but push fails)
249 // 2. Avoids needing release() on the producer path after a failed push(),
250 // preserving the SPSC contract on the pool's internal free list
251 esphome::EventPool<BLEEvent, MAX_BLE_QUEUE_SIZE - 1> ble_event_pool_;
252
253 // 4-byte aligned members
254#ifdef USE_ESP32_BLE_ADVERTISING
255 BLEAdvertising *advertising_{}; // 4 bytes (pointer)
256#endif
257 const char *name_{nullptr}; // 4 bytes (pointer to string literal in flash)
258 uint32_t advertising_cycle_time_{}; // 4 bytes
259
260 // 2-byte aligned members
261 uint16_t appearance_{0}; // 2 bytes
262
263 // 1-byte aligned members (grouped together to minimize padding)
264 esp_ble_io_cap_t io_cap_{ESP_IO_CAP_NONE}; // 1 byte (uint8_t typedef)
265 BLEComponentState state_{BLE_COMPONENT_STATE_OFF}; // 1 byte (uint8_t enum)
266 bool enable_on_boot_{}; // 1 byte
267 // Peers already warned about a failed conn param update, one per connection; all-zero is free
268 esp_bd_addr_t conn_param_failed_bdas_[USE_ESP32_BLE_MAX_CONNECTIONS]{};
269#ifdef USE_ESP32_BLE_ADVERTISING
270 uint8_t advertising_ref_count_{0}; // 1 byte, number of components requesting advertising
271#endif
272
273#ifdef ESPHOME_ESP32_BLE_EXTENDED_AUTH_PARAMS
274 optional<esp_ble_auth_req_t> auth_req_mode_;
275
276 uint8_t max_key_size_{0}; // range is 7..16, 0 is unset
277 uint8_t min_key_size_{0}; // range is 7..16, 0 is unset
278#endif
279};
280
281// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
282extern ESP32BLE *global_ble;
283
284} // namespace esphome::esp32_ble
285
286#endif
CallbackManager backed by StaticVector for compile-time-known callback counts.
Definition helpers.h:2047
void add_gatts_event_callback(F &&callback)
Definition ble.h:160
void advertising_set_manufacturer_data(const std::vector< uint8_t > &data)
Definition ble.cpp:209
void get_mac_msb_first(uint8_t out[MAC_ADDRESS_SIZE]) const
Adapter MAC in printable (MSB-first) order; all-zero until the stack is up.
Definition ble.cpp:812
ESPHOME_ALWAYS_INLINE void advertising_loop_()
Definition ble.h:198
void add_gap_scan_event_callback(F &&callback)
Definition ble.h:150
void set_enable_on_boot(bool enable_on_boot)
Definition ble.h:169
static void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
Definition ble.cpp:709
void set_auth_req(AuthReqMode req)
Definition ble.h:97
void add_gap_event_callback(F &&callback)
Definition ble.h:145
static constexpr size_t DEVICE_NAME_BUFFER_SIZE
Definition ble.h:116
const char * device_name(char *buffer) const
The device name; written to buffer unless the configured name is used as is.
Definition ble.cpp:275
void set_name(const char *name)
Definition ble.h:114
static void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param)
Definition ble.cpp:788
void advertising_start()
Request advertising on behalf of a component.
Definition ble.cpp:178
void advertising_refresh()
Apply the current payload and request count: advertise while requested, otherwise stop.
Definition ble.cpp:191
friend void enqueue_ble_event(Args... args)
Definition ble.cpp:682
void __attribute__((noinline)) loop_handle_state_transition_not_active_()
void forget_conn_param_failure_(const uint8_t *bda)
Definition ble.cpp:806
uint8_t * conn_param_failed_slot_(const uint8_t *bda)
Definition ble.cpp:798
void advertising_register_raw_advertisement_callback(std::function< void(bool)> &&callback)
Definition ble.cpp:237
void advertising_set_service_data_and_name(std::span< const uint8_t > data, bool include_name)
Definition ble.cpp:215
void set_advertising_cycle_time(uint32_t advertising_cycle_time)
Definition ble.h:100
void advertising_add_service_uuid(ESPBTUUID uuid)
Definition ble.cpp:242
void advertising_cancel_start_()
Definition ble.h:206
void advertising_clear_priority_uuid()
Definition ble.cpp:253
void dump_config() override
Definition ble.cpp:825
void request_state_(bool enable)
Definition ble.cpp:161
void loop() override
Definition ble.cpp:507
static void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param)
Definition ble.cpp:777
void add_ble_status_event_callback(F &&callback)
Definition ble.h:165
void advertising_set_priority_uuid(ESPBTUUID uuid)
Keep uuid and the service data alone in the advertising packet; applies on the next refresh.
Definition ble.cpp:248
void set_max_key_size(uint8_t key_size)
Definition ble.h:95
void advertising_set_service_data(const std::vector< uint8_t > &data)
Definition ble.cpp:203
void set_io_capability(IoCapability io_capability)
Definition ble.h:92
void advertising_set_appearance(uint16_t appearance)
Definition ble.h:134
ESPHOME_ALWAYS_INLINE bool is_active()
Definition ble.h:107
float get_setup_priority() const override
Definition ble.cpp:823
void add_gattc_event_callback(F &&callback)
Definition ble.h:155
void setup() override
Definition ble.cpp:143
void set_min_key_size(uint8_t key_size)
Definition ble.h:96
void advertising_stop()
Release a request made with advertising_start(); advertising stops at the last release.
Definition ble.cpp:184
uint32_t get_advertising_cycle_time() const
Definition ble.h:103
void advertising_remove_service_uuid(ESPBTUUID uuid)
Definition ble.cpp:258
std::vector< uint8_t > & out
Definition gif.cpp:49
uint32_t buffer
Definition gif.cpp:50
ESP32BLE * global_ble
Definition ble.cpp:908
@ BLE_COMPONENT_STATE_DISABLE
BLE should be disabled on next loop.
Definition ble.h:81
@ BLE_COMPONENT_STATE_OFF
Nothing has been initialized yet.
Definition ble.h:79
@ BLE_COMPONENT_STATE_ENABLE
BLE should be enabled on next loop.
Definition ble.h:85
@ BLE_COMPONENT_STATE_DISABLED
BLE is disabled.
Definition ble.h:83
@ BLE_COMPONENT_STATE_ACTIVE
BLE is active.
Definition ble.h:87
uint64_t ble_addr_to_uint64(const esp_bd_addr_t address)
Definition ble.h:38
@ AUTH_REQ_SC_MITM_BOND
Definition ble.h:73
@ AUTH_REQ_BOND_MITM
Definition ble.h:69
static void uint32_t