ESPHome 2026.1.0-dev
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#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
415 for (auto &svc : this->services_) {
416 char uuid_buf[espbt::UUID_STR_LEN];
417 svc->uuid.to_str(uuid_buf);
418 ESP_LOGV(TAG, "[%d] [%s] Service UUID: %s", this->connection_index_, this->address_str_, uuid_buf);
419 ESP_LOGV(TAG, "[%d] [%s] start_handle: 0x%x end_handle: 0x%x", this->connection_index_, this->address_str_,
420 svc->start_handle, svc->end_handle);
421 }
422#endif
423#endif
424 }
425 ESP_LOGI(TAG, "[%d] [%s] Service discovery complete", this->connection_index_, this->address_str_);
426 this->state_ = espbt::ClientState::ESTABLISHED;
427 break;
428 }
429 case ESP_GATTC_READ_DESCR_EVT: {
430 if (this->conn_id_ != param->write.conn_id)
431 return false;
432 this->log_gattc_event_("READ_DESCR");
433 break;
434 }
435 case ESP_GATTC_WRITE_DESCR_EVT: {
436 if (this->conn_id_ != param->write.conn_id)
437 return false;
438 this->log_gattc_event_("WRITE_DESCR");
439 break;
440 }
441 case ESP_GATTC_WRITE_CHAR_EVT: {
442 if (this->conn_id_ != param->write.conn_id)
443 return false;
444 this->log_gattc_event_("WRITE_CHAR");
445 break;
446 }
447 case ESP_GATTC_READ_CHAR_EVT: {
448 if (this->conn_id_ != param->read.conn_id)
449 return false;
450 this->log_gattc_event_("READ_CHAR");
451 break;
452 }
453 case ESP_GATTC_NOTIFY_EVT: {
454 if (this->conn_id_ != param->notify.conn_id)
455 return false;
456 this->log_gattc_event_("NOTIFY");
457 break;
458 }
459 case ESP_GATTC_REG_FOR_NOTIFY_EVT: {
460 this->log_gattc_event_("REG_FOR_NOTIFY");
461 if (this->connection_type_ == espbt::ConnectionType::V3_WITH_CACHE ||
462 this->connection_type_ == espbt::ConnectionType::V3_WITHOUT_CACHE) {
463 // Client is responsible for flipping the descriptor value
464 // when using the cache
465 break;
466 }
467 esp_gattc_descr_elem_t desc_result;
468 uint16_t count = 1;
469 esp_gatt_status_t descr_status = esp_ble_gattc_get_descr_by_char_handle(
470 this->gattc_if_, this->conn_id_, param->reg_for_notify.handle, NOTIFY_DESC_UUID, &desc_result, &count);
471 if (descr_status != ESP_GATT_OK) {
472 this->log_gattc_warning_("esp_ble_gattc_get_descr_by_char_handle", descr_status);
473 break;
474 }
475 esp_gattc_char_elem_t char_result;
476 esp_gatt_status_t char_status =
477 esp_ble_gattc_get_all_char(this->gattc_if_, this->conn_id_, param->reg_for_notify.handle,
478 param->reg_for_notify.handle, &char_result, &count, 0);
479 if (char_status != ESP_GATT_OK) {
480 this->log_gattc_warning_("esp_ble_gattc_get_all_char", char_status);
481 break;
482 }
483
484 /*
485 1 = notify
486 2 = indicate
487 */
488 uint16_t notify_en = char_result.properties & ESP_GATT_CHAR_PROP_BIT_NOTIFY ? 1 : 2;
489 esp_err_t status =
490 esp_ble_gattc_write_char_descr(this->gattc_if_, this->conn_id_, desc_result.handle, sizeof(notify_en),
491 (uint8_t *) &notify_en, ESP_GATT_WRITE_TYPE_RSP, ESP_GATT_AUTH_REQ_NONE);
492 ESP_LOGD(TAG, "Wrote notify descriptor %d, properties=%d", notify_en, char_result.properties);
493 if (status) {
494 this->log_gattc_warning_("esp_ble_gattc_write_char_descr", status);
495 }
496 break;
497 }
498
499 case ESP_GATTC_UNREG_FOR_NOTIFY_EVT: {
500 this->log_gattc_event_("UNREG_FOR_NOTIFY");
501 break;
502 }
503
504 default:
505 // ideally would check all other events for matching conn_id
506 ESP_LOGD(TAG, "[%d] [%s] Event %d", this->connection_index_, this->address_str_, event);
507 break;
508 }
509 return true;
510}
511
512// clients can't call defer() directly since it's protected.
513void BLEClientBase::run_later(std::function<void()> &&f) { // NOLINT
514 this->defer(std::move(f));
515}
516
517void BLEClientBase::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
518 switch (event) {
519 // This event is sent by the server when it requests security
520 case ESP_GAP_BLE_SEC_REQ_EVT:
521 if (!this->check_addr(param->ble_security.auth_cmpl.bd_addr))
522 return;
523 ESP_LOGV(TAG, "[%d] [%s] ESP_GAP_BLE_SEC_REQ_EVT %x", this->connection_index_, this->address_str_, event);
524 esp_ble_gap_security_rsp(param->ble_security.ble_req.bd_addr, true);
525 break;
526 // This event is sent once authentication has completed
527 case ESP_GAP_BLE_AUTH_CMPL_EVT:
528 if (!this->check_addr(param->ble_security.auth_cmpl.bd_addr))
529 return;
530 char addr_str[MAC_ADDR_STR_LEN];
531 format_mac_addr_upper(param->ble_security.auth_cmpl.bd_addr, addr_str);
532 ESP_LOGI(TAG, "[%d] [%s] auth complete addr: %s", this->connection_index_, this->address_str_, addr_str);
533 if (!param->ble_security.auth_cmpl.success) {
534 this->log_error_("auth fail reason", param->ble_security.auth_cmpl.fail_reason);
535 } else {
536 this->paired_ = true;
537 ESP_LOGD(TAG, "[%d] [%s] auth success type = %d mode = %d", this->connection_index_, this->address_str_,
538 param->ble_security.auth_cmpl.addr_type, param->ble_security.auth_cmpl.auth_mode);
539 }
540 break;
541
542 // There are other events we'll want to implement at some point to support things like pass key
543 // https://github.com/espressif/esp-idf/blob/cba69dd088344ed9d26739f04736ae7a37541b3a/examples/bluetooth/bluedroid/ble/gatt_security_client/tutorial/Gatt_Security_Client_Example_Walkthrough.md
544 default:
545 break;
546 }
547}
548
549// Parse GATT values into a float for a sensor.
550// Ref: https://www.bluetooth.com/specifications/assigned-numbers/format-types/
551float BLEClientBase::parse_char_value(uint8_t *value, uint16_t length) {
552 // A length of one means a single octet value.
553 if (length == 0)
554 return 0;
555 if (length == 1)
556 return (float) ((uint8_t) value[0]);
557
558 switch (value[0]) {
559 case 0x1: // boolean.
560 case 0x2: // 2bit.
561 case 0x3: // nibble.
562 case 0x4: // uint8.
563 return (float) ((uint8_t) value[1]);
564 case 0x5: // uint12.
565 case 0x6: // uint16.
566 if (length > 2) {
567 return (float) encode_uint16(value[1], value[2]);
568 }
569 [[fallthrough]];
570 case 0x7: // uint24.
571 if (length > 3) {
572 return (float) encode_uint24(value[1], value[2], value[3]);
573 }
574 [[fallthrough]];
575 case 0x8: // uint32.
576 if (length > 4) {
577 return (float) encode_uint32(value[1], value[2], value[3], value[4]);
578 }
579 [[fallthrough]];
580 case 0xC: // int8.
581 return (float) ((int8_t) value[1]);
582 case 0xD: // int12.
583 case 0xE: // int16.
584 if (length > 2) {
585 return (float) ((int16_t) (value[1] << 8) + (int16_t) value[2]);
586 }
587 [[fallthrough]];
588 case 0xF: // int24.
589 if (length > 3) {
590 return (float) ((int32_t) (value[1] << 16) + (int32_t) (value[2] << 8) + (int32_t) (value[3]));
591 }
592 [[fallthrough]];
593 case 0x10: // int32.
594 if (length > 4) {
595 return (float) ((int32_t) (value[1] << 24) + (int32_t) (value[2] << 16) + (int32_t) (value[3] << 8) +
596 (int32_t) (value[4]));
597 }
598 }
599 ESP_LOGW(TAG, "[%d] [%s] Cannot parse characteristic value of type 0x%x length %d", this->connection_index_,
600 this->address_str_, value[0], length);
601 return NAN;
602}
603
604#ifdef USE_ESP32_BLE_DEVICE
606 for (auto *svc : this->services_) {
607 if (svc->uuid == uuid)
608 return svc;
609 }
610 return nullptr;
611}
612
613BLEService *BLEClientBase::get_service(uint16_t uuid) { return this->get_service(espbt::ESPBTUUID::from_uint16(uuid)); }
614
616 auto *svc = this->get_service(service);
617 if (svc == nullptr)
618 return nullptr;
619 return svc->get_characteristic(chr);
620}
621
622BLECharacteristic *BLEClientBase::get_characteristic(uint16_t service, uint16_t chr) {
623 return this->get_characteristic(espbt::ESPBTUUID::from_uint16(service), espbt::ESPBTUUID::from_uint16(chr));
624}
625
627 for (auto *svc : this->services_) {
628 if (!svc->parsed)
629 svc->parse_characteristics();
630 for (auto *chr : svc->characteristics) {
631 if (chr->handle == handle)
632 return chr;
633 }
634 }
635 return nullptr;
636}
637
639 auto *chr = this->get_characteristic(handle);
640 if (chr != nullptr) {
641 if (!chr->parsed)
642 chr->parse_descriptors();
643 for (auto &desc : chr->descriptors) {
644 if (desc->uuid.get_uuid().uuid.uuid16 == ESP_GATT_UUID_CHAR_CLIENT_CONFIG)
645 return desc;
646 }
647 }
648 return nullptr;
649}
650
652 auto *svc = this->get_service(service);
653 if (svc == nullptr)
654 return nullptr;
655 auto *ch = svc->get_characteristic(chr);
656 if (ch == nullptr)
657 return nullptr;
658 return ch->get_descriptor(descr);
659}
660
661BLEDescriptor *BLEClientBase::get_descriptor(uint16_t service, uint16_t chr, uint16_t descr) {
662 return this->get_descriptor(espbt::ESPBTUUID::from_uint16(service), espbt::ESPBTUUID::from_uint16(chr),
663 espbt::ESPBTUUID::from_uint16(descr));
664}
665
667 for (auto *svc : this->services_) {
668 if (!svc->parsed)
669 svc->parse_characteristics();
670 for (auto *chr : svc->characteristics) {
671 if (!chr->parsed)
672 chr->parse_descriptors();
673 for (auto *desc : chr->descriptors) {
674 if (desc->handle == handle)
675 return desc;
676 }
677 }
678 }
679 return nullptr;
680}
681#endif // USE_ESP32_BLE_DEVICE
682
683} // namespace esphome::esp32_ble_client
684
685#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:673
const float AFTER_BLUETOOTH
Definition component.cpp:84
void 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:765
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:424
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:428
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:420
uint16_t length
Definition tt21100.cpp:0