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