xref: /btstack/src/ble/gatt_client.c (revision 88371317a5f44e71d70f9cbd11ce90e6e28c133e)
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 HX
951     uint8_t packet[24];
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, start_group_handle);
956     hci_event_builder_add_16(&context, end_group_handle);
957     hci_event_builder_add_128(&context, uuid128);
958     emit_event_new(gatt_client->callback, packet, hci_event_builder_get_length(&context));
959 }
960 
961 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){
962     // @format HX
963     uint8_t packet[26];
964     hci_event_builder_context_t context;
965     hci_event_builder_init(&context, packet, sizeof(packet), GATT_EVENT_INCLUDED_SERVICE_QUERY_RESULT, 0);
966     hci_event_builder_add_con_handle(&context, gatt_client->con_handle);
967     hci_event_builder_add_16(&context, include_handle);
968     hci_event_builder_add_16(&context, start_group_handle);
969     hci_event_builder_add_16(&context, end_group_handle);
970     hci_event_builder_add_128(&context, uuid128);
971     emit_event_new(gatt_client->callback, packet, hci_event_builder_get_length(&context));
972 }
973 
974 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,
975                                                         uint16_t properties, const uint8_t * uuid128){
976     // @format HY
977     uint8_t packet[28];
978     hci_event_builder_context_t context;
979     hci_event_builder_init(&context, packet, sizeof(packet), GATT_EVENT_CHARACTERISTIC_QUERY_RESULT, 0);
980     hci_event_builder_add_con_handle(&context, gatt_client->con_handle);
981     hci_event_builder_add_16(&context, start_handle);
982     hci_event_builder_add_16(&context, value_handle);
983     hci_event_builder_add_16(&context, end_handle);
984     hci_event_builder_add_16(&context, properties);
985     hci_event_builder_add_128(&context, uuid128);
986     emit_event_new(gatt_client->callback, packet, hci_event_builder_get_length(&context));
987 }
988 
989 static void emit_gatt_all_characteristic_descriptors_result_event(
990         gatt_client_t * gatt_client, uint16_t descriptor_handle, const uint8_t * uuid128){
991     // @format HZ
992     uint8_t packet[22];
993     hci_event_builder_context_t context;
994     hci_event_builder_init(&context, packet, sizeof(packet), GATT_EVENT_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT, 0);
995     hci_event_builder_add_con_handle(&context, gatt_client->con_handle);
996     hci_event_builder_add_16(&context, descriptor_handle);
997     hci_event_builder_add_128(&context, uuid128);
998     emit_event_new(gatt_client->callback, packet, hci_event_builder_get_length(&context));
999 }
1000 
1001 static void emit_gatt_mtu_exchanged_result_event(gatt_client_t * gatt_client, uint16_t new_mtu){
1002     // @format H2
1003     uint8_t packet[6];
1004     packet[0] = GATT_EVENT_MTU;
1005     packet[1] = sizeof(packet) - 2u;
1006     little_endian_store_16(packet, 2, gatt_client->con_handle);
1007     little_endian_store_16(packet, 4, new_mtu);
1008     att_dispatch_client_mtu_exchanged(gatt_client->con_handle, new_mtu);
1009     emit_event_new(gatt_client->callback, packet, sizeof(packet));
1010 }
1011 
1012 // helper
1013 static void gatt_client_handle_transaction_complete(gatt_client_t *gatt_client, uint8_t att_status) {
1014     gatt_client->state = P_READY;
1015     gatt_client_timeout_stop(gatt_client);
1016     emit_gatt_complete_event(gatt_client, att_status);
1017     gatt_client_notify_can_send_query(gatt_client);
1018 }
1019 
1020 // @return packet pointer
1021 // @note assume that value is part of an l2cap buffer - overwrite HCI + L2CAP packet headers
1022 #define CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE 8
1023 static uint8_t *
1024 setup_characteristic_value_packet(const gatt_client_t *gatt_client, uint8_t type, uint16_t attribute_handle,
1025                                   uint8_t *value, uint16_t length) {
1026 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1027     // copy value into test packet for testing
1028     static uint8_t packet[1000];
1029     memcpy(&packet[CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE], value, length);
1030 #else
1031     // before the value inside the ATT PDU
1032     uint8_t * packet = value - CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE;
1033 #endif
1034     packet[0] = type;
1035     packet[1] = CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE - 2 + length;
1036     little_endian_store_16(packet, 2, gatt_client->con_handle);
1037     little_endian_store_16(packet, 4, attribute_handle);
1038     little_endian_store_16(packet, 6, length);
1039     return packet;
1040 }
1041 
1042 // @return packet pointer
1043 // @note assume that value is part of an l2cap buffer - overwrite parts of the HCI/L2CAP/ATT packet (4/4/3) bytes
1044 #define LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE 10
1045 
1046 // L2CAP Header (4) + ACL Header (4) => 8 bytes
1047 #if !defined(HCI_INCOMING_PRE_BUFFER_SIZE) || ((HCI_INCOMING_PRE_BUFFER_SIZE < LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE - 8))
1048 #error "Long Characteristic reads requires HCI_INCOMING_PRE_BUFFER_SIZE >= 2"
1049 #endif
1050 
1051 static uint8_t *
1052 setup_long_characteristic_value_packet(const gatt_client_t *gatt_client, uint8_t type, uint16_t attribute_handle,
1053                                        uint16_t offset, uint8_t *value, uint16_t length) {
1054 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1055     // avoid using pre ATT headers.
1056     // copy value into test packet for testing
1057     static uint8_t packet[1000];
1058     memcpy(&packet[LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE], value, length);
1059 #else
1060     // before the value inside the ATT PDU
1061     uint8_t * packet = value - LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE;
1062 #endif
1063     packet[0] = type;
1064     packet[1] = LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE - 2 + length;
1065     little_endian_store_16(packet, 2, gatt_client->con_handle);
1066     little_endian_store_16(packet, 4, attribute_handle);
1067     little_endian_store_16(packet, 6, offset);
1068     little_endian_store_16(packet, 8, length);
1069     return packet;
1070 }
1071 
1072 #if (LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE > CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE)
1073 #define REPORT_PREBUFFER_HEADER LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE
1074 #else
1075 #define REPORT_PREBUFFER_HEADER CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE
1076 #endif
1077 
1078 ///
1079 static void report_gatt_services(gatt_client_t * gatt_client, uint8_t * packet, uint16_t size){
1080     if (size < 2) return;
1081     uint8_t attr_length = packet[1];
1082     uint8_t uuid_length = attr_length - 4u;
1083 
1084     int i;
1085     for (i = 2; (i+attr_length) <= size; i += attr_length){
1086         uint16_t start_group_handle = little_endian_read_16(packet,i);
1087         uint16_t end_group_handle   = little_endian_read_16(packet,i+2);
1088         uint8_t  uuid128[16];
1089         uint16_t uuid16 = 0;
1090 
1091         if (uuid_length == 2u){
1092             uuid16 = little_endian_read_16(packet, i+4);
1093             uuid_add_bluetooth_prefix((uint8_t*) &uuid128, uuid16);
1094         } else if (uuid_length == 16u) {
1095             reverse_128(&packet[i+4], uuid128);
1096         } else {
1097             return;
1098         }
1099         emit_gatt_service_query_result_event(gatt_client, start_group_handle, end_group_handle, uuid128);
1100     }
1101 }
1102 
1103 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){
1104     uint8_t uuid128[16];
1105     uint16_t uuid16 = 0;
1106     if (uuid_length == 2u){
1107         uuid16 = little_endian_read_16(uuid, 0);
1108         uuid_add_bluetooth_prefix((uint8_t*) uuid128, uuid16);
1109     } else if (uuid_length == 16u){
1110         reverse_128(uuid, uuid128);
1111     } else {
1112         return;
1113     }
1114 
1115     if (gatt_client->filter_with_uuid && (memcmp(gatt_client->uuid128, uuid128, 16) != 0)) return;
1116 
1117     gatt_client->characteristic_properties = properties;
1118     gatt_client->characteristic_start_handle = start_handle;
1119     gatt_client->attribute_handle = value_handle;
1120 
1121     if (gatt_client->filter_with_uuid) return;
1122 
1123     gatt_client->uuid16 = uuid16;
1124     (void)memcpy(gatt_client->uuid128, uuid128, 16);
1125 }
1126 
1127 static void report_gatt_characteristic_end_found(gatt_client_t * gatt_client, uint16_t end_handle){
1128     // TODO: stop searching if filter and uuid found
1129 
1130     if (!gatt_client->characteristic_start_handle) return;
1131 
1132     emit_gatt_characteristic_query_result_event(gatt_client, gatt_client->characteristic_start_handle, gatt_client->attribute_handle,
1133                                                 end_handle, gatt_client->characteristic_properties, gatt_client->uuid128);
1134 
1135     gatt_client->characteristic_start_handle = 0;
1136 }
1137 
1138 
1139 static void report_gatt_characteristics(gatt_client_t * gatt_client, uint8_t * packet, uint16_t size){
1140     if (size < 2u) return;
1141     uint8_t attr_length = packet[1];
1142     if ((attr_length != 7u) && (attr_length != 21u)) return;
1143     uint8_t uuid_length = attr_length - 5u;
1144     int i;
1145     for (i = 2u; (i + attr_length) <= size; i += attr_length){
1146         uint16_t start_handle = little_endian_read_16(packet, i);
1147         uint8_t  properties = packet[i+2];
1148         uint16_t value_handle = little_endian_read_16(packet, i+3);
1149         report_gatt_characteristic_end_found(gatt_client, start_handle - 1u);
1150         report_gatt_characteristic_start_found(gatt_client, start_handle, properties, value_handle, &packet[i + 5],
1151                                                uuid_length);
1152     }
1153 }
1154 
1155 static void report_gatt_included_service_uuid16(gatt_client_t * gatt_client, uint16_t include_handle, uint16_t uuid16){
1156     uint8_t normalized_uuid128[16];
1157     uuid_add_bluetooth_prefix(normalized_uuid128, uuid16);
1158     emit_gatt_included_service_query_result_event(gatt_client, include_handle, gatt_client->query_start_handle,
1159                                                   gatt_client->query_end_handle, normalized_uuid128);
1160 }
1161 
1162 static void report_gatt_included_service_uuid128(gatt_client_t * gatt_client, uint16_t include_handle, const uint8_t * uuid128){
1163     emit_gatt_included_service_query_result_event(gatt_client, include_handle, gatt_client->query_start_handle,
1164                                                   gatt_client->query_end_handle, uuid128);
1165 }
1166 
1167 // @note assume that value is part of an l2cap buffer - overwrite parts of the HCI/L2CAP/ATT packet (4/4/3) bytes
1168 static void report_gatt_notification(gatt_client_t *gatt_client, uint16_t value_handle, uint8_t *value, int length) {
1169 	if (!gatt_client_accept_server_message(gatt_client)) return;
1170     uint8_t * packet = setup_characteristic_value_packet(gatt_client, GATT_EVENT_NOTIFICATION, value_handle,
1171                                                          value, length);
1172     emit_event_to_registered_listeners(gatt_client->con_handle, value_handle, packet, CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE + length);
1173 }
1174 
1175 // @note assume that value is part of an l2cap buffer - overwrite parts of the HCI/L2CAP/ATT packet (4/4/3) bytes
1176 static void report_gatt_indication(gatt_client_t *gatt_client, uint16_t value_handle, uint8_t *value, int length) {
1177 	if (!gatt_client_accept_server_message(gatt_client)) return;
1178 #ifdef ENABLE_GATT_CLIENT_SERVICE_CHANGED
1179     // Directly Handle GATT Service Changed and Database Hash indications
1180     if (value_handle == gatt_client->gatt_service_database_hash_value_handle){
1181         gatt_client_service_emit_database_hash(gatt_client, value, length);
1182     }
1183     if (value_handle == gatt_client->gatt_service_changed_value_handle){
1184         gatt_client_service_emit_service_changed(gatt_client, value, length);
1185     }
1186 #endif
1187     uint8_t * packet = setup_characteristic_value_packet(gatt_client, GATT_EVENT_INDICATION, value_handle,
1188                                                          value, length);
1189     emit_event_to_registered_listeners(gatt_client->con_handle, value_handle, packet, CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE + length);
1190 }
1191 
1192 // @note assume that value is part of an l2cap buffer - overwrite parts of the HCI/L2CAP/ATT packet (4/4/3) bytes
1193 static void report_gatt_characteristic_value(gatt_client_t * gatt_client, uint16_t attribute_handle, uint8_t * value, uint16_t length){
1194     uint8_t * packet = setup_characteristic_value_packet(
1195             gatt_client, GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT, attribute_handle, value, length);
1196     emit_event_new(gatt_client->callback, packet, CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE + length);
1197 }
1198 
1199 // @note assume that value is part of an l2cap buffer - overwrite parts of the HCI/L2CAP/ATT packet (4/4/3) bytes
1200 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){
1201     uint8_t * packet = setup_long_characteristic_value_packet(gatt_client,
1202                                                               GATT_EVENT_LONG_CHARACTERISTIC_VALUE_QUERY_RESULT,
1203                                                               attribute_handle, value_offset,
1204                                                               blob, blob_length);
1205     emit_event_new(gatt_client->callback, packet, blob_length + LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE);
1206 }
1207 
1208 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){
1209     UNUSED(value_offset);
1210     uint8_t * packet = setup_characteristic_value_packet(gatt_client, GATT_EVENT_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT,
1211                                                          descriptor_handle, value,
1212                                                          value_length);
1213     emit_event_new(gatt_client->callback, packet, value_length + 8u);
1214 }
1215 
1216 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){
1217     uint8_t * packet = setup_long_characteristic_value_packet(gatt_client,
1218                                                               GATT_EVENT_LONG_CHARACTERISTIC_DESCRIPTOR_QUERY_RESULT,
1219                                                               descriptor_handle, value_offset,
1220                                                               blob, blob_length);
1221     emit_event_new(gatt_client->callback, packet, blob_length + LONG_CHARACTERISTIC_VALUE_EVENT_HEADER_SIZE);
1222 }
1223 
1224 static void report_gatt_all_characteristic_descriptors(gatt_client_t * gatt_client, uint8_t * packet, uint16_t size, uint16_t pair_size){
1225     int i;
1226     for (i = 0u; (i + pair_size) <= size; i += pair_size){
1227         uint16_t descriptor_handle = little_endian_read_16(packet,i);
1228         uint8_t uuid128[16];
1229         uint16_t uuid16 = 0;
1230         if (pair_size == 4u){
1231             uuid16 = little_endian_read_16(packet,i+2);
1232             uuid_add_bluetooth_prefix(uuid128, uuid16);
1233         } else {
1234             reverse_128(&packet[i+2], uuid128);
1235         }
1236         emit_gatt_all_characteristic_descriptors_result_event(gatt_client, descriptor_handle, uuid128);
1237     }
1238 
1239 }
1240 
1241 static bool is_query_done(gatt_client_t * gatt_client, uint16_t last_result_handle){
1242     return last_result_handle >= gatt_client->end_group_handle;
1243 }
1244 
1245 static void trigger_next_query(gatt_client_t * gatt_client, uint16_t last_result_handle, gatt_client_state_t next_query_state){
1246     if (is_query_done(gatt_client, last_result_handle)){
1247         gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1248         return;
1249     }
1250     // next
1251     gatt_client->start_group_handle = last_result_handle + 1u;
1252     gatt_client->state = next_query_state;
1253 }
1254 
1255 static void trigger_next_included_service_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1256     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_INCLUDED_SERVICE_QUERY);
1257 }
1258 
1259 static void trigger_next_service_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1260     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_SERVICE_QUERY);
1261 }
1262 
1263 static void trigger_next_service_by_uuid_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1264     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_SERVICE_WITH_UUID_QUERY);
1265 }
1266 
1267 static void trigger_next_characteristic_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1268     if (is_query_done(gatt_client, last_result_handle)){
1269         // report last characteristic
1270         report_gatt_characteristic_end_found(gatt_client, gatt_client->end_group_handle);
1271     }
1272     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY);
1273 }
1274 
1275 static void trigger_next_characteristic_descriptor_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1276     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY);
1277 }
1278 
1279 static void trigger_next_read_by_type_query(gatt_client_t * gatt_client, uint16_t last_result_handle){
1280     trigger_next_query(gatt_client, last_result_handle, P_W2_SEND_READ_BY_TYPE_REQUEST);
1281 }
1282 
1283 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){
1284     gatt_client->attribute_offset += write_blob_length(gatt_client);
1285     uint16_t next_blob_length =  write_blob_length(gatt_client);
1286 
1287     if (next_blob_length == 0u){
1288         gatt_client->state = done_state;
1289         return;
1290     }
1291     gatt_client->state = next_query_state;
1292 }
1293 
1294 static void trigger_next_blob_query(gatt_client_t * gatt_client, gatt_client_state_t next_query_state, uint16_t received_blob_length){
1295 
1296     uint16_t max_blob_length = gatt_client->mtu - 1u;
1297     if (received_blob_length < max_blob_length){
1298         gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1299         return;
1300     }
1301 
1302     gatt_client->attribute_offset += received_blob_length;
1303     gatt_client->state = next_query_state;
1304 }
1305 
1306 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){
1307     notification->callback = callback;
1308     notification->con_handle = con_handle;
1309     if (characteristic == NULL){
1310         notification->attribute_handle = GATT_CLIENT_ANY_VALUE_HANDLE;
1311     } else {
1312         notification->attribute_handle = characteristic->value_handle;
1313     }
1314     btstack_linked_list_add(&gatt_client_value_listeners, (btstack_linked_item_t*) notification);
1315 }
1316 
1317 void gatt_client_stop_listening_for_characteristic_value_updates(gatt_client_notification_t * notification){
1318     btstack_linked_list_remove(&gatt_client_value_listeners, (btstack_linked_item_t*) notification);
1319 }
1320 
1321 static bool is_value_valid(gatt_client_t *gatt_client, uint8_t *packet, uint16_t size){
1322     uint16_t attribute_handle = little_endian_read_16(packet, 1);
1323     uint16_t value_offset = little_endian_read_16(packet, 3);
1324 
1325     if (gatt_client->attribute_handle != attribute_handle) return false;
1326     if (gatt_client->attribute_offset != value_offset) return false;
1327     return memcmp(&gatt_client->attribute_value[gatt_client->attribute_offset], &packet[5], size - 5u) == 0u;
1328 }
1329 
1330 #ifdef ENABLE_LE_SIGNED_WRITE
1331 static void gatt_client_run_for_client_start_signed_write(gatt_client_t *gatt_client) {
1332     sm_key_t csrk;
1333     le_device_db_local_csrk_get(gatt_client->le_device_index, csrk);
1334     uint32_t sign_counter = le_device_db_local_counter_get(gatt_client->le_device_index);
1335     gatt_client->state = P_W4_CMAC_RESULT;
1336     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);
1337 }
1338 #endif
1339 
1340 // returns true if packet was sent
1341 static bool gatt_client_run_for_gatt_client(gatt_client_t * gatt_client){
1342 
1343     // wait until re-encryption is complete
1344     if (gap_reconnect_security_setup_active(gatt_client->con_handle)) return false;
1345 
1346     // wait until re-encryption is complete
1347     if (gatt_client->reencryption_active) return false;
1348 
1349     // wait until pairing complete (either reactive authentication or due to required security level)
1350     if (gatt_client->wait_for_authentication_complete) return false;
1351 
1352     bool client_request_pending = gatt_client->state != P_READY;
1353 
1354     // verify security level for Mandatory Authentication over LE
1355     bool check_security;
1356     switch (gatt_client->bearer_type){
1357         case ATT_BEARER_UNENHANCED_LE:
1358             check_security = true;
1359             break;
1360         default:
1361             check_security = false;
1362             break;
1363     }
1364     if (client_request_pending && (gatt_client_required_security_level > gatt_client->security_level) && check_security){
1365         log_info("Trigger pairing, current security level %u, required %u\n", gatt_client->security_level, gatt_client_required_security_level);
1366         gatt_client->wait_for_authentication_complete = true;
1367         // set att error code for pairing failure based on required level
1368         switch (gatt_client_required_security_level){
1369             case LEVEL_4:
1370             case LEVEL_3:
1371                 gatt_client->pending_error_code = ATT_ERROR_INSUFFICIENT_AUTHENTICATION;
1372                 break;
1373             default:
1374                 gatt_client->pending_error_code = ATT_ERROR_INSUFFICIENT_ENCRYPTION;
1375                 break;
1376         }
1377         sm_request_pairing(gatt_client->con_handle);
1378         // sm probably just sent a pdu
1379         return true;
1380     }
1381 
1382     switch (gatt_client->mtu_state) {
1383         case SEND_MTU_EXCHANGE:
1384             gatt_client->mtu_state = SENT_MTU_EXCHANGE;
1385             att_exchange_mtu_request(gatt_client);
1386             return true;
1387         case SENT_MTU_EXCHANGE:
1388             return false;
1389         default:
1390             break;
1391     }
1392 
1393     if (gatt_client->send_confirmation){
1394         gatt_client->send_confirmation = false;
1395         att_confirmation(gatt_client);
1396         return true;
1397     }
1398 
1399     // check MTU for writes
1400     switch (gatt_client->state){
1401         case P_W2_SEND_WRITE_CHARACTERISTIC_VALUE:
1402         case P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR:
1403             if (gatt_client->attribute_length <= (gatt_client->mtu - 3u)) break;
1404             log_error("gatt_client_run: value len %u > MTU %u - 3\n", gatt_client->attribute_length,gatt_client->mtu);
1405             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_INVALID_ATTRIBUTE_VALUE_LENGTH);
1406             return false;
1407         default:
1408             break;
1409     }
1410 
1411     bool packet_sent = true;
1412     bool done = true;
1413     switch (gatt_client->state){
1414         case P_W2_SEND_SERVICE_QUERY:
1415             gatt_client->state = P_W4_SERVICE_QUERY_RESULT;
1416             send_gatt_services_request(gatt_client);
1417             break;
1418 
1419         case P_W2_SEND_SERVICE_WITH_UUID_QUERY:
1420             gatt_client->state = P_W4_SERVICE_WITH_UUID_RESULT;
1421             send_gatt_services_by_uuid_request(gatt_client);
1422             break;
1423 
1424         case P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY:
1425             gatt_client->state = P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT;
1426             send_gatt_characteristic_request(gatt_client);
1427             break;
1428 
1429         case P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY:
1430             gatt_client->state = P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT;
1431             send_gatt_characteristic_request(gatt_client);
1432             break;
1433 
1434         case P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY:
1435             gatt_client->state = P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT;
1436             send_gatt_characteristic_descriptor_request(gatt_client);
1437             break;
1438 
1439         case P_W2_SEND_INCLUDED_SERVICE_QUERY:
1440             gatt_client->state = P_W4_INCLUDED_SERVICE_QUERY_RESULT;
1441             send_gatt_included_service_request(gatt_client);
1442             break;
1443 
1444         case P_W2_SEND_INCLUDED_SERVICE_WITH_UUID_QUERY:
1445             gatt_client->state = P_W4_INCLUDED_SERVICE_UUID_WITH_QUERY_RESULT;
1446             send_gatt_included_service_uuid_request(gatt_client);
1447             break;
1448 
1449         case P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY:
1450             gatt_client->state = P_W4_READ_CHARACTERISTIC_VALUE_RESULT;
1451             send_gatt_read_characteristic_value_request(gatt_client);
1452             break;
1453 
1454         case P_W2_SEND_READ_BLOB_QUERY:
1455             gatt_client->state = P_W4_READ_BLOB_RESULT;
1456             send_gatt_read_blob_request(gatt_client);
1457             break;
1458 
1459         case P_W2_SEND_READ_BY_TYPE_REQUEST:
1460             gatt_client->state = P_W4_READ_BY_TYPE_RESPONSE;
1461             send_gatt_read_by_type_request(gatt_client);
1462             break;
1463 
1464         case P_W2_SEND_READ_MULTIPLE_REQUEST:
1465             gatt_client->state = P_W4_READ_MULTIPLE_RESPONSE;
1466             send_gatt_read_multiple_request(gatt_client);
1467             break;
1468 
1469 #ifdef ENABLE_GATT_OVER_EATT
1470         case P_W2_SEND_READ_MULTIPLE_VARIABLE_REQUEST:
1471             gatt_client->state = P_W4_READ_MULTIPLE_VARIABLE_RESPONSE;
1472             send_gatt_read_multiple_variable_request(gatt_client);
1473             break;
1474 #endif
1475 
1476         case P_W2_SEND_WRITE_CHARACTERISTIC_VALUE:
1477             gatt_client->state = P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT;
1478             send_gatt_write_attribute_value_request(gatt_client);
1479             break;
1480 
1481         case P_W2_PREPARE_WRITE:
1482             gatt_client->state = P_W4_PREPARE_WRITE_RESULT;
1483             send_gatt_prepare_write_request(gatt_client);
1484             break;
1485 
1486         case P_W2_PREPARE_WRITE_SINGLE:
1487             gatt_client->state = P_W4_PREPARE_WRITE_SINGLE_RESULT;
1488             send_gatt_prepare_write_request(gatt_client);
1489             break;
1490 
1491         case P_W2_PREPARE_RELIABLE_WRITE:
1492             gatt_client->state = P_W4_PREPARE_RELIABLE_WRITE_RESULT;
1493             send_gatt_prepare_write_request(gatt_client);
1494             break;
1495 
1496         case P_W2_EXECUTE_PREPARED_WRITE:
1497             gatt_client->state = P_W4_EXECUTE_PREPARED_WRITE_RESULT;
1498             send_gatt_execute_write_request(gatt_client);
1499             break;
1500 
1501         case P_W2_CANCEL_PREPARED_WRITE:
1502             gatt_client->state = P_W4_CANCEL_PREPARED_WRITE_RESULT;
1503             send_gatt_cancel_prepared_write_request(gatt_client);
1504             break;
1505 
1506         case P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH:
1507             gatt_client->state = P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT;
1508             send_gatt_cancel_prepared_write_request(gatt_client);
1509             break;
1510 
1511 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
1512         case P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY:
1513             // use Find Information
1514             gatt_client->gatt_client_state = P_W4_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT;
1515             send_gatt_characteristic_descriptor_request(gatt_client);
1516 #else
1517         case P_W2_SEND_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY:
1518             // Use Read By Type
1519             gatt_client->state = P_W4_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT;
1520             send_gatt_read_client_characteristic_configuration_request(gatt_client);
1521 #endif
1522             break;
1523 
1524         case P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY:
1525             gatt_client->state = P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT;
1526             send_gatt_read_characteristic_descriptor_request(gatt_client);
1527             break;
1528 
1529         case P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY:
1530             gatt_client->state = P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT;
1531             send_gatt_read_blob_request(gatt_client);
1532             break;
1533 
1534         case P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR:
1535             gatt_client->state = P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT;
1536             send_gatt_write_attribute_value_request(gatt_client);
1537             break;
1538 
1539         case P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION:
1540             gatt_client->state = P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT;
1541             send_gatt_write_client_characteristic_configuration_request(gatt_client);
1542             break;
1543 
1544         case P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR:
1545             gatt_client->state = P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT;
1546             send_gatt_prepare_write_request(gatt_client);
1547             break;
1548 
1549         case P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR:
1550             gatt_client->state = P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT;
1551             send_gatt_execute_write_request(gatt_client);
1552             break;
1553 
1554 #ifdef ENABLE_LE_SIGNED_WRITE
1555         case P_W4_IDENTITY_RESOLVING:
1556             log_info("P_W4_IDENTITY_RESOLVING - state %x", sm_identity_resolving_state(gatt_client->con_handle));
1557             switch (sm_identity_resolving_state(gatt_client->con_handle)){
1558                 case IRK_LOOKUP_SUCCEEDED:
1559                     gatt_client->le_device_index = sm_le_device_index(gatt_client->con_handle);
1560                     gatt_client->state = P_W4_CMAC_READY;
1561                     if (sm_cmac_ready()){
1562                         gatt_client_run_for_client_start_signed_write(gatt_client);
1563                     }
1564                     break;
1565                 case IRK_LOOKUP_FAILED:
1566                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_BONDING_INFORMATION_MISSING);
1567                     break;
1568                 default:
1569                     break;
1570             }
1571             packet_sent = false;
1572             break;
1573 
1574         case P_W4_CMAC_READY:
1575             if (sm_cmac_ready()){
1576                 gatt_client_run_for_client_start_signed_write(gatt_client);
1577             }
1578             packet_sent = false;
1579             break;
1580 
1581         case P_W2_SEND_SIGNED_WRITE: {
1582             gatt_client->state = P_W4_SEND_SIGNED_WRITE_DONE;
1583             // bump local signing counter
1584             uint32_t sign_counter = le_device_db_local_counter_get(gatt_client->le_device_index);
1585             le_device_db_local_counter_set(gatt_client->le_device_index, sign_counter + 1);
1586             // send signed write command
1587             send_gatt_signed_write_request(gatt_client, sign_counter);
1588             // finally, notifiy client that write is complete
1589             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1590             break;
1591         }
1592 #endif
1593         default:
1594             done = false;
1595             break;
1596     }
1597 
1598     if (done){
1599         return packet_sent;
1600     }
1601 
1602     // write without response callback
1603     btstack_context_callback_registration_t * callback =
1604             (btstack_context_callback_registration_t *) btstack_linked_list_pop(&gatt_client->write_without_response_requests);
1605     if (callback != NULL){
1606         (*callback->callback)(callback->context);
1607         return true;
1608     }
1609 
1610     // requested can send now old
1611     if (gatt_client->write_without_response_callback != NULL){
1612         btstack_packet_handler_t packet_handler = gatt_client->write_without_response_callback;
1613         gatt_client->write_without_response_callback = NULL;
1614         uint8_t event[4];
1615         event[0] = GATT_EVENT_CAN_WRITE_WITHOUT_RESPONSE;
1616         event[1] = sizeof(event) - 2u;
1617         little_endian_store_16(event, 2, gatt_client->con_handle);
1618         packet_handler(HCI_EVENT_PACKET, gatt_client->con_handle, event, sizeof(event));
1619         return true; // to trigger requeueing (even if higher layer didn't sent)
1620     }
1621 
1622     return false;
1623 }
1624 
1625 static void gatt_client_run(void){
1626     btstack_linked_item_t *it;
1627     bool packet_sent;
1628 #ifdef ENABLE_GATT_OVER_EATT
1629     btstack_linked_list_iterator_t it_eatt;
1630 #endif
1631     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
1632         gatt_client_t * gatt_client = (gatt_client_t *) it;
1633         switch (gatt_client->bearer_type){
1634             case ATT_BEARER_UNENHANCED_LE:
1635 #ifdef ENABLE_GATT_OVER_EATT
1636                 btstack_linked_list_iterator_init(&it_eatt, &gatt_client->eatt_clients);
1637                 while (btstack_linked_list_iterator_has_next(&it_eatt)) {
1638                     gatt_client_t * eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it_eatt);
1639                     if (eatt_client->state != P_READY){
1640                         if (att_dispatch_client_can_send_now(gatt_client->con_handle)){
1641                             gatt_client_run_for_gatt_client(eatt_client);
1642                         }
1643                     }
1644                 }
1645 #endif
1646                 if (!att_dispatch_client_can_send_now(gatt_client->con_handle)) {
1647                     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
1648                     return;
1649                 }
1650                 packet_sent = gatt_client_run_for_gatt_client(gatt_client);
1651                 if (packet_sent){
1652                     // request new permission
1653                     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
1654                     // requeue client for fairness and exit
1655                     // note: iterator has become invalid
1656                     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1657                     btstack_linked_list_add_tail(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1658                     return;
1659                 }
1660                 break;
1661 #ifdef ENABLE_GATT_OVER_CLASSIC
1662             case ATT_BEARER_UNENHANCED_CLASSIC:
1663                 if (gatt_client->con_handle == HCI_CON_HANDLE_INVALID) {
1664                     continue;
1665                 }
1666 
1667                 // handle GATT over BR/EDR
1668                 if (att_dispatch_client_can_send_now(gatt_client->con_handle) == false) {
1669                     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
1670                     return;
1671                 }
1672                 packet_sent = gatt_client_run_for_gatt_client(gatt_client);
1673                 if (packet_sent){
1674                     // request new permission
1675                     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
1676                     // requeue client for fairness and exit
1677                     // note: iterator has become invalid
1678                     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1679                     btstack_linked_list_add_tail(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1680                     return;
1681                 }
1682                 break;
1683 #endif
1684             default:
1685                 btstack_unreachable();
1686                 break;
1687         }
1688 
1689 
1690     }
1691 }
1692 
1693 // emit complete event, used to avoid emitting event from API call
1694 static void gatt_client_emit_events(void * context){
1695     UNUSED(context);
1696     btstack_linked_item_t *it;
1697     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next) {
1698         gatt_client_t *gatt_client = (gatt_client_t *) it;
1699         if (gatt_client->state == P_W2_EMIT_QUERY_COMPLETE_EVENT){
1700             gatt_client->state = P_READY;
1701             emit_gatt_complete_event(gatt_client, ATT_ERROR_SUCCESS);
1702         }
1703     }
1704 }
1705 
1706 static void gatt_client_report_error_if_pending(gatt_client_t *gatt_client, uint8_t att_error_code) {
1707     if (is_ready(gatt_client)) return;
1708     gatt_client_handle_transaction_complete(gatt_client, att_error_code);
1709 }
1710 
1711 static void gatt_client_handle_reencryption_complete(const uint8_t * packet){
1712     hci_con_handle_t con_handle = sm_event_reencryption_complete_get_handle(packet);
1713     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
1714     if (gatt_client == NULL) return;
1715 
1716     // update security level
1717     gatt_client->security_level = gatt_client_le_security_level_for_connection(con_handle);
1718 
1719     gatt_client->reencryption_result = sm_event_reencryption_complete_get_status(packet);
1720     gatt_client->reencryption_active = false;
1721     gatt_client->wait_for_authentication_complete = false;
1722 
1723     if (gatt_client->state == P_READY) return;
1724 
1725     switch (sm_event_reencryption_complete_get_status(packet)){
1726         case ERROR_CODE_SUCCESS:
1727             log_info("re-encryption success, retry operation");
1728             break;
1729         case ERROR_CODE_AUTHENTICATION_FAILURE:
1730         case ERROR_CODE_PIN_OR_KEY_MISSING:
1731 #if defined(ENABLE_GATT_CLIENT_PAIRING) && !defined(ENABLE_LE_PROACTIVE_AUTHENTICATION)
1732             if (gatt_client_required_security_level == LEVEL_0) {
1733                 // re-encryption failed for reactive authentication with pairing and we have a pending client request
1734                 // => try to resolve it by deleting bonding information if we started pairing before
1735                 // delete bonding information
1736                 int le_device_db_index = sm_le_device_index(gatt_client->con_handle);
1737                 btstack_assert(le_device_db_index >= 0);
1738                 log_info("reactive auth with pairing: delete bonding and start pairing");
1739 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
1740                 hci_remove_le_device_db_entry_from_resolving_list((uint16_t) le_device_db_index);
1741 #endif
1742                 le_device_db_remove(le_device_db_index);
1743                 // trigger pairing again
1744                 sm_request_pairing(gatt_client->con_handle);
1745                 break;
1746             }
1747 #endif
1748             // report bonding information missing
1749             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_BONDING_INFORMATION_MISSING);
1750             break;
1751         default:
1752             // report bonding information missing
1753             gatt_client_handle_transaction_complete(gatt_client, gatt_client->pending_error_code);
1754             break;
1755     }
1756 }
1757 
1758 static void gatt_client_handle_disconnection_complete(const uint8_t * packet){
1759     log_info("GATT Client: HCI_EVENT_DISCONNECTION_COMPLETE");
1760     hci_con_handle_t con_handle = little_endian_read_16(packet,3);
1761     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
1762     if (gatt_client == NULL) return;
1763 
1764     gatt_client_report_error_if_pending(gatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
1765     gatt_client_timeout_stop(gatt_client);
1766     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
1767     btstack_memory_gatt_client_free(gatt_client);
1768 }
1769 
1770 static void gatt_client_event_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
1771     UNUSED(channel);    // ok: handling own l2cap events
1772     UNUSED(size);       // ok: there is no channel
1773 
1774     if (packet_type != HCI_EVENT_PACKET) return;
1775 
1776     hci_con_handle_t con_handle;
1777     gatt_client_t * gatt_client;
1778     switch (hci_event_packet_get_type(packet)) {
1779         case HCI_EVENT_DISCONNECTION_COMPLETE:
1780             gatt_client_handle_disconnection_complete(packet);
1781             break;
1782 
1783         // Pairing complete (with/without bonding=storing of pairing information)
1784         case SM_EVENT_PAIRING_COMPLETE:
1785             con_handle = sm_event_pairing_complete_get_handle(packet);
1786             gatt_client = gatt_client_get_context_for_handle(con_handle);
1787             if (gatt_client == NULL) break;
1788 
1789             // update security level
1790             gatt_client->security_level = gatt_client_le_security_level_for_connection(con_handle);
1791 
1792             if (gatt_client->wait_for_authentication_complete){
1793                 gatt_client->wait_for_authentication_complete = false;
1794                 if (sm_event_pairing_complete_get_status(packet) != ERROR_CODE_SUCCESS){
1795                     log_info("pairing failed, report previous error 0x%x", gatt_client->pending_error_code);
1796                     gatt_client_report_error_if_pending(gatt_client, gatt_client->pending_error_code);
1797                 } else {
1798                     log_info("pairing success, retry operation");
1799                 }
1800             }
1801             break;
1802 
1803 #ifdef ENABLE_LE_SIGNED_WRITE
1804         // Identity Resolving completed (no code, gatt_client_run will continue)
1805         case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED:
1806         case SM_EVENT_IDENTITY_RESOLVING_FAILED:
1807             break;
1808 #endif
1809 
1810         // re-encryption started
1811         case SM_EVENT_REENCRYPTION_STARTED:
1812             con_handle = sm_event_reencryption_complete_get_handle(packet);
1813             gatt_client = gatt_client_get_context_for_handle(con_handle);
1814             if (gatt_client == NULL) break;
1815 
1816             gatt_client->reencryption_active = true;
1817             gatt_client->reencryption_result = ERROR_CODE_SUCCESS;
1818             break;
1819 
1820         // re-encryption complete
1821         case SM_EVENT_REENCRYPTION_COMPLETE:
1822             gatt_client_handle_reencryption_complete(packet);
1823             break;
1824         default:
1825             break;
1826     }
1827 
1828     gatt_client_run();
1829 }
1830 
1831 static void gatt_client_handle_att_read_response(gatt_client_t *gatt_client, uint8_t *packet, uint16_t size) {
1832     switch (gatt_client->state) {
1833         case P_W4_INCLUDED_SERVICE_UUID_WITH_QUERY_RESULT:
1834             if (size >= 17) {
1835                 uint8_t uuid128[16];
1836                 reverse_128(&packet[1], uuid128);
1837                 report_gatt_included_service_uuid128(gatt_client, gatt_client->start_group_handle, uuid128);
1838             }
1839             trigger_next_included_service_query(gatt_client, gatt_client->start_group_handle);
1840             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1841             break;
1842 
1843         case P_W4_READ_CHARACTERISTIC_VALUE_RESULT:
1844             report_gatt_characteristic_value(gatt_client, gatt_client->attribute_handle, &packet[1], size - 1u);
1845             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1846             break;
1847 
1848         case P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT:
1849             report_gatt_characteristic_descriptor(gatt_client, gatt_client->attribute_handle, &packet[1],
1850                                                   size - 1u, 0u);
1851             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1852             break;
1853 
1854             // Use ATT_READ_REQUEST for first blob of Read Long Characteristic
1855         case P_W4_READ_BLOB_RESULT:
1856             report_gatt_long_characteristic_value_blob(gatt_client, gatt_client->attribute_handle, &packet[1],
1857                                                        size - 1u, gatt_client->attribute_offset);
1858             trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_QUERY, size - 1u);
1859             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1860             break;
1861 
1862             // Use ATT_READ_REQUEST for first blob of Read Long Characteristic Descriptor
1863         case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
1864             report_gatt_long_characteristic_descriptor(gatt_client, gatt_client->attribute_handle, &packet[1],
1865                                                        size - 1u, gatt_client->attribute_offset);
1866             trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY,
1867                                     size - 1u);
1868             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1869             break;
1870 
1871         default:
1872             break;
1873     }
1874 }
1875 
1876 static void gatt_client_handle_att_read_by_type_response(gatt_client_t *gatt_client, uint8_t *packet, uint16_t size) {
1877     switch (gatt_client->state) {
1878         case P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT:
1879             report_gatt_characteristics(gatt_client, packet, size);
1880             trigger_next_characteristic_query(gatt_client,
1881                                               get_last_result_handle_from_characteristics_list(packet, size));
1882             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done, or by ATT_ERROR
1883             break;
1884         case P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT:
1885             report_gatt_characteristics(gatt_client, packet, size);
1886             trigger_next_characteristic_query(gatt_client,
1887                                               get_last_result_handle_from_characteristics_list(packet, size));
1888             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done, or by ATT_ERROR
1889             break;
1890         case P_W4_INCLUDED_SERVICE_QUERY_RESULT: {
1891             if (size < 2u) break;
1892             uint16_t uuid16 = 0;
1893             uint16_t pair_size = packet[1];
1894 
1895             if (pair_size == 6u) {
1896                 if (size < 8u) break;
1897                 // UUIDs not available, query first included service
1898                 gatt_client->start_group_handle = little_endian_read_16(packet, 2); // ready for next query
1899                 gatt_client->query_start_handle = little_endian_read_16(packet, 4);
1900                 gatt_client->query_end_handle = little_endian_read_16(packet, 6);
1901                 gatt_client->state = P_W2_SEND_INCLUDED_SERVICE_WITH_UUID_QUERY;
1902                 break;
1903             }
1904 
1905             if (pair_size != 8u) break;
1906 
1907             // UUIDs included, report all of them
1908             uint16_t offset;
1909             for (offset = 2u; (offset + 8u) <= size; offset += pair_size) {
1910                 uint16_t include_handle = little_endian_read_16(packet, offset);
1911                 gatt_client->query_start_handle = little_endian_read_16(packet, offset + 2u);
1912                 gatt_client->query_end_handle = little_endian_read_16(packet, offset + 4u);
1913                 uuid16 = little_endian_read_16(packet, offset + 6u);
1914                 report_gatt_included_service_uuid16(gatt_client, include_handle, uuid16);
1915             }
1916 
1917             trigger_next_included_service_query(gatt_client,
1918                                                 get_last_result_handle_from_included_services_list(packet,
1919                                                                                                    size));
1920             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
1921             break;
1922         }
1923 #ifndef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
1924         case P_W4_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT:
1925             gatt_client->client_characteristic_configuration_handle = little_endian_read_16(packet, 2);
1926             gatt_client->state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
1927             break;
1928 #endif
1929         case P_W4_READ_BY_TYPE_RESPONSE: {
1930             uint16_t pair_size = packet[1];
1931             // set last result handle to last valid handle, only used if pair_size invalid
1932             uint16_t last_result_handle = 0xffff;
1933             if (pair_size > 2) {
1934                 uint16_t offset;
1935                 for (offset = 2; offset < size; offset += pair_size) {
1936                     uint16_t value_handle = little_endian_read_16(packet, offset);
1937                     report_gatt_characteristic_value(gatt_client, value_handle, &packet[offset + 2u],
1938                                                      pair_size - 2u);
1939                     last_result_handle = value_handle;
1940                 }
1941             }
1942             trigger_next_read_by_type_query(gatt_client, last_result_handle);
1943             break;
1944         }
1945         default:
1946             break;
1947     }
1948 }
1949 
1950 static void gatt_client_handle_att_write_response(gatt_client_t *gatt_client) {
1951     switch (gatt_client->state) {
1952         case P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT:
1953             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1954             break;
1955         case P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT:
1956             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1957             break;
1958         case P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
1959             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
1960             break;
1961         default:
1962             break;
1963     }
1964 }
1965 
1966 static void gatt_client_handle_att_response(gatt_client_t * gatt_client, uint8_t * packet, uint16_t size) {
1967     uint8_t att_status;
1968     switch (packet[0]) {
1969         case ATT_EXCHANGE_MTU_RESPONSE: {
1970             if (size < 3u) break;
1971             bool update_gatt_server_att_mtu = false;
1972             uint16_t remote_rx_mtu = little_endian_read_16(packet, 1);
1973             uint16_t local_rx_mtu = l2cap_max_le_mtu();
1974             switch (gatt_client->bearer_type){
1975                 case ATT_BEARER_UNENHANCED_LE:
1976                     update_gatt_server_att_mtu = true;
1977                     break;
1978 #ifdef ENABLE_GATT_OVER_CLASSIC
1979                 case ATT_BEARER_UNENHANCED_CLASSIC:
1980                     local_rx_mtu = gatt_client->mtu;
1981                     break;
1982 #endif
1983                 default:
1984                     btstack_unreachable();
1985                     break;
1986             }
1987 
1988             uint16_t mtu = (remote_rx_mtu < local_rx_mtu) ? remote_rx_mtu : local_rx_mtu;
1989 
1990             // set gatt client mtu
1991             gatt_client->mtu = mtu;
1992             gatt_client->mtu_state = MTU_EXCHANGED;
1993 
1994             if (update_gatt_server_att_mtu){
1995                 // set per connection mtu state - for fixed channel
1996                 hci_connection_t *hci_connection = hci_connection_for_handle(gatt_client->con_handle);
1997                 hci_connection->att_connection.mtu = gatt_client->mtu;
1998                 hci_connection->att_connection.mtu_exchanged = true;
1999             }
2000             emit_gatt_mtu_exchanged_result_event(gatt_client, gatt_client->mtu);
2001             break;
2002         }
2003         case ATT_READ_BY_GROUP_TYPE_RESPONSE:
2004             switch (gatt_client->state) {
2005                 case P_W4_SERVICE_QUERY_RESULT:
2006                     report_gatt_services(gatt_client, packet, size);
2007                     trigger_next_service_query(gatt_client, get_last_result_handle_from_service_list(packet, size));
2008                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2009                     break;
2010                 default:
2011                     break;
2012             }
2013             break;
2014         case ATT_HANDLE_VALUE_NOTIFICATION:
2015             if (size < 3u) return;
2016             report_gatt_notification(gatt_client, little_endian_read_16(packet, 1u), &packet[3], size - 3u);
2017             return;
2018 #ifdef ENABLE_GATT_OVER_EATT
2019         case ATT_MULTIPLE_HANDLE_VALUE_NTF:
2020             if (size >= 5u) {
2021                 uint16_t offset = 1;
2022                 while (true){
2023                     uint16_t value_handle = little_endian_read_16(packet, offset);
2024                     offset += 2;
2025                     uint16_t value_length = little_endian_read_16(packet, offset);
2026                     offset += 2;
2027                     if ((offset + value_length) > size) break;
2028                     report_gatt_notification(gatt_client, value_handle, &packet[offset], value_length);
2029                     offset += value_length;
2030                 }
2031             }
2032             return;
2033 #endif
2034         case ATT_HANDLE_VALUE_INDICATION:
2035             if (size < 3u) break;
2036             report_gatt_indication(gatt_client, little_endian_read_16(packet, 1u), &packet[3], size - 3u);
2037             gatt_client->send_confirmation = true;
2038             break;
2039         case ATT_READ_BY_TYPE_RESPONSE:
2040             gatt_client_handle_att_read_by_type_response(gatt_client, packet, size);
2041             break;
2042         case ATT_READ_RESPONSE:
2043             gatt_client_handle_att_read_response(gatt_client, packet, size);
2044             break;
2045         case ATT_FIND_BY_TYPE_VALUE_RESPONSE: {
2046             uint8_t pair_size = 4;
2047             int i;
2048             uint16_t start_group_handle;
2049             uint16_t end_group_handle = 0xffff; // asserts GATT_EVENT_QUERY_COMPLETE is emitted if no results
2050             for (i = 1u; (i + pair_size) <= size; i += pair_size) {
2051                 start_group_handle = little_endian_read_16(packet, i);
2052                 end_group_handle = little_endian_read_16(packet, i + 2);
2053                 emit_gatt_service_query_result_event(gatt_client, start_group_handle, end_group_handle,
2054                                                      gatt_client->uuid128);
2055             }
2056             trigger_next_service_by_uuid_query(gatt_client, end_group_handle);
2057             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2058             break;
2059         }
2060         case ATT_FIND_INFORMATION_REPLY: {
2061             if (size < 2u) break;
2062 
2063             uint8_t pair_size = 4;
2064             if (packet[1u] == 2u) {
2065                 pair_size = 18;
2066             }
2067             uint16_t offset = 2;
2068 
2069             if (size < (pair_size + offset)) break;
2070             uint16_t last_descriptor_handle = little_endian_read_16(packet, size - pair_size);
2071 
2072 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
2073             log_info("ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY, state %x", gatt_client->gatt_client_state);
2074             if (gatt_client->gatt_client_state == P_W4_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY_RESULT){
2075                 // iterate over descriptors looking for CCC
2076                 if (pair_size == 4){
2077                     while ((offset + 4) <= size){
2078                         uint16_t uuid16 = little_endian_read_16(packet, offset + 2);
2079                         if (uuid16 == GATT_CLIENT_CHARACTERISTICS_CONFIGURATION){
2080                             gatt_client->client_characteristic_configuration_handle = little_endian_read_16(packet, offset);
2081                             gatt_client->gatt_client_state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
2082                             log_info("CCC found %x", gatt_client->client_characteristic_configuration_handle);
2083                             break;
2084                         }
2085                         offset += pair_size;
2086                     }
2087                 }
2088                 if (is_query_done(gatt_client, last_descriptor_handle)){
2089 
2090                 } else {
2091                     // next
2092                     gatt_client->start_group_handle = last_descriptor_handle + 1;
2093                     gatt_client->gatt_client_state = P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2094                 }
2095                 break;
2096             }
2097 #endif
2098             report_gatt_all_characteristic_descriptors(gatt_client, &packet[2], size - 2u, pair_size);
2099             trigger_next_characteristic_descriptor_query(gatt_client, last_descriptor_handle);
2100             // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2101             break;
2102         }
2103 
2104         case ATT_WRITE_RESPONSE:
2105             gatt_client_handle_att_write_response(gatt_client);
2106             break;
2107 
2108         case ATT_READ_BLOB_RESPONSE: {
2109             uint16_t received_blob_length = size - 1u;
2110             switch (gatt_client->state) {
2111                 case P_W4_READ_BLOB_RESULT:
2112                     report_gatt_long_characteristic_value_blob(gatt_client, gatt_client->attribute_handle, &packet[1],
2113                                                                received_blob_length, gatt_client->attribute_offset);
2114                     trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_QUERY, received_blob_length);
2115                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2116                     break;
2117                 case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
2118                     report_gatt_long_characteristic_descriptor(gatt_client, gatt_client->attribute_handle,
2119                                                                &packet[1], received_blob_length,
2120                                                                gatt_client->attribute_offset);
2121                     trigger_next_blob_query(gatt_client, P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY,
2122                                             received_blob_length);
2123                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2124                     break;
2125                 default:
2126                     break;
2127             }
2128             break;
2129         }
2130         case ATT_PREPARE_WRITE_RESPONSE:
2131             switch (gatt_client->state) {
2132                 case P_W4_PREPARE_WRITE_SINGLE_RESULT:
2133                     if (is_value_valid(gatt_client, packet, size)) {
2134                         att_status = ATT_ERROR_SUCCESS;
2135                     } else {
2136                         att_status = ATT_ERROR_DATA_MISMATCH;
2137                     }
2138                     gatt_client_handle_transaction_complete(gatt_client, att_status);
2139                     break;
2140 
2141                 case P_W4_PREPARE_WRITE_RESULT: {
2142                     gatt_client->attribute_offset = little_endian_read_16(packet, 3);
2143                     trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_WRITE, P_W2_EXECUTE_PREPARED_WRITE);
2144                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2145                     break;
2146                 }
2147                 case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT: {
2148                     gatt_client->attribute_offset = little_endian_read_16(packet, 3);
2149                     trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR,
2150                                                      P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR);
2151                     // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2152                     break;
2153                 }
2154                 case P_W4_PREPARE_RELIABLE_WRITE_RESULT: {
2155                     if (is_value_valid(gatt_client, packet, size)) {
2156                         gatt_client->attribute_offset = little_endian_read_16(packet, 3);
2157                         trigger_next_prepare_write_query(gatt_client, P_W2_PREPARE_RELIABLE_WRITE,
2158                                                          P_W2_EXECUTE_PREPARED_WRITE);
2159                         // GATT_EVENT_QUERY_COMPLETE is emitted by trigger_next_xxx when done
2160                         break;
2161                     }
2162                     gatt_client->state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
2163                     break;
2164                 }
2165                 default:
2166                     break;
2167             }
2168             break;
2169 
2170         case ATT_EXECUTE_WRITE_RESPONSE:
2171             switch (gatt_client->state) {
2172                 case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
2173                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2174                     break;
2175                 case P_W4_CANCEL_PREPARED_WRITE_RESULT:
2176                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2177                     break;
2178                 case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
2179                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_DATA_MISMATCH);
2180                     break;
2181                 case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
2182                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2183                     break;
2184                 default:
2185                     break;
2186 
2187             }
2188             break;
2189 
2190         case ATT_READ_MULTIPLE_RESPONSE:
2191             switch (gatt_client->state) {
2192                 case P_W4_READ_MULTIPLE_RESPONSE:
2193                     report_gatt_characteristic_value(gatt_client, 0u, &packet[1], size - 1u);
2194                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2195                     break;
2196                 default:
2197                     break;
2198             }
2199             break;
2200 
2201 #ifdef ENABLE_GATT_OVER_EATT
2202         case ATT_READ_MULTIPLE_VARIABLE_RSP:
2203             switch (gatt_client->state) {
2204                 case P_W4_READ_MULTIPLE_VARIABLE_RESPONSE:
2205                     report_gatt_characteristic_value(gatt_client, 0u, &packet[1], size - 1u);
2206                     gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2207                     break;
2208                 default:
2209                     break;
2210             }
2211             break;
2212 #endif
2213 
2214         case ATT_ERROR_RESPONSE:
2215             if (size < 5u) return;
2216             att_status = packet[4];
2217             switch (att_status) {
2218                 case ATT_ERROR_ATTRIBUTE_NOT_FOUND: {
2219                     switch (gatt_client->state) {
2220                         case P_W4_SERVICE_QUERY_RESULT:
2221                         case P_W4_SERVICE_WITH_UUID_RESULT:
2222                         case P_W4_INCLUDED_SERVICE_QUERY_RESULT:
2223                         case P_W4_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY_RESULT:
2224                             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2225                             break;
2226                         case P_W4_ALL_CHARACTERISTICS_OF_SERVICE_QUERY_RESULT:
2227                         case P_W4_CHARACTERISTIC_WITH_UUID_QUERY_RESULT:
2228                             report_gatt_characteristic_end_found(gatt_client, gatt_client->end_group_handle);
2229                             gatt_client_handle_transaction_complete(gatt_client, ATT_ERROR_SUCCESS);
2230                             break;
2231                         case P_W4_READ_BY_TYPE_RESPONSE:
2232                             if (gatt_client->start_group_handle == gatt_client->query_start_handle) {
2233                                 att_status = ATT_ERROR_ATTRIBUTE_NOT_FOUND;
2234                             } else {
2235                                 att_status = ATT_ERROR_SUCCESS;
2236                             }
2237                             gatt_client_handle_transaction_complete(gatt_client, att_status);
2238                             break;
2239                         default:
2240                             gatt_client_report_error_if_pending(gatt_client, att_status);
2241                             break;
2242                     }
2243                     break;
2244                 }
2245 
2246 #ifdef ENABLE_GATT_CLIENT_PAIRING
2247 
2248                     case ATT_ERROR_INSUFFICIENT_AUTHENTICATION:
2249                     case ATT_ERROR_INSUFFICIENT_ENCRYPTION_KEY_SIZE:
2250                     case ATT_ERROR_INSUFFICIENT_ENCRYPTION: {
2251 
2252                         // security too low
2253                         if (gatt_client->security_counter > 0) {
2254                             gatt_client_report_error_if_pending(gatt_client, att_status);
2255                             break;
2256                         }
2257                         // start security
2258                         gatt_client->security_counter++;
2259 
2260                         // setup action
2261                         int retry = 1;
2262                         switch (gatt_client->state){
2263                             case P_W4_READ_CHARACTERISTIC_VALUE_RESULT:
2264                                 gatt_client->state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY ;
2265                                 break;
2266                             case P_W4_READ_BLOB_RESULT:
2267                                 gatt_client->state = P_W2_SEND_READ_BLOB_QUERY;
2268                                 break;
2269                             case P_W4_READ_BY_TYPE_RESPONSE:
2270                                 gatt_client->state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2271                                 break;
2272                             case P_W4_READ_MULTIPLE_RESPONSE:
2273                                 gatt_client->state = P_W2_SEND_READ_MULTIPLE_REQUEST;
2274                                 break;
2275                             case P_W4_READ_MULTIPLE_VARIABLE_RESPONSE:
2276                                 gatt_client->state = P_W2_SEND_READ_MULTIPLE_VARIABLE_REQUEST;
2277                                 break;
2278                             case P_W4_WRITE_CHARACTERISTIC_VALUE_RESULT:
2279                                 gatt_client->state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
2280                                 break;
2281                             case P_W4_PREPARE_WRITE_RESULT:
2282                                 gatt_client->state = P_W2_PREPARE_WRITE;
2283                                 break;
2284                             case P_W4_PREPARE_WRITE_SINGLE_RESULT:
2285                                 gatt_client->state = P_W2_PREPARE_WRITE_SINGLE;
2286                                 break;
2287                             case P_W4_PREPARE_RELIABLE_WRITE_RESULT:
2288                                 gatt_client->state = P_W2_PREPARE_RELIABLE_WRITE;
2289                                 break;
2290                             case P_W4_EXECUTE_PREPARED_WRITE_RESULT:
2291                                 gatt_client->state = P_W2_EXECUTE_PREPARED_WRITE;
2292                                 break;
2293                             case P_W4_CANCEL_PREPARED_WRITE_RESULT:
2294                                 gatt_client->state = P_W2_CANCEL_PREPARED_WRITE;
2295                                 break;
2296                             case P_W4_CANCEL_PREPARED_WRITE_DATA_MISMATCH_RESULT:
2297                                 gatt_client->state = P_W2_CANCEL_PREPARED_WRITE_DATA_MISMATCH;
2298                                 break;
2299                             case P_W4_READ_CHARACTERISTIC_DESCRIPTOR_RESULT:
2300                                 gatt_client->state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
2301                                 break;
2302                             case P_W4_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_RESULT:
2303                                 gatt_client->state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
2304                                 break;
2305                             case P_W4_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
2306                                 gatt_client->state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
2307                                 break;
2308                             case P_W4_CLIENT_CHARACTERISTIC_CONFIGURATION_RESULT:
2309                                 gatt_client->state = P_W2_WRITE_CLIENT_CHARACTERISTIC_CONFIGURATION;
2310                                 break;
2311                             case P_W4_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
2312                                 gatt_client->state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
2313                                 break;
2314                             case P_W4_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR_RESULT:
2315                                 gatt_client->state = P_W2_EXECUTE_PREPARED_WRITE_CHARACTERISTIC_DESCRIPTOR;
2316                                 break;
2317 #ifdef ENABLE_LE_SIGNED_WRITE
2318                             case P_W4_SEND_SIGNED_WRITE_DONE:
2319                                 gatt_client->state = P_W2_SEND_SIGNED_WRITE;
2320                                 break;
2321 #endif
2322                             default:
2323                                 log_info("retry not supported for state %x", gatt_client->state);
2324                                 retry = 0;
2325                                 break;
2326                         }
2327 
2328                         if (!retry) {
2329                             gatt_client_report_error_if_pending(gatt_client, att_status);
2330                             break;
2331                         }
2332 
2333                         log_info("security error, start pairing");
2334 
2335                         // start pairing for higher security level
2336                         gatt_client->wait_for_authentication_complete = true;
2337                         gatt_client->pending_error_code = att_status;
2338                         sm_request_pairing(gatt_client->con_handle);
2339                         break;
2340                     }
2341 #endif
2342 
2343                     // nothing we can do about that
2344                 case ATT_ERROR_INSUFFICIENT_AUTHORIZATION:
2345                 default:
2346                     gatt_client_report_error_if_pending(gatt_client, att_status);
2347                     break;
2348             }
2349             break;
2350 
2351         default:
2352             log_info("ATT Handler, unhandled response type 0x%02x", packet[0]);
2353             break;
2354     }
2355 }
2356 
2357 static void gatt_client_att_packet_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size) {
2358     gatt_client_t *gatt_client;
2359 #ifdef ENABLE_GATT_OVER_CLASSIC
2360     uint8_t status;
2361     hci_connection_t * hci_connection;
2362     hci_con_handle_t con_handle;
2363 #endif
2364 
2365     if (size < 1u) return;
2366     switch (packet_type){
2367         case HCI_EVENT_PACKET:
2368             switch (hci_event_packet_get_type(packet)) {
2369 #ifdef ENABLE_GATT_OVER_CLASSIC
2370                 case L2CAP_EVENT_CHANNEL_OPENED:
2371                     status = l2cap_event_channel_opened_get_status(packet);
2372                     gatt_client = gatt_client_get_context_for_l2cap_cid(l2cap_event_channel_opened_get_local_cid(packet));
2373                     if (gatt_client != NULL){
2374                         con_handle = l2cap_event_channel_opened_get_handle(packet);
2375                         hci_connection = hci_connection_for_handle(con_handle);
2376                         if (status == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_RESOURCES){
2377                             if ((hci_connection != NULL) && hci_connection->att_server.incoming_connection_request) {
2378                                 log_info("Collision, retry in 100ms");
2379                                 gatt_client->state = P_W2_L2CAP_CONNECT;
2380                                 // set timer for retry
2381                                 btstack_run_loop_set_timer(&gatt_client->gc_timeout, GATT_CLIENT_COLLISION_BACKOFF_MS);
2382                                 btstack_run_loop_set_timer_handler(&gatt_client->gc_timeout, gatt_client_classic_retry);
2383                                 btstack_run_loop_add_timer(&gatt_client->gc_timeout);
2384                                 break;
2385                             }
2386                         }
2387                         // if status != 0, gatt_client will be discarded
2388                         gatt_client->state = P_READY;
2389                         gatt_client->con_handle = l2cap_event_channel_opened_get_handle(packet);
2390                         gatt_client->mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
2391                         gatt_client_classic_handle_connected(gatt_client, status);
2392                     }
2393                     break;
2394                 case L2CAP_EVENT_CHANNEL_CLOSED:
2395                     gatt_client = gatt_client_get_context_for_l2cap_cid(l2cap_event_channel_closed_get_local_cid(packet));
2396                     if (gatt_client != NULL){
2397                         // discard gatt client object
2398                         gatt_client_classic_handle_disconnected(gatt_client);
2399                     }
2400                     break;
2401 #endif
2402                 case L2CAP_EVENT_CAN_SEND_NOW:
2403                     gatt_client_run();
2404                     break;
2405                     // att_server has negotiated the mtu for this connection, cache if context exists
2406                 case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
2407                     if (size < 6u) break;
2408                     gatt_client = gatt_client_get_context_for_handle(handle);
2409                     if (gatt_client != NULL) {
2410                         gatt_client->mtu = little_endian_read_16(packet, 4);
2411                     }
2412                     break;
2413                 default:
2414                     break;
2415             }
2416             break;
2417 
2418         case ATT_DATA_PACKET:
2419             // special cases: notifications & indications motivate creating context
2420             switch (packet[0]) {
2421                 case ATT_HANDLE_VALUE_NOTIFICATION:
2422                 case ATT_HANDLE_VALUE_INDICATION:
2423                     gatt_client_provide_context_for_handle(handle, &gatt_client);
2424                     break;
2425                 default:
2426                     gatt_client = gatt_client_get_context_for_handle(handle);
2427                     break;
2428             }
2429 
2430             if (gatt_client != NULL) {
2431                 gatt_client_handle_att_response(gatt_client, packet, size);
2432                 gatt_client_run();
2433             }
2434             break;
2435 
2436 #ifdef ENABLE_GATT_OVER_CLASSIC
2437         case L2CAP_DATA_PACKET:
2438             gatt_client = gatt_client_get_context_for_l2cap_cid(handle);
2439             if (gatt_client != NULL){
2440                 gatt_client_handle_att_response(gatt_client, packet, size);
2441                 gatt_client_run();
2442             }
2443             break;
2444 #endif
2445 
2446         default:
2447             break;
2448     }
2449 }
2450 
2451 #ifdef ENABLE_LE_SIGNED_WRITE
2452 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
2453     btstack_linked_list_iterator_t it;
2454     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
2455     while (btstack_linked_list_iterator_has_next(&it)){
2456         gatt_client_t * gatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
2457         if (gatt_client->state == P_W4_CMAC_RESULT){
2458             // store result
2459             (void)memcpy(gatt_client->cmac, hash, 8);
2460             // reverse_64(hash, gatt_client->cmac);
2461             gatt_client->state = P_W2_SEND_SIGNED_WRITE;
2462             gatt_client_run();
2463             return;
2464         }
2465     }
2466 }
2467 
2468 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){
2469     gatt_client_t * gatt_client;
2470     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2471     if (status != ERROR_CODE_SUCCESS){
2472         return status;
2473     }
2474     if (is_ready(gatt_client) == 0){
2475         return GATT_CLIENT_IN_WRONG_STATE;
2476     }
2477 
2478     gatt_client->callback = callback;
2479     gatt_client->attribute_handle = value_handle;
2480     gatt_client->attribute_length = message_len;
2481     gatt_client->attribute_value = message;
2482     gatt_client->state = P_W4_IDENTITY_RESOLVING;
2483     gatt_client_run();
2484     return ERROR_CODE_SUCCESS;
2485 }
2486 #endif
2487 
2488 uint8_t gatt_client_discover_primary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2489     gatt_client_t * gatt_client;
2490     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2491     if (status != ERROR_CODE_SUCCESS){
2492         return status;
2493     }
2494 
2495     gatt_client->callback = callback;
2496     gatt_client->start_group_handle = 0x0001;
2497     gatt_client->end_group_handle   = 0xffff;
2498     gatt_client->state = P_W2_SEND_SERVICE_QUERY;
2499     gatt_client->uuid16 = GATT_PRIMARY_SERVICE_UUID;
2500     gatt_client_run();
2501     return ERROR_CODE_SUCCESS;
2502 }
2503 
2504 uint8_t gatt_client_discover_secondary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2505     gatt_client_t * gatt_client;
2506     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2507     if (status != ERROR_CODE_SUCCESS){
2508         return status;
2509     }
2510 
2511     gatt_client->callback = callback;
2512     gatt_client->start_group_handle = 0x0001;
2513     gatt_client->end_group_handle   = 0xffff;
2514     gatt_client->state = P_W2_SEND_SERVICE_QUERY;
2515     gatt_client->uuid16 = GATT_SECONDARY_SERVICE_UUID;
2516     gatt_client_run();
2517     return ERROR_CODE_SUCCESS;
2518 }
2519 
2520 uint8_t gatt_client_discover_primary_services_by_uuid16(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t uuid16){
2521     gatt_client_t * gatt_client;
2522     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2523     if (status != ERROR_CODE_SUCCESS){
2524         return status;
2525     }
2526 
2527     gatt_client->callback = callback;
2528     gatt_client->start_group_handle = 0x0001;
2529     gatt_client->end_group_handle   = 0xffff;
2530     gatt_client->state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
2531     gatt_client->uuid16 = uuid16;
2532     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), gatt_client->uuid16);
2533     gatt_client_run();
2534     return ERROR_CODE_SUCCESS;
2535 }
2536 
2537 uint8_t gatt_client_discover_primary_services_by_uuid128(btstack_packet_handler_t callback, hci_con_handle_t con_handle, const uint8_t * uuid128){
2538     gatt_client_t * gatt_client;
2539     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2540     if (status != ERROR_CODE_SUCCESS){
2541         return status;
2542     }
2543 
2544     gatt_client->callback = callback;
2545     gatt_client->start_group_handle = 0x0001;
2546     gatt_client->end_group_handle   = 0xffff;
2547     gatt_client->uuid16 = 0;
2548     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2549     gatt_client->state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
2550     gatt_client_run();
2551     return ERROR_CODE_SUCCESS;
2552 }
2553 
2554 uint8_t gatt_client_discover_characteristics_for_service(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_service_t * service){
2555     gatt_client_t * gatt_client;
2556     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2557     if (status != ERROR_CODE_SUCCESS){
2558         return status;
2559     }
2560 
2561     gatt_client->callback = callback;
2562     gatt_client->start_group_handle = service->start_group_handle;
2563     gatt_client->end_group_handle   = service->end_group_handle;
2564     gatt_client->filter_with_uuid = false;
2565     gatt_client->characteristic_start_handle = 0;
2566     gatt_client->state = P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY;
2567     gatt_client_run();
2568     return ERROR_CODE_SUCCESS;
2569 }
2570 
2571 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){
2572     gatt_client_t * gatt_client;
2573     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2574     if (status != ERROR_CODE_SUCCESS){
2575         return status;
2576     }
2577 
2578     gatt_client->callback = callback;
2579     gatt_client->start_group_handle = service->start_group_handle;
2580     gatt_client->end_group_handle   = service->end_group_handle;
2581     gatt_client->state = P_W2_SEND_INCLUDED_SERVICE_QUERY;
2582 
2583     gatt_client_run();
2584     return ERROR_CODE_SUCCESS;
2585 }
2586 
2587 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){
2588     gatt_client_t * gatt_client;
2589     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2590     if (status != ERROR_CODE_SUCCESS){
2591         return status;
2592     }
2593 
2594     gatt_client->callback = callback;
2595     gatt_client->start_group_handle = start_handle;
2596     gatt_client->end_group_handle   = end_handle;
2597     gatt_client->filter_with_uuid = true;
2598     gatt_client->uuid16 = uuid16;
2599     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), uuid16);
2600     gatt_client->characteristic_start_handle = 0;
2601     gatt_client->state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
2602     gatt_client_run();
2603     return ERROR_CODE_SUCCESS;
2604 }
2605 
2606 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){
2607     gatt_client_t * gatt_client;
2608     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2609     if (status != ERROR_CODE_SUCCESS){
2610         return status;
2611     }
2612 
2613     gatt_client->callback = callback;
2614     gatt_client->start_group_handle = start_handle;
2615     gatt_client->end_group_handle   = end_handle;
2616     gatt_client->filter_with_uuid = true;
2617     gatt_client->uuid16 = 0;
2618     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2619     gatt_client->characteristic_start_handle = 0;
2620     gatt_client->state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
2621     gatt_client_run();
2622     return ERROR_CODE_SUCCESS;
2623 }
2624 
2625 
2626 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){
2627     return gatt_client_discover_characteristics_for_handle_range_by_uuid16(callback, con_handle, service->start_group_handle, service->end_group_handle, uuid16);
2628 }
2629 
2630 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){
2631     return gatt_client_discover_characteristics_for_handle_range_by_uuid128(callback, con_handle, service->start_group_handle, service->end_group_handle, uuid128);
2632 }
2633 
2634 uint8_t gatt_client_discover_characteristic_descriptors(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2635     gatt_client_t * gatt_client;
2636     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2637     if (status != ERROR_CODE_SUCCESS){
2638         return status;
2639     }
2640 
2641     // check if there is space for characteristics descriptors
2642     if (characteristic->end_handle > characteristic->value_handle){
2643         gatt_client->callback = callback;
2644         gatt_client->start_group_handle = characteristic->value_handle + 1u;
2645         gatt_client->end_group_handle   = characteristic->end_handle;
2646         gatt_client->state = P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY;
2647         gatt_client_run();
2648     } else {
2649         // schedule gatt complete event on next run loop iteration otherwise
2650         gatt_client->state = P_W2_EMIT_QUERY_COMPLETE_EVENT;
2651         gatt_client_deferred_event_emit.callback = gatt_client_emit_events;
2652         btstack_run_loop_execute_on_main_thread(&gatt_client_deferred_event_emit);
2653     }
2654     return ERROR_CODE_SUCCESS;
2655 }
2656 
2657 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){
2658     gatt_client_t * gatt_client;
2659     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2660     if (status != ERROR_CODE_SUCCESS){
2661         return status;
2662     }
2663 
2664     gatt_client->callback = callback;
2665     gatt_client->attribute_handle = value_handle;
2666     gatt_client->attribute_offset = 0;
2667     gatt_client->state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY;
2668     gatt_client_run();
2669     return ERROR_CODE_SUCCESS;
2670 }
2671 
2672 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){
2673     gatt_client_t * gatt_client;
2674     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2675     if (status != ERROR_CODE_SUCCESS){
2676         return status;
2677     }
2678 
2679     gatt_client->callback = callback;
2680     gatt_client->start_group_handle = start_handle;
2681     gatt_client->end_group_handle = end_handle;
2682     gatt_client->query_start_handle = start_handle;
2683     gatt_client->query_end_handle = end_handle;
2684     gatt_client->uuid16 = uuid16;
2685     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), uuid16);
2686     gatt_client->state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2687     gatt_client_run();
2688     return ERROR_CODE_SUCCESS;
2689 }
2690 
2691 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){
2692     gatt_client_t * gatt_client;
2693     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2694     if (status != ERROR_CODE_SUCCESS){
2695         return status;
2696     }
2697 
2698     gatt_client->callback = callback;
2699     gatt_client->start_group_handle = start_handle;
2700     gatt_client->end_group_handle = end_handle;
2701     gatt_client->query_start_handle = start_handle;
2702     gatt_client->query_end_handle = end_handle;
2703     gatt_client->uuid16 = 0;
2704     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2705     gatt_client->state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2706     gatt_client_run();
2707     return ERROR_CODE_SUCCESS;
2708 }
2709 
2710 
2711 uint8_t gatt_client_read_value_of_characteristic(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2712     return gatt_client_read_value_of_characteristic_using_value_handle(callback, con_handle, characteristic->value_handle);
2713 }
2714 
2715 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){
2716     gatt_client_t * gatt_client;
2717     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2718     if (status != ERROR_CODE_SUCCESS){
2719         return status;
2720     }
2721 
2722     gatt_client->callback = callback;
2723     gatt_client->attribute_handle = value_handle;
2724     gatt_client->attribute_offset = offset;
2725     gatt_client->state = P_W2_SEND_READ_BLOB_QUERY;
2726     gatt_client_run();
2727     return ERROR_CODE_SUCCESS;
2728 }
2729 
2730 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){
2731     return gatt_client_read_long_value_of_characteristic_using_value_handle_with_offset(callback, con_handle, value_handle, 0);
2732 }
2733 
2734 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){
2735     return gatt_client_read_long_value_of_characteristic_using_value_handle(callback, con_handle, characteristic->value_handle);
2736 }
2737 
2738 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){
2739     gatt_client_t * gatt_client;
2740     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2741     if (status != ERROR_CODE_SUCCESS){
2742         return status;
2743     }
2744 
2745 #ifdef ENABLE_GATT_OVER_EATT
2746     if (state == P_W2_SEND_READ_MULTIPLE_VARIABLE_REQUEST){
2747         if (gatt_client->bearer_type != ATT_BEARER_ENHANCED_LE){
2748             return ERROR_CODE_COMMAND_DISALLOWED;
2749         }
2750     }
2751 #endif
2752 
2753     gatt_client->callback = callback;
2754     gatt_client->read_multiple_handle_count = num_value_handles;
2755     gatt_client->read_multiple_handles = value_handles;
2756     gatt_client->state = state;
2757     gatt_client_run();
2758     return ERROR_CODE_SUCCESS;
2759 }
2760 
2761 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){
2762     return gatt_client_read_multiple_characteristic_values_with_state(callback, con_handle, num_value_handles, value_handles, P_W2_SEND_READ_MULTIPLE_REQUEST);
2763 }
2764 
2765 #ifdef ENABLE_GATT_OVER_EATT
2766 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){
2767     return gatt_client_read_multiple_characteristic_values_with_state(callback, con_handle, num_value_handles, value_handles, P_W2_SEND_READ_MULTIPLE_VARIABLE_REQUEST);
2768 }
2769 #endif
2770 
2771 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){
2772     gatt_client_t * gatt_client;
2773     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2774     if (status != ERROR_CODE_SUCCESS){
2775         return status;
2776     }
2777 
2778     if (value_length > (gatt_client->mtu - 3u)) return GATT_CLIENT_VALUE_TOO_LONG;
2779     if (!att_dispatch_client_can_send_now(gatt_client->con_handle)) return GATT_CLIENT_BUSY;
2780 
2781     return att_write_request(gatt_client, ATT_WRITE_COMMAND, value_handle, value_length, value);
2782 }
2783 
2784 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){
2785     gatt_client_t * gatt_client;
2786     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2787     if (status != ERROR_CODE_SUCCESS){
2788         return status;
2789     }
2790 
2791     gatt_client->callback = callback;
2792     gatt_client->attribute_handle = value_handle;
2793     gatt_client->attribute_length = value_length;
2794     gatt_client->attribute_value = value;
2795     gatt_client->state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
2796     gatt_client_run();
2797     return ERROR_CODE_SUCCESS;
2798 }
2799 
2800 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){
2801     gatt_client_t * gatt_client;
2802     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2803     if (status != ERROR_CODE_SUCCESS){
2804         return status;
2805     }
2806 
2807     gatt_client->callback = callback;
2808     gatt_client->attribute_handle = value_handle;
2809     gatt_client->attribute_length = value_length;
2810     gatt_client->attribute_offset = offset;
2811     gatt_client->attribute_value = value;
2812     gatt_client->state = P_W2_PREPARE_WRITE;
2813     gatt_client_run();
2814     return ERROR_CODE_SUCCESS;
2815 }
2816 
2817 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){
2818     return gatt_client_write_long_value_of_characteristic_with_offset(callback, con_handle, value_handle, 0, value_length, value);
2819 }
2820 
2821 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){
2822     gatt_client_t * gatt_client;
2823     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2824     if (status != ERROR_CODE_SUCCESS){
2825         return status;
2826     }
2827 
2828     gatt_client->callback = callback;
2829     gatt_client->attribute_handle = value_handle;
2830     gatt_client->attribute_length = value_length;
2831     gatt_client->attribute_offset = 0;
2832     gatt_client->attribute_value = value;
2833     gatt_client->state = P_W2_PREPARE_RELIABLE_WRITE;
2834     gatt_client_run();
2835     return ERROR_CODE_SUCCESS;
2836 }
2837 
2838 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){
2839     gatt_client_t * gatt_client;
2840     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2841     if (status != ERROR_CODE_SUCCESS){
2842         return status;
2843     }
2844 
2845     if (configuration > 3){
2846         return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE;
2847     }
2848 
2849     if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION) &&
2850         ((characteristic->properties & ATT_PROPERTY_NOTIFY) == 0u)) {
2851         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED");
2852         return GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED;
2853     } else if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_INDICATION) &&
2854                ((characteristic->properties & ATT_PROPERTY_INDICATE) == 0u)){
2855         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED");
2856         return GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED;
2857     }
2858 
2859     gatt_client->callback = callback;
2860     gatt_client->start_group_handle = characteristic->value_handle;
2861     gatt_client->end_group_handle = characteristic->end_handle;
2862     little_endian_store_16(gatt_client->client_characteristic_configuration_value, 0, configuration);
2863 
2864 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
2865     gatt_client->gatt_client_state = P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2866 #else
2867     gatt_client->state = P_W2_SEND_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2868 #endif
2869     gatt_client_run();
2870     return ERROR_CODE_SUCCESS;
2871 }
2872 
2873 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){
2874     gatt_client_t * gatt_client;
2875     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2876     if (status != ERROR_CODE_SUCCESS){
2877         return status;
2878     }
2879 
2880     gatt_client->callback = callback;
2881     gatt_client->attribute_handle = descriptor_handle;
2882 
2883     gatt_client->state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
2884     gatt_client_run();
2885     return ERROR_CODE_SUCCESS;
2886 }
2887 
2888 uint8_t gatt_client_read_characteristic_descriptor(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_descriptor_t * descriptor){
2889     return gatt_client_read_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
2890 }
2891 
2892 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){
2893     gatt_client_t * gatt_client;
2894     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2895     if (status != ERROR_CODE_SUCCESS){
2896         return status;
2897     }
2898 
2899     gatt_client->callback = callback;
2900     gatt_client->attribute_handle = descriptor_handle;
2901     gatt_client->attribute_offset = offset;
2902     gatt_client->state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
2903     gatt_client_run();
2904     return ERROR_CODE_SUCCESS;
2905 }
2906 
2907 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){
2908     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0);
2909 }
2910 
2911 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){
2912     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
2913 }
2914 
2915 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){
2916     gatt_client_t * gatt_client;
2917     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2918     if (status != ERROR_CODE_SUCCESS){
2919         return status;
2920     }
2921 
2922     gatt_client->callback = callback;
2923     gatt_client->attribute_handle = descriptor_handle;
2924     gatt_client->attribute_length = value_length;
2925     gatt_client->attribute_offset = 0;
2926     gatt_client->attribute_value = value;
2927     gatt_client->state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
2928     gatt_client_run();
2929     return ERROR_CODE_SUCCESS;
2930 }
2931 
2932 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){
2933     return gatt_client_write_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, value_length, value);
2934 }
2935 
2936 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){
2937     gatt_client_t * gatt_client;
2938     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2939     if (status != ERROR_CODE_SUCCESS){
2940         return status;
2941     }
2942 
2943     gatt_client->callback = callback;
2944     gatt_client->attribute_handle = descriptor_handle;
2945     gatt_client->attribute_length = value_length;
2946     gatt_client->attribute_offset = offset;
2947     gatt_client->attribute_value = value;
2948     gatt_client->state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
2949     gatt_client_run();
2950     return ERROR_CODE_SUCCESS;
2951 }
2952 
2953 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){
2954     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0, value_length, value);
2955 }
2956 
2957 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){
2958     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, value_length, value);
2959 }
2960 
2961 /**
2962  * @brief -> gatt complete event
2963  */
2964 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){
2965     gatt_client_t * gatt_client;
2966     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2967     if (status != ERROR_CODE_SUCCESS){
2968         return status;
2969     }
2970 
2971     gatt_client->callback = callback;
2972     gatt_client->attribute_handle = attribute_handle;
2973     gatt_client->attribute_length = value_length;
2974     gatt_client->attribute_offset = offset;
2975     gatt_client->attribute_value = value;
2976     gatt_client->state = P_W2_PREPARE_WRITE_SINGLE;
2977     gatt_client_run();
2978     return ERROR_CODE_SUCCESS;
2979 }
2980 
2981 /**
2982  * @brief -> gatt complete event
2983  */
2984 uint8_t gatt_client_execute_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2985     gatt_client_t * gatt_client;
2986     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2987     if (status != ERROR_CODE_SUCCESS){
2988         return status;
2989     }
2990 
2991     gatt_client->callback = callback;
2992     gatt_client->state = P_W2_EXECUTE_PREPARED_WRITE;
2993     gatt_client_run();
2994     return ERROR_CODE_SUCCESS;
2995 }
2996 
2997 /**
2998  * @brief -> gatt complete event
2999  */
3000 uint8_t gatt_client_cancel_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
3001     gatt_client_t * gatt_client;
3002     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
3003     if (status != ERROR_CODE_SUCCESS){
3004         return status;
3005     }
3006 
3007     gatt_client->callback = callback;
3008     gatt_client->state = P_W2_CANCEL_PREPARED_WRITE;
3009     gatt_client_run();
3010     return ERROR_CODE_SUCCESS;
3011 }
3012 
3013 void gatt_client_deserialize_service(const uint8_t *packet, int offset, gatt_client_service_t * service){
3014     service->start_group_handle = little_endian_read_16(packet, offset);
3015     service->end_group_handle = little_endian_read_16(packet, offset + 2);
3016     reverse_128(&packet[offset + 4], service->uuid128);
3017     if (uuid_has_bluetooth_prefix(service->uuid128)){
3018         service->uuid16 = big_endian_read_32(service->uuid128, 0);
3019     } else {
3020         service->uuid16 = 0;
3021     }
3022 }
3023 
3024 void gatt_client_deserialize_characteristic(const uint8_t * packet, int offset, gatt_client_characteristic_t * characteristic){
3025     characteristic->start_handle = little_endian_read_16(packet, offset);
3026     characteristic->value_handle = little_endian_read_16(packet, offset + 2);
3027     characteristic->end_handle = little_endian_read_16(packet, offset + 4);
3028     characteristic->properties = little_endian_read_16(packet, offset + 6);
3029     reverse_128(&packet[offset+8], characteristic->uuid128);
3030     if (uuid_has_bluetooth_prefix(characteristic->uuid128)){
3031         characteristic->uuid16 = big_endian_read_32(characteristic->uuid128, 0);
3032     } else {
3033         characteristic->uuid16 = 0;
3034     }
3035 }
3036 
3037 void gatt_client_deserialize_characteristic_descriptor(const uint8_t * packet, int offset, gatt_client_characteristic_descriptor_t * descriptor){
3038     descriptor->handle = little_endian_read_16(packet, offset);
3039     reverse_128(&packet[offset+2], descriptor->uuid128);
3040     if (uuid_has_bluetooth_prefix(descriptor->uuid128)){
3041         descriptor->uuid16 = big_endian_read_32(descriptor->uuid128, 0);
3042     } else {
3043         descriptor->uuid16 = 0;
3044     }
3045 }
3046 
3047 void gatt_client_send_mtu_negotiation(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
3048     gatt_client_t * gatt_client;
3049     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3050     if (status != ERROR_CODE_SUCCESS){
3051         return;
3052     }
3053     if (gatt_client->mtu_state == MTU_AUTO_EXCHANGE_DISABLED){
3054         gatt_client->callback = callback;
3055         gatt_client->mtu_state = SEND_MTU_EXCHANGE;
3056         gatt_client_run();
3057     }
3058 }
3059 
3060 uint8_t gatt_client_request_to_write_without_response(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
3061     gatt_client_t * gatt_client;
3062     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3063     if (status != ERROR_CODE_SUCCESS){
3064         return status;
3065     }
3066     bool added = btstack_linked_list_add_tail(&gatt_client->write_without_response_requests, (btstack_linked_item_t*) callback_registration);
3067     if (added == false){
3068         return ERROR_CODE_COMMAND_DISALLOWED;
3069     } else {
3070         att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
3071         return ERROR_CODE_SUCCESS;
3072     }
3073 }
3074 
3075 uint8_t gatt_client_request_to_send_gatt_query(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
3076     gatt_client_t * gatt_client;
3077     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3078     if (status != ERROR_CODE_SUCCESS){
3079         return status;
3080     }
3081     bool added = btstack_linked_list_add_tail(&gatt_client->query_requests, (btstack_linked_item_t*) callback_registration);
3082     if (added == false){
3083         return ERROR_CODE_COMMAND_DISALLOWED;
3084     } else {
3085         gatt_client_notify_can_send_query(gatt_client);
3086         return ERROR_CODE_SUCCESS;
3087     }
3088 }
3089 
3090 uint8_t gatt_client_remove_gatt_query(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
3091     gatt_client_t * gatt_client;
3092     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3093     if (status != ERROR_CODE_SUCCESS){
3094         return status;
3095     }
3096     (void)btstack_linked_list_remove(&gatt_client->query_requests, (btstack_linked_item_t*) callback_registration);
3097     return ERROR_CODE_SUCCESS;
3098 }
3099 
3100 uint8_t gatt_client_request_can_write_without_response_event(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
3101     gatt_client_t * gatt_client;
3102     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3103     if (status != ERROR_CODE_SUCCESS){
3104         return status;
3105     }
3106     if (gatt_client->write_without_response_callback != NULL){
3107         return GATT_CLIENT_IN_WRONG_STATE;
3108     }
3109     gatt_client->write_without_response_callback = callback;
3110     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
3111     return ERROR_CODE_SUCCESS;
3112 }
3113 
3114 #ifdef ENABLE_GATT_CLIENT_SERVICE_CHANGED
3115 void gatt_client_add_service_changed_handler(btstack_packet_callback_registration_t * callback) {
3116     btstack_linked_list_add_tail(&gatt_client_service_changed_handler, (btstack_linked_item_t*) callback);
3117 }
3118 
3119 void gatt_client_remove_service_changed_handler(btstack_packet_callback_registration_t * callback){
3120     btstack_linked_list_remove(&gatt_client_service_changed_handler, (btstack_linked_item_t*) callback);
3121 }
3122 #endif
3123 
3124 #if defined(ENABLE_GATT_OVER_CLASSIC) || defined(ENABLE_GATT_OVER_EATT)
3125 
3126 #include "hci_event.h"
3127 
3128 static const hci_event_t gatt_client_connected = {
3129         GATT_EVENT_CONNECTED, 0, "11BH"
3130 };
3131 
3132 static const hci_event_t gatt_client_disconnected = {
3133         GATT_EVENT_DISCONNECTED, 0, "H"
3134 };
3135 
3136 static void
3137 gatt_client_emit_connected(btstack_packet_handler_t callback, uint8_t status, bd_addr_type_t addr_type, bd_addr_t addr,
3138                            hci_con_handle_t con_handle) {
3139     uint8_t buffer[20];
3140     uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_connected, status, addr, con_handle);
3141     (*callback)(HCI_EVENT_PACKET, 0, buffer, len);
3142 }
3143 
3144 #endif
3145 
3146 #ifdef ENABLE_GATT_OVER_CLASSIC
3147 
3148 #include "bluetooth_psm.h"
3149 
3150 // single active SDP query
3151 static gatt_client_t * gatt_client_classic_active_sdp_query;
3152 
3153 // macos protocol descriptor list requires 16 bytes
3154 static uint8_t gatt_client_classic_sdp_buffer[32];
3155 
3156 
3157 static gatt_client_t * gatt_client_get_context_for_classic_addr(bd_addr_t addr){
3158     btstack_linked_item_t *it;
3159     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
3160         gatt_client_t * gatt_client = (gatt_client_t *) it;
3161         if (memcmp(gatt_client->addr, addr, 6) == 0){
3162             return gatt_client;
3163         }
3164     }
3165     return NULL;
3166 }
3167 
3168 static gatt_client_t * gatt_client_get_context_for_l2cap_cid(uint16_t l2cap_cid){
3169     btstack_linked_item_t *it;
3170     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
3171         gatt_client_t * gatt_client = (gatt_client_t *) it;
3172         if (gatt_client->l2cap_cid == l2cap_cid){
3173             return gatt_client;
3174         }
3175     }
3176     return NULL;
3177 }
3178 
3179 static void gatt_client_classic_handle_connected(gatt_client_t * gatt_client, uint8_t status){
3180     // cache peer information
3181     bd_addr_t addr;
3182     // cppcheck-suppress uninitvar ; addr is reported as uninitialized although it's the destination of the memcpy
3183     memcpy(addr, gatt_client->addr, 6);
3184     bd_addr_type_t addr_type = gatt_client->addr_type;
3185     gatt_client->addr_type = BD_ADDR_TYPE_ACL;
3186     hci_con_handle_t con_handle = gatt_client->con_handle;
3187     btstack_packet_handler_t callback = gatt_client->callback;
3188 
3189     if (status != ERROR_CODE_SUCCESS){
3190         btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
3191         btstack_memory_gatt_client_free(gatt_client);
3192     }
3193 
3194     gatt_client_emit_connected(callback, status, addr_type, addr, con_handle);
3195 }
3196 
3197 static void gatt_client_classic_retry(btstack_timer_source_t * ts){
3198     gatt_client_t * gatt_client = gatt_client_for_timer(ts);
3199     if (gatt_client != NULL){
3200         gatt_client->state = P_W4_L2CAP_CONNECTION;
3201         att_dispatch_classic_connect(gatt_client->addr, gatt_client->l2cap_psm, &gatt_client->l2cap_cid);
3202     }
3203 }
3204 
3205 static void gatt_client_classic_handle_disconnected(gatt_client_t * gatt_client){
3206 
3207     gatt_client_report_error_if_pending(gatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
3208     gatt_client_timeout_stop(gatt_client);
3209 
3210     hci_con_handle_t con_handle = gatt_client->con_handle;
3211     btstack_packet_handler_t callback = gatt_client->callback;
3212     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
3213     btstack_memory_gatt_client_free(gatt_client);
3214 
3215     uint8_t buffer[20];
3216     uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_disconnected, con_handle);
3217     (*callback)(HCI_EVENT_PACKET, 0, buffer, len);
3218 }
3219 
3220 static void gatt_client_handle_sdp_client_query_attribute_value(gatt_client_t * connection, uint8_t *packet){
3221     des_iterator_t des_list_it;
3222     des_iterator_t prot_it;
3223 
3224     if (sdp_event_query_attribute_byte_get_attribute_length(packet) <= sizeof(gatt_client_classic_sdp_buffer)) {
3225         gatt_client_classic_sdp_buffer[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet);
3226         if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)) {
3227             switch(sdp_event_query_attribute_byte_get_attribute_id(packet)) {
3228                 case BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST:
3229                     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)) {
3230                         uint8_t       *des_element;
3231                         uint8_t       *element;
3232                         uint32_t       uuid;
3233 
3234                         if (des_iterator_get_type(&des_list_it) != DE_DES) continue;
3235 
3236                         des_element = des_iterator_get_element(&des_list_it);
3237                         des_iterator_init(&prot_it, des_element);
3238                         element = des_iterator_get_element(&prot_it);
3239 
3240                         if (de_get_element_type(element) != DE_UUID) continue;
3241 
3242                         uuid = de_get_uuid32(element);
3243                         des_iterator_next(&prot_it);
3244                         // we assume that the even if there are both roles supported, remote device uses the same psm and avdtp version for both
3245                         switch (uuid){
3246                             case BLUETOOTH_PROTOCOL_L2CAP:
3247                                 if (!des_iterator_has_more(&prot_it)) continue;
3248                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &connection->l2cap_psm);
3249                                 break;
3250                             default:
3251                                 break;
3252                         }
3253                     }
3254                     break;
3255 
3256                 default:
3257                     break;
3258             }
3259         }
3260     }
3261 }
3262 
3263 static void gatt_client_classic_sdp_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
3264     gatt_client_t * gatt_client = gatt_client_classic_active_sdp_query;
3265     btstack_assert(gatt_client != NULL);
3266     uint8_t status;
3267 
3268     // TODO: handle sdp events, get l2cap psm
3269     switch (hci_event_packet_get_type(packet)){
3270         case SDP_EVENT_QUERY_ATTRIBUTE_VALUE:
3271             gatt_client_handle_sdp_client_query_attribute_value(gatt_client, packet);
3272             // TODO:
3273             return;
3274         case SDP_EVENT_QUERY_COMPLETE:
3275             status = sdp_event_query_complete_get_status(packet);
3276             gatt_client_classic_active_sdp_query = NULL;
3277             log_info("l2cap psm: %0x, status %02x", gatt_client->l2cap_psm, status);
3278             if (status != ERROR_CODE_SUCCESS) break;
3279             if (gatt_client->l2cap_psm == 0) {
3280                 status = SDP_SERVICE_NOT_FOUND;
3281                 break;
3282             }
3283             break;
3284         default:
3285             btstack_assert(false);
3286             return;
3287     }
3288 
3289     // done
3290     if (status == ERROR_CODE_SUCCESS){
3291         gatt_client->state = P_W4_L2CAP_CONNECTION;
3292         status = att_dispatch_classic_connect(gatt_client->addr, gatt_client->l2cap_psm, &gatt_client->l2cap_cid);
3293     }
3294     if (status != ERROR_CODE_SUCCESS) {
3295         gatt_client_classic_handle_connected(gatt_client, status);
3296     }
3297 }
3298 
3299 static void gatt_client_classic_sdp_start(void * context){
3300     gatt_client_classic_active_sdp_query = (gatt_client_t *) context;
3301     gatt_client_classic_active_sdp_query->state = P_W4_SDP_QUERY;
3302     sdp_client_query_uuid16(gatt_client_classic_sdp_handler, gatt_client_classic_active_sdp_query->addr, ORG_BLUETOOTH_SERVICE_GENERIC_ATTRIBUTE);
3303 }
3304 
3305 static void gatt_client_classic_emit_connected(void * context){
3306     gatt_client_t * gatt_client = (gatt_client_t *) context;
3307     gatt_client->state = P_READY;
3308     gatt_client_emit_connected(gatt_client->callback, ERROR_CODE_SUCCESS, gatt_client->addr_type, gatt_client->addr, gatt_client->con_handle);
3309 }
3310 
3311 uint8_t gatt_client_classic_connect(btstack_packet_handler_t callback, bd_addr_t addr){
3312     gatt_client_t * gatt_client = gatt_client_get_context_for_classic_addr(addr);
3313     if (gatt_client != NULL){
3314         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
3315     }
3316     gatt_client = btstack_memory_gatt_client_get();
3317     if (gatt_client == NULL){
3318         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
3319     }
3320     // init state
3321     gatt_client->bearer_type = ATT_BEARER_UNENHANCED_CLASSIC;
3322     gatt_client->con_handle = HCI_CON_HANDLE_INVALID;
3323     memcpy(gatt_client->addr, addr, 6);
3324     gatt_client->addr_type = BD_ADDR_TYPE_ACL;
3325     gatt_client->mtu = ATT_DEFAULT_MTU;
3326     gatt_client->security_level = LEVEL_0;
3327     gatt_client->mtu_state = MTU_AUTO_EXCHANGE_DISABLED;
3328     gatt_client->callback = callback;
3329 #ifdef ENABLE_GATT_OVER_EATT
3330     gatt_client->eatt_state = GATT_CLIENT_EATT_IDLE;
3331 #endif
3332     btstack_linked_list_add(&gatt_client_connections, (btstack_linked_item_t*)gatt_client);
3333 
3334     // schedule emitted event if already connected, otherwise
3335     bool already_connected = false;
3336     hci_connection_t * hci_connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3337     if (hci_connection != NULL){
3338         if (hci_connection->att_server.l2cap_cid != 0){
3339             already_connected = true;
3340         }
3341     }
3342     gatt_client->callback_request.context = gatt_client;
3343     if (already_connected){
3344         gatt_client->con_handle = hci_connection->con_handle;
3345         gatt_client->callback_request.callback = &gatt_client_classic_emit_connected;
3346         gatt_client->state = P_W2_EMIT_CONNECTED;
3347         btstack_run_loop_execute_on_main_thread(&gatt_client->callback_request);
3348     } else {
3349         gatt_client->callback_request.callback = &gatt_client_classic_sdp_start;
3350         gatt_client->state = P_W2_SDP_QUERY;
3351         sdp_client_register_query_callback(&gatt_client->callback_request);
3352     }
3353     return ERROR_CODE_SUCCESS;
3354 }
3355 
3356 uint8_t gatt_client_classic_disconnect(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
3357     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
3358     if (gatt_client == NULL){
3359         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3360     }
3361     gatt_client->callback = callback;
3362     return l2cap_disconnect(gatt_client->l2cap_cid);
3363 }
3364 #endif
3365 
3366 #ifdef ENABLE_GATT_OVER_EATT
3367 
3368 #define MAX_NR_EATT_CHANNELS 5
3369 
3370 static void gatt_client_le_enhanced_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
3371 
3372 static uint8_t gatt_client_le_enhanced_num_eatt_clients_in_state(gatt_client_t * gatt_client, gatt_client_state_t state){
3373     uint8_t num_clients = 0;
3374     btstack_linked_list_iterator_t it;
3375     btstack_linked_list_iterator_init(&it, &gatt_client->eatt_clients);
3376     while (btstack_linked_list_iterator_has_next(&it)){
3377         gatt_client_t * eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3378         if (eatt_client->state == state){
3379             num_clients++;
3380         }
3381     }
3382     return num_clients;
3383 }
3384 
3385 static void gatt_client_eatt_finalize(gatt_client_t * gatt_client) {
3386     // free eatt clients
3387     btstack_linked_list_iterator_t it;
3388     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
3389     while (btstack_linked_list_iterator_has_next(&it)) {
3390         gatt_client_t *eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3391         btstack_linked_list_iterator_remove(&it);
3392         btstack_memory_gatt_client_free(eatt_client);
3393     }
3394 }
3395 
3396 // all channels connected
3397 static void gatt_client_le_enhanced_handle_connected(gatt_client_t * gatt_client, uint8_t status) {
3398     if (status == ERROR_CODE_SUCCESS){
3399         uint8_t num_ready = gatt_client_le_enhanced_num_eatt_clients_in_state(gatt_client, P_READY);
3400         if (num_ready > 0){
3401             gatt_client->eatt_state = GATT_CLIENT_EATT_READY;
3402             // free unused channels
3403             btstack_linked_list_iterator_t it;
3404             btstack_linked_list_iterator_init(&it, &gatt_client_connections);
3405             while (btstack_linked_list_iterator_has_next(&it)) {
3406                 gatt_client_t *eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3407                 if (eatt_client->state == P_L2CAP_CLOSED){
3408                     btstack_linked_list_iterator_remove(&it);
3409                     btstack_memory_gatt_client_free(eatt_client);
3410                 }
3411             }
3412         } else {
3413             hci_connection_t * hci_connection = hci_connection_for_handle(gatt_client->con_handle);
3414             btstack_assert(hci_connection != NULL);
3415             if (hci_connection->att_server.incoming_connection_request){
3416                 hci_connection->att_server.incoming_connection_request = false;
3417                 log_info("Collision, retry in 100ms");
3418                 gatt_client->state = P_W2_L2CAP_CONNECT;
3419                 // set timer for retry
3420                 btstack_run_loop_set_timer(&gatt_client->gc_timeout, GATT_CLIENT_COLLISION_BACKOFF_MS);
3421                 btstack_run_loop_set_timer_handler(&gatt_client->gc_timeout, gatt_client_le_enhanced_retry);
3422                 btstack_run_loop_add_timer(&gatt_client->gc_timeout);
3423                 return;
3424             } else {
3425                 gatt_client->eatt_state = GATT_CLIENT_EATT_IDLE;
3426                 status = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES;
3427             }
3428         }
3429     } else {
3430         gatt_client_eatt_finalize(gatt_client);
3431         gatt_client->eatt_state = GATT_CLIENT_EATT_IDLE;
3432     }
3433 
3434     gatt_client_emit_connected(gatt_client->callback, status, gatt_client->addr_type, gatt_client->addr, gatt_client->con_handle);
3435 }
3436 
3437 // single channel disconnected
3438 static void gatt_client_le_enhanced_handle_ecbm_disconnected(gatt_client_t * gatt_client, gatt_client_t * eatt_client) {
3439 
3440     // report error
3441     gatt_client_report_error_if_pending(eatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
3442 
3443     // free memory
3444     btstack_linked_list_remove(&gatt_client->eatt_clients, (btstack_linked_item_t *) eatt_client);
3445     btstack_memory_gatt_client_free(eatt_client);
3446 
3447     // last channel
3448     if (btstack_linked_list_empty(&gatt_client->eatt_clients)){
3449         hci_connection_t * hci_connection = hci_connection_for_handle(gatt_client->con_handle);
3450         hci_connection->att_server.eatt_outgoing_active = false;
3451 
3452         if (gatt_client->eatt_state == GATT_CLIENT_EATT_READY) {
3453             // report disconnected if last channel closed
3454             uint8_t buffer[20];
3455             uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_disconnected, gatt_client->con_handle);
3456             (*gatt_client->callback)(HCI_EVENT_PACKET, 0, buffer, len);
3457         }
3458     }
3459 }
3460 
3461 static gatt_client_t * gatt_client_le_enhanced_get_context_for_l2cap_cid(uint16_t l2cap_cid, gatt_client_t ** out_eatt_client){
3462     btstack_linked_list_iterator_t it;
3463     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
3464     while (btstack_linked_list_iterator_has_next(&it)) {
3465         gatt_client_t * gatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3466         btstack_linked_list_iterator_t it2;
3467         btstack_linked_list_iterator_init(&it2, &gatt_client->eatt_clients);
3468         while (btstack_linked_list_iterator_has_next(&it2)) {
3469             gatt_client_t * eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it2);
3470             if (eatt_client->l2cap_cid == l2cap_cid){
3471                 *out_eatt_client = eatt_client;
3472                 return gatt_client;
3473             }
3474         }
3475     }
3476     return NULL;
3477 }
3478 
3479 static void gatt_client_le_enhanced_setup_l2cap_channel(gatt_client_t * gatt_client){
3480     uint8_t num_channels = gatt_client->eatt_num_clients;
3481 
3482     // setup channels
3483     uint16_t buffer_size_per_client = gatt_client->eatt_storage_size / num_channels;
3484     uint16_t max_mtu = (buffer_size_per_client - REPORT_PREBUFFER_HEADER) / 2;
3485     uint8_t * receive_buffers[MAX_NR_EATT_CHANNELS];
3486     uint16_t  new_cids[MAX_NR_EATT_CHANNELS];
3487     memset(gatt_client->eatt_storage_buffer, 0, gatt_client->eatt_storage_size);
3488     uint8_t i;
3489     for (i=0;i<gatt_client->eatt_num_clients; i++){
3490         receive_buffers[i] = &gatt_client->eatt_storage_buffer[REPORT_PREBUFFER_HEADER];
3491         gatt_client->eatt_storage_buffer += REPORT_PREBUFFER_HEADER + max_mtu;
3492     }
3493 
3494     log_info("%u EATT clients with receive buffer size %u", gatt_client->eatt_num_clients, buffer_size_per_client);
3495 
3496     uint8_t status = l2cap_ecbm_create_channels(&gatt_client_le_enhanced_packet_handler,
3497                                                 gatt_client->con_handle,
3498                                                 gatt_client->security_level,
3499                                                 BLUETOOTH_PSM_EATT, num_channels,
3500                                                 L2CAP_LE_AUTOMATIC_CREDITS,
3501                                                 buffer_size_per_client,
3502                                                 receive_buffers,
3503                                                 new_cids);
3504 
3505     if (status == ERROR_CODE_SUCCESS){
3506         i = 0;
3507         btstack_linked_list_iterator_t it;
3508         btstack_linked_list_iterator_init(&it, &gatt_client->eatt_clients);
3509         while (btstack_linked_list_iterator_has_next(&it)) {
3510             gatt_client_t *new_eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3511 
3512             // init state with new cid and transmit buffer
3513             new_eatt_client->bearer_type = ATT_BEARER_ENHANCED_LE;
3514             new_eatt_client->con_handle = gatt_client->con_handle;
3515             new_eatt_client->mtu = 64;
3516             new_eatt_client->security_level = LEVEL_0;
3517             new_eatt_client->mtu_state = MTU_AUTO_EXCHANGE_DISABLED;
3518             new_eatt_client->state = P_W4_L2CAP_CONNECTION;
3519             new_eatt_client->l2cap_cid = new_cids[i];
3520             new_eatt_client->eatt_storage_buffer = gatt_client->eatt_storage_buffer;
3521             gatt_client->eatt_storage_buffer += max_mtu;
3522             i++;
3523         }
3524         gatt_client->eatt_state = GATT_CLIENT_EATT_L2CAP_SETUP;
3525     } else {
3526         gatt_client_le_enhanced_handle_connected(gatt_client, status);
3527     }
3528 }
3529 
3530 static void gatt_client_le_enhanced_retry(btstack_timer_source_t * ts){
3531     gatt_client_t * gatt_client = gatt_client_for_timer(ts);
3532     if (gatt_client != NULL){
3533         gatt_client->state = P_W4_L2CAP_CONNECTION;
3534         gatt_client_le_enhanced_setup_l2cap_channel(gatt_client);
3535     }
3536 }
3537 
3538 static void gatt_client_le_enhanced_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
3539     gatt_client_t *gatt_client;
3540     gatt_client_t *eatt_client;
3541     hci_con_handle_t con_handle;
3542     uint16_t l2cap_cid;
3543     uint8_t status;
3544     gatt_client_characteristic_t characteristic;
3545     gatt_client_service_t service;
3546     switch (packet_type) {
3547         case HCI_EVENT_PACKET:
3548             switch (hci_event_packet_get_type(packet)) {
3549                 case GATT_EVENT_SERVICE_QUERY_RESULT:
3550                     con_handle = gatt_event_service_query_result_get_handle(packet);
3551                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3552                     btstack_assert(gatt_client != NULL);
3553                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W4_DONE);
3554                     gatt_event_service_query_result_get_service(packet, &service);
3555                     gatt_client->gatt_service_start_group_handle = service.start_group_handle;
3556                     gatt_client->gatt_service_end_group_handle = service.end_group_handle;
3557                     break;
3558                 case GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT:
3559                     con_handle = gatt_event_characteristic_value_query_result_get_handle(packet);
3560                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3561                     btstack_assert(gatt_client != NULL);
3562                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_DONE);
3563                     if (gatt_event_characteristic_value_query_result_get_value_length(packet) >= 1) {
3564                         gatt_client->gatt_server_supported_features = gatt_event_characteristic_value_query_result_get_value(packet)[0];
3565                     }
3566                     break;
3567                 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
3568                     con_handle = gatt_event_characteristic_query_result_get_handle(packet);
3569                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3570                     btstack_assert(gatt_client != NULL);
3571                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_DONE);
3572                     gatt_event_characteristic_query_result_get_characteristic(packet, &characteristic);
3573                     gatt_client->gatt_client_supported_features_handle = characteristic.value_handle;
3574                     break;
3575                 case GATT_EVENT_QUERY_COMPLETE:
3576                     con_handle = gatt_event_query_complete_get_handle(packet);
3577                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3578                     btstack_assert(gatt_client != NULL);
3579                     switch (gatt_client->eatt_state){
3580                         case GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W4_DONE:
3581                             if (gatt_client->gatt_service_start_group_handle == 0){
3582                                 gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
3583                             } else {
3584                                 gatt_client->eatt_state = GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W2_SEND;
3585                             }
3586                             break;
3587                         case GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_DONE:
3588                             if ((gatt_client->gatt_server_supported_features & 1) == 0) {
3589                                 gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
3590                             } else {
3591                                 gatt_client->eatt_state = GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W2_SEND;
3592                             }
3593                             break;
3594                         case GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_DONE:
3595                             if (gatt_client->gatt_client_supported_features_handle == 0){
3596                                 gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
3597                             } else {
3598                                 gatt_client->eatt_state = GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W2_SEND;
3599                             }
3600                             break;
3601                         case GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W4_DONE:
3602                             gatt_client_le_enhanced_setup_l2cap_channel(gatt_client);
3603                             break;
3604                         default:
3605                             break;
3606                     }
3607                     break;
3608                 case L2CAP_EVENT_ECBM_CHANNEL_OPENED:
3609                     l2cap_cid = l2cap_event_ecbm_channel_opened_get_local_cid(packet);
3610                     gatt_client = gatt_client_le_enhanced_get_context_for_l2cap_cid(l2cap_cid, &eatt_client);
3611 
3612                     btstack_assert(gatt_client != NULL);
3613                     btstack_assert(eatt_client != NULL);
3614                     btstack_assert(eatt_client->state == P_W4_L2CAP_CONNECTION);
3615 
3616                     status = l2cap_event_channel_opened_get_status(packet);
3617                     if (status == ERROR_CODE_SUCCESS){
3618                         eatt_client->state = P_READY;
3619                         eatt_client->mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
3620                     } else {
3621                         eatt_client->state = P_L2CAP_CLOSED;
3622                     }
3623                     // connected if opened event for all channels received
3624                     if (gatt_client_le_enhanced_num_eatt_clients_in_state(gatt_client, P_W4_L2CAP_CONNECTION) == 0){
3625                         gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_SUCCESS);
3626                     }
3627                     break;
3628                 case L2CAP_EVENT_CHANNEL_CLOSED:
3629                     l2cap_cid = l2cap_event_channel_closed_get_local_cid(packet);
3630                     gatt_client = gatt_client_le_enhanced_get_context_for_l2cap_cid(l2cap_cid, &eatt_client);
3631                     btstack_assert(gatt_client != NULL);
3632                     btstack_assert(eatt_client != NULL);
3633                     gatt_client_le_enhanced_handle_ecbm_disconnected(gatt_client, eatt_client);
3634                     break;
3635                 default:
3636                     break;
3637             }
3638             break;
3639         case L2CAP_DATA_PACKET:
3640             gatt_client = gatt_client_le_enhanced_get_context_for_l2cap_cid(channel, &eatt_client);
3641             btstack_assert(gatt_client != NULL);
3642             btstack_assert(eatt_client != NULL);
3643             gatt_client_handle_att_response(eatt_client, packet, size);
3644             gatt_client_run();
3645             break;
3646         default:
3647             break;
3648     }
3649 }
3650 
3651 static bool gatt_client_le_enhanced_handle_can_send_query(gatt_client_t * gatt_client){
3652     uint8_t status = ERROR_CODE_SUCCESS;
3653     uint8_t gatt_client_supported_features = 0x06; // eatt + multiple value notifications
3654     switch (gatt_client->eatt_state){
3655         case GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W2_SEND:
3656             gatt_client->gatt_service_start_group_handle = 0;
3657             gatt_client->eatt_state = GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W4_DONE;
3658             status = gatt_client_discover_primary_services_by_uuid16(&gatt_client_le_enhanced_packet_handler,
3659                                                                      gatt_client->con_handle,
3660                                                                      ORG_BLUETOOTH_SERVICE_GENERIC_ATTRIBUTE);
3661             break;
3662         case GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W2_SEND:
3663             gatt_client->gatt_server_supported_features = 0;
3664             gatt_client->eatt_state = GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_DONE;
3665             status = gatt_client_read_value_of_characteristics_by_uuid16(&gatt_client_le_enhanced_packet_handler,
3666                                                                          gatt_client->con_handle,
3667                                                                          gatt_client->gatt_service_start_group_handle,
3668                                                                          gatt_client->gatt_service_end_group_handle,
3669                                                                          ORG_BLUETOOTH_CHARACTERISTIC_SERVER_SUPPORTED_FEATURES);
3670             return true;
3671         case GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W2_SEND:
3672             gatt_client->gatt_client_supported_features_handle = 0;
3673             gatt_client->eatt_state = GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_DONE;
3674             status = gatt_client_discover_characteristics_for_handle_range_by_uuid16(&gatt_client_le_enhanced_packet_handler,
3675                                                                                      gatt_client->con_handle,
3676                                                                                      gatt_client->gatt_service_start_group_handle,
3677                                                                                      gatt_client->gatt_service_end_group_handle,
3678                                                                                      ORG_BLUETOOTH_CHARACTERISTIC_CLIENT_SUPPORTED_FEATURES);
3679             return true;
3680         case GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W2_SEND:
3681             gatt_client->eatt_state = GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W4_DONE;
3682             status = gatt_client_write_value_of_characteristic(&gatt_client_le_enhanced_packet_handler, gatt_client->con_handle,
3683                                                                gatt_client->gatt_client_supported_features_handle, 1,
3684                                                                &gatt_client_supported_features);
3685             return true;
3686         default:
3687             break;
3688     }
3689     btstack_assert(status == ERROR_CODE_SUCCESS);
3690     UNUSED(status);
3691     return false;
3692 }
3693 
3694 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) {
3695     gatt_client_t * gatt_client;
3696     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3697     if (status != ERROR_CODE_SUCCESS){
3698         return status;
3699     }
3700 
3701     if (gatt_client->eatt_state != GATT_CLIENT_EATT_IDLE){
3702         return ERROR_CODE_COMMAND_DISALLOWED;
3703     }
3704 
3705     // need one buffer for sending and one for receiving. Receiving includes pre-buffer for reports
3706     uint16_t buffer_size_per_client = storage_size / num_channels;
3707     uint16_t max_mtu = (buffer_size_per_client - REPORT_PREBUFFER_HEADER) / 2;
3708     if (max_mtu < 64) {
3709         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
3710     }
3711 
3712     if ((num_channels == 0) || (num_channels > MAX_NR_EATT_CHANNELS)){
3713         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
3714     }
3715 
3716     // create max num_channel eatt clients
3717     uint8_t i;
3718     btstack_linked_list_t eatt_clients = NULL;
3719     for (i=0;i<num_channels;i++) {
3720         gatt_client_t * new_gatt_client = btstack_memory_gatt_client_get();
3721         if (new_gatt_client == NULL) {
3722             break;
3723         }
3724         btstack_linked_list_add(&eatt_clients, (btstack_linked_item_t*)new_gatt_client);
3725     }
3726 
3727     if (i != num_channels){
3728         while (true){
3729             gatt_client = (gatt_client_t *) btstack_linked_list_pop(&eatt_clients);
3730             if (gatt_client == NULL) {
3731                 break;
3732             }
3733             btstack_memory_gatt_client_free(gatt_client);
3734         }
3735         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
3736     }
3737 
3738     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
3739     hci_connection->att_server.eatt_outgoing_active = true;
3740 
3741     gatt_client->callback = callback;
3742     gatt_client->eatt_num_clients   = num_channels;
3743     gatt_client->eatt_storage_buffer = storage_buffer;
3744     gatt_client->eatt_storage_size   = storage_size;
3745     gatt_client->eatt_clients = eatt_clients;
3746     gatt_client->eatt_state = GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W2_SEND;
3747     gatt_client_notify_can_send_query(gatt_client);
3748 
3749     return ERROR_CODE_SUCCESS;
3750 }
3751 
3752 #endif
3753 
3754 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
3755 void gatt_client_att_packet_handler_fuzz(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
3756     gatt_client_att_packet_handler(packet_type, handle, packet, size);
3757 }
3758 
3759 uint8_t gatt_client_get_client(hci_con_handle_t con_handle, gatt_client_t ** out_gatt_client){
3760     uint8_t status = gatt_client_provide_context_for_handle(con_handle, out_gatt_client);
3761     return status;
3762 }
3763 #endif
3764