ESPHome 2025.10.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_.c_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().c_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_,
108 this->address_str_.c_str(), espbt::client_state_to_string(this->state_));
109 return;
110 }
111 ESP_LOGI(TAG, "[%d] [%s] 0x%02x Connecting", this->connection_index_, this->address_str_.c_str(),
112 this->remote_addr_type_);
113 this->paired_ = false;
114 // Enable loop for state processing
115 this->enable_loop();
116 // Immediately transition to CONNECTING to prevent duplicate connection attempts
117 this->set_state(espbt::ClientState::CONNECTING);
118
119 // Determine connection parameters based on connection type
120 if (this->connection_type_ == espbt::ConnectionType::V3_WITHOUT_CACHE) {
121 // V3 without cache needs fast params for service discovery
122 this->set_conn_params_(FAST_MIN_CONN_INTERVAL, FAST_MAX_CONN_INTERVAL, 0, FAST_CONN_TIMEOUT, "fast");
123 } else if (this->connection_type_ == espbt::ConnectionType::V3_WITH_CACHE) {
124 // V3 with cache can use medium params
125 this->set_conn_params_(MEDIUM_MIN_CONN_INTERVAL, MEDIUM_MAX_CONN_INTERVAL, 0, MEDIUM_CONN_TIMEOUT, "medium");
126 }
127 // For V1/Legacy, don't set params - use ESP-IDF defaults
128
129 // Open the connection
130 auto ret = esp_ble_gattc_open(this->gattc_if_, this->remote_bda_, this->remote_addr_type_, true);
131 this->handle_connection_result_(ret);
132}
133
134esp_err_t BLEClientBase::pair() { return esp_ble_set_encryption(this->remote_bda_, ESP_BLE_SEC_ENCRYPT); }
135
137 if (this->state_ == espbt::ClientState::IDLE || this->state_ == espbt::ClientState::DISCONNECTING) {
138 ESP_LOGI(TAG, "[%d] [%s] Disconnect requested, but already %s", this->connection_index_, this->address_str_.c_str(),
139 espbt::client_state_to_string(this->state_));
140 return;
141 }
142 if (this->state_ == espbt::ClientState::CONNECTING || this->conn_id_ == UNSET_CONN_ID) {
143 ESP_LOGD(TAG, "[%d] [%s] Disconnect before connected, disconnect scheduled", this->connection_index_,
144 this->address_str_.c_str());
145 this->want_disconnect_ = true;
146 return;
147 }
149}
150
152 // Disconnect without checking the state.
153 ESP_LOGI(TAG, "[%d] [%s] Disconnecting (conn_id: %d).", this->connection_index_, this->address_str_.c_str(),
154 this->conn_id_);
155 if (this->state_ == espbt::ClientState::DISCONNECTING) {
156 this->log_error_("Already disconnecting");
157 return;
158 }
159 if (this->conn_id_ == UNSET_CONN_ID) {
160 this->log_error_("conn id unset, cannot disconnect");
161 return;
162 }
163 auto err = esp_ble_gattc_close(this->gattc_if_, this->conn_id_);
164 if (err != ESP_OK) {
165 //
166 // This is a fatal error, but we can't do anything about it
167 // and it likely means the BLE stack is in a bad state.
168 //
169 // In the future we might consider App.reboot() here since
170 // the BLE stack is in an indeterminate state.
171 //
172 this->log_gattc_warning_("esp_ble_gattc_close", err);
173 }
174
175 if (this->state_ == espbt::ClientState::DISCOVERED) {
176 this->set_address(0);
177 this->set_state(espbt::ClientState::IDLE);
178 } else {
179 this->set_state(espbt::ClientState::DISCONNECTING);
180 }
181}
182
184#ifdef USE_ESP32_BLE_DEVICE
185 for (auto &svc : this->services_)
186 delete svc; // NOLINT(cppcoreguidelines-owning-memory)
187 this->services_.clear();
188#endif
189#ifndef CONFIG_BT_GATTC_CACHE_NVS_FLASH
190 esp_ble_gattc_cache_clean(this->remote_bda_);
191#endif
192}
193
194void BLEClientBase::log_event_(const char *name) {
195 ESP_LOGD(TAG, "[%d] [%s] %s", this->connection_index_, this->address_str_.c_str(), name);
196}
197
198void BLEClientBase::log_gattc_event_(const char *name) {
199 ESP_LOGD(TAG, "[%d] [%s] ESP_GATTC_%s_EVT", this->connection_index_, this->address_str_.c_str(), name);
200}
201
202void BLEClientBase::log_gattc_warning_(const char *operation, esp_gatt_status_t status) {
203 ESP_LOGW(TAG, "[%d] [%s] %s error, status=%d", this->connection_index_, this->address_str_.c_str(), operation,
204 status);
205}
206
207void BLEClientBase::log_gattc_warning_(const char *operation, esp_err_t err) {
208 ESP_LOGW(TAG, "[%d] [%s] %s error, status=%d", this->connection_index_, this->address_str_.c_str(), operation, err);
209}
210
211void BLEClientBase::log_connection_params_(const char *param_type) {
212 ESP_LOGD(TAG, "[%d] [%s] %s conn params", this->connection_index_, this->address_str_.c_str(), param_type);
213}
214
216 if (ret) {
217 this->log_gattc_warning_("esp_ble_gattc_open", ret);
218 this->set_state(espbt::ClientState::IDLE);
219 }
220}
221
222void BLEClientBase::log_error_(const char *message) {
223 ESP_LOGE(TAG, "[%d] [%s] %s", this->connection_index_, this->address_str_.c_str(), message);
224}
225
226void BLEClientBase::log_error_(const char *message, int code) {
227 ESP_LOGE(TAG, "[%d] [%s] %s=%d", this->connection_index_, this->address_str_.c_str(), message, code);
228}
229
230void BLEClientBase::log_warning_(const char *message) {
231 ESP_LOGW(TAG, "[%d] [%s] %s", this->connection_index_, this->address_str_.c_str(), message);
232}
233
234void BLEClientBase::update_conn_params_(uint16_t min_interval, uint16_t max_interval, uint16_t latency,
235 uint16_t timeout, const char *param_type) {
236 esp_ble_conn_update_params_t conn_params = {{0}};
237 memcpy(conn_params.bda, this->remote_bda_, sizeof(esp_bd_addr_t));
238 conn_params.min_int = min_interval;
239 conn_params.max_int = max_interval;
240 conn_params.latency = latency;
241 conn_params.timeout = timeout;
242 this->log_connection_params_(param_type);
243 esp_err_t err = esp_ble_gap_update_conn_params(&conn_params);
244 if (err != ESP_OK) {
245 this->log_gattc_warning_("esp_ble_gap_update_conn_params", err);
246 }
247}
248
249void BLEClientBase::set_conn_params_(uint16_t min_interval, uint16_t max_interval, uint16_t latency, uint16_t timeout,
250 const char *param_type) {
251 // Set preferred connection parameters before connecting
252 // These will be used when establishing the connection
253 this->log_connection_params_(param_type);
254 esp_err_t err = esp_ble_gap_set_prefer_conn_params(this->remote_bda_, min_interval, max_interval, latency, timeout);
255 if (err != ESP_OK) {
256 this->log_gattc_warning_("esp_ble_gap_set_prefer_conn_params", err);
257 }
258}
259
260bool BLEClientBase::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t esp_gattc_if,
261 esp_ble_gattc_cb_param_t *param) {
262 if (event == ESP_GATTC_REG_EVT && this->app_id != param->reg.app_id)
263 return false;
264 if (event != ESP_GATTC_REG_EVT && esp_gattc_if != ESP_GATT_IF_NONE && esp_gattc_if != this->gattc_if_)
265 return false;
266
267 ESP_LOGV(TAG, "[%d] [%s] gattc_event_handler: event=%d gattc_if=%d", this->connection_index_,
268 this->address_str_.c_str(), event, esp_gattc_if);
269
270 switch (event) {
271 case ESP_GATTC_REG_EVT: {
272 if (param->reg.status == ESP_GATT_OK) {
273 ESP_LOGV(TAG, "[%d] [%s] gattc registered app id %d", this->connection_index_, this->address_str_.c_str(),
274 this->app_id);
275 this->gattc_if_ = esp_gattc_if;
276 } else {
277 this->log_error_("gattc app registration failed status", param->reg.status);
278 this->status_ = param->reg.status;
279 this->mark_failed();
280 }
281 break;
282 }
283 case ESP_GATTC_OPEN_EVT: {
284 if (!this->check_addr(param->open.remote_bda))
285 return false;
286 this->log_gattc_event_("OPEN");
287 // conn_id was already set in ESP_GATTC_CONNECT_EVT
288 this->service_count_ = 0;
289
290 // ESP-IDF's BLE stack may send ESP_GATTC_OPEN_EVT after esp_ble_gattc_open() returns an
291 // error, if the error occurred at the BTA/GATT layer. This can result in the event
292 // arriving after we've already transitioned to IDLE state.
293 if (this->state_ == espbt::ClientState::IDLE) {
294 ESP_LOGD(TAG, "[%d] [%s] ESP_GATTC_OPEN_EVT in IDLE state (status=%d), ignoring", this->connection_index_,
295 this->address_str_.c_str(), param->open.status);
296 break;
297 }
298
299 if (this->state_ != espbt::ClientState::CONNECTING) {
300 // This should not happen but lets log it in case it does
301 // because it means we have a bad assumption about how the
302 // ESP BT stack works.
303 ESP_LOGE(TAG, "[%d] [%s] ESP_GATTC_OPEN_EVT in %s state (status=%d)", this->connection_index_,
304 this->address_str_.c_str(), espbt::client_state_to_string(this->state_), param->open.status);
305 }
306 if (param->open.status != ESP_GATT_OK && param->open.status != ESP_GATT_ALREADY_OPEN) {
307 this->log_gattc_warning_("Connection open", param->open.status);
308 this->set_state(espbt::ClientState::IDLE);
309 break;
310 }
311 if (this->want_disconnect_) {
312 // Disconnect was requested after connecting started,
313 // but before the connection was established. Now that we have
314 // this->conn_id_ set, we can disconnect it.
316 this->conn_id_ = UNSET_CONN_ID;
317 break;
318 }
319 // MTU negotiation already started in ESP_GATTC_CONNECT_EVT
320 this->set_state(espbt::ClientState::CONNECTED);
321 ESP_LOGI(TAG, "[%d] [%s] Connection open", this->connection_index_, this->address_str_.c_str());
322 if (this->connection_type_ == espbt::ConnectionType::V3_WITH_CACHE) {
323 // Cached connections already connected with medium parameters, no update needed
324 // only set our state, subclients might have more stuff to do yet.
325 this->state_ = espbt::ClientState::ESTABLISHED;
326 break;
327 }
328 // For V3_WITHOUT_CACHE, we already set fast params before connecting
329 // No need to update them again here
330 this->log_event_("Searching for services");
331 esp_ble_gattc_search_service(esp_gattc_if, param->cfg_mtu.conn_id, nullptr);
332 break;
333 }
334 case ESP_GATTC_CONNECT_EVT: {
335 if (!this->check_addr(param->connect.remote_bda))
336 return false;
337 this->log_gattc_event_("CONNECT");
338 this->conn_id_ = param->connect.conn_id;
339 // Start MTU negotiation immediately as recommended by ESP-IDF examples
340 // (gatt_client, ble_throughput) which call esp_ble_gattc_send_mtu_req in
341 // ESP_GATTC_CONNECT_EVT instead of waiting for ESP_GATTC_OPEN_EVT.
342 // This saves ~3ms in the connection process.
343 auto ret = esp_ble_gattc_send_mtu_req(this->gattc_if_, param->connect.conn_id);
344 if (ret) {
345 this->log_gattc_warning_("esp_ble_gattc_send_mtu_req", ret);
346 }
347 break;
348 }
349 case ESP_GATTC_DISCONNECT_EVT: {
350 if (!this->check_addr(param->disconnect.remote_bda))
351 return false;
352 // Check if we were disconnected while waiting for service discovery
353 if (param->disconnect.reason == ESP_GATT_CONN_TERMINATE_PEER_USER &&
354 this->state_ == espbt::ClientState::CONNECTED) {
355 this->log_warning_("Remote closed during discovery");
356 } else {
357 ESP_LOGD(TAG, "[%d] [%s] ESP_GATTC_DISCONNECT_EVT, reason 0x%02x", this->connection_index_,
358 this->address_str_.c_str(), param->disconnect.reason);
359 }
360 this->release_services();
361 this->set_state(espbt::ClientState::IDLE);
362 break;
363 }
364
365 case ESP_GATTC_CFG_MTU_EVT: {
366 if (this->conn_id_ != param->cfg_mtu.conn_id)
367 return false;
368 if (param->cfg_mtu.status != ESP_GATT_OK) {
369 ESP_LOGW(TAG, "[%d] [%s] cfg_mtu failed, mtu %d, status %d", this->connection_index_,
370 this->address_str_.c_str(), param->cfg_mtu.mtu, param->cfg_mtu.status);
371 // No state change required here - disconnect event will follow if needed.
372 break;
373 }
374 ESP_LOGD(TAG, "[%d] [%s] cfg_mtu status %d, mtu %d", this->connection_index_, this->address_str_.c_str(),
375 param->cfg_mtu.status, param->cfg_mtu.mtu);
376 this->mtu_ = param->cfg_mtu.mtu;
377 break;
378 }
379 case ESP_GATTC_CLOSE_EVT: {
380 if (this->conn_id_ != param->close.conn_id)
381 return false;
382 this->log_gattc_event_("CLOSE");
383 this->release_services();
384 this->set_state(espbt::ClientState::IDLE);
385 this->conn_id_ = UNSET_CONN_ID;
386 break;
387 }
388 case ESP_GATTC_SEARCH_RES_EVT: {
389 if (this->conn_id_ != param->search_res.conn_id)
390 return false;
391 this->service_count_++;
392 if (this->connection_type_ == espbt::ConnectionType::V3_WITHOUT_CACHE) {
393 // V3 clients don't need services initialized since
394 // as they use the ESP APIs to get services.
395 break;
396 }
397#ifdef USE_ESP32_BLE_DEVICE
398 BLEService *ble_service = new BLEService(); // NOLINT(cppcoreguidelines-owning-memory)
399 ble_service->uuid = espbt::ESPBTUUID::from_uuid(param->search_res.srvc_id.uuid);
400 ble_service->start_handle = param->search_res.start_handle;
401 ble_service->end_handle = param->search_res.end_handle;
402 ble_service->client = this;
403 this->services_.push_back(ble_service);
404#endif
405 break;
406 }
407 case ESP_GATTC_SEARCH_CMPL_EVT: {
408 if (this->conn_id_ != param->search_cmpl.conn_id)
409 return false;
410 this->log_gattc_event_("SEARCH_CMPL");
411 // For V3_WITHOUT_CACHE, switch back to medium connection parameters after service discovery
412 // This balances performance with bandwidth usage after the critical discovery phase
413 if (this->connection_type_ == espbt::ConnectionType::V3_WITHOUT_CACHE) {
414 this->update_conn_params_(MEDIUM_MIN_CONN_INTERVAL, MEDIUM_MAX_CONN_INTERVAL, 0, MEDIUM_CONN_TIMEOUT, "medium");
415 } else if (this->connection_type_ != espbt::ConnectionType::V3_WITH_CACHE) {
416#ifdef USE_ESP32_BLE_DEVICE
417 for (auto &svc : this->services_) {
418 ESP_LOGV(TAG, "[%d] [%s] Service UUID: %s", this->connection_index_, this->address_str_.c_str(),
419 svc->uuid.to_string().c_str());
420 ESP_LOGV(TAG, "[%d] [%s] start_handle: 0x%x end_handle: 0x%x", this->connection_index_,
421 this->address_str_.c_str(), svc->start_handle, svc->end_handle);
422 }
423#endif
424 }
425 ESP_LOGI(TAG, "[%d] [%s] Service discovery complete", this->connection_index_, this->address_str_.c_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_.c_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_.c_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 esp_bd_addr_t bd_addr;
531 memcpy(bd_addr, param->ble_security.auth_cmpl.bd_addr, sizeof(esp_bd_addr_t));
532 ESP_LOGI(TAG, "[%d] [%s] auth complete addr: %s", this->connection_index_, this->address_str_.c_str(),
533 format_hex(bd_addr, 6).c_str());
534 if (!param->ble_security.auth_cmpl.success) {
535 this->log_error_("auth fail reason", param->ble_security.auth_cmpl.fail_reason);
536 } else {
537 this->paired_ = true;
538 ESP_LOGD(TAG, "[%d] [%s] auth success type = %d mode = %d", this->connection_index_, this->address_str_.c_str(),
539 param->ble_security.auth_cmpl.addr_type, param->ble_security.auth_cmpl.auth_mode);
540 }
541 break;
542
543 // There are other events we'll want to implement at some point to support things like pass key
544 // https://github.com/espressif/esp-idf/blob/cba69dd088344ed9d26739f04736ae7a37541b3a/examples/bluetooth/bluedroid/ble/gatt_security_client/tutorial/Gatt_Security_Client_Example_Walkthrough.md
545 default:
546 break;
547 }
548}
549
550// Parse GATT values into a float for a sensor.
551// Ref: https://www.bluetooth.com/specifications/assigned-numbers/format-types/
552float BLEClientBase::parse_char_value(uint8_t *value, uint16_t length) {
553 // A length of one means a single octet value.
554 if (length == 0)
555 return 0;
556 if (length == 1)
557 return (float) ((uint8_t) value[0]);
558
559 switch (value[0]) {
560 case 0x1: // boolean.
561 case 0x2: // 2bit.
562 case 0x3: // nibble.
563 case 0x4: // uint8.
564 return (float) ((uint8_t) value[1]);
565 case 0x5: // uint12.
566 case 0x6: // uint16.
567 if (length > 2) {
568 return (float) encode_uint16(value[1], value[2]);
569 }
570 [[fallthrough]];
571 case 0x7: // uint24.
572 if (length > 3) {
573 return (float) encode_uint24(value[1], value[2], value[3]);
574 }
575 [[fallthrough]];
576 case 0x8: // uint32.
577 if (length > 4) {
578 return (float) encode_uint32(value[1], value[2], value[3], value[4]);
579 }
580 [[fallthrough]];
581 case 0xC: // int8.
582 return (float) ((int8_t) value[1]);
583 case 0xD: // int12.
584 case 0xE: // int16.
585 if (length > 2) {
586 return (float) ((int16_t) (value[1] << 8) + (int16_t) value[2]);
587 }
588 [[fallthrough]];
589 case 0xF: // int24.
590 if (length > 3) {
591 return (float) ((int32_t) (value[1] << 16) + (int32_t) (value[2] << 8) + (int32_t) (value[3]));
592 }
593 [[fallthrough]];
594 case 0x10: // int32.
595 if (length > 4) {
596 return (float) ((int32_t) (value[1] << 24) + (int32_t) (value[2] << 16) + (int32_t) (value[3] << 8) +
597 (int32_t) (value[4]));
598 }
599 }
600 ESP_LOGW(TAG, "[%d] [%s] Cannot parse characteristic value of type 0x%x length %d", this->connection_index_,
601 this->address_str_.c_str(), value[0], length);
602 return NAN;
603}
604
605#ifdef USE_ESP32_BLE_DEVICE
607 for (auto *svc : this->services_) {
608 if (svc->uuid == uuid)
609 return svc;
610 }
611 return nullptr;
612}
613
614BLEService *BLEClientBase::get_service(uint16_t uuid) { return this->get_service(espbt::ESPBTUUID::from_uint16(uuid)); }
615
617 auto *svc = this->get_service(service);
618 if (svc == nullptr)
619 return nullptr;
620 return svc->get_characteristic(chr);
621}
622
623BLECharacteristic *BLEClientBase::get_characteristic(uint16_t service, uint16_t chr) {
624 return this->get_characteristic(espbt::ESPBTUUID::from_uint16(service), espbt::ESPBTUUID::from_uint16(chr));
625}
626
628 for (auto *svc : this->services_) {
629 if (!svc->parsed)
630 svc->parse_characteristics();
631 for (auto *chr : svc->characteristics) {
632 if (chr->handle == handle)
633 return chr;
634 }
635 }
636 return nullptr;
637}
638
640 auto *chr = this->get_characteristic(handle);
641 if (chr != nullptr) {
642 if (!chr->parsed)
643 chr->parse_descriptors();
644 for (auto &desc : chr->descriptors) {
645 if (desc->uuid.get_uuid().uuid.uuid16 == ESP_GATT_UUID_CHAR_CLIENT_CONFIG)
646 return desc;
647 }
648 }
649 return nullptr;
650}
651
653 auto *svc = this->get_service(service);
654 if (svc == nullptr)
655 return nullptr;
656 auto *ch = svc->get_characteristic(chr);
657 if (ch == nullptr)
658 return nullptr;
659 return ch->get_descriptor(descr);
660}
661
662BLEDescriptor *BLEClientBase::get_descriptor(uint16_t service, uint16_t chr, uint16_t descr) {
663 return this->get_descriptor(espbt::ESPBTUUID::from_uint16(service), espbt::ESPBTUUID::from_uint16(chr),
664 espbt::ESPBTUUID::from_uint16(descr));
665}
666
668 for (auto *svc : this->services_) {
669 if (!svc->parsed)
670 svc->parse_characteristics();
671 for (auto *chr : svc->characteristics) {
672 if (!chr->parsed)
673 chr->parse_descriptors();
674 for (auto *desc : chr->descriptors) {
675 if (desc->handle == handle)
676 return desc;
677 }
678 }
679 }
680 return nullptr;
681}
682#endif // USE_ESP32_BLE_DEVICE
683
684} // namespace esphome::esp32_ble_client
685
686#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)
const std::string & address_str() const
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
ESP32BLETracker * global_esp32_ble_tracker
const char * client_state_to_string(ClientState state)
ESP32BLE * global_ble
Definition ble.cpp:586
const float AFTER_BLUETOOTH
Definition component.cpp:52
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:263
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:189
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:193
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:185
uint16_t length
Definition tt21100.cpp:0