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