ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
bluetooth_connection_rp2.cpp
Go to the documentation of this file.
2
4
5#if defined(USE_RP2040_BLE) && defined(USE_BLE_GATT_CLIENT)
6
7#include "esphome/core/hal.h"
9#include "esphome/core/log.h"
10
11#include <BluetoothLock.h>
12
13#include <cstring>
14
16
17ESPHOME_LOG_TAG(TAG, "bluetooth_connection");
18
19using ble_device_base::GATT_ERR_NOT_CONNECTED;
20using ble_device_base::GATT_ERR_NO_MEMORY;
21
22// Engine-owned timeouts: BTstack has a 30 s ATT transaction timeout but no
23// connect timeout — a stuck LE_CONNECTING both blocks future gap_connect calls
24// and keeps the scan inhibited, so the engine cancels after 20 s. The
25// disconnect timeout mirrors the esp32 CLOSE_EVT safety net.
26static constexpr uint32_t CONNECT_TIMEOUT_MS = 20000;
27// Budget after a cancel is in flight: its completion normally lands within
28// tens of ms, and while the engine waits it pins the stack-wide connect slot,
29// so a lost completion must cost seconds, not another full connect budget.
30static constexpr uint32_t CONNECT_CANCEL_TIMEOUT_MS = 2000;
31// Pending engines re-attempt gap_connect on this cadence instead of every
32// loop pass: the DISALLOWED path (teardown overlap) takes BluetoothLock.
33static constexpr uint32_t CONNECT_RETRY_INTERVAL_MS = 50;
34// Can-send windows normally open within a connection interval (tens of ms).
35static constexpr uint32_t WRITE_NO_RSP_TIMEOUT_MS = 500;
36
37// HCI "connection timeout" reason, reported when a teardown had to be forced.
38static constexpr uint8_t HCI_REASON_CONNECTION_TIMEOUT = 0x08;
39
40// Initiating-scan parameters and connection-event lengths for outgoing
41// connections (BTstack-specific knobs; the connection intervals themselves are
42// the shared FAST/MEDIUM parameters from ble_device_base/ble_client_state.h,
43// used in the same lifecycle places as esp32: FAST for connect and service
44// discovery, MEDIUM once established).
45static constexpr uint16_t CONN_SCAN_INTERVAL = 96; // 60 ms in 0.625 ms units
46static constexpr uint16_t CONN_SCAN_WINDOW = 48; // 30 ms in 0.625 ms units
47static constexpr uint16_t CONN_CE_MIN = 16; // 10 ms in 0.625 ms units
48static constexpr uint16_t CONN_CE_MAX = 48; // 30 ms in 0.625 ms units
49
50using ble_device_base::FAST_CONN_TIMEOUT;
51using ble_device_base::FAST_MAX_CONN_INTERVAL;
52using ble_device_base::FAST_MIN_CONN_INTERVAL;
53using ble_device_base::MEDIUM_CONN_TIMEOUT;
54using ble_device_base::MEDIUM_MAX_CONN_INTERVAL;
55using ble_device_base::MEDIUM_MIN_CONN_INTERVAL;
56
57// NOLINTBEGIN(cppcoreguidelines-avoid-non-const-global-variables)
58RP2GattClient *RP2GattClient::instances[ESPHOME_BLE_GATT_CLIENT_COUNT] = {};
60btstack_packet_callback_registration_t RP2GattClient::hci_event_registration = {};
61btstack_packet_callback_registration_t RP2GattClient::sm_event_registration = {};
62RP2GattClient *RP2GattClient::connect_owner = nullptr;
63// NOLINTEND(cppcoreguidelines-avoid-non-const-global-variables)
64
66 // Pre-create every pool entry so the packet handlers' allocate() calls are
67 // always a free-list pop -- the IRQ path must never reach malloc().
68 if (!this->event_pool_.warm() || !this->notify_pool_.warm()) {
69 this->mark_failed(LOG_STR("GATT event pool warm-up failed"));
70 return;
71 }
72
73 // Register this engine for IRQ-context event routing.
74 if (instance_count >= ESPHOME_BLE_GATT_CLIENT_COUNT) {
75 // Cannot happen with codegen-sized storage; refuse loudly if it ever does.
76 this->mark_failed(LOG_STR("GATT client registry full"));
77 return;
78 }
79 {
80 // One locked section: the slot store lands before the count bump, and a
81 // live HCI handler (N > 1 builds) cannot read a half-written registry.
82 BluetoothLock lock;
86 // One HCI event handler for all engine instances (BTstack supports
87 // multiple registrations, so rp2040_ble's own handler is unaffected).
88 if (hci_event_registration.callback == nullptr) {
90 hci_add_event_handler(&hci_event_registration);
92 sm_add_event_handler(&sm_event_registration);
93 }
94 }
95
96#ifdef USE_OTA_STATE_LISTENER
97 ota::get_global_ota_callback()->add_global_state_listener(this);
98#endif
99
100 this->disable_loop();
101}
102
103#ifdef USE_OTA_STATE_LISTENER
104void RP2GattClient::on_ota_global_state(ota::OTAState state, float progress, uint8_t error, ota::OTAComponent *comp) {
105 // esp32 parity (its tracker disconnects every client at OTA start): free
106 // the shared radio for the transfer. No restore needed; the client
107 // reconnects, and on success the device reboots anyway.
108 if (state == ota::OTA_STARTED && this->state_ != EngineState::IDLE) {
109 this->gatt_disconnect();
110 }
111}
112#endif
113
115
116void RP2GattClient::dump_config() { ESP_LOGCONFIG(TAG, "RP2 GATT client (BTstack)"); }
117
118// ---- IRQ-context handlers: copy-and-enqueue only ----
119
121 for (uint8_t i = 0; i < instance_count; i++) {
122 if (instances[i]->con_handle_ == con_handle) {
123 return instances[i];
124 }
125 }
126 return nullptr;
127}
128
129void RP2GattClient::hci_packet_handler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t size) {
130 if (type != HCI_EVENT_PACKET) {
131 return;
132 }
133 uint8_t event_type = hci_event_packet_get_type(packet);
134 switch (event_type) {
135 case HCI_EVENT_META_GAP: {
136 if (hci_event_gap_meta_get_subevent_code(packet) != GAP_SUBEVENT_LE_CONNECTION_COMPLETE) {
137 break;
138 }
139 uint8_t status = gap_subevent_le_connection_complete_get_status(packet);
140 hci_con_handle_t con_handle = gap_subevent_le_connection_complete_get_connection_handle(packet);
141 bd_addr_t peer;
142 gap_subevent_le_connection_complete_get_peer_address(packet, peer);
143 // Route by ownership, not address: gap_connect refuses a new
144 // create-connection until the previous completion is processed, so the
145 // event belongs to the owner by construction. Cancel completions carry
146 // a zeroed peer address on this controller, so an address match would
147 // drop them and pin the owner until its backstop.
149 static constexpr bd_addr_t ZERO_ADDR = {};
150 if (inst != nullptr && memcmp(peer, ZERO_ADDR, sizeof(bd_addr_t)) != 0 &&
151 memcmp(inst->peer_addr_, peer, sizeof(bd_addr_t)) != 0) {
152 // Addressed completion for a peer the owner is not connecting to: a
153 // success delayed past a cancel and an ownership handoff (the cancel
154 // idles the stack's request immediately) must not stamp the old
155 // procedure's link onto the new owner. Zero-address (cancel)
156 // completions need no such guard: BTstack only emits them while its
157 // request state is idle, and a new owner re-arms that state when it
158 // claims the token, so a stale cancel completion is swallowed by the
159 // stack, never re-attributed. A successful stale link still needs
160 // disposal (same hazard as the unowned branch below).
161 if (status == 0) {
162 gap_disconnect(con_handle);
163 }
164 break;
165 }
166 connect_owner = nullptr;
167 if (inst == nullptr) {
168 if (status == 0) {
169 // Nobody owns this late link (the owner escalated first): tear it
170 // down here or the hci_connection_t leaks and the peer answers
171 // DISALLOWED until reboot.
172 gap_disconnect(con_handle);
173 }
174 break;
175 }
176 if (status == 0) {
177 // Stamp the handle here in the BTstack context: a disconnection
178 // racing the queued CONNECTED event arrives in this same context
179 // and must route by handle (it carries no address).
180 inst->con_handle_ = con_handle;
181 }
183 break;
184 }
185 case HCI_EVENT_DISCONNECTION_COMPLETE: {
186 // Routable even against a still-queued CONNECTED event: the handle is
187 // stamped in this context at connection-complete time.
188 RP2GattClient *inst = instance_for_con_handle(hci_event_disconnection_complete_get_connection_handle(packet));
189 if (inst != nullptr) {
190 inst->enqueue_event_irq_(RP2GattEvent::DISCONNECTED, hci_event_disconnection_complete_get_reason(packet), 0);
191 }
192 break;
193 }
194 default:
195 break;
196 }
197}
198
199void RP2GattClient::sm_packet_handler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t size) {
200 if (type != HCI_EVENT_PACKET) {
201 return;
202 }
203 switch (hci_event_packet_get_type(packet)) {
204 case SM_EVENT_JUST_WORKS_REQUEST:
205 // Confirming from the SM callback is the intended BTstack pattern.
206 // Unscoped on purpose: no peripheral role exists in-tree, and scoping
207 // would drop a request racing the queued CONNECTED event.
208 sm_just_works_confirm(sm_event_just_works_request_get_handle(packet));
209 break;
210 case SM_EVENT_PAIRING_COMPLETE: {
211 RP2GattClient *inst = instance_for_con_handle(sm_event_pairing_complete_get_handle(packet));
212 if (inst != nullptr) {
213 inst->enqueue_event_irq_(RP2GattEvent::PAIRING_RESULT, sm_event_pairing_complete_get_status(packet), 0);
214 }
215 break;
216 }
217 case SM_EVENT_REENCRYPTION_COMPLETE: {
218 // A bonded peer re-encrypts instead of pairing; BTstack emits only this
219 // event on that path, so it answers the PAIR request too.
220 RP2GattClient *inst = instance_for_con_handle(sm_event_reencryption_complete_get_handle(packet));
221 if (inst != nullptr) {
222 inst->enqueue_event_irq_(RP2GattEvent::PAIRING_RESULT, sm_event_reencryption_complete_get_status(packet), 0);
223 }
224 break;
225 }
226 default:
227 break;
228 }
229}
230
231void RP2GattClient::gatt_packet_handler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t size) {
232 if (type != HCI_EVENT_PACKET) {
233 return;
234 }
235 uint8_t event_type = hci_event_packet_get_type(packet);
236 // Every GATT event carries the connection handle in the same position via
237 // its accessor; route on it.
238 hci_con_handle_t con_handle;
239 switch (event_type) {
240 case GATT_EVENT_MTU:
241 con_handle = gatt_event_mtu_get_handle(packet);
242 break;
243 case GATT_EVENT_SERVICE_QUERY_RESULT:
244 con_handle = gatt_event_service_query_result_get_handle(packet);
245 break;
246 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
247 con_handle = gatt_event_characteristic_query_result_get_handle(packet);
248 break;
249 case GATT_EVENT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
250 con_handle = gatt_event_all_characteristic_descriptors_query_result_get_handle(packet);
251 break;
252 case GATT_EVENT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT:
253 con_handle = gatt_event_long_characteristic_value_query_result_get_handle(packet);
254 break;
255 case GATT_EVENT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
256 con_handle = gatt_event_long_characteristic_descriptor_query_result_get_handle(packet);
257 break;
258 case GATT_EVENT_NOTIFICATION:
259 con_handle = gatt_event_notification_get_handle(packet);
260 break;
261 case GATT_EVENT_INDICATION:
262 con_handle = gatt_event_indication_get_handle(packet);
263 break;
264 case GATT_EVENT_QUERY_COMPLETE:
265 con_handle = gatt_event_query_complete_get_handle(packet);
266 break;
267 default:
268 return;
269 }
270 RP2GattClient *inst = instance_for_con_handle(con_handle);
271 if (inst != nullptr) {
272 inst->handle_gatt_event_irq_(event_type, packet);
273 }
274}
275
276void RP2GattClient::handle_gatt_event_irq_(uint8_t event_type, const uint8_t *packet) {
277 switch (event_type) {
278 case GATT_EVENT_MTU:
279 this->enqueue_event_irq_(RP2GattEvent::MTU_EXCHANGED, 0, gatt_event_mtu_get_MTU(packet));
280 break;
281 case GATT_EVENT_QUERY_COMPLETE:
282 this->enqueue_event_irq_(RP2GattEvent::QUERY_COMPLETE, gatt_event_query_complete_get_att_status(packet), 0);
283 break;
284 case GATT_EVENT_SERVICE_QUERY_RESULT: {
285 if (this->arena_ == nullptr) {
286 break;
287 }
288 if (this->service_count_ >= RP2_GATT_MAX_SERVICES) {
289 this->truncated_ = true;
290 break;
291 }
292 gatt_client_service_t service;
293 gatt_event_service_query_result_get_service(packet, &service);
294 // Not uuid16: BTstack stores a 32-bit base UUID there truncated to its low 16 bits
295 auto &dst = this->arena_->services[this->service_count_];
296 dst.uuid = uuid_from_be128(service.uuid128);
297 dst.start_handle = service.start_group_handle;
298 dst.end_handle = service.end_group_handle;
299 dst.first_characteristic = 0;
300 dst.characteristic_count = 0;
301 this->service_count_++;
302 break;
303 }
304 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT: {
305 if (this->arena_ == nullptr) {
306 break;
307 }
308 if (this->char_count_ >= RP2_GATT_MAX_CHARACTERISTICS) {
309 this->truncated_ = true;
310 break;
311 }
312 gatt_client_characteristic_t characteristic;
313 gatt_event_characteristic_query_result_get_characteristic(packet, &characteristic);
314 auto &dst = this->arena_->characteristics[this->char_count_];
315 dst.uuid = uuid_from_be128(characteristic.uuid128);
316 dst.value_handle = characteristic.value_handle;
317 dst.end_handle = characteristic.end_handle;
318 dst.properties = static_cast<uint8_t>(characteristic.properties);
319 dst.first_descriptor = 0;
320 dst.descriptor_count = 0;
321 this->char_count_++;
322 break;
323 }
324 case GATT_EVENT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT: {
325 if (this->arena_ == nullptr) {
326 break;
327 }
328 if (this->desc_count_ >= RP2_GATT_MAX_DESCRIPTORS) {
329 this->truncated_ = true;
330 break;
331 }
332 gatt_client_characteristic_descriptor_t descriptor;
333 gatt_event_all_characteristic_descriptors_query_result_get_characteristic_descriptor(packet, &descriptor);
334 auto &dst = this->arena_->descriptors[this->desc_count_];
335 dst.uuid = uuid_from_be128(descriptor.uuid128);
336 dst.handle = descriptor.handle;
337 this->desc_count_++;
338 break;
339 }
340 case GATT_EVENT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT:
341 // One blob per event at the reported offset; assemble into the op buffer.
342 this->assemble_blob_irq_(gatt_event_long_characteristic_value_query_result_get_value_offset(packet),
343 gatt_event_long_characteristic_value_query_result_get_value(packet),
344 gatt_event_long_characteristic_value_query_result_get_value_length(packet));
345 break;
346 case GATT_EVENT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
347 this->assemble_blob_irq_(gatt_event_long_characteristic_descriptor_query_result_get_descriptor_offset(packet),
348 gatt_event_long_characteristic_descriptor_query_result_get_descriptor(packet),
349 gatt_event_long_characteristic_descriptor_query_result_get_descriptor_length(packet));
350 break;
351 case GATT_EVENT_NOTIFICATION:
352 this->enqueue_notify_irq_(gatt_event_notification_get_value_handle(packet),
353 gatt_event_notification_get_value(packet),
354 gatt_event_notification_get_value_length(packet));
355 break;
356 case GATT_EVENT_INDICATION:
357 // BTstack auto-confirms indications; deliver like a notification.
358 this->enqueue_notify_irq_(gatt_event_indication_get_value_handle(packet), gatt_event_indication_get_value(packet),
359 gatt_event_indication_get_value_length(packet));
360 break;
361 default:
362 break;
363 }
364}
365
366// NOLINTBEGIN(clang-analyzer-unix.Malloc)
367void RP2GattClient::assemble_blob_irq_(uint16_t offset, const uint8_t *data, uint16_t len) {
368 if (offset >= RP2_GATT_MAX_ATTR_LEN) {
369 return;
370 }
371 if (len > RP2_GATT_MAX_ATTR_LEN - offset) {
372 len = RP2_GATT_MAX_ATTR_LEN - offset;
373 }
374 memcpy(this->op_buffer_ + offset, data, len);
375 if (offset + len > this->op_len_) {
376 this->op_len_ = offset + len;
377 }
378}
379
381 RP2GattEvent *event = this->event_pool_.allocate();
382 if (event == nullptr) {
383 this->event_queue_.increment_dropped_count();
385 return;
386 }
387 event->type = type;
388 event->status = status;
389 event->value = value;
390 this->event_queue_.push(event);
392}
393
394void RP2GattClient::enqueue_notify_irq_(uint16_t handle, const uint8_t *data, uint16_t len) {
395 RP2GattNotifyEvent *event = this->notify_pool_.allocate();
396 if (event == nullptr) {
397 this->notify_queue_.increment_dropped_count();
399 return;
400 }
401 event->handle = handle;
402 event->len = len > RP2_GATT_MAX_ATTR_LEN ? RP2_GATT_MAX_ATTR_LEN : len;
403 memcpy(event->data, data, event->len);
404 this->notify_queue_.push(event);
406}
407// NOLINTEND(clang-analyzer-unix.Malloc)
408
409// ---- Main-loop state machine ----
410
412 RP2GattEvent *event;
413 while ((event = this->event_queue_.pop()) != nullptr) {
414 RP2GattEvent copy = *event;
415 this->event_pool_.release(event);
416 this->handle_event_(copy);
417 }
418
419 RP2GattNotifyEvent *notify;
420 while ((notify = this->notify_queue_.pop()) != nullptr) {
421 if (this->notify_subscribed_(notify->handle)) {
422 this->listener_->on_notify_data(notify->handle, notify->data, notify->len);
423 }
424 this->notify_pool_.release(notify);
425 }
426
427 uint16_t dropped = this->event_queue_.get_and_reset_dropped_count();
428 if (dropped > 0) {
429 // Control events must not be lost; the connection state is no longer
430 // trustworthy — recover with a forced teardown.
431 ESP_LOGE(TAG, "[%u] Dropped %u GATT control events, disconnecting", this->engine_index_, dropped);
432 this->gatt_disconnect();
433 }
434 uint16_t notify_dropped = this->notify_queue_.get_and_reset_dropped_count();
435 if (notify_dropped > 0) {
436 ESP_LOGW(TAG, "[%u] Dropped %u GATT notifications (queue full)", this->engine_index_, notify_dropped);
437 }
438
440 uint32_t now = millis();
441 if (now - this->connect_started_ > CONNECT_TIMEOUT_MS) {
442 // Never reached the radio; nothing stack-side to cancel.
443 ESP_LOGW(TAG, "[%u] Connect timeout (queued)", this->engine_index_);
444 this->fail_connection_(HCI_REASON_CONNECTION_TIMEOUT);
445 } else if (now - this->connect_retry_ms_ >= CONNECT_RETRY_INTERVAL_MS) {
446 this->connect_retry_ms_ = now;
447 if (int err = this->try_gap_connect_(); err != 0) {
448 this->fail_connection_(static_cast<uint8_t>(err));
449 }
450 }
451 } else if (this->state_ == EngineState::CONNECTING || this->state_ == EngineState::MTU_EXCHANGE) {
452 uint32_t now = millis();
453 bool cancel_in_flight = this->state_ == EngineState::CONNECTING && this->con_handle_ == HCI_CON_HANDLE_INVALID &&
455 uint32_t budget = cancel_in_flight ? CONNECT_CANCEL_TIMEOUT_MS : CONNECT_TIMEOUT_MS;
456 if (now - this->connect_started_ > budget) {
457 ESP_LOGW(TAG, "[%u] Connect timeout", this->engine_index_);
458 bool link_up = this->state_ != EngineState::CONNECTING;
459 bool cancel_sent = false;
460 if (!link_up) {
461 BluetoothLock lock;
462 // Handle check under the lock: a success completion can stamp it in
463 // the BTstack context right up to this point, and escalating past a
464 // live link would orphan it (the queued CONNECTED event is dropped
465 // by the state guard once fail_connection_ runs).
466 link_up = this->con_handle_ != HCI_CON_HANDLE_INVALID;
467 if (!link_up && connect_owner == this) {
468 // gap_connect_cancel is stack-global; only the engine whose
469 // create-connection is in flight may issue it. First timeout:
470 // cancel and give the completion a grace period. Second: the
471 // completion was lost, re-issue the cancel in case the procedure
472 // still runs (a no-op on an idle stack), then escalate.
473 gap_connect_cancel();
474 cancel_sent = !this->connect_cancel_attempted_;
475 }
476 this->connect_cancel_attempted_ = true;
477 }
478 if (link_up) {
479 // The link is up (stamped mid-timeout or MTU exchange stalled): tear
480 // it down properly so the controller frees its side; the
481 // DISCONNECTING safety net below reclaims state if the disconnection
482 // event is lost. Dropping engine state without gap_disconnect would
483 // leak the live link and this engine's GATT slot for the rest of the
484 // boot.
485 this->gatt_disconnect();
486 } else if (cancel_sent) {
487 // The cancel produces a connection-complete event with a failure
488 // status, which drives the normal failure path; restart the timer so
489 // a lost event escalates on the short cancel budget.
490 this->connect_started_ = now;
491 } else {
492 this->fail_connection_(HCI_REASON_CONNECTION_TIMEOUT);
493 }
494 }
495 } else if (this->state_ == EngineState::DISCONNECTING) {
496 if (millis() - this->disconnecting_started_ > ble_device_base::GATT_DISCONNECT_TIMEOUT_MS) {
497 ESP_LOGW(TAG, "[%u] Disconnect timeout, forcing idle", this->engine_index_);
498 this->handle_disconnected_(HCI_REASON_CONNECTION_TIMEOUT);
499 }
500 } else if (this->state_ == EngineState::READY && this->op_type_ == OpType::WRITE_CHAR_NO_RSP &&
501 millis() - this->write_no_rsp_started_ > WRITE_NO_RSP_TIMEOUT_MS) {
502 // The can-send window never opened; report instead of hanging the op slot.
503 bool timed_out = false;
504 {
505 BluetoothLock lock;
506 // The trampoline may have just sent it; its queued result wins.
507 if (this->event_queue_.empty()) {
508 this->op_type_ = OpType::NONE;
509 timed_out = true;
510 }
511 }
512 if (timed_out) {
513 ESP_LOGW(TAG, "[%u] Deferred write timeout, handle=0x%04x", this->engine_index_, this->op_handle_);
514 this->listener_->on_write_result(this->op_handle_, GATT_CLIENT_BUSY);
515 }
516 } else if (this->state_ == EngineState::IDLE || (this->state_ == EngineState::READY && !this->op_in_flight_() &&
517 this->event_queue_.empty() && this->notify_queue_.empty())) {
518 // Nothing pending: the enqueue path re-arms the loop from any context.
519 this->disable_loop();
520 }
521}
522
524 switch (event.type) {
526 this->handle_connected_(event.status, event.value);
527 break;
529 this->handle_disconnected_(event.status);
530 break;
532 if (this->state_ == EngineState::MTU_EXCHANGE) {
533 this->mtu_ = event.value;
534 ESP_LOGV(TAG, "[%u] MTU %u", this->engine_index_, this->mtu_);
536 // Scanning resumes and runs alongside the established connection.
537 this->release_scan_inhibit_();
538 // The first exchange on the link: only now is it established
539 this->listener_->on_link_open(true);
540 this->listener_->on_connection_state(true, this->mtu_, 0);
541 }
542 break;
544 this->handle_query_complete_(event.status);
545 break;
547 this->finish_write_no_rsp_(event.status);
548 break;
550 this->listener_->on_pairing_result(event.status);
551 break;
552 }
553}
554
556 // BTstack context: this callback IS the can-send window, so the deferred
557 // write happens here; only the result is enqueued for the main loop.
558 auto *self = static_cast<RP2GattClient *>(context);
559 if (self->op_type_ != OpType::WRITE_CHAR_NO_RSP) {
560 return;
561 }
562 uint8_t status = gatt_client_write_value_of_characteristic_without_response(self->con_handle_, self->op_handle_,
563 self->op_len_, self->op_buffer_);
564 if ((status == GATT_CLIENT_BUSY || status == BTSTACK_ACL_BUFFERS_FULL) &&
565 gatt_client_request_to_write_without_response(&self->can_write_registration_, self->con_handle_) == 0) {
566 return; // next window retries; a failed re-arm falls through as an error
567 }
568 self->enqueue_event_irq_(RP2GattEvent::WRITE_NO_RSP_DONE, status, 0);
569}
570
572 if (this->op_type_ != OpType::WRITE_CHAR_NO_RSP) {
573 return;
574 }
575 this->op_type_ = OpType::NONE;
576 this->listener_->on_write_result(this->op_handle_, status);
577}
578
579void RP2GattClient::handle_connected_(uint8_t status, uint16_t con_handle) {
580 if (this->state_ != EngineState::CONNECTING) {
581 return;
582 }
583 if (status != 0) {
584 ESP_LOGW(TAG, "[%u] Connect failed, status=0x%02x", this->engine_index_, status);
585 if (status == ERROR_CODE_CONNECTION_FAILED_TO_BE_ESTABLISHED)
586 this->listener_->on_link_open(false);
587 this->fail_connection_(status);
588 return;
589 }
590 if (this->cancel_requested_) {
591 // No link-open report: BTstack may still follow with a 0x3e disconnect, so an earlier strike stays
592 // A disconnect request raced the connection complete and lost; finish
593 // the teardown instead of reporting a connection nobody wants.
594 this->con_handle_ = con_handle;
597 // No more initiating: give the radio back to the scanner during teardown.
598 this->release_scan_inhibit_();
599 uint8_t disc_status;
600 {
601 BluetoothLock lock;
602 disc_status = gap_disconnect(this->con_handle_);
603 }
604 if (disc_status != 0) {
605 this->handle_disconnected_(HCI_REASON_CONNECTION_TIMEOUT);
606 }
607 return;
608 }
609 this->con_handle_ = con_handle;
611 ESP_LOGV(TAG, "[%u] Link up, handle=0x%04x, negotiating MTU", this->engine_index_, con_handle);
612 BluetoothLock lock;
613 // One wildcard listener covers notifications/indications for every
614 // characteristic on this connection; the CCCD writes come from the API
615 // client as plain descriptor writes.
616 gatt_client_listen_for_characteristic_value_updates(&this->notification_registration_,
618 // Auto MTU negotiation is disabled (see rp2040_ble enable hooks), so the
619 // exchange is kicked explicitly; GATT_EVENT_MTU completes it. Without the
620 // explicit kick the MTU would only be exchanged on the first GATT query,
621 // which never happens on a V3_WITH_CACHE connection.
622 // Both registration calls above return void (BTstack 075a078, arduino-pico
623 // 6.1.0); failures surface as a missing GATT_EVENT_MTU and are reclaimed by
624 // the connect timeout in loop().
625 gatt_client_send_mtu_negotiation(&RP2GattClient::gatt_packet_handler, this->con_handle_);
626}
627
629 if (this->holds_scan_inhibit_) {
630 this->holds_scan_inhibit_ = false;
632 }
633}
634
636 {
637 // Timeout escalation can fire with the completion event lost; release the
638 // stack-wide connect slot so pending engines can proceed. Until the old
639 // completion is processed, gap_connect answers any peer with DISALLOWED
640 // (the request-level guard in hci.c); a cancel idles that request
641 // immediately, and a late addressed completion from the old procedure is
642 // then dropped by the owner-peer cross-check in the handler.
643 BluetoothLock lock;
644 if (connect_owner == this) {
645 connect_owner = nullptr;
646 }
647 if (this->state_ == EngineState::CONNECTING && this->con_handle_ != HCI_CON_HANDLE_INVALID) {
648 // A success completion stamped the handle between the escalation
649 // decision and this lock: tear the link down before cleanup wipes the
650 // handle, or it leaks its pool block for the rest of the boot.
651 gap_disconnect(this->con_handle_);
652 }
653 }
654 this->cleanup_link_state_();
655 this->release_scan_inhibit_();
657 this->listener_->on_connection_state(false, 0, reason);
658}
659
661 // Drop notifications queued behind the disconnect so they cannot emit
662 // against a freed slot (address 0) on the next loop.
663 RP2GattNotifyEvent *stale;
664 while ((stale = this->notify_queue_.pop()) != nullptr) {
665 this->notify_pool_.release(stale);
666 }
667 // con_handle_ may be stamped in the BTstack context before the main loop
668 // registers the listener, so a valid handle does not imply a registration;
669 // stop_listening on an unregistered entry is a benign no-op. One lock
670 // scope around check and reset so an IRQ stamp cannot land in between
671 // (unreachable today — ownership is released before cleanup — but the
672 // invariant lives three functions away).
673 {
674 BluetoothLock lock;
675 if (this->con_handle_ != HCI_CON_HANDLE_INVALID) {
676 gatt_client_stop_listening_for_characteristic_value_updates(&this->notification_registration_);
677 }
678 this->con_handle_ = HCI_CON_HANDLE_INVALID;
679 }
681 this->cancel_requested_ = false;
682 this->op_type_ = OpType::NONE;
684 this->release_services();
685}
686
688 if (this->state_ == EngineState::IDLE) {
689 return;
690 }
691 ESP_LOGV(TAG, "[%u] Disconnected, reason=0x%02x", this->engine_index_, reason);
692 if (this->state_ == EngineState::MTU_EXCHANGE) {
693 // BTstack reports a failed establish as a connection followed by a 0x3e disconnect
694 this->listener_->on_link_open(reason != ERROR_CODE_CONNECTION_FAILED_TO_BE_ESTABLISHED);
695 }
696 this->fail_connection_(reason);
697}
698
700 // Stale completions cannot cross connections: the loop drains the whole
701 // event queue every iteration, teardown resets op/discovery state, and a
702 // new discovery is only issued after the new link's MTU event — which in
703 // this BTstack emits no QUERY_COMPLETE (the MTU state machine is separate
704 // from the query state machine). Completions with nothing in flight are
705 // dropped below.
706 if (this->op_type_ != OpType::NONE && this->op_type_ != OpType::WRITE_CHAR_NO_RSP) {
707 OpType op = this->op_type_;
708 this->op_type_ = OpType::NONE;
709 switch (op) {
712 // A value that is an exact multiple of MTU - 1 ends with a trailing
713 // blob request some peers refuse with INVALID_OFFSET; the read is
714 // complete, not failed.
715 if ((att_status == ATT_ERROR_INVALID_OFFSET || att_status == ATT_ERROR_ATTRIBUTE_NOT_LONG) &&
716 this->op_len_ > 0) {
717 att_status = 0;
718 }
719 this->listener_->on_read_result(this->op_handle_, this->op_buffer_, att_status == 0 ? this->op_len_ : 0,
720 att_status);
721 break;
724 this->listener_->on_write_result(this->op_handle_, att_status);
725 break;
726 default:
727 break;
728 }
729 return;
730 }
732 this->advance_discovery_(att_status);
733 }
734}
735
736// ---- Service discovery ----
737
739 if (this->state_ != EngineState::READY) {
740 return GATT_ERR_NOT_CONNECTED;
741 }
742 if (this->op_in_flight_()) {
743 return GATT_CLIENT_IN_WRONG_STATE;
744 }
745 if (this->arena_ == nullptr) {
746 // Transient: freed in release_services() right after the table streams
747 // to the API client (mirrors Bluedroid's own per-connection GATT DB
748 // lifetime on esp32). Checked: a fragmented heap must surface as a
749 // stack error the proxy can report, not a device reset.
751 if (this->arena_ == nullptr) {
752 ESP_LOGE(TAG, "[%u] Service table allocation failed", this->engine_index_);
753 return ble_device_base::GATT_ERR_NO_MEMORY;
754 }
755 }
756 this->service_count_ = 0;
757 this->char_count_ = 0;
758 this->desc_count_ = 0;
759 this->truncated_ = false;
761 BluetoothLock lock;
762 uint8_t status = gatt_client_discover_primary_services(&RP2GattClient::gatt_packet_handler, this->con_handle_);
763 if (status != 0) {
765 this->release_services();
766 return status;
767 }
768 return 0;
769}
770
772 auto &service = this->arena_->services[service_index];
773 gatt_client_service_t btstack_service = {};
774 btstack_service.start_group_handle = service.start_handle;
775 btstack_service.end_group_handle = service.end_handle;
776 service.first_characteristic = this->char_count_;
777 BluetoothLock lock;
778 return gatt_client_discover_characteristics_for_service(&RP2GattClient::gatt_packet_handler, this->con_handle_,
779 &btstack_service);
780}
781
783 auto &chr = this->arena_->characteristics[char_index];
784 gatt_client_characteristic_t btstack_characteristic = {};
785 btstack_characteristic.value_handle = chr.value_handle;
786 btstack_characteristic.end_handle = chr.end_handle;
787 chr.first_descriptor = this->desc_count_;
788 BluetoothLock lock;
789 return gatt_client_discover_characteristic_descriptors(&RP2GattClient::gatt_packet_handler, this->con_handle_,
790 &btstack_characteristic);
791}
792
793void RP2GattClient::advance_discovery_(uint8_t att_status) {
794 if (this->arena_ == nullptr) {
795 // release_services() is publicly callable; a table freed mid-discovery
796 // must end the discovery instead of dereferencing a null arena.
797 this->finish_discovery_(GATT_ERR_NOT_CONNECTED);
798 return;
799 }
800 if (att_status != 0) {
801 this->finish_discovery_(att_status);
802 return;
803 }
804 switch (this->discovery_phase_) {
806 if (this->service_count_ == 0) {
807 this->finish_discovery_(0);
808 return;
809 }
811 this->disc_service_cursor_ = 0;
812 if (int err = this->issue_characteristic_query_(0); err != 0) {
813 this->finish_discovery_(err);
814 }
815 break;
817 auto &service = this->arena_->services[this->disc_service_cursor_];
818 service.characteristic_count = this->char_count_ - service.first_characteristic;
819 this->disc_service_cursor_++;
821 if (int err = this->issue_characteristic_query_(this->disc_service_cursor_); err != 0) {
822 this->finish_discovery_(err);
823 }
824 return;
825 }
826 if (this->char_count_ == 0) {
827 this->finish_discovery_(0);
828 return;
829 }
831 this->disc_char_cursor_ = 0;
832 if (int err = this->issue_descriptor_query_(0); err != 0) {
833 this->finish_discovery_(err);
834 }
835 break;
836 }
838 auto &chr = this->arena_->characteristics[this->disc_char_cursor_];
839 chr.descriptor_count = this->desc_count_ - chr.first_descriptor;
840 this->disc_char_cursor_++;
842 if (int err = this->issue_descriptor_query_(this->disc_char_cursor_); err != 0) {
843 this->finish_discovery_(err);
844 }
845 return;
846 }
847 this->finish_discovery_(0);
848 break;
849 }
850 default:
851 break;
852 }
853}
854
857 ESP_LOGV(TAG, "[%u] Discovery done (err=%d): %u services, %u characteristics, %u descriptors", this->engine_index_,
858 error, this->service_count_, this->char_count_, this->desc_count_);
859 if (error == 0 && this->truncated_) {
860 // A partial table must not stream: V3 clients cache the database
861 // permanently, so an incomplete one would be wrong forever.
862 error = ATT_ERROR_INSUFFICIENT_RESOURCES;
863 }
864 if (error == 0) {
865 // Discovery no longer needs the fast interval; settle into the shared
866 // steady-state parameters (same lifecycle place as esp32). Status
867 // discarded: BTstack fails this only for an already-gone handle.
868 BluetoothLock lock;
869 gap_update_connection_parameters(this->con_handle_, MEDIUM_MIN_CONN_INTERVAL, MEDIUM_MAX_CONN_INTERVAL, 0,
870 MEDIUM_CONN_TIMEOUT);
871 }
872 if (this->truncated_) {
873 ESP_LOGE(TAG, "Service table truncated (device exceeds %u services / %u characteristics / %u descriptors)",
874 RP2_GATT_MAX_SERVICES, RP2_GATT_MAX_CHARACTERISTICS, RP2_GATT_MAX_DESCRIPTORS);
875 }
876 if (error != 0) {
877 this->release_services();
878 }
880}
881
884 if (this->arena_ != nullptr) {
885 table.services = this->arena_->services;
886 table.characteristics = this->arena_->characteristics;
887 table.descriptors = this->arena_->descriptors;
888 table.service_count = this->service_count_;
889 table.characteristic_count = this->char_count_;
890 table.descriptor_count = this->desc_count_;
891 }
892 return table;
893}
894
896 if (this->arena_ != nullptr) {
897 // Under BluetoothLock so a discovery result landing in the BTstack
898 // context cannot write into the arena mid-free.
899 BluetoothLock lock;
900 this->arena_.reset();
901 }
902 this->service_count_ = 0;
903 this->char_count_ = 0;
904 this->desc_count_ = 0;
905 this->truncated_ = false;
906}
907
908// ---- Connection control ----
909
910int RP2GattClient::connect(uint64_t address, uint8_t addr_type) {
911 if (this->is_failed()) {
912 // setup() failed: nothing is registered for event routing and loop()
913 // never runs, so a connect could not complete or time out.
914 return GATT_ERR_NOT_CONNECTED;
915 }
916 if (this->state_ != EngineState::IDLE) {
917 return GATT_CLIENT_IN_WRONG_STATE;
918 }
919 if (!this->parent_->is_active()) {
920 return GATT_ERR_NOT_CONNECTED;
921 }
923 // BLE_ADDR_TYPE_* code space: bit 0 distinguishes public from random
924 // (resolved RPA types 2/3 connect with the underlying kind).
925 this->peer_addr_type_ = (addr_type & 1) != 0 ? BD_ADDR_TYPE_LE_RANDOM : BD_ADDR_TYPE_LE_PUBLIC;
926
927 // Stop the shared radio's scan for the duration of the connect attempt
928 // (esp32 parity: initiating and scanning contend for the radio).
929 this->holds_scan_inhibit_ = true;
930 this->parent_->inhibit_scan();
931 this->connect_cancel_attempted_ = false;
932 this->cancel_requested_ = false;
933 // Bounds the queued wait; restarted when gap_connect is accepted so the
934 // radio attempt gets its full budget (HA's own ~20 s timeout arbitrates the
935 // sum via a disconnect request).
936 this->connect_started_ = millis();
937 if (int err = this->try_gap_connect_(); err != 0) {
938 this->release_scan_inhibit_();
939 return err;
940 }
941 this->enable_loop();
942 return 0;
943}
944
945// One outgoing LE create-connection exists stack-wide: issue it if no other
946// engine owns it, otherwise park in CONNECT_PENDING for loop() to retry.
947// Returns nonzero only for hard failures (state untouched; caller cleans up).
949 // Unlocked peek: single core, aligned pointer; a stale value costs one loop
950 // pass and the locked re-check below is authoritative. Keeps the per-loop
951 // pending retry from taking BluetoothLock just to find the radio busy.
952 if (connect_owner != nullptr) {
954 return 0;
955 }
956 uint8_t status;
957 {
958 BluetoothLock lock;
959 if (connect_owner != nullptr) {
960 status = ERROR_CODE_COMMAND_DISALLOWED;
961 } else {
962 // esp32 parity: cached connections come up at MEDIUM already (nothing
963 // consumes the fast interval without a discovery phase), so there is no
964 // post-connect update procedure to race or silently lose; sustained
965 // FAST intervals also starve WiFi on the shared CYW43 radio.
966 // Without-cache runs FAST for discovery unless the hub relaxed this peripheral.
968 gap_set_connection_parameters(CONN_SCAN_INTERVAL, CONN_SCAN_WINDOW,
969 medium ? MEDIUM_MIN_CONN_INTERVAL : FAST_MIN_CONN_INTERVAL,
970 medium ? MEDIUM_MAX_CONN_INTERVAL : FAST_MAX_CONN_INTERVAL, 0,
971 medium ? MEDIUM_CONN_TIMEOUT : FAST_CONN_TIMEOUT, CONN_CE_MIN, CONN_CE_MAX);
972 status = gap_connect(this->peer_addr_, this->peer_addr_type_);
973 if (status == 0) {
974 connect_owner = this;
975 // Still under the lock: a synthesized failure completion can fire in
976 // the BTstack context the instant it releases, and completion routing
977 // requires CONNECTING — set after the fact, the event is discarded
978 // and the engine burns its whole budget waiting for it.
980 this->connect_started_ = millis();
981 }
982 }
983 }
984 if (status == 0) {
985 return 0;
986 }
987 if (status == ERROR_CODE_COMMAND_DISALLOWED) {
988 // Radio busy with another engine's connect; resolved from loop().
990 return 0;
991 }
992 ESP_LOGW(TAG, "[%u] gap_connect failed, status=0x%02x", this->engine_index_, status);
993 return status;
994}
995
997 switch (this->state_) {
999 return GATT_ERR_NOT_CONNECTED;
1001 return 0; // already on its way down
1003 // Nothing issued stack-side; the invalid handle takes the refused
1004 // path below without touching the stack.
1005 break;
1007 if (this->con_handle_ == HCI_CON_HANDLE_INVALID) {
1008 // The cancel can lose the race against a successful connection
1009 // complete; handle_connected_ checks this flag and finishes the
1010 // teardown instead of proceeding. It also counts as the one cancel
1011 // attempt, so a lost completion escalates on the next timeout tick.
1012 this->cancel_requested_ = true;
1013 this->connect_cancel_attempted_ = true;
1014 // Grace period for the cancel completion: the client's disconnect
1015 // often lands right at the engine's own deadline, and without the
1016 // restart the loop timeout fires first and reports before the
1017 // completion can finish the teardown cleanly.
1018 this->connect_started_ = millis();
1019 BluetoothLock lock;
1020 // Owner: the cancel completes as a failed connection-complete. Not
1021 // the owner (completion already resolved in the BTstack context): the
1022 // queued event drives the same teardown, nothing to cancel.
1023 if (connect_owner == this) {
1024 gap_connect_cancel();
1025 }
1026 return 0;
1027 }
1028 break;
1029 }
1030 default:
1031 break;
1032 }
1033 uint8_t status = ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1034 if (this->con_handle_ != HCI_CON_HANDLE_INVALID) {
1035 {
1036 BluetoothLock lock;
1037 status = gap_disconnect(this->con_handle_);
1038 }
1039 if (status != 0) {
1040 ESP_LOGW(TAG, "[%u] gap_disconnect failed, status=0x%02x", this->engine_index_, status);
1041 }
1042 }
1043 if (status != 0) {
1044 // Refused (handle already gone) or never issued (CONNECT_PENDING):
1045 // complete via the event queue so the listener cannot re-enter
1046 // disconnect mid-call. BluetoothLock stops the IRQ producer, so this
1047 // main-loop push is SPSC-safe.
1048 BluetoothLock lock;
1049 this->enqueue_event_irq_(RP2GattEvent::DISCONNECTED, HCI_REASON_CONNECTION_TIMEOUT, 0);
1050 }
1053 // No more initiating: give the radio back to the scanner during teardown.
1054 this->release_scan_inhibit_();
1055 this->enable_loop();
1056 return 0;
1057}
1058
1059// ---- GATT operations (single outstanding op) ----
1060
1062 if (this->state_ != EngineState::READY) {
1063 return GATT_ERR_NOT_CONNECTED;
1064 }
1065 if (this->op_in_flight_()) {
1066 return GATT_CLIENT_IN_WRONG_STATE;
1067 }
1069 this->op_handle_ = handle;
1070 this->op_len_ = 0;
1071 BluetoothLock lock;
1072 // Long variant: plain read first, blob continuations only past MTU - 1.
1073 uint8_t status = gatt_client_read_long_value_of_characteristic_using_value_handle(&RP2GattClient::gatt_packet_handler,
1074 this->con_handle_, handle);
1075 if (status != 0) {
1076 this->op_type_ = OpType::NONE;
1077 return status;
1078 }
1079 return 0;
1080}
1081
1082int RP2GattClient::write_characteristic(uint16_t handle, const uint8_t *data, uint16_t len, bool response) {
1083 if (this->state_ != EngineState::READY) {
1084 return GATT_ERR_NOT_CONNECTED;
1085 }
1086 if (len > RP2_GATT_MAX_ATTR_LEN) {
1087 return ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH;
1088 }
1089 if (!response) {
1090 // Synchronous in BTstack: the data is copied into the L2CAP buffer before
1091 // the call returns, and no completion event exists — synthesize one so
1092 // the wire behavior matches esp32 (which reports write-no-response too).
1093 uint8_t status;
1094 {
1095 BluetoothLock lock;
1096 if (this->op_type_ == OpType::WRITE_CHAR_NO_RSP) {
1097 // A deferred write is parked; sending now would overtake it.
1098 return GATT_CLIENT_BUSY;
1099 }
1100 status = gatt_client_write_value_of_characteristic_without_response(this->con_handle_, handle, len,
1101 const_cast<uint8_t *>(data));
1102 // BTSTACK_ACL_BUFFERS_FULL is the same transient flow control one layer
1103 // down (L2CAP), so it defers identically.
1104 if (status == GATT_CLIENT_BUSY || status == BTSTACK_ACL_BUFFERS_FULL) {
1105 if (this->op_in_flight_()) {
1106 // The op buffer is owned; bounce the busy to the caller as before.
1107 return status;
1108 }
1109 // Stash the payload and send from the can-send callback.
1110 memcpy(this->op_buffer_, data, len);
1112 this->op_handle_ = handle;
1113 this->op_len_ = len;
1114 this->write_no_rsp_started_ = millis();
1116 this->can_write_registration_.context = this;
1117 uint8_t req = gatt_client_request_to_write_without_response(&this->can_write_registration_, this->con_handle_);
1118 if (req != 0 && req != ERROR_CODE_COMMAND_DISALLOWED) {
1119 this->op_type_ = OpType::NONE;
1120 return req;
1121 }
1122 // COMMAND_DISALLOWED = still armed from a timed-out deferral; that
1123 // registration sends the newly parked payload. Keep the loop running
1124 // so the deadline below can fire on a stalled link.
1125 this->enable_loop();
1126 return 0;
1127 }
1128 }
1129 if (status == 0) {
1130 this->listener_->on_write_result(handle, 0);
1131 }
1132 return status;
1133 }
1134 if (this->op_in_flight_()) {
1135 return GATT_CLIENT_IN_WRONG_STATE;
1136 }
1137 // BTstack keeps the caller's pointer until the request is sent; the payload
1138 // must live in engine-owned storage across the async operation.
1139 memcpy(this->op_buffer_, data, len);
1141 this->op_handle_ = handle;
1142 BluetoothLock lock;
1143 uint8_t status;
1144 if (len <= this->mtu_ - 3) {
1145 status = gatt_client_write_value_of_characteristic(&RP2GattClient::gatt_packet_handler, this->con_handle_, handle,
1146 len, this->op_buffer_);
1147 } else {
1148 status = gatt_client_write_long_value_of_characteristic(&RP2GattClient::gatt_packet_handler, this->con_handle_,
1149 handle, len, this->op_buffer_);
1150 }
1151 if (status != 0) {
1152 this->op_type_ = OpType::NONE;
1153 return status;
1154 }
1155 return 0;
1156}
1157
1159 if (this->state_ != EngineState::READY) {
1160 return GATT_ERR_NOT_CONNECTED;
1161 }
1162 if (this->op_in_flight_()) {
1163 return GATT_CLIENT_IN_WRONG_STATE;
1164 }
1166 this->op_handle_ = handle;
1167 this->op_len_ = 0;
1168 BluetoothLock lock;
1169 uint8_t status = gatt_client_read_long_characteristic_descriptor_using_descriptor_handle(
1171 if (status != 0) {
1172 this->op_type_ = OpType::NONE;
1173 return status;
1174 }
1175 return 0;
1176}
1177
1178int RP2GattClient::write_descriptor(uint16_t handle, const uint8_t *data, uint16_t len) {
1179 if (this->state_ != EngineState::READY) {
1180 return GATT_ERR_NOT_CONNECTED;
1181 }
1182 if (this->op_in_flight_()) {
1183 return GATT_CLIENT_IN_WRONG_STATE;
1184 }
1185 if (len > RP2_GATT_MAX_ATTR_LEN) {
1186 return ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH;
1187 }
1188 memcpy(this->op_buffer_, data, len);
1190 this->op_handle_ = handle;
1191 BluetoothLock lock;
1192 uint8_t status = gatt_client_write_characteristic_descriptor_using_descriptor_handle(
1194 if (status != 0) {
1195 this->op_type_ = OpType::NONE;
1196 return status;
1197 }
1198 return 0;
1199}
1200
1202 if (this->state_ != EngineState::READY) {
1203 return GATT_ERR_NOT_CONNECTED;
1204 }
1205 BluetoothLock lock;
1206 sm_request_pairing(this->con_handle_); // void API; completion via SM events
1207 return 0;
1208}
1209
1211 if (this->state_ != EngineState::READY) {
1212 return GATT_ERR_NOT_CONNECTED;
1213 }
1214 // The CCCD write arrives separately as a descriptor write (V3 semantics);
1215 // this call only gates local delivery via the subscription list.
1216 if (enable) {
1217 if (!this->notify_subscribed_(handle)) {
1218 if (this->notify_subscription_count_ >= RP2_GATT_MAX_NOTIFY_SUBSCRIPTIONS) {
1219 return GATT_ERR_NO_MEMORY;
1220 }
1222 }
1223 } else {
1224 for (uint8_t i = 0; i < this->notify_subscription_count_; i++) {
1225 if (this->notify_subscriptions_[i] == handle) {
1227 break;
1228 }
1229 }
1230 }
1231 this->listener_->on_notify_state(handle, enable, 0);
1232 return 0;
1233}
1234
1236 for (uint8_t i = 0; i < this->notify_subscription_count_; i++) {
1237 if (this->notify_subscriptions_[i] == handle) {
1238 return true;
1239 }
1240 }
1241 return false;
1242}
1243
1244int RP2GattClient::update_connection_params(uint16_t min_interval, uint16_t max_interval, uint16_t latency,
1245 uint16_t timeout) {
1246 if (this->state_ != EngineState::READY) {
1247 return GATT_ERR_NOT_CONNECTED;
1248 }
1249 BluetoothLock lock;
1250 return gap_update_connection_parameters(this->con_handle_, min_interval, max_interval, latency, timeout);
1251}
1252
1254 uint8_t mac[MAC_ADDRESS_SIZE];
1256 bool found = false;
1257 BluetoothLock lock;
1258 // Exhaustive: the db keys on (type, address), so stale entries can share
1259 // the same address bytes under different types.
1260 for (int i = 0; i < le_device_db_max_count(); i++) {
1261 int addr_type = 0;
1262 bd_addr_t addr;
1263 le_device_db_info(i, &addr_type, addr, nullptr);
1264 if (addr_type != BD_ADDR_TYPE_UNKNOWN && memcmp(addr, mac, sizeof(bd_addr_t)) == 0) {
1265 le_device_db_remove(i);
1266 found = true;
1267 }
1268 }
1269 if (found) {
1270 return CONN_OK;
1271 }
1272 // No bond for this address; the shared error domain has no closer code
1273 // (esp32 parity: its remove-bond call also errors for an unknown address).
1274 return GATT_NOT_CONNECTED;
1275}
1276
1277} // namespace esphome::bluetooth_connection
1278
1279#endif // USE_RP2040_BLE && USE_BLE_GATT_CLIENT
uint8_t status
Definition bl0942.h:8
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:288
void enable_loop_soon_any_context()
Thread and ISR-safe version of enable_loop() that can be called from any context.
void enable_loop()
Enable this component's loop.
Definition component.h:262
void disable_loop()
Disable this component's loop.
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:2670
RAMUniquePtr< T > make_unique(Args &&...args)
Value initialize one T; empty on exhaustion.
Definition helpers.h:2733
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).
void enqueue_notify_irq_(uint16_t handle, const uint8_t *data, uint16_t len)
esphome::EventPool< RP2GattNotifyEvent, RP2_GATT_NOTIFY_QUEUE_SIZE - 1 > notify_pool_
btstack_context_callback_registration_t can_write_registration_
void enqueue_event_irq_(RP2GattEvent::Type type, uint8_t status, uint16_t value)
void handle_connected_(uint8_t status, uint16_t con_handle)
void handle_gatt_event_irq_(uint8_t event_type, const uint8_t *packet)
static void sm_packet_handler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t size)
int write_characteristic(uint16_t handle, const uint8_t *data, uint16_t len, bool response)
static btstack_packet_callback_registration_t hci_event_registration
static RP2GattClient * instance_for_con_handle(hci_con_handle_t con_handle)
void on_ota_global_state(ota::OTAState state, float progress, uint8_t error, ota::OTAComponent *comp) override
static void hci_packet_handler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t size)
ble_device_base::GattServiceTable get_service_table()
int connect(uint64_t address, uint8_t addr_type)
std::array< uint16_t, RP2_GATT_MAX_NOTIFY_SUBSCRIPTIONS > notify_subscriptions_
esphome::LockFreeQueue< RP2GattNotifyEvent, RP2_GATT_NOTIFY_QUEUE_SIZE > notify_queue_
ble_device_base::GattClientListener * listener_
int update_connection_params(uint16_t min_interval, uint16_t max_interval, uint16_t latency, uint16_t timeout)
static btstack_packet_callback_registration_t sm_event_registration
int write_descriptor(uint16_t handle, const uint8_t *data, uint16_t len)
static RP2GattClient * instances[ESPHOME_BLE_GATT_CLIENT_COUNT]
void assemble_blob_irq_(uint16_t offset, const uint8_t *data, uint16_t len)
static void gatt_packet_handler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t size)
esphome::LockFreeQueue< RP2GattEvent, RP2_GATT_EVENT_QUEUE_SIZE > event_queue_
esphome::EventPool< RP2GattEvent, RP2_GATT_EVENT_QUEUE_SIZE - 1 > event_pool_
void inhibit_scan()
Pause the physical scan for the duration of a GATT connect attempt (initiating and scanning contend f...
uint8_t type
bool state
Definition fan.h:2
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
conn_err_t unpair_device(uint64_t address)
ESPHOME_LOG_TAG(TAG, "bluetooth_connection")
ble_device_base::ESPBTUUID uuid_from_be128(const uint8_t *uuid128)
A 128-bit UUID in big-endian (printable) order, as its 16 or 32-bit form when it is on the Bluetooth ...
OTAGlobalCallback * get_global_ota_callback()
constexpr float AFTER_BLUETOOTH
Definition component.h:50
uint32_t value
Definition hal.cpp:59
const void size_t len
Definition hal.h:68
uint16_t size
Definition helpers.cpp:44
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
static void uint32_t
Borrowed view of the backend-owned service table.
const GattCharacteristic * characteristics
SemaphoreHandle_t lock
spi_device_handle_t handle