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