ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
bluetooth_connection_bluedroid.cpp
Go to the documentation of this file.
2
3#if defined(USE_ESP32_BLE) && defined(USE_BLE_GATT_CLIENT)
4
5// The in-place streamer serves the proxy's service-discovery API; backend-only
6// builds compile without the proxy headers or the streamer.
7#ifdef USE_BLUETOOTH_PROXY_CONNECTIONS
10
12#endif
13
15#include "esphome/core/hal.h"
17#include "esphome/core/log.h"
18
19#include <cstring>
20#include <esp_idf_version.h>
21
22// cancel_open exists from ESP-IDF 5.5.5 and 6.0.1.
23#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 5) && ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(6, 0, 0)) || \
24 ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 1)
25#define BLUEDROID_HAS_CANCEL_OPEN
26#endif
27
29
30ESPHOME_LOG_TAG(TAG, "bluetooth_connection");
31
32using ble_device_base::FAST_CONN_TIMEOUT;
33using ble_device_base::FAST_MAX_CONN_INTERVAL;
34using ble_device_base::FAST_MIN_CONN_INTERVAL;
35using ble_device_base::MEDIUM_CONN_TIMEOUT;
36using ble_device_base::MEDIUM_MAX_CONN_INTERVAL;
37using ble_device_base::MEDIUM_MIN_CONN_INTERVAL;
40
41// ---- tracker surface ----
42
45 // OTA calls this and then blocks the loop, so a still-pending open must not keep BLE priority.
47 this->gatt_disconnect();
48}
49
50// ---- component ----
51
53 static uint8_t connection_index = 0;
54 this->connection_index_ = connection_index++;
55}
56
58 if (!esp32_ble::global_ble->is_active()) {
59 // ble_before_disabled_event_handler() settles the slot.
60 return;
61 }
62 auto st = this->state();
63 if (st == ClientState::INIT) {
64 // Parity with BLEClientBase: a failed registration marks the slot
65 // failed and idles it without retry.
66 auto ret = esp_ble_gattc_app_register(this->app_id);
67 if (ret) {
68 ESP_LOGE(TAG, "gattc app register failed: app_id=%d code=%d", this->app_id, ret);
69 this->mark_failed(
70 LOG_STR("Registration failed; if the error was ESP_GATT_NO_RESOURCES, reduce the connection slots"));
71 }
72 // Do not wait for REG_EVT; connect() rejects until it lands.
73 this->set_idle_();
74 } else if (st == ClientState::DISCONNECTING || this->disconnect_pending()) {
75 // The one teardown safety net: a lost CLOSE_EVT, or a scheduled
76 // teardown whose OPEN_EVT never arrives.
77 if (millis() - this->disconnecting_started_ > ble_device_base::GATT_DISCONNECT_TIMEOUT_MS) {
78 if (this->conn_id_ == UNSET_CONN_ID) {
80 } else if (st == ClientState::CONNECTING) {
81 // CONNECT_EVT came but OPEN_EVT was lost, so our open still holds the ACL link.
82 this->check_and_log_error_("esp_ble_gap_disconnect", esp_ble_gap_disconnect(this->remote_bda_));
83 }
84 ESP_LOGE(TAG, "[%d] Timeout waiting for teardown, forcing IDLE", this->connection_index_);
85 // Release before idling: a lost completion must not leak the cache.
86 this->release_services();
87 this->set_idle_(); // also clears want_disconnect_
88 this->listener_->on_connection_state(false, 0, ESP_GATT_CONN_TIMEOUT);
89 }
90 } else {
91 // The loop stays on while a link exists (pre-started search flush); it
92 // settles only back at IDLE.
94 if (this->state() == ClientState::IDLE) {
95 this->disable_loop();
96 }
97 }
98}
99
100// Stack down: no CLOSE_EVT will come. Settle a live link so the consumer
101// frees its slot, then register the app again on the next enable.
103 auto st = this->state();
104 if (st != ClientState::IDLE && st != ClientState::INIT) {
105 this->release_services();
106 this->set_idle_();
107 this->listener_->on_connection_state(false, 0, ble_device_base::GATT_ERR_NOT_CONNECTED);
108 }
109 // The interface belongs to the torn-down stack.
110 this->gattc_if_ = ESP_GATT_IF_NONE;
111 this->set_state(ClientState::INIT);
112 // An idle slot runs no loop; the INIT branch must run to register again.
113 this->enable_loop();
114}
115
116void BluedroidGattClient::dump_config() { ESP_LOGCONFIG(TAG, "Bluedroid GATT client %d", this->connection_index_); }
117
118// ---- contract ops ----
119
120int BluedroidGattClient::connect(uint64_t address, uint8_t addr_type) {
121 if (this->gattc_if_ == ESP_GATT_IF_NONE) {
122 // Bluedroid drops an open on an unknown interface without any event.
123 ESP_LOGW(TAG, "[%d] Connect rejected, GATT app not registered", this->connection_index_);
124 return ble_device_base::GATT_ERR_NOT_CONNECTED;
125 }
126 // Only from idle: clobbering DISCONNECTING would open a new link the
127 // stale CLOSE_EVT then tears down.
128 if (this->state() != ClientState::IDLE) {
129 ESP_LOGW(TAG, "[%d] Connect rejected, slot busy", this->connection_index_);
130 return ESP_GATT_BUSY;
131 }
133 this->remote_addr_type_ = addr_type;
134 // Hand the request to the tracker's promote loop: it stops the scan and
135 // calls tracker_connect_() - the tracker owns connect timing here.
136 this->set_state(ClientState::DISCOVERED);
137 return 0;
138}
139
141 auto st = this->state();
142 if (st == ClientState::CONNECTING || st == ClientState::CONNECTED || st == ClientState::ESTABLISHED) {
143 ESP_LOGW(TAG, "[%d] Connection already in progress", this->connection_index_);
144 return;
145 }
146 if (st == ClientState::DISCONNECTING) {
147 ESP_LOGW(TAG, "[%d] Cannot connect, still waiting for CLOSE_EVT", this->connection_index_);
148 return;
149 }
150 ESP_LOGI(TAG, "[%d] 0x%02x Connecting", this->connection_index_, this->remote_addr_type_);
151 // Per-attempt latches; the search machine is reset by set_idle_(), the
152 // one door back to IDLE.
153 this->services_released_ = false;
154 this->seen_mtu_ = false;
155 this->mtu_failed_ = false;
156 this->cancel_open_sent_ = false;
157 this->conn_id_ = UNSET_CONN_ID;
158 this->enable_loop();
159 this->set_state(ClientState::CONNECTING);
160 uint16_t min_interval = MEDIUM_MIN_CONN_INTERVAL;
161 uint16_t max_interval = MEDIUM_MAX_CONN_INTERVAL;
162 uint16_t timeout = MEDIUM_CONN_TIMEOUT;
163 if (this->connection_type_ == ConnectionType::V3_WITHOUT_CACHE) {
164#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
165 if (!this->coex_held_) {
166 this->coex_held_ = true;
168 }
169#endif
170 // FAST for discovery, stepped down at SEARCH_CMPL; MEDIUM when the hub relaxed this peripheral
171 if (!this->relaxed_open_) {
172 min_interval = FAST_MIN_CONN_INTERVAL;
173 max_interval = FAST_MAX_CONN_INTERVAL;
174 timeout = FAST_CONN_TIMEOUT;
175 }
176 }
178 "esp_ble_gap_set_prefer_conn_params",
179 esp_ble_gap_set_prefer_conn_params(this->remote_bda_, min_interval, max_interval, 0, timeout));
180 auto ret = esp_ble_gattc_open(this->gattc_if_, this->remote_bda_,
181 static_cast<esp_ble_addr_type_t>(this->remote_addr_type_), true);
182 if (ret) {
183 this->log_gattc_warning_("esp_ble_gattc_open", ret);
184 // CONNECT_EVT never fired; nothing to close.
185 this->set_idle_();
186 this->listener_->on_connection_state(false, 0, ret);
187 }
188}
189
191 auto st = this->state();
192 if (st == ClientState::DISCONNECTING) {
193 return 0;
194 }
195 // Nothing was opened, so no completion event will follow: report
196 // not-connected and the hub frees the slot at once (rp2 convention).
197 if (st == ClientState::IDLE) {
198 return ble_device_base::GATT_ERR_NOT_CONNECTED;
199 }
200 if (st == ClientState::DISCOVERED) {
201 // Parked for the tracker promote loop, never opened.
202 this->set_idle_();
203 return ble_device_base::GATT_ERR_NOT_CONNECTED;
204 }
205 if (st == ClientState::CONNECTING || this->conn_id_ == UNSET_CONN_ID) {
206 ESP_LOGD(TAG, "[%d] Disconnect scheduled", this->connection_index_);
207 this->want_disconnect_ = true;
208 // Arm the safety window: a lost OPEN_EVT must not leak the teardown.
210 this->enable_loop();
211 if (this->conn_id_ == UNSET_CONN_ID) {
212 // CANCEL_OPEN_EVT or a racing OPEN_EVT settles the slot.
213 this->cancel_pending_open_();
214 }
215 return 0;
216 }
218 return 0;
219}
220
222#ifdef BLUEDROID_HAS_CANCEL_OPEN
223 esp_ble_gattc_cancel_open_params_t params{};
224 params.gattc_if = this->gattc_if_;
225 memcpy(params.remote_bda, this->remote_bda_, sizeof(esp_bd_addr_t));
226 // A refused cancel schedules no CANCEL_OPEN_EVT, so the teardown stays cancellable.
227 if (this->check_and_log_error_("esp_ble_gattc_cancel_open", esp_ble_gattc_cancel_open(&params)) == ESP_OK) {
228 this->cancel_open_sent_ = true;
229 }
230#endif
231}
232
234 ESP_LOGI(TAG, "[%d] Disconnecting (conn_id: %d)", this->connection_index_, this->conn_id_);
235 if (this->conn_id_ == UNSET_CONN_ID) {
236 // Terminal state now rather than leaning on the scheduled-teardown timer.
237 ESP_LOGE(TAG, "[%d] conn id unset, cannot disconnect", this->connection_index_);
238 this->release_services();
239 this->set_idle_();
240 this->listener_->on_connection_state(false, 0, ble_device_base::GATT_ERR_NOT_CONNECTED);
241 return;
242 }
243 auto err = esp_ble_gattc_close(this->gattc_if_, this->conn_id_);
244 if (err != ESP_OK) {
245 // The stack is now in an indeterminate state for this link.
246 ESP_LOGE(TAG, "[%d] esp_ble_gattc_close error: %d", this->connection_index_, err);
247 }
248 this->set_disconnecting_();
249}
250
252 // Only a scheduled teardown (want_disconnect_ latched while the open is
253 // still in flight) is cancellable; once closing started the terminal
254 // report settles the race.
255 if (this->state() != ClientState::CONNECTING || !this->disconnect_pending()) {
256 return false;
257 }
258 if (this->cancel_open_sent_) {
259 // The cancel already went out, so CANCEL_OPEN_EVT ends it.
260 return false;
261 }
262 this->want_disconnect_ = false;
263 return true;
264}
265
267 if (this->conn_id_ == UNSET_CONN_ID) {
268 return ble_device_base::GATT_ERR_NOT_CONNECTED;
269 }
270 switch (this->search_state_) {
272 // The pending SEARCH_CMPL reports once it lands.
274 return 0;
276 // Already landed: the flush after the connected report delivers
277 // (loop() covers a claim made outside that event drain).
279 this->enable_loop();
280 return 0;
283 return 0; // One completion is already owed to this claimant.
285 default:
286 break;
287 }
288 int err = this->check_and_log_error_("esp_ble_gattc_search_service",
289 esp_ble_gattc_search_service(this->gattc_if_, this->conn_id_, nullptr));
290 if (err == 0) {
292 }
293 return err;
294}
295
297 if (this->conn_id_ == UNSET_CONN_ID) {
298 return ble_device_base::GATT_ERR_NOT_CONNECTED;
299 }
300 return this->check_and_log_error_("esp_ble_gattc_read_char", esp_ble_gattc_read_char(this->gattc_if_, this->conn_id_,
301 handle, ESP_GATT_AUTH_REQ_NONE));
302}
303
304int BluedroidGattClient::write_characteristic(uint16_t handle, const uint8_t *data, uint16_t len, bool response) {
305 if (this->conn_id_ == UNSET_CONN_ID) {
306 return ble_device_base::GATT_ERR_NOT_CONNECTED;
307 }
308 // The BTC layer copies the payload immediately, so the const_cast is safe.
309 return this->check_and_log_error_(
310 "esp_ble_gattc_write_char",
311 esp_ble_gattc_write_char(this->gattc_if_, this->conn_id_, handle, len, const_cast<uint8_t *>(data),
312 response ? ESP_GATT_WRITE_TYPE_RSP : ESP_GATT_WRITE_TYPE_NO_RSP,
313 ESP_GATT_AUTH_REQ_NONE));
314}
315
317 if (this->conn_id_ == UNSET_CONN_ID) {
318 return ble_device_base::GATT_ERR_NOT_CONNECTED;
319 }
320 return this->check_and_log_error_(
321 "esp_ble_gattc_read_char_descr",
322 esp_ble_gattc_read_char_descr(this->gattc_if_, this->conn_id_, handle, ESP_GATT_AUTH_REQ_NONE));
323}
324
325int BluedroidGattClient::write_descriptor(uint16_t handle, const uint8_t *data, uint16_t len) {
326 if (this->conn_id_ == UNSET_CONN_ID) {
327 return ble_device_base::GATT_ERR_NOT_CONNECTED;
328 }
329 return this->check_and_log_error_(
330 "esp_ble_gattc_write_char_descr",
331 esp_ble_gattc_write_char_descr(this->gattc_if_, this->conn_id_, handle, len, const_cast<uint8_t *>(data),
332 ESP_GATT_WRITE_TYPE_RSP, ESP_GATT_AUTH_REQ_NONE));
333}
334
336 if (this->conn_id_ == UNSET_CONN_ID) {
337 return ble_device_base::GATT_ERR_NOT_CONNECTED;
338 }
339 // Local registration only; the CCCD write is the API client's responsibility.
340 if (enable) {
341 return this->check_and_log_error_("esp_ble_gattc_register_for_notify",
342 esp_ble_gattc_register_for_notify(this->gattc_if_, this->remote_bda_, handle));
343 }
344 return this->check_and_log_error_("esp_ble_gattc_unregister_for_notify",
345 esp_ble_gattc_unregister_for_notify(this->gattc_if_, this->remote_bda_, handle));
346}
347
349 if (this->conn_id_ == UNSET_CONN_ID) {
350 return ble_device_base::GATT_ERR_NOT_CONNECTED;
351 }
352 return esp_ble_set_encryption(this->remote_bda_, ESP_BLE_SEC_ENCRYPT);
353}
354
355int BluedroidGattClient::update_connection_params(uint16_t min_interval, uint16_t max_interval, uint16_t latency,
356 uint16_t timeout) {
357 return this->update_conn_params_(min_interval, max_interval, latency, timeout, "custom");
358}
359
361 this->service_total_ = 0;
362 // Always set: terminates any in-flight stream on every cache config.
363 this->services_released_ = true;
364#ifndef CONFIG_BT_GATTC_CACHE_NVS_FLASH
365 // A failed clean leaves a stale database the next connection could serve
366 // as authoritative. A disabled stack invalidates its own cache; skip the
367 // meaningless call instead of warning on every OTA/ble.disable teardown.
368 if (esp32_ble::global_ble->is_active()) {
369 this->check_and_log_error_("esp_ble_gattc_cache_clean", esp_ble_gattc_cache_clean(this->remote_bda_));
370 }
371#endif
372}
373
374// ---- internals ----
375
376bool BluedroidGattClient::check_addr_(const esp_bd_addr_t &addr) const {
377 return memcmp(addr, this->remote_bda_, sizeof(esp_bd_addr_t)) == 0;
378}
379
382 this->set_state(ClientState::IDLE);
383 this->conn_id_ = UNSET_CONN_ID;
385 this->search_status_ = 0;
386}
387
389#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
390 if (this->coex_held_) {
391 this->coex_held_ = false;
393 }
394#endif
395}
396
400 this->set_state(ClientState::DISCONNECTING);
401 // The loop may be disabled while idle; the safety timeout needs it.
402 this->enable_loop();
403}
404
405esp_err_t BluedroidGattClient::update_conn_params_(uint16_t min_interval, uint16_t max_interval, uint16_t latency,
406 uint16_t timeout, const char *param_type) {
407 esp_ble_conn_update_params_t conn_params = {};
408 memcpy(conn_params.bda, this->remote_bda_, sizeof(esp_bd_addr_t));
409 conn_params.min_int = min_interval;
410 conn_params.max_int = max_interval;
411 conn_params.latency = latency;
412 conn_params.timeout = timeout;
413 ESP_LOGD(TAG, "[%d] %s conn params", this->connection_index_, param_type);
414 return this->check_and_log_error_("esp_ble_gap_update_conn_params", esp_ble_gap_update_conn_params(&conn_params));
415}
416
417int BluedroidGattClient::check_and_log_error_(const char *operation, esp_err_t err) {
418 if (err != ESP_OK) {
419 this->log_gattc_warning_(operation, err);
420 }
421 return err;
422}
423
424void BluedroidGattClient::log_gattc_warning_(const char *operation, int code) {
425 ESP_LOGW(TAG, "[%d] %s failed, status=%d", this->connection_index_, operation, code);
426}
427
428// ---- service streaming ----
429
430int BluedroidGattClient::handle_search_cmpl_(esp_gatt_status_t status) {
432 // Step down from the fast discovery params.
433 this->update_conn_params_(MEDIUM_MIN_CONN_INTERVAL, MEDIUM_MAX_CONN_INTERVAL, 0, MEDIUM_CONN_TIMEOUT, "medium");
434 if (status != ESP_GATT_OK) {
435 // A failed discovery reads as a clean zero from the count calls below;
436 // honoring the event status stops it becoming an authoritative empty
437 // list.
438 return status;
439 }
440 uint16_t primary = 0;
441 uint16_t secondary = 0;
442 auto primary_status = esp_ble_gattc_get_attr_count(this->gattc_if_, this->conn_id_, ESP_GATT_DB_PRIMARY_SERVICE,
443 0x0001, 0xFFFF, 0, &primary);
444 auto secondary_status = esp_ble_gattc_get_attr_count(this->gattc_if_, this->conn_id_, ESP_GATT_DB_SECONDARY_SERVICE,
445 0x0001, 0xFFFF, 0, &secondary);
446 if (primary_status != ESP_GATT_OK || secondary_status != ESP_GATT_OK) {
447 // A failed count must not become an authoritative empty database.
448 auto count_status = primary_status != ESP_GATT_OK ? primary_status : secondary_status;
449 this->log_gattc_warning_("esp_ble_gattc_get_attr_count", count_status);
450 return count_status;
451 }
452 this->service_total_ = primary + secondary;
453 return 0;
454}
455
456// Reports a completed search once claimed; delivery consumes the state so
457// a re-discovery issues a real search.
464
465#ifdef USE_BLUETOOTH_PROXY_CONNECTIONS
466// The wrapper's compile-time streamer detection must keep finding this
467// method; a signature drift would silently fall back to the table streamer,
468// which proxy builds compile without a materializer.
469static_assert(requires(BluedroidGattClient c, BluetoothConnection &conn) { c.stream_service_batch(conn); });
470
471// Bound by the SERVICE STREAMING HAZARD note at the top of
472// bluetooth_connection_hub.cpp: never skip a batch, never send done early.
474 if (this->services_released_) {
475 // Released under the stream: park without services-done so a partial
476 // list is never cached as authoritative (the client retries after its
477 // GetServices timeout).
478 ESP_LOGW(TAG, "[%d] [%s] Services released mid-stream, parking", conn.connection_index_, conn.address_str_);
479 conn.send_service_ = DONE_SENDING_SERVICES;
480 return;
481 }
482 if (conn.send_service_ >= this->service_total_) {
483 this->release_services();
484 conn.send_services_done_();
485 return;
486 }
487
488 // The subscriber vanished mid-stream.
489 auto *api_conn = conn.proxy_->get_api_connection();
490 if (api_conn == nullptr) {
491 ESP_LOGW(TAG, "[%d] [%s] API connection lost while streaming services", conn.connection_index_, conn.address_str_);
493 return;
494 }
495
496 bool use_efficient_uuids = conn.proxy_->client_supports_efficient_uuids();
498 resp.address = conn.address_;
499 size_t current_size = resp.calculate_size();
500 int16_t batch_start = conn.send_service_;
501
502 while (conn.send_service_ < this->service_total_) {
503 esp_gattc_service_elem_t service_result;
504 uint16_t svc_count = 1;
505 esp_gatt_status_t svc_status = esp_ble_gattc_get_service(this->gattc_if_, this->conn_id_, nullptr, &service_result,
506 &svc_count, conn.send_service_);
507 if (svc_status != ESP_GATT_OK || svc_count == 0) {
508 ESP_LOGE(TAG, "[%d] [%s] Service walk failed (service %d), aborting stream", conn.connection_index_,
509 conn.address_str_, conn.send_service_);
510 conn.abort_service_stream(svc_status != ESP_GATT_OK ? svc_status : ESP_GATT_NOT_FOUND);
511 return;
512 }
513 uint16_t total_char_count = 0;
514 auto char_count_status =
515 esp_ble_gattc_get_attr_count(this->gattc_if_, this->conn_id_, ESP_GATT_DB_CHARACTERISTIC,
516 service_result.start_handle, service_result.end_handle, 0, &total_char_count);
517 if (char_count_status != ESP_GATT_OK) {
518 this->log_gattc_warning_("esp_ble_gattc_get_attr_count", char_count_status);
519 conn.abort_service_stream(char_count_status);
520 return;
521 }
522
523 // If this service likely won't fit, send the current batch first.
524 size_t estimated_size = estimate_service_size(total_char_count, use_efficient_uuids);
525 if (!resp.services.empty() && current_size + estimated_size > MAX_PACKET_SIZE) {
526 break;
527 }
528
529 resp.services.emplace_back();
530 auto &service_resp = resp.services.back();
531 fill_gatt_uuid(service_resp.uuid, service_resp.short_uuid,
532 ble_device_base::ESPBTUUID::from_uuid(service_result.uuid), use_efficient_uuids);
533 service_resp.handle = service_result.start_handle;
534
535 if (total_char_count > 0) {
536 service_resp.characteristics.init(total_char_count);
537 uint16_t char_offset = 0;
538 esp_gattc_char_elem_t char_result;
539 // Bounded by the count query: a misbehaving peripheral can make the
540 // enumeration return more entries than it reported.
541 while (char_offset < total_char_count) {
542 uint16_t cc = 1;
543 auto char_status = esp_ble_gattc_get_all_char(this->gattc_if_, this->conn_id_, service_result.start_handle,
544 service_result.end_handle, &char_result, &cc, char_offset);
545 if (char_status != ESP_GATT_OK || cc == 0) {
546 // An early terminator contradicts the count from the same cache;
547 // never stream a silently truncated list.
548 this->log_gattc_warning_("esp_ble_gattc_get_all_char", char_status);
549 conn.abort_service_stream(char_status != ESP_GATT_OK ? char_status : ESP_GATT_NOT_FOUND);
550 return;
551 }
552 service_resp.characteristics.emplace_back();
553 auto &characteristic_resp = service_resp.characteristics.back();
554 fill_gatt_uuid(characteristic_resp.uuid, characteristic_resp.short_uuid,
555 ble_device_base::ESPBTUUID::from_uuid(char_result.uuid), use_efficient_uuids);
556 characteristic_resp.handle = char_result.char_handle;
557 characteristic_resp.properties = char_result.properties;
558
559 uint16_t total_desc_count = 0;
560 auto desc_count_status = esp_ble_gattc_get_attr_count(this->gattc_if_, this->conn_id_, ESP_GATT_DB_DESCRIPTOR,
561 0, 0, char_result.char_handle, &total_desc_count);
562 if (desc_count_status != ESP_GATT_OK) {
563 // Abort rather than stream the characteristic descriptor-less: a
564 // missing CCCD in a cached database breaks notifications for good.
565 this->log_gattc_warning_("esp_ble_gattc_get_attr_count", desc_count_status);
566 conn.abort_service_stream(desc_count_status);
567 return;
568 }
569 if (total_desc_count > 0) {
570 characteristic_resp.descriptors.init(total_desc_count);
571 uint16_t desc_offset = 0;
572 esp_gattc_descr_elem_t desc_result;
573 while (desc_offset < total_desc_count) {
574 uint16_t dc = 1;
575 auto desc_status = esp_ble_gattc_get_all_descr(this->gattc_if_, this->conn_id_, char_result.char_handle,
576 &desc_result, &dc, desc_offset);
577 if (desc_status != ESP_GATT_OK || dc == 0) {
578 this->log_gattc_warning_("esp_ble_gattc_get_all_descr", desc_status);
579 conn.abort_service_stream(desc_status != ESP_GATT_OK ? desc_status : ESP_GATT_NOT_FOUND);
580 return;
581 }
582 characteristic_resp.descriptors.emplace_back();
583 auto &descriptor_resp = characteristic_resp.descriptors.back();
584 fill_gatt_uuid(descriptor_resp.uuid, descriptor_resp.short_uuid,
585 ble_device_base::ESPBTUUID::from_uuid(desc_result.uuid), use_efficient_uuids);
586 descriptor_resp.handle = desc_result.handle;
587 desc_offset++;
588 }
589 }
590 char_offset++;
591 }
592 }
593
594 if (close_service_batch(resp, current_size, conn.send_service_, conn.connection_index_, conn.address_str_) !=
596 break;
597 }
598 }
599
600 // On a failed send, rewind the cursor so the batch is retried instead of
601 // silently skipped.
602 if (!api_conn->send_message(resp)) {
603 conn.note_batch_stalled_();
604 conn.send_service_ = batch_start;
605 return;
606 }
607 conn.batch_stalled_ = false;
608}
609#endif // USE_BLUETOOTH_PROXY_CONNECTIONS
610
611// ---- events ----
612
613void BluedroidGattClient::handle_open_evt_(esp_ble_gattc_cb_param_t *param) {
614 auto st = this->state();
615 if (st == ClientState::IDLE) {
616 // Late OPEN_EVT after the slot went IDLE (open-error race, or the
617 // teardown net gave up): close a won link, never resurrect the slot.
618 ESP_LOGD(TAG, "[%d] OPEN_EVT in IDLE state (status=%d)", this->connection_index_, param->open.status);
619 if (param->open.status == ESP_GATT_OK || param->open.status == ESP_GATT_ALREADY_OPEN) {
620 // A failed close here leaks a live link nothing tracks; make it heard.
621 this->check_and_log_error_("esp_ble_gattc_close", esp_ble_gattc_close(this->gattc_if_, param->open.conn_id));
622 }
623 return;
624 }
625 if (st != ClientState::CONNECTING) {
626 ESP_LOGE(TAG, "[%d] OPEN_EVT in unexpected state", this->connection_index_);
627 }
628 if (param->open.status != ESP_GATT_OK && param->open.status != ESP_GATT_ALREADY_OPEN) {
629 this->log_gattc_warning_("Connection open", param->open.status);
630 // Never established, CLOSE_EVT may not follow.
631 this->set_idle_();
632 this->listener_->on_connection_state(false, 0, param->open.status);
633 return;
634 }
635 // ALREADY_OPEN on an existing link sends no CONNECT_EVT, so take the id here.
636 this->conn_id_ = param->open.conn_id;
637 // Reported before the teardown below: the link came up even if it closes right away
638 this->listener_->on_link_open(true);
639 if (this->disconnect_pending()) {
640 // Open resolved with a teardown scheduled: close now (conn_id_ stays set
641 // so CLOSE_EVT still matches).
643 return;
644 }
645 this->set_state(ClientState::CONNECTED);
646 ESP_LOGI(TAG, "[%d] Connection open", this->connection_index_);
647 if (this->connection_type_ == ConnectionType::V3_WITH_CACHE) {
648 this->set_state(ClientState::ESTABLISHED);
649 // No discovery phase: report immediately with the default MTU. The
650 // cached path never waits for (or reports) the exchange - seen_mtu_
651 // suppresses the CFG_MTU report, matching the previous esp32 behavior.
652 this->seen_mtu_ = true;
653 this->listener_->on_connection_state(true, ble_device_base::DEFAULT_ATT_MTU, 0);
654 } else {
655 // Discovery-bound connection: start the search now so it overlaps the
656 // MTU exchange. On a refusal fall back to the serialized path - the
657 // consumer's own discover_services() call retries the real search.
658 if (this->check_and_log_error_("esp_ble_gattc_search_service",
659 esp_ble_gattc_search_service(this->gattc_if_, param->open.conn_id, nullptr)) == 0) {
661 }
662 if (this->mtu_failed_ && !this->seen_mtu_) {
663 // Refused MTU request: report with the default so the consumer
664 // proceeds.
665 this->seen_mtu_ = true;
666 this->listener_->on_connection_state(true, ble_device_base::DEFAULT_ATT_MTU, 0);
668 }
669 }
670}
671
672void BluedroidGattClient::handle_disconnect_evt_(esp_ble_gattc_cb_param_t *param) {
673 if (param->disconnect.reason == ESP_GATT_CONN_TERMINATE_PEER_USER && this->state() == ClientState::CONNECTED) {
674 ESP_LOGW(TAG, "[%d] Remote closed during discovery", this->connection_index_);
675 } else {
676 ESP_LOGD(TAG, "[%d] DISCONNECT_EVT reason=0x%02x", this->connection_index_, param->disconnect.reason);
677 }
678 // A failed establish arrives here as 0x3e before OPEN_EVT, whose status is only the generic 133
679 if (this->state() == ClientState::CONNECTING && param->disconnect.reason == ESP_GATT_CONN_FAIL_ESTABLISH)
680 this->listener_->on_link_open(false);
681 if (this->state() == ClientState::IDLE) {
682 // Active close delivers CLOSE_EVT first; never walk back to DISCONNECTING.
683 return;
684 }
685 if (this->conn_id_ == UNSET_CONN_ID) {
686 // No CONNECT_EVT for this attempt yet, so the event belongs to an earlier
687 // link, such as one the teardown timeout forced down.
688 return;
689 }
690 // Passive disconnect: wait for CLOSE_EVT before going IDLE (reconnecting
691 // earlier makes the controller reject with 133 or assert) and before
692 // reporting - the wrapper frees the slot on the report, and a freed slot
693 // invites a reconnect into the still-closing link.
694 this->release_services();
695 this->set_disconnecting_();
696}
697
698bool BluedroidGattClient::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t esp_gattc_if,
699 esp_ble_gattc_cb_param_t *param) {
700 if (event == ESP_GATTC_REG_EVT && this->app_id != param->reg.app_id)
701 return false;
702 if (event != ESP_GATTC_REG_EVT && esp_gattc_if != ESP_GATT_IF_NONE && esp_gattc_if != this->gattc_if_)
703 return false;
704
705 switch (event) {
706 case ESP_GATTC_REG_EVT: {
707 if (param->reg.status == ESP_GATT_OK) {
708 this->gattc_if_ = esp_gattc_if;
709 } else {
710 ESP_LOGE(TAG, "[%d] gattc app registration failed, status=%d", this->connection_index_, param->reg.status);
711 this->mark_failed(
712 LOG_STR("Registration failed; if the error was ESP_GATT_NO_RESOURCES, reduce the connection slots"));
713 }
714 break;
715 }
716 case ESP_GATTC_CONNECT_EVT: {
717 if (!this->check_addr_(param->connect.remote_bda))
718 return false;
719 // Every client interface gets CONNECT_EVT for every new link; only an
720 // attempt in flight owns it. An idle slot must not adopt another slot's link.
721 if (this->state() != ClientState::CONNECTING)
722 break;
723 this->conn_id_ = param->connect.conn_id;
724 // MTU request here rather than OPEN_EVT, matching the IDF examples.
725 auto ret = esp_ble_gattc_send_mtu_req(this->gattc_if_, param->connect.conn_id);
726 if (ret) {
727 this->log_gattc_warning_("esp_ble_gattc_send_mtu_req", ret);
728 // No CFG_MTU_EVT will follow; OPEN_EVT reports with the default.
729 this->mtu_failed_ = true;
730 }
731 break;
732 }
733 case ESP_GATTC_OPEN_EVT: {
734 if (!this->check_addr_(param->open.remote_bda)) {
735 // Our interface (filtered above), stale address, so nobody tracks this link.
736 if (param->open.status == ESP_GATT_OK || param->open.status == ESP_GATT_ALREADY_OPEN) {
737 ESP_LOGW(TAG, "[%d] Closing link left by an abandoned open", this->connection_index_);
738 this->check_and_log_error_("esp_ble_gattc_close", esp_ble_gattc_close(this->gattc_if_, param->open.conn_id));
739 return true;
740 }
741 return false;
742 }
743 this->handle_open_evt_(param);
744 break;
745 }
746 case ESP_GATTC_CFG_MTU_EVT: {
747 if (this->conn_id_ != param->cfg_mtu.conn_id)
748 return false;
749 if (param->cfg_mtu.status != ESP_GATT_OK) {
750 // Warn only; a disconnect will follow if the link is dead.
751 this->log_gattc_warning_("MTU exchange", param->cfg_mtu.status);
752 }
753 if (!this->seen_mtu_ && !this->disconnect_pending() && this->state() != ClientState::DISCONNECTING) {
754 // Teardown owns the link: suppress the connected report here like
755 // OPEN_EVT and SEARCH_CMPL do; the terminal report settles it.
756 this->seen_mtu_ = true;
757 // The connected report waited for the MTU; forwarded, not stored.
759 true, param->cfg_mtu.status == ESP_GATT_OK ? param->cfg_mtu.mtu : ble_device_base::DEFAULT_ATT_MTU, 0);
760 // The consumer requests discovery from inside that report; when the
761 // pre-started search already finished, complete it in the same drain.
763 }
764 break;
765 }
766 case ESP_GATTC_DISCONNECT_EVT: {
767 if (!this->check_addr_(param->disconnect.remote_bda))
768 return false;
769 this->handle_disconnect_evt_(param);
770 break;
771 }
772 case ESP_GATTC_CLOSE_EVT: {
773 if (this->conn_id_ != param->close.conn_id)
774 return false;
775 this->release_services();
776 this->set_idle_();
777 // The one connected=false report: the wrapper frees the slot on it,
778 // so it must not fire before the controller finished closing.
779 this->listener_->on_connection_state(false, 0, param->close.reason);
780 break;
781 }
782 case ESP_GATTC_SEARCH_CMPL_EVT: {
783 if (this->conn_id_ != param->search_cmpl.conn_id)
784 return false;
785 ESP_LOGI(TAG, "[%d] Service discovery complete", this->connection_index_);
786 if (this->state() == ClientState::DISCONNECTING) {
787 // Teardown owns the link; the result is never delivered, skip the
788 // work.
789 break;
790 }
791 this->search_status_ = this->handle_search_cmpl_(static_cast<esp_gatt_status_t>(param->search_cmpl.status));
792 this->search_state_ =
794 this->set_state(ClientState::ESTABLISHED);
796 break;
797 }
798 case ESP_GATTC_READ_CHAR_EVT:
799 case ESP_GATTC_READ_DESCR_EVT: {
800 if (this->conn_id_ != param->read.conn_id)
801 return false;
802 bool ok = param->read.status == ESP_GATT_OK;
803 this->listener_->on_read_result(param->read.handle, ok ? param->read.value : nullptr,
804 ok ? param->read.value_len : 0, ok ? 0 : param->read.status);
805 break;
806 }
807 case ESP_GATTC_WRITE_CHAR_EVT:
808 case ESP_GATTC_WRITE_DESCR_EVT: {
809 if (this->conn_id_ != param->write.conn_id)
810 return false;
811 this->listener_->on_write_result(param->write.handle,
812 param->write.status == ESP_GATT_OK ? 0 : param->write.status);
813 break;
814 }
815 case ESP_GATTC_REG_FOR_NOTIFY_EVT: {
816 this->listener_->on_notify_state(param->reg_for_notify.handle, true,
817 param->reg_for_notify.status == ESP_GATT_OK ? 0 : param->reg_for_notify.status);
818 break;
819 }
820 case ESP_GATTC_UNREG_FOR_NOTIFY_EVT: {
822 param->unreg_for_notify.handle, false,
823 param->unreg_for_notify.status == ESP_GATT_OK ? 0 : param->unreg_for_notify.status);
824 break;
825 }
826 case ESP_GATTC_NOTIFY_EVT: {
827 if (this->conn_id_ != param->notify.conn_id)
828 return false;
829 ESP_LOGV(TAG, "[%d] NOTIFY_EVT handle=0x%2X", this->connection_index_, param->notify.handle);
830 this->listener_->on_notify_data(param->notify.handle, param->notify.value, param->notify.value_len);
831 break;
832 }
833#ifdef BLUEDROID_HAS_CANCEL_OPEN
834 case ESP_GATTC_CANCEL_OPEN_EVT: {
835 if (!this->check_addr_(param->cancel_open.remote_bda))
836 return false;
837 if (param->cancel_open.status != ESP_GATT_OK) {
838 // Too late to cancel: OPEN_EVT follows and settles the slot. The latch
839 // stays set because the event cannot be tied to this attempt's cancel.
840 break;
841 }
842 if (this->state() == ClientState::CONNECTING && this->disconnect_pending()) {
843 ESP_LOGD(TAG, "[%d] Pending open cancelled", this->connection_index_);
844 this->release_services();
845 this->set_idle_();
846 this->listener_->on_connection_state(false, 0, ESP_GATT_CONN_CONN_CANCEL);
847 }
848 break;
849 }
850#endif
851 default:
852 break;
853 }
854 return true;
855}
856
857void BluedroidGattClient::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
858 switch (event) {
859 case ESP_GAP_BLE_SEC_REQ_EVT: {
860 if (!this->check_addr_(param->ble_security.auth_cmpl.bd_addr))
861 break;
862 // Always accept; a refused response means no AUTH_CMPL, so answer the
863 // pairing request with the failure.
864 int sec_err = this->check_and_log_error_("esp_ble_gap_security_rsp",
865 esp_ble_gap_security_rsp(param->ble_security.ble_req.bd_addr, true));
866 if (sec_err != 0) {
867 this->listener_->on_pairing_result(sec_err);
868 }
869 break;
870 }
871 case ESP_GAP_BLE_AUTH_CMPL_EVT: {
872 if (!this->check_addr_(param->ble_security.auth_cmpl.bd_addr))
873 break;
875 param->ble_security.auth_cmpl.success ? 0 : param->ble_security.auth_cmpl.fail_reason);
876 break;
877 }
878 default:
879 break;
880 }
881}
882
883} // namespace esphome::bluetooth_connection
884
885#endif // USE_ESP32_BLE && USE_BLE_GATT_CLIENT
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:262
void disable_loop()
Disable this component's loop.
std::vector< BluetoothGATTService > services
Definition api_pb2.h:2624
static ESPBTUUID from_uuid(esp_bt_uuid_t uuid)
Source compatibility with the historical esp32_ble API (esp32 builds only).
virtual void on_notify_state(uint16_t handle, bool enabled, int error)
virtual void on_notify_data(uint16_t handle, const uint8_t *data, uint16_t len)
virtual void on_write_result(uint16_t handle, int error)
virtual void on_connection_state(bool connected, uint16_t mtu, int error)
virtual void on_read_result(uint16_t handle, const uint8_t *data, uint16_t len, int error)
virtual void on_link_open(bool established)
The link came up (true) or failed to establish with HCI 0x3e (false).
esp_err_t update_conn_params_(uint16_t min_interval, uint16_t max_interval, uint16_t latency, uint16_t timeout, const char *param_type)
int write_descriptor(uint16_t handle, const uint8_t *data, uint16_t len)
int write_characteristic(uint16_t handle, const uint8_t *data, uint16_t len, bool response)
int update_connection_params(uint16_t min_interval, uint16_t max_interval, uint16_t latency, uint16_t timeout)
void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) override
bool gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) override
void stream_service_batch(BluetoothConnection &conn)
In-place service streamer (the proxy wrapper detects and prefers it): builds one api response batch d...
void abort_service_stream(conn_err_t err)
Streamer abort: latch the GATT cause, park the cursor, tear down.
bool batch_stalled_
Set while a refused batch is retrying, so only the first one warns.
void send_services_done_()
Send services-done and settle the cursor: DONE when it lands (or no subscriber), SERVICES_DONE_PENDIN...
void park_service_stream_()
Park the stream without services-done and free any held table: an interrupted stream must never be de...
void note_batch_stalled_()
Warn on the stall's leading edge only.
bool client_supports_efficient_uuids() const
Whether the subscribed API client understands 16/32-bit UUID fields.
virtual void set_state(ClientState st)
Set the client state with IDLE handling (clears want_disconnect_).
int ret
void uint64_to_mac_msb_first(uint64_t address, uint8_t out[6])
Unpack a uint64 BLE address into printable (MSB-first) byte order — the order bd_addr_t / esp_bd_addr...
Definition ble_device.h:205
size_t estimate_service_size(uint16_t char_count, bool use_efficient_uuids)
Estimate the wire size of a service (service overhead + its characteristics, assuming 128-bit UUIDs a...
ESPHOME_LOG_TAG(TAG, "bluetooth_connection")
BatchClose close_service_batch(api::BluetoothGATTGetServicesResponse &resp, size_t &current_size, int16_t &send_service, uint8_t connection_index, const char *address_str)
Close out the service just packed into resp (account its actual wire size, advance the cursor) and de...
void fill_gatt_uuid(std::array< uint64_t, 2 > &uuid_128, uint32_t &short_uuid, const ble_device_base::ESPBTUUID &uuid, bool use_efficient_uuids)
Fill the UUID in the appropriate wire format based on client support and UUID type (128-bit array for...
void coex_ble_priority_acquire()
Give BLE priority over WiFi on the shared radio while a GATT client discovers services.
ESP32BLE * global_ble
Definition ble.cpp:932
const void size_t len
Definition hal.h:68
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
spi_device_handle_t handle