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