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