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