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