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