ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
ble_server.cpp
Go to the documentation of this file.
1#include "ble_server.h"
2
5#include "esphome/core/log.h"
8
9#ifdef USE_ESP32
10
11#include <freertos/FreeRTOSConfig.h>
12#include <esp_bt_main.h>
13#ifndef CONFIG_BT_CONTROLLER_DISABLED
14#include <esp_bt.h>
15#endif
16#include <freertos/task.h>
17#include <esp_gap_ble_api.h>
18#include <cstring>
19
21
22ESPHOME_LOG_TAG(TAG, "esp32_ble_server");
23
25 if (this->parent_->is_failed()) {
26 this->mark_failed();
27 ESP_LOGE(TAG, "BLE Server was marked failed by ESP32BLE");
28 return;
29 }
30 global_ble_server = this;
31}
32
34 if (!this->parent_->is_active()) {
35 return;
36 }
37 switch (this->state_) {
38 case RUNNING: {
39 // Start all services that are pending to start
40 if (!this->services_to_start_.empty()) {
41 size_t write_idx = 0;
42 for (auto *service : this->services_to_start_) {
43 if (service->is_created()) {
44 service->start(); // Needs to be called once per characteristic in the service
45 }
46 // Remove services that have started or are starting
47 if (!service->is_starting() && !service->is_running()) {
48 this->services_to_start_[write_idx++] = service;
49 }
50 }
51 this->services_to_start_.erase(this->services_to_start_.begin() + write_idx, this->services_to_start_.end());
52 }
53 break;
54 }
55 case INIT: {
56#ifdef USE_ESP32_BLE_SERVER_STATIC_PASSKEY
57 // A stack setting, so it is set again each time BLE is enabled
58 esp_err_t passkey_err =
59 esp_ble_gap_set_security_param(ESP_BLE_SM_SET_STATIC_PASSKEY, &this->passkey_, sizeof(this->passkey_));
60 if (passkey_err != ESP_OK) {
61 ESP_LOGE(TAG, "Setting static passkey failed: %d", passkey_err);
62 }
63#endif
64 esp_err_t err = esp_ble_gatts_app_register(0);
65 if (err != ESP_OK) {
66 ESP_LOGE(TAG, "esp_ble_gatts_app_register failed: %d", err);
67 this->mark_failed();
68 return;
69 }
70 this->state_ = REGISTERING;
71 break;
72 }
73 case REGISTERING: {
74 if (this->registered_) {
75 // Create the device information service first so
76 // it is at the top of the GATT table
78 // Create all services previously created
79 for (auto &entry : this->services_) {
80 if (entry.service == this->device_information_service_) {
81 continue;
82 }
83 entry.service->do_create(this);
84 }
85 this->state_ = STARTING_SERVICE;
86 }
87 break;
88 }
89 case STARTING_SERVICE: {
91 this->state_ = RUNNING;
94 ESP_LOGD(TAG, "BLE server setup successfully");
95 } else if (this->device_information_service_->is_created()) {
97 }
98 break;
99 }
100 }
101}
102
103bool BLEServer::can_proceed() { return this->is_running() || !this->parent_->is_active(); }
104
106 if (this->is_running()) {
107 this->parent_->advertising_set_manufacturer_data(this->manufacturer_data_);
108 }
109}
110
113 return;
114 this->advertising_requested_ = true;
115 this->parent_->advertising_start();
116}
117
119 if (!this->advertising_requested_)
120 return;
121 this->advertising_requested_ = false;
122 this->parent_->advertising_stop();
123}
124
125BLEService *BLEServer::create_service(ESPBTUUID uuid, bool advertise, uint16_t num_handles) {
126#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
127 char uuid_buf[esp32_ble::UUID_STR_LEN];
128 uuid.to_str(uuid_buf);
129 ESP_LOGV(TAG, "Creating BLE service - %s", uuid_buf);
130#endif
131 // Calculate the inst_id for the service
132 uint8_t inst_id = 0;
133 for (; inst_id < 0xFF; inst_id++) {
134 if (this->get_service(uuid, inst_id) == nullptr) {
135 break;
136 }
137 }
138 if (inst_id == 0xFF) {
139 char warn_uuid_buf[esp32_ble::UUID_STR_LEN];
140 uuid.to_str(warn_uuid_buf);
141 ESP_LOGW(TAG, "Could not create BLE service %s, too many instances", warn_uuid_buf);
142 return nullptr;
143 }
144 BLEService *service = // NOLINT(cppcoreguidelines-owning-memory)
145 new BLEService(uuid, num_handles, inst_id, advertise);
146 this->services_.push_back({uuid, inst_id, service});
147 if (this->parent_->is_active() && this->registered_) {
148 service->do_create(this);
149 }
150 return service;
151}
152
153void BLEServer::remove_service(ESPBTUUID uuid, uint8_t inst_id) {
154#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
155 char uuid_buf[esp32_ble::UUID_STR_LEN];
156 uuid.to_str(uuid_buf);
157 ESP_LOGV(TAG, "Removing BLE service - %s %d", uuid_buf, inst_id);
158#endif
159 for (auto it = this->services_.begin(); it != this->services_.end(); ++it) {
160 if (it->uuid == uuid && it->inst_id == inst_id) {
161 it->service->do_delete();
162 delete it->service; // NOLINT(cppcoreguidelines-owning-memory)
163 this->services_.erase(it);
164 return;
165 }
166 }
167 char warn_uuid_buf[esp32_ble::UUID_STR_LEN];
168 uuid.to_str(warn_uuid_buf);
169 ESP_LOGW(TAG, "BLE service %s %d does not exist", warn_uuid_buf, inst_id);
170}
171
172BLEService *BLEServer::get_service(ESPBTUUID uuid, uint8_t inst_id) {
173 for (auto &entry : this->services_) {
174 if (entry.uuid == uuid && entry.inst_id == inst_id) {
175 return entry.service;
176 }
177 }
178 return nullptr;
179}
180
182 for (auto &entry : this->callbacks_) {
183 if (entry.type == type) {
184 entry.callback(conn_id);
185 }
186 }
187}
188
189void BLEServer::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if,
190 esp_ble_gatts_cb_param_t *param) {
191 switch (event) {
192 case ESP_GATTS_CONNECT_EVT: {
193 ESP_LOGD(TAG, "BLE Client connected");
194 this->add_client_(param->connect);
195 // Resume advertising so additional clients can discover and connect
197 this->parent_->advertising_refresh();
198 }
199 this->dispatch_callbacks_(CallbackType::ON_CONNECT, param->connect.conn_id);
200 break;
201 }
202 case ESP_GATTS_DISCONNECT_EVT: {
203 ESP_LOGD(TAG, "BLE Client disconnected");
204 this->remove_client_(param->disconnect.conn_id);
205 this->parent_->advertising_refresh();
206 this->dispatch_callbacks_(CallbackType::ON_DISCONNECT, param->disconnect.conn_id);
207 break;
208 }
209 case ESP_GATTS_REG_EVT: {
210 this->gatts_if_ = gatts_if;
211 this->registered_ = true;
212 break;
213 }
214 default:
215 break;
216 }
217
218 for (auto &entry : this->services_) {
219 entry.service->gatts_event_handler(event, gatts_if, param);
220 }
221}
222
223int8_t BLEServer::find_client_index_(uint16_t conn_id) const {
224 for (uint8_t i = 0; i < this->client_count_; i++) {
225 if (this->clients_[i] == conn_id)
226 return i;
227 }
228 return -1;
229}
230
231void BLEServer::add_client_(const esp_ble_gatts_cb_param_t::gatts_connect_evt_param &connect) {
232 // Check if already in list
233 if (this->find_client_index_(connect.conn_id) >= 0)
234 return;
235 // Add if there's space
236 if (this->client_count_ < USE_ESP32_BLE_MAX_CONNECTIONS) {
237#ifdef USE_ESP32_BLE_SERVER_SECURITY
238 // Links this device opened as a central (link_role 0) are reported here too; their pairing
239 // belongs to ble_client, so a zero address keeps them out of the security handler
240 auto &address = this->client_addresses_[this->client_count_];
241 if (connect.link_role == 1) {
242 memcpy(address, connect.remote_bda, sizeof(esp_bd_addr_t));
243 } else {
244 memset(address, 0, sizeof(esp_bd_addr_t));
245 }
246#endif
247 this->clients_[this->client_count_++] = connect.conn_id;
248 } else {
249 // This should never happen since max clients is known at compile time
250 ESP_LOGE(TAG, "Client array full");
251 }
252}
253
254void BLEServer::remove_client_(uint16_t conn_id) {
255 int8_t index = this->find_client_index_(conn_id);
256 if (index >= 0) {
257 // Replace with last element and decrement count (client order not preserved)
258 this->clients_[index] = this->clients_[--this->client_count_];
259#ifdef USE_ESP32_BLE_SERVER_SECURITY
260 memcpy(this->client_addresses_[index], this->client_addresses_[this->client_count_], sizeof(esp_bd_addr_t));
261#endif
262 }
263}
264
265#ifdef USE_ESP32_BLE_SERVER_SECURITY
266bool BLEServer::is_client_address_(const esp_bd_addr_t address) const {
267 for (uint8_t i = 0; i < this->client_count_; i++) {
268 if (memcmp(this->client_addresses_[i], address, sizeof(esp_bd_addr_t)) == 0)
269 return true;
270 }
271 return false;
272}
273#endif
274
276 // Advertising is re-requested once the server is running again after BLE is re-enabled
277 this->release_advertising_();
278 // Delete all clients
279 this->client_count_ = 0;
280 // Delete all services
281 for (auto &entry : this->services_) {
282 entry.service->do_delete();
283 }
284 this->registered_ = false;
285 this->state_ = INIT;
286}
287
288#ifdef USE_ESP32_BLE_SERVER_SECURITY
289void BLEServer::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
290 switch (event) {
291 case ESP_GAP_BLE_SEC_REQ_EVT:
292 case ESP_GAP_BLE_AUTH_CMPL_EVT:
293 case ESP_GAP_BLE_PASSKEY_REQ_EVT:
294 case ESP_GAP_BLE_PASSKEY_NOTIF_EVT:
295 case ESP_GAP_BLE_NC_REQ_EVT:
296 break;
297 default:
298 return;
299 }
300 // The params of every security event start with the peer address. Security events are sent to every GAP
301 // handler; ble_client and bluetooth_proxy links are not ours.
302 const uint8_t *bd_addr = param->ble_security.ble_req.bd_addr;
303 if (!this->is_client_address_(bd_addr))
304 return;
305 switch (event) {
306 case ESP_GAP_BLE_SEC_REQ_EVT:
307 esp_ble_gap_security_rsp(param->ble_security.ble_req.bd_addr, this->pairing_enabled_);
308 break;
309 case ESP_GAP_BLE_AUTH_CMPL_EVT: {
310 const auto &auth_cmpl = param->ble_security.auth_cmpl;
311 char addr_str[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
312 format_mac_addr_upper(bd_addr, addr_str);
313 if (auth_cmpl.success) {
314 ESP_LOGI(TAG, "[%s] Authentication complete", addr_str);
315 } else {
316 ESP_LOGW(TAG, "[%s] Authentication failed, reason 0x%x", addr_str, auth_cmpl.fail_reason);
317 }
318 break;
319 }
320#ifdef USE_ESP32_BLE_SERVER_ON_PASSKEY_REQUEST
321 case ESP_GAP_BLE_PASSKEY_REQ_EVT:
323 break;
324#endif
325#ifdef USE_ESP32_BLE_SERVER_ON_PASSKEY_NOTIFICATION
326 case ESP_GAP_BLE_PASSKEY_NOTIF_EVT:
327 this->passkey_notification_callback_.call(ble_addr_to_uint64(bd_addr), param->ble_security.key_notif.passkey);
328 break;
329#endif
330#ifdef USE_ESP32_BLE_SERVER_ON_NUMERIC_COMPARISON_REQUEST
331 case ESP_GAP_BLE_NC_REQ_EVT:
333 param->ble_security.key_notif.passkey);
334 break;
335#endif
336 default:
337 break;
338 }
339}
340
342 esp_bd_addr_t bda;
344 esp_ble_passkey_reply(bda, true, passkey);
345}
346
347void BLEServer::numeric_comparison_reply(uint64_t address, bool accept) {
348 esp_bd_addr_t bda;
350 esp_ble_confirm_reply(bda, accept);
351}
352#endif // USE_ESP32_BLE_SERVER_SECURITY
353
355 esp_bd_addr_t bda;
357 esp_err_t err = esp_ble_remove_bond_device(bda);
358 if (err != ESP_OK) {
359 ESP_LOGW(TAG, "Removing bond failed: %d", err);
360 }
361}
362
364
366 ESP_LOGCONFIG(TAG,
367 "ESP32 BLE Server:\n"
368 " Max clients: %u",
369 this->max_clients_);
370}
371
372BLEServer *global_ble_server = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
373
374} // namespace esphome::esp32_ble_server
375
376#endif
void mark_failed()
Mark this component as failed.
std::vector< CallbackEntry > callbacks_
Definition ble_server.h:132
void add_client_(const esp_ble_gatts_cb_param_t::gatts_connect_evt_param &connect)
CallbackManager< void(uint64_t)> passkey_request_callback_
Definition ble_server.h:134
std::vector< uint8_t > manufacturer_data_
Definition ble_server.h:146
esp_bd_addr_t client_addresses_[USE_ESP32_BLE_MAX_CONNECTIONS]
Definition ble_server.h:158
void remove_client_(uint16_t conn_id)
float get_setup_priority() const override
enum esphome::esp32_ble_server::BLEServer::State INIT
void dispatch_callbacks_(CallbackType type, uint16_t conn_id)
ESPHOME_ALWAYS_INLINE bool is_running()
Definition ble_server.h:34
void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
BLEService * get_service(ESPBTUUID uuid, uint8_t inst_id=0)
void passkey_reply(uint64_t address, uint32_t passkey)
Answer a passkey request from the connected client at address.
void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param)
std::vector< BLEService * > services_to_start_
Definition ble_server.h:163
bool is_client_address_(const esp_bd_addr_t address) const
BLEService * create_service(ESPBTUUID uuid, bool advertise=false, uint16_t num_handles=15)
void remove_service(ESPBTUUID uuid, uint8_t inst_id=0)
std::vector< ServiceEntry > services_
Definition ble_server.h:162
uint16_t clients_[USE_ESP32_BLE_MAX_CONNECTIONS]
Definition ble_server.h:155
CallbackManager< void(uint64_t, uint32_t)> numeric_comparison_request_callback_
Definition ble_server.h:140
int8_t find_client_index_(uint16_t conn_id) const
void numeric_comparison_reply(uint64_t address, bool accept)
Accept or reject a numeric comparison request from the connected client at address.
void remove_bond(uint64_t address)
CallbackManager< void(uint64_t, uint32_t)> passkey_notification_callback_
Definition ble_server.h:137
void do_create(BLEServer *server)
uint8_t type
void uint64_to_mac_msb_first(uint64_t address, uint8_t out[6])
Unpack a uint64 BLE address into printable (MSB-first) byte order — the order bd_addr_t / esp_bd_addr...
Definition ble_device.h:169
uint64_t ble_addr_to_uint64(const esp_bd_addr_t address)
Definition ble.h:38
ESPHOME_LOG_TAG(TAG, "esp32_ble")
constexpr float AFTER_BLUETOOTH
Definition component.h:49
char * format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase, colon separators)
Definition helpers.h:1754
static void uint32_t