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