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