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