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