xref: /btstack/src/ble/gatt_client.c (revision cbba69d54e1fd9a55ee11d6bdf782475a7eb3734)
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 #ifdef ENABLE_GATT_OVER_EATT
1749         case ATT_MULTIPLE_HANDLE_VALUE_NTF:
1750             if (size >= 5u) {
1751                 uint16_t offset = 1;
1752                 while (true){
1753                     uint16_t value_handle = little_endian_read_16(packet, offset);
1754                     offset += 2;
1755                     uint16_t value_length = little_endian_read_16(packet, offset);
1756                     offset += 2;
1757                     if ((offset + value_length) > size) break;
1758                     report_gatt_notification(gatt_client, value_handle, &packet[offset], value_length);
1759                     offset += value_length;
1760                 }
1761             }
1762             return;
1763 #endif
1764         case ATT_HANDLE_VALUE_INDICATION:
1765             if (size < 3u) break;
1766             report_gatt_indication(gatt_client, little_endian_read_16(packet, 1u), &packet[3], size - 3u);
1767             gatt_client->send_confirmation = 1;
1768             break;
1769         case ATT_READ_BY_TYPE_RESPONSE:
1770             gatt_client_handle_att_read_by_type_response(gatt_client, packet, size);
1771             break;
1772         case ATT_READ_RESPONSE:
1773             gatt_client_handle_att_read_response(gatt_client, packet, size);
1774             break;
1775         case ATT_FIND_BY_TYPE_VALUE_RESPONSE: {
1776             uint8_t pair_size = 4;
1777             int i;
1778             uint16_t start_group_handle;
1779             uint16_t end_group_handle = 0xffff; // asserts GATT_EVENT_QUERY_COMPLETE is emitted if no results
1780             for (i = 1u; (i + pair_size) <= size; i += pair_size) {
1781                 start_group_handle = little_endian_read_16(packet, i);
1782                 end_group_handle = little_endian_read_16(packet, i + 2);
1783                 emit_gatt_service_query_result_event(gatt_client, start_group_handle, end_group_handle,
1784                                                      gatt_client->uuid128);
1785             }
1786             trigger_next_service_by_uuid_query(gatt_client, end_group_handle);
1787             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1788             break;
1789         }
1790         case ATT_FIND_INFORMATION_REPLY: {
1791             if (size < 2u) break;
1792 
1793             uint8_t pair_size = 4;
1794             if (packet[1u] == 2u) {
1795                 pair_size = 18;
1796             }
1797             uint16_t offset = 2;
1798 
1799             if (size < (pair_size + offset)) break;
1800             uint16_t last_descriptor_handle = little_endian_read_16(packet, size - pair_size);
1801 
1802 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
1803             log_info("ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY, state %x", gatt_client->gatt_client_state);
1804             if (gatt_client->gatt_client_state == P_W4_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT){
1805                 // iterate over descriptors looking for CCC
1806                 if (pair_size == 4){
1807                     while ((offset + 4) <= size){
1808                         uint16_t uuid16 = little_endian_read_16(packet, offset + 2);
1809                         if (uuid16 == GATT_CLIENT_CHARACTERISTICS_CONFIGURATION){
1810                             gatt_client->client_characteristic_configuration_handle = little_endian_read_16(packet, offset);
1811                             gatt_client->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
1812                             log_info("CCC found %x", gatt_client->client_characteristic_configuration_handle);
1813                             break;
1814                         }
1815                         offset += pair_size;
1816                     }
1817                 }
1818                 if (is_query_done(gatt_client, last_descriptor_handle)){
1819 
1820                 } else {
1821                     // next
1822                     gatt_client->start_group_handle = last_descriptor_handle + 1;
1823                     gatt_client->gatt_client_state = P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
1824                 }
1825                 break;
1826             }
1827 #endif
1828             report_gatt_all_characteristic_descriptors(gatt_client, &packet[2], size - 2u, pair_size);
1829             trigger_next_characteristic_descriptor_query(gatt_client, last_descriptor_handle);
1830             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1831             break;
1832         }
1833 
1834         case ATT_WRITE_RESPONSE:
1835             gatt_client_handle_att_write_response(gatt_client);
1836             break;
1837 
1838         case ATT_READ_BLOB_RESPONSE: {
1839             uint16_t received_blob_length = size - 1u;
1840             switch (gatt_client->gatt_client_state) {
1841                 case P_W4_READ_BLOB_RESULT:
1842                     report_gatt_long_characteristic_value_blob(gatt_client, gatt_client->attribute_handle, &packet[1],
1843                                                                received_blob_length, gatt_client->attribute_offset);
1844                     trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_QUERY, received_blob_length);
1845                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1846                     break;
1847                 case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
1848                     report_gatt_long_characteristic_descriptor(gatt_client, gatt_client->attribute_handle,
1849                                                                &packet[1], received_blob_length,
1850                                                                gatt_client->attribute_offset);
1851                     trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY,
1852                                             received_blob_length);
1853                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1854                     break;
1855                 default:
1856                     break;
1857             }
1858             break;
1859         }
1860         case ATT_PREPARE_WRITE_RESPONSE:
1861             switch (gatt_client->gatt_client_state) {
1862                 case P_W4_PREPARE_WRITE_SINGLE_RESULT:
1863                     if (is_value_valid(gatt_client, packet, size)) {
1864                         att_status = ATT_ERROR_SUCCESS;
1865                     } else {
1866                         att_status = ATT_ERROR_DATA_MISMATCH;
1867                     }
1868                     gatt_client_handle_transaction_complete(gatt_client, att_status);
1869                     break;
1870 
1871                 case P_W4_PREPARE_WRITE_RESULT: {
1872                     gatt_client->attribute_offset = little_endian_read_16(packet, 3);
1873                     trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_WRITE, P_W2_EXECUTE_PREPARED_WRITE);
1874                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1875                     break;
1876                 }
1877                 case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT: {
1878                     gatt_client->attribute_offset = little_endian_read_16(packet, 3);
1879                     trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR,
1880                                                      P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR);
1881                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1882                     break;
1883                 }
1884                 case P_W4_PREPARE_RELIABLE_WRITE_RESULT: {
1885                     if (is_value_valid(gatt_client, packet, size)) {
1886                         gatt_client->attribute_offset = little_endian_read_16(packet, 3);
1887                         trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_RELIABLE_WRITE,
1888                                                          P_W2_EXECUTE_PREPARED_WRITE);
1889                         // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1890                         break;
1891                     }
1892                     gatt_client->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
1893                     break;
1894                 }
1895                 default:
1896                     break;
1897             }
1898             break;
1899 
1900         case ATT_EXECUTE_WRITE_RESPONSE:
1901             switch (gatt_client->gatt_client_state) {
1902                 case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
1903                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1904                     break;
1905                 case P_W4_CANCEL_PREPARED_WRITE_RESULT:
1906                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1907                     break;
1908                 case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
1909                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_DATA_MISMATCH);
1910                     break;
1911                 case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1912                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1913                     break;
1914                 default:
1915                     break;
1916 
1917             }
1918             break;
1919 
1920         case ATT_READ_MULTIPLE_RESPONSE:
1921             switch (gatt_client->gatt_client_state) {
1922                 case P_W4_READ_MULTIPLE_RESPONSE:
1923                     report_gatt_characteristic_value(gatt_client, 0u, &packet[1], size - 1u);
1924                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1925                     break;
1926                 default:
1927                     break;
1928             }
1929             break;
1930 
1931 #ifdef ENABLE_GATT_OVER_EATT
1932         case ATT_READ_MULTIPLE_VARIABLE_RSP:
1933             switch (gatt_client->gatt_client_state) {
1934                 case P_W4_READ_MULTIPLE_VARIABLE_RESPONSE:
1935                     report_gatt_characteristic_value(gatt_client, 0u, &packet[1], size - 1u);
1936                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1937                     break;
1938                 default:
1939                     break;
1940             }
1941             break;
1942 #endif
1943 
1944         case ATT_ERROR_RESPONSE:
1945             if (size < 5u) return;
1946             att_status = packet[4];
1947             switch (att_status) {
1948                 case ATT_ERROR_ATTRIBUTE_NOT_FOUND: {
1949                     switch (gatt_client->gatt_client_state) {
1950                         case P_W4_SERVICE_QUERY_RESULT:
1951                         case P_W4_SERVICE_WITH_UUID_RESULT:
1952                         case P_W4_INCLUDED_SERVICE_QUERY_RESULT:
1953                         case P_W4_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
1954                             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1955                             break;
1956                         case P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT:
1957                         case P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT:
1958                             report_gatt_characteristic_end_found(gatt_client, gatt_client->end_group_handle);
1959                             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1960                             break;
1961                         case P_W4_READ_BY_TYPE_RESPONSE:
1962                             if (gatt_client->start_group_handle == gatt_client->query_start_handle) {
1963                                 att_status = ATT_ERROR_ATTRIBUTE_NOT_FOUND;
1964                             } else {
1965                                 att_status = ATT_ERROR_SUCCESS;
1966                             }
1967                             gatt_client_handle_transaction_complete(gatt_client, att_status);
1968                             break;
1969                         default:
1970                             gatt_client_report_error_if_pending(gatt_client, att_status);
1971                             break;
1972                     }
1973                     break;
1974                 }
1975 
1976 #ifdef ENABLE_GATT_CLIENT_PAIRING
1977 
1978                     case ATT_ERROR_INSUFFICIENT_AUTHENTICATION:
1979                     case ATT_ERROR_INSUFFICIENT_ENCRYPTION_KEY_SIZE:
1980                     case ATT_ERROR_INSUFFICIENT_ENCRYPTION: {
1981 
1982                         // security too low
1983                         if (gatt_client->security_counter > 0) {
1984                             gatt_client_report_error_if_pending(gatt_client, att_status);
1985                             break;
1986                         }
1987                         // start security
1988                         gatt_client->security_counter++;
1989 
1990                         // setup action
1991                         int retry = 1;
1992                         switch (gatt_client->gatt_client_state){
1993                             case P_W4_READ_CHARACTERISTIC_VALUE_RESULT:
1994                                 gatt_client->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY ;
1995                                 break;
1996                             case P_W4_READ_BLOB_RESULT:
1997                                 gatt_client->gatt_client_state = P_W2_SEND_READ_BLOB_QUERY;
1998                                 break;
1999                             case P_W4_READ_BY_TYPE_RESPONSE:
2000                                 gatt_client->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2001                                 break;
2002                             case P_W4_READ_MULTIPLE_RESPONSE:
2003                                 gatt_client->gatt_client_state = P_W2_SEND_READ_MULTIPLE_REQUEST;
2004                                 break;
2005                             case P_W4_READ_MULTIPLE_VARIABLE_RESPONSE:
2006                                 gatt_client->gatt_client_state = P_W2_SEND_READ_MULTIPLE_VARIABLE_REQUEST;
2007                                 break;
2008                             case P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT:
2009                                 gatt_client->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
2010                                 break;
2011                             case P_W4_PREPARE_WRITE_RESULT:
2012                                 gatt_client->gatt_client_state = P_W2_PREPARE_WRITE;
2013                                 break;
2014                             case P_W4_PREPARE_WRITE_SINGLE_RESULT:
2015                                 gatt_client->gatt_client_state = P_W2_PREPARE_WRITE_SINGLE;
2016                                 break;
2017                             case P_W4_PREPARE_RELIABLE_WRITE_RESULT:
2018                                 gatt_client->gatt_client_state = P_W2_PREPARE_RELIABLE_WRITE;
2019                                 break;
2020                             case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
2021                                 gatt_client->gatt_client_state = P_W2_EXECUTE_PREPARED_WRITE;
2022                                 break;
2023                             case P_W4_CANCEL_PREPARED_WRITE_RESULT:
2024                                 gatt_client->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE;
2025                                 break;
2026                             case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
2027                                 gatt_client->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
2028                                 break;
2029                             case P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT:
2030                                 gatt_client->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
2031                                 break;
2032                             case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
2033                                 gatt_client->gatt_client_state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
2034                                 break;
2035                             case P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
2036                                 gatt_client->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
2037                                 break;
2038                             case P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT:
2039                                 gatt_client->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
2040                                 break;
2041                             case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
2042                                 gatt_client->gatt_client_state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
2043                                 break;
2044                             case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
2045                                 gatt_client->gatt_client_state = P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR;
2046                                 break;
2047 #ifdef ENABLE_LE_SIGNED_WRITE
2048                             case P_W4_SEND_SINGED_WRITE_DONE:
2049                                 gatt_client->gatt_client_state = P_W2_SEND_SIGNED_WRITE;
2050                                 break;
2051 #endif
2052                             default:
2053                                 log_info("retry not supported for state %x", gatt_client->gatt_client_state);
2054                                 retry = 0;
2055                                 break;
2056                         }
2057 
2058                         if (!retry) {
2059                             gatt_client_report_error_if_pending(gatt_client, att_status);
2060                             break;
2061                         }
2062 
2063                         log_info("security error, start pairing");
2064 
2065                         // start pairing for higher security level
2066                         gatt_client->wait_for_authentication_complete = 1;
2067                         gatt_client->pending_error_code = att_status;
2068                         sm_request_pairing(gatt_client->con_handle);
2069                         break;
2070                     }
2071 #endif
2072 
2073                     // nothing we can do about that
2074                 case ATT_ERROR_INSUFFICIENT_AUTHORIZATION:
2075                 default:
2076                     gatt_client_report_error_if_pending(gatt_client, att_status);
2077                     break;
2078             }
2079             break;
2080 
2081         default:
2082             log_info("ATT Handler, unhandled response type 0x%02x", packet[0]);
2083             break;
2084     }
2085 }
2086 
2087 static void gatt_client_att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size) {
2088     gatt_client_t *gatt_client;
2089     if (size < 1u) return;
2090 
2091     if (packet_type == HCI_EVENT_PACKET) {
2092         switch (packet[0]) {
2093             case L2CAP_EVENT_CAN_SEND_NOW:
2094                 gatt_client_run();
2095                 break;
2096                 // att_server has negotiated the mtu for this connection, cache if context exists
2097             case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
2098                 if (size < 6u) break;
2099                 gatt_client = gatt_client_get_context_for_handle(handle);
2100                 if (gatt_client == NULL) break;
2101                 gatt_client->mtu = little_endian_read_16(packet, 4);
2102                 break;
2103             default:
2104                 break;
2105         }
2106         return;
2107     }
2108 
2109     if (packet_type != ATT_DATA_PACKET) return;
2110 
2111     // special cases: notifications & indications motivate creating context
2112     switch (packet[0]) {
2113         case ATT_HANDLE_VALUE_NOTIFICATION:
2114         case ATT_HANDLE_VALUE_INDICATION:
2115             gatt_client_provide_context_for_handle(handle, &gatt_client);
2116             break;
2117         default:
2118             gatt_client = gatt_client_get_context_for_handle(handle);
2119             break;
2120     }
2121 
2122     if (gatt_client != NULL) {
2123         gatt_client_handle_att_response(gatt_client, packet, size);
2124         gatt_client_run();
2125     }
2126 }
2127 
2128 #ifdef ENABLE_LE_SIGNED_WRITE
2129 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
2130     btstack_linked_list_iterator_t it;
2131     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
2132     while (btstack_linked_list_iterator_has_next(&it)){
2133         gatt_client_t * gatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
2134         if (gatt_client->gatt_client_state == P_W4_CMAC_RESULT){
2135             // store result
2136             (void)memcpy(gatt_client->cmac, hash, 8);
2137             // reverse_64(hash, gatt_client->cmac);
2138             gatt_client->gatt_client_state = P_W2_SEND_SIGNED_WRITE;
2139             gatt_client_run();
2140             return;
2141         }
2142     }
2143 }
2144 
2145 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){
2146     gatt_client_t * gatt_client;
2147     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2148     if (status != ERROR_CODE_SUCCESS){
2149         return status;
2150     }
2151     if (is_ready(gatt_client) == 0){
2152         return GATT_CLIENT_IN_WRONG_STATE;
2153     }
2154 
2155     gatt_client->callback = callback;
2156     gatt_client->attribute_handle = value_handle;
2157     gatt_client->attribute_length = message_len;
2158     gatt_client->attribute_value = message;
2159     gatt_client->gatt_client_state = P_W4_IDENTITY_RESOLVING;
2160     gatt_client_run();
2161     return ERROR_CODE_SUCCESS;
2162 }
2163 #endif
2164 
2165 uint8_t gatt_client_discover_primary_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_PRIMARY_SERVICE_UUID;
2177     gatt_client_run();
2178     return ERROR_CODE_SUCCESS;
2179 }
2180 
2181 uint8_t gatt_client_discover_secondary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
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_QUERY;
2192     gatt_client->uuid16 = GATT_SECONDARY_SERVICE_UUID;
2193     gatt_client_run();
2194     return ERROR_CODE_SUCCESS;
2195 }
2196 
2197 uint8_t gatt_client_discover_primary_services_by_uuid16(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t uuid16){
2198     gatt_client_t * gatt_client;
2199     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2200     if (status != ERROR_CODE_SUCCESS){
2201         return status;
2202     }
2203 
2204     gatt_client->callback = callback;
2205     gatt_client->start_group_handle = 0x0001;
2206     gatt_client->end_group_handle   = 0xffff;
2207     gatt_client->gatt_client_state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
2208     gatt_client->uuid16 = uuid16;
2209     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), gatt_client->uuid16);
2210     gatt_client_run();
2211     return ERROR_CODE_SUCCESS;
2212 }
2213 
2214 uint8_t gatt_client_discover_primary_services_by_uuid128(btstack_packet_handler_t callback, hci_con_handle_t con_handle, const uint8_t * uuid128){
2215     gatt_client_t * gatt_client;
2216     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2217     if (status != ERROR_CODE_SUCCESS){
2218         return status;
2219     }
2220 
2221     gatt_client->callback = callback;
2222     gatt_client->start_group_handle = 0x0001;
2223     gatt_client->end_group_handle   = 0xffff;
2224     gatt_client->uuid16 = 0;
2225     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2226     gatt_client->gatt_client_state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
2227     gatt_client_run();
2228     return ERROR_CODE_SUCCESS;
2229 }
2230 
2231 uint8_t gatt_client_discover_characteristics_for_service(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_service_t * service){
2232     gatt_client_t * gatt_client;
2233     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2234     if (status != ERROR_CODE_SUCCESS){
2235         return status;
2236     }
2237 
2238     gatt_client->callback = callback;
2239     gatt_client->start_group_handle = service->start_group_handle;
2240     gatt_client->end_group_handle   = service->end_group_handle;
2241     gatt_client->filter_with_uuid = 0;
2242     gatt_client->characteristic_start_handle = 0;
2243     gatt_client->gatt_client_state = P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY;
2244     gatt_client_run();
2245     return ERROR_CODE_SUCCESS;
2246 }
2247 
2248 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){
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 = service->start_group_handle;
2257     gatt_client->end_group_handle   = service->end_group_handle;
2258     gatt_client->gatt_client_state = P_W2_SEND_INCLUDED_SERVICE_QUERY;
2259 
2260     gatt_client_run();
2261     return ERROR_CODE_SUCCESS;
2262 }
2263 
2264 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){
2265     gatt_client_t * gatt_client;
2266     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2267     if (status != ERROR_CODE_SUCCESS){
2268         return status;
2269     }
2270 
2271     gatt_client->callback = callback;
2272     gatt_client->start_group_handle = start_handle;
2273     gatt_client->end_group_handle   = end_handle;
2274     gatt_client->filter_with_uuid = 1;
2275     gatt_client->uuid16 = uuid16;
2276     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), uuid16);
2277     gatt_client->characteristic_start_handle = 0;
2278     gatt_client->gatt_client_state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
2279     gatt_client_run();
2280     return ERROR_CODE_SUCCESS;
2281 }
2282 
2283 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){
2284     gatt_client_t * gatt_client;
2285     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2286     if (status != ERROR_CODE_SUCCESS){
2287         return status;
2288     }
2289 
2290     gatt_client->callback = callback;
2291     gatt_client->start_group_handle = start_handle;
2292     gatt_client->end_group_handle   = end_handle;
2293     gatt_client->filter_with_uuid = 1;
2294     gatt_client->uuid16 = 0;
2295     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2296     gatt_client->characteristic_start_handle = 0;
2297     gatt_client->gatt_client_state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
2298     gatt_client_run();
2299     return ERROR_CODE_SUCCESS;
2300 }
2301 
2302 
2303 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){
2304     return gatt_client_discover_characteristics_for_handle_range_by_uuid16(callback, con_handle, service->start_group_handle, service->end_group_handle, uuid16);
2305 }
2306 
2307 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){
2308     return gatt_client_discover_characteristics_for_handle_range_by_uuid128(callback, con_handle, service->start_group_handle, service->end_group_handle, uuid128);
2309 }
2310 
2311 uint8_t gatt_client_discover_characteristic_descriptors(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2312     gatt_client_t * gatt_client;
2313     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2314     if (status != ERROR_CODE_SUCCESS){
2315         return status;
2316     }
2317 
2318     if (characteristic->value_handle == characteristic->end_handle){
2319         return ERROR_CODE_SUCCESS;
2320     }
2321     gatt_client->callback = callback;
2322     gatt_client->start_group_handle = characteristic->value_handle + 1u;
2323     gatt_client->end_group_handle   = characteristic->end_handle;
2324     gatt_client->gatt_client_state = P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY;
2325     gatt_client_run();
2326     return ERROR_CODE_SUCCESS;
2327 }
2328 
2329 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){
2330     gatt_client_t * gatt_client;
2331     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2332     if (status != ERROR_CODE_SUCCESS){
2333         return status;
2334     }
2335 
2336     gatt_client->callback = callback;
2337     gatt_client->attribute_handle = value_handle;
2338     gatt_client->attribute_offset = 0;
2339     gatt_client->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY;
2340     gatt_client_run();
2341     return ERROR_CODE_SUCCESS;
2342 }
2343 
2344 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){
2345     gatt_client_t * gatt_client;
2346     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2347     if (status != ERROR_CODE_SUCCESS){
2348         return status;
2349     }
2350 
2351     gatt_client->callback = callback;
2352     gatt_client->start_group_handle = start_handle;
2353     gatt_client->end_group_handle = end_handle;
2354     gatt_client->query_start_handle = start_handle;
2355     gatt_client->query_end_handle = end_handle;
2356     gatt_client->uuid16 = uuid16;
2357     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), uuid16);
2358     gatt_client->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2359     gatt_client_run();
2360     return ERROR_CODE_SUCCESS;
2361 }
2362 
2363 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){
2364     gatt_client_t * gatt_client;
2365     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2366     if (status != ERROR_CODE_SUCCESS){
2367         return status;
2368     }
2369 
2370     gatt_client->callback = callback;
2371     gatt_client->start_group_handle = start_handle;
2372     gatt_client->end_group_handle = end_handle;
2373     gatt_client->query_start_handle = start_handle;
2374     gatt_client->query_end_handle = end_handle;
2375     gatt_client->uuid16 = 0;
2376     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2377     gatt_client->gatt_client_state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2378     gatt_client_run();
2379     return ERROR_CODE_SUCCESS;
2380 }
2381 
2382 
2383 uint8_t gatt_client_read_value_of_characteristic(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2384     return gatt_client_read_value_of_characteristic_using_value_handle(callback, con_handle, characteristic->value_handle);
2385 }
2386 
2387 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){
2388     gatt_client_t * gatt_client;
2389     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2390     if (status != ERROR_CODE_SUCCESS){
2391         return status;
2392     }
2393 
2394     gatt_client->callback = callback;
2395     gatt_client->attribute_handle = value_handle;
2396     gatt_client->attribute_offset = offset;
2397     gatt_client->gatt_client_state = P_W2_SEND_READ_BLOB_QUERY;
2398     gatt_client_run();
2399     return ERROR_CODE_SUCCESS;
2400 }
2401 
2402 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){
2403     return gatt_client_read_long_value_of_characteristic_using_value_handle_with_offset(callback, con_handle, value_handle, 0);
2404 }
2405 
2406 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){
2407     return gatt_client_read_long_value_of_characteristic_using_value_handle(callback, con_handle, characteristic->value_handle);
2408 }
2409 
2410 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){
2411     gatt_client_t * gatt_client;
2412     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2413     if (status != ERROR_CODE_SUCCESS){
2414         return status;
2415     }
2416 
2417 #ifdef ENABLE_GATT_OVER_EATT
2418     if (state == P_W2_SEND_READ_MULTIPLE_VARIABLE_REQUEST){
2419         if (gatt_client->bearer_type != ATT_BEARER_ENHANCED_LE){
2420             return ERROR_CODE_COMMAND_DISALLOWED;
2421         }
2422     }
2423 #endif
2424 
2425     gatt_client->callback = callback;
2426     gatt_client->read_multiple_handle_count = num_value_handles;
2427     gatt_client->read_multiple_handles = value_handles;
2428     gatt_client->gatt_client_state = state;
2429     gatt_client_run();
2430     return ERROR_CODE_SUCCESS;
2431 }
2432 
2433 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){
2434     return gatt_client_read_multiple_characteristic_values_with_state(callback, con_handle, num_value_handles, value_handles, P_W2_SEND_READ_MULTIPLE_REQUEST);
2435 }
2436 
2437 #ifdef ENABLE_GATT_OVER_EATT
2438 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){
2439     return gatt_client_read_multiple_characteristic_values_with_state(callback, con_handle, num_value_handles, value_handles, P_W2_SEND_READ_MULTIPLE_VARIABLE_REQUEST);
2440 }
2441 #endif
2442 
2443 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){
2444     gatt_client_t * gatt_client;
2445     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2446     if (status != ERROR_CODE_SUCCESS){
2447         return status;
2448     }
2449 
2450     if (value_length > (gatt_client->mtu - 3u)) return GATT_CLIENT_VALUE_TOO_LONG;
2451     if (!att_dispatch_client_can_send_now(gatt_client->con_handle)) return GATT_CLIENT_BUSY;
2452 
2453     return att_write_request(gatt_client, ATT_WRITE_COMMAND, value_handle, value_length, value);
2454 }
2455 
2456 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){
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_value = value;
2467     gatt_client->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
2468     gatt_client_run();
2469     return ERROR_CODE_SUCCESS;
2470 }
2471 
2472 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){
2473     gatt_client_t * gatt_client;
2474     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2475     if (status != ERROR_CODE_SUCCESS){
2476         return status;
2477     }
2478 
2479     gatt_client->callback = callback;
2480     gatt_client->attribute_handle = value_handle;
2481     gatt_client->attribute_length = value_length;
2482     gatt_client->attribute_offset = offset;
2483     gatt_client->attribute_value = value;
2484     gatt_client->gatt_client_state = P_W2_PREPARE_WRITE;
2485     gatt_client_run();
2486     return ERROR_CODE_SUCCESS;
2487 }
2488 
2489 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){
2490     return gatt_client_write_long_value_of_characteristic_with_offset(callback, con_handle, value_handle, 0, value_length, value);
2491 }
2492 
2493 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){
2494     gatt_client_t * gatt_client;
2495     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2496     if (status != ERROR_CODE_SUCCESS){
2497         return status;
2498     }
2499 
2500     gatt_client->callback = callback;
2501     gatt_client->attribute_handle = value_handle;
2502     gatt_client->attribute_length = value_length;
2503     gatt_client->attribute_offset = 0;
2504     gatt_client->attribute_value = value;
2505     gatt_client->gatt_client_state = P_W2_PREPARE_RELIABLE_WRITE;
2506     gatt_client_run();
2507     return ERROR_CODE_SUCCESS;
2508 }
2509 
2510 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){
2511     gatt_client_t * gatt_client;
2512     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2513     if (status != ERROR_CODE_SUCCESS){
2514         return status;
2515     }
2516 
2517     if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION) &&
2518         ((characteristic->properties & ATT_PROPERTY_NOTIFY) == 0u)) {
2519         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED");
2520         return GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED;
2521     } else if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_INDICATION) &&
2522                ((characteristic->properties & ATT_PROPERTY_INDICATE) == 0u)){
2523         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED");
2524         return GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED;
2525     }
2526 
2527     gatt_client->callback = callback;
2528     gatt_client->start_group_handle = characteristic->value_handle;
2529     gatt_client->end_group_handle = characteristic->end_handle;
2530     little_endian_store_16(gatt_client->client_characteristic_configuration_value, 0, configuration);
2531 
2532 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
2533     gatt_client->gatt_client_state = P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2534 #else
2535     gatt_client->gatt_client_state = P_W2_SEND_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2536 #endif
2537     gatt_client_run();
2538     return ERROR_CODE_SUCCESS;
2539 }
2540 
2541 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){
2542     gatt_client_t * gatt_client;
2543     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2544     if (status != ERROR_CODE_SUCCESS){
2545         return status;
2546     }
2547 
2548     gatt_client->callback = callback;
2549     gatt_client->attribute_handle = descriptor_handle;
2550 
2551     gatt_client->gatt_client_state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
2552     gatt_client_run();
2553     return ERROR_CODE_SUCCESS;
2554 }
2555 
2556 uint8_t gatt_client_read_characteristic_descriptor(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_descriptor_t * descriptor){
2557     return gatt_client_read_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
2558 }
2559 
2560 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){
2561     gatt_client_t * gatt_client;
2562     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2563     if (status != ERROR_CODE_SUCCESS){
2564         return status;
2565     }
2566 
2567     gatt_client->callback = callback;
2568     gatt_client->attribute_handle = descriptor_handle;
2569     gatt_client->attribute_offset = offset;
2570     gatt_client->gatt_client_state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
2571     gatt_client_run();
2572     return ERROR_CODE_SUCCESS;
2573 }
2574 
2575 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){
2576     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0);
2577 }
2578 
2579 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){
2580     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
2581 }
2582 
2583 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){
2584     gatt_client_t * gatt_client;
2585     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2586     if (status != ERROR_CODE_SUCCESS){
2587         return status;
2588     }
2589 
2590     gatt_client->callback = callback;
2591     gatt_client->attribute_handle = descriptor_handle;
2592     gatt_client->attribute_length = value_length;
2593     gatt_client->attribute_offset = 0;
2594     gatt_client->attribute_value = value;
2595     gatt_client->gatt_client_state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
2596     gatt_client_run();
2597     return ERROR_CODE_SUCCESS;
2598 }
2599 
2600 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){
2601     return gatt_client_write_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, value_length, value);
2602 }
2603 
2604 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){
2605     gatt_client_t * gatt_client;
2606     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2607     if (status != ERROR_CODE_SUCCESS){
2608         return status;
2609     }
2610 
2611     gatt_client->callback = callback;
2612     gatt_client->attribute_handle = descriptor_handle;
2613     gatt_client->attribute_length = value_length;
2614     gatt_client->attribute_offset = offset;
2615     gatt_client->attribute_value = value;
2616     gatt_client->gatt_client_state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
2617     gatt_client_run();
2618     return ERROR_CODE_SUCCESS;
2619 }
2620 
2621 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){
2622     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0, value_length, value);
2623 }
2624 
2625 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){
2626     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, value_length, value);
2627 }
2628 
2629 /**
2630  * @brief -> gatt complete event
2631  */
2632 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){
2633     gatt_client_t * gatt_client;
2634     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2635     if (status != ERROR_CODE_SUCCESS){
2636         return status;
2637     }
2638 
2639     gatt_client->callback = callback;
2640     gatt_client->attribute_handle = attribute_handle;
2641     gatt_client->attribute_length = value_length;
2642     gatt_client->attribute_offset = offset;
2643     gatt_client->attribute_value = value;
2644     gatt_client->gatt_client_state = P_W2_PREPARE_WRITE_SINGLE;
2645     gatt_client_run();
2646     return ERROR_CODE_SUCCESS;
2647 }
2648 
2649 /**
2650  * @brief -> gatt complete event
2651  */
2652 uint8_t gatt_client_execute_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_EXECUTE_PREPARED_WRITE;
2661     gatt_client_run();
2662     return ERROR_CODE_SUCCESS;
2663 }
2664 
2665 /**
2666  * @brief -> gatt complete event
2667  */
2668 uint8_t gatt_client_cancel_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2669     gatt_client_t * gatt_client;
2670     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2671     if (status != ERROR_CODE_SUCCESS){
2672         return status;
2673     }
2674 
2675     gatt_client->callback = callback;
2676     gatt_client->gatt_client_state = P_W2_CANCEL_PREPARED_WRITE;
2677     gatt_client_run();
2678     return ERROR_CODE_SUCCESS;
2679 }
2680 
2681 void gatt_client_deserialize_service(const uint8_t *packet, int offset, gatt_client_service_t * service){
2682     service->start_group_handle = little_endian_read_16(packet, offset);
2683     service->end_group_handle = little_endian_read_16(packet, offset + 2);
2684     reverse_128(&packet[offset + 4], service->uuid128);
2685     if (uuid_has_bluetooth_prefix(service->uuid128)){
2686         service->uuid16 = big_endian_read_32(service->uuid128, 0);
2687     } else {
2688         service->uuid16 = 0;
2689     }
2690 }
2691 
2692 void gatt_client_deserialize_characteristic(const uint8_t * packet, int offset, gatt_client_characteristic_t * characteristic){
2693     characteristic->start_handle = little_endian_read_16(packet, offset);
2694     characteristic->value_handle = little_endian_read_16(packet, offset + 2);
2695     characteristic->end_handle = little_endian_read_16(packet, offset + 4);
2696     characteristic->properties = little_endian_read_16(packet, offset + 6);
2697     reverse_128(&packet[offset+8], characteristic->uuid128);
2698     if (uuid_has_bluetooth_prefix(characteristic->uuid128)){
2699         characteristic->uuid16 = big_endian_read_32(characteristic->uuid128, 0);
2700     } else {
2701         characteristic->uuid16 = 0;
2702     }
2703 }
2704 
2705 void gatt_client_deserialize_characteristic_descriptor(const uint8_t * packet, int offset, gatt_client_characteristic_descriptor_t * descriptor){
2706     descriptor->handle = little_endian_read_16(packet, offset);
2707     reverse_128(&packet[offset+2], descriptor->uuid128);
2708     if (uuid_has_bluetooth_prefix(descriptor->uuid128)){
2709         descriptor->uuid16 = big_endian_read_32(descriptor->uuid128, 0);
2710     } else {
2711         descriptor->uuid16 = 0;
2712     }
2713 }
2714 
2715 void gatt_client_send_mtu_negotiation(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2716     gatt_client_t * gatt_client;
2717     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2718     if (status != ERROR_CODE_SUCCESS){
2719         return;
2720     }
2721     if (gatt_client->mtu_state == MTU_AUTO_EXCHANGE_DISABLED){
2722         gatt_client->callback = callback;
2723         gatt_client->mtu_state = SEND_MTU_EXCHANGE;
2724         gatt_client_run();
2725     }
2726 }
2727 
2728 uint8_t gatt_client_request_to_write_without_response(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
2729     gatt_client_t * gatt_client;
2730     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2731     if (status != ERROR_CODE_SUCCESS){
2732         return status;
2733     }
2734     bool added = btstack_linked_list_add_tail(&gatt_client->write_without_response_requests, (btstack_linked_item_t*) callback_registration);
2735     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
2736     if (added){
2737         return ERROR_CODE_SUCCESS;
2738     } else {
2739         return ERROR_CODE_COMMAND_DISALLOWED;
2740     }
2741 }
2742 
2743 uint8_t gatt_client_request_to_send_gatt_query(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
2744     gatt_client_t * gatt_client;
2745     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2746     if (status != ERROR_CODE_SUCCESS){
2747         return status;
2748     }
2749     bool added = btstack_linked_list_add_tail(&gatt_client->query_requests, (btstack_linked_item_t*) callback_registration);
2750     gatt_client_notify_can_send_query(gatt_client);
2751     if (added){
2752         return ERROR_CODE_SUCCESS;
2753     } else {
2754         return ERROR_CODE_COMMAND_DISALLOWED;
2755     }
2756 }
2757 
2758 uint8_t gatt_client_request_can_write_without_response_event(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2759     gatt_client_t * gatt_client;
2760     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2761     if (status != ERROR_CODE_SUCCESS){
2762         return status;
2763     }
2764     if (gatt_client->write_without_response_callback != NULL){
2765         return GATT_CLIENT_IN_WRONG_STATE;
2766     }
2767     gatt_client->write_without_response_callback = callback;
2768     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
2769     return ERROR_CODE_SUCCESS;
2770 }
2771 
2772 
2773 #if defined(ENABLE_GATT_OVER_CLASSIC) || defined(ENABLE_GATT_OVER_EATT)
2774 
2775 #include "hci_event.h"
2776 
2777 static const hci_event_t gatt_client_connected = {
2778         GATT_EVENT_CONNECTED, 0, "1BH"
2779 };
2780 
2781 static const hci_event_t gatt_client_disconnected = {
2782         GATT_EVENT_DISCONNECTED, 0, "H"
2783 };
2784 #endif
2785 
2786 #ifdef ENABLE_GATT_OVER_CLASSIC
2787 
2788 #include "bluetooth_psm.h"
2789 
2790 // single active SDP query
2791 static gatt_client_t * gatt_client_classic_active_sdp_query;
2792 
2793 // macos protocol descriptor list requires 16 bytes
2794 static uint8_t gatt_client_classic_sdp_buffer[32];
2795 
2796 
2797 static gatt_client_t * gatt_client_get_context_for_classic_addr(bd_addr_t addr){
2798     btstack_linked_item_t *it;
2799     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
2800         gatt_client_t * gatt_client = (gatt_client_t *) it;
2801         if (memcmp(gatt_client->addr, addr, 6) == 0){
2802             return gatt_client;
2803         }
2804     }
2805     return NULL;
2806 }
2807 
2808 static gatt_client_t * gatt_client_get_context_for_l2cap_cid(uint16_t l2cap_cid){
2809     btstack_linked_item_t *it;
2810     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
2811         gatt_client_t * gatt_client = (gatt_client_t *) it;
2812         if (gatt_client->l2cap_cid == l2cap_cid){
2813             return gatt_client;
2814         }
2815     }
2816     return NULL;
2817 }
2818 
2819 static void gatt_client_classic_handle_connected(gatt_client_t * gatt_client, uint8_t status){
2820     bd_addr_t addr;
2821     // cppcheck-suppress uninitvar ; addr is reported as uninitialized although it's the destination of the memcpy
2822     memcpy(addr, gatt_client->addr, 6);
2823     hci_con_handle_t con_handle = gatt_client->con_handle;
2824     btstack_packet_handler_t callback = gatt_client->callback;
2825     if (status != ERROR_CODE_SUCCESS){
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_connected, status, addr,
2831                                                                 con_handle);
2832     (*callback)(HCI_EVENT_PACKET, 0, buffer, len);
2833 }
2834 
2835 static void gatt_client_classic_handle_disconnected(gatt_client_t * gatt_client){
2836 
2837     gatt_client_report_error_if_pending(gatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
2838     gatt_client_timeout_stop(gatt_client);
2839 
2840     hci_con_handle_t con_handle = gatt_client->con_handle;
2841     btstack_packet_handler_t callback = gatt_client->callback;
2842     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
2843     btstack_memory_gatt_client_free(gatt_client);
2844 
2845     uint8_t buffer[20];
2846     uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_disconnected, con_handle);
2847     (*callback)(HCI_EVENT_PACKET, 0, buffer, len);
2848 }
2849 
2850 static void gatt_client_l2cap_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
2851     gatt_client_t * gatt_client = NULL;
2852     uint8_t status;
2853     switch (packet_type){
2854         case HCI_EVENT_PACKET:
2855             switch (hci_event_packet_get_type(packet)) {
2856                 case L2CAP_EVENT_CHANNEL_OPENED:
2857                     status = l2cap_event_channel_opened_get_status(packet);
2858                     gatt_client = gatt_client_get_context_for_l2cap_cid(l2cap_event_channel_opened_get_local_cid(packet));
2859                     btstack_assert(gatt_client != NULL);
2860                     // if status != 0, gatt_client will be discarded
2861                     gatt_client->gatt_client_state = P_READY;
2862                     gatt_client->con_handle = l2cap_event_channel_opened_get_handle(packet);
2863                     gatt_client->mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
2864                     gatt_client_classic_handle_connected(gatt_client, status);
2865                     break;
2866                 case L2CAP_EVENT_CHANNEL_CLOSED:
2867                     gatt_client = gatt_client_get_context_for_l2cap_cid(l2cap_event_channel_closed_get_local_cid(packet));
2868                     gatt_client_classic_handle_disconnected(gatt_client);
2869                     break;
2870                 default:
2871                     break;
2872             }
2873             break;
2874         case L2CAP_DATA_PACKET:
2875             gatt_client = gatt_client_get_context_for_l2cap_cid(channel);
2876             btstack_assert(gatt_client != NULL);
2877             gatt_client_handle_att_response(gatt_client, packet, size);
2878             gatt_client_run();
2879             break;
2880         default:
2881             break;
2882     }
2883 }
2884 
2885 static void gatt_client_handle_sdp_client_query_attribute_value(gatt_client_t * connection, uint8_t *packet){
2886     des_iterator_t des_list_it;
2887     des_iterator_t prot_it;
2888 
2889     if (sdp_event_query_attribute_byte_get_attribute_length(packet) <= sizeof(gatt_client_classic_sdp_buffer)) {
2890         gatt_client_classic_sdp_buffer[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet);
2891         if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)) {
2892             switch(sdp_event_query_attribute_byte_get_attribute_id(packet)) {
2893                 case BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST:
2894                     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)) {
2895                         uint8_t       *des_element;
2896                         uint8_t       *element;
2897                         uint32_t       uuid;
2898 
2899                         if (des_iterator_get_type(&des_list_it) != DE_DES) continue;
2900 
2901                         des_element = des_iterator_get_element(&des_list_it);
2902                         des_iterator_init(&prot_it, des_element);
2903                         element = des_iterator_get_element(&prot_it);
2904 
2905                         if (de_get_element_type(element) != DE_UUID) continue;
2906 
2907                         uuid = de_get_uuid32(element);
2908                         des_iterator_next(&prot_it);
2909                         // we assume that the even if there are both roles supported, remote device uses the same psm and avdtp version for both
2910                         switch (uuid){
2911                             case BLUETOOTH_PROTOCOL_L2CAP:
2912                                 if (!des_iterator_has_more(&prot_it)) continue;
2913                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &connection->l2cap_psm);
2914                                 break;
2915                             default:
2916                                 break;
2917                         }
2918                     }
2919                     break;
2920 
2921                 default:
2922                     break;
2923             }
2924         }
2925     }
2926 }
2927 
2928 static void gatt_client_classic_sdp_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
2929     gatt_client_t * gatt_client = gatt_client_classic_active_sdp_query;
2930     btstack_assert(gatt_client != NULL);
2931     uint8_t status;
2932 
2933     // TODO: handle sdp events, get l2cap psm
2934     switch (hci_event_packet_get_type(packet)){
2935         case SDP_EVENT_QUERY_ATTRIBUTE_VALUE:
2936             gatt_client_handle_sdp_client_query_attribute_value(gatt_client, packet);
2937             // TODO:
2938             return;
2939         case SDP_EVENT_QUERY_COMPLETE:
2940             status = sdp_event_query_complete_get_status(packet);
2941             gatt_client_classic_active_sdp_query = NULL;
2942             log_info("l2cap psm: %0x, status %02x", gatt_client->l2cap_psm, status);
2943             if (status != ERROR_CODE_SUCCESS) break;
2944             if (gatt_client->l2cap_psm == 0) {
2945                 status = SDP_SERVICE_NOT_FOUND;
2946                 break;
2947             }
2948             break;
2949         default:
2950             btstack_assert(false);
2951             return;
2952     }
2953 
2954     // done
2955     if (status == ERROR_CODE_SUCCESS){
2956         gatt_client->gatt_client_state = P_W4_L2CAP_CONNECTION;
2957         status = l2cap_create_channel(gatt_client_l2cap_handler, gatt_client->addr, gatt_client->l2cap_psm, 0xffff,
2958                              &gatt_client->l2cap_cid);
2959     }
2960     if (status != ERROR_CODE_SUCCESS) {
2961         gatt_client_classic_handle_connected(gatt_client, status);
2962     }
2963 }
2964 
2965 static void gatt_client_classic_sdp_start(void * context){
2966     gatt_client_classic_active_sdp_query = (gatt_client_t *) context;
2967     gatt_client_classic_active_sdp_query->gatt_client_state = P_W4_SDP_QUERY;
2968     sdp_client_query_uuid16(gatt_client_classic_sdp_handler, gatt_client_classic_active_sdp_query->addr, ORG_BLUETOOTH_SERVICE_GENERIC_ATTRIBUTE);
2969 }
2970 
2971 uint8_t gatt_client_classic_connect(btstack_packet_handler_t callback, bd_addr_t addr){
2972     gatt_client_t * gatt_client = gatt_client_get_context_for_classic_addr(addr);
2973     if (gatt_client != NULL){
2974         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
2975     }
2976     gatt_client = btstack_memory_gatt_client_get();
2977     if (gatt_client == NULL){
2978         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
2979     }
2980     // init state
2981     gatt_client->bearer_type = ATT_BEARER_UNENHANCED_CLASSIC;
2982     gatt_client->con_handle = HCI_CON_HANDLE_INVALID;
2983     memcpy(gatt_client->addr, addr, 6);
2984     gatt_client->mtu = ATT_DEFAULT_MTU;
2985     gatt_client->security_level = LEVEL_0;
2986     gatt_client->mtu_state = MTU_AUTO_EXCHANGE_DISABLED;
2987     gatt_client->gatt_client_state = P_W2_SDP_QUERY;
2988     gatt_client->sdp_query_request.callback = &gatt_client_classic_sdp_start;
2989     gatt_client->sdp_query_request.context = gatt_client;
2990     gatt_client->callback = callback;
2991 #ifdef ENABLE_GATT_OVER_EATT
2992     gatt_client->eatt_state = GATT_CLIENT_EATT_IDLE;
2993 #endif
2994     btstack_linked_list_add(&gatt_client_connections, (btstack_linked_item_t*)gatt_client);
2995     sdp_client_register_query_callback(&gatt_client->sdp_query_request);
2996     return ERROR_CODE_SUCCESS;
2997 }
2998 
2999 uint8_t gatt_client_classic_disconnect(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
3000     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
3001     if (gatt_client == NULL){
3002         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3003     }
3004     gatt_client->callback = callback;
3005     return l2cap_disconnect(gatt_client->l2cap_cid);
3006 }
3007 #endif
3008 
3009 #ifdef ENABLE_GATT_OVER_EATT
3010 
3011 #define MAX_NR_EATT_CHANNELS 5
3012 
3013 static void gatt_client_le_enhanced_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
3014 
3015 static void gatt_client_eatt_finalize(gatt_client_t * gatt_client) {
3016     // free eatt clients
3017     btstack_linked_list_iterator_t it;
3018     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
3019     while (btstack_linked_list_iterator_has_next(&it)) {
3020         gatt_client_t *eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3021         btstack_linked_list_iterator_remove(&it);
3022         btstack_memory_gatt_client_free(eatt_client);
3023     }
3024 }
3025 
3026 // all channels connected
3027 static void gatt_client_le_enhanced_handle_connected(gatt_client_t * gatt_client, uint8_t status) {
3028     if (status == ERROR_CODE_SUCCESS){
3029         gatt_client->eatt_state = GATT_CLIENT_EATT_READY;
3030     } else {
3031         gatt_client_eatt_finalize(gatt_client);
3032         gatt_client->eatt_state = GATT_CLIENT_EATT_IDLE;
3033     }
3034 
3035     uint8_t buffer[20];
3036     uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_connected, status, gatt_client->addr,
3037                                                                 gatt_client->con_handle);
3038     (*gatt_client->callback)(HCI_EVENT_PACKET, 0, buffer, len);
3039 }
3040 
3041 // single channel disconnected
3042 static void gatt_client_le_enhanced_handle_ecbm_disconnected(gatt_client_t * gatt_client, gatt_client_t * eatt_client) {
3043     if (gatt_client->eatt_state == GATT_CLIENT_EATT_READY) {
3044 
3045         // report error
3046         gatt_client_report_error_if_pending(eatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
3047 
3048         // free memory
3049         btstack_linked_list_remove(&gatt_client->eatt_clients, (btstack_linked_item_t *) eatt_client);
3050         btstack_memory_gatt_client_free(eatt_client);
3051 
3052         // report disconnected if last channel closed
3053         if (btstack_linked_list_empty(&gatt_client->eatt_clients)){
3054             // emit disconnected when last eatt client is gone
3055             uint8_t buffer[20];
3056             uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_disconnected, gatt_client->con_handle);
3057             (*gatt_client->callback)(HCI_EVENT_PACKET, 0, buffer, len);
3058         }
3059     }
3060 }
3061 
3062 static gatt_client_t * gatt_client_le_enhanced_get_context_for_l2cap_cid(uint16_t l2cap_cid, gatt_client_t ** out_eatt_client){
3063     btstack_linked_list_iterator_t it;
3064     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
3065     while (btstack_linked_list_iterator_has_next(&it)) {
3066         gatt_client_t * gatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3067         btstack_linked_list_iterator_t it2;
3068         btstack_linked_list_iterator_init(&it2, &gatt_client->eatt_clients);
3069         while (btstack_linked_list_iterator_has_next(&it2)) {
3070             gatt_client_t * eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it2);
3071             if (eatt_client->l2cap_cid == l2cap_cid){
3072                 *out_eatt_client = eatt_client;
3073                 return gatt_client;
3074             }
3075         }
3076     }
3077     return NULL;
3078 }
3079 
3080 static void gatt_client_le_enhanced_setup_l2cap_channel(gatt_client_t * gatt_client){
3081     uint8_t num_channels = gatt_client->eatt_num_clients;
3082 
3083     // setup channels
3084     uint16_t buffer_size_per_client = gatt_client->eatt_storage_size / num_channels;
3085     uint16_t max_mtu = (buffer_size_per_client - REPORT_PREBUFFER_HEADER) / 2;
3086     uint8_t * receive_buffers[MAX_NR_EATT_CHANNELS];
3087     uint16_t  new_cids[MAX_NR_EATT_CHANNELS];
3088     memset(gatt_client->eatt_storage_buffer, 0, gatt_client->eatt_storage_size);
3089     uint8_t i;
3090     for (i=0;i<gatt_client->eatt_num_clients; i++){
3091         receive_buffers[i] = &gatt_client->eatt_storage_buffer[REPORT_PREBUFFER_HEADER];
3092         gatt_client->eatt_storage_buffer += REPORT_PREBUFFER_HEADER + max_mtu;
3093     }
3094 
3095     log_info("%u EATT clients with receive buffer size %u", gatt_client->eatt_num_clients, buffer_size_per_client);
3096 
3097     uint8_t status = l2cap_ecbm_create_channels(&gatt_client_le_enhanced_packet_handler,
3098                                                 gatt_client->con_handle,
3099                                                 gatt_client->security_level,
3100                                                 BLUETOOTH_PSM_EATT, num_channels,
3101                                                 L2CAP_LE_AUTOMATIC_CREDITS,
3102                                                 buffer_size_per_client,
3103                                                 receive_buffers,
3104                                                 new_cids);
3105 
3106     if (status == ERROR_CODE_SUCCESS){
3107         i = 0;
3108         btstack_linked_list_iterator_t it;
3109         btstack_linked_list_iterator_init(&it, &gatt_client->eatt_clients);
3110         while (btstack_linked_list_iterator_has_next(&it)) {
3111             gatt_client_t *new_eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3112 
3113             // init state with new cid and transmit buffer
3114             new_eatt_client->bearer_type = ATT_BEARER_ENHANCED_LE;
3115             new_eatt_client->con_handle = gatt_client->con_handle;
3116             new_eatt_client->mtu = 64;
3117             new_eatt_client->security_level = LEVEL_0;
3118             new_eatt_client->mtu_state = MTU_AUTO_EXCHANGE_DISABLED;
3119             new_eatt_client->gatt_client_state = P_W4_L2CAP_CONNECTION;
3120             new_eatt_client->l2cap_cid = new_cids[i];
3121             new_eatt_client->eatt_storage_buffer = gatt_client->eatt_storage_buffer;
3122             gatt_client->eatt_storage_buffer += max_mtu;
3123             i++;
3124         }
3125         gatt_client->eatt_state = GATT_CLIENT_EATT_L2CAP_SETUP;
3126     } else {
3127         gatt_client_le_enhanced_handle_connected(gatt_client, status);
3128     }
3129 }
3130 
3131 static void gatt_client_le_enhanced_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
3132     gatt_client_t *gatt_client;
3133     gatt_client_t *eatt_client;
3134     hci_con_handle_t con_handle;
3135     uint16_t l2cap_cid;
3136     uint8_t status;
3137     gatt_client_characteristic_t characteristic;
3138     gatt_client_service_t service;
3139     switch (packet_type) {
3140         case HCI_EVENT_PACKET:
3141             switch (hci_event_packet_get_type(packet)) {
3142                 case GATT_EVENT_SERVICE_QUERY_RESULT:
3143                     con_handle = gatt_event_service_query_result_get_handle(packet);
3144                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3145                     btstack_assert(gatt_client != NULL);
3146                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W4_DONE);
3147                     gatt_event_service_query_result_get_service(packet, &service);
3148                     gatt_client->gatt_service_start_group_handle = service.start_group_handle;
3149                     gatt_client->gatt_service_end_group_handle = service.end_group_handle;
3150                     break;
3151                 case GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT:
3152                     con_handle = gatt_event_characteristic_value_query_result_get_handle(packet);
3153                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3154                     btstack_assert(gatt_client != NULL);
3155                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_DONE);
3156                     if (gatt_event_characteristic_value_query_result_get_value_length(packet) >= 1) {
3157                         gatt_client->gatt_server_supported_features = gatt_event_characteristic_value_query_result_get_value(packet)[0];
3158                     }
3159                     break;
3160                 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
3161                     con_handle = gatt_event_characteristic_query_result_get_handle(packet);
3162                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3163                     btstack_assert(gatt_client != NULL);
3164                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_DONE);
3165                     gatt_event_characteristic_query_result_get_characteristic(packet, &characteristic);
3166                     gatt_client->gatt_client_supported_features_handle = characteristic.value_handle;
3167                     break;
3168                 case GATT_EVENT_QUERY_COMPLETE:
3169                     con_handle = gatt_event_query_complete_get_handle(packet);
3170                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3171                     btstack_assert(gatt_client != NULL);
3172                     switch (gatt_client->eatt_state){
3173                         case GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W4_DONE:
3174                             if (gatt_client->gatt_service_start_group_handle == 0){
3175                                 gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
3176                             } else {
3177                                 gatt_client->eatt_state = GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W2_SEND;
3178                             }
3179                             break;
3180                         case GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_DONE:
3181                             if ((gatt_client->gatt_server_supported_features & 1) == 0) {
3182                                 gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
3183                             } else {
3184                                 gatt_client->eatt_state = GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W2_SEND;
3185                             }
3186                             break;
3187                         case GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_DONE:
3188                             if (gatt_client->gatt_client_supported_features_handle == 0){
3189                                 gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
3190                             } else {
3191                                 gatt_client->eatt_state = GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W2_SEND;
3192                             }
3193                             break;
3194                         case GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W4_DONE:
3195                             gatt_client_le_enhanced_setup_l2cap_channel(gatt_client);
3196                             break;
3197                         default:
3198                             break;
3199                     }
3200                     break;
3201                 case L2CAP_EVENT_ECBM_CHANNEL_OPENED:
3202                     l2cap_cid = l2cap_event_ecbm_channel_opened_get_local_cid(packet);
3203                     gatt_client = gatt_client_le_enhanced_get_context_for_l2cap_cid(l2cap_cid, &eatt_client);
3204 
3205                     btstack_assert(gatt_client != NULL);
3206                     btstack_assert(eatt_client != NULL);
3207                     btstack_assert(eatt_client->gatt_client_state == P_W4_L2CAP_CONNECTION);
3208 
3209                     status = l2cap_event_channel_opened_get_status(packet);
3210                     if (status == ERROR_CODE_SUCCESS){
3211                         eatt_client->gatt_client_state = P_READY;
3212                         eatt_client->mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
3213                     } else {
3214                         gatt_client_le_enhanced_handle_ecbm_disconnected(gatt_client, eatt_client);
3215                     }
3216                     // all channels opened?
3217                     gatt_client->eatt_num_clients--;
3218                     if (gatt_client->eatt_num_clients == 0){
3219                         gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_SUCCESS);
3220                     }
3221                     break;
3222                 case L2CAP_EVENT_CHANNEL_CLOSED:
3223                     l2cap_cid = l2cap_event_channel_closed_get_local_cid(packet);
3224                     gatt_client = gatt_client_le_enhanced_get_context_for_l2cap_cid(l2cap_cid, &eatt_client);
3225                     btstack_assert(gatt_client != NULL);
3226                     btstack_assert(eatt_client != NULL);
3227                     gatt_client_le_enhanced_handle_ecbm_disconnected(gatt_client, eatt_client);
3228                     break;
3229                 default:
3230                     break;
3231             }
3232             break;
3233         case L2CAP_DATA_PACKET:
3234             gatt_client = gatt_client_le_enhanced_get_context_for_l2cap_cid(channel, &eatt_client);
3235             btstack_assert(gatt_client != NULL);
3236             btstack_assert(eatt_client != NULL);
3237             gatt_client_handle_att_response(eatt_client, packet, size);
3238             gatt_client_run();
3239             break;
3240         default:
3241             break;
3242     }
3243 }
3244 
3245 static bool gatt_client_le_enhanced_handle_can_send_query(gatt_client_t * gatt_client){
3246     uint8_t status = ERROR_CODE_SUCCESS;
3247     uint8_t gatt_client_supported_features = 0x06; // eatt + multiple value notifications
3248     switch (gatt_client->eatt_state){
3249         case GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W2_SEND:
3250             gatt_client->gatt_service_start_group_handle = 0;
3251             gatt_client->eatt_state = GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W4_DONE;
3252             status = gatt_client_discover_primary_services_by_uuid16(&gatt_client_le_enhanced_packet_handler,
3253                                                                      gatt_client->con_handle,
3254                                                                      ORG_BLUETOOTH_SERVICE_GENERIC_ATTRIBUTE);
3255             break;
3256         case GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W2_SEND:
3257             gatt_client->gatt_server_supported_features = 0;
3258             gatt_client->eatt_state = GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_DONE;
3259             status = gatt_client_read_value_of_characteristics_by_uuid16(&gatt_client_le_enhanced_packet_handler,
3260                                                                          gatt_client->con_handle,
3261                                                                          gatt_client->gatt_service_start_group_handle,
3262                                                                          gatt_client->gatt_service_end_group_handle,
3263                                                                          ORG_BLUETOOTH_CHARACTERISTIC_SERVER_SUPPORTED_FEATURES);
3264             return true;
3265         case GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W2_SEND:
3266             gatt_client->gatt_client_supported_features_handle = 0;
3267             gatt_client->eatt_state = GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_DONE;
3268             status = gatt_client_discover_characteristics_for_handle_range_by_uuid16(&gatt_client_le_enhanced_packet_handler,
3269                                                                                      gatt_client->con_handle,
3270                                                                                      gatt_client->gatt_service_start_group_handle,
3271                                                                                      gatt_client->gatt_service_end_group_handle,
3272                                                                                      ORG_BLUETOOTH_CHARACTERISTIC_CLIENT_SUPPORTED_FEATURES);
3273             return true;
3274         case GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W2_SEND:
3275             gatt_client->eatt_state = GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W4_DONE;
3276             status = gatt_client_write_value_of_characteristic(&gatt_client_le_enhanced_packet_handler, gatt_client->con_handle,
3277                                                                gatt_client->gatt_client_supported_features_handle, 1,
3278                                                                &gatt_client_supported_features);
3279             return true;
3280         default:
3281             break;
3282     }
3283     btstack_assert(status == ERROR_CODE_SUCCESS);
3284     UNUSED(status);
3285     return false;
3286 }
3287 
3288 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) {
3289     gatt_client_t * gatt_client;
3290     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3291     if (status != ERROR_CODE_SUCCESS){
3292         return status;
3293     }
3294 
3295     if (gatt_client->eatt_state != GATT_CLIENT_EATT_IDLE){
3296         return ERROR_CODE_COMMAND_DISALLOWED;
3297     }
3298 
3299     // need one buffer for sending and one for receiving. Receiving includes pre-buffer for reports
3300     uint16_t buffer_size_per_client = storage_size / num_channels;
3301     uint16_t max_mtu = (buffer_size_per_client - REPORT_PREBUFFER_HEADER) / 2;
3302     if (max_mtu < 64) {
3303         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
3304     }
3305 
3306     if ((num_channels == 0) || (num_channels > MAX_NR_EATT_CHANNELS)){
3307         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
3308     }
3309 
3310     // create max num_channel eatt clients
3311     uint8_t i;
3312     btstack_linked_list_t eatt_clients = NULL;
3313     for (i=0;i<num_channels;i++) {
3314         gatt_client_t * new_gatt_client = btstack_memory_gatt_client_get();
3315         if (new_gatt_client == NULL) {
3316             break;
3317         }
3318         btstack_linked_list_add(&eatt_clients, (btstack_linked_item_t*)new_gatt_client);
3319     }
3320 
3321     if (i != num_channels){
3322         while (true){
3323             gatt_client = (gatt_client_t *) btstack_linked_list_pop(&eatt_clients);
3324             if (gatt_client == NULL) {
3325                 break;
3326             }
3327             btstack_memory_gatt_client_free(gatt_client);
3328         }
3329         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
3330     }
3331 
3332     gatt_client->callback = callback;
3333     gatt_client->eatt_num_clients   = num_channels;
3334     gatt_client->eatt_storage_buffer = storage_buffer;
3335     gatt_client->eatt_storage_size   = storage_size;
3336     gatt_client->eatt_clients = eatt_clients;
3337     gatt_client->eatt_state = GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W2_SEND;
3338     gatt_client_notify_can_send_query(gatt_client);
3339 
3340     return ERROR_CODE_SUCCESS;
3341 }
3342 
3343 #endif
3344 
3345 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
3346 void gatt_client_att_packet_handler_fuzz(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
3347     gatt_client_att_packet_handler(packet_type, handle, packet, size);
3348 }
3349 
3350 uint8_t gatt_client_get_client(hci_con_handle_t con_handle, gatt_client_t ** out_gatt_client){
3351     uint8_t status = gatt_client_provide_context_for_handle(con_handle, out_gatt_client);
3352     return status;
3353 }
3354 #endif
3355