5#if defined(USE_RP2040_BLE) && defined(USE_BLE_GATT_CLIENT)
11#include <BluetoothLock.h>
19using ble_device_base::GATT_ERR_NOT_CONNECTED;
20using ble_device_base::GATT_ERR_NO_MEMORY;
26static constexpr uint32_t CONNECT_TIMEOUT_MS = 20000;
30static constexpr uint32_t CONNECT_CANCEL_TIMEOUT_MS = 2000;
33static constexpr uint32_t CONNECT_RETRY_INTERVAL_MS = 50;
35static constexpr uint32_t WRITE_NO_RSP_TIMEOUT_MS = 500;
38static constexpr uint8_t HCI_REASON_CONNECTION_TIMEOUT = 0x08;
45static constexpr uint16_t CONN_SCAN_INTERVAL = 96;
46static constexpr uint16_t CONN_SCAN_WINDOW = 48;
47static constexpr uint16_t CONN_CE_MIN = 16;
48static constexpr uint16_t CONN_CE_MAX = 48;
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;
68 if (!this->
event_pool_.warm() || !this->notify_pool_.warm()) {
69 this->
mark_failed(LOG_STR(
"GATT event pool warm-up failed"));
76 this->
mark_failed(LOG_STR(
"GATT client registry full"));
96#ifdef USE_OTA_STATE_LISTENER
103#ifdef USE_OTA_STATE_LISTENER
130 if (
type != HCI_EVENT_PACKET) {
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) {
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);
142 gap_subevent_le_connection_complete_get_peer_address(packet, peer);
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) {
162 gap_disconnect(con_handle);
167 if (inst ==
nullptr) {
172 gap_disconnect(con_handle);
185 case HCI_EVENT_DISCONNECTION_COMPLETE: {
189 if (inst !=
nullptr) {
200 if (
type != HCI_EVENT_PACKET) {
203 switch (hci_event_packet_get_type(packet)) {
204 case SM_EVENT_JUST_WORKS_REQUEST:
208 sm_just_works_confirm(sm_event_just_works_request_get_handle(packet));
210 case SM_EVENT_PAIRING_COMPLETE: {
212 if (inst !=
nullptr) {
217 case SM_EVENT_REENCRYPTION_COMPLETE: {
221 if (inst !=
nullptr) {
232 if (
type != HCI_EVENT_PACKET) {
235 uint8_t event_type = hci_event_packet_get_type(packet);
238 hci_con_handle_t con_handle;
239 switch (event_type) {
241 con_handle = gatt_event_mtu_get_handle(packet);
243 case GATT_EVENT_SERVICE_QUERY_RESULT:
244 con_handle = gatt_event_service_query_result_get_handle(packet);
246 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
247 con_handle = gatt_event_characteristic_query_result_get_handle(packet);
249 case GATT_EVENT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
250 con_handle = gatt_event_all_characteristic_descriptors_query_result_get_handle(packet);
252 case GATT_EVENT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT:
253 con_handle = gatt_event_long_characteristic_value_query_result_get_handle(packet);
255 case GATT_EVENT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT:
256 con_handle = gatt_event_long_characteristic_descriptor_query_result_get_handle(packet);
258 case GATT_EVENT_NOTIFICATION:
259 con_handle = gatt_event_notification_get_handle(packet);
261 case GATT_EVENT_INDICATION:
262 con_handle = gatt_event_indication_get_handle(packet);
264 case GATT_EVENT_QUERY_COMPLETE:
265 con_handle = gatt_event_query_complete_get_handle(packet);
271 if (inst !=
nullptr) {
277 switch (event_type) {
281 case GATT_EVENT_QUERY_COMPLETE:
284 case GATT_EVENT_SERVICE_QUERY_RESULT: {
285 if (this->
arena_ ==
nullptr) {
292 gatt_client_service_t service;
293 gatt_event_service_query_result_get_service(packet, &service);
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;
304 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT: {
305 if (this->
arena_ ==
nullptr) {
308 if (this->
char_count_ >= RP2_GATT_MAX_CHARACTERISTICS) {
312 gatt_client_characteristic_t characteristic;
313 gatt_event_characteristic_query_result_get_characteristic(packet, &characteristic);
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;
324 case GATT_EVENT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT: {
325 if (this->
arena_ ==
nullptr) {
328 if (this->
desc_count_ >= RP2_GATT_MAX_DESCRIPTORS) {
332 gatt_client_characteristic_descriptor_t descriptor;
333 gatt_event_all_characteristic_descriptors_query_result_get_characteristic_descriptor(packet, &descriptor);
336 dst.handle = descriptor.handle;
340 case GATT_EVENT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT:
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));
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));
351 case GATT_EVENT_NOTIFICATION:
353 gatt_event_notification_get_value(packet),
354 gatt_event_notification_get_value_length(packet));
356 case GATT_EVENT_INDICATION:
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));
368 if (offset >= RP2_GATT_MAX_ATTR_LEN) {
371 if (
len > RP2_GATT_MAX_ATTR_LEN - offset) {
372 len = RP2_GATT_MAX_ATTR_LEN - offset;
382 if (event ==
nullptr) {
388 event->status = status;
389 event->value =
value;
396 if (event ==
nullptr) {
402 event->len = len > RP2_GATT_MAX_ATTR_LEN ? RP2_GATT_MAX_ATTR_LEN :
len;
403 memcpy(event->data, data, event->len);
427 uint16_t dropped = this->
event_queue_.get_and_reset_dropped_count();
431 ESP_LOGE(TAG,
"[%u] Dropped %u GATT control events, disconnecting", this->
engine_index_, dropped);
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);
443 ESP_LOGW(TAG,
"[%u] Connect timeout (queued)", this->
engine_index_);
455 uint32_t budget = cancel_in_flight ? CONNECT_CANCEL_TIMEOUT_MS : CONNECT_TIMEOUT_MS;
459 bool cancel_sent =
false;
466 link_up = this->con_handle_ != HCI_CON_HANDLE_INVALID;
473 gap_connect_cancel();
476 this->connect_cancel_attempted_ =
true;
486 }
else if (cancel_sent) {
497 ESP_LOGW(TAG,
"[%u] Disconnect timeout, forcing idle", this->
engine_index_);
503 bool timed_out =
false;
517 this->
event_queue_.empty() && this->notify_queue_.empty())) {
524 switch (event.
type) {
533 this->
mtu_ =
event.value;
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) {
582 ESP_LOGW(TAG,
"[%u] Connect failed, status=0x%02x", this->
engine_index_, status);
599 if (disc_status != 0) {
606 ESP_LOGV(TAG,
"[%u] Link up, handle=0x%04x, negotiating MTU", this->
engine_index_, con_handle);
686 ESP_LOGV(TAG,
"[%u] Disconnected, reason=0x%02x", this->
engine_index_, reason);
706 if ((att_status == ATT_ERROR_INVALID_OFFSET || att_status == ATT_ERROR_ATTRIBUTE_NOT_LONG) &&
731 return GATT_ERR_NOT_CONNECTED;
734 return GATT_CLIENT_IN_WRONG_STATE;
736 if (this->
arena_ ==
nullptr) {
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;
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;
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;
781 &btstack_characteristic);
785 if (this->
arena_ ==
nullptr) {
791 if (att_status != 0) {
809 service.characteristic_count = this->
char_count_ - service.first_characteristic;
830 chr.descriptor_count = this->
desc_count_ - chr.first_descriptor;
848 ESP_LOGV(TAG,
"[%u] Discovery done (err=%d): %u services, %u characteristics, %u descriptors", this->
engine_index_,
853 error = ATT_ERROR_INSUFFICIENT_RESOURCES;
860 gap_update_connection_parameters(this->
con_handle_, MEDIUM_MIN_CONN_INTERVAL, MEDIUM_MAX_CONN_INTERVAL, 0,
861 MEDIUM_CONN_TIMEOUT);
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);
875 if (this->
arena_ !=
nullptr) {
887 if (this->
arena_ !=
nullptr) {
905 return GATT_ERR_NOT_CONNECTED;
908 return GATT_CLIENT_IN_WRONG_STATE;
911 return GATT_ERR_NOT_CONNECTED;
916 this->
peer_addr_type_ = (addr_type & 1) != 0 ? BD_ADDR_TYPE_LE_RANDOM : BD_ADDR_TYPE_LE_PUBLIC;
951 status = ERROR_CODE_COMMAND_DISALLOWED;
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);
979 if (
status == ERROR_CODE_COMMAND_DISALLOWED) {
984 ESP_LOGW(TAG,
"[%u] gap_connect failed, status=0x%02x", this->
engine_index_, status);
991 return GATT_ERR_NOT_CONNECTED;
1016 gap_connect_cancel();
1025 uint8_t
status = ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
1026 if (this->
con_handle_ != HCI_CON_HANDLE_INVALID) {
1032 ESP_LOGW(TAG,
"[%u] gap_disconnect failed, status=0x%02x", this->
engine_index_, status);
1055 return GATT_ERR_NOT_CONNECTED;
1058 return GATT_CLIENT_IN_WRONG_STATE;
1076 return GATT_ERR_NOT_CONNECTED;
1078 if (
len > RP2_GATT_MAX_ATTR_LEN) {
1079 return ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH;
1090 return GATT_CLIENT_BUSY;
1092 status = gatt_client_write_value_of_characteristic_without_response(this->
con_handle_, handle,
len,
1093 const_cast<uint8_t *
>(data));
1096 if (
status == GATT_CLIENT_BUSY ||
status == BTSTACK_ACL_BUFFERS_FULL) {
1110 if (req != 0 && req != ERROR_CODE_COMMAND_DISALLOWED) {
1127 return GATT_CLIENT_IN_WRONG_STATE;
1152 return GATT_ERR_NOT_CONNECTED;
1155 return GATT_CLIENT_IN_WRONG_STATE;
1161 uint8_t
status = gatt_client_read_long_characteristic_descriptor_using_descriptor_handle(
1172 return GATT_ERR_NOT_CONNECTED;
1175 return GATT_CLIENT_IN_WRONG_STATE;
1177 if (
len > RP2_GATT_MAX_ATTR_LEN) {
1178 return ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH;
1184 uint8_t
status = gatt_client_write_characteristic_descriptor_using_descriptor_handle(
1195 return GATT_ERR_NOT_CONNECTED;
1204 return GATT_ERR_NOT_CONNECTED;
1211 return GATT_ERR_NO_MEMORY;
1239 return GATT_ERR_NOT_CONNECTED;
1242 return gap_update_connection_parameters(this->
con_handle_, min_interval, max_interval, latency, timeout);
1246 uint8_t mac[MAC_ADDRESS_SIZE];
1252 for (
int i = 0; i < le_device_db_max_count(); i++) {
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);
1266 return GATT_NOT_CONNECTED;
void mark_failed()
Mark this component as failed.
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.
void disable_loop()
Disable this component's loop.
rp2040_ble::RP2040BLE * parent_
An STL allocator that uses SPI or internal RAM.
RAMUniquePtr< T > make_unique(Args &&...args)
Value initialize one T; empty on exhaustion.
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_service_discovery_done(int error)
virtual void on_pairing_result(int status)
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)
uint16_t disc_service_cursor_
static RP2GattClient * connect_owner
int read_characteristic(uint16_t handle)
uint8_t notify_subscription_count_
esphome::EventPool< RP2GattNotifyEvent, RP2_GATT_NOTIFY_QUEUE_SIZE - 1 > notify_pool_
btstack_context_callback_registration_t can_write_registration_
int issue_characteristic_query_(uint16_t service_index)
void advance_discovery_(uint8_t att_status)
bd_addr_type_t peer_addr_type_
void finish_discovery_(int error)
void handle_event_(const RP2GattEvent &event)
void finish_write_no_rsp_(uint8_t status)
uint32_t write_no_rsp_started_
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
void cleanup_link_state_()
hci_con_handle_t con_handle_
static RP2GattClient * instance_for_con_handle(hci_con_handle_t con_handle)
static void can_write_no_rsp_trampoline(void *context)
void on_ota_global_state(ota::OTAState state, float progress, uint8_t error, ota::OTAComponent *comp) override
DiscoveryPhase discovery_phase_
uint16_t disc_char_cursor_
int read_descriptor(uint16_t handle)
bool op_in_flight_() const
static uint8_t instance_count
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_
uint32_t disconnecting_started_
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)
uint32_t connect_started_
int notify_characteristic(uint16_t handle, bool enable)
static btstack_packet_callback_registration_t sm_event_registration
bool notify_subscribed_(uint16_t handle) const
gatt_client_notification_t notification_registration_
int write_descriptor(uint16_t handle, const uint8_t *data, uint16_t len)
void handle_disconnected_(uint8_t reason)
static RP2GattClient * instances[ESPHOME_BLE_GATT_CLIENT_COUNT]
void handle_query_complete_(uint8_t att_status)
void assemble_blob_irq_(uint16_t offset, const uint8_t *data, uint16_t len)
float get_setup_priority() const override
void dump_config() override
int issue_descriptor_query_(uint16_t char_index)
static void gatt_packet_handler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t size)
void release_scan_inhibit_()
RAMUniquePtr< ServiceArena > arena_
uint8_t op_buffer_[RP2_GATT_MAX_ATTR_LEN]
ble_device_base::ConnectionType connection_type_
esphome::LockFreeQueue< RP2GattEvent, RP2_GATT_EVENT_QUEUE_SIZE > event_queue_
esphome::EventPool< RP2GattEvent, RP2_GATT_EVENT_QUEUE_SIZE - 1 > event_pool_
uint32_t connect_retry_ms_
bool connect_cancel_attempted_
void fail_connection_(uint8_t reason)
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...
void release_scan_inhibit()
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...
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
uint32_t IRAM_ATTR HOT millis()
Borrowed view of the backend-owned service table.
const GattDescriptor * descriptors
uint16_t descriptor_count
const GattCharacteristic * characteristics
const GattService * services
uint16_t characteristic_count
uint8_t data[RP2_GATT_MAX_ATTR_LEN]
spi_device_handle_t handle