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