ESPHome 2026.3.3
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
91 public:
92 virtual void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) = 0;
93};
94
96 public:
97 virtual void gap_scan_event_handler(const BLEScanResult &scan_result) = 0;
98};
99
100#ifdef USE_ESP32_BLE_CLIENT
102 public:
103 virtual void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
104 esp_ble_gattc_cb_param_t *param) = 0;
105};
106#endif
107
108#ifdef USE_ESP32_BLE_SERVER
110 public:
111 virtual void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if,
112 esp_ble_gatts_cb_param_t *param) = 0;
113};
114#endif
115
117 public:
119};
120
121class ESP32BLE : public Component {
122 public:
123 void set_io_capability(IoCapability io_capability) { this->io_cap_ = (esp_ble_io_cap_t) io_capability; }
124
125#ifdef ESPHOME_ESP32_BLE_EXTENDED_AUTH_PARAMS
126 void set_max_key_size(uint8_t key_size) { this->max_key_size_ = key_size; }
127 void set_min_key_size(uint8_t key_size) { this->min_key_size_ = key_size; }
128 void set_auth_req(AuthReqMode req) { this->auth_req_mode_ = (esp_ble_auth_req_t) req; }
129#endif
130
131 void set_advertising_cycle_time(uint32_t advertising_cycle_time) {
132 this->advertising_cycle_time_ = advertising_cycle_time;
133 }
134 uint32_t get_advertising_cycle_time() const { return this->advertising_cycle_time_; }
135
136 void enable();
137 void disable();
138 bool is_active();
139 void setup() override;
140 void loop() override;
141 void dump_config() override;
142 float get_setup_priority() const override;
143 void set_name(const char *name) { this->name_ = name; }
144
145#ifdef USE_ESP32_BLE_ADVERTISING
146 void advertising_start();
147 void advertising_set_service_data(const std::vector<uint8_t> &data);
148 void advertising_set_manufacturer_data(const std::vector<uint8_t> &data);
149 void advertising_set_appearance(uint16_t appearance) { this->appearance_ = appearance; }
150 void advertising_set_service_data_and_name(std::span<const uint8_t> data, bool include_name);
153 void advertising_register_raw_advertisement_callback(std::function<void(bool)> &&callback);
154#endif
155
156#ifdef ESPHOME_ESP32_BLE_GAP_EVENT_HANDLER_COUNT
157 void register_gap_event_handler(GAPEventHandler *handler) { this->gap_event_handlers_.push_back(handler); }
158#endif
159#ifdef ESPHOME_ESP32_BLE_GAP_SCAN_EVENT_HANDLER_COUNT
161 this->gap_scan_event_handlers_.push_back(handler);
162 }
163#endif
164#if defined(USE_ESP32_BLE_CLIENT) && defined(ESPHOME_ESP32_BLE_GATTC_EVENT_HANDLER_COUNT)
165 void register_gattc_event_handler(GATTcEventHandler *handler) { this->gattc_event_handlers_.push_back(handler); }
166#endif
167#if defined(USE_ESP32_BLE_SERVER) && defined(ESPHOME_ESP32_BLE_GATTS_EVENT_HANDLER_COUNT)
168 void register_gatts_event_handler(GATTsEventHandler *handler) { this->gatts_event_handlers_.push_back(handler); }
169#endif
170#ifdef ESPHOME_ESP32_BLE_BLE_STATUS_EVENT_HANDLER_COUNT
172 this->ble_status_event_handlers_.push_back(handler);
173 }
174#endif
175 void set_enable_on_boot(bool enable_on_boot) { this->enable_on_boot_ = enable_on_boot; }
176
177 protected:
178#ifdef USE_ESP32_BLE_SERVER
179 static void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
180#endif
181#ifdef USE_ESP32_BLE_CLIENT
182 static void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param);
183#endif
184 static void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param);
185
186 // Handle DISABLE and ENABLE transitions when not in the ACTIVE state.
187 // Other non-ACTIVE states (e.g. OFF, DISABLED) are currently treated as no-ops.
188 void __attribute__((noinline)) loop_handle_state_transition_not_active_();
189
190 bool ble_setup_();
191 bool ble_dismantle_();
192 bool ble_pre_setup_();
193#ifdef USE_ESP32_BLE_ADVERTISING
194 void advertising_init_();
195#endif
196
197 // BLE uses the core wake_loop_threadsafe() mechanism to wake the main event loop
198 // from BLE tasks. This enables low-latency (~12μs) event processing instead of
199 // waiting for select() timeout (0-16ms). The wake socket is shared with other
200 // components that need this functionality.
201
202 private:
203 template<typename... Args> friend void enqueue_ble_event(Args... args);
204
205 // Handler vectors - use StaticVector when counts are known at compile time
206#ifdef ESPHOME_ESP32_BLE_GAP_EVENT_HANDLER_COUNT
208#endif
209#ifdef ESPHOME_ESP32_BLE_GAP_SCAN_EVENT_HANDLER_COUNT
211#endif
212#if defined(USE_ESP32_BLE_CLIENT) && defined(ESPHOME_ESP32_BLE_GATTC_EVENT_HANDLER_COUNT)
214#endif
215#if defined(USE_ESP32_BLE_SERVER) && defined(ESPHOME_ESP32_BLE_GATTS_EVENT_HANDLER_COUNT)
217#endif
218#ifdef ESPHOME_ESP32_BLE_BLE_STATUS_EVENT_HANDLER_COUNT
220#endif
221
222 // Large objects (size depends on template parameters, but typically aligned to 4 bytes)
224 // Pool sized to queue capacity (SIZE-1) because LockFreeQueue<T,N> is a ring
225 // buffer that holds N-1 elements (one slot distinguishes full from empty).
226 // This guarantees allocate() returns nullptr before push() can fail, which:
227 // 1. Prevents leaking a pool slot (the Nth allocate succeeds but push fails)
228 // 2. Avoids needing release() on the producer path after a failed push(),
229 // preserving the SPSC contract on the pool's internal free list
230 esphome::EventPool<BLEEvent, MAX_BLE_QUEUE_SIZE - 1> ble_event_pool_;
231
232 // 4-byte aligned members
233#ifdef USE_ESP32_BLE_ADVERTISING
234 BLEAdvertising *advertising_{}; // 4 bytes (pointer)
235#endif
236 const char *name_{nullptr}; // 4 bytes (pointer to string literal in flash)
237 esp_ble_io_cap_t io_cap_{ESP_IO_CAP_NONE}; // 4 bytes (enum)
238 uint32_t advertising_cycle_time_{}; // 4 bytes
239
240 // 2-byte aligned members
241 uint16_t appearance_{0}; // 2 bytes
242
243 // 1-byte aligned members (grouped together to minimize padding)
244 BLEComponentState state_{BLE_COMPONENT_STATE_OFF}; // 1 byte (uint8_t enum)
245 bool enable_on_boot_{}; // 1 byte
246
247#ifdef ESPHOME_ESP32_BLE_EXTENDED_AUTH_PARAMS
248 optional<esp_ble_auth_req_t> auth_req_mode_;
249
250 uint8_t max_key_size_{0}; // range is 7..16, 0 is unset
251 uint8_t min_key_size_{0}; // range is 7..16, 0 is unset
252#endif
253};
254
255// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
256extern ESP32BLE *global_ble;
257
258template<typename... Ts> class BLEEnabledCondition : public Condition<Ts...> {
259 public:
260 bool check(const Ts &...x) override { return global_ble != nullptr && global_ble->is_active(); }
261};
262
263template<typename... Ts> class BLEEnableAction : public Action<Ts...> {
264 public:
265 void play(const Ts &...x) override {
266 if (global_ble != nullptr)
268 }
269};
270
271template<typename... Ts> class BLEDisableAction : public Action<Ts...> {
272 public:
273 void play(const Ts &...x) override {
274 if (global_ble != nullptr)
276 }
277};
278
279} // namespace esphome::esp32_ble
280
281#endif
uint8_t address
Definition bl0906.h:4
Base class for all automation conditions.
Definition automation.h:304
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:209
void play(const Ts &...x) override
Definition ble.h:273
void play(const Ts &...x) override
Definition ble.h:265
bool check(const Ts &...x) override
Definition ble.h:260
void advertising_set_manufacturer_data(const std::vector< uint8_t > &data)
Definition ble.cpp:100
void register_gap_event_handler(GAPEventHandler *handler)
Definition ble.h:157
void set_enable_on_boot(bool enable_on_boot)
Definition ble.h:175
static void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
Definition ble.cpp:592
void set_auth_req(AuthReqMode req)
Definition ble.h:128
void register_gattc_event_handler(GATTcEventHandler *handler)
Definition ble.h:165
void register_gap_scan_event_handler(GAPScanEventHandler *handler)
Definition ble.h:160
void set_name(const char *name)
Definition ble.h:143
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:640
friend void enqueue_ble_event(Args... args)
Definition ble.cpp:565
void __attribute__((noinline)) loop_handle_state_transition_not_active_()
void advertising_register_raw_advertisement_callback(std::function< void(bool)> &&callback)
Definition ble.cpp:128
void advertising_set_service_data_and_name(std::span< const uint8_t > data, bool include_name)
Definition ble.cpp:106
void set_advertising_cycle_time(uint32_t advertising_cycle_time)
Definition ble.h:131
void register_ble_status_event_handler(BLEStatusEventHandler *handler)
Definition ble.h:171
void advertising_add_service_uuid(ESPBTUUID uuid)
Definition ble.cpp:133
void dump_config() override
Definition ble.cpp:652
void loop() override
Definition ble.cpp:398
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:629
void register_gatts_event_handler(GATTsEventHandler *handler)
Definition ble.h:168
void set_max_key_size(uint8_t key_size)
Definition ble.h:126
void advertising_set_service_data(const std::vector< uint8_t > &data)
Definition ble.cpp:94
void set_io_capability(IoCapability io_capability)
Definition ble.h:123
void advertising_set_appearance(uint16_t appearance)
Definition ble.h:149
float get_setup_priority() const override
Definition ble.cpp:650
void setup() override
Definition ble.cpp:56
void set_min_key_size(uint8_t key_size)
Definition ble.h:127
uint32_t get_advertising_cycle_time() const
Definition ble.h:134
void advertising_remove_service_uuid(ESPBTUUID uuid)
Definition ble.cpp:139
virtual void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)=0
virtual void gap_scan_event_handler(const BLEScanResult &scan_result)=0
virtual void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param)=0
virtual void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param)=0
ESP32BLE * global_ble
Definition ble.cpp:731
@ 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
const char int const __FlashStringHelper va_list args
Definition log.h:74
static void uint32_t
uint16_t x
Definition tt21100.cpp:5