ESPHome 2026.11.0b6
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
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 this->listener_->on_connection_state(true, this->mtu_, 0);
539 }
540 break;
542 this->handle_query_complete_(event.status);
543 break;
545 this->finish_write_no_rsp_(event.status);
546 break;
548 this->listener_->on_pairing_result(event.status);
549 break;
550 }
551}
552
554 // BTstack context: this callback IS the can-send window, so the deferred
555 // write happens here; only the result is enqueued for the main loop.
556 auto *self = static_cast<RP2GattClient *>(context);
557 if (self->op_type_ != OpType::WRITE_CHAR_NO_RSP) {
558 return;
559 }
560 uint8_t status = gatt_client_write_value_of_characteristic_without_response(self->con_handle_, self->op_handle_,
561 self->op_len_, self->op_buffer_);
562 if ((status == GATT_CLIENT_BUSY || status == BTSTACK_ACL_BUFFERS_FULL) &&
563 gatt_client_request_to_write_without_response(&self->can_write_registration_, self->con_handle_) == 0) {
564 return; // next window retries; a failed re-arm falls through as an error
565 }
566 self->enqueue_event_irq_(RP2GattEvent::WRITE_NO_RSP_DONE, status, 0);
567}
568
570 if (this->op_type_ != OpType::WRITE_CHAR_NO_RSP) {
571 return;
572 }
573 this->op_type_ = OpType::NONE;
574 this->listener_->on_write_result(this->op_handle_, status);
575}
576
577void RP2GattClient::handle_connected_(uint8_t status, uint16_t con_handle) {
578 if (this->state_ != EngineState::CONNECTING) {
579 return;
580 }
581 if (status != 0) {
582 ESP_LOGW(TAG, "[%u] Connect failed, status=0x%02x", this->engine_index_, status);
583 this->fail_connection_(status);
584 return;
585 }
586 if (this->cancel_requested_) {
587 // A disconnect request raced the connection complete and lost; finish
588 // the teardown instead of reporting a connection nobody wants.
589 this->con_handle_ = con_handle;
592 // No more initiating: give the radio back to the scanner during teardown.
593 this->release_scan_inhibit_();
594 uint8_t disc_status;
595 {
596 BluetoothLock lock;
597 disc_status = gap_disconnect(this->con_handle_);
598 }
599 if (disc_status != 0) {
600 this->handle_disconnected_(HCI_REASON_CONNECTION_TIMEOUT);
601 }
602 return;
603 }
604 this->con_handle_ = con_handle;
606 ESP_LOGV(TAG, "[%u] Link up, handle=0x%04x, negotiating MTU", this->engine_index_, con_handle);
607 BluetoothLock lock;
608 // One wildcard listener covers notifications/indications for every
609 // characteristic on this connection; the CCCD writes come from the API
610 // client as plain descriptor writes.
611 gatt_client_listen_for_characteristic_value_updates(&this->notification_registration_,
613 // Auto MTU negotiation is disabled (see rp2040_ble enable hooks), so the
614 // exchange is kicked explicitly; GATT_EVENT_MTU completes it. Without the
615 // explicit kick the MTU would only be exchanged on the first GATT query,
616 // which never happens on a V3_WITH_CACHE connection.
617 // Both registration calls above return void (BTstack 075a078, arduino-pico
618 // 6.1.0); failures surface as a missing GATT_EVENT_MTU and are reclaimed by
619 // the connect timeout in loop().
620 gatt_client_send_mtu_negotiation(&RP2GattClient::gatt_packet_handler, this->con_handle_);
621}
622
624 if (this->holds_scan_inhibit_) {
625 this->holds_scan_inhibit_ = false;
627 }
628}
629
631 {
632 // Timeout escalation can fire with the completion event lost; release the
633 // stack-wide connect slot so pending engines can proceed. Until the old
634 // completion is processed, gap_connect answers any peer with DISALLOWED
635 // (the request-level guard in hci.c); a cancel idles that request
636 // immediately, and a late addressed completion from the old procedure is
637 // then dropped by the owner-peer cross-check in the handler.
638 BluetoothLock lock;
639 if (connect_owner == this) {
640 connect_owner = nullptr;
641 }
642 if (this->state_ == EngineState::CONNECTING && this->con_handle_ != HCI_CON_HANDLE_INVALID) {
643 // A success completion stamped the handle between the escalation
644 // decision and this lock: tear the link down before cleanup wipes the
645 // handle, or it leaks its pool block for the rest of the boot.
646 gap_disconnect(this->con_handle_);
647 }
648 }
649 this->cleanup_link_state_();
650 this->release_scan_inhibit_();
652 this->listener_->on_connection_state(false, 0, reason);
653}
654
656 // Drop notifications queued behind the disconnect so they cannot emit
657 // against a freed slot (address 0) on the next loop.
658 RP2GattNotifyEvent *stale;
659 while ((stale = this->notify_queue_.pop()) != nullptr) {
660 this->notify_pool_.release(stale);
661 }
662 // con_handle_ may be stamped in the BTstack context before the main loop
663 // registers the listener, so a valid handle does not imply a registration;
664 // stop_listening on an unregistered entry is a benign no-op. One lock
665 // scope around check and reset so an IRQ stamp cannot land in between
666 // (unreachable today — ownership is released before cleanup — but the
667 // invariant lives three functions away).
668 {
669 BluetoothLock lock;
670 if (this->con_handle_ != HCI_CON_HANDLE_INVALID) {
671 gatt_client_stop_listening_for_characteristic_value_updates(&this->notification_registration_);
672 }
673 this->con_handle_ = HCI_CON_HANDLE_INVALID;
674 }
676 this->cancel_requested_ = false;
677 this->op_type_ = OpType::NONE;
679 this->release_services();
680}
681
683 if (this->state_ == EngineState::IDLE) {
684 return;
685 }
686 ESP_LOGV(TAG, "[%u] Disconnected, reason=0x%02x", this->engine_index_, reason);
687 this->fail_connection_(reason);
688}
689
691 // Stale completions cannot cross connections: the loop drains the whole
692 // event queue every iteration, teardown resets op/discovery state, and a
693 // new discovery is only issued after the new link's MTU event — which in
694 // this BTstack emits no QUERY_COMPLETE (the MTU state machine is separate
695 // from the query state machine). Completions with nothing in flight are
696 // dropped below.
697 if (this->op_type_ != OpType::NONE && this->op_type_ != OpType::WRITE_CHAR_NO_RSP) {
698 OpType op = this->op_type_;
699 this->op_type_ = OpType::NONE;
700 switch (op) {
703 // A value that is an exact multiple of MTU - 1 ends with a trailing
704 // blob request some peers refuse with INVALID_OFFSET; the read is
705 // complete, not failed.
706 if ((att_status == ATT_ERROR_INVALID_OFFSET || att_status == ATT_ERROR_ATTRIBUTE_NOT_LONG) &&
707 this->op_len_ > 0) {
708 att_status = 0;
709 }
710 this->listener_->on_read_result(this->op_handle_, this->op_buffer_, att_status == 0 ? this->op_len_ : 0,
711 att_status);
712 break;
715 this->listener_->on_write_result(this->op_handle_, att_status);
716 break;
717 default:
718 break;
719 }
720 return;
721 }
723 this->advance_discovery_(att_status);
724 }
725}
726
727// ---- Service discovery ----
728
730 if (this->state_ != EngineState::READY) {
731 return GATT_ERR_NOT_CONNECTED;
732 }
733 if (this->op_in_flight_()) {
734 return GATT_CLIENT_IN_WRONG_STATE;
735 }
736 if (this->arena_ == nullptr) {
737 // Transient: freed in release_services() right after the table streams
738 // to the API client (mirrors Bluedroid's own per-connection GATT DB
739 // lifetime on esp32). Checked: a fragmented heap must surface as a
740 // stack error the proxy can report, not a device reset.
742 if (this->arena_ == nullptr) {
743 ESP_LOGE(TAG, "[%u] Service table allocation failed", this->engine_index_);
744 return ble_device_base::GATT_ERR_NO_MEMORY;
745 }
746 }
747 this->service_count_ = 0;
748 this->char_count_ = 0;
749 this->desc_count_ = 0;
750 this->truncated_ = false;
752 BluetoothLock lock;
753 uint8_t status = gatt_client_discover_primary_services(&RP2GattClient::gatt_packet_handler, this->con_handle_);
754 if (status != 0) {
756 this->release_services();
757 return status;
758 }
759 return 0;
760}
761
763 auto &service = this->arena_->services[service_index];
764 gatt_client_service_t btstack_service = {};
765 btstack_service.start_group_handle = service.start_handle;
766 btstack_service.end_group_handle = service.end_handle;
767 service.first_characteristic = this->char_count_;
768 BluetoothLock lock;
769 return gatt_client_discover_characteristics_for_service(&RP2GattClient::gatt_packet_handler, this->con_handle_,
770 &btstack_service);
771}
772
774 auto &chr = this->arena_->characteristics[char_index];
775 gatt_client_characteristic_t btstack_characteristic = {};
776 btstack_characteristic.value_handle = chr.value_handle;
777 btstack_characteristic.end_handle = chr.end_handle;
778 chr.first_descriptor = this->desc_count_;
779 BluetoothLock lock;
780 return gatt_client_discover_characteristic_descriptors(&RP2GattClient::gatt_packet_handler, this->con_handle_,
781 &btstack_characteristic);
782}
783
784void RP2GattClient::advance_discovery_(uint8_t att_status) {
785 if (this->arena_ == nullptr) {
786 // release_services() is publicly callable; a table freed mid-discovery
787 // must end the discovery instead of dereferencing a null arena.
788 this->finish_discovery_(GATT_ERR_NOT_CONNECTED);
789 return;
790 }
791 if (att_status != 0) {
792 this->finish_discovery_(att_status);
793 return;
794 }
795 switch (this->discovery_phase_) {
797 if (this->service_count_ == 0) {
798 this->finish_discovery_(0);
799 return;
800 }
802 this->disc_service_cursor_ = 0;
803 if (int err = this->issue_characteristic_query_(0); err != 0) {
804 this->finish_discovery_(err);
805 }
806 break;
808 auto &service = this->arena_->services[this->disc_service_cursor_];
809 service.characteristic_count = this->char_count_ - service.first_characteristic;
810 this->disc_service_cursor_++;
812 if (int err = this->issue_characteristic_query_(this->disc_service_cursor_); err != 0) {
813 this->finish_discovery_(err);
814 }
815 return;
816 }
817 if (this->char_count_ == 0) {
818 this->finish_discovery_(0);
819 return;
820 }
822 this->disc_char_cursor_ = 0;
823 if (int err = this->issue_descriptor_query_(0); err != 0) {
824 this->finish_discovery_(err);
825 }
826 break;
827 }
829 auto &chr = this->arena_->characteristics[this->disc_char_cursor_];
830 chr.descriptor_count = this->desc_count_ - chr.first_descriptor;
831 this->disc_char_cursor_++;
833 if (int err = this->issue_descriptor_query_(this->disc_char_cursor_); err != 0) {
834 this->finish_discovery_(err);
835 }
836 return;
837 }
838 this->finish_discovery_(0);
839 break;
840 }
841 default:
842 break;
843 }
844}
845
848 ESP_LOGV(TAG, "[%u] Discovery done (err=%d): %u services, %u characteristics, %u descriptors", this->engine_index_,
849 error, this->service_count_, this->char_count_, this->desc_count_);
850 if (error == 0 && this->truncated_) {
851 // A partial table must not stream: V3 clients cache the database
852 // permanently, so an incomplete one would be wrong forever.
853 error = ATT_ERROR_INSUFFICIENT_RESOURCES;
854 }
855 if (error == 0) {
856 // Discovery no longer needs the fast interval; settle into the shared
857 // steady-state parameters (same lifecycle place as esp32). Status
858 // discarded: BTstack fails this only for an already-gone handle.
859 BluetoothLock lock;
860 gap_update_connection_parameters(this->con_handle_, MEDIUM_MIN_CONN_INTERVAL, MEDIUM_MAX_CONN_INTERVAL, 0,
861 MEDIUM_CONN_TIMEOUT);
862 }
863 if (this->truncated_) {
864 ESP_LOGE(TAG, "Service table truncated (device exceeds %u services / %u characteristics / %u descriptors)",
865 RP2_GATT_MAX_SERVICES, RP2_GATT_MAX_CHARACTERISTICS, RP2_GATT_MAX_DESCRIPTORS);
866 }
867 if (error != 0) {
868 this->release_services();
869 }
871}
872
875 if (this->arena_ != nullptr) {
876 table.services = this->arena_->services;
877 table.characteristics = this->arena_->characteristics;
878 table.descriptors = this->arena_->descriptors;
879 table.service_count = this->service_count_;
880 table.characteristic_count = this->char_count_;
881 table.descriptor_count = this->desc_count_;
882 }
883 return table;
884}
885
887 if (this->arena_ != nullptr) {
888 // Under BluetoothLock so a discovery result landing in the BTstack
889 // context cannot write into the arena mid-free.
890 BluetoothLock lock;
891 this->arena_.reset();
892 }
893 this->service_count_ = 0;
894 this->char_count_ = 0;
895 this->desc_count_ = 0;
896 this->truncated_ = false;
897}
898
899// ---- Connection control ----
900
901int RP2GattClient::connect(uint64_t address, uint8_t addr_type) {
902 if (this->is_failed()) {
903 // setup() failed: nothing is registered for event routing and loop()
904 // never runs, so a connect could not complete or time out.
905 return GATT_ERR_NOT_CONNECTED;
906 }
907 if (this->state_ != EngineState::IDLE) {
908 return GATT_CLIENT_IN_WRONG_STATE;
909 }
910 if (!this->parent_->is_active()) {
911 return GATT_ERR_NOT_CONNECTED;
912 }
914 // BLE_ADDR_TYPE_* code space: bit 0 distinguishes public from random
915 // (resolved RPA types 2/3 connect with the underlying kind).
916 this->peer_addr_type_ = (addr_type & 1) != 0 ? BD_ADDR_TYPE_LE_RANDOM : BD_ADDR_TYPE_LE_PUBLIC;
917
918 // Stop the shared radio's scan for the duration of the connect attempt
919 // (esp32 parity: initiating and scanning contend for the radio).
920 this->holds_scan_inhibit_ = true;
921 this->parent_->inhibit_scan();
922 this->connect_cancel_attempted_ = false;
923 this->cancel_requested_ = false;
924 // Bounds the queued wait; restarted when gap_connect is accepted so the
925 // radio attempt gets its full budget (HA's own ~20 s timeout arbitrates the
926 // sum via a disconnect request).
927 this->connect_started_ = millis();
928 if (int err = this->try_gap_connect_(); err != 0) {
929 this->release_scan_inhibit_();
930 return err;
931 }
932 this->enable_loop();
933 return 0;
934}
935
936// One outgoing LE create-connection exists stack-wide: issue it if no other
937// engine owns it, otherwise park in CONNECT_PENDING for loop() to retry.
938// Returns nonzero only for hard failures (state untouched; caller cleans up).
940 // Unlocked peek: single core, aligned pointer; a stale value costs one loop
941 // pass and the locked re-check below is authoritative. Keeps the per-loop
942 // pending retry from taking BluetoothLock just to find the radio busy.
943 if (connect_owner != nullptr) {
945 return 0;
946 }
947 uint8_t status;
948 {
949 BluetoothLock lock;
950 if (connect_owner != nullptr) {
951 status = ERROR_CODE_COMMAND_DISALLOWED;
952 } else {
953 // esp32 parity: cached connections come up at MEDIUM already (nothing
954 // consumes the fast interval without a discovery phase), so there is no
955 // post-connect update procedure to race or silently lose; sustained
956 // FAST intervals also starve WiFi on the shared CYW43 radio.
957 // Without-cache runs FAST for discovery and steps down in
958 // finish_discovery_.
960 gap_set_connection_parameters(CONN_SCAN_INTERVAL, CONN_SCAN_WINDOW,
961 cached ? MEDIUM_MIN_CONN_INTERVAL : FAST_MIN_CONN_INTERVAL,
962 cached ? MEDIUM_MAX_CONN_INTERVAL : FAST_MAX_CONN_INTERVAL, 0,
963 cached ? MEDIUM_CONN_TIMEOUT : FAST_CONN_TIMEOUT, CONN_CE_MIN, CONN_CE_MAX);
964 status = gap_connect(this->peer_addr_, this->peer_addr_type_);
965 if (status == 0) {
966 connect_owner = this;
967 // Still under the lock: a synthesized failure completion can fire in
968 // the BTstack context the instant it releases, and completion routing
969 // requires CONNECTING — set after the fact, the event is discarded
970 // and the engine burns its whole budget waiting for it.
972 this->connect_started_ = millis();
973 }
974 }
975 }
976 if (status == 0) {
977 return 0;
978 }
979 if (status == ERROR_CODE_COMMAND_DISALLOWED) {
980 // Radio busy with another engine's connect; resolved from loop().
982 return 0;
983 }
984 ESP_LOGW(TAG, "[%u] gap_connect failed, status=0x%02x", this->engine_index_, status);
985 return status;
986}
987
989 switch (this->state_) {
991 return GATT_ERR_NOT_CONNECTED;
993 return 0; // already on its way down
995 // Nothing issued stack-side; the invalid handle takes the refused
996 // path below without touching the stack.
997 break;
999 if (this->con_handle_ == HCI_CON_HANDLE_INVALID) {
1000 // The cancel can lose the race against a successful connection
1001 // complete; handle_connected_ checks this flag and finishes the
1002 // teardown instead of proceeding. It also counts as the one cancel
1003 // attempt, so a lost completion escalates on the next timeout tick.
1004 this->cancel_requested_ = true;
1005 this->connect_cancel_attempted_ = true;
1006 // Grace period for the cancel completion: the client's disconnect
1007 // often lands right at the engine's own deadline, and without the
1008 // restart the loop timeout fires first and reports before the
1009 // completion can finish the teardown cleanly.
1010 this->connect_started_ = millis();
1011 BluetoothLock lock;
1012 // Owner: the cancel completes as a failed connection-complete. Not
1013 // the owner (completion already resolved in the BTstack context): the
1014 // queued event drives the same teardown, nothing to cancel.
1015 if (connect_owner == this) {
1016 gap_connect_cancel();
1017 }
1018 return 0;
1019 }
1020 break;
1021 }
1022 default:
1023 break;
1024 }
1025 uint8_t status = ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1026 if (this->con_handle_ != HCI_CON_HANDLE_INVALID) {
1027 {
1028 BluetoothLock lock;
1029 status = gap_disconnect(this->con_handle_);
1030 }
1031 if (status != 0) {
1032 ESP_LOGW(TAG, "[%u] gap_disconnect failed, status=0x%02x", this->engine_index_, status);
1033 }
1034 }
1035 if (status != 0) {
1036 // Refused (handle already gone) or never issued (CONNECT_PENDING):
1037 // complete via the event queue so the listener cannot re-enter
1038 // disconnect mid-call. BluetoothLock stops the IRQ producer, so this
1039 // main-loop push is SPSC-safe.
1040 BluetoothLock lock;
1041 this->enqueue_event_irq_(RP2GattEvent::DISCONNECTED, HCI_REASON_CONNECTION_TIMEOUT, 0);
1042 }
1045 // No more initiating: give the radio back to the scanner during teardown.
1046 this->release_scan_inhibit_();
1047 this->enable_loop();
1048 return 0;
1049}
1050
1051// ---- GATT operations (single outstanding op) ----
1052
1054 if (this->state_ != EngineState::READY) {
1055 return GATT_ERR_NOT_CONNECTED;
1056 }
1057 if (this->op_in_flight_()) {
1058 return GATT_CLIENT_IN_WRONG_STATE;
1059 }
1061 this->op_handle_ = handle;
1062 this->op_len_ = 0;
1063 BluetoothLock lock;
1064 // Long variant: plain read first, blob continuations only past MTU - 1.
1065 uint8_t status = gatt_client_read_long_value_of_characteristic_using_value_handle(&RP2GattClient::gatt_packet_handler,
1066 this->con_handle_, handle);
1067 if (status != 0) {
1068 this->op_type_ = OpType::NONE;
1069 return status;
1070 }
1071 return 0;
1072}
1073
1074int RP2GattClient::write_characteristic(uint16_t handle, const uint8_t *data, uint16_t len, bool response) {
1075 if (this->state_ != EngineState::READY) {
1076 return GATT_ERR_NOT_CONNECTED;
1077 }
1078 if (len > RP2_GATT_MAX_ATTR_LEN) {
1079 return ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH;
1080 }
1081 if (!response) {
1082 // Synchronous in BTstack: the data is copied into the L2CAP buffer before
1083 // the call returns, and no completion event exists — synthesize one so
1084 // the wire behavior matches esp32 (which reports write-no-response too).
1085 uint8_t status;
1086 {
1087 BluetoothLock lock;
1088 if (this->op_type_ == OpType::WRITE_CHAR_NO_RSP) {
1089 // A deferred write is parked; sending now would overtake it.
1090 return GATT_CLIENT_BUSY;
1091 }
1092 status = gatt_client_write_value_of_characteristic_without_response(this->con_handle_, handle, len,
1093 const_cast<uint8_t *>(data));
1094 // BTSTACK_ACL_BUFFERS_FULL is the same transient flow control one layer
1095 // down (L2CAP), so it defers identically.
1096 if (status == GATT_CLIENT_BUSY || status == BTSTACK_ACL_BUFFERS_FULL) {
1097 if (this->op_in_flight_()) {
1098 // The op buffer is owned; bounce the busy to the caller as before.
1099 return status;
1100 }
1101 // Stash the payload and send from the can-send callback.
1102 memcpy(this->op_buffer_, data, len);
1104 this->op_handle_ = handle;
1105 this->op_len_ = len;
1106 this->write_no_rsp_started_ = millis();
1108 this->can_write_registration_.context = this;
1109 uint8_t req = gatt_client_request_to_write_without_response(&this->can_write_registration_, this->con_handle_);
1110 if (req != 0 && req != ERROR_CODE_COMMAND_DISALLOWED) {
1111 this->op_type_ = OpType::NONE;
1112 return req;
1113 }
1114 // COMMAND_DISALLOWED = still armed from a timed-out deferral; that
1115 // registration sends the newly parked payload. Keep the loop running
1116 // so the deadline below can fire on a stalled link.
1117 this->enable_loop();
1118 return 0;
1119 }
1120 }
1121 if (status == 0) {
1122 this->listener_->on_write_result(handle, 0);
1123 }
1124 return status;
1125 }
1126 if (this->op_in_flight_()) {
1127 return GATT_CLIENT_IN_WRONG_STATE;
1128 }
1129 // BTstack keeps the caller's pointer until the request is sent; the payload
1130 // must live in engine-owned storage across the async operation.
1131 memcpy(this->op_buffer_, data, len);
1133 this->op_handle_ = handle;
1134 BluetoothLock lock;
1135 uint8_t status;
1136 if (len <= this->mtu_ - 3) {
1137 status = gatt_client_write_value_of_characteristic(&RP2GattClient::gatt_packet_handler, this->con_handle_, handle,
1138 len, this->op_buffer_);
1139 } else {
1140 status = gatt_client_write_long_value_of_characteristic(&RP2GattClient::gatt_packet_handler, this->con_handle_,
1141 handle, len, this->op_buffer_);
1142 }
1143 if (status != 0) {
1144 this->op_type_ = OpType::NONE;
1145 return status;
1146 }
1147 return 0;
1148}
1149
1151 if (this->state_ != EngineState::READY) {
1152 return GATT_ERR_NOT_CONNECTED;
1153 }
1154 if (this->op_in_flight_()) {
1155 return GATT_CLIENT_IN_WRONG_STATE;
1156 }
1158 this->op_handle_ = handle;
1159 this->op_len_ = 0;
1160 BluetoothLock lock;
1161 uint8_t status = gatt_client_read_long_characteristic_descriptor_using_descriptor_handle(
1163 if (status != 0) {
1164 this->op_type_ = OpType::NONE;
1165 return status;
1166 }
1167 return 0;
1168}
1169
1170int RP2GattClient::write_descriptor(uint16_t handle, const uint8_t *data, uint16_t len) {
1171 if (this->state_ != EngineState::READY) {
1172 return GATT_ERR_NOT_CONNECTED;
1173 }
1174 if (this->op_in_flight_()) {
1175 return GATT_CLIENT_IN_WRONG_STATE;
1176 }
1177 if (len > RP2_GATT_MAX_ATTR_LEN) {
1178 return ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH;
1179 }
1180 memcpy(this->op_buffer_, data, len);
1182 this->op_handle_ = handle;
1183 BluetoothLock lock;
1184 uint8_t status = gatt_client_write_characteristic_descriptor_using_descriptor_handle(
1186 if (status != 0) {
1187 this->op_type_ = OpType::NONE;
1188 return status;
1189 }
1190 return 0;
1191}
1192
1194 if (this->state_ != EngineState::READY) {
1195 return GATT_ERR_NOT_CONNECTED;
1196 }
1197 BluetoothLock lock;
1198 sm_request_pairing(this->con_handle_); // void API; completion via SM events
1199 return 0;
1200}
1201
1203 if (this->state_ != EngineState::READY) {
1204 return GATT_ERR_NOT_CONNECTED;
1205 }
1206 // The CCCD write arrives separately as a descriptor write (V3 semantics);
1207 // this call only gates local delivery via the subscription list.
1208 if (enable) {
1209 if (!this->notify_subscribed_(handle)) {
1210 if (this->notify_subscription_count_ >= RP2_GATT_MAX_NOTIFY_SUBSCRIPTIONS) {
1211 return GATT_ERR_NO_MEMORY;
1212 }
1214 }
1215 } else {
1216 for (uint8_t i = 0; i < this->notify_subscription_count_; i++) {
1217 if (this->notify_subscriptions_[i] == handle) {
1219 break;
1220 }
1221 }
1222 }
1223 this->listener_->on_notify_state(handle, enable, 0);
1224 return 0;
1225}
1226
1228 for (uint8_t i = 0; i < this->notify_subscription_count_; i++) {
1229 if (this->notify_subscriptions_[i] == handle) {
1230 return true;
1231 }
1232 }
1233 return false;
1234}
1235
1236int RP2GattClient::update_connection_params(uint16_t min_interval, uint16_t max_interval, uint16_t latency,
1237 uint16_t timeout) {
1238 if (this->state_ != EngineState::READY) {
1239 return GATT_ERR_NOT_CONNECTED;
1240 }
1241 BluetoothLock lock;
1242 return gap_update_connection_parameters(this->con_handle_, min_interval, max_interval, latency, timeout);
1243}
1244
1246 uint8_t mac[MAC_ADDRESS_SIZE];
1248 bool found = false;
1249 BluetoothLock lock;
1250 // Exhaustive: the db keys on (type, address), so stale entries can share
1251 // the same address bytes under different types.
1252 for (int i = 0; i < le_device_db_max_count(); i++) {
1253 int addr_type = 0;
1254 bd_addr_t addr;
1255 le_device_db_info(i, &addr_type, addr, nullptr);
1256 if (addr_type != BD_ADDR_TYPE_UNKNOWN && memcmp(addr, mac, sizeof(bd_addr_t)) == 0) {
1257 le_device_db_remove(i);
1258 found = true;
1259 }
1260 }
1261 if (found) {
1262 return CONN_OK;
1263 }
1264 // No bond for this address; the shared error domain has no closer code
1265 // (esp32 parity: its remove-bond call also errors for an unknown address).
1266 return GATT_NOT_CONNECTED;
1267}
1268
1269} // namespace esphome::bluetooth_connection
1270
1271#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:287
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:261
void disable_loop()
Disable this component's loop.
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:2396
RAMUniquePtr< T > make_unique(Args &&...args)
Value initialize one T; empty on exhaustion.
Definition helpers.h:2459
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)
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 add_global_state_listener(OTAGlobalStateListener *listener)
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:169
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:49
uint32_t value
Definition hal.cpp:41
const void size_t len
Definition hal.h:68
uint16_t size
Definition helpers.cpp:34
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