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