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