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