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