xref: /btstack/src/ble/gatt_client.c (revision 348725bedd01d1e7ec8db9a37db133db1d0f3f2c)
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_btstack_event(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                     if (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                     }
2158                     break;
2159                 case L2CAP_EVENT_CHANNEL_CLOSED:
2160                     gatt_client = gatt_client_get_context_for_l2cap_cid(l2cap_event_channel_closed_get_local_cid(packet));
2161                     if (gatt_client != NULL){
2162                         // discard gatt client object
2163                         gatt_client_classic_handle_disconnected(gatt_client);
2164                     }
2165                     break;
2166 #endif
2167                 case L2CAP_EVENT_CAN_SEND_NOW:
2168                     gatt_client_run();
2169                     break;
2170                     // att_server has negotiated the mtu for this connection, cache if context exists
2171                 case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
2172                     if (size < 6u) break;
2173                     gatt_client = gatt_client_get_context_for_handle(handle);
2174                     if (gatt_client != NULL) {
2175                         gatt_client->mtu = little_endian_read_16(packet, 4);
2176                     }
2177                     break;
2178                 default:
2179                     break;
2180             }
2181             break;
2182 
2183         case ATT_DATA_PACKET:
2184             // special cases: notifications & indications motivate creating context
2185             switch (packet[0]) {
2186                 case ATT_HANDLE_VALUE_NOTIFICATION:
2187                 case ATT_HANDLE_VALUE_INDICATION:
2188                     gatt_client_provide_context_for_handle(handle, &gatt_client);
2189                     break;
2190                 default:
2191                     gatt_client = gatt_client_get_context_for_handle(handle);
2192                     break;
2193             }
2194 
2195             if (gatt_client != NULL) {
2196                 gatt_client_handle_att_response(gatt_client, packet, size);
2197                 gatt_client_run();
2198             }
2199             break;
2200 
2201 #ifdef ENABLE_GATT_OVER_CLASSIC
2202         case L2CAP_DATA_PACKET:
2203             gatt_client = gatt_client_get_context_for_l2cap_cid(handle);
2204             if (gatt_client != NULL){
2205                 gatt_client_handle_att_response(gatt_client, packet, size);
2206                 gatt_client_run();
2207             }
2208             break;
2209 #endif
2210 
2211         default:
2212             break;
2213     }
2214 }
2215 
2216 #ifdef ENABLE_LE_SIGNED_WRITE
2217 static void att_signed_write_handle_cmac_result(uint8_t hash[8]){
2218     btstack_linked_list_iterator_t it;
2219     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
2220     while (btstack_linked_list_iterator_has_next(&it)){
2221         gatt_client_t * gatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
2222         if (gatt_client->state == P_W4_CMAC_RESULT){
2223             // store result
2224             (void)memcpy(gatt_client->cmac, hash, 8);
2225             // reverse_64(hash, gatt_client->cmac);
2226             gatt_client->state = P_W2_SEND_SIGNED_WRITE;
2227             gatt_client_run();
2228             return;
2229         }
2230     }
2231 }
2232 
2233 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){
2234     gatt_client_t * gatt_client;
2235     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2236     if (status != ERROR_CODE_SUCCESS){
2237         return status;
2238     }
2239     if (is_ready(gatt_client) == 0){
2240         return GATT_CLIENT_IN_WRONG_STATE;
2241     }
2242 
2243     gatt_client->callback = callback;
2244     gatt_client->attribute_handle = value_handle;
2245     gatt_client->attribute_length = message_len;
2246     gatt_client->attribute_value = message;
2247     gatt_client->state = P_W4_IDENTITY_RESOLVING;
2248     gatt_client_run();
2249     return ERROR_CODE_SUCCESS;
2250 }
2251 #endif
2252 
2253 uint8_t gatt_client_discover_primary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2254     gatt_client_t * gatt_client;
2255     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2256     if (status != ERROR_CODE_SUCCESS){
2257         return status;
2258     }
2259 
2260     gatt_client->callback = callback;
2261     gatt_client->start_group_handle = 0x0001;
2262     gatt_client->end_group_handle   = 0xffff;
2263     gatt_client->state = P_W2_SEND_SERVICE_QUERY;
2264     gatt_client->uuid16 = GATT_PRIMARY_SERVICE_UUID;
2265     gatt_client_run();
2266     return ERROR_CODE_SUCCESS;
2267 }
2268 
2269 uint8_t gatt_client_discover_secondary_services(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2270     gatt_client_t * gatt_client;
2271     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2272     if (status != ERROR_CODE_SUCCESS){
2273         return status;
2274     }
2275 
2276     gatt_client->callback = callback;
2277     gatt_client->start_group_handle = 0x0001;
2278     gatt_client->end_group_handle   = 0xffff;
2279     gatt_client->state = P_W2_SEND_SERVICE_QUERY;
2280     gatt_client->uuid16 = GATT_SECONDARY_SERVICE_UUID;
2281     gatt_client_run();
2282     return ERROR_CODE_SUCCESS;
2283 }
2284 
2285 uint8_t gatt_client_discover_primary_services_by_uuid16(btstack_packet_handler_t callback, hci_con_handle_t con_handle, uint16_t uuid16){
2286     gatt_client_t * gatt_client;
2287     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2288     if (status != ERROR_CODE_SUCCESS){
2289         return status;
2290     }
2291 
2292     gatt_client->callback = callback;
2293     gatt_client->start_group_handle = 0x0001;
2294     gatt_client->end_group_handle   = 0xffff;
2295     gatt_client->state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
2296     gatt_client->uuid16 = uuid16;
2297     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), gatt_client->uuid16);
2298     gatt_client_run();
2299     return ERROR_CODE_SUCCESS;
2300 }
2301 
2302 uint8_t gatt_client_discover_primary_services_by_uuid128(btstack_packet_handler_t callback, hci_con_handle_t con_handle, const uint8_t * uuid128){
2303     gatt_client_t * gatt_client;
2304     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2305     if (status != ERROR_CODE_SUCCESS){
2306         return status;
2307     }
2308 
2309     gatt_client->callback = callback;
2310     gatt_client->start_group_handle = 0x0001;
2311     gatt_client->end_group_handle   = 0xffff;
2312     gatt_client->uuid16 = 0;
2313     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2314     gatt_client->state = P_W2_SEND_SERVICE_WITH_UUID_QUERY;
2315     gatt_client_run();
2316     return ERROR_CODE_SUCCESS;
2317 }
2318 
2319 uint8_t gatt_client_discover_characteristics_for_service(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_service_t * service){
2320     gatt_client_t * gatt_client;
2321     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2322     if (status != ERROR_CODE_SUCCESS){
2323         return status;
2324     }
2325 
2326     gatt_client->callback = callback;
2327     gatt_client->start_group_handle = service->start_group_handle;
2328     gatt_client->end_group_handle   = service->end_group_handle;
2329     gatt_client->filter_with_uuid = false;
2330     gatt_client->characteristic_start_handle = 0;
2331     gatt_client->state = P_W2_SEND_ALL_CHARACTERISTICS_OF_SERVICE_QUERY;
2332     gatt_client_run();
2333     return ERROR_CODE_SUCCESS;
2334 }
2335 
2336 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){
2337     gatt_client_t * gatt_client;
2338     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2339     if (status != ERROR_CODE_SUCCESS){
2340         return status;
2341     }
2342 
2343     gatt_client->callback = callback;
2344     gatt_client->start_group_handle = service->start_group_handle;
2345     gatt_client->end_group_handle   = service->end_group_handle;
2346     gatt_client->state = P_W2_SEND_INCLUDED_SERVICE_QUERY;
2347 
2348     gatt_client_run();
2349     return ERROR_CODE_SUCCESS;
2350 }
2351 
2352 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){
2353     gatt_client_t * gatt_client;
2354     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2355     if (status != ERROR_CODE_SUCCESS){
2356         return status;
2357     }
2358 
2359     gatt_client->callback = callback;
2360     gatt_client->start_group_handle = start_handle;
2361     gatt_client->end_group_handle   = end_handle;
2362     gatt_client->filter_with_uuid = true;
2363     gatt_client->uuid16 = uuid16;
2364     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), uuid16);
2365     gatt_client->characteristic_start_handle = 0;
2366     gatt_client->state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
2367     gatt_client_run();
2368     return ERROR_CODE_SUCCESS;
2369 }
2370 
2371 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){
2372     gatt_client_t * gatt_client;
2373     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2374     if (status != ERROR_CODE_SUCCESS){
2375         return status;
2376     }
2377 
2378     gatt_client->callback = callback;
2379     gatt_client->start_group_handle = start_handle;
2380     gatt_client->end_group_handle   = end_handle;
2381     gatt_client->filter_with_uuid = true;
2382     gatt_client->uuid16 = 0;
2383     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2384     gatt_client->characteristic_start_handle = 0;
2385     gatt_client->state = P_W2_SEND_CHARACTERISTIC_WITH_UUID_QUERY;
2386     gatt_client_run();
2387     return ERROR_CODE_SUCCESS;
2388 }
2389 
2390 
2391 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){
2392     return gatt_client_discover_characteristics_for_handle_range_by_uuid16(callback, con_handle, service->start_group_handle, service->end_group_handle, uuid16);
2393 }
2394 
2395 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){
2396     return gatt_client_discover_characteristics_for_handle_range_by_uuid128(callback, con_handle, service->start_group_handle, service->end_group_handle, uuid128);
2397 }
2398 
2399 uint8_t gatt_client_discover_characteristic_descriptors(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2400     gatt_client_t * gatt_client;
2401     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2402     if (status != ERROR_CODE_SUCCESS){
2403         return status;
2404     }
2405 
2406     // check if there is space for characteristics descriptors
2407     if (characteristic->end_handle > characteristic->value_handle){
2408         gatt_client->callback = callback;
2409         gatt_client->start_group_handle = characteristic->value_handle + 1u;
2410         gatt_client->end_group_handle   = characteristic->end_handle;
2411         gatt_client->state = P_W2_SEND_ALL_CHARACTERISTIC_DESCRIPTORS_QUERY;
2412         gatt_client_run();
2413     } else {
2414         // schedule gatt complete event on next run loop iteration otherwise
2415         gatt_client->state = P_W2_EMIT_QUERY_COMPLETE_EVENT;
2416         gatt_client_deferred_event_emit.callback = gatt_client_emit_events;
2417         btstack_run_loop_execute_on_main_thread(&gatt_client_deferred_event_emit);
2418     }
2419     return ERROR_CODE_SUCCESS;
2420 }
2421 
2422 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){
2423     gatt_client_t * gatt_client;
2424     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2425     if (status != ERROR_CODE_SUCCESS){
2426         return status;
2427     }
2428 
2429     gatt_client->callback = callback;
2430     gatt_client->attribute_handle = value_handle;
2431     gatt_client->attribute_offset = 0;
2432     gatt_client->state = P_W2_SEND_READ_CHARACTERISTIC_VALUE_QUERY;
2433     gatt_client_run();
2434     return ERROR_CODE_SUCCESS;
2435 }
2436 
2437 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){
2438     gatt_client_t * gatt_client;
2439     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2440     if (status != ERROR_CODE_SUCCESS){
2441         return status;
2442     }
2443 
2444     gatt_client->callback = callback;
2445     gatt_client->start_group_handle = start_handle;
2446     gatt_client->end_group_handle = end_handle;
2447     gatt_client->query_start_handle = start_handle;
2448     gatt_client->query_end_handle = end_handle;
2449     gatt_client->uuid16 = uuid16;
2450     uuid_add_bluetooth_prefix((uint8_t*) &(gatt_client->uuid128), uuid16);
2451     gatt_client->state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2452     gatt_client_run();
2453     return ERROR_CODE_SUCCESS;
2454 }
2455 
2456 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){
2457     gatt_client_t * gatt_client;
2458     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2459     if (status != ERROR_CODE_SUCCESS){
2460         return status;
2461     }
2462 
2463     gatt_client->callback = callback;
2464     gatt_client->start_group_handle = start_handle;
2465     gatt_client->end_group_handle = end_handle;
2466     gatt_client->query_start_handle = start_handle;
2467     gatt_client->query_end_handle = end_handle;
2468     gatt_client->uuid16 = 0;
2469     (void)memcpy(gatt_client->uuid128, uuid128, 16);
2470     gatt_client->state = P_W2_SEND_READ_BY_TYPE_REQUEST;
2471     gatt_client_run();
2472     return ERROR_CODE_SUCCESS;
2473 }
2474 
2475 
2476 uint8_t gatt_client_read_value_of_characteristic(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_t * characteristic){
2477     return gatt_client_read_value_of_characteristic_using_value_handle(callback, con_handle, characteristic->value_handle);
2478 }
2479 
2480 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){
2481     gatt_client_t * gatt_client;
2482     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2483     if (status != ERROR_CODE_SUCCESS){
2484         return status;
2485     }
2486 
2487     gatt_client->callback = callback;
2488     gatt_client->attribute_handle = value_handle;
2489     gatt_client->attribute_offset = offset;
2490     gatt_client->state = P_W2_SEND_READ_BLOB_QUERY;
2491     gatt_client_run();
2492     return ERROR_CODE_SUCCESS;
2493 }
2494 
2495 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){
2496     return gatt_client_read_long_value_of_characteristic_using_value_handle_with_offset(callback, con_handle, value_handle, 0);
2497 }
2498 
2499 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){
2500     return gatt_client_read_long_value_of_characteristic_using_value_handle(callback, con_handle, characteristic->value_handle);
2501 }
2502 
2503 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){
2504     gatt_client_t * gatt_client;
2505     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2506     if (status != ERROR_CODE_SUCCESS){
2507         return status;
2508     }
2509 
2510 #ifdef ENABLE_GATT_OVER_EATT
2511     if (state == P_W2_SEND_READ_MULTIPLE_VARIABLE_REQUEST){
2512         if (gatt_client->bearer_type != ATT_BEARER_ENHANCED_LE){
2513             return ERROR_CODE_COMMAND_DISALLOWED;
2514         }
2515     }
2516 #endif
2517 
2518     gatt_client->callback = callback;
2519     gatt_client->read_multiple_handle_count = num_value_handles;
2520     gatt_client->read_multiple_handles = value_handles;
2521     gatt_client->state = state;
2522     gatt_client_run();
2523     return ERROR_CODE_SUCCESS;
2524 }
2525 
2526 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){
2527     return gatt_client_read_multiple_characteristic_values_with_state(callback, con_handle, num_value_handles, value_handles, P_W2_SEND_READ_MULTIPLE_REQUEST);
2528 }
2529 
2530 #ifdef ENABLE_GATT_OVER_EATT
2531 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){
2532     return gatt_client_read_multiple_characteristic_values_with_state(callback, con_handle, num_value_handles, value_handles, P_W2_SEND_READ_MULTIPLE_VARIABLE_REQUEST);
2533 }
2534 #endif
2535 
2536 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){
2537     gatt_client_t * gatt_client;
2538     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2539     if (status != ERROR_CODE_SUCCESS){
2540         return status;
2541     }
2542 
2543     if (value_length > (gatt_client->mtu - 3u)) return GATT_CLIENT_VALUE_TOO_LONG;
2544     if (!att_dispatch_client_can_send_now(gatt_client->con_handle)) return GATT_CLIENT_BUSY;
2545 
2546     return att_write_request(gatt_client, ATT_WRITE_COMMAND, value_handle, value_length, value);
2547 }
2548 
2549 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){
2550     gatt_client_t * gatt_client;
2551     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2552     if (status != ERROR_CODE_SUCCESS){
2553         return status;
2554     }
2555 
2556     gatt_client->callback = callback;
2557     gatt_client->attribute_handle = value_handle;
2558     gatt_client->attribute_length = value_length;
2559     gatt_client->attribute_value = value;
2560     gatt_client->state = P_W2_SEND_WRITE_CHARACTERISTIC_VALUE;
2561     gatt_client_run();
2562     return ERROR_CODE_SUCCESS;
2563 }
2564 
2565 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){
2566     gatt_client_t * gatt_client;
2567     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2568     if (status != ERROR_CODE_SUCCESS){
2569         return status;
2570     }
2571 
2572     gatt_client->callback = callback;
2573     gatt_client->attribute_handle = value_handle;
2574     gatt_client->attribute_length = value_length;
2575     gatt_client->attribute_offset = offset;
2576     gatt_client->attribute_value = value;
2577     gatt_client->state = P_W2_PREPARE_WRITE;
2578     gatt_client_run();
2579     return ERROR_CODE_SUCCESS;
2580 }
2581 
2582 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){
2583     return gatt_client_write_long_value_of_characteristic_with_offset(callback, con_handle, value_handle, 0, value_length, value);
2584 }
2585 
2586 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){
2587     gatt_client_t * gatt_client;
2588     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2589     if (status != ERROR_CODE_SUCCESS){
2590         return status;
2591     }
2592 
2593     gatt_client->callback = callback;
2594     gatt_client->attribute_handle = value_handle;
2595     gatt_client->attribute_length = value_length;
2596     gatt_client->attribute_offset = 0;
2597     gatt_client->attribute_value = value;
2598     gatt_client->state = P_W2_PREPARE_RELIABLE_WRITE;
2599     gatt_client_run();
2600     return ERROR_CODE_SUCCESS;
2601 }
2602 
2603 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){
2604     gatt_client_t * gatt_client;
2605     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2606     if (status != ERROR_CODE_SUCCESS){
2607         return status;
2608     }
2609 
2610     if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION) &&
2611         ((characteristic->properties & ATT_PROPERTY_NOTIFY) == 0u)) {
2612         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED");
2613         return GATT_CLIENT_CHARACTERISTIC_NOTIFICATION_NOT_SUPPORTED;
2614     } else if ( (configuration & GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_INDICATION) &&
2615                ((characteristic->properties & ATT_PROPERTY_INDICATE) == 0u)){
2616         log_info("gatt_client_write_client_characteristic_configuration: GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED");
2617         return GATT_CLIENT_CHARACTERISTIC_INDICATION_NOT_SUPPORTED;
2618     }
2619 
2620     gatt_client->callback = callback;
2621     gatt_client->start_group_handle = characteristic->value_handle;
2622     gatt_client->end_group_handle = characteristic->end_handle;
2623     little_endian_store_16(gatt_client->client_characteristic_configuration_value, 0, configuration);
2624 
2625 #ifdef ENABLE_GATT_FIND_INFORMATION_FOR_CCC_DISCOVERY
2626     gatt_client->gatt_client_state = P_W2_SEND_FIND_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2627 #else
2628     gatt_client->state = P_W2_SEND_READ_CLIENT_CHARACTERISTIC_CONFIGURATION_QUERY;
2629 #endif
2630     gatt_client_run();
2631     return ERROR_CODE_SUCCESS;
2632 }
2633 
2634 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){
2635     gatt_client_t * gatt_client;
2636     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2637     if (status != ERROR_CODE_SUCCESS){
2638         return status;
2639     }
2640 
2641     gatt_client->callback = callback;
2642     gatt_client->attribute_handle = descriptor_handle;
2643 
2644     gatt_client->state = P_W2_SEND_READ_CHARACTERISTIC_DESCRIPTOR_QUERY;
2645     gatt_client_run();
2646     return ERROR_CODE_SUCCESS;
2647 }
2648 
2649 uint8_t gatt_client_read_characteristic_descriptor(btstack_packet_handler_t callback, hci_con_handle_t con_handle, gatt_client_characteristic_descriptor_t * descriptor){
2650     return gatt_client_read_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
2651 }
2652 
2653 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){
2654     gatt_client_t * gatt_client;
2655     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2656     if (status != ERROR_CODE_SUCCESS){
2657         return status;
2658     }
2659 
2660     gatt_client->callback = callback;
2661     gatt_client->attribute_handle = descriptor_handle;
2662     gatt_client->attribute_offset = offset;
2663     gatt_client->state = P_W2_SEND_READ_BLOB_CHARACTERISTIC_DESCRIPTOR_QUERY;
2664     gatt_client_run();
2665     return ERROR_CODE_SUCCESS;
2666 }
2667 
2668 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){
2669     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0);
2670 }
2671 
2672 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){
2673     return gatt_client_read_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle);
2674 }
2675 
2676 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){
2677     gatt_client_t * gatt_client;
2678     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2679     if (status != ERROR_CODE_SUCCESS){
2680         return status;
2681     }
2682 
2683     gatt_client->callback = callback;
2684     gatt_client->attribute_handle = descriptor_handle;
2685     gatt_client->attribute_length = value_length;
2686     gatt_client->attribute_offset = 0;
2687     gatt_client->attribute_value = value;
2688     gatt_client->state = P_W2_SEND_WRITE_CHARACTERISTIC_DESCRIPTOR;
2689     gatt_client_run();
2690     return ERROR_CODE_SUCCESS;
2691 }
2692 
2693 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){
2694     return gatt_client_write_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, value_length, value);
2695 }
2696 
2697 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){
2698     gatt_client_t * gatt_client;
2699     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2700     if (status != ERROR_CODE_SUCCESS){
2701         return status;
2702     }
2703 
2704     gatt_client->callback = callback;
2705     gatt_client->attribute_handle = descriptor_handle;
2706     gatt_client->attribute_length = value_length;
2707     gatt_client->attribute_offset = offset;
2708     gatt_client->attribute_value = value;
2709     gatt_client->state = P_W2_PREPARE_WRITE_CHARACTERISTIC_DESCRIPTOR;
2710     gatt_client_run();
2711     return ERROR_CODE_SUCCESS;
2712 }
2713 
2714 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){
2715     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle_with_offset(callback, con_handle, descriptor_handle, 0, value_length, value);
2716 }
2717 
2718 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){
2719     return gatt_client_write_long_characteristic_descriptor_using_descriptor_handle(callback, con_handle, descriptor->handle, value_length, value);
2720 }
2721 
2722 /**
2723  * @brief -> gatt complete event
2724  */
2725 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){
2726     gatt_client_t * gatt_client;
2727     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2728     if (status != ERROR_CODE_SUCCESS){
2729         return status;
2730     }
2731 
2732     gatt_client->callback = callback;
2733     gatt_client->attribute_handle = attribute_handle;
2734     gatt_client->attribute_length = value_length;
2735     gatt_client->attribute_offset = offset;
2736     gatt_client->attribute_value = value;
2737     gatt_client->state = P_W2_PREPARE_WRITE_SINGLE;
2738     gatt_client_run();
2739     return ERROR_CODE_SUCCESS;
2740 }
2741 
2742 /**
2743  * @brief -> gatt complete event
2744  */
2745 uint8_t gatt_client_execute_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2746     gatt_client_t * gatt_client;
2747     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2748     if (status != ERROR_CODE_SUCCESS){
2749         return status;
2750     }
2751 
2752     gatt_client->callback = callback;
2753     gatt_client->state = P_W2_EXECUTE_PREPARED_WRITE;
2754     gatt_client_run();
2755     return ERROR_CODE_SUCCESS;
2756 }
2757 
2758 /**
2759  * @brief -> gatt complete event
2760  */
2761 uint8_t gatt_client_cancel_write(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2762     gatt_client_t * gatt_client;
2763     uint8_t status = gatt_client_provide_context_for_request(con_handle, &gatt_client);
2764     if (status != ERROR_CODE_SUCCESS){
2765         return status;
2766     }
2767 
2768     gatt_client->callback = callback;
2769     gatt_client->state = P_W2_CANCEL_PREPARED_WRITE;
2770     gatt_client_run();
2771     return ERROR_CODE_SUCCESS;
2772 }
2773 
2774 void gatt_client_deserialize_service(const uint8_t *packet, int offset, gatt_client_service_t * service){
2775     service->start_group_handle = little_endian_read_16(packet, offset);
2776     service->end_group_handle = little_endian_read_16(packet, offset + 2);
2777     reverse_128(&packet[offset + 4], service->uuid128);
2778     if (uuid_has_bluetooth_prefix(service->uuid128)){
2779         service->uuid16 = big_endian_read_32(service->uuid128, 0);
2780     } else {
2781         service->uuid16 = 0;
2782     }
2783 }
2784 
2785 void gatt_client_deserialize_characteristic(const uint8_t * packet, int offset, gatt_client_characteristic_t * characteristic){
2786     characteristic->start_handle = little_endian_read_16(packet, offset);
2787     characteristic->value_handle = little_endian_read_16(packet, offset + 2);
2788     characteristic->end_handle = little_endian_read_16(packet, offset + 4);
2789     characteristic->properties = little_endian_read_16(packet, offset + 6);
2790     reverse_128(&packet[offset+8], characteristic->uuid128);
2791     if (uuid_has_bluetooth_prefix(characteristic->uuid128)){
2792         characteristic->uuid16 = big_endian_read_32(characteristic->uuid128, 0);
2793     } else {
2794         characteristic->uuid16 = 0;
2795     }
2796 }
2797 
2798 void gatt_client_deserialize_characteristic_descriptor(const uint8_t * packet, int offset, gatt_client_characteristic_descriptor_t * descriptor){
2799     descriptor->handle = little_endian_read_16(packet, offset);
2800     reverse_128(&packet[offset+2], descriptor->uuid128);
2801     if (uuid_has_bluetooth_prefix(descriptor->uuid128)){
2802         descriptor->uuid16 = big_endian_read_32(descriptor->uuid128, 0);
2803     } else {
2804         descriptor->uuid16 = 0;
2805     }
2806 }
2807 
2808 void gatt_client_send_mtu_negotiation(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2809     gatt_client_t * gatt_client;
2810     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2811     if (status != ERROR_CODE_SUCCESS){
2812         return;
2813     }
2814     if (gatt_client->mtu_state == MTU_AUTO_EXCHANGE_DISABLED){
2815         gatt_client->callback = callback;
2816         gatt_client->mtu_state = SEND_MTU_EXCHANGE;
2817         gatt_client_run();
2818     }
2819 }
2820 
2821 uint8_t gatt_client_request_to_write_without_response(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
2822     gatt_client_t * gatt_client;
2823     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2824     if (status != ERROR_CODE_SUCCESS){
2825         return status;
2826     }
2827     bool added = btstack_linked_list_add_tail(&gatt_client->write_without_response_requests, (btstack_linked_item_t*) callback_registration);
2828     if (added == false){
2829         return ERROR_CODE_COMMAND_DISALLOWED;
2830     } else {
2831         att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
2832         return ERROR_CODE_SUCCESS;
2833     }
2834 }
2835 
2836 uint8_t gatt_client_request_to_send_gatt_query(btstack_context_callback_registration_t * callback_registration, hci_con_handle_t con_handle){
2837     gatt_client_t * gatt_client;
2838     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2839     if (status != ERROR_CODE_SUCCESS){
2840         return status;
2841     }
2842     bool added = btstack_linked_list_add_tail(&gatt_client->query_requests, (btstack_linked_item_t*) callback_registration);
2843     if (added == false){
2844         return ERROR_CODE_COMMAND_DISALLOWED;
2845     } else {
2846         gatt_client_notify_can_send_query(gatt_client);
2847         return ERROR_CODE_SUCCESS;
2848     }
2849 }
2850 
2851 uint8_t gatt_client_request_can_write_without_response_event(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
2852     gatt_client_t * gatt_client;
2853     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
2854     if (status != ERROR_CODE_SUCCESS){
2855         return status;
2856     }
2857     if (gatt_client->write_without_response_callback != NULL){
2858         return GATT_CLIENT_IN_WRONG_STATE;
2859     }
2860     gatt_client->write_without_response_callback = callback;
2861     att_dispatch_client_request_can_send_now_event(gatt_client->con_handle);
2862     return ERROR_CODE_SUCCESS;
2863 }
2864 
2865 
2866 #if defined(ENABLE_GATT_OVER_CLASSIC) || defined(ENABLE_GATT_OVER_EATT)
2867 
2868 #include "hci_event.h"
2869 
2870 static const hci_event_t gatt_client_connected = {
2871         GATT_EVENT_CONNECTED, 0, "1BH"
2872 };
2873 
2874 static const hci_event_t gatt_client_disconnected = {
2875         GATT_EVENT_DISCONNECTED, 0, "H"
2876 };
2877 
2878 static void gatt_client_emit_connected(btstack_packet_handler_t callback, uint8_t status, bd_addr_t addr,
2879                                        hci_con_handle_t con_handle) {
2880     uint8_t buffer[20];
2881     uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_connected, status, addr, con_handle);
2882     (*callback)(HCI_EVENT_PACKET, 0, buffer, len);
2883 }
2884 
2885 #endif
2886 
2887 #ifdef ENABLE_GATT_OVER_CLASSIC
2888 
2889 #include "bluetooth_psm.h"
2890 
2891 // single active SDP query
2892 static gatt_client_t * gatt_client_classic_active_sdp_query;
2893 
2894 // macos protocol descriptor list requires 16 bytes
2895 static uint8_t gatt_client_classic_sdp_buffer[32];
2896 
2897 
2898 static gatt_client_t * gatt_client_get_context_for_classic_addr(bd_addr_t addr){
2899     btstack_linked_item_t *it;
2900     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
2901         gatt_client_t * gatt_client = (gatt_client_t *) it;
2902         if (memcmp(gatt_client->addr, addr, 6) == 0){
2903             return gatt_client;
2904         }
2905     }
2906     return NULL;
2907 }
2908 
2909 static gatt_client_t * gatt_client_get_context_for_l2cap_cid(uint16_t l2cap_cid){
2910     btstack_linked_item_t *it;
2911     for (it = (btstack_linked_item_t *) gatt_client_connections; it != NULL; it = it->next){
2912         gatt_client_t * gatt_client = (gatt_client_t *) it;
2913         if (gatt_client->l2cap_cid == l2cap_cid){
2914             return gatt_client;
2915         }
2916     }
2917     return NULL;
2918 }
2919 
2920 static void gatt_client_classic_handle_connected(gatt_client_t * gatt_client, uint8_t status){
2921     bd_addr_t addr;
2922     // cppcheck-suppress uninitvar ; addr is reported as uninitialized although it's the destination of the memcpy
2923     memcpy(addr, gatt_client->addr, 6);
2924     hci_con_handle_t con_handle = gatt_client->con_handle;
2925     btstack_packet_handler_t callback = gatt_client->callback;
2926     if (status != ERROR_CODE_SUCCESS){
2927         btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
2928         btstack_memory_gatt_client_free(gatt_client);
2929     }
2930     gatt_client_emit_connected(callback, status, addr, con_handle);
2931 }
2932 
2933 static void gatt_client_classic_retry(btstack_timer_source_t * ts){
2934     gatt_client_t * gatt_client = gatt_client_for_timer(ts);
2935     if (gatt_client != NULL){
2936         gatt_client->state = P_W4_L2CAP_CONNECTION;
2937         att_dispatch_classic_connect(gatt_client->addr, gatt_client->l2cap_psm, &gatt_client->l2cap_cid);
2938     }
2939 }
2940 
2941 static void gatt_client_classic_handle_disconnected(gatt_client_t * gatt_client){
2942 
2943     gatt_client_report_error_if_pending(gatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
2944     gatt_client_timeout_stop(gatt_client);
2945 
2946     hci_con_handle_t con_handle = gatt_client->con_handle;
2947     btstack_packet_handler_t callback = gatt_client->callback;
2948     btstack_linked_list_remove(&gatt_client_connections, (btstack_linked_item_t *) gatt_client);
2949     btstack_memory_gatt_client_free(gatt_client);
2950 
2951     uint8_t buffer[20];
2952     uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_disconnected, con_handle);
2953     (*callback)(HCI_EVENT_PACKET, 0, buffer, len);
2954 }
2955 
2956 static void gatt_client_handle_sdp_client_query_attribute_value(gatt_client_t * connection, uint8_t *packet){
2957     des_iterator_t des_list_it;
2958     des_iterator_t prot_it;
2959 
2960     if (sdp_event_query_attribute_byte_get_attribute_length(packet) <= sizeof(gatt_client_classic_sdp_buffer)) {
2961         gatt_client_classic_sdp_buffer[sdp_event_query_attribute_byte_get_data_offset(packet)] = sdp_event_query_attribute_byte_get_data(packet);
2962         if ((uint16_t)(sdp_event_query_attribute_byte_get_data_offset(packet)+1) == sdp_event_query_attribute_byte_get_attribute_length(packet)) {
2963             switch(sdp_event_query_attribute_byte_get_attribute_id(packet)) {
2964                 case BLUETOOTH_ATTRIBUTE_PROTOCOL_DESCRIPTOR_LIST:
2965                     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)) {
2966                         uint8_t       *des_element;
2967                         uint8_t       *element;
2968                         uint32_t       uuid;
2969 
2970                         if (des_iterator_get_type(&des_list_it) != DE_DES) continue;
2971 
2972                         des_element = des_iterator_get_element(&des_list_it);
2973                         des_iterator_init(&prot_it, des_element);
2974                         element = des_iterator_get_element(&prot_it);
2975 
2976                         if (de_get_element_type(element) != DE_UUID) continue;
2977 
2978                         uuid = de_get_uuid32(element);
2979                         des_iterator_next(&prot_it);
2980                         // we assume that the even if there are both roles supported, remote device uses the same psm and avdtp version for both
2981                         switch (uuid){
2982                             case BLUETOOTH_PROTOCOL_L2CAP:
2983                                 if (!des_iterator_has_more(&prot_it)) continue;
2984                                 de_element_get_uint16(des_iterator_get_element(&prot_it), &connection->l2cap_psm);
2985                                 break;
2986                             default:
2987                                 break;
2988                         }
2989                     }
2990                     break;
2991 
2992                 default:
2993                     break;
2994             }
2995         }
2996     }
2997 }
2998 
2999 static void gatt_client_classic_sdp_handler(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
3000     gatt_client_t * gatt_client = gatt_client_classic_active_sdp_query;
3001     btstack_assert(gatt_client != NULL);
3002     uint8_t status;
3003 
3004     // TODO: handle sdp events, get l2cap psm
3005     switch (hci_event_packet_get_type(packet)){
3006         case SDP_EVENT_QUERY_ATTRIBUTE_VALUE:
3007             gatt_client_handle_sdp_client_query_attribute_value(gatt_client, packet);
3008             // TODO:
3009             return;
3010         case SDP_EVENT_QUERY_COMPLETE:
3011             status = sdp_event_query_complete_get_status(packet);
3012             gatt_client_classic_active_sdp_query = NULL;
3013             log_info("l2cap psm: %0x, status %02x", gatt_client->l2cap_psm, status);
3014             if (status != ERROR_CODE_SUCCESS) break;
3015             if (gatt_client->l2cap_psm == 0) {
3016                 status = SDP_SERVICE_NOT_FOUND;
3017                 break;
3018             }
3019             break;
3020         default:
3021             btstack_assert(false);
3022             return;
3023     }
3024 
3025     // done
3026     if (status == ERROR_CODE_SUCCESS){
3027         gatt_client->state = P_W4_L2CAP_CONNECTION;
3028         status = att_dispatch_classic_connect(gatt_client->addr, gatt_client->l2cap_psm, &gatt_client->l2cap_cid);
3029     }
3030     if (status != ERROR_CODE_SUCCESS) {
3031         gatt_client_classic_handle_connected(gatt_client, status);
3032     }
3033 }
3034 
3035 static void gatt_client_classic_sdp_start(void * context){
3036     gatt_client_classic_active_sdp_query = (gatt_client_t *) context;
3037     gatt_client_classic_active_sdp_query->state = P_W4_SDP_QUERY;
3038     sdp_client_query_uuid16(gatt_client_classic_sdp_handler, gatt_client_classic_active_sdp_query->addr, ORG_BLUETOOTH_SERVICE_GENERIC_ATTRIBUTE);
3039 }
3040 
3041 static void gatt_client_classic_emit_connected(void * context){
3042     gatt_client_t * gatt_client = (gatt_client_t *) context;
3043     gatt_client->state = P_READY;
3044     hci_connection_t * hci_connection = hci_connection_for_handle(gatt_client->con_handle);
3045     btstack_assert(hci_connection != NULL);
3046     gatt_client_emit_connected(gatt_client->callback, ERROR_CODE_SUCCESS, hci_connection->address, gatt_client->con_handle);
3047 }
3048 
3049 uint8_t gatt_client_classic_connect(btstack_packet_handler_t callback, bd_addr_t addr){
3050     gatt_client_t * gatt_client = gatt_client_get_context_for_classic_addr(addr);
3051     if (gatt_client != NULL){
3052         return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
3053     }
3054     gatt_client = btstack_memory_gatt_client_get();
3055     if (gatt_client == NULL){
3056         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
3057     }
3058     // init state
3059     gatt_client->bearer_type = ATT_BEARER_UNENHANCED_CLASSIC;
3060     gatt_client->con_handle = HCI_CON_HANDLE_INVALID;
3061     memcpy(gatt_client->addr, addr, 6);
3062     gatt_client->mtu = ATT_DEFAULT_MTU;
3063     gatt_client->security_level = LEVEL_0;
3064     gatt_client->mtu_state = MTU_AUTO_EXCHANGE_DISABLED;
3065     gatt_client->callback = callback;
3066 #ifdef ENABLE_GATT_OVER_EATT
3067     gatt_client->eatt_state = GATT_CLIENT_EATT_IDLE;
3068 #endif
3069     btstack_linked_list_add(&gatt_client_connections, (btstack_linked_item_t*)gatt_client);
3070 
3071     // schedule emitted event if already connected, otherwise
3072     bool already_connected = false;
3073     hci_connection_t * hci_connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3074     if (hci_connection != NULL){
3075         if (hci_connection->att_server.l2cap_cid != 0){
3076             already_connected = true;
3077         }
3078     }
3079     gatt_client->callback_request.context = gatt_client;
3080     if (already_connected){
3081         gatt_client->con_handle = hci_connection->con_handle;
3082         gatt_client->callback_request.callback = &gatt_client_classic_emit_connected;
3083         gatt_client->state = P_W2_EMIT_CONNECTED;
3084         btstack_run_loop_execute_on_main_thread(&gatt_client->callback_request);
3085     } else {
3086         gatt_client->callback_request.callback = &gatt_client_classic_sdp_start;
3087         gatt_client->state = P_W2_SDP_QUERY;
3088         sdp_client_register_query_callback(&gatt_client->callback_request);
3089     }
3090     return ERROR_CODE_SUCCESS;
3091 }
3092 
3093 uint8_t gatt_client_classic_disconnect(btstack_packet_handler_t callback, hci_con_handle_t con_handle){
3094     gatt_client_t * gatt_client = gatt_client_get_context_for_handle(con_handle);
3095     if (gatt_client == NULL){
3096         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3097     }
3098     gatt_client->callback = callback;
3099     return l2cap_disconnect(gatt_client->l2cap_cid);
3100 }
3101 #endif
3102 
3103 #ifdef ENABLE_GATT_OVER_EATT
3104 
3105 #define MAX_NR_EATT_CHANNELS 5
3106 
3107 static void gatt_client_le_enhanced_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
3108 
3109 static uint8_t gatt_client_le_enhanced_num_eatt_clients_in_state(gatt_client_t * gatt_client, gatt_client_state_t state){
3110     uint8_t num_clients = 0;
3111     btstack_linked_list_iterator_t it;
3112     btstack_linked_list_iterator_init(&it, &gatt_client->eatt_clients);
3113     while (btstack_linked_list_iterator_has_next(&it)){
3114         gatt_client_t * eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3115         if (eatt_client->state == state){
3116             num_clients++;
3117         }
3118     }
3119     return num_clients;
3120 }
3121 
3122 static void gatt_client_eatt_finalize(gatt_client_t * gatt_client) {
3123     // free eatt clients
3124     btstack_linked_list_iterator_t it;
3125     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
3126     while (btstack_linked_list_iterator_has_next(&it)) {
3127         gatt_client_t *eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3128         btstack_linked_list_iterator_remove(&it);
3129         btstack_memory_gatt_client_free(eatt_client);
3130     }
3131 }
3132 
3133 // all channels connected
3134 static void gatt_client_le_enhanced_handle_connected(gatt_client_t * gatt_client, uint8_t status) {
3135     if (status == ERROR_CODE_SUCCESS){
3136         uint8_t num_ready = gatt_client_le_enhanced_num_eatt_clients_in_state(gatt_client, P_READY);
3137         if (num_ready > 0){
3138             gatt_client->eatt_state = GATT_CLIENT_EATT_READY;
3139             // free unused channels
3140             btstack_linked_list_iterator_t it;
3141             btstack_linked_list_iterator_init(&it, &gatt_client_connections);
3142             while (btstack_linked_list_iterator_has_next(&it)) {
3143                 gatt_client_t *eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3144                 if (eatt_client->state == P_L2CAP_CLOSED){
3145                     btstack_linked_list_iterator_remove(&it);
3146                     btstack_memory_gatt_client_free(eatt_client);
3147                 }
3148             }
3149         } else {
3150             hci_connection_t * hci_connection = hci_connection_for_handle(gatt_client->con_handle);
3151             btstack_assert(hci_connection != NULL);
3152             if (hci_connection->att_server.incoming_connection_request){
3153                 hci_connection->att_server.incoming_connection_request = false;
3154                 log_info("Collision, retry in 100ms");
3155                 gatt_client->state = P_W2_L2CAP_CONNECT;
3156                 // set timer for retry
3157                 btstack_run_loop_set_timer(&gatt_client->gc_timeout, GATT_CLIENT_COLLISION_BACKOFF_MS);
3158                 btstack_run_loop_set_timer_handler(&gatt_client->gc_timeout, gatt_client_le_enhanced_retry);
3159                 btstack_run_loop_add_timer(&gatt_client->gc_timeout);
3160                 return;
3161             } else {
3162                 gatt_client->eatt_state = GATT_CLIENT_EATT_IDLE;
3163                 status = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES;
3164             }
3165         }
3166     } else {
3167         gatt_client_eatt_finalize(gatt_client);
3168         gatt_client->eatt_state = GATT_CLIENT_EATT_IDLE;
3169     }
3170 
3171     gatt_client_emit_connected(gatt_client->callback, status,  gatt_client->addr, gatt_client->con_handle);
3172 }
3173 
3174 // single channel disconnected
3175 static void gatt_client_le_enhanced_handle_ecbm_disconnected(gatt_client_t * gatt_client, gatt_client_t * eatt_client) {
3176 
3177     // report error
3178     gatt_client_report_error_if_pending(eatt_client, ATT_ERROR_HCI_DISCONNECT_RECEIVED);
3179 
3180     // free memory
3181     btstack_linked_list_remove(&gatt_client->eatt_clients, (btstack_linked_item_t *) eatt_client);
3182     btstack_memory_gatt_client_free(eatt_client);
3183 
3184     // last channel
3185     if (btstack_linked_list_empty(&gatt_client->eatt_clients)){
3186         hci_connection_t * hci_connection = hci_connection_for_handle(gatt_client->con_handle);
3187         hci_connection->att_server.eatt_outgoing_active = false;
3188 
3189         if (gatt_client->eatt_state == GATT_CLIENT_EATT_READY) {
3190             // report disconnected if last channel closed
3191             uint8_t buffer[20];
3192             uint16_t len = hci_event_create_from_template_and_arguments(buffer, sizeof(buffer), &gatt_client_disconnected, gatt_client->con_handle);
3193             (*gatt_client->callback)(HCI_EVENT_PACKET, 0, buffer, len);
3194         }
3195     }
3196 }
3197 
3198 static gatt_client_t * gatt_client_le_enhanced_get_context_for_l2cap_cid(uint16_t l2cap_cid, gatt_client_t ** out_eatt_client){
3199     btstack_linked_list_iterator_t it;
3200     btstack_linked_list_iterator_init(&it, &gatt_client_connections);
3201     while (btstack_linked_list_iterator_has_next(&it)) {
3202         gatt_client_t * gatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3203         btstack_linked_list_iterator_t it2;
3204         btstack_linked_list_iterator_init(&it2, &gatt_client->eatt_clients);
3205         while (btstack_linked_list_iterator_has_next(&it2)) {
3206             gatt_client_t * eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it2);
3207             if (eatt_client->l2cap_cid == l2cap_cid){
3208                 *out_eatt_client = eatt_client;
3209                 return gatt_client;
3210             }
3211         }
3212     }
3213     return NULL;
3214 }
3215 
3216 static void gatt_client_le_enhanced_setup_l2cap_channel(gatt_client_t * gatt_client){
3217     uint8_t num_channels = gatt_client->eatt_num_clients;
3218 
3219     // setup channels
3220     uint16_t buffer_size_per_client = gatt_client->eatt_storage_size / num_channels;
3221     uint16_t max_mtu = (buffer_size_per_client - REPORT_PREBUFFER_HEADER) / 2;
3222     uint8_t * receive_buffers[MAX_NR_EATT_CHANNELS];
3223     uint16_t  new_cids[MAX_NR_EATT_CHANNELS];
3224     memset(gatt_client->eatt_storage_buffer, 0, gatt_client->eatt_storage_size);
3225     uint8_t i;
3226     for (i=0;i<gatt_client->eatt_num_clients; i++){
3227         receive_buffers[i] = &gatt_client->eatt_storage_buffer[REPORT_PREBUFFER_HEADER];
3228         gatt_client->eatt_storage_buffer += REPORT_PREBUFFER_HEADER + max_mtu;
3229     }
3230 
3231     log_info("%u EATT clients with receive buffer size %u", gatt_client->eatt_num_clients, buffer_size_per_client);
3232 
3233     uint8_t status = l2cap_ecbm_create_channels(&gatt_client_le_enhanced_packet_handler,
3234                                                 gatt_client->con_handle,
3235                                                 gatt_client->security_level,
3236                                                 BLUETOOTH_PSM_EATT, num_channels,
3237                                                 L2CAP_LE_AUTOMATIC_CREDITS,
3238                                                 buffer_size_per_client,
3239                                                 receive_buffers,
3240                                                 new_cids);
3241 
3242     if (status == ERROR_CODE_SUCCESS){
3243         i = 0;
3244         btstack_linked_list_iterator_t it;
3245         btstack_linked_list_iterator_init(&it, &gatt_client->eatt_clients);
3246         while (btstack_linked_list_iterator_has_next(&it)) {
3247             gatt_client_t *new_eatt_client = (gatt_client_t *) btstack_linked_list_iterator_next(&it);
3248 
3249             // init state with new cid and transmit buffer
3250             new_eatt_client->bearer_type = ATT_BEARER_ENHANCED_LE;
3251             new_eatt_client->con_handle = gatt_client->con_handle;
3252             new_eatt_client->mtu = 64;
3253             new_eatt_client->security_level = LEVEL_0;
3254             new_eatt_client->mtu_state = MTU_AUTO_EXCHANGE_DISABLED;
3255             new_eatt_client->state = P_W4_L2CAP_CONNECTION;
3256             new_eatt_client->l2cap_cid = new_cids[i];
3257             new_eatt_client->eatt_storage_buffer = gatt_client->eatt_storage_buffer;
3258             gatt_client->eatt_storage_buffer += max_mtu;
3259             i++;
3260         }
3261         gatt_client->eatt_state = GATT_CLIENT_EATT_L2CAP_SETUP;
3262     } else {
3263         gatt_client_le_enhanced_handle_connected(gatt_client, status);
3264     }
3265 }
3266 
3267 static void gatt_client_le_enhanced_retry(btstack_timer_source_t * ts){
3268     gatt_client_t * gatt_client = gatt_client_for_timer(ts);
3269     if (gatt_client != NULL){
3270         gatt_client->state = P_W4_L2CAP_CONNECTION;
3271         gatt_client_le_enhanced_setup_l2cap_channel(gatt_client);
3272     }
3273 }
3274 
3275 static void gatt_client_le_enhanced_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
3276     gatt_client_t *gatt_client;
3277     gatt_client_t *eatt_client;
3278     hci_con_handle_t con_handle;
3279     uint16_t l2cap_cid;
3280     uint8_t status;
3281     gatt_client_characteristic_t characteristic;
3282     gatt_client_service_t service;
3283     btstack_linked_list_iterator_t it;
3284     uint8_t num_pending_channels;
3285     switch (packet_type) {
3286         case HCI_EVENT_PACKET:
3287             switch (hci_event_packet_get_type(packet)) {
3288                 case GATT_EVENT_SERVICE_QUERY_RESULT:
3289                     con_handle = gatt_event_service_query_result_get_handle(packet);
3290                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3291                     btstack_assert(gatt_client != NULL);
3292                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W4_DONE);
3293                     gatt_event_service_query_result_get_service(packet, &service);
3294                     gatt_client->gatt_service_start_group_handle = service.start_group_handle;
3295                     gatt_client->gatt_service_end_group_handle = service.end_group_handle;
3296                     break;
3297                 case GATT_EVENT_CHARACTERISTIC_VALUE_QUERY_RESULT:
3298                     con_handle = gatt_event_characteristic_value_query_result_get_handle(packet);
3299                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3300                     btstack_assert(gatt_client != NULL);
3301                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_DONE);
3302                     if (gatt_event_characteristic_value_query_result_get_value_length(packet) >= 1) {
3303                         gatt_client->gatt_server_supported_features = gatt_event_characteristic_value_query_result_get_value(packet)[0];
3304                     }
3305                     break;
3306                 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
3307                     con_handle = gatt_event_characteristic_query_result_get_handle(packet);
3308                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3309                     btstack_assert(gatt_client != NULL);
3310                     btstack_assert(gatt_client->eatt_state == GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_DONE);
3311                     gatt_event_characteristic_query_result_get_characteristic(packet, &characteristic);
3312                     gatt_client->gatt_client_supported_features_handle = characteristic.value_handle;
3313                     break;
3314                 case GATT_EVENT_QUERY_COMPLETE:
3315                     con_handle = gatt_event_query_complete_get_handle(packet);
3316                     gatt_client = gatt_client_get_context_for_handle(con_handle);
3317                     btstack_assert(gatt_client != NULL);
3318                     switch (gatt_client->eatt_state){
3319                         case GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W4_DONE:
3320                             if (gatt_client->gatt_service_start_group_handle == 0){
3321                                 gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
3322                             } else {
3323                                 gatt_client->eatt_state = GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W2_SEND;
3324                             }
3325                             break;
3326                         case GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_DONE:
3327                             if ((gatt_client->gatt_server_supported_features & 1) == 0) {
3328                                 gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
3329                             } else {
3330                                 gatt_client->eatt_state = GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W2_SEND;
3331                             }
3332                             break;
3333                         case GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_DONE:
3334                             if (gatt_client->gatt_client_supported_features_handle == 0){
3335                                 gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE);
3336                             } else {
3337                                 gatt_client->eatt_state = GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W2_SEND;
3338                             }
3339                             break;
3340                         case GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W4_DONE:
3341                             gatt_client_le_enhanced_setup_l2cap_channel(gatt_client);
3342                             break;
3343                         default:
3344                             break;
3345                     }
3346                     break;
3347                 case L2CAP_EVENT_ECBM_CHANNEL_OPENED:
3348                     l2cap_cid = l2cap_event_ecbm_channel_opened_get_local_cid(packet);
3349                     gatt_client = gatt_client_le_enhanced_get_context_for_l2cap_cid(l2cap_cid, &eatt_client);
3350 
3351                     btstack_assert(gatt_client != NULL);
3352                     btstack_assert(eatt_client != NULL);
3353                     btstack_assert(eatt_client->state == P_W4_L2CAP_CONNECTION);
3354 
3355                     status = l2cap_event_channel_opened_get_status(packet);
3356                     if (status == ERROR_CODE_SUCCESS){
3357                         eatt_client->state = P_READY;
3358                         eatt_client->mtu = l2cap_event_channel_opened_get_remote_mtu(packet);
3359                     } else {
3360                         eatt_client->state = P_L2CAP_CLOSED;
3361                     }
3362                     // connected if opened event for all channels received
3363                     if (gatt_client_le_enhanced_num_eatt_clients_in_state(gatt_client, P_W4_L2CAP_CONNECTION) == 0){
3364                         gatt_client_le_enhanced_handle_connected(gatt_client, ERROR_CODE_SUCCESS);
3365                     }
3366                     break;
3367                 case L2CAP_EVENT_CHANNEL_CLOSED:
3368                     l2cap_cid = l2cap_event_channel_closed_get_local_cid(packet);
3369                     gatt_client = gatt_client_le_enhanced_get_context_for_l2cap_cid(l2cap_cid, &eatt_client);
3370                     btstack_assert(gatt_client != NULL);
3371                     btstack_assert(eatt_client != NULL);
3372                     gatt_client_le_enhanced_handle_ecbm_disconnected(gatt_client, eatt_client);
3373                     break;
3374                 default:
3375                     break;
3376             }
3377             break;
3378         case L2CAP_DATA_PACKET:
3379             gatt_client = gatt_client_le_enhanced_get_context_for_l2cap_cid(channel, &eatt_client);
3380             btstack_assert(gatt_client != NULL);
3381             btstack_assert(eatt_client != NULL);
3382             gatt_client_handle_att_response(eatt_client, packet, size);
3383             gatt_client_run();
3384             break;
3385         default:
3386             break;
3387     }
3388 }
3389 
3390 static bool gatt_client_le_enhanced_handle_can_send_query(gatt_client_t * gatt_client){
3391     uint8_t status = ERROR_CODE_SUCCESS;
3392     uint8_t gatt_client_supported_features = 0x06; // eatt + multiple value notifications
3393     switch (gatt_client->eatt_state){
3394         case GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W2_SEND:
3395             gatt_client->gatt_service_start_group_handle = 0;
3396             gatt_client->eatt_state = GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W4_DONE;
3397             status = gatt_client_discover_primary_services_by_uuid16(&gatt_client_le_enhanced_packet_handler,
3398                                                                      gatt_client->con_handle,
3399                                                                      ORG_BLUETOOTH_SERVICE_GENERIC_ATTRIBUTE);
3400             break;
3401         case GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W2_SEND:
3402             gatt_client->gatt_server_supported_features = 0;
3403             gatt_client->eatt_state = GATT_CLIENT_EATT_READ_SERVER_SUPPORTED_FEATURES_W4_DONE;
3404             status = gatt_client_read_value_of_characteristics_by_uuid16(&gatt_client_le_enhanced_packet_handler,
3405                                                                          gatt_client->con_handle,
3406                                                                          gatt_client->gatt_service_start_group_handle,
3407                                                                          gatt_client->gatt_service_end_group_handle,
3408                                                                          ORG_BLUETOOTH_CHARACTERISTIC_SERVER_SUPPORTED_FEATURES);
3409             return true;
3410         case GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W2_SEND:
3411             gatt_client->gatt_client_supported_features_handle = 0;
3412             gatt_client->eatt_state = GATT_CLIENT_EATT_FIND_CLIENT_SUPPORTED_FEATURES_W4_DONE;
3413             status = gatt_client_discover_characteristics_for_handle_range_by_uuid16(&gatt_client_le_enhanced_packet_handler,
3414                                                                                      gatt_client->con_handle,
3415                                                                                      gatt_client->gatt_service_start_group_handle,
3416                                                                                      gatt_client->gatt_service_end_group_handle,
3417                                                                                      ORG_BLUETOOTH_CHARACTERISTIC_CLIENT_SUPPORTED_FEATURES);
3418             return true;
3419         case GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W2_SEND:
3420             gatt_client->eatt_state = GATT_CLIENT_EATT_WRITE_ClIENT_SUPPORTED_FEATURES_W4_DONE;
3421             status = gatt_client_write_value_of_characteristic(&gatt_client_le_enhanced_packet_handler, gatt_client->con_handle,
3422                                                                gatt_client->gatt_client_supported_features_handle, 1,
3423                                                                &gatt_client_supported_features);
3424             return true;
3425         default:
3426             break;
3427     }
3428     btstack_assert(status == ERROR_CODE_SUCCESS);
3429     UNUSED(status);
3430     return false;
3431 }
3432 
3433 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) {
3434     gatt_client_t * gatt_client;
3435     uint8_t status = gatt_client_provide_context_for_handle(con_handle, &gatt_client);
3436     if (status != ERROR_CODE_SUCCESS){
3437         return status;
3438     }
3439 
3440     if (gatt_client->eatt_state != GATT_CLIENT_EATT_IDLE){
3441         return ERROR_CODE_COMMAND_DISALLOWED;
3442     }
3443 
3444     // need one buffer for sending and one for receiving. Receiving includes pre-buffer for reports
3445     uint16_t buffer_size_per_client = storage_size / num_channels;
3446     uint16_t max_mtu = (buffer_size_per_client - REPORT_PREBUFFER_HEADER) / 2;
3447     if (max_mtu < 64) {
3448         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
3449     }
3450 
3451     if ((num_channels == 0) || (num_channels > MAX_NR_EATT_CHANNELS)){
3452         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
3453     }
3454 
3455     // create max num_channel eatt clients
3456     uint8_t i;
3457     btstack_linked_list_t eatt_clients = NULL;
3458     for (i=0;i<num_channels;i++) {
3459         gatt_client_t * new_gatt_client = btstack_memory_gatt_client_get();
3460         if (new_gatt_client == NULL) {
3461             break;
3462         }
3463         btstack_linked_list_add(&eatt_clients, (btstack_linked_item_t*)new_gatt_client);
3464     }
3465 
3466     if (i != num_channels){
3467         while (true){
3468             gatt_client = (gatt_client_t *) btstack_linked_list_pop(&eatt_clients);
3469             if (gatt_client == NULL) {
3470                 break;
3471             }
3472             btstack_memory_gatt_client_free(gatt_client);
3473         }
3474         return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
3475     }
3476 
3477     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
3478     hci_connection->att_server.eatt_outgoing_active = true;
3479 
3480     gatt_client->callback = callback;
3481     gatt_client->eatt_num_clients   = num_channels;
3482     gatt_client->eatt_storage_buffer = storage_buffer;
3483     gatt_client->eatt_storage_size   = storage_size;
3484     gatt_client->eatt_clients = eatt_clients;
3485     gatt_client->eatt_state = GATT_CLIENT_EATT_DISCOVER_GATT_SERVICE_W2_SEND;
3486     gatt_client_notify_can_send_query(gatt_client);
3487 
3488     return ERROR_CODE_SUCCESS;
3489 }
3490 
3491 #endif
3492 
3493 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
3494 void gatt_client_att_packet_handler_fuzz(uint8_t packet_type, uint16_t handle, uint8_t *packet, uint16_t size){
3495     gatt_client_att_packet_handler(packet_type, handle, packet, size);
3496 }
3497 
3498 uint8_t gatt_client_get_client(hci_con_handle_t con_handle, gatt_client_t ** out_gatt_client){
3499     uint8_t status = gatt_client_provide_context_for_handle(con_handle, out_gatt_client);
3500     return status;
3501 }
3502 #endif
3503