xref: /btstack/src/ble/gatt_client.c (revision 185497a5c58bebd5c4096b5eddb330eaea602330)
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 HX
965     uint8_t packet[26];
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, include_handle);
970     hci_event_builder_add_16(&context, start_group_handle);
971     hci_event_builder_add_16(&context, end_group_handle);
972     hci_event_builder_add_128(&context, uuid128);
973     emit_event_new(gatt_client->callback, packet, hci_event_builder_get_length(&context));
974 }
975 
976 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,
977                                                         uint16_t properties, const uint8_t * uuid128){
978     // @format H22Y
979     uint8_t packet[32];
980     hci_event_builder_context_t context;
981     hci_event_builder_init(&context, packet, sizeof(packet), GATT_EVENT_CHARACTERISTIC_QUERY_RESULT, 0);
982     hci_event_builder_add_con_handle(&context, gatt_client->con_handle);
983     hci_event_builder_add_16(&context, gatt_client->service_id);
984     hci_event_builder_add_16(&context, gatt_client->connection_id);
985     hci_event_builder_add_16(&context, start_handle);
986     hci_event_builder_add_16(&context, value_handle);
987     hci_event_builder_add_16(&context, end_handle);
988     hci_event_builder_add_16(&context, properties);
989     hci_event_builder_add_128(&context, uuid128);
990     emit_event_new(gatt_client->callback, packet, hci_event_builder_get_length(&context));
991 }
992 
993 static void emit_gatt_all_characteristic_descriptors_result_event(
994         gatt_client_t * gatt_client, uint16_t descriptor_handle, const uint8_t * uuid128){
995     // @format HZ
996     uint8_t packet[22];
997     hci_event_builder_context_t context;
998     hci_event_builder_init(&context, packet, sizeof(packet), GATT_EVENT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT, 0);
999     hci_event_builder_add_con_handle(&context, gatt_client->con_handle);
1000     hci_event_builder_add_16(&context, descriptor_handle);
1001     hci_event_builder_add_128(&context, uuid128);
1002     emit_event_new(gatt_client->callback, packet, hci_event_builder_get_length(&context));
1003 }
1004 
1005 static void emit_gatt_mtu_exchanged_result_event(gatt_client_t * gatt_client, uint16_t new_mtu){
1006     // @format H2
1007     uint8_t packet[6];
1008     packet[0] = GATT_EVENT_MTU;
1009     packet[1] = sizeof(packet) - 2u;
1010     little_endian_store_16(packet, 2, gatt_client->con_handle);
1011     little_endian_store_16(packet, 4, new_mtu);
1012     att_dispatch_client_mtu_exchanged(gatt_client->con_handle, new_mtu);
1013     emit_event_new(gatt_client->callback, packet, sizeof(packet));
1014 }
1015 
1016 // helper
1017 static void gatt_client_handle_transaction_complete(gatt_client_t *gatt_client, uint8_t att_status) {
1018     gatt_client->state = P_READY;
1019     gatt_client_timeout_stop(gatt_client);
1020     emit_gatt_complete_event(gatt_client, att_status);
1021     gatt_client_notify_can_send_query(gatt_client);
1022 }
1023 
1024 // @return packet pointer
1025 // @note assume that value is part of an l2cap buffer - overwrite HCI + L2CAP packet headers
1026 #define CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE 8
1027 static uint8_t *
1028 setup_characteristic_value_packet(const gatt_client_t *gatt_client, uint8_t type, uint16_t attribute_handle,
1029                                   uint8_t *value, uint16_t length) {
1030 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1031     // copy value into test packet for testing
1032     static uint8_t packet[1000];
1033     memcpy(&packet[CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE], value, length);
1034 #else
1035     // before the value inside the ATT PDU
1036     uint8_t * packet = value - CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE;
1037 #endif
1038     packet[0] = type;
1039     packet[1] = CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE - 2 + length;
1040     little_endian_store_16(packet, 2, gatt_client->con_handle);
1041     little_endian_store_16(packet, 4, attribute_handle);
1042     little_endian_store_16(packet, 6, length);
1043     return packet;
1044 }
1045 
1046 // @return packet pointer
1047 // @note assume that value is part of an l2cap buffer - overwrite parts of the HCI/L2CAP/ATT packet (4/4/3) bytes
1048 #define LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE 10
1049 
1050 // L2CAP Header (4) + ACL Header (4) => 8 bytes
1051 #if !defined(HCI_INCOMING_PRE_BUFFER_SIZE) || ((HCI_INCOMING_PRE_BUFFER_SIZE < LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE - 8))
1052 #error "Long Characteristic reads requires HCI_INCOMING_PRE_BUFFER_SIZE >= 2"
1053 #endif
1054 
1055 static uint8_t *
1056 setup_long_characteristic_value_packet(const gatt_client_t *gatt_client, uint8_t type, uint16_t attribute_handle,
1057                                        uint16_t offset, uint8_t *value, uint16_t length) {
1058 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1059     // avoid using pre ATT headers.
1060     // copy value into test packet for testing
1061     static uint8_t packet[1000];
1062     memcpy(&packet[LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE], value, length);
1063 #else
1064     // before the value inside the ATT PDU
1065     uint8_t * packet = value - LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE;
1066 #endif
1067     packet[0] = type;
1068     packet[1] = LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE - 2 + length;
1069     little_endian_store_16(packet, 2, gatt_client->con_handle);
1070     little_endian_store_16(packet, 4, attribute_handle);
1071     little_endian_store_16(packet, 6, offset);
1072     little_endian_store_16(packet, 8, length);
1073     return packet;
1074 }
1075 
1076 #if (LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE > CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE)
1077 #define REPORT_PREBUFFER_HEADER LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE
1078 #else
1079 #define REPORT_PREBUFFER_HEADER CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE
1080 #endif
1081 
1082 ///
1083 static void report_gatt_services(gatt_client_t * gatt_client, uint8_t * packet, uint16_t size){
1084     if (size < 2) return;
1085     uint8_t attr_length = packet[1];
1086     uint8_t uuid_length = attr_length - 4u;
1087 
1088     int i;
1089     for (i = 2; (i+attr_length) <= size; i += attr_length){
1090         uint16_t start_group_handle = little_endian_read_16(packet,i);
1091         uint16_t end_group_handle   = little_endian_read_16(packet,i+2);
1092         uint8_t  uuid128[16];
1093         uint16_t uuid16 = 0;
1094 
1095         if (uuid_length == 2u){
1096             uuid16 = little_endian_read_16(packet, i+4);
1097             uuid_add_bluetooth_prefix((uint8_t*) &uuid128, uuid16);
1098         } else if (uuid_length == 16u) {
1099             reverse_128(&packet[i+4], uuid128);
1100         } else {
1101             return;
1102         }
1103         emit_gatt_service_query_result_event(gatt_client, start_group_handle, end_group_handle, uuid128);
1104     }
1105 }
1106 
1107 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){
1108     uint8_t uuid128[16];
1109     uint16_t uuid16 = 0;
1110     if (uuid_length == 2u){
1111         uuid16 = little_endian_read_16(uuid, 0);
1112         uuid_add_bluetooth_prefix((uint8_t*) uuid128, uuid16);
1113     } else if (uuid_length == 16u){
1114         reverse_128(uuid, uuid128);
1115     } else {
1116         return;
1117     }
1118 
1119     if (gatt_client->filter_with_uuid && (memcmp(gatt_client->uuid128, uuid128, 16) != 0)) return;
1120 
1121     gatt_client->characteristic_properties = properties;
1122     gatt_client->characteristic_start_handle = start_handle;
1123     gatt_client->attribute_handle = value_handle;
1124 
1125     if (gatt_client->filter_with_uuid) return;
1126 
1127     gatt_client->uuid16 = uuid16;
1128     (void)memcpy(gatt_client->uuid128, uuid128, 16);
1129 }
1130 
1131 static void report_gatt_characteristic_end_found(gatt_client_t * gatt_client, uint16_t end_handle){
1132     // TODO: stop searching if filter and uuid found
1133 
1134     if (!gatt_client->characteristic_start_handle) return;
1135 
1136     emit_gatt_characteristic_query_result_event(gatt_client, gatt_client->characteristic_start_handle, gatt_client->attribute_handle,
1137                                                 end_handle, gatt_client->characteristic_properties, gatt_client->uuid128);
1138 
1139     gatt_client->characteristic_start_handle = 0;
1140 }
1141 
1142 
1143 static void report_gatt_characteristics(gatt_client_t * gatt_client, uint8_t * packet, uint16_t size){
1144     if (size < 2u) return;
1145     uint8_t attr_length = packet[1];
1146     if ((attr_length != 7u) && (attr_length != 21u)) return;
1147     uint8_t uuid_length = attr_length - 5u;
1148     int i;
1149     for (i = 2u; (i + attr_length) <= size; i += attr_length){
1150         uint16_t start_handle = little_endian_read_16(packet, i);
1151         uint8_t  properties = packet[i+2];
1152         uint16_t value_handle = little_endian_read_16(packet, i+3);
1153         report_gatt_characteristic_end_found(gatt_client, start_handle - 1u);
1154         report_gatt_characteristic_start_found(gatt_client, start_handle, properties, value_handle, &packet[i + 5],
1155                                                uuid_length);
1156     }
1157 }
1158 
1159 static void report_gatt_included_service_uuid16(gatt_client_t * gatt_client, uint16_t include_handle, uint16_t uuid16){
1160     uint8_t normalized_uuid128[16];
1161     uuid_add_bluetooth_prefix(normalized_uuid128, uuid16);
1162     emit_gatt_included_service_query_result_event(gatt_client, include_handle, gatt_client->query_start_handle,
1163                                                   gatt_client->query_end_handle, normalized_uuid128);
1164 }
1165 
1166 static void report_gatt_included_service_uuid128(gatt_client_t * gatt_client, uint16_t include_handle, const uint8_t * uuid128){
1167     emit_gatt_included_service_query_result_event(gatt_client, include_handle, gatt_client->query_start_handle,
1168                                                   gatt_client->query_end_handle, uuid128);
1169 }
1170 
1171 // @note assume that value is part of an l2cap buffer - overwrite parts of the HCI/L2CAP/ATT packet (4/4/3) bytes
1172 static void report_gatt_notification(gatt_client_t *gatt_client, uint16_t value_handle, uint8_t *value, int length) {
1173 	if (!gatt_client_accept_server_message(gatt_client)) return;
1174     uint8_t * packet = setup_characteristic_value_packet(gatt_client, GATT_EVENT_NOTIFICATION, value_handle,
1175                                                          value, length);
1176     emit_event_to_registered_listeners(gatt_client->con_handle, value_handle, packet, CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE + length);
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_indication(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 #ifdef ENABLE_GATT_CLIENT_SERVICE_CHANGED
1183     // Directly Handle GATT Service Changed and Database Hash indications
1184     if (value_handle == gatt_client->gatt_service_database_hash_value_handle){
1185         gatt_client_service_emit_database_hash(gatt_client, value, length);
1186     }
1187     if (value_handle == gatt_client->gatt_service_changed_value_handle){
1188         gatt_client_service_emit_service_changed(gatt_client, value, length);
1189     }
1190 #endif
1191     uint8_t * packet = setup_characteristic_value_packet(gatt_client, GATT_EVENT_INDICATION, value_handle,
1192                                                          value, length);
1193     emit_event_to_registered_listeners(gatt_client->con_handle, value_handle, packet, CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE + length);
1194 }
1195 
1196 // @note assume that value is part of an l2cap buffer - overwrite parts of the HCI/L2CAP/ATT packet (4/4/3) bytes
1197 static void report_gatt_characteristic_value(gatt_client_t * gatt_client, uint16_t attribute_handle, uint8_t * value, uint16_t length){
1198     uint8_t * packet = setup_characteristic_value_packet(
1199             gatt_client, GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT, attribute_handle, value, length);
1200     emit_event_new(gatt_client->callback, packet, CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE + length);
1201 }
1202 
1203 // @note assume that value is part of an l2cap buffer - overwrite parts of the HCI/L2CAP/ATT packet (4/4/3) bytes
1204 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){
1205     uint8_t * packet = setup_long_characteristic_value_packet(gatt_client,
1206                                                               GATT_EVENT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT,
1207                                                               attribute_handle, value_offset,
1208                                                               blob, blob_length);
1209     emit_event_new(gatt_client->callback, packet, blob_length + LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE);
1210 }
1211 
1212 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){
1213     UNUSED(value_offset);
1214     uint8_t * packet = setup_characteristic_value_packet(gatt_client, GATT_EVENT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT,
1215                                                          descriptor_handle, value,
1216                                                          value_length);
1217     emit_event_new(gatt_client->callback, packet, value_length + 8u);
1218 }
1219 
1220 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){
1221     uint8_t * packet = setup_long_characteristic_value_packet(gatt_client,
1222                                                               GATT_EVENT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT,
1223                                                               descriptor_handle, value_offset,
1224                                                               blob, blob_length);
1225     emit_event_new(gatt_client->callback, packet, blob_length + LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE);
1226 }
1227 
1228 static void report_gatt_all_characteristic_descriptors(gatt_client_t * gatt_client, uint8_t * packet, uint16_t size, uint16_t pair_size){
1229     int i;
1230     for (i = 0u; (i + pair_size) <= size; i += pair_size){
1231         uint16_t descriptor_handle = little_endian_read_16(packet,i);
1232         uint8_t uuid128[16];
1233         uint16_t uuid16 = 0;
1234         if (pair_size == 4u){
1235             uuid16 = little_endian_read_16(packet,i+2);
1236             uuid_add_bluetooth_prefix(uuid128, uuid16);
1237         } else {
1238             reverse_128(&packet[i+2], uuid128);
1239         }
1240         emit_gatt_all_characteristic_descriptors_result_event(gatt_client, descriptor_handle, uuid128);
1241     }
1242 
1243 }
1244 
1245 static bool is_query_done(gatt_client_t * gatt_client, uint16_t last_result_handle){
1246     return last_result_handle >= gatt_client->end_group_handle;
1247 }
1248 
1249 static void trigger_next_query(gatt_client_t * gatt_client, uint16_t last_result_handle, gatt_client_state_t next_query_state){
1250     if (is_query_done(gatt_client, last_result_handle)){
1251         gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1252         return;
1253     }
1254     // next
1255     gatt_client->start_group_handle = last_result_handle + 1u;
1256     gatt_client->state = next_query_state;
1257 }
1258 
1259 static void trigger_next_included_service_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1260     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_INCLUDED_SERVICE_QUERY);
1261 }
1262 
1263 static void trigger_next_service_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1264     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_SERVICE_QUERY);
1265 }
1266 
1267 static void trigger_next_service_by_uuid_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1268     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_SERVICE_WITH_UUID_QUERY);
1269 }
1270 
1271 static void trigger_next_characteristic_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1272     if (is_query_done(gatt_client, last_result_handle)){
1273         // report last characteristic
1274         report_gatt_characteristic_end_found(gatt_client, gatt_client->end_group_handle);
1275     }
1276     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY);
1277 }
1278 
1279 static void trigger_next_characteristic_descriptor_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1280     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY);
1281 }
1282 
1283 static void trigger_next_read_by_type_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1284     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_READ_BY_TYPE_REQUEST);
1285 }
1286 
1287 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){
1288     gatt_client->attribute_offset += write_blob_length(gatt_client);
1289     uint16_t next_blob_length =  write_blob_length(gatt_client);
1290 
1291     if (next_blob_length == 0u){
1292         gatt_client->state = done_state;
1293         return;
1294     }
1295     gatt_client->state = next_query_state;
1296 }
1297 
1298 static void trigger_next_blob_query(gatt_client_t * gatt_client, gatt_client_state_t next_query_state, uint16_t received_blob_length){
1299 
1300     uint16_t max_blob_length = gatt_client->mtu - 1u;
1301     if (received_blob_length < max_blob_length){
1302         gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1303         return;
1304     }
1305 
1306     gatt_client->attribute_offset += received_blob_length;
1307     gatt_client->state = next_query_state;
1308 }
1309 
1310 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){
1311     notification->callback = callback;
1312     notification->con_handle = con_handle;
1313     if (characteristic == NULL){
1314         notification->attribute_handle = GATT_CLIENT_ANY_VALUE_HANDLE;
1315     } else {
1316         notification->attribute_handle = characteristic->value_handle;
1317     }
1318     btstack_linked_list_add(&gatt_client_value_listeners, (btstack_linked_item_t*) notification);
1319 }
1320 
1321 void gatt_client_stop_listening_for_characteristic_value_updates(gatt_client_notification_t * notification){
1322     btstack_linked_list_remove(&gatt_client_value_listeners, (btstack_linked_item_t*) notification);
1323 }
1324 
1325 static bool is_value_valid(gatt_client_t *gatt_client, uint8_t *packet, uint16_t size){
1326     uint16_t attribute_handle = little_endian_read_16(packet, 1);
1327     uint16_t value_offset = little_endian_read_16(packet, 3);
1328 
1329     if (gatt_client->attribute_handle != attribute_handle) return false;
1330     if (gatt_client->attribute_offset != value_offset) return false;
1331     return memcmp(&gatt_client->attribute_value[gatt_client->attribute_offset], &packet[5], size - 5u) == 0u;
1332 }
1333 
1334 #ifdef ENABLE_LE_SIGNED_WRITE
1335 static void gatt_client_run_for_client_start_signed_write(gatt_client_t *gatt_client) {
1336     sm_key_t csrk;
1337     le_device_db_local_csrk_get(gatt_client->le_device_index, csrk);
1338     uint32_t sign_counter = le_device_db_local_counter_get(gatt_client->le_device_index);
1339     gatt_client->state = P_W4_CMAC_RESULT;
1340     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);
1341 }
1342 #endif
1343 
1344 // returns true if packet was sent
1345 static bool gatt_client_run_for_gatt_client(gatt_client_t * gatt_client){
1346 
1347     // wait until re-encryption is complete
1348     if (gap_reconnect_security_setup_active(gatt_client->con_handle)) return false;
1349 
1350     // wait until re-encryption is complete
1351     if (gatt_client->reencryption_active) return false;
1352 
1353     // wait until pairing complete (either reactive authentication or due to required security level)
1354     if (gatt_client->wait_for_authentication_complete) return false;
1355 
1356     bool client_request_pending = gatt_client->state != P_READY;
1357 
1358     // verify security level for Mandatory Authentication over LE
1359     bool check_security;
1360     switch (gatt_client->bearer_type){
1361         case ATT_BEARER_UNENHANCED_LE:
1362             check_security = true;
1363             break;
1364         default:
1365             check_security = false;
1366             break;
1367     }
1368     if (client_request_pending && (gatt_client_required_security_level > gatt_client->security_level) && check_security){
1369         log_info("Trigger pairing, current security level %u, required %u\n", gatt_client->security_level, gatt_client_required_security_level);
1370         gatt_client->wait_for_authentication_complete = true;
1371         // set att error code for pairing failure based on required level
1372         switch (gatt_client_required_security_level){
1373             case LEVEL_4:
1374             case LEVEL_3:
1375                 gatt_client->pending_error_code = ATT_ERROR_INSUFFICIENT_AUTHENTICATION;
1376                 break;
1377             default:
1378                 gatt_client->pending_error_code = ATT_ERROR_INSUFFICIENT_ENCRYPTION;
1379                 break;
1380         }
1381         sm_request_pairing(gatt_client->con_handle);
1382         // sm probably just sent a pdu
1383         return true;
1384     }
1385 
1386     switch (gatt_client->mtu_state) {
1387         case SEND_MTU_EXCHANGE:
1388             gatt_client->mtu_state = SENT_MTU_EXCHANGE;
1389             att_exchange_mtu_request(gatt_client);
1390             return true;
1391         case SENT_MTU_EXCHANGE:
1392             return false;
1393         default:
1394             break;
1395     }
1396 
1397     if (gatt_client->send_confirmation){
1398         gatt_client->send_confirmation = false;
1399         att_confirmation(gatt_client);
1400         return true;
1401     }
1402 
1403     // check MTU for writes
1404     switch (gatt_client->state){
1405         case P_W2_SEND_WRITE_CHARACTERISTIC_VALUE:
1406         case P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR:
1407             if (gatt_client->attribute_length <= (gatt_client->mtu - 3u)) break;
1408             log_error("gatt_client_run: value len %u > MTU %u - 3\n", gatt_client->attribute_length,gatt_client->mtu);
1409             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH);
1410             return false;
1411         default:
1412             break;
1413     }
1414 
1415     bool packet_sent = true;
1416     bool done = true;
1417     switch (gatt_client->state){
1418         case P_W2_SEND_SERVICE_QUERY:
1419             gatt_client->state = P_W4_SERVICE_QUERY_RESULT;
1420             send_gatt_services_request(gatt_client);
1421             break;
1422 
1423         case P_W2_SEND_SERVICE_WITH_UUID_QUERY:
1424             gatt_client->state = P_W4_SERVICE_WITH_UUID_RESULT;
1425             send_gatt_services_by_uuid_request(gatt_client);
1426             break;
1427 
1428         case P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY:
1429             gatt_client->state = P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT;
1430             send_gatt_characteristic_request(gatt_client);
1431             break;
1432 
1433         case P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY:
1434             gatt_client->state = P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT;
1435             send_gatt_characteristic_request(gatt_client);
1436             break;
1437 
1438         case P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY:
1439             gatt_client->state = P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT;
1440             send_gatt_characteristic_descriptor_request(gatt_client);
1441             break;
1442 
1443         case P_W2_SEND_INCLUDED_SERVICE_QUERY:
1444             gatt_client->state = P_W4_INCLUDED_SERVICE_QUERY_RESULT;
1445             send_gatt_included_service_request(gatt_client);
1446             break;
1447 
1448         case P_W2_SEND_INCLUDED_SERVICE_WITH_UUID_QUERY:
1449             gatt_client->state = P_W4_INCLUDED_SERVICE_UUID_WITH_QUERY_RESULT;
1450             send_gatt_included_service_uuid_request(gatt_client);
1451             break;
1452 
1453         case P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY:
1454             gatt_client->state = P_W4_READ_CHARACTERISTIC_VALUE_RESULT;
1455             send_gatt_read_characteristic_value_request(gatt_client);
1456             break;
1457 
1458         case P_W2_SEND_READ_BLOB_QUERY:
1459             gatt_client->state = P_W4_READ_BLOB_RESULT;
1460             send_gatt_read_blob_request(gatt_client);
1461             break;
1462 
1463         case P_W2_SEND_READ_BY_TYPE_REQUEST:
1464             gatt_client->state = P_W4_READ_BY_TYPE_RESPONSE;
1465             send_gatt_read_by_type_request(gatt_client);
1466             break;
1467 
1468         case P_W2_SEND_READ_MULTIPLE_REQUEST:
1469             gatt_client->state = P_W4_READ_MULTIPLE_RESPONSE;
1470             send_gatt_read_multiple_request(gatt_client);
1471             break;
1472 
1473 #ifdef ENABLE_GATT_OVER_EATT
1474         case P_W2_SEND_READ_MULTIPLE_VARIABLE_REQUEST:
1475             gatt_client->state = P_W4_READ_MULTIPLE_VARIABLE_RESPONSE;
1476             send_gatt_read_multiple_variable_request(gatt_client);
1477             break;
1478 #endif
1479 
1480         case P_W2_SEND_WRITE_CHARACTERISTIC_VALUE:
1481             gatt_client->state = P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT;
1482             send_gatt_write_attribute_value_request(gatt_client);
1483             break;
1484 
1485         case P_W2_PREPARE_WRITE:
1486             gatt_client->state = P_W4_PREPARE_WRITE_RESULT;
1487             send_gatt_prepare_write_request(gatt_client);
1488             break;
1489 
1490         case P_W2_PREPARE_WRITE_SINGLE:
1491             gatt_client->state = P_W4_PREPARE_WRITE_SINGLE_RESULT;
1492             send_gatt_prepare_write_request(gatt_client);
1493             break;
1494 
1495         case P_W2_PREPARE_RELIABLE_WRITE:
1496             gatt_client->state = P_W4_PREPARE_RELIABLE_WRITE_RESULT;
1497             send_gatt_prepare_write_request(gatt_client);
1498             break;
1499 
1500         case P_W2_EXECUTE_PREPARED_WRITE:
1501             gatt_client->state = P_W4_EXECUTE_PREPARED_WRITE_RESULT;
1502             send_gatt_execute_write_request(gatt_client);
1503             break;
1504 
1505         case P_W2_CANCEL_PREPARED_WRITE:
1506             gatt_client->state = P_W4_CANCEL_PREPARED_WRITE_RESULT;
1507             send_gatt_cancel_prepared_write_request(gatt_client);
1508             break;
1509 
1510         case P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH:
1511             gatt_client->state = P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT;
1512             send_gatt_cancel_prepared_write_request(gatt_client);
1513             break;
1514 
1515 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
1516         case P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY:
1517             // use Find Information
1518             gatt_client->gatt_client_state = P_W4_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT;
1519             send_gatt_characteristic_descriptor_request(gatt_client);
1520 #else
1521         case P_W2_SEND_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY:
1522             // Use Read By Type
1523             gatt_client->state = P_W4_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT;
1524             send_gatt_read_client_characteristic_configuration_request(gatt_client);
1525 #endif
1526             break;
1527 
1528         case P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY:
1529             gatt_client->state = P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT;
1530             send_gatt_read_characteristic_descriptor_request(gatt_client);
1531             break;
1532 
1533         case P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY:
1534             gatt_client->state = P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT;
1535             send_gatt_read_blob_request(gatt_client);
1536             break;
1537 
1538         case P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR:
1539             gatt_client->state = P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT;
1540             send_gatt_write_attribute_value_request(gatt_client);
1541             break;
1542 
1543         case P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION:
1544             gatt_client->state = P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT;
1545             send_gatt_write_client_characteristic_configuration_request(gatt_client);
1546             break;
1547 
1548         case P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR:
1549             gatt_client->state = P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT;
1550             send_gatt_prepare_write_request(gatt_client);
1551             break;
1552 
1553         case P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR:
1554             gatt_client->state = P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT;
1555             send_gatt_execute_write_request(gatt_client);
1556             break;
1557 
1558 #ifdef ENABLE_LE_SIGNED_WRITE
1559         case P_W4_IDENTITY_RESOLVING:
1560             log_info("P_W4_IDENTITY_RESOLVING - state %x", sm_identity_resolving_state(gatt_client->con_handle));
1561             switch (sm_identity_resolving_state(gatt_client->con_handle)){
1562                 case IRK_LOOKUP_SUCCEEDED:
1563                     gatt_client->le_device_index = sm_le_device_index(gatt_client->con_handle);
1564                     gatt_client->state = P_W4_CMAC_READY;
1565                     if (sm_cmac_ready()){
1566                         gatt_client_run_for_client_start_signed_write(gatt_client);
1567                     }
1568                     break;
1569                 case IRK_LOOKUP_FAILED:
1570                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_BONDING_INFORMATION_MISSING);
1571                     break;
1572                 default:
1573                     break;
1574             }
1575             packet_sent = false;
1576             break;
1577 
1578         case P_W4_CMAC_READY:
1579             if (sm_cmac_ready()){
1580                 gatt_client_run_for_client_start_signed_write(gatt_client);
1581             }
1582             packet_sent = false;
1583             break;
1584 
1585         case P_W2_SEND_SIGNED_WRITE: {
1586             gatt_client->state = P_W4_SEND_SIGNED_WRITE_DONE;
1587             // bump local signing counter
1588             uint32_t sign_counter = le_device_db_local_counter_get(gatt_client->le_device_index);
1589             le_device_db_local_counter_set(gatt_client->le_device_index, sign_counter + 1);
1590             // send signed write command
1591             send_gatt_signed_write_request(gatt_client, sign_counter);
1592             // finally, notifiy client that write is complete
1593             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1594             break;
1595         }
1596 #endif
1597         default:
1598             done = false;
1599             break;
1600     }
1601 
1602     if (done){
1603         return packet_sent;
1604     }
1605 
1606     // write without response callback
1607     btstack_context_callback_registration_t * callback =
1608             (btstack_context_callback_registration_t *) btstack_linked_list_pop(&gatt_client->write_without_response_requests);
1609     if (callback != NULL){
1610         (*callback->callback)(callback->context);
1611         return true;
1612     }
1613 
1614     // requested can send now old
1615     if (gatt_client->write_without_response_callback != NULL){
1616         btstack_packet_handler_t packet_handler = gatt_client->write_without_response_callback;
1617         gatt_client->write_without_response_callback = NULL;
1618         uint8_t event[4];
1619         event[0] = GATT_EVENT_CAN_WRITE_WITHOUT_RESPONSE;
1620         event[1] = sizeof(event) - 2u;
1621         little_endian_store_16(event, 2, gatt_client->con_handle);
1622         packet_handler(HCI_EVENT_PACKET, gatt_client->con_handle, event, sizeof(event));
1623         return true; // to trigger requeueing (even if higher layer didn't sent)
1624     }
1625 
1626     return false;
1627 }
1628 
1629 static void gatt_client_run(void){
1630     btstack_linked_item_t *it;
1631     bool packet_sent;
1632 #ifdef ENABLE_GATT_OVER_EATT
1633     btstack_linked_list_iterator_t it_eatt;
1634 #endif
1635     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
1636         gatt_client_t * gatt_client = (gatt_client_t *) it;
1637         switch (gatt_client->bearer_type){
1638             case ATT_BEARER_UNENHANCED_LE:
1639 #ifdef ENABLE_GATT_OVER_EATT
1640                 btstack_linked_list_iterator_init(&it_eatt, &gatt_client->eatt_clients);
1641                 while (btstack_linked_list_iterator_has_next(&it_eatt)) {
1642                     gatt_client_t * eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it_eatt);
1643                     if (eatt_client->state != P_READY){
1644                         if (att_dispatch_client_can_send_now(gatt_client->con_handle)){
1645                             gatt_client_run_for_gatt_client(eatt_client);
1646                         }
1647                     }
1648                 }
1649 #endif
1650                 if (!att_dispatch_client_can_send_now(gatt_client->con_handle)) {
1651                     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
1652                     return;
1653                 }
1654                 packet_sent = gatt_client_run_for_gatt_client(gatt_client);
1655                 if (packet_sent){
1656                     // request new permission
1657                     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
1658                     // requeue client for fairness and exit
1659                     // note: iterator has become invalid
1660                     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1661                     btstack_linked_list_add_tail(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1662                     return;
1663                 }
1664                 break;
1665 #ifdef ENABLE_GATT_OVER_CLASSIC
1666             case ATT_BEARER_UNENHANCED_CLASSIC:
1667                 if (gatt_client->con_handle == HCI_CON_HANDLE_INVALID) {
1668                     continue;
1669                 }
1670 
1671                 // handle GATT over BR/EDR
1672                 if (att_dispatch_client_can_send_now(gatt_client->con_handle) == false) {
1673                     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
1674                     return;
1675                 }
1676                 packet_sent = gatt_client_run_for_gatt_client(gatt_client);
1677                 if (packet_sent){
1678                     // request new permission
1679                     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
1680                     // requeue client for fairness and exit
1681                     // note: iterator has become invalid
1682                     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1683                     btstack_linked_list_add_tail(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1684                     return;
1685                 }
1686                 break;
1687 #endif
1688             default:
1689                 btstack_unreachable();
1690                 break;
1691         }
1692 
1693 
1694     }
1695 }
1696 
1697 // emit complete event, used to avoid emitting event from API call
1698 static void gatt_client_emit_events(void * context){
1699     UNUSED(context);
1700     btstack_linked_item_t *it;
1701     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next) {
1702         gatt_client_t *gatt_client = (gatt_client_t *) it;
1703         if (gatt_client->state == P_W2_EMIT_QUERY_COMPLETE_EVENT){
1704             gatt_client->state = P_READY;
1705             emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1706         }
1707     }
1708 }
1709 
1710 static void gatt_client_report_error_if_pending(gatt_client_t *gatt_client, uint8_t att_error_code) {
1711     if (is_ready(gatt_client)) return;
1712     gatt_client_handle_transaction_complete(gatt_client, att_error_code);
1713 }
1714 
1715 static void gatt_client_handle_reencryption_complete(const uint8_t * packet){
1716     hci_con_handle_t con_handle = sm_event_reencryption_complete_get_handle(packet);
1717     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
1718     if (gatt_client == NULL) return;
1719 
1720     // update security level
1721     gatt_client->security_level = gatt_client_le_security_level_for_connection(con_handle);
1722 
1723     gatt_client->reencryption_result = sm_event_reencryption_complete_get_status(packet);
1724     gatt_client->reencryption_active = false;
1725     gatt_client->wait_for_authentication_complete = false;
1726 
1727     if (gatt_client->state == P_READY) return;
1728 
1729     switch (sm_event_reencryption_complete_get_status(packet)){
1730         case ERROR_CODE_SUCCESS:
1731             log_info("re-encryption success, retry operation");
1732             break;
1733         case ERROR_CODE_AUTHENTICATION_FAILURE:
1734         case ERROR_CODE_PIN_OR_KEY_MISSING:
1735 #if defined(ENABLE_GATT_CLIENT_PAIRING) && !defined(ENABLE_LE_PROACTIVE_AUTHENTICATION)
1736             if (gatt_client_required_security_level == LEVEL_0) {
1737                 // re-encryption failed for reactive authentication with pairing and we have a pending client request
1738                 // => try to resolve it by deleting bonding information if we started pairing before
1739                 // delete bonding information
1740                 int le_device_db_index = sm_le_device_index(gatt_client->con_handle);
1741                 btstack_assert(le_device_db_index >= 0);
1742                 log_info("reactive auth with pairing: delete bonding and start pairing");
1743 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
1744                 hci_remove_le_device_db_entry_from_resolving_list((uint16_t) le_device_db_index);
1745 #endif
1746                 le_device_db_remove(le_device_db_index);
1747                 // trigger pairing again
1748                 sm_request_pairing(gatt_client->con_handle);
1749                 break;
1750             }
1751 #endif
1752             // report bonding information missing
1753             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_BONDING_INFORMATION_MISSING);
1754             break;
1755         default:
1756             // report bonding information missing
1757             gatt_client_handle_transaction_complete(gatt_client, gatt_client->pending_error_code);
1758             break;
1759     }
1760 }
1761 
1762 static void gatt_client_handle_disconnection_complete(const uint8_t * packet){
1763     log_info("GATT Client: HCI_EVENT_DISCONNECTION_COMPLETE");
1764     hci_con_handle_t con_handle = little_endian_read_16(packet,3);
1765     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
1766     if (gatt_client == NULL) return;
1767 
1768     gatt_client_report_error_if_pending(gatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
1769     gatt_client_timeout_stop(gatt_client);
1770     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1771     btstack_memory_gatt_client_free(gatt_client);
1772 }
1773 
1774 static void gatt_client_event_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1775     UNUSED(channel);    // ok: handling own l2cap events
1776     UNUSED(size);       // ok: there is no channel
1777 
1778     if (packet_type != HCI_EVENT_PACKET) return;
1779 
1780     hci_con_handle_t con_handle;
1781     gatt_client_t * gatt_client;
1782     switch (hci_event_packet_get_type(packet)) {
1783         case HCI_EVENT_DISCONNECTION_COMPLETE:
1784             gatt_client_handle_disconnection_complete(packet);
1785             break;
1786 
1787         // Pairing complete (with/without bonding=storing of pairing information)
1788         case SM_EVENT_PAIRING_COMPLETE:
1789             con_handle = sm_event_pairing_complete_get_handle(packet);
1790             gatt_client = gatt_client_get_context_for_handle(con_handle);
1791             if (gatt_client == NULL) break;
1792 
1793             // update security level
1794             gatt_client->security_level = gatt_client_le_security_level_for_connection(con_handle);
1795 
1796             if (gatt_client->wait_for_authentication_complete){
1797                 gatt_client->wait_for_authentication_complete = false;
1798                 if (sm_event_pairing_complete_get_status(packet) != ERROR_CODE_SUCCESS){
1799                     log_info("pairing failed, report previous error 0x%x", gatt_client->pending_error_code);
1800                     gatt_client_report_error_if_pending(gatt_client, gatt_client->pending_error_code);
1801                 } else {
1802                     log_info("pairing success, retry operation");
1803                 }
1804             }
1805             break;
1806 
1807 #ifdef ENABLE_LE_SIGNED_WRITE
1808         // Identity Resolving completed (no code, gatt_client_run will continue)
1809         case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED:
1810         case SM_EVENT_IDENTITY_RESOLVING_FAILED:
1811             break;
1812 #endif
1813 
1814         // re-encryption started
1815         case SM_EVENT_REENCRYPTION_STARTED:
1816             con_handle = sm_event_reencryption_complete_get_handle(packet);
1817             gatt_client = gatt_client_get_context_for_handle(con_handle);
1818             if (gatt_client == NULL) break;
1819 
1820             gatt_client->reencryption_active = true;
1821             gatt_client->reencryption_result = ERROR_CODE_SUCCESS;
1822             break;
1823 
1824         // re-encryption complete
1825         case SM_EVENT_REENCRYPTION_COMPLETE:
1826             gatt_client_handle_reencryption_complete(packet);
1827             break;
1828         default:
1829             break;
1830     }
1831 
1832     gatt_client_run();
1833 }
1834 
1835 static void gatt_client_handle_att_read_response(gatt_client_t *gatt_client, uint8_t *packet, uint16_t size) {
1836     switch (gatt_client->state) {
1837         case P_W4_INCLUDED_SERVICE_UUID_WITH_QUERY_RESULT:
1838             if (size >= 17) {
1839                 uint8_t uuid128[16];
1840                 reverse_128(&packet[1], uuid128);
1841                 report_gatt_included_service_uuid128(gatt_client, gatt_client->start_group_handle, uuid128);
1842             }
1843             trigger_next_included_service_query(gatt_client, gatt_client->start_group_handle);
1844             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1845             break;
1846 
1847         case P_W4_READ_CHARACTERISTIC_VALUE_RESULT:
1848             report_gatt_characteristic_value(gatt_client, gatt_client->attribute_handle, &packet[1], size - 1u);
1849             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1850             break;
1851 
1852         case P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT:
1853             report_gatt_characteristic_descriptor(gatt_client, gatt_client->attribute_handle, &packet[1],
1854                                                   size - 1u, 0u);
1855             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1856             break;
1857 
1858             // Use ATT_READ_REQUEST for first blob of Read Long Characteristic
1859         case P_W4_READ_BLOB_RESULT:
1860             report_gatt_long_characteristic_value_blob(gatt_client, gatt_client->attribute_handle, &packet[1],
1861                                                        size - 1u, gatt_client->attribute_offset);
1862             trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_QUERY, size - 1u);
1863             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1864             break;
1865 
1866             // Use ATT_READ_REQUEST for first blob of Read Long Characteristic Descriptor
1867         case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
1868             report_gatt_long_characteristic_descriptor(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_CHARACTERISTIC_DESCRIPTOR_QUERY,
1871                                     size - 1u);
1872             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1873             break;
1874 
1875         default:
1876             break;
1877     }
1878 }
1879 
1880 static void gatt_client_handle_att_read_by_type_response(gatt_client_t *gatt_client, uint8_t *packet, uint16_t size) {
1881     switch (gatt_client->state) {
1882         case P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT:
1883             report_gatt_characteristics(gatt_client, packet, size);
1884             trigger_next_characteristic_query(gatt_client,
1885                                               get_last_result_handle_from_characteristics_list(packet, size));
1886             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done, or by ATT_ERROR
1887             break;
1888         case P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT:
1889             report_gatt_characteristics(gatt_client, packet, size);
1890             trigger_next_characteristic_query(gatt_client,
1891                                               get_last_result_handle_from_characteristics_list(packet, size));
1892             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done, or by ATT_ERROR
1893             break;
1894         case P_W4_INCLUDED_SERVICE_QUERY_RESULT: {
1895             if (size < 2u) break;
1896             uint16_t uuid16 = 0;
1897             uint16_t pair_size = packet[1];
1898 
1899             if (pair_size == 6u) {
1900                 if (size < 8u) break;
1901                 // UUIDs not available, query first included service
1902                 gatt_client->start_group_handle = little_endian_read_16(packet, 2); // ready for next query
1903                 gatt_client->query_start_handle = little_endian_read_16(packet, 4);
1904                 gatt_client->query_end_handle = little_endian_read_16(packet, 6);
1905                 gatt_client->state = P_W2_SEND_INCLUDED_SERVICE_WITH_UUID_QUERY;
1906                 break;
1907             }
1908 
1909             if (pair_size != 8u) break;
1910 
1911             // UUIDs included, report all of them
1912             uint16_t offset;
1913             for (offset = 2u; (offset + 8u) <= size; offset += pair_size) {
1914                 uint16_t include_handle = little_endian_read_16(packet, offset);
1915                 gatt_client->query_start_handle = little_endian_read_16(packet, offset + 2u);
1916                 gatt_client->query_end_handle = little_endian_read_16(packet, offset + 4u);
1917                 uuid16 = little_endian_read_16(packet, offset + 6u);
1918                 report_gatt_included_service_uuid16(gatt_client, include_handle, uuid16);
1919             }
1920 
1921             trigger_next_included_service_query(gatt_client,
1922                                                 get_last_result_handle_from_included_services_list(packet,
1923                                                                                                    size));
1924             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1925             break;
1926         }
1927 #ifndef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
1928         case P_W4_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT:
1929             gatt_client->client_characteristic_configuration_handle = little_endian_read_16(packet, 2);
1930             gatt_client->state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
1931             break;
1932 #endif
1933         case P_W4_READ_BY_TYPE_RESPONSE: {
1934             uint16_t pair_size = packet[1];
1935             // set last result handle to last valid handle, only used if pair_size invalid
1936             uint16_t last_result_handle = 0xffff;
1937             if (pair_size > 2) {
1938                 uint16_t offset;
1939                 for (offset = 2; offset < size; offset += pair_size) {
1940                     uint16_t value_handle = little_endian_read_16(packet, offset);
1941                     report_gatt_characteristic_value(gatt_client, value_handle, &packet[offset + 2u],
1942                                                      pair_size - 2u);
1943                     last_result_handle = value_handle;
1944                 }
1945             }
1946             trigger_next_read_by_type_query(gatt_client, last_result_handle);
1947             break;
1948         }
1949         default:
1950             break;
1951     }
1952 }
1953 
1954 static void gatt_client_handle_att_write_response(gatt_client_t *gatt_client) {
1955     switch (gatt_client->state) {
1956         case P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT:
1957             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1958             break;
1959         case P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT:
1960             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1961             break;
1962         case P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1963             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1964             break;
1965         default:
1966             break;
1967     }
1968 }
1969 
1970 static void gatt_client_handle_att_response(gatt_client_t * gatt_client, uint8_t * packet, uint16_t size) {
1971     uint8_t att_status;
1972     switch (packet[0]) {
1973         case ATT_EXCHANGE_MTU_RESPONSE: {
1974             if (size < 3u) break;
1975             bool update_gatt_server_att_mtu = false;
1976             uint16_t remote_rx_mtu = little_endian_read_16(packet, 1);
1977             uint16_t local_rx_mtu = l2cap_max_le_mtu();
1978             switch (gatt_client->bearer_type){
1979                 case ATT_BEARER_UNENHANCED_LE:
1980                     update_gatt_server_att_mtu = true;
1981                     break;
1982 #ifdef ENABLE_GATT_OVER_CLASSIC
1983                 case ATT_BEARER_UNENHANCED_CLASSIC:
1984                     local_rx_mtu = gatt_client->mtu;
1985                     break;
1986 #endif
1987                 default:
1988                     btstack_unreachable();
1989                     break;
1990             }
1991 
1992             uint16_t mtu = (remote_rx_mtu < local_rx_mtu) ? remote_rx_mtu : local_rx_mtu;
1993 
1994             // set gatt client mtu
1995             gatt_client->mtu = mtu;
1996             gatt_client->mtu_state = MTU_EXCHANGED;
1997 
1998             if (update_gatt_server_att_mtu){
1999                 // set per connection mtu state - for fixed channel
2000                 hci_connection_t *hci_connection = hci_connection_for_handle(gatt_client->con_handle);
2001                 hci_connection->att_connection.mtu = gatt_client->mtu;
2002                 hci_connection->att_connection.mtu_exchanged = true;
2003             }
2004             emit_gatt_mtu_exchanged_result_event(gatt_client, gatt_client->mtu);
2005             break;
2006         }
2007         case ATT_READ_BY_GROUP_TYPE_RESPONSE:
2008             switch (gatt_client->state) {
2009                 case P_W4_SERVICE_QUERY_RESULT:
2010                     report_gatt_services(gatt_client, packet, size);
2011                     trigger_next_service_query(gatt_client, get_last_result_handle_from_service_list(packet, size));
2012                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2013                     break;
2014                 default:
2015                     break;
2016             }
2017             break;
2018         case ATT_HANDLE_VALUE_NOTIFICATION:
2019             if (size < 3u) return;
2020             report_gatt_notification(gatt_client, little_endian_read_16(packet, 1u), &packet[3], size - 3u);
2021             return;
2022 #ifdef ENABLE_GATT_OVER_EATT
2023         case ATT_MULTIPLE_HANDLE_VALUE_NTF:
2024             if (size >= 5u) {
2025                 uint16_t offset = 1;
2026                 while (true){
2027                     uint16_t value_handle = little_endian_read_16(packet, offset);
2028                     offset += 2;
2029                     uint16_t value_length = little_endian_read_16(packet, offset);
2030                     offset += 2;
2031                     if ((offset + value_length) > size) break;
2032                     report_gatt_notification(gatt_client, value_handle, &packet[offset], value_length);
2033                     offset += value_length;
2034                 }
2035             }
2036             return;
2037 #endif
2038         case ATT_HANDLE_VALUE_INDICATION:
2039             if (size < 3u) break;
2040             report_gatt_indication(gatt_client, little_endian_read_16(packet, 1u), &packet[3], size - 3u);
2041             gatt_client->send_confirmation = true;
2042             break;
2043         case ATT_READ_BY_TYPE_RESPONSE:
2044             gatt_client_handle_att_read_by_type_response(gatt_client, packet, size);
2045             break;
2046         case ATT_READ_RESPONSE:
2047             gatt_client_handle_att_read_response(gatt_client, packet, size);
2048             break;
2049         case ATT_FIND_BY_TYPE_VALUE_RESPONSE: {
2050             uint8_t pair_size = 4;
2051             int i;
2052             uint16_t start_group_handle;
2053             uint16_t end_group_handle = 0xffff; // asserts GATT_EVENT_QUERY_COMPLETE is emitted if no results
2054             for (i = 1u; (i + pair_size) <= size; i += pair_size) {
2055                 start_group_handle = little_endian_read_16(packet, i);
2056                 end_group_handle = little_endian_read_16(packet, i + 2);
2057                 emit_gatt_service_query_result_event(gatt_client, start_group_handle, end_group_handle,
2058                                                      gatt_client->uuid128);
2059             }
2060             trigger_next_service_by_uuid_query(gatt_client, end_group_handle);
2061             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2062             break;
2063         }
2064         case ATT_FIND_INFORMATION_REPLY: {
2065             if (size < 2u) break;
2066 
2067             uint8_t pair_size = 4;
2068             if (packet[1u] == 2u) {
2069                 pair_size = 18;
2070             }
2071             uint16_t offset = 2;
2072 
2073             if (size < (pair_size + offset)) break;
2074             uint16_t last_descriptor_handle = little_endian_read_16(packet, size - pair_size);
2075 
2076 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
2077             log_info("ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY, state %x", gatt_client->gatt_client_state);
2078             if (gatt_client->gatt_client_state == P_W4_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT){
2079                 // iterate over descriptors looking for CCC
2080                 if (pair_size == 4){
2081                     while ((offset + 4) <= size){
2082                         uint16_t uuid16 = little_endian_read_16(packet, offset + 2);
2083                         if (uuid16 == GATT_CLIENT_CHARACTERISTICS_CONFIGURATION){
2084                             gatt_client->client_characteristic_configuration_handle = little_endian_read_16(packet, offset);
2085                             gatt_client->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
2086                             log_info("CCC found %x", gatt_client->client_characteristic_configuration_handle);
2087                             break;
2088                         }
2089                         offset += pair_size;
2090                     }
2091                 }
2092                 if (is_query_done(gatt_client, last_descriptor_handle)){
2093 
2094                 } else {
2095                     // next
2096                     gatt_client->start_group_handle = last_descriptor_handle + 1;
2097                     gatt_client->gatt_client_state = P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2098                 }
2099                 break;
2100             }
2101 #endif
2102             report_gatt_all_characteristic_descriptors(gatt_client, &packet[2], size - 2u, pair_size);
2103             trigger_next_characteristic_descriptor_query(gatt_client, last_descriptor_handle);
2104             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2105             break;
2106         }
2107 
2108         case ATT_WRITE_RESPONSE:
2109             gatt_client_handle_att_write_response(gatt_client);
2110             break;
2111 
2112         case ATT_READ_BLOB_RESPONSE: {
2113             uint16_t received_blob_length = size - 1u;
2114             switch (gatt_client->state) {
2115                 case P_W4_READ_BLOB_RESULT:
2116                     report_gatt_long_characteristic_value_blob(gatt_client, gatt_client->attribute_handle, &packet[1],
2117                                                                received_blob_length, gatt_client->attribute_offset);
2118                     trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_QUERY, received_blob_length);
2119                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2120                     break;
2121                 case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
2122                     report_gatt_long_characteristic_descriptor(gatt_client, gatt_client->attribute_handle,
2123                                                                &packet[1], received_blob_length,
2124                                                                gatt_client->attribute_offset);
2125                     trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY,
2126                                             received_blob_length);
2127                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2128                     break;
2129                 default:
2130                     break;
2131             }
2132             break;
2133         }
2134         case ATT_PREPARE_WRITE_RESPONSE:
2135             switch (gatt_client->state) {
2136                 case P_W4_PREPARE_WRITE_SINGLE_RESULT:
2137                     if (is_value_valid(gatt_client, packet, size)) {
2138                         att_status = ATT_ERROR_SUCCESS;
2139                     } else {
2140                         att_status = ATT_ERROR_DATA_MISMATCH;
2141                     }
2142                     gatt_client_handle_transaction_complete(gatt_client, att_status);
2143                     break;
2144 
2145                 case P_W4_PREPARE_WRITE_RESULT: {
2146                     gatt_client->attribute_offset = little_endian_read_16(packet, 3);
2147                     trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_WRITE, P_W2_EXECUTE_PREPARED_WRITE);
2148                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2149                     break;
2150                 }
2151                 case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT: {
2152                     gatt_client->attribute_offset = little_endian_read_16(packet, 3);
2153                     trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR,
2154                                                      P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR);
2155                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2156                     break;
2157                 }
2158                 case P_W4_PREPARE_RELIABLE_WRITE_RESULT: {
2159                     if (is_value_valid(gatt_client, packet, size)) {
2160                         gatt_client->attribute_offset = little_endian_read_16(packet, 3);
2161                         trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_RELIABLE_WRITE,
2162                                                          P_W2_EXECUTE_PREPARED_WRITE);
2163                         // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2164                         break;
2165                     }
2166                     gatt_client->state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
2167                     break;
2168                 }
2169                 default:
2170                     break;
2171             }
2172             break;
2173 
2174         case ATT_EXECUTE_WRITE_RESPONSE:
2175             switch (gatt_client->state) {
2176                 case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
2177                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2178                     break;
2179                 case P_W4_CANCEL_PREPARED_WRITE_RESULT:
2180                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2181                     break;
2182                 case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
2183                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_DATA_MISMATCH);
2184                     break;
2185                 case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
2186                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2187                     break;
2188                 default:
2189                     break;
2190 
2191             }
2192             break;
2193 
2194         case ATT_READ_MULTIPLE_RESPONSE:
2195             switch (gatt_client->state) {
2196                 case P_W4_READ_MULTIPLE_RESPONSE:
2197                     report_gatt_characteristic_value(gatt_client, 0u, &packet[1], size - 1u);
2198                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2199                     break;
2200                 default:
2201                     break;
2202             }
2203             break;
2204 
2205 #ifdef ENABLE_GATT_OVER_EATT
2206         case ATT_READ_MULTIPLE_VARIABLE_RSP:
2207             switch (gatt_client->state) {
2208                 case P_W4_READ_MULTIPLE_VARIABLE_RESPONSE:
2209                     report_gatt_characteristic_value(gatt_client, 0u, &packet[1], size - 1u);
2210                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2211                     break;
2212                 default:
2213                     break;
2214             }
2215             break;
2216 #endif
2217 
2218         case ATT_ERROR_RESPONSE:
2219             if (size < 5u) return;
2220             att_status = packet[4];
2221             switch (att_status) {
2222                 case ATT_ERROR_ATTRIBUTE_NOT_FOUND: {
2223                     switch (gatt_client->state) {
2224                         case P_W4_SERVICE_QUERY_RESULT:
2225                         case P_W4_SERVICE_WITH_UUID_RESULT:
2226                         case P_W4_INCLUDED_SERVICE_QUERY_RESULT:
2227                         case P_W4_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
2228                             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2229                             break;
2230                         case P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT:
2231                         case P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT:
2232                             report_gatt_characteristic_end_found(gatt_client, gatt_client->end_group_handle);
2233                             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2234                             break;
2235                         case P_W4_READ_BY_TYPE_RESPONSE:
2236                             if (gatt_client->start_group_handle == gatt_client->query_start_handle) {
2237                                 att_status = ATT_ERROR_ATTRIBUTE_NOT_FOUND;
2238                             } else {
2239                                 att_status = ATT_ERROR_SUCCESS;
2240                             }
2241                             gatt_client_handle_transaction_complete(gatt_client, att_status);
2242                             break;
2243                         default:
2244                             gatt_client_report_error_if_pending(gatt_client, att_status);
2245                             break;
2246                     }
2247                     break;
2248                 }
2249 
2250 #ifdef ENABLE_GATT_CLIENT_PAIRING
2251 
2252                     case ATT_ERROR_INSUFFICIENT_AUTHENTICATION:
2253                     case ATT_ERROR_INSUFFICIENT_ENCRYPTION_KEY_SIZE:
2254                     case ATT_ERROR_INSUFFICIENT_ENCRYPTION: {
2255 
2256                         // security too low
2257                         if (gatt_client->security_counter > 0) {
2258                             gatt_client_report_error_if_pending(gatt_client, att_status);
2259                             break;
2260                         }
2261                         // start security
2262                         gatt_client->security_counter++;
2263 
2264                         // setup action
2265                         int retry = 1;
2266                         switch (gatt_client->state){
2267                             case P_W4_READ_CHARACTERISTIC_VALUE_RESULT:
2268                                 gatt_client->state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY ;
2269                                 break;
2270                             case P_W4_READ_BLOB_RESULT:
2271                                 gatt_client->state = P_W2_SEND_READ_BLOB_QUERY;
2272                                 break;
2273                             case P_W4_READ_BY_TYPE_RESPONSE:
2274                                 gatt_client->state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2275                                 break;
2276                             case P_W4_READ_MULTIPLE_RESPONSE:
2277                                 gatt_client->state = P_W2_SEND_READ_MULTIPLE_REQUEST;
2278                                 break;
2279                             case P_W4_READ_MULTIPLE_VARIABLE_RESPONSE:
2280                                 gatt_client->state = P_W2_SEND_READ_MULTIPLE_VARIABLE_REQUEST;
2281                                 break;
2282                             case P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT:
2283                                 gatt_client->state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
2284                                 break;
2285                             case P_W4_PREPARE_WRITE_RESULT:
2286                                 gatt_client->state = P_W2_PREPARE_WRITE;
2287                                 break;
2288                             case P_W4_PREPARE_WRITE_SINGLE_RESULT:
2289                                 gatt_client->state = P_W2_PREPARE_WRITE_SINGLE;
2290                                 break;
2291                             case P_W4_PREPARE_RELIABLE_WRITE_RESULT:
2292                                 gatt_client->state = P_W2_PREPARE_RELIABLE_WRITE;
2293                                 break;
2294                             case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
2295                                 gatt_client->state = P_W2_EXECUTE_PREPARED_WRITE;
2296                                 break;
2297                             case P_W4_CANCEL_PREPARED_WRITE_RESULT:
2298                                 gatt_client->state = P_W2_CANCEL_PREPARED_WRITE;
2299                                 break;
2300                             case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
2301                                 gatt_client->state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
2302                                 break;
2303                             case P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT:
2304                                 gatt_client->state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
2305                                 break;
2306                             case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
2307                                 gatt_client->state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
2308                                 break;
2309                             case P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
2310                                 gatt_client->state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
2311                                 break;
2312                             case P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT:
2313                                 gatt_client->state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
2314                                 break;
2315                             case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
2316                                 gatt_client->state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
2317                                 break;
2318                             case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
2319                                 gatt_client->state = P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR;
2320                                 break;
2321 #ifdef ENABLE_LE_SIGNED_WRITE
2322                             case P_W4_SEND_SIGNED_WRITE_DONE:
2323                                 gatt_client->state = P_W2_SEND_SIGNED_WRITE;
2324                                 break;
2325 #endif
2326                             default:
2327                                 log_info("retry not supported for state %x", gatt_client->state);
2328                                 retry = 0;
2329                                 break;
2330                         }
2331 
2332                         if (!retry) {
2333                             gatt_client_report_error_if_pending(gatt_client, att_status);
2334                             break;
2335                         }
2336 
2337                         log_info("security error, start pairing");
2338 
2339                         // start pairing for higher security level
2340                         gatt_client->wait_for_authentication_complete = true;
2341                         gatt_client->pending_error_code = att_status;
2342                         sm_request_pairing(gatt_client->con_handle);
2343                         break;
2344                     }
2345 #endif
2346 
2347                     // nothing we can do about that
2348                 case ATT_ERROR_INSUFFICIENT_AUTHORIZATION:
2349                 default:
2350                     gatt_client_report_error_if_pending(gatt_client, att_status);
2351                     break;
2352             }
2353             break;
2354 
2355         default:
2356             log_info("ATT Handler, unhandled response type 0x%02x", packet[0]);
2357             break;
2358     }
2359 }
2360 
2361 static void gatt_client_att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size) {
2362     gatt_client_t *gatt_client;
2363 #ifdef ENABLE_GATT_OVER_CLASSIC
2364     uint8_t status;
2365     hci_connection_t * hci_connection;
2366     hci_con_handle_t con_handle;
2367 #endif
2368 
2369     if (size < 1u) return;
2370     switch (packet_type){
2371         case HCI_EVENT_PACKET:
2372             switch (hci_event_packet_get_type(packet)) {
2373 #ifdef ENABLE_GATT_OVER_CLASSIC
2374                 case L2CAP_EVENT_CHANNEL_OPENED:
2375                     status = l2cap_event_channel_opened_get_status(packet);
2376                     gatt_client = gatt_client_get_context_for_l2cap_cid(l2cap_event_channel_opened_get_local_cid(packet));
2377                     if (gatt_client != NULL){
2378                         con_handle = l2cap_event_channel_opened_get_handle(packet);
2379                         hci_connection = hci_connection_for_handle(con_handle);
2380                         if (status == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_RESOURCES){
2381                             if ((hci_connection != NULL) && hci_connection->att_server.incoming_connection_request) {
2382                                 log_info("Collision, retry in 100ms");
2383                                 gatt_client->state = P_W2_L2CAP_CONNECT;
2384                                 // set timer for retry
2385                                 btstack_run_loop_set_timer(&gatt_client->gc_timeout, GATT_CLIENT_COLLISION_BACKOFF_MS);
2386                                 btstack_run_loop_set_timer_handler(&gatt_client->gc_timeout, gatt_client_classic_retry);
2387                                 btstack_run_loop_add_timer(&gatt_client->gc_timeout);
2388                                 break;
2389                             }
2390                         }
2391                         // if status != 0, gatt_client will be discarded
2392                         gatt_client->state = P_READY;
2393                         gatt_client->con_handle = l2cap_event_channel_opened_get_handle(packet);
2394                         gatt_client->mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
2395                         gatt_client_classic_handle_connected(gatt_client, status);
2396                     }
2397                     break;
2398                 case L2CAP_EVENT_CHANNEL_CLOSED:
2399                     gatt_client = gatt_client_get_context_for_l2cap_cid(l2cap_event_channel_closed_get_local_cid(packet));
2400                     if (gatt_client != NULL){
2401                         // discard gatt client object
2402                         gatt_client_classic_handle_disconnected(gatt_client);
2403                     }
2404                     break;
2405 #endif
2406                 case L2CAP_EVENT_CAN_SEND_NOW:
2407                     gatt_client_run();
2408                     break;
2409                     // att_server has negotiated the mtu for this connection, cache if context exists
2410                 case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
2411                     if (size < 6u) break;
2412                     gatt_client = gatt_client_get_context_for_handle(handle);
2413                     if (gatt_client != NULL) {
2414                         gatt_client->mtu = little_endian_read_16(packet, 4);
2415                     }
2416                     break;
2417                 default:
2418                     break;
2419             }
2420             break;
2421 
2422         case ATT_DATA_PACKET:
2423             // special cases: notifications & indications motivate creating context
2424             switch (packet[0]) {
2425                 case ATT_HANDLE_VALUE_NOTIFICATION:
2426                 case ATT_HANDLE_VALUE_INDICATION:
2427                     gatt_client_provide_context_for_handle(handle, &gatt_client);
2428                     break;
2429                 default:
2430                     gatt_client = gatt_client_get_context_for_handle(handle);
2431                     break;
2432             }
2433 
2434             if (gatt_client != NULL) {
2435                 gatt_client_handle_att_response(gatt_client, packet, size);
2436                 gatt_client_run();
2437             }
2438             break;
2439 
2440 #ifdef ENABLE_GATT_OVER_CLASSIC
2441         case L2CAP_DATA_PACKET:
2442             gatt_client = gatt_client_get_context_for_l2cap_cid(handle);
2443             if (gatt_client != NULL){
2444                 gatt_client_handle_att_response(gatt_client, packet, size);
2445                 gatt_client_run();
2446             }
2447             break;
2448 #endif
2449 
2450         default:
2451             break;
2452     }
2453 }
2454 
2455 #ifdef ENABLE_LE_SIGNED_WRITE
2456 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
2457     btstack_linked_list_iterator_t it;
2458     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
2459     while (btstack_linked_list_iterator_has_next(&it)){
2460         gatt_client_t * gatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
2461         if (gatt_client->state == P_W4_CMAC_RESULT){
2462             // store result
2463             (void)memcpy(gatt_client->cmac, hash, 8);
2464             // reverse_64(hash, gatt_client->cmac);
2465             gatt_client->state = P_W2_SEND_SIGNED_WRITE;
2466             gatt_client_run();
2467             return;
2468         }
2469     }
2470 }
2471 
2472 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){
2473     gatt_client_t * gatt_client;
2474     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2475     if (status != ERROR_CODE_SUCCESS){
2476         return status;
2477     }
2478     if (is_ready(gatt_client) == 0){
2479         return GATT_CLIENT_IN_WRONG_STATE;
2480     }
2481 
2482     gatt_client->callback = callback;
2483     gatt_client->attribute_handle = value_handle;
2484     gatt_client->attribute_length = message_len;
2485     gatt_client->attribute_value = message;
2486     gatt_client->state = P_W4_IDENTITY_RESOLVING;
2487     gatt_client_run();
2488     return ERROR_CODE_SUCCESS;
2489 }
2490 #endif
2491 
2492 uint8_t gatt_client_discover_primary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2493     gatt_client_t * gatt_client;
2494     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2495     if (status != ERROR_CODE_SUCCESS){
2496         return status;
2497     }
2498 
2499     gatt_client->callback = callback;
2500     gatt_client->start_group_handle = 0x0001;
2501     gatt_client->end_group_handle   = 0xffff;
2502     gatt_client->state = P_W2_SEND_SERVICE_QUERY;
2503     gatt_client->uuid16 = GATT_PRIMARY_SERVICE_UUID;
2504     gatt_client_run();
2505     return ERROR_CODE_SUCCESS;
2506 }
2507 
2508 uint8_t gatt_client_discover_secondary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2509     gatt_client_t * gatt_client;
2510     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2511     if (status != ERROR_CODE_SUCCESS){
2512         return status;
2513     }
2514 
2515     gatt_client->callback = callback;
2516     gatt_client->start_group_handle = 0x0001;
2517     gatt_client->end_group_handle   = 0xffff;
2518     gatt_client->state = P_W2_SEND_SERVICE_QUERY;
2519     gatt_client->uuid16 = GATT_SECONDARY_SERVICE_UUID;
2520     gatt_client_run();
2521     return ERROR_CODE_SUCCESS;
2522 }
2523 
2524 uint8_t gatt_client_discover_primary_services_by_uuid16(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t uuid16){
2525     gatt_client_t * gatt_client;
2526     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2527     if (status != ERROR_CODE_SUCCESS){
2528         return status;
2529     }
2530 
2531     gatt_client->callback = callback;
2532     gatt_client->start_group_handle = 0x0001;
2533     gatt_client->end_group_handle   = 0xffff;
2534     gatt_client->state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
2535     gatt_client->uuid16 = uuid16;
2536     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), gatt_client->uuid16);
2537     gatt_client_run();
2538     return ERROR_CODE_SUCCESS;
2539 }
2540 
2541 uint8_t gatt_client_discover_primary_services_by_uuid128(btstack_packet_handler_t callback, hci_con_handle_t con_handle, const uint8_t * uuid128){
2542     gatt_client_t * gatt_client;
2543     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2544     if (status != ERROR_CODE_SUCCESS){
2545         return status;
2546     }
2547 
2548     gatt_client->callback = callback;
2549     gatt_client->start_group_handle = 0x0001;
2550     gatt_client->end_group_handle   = 0xffff;
2551     gatt_client->uuid16 = 0;
2552     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2553     gatt_client->state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
2554     gatt_client_run();
2555     return ERROR_CODE_SUCCESS;
2556 }
2557 
2558 uint8_t gatt_client_discover_characteristics_for_service(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_service_t * service){
2559     gatt_client_t * gatt_client;
2560     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2561     if (status != ERROR_CODE_SUCCESS){
2562         return status;
2563     }
2564 
2565     gatt_client->callback = callback;
2566     gatt_client->start_group_handle = service->start_group_handle;
2567     gatt_client->end_group_handle   = service->end_group_handle;
2568     gatt_client->filter_with_uuid = false;
2569     gatt_client->characteristic_start_handle = 0;
2570     gatt_client->state = P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY;
2571     gatt_client_run();
2572     return ERROR_CODE_SUCCESS;
2573 }
2574 
2575 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){
2576     gatt_client_t * gatt_client;
2577     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2578     if (status != ERROR_CODE_SUCCESS){
2579         return status;
2580     }
2581 
2582     gatt_client->callback = callback;
2583     gatt_client->start_group_handle = service->start_group_handle;
2584     gatt_client->end_group_handle   = service->end_group_handle;
2585     gatt_client->state = P_W2_SEND_INCLUDED_SERVICE_QUERY;
2586 
2587     gatt_client_run();
2588     return ERROR_CODE_SUCCESS;
2589 }
2590 
2591 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){
2592     gatt_client_t * gatt_client;
2593     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2594     if (status != ERROR_CODE_SUCCESS){
2595         return status;
2596     }
2597 
2598     gatt_client->callback = callback;
2599     gatt_client->start_group_handle = start_handle;
2600     gatt_client->end_group_handle   = end_handle;
2601     gatt_client->filter_with_uuid = true;
2602     gatt_client->uuid16 = uuid16;
2603     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), uuid16);
2604     gatt_client->characteristic_start_handle = 0;
2605     gatt_client->state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
2606     gatt_client_run();
2607     return ERROR_CODE_SUCCESS;
2608 }
2609 
2610 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){
2611     gatt_client_t * gatt_client;
2612     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2613     if (status != ERROR_CODE_SUCCESS){
2614         return status;
2615     }
2616 
2617     gatt_client->callback = callback;
2618     gatt_client->start_group_handle = start_handle;
2619     gatt_client->end_group_handle   = end_handle;
2620     gatt_client->filter_with_uuid = true;
2621     gatt_client->uuid16 = 0;
2622     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2623     gatt_client->characteristic_start_handle = 0;
2624     gatt_client->state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
2625     gatt_client_run();
2626     return ERROR_CODE_SUCCESS;
2627 }
2628 
2629 
2630 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){
2631     return gatt_client_discover_characteristics_for_handle_range_by_uuid16(callback, con_handle, service->start_group_handle, service->end_group_handle, uuid16);
2632 }
2633 
2634 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){
2635     return gatt_client_discover_characteristics_for_handle_range_by_uuid128(callback, con_handle, service->start_group_handle, service->end_group_handle, uuid128);
2636 }
2637 
2638 uint8_t gatt_client_discover_characteristic_descriptors(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2639     gatt_client_t * gatt_client;
2640     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2641     if (status != ERROR_CODE_SUCCESS){
2642         return status;
2643     }
2644 
2645     // check if there is space for characteristics descriptors
2646     if (characteristic->end_handle > characteristic->value_handle){
2647         gatt_client->callback = callback;
2648         gatt_client->start_group_handle = characteristic->value_handle + 1u;
2649         gatt_client->end_group_handle   = characteristic->end_handle;
2650         gatt_client->state = P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY;
2651         gatt_client_run();
2652     } else {
2653         // schedule gatt complete event on next run loop iteration otherwise
2654         gatt_client->state = P_W2_EMIT_QUERY_COMPLETE_EVENT;
2655         gatt_client_deferred_event_emit.callback = gatt_client_emit_events;
2656         btstack_run_loop_execute_on_main_thread(&gatt_client_deferred_event_emit);
2657     }
2658     return ERROR_CODE_SUCCESS;
2659 }
2660 
2661 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){
2662     gatt_client_t * gatt_client;
2663     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2664     if (status != ERROR_CODE_SUCCESS){
2665         return status;
2666     }
2667 
2668     gatt_client->callback = callback;
2669     gatt_client->attribute_handle = value_handle;
2670     gatt_client->attribute_offset = 0;
2671     gatt_client->state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY;
2672     gatt_client_run();
2673     return ERROR_CODE_SUCCESS;
2674 }
2675 
2676 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){
2677     gatt_client_t * gatt_client;
2678     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2679     if (status != ERROR_CODE_SUCCESS){
2680         return status;
2681     }
2682 
2683     gatt_client->callback = callback;
2684     gatt_client->start_group_handle = start_handle;
2685     gatt_client->end_group_handle = end_handle;
2686     gatt_client->query_start_handle = start_handle;
2687     gatt_client->query_end_handle = end_handle;
2688     gatt_client->uuid16 = uuid16;
2689     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), uuid16);
2690     gatt_client->state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2691     gatt_client_run();
2692     return ERROR_CODE_SUCCESS;
2693 }
2694 
2695 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){
2696     gatt_client_t * gatt_client;
2697     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2698     if (status != ERROR_CODE_SUCCESS){
2699         return status;
2700     }
2701 
2702     gatt_client->callback = callback;
2703     gatt_client->start_group_handle = start_handle;
2704     gatt_client->end_group_handle = end_handle;
2705     gatt_client->query_start_handle = start_handle;
2706     gatt_client->query_end_handle = end_handle;
2707     gatt_client->uuid16 = 0;
2708     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2709     gatt_client->state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2710     gatt_client_run();
2711     return ERROR_CODE_SUCCESS;
2712 }
2713 
2714 
2715 uint8_t gatt_client_read_value_of_characteristic(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2716     return gatt_client_read_value_of_characteristic_using_value_handle(callback, con_handle, characteristic->value_handle);
2717 }
2718 
2719 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){
2720     gatt_client_t * gatt_client;
2721     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2722     if (status != ERROR_CODE_SUCCESS){
2723         return status;
2724     }
2725 
2726     gatt_client->callback = callback;
2727     gatt_client->attribute_handle = value_handle;
2728     gatt_client->attribute_offset = offset;
2729     gatt_client->state = P_W2_SEND_READ_BLOB_QUERY;
2730     gatt_client_run();
2731     return ERROR_CODE_SUCCESS;
2732 }
2733 
2734 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){
2735     return gatt_client_read_long_value_of_characteristic_using_value_handle_with_offset(callback, con_handle, value_handle, 0);
2736 }
2737 
2738 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){
2739     return gatt_client_read_long_value_of_characteristic_using_value_handle(callback, con_handle, characteristic->value_handle);
2740 }
2741 
2742 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){
2743     gatt_client_t * gatt_client;
2744     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2745     if (status != ERROR_CODE_SUCCESS){
2746         return status;
2747     }
2748 
2749 #ifdef ENABLE_GATT_OVER_EATT
2750     if (state == P_W2_SEND_READ_MULTIPLE_VARIABLE_REQUEST){
2751         if (gatt_client->bearer_type != ATT_BEARER_ENHANCED_LE){
2752             return ERROR_CODE_COMMAND_DISALLOWED;
2753         }
2754     }
2755 #endif
2756 
2757     gatt_client->callback = callback;
2758     gatt_client->read_multiple_handle_count = num_value_handles;
2759     gatt_client->read_multiple_handles = value_handles;
2760     gatt_client->state = state;
2761     gatt_client_run();
2762     return ERROR_CODE_SUCCESS;
2763 }
2764 
2765 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){
2766     return gatt_client_read_multiple_characteristic_values_with_state(callback, con_handle, num_value_handles, value_handles, P_W2_SEND_READ_MULTIPLE_REQUEST);
2767 }
2768 
2769 #ifdef ENABLE_GATT_OVER_EATT
2770 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){
2771     return gatt_client_read_multiple_characteristic_values_with_state(callback, con_handle, num_value_handles, value_handles, P_W2_SEND_READ_MULTIPLE_VARIABLE_REQUEST);
2772 }
2773 #endif
2774 
2775 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){
2776     gatt_client_t * gatt_client;
2777     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2778     if (status != ERROR_CODE_SUCCESS){
2779         return status;
2780     }
2781 
2782     if (value_length > (gatt_client->mtu - 3u)) return GATT_CLIENT_VALUE_TOO_LONG;
2783     if (!att_dispatch_client_can_send_now(gatt_client->con_handle)) return GATT_CLIENT_BUSY;
2784 
2785     return att_write_request(gatt_client, ATT_WRITE_COMMAND, value_handle, value_length, value);
2786 }
2787 
2788 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){
2789     gatt_client_t * gatt_client;
2790     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2791     if (status != ERROR_CODE_SUCCESS){
2792         return status;
2793     }
2794 
2795     gatt_client->callback = callback;
2796     gatt_client->attribute_handle = value_handle;
2797     gatt_client->attribute_length = value_length;
2798     gatt_client->attribute_value = value;
2799     gatt_client->state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
2800     gatt_client_run();
2801     return ERROR_CODE_SUCCESS;
2802 }
2803 
2804 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){
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     gatt_client->callback = callback;
2812     gatt_client->attribute_handle = value_handle;
2813     gatt_client->attribute_length = value_length;
2814     gatt_client->attribute_offset = offset;
2815     gatt_client->attribute_value = value;
2816     gatt_client->state = P_W2_PREPARE_WRITE;
2817     gatt_client_run();
2818     return ERROR_CODE_SUCCESS;
2819 }
2820 
2821 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){
2822     return gatt_client_write_long_value_of_characteristic_with_offset(callback, con_handle, value_handle, 0, value_length, value);
2823 }
2824 
2825 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){
2826     gatt_client_t * gatt_client;
2827     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2828     if (status != ERROR_CODE_SUCCESS){
2829         return status;
2830     }
2831 
2832     gatt_client->callback = callback;
2833     gatt_client->attribute_handle = value_handle;
2834     gatt_client->attribute_length = value_length;
2835     gatt_client->attribute_offset = 0;
2836     gatt_client->attribute_value = value;
2837     gatt_client->state = P_W2_PREPARE_RELIABLE_WRITE;
2838     gatt_client_run();
2839     return ERROR_CODE_SUCCESS;
2840 }
2841 
2842 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){
2843     gatt_client_t * gatt_client;
2844     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2845     if (status != ERROR_CODE_SUCCESS){
2846         return status;
2847     }
2848 
2849     if (configuration > 3){
2850         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
2851     }
2852 
2853     if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION) &&
2854         ((characteristic->properties & ATT_PROPERTY_NOTIFY) == 0u)) {
2855         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED");
2856         return GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED;
2857     } else if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_INDICATION) &&
2858                ((characteristic->properties & ATT_PROPERTY_INDICATE) == 0u)){
2859         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED");
2860         return GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED;
2861     }
2862 
2863     gatt_client->callback = callback;
2864     gatt_client->start_group_handle = characteristic->value_handle;
2865     gatt_client->end_group_handle = characteristic->end_handle;
2866     little_endian_store_16(gatt_client->client_characteristic_configuration_value, 0, configuration);
2867 
2868 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
2869     gatt_client->gatt_client_state = P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2870 #else
2871     gatt_client->state = P_W2_SEND_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2872 #endif
2873     gatt_client_run();
2874     return ERROR_CODE_SUCCESS;
2875 }
2876 
2877 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){
2878     gatt_client_t * gatt_client;
2879     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2880     if (status != ERROR_CODE_SUCCESS){
2881         return status;
2882     }
2883 
2884     gatt_client->callback = callback;
2885     gatt_client->attribute_handle = descriptor_handle;
2886 
2887     gatt_client->state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
2888     gatt_client_run();
2889     return ERROR_CODE_SUCCESS;
2890 }
2891 
2892 uint8_t gatt_client_read_characteristic_descriptor(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_descriptor_t * descriptor){
2893     return gatt_client_read_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
2894 }
2895 
2896 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){
2897     gatt_client_t * gatt_client;
2898     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2899     if (status != ERROR_CODE_SUCCESS){
2900         return status;
2901     }
2902 
2903     gatt_client->callback = callback;
2904     gatt_client->attribute_handle = descriptor_handle;
2905     gatt_client->attribute_offset = offset;
2906     gatt_client->state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
2907     gatt_client_run();
2908     return ERROR_CODE_SUCCESS;
2909 }
2910 
2911 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){
2912     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0);
2913 }
2914 
2915 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){
2916     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
2917 }
2918 
2919 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){
2920     gatt_client_t * gatt_client;
2921     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2922     if (status != ERROR_CODE_SUCCESS){
2923         return status;
2924     }
2925 
2926     gatt_client->callback = callback;
2927     gatt_client->attribute_handle = descriptor_handle;
2928     gatt_client->attribute_length = value_length;
2929     gatt_client->attribute_offset = 0;
2930     gatt_client->attribute_value = value;
2931     gatt_client->state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
2932     gatt_client_run();
2933     return ERROR_CODE_SUCCESS;
2934 }
2935 
2936 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){
2937     return gatt_client_write_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, value_length, value);
2938 }
2939 
2940 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){
2941     gatt_client_t * gatt_client;
2942     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2943     if (status != ERROR_CODE_SUCCESS){
2944         return status;
2945     }
2946 
2947     gatt_client->callback = callback;
2948     gatt_client->attribute_handle = descriptor_handle;
2949     gatt_client->attribute_length = value_length;
2950     gatt_client->attribute_offset = offset;
2951     gatt_client->attribute_value = value;
2952     gatt_client->state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
2953     gatt_client_run();
2954     return ERROR_CODE_SUCCESS;
2955 }
2956 
2957 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){
2958     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0, value_length, value);
2959 }
2960 
2961 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){
2962     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, value_length, value);
2963 }
2964 
2965 /**
2966  * @brief -> gatt complete event
2967  */
2968 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){
2969     gatt_client_t * gatt_client;
2970     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2971     if (status != ERROR_CODE_SUCCESS){
2972         return status;
2973     }
2974 
2975     gatt_client->callback = callback;
2976     gatt_client->attribute_handle = attribute_handle;
2977     gatt_client->attribute_length = value_length;
2978     gatt_client->attribute_offset = offset;
2979     gatt_client->attribute_value = value;
2980     gatt_client->state = P_W2_PREPARE_WRITE_SINGLE;
2981     gatt_client_run();
2982     return ERROR_CODE_SUCCESS;
2983 }
2984 
2985 /**
2986  * @brief -> gatt complete event
2987  */
2988 uint8_t gatt_client_execute_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2989     gatt_client_t * gatt_client;
2990     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2991     if (status != ERROR_CODE_SUCCESS){
2992         return status;
2993     }
2994 
2995     gatt_client->callback = callback;
2996     gatt_client->state = P_W2_EXECUTE_PREPARED_WRITE;
2997     gatt_client_run();
2998     return ERROR_CODE_SUCCESS;
2999 }
3000 
3001 /**
3002  * @brief -> gatt complete event
3003  */
3004 uint8_t gatt_client_cancel_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
3005     gatt_client_t * gatt_client;
3006     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
3007     if (status != ERROR_CODE_SUCCESS){
3008         return status;
3009     }
3010 
3011     gatt_client->callback = callback;
3012     gatt_client->state = P_W2_CANCEL_PREPARED_WRITE;
3013     gatt_client_run();
3014     return ERROR_CODE_SUCCESS;
3015 }
3016 
3017 void gatt_client_deserialize_service(const uint8_t *packet, int offset, gatt_client_service_t * service){
3018     service->start_group_handle = little_endian_read_16(packet, offset);
3019     service->end_group_handle = little_endian_read_16(packet, offset + 2);
3020     reverse_128(&packet[offset + 4], service->uuid128);
3021     if (uuid_has_bluetooth_prefix(service->uuid128)){
3022         service->uuid16 = big_endian_read_32(service->uuid128, 0);
3023     } else {
3024         service->uuid16 = 0;
3025     }
3026 }
3027 
3028 void gatt_client_deserialize_characteristic(const uint8_t * packet, int offset, gatt_client_characteristic_t * characteristic){
3029     characteristic->start_handle = little_endian_read_16(packet, offset);
3030     characteristic->value_handle = little_endian_read_16(packet, offset + 2);
3031     characteristic->end_handle = little_endian_read_16(packet, offset + 4);
3032     characteristic->properties = little_endian_read_16(packet, offset + 6);
3033     reverse_128(&packet[offset+8], characteristic->uuid128);
3034     if (uuid_has_bluetooth_prefix(characteristic->uuid128)){
3035         characteristic->uuid16 = big_endian_read_32(characteristic->uuid128, 0);
3036     } else {
3037         characteristic->uuid16 = 0;
3038     }
3039 }
3040 
3041 void gatt_client_deserialize_characteristic_descriptor(const uint8_t * packet, int offset, gatt_client_characteristic_descriptor_t * descriptor){
3042     descriptor->handle = little_endian_read_16(packet, offset);
3043     reverse_128(&packet[offset+2], descriptor->uuid128);
3044     if (uuid_has_bluetooth_prefix(descriptor->uuid128)){
3045         descriptor->uuid16 = big_endian_read_32(descriptor->uuid128, 0);
3046     } else {
3047         descriptor->uuid16 = 0;
3048     }
3049 }
3050 
3051 void gatt_client_send_mtu_negotiation(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
3052     gatt_client_t * gatt_client;
3053     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3054     if (status != ERROR_CODE_SUCCESS){
3055         return;
3056     }
3057     if (gatt_client->mtu_state == MTU_AUTO_EXCHANGE_DISABLED){
3058         gatt_client->callback = callback;
3059         gatt_client->mtu_state = SEND_MTU_EXCHANGE;
3060         gatt_client_run();
3061     }
3062 }
3063 
3064 uint8_t gatt_client_request_to_write_without_response(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
3065     gatt_client_t * gatt_client;
3066     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3067     if (status != ERROR_CODE_SUCCESS){
3068         return status;
3069     }
3070     bool added = btstack_linked_list_add_tail(&gatt_client->write_without_response_requests, (btstack_linked_item_t*) callback_registration);
3071     if (added == false){
3072         return ERROR_CODE_COMMAND_DISALLOWED;
3073     } else {
3074         att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
3075         return ERROR_CODE_SUCCESS;
3076     }
3077 }
3078 
3079 uint8_t gatt_client_request_to_send_gatt_query(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
3080     gatt_client_t * gatt_client;
3081     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3082     if (status != ERROR_CODE_SUCCESS){
3083         return status;
3084     }
3085     bool added = btstack_linked_list_add_tail(&gatt_client->query_requests, (btstack_linked_item_t*) callback_registration);
3086     if (added == false){
3087         return ERROR_CODE_COMMAND_DISALLOWED;
3088     } else {
3089         gatt_client_notify_can_send_query(gatt_client);
3090         return ERROR_CODE_SUCCESS;
3091     }
3092 }
3093 
3094 uint8_t gatt_client_remove_gatt_query(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
3095     gatt_client_t * gatt_client;
3096     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3097     if (status != ERROR_CODE_SUCCESS){
3098         return status;
3099     }
3100     (void)btstack_linked_list_remove(&gatt_client->query_requests, (btstack_linked_item_t*) callback_registration);
3101     return ERROR_CODE_SUCCESS;
3102 }
3103 
3104 uint8_t gatt_client_request_can_write_without_response_event(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
3105     gatt_client_t * gatt_client;
3106     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3107     if (status != ERROR_CODE_SUCCESS){
3108         return status;
3109     }
3110     if (gatt_client->write_without_response_callback != NULL){
3111         return GATT_CLIENT_IN_WRONG_STATE;
3112     }
3113     gatt_client->write_without_response_callback = callback;
3114     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
3115     return ERROR_CODE_SUCCESS;
3116 }
3117 
3118 #ifdef ENABLE_GATT_CLIENT_SERVICE_CHANGED
3119 void gatt_client_add_service_changed_handler(btstack_packet_callback_registration_t * callback) {
3120     btstack_linked_list_add_tail(&gatt_client_service_changed_handler, (btstack_linked_item_t*) callback);
3121 }
3122 
3123 void gatt_client_remove_service_changed_handler(btstack_packet_callback_registration_t * callback){
3124     btstack_linked_list_remove(&gatt_client_service_changed_handler, (btstack_linked_item_t*) callback);
3125 }
3126 #endif
3127 
3128 #if defined(ENABLE_GATT_OVER_CLASSIC) || defined(ENABLE_GATT_OVER_EATT)
3129 
3130 #include "hci_event.h"
3131 
3132 static const hci_event_t gatt_client_connected = {
3133         GATT_EVENT_CONNECTED, 0, "11BH"
3134 };
3135 
3136 static const hci_event_t gatt_client_disconnected = {
3137         GATT_EVENT_DISCONNECTED, 0, "H"
3138 };
3139 
3140 static void
3141 gatt_client_emit_connected(btstack_packet_handler_t callback, uint8_t status, bd_addr_type_t addr_type, bd_addr_t addr,
3142                            hci_con_handle_t con_handle) {
3143     uint8_t buffer[20];
3144     uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_connected, status, addr, con_handle);
3145     (*callback)(HCI_EVENT_PACKET, 0, buffer, len);
3146 }
3147 
3148 #endif
3149 
3150 #ifdef ENABLE_GATT_OVER_CLASSIC
3151 
3152 #include "bluetooth_psm.h"
3153 
3154 // single active SDP query
3155 static gatt_client_t * gatt_client_classic_active_sdp_query;
3156 
3157 // macos protocol descriptor list requires 16 bytes
3158 static uint8_t gatt_client_classic_sdp_buffer[32];
3159 
3160 
3161 static gatt_client_t * gatt_client_get_context_for_classic_addr(bd_addr_t addr){
3162     btstack_linked_item_t *it;
3163     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
3164         gatt_client_t * gatt_client = (gatt_client_t *) it;
3165         if (memcmp(gatt_client->addr, addr, 6) == 0){
3166             return gatt_client;
3167         }
3168     }
3169     return NULL;
3170 }
3171 
3172 static gatt_client_t * gatt_client_get_context_for_l2cap_cid(uint16_t l2cap_cid){
3173     btstack_linked_item_t *it;
3174     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
3175         gatt_client_t * gatt_client = (gatt_client_t *) it;
3176         if (gatt_client->l2cap_cid == l2cap_cid){
3177             return gatt_client;
3178         }
3179     }
3180     return NULL;
3181 }
3182 
3183 static void gatt_client_classic_handle_connected(gatt_client_t * gatt_client, uint8_t status){
3184     // cache peer information
3185     bd_addr_t addr;
3186     // cppcheck-suppress uninitvar ; addr is reported as uninitialized although it's the destination of the memcpy
3187     memcpy(addr, gatt_client->addr, 6);
3188     bd_addr_type_t addr_type = gatt_client->addr_type;
3189     gatt_client->addr_type = BD_ADDR_TYPE_ACL;
3190     hci_con_handle_t con_handle = gatt_client->con_handle;
3191     btstack_packet_handler_t callback = gatt_client->callback;
3192 
3193     if (status != ERROR_CODE_SUCCESS){
3194         btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
3195         btstack_memory_gatt_client_free(gatt_client);
3196     }
3197 
3198     gatt_client_emit_connected(callback, status, addr_type, addr, con_handle);
3199 }
3200 
3201 static void gatt_client_classic_retry(btstack_timer_source_t * ts){
3202     gatt_client_t * gatt_client = gatt_client_for_timer(ts);
3203     if (gatt_client != NULL){
3204         gatt_client->state = P_W4_L2CAP_CONNECTION;
3205         att_dispatch_classic_connect(gatt_client->addr, gatt_client->l2cap_psm, &gatt_client->l2cap_cid);
3206     }
3207 }
3208 
3209 static void gatt_client_classic_handle_disconnected(gatt_client_t * gatt_client){
3210 
3211     gatt_client_report_error_if_pending(gatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
3212     gatt_client_timeout_stop(gatt_client);
3213 
3214     hci_con_handle_t con_handle = gatt_client->con_handle;
3215     btstack_packet_handler_t callback = gatt_client->callback;
3216     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
3217     btstack_memory_gatt_client_free(gatt_client);
3218 
3219     uint8_t buffer[20];
3220     uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_disconnected, con_handle);
3221     (*callback)(HCI_EVENT_PACKET, 0, buffer, len);
3222 }
3223 
3224 static void gatt_client_handle_sdp_client_query_attribute_value(gatt_client_t * connection, uint8_t *packet){
3225     des_iterator_t des_list_it;
3226     des_iterator_t prot_it;
3227 
3228     if (sdp_event_query_attribute_byte_get_attribute_length(packet) <= sizeof(gatt_client_classic_sdp_buffer)) {
3229         gatt_client_classic_sdp_buffer[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet);
3230         if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)) {
3231             switch(sdp_event_query_attribute_byte_get_attribute_id(packet)) {
3232                 case BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST:
3233                     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)) {
3234                         uint8_t       *des_element;
3235                         uint8_t       *element;
3236                         uint32_t       uuid;
3237 
3238                         if (des_iterator_get_type(&des_list_it) != DE_DES) continue;
3239 
3240                         des_element = des_iterator_get_element(&des_list_it);
3241                         des_iterator_init(&prot_it, des_element);
3242                         element = des_iterator_get_element(&prot_it);
3243 
3244                         if (de_get_element_type(element) != DE_UUID) continue;
3245 
3246                         uuid = de_get_uuid32(element);
3247                         des_iterator_next(&prot_it);
3248                         // we assume that the even if there are both roles supported, remote device uses the same psm and avdtp version for both
3249                         switch (uuid){
3250                             case BLUETOOTH_PROTOCOL_L2CAP:
3251                                 if (!des_iterator_has_more(&prot_it)) continue;
3252                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &connection->l2cap_psm);
3253                                 break;
3254                             default:
3255                                 break;
3256                         }
3257                     }
3258                     break;
3259 
3260                 default:
3261                     break;
3262             }
3263         }
3264     }
3265 }
3266 
3267 static void gatt_client_classic_sdp_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
3268     gatt_client_t * gatt_client = gatt_client_classic_active_sdp_query;
3269     btstack_assert(gatt_client != NULL);
3270     uint8_t status;
3271 
3272     // TODO: handle sdp events, get l2cap psm
3273     switch (hci_event_packet_get_type(packet)){
3274         case SDP_EVENT_QUERY_ATTRIBUTE_VALUE:
3275             gatt_client_handle_sdp_client_query_attribute_value(gatt_client, packet);
3276             // TODO:
3277             return;
3278         case SDP_EVENT_QUERY_COMPLETE:
3279             status = sdp_event_query_complete_get_status(packet);
3280             gatt_client_classic_active_sdp_query = NULL;
3281             log_info("l2cap psm: %0x, status %02x", gatt_client->l2cap_psm, status);
3282             if (status != ERROR_CODE_SUCCESS) break;
3283             if (gatt_client->l2cap_psm == 0) {
3284                 status = SDP_SERVICE_NOT_FOUND;
3285                 break;
3286             }
3287             break;
3288         default:
3289             btstack_assert(false);
3290             return;
3291     }
3292 
3293     // done
3294     if (status == ERROR_CODE_SUCCESS){
3295         gatt_client->state = P_W4_L2CAP_CONNECTION;
3296         status = att_dispatch_classic_connect(gatt_client->addr, gatt_client->l2cap_psm, &gatt_client->l2cap_cid);
3297     }
3298     if (status != ERROR_CODE_SUCCESS) {
3299         gatt_client_classic_handle_connected(gatt_client, status);
3300     }
3301 }
3302 
3303 static void gatt_client_classic_sdp_start(void * context){
3304     gatt_client_classic_active_sdp_query = (gatt_client_t *) context;
3305     gatt_client_classic_active_sdp_query->state = P_W4_SDP_QUERY;
3306     sdp_client_query_uuid16(gatt_client_classic_sdp_handler, gatt_client_classic_active_sdp_query->addr, ORG_BLUETOOTH_SERVICE_GENERIC_ATTRIBUTE);
3307 }
3308 
3309 static void gatt_client_classic_emit_connected(void * context){
3310     gatt_client_t * gatt_client = (gatt_client_t *) context;
3311     gatt_client->state = P_READY;
3312     gatt_client_emit_connected(gatt_client->callback, ERROR_CODE_SUCCESS, gatt_client->addr_type, gatt_client->addr, gatt_client->con_handle);
3313 }
3314 
3315 uint8_t gatt_client_classic_connect(btstack_packet_handler_t callback, bd_addr_t addr){
3316     gatt_client_t * gatt_client = gatt_client_get_context_for_classic_addr(addr);
3317     if (gatt_client != NULL){
3318         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
3319     }
3320     gatt_client = btstack_memory_gatt_client_get();
3321     if (gatt_client == NULL){
3322         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
3323     }
3324     // init state
3325     gatt_client->bearer_type = ATT_BEARER_UNENHANCED_CLASSIC;
3326     gatt_client->con_handle = HCI_CON_HANDLE_INVALID;
3327     memcpy(gatt_client->addr, addr, 6);
3328     gatt_client->addr_type = BD_ADDR_TYPE_ACL;
3329     gatt_client->mtu = ATT_DEFAULT_MTU;
3330     gatt_client->security_level = LEVEL_0;
3331     gatt_client->mtu_state = MTU_AUTO_EXCHANGE_DISABLED;
3332     gatt_client->callback = callback;
3333 #ifdef ENABLE_GATT_OVER_EATT
3334     gatt_client->eatt_state = GATT_CLIENT_EATT_IDLE;
3335 #endif
3336     btstack_linked_list_add(&gatt_client_connections, (btstack_linked_item_t*)gatt_client);
3337 
3338     // schedule emitted event if already connected, otherwise
3339     bool already_connected = false;
3340     hci_connection_t * hci_connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3341     if (hci_connection != NULL){
3342         if (hci_connection->att_server.l2cap_cid != 0){
3343             already_connected = true;
3344         }
3345     }
3346     gatt_client->callback_request.context = gatt_client;
3347     if (already_connected){
3348         gatt_client->con_handle = hci_connection->con_handle;
3349         gatt_client->callback_request.callback = &gatt_client_classic_emit_connected;
3350         gatt_client->state = P_W2_EMIT_CONNECTED;
3351         btstack_run_loop_execute_on_main_thread(&gatt_client->callback_request);
3352     } else {
3353         gatt_client->callback_request.callback = &gatt_client_classic_sdp_start;
3354         gatt_client->state = P_W2_SDP_QUERY;
3355         sdp_client_register_query_callback(&gatt_client->callback_request);
3356     }
3357     return ERROR_CODE_SUCCESS;
3358 }
3359 
3360 uint8_t gatt_client_classic_disconnect(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
3361     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
3362     if (gatt_client == NULL){
3363         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3364     }
3365     gatt_client->callback = callback;
3366     return l2cap_disconnect(gatt_client->l2cap_cid);
3367 }
3368 #endif
3369 
3370 #ifdef ENABLE_GATT_OVER_EATT
3371 
3372 #define MAX_NR_EATT_CHANNELS 5
3373 
3374 static void gatt_client_le_enhanced_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
3375 
3376 static uint8_t gatt_client_le_enhanced_num_eatt_clients_in_state(gatt_client_t * gatt_client, gatt_client_state_t state){
3377     uint8_t num_clients = 0;
3378     btstack_linked_list_iterator_t it;
3379     btstack_linked_list_iterator_init(&it, &gatt_client->eatt_clients);
3380     while (btstack_linked_list_iterator_has_next(&it)){
3381         gatt_client_t * eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3382         if (eatt_client->state == state){
3383             num_clients++;
3384         }
3385     }
3386     return num_clients;
3387 }
3388 
3389 static void gatt_client_eatt_finalize(gatt_client_t * gatt_client) {
3390     // free eatt clients
3391     btstack_linked_list_iterator_t it;
3392     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
3393     while (btstack_linked_list_iterator_has_next(&it)) {
3394         gatt_client_t *eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3395         btstack_linked_list_iterator_remove(&it);
3396         btstack_memory_gatt_client_free(eatt_client);
3397     }
3398 }
3399 
3400 // all channels connected
3401 static void gatt_client_le_enhanced_handle_connected(gatt_client_t * gatt_client, uint8_t status) {
3402     if (status == ERROR_CODE_SUCCESS){
3403         uint8_t num_ready = gatt_client_le_enhanced_num_eatt_clients_in_state(gatt_client, P_READY);
3404         if (num_ready > 0){
3405             gatt_client->eatt_state = GATT_CLIENT_EATT_READY;
3406             // free unused channels
3407             btstack_linked_list_iterator_t it;
3408             btstack_linked_list_iterator_init(&it, &gatt_client_connections);
3409             while (btstack_linked_list_iterator_has_next(&it)) {
3410                 gatt_client_t *eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3411                 if (eatt_client->state == P_L2CAP_CLOSED){
3412                     btstack_linked_list_iterator_remove(&it);
3413                     btstack_memory_gatt_client_free(eatt_client);
3414                 }
3415             }
3416         } else {
3417             hci_connection_t * hci_connection = hci_connection_for_handle(gatt_client->con_handle);
3418             btstack_assert(hci_connection != NULL);
3419             if (hci_connection->att_server.incoming_connection_request){
3420                 hci_connection->att_server.incoming_connection_request = false;
3421                 log_info("Collision, retry in 100ms");
3422                 gatt_client->state = P_W2_L2CAP_CONNECT;
3423                 // set timer for retry
3424                 btstack_run_loop_set_timer(&gatt_client->gc_timeout, GATT_CLIENT_COLLISION_BACKOFF_MS);
3425                 btstack_run_loop_set_timer_handler(&gatt_client->gc_timeout, gatt_client_le_enhanced_retry);
3426                 btstack_run_loop_add_timer(&gatt_client->gc_timeout);
3427                 return;
3428             } else {
3429                 gatt_client->eatt_state = GATT_CLIENT_EATT_IDLE;
3430                 status = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES;
3431             }
3432         }
3433     } else {
3434         gatt_client_eatt_finalize(gatt_client);
3435         gatt_client->eatt_state = GATT_CLIENT_EATT_IDLE;
3436     }
3437 
3438     gatt_client_emit_connected(gatt_client->callback, status, gatt_client->addr_type, gatt_client->addr, gatt_client->con_handle);
3439 }
3440 
3441 // single channel disconnected
3442 static void gatt_client_le_enhanced_handle_ecbm_disconnected(gatt_client_t * gatt_client, gatt_client_t * eatt_client) {
3443 
3444     // report error
3445     gatt_client_report_error_if_pending(eatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
3446 
3447     // free memory
3448     btstack_linked_list_remove(&gatt_client->eatt_clients, (btstack_linked_item_t *) eatt_client);
3449     btstack_memory_gatt_client_free(eatt_client);
3450 
3451     // last channel
3452     if (btstack_linked_list_empty(&gatt_client->eatt_clients)){
3453         hci_connection_t * hci_connection = hci_connection_for_handle(gatt_client->con_handle);
3454         hci_connection->att_server.eatt_outgoing_active = false;
3455 
3456         if (gatt_client->eatt_state == GATT_CLIENT_EATT_READY) {
3457             // report disconnected if last channel closed
3458             uint8_t buffer[20];
3459             uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_disconnected, gatt_client->con_handle);
3460             (*gatt_client->callback)(HCI_EVENT_PACKET, 0, buffer, len);
3461         }
3462     }
3463 }
3464 
3465 static gatt_client_t * gatt_client_le_enhanced_get_context_for_l2cap_cid(uint16_t l2cap_cid, gatt_client_t ** out_eatt_client){
3466     btstack_linked_list_iterator_t it;
3467     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
3468     while (btstack_linked_list_iterator_has_next(&it)) {
3469         gatt_client_t * gatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3470         btstack_linked_list_iterator_t it2;
3471         btstack_linked_list_iterator_init(&it2, &gatt_client->eatt_clients);
3472         while (btstack_linked_list_iterator_has_next(&it2)) {
3473             gatt_client_t * eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it2);
3474             if (eatt_client->l2cap_cid == l2cap_cid){
3475                 *out_eatt_client = eatt_client;
3476                 return gatt_client;
3477             }
3478         }
3479     }
3480     return NULL;
3481 }
3482 
3483 static void gatt_client_le_enhanced_setup_l2cap_channel(gatt_client_t * gatt_client){
3484     uint8_t num_channels = gatt_client->eatt_num_clients;
3485 
3486     // setup channels
3487     uint16_t buffer_size_per_client = gatt_client->eatt_storage_size / num_channels;
3488     uint16_t max_mtu = (buffer_size_per_client - REPORT_PREBUFFER_HEADER) / 2;
3489     uint8_t * receive_buffers[MAX_NR_EATT_CHANNELS];
3490     uint16_t  new_cids[MAX_NR_EATT_CHANNELS];
3491     memset(gatt_client->eatt_storage_buffer, 0, gatt_client->eatt_storage_size);
3492     uint8_t i;
3493     for (i=0;i<gatt_client->eatt_num_clients; i++){
3494         receive_buffers[i] = &gatt_client->eatt_storage_buffer[REPORT_PREBUFFER_HEADER];
3495         gatt_client->eatt_storage_buffer += REPORT_PREBUFFER_HEADER + max_mtu;
3496     }
3497 
3498     log_info("%u EATT clients with receive buffer size %u", gatt_client->eatt_num_clients, buffer_size_per_client);
3499 
3500     uint8_t status = l2cap_ecbm_create_channels(&gatt_client_le_enhanced_packet_handler,
3501                                                 gatt_client->con_handle,
3502                                                 gatt_client->security_level,
3503                                                 BLUETOOTH_PSM_EATT, num_channels,
3504                                                 L2CAP_LE_AUTOMATIC_CREDITS,
3505                                                 buffer_size_per_client,
3506                                                 receive_buffers,
3507                                                 new_cids);
3508 
3509     if (status == ERROR_CODE_SUCCESS){
3510         i = 0;
3511         btstack_linked_list_iterator_t it;
3512         btstack_linked_list_iterator_init(&it, &gatt_client->eatt_clients);
3513         while (btstack_linked_list_iterator_has_next(&it)) {
3514             gatt_client_t *new_eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3515 
3516             // init state with new cid and transmit buffer
3517             new_eatt_client->bearer_type = ATT_BEARER_ENHANCED_LE;
3518             new_eatt_client->con_handle = gatt_client->con_handle;
3519             new_eatt_client->mtu = 64;
3520             new_eatt_client->security_level = LEVEL_0;
3521             new_eatt_client->mtu_state = MTU_AUTO_EXCHANGE_DISABLED;
3522             new_eatt_client->state = P_W4_L2CAP_CONNECTION;
3523             new_eatt_client->l2cap_cid = new_cids[i];
3524             new_eatt_client->eatt_storage_buffer = gatt_client->eatt_storage_buffer;
3525             gatt_client->eatt_storage_buffer += max_mtu;
3526             i++;
3527         }
3528         gatt_client->eatt_state = GATT_CLIENT_EATT_L2CAP_SETUP;
3529     } else {
3530         gatt_client_le_enhanced_handle_connected(gatt_client, status);
3531     }
3532 }
3533 
3534 static void gatt_client_le_enhanced_retry(btstack_timer_source_t * ts){
3535     gatt_client_t * gatt_client = gatt_client_for_timer(ts);
3536     if (gatt_client != NULL){
3537         gatt_client->state = P_W4_L2CAP_CONNECTION;
3538         gatt_client_le_enhanced_setup_l2cap_channel(gatt_client);
3539     }
3540 }
3541 
3542 static void gatt_client_le_enhanced_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
3543     gatt_client_t *gatt_client;
3544     gatt_client_t *eatt_client;
3545     hci_con_handle_t con_handle;
3546     uint16_t l2cap_cid;
3547     uint8_t status;
3548     gatt_client_characteristic_t characteristic;
3549     gatt_client_service_t service;
3550     switch (packet_type) {
3551         case HCI_EVENT_PACKET:
3552             switch (hci_event_packet_get_type(packet)) {
3553                 case GATT_EVENT_SERVICE_QUERY_RESULT:
3554                     con_handle = gatt_event_service_query_result_get_handle(packet);
3555                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3556                     btstack_assert(gatt_client != NULL);
3557                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W4_DONE);
3558                     gatt_event_service_query_result_get_service(packet, &service);
3559                     gatt_client->gatt_service_start_group_handle = service.start_group_handle;
3560                     gatt_client->gatt_service_end_group_handle = service.end_group_handle;
3561                     break;
3562                 case GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT:
3563                     con_handle = gatt_event_characteristic_value_query_result_get_handle(packet);
3564                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3565                     btstack_assert(gatt_client != NULL);
3566                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_DONE);
3567                     if (gatt_event_characteristic_value_query_result_get_value_length(packet) >= 1) {
3568                         gatt_client->gatt_server_supported_features = gatt_event_characteristic_value_query_result_get_value(packet)[0];
3569                     }
3570                     break;
3571                 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
3572                     con_handle = gatt_event_characteristic_query_result_get_handle(packet);
3573                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3574                     btstack_assert(gatt_client != NULL);
3575                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_DONE);
3576                     gatt_event_characteristic_query_result_get_characteristic(packet, &characteristic);
3577                     gatt_client->gatt_client_supported_features_handle = characteristic.value_handle;
3578                     break;
3579                 case GATT_EVENT_QUERY_COMPLETE:
3580                     con_handle = gatt_event_query_complete_get_handle(packet);
3581                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3582                     btstack_assert(gatt_client != NULL);
3583                     switch (gatt_client->eatt_state){
3584                         case GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W4_DONE:
3585                             if (gatt_client->gatt_service_start_group_handle == 0){
3586                                 gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
3587                             } else {
3588                                 gatt_client->eatt_state = GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W2_SEND;
3589                             }
3590                             break;
3591                         case GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_DONE:
3592                             if ((gatt_client->gatt_server_supported_features & 1) == 0) {
3593                                 gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
3594                             } else {
3595                                 gatt_client->eatt_state = GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W2_SEND;
3596                             }
3597                             break;
3598                         case GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_DONE:
3599                             if (gatt_client->gatt_client_supported_features_handle == 0){
3600                                 gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
3601                             } else {
3602                                 gatt_client->eatt_state = GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W2_SEND;
3603                             }
3604                             break;
3605                         case GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W4_DONE:
3606                             gatt_client_le_enhanced_setup_l2cap_channel(gatt_client);
3607                             break;
3608                         default:
3609                             break;
3610                     }
3611                     break;
3612                 case L2CAP_EVENT_ECBM_CHANNEL_OPENED:
3613                     l2cap_cid = l2cap_event_ecbm_channel_opened_get_local_cid(packet);
3614                     gatt_client = gatt_client_le_enhanced_get_context_for_l2cap_cid(l2cap_cid, &eatt_client);
3615 
3616                     btstack_assert(gatt_client != NULL);
3617                     btstack_assert(eatt_client != NULL);
3618                     btstack_assert(eatt_client->state == P_W4_L2CAP_CONNECTION);
3619 
3620                     status = l2cap_event_channel_opened_get_status(packet);
3621                     if (status == ERROR_CODE_SUCCESS){
3622                         eatt_client->state = P_READY;
3623                         eatt_client->mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
3624                     } else {
3625                         eatt_client->state = P_L2CAP_CLOSED;
3626                     }
3627                     // connected if opened event for all channels received
3628                     if (gatt_client_le_enhanced_num_eatt_clients_in_state(gatt_client, P_W4_L2CAP_CONNECTION) == 0){
3629                         gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_SUCCESS);
3630                     }
3631                     break;
3632                 case L2CAP_EVENT_CHANNEL_CLOSED:
3633                     l2cap_cid = l2cap_event_channel_closed_get_local_cid(packet);
3634                     gatt_client = gatt_client_le_enhanced_get_context_for_l2cap_cid(l2cap_cid, &eatt_client);
3635                     btstack_assert(gatt_client != NULL);
3636                     btstack_assert(eatt_client != NULL);
3637                     gatt_client_le_enhanced_handle_ecbm_disconnected(gatt_client, eatt_client);
3638                     break;
3639                 default:
3640                     break;
3641             }
3642             break;
3643         case L2CAP_DATA_PACKET:
3644             gatt_client = gatt_client_le_enhanced_get_context_for_l2cap_cid(channel, &eatt_client);
3645             btstack_assert(gatt_client != NULL);
3646             btstack_assert(eatt_client != NULL);
3647             gatt_client_handle_att_response(eatt_client, packet, size);
3648             gatt_client_run();
3649             break;
3650         default:
3651             break;
3652     }
3653 }
3654 
3655 static bool gatt_client_le_enhanced_handle_can_send_query(gatt_client_t * gatt_client){
3656     uint8_t status = ERROR_CODE_SUCCESS;
3657     uint8_t gatt_client_supported_features = 0x06; // eatt + multiple value notifications
3658     switch (gatt_client->eatt_state){
3659         case GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W2_SEND:
3660             gatt_client->gatt_service_start_group_handle = 0;
3661             gatt_client->eatt_state = GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W4_DONE;
3662             status = gatt_client_discover_primary_services_by_uuid16(&gatt_client_le_enhanced_packet_handler,
3663                                                                      gatt_client->con_handle,
3664                                                                      ORG_BLUETOOTH_SERVICE_GENERIC_ATTRIBUTE);
3665             break;
3666         case GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W2_SEND:
3667             gatt_client->gatt_server_supported_features = 0;
3668             gatt_client->eatt_state = GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_DONE;
3669             status = gatt_client_read_value_of_characteristics_by_uuid16(&gatt_client_le_enhanced_packet_handler,
3670                                                                          gatt_client->con_handle,
3671                                                                          gatt_client->gatt_service_start_group_handle,
3672                                                                          gatt_client->gatt_service_end_group_handle,
3673                                                                          ORG_BLUETOOTH_CHARACTERISTIC_SERVER_SUPPORTED_FEATURES);
3674             return true;
3675         case GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W2_SEND:
3676             gatt_client->gatt_client_supported_features_handle = 0;
3677             gatt_client->eatt_state = GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_DONE;
3678             status = gatt_client_discover_characteristics_for_handle_range_by_uuid16(&gatt_client_le_enhanced_packet_handler,
3679                                                                                      gatt_client->con_handle,
3680                                                                                      gatt_client->gatt_service_start_group_handle,
3681                                                                                      gatt_client->gatt_service_end_group_handle,
3682                                                                                      ORG_BLUETOOTH_CHARACTERISTIC_CLIENT_SUPPORTED_FEATURES);
3683             return true;
3684         case GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W2_SEND:
3685             gatt_client->eatt_state = GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W4_DONE;
3686             status = gatt_client_write_value_of_characteristic(&gatt_client_le_enhanced_packet_handler, gatt_client->con_handle,
3687                                                                gatt_client->gatt_client_supported_features_handle, 1,
3688                                                                &gatt_client_supported_features);
3689             return true;
3690         default:
3691             break;
3692     }
3693     btstack_assert(status == ERROR_CODE_SUCCESS);
3694     UNUSED(status);
3695     return false;
3696 }
3697 
3698 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) {
3699     gatt_client_t * gatt_client;
3700     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3701     if (status != ERROR_CODE_SUCCESS){
3702         return status;
3703     }
3704 
3705     if (gatt_client->eatt_state != GATT_CLIENT_EATT_IDLE){
3706         return ERROR_CODE_COMMAND_DISALLOWED;
3707     }
3708 
3709     // need one buffer for sending and one for receiving. Receiving includes pre-buffer for reports
3710     uint16_t buffer_size_per_client = storage_size / num_channels;
3711     uint16_t max_mtu = (buffer_size_per_client - REPORT_PREBUFFER_HEADER) / 2;
3712     if (max_mtu < 64) {
3713         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
3714     }
3715 
3716     if ((num_channels == 0) || (num_channels > MAX_NR_EATT_CHANNELS)){
3717         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
3718     }
3719 
3720     // create max num_channel eatt clients
3721     uint8_t i;
3722     btstack_linked_list_t eatt_clients = NULL;
3723     for (i=0;i<num_channels;i++) {
3724         gatt_client_t * new_gatt_client = btstack_memory_gatt_client_get();
3725         if (new_gatt_client == NULL) {
3726             break;
3727         }
3728         btstack_linked_list_add(&eatt_clients, (btstack_linked_item_t*)new_gatt_client);
3729     }
3730 
3731     if (i != num_channels){
3732         while (true){
3733             gatt_client = (gatt_client_t *) btstack_linked_list_pop(&eatt_clients);
3734             if (gatt_client == NULL) {
3735                 break;
3736             }
3737             btstack_memory_gatt_client_free(gatt_client);
3738         }
3739         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
3740     }
3741 
3742     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
3743     hci_connection->att_server.eatt_outgoing_active = true;
3744 
3745     gatt_client->callback = callback;
3746     gatt_client->eatt_num_clients   = num_channels;
3747     gatt_client->eatt_storage_buffer = storage_buffer;
3748     gatt_client->eatt_storage_size   = storage_size;
3749     gatt_client->eatt_clients = eatt_clients;
3750     gatt_client->eatt_state = GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W2_SEND;
3751     gatt_client_notify_can_send_query(gatt_client);
3752 
3753     return ERROR_CODE_SUCCESS;
3754 }
3755 
3756 #endif
3757 
3758 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
3759 void gatt_client_att_packet_handler_fuzz(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
3760     gatt_client_att_packet_handler(packet_type, handle, packet, size);
3761 }
3762 
3763 uint8_t gatt_client_get_client(hci_con_handle_t con_handle, gatt_client_t ** out_gatt_client){
3764     uint8_t status = gatt_client_provide_context_for_handle(con_handle, out_gatt_client);
3765     return status;
3766 }
3767 #endif
3768