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