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