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