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