ESPHome 2026.8.0
Loading...
Searching...
No Matches
ble_client_base.cpp
Go to the documentation of this file.
1#include "ble_client_base.h"
2
4#include "esphome/core/log.h"
5
6#ifdef USE_ESP32
7
8#include <esp_gap_ble_api.h>
9#include <esp_gatt_defs.h>
10#include <esp_gattc_api.h>
11
13
14static const char *const TAG = "esp32_ble_client";
15
16// Connection parameters are shared with the other GATT client backends
17// (ble_device_base/ble_client_state.h) so the platforms cannot drift.
18using ble_device_base::FAST_CONN_TIMEOUT;
19using ble_device_base::FAST_MAX_CONN_INTERVAL;
20using ble_device_base::FAST_MIN_CONN_INTERVAL;
21using ble_device_base::MEDIUM_CONN_TIMEOUT;
22using ble_device_base::MEDIUM_MAX_CONN_INTERVAL;
23using ble_device_base::MEDIUM_MIN_CONN_INTERVAL;
24static constexpr uint32_t DISCONNECTING_TIMEOUT = 10000; // 10s
25static const esp_bt_uuid_t NOTIFY_DESC_UUID = {
26 .len = ESP_UUID_LEN_16,
27 .uuid =
28 {
29 .uuid16 = ESP_GATT_UUID_CHAR_CLIENT_CONFIG,
30 },
31};
32
34 static uint8_t connection_index = 0;
35 this->connection_index_ = connection_index++;
36}
37
38void BLEClientBase::set_state(espbt::ClientState st) {
39 ESP_LOGV(TAG, "[%d] [%s] Set state %d", this->connection_index_, this->address_str_, (int) st);
40 ESPBTClient::set_state(st);
41}
42
44 if (!esp32_ble::global_ble->is_active()) {
45 this->set_state(espbt::ClientState::INIT);
46 return;
47 }
48 if (this->state() == espbt::ClientState::INIT) {
49 auto ret = esp_ble_gattc_app_register(this->app_id);
50 if (ret) {
51 ESP_LOGE(TAG, "gattc app register failed. app_id=%d code=%d", this->app_id, ret);
52 this->mark_failed();
53 }
54 this->set_state(espbt::ClientState::IDLE);
55 }
56 // If idle, we can disable the loop as connect()
57 // will enable it again when a connection is needed.
58 else if (this->state() == espbt::ClientState::IDLE) {
59 this->disable_loop();
60 } else if (this->state() == espbt::ClientState::DISCONNECTING &&
61 (millis() - this->disconnecting_started_) > DISCONNECTING_TIMEOUT) {
62 ESP_LOGE(TAG, "[%d] [%s] Timeout waiting for CLOSE_EVT after disconnect, forcing IDLE", this->connection_index_,
63 this->address_str_);
64 // release_services() must be called before set_idle_() — if we entered DISCONNECTING
65 // via unconditional_disconnect() (which doesn't call release_services()), and ESP-IDF
66 // never delivered CLOSE_EVT/DISCONNECT_EVT, services would leak without this call.
67 this->release_services();
68 this->set_idle_();
69 this->on_disconnect_complete(ESP_GATT_CONN_TIMEOUT);
70 }
71}
72
74
76 ESP_LOGCONFIG(TAG,
77 " Address: %s\n"
78 " Auto-Connect: %s\n"
79 " State: %s",
80 this->address_str(), TRUEFALSE(this->auto_connect_), espbt::client_state_to_string(this->state()));
81 if (this->status_ == ESP_GATT_NO_RESOURCES) {
82 ESP_LOGE(TAG, " Failed due to no resources. Try to reduce number of BLE clients in config.");
83 } else if (this->status_ != ESP_GATT_OK) {
84 ESP_LOGW(TAG, " Failed due to error code %d", this->status_);
85 }
86}
87
88#ifdef USE_ESP32_BLE_DEVICE
90 if (!this->auto_connect_)
91 return false;
92 if (this->address_ == 0 || device.address_uint64() != this->address_)
93 return false;
94 if (this->state() != espbt::ClientState::IDLE)
95 return false;
96
97 this->log_event_("Found device");
98 if (ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG)
100
101 this->set_state(espbt::ClientState::DISCOVERED);
102 this->set_address(device.address_uint64());
103 this->remote_addr_type_ = device.get_address_type();
104 return true;
105}
106#endif
107
109 // Prevent duplicate connection attempts or connecting while still disconnecting
110 if (this->state() == espbt::ClientState::CONNECTING || this->state() == espbt::ClientState::CONNECTED ||
111 this->state() == espbt::ClientState::ESTABLISHED) {
112 ESP_LOGW(TAG, "[%d] [%s] Connection already in progress, state=%s", this->connection_index_, this->address_str_,
113 espbt::client_state_to_string(this->state()));
114 return;
115 } else if (this->state() == espbt::ClientState::DISCONNECTING) {
116 ESP_LOGW(TAG, "[%d] [%s] Cannot connect, still waiting for CLOSE_EVT to complete disconnect",
117 this->connection_index_, this->address_str_);
118 return;
119 }
120 ESP_LOGI(TAG, "[%d] [%s] 0x%02x Connecting", this->connection_index_, this->address_str_, this->remote_addr_type_);
121 this->paired_ = false;
122 // A registration whose event never arrived must not block this connection's release.
123 this->services_released_ = false;
124 this->pending_notify_regs_ = 0;
125 // Enable loop for state processing
126 this->enable_loop();
127 // Immediately transition to CONNECTING to prevent duplicate connection attempts
128 this->set_state(espbt::ClientState::CONNECTING);
129
130 // Determine connection parameters based on connection type
131 if (this->connection_type_ == espbt::ConnectionType::V3_WITHOUT_CACHE) {
132 // V3 without cache needs fast params for service discovery
133 this->set_conn_params_(FAST_MIN_CONN_INTERVAL, FAST_MAX_CONN_INTERVAL, 0, FAST_CONN_TIMEOUT, "fast");
134 } else if (this->connection_type_ == espbt::ConnectionType::V3_WITH_CACHE) {
135 // V3 with cache can use medium params
136 this->set_conn_params_(MEDIUM_MIN_CONN_INTERVAL, MEDIUM_MAX_CONN_INTERVAL, 0, MEDIUM_CONN_TIMEOUT, "medium");
137 }
138 // For V1/Legacy, don't set params - use ESP-IDF defaults
139
140 // Open the connection
141 auto ret = esp_ble_gattc_open(this->gattc_if_, this->remote_bda_, this->remote_addr_type_, true);
143}
144
145esp_err_t BLEClientBase::pair() { return esp_ble_set_encryption(this->remote_bda_, ESP_BLE_SEC_ENCRYPT); }
146
148 if (this->state() == espbt::ClientState::IDLE || this->state() == espbt::ClientState::DISCONNECTING) {
149 ESP_LOGI(TAG, "[%d] [%s] Disconnect requested, but already %s", this->connection_index_, this->address_str_,
150 espbt::client_state_to_string(this->state()));
151 return;
152 }
153 if (this->state() == espbt::ClientState::CONNECTING || this->conn_id_ == UNSET_CONN_ID) {
154 ESP_LOGD(TAG, "[%d] [%s] Disconnect before connected, disconnect scheduled", this->connection_index_,
155 this->address_str_);
156 this->want_disconnect_ = true;
157 return;
158 }
160}
161
163 // Disconnect without checking the state.
164 ESP_LOGI(TAG, "[%d] [%s] Disconnecting (conn_id: %d).", this->connection_index_, this->address_str_, this->conn_id_);
165 if (this->state() == espbt::ClientState::DISCONNECTING) {
166 this->log_error_("Already disconnecting");
167 return;
168 }
169 if (this->conn_id_ == UNSET_CONN_ID) {
170 this->log_error_("conn id unset, cannot disconnect");
171 return;
172 }
173 auto err = esp_ble_gattc_close(this->gattc_if_, this->conn_id_);
174 if (err != ESP_OK) {
175 //
176 // This is a fatal error, but we can't do anything about it
177 // and it likely means the BLE stack is in a bad state.
178 //
179 // In the future we might consider App.reboot() here since
180 // the BLE stack is in an indeterminate state.
181 //
182 this->log_gattc_warning_("esp_ble_gattc_close", err);
183 }
184
185 if (this->state() == espbt::ClientState::DISCOVERED) {
186 this->set_address(0);
187 this->set_state(espbt::ClientState::IDLE);
188 } else {
189 this->set_disconnecting_();
190 }
191}
192
194#ifdef USE_ESP32_BLE_DEVICE
195 for (auto &svc : this->services_)
196 delete svc; // NOLINT(cppcoreguidelines-owning-memory)
197 this->services_.clear();
198#endif
199#ifndef CONFIG_BT_GATTC_CACHE_NVS_FLASH
200 // Only the cache clean makes the stack's database unsafe to walk.
201 this->services_released_ = true;
202 esp_ble_gattc_cache_clean(this->remote_bda_);
203#endif
204}
205
206esp_err_t BLEClientBase::register_for_notify(uint16_t char_handle) {
207 esp_err_t err = esp_ble_gattc_register_for_notify(this->gattc_if_, this->remote_bda_, char_handle);
208 if (err != ESP_OK)
209 return err;
210 if (this->pending_notify_regs_ == UINT8_MAX) {
211 // Saturating undercounts, so the release can run before the last registration completes.
212 // Wrapping to zero would undercount by the full range instead, which is worse.
213 this->log_warning_("Too many outstanding notify registrations to track");
214 return err;
215 }
216 this->pending_notify_regs_++;
217 return err;
218}
219
220void BLEClientBase::log_event_(const char *name) {
221 ESP_LOGD(TAG, "[%d] [%s] %s", this->connection_index_, this->address_str_, name);
222}
223
225 ESP_LOGD(TAG, "[%d] [%s] ESP_GATTC_%s_EVT", this->connection_index_, this->address_str_, name);
226}
227
229 // Data transfer events are logged at VERBOSE level because logging to UART creates
230 // delays that cause timing issues during time-sensitive BLE operations. This is
231 // especially problematic during pairing or firmware updates which require rapid
232 // writes to many characteristics - the log spam can cause these operations to fail.
233 ESP_LOGV(TAG, "[%d] [%s] ESP_GATTC_%s_EVT", this->connection_index_, this->address_str_, name);
234}
235
236void BLEClientBase::log_gattc_warning_(const char *operation, esp_gatt_status_t status) {
237 ESP_LOGW(TAG, "[%d] [%s] %s error, status=%d", this->connection_index_, this->address_str_, operation, status);
238}
239
240void BLEClientBase::log_gattc_warning_(const char *operation, esp_err_t err) {
241 ESP_LOGW(TAG, "[%d] [%s] %s error, status=%d", this->connection_index_, this->address_str_, operation, err);
242}
243
244void BLEClientBase::log_connection_params_(const char *param_type) {
245 ESP_LOGD(TAG, "[%d] [%s] %s conn params", this->connection_index_, this->address_str_, param_type);
246}
247
249 if (ret) {
250 this->log_gattc_warning_("esp_ble_gattc_open", ret);
251 // Don't use set_idle_() here — CONNECT_EVT never fired so conn_id_ is still UNSET_CONN_ID.
252 this->set_state(espbt::ClientState::IDLE);
253 }
254}
255
257 ESP_LOGE(TAG, "[%d] [%s] %s", this->connection_index_, this->address_str_, message);
258}
259
260void BLEClientBase::log_error_(const char *message, int code) {
261 ESP_LOGE(TAG, "[%d] [%s] %s=%d", this->connection_index_, this->address_str_, message, code);
262}
263
265 ESP_LOGW(TAG, "[%d] [%s] %s", this->connection_index_, this->address_str_, message);
266}
267
268esp_err_t BLEClientBase::update_conn_params_(uint16_t min_interval, uint16_t max_interval, uint16_t latency,
269 uint16_t timeout, const char *param_type) {
270 esp_ble_conn_update_params_t conn_params = {{0}};
271 memcpy(conn_params.bda, this->remote_bda_, sizeof(esp_bd_addr_t));
272 conn_params.min_int = min_interval;
273 conn_params.max_int = max_interval;
274 conn_params.latency = latency;
275 conn_params.timeout = timeout;
276 this->log_connection_params_(param_type);
277 esp_err_t err = esp_ble_gap_update_conn_params(&conn_params);
278 if (err != ESP_OK) {
279 this->log_gattc_warning_("esp_ble_gap_update_conn_params", err);
280 }
281 return err;
282}
283
284void BLEClientBase::set_conn_params_(uint16_t min_interval, uint16_t max_interval, uint16_t latency, uint16_t timeout,
285 const char *param_type) {
286 // Set preferred connection parameters before connecting
287 // These will be used when establishing the connection
288 this->log_connection_params_(param_type);
289 esp_err_t err = esp_ble_gap_set_prefer_conn_params(this->remote_bda_, min_interval, max_interval, latency, timeout);
290 if (err != ESP_OK) {
291 this->log_gattc_warning_("esp_ble_gap_set_prefer_conn_params", err);
292 }
293}
294
295bool BLEClientBase::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t esp_gattc_if,
296 esp_ble_gattc_cb_param_t *param) {
297 if (event == ESP_GATTC_REG_EVT && this->app_id != param->reg.app_id)
298 return false;
299 if (event != ESP_GATTC_REG_EVT && esp_gattc_if != ESP_GATT_IF_NONE && esp_gattc_if != this->gattc_if_)
300 return false;
301
302 ESP_LOGV(TAG, "[%d] [%s] gattc_event_handler: event=%d gattc_if=%d", this->connection_index_, this->address_str_,
303 event, esp_gattc_if);
304
305 switch (event) {
306 case ESP_GATTC_REG_EVT: {
307 if (param->reg.status == ESP_GATT_OK) {
308 ESP_LOGV(TAG, "[%d] [%s] gattc registered app id %d", this->connection_index_, this->address_str_,
309 this->app_id);
310 this->gattc_if_ = esp_gattc_if;
311 } else {
312 this->log_error_("gattc app registration failed status", param->reg.status);
313 this->status_ = param->reg.status;
314 this->mark_failed();
315 }
316 break;
317 }
318 case ESP_GATTC_OPEN_EVT: {
319 if (!this->check_addr(param->open.remote_bda))
320 return false;
321 this->log_gattc_lifecycle_event_("OPEN");
322 // conn_id was already set in ESP_GATTC_CONNECT_EVT
323 this->service_count_ = 0;
324
325 // ESP-IDF's BLE stack may send ESP_GATTC_OPEN_EVT after esp_ble_gattc_open() returns an
326 // error, if the error occurred at the BTA/GATT layer. This can result in the event
327 // arriving after we've already transitioned to IDLE state.
328 if (this->state() == espbt::ClientState::IDLE) {
329 ESP_LOGD(TAG, "[%d] [%s] ESP_GATTC_OPEN_EVT in IDLE state (status=%d), ignoring", this->connection_index_,
330 this->address_str_, param->open.status);
331 break;
332 }
333
334 if (this->state() != espbt::ClientState::CONNECTING) {
335 // This should not happen but lets log it in case it does
336 // because it means we have a bad assumption about how the
337 // ESP BT stack works.
338 ESP_LOGE(TAG, "[%d] [%s] ESP_GATTC_OPEN_EVT in %s state (status=%d)", this->connection_index_,
339 this->address_str_, espbt::client_state_to_string(this->state()), param->open.status);
340 }
341 if (param->open.status != ESP_GATT_OK && param->open.status != ESP_GATT_ALREADY_OPEN) {
342 this->log_gattc_warning_("Connection open", param->open.status);
343 // Connection was never established so CLOSE_EVT may not follow
344 this->set_idle_();
345 break;
346 }
347 if (this->want_disconnect_) {
348 // Disconnect was requested after connecting started,
349 // but before the connection was established. Now that we have
350 // this->conn_id_ set, we can disconnect it.
351 // Don't reset conn_id_ here — CLOSE_EVT needs it to match and call set_idle_().
353 break;
354 }
355 // MTU negotiation already started in ESP_GATTC_CONNECT_EVT
356 this->set_state(espbt::ClientState::CONNECTED);
357 ESP_LOGI(TAG, "[%d] [%s] Connection open", this->connection_index_, this->address_str_);
358 if (this->connection_type_ == espbt::ConnectionType::V3_WITH_CACHE) {
359 // Cached connections already connected with medium parameters, no update needed
360 // only set our state, subclients might have more stuff to do yet.
361 this->set_state_internal_(espbt::ClientState::ESTABLISHED);
362 break;
363 }
364 // For V3_WITHOUT_CACHE, we already set fast params before connecting
365 // No need to update them again here
366 this->log_event_("Searching for services");
367 esp_ble_gattc_search_service(esp_gattc_if, param->open.conn_id, nullptr);
368 break;
369 }
370 case ESP_GATTC_CONNECT_EVT: {
371 if (!this->check_addr(param->connect.remote_bda))
372 return false;
373 this->log_gattc_lifecycle_event_("CONNECT");
374 this->conn_id_ = param->connect.conn_id;
375 // Start MTU negotiation immediately as recommended by ESP-IDF examples
376 // (gatt_client, ble_throughput) which call esp_ble_gattc_send_mtu_req in
377 // ESP_GATTC_CONNECT_EVT instead of waiting for ESP_GATTC_OPEN_EVT.
378 // This saves ~3ms in the connection process.
379 auto ret = esp_ble_gattc_send_mtu_req(this->gattc_if_, param->connect.conn_id);
380 if (ret) {
381 this->log_gattc_warning_("esp_ble_gattc_send_mtu_req", ret);
382 }
383 break;
384 }
385 case ESP_GATTC_DISCONNECT_EVT: {
386 if (!this->check_addr(param->disconnect.remote_bda))
387 return false;
388 // Check if we were disconnected while waiting for service discovery
389 if (param->disconnect.reason == ESP_GATT_CONN_TERMINATE_PEER_USER &&
390 this->state() == espbt::ClientState::CONNECTED) {
391 this->log_warning_("Remote closed during discovery");
392 } else {
393 ESP_LOGD(TAG, "[%d] [%s] ESP_GATTC_DISCONNECT_EVT, reason 0x%02x", this->connection_index_, this->address_str_,
394 param->disconnect.reason);
395 }
396 // For active disconnects (esp_ble_gattc_close), CLOSE_EVT arrives before
397 // DISCONNECT_EVT. If CLOSE_EVT already transitioned us to IDLE, don't go
398 // backwards to DISCONNECTING — the connection is already fully cleaned up.
399 if (this->state() == espbt::ClientState::IDLE) {
400 this->log_event_("DISCONNECT_EVT after CLOSE_EVT, already IDLE");
401 break;
402 }
403 // For passive disconnects (remote device disconnected or link lost),
404 // DISCONNECT_EVT arrives first. Don't transition to IDLE yet — wait for
405 // CLOSE_EVT to ensure the controller has fully freed resources (L2CAP
406 // channels, ATT resources, HCI connection handle). Transitioning to IDLE
407 // here would allow reconnection before cleanup is complete, causing the
408 // controller to reject the new connection (status=133) or crash with
409 // ASSERT_PARAM in lld_evt.c.
410 this->release_services();
411 this->set_disconnecting_();
412 break;
413 }
414
415 case ESP_GATTC_CFG_MTU_EVT: {
416 if (this->conn_id_ != param->cfg_mtu.conn_id)
417 return false;
418 if (param->cfg_mtu.status != ESP_GATT_OK) {
419 ESP_LOGW(TAG, "[%d] [%s] cfg_mtu failed, mtu %d, status %d", this->connection_index_, this->address_str_,
420 param->cfg_mtu.mtu, param->cfg_mtu.status);
421 // No state change required here - disconnect event will follow if needed.
422 break;
423 }
424 ESP_LOGD(TAG, "[%d] [%s] cfg_mtu status %d, mtu %d", this->connection_index_, this->address_str_,
425 param->cfg_mtu.status, param->cfg_mtu.mtu);
426 this->mtu_ = param->cfg_mtu.mtu;
427 break;
428 }
429 case ESP_GATTC_CLOSE_EVT: {
430 if (this->conn_id_ != param->close.conn_id)
431 return false;
432 this->log_gattc_lifecycle_event_("CLOSE");
433 this->release_services();
434 this->set_idle_();
435 this->on_disconnect_complete(param->close.reason);
436 break;
437 }
438 case ESP_GATTC_SEARCH_RES_EVT: {
439 if (this->conn_id_ != param->search_res.conn_id)
440 return false;
441 this->service_count_++;
442 if (this->connection_type_ == espbt::ConnectionType::V3_WITHOUT_CACHE) {
443 // V3 clients don't need services initialized since
444 // as they use the ESP APIs to get services.
445 break;
446 }
447#ifdef USE_ESP32_BLE_DEVICE
448 BLEService *ble_service = new BLEService(); // NOLINT(cppcoreguidelines-owning-memory)
449 ble_service->uuid = espbt::ESPBTUUID::from_uuid(param->search_res.srvc_id.uuid);
450 ble_service->start_handle = param->search_res.start_handle;
451 ble_service->end_handle = param->search_res.end_handle;
452 ble_service->client = this;
453 this->services_.push_back(ble_service);
454#endif
455 break;
456 }
457 case ESP_GATTC_SEARCH_CMPL_EVT: {
458 if (this->conn_id_ != param->search_cmpl.conn_id)
459 return false;
460 this->log_gattc_lifecycle_event_("SEARCH_CMPL");
461 // For V3_WITHOUT_CACHE, switch back to medium connection parameters after service discovery
462 // This balances performance with bandwidth usage after the critical discovery phase
463 if (this->connection_type_ == espbt::ConnectionType::V3_WITHOUT_CACHE) {
464 this->update_conn_params_(MEDIUM_MIN_CONN_INTERVAL, MEDIUM_MAX_CONN_INTERVAL, 0, MEDIUM_CONN_TIMEOUT, "medium");
465 } else if (this->connection_type_ != espbt::ConnectionType::V3_WITH_CACHE) {
466#ifdef USE_ESP32_BLE_DEVICE
467#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
468 for (auto &svc : this->services_) {
469 char uuid_buf[espbt::UUID_STR_LEN];
470 svc->uuid.to_str(uuid_buf);
471 ESP_LOGV(TAG, "[%d] [%s] Service UUID: %s", this->connection_index_, this->address_str_, uuid_buf);
472 ESP_LOGV(TAG, "[%d] [%s] start_handle: 0x%x end_handle: 0x%x", this->connection_index_, this->address_str_,
473 svc->start_handle, svc->end_handle);
474 }
475#endif
476#endif
477 }
478 ESP_LOGI(TAG, "[%d] [%s] Service discovery complete", this->connection_index_, this->address_str_);
479 this->set_state_internal_(espbt::ClientState::ESTABLISHED);
480 break;
481 }
482 case ESP_GATTC_READ_DESCR_EVT: {
483 if (this->conn_id_ != param->write.conn_id)
484 return false;
485 this->log_gattc_data_event_("READ_DESCR");
486 break;
487 }
488 case ESP_GATTC_WRITE_DESCR_EVT: {
489 if (this->conn_id_ != param->write.conn_id)
490 return false;
491 this->log_gattc_data_event_("WRITE_DESCR");
492 break;
493 }
494 case ESP_GATTC_WRITE_CHAR_EVT: {
495 if (this->conn_id_ != param->write.conn_id)
496 return false;
497 this->log_gattc_data_event_("WRITE_CHAR");
498 break;
499 }
500 case ESP_GATTC_READ_CHAR_EVT: {
501 if (this->conn_id_ != param->read.conn_id)
502 return false;
503 this->log_gattc_data_event_("READ_CHAR");
504 break;
505 }
506 case ESP_GATTC_NOTIFY_EVT: {
507 if (this->conn_id_ != param->notify.conn_id)
508 return false;
509 this->log_gattc_data_event_("NOTIFY");
510 break;
511 }
512 case ESP_GATTC_REG_FOR_NOTIFY_EVT: {
513 this->log_gattc_data_event_("REG_FOR_NOTIFY");
514 // The event carries no conn_id, so this is the only place the request can be retired.
515 if (this->pending_notify_regs_ > 0)
516 this->pending_notify_regs_--;
517 if (this->connection_type_ == espbt::ConnectionType::V3_WITH_CACHE ||
518 this->connection_type_ == espbt::ConnectionType::V3_WITHOUT_CACHE) {
519 // Client is responsible for flipping the descriptor value
520 // when using the cache
521 break;
522 }
523 if (this->services_released_) {
524 // The lookup below walks the freed GATT cache, and Bluedroid asserts on it rather than erroring.
525 this->log_warning_("REG_FOR_NOTIFY after services released, notifications not enabled");
526 break;
527 }
528 esp_gattc_descr_elem_t desc_result;
529 uint16_t count = 1;
530 esp_gatt_status_t descr_status = esp_ble_gattc_get_descr_by_char_handle(
531 this->gattc_if_, this->conn_id_, param->reg_for_notify.handle, NOTIFY_DESC_UUID, &desc_result, &count);
532 if (descr_status != ESP_GATT_OK) {
533 this->log_gattc_warning_("esp_ble_gattc_get_descr_by_char_handle", descr_status);
534 break;
535 }
536 esp_gattc_char_elem_t char_result;
537 esp_gatt_status_t char_status =
538 esp_ble_gattc_get_all_char(this->gattc_if_, this->conn_id_, param->reg_for_notify.handle,
539 param->reg_for_notify.handle, &char_result, &count, 0);
540 if (char_status != ESP_GATT_OK) {
541 this->log_gattc_warning_("esp_ble_gattc_get_all_char", char_status);
542 break;
543 }
544
545 /*
546 1 = notify
547 2 = indicate
548 */
549 uint16_t notify_en = char_result.properties & ESP_GATT_CHAR_PROP_BIT_NOTIFY ? 1 : 2;
550 esp_err_t status =
551 esp_ble_gattc_write_char_descr(this->gattc_if_, this->conn_id_, desc_result.handle, sizeof(notify_en),
552 (uint8_t *) &notify_en, ESP_GATT_WRITE_TYPE_RSP, ESP_GATT_AUTH_REQ_NONE);
553 ESP_LOGV(TAG, "Wrote notify descriptor %d, properties=%d", notify_en, char_result.properties);
554 if (status) {
555 this->log_gattc_warning_("esp_ble_gattc_write_char_descr", status);
556 }
557 break;
558 }
559
560 case ESP_GATTC_UNREG_FOR_NOTIFY_EVT: {
561 this->log_gattc_data_event_("UNREG_FOR_NOTIFY");
562 break;
563 }
564
565 default:
566 // Unknown events logged at VERBOSE to avoid UART delays during time-sensitive operations
567 ESP_LOGV(TAG, "[%d] [%s] Event %d", this->connection_index_, this->address_str_, event);
568 break;
569 }
570 return true;
571}
572
573// clients can't call defer() directly since it's protected.
574void BLEClientBase::run_later(std::function<void()> &&f) { // NOLINT
575 this->defer(std::move(f));
576}
577
578void BLEClientBase::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
579 switch (event) {
580 // This event is sent by the server when it requests security
581 case ESP_GAP_BLE_SEC_REQ_EVT:
582 if (!this->check_addr(param->ble_security.auth_cmpl.bd_addr))
583 return;
584 ESP_LOGV(TAG, "[%d] [%s] ESP_GAP_BLE_SEC_REQ_EVT %x", this->connection_index_, this->address_str_, event);
585 esp_ble_gap_security_rsp(param->ble_security.ble_req.bd_addr, true);
586 break;
587 // This event is sent once authentication has completed
588 case ESP_GAP_BLE_AUTH_CMPL_EVT:
589 if (!this->check_addr(param->ble_security.auth_cmpl.bd_addr))
590 return;
591 char addr_str[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
592 format_mac_addr_upper(param->ble_security.auth_cmpl.bd_addr, addr_str);
593 ESP_LOGI(TAG, "[%d] [%s] auth complete addr: %s", this->connection_index_, this->address_str_, addr_str);
594 if (!param->ble_security.auth_cmpl.success) {
595 this->log_error_("auth fail reason", param->ble_security.auth_cmpl.fail_reason);
596 } else {
597 this->paired_ = true;
598 ESP_LOGD(TAG, "[%d] [%s] auth success type = %d mode = %d", this->connection_index_, this->address_str_,
599 param->ble_security.auth_cmpl.addr_type, param->ble_security.auth_cmpl.auth_mode);
600 }
601 break;
602
603 // There are other events we'll want to implement at some point to support things like pass key
604 // https://github.com/espressif/esp-idf/blob/cba69dd088344ed9d26739f04736ae7a37541b3a/examples/bluetooth/bluedroid/ble/gatt_security_client/tutorial/Gatt_Security_Client_Example_Walkthrough.md
605 default:
606 break;
607 }
608}
609
610// Parse GATT values into a float for a sensor.
611// Ref: https://www.bluetooth.com/specifications/assigned-numbers/format-types/
612float BLEClientBase::parse_char_value(uint8_t *value, uint16_t length) {
613 // A length of one means a single octet value.
614 if (length == 0)
615 return 0;
616 if (length == 1)
617 return (float) ((uint8_t) value[0]);
618
619 switch (value[0]) {
620 case 0x1: // boolean.
621 case 0x2: // 2bit.
622 case 0x3: // nibble.
623 case 0x4: // uint8.
624 return (float) ((uint8_t) value[1]);
625 case 0x5: // uint12.
626 case 0x6: // uint16.
627 if (length > 2) {
628 return (float) encode_uint16(value[1], value[2]);
629 }
630 [[fallthrough]];
631 case 0x7: // uint24.
632 if (length > 3) {
633 return (float) encode_uint24(value[1], value[2], value[3]);
634 }
635 [[fallthrough]];
636 case 0x8: // uint32.
637 if (length > 4) {
638 return (float) encode_uint32(value[1], value[2], value[3], value[4]);
639 }
640 [[fallthrough]];
641 case 0xC: // int8.
642 return (float) ((int8_t) value[1]);
643 case 0xD: // int12.
644 case 0xE: // int16.
645 if (length > 2) {
646 return (float) ((int16_t) (value[1] << 8) + (int16_t) value[2]);
647 }
648 [[fallthrough]];
649 case 0xF: // int24.
650 if (length > 3) {
651 return (float) ((int32_t) (value[1] << 16) + (int32_t) (value[2] << 8) + (int32_t) (value[3]));
652 }
653 [[fallthrough]];
654 case 0x10: // int32.
655 if (length > 4) {
656 return (float) ((int32_t) (value[1] << 24) + (int32_t) (value[2] << 16) + (int32_t) (value[3] << 8) +
657 (int32_t) (value[4]));
658 }
659 }
660 ESP_LOGW(TAG, "[%d] [%s] Cannot parse characteristic value of type 0x%x length %d", this->connection_index_,
661 this->address_str_, value[0], length);
662 return NAN;
663}
664
665#ifdef USE_ESP32_BLE_DEVICE
667 for (auto *svc : this->services_) {
668 if (svc->uuid == uuid)
669 return svc;
670 }
671 return nullptr;
672}
673
674BLEService *BLEClientBase::get_service(uint16_t uuid) { return this->get_service(espbt::ESPBTUUID::from_uint16(uuid)); }
675
677 auto *svc = this->get_service(service);
678 if (svc == nullptr)
679 return nullptr;
680 return svc->get_characteristic(chr);
681}
682
683BLECharacteristic *BLEClientBase::get_characteristic(uint16_t service, uint16_t chr) {
684 return this->get_characteristic(espbt::ESPBTUUID::from_uint16(service), espbt::ESPBTUUID::from_uint16(chr));
685}
686
688 for (auto *svc : this->services_) {
689 if (!svc->parsed)
690 svc->parse_characteristics();
691 for (auto *chr : svc->characteristics) {
692 if (chr->handle == handle)
693 return chr;
694 }
695 }
696 return nullptr;
697}
698
700 auto *chr = this->get_characteristic(handle);
701 if (chr != nullptr) {
702 if (!chr->parsed)
703 chr->parse_descriptors();
704 for (auto &desc : chr->descriptors) {
705 if (desc->uuid.get_uuid().uuid.uuid16 == ESP_GATT_UUID_CHAR_CLIENT_CONFIG)
706 return desc;
707 }
708 }
709 return nullptr;
710}
711
713 auto *svc = this->get_service(service);
714 if (svc == nullptr)
715 return nullptr;
716 auto *ch = svc->get_characteristic(chr);
717 if (ch == nullptr)
718 return nullptr;
719 return ch->get_descriptor(descr);
720}
721
722BLEDescriptor *BLEClientBase::get_descriptor(uint16_t service, uint16_t chr, uint16_t descr) {
723 return this->get_descriptor(espbt::ESPBTUUID::from_uint16(service), espbt::ESPBTUUID::from_uint16(chr),
724 espbt::ESPBTUUID::from_uint16(descr));
725}
726
728 for (auto *svc : this->services_) {
729 if (!svc->parsed)
730 svc->parse_characteristics();
731 for (auto *chr : svc->characteristics) {
732 if (!chr->parsed)
733 chr->parse_descriptors();
734 for (auto *desc : chr->descriptors) {
735 if (desc->handle == handle)
736 return desc;
737 }
738 }
739 }
740 return nullptr;
741}
742#endif // USE_ESP32_BLE_DEVICE
743
744} // namespace esphome::esp32_ble_client
745
746#endif // USE_ESP32
uint8_t status
Definition bl0942.h:8
void mark_failed()
Mark this component as failed.
void enable_loop()
Enable this component's loop.
Definition component.h:246
void defer(const char *name, std::function< void()> &&f)
Defer a callback to the next loop() call with a const char* name.
void disable_loop()
Disable this component's loop.
esp_ble_addr_type_t get_address_type() const
Definition ble_device.h:204
uint64_t address_uint64() const
Return MAC as packed uint64 (byte 0 in LSB — matches esp32's address_uint64).
std::vector< BLEService * > services_
char address_str_[MAC_ADDRESS_PRETTY_BUFFER_SIZE]
void log_gattc_warning_(const char *operation, esp_gatt_status_t status)
void log_connection_params_(const char *param_type)
BLEDescriptor * get_descriptor(espbt::ESPBTUUID service, espbt::ESPBTUUID chr, espbt::ESPBTUUID descr)
void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) override
void set_state(espbt::ClientState st) override
esp_err_t register_for_notify(uint16_t char_handle)
Register for notifications, holding the service release until the registration completes.
esp_err_t update_conn_params_(uint16_t min_interval, uint16_t max_interval, uint16_t latency, uint16_t timeout, const char *param_type)
BLECharacteristic * get_characteristic(espbt::ESPBTUUID service, espbt::ESPBTUUID chr)
virtual void set_address(uint64_t address)
void set_idle_()
Transition to IDLE and reset conn_id — call when the connection is fully dead.
void run_later(std::function< void()> &&f)
virtual void on_disconnect_complete(esp_err_t reason)
Hook called once a connection has been fully torn down (after release_services() and set_idle_()),...
BLEService * get_service(espbt::ESPBTUUID uuid)
void set_disconnecting_()
Transition to DISCONNECTING and start the safety timeout.
bool gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) override
bool parse_device(const espbt::ESPBTDevice &device) override
float parse_char_value(uint8_t *value, uint16_t length)
BLEDescriptor * get_config_descriptor(uint16_t handle)
void set_conn_params_(uint16_t min_interval, uint16_t max_interval, uint16_t latency, uint16_t timeout, const char *param_type)
void print_bt_device_info(const ESPBTDevice &device)
void set_state_internal_(ClientState st)
Set state without IDLE handling - use for direct state transitions.
const LogString * message
Definition component.cpp:35
int ret
ESP32BLETracker * global_esp32_ble_tracker
ESP32BLE * global_ble
Definition ble.cpp:775
constexpr float AFTER_BLUETOOTH
Definition component.h:49
constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3)
Encode a 24-bit value given three bytes in most to least significant byte order.
Definition helpers.h:887
constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4)
Encode a 32-bit value given four bytes in most to least significant byte order.
Definition helpers.h:891
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition helpers.h:883
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:28
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:1493
static void uint32_t
uint16_t length
Definition tt21100.cpp:0
spi_device_handle_t handle