xref: /btstack/src/ble/gatt_client.c (revision 2a954d4aec7ecbfde55b8fc19be74a0e88beb75c)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
24  * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define BTSTACK_FILE__ "gatt_client.c"
39 
40 #include <stdint.h>
41 #include <string.h>
42 #include <stddef.h>
43 
44 #include "btstack_config.h"
45 
46 #include "ble/att_dispatch.h"
47 #include "ble/att_db.h"
48 #include "ble/gatt_client.h"
49 #include "ble/le_device_db.h"
50 #include "ble/sm.h"
51 #include "bluetooth_psm.h"
52 #include "btstack_debug.h"
53 #include "btstack_event.h"
54 #include "btstack_memory.h"
55 #include "btstack_run_loop.h"
56 #include "btstack_util.h"
57 #include "hci.h"
58 #include "hci_dump.h"
59 #include "hci_event_builder.h"
60 #include "l2cap.h"
61 #include "classic/sdp_client.h"
62 #include "bluetooth_gatt.h"
63 #include "bluetooth_sdp.h"
64 #include "classic/sdp_util.h"
65 
66 #if defined(ENABLE_GATT_OVER_EATT) && !defined(ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE)
67 #error "GATT Over EATT requires support for L2CAP Enhanced CoC. Please enable ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE"
68 #endif
69 
70 // L2CAP Test Spec p35 defines a minimum of 100 ms, but PTS might indicate an error if we sent after 100 ms
71 #define GATT_CLIENT_COLLISION_BACKOFF_MS 150
72 
73 static btstack_linked_list_t gatt_client_connections;
74 static btstack_linked_list_t gatt_client_value_listeners;
75 #ifdef ENABLE_GATT_CLIENT_SERVICE_CHANGED
76 static btstack_linked_list_t gatt_client_service_changed_handler;
77 #endif
78 static btstack_packet_callback_registration_t hci_event_callback_registration;
79 static btstack_packet_callback_registration_t sm_event_callback_registration;
80 static btstack_context_callback_registration_t gatt_client_deferred_event_emit;
81 
82 // GATT Client Configuration
83 static bool                 gatt_client_mtu_exchange_enabled;
84 static gap_security_level_t gatt_client_required_security_level;
85 
86 static void gatt_client_att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size);
87 static void gatt_client_event_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
88 static void gatt_client_report_error_if_pending(gatt_client_t *gatt_client, uint8_t att_error_code);
89 
90 #ifdef ENABLE_LE_SIGNED_WRITE
91 static void att_signed_write_handle_cmac_result(uint8_t hash[8]);
92 #endif
93 
94 #ifdef ENABLE_GATT_OVER_CLASSIC
95 static gatt_client_t * gatt_client_get_context_for_l2cap_cid(uint16_t l2cap_cid);
96 static void gatt_client_classic_handle_connected(gatt_client_t * gatt_client, uint8_t status);
97 static void gatt_client_classic_handle_disconnected(gatt_client_t * gatt_client);
98 static void gatt_client_classic_retry(btstack_timer_source_t * ts);
99 #endif
100 
101 #ifdef ENABLE_GATT_OVER_EATT
102 static bool gatt_client_le_enhanced_handle_can_send_query(gatt_client_t * gatt_client);
103 static void gatt_client_le_enhanced_retry(btstack_timer_source_t * ts);
104 #endif
105 
106 void gatt_client_init(void){
107     gatt_client_connections = NULL;
108 #ifdef ENABLE_GATT_CLIENT_SERVICE_CHANGED
109     gatt_client_service_changed_handler = NULL;
110 #endif
111     // default configuration
112     gatt_client_mtu_exchange_enabled    = true;
113     gatt_client_required_security_level = LEVEL_0;
114 
115     // register for HCI Events
116     hci_event_callback_registration.callback = &gatt_client_event_packet_handler;
117     hci_add_event_handler(&hci_event_callback_registration);
118 
119     // register for SM Events
120     sm_event_callback_registration.callback = &gatt_client_event_packet_handler;
121     sm_add_event_handler(&sm_event_callback_registration);
122 
123     // and ATT Client PDUs
124     att_dispatch_register_client(gatt_client_att_packet_handler);
125 }
126 
127 void gatt_client_set_required_security_level(gap_security_level_t level){
128     gatt_client_required_security_level = level;
129 }
130 
131 static gatt_client_t * gatt_client_for_timer(btstack_timer_source_t * ts){
132     btstack_linked_list_iterator_t it;
133     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
134     while (btstack_linked_list_iterator_has_next(&it)){
135         gatt_client_t * gatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
136         if (&gatt_client->gc_timeout == ts) {
137             return gatt_client;
138         }
139     }
140     return NULL;
141 }
142 
143 static void gatt_client_timeout_handler(btstack_timer_source_t * timer){
144     gatt_client_t * gatt_client = gatt_client_for_timer(timer);
145     if (gatt_client == NULL) return;
146     log_info("GATT client timeout handle, handle 0x%02x", gatt_client->con_handle);
147     gatt_client_report_error_if_pending(gatt_client, ATT_ERROR_TIMEOUT);
148 }
149 
150 static void gatt_client_timeout_start(gatt_client_t * gatt_client){
151     log_debug("GATT client timeout start, handle 0x%02x", gatt_client->con_handle);
152     btstack_run_loop_remove_timer(&gatt_client->gc_timeout);
153     btstack_run_loop_set_timer_handler(&gatt_client->gc_timeout, gatt_client_timeout_handler);
154     btstack_run_loop_set_timer(&gatt_client->gc_timeout, 30000); // 30 seconds sm timeout
155     btstack_run_loop_add_timer(&gatt_client->gc_timeout);
156 }
157 
158 static void gatt_client_timeout_stop(gatt_client_t * gatt_client){
159     log_debug("GATT client timeout stop, handle 0x%02x", gatt_client->con_handle);
160     btstack_run_loop_remove_timer(&gatt_client->gc_timeout);
161 }
162 
163 static gap_security_level_t gatt_client_le_security_level_for_connection(hci_con_handle_t con_handle){
164     uint8_t encryption_key_size = gap_encryption_key_size(con_handle);
165     if (encryption_key_size == 0) return LEVEL_0;
166 
167     bool authenticated = gap_authenticated(con_handle);
168     if (!authenticated) return LEVEL_2;
169 
170     return encryption_key_size == 16 ? LEVEL_4 : LEVEL_3;
171 }
172 
173 static gatt_client_t * gatt_client_get_context_for_handle(uint16_t handle){
174     btstack_linked_item_t *it;
175     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
176         gatt_client_t * gatt_client = (gatt_client_t *) it;
177         if (gatt_client->con_handle == handle){
178             return gatt_client;
179         }
180     }
181     return NULL;
182 }
183 
184 
185 // @return gatt_client context
186 // returns existing one, or tries to setup new one
187 static uint8_t gatt_client_provide_context_for_handle(hci_con_handle_t con_handle, gatt_client_t ** out_gatt_client){
188     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
189 
190     if (gatt_client != NULL){
191         *out_gatt_client = gatt_client;
192         return ERROR_CODE_SUCCESS;
193     }
194 
195     // bail if no such hci connection
196     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
197     if (hci_connection == NULL){
198         log_error("No connection for handle 0x%04x", con_handle);
199         *out_gatt_client = NULL;
200         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
201     }
202 
203     gatt_client = btstack_memory_gatt_client_get();
204     if (gatt_client == NULL){
205         *out_gatt_client = NULL;
206         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
207     }
208     // init state
209     gatt_client->bearer_type = ATT_BEARER_UNENHANCED_LE;
210     gatt_client->con_handle = con_handle;
211     gatt_client->mtu = ATT_DEFAULT_MTU;
212     gatt_client->security_level = gatt_client_le_security_level_for_connection(con_handle);
213     if (gatt_client_mtu_exchange_enabled){
214         gatt_client->mtu_state = SEND_MTU_EXCHANGE;
215     } else {
216         gatt_client->mtu_state = MTU_AUTO_EXCHANGE_DISABLED;
217     }
218     gatt_client->state = P_READY;
219     gatt_client->gatt_service_state = GATT_CLIENT_SERVICE_DISCOVER_W2_SEND;
220 #ifdef ENABLE_GATT_OVER_EATT
221     gatt_client->eatt_state = GATT_CLIENT_EATT_IDLE;
222 #endif
223     btstack_linked_list_add(&gatt_client_connections, (btstack_linked_item_t*)gatt_client);
224 
225     // get unenhanced att bearer state
226     if (hci_connection->att_connection.mtu_exchanged){
227         gatt_client->mtu = hci_connection->att_connection.mtu;
228         gatt_client->mtu_state = MTU_EXCHANGED;
229     }
230     *out_gatt_client = gatt_client;
231     return ERROR_CODE_SUCCESS;
232 }
233 
234 static bool is_ready(gatt_client_t * gatt_client){
235     return gatt_client->state == P_READY;
236 }
237 
238 static uint8_t gatt_client_provide_context_for_request(hci_con_handle_t con_handle, gatt_client_t ** out_gatt_client){
239     gatt_client_t * gatt_client = NULL;
240     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
241     if (status != ERROR_CODE_SUCCESS){
242         return status;
243     }
244 
245 #ifdef ENABLE_GATT_OVER_EATT
246     if (gatt_client->eatt_state == GATT_CLIENT_EATT_READY){
247         btstack_linked_list_iterator_t it;
248         gatt_client_t * eatt_client = NULL;
249         // find free eatt client
250         btstack_linked_list_iterator_init(&it, &gatt_client->eatt_clients);
251         while (btstack_linked_list_iterator_has_next(&it)){
252             gatt_client_t * client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
253             if (client->state == P_READY){
254                 eatt_client = client;
255                 break;
256             }
257         }
258         if (eatt_client == NULL){
259             return ERROR_CODE_COMMAND_DISALLOWED;
260         }
261         gatt_client = eatt_client;
262     }
263 #endif
264 
265     if (is_ready(gatt_client) == false){
266         return GATT_CLIENT_IN_WRONG_STATE;
267     }
268 
269     gatt_client_timeout_start(gatt_client);
270 
271     *out_gatt_client = gatt_client;
272 
273     return status;
274 }
275 
276 int gatt_client_is_ready(hci_con_handle_t con_handle){
277     gatt_client_t * gatt_client;
278     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
279     if (status != ERROR_CODE_SUCCESS){
280         return 0;
281     }
282     return is_ready(gatt_client) ? 1 : 0;
283 }
284 
285 void gatt_client_mtu_enable_auto_negotiation(uint8_t enabled){
286     gatt_client_mtu_exchange_enabled = enabled != 0;
287 }
288 
289 uint8_t gatt_client_get_mtu(hci_con_handle_t con_handle, uint16_t * mtu){
290     gatt_client_t * gatt_client;
291     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
292     if (status != ERROR_CODE_SUCCESS){
293         return status;
294     }
295 
296     if ((gatt_client->mtu_state == MTU_EXCHANGED) || (gatt_client->mtu_state == MTU_AUTO_EXCHANGE_DISABLED)){
297         *mtu = gatt_client->mtu;
298         return ERROR_CODE_SUCCESS;
299     }
300     *mtu = ATT_DEFAULT_MTU;
301     return GATT_CLIENT_IN_WRONG_STATE;
302 }
303 
304 static uint8_t *gatt_client_reserve_request_buffer(gatt_client_t *gatt_client) {
305     switch (gatt_client->bearer_type){
306 #ifdef ENABLE_GATT_OVER_CLASSIC
307         case ATT_BEARER_UNENHANCED_CLASSIC:
308 #endif
309         case ATT_BEARER_UNENHANCED_LE:
310             l2cap_reserve_packet_buffer();
311             return l2cap_get_outgoing_buffer();
312 #ifdef ENABLE_GATT_OVER_EATT
313         case ATT_BEARER_ENHANCED_LE:
314             return gatt_client->eatt_storage_buffer;
315 #endif
316         default:
317             btstack_unreachable();
318             break;
319     }
320     return NULL;
321 }
322 
323 // precondition: can_send_packet_now == TRUE
324 static uint8_t gatt_client_send(gatt_client_t * gatt_client, uint16_t len){
325     switch (gatt_client->bearer_type){
326         case ATT_BEARER_UNENHANCED_LE:
327             return l2cap_send_prepared_connectionless(gatt_client->con_handle, L2CAP_CID_ATTRIBUTE_PROTOCOL, len);
328 #ifdef ENABLE_GATT_OVER_CLASSIC
329         case ATT_BEARER_UNENHANCED_CLASSIC:
330             return l2cap_send_prepared(gatt_client->l2cap_cid, len);
331 #endif
332 #ifdef ENABLE_GATT_OVER_EATT
333         case ATT_BEARER_ENHANCED_LE:
334             return l2cap_send(gatt_client->l2cap_cid, gatt_client->eatt_storage_buffer, len);
335 #endif
336         default:
337             btstack_unreachable();
338             return ERROR_CODE_HARDWARE_FAILURE;
339     }
340 }
341 
342 // precondition: can_send_packet_now == TRUE
343 static uint8_t att_confirmation(gatt_client_t * gatt_client) {
344     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
345 
346     request[0] = ATT_HANDLE_VALUE_CONFIRMATION;
347 
348     return gatt_client_send(gatt_client, 1);
349 }
350 
351 // precondition: can_send_packet_now == TRUE
352 static uint8_t att_find_information_request(gatt_client_t *gatt_client, uint8_t request_type, uint16_t start_handle,
353                                             uint16_t end_handle) {
354     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
355 
356     request[0] = request_type;
357     little_endian_store_16(request, 1, start_handle);
358     little_endian_store_16(request, 3, end_handle);
359 
360     return gatt_client_send(gatt_client, 5);
361 }
362 
363 // precondition: can_send_packet_now == TRUE
364 static uint8_t
365 att_find_by_type_value_request(gatt_client_t *gatt_client, uint8_t request_type, uint16_t attribute_group_type,
366                                uint16_t start_handle, uint16_t end_handle, uint8_t *value, uint16_t value_size) {
367     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
368     request[0] = request_type;
369 
370     little_endian_store_16(request, 1, start_handle);
371     little_endian_store_16(request, 3, end_handle);
372     little_endian_store_16(request, 5, attribute_group_type);
373     (void)memcpy(&request[7], value, value_size);
374 
375     return gatt_client_send(gatt_client, 7u + value_size);
376 }
377 
378 // precondition: can_send_packet_now == TRUE
379 static uint8_t
380 att_read_by_type_or_group_request_for_uuid16(gatt_client_t *gatt_client, uint8_t request_type, uint16_t uuid16,
381                                              uint16_t start_handle, uint16_t end_handle) {
382     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
383 
384     request[0] = request_type;
385     little_endian_store_16(request, 1, start_handle);
386     little_endian_store_16(request, 3, end_handle);
387     little_endian_store_16(request, 5, uuid16);
388 
389     return gatt_client_send(gatt_client, 7);
390 }
391 
392 // precondition: can_send_packet_now == TRUE
393 static uint8_t
394 att_read_by_type_or_group_request_for_uuid128(gatt_client_t *gatt_client, uint8_t request_type, const uint8_t *uuid128,
395                                               uint16_t start_handle, uint16_t end_handle) {
396     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
397 
398     request[0] = request_type;
399     little_endian_store_16(request, 1, start_handle);
400     little_endian_store_16(request, 3, end_handle);
401     reverse_128(uuid128, &request[5]);
402 
403     return gatt_client_send(gatt_client, 21);
404 }
405 
406 // precondition: can_send_packet_now == TRUE
407 static uint8_t att_read_request(gatt_client_t *gatt_client, uint8_t request_type, uint16_t attribute_handle) {
408     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
409 
410     request[0] = request_type;
411     little_endian_store_16(request, 1, attribute_handle);
412 
413     return gatt_client_send(gatt_client, 3);
414 }
415 
416 // precondition: can_send_packet_now == TRUE
417 static uint8_t att_read_blob_request(gatt_client_t *gatt_client, uint8_t request_type, uint16_t attribute_handle,
418                                      uint16_t value_offset) {
419     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
420 
421     request[0] = request_type;
422     little_endian_store_16(request, 1, attribute_handle);
423     little_endian_store_16(request, 3, value_offset);
424 
425     return gatt_client_send(gatt_client, 5);
426 }
427 
428 static uint8_t
429 att_read_multiple_request_with_opcode(gatt_client_t *gatt_client, uint16_t num_value_handles, uint16_t *value_handles, uint8_t opcode) {
430     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
431 
432     request[0] = opcode;
433     uint16_t i;
434     uint16_t offset = 1;
435     for (i=0;i<num_value_handles;i++){
436         little_endian_store_16(request, offset, value_handles[i]);
437         offset += 2;
438     }
439 
440     return gatt_client_send(gatt_client, offset);
441 }
442 
443 static uint8_t
444 att_read_multiple_request(gatt_client_t *gatt_client, uint16_t num_value_handles, uint16_t *value_handles) {
445     return att_read_multiple_request_with_opcode(gatt_client, num_value_handles, value_handles, ATT_READ_MULTIPLE_REQUEST);
446 }
447 
448 #ifdef ENABLE_GATT_OVER_EATT
449 static uint8_t
450 att_read_multiple_variable_request(gatt_client_t *gatt_client, uint16_t num_value_handles, uint16_t *value_handles) {
451     return att_read_multiple_request_with_opcode(gatt_client, num_value_handles, value_handles, ATT_READ_MULTIPLE_VARIABLE_REQ);
452 }
453 #endif
454 
455 #ifdef ENABLE_LE_SIGNED_WRITE
456 // precondition: can_send_packet_now == TRUE
457 static uint8_t att_signed_write_request(gatt_client_t *gatt_client, uint16_t request_type, uint16_t attribute_handle,
458                                         uint16_t value_length, uint8_t *value, uint32_t sign_counter, uint8_t sgn[8]) {
459     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
460 
461     request[0] = request_type;
462     little_endian_store_16(request, 1, attribute_handle);
463     (void)memcpy(&request[3], value, value_length);
464     little_endian_store_32(request, 3 + value_length, sign_counter);
465     reverse_64(sgn, &request[3 + value_length + 4]);
466 
467     return gatt_client_send(gatt_client, 3 + value_length + 12);
468 }
469 #endif
470 
471 // precondition: can_send_packet_now == TRUE
472 static uint8_t
473 att_write_request(gatt_client_t *gatt_client, uint8_t request_type, uint16_t attribute_handle, uint16_t value_length,
474                   uint8_t *value) {
475     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
476 
477     request[0] = request_type;
478     little_endian_store_16(request, 1, attribute_handle);
479     (void)memcpy(&request[3], value, value_length);
480 
481     return gatt_client_send(gatt_client, 3u + value_length);
482 }
483 
484 // precondition: can_send_packet_now == TRUE
485 static uint8_t att_execute_write_request(gatt_client_t *gatt_client, uint8_t request_type, uint8_t execute_write) {
486     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
487 
488     request[0] = request_type;
489     request[1] = execute_write;
490 
491     return gatt_client_send(gatt_client, 2);
492 }
493 
494 // precondition: can_send_packet_now == TRUE
495 static uint8_t att_prepare_write_request(gatt_client_t *gatt_client, uint8_t request_type, uint16_t attribute_handle,
496                                          uint16_t value_offset, uint16_t blob_length, uint8_t *value) {
497     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
498 
499     request[0] = request_type;
500     little_endian_store_16(request, 1, attribute_handle);
501     little_endian_store_16(request, 3, value_offset);
502     (void)memcpy(&request[5], &value[value_offset], blob_length);
503 
504     return gatt_client_send(gatt_client,  5u + blob_length);
505 }
506 
507 static uint8_t att_exchange_mtu_request(gatt_client_t *gatt_client) {
508     uint8_t *request = gatt_client_reserve_request_buffer(gatt_client);
509 
510     request[0] = ATT_EXCHANGE_MTU_REQUEST;
511     uint16_t mtu = l2cap_max_le_mtu();
512     little_endian_store_16(request, 1, mtu);
513 
514     return gatt_client_send(gatt_client, 3);
515 }
516 
517 static uint16_t write_blob_length(gatt_client_t * gatt_client){
518     uint16_t max_blob_length = gatt_client->mtu - 5u;
519     if (gatt_client->attribute_offset >= gatt_client->attribute_length) {
520         return 0;
521     }
522     uint16_t rest_length = gatt_client->attribute_length - gatt_client->attribute_offset;
523     if (max_blob_length > rest_length){
524         return rest_length;
525     }
526     return max_blob_length;
527 }
528 
529 static void send_gatt_services_request(gatt_client_t *gatt_client){
530     att_read_by_type_or_group_request_for_uuid16(gatt_client, ATT_READ_BY_GROUP_TYPE_REQUEST,
531                                                  gatt_client->uuid16, gatt_client->start_group_handle,
532                                                  gatt_client->end_group_handle);
533 }
534 
535 static void send_gatt_by_uuid_request(gatt_client_t *gatt_client, uint16_t attribute_group_type){
536     if (gatt_client->uuid16 != 0u){
537         uint8_t uuid16[2];
538         little_endian_store_16(uuid16, 0, gatt_client->uuid16);
539         att_find_by_type_value_request(gatt_client, ATT_FIND_BY_TYPE_VALUE_REQUEST, attribute_group_type,
540                                        gatt_client->start_group_handle, gatt_client->end_group_handle, uuid16, 2);
541         return;
542     }
543     uint8_t uuid128[16];
544     reverse_128(gatt_client->uuid128, uuid128);
545     att_find_by_type_value_request(gatt_client, ATT_FIND_BY_TYPE_VALUE_REQUEST, attribute_group_type,
546                                    gatt_client->start_group_handle, gatt_client->end_group_handle, uuid128, 16);
547 }
548 
549 static void send_gatt_services_by_uuid_request(gatt_client_t *gatt_client){
550     send_gatt_by_uuid_request(gatt_client, GATT_PRIMARY_SERVICE_UUID);
551 }
552 
553 static void send_gatt_included_service_uuid_request(gatt_client_t *gatt_client){
554     att_read_request(gatt_client, ATT_READ_REQUEST, gatt_client->query_start_handle);
555 }
556 
557 static void send_gatt_included_service_request(gatt_client_t *gatt_client){
558     att_read_by_type_or_group_request_for_uuid16(gatt_client, ATT_READ_BY_TYPE_REQUEST,
559                                                  GATT_INCLUDE_SERVICE_UUID, gatt_client->start_group_handle,
560                                                  gatt_client->end_group_handle);
561 }
562 
563 static void send_gatt_characteristic_request(gatt_client_t *gatt_client){
564     att_read_by_type_or_group_request_for_uuid16(gatt_client, ATT_READ_BY_TYPE_REQUEST,
565                                                  GATT_CHARACTERISTICS_UUID, gatt_client->start_group_handle,
566                                                  gatt_client->end_group_handle);
567 }
568 
569 static void send_gatt_characteristic_descriptor_request(gatt_client_t *gatt_client){
570     att_find_information_request(gatt_client, ATT_FIND_INFORMATION_REQUEST, gatt_client->start_group_handle,
571                                  gatt_client->end_group_handle);
572 }
573 
574 static void send_gatt_read_characteristic_value_request(gatt_client_t *gatt_client){
575     att_read_request(gatt_client, ATT_READ_REQUEST, gatt_client->attribute_handle);
576 }
577 
578 static void send_gatt_read_by_type_request(gatt_client_t * gatt_client){
579     if (gatt_client->uuid16 != 0u){
580         att_read_by_type_or_group_request_for_uuid16(gatt_client, ATT_READ_BY_TYPE_REQUEST,
581                                                      gatt_client->uuid16, gatt_client->start_group_handle,
582                                                      gatt_client->end_group_handle);
583     } else {
584         att_read_by_type_or_group_request_for_uuid128(gatt_client, ATT_READ_BY_TYPE_REQUEST,
585                                                       gatt_client->uuid128, gatt_client->start_group_handle,
586                                                       gatt_client->end_group_handle);
587     }
588 }
589 
590 static void send_gatt_read_blob_request(gatt_client_t *gatt_client){
591     if (gatt_client->attribute_offset == 0){
592         att_read_request(gatt_client, ATT_READ_REQUEST, gatt_client->attribute_handle);
593     } else {
594         att_read_blob_request(gatt_client, ATT_READ_BLOB_REQUEST, gatt_client->attribute_handle,
595                               gatt_client->attribute_offset);
596     }
597 }
598 
599 static void send_gatt_read_multiple_request(gatt_client_t * gatt_client){
600     att_read_multiple_request(gatt_client, gatt_client->read_multiple_handle_count, gatt_client->read_multiple_handles);
601 }
602 
603 #ifdef ENABLE_GATT_OVER_EATT
604 static void send_gatt_read_multiple_variable_request(gatt_client_t * gatt_client){
605     att_read_multiple_variable_request(gatt_client, gatt_client->read_multiple_handle_count, gatt_client->read_multiple_handles);
606 }
607 #endif
608 
609 static void send_gatt_write_attribute_value_request(gatt_client_t * gatt_client){
610     att_write_request(gatt_client, ATT_WRITE_REQUEST, gatt_client->attribute_handle, gatt_client->attribute_length,
611                       gatt_client->attribute_value);
612 }
613 
614 static void send_gatt_write_client_characteristic_configuration_request(gatt_client_t * gatt_client){
615     att_write_request(gatt_client, ATT_WRITE_REQUEST, gatt_client->client_characteristic_configuration_handle, 2,
616                       gatt_client->client_characteristic_configuration_value);
617 }
618 
619 static void send_gatt_prepare_write_request(gatt_client_t * gatt_client){
620     att_prepare_write_request(gatt_client, ATT_PREPARE_WRITE_REQUEST, gatt_client->attribute_handle,
621                               gatt_client->attribute_offset, write_blob_length(gatt_client),
622                               gatt_client->attribute_value);
623 }
624 
625 static void send_gatt_execute_write_request(gatt_client_t * gatt_client){
626     att_execute_write_request(gatt_client, ATT_EXECUTE_WRITE_REQUEST, 1);
627 }
628 
629 static void send_gatt_cancel_prepared_write_request(gatt_client_t * gatt_client){
630     att_execute_write_request(gatt_client, ATT_EXECUTE_WRITE_REQUEST, 0);
631 }
632 
633 #ifndef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
634 static void send_gatt_read_client_characteristic_configuration_request(gatt_client_t * gatt_client){
635     att_read_by_type_or_group_request_for_uuid16(gatt_client, ATT_READ_BY_TYPE_REQUEST,
636                                                  GATT_CLIENT_CHARACTERISTICS_CONFIGURATION,
637                                                  gatt_client->start_group_handle, gatt_client->end_group_handle);
638 }
639 #endif
640 
641 static void send_gatt_read_characteristic_descriptor_request(gatt_client_t * gatt_client){
642     att_read_request(gatt_client, ATT_READ_REQUEST, gatt_client->attribute_handle);
643 }
644 
645 #ifdef ENABLE_LE_SIGNED_WRITE
646 static void send_gatt_signed_write_request(gatt_client_t * gatt_client, uint32_t sign_counter){
647     att_signed_write_request(gatt_client, ATT_SIGNED_WRITE_COMMAND, gatt_client->attribute_handle,
648                              gatt_client->attribute_length, gatt_client->attribute_value, sign_counter,
649                              gatt_client->cmac);
650 }
651 #endif
652 
653 static uint16_t get_last_result_handle_from_service_list(uint8_t * packet, uint16_t size){
654     if (size < 2) return 0xffff;
655     uint8_t attr_length = packet[1];
656     if ((2 + attr_length) > size) return 0xffff;
657     return little_endian_read_16(packet, size - attr_length + 2u);
658 }
659 
660 static uint16_t get_last_result_handle_from_characteristics_list(uint8_t * packet, uint16_t size){
661     if (size < 2) return 0xffff;
662     uint8_t attr_length = packet[1];
663     if ((2 + attr_length) > size) return 0xffff;
664     return little_endian_read_16(packet, size - attr_length + 3u);
665 }
666 
667 static uint16_t get_last_result_handle_from_included_services_list(uint8_t * packet, uint16_t size){
668     if (size < 2) return 0xffff;
669     uint8_t attr_length = packet[1];
670     if ((2 + attr_length) > size) return 0xffff;
671     return little_endian_read_16(packet, size - attr_length);
672 }
673 
674 #ifdef ENABLE_GATT_CLIENT_SERVICE_CHANGED
675 static void gatt_client_service_emit_event(gatt_client_t * gatt_client, uint8_t * event, uint16_t size){
676     btstack_linked_list_iterator_t it;
677     btstack_linked_list_iterator_init(&it, &gatt_client_service_changed_handler);
678     while (btstack_linked_list_iterator_has_next(&it)) {
679         btstack_packet_callback_registration_t *callback = (btstack_packet_callback_registration_t *) btstack_linked_list_iterator_next(&it);
680         (*callback->callback)(HCI_EVENT_PACKET, (uint16_t) gatt_client->con_handle, event, size);
681     }
682 }
683 
684 static void
685 gatt_client_service_emit_database_hash(gatt_client_t *gatt_client, const uint8_t *value, uint16_t value_len) {
686     if (value_len == 16){
687         uint8_t event[21];
688         hci_event_builder_context_t context;
689         hci_event_builder_init(&context, event, sizeof(event), HCI_EVENT_GATTSERVICE_META, GATTSERVICE_SUBEVENT_GATT_DATABASE_HASH);
690         hci_event_builder_add_con_handle(&context, gatt_client->con_handle);
691         hci_event_builder_add_bytes(&context, value, 16);
692         gatt_client_service_emit_event(gatt_client, event, hci_event_builder_get_length(&context));
693     }
694 }
695 
696 static void
697 gatt_client_service_emit_service_changed(gatt_client_t *gatt_client, const uint8_t *value, uint16_t value_len) {
698     if (value_len == 4){
699         uint8_t event[9];
700         hci_event_builder_context_t context;
701         hci_event_builder_init(&context, event, sizeof(event), HCI_EVENT_GATTSERVICE_META, GATTSERVICE_SUBEVENT_GATT_SERVICE_CHANGED);
702         hci_event_builder_add_con_handle(&context, gatt_client->con_handle);
703         hci_event_builder_add_bytes(&context, value, 4);
704         gatt_client_service_emit_event(gatt_client, event, hci_event_builder_get_length(&context));
705     }
706 }
707 
708 static void gatt_client_service_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
709     UNUSED(channel);  // ok: handling own l2cap events
710     UNUSED(size);     // ok: there is no channel
711 
712     hci_con_handle_t con_handle;
713     gatt_client_t *gatt_client;
714     gatt_client_service_t service;
715     gatt_client_characteristic_t characteristic;
716     switch (packet_type) {
717         case HCI_EVENT_PACKET:
718             switch (hci_event_packet_get_type(packet)) {
719                 case GATT_EVENT_SERVICE_QUERY_RESULT:
720                     con_handle = gatt_event_service_query_result_get_handle(packet);
721                     gatt_client = gatt_client_get_context_for_handle(con_handle);
722                     btstack_assert(gatt_client != NULL);
723                     btstack_assert(gatt_client->gatt_service_state == GATT_CLIENT_SERVICE_DISCOVER_W4_DONE);
724                     gatt_event_service_query_result_get_service(packet, &service);
725                     gatt_client->gatt_service_start_group_handle = service.start_group_handle;
726                     gatt_client->gatt_service_end_group_handle = service.end_group_handle;
727                     break;
728                 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
729                     con_handle = gatt_event_characteristic_query_result_get_handle(packet);
730                     gatt_client = gatt_client_get_context_for_handle(con_handle);
731                     btstack_assert(gatt_client != NULL);
732                     btstack_assert(gatt_client->gatt_service_state == GATT_CLIENT_SERVICE_DISCOVER_CHARACTERISTICS_W4_DONE);
733                     gatt_event_characteristic_query_result_get_characteristic(packet, &characteristic);
734                     switch (characteristic.uuid16){
735                         case ORG_BLUETOOTH_CHARACTERISTIC_GATT_SERVICE_CHANGED:
736                             gatt_client->gatt_service_changed_value_handle = characteristic.value_handle;
737                             gatt_client->gatt_service_changed_end_handle = characteristic.end_handle;
738                             break;
739                         case ORG_BLUETOOTH_CHARACTERISTIC_DATABASE_HASH:
740                             gatt_client->gatt_service_database_hash_value_handle = characteristic.value_handle;
741                             gatt_client->gatt_service_database_hash_end_handle = characteristic.end_handle;
742                             break;
743                         default:
744                             break;
745                     }
746                     break;
747                 case GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT:
748                     con_handle = gatt_event_characteristic_value_query_result_get_handle(packet);
749                     gatt_client = gatt_client_get_context_for_handle(con_handle);
750                     btstack_assert(gatt_client != NULL);
751                     btstack_assert(gatt_client->gatt_service_state == GATT_CLIENT_SERVICE_DATABASE_HASH_READ_W4_DONE);
752                         gatt_client_service_emit_database_hash(gatt_client,
753                                                                gatt_event_characteristic_value_query_result_get_value(packet),
754                                                                gatt_event_characteristic_value_query_result_get_value_length(packet));
755                     break;
756                 case GATT_EVENT_QUERY_COMPLETE:
757                     con_handle = gatt_event_query_complete_get_handle(packet);
758                     gatt_client = gatt_client_get_context_for_handle(con_handle);
759                     btstack_assert(gatt_client != NULL);
760                     switch (gatt_client->gatt_service_state) {
761                         case GATT_CLIENT_SERVICE_DISCOVER_W4_DONE:
762                             gatt_client->gatt_service_state = GATT_CLIENT_SERVICE_DISCOVER_CHARACTERISTICS_W2_SEND;
763                             break;
764                         case GATT_CLIENT_SERVICE_DISCOVER_CHARACTERISTICS_W4_DONE:
765                             gatt_client->gatt_service_state = GATT_CLIENT_SERVICE_SERVICE_CHANGED_WRITE_CCCD_W2_SEND;
766                             break;
767                         case GATT_CLIENT_SERVICE_SERVICE_CHANGED_WRITE_CCCD_W4_DONE:
768                             gatt_client->gatt_service_state = GATT_CLIENT_SERVICE_DATABASE_HASH_READ_W2_SEND;
769                             break;
770                         case GATT_CLIENT_SERVICE_DATABASE_HASH_READ_W4_DONE:
771                             gatt_client->gatt_service_state = GATT_CLIENT_SERVICE_DATABASE_HASH_WRITE_CCCD_W2_SEND;
772                             break;
773                         case GATT_CLIENT_SERVICE_DATABASE_HASH_WRITE_CCCD_W4_DONE:
774                             gatt_client->gatt_service_state = GATT_CLIENT_SERVICE_DONE;
775                             break;
776                         default:
777                             btstack_unreachable();
778                             break;
779                     }
780                     break;
781                 default:
782                     break;
783             }
784             break;
785         default:
786             break;
787     }
788 }
789 #endif
790 
791 static void gatt_client_notify_can_send_query(gatt_client_t * gatt_client){
792 
793 #ifdef ENABLE_GATT_OVER_EATT
794     // if eatt is ready, notify all clients that can send a query
795     if (gatt_client->eatt_state == GATT_CLIENT_EATT_READY){
796         btstack_linked_list_iterator_t it;
797         btstack_linked_list_iterator_init(&it, &gatt_client->eatt_clients);
798         while (btstack_linked_list_iterator_has_next(&it)){
799             gatt_client_t * client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
800             if (client->state == P_READY){
801                 // call callback
802                 btstack_context_callback_registration_t * callback = (btstack_context_callback_registration_t *) btstack_linked_list_pop(&gatt_client->query_requests);
803                 if (callback == NULL) {
804                     return;
805                 }
806                 (*callback->callback)(callback->context);
807             }
808         }
809         return;
810     }
811 #endif
812 
813     while (gatt_client->state == P_READY){
814         bool query_sent = false;
815         UNUSED(query_sent);
816 
817 #ifdef ENABLE_GATT_CLIENT_SERVICE_CHANGED
818         uint8_t status = ERROR_CODE_SUCCESS;
819         gatt_client_service_t gatt_service;
820         gatt_client_characteristic_t characteristic;
821         switch (gatt_client->gatt_service_state){
822             case GATT_CLIENT_SERVICE_DISCOVER_W2_SEND:
823                 gatt_client->gatt_service_state = GATT_CLIENT_SERVICE_DISCOVER_W4_DONE;
824                 status = gatt_client_discover_primary_services_by_uuid16(&gatt_client_service_packet_handler,
825                                                                                          gatt_client->con_handle,
826                                                                                          ORG_BLUETOOTH_SERVICE_GENERIC_ATTRIBUTE);
827                 query_sent = true;
828                 break;
829             case GATT_CLIENT_SERVICE_DISCOVER_CHARACTERISTICS_W2_SEND:
830                 if (gatt_client->gatt_service_start_group_handle != 0){
831                     gatt_client->gatt_service_state = GATT_CLIENT_SERVICE_DISCOVER_CHARACTERISTICS_W4_DONE;
832                     gatt_service.start_group_handle = gatt_client->gatt_service_start_group_handle;
833                     gatt_service.end_group_handle   = gatt_client->gatt_service_end_group_handle;
834                     status = gatt_client_discover_characteristics_for_service(&gatt_client_service_packet_handler, gatt_client->con_handle, &gatt_service);
835                     query_sent = true;
836                     break;
837                 }
838 
839                 /* fall through */
840 
841             case GATT_CLIENT_SERVICE_SERVICE_CHANGED_WRITE_CCCD_W2_SEND:
842                 if (gatt_client->gatt_service_changed_value_handle != 0){
843                     gatt_client->gatt_service_state = GATT_CLIENT_SERVICE_SERVICE_CHANGED_WRITE_CCCD_W4_DONE;
844                     characteristic.value_handle = gatt_client->gatt_service_changed_value_handle;
845                     characteristic.end_handle   = gatt_client->gatt_service_changed_end_handle;
846                     // we assume good case. We cannot do much otherwise
847                     characteristic.properties = ATT_PROPERTY_INDICATE;
848                     status = gatt_client_write_client_characteristic_configuration(&gatt_client_service_packet_handler,
849                                                                                    gatt_client->con_handle, &characteristic,
850                                                                                    GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_INDICATION);
851                     query_sent = true;
852                     break;
853                 }
854 
855                 /* fall through */
856 
857             case GATT_CLIENT_SERVICE_DATABASE_HASH_READ_W2_SEND:
858                 if (gatt_client->gatt_service_database_hash_value_handle != 0){
859                     gatt_client->gatt_service_state = GATT_CLIENT_SERVICE_DATABASE_HASH_READ_W4_DONE;
860                     status = gatt_client_read_value_of_characteristics_by_uuid16(&gatt_client_service_packet_handler,
861                                                                                          gatt_client->con_handle,
862                                                                                          0x0001, 0xffff, ORG_BLUETOOTH_CHARACTERISTIC_DATABASE_HASH);
863                     query_sent = true;
864                     break;
865                 }
866 
867                 /* fall through */
868 
869             case GATT_CLIENT_SERVICE_DATABASE_HASH_WRITE_CCCD_W2_SEND:
870                 if (gatt_client->gatt_service_database_hash_value_handle != 0) {
871                     gatt_client->gatt_service_state = GATT_CLIENT_SERVICE_DATABASE_HASH_WRITE_CCCD_W4_DONE;
872                     characteristic.value_handle = gatt_client->gatt_service_database_hash_value_handle;
873                     characteristic.end_handle = gatt_client->gatt_service_database_hash_end_handle;
874                     // we assume good case. We cannot do much otherwise
875                     characteristic.properties = ATT_PROPERTY_INDICATE;
876                     status = gatt_client_write_client_characteristic_configuration(&gatt_client_service_packet_handler,
877                                                                                    gatt_client->con_handle,
878                                                                                    &characteristic,
879                                                                                    GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_INDICATION);
880                     query_sent = true;
881                     break;
882                 }
883 
884                 // DONE
885                 gatt_client->gatt_service_state = GATT_CLIENT_SERVICE_DONE;
886                 break;
887             default:
888                 break;
889         }
890         btstack_assert(status == ERROR_CODE_SUCCESS);
891         UNUSED(status);
892         if (query_sent){
893             continue;
894         }
895 #endif
896 
897 #ifdef ENABLE_GATT_OVER_EATT
898         query_sent = gatt_client_le_enhanced_handle_can_send_query(gatt_client);
899         if (query_sent){
900             continue;
901         }
902 #endif
903         btstack_context_callback_registration_t * callback = (btstack_context_callback_registration_t *) btstack_linked_list_pop(&gatt_client->query_requests);
904         if (callback == NULL) {
905             return;
906         }
907         (*callback->callback)(callback->context);
908     }
909 }
910 
911 // test if notification/indication should be delivered to application (BLESA)
912 static bool gatt_client_accept_server_message(gatt_client_t *gatt_client) {
913     // ignore messages until re-encryption is complete
914     if (gap_reconnect_security_setup_active(gatt_client->con_handle)) return false;
915 
916 	// after that ignore if bonded but not encrypted
917 	return !gap_bonded(gatt_client->con_handle) || (gap_encryption_key_size(gatt_client->con_handle) > 0);
918 }
919 
920 static void emit_event_new(btstack_packet_handler_t callback, uint8_t * packet, uint16_t size){
921     if (!callback) return;
922     hci_dump_btstack_event(packet, size);
923     (*callback)(HCI_EVENT_PACKET, 0, packet, size);
924 }
925 
926 static void emit_event_to_registered_listeners(hci_con_handle_t con_handle, uint16_t attribute_handle, uint8_t * packet, uint16_t size){
927     btstack_linked_list_iterator_t it;
928     btstack_linked_list_iterator_init(&it, &gatt_client_value_listeners);
929     while (btstack_linked_list_iterator_has_next(&it)){
930         gatt_client_notification_t * notification = (gatt_client_notification_t*) btstack_linked_list_iterator_next(&it);
931         if ((notification->con_handle       != GATT_CLIENT_ANY_CONNECTION)   && (notification->con_handle       != con_handle)) continue;
932         if ((notification->attribute_handle != GATT_CLIENT_ANY_VALUE_HANDLE) && (notification->attribute_handle != attribute_handle)) continue;
933         (*notification->callback)(HCI_EVENT_PACKET, 0, packet, size);
934     }
935 }
936 
937 static void emit_gatt_complete_event(gatt_client_t * gatt_client, uint8_t att_status){
938     // @format H122
939     uint8_t packet[9];
940     hci_event_builder_context_t context;
941     hci_event_builder_init(&context, packet, sizeof(packet), GATT_EVENT_QUERY_COMPLETE, 0);
942     hci_event_builder_add_con_handle(&context, gatt_client->con_handle);
943     hci_event_builder_add_16(&context, gatt_client->service_id);
944     hci_event_builder_add_16(&context, gatt_client->connection_id);
945     hci_event_builder_add_08(&context, att_status);
946     emit_event_new(gatt_client->callback, packet, hci_event_builder_get_length(&context));
947 }
948 
949 static void emit_gatt_service_query_result_event(gatt_client_t * gatt_client, uint16_t start_group_handle, uint16_t end_group_handle, const uint8_t * uuid128){
950     // @format H22X
951     uint8_t packet[28];
952     hci_event_builder_context_t context;
953     hci_event_builder_init(&context, packet, sizeof(packet), GATT_EVENT_SERVICE_QUERY_RESULT, 0);
954     hci_event_builder_add_con_handle(&context, gatt_client->con_handle);
955     hci_event_builder_add_16(&context, gatt_client->service_id);
956     hci_event_builder_add_16(&context, gatt_client->connection_id);
957     hci_event_builder_add_16(&context, start_group_handle);
958     hci_event_builder_add_16(&context, end_group_handle);
959     hci_event_builder_add_128(&context, uuid128);
960     emit_event_new(gatt_client->callback, packet, hci_event_builder_get_length(&context));
961 }
962 
963 static void emit_gatt_included_service_query_result_event(gatt_client_t * gatt_client, uint16_t include_handle, uint16_t start_group_handle, uint16_t end_group_handle, const uint8_t * uuid128){
964     // @format H22X
965     uint8_t packet[30];
966     hci_event_builder_context_t context;
967     hci_event_builder_init(&context, packet, sizeof(packet), GATT_EVENT_INCLUDED_SERVICE_QUERY_RESULT, 0);
968     hci_event_builder_add_con_handle(&context, gatt_client->con_handle);
969     hci_event_builder_add_16(&context, gatt_client->service_id);
970     hci_event_builder_add_16(&context, gatt_client->connection_id);
971     hci_event_builder_add_16(&context, include_handle);
972     hci_event_builder_add_16(&context, start_group_handle);
973     hci_event_builder_add_16(&context, end_group_handle);
974     hci_event_builder_add_128(&context, uuid128);
975     emit_event_new(gatt_client->callback, packet, hci_event_builder_get_length(&context));
976 }
977 
978 static void emit_gatt_characteristic_query_result_event(gatt_client_t * gatt_client, uint16_t start_handle, uint16_t value_handle, uint16_t end_handle,
979                                                         uint16_t properties, const uint8_t * uuid128){
980     // @format H22Y
981     uint8_t packet[32];
982     hci_event_builder_context_t context;
983     hci_event_builder_init(&context, packet, sizeof(packet), GATT_EVENT_CHARACTERISTIC_QUERY_RESULT, 0);
984     hci_event_builder_add_con_handle(&context, gatt_client->con_handle);
985     hci_event_builder_add_16(&context, gatt_client->service_id);
986     hci_event_builder_add_16(&context, gatt_client->connection_id);
987     hci_event_builder_add_16(&context, start_handle);
988     hci_event_builder_add_16(&context, value_handle);
989     hci_event_builder_add_16(&context, end_handle);
990     hci_event_builder_add_16(&context, properties);
991     hci_event_builder_add_128(&context, uuid128);
992     emit_event_new(gatt_client->callback, packet, hci_event_builder_get_length(&context));
993 }
994 
995 static void emit_gatt_all_characteristic_descriptors_result_event(
996         gatt_client_t * gatt_client, uint16_t descriptor_handle, const uint8_t * uuid128){
997     // @format H22Z
998     uint8_t packet[26];
999     hci_event_builder_context_t context;
1000     hci_event_builder_init(&context, packet, sizeof(packet), GATT_EVENT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT, 0);
1001     hci_event_builder_add_con_handle(&context, gatt_client->con_handle);
1002     hci_event_builder_add_16(&context, gatt_client->service_id);
1003     hci_event_builder_add_16(&context, gatt_client->connection_id);
1004     hci_event_builder_add_16(&context, descriptor_handle);
1005     hci_event_builder_add_128(&context, uuid128);
1006     emit_event_new(gatt_client->callback, packet, hci_event_builder_get_length(&context));
1007 }
1008 
1009 static void emit_gatt_mtu_exchanged_result_event(gatt_client_t * gatt_client, uint16_t new_mtu){
1010     // @format H2
1011     uint8_t packet[6];
1012     packet[0] = GATT_EVENT_MTU;
1013     packet[1] = sizeof(packet) - 2u;
1014     little_endian_store_16(packet, 2, gatt_client->con_handle);
1015     little_endian_store_16(packet, 4, new_mtu);
1016     att_dispatch_client_mtu_exchanged(gatt_client->con_handle, new_mtu);
1017     emit_event_new(gatt_client->callback, packet, sizeof(packet));
1018 }
1019 
1020 // helper
1021 static void gatt_client_handle_transaction_complete(gatt_client_t *gatt_client, uint8_t att_status) {
1022     gatt_client->state = P_READY;
1023     gatt_client_timeout_stop(gatt_client);
1024     emit_gatt_complete_event(gatt_client, att_status);
1025     gatt_client_notify_can_send_query(gatt_client);
1026 }
1027 
1028 // @return packet pointer
1029 // @note assume that value is part of an l2cap buffer - overwrite HCI + L2CAP packet headers + 4 pre_buffer bytes
1030 #define CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE 12
1031 static uint8_t *
1032 setup_characteristic_value_packet(const gatt_client_t *gatt_client, uint8_t type, uint16_t attribute_handle,
1033                                   uint8_t *value, uint16_t length) {
1034 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1035     // copy value into test packet for testing
1036     static uint8_t packet[1000];
1037     memcpy(&packet[CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE], value, length);
1038 #else
1039     // before the value inside the ATT PDU
1040     uint8_t * packet = value - CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE;
1041 #endif
1042     packet[0] = type;
1043     packet[1] = CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE - 2 + length;
1044     little_endian_store_16(packet, 2, gatt_client->con_handle);
1045     little_endian_store_16(packet, 4, gatt_client->service_id);
1046     little_endian_store_16(packet, 6, gatt_client->connection_id);
1047     little_endian_store_16(packet, 8, attribute_handle);
1048     little_endian_store_16(packet, 10, length);
1049     return packet;
1050 }
1051 
1052 // @return packet pointer
1053 // @note assume that value is part of an l2cap buffer - overwrite HCI + L2CAP packet headers + 6 pre_buffer bytes
1054 #define LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE 14
1055 
1056 // L2CAP Header (4) + ACL Header (4) => 8 bytes
1057 #if !defined(HCI_INCOMING_PRE_BUFFER_SIZE) || ((HCI_INCOMING_PRE_BUFFER_SIZE < LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE - 8))
1058 #error "Long Characteristic reads requires HCI_INCOMING_PRE_BUFFER_SIZE >= 2"
1059 #endif
1060 
1061 static uint8_t *
1062 setup_long_characteristic_value_packet(const gatt_client_t *gatt_client, uint8_t type, uint16_t attribute_handle,
1063                                        uint16_t offset, uint8_t *value, uint16_t length) {
1064 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1065     // avoid using pre ATT headers.
1066     // copy value into test packet for testing
1067     static uint8_t packet[1000];
1068     memcpy(&packet[LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE], value, length);
1069 #else
1070     // before the value inside the ATT PDU
1071     uint8_t * packet = value - LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE;
1072 #endif
1073     packet[0] = type;
1074     packet[1] = LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE - 2 + length;
1075     little_endian_store_16(packet, 2, gatt_client->con_handle);
1076     little_endian_store_16(packet, 4, gatt_client->service_id);
1077     little_endian_store_16(packet, 6, gatt_client->connection_id);
1078     little_endian_store_16(packet, 8, attribute_handle);
1079     little_endian_store_16(packet, 10, offset);
1080     little_endian_store_16(packet, 12, length);
1081     return packet;
1082 }
1083 
1084 #if (LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE > CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE)
1085 #define REPORT_PREBUFFER_HEADER LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE
1086 #else
1087 #define REPORT_PREBUFFER_HEADER CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE
1088 #endif
1089 
1090 ///
1091 static void report_gatt_services(gatt_client_t * gatt_client, uint8_t * packet, uint16_t size){
1092     if (size < 2) return;
1093     uint8_t attr_length = packet[1];
1094     uint8_t uuid_length = attr_length - 4u;
1095 
1096     int i;
1097     for (i = 2; (i+attr_length) <= size; i += attr_length){
1098         uint16_t start_group_handle = little_endian_read_16(packet,i);
1099         uint16_t end_group_handle   = little_endian_read_16(packet,i+2);
1100         uint8_t  uuid128[16];
1101         uint16_t uuid16 = 0;
1102 
1103         if (uuid_length == 2u){
1104             uuid16 = little_endian_read_16(packet, i+4);
1105             uuid_add_bluetooth_prefix((uint8_t*) &uuid128, uuid16);
1106         } else if (uuid_length == 16u) {
1107             reverse_128(&packet[i+4], uuid128);
1108         } else {
1109             return;
1110         }
1111         emit_gatt_service_query_result_event(gatt_client, start_group_handle, end_group_handle, uuid128);
1112     }
1113 }
1114 
1115 static void report_gatt_characteristic_start_found(gatt_client_t * gatt_client, uint16_t start_handle, uint8_t properties, uint16_t value_handle, uint8_t * uuid, uint16_t uuid_length){
1116     uint8_t uuid128[16];
1117     uint16_t uuid16 = 0;
1118     if (uuid_length == 2u){
1119         uuid16 = little_endian_read_16(uuid, 0);
1120         uuid_add_bluetooth_prefix((uint8_t*) uuid128, uuid16);
1121     } else if (uuid_length == 16u){
1122         reverse_128(uuid, uuid128);
1123     } else {
1124         return;
1125     }
1126 
1127     if (gatt_client->filter_with_uuid && (memcmp(gatt_client->uuid128, uuid128, 16) != 0)) return;
1128 
1129     gatt_client->characteristic_properties = properties;
1130     gatt_client->characteristic_start_handle = start_handle;
1131     gatt_client->attribute_handle = value_handle;
1132 
1133     if (gatt_client->filter_with_uuid) return;
1134 
1135     gatt_client->uuid16 = uuid16;
1136     (void)memcpy(gatt_client->uuid128, uuid128, 16);
1137 }
1138 
1139 static void report_gatt_characteristic_end_found(gatt_client_t * gatt_client, uint16_t end_handle){
1140     // TODO: stop searching if filter and uuid found
1141 
1142     if (!gatt_client->characteristic_start_handle) return;
1143 
1144     emit_gatt_characteristic_query_result_event(gatt_client, gatt_client->characteristic_start_handle, gatt_client->attribute_handle,
1145                                                 end_handle, gatt_client->characteristic_properties, gatt_client->uuid128);
1146 
1147     gatt_client->characteristic_start_handle = 0;
1148 }
1149 
1150 
1151 static void report_gatt_characteristics(gatt_client_t * gatt_client, uint8_t * packet, uint16_t size){
1152     if (size < 2u) return;
1153     uint8_t attr_length = packet[1];
1154     if ((attr_length != 7u) && (attr_length != 21u)) return;
1155     uint8_t uuid_length = attr_length - 5u;
1156     int i;
1157     for (i = 2u; (i + attr_length) <= size; i += attr_length){
1158         uint16_t start_handle = little_endian_read_16(packet, i);
1159         uint8_t  properties = packet[i+2];
1160         uint16_t value_handle = little_endian_read_16(packet, i+3);
1161         report_gatt_characteristic_end_found(gatt_client, start_handle - 1u);
1162         report_gatt_characteristic_start_found(gatt_client, start_handle, properties, value_handle, &packet[i + 5],
1163                                                uuid_length);
1164     }
1165 }
1166 
1167 static void report_gatt_included_service_uuid16(gatt_client_t * gatt_client, uint16_t include_handle, uint16_t uuid16){
1168     uint8_t normalized_uuid128[16];
1169     uuid_add_bluetooth_prefix(normalized_uuid128, uuid16);
1170     emit_gatt_included_service_query_result_event(gatt_client, include_handle, gatt_client->query_start_handle,
1171                                                   gatt_client->query_end_handle, normalized_uuid128);
1172 }
1173 
1174 static void report_gatt_included_service_uuid128(gatt_client_t * gatt_client, uint16_t include_handle, const uint8_t * uuid128){
1175     emit_gatt_included_service_query_result_event(gatt_client, include_handle, gatt_client->query_start_handle,
1176                                                   gatt_client->query_end_handle, uuid128);
1177 }
1178 
1179 // @note assume that value is part of an l2cap buffer - overwrite parts of the HCI/L2CAP/ATT packet (4/4/3) bytes
1180 static void report_gatt_notification(gatt_client_t *gatt_client, uint16_t value_handle, uint8_t *value, int length) {
1181 	if (!gatt_client_accept_server_message(gatt_client)) return;
1182     uint8_t * packet = setup_characteristic_value_packet(gatt_client, GATT_EVENT_NOTIFICATION, value_handle,
1183                                                          value, length);
1184     emit_event_to_registered_listeners(gatt_client->con_handle, value_handle, packet, CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE + length);
1185 }
1186 
1187 // @note assume that value is part of an l2cap buffer - overwrite parts of the HCI/L2CAP/ATT packet (4/4/3) bytes
1188 static void report_gatt_indication(gatt_client_t *gatt_client, uint16_t value_handle, uint8_t *value, int length) {
1189 	if (!gatt_client_accept_server_message(gatt_client)) return;
1190 #ifdef ENABLE_GATT_CLIENT_SERVICE_CHANGED
1191     // Directly Handle GATT Service Changed and Database Hash indications
1192     if (value_handle == gatt_client->gatt_service_database_hash_value_handle){
1193         gatt_client_service_emit_database_hash(gatt_client, value, length);
1194     }
1195     if (value_handle == gatt_client->gatt_service_changed_value_handle){
1196         gatt_client_service_emit_service_changed(gatt_client, value, length);
1197     }
1198 #endif
1199     uint8_t * packet = setup_characteristic_value_packet(gatt_client, GATT_EVENT_INDICATION, value_handle,
1200                                                          value, length);
1201     emit_event_to_registered_listeners(gatt_client->con_handle, value_handle, packet, CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE + length);
1202 }
1203 
1204 // @note assume that value is part of an l2cap buffer - overwrite parts of the HCI/L2CAP/ATT packet (4/4/3) bytes
1205 static void report_gatt_characteristic_value(gatt_client_t * gatt_client, uint16_t attribute_handle, uint8_t * value, uint16_t length){
1206     uint8_t * packet = setup_characteristic_value_packet(
1207             gatt_client, GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT, attribute_handle, value, length);
1208     emit_event_new(gatt_client->callback, packet, CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE + length);
1209 }
1210 
1211 // @note assume that value is part of an l2cap buffer - overwrite parts of the HCI/L2CAP/ATT packet (4/4/3) bytes
1212 static void report_gatt_long_characteristic_value_blob(gatt_client_t * gatt_client, uint16_t attribute_handle, uint8_t * blob, uint16_t blob_length, int value_offset){
1213     uint8_t * packet = setup_long_characteristic_value_packet(gatt_client,
1214                                                               GATT_EVENT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT,
1215                                                               attribute_handle, value_offset,
1216                                                               blob, blob_length);
1217     emit_event_new(gatt_client->callback, packet, blob_length + LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE);
1218 }
1219 
1220 static void report_gatt_characteristic_descriptor(gatt_client_t * gatt_client, uint16_t descriptor_handle, uint8_t *value, uint16_t value_length, uint16_t value_offset){
1221     UNUSED(value_offset);
1222     uint8_t * packet = setup_characteristic_value_packet(gatt_client, GATT_EVENT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT,
1223                                                          descriptor_handle, value,
1224                                                          value_length);
1225     emit_event_new(gatt_client->callback, packet, value_length + 8u);
1226 }
1227 
1228 static void report_gatt_long_characteristic_descriptor(gatt_client_t * gatt_client, uint16_t descriptor_handle, uint8_t *blob, uint16_t blob_length, uint16_t value_offset){
1229     uint8_t * packet = setup_long_characteristic_value_packet(gatt_client,
1230                                                               GATT_EVENT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT,
1231                                                               descriptor_handle, value_offset,
1232                                                               blob, blob_length);
1233     emit_event_new(gatt_client->callback, packet, blob_length + LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE);
1234 }
1235 
1236 static void report_gatt_all_characteristic_descriptors(gatt_client_t * gatt_client, uint8_t * packet, uint16_t size, uint16_t pair_size){
1237     int i;
1238     for (i = 0u; (i + pair_size) <= size; i += pair_size){
1239         uint16_t descriptor_handle = little_endian_read_16(packet,i);
1240         uint8_t uuid128[16];
1241         uint16_t uuid16 = 0;
1242         if (pair_size == 4u){
1243             uuid16 = little_endian_read_16(packet,i+2);
1244             uuid_add_bluetooth_prefix(uuid128, uuid16);
1245         } else {
1246             reverse_128(&packet[i+2], uuid128);
1247         }
1248         emit_gatt_all_characteristic_descriptors_result_event(gatt_client, descriptor_handle, uuid128);
1249     }
1250 
1251 }
1252 
1253 static bool is_query_done(gatt_client_t * gatt_client, uint16_t last_result_handle){
1254     return last_result_handle >= gatt_client->end_group_handle;
1255 }
1256 
1257 static void trigger_next_query(gatt_client_t * gatt_client, uint16_t last_result_handle, gatt_client_state_t next_query_state){
1258     if (is_query_done(gatt_client, last_result_handle)){
1259         gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1260         return;
1261     }
1262     // next
1263     gatt_client->start_group_handle = last_result_handle + 1u;
1264     gatt_client->state = next_query_state;
1265 }
1266 
1267 static void trigger_next_included_service_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1268     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_INCLUDED_SERVICE_QUERY);
1269 }
1270 
1271 static void trigger_next_service_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1272     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_SERVICE_QUERY);
1273 }
1274 
1275 static void trigger_next_service_by_uuid_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1276     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_SERVICE_WITH_UUID_QUERY);
1277 }
1278 
1279 static void trigger_next_characteristic_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1280     if (is_query_done(gatt_client, last_result_handle)){
1281         // report last characteristic
1282         report_gatt_characteristic_end_found(gatt_client, gatt_client->end_group_handle);
1283     }
1284     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY);
1285 }
1286 
1287 static void trigger_next_characteristic_descriptor_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1288     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY);
1289 }
1290 
1291 static void trigger_next_read_by_type_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1292     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_READ_BY_TYPE_REQUEST);
1293 }
1294 
1295 static void trigger_next_prepare_write_query(gatt_client_t * gatt_client, gatt_client_state_t next_query_state, gatt_client_state_t done_state){
1296     gatt_client->attribute_offset += write_blob_length(gatt_client);
1297     uint16_t next_blob_length =  write_blob_length(gatt_client);
1298 
1299     if (next_blob_length == 0u){
1300         gatt_client->state = done_state;
1301         return;
1302     }
1303     gatt_client->state = next_query_state;
1304 }
1305 
1306 static void trigger_next_blob_query(gatt_client_t * gatt_client, gatt_client_state_t next_query_state, uint16_t received_blob_length){
1307 
1308     uint16_t max_blob_length = gatt_client->mtu - 1u;
1309     if (received_blob_length < max_blob_length){
1310         gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1311         return;
1312     }
1313 
1314     gatt_client->attribute_offset += received_blob_length;
1315     gatt_client->state = next_query_state;
1316 }
1317 
1318 void gatt_client_listen_for_characteristic_value_updates(gatt_client_notification_t * notification, btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
1319     notification->callback = callback;
1320     notification->con_handle = con_handle;
1321     if (characteristic == NULL){
1322         notification->attribute_handle = GATT_CLIENT_ANY_VALUE_HANDLE;
1323     } else {
1324         notification->attribute_handle = characteristic->value_handle;
1325     }
1326     btstack_linked_list_add(&gatt_client_value_listeners, (btstack_linked_item_t*) notification);
1327 }
1328 
1329 void gatt_client_stop_listening_for_characteristic_value_updates(gatt_client_notification_t * notification){
1330     btstack_linked_list_remove(&gatt_client_value_listeners, (btstack_linked_item_t*) notification);
1331 }
1332 
1333 static bool is_value_valid(gatt_client_t *gatt_client, uint8_t *packet, uint16_t size){
1334     uint16_t attribute_handle = little_endian_read_16(packet, 1);
1335     uint16_t value_offset = little_endian_read_16(packet, 3);
1336 
1337     if (gatt_client->attribute_handle != attribute_handle) return false;
1338     if (gatt_client->attribute_offset != value_offset) return false;
1339     return memcmp(&gatt_client->attribute_value[gatt_client->attribute_offset], &packet[5], size - 5u) == 0u;
1340 }
1341 
1342 #ifdef ENABLE_LE_SIGNED_WRITE
1343 static void gatt_client_run_for_client_start_signed_write(gatt_client_t *gatt_client) {
1344     sm_key_t csrk;
1345     le_device_db_local_csrk_get(gatt_client->le_device_index, csrk);
1346     uint32_t sign_counter = le_device_db_local_counter_get(gatt_client->le_device_index);
1347     gatt_client->state = P_W4_CMAC_RESULT;
1348     sm_cmac_signed_write_start(csrk, ATT_SIGNED_WRITE_COMMAND, gatt_client->attribute_handle, gatt_client->attribute_length, gatt_client->attribute_value, sign_counter, att_signed_write_handle_cmac_result);
1349 }
1350 #endif
1351 
1352 // returns true if packet was sent
1353 static bool gatt_client_run_for_gatt_client(gatt_client_t * gatt_client){
1354 
1355     // wait until re-encryption is complete
1356     if (gap_reconnect_security_setup_active(gatt_client->con_handle)) return false;
1357 
1358     // wait until re-encryption is complete
1359     if (gatt_client->reencryption_active) return false;
1360 
1361     // wait until pairing complete (either reactive authentication or due to required security level)
1362     if (gatt_client->wait_for_authentication_complete) return false;
1363 
1364     bool client_request_pending = gatt_client->state != P_READY;
1365 
1366     // verify security level for Mandatory Authentication over LE
1367     bool check_security;
1368     switch (gatt_client->bearer_type){
1369         case ATT_BEARER_UNENHANCED_LE:
1370             check_security = true;
1371             break;
1372         default:
1373             check_security = false;
1374             break;
1375     }
1376     if (client_request_pending && (gatt_client_required_security_level > gatt_client->security_level) && check_security){
1377         log_info("Trigger pairing, current security level %u, required %u\n", gatt_client->security_level, gatt_client_required_security_level);
1378         gatt_client->wait_for_authentication_complete = true;
1379         // set att error code for pairing failure based on required level
1380         switch (gatt_client_required_security_level){
1381             case LEVEL_4:
1382             case LEVEL_3:
1383                 gatt_client->pending_error_code = ATT_ERROR_INSUFFICIENT_AUTHENTICATION;
1384                 break;
1385             default:
1386                 gatt_client->pending_error_code = ATT_ERROR_INSUFFICIENT_ENCRYPTION;
1387                 break;
1388         }
1389         sm_request_pairing(gatt_client->con_handle);
1390         // sm probably just sent a pdu
1391         return true;
1392     }
1393 
1394     switch (gatt_client->mtu_state) {
1395         case SEND_MTU_EXCHANGE:
1396             gatt_client->mtu_state = SENT_MTU_EXCHANGE;
1397             att_exchange_mtu_request(gatt_client);
1398             return true;
1399         case SENT_MTU_EXCHANGE:
1400             return false;
1401         default:
1402             break;
1403     }
1404 
1405     if (gatt_client->send_confirmation){
1406         gatt_client->send_confirmation = false;
1407         att_confirmation(gatt_client);
1408         return true;
1409     }
1410 
1411     // check MTU for writes
1412     switch (gatt_client->state){
1413         case P_W2_SEND_WRITE_CHARACTERISTIC_VALUE:
1414         case P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR:
1415             if (gatt_client->attribute_length <= (gatt_client->mtu - 3u)) break;
1416             log_error("gatt_client_run: value len %u > MTU %u - 3\n", gatt_client->attribute_length,gatt_client->mtu);
1417             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH);
1418             return false;
1419         default:
1420             break;
1421     }
1422 
1423     bool packet_sent = true;
1424     bool done = true;
1425     switch (gatt_client->state){
1426         case P_W2_SEND_SERVICE_QUERY:
1427             gatt_client->state = P_W4_SERVICE_QUERY_RESULT;
1428             send_gatt_services_request(gatt_client);
1429             break;
1430 
1431         case P_W2_SEND_SERVICE_WITH_UUID_QUERY:
1432             gatt_client->state = P_W4_SERVICE_WITH_UUID_RESULT;
1433             send_gatt_services_by_uuid_request(gatt_client);
1434             break;
1435 
1436         case P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY:
1437             gatt_client->state = P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT;
1438             send_gatt_characteristic_request(gatt_client);
1439             break;
1440 
1441         case P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY:
1442             gatt_client->state = P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT;
1443             send_gatt_characteristic_request(gatt_client);
1444             break;
1445 
1446         case P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY:
1447             gatt_client->state = P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT;
1448             send_gatt_characteristic_descriptor_request(gatt_client);
1449             break;
1450 
1451         case P_W2_SEND_INCLUDED_SERVICE_QUERY:
1452             gatt_client->state = P_W4_INCLUDED_SERVICE_QUERY_RESULT;
1453             send_gatt_included_service_request(gatt_client);
1454             break;
1455 
1456         case P_W2_SEND_INCLUDED_SERVICE_WITH_UUID_QUERY:
1457             gatt_client->state = P_W4_INCLUDED_SERVICE_UUID_WITH_QUERY_RESULT;
1458             send_gatt_included_service_uuid_request(gatt_client);
1459             break;
1460 
1461         case P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY:
1462             gatt_client->state = P_W4_READ_CHARACTERISTIC_VALUE_RESULT;
1463             send_gatt_read_characteristic_value_request(gatt_client);
1464             break;
1465 
1466         case P_W2_SEND_READ_BLOB_QUERY:
1467             gatt_client->state = P_W4_READ_BLOB_RESULT;
1468             send_gatt_read_blob_request(gatt_client);
1469             break;
1470 
1471         case P_W2_SEND_READ_BY_TYPE_REQUEST:
1472             gatt_client->state = P_W4_READ_BY_TYPE_RESPONSE;
1473             send_gatt_read_by_type_request(gatt_client);
1474             break;
1475 
1476         case P_W2_SEND_READ_MULTIPLE_REQUEST:
1477             gatt_client->state = P_W4_READ_MULTIPLE_RESPONSE;
1478             send_gatt_read_multiple_request(gatt_client);
1479             break;
1480 
1481 #ifdef ENABLE_GATT_OVER_EATT
1482         case P_W2_SEND_READ_MULTIPLE_VARIABLE_REQUEST:
1483             gatt_client->state = P_W4_READ_MULTIPLE_VARIABLE_RESPONSE;
1484             send_gatt_read_multiple_variable_request(gatt_client);
1485             break;
1486 #endif
1487 
1488         case P_W2_SEND_WRITE_CHARACTERISTIC_VALUE:
1489             gatt_client->state = P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT;
1490             send_gatt_write_attribute_value_request(gatt_client);
1491             break;
1492 
1493         case P_W2_PREPARE_WRITE:
1494             gatt_client->state = P_W4_PREPARE_WRITE_RESULT;
1495             send_gatt_prepare_write_request(gatt_client);
1496             break;
1497 
1498         case P_W2_PREPARE_WRITE_SINGLE:
1499             gatt_client->state = P_W4_PREPARE_WRITE_SINGLE_RESULT;
1500             send_gatt_prepare_write_request(gatt_client);
1501             break;
1502 
1503         case P_W2_PREPARE_RELIABLE_WRITE:
1504             gatt_client->state = P_W4_PREPARE_RELIABLE_WRITE_RESULT;
1505             send_gatt_prepare_write_request(gatt_client);
1506             break;
1507 
1508         case P_W2_EXECUTE_PREPARED_WRITE:
1509             gatt_client->state = P_W4_EXECUTE_PREPARED_WRITE_RESULT;
1510             send_gatt_execute_write_request(gatt_client);
1511             break;
1512 
1513         case P_W2_CANCEL_PREPARED_WRITE:
1514             gatt_client->state = P_W4_CANCEL_PREPARED_WRITE_RESULT;
1515             send_gatt_cancel_prepared_write_request(gatt_client);
1516             break;
1517 
1518         case P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH:
1519             gatt_client->state = P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT;
1520             send_gatt_cancel_prepared_write_request(gatt_client);
1521             break;
1522 
1523 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
1524         case P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY:
1525             // use Find Information
1526             gatt_client->gatt_client_state = P_W4_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT;
1527             send_gatt_characteristic_descriptor_request(gatt_client);
1528 #else
1529         case P_W2_SEND_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY:
1530             // Use Read By Type
1531             gatt_client->state = P_W4_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT;
1532             send_gatt_read_client_characteristic_configuration_request(gatt_client);
1533 #endif
1534             break;
1535 
1536         case P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY:
1537             gatt_client->state = P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT;
1538             send_gatt_read_characteristic_descriptor_request(gatt_client);
1539             break;
1540 
1541         case P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY:
1542             gatt_client->state = P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT;
1543             send_gatt_read_blob_request(gatt_client);
1544             break;
1545 
1546         case P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR:
1547             gatt_client->state = P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT;
1548             send_gatt_write_attribute_value_request(gatt_client);
1549             break;
1550 
1551         case P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION:
1552             gatt_client->state = P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT;
1553             send_gatt_write_client_characteristic_configuration_request(gatt_client);
1554             break;
1555 
1556         case P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR:
1557             gatt_client->state = P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT;
1558             send_gatt_prepare_write_request(gatt_client);
1559             break;
1560 
1561         case P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR:
1562             gatt_client->state = P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT;
1563             send_gatt_execute_write_request(gatt_client);
1564             break;
1565 
1566 #ifdef ENABLE_LE_SIGNED_WRITE
1567         case P_W4_IDENTITY_RESOLVING:
1568             log_info("P_W4_IDENTITY_RESOLVING - state %x", sm_identity_resolving_state(gatt_client->con_handle));
1569             switch (sm_identity_resolving_state(gatt_client->con_handle)){
1570                 case IRK_LOOKUP_SUCCEEDED:
1571                     gatt_client->le_device_index = sm_le_device_index(gatt_client->con_handle);
1572                     gatt_client->state = P_W4_CMAC_READY;
1573                     if (sm_cmac_ready()){
1574                         gatt_client_run_for_client_start_signed_write(gatt_client);
1575                     }
1576                     break;
1577                 case IRK_LOOKUP_FAILED:
1578                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_BONDING_INFORMATION_MISSING);
1579                     break;
1580                 default:
1581                     break;
1582             }
1583             packet_sent = false;
1584             break;
1585 
1586         case P_W4_CMAC_READY:
1587             if (sm_cmac_ready()){
1588                 gatt_client_run_for_client_start_signed_write(gatt_client);
1589             }
1590             packet_sent = false;
1591             break;
1592 
1593         case P_W2_SEND_SIGNED_WRITE: {
1594             gatt_client->state = P_W4_SEND_SIGNED_WRITE_DONE;
1595             // bump local signing counter
1596             uint32_t sign_counter = le_device_db_local_counter_get(gatt_client->le_device_index);
1597             le_device_db_local_counter_set(gatt_client->le_device_index, sign_counter + 1);
1598             // send signed write command
1599             send_gatt_signed_write_request(gatt_client, sign_counter);
1600             // finally, notifiy client that write is complete
1601             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1602             break;
1603         }
1604 #endif
1605         default:
1606             done = false;
1607             break;
1608     }
1609 
1610     if (done){
1611         return packet_sent;
1612     }
1613 
1614     // write without response callback
1615     btstack_context_callback_registration_t * callback =
1616             (btstack_context_callback_registration_t *) btstack_linked_list_pop(&gatt_client->write_without_response_requests);
1617     if (callback != NULL){
1618         (*callback->callback)(callback->context);
1619         return true;
1620     }
1621 
1622     // requested can send now old
1623     if (gatt_client->write_without_response_callback != NULL){
1624         btstack_packet_handler_t packet_handler = gatt_client->write_without_response_callback;
1625         gatt_client->write_without_response_callback = NULL;
1626         uint8_t event[4];
1627         event[0] = GATT_EVENT_CAN_WRITE_WITHOUT_RESPONSE;
1628         event[1] = sizeof(event) - 2u;
1629         little_endian_store_16(event, 2, gatt_client->con_handle);
1630         packet_handler(HCI_EVENT_PACKET, gatt_client->con_handle, event, sizeof(event));
1631         return true; // to trigger requeueing (even if higher layer didn't sent)
1632     }
1633 
1634     return false;
1635 }
1636 
1637 static void gatt_client_run(void){
1638     btstack_linked_item_t *it;
1639     bool packet_sent;
1640 #ifdef ENABLE_GATT_OVER_EATT
1641     btstack_linked_list_iterator_t it_eatt;
1642 #endif
1643     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
1644         gatt_client_t * gatt_client = (gatt_client_t *) it;
1645         switch (gatt_client->bearer_type){
1646             case ATT_BEARER_UNENHANCED_LE:
1647 #ifdef ENABLE_GATT_OVER_EATT
1648                 btstack_linked_list_iterator_init(&it_eatt, &gatt_client->eatt_clients);
1649                 while (btstack_linked_list_iterator_has_next(&it_eatt)) {
1650                     gatt_client_t * eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it_eatt);
1651                     if (eatt_client->state != P_READY){
1652                         if (att_dispatch_client_can_send_now(gatt_client->con_handle)){
1653                             gatt_client_run_for_gatt_client(eatt_client);
1654                         }
1655                     }
1656                 }
1657 #endif
1658                 if (!att_dispatch_client_can_send_now(gatt_client->con_handle)) {
1659                     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
1660                     return;
1661                 }
1662                 packet_sent = gatt_client_run_for_gatt_client(gatt_client);
1663                 if (packet_sent){
1664                     // request new permission
1665                     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
1666                     // requeue client for fairness and exit
1667                     // note: iterator has become invalid
1668                     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1669                     btstack_linked_list_add_tail(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1670                     return;
1671                 }
1672                 break;
1673 #ifdef ENABLE_GATT_OVER_CLASSIC
1674             case ATT_BEARER_UNENHANCED_CLASSIC:
1675                 if (gatt_client->con_handle == HCI_CON_HANDLE_INVALID) {
1676                     continue;
1677                 }
1678 
1679                 // handle GATT over BR/EDR
1680                 if (att_dispatch_client_can_send_now(gatt_client->con_handle) == false) {
1681                     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
1682                     return;
1683                 }
1684                 packet_sent = gatt_client_run_for_gatt_client(gatt_client);
1685                 if (packet_sent){
1686                     // request new permission
1687                     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
1688                     // requeue client for fairness and exit
1689                     // note: iterator has become invalid
1690                     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1691                     btstack_linked_list_add_tail(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1692                     return;
1693                 }
1694                 break;
1695 #endif
1696             default:
1697                 btstack_unreachable();
1698                 break;
1699         }
1700 
1701 
1702     }
1703 }
1704 
1705 // emit complete event, used to avoid emitting event from API call
1706 static void gatt_client_emit_events(void * context){
1707     UNUSED(context);
1708     btstack_linked_item_t *it;
1709     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next) {
1710         gatt_client_t *gatt_client = (gatt_client_t *) it;
1711         if (gatt_client->state == P_W2_EMIT_QUERY_COMPLETE_EVENT){
1712             gatt_client->state = P_READY;
1713             emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1714         }
1715     }
1716 }
1717 
1718 static void gatt_client_report_error_if_pending(gatt_client_t *gatt_client, uint8_t att_error_code) {
1719     if (is_ready(gatt_client)) return;
1720     gatt_client_handle_transaction_complete(gatt_client, att_error_code);
1721 }
1722 
1723 static void gatt_client_handle_reencryption_complete(const uint8_t * packet){
1724     hci_con_handle_t con_handle = sm_event_reencryption_complete_get_handle(packet);
1725     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
1726     if (gatt_client == NULL) return;
1727 
1728     // update security level
1729     gatt_client->security_level = gatt_client_le_security_level_for_connection(con_handle);
1730 
1731     gatt_client->reencryption_result = sm_event_reencryption_complete_get_status(packet);
1732     gatt_client->reencryption_active = false;
1733     gatt_client->wait_for_authentication_complete = false;
1734 
1735     if (gatt_client->state == P_READY) return;
1736 
1737     switch (sm_event_reencryption_complete_get_status(packet)){
1738         case ERROR_CODE_SUCCESS:
1739             log_info("re-encryption success, retry operation");
1740             break;
1741         case ERROR_CODE_AUTHENTICATION_FAILURE:
1742         case ERROR_CODE_PIN_OR_KEY_MISSING:
1743 #if defined(ENABLE_GATT_CLIENT_PAIRING) && !defined(ENABLE_LE_PROACTIVE_AUTHENTICATION)
1744             if (gatt_client_required_security_level == LEVEL_0) {
1745                 // re-encryption failed for reactive authentication with pairing and we have a pending client request
1746                 // => try to resolve it by deleting bonding information if we started pairing before
1747                 // delete bonding information
1748                 int le_device_db_index = sm_le_device_index(gatt_client->con_handle);
1749                 btstack_assert(le_device_db_index >= 0);
1750                 log_info("reactive auth with pairing: delete bonding and start pairing");
1751 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
1752                 hci_remove_le_device_db_entry_from_resolving_list((uint16_t) le_device_db_index);
1753 #endif
1754                 le_device_db_remove(le_device_db_index);
1755                 // trigger pairing again
1756                 sm_request_pairing(gatt_client->con_handle);
1757                 break;
1758             }
1759 #endif
1760             // report bonding information missing
1761             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_BONDING_INFORMATION_MISSING);
1762             break;
1763         default:
1764             // report bonding information missing
1765             gatt_client_handle_transaction_complete(gatt_client, gatt_client->pending_error_code);
1766             break;
1767     }
1768 }
1769 
1770 static void gatt_client_handle_disconnection_complete(const uint8_t * packet){
1771     log_info("GATT Client: HCI_EVENT_DISCONNECTION_COMPLETE");
1772     hci_con_handle_t con_handle = little_endian_read_16(packet,3);
1773     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
1774     if (gatt_client == NULL) return;
1775 
1776     gatt_client_report_error_if_pending(gatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
1777     gatt_client_timeout_stop(gatt_client);
1778     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1779     btstack_memory_gatt_client_free(gatt_client);
1780 }
1781 
1782 static void gatt_client_event_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1783     UNUSED(channel);    // ok: handling own l2cap events
1784     UNUSED(size);       // ok: there is no channel
1785 
1786     if (packet_type != HCI_EVENT_PACKET) return;
1787 
1788     hci_con_handle_t con_handle;
1789     gatt_client_t * gatt_client;
1790     switch (hci_event_packet_get_type(packet)) {
1791         case HCI_EVENT_DISCONNECTION_COMPLETE:
1792             gatt_client_handle_disconnection_complete(packet);
1793             break;
1794 
1795         // Pairing complete (with/without bonding=storing of pairing information)
1796         case SM_EVENT_PAIRING_COMPLETE:
1797             con_handle = sm_event_pairing_complete_get_handle(packet);
1798             gatt_client = gatt_client_get_context_for_handle(con_handle);
1799             if (gatt_client == NULL) break;
1800 
1801             // update security level
1802             gatt_client->security_level = gatt_client_le_security_level_for_connection(con_handle);
1803 
1804             if (gatt_client->wait_for_authentication_complete){
1805                 gatt_client->wait_for_authentication_complete = false;
1806                 if (sm_event_pairing_complete_get_status(packet) != ERROR_CODE_SUCCESS){
1807                     log_info("pairing failed, report previous error 0x%x", gatt_client->pending_error_code);
1808                     gatt_client_report_error_if_pending(gatt_client, gatt_client->pending_error_code);
1809                 } else {
1810                     log_info("pairing success, retry operation");
1811                 }
1812             }
1813             break;
1814 
1815 #ifdef ENABLE_LE_SIGNED_WRITE
1816         // Identity Resolving completed (no code, gatt_client_run will continue)
1817         case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED:
1818         case SM_EVENT_IDENTITY_RESOLVING_FAILED:
1819             break;
1820 #endif
1821 
1822         // re-encryption started
1823         case SM_EVENT_REENCRYPTION_STARTED:
1824             con_handle = sm_event_reencryption_complete_get_handle(packet);
1825             gatt_client = gatt_client_get_context_for_handle(con_handle);
1826             if (gatt_client == NULL) break;
1827 
1828             gatt_client->reencryption_active = true;
1829             gatt_client->reencryption_result = ERROR_CODE_SUCCESS;
1830             break;
1831 
1832         // re-encryption complete
1833         case SM_EVENT_REENCRYPTION_COMPLETE:
1834             gatt_client_handle_reencryption_complete(packet);
1835             break;
1836         default:
1837             break;
1838     }
1839 
1840     gatt_client_run();
1841 }
1842 
1843 static void gatt_client_handle_att_read_response(gatt_client_t *gatt_client, uint8_t *packet, uint16_t size) {
1844     switch (gatt_client->state) {
1845         case P_W4_INCLUDED_SERVICE_UUID_WITH_QUERY_RESULT:
1846             if (size >= 17) {
1847                 uint8_t uuid128[16];
1848                 reverse_128(&packet[1], uuid128);
1849                 report_gatt_included_service_uuid128(gatt_client, gatt_client->start_group_handle, uuid128);
1850             }
1851             trigger_next_included_service_query(gatt_client, gatt_client->start_group_handle);
1852             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1853             break;
1854 
1855         case P_W4_READ_CHARACTERISTIC_VALUE_RESULT:
1856             report_gatt_characteristic_value(gatt_client, gatt_client->attribute_handle, &packet[1], size - 1u);
1857             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1858             break;
1859 
1860         case P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT:
1861             report_gatt_characteristic_descriptor(gatt_client, gatt_client->attribute_handle, &packet[1],
1862                                                   size - 1u, 0u);
1863             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1864             break;
1865 
1866             // Use ATT_READ_REQUEST for first blob of Read Long Characteristic
1867         case P_W4_READ_BLOB_RESULT:
1868             report_gatt_long_characteristic_value_blob(gatt_client, gatt_client->attribute_handle, &packet[1],
1869                                                        size - 1u, gatt_client->attribute_offset);
1870             trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_QUERY, size - 1u);
1871             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1872             break;
1873 
1874             // Use ATT_READ_REQUEST for first blob of Read Long Characteristic Descriptor
1875         case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
1876             report_gatt_long_characteristic_descriptor(gatt_client, gatt_client->attribute_handle, &packet[1],
1877                                                        size - 1u, gatt_client->attribute_offset);
1878             trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY,
1879                                     size - 1u);
1880             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1881             break;
1882 
1883         default:
1884             break;
1885     }
1886 }
1887 
1888 static void gatt_client_handle_att_read_by_type_response(gatt_client_t *gatt_client, uint8_t *packet, uint16_t size) {
1889     switch (gatt_client->state) {
1890         case P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT:
1891             report_gatt_characteristics(gatt_client, packet, size);
1892             trigger_next_characteristic_query(gatt_client,
1893                                               get_last_result_handle_from_characteristics_list(packet, size));
1894             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done, or by ATT_ERROR
1895             break;
1896         case P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT:
1897             report_gatt_characteristics(gatt_client, packet, size);
1898             trigger_next_characteristic_query(gatt_client,
1899                                               get_last_result_handle_from_characteristics_list(packet, size));
1900             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done, or by ATT_ERROR
1901             break;
1902         case P_W4_INCLUDED_SERVICE_QUERY_RESULT: {
1903             if (size < 2u) break;
1904             uint16_t uuid16 = 0;
1905             uint16_t pair_size = packet[1];
1906 
1907             if (pair_size == 6u) {
1908                 if (size < 8u) break;
1909                 // UUIDs not available, query first included service
1910                 gatt_client->start_group_handle = little_endian_read_16(packet, 2); // ready for next query
1911                 gatt_client->query_start_handle = little_endian_read_16(packet, 4);
1912                 gatt_client->query_end_handle = little_endian_read_16(packet, 6);
1913                 gatt_client->state = P_W2_SEND_INCLUDED_SERVICE_WITH_UUID_QUERY;
1914                 break;
1915             }
1916 
1917             if (pair_size != 8u) break;
1918 
1919             // UUIDs included, report all of them
1920             uint16_t offset;
1921             for (offset = 2u; (offset + 8u) <= size; offset += pair_size) {
1922                 uint16_t include_handle = little_endian_read_16(packet, offset);
1923                 gatt_client->query_start_handle = little_endian_read_16(packet, offset + 2u);
1924                 gatt_client->query_end_handle = little_endian_read_16(packet, offset + 4u);
1925                 uuid16 = little_endian_read_16(packet, offset + 6u);
1926                 report_gatt_included_service_uuid16(gatt_client, include_handle, uuid16);
1927             }
1928 
1929             trigger_next_included_service_query(gatt_client,
1930                                                 get_last_result_handle_from_included_services_list(packet,
1931                                                                                                    size));
1932             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1933             break;
1934         }
1935 #ifndef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
1936         case P_W4_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT:
1937             gatt_client->client_characteristic_configuration_handle = little_endian_read_16(packet, 2);
1938             gatt_client->state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
1939             break;
1940 #endif
1941         case P_W4_READ_BY_TYPE_RESPONSE: {
1942             uint16_t pair_size = packet[1];
1943             // set last result handle to last valid handle, only used if pair_size invalid
1944             uint16_t last_result_handle = 0xffff;
1945             if (pair_size > 2) {
1946                 uint16_t offset;
1947                 for (offset = 2; offset < size; offset += pair_size) {
1948                     uint16_t value_handle = little_endian_read_16(packet, offset);
1949                     report_gatt_characteristic_value(gatt_client, value_handle, &packet[offset + 2u],
1950                                                      pair_size - 2u);
1951                     last_result_handle = value_handle;
1952                 }
1953             }
1954             trigger_next_read_by_type_query(gatt_client, last_result_handle);
1955             break;
1956         }
1957         default:
1958             break;
1959     }
1960 }
1961 
1962 static void gatt_client_handle_att_write_response(gatt_client_t *gatt_client) {
1963     switch (gatt_client->state) {
1964         case P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT:
1965             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1966             break;
1967         case P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT:
1968             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1969             break;
1970         case P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1971             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1972             break;
1973         default:
1974             break;
1975     }
1976 }
1977 
1978 static void gatt_client_handle_att_response(gatt_client_t * gatt_client, uint8_t * packet, uint16_t size) {
1979     uint8_t att_status;
1980     switch (packet[0]) {
1981         case ATT_EXCHANGE_MTU_RESPONSE: {
1982             if (size < 3u) break;
1983             bool update_gatt_server_att_mtu = false;
1984             uint16_t remote_rx_mtu = little_endian_read_16(packet, 1);
1985             uint16_t local_rx_mtu = l2cap_max_le_mtu();
1986             switch (gatt_client->bearer_type){
1987                 case ATT_BEARER_UNENHANCED_LE:
1988                     update_gatt_server_att_mtu = true;
1989                     break;
1990 #ifdef ENABLE_GATT_OVER_CLASSIC
1991                 case ATT_BEARER_UNENHANCED_CLASSIC:
1992                     local_rx_mtu = gatt_client->mtu;
1993                     break;
1994 #endif
1995                 default:
1996                     btstack_unreachable();
1997                     break;
1998             }
1999 
2000             uint16_t mtu = (remote_rx_mtu < local_rx_mtu) ? remote_rx_mtu : local_rx_mtu;
2001 
2002             // set gatt client mtu
2003             gatt_client->mtu = mtu;
2004             gatt_client->mtu_state = MTU_EXCHANGED;
2005 
2006             if (update_gatt_server_att_mtu){
2007                 // set per connection mtu state - for fixed channel
2008                 hci_connection_t *hci_connection = hci_connection_for_handle(gatt_client->con_handle);
2009                 hci_connection->att_connection.mtu = gatt_client->mtu;
2010                 hci_connection->att_connection.mtu_exchanged = true;
2011             }
2012             emit_gatt_mtu_exchanged_result_event(gatt_client, gatt_client->mtu);
2013             break;
2014         }
2015         case ATT_READ_BY_GROUP_TYPE_RESPONSE:
2016             switch (gatt_client->state) {
2017                 case P_W4_SERVICE_QUERY_RESULT:
2018                     report_gatt_services(gatt_client, packet, size);
2019                     trigger_next_service_query(gatt_client, get_last_result_handle_from_service_list(packet, size));
2020                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2021                     break;
2022                 default:
2023                     break;
2024             }
2025             break;
2026         case ATT_HANDLE_VALUE_NOTIFICATION:
2027             if (size < 3u) return;
2028             report_gatt_notification(gatt_client, little_endian_read_16(packet, 1u), &packet[3], size - 3u);
2029             return;
2030 #ifdef ENABLE_GATT_OVER_EATT
2031         case ATT_MULTIPLE_HANDLE_VALUE_NTF:
2032             if (size >= 5u) {
2033                 uint16_t offset = 1;
2034                 while (true){
2035                     uint16_t value_handle = little_endian_read_16(packet, offset);
2036                     offset += 2;
2037                     uint16_t value_length = little_endian_read_16(packet, offset);
2038                     offset += 2;
2039                     if ((offset + value_length) > size) break;
2040                     report_gatt_notification(gatt_client, value_handle, &packet[offset], value_length);
2041                     offset += value_length;
2042                 }
2043             }
2044             return;
2045 #endif
2046         case ATT_HANDLE_VALUE_INDICATION:
2047             if (size < 3u) break;
2048             report_gatt_indication(gatt_client, little_endian_read_16(packet, 1u), &packet[3], size - 3u);
2049             gatt_client->send_confirmation = true;
2050             break;
2051         case ATT_READ_BY_TYPE_RESPONSE:
2052             gatt_client_handle_att_read_by_type_response(gatt_client, packet, size);
2053             break;
2054         case ATT_READ_RESPONSE:
2055             gatt_client_handle_att_read_response(gatt_client, packet, size);
2056             break;
2057         case ATT_FIND_BY_TYPE_VALUE_RESPONSE: {
2058             uint8_t pair_size = 4;
2059             int i;
2060             uint16_t start_group_handle;
2061             uint16_t end_group_handle = 0xffff; // asserts GATT_EVENT_QUERY_COMPLETE is emitted if no results
2062             for (i = 1u; (i + pair_size) <= size; i += pair_size) {
2063                 start_group_handle = little_endian_read_16(packet, i);
2064                 end_group_handle = little_endian_read_16(packet, i + 2);
2065                 emit_gatt_service_query_result_event(gatt_client, start_group_handle, end_group_handle,
2066                                                      gatt_client->uuid128);
2067             }
2068             trigger_next_service_by_uuid_query(gatt_client, end_group_handle);
2069             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2070             break;
2071         }
2072         case ATT_FIND_INFORMATION_REPLY: {
2073             if (size < 2u) break;
2074 
2075             uint8_t pair_size = 4;
2076             if (packet[1u] == 2u) {
2077                 pair_size = 18;
2078             }
2079             uint16_t offset = 2;
2080 
2081             if (size < (pair_size + offset)) break;
2082             uint16_t last_descriptor_handle = little_endian_read_16(packet, size - pair_size);
2083 
2084 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
2085             log_info("ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY, state %x", gatt_client->gatt_client_state);
2086             if (gatt_client->gatt_client_state == P_W4_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT){
2087                 // iterate over descriptors looking for CCC
2088                 if (pair_size == 4){
2089                     while ((offset + 4) <= size){
2090                         uint16_t uuid16 = little_endian_read_16(packet, offset + 2);
2091                         if (uuid16 == GATT_CLIENT_CHARACTERISTICS_CONFIGURATION){
2092                             gatt_client->client_characteristic_configuration_handle = little_endian_read_16(packet, offset);
2093                             gatt_client->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
2094                             log_info("CCC found %x", gatt_client->client_characteristic_configuration_handle);
2095                             break;
2096                         }
2097                         offset += pair_size;
2098                     }
2099                 }
2100                 if (is_query_done(gatt_client, last_descriptor_handle)){
2101 
2102                 } else {
2103                     // next
2104                     gatt_client->start_group_handle = last_descriptor_handle + 1;
2105                     gatt_client->gatt_client_state = P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2106                 }
2107                 break;
2108             }
2109 #endif
2110             report_gatt_all_characteristic_descriptors(gatt_client, &packet[2], size - 2u, pair_size);
2111             trigger_next_characteristic_descriptor_query(gatt_client, last_descriptor_handle);
2112             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2113             break;
2114         }
2115 
2116         case ATT_WRITE_RESPONSE:
2117             gatt_client_handle_att_write_response(gatt_client);
2118             break;
2119 
2120         case ATT_READ_BLOB_RESPONSE: {
2121             uint16_t received_blob_length = size - 1u;
2122             switch (gatt_client->state) {
2123                 case P_W4_READ_BLOB_RESULT:
2124                     report_gatt_long_characteristic_value_blob(gatt_client, gatt_client->attribute_handle, &packet[1],
2125                                                                received_blob_length, gatt_client->attribute_offset);
2126                     trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_QUERY, received_blob_length);
2127                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2128                     break;
2129                 case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
2130                     report_gatt_long_characteristic_descriptor(gatt_client, gatt_client->attribute_handle,
2131                                                                &packet[1], received_blob_length,
2132                                                                gatt_client->attribute_offset);
2133                     trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY,
2134                                             received_blob_length);
2135                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2136                     break;
2137                 default:
2138                     break;
2139             }
2140             break;
2141         }
2142         case ATT_PREPARE_WRITE_RESPONSE:
2143             switch (gatt_client->state) {
2144                 case P_W4_PREPARE_WRITE_SINGLE_RESULT:
2145                     if (is_value_valid(gatt_client, packet, size)) {
2146                         att_status = ATT_ERROR_SUCCESS;
2147                     } else {
2148                         att_status = ATT_ERROR_DATA_MISMATCH;
2149                     }
2150                     gatt_client_handle_transaction_complete(gatt_client, att_status);
2151                     break;
2152 
2153                 case P_W4_PREPARE_WRITE_RESULT: {
2154                     gatt_client->attribute_offset = little_endian_read_16(packet, 3);
2155                     trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_WRITE, P_W2_EXECUTE_PREPARED_WRITE);
2156                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2157                     break;
2158                 }
2159                 case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT: {
2160                     gatt_client->attribute_offset = little_endian_read_16(packet, 3);
2161                     trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR,
2162                                                      P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR);
2163                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2164                     break;
2165                 }
2166                 case P_W4_PREPARE_RELIABLE_WRITE_RESULT: {
2167                     if (is_value_valid(gatt_client, packet, size)) {
2168                         gatt_client->attribute_offset = little_endian_read_16(packet, 3);
2169                         trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_RELIABLE_WRITE,
2170                                                          P_W2_EXECUTE_PREPARED_WRITE);
2171                         // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2172                         break;
2173                     }
2174                     gatt_client->state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
2175                     break;
2176                 }
2177                 default:
2178                     break;
2179             }
2180             break;
2181 
2182         case ATT_EXECUTE_WRITE_RESPONSE:
2183             switch (gatt_client->state) {
2184                 case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
2185                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2186                     break;
2187                 case P_W4_CANCEL_PREPARED_WRITE_RESULT:
2188                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2189                     break;
2190                 case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
2191                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_DATA_MISMATCH);
2192                     break;
2193                 case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
2194                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2195                     break;
2196                 default:
2197                     break;
2198 
2199             }
2200             break;
2201 
2202         case ATT_READ_MULTIPLE_RESPONSE:
2203             switch (gatt_client->state) {
2204                 case P_W4_READ_MULTIPLE_RESPONSE:
2205                     report_gatt_characteristic_value(gatt_client, 0u, &packet[1], size - 1u);
2206                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2207                     break;
2208                 default:
2209                     break;
2210             }
2211             break;
2212 
2213 #ifdef ENABLE_GATT_OVER_EATT
2214         case ATT_READ_MULTIPLE_VARIABLE_RSP:
2215             switch (gatt_client->state) {
2216                 case P_W4_READ_MULTIPLE_VARIABLE_RESPONSE:
2217                     report_gatt_characteristic_value(gatt_client, 0u, &packet[1], size - 1u);
2218                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2219                     break;
2220                 default:
2221                     break;
2222             }
2223             break;
2224 #endif
2225 
2226         case ATT_ERROR_RESPONSE:
2227             if (size < 5u) return;
2228             att_status = packet[4];
2229             switch (att_status) {
2230                 case ATT_ERROR_ATTRIBUTE_NOT_FOUND: {
2231                     switch (gatt_client->state) {
2232                         case P_W4_SERVICE_QUERY_RESULT:
2233                         case P_W4_SERVICE_WITH_UUID_RESULT:
2234                         case P_W4_INCLUDED_SERVICE_QUERY_RESULT:
2235                         case P_W4_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
2236                             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2237                             break;
2238                         case P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT:
2239                         case P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT:
2240                             report_gatt_characteristic_end_found(gatt_client, gatt_client->end_group_handle);
2241                             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2242                             break;
2243                         case P_W4_READ_BY_TYPE_RESPONSE:
2244                             if (gatt_client->start_group_handle == gatt_client->query_start_handle) {
2245                                 att_status = ATT_ERROR_ATTRIBUTE_NOT_FOUND;
2246                             } else {
2247                                 att_status = ATT_ERROR_SUCCESS;
2248                             }
2249                             gatt_client_handle_transaction_complete(gatt_client, att_status);
2250                             break;
2251                         default:
2252                             gatt_client_report_error_if_pending(gatt_client, att_status);
2253                             break;
2254                     }
2255                     break;
2256                 }
2257 
2258 #ifdef ENABLE_GATT_CLIENT_PAIRING
2259 
2260                     case ATT_ERROR_INSUFFICIENT_AUTHENTICATION:
2261                     case ATT_ERROR_INSUFFICIENT_ENCRYPTION_KEY_SIZE:
2262                     case ATT_ERROR_INSUFFICIENT_ENCRYPTION: {
2263 
2264                         // security too low
2265                         if (gatt_client->security_counter > 0) {
2266                             gatt_client_report_error_if_pending(gatt_client, att_status);
2267                             break;
2268                         }
2269                         // start security
2270                         gatt_client->security_counter++;
2271 
2272                         // setup action
2273                         int retry = 1;
2274                         switch (gatt_client->state){
2275                             case P_W4_READ_CHARACTERISTIC_VALUE_RESULT:
2276                                 gatt_client->state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY ;
2277                                 break;
2278                             case P_W4_READ_BLOB_RESULT:
2279                                 gatt_client->state = P_W2_SEND_READ_BLOB_QUERY;
2280                                 break;
2281                             case P_W4_READ_BY_TYPE_RESPONSE:
2282                                 gatt_client->state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2283                                 break;
2284                             case P_W4_READ_MULTIPLE_RESPONSE:
2285                                 gatt_client->state = P_W2_SEND_READ_MULTIPLE_REQUEST;
2286                                 break;
2287                             case P_W4_READ_MULTIPLE_VARIABLE_RESPONSE:
2288                                 gatt_client->state = P_W2_SEND_READ_MULTIPLE_VARIABLE_REQUEST;
2289                                 break;
2290                             case P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT:
2291                                 gatt_client->state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
2292                                 break;
2293                             case P_W4_PREPARE_WRITE_RESULT:
2294                                 gatt_client->state = P_W2_PREPARE_WRITE;
2295                                 break;
2296                             case P_W4_PREPARE_WRITE_SINGLE_RESULT:
2297                                 gatt_client->state = P_W2_PREPARE_WRITE_SINGLE;
2298                                 break;
2299                             case P_W4_PREPARE_RELIABLE_WRITE_RESULT:
2300                                 gatt_client->state = P_W2_PREPARE_RELIABLE_WRITE;
2301                                 break;
2302                             case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
2303                                 gatt_client->state = P_W2_EXECUTE_PREPARED_WRITE;
2304                                 break;
2305                             case P_W4_CANCEL_PREPARED_WRITE_RESULT:
2306                                 gatt_client->state = P_W2_CANCEL_PREPARED_WRITE;
2307                                 break;
2308                             case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
2309                                 gatt_client->state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
2310                                 break;
2311                             case P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT:
2312                                 gatt_client->state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
2313                                 break;
2314                             case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
2315                                 gatt_client->state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
2316                                 break;
2317                             case P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
2318                                 gatt_client->state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
2319                                 break;
2320                             case P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT:
2321                                 gatt_client->state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
2322                                 break;
2323                             case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
2324                                 gatt_client->state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
2325                                 break;
2326                             case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
2327                                 gatt_client->state = P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR;
2328                                 break;
2329 #ifdef ENABLE_LE_SIGNED_WRITE
2330                             case P_W4_SEND_SIGNED_WRITE_DONE:
2331                                 gatt_client->state = P_W2_SEND_SIGNED_WRITE;
2332                                 break;
2333 #endif
2334                             default:
2335                                 log_info("retry not supported for state %x", gatt_client->state);
2336                                 retry = 0;
2337                                 break;
2338                         }
2339 
2340                         if (!retry) {
2341                             gatt_client_report_error_if_pending(gatt_client, att_status);
2342                             break;
2343                         }
2344 
2345                         log_info("security error, start pairing");
2346 
2347                         // start pairing for higher security level
2348                         gatt_client->wait_for_authentication_complete = true;
2349                         gatt_client->pending_error_code = att_status;
2350                         sm_request_pairing(gatt_client->con_handle);
2351                         break;
2352                     }
2353 #endif
2354 
2355                     // nothing we can do about that
2356                 case ATT_ERROR_INSUFFICIENT_AUTHORIZATION:
2357                 default:
2358                     gatt_client_report_error_if_pending(gatt_client, att_status);
2359                     break;
2360             }
2361             break;
2362 
2363         default:
2364             log_info("ATT Handler, unhandled response type 0x%02x", packet[0]);
2365             break;
2366     }
2367 }
2368 
2369 static void gatt_client_att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size) {
2370     gatt_client_t *gatt_client;
2371 #ifdef ENABLE_GATT_OVER_CLASSIC
2372     uint8_t status;
2373     hci_connection_t * hci_connection;
2374     hci_con_handle_t con_handle;
2375 #endif
2376 
2377     if (size < 1u) return;
2378     switch (packet_type){
2379         case HCI_EVENT_PACKET:
2380             switch (hci_event_packet_get_type(packet)) {
2381 #ifdef ENABLE_GATT_OVER_CLASSIC
2382                 case L2CAP_EVENT_CHANNEL_OPENED:
2383                     status = l2cap_event_channel_opened_get_status(packet);
2384                     gatt_client = gatt_client_get_context_for_l2cap_cid(l2cap_event_channel_opened_get_local_cid(packet));
2385                     if (gatt_client != NULL){
2386                         con_handle = l2cap_event_channel_opened_get_handle(packet);
2387                         hci_connection = hci_connection_for_handle(con_handle);
2388                         if (status == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_RESOURCES){
2389                             if ((hci_connection != NULL) && hci_connection->att_server.incoming_connection_request) {
2390                                 log_info("Collision, retry in 100ms");
2391                                 gatt_client->state = P_W2_L2CAP_CONNECT;
2392                                 // set timer for retry
2393                                 btstack_run_loop_set_timer(&gatt_client->gc_timeout, GATT_CLIENT_COLLISION_BACKOFF_MS);
2394                                 btstack_run_loop_set_timer_handler(&gatt_client->gc_timeout, gatt_client_classic_retry);
2395                                 btstack_run_loop_add_timer(&gatt_client->gc_timeout);
2396                                 break;
2397                             }
2398                         }
2399                         // if status != 0, gatt_client will be discarded
2400                         gatt_client->state = P_READY;
2401                         gatt_client->con_handle = l2cap_event_channel_opened_get_handle(packet);
2402                         gatt_client->mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
2403                         gatt_client_classic_handle_connected(gatt_client, status);
2404                     }
2405                     break;
2406                 case L2CAP_EVENT_CHANNEL_CLOSED:
2407                     gatt_client = gatt_client_get_context_for_l2cap_cid(l2cap_event_channel_closed_get_local_cid(packet));
2408                     if (gatt_client != NULL){
2409                         // discard gatt client object
2410                         gatt_client_classic_handle_disconnected(gatt_client);
2411                     }
2412                     break;
2413 #endif
2414                 case L2CAP_EVENT_CAN_SEND_NOW:
2415                     gatt_client_run();
2416                     break;
2417                     // att_server has negotiated the mtu for this connection, cache if context exists
2418                 case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
2419                     if (size < 6u) break;
2420                     gatt_client = gatt_client_get_context_for_handle(handle);
2421                     if (gatt_client != NULL) {
2422                         gatt_client->mtu = little_endian_read_16(packet, 4);
2423                     }
2424                     break;
2425                 default:
2426                     break;
2427             }
2428             break;
2429 
2430         case ATT_DATA_PACKET:
2431             // special cases: notifications & indications motivate creating context
2432             switch (packet[0]) {
2433                 case ATT_HANDLE_VALUE_NOTIFICATION:
2434                 case ATT_HANDLE_VALUE_INDICATION:
2435                     gatt_client_provide_context_for_handle(handle, &gatt_client);
2436                     break;
2437                 default:
2438                     gatt_client = gatt_client_get_context_for_handle(handle);
2439                     break;
2440             }
2441 
2442             if (gatt_client != NULL) {
2443                 gatt_client_handle_att_response(gatt_client, packet, size);
2444                 gatt_client_run();
2445             }
2446             break;
2447 
2448 #ifdef ENABLE_GATT_OVER_CLASSIC
2449         case L2CAP_DATA_PACKET:
2450             gatt_client = gatt_client_get_context_for_l2cap_cid(handle);
2451             if (gatt_client != NULL){
2452                 gatt_client_handle_att_response(gatt_client, packet, size);
2453                 gatt_client_run();
2454             }
2455             break;
2456 #endif
2457 
2458         default:
2459             break;
2460     }
2461 }
2462 
2463 #ifdef ENABLE_LE_SIGNED_WRITE
2464 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
2465     btstack_linked_list_iterator_t it;
2466     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
2467     while (btstack_linked_list_iterator_has_next(&it)){
2468         gatt_client_t * gatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
2469         if (gatt_client->state == P_W4_CMAC_RESULT){
2470             // store result
2471             (void)memcpy(gatt_client->cmac, hash, 8);
2472             // reverse_64(hash, gatt_client->cmac);
2473             gatt_client->state = P_W2_SEND_SIGNED_WRITE;
2474             gatt_client_run();
2475             return;
2476         }
2477     }
2478 }
2479 
2480 uint8_t gatt_client_signed_write_without_response(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t value_handle, uint16_t message_len, uint8_t * message){
2481     gatt_client_t * gatt_client;
2482     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2483     if (status != ERROR_CODE_SUCCESS){
2484         return status;
2485     }
2486     if (is_ready(gatt_client) == 0){
2487         return GATT_CLIENT_IN_WRONG_STATE;
2488     }
2489 
2490     gatt_client->callback = callback;
2491     gatt_client->attribute_handle = value_handle;
2492     gatt_client->attribute_length = message_len;
2493     gatt_client->attribute_value = message;
2494     gatt_client->state = P_W4_IDENTITY_RESOLVING;
2495     gatt_client_run();
2496     return ERROR_CODE_SUCCESS;
2497 }
2498 #endif
2499 
2500 uint8_t gatt_client_discover_primary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2501     gatt_client_t * gatt_client;
2502     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2503     if (status != ERROR_CODE_SUCCESS){
2504         return status;
2505     }
2506 
2507     gatt_client->callback = callback;
2508     gatt_client->start_group_handle = 0x0001;
2509     gatt_client->end_group_handle   = 0xffff;
2510     gatt_client->state = P_W2_SEND_SERVICE_QUERY;
2511     gatt_client->uuid16 = GATT_PRIMARY_SERVICE_UUID;
2512     gatt_client_run();
2513     return ERROR_CODE_SUCCESS;
2514 }
2515 
2516 uint8_t gatt_client_discover_secondary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2517     gatt_client_t * gatt_client;
2518     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2519     if (status != ERROR_CODE_SUCCESS){
2520         return status;
2521     }
2522 
2523     gatt_client->callback = callback;
2524     gatt_client->start_group_handle = 0x0001;
2525     gatt_client->end_group_handle   = 0xffff;
2526     gatt_client->state = P_W2_SEND_SERVICE_QUERY;
2527     gatt_client->uuid16 = GATT_SECONDARY_SERVICE_UUID;
2528     gatt_client_run();
2529     return ERROR_CODE_SUCCESS;
2530 }
2531 
2532 uint8_t gatt_client_discover_primary_services_by_uuid16_with_context(btstack_packet_handler_t callback, hci_con_handle_t con_handle,
2533                                                                      uint16_t uuid16, uint16_t service_id, uint16_t connection_id){
2534     gatt_client_t * gatt_client;
2535     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2536     if (status != ERROR_CODE_SUCCESS){
2537         return status;
2538     }
2539 
2540     gatt_client->callback = callback;
2541     gatt_client->service_id = service_id;
2542     gatt_client->connection_id = connection_id;
2543     gatt_client->start_group_handle = 0x0001;
2544     gatt_client->end_group_handle   = 0xffff;
2545     gatt_client->state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
2546     gatt_client->uuid16 = uuid16;
2547     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), gatt_client->uuid16);
2548     gatt_client_run();
2549     return ERROR_CODE_SUCCESS;
2550 }
2551 
2552 uint8_t gatt_client_discover_primary_services_by_uuid16(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t uuid16){
2553     return gatt_client_discover_primary_services_by_uuid16_with_context(callback, con_handle, uuid16, 0, 0);
2554 }
2555 
2556 uint8_t gatt_client_discover_primary_services_by_uuid128(btstack_packet_handler_t callback, hci_con_handle_t con_handle, const uint8_t * uuid128){
2557     gatt_client_t * gatt_client;
2558     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2559     if (status != ERROR_CODE_SUCCESS){
2560         return status;
2561     }
2562 
2563     gatt_client->callback = callback;
2564     gatt_client->start_group_handle = 0x0001;
2565     gatt_client->end_group_handle   = 0xffff;
2566     gatt_client->uuid16 = 0;
2567     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2568     gatt_client->state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
2569     gatt_client_run();
2570     return ERROR_CODE_SUCCESS;
2571 }
2572 
2573 uint8_t gatt_client_discover_characteristics_for_service_with_context(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_service_t * service,
2574                                                                       uint16_t service_id, uint16_t connection_id){
2575     gatt_client_t * gatt_client;
2576     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2577     if (status != ERROR_CODE_SUCCESS){
2578         return status;
2579     }
2580 
2581     gatt_client->callback = callback;
2582     gatt_client->service_id = service_id;
2583     gatt_client->connection_id = connection_id;
2584     gatt_client->start_group_handle = service->start_group_handle;
2585     gatt_client->end_group_handle   = service->end_group_handle;
2586     gatt_client->filter_with_uuid = false;
2587     gatt_client->characteristic_start_handle = 0;
2588     gatt_client->state = P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY;
2589     gatt_client_run();
2590     return ERROR_CODE_SUCCESS;
2591 }
2592 
2593 uint8_t gatt_client_discover_characteristics_for_service(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_service_t * service){
2594     return gatt_client_discover_characteristics_for_service_with_context(callback, con_handle, service, 0, 0);
2595 }
2596 
2597 uint8_t gatt_client_find_included_services_for_service_with_context(btstack_packet_handler_t callback, hci_con_handle_t con_handle,
2598                                                                     gatt_client_service_t * service, uint16_t service_id, uint16_t connection_id){
2599     gatt_client_t * gatt_client;
2600     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2601     if (status != ERROR_CODE_SUCCESS){
2602         return status;
2603     }
2604 
2605     gatt_client->callback = callback;
2606     gatt_client->service_id = service_id;
2607     gatt_client->connection_id = connection_id;
2608     gatt_client->start_group_handle = service->start_group_handle;
2609     gatt_client->end_group_handle   = service->end_group_handle;
2610     gatt_client->state = P_W2_SEND_INCLUDED_SERVICE_QUERY;
2611 
2612     gatt_client_run();
2613     return ERROR_CODE_SUCCESS;
2614 }
2615 
2616 uint8_t gatt_client_find_included_services_for_service(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_service_t * service) {
2617     return gatt_client_find_included_services_for_service_with_context(callback, con_handle, service, 0, 0);
2618 }
2619 
2620 uint8_t gatt_client_discover_characteristics_for_handle_range_by_uuid16(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t start_handle, uint16_t end_handle, uint16_t uuid16){
2621     gatt_client_t * gatt_client;
2622     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2623     if (status != ERROR_CODE_SUCCESS){
2624         return status;
2625     }
2626 
2627     gatt_client->callback = callback;
2628     gatt_client->start_group_handle = start_handle;
2629     gatt_client->end_group_handle   = end_handle;
2630     gatt_client->filter_with_uuid = true;
2631     gatt_client->uuid16 = uuid16;
2632     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), uuid16);
2633     gatt_client->characteristic_start_handle = 0;
2634     gatt_client->state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
2635     gatt_client_run();
2636     return ERROR_CODE_SUCCESS;
2637 }
2638 
2639 uint8_t gatt_client_discover_characteristics_for_handle_range_by_uuid128(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t start_handle, uint16_t end_handle, const uint8_t * uuid128){
2640     gatt_client_t * gatt_client;
2641     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2642     if (status != ERROR_CODE_SUCCESS){
2643         return status;
2644     }
2645 
2646     gatt_client->callback = callback;
2647     gatt_client->start_group_handle = start_handle;
2648     gatt_client->end_group_handle   = end_handle;
2649     gatt_client->filter_with_uuid = true;
2650     gatt_client->uuid16 = 0;
2651     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2652     gatt_client->characteristic_start_handle = 0;
2653     gatt_client->state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
2654     gatt_client_run();
2655     return ERROR_CODE_SUCCESS;
2656 }
2657 
2658 
2659 uint8_t gatt_client_discover_characteristics_for_service_by_uuid16(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_service_t * service, uint16_t uuid16){
2660     return gatt_client_discover_characteristics_for_handle_range_by_uuid16(callback, con_handle, service->start_group_handle, service->end_group_handle, uuid16);
2661 }
2662 
2663 uint8_t gatt_client_discover_characteristics_for_service_by_uuid128(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_service_t * service, const uint8_t * uuid128){
2664     return gatt_client_discover_characteristics_for_handle_range_by_uuid128(callback, con_handle, service->start_group_handle, service->end_group_handle, uuid128);
2665 }
2666 
2667 uint8_t gatt_client_discover_characteristic_descriptors_with_context(btstack_packet_handler_t callback, hci_con_handle_t con_handle,
2668                                                                      gatt_client_characteristic_t * characteristic,  uint16_t service_id, uint16_t connection_id){
2669     gatt_client_t * gatt_client;
2670     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2671     if (status != ERROR_CODE_SUCCESS){
2672         return status;
2673     }
2674 
2675     gatt_client->service_id = service_id;
2676     gatt_client->connection_id = connection_id;
2677 
2678     // check if there is space for characteristics descriptors
2679     if (characteristic->end_handle > characteristic->value_handle){
2680         gatt_client->callback = callback;
2681         gatt_client->start_group_handle = characteristic->value_handle + 1u;
2682         gatt_client->end_group_handle   = characteristic->end_handle;
2683         gatt_client->state = P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY;
2684         gatt_client_run();
2685     } else {
2686         // schedule gatt complete event on next run loop iteration otherwise
2687         gatt_client->state = P_W2_EMIT_QUERY_COMPLETE_EVENT;
2688         gatt_client_deferred_event_emit.callback = gatt_client_emit_events;
2689         btstack_run_loop_execute_on_main_thread(&gatt_client_deferred_event_emit);
2690     }
2691     return ERROR_CODE_SUCCESS;
2692 }
2693 
2694 uint8_t gatt_client_discover_characteristic_descriptors(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2695     return gatt_client_discover_characteristic_descriptors_with_context(callback, con_handle, characteristic, 0, 0);
2696 }
2697 
2698 uint8_t gatt_client_read_value_of_characteristic_using_value_handle_with_context(btstack_packet_handler_t callback,
2699                                                                                  hci_con_handle_t con_handle,
2700                                                                                  uint16_t value_handle,
2701                                                                                  uint16_t service_id,
2702                                                                                  uint16_t connection_id) {
2703     gatt_client_t * gatt_client;
2704     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2705     if (status != ERROR_CODE_SUCCESS){
2706         return status;
2707     }
2708 
2709     gatt_client->callback = callback;
2710     gatt_client->service_id = service_id;
2711     gatt_client->connection_id = connection_id;
2712     gatt_client->attribute_handle = value_handle;
2713     gatt_client->attribute_offset = 0;
2714     gatt_client->state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY;
2715     gatt_client_run();
2716     return ERROR_CODE_SUCCESS;
2717 }
2718 
2719 uint8_t gatt_client_read_value_of_characteristic_using_value_handle(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t value_handle){
2720     return gatt_client_read_value_of_characteristic_using_value_handle_with_context(callback, con_handle, value_handle, 0, 0);
2721 
2722 }
2723 
2724 uint8_t gatt_client_read_value_of_characteristics_by_uuid16(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t start_handle, uint16_t end_handle, uint16_t uuid16){
2725     gatt_client_t * gatt_client;
2726     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2727     if (status != ERROR_CODE_SUCCESS){
2728         return status;
2729     }
2730 
2731     gatt_client->callback = callback;
2732     gatt_client->start_group_handle = start_handle;
2733     gatt_client->end_group_handle = end_handle;
2734     gatt_client->query_start_handle = start_handle;
2735     gatt_client->query_end_handle = end_handle;
2736     gatt_client->uuid16 = uuid16;
2737     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), uuid16);
2738     gatt_client->state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2739     gatt_client_run();
2740     return ERROR_CODE_SUCCESS;
2741 }
2742 
2743 uint8_t gatt_client_read_value_of_characteristics_by_uuid128(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t start_handle, uint16_t end_handle, const uint8_t * uuid128){
2744     gatt_client_t * gatt_client;
2745     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2746     if (status != ERROR_CODE_SUCCESS){
2747         return status;
2748     }
2749 
2750     gatt_client->callback = callback;
2751     gatt_client->start_group_handle = start_handle;
2752     gatt_client->end_group_handle = end_handle;
2753     gatt_client->query_start_handle = start_handle;
2754     gatt_client->query_end_handle = end_handle;
2755     gatt_client->uuid16 = 0;
2756     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2757     gatt_client->state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2758     gatt_client_run();
2759     return ERROR_CODE_SUCCESS;
2760 }
2761 
2762 
2763 uint8_t gatt_client_read_value_of_characteristic(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2764     return gatt_client_read_value_of_characteristic_using_value_handle(callback, con_handle, characteristic->value_handle);
2765 }
2766 
2767 uint8_t gatt_client_read_long_value_of_characteristic_using_value_handle_with_offset(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t value_handle, uint16_t offset){
2768     gatt_client_t * gatt_client;
2769     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2770     if (status != ERROR_CODE_SUCCESS){
2771         return status;
2772     }
2773 
2774     gatt_client->callback = callback;
2775     gatt_client->attribute_handle = value_handle;
2776     gatt_client->attribute_offset = offset;
2777     gatt_client->state = P_W2_SEND_READ_BLOB_QUERY;
2778     gatt_client_run();
2779     return ERROR_CODE_SUCCESS;
2780 }
2781 uint8_t gatt_client_read_long_value_of_characteristic_using_value_handle_with_context(btstack_packet_handler_t callback,
2782                                                                                       hci_con_handle_t con_handle, uint16_t value_handle,
2783                                                                                       uint16_t service_id, uint16_t connection_id){
2784     // TODO: move into gatt_client_read_long_value_of_characteristic_using_value_handle_with_offset once
2785     //       gatt_client_read_long_value_of_characteristic_using_value_handle_with_offset_and_context exists
2786     gatt_client_t * gatt_client;
2787     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2788     if (status != ERROR_CODE_SUCCESS){
2789         return status;
2790     }
2791     gatt_client->service_id = service_id;
2792     gatt_client->connection_id = connection_id;
2793     return gatt_client_read_long_value_of_characteristic_using_value_handle_with_offset(callback, con_handle, value_handle, 0);
2794 }
2795 
2796 uint8_t gatt_client_read_long_value_of_characteristic_using_value_handle(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t value_handle){
2797     return gatt_client_read_long_value_of_characteristic_using_value_handle_with_context(callback, con_handle, value_handle, 0, 0);
2798 }
2799 
2800 uint8_t gatt_client_read_long_value_of_characteristic(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2801     return gatt_client_read_long_value_of_characteristic_using_value_handle(callback, con_handle, characteristic->value_handle);
2802 }
2803 
2804 static uint8_t gatt_client_read_multiple_characteristic_values_with_state(btstack_packet_handler_t callback, hci_con_handle_t con_handle, int num_value_handles, uint16_t * value_handles, gatt_client_state_t state){
2805     gatt_client_t * gatt_client;
2806     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2807     if (status != ERROR_CODE_SUCCESS){
2808         return status;
2809     }
2810 
2811 #ifdef ENABLE_GATT_OVER_EATT
2812     if (state == P_W2_SEND_READ_MULTIPLE_VARIABLE_REQUEST){
2813         if (gatt_client->bearer_type != ATT_BEARER_ENHANCED_LE){
2814             return ERROR_CODE_COMMAND_DISALLOWED;
2815         }
2816     }
2817 #endif
2818 
2819     gatt_client->callback = callback;
2820     gatt_client->read_multiple_handle_count = num_value_handles;
2821     gatt_client->read_multiple_handles = value_handles;
2822     gatt_client->state = state;
2823     gatt_client_run();
2824     return ERROR_CODE_SUCCESS;
2825 }
2826 
2827 uint8_t gatt_client_read_multiple_characteristic_values(btstack_packet_handler_t callback, hci_con_handle_t con_handle, int num_value_handles, uint16_t * value_handles){
2828     return gatt_client_read_multiple_characteristic_values_with_state(callback, con_handle, num_value_handles, value_handles, P_W2_SEND_READ_MULTIPLE_REQUEST);
2829 }
2830 
2831 #ifdef ENABLE_GATT_OVER_EATT
2832 uint8_t gatt_client_read_multiple_variable_characteristic_values(btstack_packet_handler_t callback, hci_con_handle_t con_handle, int num_value_handles, uint16_t * value_handles){
2833     return gatt_client_read_multiple_characteristic_values_with_state(callback, con_handle, num_value_handles, value_handles, P_W2_SEND_READ_MULTIPLE_VARIABLE_REQUEST);
2834 }
2835 #endif
2836 
2837 uint8_t gatt_client_write_value_of_characteristic_without_response(hci_con_handle_t con_handle, uint16_t value_handle, uint16_t value_length, uint8_t * value){
2838     gatt_client_t * gatt_client;
2839     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2840     if (status != ERROR_CODE_SUCCESS){
2841         return status;
2842     }
2843 
2844     if (value_length > (gatt_client->mtu - 3u)) return GATT_CLIENT_VALUE_TOO_LONG;
2845     if (!att_dispatch_client_can_send_now(gatt_client->con_handle)) return GATT_CLIENT_BUSY;
2846 
2847     return att_write_request(gatt_client, ATT_WRITE_COMMAND, value_handle, value_length, value);
2848 }
2849 uint8_t gatt_client_write_value_of_characteristic_with_context(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t value_handle,
2850                                                                uint16_t value_length, uint8_t * value, uint16_t service_id, uint16_t connection_id){
2851     gatt_client_t * gatt_client;
2852     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2853     if (status != ERROR_CODE_SUCCESS){
2854         return status;
2855     }
2856 
2857     gatt_client->callback = callback;
2858     gatt_client->service_id = service_id;
2859     gatt_client->connection_id = connection_id;
2860     gatt_client->attribute_handle = value_handle;
2861     gatt_client->attribute_length = value_length;
2862     gatt_client->attribute_value = value;
2863     gatt_client->state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
2864     gatt_client_run();
2865     return ERROR_CODE_SUCCESS;
2866 }
2867 uint8_t gatt_client_write_value_of_characteristic(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t value_handle, uint16_t value_length, uint8_t * value) {
2868     return gatt_client_write_value_of_characteristic_with_context(callback, con_handle, value_handle, value_length, value, 0, 0);
2869 }
2870 
2871 uint8_t gatt_client_write_long_value_of_characteristic_with_offset(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t value_handle, uint16_t offset, uint16_t value_length, uint8_t * value){
2872     gatt_client_t * gatt_client;
2873     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2874     if (status != ERROR_CODE_SUCCESS){
2875         return status;
2876     }
2877 
2878     gatt_client->callback = callback;
2879     gatt_client->attribute_handle = value_handle;
2880     gatt_client->attribute_length = value_length;
2881     gatt_client->attribute_offset = offset;
2882     gatt_client->attribute_value = value;
2883     gatt_client->state = P_W2_PREPARE_WRITE;
2884     gatt_client_run();
2885     return ERROR_CODE_SUCCESS;
2886 }
2887 
2888 uint8_t gatt_client_write_long_value_of_characteristic_with_context(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t value_handle, uint16_t value_length, uint8_t * value, uint16_t service_id, uint16_t connection_id){
2889     // TODO: move into gatt_client_write_long_value_of_characteristic_with_offset once gatt_client_write_long_value_of_characteristic_with_offset_with_context exists
2890     gatt_client_t * gatt_client;
2891     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2892     if (status != ERROR_CODE_SUCCESS){
2893         return status;
2894     }
2895     gatt_client->service_id = service_id;
2896     gatt_client->connection_id = connection_id;
2897     return gatt_client_write_long_value_of_characteristic_with_offset(callback, con_handle, value_handle, 0, value_length, value);
2898 }
2899 
2900 uint8_t gatt_client_write_long_value_of_characteristic(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t value_handle, uint16_t value_length, uint8_t * value){
2901     return gatt_client_write_long_value_of_characteristic_with_context(callback, con_handle, value_handle, value_length, value, 0, 0);
2902 }
2903 
2904 uint8_t gatt_client_reliable_write_long_value_of_characteristic(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t value_handle, uint16_t value_length, uint8_t * value){
2905     gatt_client_t * gatt_client;
2906     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2907     if (status != ERROR_CODE_SUCCESS){
2908         return status;
2909     }
2910 
2911     gatt_client->callback = callback;
2912     gatt_client->attribute_handle = value_handle;
2913     gatt_client->attribute_length = value_length;
2914     gatt_client->attribute_offset = 0;
2915     gatt_client->attribute_value = value;
2916     gatt_client->state = P_W2_PREPARE_RELIABLE_WRITE;
2917     gatt_client_run();
2918     return ERROR_CODE_SUCCESS;
2919 }
2920 
2921 uint8_t gatt_client_write_client_characteristic_configuration_with_context(btstack_packet_handler_t callback, hci_con_handle_t con_handle,
2922                                                               gatt_client_characteristic_t * characteristic, uint16_t configuration, uint16_t service_id, uint16_t connection_id){
2923     gatt_client_t * gatt_client;
2924     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2925     if (status != ERROR_CODE_SUCCESS){
2926         return status;
2927     }
2928 
2929     if (configuration > 3){
2930         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
2931     }
2932 
2933     if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION) &&
2934         ((characteristic->properties & ATT_PROPERTY_NOTIFY) == 0u)) {
2935         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED");
2936         return GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED;
2937     } else if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_INDICATION) &&
2938                ((characteristic->properties & ATT_PROPERTY_INDICATE) == 0u)){
2939         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED");
2940         return GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED;
2941     }
2942 
2943     gatt_client->callback = callback;
2944     gatt_client->service_id = service_id;
2945     gatt_client->connection_id = connection_id;
2946     gatt_client->start_group_handle = characteristic->value_handle;
2947     gatt_client->end_group_handle = characteristic->end_handle;
2948     little_endian_store_16(gatt_client->client_characteristic_configuration_value, 0, configuration);
2949 
2950 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
2951     gatt_client->gatt_client_state = P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2952 #else
2953     gatt_client->state = P_W2_SEND_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2954 #endif
2955     gatt_client_run();
2956     return ERROR_CODE_SUCCESS;
2957 }
2958 
2959 uint8_t gatt_client_write_client_characteristic_configuration(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic, uint16_t configuration){
2960     return gatt_client_write_client_characteristic_configuration_with_context(callback, con_handle, characteristic, configuration, 0, 0);
2961 }
2962 
2963 uint8_t gatt_client_read_characteristic_descriptor_using_descriptor_handle(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t descriptor_handle){
2964     gatt_client_t * gatt_client;
2965     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2966     if (status != ERROR_CODE_SUCCESS){
2967         return status;
2968     }
2969 
2970     gatt_client->callback = callback;
2971     gatt_client->attribute_handle = descriptor_handle;
2972 
2973     gatt_client->state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
2974     gatt_client_run();
2975     return ERROR_CODE_SUCCESS;
2976 }
2977 
2978 uint8_t gatt_client_read_characteristic_descriptor(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_descriptor_t * descriptor){
2979     return gatt_client_read_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
2980 }
2981 
2982 uint8_t gatt_client_read_long_characteristic_descriptor_using_descriptor_handle_with_offset(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t descriptor_handle, uint16_t offset){
2983     gatt_client_t * gatt_client;
2984     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2985     if (status != ERROR_CODE_SUCCESS){
2986         return status;
2987     }
2988 
2989     gatt_client->callback = callback;
2990     gatt_client->attribute_handle = descriptor_handle;
2991     gatt_client->attribute_offset = offset;
2992     gatt_client->state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
2993     gatt_client_run();
2994     return ERROR_CODE_SUCCESS;
2995 }
2996 
2997 uint8_t gatt_client_read_long_characteristic_descriptor_using_descriptor_handle(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t descriptor_handle){
2998     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0);
2999 }
3000 
3001 uint8_t gatt_client_read_long_characteristic_descriptor(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_descriptor_t * descriptor){
3002     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
3003 }
3004 
3005 uint8_t gatt_client_write_characteristic_descriptor_using_descriptor_handle(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t descriptor_handle, uint16_t value_length, uint8_t * value){
3006     gatt_client_t * gatt_client;
3007     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
3008     if (status != ERROR_CODE_SUCCESS){
3009         return status;
3010     }
3011 
3012     gatt_client->callback = callback;
3013     gatt_client->attribute_handle = descriptor_handle;
3014     gatt_client->attribute_length = value_length;
3015     gatt_client->attribute_offset = 0;
3016     gatt_client->attribute_value = value;
3017     gatt_client->state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
3018     gatt_client_run();
3019     return ERROR_CODE_SUCCESS;
3020 }
3021 
3022 uint8_t gatt_client_write_characteristic_descriptor(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_descriptor_t * descriptor, uint16_t value_length, uint8_t * value){
3023     return gatt_client_write_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, value_length, value);
3024 }
3025 
3026 uint8_t gatt_client_write_long_characteristic_descriptor_using_descriptor_handle_with_offset(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t descriptor_handle, uint16_t offset, uint16_t value_length, uint8_t * value){
3027     gatt_client_t * gatt_client;
3028     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
3029     if (status != ERROR_CODE_SUCCESS){
3030         return status;
3031     }
3032 
3033     gatt_client->callback = callback;
3034     gatt_client->attribute_handle = descriptor_handle;
3035     gatt_client->attribute_length = value_length;
3036     gatt_client->attribute_offset = offset;
3037     gatt_client->attribute_value = value;
3038     gatt_client->state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
3039     gatt_client_run();
3040     return ERROR_CODE_SUCCESS;
3041 }
3042 
3043 uint8_t gatt_client_write_long_characteristic_descriptor_using_descriptor_handle(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t descriptor_handle, uint16_t value_length, uint8_t * value){
3044     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0, value_length, value);
3045 }
3046 
3047 uint8_t gatt_client_write_long_characteristic_descriptor(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_descriptor_t * descriptor, uint16_t value_length, uint8_t * value){
3048     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, value_length, value);
3049 }
3050 
3051 /**
3052  * @brief -> gatt complete event
3053  */
3054 uint8_t gatt_client_prepare_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t attribute_handle, uint16_t offset, uint16_t value_length, uint8_t * value){
3055     gatt_client_t * gatt_client;
3056     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
3057     if (status != ERROR_CODE_SUCCESS){
3058         return status;
3059     }
3060 
3061     gatt_client->callback = callback;
3062     gatt_client->attribute_handle = attribute_handle;
3063     gatt_client->attribute_length = value_length;
3064     gatt_client->attribute_offset = offset;
3065     gatt_client->attribute_value = value;
3066     gatt_client->state = P_W2_PREPARE_WRITE_SINGLE;
3067     gatt_client_run();
3068     return ERROR_CODE_SUCCESS;
3069 }
3070 
3071 /**
3072  * @brief -> gatt complete event
3073  */
3074 uint8_t gatt_client_execute_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
3075     gatt_client_t * gatt_client;
3076     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
3077     if (status != ERROR_CODE_SUCCESS){
3078         return status;
3079     }
3080 
3081     gatt_client->callback = callback;
3082     gatt_client->state = P_W2_EXECUTE_PREPARED_WRITE;
3083     gatt_client_run();
3084     return ERROR_CODE_SUCCESS;
3085 }
3086 
3087 /**
3088  * @brief -> gatt complete event
3089  */
3090 uint8_t gatt_client_cancel_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
3091     gatt_client_t * gatt_client;
3092     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
3093     if (status != ERROR_CODE_SUCCESS){
3094         return status;
3095     }
3096 
3097     gatt_client->callback = callback;
3098     gatt_client->state = P_W2_CANCEL_PREPARED_WRITE;
3099     gatt_client_run();
3100     return ERROR_CODE_SUCCESS;
3101 }
3102 
3103 void gatt_client_deserialize_service(const uint8_t *packet, int offset, gatt_client_service_t * service){
3104     service->start_group_handle = little_endian_read_16(packet, offset);
3105     service->end_group_handle = little_endian_read_16(packet, offset + 2);
3106     reverse_128(&packet[offset + 4], service->uuid128);
3107     if (uuid_has_bluetooth_prefix(service->uuid128)){
3108         service->uuid16 = big_endian_read_32(service->uuid128, 0);
3109     } else {
3110         service->uuid16 = 0;
3111     }
3112 }
3113 
3114 void gatt_client_deserialize_characteristic(const uint8_t * packet, int offset, gatt_client_characteristic_t * characteristic){
3115     characteristic->start_handle = little_endian_read_16(packet, offset);
3116     characteristic->value_handle = little_endian_read_16(packet, offset + 2);
3117     characteristic->end_handle = little_endian_read_16(packet, offset + 4);
3118     characteristic->properties = little_endian_read_16(packet, offset + 6);
3119     reverse_128(&packet[offset+8], characteristic->uuid128);
3120     if (uuid_has_bluetooth_prefix(characteristic->uuid128)){
3121         characteristic->uuid16 = big_endian_read_32(characteristic->uuid128, 0);
3122     } else {
3123         characteristic->uuid16 = 0;
3124     }
3125 }
3126 
3127 void gatt_client_deserialize_characteristic_descriptor(const uint8_t * packet, int offset, gatt_client_characteristic_descriptor_t * descriptor){
3128     descriptor->handle = little_endian_read_16(packet, offset);
3129     reverse_128(&packet[offset+2], descriptor->uuid128);
3130     if (uuid_has_bluetooth_prefix(descriptor->uuid128)){
3131         descriptor->uuid16 = big_endian_read_32(descriptor->uuid128, 0);
3132     } else {
3133         descriptor->uuid16 = 0;
3134     }
3135 }
3136 
3137 void gatt_client_send_mtu_negotiation(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
3138     gatt_client_t * gatt_client;
3139     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3140     if (status != ERROR_CODE_SUCCESS){
3141         return;
3142     }
3143     if (gatt_client->mtu_state == MTU_AUTO_EXCHANGE_DISABLED){
3144         gatt_client->callback = callback;
3145         gatt_client->mtu_state = SEND_MTU_EXCHANGE;
3146         gatt_client_run();
3147     }
3148 }
3149 
3150 uint8_t gatt_client_request_to_write_without_response(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
3151     gatt_client_t * gatt_client;
3152     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3153     if (status != ERROR_CODE_SUCCESS){
3154         return status;
3155     }
3156     bool added = btstack_linked_list_add_tail(&gatt_client->write_without_response_requests, (btstack_linked_item_t*) callback_registration);
3157     if (added == false){
3158         return ERROR_CODE_COMMAND_DISALLOWED;
3159     } else {
3160         att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
3161         return ERROR_CODE_SUCCESS;
3162     }
3163 }
3164 
3165 uint8_t gatt_client_request_to_send_gatt_query(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
3166     gatt_client_t * gatt_client;
3167     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3168     if (status != ERROR_CODE_SUCCESS){
3169         return status;
3170     }
3171     bool added = btstack_linked_list_add_tail(&gatt_client->query_requests, (btstack_linked_item_t*) callback_registration);
3172     if (added == false){
3173         return ERROR_CODE_COMMAND_DISALLOWED;
3174     } else {
3175         gatt_client_notify_can_send_query(gatt_client);
3176         return ERROR_CODE_SUCCESS;
3177     }
3178 }
3179 
3180 uint8_t gatt_client_remove_gatt_query(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
3181     gatt_client_t * gatt_client;
3182     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3183     if (status != ERROR_CODE_SUCCESS){
3184         return status;
3185     }
3186     (void)btstack_linked_list_remove(&gatt_client->query_requests, (btstack_linked_item_t*) callback_registration);
3187     return ERROR_CODE_SUCCESS;
3188 }
3189 
3190 uint8_t gatt_client_request_can_write_without_response_event(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
3191     gatt_client_t * gatt_client;
3192     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3193     if (status != ERROR_CODE_SUCCESS){
3194         return status;
3195     }
3196     if (gatt_client->write_without_response_callback != NULL){
3197         return GATT_CLIENT_IN_WRONG_STATE;
3198     }
3199     gatt_client->write_without_response_callback = callback;
3200     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
3201     return ERROR_CODE_SUCCESS;
3202 }
3203 
3204 #ifdef ENABLE_GATT_CLIENT_SERVICE_CHANGED
3205 void gatt_client_add_service_changed_handler(btstack_packet_callback_registration_t * callback) {
3206     btstack_linked_list_add_tail(&gatt_client_service_changed_handler, (btstack_linked_item_t*) callback);
3207 }
3208 
3209 void gatt_client_remove_service_changed_handler(btstack_packet_callback_registration_t * callback){
3210     btstack_linked_list_remove(&gatt_client_service_changed_handler, (btstack_linked_item_t*) callback);
3211 }
3212 #endif
3213 
3214 #if defined(ENABLE_GATT_OVER_CLASSIC) || defined(ENABLE_GATT_OVER_EATT)
3215 
3216 #include "hci_event.h"
3217 
3218 static const hci_event_t gatt_client_connected = {
3219         GATT_EVENT_CONNECTED, 0, "11BH"
3220 };
3221 
3222 static const hci_event_t gatt_client_disconnected = {
3223         GATT_EVENT_DISCONNECTED, 0, "H"
3224 };
3225 
3226 static void
3227 gatt_client_emit_connected(btstack_packet_handler_t callback, uint8_t status, bd_addr_type_t addr_type, bd_addr_t addr,
3228                            hci_con_handle_t con_handle) {
3229     uint8_t buffer[20];
3230     uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_connected, status, addr, con_handle);
3231     (*callback)(HCI_EVENT_PACKET, 0, buffer, len);
3232 }
3233 
3234 #endif
3235 
3236 #ifdef ENABLE_GATT_OVER_CLASSIC
3237 
3238 #include "bluetooth_psm.h"
3239 
3240 // single active SDP query
3241 static gatt_client_t * gatt_client_classic_active_sdp_query;
3242 
3243 // macos protocol descriptor list requires 16 bytes
3244 static uint8_t gatt_client_classic_sdp_buffer[32];
3245 
3246 
3247 static gatt_client_t * gatt_client_get_context_for_classic_addr(bd_addr_t addr){
3248     btstack_linked_item_t *it;
3249     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
3250         gatt_client_t * gatt_client = (gatt_client_t *) it;
3251         if (memcmp(gatt_client->addr, addr, 6) == 0){
3252             return gatt_client;
3253         }
3254     }
3255     return NULL;
3256 }
3257 
3258 static gatt_client_t * gatt_client_get_context_for_l2cap_cid(uint16_t l2cap_cid){
3259     btstack_linked_item_t *it;
3260     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
3261         gatt_client_t * gatt_client = (gatt_client_t *) it;
3262         if (gatt_client->l2cap_cid == l2cap_cid){
3263             return gatt_client;
3264         }
3265     }
3266     return NULL;
3267 }
3268 
3269 static void gatt_client_classic_handle_connected(gatt_client_t * gatt_client, uint8_t status){
3270     // cache peer information
3271     bd_addr_t addr;
3272     // cppcheck-suppress uninitvar ; addr is reported as uninitialized although it's the destination of the memcpy
3273     memcpy(addr, gatt_client->addr, 6);
3274     bd_addr_type_t addr_type = gatt_client->addr_type;
3275     gatt_client->addr_type = BD_ADDR_TYPE_ACL;
3276     hci_con_handle_t con_handle = gatt_client->con_handle;
3277     btstack_packet_handler_t callback = gatt_client->callback;
3278 
3279     if (status != ERROR_CODE_SUCCESS){
3280         btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
3281         btstack_memory_gatt_client_free(gatt_client);
3282     }
3283 
3284     gatt_client_emit_connected(callback, status, addr_type, addr, con_handle);
3285 }
3286 
3287 static void gatt_client_classic_retry(btstack_timer_source_t * ts){
3288     gatt_client_t * gatt_client = gatt_client_for_timer(ts);
3289     if (gatt_client != NULL){
3290         gatt_client->state = P_W4_L2CAP_CONNECTION;
3291         att_dispatch_classic_connect(gatt_client->addr, gatt_client->l2cap_psm, &gatt_client->l2cap_cid);
3292     }
3293 }
3294 
3295 static void gatt_client_classic_handle_disconnected(gatt_client_t * gatt_client){
3296 
3297     gatt_client_report_error_if_pending(gatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
3298     gatt_client_timeout_stop(gatt_client);
3299 
3300     hci_con_handle_t con_handle = gatt_client->con_handle;
3301     btstack_packet_handler_t callback = gatt_client->callback;
3302     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
3303     btstack_memory_gatt_client_free(gatt_client);
3304 
3305     uint8_t buffer[20];
3306     uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_disconnected, con_handle);
3307     (*callback)(HCI_EVENT_PACKET, 0, buffer, len);
3308 }
3309 
3310 static void gatt_client_handle_sdp_client_query_attribute_value(gatt_client_t * connection, uint8_t *packet){
3311     des_iterator_t des_list_it;
3312     des_iterator_t prot_it;
3313 
3314     if (sdp_event_query_attribute_byte_get_attribute_length(packet) <= sizeof(gatt_client_classic_sdp_buffer)) {
3315         gatt_client_classic_sdp_buffer[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet);
3316         if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)) {
3317             switch(sdp_event_query_attribute_byte_get_attribute_id(packet)) {
3318                 case BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST:
3319                     for (des_iterator_init(&des_list_it, gatt_client_classic_sdp_buffer); des_iterator_has_more(&des_list_it); des_iterator_next(&des_list_it)) {
3320                         uint8_t       *des_element;
3321                         uint8_t       *element;
3322                         uint32_t       uuid;
3323 
3324                         if (des_iterator_get_type(&des_list_it) != DE_DES) continue;
3325 
3326                         des_element = des_iterator_get_element(&des_list_it);
3327                         des_iterator_init(&prot_it, des_element);
3328                         element = des_iterator_get_element(&prot_it);
3329 
3330                         if (de_get_element_type(element) != DE_UUID) continue;
3331 
3332                         uuid = de_get_uuid32(element);
3333                         des_iterator_next(&prot_it);
3334                         // we assume that the even if there are both roles supported, remote device uses the same psm and avdtp version for both
3335                         switch (uuid){
3336                             case BLUETOOTH_PROTOCOL_L2CAP:
3337                                 if (!des_iterator_has_more(&prot_it)) continue;
3338                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &connection->l2cap_psm);
3339                                 break;
3340                             default:
3341                                 break;
3342                         }
3343                     }
3344                     break;
3345 
3346                 default:
3347                     break;
3348             }
3349         }
3350     }
3351 }
3352 
3353 static void gatt_client_classic_sdp_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
3354     gatt_client_t * gatt_client = gatt_client_classic_active_sdp_query;
3355     btstack_assert(gatt_client != NULL);
3356     uint8_t status;
3357 
3358     // TODO: handle sdp events, get l2cap psm
3359     switch (hci_event_packet_get_type(packet)){
3360         case SDP_EVENT_QUERY_ATTRIBUTE_VALUE:
3361             gatt_client_handle_sdp_client_query_attribute_value(gatt_client, packet);
3362             // TODO:
3363             return;
3364         case SDP_EVENT_QUERY_COMPLETE:
3365             status = sdp_event_query_complete_get_status(packet);
3366             gatt_client_classic_active_sdp_query = NULL;
3367             log_info("l2cap psm: %0x, status %02x", gatt_client->l2cap_psm, status);
3368             if (status != ERROR_CODE_SUCCESS) break;
3369             if (gatt_client->l2cap_psm == 0) {
3370                 status = SDP_SERVICE_NOT_FOUND;
3371                 break;
3372             }
3373             break;
3374         default:
3375             btstack_assert(false);
3376             return;
3377     }
3378 
3379     // done
3380     if (status == ERROR_CODE_SUCCESS){
3381         gatt_client->state = P_W4_L2CAP_CONNECTION;
3382         status = att_dispatch_classic_connect(gatt_client->addr, gatt_client->l2cap_psm, &gatt_client->l2cap_cid);
3383     }
3384     if (status != ERROR_CODE_SUCCESS) {
3385         gatt_client_classic_handle_connected(gatt_client, status);
3386     }
3387 }
3388 
3389 static void gatt_client_classic_sdp_start(void * context){
3390     gatt_client_classic_active_sdp_query = (gatt_client_t *) context;
3391     gatt_client_classic_active_sdp_query->state = P_W4_SDP_QUERY;
3392     sdp_client_query_uuid16(gatt_client_classic_sdp_handler, gatt_client_classic_active_sdp_query->addr, ORG_BLUETOOTH_SERVICE_GENERIC_ATTRIBUTE);
3393 }
3394 
3395 static void gatt_client_classic_emit_connected(void * context){
3396     gatt_client_t * gatt_client = (gatt_client_t *) context;
3397     gatt_client->state = P_READY;
3398     gatt_client_emit_connected(gatt_client->callback, ERROR_CODE_SUCCESS, gatt_client->addr_type, gatt_client->addr, gatt_client->con_handle);
3399 }
3400 
3401 uint8_t gatt_client_classic_connect(btstack_packet_handler_t callback, bd_addr_t addr){
3402     gatt_client_t * gatt_client = gatt_client_get_context_for_classic_addr(addr);
3403     if (gatt_client != NULL){
3404         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
3405     }
3406     gatt_client = btstack_memory_gatt_client_get();
3407     if (gatt_client == NULL){
3408         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
3409     }
3410     // init state
3411     gatt_client->bearer_type = ATT_BEARER_UNENHANCED_CLASSIC;
3412     gatt_client->con_handle = HCI_CON_HANDLE_INVALID;
3413     memcpy(gatt_client->addr, addr, 6);
3414     gatt_client->addr_type = BD_ADDR_TYPE_ACL;
3415     gatt_client->mtu = ATT_DEFAULT_MTU;
3416     gatt_client->security_level = LEVEL_0;
3417     gatt_client->mtu_state = MTU_AUTO_EXCHANGE_DISABLED;
3418     gatt_client->callback = callback;
3419 #ifdef ENABLE_GATT_OVER_EATT
3420     gatt_client->eatt_state = GATT_CLIENT_EATT_IDLE;
3421 #endif
3422     btstack_linked_list_add(&gatt_client_connections, (btstack_linked_item_t*)gatt_client);
3423 
3424     // schedule emitted event if already connected, otherwise
3425     bool already_connected = false;
3426     hci_connection_t * hci_connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3427     if (hci_connection != NULL){
3428         if (hci_connection->att_server.l2cap_cid != 0){
3429             already_connected = true;
3430         }
3431     }
3432     gatt_client->callback_request.context = gatt_client;
3433     if (already_connected){
3434         gatt_client->con_handle = hci_connection->con_handle;
3435         gatt_client->callback_request.callback = &gatt_client_classic_emit_connected;
3436         gatt_client->state = P_W2_EMIT_CONNECTED;
3437         btstack_run_loop_execute_on_main_thread(&gatt_client->callback_request);
3438     } else {
3439         gatt_client->callback_request.callback = &gatt_client_classic_sdp_start;
3440         gatt_client->state = P_W2_SDP_QUERY;
3441         sdp_client_register_query_callback(&gatt_client->callback_request);
3442     }
3443     return ERROR_CODE_SUCCESS;
3444 }
3445 
3446 uint8_t gatt_client_classic_disconnect(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
3447     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
3448     if (gatt_client == NULL){
3449         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3450     }
3451     gatt_client->callback = callback;
3452     return l2cap_disconnect(gatt_client->l2cap_cid);
3453 }
3454 #endif
3455 
3456 #ifdef ENABLE_GATT_OVER_EATT
3457 
3458 #define MAX_NR_EATT_CHANNELS 5
3459 
3460 static void gatt_client_le_enhanced_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
3461 
3462 static uint8_t gatt_client_le_enhanced_num_eatt_clients_in_state(gatt_client_t * gatt_client, gatt_client_state_t state){
3463     uint8_t num_clients = 0;
3464     btstack_linked_list_iterator_t it;
3465     btstack_linked_list_iterator_init(&it, &gatt_client->eatt_clients);
3466     while (btstack_linked_list_iterator_has_next(&it)){
3467         gatt_client_t * eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3468         if (eatt_client->state == state){
3469             num_clients++;
3470         }
3471     }
3472     return num_clients;
3473 }
3474 
3475 static void gatt_client_eatt_finalize(gatt_client_t * gatt_client) {
3476     // free eatt clients
3477     btstack_linked_list_iterator_t it;
3478     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
3479     while (btstack_linked_list_iterator_has_next(&it)) {
3480         gatt_client_t *eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3481         btstack_linked_list_iterator_remove(&it);
3482         btstack_memory_gatt_client_free(eatt_client);
3483     }
3484 }
3485 
3486 // all channels connected
3487 static void gatt_client_le_enhanced_handle_connected(gatt_client_t * gatt_client, uint8_t status) {
3488     if (status == ERROR_CODE_SUCCESS){
3489         uint8_t num_ready = gatt_client_le_enhanced_num_eatt_clients_in_state(gatt_client, P_READY);
3490         if (num_ready > 0){
3491             gatt_client->eatt_state = GATT_CLIENT_EATT_READY;
3492             // free unused channels
3493             btstack_linked_list_iterator_t it;
3494             btstack_linked_list_iterator_init(&it, &gatt_client_connections);
3495             while (btstack_linked_list_iterator_has_next(&it)) {
3496                 gatt_client_t *eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3497                 if (eatt_client->state == P_L2CAP_CLOSED){
3498                     btstack_linked_list_iterator_remove(&it);
3499                     btstack_memory_gatt_client_free(eatt_client);
3500                 }
3501             }
3502         } else {
3503             hci_connection_t * hci_connection = hci_connection_for_handle(gatt_client->con_handle);
3504             btstack_assert(hci_connection != NULL);
3505             if (hci_connection->att_server.incoming_connection_request){
3506                 hci_connection->att_server.incoming_connection_request = false;
3507                 log_info("Collision, retry in 100ms");
3508                 gatt_client->state = P_W2_L2CAP_CONNECT;
3509                 // set timer for retry
3510                 btstack_run_loop_set_timer(&gatt_client->gc_timeout, GATT_CLIENT_COLLISION_BACKOFF_MS);
3511                 btstack_run_loop_set_timer_handler(&gatt_client->gc_timeout, gatt_client_le_enhanced_retry);
3512                 btstack_run_loop_add_timer(&gatt_client->gc_timeout);
3513                 return;
3514             } else {
3515                 gatt_client->eatt_state = GATT_CLIENT_EATT_IDLE;
3516                 status = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES;
3517             }
3518         }
3519     } else {
3520         gatt_client_eatt_finalize(gatt_client);
3521         gatt_client->eatt_state = GATT_CLIENT_EATT_IDLE;
3522     }
3523 
3524     gatt_client_emit_connected(gatt_client->callback, status, gatt_client->addr_type, gatt_client->addr, gatt_client->con_handle);
3525 }
3526 
3527 // single channel disconnected
3528 static void gatt_client_le_enhanced_handle_ecbm_disconnected(gatt_client_t * gatt_client, gatt_client_t * eatt_client) {
3529 
3530     // report error
3531     gatt_client_report_error_if_pending(eatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
3532 
3533     // free memory
3534     btstack_linked_list_remove(&gatt_client->eatt_clients, (btstack_linked_item_t *) eatt_client);
3535     btstack_memory_gatt_client_free(eatt_client);
3536 
3537     // last channel
3538     if (btstack_linked_list_empty(&gatt_client->eatt_clients)){
3539         hci_connection_t * hci_connection = hci_connection_for_handle(gatt_client->con_handle);
3540         hci_connection->att_server.eatt_outgoing_active = false;
3541 
3542         if (gatt_client->eatt_state == GATT_CLIENT_EATT_READY) {
3543             // report disconnected if last channel closed
3544             uint8_t buffer[20];
3545             uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_disconnected, gatt_client->con_handle);
3546             (*gatt_client->callback)(HCI_EVENT_PACKET, 0, buffer, len);
3547         }
3548     }
3549 }
3550 
3551 static gatt_client_t * gatt_client_le_enhanced_get_context_for_l2cap_cid(uint16_t l2cap_cid, gatt_client_t ** out_eatt_client){
3552     btstack_linked_list_iterator_t it;
3553     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
3554     while (btstack_linked_list_iterator_has_next(&it)) {
3555         gatt_client_t * gatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3556         btstack_linked_list_iterator_t it2;
3557         btstack_linked_list_iterator_init(&it2, &gatt_client->eatt_clients);
3558         while (btstack_linked_list_iterator_has_next(&it2)) {
3559             gatt_client_t * eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it2);
3560             if (eatt_client->l2cap_cid == l2cap_cid){
3561                 *out_eatt_client = eatt_client;
3562                 return gatt_client;
3563             }
3564         }
3565     }
3566     return NULL;
3567 }
3568 
3569 static void gatt_client_le_enhanced_setup_l2cap_channel(gatt_client_t * gatt_client){
3570     uint8_t num_channels = gatt_client->eatt_num_clients;
3571 
3572     // setup channels
3573     uint16_t buffer_size_per_client = gatt_client->eatt_storage_size / num_channels;
3574     uint16_t max_mtu = (buffer_size_per_client - REPORT_PREBUFFER_HEADER) / 2;
3575     uint8_t * receive_buffers[MAX_NR_EATT_CHANNELS];
3576     uint16_t  new_cids[MAX_NR_EATT_CHANNELS];
3577     memset(gatt_client->eatt_storage_buffer, 0, gatt_client->eatt_storage_size);
3578     uint8_t i;
3579     for (i=0;i<gatt_client->eatt_num_clients; i++){
3580         receive_buffers[i] = &gatt_client->eatt_storage_buffer[REPORT_PREBUFFER_HEADER];
3581         gatt_client->eatt_storage_buffer += REPORT_PREBUFFER_HEADER + max_mtu;
3582     }
3583 
3584     log_info("%u EATT clients with receive buffer size %u", gatt_client->eatt_num_clients, buffer_size_per_client);
3585 
3586     uint8_t status = l2cap_ecbm_create_channels(&gatt_client_le_enhanced_packet_handler,
3587                                                 gatt_client->con_handle,
3588                                                 gatt_client->security_level,
3589                                                 BLUETOOTH_PSM_EATT, num_channels,
3590                                                 L2CAP_LE_AUTOMATIC_CREDITS,
3591                                                 buffer_size_per_client,
3592                                                 receive_buffers,
3593                                                 new_cids);
3594 
3595     if (status == ERROR_CODE_SUCCESS){
3596         i = 0;
3597         btstack_linked_list_iterator_t it;
3598         btstack_linked_list_iterator_init(&it, &gatt_client->eatt_clients);
3599         while (btstack_linked_list_iterator_has_next(&it)) {
3600             gatt_client_t *new_eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3601 
3602             // init state with new cid and transmit buffer
3603             new_eatt_client->bearer_type = ATT_BEARER_ENHANCED_LE;
3604             new_eatt_client->con_handle = gatt_client->con_handle;
3605             new_eatt_client->mtu = 64;
3606             new_eatt_client->security_level = LEVEL_0;
3607             new_eatt_client->mtu_state = MTU_AUTO_EXCHANGE_DISABLED;
3608             new_eatt_client->state = P_W4_L2CAP_CONNECTION;
3609             new_eatt_client->l2cap_cid = new_cids[i];
3610             new_eatt_client->eatt_storage_buffer = gatt_client->eatt_storage_buffer;
3611             gatt_client->eatt_storage_buffer += max_mtu;
3612             i++;
3613         }
3614         gatt_client->eatt_state = GATT_CLIENT_EATT_L2CAP_SETUP;
3615     } else {
3616         gatt_client_le_enhanced_handle_connected(gatt_client, status);
3617     }
3618 }
3619 
3620 static void gatt_client_le_enhanced_retry(btstack_timer_source_t * ts){
3621     gatt_client_t * gatt_client = gatt_client_for_timer(ts);
3622     if (gatt_client != NULL){
3623         gatt_client->state = P_W4_L2CAP_CONNECTION;
3624         gatt_client_le_enhanced_setup_l2cap_channel(gatt_client);
3625     }
3626 }
3627 
3628 static void gatt_client_le_enhanced_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
3629     gatt_client_t *gatt_client;
3630     gatt_client_t *eatt_client;
3631     hci_con_handle_t con_handle;
3632     uint16_t l2cap_cid;
3633     uint8_t status;
3634     gatt_client_characteristic_t characteristic;
3635     gatt_client_service_t service;
3636     switch (packet_type) {
3637         case HCI_EVENT_PACKET:
3638             switch (hci_event_packet_get_type(packet)) {
3639                 case GATT_EVENT_SERVICE_QUERY_RESULT:
3640                     con_handle = gatt_event_service_query_result_get_handle(packet);
3641                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3642                     btstack_assert(gatt_client != NULL);
3643                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W4_DONE);
3644                     gatt_event_service_query_result_get_service(packet, &service);
3645                     gatt_client->gatt_service_start_group_handle = service.start_group_handle;
3646                     gatt_client->gatt_service_end_group_handle = service.end_group_handle;
3647                     break;
3648                 case GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT:
3649                     con_handle = gatt_event_characteristic_value_query_result_get_handle(packet);
3650                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3651                     btstack_assert(gatt_client != NULL);
3652                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_DONE);
3653                     if (gatt_event_characteristic_value_query_result_get_value_length(packet) >= 1) {
3654                         gatt_client->gatt_server_supported_features = gatt_event_characteristic_value_query_result_get_value(packet)[0];
3655                     }
3656                     break;
3657                 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
3658                     con_handle = gatt_event_characteristic_query_result_get_handle(packet);
3659                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3660                     btstack_assert(gatt_client != NULL);
3661                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_DONE);
3662                     gatt_event_characteristic_query_result_get_characteristic(packet, &characteristic);
3663                     gatt_client->gatt_client_supported_features_handle = characteristic.value_handle;
3664                     break;
3665                 case GATT_EVENT_QUERY_COMPLETE:
3666                     con_handle = gatt_event_query_complete_get_handle(packet);
3667                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3668                     btstack_assert(gatt_client != NULL);
3669                     switch (gatt_client->eatt_state){
3670                         case GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W4_DONE:
3671                             if (gatt_client->gatt_service_start_group_handle == 0){
3672                                 gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
3673                             } else {
3674                                 gatt_client->eatt_state = GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W2_SEND;
3675                             }
3676                             break;
3677                         case GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_DONE:
3678                             if ((gatt_client->gatt_server_supported_features & 1) == 0) {
3679                                 gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
3680                             } else {
3681                                 gatt_client->eatt_state = GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W2_SEND;
3682                             }
3683                             break;
3684                         case GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_DONE:
3685                             if (gatt_client->gatt_client_supported_features_handle == 0){
3686                                 gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
3687                             } else {
3688                                 gatt_client->eatt_state = GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W2_SEND;
3689                             }
3690                             break;
3691                         case GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W4_DONE:
3692                             gatt_client_le_enhanced_setup_l2cap_channel(gatt_client);
3693                             break;
3694                         default:
3695                             break;
3696                     }
3697                     break;
3698                 case L2CAP_EVENT_ECBM_CHANNEL_OPENED:
3699                     l2cap_cid = l2cap_event_ecbm_channel_opened_get_local_cid(packet);
3700                     gatt_client = gatt_client_le_enhanced_get_context_for_l2cap_cid(l2cap_cid, &eatt_client);
3701 
3702                     btstack_assert(gatt_client != NULL);
3703                     btstack_assert(eatt_client != NULL);
3704                     btstack_assert(eatt_client->state == P_W4_L2CAP_CONNECTION);
3705 
3706                     status = l2cap_event_channel_opened_get_status(packet);
3707                     if (status == ERROR_CODE_SUCCESS){
3708                         eatt_client->state = P_READY;
3709                         eatt_client->mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
3710                     } else {
3711                         eatt_client->state = P_L2CAP_CLOSED;
3712                     }
3713                     // connected if opened event for all channels received
3714                     if (gatt_client_le_enhanced_num_eatt_clients_in_state(gatt_client, P_W4_L2CAP_CONNECTION) == 0){
3715                         gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_SUCCESS);
3716                     }
3717                     break;
3718                 case L2CAP_EVENT_CHANNEL_CLOSED:
3719                     l2cap_cid = l2cap_event_channel_closed_get_local_cid(packet);
3720                     gatt_client = gatt_client_le_enhanced_get_context_for_l2cap_cid(l2cap_cid, &eatt_client);
3721                     btstack_assert(gatt_client != NULL);
3722                     btstack_assert(eatt_client != NULL);
3723                     gatt_client_le_enhanced_handle_ecbm_disconnected(gatt_client, eatt_client);
3724                     break;
3725                 default:
3726                     break;
3727             }
3728             break;
3729         case L2CAP_DATA_PACKET:
3730             gatt_client = gatt_client_le_enhanced_get_context_for_l2cap_cid(channel, &eatt_client);
3731             btstack_assert(gatt_client != NULL);
3732             btstack_assert(eatt_client != NULL);
3733             gatt_client_handle_att_response(eatt_client, packet, size);
3734             gatt_client_run();
3735             break;
3736         default:
3737             break;
3738     }
3739 }
3740 
3741 static bool gatt_client_le_enhanced_handle_can_send_query(gatt_client_t * gatt_client){
3742     uint8_t status = ERROR_CODE_SUCCESS;
3743     uint8_t gatt_client_supported_features = 0x06; // eatt + multiple value notifications
3744     switch (gatt_client->eatt_state){
3745         case GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W2_SEND:
3746             gatt_client->gatt_service_start_group_handle = 0;
3747             gatt_client->eatt_state = GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W4_DONE;
3748             status = gatt_client_discover_primary_services_by_uuid16(&gatt_client_le_enhanced_packet_handler,
3749                                                                      gatt_client->con_handle,
3750                                                                      ORG_BLUETOOTH_SERVICE_GENERIC_ATTRIBUTE);
3751             break;
3752         case GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W2_SEND:
3753             gatt_client->gatt_server_supported_features = 0;
3754             gatt_client->eatt_state = GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_DONE;
3755             status = gatt_client_read_value_of_characteristics_by_uuid16(&gatt_client_le_enhanced_packet_handler,
3756                                                                          gatt_client->con_handle,
3757                                                                          gatt_client->gatt_service_start_group_handle,
3758                                                                          gatt_client->gatt_service_end_group_handle,
3759                                                                          ORG_BLUETOOTH_CHARACTERISTIC_SERVER_SUPPORTED_FEATURES);
3760             return true;
3761         case GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W2_SEND:
3762             gatt_client->gatt_client_supported_features_handle = 0;
3763             gatt_client->eatt_state = GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_DONE;
3764             status = gatt_client_discover_characteristics_for_handle_range_by_uuid16(&gatt_client_le_enhanced_packet_handler,
3765                                                                                      gatt_client->con_handle,
3766                                                                                      gatt_client->gatt_service_start_group_handle,
3767                                                                                      gatt_client->gatt_service_end_group_handle,
3768                                                                                      ORG_BLUETOOTH_CHARACTERISTIC_CLIENT_SUPPORTED_FEATURES);
3769             return true;
3770         case GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W2_SEND:
3771             gatt_client->eatt_state = GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W4_DONE;
3772             status = gatt_client_write_value_of_characteristic(&gatt_client_le_enhanced_packet_handler, gatt_client->con_handle,
3773                                                                gatt_client->gatt_client_supported_features_handle, 1,
3774                                                                &gatt_client_supported_features);
3775             return true;
3776         default:
3777             break;
3778     }
3779     btstack_assert(status == ERROR_CODE_SUCCESS);
3780     UNUSED(status);
3781     return false;
3782 }
3783 
3784 uint8_t gatt_client_le_enhanced_connect(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint8_t num_channels, uint8_t * storage_buffer, uint16_t storage_size) {
3785     gatt_client_t * gatt_client;
3786     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3787     if (status != ERROR_CODE_SUCCESS){
3788         return status;
3789     }
3790 
3791     if (gatt_client->eatt_state != GATT_CLIENT_EATT_IDLE){
3792         return ERROR_CODE_COMMAND_DISALLOWED;
3793     }
3794 
3795     // need one buffer for sending and one for receiving. Receiving includes pre-buffer for reports
3796     uint16_t buffer_size_per_client = storage_size / num_channels;
3797     uint16_t max_mtu = (buffer_size_per_client - REPORT_PREBUFFER_HEADER) / 2;
3798     if (max_mtu < 64) {
3799         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
3800     }
3801 
3802     if ((num_channels == 0) || (num_channels > MAX_NR_EATT_CHANNELS)){
3803         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
3804     }
3805 
3806     // create max num_channel eatt clients
3807     uint8_t i;
3808     btstack_linked_list_t eatt_clients = NULL;
3809     for (i=0;i<num_channels;i++) {
3810         gatt_client_t * new_gatt_client = btstack_memory_gatt_client_get();
3811         if (new_gatt_client == NULL) {
3812             break;
3813         }
3814         btstack_linked_list_add(&eatt_clients, (btstack_linked_item_t*)new_gatt_client);
3815     }
3816 
3817     if (i != num_channels){
3818         while (true){
3819             gatt_client = (gatt_client_t *) btstack_linked_list_pop(&eatt_clients);
3820             if (gatt_client == NULL) {
3821                 break;
3822             }
3823             btstack_memory_gatt_client_free(gatt_client);
3824         }
3825         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
3826     }
3827 
3828     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
3829     hci_connection->att_server.eatt_outgoing_active = true;
3830 
3831     gatt_client->callback = callback;
3832     gatt_client->eatt_num_clients   = num_channels;
3833     gatt_client->eatt_storage_buffer = storage_buffer;
3834     gatt_client->eatt_storage_size   = storage_size;
3835     gatt_client->eatt_clients = eatt_clients;
3836     gatt_client->eatt_state = GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W2_SEND;
3837     gatt_client_notify_can_send_query(gatt_client);
3838 
3839     return ERROR_CODE_SUCCESS;
3840 }
3841 
3842 #endif
3843 
3844 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
3845 void gatt_client_att_packet_handler_fuzz(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
3846     gatt_client_att_packet_handler(packet_type, handle, packet, size);
3847 }
3848 
3849 uint8_t gatt_client_get_client(hci_con_handle_t con_handle, gatt_client_t ** out_gatt_client){
3850     uint8_t status = gatt_client_provide_context_for_handle(con_handle, out_gatt_client);
3851     return status;
3852 }
3853 #endif
3854